From ac6191b514c0e54b468623bf868134e1ce809df5 Mon Sep 17 00:00:00 2001 From: bdemsky Date: Tue, 19 Aug 2008 09:57:12 +0000 Subject: [PATCH] Change tabbing for everything.... make file now has options to standardize tabbing --- Robust/src/Analysis/CallGraph/CallGraph.java | 416 +- .../src/Analysis/FlatIRGraph/FlatIRGraph.java | 186 +- .../Locality/GenerateConversions.java | 392 +- .../Analysis/Locality/LocalityAnalysis.java | 1424 ++--- .../Analysis/Locality/LocalityBinding.java | 322 +- .../src/Analysis/Locality/TempNodePair.java | 82 +- .../OwnershipAnalysis/AllocationSite.java | 130 +- .../Analysis/OwnershipAnalysis/Canonical.java | 16 +- .../OwnershipAnalysis/ChangeTuple.java | 66 +- .../OwnershipAnalysis/ChangeTupleSet.java | 114 +- .../OwnershipAnalysis/HeapRegionNode.java | 274 +- .../Analysis/OwnershipAnalysis/LabelNode.java | 52 +- .../OwnershipAnalysis/OwnershipAnalysis.java | 1312 ++-- .../OwnershipAnalysis/OwnershipGraph.java | 3220 +++++----- .../OwnershipAnalysis/OwnershipNode.java | 74 +- .../OwnershipAnalysis/ReachabilitySet.java | 374 +- .../OwnershipAnalysis/ReferenceEdge.java | 236 +- .../OwnershipAnalysis/SubstitutionTuple.java | 66 +- .../OwnershipAnalysis/TokenTuple.java | 130 +- .../OwnershipAnalysis/TokenTupleSet.java | 266 +- .../Analysis/Prefetch/IndexDescriptor.java | 142 +- Robust/src/Analysis/Prefetch/LoopExit.java | 134 +- Robust/src/Analysis/Prefetch/PairMap.java | 106 +- .../Analysis/Prefetch/PrefetchAnalysis.java | 1884 +++--- .../src/Analysis/Prefetch/PrefetchPair.java | 236 +- Robust/src/Analysis/Scheduling/ClassNode.java | 268 +- .../Analysis/Scheduling/CombinationUtil.java | 1010 ++-- .../Analysis/Scheduling/CoreSimulator.java | 310 +- .../Analysis/Scheduling/FIFORSchedule.java | 74 +- .../src/Analysis/Scheduling/ObjectInfo.java | 42 +- .../Analysis/Scheduling/ObjectSimulator.java | 110 +- .../Analysis/Scheduling/RuntimeSchedule.java | 22 +- Robust/src/Analysis/Scheduling/Schedule.java | 254 +- .../Analysis/Scheduling/ScheduleAnalysis.java | 1947 +++--- .../src/Analysis/Scheduling/ScheduleEdge.java | 416 +- .../src/Analysis/Scheduling/ScheduleNode.java | 691 +-- .../Scheduling/ScheduleSimulator.java | 840 +-- .../Analysis/Scheduling/SchedulingUtil.java | 948 +-- .../Analysis/Scheduling/TaskSimulator.java | 482 +- .../Scheduling/TransTaskSimulator.java | 74 +- .../TaskStateAnalysis/Allocations.java | 37 +- .../Analysis/TaskStateAnalysis/EGEdge.java | 24 +- .../TaskStateAnalysis/EGTaskNode.java | 172 +- .../TaskStateAnalysis/ExecutionGraph.java | 240 +- .../src/Analysis/TaskStateAnalysis/FEdge.java | 314 +- .../TaskStateAnalysis/FlagComparator.java | 36 +- .../Analysis/TaskStateAnalysis/FlagInfo.java | 70 +- .../Analysis/TaskStateAnalysis/FlagState.java | 858 +-- .../TaskStateAnalysis/FlagTagState.java | 30 +- .../TaskStateAnalysis/GarbageAnalysis.java | 124 +- .../TaskStateAnalysis/ObjWrapper.java | 28 +- .../OptionalTaskDescriptor.java | 84 +- .../Analysis/TaskStateAnalysis/Predicate.java | 44 +- .../TaskStateAnalysis/SafetyAnalysis.java | 1021 ++-- .../src/Analysis/TaskStateAnalysis/TEdge.java | 36 +- .../TaskStateAnalysis/TagAnalysis.java | 384 +- .../TaskStateAnalysis/TagBinding.java | 92 +- .../Analysis/TaskStateAnalysis/TagEdge.java | 46 +- .../Analysis/TaskStateAnalysis/TagState.java | 180 +- .../TaskStateAnalysis/TagWrapper.java | 38 +- .../TaskStateAnalysis/TaskAnalysis.java | 766 +-- .../TaskStateAnalysis/TaskBinding.java | 208 +- .../Analysis/TaskStateAnalysis/TaskEdges.java | 45 +- .../Analysis/TaskStateAnalysis/TaskGraph.java | 408 +- .../Analysis/TaskStateAnalysis/TaskIndex.java | 68 +- .../Analysis/TaskStateAnalysis/TaskNode.java | 124 +- .../TaskStateAnalysis/TaskNodeNamer.java | 19 +- .../Analysis/TaskStateAnalysis/TaskQueue.java | 64 +- .../TaskStateAnalysis/TaskQueueIterator.java | 266 +- .../TaskStateAnalysis/TaskTagAnalysis.java | 1160 ++-- Robust/src/ClassLibrary/Barrier.java | 82 +- .../src/ClassLibrary/BufferedInputStream.java | 26 +- .../ClassLibrary/BufferedOutputStream.java | 26 +- Robust/src/ClassLibrary/BufferedWriter.java | 32 +- Robust/src/ClassLibrary/Character.java | 26 +- Robust/src/ClassLibrary/Date.java | 5 +- Robust/src/ClassLibrary/File.java | 22 +- Robust/src/ClassLibrary/FileInputStream.java | 54 +- Robust/src/ClassLibrary/FileOutputStream.java | 110 +- Robust/src/ClassLibrary/FileWriter.java | 6 +- Robust/src/ClassLibrary/HashEntry.java | 9 +- Robust/src/ClassLibrary/HashMap.java | 224 +- Robust/src/ClassLibrary/HashMapIterator.java | 80 +- Robust/src/ClassLibrary/HashSet.java | 56 +- Robust/src/ClassLibrary/InetAddress.java | 104 +- Robust/src/ClassLibrary/InputStream.java | 18 +- Robust/src/ClassLibrary/Integer.java | 102 +- Robust/src/ClassLibrary/Math.java | 62 +- Robust/src/ClassLibrary/Object.java | 44 +- Robust/src/ClassLibrary/ObjectJava.java | 48 +- Robust/src/ClassLibrary/ObjectJavaDSM.java | 44 +- Robust/src/ClassLibrary/ObjectJavaNT.java | 40 +- Robust/src/ClassLibrary/OutputStream.java | 34 +- .../src/ClassLibrary/OutputStreamWriter.java | 20 +- Robust/src/ClassLibrary/ServerSocket.java | 69 +- Robust/src/ClassLibrary/ServerSocketJava.java | 42 +- Robust/src/ClassLibrary/Signal.java | 2 +- Robust/src/ClassLibrary/Socket.java | 116 +- .../src/ClassLibrary/SocketInputStream.java | 34 +- Robust/src/ClassLibrary/SocketJava.java | 118 +- .../src/ClassLibrary/SocketOutputStream.java | 40 +- Robust/src/ClassLibrary/StartupObject.java | 4 +- Robust/src/ClassLibrary/String.java | 682 +-- Robust/src/ClassLibrary/StringBuffer.java | 124 +- Robust/src/ClassLibrary/System.java | 26 +- Robust/src/ClassLibrary/Thread.java | 33 +- Robust/src/ClassLibrary/ThreadDSM.java | 26 +- Robust/src/ClassLibrary/Vector.java | 130 +- Robust/src/ClassLibrary/Writer.java | 24 +- Robust/src/ClassLibrary/gnu/Random.java | 316 +- Robust/src/IR/AssignOperation.java | 251 +- Robust/src/IR/ClassDescriptor.java | 272 +- Robust/src/IR/Descriptor.java | 72 +- Robust/src/IR/FieldDescriptor.java | 76 +- Robust/src/IR/FlagDescriptor.java | 30 +- Robust/src/IR/Flat/BuildCode.java | 5287 +++++++++-------- Robust/src/IR/Flat/BuildCodeMultiCore.java | 2404 ++++---- Robust/src/IR/Flat/BuildFlat.java | 1894 +++--- Robust/src/IR/Flat/FKind.java | 42 +- Robust/src/IR/Flat/FlatAtomicEnterNode.java | 30 +- Robust/src/IR/Flat/FlatAtomicExitNode.java | 26 +- Robust/src/IR/Flat/FlatBackEdge.java | 16 +- Robust/src/IR/Flat/FlatCall.java | 132 +- Robust/src/IR/Flat/FlatCastNode.java | 74 +- Robust/src/IR/Flat/FlatCheckNode.java | 48 +- Robust/src/IR/Flat/FlatCondBranch.java | 102 +- Robust/src/IR/Flat/FlatElementNode.java | 82 +- Robust/src/IR/Flat/FlatFieldNode.java | 74 +- Robust/src/IR/Flat/FlatFlagActionNode.java | 227 +- Robust/src/IR/Flat/FlatGlobalConvNode.java | 84 +- Robust/src/IR/Flat/FlatLiteralNode.java | 104 +- Robust/src/IR/Flat/FlatMethod.java | 348 +- Robust/src/IR/Flat/FlatNew.java | 112 +- Robust/src/IR/Flat/FlatNode.java | 104 +- Robust/src/IR/Flat/FlatNop.java | 16 +- Robust/src/IR/Flat/FlatOpNode.java | 106 +- Robust/src/IR/Flat/FlatPrefetchNode.java | 80 +- Robust/src/IR/Flat/FlatReturnNode.java | 38 +- Robust/src/IR/Flat/FlatSetElementNode.java | 74 +- Robust/src/IR/Flat/FlatSetFieldNode.java | 66 +- Robust/src/IR/Flat/FlatTagDeclaration.java | 62 +- Robust/src/IR/Flat/NodePair.java | 24 +- Robust/src/IR/Flat/ParamsObject.java | 150 +- Robust/src/IR/Flat/TempDescriptor.java | 154 +- Robust/src/IR/Flat/TempFlagPair.java | 54 +- Robust/src/IR/Flat/TempObject.java | 160 +- Robust/src/IR/Flat/TempTagPair.java | 86 +- Robust/src/IR/MethodDescriptor.java | 348 +- Robust/src/IR/NameDescriptor.java | 60 +- Robust/src/IR/Operation.java | 316 +- Robust/src/IR/State.java | 354 +- Robust/src/IR/SymbolTable.java | 236 +- Robust/src/IR/TagDescriptor.java | 34 +- Robust/src/IR/TagVarDescriptor.java | 92 +- Robust/src/IR/TaskDescriptor.java | 186 +- Robust/src/IR/Tree/ArrayAccessNode.java | 42 +- Robust/src/IR/Tree/AssignmentNode.java | 66 +- Robust/src/IR/Tree/AtomicNode.java | 28 +- Robust/src/IR/Tree/BlockExpressionNode.java | 28 +- Robust/src/IR/Tree/BlockNode.java | 140 +- Robust/src/IR/Tree/BlockStatementNode.java | 12 +- Robust/src/IR/Tree/BuildIR.java | 1558 +++-- Robust/src/IR/Tree/CastNode.java | 84 +- Robust/src/IR/Tree/ConstraintCheck.java | 88 +- Robust/src/IR/Tree/CreateObjectNode.java | 118 +- Robust/src/IR/Tree/DNFFlag.java | 186 +- Robust/src/IR/Tree/DNFFlagAtom.java | 42 +- Robust/src/IR/Tree/DeclarationNode.java | 44 +- Robust/src/IR/Tree/ExpressionNode.java | 12 +- Robust/src/IR/Tree/FieldAccessNode.java | 68 +- Robust/src/IR/Tree/FlagEffect.java | 62 +- Robust/src/IR/Tree/FlagEffects.java | 90 +- Robust/src/IR/Tree/FlagExpressionNode.java | 12 +- Robust/src/IR/Tree/FlagNode.java | 52 +- Robust/src/IR/Tree/FlagOpNode.java | 102 +- Robust/src/IR/Tree/IfStatementNode.java | 56 +- Robust/src/IR/Tree/Kind.java | 42 +- Robust/src/IR/Tree/LiteralNode.java | 112 +- Robust/src/IR/Tree/LoopNode.java | 104 +- Robust/src/IR/Tree/MethodInvokeNode.java | 132 +- Robust/src/IR/Tree/Modifiers.java | 110 +- Robust/src/IR/Tree/NameNode.java | 106 +- Robust/src/IR/Tree/OpNode.java | 104 +- Robust/src/IR/Tree/ParseNode.java | 406 +- Robust/src/IR/Tree/ParseNodeDOTVisitor.java | 104 +- Robust/src/IR/Tree/ParseNodeVector.java | 32 +- Robust/src/IR/Tree/ReturnNode.java | 38 +- Robust/src/IR/Tree/SemanticCheck.java | 1924 +++--- Robust/src/IR/Tree/SubBlockNode.java | 28 +- Robust/src/IR/Tree/TagDeclarationNode.java | 50 +- Robust/src/IR/Tree/TagEffect.java | 62 +- Robust/src/IR/Tree/TagExpressionList.java | 72 +- Robust/src/IR/Tree/TaskExitNode.java | 36 +- Robust/src/IR/Tree/TreeNode.java | 26 +- Robust/src/IR/Tree/Walkable.java | 40 +- Robust/src/IR/TypeDescriptor.java | 520 +- Robust/src/IR/TypeUtil.java | 472 +- Robust/src/IR/VarDescriptor.java | 40 +- Robust/src/IR/Virtual.java | 212 +- Robust/src/Interface/HTTPHeader.java | 61 +- Robust/src/Interface/HTTPResponse.java | 6 +- Robust/src/Interface/HTTPServices.java | 128 +- Robust/src/Interface/HashStrings.java | 56 +- Robust/src/Interface/IdentityRelation.java | 42 +- Robust/src/Interface/Imap.java | 254 +- Robust/src/Interface/JhttpServer.java | 55 +- Robust/src/Interface/JhttpWorker.java | 297 +- Robust/src/Interface/LogFile.java | 72 +- Robust/src/Interface/WebInterface.java | 518 +- Robust/src/Lex/BooleanLiteral.java | 12 +- Robust/src/Lex/CharacterLiteral.java | 12 +- Robust/src/Lex/Comment.java | 6 +- Robust/src/Lex/DocumentationComment.java | 5 +- Robust/src/Lex/DoubleLiteral.java | 8 +- Robust/src/Lex/EOF.java | 11 +- Robust/src/Lex/EndOfLineComment.java | 4 +- Robust/src/Lex/EscapedUnicodeReader.java | 16 +- Robust/src/Lex/FIFO.java | 18 +- Robust/src/Lex/FloatLiteral.java | 8 +- Robust/src/Lex/Identifier.java | 12 +- Robust/src/Lex/IntegerLiteral.java | 8 +- Robust/src/Lex/Keyword.java | 8 +- Robust/src/Lex/Lexer.java | 129 +- Robust/src/Lex/LongLiteral.java | 8 +- Robust/src/Lex/NullLiteral.java | 11 +- Robust/src/Lex/NumericLiteral.java | 4 +- Robust/src/Lex/Operator.java | 12 +- Robust/src/Lex/Separator.java | 14 +- Robust/src/Lex/StringLiteral.java | 12 +- Robust/src/Lex/Token.java | 3 + Robust/src/Lex/TraditionalComment.java | 3 +- Robust/src/Lex/WhiteSpace.java | 10 +- Robust/src/Main/Main.java | 828 ++- .../DSTM/interface/addPrefetchEnhance.c | 32 +- .../DSTM/interface/addPrefetchEnhance.h | 6 +- .../Runtime/DSTM/interface/addUdpEnhance.c | 39 +- .../Runtime/DSTM/interface/addUdpEnhance.h | 2 +- Robust/src/Runtime/DSTM/interface/clookup.c | 96 +- Robust/src/Runtime/DSTM/interface/clookup.h | 8 +- Robust/src/Runtime/DSTM/interface/dht.c | 2882 +++++---- Robust/src/Runtime/DSTM/interface/dht.h | 2 +- Robust/src/Runtime/DSTM/interface/dsmdebug.h | 12 +- Robust/src/Runtime/DSTM/interface/dstm.h | 190 +- .../src/Runtime/DSTM/interface/dstmserver.c | 670 +-- Robust/src/Runtime/DSTM/interface/gCollect.c | 88 +- Robust/src/Runtime/DSTM/interface/ip.c | 137 +- Robust/src/Runtime/DSTM/interface/ip.h | 10 +- Robust/src/Runtime/DSTM/interface/llookup.c | 342 +- Robust/src/Runtime/DSTM/interface/llookup.h | 16 +- .../src/Runtime/DSTM/interface/localobjects.h | 2 +- .../src/Runtime/DSTM/interface/machinepile.c | 14 +- Robust/src/Runtime/DSTM/interface/main.c | 36 +- Robust/src/Runtime/DSTM/interface/mcpileq.c | 14 +- Robust/src/Runtime/DSTM/interface/mcpileq.h | 10 +- Robust/src/Runtime/DSTM/interface/mlookup.c | 367 +- Robust/src/Runtime/DSTM/interface/mlookup.h | 16 +- Robust/src/Runtime/DSTM/interface/objstr.c | 26 +- Robust/src/Runtime/DSTM/interface/plookup.c | 114 +- Robust/src/Runtime/DSTM/interface/plookup.h | 20 +- Robust/src/Runtime/DSTM/interface/prelookup.c | 98 +- Robust/src/Runtime/DSTM/interface/prelookup.h | 8 +- Robust/src/Runtime/DSTM/interface/queue.c | 14 +- Robust/src/Runtime/DSTM/interface/queue.h | 8 +- Robust/src/Runtime/DSTM/interface/signal.c | 10 +- Robust/src/Runtime/DSTM/interface/sockpool.c | 208 +- Robust/src/Runtime/DSTM/interface/sockpool.h | 24 +- .../src/Runtime/DSTM/interface/threadnotify.c | 74 +- .../src/Runtime/DSTM/interface/threadnotify.h | 44 +- Robust/src/Runtime/DSTM/interface/trans.c | 836 ++- Robust/src/Runtime/GenericHashtable.c | 48 +- Robust/src/Runtime/ObjectHash.c | 266 +- Robust/src/Runtime/ObjectHash.h | 10 +- Robust/src/Runtime/SimpleHash.c | 286 +- Robust/src/Runtime/SimpleHash.h | 10 +- Robust/src/Runtime/checkpoint.c | 116 +- Robust/src/Runtime/file.c | 14 +- Robust/src/Runtime/garbage.c | 91 +- Robust/src/Runtime/mem.c | 56 +- Robust/src/Runtime/mem.h | 4 +- Robust/src/Runtime/multicoreruntime.c | 54 +- Robust/src/Runtime/multicoretask.c | 4247 ++++++------- Robust/src/Runtime/object.c | 2 +- Robust/src/Runtime/object.h | 2 +- Robust/src/Runtime/option.c | 4 +- Robust/src/Runtime/runtime.c | 27 +- Robust/src/Runtime/runtime.h | 14 +- Robust/src/Runtime/socket.c | 84 +- Robust/src/Runtime/task.c | 494 +- Robust/src/Runtime/thread.c | 78 +- Robust/src/Util/Edge.java | 122 +- Robust/src/Util/GraphNode.java | 980 +-- Robust/src/Util/Namer.java | 29 +- Robust/src/Util/Relation.java | 66 +- 293 files changed, 33895 insertions(+), 33772 deletions(-) diff --git a/Robust/src/Analysis/CallGraph/CallGraph.java b/Robust/src/Analysis/CallGraph/CallGraph.java index b3e68e12..3042da3e 100644 --- a/Robust/src/Analysis/CallGraph/CallGraph.java +++ b/Robust/src/Analysis/CallGraph/CallGraph.java @@ -13,225 +13,225 @@ import java.util.*; import java.io.*; public class CallGraph { - private State state; - - // MethodDescriptor maps to HashSet - private Hashtable mapVirtual2ImplementationSet; - - // MethodDescriptor or TaskDescriptor maps to HashSet - private Hashtable mapCaller2CalleeSet; - - // MethodDescriptor maps to HashSet - private Hashtable mapCallee2CallerSet; - - public CallGraph(State state) { - this.state=state; - mapVirtual2ImplementationSet = new Hashtable(); - mapCaller2CalleeSet = new Hashtable(); - mapCallee2CallerSet = new Hashtable(); - buildVirtualMap(); - buildGraph(); - } - - // this method returns the set of Descriptors - // (MethodDescriptors and/or TaskDescriptors) - // that call the given method - public Set getCallerSet( MethodDescriptor md ) { - return (Set) mapCallee2CallerSet.get( md ); - } - - // this method returns the set of MethodDescriptors that - // are called by the given method or task - public Set getCalleeSet( Descriptor d ) { - assert (d instanceof MethodDescriptor) || - (d instanceof TaskDescriptor); - - return (Set) mapCaller2CalleeSet.get( d ); - } - - // build a mapping of virtual methods to all - // possible implementations of that method - private void buildVirtualMap() { - //Iterator through classes - Iterator it=state.getClassSymbolTable().getDescriptorsIterator(); - while(it.hasNext()) { - ClassDescriptor cn=(ClassDescriptor)it.next(); - Iterator methodit=cn.getMethods(); - //Iterator through methods - while(methodit.hasNext()) { - MethodDescriptor md=(MethodDescriptor)methodit.next(); - if (md.isStatic()||md.getReturnType()==null) - continue; - ClassDescriptor superdesc=cn.getSuperDesc(); - 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)) { - if (!mapVirtual2ImplementationSet.containsKey(matchmd)) - mapVirtual2ImplementationSet.put(matchmd,new HashSet()); - ((HashSet)mapVirtual2ImplementationSet.get(matchmd)).add(md); - break; - } - } - } + private State state; + + // MethodDescriptor maps to HashSet + private Hashtable mapVirtual2ImplementationSet; + + // MethodDescriptor or TaskDescriptor maps to HashSet + private Hashtable mapCaller2CalleeSet; + + // MethodDescriptor maps to HashSet + private Hashtable mapCallee2CallerSet; + + public CallGraph(State state) { + this.state=state; + mapVirtual2ImplementationSet = new Hashtable(); + mapCaller2CalleeSet = new Hashtable(); + mapCallee2CallerSet = new Hashtable(); + buildVirtualMap(); + buildGraph(); + } + + // this method returns the set of Descriptors + // (MethodDescriptors and/or TaskDescriptors) + // that call the given method + public Set getCallerSet(MethodDescriptor md) { + return (Set) mapCallee2CallerSet.get(md); + } + + // this method returns the set of MethodDescriptors that + // are called by the given method or task + public Set getCalleeSet(Descriptor d) { + assert(d instanceof MethodDescriptor) || + (d instanceof TaskDescriptor); + + return (Set) mapCaller2CalleeSet.get(d); + } + + // build a mapping of virtual methods to all + // possible implementations of that method + private void buildVirtualMap() { + //Iterator through classes + Iterator it=state.getClassSymbolTable().getDescriptorsIterator(); + while(it.hasNext()) { + ClassDescriptor cn=(ClassDescriptor)it.next(); + Iterator methodit=cn.getMethods(); + //Iterator through methods + while(methodit.hasNext()) { + MethodDescriptor md=(MethodDescriptor)methodit.next(); + if (md.isStatic()||md.getReturnType()==null) + continue; + ClassDescriptor superdesc=cn.getSuperDesc(); + 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)) { + if (!mapVirtual2ImplementationSet.containsKey(matchmd)) + mapVirtual2ImplementationSet.put(matchmd,new HashSet()); + ((HashSet)mapVirtual2ImplementationSet.get(matchmd)).add(md); + break; } + } } + } } - - public Set getMethods(MethodDescriptor md, TypeDescriptor type) { - return getMethods(md); - } - - /** Given a call to MethodDescriptor, lists the methods which - could actually be called due to virtual dispatch. */ - public Set getMethods(MethodDescriptor md) { - HashSet ns=new HashSet(); - ns.add(md); - 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)); - } - return ns; + } + + public Set getMethods(MethodDescriptor md, TypeDescriptor type) { + return getMethods(md); + } + + /** Given a call to MethodDescriptor, lists the methods which + could actually be called due to virtual dispatch. */ + public Set getMethods(MethodDescriptor md) { + HashSet ns=new HashSet(); + ns.add(md); + 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)); + } + return ns; + } + + /** Given a call to MethodDescriptor, lists the methods which + could actually be call by that method. */ + public Set getMethodCalls(MethodDescriptor md) { + HashSet ns=new HashSet(); + ns.add(md); + Set s=(Set)mapCaller2CalleeSet.get(md); + if (s!=null) + for(Iterator it=s.iterator(); it.hasNext();) { + MethodDescriptor md2=(MethodDescriptor)it.next(); + ns.addAll(getMethodCalls(md2)); + } + return ns; + } + + private void buildGraph() { + Iterator it=state.getClassSymbolTable().getDescriptorsIterator(); + while(it.hasNext()) { + ClassDescriptor cn=(ClassDescriptor)it.next(); + Iterator methodit=cn.getMethods(); + //Iterator through methods + while(methodit.hasNext()) { + MethodDescriptor md=(MethodDescriptor)methodit.next(); + analyzeMethod( (Object)md, state.getMethodFlat(md) ); + } } - - /** Given a call to MethodDescriptor, lists the methods which - could actually be call by that method. */ - public Set getMethodCalls(MethodDescriptor md) { - HashSet ns=new HashSet(); - ns.add(md); - Set s=(Set)mapCaller2CalleeSet.get(md); - if (s!=null) - for(Iterator it=s.iterator();it.hasNext();) { - MethodDescriptor md2=(MethodDescriptor)it.next(); - ns.addAll(getMethodCalls(md2)); - } - return ns; + it=state.getTaskSymbolTable().getDescriptorsIterator(); + while(it.hasNext()) { + TaskDescriptor td=(TaskDescriptor)it.next(); + analyzeMethod( (Object)td, state.getMethodFlat(td) ); } - - private void buildGraph() { - Iterator it=state.getClassSymbolTable().getDescriptorsIterator(); - while(it.hasNext()) { - ClassDescriptor cn=(ClassDescriptor)it.next(); - Iterator methodit=cn.getMethods(); - //Iterator through methods - while(methodit.hasNext()) { - MethodDescriptor md=(MethodDescriptor)methodit.next(); - analyzeMethod( (Object)md, state.getMethodFlat(md) ); - } + } + + private void analyzeMethod(Object caller, FlatMethod fm) { + HashSet toexplore=new HashSet(); + toexplore.add(fm); + HashSet explored=new HashSet(); + //look at all the nodes in the flat representation + while(!toexplore.isEmpty()) { + FlatNode fn=(FlatNode)(toexplore.iterator()).next(); + toexplore.remove(fn); + explored.add(fn); + for(int i=0; i callee maps + if( !mapCaller2CalleeSet.containsKey(caller) ) { + mapCaller2CalleeSet.put(caller, new HashSet() ); } - it=state.getTaskSymbolTable().getDescriptorsIterator(); - while(it.hasNext()) { - TaskDescriptor td=(TaskDescriptor)it.next(); - analyzeMethod( (Object)td, state.getMethodFlat(td) ); + ((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); } + } } - - private void analyzeMethod(Object caller, FlatMethod fm) { - HashSet toexplore=new HashSet(); - toexplore.add(fm); - HashSet explored=new HashSet(); - //look at all the nodes in the flat representation - while(!toexplore.isEmpty()) { - FlatNode fn=(FlatNode)(toexplore.iterator()).next(); - 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 ); - } - } + } + + public void writeToDot(String graphName) throws java.io.IOException { + // each task or method only needs to be labeled once + // in a dot file + HashSet labeledInDot = new HashSet(); + + // write out the call graph using the callees mapping + BufferedWriter bw = new BufferedWriter(new FileWriter(graphName+"byCallees.dot") ); + bw.write("digraph "+graphName+"byCallees {\n"); + Iterator mapItr = mapCallee2CallerSet.entrySet().iterator(); + while( mapItr.hasNext() ) { + Map.Entry me = (Map.Entry)mapItr.next(); + MethodDescriptor callee = (MethodDescriptor) me.getKey(); + HashSet callerSet = (HashSet) me.getValue(); + + if( !labeledInDot.contains(callee) ) { + labeledInDot.add(callee); + bw.write(" " + callee.getNum() + "[label=\"" + callee + "\"];\n"); + } + + Iterator callerItr = callerSet.iterator(); + while( callerItr.hasNext() ) { + Descriptor caller = (Descriptor) callerItr.next(); + + if( !labeledInDot.contains(caller) ) { + labeledInDot.add(caller); + bw.write(" " + caller.getNum() + "[label=\"" + caller + "\"];\n"); } - } - - public void writeToDot( String graphName ) throws java.io.IOException { - // each task or method only needs to be labeled once - // in a dot file - HashSet labeledInDot = new HashSet(); - - // write out the call graph using the callees mapping - BufferedWriter bw = new BufferedWriter( new FileWriter( graphName+"byCallees.dot" ) ); - bw.write( "digraph "+graphName+"byCallees {\n" ); - Iterator mapItr = mapCallee2CallerSet.entrySet().iterator(); - while( mapItr.hasNext() ) { - Map.Entry me = (Map.Entry) mapItr.next(); - MethodDescriptor callee = (MethodDescriptor) me.getKey(); - HashSet callerSet = (HashSet) me.getValue(); - - if( !labeledInDot.contains( callee ) ) { - labeledInDot.add( callee ); - bw.write( " " + callee.getNum() + "[label=\"" + callee + "\"];\n" ); - } - - Iterator callerItr = callerSet.iterator(); - while( callerItr.hasNext() ) { - Descriptor caller = (Descriptor) callerItr.next(); - if( !labeledInDot.contains( caller ) ) { - labeledInDot.add( caller ); - bw.write( " " + caller.getNum() + "[label=\"" + caller + "\"];\n" ); - } - - bw.write( " " + callee.getNum() + "->" + caller.getNum() + ";\n" ); - } + bw.write(" " + callee.getNum() + "->" + caller.getNum() + ";\n"); + } + } + bw.write("}\n"); + bw.close(); + + // write out the call graph (should be equivalent) by + // using the callers mapping + labeledInDot = new HashSet(); + bw = new BufferedWriter(new FileWriter(graphName+"byCallers.dot") ); + bw.write("digraph "+graphName+"byCallers {\n"); + mapItr = mapCaller2CalleeSet.entrySet().iterator(); + while( mapItr.hasNext() ) { + Map.Entry me = (Map.Entry)mapItr.next(); + Descriptor caller = (Descriptor) me.getKey(); + HashSet calleeSet = (HashSet) me.getValue(); + + if( !labeledInDot.contains(caller) ) { + labeledInDot.add(caller); + bw.write(" " + caller.getNum() + "[label=\"" + caller + "\"];\n"); + } + + Iterator calleeItr = calleeSet.iterator(); + while( calleeItr.hasNext() ) { + MethodDescriptor callee = (MethodDescriptor) calleeItr.next(); + + if( !labeledInDot.contains(callee) ) { + labeledInDot.add(callee); + bw.write(" " + callee.getNum() + "[label=\"" + callee + "\"];\n"); } - bw.write( "}\n" ); - bw.close(); - - // write out the call graph (should be equivalent) by - // using the callers mapping - labeledInDot = new HashSet(); - bw = new BufferedWriter( new FileWriter( graphName+"byCallers.dot" ) ); - bw.write( "digraph "+graphName+"byCallers {\n" ); - mapItr = mapCaller2CalleeSet.entrySet().iterator(); - while( mapItr.hasNext() ) { - Map.Entry me = (Map.Entry) mapItr.next(); - Descriptor caller = (Descriptor) me.getKey(); - HashSet calleeSet = (HashSet) me.getValue(); - - if( !labeledInDot.contains( caller ) ) { - labeledInDot.add( caller ); - bw.write( " " + caller.getNum() + "[label=\"" + caller + "\"];\n" ); - } - Iterator calleeItr = calleeSet.iterator(); - while( calleeItr.hasNext() ) { - MethodDescriptor callee = (MethodDescriptor) calleeItr.next(); - - if( !labeledInDot.contains( callee ) ) { - labeledInDot.add( callee ); - bw.write( " " + callee.getNum() + "[label=\"" + callee + "\"];\n" ); - } - - bw.write( " " + callee.getNum() + "->" + caller.getNum() + ";\n" ); - } - } - bw.write( "}\n" ); - bw.close(); + bw.write(" " + callee.getNum() + "->" + caller.getNum() + ";\n"); + } } + bw.write("}\n"); + bw.close(); + } } diff --git a/Robust/src/Analysis/FlatIRGraph/FlatIRGraph.java b/Robust/src/Analysis/FlatIRGraph/FlatIRGraph.java index ac816503..a5bfd34d 100644 --- a/Robust/src/Analysis/FlatIRGraph/FlatIRGraph.java +++ b/Robust/src/Analysis/FlatIRGraph/FlatIRGraph.java @@ -7,111 +7,111 @@ import java.io.*; public class FlatIRGraph { - private State state; + private State state; - private BufferedWriter flatbw; + private BufferedWriter flatbw; - private HashSet visited; - private HashSet toVisit; - - private int labelindex; - private Hashtable flatnodetolabel; + private HashSet visited; + private HashSet toVisit; - public FlatIRGraph(State state, boolean tasks, boolean usermethods, boolean libmethods) throws java.io.IOException { - this.state=state; + private int labelindex; + private Hashtable flatnodetolabel; - if( tasks ) - graphTasks(); + public FlatIRGraph(State state, boolean tasks, boolean usermethods, boolean libmethods) throws java.io.IOException { + this.state=state; - if( usermethods || libmethods ) - graphMethods(); - } + if( tasks ) + graphTasks(); - private void graphTasks() throws java.io.IOException { - for(Iterator it_tasks=state.getTaskSymbolTable().getDescriptorsIterator();it_tasks.hasNext();) { - TaskDescriptor td = (TaskDescriptor)it_tasks.next(); - FlatMethod fm = state.getMethodFlat(td); - writeFlatIRGraph(fm,"task"+td.getSymbol()); - } - } + if( usermethods || libmethods ) + graphMethods(); + } - private void graphMethods() throws java.io.IOException { - 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()); - } - } + private void graphTasks() throws java.io.IOException { + for(Iterator it_tasks=state.getTaskSymbolTable().getDescriptorsIterator(); it_tasks.hasNext();) { + TaskDescriptor td = (TaskDescriptor)it_tasks.next(); + FlatMethod fm = state.getMethodFlat(td); + writeFlatIRGraph(fm,"task"+td.getSymbol()); } - - private void writeFlatIRGraph( FlatMethod fm, String graphname ) throws java.io.IOException { - // give every node in the flat IR graph a unique label - // so a human being can inspect the graph and verify - // correctness - flatnodetolabel=new Hashtable(); - visited=new HashSet(); - labelindex=0; - labelFlatNodes( fm ); - - // take symbols out of graphname that cause dot to fail - graphname = graphname.replaceAll( "[\\W]", "" ); - - flatbw=new BufferedWriter( new FileWriter( graphname+"_flatIRGraph.dot" ) ); - flatbw.write("digraph "+graphname+" {\n"); - - visited=new HashSet(); - toVisit=new HashSet(); - toVisit.add(fm); - - while( !toVisit.isEmpty() ) { - FlatNode fn=(FlatNode)toVisit.iterator().next(); - toVisit.remove(fn); - visited.add(fn); - - if( fn.kind() == FKind.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() ) ); - } - - for(int i=0;i node"+flatnodetolabel.get(nn)+";\n" ); - - if( !visited.contains( nn ) ) { - toVisit.add( nn ); - } - } - } - - flatbw.write( "}\n" ); - flatbw.close(); + } + + private void graphMethods() throws java.io.IOException { + 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()); + } } - - private void labelFlatNodes(FlatNode fn) { - visited.add(fn); - flatnodetolabel.put(fn,new Integer(labelindex++)); - for(int i=0;i(); + visited=new HashSet(); + labelindex=0; + labelFlatNodes(fm); + + // take symbols out of graphname that cause dot to fail + graphname = graphname.replaceAll("[\\W]", ""); + + flatbw=new BufferedWriter(new FileWriter(graphname+"_flatIRGraph.dot") ); + flatbw.write("digraph "+graphname+" {\n"); + + visited=new HashSet(); + toVisit=new HashSet(); + toVisit.add(fm); + + while( !toVisit.isEmpty() ) { + FlatNode fn=(FlatNode)toVisit.iterator().next(); + toVisit.remove(fn); + visited.add(fn); + + if( fn.kind() == FKind.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() ) ); + } + + for(int i=0; i node"+flatnodetolabel.get(nn)+";\n"); + + if( !visited.contains(nn) ) { + toVisit.add(nn); } + } } - private String makeNodeName( String graphname, Integer id, String type ) { - String s = String.format( "%05d", id ); - return "FN"+s+"_"+type; + flatbw.write("}\n"); + flatbw.close(); + } + + private void labelFlatNodes(FlatNode fn) { + visited.add(fn); + flatnodetolabel.put(fn,new Integer(labelindex++)); + for(int i=0; i bindings=locality.getLocalityBindings(); + Iterator bindit=bindings.iterator(); + while(bindit.hasNext()) { + LocalityBinding lb=bindit.next(); + //Don't need to do conversion if it is already atomic + if (lb.isAtomic()) + continue; + converttoPtr(lb); + converttoOid(lb); } - - private void doConversion() { - Set bindings=locality.getLocalityBindings(); - Iterator bindit=bindings.iterator(); - while(bindit.hasNext()) { - LocalityBinding lb=bindit.next(); - //Don't need to do conversion if it is already atomic - if (lb.isAtomic()) - continue; - converttoPtr(lb); - converttoOid(lb); + } + + /* At the end of an atomic block, we need to convert any global + * references that will be used again into OID's. */ + + private void converttoOid(LocalityBinding lb) { + Hashtable atomictab=locality.getAtomic(lb); + Hashtable> temptab=locality.getNodeTempInfo(lb); + MethodDescriptor md=lb.getMethod(); + FlatMethod fm=state.getMethodFlat(md); + Hashtable> nodetotnpair=new Hashtable>(); + Hashtable> nodetoconvs=new Hashtable>(); + + Set toprocess=fm.getNodeSet(); + + while(!toprocess.isEmpty()) { + FlatNode fn=toprocess.iterator().next(); + toprocess.remove(fn); + boolean isatomic=atomictab.get(fn).intValue()>0; + Hashtable nodetemptab=temptab.get(fn); + + List reads=Arrays.asList(fn.readsTemps()); + List writes=Arrays.asList(fn.writesTemps()); + + if (!isatomic&&fn.kind()==FKind.FlatAtomicExitNode + &&!nodetoconvs.containsKey(fn)) + nodetoconvs.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); + } else + tempset.add(tnp); + } else + tempset.add(tnp); } - } - - /* At the end of an atomic block, we need to convert any global - * references that will be used again into OID's. */ - - private void converttoOid(LocalityBinding lb) { - Hashtable atomictab=locality.getAtomic(lb); - Hashtable> temptab=locality.getNodeTempInfo(lb); - MethodDescriptor md=lb.getMethod(); - FlatMethod fm=state.getMethodFlat(md); - Hashtable> nodetotnpair=new Hashtable>(); - Hashtable> nodetoconvs=new Hashtable>(); - - Set toprocess=fm.getNodeSet(); - - while(!toprocess.isEmpty()) { - FlatNode fn=toprocess.iterator().next(); - toprocess.remove(fn); - boolean isatomic=atomictab.get(fn).intValue()>0; - Hashtable nodetemptab=temptab.get(fn); - - List reads=Arrays.asList(fn.readsTemps()); - List writes=Arrays.asList(fn.writesTemps()); - - if (!isatomic&&fn.kind()==FKind.FlatAtomicExitNode - &&!nodetoconvs.containsKey(fn)) - nodetoconvs.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); - } 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 (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;i writeit=writes.iterator(); writeit.hasNext();) { + TempDescriptor wrtmp=writeit.next(); + if (nodetemptab.get(wrtmp)==LocalityAnalysis.GLOBAL) { + TempNodePair tnp=new TempNodePair(wrtmp); + tempset.add(tnp); } + } } - //Place Convert to Oid nodes - toprocess=fm.getNodeSet(); - for(Iterator it=toprocess.iterator();it.hasNext();) { - FlatNode fn=it.next(); - if (atomictab.get(fn).intValue()==0&&fn.numPrev()>0&& - atomictab.get(fn.getPrev(0)).intValue()>0) { - //sanity check - assert(fn.kind()==FKind.FlatAtomicExitNode); - //insert calls here... - Set tempset=nodetoconvs.get(fn); - for(Iterator tempit=tempset.iterator();tempit.hasNext();) { - FlatGlobalConvNode fgcn=new FlatGlobalConvNode(tempit.next(), lb, false); - atomictab.put(fgcn, atomictab.get(fn)); - temptab.put(fgcn, (Hashtable) temptab.get(fn).clone()); - - for(int i=0;i> nodetotranstemps=new Hashtable>(); - Hashtable atomictab=locality.getAtomic(lb); - Hashtable> temptab=locality.getNodeTempInfo(lb); - MethodDescriptor md=lb.getMethod(); - FlatMethod fm=state.getMethodFlat(md); - Set toprocess=fm.getNodeSet(); - - while(!toprocess.isEmpty()) { - FlatNode fn=toprocess.iterator().next(); - toprocess.remove(fn); - - if (atomictab.get(fn).intValue()>0) { - //build set of transaction temps use by next nodes - HashSet transtemps=new HashSet(); - for(int i=0;i pretemptab=locality.getNodePreTempInfo(lb, fn); - TempDescriptor []readtemps=fn.readsTemps(); - for(int i=0;i it=toprocess.iterator(); it.hasNext();) { + FlatNode fn=it.next(); + if (atomictab.get(fn).intValue()==0&&fn.numPrev()>0&& + atomictab.get(fn.getPrev(0)).intValue()>0) { + //sanity check + assert(fn.kind()==FKind.FlatAtomicExitNode); + //insert calls here... + Set tempset=nodetoconvs.get(fn); + for(Iterator tempit=tempset.iterator(); tempit.hasNext();) { + FlatGlobalConvNode fgcn=new FlatGlobalConvNode(tempit.next(), lb, false); + atomictab.put(fgcn, atomictab.get(fn)); + temptab.put(fgcn, (Hashtable)temptab.get(fn).clone()); + + for(int i=0; i it=toprocess.iterator();it.hasNext();) { - FlatNode fn=it.next(); - if (atomictab.get(fn).intValue()>0&& - 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); - atomictab.put(fgcn, atomictab.get(fn)); - temptab.put(fgcn, (Hashtable) temptab.get(fn).clone()); - fgcn.addNext(fn.getNext(0)); - fn.setNext(0, fgcn); - } - } + } + } + } + + /* At the beginning of an atomic block, we need to convert any + * OID's that will be used in the atomic block to pointers */ + + private void converttoPtr(LocalityBinding lb) { + Hashtable> nodetotranstemps=new Hashtable>(); + Hashtable atomictab=locality.getAtomic(lb); + Hashtable> temptab=locality.getNodeTempInfo(lb); + MethodDescriptor md=lb.getMethod(); + FlatMethod fm=state.getMethodFlat(md); + Set toprocess=fm.getNodeSet(); + + while(!toprocess.isEmpty()) { + FlatNode fn=toprocess.iterator().next(); + toprocess.remove(fn); + + if (atomictab.get(fn).intValue()>0) { + //build set of transaction temps use by next nodes + HashSet transtemps=new HashSet(); + for(int i=0; i pretemptab=locality.getNodePreTempInfo(lb, fn); + TempDescriptor [] readtemps=fn.readsTemps(); + for(int i=0; i it=toprocess.iterator(); it.hasNext();) { + FlatNode fn=it.next(); + if (atomictab.get(fn).intValue()>0&& + 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); + atomictab.put(fgcn, atomictab.get(fn)); + temptab.put(fgcn, (Hashtable)temptab.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 adac83f8..a7e645f5 100644 --- a/Robust/src/Analysis/Locality/LocalityAnalysis.java +++ b/Robust/src/Analysis/Locality/LocalityAnalysis.java @@ -10,718 +10,732 @@ import IR.Flat.*; import IR.ClassDescriptor; public class LocalityAnalysis { - State state; - Stack lbtovisit; - Hashtable discovered; - Hashtable> dependence; - Hashtable> calldep; - Hashtable>> temptab; - Hashtable> atomictab; - Hashtable>> tempstosave; - Hashtable> classtolb; - Hashtable> methodtolb; - private LocalityBinding lbmain; - private LocalityBinding lbrun; - - CallGraph callgraph; - TypeUtil typeutil; - public static final Integer LOCAL=new Integer(0); - public static final Integer GLOBAL=new Integer(1); - public static final Integer EITHER=new Integer(2); - public static final Integer CONFLICT=new Integer(3); - - public LocalityAnalysis(State state, CallGraph callgraph, TypeUtil typeutil) { - this.typeutil=typeutil; - this.state=state; - this.discovered=new Hashtable(); - this.dependence=new Hashtable>(); - this.calldep=new Hashtable>(); - this.temptab=new Hashtable>>(); - this.atomictab=new Hashtable>(); - this.lbtovisit=new Stack(); - this.callgraph=callgraph; - this.tempstosave=new Hashtable>>(); - this.classtolb=new Hashtable>(); - this.methodtolb=new Hashtable>(); - doAnalysis(); - } - - public LocalityBinding getMain() { - return lbmain; - } - - /** This method returns the set of LocalityBindings that a given - * flatcall could invoke */ - - public LocalityBinding getBinding(LocalityBinding currlb, FlatCall fc) { - boolean isatomic=getAtomic(currlb).get(fc).intValue()>0; - Hashtable currtable=getNodePreTempInfo(currlb,fc); - MethodDescriptor md=fc.getMethod(); - - boolean isnative=md.getModifiers().isNative(); - - LocalityBinding lb=new LocalityBinding(md, isatomic); - - for(int i=0;i getClassBindings(ClassDescriptor cd) { - return classtolb.get(cd); - } - - /** This method returns a set of LocalityBindings for the parameter method. */ - - public Set getMethodBindings(MethodDescriptor md) { - return methodtolb.get(md); - } - - public Set getMethods() { - return methodtolb.keySet(); - } - - /** This method returns a set of LocalityBindings. A - * LocalityBinding specifies a context a method can be invoked in. - * It specifies whether the method is in a transaction and whether - * its parameter objects are locals or globals. */ - - public Set getLocalityBindings() { - return discovered.keySet(); - } - - /** This method returns a hashtable for a given LocalityBinding - * that tells the current local/global status of temps at the each - * node in the flat representation. */ - - public Hashtable> getNodeTempInfo(LocalityBinding lb) { - return temptab.get(lb); - } - - /** This method returns a hashtable for a given LocalityBinding - * that tells the current local/global status of temps at the - * beginning of each node in the flat representation. */ - - public Hashtable getNodePreTempInfo(LocalityBinding lb, FlatNode fn) { - Hashtable currtable=new Hashtable(); - Hashtable> temptable=getNodeTempInfo(lb); - - 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); - } - } - return currtable; - } - - /** This method returns an hashtable for a given LocalitBinding - * that tells whether a node in the flat represenation is in a - * transaction or not. Integer values greater than 0 indicate - * that the node is in a transaction and give the nesting depth. - * The outermost AtomicEnterNode will have a value of 1 and the - * outermost AtomicExitNode will have a value of 0. */ - - public Hashtable getAtomic(LocalityBinding lb) { - return atomictab.get(lb); - } - - /** This methods returns a hashtable for a given LocalityBinding - * that tells which temps needs to be saved for each - * AtomicEnterNode. */ - - public Hashtable> getTemps(LocalityBinding lb) { - return tempstosave.get(lb); - } - - public Set getTempSet(LocalityBinding lb) { - HashSet set=new HashSet(); - Hashtable> table=getTemps(lb); - if (table!=null) - for(Iterator faenit=table.keySet().iterator();faenit.hasNext();) { - FlatAtomicEnterNode faen=faenit.next(); - set.addAll(table.get(faen)); - } - return set; - } - - private void doAnalysis() { - computeLocalityBindings(); - computeTempstoSave(); - cleanSets(); - } - - private void cleanSets() { - HashSet lbset=new HashSet(); - Stack lbstack=new Stack(); - lbstack.add(lbmain); - lbstack.add(lbrun); - lbset.add(lbmain); - lbset.add(lbrun); - 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); - } - } - 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); - } - } - } - - private void computeLocalityBindings() { - lbmain=new LocalityBinding(typeutil.getMain(), false); - lbmain.setGlobalReturn(EITHER); - lbmain.setGlobal(0, LOCAL); - lbtovisit.add(lbmain); - discovered.put(lbmain, lbmain); - if (!classtolb.containsKey(lbmain.getMethod().getClassDesc())) - classtolb.put(lbmain.getMethod().getClassDesc(), new HashSet()); - classtolb.get(lbmain.getMethod().getClassDesc()).add(lbmain); - - if (!methodtolb.containsKey(lbmain.getMethod())) - methodtolb.put(lbmain.getMethod(), new HashSet()); - methodtolb.get(lbmain.getMethod()).add(lbmain); - - //Do this to force a virtual table number for the run method - lbrun=new LocalityBinding(typeutil.getRun(), false); - lbrun.setGlobalReturn(EITHER); - lbrun.setGlobalThis(GLOBAL); - lbtovisit.add(lbrun); - discovered.put(lbrun, lbrun); - if (!classtolb.containsKey(lbrun.getMethod().getClassDesc())) - classtolb.put(lbrun.getMethod().getClassDesc(), new HashSet()); - classtolb.get(lbrun.getMethod().getClassDesc()).add(lbrun); - - if (!methodtolb.containsKey(lbrun.getMethod())) - methodtolb.put(lbrun.getMethod(), new HashSet()); - methodtolb.get(lbrun.getMethod()).add(lbrun); - - while(!lbtovisit.empty()) { - LocalityBinding lb=(LocalityBinding) lbtovisit.pop(); - Integer returnglobal=lb.getGlobalReturn(); - MethodDescriptor md=lb.getMethod(); - Hashtable> temptable=new Hashtable>(); - Hashtable atomictable=new Hashtable(); - calldep.remove(lb); - try { - computeCallsFlags(md, lb, temptable, atomictable); - } catch (Error e) { - System.out.println("Error in "+md+" context "+lb); - e.printStackTrace(); - System.exit(-1); - } - atomictab.put(lb, atomictable); - temptab.put(lb, temptable); - - if (md.getReturnType()!=null&&!returnglobal.equals(lb.getGlobalReturn())) { - //return type is more precise now - //rerun everything that call us - lbtovisit.addAll(dependence.get(lb)); - } - } - } - - public void computeCallsFlags(MethodDescriptor md, LocalityBinding lb, Hashtable> temptable, Hashtable atomictable) { - FlatMethod fm=state.getMethodFlat(md); - HashSet tovisit=new HashSet(); - tovisit.add(fm.getNext(0)); - { - // Build table for initial node - Hashtable table=new Hashtable(); - temptable.put(fm, table); - atomictable.put(fm, lb.isAtomic()?1:0); - int offset=md.isStatic()?0:1; - if (!md.isStatic()) { - 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); - } - } - atomictable.put(fn, atomicstate); - // Process this node - switch(fn.kind()) { - case FKind.FlatAtomicEnterNode: - processAtomicEnterNode((FlatAtomicEnterNode)fn, atomictable); - if (!lb.isAtomic()) - lb.setHasAtomic(); - break; - case FKind.FlatAtomicExitNode: - processAtomicExitNode((FlatAtomicExitNode)fn, atomictable); - break; - case FKind.FlatCall: - processCallNode(lb, (FlatCall)fn, currtable, isAtomic(atomictable, fn)); - break; - case FKind.FlatFieldNode: - processFieldNode(lb, (FlatFieldNode)fn, isAtomic(atomictable, fn), currtable); - break; - case FKind.FlatSetFieldNode: - processSetFieldNode(lb, (FlatSetFieldNode)fn, isAtomic(atomictable,fn), currtable); - break; - case FKind.FlatNew: - processNew(lb, (FlatNew)fn, isAtomic(atomictable, fn), currtable); - break; - case FKind.FlatOpNode: - processOpNode((FlatOpNode)fn, currtable); - break; - case FKind.FlatCastNode: - processCastNode((FlatCastNode)fn, currtable); - break; - case FKind.FlatLiteralNode: - processLiteralNode((FlatLiteralNode)fn, currtable); - break; - case FKind.FlatReturnNode: - processReturnNode(lb, (FlatReturnNode)fn, currtable); - break; - case FKind.FlatSetElementNode: - processSetElementNode(lb, (FlatSetElementNode)fn, currtable, isAtomic(atomictable, fn)); - break; - case FKind.FlatElementNode: - processElementNode(lb, (FlatElementNode)fn, currtable, isAtomic(atomictable, fn)); - break; - case FKind.FlatCondBranch: - case FKind.FlatBackEdge: - case FKind.FlatNop: - case FKind.FlatPrefetchNode: - //No action needed for these - break; - case FKind.FlatFlagActionNode: - case FKind.FlatCheckNode: - case FKind.FlatTagDeclaration: - throw new Error("Incompatible with tasks!"); - case FKind.FlatMethod: - default: - throw new Error(); - } - 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 atomictable, FlatNode fn) { - return atomictable.get(fn).intValue()>0; - } - - private static Integer merge(Integer a, Integer b) { - if (a==null||a.equals(EITHER)) - return b; - if (b==null||b.equals(EITHER)) - return a; - if (a.equals(b)) - return a; - return CONFLICT; - } - - void processCallNode(LocalityBinding currlb, FlatCall fc, Hashtable currtable, boolean isatomic) { - MethodDescriptor nodemd=fc.getMethod(); - Set methodset=null; - Set runmethodset=null; - - if (nodemd.isStatic()||nodemd.getReturnType()==null) { - methodset=new HashSet(); - methodset.add(nodemd); - } else { - methodset=callgraph.getMethods(nodemd, fc.getThis().getType()); - // Build start -> run link - if (nodemd.getClassDesc().getSymbol().equals(TypeUtil.ThreadClass)&& - nodemd.getSymbol().equals("start")&&!nodemd.getModifiers().isStatic()&& - nodemd.numParameters()==1&&nodemd.getParamType(0).isInt()) { - assert(nodemd.getModifiers().isNative()); - - MethodDescriptor runmd=null; - for(Iterator methodit=nodemd.getClassDesc().getMethodTable().getSet("run").iterator();methodit.hasNext();) { - MethodDescriptor md=(MethodDescriptor) methodit.next(); - if (md.numParameters()!=0||md.getModifiers().isStatic()) - continue; - runmd=md; - break; - } - if (runmd!=null) { - runmethodset=callgraph.getMethods(runmd,fc.getThis().getType()); - methodset.addAll(runmethodset); - } else throw new Error("Can't find run method"); - } + State state; + Stack lbtovisit; + Hashtable discovered; + Hashtable> dependence; + Hashtable> calldep; + Hashtable>> temptab; + Hashtable> atomictab; + Hashtable>> tempstosave; + Hashtable> classtolb; + Hashtable> methodtolb; + private LocalityBinding lbmain; + private LocalityBinding lbrun; + + CallGraph callgraph; + TypeUtil typeutil; + public static final Integer LOCAL=new Integer(0); + public static final Integer GLOBAL=new Integer(1); + public static final Integer EITHER=new Integer(2); + public static final Integer CONFLICT=new Integer(3); + + public LocalityAnalysis(State state, CallGraph callgraph, TypeUtil typeutil) { + this.typeutil=typeutil; + this.state=state; + this.discovered=new Hashtable(); + this.dependence=new Hashtable>(); + this.calldep=new Hashtable>(); + this.temptab=new Hashtable>>(); + this.atomictab=new Hashtable>(); + this.lbtovisit=new Stack(); + this.callgraph=callgraph; + this.tempstosave=new Hashtable>>(); + this.classtolb=new Hashtable>(); + this.methodtolb=new Hashtable>(); + doAnalysis(); + } + + public LocalityBinding getMain() { + return lbmain; + } + + /** This method returns the set of LocalityBindings that a given + * flatcall could invoke */ + + public LocalityBinding getBinding(LocalityBinding currlb, FlatCall fc) { + boolean isatomic=getAtomic(currlb).get(fc).intValue()>0; + Hashtable currtable=getNodePreTempInfo(currlb,fc); + MethodDescriptor md=fc.getMethod(); + + boolean isnative=md.getModifiers().isNative(); + + LocalityBinding lb=new LocalityBinding(md, isatomic); + + for(int i=0; i getClassBindings(ClassDescriptor cd) { + return classtolb.get(cd); + } + + /** This method returns a set of LocalityBindings for the parameter method. */ + + public Set getMethodBindings(MethodDescriptor md) { + return methodtolb.get(md); + } + + public Set getMethods() { + return methodtolb.keySet(); + } + + /** This method returns a set of LocalityBindings. A + * LocalityBinding specifies a context a method can be invoked in. + * It specifies whether the method is in a transaction and whether + * its parameter objects are locals or globals. */ + + public Set getLocalityBindings() { + return discovered.keySet(); + } + + /** This method returns a hashtable for a given LocalityBinding + * that tells the current local/global status of temps at the each + * node in the flat representation. */ + + public Hashtable> getNodeTempInfo(LocalityBinding lb) { + return temptab.get(lb); + } + + /** This method returns a hashtable for a given LocalityBinding + * that tells the current local/global status of temps at the + * beginning of each node in the flat representation. */ + + public Hashtable getNodePreTempInfo(LocalityBinding lb, FlatNode fn) { + Hashtable currtable=new Hashtable(); + Hashtable> temptable=getNodeTempInfo(lb); + + 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); + } + } + return currtable; + } + + /** This method returns an hashtable for a given LocalitBinding + * that tells whether a node in the flat represenation is in a + * transaction or not. Integer values greater than 0 indicate + * that the node is in a transaction and give the nesting depth. + * The outermost AtomicEnterNode will have a value of 1 and the + * outermost AtomicExitNode will have a value of 0. */ + + public Hashtable getAtomic(LocalityBinding lb) { + return atomictab.get(lb); + } + + /** This methods returns a hashtable for a given LocalityBinding + * that tells which temps needs to be saved for each + * AtomicEnterNode. */ + + public Hashtable> getTemps(LocalityBinding lb) { + return tempstosave.get(lb); + } + + public Set getTempSet(LocalityBinding lb) { + HashSet set=new HashSet(); + Hashtable> table=getTemps(lb); + if (table!=null) + for(Iterator faenit=table.keySet().iterator(); faenit.hasNext();) { + FlatAtomicEnterNode faen=faenit.next(); + set.addAll(table.get(faen)); + } + return set; + } + + private void doAnalysis() { + computeLocalityBindings(); + computeTempstoSave(); + cleanSets(); + } + + private void cleanSets() { + HashSet lbset=new HashSet(); + Stack lbstack=new Stack(); + lbstack.add(lbmain); + lbstack.add(lbrun); + lbset.add(lbmain); + lbset.add(lbrun); + 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); + } + } + 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); + } + } + } + + private void computeLocalityBindings() { + lbmain=new LocalityBinding(typeutil.getMain(), false); + lbmain.setGlobalReturn(EITHER); + lbmain.setGlobal(0, LOCAL); + lbtovisit.add(lbmain); + discovered.put(lbmain, lbmain); + if (!classtolb.containsKey(lbmain.getMethod().getClassDesc())) + classtolb.put(lbmain.getMethod().getClassDesc(), new HashSet()); + classtolb.get(lbmain.getMethod().getClassDesc()).add(lbmain); + + if (!methodtolb.containsKey(lbmain.getMethod())) + methodtolb.put(lbmain.getMethod(), new HashSet()); + methodtolb.get(lbmain.getMethod()).add(lbmain); + + //Do this to force a virtual table number for the run method + lbrun=new LocalityBinding(typeutil.getRun(), false); + lbrun.setGlobalReturn(EITHER); + lbrun.setGlobalThis(GLOBAL); + lbtovisit.add(lbrun); + discovered.put(lbrun, lbrun); + if (!classtolb.containsKey(lbrun.getMethod().getClassDesc())) + classtolb.put(lbrun.getMethod().getClassDesc(), new HashSet()); + classtolb.get(lbrun.getMethod().getClassDesc()).add(lbrun); + + if (!methodtolb.containsKey(lbrun.getMethod())) + methodtolb.put(lbrun.getMethod(), new HashSet()); + methodtolb.get(lbrun.getMethod()).add(lbrun); + + while(!lbtovisit.empty()) { + LocalityBinding lb=(LocalityBinding) lbtovisit.pop(); + Integer returnglobal=lb.getGlobalReturn(); + MethodDescriptor md=lb.getMethod(); + Hashtable> temptable=new Hashtable>(); + Hashtable atomictable=new Hashtable(); + calldep.remove(lb); + try { + computeCallsFlags(md, lb, temptable, atomictable); + } catch (Error e) { + System.out.println("Error in "+md+" context "+lb); + e.printStackTrace(); + System.exit(-1); + } + atomictab.put(lb, atomictable); + temptab.put(lb, temptable); + + if (md.getReturnType()!=null&&!returnglobal.equals(lb.getGlobalReturn())) { + //return type is more precise now + //rerun everything that call us + lbtovisit.addAll(dependence.get(lb)); + } + } + } + + public void computeCallsFlags(MethodDescriptor md, LocalityBinding lb, Hashtable> temptable, Hashtable atomictable) { + FlatMethod fm=state.getMethodFlat(md); + HashSet tovisit=new HashSet(); + tovisit.add(fm.getNext(0)); + { + // Build table for initial node + Hashtable table=new Hashtable(); + temptable.put(fm, table); + atomictable.put(fm, lb.isAtomic() ? 1 : 0); + int offset=md.isStatic() ? 0 : 1; + if (!md.isStatic()) { + table.put(fm.getParameter(0), lb.getGlobalThis()); + } + for(int i=offset; i currtable=new Hashtable(); + int atomicstate=0; + 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); - } else - lb=discovered.get(lb); - Integer returnval=lb.getGlobalReturn(); - currreturnval=merge(returnval, currreturnval); - if (!dependence.containsKey(lb)) - dependence.put(lb, new HashSet()); - dependence.get(lb).add(currlb); - - if (!calldep.containsKey(currlb)) - calldep.put(currlb, new HashSet()); - calldep.get(currlb).add(lb); + 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); } - if (fc.getReturnTemp()!=null) { - currtable.put(fc.getReturnTemp(), currreturnval); + } + atomictable.put(fn, atomicstate); + // Process this node + switch(fn.kind()) { + case FKind.FlatAtomicEnterNode: + processAtomicEnterNode((FlatAtomicEnterNode)fn, atomictable); + if (!lb.isAtomic()) + lb.setHasAtomic(); + break; + + case FKind.FlatAtomicExitNode: + processAtomicExitNode((FlatAtomicExitNode)fn, atomictable); + break; + + case FKind.FlatCall: + processCallNode(lb, (FlatCall)fn, currtable, isAtomic(atomictable, fn)); + break; + + case FKind.FlatFieldNode: + processFieldNode(lb, (FlatFieldNode)fn, isAtomic(atomictable, fn), currtable); + break; + + case FKind.FlatSetFieldNode: + processSetFieldNode(lb, (FlatSetFieldNode)fn, isAtomic(atomictable,fn), currtable); + break; + + case FKind.FlatNew: + processNew(lb, (FlatNew)fn, isAtomic(atomictable, fn), currtable); + break; + + case FKind.FlatOpNode: + processOpNode((FlatOpNode)fn, currtable); + break; + + case FKind.FlatCastNode: + processCastNode((FlatCastNode)fn, currtable); + break; + + case FKind.FlatLiteralNode: + processLiteralNode((FlatLiteralNode)fn, currtable); + break; + + case FKind.FlatReturnNode: + processReturnNode(lb, (FlatReturnNode)fn, currtable); + break; + + case FKind.FlatSetElementNode: + processSetElementNode(lb, (FlatSetElementNode)fn, currtable, isAtomic(atomictable, fn)); + break; + + case FKind.FlatElementNode: + processElementNode(lb, (FlatElementNode)fn, currtable, isAtomic(atomictable, fn)); + break; + + case FKind.FlatCondBranch: + case FKind.FlatBackEdge: + case FKind.FlatNop: + case FKind.FlatPrefetchNode: + //No action needed for these + break; + + case FKind.FlatFlagActionNode: + case FKind.FlatCheckNode: + case FKind.FlatTagDeclaration: + throw new Error("Incompatible with tasks!"); + + case FKind.FlatMethod: + default: + throw new Error(); + } + 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 currtable) { - Integer type=currtable.get(ffn.getSrc()); - TempDescriptor dst=ffn.getDst(); - if (type.equals(LOCAL)) { - if (ffn.getField().isGlobal()) - currtable.put(dst,GLOBAL); - else - 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()); - if (ffn.getField().getType().isPrimitive()&&!ffn.getField().getType().isArray()) - currtable.put(dst, LOCAL); // primitives are local - else - 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 - else if (ffn.getField().isGlobal()) - currtable.put(dst, GLOBAL); - else - 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()); + } + } + } + + private static boolean isAtomic(Hashtable atomictable, FlatNode fn) { + return atomictable.get(fn).intValue()>0; + } + + private static Integer merge(Integer a, Integer b) { + if (a==null||a.equals(EITHER)) + return b; + if (b==null||b.equals(EITHER)) + return a; + if (a.equals(b)) + return a; + return CONFLICT; + } + + void processCallNode(LocalityBinding currlb, FlatCall fc, Hashtable currtable, boolean isatomic) { + MethodDescriptor nodemd=fc.getMethod(); + Set methodset=null; + Set runmethodset=null; + + if (nodemd.isStatic()||nodemd.getReturnType()==null) { + methodset=new HashSet(); + methodset.add(nodemd); + } else { + methodset=callgraph.getMethods(nodemd, fc.getThis().getType()); + // Build start -> run link + if (nodemd.getClassDesc().getSymbol().equals(TypeUtil.ThreadClass)&& + nodemd.getSymbol().equals("start")&&!nodemd.getModifiers().isStatic()&& + nodemd.numParameters()==1&&nodemd.getParamType(0).isInt()) { + assert(nodemd.getModifiers().isNative()); + + MethodDescriptor runmd=null; + for(Iterator methodit=nodemd.getClassDesc().getMethodTable().getSet("run").iterator(); methodit.hasNext();) { + MethodDescriptor md=(MethodDescriptor) methodit.next(); + if (md.numParameters()!=0||md.getModifiers().isStatic()) + continue; + runmd=md; + break; } - } - - //need to handle primitives - void processSetFieldNode(LocalityBinding lb, FlatSetFieldNode fsfn, boolean transaction, Hashtable currtable) { - Integer srctype=currtable.get(fsfn.getSrc()); - Integer dsttype=currtable.get(fsfn.getDst()); - - 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()); - } else { - 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()); - //okay to store primitives in global object - if (srctype.equals(LOCAL) && fsfn.getField().getType().isPrimitive() && ! fsfn.getField().getType().isArray()) - 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); - } 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()); - } else if (dsttype.equals(CONFLICT)) { - throw new Error("Access to object that could be either global or local in context:\n"+lb.getExplanation()); + if (runmd!=null) { + runmethodset=callgraph.getMethods(runmd,fc.getThis().getType()); + methodset.addAll(runmethodset); + } else throw new Error("Can't find run method"); + } + } + + Integer currreturnval=EITHER; //Start off with the either value + for(Iterator methodit=methodset.iterator(); methodit.hasNext();) { + MethodDescriptor md=(MethodDescriptor) methodit.next(); + + boolean isnative=md.getModifiers().isNative(); + boolean isjoin = md.getClassDesc().getSymbol().equals(TypeUtil.ThreadClass)&&!nodemd.getModifiers().isStatic()&&nodemd.numParameters()==0&&md.getSymbol().equals("join"); + + LocalityBinding lb=new LocalityBinding(md, isatomic); + if (isnative&&isatomic) { + System.out.println("Don't call native methods in atomic blocks!"+currlb.getMethod()); + } + if (runmethodset==null||!runmethodset.contains(md)) { + //Skip this part if it is a run method + for(int i=0; i currtable) { - if (fn.isGlobal()&&!transaction) { - throw new Error("Allocating global object outside of transaction in context:"+lb.getExplanation()); - } - if (fn.isGlobal()) - currtable.put(fn.getDst(), GLOBAL); - else - currtable.put(fn.getDst(), LOCAL); - } - - void processOpNode(FlatOpNode fon, Hashtable currtable) { - /* Just propagate value */ - Integer srcvalue=currtable.get(fon.getLeft()); - - if (srcvalue==null) { - if (!fon.getLeft().getType().isPtr()) { - srcvalue=LOCAL; - } else - throw new Error(fon.getLeft()+" is undefined!"); - } - currtable.put(fon.getDest(), srcvalue); - } - - void processCastNode(FlatCastNode fcn, Hashtable currtable) { - currtable.put(fcn.getDst(), currtable.get(fcn.getSrc())); - } - - void processLiteralNode(FlatLiteralNode fln, Hashtable currtable) { - //null is either - if (fln.getValue()==null) - currtable.put(fln.getDst(), EITHER); + } + + if (fc.getThis()!=null) { + Integer thistype=currtable.get(fc.getThis()); + if (thistype==null) + thistype=EITHER; + + if(runmethodset!=null&&runmethodset.contains(md)&&thistype.equals(LOCAL)) + throw new Error("Starting thread on local object not allowed in context:\n"+currlb.getExplanation()); + if(isjoin&&thistype.equals(LOCAL)) + throw new Error("Joining thread on local object not allowed in context:\n"+currlb.getExplanation()); + if(thistype.equals(CONFLICT)) + throw new Error("Using type that can be either local or global in context:\n"+currlb.getExplanation()); + if(runmethodset==null&&thistype.equals(GLOBAL)&&!isatomic && !isjoin) + throw new Error("Using global object outside of transaction in context:\n"+currlb.getExplanation()); + if (runmethodset==null&&isnative&&thistype.equals(GLOBAL) && !isjoin) + throw new Error("Potential call to native method "+md+" on global objects:\n"+currlb.getExplanation()); + lb.setGlobalThis(thistype); + } + //lb is built + if (!discovered.containsKey(lb)) { + if (isnative) + lb.setGlobalReturn(LOCAL); else - currtable.put(fln.getDst(), LOCAL); - } - - void processReturnNode(LocalityBinding lb, FlatReturnNode frn, Hashtable currtable) { - if(frn.getReturnTemp()!=null) { - Integer returntype=currtable.get(frn.getReturnTemp()); - lb.setGlobalReturn(merge(returntype, lb.getGlobalReturn())); - } - } - - void processSetElementNode(LocalityBinding lb, FlatSetElementNode fsen, Hashtable currtable, boolean isatomic) { - Integer srctype=currtable.get(fsen.getSrc()); - Integer dsttype=currtable.get(fsen.getDst()); - - 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); - } else if (dsttype.equals(GLOBAL)) { - if (srctype.equals(LOCAL) && fsen.getDst().getType().dereference().isPrimitive() && ! fsen.getDst().getType().dereference().isArray()) - return; - if (!(srctype.equals(GLOBAL)||srctype.equals(EITHER))) - 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()); - } 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()); - } else if (dsttype.equals(CONFLICT)) { - throw new Error("Access to object that could be either global or local in context:\n"+lb.getExplanation()); + 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); + Integer returnval=lb.getGlobalReturn(); + currreturnval=merge(returnval, currreturnval); + if (!dependence.containsKey(lb)) + dependence.put(lb, new HashSet()); + dependence.get(lb).add(currlb); + + if (!calldep.containsKey(currlb)) + calldep.put(currlb, new HashSet()); + calldep.get(currlb).add(lb); + } + if (fc.getReturnTemp()!=null) { + currtable.put(fc.getReturnTemp(), currreturnval); + } + } + + void processFieldNode(LocalityBinding lb, FlatFieldNode ffn, boolean transaction, Hashtable currtable) { + Integer type=currtable.get(ffn.getSrc()); + TempDescriptor dst=ffn.getDst(); + if (type.equals(LOCAL)) { + if (ffn.getField().isGlobal()) + currtable.put(dst,GLOBAL); + else + 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()); + if (ffn.getField().getType().isPrimitive()&&!ffn.getField().getType().isArray()) + currtable.put(dst, LOCAL); // primitives are local + else + 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 + else if (ffn.getField().isGlobal()) + currtable.put(dst, GLOBAL); + else + 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()); + } + } + + //need to handle primitives + void processSetFieldNode(LocalityBinding lb, FlatSetFieldNode fsfn, boolean transaction, Hashtable currtable) { + Integer srctype=currtable.get(fsfn.getSrc()); + Integer dsttype=currtable.get(fsfn.getDst()); + + 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()); + } else { + 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()); + //okay to store primitives in global object + if (srctype.equals(LOCAL) && fsfn.getField().getType().isPrimitive() && !fsfn.getField().getType().isArray()) + 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); + } 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()); + } else if (dsttype.equals(CONFLICT)) { + throw new Error("Access to object that could be either global or local in context:\n"+lb.getExplanation()); + } + } + + void processNew(LocalityBinding lb, FlatNew fn, boolean transaction, Hashtable currtable) { + if (fn.isGlobal()&&!transaction) { + throw new Error("Allocating global object outside of transaction in context:"+lb.getExplanation()); + } + if (fn.isGlobal()) + currtable.put(fn.getDst(), GLOBAL); + else + currtable.put(fn.getDst(), LOCAL); + } + + void processOpNode(FlatOpNode fon, Hashtable currtable) { + /* Just propagate value */ + Integer srcvalue=currtable.get(fon.getLeft()); + + if (srcvalue==null) { + if (!fon.getLeft().getType().isPtr()) { + srcvalue=LOCAL; + } else + throw new Error(fon.getLeft()+" is undefined!"); + } + currtable.put(fon.getDest(), srcvalue); + } + + void processCastNode(FlatCastNode fcn, Hashtable currtable) { + currtable.put(fcn.getDst(), currtable.get(fcn.getSrc())); + } + + void processLiteralNode(FlatLiteralNode fln, Hashtable currtable) { + //null is either + if (fln.getValue()==null) + currtable.put(fln.getDst(), EITHER); + else + currtable.put(fln.getDst(), LOCAL); + } + + void processReturnNode(LocalityBinding lb, FlatReturnNode frn, Hashtable currtable) { + if(frn.getReturnTemp()!=null) { + Integer returntype=currtable.get(frn.getReturnTemp()); + lb.setGlobalReturn(merge(returntype, lb.getGlobalReturn())); + } + } + + void processSetElementNode(LocalityBinding lb, FlatSetElementNode fsen, Hashtable currtable, boolean isatomic) { + Integer srctype=currtable.get(fsen.getSrc()); + Integer dsttype=currtable.get(fsen.getDst()); + + 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); + } else if (dsttype.equals(GLOBAL)) { + if (srctype.equals(LOCAL) && fsen.getDst().getType().dereference().isPrimitive() && !fsen.getDst().getType().dereference().isArray()) + return; + if (!(srctype.equals(GLOBAL)||srctype.equals(EITHER))) + 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()); + } 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()); + } else if (dsttype.equals(CONFLICT)) { + throw new Error("Access to object that could be either global or local in context:\n"+lb.getExplanation()); + } + } + + void processElementNode(LocalityBinding lb, FlatElementNode fen, Hashtable currtable, boolean isatomic) { + Integer type=currtable.get(fen.getSrc()); + TempDescriptor dst=fen.getDst(); + if (type.equals(LOCAL)) { + 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()); + if(fen.getSrc().getType().dereference().isPrimitive()&& + !fen.getSrc().getType().dereference().isArray()) + currtable.put(dst, LOCAL); + else + currtable.put(dst, GLOBAL); + } else if (type.equals(EITHER)) { + if(fen.getSrc().getType().dereference().isPrimitive()&& + !fen.getSrc().getType().dereference().isArray()) + currtable.put(dst, LOCAL); + else + 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()); + } + } + + void processAtomicEnterNode(FlatAtomicEnterNode fen, Hashtable atomictable) { + int atomic=atomictable.get(fen).intValue(); + atomictable.put(fen, new Integer(atomic+1)); + } + + void processAtomicExitNode(FlatAtomicExitNode fen, Hashtable atomictable) { + int atomic=atomictable.get(fen).intValue(); + atomictable.put(fen, new Integer(atomic-1)); + } + + private Hashtable> computeLiveTemps(FlatMethod fm) { + Hashtable> nodetotemps=new Hashtable>(); + + Set toprocess=fm.getNodeSet(); + + while(!toprocess.isEmpty()) { + FlatNode fn=toprocess.iterator().next(); + toprocess.remove(fn); + + List reads=Arrays.asList(fn.readsTemps()); + List writes=Arrays.asList(fn.writesTemps()); + + HashSet tempset=new HashSet(); + for(int i=0; i lbit=getLocalityBindings().iterator(); lbit.hasNext();) { + LocalityBinding lb=lbit.next(); + computeTempstoSave(lb); + } + } + + /* Need to checkpoint all temps that could be read from along any + * path that are either: + 1) Written to by any assignment inside the transaction + 2) Read from a global temp. + + Generate tempstosave map from + localitybinding->flatatomicenternode->Set + */ + + private void computeTempstoSave(LocalityBinding lb) { + if (lb.isAtomic()) + return; + Hashtable atomictab=getAtomic(lb); + Hashtable> temptab=getNodeTempInfo(lb); + MethodDescriptor md=lb.getMethod(); + FlatMethod fm=state.getMethodFlat(md); + Hashtable> nodetotemps=computeLiveTemps(fm); + Hashtable> nodetosavetemps=new Hashtable>(); + tempstosave.put(lb, nodetosavetemps); + Hashtable nodemap=new Hashtable(); + HashSet toprocess=new HashSet(); + HashSet discovered=new HashSet(); + toprocess.add(fm); + discovered.add(fm); + while(!toprocess.isEmpty()) { + FlatNode fn=toprocess.iterator().next(); + toprocess.remove(fn); + boolean isatomic=atomictab.get(fn).intValue()>0; + if (isatomic&& + atomictab.get(fn.getPrev(0)).intValue()==0) { + assert(fn.getPrev(0).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(fn); + List reads=Arrays.asList(fn.readsTemps()); + List writes=Arrays.asList(fn.readsTemps()); + + for(Iterator tempit=livetemps.iterator(); tempit.hasNext();) { + TempDescriptor tmp=tempit.next(); + if (writes.contains(tmp)) { + nodetosavetemps.get(atomicnode).add(tmp); + } else if (reads.contains(tmp)&&temptab.get(fn).get(tmp)==GLOBAL) { + nodetosavetemps.get(atomicnode).add(tmp); + } } - } - - void processElementNode(LocalityBinding lb, FlatElementNode fen, Hashtable currtable, boolean isatomic) { - Integer type=currtable.get(fen.getSrc()); - TempDescriptor dst=fen.getDst(); - if (type.equals(LOCAL)) { - 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()); - if(fen.getSrc().getType().dereference().isPrimitive()&& - !fen.getSrc().getType().dereference().isArray()) - currtable.put(dst, LOCAL); - else - currtable.put(dst, GLOBAL); - } else if (type.equals(EITHER)) { - if(fen.getSrc().getType().dereference().isPrimitive()&& - !fen.getSrc().getType().dereference().isArray()) - currtable.put(dst, LOCAL); - else - 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()); - } - } - - void processAtomicEnterNode(FlatAtomicEnterNode fen, Hashtable atomictable) { - int atomic=atomictable.get(fen).intValue(); - atomictable.put(fen, new Integer(atomic+1)); - } - - void processAtomicExitNode(FlatAtomicExitNode fen, Hashtable atomictable) { - int atomic=atomictable.get(fen).intValue(); - atomictable.put(fen, new Integer(atomic-1)); - } - - private Hashtable> computeLiveTemps(FlatMethod fm) { - Hashtable> nodetotemps=new Hashtable>(); - - Set toprocess=fm.getNodeSet(); - - while(!toprocess.isEmpty()) { - FlatNode fn=toprocess.iterator().next(); - toprocess.remove(fn); - - List reads=Arrays.asList(fn.readsTemps()); - List writes=Arrays.asList(fn.writesTemps()); - - HashSet tempset=new HashSet(); - for(int i=0;i lbit=getLocalityBindings().iterator();lbit.hasNext();) { - LocalityBinding lb=lbit.next(); - computeTempstoSave(lb); - } - } - - /* Need to checkpoint all temps that could be read from along any - * path that are either: - 1) Written to by any assignment inside the transaction - 2) Read from a global temp. - - Generate tempstosave map from - localitybinding->flatatomicenternode->Set - */ - - private void computeTempstoSave(LocalityBinding lb) { - if (lb.isAtomic()) - return; - Hashtable atomictab=getAtomic(lb); - Hashtable> temptab=getNodeTempInfo(lb); - MethodDescriptor md=lb.getMethod(); - FlatMethod fm=state.getMethodFlat(md); - Hashtable> nodetotemps=computeLiveTemps(fm); - Hashtable> nodetosavetemps=new Hashtable>(); - tempstosave.put(lb, nodetosavetemps); - Hashtable nodemap=new Hashtable(); - HashSet toprocess=new HashSet(); - HashSet discovered=new HashSet(); - toprocess.add(fm); - discovered.add(fm); - while(!toprocess.isEmpty()) { - FlatNode fn=toprocess.iterator().next(); - toprocess.remove(fn); - boolean isatomic=atomictab.get(fn).intValue()>0; - if (isatomic&& - atomictab.get(fn.getPrev(0)).intValue()==0) { - assert(fn.getPrev(0).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(fn); - List reads=Arrays.asList(fn.readsTemps()); - List writes=Arrays.asList(fn.readsTemps()); - - for(Iterator tempit=livetemps.iterator();tempit.hasNext();) { - TempDescriptor tmp=tempit.next(); - if (writes.contains(tmp)) { - nodetosavetemps.get(atomicnode).add(tmp); - } else if (reads.contains(tmp)&&temptab.get(fn).get(tmp)==GLOBAL) { - nodetosavetemps.get(atomicnode).add(tmp); - } - } - } - for(int i=0;i"; - else - return "<"+getNode()+","+getTemp()+">"; + TempDescriptor tmp; + FlatNode fn; + + public TempNodePair(TempDescriptor tmp) { + this.tmp=tmp; + } + + public TempDescriptor getTemp() { + return tmp; + } + + public void setNode(FlatNode fn) { + this.fn=fn; + } + + public FlatNode getNode() { + return fn; + } + + public boolean equals(Object o) { + if (o instanceof TempNodePair) { + TempNodePair tnp=(TempNodePair)o; + if (tnp.fn!=null||fn!=null) { + // need to check flat node equivalence also + if (tnp.fn==null||fn==null||(!fn.equals(tnp.fn))) + return false; + } + return tmp.equals(tnp.tmp); } + return false; + } + + public int hashCode() { + return tmp.hashCode(); + } + + public String toString() { + if (getNode()==null) + return ""; + else + return "<"+getNode()+","+getTemp()+">"; + } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/AllocationSite.java b/Robust/src/Analysis/OwnershipAnalysis/AllocationSite.java index c915bbd0..607783b3 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/AllocationSite.java +++ b/Robust/src/Analysis/OwnershipAnalysis/AllocationSite.java @@ -21,90 +21,90 @@ import java.util.*; public class AllocationSite { - static private int uniqueIDcount = 0; + static private int uniqueIDcount = 0; - protected Integer id; - protected int allocationDepth; - protected Vector ithOldest; - protected Integer summary; - protected TypeDescriptor type; + protected Integer id; + protected int allocationDepth; + protected Vector ithOldest; + protected Integer summary; + protected TypeDescriptor type; - public static final int AGE_notInThisSite = -1; - public static final int AGE_oldest = -2; - public static final int AGE_summary = -3; + public static final int AGE_notInThisSite = -1; + public static final int AGE_oldest = -2; + public static final int AGE_summary = -3; - public AllocationSite( int allocationDepth, TypeDescriptor type ) { - assert allocationDepth >= 1; + public AllocationSite(int allocationDepth, TypeDescriptor type) { + assert allocationDepth >= 1; - this.allocationDepth = allocationDepth; - this.type = type; + this.allocationDepth = allocationDepth; + this.type = type; - ithOldest = new Vector( allocationDepth ); - id = generateUniqueAllocationSiteID(); - } + ithOldest = new Vector(allocationDepth); + id = generateUniqueAllocationSiteID(); + } - static public Integer generateUniqueAllocationSiteID() { - ++uniqueIDcount; - return new Integer( uniqueIDcount ); - } + static public Integer generateUniqueAllocationSiteID() { + ++uniqueIDcount; + return new Integer(uniqueIDcount); + } - - public int getAllocationDepth() { - return allocationDepth; - } - public void setIthOldest( int i, Integer id ) { - assert i >= 0; - assert i < allocationDepth; - assert id != null; + public int getAllocationDepth() { + return allocationDepth; + } - ithOldest.add( i, id ); - } + public void setIthOldest(int i, Integer id) { + assert i >= 0; + assert i < allocationDepth; + assert id != null; - public Integer getIthOldest( int i ) { - assert i >= 0; - assert i < allocationDepth; + ithOldest.add(i, id); + } - return ithOldest.get( i ); - } + public Integer getIthOldest(int i) { + assert i >= 0; + assert i < allocationDepth; - public Integer getOldest() { - return ithOldest.get( allocationDepth - 1 ); - } + return ithOldest.get(i); + } - public void setSummary( Integer id ) { - assert id != null; - summary = id; - } + public Integer getOldest() { + return ithOldest.get(allocationDepth - 1); + } - public Integer getSummary() { - return summary; - } + public void setSummary(Integer id) { + assert id != null; + summary = id; + } + + public Integer getSummary() { + return summary; + } + + public TypeDescriptor getType() { + return type; + } - public TypeDescriptor getType() { - return type; + public int getAge(Integer id) { + if( id.equals(summary) ) { + return AGE_summary; } - public int getAge( Integer id ) { - if( id.equals( summary ) ) { - return AGE_summary; - } - - if( id.equals( getOldest() ) ) { - return AGE_oldest; - } - - for( int i = 0; i < allocationDepth - 1; ++i ) { - if( id.equals( ithOldest.get( i ) ) ) { - return i; - } - } - - return AGE_notInThisSite; + if( id.equals(getOldest() ) ) { + return AGE_oldest; } - public String toString() { - return "allocSite" + id; + for( int i = 0; i < allocationDepth - 1; ++i ) { + if( id.equals(ithOldest.get(i) ) ) { + return i; + } } + + return AGE_notInThisSite; + } + + public String toString() { + return "allocSite" + id; + } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/Canonical.java b/Robust/src/Analysis/OwnershipAnalysis/Canonical.java index f2d5901e..c4e2a09a 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/Canonical.java +++ b/Robust/src/Analysis/OwnershipAnalysis/Canonical.java @@ -7,14 +7,14 @@ import java.io.*; public class Canonical { - private static Hashtable canon = new Hashtable(); + private static Hashtable canon = new Hashtable(); - public static Canonical makeCanonical( Canonical c ) { - if( canon.containsKey( c ) ) { - return canon.get( c ); - } - - canon.put( c, c ); - return c; + public static Canonical makeCanonical(Canonical c) { + if( canon.containsKey(c) ) { + return canon.get(c); } + + canon.put(c, c); + return c; + } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/ChangeTuple.java b/Robust/src/Analysis/OwnershipAnalysis/ChangeTuple.java index 93106a34..9b337d22 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/ChangeTuple.java +++ b/Robust/src/Analysis/OwnershipAnalysis/ChangeTuple.java @@ -14,42 +14,46 @@ import java.io.*; public class ChangeTuple extends Canonical { - private TokenTupleSet toMatch; - private TokenTupleSet toAdd; - - public ChangeTuple( TokenTupleSet toMatch, - TokenTupleSet toAdd ) { - this.toMatch = toMatch; - this.toAdd = toAdd; + private TokenTupleSet toMatch; + private TokenTupleSet toAdd; + + public ChangeTuple(TokenTupleSet toMatch, + TokenTupleSet toAdd) { + this.toMatch = toMatch; + this.toAdd = toAdd; + } + + public ChangeTuple makeCanonical() { + return (ChangeTuple) Canonical.makeCanonical(this); + } + + public TokenTupleSet getSetToMatch() { + return toMatch; + } + public TokenTupleSet getSetToAdd() { + return toAdd; + } + + public boolean equals(Object o) { + if( o == null ) { + return false; } - public ChangeTuple makeCanonical() { - return (ChangeTuple) Canonical.makeCanonical( this ); + if( !(o instanceof ChangeTuple) ) { + return false; } - public TokenTupleSet getSetToMatch() { return toMatch; } - public TokenTupleSet getSetToAdd() { return toAdd; } - - public boolean equals( Object o ) { - if( o == null ) { - return false; - } + ChangeTuple ct = (ChangeTuple) o; - if( !(o instanceof ChangeTuple) ) { - return false; - } + return toMatch.equals(ct.getSetToMatch() ) && + toAdd.equals(ct.getSetToAdd() ); + } - ChangeTuple ct = (ChangeTuple) o; - - return toMatch.equals( ct.getSetToMatch() ) && - toAdd.equals( ct.getSetToAdd() ); - } + public int hashCode() { + return toMatch.hashCode() + toAdd.hashCode()*3; + } - public int hashCode() { - return toMatch.hashCode() + toAdd.hashCode()*3; - } - - public String toString() { - return new String( "<"+toMatch+" -> "+toAdd+">" ); - } + public String toString() { + return new String("<"+toMatch+" -> "+toAdd+">"); + } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/ChangeTupleSet.java b/Robust/src/Analysis/OwnershipAnalysis/ChangeTupleSet.java index ee2813dd..9bb1f54c 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/ChangeTupleSet.java +++ b/Robust/src/Analysis/OwnershipAnalysis/ChangeTupleSet.java @@ -8,81 +8,81 @@ import java.io.*; public class ChangeTupleSet extends Canonical { - private HashSet changeTuples; + private HashSet changeTuples; - public ChangeTupleSet() { - changeTuples = new HashSet(); - } + public ChangeTupleSet() { + changeTuples = new HashSet(); + } - public ChangeTupleSet( ChangeTuple ct ) { - this(); - changeTuples.add( ct ); - } + public ChangeTupleSet(ChangeTuple ct) { + this(); + changeTuples.add(ct); + } - public ChangeTupleSet( ChangeTupleSet cts ) { - changeTuples = (HashSet) cts.changeTuples.clone(); - } + public ChangeTupleSet(ChangeTupleSet cts) { + changeTuples = (HashSet)cts.changeTuples.clone(); + } - public ChangeTupleSet makeCanonical() { - return (ChangeTupleSet) Canonical.makeCanonical( this ); - } + public ChangeTupleSet makeCanonical() { + return (ChangeTupleSet) Canonical.makeCanonical(this); + } - public Iterator iterator() { - return changeTuples.iterator(); - } + public Iterator iterator() { + return changeTuples.iterator(); + } - public ChangeTupleSet union( ChangeTupleSet ctsIn ) { - assert ctsIn != null; + public ChangeTupleSet union(ChangeTupleSet ctsIn) { + assert ctsIn != null; - ChangeTupleSet ctsOut = new ChangeTupleSet( this ); - ctsOut.changeTuples.addAll( ctsIn.changeTuples ); - return ctsOut.makeCanonical(); - } + ChangeTupleSet ctsOut = new ChangeTupleSet(this); + ctsOut.changeTuples.addAll(ctsIn.changeTuples); + return ctsOut.makeCanonical(); + } - public ChangeTupleSet union( ChangeTuple ctIn ) { - assert ctIn != null; + public ChangeTupleSet union(ChangeTuple ctIn) { + assert ctIn != null; - ChangeTupleSet ctsOut = new ChangeTupleSet( this ); - ctsOut.changeTuples.add( ctIn ); - return ctsOut.makeCanonical(); - } + ChangeTupleSet ctsOut = new ChangeTupleSet(this); + ctsOut.changeTuples.add(ctIn); + return ctsOut.makeCanonical(); + } - public boolean isEmpty() { - return changeTuples.isEmpty(); - } - - public boolean isSubset( ChangeTupleSet ctsIn ) { - assert ctsIn != null; - return ctsIn.changeTuples.containsAll( this.changeTuples ); - } + public boolean isEmpty() { + return changeTuples.isEmpty(); + } - public boolean equals( Object o ) { - if( o == null ) { - return false; - } + public boolean isSubset(ChangeTupleSet ctsIn) { + assert ctsIn != null; + return ctsIn.changeTuples.containsAll(this.changeTuples); + } - if( !(o instanceof ChangeTupleSet) ) { - return false; - } - - ChangeTupleSet cts = (ChangeTupleSet) o; - return changeTuples.equals( cts.changeTuples ); + public boolean equals(Object o) { + if( o == null ) { + return false; } - public int hashCode() { - return changeTuples.hashCode(); + if( !(o instanceof ChangeTupleSet) ) { + return false; } - public String toString() { - String s = "["; + ChangeTupleSet cts = (ChangeTupleSet) o; + return changeTuples.equals(cts.changeTuples); + } - Iterator i = this.iterator(); - while( i.hasNext() ) { - s += "\n "+i.next(); - } + public int hashCode() { + return changeTuples.hashCode(); + } - s += "\n]"; + public String toString() { + String s = "["; - return s; + Iterator i = this.iterator(); + while( i.hasNext() ) { + s += "\n "+i.next(); } + + s += "\n]"; + + return s; + } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/HeapRegionNode.java b/Robust/src/Analysis/OwnershipAnalysis/HeapRegionNode.java index 2604b21f..04778154 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/HeapRegionNode.java +++ b/Robust/src/Analysis/OwnershipAnalysis/HeapRegionNode.java @@ -6,195 +6,195 @@ import java.util.*; public class HeapRegionNode extends OwnershipNode { - protected Integer id; + protected Integer id; - protected boolean isSingleObject; - protected boolean isFlagged; - protected boolean isNewSummary; + protected boolean isSingleObject; + protected boolean isFlagged; + protected boolean isNewSummary; - protected HashSet referencers; + protected HashSet referencers; - protected AllocationSite allocSite; + protected AllocationSite allocSite; - protected ReachabilitySet alpha; - protected ReachabilitySet alphaNew; + protected ReachabilitySet alpha; + protected ReachabilitySet alphaNew; - protected String description; + protected String description; - public HeapRegionNode( Integer id, - boolean isSingleObject, - boolean isFlagged, - boolean isNewSummary, - AllocationSite allocSite, - ReachabilitySet alpha, - String description ) { - this.id = id; - this.isSingleObject = isSingleObject; - this.isFlagged = isFlagged; - this.isNewSummary = isNewSummary; - this.allocSite = allocSite; - this.alpha = alpha; - this.description = description; - - referencers = new HashSet(); - alphaNew = new ReachabilitySet().makeCanonical(); - } - - public HeapRegionNode copy() { - return new HeapRegionNode( id, - isSingleObject, - isFlagged, - isNewSummary, - allocSite, - alpha, - description ); - } + public HeapRegionNode(Integer id, + boolean isSingleObject, + boolean isFlagged, + boolean isNewSummary, + AllocationSite allocSite, + ReachabilitySet alpha, + String description) { + this.id = id; + this.isSingleObject = isSingleObject; + this.isFlagged = isFlagged; + this.isNewSummary = isNewSummary; + this.allocSite = allocSite; + this.alpha = alpha; + this.description = description; + referencers = new HashSet(); + alphaNew = new ReachabilitySet().makeCanonical(); + } - public Integer getID() { - return id; - } + public HeapRegionNode copy() { + return new HeapRegionNode(id, + isSingleObject, + isFlagged, + isNewSummary, + allocSite, + alpha, + description); + } - public boolean equalsIncludingAlpha( HeapRegionNode hrn ) { - return equals( hrn ) && alpha.equals( hrn.alpha ); - } + public Integer getID() { + return id; + } - public boolean equals( Object o ) { - if( o == null ) { - return false; - } + public boolean equalsIncludingAlpha(HeapRegionNode hrn) { + return equals(hrn) && alpha.equals(hrn.alpha); + } - if( !( o instanceof HeapRegionNode) ) { - return false; - } - HeapRegionNode hrn = (HeapRegionNode) o; + public boolean equals(Object o) { + if( o == null ) { + return false; + } - if( !id.equals( hrn.getID() ) ) { - return false; - } + if( !( o instanceof HeapRegionNode) ) { + return false; + } - assert isSingleObject == hrn.isSingleObject(); - assert isFlagged == hrn.isFlagged(); - assert isNewSummary == hrn.isNewSummary(); - assert description.equals( hrn.getDescription() ); + HeapRegionNode hrn = (HeapRegionNode) o; - return true; + if( !id.equals(hrn.getID() ) ) { + return false; } - public int hashCode() { - return id.intValue()*17; - } + assert isSingleObject == hrn.isSingleObject(); + assert isFlagged == hrn.isFlagged(); + assert isNewSummary == hrn.isNewSummary(); + assert description.equals(hrn.getDescription() ); + return true; + } - public boolean isSingleObject() { - return isSingleObject; - } + public int hashCode() { + return id.intValue()*17; + } - public boolean isFlagged() { - return isFlagged; - } - public boolean isNewSummary() { - return isNewSummary; - } + public boolean isSingleObject() { + return isSingleObject; + } + public boolean isFlagged() { + return isFlagged; + } + public boolean isNewSummary() { + return isNewSummary; + } - public Iterator iteratorToReferencers() { - return referencers.iterator(); - } - public Iterator iteratorToReferencersClone() { - HashSet clone = (HashSet) referencers.clone(); - return clone.iterator(); - } - public int getNumReferencers() { - return referencers.size(); - } + public Iterator iteratorToReferencers() { + return referencers.iterator(); + } + public Iterator iteratorToReferencersClone() { + HashSet clone = (HashSet)referencers.clone(); + return clone.iterator(); + } - public void addReferencer( ReferenceEdge edge ) { - assert edge != null; + public int getNumReferencers() { + return referencers.size(); + } - referencers.add( edge ); - } - public void removeReferencer( ReferenceEdge edge ) { - assert edge != null; - assert referencers.contains( edge ); + public void addReferencer(ReferenceEdge edge) { + assert edge != null; - referencers.remove( edge ); - } + referencers.add(edge); + } - public ReferenceEdge getReferenceFrom( OwnershipNode on, - FieldDescriptor fd ) { - assert on != null; + public void removeReferencer(ReferenceEdge edge) { + assert edge != null; + assert referencers.contains(edge); - Iterator itrEdge = referencers.iterator(); - while( itrEdge.hasNext() ) { - ReferenceEdge edge = itrEdge.next(); - if( edge.getSrc().equals( on ) && - edge.getFieldDesc() == fd ) { - return edge; - } - } + referencers.remove(edge); + } - return null; + public ReferenceEdge getReferenceFrom(OwnershipNode on, + FieldDescriptor fd) { + assert on != null; + + Iterator itrEdge = referencers.iterator(); + while( itrEdge.hasNext() ) { + ReferenceEdge edge = itrEdge.next(); + if( edge.getSrc().equals(on) && + edge.getFieldDesc() == fd ) { + return edge; + } } + return null; + } - public AllocationSite getAllocationSite() { - return allocSite; - } + public AllocationSite getAllocationSite() { + return allocSite; + } - public void setAlpha( ReachabilitySet alpha ) { - this.alpha = alpha; - } - public ReachabilitySet getAlpha() { - return alpha; - } + public void setAlpha(ReachabilitySet alpha) { + this.alpha = alpha; + } - public ReachabilitySet getAlphaNew() { - return alphaNew; - } + public ReachabilitySet getAlpha() { + return alpha; + } - public void setAlphaNew( ReachabilitySet alpha ) { - this.alphaNew = alpha; - } + public ReachabilitySet getAlphaNew() { + return alphaNew; + } - public void applyAlphaNew() { - assert alphaNew != null; + public void setAlphaNew(ReachabilitySet alpha) { + this.alphaNew = alpha; + } - alpha = alphaNew; + public void applyAlphaNew() { + assert alphaNew != null; - alphaNew = new ReachabilitySet(); - alphaNew = alphaNew.makeCanonical(); - } + alpha = alphaNew; + alphaNew = new ReachabilitySet(); + alphaNew = alphaNew.makeCanonical(); + } - public String getIDString() { - return id.toString(); - } - public String getAlphaString() { - return alpha.toStringEscapeNewline(); - } + public String getIDString() { + return id.toString(); + } - public String toString() { - return "HRN"+getIDString(); - } + public String getAlphaString() { + return alpha.toStringEscapeNewline(); + } - // WHY WHY WHY WHY WHY WHY?! - public String getDescription() { - return new String( description ); - //return new String( description+" ID "+getIDString() ); - } + public String toString() { + return "HRN"+getIDString(); + } + + // WHY WHY WHY WHY WHY WHY?! + public String getDescription() { + return new String(description); + //return new String( description+" ID "+getIDString() ); + } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/LabelNode.java b/Robust/src/Analysis/OwnershipAnalysis/LabelNode.java index 5633ee2d..f4f6560f 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/LabelNode.java +++ b/Robust/src/Analysis/OwnershipAnalysis/LabelNode.java @@ -5,39 +5,39 @@ import IR.Flat.*; import java.util.*; public class LabelNode extends OwnershipNode { - protected TempDescriptor td; + protected TempDescriptor td; - public LabelNode( TempDescriptor td ) { - this.td = td; - } + public LabelNode(TempDescriptor td) { + this.td = td; + } - public TempDescriptor getTempDescriptor() { - return td; - } + public TempDescriptor getTempDescriptor() { + return td; + } - public boolean equals( Object o ) { - if( o == null ) { - return false; - } + public boolean equals(Object o) { + if( o == null ) { + return false; + } - if( !( o instanceof LabelNode) ) { - return false; - } + if( !( o instanceof LabelNode) ) { + return false; + } - LabelNode ln = (LabelNode) o; + LabelNode ln = (LabelNode) o; - return td == ln.getTempDescriptor(); - } + return td == ln.getTempDescriptor(); + } - public int hashCode() { - return td.getNum(); - } + public int hashCode() { + return td.getNum(); + } - public String getTempDescriptorString() { - return td.toString(); - } + public String getTempDescriptorString() { + return td.toString(); + } - public String toString() { - return "LN_"+getTempDescriptorString(); - } + public String toString() { + return "LN_"+getTempDescriptorString(); + } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/OwnershipAnalysis.java b/Robust/src/Analysis/OwnershipAnalysis/OwnershipAnalysis.java index 24b3912b..4e7be31b 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/OwnershipAnalysis.java +++ b/Robust/src/Analysis/OwnershipAnalysis/OwnershipAnalysis.java @@ -9,770 +9,770 @@ import java.io.*; public class OwnershipAnalysis { - /////////////////////////////////////////// - // - // Public interface to discover possible - // aliases in the program under analysis - // - /////////////////////////////////////////// + /////////////////////////////////////////// + // + // Public interface to discover possible + // aliases in the program under analysis + // + /////////////////////////////////////////// + /* + public HashSet + getFlaggedAllocationSitesReachableFromTask( TaskDescriptor td ) { + + return getFlaggedAllocationSitesReachableFromTaskPRIVATE( td ); + } + + public AllocationSite getAllocationSiteFromFlatNew( FlatNew fn ) { + return getAllocationSiteFromFlatNewPRIVATE( fn ); + } + + public boolean createsPotentialAliases( Descriptor taskOrMethod, + int paramIndex1, + int paramIndex2 ) { + + OwnershipGraph og = mapDescriptorToCompleteOwnershipGraph.get( taskOrMethod ); + assert( og != null ); + + return createsPotentialAliases( og, + getHeapRegionIDset( og, paramIndex1 ), + getHeapRegionIDset( og, paramIndex2 ) ); + } + + public boolean createsPotentialAliases( Descriptor taskOrMethod, + int paramIndex, + AllocationSite alloc ) { + + OwnershipGraph og = mapDescriptorToCompleteOwnershipGraph.get( taskOrMethod ); + assert( og != null ); + + return createsPotentialAliases( og, + getHeapRegionIDset( og, paramIndex ), + getHeapRegionIDset( alloc ) ); + } + + public boolean createsPotentialAliases( Descriptor taskOrMethod, + AllocationSite alloc, + int paramIndex ) { + + OwnershipGraph og = mapDescriptorToCompleteOwnershipGraph.get( taskOrMethod ); + assert( og != null ); + + return createsPotentialAliases( og, + getHeapRegionIDset( og, paramIndex ), + getHeapRegionIDset( alloc ) ); + } + + public boolean createsPotentialAliases( Descriptor taskOrMethod, + AllocationSite alloc1, + AllocationSite alloc2 ) { + + OwnershipGraph og = mapDescriptorToCompleteOwnershipGraph.get( taskOrMethod ); + assert( og != null ); + + return createsPotentialAliases( og, + getHeapRegionIDset( alloc1 ), + getHeapRegionIDset( alloc2 ) ); + } + + public boolean createsPotentialAliases( Descriptor taskOrMethod, + AllocationSite alloc, + HashSet allocSet ) { + + OwnershipGraph og = mapDescriptorToCompleteOwnershipGraph.get( taskOrMethod ); + assert( og != null ); + + return createsPotentialAliases( og, + getHeapRegionIDset( alloc ), + getHeapRegionIDset( allocSet ) ); + } + */ + + // use the methods given above to check every possible alias + // between task parameters and flagged allocation sites reachable + // from the task + public void writeAllAliases(String outputFile) throws java.io.IOException { + + BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile) ); /* - public HashSet - getFlaggedAllocationSitesReachableFromTask( TaskDescriptor td ) { + // look through every task for potential aliases + Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator(); + while( taskItr.hasNext() ) { + TaskDescriptor td = (TaskDescriptor) taskItr.next(); + + HashSet allocSites = getFlaggedAllocationSitesReachableFromTask( td ); + + // for each task parameter, check for aliases with + // other task parameters and every allocation site + // reachable from this task + 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 ) { + if( createsPotentialAliases( td, i, j ) ) { + bw.write( "Task "+td+" potentially aliases parameters "+i+" and "+j+".\n" ); + } + } + + // 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(); + if( createsPotentialAliases( td, i, as ) ) { + bw.write( "Task "+td+" potentially aliases parameter "+i+" and "+as+".\n" ); + } + } + } + + // for each allocation site check for aliases with + // other allocation sites in the context of execution + // of this task + Iterator allocItr = allocSites.iterator(); + while( allocItr.hasNext() ) { + AllocationSite as = (AllocationSite) allocItr.next(); + if( createsPotentialAliases( td, as, allocSites ) ) { + bw.write( "Task "+td+" potentially aliases "+as+" and the rest of the set.\n" ); + } + } + } + + bw.close(); + */ + } + + /////////////////////////////////////////// + // + // end public interface + // + /////////////////////////////////////////// + + + + + + + + + // data from the compiler + private State state; + private CallGraph callGraph; + private int allocationDepth; + + // used to identify HeapRegionNode objects + // A unique ID equates an object in one + // ownership graph with an object in another + // graph that logically represents the same + // heap region + static private int uniqueIDcount = 0; + + + // Use these data structures to track progress of + // processing all methods in the program, and by methods + // TaskDescriptor and MethodDescriptor are combined + // together, with a common parent class Descriptor + private HashSet descriptorsToVisit; + private Hashtable mapDescriptorToCompleteOwnershipGraph; + private Hashtable mapFlatNewToAllocationSite; + private Hashtable > mapDescriptorToAllocationSiteSet; + + // Use these data structures to track progress of one pass of + // processing the FlatNodes of a particular method + private HashSet flatNodesToVisit; + private Hashtable mapFlatNodeToOwnershipGraph; + private HashSet returnNodesToCombineForCompleteOwnershipGraph; + + + // this analysis generates an ownership graph for every task + // in the program + public OwnershipAnalysis(State state, + CallGraph callGraph, + int allocationDepth) throws java.io.IOException { + this.state = state; + this.callGraph = callGraph; + this.allocationDepth = allocationDepth; + + // temporary for debugging + this.allocationDepth = 1; + + descriptorsToVisit = new HashSet(); + + mapDescriptorToCompleteOwnershipGraph = + new Hashtable(); + + mapFlatNewToAllocationSite = + new Hashtable(); + + mapDescriptorToAllocationSiteSet = + new Hashtable >(); + + // use this set to prevent infinite recursion when + // traversing the call graph + HashSet calleesScheduled = new HashSet(); + - return getFlaggedAllocationSitesReachableFromTaskPRIVATE( td ); - } + // initialize methods to visit as the set of all tasks in the + // program and then any method that could be called starting + // from those tasks + Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator(); + while( taskItr.hasNext() ) { + Descriptor d = (Descriptor) taskItr.next(); + descriptorsToVisit.add(d); - public AllocationSite getAllocationSiteFromFlatNew( FlatNew fn ) { - return getAllocationSiteFromFlatNewPRIVATE( fn ); + // recursively find all callees from this task + scheduleAllCallees(calleesScheduled, d); } - public boolean createsPotentialAliases( Descriptor taskOrMethod, - int paramIndex1, - int paramIndex2 ) { - - OwnershipGraph og = mapDescriptorToCompleteOwnershipGraph.get( taskOrMethod ); - assert( og != null ); + // before beginning analysis, initialize every scheduled method + // with an ownership graph that has populated parameter index tables + // by analyzing the first node which is always a FlatMethod node + Iterator dItr = calleesScheduled.iterator(); + while( dItr.hasNext() ) { + Descriptor d = dItr.next(); + OwnershipGraph og = new OwnershipGraph(allocationDepth); + + FlatMethod fm; + if( d instanceof MethodDescriptor ) { + fm = state.getMethodFlat( (MethodDescriptor) d); + } else { + assert d instanceof TaskDescriptor; + fm = state.getMethodFlat( (TaskDescriptor) d); + } + + analyzeFlatNode(d, fm, null, og); + mapDescriptorToCompleteOwnershipGraph.put(d, og); + } - return createsPotentialAliases( og, - getHeapRegionIDset( og, paramIndex1 ), - getHeapRegionIDset( og, paramIndex2 ) ); + // as mentioned above, analyze methods one-by-one, possibly revisiting + // a method if the methods that it calls are updated + analyzeMethods(); + } + + // called from the constructor to help initialize the set + // of methods that needs to be analyzed by ownership analysis + private void scheduleAllCallees(HashSet calleesScheduled, + Descriptor d) { + if( calleesScheduled.contains(d) ) { + return; } + calleesScheduled.add(d); - public boolean createsPotentialAliases( Descriptor taskOrMethod, - int paramIndex, - AllocationSite alloc ) { + Set callees = callGraph.getCalleeSet(d); + if( callees == null ) { + return; + } - OwnershipGraph og = mapDescriptorToCompleteOwnershipGraph.get( taskOrMethod ); - assert( og != null ); + Iterator methItr = callees.iterator(); + while( methItr.hasNext() ) { + MethodDescriptor md = (MethodDescriptor) methItr.next(); + descriptorsToVisit.add(md); - return createsPotentialAliases( og, - getHeapRegionIDset( og, paramIndex ), - getHeapRegionIDset( alloc ) ); + // recursively find all callees from this task + scheduleAllCallees(calleesScheduled, md); } + } - public boolean createsPotentialAliases( Descriptor taskOrMethod, - AllocationSite alloc, - int paramIndex ) { - OwnershipGraph og = mapDescriptorToCompleteOwnershipGraph.get( taskOrMethod ); - assert( og != null ); + // manage the set of tasks and methods to be analyzed + // and be sure to reschedule tasks/methods when the methods + // they call are updated + private void analyzeMethods() throws java.io.IOException { - return createsPotentialAliases( og, - getHeapRegionIDset( og, paramIndex ), - getHeapRegionIDset( alloc ) ); - } - - public boolean createsPotentialAliases( Descriptor taskOrMethod, - AllocationSite alloc1, - AllocationSite alloc2 ) { + while( !descriptorsToVisit.isEmpty() ) { + Descriptor d = (Descriptor) descriptorsToVisit.iterator().next(); + descriptorsToVisit.remove(d); - OwnershipGraph og = mapDescriptorToCompleteOwnershipGraph.get( taskOrMethod ); - assert( og != null ); + // because the task or method descriptor just extracted + // was in the "to visit" set it either hasn't been analyzed + // yet, or some method that it depends on has been + // updated. Recompute a complete ownership graph for + // this task/method and compare it to any previous result. + // If there is a change detected, add any methods/tasks + // that depend on this one to the "to visit" set. - return createsPotentialAliases( og, - getHeapRegionIDset( alloc1 ), - getHeapRegionIDset( alloc2 ) ); - } + System.out.println("Analyzing " + d); - public boolean createsPotentialAliases( Descriptor taskOrMethod, - AllocationSite alloc, - HashSet allocSet ) { + FlatMethod fm; + if( d instanceof MethodDescriptor ) { + fm = state.getMethodFlat( (MethodDescriptor) d); + } else { + assert d instanceof TaskDescriptor; + fm = state.getMethodFlat( (TaskDescriptor) d); + } - OwnershipGraph og = mapDescriptorToCompleteOwnershipGraph.get( taskOrMethod ); - assert( og != null ); + OwnershipGraph og = analyzeFlatMethod(d, fm); + OwnershipGraph ogPrev = mapDescriptorToCompleteOwnershipGraph.get(d); + if( !og.equals(ogPrev) ) { + mapDescriptorToCompleteOwnershipGraph.put(d, og); - return createsPotentialAliases( og, - getHeapRegionIDset( alloc ), - getHeapRegionIDset( allocSet ) ); - } - */ - - // use the methods given above to check every possible alias - // between task parameters and flagged allocation sites reachable - // from the task - public void writeAllAliases( String outputFile ) throws java.io.IOException { - - BufferedWriter bw = new BufferedWriter( new FileWriter( outputFile ) ); /* - // look through every task for potential aliases - Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator(); - while( taskItr.hasNext() ) { - TaskDescriptor td = (TaskDescriptor) taskItr.next(); - - HashSet allocSites = getFlaggedAllocationSitesReachableFromTask( td ); - - // for each task parameter, check for aliases with - // other task parameters and every allocation site - // reachable from this task - 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 ) { - if( createsPotentialAliases( td, i, j ) ) { - bw.write( "Task "+td+" potentially aliases parameters "+i+" and "+j+".\n" ); - } - } - - // 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(); - if( createsPotentialAliases( td, i, as ) ) { - bw.write( "Task "+td+" potentially aliases parameter "+i+" and "+as+".\n" ); - } - } - } - - // for each allocation site check for aliases with - // other allocation sites in the context of execution - // of this task - Iterator allocItr = allocSites.iterator(); - while( allocItr.hasNext() ) { - AllocationSite as = (AllocationSite) allocItr.next(); - if( createsPotentialAliases( td, as, allocSites ) ) { - bw.write( "Task "+td+" potentially aliases "+as+" and the rest of the set.\n" ); - } - } + boolean writeLabels, + boolean labelSelect, + boolean pruneGarbage, + boolean writeReferencers + */ + og.writeGraph(d, true, true, true, false); + + // only methods have dependents, tasks cannot + // be invoked by any user program calls + if( d instanceof MethodDescriptor ) { + MethodDescriptor md = (MethodDescriptor) d; + Set dependents = callGraph.getCallerSet(md); + if( dependents != null ) { + descriptorsToVisit.addAll(dependents); + } } - - bw.close(); - */ + } } - - /////////////////////////////////////////// - // - // end public interface - // - /////////////////////////////////////////// + } + int x = 0; + // keep passing the Descriptor of the method along for debugging + // and dot file writing + private OwnershipGraph + analyzeFlatMethod(Descriptor mDesc, + FlatMethod flatm) throws java.io.IOException { + // initialize flat nodes to visit as the flat method + // because all other nodes in this flat method are + // decendents of the flat method itself + flatNodesToVisit = new HashSet(); + flatNodesToVisit.add(flatm); - - // data from the compiler - private State state; - private CallGraph callGraph; - private int allocationDepth; + // initilize the mapping of flat nodes in this flat method to + // ownership graph results to an empty mapping + mapFlatNodeToOwnershipGraph = new Hashtable(); - // used to identify HeapRegionNode objects - // A unique ID equates an object in one - // ownership graph with an object in another - // graph that logically represents the same - // heap region - static private int uniqueIDcount = 0; + // initialize the set of return nodes that will be combined as + // the final ownership graph result to return as an empty set + returnNodesToCombineForCompleteOwnershipGraph = new HashSet(); + while( !flatNodesToVisit.isEmpty() ) { + FlatNode fn = (FlatNode) flatNodesToVisit.iterator().next(); + flatNodesToVisit.remove(fn); - // Use these data structures to track progress of - // processing all methods in the program, and by methods - // TaskDescriptor and MethodDescriptor are combined - // together, with a common parent class Descriptor - private HashSet descriptorsToVisit; - private Hashtable mapDescriptorToCompleteOwnershipGraph; - private Hashtable mapFlatNewToAllocationSite; - private Hashtable > mapDescriptorToAllocationSiteSet; + // perform this node's contributions to the ownership + // graph on a new copy, then compare it to the old graph + // at this node to see if anything was updated. + OwnershipGraph og = new OwnershipGraph(allocationDepth); - // Use these data structures to track progress of one pass of - // processing the FlatNodes of a particular method - private HashSet flatNodesToVisit; - private Hashtable mapFlatNodeToOwnershipGraph; - private HashSet returnNodesToCombineForCompleteOwnershipGraph; + // start by merging all node's parents' graphs + for( int i = 0; i < fn.numPrev(); ++i ) { + FlatNode pn = fn.getPrev(i); + OwnershipGraph ogParent = getGraphFromFlatNode(pn); + og.merge(ogParent); + } + // apply the analysis of the flat node to the + // ownership graph made from the merge of the + // parent graphs + analyzeFlatNode(mDesc, + fn, + returnNodesToCombineForCompleteOwnershipGraph, + og); - // this analysis generates an ownership graph for every task - // in the program - public OwnershipAnalysis( State state, - CallGraph callGraph, - int allocationDepth ) throws java.io.IOException { - this.state = state; - this.callGraph = callGraph; - this.allocationDepth = allocationDepth; + // if the results of the new graph are different from + // the current graph at this node, replace the graph + // with the update and enqueue the children for + // processing + OwnershipGraph ogPrev = getGraphFromFlatNode(fn); - // temporary for debugging - this.allocationDepth = 1; + if( !og.equals(ogPrev) ) { + setGraphForFlatNode(fn, og); - descriptorsToVisit = new HashSet(); - mapDescriptorToCompleteOwnershipGraph = - new Hashtable(); - mapFlatNewToAllocationSite = - new Hashtable(); + x++; + if( x > 0 ) { + String s = String.format("debug%04d", x); + //og.writeGraph( s, true, true, true, false ); + } - mapDescriptorToAllocationSiteSet = - new Hashtable >(); - // use this set to prevent infinite recursion when - // traversing the call graph - HashSet calleesScheduled = new HashSet(); + for( int i = 0; i < fn.numNext(); i++ ) { + FlatNode nn = fn.getNext(i); + flatNodesToVisit.add(nn); + } + } + } - // initialize methods to visit as the set of all tasks in the - // program and then any method that could be called starting - // from those tasks - Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator(); - while( taskItr.hasNext() ) { - Descriptor d = (Descriptor) taskItr.next(); - descriptorsToVisit.add( d ); + // end by merging all return nodes into a complete + // ownership graph that represents all possible heap + // states after the flat method returns + OwnershipGraph completeGraph = new OwnershipGraph(allocationDepth); + Iterator retItr = returnNodesToCombineForCompleteOwnershipGraph.iterator(); + while( retItr.hasNext() ) { + FlatReturnNode frn = (FlatReturnNode) retItr.next(); + OwnershipGraph ogr = getGraphFromFlatNode(frn); + completeGraph.merge(ogr); + } + return completeGraph; + } + + + private void + analyzeFlatNode(Descriptor methodDesc, + FlatNode fn, + HashSet setRetNodes, + OwnershipGraph og) throws java.io.IOException { + + TempDescriptor src; + TempDescriptor dst; + FieldDescriptor fld; + + // use node type to decide what alterations to make + // to the ownership graph + switch( fn.kind() ) { + + case FKind.FlatMethod: + FlatMethod fm = (FlatMethod) fn; + + // there should only be one FlatMethod node as the + // parent of all other FlatNode objects, so take + // the opportunity to construct the initial graph by + // adding parameters labels to new heap regions + for( int i = 0; i < fm.numParameters(); ++i ) { + TempDescriptor tdParam = fm.getParameter(i); + og.assignParameterAllocationToTemp(methodDesc instanceof TaskDescriptor, + tdParam, + new Integer(i) ); + } + + break; + + case FKind.FlatOpNode: + FlatOpNode fon = (FlatOpNode) fn; + if( fon.getOp().getOp() == Operation.ASSIGN ) { + src = fon.getLeft(); + dst = fon.getDest(); + og.assignTempYToTempX(src, dst); + } + break; + + case FKind.FlatFieldNode: + FlatFieldNode ffn = (FlatFieldNode) fn; + src = ffn.getSrc(); + dst = ffn.getDst(); + fld = ffn.getField(); + if( !fld.getType().isPrimitive() ) { + og.assignTempYFieldFToTempX(src, fld, dst); + } + break; + + case FKind.FlatSetFieldNode: + FlatSetFieldNode fsfn = (FlatSetFieldNode) fn; + src = fsfn.getSrc(); + dst = fsfn.getDst(); + fld = fsfn.getField(); + og.assignTempYToTempXFieldF(src, dst, fld); + break; + + case FKind.FlatNew: + FlatNew fnn = (FlatNew) fn; + dst = fnn.getDst(); + AllocationSite as = getAllocationSiteFromFlatNewPRIVATE(fnn); + + og.assignNewAllocationToTempX(dst, as); + break; + + case FKind.FlatCall: + FlatCall fc = (FlatCall) fn; + MethodDescriptor md = fc.getMethod(); + FlatMethod flatm = state.getMethodFlat(md); + //HashSet allocSiteSet = getAllocationSiteSet( md ); + OwnershipGraph ogAllPossibleCallees = new OwnershipGraph(allocationDepth); + + if( md.isStatic() ) { + // a static method is simply always the same, makes life easy + OwnershipGraph onlyPossibleCallee = mapDescriptorToCompleteOwnershipGraph.get(md); + ogAllPossibleCallees.merge(onlyPossibleCallee); - // recursively find all callees from this task - scheduleAllCallees( calleesScheduled, d ); - } - - // before beginning analysis, initialize every scheduled method - // with an ownership graph that has populated parameter index tables - // by analyzing the first node which is always a FlatMethod node - Iterator dItr = calleesScheduled.iterator(); - while( dItr.hasNext() ) { - Descriptor d = dItr.next(); - OwnershipGraph og = new OwnershipGraph( allocationDepth ); - - FlatMethod fm; - if( d instanceof MethodDescriptor ) { - fm = state.getMethodFlat( (MethodDescriptor) d ); - } else { - assert d instanceof TaskDescriptor; - fm = state.getMethodFlat( (TaskDescriptor) d ); - } - - analyzeFlatNode( d, fm, null, og ); - mapDescriptorToCompleteOwnershipGraph.put( d, og ); + /* + if( onlyPossibleCallee != null ) { + onlyPossibleCallee.writeGraph( "only", false, false ); + System.out.println( "There was only one possible callee, "+md ); + } + */ + + } 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 graphs together + TypeDescriptor typeDesc = fc.getThis().getType(); + Set possibleCallees = callGraph.getMethods(md, typeDesc); + + //int j = 0; + + Iterator i = possibleCallees.iterator(); + while( i.hasNext() ) { + MethodDescriptor possibleMd = (MethodDescriptor) i.next(); + //allocSiteSet.addAll( getAllocationSiteSet( possibleMd ) ); + OwnershipGraph ogPotentialCallee = mapDescriptorToCompleteOwnershipGraph.get(possibleMd); + + /* + if( ogPotentialCallee != null ) { + ogPotentialCallee.writeGraph( "potential"+j, false, false ); + ++j; + } + */ + + ogAllPossibleCallees.merge(ogPotentialCallee); } - // as mentioned above, analyze methods one-by-one, possibly revisiting - // a method if the methods that it calls are updated - analyzeMethods(); + //System.out.println( "There were "+j+" potential callees merged together." ); + } + + //System.out.println( "AllocationSiteSet has "+allocSiteSet.size()+" items." ); + + // now we should have the following information to resolve this method call: + // + // 1. A FlatCall fc to query for the caller's context (argument labels, etc) + // + // 2. Whether the method is static; if not we need to deal with the "this" pointer + // + // ******************************************************************************************* + // 3. The original FlatMethod flatm to query for callee's context (paramter labels) + // NOTE! I assume FlatMethod before virtual dispatch accurately describes all possible methods! + // ******************************************************************************************* + // + // 4. The OwnershipGraph ogAllPossibleCallees is a merge of every ownership graph of all the possible + // methods to capture any possible references made. + // + // 5. The Set of AllocationSite objects, allocSiteSet that is the set of allocation sites from + // every possible method we might have chosen + // + og.resolveMethodCall(fc, md.isStatic(), flatm, ogAllPossibleCallees); + break; + + case FKind.FlatReturnNode: + FlatReturnNode frn = (FlatReturnNode) fn; + setRetNodes.add(frn); + break; } + } - // called from the constructor to help initialize the set - // of methods that needs to be analyzed by ownership analysis - private void scheduleAllCallees( HashSet calleesScheduled, - Descriptor d ) { - if( calleesScheduled.contains( d ) ) { - return; - } - calleesScheduled.add( d ); - Set callees = callGraph.getCalleeSet( d ); - if( callees == null ) { - return; - } + // this method should generate integers strictly greater than zero! + // special "shadow" regions are made from a heap region by negating + // the ID + static public Integer generateUniqueHeapRegionNodeID() { + ++uniqueIDcount; + return new Integer(uniqueIDcount); + } - Iterator methItr = callees.iterator(); - while( methItr.hasNext() ) { - MethodDescriptor md = (MethodDescriptor) methItr.next(); - descriptorsToVisit.add( md ); - // recursively find all callees from this task - scheduleAllCallees( calleesScheduled, md ); - } + private OwnershipGraph getGraphFromFlatNode(FlatNode fn) { + if( !mapFlatNodeToOwnershipGraph.containsKey(fn) ) { + mapFlatNodeToOwnershipGraph.put(fn, new OwnershipGraph(allocationDepth) ); } + return mapFlatNodeToOwnershipGraph.get(fn); + } - // manage the set of tasks and methods to be analyzed - // and be sure to reschedule tasks/methods when the methods - // they call are updated - private void analyzeMethods() throws java.io.IOException { - - while( !descriptorsToVisit.isEmpty() ) { - Descriptor d = (Descriptor) descriptorsToVisit.iterator().next(); - descriptorsToVisit.remove( d ); - - // because the task or method descriptor just extracted - // was in the "to visit" set it either hasn't been analyzed - // yet, or some method that it depends on has been - // updated. Recompute a complete ownership graph for - // this task/method and compare it to any previous result. - // If there is a change detected, add any methods/tasks - // that depend on this one to the "to visit" set. - - System.out.println( "Analyzing " + d ); - - FlatMethod fm; - if( d instanceof MethodDescriptor ) { - fm = state.getMethodFlat( (MethodDescriptor) d ); - } else { - assert d instanceof TaskDescriptor; - fm = state.getMethodFlat( (TaskDescriptor) d ); - } - - OwnershipGraph og = analyzeFlatMethod( d, fm ); - OwnershipGraph ogPrev = mapDescriptorToCompleteOwnershipGraph.get( d ); - if( !og.equals( ogPrev ) ) { - mapDescriptorToCompleteOwnershipGraph.put( d, og ); - - /* - boolean writeLabels, - boolean labelSelect, - boolean pruneGarbage, - boolean writeReferencers - */ - og.writeGraph( d, true, true, true, false ); - - // only methods have dependents, tasks cannot - // be invoked by any user program calls - if( d instanceof MethodDescriptor ) { - MethodDescriptor md = (MethodDescriptor) d; - Set dependents = callGraph.getCallerSet( md ); - if( dependents != null ) { - descriptorsToVisit.addAll( dependents ); - } - } - } - } + private void setGraphForFlatNode(FlatNode fn, OwnershipGraph og) { + mapFlatNodeToOwnershipGraph.put(fn, og); + } - } - int x = 0; - - - // keep passing the Descriptor of the method along for debugging - // and dot file writing - private OwnershipGraph - analyzeFlatMethod( Descriptor mDesc, - FlatMethod flatm ) throws java.io.IOException { - - // initialize flat nodes to visit as the flat method - // because all other nodes in this flat method are - // decendents of the flat method itself - flatNodesToVisit = new HashSet(); - flatNodesToVisit.add( flatm ); - - // initilize the mapping of flat nodes in this flat method to - // ownership graph results to an empty mapping - mapFlatNodeToOwnershipGraph = new Hashtable(); - - // initialize the set of return nodes that will be combined as - // the final ownership graph result to return as an empty set - returnNodesToCombineForCompleteOwnershipGraph = new HashSet(); - - while( !flatNodesToVisit.isEmpty() ) { - FlatNode fn = (FlatNode) flatNodesToVisit.iterator().next(); - flatNodesToVisit.remove( fn ); - - // perform this node's contributions to the ownership - // graph on a new copy, then compare it to the old graph - // at this node to see if anything was updated. - OwnershipGraph og = new OwnershipGraph( allocationDepth ); - - // start by merging all node's parents' graphs - for( int i = 0; i < fn.numPrev(); ++i ) { - FlatNode pn = fn.getPrev( i ); - OwnershipGraph ogParent = getGraphFromFlatNode( pn ); - og.merge( ogParent ); - } - - // apply the analysis of the flat node to the - // ownership graph made from the merge of the - // parent graphs - analyzeFlatNode( mDesc, - fn, - returnNodesToCombineForCompleteOwnershipGraph, - og ); - - // if the results of the new graph are different from - // the current graph at this node, replace the graph - // with the update and enqueue the children for - // processing - OwnershipGraph ogPrev = getGraphFromFlatNode( fn ); - - if( !og.equals( ogPrev ) ) { - setGraphForFlatNode( fn, og ); - - - - x++; - if( x > 0 ) { - String s = String.format( "debug%04d", x ); - //og.writeGraph( s, true, true, true, false ); - } - - - - for( int i = 0; i < fn.numNext(); i++ ) { - FlatNode nn = fn.getNext( i ); - flatNodesToVisit.add( nn ); - } - } - } - - // end by merging all return nodes into a complete - // ownership graph that represents all possible heap - // states after the flat method returns - OwnershipGraph completeGraph = new OwnershipGraph( allocationDepth ); - Iterator retItr = returnNodesToCombineForCompleteOwnershipGraph.iterator(); - while( retItr.hasNext() ) { - FlatReturnNode frn = (FlatReturnNode) retItr.next(); - OwnershipGraph ogr = getGraphFromFlatNode( frn ); - completeGraph.merge( ogr ); - } - return completeGraph; - } - private void - analyzeFlatNode( Descriptor methodDesc, - FlatNode fn, - HashSet setRetNodes, - OwnershipGraph og ) throws java.io.IOException { - - TempDescriptor src; - TempDescriptor dst; - FieldDescriptor fld; - - // use node type to decide what alterations to make - // to the ownership graph - switch( fn.kind() ) { - - case FKind.FlatMethod: - FlatMethod fm = (FlatMethod) fn; - - // there should only be one FlatMethod node as the - // parent of all other FlatNode objects, so take - // the opportunity to construct the initial graph by - // adding parameters labels to new heap regions - for( int i = 0; i < fm.numParameters(); ++i ) { - TempDescriptor tdParam = fm.getParameter( i ); - og.assignParameterAllocationToTemp( methodDesc instanceof TaskDescriptor, - tdParam, - new Integer( i ) ); - } - - break; - - case FKind.FlatOpNode: - FlatOpNode fon = (FlatOpNode) fn; - if( fon.getOp().getOp() == Operation.ASSIGN ) { - src = fon.getLeft(); - dst = fon.getDest(); - og.assignTempYToTempX( src, dst ); - } - break; - - case FKind.FlatFieldNode: - FlatFieldNode ffn = (FlatFieldNode) fn; - src = ffn.getSrc(); - dst = ffn.getDst(); - fld = ffn.getField(); - if( !fld.getType().isPrimitive() ) { - og.assignTempYFieldFToTempX( src, fld, dst ); - } - break; - - case FKind.FlatSetFieldNode: - FlatSetFieldNode fsfn = (FlatSetFieldNode) fn; - src = fsfn.getSrc(); - dst = fsfn.getDst(); - fld = fsfn.getField(); - og.assignTempYToTempXFieldF( src, dst, fld ); - break; - - case FKind.FlatNew: - FlatNew fnn = (FlatNew) fn; - dst = fnn.getDst(); - AllocationSite as = getAllocationSiteFromFlatNewPRIVATE( fnn ); - - og.assignNewAllocationToTempX( dst, as ); - break; - - case FKind.FlatCall: - FlatCall fc = (FlatCall) fn; - MethodDescriptor md = fc.getMethod(); - FlatMethod flatm = state.getMethodFlat( md ); - //HashSet allocSiteSet = getAllocationSiteSet( md ); - OwnershipGraph ogAllPossibleCallees = new OwnershipGraph( allocationDepth ); - - if( md.isStatic() ) { - // a static method is simply always the same, makes life easy - OwnershipGraph onlyPossibleCallee = mapDescriptorToCompleteOwnershipGraph.get( md ); - ogAllPossibleCallees.merge( onlyPossibleCallee ); - - /* - if( onlyPossibleCallee != null ) { - onlyPossibleCallee.writeGraph( "only", false, false ); - System.out.println( "There was only one possible callee, "+md ); - } - */ - - } 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 graphs together - TypeDescriptor typeDesc = fc.getThis().getType(); - Set possibleCallees = callGraph.getMethods( md, typeDesc ); - - //int j = 0; - - Iterator i = possibleCallees.iterator(); - while( i.hasNext() ) { - MethodDescriptor possibleMd = (MethodDescriptor) i.next(); - //allocSiteSet.addAll( getAllocationSiteSet( possibleMd ) ); - OwnershipGraph ogPotentialCallee = mapDescriptorToCompleteOwnershipGraph.get( possibleMd ); - - /* - if( ogPotentialCallee != null ) { - ogPotentialCallee.writeGraph( "potential"+j, false, false ); - ++j; - } - */ - - ogAllPossibleCallees.merge( ogPotentialCallee ); - } - - //System.out.println( "There were "+j+" potential callees merged together." ); - } - - //System.out.println( "AllocationSiteSet has "+allocSiteSet.size()+" items." ); - - // now we should have the following information to resolve this method call: - // - // 1. A FlatCall fc to query for the caller's context (argument labels, etc) - // - // 2. Whether the method is static; if not we need to deal with the "this" pointer - // - // ******************************************************************************************* - // 3. The original FlatMethod flatm to query for callee's context (paramter labels) - // NOTE! I assume FlatMethod before virtual dispatch accurately describes all possible methods! - // ******************************************************************************************* - // - // 4. The OwnershipGraph ogAllPossibleCallees is a merge of every ownership graph of all the possible - // methods to capture any possible references made. - // - // 5. The Set of AllocationSite objects, allocSiteSet that is the set of allocation sites from - // every possible method we might have chosen - // - og.resolveMethodCall( fc, md.isStatic(), flatm, ogAllPossibleCallees ); - break; - - case FKind.FlatReturnNode: - FlatReturnNode frn = (FlatReturnNode) fn; - setRetNodes.add( frn ); - break; - } - } + // return just the allocation site associated with one FlatNew node + private AllocationSite getAllocationSiteFromFlatNewPRIVATE(FlatNew fn) { - // this method should generate integers strictly greater than zero! - // special "shadow" regions are made from a heap region by negating - // the ID - static public Integer generateUniqueHeapRegionNodeID() { - ++uniqueIDcount; - return new Integer( uniqueIDcount ); - } + if( !mapFlatNewToAllocationSite.containsKey(fn) ) { + AllocationSite as = new AllocationSite(allocationDepth, fn.getType() ); + // the newest nodes are single objects + for( int i = 0; i < allocationDepth; ++i ) { + Integer id = generateUniqueHeapRegionNodeID(); + as.setIthOldest(i, id); + } - private OwnershipGraph getGraphFromFlatNode( FlatNode fn ) { - if( !mapFlatNodeToOwnershipGraph.containsKey( fn ) ) { - mapFlatNodeToOwnershipGraph.put( fn, new OwnershipGraph( allocationDepth ) ); - } + // the oldest node is a summary node + Integer idSummary = generateUniqueHeapRegionNodeID(); + as.setSummary(idSummary); - return mapFlatNodeToOwnershipGraph.get( fn ); + mapFlatNewToAllocationSite.put(fn, as); } - private void setGraphForFlatNode( FlatNode fn, OwnershipGraph og ) { - mapFlatNodeToOwnershipGraph.put( fn, og ); + return mapFlatNewToAllocationSite.get(fn); + } + + + // return all allocation sites in the method (there is one allocation + // site per FlatNew node in a method) + private HashSet getAllocationSiteSet(Descriptor d) { + if( !mapDescriptorToAllocationSiteSet.containsKey(d) ) { + buildAllocationSiteSet(d); } + return mapDescriptorToAllocationSiteSet.get(d); + } - + private void buildAllocationSiteSet(Descriptor d) { + HashSet s = new HashSet(); + FlatMethod fm; + if( d instanceof MethodDescriptor ) { + fm = state.getMethodFlat( (MethodDescriptor) d); + } else { + assert d instanceof TaskDescriptor; + fm = state.getMethodFlat( (TaskDescriptor) d); + } - // return just the allocation site associated with one FlatNew node - private AllocationSite getAllocationSiteFromFlatNewPRIVATE( FlatNew fn ) { + // visit every node in this FlatMethod's IR graph + // and make a set of the allocation sites from the + // FlatNew node's visited + HashSet visited = new HashSet(); + HashSet toVisit = new HashSet(); + toVisit.add(fm); - if( !mapFlatNewToAllocationSite.containsKey( fn ) ) { - AllocationSite as = new AllocationSite( allocationDepth, fn.getType() ); + while( !toVisit.isEmpty() ) { + FlatNode n = toVisit.iterator().next(); - // the newest nodes are single objects - for( int i = 0; i < allocationDepth; ++i ) { - Integer id = generateUniqueHeapRegionNodeID(); - as.setIthOldest( i, id ); - } + if( n instanceof FlatNew ) { + s.add(getAllocationSiteFromFlatNewPRIVATE( (FlatNew) n) ); + } - // the oldest node is a summary node - Integer idSummary = generateUniqueHeapRegionNodeID(); - as.setSummary( idSummary ); + toVisit.remove(n); + visited.add(n); - mapFlatNewToAllocationSite.put( fn, as ); + for( int i = 0; i < n.numNext(); ++i ) { + FlatNode child = n.getNext(i); + if( !visited.contains(child) ) { + toVisit.add(child); } - - return mapFlatNewToAllocationSite.get( fn ); + } } + mapDescriptorToAllocationSiteSet.put(d, s); + } - // return all allocation sites in the method (there is one allocation - // site per FlatNew node in a method) - private HashSet getAllocationSiteSet( Descriptor d ) { - if( !mapDescriptorToAllocationSiteSet.containsKey( d ) ) { - buildAllocationSiteSet( d ); - } - return mapDescriptorToAllocationSiteSet.get( d ); + private HashSet + getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) { - } + HashSet asSetTotal = new HashSet(); + HashSet toVisit = new HashSet(); + HashSet visited = new HashSet(); - private void buildAllocationSiteSet( Descriptor d ) { - HashSet s = new HashSet(); + toVisit.add(td); - FlatMethod fm; - if( d instanceof MethodDescriptor ) { - fm = state.getMethodFlat( (MethodDescriptor) d ); - } else { - assert d instanceof TaskDescriptor; - fm = state.getMethodFlat( (TaskDescriptor) d ); - } + // traverse this task and all methods reachable from this task + while( !toVisit.isEmpty() ) { + Descriptor d = toVisit.iterator().next(); + toVisit.remove(d); + visited.add(d); - // visit every node in this FlatMethod's IR graph - // and make a set of the allocation sites from the - // FlatNew node's visited - HashSet visited = new HashSet(); - HashSet toVisit = new HashSet(); - toVisit.add( fm ); - - while( !toVisit.isEmpty() ) { - FlatNode n = toVisit.iterator().next(); - - if( n instanceof FlatNew ) { - 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 ); - } - } + HashSet asSet = getAllocationSiteSet(d); + Iterator asItr = asSet.iterator(); + while( asItr.hasNext() ) { + AllocationSite as = (AllocationSite) asItr.next(); + if( as.getType().getClassDesc().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(); - mapDescriptorToAllocationSiteSet.put( d, s ); + if( !visited.contains(md) ) { + toVisit.add(md); + } + } + } } - private HashSet - getFlaggedAllocationSitesReachableFromTaskPRIVATE( TaskDescriptor td ) { - - HashSet asSetTotal = new HashSet(); - HashSet toVisit = new HashSet(); - HashSet visited = new HashSet(); - - toVisit.add( td ); - - // traverse this task and all methods reachable from this task - while( !toVisit.isEmpty() ) { - Descriptor d = toVisit.iterator().next(); - toVisit.remove( d ); - visited.add( d ); - - HashSet asSet = getAllocationSiteSet( d ); - Iterator asItr = asSet.iterator(); - while( asItr.hasNext() ) { - AllocationSite as = (AllocationSite) asItr.next(); - if( as.getType().getClassDesc().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 ); - } - } - } - } - + return asSetTotal; + } - return asSetTotal; - } + private HashSet getHeapRegionIDset(OwnershipGraph og, + int paramIndex) { - private HashSet getHeapRegionIDset( OwnershipGraph og, - int paramIndex ) { - - assert og.paramIndex2id.containsKey( paramIndex ); - Integer idParam = og.paramIndex2id.get( paramIndex ); + assert og.paramIndex2id.containsKey(paramIndex); + Integer idParam = og.paramIndex2id.get(paramIndex); - HashSet idSet = new HashSet(); - idSet.add( idParam ); + HashSet idSet = new HashSet(); + idSet.add(idParam); - return idSet; - } + return idSet; + } - private HashSet getHeapRegionIDset( AllocationSite alloc ) { + private HashSet getHeapRegionIDset(AllocationSite alloc) { - HashSet idSet = new HashSet(); - - for( int i = 0; i < alloc.getAllocationDepth(); ++i ) { - Integer id = alloc.getIthOldest( i ); - idSet.add( id ); - } - - Integer idSummary = alloc.getSummary(); - idSet.add( idSummary ); + HashSet idSet = new HashSet(); - return idSet; + for( int i = 0; i < alloc.getAllocationDepth(); ++i ) { + Integer id = alloc.getIthOldest(i); + idSet.add(id); } - private HashSet getHeapRegionIDset( HashSet allocSet ) { + Integer idSummary = alloc.getSummary(); + idSet.add(idSummary); - HashSet idSet = new HashSet(); + return idSet; + } - Iterator allocItr = allocSet.iterator(); - while( allocItr.hasNext() ) { - AllocationSite alloc = (AllocationSite) allocItr.next(); + private HashSet getHeapRegionIDset(HashSet allocSet) { - for( int i = 0; i < alloc.getAllocationDepth(); ++i ) { - Integer id = alloc.getIthOldest( i ); - idSet.add( id ); - } - - Integer idSummary = alloc.getSummary(); - idSet.add( idSummary ); - } + HashSet idSet = new HashSet(); - return idSet; - } + Iterator allocItr = allocSet.iterator(); + while( allocItr.hasNext() ) { + AllocationSite alloc = (AllocationSite) allocItr.next(); - private boolean createsPotentialAliases( OwnershipGraph og, - HashSet idSetA, - HashSet idSetB ) { - boolean potentialAlias = false; + for( int i = 0; i < alloc.getAllocationDepth(); ++i ) { + Integer id = alloc.getIthOldest(i); + idSet.add(id); + } - /* - // first expand set B into the set of all heap region node ID's - // reachable from the nodes in set B - HashSet idSetReachableFromB = og.getReachableSet( idSetB ); + Integer idSummary = alloc.getSummary(); + idSet.add(idSummary); + } - // then see if anything in A can reach a node in the set reachable - // from B. If so, there is a potential alias. - Iterator i = idSetA.iterator(); - while( i.hasNext() ) { - Integer id = (Integer) i.next(); - if( og.canIdReachSet( id, idSetB ) ) { - return true; - } - } - */ + return idSet; + } - return false; - } + private boolean createsPotentialAliases(OwnershipGraph og, + HashSet idSetA, + HashSet idSetB) { + boolean potentialAlias = false; + + /* + // first expand set B into the set of all heap region node ID's + // reachable from the nodes in set B + HashSet idSetReachableFromB = og.getReachableSet( idSetB ); + + // then see if anything in A can reach a node in the set reachable + // from B. If so, there is a potential alias. + Iterator i = idSetA.iterator(); + while( i.hasNext() ) { + Integer id = (Integer) i.next(); + if( og.canIdReachSet( id, idSetB ) ) { + return true; + } + } + */ + + return false; + } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/OwnershipGraph.java b/Robust/src/Analysis/OwnershipAnalysis/OwnershipGraph.java index 87052d0a..e3e37c58 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/OwnershipGraph.java +++ b/Robust/src/Analysis/OwnershipAnalysis/OwnershipGraph.java @@ -7,1838 +7,1838 @@ import java.io.*; public class OwnershipGraph { - private int allocationDepth; + private int allocationDepth; - // there was already one other very similar reason - // for traversing heap nodes that is no longer needed - // instead of writing a new heap region visitor, use - // the existing method with a new mode to describe what - // actions to take during the traversal - protected static final int VISIT_HRN_WRITE_FULL = 0; + // there was already one other very similar reason + // for traversing heap nodes that is no longer needed + // instead of writing a new heap region visitor, use + // the existing method with a new mode to describe what + // actions to take during the traversal + protected static final int VISIT_HRN_WRITE_FULL = 0; - public Hashtable id2hrn; - public Hashtable td2ln; - public Hashtable id2paramIndex; - public Hashtable paramIndex2id; + public Hashtable id2hrn; + public Hashtable td2ln; + public Hashtable id2paramIndex; + public Hashtable paramIndex2id; - public HashSet allocationSites; + public HashSet allocationSites; - public OwnershipGraph( int allocationDepth ) { - this.allocationDepth = allocationDepth; - - id2hrn = new Hashtable(); - td2ln = new Hashtable(); - id2paramIndex = new Hashtable(); - paramIndex2id = new Hashtable(); + public OwnershipGraph(int allocationDepth) { + this.allocationDepth = allocationDepth; - allocationSites = new HashSet (); - } - - - // label nodes are much easier to deal with than - // heap region nodes. Whenever there is a request - // for the label node that is associated with a - // temp descriptor we can either find it or make a - // new one and return it. This is because temp - // descriptors are globally unique and every label - // node is mapped to exactly one temp descriptor. - protected LabelNode getLabelNodeFromTemp( TempDescriptor td ) { - assert td != null; - - if( !td2ln.containsKey( td ) ) { - td2ln.put( td, new LabelNode( td ) ); - } - - return td2ln.get( td ); - } + id2hrn = new Hashtable(); + td2ln = new Hashtable(); + id2paramIndex = new Hashtable(); + paramIndex2id = new Hashtable(); + allocationSites = new HashSet (); + } - // the reason for this method is to have the option - // creating new heap regions with specific IDs, or - // duplicating heap regions with specific IDs (especially - // in the merge() operation) or to create new heap - // regions with a new unique ID. - protected HeapRegionNode - createNewHeapRegionNode( Integer id, - boolean isSingleObject, - boolean isFlagged, - boolean isNewSummary, - boolean isParameter, - AllocationSite allocSite, - ReachabilitySet alpha, - String description ) { - - if( id == null ) { - id = OwnershipAnalysis.generateUniqueHeapRegionNodeID(); - } - if( alpha == null ) { - if( isFlagged || isParameter ) { - alpha = new ReachabilitySet( new TokenTuple( id, - !isSingleObject, - TokenTuple.ARITY_ONE ) - ).makeCanonical(); - } else { - alpha = new ReachabilitySet( new TokenTupleSet() - ).makeCanonical(); - } - } + // label nodes are much easier to deal with than + // heap region nodes. Whenever there is a request + // for the label node that is associated with a + // temp descriptor we can either find it or make a + // new one and return it. This is because temp + // descriptors are globally unique and every label + // node is mapped to exactly one temp descriptor. + protected LabelNode getLabelNodeFromTemp(TempDescriptor td) { + assert td != null; - HeapRegionNode hrn = new HeapRegionNode( id, - isSingleObject, - isFlagged, - isNewSummary, - allocSite, - alpha, - description ); - id2hrn.put( id, hrn ); - return hrn; + if( !td2ln.containsKey(td) ) { + td2ln.put(td, new LabelNode(td) ); } - - - //////////////////////////////////////////////// - // - // Low-level referencee and referencer methods - // - // These methods provide the lowest level for - // creating references between ownership nodes - // and handling the details of maintaining both - // list of referencers and referencees. - // - //////////////////////////////////////////////// - protected void addReferenceEdge( OwnershipNode referencer, - HeapRegionNode referencee, - ReferenceEdge edge ) { - assert referencer != null; - assert referencee != null; - assert edge != null; - assert edge.getSrc() == referencer; - assert edge.getDst() == referencee; - - referencer.addReferencee( edge ); - referencee.addReferencer( edge ); + return td2ln.get(td); + } + + + // the reason for this method is to have the option + // creating new heap regions with specific IDs, or + // duplicating heap regions with specific IDs (especially + // in the merge() operation) or to create new heap + // regions with a new unique ID. + protected HeapRegionNode + createNewHeapRegionNode(Integer id, + boolean isSingleObject, + boolean isFlagged, + boolean isNewSummary, + boolean isParameter, + AllocationSite allocSite, + ReachabilitySet alpha, + String description) { + + if( id == null ) { + id = OwnershipAnalysis.generateUniqueHeapRegionNodeID(); } - protected void removeReferenceEdge( OwnershipNode referencer, - HeapRegionNode referencee, - FieldDescriptor fieldDesc ) { - assert referencer != null; - assert referencee != null; - - ReferenceEdge edge = referencer.getReferenceTo( referencee, - fieldDesc ); - assert edge != null; - assert edge == referencee.getReferenceFrom( referencer, - fieldDesc ); - - referencer.removeReferencee( edge ); - referencee.removeReferencer( edge ); + if( alpha == null ) { + if( isFlagged || isParameter ) { + alpha = new ReachabilitySet(new TokenTuple(id, + !isSingleObject, + TokenTuple.ARITY_ONE) + ).makeCanonical(); + } else { + alpha = new ReachabilitySet(new TokenTupleSet() + ).makeCanonical(); + } } - protected void clearReferenceEdgesFrom( OwnershipNode referencer, - FieldDescriptor fieldDesc, - boolean removeAll ) { - assert referencer != null; - - // get a copy of the set to iterate over, otherwise - // we will be trying to take apart the set as we - // are iterating over it, which won't work - Iterator i = referencer.iteratorToReferenceesClone(); - while( i.hasNext() ) { - ReferenceEdge edge = i.next(); - - if( removeAll || edge.getFieldDesc() == fieldDesc ) { - HeapRegionNode referencee = edge.getDst(); - - removeReferenceEdge( referencer, - referencee, - edge.getFieldDesc() ); - } - } + HeapRegionNode hrn = new HeapRegionNode(id, + isSingleObject, + isFlagged, + isNewSummary, + allocSite, + alpha, + description); + id2hrn.put(id, hrn); + return hrn; + } + + + + //////////////////////////////////////////////// + // + // Low-level referencee and referencer methods + // + // These methods provide the lowest level for + // creating references between ownership nodes + // and handling the details of maintaining both + // list of referencers and referencees. + // + //////////////////////////////////////////////// + protected void addReferenceEdge(OwnershipNode referencer, + HeapRegionNode referencee, + ReferenceEdge edge) { + assert referencer != null; + assert referencee != null; + assert edge != null; + assert edge.getSrc() == referencer; + assert edge.getDst() == referencee; + + referencer.addReferencee(edge); + referencee.addReferencer(edge); + } + + protected void removeReferenceEdge(OwnershipNode referencer, + HeapRegionNode referencee, + FieldDescriptor fieldDesc) { + assert referencer != null; + assert referencee != null; + + ReferenceEdge edge = referencer.getReferenceTo(referencee, + fieldDesc); + assert edge != null; + assert edge == referencee.getReferenceFrom(referencer, + fieldDesc); + + referencer.removeReferencee(edge); + referencee.removeReferencer(edge); + } + + protected void clearReferenceEdgesFrom(OwnershipNode referencer, + FieldDescriptor fieldDesc, + boolean removeAll) { + assert referencer != null; + + // get a copy of the set to iterate over, otherwise + // we will be trying to take apart the set as we + // are iterating over it, which won't work + Iterator i = referencer.iteratorToReferenceesClone(); + while( i.hasNext() ) { + ReferenceEdge edge = i.next(); + + if( removeAll || edge.getFieldDesc() == fieldDesc ) { + HeapRegionNode referencee = edge.getDst(); + + removeReferenceEdge(referencer, + referencee, + edge.getFieldDesc() ); + } } - - protected void clearReferenceEdgesTo( HeapRegionNode referencee, - FieldDescriptor fieldDesc, - boolean removeAll ) { - assert referencee != null; - - // get a copy of the set to iterate over, otherwise - // we will be trying to take apart the set as we - // are iterating over it, which won't work - Iterator i = referencee.iteratorToReferencersClone(); - while( i.hasNext() ) { - ReferenceEdge edge = i.next(); - - if( removeAll || edge.getFieldDesc() == fieldDesc ) { - OwnershipNode referencer = edge.getSrc(); - removeReferenceEdge( referencer, - referencee, - edge.getFieldDesc() ); - } - } + } + + protected void clearReferenceEdgesTo(HeapRegionNode referencee, + FieldDescriptor fieldDesc, + boolean removeAll) { + assert referencee != null; + + // get a copy of the set to iterate over, otherwise + // we will be trying to take apart the set as we + // are iterating over it, which won't work + Iterator i = referencee.iteratorToReferencersClone(); + while( i.hasNext() ) { + ReferenceEdge edge = i.next(); + + if( removeAll || edge.getFieldDesc() == fieldDesc ) { + OwnershipNode referencer = edge.getSrc(); + removeReferenceEdge(referencer, + referencee, + edge.getFieldDesc() ); + } } - - - protected void propagateTokensOverNodes( HeapRegionNode nPrime, - ChangeTupleSet c0, - HashSet nodesWithNewAlpha, - HashSet edgesWithNewBeta ) { - - HashSet todoNodes - = new HashSet(); - todoNodes.add( nPrime ); - - HashSet todoEdges - = new HashSet(); - - Hashtable nodePlannedChanges - = new Hashtable(); - nodePlannedChanges.put( nPrime, c0 ); - - Hashtable edgePlannedChanges - = new Hashtable(); - - - while( !todoNodes.isEmpty() ) { - HeapRegionNode n = todoNodes.iterator().next(); - ChangeTupleSet C = nodePlannedChanges.get( n ); - - Iterator itrC = C.iterator(); - while( itrC.hasNext() ) { - ChangeTuple c = (ChangeTuple) itrC.next(); - - if( n.getAlpha().contains( c.getSetToMatch() ) ) { - ReachabilitySet withChange = n.getAlpha().union( c.getSetToAdd() ); - n.setAlphaNew( n.getAlphaNew().union( withChange ) ); - nodesWithNewAlpha.add( n ); - } - } + } - Iterator referItr = n.iteratorToReferencers(); - while( referItr.hasNext() ) { - ReferenceEdge edge = referItr.next(); - todoEdges.add( edge ); - if( !edgePlannedChanges.containsKey( edge ) ) { - edgePlannedChanges.put( edge, new ChangeTupleSet().makeCanonical() ); - } + protected void propagateTokensOverNodes(HeapRegionNode nPrime, + ChangeTupleSet c0, + HashSet nodesWithNewAlpha, + HashSet edgesWithNewBeta) { - edgePlannedChanges.put( edge, edgePlannedChanges.get( edge ).union( C ) ); - } + HashSet todoNodes + = new HashSet(); + todoNodes.add(nPrime); - Iterator refeeItr = n.iteratorToReferencees(); - while( refeeItr.hasNext() ) { - ReferenceEdge edgeF = refeeItr.next(); - HeapRegionNode m = edgeF.getDst(); + HashSet todoEdges + = new HashSet(); - ChangeTupleSet changesToPass = new ChangeTupleSet().makeCanonical(); + Hashtable nodePlannedChanges + = new Hashtable(); + nodePlannedChanges.put(nPrime, c0); - Iterator itrCprime = C.iterator(); - while( itrCprime.hasNext() ) { - ChangeTuple c = itrCprime.next(); - if( edgeF.getBeta().contains( c.getSetToMatch() ) ) { - changesToPass = changesToPass.union( c ); - } - } + Hashtable edgePlannedChanges + = new Hashtable(); - if( !changesToPass.isEmpty() ) { - if( !nodePlannedChanges.containsKey( m ) ) { - nodePlannedChanges.put( m, new ChangeTupleSet().makeCanonical() ); - } - ChangeTupleSet currentChanges = nodePlannedChanges.get( m ); + while( !todoNodes.isEmpty() ) { + HeapRegionNode n = todoNodes.iterator().next(); + ChangeTupleSet C = nodePlannedChanges.get(n); - if( !changesToPass.isSubset( currentChanges ) ) { + Iterator itrC = C.iterator(); + while( itrC.hasNext() ) { + ChangeTuple c = (ChangeTuple) itrC.next(); - nodePlannedChanges.put( m, currentChanges.union( changesToPass ) ); - todoNodes.add( m ); - } - } - } + if( n.getAlpha().contains(c.getSetToMatch() ) ) { + ReachabilitySet withChange = n.getAlpha().union(c.getSetToAdd() ); + n.setAlphaNew(n.getAlphaNew().union(withChange) ); + nodesWithNewAlpha.add(n); + } + } + + Iterator referItr = n.iteratorToReferencers(); + while( referItr.hasNext() ) { + ReferenceEdge edge = referItr.next(); + todoEdges.add(edge); - todoNodes.remove( n ); + if( !edgePlannedChanges.containsKey(edge) ) { + edgePlannedChanges.put(edge, new ChangeTupleSet().makeCanonical() ); } - propagateTokensOverEdges( todoEdges, edgePlannedChanges, nodesWithNewAlpha, edgesWithNewBeta ); - } + edgePlannedChanges.put(edge, edgePlannedChanges.get(edge).union(C) ); + } + Iterator refeeItr = n.iteratorToReferencees(); + while( refeeItr.hasNext() ) { + ReferenceEdge edgeF = refeeItr.next(); + HeapRegionNode m = edgeF.getDst(); - protected void propagateTokensOverEdges( - HashSet todoEdges, - Hashtable edgePlannedChanges, - HashSet nodesWithNewAlpha, - HashSet edgesWithNewBeta ) { - + ChangeTupleSet changesToPass = new ChangeTupleSet().makeCanonical(); - while( !todoEdges.isEmpty() ) { - ReferenceEdge edgeE = todoEdges.iterator().next(); - todoEdges.remove( edgeE ); + Iterator itrCprime = C.iterator(); + while( itrCprime.hasNext() ) { + ChangeTuple c = itrCprime.next(); + if( edgeF.getBeta().contains(c.getSetToMatch() ) ) { + changesToPass = changesToPass.union(c); + } + } - if( !edgePlannedChanges.containsKey( edgeE ) ) { - edgePlannedChanges.put( edgeE, new ChangeTupleSet().makeCanonical() ); - } - - ChangeTupleSet C = edgePlannedChanges.get( edgeE ); - - ChangeTupleSet changesToPass = new ChangeTupleSet().makeCanonical(); - - Iterator itrC = C.iterator(); - while( itrC.hasNext() ) { - ChangeTuple c = itrC.next(); - if( edgeE.getBeta().contains( c.getSetToMatch() ) ) { - ReachabilitySet withChange = edgeE.getBeta().union( c.getSetToAdd() ); - edgeE.setBetaNew( edgeE.getBetaNew().union( withChange ) ); - edgesWithNewBeta.add( edgeE ); - changesToPass = changesToPass.union( c ); - } - } + if( !changesToPass.isEmpty() ) { + if( !nodePlannedChanges.containsKey(m) ) { + nodePlannedChanges.put(m, new ChangeTupleSet().makeCanonical() ); + } - OwnershipNode onSrc = edgeE.getSrc(); - - if( !changesToPass.isEmpty() && onSrc instanceof HeapRegionNode ) { - HeapRegionNode n = (HeapRegionNode) onSrc; - - Iterator referItr = n.iteratorToReferencers(); - while( referItr.hasNext() ) { - ReferenceEdge edgeF = referItr.next(); - - if( !edgePlannedChanges.containsKey( edgeF ) ) { - edgePlannedChanges.put( edgeF, new ChangeTupleSet().makeCanonical() ); - } - - ChangeTupleSet currentChanges = edgePlannedChanges.get( edgeF ); - - if( !changesToPass.isSubset( currentChanges ) ) { - todoEdges.add( edgeF ); - edgePlannedChanges.put( edgeF, currentChanges.union( changesToPass ) ); - } - } - } - } - } + ChangeTupleSet currentChanges = nodePlannedChanges.get(m); + if( !changesToPass.isSubset(currentChanges) ) { - //////////////////////////////////////////////////// - // - // Assignment Operation Methods - // - // These methods are high-level operations for - // modeling program assignment statements using - // the low-level reference create/remove methods - // above. - // - // The destination in an assignment statement is - // going to have new references. The method of - // determining the references depends on the type - // of the FlatNode assignment and the predicates - // of the nodes and edges involved. - // - //////////////////////////////////////////////////// - public void assignTempYToTempX( TempDescriptor y, - TempDescriptor x ) { - - LabelNode lnX = getLabelNodeFromTemp( x ); - LabelNode lnY = getLabelNodeFromTemp( y ); - - clearReferenceEdgesFrom( lnX, null, true ); - - Iterator itrYhrn = lnY.iteratorToReferencees(); - while( itrYhrn.hasNext() ) { - ReferenceEdge edgeY = itrYhrn.next(); - HeapRegionNode referencee = edgeY.getDst(); - ReferenceEdge edgeNew = edgeY.copy(); - edgeNew.setSrc( lnX ); - - addReferenceEdge( lnX, referencee, edgeNew ); + nodePlannedChanges.put(m, currentChanges.union(changesToPass) ); + todoNodes.add(m); + } } + } + + todoNodes.remove(n); } + propagateTokensOverEdges(todoEdges, edgePlannedChanges, nodesWithNewAlpha, edgesWithNewBeta); + } - public void assignTempYFieldFToTempX( TempDescriptor y, - FieldDescriptor f, - TempDescriptor x ) { - LabelNode lnX = getLabelNodeFromTemp( x ); - LabelNode lnY = getLabelNodeFromTemp( y ); + protected void propagateTokensOverEdges( + HashSet todoEdges, + Hashtable edgePlannedChanges, + HashSet nodesWithNewAlpha, + HashSet edgesWithNewBeta) { - clearReferenceEdgesFrom( lnX, null, true ); - Iterator itrYhrn = lnY.iteratorToReferencees(); - while( itrYhrn.hasNext() ) { - ReferenceEdge edgeY = itrYhrn.next(); - HeapRegionNode hrnY = edgeY.getDst(); - ReachabilitySet betaY = edgeY.getBeta(); + while( !todoEdges.isEmpty() ) { + ReferenceEdge edgeE = todoEdges.iterator().next(); + todoEdges.remove(edgeE); - Iterator itrHrnFhrn = hrnY.iteratorToReferencees(); - while( itrHrnFhrn.hasNext() ) { - ReferenceEdge edgeHrn = itrHrnFhrn.next(); - HeapRegionNode hrnHrn = edgeHrn.getDst(); - ReachabilitySet betaHrn = edgeHrn.getBeta(); + if( !edgePlannedChanges.containsKey(edgeE) ) { + edgePlannedChanges.put(edgeE, new ChangeTupleSet().makeCanonical() ); + } - if( edgeHrn.getFieldDesc() == null || - edgeHrn.getFieldDesc() == f ) { + ChangeTupleSet C = edgePlannedChanges.get(edgeE); - ReferenceEdge edgeNew = new ReferenceEdge( lnX, - hrnHrn, - f, - false, - betaY.intersection( betaHrn ) ); - - addReferenceEdge( lnX, hrnHrn, edgeNew ); - } - } + ChangeTupleSet changesToPass = new ChangeTupleSet().makeCanonical(); + + Iterator itrC = C.iterator(); + while( itrC.hasNext() ) { + ChangeTuple c = itrC.next(); + if( edgeE.getBeta().contains(c.getSetToMatch() ) ) { + ReachabilitySet withChange = edgeE.getBeta().union(c.getSetToAdd() ); + edgeE.setBetaNew(edgeE.getBetaNew().union(withChange) ); + edgesWithNewBeta.add(edgeE); + changesToPass = changesToPass.union(c); } - } + } + OwnershipNode onSrc = edgeE.getSrc(); - public void assignTempYToTempXFieldF( TempDescriptor y, - TempDescriptor x, - FieldDescriptor f ) { - - LabelNode lnX = getLabelNodeFromTemp( x ); - LabelNode lnY = getLabelNodeFromTemp( y ); - - HashSet nodesWithNewAlpha = new HashSet(); - HashSet edgesWithNewBeta = new HashSet(); - - Iterator itrXhrn = lnX.iteratorToReferencees(); - while( itrXhrn.hasNext() ) { - ReferenceEdge edgeX = itrXhrn.next(); - HeapRegionNode hrnX = edgeX.getDst(); - ReachabilitySet betaX = edgeX.getBeta(); - - ReachabilitySet R = hrnX.getAlpha().intersection( edgeX.getBeta() ); - - Iterator itrYhrn = lnY.iteratorToReferencees(); - while( itrYhrn.hasNext() ) { - ReferenceEdge edgeY = itrYhrn.next(); - HeapRegionNode hrnY = edgeY.getDst(); - ReachabilitySet O = edgeY.getBeta(); - - - // 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, - nodesWithNewAlpha, - edgesWithNewBeta ); - - - - //System.out.println( edgeY.getBetaNew() + "\nbeing pruned by\n" + hrnX.getAlpha() ); - - // create the actual reference edge hrnX.f -> hrnY - ReferenceEdge edgeNew = new ReferenceEdge( hrnX, - hrnY, - f, - false, - edgeY.getBetaNew().pruneBy( hrnX.getAlpha() ) - //edgeY.getBeta().pruneBy( hrnX.getAlpha() ) - ); - addReferenceEdge( hrnX, hrnY, edgeNew ); - - /* - if( f != null ) { - // we can do a strong update here if one of two cases holds - // SAVE FOR LATER, WITHOUT STILL CORRECT - if( (hrnX.getNumReferencers() == 1) || - ( lnX.getNumReferencees() == 1 && hrnX.isSingleObject() ) - ) { - clearReferenceEdgesFrom( hrnX, f, false ); - } - - addReferenceEdge( hrnX, hrnY, edgeNew ); - - } else { - // if the field is null, or "any" field, then - // look to see if an any field already exists - // and merge with it, otherwise just add the edge - ReferenceEdge edgeExisting = hrnX.getReferenceTo( hrnY, f ); - - if( edgeExisting != null ) { - edgeExisting.setBetaNew( - edgeExisting.getBetaNew().union( edgeNew.getBeta() ) - ); - // a new edge here cannot be reflexive, so existing will - // always be also not reflexive anymore - edgeExisting.setIsInitialParamReflexive( false ); - - } else { - addReferenceEdge( hrnX, hrnY, edgeNew ); - } - } - */ - } - } + if( !changesToPass.isEmpty() && onSrc instanceof HeapRegionNode ) { + HeapRegionNode n = (HeapRegionNode) onSrc; - Iterator nodeItr = nodesWithNewAlpha.iterator(); - while( nodeItr.hasNext() ) { - nodeItr.next().applyAlphaNew(); - } + Iterator referItr = n.iteratorToReferencers(); + while( referItr.hasNext() ) { + ReferenceEdge edgeF = referItr.next(); - Iterator edgeItr = edgesWithNewBeta.iterator(); - while( edgeItr.hasNext() ) { - edgeItr.next().applyBetaNew(); - } - } + if( !edgePlannedChanges.containsKey(edgeF) ) { + edgePlannedChanges.put(edgeF, new ChangeTupleSet().makeCanonical() ); + } + ChangeTupleSet currentChanges = edgePlannedChanges.get(edgeF); - public void assignParameterAllocationToTemp( boolean isTask, - TempDescriptor td, - Integer paramIndex ) { - assert td != null; - - LabelNode lnParam = getLabelNodeFromTemp( td ); - HeapRegionNode hrn = createNewHeapRegionNode( null, - false, - isTask, - false, - true, - null, - null, - "param" + paramIndex ); - - // keep track of heap regions that were created for - // parameter labels, the index of the parameter they - // are for is important when resolving method calls - Integer newID = hrn.getID(); - assert !id2paramIndex.containsKey ( newID ); - assert !id2paramIndex.containsValue( paramIndex ); - id2paramIndex.put( newID, paramIndex ); - paramIndex2id.put( paramIndex, newID ); - - ReachabilitySet beta = new ReachabilitySet( new TokenTuple( newID, - true, - TokenTuple.ARITY_ONE ) ); - - // heap regions for parameters are always multiple object (see above) - // and have a reference to themselves, because we can't know the - // structure of memory that is passed into the method. We're assuming - // the worst here. - - ReferenceEdge edgeFromLabel = - new ReferenceEdge( lnParam, hrn, null, false, beta ); - - ReferenceEdge edgeReflexive = - new ReferenceEdge( hrn, hrn, null, true, beta ); - - addReferenceEdge( lnParam, hrn, edgeFromLabel ); - addReferenceEdge( hrn, hrn, edgeReflexive ); + if( !changesToPass.isSubset(currentChanges) ) { + todoEdges.add(edgeF); + edgePlannedChanges.put(edgeF, currentChanges.union(changesToPass) ); + } + } + } + } + } + + + //////////////////////////////////////////////////// + // + // Assignment Operation Methods + // + // These methods are high-level operations for + // modeling program assignment statements using + // the low-level reference create/remove methods + // above. + // + // The destination in an assignment statement is + // going to have new references. The method of + // determining the references depends on the type + // of the FlatNode assignment and the predicates + // of the nodes and edges involved. + // + //////////////////////////////////////////////////// + public void assignTempYToTempX(TempDescriptor y, + TempDescriptor x) { + + LabelNode lnX = getLabelNodeFromTemp(x); + LabelNode lnY = getLabelNodeFromTemp(y); + + clearReferenceEdgesFrom(lnX, null, true); + + Iterator itrYhrn = lnY.iteratorToReferencees(); + while( itrYhrn.hasNext() ) { + ReferenceEdge edgeY = itrYhrn.next(); + HeapRegionNode referencee = edgeY.getDst(); + ReferenceEdge edgeNew = edgeY.copy(); + edgeNew.setSrc(lnX); + + addReferenceEdge(lnX, referencee, edgeNew); } + } - - public void assignNewAllocationToTempX( TempDescriptor x, - AllocationSite as ) { - assert x != null; - assert as != null; - age( as ); + public void assignTempYFieldFToTempX(TempDescriptor y, + FieldDescriptor f, + TempDescriptor x) { - // after the age operation the newest (or zero-ith oldest) - // node associated with the allocation site should have - // no references to it as if it were a newly allocated - // heap region, so make a reference to it to complete - // this operation + LabelNode lnX = getLabelNodeFromTemp(x); + LabelNode lnY = getLabelNodeFromTemp(y); - Integer idNewest = as.getIthOldest( 0 ); - HeapRegionNode hrnNewest = id2hrn.get( idNewest ); - assert hrnNewest != null; + clearReferenceEdgesFrom(lnX, null, true); - LabelNode lnX = getLabelNodeFromTemp( x ); - clearReferenceEdgesFrom( lnX, null, true ); + Iterator itrYhrn = lnY.iteratorToReferencees(); + while( itrYhrn.hasNext() ) { + ReferenceEdge edgeY = itrYhrn.next(); + HeapRegionNode hrnY = edgeY.getDst(); + ReachabilitySet betaY = edgeY.getBeta(); - ReferenceEdge edgeNew = - new ReferenceEdge( lnX, hrnNewest, null, false, hrnNewest.getAlpha() ); - - addReferenceEdge( lnX, hrnNewest, edgeNew ); - } + Iterator itrHrnFhrn = hrnY.iteratorToReferencees(); + while( itrHrnFhrn.hasNext() ) { + ReferenceEdge edgeHrn = itrHrnFhrn.next(); + HeapRegionNode hrnHrn = edgeHrn.getDst(); + ReachabilitySet betaHrn = edgeHrn.getBeta(); + if( edgeHrn.getFieldDesc() == null || + edgeHrn.getFieldDesc() == f ) { - // use the allocation site (unique to entire analysis) to - // locate the heap region nodes in this ownership graph - // that should be aged. The process models the allocation - // of new objects and collects all the oldest allocations - // in a summary node to allow for a finite analysis - // - // There is an additional property of this method. After - // running it on a particular ownership graph (many graphs - // may have heap regions related to the same allocation site) - // the heap region node objects in this ownership graph will be - // allocated. Therefore, after aging a graph for an allocation - // site, attempts to retrieve the heap region nodes using the - // integer id's contained in the allocation site should always - // return non-null heap regions. - public void age( AllocationSite as ) { - - // aging adds this allocation site to the graph's - // list of sites that exist in the graph, or does - // nothing if the site is already in the list - allocationSites.add( as ); - - // get the summary node for the allocation site in the context - // of this particular ownership graph - HeapRegionNode hrnSummary = getSummaryNode( as ); - - // merge oldest node into summary - Integer idK = as.getOldest(); - HeapRegionNode hrnK = id2hrn.get( idK ); - mergeIntoSummary( hrnK, hrnSummary ); - - // move down the line of heap region nodes - // clobbering the ith and transferring all references - // to and from i-1 to node i. Note that this clobbers - // the oldest node (hrnK) that was just merged into - // the summary - for( int i = allocationDepth - 1; i > 0; --i ) { - - // move references from the i-1 oldest to the ith oldest - Integer idIth = as.getIthOldest( i ); - HeapRegionNode hrnI = id2hrn.get( idIth ); - Integer idImin1th = as.getIthOldest( i - 1 ); - HeapRegionNode hrnImin1 = id2hrn.get( idImin1th ); - - transferOnto( hrnImin1, hrnI ); - } + ReferenceEdge edgeNew = new ReferenceEdge(lnX, + hrnHrn, + f, + false, + betaY.intersection(betaHrn) ); - // as stated above, the newest node should have had its - // references moved over to the second oldest, so we wipe newest - // in preparation for being the new object to assign something to - Integer id0th = as.getIthOldest( 0 ); - HeapRegionNode hrn0 = id2hrn.get( id0th ); - assert hrn0 != null; - - // clear all references in and out of newest node - clearReferenceEdgesFrom( hrn0, null, true ); - clearReferenceEdgesTo ( hrn0, null, true ); - - - // now tokens in reachability sets need to "age" also - Iterator itrAllLabelNodes = td2ln.entrySet().iterator(); - while( itrAllLabelNodes.hasNext() ) { - Map.Entry me = (Map.Entry) itrAllLabelNodes.next(); - LabelNode ln = (LabelNode) me.getValue(); - - Iterator itrEdges = ln.iteratorToReferencees(); - while( itrEdges.hasNext() ) { - ageTokens( as, itrEdges.next() ); - } + addReferenceEdge(lnX, hrnHrn, edgeNew); } + } + } + } - Iterator itrAllHRNodes = id2hrn.entrySet().iterator(); - while( itrAllHRNodes.hasNext() ) { - Map.Entry me = (Map.Entry) itrAllHRNodes.next(); - HeapRegionNode hrnToAge = (HeapRegionNode) me.getValue(); - ageTokens( as, hrnToAge ); + public void assignTempYToTempXFieldF(TempDescriptor y, + TempDescriptor x, + FieldDescriptor f) { - Iterator itrEdges = hrnToAge.iteratorToReferencees(); - while( itrEdges.hasNext() ) { - ageTokens( as, itrEdges.next() ); - } - } + LabelNode lnX = getLabelNodeFromTemp(x); + LabelNode lnY = getLabelNodeFromTemp(y); + HashSet nodesWithNewAlpha = new HashSet(); + HashSet edgesWithNewBeta = new HashSet(); - // after tokens have been aged, reset newest node's reachability - if( hrn0.isFlagged() ) { - hrn0.setAlpha( new ReachabilitySet( new TokenTupleSet( - new TokenTuple( hrn0 ) - ) - ).makeCanonical() - ); - } else { - hrn0.setAlpha( new ReachabilitySet( new TokenTupleSet() - ).makeCanonical() - ); - } - } - - - protected HeapRegionNode getSummaryNode( AllocationSite as ) { - - Integer idSummary = as.getSummary(); - HeapRegionNode hrnSummary = id2hrn.get( idSummary ); - - // If this is null then we haven't touched this allocation site - // in the context of the current ownership graph, so allocate - // heap region nodes appropriate for the entire allocation site. - // This should only happen once per ownership graph per allocation site, - // and a particular integer id can be used to locate the heap region - // in different ownership graphs that represents the same part of an - // allocation site. - if( hrnSummary == null ) { - - boolean hasFlags = false; - if( as.getType().isClass() ) { - hasFlags = as.getType().getClassDesc().hasFlags(); - } + Iterator itrXhrn = lnX.iteratorToReferencees(); + while( itrXhrn.hasNext() ) { + ReferenceEdge edgeX = itrXhrn.next(); + HeapRegionNode hrnX = edgeX.getDst(); + ReachabilitySet betaX = edgeX.getBeta(); - hrnSummary = createNewHeapRegionNode( idSummary, - false, - hasFlags, - true, - false, - as, - null, - as + "\\n" + as.getType() + "\\nsummary" ); - - for( int i = 0; i < as.getAllocationDepth(); ++i ) { - Integer idIth = as.getIthOldest( i ); - assert !id2hrn.containsKey( idIth ); - createNewHeapRegionNode( idIth, - true, - hasFlags, - false, - false, - as, - null, - as + "\\n" + as.getType() + "\\n" + i + " oldest" ); - } - } + ReachabilitySet R = hrnX.getAlpha().intersection(edgeX.getBeta() ); - return hrnSummary; - } + Iterator itrYhrn = lnY.iteratorToReferencees(); + while( itrYhrn.hasNext() ) { + ReferenceEdge edgeY = itrYhrn.next(); + HeapRegionNode hrnY = edgeY.getDst(); + ReachabilitySet O = edgeY.getBeta(); - protected HeapRegionNode getShadowSummaryNode( AllocationSite as ) { - - Integer idShadowSummary = -(as.getSummary()); - HeapRegionNode hrnShadowSummary = id2hrn.get( idShadowSummary ); + // 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); - if( hrnShadowSummary == null ) { - boolean hasFlags = false; - if( as.getType().isClass() ) { - hasFlags = as.getType().getClassDesc().hasFlags(); - } + // then propagate back just up the edges from hrn + ChangeTupleSet Cx = R.unionUpArityToChangeSet(O); - hrnShadowSummary = createNewHeapRegionNode( idShadowSummary, - false, - hasFlags, - true, - false, - as, - null, - as + "\\n" + as.getType() + "\\nshadowSum" ); - - for( int i = 0; i < as.getAllocationDepth(); ++i ) { - Integer idShadowIth = -(as.getIthOldest( i )); - assert !id2hrn.containsKey( idShadowIth ); - createNewHeapRegionNode( idShadowIth, - true, - hasFlags, - false, - false, - as, - null, - as + "\\n" + as.getType() + "\\n" + i + " shadow" ); - } + 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); } - return hrnShadowSummary; - } + propagateTokensOverEdges(todoEdges, + edgePlannedChanges, + nodesWithNewAlpha, + edgesWithNewBeta); - protected void mergeIntoSummary( HeapRegionNode hrn, HeapRegionNode hrnSummary ) { - assert hrnSummary.isNewSummary(); - // transfer references _from_ hrn over to hrnSummary - Iterator itrReferencee = hrn.iteratorToReferencees(); - while( itrReferencee.hasNext() ) { - ReferenceEdge edge = itrReferencee.next(); - ReferenceEdge edgeMerged = edge.copy(); - edgeMerged.setSrc( hrnSummary ); + //System.out.println( edgeY.getBetaNew() + "\nbeing pruned by\n" + hrnX.getAlpha() ); - HeapRegionNode hrnReferencee = edge.getDst(); - ReferenceEdge edgeSummary = hrnSummary.getReferenceTo( hrnReferencee, edge.getFieldDesc() ); + // create the actual reference edge hrnX.f -> hrnY + ReferenceEdge edgeNew = new ReferenceEdge(hrnX, + hrnY, + f, + false, + edgeY.getBetaNew().pruneBy(hrnX.getAlpha() ) + //edgeY.getBeta().pruneBy( hrnX.getAlpha() ) + ); + addReferenceEdge(hrnX, hrnY, edgeNew); - if( edgeSummary == null ) { - // 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() ) ); + /* + if( f != null ) { + // we can do a strong update here if one of two cases holds + // SAVE FOR LATER, WITHOUT STILL CORRECT + if( (hrnX.getNumReferencers() == 1) || + ( lnX.getNumReferencees() == 1 && hrnX.isSingleObject() ) + ) { + clearReferenceEdgesFrom( hrnX, f, false ); } - addReferenceEdge( hrnSummary, hrnReferencee, edgeMerged ); - } - - // next transfer references _to_ hrn over to hrnSummary - Iterator itrReferencer = hrn.iteratorToReferencers(); - while( itrReferencer.hasNext() ) { - ReferenceEdge edge = itrReferencer.next(); - ReferenceEdge edgeMerged = edge.copy(); - edgeMerged.setDst( hrnSummary ); - - OwnershipNode onReferencer = edge.getSrc(); - ReferenceEdge edgeSummary = onReferencer.getReferenceTo( hrnSummary, edge.getFieldDesc() ); - - if( edgeSummary == null ) { - // the merge is trivial, nothing to be done + addReferenceEdge( hrnX, hrnY, edgeNew ); + + } else { + // if the field is null, or "any" field, then + // look to see if an any field already exists + // and merge with it, otherwise just add the edge + ReferenceEdge edgeExisting = hrnX.getReferenceTo( hrnY, f ); + + if( edgeExisting != null ) { + edgeExisting.setBetaNew( + edgeExisting.getBetaNew().union( edgeNew.getBeta() ) + ); + // a new edge here cannot be reflexive, so existing will + // always be also not reflexive anymore + edgeExisting.setIsInitialParamReflexive( false ); + } 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() ) ); + addReferenceEdge( hrnX, hrnY, edgeNew ); } - - addReferenceEdge( onReferencer, hrnSummary, edgeMerged ); - } + } + */ + } + } - // then merge hrn reachability into hrnSummary - hrnSummary.setAlpha( hrnSummary.getAlpha().union( hrn.getAlpha() ) ); + Iterator nodeItr = nodesWithNewAlpha.iterator(); + while( nodeItr.hasNext() ) { + nodeItr.next().applyAlphaNew(); } + Iterator edgeItr = edgesWithNewBeta.iterator(); + while( edgeItr.hasNext() ) { + edgeItr.next().applyBetaNew(); + } + } + + + public void assignParameterAllocationToTemp(boolean isTask, + TempDescriptor td, + Integer paramIndex) { + assert td != null; + + LabelNode lnParam = getLabelNodeFromTemp(td); + HeapRegionNode hrn = createNewHeapRegionNode(null, + false, + isTask, + false, + true, + null, + null, + "param" + paramIndex); + + // keep track of heap regions that were created for + // parameter labels, the index of the parameter they + // are for is important when resolving method calls + Integer newID = hrn.getID(); + assert !id2paramIndex.containsKey(newID); + assert !id2paramIndex.containsValue(paramIndex); + id2paramIndex.put(newID, paramIndex); + paramIndex2id.put(paramIndex, newID); + + ReachabilitySet beta = new ReachabilitySet(new TokenTuple(newID, + true, + TokenTuple.ARITY_ONE) ); + + // heap regions for parameters are always multiple object (see above) + // and have a reference to themselves, because we can't know the + // structure of memory that is passed into the method. We're assuming + // the worst here. + + ReferenceEdge edgeFromLabel = + new ReferenceEdge(lnParam, hrn, null, false, beta); + + ReferenceEdge edgeReflexive = + new ReferenceEdge(hrn, hrn, null, true, beta); + + addReferenceEdge(lnParam, hrn, edgeFromLabel); + addReferenceEdge(hrn, hrn, edgeReflexive); + } + + + public void assignNewAllocationToTempX(TempDescriptor x, + AllocationSite as) { + assert x != null; + assert as != null; + + age(as); + + // after the age operation the newest (or zero-ith oldest) + // node associated with the allocation site should have + // no references to it as if it were a newly allocated + // heap region, so make a reference to it to complete + // this operation + + Integer idNewest = as.getIthOldest(0); + HeapRegionNode hrnNewest = id2hrn.get(idNewest); + assert hrnNewest != null; + + LabelNode lnX = getLabelNodeFromTemp(x); + clearReferenceEdgesFrom(lnX, null, true); + + ReferenceEdge edgeNew = + new ReferenceEdge(lnX, hrnNewest, null, false, hrnNewest.getAlpha() ); + + addReferenceEdge(lnX, hrnNewest, edgeNew); + } + + + // use the allocation site (unique to entire analysis) to + // locate the heap region nodes in this ownership graph + // that should be aged. The process models the allocation + // of new objects and collects all the oldest allocations + // in a summary node to allow for a finite analysis + // + // There is an additional property of this method. After + // running it on a particular ownership graph (many graphs + // may have heap regions related to the same allocation site) + // the heap region node objects in this ownership graph will be + // allocated. Therefore, after aging a graph for an allocation + // site, attempts to retrieve the heap region nodes using the + // integer id's contained in the allocation site should always + // return non-null heap regions. + public void age(AllocationSite as) { + + // aging adds this allocation site to the graph's + // list of sites that exist in the graph, or does + // nothing if the site is already in the list + allocationSites.add(as); + + // get the summary node for the allocation site in the context + // of this particular ownership graph + HeapRegionNode hrnSummary = getSummaryNode(as); + + // merge oldest node into summary + Integer idK = as.getOldest(); + HeapRegionNode hrnK = id2hrn.get(idK); + mergeIntoSummary(hrnK, hrnSummary); + + // move down the line of heap region nodes + // clobbering the ith and transferring all references + // to and from i-1 to node i. Note that this clobbers + // the oldest node (hrnK) that was just merged into + // the summary + for( int i = allocationDepth - 1; i > 0; --i ) { + + // move references from the i-1 oldest to the ith oldest + Integer idIth = as.getIthOldest(i); + HeapRegionNode hrnI = id2hrn.get(idIth); + Integer idImin1th = as.getIthOldest(i - 1); + HeapRegionNode hrnImin1 = id2hrn.get(idImin1th); + + transferOnto(hrnImin1, hrnI); + } - protected void transferOnto( HeapRegionNode hrnA, HeapRegionNode hrnB ) { + // as stated above, the newest node should have had its + // references moved over to the second oldest, so we wipe newest + // in preparation for being the new object to assign something to + Integer id0th = as.getIthOldest(0); + HeapRegionNode hrn0 = id2hrn.get(id0th); + assert hrn0 != null; - // clear references in and out of node i - clearReferenceEdgesFrom( hrnB, null, true ); - clearReferenceEdgesTo ( hrnB, null, true ); - - // copy each edge in and out of A to B - Iterator itrReferencee = hrnA.iteratorToReferencees(); - while( itrReferencee.hasNext() ) { - ReferenceEdge edge = itrReferencee.next(); - HeapRegionNode hrnReferencee = edge.getDst(); - ReferenceEdge edgeNew = edge.copy(); - edgeNew.setSrc( hrnB ); + // clear all references in and out of newest node + clearReferenceEdgesFrom(hrn0, null, true); + clearReferenceEdgesTo(hrn0, null, true); - addReferenceEdge( hrnB, hrnReferencee, edgeNew ); - } - - Iterator itrReferencer = hrnA.iteratorToReferencers(); - while( itrReferencer.hasNext() ) { - ReferenceEdge edge = itrReferencer.next(); - OwnershipNode onReferencer = edge.getSrc(); - ReferenceEdge edgeNew = edge.copy(); - edgeNew.setDst( hrnB ); - - addReferenceEdge( onReferencer, hrnB, edgeNew ); - } - - // replace hrnB reachability with hrnA's - hrnB.setAlpha( hrnA.getAlpha() ); - } + // now tokens in reachability sets need to "age" also + Iterator itrAllLabelNodes = td2ln.entrySet().iterator(); + while( itrAllLabelNodes.hasNext() ) { + Map.Entry me = (Map.Entry)itrAllLabelNodes.next(); + LabelNode ln = (LabelNode) me.getValue(); - protected void ageTokens( AllocationSite as, ReferenceEdge edge ) { - edge.setBeta( edge.getBeta().ageTokens( as ) ); + Iterator itrEdges = ln.iteratorToReferencees(); + while( itrEdges.hasNext() ) { + ageTokens(as, itrEdges.next() ); + } } - protected void ageTokens( AllocationSite as, HeapRegionNode hrn ) { - hrn.setAlpha( hrn.getAlpha().ageTokens( as ) ); + Iterator itrAllHRNodes = id2hrn.entrySet().iterator(); + while( itrAllHRNodes.hasNext() ) { + Map.Entry me = (Map.Entry)itrAllHRNodes.next(); + HeapRegionNode hrnToAge = (HeapRegionNode) me.getValue(); + + ageTokens(as, hrnToAge); + + Iterator itrEdges = hrnToAge.iteratorToReferencees(); + while( itrEdges.hasNext() ) { + ageTokens(as, itrEdges.next() ); + } } - protected void majorAgeTokens( AllocationSite as, ReferenceEdge edge ) { - //edge.setBeta( edge.getBeta().majorAgeTokens( as ) ); + + // after tokens have been aged, reset newest node's reachability + if( hrn0.isFlagged() ) { + hrn0.setAlpha(new ReachabilitySet(new TokenTupleSet( + new TokenTuple(hrn0) + ) + ).makeCanonical() + ); + } else { + hrn0.setAlpha(new ReachabilitySet(new TokenTupleSet() + ).makeCanonical() + ); + } + } + + + protected HeapRegionNode getSummaryNode(AllocationSite as) { + + Integer idSummary = as.getSummary(); + HeapRegionNode hrnSummary = id2hrn.get(idSummary); + + // If this is null then we haven't touched this allocation site + // in the context of the current ownership graph, so allocate + // heap region nodes appropriate for the entire allocation site. + // This should only happen once per ownership graph per allocation site, + // and a particular integer id can be used to locate the heap region + // in different ownership graphs that represents the same part of an + // allocation site. + if( hrnSummary == null ) { + + boolean hasFlags = false; + if( as.getType().isClass() ) { + hasFlags = as.getType().getClassDesc().hasFlags(); + } + + hrnSummary = createNewHeapRegionNode(idSummary, + false, + hasFlags, + true, + false, + as, + null, + as + "\\n" + as.getType() + "\\nsummary"); + + for( int i = 0; i < as.getAllocationDepth(); ++i ) { + Integer idIth = as.getIthOldest(i); + assert !id2hrn.containsKey(idIth); + createNewHeapRegionNode(idIth, + true, + hasFlags, + false, + false, + as, + null, + as + "\\n" + as.getType() + "\\n" + i + " oldest"); + } } - protected void majorAgeTokens( AllocationSite as, HeapRegionNode hrn ) { - //hrn.setAlpha( hrn.getAlpha().majorAgeTokens( as ) ); + return hrnSummary; + } + + + protected HeapRegionNode getShadowSummaryNode(AllocationSite as) { + + Integer idShadowSummary = -(as.getSummary()); + HeapRegionNode hrnShadowSummary = id2hrn.get(idShadowSummary); + + if( hrnShadowSummary == null ) { + + boolean hasFlags = false; + if( as.getType().isClass() ) { + hasFlags = as.getType().getClassDesc().hasFlags(); + } + + hrnShadowSummary = createNewHeapRegionNode(idShadowSummary, + false, + hasFlags, + true, + false, + as, + null, + as + "\\n" + as.getType() + "\\nshadowSum"); + + for( int i = 0; i < as.getAllocationDepth(); ++i ) { + Integer idShadowIth = -(as.getIthOldest(i)); + assert !id2hrn.containsKey(idShadowIth); + createNewHeapRegionNode(idShadowIth, + true, + hasFlags, + false, + false, + as, + null, + as + "\\n" + as.getType() + "\\n" + i + " shadow"); + } } - - public void resolveMethodCall( FlatCall fc, - boolean isStatic, - FlatMethod fm, - OwnershipGraph ogCallee ) { + return hrnShadowSummary; + } - /* - // verify the existence of allocation sites and their - // shadows from the callee in the context of this caller graph - Iterator asItr = ogCallee.allocationSites.iterator(); - while( asItr.hasNext() ) { - AllocationSite allocSite = asItr.next(); - HeapRegionNode hrnSummary = getSummaryNode ( allocSite ); - HeapRegionNode hrnShadowSummary = getShadowSummaryNode( allocSite ); - } - - // in non-static methods there is a "this" pointer - // that should be taken into account - if( isStatic ) { - assert fc.numArgs() == fm.numParameters(); - } else { - assert fc.numArgs() + 1 == fm.numParameters(); - } - // make a change set to translate callee tokens into caller tokens - ChangeTupleSet C = new ChangeTupleSet().makeCanonical(); + protected void mergeIntoSummary(HeapRegionNode hrn, HeapRegionNode hrnSummary) { + assert hrnSummary.isNewSummary(); - for( int i = 0; i < fm.numParameters(); ++i ) { - - Integer indexParam = new Integer( i ); + // transfer references _from_ hrn over to hrnSummary + Iterator itrReferencee = hrn.iteratorToReferencees(); + while( itrReferencee.hasNext() ) { + ReferenceEdge edge = itrReferencee.next(); + ReferenceEdge edgeMerged = edge.copy(); + edgeMerged.setSrc(hrnSummary); - System.out.println( "In method "+fm+ " on param "+indexParam ); + HeapRegionNode hrnReferencee = edge.getDst(); + ReferenceEdge edgeSummary = hrnSummary.getReferenceTo(hrnReferencee, edge.getFieldDesc() ); - assert ogCallee.paramIndex2id.containsKey( indexParam ); - Integer idParam = ogCallee.paramIndex2id.get( indexParam ); + if( edgeSummary == null ) { + // 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() ) ); + } - assert ogCallee.id2hrn.containsKey( idParam ); - HeapRegionNode hrnParam = ogCallee.id2hrn.get( idParam ); - assert hrnParam != null; + addReferenceEdge(hrnSummary, hrnReferencee, edgeMerged); + } - TokenTupleSet calleeTokenToMatch = - new TokenTupleSet( new TokenTuple( hrnParam ) ).makeCanonical(); + // next transfer references _to_ hrn over to hrnSummary + Iterator itrReferencer = hrn.iteratorToReferencers(); + while( itrReferencer.hasNext() ) { + ReferenceEdge edge = itrReferencer.next(); + ReferenceEdge edgeMerged = edge.copy(); + edgeMerged.setDst(hrnSummary); + + OwnershipNode onReferencer = edge.getSrc(); + ReferenceEdge edgeSummary = onReferencer.getReferenceTo(hrnSummary, edge.getFieldDesc() ); + + if( edgeSummary == null ) { + // 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() ) ); + } + + addReferenceEdge(onReferencer, hrnSummary, edgeMerged); + } - - // now depending on whether the callee is static or not - // we need to account for a "this" argument in order to - // find the matching argument in the caller context - TempDescriptor argTemp; - if( isStatic ) { - argTemp = fc.getArg( indexParam ); - } else { - if( indexParam == 0 ) { - argTemp = fc.getThis(); - } else { - argTemp = fc.getArg( indexParam - 1 ); - } - } - - LabelNode argLabel = getLabelNodeFromTemp( argTemp ); - Iterator argHeapRegionsItr = argLabel.setIteratorToReferencedRegions(); - while( argHeapRegionsItr.hasNext() ) { - Map.Entry meArg = (Map.Entry) argHeapRegionsItr.next(); - HeapRegionNode argHeapRegion = (HeapRegionNode) meArg.getKey(); - ReferenceEdgeProperties repArg = (ReferenceEdgeProperties) meArg.getValue(); - - Iterator ttsItr = repArg.getBeta().iterator(); - while( ttsItr.hasNext() ) { - TokenTupleSet callerTokensToReplace = ttsItr.next(); - - ChangeTuple ct = new ChangeTuple( calleeTokenToMatch, - callerTokensToReplace ).makeCanonical(); - - C = C.union( ct ); - } - } - } + // then merge hrn reachability into hrnSummary + hrnSummary.setAlpha(hrnSummary.getAlpha().union(hrn.getAlpha() ) ); + } - System.out.println( "Applying method call "+fm ); - System.out.println( " Change: "+C ); - - - // the heap regions represented by the arguments (caller graph) - // and heap regions for the parameters (callee graph) - // don't correspond to each other by heap region ID. In fact, - // an argument label node can be referencing several heap regions - // so the parameter label always references a multiple-object - // heap region in order to handle the range of possible contexts - // for a method call. This means we need to make a special mapping - // of argument->parameter regions in order to update the caller graph - - // for every heap region->heap region edge in the - // callee graph, create the matching edge or edges - // in the caller graph - Set sCallee = ogCallee.id2hrn.entrySet(); - Iterator iCallee = sCallee.iterator(); - while( iCallee.hasNext() ) { - Map.Entry meCallee = (Map.Entry) iCallee.next(); - Integer idCallee = (Integer) meCallee.getKey(); - HeapRegionNode hrnCallee = (HeapRegionNode) meCallee.getValue(); - - HeapRegionNode hrnChildCallee = null; - Iterator heapRegionsItrCallee = hrnCallee.setIteratorToReferencedRegions(); - while( heapRegionsItrCallee.hasNext() ) { - Map.Entry me = (Map.Entry) heapRegionsItrCallee.next(); - hrnChildCallee = (HeapRegionNode) me.getKey(); - ReferenceEdgeProperties repC = (ReferenceEdgeProperties) me.getValue(); - - Integer idChildCallee = hrnChildCallee.getID(); - - // only address this edge if it is not a special reflexive edge - if( !repC.isInitialParamReflexive() ) { - - // 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 - // - // 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, - idCallee, - fc, - isStatic ); - - HashSet possibleCallerDsts = - getHRNSetThatPossiblyMapToCalleeHRN( ogCallee, - idChildCallee, - fc, - isStatic ); - - // make every possible pair of {srcSet} -> {dstSet} edges in the caller - Iterator srcItr = possibleCallerSrcs.iterator(); - while( srcItr.hasNext() ) { - HeapRegionNode src = (HeapRegionNode) srcItr.next(); - - Iterator dstItr = possibleCallerDsts.iterator(); - while( dstItr.hasNext() ) { - HeapRegionNode dst = (HeapRegionNode) dstItr.next(); - - addReferenceEdge( src, dst, repC.copy() ); - } - } - } - } - } - */ - } - /* - private HashSet getHRNSetThatPossiblyMapToCalleeHRN( OwnershipGraph ogCallee, - Integer idCallee, - FlatCall fc, - boolean isStatic ) { - - HashSet possibleCallerHRNs = new HashSet(); - - if( ogCallee.id2paramIndex.containsKey( idCallee ) ) { - // the heap region that is part of this - // reference edge won't have a matching ID in the - // caller graph because it is specifically allocated - // for a particular parameter. Use that information - // to find the corresponding argument label in the - // caller in order to create the proper reference edge - // or edges. - assert !id2hrn.containsKey( idCallee ); - - Integer paramIndex = ogCallee.id2paramIndex.get( idCallee ); - TempDescriptor argTemp; - - // now depending on whether the callee is static or not - // we need to account for a "this" argument in order to - // find the matching argument in the caller context - if( isStatic ) { - argTemp = fc.getArg( paramIndex ); - } else { - if( paramIndex == 0 ) { - argTemp = fc.getThis(); - } else { - argTemp = fc.getArg( paramIndex - 1 ); - } - } - - LabelNode argLabel = getLabelNodeFromTemp( argTemp ); - Iterator argHeapRegionsItr = argLabel.setIteratorToReferencedRegions(); - while( argHeapRegionsItr.hasNext() ) { - Map.Entry meArg = (Map.Entry) argHeapRegionsItr.next(); - HeapRegionNode argHeapRegion = (HeapRegionNode) meArg.getKey(); - ReferenceEdgeProperties repArg = (ReferenceEdgeProperties) meArg.getValue(); - - possibleCallerHRNs.add( (HeapRegionNode) argHeapRegion ); - } - - } else { - // this heap region is not a parameter, so it should - // have a matching heap region in the caller graph - assert id2hrn.containsKey( idCallee ); - possibleCallerHRNs.add( id2hrn.get( idCallee ) ); - } + protected void transferOnto(HeapRegionNode hrnA, HeapRegionNode hrnB) { - return possibleCallerHRNs; - } - */ + // clear references in and out of node i + clearReferenceEdgesFrom(hrnB, null, true); + clearReferenceEdgesTo(hrnB, null, true); + // copy each edge in and out of A to B + Iterator itrReferencee = hrnA.iteratorToReferencees(); + while( itrReferencee.hasNext() ) { + ReferenceEdge edge = itrReferencee.next(); + HeapRegionNode hrnReferencee = edge.getDst(); + ReferenceEdge edgeNew = edge.copy(); + edgeNew.setSrc(hrnB); - //////////////////////////////////////////////////// - // in merge() and equals() methods the suffix A - // represents the passed in graph and the suffix - // B refers to the graph in this object - // Merging means to take the incoming graph A and - // merge it into B, so after the operation graph B - // is the final result. - //////////////////////////////////////////////////// - public void merge( OwnershipGraph og ) { + addReferenceEdge(hrnB, hrnReferencee, edgeNew); + } - if( og == null ) { - return; - } + Iterator itrReferencer = hrnA.iteratorToReferencers(); + while( itrReferencer.hasNext() ) { + ReferenceEdge edge = itrReferencer.next(); + OwnershipNode onReferencer = edge.getSrc(); + ReferenceEdge edgeNew = edge.copy(); + edgeNew.setDst(hrnB); - mergeOwnershipNodes ( og ); - mergeReferenceEdges ( og ); - mergeId2paramIndex ( og ); - mergeAllocationSites( og ); + addReferenceEdge(onReferencer, hrnB, edgeNew); } + // replace hrnB reachability with hrnA's + hrnB.setAlpha(hrnA.getAlpha() ); + } - protected void mergeOwnershipNodes( OwnershipGraph og ) { - Set sA = og.id2hrn.entrySet(); - Iterator iA = sA.iterator(); - while( iA.hasNext() ) { - Map.Entry meA = (Map.Entry) iA.next(); - Integer idA = (Integer) meA.getKey(); - HeapRegionNode hrnA = (HeapRegionNode) meA.getValue(); - - // 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 ); - - } 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() ) ); - } - } - // now add any label nodes that are in graph B but - // not in A - sA = og.td2ln.entrySet(); - iA = sA.iterator(); - while( iA.hasNext() ) { - Map.Entry meA = (Map.Entry) iA.next(); - TempDescriptor tdA = (TempDescriptor) meA.getKey(); - LabelNode lnA = (LabelNode) meA.getValue(); - - // if the label doesn't exist in B, allocate and add it - LabelNode lnB = getLabelNodeFromTemp( tdA ); - } - } + protected void ageTokens(AllocationSite as, ReferenceEdge edge) { + edge.setBeta(edge.getBeta().ageTokens(as) ); + } - protected void mergeReferenceEdges( OwnershipGraph og ) { - - // heap regions - Set sA = og.id2hrn.entrySet(); - Iterator iA = sA.iterator(); - while( iA.hasNext() ) { - Map.Entry meA = (Map.Entry) iA.next(); - Integer idA = (Integer) meA.getKey(); - HeapRegionNode hrnA = (HeapRegionNode) meA.getValue(); - - 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.getFieldDesc() == edgeA.getFieldDesc() ) { - 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() ) - ); - if( !edgeA.isInitialParamReflexive() ) { - edgeToMerge.setIsInitialParamReflexive( false ); - } - } - } - } + protected void ageTokens(AllocationSite as, HeapRegionNode hrn) { + hrn.setAlpha(hrn.getAlpha().ageTokens(as) ); + } - // and then again with label nodes - sA = og.td2ln.entrySet(); - iA = sA.iterator(); - while( iA.hasNext() ) { - Map.Entry meA = (Map.Entry) iA.next(); - TempDescriptor tdA = (TempDescriptor) meA.getKey(); - LabelNode lnA = (LabelNode) meA.getValue(); - - 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; - - // labels never have edges with a field - //assert edgeA.getFieldDesc() == null; - - Iterator heapRegionsItrB = lnB.iteratorToReferencees(); - while( heapRegionsItrB.hasNext() && - edgeToMerge == null ) { - - ReferenceEdge edgeB = heapRegionsItrB.next(); - HeapRegionNode hrnChildB = edgeB.getDst(); - Integer idChildB = hrnChildB.getID(); - - // labels never have edges with a field - //assert edgeB.getFieldDesc() == null; - - // don't use the ReferenceEdge.equals() here because - // we're talking about existence between graphs - if( idChildB.equals( idChildA ) && - edgeB.getFieldDesc() == edgeA.getFieldDesc() ) { - 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() ) - ); - if( !edgeA.isInitialParamReflexive() ) { - edgeToMerge.setIsInitialParamReflexive( false ); - } - } - } - } - } + protected void majorAgeTokens(AllocationSite as, ReferenceEdge edge) { + //edge.setBeta( edge.getBeta().majorAgeTokens( as ) ); + } - // you should only merge ownership graphs that have the - // same number of parameters, or if one or both parameter - // index tables are empty - protected void mergeId2paramIndex( OwnershipGraph og ) { - if( id2paramIndex.size() == 0 ) { - id2paramIndex = og.id2paramIndex; - paramIndex2id = og.paramIndex2id; - return; - } + protected void majorAgeTokens(AllocationSite as, HeapRegionNode hrn) { + //hrn.setAlpha( hrn.getAlpha().majorAgeTokens( as ) ); + } - if( og.id2paramIndex.size() == 0 ) { - return; - } - assert id2paramIndex.size() == og.id2paramIndex.size(); - } + public void resolveMethodCall(FlatCall fc, + boolean isStatic, + FlatMethod fm, + OwnershipGraph ogCallee) { - protected void mergeAllocationSites( OwnershipGraph og ) { - allocationSites.addAll( og.allocationSites ); - } + /* + // verify the existence of allocation sites and their + // shadows from the callee in the context of this caller graph + Iterator asItr = ogCallee.allocationSites.iterator(); + while( asItr.hasNext() ) { + AllocationSite allocSite = asItr.next(); + HeapRegionNode hrnSummary = getSummaryNode ( allocSite ); + HeapRegionNode hrnShadowSummary = getShadowSummaryNode( allocSite ); + } + + // in non-static methods there is a "this" pointer + // that should be taken into account + if( isStatic ) { + assert fc.numArgs() == fm.numParameters(); + } else { + assert fc.numArgs() + 1 == fm.numParameters(); + } + + // make a change set to translate callee tokens into caller tokens + ChangeTupleSet C = new ChangeTupleSet().makeCanonical(); + + for( int i = 0; i < fm.numParameters(); ++i ) { + + Integer indexParam = new Integer( i ); + + System.out.println( "In method "+fm+ " on param "+indexParam ); + + assert ogCallee.paramIndex2id.containsKey( indexParam ); + Integer idParam = ogCallee.paramIndex2id.get( indexParam ); + + assert ogCallee.id2hrn.containsKey( idParam ); + HeapRegionNode hrnParam = ogCallee.id2hrn.get( idParam ); + assert hrnParam != null; + + TokenTupleSet calleeTokenToMatch = + new TokenTupleSet( new TokenTuple( hrnParam ) ).makeCanonical(); + + + // now depending on whether the callee is static or not + // we need to account for a "this" argument in order to + // find the matching argument in the caller context + TempDescriptor argTemp; + if( isStatic ) { + argTemp = fc.getArg( indexParam ); + } else { + if( indexParam == 0 ) { + argTemp = fc.getThis(); + } else { + argTemp = fc.getArg( indexParam - 1 ); + } + } + LabelNode argLabel = getLabelNodeFromTemp( argTemp ); + Iterator argHeapRegionsItr = argLabel.setIteratorToReferencedRegions(); + while( argHeapRegionsItr.hasNext() ) { + Map.Entry meArg = (Map.Entry) argHeapRegionsItr.next(); + HeapRegionNode argHeapRegion = (HeapRegionNode) meArg.getKey(); + ReferenceEdgeProperties repArg = (ReferenceEdgeProperties) meArg.getValue(); + Iterator ttsItr = repArg.getBeta().iterator(); + while( ttsItr.hasNext() ) { + TokenTupleSet callerTokensToReplace = ttsItr.next(); - // it is necessary in the equals() member functions - // to "check both ways" when comparing the data - // structures of two graphs. For instance, if all - // edges between heap region nodes in graph A are - // present and equal in graph B it is not sufficient - // to say the graphs are equal. Consider that there - // may be edges in graph B that are not in graph A. - // the only way to know that all edges in both graphs - // are equally present is to iterate over both data - // structures and compare against the other graph. - public boolean equals( OwnershipGraph og ) { + ChangeTuple ct = new ChangeTuple( calleeTokenToMatch, + callerTokensToReplace ).makeCanonical(); - if( og == null ) { - return false; + C = C.union( ct ); + } } - - if( !areHeapRegionNodesEqual( og ) ) { - return false; - } + } + + System.out.println( "Applying method call "+fm ); + System.out.println( " Change: "+C ); + + + // the heap regions represented by the arguments (caller graph) + // and heap regions for the parameters (callee graph) + // don't correspond to each other by heap region ID. In fact, + // an argument label node can be referencing several heap regions + // so the parameter label always references a multiple-object + // heap region in order to handle the range of possible contexts + // for a method call. This means we need to make a special mapping + // of argument->parameter regions in order to update the caller graph + + // for every heap region->heap region edge in the + // callee graph, create the matching edge or edges + // in the caller graph + Set sCallee = ogCallee.id2hrn.entrySet(); + Iterator iCallee = sCallee.iterator(); + while( iCallee.hasNext() ) { + Map.Entry meCallee = (Map.Entry) iCallee.next(); + Integer idCallee = (Integer) meCallee.getKey(); + HeapRegionNode hrnCallee = (HeapRegionNode) meCallee.getValue(); + + HeapRegionNode hrnChildCallee = null; + Iterator heapRegionsItrCallee = hrnCallee.setIteratorToReferencedRegions(); + while( heapRegionsItrCallee.hasNext() ) { + Map.Entry me = (Map.Entry) heapRegionsItrCallee.next(); + hrnChildCallee = (HeapRegionNode) me.getKey(); + ReferenceEdgeProperties repC = (ReferenceEdgeProperties) me.getValue(); + + Integer idChildCallee = hrnChildCallee.getID(); + + // only address this edge if it is not a special reflexive edge + if( !repC.isInitialParamReflexive() ) { + + // 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 + // + // 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, + idCallee, + fc, + isStatic ); + + HashSet possibleCallerDsts = + getHRNSetThatPossiblyMapToCalleeHRN( ogCallee, + idChildCallee, + fc, + isStatic ); + + // make every possible pair of {srcSet} -> {dstSet} edges in the caller + Iterator srcItr = possibleCallerSrcs.iterator(); + while( srcItr.hasNext() ) { + HeapRegionNode src = (HeapRegionNode) srcItr.next(); + + Iterator dstItr = possibleCallerDsts.iterator(); + while( dstItr.hasNext() ) { + HeapRegionNode dst = (HeapRegionNode) dstItr.next(); + + addReferenceEdge( src, dst, repC.copy() ); + } + } + } + } + } + */ + } + + /* + private HashSet getHRNSetThatPossiblyMapToCalleeHRN( OwnershipGraph ogCallee, + Integer idCallee, + FlatCall fc, + boolean isStatic ) { + + HashSet possibleCallerHRNs = new HashSet(); + + if( ogCallee.id2paramIndex.containsKey( idCallee ) ) { + // the heap region that is part of this + // reference edge won't have a matching ID in the + // caller graph because it is specifically allocated + // for a particular parameter. Use that information + // to find the corresponding argument label in the + // caller in order to create the proper reference edge + // or edges. + assert !id2hrn.containsKey( idCallee ); + + Integer paramIndex = ogCallee.id2paramIndex.get( idCallee ); + TempDescriptor argTemp; + + // now depending on whether the callee is static or not + // we need to account for a "this" argument in order to + // find the matching argument in the caller context + if( isStatic ) { + argTemp = fc.getArg( paramIndex ); + } else { + if( paramIndex == 0 ) { + argTemp = fc.getThis(); + } else { + argTemp = fc.getArg( paramIndex - 1 ); + } + } + + LabelNode argLabel = getLabelNodeFromTemp( argTemp ); + Iterator argHeapRegionsItr = argLabel.setIteratorToReferencedRegions(); + while( argHeapRegionsItr.hasNext() ) { + Map.Entry meArg = (Map.Entry) argHeapRegionsItr.next(); + HeapRegionNode argHeapRegion = (HeapRegionNode) meArg.getKey(); + ReferenceEdgeProperties repArg = (ReferenceEdgeProperties) meArg.getValue(); + + possibleCallerHRNs.add( (HeapRegionNode) argHeapRegion ); + } + + } else { + // this heap region is not a parameter, so it should + // have a matching heap region in the caller graph + assert id2hrn.containsKey( idCallee ); + possibleCallerHRNs.add( id2hrn.get( idCallee ) ); + } + + return possibleCallerHRNs; + } + */ + + + //////////////////////////////////////////////////// + // in merge() and equals() methods the suffix A + // represents the passed in graph and the suffix + // B refers to the graph in this object + // Merging means to take the incoming graph A and + // merge it into B, so after the operation graph B + // is the final result. + //////////////////////////////////////////////////// + public void merge(OwnershipGraph og) { + + if( og == null ) { + return; + } + + mergeOwnershipNodes(og); + mergeReferenceEdges(og); + mergeId2paramIndex(og); + mergeAllocationSites(og); + } + + + protected void mergeOwnershipNodes(OwnershipGraph og) { + Set sA = og.id2hrn.entrySet(); + Iterator iA = sA.iterator(); + while( iA.hasNext() ) { + Map.Entry meA = (Map.Entry)iA.next(); + Integer idA = (Integer) meA.getKey(); + HeapRegionNode hrnA = (HeapRegionNode) meA.getValue(); + + // 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); + + } 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() ) ); + } + } - if( !areLabelNodesEqual( og ) ) { - return false; + // now add any label nodes that are in graph B but + // not in A + sA = og.td2ln.entrySet(); + iA = sA.iterator(); + while( iA.hasNext() ) { + Map.Entry meA = (Map.Entry)iA.next(); + TempDescriptor tdA = (TempDescriptor) meA.getKey(); + LabelNode lnA = (LabelNode) meA.getValue(); + + // if the label doesn't exist in B, allocate and add it + LabelNode lnB = getLabelNodeFromTemp(tdA); + } + } + + protected void mergeReferenceEdges(OwnershipGraph og) { + + // heap regions + Set sA = og.id2hrn.entrySet(); + Iterator iA = sA.iterator(); + while( iA.hasNext() ) { + Map.Entry meA = (Map.Entry)iA.next(); + Integer idA = (Integer) meA.getKey(); + HeapRegionNode hrnA = (HeapRegionNode) meA.getValue(); + + 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.getFieldDesc() == edgeA.getFieldDesc() ) { + edgeToMerge = edgeB; + } } - if( !areReferenceEdgesEqual( og ) ) { - return false; + // 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() ) + ); + if( !edgeA.isInitialParamReflexive() ) { + edgeToMerge.setIsInitialParamReflexive(false); + } } + } + } - if( !areId2paramIndexEqual( og ) ) { - return false; + // and then again with label nodes + sA = og.td2ln.entrySet(); + iA = sA.iterator(); + while( iA.hasNext() ) { + Map.Entry meA = (Map.Entry)iA.next(); + TempDescriptor tdA = (TempDescriptor) meA.getKey(); + LabelNode lnA = (LabelNode) meA.getValue(); + + 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; + + // labels never have edges with a field + //assert edgeA.getFieldDesc() == null; + + Iterator heapRegionsItrB = lnB.iteratorToReferencees(); + while( heapRegionsItrB.hasNext() && + edgeToMerge == null ) { + + ReferenceEdge edgeB = heapRegionsItrB.next(); + HeapRegionNode hrnChildB = edgeB.getDst(); + Integer idChildB = hrnChildB.getID(); + + // labels never have edges with a field + //assert edgeB.getFieldDesc() == null; + + // don't use the ReferenceEdge.equals() here because + // we're talking about existence between graphs + if( idChildB.equals(idChildA) && + edgeB.getFieldDesc() == edgeA.getFieldDesc() ) { + edgeToMerge = edgeB; + } } - // if everything is equal up to this point, - // assert that allocationSites is also equal-- - // this data is redundant and kept for efficiency - assert allocationSites.equals( og.allocationSites ); + // 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() ) + ); + if( !edgeA.isInitialParamReflexive() ) { + edgeToMerge.setIsInitialParamReflexive(false); + } + } + } + } + } + + // you should only merge ownership graphs that have the + // same number of parameters, or if one or both parameter + // index tables are empty + protected void mergeId2paramIndex(OwnershipGraph og) { + if( id2paramIndex.size() == 0 ) { + id2paramIndex = og.id2paramIndex; + paramIndex2id = og.paramIndex2id; + return; + } - return true; + if( og.id2paramIndex.size() == 0 ) { + return; } - protected boolean areHeapRegionNodesEqual( OwnershipGraph og ) { + assert id2paramIndex.size() == og.id2paramIndex.size(); + } - if( !areallHRNinAalsoinBandequal( this, og ) ) { - return false; - } + protected void mergeAllocationSites(OwnershipGraph og) { + allocationSites.addAll(og.allocationSites); + } - if( !areallHRNinAalsoinBandequal( og, this ) ) { - return false; - } - return true; + + // it is necessary in the equals() member functions + // to "check both ways" when comparing the data + // structures of two graphs. For instance, if all + // edges between heap region nodes in graph A are + // present and equal in graph B it is not sufficient + // to say the graphs are equal. Consider that there + // may be edges in graph B that are not in graph A. + // the only way to know that all edges in both graphs + // are equally present is to iterate over both data + // structures and compare against the other graph. + public boolean equals(OwnershipGraph og) { + + if( og == null ) { + return false; } - static protected boolean areallHRNinAalsoinBandequal( OwnershipGraph ogA, - OwnershipGraph ogB ) { - Set sA = ogA.id2hrn.entrySet(); - Iterator iA = sA.iterator(); - while( iA.hasNext() ) { - Map.Entry meA = (Map.Entry) iA.next(); - Integer idA = (Integer) meA.getKey(); - HeapRegionNode hrnA = (HeapRegionNode) meA.getValue(); - - if( !ogB.id2hrn.containsKey( idA ) ) { - return false; - } + if( !areHeapRegionNodesEqual(og) ) { + return false; + } - HeapRegionNode hrnB = ogB.id2hrn.get( idA ); - if( !hrnA.equalsIncludingAlpha( hrnB ) ) { - return false; - } - } + if( !areLabelNodesEqual(og) ) { + return false; + } - return true; + if( !areReferenceEdgesEqual(og) ) { + return false; } + if( !areId2paramIndexEqual(og) ) { + return false; + } - protected boolean areLabelNodesEqual( OwnershipGraph og ) { + // if everything is equal up to this point, + // assert that allocationSites is also equal-- + // this data is redundant and kept for efficiency + assert allocationSites.equals(og.allocationSites); - if( !areallLNinAalsoinBandequal( this, og ) ) { - return false; - } + return true; + } - if( !areallLNinAalsoinBandequal( og, this ) ) { - return false; - } + protected boolean areHeapRegionNodesEqual(OwnershipGraph og) { - return true; + if( !areallHRNinAalsoinBandequal(this, og) ) { + return false; } - static protected boolean areallLNinAalsoinBandequal( OwnershipGraph ogA, - OwnershipGraph ogB ) { - Set sA = ogA.td2ln.entrySet(); - Iterator iA = sA.iterator(); - while( iA.hasNext() ) { - Map.Entry meA = (Map.Entry) iA.next(); - TempDescriptor tdA = (TempDescriptor) meA.getKey(); - - if( !ogB.td2ln.containsKey( tdA ) ) { - return false; - } - } - - return true; + if( !areallHRNinAalsoinBandequal(og, this) ) { + return false; } + return true; + } - protected boolean areReferenceEdgesEqual( OwnershipGraph og ) { - if( !areallREinAandBequal( this, og ) ) { - return false; - } + static protected boolean areallHRNinAalsoinBandequal(OwnershipGraph ogA, + OwnershipGraph ogB) { + Set sA = ogA.id2hrn.entrySet(); + Iterator iA = sA.iterator(); + while( iA.hasNext() ) { + Map.Entry meA = (Map.Entry)iA.next(); + Integer idA = (Integer) meA.getKey(); + HeapRegionNode hrnA = (HeapRegionNode) meA.getValue(); - return true; - } + if( !ogB.id2hrn.containsKey(idA) ) { + return false; + } - static protected boolean areallREinAandBequal( OwnershipGraph ogA, - OwnershipGraph ogB ) { + HeapRegionNode hrnB = ogB.id2hrn.get(idA); + if( !hrnA.equalsIncludingAlpha(hrnB) ) { + return false; + } + } - // check all the heap region->heap region edges - Set sA = ogA.id2hrn.entrySet(); - Iterator iA = sA.iterator(); - while( iA.hasNext() ) { - Map.Entry meA = (Map.Entry) iA.next(); - Integer idA = (Integer) meA.getKey(); - HeapRegionNode hrnA = (HeapRegionNode) meA.getValue(); + return true; + } - // we should have already checked that the same - // heap regions exist in both graphs - assert ogB.id2hrn.containsKey( idA ); - if( !areallREfromAequaltoB( ogA, hrnA, ogB ) ) { - return false; - } + protected boolean areLabelNodesEqual(OwnershipGraph og) { - // then check every edge in B for presence in A, starting - // from the same parent HeapRegionNode - HeapRegionNode hrnB = ogB.id2hrn.get( idA ); + if( !areallLNinAalsoinBandequal(this, og) ) { + return false; + } - if( !areallREfromAequaltoB( ogB, hrnB, ogA ) ) { - return false; - } - } + if( !areallLNinAalsoinBandequal(og, this) ) { + return false; + } - // then check all the label->heap region edges - sA = ogA.td2ln.entrySet(); - iA = sA.iterator(); - while( iA.hasNext() ) { - Map.Entry meA = (Map.Entry) iA.next(); - TempDescriptor tdA = (TempDescriptor) meA.getKey(); - LabelNode lnA = (LabelNode) meA.getValue(); + return true; + } - // we should have already checked that the same - // label nodes exist in both graphs - assert ogB.td2ln.containsKey( tdA ); + static protected boolean areallLNinAalsoinBandequal(OwnershipGraph ogA, + OwnershipGraph ogB) { + Set sA = ogA.td2ln.entrySet(); + Iterator iA = sA.iterator(); + while( iA.hasNext() ) { + Map.Entry meA = (Map.Entry)iA.next(); + TempDescriptor tdA = (TempDescriptor) meA.getKey(); - if( !areallREfromAequaltoB( ogA, lnA, ogB ) ) { - return false; - } + if( !ogB.td2ln.containsKey(tdA) ) { + return false; + } + } - // then check every edge in B for presence in A, starting - // from the same parent LabelNode - LabelNode lnB = ogB.td2ln.get( tdA ); + return true; + } - if( !areallREfromAequaltoB( ogB, lnB, ogA ) ) { - return false; - } - } - return true; + protected boolean areReferenceEdgesEqual(OwnershipGraph og) { + if( !areallREinAandBequal(this, og) ) { + return false; } + return true; + } - static protected boolean areallREfromAequaltoB( OwnershipGraph ogA, - OwnershipNode onA, - OwnershipGraph ogB ) { - - Iterator itrA = onA.iteratorToReferencees(); - while( itrA.hasNext() ) { - ReferenceEdge edgeA = itrA.next(); - HeapRegionNode hrnChildA = edgeA.getDst(); - Integer idChildA = hrnChildA.getID(); + static protected boolean areallREinAandBequal(OwnershipGraph ogA, + OwnershipGraph ogB) { - assert ogB.id2hrn.containsKey( idChildA ); + // check all the heap region->heap region edges + Set sA = ogA.id2hrn.entrySet(); + Iterator iA = sA.iterator(); + while( iA.hasNext() ) { + Map.Entry meA = (Map.Entry)iA.next(); + Integer idA = (Integer) meA.getKey(); + HeapRegionNode hrnA = (HeapRegionNode) meA.getValue(); - // at this point we know an edge in graph A exists - // onA -> idChildA, does this exact edge exist in B? - boolean edgeFound = false; + // we should have already checked that the same + // heap regions exist in both graphs + assert ogB.id2hrn.containsKey(idA); - OwnershipNode onB = null; - if( onA instanceof HeapRegionNode ) { - HeapRegionNode hrnA = (HeapRegionNode) onA; - onB = ogB.id2hrn.get( hrnA.getID() ); - } else { - LabelNode lnA = (LabelNode) onA; - onB = ogB.td2ln.get( lnA.getTempDescriptor() ); - } + if( !areallREfromAequaltoB(ogA, hrnA, ogB) ) { + return false; + } - Iterator itrB = onB.iteratorToReferencees(); - while( itrB.hasNext() ) { - ReferenceEdge edgeB = itrB.next(); - HeapRegionNode hrnChildB = edgeB.getDst(); - Integer idChildB = hrnChildB.getID(); - - if( idChildA.equals( idChildB ) && - edgeA.getFieldDesc() == edgeB.getFieldDesc() ) { - - // 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; - //} else { - //return false; - } - } - } + // then check every edge in B for presence in A, starting + // from the same parent HeapRegionNode + HeapRegionNode hrnB = ogB.id2hrn.get(idA); - if( !edgeFound ) { - return false; - } - } - - return true; + if( !areallREfromAequaltoB(ogB, hrnB, ogA) ) { + return false; + } } + // then check all the label->heap region edges + sA = ogA.td2ln.entrySet(); + iA = sA.iterator(); + while( iA.hasNext() ) { + Map.Entry meA = (Map.Entry)iA.next(); + TempDescriptor tdA = (TempDescriptor) meA.getKey(); + LabelNode lnA = (LabelNode) meA.getValue(); + + // we should have already checked that the same + // label nodes exist in both graphs + assert ogB.td2ln.containsKey(tdA); + + if( !areallREfromAequaltoB(ogA, lnA, ogB) ) { + return false; + } + + // then check every edge in B for presence in A, starting + // from the same parent LabelNode + LabelNode lnB = ogB.td2ln.get(tdA); - protected boolean areId2paramIndexEqual( OwnershipGraph og ) { - return id2paramIndex.size() == og.id2paramIndex.size(); + if( !areallREfromAequaltoB(ogB, lnB, ogA) ) { + return false; + } } + return true; + } - /* - // given a set B of heap region node ID's, return the set of heap - // region node ID's that is reachable from B - public HashSet getReachableSet( HashSet idSetB ) { - - HashSet toVisit = new HashSet(); - HashSet visited = new HashSet(); - - // initial nodes to visit are from set B - Iterator initialItr = idSetB.iterator(); - while( initialItr.hasNext() ) { - Integer idInitial = (Integer) initialItr.next(); - assert id2hrn.contains( idInitial ); - HeapRegionNode hrnInitial = id2hrn.get( idInitial ); - toVisit.add( hrnInitial ); - } - HashSet idSetReachableFromB = new HashSet(); + static protected boolean areallREfromAequaltoB(OwnershipGraph ogA, + OwnershipNode onA, + OwnershipGraph ogB) { - // do a heap traversal - while( !toVisit.isEmpty() ) { - HeapRegionNode hrnVisited = (HeapRegionNode) toVisit.iterator().next(); - toVisit.remove( hrnVisited ); - visited.add ( hrnVisited ); + Iterator itrA = onA.iteratorToReferencees(); + while( itrA.hasNext() ) { + ReferenceEdge edgeA = itrA.next(); + HeapRegionNode hrnChildA = edgeA.getDst(); + Integer idChildA = hrnChildA.getID(); - // for every node visited, add it to the total - // reachable set - idSetReachableFromB.add( hrnVisited.getID() ); + assert ogB.id2hrn.containsKey(idChildA); - // find other reachable nodes - Iterator referenceeItr = hrnVisited.setIteratorToReferencedRegions(); - while( referenceeItr.hasNext() ) { - Map.Entry me = (Map.Entry) referenceeItr.next(); - HeapRegionNode hrnReferencee = (HeapRegionNode) me.getKey(); - ReferenceEdgeProperties rep = (ReferenceEdgeProperties) me.getValue(); + // at this point we know an edge in graph A exists + // onA -> idChildA, does this exact edge exist in B? + boolean edgeFound = false; - if( !visited.contains( hrnReferencee ) ) { - toVisit.add( hrnReferencee ); - } - } - } + OwnershipNode onB = null; + if( onA instanceof HeapRegionNode ) { + HeapRegionNode hrnA = (HeapRegionNode) onA; + onB = ogB.id2hrn.get(hrnA.getID() ); + } else { + LabelNode lnA = (LabelNode) onA; + onB = ogB.td2ln.get(lnA.getTempDescriptor() ); + } - return idSetReachableFromB; - } + Iterator itrB = onB.iteratorToReferencees(); + while( itrB.hasNext() ) { + ReferenceEdge edgeB = itrB.next(); + HeapRegionNode hrnChildB = edgeB.getDst(); + Integer idChildB = hrnChildB.getID(); + if( idChildA.equals(idChildB) && + edgeA.getFieldDesc() == edgeB.getFieldDesc() ) { - // used to find if a heap region can possibly have a reference to - // any of the heap regions in the given set - // if the id supplied is in the set, then a self-referencing edge - // would return true, but that special case is specifically allowed - // meaning that it isn't an external alias - public boolean canIdReachSet( Integer id, HashSet idSet ) { - - assert id2hrn.contains( id ); - HeapRegionNode hrn = id2hrn.get( id ); - - - //HashSet hrnSet = new HashSet(); - - //Iterator i = idSet.iterator(); - //while( i.hasNext() ) { - // Integer idFromSet = (Integer) i.next(); - // assert id2hrn.contains( idFromSet ); - // hrnSet.add( id2hrn.get( idFromSet ) ); - //} - - - // do a traversal from hrn and see if any of the - // heap regions from the set come up during that - HashSet toVisit = new HashSet(); - HashSet visited = new HashSet(); - - toVisit.add( hrn ); - while( !toVisit.isEmpty() ) { - HeapRegionNode hrnVisited = (HeapRegionNode) toVisit.iterator().next(); - toVisit.remove( hrnVisited ); - visited.add ( hrnVisited ); - - Iterator referenceeItr = hrnVisited.setIteratorToReferencedRegions(); - while( referenceeItr.hasNext() ) { - Map.Entry me = (Map.Entry) referenceeItr.next(); - HeapRegionNode hrnReferencee = (HeapRegionNode) me.getKey(); - ReferenceEdgeProperties rep = (ReferenceEdgeProperties) me.getValue(); - - if( idSet.contains( hrnReferencee.getID() ) ) { - if( !id.equals( hrnReferencee.getID() ) ) { - return true; - } - } - - if( !visited.contains( hrnReferencee ) ) { - toVisit.add( hrnReferencee ); - } - } + // 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; + //} else { + //return false; + } } + } + if( !edgeFound ) { return false; - } - */ - - - // for writing ownership graphs to dot files - public void writeGraph( Descriptor methodDesc, - FlatNode fn, - boolean writeLabels, - boolean labelSelect, - boolean pruneGarbage, - boolean writeReferencers - ) throws java.io.IOException { - writeGraph( - methodDesc.getSymbol() + - methodDesc.getNum() + - fn.toString(), - writeLabels, - labelSelect, - pruneGarbage, - writeReferencers - ); + } } - public void writeGraph( Descriptor methodDesc, - FlatNode fn, - boolean writeLabels, - boolean writeReferencers - ) throws java.io.IOException { - writeGraph( - methodDesc.getSymbol() + - methodDesc.getNum() + - fn.toString(), - writeLabels, - false, - false, - writeReferencers - ); - } + return true; + } + + + protected boolean areId2paramIndexEqual(OwnershipGraph og) { + return id2paramIndex.size() == og.id2paramIndex.size(); + } + - public void writeGraph( Descriptor methodDesc, - boolean writeLabels, - boolean writeReferencers - ) throws java.io.IOException { - writeGraph( - methodDesc.getSymbol() + - methodDesc.getNum() + - "COMPLETE", - writeLabels, - false, - false, - writeReferencers - ); - } + /* + // given a set B of heap region node ID's, return the set of heap + // region node ID's that is reachable from B + public HashSet getReachableSet( HashSet idSetB ) { - public void writeGraph( Descriptor methodDesc, - boolean writeLabels, - boolean labelSelect, - boolean pruneGarbage, - boolean writeReferencers - ) throws java.io.IOException { - writeGraph( - methodDesc.getSymbol() + - methodDesc.getNum() + - "COMPLETE", - writeLabels, - labelSelect, - pruneGarbage, - writeReferencers - ); + HashSet toVisit = new HashSet(); + HashSet visited = new HashSet(); + + // initial nodes to visit are from set B + Iterator initialItr = idSetB.iterator(); + while( initialItr.hasNext() ) { + Integer idInitial = (Integer) initialItr.next(); + assert id2hrn.contains( idInitial ); + HeapRegionNode hrnInitial = id2hrn.get( idInitial ); + toVisit.add( hrnInitial ); + } + + HashSet idSetReachableFromB = new HashSet(); + + // do a heap traversal + while( !toVisit.isEmpty() ) { + HeapRegionNode hrnVisited = (HeapRegionNode) toVisit.iterator().next(); + toVisit.remove( hrnVisited ); + visited.add ( hrnVisited ); + + // for every node visited, add it to the total + // reachable set + idSetReachableFromB.add( hrnVisited.getID() ); + + // find other reachable nodes + Iterator referenceeItr = hrnVisited.setIteratorToReferencedRegions(); + while( referenceeItr.hasNext() ) { + Map.Entry me = (Map.Entry) referenceeItr.next(); + HeapRegionNode hrnReferencee = (HeapRegionNode) me.getKey(); + ReferenceEdgeProperties rep = (ReferenceEdgeProperties) me.getValue(); + + if( !visited.contains( hrnReferencee ) ) { + toVisit.add( hrnReferencee ); + } + } + } + + return idSetReachableFromB; + } + + + // used to find if a heap region can possibly have a reference to + // any of the heap regions in the given set + // if the id supplied is in the set, then a self-referencing edge + // would return true, but that special case is specifically allowed + // meaning that it isn't an external alias + public boolean canIdReachSet( Integer id, HashSet idSet ) { + + assert id2hrn.contains( id ); + HeapRegionNode hrn = id2hrn.get( id ); + + + //HashSet hrnSet = new HashSet(); + + //Iterator i = idSet.iterator(); + //while( i.hasNext() ) { + // Integer idFromSet = (Integer) i.next(); + // assert id2hrn.contains( idFromSet ); + // hrnSet.add( id2hrn.get( idFromSet ) ); + //} + + + // do a traversal from hrn and see if any of the + // heap regions from the set come up during that + HashSet toVisit = new HashSet(); + HashSet visited = new HashSet(); + + toVisit.add( hrn ); + while( !toVisit.isEmpty() ) { + HeapRegionNode hrnVisited = (HeapRegionNode) toVisit.iterator().next(); + toVisit.remove( hrnVisited ); + visited.add ( hrnVisited ); + + Iterator referenceeItr = hrnVisited.setIteratorToReferencedRegions(); + while( referenceeItr.hasNext() ) { + Map.Entry me = (Map.Entry) referenceeItr.next(); + HeapRegionNode hrnReferencee = (HeapRegionNode) me.getKey(); + ReferenceEdgeProperties rep = (ReferenceEdgeProperties) me.getValue(); + + if( idSet.contains( hrnReferencee.getID() ) ) { + if( !id.equals( hrnReferencee.getID() ) ) { + return true; + } + } + + if( !visited.contains( hrnReferencee ) ) { + toVisit.add( hrnReferencee ); + } + } + } + + return false; + } + */ + + + // for writing ownership graphs to dot files + public void writeGraph(Descriptor methodDesc, + FlatNode fn, + boolean writeLabels, + boolean labelSelect, + boolean pruneGarbage, + boolean writeReferencers + ) throws java.io.IOException { + writeGraph( + methodDesc.getSymbol() + + methodDesc.getNum() + + fn.toString(), + writeLabels, + labelSelect, + pruneGarbage, + writeReferencers + ); + } + + public void writeGraph(Descriptor methodDesc, + FlatNode fn, + boolean writeLabels, + boolean writeReferencers + ) throws java.io.IOException { + writeGraph( + methodDesc.getSymbol() + + methodDesc.getNum() + + fn.toString(), + writeLabels, + false, + false, + writeReferencers + ); + } + + public void writeGraph(Descriptor methodDesc, + boolean writeLabels, + boolean writeReferencers + ) throws java.io.IOException { + writeGraph( + methodDesc.getSymbol() + + methodDesc.getNum() + + "COMPLETE", + writeLabels, + false, + false, + writeReferencers + ); + } + + public void writeGraph(Descriptor methodDesc, + boolean writeLabels, + boolean labelSelect, + boolean pruneGarbage, + boolean writeReferencers + ) throws java.io.IOException { + writeGraph( + methodDesc.getSymbol() + + methodDesc.getNum() + + "COMPLETE", + writeLabels, + labelSelect, + pruneGarbage, + writeReferencers + ); + } + + public void writeGraph(String graphName, + boolean writeLabels, + boolean labelSelect, + boolean pruneGarbage, + boolean writeReferencers + ) throws java.io.IOException { + + // remove all non-word characters from the graph name so + // the filename and identifier in dot don't cause errors + graphName = graphName.replaceAll("[\\W]", ""); + + BufferedWriter bw = new BufferedWriter(new FileWriter(graphName+".dot") ); + bw.write("digraph "+graphName+" {\n"); + //bw.write( " size=\"7.5,10\";\n" ); + + HashSet visited = new HashSet(); + + // then visit every heap region node + if( !pruneGarbage ) { + Set s = id2hrn.entrySet(); + Iterator i = s.iterator(); + while( i.hasNext() ) { + Map.Entry me = (Map.Entry)i.next(); + HeapRegionNode hrn = (HeapRegionNode) me.getValue(); + if( !visited.contains(hrn) ) { + traverseHeapRegionNodes(VISIT_HRN_WRITE_FULL, + hrn, + bw, + null, + visited, + writeReferencers); + } + } } - public void writeGraph( String graphName, - boolean writeLabels, - boolean labelSelect, - boolean pruneGarbage, - boolean writeReferencers - ) throws java.io.IOException { - - // remove all non-word characters from the graph name so - // the filename and identifier in dot don't cause errors - graphName = graphName.replaceAll( "[\\W]", "" ); - - BufferedWriter bw = new BufferedWriter( new FileWriter( graphName+".dot" ) ); - bw.write( "digraph "+graphName+" {\n" ); - //bw.write( " size=\"7.5,10\";\n" ); - - HashSet visited = new HashSet(); - - // then visit every heap region node - if( !pruneGarbage ) { - Set s = id2hrn.entrySet(); - Iterator i = s.iterator(); - while( i.hasNext() ) { - Map.Entry me = (Map.Entry) i.next(); - HeapRegionNode hrn = (HeapRegionNode) me.getValue(); - if( !visited.contains( hrn ) ) { - traverseHeapRegionNodes( VISIT_HRN_WRITE_FULL, - hrn, - bw, - null, - visited, - writeReferencers ); - } - } + bw.write(" graphTitle[label=\""+graphName+"\",shape=box];\n"); + + + // then visit every label node, useful for debugging + if( writeLabels ) { + Set s = td2ln.entrySet(); + Iterator 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") ) { + continue; + } } - bw.write( " graphTitle[label=\""+graphName+"\",shape=box];\n" ); - - - // then visit every label node, useful for debugging - if( writeLabels ) { - Set s = td2ln.entrySet(); - Iterator 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" ) ) { - 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 ); - } - - bw.write( " " + ln.toString() + - " -> " + hrn.toString() + - "[label=\"" + edge.toGraphEdgeString() + - "\",decorate];\n" ); - } - } + 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); + } + + bw.write(" " + ln.toString() + + " -> " + hrn.toString() + + "[label=\"" + edge.toGraphEdgeString() + + "\",decorate];\n"); } - - - bw.write( "}\n" ); - bw.close(); + } } - protected void traverseHeapRegionNodes( int mode, - HeapRegionNode hrn, - BufferedWriter bw, - TempDescriptor td, - HashSet visited, - boolean writeReferencers - ) throws java.io.IOException { - if( visited.contains( hrn ) ) { - return; - } - visited.add( hrn ); + bw.write("}\n"); + bw.close(); + } - switch( mode ) { - case VISIT_HRN_WRITE_FULL: - - String attributes = "["; - - if( hrn.isSingleObject() ) { - attributes += "shape=box"; - } else { - attributes += "shape=Msquare"; - } + protected void traverseHeapRegionNodes(int mode, + HeapRegionNode hrn, + BufferedWriter bw, + TempDescriptor td, + HashSet visited, + boolean writeReferencers + ) throws java.io.IOException { - if( hrn.isFlagged() ) { - attributes += ",style=filled,fillcolor=lightgrey"; - } + if( visited.contains(hrn) ) { + return; + } + visited.add(hrn); - attributes += ",label=\"ID" + - hrn.getID() + - "\\n" + - hrn.getDescription() + - "\\n" + - hrn.getAlphaString() + - "\"]"; + switch( mode ) { + case VISIT_HRN_WRITE_FULL: - bw.write( " " + hrn.toString() + attributes + ";\n" ); - break; - } + String attributes = "["; + if( hrn.isSingleObject() ) { + attributes += "shape=box"; + } else { + attributes += "shape=Msquare"; + } - // useful for debugging - if( writeReferencers ) { - OwnershipNode onRef = null; - Iterator refItr = hrn.iteratorToReferencers(); - while( refItr.hasNext() ) { - onRef = (OwnershipNode) refItr.next(); - - switch( mode ) { - case VISIT_HRN_WRITE_FULL: - bw.write( " " + hrn.toString() + - " -> " + onRef.toString() + - "[color=lightgray];\n" ); - break; - } - } - } + if( hrn.isFlagged() ) { + attributes += ",style=filled,fillcolor=lightgrey"; + } + + attributes += ",label=\"ID" + + hrn.getID() + + "\\n" + + hrn.getDescription() + + "\\n" + + hrn.getAlphaString() + + "\"]"; + + bw.write(" " + hrn.toString() + attributes + ";\n"); + break; + } - Iterator childRegionsItr = hrn.iteratorToReferencees(); - while( childRegionsItr.hasNext() ) { - ReferenceEdge edge = childRegionsItr.next(); - HeapRegionNode hrnChild = edge.getDst(); - - switch( mode ) { - case VISIT_HRN_WRITE_FULL: - bw.write( " " + hrn.toString() + - " -> " + hrnChild.toString() + - "[label=\"" + edge.toGraphEdgeString() + - "\",decorate];\n" ); - break; - } - traverseHeapRegionNodes( mode, - hrnChild, - bw, - td, - visited, - writeReferencers ); + // useful for debugging + if( writeReferencers ) { + OwnershipNode onRef = null; + Iterator refItr = hrn.iteratorToReferencers(); + while( refItr.hasNext() ) { + onRef = (OwnershipNode) refItr.next(); + + switch( mode ) { + case VISIT_HRN_WRITE_FULL: + bw.write(" " + hrn.toString() + + " -> " + onRef.toString() + + "[color=lightgray];\n"); + break; } + } + } + + Iterator childRegionsItr = hrn.iteratorToReferencees(); + while( childRegionsItr.hasNext() ) { + ReferenceEdge edge = childRegionsItr.next(); + HeapRegionNode hrnChild = edge.getDst(); + + switch( mode ) { + case VISIT_HRN_WRITE_FULL: + bw.write(" " + hrn.toString() + + " -> " + hrnChild.toString() + + "[label=\"" + edge.toGraphEdgeString() + + "\",decorate];\n"); + break; + } + + traverseHeapRegionNodes(mode, + hrnChild, + bw, + td, + visited, + writeReferencers); } + } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/OwnershipNode.java b/Robust/src/Analysis/OwnershipAnalysis/OwnershipNode.java index 88b786bb..390813e3 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/OwnershipNode.java +++ b/Robust/src/Analysis/OwnershipAnalysis/OwnershipNode.java @@ -4,54 +4,54 @@ import IR.*; import IR.Flat.*; import java.util.*; -public abstract class OwnershipNode { +public abstract class OwnershipNode { - protected HashSet referencees; - - public OwnershipNode() { - referencees = new HashSet(); - } + protected HashSet referencees; + public OwnershipNode() { + referencees = new HashSet(); + } - public Iterator iteratorToReferencees() { - return referencees.iterator(); - } - public Iterator iteratorToReferenceesClone() { - HashSet clone = (HashSet) referencees.clone(); - return clone.iterator(); - } + public Iterator iteratorToReferencees() { + return referencees.iterator(); + } - public int getNumReferencees() { - return referencees.size(); - } + public Iterator iteratorToReferenceesClone() { + HashSet clone = (HashSet)referencees.clone(); + return clone.iterator(); + } - public void addReferencee( ReferenceEdge edge ) { - assert edge != null; + public int getNumReferencees() { + return referencees.size(); + } - referencees.add( edge ); - } + public void addReferencee(ReferenceEdge edge) { + assert edge != null; - public void removeReferencee( ReferenceEdge edge ) { - assert edge != null; - assert referencees.contains( edge ); + referencees.add(edge); + } - referencees.remove( edge ); - } + public void removeReferencee(ReferenceEdge edge) { + assert edge != null; + assert referencees.contains(edge); - public ReferenceEdge getReferenceTo( HeapRegionNode hrn, - FieldDescriptor fd ) { - assert hrn != null; + referencees.remove(edge); + } - Iterator itrEdge = referencees.iterator(); - while( itrEdge.hasNext() ) { - ReferenceEdge edge = itrEdge.next(); - if( edge.getDst().equals( hrn ) && - edge.getFieldDesc() == fd ) { - return edge; - } - } + public ReferenceEdge getReferenceTo(HeapRegionNode hrn, + FieldDescriptor fd) { + assert hrn != null; - return null; + Iterator itrEdge = referencees.iterator(); + while( itrEdge.hasNext() ) { + ReferenceEdge edge = itrEdge.next(); + if( edge.getDst().equals(hrn) && + edge.getFieldDesc() == fd ) { + return edge; + } } + + return null; + } } \ No newline at end of file diff --git a/Robust/src/Analysis/OwnershipAnalysis/ReachabilitySet.java b/Robust/src/Analysis/OwnershipAnalysis/ReachabilitySet.java index eb9c958e..cb12451a 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/ReachabilitySet.java +++ b/Robust/src/Analysis/OwnershipAnalysis/ReachabilitySet.java @@ -8,253 +8,253 @@ import java.io.*; public class ReachabilitySet extends Canonical { - private HashSet possibleReachabilities; - - public ReachabilitySet() { - possibleReachabilities = new HashSet(); + private HashSet possibleReachabilities; + + public ReachabilitySet() { + possibleReachabilities = new HashSet(); + } + + public ReachabilitySet(TokenTupleSet tts) { + this(); + assert tts != null; + possibleReachabilities.add(tts); + } + + public ReachabilitySet(TokenTuple tt) { + // can't assert before calling this(), it will + // do the checking though + this( new TokenTupleSet(tt).makeCanonical() ); + } + + public ReachabilitySet(HashSet possibleReachabilities) { + assert possibleReachabilities != null; + this.possibleReachabilities = possibleReachabilities; + } + + public ReachabilitySet(ReachabilitySet rs) { + assert rs != null; + // okay to clone, ReachabilitySet should be canonical + possibleReachabilities = (HashSet)rs.possibleReachabilities.clone(); + } + + + public ReachabilitySet makeCanonical() { + return (ReachabilitySet) Canonical.makeCanonical(this); + } + + public Iterator iterator() { + return possibleReachabilities.iterator(); + } + + + public boolean contains(TokenTupleSet tts) { + assert tts != null; + return possibleReachabilities.contains(tts); + } + + public boolean containsTuple(TokenTuple tt) { + Iterator itr = iterator(); + while( itr.hasNext() ) { + TokenTupleSet tts = (TokenTupleSet) itr.next(); + if( tts.containsTuple(tt) ) { + return true; + } } + return false; + } - public ReachabilitySet( TokenTupleSet tts ) { - this(); - assert tts != null; - possibleReachabilities.add( tts ); - } - public ReachabilitySet( TokenTuple tt ) { - // can't assert before calling this(), it will - // do the checking though - this( new TokenTupleSet( tt ).makeCanonical() ); - } + public ReachabilitySet increaseArity(Integer token) { + assert token != null; - public ReachabilitySet( HashSet possibleReachabilities ) { - assert possibleReachabilities != null; - this.possibleReachabilities = possibleReachabilities; - } + HashSet possibleReachabilitiesNew = new HashSet(); - public ReachabilitySet( ReachabilitySet rs ) { - assert rs != null; - // okay to clone, ReachabilitySet should be canonical - possibleReachabilities = (HashSet) rs.possibleReachabilities.clone(); + Iterator itr = iterator(); + while( itr.hasNext() ) { + TokenTupleSet tts = (TokenTupleSet) itr.next(); + possibleReachabilitiesNew.add(tts.increaseArity(token) ); } + return new ReachabilitySet(possibleReachabilitiesNew).makeCanonical(); + } - public ReachabilitySet makeCanonical() { - return (ReachabilitySet) Canonical.makeCanonical( this ); - } - - public Iterator iterator() { - return possibleReachabilities.iterator(); - } + public ReachabilitySet union(ReachabilitySet rsIn) { + assert rsIn != null; - public boolean contains( TokenTupleSet tts ) { - assert tts != null; - return possibleReachabilities.contains( tts ); - } + ReachabilitySet rsOut = new ReachabilitySet(this); + rsOut.possibleReachabilities.addAll(rsIn.possibleReachabilities); + return rsOut.makeCanonical(); + } - public boolean containsTuple( TokenTuple tt ) { - Iterator itr = iterator(); - while( itr.hasNext() ) { - TokenTupleSet tts = (TokenTupleSet) itr.next(); - if( tts.containsTuple( tt ) ) { - return true; - } - } - return false; - } + public ReachabilitySet union(TokenTupleSet ttsIn) { + assert ttsIn != null; + ReachabilitySet rsOut = new ReachabilitySet(this); + rsOut.possibleReachabilities.add(ttsIn); + return rsOut.makeCanonical(); + } - public ReachabilitySet increaseArity( Integer token ) { - assert token != null; + public ReachabilitySet intersection(ReachabilitySet rsIn) { + assert rsIn != null; - HashSet possibleReachabilitiesNew = new HashSet(); + ReachabilitySet rsOut = new ReachabilitySet(); - Iterator itr = iterator(); - while( itr.hasNext() ) { - TokenTupleSet tts = (TokenTupleSet) itr.next(); - possibleReachabilitiesNew.add( tts.increaseArity( token ) ); - } - - return new ReachabilitySet( possibleReachabilitiesNew ).makeCanonical(); + Iterator i = this.iterator(); + while( i.hasNext() ) { + TokenTupleSet tts = (TokenTupleSet) i.next(); + if( rsIn.possibleReachabilities.contains(tts) ) { + rsOut.possibleReachabilities.add(tts); + } } + return rsOut.makeCanonical(); + } - public ReachabilitySet union( ReachabilitySet rsIn ) { - assert rsIn != null; - ReachabilitySet rsOut = new ReachabilitySet( this ); - rsOut.possibleReachabilities.addAll( rsIn.possibleReachabilities ); - return rsOut.makeCanonical(); - } + public ReachabilitySet add(TokenTupleSet tts) { + assert tts != null; + ReachabilitySet rsOut = new ReachabilitySet(tts); + return rsOut.union(this); + } - public ReachabilitySet union( TokenTupleSet ttsIn ) { - assert ttsIn != null; - ReachabilitySet rsOut = new ReachabilitySet( this ); - rsOut.possibleReachabilities.add( ttsIn ); - return rsOut.makeCanonical(); - } + public ChangeTupleSet unionUpArityToChangeSet(ReachabilitySet rsIn) { + assert rsIn != null; - public ReachabilitySet intersection( ReachabilitySet rsIn ) { - assert rsIn != null; + ChangeTupleSet ctsOut = new ChangeTupleSet(); - ReachabilitySet rsOut = new ReachabilitySet(); + Iterator itrO = this.iterator(); + while( itrO.hasNext() ) { + TokenTupleSet o = (TokenTupleSet) itrO.next(); - Iterator i = this.iterator(); - while( i.hasNext() ) { - TokenTupleSet tts = (TokenTupleSet) i.next(); - if( rsIn.possibleReachabilities.contains( tts ) ) { - rsOut.possibleReachabilities.add( tts ); - } - } - - return rsOut.makeCanonical(); - } - - - public ReachabilitySet add( TokenTupleSet tts ) { - assert tts != null; - ReachabilitySet rsOut = new ReachabilitySet( tts ); - return rsOut.union( this ); - } + Iterator itrR = rsIn.iterator(); + while( itrR.hasNext() ) { + TokenTupleSet r = (TokenTupleSet) itrR.next(); + TokenTupleSet theUnion = new TokenTupleSet(); - public ChangeTupleSet unionUpArityToChangeSet( ReachabilitySet rsIn ) { - assert rsIn != null; + Iterator itrRelement = r.iterator(); + while( itrRelement.hasNext() ) { + TokenTuple e = (TokenTuple) itrRelement.next(); - ChangeTupleSet ctsOut = new ChangeTupleSet(); - - Iterator itrO = this.iterator(); - while( itrO.hasNext() ) { - TokenTupleSet o = (TokenTupleSet) itrO.next(); - - Iterator itrR = rsIn.iterator(); - while( itrR.hasNext() ) { - TokenTupleSet r = (TokenTupleSet) itrR.next(); - - TokenTupleSet theUnion = new TokenTupleSet(); - - Iterator itrRelement = r.iterator(); - while( itrRelement.hasNext() ) { - TokenTuple e = (TokenTuple) itrRelement.next(); - - if( o.containsToken( e.getToken() ) ) { - theUnion = theUnion.union( new TokenTupleSet( e.increaseArity() ) ).makeCanonical(); - } else { - theUnion = theUnion.union( new TokenTupleSet( e ) ).makeCanonical(); - } - } - - Iterator itrOelement = o.iterator(); - while( itrOelement.hasNext() ) { - TokenTuple e = (TokenTuple) itrOelement.next(); + if( o.containsToken(e.getToken() ) ) { + theUnion = theUnion.union(new TokenTupleSet(e.increaseArity() ) ).makeCanonical(); + } else { + theUnion = theUnion.union(new TokenTupleSet(e) ).makeCanonical(); + } + } - if( !theUnion.containsToken( e.getToken() ) ) { - theUnion = theUnion.union( new TokenTupleSet( e ) ).makeCanonical(); - } - } + Iterator itrOelement = o.iterator(); + while( itrOelement.hasNext() ) { + TokenTuple e = (TokenTuple) itrOelement.next(); - if( !theUnion.isEmpty() ) { - ctsOut = ctsOut.union( - new ChangeTupleSet( new ChangeTuple( o, theUnion ) ) - ); - } - } + if( !theUnion.containsToken(e.getToken() ) ) { + theUnion = theUnion.union(new TokenTupleSet(e) ).makeCanonical(); + } } - return ctsOut.makeCanonical(); + if( !theUnion.isEmpty() ) { + ctsOut = ctsOut.union( + new ChangeTupleSet(new ChangeTuple(o, theUnion) ) + ); + } + } } + return ctsOut.makeCanonical(); + } - public ReachabilitySet ageTokens( AllocationSite as ) { - assert as != null; - - ReachabilitySet rsOut = new ReachabilitySet(); - Iterator itrS = this.iterator(); - while( itrS.hasNext() ) { - TokenTupleSet tts = (TokenTupleSet) itrS.next(); - rsOut.possibleReachabilities.add( tts.ageTokens( as ) ); - } + public ReachabilitySet ageTokens(AllocationSite as) { + assert as != null; - return rsOut.makeCanonical(); + ReachabilitySet rsOut = new ReachabilitySet(); + + Iterator itrS = this.iterator(); + while( itrS.hasNext() ) { + TokenTupleSet tts = (TokenTupleSet) itrS.next(); + rsOut.possibleReachabilities.add(tts.ageTokens(as) ); } + return rsOut.makeCanonical(); + } + - public ReachabilitySet pruneBy( ReachabilitySet rsIn ) { - assert rsIn != null; + public ReachabilitySet pruneBy(ReachabilitySet rsIn) { + assert rsIn != null; - ReachabilitySet rsOut = new ReachabilitySet(); + ReachabilitySet rsOut = new ReachabilitySet(); - Iterator itrB = this.iterator(); - while( itrB.hasNext() ) { - TokenTupleSet ttsB = (TokenTupleSet) itrB.next(); + Iterator itrB = this.iterator(); + while( itrB.hasNext() ) { + TokenTupleSet ttsB = (TokenTupleSet) itrB.next(); - boolean subsetExists = false; + boolean subsetExists = false; - Iterator itrA = rsIn.iterator(); - while( itrA.hasNext() && !subsetExists ) { - TokenTupleSet ttsA = (TokenTupleSet) itrA.next(); - - if( ttsA.isSubset( ttsB ) ) { - subsetExists = true; - } - } + Iterator itrA = rsIn.iterator(); + while( itrA.hasNext() && !subsetExists ) { + TokenTupleSet ttsA = (TokenTupleSet) itrA.next(); - if( subsetExists ) { - rsOut.possibleReachabilities.add( ttsB ); - } + if( ttsA.isSubset(ttsB) ) { + subsetExists = true; } + } - return rsOut.makeCanonical(); + if( subsetExists ) { + rsOut.possibleReachabilities.add(ttsB); + } } + return rsOut.makeCanonical(); + } - public boolean equals( Object o ) { - if( o == null ) { - return false; - } - - if( !(o instanceof ReachabilitySet) ) { - return false; - } - ReachabilitySet rs = (ReachabilitySet) o; - return possibleReachabilities.equals( rs.possibleReachabilities ); + public boolean equals(Object o) { + if( o == null ) { + return false; } - public int hashCode() { - return possibleReachabilities.hashCode(); + if( !(o instanceof ReachabilitySet) ) { + return false; } + ReachabilitySet rs = (ReachabilitySet) o; + return possibleReachabilities.equals(rs.possibleReachabilities); + } - public String toStringEscapeNewline() { - String s = "["; + public int hashCode() { + return possibleReachabilities.hashCode(); + } - Iterator i = this.iterator(); - while( i.hasNext() ) { - s += i.next(); - if( i.hasNext() ) { - s += "\\n"; - } - } - s += "]"; - return s; + public String toStringEscapeNewline() { + String s = "["; + + Iterator i = this.iterator(); + while( i.hasNext() ) { + s += i.next(); + if( i.hasNext() ) { + s += "\\n"; + } } - public String toString() { - String s = "["; + s += "]"; + return s; + } - Iterator i = this.iterator(); - while( i.hasNext() ) { - s += i.next(); - if( i.hasNext() ) { - s += "\n"; - } - } + public String toString() { + String s = "["; - s += "]"; - return s; + Iterator i = this.iterator(); + while( i.hasNext() ) { + s += i.next(); + if( i.hasNext() ) { + s += "\n"; + } } + + s += "]"; + return s; + } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/ReferenceEdge.java b/Robust/src/Analysis/OwnershipAnalysis/ReferenceEdge.java index 68a38cd8..7e625b15 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/ReferenceEdge.java +++ b/Robust/src/Analysis/OwnershipAnalysis/ReferenceEdge.java @@ -7,170 +7,170 @@ import IR.Flat.*; public class ReferenceEdge { - // a null field descriptor means "any field" - protected FieldDescriptor fieldDesc; + // a null field descriptor means "any field" + protected FieldDescriptor fieldDesc; - protected boolean isInitialParamReflexive; + protected boolean isInitialParamReflexive; - protected ReachabilitySet beta; - protected ReachabilitySet betaNew; + protected ReachabilitySet beta; + protected ReachabilitySet betaNew; - protected OwnershipNode src; - protected HeapRegionNode dst; + protected OwnershipNode src; + protected HeapRegionNode dst; - public ReferenceEdge( OwnershipNode src, - HeapRegionNode dst, - FieldDescriptor fieldDesc, - boolean isInitialParamReflexive, - ReachabilitySet beta ) { + public ReferenceEdge(OwnershipNode src, + HeapRegionNode dst, + FieldDescriptor fieldDesc, + boolean isInitialParamReflexive, + ReachabilitySet beta) { - this.src = src; - this.dst = dst; - this.fieldDesc = fieldDesc; - this.isInitialParamReflexive = isInitialParamReflexive; + this.src = src; + this.dst = dst; + this.fieldDesc = fieldDesc; + this.isInitialParamReflexive = isInitialParamReflexive; - if( beta != null ) { - this.beta = beta; - } else { - this.beta = new ReachabilitySet().makeCanonical(); - } - - // when edges are not undergoing a transitional operation - // that is changing beta info, betaNew is always empty - betaNew = new ReachabilitySet().makeCanonical(); + if( beta != null ) { + this.beta = beta; + } else { + this.beta = new ReachabilitySet().makeCanonical(); } + // when edges are not undergoing a transitional operation + // that is changing beta info, betaNew is always empty + betaNew = new ReachabilitySet().makeCanonical(); + } - public ReferenceEdge copy() { - return new ReferenceEdge( src, - dst, - fieldDesc, - isInitialParamReflexive, - beta ); - } + public ReferenceEdge copy() { + return new ReferenceEdge(src, + dst, + fieldDesc, + isInitialParamReflexive, + beta); + } - public boolean equals( Object o ) { - if( o == null ) { - return false; - } - if( !(o instanceof ReferenceEdge) ) { - return false; - } - - ReferenceEdge edge = (ReferenceEdge) o; + public boolean equals(Object o) { + if( o == null ) { + return false; + } - if( fieldDesc != edge.fieldDesc ) { - return false; - } + if( !(o instanceof ReferenceEdge) ) { + return false; + } - // Equality of edges is only valid within a graph, so - // compare src and dst by reference - if( !(src == edge.src) || - !(dst == edge.dst) ) { - return false; - } + ReferenceEdge edge = (ReferenceEdge) o; - return true; + if( fieldDesc != edge.fieldDesc ) { + return false; } - - public boolean equalsIncludingBeta( ReferenceEdge edge ) { - return equals( edge ) && beta.equals( edge.beta ); + // Equality of edges is only valid within a graph, so + // compare src and dst by reference + if( !(src == edge.src) || + !(dst == edge.dst) ) { + return false; } + return true; + } + - public int hashCode() { - int hash = 0; + public boolean equalsIncludingBeta(ReferenceEdge edge) { + return equals(edge) && beta.equals(edge.beta); + } - if( fieldDesc != null ) { - hash += fieldDesc.getType().hashCode(); - } - hash += src.hashCode()*11; - hash += dst.hashCode(); + public int hashCode() { + int hash = 0; - return hash; + if( fieldDesc != null ) { + hash += fieldDesc.getType().hashCode(); } + hash += src.hashCode()*11; + hash += dst.hashCode(); - public OwnershipNode getSrc() { - return src; - } + return hash; + } - public void setSrc( OwnershipNode on ) { - assert on != null; - src = on; - } - public HeapRegionNode getDst() { - return dst; - } + public OwnershipNode getSrc() { + return src; + } - public void setDst( HeapRegionNode hrn ) { - assert hrn != null; - dst = hrn; - } + public void setSrc(OwnershipNode on) { + assert on != null; + src = on; + } + public HeapRegionNode getDst() { + return dst; + } - public FieldDescriptor getFieldDesc() { - return fieldDesc; - } + public void setDst(HeapRegionNode hrn) { + assert hrn != null; + dst = hrn; + } - public void setFieldDesc( FieldDescriptor fieldDesc ) { - this.fieldDesc = fieldDesc; - } + public FieldDescriptor getFieldDesc() { + return fieldDesc; + } - public boolean isInitialParamReflexive() { - return isInitialParamReflexive; - } - public void setIsInitialParamReflexive( boolean isInitialParamReflexive ) { - this.isInitialParamReflexive = isInitialParamReflexive; - } + public void setFieldDesc(FieldDescriptor fieldDesc) { + this.fieldDesc = fieldDesc; + } - public ReachabilitySet getBeta() { - return beta; - } + public boolean isInitialParamReflexive() { + return isInitialParamReflexive; + } + public void setIsInitialParamReflexive(boolean isInitialParamReflexive) { + this.isInitialParamReflexive = isInitialParamReflexive; + } - public void setBeta( ReachabilitySet beta ) { - assert beta != null; - this.beta = beta; - } - public ReachabilitySet getBetaNew() { - return betaNew; - } + public ReachabilitySet getBeta() { + return beta; + } - public void setBetaNew( ReachabilitySet beta ) { - assert beta != null; - this.betaNew = beta; - } + public void setBeta(ReachabilitySet beta) { + assert beta != null; + this.beta = beta; + } - public void applyBetaNew() { - assert betaNew != null; + public ReachabilitySet getBetaNew() { + return betaNew; + } - beta = betaNew; - betaNew = new ReachabilitySet().makeCanonical(); - } + public void setBetaNew(ReachabilitySet beta) { + assert beta != null; + this.betaNew = beta; + } + + public void applyBetaNew() { + assert betaNew != null; - - public String toGraphEdgeString() { - String edgeLabel = ""; + beta = betaNew; + betaNew = new ReachabilitySet().makeCanonical(); + } - if( fieldDesc != null ) { - edgeLabel += fieldDesc.toStringBrief() + "\\n"; - } - if( isInitialParamReflexive ) { - edgeLabel += "Rflx\\n"; - } + public String toGraphEdgeString() { + String edgeLabel = ""; - edgeLabel += beta.toStringEscapeNewline(); + if( fieldDesc != null ) { + edgeLabel += fieldDesc.toStringBrief() + "\\n"; + } - return edgeLabel; + if( isInitialParamReflexive ) { + edgeLabel += "Rflx\\n"; } + + edgeLabel += beta.toStringEscapeNewline(); + + return edgeLabel; + } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/SubstitutionTuple.java b/Robust/src/Analysis/OwnershipAnalysis/SubstitutionTuple.java index ce36f671..62ddef67 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/SubstitutionTuple.java +++ b/Robust/src/Analysis/OwnershipAnalysis/SubstitutionTuple.java @@ -14,42 +14,46 @@ import java.io.*; public class ChangeTuple extends Canonical { - private TokenTupleSet toMatch; - private TokenTupleSet toAdd; - - public ChangeTuple( TokenTupleSet toMatch, - TokenTupleSet toAdd ) { - this.toMatch = toMatch; - this.toAdd = toAdd; + private TokenTupleSet toMatch; + private TokenTupleSet toAdd; + + public ChangeTuple(TokenTupleSet toMatch, + TokenTupleSet toAdd) { + this.toMatch = toMatch; + this.toAdd = toAdd; + } + + public ChangeTuple makeCanonical() { + return (ChangeTuple) Canonical.makeCanonical(this); + } + + public TokenTupleSet getSetToMatch() { + return toMatch; + } + public TokenTupleSet getSetToAdd() { + return toAdd; + } + + public boolean equals(Object o) { + if( o == null ) { + return false; } - public ChangeTuple makeCanonical() { - return (ChangeTuple) Canonical.makeCanonical( this ); + if( !(o instanceof ChangeTuple) ) { + return false; } - public TokenTupleSet getSetToMatch() { return toMatch; } - public TokenTupleSet getSetToAdd() { return toAdd; } - - public boolean equals( Object o ) { - if( o == null ) { - return false; - } + ChangeTuple ct = (ChangeTuple) o; - if( !(o instanceof ChangeTuple) ) { - return false; - } + return toMatch.equals(ct.getSetToMatch() ) && + toAdd.equals(ct.getSetToAdd() ); + } - ChangeTuple ct = (ChangeTuple) o; - - return toMatch.equals( ct.getSetToMatch() ) && - toAdd.equals( ct.getSetToAdd() ); - } + public int hashCode() { + return toMatch.hashCode() + toAdd.hashCode(); + } - public int hashCode() { - return toMatch.hashCode() + toAdd.hashCode(); - } - - public String toString() { - return new String( "<"+toMatch+" -> "+toAdd+">" ); - } + public String toString() { + return new String("<"+toMatch+" -> "+toAdd+">"); + } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/TokenTuple.java b/Robust/src/Analysis/OwnershipAnalysis/TokenTuple.java index 93f6a6da..04173760 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/TokenTuple.java +++ b/Robust/src/Analysis/OwnershipAnalysis/TokenTuple.java @@ -13,95 +13,99 @@ import java.io.*; public class TokenTuple extends Canonical { - private Integer token; - private boolean isNewSummary; + private Integer token; + private boolean isNewSummary; - // only summary tokens should have ARITY_MANY? - public static final int ARITY_ONE = 1; - public static final int ARITY_MANY = 2; - private int arity; + // only summary tokens should have ARITY_MANY? + public static final int ARITY_ONE = 1; + public static final int ARITY_MANY = 2; + private int arity; - public TokenTuple( HeapRegionNode hrn ) { - assert hrn != null; + public TokenTuple(HeapRegionNode hrn) { + assert hrn != null; - token = hrn.getID(); - isNewSummary = hrn.isNewSummary(); - arity = ARITY_ONE; - } + token = hrn.getID(); + isNewSummary = hrn.isNewSummary(); + arity = ARITY_ONE; + } - public TokenTuple( Integer token, - boolean isNewSummary, - int arity ) { - assert token != null; + public TokenTuple(Integer token, + boolean isNewSummary, + int arity) { + assert token != null; - this.token = token; - this.isNewSummary = isNewSummary; - this.arity = arity; - } + this.token = token; + this.isNewSummary = isNewSummary; + this.arity = arity; + } - public TokenTuple makeCanonical() { - return (TokenTuple) Canonical.makeCanonical( this ); - } + public TokenTuple makeCanonical() { + return (TokenTuple) Canonical.makeCanonical(this); + } - public Integer getToken() { return token; } - public int getArity() { return arity; } + public Integer getToken() { + return token; + } + public int getArity() { + return arity; + } - public TokenTuple increaseArity() { - if( isNewSummary ) { - return (TokenTuple) Canonical.makeCanonical( - new TokenTuple( token, isNewSummary, ARITY_MANY ) - ); - } - return this; + public TokenTuple increaseArity() { + if( isNewSummary ) { + return (TokenTuple) Canonical.makeCanonical( + new TokenTuple(token, isNewSummary, ARITY_MANY) + ); } + return this; + } - public TokenTuple changeTokenTo( Integer tokenToChangeTo ) { - assert tokenToChangeTo != null; - assert isNewSummary == false; - - return new TokenTuple( tokenToChangeTo, - isNewSummary, - arity ).makeCanonical(); - } - + public TokenTuple changeTokenTo(Integer tokenToChangeTo) { + assert tokenToChangeTo != null; + assert isNewSummary == false; - public boolean equals( Object o ) { - if( o == null ) { - return false; - } + return new TokenTuple(tokenToChangeTo, + isNewSummary, + arity).makeCanonical(); + } - if( !(o instanceof TokenTuple) ) { - return false; - } - TokenTuple tt = (TokenTuple) o; - - return token.equals( tt.getToken() ) && - arity == tt.getArity(); + public boolean equals(Object o) { + if( o == null ) { + return false; } - public int hashCode() { - return token.intValue()*31 + arity; + if( !(o instanceof TokenTuple) ) { + return false; } + TokenTuple tt = (TokenTuple) o; + + return token.equals(tt.getToken() ) && + arity == tt.getArity(); + } - public String toString() { - String s = token.toString(); + public int hashCode() { + return token.intValue()*31 + arity; + } - if( isNewSummary ) { - s += "S"; - } - if( arity == ARITY_MANY ) { - s += "*"; - } + public String toString() { + String s = token.toString(); - return s; + if( isNewSummary ) { + s += "S"; } + + if( arity == ARITY_MANY ) { + s += "*"; + } + + return s; + } } diff --git a/Robust/src/Analysis/OwnershipAnalysis/TokenTupleSet.java b/Robust/src/Analysis/OwnershipAnalysis/TokenTupleSet.java index e52a92d2..334b7d56 100644 --- a/Robust/src/Analysis/OwnershipAnalysis/TokenTupleSet.java +++ b/Robust/src/Analysis/OwnershipAnalysis/TokenTupleSet.java @@ -8,180 +8,180 @@ import java.io.*; public class TokenTupleSet extends Canonical { - private HashSet tokenTuples; + private HashSet tokenTuples; - public TokenTupleSet() { - tokenTuples = new HashSet(); - } + public TokenTupleSet() { + tokenTuples = new HashSet(); + } - public TokenTupleSet( TokenTuple tt ) { - this(); - assert tt != null; - tokenTuples.add( tt ); - } + public TokenTupleSet(TokenTuple tt) { + this(); + assert tt != null; + tokenTuples.add(tt); + } - public TokenTupleSet( TokenTupleSet tts ) { - assert tts != null; - // okay to clone, TokenTuple and TokenTupleSet should be canonical - tokenTuples = (HashSet) tts.tokenTuples.clone(); - } + public TokenTupleSet(TokenTupleSet tts) { + assert tts != null; + // okay to clone, TokenTuple and TokenTupleSet should be canonical + tokenTuples = (HashSet)tts.tokenTuples.clone(); + } - public TokenTupleSet makeCanonical() { - return (TokenTupleSet) Canonical.makeCanonical( this ); - } + public TokenTupleSet makeCanonical() { + return (TokenTupleSet) Canonical.makeCanonical(this); + } - public Iterator iterator() { - return tokenTuples.iterator(); - } + public Iterator iterator() { + return tokenTuples.iterator(); + } - public boolean isEmpty() { - return tokenTuples.isEmpty(); - } + public boolean isEmpty() { + return tokenTuples.isEmpty(); + } - public boolean isSubset( TokenTupleSet ttsIn ) { - assert ttsIn != null; - return ttsIn.tokenTuples.containsAll( this.tokenTuples ); - } + public boolean isSubset(TokenTupleSet ttsIn) { + assert ttsIn != null; + return ttsIn.tokenTuples.containsAll(this.tokenTuples); + } - public boolean containsTuple( TokenTuple tt ) { - assert tt != null; - return tokenTuples.contains( tt ); - } + public boolean containsTuple(TokenTuple tt) { + assert tt != null; + return tokenTuples.contains(tt); + } - public TokenTupleSet union( TokenTupleSet ttsIn ) { - assert ttsIn != null; - TokenTupleSet ttsOut = new TokenTupleSet( this ); - ttsOut.tokenTuples.addAll( ttsIn.tokenTuples ); - return ttsOut.makeCanonical(); - } + public TokenTupleSet union(TokenTupleSet ttsIn) { + assert ttsIn != null; + TokenTupleSet ttsOut = new TokenTupleSet(this); + ttsOut.tokenTuples.addAll(ttsIn.tokenTuples); + return ttsOut.makeCanonical(); + } - public TokenTupleSet add( TokenTuple tt ) { - assert tt != null; - TokenTupleSet ttsOut = new TokenTupleSet( tt ); - return ttsOut.union( this ); - } + public TokenTupleSet add(TokenTuple tt) { + assert tt != null; + TokenTupleSet ttsOut = new TokenTupleSet(tt); + return ttsOut.union(this); + } - // this should only be done with a multiple-object heap region's token! - public TokenTupleSet increaseArity( Integer token ) { - assert token != null; - TokenTupleSet ttsOut = new TokenTupleSet( this ); - TokenTuple tt - = new TokenTuple( token, true, TokenTuple.ARITY_ONE ).makeCanonical(); - if( ttsOut.tokenTuples.contains( tt ) ) { - ttsOut.tokenTuples.remove( tt ); - ttsOut.tokenTuples.add( - new TokenTuple( token, true, TokenTuple.ARITY_MANY ).makeCanonical() - ); - } - - return ttsOut.makeCanonical(); + // this should only be done with a multiple-object heap region's token! + public TokenTupleSet increaseArity(Integer token) { + assert token != null; + TokenTupleSet ttsOut = new TokenTupleSet(this); + TokenTuple tt + = new TokenTuple(token, true, TokenTuple.ARITY_ONE).makeCanonical(); + if( ttsOut.tokenTuples.contains(tt) ) { + ttsOut.tokenTuples.remove(tt); + ttsOut.tokenTuples.add( + new TokenTuple(token, true, TokenTuple.ARITY_MANY).makeCanonical() + ); } + return ttsOut.makeCanonical(); + } - public boolean equals( Object o ) { - if( o == null ) { - return false; - } - - if( !(o instanceof TokenTupleSet) ) { - return false; - } - TokenTupleSet tts = (TokenTupleSet) o; - return tokenTuples.equals( tts.tokenTuples ); + public boolean equals(Object o) { + if( o == null ) { + return false; } - public int hashCode() { - return tokenTuples.hashCode(); + if( !(o instanceof TokenTupleSet) ) { + return false; } + TokenTupleSet tts = (TokenTupleSet) o; + return tokenTuples.equals(tts.tokenTuples); + } - // this should be a hash table so we can do this by key - public boolean containsToken( Integer token ) { - assert token != null; + public int hashCode() { + return tokenTuples.hashCode(); + } - Iterator itr = tokenTuples.iterator(); - while( itr.hasNext() ) { - TokenTuple tt = (TokenTuple) itr.next(); - if( token.equals( tt.getToken() ) ) { - return true; - } - } - return false; - } + // this should be a hash table so we can do this by key + public boolean containsToken(Integer token) { + assert token != null; - public TokenTupleSet ageTokens( AllocationSite as ) { - assert as != null; + Iterator itr = tokenTuples.iterator(); + while( itr.hasNext() ) { + TokenTuple tt = (TokenTuple) itr.next(); + if( token.equals(tt.getToken() ) ) { + return true; + } + } + return false; + } - TokenTupleSet ttsOut = new TokenTupleSet(); - TokenTuple ttSummary = null; - boolean foundOldest = false; + public TokenTupleSet ageTokens(AllocationSite as) { + assert as != null; - Iterator itrT = this.iterator(); - while( itrT.hasNext() ) { - TokenTuple tt = (TokenTuple) itrT.next(); + TokenTupleSet ttsOut = new TokenTupleSet(); - Integer token = tt.getToken(); - int age = as.getAge( token ); + TokenTuple ttSummary = null; + boolean foundOldest = false; - // summary tokens and tokens not associated with - // the site should be left alone - if( age == AllocationSite.AGE_notInThisSite ) { - ttsOut.tokenTuples.add( tt ); + Iterator itrT = this.iterator(); + while( itrT.hasNext() ) { + TokenTuple tt = (TokenTuple) itrT.next(); - } 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; + Integer token = tt.getToken(); + int age = as.getAge(token); - } else if( age == AllocationSite.AGE_oldest ) { - // found an oldest token, again just remember - // for later - foundOldest = true; + // summary tokens and tokens not associated with + // the site should be left alone + if( age == AllocationSite.AGE_notInThisSite ) { + ttsOut.tokenTuples.add(tt); - } else { - // otherwise, we change this token to the - // next older token - Integer tokenToChangeTo = as.getIthOldest( age + 1 ); - TokenTuple ttAged = tt.changeTokenTo( tokenToChangeTo ); - ttsOut.tokenTuples.add( ttAged ); - } + } 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; - } - } + } else if( age == AllocationSite.AGE_oldest ) { + // found an oldest token, again just remember + // for later + foundOldest = true; - // there are four cases to consider here - // 1. we found a summary tuple and no oldest tuple - // Here we just pass the summary unchanged - // 2. we found an oldest tuple, no summary - // Make a new, arity-one summary tuple - // 3. we found both a summary and an oldest - // Merge them by increasing arity of summary - // 4. (not handled) we found neither, do nothing - if ( ttSummary != null && !foundOldest ) { - ttsOut.tokenTuples.add( ttSummary ); - - } else if( ttSummary == null && foundOldest ) { - ttsOut.tokenTuples.add( new TokenTuple( as.getSummary(), - true, - TokenTuple.ARITY_ONE ).makeCanonical() ); - - } else if( ttSummary != null && foundOldest ) { - ttsOut.tokenTuples.add( ttSummary.increaseArity() ); + } else { + // otherwise, we change this token to the + // next older token + Integer tokenToChangeTo = as.getIthOldest(age + 1); + TokenTuple ttAged = tt.changeTokenTo(tokenToChangeTo); + ttsOut.tokenTuples.add(ttAged); } - return ttsOut.makeCanonical(); + } } + // there are four cases to consider here + // 1. we found a summary tuple and no oldest tuple + // Here we just pass the summary unchanged + // 2. we found an oldest tuple, no summary + // Make a new, arity-one summary tuple + // 3. we found both a summary and an oldest + // Merge them by increasing arity of summary + // 4. (not handled) we found neither, do nothing + if ( ttSummary != null && !foundOldest ) { + ttsOut.tokenTuples.add(ttSummary); + + } else if( ttSummary == null && foundOldest ) { + ttsOut.tokenTuples.add(new TokenTuple(as.getSummary(), + true, + TokenTuple.ARITY_ONE).makeCanonical() ); - public String toString() { - return tokenTuples.toString(); + } else if( ttSummary != null && foundOldest ) { + ttsOut.tokenTuples.add(ttSummary.increaseArity() ); } + + return ttsOut.makeCanonical(); + } + + + public String toString() { + return tokenTuples.toString(); + } } diff --git a/Robust/src/Analysis/Prefetch/IndexDescriptor.java b/Robust/src/Analysis/Prefetch/IndexDescriptor.java index b322183e..b4a6a644 100644 --- a/Robust/src/Analysis/Prefetch/IndexDescriptor.java +++ b/Robust/src/Analysis/Prefetch/IndexDescriptor.java @@ -13,81 +13,81 @@ import IR.*; * Descriptor * * This class is used to represent the index and index offset of Arrays in - * a prefetch pair - * for eg: for a prefetch pair a[i+z], an instance of this class stores var i and var z + * a prefetch pair + * for eg: for a prefetch pair a[i+z], an instance of this class stores var i and var z */ public class IndexDescriptor extends Descriptor { - public ArrayList tddesc; - public Integer offset; - - public IndexDescriptor(Integer offset) { - super(offset.toString()); - this.offset = offset; - this.tddesc=new ArrayList(); - } - - public IndexDescriptor(TempDescriptor tdesc, Integer offset) { - super(tdesc.toString()); - tddesc = new ArrayList(); - tddesc.add(tdesc); - this.offset = offset; - } - - public IndexDescriptor() { - super("Empty"); - tddesc = new ArrayList(); - offset = 0; - } + public ArrayList tddesc; + public Integer offset; - public IndexDescriptor(ArrayList tdesc, Integer offset) { - super(tdesc.toString()); - tddesc = new ArrayList(); - tddesc.addAll(tdesc); - this.offset = offset; - } - - public ArrayList getTempDesc() { - return tddesc; - } - - public TempDescriptor getTempDescAt(int index) { - return ((TempDescriptor) (tddesc.get(index))); - } - - public int getOffset() { - return offset.intValue(); - } - - public String toString() { - String label="["; - if(getTempDesc() == null) { - label += offset.toString(); - return label; - } else { - ListIterator lit = getTempDesc().listIterator(); - for(;lit.hasNext();) { - TempDescriptor td = (TempDescriptor) lit.next(); - label += td.toString()+"+"; - } - label +=offset.toString(); - } - label += "]"; - return label; - } - - public int hashCode() { - int hashcode = (Integer) offset.hashCode(); - hashcode^=tddesc.hashCode(); - return hashcode; + public IndexDescriptor(Integer offset) { + super(offset.toString()); + this.offset = offset; + this.tddesc=new ArrayList(); + } + + public IndexDescriptor(TempDescriptor tdesc, Integer offset) { + super(tdesc.toString()); + tddesc = new ArrayList(); + tddesc.add(tdesc); + this.offset = offset; + } + + public IndexDescriptor() { + super("Empty"); + tddesc = new ArrayList(); + offset = 0; + } + + public IndexDescriptor(ArrayList tdesc, Integer offset) { + super(tdesc.toString()); + tddesc = new ArrayList(); + tddesc.addAll(tdesc); + this.offset = offset; + } + + public ArrayList getTempDesc() { + return tddesc; + } + + public TempDescriptor getTempDescAt(int index) { + return ((TempDescriptor) (tddesc.get(index))); + } + + public int getOffset() { + return offset.intValue(); + } + + public String toString() { + String label="["; + if(getTempDesc() == null) { + label += offset.toString(); + return label; + } else { + ListIterator lit = getTempDesc().listIterator(); + for(; lit.hasNext();) { + TempDescriptor td = (TempDescriptor) lit.next(); + label += td.toString()+"+"; + } + label +=offset.toString(); } - - public boolean equals(Object o) { - if(o instanceof IndexDescriptor) { - IndexDescriptor idesc = (IndexDescriptor) o; - return offset==idesc.offset&& - tddesc.equals(idesc.tddesc); - } - return false; + label += "]"; + return label; + } + + public int hashCode() { + int hashcode = (Integer) offset.hashCode(); + hashcode^=tddesc.hashCode(); + return hashcode; + } + + public boolean equals(Object o) { + if(o instanceof IndexDescriptor) { + IndexDescriptor idesc = (IndexDescriptor) o; + return offset==idesc.offset&& + tddesc.equals(idesc.tddesc); } + return false; + } } diff --git a/Robust/src/Analysis/Prefetch/LoopExit.java b/Robust/src/Analysis/Prefetch/LoopExit.java index 2b1099b6..498f2a80 100644 --- a/Robust/src/Analysis/Prefetch/LoopExit.java +++ b/Robust/src/Analysis/Prefetch/LoopExit.java @@ -11,80 +11,80 @@ import IR.ClassDescriptor; public class LoopExit { - State state; - Hashtable> results; + State state; + Hashtable> results; - public LoopExit(State state) { - this.state=state; - this.results=new Hashtable>(); - } + public LoopExit(State state) { + this.state=state; + this.results=new Hashtable>(); + } - public Set getLoopBranches(MethodDescriptor md) { - if (!results.containsKey(md)) - doAnalysis(md); - return results.get(md); - } + public Set getLoopBranches(MethodDescriptor md) { + if (!results.containsKey(md)) + doAnalysis(md); + return results.get(md); + } - public boolean isLoopingBranch(MethodDescriptor md, FlatCondBranch fcb) { - return getLoopBranches(md).contains(fcb); - } + public boolean isLoopingBranch(MethodDescriptor md, FlatCondBranch fcb) { + return getLoopBranches(md).contains(fcb); + } - private void doAnalysis(MethodDescriptor md) { - FlatMethod fm=state.getMethodFlat(md); - HashSet nodeset=new HashSet(); - nodeset.addAll(fm.getNodeSet()); - Hashtable> table=new Hashtable>(); + private void doAnalysis(MethodDescriptor md) { + FlatMethod fm=state.getMethodFlat(md); + HashSet nodeset=new HashSet(); + nodeset.addAll(fm.getNodeSet()); + Hashtable> table=new Hashtable>(); - HashSet loopbranchset=new HashSet(); - HashSet exitset=new HashSet(); - - while(!nodeset.isEmpty()) { - 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); - } else if (fn.kind()==FKind.FlatReturnNode) { - if (table.containsKey(fn)) - exitset.addAll(table.get(fn)); - } else { - for(int i=0;i loopbranchset=new HashSet(); + HashSet exitset=new HashSet(); + + while(!nodeset.isEmpty()) { + 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); + } else if (fn.kind()==FKind.FlatReturnNode) { + if (table.containsKey(fn)) + exitset.addAll(table.get(fn)); + } else { + for(int i=0; i tovisit, Hashtable> table, FlatNode fn, FlatNode fnnext, FlatCondBranch fcb) { - boolean enqueuechange=false; - if (table.containsKey(fn)) { - if (!table.containsKey(fnnext)) - table.put(fnnext, new HashSet()); - HashSet toadd=new HashSet(); - toadd.addAll(table.get(fn)); - if (toadd.contains(fnnext)) //can't propagate back to node - toadd.remove(fnnext); - if(!table.get(fnnext).containsAll(toadd)) { - table.get(fnnext).addAll(toadd); - enqueuechange=true; - } - } - if (fcb!=null) { - if (!table.containsKey(fnnext)) - table.put(fnnext, new HashSet()); - if (!table.get(fnnext).contains(fcb)) { - table.get(fnnext).add(fcb); - enqueuechange=true; - } - } - if (enqueuechange) - tovisit.add(fnnext); + void propagateset(Set tovisit, Hashtable> table, FlatNode fn, FlatNode fnnext, FlatCondBranch fcb) { + boolean enqueuechange=false; + if (table.containsKey(fn)) { + if (!table.containsKey(fnnext)) + table.put(fnnext, new HashSet()); + HashSet toadd=new HashSet(); + toadd.addAll(table.get(fn)); + if (toadd.contains(fnnext)) //can't propagate back to node + toadd.remove(fnnext); + if(!table.get(fnnext).containsAll(toadd)) { + table.get(fnnext).addAll(toadd); + enqueuechange=true; + } + } + if (fcb!=null) { + if (!table.containsKey(fnnext)) + table.put(fnnext, new HashSet()); + if (!table.get(fnnext).contains(fcb)) { + table.get(fnnext).add(fcb); + enqueuechange=true; + } } + if (enqueuechange) + tovisit.add(fnnext); + } } diff --git a/Robust/src/Analysis/Prefetch/PairMap.java b/Robust/src/Analysis/Prefetch/PairMap.java index e8f47fa7..905fd801 100644 --- a/Robust/src/Analysis/Prefetch/PairMap.java +++ b/Robust/src/Analysis/Prefetch/PairMap.java @@ -17,61 +17,61 @@ import IR.*; */ public class PairMap { - public HashMap mappair; - - public PairMap() { - mappair = new HashMap(); - } - - public void addPair(PrefetchPair ppKey, PrefetchPair ppValue) { - mappair.put(ppKey, ppValue); - } - - public void removePair(PrefetchPair ppKey) { - mappair.remove(ppKey); - } - - public PrefetchPair getPair(PrefetchPair ppKey) { - if(mappair != null) - return mappair.get(ppKey); - return null; - } - - public int hashCode() { - return mappair.hashCode(); - } - - public int size() { - return mappair.size(); - } - - public boolean contains(PrefetchPair ppKey) { - if(mappair.containsKey(ppKey)) - return true; - return false; - } + public HashMap mappair; - public String toString() { - String label = null; - Set mapping = mappair.entrySet(); - Iterator it = mapping.iterator(); - label = "Mappings are: "; - for(;it.hasNext();) { - Object o = it.next(); - label += o.toString() + " , "; - } - return label; - } + public PairMap() { + mappair = new HashMap(); + } - public boolean equals(Object o) { - if(o instanceof PairMap) { - PairMap pm = (PairMap) o; - return mappair.equals(pm.mappair); - } - return false; + public void addPair(PrefetchPair ppKey, PrefetchPair ppValue) { + mappair.put(ppKey, ppValue); + } + + public void removePair(PrefetchPair ppKey) { + mappair.remove(ppKey); + } + + public PrefetchPair getPair(PrefetchPair ppKey) { + if(mappair != null) + return mappair.get(ppKey); + return null; + } + + public int hashCode() { + return mappair.hashCode(); + } + + public int size() { + return mappair.size(); + } + + public boolean contains(PrefetchPair ppKey) { + if(mappair.containsKey(ppKey)) + return true; + return false; + } + + public String toString() { + String label = null; + Set mapping = mappair.entrySet(); + Iterator it = mapping.iterator(); + label = "Mappings are: "; + for(; it.hasNext();) { + Object o = it.next(); + label += o.toString() + " , "; } - - public boolean isEmpty() { - return mappair.isEmpty(); + return label; + } + + public boolean equals(Object o) { + if(o instanceof PairMap) { + PairMap pm = (PairMap) o; + return mappair.equals(pm.mappair); } + return false; + } + + public boolean isEmpty() { + return mappair.isEmpty(); + } } diff --git a/Robust/src/Analysis/Prefetch/PrefetchAnalysis.java b/Robust/src/Analysis/Prefetch/PrefetchAnalysis.java index abab858f..9fcde860 100644 --- a/Robust/src/Analysis/Prefetch/PrefetchAnalysis.java +++ b/Robust/src/Analysis/Prefetch/PrefetchAnalysis.java @@ -15,989 +15,997 @@ import IR.*; import IR.ClassDescriptor; public class PrefetchAnalysis { - State state; - CallGraph callgraph; - TypeUtil typeutil; - LoopExit loop; - - Set tovisit; - public Hashtable> prefetch_hash;//holds all flatnodes and corresponding prefetch set - public Hashtable> pmap_hash;//holds all flatnodes and mappings between child prefetch pair and parent prefetch pair - public static final double PROB_DIFF = 0.05; //threshold for difference in probabilities during first phase of analysis - public static final double ANALYSIS_THRESHOLD_PROB = 0.10; //threshold for prefetches to stop propagating during first phase of analysis - public static final double PREFETCH_THRESHOLD_PROB = 0.30;//threshold for prefetches to stop propagating while applying prefetch rules during second phase of analysis - public static int prefetchsiteid = 1; //initialized to one because there is a prefetch siteid 0 for starting remote thread - LocalityAnalysis locality; - - public PrefetchAnalysis(State state, CallGraph callgraph, TypeUtil typeutil, LocalityAnalysis locality) { - this.typeutil=typeutil; - this.state=state; - this.callgraph=callgraph; - this.locality=locality; - prefetch_hash = new Hashtable>(); - pmap_hash = new Hashtable>(); - this.loop=new LoopExit(state); - DoPrefetch(); - } - - - /** This function starts the prefetch analysis */ - private void DoPrefetch() { - for (Iterator methodit=locality.getMethods().iterator();methodit.hasNext();) { - MethodDescriptor md=(MethodDescriptor)methodit.next(); - if (state.excprefetch.contains(md.getClassMethodName())) - continue; //Skip this method - Hashtable> newprefetchset = new Hashtable>(); - FlatMethod fm=state.getMethodFlat(md); - doFlatNodeAnalysis(fm); - doInsPrefetchAnalysis(fm, newprefetchset); - if(newprefetchset.size() > 0) { - addFlatPrefetchNode(newprefetchset); - } - newprefetchset = null; - } + State state; + CallGraph callgraph; + TypeUtil typeutil; + LoopExit loop; + + Set tovisit; + public Hashtable> prefetch_hash; //holds all flatnodes and corresponding prefetch set + public Hashtable> pmap_hash; //holds all flatnodes and mappings between child prefetch pair and parent prefetch pair + public static final double PROB_DIFF = 0.05; //threshold for difference in probabilities during first phase of analysis + public static final double ANALYSIS_THRESHOLD_PROB = 0.10; //threshold for prefetches to stop propagating during first phase of analysis + public static final double PREFETCH_THRESHOLD_PROB = 0.30; //threshold for prefetches to stop propagating while applying prefetch rules during second phase of analysis + public static int prefetchsiteid = 1; //initialized to one because there is a prefetch siteid 0 for starting remote thread + LocalityAnalysis locality; + + public PrefetchAnalysis(State state, CallGraph callgraph, TypeUtil typeutil, LocalityAnalysis locality) { + this.typeutil=typeutil; + this.state=state; + this.callgraph=callgraph; + this.locality=locality; + prefetch_hash = new Hashtable>(); + pmap_hash = new Hashtable>(); + this.loop=new LoopExit(state); + DoPrefetch(); + } + + + /** This function starts the prefetch analysis */ + private void DoPrefetch() { + for (Iterator methodit=locality.getMethods().iterator(); methodit.hasNext();) { + MethodDescriptor md=(MethodDescriptor)methodit.next(); + if (state.excprefetch.contains(md.getClassMethodName())) + continue; //Skip this method + Hashtable> newprefetchset = new Hashtable>(); + FlatMethod fm=state.getMethodFlat(md); + doFlatNodeAnalysis(fm); + doInsPrefetchAnalysis(fm, newprefetchset); + if(newprefetchset.size() > 0) { + addFlatPrefetchNode(newprefetchset); + } + newprefetchset = null; } - - /** This function calls analysis for every node in a method */ - private void doFlatNodeAnalysis(FlatMethod fm) { - tovisit = fm.getNodeSet(); - Hashtable nodehash = new Hashtable(); - /* Create Empty Prefetch Sets for all flat nodes in the global hashtable */ - while(!tovisit.isEmpty()) { - FlatNode fn = (FlatNode)tovisit.iterator().next(); - prefetch_hash.put(fn, nodehash); - tovisit.remove(fn); - } + } - /* Visit and process nodes */ - tovisit = fm.getNodeSet(); - while(!tovisit.isEmpty()) { - FlatNode fn = (FlatNode)tovisit.iterator().next(); - doChildNodeAnalysis(fm.getMethod(),fn); - tovisit.remove(fn); - } + /** This function calls analysis for every node in a method */ + private void doFlatNodeAnalysis(FlatMethod fm) { + tovisit = fm.getNodeSet(); + Hashtable nodehash = new Hashtable(); + /* Create Empty Prefetch Sets for all flat nodes in the global hashtable */ + while(!tovisit.isEmpty()) { + FlatNode fn = (FlatNode)tovisit.iterator().next(); + prefetch_hash.put(fn, nodehash); + tovisit.remove(fn); } - - /** - * This function generates the prefetch sets for a given Flatnode considering the kind of node - * It calls severals functions based on the kind of the node and - * returns true: if the prefetch set has changed since last time the node was analysed - * returns false : otherwise - */ - private void doChildNodeAnalysis(MethodDescriptor md, FlatNode curr) { - if (curr.kind()==FKind.FlatCondBranch) { - processFlatCondBranch((FlatCondBranch)curr, md); - } 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(); - } - } - switch(curr.kind()) { - case FKind.FlatCall: - processCall((FlatCall)curr,child_prefetch_set_copy); - break; - - case FKind.FlatBackEdge: - case FKind.FlatCheckNode: - case FKind.FlatReturnNode: - case FKind.FlatAtomicEnterNode: - case FKind.FlatAtomicExitNode: - case FKind.FlatFlagActionNode: - case FKind.FlatGlobalConvNode: - case FKind.FlatNop: - case FKind.FlatNew: - case FKind.FlatCastNode: - case FKind.FlatTagDeclaration: - 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; - case FKind.FlatFieldNode: - processFlatFieldNode(curr, child_prefetch_set_copy); - break; - case FKind.FlatElementNode: - processFlatElementNode(curr, child_prefetch_set_copy); - break; - case FKind.FlatOpNode: - processFlatOpNode(curr, child_prefetch_set_copy); - break; - case FKind.FlatLiteralNode: - processFlatLiteralNode(curr, child_prefetch_set_copy); - break; - case FKind.FlatSetElementNode: - processFlatSetElementNode(curr, child_prefetch_set_copy); - break; - case FKind.FlatSetFieldNode: - processFlatSetFieldNode(curr, child_prefetch_set_copy); - break; - default: - throw new Error("No such Flatnode kind"); - } - } + /* Visit and process nodes */ + tovisit = fm.getNodeSet(); + while(!tovisit.isEmpty()) { + FlatNode fn = (FlatNode)tovisit.iterator().next(); + doChildNodeAnalysis(fm.getMethod(),fn); + tovisit.remove(fn); } - - /**This function compares all the prefetch pairs in a Prefetch set hashtable and - * returns: true if something has changed in the new Prefetch set else - * returns: false - */ - private boolean comparePrefetchSets(Hashtable oldPrefetchSet, Hashtable newPrefetchSet) { - if (oldPrefetchSet.size()!=newPrefetchSet.size()) - return true; - - for(Enumeration e = newPrefetchSet.keys();e.hasMoreElements();) { - PrefetchPair pp = (PrefetchPair) e.nextElement(); - double newprob = newPrefetchSet.get(pp).doubleValue(); - if (!oldPrefetchSet.containsKey(pp)) - return true; - double oldprob = oldPrefetchSet.get(pp).doubleValue(); - - if((newprob - oldprob) > PROB_DIFF) { - return true; - } - if (newprob >= PREFETCH_THRESHOLD_PROB && oldprob < PREFETCH_THRESHOLD_PROB) { - return true; - } - if (oldprob>newprob) { - System.out.println("ERROR:" + pp); - System.out.println(oldprob + " -> "+ newprob); - } + } + + /** + * This function generates the prefetch sets for a given Flatnode considering the kind of node + * It calls severals functions based on the kind of the node and + * returns true: if the prefetch set has changed since last time the node was analysed + * returns false : otherwise + */ + private void doChildNodeAnalysis(MethodDescriptor md, FlatNode curr) { + if (curr.kind()==FKind.FlatCondBranch) { + processFlatCondBranch((FlatCondBranch)curr, md); + } 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(); } - return false; + + } + switch(curr.kind()) { + case FKind.FlatCall: + processCall((FlatCall)curr,child_prefetch_set_copy); + break; + + case FKind.FlatBackEdge: + case FKind.FlatCheckNode: + case FKind.FlatReturnNode: + case FKind.FlatAtomicEnterNode: + case FKind.FlatAtomicExitNode: + case FKind.FlatFlagActionNode: + case FKind.FlatGlobalConvNode: + case FKind.FlatNop: + case FKind.FlatNew: + case FKind.FlatCastNode: + case FKind.FlatTagDeclaration: + 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; + + case FKind.FlatFieldNode: + processFlatFieldNode(curr, child_prefetch_set_copy); + break; + + case FKind.FlatElementNode: + processFlatElementNode(curr, child_prefetch_set_copy); + break; + + case FKind.FlatOpNode: + processFlatOpNode(curr, child_prefetch_set_copy); + break; + + case FKind.FlatLiteralNode: + processFlatLiteralNode(curr, child_prefetch_set_copy); + break; + + case FKind.FlatSetElementNode: + processFlatSetElementNode(curr, child_prefetch_set_copy); + break; + + case FKind.FlatSetFieldNode: + processFlatSetFieldNode(curr, child_prefetch_set_copy); + break; + + default: + throw new Error("No such Flatnode kind"); + } } + } - private void updatePairMap(FlatNode curr, PairMap pm, int index) { - if (index>=curr.numNext()) - return; - if (!pmap_hash.containsKey(curr.getNext(index))) { - pmap_hash.put(curr.getNext(index), new Hashtable()); - } - pmap_hash.get(curr.getNext(index)).put(curr, pm); + /**This function compares all the prefetch pairs in a Prefetch set hashtable and + * returns: true if something has changed in the new Prefetch set else + * returns: false + */ + private boolean comparePrefetchSets(Hashtable oldPrefetchSet, Hashtable newPrefetchSet) { + if (oldPrefetchSet.size()!=newPrefetchSet.size()) + return true; + + for(Enumeration e = newPrefetchSet.keys(); e.hasMoreElements();) { + PrefetchPair pp = (PrefetchPair) e.nextElement(); + double newprob = newPrefetchSet.get(pp).doubleValue(); + if (!oldPrefetchSet.containsKey(pp)) + return true; + double oldprob = oldPrefetchSet.get(pp).doubleValue(); + + if((newprob - oldprob) > PROB_DIFF) { + return true; + } + if (newprob >= PREFETCH_THRESHOLD_PROB && oldprob < PREFETCH_THRESHOLD_PROB) { + return true; + } + if (oldprob>newprob) { + System.out.println("ERROR:" + pp); + System.out.println(oldprob + " -> "+ newprob); + } } + return false; + } - private void updatePrefetchSet(FlatNode curr, Hashtable newset) { - Hashtableoldset=prefetch_hash.get(curr); - if (comparePrefetchSets(oldset, newset)) { - for(int i=0;i=curr.numNext()) + return; + if (!pmap_hash.containsKey(curr.getNext(index))) { + pmap_hash.put(curr.getNext(index), new Hashtable()); } + pmap_hash.get(curr.getNext(index)).put(curr, pm); + } - - /** This function processes the prefetch set of FlatFieldNode - * It generates a new prefetch set after comparision with its children - * Then compares it with its old prefetch set - * If old prefetch set is not same as new prefetch set then enqueue the parents - * of the current FlatFieldNode - * */ - private void processFlatFieldNode(FlatNode curr, Hashtable child_prefetch_set_copy) { - Hashtable currcopy = new Hashtable(); - Hashtable tocompare = new Hashtable(); - FlatFieldNode currffn = (FlatFieldNode) curr; - PairMap pm = new PairMap(); - - /* Do Self analysis of the current node*/ - FieldDescriptor currffn_field = currffn.getField(); - TempDescriptor currffn_src = currffn.getSrc(); - if (currffn_field.getType().isPtr()) { - PrefetchPair pp = new PrefetchPair(currffn_src, (Descriptor) currffn_field); - Double prob = new Double(1.0); - tocompare.put(pp, prob); - } - - /* Get each prefetch pair of the child and match it with the destination temp descriptor of curr FlatFieldNode */ - - for (Enumeration ecld = child_prefetch_set_copy.keys();ecld.hasMoreElements();) { - PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); - if (childpp.base == currffn.getDst() && (childpp.getDesc()!= null)) { - 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); - } else if(childpp.containsTemp(currffn.getDst())) { - 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); - } - } + private void updatePrefetchSet(FlatNode curr, Hashtable newset) { + Hashtableoldset=prefetch_hash.get(curr); + if (comparePrefetchSets(oldset, newset)) { + for(int i=0; i it=tocompare.keySet().iterator();it.hasNext();) { - PrefetchPair pp=it.next(); - if (tocompare.get(pp) child_prefetch_set_copy) { - - Hashtable currcopy = new Hashtable(); - Hashtable tocompare = new Hashtable(); - FlatElementNode currfen = (FlatElementNode) curr; - PairMap pm = new PairMap(); - - - /* Do Self analysis of the current node*/ - TempDescriptor currfen_index = currfen.getIndex(); - IndexDescriptor idesc = new IndexDescriptor(currfen_index, 0); - TempDescriptor currfen_src = currfen.getSrc(); - if(currfen.getDst().getType().isPtr()) { - PrefetchPair pp = new PrefetchPair(currfen_src, (Descriptor) idesc); - Double prob = new Double(1.0); - currcopy.put(pp, prob); - } - - /* Get each prefetch pair of the child and match it with the destination temp descriptor of curr FlatFieldNode */ - PrefetchPair currpp = null; - for (Enumeration ecld = child_prefetch_set_copy.keys();ecld.hasMoreElements();) { - PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); - if (childpp.base == currfen.getDst() && (childpp.getDesc()!= null)) { - 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); - } else if(childpp.containsTemp(currfen.getDst())) { - child_prefetch_set_copy.remove(childpp); + + /** This function processes the prefetch set of FlatFieldNode + * It generates a new prefetch set after comparision with its children + * Then compares it with its old prefetch set + * If old prefetch set is not same as new prefetch set then enqueue the parents + * of the current FlatFieldNode + * */ + private void processFlatFieldNode(FlatNode curr, Hashtable child_prefetch_set_copy) { + Hashtable currcopy = new Hashtable(); + Hashtable tocompare = new Hashtable(); + FlatFieldNode currffn = (FlatFieldNode) curr; + PairMap pm = new PairMap(); + + /* Do Self analysis of the current node*/ + FieldDescriptor currffn_field = currffn.getField(); + TempDescriptor currffn_src = currffn.getSrc(); + if (currffn_field.getType().isPtr()) { + PrefetchPair pp = new PrefetchPair(currffn_src, (Descriptor) currffn_field); + Double prob = new Double(1.0); + tocompare.put(pp, prob); + } + + /* Get each prefetch pair of the child and match it with the destination temp descriptor of curr FlatFieldNode */ + + for (Enumeration ecld = child_prefetch_set_copy.keys(); ecld.hasMoreElements();) { + PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); + if (childpp.base == currffn.getDst() && (childpp.getDesc()!= null)) { + 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); + } else if(childpp.containsTemp(currffn.getDst())) { + 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); + } + } + + for(Iterator it=tocompare.keySet().iterator(); it.hasNext();) { + PrefetchPair pp=it.next(); + if (tocompare.get(pp) child_prefetch_set_copy) { + + Hashtable currcopy = new Hashtable(); + Hashtable tocompare = new Hashtable(); + FlatElementNode currfen = (FlatElementNode) curr; + PairMap pm = new PairMap(); + + + /* Do Self analysis of the current node*/ + TempDescriptor currfen_index = currfen.getIndex(); + IndexDescriptor idesc = new IndexDescriptor(currfen_index, 0); + TempDescriptor currfen_src = currfen.getSrc(); + if(currfen.getDst().getType().isPtr()) { + PrefetchPair pp = new PrefetchPair(currfen_src, (Descriptor) idesc); + Double prob = new Double(1.0); + currcopy.put(pp, prob); + } + + /* Get each prefetch pair of the child and match it with the destination temp descriptor of curr FlatFieldNode */ + PrefetchPair currpp = null; + for (Enumeration ecld = child_prefetch_set_copy.keys(); ecld.hasMoreElements();) { + PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); + if (childpp.base == currfen.getDst() && (childpp.getDesc()!= null)) { + 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 { - continue; + tocompare.put(newpp, newprob); + pm.addPair(newpp, newpp); } - } - /* Check if curr prefetch set and the child prefetch set have same prefetch pairs - * if so calculate the new probability */ - 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; - } - } - } - - /* Merge child prefetch pairs */ - for (Enumeration ecld = child_prefetch_set_copy.keys();ecld.hasMoreElements();) { - PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); - tocompare.put(childpp, child_prefetch_set_copy.get(childpp).doubleValue()); - pm.addPair(childpp, childpp); - child_prefetch_set_copy.remove(childpp); - } - - /* Merge curr prefetch pairs */ - for (Enumeration e = currcopy.keys();e.hasMoreElements();) { - currpp = (PrefetchPair) e.nextElement(); - tocompare.put(currpp, currcopy.get(currpp).doubleValue()); - currcopy.remove(currpp); - } - - updatePairMap(curr, pm, 0); - updatePrefetchSet(curr, tocompare); - } - - /** This function processes the prefetch set of a FlatSetFieldNode - * It generates a new prefetch set after comparision with its children - * It compares the old prefetch set with this new prefetch set and enqueues the parents - * of the current node if change occurs and then updates the global flatnode hash table - * */ - private void processFlatSetFieldNode(FlatNode curr, Hashtable child_prefetch_set_copy) { - Hashtable tocompare = new Hashtable(); - FlatSetFieldNode currfsfn = (FlatSetFieldNode) curr; - PairMap pm = new PairMap(); - - 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; - } + child_prefetch_set_copy.remove(newpp); + } + } + } else if(childpp.base == currfen.getDst() && (childpp.getDesc() == null)) { + child_prefetch_set_copy.remove(childpp); + } else if(childpp.containsTemp(currfen.getDst())) { + child_prefetch_set_copy.remove(childpp); + } else { + continue; + } + } + /* Check if curr prefetch set and the child prefetch set have same prefetch pairs + * if so calculate the new probability */ + 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; + } + } + } + + /* Merge child prefetch pairs */ + for (Enumeration ecld = child_prefetch_set_copy.keys(); ecld.hasMoreElements();) { + PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); + tocompare.put(childpp, child_prefetch_set_copy.get(childpp).doubleValue()); + pm.addPair(childpp, childpp); + child_prefetch_set_copy.remove(childpp); + } + + /* Merge curr prefetch pairs */ + for (Enumeration e = currcopy.keys(); e.hasMoreElements();) { + currpp = (PrefetchPair) e.nextElement(); + tocompare.put(currpp, currcopy.get(currpp).doubleValue()); + currcopy.remove(currpp); + } + + updatePairMap(curr, pm, 0); + updatePrefetchSet(curr, tocompare); + } + + /** This function processes the prefetch set of a FlatSetFieldNode + * It generates a new prefetch set after comparision with its children + * It compares the old prefetch set with this new prefetch set and enqueues the parents + * of the current node if change occurs and then updates the global flatnode hash table + * */ + private void processFlatSetFieldNode(FlatNode curr, Hashtable child_prefetch_set_copy) { + Hashtable tocompare = new Hashtable(); + FlatSetFieldNode currfsfn = (FlatSetFieldNode) curr; + PairMap pm = new PairMap(); + + 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)); } - } - - /* Merge child prefetch pairs */ - for (Enumeration ecld = child_prefetch_set_copy.keys();ecld.hasMoreElements();) { - PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); - tocompare.put(childpp, child_prefetch_set_copy.get(childpp).doubleValue()); - pm.addPair(childpp, childpp); + 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); - } - - updatePairMap(curr, pm, 0); - updatePrefetchSet(curr, tocompare); - } - - /** This function processes the prefetch set of a FlatSetElementNode - * It generates a new prefetch set after comparision with its children - * It compares the old prefetch set with this new prefetch set and enqueues the parents - * of the current node if change occurs and then updates the global flatnode hash table - * */ - private void processFlatSetElementNode(FlatNode curr, Hashtable child_prefetch_set_copy) { - Hashtable tocompare = new Hashtable(); - FlatSetElementNode currfsen = (FlatSetElementNode) curr; - PairMap pm = new PairMap(); - - 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; - } - } + /* 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); } - } - /* Merge child prefetch pairs */ - for (Enumeration ecld = child_prefetch_set_copy.keys();ecld.hasMoreElements();) { - PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); - tocompare.put(childpp, child_prefetch_set_copy.get(childpp).doubleValue()); - pm.addPair(childpp, childpp); + } + } 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; } - - updatePairMap(curr, pm, 0); - updatePrefetchSet(curr, tocompare); - } - - /** This function applies rules and does analysis for a FlatOpNode - * And updates the global prefetch hashtable - * */ - private void processFlatOpNode(FlatNode curr, Hashtable child_prefetch_set_copy) { - int index; - Hashtable tocompare = new Hashtable(); - FlatOpNode currfopn = (FlatOpNode) curr; - PairMap pm = new PairMap(); - - 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; + } + } + + /* Merge child prefetch pairs */ + for (Enumeration ecld = child_prefetch_set_copy.keys(); ecld.hasMoreElements();) { + PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); + tocompare.put(childpp, child_prefetch_set_copy.get(childpp).doubleValue()); + pm.addPair(childpp, childpp); + child_prefetch_set_copy.remove(childpp); + } + + updatePairMap(curr, pm, 0); + updatePrefetchSet(curr, tocompare); + } + + /** This function processes the prefetch set of a FlatSetElementNode + * It generates a new prefetch set after comparision with its children + * It compares the old prefetch set with this new prefetch set and enqueues the parents + * of the current node if change occurs and then updates the global flatnode hash table + * */ + private void processFlatSetElementNode(FlatNode curr, Hashtable child_prefetch_set_copy) { + Hashtable tocompare = new Hashtable(); + FlatSetElementNode currfsen = (FlatSetElementNode) curr; + PairMap pm = new PairMap(); + + 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 { - continue; + 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 */ + for (Enumeration ecld = child_prefetch_set_copy.keys(); ecld.hasMoreElements();) { + PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); + tocompare.put(childpp, child_prefetch_set_copy.get(childpp).doubleValue()); + pm.addPair(childpp, childpp); + child_prefetch_set_copy.remove(childpp); + } + + updatePairMap(curr, pm, 0); + updatePrefetchSet(curr, tocompare); + } + + /** This function applies rules and does analysis for a FlatOpNode + * And updates the global prefetch hashtable + * */ + private void processFlatOpNode(FlatNode curr, Hashtable child_prefetch_set_copy) { + int index; + Hashtable tocompare = new Hashtable(); + FlatOpNode currfopn = (FlatOpNode) curr; + PairMap pm = new PairMap(); + + 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); } - //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; - } + 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); } - } 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); - } - } - } else { - //FIXME Is not taken care of for cases like x = -y followed by a[x].i - } - - /* Merge child prefetch pairs */ - for (Enumeration ecld = child_prefetch_set_copy.keys();ecld.hasMoreElements();) { - PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); - tocompare.put(childpp, child_prefetch_set_copy.get(childpp).doubleValue()); - pm.addPair(childpp, childpp); - child_prefetch_set_copy.remove(childpp); - } - - updatePairMap(curr, pm, 0); - updatePrefetchSet(curr, tocompare); - } - - /** This function processes a FlatLiteralNode where cases such as - * for e.g. i = 0 with child prefetch sets a[i].r, a[j+i].r or a[j].b[i].r - * are handled */ - private void processFlatLiteralNode(FlatNode curr, Hashtable child_prefetch_set_copy) { - Hashtable tocompare = new Hashtable(); - FlatLiteralNode currfln = (FlatLiteralNode) curr; - PairMap pm = new PairMap(); - - 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); - } - } + 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; } - - /* Merge child prefetch pairs */ - for (Enumeration ecld = child_prefetch_set_copy.keys();ecld.hasMoreElements();) { - PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); - tocompare.put(childpp, child_prefetch_set_copy.get(childpp).doubleValue()); - pm.addPair(childpp, childpp); - child_prefetch_set_copy.remove(childpp); - } - - updatePairMap(curr, pm, 0); - updatePrefetchSet(curr, tocompare); - } - - /** This function processes a FlatMethod where the method propagates - * the entire prefetch set of its child node */ - private void processFlatMethod(FlatNode curr, Hashtable child_prefetch_set_copy) { - Hashtable tocompare = new Hashtable(); - FlatMethod currfm = (FlatMethod) curr; - PairMap pm = new PairMap(); - - /* Merge child prefetch pairs */ - for (Enumeration ecld = child_prefetch_set_copy.keys();ecld.hasMoreElements();) { - PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); - tocompare.put(childpp, child_prefetch_set_copy.get(childpp).doubleValue()); - pm.addPair(childpp, childpp); + } + } 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); } - - updatePairMap(curr, pm, 0); - updatePrefetchSet(curr, tocompare); - } - - /** This function handles the processes the FlatNode of type FlatCondBranch - * It combines prefetches of both child elements and create a new hash table called - * branch_prefetch_set to contains the entries of both its children - */ - private void processFlatCondBranch(FlatCondBranch fcb, MethodDescriptor md) { - Hashtable tocompare = new Hashtable();//temporary hash table - PairMap truepm = new PairMap(); - PairMap falsepm = new PairMap(); - Hashtable truechild=prefetch_hash.get(fcb.getNext(0)); - Hashtable falsechild=prefetch_hash.get(fcb.getNext(1)); - - HashSet allpp=new HashSet(); - allpp.addAll(truechild.keySet()); - allpp.addAll(falsechild.keySet()); - - for(Iterator ppit=allpp.iterator();ppit.hasNext();) { - PrefetchPair pp=ppit.next(); - double trueprob=0,falseprob=0; - if (truechild.containsKey(pp)) - trueprob=truechild.get(pp).doubleValue(); - if (falsechild.containsKey(pp)) - falseprob=falsechild.get(pp).doubleValue(); - - double newprob=trueprob*fcb.getTrueProb()+falseprob*fcb.getFalseProb(); - if (loop.isLoopingBranch(md,fcb)&& - newprob child_prefetch_set_copy) { - PairMap pm = new PairMap(); - Hashtable tocompare = new Hashtable(); - - /* Propagate all child nodes */ - nexttemp: - for(Enumeration e = child_prefetch_set_copy.keys(); e.hasMoreElements();) { - PrefetchPair childpp = (PrefetchPair) e.nextElement(); - TempDescriptor[] writearray=curr.writesTemps(); - for(int i=0;i child_prefetch_set_copy) { - PairMap pm = new PairMap(); - Hashtable tocompare = new Hashtable(); - - /* Don't propagate prefetches across cache clear */ - if (!(curr.getMethod().getClassMethodName().equals("System.clearPrefetchCache")|| - curr.getMethod().getClassMethodName().equals("Barrier.enterBarrier"))) { - /* Propagate all child nodes */ - nexttemp: - for(Enumeration e = child_prefetch_set_copy.keys(); e.hasMoreElements();) { - PrefetchPair childpp = (PrefetchPair) e.nextElement(); - TempDescriptor[] writearray=curr.writesTemps(); - for(int i=0;i child_prefetch_set_copy) { + Hashtable tocompare = new Hashtable(); + FlatLiteralNode currfln = (FlatLiteralNode) curr; + PairMap pm = new PairMap(); + + 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(); + } } - tocompare.put(childpp, child_prefetch_set_copy.get(childpp)); - pm.addPair(childpp, childpp); - } - - } - updatePairMap(curr, pm, 0); - updatePrefetchSet(curr, tocompare); - } - - /** This function prints the Prefetch pairs of a given flatnode */ - private void printPrefetchPairs(FlatNode fn) { - System.out.println(fn); - if(prefetch_hash.containsKey(fn)) { - System.out.print("Prefetch" + "("); - Hashtable currhash = (Hashtable) prefetch_hash.get(fn); - for(Enumeration pphash= currhash.keys(); pphash.hasMoreElements();) { - PrefetchPair pp = (PrefetchPair) pphash.nextElement(); - System.out.print(pp.toString() + ", "); + } + 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); } - System.out.println(")"); - } else { - System.out.println("Flatnode is currently not present in the global hash: Prefetch Set is Empty"); + child_prefetch_set_copy.remove(newpp); + } } + } } - private void doInsPrefetchAnalysis(FlatMethod fm, Hashtable> newprefetchset) { - Hashtable> pset1_hash = new Hashtable>(); - HashSet pset1_init = new HashSet(); - LinkedList newtovisit = new LinkedList(); - LinkedList newvisited = new LinkedList(); - - newtovisit.addLast((FlatNode)fm); - while(!newtovisit.isEmpty()) { - FlatNode fn = (FlatNode) newtovisit.iterator().next(); - newtovisit.remove(0); - pset1_hash.put(fn, pset1_init); //Initialize pset1_hash - newvisited.addLast(fn); - for(int i=0; i> newprefetchset) { - for (Enumeration e = newprefetchset.keys();e.hasMoreElements();) { - FlatNode fn = (FlatNode) e.nextElement(); - Set ppairs = newprefetchset.get(fn); - 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); - } - } - - ppairs.removeAll(toremove); + /* Merge child prefetch pairs */ + for (Enumeration ecld = child_prefetch_set_copy.keys(); ecld.hasMoreElements();) { + PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); + tocompare.put(childpp, child_prefetch_set_copy.get(childpp).doubleValue()); + pm.addPair(childpp, childpp); + child_prefetch_set_copy.remove(childpp); + } + + updatePairMap(curr, pm, 0); + updatePrefetchSet(curr, tocompare); + } + + /** This function processes a FlatMethod where the method propagates + * the entire prefetch set of its child node */ + private void processFlatMethod(FlatNode curr, Hashtable child_prefetch_set_copy) { + Hashtable tocompare = new Hashtable(); + FlatMethod currfm = (FlatMethod) curr; + PairMap pm = new PairMap(); + + /* Merge child prefetch pairs */ + for (Enumeration ecld = child_prefetch_set_copy.keys(); ecld.hasMoreElements();) { + PrefetchPair childpp = (PrefetchPair) ecld.nextElement(); + tocompare.put(childpp, child_prefetch_set_copy.get(childpp).doubleValue()); + pm.addPair(childpp, childpp); + } + + updatePairMap(curr, pm, 0); + updatePrefetchSet(curr, tocompare); + } + + /** This function handles the processes the FlatNode of type FlatCondBranch + * It combines prefetches of both child elements and create a new hash table called + * branch_prefetch_set to contains the entries of both its children + */ + private void processFlatCondBranch(FlatCondBranch fcb, MethodDescriptor md) { + Hashtable tocompare = new Hashtable(); //temporary hash table + PairMap truepm = new PairMap(); + PairMap falsepm = new PairMap(); + Hashtable truechild=prefetch_hash.get(fcb.getNext(0)); + Hashtable falsechild=prefetch_hash.get(fcb.getNext(1)); + + HashSet allpp=new HashSet(); + allpp.addAll(truechild.keySet()); + allpp.addAll(falsechild.keySet()); + + for(Iterator ppit=allpp.iterator(); ppit.hasNext();) { + PrefetchPair pp=ppit.next(); + double trueprob=0,falseprob=0; + if (truechild.containsKey(pp)) + trueprob=truechild.get(pp).doubleValue(); + if (falsechild.containsKey(pp)) + falseprob=falsechild.get(pp).doubleValue(); + + double newprob=trueprob*fcb.getTrueProb()+falseprob*fcb.getFalseProb(); + if (loop.isLoopingBranch(md,fcb)&& + newprob child_prefetch_set_copy) { + PairMap pm = new PairMap(); + Hashtable tocompare = new Hashtable(); + + /* Propagate all child nodes */ +nexttemp: + for(Enumeration e = child_prefetch_set_copy.keys(); e.hasMoreElements();) { + PrefetchPair childpp = (PrefetchPair) e.nextElement(); + TempDescriptor[] writearray=curr.writesTemps(); + for(int i=0; i child_prefetch_set_copy) { + PairMap pm = new PairMap(); + Hashtable tocompare = new Hashtable(); + + /* Don't propagate prefetches across cache clear */ + if (!(curr.getMethod().getClassMethodName().equals("System.clearPrefetchCache")|| + curr.getMethod().getClassMethodName().equals("Barrier.enterBarrier"))) { + /* Propagate all child nodes */ +nexttemp: + for(Enumeration e = child_prefetch_set_copy.keys(); e.hasMoreElements();) { + PrefetchPair childpp = (PrefetchPair) e.nextElement(); + TempDescriptor[] writearray=curr.writesTemps(); + for(int i=0; i currhash = (Hashtable) prefetch_hash.get(fn); + for(Enumeration pphash= currhash.keys(); pphash.hasMoreElements();) { + PrefetchPair pp = (PrefetchPair) pphash.nextElement(); + System.out.print(pp.toString() + ", "); + } + System.out.println(")"); + } else { + System.out.println("Flatnode is currently not present in the global hash: Prefetch Set is Empty"); + } + } + + private void doInsPrefetchAnalysis(FlatMethod fm, Hashtable> newprefetchset) { + Hashtable> pset1_hash = new Hashtable>(); + HashSet pset1_init = new HashSet(); + LinkedList newtovisit = new LinkedList(); + LinkedList newvisited = new LinkedList(); + + newtovisit.addLast((FlatNode)fm); + while(!newtovisit.isEmpty()) { + FlatNode fn = (FlatNode) newtovisit.iterator().next(); + newtovisit.remove(0); + pset1_hash.put(fn, pset1_init); //Initialize pset1_hash + newvisited.addLast(fn); + for(int i=0; i> newprefetchset) { + for (Enumeration e = newprefetchset.keys(); e.hasMoreElements();) { + FlatNode fn = (FlatNode) e.nextElement(); + Set ppairs = newprefetchset.get(fn); + 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); } + } + + ppairs.removeAll(toremove); } - - /** This function returns: true if the shorter prefetch pair is a subset of the longer prefetch - * pair else it returns: false */ - private boolean isSubSet(PrefetchPair shrt, PrefetchPair lng) { - if (shrt.base != lng.base) { + } + + /** This function returns: true if the shorter prefetch pair is a subset of the longer prefetch + * pair else it returns: false */ + private boolean isSubSet(PrefetchPair shrt, PrefetchPair lng) { + if (shrt.base != lng.base) { + return false; + } + 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; } - 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; - } - } else { - if ((Descriptor)shrt.getDescAt(j) != (Descriptor)lng.getDescAt(j)){ - return false; - } - } + } else { + if ((Descriptor)shrt.getDescAt(j) != (Descriptor)lng.getDescAt(j)){ + return false; } - return true; + } } + return true; + } - /**This function compares all the prefetch pairs in a Prefetch set hashtable and - * returns: true if something has changed in the new Prefetch set else - * returns: false - */ - private boolean comparePSet1(HashSet oldPSet, HashSetnewPSet) { - if(oldPSet.size() != newPSet.size()) { - return true; - } else { - for(Iterator it = newPSet.iterator();it.hasNext();) { - if(!oldPSet.contains((PrefetchPair)it.next())) { - return true; - } - } + /**This function compares all the prefetch pairs in a Prefetch set hashtable and + * returns: true if something has changed in the new Prefetch set else + * returns: false + */ + private boolean comparePSet1(HashSet oldPSet, HashSetnewPSet) { + if(oldPSet.size() != newPSet.size()) { + return true; + } else { + for(Iterator it = newPSet.iterator(); it.hasNext();) { + if(!oldPSet.contains((PrefetchPair)it.next())) { + return true; + } + } + } + return false; + } + + /** This function creates a set called pset1 that contains prefetch pairs that have already + * been prefetched. While traversing the graph of a flat representation in a top down fashion, + * this function creates pset1 such that it contains prefetch pairs that have been prefetched at + * the previous nodes */ + + private void applyPrefetchInsertRules(FlatNode fn, LinkedList newvisited, Hashtable> pset1_hash, Hashtable> newprefetchset) { + if(fn.kind() == FKind.FlatMethod) { + 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); + } + } + /* Enqueue child node if Pset1 has changed */ + if (comparePSet1(pset1_hash.get(fn), pset1)) { + for(int j=0; j pset2 = new HashSet(); + HashSet newpset = new HashSet(); + Hashtable 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 newvisited, Hashtable> pset1_hash, Hashtable> newprefetchset) { + + if(mapIsPresent) + pset2.add(pp); + + if(pprobIsGreater && mapprobIsLess) + newpset.add(pp); + } + + HashSet pset1 = new HashSet(); + pset1.addAll(pset2); + pset1.addAll(newpset); + /* Enqueue child node if Pset1 has changed */ + if (comparePSet1(pset1_hash.get(fn), pset1)) { + for(int i=0; i s = new HashSet(); + s.addAll(newpset); + s.removeAll(pset2); + newprefetchset.put(fn, s); + } + } + + private void addFlatPrefetchNode(Hashtable> newprefetchset) { + boolean isFNPresent = false; /* Detects presence of FlatNew node */ + /* This modifies the Flat representation graph */ + for(Enumeration e = newprefetchset.keys(); e.hasMoreElements();) { + FlatNode fn = (FlatNode) e.nextElement(); + FlatPrefetchNode fpn = new FlatPrefetchNode(); + if(newprefetchset.get(fn).size() > 0) { + fpn.insAllpp((HashSet)newprefetchset.get(fn)); if(fn.kind() == FKind.FlatMethod) { - 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); - } - } - /* Enqueue child node if Pset1 has changed */ - if (comparePSet1(pset1_hash.get(fn), pset1)) { - for(int j=0; j pset2 = new HashSet(); - HashSet newpset = new HashSet(); - Hashtable 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 pset1 = new HashSet(); - pset1.addAll(pset2); - pset1.addAll(newpset); - /* Enqueue child node if Pset1 has changed */ - if (comparePSet1(pset1_hash.get(fn), pset1)) { - for(int i=0; i 0) { + FlatNode nn = fn.getPrev(0); + for(int j = 0; j s = new HashSet(); - s.addAll(newpset); - s.removeAll(pset2); - newprefetchset.put(fn, s); - } - } - - private void addFlatPrefetchNode(Hashtable> newprefetchset) { - boolean isFNPresent = false; /* Detects presence of FlatNew node */ - /* This modifies the Flat representation graph */ - for(Enumeration e = newprefetchset.keys();e.hasMoreElements();) { - FlatNode fn = (FlatNode) e.nextElement(); - FlatPrefetchNode fpn = new FlatPrefetchNode(); - if(newprefetchset.get(fn).size() > 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*/ - for(int i = 0; i< fn.numPrev(); i++) { - FlatNode nn = fn.getPrev(i); - if(nn.kind() == FKind.FlatNew) { - isFNPresent = true; - } - } - if(!isFNPresent) { - while(fn.numPrev() > 0) { - FlatNode nn = fn.getPrev(0); - for(int j = 0; j desc; - - public PrefetchPair(){ - base = new TempDescriptor(""); - desc = new ArrayList(); - } - - public PrefetchPair(TempDescriptor t, Descriptor f) { - base = t; - desc = new ArrayList(); - desc.add(f); - } + public TempDescriptor base; + public ArrayList desc; - public PrefetchPair(TempDescriptor t, ArrayList descriptor) { - base = t; - desc = new ArrayList(); - desc.addAll(descriptor); - } + public PrefetchPair() { + base = new TempDescriptor(""); + desc = new ArrayList(); + } - public TempDescriptor getBase() { - return base; - } - - public Descriptor getDescAt(int index) { - return desc.get(index); - } - - public ArrayList getDesc() { - return desc; - } - - public FieldDescriptor getFieldDesc(int index) { - return (FieldDescriptor) desc.get(index); - } - - public IndexDescriptor getIndexDesc(int index) { - return (IndexDescriptor) desc.get(index); - } - - public int hashCode() { - int hashcode = base.toString().hashCode(); - if(desc != null) { - hashcode^=desc.hashCode(); - } - return hashcode; + public PrefetchPair(TempDescriptor t, Descriptor f) { + base = t; + desc = new ArrayList(); + desc.add(f); + } + + public PrefetchPair(TempDescriptor t, ArrayList descriptor) { + base = t; + desc = new ArrayList(); + desc.addAll(descriptor); + } + + public TempDescriptor getBase() { + return base; + } + + public Descriptor getDescAt(int index) { + return desc.get(index); + } + + public ArrayList getDesc() { + return desc; + } + + public FieldDescriptor getFieldDesc(int index) { + return (FieldDescriptor) desc.get(index); + } + + public IndexDescriptor getIndexDesc(int index) { + return (IndexDescriptor) desc.get(index); + } + + public int hashCode() { + int hashcode = base.toString().hashCode(); + if(desc != null) { + hashcode^=desc.hashCode(); } - - public String toString() { - String label= getBase().toString(); - if(getDesc() == null) - return label; - ListIterator it=getDesc().listIterator(); - for(;it.hasNext();) { - Object o = it.next(); - if(o instanceof FieldDescriptor) { - FieldDescriptor fd = (FieldDescriptor) o; - label+="."+ fd.toString(); - } else { - IndexDescriptor id = (IndexDescriptor) o; - label+= id.toString(); - } - } - return label; + return hashcode; + } + + public String toString() { + String label= getBase().toString(); + if(getDesc() == null) + return label; + ListIterator it=getDesc().listIterator(); + for(; it.hasNext();) { + Object o = it.next(); + if(o instanceof FieldDescriptor) { + FieldDescriptor fd = (FieldDescriptor) o; + label+="."+ fd.toString(); + } else { + IndexDescriptor id = (IndexDescriptor) o; + label+= id.toString(); + } } - - public boolean equals(Object o) { - if(o instanceof PrefetchPair) { - PrefetchPair pp = (PrefetchPair) o; - return base == pp.base && desc.equals(pp.desc); - } - return false; + return label; + } + + public boolean equals(Object o) { + if(o instanceof PrefetchPair) { + PrefetchPair pp = (PrefetchPair) o; + return base == pp.base && desc.equals(pp.desc); } - - public Object clone() { - PrefetchPair newpp = new PrefetchPair(); - newpp.base = this.base; - for(int i = 0; i < this.desc.size(); i++) { - Object o = desc.get(i); - if(o instanceof FieldDescriptor) { - newpp.desc.add((FieldDescriptor) o); - } else { - 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 false; + } + + public Object clone() { + PrefetchPair newpp = new PrefetchPair(); + newpp.base = this.base; + for(int i = 0; i < this.desc.size(); i++) { + Object o = desc.get(i); + if(o instanceof FieldDescriptor) { + newpp.desc.add((FieldDescriptor) o); + } else { + ArrayList td = new ArrayList(); + for(int j = 0; j < ((IndexDescriptor)o).tddesc.size(); j++) { + td.add(((IndexDescriptor)o).getTempDescAt(j)); } - return newpp; + IndexDescriptor idesc = new IndexDescriptor(); + idesc.tddesc = td; + idesc.offset = ((IndexDescriptor)o).offset; + newpp.desc.add(idesc); + } } + return newpp; + } - /** This function returns true if a tempdescriptor object is found in the array of descriptors - * for a given prefetch pair else returns false*/ - public boolean containsTemp(TempDescriptor td) { - ArrayList desc = (ArrayList) getDesc(); - 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; - } - } + /** This function returns true if a tempdescriptor object is found in the array of descriptors + * for a given prefetch pair else returns false*/ + public boolean containsTemp(TempDescriptor td) { + ArrayList desc = (ArrayList)getDesc(); + 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; } - return false; + } } + return false; + } - /** This function creates a new Arraylist of Descriptors by replacing old tempdescriptors with new - * tempdescriptors when there is a match */ - public PrefetchPair replaceTemp(TempDescriptor td, TempDescriptor[] newtd) { - PrefetchPair npp=(PrefetchPair)clone(); - ArrayList desc = (ArrayList) npp.getDesc(); - 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 desc = (ArrayList)npp.getDesc(); + 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 flagStates; - private boolean sorted = false; - private boolean clone = false; - - private int transTime; - - /** Class constructor - * @param cd ClassDescriptor - * @param fStates - */ - public ClassNode(ClassDescriptor cd, Vector fStates) { - this.cd=cd; - this.flagStates = fStates; - this.sn = null; - this.uid=ClassNode.nodeID++; - this.transTime = 0; - } - - public int getTransTime() { - return this.transTime; - } - - public void setTransTime(int transTime) { - this.transTime = transTime; - } - - public int getuid() { - return uid; - } - - public ScheduleNode getScheduleNode() { - return this.sn; - } - - public void setScheduleNode(ScheduleNode sn) { - this.sn = sn; - } - - public boolean isSorted() { - return sorted; - } - - public void setSorted(boolean sorted) { - this.sorted = sorted; - } - - public Vector getFlagStates() { - return flagStates; - } - - public boolean isclone() { - return clone; - } - - public String toString() { - return cd.toString()+getTextLabel(); - } +public class ClassNode extends GraphNode implements Cloneable { - /** @return Iterator over the flags in the flagstate. - */ - - public Iterator getFlags() { - return flagStates.iterator(); - } + private int uid; + private static int nodeID=0; - public int numFlags(){ - return flagStates.size(); - } - - /** Accessor method - * @return returns the classdescriptor of the flagstate. - */ - - public ClassDescriptor getClassDescriptor(){ - return cd; - } - - /** Tests for equality of two flagstate objects. - */ - - public boolean equals(Object o) { - if (o instanceof ClassNode) { - ClassNode fs=(ClassNode)o; - if ((fs.getClassDescriptor()!= cd) || - (fs.isSorted() != sorted) || - (fs.clone != this.clone) || - (fs.transTime != this.transTime)) { - return false; - } - return (fs.getFlagStates().equals(flagStates)); - } - return false; - } + private final ClassDescriptor cd; + private ScheduleNode sn; + private Vector flagStates; + private boolean sorted = false; + private boolean clone = false; - public int hashCode() { - return cd.hashCode()^Boolean.toString(sorted).hashCode()^Boolean.toString(clone).hashCode()^ - transTime^flagStates.hashCode(); - } + private int transTime; - public String getLabel() { - return "N_"+uid; - } - - public String getClusterLabel() { - return "cluster_"+uid; - } + /** Class constructor + * @param cd ClassDescriptor + * @param fStates + */ + public ClassNode(ClassDescriptor cd, Vector fStates) { + this.cd=cd; + this.flagStates = fStates; + this.sn = null; + this.uid=ClassNode.nodeID++; + this.transTime = 0; + } - public String getTextLabel() { - String label=null; - label = "Class " + this.cd.getSymbol(); - - if (label==null) - return " "; - return label; - } - - public Object clone() { - ClassNode o = null; - try { - o = (ClassNode)super.clone(); - } catch(CloneNotSupportedException e){ - e.printStackTrace(); - } - o.uid = ClassNode.nodeID++; - o.clone = true; - return o; - } - - public void calExeTime() { - for(int i = 0; i < this.flagStates.size(); i++) { - this.flagStates.elementAt(i).getExeTime(); - } + public int getTransTime() { + return this.transTime; + } + + public void setTransTime(int transTime) { + this.transTime = transTime; + } + + public int getuid() { + return uid; + } + + public ScheduleNode getScheduleNode() { + return this.sn; + } + + public void setScheduleNode(ScheduleNode sn) { + this.sn = sn; + } + + public boolean isSorted() { + return sorted; + } + + public void setSorted(boolean sorted) { + this.sorted = sorted; + } + + public Vector getFlagStates() { + return flagStates; + } + + public boolean isclone() { + return clone; + } + + public String toString() { + return cd.toString()+getTextLabel(); + } + + /** @return Iterator over the flags in the flagstate. + */ + + public Iterator getFlags() { + return flagStates.iterator(); + } + + public int numFlags() { + return flagStates.size(); + } + + /** Accessor method + * @return returns the classdescriptor of the flagstate. + */ + + public ClassDescriptor getClassDescriptor() { + return cd; + } + + /** Tests for equality of two flagstate objects. + */ + + public boolean equals(Object o) { + if (o instanceof ClassNode) { + ClassNode fs=(ClassNode)o; + if ((fs.getClassDescriptor()!= cd) || + (fs.isSorted() != sorted) || + (fs.clone != this.clone) || + (fs.transTime != this.transTime)) { + return false; + } + return (fs.getFlagStates().equals(flagStates)); + } + return false; + } + + public int hashCode() { + return cd.hashCode()^Boolean.toString(sorted).hashCode()^Boolean.toString(clone).hashCode()^ + transTime^flagStates.hashCode(); + } + + public String getLabel() { + return "N_"+uid; + } + + public String getClusterLabel() { + return "cluster_"+uid; + } + + public String getTextLabel() { + String label=null; + label = "Class " + this.cd.getSymbol(); + + if (label==null) + return " "; + return label; + } + + public Object clone() { + ClassNode o = null; + try { + o = (ClassNode) super.clone(); + } catch(CloneNotSupportedException e){ + e.printStackTrace(); + } + o.uid = ClassNode.nodeID++; + o.clone = true; + return o; + } + + public void calExeTime() { + for(int i = 0; i < this.flagStates.size(); i++) { + this.flagStates.elementAt(i).getExeTime(); } + } } diff --git a/Robust/src/Analysis/Scheduling/CombinationUtil.java b/Robust/src/Analysis/Scheduling/CombinationUtil.java index 6c180a70..36c72e6f 100644 --- a/Robust/src/Analysis/Scheduling/CombinationUtil.java +++ b/Robust/src/Analysis/Scheduling/CombinationUtil.java @@ -3,545 +3,545 @@ package Analysis.Scheduling; import java.util.Vector; public class CombinationUtil { - static CombinationUtil cu; - - public CombinationUtil() { - } - - public static CombinationUtil allocateCombinationUtil() { - if(cu == null) { - cu = new CombinationUtil(); - } - return cu; - } - - public static RootsGenerator allocateRootsGenerator(Vector> snodevecs, int rootNum) { - return CombinationUtil.allocateCombinationUtil().new RootsGenerator(snodevecs, rootNum); + static CombinationUtil cu; + + public CombinationUtil() { + } + + public static CombinationUtil allocateCombinationUtil() { + if(cu == null) { + cu = new CombinationUtil(); } - - public static CombineGenerator allocateCombineGenerator(Vector> rootnodes, Vector> node2combine) { - return CombinationUtil.allocateCombinationUtil().new CombineGenerator(rootnodes, node2combine); + return cu; + } + + public static RootsGenerator allocateRootsGenerator(Vector> snodevecs, int rootNum) { + return CombinationUtil.allocateCombinationUtil().new RootsGenerator(snodevecs, rootNum); + } + + public static CombineGenerator allocateCombineGenerator(Vector> rootnodes, Vector> node2combine) { + return CombinationUtil.allocateCombinationUtil().new CombineGenerator(rootnodes, node2combine); + } + + public class RootsGenerator { + Vector> sNodeVecs; + Vector> node2Combine; + Vector> rootNodes; + int rootNum; + + public RootsGenerator(Vector> snodevecs, int rootNum) { + this.sNodeVecs = snodevecs; + this.rootNum = rootNum; + this.node2Combine = null; + this.rootNodes = null; } - - public class RootsGenerator { - Vector> sNodeVecs; - Vector> node2Combine; - Vector> rootNodes; - int rootNum; - - public RootsGenerator(Vector> snodevecs, int rootNum) { - this.sNodeVecs = snodevecs; - this.rootNum = rootNum; - this.node2Combine = null; - this.rootNodes = null; + + 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); + } 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); } - - 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); - } 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); + trial = trial(num2choose, next); + } + if(trial) { + // left 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)); + } + } else { + this.node2Combine.add(null); } - if(trial) { - // left 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)); - } - } 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)); - } - } - 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)); - } - } else { - this.node2Combine.add(null); - } - next++; - } + 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)); } - return trial; + } + next++; } - - private boolean trial(int num2choose, int next) { - 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; - } + 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)); } - return true; + } else { + this.node2Combine.add(null); + } + next++; } + } + return trial; + } - public Vector> getNode2Combine() { - return node2Combine; + private boolean trial(int num2choose, int next) { + 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; + } + } + return true; + } + + public Vector> getNode2Combine() { + return node2Combine; + } + + public Vector> getRootNodes() { + return rootNodes; + } + } + + public class Combine { + public ScheduleNode node; + public int root; + public int index; + + public Combine(ScheduleNode n) { + this.node = n; + this.root = -1; + this.index = -1; + } + } + + public class CombineGenerator { + Vector> rootNodes; + Vector> rootNStates; + Vector> node2Combine; + Vector> combine; + int[] lastchoices; + boolean first4choice; - public Vector> getRootNodes() { - return rootNodes; + public CombineGenerator(Vector> rootnodes, Vector> node2combine) { + this.rootNodes = rootnodes; + this.node2Combine = node2combine; + this.rootNStates = new Vector>(); + 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; + } } + } + this.combine = new Vector>(); + 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))); + } + } + } + this.lastchoices = null; + this.first4choice = false; + } + + public Vector> getCombine() { + return combine; } - - public class Combine { - public ScheduleNode node; - public int root; - public int index; - - public Combine(ScheduleNode n) { - this.node = n; - this.root = -1; - this.index = -1; + + 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(); + } 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(); + } + } + return trial; } - - public class CombineGenerator { - Vector> rootNodes; - Vector> rootNStates; - Vector> node2Combine; - Vector> combine; - int[] lastchoices; - boolean first4choice; - - public CombineGenerator(Vector> rootnodes, Vector> node2combine) { - this.rootNodes = rootnodes; - this.node2Combine = node2combine; - this.rootNStates = new Vector>(); - 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; - } - } + + 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; + } else { + int next = this.node2Combine.size() - 1; + int layer = 0; + suc = innertrial(next, layer); + } + return suc; + } + + 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]--; } - this.combine = new Vector>(); - 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))); - } - } + tmp.root = choice; + tmp.index = 0; + if(!first) { + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; } - this.lastchoices = null; - this.first4choice = false; + } + 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; + } - public Vector> getCombine() { - return combine; + private boolean innertrial(int next, 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); } - - 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(); - } 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(); - } + } + Combine tmp = this.combine.elementAt(next).lastElement(); + // try to move it backward + int root = tmp.root; + int index = tmp.index; + index++; + if(index == this.rootNodes.elementAt(root).size()) { + // 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++; + } + 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; } - return trial; - } - - 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; + t--; + } + if(t < 0) { + // try the bucket in node2combine before + if(next - 1 < 0) { + return false; } else { - int next = this.node2Combine.size() - 1; - int layer = 0; - suc = innertrial(next, layer); + return innertrial(next - 1, ++layer); } - return suc; - } - - 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; - } - } - } + } 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); + } } - return true; - } - - private boolean innertrial(int next, 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); - } + 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]++; } - Combine tmp = this.combine.elementAt(next).lastElement(); - // try to move it backward - int root = tmp.root; - int index = tmp.index; - index++; - if(index == this.rootNodes.elementAt(root).size()) { - // 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++; + if(layer != 0) { + return firstexpand(next+1, this.first4choice); } - if(root == this.rootNodes.size()) { - // no more bucket - // backtrack - root = tmp.root; + 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; - 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); - } + 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); + } } - - private boolean propagateOne(int next, int rooti, int indexi, int ti, Combine tmp) { - int root = rooti; - int index = indexi; - int t = ti; - int rootbk = tmp.root; - int indexbk = tmp.index; + } + } + + private boolean propagateOne(int next, int rooti, int indexi, int ti, Combine tmp) { + int root = rooti; + int index = indexi; + int t = ti; + int rootbk = tmp.root; + int indexbk = tmp.index; + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--; + tmp.root = root; + tmp.index = index; + this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; + t += 2; + 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 = root; - tmp.index = index; + tmp.root = rootbk; + tmp.index = indexbk; this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++; - t += 2; - 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; - } else { - return true; - } + 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; + } } + } } \ No newline at end of file diff --git a/Robust/src/Analysis/Scheduling/CoreSimulator.java b/Robust/src/Analysis/Scheduling/CoreSimulator.java index cc1763e4..29e78b25 100644 --- a/Robust/src/Analysis/Scheduling/CoreSimulator.java +++ b/Robust/src/Analysis/Scheduling/CoreSimulator.java @@ -8,181 +8,181 @@ import Analysis.TaskStateAnalysis.FlagState; import IR.TaskDescriptor; public class CoreSimulator { - Vector tasks; - RuntimeSchedule rSchedule; - TaskSimulator rtask; - Hashtable> targetCSimulator; - Hashtable> allyCSimulator; - Hashtable targetFState; - int coreNum; - int activeTime; - - public CoreSimulator(RuntimeSchedule schedule, int coreNum) { - super(); - reset(); - this.rSchedule = schedule; - this.coreNum = coreNum; - } - - public CoreSimulator(int coreNum) { - super(); - reset(); - this.coreNum = coreNum; - } - - public void reset() { - this.activeTime = 0; - this.tasks = null; - this.targetCSimulator = null; - this.targetFState = null; - this.rSchedule = null; - this.rtask = null; - } - - public void deployTasks(Vector tasks) { - if(tasks == null) { - return; - } - - if(this.tasks == null) { - this.tasks = new Vector(); - } else { - this.tasks.clear(); - } - - for(int i = 0; i < tasks.size(); i++) { - TaskDescriptor td = tasks.elementAt(i); - this.tasks.add(new TaskSimulator(td, this)); - } - } - - public Queue getTargetCores(FlagState fstate) { - if(targetCSimulator == null) { - return null; - } - return targetCSimulator.get(fstate); - } + Vector tasks; + RuntimeSchedule rSchedule; + TaskSimulator rtask; + Hashtable> targetCSimulator; + Hashtable> allyCSimulator; + Hashtable targetFState; + int coreNum; + int activeTime; - public void setTargetCSimulator(Hashtable> targetCSimulator) { - this.targetCSimulator = targetCSimulator; + public CoreSimulator(RuntimeSchedule schedule, int coreNum) { + super(); + reset(); + this.rSchedule = schedule; + this.coreNum = coreNum; + } + + public CoreSimulator(int coreNum) { + super(); + reset(); + this.coreNum = coreNum; + } + + public void reset() { + this.activeTime = 0; + this.tasks = null; + this.targetCSimulator = null; + this.targetFState = null; + this.rSchedule = null; + this.rtask = null; + } + + public void deployTasks(Vector tasks) { + if(tasks == null) { + return; } - - public Vector getAllyCores(FlagState fstate) { - if(allyCSimulator == null) { - return null; - } - return allyCSimulator.get(fstate); + + if(this.tasks == null) { + this.tasks = new Vector(); + } else { + this.tasks.clear(); } - public void setAllyCSimulator(Hashtable> allyCSimulator) { - this.allyCSimulator = allyCSimulator; + for(int i = 0; i < tasks.size(); i++) { + TaskDescriptor td = tasks.elementAt(i); + this.tasks.add(new TaskSimulator(td, this)); } - - public FlagState getTargetFState(FlagState fstate) { - if(targetFState == null) { - return fstate; - } - return targetFState.get(fstate); + } + + public Queue getTargetCores(FlagState fstate) { + if(targetCSimulator == null) { + return null; } + return targetCSimulator.get(fstate); + } - public void setTargetFState(Hashtable targetFState) { - this.targetFState = targetFState; + public void setTargetCSimulator(Hashtable> targetCSimulator) { + this.targetCSimulator = targetCSimulator; + } + + public Vector getAllyCores(FlagState fstate) { + if(allyCSimulator == null) { + return null; } + return allyCSimulator.get(fstate); + } + + public void setAllyCSimulator(Hashtable> allyCSimulator) { + this.allyCSimulator = allyCSimulator; + } - public int getActiveTime() { - return activeTime; + public FlagState getTargetFState(FlagState fstate) { + if(targetFState == null) { + return fstate; } + return targetFState.get(fstate); + } - public int getCoreNum() { - return coreNum; + public void setTargetFState(Hashtable targetFState) { + this.targetFState = targetFState; + } + + public int getActiveTime() { + return activeTime; + } + + public int getCoreNum() { + return coreNum; + } + + public Vector getTasks() { + return tasks; + } + + public RuntimeSchedule getRSchedule() { + return rSchedule; + } + + public void setRSchedule(RuntimeSchedule schedule) { + rSchedule = schedule; + } + + public TaskSimulator getRtask() { + return rtask; + } + + public void addObject(ObjectSimulator newObj) { + if(this.tasks == null) { + return; } - - public Vector getTasks() { - return tasks; + for(int i = 0; i < this.tasks.size(); i++) { + this.tasks.elementAt(i).enquePara(newObj, null, 0, true); } + } - public RuntimeSchedule getRSchedule() { - return rSchedule; + public void addObject(ObjectSimulator newObj, FlagState fs, int version) { + if(this.tasks == null) { + return; } - - public void setRSchedule(RuntimeSchedule schedule) { - rSchedule = schedule; + for(int i = 0; i < this.tasks.size(); i++) { + this.tasks.elementAt(i).enquePara(newObj, fs, version, false); } + } - public TaskSimulator getRtask() { - return rtask; - } + public Vector finishTask() { + assert(this.rtask != null); - public void addObject(ObjectSimulator newObj) { - if(this.tasks == null) { - return; + Vector transObjs = null; + 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(); } - for(int i = 0; i < this.tasks.size(); i++) { - this.tasks.elementAt(i).enquePara(newObj, null, 0, true); + if(!transObjs.contains(obj)) { + transObjs.add(obj); } - } - - public void addObject(ObjectSimulator newObj, FlagState fs, int version) { - if(this.tasks == null) { - return; - } - for(int i = 0; i < this.tasks.size(); i++) { - this.tasks.elementAt(i).enquePara(newObj, fs, version, false); + 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; } - } - - public Vector finishTask() { - assert(this.rtask != null); - - Vector transObjs = null; - 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; - } - } - for(int j = 0; j < this.tasks.size(); j++) { - this.tasks.elementAt(j).refreshPara(obj, remove); - } - } - this.activeTime += this.rtask.getCurrentRun().getFinishTime(); - this.rtask.finish(); - this.rtask = null; - return transObjs; - } - - public void updateTask(int time) { - this.activeTime += time; - this.rtask.updateFinishTime(time); - } + } + for(int j = 0; j < this.tasks.size(); j++) { + this.tasks.elementAt(j).refreshPara(obj, remove); + } + } + this.activeTime += this.rtask.getCurrentRun().getFinishTime(); + this.rtask.finish(); + this.rtask = null; + return transObjs; + } + + public void updateTask(int time) { + this.activeTime += time; + this.rtask.updateFinishTime(time); + } + + public TaskSimulator process() { + TaskSimulator next = rSchedule.schedule(tasks); + this.rtask = next; + return next; + } - public TaskSimulator process() { - TaskSimulator next = rSchedule.schedule(tasks); - this.rtask = next; - return next; - } - } \ No newline at end of file diff --git a/Robust/src/Analysis/Scheduling/FIFORSchedule.java b/Robust/src/Analysis/Scheduling/FIFORSchedule.java index c64cc84d..6a247404 100644 --- a/Robust/src/Analysis/Scheduling/FIFORSchedule.java +++ b/Robust/src/Analysis/Scheduling/FIFORSchedule.java @@ -4,46 +4,46 @@ import java.util.Queue; import java.util.Vector; public class FIFORSchedule extends RuntimeSchedule { - static FIFORSchedule rschedule; - - public static FIFORSchedule getFIFORSchedule() { - if(rschedule == null) { - rschedule = new FIFORSchedule(); - } - return rschedule; - } - - public FIFORSchedule() { - super("FIFO Algorithm"); + static FIFORSchedule rschedule; + + public static FIFORSchedule getFIFORSchedule() { + if(rschedule == null) { + rschedule = new FIFORSchedule(); } + return rschedule; + } - public TaskSimulator schedule(Vector tasks) { - if(tasks == null) { - return null; - } - TaskSimulator next = null; - int i = 0; - for(; i < tasks.size(); i++) { - next = tasks.elementAt(i); - int paraNum = next.getTd().numParameters(); - Vector> pqueues = next.getParaQueues(); - if((pqueues == null) || (pqueues.size() < paraNum)) { - continue; - } - int j = 0; - for(; j < pqueues.size(); j++) { - Queue objs = pqueues.elementAt(j); - if((objs == null) || (objs.size() == 0)) { - break; - } - } - if(j == pqueues.size()) { - return next; - } - } - if(i == tasks.size()) { - return null; + public FIFORSchedule() { + super("FIFO Algorithm"); + } + + public TaskSimulator schedule(Vector tasks) { + if(tasks == null) { + return null; + } + TaskSimulator next = null; + int i = 0; + for(; i < tasks.size(); i++) { + next = tasks.elementAt(i); + int paraNum = next.getTd().numParameters(); + Vector> pqueues = next.getParaQueues(); + if((pqueues == null) || (pqueues.size() < paraNum)) { + continue; + } + int j = 0; + for(; j < pqueues.size(); j++) { + Queue objs = pqueues.elementAt(j); + if((objs == null) || (objs.size() == 0)) { + break; } + } + if(j == pqueues.size()) { return next; + } + } + if(i == tasks.size()) { + return null; } + return next; + } } \ No newline at end of file diff --git a/Robust/src/Analysis/Scheduling/ObjectInfo.java b/Robust/src/Analysis/Scheduling/ObjectInfo.java index d4a4a2ca..7ffe09a6 100644 --- a/Robust/src/Analysis/Scheduling/ObjectInfo.java +++ b/Robust/src/Analysis/Scheduling/ObjectInfo.java @@ -3,30 +3,30 @@ package Analysis.Scheduling; import Analysis.TaskStateAnalysis.FlagState; public class ObjectInfo { - public ObjectSimulator obj; - public FlagState fs; - public int version; + public ObjectSimulator obj; + public FlagState fs; + public int version; - public ObjectInfo(ObjectSimulator obj) { - this.obj = obj; - this.fs = obj.getCurrentFS(); - this.version = obj.getVersion(); - } + public ObjectInfo(ObjectSimulator obj) { + this.obj = obj; + this.fs = obj.getCurrentFS(); + this.version = obj.getVersion(); + } - public boolean equals(Object o) { - if (o instanceof ObjectInfo) { - ObjectInfo oi=(ObjectInfo)o; - if ((oi.obj != obj) || - (oi.fs != fs) || - (oi.version != version)) { - return false; - } - return true; - } + public boolean equals(Object o) { + if (o instanceof ObjectInfo) { + ObjectInfo oi=(ObjectInfo)o; + if ((oi.obj != obj) || + (oi.fs != fs) || + (oi.version != version)) { return false; + } + return true; } + return false; + } - public int hashCode() { - return obj.hashCode()^fs.hashCode()^version; - } + public int hashCode() { + return obj.hashCode()^fs.hashCode()^version; + } } \ No newline at end of file diff --git a/Robust/src/Analysis/Scheduling/ObjectSimulator.java b/Robust/src/Analysis/Scheduling/ObjectSimulator.java index 4c92e296..3eebda44 100644 --- a/Robust/src/Analysis/Scheduling/ObjectSimulator.java +++ b/Robust/src/Analysis/Scheduling/ObjectSimulator.java @@ -5,70 +5,70 @@ import Analysis.TaskStateAnalysis.FlagState; import IR.ClassDescriptor; public class ObjectSimulator { - ClassDescriptor cd; - FlagState currentFS; - boolean changed; - boolean shared; - boolean hold; - int version; - - public ObjectSimulator(ClassDescriptor cd, FlagState currentFS) { - super(); - this.cd = cd; - this.currentFS = currentFS; - this.changed = true; - this.shared = false; - this.hold = false; - this.version = 0; - } - - public void applyEdge(FEdge fedge) { - if(!currentFS.equals((FlagState)fedge.getTarget())) { - this.changed = true; - currentFS = (FlagState)fedge.getTarget(); - } else { - this.changed = false; - } - } + ClassDescriptor cd; + FlagState currentFS; + boolean changed; + boolean shared; + boolean hold; + int version; - public ClassDescriptor getCd() { - return cd; - } + public ObjectSimulator(ClassDescriptor cd, FlagState currentFS) { + super(); + this.cd = cd; + this.currentFS = currentFS; + this.changed = true; + this.shared = false; + this.hold = false; + this.version = 0; + } - public FlagState getCurrentFS() { - return currentFS; + public void applyEdge(FEdge fedge) { + if(!currentFS.equals((FlagState)fedge.getTarget())) { + this.changed = true; + currentFS = (FlagState)fedge.getTarget(); + } else { + this.changed = false; } + } - public boolean isChanged() { - return changed; - } + public ClassDescriptor getCd() { + return cd; + } - public void setCurrentFS(FlagState currentFS) { - changed = true; - this.currentFS = currentFS; - } + public FlagState getCurrentFS() { + return currentFS; + } - public boolean isHold() { - return hold; - } + public boolean isChanged() { + return changed; + } - public void setHold(boolean hold) { - this.hold = hold; - } + public void setCurrentFS(FlagState currentFS) { + changed = true; + this.currentFS = currentFS; + } - public boolean isShared() { - return shared; - } + public boolean isHold() { + return hold; + } - public void setShared(boolean shared) { - this.shared = shared; - } + public void setHold(boolean hold) { + this.hold = hold; + } - public int getVersion() { - return version; - } + public boolean isShared() { + return shared; + } - public void increaseVersion() { - this.version++; - } + public void setShared(boolean shared) { + this.shared = shared; + } + + public int getVersion() { + return version; + } + + public void increaseVersion() { + this.version++; + } } \ No newline at end of file diff --git a/Robust/src/Analysis/Scheduling/RuntimeSchedule.java b/Robust/src/Analysis/Scheduling/RuntimeSchedule.java index 8f38551e..47a8a735 100644 --- a/Robust/src/Analysis/Scheduling/RuntimeSchedule.java +++ b/Robust/src/Analysis/Scheduling/RuntimeSchedule.java @@ -4,16 +4,16 @@ import java.util.Vector; import java.lang.String; public abstract class RuntimeSchedule { - String rsAlgorithm; - - public RuntimeSchedule(String rsAlgorithm) { - super(); - this.rsAlgorithm = rsAlgorithm; - } + String rsAlgorithm; - public abstract TaskSimulator schedule(Vector tasks); - - public String algorithm() { - return rsAlgorithm; - } + public RuntimeSchedule(String rsAlgorithm) { + super(); + this.rsAlgorithm = rsAlgorithm; + } + + public abstract TaskSimulator schedule(Vector tasks); + + public String algorithm() { + return rsAlgorithm; + } } \ No newline at end of file diff --git a/Robust/src/Analysis/Scheduling/Schedule.java b/Robust/src/Analysis/Scheduling/Schedule.java index a04c629b..303513c7 100644 --- a/Robust/src/Analysis/Scheduling/Schedule.java +++ b/Robust/src/Analysis/Scheduling/Schedule.java @@ -11,131 +11,131 @@ import IR.TaskDescriptor; /** This class holds flag transition diagram(s) can be put on one core. */ public class Schedule { - private int coreNum; - private Vector tasks; - private Hashtable> targetCores; - private Hashtable targetFState; // only affected by transimit edges - private Hashtable> allyCores; - private Hashtable> td2fs; - - public Schedule(int coreNum) { - super(); - this.coreNum = coreNum; - this.tasks = null; - this.targetCores = null; - this.targetFState = null; - this.allyCores = null; - this.td2fs = null; - } - - public int getCoreNum() { - return coreNum; - } - - public Hashtable> getTargetCoreTable() { - return targetCores; - } - - public Queue getTargetCores(FlagState fstate) { - if(targetCores == null) { - return null; - } - return targetCores.get(fstate); - } - - public Hashtable getTargetFStateTable() { - return targetFState; - } - - public FlagState getTargetFState(FlagState fstate) { - if(targetFState == null) { - return null; - } - return targetFState.get(fstate); - } - - public Hashtable> getAllyCoreTable() { - return this.allyCores; - } - - public Vector getAllyCores(FlagState fstate) { - if(this.allyCores == null) { - return null; - } - return this.allyCores.get(fstate); - } - - public Hashtable> getTd2FsTable() { - return this.td2fs; - } - - public Vector getFStates4TD(TaskDescriptor td) { - if(this.td2fs == null) { - return null; - } - return this.td2fs.get(td); - } - - public void addTargetCore(FlagState fstate, Integer targetCore) { - if(this.targetCores == null) { - this.targetCores = new Hashtable>(); - } - if(!this.targetCores.containsKey(fstate)) { - this.targetCores.put(fstate, new LinkedList()); - } - this.targetCores.get(fstate).add(targetCore); // there may have some duplicate items, - // which reflects probabilities. - } - - public void addTargetCore(FlagState fstate, Integer targetCore, FlagState tfstate) { - if(this.targetCores == null) { - this.targetCores = new Hashtable>(); - } - if(!this.targetCores.containsKey(fstate)) { - this.targetCores.put(fstate, new LinkedList()); - } - this.targetCores.get(fstate).add(targetCore); - if(this.targetFState == null) { - this.targetFState = new Hashtable(); - } - this.targetFState.put(fstate, tfstate); - } - - public void addAllyCore(FlagState fstate, Integer targetCore) { - if(this.allyCores == null) { - this.allyCores = new Hashtable>(); - } - if(!this.allyCores.containsKey(fstate)) { - this.allyCores.put(fstate, new Vector()); - } - if((this.coreNum != targetCore.intValue()) && (!this.allyCores.get(fstate).contains(targetCore))) { - this.allyCores.get(fstate).add(targetCore); // there may have some duplicate items, - // which reflects probabilities. - } - } - - public void addFState4TD(TaskDescriptor td, FlagState fstate) { - if(this.td2fs == null) { - this.td2fs = new Hashtable>(); - } - if(!this.td2fs.containsKey(td)) { - this.td2fs.put(td, new Vector()); - } - if(!this.td2fs.get(td).contains(fstate)) { - this.td2fs.get(td).add(fstate); - } - } - - public Vector getTasks() { - return tasks; - } - - public void addTask(TaskDescriptor task) { - if(this.tasks == null) { - this.tasks = new Vector(); - } - if(!this.tasks.contains(task)) { - this.tasks.add(task); - } - } + private int coreNum; + private Vector tasks; + private Hashtable> targetCores; + private Hashtable targetFState; // only affected by transimit edges + private Hashtable> allyCores; + private Hashtable> td2fs; + + public Schedule(int coreNum) { + super(); + this.coreNum = coreNum; + this.tasks = null; + this.targetCores = null; + this.targetFState = null; + this.allyCores = null; + this.td2fs = null; + } + + public int getCoreNum() { + return coreNum; + } + + public Hashtable> getTargetCoreTable() { + return targetCores; + } + + public Queue getTargetCores(FlagState fstate) { + if(targetCores == null) { + return null; + } + return targetCores.get(fstate); + } + + public Hashtable getTargetFStateTable() { + return targetFState; + } + + public FlagState getTargetFState(FlagState fstate) { + if(targetFState == null) { + return null; + } + return targetFState.get(fstate); + } + + public Hashtable> getAllyCoreTable() { + return this.allyCores; + } + + public Vector getAllyCores(FlagState fstate) { + if(this.allyCores == null) { + return null; + } + return this.allyCores.get(fstate); + } + + public Hashtable> getTd2FsTable() { + return this.td2fs; + } + + public Vector getFStates4TD(TaskDescriptor td) { + if(this.td2fs == null) { + return null; + } + return this.td2fs.get(td); + } + + public void addTargetCore(FlagState fstate, Integer targetCore) { + if(this.targetCores == null) { + this.targetCores = new Hashtable>(); + } + if(!this.targetCores.containsKey(fstate)) { + this.targetCores.put(fstate, new LinkedList()); + } + this.targetCores.get(fstate).add(targetCore); // there may have some duplicate items, + // which reflects probabilities. + } + + public void addTargetCore(FlagState fstate, Integer targetCore, FlagState tfstate) { + if(this.targetCores == null) { + this.targetCores = new Hashtable>(); + } + if(!this.targetCores.containsKey(fstate)) { + this.targetCores.put(fstate, new LinkedList()); + } + this.targetCores.get(fstate).add(targetCore); + if(this.targetFState == null) { + this.targetFState = new Hashtable(); + } + this.targetFState.put(fstate, tfstate); + } + + public void addAllyCore(FlagState fstate, Integer targetCore) { + if(this.allyCores == null) { + this.allyCores = new Hashtable>(); + } + if(!this.allyCores.containsKey(fstate)) { + this.allyCores.put(fstate, new Vector()); + } + if((this.coreNum != targetCore.intValue()) && (!this.allyCores.get(fstate).contains(targetCore))) { + this.allyCores.get(fstate).add(targetCore); // there may have some duplicate items, + // which reflects probabilities. + } + } + + public void addFState4TD(TaskDescriptor td, FlagState fstate) { + if(this.td2fs == null) { + this.td2fs = new Hashtable>(); + } + if(!this.td2fs.containsKey(td)) { + this.td2fs.put(td, new Vector()); + } + if(!this.td2fs.get(td).contains(fstate)) { + this.td2fs.get(td).add(fstate); + } + } + + public Vector getTasks() { + return tasks; + } + + public void addTask(TaskDescriptor task) { + if(this.tasks == null) { + this.tasks = new Vector(); + } + if(!this.tasks.contains(task)) { + this.tasks.add(task); + } + } } \ No newline at end of file diff --git a/Robust/src/Analysis/Scheduling/ScheduleAnalysis.java b/Robust/src/Analysis/Scheduling/ScheduleAnalysis.java index f65c08fe..5673edaf 100644 --- a/Robust/src/Analysis/Scheduling/ScheduleAnalysis.java +++ b/Robust/src/Analysis/Scheduling/ScheduleAnalysis.java @@ -8,1029 +8,1036 @@ import java.util.*; /** This class holds flag transition diagram(s) can be put on one core. */ public class ScheduleAnalysis { - - State state; - TaskAnalysis taskanalysis; - Vector scheduleNodes; - Vector classNodes; - Vector scheduleEdges; - Hashtable cd2ClassNode; - boolean sorted = false; - - int transThreshold; - - int coreNum; - Vector> scheduleGraphs; - Vector> schedulings; - - public ScheduleAnalysis(State state, TaskAnalysis taskanalysis) { - this.state = state; - this.taskanalysis = taskanalysis; - this.scheduleNodes = new Vector(); - this.classNodes = new Vector(); - this.scheduleEdges = new Vector(); - this.cd2ClassNode = new Hashtable(); - this.transThreshold = 45; - this.coreNum = -1; - this.scheduleGraphs = null; - this.schedulings = null; - } - - public void setTransThreshold(int tt) { - this.transThreshold = tt; - } - - public int getCoreNum() { - return coreNum; + + State state; + TaskAnalysis taskanalysis; + Vector scheduleNodes; + Vector classNodes; + Vector scheduleEdges; + Hashtable cd2ClassNode; + boolean sorted = false; + + int transThreshold; + + int coreNum; + Vector> scheduleGraphs; + Vector> schedulings; + + public ScheduleAnalysis(State state, TaskAnalysis taskanalysis) { + this.state = state; + this.taskanalysis = taskanalysis; + this.scheduleNodes = new Vector(); + this.classNodes = new Vector(); + this.scheduleEdges = new Vector(); + this.cd2ClassNode = new Hashtable(); + this.transThreshold = 45; + this.coreNum = -1; + this.scheduleGraphs = null; + this.schedulings = null; + } + + public void setTransThreshold(int tt) { + this.transThreshold = tt; + } + + public int getCoreNum() { + return coreNum; + } + + public void setCoreNum(int coreNum) { + this.coreNum = coreNum; + } + + public Iterator getScheduleGraphs() { + return this.scheduleGraphs.iterator(); + } + + public Iterator getSchedulingsIter() { + return this.schedulings.iterator(); + } + + public Vector> getSchedulings() { + return this.schedulings; + } + + // for test + public Vector getSEdges4Test() { + return scheduleEdges; + } + + public void preSchedule() { + Hashtable cdToCNodes = new Hashtable(); + // Build the combined flag transition diagram + // First, for each class create a ClassNode + for(Iterator it_classes = state.getClassSymbolTable().getDescriptorsIterator(); it_classes.hasNext(); ) { + ClassDescriptor cd = (ClassDescriptor) it_classes.next(); + Set fStates = taskanalysis.getFlagStates(cd); + + //Sort flagState nodes inside this ClassNode + Vector sFStates = FlagState.DFS.topology(fStates, null); + + 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(); + + // for test + if(cd.getSymbol().equals("C")) { + cNode.setTransTime(45); + } + } + fStates = null; + sFStates = null; } - public void setCoreNum(int coreNum) { - this.coreNum = coreNum; + ScheduleNode startupNode = null; + // For each ClassNode create a ScheduleNode containing it + int i = 0; + for(i = 0; i < classNodes.size(); i++) { + ClassNode cn = classNodes.elementAt(i); + ScheduleNode sn = new ScheduleNode(cn, 0); + if(cn.getClassDescriptor().getSymbol().equals(TypeUtil.StartupClass)) { + startupNode = sn; + } + cn.setScheduleNode(sn); + scheduleNodes.add(sn); + try { + sn.calExeTime(); + } catch (Exception e) { + e.printStackTrace(); + } } - - public Iterator getScheduleGraphs() { - return this.scheduleGraphs.iterator(); + + // Create 'new' edges between the ScheduleNodes. + Vector toBreakDown = new Vector(); + for(i = 0; i < classNodes.size(); i++) { + ClassNode cNode = classNodes.elementAt(i); + 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; + } } - - public Iterator getSchedulingsIter() { - return this.schedulings.iterator(); + cdToCNodes = null; + + // Break down the 'cycle's + try { + for(i = 0; i < toBreakDown.size(); i++ ) { + cloneSNodeList(toBreakDown.elementAt(i), false); + } + toBreakDown = null; + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); } - - public Vector> getSchedulings() { - return this.schedulings; + + // Remove fake 'new' edges + 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()); + } } - - // for test - public Vector getSEdges4Test() { - return scheduleEdges; + + // Do topology sort of the ClassNodes and ScheduleEdges. + Vector ssev = new Vector(); + Vector tempSNodes = ClassNode.DFS.topology(scheduleNodes, ssev); + scheduleNodes.removeAllElements(); + scheduleNodes = tempSNodes; + tempSNodes = null; + scheduleEdges.removeAllElements(); + scheduleEdges = ssev; + ssev = null; + sorted = true; + + // Set the cid of these ScheduleNode + Queue toVisit = new LinkedList(); + toVisit.add(startupNode); + 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()); + } + } } - - public void preSchedule() { - Hashtable cdToCNodes = new Hashtable(); - // Build the combined flag transition diagram - // First, for each class create a ClassNode - for(Iterator it_classes = state.getClassSymbolTable().getDescriptorsIterator(); it_classes.hasNext(); ) { - ClassDescriptor cd = (ClassDescriptor) it_classes.next(); - Set fStates = taskanalysis.getFlagStates(cd); - - //Sort flagState nodes inside this ClassNode - Vector sFStates = FlagState.DFS.topology(fStates, null); - - 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(); - - // for test - if(cd.getSymbol().equals("C")) { - cNode.setTransTime(45); - } - } - fStates = null; - sFStates = null; - } - - ScheduleNode startupNode = null; - // For each ClassNode create a ScheduleNode containing it - int i = 0; - for(i = 0; i < classNodes.size(); i++) { - ClassNode cn = classNodes.elementAt(i); - ScheduleNode sn = new ScheduleNode(cn, 0); - if(cn.getClassDescriptor().getSymbol().equals(TypeUtil.StartupClass)) { - startupNode = sn; + + SchedulingUtil.printScheduleGraph("scheduling_ori.dot", this.scheduleNodes); + } + + public void scheduleAnalysis() { + // First iteration + int i = 0; + //Access the ScheduleEdges in reverse topology order + Hashtable> fe2ses = new Hashtable>(); + Hashtable> sn2fes = new Hashtable>(); + ScheduleNode preSNode = null; + 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()) { + // back edge + try { + int repeat = (int)Math.ceil(se.getNewRate() * se.getProbability() / 100); + int rate = 0; + if(repeat > 1){ + for(int j = 1; j< repeat; j++ ) { + cloneSNodeList(se, true); + } + se.setNewRate(1); + se.setProbability(100); } - cn.setScheduleNode(sn); - scheduleNodes.add(sn); try { - sn.calExeTime(); + rate = (int)Math.ceil(se.getListExeTime()/ calInExeTime(se.getSourceFState())); } catch (Exception e) { - e.printStackTrace(); + e.printStackTrace(); + } + for(int j = rate - 1; j > 0; j--) { + for(int k = repeat; k > 0; k--) { + cloneSNodeList(se, true); + } } - } - - // Create 'new' edges between the ScheduleNodes. - Vector toBreakDown = new Vector(); - for(i = 0; i < classNodes.size(); i++) { - ClassNode cNode = classNodes.elementAt(i); - 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; + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); + } + } else { + // 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); + ScheduleEdge tempse = ses.elementAt(0); + int temptime = tempse.getListExeTime(); + // find out the ScheduleEdge with least exeTime + for(int k = 1; k < ses.size(); k++) { + int ttemp = ses.elementAt(k).getListExeTime(); + if(ttemp < temptime) { + tempse = ses.elementAt(k); + temptime = ttemp; } - } - rootnodes = null; + } + // handle the tempse + handleScheduleEdge(tempse, true); + ses.removeElement(tempse); + // handle other ScheduleEdges + for(int k = 0; k < ses.size(); k++) { + handleScheduleEdge(ses.elementAt(k), false); + } + ses = null; + fe2ses.remove(tempfe); + } + fes = null; + } } - } - cdToCNodes = null; - - // Break down the 'cycle's - try { - for(i = 0; i < toBreakDown.size(); i++ ) { - cloneSNodeList(toBreakDown.elementAt(i), false); - } - toBreakDown = null; - } catch (Exception e) { - e.printStackTrace(); - System.exit(-1); - } - - // Remove fake 'new' edges - 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()); + preSNode = (ScheduleNode)se.getSource(); + } + + // if fe is the last task inside this ClassNode, delay the expanding and merging until we find all such 'new' edges + // associated with a last task inside this ClassNode + if(!fe.getTarget().edges().hasNext()) { + if(fe2ses.get(fe) == null) { + fe2ses.put(fe, new Vector()); } - } - - // Do topology sort of the ClassNodes and ScheduleEdges. - Vector ssev = new Vector(); - Vector tempSNodes = ClassNode.DFS.topology(scheduleNodes, ssev); - scheduleNodes.removeAllElements(); - scheduleNodes = tempSNodes; - tempSNodes = null; - scheduleEdges.removeAllElements(); - scheduleEdges = ssev; - ssev = null; - sorted = true; - - // Set the cid of these ScheduleNode - Queue toVisit = new LinkedList(); - toVisit.add(startupNode); - 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()); - } - } - } - - SchedulingUtil.printScheduleGraph("scheduling_ori.dot", this.scheduleNodes); - } - - public void scheduleAnalysis() { - // First iteration - int i = 0; - //Access the ScheduleEdges in reverse topology order - Hashtable> fe2ses = new Hashtable>(); - Hashtable> sn2fes = new Hashtable>(); - ScheduleNode preSNode = null; - 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()) { - // back edge - try { - int repeat = (int)Math.ceil(se.getNewRate() * se.getProbability() / 100); - int rate = 0; - if(repeat > 1){ - for(int j = 1; j< repeat; j++ ) { - cloneSNodeList(se, true); - } - se.setNewRate(1); - se.setProbability(100); - } - try { - rate = (int)Math.ceil(se.getListExeTime()/ calInExeTime(se.getSourceFState())); - } catch (Exception e) { - e.printStackTrace(); - } - for(int j = rate - 1; j > 0; j--) { - for(int k = repeat; k > 0; k--) { - cloneSNodeList(se, true); - } - } - } catch (Exception e) { - e.printStackTrace(); - System.exit(-1); - } - } else { - // 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); - ScheduleEdge tempse = ses.elementAt(0); - int temptime = tempse.getListExeTime(); - // find out the ScheduleEdge with least exeTime - for(int k = 1; k < ses.size(); k++) { - int ttemp = ses.elementAt(k).getListExeTime(); - if(ttemp < temptime) { - tempse = ses.elementAt(k); - temptime = ttemp; - } - } - // handle the tempse - handleScheduleEdge(tempse, true); - ses.removeElement(tempse); - // handle other ScheduleEdges - for(int k = 0; k < ses.size(); k++) { - handleScheduleEdge(ses.elementAt(k), false); - } - ses = null; - fe2ses.remove(tempfe); - } - fes = null; - } - } - preSNode = (ScheduleNode)se.getSource(); - } - - // if fe is the last task inside this ClassNode, delay the expanding and merging until we find all such 'new' edges - // associated with a last task inside this ClassNode - if(!fe.getTarget().edges().hasNext()) { - 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); - } - } else { - // As this is not a last task, first handle available ScheduleEdges previously put into fe2ses - if((same) && (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); - ScheduleEdge tempse = ses.elementAt(0); - int temptime = tempse.getListExeTime(); - // find out the ScheduleEdge with least exeTime - for(int k = 1; k < ses.size(); k++) { - int ttemp = ses.elementAt(k).getListExeTime(); - if(ttemp < temptime) { - tempse = ses.elementAt(k); - temptime = ttemp; - } - } - // handle the tempse - handleScheduleEdge(tempse, true); - ses.removeElement(tempse); - // handle other ScheduleEdges - for(int k = 0; k < ses.size(); k++) { - handleScheduleEdge(ses.elementAt(k), false); - } - ses = null; - fe2ses.remove(tempfe); - } - fes = null; - } - - if((!(se.getTransTime() < this.transThreshold)) && (se.getSourceCNode().getTransTime() < se.getTransTime())) { - split = true; - splitSNode(se, true); - } else { - // handle this ScheduleEdge - handleScheduleEdge(se, true); - } - } - } + if(sn2fes.get((ScheduleNode)se.getSource()) == null) { + sn2fes.put((ScheduleNode)se.getSource(), new Vector()); } - } - 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); - ScheduleEdge tempse = ses.elementAt(0); - int temptime = tempse.getListExeTime(); - // find out the ScheduleEdge with least exeTime - for(int k = 1; k < ses.size(); k++) { - int ttemp = ses.elementAt(k).getListExeTime(); - if(ttemp < temptime) { - tempse = ses.elementAt(k); - temptime = ttemp; - } - } - // handle the tempse - handleScheduleEdge(tempse, true); - ses.removeElement(tempse); - // handle other ScheduleEdges - for(int k = 0; k < ses.size(); k++) { - handleScheduleEdge(ses.elementAt(k), false); - } - ses = null; - } - keys = null; - fe2ses.clear(); - sn2fes.clear(); - } - fe2ses = null; - sn2fes = null; - - SchedulingUtil.printScheduleGraph("scheduling_extend.dot", this.scheduleNodes); - } - - private void handleScheduleEdge(ScheduleEdge se, boolean merge) { - try { - 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(!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); + } + } else { + // As this is not a last task, first handle available ScheduleEdges previously put into fe2ses + if((same) && (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); + ScheduleEdge tempse = ses.elementAt(0); + int temptime = tempse.getListExeTime(); + // find out the ScheduleEdge with least exeTime + for(int k = 1; k < ses.size(); k++) { + int ttemp = ses.elementAt(k).getListExeTime(); + if(ttemp < temptime) { + tempse = ses.elementAt(k); + temptime = ttemp; + } } - 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); + // handle the tempse + handleScheduleEdge(tempse, true); + ses.removeElement(tempse); + // handle other ScheduleEdges + for(int k = 0; k < ses.size(); k++) { + handleScheduleEdge(ses.elementAt(k), false); } + ses = null; + fe2ses.remove(tempfe); + } + fes = null; + } + + if((!(se.getTransTime() < this.transThreshold)) && (se.getSourceCNode().getTransTime() < se.getTransTime())) { + split = true; + splitSNode(se, true); } 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); + // handle this ScheduleEdge + handleScheduleEdge(se, true); } - } catch (Exception e) { - e.printStackTrace(); - System.exit(-1); + } } + } } - - private void cloneSNodeList(ScheduleEdge sEdge, boolean copyIE) throws Exception { - Hashtable cn2cn = new Hashtable(); // hashtable from classnode in orignal se's targe to cloned one - ScheduleNode csNode = (ScheduleNode)((ScheduleNode)sEdge.getTarget()).clone(cn2cn, 0); - scheduleNodes.add(csNode); - - // Clone all the external in ScheduleEdges - int i; - 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); - } - inedges = null; - } else { - sEdge.getTarget().removeInedge(sEdge); - sEdge.setTarget(csNode); - csNode.getInedgeVector().add(sEdge); - sEdge.setTargetCNode(cn2cn.get(sEdge.getTargetCNode())); - sEdge.setIsclone(true); + 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); + ScheduleEdge tempse = ses.elementAt(0); + int temptime = tempse.getListExeTime(); + // find out the ScheduleEdge with least exeTime + for(int k = 1; k < ses.size(); k++) { + int ttemp = ses.elementAt(k).getListExeTime(); + if(ttemp < temptime) { + tempse = ses.elementAt(k); + temptime = ttemp; + } } - - Queue toClone = new LinkedList(); // all nodes to be cloned - Queue clone = new LinkedList(); //clone nodes - Queue qcn2cn = new LinkedList(); // queue of the mappings of classnodes inside cloned ScheduleNode - Vector origins = new Vector(); // queue of source ScheduleNode cloned - Hashtable sn2sn = new Hashtable(); // mapping from cloned ScheduleNode to clone ScheduleNode - clone.add(csNode); - toClone.add((ScheduleNode)sEdge.getTarget()); - origins.addElement((ScheduleNode)sEdge.getTarget()); - sn2sn.put((ScheduleNode)sEdge.getTarget(), csNode); - qcn2cn.add(cn2cn); - while(!toClone.isEmpty()) { - Hashtable tocn2cn = new Hashtable(); - csNode = clone.poll(); - ScheduleNode osNode = toClone.poll(); - cn2cn = qcn2cn.poll(); - // 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); - } - tocn2cn = null; - edges = null; - } - - toClone = null; - clone = null; - qcn2cn = null; - cn2cn = null; - } - - private int calInExeTime(FlagState fs) throws Exception { - int exeTime = 0; - ClassDescriptor cd = fs.getClassDescriptor(); - ClassNode cNode = cd2ClassNode.get(cd); - exeTime = cNode.getFlagStates().elementAt(0).getExeTime() - fs.getExeTime(); - while(true) { - Vector inedges = cNode.getInedgeVector(); - // 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!"); - } - if(inedges.size() > 0) { - ScheduleEdge sEdge = (ScheduleEdge)inedges.elementAt(0); - cNode = (ClassNode)sEdge.getSource(); - exeTime += cNode.getFlagStates().elementAt(0).getExeTime(); - }else { - break; - } - inedges = null; - } - exeTime = cNode.getScheduleNode().getExeTime() - exeTime; - return exeTime; - } - - private ScheduleNode splitSNode(ScheduleEdge se, boolean copy) { - assert(ScheduleEdge.NEWEDGE == se.getType()); - - FEdge fe = se.getFEdge(); - FlagState fs = (FlagState)fe.getTarget(); - FlagState nfs = (FlagState)fs.clone(); - fs.getEdgeVector().removeAllElements(); - nfs.getInedgeVector().removeAllElements(); - ClassNode sCNode = se.getSourceCNode(); - - // split the subtree whose root is nfs from the whole flag transition tree - Vector sfss = sCNode.getFlagStates(); - Vector fStates = new Vector(); - Queue toiterate = new LinkedList(); - toiterate.add(nfs); - fStates.add(nfs); - while(!toiterate.isEmpty()){ - 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); - } - } + // handle the tempse + handleScheduleEdge(tempse, true); + ses.removeElement(tempse); + // handle other ScheduleEdges + for(int k = 0; k < ses.size(); k++) { + handleScheduleEdge(ses.elementAt(k), false); } - sfss = null; - Vector sFStates = FlagState.DFS.topology(fStates, null); - fStates = null; - // create a ClassNode and ScheduleNode for this subtree - ClassNode cNode = new ClassNode(sCNode.getClassDescriptor(), sFStates); - ScheduleNode sNode = new ScheduleNode(cNode, 0); - cNode.setScheduleNode(sNode); - cNode.setSorted(true); - cNode.setTransTime(sCNode.getTransTime()); - classNodes.add(cNode); - scheduleNodes.add(sNode); + ses = null; + } + keys = null; + fe2ses.clear(); + sn2fes.clear(); + } + fe2ses = null; + sn2fes = null; + + SchedulingUtil.printScheduleGraph("scheduling_extend.dot", this.scheduleNodes); + } + + private void handleScheduleEdge(ScheduleEdge se, boolean merge) { + try { + int rate = 0; + int repeat = (int)Math.ceil(se.getNewRate() * se.getProbability() / 100); + if(merge) { try { - sNode.calExeTime(); + 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(); + e.printStackTrace(); } - // flush the exeTime of fs and its ancestors - fs.setExeTime(0); - toiterate.add(fs); - while(!toiterate.isEmpty()) { - FlagState tfs = toiterate.poll(); - int ttime = tfs.getExeTime(); - Iterator it_inedges = tfs.inedges(); - while(it_inedges.hasNext()) { - FEdge fEdge = (FEdge)it_inedges.next(); - FlagState temp = (FlagState)fEdge.getSource(); - int time = fEdge.getExeTime() + ttime; - if(temp.getExeTime() > time) { - temp.setExeTime(time); - toiterate.add(temp); - } + 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); + } } - toiterate = null; - - // create a 'trans' ScheudleEdge between this new ScheduleNode and se's source ScheduleNode - ScheduleEdge sEdge = new ScheduleEdge(sNode, "transmit", fs, ScheduleEdge.TRANSEDGE, 0);//new ScheduleEdge(sNode, "transmit", cNode.getClassDescriptor(), false, 0); - sEdge.setFEdge(fe); - sEdge.setSourceCNode(sCNode); - sEdge.setTargetCNode(cNode); - sEdge.setTargetFState(nfs); - // TODO - // Add calculation codes for calculating transmit time of an object - sEdge.setTransTime(cNode.getTransTime()); - se.getSource().addEdge(sEdge); - scheduleEdges.add(sEdge); - // remove the ClassNodes and internal ScheduleEdges out of this subtree to the new ScheduleNode - ScheduleNode oldSNode = (ScheduleNode)se.getSource(); - Iterator it_isEdges = oldSNode.getScheduleEdgesIterator(); - Vector toremove = new Vector(); - Vector rCNodes = new Vector(); - rCNodes.addElement(sCNode); - if(it_isEdges != null){ - while(it_isEdges.hasNext()) { - ScheduleEdge tse = (ScheduleEdge)it_isEdges.next(); - if(rCNodes.contains(tse.getSourceCNode())) { - if(sCNode == tse.getSourceCNode()) { - if ((tse.getSourceFState() != 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); - } - } + // 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); } - oldSNode.getScheduleEdges().removeAll(toremove); - toremove.clear(); - // redirect ScheudleEdges out of this subtree to the new ScheduleNode - Iterator it_sEdges = se.getSource().edges(); - while(it_sEdges.hasNext()) { - ScheduleEdge tse = (ScheduleEdge)it_sEdges.next(); - if((tse != se) && (tse != sEdge) && (tse.getSourceCNode() == sCNode)) { - if((tse.getSourceFState() != fs) && (sFStates.contains(tse.getSourceFState()))) { - tse.setSource(sNode); - tse.setSourceCNode(cNode); - sNode.getEdgeVector().addElement(tse); - toremove.add(tse); - } - } + } else { + // clone the whole ScheduleNode lists starting with se's target + for(int j = 1; j < repeat; j++ ) { + cloneSNodeList(se, true); } - se.getSource().getEdgeVector().removeAll(toremove); - toremove = null; - sFStates = null; - - try { - if(!copy) { - //merge se into its source ScheduleNode - ((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.setNewRate(1); + se.setProbability(100); + } + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); + } + } + + private void cloneSNodeList(ScheduleEdge sEdge, boolean copyIE) throws Exception { + Hashtable cn2cn = new Hashtable(); // hashtable from classnode in orignal se's targe to cloned one + ScheduleNode csNode = (ScheduleNode)((ScheduleNode)sEdge.getTarget()).clone(cn2cn, 0); + scheduleNodes.add(csNode); + + // Clone all the external in ScheduleEdges + int i; + 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); + } + inedges = null; + } else { + sEdge.getTarget().removeInedge(sEdge); + sEdge.setTarget(csNode); + csNode.getInedgeVector().add(sEdge); + sEdge.setTargetCNode(cn2cn.get(sEdge.getTargetCNode())); + sEdge.setIsclone(true); + } + + Queue toClone = new LinkedList(); // all nodes to be cloned + Queue clone = new LinkedList(); //clone nodes + Queue qcn2cn = new LinkedList(); // queue of the mappings of classnodes inside cloned ScheduleNode + Vector origins = new Vector(); // queue of source ScheduleNode cloned + Hashtable sn2sn = new Hashtable(); // mapping from cloned ScheduleNode to clone ScheduleNode + clone.add(csNode); + toClone.add((ScheduleNode)sEdge.getTarget()); + origins.addElement((ScheduleNode)sEdge.getTarget()); + sn2sn.put((ScheduleNode)sEdge.getTarget(), csNode); + qcn2cn.add(cn2cn); + while(!toClone.isEmpty()) { + Hashtable tocn2cn = new Hashtable(); + csNode = clone.poll(); + ScheduleNode osNode = toClone.poll(); + cn2cn = qcn2cn.poll(); + // 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); + } + tocn2cn = null; + edges = null; + } + + toClone = null; + clone = null; + qcn2cn = null; + cn2cn = null; + } + + private int calInExeTime(FlagState fs) throws Exception { + int exeTime = 0; + ClassDescriptor cd = fs.getClassDescriptor(); + ClassNode cNode = cd2ClassNode.get(cd); + exeTime = cNode.getFlagStates().elementAt(0).getExeTime() - fs.getExeTime(); + while(true) { + Vector inedges = cNode.getInedgeVector(); + // 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!"); + } + if(inedges.size() > 0) { + ScheduleEdge sEdge = (ScheduleEdge)inedges.elementAt(0); + cNode = (ClassNode)sEdge.getSource(); + exeTime += cNode.getFlagStates().elementAt(0).getExeTime(); + } else { + break; + } + inedges = null; + } + exeTime = cNode.getScheduleNode().getExeTime() - exeTime; + return exeTime; + } + + private ScheduleNode splitSNode(ScheduleEdge se, boolean copy) { + assert(ScheduleEdge.NEWEDGE == se.getType()); + + FEdge fe = se.getFEdge(); + FlagState fs = (FlagState)fe.getTarget(); + FlagState nfs = (FlagState)fs.clone(); + fs.getEdgeVector().removeAllElements(); + nfs.getInedgeVector().removeAllElements(); + ClassNode sCNode = se.getSourceCNode(); + + // split the subtree whose root is nfs from the whole flag transition tree + Vector sfss = sCNode.getFlagStates(); + Vector fStates = new Vector(); + Queue toiterate = new LinkedList(); + toiterate.add(nfs); + fStates.add(nfs); + while(!toiterate.isEmpty()){ + 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); + } + } + } + sfss = null; + Vector sFStates = FlagState.DFS.topology(fStates, null); + fStates = null; + // create a ClassNode and ScheduleNode for this subtree + ClassNode cNode = new ClassNode(sCNode.getClassDescriptor(), sFStates); + ScheduleNode sNode = new ScheduleNode(cNode, 0); + cNode.setScheduleNode(sNode); + cNode.setSorted(true); + cNode.setTransTime(sCNode.getTransTime()); + classNodes.add(cNode); + scheduleNodes.add(sNode); + try { + sNode.calExeTime(); + } catch (Exception e) { + e.printStackTrace(); + } + // flush the exeTime of fs and its ancestors + fs.setExeTime(0); + toiterate.add(fs); + while(!toiterate.isEmpty()) { + FlagState tfs = toiterate.poll(); + int ttime = tfs.getExeTime(); + Iterator it_inedges = tfs.inedges(); + while(it_inedges.hasNext()) { + FEdge fEdge = (FEdge)it_inedges.next(); + FlagState temp = (FlagState)fEdge.getSource(); + int time = fEdge.getExeTime() + ttime; + if(temp.getExeTime() > time) { + temp.setExeTime(time); + toiterate.add(temp); + } + } + } + toiterate = null; + + // create a 'trans' ScheudleEdge between this new ScheduleNode and se's source ScheduleNode + ScheduleEdge sEdge = new ScheduleEdge(sNode, "transmit", fs, ScheduleEdge.TRANSEDGE, 0); //new ScheduleEdge(sNode, "transmit", cNode.getClassDescriptor(), false, 0); + sEdge.setFEdge(fe); + sEdge.setSourceCNode(sCNode); + sEdge.setTargetCNode(cNode); + sEdge.setTargetFState(nfs); + // TODO + // Add calculation codes for calculating transmit time of an object + sEdge.setTransTime(cNode.getTransTime()); + se.getSource().addEdge(sEdge); + scheduleEdges.add(sEdge); + // remove the ClassNodes and internal ScheduleEdges out of this subtree to the new ScheduleNode + ScheduleNode oldSNode = (ScheduleNode)se.getSource(); + Iterator it_isEdges = oldSNode.getScheduleEdgesIterator(); + Vector toremove = new Vector(); + Vector rCNodes = new Vector(); + rCNodes.addElement(sCNode); + if(it_isEdges != null){ + while(it_isEdges.hasNext()) { + ScheduleEdge tse = (ScheduleEdge)it_isEdges.next(); + if(rCNodes.contains(tse.getSourceCNode())) { + if(sCNode == tse.getSourceCNode()) { + if ((tse.getSourceFState() != fs) && (sFStates.contains(tse.getSourceFState()))) { + tse.setSource(cNode); + tse.setSourceCNode(cNode); } else { - handleScheduleEdge(se, true); + continue; } - } catch (Exception e) { - e.printStackTrace(); - System.exit(-1); + } + sNode.getScheduleEdges().addElement(tse); + sNode.getClassNodes().addElement(tse.getTargetCNode()); + rCNodes.addElement(tse.getTargetCNode()); + oldSNode.getClassNodes().removeElement(tse.getTargetCNode()); + toremove.addElement(tse); } - - return sNode; + } } - - public void schedule() throws Exception { - if(this.coreNum == -1) { - throw new Exception("Error: un-initialized coreNum when doing scheduling."); + oldSNode.getScheduleEdges().removeAll(toremove); + toremove.clear(); + // redirect ScheudleEdges out of this subtree to the new ScheduleNode + Iterator it_sEdges = se.getSource().edges(); + while(it_sEdges.hasNext()) { + ScheduleEdge tse = (ScheduleEdge)it_sEdges.next(); + if((tse != se) && (tse != sEdge) && (tse.getSourceCNode() == sCNode)) { + if((tse.getSourceFState() != fs) && (sFStates.contains(tse.getSourceFState()))) { + tse.setSource(sNode); + tse.setSourceCNode(cNode); + sNode.getEdgeVector().addElement(tse); + toremove.add(tse); } - - if(this.scheduleGraphs == null) { - this.scheduleGraphs = new Vector>(); + } + } + se.getSource().getEdgeVector().removeAll(toremove); + toremove = null; + sFStates = null; + + try { + if(!copy) { + //merge se into its source ScheduleNode + ((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); } - - int reduceNum = this.scheduleNodes.size() - this.coreNum; - - // Combine some ScheduleNode if necessary - // May generate multiple graphs suggesting candidate schedulings - if(!(reduceNum > 0)) { - // Enough cores, no need to combine any ScheduleNode - this.scheduleGraphs.addElement(this.scheduleNodes); - int gid = 1; - String path = "scheduling_" + gid + ".dot"; - SchedulingUtil.printScheduleGraph(path, this.scheduleNodes); - } else { - // Go through all the Scheudle Nodes, organize them in order of their cid - Vector> sNodeVecs = new Vector>(); - for(int i = 0; i < this.scheduleNodes.size(); i++) { - ScheduleNode tmpn = this.scheduleNodes.elementAt(i); - int index = tmpn.getCid(); - while(sNodeVecs.size() <= index) { - sNodeVecs.add(null); - } - if(sNodeVecs.elementAt(index) == null) { - sNodeVecs.setElementAt(new Vector(), index); - } - sNodeVecs.elementAt(index).add(tmpn); - } - - CombinationUtil.RootsGenerator rGen = CombinationUtil.allocateRootsGenerator(sNodeVecs, this.coreNum); - - int gid = 1; - while(rGen.nextGen()) { - // first get the chosen rootNodes - Vector> rootNodes = rGen.getRootNodes(); - Vector> nodes2combine = rGen.getNode2Combine(); - - CombinationUtil.CombineGenerator cGen = CombinationUtil.allocateCombineGenerator(rootNodes, nodes2combine); - while (cGen.nextGen()) { - Vector> combine = cGen.getCombine(); - Vector sNodes = generateScheduling(rootNodes, combine, gid++); - this.scheduleGraphs.add(sNodes); - combine = null; - sNodes = null; - } - rootNodes = null; - nodes2combine = null; - } - sNodeVecs = null; + } else { + handleScheduleEdge(se, true); + } + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); + } + + return sNode; + } + + public void schedule() throws Exception { + if(this.coreNum == -1) { + throw new Exception("Error: un-initialized coreNum when doing scheduling."); + } + + if(this.scheduleGraphs == null) { + this.scheduleGraphs = new Vector>(); + } + + int reduceNum = this.scheduleNodes.size() - this.coreNum; + + // Combine some ScheduleNode if necessary + // May generate multiple graphs suggesting candidate schedulings + if(!(reduceNum > 0)) { + // Enough cores, no need to combine any ScheduleNode + this.scheduleGraphs.addElement(this.scheduleNodes); + int gid = 1; + String path = "scheduling_" + gid + ".dot"; + SchedulingUtil.printScheduleGraph(path, this.scheduleNodes); + } else { + // Go through all the Scheudle Nodes, organize them in order of their cid + Vector> sNodeVecs = new Vector>(); + for(int i = 0; i < this.scheduleNodes.size(); i++) { + ScheduleNode tmpn = this.scheduleNodes.elementAt(i); + int index = tmpn.getCid(); + while(sNodeVecs.size() <= index) { + sNodeVecs.add(null); } - - // Generate schedulings according to result schedule graph - if(this.schedulings == null) { - this.schedulings = new Vector>(); + if(sNodeVecs.elementAt(index) == null) { + sNodeVecs.setElementAt(new Vector(), index); } - - Vector multiparamtds = new Vector(); - Iterator it_tasks = state.getTaskSymbolTable().getDescriptorsIterator(); - while(it_tasks.hasNext()) { - TaskDescriptor td = (TaskDescriptor)it_tasks.next(); - if(td.numParameters() > 1) { - multiparamtds.addElement(td); + sNodeVecs.elementAt(index).add(tmpn); + } + + CombinationUtil.RootsGenerator rGen = CombinationUtil.allocateRootsGenerator(sNodeVecs, this.coreNum); + + int gid = 1; + while(rGen.nextGen()) { + // first get the chosen rootNodes + Vector> rootNodes = rGen.getRootNodes(); + Vector> nodes2combine = rGen.getNode2Combine(); + + CombinationUtil.CombineGenerator cGen = CombinationUtil.allocateCombineGenerator(rootNodes, nodes2combine); + while (cGen.nextGen()) { + Vector> combine = cGen.getCombine(); + Vector sNodes = generateScheduling(rootNodes, combine, gid++); + this.scheduleGraphs.add(sNodes); + combine = null; + sNodes = null; + } + rootNodes = null; + nodes2combine = null; + } + sNodeVecs = null; + } + + // Generate schedulings according to result schedule graph + if(this.schedulings == null) { + this.schedulings = new Vector>(); + } + + Vector multiparamtds = new Vector(); + Iterator it_tasks = state.getTaskSymbolTable().getDescriptorsIterator(); + while(it_tasks.hasNext()) { + TaskDescriptor td = (TaskDescriptor)it_tasks.next(); + if(td.numParameters() > 1) { + multiparamtds.addElement(td); + } + } + + for(int i = 0; i < this.scheduleGraphs.size(); i++) { + Hashtable> td2cores = new Hashtable>(); // multiparam tasks reside on which cores + Vector scheduleGraph = this.scheduleGraphs.elementAt(i); + Vector scheduling = new Vector(scheduleGraph.size()); + // for each ScheduleNode create a schedule node representing a core + Hashtable sn2coreNum = new Hashtable(); + int j = 0; + for(j = 0; j < scheduleGraph.size(); j++) { + sn2coreNum.put(scheduleGraph.elementAt(j), j); + } + int startupcore = 0; + boolean setstartupcore = false; + Schedule startup = null; + for(j = 0; j < scheduleGraph.size(); j++) { + Schedule tmpSchedule = new Schedule(j); + ScheduleNode sn = scheduleGraph.elementAt(j); + + Vector cNodes = sn.getClassNodes(); + for(int k = 0; k < cNodes.size(); k++) { + Iterator it_flags = cNodes.elementAt(k).getFlags(); + while(it_flags.hasNext()) { + FlagState fs = (FlagState)it_flags.next(); + Iterator it_edges = fs.edges(); + while(it_edges.hasNext()) { + TaskDescriptor td = ((FEdge)it_edges.next()).getTask(); + tmpSchedule.addTask(td); + if(!td2cores.containsKey(td)) { + td2cores.put(td, new Vector()); + } + Vector tmpcores = td2cores.get(td); + if(!tmpcores.contains(tmpSchedule)) { + tmpcores.add(tmpSchedule); + } + // if the FlagState can be fed to some multi-param tasks, + // need to record corresponding ally cores later + if(td.numParameters() > 1) { + tmpSchedule.addFState4TD(td, fs); + } + if(td.getParamType(0).getClassDesc().getSymbol().equals(TypeUtil.StartupClass)) { + assert(!setstartupcore); + startupcore = j; + startup = tmpSchedule; + setstartupcore = true; + } } + } } - - for(int i = 0; i < this.scheduleGraphs.size(); i++) { - Hashtable> td2cores = new Hashtable>(); // multiparam tasks reside on which cores - Vector scheduleGraph = this.scheduleGraphs.elementAt(i); - Vector scheduling = new Vector(scheduleGraph.size()); - // for each ScheduleNode create a schedule node representing a core - Hashtable sn2coreNum = new Hashtable(); - int j = 0; - for(j = 0; j < scheduleGraph.size(); j++) { - sn2coreNum.put(scheduleGraph.elementAt(j), j); + + // For each of the ScheduleEdge out of this ScheduleNode, add the 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: { + for(int k = 0; k < se.getNewRate(); k++) { + tmpSchedule.addTargetCore(se.getFstate(), targetcore); } - int startupcore = 0; - boolean setstartupcore = false; - Schedule startup = null; - for(j = 0; j < scheduleGraph.size(); j++) { - Schedule tmpSchedule = new Schedule(j); - ScheduleNode sn = scheduleGraph.elementAt(j); - - Vector cNodes = sn.getClassNodes(); - for(int k = 0; k < cNodes.size(); k++) { - Iterator it_flags = cNodes.elementAt(k).getFlags(); - while(it_flags.hasNext()) { - FlagState fs = (FlagState)it_flags.next(); - Iterator it_edges = fs.edges(); - while(it_edges.hasNext()) { - TaskDescriptor td = ((FEdge)it_edges.next()).getTask(); - tmpSchedule.addTask(td); - if(!td2cores.containsKey(td)) { - td2cores.put(td, new Vector()); - } - Vector tmpcores = td2cores.get(td); - if(!tmpcores.contains(tmpSchedule)) { - tmpcores.add(tmpSchedule); - } - // if the FlagState can be fed to some multi-param tasks, - // need to record corresponding ally cores later - if(td.numParameters() > 1) { - tmpSchedule.addFState4TD(td, fs); - } - if(td.getParamType(0).getClassDesc().getSymbol().equals(TypeUtil.StartupClass)) { - assert(!setstartupcore); - startupcore = j; - startup = tmpSchedule; - setstartupcore = true; - } - } - } - } + break; + } - // For each of the ScheduleEdge out of this ScheduleNode, add the 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: { - for(int k = 0; k < se.getNewRate(); k++) { - tmpSchedule.addTargetCore(se.getFstate(), 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) { - if(tmpSchedule.getTasks().contains(td)) { - tmpSchedule.addFState4TD(td, fs); - } - } - } - 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) { + if(tmpSchedule.getTasks().contains(td)) { + tmpSchedule.addFState4TD(td, fs); } - it_edges = sn.getScheduleEdgesIterator(); + } + } + break; + } + } + } + it_edges = sn.getScheduleEdgesIterator(); + while(it_edges.hasNext()) { + ScheduleEdge se = (ScheduleEdge)it_edges.next(); + switch(se.getType()) { + case ScheduleEdge.NEWEDGE: { + 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()); + break; + } + } + } + scheduling.add(tmpSchedule); + } + + int number = this.coreNum; + if(scheduling.size() < number) { + number = scheduling.size(); + } + + // set up all the associate ally cores + if(multiparamtds.size() > 0) { + for(j = 0; j < multiparamtds.size(); ++j) { + TaskDescriptor td = multiparamtds.elementAt(j); + Vector fes = (Vector) this.taskanalysis.getFEdgesFromTD(td); + Vector cores = td2cores.get(td); + for(int k = 0; k < cores.size(); ++k) { + Schedule tmpSchedule = cores.elementAt(k); + + 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().contains(tmpfs))) { + // add up all possible cores' info + Iterator it_edges = tmpfs.edges(); while(it_edges.hasNext()) { - ScheduleEdge se = (ScheduleEdge)it_edges.next(); - switch(se.getType()) { - case ScheduleEdge.NEWEDGE: { - for(int k = 0; k < se.getNewRate(); k++) { - tmpSchedule.addTargetCore(se.getFstate(), j); + TaskDescriptor tmptd = ((FEdge)it_edges.next()).getTask(); + if(!tmptds.contains(tmptd)) { + tmptds.add(tmptd); + Vector tmpcores = td2cores.get(tmptd); + for(int m = 0; m < tmpcores.size(); ++m) { + if(m != tmpSchedule.getCoreNum()) { + // if the FlagState can be fed to some multi-param tasks, + // need to record corresponding ally cores later + if(tmptd.numParameters() > 1) { + tmpSchedule.addAllyCore(tmpfs, tmpcores.elementAt(m).getCoreNum()); + } else { + tmpSchedule.addTargetCore(tmpfs, tmpcores.elementAt(m).getCoreNum()); } - break; - } - case ScheduleEdge.TRANSEDGE: { - // 'transmit' edge - tmpSchedule.addTargetCore(se.getFstate(), j, se.getTargetFState()); - break; - } + } } + } } - scheduling.add(tmpSchedule); - } - - int number = this.coreNum; - if(scheduling.size() < number) { - number = scheduling.size(); + } } - - // set up all the associate ally cores - if(multiparamtds.size() > 0) { - for(j = 0; j < multiparamtds.size(); ++j) { - TaskDescriptor td = multiparamtds.elementAt(j); - Vector fes = (Vector)this.taskanalysis.getFEdgesFromTD(td); - Vector cores = td2cores.get(td); - for(int k = 0; k < cores.size(); ++k) { - Schedule tmpSchedule = cores.elementAt(k); - - 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().contains(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); - Vector tmpcores = td2cores.get(tmptd); - for(int m = 0; m < tmpcores.size(); ++m) { - if(m != tmpSchedule.getCoreNum()) { - // if the FlagState can be fed to some multi-param tasks, - // need to record corresponding ally cores later - if(tmptd.numParameters() > 1) { - tmpSchedule.addAllyCore(tmpfs, tmpcores.elementAt(m).getCoreNum()); - } else { - tmpSchedule.addTargetCore(tmpfs, tmpcores.elementAt(m).getCoreNum()); - } - } - } - } - } - } - } - - if(cores.size() > 1) { - Vector tmpfss = tmpSchedule.getFStates4TD(td); - for(int h = 0; h < tmpfss.size(); ++h) { - for(int l = 0; l < cores.size(); ++l) { - if(l != k) { - tmpSchedule.addAllyCore(tmpfss.elementAt(h), cores.elementAt(l).getCoreNum()); - } - } - } - } - } + + if(cores.size() > 1) { + Vector tmpfss = tmpSchedule.getFStates4TD(td); + for(int h = 0; h < tmpfss.size(); ++h) { + for(int l = 0; l < cores.size(); ++l) { + if(l != k) { + tmpSchedule.addAllyCore(tmpfss.elementAt(h), cores.elementAt(l).getCoreNum()); + } } + } } - - this.schedulings.add(scheduling); + } } + } + + this.schedulings.add(scheduling); } - - public Vector generateScheduling(Vector> rootnodes, Vector> combine, int gid) { - Vector result = new Vector(); - - // clone the ScheduleNodes - Hashtable> sn2hash = new Hashtable>(); - Hashtable sn2sn = new Hashtable(); - for(int i = 0; i < this.scheduleNodes.size(); i++) { - Hashtable cn2cn = new Hashtable(); - ScheduleNode tocopy = this.scheduleNodes.elementAt(i); - ScheduleNode temp = (ScheduleNode)tocopy.clone(cn2cn, gid); - result.add(i, temp); - sn2hash.put(temp, cn2cn); - sn2sn.put(tocopy, temp); - cn2cn = null; - } - // clone the ScheduleEdges - for(int i = 0; i < this.scheduleEdges.size(); i++) { - ScheduleEdge sse = this.scheduleEdges.elementAt(i); - ScheduleNode csource = sn2sn.get(sse.getSource()); - ScheduleNode ctarget = sn2sn.get(sse.getTarget()); - Hashtable sourcecn2cn = sn2hash.get(csource); - Hashtable targetcn2cn = sn2hash.get(ctarget); - 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; - } - case ScheduleEdge.TRANSEDGE: { - 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())); - se.setTargetCNode(targetcn2cn.get(sse.getTargetCNode())); - se.setFEdge(sse.getFEdge()); - se.setTargetFState(sse.getTargetFState()); - se.setIsclone(true); - csource.addEdge(se); - sourcecn2cn = null; - targetcn2cn = null; - } - - // 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); - } - } else { - root.mergeSNode(tocombine); - } - } catch(Exception e) { - e.printStackTrace(); - System.exit(-1); - } - result.removeElement(tocombine); - } + } + + public Vector generateScheduling(Vector> rootnodes, Vector> combine, int gid) { + Vector result = new Vector(); + + // clone the ScheduleNodes + Hashtable> sn2hash = new Hashtable>(); + Hashtable sn2sn = new Hashtable(); + for(int i = 0; i < this.scheduleNodes.size(); i++) { + Hashtable cn2cn = new Hashtable(); + ScheduleNode tocopy = this.scheduleNodes.elementAt(i); + ScheduleNode temp = (ScheduleNode)tocopy.clone(cn2cn, gid); + result.add(i, temp); + sn2hash.put(temp, cn2cn); + sn2sn.put(tocopy, temp); + cn2cn = null; + } + // clone the ScheduleEdges + for(int i = 0; i < this.scheduleEdges.size(); i++) { + ScheduleEdge sse = this.scheduleEdges.elementAt(i); + ScheduleNode csource = sn2sn.get(sse.getSource()); + ScheduleNode ctarget = sn2sn.get(sse.getTarget()); + Hashtable sourcecn2cn = sn2hash.get(csource); + Hashtable targetcn2cn = sn2hash.get(ctarget); + 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; + } + + case ScheduleEdge.TRANSEDGE: { + 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())); + se.setTargetCNode(targetcn2cn.get(sse.getTargetCNode())); + se.setFEdge(sse.getFEdge()); + se.setTargetFState(sse.getTargetFState()); + se.setIsclone(true); + csource.addEdge(se); + sourcecn2cn = null; + targetcn2cn = null; + } + + // 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); + } + } else { + root.mergeSNode(tocombine); } + } catch(Exception e) { + e.printStackTrace(); + System.exit(-1); + } + result.removeElement(tocombine); } - - sn2hash = null; - sn2sn = null; - - String path = "scheduling_" + gid + ".dot"; - SchedulingUtil.printScheduleGraph(path, result); - - return result; + } } + + sn2hash = null; + sn2sn = null; + + String path = "scheduling_" + gid + ".dot"; + SchedulingUtil.printScheduleGraph(path, result); + + return result; + } } diff --git a/Robust/src/Analysis/Scheduling/ScheduleEdge.java b/Robust/src/Analysis/Scheduling/ScheduleEdge.java index 1c4a52b3..5496ff96 100644 --- a/Robust/src/Analysis/Scheduling/ScheduleEdge.java +++ b/Robust/src/Analysis/Scheduling/ScheduleEdge.java @@ -9,215 +9,215 @@ import Util.GraphNode; /* Edge *****************/ public class ScheduleEdge extends Edge { - public final static int NEWEDGE = 0; - public final static int TRANSEDGE = 1; + public final static int NEWEDGE = 0; + public final static int TRANSEDGE = 1; - protected int uid; - protected int gid; - protected static int nodeID=0; + protected int uid; + protected int gid; + protected static int nodeID=0; - protected String label; - protected final FlagState fstate; - protected int type; // 0--new edge: indicate creating new objects + protected String label; + protected final FlagState fstate; + protected int type; // 0--new edge: indicate creating new objects // 1--transmit edge: indicate transimitting an existing object - - protected FlagState targetFState; - - private ClassNode sourceCNode; - private ClassNode targetCNode; - - private int probability; - private int transTime; - private int listExeTime; - - private FEdge fedge; - private int newRate; - - private boolean isclone; - - /** Class Constructor - * - */ - public ScheduleEdge(ScheduleNode target, String label, FlagState fstate, int type, int gid) { - super(target); - this.uid = ScheduleEdge.nodeID++; - this.gid = gid; - this.fedge = null; - this.targetFState = null; - this.sourceCNode = null; - this.targetCNode = null; - this.label = label; - this.fstate = fstate; - this.newRate = -1; - this.probability = 100; - this.transTime = -1; - this.listExeTime = -1; - this.isclone = false; - this.type = type; - } - - public boolean isclone() { - return isclone; - } - - public void setIsclone(boolean isclone) { - this.isclone = isclone; - } - - public void setTarget(GraphNode sn) { - this.target = sn; - } - - public int getType() { - return type; - } - - public String getLabel() { - String completeLabel = label; - if(ScheduleEdge.NEWEDGE == this.type) { - completeLabel += ":" + Integer.toString(this.newRate); - } - completeLabel += ":(" + Integer.toString(this.probability) + "%)" + ":[" + Integer.toString(this.transTime) + "]"; - return completeLabel; - } - - public FlagState getFstate() { - return fstate; - } - - public FEdge getFEdge() { - return this.fedge; - } - - public void setFEdge(FEdge fEdge) { - this.fedge = fEdge; - } - - public FlagState getSourceFState() { - if(this.fedge == null) { - return null; - } - return (FlagState)this.fedge.getTarget(); - } - - public void setTargetFState(FlagState targetFState) { - this.targetFState = targetFState; - } - - public FlagState getTargetFState() { - return this.targetFState; - } - - public int getProbability() { - return this.probability; - } - - public int getNewRate() { - return this.newRate; - } - - public ClassNode getSourceCNode() { - return this.sourceCNode; - } - - public void setSourceCNode(ClassNode sourceCNode) { - this.sourceCNode = sourceCNode; - } - - public ClassNode getTargetCNode() { - return this.targetCNode; - } - - public void setTargetCNode(ClassNode targetCNode) { - this.targetCNode = targetCNode; - this.transTime = targetCNode.getTransTime(); - } - - public boolean equals(Object o) { - if (o instanceof ScheduleEdge) { - ScheduleEdge e=(ScheduleEdge)o; - if(e.gid == this.gid) { - if(e.uid != this.uid) { - return false; - } - } - if ((e.label.equals(label))&& - (e.target.equals(target))&& - (e.source.equals(source)) && - (e.fstate.equals(fstate)) && - (e.sourceCNode.equals(sourceCNode)) && - (e.targetCNode.equals(targetCNode)) && - (e.newRate == newRate) && - (e.probability == probability) && - (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.fedge != null) { - return e.fedge.equals(fedge); - } else if(this.fedge == null) { - return true; - } - } - return false; - } - - public int hashCode(){ - int hashcode = gid^uid^label.hashCode()^target.hashCode()^source.hashCode()^fstate.hashCode()^ - sourceCNode.hashCode()^targetCNode.hashCode()^newRate^probability^ - type^transTime^listExeTime; - if(targetFState != null) { - hashcode ^= targetFState.hashCode(); - } - if(fedge != null) { - hashcode ^= fedge.hashCode(); - } - return hashcode; - } - - public void setProbability(int prob) { - this.probability = prob; - } - - public void setNewRate(int nr) { - this.newRate = nr; - } - - public int getTransTime() { - return this.transTime; - } - - public void setTransTime(int transTime) { - this.transTime = transTime; - } - - public int getListExeTime() { - if(listExeTime == -1) { - // calculate the lisExeTime - listExeTime = ((ScheduleNode)this.getTarget()).getExeTime() + this.getTransTime() * this.getNewRate(); - Iterator it_edges = this.getTarget().edges(); - int temp = 0; - if(it_edges.hasNext()) { - temp = ((ScheduleEdge)it_edges.next()).getListExeTime(); - } - while(it_edges.hasNext()) { - int tetime = ((ScheduleEdge)it_edges.next()).getListExeTime(); - if(temp < tetime) { - temp = tetime; - } - } - listExeTime += temp; - } - return this.listExeTime; - } - - public void resetListExeTime() { - this.listExeTime = -1; - } + + protected FlagState targetFState; + + private ClassNode sourceCNode; + private ClassNode targetCNode; + + private int probability; + private int transTime; + private int listExeTime; + + private FEdge fedge; + private int newRate; + + private boolean isclone; + + /** Class Constructor + * + */ + public ScheduleEdge(ScheduleNode target, String label, FlagState fstate, int type, int gid) { + super(target); + this.uid = ScheduleEdge.nodeID++; + this.gid = gid; + this.fedge = null; + this.targetFState = null; + this.sourceCNode = null; + this.targetCNode = null; + this.label = label; + this.fstate = fstate; + this.newRate = -1; + this.probability = 100; + this.transTime = -1; + this.listExeTime = -1; + this.isclone = false; + this.type = type; + } + + public boolean isclone() { + return isclone; + } + + public void setIsclone(boolean isclone) { + this.isclone = isclone; + } + + public void setTarget(GraphNode sn) { + this.target = sn; + } + + public int getType() { + return type; + } + + public String getLabel() { + String completeLabel = label; + if(ScheduleEdge.NEWEDGE == this.type) { + completeLabel += ":" + Integer.toString(this.newRate); + } + completeLabel += ":(" + Integer.toString(this.probability) + "%)" + ":[" + Integer.toString(this.transTime) + "]"; + return completeLabel; + } + + public FlagState getFstate() { + return fstate; + } + + public FEdge getFEdge() { + return this.fedge; + } + + public void setFEdge(FEdge fEdge) { + this.fedge = fEdge; + } + + public FlagState getSourceFState() { + if(this.fedge == null) { + return null; + } + return (FlagState) this.fedge.getTarget(); + } + + public void setTargetFState(FlagState targetFState) { + this.targetFState = targetFState; + } + + public FlagState getTargetFState() { + return this.targetFState; + } + + public int getProbability() { + return this.probability; + } + + public int getNewRate() { + return this.newRate; + } + + public ClassNode getSourceCNode() { + return this.sourceCNode; + } + + public void setSourceCNode(ClassNode sourceCNode) { + this.sourceCNode = sourceCNode; + } + + public ClassNode getTargetCNode() { + return this.targetCNode; + } + + public void setTargetCNode(ClassNode targetCNode) { + this.targetCNode = targetCNode; + this.transTime = targetCNode.getTransTime(); + } + + public boolean equals(Object o) { + if (o instanceof ScheduleEdge) { + ScheduleEdge e=(ScheduleEdge)o; + if(e.gid == this.gid) { + if(e.uid != this.uid) { + return false; + } + } + if ((e.label.equals(label))&& + (e.target.equals(target))&& + (e.source.equals(source)) && + (e.fstate.equals(fstate)) && + (e.sourceCNode.equals(sourceCNode)) && + (e.targetCNode.equals(targetCNode)) && + (e.newRate == newRate) && + (e.probability == probability) && + (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.fedge != null) { + return e.fedge.equals(fedge); + } else if(this.fedge == null) { + return true; + } + } + return false; + } + + public int hashCode() { + int hashcode = gid^uid^label.hashCode()^target.hashCode()^source.hashCode()^fstate.hashCode()^ + sourceCNode.hashCode()^targetCNode.hashCode()^newRate^probability^ + type^transTime^listExeTime; + if(targetFState != null) { + hashcode ^= targetFState.hashCode(); + } + if(fedge != null) { + hashcode ^= fedge.hashCode(); + } + return hashcode; + } + + public void setProbability(int prob) { + this.probability = prob; + } + + public void setNewRate(int nr) { + this.newRate = nr; + } + + public int getTransTime() { + return this.transTime; + } + + public void setTransTime(int transTime) { + this.transTime = transTime; + } + + public int getListExeTime() { + if(listExeTime == -1) { + // calculate the lisExeTime + listExeTime = ((ScheduleNode) this.getTarget()).getExeTime() + this.getTransTime() * this.getNewRate(); + Iterator it_edges = this.getTarget().edges(); + int temp = 0; + if(it_edges.hasNext()) { + temp = ((ScheduleEdge)it_edges.next()).getListExeTime(); + } + while(it_edges.hasNext()) { + int tetime = ((ScheduleEdge)it_edges.next()).getListExeTime(); + if(temp < tetime) { + temp = tetime; + } + } + listExeTime += temp; + } + return this.listExeTime; + } + + public void resetListExeTime() { + this.listExeTime = -1; + } } diff --git a/Robust/src/Analysis/Scheduling/ScheduleNode.java b/Robust/src/Analysis/Scheduling/ScheduleNode.java index 063515f9..8129cd6d 100644 --- a/Robust/src/Analysis/Scheduling/ScheduleNode.java +++ b/Robust/src/Analysis/Scheduling/ScheduleNode.java @@ -8,375 +8,376 @@ import Util.GraphNode; /** This class holds flag transition diagram(s) can be put on one core. */ -public class ScheduleNode extends GraphNode implements Cloneable{ - - private int uid; - private int gid; - private int cid; - private static int nodeID=0; - public static int colorID = 0; - - private Vector classNodes; - Vector scheduleEdges; - - private int executionTime; - - /** Class constructor - * @param cd ClassDescriptor - * @param fStates - */ - public ScheduleNode(int gid) { - this.uid = ScheduleNode.nodeID++; - this.gid = gid; - this.cid = -1; - this.executionTime = -1; - this.classNodes = null; - this.scheduleEdges = null; +public class ScheduleNode extends GraphNode implements Cloneable { + + private int uid; + private int gid; + private int cid; + private static int nodeID=0; + public static int colorID = 0; + + private Vector classNodes; + Vector scheduleEdges; + + private int executionTime; + + /** Class constructor + * @param cd ClassDescriptor + * @param fStates + */ + public ScheduleNode(int gid) { + this.uid = ScheduleNode.nodeID++; + this.gid = gid; + this.cid = -1; + this.executionTime = -1; + this.classNodes = null; + this.scheduleEdges = null; + } + + public ScheduleNode(ClassNode cn, int gid) { + this.uid = ScheduleNode.nodeID++; + this.gid = gid; + this.cid = -1; + this.classNodes = new Vector(); + this.scheduleEdges = new Vector(); + this.classNodes.add(cn); + this.addEdge(cn.getEdgeVector()); + this.executionTime = -1; + } + + public int getuid() { + return uid; + } + + public int getCid() { + return cid; + } + + public void setCid(int cid) { + this.cid = cid; + } + + public String toString() { + String temp = new String(""); + for(int i = 0; i < classNodes.size(); i++) { + temp += classNodes.elementAt(i).getClassDescriptor().toString() + ", "; } - - public ScheduleNode(ClassNode cn, int gid) { - this.uid = ScheduleNode.nodeID++; - this.gid = gid; - this.cid = -1; - this.classNodes = new Vector(); - this.scheduleEdges = new Vector(); - this.classNodes.add(cn); - this.addEdge(cn.getEdgeVector()); - this.executionTime = -1; + temp += getTextLabel(); + return temp; + } + + public Vector getClassNodes() { + return classNodes; + } + + public Iterator getClassNodesIterator() { + if(classNodes == null) { + return null; } - - public int getuid() { - return uid; + return classNodes.iterator(); + } + + public void resetClassNodes() { + classNodes = null; + } + + public Vector getScheduleEdges() { + return scheduleEdges; + } + + public Iterator getScheduleEdgesIterator() { + if(scheduleEdges == null) { + return null; } - - public int getCid() { - return cid; + return scheduleEdges.iterator(); + } + + public void resetScheduleEdges() { + scheduleEdges = null; + } + + public int getExeTime() { + if(this.executionTime == -1) { + try { + calExeTime(); + } catch (Exception e) { + e.printStackTrace(); + } } + return this.executionTime; + } - public void setCid(int cid) { - this.cid = cid; + public void calExeTime() throws Exception { + if(this.classNodes.size() != 1) { + throw new Exception("Error: there are multiple ClassNodes inside the ScheduleNode when calculating executionTime"); + } + ClassNode cn = this.classNodes.elementAt(0); + if(!cn.isSorted()) { + throw new Error("Error: Non-sorted ClassNode!"); } + this.executionTime = cn.getFlagStates().elementAt(0).getExeTime(); + } + + /** Tests for equality of two flagstate objects. + */ - public String toString() { - String temp = new String(""); - for(int i = 0; i < classNodes.size(); i++) { - temp += classNodes.elementAt(i).getClassDescriptor().toString() + ", "; - } - temp += getTextLabel(); - return temp; + public boolean equals(Object o) { + 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.executionTime != this.executionTime)){ + return false; + } + if(fs.classNodes != null) { + if(!fs.classNodes.equals(classNodes)) { + return false; + } + } else if(classNodes != null) { + return false; + } + return true; } - - public Vector getClassNodes() { - return classNodes; + return false; + } + + public int hashCode() { + int hashcode = gid^uid^cid^executionTime; + if(this.classNodes != null) { + hashcode ^= classNodes.hashCode(); } - - public Iterator getClassNodesIterator() { - if(classNodes == null) { - return null; - } - return classNodes.iterator(); + return hashcode; + } + + public String getLabel() { + return "cluster" + uid; + } + + public String getTextLabel() { + String label=null; + + if (label==null) + return " "; + return label; + } + + public Object clone(Hashtable cn2cn, int gid) { + ScheduleNode o = null; + try { + o = (ScheduleNode) super.clone(); + } catch(CloneNotSupportedException e){ + e.printStackTrace(); } - - public void resetClassNodes() { - classNodes = null; + o.uid = ScheduleNode.nodeID++; + o.gid = gid; + o.cid = this.cid; + // Clone all the internal ClassNodes and ScheduleEdges + Vector tcns = new Vector(); + Vector tses = new Vector(); + int i = 0; + for(i = 0; i < this.classNodes.size(); i++) { + ClassNode tcn = this.classNodes.elementAt(i); + ClassNode cn = (ClassNode)tcn.clone(); + cn.setScheduleNode(o); + tcns.add(cn); + cn2cn.put(tcn, cn); } - - public Vector getScheduleEdges() { - return scheduleEdges; + for(i = 0; i < this.scheduleEdges.size(); i++) { + ScheduleEdge temp = this.scheduleEdges.elementAt(i); + 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; + } + + case ScheduleEdge.TRANSEDGE: { + 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())); + se.setTargetCNode(cn2cn.get(temp.getTargetCNode())); + se.setTransTime(temp.getTransTime()); + se.setFEdge(temp.getFEdge()); + se.setTargetFState(temp.getTargetFState()); + se.setIsclone(true); + tses.add(se); } - - public Iterator getScheduleEdgesIterator() { - if(scheduleEdges == null) { - return null; - } - return scheduleEdges.iterator(); + o.classNodes = tcns; + o.scheduleEdges = tses; + tcns = null; + tses = null; + + o.inedges = new Vector(); + o.edges = new Vector(); + return o; + } + + public void mergeSEdge(ScheduleEdge se) throws Exception { + ScheduleNode sn = (ScheduleNode)se.getTarget(); + Vector targetCNodes = (Vector)sn.getClassNodes(); + Vector targetSEdges = (Vector)sn.getScheduleEdges(); + + for(int i = 0; i < targetCNodes.size(); i++) { + targetCNodes.elementAt(i).setScheduleNode(this); } - - public void resetScheduleEdges() { - scheduleEdges = null; + + if(classNodes == null) { + classNodes = targetCNodes; + scheduleEdges = targetSEdges; + } else { + if(targetCNodes.size() != 0) { + classNodes.addAll(targetCNodes); + } + if(targetSEdges.size() != 0) { + scheduleEdges.addAll(targetSEdges); + } } - - public int getExeTime() { - if(this.executionTime == -1) { - try { - calExeTime(); - } catch (Exception e) { - e.printStackTrace(); - } + targetCNodes = null; + + if(ScheduleEdge.TRANSEDGE == se.getType()) { + sn.removeInedge(se); + this.removeEdge(se); + + // merge the split ClassNode of same class + FlagState sfs = se.getFstate(); + FlagState tfs = se.getTargetFState(); + ClassNode scn = se.getSourceCNode(); + ClassNode tcn = se.getTargetCNode(); + sfs.getEdgeVector().addAll(tfs.getEdgeVector()); + // merge the subtree whose root is nfs from the whole flag transition tree + Vector sfss = scn.getFlagStates(); + sfss.addAll(tcn.getFlagStates()); + sfss.removeElement(tfs); + classNodes.removeElement(tcn); + + // flush the exeTime of fs and its ancestors + sfs.setExeTime(0); + Queue toiterate = new LinkedList(); + toiterate.add(sfs); + while(!toiterate.isEmpty()) { + FlagState tmpfs = toiterate.poll(); + int ttime = tmpfs.getExeTime(); + Iterator it_inedges = tmpfs.inedges(); + while(it_inedges.hasNext()) { + FEdge fEdge = (FEdge)it_inedges.next(); + FlagState temp = (FlagState)fEdge.getSource(); + int time = fEdge.getExeTime() + ttime; + if(temp.getExeTime() > time) { + temp.setExeTime(time); + toiterate.add(temp); + } } - return this.executionTime; - } - - public void calExeTime() throws Exception { - if(this.classNodes.size() != 1) { - throw new Exception("Error: there are multiple ClassNodes inside the ScheduleNode when calculating executionTime"); - } - ClassNode cn = this.classNodes.elementAt(0); - if(!cn.isSorted()) { - throw new Error("Error: Non-sorted ClassNode!"); + } + 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); } - this.executionTime = cn.getFlagStates().elementAt(0).getExeTime(); - } - - /** Tests for equality of two flagstate objects. - */ - - public boolean equals(Object o) { - 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.executionTime != this.executionTime)){ - return false; - } - if(fs.classNodes != null) { - if(!fs.classNodes.equals(classNodes)) { - return false; - } - } else if(classNodes != null) { - return false; - } - return true; - } - return false; - } + } - public int hashCode() { - int hashcode = gid^uid^cid^executionTime; - if(this.classNodes != null) { - hashcode ^= classNodes.hashCode(); + // 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); } - return hashcode; + this.edges.addElement(tse); + } + + targetSEdges = 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) { + throw new Exception("Error: ScheduleNode without initiate execution time when analysising."); + } + if(this.executionTime < sn.getExeTime()) { + this.executionTime = sn.getExeTime(); + } + } else if(ScheduleEdge.NEWEDGE == se.getType()) { + targetSEdges = null; + + scheduleEdges.add(se); + se.resetListExeTime(); + sn.removeInedge(se); + 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); + } + + // 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 += ((ScheduleNode)se.getTarget()).getExeTime(); } + } - public String getLabel() { - return "cluster" + uid; - } + public void mergeSNode(ScheduleNode sn) throws Exception { + Vector targetCNodes = (Vector)sn.getClassNodes(); + Vector targetSEdges = (Vector)sn.getScheduleEdges(); - public String getTextLabel() { - String label=null; - - if (label==null) - return " "; - return label; + for(int i = 0; i < targetCNodes.size(); i++) { + targetCNodes.elementAt(i).setScheduleNode(this); } - - public Object clone(Hashtable cn2cn, int gid) { - ScheduleNode o = null; - try { - o = (ScheduleNode)super.clone(); - } catch(CloneNotSupportedException e){ - e.printStackTrace(); - } - o.uid = ScheduleNode.nodeID++; - o.gid = gid; - o.cid = this.cid; - // Clone all the internal ClassNodes and ScheduleEdges - Vector tcns = new Vector(); - Vector tses = new Vector(); - int i = 0; - for(i = 0; i < this.classNodes.size(); i++) { - ClassNode tcn = this.classNodes.elementAt(i); - ClassNode cn = (ClassNode)tcn.clone(); - cn.setScheduleNode(o); - tcns.add(cn); - cn2cn.put(tcn, cn); - } - for(i = 0; i < this.scheduleEdges.size(); i++) { - ScheduleEdge temp = this.scheduleEdges.elementAt(i); - 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; - } - case ScheduleEdge.TRANSEDGE: { - 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())); - se.setTargetCNode(cn2cn.get(temp.getTargetCNode())); - se.setTransTime(temp.getTransTime()); - se.setFEdge(temp.getFEdge()); - se.setTargetFState(temp.getTargetFState()); - se.setIsclone(true); - tses.add(se); - } - o.classNodes = tcns; - o.scheduleEdges = tses; - tcns = null; - tses = null; - - o.inedges = new Vector(); - o.edges = new Vector(); - return o; + + if(classNodes == null) { + classNodes = targetCNodes; + scheduleEdges = targetSEdges; + } else { + if(targetCNodes.size() != 0) { + classNodes.addAll(targetCNodes); + } + if(targetSEdges.size() != 0) { + scheduleEdges.addAll(targetSEdges); + } } - - public void mergeSEdge(ScheduleEdge se) throws Exception { - ScheduleNode sn = (ScheduleNode)se.getTarget(); - Vector targetCNodes = (Vector)sn.getClassNodes(); - Vector targetSEdges = (Vector)sn.getScheduleEdges(); - - for(int i = 0; i < targetCNodes.size(); i++) { - targetCNodes.elementAt(i).setScheduleNode(this); - } - - if(classNodes == null) { - classNodes = targetCNodes; - scheduleEdges = targetSEdges; - } else { - if(targetCNodes.size() != 0) { - classNodes.addAll(targetCNodes); - } - if(targetSEdges.size() != 0) { - scheduleEdges.addAll(targetSEdges); - } - } - targetCNodes = null; - - if(ScheduleEdge.TRANSEDGE == se.getType()) { - sn.removeInedge(se); - this.removeEdge(se); - - // merge the split ClassNode of same class - FlagState sfs = se.getFstate(); - FlagState tfs = se.getTargetFState(); - ClassNode scn = se.getSourceCNode(); - ClassNode tcn = se.getTargetCNode(); - sfs.getEdgeVector().addAll(tfs.getEdgeVector()); - // merge the subtree whose root is nfs from the whole flag transition tree - Vector sfss = scn.getFlagStates(); - sfss.addAll(tcn.getFlagStates()); - sfss.removeElement(tfs); - classNodes.removeElement(tcn); - - // flush the exeTime of fs and its ancestors - sfs.setExeTime(0); - Queue toiterate = new LinkedList(); - toiterate.add(sfs); - while(!toiterate.isEmpty()) { - FlagState tmpfs = toiterate.poll(); - int ttime = tmpfs.getExeTime(); - Iterator it_inedges = tmpfs.inedges(); - while(it_inedges.hasNext()) { - FEdge fEdge = (FEdge)it_inedges.next(); - FlagState temp = (FlagState)fEdge.getSource(); - int time = fEdge.getExeTime() + ttime; - if(temp.getExeTime() > time) { - temp.setExeTime(time); - toiterate.add(temp); - } - } - } - 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); - } - } - - // 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); - } - - targetSEdges = 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) { - throw new Exception("Error: ScheduleNode without initiate execution time when analysising."); - } - if(this.executionTime < sn.getExeTime()) { - this.executionTime = sn.getExeTime(); - } - } else if(ScheduleEdge.NEWEDGE == se.getType()) { - targetSEdges = null; - - scheduleEdges.add(se); - se.resetListExeTime(); - sn.removeInedge(se); - 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); - } - - // 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 += ((ScheduleNode)se.getTarget()).getExeTime(); - } + targetCNodes = null; + targetSEdges = null; + + // redirect external ScheduleEdges to this ScheduleNode + Iterator it_edges = sn.edges(); + while(it_edges.hasNext()) { + ScheduleEdge tse = (ScheduleEdge)it_edges.next(); + tse.setSource(this); + this.edges.addElement(tse); } - - public void mergeSNode(ScheduleNode sn) throws Exception { - Vector targetCNodes = (Vector)sn.getClassNodes(); - Vector targetSEdges = (Vector)sn.getScheduleEdges(); - - for(int i = 0; i < targetCNodes.size(); i++) { - targetCNodes.elementAt(i).setScheduleNode(this); - } - - if(classNodes == null) { - classNodes = targetCNodes; - scheduleEdges = targetSEdges; - } else { - if(targetCNodes.size() != 0) { - classNodes.addAll(targetCNodes); - } - if(targetSEdges.size() != 0) { - scheduleEdges.addAll(targetSEdges); - } - } - targetCNodes = null; - targetSEdges = null; - - // redirect external ScheduleEdges to this ScheduleNode - Iterator it_edges = sn.edges(); - while(it_edges.hasNext()) { - ScheduleEdge tse = (ScheduleEdge)it_edges.next(); - tse.setSource(this); - this.edges.addElement(tse); - } - - it_edges = sn.inedges(); - while(it_edges.hasNext()) { - ScheduleEdge tse = (ScheduleEdge)it_edges.next(); - tse.setTarget(this); - this.inedges.addElement(tse); - } - - // 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 += sn.getExeTime(); + it_edges = sn.inedges(); + while(it_edges.hasNext()) { + ScheduleEdge tse = (ScheduleEdge)it_edges.next(); + tse.setTarget(this); + this.inedges.addElement(tse); } + + // 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 += sn.getExeTime(); + + } } diff --git a/Robust/src/Analysis/Scheduling/ScheduleSimulator.java b/Robust/src/Analysis/Scheduling/ScheduleSimulator.java index 5e899b29..00b9ca02 100644 --- a/Robust/src/Analysis/Scheduling/ScheduleSimulator.java +++ b/Robust/src/Analysis/Scheduling/ScheduleSimulator.java @@ -15,463 +15,463 @@ import IR.TaskDescriptor; import IR.TypeUtil; public class ScheduleSimulator { - private int coreNum; - private Vector scheduling; - private Vector cores; - private Vector tasks; - private Vector checkpoints; - private int processTime; - private int invoketime; - - State state; - TaskAnalysis taskanalysis; - - public ScheduleSimulator(int coreNum, State state, TaskAnalysis taskanalysis) { - super(); - this.coreNum = coreNum; - this.scheduling = null; - this.cores = null; - this.tasks = null; - this.checkpoints = null; - this.processTime = 0; - this.invoketime = 0; - this.state = state; - this.taskanalysis = taskanalysis; + private int coreNum; + private Vector scheduling; + private Vector cores; + private Vector tasks; + private Vector checkpoints; + private int processTime; + private int invoketime; + + State state; + TaskAnalysis taskanalysis; + + public ScheduleSimulator(int coreNum, State state, TaskAnalysis taskanalysis) { + super(); + this.coreNum = coreNum; + this.scheduling = null; + this.cores = null; + this.tasks = null; + this.checkpoints = null; + this.processTime = 0; + this.invoketime = 0; + this.state = state; + this.taskanalysis = taskanalysis; + } + + public ScheduleSimulator(int coreNum, Vector scheduling, State state, TaskAnalysis taskanalysis) { + super(); + this.coreNum = coreNum; + this.scheduling = scheduling; + this.cores = new Vector(this.coreNum); + for(int i = 0; i < this.coreNum; i++) { + this.cores.add(new CoreSimulator(FIFORSchedule.getFIFORSchedule(), i)); } - - public ScheduleSimulator(int coreNum, Vector scheduling, State state, TaskAnalysis taskanalysis) { - super(); - this.coreNum = coreNum; - this.scheduling = scheduling; - this.cores = new Vector(this.coreNum); - for(int i = 0; i < this.coreNum; i++) { - this.cores.add(new CoreSimulator(FIFORSchedule.getFIFORSchedule(), i)); - } - this.tasks = new Vector(); - this.checkpoints = null; - this.processTime = 0; - this.invoketime = 0; - this.state = state; - this.taskanalysis = taskanalysis; - applyScheduling(); + this.tasks = new Vector(); + this.checkpoints = null; + this.processTime = 0; + this.invoketime = 0; + this.state = state; + this.taskanalysis = taskanalysis; + applyScheduling(); + } + + public Vector getCheckpoints() { + return checkpoints; + } + + public int getCoreNum() { + return coreNum; + } + + public void setCoreNum(int coreNum) { + this.coreNum = coreNum; + if(this.cores != null) { + this.cores.clear(); } - - public Vector getCheckpoints() { - return checkpoints; + this.cores = new Vector(this.coreNum); + for(int i = 0; i < this.coreNum; i++) { + this.cores.add(new CoreSimulator(FIFORSchedule.getFIFORSchedule(), i)); } - - public int getCoreNum() { - return coreNum; + if(this.scheduling != null) { + applyScheduling(); } + } - public void setCoreNum(int coreNum) { - this.coreNum = coreNum; - if(this.cores != null) { - this.cores.clear(); - } - this.cores = new Vector(this.coreNum); - for(int i = 0; i < this.coreNum; i++) { - this.cores.add(new CoreSimulator(FIFORSchedule.getFIFORSchedule(), i)); - } - if(this.scheduling != null) { - applyScheduling(); - } + public int getUtility(int index) { + return (this.cores.elementAt(index).getActiveTime() * 100) / this.processTime; + } + + public Vector getScheduling() { + return scheduling; + } + + public void setScheduling(Vector scheduling) { + this.scheduling = scheduling; + if(this.tasks == null) { + this.tasks = new Vector(); + } else { + this.tasks.clear(); + } + if(this.cores != null) { + for(int i = 0; i < this.coreNum; i++) { + 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)); + } } - public int getUtility(int index) { - return (this.cores.elementAt(index).getActiveTime() * 100) / this.processTime; + applyScheduling(); + } + + public void applyScheduling() { + assert(this.state != null); + + for(int i = 0; i < this.scheduling.size(); i++) { + Schedule temp = this.scheduling.elementAt(i); + CoreSimulator cs = this.cores.elementAt(temp.getCoreNum()); + cs.deployTasks(temp.getTasks()); + cs.setTargetCSimulator(temp.getTargetCoreTable()); + cs.setAllyCSimulator(temp.getAllyCoreTable()); + cs.setTargetFState(temp.getTargetFStateTable()); } - - public Vector getScheduling() { - return scheduling; + // inject a Startup Object to each core + for(int i = 0; i < this.coreNum; i++) { + ClassDescriptor startupobject=(ClassDescriptor)state.getClassSymbolTable().get(TypeUtil.StartupClass); + FlagState fsstartup = (FlagState)taskanalysis.getRootNodes(startupobject).elementAt(0); + ObjectSimulator newObj = new ObjectSimulator(startupobject, fsstartup); + this.cores.elementAt(i).addObject(newObj); } - - public void setScheduling(Vector scheduling) { - this.scheduling = scheduling; - if(this.tasks == null) { - this.tasks = new Vector(); - } else { - this.tasks.clear(); - } - if(this.cores != null) { - for(int i = 0; i < this.coreNum; i++) { - 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)); - } - } - - applyScheduling(); + } + + public Vector getTasks() { + return tasks; + } + + public int process() { + assert(this.scheduling != null); + + this.invoketime++; + + if(this.checkpoints == null) { + this.checkpoints = new Vector(); + } else { + this.checkpoints.clear(); } - public void applyScheduling() { - assert(this.state != null); - - for(int i = 0; i < this.scheduling.size(); i++) { - Schedule temp = this.scheduling.elementAt(i); - CoreSimulator cs = this.cores.elementAt(temp.getCoreNum()); - cs.deployTasks(temp.getTasks()); - cs.setTargetCSimulator(temp.getTargetCoreTable()); - cs.setAllyCSimulator(temp.getAllyCoreTable()); - cs.setTargetFState(temp.getTargetFStateTable()); - } - // inject a Startup Object to each core - for(int i = 0; i < this.coreNum; i++) { - ClassDescriptor startupobject=(ClassDescriptor)state.getClassSymbolTable().get(TypeUtil.StartupClass); - FlagState fsstartup = (FlagState)taskanalysis.getRootNodes(startupobject).elementAt(0); - ObjectSimulator newObj = new ObjectSimulator(startupobject, fsstartup); - this.cores.elementAt(i).addObject(newObj); - } + this.processTime = 0; + + // first decide next task to execute on each core + int i = 0; + for(i = 0; i < this.cores.size(); i++) { + CoreSimulator cs = this.cores.elementAt(i); + TaskSimulator task = cs.process(); + if(task != null) { + this.tasks.add(task); + } } - public Vector getTasks() { - return tasks; + // add STARTTASK checkpoint for all the initial tasks + CheckPoint cp = new CheckPoint(this.processTime); + for(i = 0; i < this.tasks.size(); i++) { + TaskSimulator task = this.tasks.elementAt(i); + Action action = new Action(task.getCs().getCoreNum(), Action.TASKSTART); + action.setTd(task.getTd()); + cp.addAction(action); } - - public int process() { - assert(this.scheduling != null); - - this.invoketime++; - - if(this.checkpoints == null) { - this.checkpoints = new Vector(); - } else { - this.checkpoints.clear(); - } - - this.processTime = 0; - - // first decide next task to execute on each core - int i = 0; - for(i = 0; i < this.cores.size(); i++) { - CoreSimulator cs = this.cores.elementAt(i); - TaskSimulator task = cs.process(); - if(task != null) { - this.tasks.add(task); - } + this.checkpoints.add(cp); + + while(true) { + // if no more tasks on each core, simulation finish + if(this.tasks.size() == 0) { + break; + } + + // for each task in todo queue, decide the execution path of this time + // according to statistic information + //int index = 0; // indicate the task to finish first + int finishTime = Integer.MAX_VALUE; + Vector finishTasks = new Vector(); + for(i = 0; i < this.tasks.size(); i++) { + TaskSimulator task = this.tasks.elementAt(i); + task.process(); + int tempTime = task.getCurrentRun().getFinishTime(); + if(tempTime < finishTime) { + finishTime = tempTime; + finishTasks.clear(); + finishTasks.add(task); + } else if (tempTime == finishTime) { + finishTasks.add(task); } - - // add STARTTASK checkpoint for all the initial tasks - CheckPoint cp = new CheckPoint(this.processTime); - for(i = 0; i < this.tasks.size(); i++) { - TaskSimulator task = this.tasks.elementAt(i); - Action action = new Action(task.getCs().getCoreNum(), Action.TASKSTART); - action.setTd(task.getTd()); - cp.addAction(action); + } + for(i = 0; i < this.tasks.size(); i++) { + TaskSimulator task = this.tasks.elementAt(i); + if(!finishTasks.contains(task)) { + task.getCs().updateTask(finishTime); } - this.checkpoints.add(cp); - - while(true) { - // if no more tasks on each core, simulation finish - if(this.tasks.size() == 0) { - break; + } + this.processTime += finishTime; + cp = new CheckPoint(this.processTime); + Action action = null; + for(i = 0; i < finishTasks.size(); i++) { + TaskSimulator task = finishTasks.elementAt(i); + this.tasks.removeElement(task); + if(task instanceof TransTaskSimulator) { + TransTaskSimulator tmptask = (TransTaskSimulator)task; + // add ADDOBJ task to targetCore + int targetCoreNum = tmptask.getTargetCoreNum(); + ObjectInfo objinfo = tmptask.refreshTask(); + ObjectSimulator nobj = objinfo.obj; + FlagState fs = objinfo.fs; + int version = objinfo.version; + this.cores.elementAt(targetCoreNum).addObject(nobj, fs, version); + action = new Action(targetCoreNum, Action.ADDOBJ, 1, nobj.getCd()); + cp.addAction(action); + if(!tmptask.isFinished()) { + // still have some objects to be transpotted + this.tasks.add(task); + } + 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); + action.setTd(newTask.getTd()); + cp.addAction(action); } - - // for each task in todo queue, decide the execution path of this time - // according to statistic information - //int index = 0; // indicate the task to finish first - int finishTime = Integer.MAX_VALUE; - Vector finishTasks = new Vector(); - for(i = 0; i < this.tasks.size(); i++) { - TaskSimulator task = this.tasks.elementAt(i); - task.process(); - int tempTime = task.getCurrentRun().getFinishTime(); - if(tempTime < finishTime) { - finishTime = tempTime; - finishTasks.clear(); - finishTasks.add(task); - } else if (tempTime == finishTime) { - finishTasks.add(task); + } + } else { + CoreSimulator cs = task.getCs(); + int coreNum = cs.getCoreNum(); + if(task.getCurrentRun().getExetype() == 0) { + Hashtable> transObjQueues = new Hashtable>(); + if(task.getCurrentRun().getNewObjs() == null) { + action = new Action(coreNum, Action.TASKFINISH); + action.setTd(cs.getRtask().getTd()); + } else { + action = new Action(coreNum, Action.TFWITHOBJ); + action.setTd(cs.getRtask().getTd()); + Vector nobjs = task.getCurrentRun().getNewObjs(); + for(int j = 0; j < nobjs.size(); j++) { + ObjectSimulator nobj = nobjs.elementAt(j); + 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)); + } + // enqueue this core again + cores.add(targetCore); } - } - for(i = 0; i < this.tasks.size(); i++) { - TaskSimulator task = this.tasks.elementAt(i); - if(!finishTasks.contains(task)) { - task.getCs().updateTask(finishTime); + // check if this object becoming shared or not + Vector allycores = cs.getAllyCores(nobj.getCurrentFS()); + if(allycores != null) { + nobj.setShared(true); + for(int k = 0; k < allycores.size(); ++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); + } + } + } } + } } - this.processTime += finishTime; - cp = new CheckPoint(this.processTime); - Action action = null; - for(i = 0; i < finishTasks.size(); i++) { - TaskSimulator task = finishTasks.elementAt(i); - this.tasks.removeElement(task); - if(task instanceof TransTaskSimulator) { - TransTaskSimulator tmptask = (TransTaskSimulator)task; - // add ADDOBJ task to targetCore - int targetCoreNum = tmptask.getTargetCoreNum(); - ObjectInfo objinfo = tmptask.refreshTask(); - ObjectSimulator nobj = objinfo.obj; - FlagState fs = objinfo.fs; - int version = objinfo.version; - this.cores.elementAt(targetCoreNum).addObject(nobj, fs, version); - action = new Action(targetCoreNum, Action.ADDOBJ, 1, nobj.getCd()); - cp.addAction(action); - if(!tmptask.isFinished()) { - // still have some objects to be transpotted - this.tasks.add(task); - } - 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); - action.setTd(newTask.getTd()); - cp.addAction(action); - } - } + cp.addAction(action); + Vector transObjs = cs.finishTask(); + if(transObjs != null) { + 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 { - CoreSimulator cs = task.getCs(); - int coreNum = cs.getCoreNum(); - if(task.getCurrentRun().getExetype() == 0) { - Hashtable> transObjQueues = new Hashtable>(); - if(task.getCurrentRun().getNewObjs() == null) { - action = new Action(coreNum, Action.TASKFINISH); - action.setTd(cs.getRtask().getTd()); - } else { - action = new Action(coreNum, Action.TFWITHOBJ); - action.setTd(cs.getRtask().getTd()); - Vector nobjs = task.getCurrentRun().getNewObjs(); - for(int j = 0; j < nobjs.size(); j++) { - ObjectSimulator nobj = nobjs.elementAt(j); - 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)); - } - // enqueue this core again - cores.add(targetCore); - } - // check if this object becoming shared or not - Vector allycores = cs.getAllyCores(nobj.getCurrentFS()); - if(allycores != null) { - nobj.setShared(true); - for(int k = 0; k < allycores.size(); ++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); - } - } - } - } - } - } - cp.addAction(action); - Vector transObjs = cs.finishTask(); - if(transObjs != null) { - 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.peek(); - 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)); - } - } - // check if this object becoming shared or not - Vector allycores = cs.getAllyCores(tobj.getCurrentFS()); - if(allycores != null) { - tobj.setShared(true); - for(int k = 0; k < allycores.size(); ++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); - } - } - } - } - } - } - // add 'transport' tasks - Iterator it_entries = transObjQueues.entrySet().iterator(); - while(it_entries.hasNext()) { - Entry> tmpentry = (Entry>)it_entries.next(); - Integer tmpCoreNum = tmpentry.getKey(); - Queue nobjs = tmpentry.getValue(); - TransTaskSimulator tmptask = new TransTaskSimulator(cs, tmpCoreNum, nobjs); - this.tasks.add(tmptask); - } - // Choose a new task for this core - TaskSimulator newTask = cs.process(); - if(newTask != null) { - this.tasks.add(newTask); - // add a TASKSTART action into this checkpoint - action = new Action(coreNum, Action.TASKSTART); - action.setTd(cs.getRtask().getTd()); - cp.addAction(action); - } - } else if (task.getCurrentRun().getExetype() == 1) { - action = new Action(coreNum, Action.TASKABORT); - action.setTd(cs.getRtask().getTd()); - cp.addAction(action); - } else if (task.getCurrentRun().getExetype() == 2) { - action = new Action(coreNum, Action.TASKREMOVE); - action.setTd(cs.getRtask().getTd()); - cp.addAction(action); + Integer targetCore = cores.peek(); + 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)); + } + } + // check if this object becoming shared or not + Vector allycores = cs.getAllyCores(tobj.getCurrentFS()); + if(allycores != null) { + tobj.setShared(true); + for(int k = 0; k < allycores.size(); ++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); + } } + } } + } } - this.checkpoints.add(cp); - } - - SchedulingUtil.printSimulationResult("SimulatorResult_" + this.invoketime + ".dot", this.processTime, - this.coreNum, this.checkpoints); - System.out.println("Simulate scheduling #" + this.invoketime + ": "); - 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) + "%"); + // add 'transport' tasks + Iterator it_entries = transObjQueues.entrySet().iterator(); + while(it_entries.hasNext()) { + Entry> tmpentry = (Entry>)it_entries.next(); + Integer tmpCoreNum = tmpentry.getKey(); + Queue nobjs = tmpentry.getValue(); + TransTaskSimulator tmptask = new TransTaskSimulator(cs, tmpCoreNum, nobjs); + this.tasks.add(tmptask); + } + // Choose a new task for this core + TaskSimulator newTask = cs.process(); + if(newTask != null) { + this.tasks.add(newTask); + // add a TASKSTART action into this checkpoint + action = new Action(coreNum, Action.TASKSTART); + action.setTd(cs.getRtask().getTd()); + cp.addAction(action); + } + } else if (task.getCurrentRun().getExetype() == 1) { + action = new Action(coreNum, Action.TASKABORT); + action.setTd(cs.getRtask().getTd()); + cp.addAction(action); + } else if (task.getCurrentRun().getExetype() == 2) { + action = new Action(coreNum, Action.TASKREMOVE); + action.setTd(cs.getRtask().getTd()); + cp.addAction(action); + } } - return this.processTime; + } + this.checkpoints.add(cp); } - - public class CheckPoint { - private int timepoint; - private Vector actions; - - public CheckPoint(int timepoint) { - super(); - this.timepoint = timepoint; - this.actions = new Vector(); - } - public Vector getActions() { - return actions; - } + SchedulingUtil.printSimulationResult("SimulatorResult_" + this.invoketime + ".dot", this.processTime, + this.coreNum, this.checkpoints); + System.out.println("Simulate scheduling #" + this.invoketime + ": "); + 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) + "%"); + } + return this.processTime; + } - public void addAction(Action action) { - this.actions.add(action); - } + public class CheckPoint { + private int timepoint; + private Vector actions; - public int getTimepoint() { - return timepoint; - } + public CheckPoint(int timepoint) { + super(); + this.timepoint = timepoint; + this.actions = new Vector(); } - - public class Action { - public static final int ADDOBJ = 0; - public static final int TASKFINISH = 1; - public static final int TFWITHOBJ = 2; - public static final int TASKSTART = 3; - public static final int TASKABORT = 4; - public static final int TASKREMOVE = 5; - - private int coreNum; - private int type; - private TaskDescriptor td; - private Hashtable nObjs; - private int nObjNum; - private ClassDescriptor transObj; - - public Action(int coreNum, int type) { - super(); - this.coreNum = coreNum; - this.type = type; - this.td = null; - if(this.type == TFWITHOBJ) { - this.nObjs = new Hashtable(); - } else { - this.nObjs = null; - } - this.nObjNum = -1; - this.transObj = null; - } - - public Action(int coreNum, int type, int objNum, ClassDescriptor transObj) { - super(); - assert(type == ADDOBJ); - this.coreNum = coreNum; - this.type = type; - this.td = null; - this.nObjNum = objNum; - this.transObj = transObj; - } - public void addNewObj(ClassDescriptor cd, Integer num) { - assert(this.type == TFWITHOBJ); - - if(this.nObjs.containsKey(cd)) { - Integer sum = this.nObjs.get(cd) + num; - this.nObjs.put(cd, sum); - } else { - this.nObjs.put(cd, num); - } - } + public Vector getActions() { + return actions; + } - public int getCoreNum() { - return coreNum; - } + public void addAction(Action action) { + this.actions.add(action); + } - public int getType() { - return type; - } + public int getTimepoint() { + return timepoint; + } + } - public int getNObjNum() { - return nObjNum; - } + public class Action { + public static final int ADDOBJ = 0; + public static final int TASKFINISH = 1; + public static final int TFWITHOBJ = 2; + public static final int TASKSTART = 3; + public static final int TASKABORT = 4; + public static final int TASKREMOVE = 5; - public ClassDescriptor getTransObj() { - return transObj; - } + private int coreNum; + private int type; + private TaskDescriptor td; + private Hashtable nObjs; + private int nObjNum; + private ClassDescriptor transObj; - public TaskDescriptor getTd() { - return td; - } + public Action(int coreNum, int type) { + super(); + this.coreNum = coreNum; + this.type = type; + this.td = null; + if(this.type == TFWITHOBJ) { + this.nObjs = new Hashtable(); + } else { + this.nObjs = null; + } + this.nObjNum = -1; + this.transObj = null; + } - public void setTd(TaskDescriptor td) { - this.td = td; - } + public Action(int coreNum, int type, int objNum, ClassDescriptor transObj) { + super(); + assert(type == ADDOBJ); + this.coreNum = coreNum; + this.type = type; + this.td = null; + this.nObjNum = objNum; + this.transObj = transObj; + } - public Hashtable getNObjs() { - return nObjs; - } + public void addNewObj(ClassDescriptor cd, Integer num) { + assert(this.type == TFWITHOBJ); + + if(this.nObjs.containsKey(cd)) { + Integer sum = this.nObjs.get(cd) + num; + this.nObjs.put(cd, sum); + } else { + this.nObjs.put(cd, num); + } } - + + public int getCoreNum() { + return coreNum; + } + + public int getType() { + return type; + } + + public int getNObjNum() { + return nObjNum; + } + + public ClassDescriptor getTransObj() { + return transObj; + } + + public TaskDescriptor getTd() { + return td; + } + + public void setTd(TaskDescriptor td) { + this.td = td; + } + + public Hashtable getNObjs() { + return nObjs; + } + } + } \ No newline at end of file diff --git a/Robust/src/Analysis/Scheduling/SchedulingUtil.java b/Robust/src/Analysis/Scheduling/SchedulingUtil.java index 2a629edc..64e411de 100644 --- a/Robust/src/Analysis/Scheduling/SchedulingUtil.java +++ b/Robust/src/Analysis/Scheduling/SchedulingUtil.java @@ -28,493 +28,501 @@ import Util.GraphNode; import Util.Namer; public class SchedulingUtil { - - /*public static int maxDivisor(int l, int r) { - int a = l; - int b = r; - int c = 0; - - while(true) { - if(a == 0) { - return b << c; - } else if(b == 0) { - return a << c; - } - - if(((a&1)==0) && ((b&1)==0)) { - // a and b are both even - a >>= 1; - b >>= 1; - ++c; - } else if(((a&1)==0) && ((b&1)!=0)) { - // a is even, b is odd - a >>= 1; - } else if (((a&1)!=0) && ((b&1)==0)) { - // a is odd, b is even - b >>= 1; - } else if (((a&1)!=0) && ((b&1)!=0)) { - // a and b are both odd - int tmp = a>b? b:a; - a = a>b ? (a-b):(b-a); - b = tmp; - } - } - }*/ - public static boolean isTaskTrigger_flag(FlagExpressionNode fen,FlagState fs) { - if (fen==null) - return true; - else if (fen instanceof FlagNode) - return fs.get(((FlagNode)fen).getFlag()); - else - switch (((FlagOpNode)fen).getOp().getOp()) { - case Operation.LOGIC_AND: - 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))); - case Operation.LOGIC_NOT: - return !(isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)); - default: - return false; - } - } - - public static void printScheduleGraph(String path, Vector sNodes) { - try { - File file=new File(path); - FileOutputStream dotstream=new FileOutputStream(file,false); - PrintWriter output = new java.io.PrintWriter(dotstream, true); - output.println("digraph G {"); - output.println("\tcompound=true;\n"); - traverseSNodes(output, sNodes); - output.println("}\n"); - output.close(); - } catch (Exception e) { - e.printStackTrace(); - System.exit(-1); - } + /*public static int maxDivisor(int l, int r) { + int a = l; + int b = r; + int c = 0; + + while(true) { + if(a == 0) { + return b << c; + } else if(b == 0) { + return a << c; + } + + if(((a&1)==0) && ((b&1)==0)) { + // a and b are both even + a >>= 1; + b >>= 1; + ++c; + } else if(((a&1)==0) && ((b&1)!=0)) { + // a is even, b is odd + a >>= 1; + } else if (((a&1)!=0) && ((b&1)==0)) { + // a is odd, b is even + b >>= 1; + } else if (((a&1)!=0) && ((b&1)!=0)) { + // a and b are both odd + int tmp = a>b? b:a; + a = a>b ? (a-b):(b-a); + b = tmp; + } + } + }*/ + + public static boolean isTaskTrigger_flag(FlagExpressionNode fen,FlagState fs) { + if (fen==null) + return true; + else if (fen instanceof FlagNode) + return fs.get(((FlagNode)fen).getFlag()); + else + switch (((FlagOpNode)fen).getOp().getOp()) { + case Operation.LOGIC_AND: + 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))); + + case Operation.LOGIC_NOT: + return !(isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)); + + default: + return false; + } + } + + public static void printScheduleGraph(String path, Vector sNodes) { + try { + File file=new File(path); + FileOutputStream dotstream=new FileOutputStream(file,false); + PrintWriter output = new java.io.PrintWriter(dotstream, true); + output.println("digraph G {"); + output.println("\tcompound=true;\n"); + traverseSNodes(output, sNodes); + output.println("}\n"); + output.close(); + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); } - - private static void traverseSNodes(PrintWriter output, Vector sNodes){ - //Draw clusters representing ScheduleNodes - Iterator it = sNodes.iterator(); - while (it.hasNext()) { - ScheduleNode gn = (ScheduleNode) it.next(); - Iterator edges = gn.edges(); - output.println("\tsubgraph " + gn.getLabel() + "{"); - output.println("\t\tlabel=\"" + gn.getTextLabel() + "\";"); - Iterator it_cnodes = gn.getClassNodesIterator(); - traverseCNodes(output, it_cnodes); - //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() + "];"); - } - } - } - output.println("\t}\n"); - //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];"); - } - } - } + } + + private static void traverseSNodes(PrintWriter output, Vector sNodes) { + //Draw clusters representing ScheduleNodes + Iterator it = sNodes.iterator(); + while (it.hasNext()) { + ScheduleNode gn = (ScheduleNode) it.next(); + Iterator edges = gn.edges(); + output.println("\tsubgraph " + gn.getLabel() + "{"); + output.println("\t\tlabel=\"" + gn.getTextLabel() + "\";"); + Iterator it_cnodes = gn.getClassNodesIterator(); + traverseCNodes(output, it_cnodes); + //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() + "];"); + } + } + } + output.println("\t}\n"); + //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];"); + } + } } - - private static void traverseCNodes(PrintWriter output, Iterator it){ - //Draw clusters representing ClassNodes - while (it.hasNext()) { - ClassNode gn = (ClassNode) it.next(); - if(gn.isclone()) { - 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"); - } - } + } + + private static void traverseCNodes(PrintWriter output, Iterator it) { + //Draw clusters representing ClassNodes + while (it.hasNext()) { + ClassNode gn = (ClassNode) it.next(); + if(gn.isclone()) { + 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"); + } } - - private static void traverseFlagStates(PrintWriter output, Collection nodes) { - Set cycleset=GraphNode.findcycles(nodes); - Vector namers=new Vector(); - namers.add(new Namer()); - namers.add(new Allocations()); - - Iterator it = nodes.iterator(); - while (it.hasNext()) { - GraphNode gn = (GraphNode) it.next(); - Iterator edges = gn.edges(); - String label = ""; - 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() + "%) }"; } - if (!newparams.equals("")) { - dotnodeparams+=", " + name.nodeOption(gn); - } - label+=name.nodeLabel(gn); + } + output.println("\t" + gn.getLabel() + " -> " + node2.getLabel() + " [" + "label=\"" + edgelabel + "\"" + edgedotnodeparams + "];"); } - label += ":[" + ((FlagState)gn).getExeTime() + "]"; - - if (!gn.merge) - output.println("\t" + gn.getLabel() + " [label=\"" + label + "\"" + dotnodeparams + "];"); - - if (!gn.merge) - while (edges.hasNext()) { - Edge edge = (Edge) edges.next(); - GraphNode node = edge.getTarget(); - if (nodes.contains(node)) { - for(Iterator nodeit=nonmerge(node, nodes).iterator();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() + "%) }"; - } - } - output.println("\t" + gn.getLabel() + " -> " + node2.getLabel() + " [" + "label=\"" + edgelabel + "\"" + edgedotnodeparams + "];"); - } - } - } + } } } + } - private static Set nonmerge(GraphNode gn, Collection nodes) { - HashSet newset=new HashSet(); - 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); - } - } + private static Set nonmerge(GraphNode gn, Collection nodes) { + HashSet newset=new HashSet(); + 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); } - return newset; + } } - - public static void printSimulationResult(String path, int time, int coreNum, Vector checkpoints) { - try { - File file=new File(path); - FileOutputStream dotstream=new FileOutputStream(file,false); - PrintWriter output = new java.io.PrintWriter(dotstream, true); - output.println("digraph simulation{"); - output.print("\t"); - output.println("node [shape=plaintext];"); - output.print("\t"); - output.println("edge [dir=none];"); - output.print("\t"); - output.println("ranksep=.05;"); - output.println(); - output.print("\t"); - int j = 0; - - // the capital line - output.print("{rank=source; \"Time\"; "); - for(j = 0; j < coreNum; j++) { - output.print("\"core " + j + "\"; "); + return newset; + } + + public static void printSimulationResult(String path, int time, int coreNum, Vector checkpoints) { + try { + File file=new File(path); + FileOutputStream dotstream=new FileOutputStream(file,false); + PrintWriter output = new java.io.PrintWriter(dotstream, true); + output.println("digraph simulation{"); + output.print("\t"); + output.println("node [shape=plaintext];"); + output.print("\t"); + output.println("edge [dir=none];"); + output.print("\t"); + output.println("ranksep=.05;"); + output.println(); + output.print("\t"); + int j = 0; + + // the capital line + output.print("{rank=source; \"Time\"; "); + for(j = 0; j < coreNum; j++) { + output.print("\"core " + j + "\"; "); + } + output.println("}"); + // time coordinate nodes + Vector timeNodes = new Vector(); + String[] lastTaskNodes = new String[coreNum]; + String[] lastTasks = new String[coreNum]; + boolean[] isTaskFinish = new boolean[coreNum]; + for(j = 0; j < coreNum; 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.contains(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"); } - output.println("}"); - // time coordinate nodes - Vector timeNodes = new Vector(); - String[] lastTaskNodes = new String[coreNum]; - String[] lastTasks = new String[coreNum]; - boolean[] isTaskFinish = new boolean[coreNum]; - for(j = 0; j < coreNum; j++) { - lastTaskNodes[j] = "first"; - isTaskFinish[j] = true; - lastTasks[j] = ""; + 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; } - 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.contains(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() + ">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() + ">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(";"); - } - } - 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() + ">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() + ">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() + ">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() + "\"]"); - } + break; + } + + case Action.TASKFINISH: { + if(!isfirst) { + tmpLabel.append("\\n"); + } + tmpLabel.append("<" + taction.getTd().getSymbol() + ">finishes;"); + if(!(lastTaskNodes[cNum].equals("first"))) { + if(!(lastTaskNodes[cNum].equals(tmpTaskNode))) { 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("; "); - } - output.println("}"); + 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() + ">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(";"); + } + } + 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() + ">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() + ">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"); } - output.print("\t"); - output.print("\t"); - output.println("\"Time\"->" + timeNodes.elementAt(0) + "[style=invis];"); - for(j = 0; j < time; j++) { - output.print(j + "->"); + tmpLabel.append("<" + taction.getTd().getSymbol() + ">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"); } - output.println(timeNodes.lastElement() + ";"); - output.println("}"); - output.close(); - } catch (Exception e) { - e.printStackTrace(); - System.exit(-1); - } + 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("; "); + } + output.println("}"); + output.print("\t"); + } + output.print("\t"); + output.print("\t"); + output.println("\"Time\"->" + timeNodes.elementAt(0) + "[style=invis];"); + for(j = 0; j < time; j++) { + output.print(j + "->"); + } + output.println(timeNodes.lastElement() + ";"); + output.println("}"); + output.close(); + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); } + } } \ No newline at end of file diff --git a/Robust/src/Analysis/Scheduling/TaskSimulator.java b/Robust/src/Analysis/Scheduling/TaskSimulator.java index 626d42ec..000abfd9 100644 --- a/Robust/src/Analysis/Scheduling/TaskSimulator.java +++ b/Robust/src/Analysis/Scheduling/TaskSimulator.java @@ -15,271 +15,271 @@ import IR.VarDescriptor; import IR.Tree.FlagExpressionNode; public class TaskSimulator { - TaskDescriptor td; - Vector> paraQueues; - Hashtable objVersionTbl; - ExeResult currentRun; - CoreSimulator cs; - boolean finish; - - public class ExeResult { - int finishTime; - Vector newObjs; - int exetype; // 0--normal executing - // 1--abort due to fail on grabbing locks - // 2--out of date task - - public ExeResult() { - finishTime = 0; - newObjs = null; - } - - public int getFinishTime() { - return finishTime; - } - - public void setFinishTime(int finishTime) { - this.finishTime = finishTime; - } - - public Vector getNewObjs() { - return newObjs; - } - - public void addNewObj(ObjectSimulator newObj) { - if(this.newObjs == null) { - this.newObjs = new Vector(); - } - - this.newObjs.add(newObj); - } + TaskDescriptor td; + Vector> paraQueues; + Hashtable objVersionTbl; + ExeResult currentRun; + CoreSimulator cs; + boolean finish; - public int getExetype() { - return exetype; - } + public class ExeResult { + int finishTime; + Vector newObjs; + int exetype; // 0--normal executing + // 1--abort due to fail on grabbing locks + // 2--out of date task - public void setExetype(int exetype) { - this.exetype = exetype; - } + public ExeResult() { + finishTime = 0; + newObjs = null; } - - public TaskSimulator(TaskDescriptor td, CoreSimulator cs) { - super(); - this.td = td; - this.paraQueues = null; - this.objVersionTbl = null; - this.currentRun = null; - this.cs = cs; - this.finish = true; - } - - public CoreSimulator getCs() { - return cs; + + public int getFinishTime() { + return finishTime; } - public TaskDescriptor getTd() { - return td; + public void setFinishTime(int finishTime) { + this.finishTime = finishTime; } - public ExeResult getCurrentRun() { - return currentRun; + public Vector getNewObjs() { + return newObjs; } - public Vector> getParaQueues() { - return paraQueues; + public void addNewObj(ObjectSimulator newObj) { + if(this.newObjs == null) { + this.newObjs = new Vector(); + } + + this.newObjs.add(newObj); } - - public Hashtable getObjVersionTbl() { - return objVersionTbl; + + public int getExetype() { + return exetype; } - - public int getObjVersion(ObjectSimulator os) { - return this.objVersionTbl.get(os).intValue(); + + public void setExetype(int exetype) { + this.exetype = exetype; } + } - public void enquePara(ObjectSimulator obj, FlagState fs, int version, boolean inherent) { - ClassDescriptor cd = obj.getCd(); - int paraNum = td.numParameters(); - 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); - } - } - } - } + public TaskSimulator(TaskDescriptor td, CoreSimulator cs) { + super(); + this.td = td; + this.paraQueues = null; + this.objVersionTbl = null; + this.currentRun = null; + this.cs = cs; + this.finish = true; + } + + public CoreSimulator getCs() { + return cs; + } + + public TaskDescriptor getTd() { + return td; + } + + public ExeResult getCurrentRun() { + return currentRun; + } + + public Vector> getParaQueues() { + return paraQueues; + } + + public Hashtable getObjVersionTbl() { + return objVersionTbl; + } + + public int getObjVersion(ObjectSimulator os) { + return this.objVersionTbl.get(os).intValue(); + } + + public void enquePara(ObjectSimulator obj, FlagState fs, int version, boolean inherent) { + ClassDescriptor cd = obj.getCd(); + int paraNum = td.numParameters(); + 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(); } - } - - public void refreshPara(ObjectSimulator obj, boolean remove) { - ClassDescriptor cd = obj.getCd(); - int paraNum = td.numParameters(); - 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(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); + } + } } + } } + } - public void process() { - if(!finish) { - return; + public void refreshPara(ObjectSimulator obj, boolean remove) { + ClassDescriptor cd = obj.getCd(); + int paraNum = td.numParameters(); + 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 { - finish = false; - } - - if(this.currentRun == null) { - this.currentRun = new ExeResult(); - } - - int finishTime = 0; - // According to runtime statistic information, decide the execution path of this task this time. - // Mainly following things: - // 1.the result, i.e. the result FlagState reached by each parameter. - // 2.the finish time - // 3.any new objects - - // First check if all the parameters are still available. - // For shared objects, need to first grab the lock and also check if the version is right - for(int i = 0; i < paraQueues.size(); i++) { - ObjectSimulator tpara = paraQueues.elementAt(i).peek(); - if(tpara.isShared()) { - if(tpara.isHold()) { - // shared object held by other tasks - finishTime = 1; // TODO currenly assume the effort on requesting locks are only 1 - 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); - } - return; - } else if (tpara.getVersion() != this.objVersionTbl.get(tpara)) { - // shared object has been updated and no longer fitted to this task - finishTime = 1; // TODO currenly assume the effort on requesting locks are only 1 - 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); - } + // 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); + } } - // remove this object from the remaining parameter queues - for(int j = i + 1; j < paraQueues.size(); j++) { - paraQueues.elementAt(j).remove(tpara); + if(this.paraQueues.elementAt(i) == null) { + this.paraQueues.setElementAt(new LinkedList(), i); } - } - for(int i = 0; i < paraQueues.size(); i++) { - ObjectSimulator tpara = paraQueues.elementAt(i).peek(); - - FlagState tfstate = tpara.getCurrentFS(); - FEdge toexecute = tfstate.process(td); - finishTime += toexecute.getExeTime(); - 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(); - } - } - } + 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); } - tpara.applyEdge(toexecute); - tpara.increaseVersion(); + } } - finishTime /= paraQueues.size(); - this.currentRun.setFinishTime(finishTime); - this.currentRun.setExetype(0); + } } - - public void updateFinishTime(int time) { - this.currentRun.setFinishTime(this.currentRun.finishTime - time); - finish = false; + } + + public void process() { + if(!finish) { + return; + } else { + finish = false; } - - public void finish() { - this.finish = true; + + if(this.currentRun == null) { + this.currentRun = new ExeResult(); } + + int finishTime = 0; + // According to runtime statistic information, decide the execution path of this task this time. + // Mainly following things: + // 1.the result, i.e. the result FlagState reached by each parameter. + // 2.the finish time + // 3.any new objects + + // First check if all the parameters are still available. + // For shared objects, need to first grab the lock and also check if the version is right + for(int i = 0; i < paraQueues.size(); i++) { + ObjectSimulator tpara = paraQueues.elementAt(i).peek(); + if(tpara.isShared()) { + if(tpara.isHold()) { + // shared object held by other tasks + finishTime = 1; // TODO currenly assume the effort on requesting locks are only 1 + 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); + } + return; + } else if (tpara.getVersion() != this.objVersionTbl.get(tpara)) { + // shared object has been updated and no longer fitted to this task + finishTime = 1; // TODO currenly assume the effort on requesting locks are only 1 + 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); + } + } + for(int i = 0; i < paraQueues.size(); i++) { + ObjectSimulator tpara = paraQueues.elementAt(i).peek(); + + FlagState tfstate = tpara.getCurrentFS(); + FEdge toexecute = tfstate.process(td); + finishTime += toexecute.getExeTime(); + 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(); + } + } + } + } + tpara.applyEdge(toexecute); + tpara.increaseVersion(); + } + finishTime /= paraQueues.size(); + this.currentRun.setFinishTime(finishTime); + this.currentRun.setExetype(0); + } + + public void updateFinishTime(int time) { + this.currentRun.setFinishTime(this.currentRun.finishTime - time); + finish = false; + } + + public void finish() { + this.finish = true; + } } \ No newline at end of file diff --git a/Robust/src/Analysis/Scheduling/TransTaskSimulator.java b/Robust/src/Analysis/Scheduling/TransTaskSimulator.java index 19bf74cb..66f75a2e 100644 --- a/Robust/src/Analysis/Scheduling/TransTaskSimulator.java +++ b/Robust/src/Analysis/Scheduling/TransTaskSimulator.java @@ -1,38 +1,38 @@ -package Analysis.Scheduling; - -import java.util.Queue; - -public class TransTaskSimulator extends TaskSimulator { - private int targetCoreNum; - private Queue newObjs; - - public TransTaskSimulator(CoreSimulator cs, int targetCoreNum, Queue nobjs) { - super(null, cs); - this.targetCoreNum = targetCoreNum; - this.newObjs = nobjs; - } - - public void process() { - if(this.currentRun == null) { - this.currentRun = new ExeResult(); - } - - this.currentRun.finishTime = 1 * sizeof(this.newObjs.peek().obj.getCd()); - } - - public ObjectInfo refreshTask() { - return this.newObjs.poll(); - } - - private int sizeof(Object obj) { - return 1; - } - - public boolean isFinished() { - return this.newObjs.isEmpty(); - } - - public int getTargetCoreNum() { - return targetCoreNum; - } +package Analysis.Scheduling; + +import java.util.Queue; + +public class TransTaskSimulator extends TaskSimulator { + private int targetCoreNum; + private Queue newObjs; + + public TransTaskSimulator(CoreSimulator cs, int targetCoreNum, Queue nobjs) { + super(null, cs); + this.targetCoreNum = targetCoreNum; + this.newObjs = nobjs; + } + + public void process() { + if(this.currentRun == null) { + this.currentRun = new ExeResult(); + } + + this.currentRun.finishTime = 1 * sizeof(this.newObjs.peek().obj.getCd()); + } + + public ObjectInfo refreshTask() { + return this.newObjs.poll(); + } + + private int sizeof(Object obj) { + return 1; + } + + public boolean isFinished() { + return this.newObjs.isEmpty(); + } + + public int getTargetCoreNum() { + return targetCoreNum; + } } \ No newline at end of file diff --git a/Robust/src/Analysis/TaskStateAnalysis/Allocations.java b/Robust/src/Analysis/TaskStateAnalysis/Allocations.java index 0146dafc..d258f016 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/Allocations.java +++ b/Robust/src/Analysis/TaskStateAnalysis/Allocations.java @@ -2,25 +2,26 @@ package Analysis.TaskStateAnalysis; import Util.*; public class Allocations extends Namer { - public Allocations() {} + public Allocations() { + } - public String nodeLabel(GraphNode gn) { - return ""; - } - - public String nodeOption(GraphNode gn) { - FlagState fs=(FlagState)gn; - if (fs.isSourceNode()) - return "peripheries=2, URL=\"" + fs.getClassDescriptor().toString() + "_" + fs.getLabel() + ".html\""; - else - return ""; - } + public String nodeLabel(GraphNode gn) { + return ""; + } - public String edgeLabel(Edge e) { - return ""; - } + public String nodeOption(GraphNode gn) { + FlagState fs=(FlagState)gn; + if (fs.isSourceNode()) + return "peripheries=2, URL=\"" + fs.getClassDescriptor().toString() + "_" + fs.getLabel() + ".html\""; + else + return ""; + } - public String edgeOption(Edge e) { - return ""; - } + public String edgeLabel(Edge e) { + return ""; + } + + public String edgeOption(Edge e) { + return ""; + } } diff --git a/Robust/src/Analysis/TaskStateAnalysis/EGEdge.java b/Robust/src/Analysis/TaskStateAnalysis/EGEdge.java index 12254037..0dd3984a 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/EGEdge.java +++ b/Robust/src/Analysis/TaskStateAnalysis/EGEdge.java @@ -3,18 +3,18 @@ import java.util.*; import Util.Edge; -public class EGEdge extends Edge{ - FlagState fs; - public EGEdge(FlagState fs, EGTaskNode target){ - super(target); - this.fs=fs; - } +public class EGEdge extends Edge { + FlagState fs; + public EGEdge(FlagState fs, EGTaskNode target) { + super(target); + this.fs=fs; + } - public FlagState getFS() { - return fs; - } + public FlagState getFS() { + return fs; + } - public EGTaskNode getTarget(){ - return (EGTaskNode) target; - } + public EGTaskNode getTarget() { + return (EGTaskNode) target; + } } diff --git a/Robust/src/Analysis/TaskStateAnalysis/EGTaskNode.java b/Robust/src/Analysis/TaskStateAnalysis/EGTaskNode.java index 169e52a4..7d1fe494 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/EGTaskNode.java +++ b/Robust/src/Analysis/TaskStateAnalysis/EGTaskNode.java @@ -7,90 +7,90 @@ import java.util.*; import Util.GraphNode; public class EGTaskNode extends GraphNode { - private boolean source=false; - private FlagState fs; - private FlagState postfs; - private TaskDescriptor td; - private int index; - private String name; - private int uid; - private static int nodeid; - - public EGTaskNode(String name, TaskDescriptor td, FlagState postfs){ - this(name, null, td, -1, postfs); - } - - public EGTaskNode(String name, FlagState fs, TaskDescriptor td, int index, FlagState postfs){ - this.name=name; - this.uid=nodeid++; - this.fs = fs; - this.td = td; - this.index=index; - this.postfs=postfs; - } - - public String getTextLabel() { - return "Task "+getName()+"["+fs+"]->["+postfs+"]"; - } - - public String getName() { - return name; - } - - public String getLabel() { - return "N"+uid; - } - - public int getIndex() { - return index; - } - - public String toString() { - return getTextLabel(); - } - - public FlagState getPostFS() { - return postfs; - } - - public boolean isRuntime() { - return td==null&&getName().equals("Runtime"); - } - - - public boolean isOptional() { - return (!isSource()&&td!=null&&td.isOptional(td.getParameter(index))); - } - - - public TaskDescriptor getTD(){ - return td; - } - - public void setSource(){ - source = true; - } - - public boolean isSource(){ - return source; - } - - public int getuid(){ - return uid; - } - - public boolean isMultipleParams(){ - return getTD()!=null&&getTD().numParameters()>1; - } - - public String getFSName(){ - if(fs == null) - return "no flag"; - else - return fs.getTextLabel(); - } - - public FlagState getFS(){ - return fs; - } + private boolean source=false; + private FlagState fs; + private FlagState postfs; + private TaskDescriptor td; + private int index; + private String name; + private int uid; + private static int nodeid; + + public EGTaskNode(String name, TaskDescriptor td, FlagState postfs) { + this(name, null, td, -1, postfs); + } + + public EGTaskNode(String name, FlagState fs, TaskDescriptor td, int index, FlagState postfs) { + this.name=name; + this.uid=nodeid++; + this.fs = fs; + this.td = td; + this.index=index; + this.postfs=postfs; + } + + public String getTextLabel() { + return "Task "+getName()+"["+fs+"]->["+postfs+"]"; + } + + public String getName() { + return name; + } + + public String getLabel() { + return "N"+uid; + } + + public int getIndex() { + return index; + } + + public String toString() { + return getTextLabel(); + } + + public FlagState getPostFS() { + return postfs; + } + + public boolean isRuntime() { + return td==null&&getName().equals("Runtime"); + } + + + public boolean isOptional() { + return (!isSource()&&td!=null&&td.isOptional(td.getParameter(index))); + } + + + public TaskDescriptor getTD() { + return td; + } + + public void setSource() { + source = true; + } + + public boolean isSource() { + return source; + } + + public int getuid() { + return uid; + } + + public boolean isMultipleParams() { + return getTD()!=null&&getTD().numParameters()>1; + } + + public String getFSName() { + if(fs == null) + return "no flag"; + else + return fs.getTextLabel(); + } + + public FlagState getFS() { + return fs; + } } diff --git a/Robust/src/Analysis/TaskStateAnalysis/ExecutionGraph.java b/Robust/src/Analysis/TaskStateAnalysis/ExecutionGraph.java index 9046e2d7..36be0eb4 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/ExecutionGraph.java +++ b/Robust/src/Analysis/TaskStateAnalysis/ExecutionGraph.java @@ -10,133 +10,133 @@ import java.io.FileOutputStream; import Util.Edge; public class ExecutionGraph { - private TaskAnalysis taskanalysis; - private State state; - private Hashtable executiongraph; - private HashSet marked; - private HashSet processed; - - public ExecutionGraph(State state, TaskAnalysis ta){ - this.taskanalysis=ta; - this.state=state; - this.executiongraph = new Hashtable(); - this.marked=new HashSet(); - this.processed=new HashSet(); - } + private TaskAnalysis taskanalysis; + private State state; + private Hashtable executiongraph; + private HashSet marked; + private HashSet processed; + + public ExecutionGraph(State state, TaskAnalysis ta) { + this.taskanalysis=ta; + this.state=state; + this.executiongraph = new Hashtable(); + this.marked=new HashSet(); + this.processed=new HashSet(); + } + + public Hashtable getExecutionGraph() { + return executiongraph; + } - public Hashtable getExecutionGraph(){ - return executiongraph; + public void createExecutionGraph() throws java.io.IOException { + //Cycle through classes + Enumeration e=taskanalysis.flagstates.keys(); + + while (e.hasMoreElements()) { + ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement(); + HashSet graph=exploreGraph(cdtemp); + adapt(cdtemp,graph); } - - public void createExecutionGraph() throws java.io.IOException { - //Cycle through classes - Enumeration e=taskanalysis.flagstates.keys(); - - while (e.hasMoreElements()) { - ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement(); - HashSet graph=exploreGraph(cdtemp); - adapt(cdtemp,graph); + printDOTFile(); + } + + private HashSet exploreGraph(ClassDescriptor cd) { + LinkedList fifo = new LinkedList(); + HashSet nodes=new HashSet(); + Hashtable map=new Hashtable(); + + // Go through nodes + Iterator it = taskanalysis.getFlagStates(cd).iterator(); + 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); + } } - printDOTFile(); - } - - private HashSet exploreGraph(ClassDescriptor cd) { - LinkedList fifo = new LinkedList(); - HashSet nodes=new HashSet(); - Hashtable map=new Hashtable(); - - // Go through nodes - Iterator it = taskanalysis.getFlagStates(cd).iterator(); - 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 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); - } - } - - } - return nodes; - } - - private EGTaskNode getNode(FEdge fedge, Hashtable map, HashSet nodes) { - if (map.containsKey(fedge)) - return map.get(fedge); - EGTaskNode egnode=new EGTaskNode(fedge.getLabel(), (FlagState) fedge.getSource(), fedge.getTask(), fedge.getIndex(), (FlagState) fedge.getTarget()); - map.put(fedge, egnode); - nodes.add(egnode); - return egnode; - } + } + 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); + } + } - //put the graph into executiongraph - private void adapt(ClassDescriptor cd, HashSet nodes) { - HashSet tasknodes = new HashSet(); - tasknodes.addAll(nodes); - executiongraph.put(cd,tasknodes); } + return nodes; + } - //print the contain of graph - private void test(Hashtable graph) { - System.out.println("\nGraph contains :"); - Collection c = graph.values(); - for ( Iterator it = c.iterator(); it.hasNext();){ - EGTaskNode tn = (EGTaskNode)it.next(); - System.out.println(tn.getTextLabel()+" ID "+tn.getLabel()+" FS "+tn.getFSName()); - } + private EGTaskNode getNode(FEdge fedge, Hashtable map, HashSet nodes) { + if (map.containsKey(fedge)) + return map.get(fedge); + EGTaskNode egnode=new EGTaskNode(fedge.getLabel(), (FlagState) fedge.getSource(), fedge.getTask(), fedge.getIndex(), (FlagState) fedge.getTarget()); + map.put(fedge, egnode); + nodes.add(egnode); + return egnode; + } + + //put the graph into executiongraph + private void adapt(ClassDescriptor cd, HashSet nodes) { + HashSet tasknodes = new HashSet(); + tasknodes.addAll(nodes); + executiongraph.put(cd,tasknodes); + } + + //print the contain of graph + private void test(Hashtable graph) { + System.out.println("\nGraph contains :"); + Collection c = graph.values(); + for ( Iterator it = c.iterator(); it.hasNext();){ + EGTaskNode tn = (EGTaskNode)it.next(); + System.out.println(tn.getTextLabel()+" ID "+tn.getLabel()+" FS "+tn.getFSName()); } - - //create dot files execution_classname_.dot - private void printDOTFile()throws java.io.IOException { - Enumeration e = executiongraph.keys(); - while (e.hasMoreElements()){ - createDOTFile((ClassDescriptor)e.nextElement()); - } - } - - private void createDOTFile(ClassDescriptor cd) throws java.io.IOException { - Set s = (Set)executiongraph.get(cd); - java.io.PrintWriter output; - File dotfile_flagstates= new File("execution"+cd.getSymbol()+".dot"); - FileOutputStream dotstream=new FileOutputStream(dotfile_flagstates,false); - output = new java.io.PrintWriter(dotstream, true); - output.println("digraph dotvisitor {"); - output.println("\tnode [fontsize=10,height=\"0.1\", width=\"0.1\"];"); - output.println("\tedge [fontsize=6];"); - traverse(output, s); - output.println("}\n"); + } + + //create dot files execution_classname_.dot + private void printDOTFile() throws java.io.IOException { + Enumeration e = executiongraph.keys(); + while (e.hasMoreElements()){ + createDOTFile((ClassDescriptor)e.nextElement()); } - - private void traverse(java.io.PrintWriter output, Set v) { - EGTaskNode tn; - - for(Iterator it1 = v.iterator(); it1.hasNext();){ - tn = (EGTaskNode)it1.next(); - output.println("\t"+tn.getLabel()+" [label=\""+tn.getTextLabel()+"\""); - if (tn.isMultipleParams()) output.println(", color=blue"); - output.println("];"); - - for(Iterator it2 = tn.edges();it2.hasNext();){ - output.println("\t"+tn.getLabel()+" -> "+((EGTaskNode)((EGEdge)it2.next()).getTarget()).getLabel()+";"); - } - } + } + + private void createDOTFile(ClassDescriptor cd) throws java.io.IOException { + Set s = (Set)executiongraph.get(cd); + java.io.PrintWriter output; + File dotfile_flagstates= new File("execution"+cd.getSymbol()+".dot"); + FileOutputStream dotstream=new FileOutputStream(dotfile_flagstates,false); + output = new java.io.PrintWriter(dotstream, true); + output.println("digraph dotvisitor {"); + output.println("\tnode [fontsize=10,height=\"0.1\", width=\"0.1\"];"); + output.println("\tedge [fontsize=6];"); + traverse(output, s); + output.println("}\n"); + } + + private void traverse(java.io.PrintWriter output, Set v) { + EGTaskNode tn; + + for(Iterator it1 = v.iterator(); it1.hasNext();){ + tn = (EGTaskNode)it1.next(); + output.println("\t"+tn.getLabel()+" [label=\""+tn.getTextLabel()+"\""); + if (tn.isMultipleParams()) output.println(", color=blue"); + output.println("];"); + + for(Iterator it2 = tn.edges(); it2.hasNext();){ + 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 d91f921a..4b589b54 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/FEdge.java +++ b/Robust/src/Analysis/TaskStateAnalysis/FEdge.java @@ -10,188 +10,188 @@ import Util.Edge; public class FEdge extends Edge { - private String label; - private TaskDescriptor td; - private int parameterindex; - - // jzhou - private int executeTime; - private Hashtable newObjInfos; - private int probability; - private int invokeNum; - private int expInvokeNum; - - public class NewObjInfo { - int newRate; - int probability; - FlagState root; - int invokeNum; - - public NewObjInfo() { - newRate = 0; - probability = 0; - root = null; - invokeNum = 0; - } - - public NewObjInfo(int newRate, int probability) { - this.newRate = newRate; - this.probability = probability; - } - - public int getNewRate() { - return this.newRate; - } - - public void setNewRate(int newRate) { - this.newRate = newRate; - } - - public int getProbability() { - return this.probability; - } - - public void setProbability(int probability) { - this.probability = probability; - } - - public FlagState getRoot() { - return root; - } + private String label; + private TaskDescriptor td; + private int parameterindex; - public void setRoot(FlagState root) { - this.root = root; - } + // jzhou + private int executeTime; + private Hashtable newObjInfos; + private int probability; + private int invokeNum; + private int expInvokeNum; - public int getInvokeNum() { - return invokeNum; - } + public class NewObjInfo { + int newRate; + int probability; + FlagState root; + int invokeNum; - public void incInvokeNum() { - this.invokeNum++; - } + public NewObjInfo() { + newRate = 0; + probability = 0; + root = null; + invokeNum = 0; + } - 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; - } - } - return false; - } + public NewObjInfo(int newRate, int probability) { + this.newRate = newRate; + this.probability = probability; } - - /** Class Constructor - * - */ - public FEdge(FlagState target, String label, TaskDescriptor td, int parameterindex) { - super(target); - this.label = label; - this.td=td; - this.parameterindex=parameterindex; - this.executeTime = -1; - this.newObjInfos = null; - this.probability = -1; - this.invokeNum = 0; - this.expInvokeNum = 0; + + public int getNewRate() { + return this.newRate; + } + + public void setNewRate(int newRate) { + this.newRate = newRate; } public int getProbability() { - return probability; + return this.probability; } public void setProbability(int probability) { - this.probability = probability; + this.probability = probability; } - public String getLabel() { - return label; + public FlagState getRoot() { + return root; } - - public int hashCode(){ - int hashcode = label.hashCode()^target.hashCode()^source.hashCode()^parameterindex^executeTime; - if (td!=null) - hashcode^=td.hashCode(); - if(newObjInfos != null) { - hashcode ^= newObjInfos.hashCode(); - } - return hashcode; + + public void setRoot(FlagState root) { + this.root = root; } - public TaskDescriptor getTask() { - return td; + public int getInvokeNum() { + return invokeNum; } - public int getIndex() { - return parameterindex; + public void incInvokeNum() { + this.invokeNum++; } - + public boolean equals(Object o) { - if (o instanceof FEdge) { - FEdge e=(FEdge)o; - if (e.label.equals(label)&& - e.target.equals(target)&& - e.source.equals(source) && - e.td==td&& - e.parameterindex==parameterindex && - e.executeTime == executeTime) { - if(this.newObjInfos != null) { - if(e.newObjInfos == null) { - return false; - } else { - return e.newObjInfos.equals(this.newObjInfos); - } - } - return true; - } - } - return false; - } - - public int getExeTime() { - return this.executeTime; - } - - public void setExeTime(int eTime) { - this.executeTime = eTime; - } - - public Hashtable getNewObjInfoHashtable() { - return this.newObjInfos; - } - - public NewObjInfo getNewObjInfo(ClassDescriptor cd) { - if(this.newObjInfos == null) { - return null; - } - return this.newObjInfos.get(cd); - } - - public void addNewObjInfo(ClassDescriptor cd, int newRate, int probability) { - if(this.newObjInfos == null) { - this.newObjInfos = new Hashtable(); - } - this.newObjInfos.put(cd, new NewObjInfo(newRate, probability)); - } - - public void process() { - this.invokeNum++; + 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; + } + } + return false; } + } - public int getInvokeNum() { - return invokeNum; + /** Class Constructor + * + */ + public FEdge(FlagState target, String label, TaskDescriptor td, int parameterindex) { + super(target); + this.label = label; + this.td=td; + this.parameterindex=parameterindex; + this.executeTime = -1; + this.newObjInfos = null; + this.probability = -1; + this.invokeNum = 0; + this.expInvokeNum = 0; + } + + public int getProbability() { + return probability; + } + + public void setProbability(int probability) { + this.probability = probability; + } + + public String getLabel() { + return label; + } + + public int hashCode() { + int hashcode = label.hashCode()^target.hashCode()^source.hashCode()^parameterindex^executeTime; + if (td!=null) + hashcode^=td.hashCode(); + if(newObjInfos != null) { + hashcode ^= newObjInfos.hashCode(); + } + return hashcode; + } + + public TaskDescriptor getTask() { + return td; + } + + public int getIndex() { + return parameterindex; + } + + public boolean equals(Object o) { + if (o instanceof FEdge) { + FEdge e=(FEdge)o; + if (e.label.equals(label)&& + e.target.equals(target)&& + e.source.equals(source) && + e.td==td&& + e.parameterindex==parameterindex && + e.executeTime == executeTime) { + if(this.newObjInfos != null) { + if(e.newObjInfos == null) { + return false; + } else { + return e.newObjInfos.equals(this.newObjInfos); + } + } + return true; + } } + return false; + } + + public int getExeTime() { + return this.executeTime; + } + + public void setExeTime(int eTime) { + this.executeTime = eTime; + } - public int getInvokeNumGap() { - return expInvokeNum - invokeNum; + public Hashtable getNewObjInfoHashtable() { + return this.newObjInfos; + } + + public NewObjInfo getNewObjInfo(ClassDescriptor cd) { + if(this.newObjInfos == null) { + return null; } + return this.newObjInfos.get(cd); + } - public void setExpInvokeNum(int expInvokeNum) { - this.expInvokeNum = expInvokeNum; + public void addNewObjInfo(ClassDescriptor cd, int newRate, int probability) { + if(this.newObjInfos == null) { + this.newObjInfos = new Hashtable(); } - + this.newObjInfos.put(cd, new NewObjInfo(newRate, probability)); + } + + public void process() { + this.invokeNum++; + } + + public int getInvokeNum() { + return invokeNum; + } + + public int getInvokeNumGap() { + return expInvokeNum - invokeNum; + } + + public void setExpInvokeNum(int expInvokeNum) { + this.expInvokeNum = expInvokeNum; + } + } diff --git a/Robust/src/Analysis/TaskStateAnalysis/FlagComparator.java b/Robust/src/Analysis/TaskStateAnalysis/FlagComparator.java index 1519d975..66971e18 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/FlagComparator.java +++ b/Robust/src/Analysis/TaskStateAnalysis/FlagComparator.java @@ -7,24 +7,24 @@ import IR.FlagDescriptor; /**Note: this comparator imposes orderings that are inconsistent with equals.*/ public class FlagComparator implements Comparator { - Hashtable flaginfo; - public FlagComparator(Hashtable flaginfo) { - this.flaginfo=flaginfo; - } + Hashtable flaginfo; + public FlagComparator(Hashtable flaginfo) { + this.flaginfo=flaginfo; + } - public int compare(Object o1, Object o2) { - int fs1=getFlagInt((FlagState)o1); - int fs2=getFlagInt((FlagState)o2); - return fs1-fs2; - } - - public int getFlagInt(FlagState fs) { - 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; - } - return flagid; + public int compare(Object o1, Object o2) { + int fs1=getFlagInt((FlagState)o1); + int fs2=getFlagInt((FlagState)o2); + return fs1-fs2; + } + + public int getFlagInt(FlagState fs) { + 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; } + return flagid; + } } diff --git a/Robust/src/Analysis/TaskStateAnalysis/FlagInfo.java b/Robust/src/Analysis/TaskStateAnalysis/FlagInfo.java index ecdb162f..71f9c01f 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/FlagInfo.java +++ b/Robust/src/Analysis/TaskStateAnalysis/FlagInfo.java @@ -9,44 +9,44 @@ import java.io.FileOutputStream; public class FlagInfo { - private Hashtable flags; - private State state; + private Hashtable flags; + private State state; - public FlagInfo(State state) { - this.state=state; - flags=new Hashtable(); - getFlagsfromClasses(); - } + public FlagInfo(State state) { + this.state=state; + flags=new Hashtable(); + getFlagsfromClasses(); + } - public FlagDescriptor[] getFlags(ClassDescriptor cd) { - return flags.get(cd); - } + public FlagDescriptor[] getFlags(ClassDescriptor cd) { + return flags.get(cd); + } + + /** Builds a table of flags for each class in the Bristlecone + * program. It creates one hashtables: one which holds the + * ClassDescriptors and arrays of * FlagDescriptors as key-value + * pairs. */ - /** Builds a table of flags for each class in the Bristlecone - * program. It creates one hashtables: one which holds the - * ClassDescriptors and arrays of * FlagDescriptors as key-value - * pairs. */ - - private void getFlagsfromClasses() { - for(Iterator it_classes=state.getClassSymbolTable().getDescriptorsIterator();it_classes.hasNext();) { - ClassDescriptor cd = (ClassDescriptor)it_classes.next(); - Vector vFlags=new Vector(); - FlagDescriptor flag[]; - int ctr=0; - - /* 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(); - } - - flag=new FlagDescriptor[vFlags.size()]; - - flags.put(cd,flag); + private void getFlagsfromClasses() { + for(Iterator it_classes=state.getClassSymbolTable().getDescriptorsIterator(); it_classes.hasNext();) { + ClassDescriptor cd = (ClassDescriptor)it_classes.next(); + Vector vFlags=new Vector(); + FlagDescriptor flag[]; + int ctr=0; + + /* 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(); + } + + flag=new FlagDescriptor[vFlags.size()]; + + flags.put(cd,flag); } + } } \ No newline at end of file diff --git a/Robust/src/Analysis/TaskStateAnalysis/FlagState.java b/Robust/src/Analysis/TaskStateAnalysis/FlagState.java index 4572dd50..9c975eb8 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/FlagState.java +++ b/Robust/src/Analysis/TaskStateAnalysis/FlagState.java @@ -9,464 +9,468 @@ import java.util.*; import java.io.*; import Util.GraphNode; -/** This class is used to hold the flag states that a class in the Bristlecone +/** This class is used to hold the flag states that a class in the Bristlecone * program can exist in, during runtime. */ public class FlagState extends GraphNode implements Cloneable { - public static final int ONETAG=1; - public static final int NOTAGS=0; - public static final int MULTITAGS=-1; - public static final int MAXTIME=10; - - private int uid; - private static int nodeid=0; - - private final HashSet flagstate; - private final ClassDescriptor cd; - private final Hashtable tags; - private boolean issourcenode; - private Vector tasks; - public static final int KLIMIT=2; - - // jzhou - // for static scheduling - private int executeTime; - private int visited4time; - private int invokeNum; - // for building multicore codes - private int andmask; - private int checkmask; - private boolean setmask; - private int iuid; - //private boolean isolate; - //private Vector allys; - - /** Class constructor - * Creates a new flagstate with all flags set to false. - * @param cd ClassDescriptor - */ - public FlagState(ClassDescriptor cd) { - this.flagstate=new HashSet(); - this.cd=cd; - this.tags=new Hashtable(); - this.uid=FlagState.nodeid++; - this.issourcenode=false; - this.executeTime = -1; - this.visited4time = -1; - this.invokeNum = 0; - this.andmask = 0; - this.checkmask = 0; - this.setmask = false; - this.iuid = 0; - //this.isolate = true; - //this.allys = null; - } + public static final int ONETAG=1; + public static final int NOTAGS=0; + public static final int MULTITAGS=-1; + public static final int MAXTIME=10; - /** Class constructor - * Creates a new flagstate with flags set according to the HashSet. - * If the flag exists in the hashset, it's set to true else set to false. - * @param cd ClassDescriptor - * @param flagstate a HashSet containing FlagDescriptors - */ - private FlagState(HashSet flagstate, ClassDescriptor cd,Hashtable tags) { - this.flagstate=flagstate; - this.cd=cd; - this.tags=tags; - this.uid=FlagState.nodeid++; - this.issourcenode=false; - this.executeTime = -1; - this.visited4time = -1; - this.invokeNum = 0; - } - - public int getuid() { - return uid; - } - - public int getiuid() { - return iuid++; - } + private int uid; + private static int nodeid=0; - public boolean isSetmask() { - return setmask; - } + private final HashSet flagstate; + private final ClassDescriptor cd; + private final Hashtable tags; + private boolean issourcenode; + private Vector tasks; + public static final int KLIMIT=2; - public void setSetmask(boolean setmask) { - this.setmask = setmask; - } + // jzhou + // for static scheduling + private int executeTime; + private int visited4time; + private int invokeNum; + // for building multicore codes + private int andmask; + private int checkmask; + private boolean setmask; + private int iuid; + //private boolean isolate; + //private Vector allys; - /** Accessor method - * @param fd FlagDescriptor - * @return true if the flagstate contains fd else false. - */ - public boolean get(FlagDescriptor fd) { - return flagstate.contains(fd); - } - - /** Checks if the flagstate is a source node. - * @return true if the flagstate is a sourcenode(i.e. Is the product of an allocation site). - */ - - public boolean isSourceNode(){ - return issourcenode; - } - - /** Sets the flagstate as a source node. - */ - public void setAsSourceNode(){ - if(!issourcenode){ - issourcenode=true; - this.tasks=new Vector(); - } - } - - public void addAllocatingTask(TaskDescriptor task){ - tasks.add(task); - } - - public Vector getAllocatingTasks(){ - return tasks; - } - - - public String toString() { - return cd.toString()+getTextLabel(); - } + /** Class constructor + * Creates a new flagstate with all flags set to false. + * @param cd ClassDescriptor + */ + public FlagState(ClassDescriptor cd) { + this.flagstate=new HashSet(); + this.cd=cd; + this.tags=new Hashtable(); + this.uid=FlagState.nodeid++; + this.issourcenode=false; + this.executeTime = -1; + this.visited4time = -1; + this.invokeNum = 0; + this.andmask = 0; + this.checkmask = 0; + this.setmask = false; + this.iuid = 0; + //this.isolate = true; + //this.allys = null; + } - /** @return Iterator over the flags in the flagstate. - */ - - public Iterator getFlags() { - return flagstate.iterator(); - } + /** Class constructor + * Creates a new flagstate with flags set according to the HashSet. + * If the flag exists in the hashset, it's set to true else set to false. + * @param cd ClassDescriptor + * @param flagstate a HashSet containing FlagDescriptors + */ + private FlagState(HashSet flagstate, ClassDescriptor cd,Hashtable tags) { + this.flagstate=flagstate; + this.cd=cd; + this.tags=tags; + this.uid=FlagState.nodeid++; + this.issourcenode=false; + this.executeTime = -1; + this.visited4time = -1; + this.invokeNum = 0; + } - public int numFlags(){ - return flagstate.size(); - } - - public FlagState[] setTag(TagDescriptor tag, boolean set){ - HashSet newset1=(HashSet)flagstate.clone(); - Hashtable newtags1=(Hashtable)tags.clone(); - - if (set) { - int count=0; - if (tags.containsKey(tag)) - count=tags.get(tag).intValue(); - if (count newtags1=(Hashtable)tags.clone(); + + if (set) { + int count=0; + if (tags.containsKey(tag)) + count=tags.get(tag).intValue(); + if (count newtags1=(Hashtable)tags.clone(); + + if (tags.containsKey(tag)){ + //Code could try to remove flag that doesn't exist + + switch (tags.get(tag).intValue()){ + case ONETAG: + newtags1.put(tag,new Integer(MULTITAGS)); + return new FlagState[] {this, new FlagState(newset1, cd, newtags1)}; + + case MULTITAGS: + return new FlagState[] {this}; + + default: + throw new Error(); + } + } else { + newtags1.put(tag,new Integer(ONETAG)); + return new FlagState[] {new FlagState(newset1,cd,newtags1)}; + } + } + + public int getTagCount(TagDescriptor tag) { + if (tags.containsKey(tag)) + return tags.get(tag).intValue(); + else return 0; + } + + public int getTagCount(String tagtype) { + return getTagCount(new TagDescriptor(tagtype)); + } + + public FlagState[] clearTag(TagDescriptor tag) { + if (tags.containsKey(tag)){ + switch(tags.get(tag).intValue()){ + case ONETAG: + 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(); - - if (tags.containsKey(tag)){ - //Code could try to remove flag that doesn't exist - - switch (tags.get(tag).intValue()){ - case ONETAG: - newtags1.put(tag,new Integer(MULTITAGS)); - return new FlagState[] {this, new FlagState(newset1, cd, newtags1)}; - case MULTITAGS: - return new FlagState[] {this}; - default: - throw new Error(); - } - } else { - newtags1.put(tag,new Integer(ONETAG)); - return new FlagState[] {new FlagState(newset1,cd,newtags1)}; - } - } - public int getTagCount(TagDescriptor tag) { - if (tags.containsKey(tag)) - return tags.get(tag).intValue(); - else return 0; - } + //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)}; - public int getTagCount(String tagtype){ - return getTagCount(new TagDescriptor(tagtype)); + default: + throw new Error(); + } + } else { + throw new Error("Invalid Operation: Can not clear a tag that doesn't exist."); } - - public FlagState[] clearTag(TagDescriptor tag){ - if (tags.containsKey(tag)){ - switch(tags.get(tag).intValue()){ - case ONETAG: - 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)}; - default: - throw new Error(); - } - } else { - throw new Error("Invalid Operation: Can not clear a tag that doesn't exist."); - } - } - - /** Creates a string description of the flagstate - * e.g. a flagstate with five flags could look like 01001 - * @param flags an array of flagdescriptors. - * @return string representation of the flagstate. - */ - public String toString(FlagDescriptor[] flags) + } + + /** Creates a string description of the flagstate + * e.g. a flagstate with five flags could look like 01001 + * @param flags an array of flagdescriptors. + * @return string representation of the flagstate. + */ + public String toString(FlagDescriptor[] flags) { + StringBuffer sb = new StringBuffer(flagstate.size()); + for(int i=0; i < flags.length; i++) { - StringBuffer sb = new StringBuffer(flagstate.size()); - for(int i=0;i < flags.length; i++) - { - if (get(flags[i])) - sb.append(1); - else - sb.append(0); - } - - return new String(sb); - } - - /** Accessor method - * @return returns the classdescriptor of the flagstate. - */ - - public ClassDescriptor getClassDescriptor(){ - return cd; + if (get(flags[i])) + sb.append(1); + else + sb.append(0); } - /** Sets the status of a specific flag in a flagstate after cloning it. - * @param fd FlagDescriptor of the flag whose status is being set. - * @param status boolean value - * @return the new flagstate with fd set to status. - */ - - public FlagState setFlag(FlagDescriptor fd, boolean status) { - HashSet newset=(HashSet) flagstate.clone(); - Hashtable newtags=(Hashtable)tags.clone(); - if (status) - newset.add(fd); - else if (newset.contains(fd)){ - newset.remove(fd); - } - - return new FlagState(newset, cd, newtags); - } - - /** Tests for equality of two flagstate objects. - */ - - public boolean equals(Object o) { - if (o instanceof FlagState) { - FlagState fs=(FlagState)o; - if (fs.cd!=cd) - return false; - return (fs.flagstate.equals(flagstate) & fs.tags.equals(tags)); - } - return false; - } + return new String(sb); + } - public int hashCode() { - return cd.hashCode()^flagstate.hashCode()^tags.hashCode(); - } + /** Accessor method + * @return returns the classdescriptor of the flagstate. + */ - public String getLabel() { - return "N"+uid; + public ClassDescriptor getClassDescriptor() { + return cd; + } + + /** Sets the status of a specific flag in a flagstate after cloning it. + * @param fd FlagDescriptor of the flag whose status is being set. + * @param status boolean value + * @return the new flagstate with fd set to status. + */ + + public FlagState setFlag(FlagDescriptor fd, boolean status) { + HashSet newset=(HashSet) flagstate.clone(); + Hashtable newtags=(Hashtable)tags.clone(); + if (status) + newset.add(fd); + else if (newset.contains(fd)){ + newset.remove(fd); } - - public String getTextLabel() { - String label=null; - for(Iterator it=getFlags();it.hasNext();) { - FlagDescriptor fd=(FlagDescriptor) it.next(); - if (label==null) - label=fd.toString(); - else - 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; - case MULTITAGS: - if (label==null) - label=td.toString()+"(n)"; - else - label+=", "+td.toString()+"(n)"; - break; - default: - break; - } - } + + return new FlagState(newset, cd, newtags); + } + + /** Tests for equality of two flagstate objects. + */ + + public boolean equals(Object o) { + if (o instanceof FlagState) { + FlagState fs=(FlagState)o; + if (fs.cd!=cd) + return false; + return (fs.flagstate.equals(flagstate) & fs.tags.equals(tags)); + } + return false; + } + + public int hashCode() { + return cd.hashCode()^flagstate.hashCode()^tags.hashCode(); + } + + public String getLabel() { + return "N"+uid; + } + + public String getTextLabel() { + String label=null; + for(Iterator it=getFlags(); it.hasNext();) { + FlagDescriptor fd=(FlagDescriptor) it.next(); + if (label==null) + label=fd.toString(); + else + 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) - return " "; - return label; - } - - public Enumeration getTags(){ - return tags.keys(); - } - - public int 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; - } - } - } catch (Exception e) { - e.printStackTrace(); - System.exit(0); - } - return this.executeTime; - } - - public void setExeTime(int exeTime) { - this.executeTime = exeTime; - } - - public int getAndmask() { - return andmask; - } + label=td.toString()+"(1)"; + else + label+=", "+td.toString()+"(1)"; + break; - public void setAndmask(int andmask) { - this.andmask = andmask; - } + case MULTITAGS: + if (label==null) + label=td.toString()+"(n)"; + else + label+=", "+td.toString()+"(n)"; + break; - public int getCheckmask() { - return checkmask; - } + default: + break; + } + } + if (label==null) + return " "; + return label; + } - public void setCheckmask(int checkmask) { - this.checkmask = checkmask; - } + public Enumeration getTags() { + return tags.keys(); + } - public void calExeTime() throws Exception { - Iterator it = this.edges(); - 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(fe == null) { - this.executeTime = 0; - } else { - if(fe.getExeTime() == -1) { - throw new Exception("Error: Uninitiate FEdge!"); - } - this.executeTime = fe.getExeTime() + ((FlagState)fe.getTarget()).getExeTime(); - } - } else { - this.executeTime = 0; - } - while(it.hasNext()) { - FEdge fe = (FEdge)it.next(); - int temp = fe.getExeTime() + ((FlagState)fe.getTarget()).getExeTime(); - if(temp < this.executeTime) { - this.executeTime = temp; - } - } - } - - public Object clone() { - FlagState o = null; - try { - o = (FlagState)super.clone(); - } catch(CloneNotSupportedException e){ - e.printStackTrace(); - } - o.uid = FlagState.nodeid++; - o.edges = new Vector(); - for(int i = 0; i < this.edges.size(); i++) { - o.edges.addElement(this.edges.elementAt(i)); - } - o.inedges = new Vector(); - for(int i = 0; i < this.inedges.size(); i++) { - o.inedges.addElement(this.inedges.elementAt(i)); - } - return o; - } - - public void init4Simulate() { - this.invokeNum = 0; - } - - public FEdge process(TaskDescriptor td) { - FEdge next = null; - this.invokeNum++; - // refresh all the expInvokeNum of each edge - for(int i = 0; i < this.edges.size(); i++) { - next = (FEdge)this.edges.elementAt(i); - next.setExpInvokeNum((int)Math.round(this.invokeNum * (next.getProbability() / 100))); - } - - // find the one with the biggest gap between its actual invoke time and the expected invoke time - // and associated with task td - int index = 0; - int gap = 0; - for(int i = 0; i < this.edges.size(); i++) { - int temp = ((FEdge)this.edges.elementAt(index)).getInvokeNumGap(); - if((temp > gap) && (next.getTask().equals(td))){ - index = i; - gap = temp; - } + public int 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; } - next = (FEdge)this.edges.elementAt(index); - next.process(); - - return next; + } + } catch (Exception e) { + e.printStackTrace(); + System.exit(0); } + return this.executeTime; + } - /*public Vector getAllys() { - return allys; - } + public void setExeTime(int exeTime) { + this.executeTime = exeTime; + } + + public int getAndmask() { + return andmask; + } + + public void setAndmask(int andmask) { + this.andmask = andmask; + } - public void addAlly(ScheduleEdge se) { - if(this.allys == null) { - assert(this.isolate == true); - this.isolate = false; - this.allys = new Vector(); + public int getCheckmask() { + return checkmask; + } + + public void setCheckmask(int checkmask) { + this.checkmask = checkmask; + } + + public void calExeTime() throws Exception { + Iterator it = this.edges(); + 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; } - this.allys.addElement(se); + } + if(fe == null) { + this.executeTime = 0; + } else { + if(fe.getExeTime() == -1) { + throw new Exception("Error: Uninitiate FEdge!"); + } + this.executeTime = fe.getExeTime() + ((FlagState)fe.getTarget()).getExeTime(); + } + } else { + this.executeTime = 0; + } + while(it.hasNext()) { + FEdge fe = (FEdge)it.next(); + int temp = fe.getExeTime() + ((FlagState)fe.getTarget()).getExeTime(); + if(temp < this.executeTime) { + this.executeTime = temp; + } + } + } + + public Object clone() { + FlagState o = null; + try { + o = (FlagState) super.clone(); + } catch(CloneNotSupportedException e){ + e.printStackTrace(); + } + o.uid = FlagState.nodeid++; + o.edges = new Vector(); + for(int i = 0; i < this.edges.size(); i++) { + o.edges.addElement(this.edges.elementAt(i)); + } + o.inedges = new Vector(); + for(int i = 0; i < this.inedges.size(); i++) { + o.inedges.addElement(this.inedges.elementAt(i)); + } + return o; + } + + public void init4Simulate() { + this.invokeNum = 0; + } + + public FEdge process(TaskDescriptor td) { + FEdge next = null; + this.invokeNum++; + // refresh all the expInvokeNum of each edge + for(int i = 0; i < this.edges.size(); i++) { + next = (FEdge) this.edges.elementAt(i); + next.setExpInvokeNum((int)Math.round(this.invokeNum * (next.getProbability() / 100))); } - public boolean isIsolate() { - return isolate; - }*/ - + // find the one with the biggest gap between its actual invoke time and the expected invoke time + // and associated with task td + int index = 0; + int gap = 0; + for(int i = 0; i < this.edges.size(); i++) { + int temp = ((FEdge) this.edges.elementAt(index)).getInvokeNumGap(); + if((temp > gap) && (next.getTask().equals(td))){ + index = i; + gap = temp; + } + } + next = (FEdge) this.edges.elementAt(index); + next.process(); + + return next; + } + + /*public Vector getAllys() { + return allys; + } + + public void addAlly(ScheduleEdge se) { + if(this.allys == null) { + assert(this.isolate == true); + this.isolate = false; + this.allys = new Vector(); + } + this.allys.addElement(se); + } + + public boolean isIsolate() { + return isolate; + }*/ + } diff --git a/Robust/src/Analysis/TaskStateAnalysis/FlagTagState.java b/Robust/src/Analysis/TaskStateAnalysis/FlagTagState.java index ee4ffee5..8c4a4161 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/FlagTagState.java +++ b/Robust/src/Analysis/TaskStateAnalysis/FlagTagState.java @@ -5,23 +5,23 @@ import IR.Flat.*; import java.util.*; public class FlagTagState { - TagState ts; - FlagState fs; + TagState ts; + FlagState fs; - public FlagTagState(TagState ts, FlagState fs) { - this.ts=ts; - this.fs=fs; - } + public FlagTagState(TagState ts, FlagState fs) { + this.ts=ts; + this.fs=fs; + } - public boolean equals(Object o) { - if (o instanceof FlagTagState) { - FlagTagState fts=(FlagTagState) o; - return ts.equals(fts.ts)&&fs.equals(fts.fs); - } - return false; + public boolean equals(Object o) { + if (o instanceof FlagTagState) { + FlagTagState fts=(FlagTagState) o; + return ts.equals(fts.ts)&&fs.equals(fts.fs); } + return false; + } - public int hashCode() { - return ts.hashCode()^fs.hashCode(); - } + public int hashCode() { + return ts.hashCode()^fs.hashCode(); + } } diff --git a/Robust/src/Analysis/TaskStateAnalysis/GarbageAnalysis.java b/Robust/src/Analysis/TaskStateAnalysis/GarbageAnalysis.java index 46cdfb94..c7c7aa84 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/GarbageAnalysis.java +++ b/Robust/src/Analysis/TaskStateAnalysis/GarbageAnalysis.java @@ -6,76 +6,76 @@ import Util.GraphNode; import Util.Edge; public class GarbageAnalysis extends Namer { - State state; - TaskAnalysis taskanalysis; - HashSet garbagestates; - HashSet possiblegarbagestates; + State state; + TaskAnalysis taskanalysis; + HashSet garbagestates; + HashSet possiblegarbagestates; - public GarbageAnalysis(State state, TaskAnalysis taskanalysis) { - this.state=state; - this.taskanalysis=taskanalysis; - this.garbagestates=new HashSet(); - this.possiblegarbagestates=new HashSet(); - doAnalysis(); - } - - public void doAnalysis() { - for(Iterator it=state.getClassSymbolTable().getDescriptorsIterator();it.hasNext();) { - ClassDescriptor cd=(ClassDescriptor) it.next(); - if (taskanalysis.getFlagStates(cd)==null) - continue; - analyzeClass(cd); - } + public GarbageAnalysis(State state, TaskAnalysis taskanalysis) { + this.state=state; + this.taskanalysis=taskanalysis; + this.garbagestates=new HashSet(); + this.possiblegarbagestates=new HashSet(); + doAnalysis(); + } + + public void doAnalysis() { + for(Iterator it=state.getClassSymbolTable().getDescriptorsIterator(); it.hasNext();) { + ClassDescriptor cd=(ClassDescriptor) it.next(); + if (taskanalysis.getFlagStates(cd)==null) + continue; + analyzeClass(cd); } + } - public void analyzeClass(ClassDescriptor cd) { - Set flagstatenodes=taskanalysis.getFlagStates(cd); - HashSet garbage=new HashSet(); - HashSet possiblegarbage=new HashSet(); + public void analyzeClass(ClassDescriptor cd) { + Set flagstatenodes=taskanalysis.getFlagStates(cd); + HashSet garbage=new HashSet(); + HashSet possiblegarbage=new HashSet(); - for(Iterator fsit=flagstatenodes.iterator();fsit.hasNext();) { - FlagState fs=(FlagState)fsit.next(); - if (fs.numedges()==0) - garbage.add(fs); - } + for(Iterator fsit=flagstatenodes.iterator(); fsit.hasNext();) { + FlagState fs=(FlagState)fsit.next(); + if (fs.numedges()==0) + garbage.add(fs); + } - Stack tovisit=new Stack(); - tovisit.addAll(garbage); - possiblegarbage.addAll(garbage); - while(!tovisit.isEmpty()) { - FlagState fs=(FlagState)tovisit.pop(); - for(int i=0;i fs; - HashSet tags; +public class ObjWrapper implements Wrapper { + FlagState initfs; + HashSet fs; + HashSet tags; - public ObjWrapper(FlagState fs) { - this.initfs=fs; - this.fs=new HashSet(); - tags=new HashSet(); - } + public ObjWrapper(FlagState fs) { + this.initfs=fs; + this.fs=new HashSet(); + tags=new HashSet(); + } + + public ObjWrapper() { + this.fs=new HashSet(); + this.tags=new HashSet(); + } - public ObjWrapper() { - this.fs=new HashSet(); - this.tags=new HashSet(); - } - } diff --git a/Robust/src/Analysis/TaskStateAnalysis/OptionalTaskDescriptor.java b/Robust/src/Analysis/TaskStateAnalysis/OptionalTaskDescriptor.java index dcf54601..d352689e 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/OptionalTaskDescriptor.java +++ b/Robust/src/Analysis/TaskStateAnalysis/OptionalTaskDescriptor.java @@ -6,52 +6,52 @@ import IR.Flat.*; import java.io.*; import Util.Edge; -public class OptionalTaskDescriptor { - public TaskDescriptor td; - public HashSet enterflagstates; - public HashSet exitfses; - public Predicate predicate; - private static int nodeid=0; - private int index; - private int uid; - - protected OptionalTaskDescriptor(TaskDescriptor td, int index, HashSet enterflagstates, Predicate predicate) { - this.td = td; - this.enterflagstates = enterflagstates; - this.exitfses = new HashSet(); - this.predicate = predicate; - this.index=index; - } - - public int hashCode() { - return td.hashCode()^enterflagstates.hashCode()^predicate.hashCode()^index; - } +public class OptionalTaskDescriptor { + public TaskDescriptor td; + public HashSet enterflagstates; + public HashSet exitfses; + public Predicate predicate; + private static int nodeid=0; + private int index; + private int uid; - public boolean equals(Object o) { - if (o instanceof OptionalTaskDescriptor) { - OptionalTaskDescriptor otd=(OptionalTaskDescriptor) o; - if (otd.td==td&& - otd.enterflagstates.equals(enterflagstates)&& - otd.predicate.equals(predicate)&& - otd.index==index) - return true; - } - return false; - } + protected OptionalTaskDescriptor(TaskDescriptor td, int index, HashSet enterflagstates, Predicate predicate) { + this.td = td; + this.enterflagstates = enterflagstates; + this.exitfses = new HashSet(); + this.predicate = predicate; + this.index=index; + } - public int getIndex() { - return index; - } + public int hashCode() { + return td.hashCode()^enterflagstates.hashCode()^predicate.hashCode()^index; + } - public String tostring() { - return "Optional task "+td.getSymbol(); + public boolean equals(Object o) { + if (o instanceof OptionalTaskDescriptor) { + OptionalTaskDescriptor otd=(OptionalTaskDescriptor) o; + if (otd.td==td&& + otd.enterflagstates.equals(enterflagstates)&& + otd.predicate.equals(predicate)&& + otd.index==index) + return true; } + return false; + } - public void setuid() { - uid=nodeid++; - } + public int getIndex() { + return index; + } - public int getuid() { - return uid; - } + public String tostring() { + return "Optional task "+td.getSymbol(); + } + + public void setuid() { + uid=nodeid++; + } + + public int getuid() { + return uid; + } } diff --git a/Robust/src/Analysis/TaskStateAnalysis/Predicate.java b/Robust/src/Analysis/TaskStateAnalysis/Predicate.java index 7fefe6ec..ba679e5f 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/Predicate.java +++ b/Robust/src/Analysis/TaskStateAnalysis/Predicate.java @@ -6,28 +6,28 @@ import IR.Flat.*; import Util.Edge; public class Predicate { - public HashSet vardescriptors; - public Hashtable> flags; - public Hashtable tags; - //if there is a tag change, we stop the analysis - - public Predicate(){ - this.vardescriptors = new HashSet(); - this.flags = new Hashtable>(); - this.tags = new Hashtable(); - } + public HashSet vardescriptors; + public Hashtable> flags; + public Hashtable tags; + //if there is a tag change, we stop the analysis - public boolean equals(Object o) { - if (o instanceof Predicate) { - Predicate p=(Predicate)o; - if (vardescriptors.equals(p.vardescriptors)&& - flags.equals(p.flags)&& - tags.equals(p.tags)) - return true; - } - return false; - } - public int hashCode() { - return vardescriptors.hashCode(); + public Predicate() { + this.vardescriptors = new HashSet(); + this.flags = new Hashtable>(); + this.tags = new Hashtable(); + } + + public boolean equals(Object o) { + if (o instanceof Predicate) { + Predicate p=(Predicate)o; + if (vardescriptors.equals(p.vardescriptors)&& + flags.equals(p.flags)&& + tags.equals(p.tags)) + return true; } + return false; + } + public int hashCode() { + return vardescriptors.hashCode(); + } } diff --git a/Robust/src/Analysis/TaskStateAnalysis/SafetyAnalysis.java b/Robust/src/Analysis/TaskStateAnalysis/SafetyAnalysis.java index 93961377..ed0e3609 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/SafetyAnalysis.java +++ b/Robust/src/Analysis/TaskStateAnalysis/SafetyAnalysis.java @@ -10,560 +10,559 @@ import java.io.FileOutputStream; import Util.Edge; public class SafetyAnalysis { - private Hashtable executiongraph; - private Hashtable>> safeexecution; //to use to build code - private State state; - private TaskAnalysis taskanalysis; - private Hashtable> optionaltaskdescriptors; - private Hashtable>> fstotimap; - - private ClassDescriptor processedclass; - - public Hashtable>> getResult() { - return safeexecution; + private Hashtable executiongraph; + private Hashtable>> safeexecution; //to use to build code + private State state; + private TaskAnalysis taskanalysis; + private Hashtable> optionaltaskdescriptors; + private Hashtable>> fstotimap; + + private ClassDescriptor processedclass; + + public Hashtable>> getResult() { + return safeexecution; + } + + public Hashtable> getOptionalTaskDescriptors() { + return optionaltaskdescriptors; + } + + /* Structure that stores a possible optional task which would be + safe to execute and the possible flagstates the object could be + in before executing the task during an execution without + failure*/ + + /*Constructor*/ + public SafetyAnalysis(Hashtable executiongraph, State state, TaskAnalysis taskanalysis) { + this.executiongraph = executiongraph; + this.safeexecution = new Hashtable(); + this.state = state; + this.taskanalysis = taskanalysis; + this.optionaltaskdescriptors = new Hashtable(); + this.fstotimap=new Hashtable>>(); + } + + /* Builds map of fs -> EGTasknodes that can fire on fs for class cd */ + + private Hashtable> buildMap(ClassDescriptor cd) { + Hashtable> table=new Hashtable>(); + for(Iterator it=((Set)executiongraph.get(cd)).iterator(); it.hasNext();) { + EGTaskNode node=(EGTaskNode)it.next(); + if (node.getFS()!=null) { + if (!table.containsKey(node.getFS())) + table.put(node.getFS(), new HashSet()); + table.get(node.getFS()).add(node); + } } + return table; + } + + + public Set getOptions(FlagState fs, TaskDescriptor td, int index) { + return fstotimap.get(fs).get(new TaskIndex(td, index)); + } + + public Set getOptions(FlagState fs, TaskIndex ti) { + return fstotimap.get(fs).get(ti); + } + + public Set getTaskIndex(FlagState fs) { + return fstotimap.get(fs).keySet(); + } - public Hashtable> getOptionalTaskDescriptors() { - return optionaltaskdescriptors; + + /* Builds map of fs -> set of fs that depend on this fs */ + + private Hashtable> buildUseMap(ClassDescriptor cd) { + Hashtable> table=new Hashtable>(); + 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()); + } } + return table; + } + + public void doAnalysis() { + Enumeration classit=taskanalysis.flagstates.keys(); + + while (classit.hasMoreElements()) { + ClassDescriptor cd=(ClassDescriptor)classit.nextElement(); + if (!executiongraph.containsKey(cd)) + continue; + Hashtable> fstootd=new Hashtable>(); + safeexecution.put(cd, fstootd); + + optionaltaskdescriptors.put(cd, new Hashtable()); + + Hashtable> fstoegmap=buildMap(cd); + Hashtable> fsusemap=buildUseMap(cd); - /* Structure that stores a possible optional task which would be - safe to execute and the possible flagstates the object could be - in before executing the task during an execution without - failure*/ - - /*Constructor*/ - public SafetyAnalysis(Hashtable executiongraph, State state, TaskAnalysis taskanalysis) { - this.executiongraph = executiongraph; - this.safeexecution = new Hashtable(); - this.state = state; - this.taskanalysis = taskanalysis; - this.optionaltaskdescriptors = new Hashtable(); - this.fstotimap=new Hashtable>>(); + HashSet tovisit=new HashSet(); + 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); + } } - - /* Builds map of fs -> EGTasknodes that can fire on fs for class cd */ - - private Hashtable> buildMap(ClassDescriptor cd) { - Hashtable> table=new Hashtable>(); - for(Iterator it=((Set)executiongraph.get(cd)).iterator();it.hasNext();) { - EGTaskNode node=(EGTaskNode)it.next(); - if (node.getFS()!=null) { - if (!table.containsKey(node.getFS())) - table.put(node.getFS(), new HashSet()); - table.get(node.getFS()).add(node); + printTEST(); + } + + public void analyzeFS(FlagState fs, Set egset, Hashtable> fstootd, Hashtable> fsusemap, HashSet tovisit) { + Hashtable> timap=new Hashtable>(); + Set tiselfloops=new HashSet(); + + for(Iterator egit=egset.iterator(); egit.hasNext();) { + 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); + } else if (tagChange(egnode)) { + //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(); } - return table; + } else { + 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); + } + } } - - public Set getOptions(FlagState fs, TaskDescriptor td, int index) { - return fstotimap.get(fs).get(new TaskIndex(td, index)); + //Combine all options + HashSet set=new HashSet(); + for(Iterator> it=timap.values().iterator(); it.hasNext();) { + Set otdset=it.next(); + set.addAll(otdset); } - public Set getOptions(FlagState fs, TaskIndex ti) { - return fstotimap.get(fs).get(ti); + if (!fstootd.containsKey(fs)|| + !fstootd.get(fs).equals(set)) { + fstootd.put(fs, set); + //Requeue all flagstates that may use our updated results + if (fsusemap.containsKey(fs)) { + tovisit.addAll(fsusemap.get(fs)); + } } + fstotimap.put(fs, timap); + } - public Set getTaskIndex(FlagState fs) { - return fstotimap.get(fs).keySet(); + private HashSet createIntersection(Set A, Set B, ClassDescriptor cd) { + HashSet result = new HashSet(); + 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); + } + } } + return result; + } + // This method returns true if the only parameter whose flag is + // modified is the tracked one - /* Builds map of fs -> set of fs that depend on this fs */ + private boolean goodMultiple(EGTaskNode tn) { + TaskDescriptor td = tn.getTD(); + FlatMethod fm = state.getMethodFlat(td); + TempDescriptor tmp=fm.getParameter(tn.getIndex()); - private Hashtable> buildUseMap(ClassDescriptor cd) { - Hashtable> table=new Hashtable>(); - 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()); - } + Set nodeset=fm.getNodeSet(); + + 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 + } } - return table; + } } + return true; + } - public void doAnalysis() { - Enumeration classit=taskanalysis.flagstates.keys(); - - while (classit.hasMoreElements()) { - ClassDescriptor cd=(ClassDescriptor)classit.nextElement(); - if (!executiongraph.containsKey(cd)) - continue; - Hashtable> fstootd=new Hashtable>(); - safeexecution.put(cd, fstootd); - - optionaltaskdescriptors.put(cd, new Hashtable()); - - Hashtable> fstoegmap=buildMap(cd); - Hashtable> fsusemap=buildUseMap(cd); - - HashSet tovisit=new HashSet(); - 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); - } - } - printTEST(); + private Predicate returnPredicate(EGTaskNode tn) { + Predicate result = new Predicate(); + 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)); + } } + return result; + } - public void analyzeFS(FlagState fs, Set egset, Hashtable> fstootd, Hashtable> fsusemap, HashSet tovisit) { - Hashtable> timap=new Hashtable>(); - Set tiselfloops=new HashSet(); - - for(Iterator egit=egset.iterator();egit.hasNext();) { - 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); - } else if (tagChange(egnode)) { - //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(); - } - } else { - 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); - } - } - } + private Predicate combinePredicates(Predicate A, Predicate B) { + Predicate result = new Predicate(); + result.vardescriptors.addAll(A.vardescriptors); + result.flags.putAll(A.flags); + result.tags.putAll(A.tags); + Collection c = B.vardescriptors; + 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 "); + else { + result.vardescriptors.add(vd); + } + } + Collection vardesc = result.vardescriptors; + for(Iterator varit = vardesc.iterator(); varit.hasNext();){ + VarDescriptor vd = (VarDescriptor)varit.next(); + HashSet bflags = B.flags.get(vd); + if( bflags == null ){ + continue; + } else { + 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); + } + } + return result; + } - //Combine all options - HashSet set=new HashSet(); - for(Iterator> it=timap.values().iterator();it.hasNext();) { - Set otdset=it.next(); - set.addAll(otdset); - } + //////////////////// + /* returns a set of the possible sets of flagstates + resulting from the execution of the optional task. + To do it with have to look for TaskExit FlatNodes + in the IR. + */ + private void resultingFS(OptionalTaskDescriptor otd) { + Stack stack = new Stack(); + HashSet result = new HashSet(); + FlatMethod fm = state.getMethodFlat((TaskDescriptor)otd.td); + FlatNode fn = (FlatNode)fm; + + Stack nodestack=new Stack(); + HashSet discovered=new HashSet(); + nodestack.push(fm); + discovered.add(fm); + TempDescriptor temp=fm.getParameter(otd.getIndex()); + + //Iterating through the nodes + 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(); - if (!fstootd.containsKey(fs)|| - !fstootd.get(fs).equals(set)) { - fstootd.put(fs, set); - //Requeue all flagstates that may use our updated results - if (fsusemap.containsKey(fs)) { - tovisit.addAll(fsusemap.get(fs)); + 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)); } - } - fstotimap.put(fs, timap); - } - private HashSet createIntersection(Set A, Set B, ClassDescriptor cd){ - HashSet result = new HashSet(); - 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); + 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); } + } } - } - return result; - } - - // This method returns true if the only parameter whose flag is - // modified is the tracked one - - private boolean goodMultiple(EGTaskNode tn){ - TaskDescriptor td = tn.getTD(); - FlatMethod fm = state.getMethodFlat(td); - TempDescriptor tmp=fm.getParameter(tn.getIndex()); - - Set nodeset=fm.getNodeSet(); - - 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 - } + //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 } - return true; - } - - private Predicate returnPredicate(EGTaskNode tn){ - Predicate result = new Predicate(); - 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)); - } + } else if (fn1.kind()==FKind.FlatReturnNode) { + result.add(otd.enterflagstates); + } + + /* Queue other nodes past this one */ + for(int i=0; i 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); - } - - /* Queue other nodes past this one */ - for(int i=0;i "+tn2.getLabel()+";"); - } - } + /////////DEBUG + /*Thoose two tasks create the dot file named markedgraph.dot */ + + private void createDOTFile(String classname, Collection v) throws java.io.IOException { + java.io.PrintWriter output; + File dotfile_flagstates= new File("markedgraph_"+classname+".dot"); + FileOutputStream dotstream=new FileOutputStream(dotfile_flagstates,false); + output = new java.io.PrintWriter(dotstream, true); + output.println("digraph dotvisitor {"); + output.println("\tnode [fontsize=10,height=\"0.1\", width=\"0.1\"];"); + output.println("\tedge [fontsize=6];"); + traverse(output, v); + output.println("}\n"); + } + + private void traverse(java.io.PrintWriter output, Collection v) { + EGTaskNode tn; + + for(Iterator it1 = v.iterator(); it1.hasNext();){ + tn = (EGTaskNode)it1.next(); + output.println("\t"+tn.getLabel()+" [label=\""+tn.getTextLabel()+"\""); + if (tn.isOptional()){ + if (tn.isMultipleParams()) + output.println(", shape = tripleoctagon"); + else + output.println(", shape=doubleoctagon"); + } else if (tn.isMultipleParams()) + output.println(", shape=octagon"); + output.println("];"); + + for(Iterator it2 = tn.edges(); it2.hasNext();){ + EGTaskNode tn2 = (EGTaskNode)((Edge)it2.next()).getTarget(); + output.println("\t"+tn.getLabel()+" -> "+tn2.getLabel()+";"); + } } + } } diff --git a/Robust/src/Analysis/TaskStateAnalysis/TEdge.java b/Robust/src/Analysis/TaskStateAnalysis/TEdge.java index bd54738b..84e00c8d 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/TEdge.java +++ b/Robust/src/Analysis/TaskStateAnalysis/TEdge.java @@ -7,24 +7,24 @@ import java.util.*; import Util.Edge; -public class TEdge extends Edge{ - - public TEdge(TaskNode target){ - super(target); - } - - public int hashCode(){ - return target.hashCode(); - } - - - public boolean equals(Object o) { - if (o instanceof TEdge) { - TEdge e=(TEdge)o; - return e.target.equals(target); - } - return false; +public class TEdge extends Edge { + + public TEdge(TaskNode target) { + super(target); + } + + public int hashCode() { + return target.hashCode(); + } + + + public boolean equals(Object o) { + if (o instanceof TEdge) { + TEdge e=(TEdge)o; + return e.target.equals(target); } + return false; + } + - } diff --git a/Robust/src/Analysis/TaskStateAnalysis/TagAnalysis.java b/Robust/src/Analysis/TaskStateAnalysis/TagAnalysis.java index e1f0613b..2d8b8fd7 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/TagAnalysis.java +++ b/Robust/src/Analysis/TaskStateAnalysis/TagAnalysis.java @@ -18,212 +18,212 @@ import IR.MethodDescriptor; import IR.Flat.*; public class TagAnalysis { - State state; - Hashtable flagmap; - Stack tovisit; - Hashtable discovered; - Hashtable tasktotagbindings; - Hashtable tasktoflagstates; - CallGraph callgraph; - - public TagAnalysis(State state, CallGraph callgraph) { - this.state=state; - this.flagmap=new Hashtable(); - this.discovered=new Hashtable(); - this.tovisit=new Stack(); - this.tasktoflagstates=new Hashtable(); - this.tasktotagbindings=new Hashtable(); - this.callgraph=callgraph; - doAnalysis(); + State state; + Hashtable flagmap; + Stack tovisit; + Hashtable discovered; + Hashtable tasktotagbindings; + Hashtable tasktoflagstates; + CallGraph callgraph; + + public TagAnalysis(State state, CallGraph callgraph) { + this.state=state; + this.flagmap=new Hashtable(); + this.discovered=new Hashtable(); + this.tovisit=new Stack(); + this.tasktoflagstates=new Hashtable(); + this.tasktotagbindings=new Hashtable(); + this.callgraph=callgraph; + doAnalysis(); + } + + public Set getFlagStates(TaskDescriptor task) { + return (Set)tasktoflagstates.get(task); + } + + private void doAnalysis() { + Set rootset=computeRootSet(); + computeTagBindings(rootset); + TagBinding.SCC scc=TagBinding.DFS.computeSCC(discovered.keySet()); + 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); + } + } } + } } - - private Set computeRootSet() { - HashSet rootset=new HashSet(); - SymbolTable tasktable=state.getTaskSymbolTable(); - for(Iterator taskit=tasktable.getDescriptorsIterator();taskit.hasNext();) { - TaskDescriptor task=(TaskDescriptor)taskit.next(); - HashSet roottags=new HashSet(); - HashSet taskflags=new HashSet(); - FlatMethod fm=state.getMethodFlat(task); - computeCallsFlags(fm, null, roottags, taskflags); - rootset.addAll(roottags); - tasktotagbindings.put(task,roottags); - tasktoflagstates.put(task,taskflags); - } - return rootset; - } + } -private void computeCallsFlags(FlatMethod fm, Hashtable parammap, Set tagbindings, Set newflags) { - Set nodeset=fm.getNodeSet(); - 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); - } - } - } - } + private void computeTagBindings(Set roots) { + tovisit.addAll(roots); + + for(Iterator it=roots.iterator(); it.hasNext();) { + TagBinding tb=(TagBinding)it.next(); + discovered.put(tb,tb); } -} - - private void computeTagBindings(Set roots) { - tovisit.addAll(roots); - - for(Iterator it=roots.iterator();it.hasNext();) { - TagBinding tb=(TagBinding)it.next(); - discovered.put(tb,tb); - } - while(!tovisit.empty()) { - TagBinding tb=(TagBinding) tovisit.pop(); - MethodDescriptor md=tb.getMethod(); - FlatMethod fm=state.getMethodFlat(md); - /* Build map from temps -> tagdescriptors */ - Hashtable parammap=new Hashtable(); - int offset=md.isStatic()?0:1; - - - for(int i=0;i=0) { - TagDescriptor tag=tb.getBinding(offsetindex); - - if (tag!=null) { - parammap.put(temp,tag); - } - } - } + while(!tovisit.empty()) { + TagBinding tb=(TagBinding) tovisit.pop(); + MethodDescriptor md=tb.getMethod(); + FlatMethod fm=state.getMethodFlat(md); + /* Build map from temps -> tagdescriptors */ + Hashtable parammap=new Hashtable(); + int offset=md.isStatic() ? 0 : 1; - HashSet newtags=new HashSet(); - - 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); - } + for(int i=0; i=0) { + TagDescriptor tag=tb.getBinding(offsetindex); + + if (tag!=null) { + parammap.put(temp,tag); + } } + } + + HashSet newtags=new HashSet(); + + 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); + } } + } } diff --git a/Robust/src/Analysis/TaskStateAnalysis/TagBinding.java b/Robust/src/Analysis/TaskStateAnalysis/TagBinding.java index e7360b96..adc81a5a 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/TagBinding.java +++ b/Robust/src/Analysis/TaskStateAnalysis/TagBinding.java @@ -6,61 +6,61 @@ import java.util.HashSet; import java.util.Set; public class TagBinding extends GraphNode { - private MethodDescriptor md; - private TagDescriptor[] tdarray; - private HashSet allocations; + private MethodDescriptor md; + private TagDescriptor[] tdarray; + private HashSet allocations; - public TagBinding(MethodDescriptor md) { - this.md=md; - tdarray=new TagDescriptor[md.numParameters()]; - allocations=new HashSet(); - } + public TagBinding(MethodDescriptor md) { + this.md=md; + tdarray=new TagDescriptor[md.numParameters()]; + allocations=new HashSet(); + } - public String toString() { - String st=md.toString(); - for(int i=0;i flags; - public static final int KLIMIT=2; - public HashSet sourceset; - - public TagState(ClassDescriptor cd) { - this.flags=new Hashtable(); - this.sourceset=new HashSet(); - this.cd=cd; - } + private TagDescriptor tag; + private ClassDescriptor cd; + private Hashtable flags; + public static final int KLIMIT=2; + public HashSet sourceset; - public void addSource(TaskDescriptor td) { - sourceset.add(td); - } + public TagState(ClassDescriptor cd) { + this.flags=new Hashtable(); + this.sourceset=new HashSet(); + this.cd=cd; + } - public TagState(TagDescriptor tag) { - this.tag=tag; - this.flags=new Hashtable(); - this.sourceset=new HashSet(); - } + public void addSource(TaskDescriptor td) { + sourceset.add(td); + } - public TagDescriptor getTag() { - return tag; - } + public TagState(TagDescriptor tag) { + this.tag=tag; + this.flags=new Hashtable(); + this.sourceset=new HashSet(); + } - public ClassDescriptor getClassDesc() { - return cd; - } + public TagDescriptor getTag() { + return tag; + } - public TagState[] clearFS(FlagState fs) { - int num=0; - if (flags.containsKey(fs)) - num=flags.get(fs).intValue(); - if (num>0) - num--; - - TagState ts=new TagState(tag); - ts.flags.putAll(flags); - ts.flags.put(fs, new Integer(num)); - - if ((num+1)==KLIMIT) - return new TagState[] {ts, this}; - else - return new TagState[] {ts}; - } + public ClassDescriptor getClassDesc() { + return cd; + } - public TagState[] addnewFS(FlagState fs) { - int num=0; - if (flags.containsKey(fs)) - num=flags.get(fs).intValue(); - if (num0) + num--; - public TagState[] addFS(FlagState fs) { - int num=0; - if (flags.containsKey(fs)) - num=flags.get(fs).intValue(); - if (num getFS() { - return flags.keySet(); - } + public TagState[] addnewFS(FlagState fs) { + int num=0; + if (flags.containsKey(fs)) + num=flags.get(fs).intValue(); + if (num getFS() { + return flags.keySet(); + } + + public int hashCode() { + int hashcode=flags.hashCode(); + if (tag!=null) + hashcode^=tag.hashCode(); + return hashcode; + } + + public boolean equals(Object o) { + if (o instanceof TagState) { + TagState t=(TagState)o; + if ((tag==null&&t.tag==null)|| + (tag!=null&&t.tag!=null&&tag.equals(t.tag))) { + return flags.equals(t.flags); + } } + return false; + } } diff --git a/Robust/src/Analysis/TaskStateAnalysis/TagWrapper.java b/Robust/src/Analysis/TaskStateAnalysis/TagWrapper.java index 2a6b96f8..67784b6d 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/TagWrapper.java +++ b/Robust/src/Analysis/TaskStateAnalysis/TagWrapper.java @@ -5,27 +5,27 @@ import IR.Flat.*; import java.util.*; public class TagWrapper implements Wrapper { - TagState initts; - HashSet ts; + TagState initts; + HashSet ts; - public TagWrapper(TagState ts) { - this.initts=ts; - this.ts=new HashSet(); - this.ts.add(ts); - } + public TagWrapper(TagState ts) { + this.initts=ts; + this.ts=new HashSet(); + this.ts.add(ts); + } - private TagWrapper() { - } + private TagWrapper() { + } - public TagState getState() { - assert(ts.size()==1); - return ts.iterator().next(); - } + public TagState getState() { + assert(ts.size()==1); + return ts.iterator().next(); + } - public TagWrapper clone() { - TagWrapper tw=new TagWrapper(); - tw.initts=initts; - tw.ts=(HashSet)ts.clone(); - return tw; - } + public TagWrapper clone() { + TagWrapper tw=new TagWrapper(); + tw.initts=initts; + tw.ts=(HashSet)ts.clone(); + return tw; + } } diff --git a/Robust/src/Analysis/TaskStateAnalysis/TaskAnalysis.java b/Robust/src/Analysis/TaskStateAnalysis/TaskAnalysis.java index bba02a6e..8508068e 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/TaskAnalysis.java +++ b/Robust/src/Analysis/TaskStateAnalysis/TaskAnalysis.java @@ -8,268 +8,268 @@ import java.io.FileWriter; import java.io.FileOutputStream; public class TaskAnalysis { - State state; - Hashtable flagstates; - Hashtable flags; - Hashtable extern_flags; - Queue toprocess; - TagAnalysis taganalysis; - Hashtable cdtorootnodes; - Hashtable tdToFEdges; - - TypeUtil typeutil; - - /** - * Class Constructor - * - * @param state a flattened State object - * @see State - */ - public TaskAnalysis(State state, TagAnalysis taganalysis) { - this.state=state; - this.typeutil=new TypeUtil(state); - this.taganalysis=taganalysis; - } - - /** Builds a table of flags for each class in the Bristlecone - * program. It creates two hashtables: one which holds the - * ClassDescriptors and arrays of * FlagDescriptors as key-value - * pairs; the other holds the ClassDescriptor and the * number of - * external flags for that specific class. + State state; + Hashtable flagstates; + Hashtable flags; + Hashtable extern_flags; + Queue toprocess; + TagAnalysis taganalysis; + Hashtable cdtorootnodes; + Hashtable tdToFEdges; + + TypeUtil typeutil; + + /** + * Class Constructor + * + * @param state a flattened State object + * @see State + */ + public TaskAnalysis(State state, TagAnalysis taganalysis) { + this.state=state; + this.typeutil=new TypeUtil(state); + this.taganalysis=taganalysis; + } + + /** Builds a table of flags for each class in the Bristlecone + * program. It creates two hashtables: one which holds the + * ClassDescriptors and arrays of * FlagDescriptors as key-value + * pairs; the other holds the ClassDescriptor and the * number of + * external flags for that specific class. + */ + + private void getFlagsfromClasses() { + flags=new Hashtable(); + extern_flags = new Hashtable(); + + /** Iterate through the classes used in the program to build + * the table of flags */ + for(Iterator it_classes=state.getClassSymbolTable().getDescriptorsIterator(); it_classes.hasNext();) { - private void getFlagsfromClasses() { - flags=new Hashtable(); - extern_flags = new Hashtable(); - - /** Iterate through the classes used in the program to build - * the table of flags - */ - for(Iterator it_classes=state.getClassSymbolTable().getDescriptorsIterator();it_classes.hasNext();) { - - ClassDescriptor cd = (ClassDescriptor)it_classes.next(); - Vector vFlags=new Vector(); - FlagDescriptor flag[]; - int ctr=0; - - - /* 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(); - } + ClassDescriptor cd = (ClassDescriptor)it_classes.next(); + Vector vFlags=new Vector(); + FlagDescriptor flag[]; + int ctr=0; - if (vFlags.size()!=0) { - flag=new FlagDescriptor[vFlags.size()]; - - for(int i=0;i < vFlags.size() ; i++) { - if (((FlagDescriptor)vFlags.get(i)).getExternal()) { - flag[ctr]=(FlagDescriptor)vFlags.get(i); - vFlags.remove(flag[ctr]); - ctr++; - } - } - for(int i=0;i < vFlags.size() ; i++) { - flag[i+ctr]=(FlagDescriptor)vFlags.get(i); - } - extern_flags.put(cd,new Integer(ctr)); - flags.put(cd,flag); - - } + /* 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); } - } - /** Method which starts up the analysis - */ - - public void taskAnalysis() throws java.io.IOException { - flagstates=new Hashtable(); - Hashtable sourcenodes; - cdtorootnodes=new Hashtable(); - tdToFEdges=new Hashtable(); - - getFlagsfromClasses(); - - int externs; - toprocess=new LinkedList(); - - for(Iterator it_classes=(Iterator)flags.keys();it_classes.hasNext();) { - ClassDescriptor cd=(ClassDescriptor)it_classes.next(); - externs=((Integer)extern_flags.get(cd)).intValue(); - FlagDescriptor[] fd=(FlagDescriptor[])flags.get(cd); - flagstates.put(cd,new Hashtable()); - cdtorootnodes.put(cd,new Vector()); - } - - - ClassDescriptor startupobject=typeutil.getClass(TypeUtil.StartupClass); - - sourcenodes=(Hashtable)flagstates.get(startupobject); - FlagState fsstartup=new FlagState(startupobject); - - - FlagDescriptor[] fd=(FlagDescriptor[])flags.get(startupobject); - - fsstartup=fsstartup.setFlag(fd[0],true); - fsstartup.setAsSourceNode(); - ((Vector)cdtorootnodes.get(startupobject)).add(fsstartup); - - sourcenodes.put(fsstartup,fsstartup); - toprocess.add(fsstartup); - - /** Looping through the flagstates in the toprocess queue to - * perform the state analysis */ - while (!toprocess.isEmpty()) { - FlagState trigger=toprocess.poll(); - createPossibleRuntimeStates(trigger); - - analyseTasks(trigger); + tmp=tmp.getSuperDesc(); + } + + + if (vFlags.size()!=0) { + flag=new FlagDescriptor[vFlags.size()]; + + for(int i=0; i < vFlags.size() ; i++) { + if (((FlagDescriptor)vFlags.get(i)).getExternal()) { + flag[ctr]=(FlagDescriptor)vFlags.get(i); + vFlags.remove(flag[ctr]); + ctr++; + } } - - /** Creating DOT files */ - Enumeration e=flagstates.keys(); - - while (e.hasMoreElements()) { - ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement(); - createDOTfile(cdtemp); + for(int i=0; i < vFlags.size() ; i++) { + flag[i+ctr]=(FlagDescriptor)vFlags.get(i); } + extern_flags.put(cd,new Integer(ctr)); + flags.put(cd,flag); + + } } - - - /** Analyses the set of tasks based on the given flagstate, checking - * to see which tasks are triggered and what new flagstates are created - * from the base flagstate. - * @param fs A FlagState object which is used to analyse the task - * @see FlagState - */ + } + /** Method which starts up the analysis + */ + + public void taskAnalysis() throws java.io.IOException { + flagstates=new Hashtable(); + Hashtable sourcenodes; + cdtorootnodes=new Hashtable(); + tdToFEdges=new Hashtable(); + + getFlagsfromClasses(); + + int externs; + toprocess=new LinkedList(); + + for(Iterator it_classes=(Iterator)flags.keys(); it_classes.hasNext();) { + ClassDescriptor cd=(ClassDescriptor)it_classes.next(); + externs=((Integer)extern_flags.get(cd)).intValue(); + FlagDescriptor[] fd=(FlagDescriptor[])flags.get(cd); + flagstates.put(cd,new Hashtable()); + cdtorootnodes.put(cd,new Vector()); + } + + + ClassDescriptor startupobject=typeutil.getClass(TypeUtil.StartupClass); + + sourcenodes=(Hashtable)flagstates.get(startupobject); + FlagState fsstartup=new FlagState(startupobject); + + + FlagDescriptor[] fd=(FlagDescriptor[])flags.get(startupobject); -private void analyseTasks(FlagState fs) { + fsstartup=fsstartup.setFlag(fd[0],true); + fsstartup.setAsSourceNode(); + ((Vector)cdtorootnodes.get(startupobject)).add(fsstartup); + + sourcenodes.put(fsstartup,fsstartup); + toprocess.add(fsstartup); + + /** Looping through the flagstates in the toprocess queue to + * perform the state analysis */ + while (!toprocess.isEmpty()) { + FlagState trigger=toprocess.poll(); + createPossibleRuntimeStates(trigger); + + analyseTasks(trigger); + } + + /** Creating DOT files */ + Enumeration e=flagstates.keys(); + + while (e.hasMoreElements()) { + ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement(); + createDOTfile(cdtemp); + } + } + + + /** Analyses the set of tasks based on the given flagstate, checking + * to see which tasks are triggered and what new flagstates are created + * from the base flagstate. + * @param fs A FlagState object which is used to analyse the task + * @see FlagState + */ + + private void analyseTasks(FlagState fs) { ClassDescriptor cd=fs.getClassDescriptor(); Hashtable sourcenodes=(Hashtable)flagstates.get(cd); - - for(Iterator it_tasks=state.getTaskSymbolTable().getDescriptorsIterator();it_tasks.hasNext();) { - TaskDescriptor td = (TaskDescriptor)it_tasks.next(); - String taskname=td.getSymbol(); - - if(!tdToFEdges.containsKey(td)) { - tdToFEdges.put(td, new Vector()); + + for(Iterator it_tasks=state.getTaskSymbolTable().getDescriptorsIterator(); it_tasks.hasNext();) { + TaskDescriptor td = (TaskDescriptor)it_tasks.next(); + String taskname=td.getSymbol(); + + if(!tdToFEdges.containsKey(td)) { + tdToFEdges.put(td, new Vector()); + } + + /** counter to keep track of the number of parameters (of the + * task being analyzed) that are satisfied by the flagstate. + */ + int trigger_ctr=0; + TempDescriptor temp=null; + FlatMethod fm = state.getMethodFlat(td); + 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++; } + } - /** counter to keep track of the number of parameters (of the - * task being analyzed) that are satisfied by the flagstate. - */ - int trigger_ctr=0; - TempDescriptor temp=null; - FlatMethod fm = state.getMethodFlat(td); - 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++; - } + if (trigger_ctr==0) //Look at next task + 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); + + + 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); } - - if (trigger_ctr==0) //Look at next task - 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); - - - 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); + fsnew.setAsSourceNode(); + fsnew.addAllocatingTask(td); - if(!((Vector)cdtorootnodes.get(fsnew.getClassDescriptor())).contains(fsnew)) { - ((Vector)cdtorootnodes.get(fsnew.getClassDescriptor())).add(fsnew); - } + if(!((Vector)cdtorootnodes.get(fsnew.getClassDescriptor())).contains(fsnew)) { + ((Vector)cdtorootnodes.get(fsnew.getClassDescriptor())).add(fsnew); } - - Stack nodestack=new Stack(); - HashSet discovered=new HashSet(); - nodestack.push(fm); - discovered.add(fm); - //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); - 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); - ((Vector)tdToFEdges.get(td)).add(newedge); - fs.addEdge(newedge); - - if(!targetFStates.contains(fs_taskexit)) { - targetFStates.addElement(fs_taskexit); - } - } - continue; - } + } + + Stack nodestack=new Stack(); + HashSet discovered=new HashSet(); + nodestack.push(fm); + discovered.add(fm); + //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); + 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); } - /* Queue other nodes past this one */ - for(int i=0;i 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); + ((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 evalTaskExitNode(FlatFlagActionNode ffan,ClassDescriptor cd,FlagState fs, TempDescriptor temp){ - FlagState fstemp=fs; - Vector processed=new Vector(); + default: + return false; + } + } - //Process the flag changes - - for(Iterator it_tfp=ffan.getTempFlagPairs();it_tfp.hasNext();) { - TempFlagPair tfp=(TempFlagPair)it_tfp.next(); - if (temp==tfp.getTemp()) - fstemp=fstemp.setFlag(tfp.getFlag(),ffan.getFlagChange(tfp)); - } - - //Process the tag changes - - 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); - } - } - } - return processed; - } - - - private FlagState canonicalizeFlagState(Hashtable sourcenodes, FlagState fs){ - if (sourcenodes.containsKey(fs)) - return (FlagState)sourcenodes.get(fs); - else{ - sourcenodes.put(fs,fs); - return fs; + private boolean isTaskTrigger_tag(TagExpressionList tel, FlagState fs) { + + if (tel!=null){ + for (int i=0; i getFlagStates(ClassDescriptor cd) { - if (flagstates.containsKey(cd)) - return ((Hashtable)flagstates.get(cd)).keySet(); - else - return new HashSet(); + private Vector evalTaskExitNode(FlatFlagActionNode ffan,ClassDescriptor cd,FlagState fs, TempDescriptor temp) { + FlagState fstemp=fs; + Vector processed=new Vector(); + + //Process the flag changes + + for(Iterator it_tfp=ffan.getTempFlagPairs(); it_tfp.hasNext();) { + TempFlagPair tfp=(TempFlagPair)it_tfp.next(); + if (temp==tfp.getTemp()) + fstemp=fstemp.setFlag(tfp.getFlag(),ffan.getFlagChange(tfp)); } + //Process the tag changes + + 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(); - private void createPossibleRuntimeStates(FlagState fs) { - ClassDescriptor cd = fs.getClassDescriptor(); - Hashtable sourcenodes=(Hashtable)flagstates.get(cd); - FlagDescriptor[] fd=(FlagDescriptor[])flags.get(cd); - int externs=((Integer)extern_flags.get(cd)).intValue(); - - if(externs==0) - return; - - int noOfIterations=(1< oldprocess=processed; + processed=new Vector(); - fstemp=canonicalizeFlagState(sourcenodes,fstemp); - fs.addEdge(new FEdge(fstemp,"Runtime", null, -1)); + 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); } + } } - - public Vector getRootNodes(ClassDescriptor cd){ - return (Vector)cdtorootnodes.get(cd); + return processed; + } + + + private FlagState canonicalizeFlagState(Hashtable sourcenodes, FlagState fs) { + if (sourcenodes.containsKey(fs)) + return (FlagState)sourcenodes.get(fs); + else{ + sourcenodes.put(fs,fs); + return fs; } - - public Vector getFEdgesFromTD(TaskDescriptor td) { - return (Vector)tdToFEdges.get(td); + } + + /** Creates a DOT file using the flagstates for a given class + * @param cd ClassDescriptor of the class + * @throws java.io.IOException + * @see ClassDescriptor + */ + + public void createDOTfile(ClassDescriptor cd) throws java.io.IOException { + File dotfile_flagstates= new File("graph"+cd.getSymbol()+".dot"); + FileOutputStream dotstream=new FileOutputStream(dotfile_flagstates,false); + FlagState.DOTVisitor.visit(dotstream,((Hashtable)flagstates.get(cd)).values()); + } + + /** Returns the flag states for the class descriptor. */ + public Set getFlagStates(ClassDescriptor cd) { + if (flagstates.containsKey(cd)) + return ((Hashtable)flagstates.get(cd)).keySet(); + else + return new HashSet(); + } + + + private void createPossibleRuntimeStates(FlagState fs) { + ClassDescriptor cd = fs.getClassDescriptor(); + Hashtable sourcenodes=(Hashtable)flagstates.get(cd); + FlagDescriptor[] fd=(FlagDescriptor[])flags.get(cd); + int externs=((Integer)extern_flags.get(cd)).intValue(); + + if(externs==0) + return; + + int noOfIterations=(1< decisions; - Hashtable temptotag; - ObjWrapper[] parameterbindings; - boolean increment; + TaskQueueIterator tqi; + Vector decisions; + Hashtable temptotag; + ObjWrapper[] parameterbindings; + boolean increment; - public TaskBinding(TaskQueueIterator tqi) { - this.tqi=tqi; - this.decisions=new Vector(); - int numobjs=tqi.ftsarray.length; - int numtags=tqi.tq.tags.size(); - this.parameterbindings=new ObjWrapper[numobjs]; - for(int i=0;i<(numtags+numobjs);i++) { - decisions.add(new Integer(0)); - } + public TaskBinding(TaskQueueIterator tqi) { + this.tqi=tqi; + this.decisions=new Vector(); + int numobjs=tqi.ftsarray.length; + int numtags=tqi.tq.tags.size(); + this.parameterbindings=new ObjWrapper[numobjs]; + for(int i=0; i<(numtags+numobjs); i++) { + decisions.add(new Integer(0)); } + } - public ObjWrapper getParameter(int i) { - return parameterbindings[i]; - } - - public TagWrapper getTag(TempDescriptor tmp) { - return temptotag.get(tmp); - } - - public void next() { - increment=true; + public ObjWrapper getParameter(int i) { + return parameterbindings[i]; + } + + public TagWrapper getTag(TempDescriptor tmp) { + return temptotag.get(tmp); + } + + public void next() { + increment=true; + } + + public boolean hasNext() { + Vector tagv=tqi.tq.tags; + int numtags=tagv.size(); + int numobjs=tqi.ftsarray.length; + int incrementlevel=numtags+numobjs; + if (increment) { + //actually do increment + incrementlevel--; + increment=false; } - public boolean hasNext() { - Vector tagv=tqi.tq.tags; - int numtags=tagv.size(); - int numobjs=tqi.ftsarray.length; - int incrementlevel=numtags+numobjs; - if (increment) { - //actually do increment +mainloop: + while(true) { + Hashtable> ttable=new Hashtable>(); + temptotag=new Hashtable(); + //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--; - increment=false; + 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); } - - mainloop: - while(true) { - Hashtable> ttable=new Hashtable>(); - temptotag=new Hashtable(); - //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); - } + 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; } - return true; + } + parameterbindings[objindex]=ow; + } else { + TempDescriptor tmp=tagv.get(i); + temptotag.put(tmp, tw); } + } + return true; } + } } diff --git a/Robust/src/Analysis/TaskStateAnalysis/TaskEdges.java b/Robust/src/Analysis/TaskStateAnalysis/TaskEdges.java index 2c20ca9d..c9793975 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/TaskEdges.java +++ b/Robust/src/Analysis/TaskStateAnalysis/TaskEdges.java @@ -1,25 +1,26 @@ package Analysis.TaskStateAnalysis; import Util.*; -public class TaskEdges extends Namer{ - public TaskEdges(){} - - public String nodeLabel(GraphNode gn) { - return ""; - } - - public String nodeOption(GraphNode gn) { - return ""; - } - - - public String edgeLabel(Edge edge){ - return ""; - } - - - public String edgeOption(Edge edge){ - return "URL=\""+edge.getLabel()+".html\""; - } - -} +public class TaskEdges extends Namer { + public TaskEdges() { + } + + public String nodeLabel(GraphNode gn) { + return ""; + } + + public String nodeOption(GraphNode gn) { + return ""; + } + + + public String edgeLabel(Edge edge) { + return ""; + } + + + public String edgeOption(Edge edge) { + return "URL=\""+edge.getLabel()+".html\""; + } + +} diff --git a/Robust/src/Analysis/TaskStateAnalysis/TaskGraph.java b/Robust/src/Analysis/TaskStateAnalysis/TaskGraph.java index 7f05d280..ac522e9d 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/TaskGraph.java +++ b/Robust/src/Analysis/TaskStateAnalysis/TaskGraph.java @@ -9,223 +9,223 @@ import java.io.FileWriter; import java.io.FileOutputStream; public class TaskGraph { - TaskAnalysis taskanalysis; - State state; - Hashtable cdtonodes; - Hashtable nodes; - Hashtable alltasknodes; - - //Colors - String colors[]={"red","blue","green","brown","orange","pink","black","grey","olivedrab","yellow"}; - - public TaskGraph(State state, TaskAnalysis taskanalysis) { - this.state=state; - this.taskanalysis=taskanalysis; - this.cdtonodes=new Hashtable(); - this.alltasknodes=new Hashtable(); - - for(Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();classit.hasNext();) { - ClassDescriptor cd=(ClassDescriptor) classit.next(); - if (cd.hasFlags()) - produceTaskNodes(cd); - } - produceAllTaskNodes(); + TaskAnalysis taskanalysis; + State state; + Hashtable cdtonodes; + Hashtable nodes; + Hashtable alltasknodes; + + //Colors + String colors[]={"red","blue","green","brown","orange","pink","black","grey","olivedrab","yellow"}; + + public TaskGraph(State state, TaskAnalysis taskanalysis) { + this.state=state; + this.taskanalysis=taskanalysis; + this.cdtonodes=new Hashtable(); + this.alltasknodes=new Hashtable(); + + for(Iterator classit=state.getClassSymbolTable().getDescriptorsIterator(); classit.hasNext();) { + ClassDescriptor cd=(ClassDescriptor) classit.next(); + if (cd.hasFlags()) + produceTaskNodes(cd); } - - - public void createDOTfiles() { - for(Iterator it_classes=(Iterator)cdtonodes.keys();it_classes.hasNext();) { - 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(); - } - } + produceAllTaskNodes(); + } + + + public void createDOTfiles() { + for(Iterator it_classes=(Iterator)cdtonodes.keys(); it_classes.hasNext();) { + 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(); } + } } + } - /** Returns the set of TaskNodes for the class descriptor cd */ + /** Returns the set of TaskNodes for the class descriptor cd */ - public Set getTaskNodes(ClassDescriptor cd) { - if (cdtonodes.containsKey(cd)) - return ((Hashtable)cdtonodes.get(cd)).keySet(); - else - return null; + public Set getTaskNodes(ClassDescriptor cd) { + if (cdtonodes.containsKey(cd)) + return ((Hashtable)cdtonodes.get(cd)).keySet(); + else + return null; + } + + private TaskNode canonicalizeTaskNode(Hashtable nodes, TaskNode node) { + if (nodes.containsKey(node)) + return (TaskNode)nodes.get(node); + else{ + nodes.put(node,node); + return (TaskNode)node; } + } + + private void produceTaskNodes(ClassDescriptor cd) { + Set fsnodes=taskanalysis.getFlagStates(cd); + if (fsnodes==null) + return; + + Hashtable tasknodes=new Hashtable(); + cdtonodes.put(cd, tasknodes); - private TaskNode canonicalizeTaskNode(Hashtable nodes, TaskNode node){ - if (nodes.containsKey(node)) - return (TaskNode)nodes.get(node); - else{ - nodes.put(node,node); - return (TaskNode)node; + for(Iterator it=fsnodes.iterator(); it.hasNext();) { + FlagState fs=(FlagState)it.next(); + Iterator it_inedges=fs.inedges(); + 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); + } } - } - - private void produceTaskNodes(ClassDescriptor cd) { - Set fsnodes=taskanalysis.getFlagStates(cd); - if (fsnodes==null) - return; - - Hashtable tasknodes=new Hashtable(); - cdtonodes.put(cd, tasknodes); - - for(Iterator it=fsnodes.iterator();it.hasNext();) { - FlagState fs=(FlagState)it.next(); - Iterator it_inedges=fs.inedges(); - 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); - } - } - } - - while(it_inedges.hasNext()){ - - FEdge inedge=(FEdge)it_inedges.next(); - tn=new TaskNode(inedge.getLabel()); - if(fs.edges().hasNext()){ - addEdges(fs,tn,tasknodes); - } - } + } + + while(it_inedges.hasNext()){ + + FEdge inedge=(FEdge)it_inedges.next(); + tn=new TaskNode(inedge.getLabel()); + if(fs.edges().hasNext()){ + addEdges(fs,tn,tasknodes); } + } } - - private void produceAllTaskNodes(){ - alltasknodes=new Hashtable(); - - for(Iterator it_tasks=state.getTaskSymbolTable().getDescriptorsIterator();it_tasks.hasNext();){ - TaskDescriptor td=(TaskDescriptor)it_tasks.next(); - TaskNode tn=new TaskNode(td.getSymbol()); - alltasknodes.put(tn,tn); - } - TaskNode tn_runtime=new TaskNode("Runtime"); - alltasknodes.put(tn_runtime,tn_runtime); - - int ColorID=0; - for(Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();classit.hasNext()&&ColorID<10;) { - ClassDescriptor cd=(ClassDescriptor) classit.next(); - 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++; - } - - } - } - - public Set getAllTaskNodes(){ - return alltasknodes.keySet(); - } - - - - - - - - - /* private void mergeAllNodes(){ - Hashtable alltasks=new Hashtable(); - for(Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();classit.hasNext();) { - ClassDescriptor cd=(ClassDescriptor) classit.next(); - Set tnodes=((Hashtable)cdtonodes.get(cd)).keyset(); - while (it_tnodes=tnodes.iterator();it_nodes.hasNext()){ - TaskNode tn=it_nodes.next(); - if (alltasks.containsKey(tn)){ - while(tn. - } - } - - - - + } + + private void produceAllTaskNodes() { + alltasknodes=new Hashtable(); + + for(Iterator it_tasks=state.getTaskSymbolTable().getDescriptorsIterator(); it_tasks.hasNext();){ + TaskDescriptor td=(TaskDescriptor)it_tasks.next(); + TaskNode tn=new TaskNode(td.getSymbol()); + alltasknodes.put(tn,tn); } - - */ - - private void addEdges(FlagState fs, TaskNode tn,Hashtable tasknodes){ - - // Hashtable tasknodes=(Hashtable)cdtonodes.get(fs.getClassDescriptor()); - tn=(TaskNode)canonicalizeTaskNode(tasknodes, tn); - for (Iterator it_edges=fs.edges();it_edges.hasNext();){ - TaskNode target=new TaskNode(((FEdge)it_edges.next()).getLabel()); - target=(TaskNode)canonicalizeTaskNode(tasknodes,target); - - TEdge newedge=new TEdge(target); - if (! tn.edgeExists(newedge)) - tn.addEdge(newedge); - } + TaskNode tn_runtime=new TaskNode("Runtime"); + alltasknodes.put(tn_runtime,tn_runtime); - } - - private void addEdges(FlagState fs, TaskNode tn,Hashtable tasknodes,int ColorID){ - - tn=(TaskNode)canonicalizeTaskNode(tasknodes, tn); - for (Iterator it_edges=fs.edges();it_edges.hasNext();){ - TaskNode target=new TaskNode(((FEdge)it_edges.next()).getLabel()); - target=(TaskNode)canonicalizeTaskNode(tasknodes,target); - - TEdge newedge=new TEdge(target); - newedge.setDotNodeParameters("style=bold, color = "+colors[ColorID]); - if (! tn.edgeExists(newedge)) - tn.addEdge(newedge); + int ColorID=0; + for(Iterator classit=state.getClassSymbolTable().getDescriptorsIterator(); classit.hasNext()&&ColorID<10;) { + ClassDescriptor cd=(ClassDescriptor) classit.next(); + 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++; + } + + } + } + + public Set getAllTaskNodes() { + return alltasknodes.keySet(); + } + + + + + + + + + /* private void mergeAllNodes(){ + Hashtable alltasks=new Hashtable(); + for(Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();classit.hasNext();) { + ClassDescriptor cd=(ClassDescriptor) classit.next(); + Set tnodes=((Hashtable)cdtonodes.get(cd)).keyset(); + while (it_tnodes=tnodes.iterator();it_nodes.hasNext()){ + TaskNode tn=it_nodes.next(); + if (alltasks.containsKey(tn)){ + while(tn. + } + } + + + + + } + + */ + + private void addEdges(FlagState fs, TaskNode tn,Hashtable tasknodes) { + + // Hashtable tasknodes=(Hashtable)cdtonodes.get(fs.getClassDescriptor()); + tn=(TaskNode)canonicalizeTaskNode(tasknodes, tn); + for (Iterator it_edges=fs.edges(); it_edges.hasNext();){ + TaskNode target=new TaskNode(((FEdge)it_edges.next()).getLabel()); + target=(TaskNode)canonicalizeTaskNode(tasknodes,target); + + TEdge newedge=new TEdge(target); + if (!tn.edgeExists(newedge)) + tn.addEdge(newedge); + } + + } + + private void addEdges(FlagState fs, TaskNode tn,Hashtable tasknodes,int ColorID) { + + tn=(TaskNode)canonicalizeTaskNode(tasknodes, tn); + for (Iterator it_edges=fs.edges(); it_edges.hasNext();){ + TaskNode target=new TaskNode(((FEdge)it_edges.next()).getLabel()); + target=(TaskNode)canonicalizeTaskNode(tasknodes,target); + + TEdge newedge=new TEdge(target); + newedge.setDotNodeParameters("style=bold, color = "+colors[ColorID]); + if (!tn.edgeExists(newedge)) + tn.addEdge(newedge); + } + + } + } diff --git a/Robust/src/Analysis/TaskStateAnalysis/TaskIndex.java b/Robust/src/Analysis/TaskStateAnalysis/TaskIndex.java index 84f21d0d..c158bcd4 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/TaskIndex.java +++ b/Robust/src/Analysis/TaskStateAnalysis/TaskIndex.java @@ -2,45 +2,45 @@ package Analysis.TaskStateAnalysis; import IR.TaskDescriptor; public class TaskIndex { - TaskDescriptor td; - int index; - boolean runtime; - public TaskIndex(TaskDescriptor td, int index) { - this.td=td; - this.index=index; - runtime=false; - } + TaskDescriptor td; + int index; + boolean runtime; + public TaskIndex(TaskDescriptor td, int index) { + this.td=td; + this.index=index; + runtime=false; + } - public TaskIndex() { - runtime=true; - } + public TaskIndex() { + runtime=true; + } - public boolean isRuntime() { - return runtime; - } + public boolean isRuntime() { + return runtime; + } - public int hashCode() { - if (runtime) - return 71; - return td.hashCode()^index; - } + public int hashCode() { + if (runtime) + return 71; + return td.hashCode()^index; + } - public boolean equals(Object o) { - if (o instanceof TaskIndex) { - TaskIndex ti=(TaskIndex) o; - if (ti.runtime==runtime) - return true; + public boolean equals(Object o) { + if (o instanceof TaskIndex) { + TaskIndex ti=(TaskIndex) o; + if (ti.runtime==runtime) + return true; - if (ti.index==index && ti.td==td) - return true; - } - return false; + if (ti.index==index && ti.td==td) + return true; } + return false; + } - public TaskDescriptor getTask() { - return td; - } - public int getIndex() { - return index; - } + public TaskDescriptor getTask() { + return td; + } + public int getIndex() { + return index; + } } diff --git a/Robust/src/Analysis/TaskStateAnalysis/TaskNode.java b/Robust/src/Analysis/TaskStateAnalysis/TaskNode.java index 7ee1c36f..2b776c8e 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/TaskNode.java +++ b/Robust/src/Analysis/TaskStateAnalysis/TaskNode.java @@ -8,69 +8,69 @@ import java.io.*; import Util.GraphNode; public class TaskNode extends GraphNode { - - private final String name; - protected int uid; - private static int nodeid=0; - // private int loopmarker=0; - //private boolean multipleparams=false; - /**Class Constructor - * Creates a new TaskNode using the TaskDescriptor. - * @param tasknode TaskDescriptor - */ - public TaskNode(String name){ - this.name=name; - this.uid=TaskNode.nodeid++; - } - - /**Returns the string representation of the node - * @return string representation of the tasknode (e.g "Task foo") - */ - public String getTextLabel() { - return "Task "+name; - } - - public String getLabel() { - return "N"+uid; - } - public String getName(){ - return name; - } + private final String name; + protected int uid; + private static int nodeid=0; + // private int loopmarker=0; + //private boolean multipleparams=false; + /**Class Constructor + * Creates a new TaskNode using the TaskDescriptor. + * @param tasknode TaskDescriptor + */ + public TaskNode(String name) { + this.name=name; + this.uid=TaskNode.nodeid++; + } - // public int getuid(){ - //return uid; - //} - - - /**toString method. - * @return string representation of the tasknode (e.g "Task foo") - */ - public String toString(){ - return getTextLabel(); - } - - public int hashCode(){ - return name.hashCode(); - - } - - public boolean equals(Object o) { - if (o instanceof TaskNode) { - TaskNode tn=(TaskNode)o; - return (tn.name.equals(name)); - } - return false; - } - - public boolean edgeExists(TEdge newedge){ - if(edges.isEmpty()) - return false; - else - return edges.contains(newedge); + /**Returns the string representation of the node + * @return string representation of the tasknode (e.g "Task foo") + */ + public String getTextLabel() { + return "Task "+name; + } + + public String getLabel() { + return "N"+uid; + } + + public String getName() { + return name; + } + + // public int getuid(){ + //return uid; + //} + + + /**toString method. + * @return string representation of the tasknode (e.g "Task foo") + */ + public String toString() { + return getTextLabel(); + } + + public int hashCode() { + return name.hashCode(); + + } + + public boolean equals(Object o) { + if (o instanceof TaskNode) { + TaskNode tn=(TaskNode)o; + return (tn.name.equals(name)); } - + return false; + } + + public boolean edgeExists(TEdge newedge) { + if(edges.isEmpty()) + return false; + else + return edges.contains(newedge); + } + } - - - + + + diff --git a/Robust/src/Analysis/TaskStateAnalysis/TaskNodeNamer.java b/Robust/src/Analysis/TaskStateAnalysis/TaskNodeNamer.java index 4b6bf769..3585d529 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/TaskNodeNamer.java +++ b/Robust/src/Analysis/TaskStateAnalysis/TaskNodeNamer.java @@ -1,15 +1,16 @@ package Analysis.TaskStateAnalysis; import Util.*; -public class TaskNodeNamer extends Namer{ - public TaskNodeNamer(){} +public class TaskNodeNamer extends Namer { + public TaskNodeNamer() { + } - public String nodeLabel(GraphNode gn){ - return ""; - } + public String nodeLabel(GraphNode gn) { + return ""; + } - public String nodeOption(GraphNode gn){ - return "URL=\""+gn.getName()+".html\""; - } + public String nodeOption(GraphNode gn) { + return "URL=\""+gn.getName()+".html\""; + } -} +} diff --git a/Robust/src/Analysis/TaskStateAnalysis/TaskQueue.java b/Robust/src/Analysis/TaskStateAnalysis/TaskQueue.java index 52294802..ec9a350c 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/TaskQueue.java +++ b/Robust/src/Analysis/TaskStateAnalysis/TaskQueue.java @@ -5,42 +5,42 @@ import IR.Flat.*; import java.util.*; public class TaskQueue { - protected TaskDescriptor task; - protected HashSet []parameterset; - protected Vector tags; - protected Hashtable > map; + protected TaskDescriptor task; + protected HashSet [] parameterset; + protected Vector tags; + protected Hashtable > map; - public int numParameters() { - return parameterset.length; - } + public int numParameters() { + return parameterset.length; + } - public TaskDescriptor getTask() { - return task; - } + public TaskDescriptor getTask() { + return task; + } - public TaskQueue(TaskDescriptor td) { - this.task=td; - this.parameterset=(HashSet[])new HashSet[task.numParameters()]; - this.map=new Hashtable>(); - this.tags=new Vector(); - for(int i=0;i(); - TagExpressionList tel=td.getTag(td.getParameter(i)); - if (tel!=null) - for(int j=0;j[]) new HashSet[task.numParameters()]; + this.map=new Hashtable>(); + this.tags=new Vector(); + for(int i=0; i(); + TagExpressionList tel=td.getTag(td.getParameter(i)); + if (tel!=null) + for(int j=0; j()); - } - map.get(fts.fs).add(fts); - return new TaskQueueIterator(this, index, fts); + } + + public TaskQueueIterator enqueue(int index, FlagTagState fts) { + parameterset[index].add(fts); + if (!map.containsKey(fts.fs)) { + map.put(fts.fs, new Vector()); } + map.get(fts.fs).add(fts); + return new TaskQueueIterator(this, index, fts); + } } diff --git a/Robust/src/Analysis/TaskStateAnalysis/TaskQueueIterator.java b/Robust/src/Analysis/TaskStateAnalysis/TaskQueueIterator.java index 7e6898aa..c4129561 100644 --- a/Robust/src/Analysis/TaskStateAnalysis/TaskQueueIterator.java +++ b/Robust/src/Analysis/TaskStateAnalysis/TaskQueueIterator.java @@ -5,150 +5,150 @@ import IR.Flat.*; import java.util.*; public class TaskQueueIterator { - TaskQueue tq; - int index; - FlagTagState fts; - FlagTagState ftsarray[]; - Hashtable tsarray; - Hashtable tsindexarray; - Iterator itarray[]; - boolean needit; - boolean needinit; + TaskQueue tq; + int index; + FlagTagState fts; + FlagTagState ftsarray[]; + Hashtable tsarray; + Hashtable tsindexarray; + Iterator itarray[]; + boolean needit; + boolean needinit; - public TaskQueueIterator(TaskQueue tq, int index, FlagTagState fts) { - this.tq=tq; - this.index=index; - this.fts=fts; - this.ftsarray=new FlagTagState[tq.numParameters()]; - this.ftsarray[index]=fts; - this.tsarray=new Hashtable(); - this.tsindexarray=new Hashtable(); - this.itarray=(Iterator[]) new Iterator[tq.numParameters()]; - needit=false; - needinit=true; - init(); - } - - private void init() { - for(int i=ftsarray.length-1;i>=0;i--) { - if (i!=index) - 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;j(); + this.tsindexarray=new Hashtable(); + this.itarray=(Iterator[]) new Iterator[tq.numParameters()]; + needit=false; + needinit=true; + init(); + } + + private void init() { + for(int i=ftsarray.length-1; i>=0; i--) { + if (i!=index) + 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; - } else - 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;k0 ? tel.numTags()-1 : 0; + needinit=false; + } else + 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 toprocess; - HashSet discovered; - Hashtable tasktable; - Hashtable> tsresults; - Hashtable> fsresults; - - - /** - * Class Constructor - * - */ - public TaskTagAnalysis(State state, TagAnalysis taganalysis) { - this.state=state; - this.typeutil=new TypeUtil(state); - this.taganalysis=taganalysis; - this.flaginfo=new FlagInfo(state); - this.toprocess=new HashSet(); - this.discovered=new HashSet(); - this.tasktable=new Hashtable(); - this.tsresults=new Hashtable>(); - this.fsresults=new Hashtable>(); - - - for(Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();taskit.hasNext();) { - TaskDescriptor td=(TaskDescriptor)taskit.next(); - tasktable.put(td, new TaskQueue(td)); - } - doAnalysis(); - doOutput(); + State state; + TagAnalysis taganalysis; + TypeUtil typeutil; + FlagInfo flaginfo; + HashSet toprocess; + HashSet discovered; + Hashtable tasktable; + Hashtable> tsresults; + Hashtable> fsresults; + + + /** + * Class Constructor + * + */ + public TaskTagAnalysis(State state, TagAnalysis taganalysis) { + this.state=state; + this.typeutil=new TypeUtil(state); + this.taganalysis=taganalysis; + this.flaginfo=new FlagInfo(state); + this.toprocess=new HashSet(); + this.discovered=new HashSet(); + this.tasktable=new Hashtable(); + this.tsresults=new Hashtable>(); + this.fsresults=new Hashtable>(); + + + for(Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator(); taskit.hasNext();) { + TaskDescriptor td=(TaskDescriptor)taskit.next(); + tasktable.put(td, new TaskQueue(td)); } - - private void doOutput() { - try { - for(Iterator 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); - } - 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); - } - } catch (Exception e) { - e.printStackTrace(); - } + doAnalysis(); + doOutput(); + } + + private void doOutput() { + try { + for(Iterator 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); + } + 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); + } + } catch (Exception e) { + e.printStackTrace(); } - - private void doAnalysis() { - toprocess.add(createInitialState()); - while(!toprocess.isEmpty()) { - TagState ts=toprocess.iterator().next(); - 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); - } - } + } + + private void doAnalysis() { + toprocess.add(createInitialState()); + while(!toprocess.isEmpty()) { + TagState ts=toprocess.iterator().next(); + 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); + } } - - private void processTask(TaskDescriptor td, TaskQueue tq, TagState ts) { - Set flagset=ts.getFS(); - for(Iterator fsit=flagset.iterator();fsit.hasNext();) { - FlagState fs=fsit.next(); - FlagTagState fts=new FlagTagState(ts, fs); - for(int i=0;i flagset=ts.getFS(); + for(Iterator fsit=flagset.iterator(); fsit.hasNext();) { + FlagState fs=fsit.next(); + FlagTagState fts=new FlagTagState(ts, fs); + for(int i=0; i computeInitialState(Hashtable> maintable, FlatNode fn) { - Hashtable table=new Hashtable(); - Hashtable tagtable=new Hashtable(); - for(int i=0;i prevtable=maintable.get(fn); - - //Iterator through the Tags - for(Iterator 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); - } - } - - //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); - } - } - } - return table; - } - - private void processFlatFlag(FlatFlagActionNode fn, Hashtable table, TaskDescriptor td) { - if (fn.getTaskType()==FlatFlagActionNode.PRE) { - throw new Error("Unsupported"); - } else if (fn.getTaskType()==FlatFlagActionNode.TASKEXIT) { - evalTaskExitNode(fn, table); - } else if (fn.getTaskType()==FlatFlagActionNode.NEWOBJECT) { - evalNewNode(fn, table, td); - } - } - - private void setFlag(ObjWrapper ow, FlagDescriptor fd, boolean value) { - HashSet newstate=new HashSet(); - Hashtable flagmap=new Hashtable(); - for(Iterator flagit=ow.fs.iterator();flagit.hasNext();) { - FlagState fs=flagit.next(); - FlagState fsnew=canonical(fs.setFlag(fd, value)); - newstate.add(fsnew); - flagmap.put(fs, fsnew); - } - - for(Iterator tagit=ow.tags.iterator();tagit.hasNext();) { - 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 computeInitialState(Hashtable> maintable, FlatNode fn) { + Hashtable table=new Hashtable(); + Hashtable tagtable=new Hashtable(); + for(int i=0; i prevtable=maintable.get(fn); + + //Iterator through the Tags + for(Iterator 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 { - if (!ow.tags.contains(twnew)) { - System.out.println("Tag not bound to object."); - return; - } + TagWrapper clonetag=((TagWrapper)prevtag).clone(); + tagtable.put((TagWrapper)prevtag, clonetag); + table.put(tmp, clonetag); } - HashSet newfsstates=new HashSet(); - Hashtable flagmap=new Hashtable(); - //Change the flag states - for(Iterator fsit=ow.fs.iterator();fsit.hasNext();) { - FlagState fs=fsit.next(); - FlagState[] fsnew=canonical(fs.setTag(tag, value)); - flagmap.put(fs, fsnew); - newfsstates.addAll(Arrays.asList(fsnew)); + } + + //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); } - for(Iterator tagit=ow.tags.iterator();tagit.hasNext();) { - 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 tagit=prevobj.tags.iterator(); tagit.hasNext();) { + TagWrapper tprev=tagit.next(); + TagWrapper t=tagtable.get(tprev); + currobj.tags.add(t); } - - { - HashSet 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=prevobj.fs.iterator(); flagit.hasNext();) { + FlagState fs=flagit.next(); + currobj.fs.add(fs); } - - if (value) - ow.tags.add(twnew); - else - ow.tags.remove(twnew); - ow.fs=newfsstates; + } } - - private void evalTaskExitNode(FlatFlagActionNode fn, Hashtable table) { - //Process clears first - for(Iterator it_ttp=fn.getTempTagPairs();it_ttp.hasNext();) { - TempTagPair ttp=it_ttp.next(); - TempDescriptor tmp=ttp.getTemp(); - TagDescriptor tag=ttp.getTag(); - TempDescriptor tagtmp=ttp.getTagTemp(); - TagWrapper tagw=(TagWrapper)table.get(tagtmp); - boolean newtagstate=fn.getTagChange(ttp); - ObjWrapper ow=(ObjWrapper)table.get(tmp); - if (!newtagstate) - setTag(ow, tagw, tag, newtagstate); - } - - //Do the flags next - for(Iterator it_tfp=fn.getTempFlagPairs();it_tfp.hasNext();) { - TempFlagPair tfp=it_tfp.next(); - TempDescriptor tmp=tfp.getTemp(); - FlagDescriptor fd=tfp.getFlag(); - boolean newflagstate=fn.getFlagChange(tfp); - ObjWrapper ow=(ObjWrapper)table.get(tmp); - setFlag(ow, fd, newflagstate); - } - - //Process sets last - for(Iterator it_ttp=fn.getTempTagPairs();it_ttp.hasNext();) { - TempTagPair ttp=(TempTagPair)it_ttp.next(); - TempDescriptor tmp=ttp.getTemp(); - TagDescriptor tag=ttp.getTag(); - TempDescriptor tagtmp=ttp.getTagTemp(); - TagWrapper tagw=(TagWrapper)table.get(tagtmp); - boolean newtagstate=fn.getTagChange(ttp); - ObjWrapper ow=(ObjWrapper)table.get(tmp); - if (newtagstate) - setTag(ow, tagw, tag, newtagstate); - } + return table; + } + + private void processFlatFlag(FlatFlagActionNode fn, Hashtable table, TaskDescriptor td) { + if (fn.getTaskType()==FlatFlagActionNode.PRE) { + throw new Error("Unsupported"); + } else if (fn.getTaskType()==FlatFlagActionNode.TASKEXIT) { + evalTaskExitNode(fn, table); + } else if (fn.getTaskType()==FlatFlagActionNode.NEWOBJECT) { + evalNewNode(fn, table, td); + } + } + + private void setFlag(ObjWrapper ow, FlagDescriptor fd, boolean value) { + HashSet newstate=new HashSet(); + Hashtable flagmap=new Hashtable(); + for(Iterator flagit=ow.fs.iterator(); flagit.hasNext();) { + FlagState fs=flagit.next(); + FlagState fsnew=canonical(fs.setFlag(fd, value)); + newstate.add(fsnew); + flagmap.put(fs, fsnew); } - private void evalNewNode(FlatFlagActionNode fn, Hashtable table, TaskDescriptor td) { - TempDescriptor fntemp=null; - { - /* Compute type */ - Iterator it=fn.getTempFlagPairs(); - if (it.hasNext()) { - TempFlagPair tfp=(TempFlagPair)it.next(); - fntemp=tfp.getTemp(); + for(Iterator tagit=ow.tags.iterator(); tagit.hasNext();) { + 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 { - it=fn.getTempTagPairs(); - if (!it.hasNext()) - throw new Error(); - TempTagPair ttp=(TempTagPair)it.next(); - fntemp=ttp.getTemp(); + 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 it_tfp=fn.getTempFlagPairs();it_tfp.hasNext();) { - TempFlagPair tfp=it_tfp.next(); - TempDescriptor tmp=tfp.getTemp(); - FlagDescriptor fd=tfp.getFlag(); - boolean newflagstate=fn.getFlagChange(tfp); - assert(ow==table.get(tmp)); - setFlag(ow, fd, newflagstate); - } - //Process sets next - for(Iterator it_ttp=fn.getTempTagPairs();it_ttp.hasNext();) { - TempTagPair ttp=(TempTagPair)it_ttp.next(); - TempDescriptor tmp=ttp.getTemp(); - TagDescriptor tag=ttp.getTag(); - TempDescriptor tagtmp=ttp.getTagTemp(); - TagWrapper tagw=(TagWrapper)table.get(tagtmp); - boolean newtagstate=fn.getTagChange(ttp); - assert(ow==table.get(tmp)); - if (newtagstate) - setTag(ow, tagw, tag, newtagstate); - else - throw new Error("Can't clear tag in newly allocated object"); - } - for(Iterator fsit=ow.fs.iterator();fsit.hasNext();) { - FlagState fs2=fsit.next(); - fs2.addAllocatingTask(td); - TagState ts2=new TagState(fs2.getClassDescriptor()); - ts2.addFS(fs2); - ts2=canonical(ts2); - ts2.addSource(td); - addresult(fs2.getClassDescriptor(), ts2); - if (!discovered.contains(ts2)) { - discovered.add(ts2); - toprocess.add(ts2); + } + tw.ts=newstates; + } + } + + private void setTag(ObjWrapper ow, TagWrapper twnew, TagDescriptor tag, boolean value) { + if (value) { + if (ow.tags.contains(twnew)) { + System.out.println("Tag already bound to object."); + return; + } + } else { + if (!ow.tags.contains(twnew)) { + System.out.println("Tag not bound to object."); + return; + } + } + HashSet newfsstates=new HashSet(); + Hashtable flagmap=new Hashtable(); + //Change the flag states + for(Iterator fsit=ow.fs.iterator(); fsit.hasNext();) { + FlagState fs=fsit.next(); + FlagState[] fsnew=canonical(fs.setTag(tag, value)); + flagmap.put(fs, fsnew); + newfsstates.addAll(Arrays.asList(fsnew)); + } + for(Iterator tagit=ow.tags.iterator(); tagit.hasNext();) { + 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 table, TaskDescriptor td) { - TempDescriptor tmp=fn.getDst(); - if (table.containsKey(tmp)) { - recordtagchange((TagWrapper)table.get(tmp), td); + { + HashSet 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()); - tsresults.get(td).add(ts); + if (value) + ow.tags.add(twnew); + else + ow.tags.remove(twnew); + ow.fs=newfsstates; + } + + private void evalTaskExitNode(FlatFlagActionNode fn, Hashtable table) { + //Process clears first + for(Iterator it_ttp=fn.getTempTagPairs(); it_ttp.hasNext();) { + TempTagPair ttp=it_ttp.next(); + TempDescriptor tmp=ttp.getTemp(); + TagDescriptor tag=ttp.getTag(); + TempDescriptor tagtmp=ttp.getTagTemp(); + TagWrapper tagw=(TagWrapper)table.get(tagtmp); + boolean newtagstate=fn.getTagChange(ttp); + ObjWrapper ow=(ObjWrapper)table.get(tmp); + if (!newtagstate) + setTag(ow, tagw, tag, newtagstate); } - private void addresult(ClassDescriptor cd, TagState ts) { - if (!fsresults.containsKey(cd)) - fsresults.put(cd, new HashSet()); - fsresults.get(cd).add(ts); + //Do the flags next + for(Iterator it_tfp=fn.getTempFlagPairs(); it_tfp.hasNext();) { + TempFlagPair tfp=it_tfp.next(); + TempDescriptor tmp=tfp.getTemp(); + FlagDescriptor fd=tfp.getFlag(); + boolean newflagstate=fn.getFlagChange(tfp); + ObjWrapper ow=(ObjWrapper)table.get(tmp); + setFlag(ow, fd, newflagstate); } - public void recordtagchange(TagWrapper tw, TaskDescriptor td) { - TagState init=tw.initts; - for(Iterator tsit=tw.ts.iterator(); tsit.hasNext();) { - TagState ts=tsit.next(); - if (init==null) { - ts.addSource(td); - } else { - TagEdge te=new TagEdge(ts, td); - if (!init.containsEdge(te)) { - init.addEdge(te); - } - } - if (ts.getTag()!=null) - addresult(ts.getTag(), ts); - else - addresult(ts.getClassDesc(), ts); - if (!discovered.contains(ts)) { - discovered.add(ts); - toprocess.add(ts); - } - } + //Process sets last + for(Iterator it_ttp=fn.getTempTagPairs(); it_ttp.hasNext();) { + TempTagPair ttp=(TempTagPair)it_ttp.next(); + TempDescriptor tmp=ttp.getTemp(); + TagDescriptor tag=ttp.getTag(); + TempDescriptor tagtmp=ttp.getTagTemp(); + TagWrapper tagw=(TagWrapper)table.get(tagtmp); + boolean newtagstate=fn.getTagChange(ttp); + ObjWrapper ow=(ObjWrapper)table.get(tmp); + if (newtagstate) + setTag(ow, tagw, tag, newtagstate); } + } + + private void evalNewNode(FlatFlagActionNode fn, Hashtable table, TaskDescriptor td) { + TempDescriptor fntemp=null; + { + /* Compute type */ + Iterator it=fn.getTempFlagPairs(); + if (it.hasNext()) { + TempFlagPair tfp=(TempFlagPair)it.next(); + fntemp=tfp.getTemp(); + } else { + it=fn.getTempTagPairs(); + if (!it.hasNext()) + throw new Error(); + TempTagPair ttp=(TempTagPair)it.next(); + fntemp=ttp.getTemp(); + } + } + FlagState fs=canonical(new FlagState(fntemp.getType().getClassDesc())); + ObjWrapper ow=new ObjWrapper(); + ow.fs.add(fs); + table.put(fntemp, ow); + //Do the flags first + for(Iterator it_tfp=fn.getTempFlagPairs(); it_tfp.hasNext();) { + TempFlagPair tfp=it_tfp.next(); + TempDescriptor tmp=tfp.getTemp(); + FlagDescriptor fd=tfp.getFlag(); + boolean newflagstate=fn.getFlagChange(tfp); + assert(ow==table.get(tmp)); + setFlag(ow, fd, newflagstate); + } + //Process sets next + for(Iterator it_ttp=fn.getTempTagPairs(); it_ttp.hasNext();) { + TempTagPair ttp=(TempTagPair)it_ttp.next(); + TempDescriptor tmp=ttp.getTemp(); + TagDescriptor tag=ttp.getTag(); + TempDescriptor tagtmp=ttp.getTagTemp(); + TagWrapper tagw=(TagWrapper)table.get(tagtmp); + boolean newtagstate=fn.getTagChange(ttp); + assert(ow==table.get(tmp)); + if (newtagstate) + setTag(ow, tagw, tag, newtagstate); + else + throw new Error("Can't clear tag in newly allocated object"); + } + for(Iterator fsit=ow.fs.iterator(); fsit.hasNext();) { + FlagState fs2=fsit.next(); + fs2.addAllocatingTask(td); + TagState ts2=new TagState(fs2.getClassDescriptor()); + ts2.addFS(fs2); + ts2=canonical(ts2); + ts2.addSource(td); + addresult(fs2.getClassDescriptor(), ts2); + if (!discovered.contains(ts2)) { + discovered.add(ts2); + toprocess.add(ts2); + } + } + } - private void recordobj(ObjWrapper ow, TaskDescriptor td) { - for(Iterator twit=ow.tags.iterator();twit.hasNext();) { - TagWrapper tw=twit.next(); - recordtagchange(tw, td); + private void processFlatTag(FlatTagDeclaration fn, Hashtable table, TaskDescriptor td) { + TempDescriptor tmp=fn.getDst(); + if (table.containsKey(tmp)) { + recordtagchange((TagWrapper)table.get(tmp), td); + } + TagDescriptor tag=fn.getType(); + TagState ts=canonical(new TagState(tag)); + TagWrapper tw=new TagWrapper(ts); + tw.initts=null; + table.put(tmp, tw); + } + + private void addresult(TagDescriptor td, TagState ts) { + if (!tsresults.containsKey(td)) + tsresults.put(td, new HashSet()); + tsresults.get(td).add(ts); + } + + private void addresult(ClassDescriptor cd, TagState ts) { + if (!fsresults.containsKey(cd)) + fsresults.put(cd, new HashSet()); + fsresults.get(cd).add(ts); + } + + public void recordtagchange(TagWrapper tw, TaskDescriptor td) { + TagState init=tw.initts; + for(Iterator tsit=tw.ts.iterator(); tsit.hasNext();) { + TagState ts=tsit.next(); + if (init==null) { + ts.addSource(td); + } else { + TagEdge te=new TagEdge(ts, td); + if (!init.containsEdge(te)) { + init.addEdge(te); } + } + if (ts.getTag()!=null) + addresult(ts.getTag(), ts); + else + addresult(ts.getClassDesc(), ts); + if (!discovered.contains(ts)) { + discovered.add(ts); + toprocess.add(ts); + } } + } - private void processFlatCall(FlatCall fc, Hashtable table) { - //Do nothing for now + private void recordobj(ObjWrapper ow, TaskDescriptor td) { + for(Iterator twit=ow.tags.iterator(); twit.hasNext();) { + TagWrapper tw=twit.next(); + recordtagchange(tw, td); } - - private void processFlatReturnNode(FlatReturnNode fr, Hashtable table, TaskDescriptor td) { - for(Iterator tmpit=table.keySet().iterator();tmpit.hasNext();) { - TempDescriptor tmp=tmpit.next(); - Wrapper w=table.get(tmp); - if (w instanceof TagWrapper) { - TagWrapper tw=(TagWrapper)w; - recordtagchange(tw, td); - } else { - ObjWrapper ow=(ObjWrapper)w; - recordobj(ow, td); - } - } + } + + private void processFlatCall(FlatCall fc, Hashtable table) { + //Do nothing for now + } + + private void processFlatReturnNode(FlatReturnNode fr, Hashtable table, TaskDescriptor td) { + for(Iterator tmpit=table.keySet().iterator(); tmpit.hasNext();) { + TempDescriptor tmp=tmpit.next(); + Wrapper w=table.get(tmp); + if (w instanceof TagWrapper) { + TagWrapper tw=(TagWrapper)w; + recordtagchange(tw, td); + } else { + ObjWrapper ow=(ObjWrapper)w; + recordobj(ow, td); + } } + } - private boolean equivalent(Hashtable table1, Hashtable table2) { - Hashtable emap=new Hashtable(); + private boolean equivalent(Hashtable table1, Hashtable table2) { + Hashtable emap=new Hashtable(); - if (table1.keySet().size()!=table2.keySet().size()) - return false; + if (table1.keySet().size()!=table2.keySet().size()) + return false; - for(Iterator tmpit=table1.keySet().iterator();tmpit.hasNext();) { - TempDescriptor tmp=tmpit.next(); - if (table2.containsKey(tmp)) { - emap.put(table1.get(tmp), table2.get(tmp)); - } else return false; - } - - for(Iterator tmpit=table1.keySet().iterator();tmpit.hasNext();) { - TempDescriptor tmp=tmpit.next(); - 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; - - } 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; - } - } - } - return true; + for(Iterator tmpit=table1.keySet().iterator(); tmpit.hasNext();) { + TempDescriptor tmp=tmpit.next(); + if (table2.containsKey(tmp)) { + emap.put(table1.get(tmp), table2.get(tmp)); + } else return false; } - private void doAnalysis(TaskBinding tb) { - TaskDescriptor td=tb.tqi.tq.getTask(); - FlatMethod fm=state.getMethodFlat(td); - Hashtable> wtable=new Hashtable>(); - wtable.put(fm, buildinittable(tb, fm)); - HashSet visited=new HashSet(); - HashSet tovisit=new HashSet(); - tovisit.add(fm.getNext(0)); - while(!tovisit.isEmpty()) { - FlatNode fn=tovisit.iterator().next(); - tovisit.remove(fn); - visited.add(fn); - Hashtable table=computeInitialState(wtable, fn); - switch(fn.kind()) { - case FKind.FlatFlagActionNode: - processFlatFlag((FlatFlagActionNode)fn, table, td); - break; - case FKind.FlatTagDeclaration: - processFlatTag((FlatTagDeclaration)fn, table, td); - break; - case FKind.FlatCall: - processFlatCall((FlatCall)fn, table); - break; - case FKind.FlatReturnNode: - processFlatReturnNode((FlatReturnNode)fn, table, td); - break; - default: - } - - if (!equivalent(table, wtable.get(fn))) { - wtable.put(fn, table); - for(int i=0;i tmpit=table1.keySet().iterator(); tmpit.hasNext();) { + TempDescriptor tmp=tmpit.next(); + 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; + + } 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; } - + } } - - private Hashtable buildinittable(TaskBinding tb, FlatMethod fm) { - Hashtable table=new Hashtable(); - Vector tagtmps=tb.tqi.tq.tags; - for(int i=0;i> wtable=new Hashtable>(); + wtable.put(fm, buildinittable(tb, fm)); + HashSet visited=new HashSet(); + HashSet tovisit=new HashSet(); + tovisit.add(fm.getNext(0)); + while(!tovisit.isEmpty()) { + FlatNode fn=tovisit.iterator().next(); + tovisit.remove(fn); + visited.add(fn); + Hashtable table=computeInitialState(wtable, fn); + switch(fn.kind()) { + case FKind.FlatFlagActionNode: + processFlatFlag((FlatFlagActionNode)fn, table, td); + break; + + case FKind.FlatTagDeclaration: + processFlatTag((FlatTagDeclaration)fn, table, td); + break; + + case FKind.FlatCall: + processFlatCall((FlatCall)fn, table); + break; + + case FKind.FlatReturnNode: + processFlatReturnNode((FlatReturnNode)fn, table, td); + break; + + default: + } + + if (!equivalent(table, wtable.get(fn))) { + wtable.put(fn, table); + for(int i=0; i buildinittable(TaskBinding tb, FlatMethod fm) { + Hashtable table=new Hashtable(); + Vector tagtmps=tb.tqi.tq.tags; + for(int i=0; i='0'&&ch<='9') - return ch-'0'; - else if (ch>='a'&&ch<='z') { - int val=(ch-'a')+10; - if (val='A'&&ch<='Z') { - int val=(ch-'A')+10; - if (val='0'&&ch<='9') + return ch-'0'; + else if (ch>='a'&&ch<='z') { + int val=(ch-'a')+10; + if (val='A'&&ch<='Z') { + int val=(ch-'A')+10; + if (val(loadFactor*table.length)) { - //Resize the table - resize(); - } - int bin=hash(key); - HashEntry ptr=table[bin]; - while(ptr!=null) { - if (ptr.key.equals(key)) { - Object oldvalue=ptr.value; - ptr.value=value; - return oldvalue; - } - ptr=ptr.next; - } - HashEntry he=new HashEntry(); - he.value=value; - he.key=key; - he.next=table[bin]; - table[bin]=he; - return null; + Object put(Object key, Object value) { + numItems++; + if (numItems>(loadFactor*table.length)) { + //Resize the table + resize(); + } + int bin=hash(key); + HashEntry ptr=table[bin]; + while(ptr!=null) { + if (ptr.key.equals(key)) { + Object oldvalue=ptr.value; + ptr.value=value; + return oldvalue; + } + ptr=ptr.next; } + HashEntry he=new HashEntry(); + he.value=value; + he.key=key; + he.next=table[bin]; + table[bin]=he; + return null; + } } diff --git a/Robust/src/ClassLibrary/HashMapIterator.java b/Robust/src/ClassLibrary/HashMapIterator.java index 70e1a405..48dc9137 100644 --- a/Robust/src/ClassLibrary/HashMapIterator.java +++ b/Robust/src/ClassLibrary/HashMapIterator.java @@ -1,46 +1,46 @@ class HashMapIterator { - HashMap map; - int type; - int bin; - HashEntry he; + HashMap map; + int type; + int bin; + HashEntry he; - public HashMapIterator(HashMap map, int type) { - this.map=map; - this.type=type; - this.bin=0; - this.he=null; - } + public HashMapIterator(HashMap map, int type) { + this.map=map; + this.type=type; + this.bin=0; + this.he=null; + } - public boolean hasNext() { - if (he!=null&&he.next!=null) - return true; - int i=bin; - while((i0) - h+="."; - h+=(int)address[i]; - } - return h; + addresses = new InetAddress[iplist.length]; + + for (int i = 0; i < iplist.length; i++) { + addresses[i] = new InetAddress(iplist[i], hostname); } + return addresses; + } + + public static native byte[][] getHostByName(byte[] hostname); + + public String toString() { + String h=hostname+" "; + for (int i=0; i0) + h+="."; + h+=(int)address[i]; + } + return h; + } } diff --git a/Robust/src/ClassLibrary/InputStream.java b/Robust/src/ClassLibrary/InputStream.java index e3027049..a02b9dbd 100644 --- a/Robust/src/ClassLibrary/InputStream.java +++ b/Robust/src/ClassLibrary/InputStream.java @@ -1,12 +1,12 @@ public class InputStream { - public int read() { - System.printString("called unimplemented read\n"); - } - public int read(byte[] b) { - System.printString("called unimplemented read(byte[]b)\n"); - } + public int read() { + System.printString("called unimplemented read\n"); + } + public int read(byte[] b) { + System.printString("called unimplemented read(byte[]b)\n"); + } - public void close() { - System.printString("Called unimplemented close()\n"); - } + public void close() { + System.printString("Called unimplemented close()\n"); + } } diff --git a/Robust/src/ClassLibrary/Integer.java b/Robust/src/ClassLibrary/Integer.java index 2358adb7..b287800f 100644 --- a/Robust/src/ClassLibrary/Integer.java +++ b/Robust/src/ClassLibrary/Integer.java @@ -1,60 +1,60 @@ public class Integer { - private int value; + private int value; - public Integer(int value) { - this.value=value; - } + public Integer(int value) { + this.value=value; + } - public Integer(String str) { - value=Integer.parseInt(str, 10); - } + public Integer(String str) { + value=Integer.parseInt(str, 10); + } - public int intValue() { - return value; - } + public int intValue() { + return value; + } - public static int parseInt(String str) { - return Integer.parseInt(str, 10); - } + public static int parseInt(String str) { + return Integer.parseInt(str, 10); + } - public static int parseInt(String str, int radix) { - int value=0; - boolean isNeg=false; - int start=0; - byte[] chars=str.getBytes(); - - while(chars[start]==' '||chars[start]=='\t') - start++; - - if (chars[start]=='-') { - isNeg=true; - start++; - } - boolean cont=true; - for(int i=start;cont&&i='0'&&b<='9') - val=b-'0'; - else if (b>='a'&&b<='z') - val=10+b-'a'; - else if (b>='A'&&b<='Z') - val=10+b-'A'; - else { - cont=false; - } - if (cont) { - if (val>=radix) - System.error(); - value=value*radix+val; - } - } - if (isNeg) - value=-value; - return value; - } + public static int parseInt(String str, int radix) { + int value=0; + boolean isNeg=false; + int start=0; + byte[] chars=str.getBytes(); + + while(chars[start]==' '||chars[start]=='\t') + start++; - public String toString() { - return String.valueOf(value); + if (chars[start]=='-') { + isNeg=true; + start++; + } + boolean cont=true; + for(int i=start; cont&&i='0'&&b<='9') + val=b-'0'; + else if (b>='a'&&b<='z') + val=10+b-'a'; + else if (b>='A'&&b<='Z') + val=10+b-'A'; + else { + cont=false; + } + if (cont) { + if (val>=radix) + System.error(); + value=value*radix+val; + } } + if (isNeg) + value=-value; + return value; + } + + public String toString() { + return String.valueOf(value); + } } diff --git a/Robust/src/ClassLibrary/Math.java b/Robust/src/ClassLibrary/Math.java index cd38a2e8..15e3ce24 100644 --- a/Robust/src/ClassLibrary/Math.java +++ b/Robust/src/ClassLibrary/Math.java @@ -1,35 +1,35 @@ public class Math { - //public static final double PI=3.14159265358979323846; - - public static double fabs(double x) { - if (x < 0) { - return -x; - } else { - return x; - } - } - - public static float abs(float a) { - if (a<0) - return -a; - else return a; + //public static final double PI=3.14159265358979323846; + + public static double fabs(double x) { + if (x < 0) { + return -x; + } else { + return x; } + } + + public static float abs(float a) { + if (a<0) + return -a; + else return a; + } + + public static native double sin(double a); + public static native double cos(double a); + public static native double asin(double a); + public static native double acos(double a); + public static native double tan(double a); + public static native double atan(double a); + public static native double exp(double a); + public static native double sqrt(double a); + public static native double log(double a); + public static native double pow(double a, double b); - public static native double sin(double a); - public static native double cos(double a); - public static native double asin(double a); - public static native double acos(double a); - public static native double tan(double a); - public static native double atan(double a); - public static native double exp(double a); - public static native double sqrt(double a); - public static native double log(double a); - public static native double pow(double a, double b); - - public static native float sinf(float a); - public static native float cosf(float a); - public static native float expf(float a); - public static native float sqrtf(float a); - public static native float logf(float a); - public static native float powf(float a, float b); + public static native float sinf(float a); + public static native float cosf(float a); + public static native float expf(float a); + public static native float sqrtf(float a); + public static native float logf(float a); + public static native float powf(float a, float b); } diff --git a/Robust/src/ClassLibrary/Object.java b/Robust/src/ClassLibrary/Object.java index e968e17b..f2d05d25 100644 --- a/Robust/src/ClassLibrary/Object.java +++ b/Robust/src/ClassLibrary/Object.java @@ -1,30 +1,30 @@ public class Object { - public native int nativehashCode(); - private int cachedCode;//first field has to be a primitive - private boolean cachedHash; + public native int nativehashCode(); + private int cachedCode; //first field has to be a primitive + private boolean cachedHash; - /* DO NOT USE ANY OF THESE - THEY ARE FOR IMPLEMENTING TAGS */ - private Object tags; + /* DO NOT USE ANY OF THESE - THEY ARE FOR IMPLEMENTING TAGS */ + private Object tags; - public int hashCode() { - if (!cachedHash) { - cachedCode=nativehashCode(); - cachedHash=true; - } - return cachedCode; + public int hashCode() { + if (!cachedHash) { + cachedCode=nativehashCode(); + cachedHash=true; } + return cachedCode; + } - /* DON'T USE THIS METHOD UNLESS NECESSARY */ - /* WE WILL DEPRECATE IT AS SOON AS INSTANCEOF WORKS */ - public native int getType(); + /* DON'T USE THIS METHOD UNLESS NECESSARY */ + /* WE WILL DEPRECATE IT AS SOON AS INSTANCEOF WORKS */ + public native int getType(); - public String toString() { - return "Object"+hashCode(); - } + public String toString() { + return "Object"+hashCode(); + } - public boolean equals(Object o) { - if (o==this) - return true; - return false; - } + public boolean equals(Object o) { + if (o==this) + return true; + return false; + } } diff --git a/Robust/src/ClassLibrary/ObjectJava.java b/Robust/src/ClassLibrary/ObjectJava.java index 59a62f4a..a9bf6f4d 100644 --- a/Robust/src/ClassLibrary/ObjectJava.java +++ b/Robust/src/ClassLibrary/ObjectJava.java @@ -1,33 +1,33 @@ public class Object { - public int cachedCode; //first field has to be a primitive - public boolean cachedHash; + public int cachedCode; //first field has to be a primitive + public boolean cachedHash; - public native int nativehashCode(); - private Object nextlockobject; - private Object prevlockobject; + public native int nativehashCode(); + private Object nextlockobject; + private Object prevlockobject; - public int hashCode() { - if (!cachedHash) { - cachedCode=nativehashCode(); - cachedHash=true; - } - return cachedCode; + public int hashCode() { + if (!cachedHash) { + cachedCode=nativehashCode(); + cachedHash=true; } + return cachedCode; + } - /* DON'T USE THIS METHOD UNLESS NECESSARY */ - /* WE WILL DEPRECATE IT AS SOON AS INSTANCEOF WORKS */ - public native int getType(); + /* DON'T USE THIS METHOD UNLESS NECESSARY */ + /* WE WILL DEPRECATE IT AS SOON AS INSTANCEOF WORKS */ + public native int getType(); - public native int MonitorEnter(); - public native int MonitorExit(); + public native int MonitorEnter(); + public native int MonitorExit(); - public String toString() { - return "Object"+hashCode(); - } + public String toString() { + return "Object"+hashCode(); + } - public boolean equals(Object o) { - if (o==this) - return true; - return false; - } + public boolean equals(Object o) { + if (o==this) + return true; + return false; + } } diff --git a/Robust/src/ClassLibrary/ObjectJavaDSM.java b/Robust/src/ClassLibrary/ObjectJavaDSM.java index c0e9fc42..308e81f3 100644 --- a/Robust/src/ClassLibrary/ObjectJavaDSM.java +++ b/Robust/src/ClassLibrary/ObjectJavaDSM.java @@ -1,30 +1,30 @@ public class Object { - public int cachedCode; //first field has to be a primitive - public boolean cachedHash; - public Object nextobject; /* Oid */ - public Object localcopy; + public int cachedCode; //first field has to be a primitive + public boolean cachedHash; + public Object nextobject; /* Oid */ + public Object localcopy; - public native int nativehashCode(); + public native int nativehashCode(); - public int hashCode() { - if (!cachedHash) { - cachedCode=nativehashCode(); - cachedHash=true; - } - return cachedCode; + public int hashCode() { + if (!cachedHash) { + cachedCode=nativehashCode(); + cachedHash=true; } + return cachedCode; + } - /* DON'T USE THIS METHOD UNLESS NECESSARY */ - /* WE WILL DEPRECATE IT AS SOON AS INSTANCEOF WORKS */ - public native int getType(); + /* DON'T USE THIS METHOD UNLESS NECESSARY */ + /* WE WILL DEPRECATE IT AS SOON AS INSTANCEOF WORKS */ + public native int getType(); - public String toString() { - return "Object"+hashCode(); - } + public String toString() { + return "Object"+hashCode(); + } - public boolean equals(Object o) { - if (o==this) - return true; - return false; - } + public boolean equals(Object o) { + if (o==this) + return true; + return false; + } } diff --git a/Robust/src/ClassLibrary/ObjectJavaNT.java b/Robust/src/ClassLibrary/ObjectJavaNT.java index 2d768eb6..4968cfa3 100644 --- a/Robust/src/ClassLibrary/ObjectJavaNT.java +++ b/Robust/src/ClassLibrary/ObjectJavaNT.java @@ -1,28 +1,28 @@ public class Object { - public int cachedCode; //first field has to be a primitive - public boolean cachedHash; + public int cachedCode; //first field has to be a primitive + public boolean cachedHash; - public native int nativehashCode(); + public native int nativehashCode(); - public int hashCode() { - if (!cachedHash) { - cachedCode=nativehashCode(); - cachedHash=true; - } - return cachedCode; + public int hashCode() { + if (!cachedHash) { + cachedCode=nativehashCode(); + cachedHash=true; } + return cachedCode; + } - /* DON'T USE THIS METHOD UNLESS NECESSARY */ - /* WE WILL DEPRECATE IT AS SOON AS INSTANCEOF WORKS */ - public native int getType(); + /* DON'T USE THIS METHOD UNLESS NECESSARY */ + /* WE WILL DEPRECATE IT AS SOON AS INSTANCEOF WORKS */ + public native int getType(); - public String toString() { - return "Object"+hashCode(); - } + public String toString() { + return "Object"+hashCode(); + } - public boolean equals(Object o) { - if (o==this) - return true; - return false; - } + public boolean equals(Object o) { + if (o==this) + return true; + return false; + } } diff --git a/Robust/src/ClassLibrary/OutputStream.java b/Robust/src/ClassLibrary/OutputStream.java index eab22f24..eee7fce6 100644 --- a/Robust/src/ClassLibrary/OutputStream.java +++ b/Robust/src/ClassLibrary/OutputStream.java @@ -1,23 +1,23 @@ public class OutputStream { - public OutputStream() { - } + public OutputStream() { + } - public void write(int ch) { - System.printString("Called unimplemented write(int)\n"); - } + public void write(int ch) { + System.printString("Called unimplemented write(int)\n"); + } - public void write(byte[] b) { - System.printString("Called unimplemented write(byte[])\n"); - } + public void write(byte[] b) { + System.printString("Called unimplemented write(byte[])\n"); + } - public void write(byte[] b, int off, int len) { - System.printString("Called unimplemented write(byte[],int,int)\n"); - } + public void write(byte[] b, int off, int len) { + System.printString("Called unimplemented write(byte[],int,int)\n"); + } - public void flush() { - } - - public void close() { - System.printString("Called unimplemented close()\n"); - } + public void flush() { + } + + public void close() { + System.printString("Called unimplemented close()\n"); + } } diff --git a/Robust/src/ClassLibrary/OutputStreamWriter.java b/Robust/src/ClassLibrary/OutputStreamWriter.java index 480b78a7..6121da19 100644 --- a/Robust/src/ClassLibrary/OutputStreamWriter.java +++ b/Robust/src/ClassLibrary/OutputStreamWriter.java @@ -1,14 +1,14 @@ public class OutputStreamWriter extends Writer { - OutputStream fos; - public OutputStreamWriter(OutputStream fos) { - this.fos=fos; - } + OutputStream fos; + public OutputStreamWriter(OutputStream fos) { + this.fos=fos; + } - public void write(String s) { - fos.write(s.getBytes()); - } + public void write(String s) { + fos.write(s.getBytes()); + } - public void flush() { - fos.flush(); - } + public void flush() { + fos.flush(); + } } diff --git a/Robust/src/ClassLibrary/ServerSocket.java b/Robust/src/ClassLibrary/ServerSocket.java index 465ad340..723e886c 100644 --- a/Robust/src/ClassLibrary/ServerSocket.java +++ b/Robust/src/ClassLibrary/ServerSocket.java @@ -1,37 +1,38 @@ public class ServerSocket { - /* Socket pending flag */ - external flag SocketPending; - /* File Descriptor */ - int fd; - - private native int createSocket(int port); - - public ServerSocket(int port) { - this.fd=createSocket(port); - } - - public Socket accept() { - Socket s=new Socket(); - int newfd=nativeaccept(s); - s.setFD(newfd); - return s; - } - - public Socket accept(tag td) { - Socket s=new Socket(){}{td}; - int newfd=nativeaccept(s); - s.setFD(newfd); - return s; - } - - /* Lets caller pass in their own Socket object. */ - public void accept(Socket s) { - int newfd=nativeaccept(s); - s.setFD(newfd); - } - - private native int nativeaccept(Socket s); - - public void close(); + /* Socket pending flag */ + external flag SocketPending; + /* File Descriptor */ + int fd; + + private native int createSocket(int port); + + public ServerSocket(int port) { + this.fd=createSocket(port); + } + + public Socket accept() { + Socket s=new Socket(); + int newfd=nativeaccept(s); + s.setFD(newfd); + return s; + } + + public Socket accept(tag td) { + Socket s=new Socket() { + } {td}; + int newfd=nativeaccept(s); + s.setFD(newfd); + return s; + } + + /* Lets caller pass in their own Socket object. */ + public void accept(Socket s) { + int newfd=nativeaccept(s); + s.setFD(newfd); + } + + private native int nativeaccept(Socket s); + + public void close(); } diff --git a/Robust/src/ClassLibrary/ServerSocketJava.java b/Robust/src/ClassLibrary/ServerSocketJava.java index 30e9638a..1cf07f29 100644 --- a/Robust/src/ClassLibrary/ServerSocketJava.java +++ b/Robust/src/ClassLibrary/ServerSocketJava.java @@ -1,28 +1,28 @@ public class ServerSocket { - /* File Descriptor */ - int fd; + /* File Descriptor */ + int fd; - private native int createSocket(int port); + private native int createSocket(int port); - public ServerSocket(int port) { - this.fd=createSocket(port); - } - - public Socket accept() { - Socket s=new Socket(); - int newfd=nativeaccept(s); - s.setFD(newfd); - return s; - } + public ServerSocket(int port) { + this.fd=createSocket(port); + } - /* Lets caller pass in their own Socket object. */ - public void accept(Socket s) { - int newfd=nativeaccept(s); - s.setFD(newfd); - } + public Socket accept() { + Socket s=new Socket(); + int newfd=nativeaccept(s); + s.setFD(newfd); + return s; + } - private native int nativeaccept(Socket s); - - public void close(); + /* Lets caller pass in their own Socket object. */ + public void accept(Socket s) { + int newfd=nativeaccept(s); + s.setFD(newfd); + } + + private native int nativeaccept(Socket s); + + public void close(); } diff --git a/Robust/src/ClassLibrary/Signal.java b/Robust/src/ClassLibrary/Signal.java index 85e88325..3aa49b88 100644 --- a/Robust/src/ClassLibrary/Signal.java +++ b/Robust/src/ClassLibrary/Signal.java @@ -1,7 +1,7 @@ public class Signal { public Signal() { } - public native void nativeSigAction(); + public native void nativeSigAction(); public void sigAction() { nativeSigAction(); } diff --git a/Robust/src/ClassLibrary/Socket.java b/Robust/src/ClassLibrary/Socket.java index 452e395e..506c3272 100644 --- a/Robust/src/ClassLibrary/Socket.java +++ b/Robust/src/ClassLibrary/Socket.java @@ -1,71 +1,71 @@ public class Socket { - /* Data pending flag */ - external flag IOPending; - /* File Descriptor */ - int fd; - private SocketInputStream sin; - private SocketOutputStream sout; - - public Socket() { - sin=new SocketInputStream(this); - sout=new SocketOutputStream(this); - } + /* Data pending flag */ + external flag IOPending; + /* File Descriptor */ + int fd; + private SocketInputStream sin; + private SocketOutputStream sout; - public InputStream getInputStream() { - return sin; - } + public Socket() { + sin=new SocketInputStream(this); + sout=new SocketOutputStream(this); + } - public OutputStream getOutputStream() { - return sout; - } + public InputStream getInputStream() { + return sin; + } - public Socket(String host, int port) { - InetAddress address=InetAddress.getByName(host); - fd=nativeBind(address.getAddress(), port); - nativeConnect(fd, address.getAddress(), port); - } - - public Socket(InetAddress address, int port) { - fd=nativeBind(address.getAddress(), port); - nativeConnect(fd, address.getAddress(), port); - } + public OutputStream getOutputStream() { + return sout; + } - public void connect(String host, int port) { - InetAddress address=InetAddress.getByName(host); - fd=nativeBind(address.getAddress(), port); - nativeConnect(fd, address.getAddress(), port); - } + public Socket(String host, int port) { + InetAddress address=InetAddress.getByName(host); + fd=nativeBind(address.getAddress(), port); + nativeConnect(fd, address.getAddress(), port); + } - public void connect(InetAddress address, int port) { - fd=nativeBind(address.getAddress(), port); - nativeConnect(fd, address.getAddress(), port); - } + public Socket(InetAddress address, int port) { + fd=nativeBind(address.getAddress(), port); + nativeConnect(fd, address.getAddress(), port); + } - public static native int nativeBind(byte[] address, int port); + public void connect(String host, int port) { + InetAddress address=InetAddress.getByName(host); + fd=nativeBind(address.getAddress(), port); + nativeConnect(fd, address.getAddress(), port); + } - public native int nativeConnect(int fd, byte[] address, int port); - - int setFD(int filed) { - fd=filed; - } + public void connect(InetAddress address, int port) { + fd=nativeBind(address.getAddress(), port); + nativeConnect(fd, address.getAddress(), port); + } - public int read(byte[] b) { - return nativeRead(b); - } - public void write(byte[] b) { - nativeWrite(b, 0, b.length); - } + public static native int nativeBind(byte[] address, int port); - public void write(byte[] b, int offset, int len) { - nativeWrite(b, offset, len); - } + public native int nativeConnect(int fd, byte[] address, int port); - private native void nativeBindFD(int fd); - private native int nativeRead(byte[] b); - private native void nativeWrite(byte[] b, int offset, int len); - private native void nativeClose(); + int setFD(int filed) { + fd=filed; + } - public void close() { - nativeClose(); - } + public int read(byte[] b) { + return nativeRead(b); + } + public void write(byte[] b) { + nativeWrite(b, 0, b.length); + } + + public void write(byte[] b, int offset, int len) { + nativeWrite(b, offset, len); + } + + private native void nativeBindFD(int fd); + private native int nativeRead(byte[] b); + private native void nativeWrite(byte[] b, int offset, int len); + private native void nativeClose(); + + public void close() { + nativeClose(); + } } diff --git a/Robust/src/ClassLibrary/SocketInputStream.java b/Robust/src/ClassLibrary/SocketInputStream.java index 43e4ed89..bc3a65ce 100644 --- a/Robust/src/ClassLibrary/SocketInputStream.java +++ b/Robust/src/ClassLibrary/SocketInputStream.java @@ -1,22 +1,22 @@ public class SocketInputStream extends InputStream { - Socket s; - public SocketInputStream(Socket s) { - this.s=s; - } + Socket s; + public SocketInputStream(Socket s) { + this.s=s; + } - public int read() { - byte[] x=new byte[1]; - int len=s.read(x); - if (len<=0) - return -1; - else return x[0]; - } + public int read() { + byte[] x=new byte[1]; + int len=s.read(x); + if (len<=0) + return -1; + else return x[0]; + } - public int read(byte[] b) { - return s.read(b); - } + public int read(byte[] b) { + return s.read(b); + } - public void close() { - s.close(); - } + public void close() { + s.close(); + } } diff --git a/Robust/src/ClassLibrary/SocketJava.java b/Robust/src/ClassLibrary/SocketJava.java index c2b85418..297fe3d0 100644 --- a/Robust/src/ClassLibrary/SocketJava.java +++ b/Robust/src/ClassLibrary/SocketJava.java @@ -1,61 +1,61 @@ public class Socket { - /* File Descriptor */ - int fd; - SocketInputStream sin; - SocketOutputStream sout; - - public Socket() { - sin=new SocketInputStream(this); - sout=new SocketOutputStream(this); - } - - public InputStream getInputStream() { - return sin; - } - - public OutputStream getOutputStream() { - return sout; - } - - public Socket(String host, int port) { - InetAddress address=InetAddress.getByName(host); - fd=nativeBind(address.getAddress(), port); - nativeConnect(fd, address.getAddress(), port); - sin=new SocketInputStream(this); - sout=new SocketOutputStream(this); - } - - public Socket(InetAddress address, int port) { - fd=nativeBind(address.getAddress(), port); - nativeConnect(fd, address.getAddress(), port); - sin=new SocketInputStream(this); - sout=new SocketOutputStream(this); - } - - public static native int nativeBind(byte[] address, int port); - - public static native int nativeConnect(int fd, byte[] address, int port); - - int setFD(int filed) { - fd=filed; - } - - public int read(byte[] b) { - return nativeRead(b); - } - public void write(byte[] b) { - nativeWrite(b, 0, b.length); - } - - public void write(byte[] b, int offset, int len) { - nativeWrite(b, offset, len); - } - - private native int nativeRead(byte[] b); - private native void nativeWrite(byte[] b, int offset, int len); - private native void nativeClose(); - - public void close() { - nativeClose(); - } + /* File Descriptor */ + int fd; + SocketInputStream sin; + SocketOutputStream sout; + + public Socket() { + sin=new SocketInputStream(this); + sout=new SocketOutputStream(this); + } + + public InputStream getInputStream() { + return sin; + } + + public OutputStream getOutputStream() { + return sout; + } + + public Socket(String host, int port) { + InetAddress address=InetAddress.getByName(host); + fd=nativeBind(address.getAddress(), port); + nativeConnect(fd, address.getAddress(), port); + sin=new SocketInputStream(this); + sout=new SocketOutputStream(this); + } + + public Socket(InetAddress address, int port) { + fd=nativeBind(address.getAddress(), port); + nativeConnect(fd, address.getAddress(), port); + sin=new SocketInputStream(this); + sout=new SocketOutputStream(this); + } + + public static native int nativeBind(byte[] address, int port); + + public static native int nativeConnect(int fd, byte[] address, int port); + + int setFD(int filed) { + fd=filed; + } + + public int read(byte[] b) { + return nativeRead(b); + } + public void write(byte[] b) { + nativeWrite(b, 0, b.length); + } + + public void write(byte[] b, int offset, int len) { + nativeWrite(b, offset, len); + } + + private native int nativeRead(byte[] b); + private native void nativeWrite(byte[] b, int offset, int len); + private native void nativeClose(); + + public void close() { + nativeClose(); + } } diff --git a/Robust/src/ClassLibrary/SocketOutputStream.java b/Robust/src/ClassLibrary/SocketOutputStream.java index 4e2a7a69..acec8694 100644 --- a/Robust/src/ClassLibrary/SocketOutputStream.java +++ b/Robust/src/ClassLibrary/SocketOutputStream.java @@ -1,24 +1,24 @@ public class SocketOutputStream extends OutputStream { - Socket s; - public SocketOutputStream(Socket s) { - this.s=s; - } + Socket s; + public SocketOutputStream(Socket s) { + this.s=s; + } - public void write(byte[]b) { - s.write(b); - } - - public void write(int ch) { - byte[] b=new byte[1]; - b[0]=(byte)ch; - s.write(b); - } - - public void write(byte[] b, int offset, int len) { - s.write(b, offset, len); - } + public void write(byte[] b) { + s.write(b); + } - public void close() { - s.close(); - } + public void write(int ch) { + byte[] b=new byte[1]; + b[0]=(byte)ch; + s.write(b); + } + + public void write(byte[] b, int offset, int len) { + s.write(b, offset, len); + } + + public void close() { + s.close(); + } } diff --git a/Robust/src/ClassLibrary/StartupObject.java b/Robust/src/ClassLibrary/StartupObject.java index 14c762a9..541c26f5 100644 --- a/Robust/src/ClassLibrary/StartupObject.java +++ b/Robust/src/ClassLibrary/StartupObject.java @@ -1,5 +1,5 @@ public class StartupObject { - flag initialstate; + flag initialstate; - String [] parameters; + String [] parameters; } diff --git a/Robust/src/ClassLibrary/String.java b/Robust/src/ClassLibrary/String.java index f1ec9d53..6ae7fcfa 100644 --- a/Robust/src/ClassLibrary/String.java +++ b/Robust/src/ClassLibrary/String.java @@ -1,343 +1,343 @@ public class String { - char value[]; - int count; - int offset; - private int cachedHashcode; - - private String() { - } - - public String(char str[]) { - char charstr[]=new char[str.length]; - for(int i=0;i(str.length-offset)) - length=str.length-offset; - char charstr[]=new char[length]; - for(int i=0;ithis.count||endIndex>this.count||beginIndex>endIndex) { - // FIXME - System.printString("Index error: "+beginIndex+" "+endIndex+" "+count+"\n"+this); - } - str.value=this.value; - str.count=endIndex-beginIndex; - str.offset=this.offset+beginIndex; - return str; - } - - public String subString(int beginIndex) { - return this.subString(beginIndex, this.count); - } - - public int lastindexOf(int ch) { - return this.lastindexOf(ch, count - 1); - } - - public static String concat2(String s1, String s2) { - if (s1==null) - return "null".concat(s2); - else - return s1.concat(s2); - } - - public String concat(String str) { - String newstr=new String(); - newstr.count=this.count+str.count; - char charstr[]=new char[newstr.count]; - newstr.value=charstr; - newstr.offset=0; - for(int i=0;i0;i--) - if (this.charAt(i)==ch) - return i; - return -1; - } - - public String replace(char oldch, char newch) { - char[] buffer=new char[count]; - for(int i=0;i='a'&&x<='z') { - x=(char) ((x-'a')+'A'); - } - buffer[i]=x; - } - return new String(buffer); - } - - public int indexOf(int ch) { - return this.indexOf(ch, 0); - } - - public int indexOf(int ch, int fromIndex) { - for(int i=fromIndex;ifromIndex) - k=fromIndex; - for(;k>=0;k--) { - if (regionMatches(k, str, 0, str.count)) - return k; - } - return -1; - } - - public int lastIndexOf(String str) { - return lastIndexOf(str, count-str.count); - } - - public boolean startsWith(String str) { - return regionMatches(0, str, 0, str.count); - } - - public boolean startsWith(String str, int toffset) { - return regionMatches(toffset, str, 0, str.count); - } - - public boolean regionMatches(int toffset, String other, int ooffset, int len) { - if (toffset<0 || ooffset <0 || (toffset+len)>count || (ooffset+len)>other.count) - return false; - for(int i=0;i='a'&&l<='z') - l=(char)((l-'a')+'A'); - if (r>='a'&&r<='z') - r=(char)((r-'a')+'A'); - if (l!=r) - return false; - } - return true; - } + char value[]; + int count; + int offset; + private int cachedHashcode; + + private String() { + } + + public String(char str[]) { + char charstr[]=new char[str.length]; + for(int i=0; i(str.length-offset)) + length=str.length-offset; + char charstr[]=new char[length]; + for(int i=0; ithis.count||endIndex>this.count||beginIndex>endIndex) { + // FIXME + System.printString("Index error: "+beginIndex+" "+endIndex+" "+count+"\n"+this); + } + str.value=this.value; + str.count=endIndex-beginIndex; + str.offset=this.offset+beginIndex; + return str; + } + + public String subString(int beginIndex) { + return this.subString(beginIndex, this.count); + } + + public int lastindexOf(int ch) { + return this.lastindexOf(ch, count - 1); + } + + public static String concat2(String s1, String s2) { + if (s1==null) + return "null".concat(s2); + else + return s1.concat(s2); + } + + public String concat(String str) { + String newstr=new String(); + newstr.count=this.count+str.count; + char charstr[]=new char[newstr.count]; + newstr.value=charstr; + newstr.offset=0; + for(int i=0; i0; i--) + if (this.charAt(i)==ch) + return i; + return -1; + } + + public String replace(char oldch, char newch) { + char[] buffer=new char[count]; + for(int i=0; i='a'&&x<='z') { + x=(char) ((x-'a')+'A'); + } + buffer[i]=x; + } + return new String(buffer); + } + + public int indexOf(int ch) { + return this.indexOf(ch, 0); + } + + public int indexOf(int ch, int fromIndex) { + for(int i=fromIndex; ifromIndex) + k=fromIndex; + for(; k>=0; k--) { + if (regionMatches(k, str, 0, str.count)) + return k; + } + return -1; + } + + public int lastIndexOf(String str) { + return lastIndexOf(str, count-str.count); + } + + public boolean startsWith(String str) { + return regionMatches(0, str, 0, str.count); + } + + public boolean startsWith(String str, int toffset) { + return regionMatches(toffset, str, 0, str.count); + } + + public boolean regionMatches(int toffset, String other, int ooffset, int len) { + if (toffset<0 || ooffset <0 || (toffset+len)>count || (ooffset+len)>other.count) + return false; + for(int i=0; i='a'&&l<='z') + l=(char)((l-'a')+'A'); + if (r>='a'&&r<='z') + r=(char)((r-'a')+'A'); + if (l!=r) + return false; + } + return true; + } } diff --git a/Robust/src/ClassLibrary/StringBuffer.java b/Robust/src/ClassLibrary/StringBuffer.java index f51c7248..0aa1a2d9 100644 --- a/Robust/src/ClassLibrary/StringBuffer.java +++ b/Robust/src/ClassLibrary/StringBuffer.java @@ -1,75 +1,75 @@ public class StringBuffer { - char value[]; - int count; - // private static final int DEFAULTSIZE=16; + char value[]; + int count; + // private static final int DEFAULTSIZE=16; - public StringBuffer(String str) { - value=new char[str.count+16];//16 is DEFAULTSIZE - count=str.count; - for(int i=0;ivalue.length) { - // Need to allocate - char newvalue[]=new char[s.count+count+16]; //16 is DEFAULTSIZE - for(int i=0;ivalue.length) { + // Need to allocate + char newvalue[]=new char[s.count+count+16]; //16 is DEFAULTSIZE + for(int i=0; ivalue.length) { - // Need to allocate - char newvalue[]=new char[s.count+count+16]; //16 is DEFAULTSIZE - for(int i=0;ivalue.length) { + // Need to allocate + char newvalue[]=new char[s.count+count+16]; //16 is DEFAULTSIZE + for(int i=0; i=size) { - System.printString("Illegal Vector.elementAt"); - return null; - } - return array[index]; + public Object elementAt(int index) { + if (index<0 || index >=size) { + System.printString("Illegal Vector.elementAt"); + return null; } + return array[index]; + } - public void setElementAt(Object obj, int index) { - if (index>=0 && index =0 && index array.length) { - int newsize; - if (capacityIncrement<=0) - newsize=array.length*2; - else - newsize=array.length+capacityIncrement; - if (newsizearray.length) { + int newsize; + if (capacityIncrement<=0) + newsize=array.length*2; + else + newsize=array.length+capacityIncrement; + if (newsize=size) - System.printString("Illegal remove"); - for(int i=index;i<(size-1);i++) { - array[i]=array[i+1]; - } - size--; + public void removeElementAt(int index) { + if (index<0||index>=size) + System.printString("Illegal remove"); + for(int i=index; i<(size-1); i++) { + array[i]=array[i+1]; } + size--; + } } diff --git a/Robust/src/ClassLibrary/Writer.java b/Robust/src/ClassLibrary/Writer.java index c1728a2c..d070bb33 100644 --- a/Robust/src/ClassLibrary/Writer.java +++ b/Robust/src/ClassLibrary/Writer.java @@ -1,17 +1,17 @@ public class Writer { - public void write(String s) { - System.printString("Unimplemented write(String) in Writer\n"); - } + public void write(String s) { + System.printString("Unimplemented write(String) in Writer\n"); + } - public void write(String s, int off, int len) { - write(s.substring(off, off+len)); - } + public void write(String s, int off, int len) { + write(s.substring(off, off+len)); + } - public void flush() { - System.printString("Unimplemented flush in Writer\n"); - } + public void flush() { + System.printString("Unimplemented flush in Writer\n"); + } - public void close() { - System.printString("Unimplemented close in Writer\n"); - } + public void close() { + System.printString("Unimplemented close in Writer\n"); + } } diff --git a/Robust/src/ClassLibrary/gnu/Random.java b/Robust/src/ClassLibrary/gnu/Random.java index 083da05d..b09683e6 100644 --- a/Robust/src/ClassLibrary/gnu/Random.java +++ b/Robust/src/ClassLibrary/gnu/Random.java @@ -1,39 +1,39 @@ /* Random.java -- a pseudo-random number generator Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc. -This file is part of GNU Classpath. + This file is part of GNU Classpath. -GNU Classpath is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2, or (at your option) -any later version. + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. -GNU Classpath is distributed in the hope that it will be useful, but -WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -General Public License for more details. + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. -You should have received a copy of the GNU General Public License -along with GNU Classpath; see the file COPYING. If not, write to the -Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -02110-1301 USA. + You should have received a copy of the GNU General Public License + along with GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. -Linking this library statically or dynamically with other modules is -making a combined work based on this library. Thus, the terms and -conditions of the GNU General Public License cover the whole -combination. + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. -As a special exception, the copyright holders of this library give you -permission to link this library with independent modules to produce an -executable, regardless of the license terms of these independent -modules, and to copy and distribute the resulting executable under -terms of your choice, provided that you also meet, for each linked -independent module, the terms and conditions of the license of that -module. An independent module is a module which is not derived from -or based on this library. If you modify this library, you may extend -this exception to your version of the library, but you are not -obligated to do so. If you do not wish to do so, delete this -exception statement from your version. */ + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ /** @@ -110,8 +110,7 @@ public class Random * * @see System#currentTimeMillis() */ - public Random() - { + public Random() { setSeed(System.currentTimeMillis()); } @@ -121,8 +120,7 @@ public class Random * * @param seed the initial seed */ - public Random(long seed) - { + public Random(long seed) { setSeed(seed); } @@ -132,16 +130,15 @@ public class Random * same seed, should produce the same results, if the same methods * are called. The implementation for java.util.Random is: * -
public synchronized void setSeed(long seed)
-{
-  this.seed = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1);
-  haveNextNextGaussian = false;
-}
+
public synchronized void setSeed(long seed)
+     {
+     this.seed = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1);
+     haveNextNextGaussian = false;
+     }
* * @param seed the new seed */ - public synchronized void setSeed(long seed) - { + public synchronized void setSeed(long seed) { this.seed = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1); haveNextNextGaussian = false; } @@ -152,18 +149,17 @@ public class Random * independent chosen random bits (0 and 1 are equally likely). * The implementation for java.util.Random is: * -
protected synchronized int next(int bits)
-{
-  seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
-  return (int) (seed >>> (48 - bits));
-}
+
protected synchronized int next(int bits)
+     {
+     seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
+     return (int) (seed >>> (48 - bits));
+     }
* * @param bits the number of random bits to generate, in the range 1..32 * @return the next pseudorandom value * @since 1.1 */ - protected synchronized int next(int bits) - { + protected synchronized int next(int bits) { seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1); return (int) (seed >>> (48 - bits)); } @@ -173,45 +169,43 @@ public class Random * are (approximately) equally likely. * The JDK documentation gives no implementation, but it seems to be: * -
public void nextBytes(byte[] bytes)
-{
-  for (int i = 0; i < bytes.length; i += 4)
-  {
-    int random = next(32);
-    for (int j = 0; i + j < bytes.length && j < 4; j++)
-    {
+     
public void nextBytes(byte[] bytes)
+     {
+     for (int i = 0; i < bytes.length; i += 4)
+     {
+     int random = next(32);
+     for (int j = 0; i + j < bytes.length && j < 4; j++)
+     {
       bytes[i+j] = (byte) (random & 0xff)
       random >>= 8;
-    }
-  }
-}
+ } + } + }
* * @param bytes the byte array that should be filled * @throws NullPointerException if bytes is null * @since 1.1 */ - public void nextBytes(byte[] bytes) - { + public void nextBytes(byte[] bytes) { int random; // Do a little bit unrolling of the above algorithm. int max = bytes.length & ~0x3; for (int i = 0; i < max; i += 4) + { + random = next(32); + bytes[i] = (byte) random; + bytes[i + 1] = (byte) (random >> 8); + bytes[i + 2] = (byte) (random >> 16); + bytes[i + 3] = (byte) (random >> 24); + } + if (max < bytes.length){ + random = next(32); + for (int j = max; j < bytes.length; j++) { - random = next(32); - bytes[i] = (byte) random; - bytes[i + 1] = (byte) (random >> 8); - bytes[i + 2] = (byte) (random >> 16); - bytes[i + 3] = (byte) (random >> 24); - } - if (max < bytes.length) - { - random = next(32); - for (int j = max; j < bytes.length; j++) - { - bytes[j] = (byte) random; - random >>= 8; - } + bytes[j] = (byte) random; + random >>= 8; } + } } /** @@ -219,16 +213,15 @@ public class Random * an int value whose 32 bits are independent chosen random bits * (0 and 1 are equally likely). The implementation for * java.util.Random is: - * -
public int nextInt()
-{
-  return next(32);
-}
+ * +
public int nextInt()
+     {
+     return next(32);
+     }
* * @return the next pseudorandom value */ - public int nextInt() - { + public int nextInt() { return next(32); } @@ -238,27 +231,27 @@ public class Random * each value has the same likelihodd (1/n). * (0 and 1 are equally likely). The implementation for * java.util.Random is: - * -
-public int nextInt(int n)
-{
-  if (n <= 0)
-    throw new IllegalArgumentException("n must be positive");
+   *
+     
+     public int nextInt(int n)
+     {
+     if (n <= 0)
+     throw new IllegalArgumentException("n must be positive");
 
-  if ((n & -n) == n)  // i.e., n is a power of 2
-    return (int)((n * (long) next(31)) >> 31);
+     if ((n & -n) == n)  // i.e., n is a power of 2
+     return (int)((n * (long) next(31)) >> 31);
 
-  int bits, val;
-  do
-  {
-    bits = next(31);
-    val = bits % n;
-  }
-  while(bits - val + (n-1) < 0);
+     int bits, val;
+     do
+     {
+     bits = next(31);
+     val = bits % n;
+     }
+     while(bits - val + (n-1) < 0);
 
-  return val;
-}
- * + return val; + }
+ * *

This algorithm would return every value with exactly the same * probability, if the next()-method would be a perfect random number * generator. @@ -279,19 +272,16 @@ public int nextInt(int n) * @return the next pseudorandom value * @since 1.2 */ - public int nextInt(int n) - { + public int nextInt(int n) { if (n <= 0) - System.printString("ERROR: n must be positive\n"); + System.printString("ERROR: n must be positive\n"); if ((n & -n) == n) // i.e., n is a power of 2 return (int) ((n * (long) next(31)) >> 31); int bits, val; - do - { - bits = next(31); - val = bits % n; - } - while (bits - val + (n - 1) < 0); + do { + bits = next(31); + val = bits % n; + } while (bits - val + (n - 1) < 0); return val; } @@ -300,32 +290,30 @@ public int nextInt(int n) * long are independently chosen and 0 and 1 have equal likelihood. * The implementation for java.util.Random is: * -

public long nextLong()
-{
-  return ((long) next(32) << 32) + next(32);
-}
+
public long nextLong()
+     {
+     return ((long) next(32) << 32) + next(32);
+     }
* * @return the next pseudorandom value */ - public long nextLong() - { + public long nextLong() { return ((long) next(32) << 32) + next(32); } /** * Generates the next pseudorandom boolean. True and false have * the same probability. The implementation is: - * -
public boolean nextBoolean()
-{
-  return next(1) != 0;
-}
+ * +
public boolean nextBoolean()
+     {
+     return next(1) != 0;
+     }
* * @return the next pseudorandom boolean * @since 1.2 */ - public boolean nextBoolean() - { + public boolean nextBoolean() { return next(1) != 0; } @@ -333,16 +321,15 @@ public int nextInt(int n) * Generates the next pseudorandom float uniformly distributed * between 0.0f (inclusive) and 1.0f (exclusive). The * implementation is as follows. - * -
public float nextFloat()
-{
-  return next(24) / ((float)(1 << 24));
-}
+ * +
public float nextFloat()
+     {
+     return next(24) / ((float)(1 << 24));
+     }
* * @return the next pseudorandom float */ - public float nextFloat() - { + public float nextFloat() { return next(24) / (float) (1 << 24); } @@ -351,15 +338,14 @@ public int nextInt(int n) * between 0.0 (inclusive) and 1.0 (exclusive). The * implementation is as follows. * -
public double nextDouble()
-{
-  return (((long) next(26) << 27) + next(27)) / (double)(1L << 53);
-}
+
public double nextDouble()
+     {
+     return (((long) next(26) << 27) + next(27)) / (double)(1L << 53);
+     }
* * @return the next pseudorandom double */ - public double nextDouble() - { + public double nextDouble() { return (((long) next(26) << 27) + next(27)) / (double) (1L << 53); } @@ -367,52 +353,48 @@ public int nextInt(int n) * Generates the next pseudorandom, Gaussian (normally) distributed * double value, with mean 0.0 and standard deviation 1.0. * The algorithm is as follows. - * -
public synchronized double nextGaussian()
-{
-  if (haveNextNextGaussian)
-  {
-    haveNextNextGaussian = false;
-    return nextNextGaussian;
-  }
-  else
-  {
-    double v1, v2, s;
-    do
-    {
+   *
+     
public synchronized double nextGaussian()
+     {
+     if (haveNextNextGaussian)
+     {
+     haveNextNextGaussian = false;
+     return nextNextGaussian;
+     }
+     else
+     {
+     double v1, v2, s;
+     do
+     {
       v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0
       v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0
       s = v1 * v1 + v2 * v2;
-    }
-    while (s >= 1);
+     }
+     while (s >= 1);
 
-    double norm = Math.sqrt(-2 * Math.log(s) / s);
-    nextNextGaussian = v2 * norm;
-    haveNextNextGaussian = true;
-    return v1 * norm;
-  }
-}
+ double norm = Math.sqrt(-2 * Math.log(s) / s); + nextNextGaussian = v2 * norm; + haveNextNextGaussian = true; + return v1 * norm; + } + }
* *

This is described in section 3.4.1 of The Art of Computer * Programming, Volume 2 by Donald Knuth. * * @return the next pseudorandom Gaussian distributed double */ - public synchronized double nextGaussian() - { - if (haveNextNextGaussian) - { - haveNextNextGaussian = false; - return nextNextGaussian; - } + public synchronized double nextGaussian() { + if (haveNextNextGaussian){ + haveNextNextGaussian = false; + return nextNextGaussian; + } double v1, v2, s; - do - { - v1 = 2 * nextDouble() - 1; // Between -1.0 and 1.0. - v2 = 2 * nextDouble() - 1; // Between -1.0 and 1.0. - s = v1 * v1 + v2 * v2; - } - while (s >= 1); + do { + v1 = 2 * nextDouble() - 1; // Between -1.0 and 1.0. + v2 = 2 * nextDouble() - 1; // Between -1.0 and 1.0. + s = v1 * v1 + v2 * v2; + } while (s >= 1); double norm = Math.sqrt(-2 * Math.log(s) / s); nextNextGaussian = v2 * norm; haveNextNextGaussian = true; diff --git a/Robust/src/IR/AssignOperation.java b/Robust/src/IR/AssignOperation.java index 121c4d41..e4e79c21 100644 --- a/Robust/src/IR/AssignOperation.java +++ b/Robust/src/IR/AssignOperation.java @@ -1,131 +1,144 @@ package IR; public class AssignOperation { - public static final int EQ=1; - public static final int MULTEQ=2; - public static final int DIVEQ=3; - public static final int MODEQ=4; - public static final int PLUSEQ=5; - public static final int MINUSEQ=6; - public static final int LSHIFTEQ=7; - public static final int RSHIFTEQ=8; - public static final int URSHIFTEQ=9; - public static final int ANDEQ=10; - public static final int XOREQ=11; - public static final int OREQ=12; - public static final int POSTINC=13; - public static final int POSTDEC=14; - - private int operation; - public AssignOperation(int op) { - this.operation=op; - } + public static final int EQ=1; + public static final int MULTEQ=2; + public static final int DIVEQ=3; + public static final int MODEQ=4; + public static final int PLUSEQ=5; + public static final int MINUSEQ=6; + public static final int LSHIFTEQ=7; + public static final int RSHIFTEQ=8; + public static final int URSHIFTEQ=9; + public static final int ANDEQ=10; + public static final int XOREQ=11; + public static final int OREQ=12; + public static final int POSTINC=13; + public static final int POSTDEC=14; - public AssignOperation(String op) { - this.operation=parseOp(op); - } + private int operation; + public AssignOperation(int op) { + this.operation=op; + } - public int getOp() { - return operation; - } + public AssignOperation(String op) { + this.operation=parseOp(op); + } - public Operation getBaseOp() { - switch(operation) { - case EQ: - return null; - case MULTEQ: - return new Operation(Operation.MULT); - case DIVEQ: - return new Operation(Operation.DIV); - case MODEQ: - return new Operation(Operation.MOD); - case PLUSEQ: - return new Operation(Operation.ADD); - case MINUSEQ: - return new Operation(Operation.SUB); - case LSHIFTEQ: - return new Operation(Operation.LEFTSHIFT); - case RSHIFTEQ: - return new Operation(Operation.RIGHTSHIFT); - case URSHIFTEQ: - return new Operation(Operation.URIGHTSHIFT); - case ANDEQ: - return new Operation(Operation.BIT_AND); - case XOREQ: - return new Operation(Operation.BIT_XOR); - case OREQ: - return new Operation(Operation.BIT_OR); - case POSTINC: - return new Operation(Operation.POSTINC); - case POSTDEC: - return new Operation(Operation.POSTDEC); - } - throw new Error(); - } + public int getOp() { + return operation; + } - public static int parseOp(String st) { - if (st.equals("eq")) - return EQ; - else if (st.equals("multeq")) - return MULTEQ; - else if (st.equals("diveq")) - return DIVEQ; - else if (st.equals("modeq")) - return MODEQ; - else if (st.equals("pluseq")) - return PLUSEQ; - else if (st.equals("minuseq")) - return MINUSEQ; - else if (st.equals("lshifteq")) - return LSHIFTEQ; - else if (st.equals("urshifteq")) - return URSHIFTEQ; - else if (st.equals("rshifteq")) - return RSHIFTEQ; - else if (st.equals("andeq")) - return ANDEQ; - else if (st.equals("xoreq")) - return XOREQ; - else if (st.equals("oreq")) - return OREQ; - else if (st.equals("postinc")) - return POSTINC; - else if (st.equals("postdec")) - return POSTDEC; - else throw new Error(); - } + public Operation getBaseOp() { + switch(operation) { + case EQ: + return null; + + case MULTEQ: + return new Operation(Operation.MULT); + + case DIVEQ: + return new Operation(Operation.DIV); + + case MODEQ: + return new Operation(Operation.MOD); + + case PLUSEQ: + return new Operation(Operation.ADD); + + case MINUSEQ: + return new Operation(Operation.SUB); - public String toString() { - if (operation==EQ) - return "="; - else if (operation==MULTEQ) - return "*="; - else if (operation==DIVEQ) - return "/="; - else if (operation==MODEQ) - return "%="; - else if (operation==PLUSEQ) - return "+="; - else if (operation==MINUSEQ) - return "-="; - else if (operation==LSHIFTEQ) - return "<="; - else if (operation==RSHIFTEQ) - return ">="; - else if (operation==RSHIFTEQ) - return ">>="; - else if (operation==ANDEQ) - return "&="; - else if (operation==XOREQ) - return "^="; - else if (operation==OREQ) - return "|="; - else if (operation==POSTINC) - return "postinc"; - else if (operation==POSTDEC) - return "postdec"; - else throw new Error(); + case LSHIFTEQ: + return new Operation(Operation.LEFTSHIFT); + + case RSHIFTEQ: + return new Operation(Operation.RIGHTSHIFT); + + case URSHIFTEQ: + return new Operation(Operation.URIGHTSHIFT); + + case ANDEQ: + return new Operation(Operation.BIT_AND); + + case XOREQ: + return new Operation(Operation.BIT_XOR); + + case OREQ: + return new Operation(Operation.BIT_OR); + + case POSTINC: + return new Operation(Operation.POSTINC); + + case POSTDEC: + return new Operation(Operation.POSTDEC); } + throw new Error(); + } + + public static int parseOp(String st) { + if (st.equals("eq")) + return EQ; + else if (st.equals("multeq")) + return MULTEQ; + else if (st.equals("diveq")) + return DIVEQ; + else if (st.equals("modeq")) + return MODEQ; + else if (st.equals("pluseq")) + return PLUSEQ; + else if (st.equals("minuseq")) + return MINUSEQ; + else if (st.equals("lshifteq")) + return LSHIFTEQ; + else if (st.equals("urshifteq")) + return URSHIFTEQ; + else if (st.equals("rshifteq")) + return RSHIFTEQ; + else if (st.equals("andeq")) + return ANDEQ; + else if (st.equals("xoreq")) + return XOREQ; + else if (st.equals("oreq")) + return OREQ; + else if (st.equals("postinc")) + return POSTINC; + else if (st.equals("postdec")) + return POSTDEC; + else throw new Error(); + } + + public String toString() { + if (operation==EQ) + return "="; + else if (operation==MULTEQ) + return "*="; + else if (operation==DIVEQ) + return "/="; + else if (operation==MODEQ) + return "%="; + else if (operation==PLUSEQ) + return "+="; + else if (operation==MINUSEQ) + return "-="; + else if (operation==LSHIFTEQ) + return "<="; + else if (operation==RSHIFTEQ) + return ">="; + else if (operation==RSHIFTEQ) + return ">>="; + else if (operation==ANDEQ) + return "&="; + else if (operation==XOREQ) + return "^="; + else if (operation==OREQ) + return "|="; + else if (operation==POSTINC) + return "postinc"; + else if (operation==POSTDEC) + return "postdec"; + else throw new Error(); + } } diff --git a/Robust/src/IR/ClassDescriptor.java b/Robust/src/IR/ClassDescriptor.java index a86ea6af..e38a12f6 100644 --- a/Robust/src/IR/ClassDescriptor.java +++ b/Robust/src/IR/ClassDescriptor.java @@ -3,140 +3,140 @@ import java.util.*; import IR.Tree.*; public class ClassDescriptor extends Descriptor { - private static int UIDCount=0; - private final int classid; - String superclass; - ClassDescriptor superdesc; - boolean hasFlags=false; - String packagename; - - Modifiers modifiers; - - SymbolTable fields; - SymbolTable flags; - SymbolTable methods; - - public ClassDescriptor(String classname) { - this("", classname); - } - - public ClassDescriptor(String packagename, String classname) { - super(classname); - superclass=null; - flags=new SymbolTable(); - fields=new SymbolTable(); - methods=new SymbolTable(); - classid=UIDCount++; - this.packagename=packagename; - } - - public int getId() { - return classid; - } - - public Iterator getMethods() { - return methods.getDescriptorsIterator(); - } - - public Iterator getFields() { - return fields.getDescriptorsIterator(); - } - - public Iterator getFlags() { - return flags.getDescriptorsIterator(); - } - - public SymbolTable getFieldTable() { - return fields; - } - - public SymbolTable getFlagTable() { - return flags; - } - - public SymbolTable getMethodTable() { - return methods; - } - - public String getSafeDescriptor() { - return "L"+safename.replace('.','/'); - } - - public String printTree(State state) { - int indent; - String st=modifiers.toString()+"class "+getSymbol(); - if (superclass!=null) - st+="extends "+superclass.toString(); - st+=" {\n"; - indent=TreeNode.INDENT; - boolean printcr=false; - - for(Iterator it=getFlags();it.hasNext();) { - FlagDescriptor fd=(FlagDescriptor)it.next(); - st+=TreeNode.printSpace(indent)+fd.toString()+"\n"; - printcr=true; - } - if (printcr) - st+="\n"; - - printcr=false; - - for(Iterator it=getFields();it.hasNext();) { - FieldDescriptor fd=(FieldDescriptor)it.next(); - st+=TreeNode.printSpace(indent)+fd.toString()+"\n"; - printcr=true; - } - if (printcr) - st+="\n"; - - for(Iterator it=getMethods();it.hasNext();) { - MethodDescriptor md=(MethodDescriptor)it.next(); - st+=TreeNode.printSpace(indent)+md.toString()+" "; - BlockNode bn=state.getMethodBody(md); - st+=bn.printNode(indent)+"\n\n"; - } - st+="}\n"; - return st; - } - - public void addFlag(FlagDescriptor fd) { - if (flags.contains(fd.getSymbol())) - throw new Error(fd.getSymbol()+" already defined"); - hasFlags=true; - flags.add(fd); - } - - public boolean hasFlags() { - return hasFlags||getSuperDesc()!=null&&getSuperDesc().hasFlags(); - } - - public void addField(FieldDescriptor fd) { - if (fields.contains(fd.getSymbol())) - throw new Error(fd.getSymbol()+" already defined"); - fields.add(fd); - } - - public void addMethod(MethodDescriptor md) { - methods.add(md); - } - - public void setModifiers(Modifiers modifiers) { - this.modifiers=modifiers; - } - - public void setSuper(String superclass) { - this.superclass=superclass; - } - - public ClassDescriptor getSuperDesc() { - return superdesc; - } - - public void setSuper(ClassDescriptor scd) { - this.superdesc=scd; - } - - public String getSuper() { - return superclass; - } + private static int UIDCount=0; + private final int classid; + String superclass; + ClassDescriptor superdesc; + boolean hasFlags=false; + String packagename; + + Modifiers modifiers; + + SymbolTable fields; + SymbolTable flags; + SymbolTable methods; + + public ClassDescriptor(String classname) { + this("", classname); + } + + public ClassDescriptor(String packagename, String classname) { + super(classname); + superclass=null; + flags=new SymbolTable(); + fields=new SymbolTable(); + methods=new SymbolTable(); + classid=UIDCount++; + this.packagename=packagename; + } + + public int getId() { + return classid; + } + + public Iterator getMethods() { + return methods.getDescriptorsIterator(); + } + + public Iterator getFields() { + return fields.getDescriptorsIterator(); + } + + public Iterator getFlags() { + return flags.getDescriptorsIterator(); + } + + public SymbolTable getFieldTable() { + return fields; + } + + public SymbolTable getFlagTable() { + return flags; + } + + public SymbolTable getMethodTable() { + return methods; + } + + public String getSafeDescriptor() { + return "L"+safename.replace('.','/'); + } + + public String printTree(State state) { + int indent; + String st=modifiers.toString()+"class "+getSymbol(); + if (superclass!=null) + st+="extends "+superclass.toString(); + st+=" {\n"; + indent=TreeNode.INDENT; + boolean printcr=false; + + for(Iterator it=getFlags(); it.hasNext();) { + FlagDescriptor fd=(FlagDescriptor)it.next(); + st+=TreeNode.printSpace(indent)+fd.toString()+"\n"; + printcr=true; + } + if (printcr) + st+="\n"; + + printcr=false; + + for(Iterator it=getFields(); it.hasNext();) { + FieldDescriptor fd=(FieldDescriptor)it.next(); + st+=TreeNode.printSpace(indent)+fd.toString()+"\n"; + printcr=true; + } + if (printcr) + st+="\n"; + + for(Iterator it=getMethods(); it.hasNext();) { + MethodDescriptor md=(MethodDescriptor)it.next(); + st+=TreeNode.printSpace(indent)+md.toString()+" "; + BlockNode bn=state.getMethodBody(md); + st+=bn.printNode(indent)+"\n\n"; + } + st+="}\n"; + return st; + } + + public void addFlag(FlagDescriptor fd) { + if (flags.contains(fd.getSymbol())) + throw new Error(fd.getSymbol()+" already defined"); + hasFlags=true; + flags.add(fd); + } + + public boolean hasFlags() { + return hasFlags||getSuperDesc()!=null&&getSuperDesc().hasFlags(); + } + + public void addField(FieldDescriptor fd) { + if (fields.contains(fd.getSymbol())) + throw new Error(fd.getSymbol()+" already defined"); + fields.add(fd); + } + + public void addMethod(MethodDescriptor md) { + methods.add(md); + } + + public void setModifiers(Modifiers modifiers) { + this.modifiers=modifiers; + } + + public void setSuper(String superclass) { + this.superclass=superclass; + } + + public ClassDescriptor getSuperDesc() { + return superdesc; + } + + public void setSuper(ClassDescriptor scd) { + this.superdesc=scd; + } + + public String getSuper() { + return superclass; + } } diff --git a/Robust/src/IR/Descriptor.java b/Robust/src/IR/Descriptor.java index 87d09137..4d4d67b7 100644 --- a/Robust/src/IR/Descriptor.java +++ b/Robust/src/IR/Descriptor.java @@ -1,46 +1,46 @@ package IR; /** - * Descriptor + * Descriptor * * represents a symbol in the language (var name, function name, etc). */ public abstract class Descriptor { - protected String name; - protected String safename; - static int count=0; - int uniqueid; - - public Descriptor(String name) { - this.name = name; - this.safename = "___" + name + "___"; - this.uniqueid=count++; - } - - protected Descriptor(String name, String safename) { - this.name = name; - this.safename = safename; - this.uniqueid=count++; - } - - public String toString() { - return name; - } - - public String getSymbol() { - return name; - } - - public String getSafeSymbol() { - return safename; - } - public int getNum() { - return uniqueid; - } - - public String getCoreSafeSymbol(int num) { - return safename + "core" + num + "___"; - } + protected String name; + protected String safename; + static int count=0; + int uniqueid; + + public Descriptor(String name) { + this.name = name; + this.safename = "___" + name + "___"; + this.uniqueid=count++; + } + + protected Descriptor(String name, String safename) { + this.name = name; + this.safename = safename; + this.uniqueid=count++; + } + + public String toString() { + return name; + } + + public String getSymbol() { + return name; + } + + public String getSafeSymbol() { + return safename; + } + public int getNum() { + return uniqueid; + } + + public String getCoreSafeSymbol(int num) { + return safename + "core" + num + "___"; + } } diff --git a/Robust/src/IR/FieldDescriptor.java b/Robust/src/IR/FieldDescriptor.java index fb67c8fe..edfb8959 100644 --- a/Robust/src/IR/FieldDescriptor.java +++ b/Robust/src/IR/FieldDescriptor.java @@ -3,48 +3,48 @@ import IR.Tree.Modifiers; import IR.Tree.ExpressionNode; /** - * Descriptor + * Descriptor * * represents a symbol in the language (var name, function name, etc). */ public class FieldDescriptor extends Descriptor { - public static FieldDescriptor arrayLength=new FieldDescriptor(new Modifiers(Modifiers.PUBLIC|Modifiers.FINAL), new TypeDescriptor(TypeDescriptor.INT), "length", null, false); - - protected Modifiers modifier; - protected TypeDescriptor td; - protected String identifier; - protected ExpressionNode en; - private boolean isglobal; - - public FieldDescriptor(Modifiers m, TypeDescriptor t, String identifier, ExpressionNode e, boolean isglobal) { - super(identifier); - this.modifier=m; - this.td=t; - this.en=e; - this.safename = "___" + name + "___"; - this.uniqueid=count++; - this.isglobal=isglobal; - if (en!=null) throw new Error("Field initializers not implemented"); - } - - public boolean isGlobal() { - return isglobal; - } - - public TypeDescriptor getType() { - return td; - } - - public String toString() { - if (en==null) - return modifier.toString()+td.toString()+" "+getSymbol()+";"; - else - return modifier.toString()+td.toString()+" "+getSymbol()+"="+en.printNode(0)+";"; - } - - public String toStringBrief() { - return td.toString()+" "+getSymbol(); - } + public static FieldDescriptor arrayLength=new FieldDescriptor(new Modifiers(Modifiers.PUBLIC|Modifiers.FINAL), new TypeDescriptor(TypeDescriptor.INT), "length", null, false); + + protected Modifiers modifier; + protected TypeDescriptor td; + protected String identifier; + protected ExpressionNode en; + private boolean isglobal; + + public FieldDescriptor(Modifiers m, TypeDescriptor t, String identifier, ExpressionNode e, boolean isglobal) { + super(identifier); + this.modifier=m; + this.td=t; + this.en=e; + this.safename = "___" + name + "___"; + this.uniqueid=count++; + this.isglobal=isglobal; + if (en!=null) throw new Error("Field initializers not implemented"); + } + + public boolean isGlobal() { + return isglobal; + } + + public TypeDescriptor getType() { + return td; + } + + public String toString() { + if (en==null) + return modifier.toString()+td.toString()+" "+getSymbol()+";"; + else + return modifier.toString()+td.toString()+" "+getSymbol()+"="+en.printNode(0)+";"; + } + + public String toStringBrief() { + return td.toString()+" "+getSymbol(); + } } diff --git a/Robust/src/IR/FlagDescriptor.java b/Robust/src/IR/FlagDescriptor.java index 4df76913..a390b617 100644 --- a/Robust/src/IR/FlagDescriptor.java +++ b/Robust/src/IR/FlagDescriptor.java @@ -1,28 +1,28 @@ package IR; /** - * Descriptor + * Descriptor * * represents a symbol in the language (var name, function name, etc). */ public class FlagDescriptor extends Descriptor { - public final static String InitialFlag="initialstate"; + public final static String InitialFlag="initialstate"; - public FlagDescriptor(String identifier) { - super(identifier); - } + public FlagDescriptor(String identifier) { + super(identifier); + } - private boolean isExternal=false; - public void makeExternal() { - isExternal=true; - } + private boolean isExternal=false; + public void makeExternal() { + isExternal=true; + } - public boolean getExternal() { - return isExternal; - } + public boolean getExternal() { + return isExternal; + } - public String toString() { - return "Flag "+getSymbol(); - } + public String toString() { + return "Flag "+getSymbol(); + } } diff --git a/Robust/src/IR/Flat/BuildCode.java b/Robust/src/IR/Flat/BuildCode.java index 80174069..08b6f06c 100644 --- a/Robust/src/IR/Flat/BuildCode.java +++ b/Robust/src/IR/Flat/BuildCode.java @@ -19,252 +19,252 @@ import Analysis.Locality.LocalityBinding; import Analysis.Prefetch.*; public class BuildCode { - State state; - Hashtable temptovar; - Hashtable paramstable; - Hashtable tempstable; - Hashtable fieldorder; - Hashtable flagorder; - int tag=0; - String localsprefix="___locals___"; - String paramsprefix="___params___"; - String oidstr="___nextobject___"; - String nextobjstr="___nextobject___"; - String localcopystr="___localcopy___"; - public static boolean GENERATEPRECISEGC=false; - public static String PREFIX=""; - public static String arraytype="ArrayObject"; - public static int flagcount = 0; - Virtual virtualcalls; - TypeUtil typeutil; - protected int maxtaskparams=0; - private int maxcount=0; - ClassDescriptor[] cdarray; - TypeDescriptor[] arraytable; - LocalityAnalysis locality; - Hashtable backuptable; - Hashtable reverttable; - SafetyAnalysis sa; - PrefetchAnalysis pa; - - public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) { - this(st, temptovar, typeutil, null, sa, pa); - } - - public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa) { - this(st, temptovar, typeutil, locality, null, pa); - } - - public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa) { - this.sa=sa; - this.pa=pa; - state=st; - this.temptovar=temptovar; - paramstable=new Hashtable(); - tempstable=new Hashtable(); - fieldorder=new Hashtable(); - flagorder=new Hashtable(); - this.typeutil=typeutil; - virtualcalls=new Virtual(state,locality); - if (locality!=null) { - this.locality=locality; - this.backuptable=new Hashtable(); - this.reverttable=new Hashtable(); - } + State state; + Hashtable temptovar; + Hashtable paramstable; + Hashtable tempstable; + Hashtable fieldorder; + Hashtable flagorder; + int tag=0; + String localsprefix="___locals___"; + String paramsprefix="___params___"; + String oidstr="___nextobject___"; + String nextobjstr="___nextobject___"; + String localcopystr="___localcopy___"; + public static boolean GENERATEPRECISEGC=false; + public static String PREFIX=""; + public static String arraytype="ArrayObject"; + public static int flagcount = 0; + Virtual virtualcalls; + TypeUtil typeutil; + protected int maxtaskparams=0; + private int maxcount=0; + ClassDescriptor[] cdarray; + TypeDescriptor[] arraytable; + LocalityAnalysis locality; + Hashtable backuptable; + Hashtable reverttable; + SafetyAnalysis sa; + PrefetchAnalysis pa; + + public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, PrefetchAnalysis pa) { + this(st, temptovar, typeutil, null, sa, pa); + } + + public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, PrefetchAnalysis pa) { + this(st, temptovar, typeutil, locality, null, pa); + } + + public BuildCode(State st, Hashtable temptovar, TypeUtil typeutil, LocalityAnalysis locality, SafetyAnalysis sa, PrefetchAnalysis pa) { + this.sa=sa; + this.pa=pa; + state=st; + this.temptovar=temptovar; + paramstable=new Hashtable(); + tempstable=new Hashtable(); + fieldorder=new Hashtable(); + flagorder=new Hashtable(); + this.typeutil=typeutil; + virtualcalls=new Virtual(state,locality); + if (locality!=null) { + this.locality=locality; + this.backuptable=new Hashtable(); + this.reverttable=new Hashtable(); + } + } + + /** The buildCode method outputs C code for all the methods. The Flat + * versions of the methods must already be generated and stored in + * the State object. */ + + public void buildCode() { + /* Create output streams to write to */ + PrintWriter outclassdefs=null; + PrintWriter outstructs=null; + PrintWriter outrepairstructs=null; + PrintWriter outmethodheader=null; + PrintWriter outmethod=null; + PrintWriter outvirtual=null; + PrintWriter outtask=null; + PrintWriter outtaskdefs=null; + PrintWriter outoptionalarrays=null; + PrintWriter optionalheaders=null; + + try { + outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true); + outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true); + outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true); + outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true); + outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true); + if (state.TASK) { + outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true); + outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true); + if (state.OPTIONAL){ + outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true); + optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true); + } + } + if (state.structfile!=null) { + outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true); + } + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); } - /** The buildCode method outputs C code for all the methods. The Flat - * versions of the methods must already be generated and stored in - * the State object. */ - - public void buildCode() { - /* Create output streams to write to */ - PrintWriter outclassdefs=null; - PrintWriter outstructs=null; - PrintWriter outrepairstructs=null; - PrintWriter outmethodheader=null; - PrintWriter outmethod=null; - PrintWriter outvirtual=null; - PrintWriter outtask=null; - PrintWriter outtaskdefs=null; - PrintWriter outoptionalarrays=null; - PrintWriter optionalheaders=null; - - try { - outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true); - outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true); - outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true); - outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true); - outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true); - if (state.TASK) { - outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true); - outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true); - if (state.OPTIONAL){ - outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true); - optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true); - } - } - if (state.structfile!=null) { - outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true); - } - } catch (Exception e) { - e.printStackTrace(); - System.exit(-1); - } - - /* Build the virtual dispatch tables */ - buildVirtualTables(outvirtual); + /* Build the virtual dispatch tables */ + buildVirtualTables(outvirtual); - /* Output includes */ - outmethodheader.println("#ifndef METHODHEADERS_H"); - outmethodheader.println("#define METHODHEADERS_H"); - outmethodheader.println("#include \"structdefs.h\""); - if (state.DSM) - outmethodheader.println("#include \"dstm.h\""); + /* Output includes */ + outmethodheader.println("#ifndef METHODHEADERS_H"); + outmethodheader.println("#define METHODHEADERS_H"); + outmethodheader.println("#include \"structdefs.h\""); + if (state.DSM) + outmethodheader.println("#include \"dstm.h\""); - /* Output Structures */ - outputStructs(outstructs); + /* Output Structures */ + outputStructs(outstructs); - // Output the C class declarations - // These could mutually reference each other - outputClassDeclarations(outclassdefs); + // Output the C class declarations + // These could mutually reference each other + outputClassDeclarations(outclassdefs); - // Output function prototypes and structures for parameters - Iterator it=state.getClassSymbolTable().getDescriptorsIterator(); - while(it.hasNext()) { - ClassDescriptor cn=(ClassDescriptor)it.next(); - generateCallStructs(cn, outclassdefs, outstructs, outmethodheader); - } - outclassdefs.close(); - - if (state.TASK) { - /* Map flags to integers */ - /* The runtime keeps track of flags using these integers */ - it=state.getClassSymbolTable().getDescriptorsIterator(); - while(it.hasNext()) { - ClassDescriptor cn=(ClassDescriptor)it.next(); - mapFlags(cn); - } - /* Generate Tasks */ - generateTaskStructs(outstructs, outmethodheader); - - /* Outputs generic task structures if this is a task - program */ - outputTaskTypes(outtask); - } + // Output function prototypes and structures for parameters + Iterator it=state.getClassSymbolTable().getDescriptorsIterator(); + while(it.hasNext()) { + ClassDescriptor cn=(ClassDescriptor)it.next(); + generateCallStructs(cn, outclassdefs, outstructs, outmethodheader); + } + outclassdefs.close(); + + if (state.TASK) { + /* Map flags to integers */ + /* The runtime keeps track of flags using these integers */ + it=state.getClassSymbolTable().getDescriptorsIterator(); + while(it.hasNext()) { + ClassDescriptor cn=(ClassDescriptor)it.next(); + mapFlags(cn); + } + /* Generate Tasks */ + generateTaskStructs(outstructs, outmethodheader); + + /* Outputs generic task structures if this is a task + program */ + outputTaskTypes(outtask); + } - /* Build the actual methods */ - outputMethods(outmethod); - - if (state.TASK) { - /* Output code for tasks */ - outputTaskCode(outtaskdefs, outmethod); - outtaskdefs.close(); - /* Record maximum number of task parameters */ - outstructs.println("#define MAXTASKPARAMS "+maxtaskparams); - } else if (state.main!=null) { - /* Generate main method */ - outputMainMethod(outmethod); - } - - /* Generate information for task with optional parameters */ - if (state.TASK&&state.OPTIONAL){ - generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors()); - outoptionalarrays.close(); - } - - /* Output structure definitions for repair tool */ - if (state.structfile!=null) { - buildRepairStructs(outrepairstructs); - outrepairstructs.close(); - } + /* Build the actual methods */ + outputMethods(outmethod); + + if (state.TASK) { + /* Output code for tasks */ + outputTaskCode(outtaskdefs, outmethod); + outtaskdefs.close(); + /* Record maximum number of task parameters */ + outstructs.println("#define MAXTASKPARAMS "+maxtaskparams); + } else if (state.main!=null) { + /* Generate main method */ + outputMainMethod(outmethod); + } - /* Close files */ - outmethodheader.println("#endif"); - outmethodheader.close(); - outmethod.close(); - outstructs.println("#endif"); - outstructs.close(); + /* Generate information for task with optional parameters */ + if (state.TASK&&state.OPTIONAL){ + generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors()); + outoptionalarrays.close(); } - /* This code just generates the main C method for java programs. - * The main C method packs up the arguments into a string array - * and passes it to the java main method. */ + /* Output structure definitions for repair tool */ + if (state.structfile!=null) { + buildRepairStructs(outrepairstructs); + outrepairstructs.close(); + } - private void outputMainMethod(PrintWriter outmethod) { - outmethod.println("int main(int argc, const char *argv[]) {"); - outmethod.println(" int i;"); + /* Close files */ + outmethodheader.println("#endif"); + outmethodheader.close(); + outmethod.close(); + outstructs.println("#endif"); + outstructs.close(); + } + + /* This code just generates the main C method for java programs. + * The main C method packs up the arguments into a string array + * and passes it to the java main method. */ + + private void outputMainMethod(PrintWriter outmethod) { + outmethod.println("int main(int argc, const char *argv[]) {"); + outmethod.println(" int i;"); outmethod.println("#ifdef TRANSSTATS \n"); outmethod.println("handle();\n"); outmethod.println("#endif\n"); - if (state.THREAD||state.DSM) { - outmethod.println("initializethreads();"); - } - if (state.DSM) { - outmethod.println("if (dstmStartup(argv[1])) {"); - if (GENERATEPRECISEGC) { - outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);"); - } else { - outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);"); - } - } else { - if (GENERATEPRECISEGC) { - outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);"); - } else { - outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);"); - } - } - if (state.DSM) { - outmethod.println(" for(i=2;i___length___)+sizeof(int)))[i-2]=newstring;"); - else - outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;"); - outmethod.println(" }"); - - - MethodDescriptor md=typeutil.getMain(); - ClassDescriptor cd=typeutil.getMainClass(); - - outmethod.println(" {"); - if (GENERATEPRECISEGC) { - if (state.DSM) { - outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={"); - } else - outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={"); - outmethod.println("1, NULL,"+"stringarray};"); - if (state.DSM) - outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);"); - else - outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);"); - } else { - if (state.DSM) - outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);"); - else - outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);"); - } - outmethod.println(" }"); + if (state.THREAD||state.DSM) { + outmethod.println("initializethreads();"); + } + if (state.DSM) { + outmethod.println("if (dstmStartup(argv[1])) {"); + if (GENERATEPRECISEGC) { + outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);"); + } else { + outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);"); + } + } else { + if (GENERATEPRECISEGC) { + outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);"); + } else { + outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);"); + } + } + if (state.DSM) { + outmethod.println(" for(i=2;i___length___)+sizeof(int)))[i-2]=newstring;"); + else + outmethod.println(" ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;"); + outmethod.println(" }"); + + + MethodDescriptor md=typeutil.getMain(); + ClassDescriptor cd=typeutil.getMainClass(); + + outmethod.println(" {"); + if (GENERATEPRECISEGC) { + if (state.DSM) { + outmethod.print(" struct "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={"); + } else + outmethod.print(" struct "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={"); + outmethod.println("1, NULL,"+"stringarray};"); + if (state.DSM) + outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);"); + else + outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);"); + } else { + if (state.DSM) + outmethod.println(" "+cd.getSafeSymbol()+locality.getMain().getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);"); + else + outmethod.println(" "+cd.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(stringarray);"); + } + outmethod.println(" }"); - if (state.DSM) { - outmethod.println("}"); - } + if (state.DSM) { + outmethod.println("}"); + } - if (state.THREAD||state.DSM) { - outmethod.println("pthread_mutex_lock(&gclistlock);"); - outmethod.println("threadcount--;"); - outmethod.println("pthread_cond_signal(&gccond);"); - outmethod.println("pthread_mutex_unlock(&gclistlock);"); - if (state.THREAD) - outmethod.println("pthread_exit(NULL);"); - } + if (state.THREAD||state.DSM) { + outmethod.println("pthread_mutex_lock(&gclistlock);"); + outmethod.println("threadcount--;"); + outmethod.println("pthread_cond_signal(&gccond);"); + outmethod.println("pthread_mutex_unlock(&gclistlock);"); + if (state.THREAD) + outmethod.println("pthread_exit(NULL);"); + } outmethod.println("#ifdef TRANSSTATS \n"); outmethod.println("printf(\"****** Transaction Stats ******\\n\");"); @@ -275,2570 +275,2587 @@ public class BuildCode { outmethod.println("printf(\"nprehashSearch= %d\\n\", nprehashSearch);"); outmethod.println("printf(\"nRemoteReadSend= %d\\n\", nRemoteSend);"); outmethod.println("#endif\n"); - outmethod.println("}"); + outmethod.println("}"); + + } + + /* This method outputs code for each task. */ + + private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) { + /* Compile task based program */ + outtaskdefs.println("#include \"task.h\""); + outtaskdefs.println("#include \"methodheaders.h\""); + Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator(); + while(taskit.hasNext()) { + TaskDescriptor td=(TaskDescriptor)taskit.next(); + FlatMethod fm=state.getMethodFlat(td); + generateFlatMethod(fm, null, outmethod); + generateTaskDescriptor(outtaskdefs, fm, td); + } + //Output task descriptors + taskit=state.getTaskSymbolTable().getDescriptorsIterator(); + outtaskdefs.println("struct taskdescriptor * taskarray[]= {"); + boolean first=true; + while(taskit.hasNext()) { + TaskDescriptor td=(TaskDescriptor)taskit.next(); + if (first) + first=false; + else + outtaskdefs.println(","); + outtaskdefs.print("&task_"+td.getSafeSymbol()); + } + outtaskdefs.println("};"); + + outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";"); + } + + /* This method outputs most of the methods.c file. This includes + * some standard includes and then an array with the sizes of + * objets and array that stores supertype and then the code for + * the Java methods.. */ + + protected void outputMethods(PrintWriter outmethod) { + outmethod.println("#include \"methodheaders.h\""); + outmethod.println("#include \"virtualtable.h\""); + outmethod.println("#include \"runtime.h\""); + if (state.DSM) { + outmethod.println("#include \"addPrefetchEnhance.h\""); + outmethod.println("#include \"localobjects.h\""); + } + if(state.MULTICORE) { + outmethod.println("#include \"task.h\""); + } + if (state.THREAD||state.DSM) + outmethod.println("#include "); + if (state.main!=null) { + outmethod.println("#include "); } + if (state.CONSCHECK) { + outmethod.println("#include \"checkers.h\""); + } + //Store the sizes of classes & array elements + generateSizeArray(outmethod); + + //Store table of supertypes + generateSuperTypeTable(outmethod); - /* This method outputs code for each task. */ + //Store the layout of classes + generateLayoutStructs(outmethod); - private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod) { - /* Compile task based program */ - outtaskdefs.println("#include \"task.h\""); - outtaskdefs.println("#include \"methodheaders.h\""); - Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator(); - while(taskit.hasNext()) { - TaskDescriptor td=(TaskDescriptor)taskit.next(); - FlatMethod fm=state.getMethodFlat(td); + /* Generate code for methods */ + if (state.DSM) { + for(Iterator lbit=locality.getLocalityBindings().iterator(); lbit.hasNext();) { + LocalityBinding lb=lbit.next(); + MethodDescriptor md=lb.getMethod(); + FlatMethod fm=state.getMethodFlat(md); + if (!md.getModifiers().isNative()) { + generateFlatMethod(fm, lb, outmethod); + } + } + } else { + Iterator classit=state.getClassSymbolTable().getDescriptorsIterator(); + while(classit.hasNext()) { + ClassDescriptor cn=(ClassDescriptor)classit.next(); + Iterator methodit=cn.getMethods(); + while(methodit.hasNext()) { + /* Classify parameters */ + MethodDescriptor md=(MethodDescriptor)methodit.next(); + FlatMethod fm=state.getMethodFlat(md); + if (!md.getModifiers().isNative()) { generateFlatMethod(fm, null, outmethod); - generateTaskDescriptor(outtaskdefs, fm, td); + } } - - //Output task descriptors - taskit=state.getTaskSymbolTable().getDescriptorsIterator(); - outtaskdefs.println("struct taskdescriptor * taskarray[]= {"); - boolean first=true; - while(taskit.hasNext()) { - TaskDescriptor td=(TaskDescriptor)taskit.next(); - if (first) - first=false; - else - outtaskdefs.println(","); - outtaskdefs.print("&task_"+td.getSafeSymbol()); - } - outtaskdefs.println("};"); - - outtaskdefs.println("int numtasks="+state.getTaskSymbolTable().getValueSet().size()+";"); + } } - - /* This method outputs most of the methods.c file. This includes - * some standard includes and then an array with the sizes of - * objets and array that stores supertype and then the code for - * the Java methods.. */ - - protected void outputMethods(PrintWriter outmethod) { - outmethod.println("#include \"methodheaders.h\""); - outmethod.println("#include \"virtualtable.h\""); - outmethod.println("#include \"runtime.h\""); - if (state.DSM) { - outmethod.println("#include \"addPrefetchEnhance.h\""); - outmethod.println("#include \"localobjects.h\""); - } - if(state.MULTICORE) { - outmethod.println("#include \"task.h\""); - } - if (state.THREAD||state.DSM) - outmethod.println("#include "); - if (state.main!=null) { - outmethod.println("#include "); - } - if (state.CONSCHECK) { - outmethod.println("#include \"checkers.h\""); - } - //Store the sizes of classes & array elements - generateSizeArray(outmethod); - - //Store table of supertypes - generateSuperTypeTable(outmethod); - - //Store the layout of classes - generateLayoutStructs(outmethod); - - /* Generate code for methods */ - if (state.DSM) { - for(Iterator lbit=locality.getLocalityBindings().iterator();lbit.hasNext();) { - LocalityBinding lb=lbit.next(); - MethodDescriptor md=lb.getMethod(); - FlatMethod fm=state.getMethodFlat(md); - if (!md.getModifiers().isNative()) { - generateFlatMethod(fm, lb, outmethod); - } - } - } else { - Iterator classit=state.getClassSymbolTable().getDescriptorsIterator(); - while(classit.hasNext()) { - ClassDescriptor cn=(ClassDescriptor)classit.next(); - Iterator methodit=cn.getMethods(); - while(methodit.hasNext()) { - /* Classify parameters */ - MethodDescriptor md=(MethodDescriptor)methodit.next(); - FlatMethod fm=state.getMethodFlat(md); - if (!md.getModifiers().isNative()) { - generateFlatMethod(fm, null, outmethod); - } - } - } - } + } + + protected void outputStructs(PrintWriter outstructs) { + outstructs.println("#ifndef STRUCTDEFS_H"); + outstructs.println("#define STRUCTDEFS_H"); + outstructs.println("#include \"classdefs.h\""); + + /* Output #defines that the runtime uses to determine type + * numbers for various objects it needs */ + outstructs.println("#define MAXCOUNT "+maxcount); + if (state.DSM) { + LocalityBinding lb=new LocalityBinding(typeutil.getRun(), false); + lb.setGlobalThis(LocalityAnalysis.GLOBAL); + outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lb)); } - protected void outputStructs(PrintWriter outstructs) { - outstructs.println("#ifndef STRUCTDEFS_H"); - outstructs.println("#define STRUCTDEFS_H"); - outstructs.println("#include \"classdefs.h\""); + outstructs.println("#define STRINGARRAYTYPE "+ + (state.getArrayNumber( + (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses())); - /* Output #defines that the runtime uses to determine type - * numbers for various objects it needs */ - outstructs.println("#define MAXCOUNT "+maxcount); - if (state.DSM) { - LocalityBinding lb=new LocalityBinding(typeutil.getRun(), false); - lb.setGlobalThis(LocalityAnalysis.GLOBAL); - outstructs.println("#define RUNMETHOD "+virtualcalls.getLocalityNumber(lb)); - } - - outstructs.println("#define STRINGARRAYTYPE "+ - (state.getArrayNumber( - (new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass))).makeArray(state))+state.numClasses())); + outstructs.println("#define OBJECTARRAYTYPE "+ + (state.getArrayNumber( + (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses())); - outstructs.println("#define OBJECTARRAYTYPE "+ - (state.getArrayNumber( - (new TypeDescriptor(typeutil.getClass(TypeUtil.ObjectClass))).makeArray(state))+state.numClasses())); + outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId()); + outstructs.println("#define CHARARRAYTYPE "+ + (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses())); - outstructs.println("#define STRINGTYPE "+typeutil.getClass(TypeUtil.StringClass).getId()); - outstructs.println("#define CHARARRAYTYPE "+ - (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.CHAR)).makeArray(state))+state.numClasses())); + outstructs.println("#define BYTEARRAYTYPE "+ + (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses())); - outstructs.println("#define BYTEARRAYTYPE "+ - (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state))+state.numClasses())); + outstructs.println("#define BYTEARRAYARRAYTYPE "+ + (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses())); - outstructs.println("#define BYTEARRAYARRAYTYPE "+ - (state.getArrayNumber((new TypeDescriptor(TypeDescriptor.BYTE)).makeArray(state).makeArray(state))+state.numClasses())); - - outstructs.println("#define NUMCLASSES "+state.numClasses()); - if (state.TASK) { - outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId()); - outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId()); - outstructs.println("#define TAGARRAYTYPE "+ - (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses())); - } + outstructs.println("#define NUMCLASSES "+state.numClasses()); + if (state.TASK) { + outstructs.println("#define STARTUPTYPE "+typeutil.getClass(TypeUtil.StartupClass).getId()); + outstructs.println("#define TAGTYPE "+typeutil.getClass(TypeUtil.TagClass).getId()); + outstructs.println("#define TAGARRAYTYPE "+ + (state.getArrayNumber(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass)).makeArray(state))+state.numClasses())); } - - protected void outputClassDeclarations(PrintWriter outclassdefs) { - if (state.THREAD||state.DSM) - outclassdefs.println("#include "); - if(state.OPTIONAL) - outclassdefs.println("#include \"optionalstruct.h\""); - outclassdefs.println("struct "+arraytype+";"); - /* Start by declaring all structs */ - Iterator it=state.getClassSymbolTable().getDescriptorsIterator(); - while(it.hasNext()) { - ClassDescriptor cn=(ClassDescriptor)it.next(); - outclassdefs.println("struct "+cn.getSafeSymbol()+";"); - } - outclassdefs.println(""); - //Print out definition for array type - outclassdefs.println("struct "+arraytype+" {"); - outclassdefs.println(" int type;"); - if (state.THREAD) { - outclassdefs.println(" pthread_t tid;"); - outclassdefs.println(" void * lockentry;"); - outclassdefs.println(" int lockcount;"); - } - if (state.TASK) { - outclassdefs.println(" int flag;"); - if(!state.MULTICORE) { - outclassdefs.println(" void * flagptr;"); - } else { - outclassdefs.println(" int isolate;"); // indicate if this object is shared or not - outclassdefs.println(" int version;"); - outclassdefs.println(" struct ___Object___ * original;"); - } - if(state.OPTIONAL){ - outclassdefs.println(" int numfses;"); - outclassdefs.println(" int * fses;"); - } - } - printClassStruct(typeutil.getClass(TypeUtil.ObjectClass), outclassdefs); - - outclassdefs.println(" int ___length___;"); - outclassdefs.println("};\n"); - outclassdefs.println("extern int classsize[];"); - outclassdefs.println("extern int hasflags[];"); - outclassdefs.println("extern unsigned int * pointerarray[];"); - outclassdefs.println("extern int supertypes[];"); - } - - /** Prints out definitions for generic task structures */ - - private void outputTaskTypes(PrintWriter outtask) { - outtask.println("#ifndef _TASK_H"); - outtask.println("#define _TASK_H"); - outtask.println("struct parameterdescriptor {"); - outtask.println("int type;"); - outtask.println("int numberterms;"); - outtask.println("int *intarray;"); - outtask.println("void * queue;"); - outtask.println("int numbertags;"); - outtask.println("int *tagarray;"); - outtask.println("};"); - - outtask.println("struct taskdescriptor {"); - outtask.println("void * taskptr;"); - outtask.println("int numParameters;"); - outtask.println(" int numTotal;"); - outtask.println("struct parameterdescriptor **descriptorarray;"); - outtask.println("char * name;"); - outtask.println("};"); - outtask.println("extern struct taskdescriptor * taskarray[];"); - outtask.println("extern numtasks;"); - outtask.println("#endif"); - } - - - private void buildRepairStructs(PrintWriter outrepairstructs) { - Iterator classit=state.getClassSymbolTable().getDescriptorsIterator(); - while(classit.hasNext()) { - ClassDescriptor cn=(ClassDescriptor)classit.next(); - outrepairstructs.println("structure "+cn.getSymbol()+" {"); - outrepairstructs.println(" int __type__;"); - if (state.TASK) { - outrepairstructs.println(" int __flag__;"); - if(!state.MULTICORE) { - outrepairstructs.println(" int __flagptr__;"); - } - } - printRepairStruct(cn, outrepairstructs); - outrepairstructs.println("}\n"); - } - - for(int i=0;i"); + if(state.OPTIONAL) + outclassdefs.println("#include \"optionalstruct.h\""); + outclassdefs.println("struct "+arraytype+";"); + /* Start by declaring all structs */ + Iterator it=state.getClassSymbolTable().getDescriptorsIterator(); + while(it.hasNext()) { + ClassDescriptor cn=(ClassDescriptor)it.next(); + outclassdefs.println("struct "+cn.getSafeSymbol()+";"); } - - private void printRepairStruct(ClassDescriptor cn, PrintWriter output) { - ClassDescriptor sp=cn.getSuperDesc(); - if (sp!=null) - printRepairStruct(sp, output); - - Vector fields=(Vector)fieldorder.get(cn); - - for(int i=0;imaxcount) - maxcount=virtualcalls.getMethodCount(cd); - } - MethodDescriptor[][] virtualtable=null; - LocalityBinding[][] lbvirtualtable=null; - if (state.DSM) - lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount]; - else - virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount]; - - /* Fill in virtual table */ - classit=state.getClassSymbolTable().getDescriptorsIterator(); - while(classit.hasNext()) { - ClassDescriptor cd=(ClassDescriptor)classit.next(); - if (state.DSM) - fillinRow(cd, lbvirtualtable, cd.getId()); - else - fillinRow(cd, virtualtable, cd.getId()); - } - - ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass); - Iterator arrayit=state.getArrayIterator(); - while(arrayit.hasNext()) { - TypeDescriptor td=(TypeDescriptor)arrayit.next(); - int id=state.getArrayNumber(td); - if (state.DSM) - fillinRow(objectcd, lbvirtualtable, id+state.numClasses()); - else - fillinRow(objectcd, virtualtable, id+state.numClasses()); - } - - outvirtual.print("void * virtualtable[]={"); - 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; - } + output.println("};"); + + output.println("struct taskdescriptor task_"+task.getSafeSymbol()+"={"); + output.println("&"+task.getSafeSymbol()+","); + output.println("/* number of parameters */" +task.numParameters() + ","); + int numtotal=task.numParameters()+fm.numTags(); + output.println("/* number total parameters */" +numtotal + ","); + output.println("parameterdescriptors_"+task.getSafeSymbol()+","); + output.println("\""+task.getSymbol()+"\""); + output.println("};"); + } + + + /** The buildVirtualTables method outputs the virtual dispatch + * tables for methods. */ + + protected void buildVirtualTables(PrintWriter outvirtual) { + Iterator classit=state.getClassSymbolTable().getDescriptorsIterator(); + while(classit.hasNext()) { + ClassDescriptor cd=(ClassDescriptor)classit.next(); + if (virtualcalls.getMethodCount(cd)>maxcount) + maxcount=virtualcalls.getMethodCount(cd); + } + MethodDescriptor[][] virtualtable=null; + LocalityBinding[][] lbvirtualtable=null; + if (state.DSM) + lbvirtualtable=new LocalityBinding[state.numClasses()+state.numArrays()][maxcount]; + else + virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount]; + + /* Fill in virtual table */ + classit=state.getClassSymbolTable().getDescriptorsIterator(); + while(classit.hasNext()) { + ClassDescriptor cd=(ClassDescriptor)classit.next(); + if (state.DSM) + fillinRow(cd, lbvirtualtable, cd.getId()); + else + fillinRow(cd, virtualtable, cd.getId()); } + ClassDescriptor objectcd=typeutil.getClass(TypeUtil.ObjectClass); + Iterator arrayit=state.getArrayIterator(); + while(arrayit.hasNext()) { + TypeDescriptor td=(TypeDescriptor)arrayit.next(); + int id=state.getArrayNumber(td); + if (state.DSM) + fillinRow(objectcd, lbvirtualtable, id+state.numClasses()); + else + fillinRow(objectcd, virtualtable, id+state.numClasses()); + } - /** Generate array that contains the sizes of class objects. The - * object allocation functions in the runtime use this - * information. */ - - private void generateSizeArray(PrintWriter outclassdefs) { - outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n"); - outclassdefs.print("#ifdef TRANSSTATS \n"); - outclassdefs.print("extern int numTransAbort;\n"); - outclassdefs.print("extern int numTransCommit;\n"); - outclassdefs.print("extern int nchashSearch;\n"); - outclassdefs.print("extern int nmhashSearch;\n"); - outclassdefs.print("extern int nprehashSearch;\n"); - outclassdefs.print("extern int nRemoteSend;\n"); - outclassdefs.print("extern void handle();\n"); - outclassdefs.print("#endif\n"); - outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n"); - - outclassdefs.print("int classsize[]={"); - Iterator it=state.getClassSymbolTable().getDescriptorsIterator(); - cdarray=new ClassDescriptor[state.numClasses()]; - while(it.hasNext()) { - ClassDescriptor cd=(ClassDescriptor)it.next(); - cdarray[cd.getId()]=cd; - } - 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; + } + } + + + /** Generate array that contains the sizes of class objects. The + * object allocation functions in the runtime use this + * information. */ + + private void generateSizeArray(PrintWriter outclassdefs) { + outclassdefs.print("extern struct prefetchCountStats * evalPrefetch;\n"); + outclassdefs.print("#ifdef TRANSSTATS \n"); + outclassdefs.print("extern int numTransAbort;\n"); + outclassdefs.print("extern int numTransCommit;\n"); + outclassdefs.print("extern int nchashSearch;\n"); + outclassdefs.print("extern int nmhashSearch;\n"); + outclassdefs.print("extern int nprehashSearch;\n"); + outclassdefs.print("extern int nRemoteSend;\n"); + outclassdefs.print("extern void handle();\n"); + outclassdefs.print("#endif\n"); + outclassdefs.print("int numprefetchsites = " + pa.prefetchsiteid + ";\n"); + + outclassdefs.print("int classsize[]={"); + Iterator it=state.getClassSymbolTable().getDescriptorsIterator(); + cdarray=new ClassDescriptor[state.numClasses()]; + while(it.hasNext()) { + ClassDescriptor cd=(ClassDescriptor)it.next(); + cdarray[cd.getId()]=cd; + } + boolean needcomma=false; + for(int i=0; i saveset=lb!=null ? locality.getTempSet(lb) : null; + ParamsObject objectparams=md!=null ? new ParamsObject(md,tag++) : new ParamsObject(task, tag++); + + if (lb!=null) + paramstable.put(lb, objectparams); + else if (md!=null) + paramstable.put(md, objectparams); + else + paramstable.put(task, objectparams); + + for(int i=0; i saveset=lb!=null?locality.getTempSet(lb):null; - ParamsObject objectparams=md!=null?new ParamsObject(md,tag++):new ParamsObject(task, tag++); + for(int i=0; i tmpit=backuptable.values().iterator(); tmpit.hasNext();) { + TempDescriptor tmp=tmpit.next(); + TypeDescriptor type=tmp.getType(); + if (type.isPtr()&&GENERATEPRECISEGC) + objecttemps.addPtr(tmp); else - tempstable.put(task, objecttemps); - - for(Iterator nodeit=fm.getNodeSet().iterator();nodeit.hasNext();) { - FlatNode fn=(FlatNode)nodeit.next(); - TempDescriptor[] writes=fn.writesTemps(); - for(int i=0;i tmpit=backuptable.values().iterator();tmpit.hasNext();) { - TempDescriptor tmp=tmpit.next(); - TypeDescriptor type=tmp.getType(); - if (type.isPtr()&&GENERATEPRECISEGC) - objecttemps.addPtr(tmp); - else - objecttemps.addPrim(tmp); - } - /* Create temp to hold revert table */ - if (lb.getHasAtomic()||lb.isAtomic()) { - TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass)); - if (GENERATEPRECISEGC) - objecttemps.addPtr(reverttmp); - else - objecttemps.addPrim(reverttmp); - reverttable.put(lb, reverttmp); - } - } + objecttemps.addPrim(tmp); + } + /* Create temp to hold revert table */ + if (lb.getHasAtomic()||lb.isAtomic()) { + TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass)); + if (GENERATEPRECISEGC) + objecttemps.addPtr(reverttmp); + else + objecttemps.addPrim(reverttmp); + reverttable.put(lb, reverttmp); + } } - - /** This method outputs the following information about classes - * and arrays: - * (1) For classes, what are the locations of pointers. - * (2) For arrays, does the array contain pointers or primitives. - * (3) For classes, does the class contain flags. - */ - - private void generateLayoutStructs(PrintWriter output) { - Iterator it=state.getClassSymbolTable().getDescriptorsIterator(); - while(it.hasNext()) { - ClassDescriptor cn=(ClassDescriptor)it.next(); - output.println("unsigned int "+cn.getSafeSymbol()+"_pointers[]={"); - 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++; - } - 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 int)&(((struct "+cn.getSafeSymbol() +" *)0)->"+fd.getSafeSymbol()+"))"); - } - } - output.println("};"); - } - output.println("unsigned int * pointerarray[]={"); - boolean needcomma=false; - for(int i=0;i"+fd.getSafeSymbol()+"))"); + } + } + output.println("};"); } - - /** Print out table to give us supertypes */ - private void generateSuperTypeTable(PrintWriter output) { - output.println("int supertypes[]={"); - boolean needcomma=false; - for(int i=0;imax) - 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++)); - } - } + output.println("};"); + needcomma=false; + output.println("int hasflags[]={"); + for(int i=0; imax) + 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++)); + } + } + } - /** This function outputs (1) structures that parameters are - * passed in (when PRECISE GC is enabled) and (2) function - * prototypes for the methods */ - - protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) { - /* Output class structure */ - classdefout.println("struct "+cn.getSafeSymbol()+" {"); - classdefout.println(" int type;"); - if (state.THREAD) { - classdefout.println(" pthread_t tid;"); - classdefout.println(" void * lockentry;"); - classdefout.println(" int lockcount;"); - } - - if (state.TASK) { - classdefout.println(" int flag;"); - if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) { - classdefout.println(" void * flagptr;"); - } else if (state.MULTICORE){ - classdefout.println(" int isolate;"); // indicate if this object is shared or not - classdefout.println(" int version;"); - classdefout.println(" struct ___Object___ * original;"); - } - if (state.OPTIONAL){ - classdefout.println(" int numfses;"); - classdefout.println(" int * fses;"); - } - } - printClassStruct(cn, classdefout); - classdefout.println("};\n"); - - if (state.DSM) { - /* Cycle through LocalityBindings */ - HashSet nativemethods=new HashSet(); - Set 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); - } - } - 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); - } - } + /** This function outputs (1) structures that parameters are + * passed in (when PRECISE GC is enabled) and (2) function + * prototypes for the methods */ - } else - for(Iterator methodit=cn.getMethods();methodit.hasNext();) { - MethodDescriptor md=(MethodDescriptor)methodit.next(); - generateMethod(cn, md, null, headersout, output); - } + protected void generateCallStructs(ClassDescriptor cn, PrintWriter classdefout, PrintWriter output, PrintWriter headersout) { + /* Output class structure */ + classdefout.println("struct "+cn.getSafeSymbol()+" {"); + classdefout.println(" int type;"); + if (state.THREAD) { + classdefout.println(" pthread_t tid;"); + classdefout.println(" void * lockentry;"); + classdefout.println(" int lockcount;"); } - private void generateMethodParam(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter output) { - /* Output parameter structure */ - if (GENERATEPRECISEGC) { - ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null?lb:md); - if (state.DSM&&lb!=null) - 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(" int size;"); - output.println(" void * next;"); - for(int i=0;i nativemethods=new HashSet(); + Set 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 - headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix); - printcomma=true; - } - - if (state.DSM&&lb.isAtomic()&&!md.getModifiers().isNative()) { - if (printcomma) - headersout.print(", "); - headersout.print("transrecord_t * trans"); - printcomma=true; - } - - /* Output parameter list*/ - for(int i=0;imaxtaskparams) { - maxtaskparams=objectparams.numPointers()+fm.numTags(); - } - } + ParamsObject objectparams=(ParamsObject) paramstable.get(task); + TempObject objecttemps=(TempObject) tempstable.get(task); - /* Output temp structure */ - if (GENERATEPRECISEGC) { - output.println("struct "+task.getSafeSymbol()+"_locals {"); - output.println(" int size;"); - output.println(" void * next;"); - for(int i=0;imaxtaskparams) { + maxtaskparams=objectparams.numPointers()+fm.numTags(); + } + } + + /* Output temp structure */ + if (GENERATEPRECISEGC) { + output.println("struct "+task.getSafeSymbol()+"_locals {"); + output.println(" int size;"); + output.println(" void * next;"); + for(int i=0; i nodetolabel=assignLabels(fm); - - /* Check to see if we need to do a GC if this is a - * multi-threaded program...*/ + /* Output task declaration */ + headersout.print("void " + task.getSafeSymbol()+"("); - if ((state.THREAD||state.DSM)&&GENERATEPRECISEGC) { - if (state.DSM&&lb.isAtomic()) - output.println("checkcollect2(&"+localsprefix+",trans);"); - else - output.println("checkcollect(&"+localsprefix+");"); - } - - /* Do the actual code generation */ - FlatNode current_node=null; - HashSet tovisit=new HashSet(); - HashSet visited=new HashSet(); - tovisit.add(fm.getNext(0)); - while(current_node!=null||!tovisit.isEmpty()) { - if (current_node==null) { - current_node=(FlatNode)tovisit.iterator().next(); - tovisit.remove(current_node); - } - visited.add(current_node); - if (nodetolabel.containsKey(current_node)) - output.println("L"+nodetolabel.get(current_node)+":"); - if (state.INSTRUCTIONFAILURE) { - if (state.THREAD||state.DSM) { - output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}"); - } - else - output.println("if ((--instructioncount)==0) injectinstructionfailure();"); - } - if (current_node.numNext()==0) { - output.print(" "); - generateFlatNode(fm, lb, current_node, output); - if (current_node.kind()!=FKind.FlatReturnNode) { - output.println(" return;"); - } - current_node=null; - } else if(current_node.numNext()==1) { - output.print(" "); - generateFlatNode(fm, lb, 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, lb, (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(); - } - output.println("}\n\n"); - } - - /** This method assigns labels to FlatNodes */ - - protected Hashtable assignLabels(FlatMethod fm) { - HashSet tovisit=new HashSet(); - HashSet visited=new HashSet(); - int labelindex=0; - Hashtable nodetolabel=new Hashtable(); - tovisit.add(fm.getNext(0)); - - /*Assign labels first. A node needs a label if the previous - * node has two exits or this node is a join point. */ - - while(!tovisit.isEmpty()) { - FlatNode fn=(FlatNode)tovisit.iterator().next(); - tovisit.remove(fn); - visited.add(fn); - 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++)); - } - } - } - return nodetolabel; + boolean printcomma=false; + if (GENERATEPRECISEGC) { + headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix); + } else + headersout.print("void * parameterarray[]"); + headersout.println(");\n"); } + } + /***** Generate code for FlatMethod fm. *****/ - /** Generate text string that corresponds to the TempDescriptor td. */ - protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) { - MethodDescriptor md=fm.getMethod(); - TaskDescriptor task=fm.getTask(); - TempObject objecttemps=(TempObject) tempstable.get(lb!=null?lb:md!=null?md:task); + private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) { + if (State.PRINTFLAT) + System.out.println(fm.printMethod()); + MethodDescriptor md=fm.getMethod(); - if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) { - return td.getSafeSymbol(); - } + TaskDescriptor task=fm.getTask(); - if (objecttemps.isLocalPtr(td)) { - return localsprefix+"."+td.getSafeSymbol(); - } + ClassDescriptor cn=md!=null ? md.getClassDesc() : null; - if (objecttemps.isParamPtr(td)) { - return paramsprefix+"->"+td.getSafeSymbol(); - } - throw new Error(); - } - - protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) { - switch(fn.kind()) { - case FKind.FlatAtomicEnterNode: - generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output); - return; - case FKind.FlatAtomicExitNode: - generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output); - return; - case FKind.FlatGlobalConvNode: - generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output); - return; - case FKind.FlatTagDeclaration: - generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output); - return; - case FKind.FlatCall: - generateFlatCall(fm, lb, (FlatCall) fn,output); - return; - case FKind.FlatFieldNode: - generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output); - return; - case FKind.FlatElementNode: - generateFlatElementNode(fm, lb, (FlatElementNode) fn,output); - return; - case FKind.FlatSetElementNode: - generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output); - return; - case FKind.FlatSetFieldNode: - generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output); - return; - case FKind.FlatNew: - generateFlatNew(fm, lb, (FlatNew) fn,output); - return; - case FKind.FlatOpNode: - generateFlatOpNode(fm, lb, (FlatOpNode) fn,output); - return; - case FKind.FlatCastNode: - generateFlatCastNode(fm, lb, (FlatCastNode) fn,output); - return; - case FKind.FlatLiteralNode: - generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output); - return; - case FKind.FlatReturnNode: - generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output); - return; - case FKind.FlatNop: - output.println("/* nop */"); - return; - case FKind.FlatBackEdge: - if ((state.THREAD||state.DSM)&&GENERATEPRECISEGC) { - if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) { - output.println("checkcollect2(&"+localsprefix+",trans);"); - } else - output.println("checkcollect(&"+localsprefix+");"); - } else - output.println("/* nop */"); - return; - case FKind.FlatCheckNode: - generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output); - return; - case FKind.FlatFlagActionNode: - generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output); - return; - case FKind.FlatPrefetchNode: - generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output); - return; - } - throw new Error(); - } - - public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) { - if (state.PREFETCH) { - Vector oids = new Vector(); - Vector fieldoffset = new Vector(); - 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(lb,fpn).get(pp.base); - /* Find prefetches that can generate oid */ - if(statusbase == LocalityAnalysis.GLOBAL) { - generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false); - tuplecount++; - } else if (statusbase == LocalityAnalysis.LOCAL) { - generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true); - } else { - continue; - } - } - if (tuplecount==0) - return; - System.out.println("Adding prefetch "+fpn+ " to method:" +fm); - output.println("{"); - output.println("/* prefetch */"); - output.println("/* prefetchid_" + fpn.siteid + " */"); - output.println("void * prefptr;"); - output.println("int tmpindex;"); - - output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {"); - /*Create C code for oid array */ - 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; - } - output.println("};"); - - /*Create C code for endoffset values */ - output.print(" unsigned short endoffsetarry_[] = {"); - needcomma=false; - for (Iterator it = endoffset.iterator();it.hasNext();) { - if (needcomma) - output.print(", "); - output.print(it.next()); - needcomma=true; - } - output.println("};"); - - /*Create C code for Field Offset Values */ - output.print(" short fieldarry_[] = {"); - needcomma=false; - for (Iterator it = fieldoffset.iterator();it.hasNext();) { - if (needcomma) - output.print(", "); - output.print(it.next()); - needcomma=true; - } - output.println("};"); - /* make the prefetch call to Runtime */ - output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {"); - output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;"); - output.println(" }"); - output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);"); - output.println(" } else {"); - output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;"); - output.println(" }"); - output.println("}"); - } - } - - public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) { - short offsetcount = 0; - int breakindex=0; - if (inside) { - breakindex=1; - } else if (localbase) { - for(;breakindexpp.desc.size()) //all local - return; - - TypeDescriptor lasttype=pp.base.getType(); - String basestr=generateTemp(fm, pp.base, lb); - String teststr=""; - boolean maybenull=fm.getMethod().isStatic()|| - !pp.base.equals(fm.getParameter(0)); - - for(int i=0;i"+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___)"; - - if (!teststr.equals("")) - teststr+="&&"; - teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck; - basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]"; - maybenull=true; - lasttype=lasttype.dereference(); - } - } - - String oid; - if (teststr.equals("")) { - oid="((unsigned int)"+basestr+")"; - } else { - oid="((unsigned int)(("+teststr+")?"+basestr+":NULL))"; - } - oids.add(oid); - - for(int i = breakindex; i < pp.desc.size(); i++) { - 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(); - } else { - newfieldoffset = ""; - IndexDescriptor id=(IndexDescriptor)desc; - for(int j = 0; j < id.tddesc.size(); j++) { - newfieldoffset += generateTemp(fm, id.getTempDescAt(j), lb) + "+"; - } - newfieldoffset += id.offset.toString(); - lasttype=lasttype.dereference(); - } - fieldoffset.add(newfieldoffset); - } - - int base=(tuplecount>0)?((Short)endoffset.get(tuplecount-1)).intValue():0; - base+=pp.desc.size()-breakindex; - endoffset.add(new Short((short)base)); + ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : md!=null ? md : task); + generateHeader(fm, lb, md!=null ? md : task,output); + TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task); + if (state.DSM&&lb.getHasAtomic()) { + output.println("transrecord_t * trans;"); } - - - public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) { - if (lb!=fgcn.getLocality()) - return; - /* Have to generate flat globalconv */ - if (fgcn.getMakePtr()) { - output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)transRead(trans, (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");"); - } else { - /* Need to convert to OID */ - output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");"); - } + if (GENERATEPRECISEGC) { + if (md!=null&&state.DSM) + output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={"); + else if (md!=null&&!state.DSM) + output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={"); + else + output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={"); + + output.print(objecttemp.numPointers()+","); + output.print(paramsprefix); + for(int j=0; j0) - return; - /* Backup the temps. */ - for(Iterator tmpit=locality.getTemps(lb).get(faen).iterator();tmpit.hasNext();) { - TempDescriptor tmp=tmpit.next(); - output.println(generateTemp(fm, backuptable.get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";"); - } - output.println("goto transstart"+faen.getIdentifier()+";"); - - /******* Print code to retry aborted transaction *******/ - output.println("transretry"+faen.getIdentifier()+":"); + for(int i=0; i tmpit=locality.getTemps(lb).get(faen).iterator();tmpit.hasNext();) { - TempDescriptor tmp=tmpit.next(); - output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(tmp),lb)+";"); - } + /* Assign labels to FlatNode's if necessary.*/ - /********* Need to revert local object store ********/ - String revertptr=generateTemp(fm, reverttable.get(lb),lb); + Hashtable nodetolabel=assignLabels(fm); - output.println("while ("+revertptr+") {"); - output.println("struct ___Object___ * tmpptr;"); - output.println("tmpptr="+revertptr+"->"+nextobjstr+";"); - output.println("REVERT_OBJ("+revertptr+");"); - output.println(revertptr+"=tmpptr;"); - output.println("}"); + /* Check to see if we need to do a GC if this is a + * multi-threaded program...*/ - /******* Tell the runtime to start the transaction *******/ - - output.println("transstart"+faen.getIdentifier()+":"); - output.println("trans=transStart();"); + if ((state.THREAD||state.DSM)&&GENERATEPRECISEGC) { + if (state.DSM&&lb.isAtomic()) + output.println("checkcollect2(&"+localsprefix+",trans);"); + else + output.println("checkcollect(&"+localsprefix+");"); } - public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) { - /* Check to see if we need to generate code for this atomic */ - if (locality.getAtomic(lb).get(faen).intValue()>0) - return; - //store the revert list before we lose the transaction object - String revertptr=generateTemp(fm, reverttable.get(lb),lb); - output.println(revertptr+"=trans->revertlist;"); - output.println("if (transCommit(trans)) {"); - /* Transaction aborts if it returns true */ - output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";"); - output.println("} else {"); - /* Need to commit local object store */ - output.println("while ("+revertptr+") {"); - output.println("struct ___Object___ * tmpptr;"); - output.println("tmpptr="+revertptr+"->"+nextobjstr+";"); - output.println("COMMIT_OBJ("+revertptr+");"); - output.println(revertptr+"=tmpptr;"); - output.println("}"); - output.println("}"); + /* Do the actual code generation */ + FlatNode current_node=null; + HashSet tovisit=new HashSet(); + HashSet visited=new HashSet(); + tovisit.add(fm.getNext(0)); + while(current_node!=null||!tovisit.isEmpty()) { + if (current_node==null) { + current_node=(FlatNode)tovisit.iterator().next(); + tovisit.remove(current_node); + } + visited.add(current_node); + if (nodetolabel.containsKey(current_node)) + output.println("L"+nodetolabel.get(current_node)+":"); + if (state.INSTRUCTIONFAILURE) { + if (state.THREAD||state.DSM) { + output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}"); + } else + output.println("if ((--instructioncount)==0) injectinstructionfailure();"); + } + if (current_node.numNext()==0) { + output.print(" "); + generateFlatNode(fm, lb, current_node, output); + if (current_node.kind()!=FKind.FlatReturnNode) { + output.println(" return;"); + } + current_node=null; + } else if(current_node.numNext()==1) { + output.print(" "); + generateFlatNode(fm, lb, 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, lb, (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(); } + output.println("}\n\n"); + } + + /** This method assigns labels to FlatNodes */ + + protected Hashtable assignLabels(FlatMethod fm) { + HashSet tovisit=new HashSet(); + HashSet visited=new HashSet(); + int labelindex=0; + Hashtable nodetolabel=new Hashtable(); + tovisit.add(fm.getNext(0)); + + /*Assign labels first. A node needs a label if the previous + * node has two exits or this node is a join point. */ + + while(!tovisit.isEmpty()) { + FlatNode fn=(FlatNode)tovisit.iterator().next(); + tovisit.remove(fn); + visited.add(fn); + 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++)); + } + } + } + return nodetolabel; + } - private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) { - if (state.CONSCHECK) { - String specname=fcn.getSpec(); - String varname="repairstate___"; - output.println("{"); - output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();"); - TempDescriptor[] temps=fcn.getTemps(); - String[] vars=fcn.getVars(); - for(int i=0;i"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";"); - } + /** Generate text string that corresponds to the TempDescriptor td. */ + protected String generateTemp(FlatMethod fm, TempDescriptor td, LocalityBinding lb) { + MethodDescriptor md=fm.getMethod(); + TaskDescriptor task=fm.getTask(); + TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task); - output.println("if (doanalysis"+specname+"("+varname+")) {"); - output.println("free"+specname+"_state("+varname+");"); - output.println("} else {"); - output.println("/* Bad invariant */"); - output.println("free"+specname+"_state("+varname+");"); - output.println("abort_task();"); - output.println("}"); - output.println("}"); - } + if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) { + return td.getSafeSymbol(); } - private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) { - MethodDescriptor md=fc.getMethod(); - ParamsObject objectparams=(ParamsObject)paramstable.get(state.DSM?locality.getBinding(lb, fc):md); - ClassDescriptor cn=md.getClassDesc(); - output.println("{"); - if (GENERATEPRECISEGC) { - if (state.DSM) { - LocalityBinding fclb=locality.getBinding(lb, 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(objectparams.numPointers()); - output.print(", & "+localsprefix); - if (md.getThis()!=null) { - output.print(", "); - output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb)); - } - 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()+"!"); - } - - - for(int i=0;i"+td.getSafeSymbol(); + } + throw new Error(); + } + + protected void generateFlatNode(FlatMethod fm, LocalityBinding lb, FlatNode fn, PrintWriter output) { + switch(fn.kind()) { + case FKind.FlatAtomicEnterNode: + generateFlatAtomicEnterNode(fm, lb, (FlatAtomicEnterNode) fn, output); + return; + + case FKind.FlatAtomicExitNode: + generateFlatAtomicExitNode(fm, lb, (FlatAtomicExitNode) fn, output); + return; + + case FKind.FlatGlobalConvNode: + generateFlatGlobalConvNode(fm, lb, (FlatGlobalConvNode) fn, output); + return; + + case FKind.FlatTagDeclaration: + generateFlatTagDeclaration(fm, lb, (FlatTagDeclaration) fn,output); + return; + + case FKind.FlatCall: + generateFlatCall(fm, lb, (FlatCall) fn,output); + return; + + case FKind.FlatFieldNode: + generateFlatFieldNode(fm, lb, (FlatFieldNode) fn,output); + return; + + case FKind.FlatElementNode: + generateFlatElementNode(fm, lb, (FlatElementNode) fn,output); + return; + + case FKind.FlatSetElementNode: + generateFlatSetElementNode(fm, lb, (FlatSetElementNode) fn,output); + return; + + case FKind.FlatSetFieldNode: + generateFlatSetFieldNode(fm, lb, (FlatSetFieldNode) fn,output); + return; + + case FKind.FlatNew: + generateFlatNew(fm, lb, (FlatNew) fn,output); + return; + + case FKind.FlatOpNode: + generateFlatOpNode(fm, lb, (FlatOpNode) fn,output); + return; + + case FKind.FlatCastNode: + generateFlatCastNode(fm, lb, (FlatCastNode) fn,output); + return; + + case FKind.FlatLiteralNode: + generateFlatLiteralNode(fm, lb, (FlatLiteralNode) fn,output); + return; + + case FKind.FlatReturnNode: + generateFlatReturnNode(fm, lb, (FlatReturnNode) fn,output); + return; + + case FKind.FlatNop: + output.println("/* nop */"); + return; + + case FKind.FlatBackEdge: + if ((state.THREAD||state.DSM)&&GENERATEPRECISEGC) { + if(state.DSM&&locality.getAtomic(lb).get(fn).intValue()>0) { + output.println("checkcollect2(&"+localsprefix+",trans);"); + } else + output.println("checkcollect(&"+localsprefix+");"); + } else + output.println("/* nop */"); + return; + + case FKind.FlatCheckNode: + generateFlatCheckNode(fm, lb, (FlatCheckNode) fn, output); + return; + + case FKind.FlatFlagActionNode: + generateFlatFlagActionNode(fm, lb, (FlatFlagActionNode) fn, output); + return; + + case FKind.FlatPrefetchNode: + generateFlatPrefetchNode(fm,lb, (FlatPrefetchNode) fn, output); + return; + } + throw new Error(); + } + + public void generateFlatPrefetchNode(FlatMethod fm, LocalityBinding lb, FlatPrefetchNode fpn, PrintWriter output) { + if (state.PREFETCH) { + Vector oids = new Vector(); + Vector fieldoffset = new Vector(); + 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(lb,fpn).get(pp.base); + /* Find prefetches that can generate oid */ + if(statusbase == LocalityAnalysis.GLOBAL) { + generateTransCode(fm, lb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(lb).get(fpn).intValue()>0, false); + tuplecount++; + } else if (statusbase == LocalityAnalysis.LOCAL) { + generateTransCode(fm,lb,pp,oids,fieldoffset,endoffset,tuplecount,false,true); + } else { + continue; + } + } + if (tuplecount==0) + return; + System.out.println("Adding prefetch "+fpn+ " to method:" +fm); + output.println("{"); + output.println("/* prefetch */"); + output.println("/* prefetchid_" + fpn.siteid + " */"); + output.println("void * prefptr;"); + output.println("int tmpindex;"); + + output.println("if((evalPrefetch["+fpn.siteid+"].operMode) || (evalPrefetch["+fpn.siteid+"].retrycount <= 0)) {"); + /*Create C code for oid array */ + 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; + } + output.println("};"); + + /*Create C code for endoffset values */ + output.print(" unsigned short endoffsetarry_[] = {"); + needcomma=false; + for (Iterator it = endoffset.iterator(); it.hasNext();) { + if (needcomma) + output.print(", "); + output.print(it.next()); + needcomma=true; + } + output.println("};"); + + /*Create C code for Field Offset Values */ + output.print(" short fieldarry_[] = {"); + needcomma=false; + for (Iterator it = fieldoffset.iterator(); it.hasNext();) { + if (needcomma) + output.print(", "); + output.print(it.next()); + needcomma=true; + } + output.println("};"); + /* make the prefetch call to Runtime */ + output.println(" if(!evalPrefetch["+fpn.siteid+"].operMode) {"); + output.println(" evalPrefetch["+fpn.siteid+"].retrycount = RETRYINTERVAL;"); + output.println(" }"); + output.println(" prefetch("+fpn.siteid+" ,"+tuplecount+", oidarray_, endoffsetarry_, fieldarry_);"); + output.println(" } else {"); + output.println(" evalPrefetch["+fpn.siteid+"].retrycount--;"); + output.println(" }"); + output.println("}"); + } + } + + public void generateTransCode(FlatMethod fm, LocalityBinding lb,PrefetchPair pp, Vector oids, Vector fieldoffset, Vector endoffset, int tuplecount, boolean inside, boolean localbase) { + short offsetcount = 0; + int breakindex=0; + if (inside) { + breakindex=1; + } else if (localbase) { + for(; breakindexpp.desc.size()) //all local + return; + + TypeDescriptor lasttype=pp.base.getType(); + String basestr=generateTemp(fm, pp.base, lb); + String teststr=""; + boolean maybenull=fm.getMethod().isStatic()|| + !pp.base.equals(fm.getParameter(0)); + + for(int i=0; i"+fd.getSafeSymbol(); } else { - //yes - output.print("(("); - if (md.getReturnType().isClass()||md.getReturnType().isArray()) - output.print("struct " + md.getReturnType().getSafeSymbol()+" * "); - else - output.print(md.getReturnType().getSafeSymbol()+" "); - output.print("(*)("); - - boolean printcomma=false; - if (GENERATEPRECISEGC) { - if (state.DSM) { - LocalityBinding fclb=locality.getBinding(lb, fc); - output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "); - } else - output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "); - printcomma=true; - } + 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___)"; + + if (!teststr.equals("")) + teststr+="&&"; + teststr+="((prefptr="+basestr+")!= NULL) &&"+indexcheck; + basestr="((void **)(((char *) &(((struct ArrayObject *)prefptr)->___length___))+sizeof(int)))[tmpindex]"; + maybenull=true; + lasttype=lasttype.dereference(); + } + } - for(int i=0;i"+ 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), lb) + "+"; + } + newfieldoffset += id.offset.toString(); + lasttype=lasttype.dereference(); + } + fieldoffset.add(newfieldoffset); + } - if (state.DSM&&locality.getBinding(lb,fc).isAtomic()&&!fc.getMethod().getModifiers().isNative()) { - LocalityBinding fclb=locality.getBinding(lb, fc); - if (printcomma) - output.print(", "); - output.print("transrecord_t *"); - printcomma=true; - } + int base=(tuplecount>0) ? ((Short)endoffset.get(tuplecount-1)).intValue() : 0; + base+=pp.desc.size()-breakindex; + endoffset.add(new Short((short)base)); + } - if (state.DSM) { - LocalityBinding fclb=locality.getBinding(lb, fc); - output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])"); - } else - output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])"); - } - output.print("("); - boolean needcomma=false; - if (GENERATEPRECISEGC) { - output.print("&__parameterlist__"); - needcomma=true; - } - if (state.DSM&&locality.getBinding(lb,fc).isAtomic()&&!fc.getMethod().getModifiers().isNative()) { - if (needcomma) - output.print(","); - output.print("trans"); - needcomma=true; - } + public void generateFlatGlobalConvNode(FlatMethod fm, LocalityBinding lb, FlatGlobalConvNode fgcn, PrintWriter output) { + if (lb!=fgcn.getLocality()) + return; + /* Have to generate flat globalconv */ + if (fgcn.getMakePtr()) { + output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)transRead(trans, (unsigned int) "+generateTemp(fm, fgcn.getSrc(),lb)+");"); + } else { + /* Need to convert to OID */ + output.println(generateTemp(fm, fgcn.getSrc(),lb)+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc(),lb)+");"); + } + } + + public void generateFlatAtomicEnterNode(FlatMethod fm, LocalityBinding lb, FlatAtomicEnterNode faen, PrintWriter output) { + /* Check to see if we need to generate code for this atomic */ + if (locality.getAtomic(lb).get(faen.getPrev(0)).intValue()>0) + return; + /* Backup the temps. */ + for(Iterator tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) { + TempDescriptor tmp=tmpit.next(); + output.println(generateTemp(fm, backuptable.get(tmp),lb)+"="+generateTemp(fm,tmp,lb)+";"); + } + output.println("goto transstart"+faen.getIdentifier()+";"); - if (!GENERATEPRECISEGC) { - if (fc.getThis()!=null) { - TypeDescriptor ptd=md.getThis().getType(); - if (needcomma) - output.print(","); - if (ptd.isClass()&&!ptd.isArray()) - output.print("(struct "+ptd.getSafeSymbol()+" *) "); - output.print(generateTemp(fm,fc.getThis(),lb)); - needcomma=true; - } - } + /******* Print code to retry aborted transaction *******/ + output.println("transretry"+faen.getIdentifier()+":"); - for(int i=0;i tmpit=locality.getTemps(lb).get(faen).iterator(); tmpit.hasNext();) { + TempDescriptor tmp=tmpit.next(); + output.println(generateTemp(fm, tmp,lb)+"="+generateTemp(fm,backuptable.get(tmp),lb)+";"); } - private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) { + /********* Need to revert local object store ********/ + String revertptr=generateTemp(fm, reverttable.get(lb),lb); + + output.println("while ("+revertptr+") {"); + output.println("struct ___Object___ * tmpptr;"); + output.println("tmpptr="+revertptr+"->"+nextobjstr+";"); + output.println("REVERT_OBJ("+revertptr+");"); + output.println(revertptr+"=tmpptr;"); + output.println("}"); + + /******* Tell the runtime to start the transaction *******/ + + output.println("transstart"+faen.getIdentifier()+":"); + output.println("trans=transStart();"); + } + + public void generateFlatAtomicExitNode(FlatMethod fm, LocalityBinding lb, FlatAtomicExitNode faen, PrintWriter output) { + /* Check to see if we need to generate code for this atomic */ + if (locality.getAtomic(lb).get(faen).intValue()>0) + return; + //store the revert list before we lose the transaction object + String revertptr=generateTemp(fm, reverttable.get(lb),lb); + output.println(revertptr+"=trans->revertlist;"); + output.println("if (transCommit(trans)) {"); + /* Transaction aborts if it returns true */ + output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";"); + output.println("} else {"); + /* Need to commit local object store */ + output.println("while ("+revertptr+") {"); + output.println("struct ___Object___ * tmpptr;"); + output.println("tmpptr="+revertptr+"->"+nextobjstr+";"); + output.println("COMMIT_OBJ("+revertptr+");"); + output.println(revertptr+"=tmpptr;"); + output.println("}"); + output.println("}"); + } + + private void generateFlatCheckNode(FlatMethod fm, LocalityBinding lb, FlatCheckNode fcn, PrintWriter output) { + if (state.CONSCHECK) { + String specname=fcn.getSpec(); + String varname="repairstate___"; + output.println("{"); + output.println("struct "+specname+"_state * "+varname+"=allocate"+specname+"_state();"); + + TempDescriptor[] temps=fcn.getTemps(); + String[] vars=fcn.getVars(); + for(int i=0; i"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i],lb)+";"); + } + + output.println("if (doanalysis"+specname+"("+varname+")) {"); + output.println("free"+specname+"_state("+varname+");"); + output.println("} else {"); + output.println("/* Bad invariant */"); + output.println("free"+specname+"_state("+varname+");"); + output.println("abort_task();"); + output.println("}"); + output.println("}"); + } + } + + private void generateFlatCall(FlatMethod fm, LocalityBinding lb, FlatCall fc, PrintWriter output) { + MethodDescriptor md=fc.getMethod(); + ParamsObject objectparams=(ParamsObject)paramstable.get(state.DSM ? locality.getBinding(lb, fc) : md); + ClassDescriptor cn=md.getClassDesc(); + output.println("{"); + if (GENERATEPRECISEGC) { + if (state.DSM) { + LocalityBinding fclb=locality.getBinding(lb, 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(objectparams.numPointers()); + output.print(", & "+localsprefix); + if (md.getThis()!=null) { + output.print(", "); + output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis(),lb)); + } + 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()+"!"); + } + + + for(int i=0; i"+field+"="+temp+";"); - //output.println("}"); - //output.println(dst+"=temp;"); - //output.println("}"); - //} else { - output.println(dst+"="+ src +"->"+field+ ";"); - //output.println("if ("+dst+"&0x1) {"); - output.println(dst+"=(void *) transRead(trans, (unsigned int) "+dst+");"); - //output.println(src+"->"+field+"="+src+"->"+field+";"); - //output.println("}"); - //} - } 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(),lb); - String dst=generateTemp(fm, ffn.getDst(),lb); - output.println(dst+"="+ src +"->"+field+ ";"); - if (locality.getAtomic(lb).get(ffn).intValue()>0) - output.println(dst+"=(void *) transRead(trans, (unsigned int) "+dst+");"); - } else - output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";"); - } else if (status==LocalityAnalysis.EITHER) { - //Code is reading from a null pointer - output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {"); - 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(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";"); - } else - throw new Error("Read from non-global/non-local in:"+lb.getExplanation()); + LocalityBinding fclb=locality.getBinding(lb, fc); + output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "); } else - output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";"); + output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "); + printcomma=true; + } + + for(int i=0; itype*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])"); + } else + output.print("))virtualtable["+generateTemp(fm,fc.getThis(),lb)+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])"); } + output.print("("); + boolean needcomma=false; + if (GENERATEPRECISEGC) { + output.print("&__parameterlist__"); + needcomma=true; + } - private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) { - if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray()) - throw new Error("Can't set array length"); - if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) { - Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc()); - Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst()); - boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL; + if (state.DSM&&locality.getBinding(lb,fc).isAtomic()&&!fc.getMethod().getModifiers().isNative()) { + if (needcomma) + output.print(","); + output.print("trans"); + needcomma=true; + } - String src=generateTemp(fm,fsfn.getSrc(),lb); - String dst=generateTemp(fm,fsfn.getDst(),lb); - if (srcglobal) { - output.println("{"); - output.println("int srcoid=(int)"+src+"->"+oidstr+";"); - } - if (statusdst.equals(LocalityAnalysis.GLOBAL)) { - String glbdst=dst; - //mark it dirty - output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;"); - if (srcglobal) { - output.println("*((unsigned int *)&("+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(lb),lb); - output.println(revertptr+"=trans->revertlist;"); - if (GENERATEPRECISEGC) - output.println("COPY_OBJ((struct garbagelist *)&"+localsprefix+",(struct ___Object___ *)"+dst+");"); - else - output.println("COPY_OBJ("+dst+");"); - output.println(dst+"->"+nextobjstr+"="+revertptr+";"); - output.println("trans->revertlist=(struct ___Object___ *)"+dst+";"); - output.println("}"); - if (srcglobal) - output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=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("#ifndef RAW"); - output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}"); - output.println("#endif"); - if (srcglobal) - output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=srcoid;"); - else - output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";"); - } - if (srcglobal) { - output.println("}"); - } + if (!GENERATEPRECISEGC) { + if (fc.getThis()!=null) { + TypeDescriptor ptd=md.getThis().getType(); + if (needcomma) + output.print(","); + if (ptd.isClass()&&!ptd.isArray()) + output.print("(struct "+ptd.getSafeSymbol()+" *) "); + output.print(generateTemp(fm,fc.getThis(),lb)); + needcomma=true; + } + } + + for(int i=0; i"+field+"="+temp+";"); + //output.println("}"); + //output.println(dst+"=temp;"); + //output.println("}"); + //} else { + output.println(dst+"="+ src +"->"+field+ ";"); + //output.println("if ("+dst+"&0x1) {"); + output.println(dst+"=(void *) transRead(trans, (unsigned int) "+dst+");"); + //output.println(src+"->"+field+"="+src+"->"+field+";"); + //output.println("}"); + //} } else { - output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";"); - } + 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(),lb); + String dst=generateTemp(fm, ffn.getDst(),lb); + output.println(dst+"="+ src +"->"+field+ ";"); + if (locality.getAtomic(lb).get(ffn).intValue()>0) + output.println(dst+"=(void *) transRead(trans, (unsigned int) "+dst+");"); + } else + output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";"); + } else if (status==LocalityAnalysis.EITHER) { + //Code is reading from a null pointer + output.println("if ("+generateTemp(fm, ffn.getSrc(),lb)+") {"); + 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(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";"); + } else + throw new Error("Read from non-global/non-local in:"+lb.getExplanation()); + } else + output.println(generateTemp(fm, ffn.getDst(),lb)+"="+ generateTemp(fm,ffn.getSrc(),lb)+"->"+ ffn.getField().getSafeSymbol()+";"); + } + + + private void generateFlatSetFieldNode(FlatMethod fm, LocalityBinding lb, FlatSetFieldNode fsfn, PrintWriter output) { + if (fsfn.getField().getSymbol().equals("length")&&fsfn.getDst().getType().isArray()) + throw new Error("Can't set array length"); + if (state.DSM && locality.getAtomic(lb).get(fsfn).intValue()>0) { + Integer statussrc=locality.getNodePreTempInfo(lb,fsfn).get(fsfn.getSrc()); + Integer statusdst=locality.getNodeTempInfo(lb).get(fsfn).get(fsfn.getDst()); + boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL; + + String src=generateTemp(fm,fsfn.getSrc(),lb); + String dst=generateTemp(fm,fsfn.getDst(),lb); + if (srcglobal) { + output.println("{"); + output.println("int srcoid=(int)"+src+"->"+oidstr+";"); + } + if (statusdst.equals(LocalityAnalysis.GLOBAL)) { + String glbdst=dst; + //mark it dirty + output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;"); + if (srcglobal) { + output.println("*((unsigned int *)&("+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(lb),lb); + output.println(revertptr+"=trans->revertlist;"); + if (GENERATEPRECISEGC) + output.println("COPY_OBJ((struct garbagelist *)&"+localsprefix+",(struct ___Object___ *)"+dst+");"); + else + output.println("COPY_OBJ("+dst+");"); + output.println(dst+"->"+nextobjstr+"="+revertptr+";"); + output.println("trans->revertlist=(struct ___Object___ *)"+dst+";"); + output.println("}"); + if (srcglobal) + output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=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("#ifndef RAW"); + output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}"); + output.println("#endif"); + if (srcglobal) + output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"=srcoid;"); + else + output.println(dst+"->"+ fsfn.getField().getSafeSymbol()+"="+ src+";"); + } + if (srcglobal) { + output.println("}"); + } + } else { + output.println(generateTemp(fm, fsfn.getDst(),lb)+"->"+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc(),lb)+";"); } + } - private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) { - TypeDescriptor elementtype=fen.getSrc().getType().dereference(); - String type=""; + private void generateFlatElementNode(FlatMethod fm, LocalityBinding lb, FlatElementNode fen, PrintWriter output) { + TypeDescriptor elementtype=fen.getSrc().getType().dereference(); + String type=""; - if (elementtype.isArray()||elementtype.isClass()) - type="void *"; - else - type=elementtype.getSafeSymbol()+" "; + if (elementtype.isArray()||elementtype.isClass()) + type="void *"; + else + type=elementtype.getSafeSymbol()+" "; - if (fen.needsBoundsCheck()) { - output.println("if ("+generateTemp(fm, fen.getIndex(),lb)+"< 0 || "+generateTemp(fm, fen.getIndex(),lb)+" >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___)"); - output.println("failedboundschk();"); - } - if (state.DSM) { - Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc()); - if (status==LocalityAnalysis.GLOBAL) { - String dst=generateTemp(fm, fen.getDst(),lb); - - if (elementtype.isPtr()) { - output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];"); - output.println(dst+"=(void *) transRead(trans, (unsigned int) "+dst+");"); - } else { - output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];"); - } - } else if (status==LocalityAnalysis.LOCAL) { - output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];"); - } else if (status==LocalityAnalysis.EITHER) { - //Code is reading from a null pointer - output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {"); - 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(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];"); - } else - throw new Error("Read from non-global/non-local in:"+lb.getExplanation()); + if (fen.needsBoundsCheck()) { + output.println("if ("+generateTemp(fm, fen.getIndex(),lb)+"< 0 || "+generateTemp(fm, fen.getIndex(),lb)+" >= "+generateTemp(fm,fen.getSrc(),lb) + "->___length___)"); + output.println("failedboundschk();"); + } + if (state.DSM) { + Integer status=locality.getNodePreTempInfo(lb,fen).get(fen.getSrc()); + if (status==LocalityAnalysis.GLOBAL) { + String dst=generateTemp(fm, fen.getDst(),lb); + + if (elementtype.isPtr()) { + output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];"); + output.println(dst+"=(void *) transRead(trans, (unsigned int) "+dst+");"); } else { - output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];"); - } + output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];"); + } + } else if (status==LocalityAnalysis.LOCAL) { + output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];"); + } else if (status==LocalityAnalysis.EITHER) { + //Code is reading from a null pointer + output.println("if ("+generateTemp(fm, fen.getSrc(),lb)+") {"); + 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(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];"); + } else + throw new Error("Read from non-global/non-local in:"+lb.getExplanation()); + } else { + output.println(generateTemp(fm, fen.getDst(),lb)+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex(),lb)+"];"); } + } - private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) { - //TODO: need dynamic check to make sure this assignment is actually legal - //Because Object[] could actually be something more specific...ie. Integer[] - - TypeDescriptor elementtype=fsen.getDst().getType().dereference(); - String type=""; + private void generateFlatSetElementNode(FlatMethod fm, LocalityBinding lb, FlatSetElementNode fsen, PrintWriter output) { + //TODO: need dynamic check to make sure this assignment is actually legal + //Because Object[] could actually be something more specific...ie. Integer[] - if (elementtype.isArray()||elementtype.isClass()) - type="void *"; - else - type=elementtype.getSafeSymbol()+" "; + TypeDescriptor elementtype=fsen.getDst().getType().dereference(); + String type=""; + if (elementtype.isArray()||elementtype.isClass()) + type="void *"; + else + type=elementtype.getSafeSymbol()+" "; - if (fsen.needsBoundsCheck()) { - output.println("if ("+generateTemp(fm, fsen.getIndex(),lb)+"< 0 || "+generateTemp(fm, fsen.getIndex(),lb)+" >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___)"); - output.println("failedboundschk();"); - } - if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) { - Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc()); - Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst()); - boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL; - boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL; - boolean dstlocal=statusdst==LocalityAnalysis.LOCAL; - - if (dstglobal) { - output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;"); - } else if (dstlocal) { - /** Check if we need to copy */ - String dst=generateTemp(fm, fsen.getDst(),lb); - output.println("if(!"+dst+"->"+localcopystr+") {"); - /* Link object into list */ - String revertptr=generateTemp(fm, reverttable.get(lb),lb); - output.println(revertptr+"=trans->revertlist;"); - if (GENERATEPRECISEGC) - output.println("COPY_OBJ((struct garbagelist *)&"+localsprefix+",(struct ___Object___ *)"+dst+");"); - else - output.println("COPY_OBJ("+dst+");"); - output.println(dst+"->"+nextobjstr+"="+revertptr+";"); - output.println("trans->revertlist=(struct ___Object___ *)"+dst+";"); - output.println("}"); - } else throw new Error("Unknown array type"); - if (srcglobal) { - output.println("{"); - String src=generateTemp(fm, fsen.getSrc(), lb); - output.println("int srcoid=(int)"+src+"->"+oidstr+";"); - output.println("((int*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;"); - output.println("}"); - } else { - output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";"); - } - } else - output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";"); + if (fsen.needsBoundsCheck()) { + output.println("if ("+generateTemp(fm, fsen.getIndex(),lb)+"< 0 || "+generateTemp(fm, fsen.getIndex(),lb)+" >= "+generateTemp(fm,fsen.getDst(),lb) + "->___length___)"); + output.println("failedboundschk();"); } - private void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) { - if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) { - //Stash pointer in case of GC - String revertptr=generateTemp(fm, reverttable.get(lb),lb); - output.println(revertptr+"=trans->revertlist;"); - } - if (fn.getType().isArray()) { - int arrayid=state.getArrayNumber(fn.getType())+state.numClasses(); - if (fn.isGlobal()) { - output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal(trans, "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");"); - } else if (GENERATEPRECISEGC) { - output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray(&"+localsprefix+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");"); - } else { - output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");"); - } - } else { - if (fn.isGlobal()) { - output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal(trans, "+fn.getType().getClassDesc().getId()+");"); - } else if (GENERATEPRECISEGC) { - output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new(&"+localsprefix+", "+fn.getType().getClassDesc().getId()+");"); - } else { - output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");"); - } - } - if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) { - String revertptr=generateTemp(fm, reverttable.get(lb),lb); - output.println("trans->revertlist="+revertptr+";"); - } + if (state.DSM && locality.getAtomic(lb).get(fsen).intValue()>0) { + Integer statussrc=locality.getNodePreTempInfo(lb,fsen).get(fsen.getSrc()); + Integer statusdst=locality.getNodePreTempInfo(lb,fsen).get(fsen.getDst()); + boolean srcglobal=statussrc==LocalityAnalysis.GLOBAL; + boolean dstglobal=statusdst==LocalityAnalysis.GLOBAL; + boolean dstlocal=statusdst==LocalityAnalysis.LOCAL; + + if (dstglobal) { + output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst(),lb)+"->___localcopy___))|=DIRTY;"); + } else if (dstlocal) { + /** Check if we need to copy */ + String dst=generateTemp(fm, fsen.getDst(),lb); + output.println("if(!"+dst+"->"+localcopystr+") {"); + /* Link object into list */ + String revertptr=generateTemp(fm, reverttable.get(lb),lb); + output.println(revertptr+"=trans->revertlist;"); + if (GENERATEPRECISEGC) + output.println("COPY_OBJ((struct garbagelist *)&"+localsprefix+",(struct ___Object___ *)"+dst+");"); + else + output.println("COPY_OBJ("+dst+");"); + output.println(dst+"->"+nextobjstr+"="+revertptr+";"); + output.println("trans->revertlist=(struct ___Object___ *)"+dst+";"); + output.println("}"); + } else throw new Error("Unknown array type"); + if (srcglobal) { + output.println("{"); + String src=generateTemp(fm, fsen.getSrc(), lb); + output.println("int srcoid=(int)"+src+"->"+oidstr+";"); + output.println("((int*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]=srcoid;"); + output.println("}"); + } else { + output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";"); + } + } else + output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst(),lb)+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex(),lb)+"]="+generateTemp(fm,fsen.getSrc(),lb)+";"); + } + + private void generateFlatNew(FlatMethod fm, LocalityBinding lb, FlatNew fn, PrintWriter output) { + if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) { + //Stash pointer in case of GC + String revertptr=generateTemp(fm, reverttable.get(lb),lb); + output.println(revertptr+"=trans->revertlist;"); } - - private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) { - if (GENERATEPRECISEGC) { - output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag(&"+localsprefix+", "+state.getTagId(fn.getType())+");"); - } else { - output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");"); - } + if (fn.getType().isArray()) { + int arrayid=state.getArrayNumber(fn.getType())+state.numClasses(); + if (fn.isGlobal()) { + output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarrayglobal(trans, "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");"); + } else if (GENERATEPRECISEGC) { + output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray(&"+localsprefix+", "+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");"); + } else { + output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize(),lb)+");"); + } + } else { + if (fn.isGlobal()) { + output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_newglobal(trans, "+fn.getType().getClassDesc().getId()+");"); + } else if (GENERATEPRECISEGC) { + output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new(&"+localsprefix+", "+fn.getType().getClassDesc().getId()+");"); + } else { + output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_new("+fn.getType().getClassDesc().getId()+");"); + } } + if (state.DSM && locality.getAtomic(lb).get(fn).intValue()>0&&!fn.isGlobal()) { + String revertptr=generateTemp(fm, reverttable.get(lb),lb); + output.println("trans->revertlist="+revertptr+";"); + } + } - private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, 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(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";"); - else - output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";"); + private void generateFlatTagDeclaration(FlatMethod fm, LocalityBinding lb, FlatTagDeclaration fn, PrintWriter output) { + if (GENERATEPRECISEGC) { + output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag(&"+localsprefix+", "+state.getTagId(fn.getType())+");"); + } else { + output.println(generateTemp(fm,fn.getDst(),lb)+"=allocate_tag("+state.getTagId(fn.getType())+");"); + } + } - } else - output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";"); - } else if (fon.getOp().getOp()==Operation.ASSIGN) - output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";"); - else if (fon.getOp().getOp()==Operation.UNARYPLUS) - output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";"); - else if (fon.getOp().getOp()==Operation.UNARYMINUS) - output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";"); - else if (fon.getOp().getOp()==Operation.LOGIC_NOT) - output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";"); - else if (fon.getOp().getOp()==Operation.COMP) - output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";"); - else if (fon.getOp().getOp()==Operation.ISAVAILABLE) { - output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;"); + private void generateFlatOpNode(FlatMethod fm, LocalityBinding lb, 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(),lb)+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";"); + else + output.println(generateTemp(fm, fon.getDest(),lb)+" = ((unsigned int)"+generateTemp(fm, fon.getLeft(),lb)+")>>"+generateTemp(fm,fon.getRight(),lb)+";"); + + } else + output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+fon.getOp().toString()+generateTemp(fm,fon.getRight(),lb)+";"); + } else if (fon.getOp().getOp()==Operation.ASSIGN) + output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";"); + else if (fon.getOp().getOp()==Operation.UNARYPLUS) + output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+";"); + else if (fon.getOp().getOp()==Operation.UNARYMINUS) + output.println(generateTemp(fm, fon.getDest(),lb)+" = -"+generateTemp(fm, fon.getLeft(),lb)+";"); + else if (fon.getOp().getOp()==Operation.LOGIC_NOT) + output.println(generateTemp(fm, fon.getDest(),lb)+" = !"+generateTemp(fm, fon.getLeft(),lb)+";"); + else if (fon.getOp().getOp()==Operation.COMP) + output.println(generateTemp(fm, fon.getDest(),lb)+" = ~"+generateTemp(fm, fon.getLeft(),lb)+";"); + else if (fon.getOp().getOp()==Operation.ISAVAILABLE) { + output.println(generateTemp(fm, fon.getDest(),lb)+" = "+generateTemp(fm, fon.getLeft(),lb)+"->fses==NULL;"); + } else + output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";"); + } + + private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) { + /* TODO: Do type check here */ + if (fcn.getType().isArray()) { + throw new Error(); + } else if (fcn.getType().isClass()) + output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";"); + else + output.println(generateTemp(fm,fcn.getDst(),lb)+"=("+fcn.getType().getSafeSymbol()+")"+generateTemp(fm,fcn.getSrc(),lb)+";"); + } + + private void generateFlatLiteralNode(FlatMethod fm, LocalityBinding lb, FlatLiteralNode fln, PrintWriter output) { + if (fln.getValue()==null) + output.println(generateTemp(fm, fln.getDst(),lb)+"=0;"); + else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) { + if (GENERATEPRECISEGC) { + if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) { + //Stash pointer in case of GC + String revertptr=generateTemp(fm, reverttable.get(lb),lb); + output.println(revertptr+"=trans->revertlist;"); + } + output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(&"+localsprefix+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");"); + if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) { + //Stash pointer in case of GC + String revertptr=generateTemp(fm, reverttable.get(lb),lb); + output.println("trans->revertlist="+revertptr+";"); + } + } else { + output.println(generateTemp(fm, fln.getDst(),lb)+"=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(),lb)+"=1;"); + else + output.println(generateTemp(fm, fln.getDst(),lb)+"=0;"); + } else if (fln.getType().isChar()) { + String st=FlatLiteralNode.escapeString(fln.getValue().toString()); + output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';"); + } else if (fln.getType().isLong()) { + output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;"); + } else + output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";"); + } + + protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) { + if (frn.getReturnTemp()!=null) { + if (frn.getReturnTemp().getType().isPtr()) + output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";"); + else + output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";"); + } else { + output.println("return;"); + } + } + + protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) { + output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";"); + } + + /** This method generates header information for the method or + * task referenced by the Descriptor des. */ + + private void generateHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) { + /* Print header */ + ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des); + MethodDescriptor md=null; + TaskDescriptor task=null; + if (des instanceof MethodDescriptor) + md=(MethodDescriptor) des; + else + task=(TaskDescriptor) des; + + ClassDescriptor cn=md!=null ? md.getClassDesc() : null; + + if (md!=null&&md.getReturnType()!=null) { + if (md.getReturnType().isClass()||md.getReturnType().isArray()) + output.print("struct " + md.getReturnType().getSafeSymbol()+" * "); + else + output.print(md.getReturnType().getSafeSymbol()+" "); + } else + //catch the constructor case + output.print("void "); + if (md!=null) { + if (state.DSM) { + output.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"("); + } else + output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"("); + } else + output.print(task.getSafeSymbol()+"("); + + boolean printcomma=false; + if (GENERATEPRECISEGC) { + if (md!=null) { + if (state.DSM) { + output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix); } else - output.println(generateTemp(fm, fon.getDest(),lb)+fon.getOp().toString()+generateTemp(fm, fon.getLeft(),lb)+";"); + output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix); + } else + output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix); + printcomma=true; } - private void generateFlatCastNode(FlatMethod fm, LocalityBinding lb, FlatCastNode fcn, PrintWriter output) { - /* TODO: Do type check here */ - if (fcn.getType().isArray()) { - throw new Error(); - } else if (fcn.getType().isClass()) - output.println(generateTemp(fm,fcn.getDst(),lb)+"=(struct "+fcn.getType().getSafeSymbol()+" *)"+generateTemp(fm,fcn.getSrc(),lb)+";"); + if (state.DSM&&lb.isAtomic()) { + if (printcomma) + output.print(", "); + output.print("transrecord_t * trans"); + printcomma=true; + } + + if (md!=null) { + /* Method */ + for(int i=0; i0) { - //Stash pointer in case of GC - String revertptr=generateTemp(fm, reverttable.get(lb),lb); - output.println(revertptr+"=trans->revertlist;"); - } - output.println(generateTemp(fm, fln.getDst(),lb)+"=NewString(&"+localsprefix+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");"); - if (state.DSM && locality.getAtomic(lb).get(fln).intValue()>0) { - //Stash pointer in case of GC - String revertptr=generateTemp(fm, reverttable.get(lb),lb); - output.println("trans->revertlist="+revertptr+";"); - } - } else { - output.println(generateTemp(fm, fln.getDst(),lb)+"=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(),lb)+"=1;"); - else - output.println(generateTemp(fm, fln.getDst(),lb)+"=0;"); - } else if (fln.getType().isChar()) { - String st=FlatLiteralNode.escapeString(fln.getValue().toString()); - output.println(generateTemp(fm, fln.getDst(),lb)+"='"+st+"';"); - } else if (fln.getType().isLong()) { - output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+"LL;"); - } else - output.println(generateTemp(fm, fln.getDst(),lb)+"="+fln.getValue()+";"); + output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol()); + } + output.println(") {"); + } else if (!GENERATEPRECISEGC) { + /* Imprecise Task */ + output.println("void * parameterarray[]) {"); + /* Unpack variables */ + for(int i=0; imaxtaskparams) + maxtaskparams=objectparams.numPrimitives()+fm.numTags(); + } else output.println(") {"); + } + + public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) { + output.println("/* FlatFlagActionNode */"); + + + /* Process tag changes */ + Relation tagsettable=new Relation(); + Relation tagcleartable=new Relation(); + + Iterator tagsit=ffan.getTempTagPairs(); + while (tagsit.hasNext()) { + TempTagPair ttp=(TempTagPair) tagsit.next(); + TempDescriptor objtmp=ttp.getTemp(); + TagDescriptor tag=ttp.getTag(); + TempDescriptor tagtmp=ttp.getTagTemp(); + boolean tagstatus=ffan.getTagChange(ttp); + if (tagstatus) { + tagsettable.put(objtmp, tagtmp); + } else { + tagcleartable.put(objtmp, tagtmp); + } } - protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) { - if (frn.getReturnTemp()!=null) { - if (frn.getReturnTemp().getType().isPtr()) - output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";"); - else - output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";"); + + Hashtable flagandtable=new Hashtable(); + Hashtable flagortable=new Hashtable(); + + /* Process flag changes */ + Iterator flagsit=ffan.getTempFlagPairs(); + while(flagsit.hasNext()) { + TempFlagPair tfp=(TempFlagPair)flagsit.next(); + TempDescriptor temp=tfp.getTemp(); + 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)); + } 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 { - output.println("return;"); - } + int mask=0xFFFFFFFF; + if (flagandtable.containsKey(temp)) { + mask=((Integer)flagandtable.get(temp)).intValue(); + } + mask&=(0xFFFFFFFF^flagid); + flagandtable.put(temp,new Integer(mask)); + } + } } - protected void generateFlatCondBranch(FlatMethod fm, LocalityBinding lb, FlatCondBranch fcb, String label, PrintWriter output) { - output.println("if (!"+generateTemp(fm, fcb.getTest(),lb)+") goto "+label+";"); + + HashSet flagtagset=new HashSet(); + flagtagset.addAll(flagortable.keySet()); + flagtagset.addAll(flagandtable.keySet()); + flagtagset.addAll(tagsettable.keySet()); + flagtagset.addAll(tagcleartable.keySet()); + + Iterator ftit=flagtagset.iterator(); + while(ftit.hasNext()) { + TempDescriptor temp=(TempDescriptor)ftit.next(); + + + Set tagtmps=tagcleartable.get(temp); + if (tagtmps!=null) { + Iterator tagit=tagtmps.iterator(); + while(tagit.hasNext()) { + TempDescriptor tagtmp=(TempDescriptor)tagit.next(); + if (GENERATEPRECISEGC) + output.println("tagclear(&"+localsprefix+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");"); + else + output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");"); + } + } + + tagtmps=tagsettable.get(temp); + if (tagtmps!=null) { + Iterator tagit=tagtmps.iterator(); + while(tagit.hasNext()) { + TempDescriptor tagtmp=(TempDescriptor)tagit.next(); + if (GENERATEPRECISEGC) + output.println("tagset(&"+localsprefix+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");"); + else + output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");"); + } + } + + int ormask=0; + int andmask=0xFFFFFFF; + + if (flagortable.containsKey(temp)) + ormask=((Integer)flagortable.get(temp)).intValue(); + if (flagandtable.containsKey(temp)) + andmask=((Integer)flagandtable.get(temp)).intValue(); + generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask); + generateObjectDistribute(ffan, fm, lb, temp, output); + } + } + + protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, + PrintWriter output, int ormask, int andmask) { + if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) { + output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");"); + } else { + output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");"); + } + } + + protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) { + output.println("enqueueObject("+generateTemp(fm, temp, lb)+");"); + } + + void generateOptionalHeader(PrintWriter headers) { + + //GENERATE HEADERS + headers.println("#include \"task.h\"\n\n"); + headers.println("#ifndef _OPTIONAL_STRUCT_"); + headers.println("#define _OPTIONAL_STRUCT_"); + + //STRUCT PREDICATEMEMBER + headers.println("struct predicatemember{"); + headers.println("int type;"); + headers.println("int numdnfterms;"); + headers.println("int * flags;"); + headers.println("int numtags;"); + headers.println("int * tags;\n};\n\n"); + + //STRUCT OPTIONALTASKDESCRIPTOR + headers.println("struct optionaltaskdescriptor{"); + headers.println("struct taskdescriptor * task;"); + headers.println("int index;"); + headers.println("int numenterflags;"); + headers.println("int * enterflags;"); + headers.println("int numpredicatemembers;"); + headers.println("struct predicatemember ** predicatememberarray;"); + headers.println("};\n\n"); + + //STRUCT TASKFAILURE + headers.println("struct taskfailure {"); + headers.println("struct taskdescriptor * task;"); + headers.println("int index;"); + headers.println("int numoptionaltaskdescriptors;"); + headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n"); + + //STRUCT FSANALYSISWRAPPER + headers.println("struct fsanalysiswrapper{"); + headers.println("int flags;"); + headers.println("int numtags;"); + headers.println("int * tags;"); + headers.println("int numtaskfailures;"); + headers.println("struct taskfailure ** taskfailurearray;"); + headers.println("int numoptionaltaskdescriptors;"); + headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n"); + + //STRUCT CLASSANALYSISWRAPPER + headers.println("struct classanalysiswrapper{"); + headers.println("int type;"); + headers.println("int numotd;"); + headers.println("struct optionaltaskdescriptor ** otdarray;"); + headers.println("int numfsanalysiswrappers;"); + headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};"); + + headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];"); + + Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator(); + while(taskit.hasNext()) { + TaskDescriptor td=(TaskDescriptor)taskit.next(); + headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";"); } - /** This method generates header information for the method or - * task referenced by the Descriptor des. */ + } + + //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE + int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) { + int predicateindex = 0; + //iterate through the classes concerned by the predicate + Set c_vard = predicate.vardescriptors; + Hashtable slotnumber=new Hashtable(); + int current_slot=0; + + for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();){ + VarDescriptor vard = (VarDescriptor)vard_it.next(); + TypeDescriptor typed = vard.getType(); + + //generate for flags + HashSet fen_hashset = predicate.flags.get(vard.getSymbol()); + 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>> safeexecution, Hashtable optionaltaskdescriptors) { + generateOptionalHeader(headers); + //GENERATE STRUCTS + output.println("#include \"optionalstruct.h\"\n\n"); + output.println("#include \"stdlib.h\"\n"); + + HashSet processedcd = new HashSet(); + int maxotd=0; + Enumeration e = safeexecution.keys(); + while (e.hasMoreElements()) { + int numotd=0; + //get the class + ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement(); + Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp); //will be used several times + + //Generate the struct of optionals + Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values(); + numotd = c_otd.size(); + if(maxotd 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; + // 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()); + } + } + output.println("};\n"); + + //get all the possible flagstates reachable by an object + Hashtable hashtbtemp = safeexecution.get(cdtemp); + int fscounter = 0; + 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()+","); } - if (md!=null) { - /* Method */ - for(int i=0;imaxtaskparams) - maxtaskparams=objectparams.numPrimitives()+fm.numTags(); - } else output.println(") {"); - } - - public void generateFlatFlagActionNode(FlatMethod fm, LocalityBinding lb, FlatFlagActionNode ffan, PrintWriter output) { - output.println("/* FlatFlagActionNode */"); - - - /* Process tag changes */ - Relation tagsettable=new Relation(); - Relation tagcleartable=new Relation(); - - Iterator tagsit=ffan.getTempTagPairs(); - while (tagsit.hasNext()) { - TempTagPair ttp=(TempTagPair) tagsit.next(); - TempDescriptor objtmp=ttp.getTemp(); - TagDescriptor tag=ttp.getTag(); - TempDescriptor tagtmp=ttp.getTagTemp(); - boolean tagstatus=ffan.getTagChange(ttp); - if (tagstatus) { - tagsettable.put(objtmp, tagtmp); - } else { - tagcleartable.put(objtmp, tagtmp); - } + //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 - Hashtable flagandtable=new Hashtable(); - Hashtable flagortable=new Hashtable(); - - /* Process flag changes */ - Iterator flagsit=ffan.getTempFlagPairs(); - while(flagsit.hasNext()) { - TempFlagPair tfp=(TempFlagPair)flagsit.next(); - TempDescriptor temp=tfp.getTemp(); - 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)); - } 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 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; - HashSet flagtagset=new HashSet(); - flagtagset.addAll(flagortable.keySet()); - flagtagset.addAll(flagandtable.keySet()); - flagtagset.addAll(tagsettable.keySet()); - flagtagset.addAll(tagcleartable.keySet()); - - Iterator ftit=flagtagset.iterator(); - while(ftit.hasNext()) { - TempDescriptor temp=(TempDescriptor)ftit.next(); - - - Set tagtmps=tagcleartable.get(temp); - if (tagtmps!=null) { - Iterator tagit=tagtmps.iterator(); - while(tagit.hasNext()) { - TempDescriptor tagtmp=(TempDescriptor)tagit.next(); - if (GENERATEPRECISEGC) - output.println("tagclear(&"+localsprefix+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");"); - else - output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");"); - } - } + Set otdset=sa.getOptions(fs, ti); - tagtmps=tagsettable.get(temp); - if (tagtmps!=null) { - Iterator tagit=tagtmps.iterator(); - while(tagit.hasNext()) { - TempDescriptor tagtmp=(TempDescriptor)tagit.next(); - if (GENERATEPRECISEGC) - output.println("tagset(&"+localsprefix+", (struct ___Object___ *)"+generateTemp(fm, temp,lb)+", "+generateTemp(fm,tagtmp,lb)+");"); - else - output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp, lb)+", "+generateTemp(fm,tagtmp, lb)+");"); - } - } + 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("};"); - int ormask=0; - int andmask=0xFFFFFFF; - - if (flagortable.containsKey(temp)) - ormask=((Integer)flagortable.get(temp)).intValue(); - if (flagandtable.containsKey(temp)) - andmask=((Integer)flagandtable.get(temp)).intValue(); - generateFlagOrAnd(ffan, fm, lb, temp, output, ormask, andmask); - generateObjectDistribute(ffan, fm, lb, temp, output); - } - } - - protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, - PrintWriter output, int ormask, int andmask) { - if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) { - output.println("flagorandinit("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");"); - } else { - output.println("flagorand("+generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");"); + 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("};"); } - } - protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, PrintWriter output) { - output.println("enqueueObject("+generateTemp(fm, temp, lb)+");"); - } - - void generateOptionalHeader(PrintWriter headers) { - - //GENERATE HEADERS - headers.println("#include \"task.h\"\n\n"); - headers.println("#ifndef _OPTIONAL_STRUCT_"); - headers.println("#define _OPTIONAL_STRUCT_"); - - //STRUCT PREDICATEMEMBER - headers.println("struct predicatemember{"); - headers.println("int type;"); - headers.println("int numdnfterms;"); - headers.println("int * flags;"); - headers.println("int numtags;"); - headers.println("int * tags;\n};\n\n"); - - //STRUCT OPTIONALTASKDESCRIPTOR - headers.println("struct optionaltaskdescriptor{"); - headers.println("struct taskdescriptor * task;"); - headers.println("int index;"); - headers.println("int numenterflags;"); - headers.println("int * enterflags;"); - headers.println("int numpredicatemembers;"); - headers.println("struct predicatemember ** predicatememberarray;"); - headers.println("};\n\n"); - - //STRUCT TASKFAILURE - headers.println("struct taskfailure {"); - headers.println("struct taskdescriptor * task;"); - headers.println("int index;"); - headers.println("int numoptionaltaskdescriptors;"); - headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n"); - - //STRUCT FSANALYSISWRAPPER - headers.println("struct fsanalysiswrapper{"); - headers.println("int flags;"); - headers.println("int numtags;"); - headers.println("int * tags;"); - headers.println("int numtaskfailures;"); - headers.println("struct taskfailure ** taskfailurearray;"); - headers.println("int numoptionaltaskdescriptors;"); - headers.println("struct optionaltaskdescriptor ** optionaltaskdescriptorarray;\n};\n\n"); - - //STRUCT CLASSANALYSISWRAPPER - headers.println("struct classanalysiswrapper{"); - headers.println("int type;"); - headers.println("int numotd;"); - headers.println("struct optionaltaskdescriptor ** otdarray;"); - headers.println("int numfsanalysiswrappers;"); - headers.println("struct fsanalysiswrapper ** fsanalysiswrapperarray;\n};"); - - headers.println("extern struct classanalysiswrapper * classanalysiswrapperarray[];"); - - Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator(); - while(taskit.hasNext()) { - TaskDescriptor td=(TaskDescriptor)taskit.next(); - headers.println("extern struct taskdescriptor task_"+td.getSafeSymbol()+";"); - } - - } - - //CHECK OVER THIS -- THERE COULD BE SOME ERRORS HERE - int generateOptionalPredicate(Predicate predicate, OptionalTaskDescriptor otd, ClassDescriptor cdtemp, PrintWriter output) { - int predicateindex = 0; - //iterate through the classes concerned by the predicate - Set c_vard = predicate.vardescriptors; - Hashtable slotnumber=new Hashtable(); - int current_slot=0; - - for(Iterator vard_it = c_vard.iterator(); vard_it.hasNext();){ - VarDescriptor vard = (VarDescriptor)vard_it.next(); - TypeDescriptor typed = vard.getType(); - - //generate for flags - HashSet fen_hashset = predicate.flags.get(vard.getSymbol()); - 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 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"); - return predicateindex; - } - - - void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable>> safeexecution, Hashtable optionaltaskdescriptors) { - generateOptionalHeader(headers); - //GENERATE STRUCTS - output.println("#include \"optionalstruct.h\"\n\n"); - output.println("#include \"stdlib.h\"\n"); - - HashSet processedcd = new HashSet(); - int maxotd=0; - Enumeration e = safeexecution.keys(); - while (e.hasMoreElements()) { - int numotd=0; - //get the class - ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement(); - Hashtable flaginfo=(Hashtable)flagorder.get(cdtemp);//will be used several times - - //Generate the struct of optionals - Collection c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values(); - numotd = c_otd.size(); - if(maxotd 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; - // 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()); - } - } - output.println("};\n"); - - //get all the possible flagstates reachable by an object - Hashtable hashtbtemp = safeexecution.get(cdtemp); - int fscounter = 0; - 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"); - - } - - //Build the array of fsanalysiswrappers - output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {"); - boolean needcomma=false; - for(int i = 0; i0) - output.print(", "); - if (processedcd.contains(cn)) - output.print("&classanalysiswrapper_"+cn.getSafeSymbol()); - else - output.print("NULL"); - } - output.println("};"); - - output.println("#define MAXOTD "+maxotd); - headers.println("#endif"); - } - - public List ordertd(Set otdset) { - Relation r=new Relation(); - for(Iteratorotdit=otdset.iterator();otdit.hasNext();) { - OptionalTaskDescriptor otd=otdit.next(); - TaskIndex ti=new TaskIndex(otd.td, otd.getIndex()); - r.put(ti, otd); - } - LinkedList l=new LinkedList(); - 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); - } - } - - return l; + //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"); + + } + + //Build the array of fsanalysiswrappers + output.println("struct fsanalysiswrapper * fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"[] = {"); + boolean needcomma=false; + for(int i = 0; i0) + output.print(", "); + if (processedcd.contains(cn)) + output.print("&classanalysiswrapper_"+cn.getSafeSymbol()); + else + output.print("NULL"); + } + output.println("};"); + + output.println("#define MAXOTD "+maxotd); + headers.println("#endif"); + } + + public List ordertd(Set otdset) { + Relation r=new Relation(); + for(Iteratorotdit=otdset.iterator(); otdit.hasNext();) { + OptionalTaskDescriptor otd=otdit.next(); + TaskIndex ti=new TaskIndex(otd.td, otd.getIndex()); + r.put(ti, otd); } - - protected void outputTransCode(PrintWriter output) { + + LinkedList l=new LinkedList(); + 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); + } } + + return l; + } + + protected void outputTransCode(PrintWriter output) { + } } - + diff --git a/Robust/src/IR/Flat/BuildCodeMultiCore.java b/Robust/src/IR/Flat/BuildCodeMultiCore.java index c737b5fc..634de6cd 100644 --- a/Robust/src/IR/Flat/BuildCodeMultiCore.java +++ b/Robust/src/IR/Flat/BuildCodeMultiCore.java @@ -30,1273 +30,1273 @@ import IR.Tree.FlagExpressionNode; import IR.Tree.TagExpressionList; public class BuildCodeMultiCore extends BuildCode { - private Vector scheduling; - int coreNum; - Schedule currentSchedule; - Hashtable[] fsate2qnames; - String objqarrayprefix= "objqueuearray4class"; - String objqueueprefix = "objqueue4parameter_"; - String paramqarrayprefix = "paramqueuearray4task"; - String coreqarrayprefix = "paramqueuearrays_core"; - String taskprefix = "task_"; - String taskarrayprefix = "taskarray_core"; - String otqueueprefix = "___otqueue"; - int startupcorenum; // record the core containing startup task, suppose only one core can hava startup object - - public BuildCodeMultiCore(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, Vector scheduling, int coreNum, PrefetchAnalysis pa) { - super(st, temptovar, typeutil, sa, pa); - this.scheduling = scheduling; - this.coreNum = coreNum; - this.currentSchedule = null; - this.fsate2qnames = null; - this.startupcorenum = 0; - - // sometimes there are extra cores then needed in scheduling - // TODO - // currently, it is guaranteed that in scheduling, the corenum - // is started from 0 and continuous. - // MAY need modification here in the future when take hardware - // information into account. - if(this.scheduling.size() < this.coreNum) { - this.coreNum = this.scheduling.size(); - } + private Vector scheduling; + int coreNum; + Schedule currentSchedule; + Hashtable[] fsate2qnames; + String objqarrayprefix= "objqueuearray4class"; + String objqueueprefix = "objqueue4parameter_"; + String paramqarrayprefix = "paramqueuearray4task"; + String coreqarrayprefix = "paramqueuearrays_core"; + String taskprefix = "task_"; + String taskarrayprefix = "taskarray_core"; + String otqueueprefix = "___otqueue"; + int startupcorenum; // record the core containing startup task, suppose only one core can hava startup object + + public BuildCodeMultiCore(State st, Hashtable temptovar, TypeUtil typeutil, SafetyAnalysis sa, Vector scheduling, int coreNum, PrefetchAnalysis pa) { + super(st, temptovar, typeutil, sa, pa); + this.scheduling = scheduling; + this.coreNum = coreNum; + this.currentSchedule = null; + this.fsate2qnames = null; + this.startupcorenum = 0; + + // sometimes there are extra cores then needed in scheduling + // TODO + // currently, it is guaranteed that in scheduling, the corenum + // is started from 0 and continuous. + // MAY need modification here in the future when take hardware + // information into account. + if(this.scheduling.size() < this.coreNum) { + this.coreNum = this.scheduling.size(); } - - public void buildCode() { - /* Create output streams to write to */ - PrintWriter outclassdefs=null; - PrintWriter outstructs=null; - PrintWriter outmethodheader=null; - PrintWriter outmethod=null; - PrintWriter outvirtual=null; - PrintWriter outtask=null; - PrintWriter outtaskdefs=null; - //PrintWriter outoptionalarrays=null; - //PrintWriter optionalheaders=null; - - try { - outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true); - outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true); - outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true); - outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true); - outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true); - if (state.TASK) { - outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true); - outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true); - /* optional - if (state.OPTIONAL){ - outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true); - optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true); - } */ - } - /*if (state.structfile!=null) { - outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true); - }*/ - } catch (Exception e) { - e.printStackTrace(); - System.exit(-1); - } - - /* Build the virtual dispatch tables */ - super.buildVirtualTables(outvirtual); - - /* Output includes */ - outmethodheader.println("#ifndef METHODHEADERS_H"); - outmethodheader.println("#define METHODHEADERS_H"); - outmethodheader.println("#include \"structdefs.h\""); - /*if (state.DSM) - outmethodheader.println("#include \"dstm.h\"");*/ - - /* Output Structures */ - super.outputStructs(outstructs); - - // Output the C class declarations - // These could mutually reference each other - super.outputClassDeclarations(outclassdefs); - - // Output function prototypes and structures for parameters - Iterator it=state.getClassSymbolTable().getDescriptorsIterator(); - int numclasses = 0; - while(it.hasNext()) { - ++numclasses; - ClassDescriptor cn=(ClassDescriptor)it.next(); - super.generateCallStructs(cn, outclassdefs, outstructs, outmethodheader); - } - outclassdefs.close(); - - if (state.TASK) { - /* Map flags to integers */ - /* The runtime keeps track of flags using these integers */ - it=state.getClassSymbolTable().getDescriptorsIterator(); - while(it.hasNext()) { - ClassDescriptor cn=(ClassDescriptor)it.next(); - super.mapFlags(cn); - } - /* Generate Tasks */ - generateTaskStructs(outstructs, outmethodheader); - - /* Outputs generic task structures if this is a task - program */ - outputTaskTypes(outtask); - } - - /* Build the actual methods */ - super.outputMethods(outmethod); - - if (state.TASK) { - Iterator[] taskits = new Iterator[this.coreNum]; - for(int i = 0; i < taskits.length; ++i) { - taskits[i] = null; - } - int[] numtasks = new int[this.coreNum]; - int[][] numqueues = new int[this.coreNum][numclasses]; - /* Output code for tasks */ - for(int i = 0; i < this.scheduling.size(); ++i) { - this.currentSchedule = this.scheduling.elementAt(i); - outputTaskCode(outtaskdefs, outmethod, outtask, taskits, numtasks, numqueues); - } - - // Output task descriptors - boolean comma = false; - outtaskdefs.println("struct parameterwrapper ** objectqueues[][NUMCLASSES] = {"); - boolean needcomma = false; - for(int i = 0; i < numqueues.length ; ++i) { - if(needcomma) { - outtaskdefs.println(","); - } else { - needcomma = true; - } - outtaskdefs.println("/* object queue array for core " + i + "*/"); - outtaskdefs.print("{"); - comma = false; - for(int j = 0; j < numclasses; ++j) { - if(comma) { - outtaskdefs.println(","); - } else { - comma = true; - } - outtaskdefs.print(this.objqarrayprefix + j + "_core" + i); - } - outtaskdefs.print("}"); - } - outtaskdefs.println("};"); - needcomma = false; - outtaskdefs.println("int numqueues[][NUMCLASSES] = {"); - for(int i = 0; i < numqueues.length; ++i) { - if(needcomma) { - outtaskdefs.println(","); - } else { - needcomma = true; - } - int[] tmparray = numqueues[i]; - comma = false; - outtaskdefs.print("{"); - for(int j = 0; j < tmparray.length; ++j) { - if(comma) { - outtaskdefs.print(","); - } else { - comma = true; - } - outtaskdefs.print(tmparray[j]); - } - outtaskdefs.print("}"); - } - outtaskdefs.println("};"); - - /* parameter queue arrays for all the tasks*/ - outtaskdefs.println("struct parameterwrapper *** paramqueues[] = {"); - needcomma = false; - for(int i = 0; i < this.coreNum ; ++i) { - if(needcomma) { - outtaskdefs.println(","); - } else { - needcomma = true; - } - outtaskdefs.println("/* parameter queue array for core " + i + "*/"); - outtaskdefs.print(this.coreqarrayprefix + i); - } - outtaskdefs.println("};"); - - for(int i = 0; i < taskits.length; ++i) { - outtaskdefs.println("struct taskdescriptor * " + this.taskarrayprefix + i + "[]={"); - Iterator taskit = taskits[i]; - if(taskit != null) { - boolean first=true; - while(taskit.hasNext()) { - TaskDescriptor td=(TaskDescriptor)taskit.next(); - if (first) - first=false; - else - outtaskdefs.println(","); - outtaskdefs.print("&" + this.taskprefix +td.getCoreSafeSymbol(i)); - } - } - outtaskdefs.println(); - outtaskdefs.println("};"); - } - outtaskdefs.println("struct taskdescriptor ** taskarray[]= {"); - comma = false; - for(int i = 0; i < taskits.length; ++i) { - if (comma) - outtaskdefs.println(","); - else - comma = true; - outtaskdefs.print(this.taskarrayprefix + i); - } - outtaskdefs.println("};"); - - outtaskdefs.print("int numtasks[]= {"); - comma = false; - for(int i = 0; i < taskits.length; ++i) { - if (comma) - outtaskdefs.print(","); - else - comma=true; - outtaskdefs.print(numtasks[i]); - } - outtaskdefs.println("};"); - outtaskdefs.println("int corenum=0;"); - - outtaskdefs.close(); - outtask.println("#endif"); - outtask.close(); - /* Record maximum number of task parameters */ - outstructs.println("#define MAXTASKPARAMS "+maxtaskparams); - /* Record maximum number of all types, i.e. length of classsize[] */ - outstructs.println("#define NUMTYPES "+(state.numClasses() + state.numArrays())); - /* Record number of cores */ - outstructs.println("#define NUMCORES "+this.coreNum); - /* Record number of core containing startup task */ - outstructs.println("#define STARTUPCORE "+this.startupcorenum); - //outstructs.println("#define STARTUPCORESTR \""+this.startupcorenum+"\""); - } //else if (state.main!=null) { - /* Generate main method */ - // outputMainMethod(outmethod); - //} - - /* Generate information for task with optional parameters */ - /*if (state.TASK&&state.OPTIONAL){ - generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors()); - outoptionalarrays.close(); - } */ - - /* Output structure definitions for repair tool */ - /*if (state.structfile!=null) { - buildRepairStructs(outrepairstructs); - outrepairstructs.close(); - }*/ - - /* Close files */ - outmethodheader.println("#endif"); - outmethodheader.close(); - outmethod.close(); - outstructs.println("#endif"); - outstructs.close(); + } + + public void buildCode() { + /* Create output streams to write to */ + PrintWriter outclassdefs=null; + PrintWriter outstructs=null; + PrintWriter outmethodheader=null; + PrintWriter outmethod=null; + PrintWriter outvirtual=null; + PrintWriter outtask=null; + PrintWriter outtaskdefs=null; + //PrintWriter outoptionalarrays=null; + //PrintWriter optionalheaders=null; + + try { + outstructs=new PrintWriter(new FileOutputStream(PREFIX+"structdefs.h"), true); + outmethodheader=new PrintWriter(new FileOutputStream(PREFIX+"methodheaders.h"), true); + outclassdefs=new PrintWriter(new FileOutputStream(PREFIX+"classdefs.h"), true); + outvirtual=new PrintWriter(new FileOutputStream(PREFIX+"virtualtable.h"), true); + outmethod=new PrintWriter(new FileOutputStream(PREFIX+"methods.c"), true); + if (state.TASK) { + outtask=new PrintWriter(new FileOutputStream(PREFIX+"task.h"), true); + outtaskdefs=new PrintWriter(new FileOutputStream(PREFIX+"taskdefs.c"), true); + /* optional + if (state.OPTIONAL){ + outoptionalarrays=new PrintWriter(new FileOutputStream(PREFIX+"optionalarrays.c"), true); + optionalheaders=new PrintWriter(new FileOutputStream(PREFIX+"optionalstruct.h"), true); + } */ + } + /*if (state.structfile!=null) { + outrepairstructs=new PrintWriter(new FileOutputStream(PREFIX+state.structfile+".struct"), true); + }*/ + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); } - /** This function outputs (1) structures that parameters are - * passed in (when PRECISE GC is enabled) and (2) function - * prototypes for the tasks */ - - private void generateTaskStructs(PrintWriter output, PrintWriter headersout) { - /* Cycle through tasks */ - for(int i = 0; i < this.scheduling.size(); ++i) { - Schedule tmpschedule = this.scheduling.elementAt(i); - int num = tmpschedule.getCoreNum(); - Iterator taskit = tmpschedule.getTasks().iterator(); - - while(taskit.hasNext()) { - /* Classify parameters */ - TaskDescriptor task=taskit.next(); - FlatMethod fm=state.getMethodFlat(task); - super.generateTempStructs(fm, null); - - ParamsObject objectparams=(ParamsObject) paramstable.get(task); - TempObject objecttemps=(TempObject) tempstable.get(task); - - /* Output parameter structure */ - if (GENERATEPRECISEGC) { - 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) { - output.println("struct "+task.getCoreSafeSymbol(num)+"_locals {"); - output.println(" int size;"); - output.println(" void * next;"); - for(int j=0;j taskit=this.currentSchedule.getTasks().iterator(); - while(taskit.hasNext()) { - TaskDescriptor td=taskit.next(); - FlatMethod fm=state.getMethodFlat(td); - generateTaskMethod(fm, null, outmethod); - generateTaskDescriptor(outtaskdefs, outtask, fm, td, qnames); + outtaskdefs.println("/* object queue array for core " + i + "*/"); + outtaskdefs.print("{"); + comma = false; + for(int j = 0; j < numclasses; ++j) { + if(comma) { + outtaskdefs.println(","); + } else { + comma = true; + } + outtaskdefs.print(this.objqarrayprefix + j + "_core" + i); } - - // generate queuearray for this core - int num = this.currentSchedule.getCoreNum(); - boolean comma = false; - for(int i = 0; i < qnames.length; ++i) { - outtaskdefs.println("/* object queue array for class " + i + " on core " + num + "*/"); - outtaskdefs.println("struct parameterwrapper * " + this.objqarrayprefix + i + "_core" + num + "[] = {"); - comma = false; - Vector tmpvector = qnames[i]; - if(tmpvector != null) { - for(int j = 0; j < tmpvector.size(); ++j) { - if(comma) { - outtaskdefs.println(","); - } else { - comma = true; - } - outtaskdefs.print("&" + tmpvector.elementAt(j)); - } - numqueues[num][i] = tmpvector.size(); - } else { - numqueues[num][i] = 0; - } - outtaskdefs.println("};"); + outtaskdefs.print("}"); + } + outtaskdefs.println("};"); + needcomma = false; + outtaskdefs.println("int numqueues[][NUMCLASSES] = {"); + for(int i = 0; i < numqueues.length; ++i) { + if(needcomma) { + outtaskdefs.println(","); + } else { + needcomma = true; } - - /* All the queues for tasks residing on this core*/ + int[] tmparray = numqueues[i]; comma = false; - outtaskdefs.println("/* object queue array for tasks on core " + num + "*/"); - outtaskdefs.println("struct parameterwrapper ** " + this.coreqarrayprefix + num + "[] = {"); - taskit=this.currentSchedule.getTasks().iterator(); - while(taskit.hasNext()) { - if (comma) { - outtaskdefs.println(","); - } else { - comma = true; - } - TaskDescriptor td=taskit.next(); - outtaskdefs.print(this.paramqarrayprefix + td.getCoreSafeSymbol(num)); + outtaskdefs.print("{"); + for(int j = 0; j < tmparray.length; ++j) { + if(comma) { + outtaskdefs.print(","); + } else { + comma = true; + } + outtaskdefs.print(tmparray[j]); } - outtaskdefs.println("};"); - - // record the iterator of tasks on this core - taskit=this.currentSchedule.getTasks().iterator(); - taskits[num] = taskit; - numtasks[num] = this.currentSchedule.getTasks().size(); - } - - /** Prints out definitions for generic task structures */ - private void outputTaskTypes(PrintWriter outtask) { - outtask.println("#ifndef _TASK_H"); - outtask.println("#define _TASK_H"); - outtask.println("#include \"ObjectHash.h\""); - outtask.println("#include \"structdefs.h\""); - outtask.println("#include \"Queue.h\""); - outtask.println("#include "); - outtask.println("#ifdef RAW"); - outtask.println("#include "); - outtask.println("#endif"); - outtask.println(); - outtask.println("struct tagobjectiterator {"); - outtask.println(" int istag; /* 0 if object iterator, 1 if tag iterator */"); - outtask.println(" struct ObjectIterator it; /* Object iterator */"); - outtask.println(" struct ObjectHash * objectset;"); - outtask.println("#ifdef OPTIONAL"); - outtask.println(" int failedstate;"); - outtask.println("#endif"); - outtask.println(" int slot;"); - outtask.println(" int tagobjindex; /* Index for tag or object depending on use */"); - outtask.println(" /*if tag we have an object binding */"); - outtask.println(" int tagid;"); - outtask.println(" int tagobjectslot;"); - outtask.println(" /*if object, we may have one or more tag bindings */"); - outtask.println(" int numtags;"); - outtask.println(" int tagbindings[MAXTASKPARAMS-1]; /* list slots */"); - outtask.println("};"); - outtask.println(); - outtask.println("struct parameterwrapper {"); - outtask.println(" //int type;"); - outtask.println(" struct ObjectHash * objectset;"); - outtask.println(" int numberofterms;"); - outtask.println(" int * intarray;"); - outtask.println(" int numbertags;"); - outtask.println(" int * tagarray;"); - outtask.println(" struct taskdescriptor * task;"); - outtask.println(" int slot;"); - outtask.println(" struct tagobjectiterator iterators[MAXTASKPARAMS-1];"); - outtask.println("};"); - outtask.println(); - outtask.println("extern struct parameterwrapper ** objectqueues[][NUMCLASSES];"); - outtask.println("extern int numqueues[][NUMCLASSES];"); - outtask.println(); - outtask.println("struct parameterdescriptor {"); - outtask.println(" int type;"); - outtask.println(" int numberterms;"); - outtask.println(" int *intarray;"); - outtask.println(" struct parameterwrapper * queue;"); - outtask.println(" int numbertags;"); - outtask.println(" int *tagarray;"); - outtask.println("};"); - outtask.println(); - outtask.println("struct taskdescriptor {"); - outtask.println(" void * taskptr;"); - outtask.println(" int numParameters;"); - outtask.println(" int numTotal;"); - outtask.println(" struct parameterdescriptor **descriptorarray;"); - outtask.println(" char * name;"); - outtask.println("};"); - outtask.println(); - outtask.println("extern struct taskdescriptor ** taskarray[];"); - outtask.println("extern int numtasks[];"); - outtask.println("extern int corenum;"); // define corenum to identify different core - outtask.println("extern struct parameterwrapper *** paramqueues[];"); - outtask.println(); - } - - private void generateObjectTransQueues(PrintWriter output) { - if(this.fsate2qnames == null) { - this.fsate2qnames = new Hashtable[this.coreNum]; - for(int i = 0; i < this.fsate2qnames.length; ++i) { - this.fsate2qnames[i] = null; - } + outtaskdefs.print("}"); + } + outtaskdefs.println("};"); + + /* parameter queue arrays for all the tasks*/ + outtaskdefs.println("struct parameterwrapper *** paramqueues[] = {"); + needcomma = false; + for(int i = 0; i < this.coreNum ; ++i) { + if(needcomma) { + outtaskdefs.println(","); + } else { + needcomma = true; } - int num = this.currentSchedule.getCoreNum(); - assert(this.fsate2qnames[num] == null); - Hashtable flag2qname = new Hashtable(); - this.fsate2qnames[num] = flag2qname; - Hashtable> targetCoreTbl = this.currentSchedule.getTargetCoreTable(); - if(targetCoreTbl != null) { - Object[] keys = targetCoreTbl.keySet().toArray(); - output.println(); - output.println("/* Object transfer queues for core" + num + ".*/"); - for(int i = 0; i < keys.length; ++i) { - 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 + "};"); - } + outtaskdefs.println("/* parameter queue array for core " + i + "*/"); + outtaskdefs.print(this.coreqarrayprefix + i); + } + outtaskdefs.println("};"); + + for(int i = 0; i < taskits.length; ++i) { + outtaskdefs.println("struct taskdescriptor * " + this.taskarrayprefix + i + "[]={"); + Iterator taskit = taskits[i]; + if(taskit != null) { + boolean first=true; + while(taskit.hasNext()) { + TaskDescriptor td=(TaskDescriptor)taskit.next(); + if (first) + first=false; + else + outtaskdefs.println(","); + outtaskdefs.print("&" + this.taskprefix +td.getCoreSafeSymbol(i)); + } } - output.println(); - } - - private void generateTaskMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) { - /*if (State.PRINTFLAT) - System.out.println(fm.printMethod());*/ - TaskDescriptor task=fm.getTask(); - assert(task != null); - int num = this.currentSchedule.getCoreNum(); - - //ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null?lb:task); - generateTaskHeader(fm, lb, task,output); - TempObject objecttemp=(TempObject) tempstable.get(lb!=null?lb:task); - /*if (state.DSM&&lb.getHasAtomic()) { - output.println("transrecord_t * trans;"); - }*/ - + outtaskdefs.println(); + outtaskdefs.println("};"); + } + outtaskdefs.println("struct taskdescriptor ** taskarray[]= {"); + comma = false; + for(int i = 0; i < taskits.length; ++i) { + if (comma) + outtaskdefs.println(","); + else + comma = true; + outtaskdefs.print(this.taskarrayprefix + i); + } + outtaskdefs.println("};"); + + outtaskdefs.print("int numtasks[]= {"); + comma = false; + for(int i = 0; i < taskits.length; ++i) { + if (comma) + outtaskdefs.print(","); + else + comma=true; + outtaskdefs.print(numtasks[i]); + } + outtaskdefs.println("};"); + outtaskdefs.println("int corenum=0;"); + + outtaskdefs.close(); + outtask.println("#endif"); + outtask.close(); + /* Record maximum number of task parameters */ + outstructs.println("#define MAXTASKPARAMS "+maxtaskparams); + /* Record maximum number of all types, i.e. length of classsize[] */ + outstructs.println("#define NUMTYPES "+(state.numClasses() + state.numArrays())); + /* Record number of cores */ + outstructs.println("#define NUMCORES "+this.coreNum); + /* Record number of core containing startup task */ + outstructs.println("#define STARTUPCORE "+this.startupcorenum); + //outstructs.println("#define STARTUPCORESTR \""+this.startupcorenum+"\""); + } //else if (state.main!=null) { + /* Generate main method */ + // outputMainMethod(outmethod); + //} + + /* Generate information for task with optional parameters */ + /*if (state.TASK&&state.OPTIONAL){ + generateOptionalArrays(outoptionalarrays, optionalheaders, state.getAnalysisResult(), state.getOptionalTaskDescriptors()); + outoptionalarrays.close(); + } */ + + /* Output structure definitions for repair tool */ + /*if (state.structfile!=null) { + buildRepairStructs(outrepairstructs); + outrepairstructs.close(); + }*/ + + /* Close files */ + outmethodheader.println("#endif"); + outmethodheader.close(); + outmethod.close(); + outstructs.println("#endif"); + outstructs.close(); + } + + /** This function outputs (1) structures that parameters are + * passed in (when PRECISE GC is enabled) and (2) function + * prototypes for the tasks */ + + private void generateTaskStructs(PrintWriter output, PrintWriter headersout) { + /* Cycle through tasks */ + for(int i = 0; i < this.scheduling.size(); ++i) { + Schedule tmpschedule = this.scheduling.elementAt(i); + int num = tmpschedule.getCoreNum(); + Iterator taskit = tmpschedule.getTasks().iterator(); + + while(taskit.hasNext()) { + /* Classify parameters */ + TaskDescriptor task=taskit.next(); + FlatMethod fm=state.getMethodFlat(task); + super.generateTempStructs(fm, null); + + ParamsObject objectparams=(ParamsObject) paramstable.get(task); + TempObject objecttemps=(TempObject) tempstable.get(task); + + /* Output parameter structure */ if (GENERATEPRECISEGC) { - output.print(" struct "+task.getCoreSafeSymbol(num)+"_locals "+localsprefix+"={"); - - output.print(objecttemp.numPointers()+","); - output.print(paramsprefix); - for(int j=0;jmaxtaskparams) { + maxtaskparams=objectparams.numPointers()+fm.numTags(); + } } - for(int i=0;iflag;"); + output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";"); + } + output.println("};\n"); } - /* Assign labels to FlatNode's if necessary.*/ + /* Output task declaration */ + headersout.print("void " + task.getCoreSafeSymbol(num)+"("); - Hashtable nodetolabel=super.assignLabels(fm); + if (GENERATEPRECISEGC) { + headersout.print("struct "+task.getCoreSafeSymbol(num)+"_params * "+paramsprefix); + } else + headersout.print("void * parameterarray[]"); + headersout.println(");\n"); + } + } - /* Check to see if we need to do a GC if this is a - * multi-threaded program...*/ + } - /*if ((state.THREAD||state.DSM)&&GENERATEPRECISEGC) { - if (state.DSM&&lb.isAtomic()) - output.println("checkcollect2(&"+localsprefix+",trans);"); - else - output.println("checkcollect(&"+localsprefix+");"); - }*/ - - /* Create queues to store objects need to be transferred to other cores and their destination*/ - output.println(" struct Queue * totransobjqueue = createQueue();"); - output.println(" struct transObjInfo * tmpObjInfo = NULL;"); - - /* generate print information for RAW version */ - output.println("#ifdef RAW"); - output.println("int tmpsum = 0;"); - output.println("char * taskname = \"" + task.getSymbol() + "\";"); - output.println("int tmplen = " + task.getSymbol().length() + ";"); - output.println("int tmpindex = 1;"); - output.println("for(;tmpindex < tmplen; tmpindex++) {"); - output.println(" tmpsum = tmpsum * 10 + *(taskname + tmpindex) - '0';"); - output.println("}"); - output.println("#ifdef RAWPATH"); - output.println("raw_test_pass(0xAAAA);"); - output.println("raw_test_pass_reg(tmpsum);"); - output.println("#endif"); - output.println("#ifdef RAWDEBUG"); - output.println("raw_test_pass(0xAAAA);"); - output.println("raw_test_pass_reg(tmpsum);"); - output.println("#endif"); - output.println("#endif"); - - for(int i = 0; i < fm.numParameters(); ++i) { - TempDescriptor temp = fm.getParameter(i); - output.println(" ++" + super.generateTemp(fm, temp, lb)+"->version;"); - } + /* This method outputs code for each task. */ - /* Do the actual code generation */ - FlatNode current_node=null; - HashSet tovisit=new HashSet(); - HashSet visited=new HashSet(); - tovisit.add(fm.getNext(0)); - while(current_node!=null||!tovisit.isEmpty()) { - if (current_node==null) { - current_node=(FlatNode)tovisit.iterator().next(); - tovisit.remove(current_node); - } - visited.add(current_node); - if (nodetolabel.containsKey(current_node)) - output.println("L"+nodetolabel.get(current_node)+":"); - /*if (state.INSTRUCTIONFAILURE) { - if (state.THREAD||state.DSM) { - output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}"); - } - else - output.println("if ((--instructioncount)==0) injectinstructionfailure();"); - }*/ - if (current_node.numNext()==0) { - output.print(" "); - super.generateFlatNode(fm, lb, current_node, output); - if (current_node.kind()!=FKind.FlatReturnNode) { - //output.println(" flushAll();"); - output.println("#ifdef RAW"); - output.println("raw_user_interrupts_off();"); - output.println("#ifdef RAWDEBUG"); - output.println("raw_test_pass(0xec00);"); - output.println("#endif"); - output.println("raw_flush_entire_cache();"); - output.println("#ifdef RAWDEBUG"); - output.println("raw_test_pass(0xecff);"); - output.println("#endif"); - output.println("raw_user_interrupts_on();"); - output.println("#endif"); - outputTransCode(output); - output.println(" return;"); - } - current_node=null; - } else if(current_node.numNext()==1) { - output.print(" "); - super.generateFlatNode(fm, lb, 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(" "); - super.generateFlatCondBranch(fm, lb, (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(); - } - - output.println("}\n\n"); - } + private void outputTaskCode(PrintWriter outtaskdefs, PrintWriter outmethod, PrintWriter outtask, Iterator[] taskits, int[] numtasks, + int[][] numqueues) { + /* Compile task based program */ + outtaskdefs.println("#include \"task.h\""); + outtaskdefs.println("#include \"methodheaders.h\""); - /** This method outputs TaskDescriptor information */ - private void generateTaskDescriptor(PrintWriter output, PrintWriter outtask, FlatMethod fm, TaskDescriptor task, Vector[] qnames) { - int num = this.currentSchedule.getCoreNum(); - - output.println("/* TaskDescriptor information for task " + task.getSymbol() + " on core " + num + "*/"); - - for (int i=0;i taskit=this.currentSchedule.getTasks().iterator(); + while(taskit.hasNext()) { + TaskDescriptor td=taskit.next(); + FlatMethod fm=state.getMethodFlat(td); + generateTaskMethod(fm, null, outmethod); + generateTaskDescriptor(outtaskdefs, outtask, fm, td, qnames); + } - // generate object queue for this parameter - String qname = this.objqueueprefix+i+"_"+task.getCoreSafeSymbol(num); - if(param_type.getClassDesc().getSymbol().equals("StartupObject")) { - this.startupcorenum = num; - } - if(qnames[param_type.getClassDesc().getId()] == null) { - qnames[param_type.getClassDesc().getId()] = new Vector(); - } - qnames[param_type.getClassDesc().getId()].addElement(qname); - outtask.println("extern struct parameterwrapper " + qname + ";"); - output.println("struct parameterwrapper " + qname + "={"); - output.println(".objectset = 0,"); // objectset - output.println("/* number of DNF terms */ .numberofterms = "+dnfterms+","); // numberofterms - output.println(".intarray = parameterdnf_"+i+"_"+task.getCoreSafeSymbol(num)+","); // intarray - // numbertags - if (param_tag!=null) - output.println("/* number of tags */ .numbertags = "+param_tag.numTags()+","); - else - output.println("/* number of tags */ .numbertags = 0,"); - output.println(".tagarray = parametertag_"+i+"_"+task.getCoreSafeSymbol(num)+","); // tagarray - output.println(".task = 0,"); // task - output.println(".slot = " + i + ",");// slot - // iterators - output.println("};"); - - output.println("struct parameterdescriptor parameter_"+i+"_"+task.getCoreSafeSymbol(num)+"={"); - output.println("/* type */"+param_type.getClassDesc().getId()+","); - output.println("/* number of DNF terms */"+dnfterms+","); - output.println("parameterdnf_"+i+"_"+task.getCoreSafeSymbol(num)+","); // intarray - output.println("&" + qname + ","); // queue - //BUG, added next line to fix and else statement...test - //with any task program - if (param_tag!=null) - output.println("/* number of tags */"+param_tag.numTags()+","); - else - output.println("/* number of tags */ 0,"); - output.println("parametertag_"+i+"_"+task.getCoreSafeSymbol(num)); // tagarray - output.println("};"); + // generate queuearray for this core + int num = this.currentSchedule.getCoreNum(); + boolean comma = false; + for(int i = 0; i < qnames.length; ++i) { + outtaskdefs.println("/* object queue array for class " + i + " on core " + num + "*/"); + outtaskdefs.println("struct parameterwrapper * " + this.objqarrayprefix + i + "_core" + num + "[] = {"); + comma = false; + Vector tmpvector = qnames[i]; + if(tmpvector != null) { + for(int j = 0; j < tmpvector.size(); ++j) { + if(comma) { + outtaskdefs.println(","); + } else { + comma = true; + } + outtaskdefs.print("&" + tmpvector.elementAt(j)); } - - /* parameter queues for this task*/ - output.println("struct parameterwrapper * " + this.paramqarrayprefix + task.getCoreSafeSymbol(num)+"[] = {"); - for (int i=0;i"); + outtask.println("#ifdef RAW"); + outtask.println("#include "); + outtask.println("#endif"); + outtask.println(); + outtask.println("struct tagobjectiterator {"); + outtask.println(" int istag; /* 0 if object iterator, 1 if tag iterator */"); + outtask.println(" struct ObjectIterator it; /* Object iterator */"); + outtask.println(" struct ObjectHash * objectset;"); + outtask.println("#ifdef OPTIONAL"); + outtask.println(" int failedstate;"); + outtask.println("#endif"); + outtask.println(" int slot;"); + outtask.println(" int tagobjindex; /* Index for tag or object depending on use */"); + outtask.println(" /*if tag we have an object binding */"); + outtask.println(" int tagid;"); + outtask.println(" int tagobjectslot;"); + outtask.println(" /*if object, we may have one or more tag bindings */"); + outtask.println(" int numtags;"); + outtask.println(" int tagbindings[MAXTASKPARAMS-1]; /* list slots */"); + outtask.println("};"); + outtask.println(); + outtask.println("struct parameterwrapper {"); + outtask.println(" //int type;"); + outtask.println(" struct ObjectHash * objectset;"); + outtask.println(" int numberofterms;"); + outtask.println(" int * intarray;"); + outtask.println(" int numbertags;"); + outtask.println(" int * tagarray;"); + outtask.println(" struct taskdescriptor * task;"); + outtask.println(" int slot;"); + outtask.println(" struct tagobjectiterator iterators[MAXTASKPARAMS-1];"); + outtask.println("};"); + outtask.println(); + outtask.println("extern struct parameterwrapper ** objectqueues[][NUMCLASSES];"); + outtask.println("extern int numqueues[][NUMCLASSES];"); + outtask.println(); + outtask.println("struct parameterdescriptor {"); + outtask.println(" int type;"); + outtask.println(" int numberterms;"); + outtask.println(" int *intarray;"); + outtask.println(" struct parameterwrapper * queue;"); + outtask.println(" int numbertags;"); + outtask.println(" int *tagarray;"); + outtask.println("};"); + outtask.println(); + outtask.println("struct taskdescriptor {"); + outtask.println(" void * taskptr;"); + outtask.println(" int numParameters;"); + outtask.println(" int numTotal;"); + outtask.println(" struct parameterdescriptor **descriptorarray;"); + outtask.println(" char * name;"); + outtask.println("};"); + outtask.println(); + outtask.println("extern struct taskdescriptor ** taskarray[];"); + outtask.println("extern int numtasks[];"); + outtask.println("extern int corenum;"); // define corenum to identify different core + outtask.println("extern struct parameterwrapper *** paramqueues[];"); + outtask.println(); + } + + private void generateObjectTransQueues(PrintWriter output) { + if(this.fsate2qnames == null) { + this.fsate2qnames = new Hashtable[this.coreNum]; + for(int i = 0; i < this.fsate2qnames.length; ++i) { + this.fsate2qnames[i] = null; + } + } + int num = this.currentSchedule.getCoreNum(); + assert(this.fsate2qnames[num] == null); + Hashtable flag2qname = new Hashtable(); + this.fsate2qnames[num] = flag2qname; + Hashtable> targetCoreTbl = this.currentSchedule.getTargetCoreTable(); + if(targetCoreTbl != null) { + Object[] keys = targetCoreTbl.keySet().toArray(); + output.println(); + output.println("/* Object transfer queues for core" + num + ".*/"); + for(int i = 0; i < keys.length; ++i) { + 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(); + } + + private void generateTaskMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) { + /*if (State.PRINTFLAT) + System.out.println(fm.printMethod());*/ + TaskDescriptor task=fm.getTask(); + assert(task != null); + int num = this.currentSchedule.getCoreNum(); + + //ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null?lb:task); + generateTaskHeader(fm, lb, task,output); + TempObject objecttemp=(TempObject) tempstable.get(lb!=null ? lb : task); + /*if (state.DSM&&lb.getHasAtomic()) { + output.println("transrecord_t * trans;"); + }*/ + + if (GENERATEPRECISEGC) { + output.print(" struct "+task.getCoreSafeSymbol(num)+"_locals "+localsprefix+"={"); + + output.print(objecttemp.numPointers()+","); + output.print(paramsprefix); + for(int j=0; jflag;"); + } - private void generateTaskHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) { - /* Print header */ - ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null?lb:des); - TaskDescriptor task=(TaskDescriptor) des; + /* Assign labels to FlatNode's if necessary.*/ + + Hashtable nodetolabel=super.assignLabels(fm); + + /* Check to see if we need to do a GC if this is a + * multi-threaded program...*/ + + /*if ((state.THREAD||state.DSM)&&GENERATEPRECISEGC) { + if (state.DSM&&lb.isAtomic()) + output.println("checkcollect2(&"+localsprefix+",trans);"); + else + output.println("checkcollect(&"+localsprefix+");"); + }*/ + + /* Create queues to store objects need to be transferred to other cores and their destination*/ + output.println(" struct Queue * totransobjqueue = createQueue();"); + output.println(" struct transObjInfo * tmpObjInfo = NULL;"); + + /* generate print information for RAW version */ + output.println("#ifdef RAW"); + output.println("int tmpsum = 0;"); + output.println("char * taskname = \"" + task.getSymbol() + "\";"); + output.println("int tmplen = " + task.getSymbol().length() + ";"); + output.println("int tmpindex = 1;"); + output.println("for(;tmpindex < tmplen; tmpindex++) {"); + output.println(" tmpsum = tmpsum * 10 + *(taskname + tmpindex) - '0';"); + output.println("}"); + output.println("#ifdef RAWPATH"); + output.println("raw_test_pass(0xAAAA);"); + output.println("raw_test_pass_reg(tmpsum);"); + output.println("#endif"); + output.println("#ifdef RAWDEBUG"); + output.println("raw_test_pass(0xAAAA);"); + output.println("raw_test_pass_reg(tmpsum);"); + output.println("#endif"); + output.println("#endif"); + + for(int i = 0; i < fm.numParameters(); ++i) { + TempDescriptor temp = fm.getParameter(i); + output.println(" ++" + super.generateTemp(fm, temp, lb)+"->version;"); + } - int num = this.currentSchedule.getCoreNum(); - //catch the constructor case - output.print("void "); - output.print(task.getCoreSafeSymbol(num)+"("); + /* Do the actual code generation */ + FlatNode current_node=null; + HashSet tovisit=new HashSet(); + HashSet visited=new HashSet(); + tovisit.add(fm.getNext(0)); + while(current_node!=null||!tovisit.isEmpty()) { + if (current_node==null) { + current_node=(FlatNode)tovisit.iterator().next(); + tovisit.remove(current_node); + } + visited.add(current_node); + if (nodetolabel.containsKey(current_node)) + output.println("L"+nodetolabel.get(current_node)+":"); + /*if (state.INSTRUCTIONFAILURE) { + if (state.THREAD||state.DSM) { + output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}"); + } + else + output.println("if ((--instructioncount)==0) injectinstructionfailure();"); + }*/ + if (current_node.numNext()==0) { + output.print(" "); + super.generateFlatNode(fm, lb, current_node, output); + if (current_node.kind()!=FKind.FlatReturnNode) { + //output.println(" flushAll();"); + output.println("#ifdef RAW"); + output.println("raw_user_interrupts_off();"); + output.println("#ifdef RAWDEBUG"); + output.println("raw_test_pass(0xec00);"); + output.println("#endif"); + output.println("raw_flush_entire_cache();"); + output.println("#ifdef RAWDEBUG"); + output.println("raw_test_pass(0xecff);"); + output.println("#endif"); + output.println("raw_user_interrupts_on();"); + output.println("#endif"); + outputTransCode(output); + output.println(" return;"); + } + current_node=null; + } else if(current_node.numNext()==1) { + output.print(" "); + super.generateFlatNode(fm, lb, 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(" "); + super.generateFlatCondBranch(fm, lb, (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(); + } - boolean printcomma=false; - if (GENERATEPRECISEGC) { - output.print("struct "+task.getCoreSafeSymbol(num)+"_params * "+paramsprefix); - printcomma=true; + output.println("}\n\n"); + } + + /** This method outputs TaskDescriptor information */ + private void generateTaskDescriptor(PrintWriter output, PrintWriter outtask, FlatMethod fm, TaskDescriptor task, Vector[] qnames) { + int num = this.currentSchedule.getCoreNum(); + + output.println("/* TaskDescriptor information for task " + task.getSymbol() + " on core " + num + "*/"); + + for (int i=0; imaxtaskparams) - maxtaskparams=objectparams.numPrimitives()+fm.numTags(); - } else output.println(") {"); + output.println("struct parameterdescriptor * parameterdescriptors_"+task.getCoreSafeSymbol(num)+"[] = {"); + for (int i=0; i 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("+super.generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+ - ", 0x"+Integer.toHexString(andmask)+", " + qinfo.qname + - ", " + qinfo.length + ");"); - output.println("}"); - } + output.println("};"); + + output.println("struct taskdescriptor " + this.taskprefix + task.getCoreSafeSymbol(num) + "={"); + output.println("&"+task.getCoreSafeSymbol(num)+","); + output.println("/* number of parameters */" +task.numParameters() + ","); + int numtotal=task.numParameters()+fm.numTags(); + output.println("/* number total parameters */" +numtotal + ","); + output.println("parameterdescriptors_"+task.getCoreSafeSymbol(num)+","); + output.println("\""+task.getSymbol()+"\""); + output.println("};"); + + output.println(); + } + + /** This method generates header information for the task + * referenced by the Descriptor des. */ + + private void generateTaskHeader(FlatMethod fm, LocalityBinding lb, Descriptor des, PrintWriter output) { + /* Print header */ + ParamsObject objectparams=(ParamsObject)paramstable.get(lb!=null ? lb : des); + TaskDescriptor task=(TaskDescriptor) des; + + int num = this.currentSchedule.getCoreNum(); + //catch the constructor case + output.print("void "); + output.print(task.getCoreSafeSymbol(num)+"("); + + boolean printcomma=false; + if (GENERATEPRECISEGC) { + output.print("struct "+task.getCoreSafeSymbol(num)+"_params * "+paramsprefix); + printcomma=true; + } + + /*if (state.DSM&&lb.isAtomic()) { + if (printcomma) + output.print(", "); + output.print("transrecord_t * trans"); + printcomma=true; + }*/ + + if (!GENERATEPRECISEGC) { + /* Imprecise Task */ + output.println("void * parameterarray[]) {"); + /* Unpack variables */ + for(int i=0; imaxtaskparams) + maxtaskparams=objectparams.numPrimitives()+fm.numTags(); + } else output.println(") {"); + } + + protected void generateFlagOrAnd(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, + PrintWriter output, int ormask, int andmask) { + if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) { + output.println("flagorandinit("+super.generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+", 0x"+Integer.toHexString(andmask)+");"); + } else { + int num = this.currentSchedule.getCoreNum(); + 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("+super.generateTemp(fm, temp, lb)+", 0x"+Integer.toHexString(ormask)+ + ", 0x"+Integer.toHexString(andmask)+", " + qinfo.qname + + ", " + qinfo.length + ");"); + output.println("}"); + } + } + } + + protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, + PrintWriter output) { + ClassDescriptor cd = temp.getType().getClassDesc(); + Vector initfstates = null; + Vector[] targetFStates = null; + if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) { + targetFStates = new Vector[1]; + targetFStates[0] = ffan.getTargetFStates4NewObj(cd); + } else { + 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); + } + } + } + boolean isolate = true; // check if this flagstate can associate to some task with multiple params which can + // reside on multiple cores + 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, lb) + "&(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("+super.generateTemp(fm, temp, lb)+", NULL, 0);"); } + if(initfstates != null) { + output.println("}"); + } + } + return; } - protected void generateObjectDistribute(FlatFlagActionNode ffan, FlatMethod fm, LocalityBinding lb, TempDescriptor temp, - PrintWriter output) { - ClassDescriptor cd = temp.getType().getClassDesc(); - Vector initfstates = null; - Vector[] targetFStates = null; - if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) { - targetFStates = new Vector[1]; - targetFStates[0] = ffan.getTargetFStates4NewObj(cd); + int num = this.currentSchedule.getCoreNum(); + Hashtable> targetCoreTbl = this.currentSchedule.getTargetCoreTable(); + for(int j = 0; j < targetFStates.length; ++j) { + FlagState fs = null; + if(initfstates != null) { + fs = initfstates.elementAt(j); + output.println("if((" + generateTempFlagName(fm, temp, lb) + "&(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 { - 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); - } - } + isolate = (this.currentSchedule.getAllyCoreTable().get(tmpFState) == null) || + (this.currentSchedule.getAllyCoreTable().get(tmpFState).size() == 0); } - boolean isolate = true; // check if this flagstate can associate to some task with multiple params which can - // reside on multiple cores - 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, lb) + "&(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("+super.generateTemp(fm, temp, lb)+", NULL, 0);"); - } - if(initfstates != null) { - output.println("}"); - } - } - return; + if(!isolate) { + // indentify this object as a shared object + // isolate flag is initially set as 1, once this flag is set as 0, it is never reset to 1, i.e. once an object + // is shared, it maybe shared all the time afterwards + output.println("if(" + super.generateTemp(fm, temp, lb) + "->isolate == 1) {"); + output.println(" " + super.generateTemp(fm, temp, lb) + "->isolate = 0;"); + output.println(" " + super.generateTemp(fm, temp, lb) + "->original = (struct ___Object___ *)" + super.generateTemp(fm, temp, lb) + ";"); + output.println("}"); } - - int num = this.currentSchedule.getCoreNum(); - Hashtable> targetCoreTbl = this.currentSchedule.getTargetCoreTable(); - for(int j = 0; j < targetFStates.length; ++j) { - FlagState fs = null; - if(initfstates != null) { - fs = initfstates.elementAt(j); - output.println("if((" + generateTempFlagName(fm, temp, lb) + "&(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; + + 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("+super.generateTemp(fm, temp, lb)+", " + qinfo.qname + + ", " + qinfo.length + ");"); + output.println("}"); } else { - isolate = (this.currentSchedule.getAllyCoreTable().get(tmpFState) == null) || - (this.currentSchedule.getAllyCoreTable().get(tmpFState).size() == 0); + // TODO + // really needed? + output.println("/* possibly needed by multi-parameter tasks on this core*/"); + output.println("enqueueObject("+super.generateTemp(fm, temp, lb)+", NULL, 0);"); } + } else { if(!isolate) { - // indentify this object as a shared object - // isolate flag is initially set as 1, once this flag is set as 0, it is never reset to 1, i.e. once an object - // is shared, it maybe shared all the time afterwards - output.println("if(" + super.generateTemp(fm, temp, lb) + "->isolate == 1) {"); - output.println(" " + super.generateTemp(fm, temp, lb) + "->isolate = 0;"); - output.println(" " + super.generateTemp(fm, temp, lb) + "->original = (struct ___Object___ *)" + super.generateTemp(fm, temp, lb) + ";"); - output.println("}"); + // TODO + // Is it possible to decide the actual queues? + output.println("/* possibly needed by multi-parameter tasks on this core*/"); + output.println("enqueueObject("+super.generateTemp(fm, temp, lb)+", NULL, 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("+super.generateTemp(fm, temp, lb)+", " + qinfo.qname + - ", " + qinfo.length + ");"); - output.println("}"); - } else { - // TODO - // really needed? - output.println("/* possibly needed by multi-parameter tasks on this core*/"); - output.println("enqueueObject("+super.generateTemp(fm, temp, lb)+", NULL, 0);"); - } - } 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("+super.generateTemp(fm, temp, lb)+", NULL, 0);"); - } - 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 = super.generateTemp(fm, temp, lb); - tmpinfo.targetcore = targetcore; - FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState); - if(targetFS != null) { - tmpinfo.fs = targetFS; - } else { - tmpinfo.fs = tmpFState; - } - if(!contains(sendto, tmpinfo)){ - 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);"); - sendto.add(tmpinfo); - } - 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("+super.generateTemp(fm, temp, lb)+", NULL, 0);"); - } - 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 = super.generateTemp(fm, temp, lb); - tmpinfo.targetcore = targetcore; - FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState); - if(targetFS != null) { - tmpinfo.fs = targetFS; - } else { - tmpinfo.fs = tmpFState; - } - if(!contains(sendto, tmpinfo)){ - 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);"); - sendto.add(tmpinfo); - } - output.println("}"); - } - output.println("/* increase index*/"); - output.println("++" + queueins + ".index;"); + 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 = super.generateTemp(fm, temp, lb); + tmpinfo.targetcore = targetcore; + FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState); + if(targetFS != null) { + tmpinfo.fs = targetFS; } 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("+super.generateTemp(fm, temp, lb)+", " + qinfo.qname + - ", " + qinfo.length + ");"); - output.println("}"); - } else { - // TODO - // really needed? - output.println("enqueueObject("+super.generateTemp(fm, temp, lb)+", NULL, 0);"); - } + tmpinfo.fs = tmpFState; } - - // 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*/"); - for(int k = 0; k < targetcores.size(); ++k) { - // TODO - // add the information of exactly which queue - //if(!sendto.contains(targetcores.elementAt(i))) { - // 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 = super.generateTemp(fm, temp, lb); - tmpinfo.targetcore = targetcores.elementAt(i); - FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState); - if(targetFS != null) { - tmpinfo.fs = targetFS; - } else { - tmpinfo.fs = tmpFState; - } - if(!contains(sendto, tmpinfo)){ - qinfo = outputtransqueues(tmpinfo.fs, targetcores.elementAt(i), output); - output.println("tmpObjInfo = RUNMALLOC(sizeof(struct transObjInfo));"); - output.println("tmpObjInfo->objptr = (void *)" + tmpinfo.name + ";"); - output.println("tmpObjInfo->targetcore = "+targetcores.elementAt(i).toString()+";"); - output.println("tmpObjInfo->queues = " + qinfo.qname + ";"); - output.println("tmpObjInfo->length = " + qinfo.length + ";"); - output.println("addNewItem(totransobjqueue, (void*)tmpObjInfo);"); - sendto.add(tmpinfo); - } - output.println("}"); - //} - } + if(!contains(sendto, tmpinfo)){ + 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);"); + sendto.add(tmpinfo); } - } - - if(initfstates != null) { output.println("}"); + } + output.println("break;"); } - } - } - - private QueueInfo outputqueues(FlagState tmpFState, int num, PrintWriter output, boolean isEnqueue) { - // queue array - QueueInfo qinfo = new QueueInfo(); - qinfo.qname = "queues_" + tmpFState.getLabel() + "_" + tmpFState.getiuid(); - output.println("struct parameterwrapper * " + qinfo.qname + "[] = {"); - Iterator it_edges = tmpFState.getEdgeVector().iterator(); - Vector residetasks = this.currentSchedule.getTasks(); - Vector tasks = new Vector(); - Vector indexes = new Vector(); - boolean comma = false; - qinfo.length = 0; - while(it_edges.hasNext()) { - FEdge fe = (FEdge)it_edges.next(); - 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; - } + 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("+super.generateTemp(fm, temp, lb)+", NULL, 0);"); + } + 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 = super.generateTemp(fm, temp, lb); + tmpinfo.targetcore = targetcore; + FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState); + if(targetFS != null) { + tmpinfo.fs = targetFS; + } else { + tmpinfo.fs = tmpFState; } + if(!contains(sendto, tmpinfo)){ + 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);"); + sendto.add(tmpinfo); + } + 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("+super.generateTemp(fm, temp, lb)+", " + qinfo.qname + + ", " + qinfo.length + ");"); + output.println("}"); + } else { + // TODO + // really needed? + output.println("enqueueObject("+super.generateTemp(fm, temp, lb)+", NULL, 0);"); + } } - output.println("};"); - return qinfo; - } - - private QueueInfo outputtransqueues(FlagState tmpFState, int targetcore, PrintWriter output) { - // queue array - QueueInfo qinfo = new QueueInfo(); - qinfo.qname = "queues_" + tmpFState.getLabel() + "_" + tmpFState.getiuid(); - output.println("int " + qinfo.qname + "_clone[] = {"); - Iterator it_edges = tmpFState.getEdgeVector().iterator(); - Vector residetasks = this.scheduling.get(targetcore).getTasks(); - Vector tasks = new Vector(); - Vector indexes = new Vector(); - boolean comma = false; - qinfo.length = 0; - while(it_edges.hasNext()) { - FEdge fe = (FEdge)it_edges.next(); - 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; - } + + // 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*/"); + for(int k = 0; k < targetcores.size(); ++k) { + // TODO + // add the information of exactly which queue + //if(!sendto.contains(targetcores.elementAt(i))) { + // 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 = super.generateTemp(fm, temp, lb); + tmpinfo.targetcore = targetcores.elementAt(i); + FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState); + if(targetFS != null) { + tmpinfo.fs = targetFS; + } else { + tmpinfo.fs = tmpFState; + } + if(!contains(sendto, tmpinfo)){ + qinfo = outputtransqueues(tmpinfo.fs, targetcores.elementAt(i), output); + output.println("tmpObjInfo = RUNMALLOC(sizeof(struct transObjInfo));"); + output.println("tmpObjInfo->objptr = (void *)" + tmpinfo.name + ";"); + output.println("tmpObjInfo->targetcore = "+targetcores.elementAt(i).toString()+";"); + output.println("tmpObjInfo->queues = " + qinfo.qname + ";"); + output.println("tmpObjInfo->length = " + qinfo.length + ";"); + output.println("addNewItem(totransobjqueue, (void*)tmpObjInfo);"); + sendto.add(tmpinfo); } + output.println("}"); + //} + } } - output.println("};"); - output.println("int * " + qinfo.qname + " = RUNMALLOC(sizeof(int) * " + qinfo.length * 2 + ");"); - output.println("memcpy(" + qinfo.qname + ", (int *)" + qinfo.qname + "_clone, sizeof(int) * " + qinfo.length * 2 + ");"); - return qinfo; - } - - private class QueueInfo { - public int length; - public String qname; + } + + if(initfstates != null) { + output.println("}"); + } } - - private String generateTempFlagName(FlatMethod fm, TempDescriptor td, LocalityBinding lb) { - MethodDescriptor md=fm.getMethod(); - TaskDescriptor task=fm.getTask(); - TempObject objecttemps=(TempObject) tempstable.get(lb!=null?lb:md!=null?md:task); - - if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) { - return td.getSafeSymbol() + "_oldflag"; + } + + private QueueInfo outputqueues(FlagState tmpFState, int num, PrintWriter output, boolean isEnqueue) { + // queue array + QueueInfo qinfo = new QueueInfo(); + qinfo.qname = "queues_" + tmpFState.getLabel() + "_" + tmpFState.getiuid(); + output.println("struct parameterwrapper * " + qinfo.qname + "[] = {"); + Iterator it_edges = tmpFState.getEdgeVector().iterator(); + Vector residetasks = this.currentSchedule.getTasks(); + Vector tasks = new Vector(); + Vector indexes = new Vector(); + boolean comma = false; + qinfo.length = 0; + while(it_edges.hasNext()) { + FEdge fe = (FEdge)it_edges.next(); + 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 (objecttemps.isLocalPtr(td)) { - return localsprefix+"_"+td.getSafeSymbol() + "_oldflag"; + } + } + output.println("};"); + return qinfo; + } + + private QueueInfo outputtransqueues(FlagState tmpFState, int targetcore, PrintWriter output) { + // queue array + QueueInfo qinfo = new QueueInfo(); + qinfo.qname = "queues_" + tmpFState.getLabel() + "_" + tmpFState.getiuid(); + output.println("int " + qinfo.qname + "_clone[] = {"); + Iterator it_edges = tmpFState.getEdgeVector().iterator(); + Vector residetasks = this.scheduling.get(targetcore).getTasks(); + Vector tasks = new Vector(); + Vector indexes = new Vector(); + boolean comma = false; + qinfo.length = 0; + while(it_edges.hasNext()) { + FEdge fe = (FEdge)it_edges.next(); + 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; } + } + } + output.println("};"); + output.println("int * " + qinfo.qname + " = RUNMALLOC(sizeof(int) * " + qinfo.length * 2 + ");"); + output.println("memcpy(" + qinfo.qname + ", (int *)" + qinfo.qname + "_clone, sizeof(int) * " + qinfo.length * 2 + ");"); + return qinfo; + } + + private class QueueInfo { + public int length; + public String qname; + } + + private String generateTempFlagName(FlatMethod fm, TempDescriptor td, LocalityBinding lb) { + MethodDescriptor md=fm.getMethod(); + TaskDescriptor task=fm.getTask(); + TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md!=null ? md : task); + + if (objecttemps.isLocalPrim(td)||objecttemps.isParamPrim(td)) { + return td.getSafeSymbol() + "_oldflag"; + } - if (objecttemps.isParamPtr(td)) { - return paramsprefix+"_"+td.getSafeSymbol() + "_oldflag"; - } - throw new Error(); + if (objecttemps.isLocalPtr(td)) { + return localsprefix+"_"+td.getSafeSymbol() + "_oldflag"; } - - protected void outputTransCode(PrintWriter output) { - output.println("while(0 == isEmpty(totransobjqueue)) {"); - output.println(" struct QueueItem * totransitem = getTail(totransobjqueue);"); - - output.println(" transferObject((struct transObjInfo *)totransitem->objectptr);"); - output.println(" RUNFREE(((struct transObjInfo *)totransitem->objectptr)->queues);"); - output.println(" RUNFREE(totransitem->objectptr);"); - output.println(" removeItem(totransobjqueue, totransitem);"); - output.println("}"); - output.println("freeQueue(totransobjqueue);"); + + if (objecttemps.isParamPtr(td)) { + return paramsprefix+"_"+td.getSafeSymbol() + "_oldflag"; } - - protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) { - if (frn.getReturnTemp()!=null) { - if (frn.getReturnTemp().getType().isPtr()) - output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";"); - else - output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";"); - } else { - if(fm.getTask() != null) { - //output.println("flushAll();"); - output.println("#ifdef RAW"); - output.println("raw_user_interrupts_off();"); - output.println("#ifdef RAWDEBUG"); - output.println("raw_test_pass(0xec00);"); - output.println("#endif"); - output.println("raw_flush_entire_cache();"); - output.println("#ifdef RAWDEBUG"); - output.println("raw_test_pass(0xecff);"); - output.println("#endif"); - output.println("raw_user_interrupts_on();"); - output.println("#endif"); - outputTransCode(output); - } - output.println("return;"); - } + throw new Error(); + } + + protected void outputTransCode(PrintWriter output) { + output.println("while(0 == isEmpty(totransobjqueue)) {"); + output.println(" struct QueueItem * totransitem = getTail(totransobjqueue);"); + + output.println(" transferObject((struct transObjInfo *)totransitem->objectptr);"); + output.println(" RUNFREE(((struct transObjInfo *)totransitem->objectptr)->queues);"); + output.println(" RUNFREE(totransitem->objectptr);"); + output.println(" removeItem(totransobjqueue, totransitem);"); + output.println("}"); + output.println("freeQueue(totransobjqueue);"); + } + + protected void generateFlatReturnNode(FlatMethod fm, LocalityBinding lb, FlatReturnNode frn, PrintWriter output) { + if (frn.getReturnTemp()!=null) { + if (frn.getReturnTemp().getType().isPtr()) + output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp(), lb)+";"); + else + output.println("return "+generateTemp(fm, frn.getReturnTemp(), lb)+";"); + } else { + if(fm.getTask() != null) { + //output.println("flushAll();"); + output.println("#ifdef RAW"); + output.println("raw_user_interrupts_off();"); + output.println("#ifdef RAWDEBUG"); + output.println("raw_test_pass(0xec00);"); + output.println("#endif"); + output.println("raw_flush_entire_cache();"); + output.println("#ifdef RAWDEBUG"); + output.println("raw_test_pass(0xecff);"); + output.println("#endif"); + output.println("raw_user_interrupts_on();"); + output.println("#endif"); + outputTransCode(output); + } + output.println("return;"); } - - class TranObjInfo { - public String name; - public int targetcore; - public FlagState fs; + } + + class TranObjInfo { + public String name; + public int targetcore; + public FlagState fs; + } + + private boolean contains(Vector sendto, TranObjInfo t) { + if(sendto.size() == 0) { + return false; } - - private boolean contains(Vector sendto, TranObjInfo t) { - if(sendto.size() == 0) { - return false; - } - for(int i = 0; i < sendto.size(); i++) { - TranObjInfo tmp = sendto.elementAt(i); - if(!tmp.name.equals(t.name)) { - return false; - } - if(tmp.targetcore != t.targetcore) { - return false; - } - if(tmp.fs != t.fs) { - return false; - } - } - return true; + for(int i = 0; i < sendto.size(); i++) { + TranObjInfo tmp = sendto.elementAt(i); + if(!tmp.name.equals(t.name)) { + return false; + } + if(tmp.targetcore != t.targetcore) { + return false; + } + if(tmp.fs != t.fs) { + return false; + } } + return true; + } } diff --git a/Robust/src/IR/Flat/BuildFlat.java b/Robust/src/IR/Flat/BuildFlat.java index a460cc98..66b37355 100644 --- a/Robust/src/IR/Flat/BuildFlat.java +++ b/Robust/src/IR/Flat/BuildFlat.java @@ -4,1011 +4,1019 @@ import IR.Tree.*; import java.util.*; public class BuildFlat { - State state; - Hashtable temptovar; - MethodDescriptor currmd; - TypeUtil typeutil; - - public BuildFlat(State st, TypeUtil typeutil) { - state=st; - temptovar=new Hashtable(); - this.typeutil=typeutil; + State state; + Hashtable temptovar; + MethodDescriptor currmd; + TypeUtil typeutil; + + public BuildFlat(State st, TypeUtil typeutil) { + state=st; + temptovar=new Hashtable(); + this.typeutil=typeutil; + } + + public Hashtable getMap() { + return temptovar; + } + + public void buildFlat() { + Iterator it=state.getClassSymbolTable().getDescriptorsIterator(); + while(it.hasNext()) { + ClassDescriptor cn=(ClassDescriptor)it.next(); + flattenClass(cn); } - public Hashtable getMap() { - return temptovar; + Iterator task_it=state.getTaskSymbolTable().getDescriptorsIterator(); + while(task_it.hasNext()) { + TaskDescriptor td=(TaskDescriptor)task_it.next(); + flattenTask(td); + } + } + + private void flattenTask(TaskDescriptor td) { + BlockNode bn=state.getMethodBody(td); + NodePair np=flattenBlockNode(bn); + FlatNode fn=np.getBegin(); + if (np.getEnd().kind()!=FKind.FlatReturnNode) { + FlatReturnNode rnflat=new FlatReturnNode(null); + np.getEnd().addNext(rnflat); } - public void buildFlat() { - Iterator it=state.getClassSymbolTable().getDescriptorsIterator(); - while(it.hasNext()) { - ClassDescriptor cn=(ClassDescriptor)it.next(); - flattenClass(cn); - } - - Iterator task_it=state.getTaskSymbolTable().getDescriptorsIterator(); - while(task_it.hasNext()) { - TaskDescriptor td=(TaskDescriptor)task_it.next(); - flattenTask(td); + FlatFlagActionNode ffan=new FlatFlagActionNode(FlatFlagActionNode.PRE); + ffan.addNext(fn); + + FlatMethod fm=new FlatMethod(td); + fm.addNext(ffan); + + Hashtable visitedset=new Hashtable(); + + 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 + return new NodePair(first, fn); } - - private NodePair flattenBlockExpressionNode(BlockExpressionNode en) { - TempDescriptor tmp=TempDescriptor.tempFactory("neverused",en.getExpression().getType()); - return flattenExpressionNode(en.getExpression(),tmp); + } + + private NodePair generateNewArrayLoop(TempDescriptor[] temparray, TypeDescriptor td, TempDescriptor tmp, int i, boolean isglobal) { + TempDescriptor index=TempDescriptor.tempFactory("index",new TypeDescriptor(TypeDescriptor.INT)); + TempDescriptor tmpone=TempDescriptor.tempFactory("index",new TypeDescriptor(TypeDescriptor.INT)); + FlatNop fnop=new FlatNop(); //last node + + //index=0 + FlatLiteralNode fln=new FlatLiteralNode(index.getType(),new Integer(0),index); + //tmpone=1 + FlatLiteralNode fln2=new FlatLiteralNode(tmpone.getType(),new Integer(1),tmpone); + + TempDescriptor tmpbool=TempDescriptor.tempFactory("comp",new TypeDescriptor(TypeDescriptor.BOOLEAN)); + + FlatOpNode fcomp=new FlatOpNode(tmpbool,index,temparray[i],new Operation(Operation.LT)); + FlatCondBranch fcb=new FlatCondBranch(tmpbool); + fcb.setTrueProb(State.TRUEPROB); + fcb.setLoop(); + //is index1) { - 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); - } + MethodDescriptor md=min.getMethod(); + + //Call to constructor + + FlatCall fc; + if(md.getReturnType()==null||md.getReturnType().isVoid()) + fc=new FlatCall(md, null, thisarg, temps); + else + fc=new FlatCall(md, out_temp, thisarg, temps); + if (first==null) { + first=fc; + } else + last.addNext(fc); + return new NodePair(first,fc); + } + + private NodePair flattenFieldAccessNode(FieldAccessNode fan,TempDescriptor out_temp) { + TempDescriptor tmp=TempDescriptor.tempFactory("temp",fan.getExpression().getType()); + NodePair npe=flattenExpressionNode(fan.getExpression(),tmp); + FlatFieldNode fn=new FlatFieldNode(fan.getField(),tmp,out_temp); + npe.getEnd().addNext(fn); + return new NodePair(npe.getBegin(),fn); + } + + private NodePair flattenArrayAccessNode(ArrayAccessNode aan,TempDescriptor out_temp) { + TempDescriptor tmp=TempDescriptor.tempFactory("temp",aan.getExpression().getType()); + TempDescriptor tmpindex=TempDescriptor.tempFactory("temp",aan.getIndex().getType()); + NodePair npe=flattenExpressionNode(aan.getExpression(),tmp); + NodePair npi=flattenExpressionNode(aan.getIndex(),tmpindex); + FlatElementNode fn=new FlatElementNode(tmp,tmpindex,out_temp); + npe.getEnd().addNext(npi.getBegin()); + npi.getEnd().addNext(fn); + return new NodePair(npe.getBegin(),fn); + } + + private NodePair flattenAssignmentNode(AssignmentNode an,TempDescriptor out_temp) { + // Three cases: + // left side is variable + // left side is field + // left side is array + + Operation base=an.getOperation().getBaseOp(); + boolean pre=base==null||(base.getOp()!=Operation.POSTINC&&base.getOp()!=Operation.POSTDEC); + + if (!pre) { + //rewrite the base operation + base=base.getOp()==Operation.POSTINC ? new Operation(Operation.ADD) : new Operation(Operation.SUB); + } + FlatNode first=null; + FlatNode last=null; + TempDescriptor src_tmp=an.getSrc()==null ? TempDescriptor.tempFactory("srctmp",an.getDest().getType()) : TempDescriptor.tempFactory("srctmp",an.getSrc().getType()); + + //Get src value + if (an.getSrc()!=null) { + 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); + first=fln; + last=fln; } - private NodePair generateNewArrayLoop(TempDescriptor[] temparray, TypeDescriptor td, TempDescriptor tmp, int i, boolean isglobal) { - TempDescriptor index=TempDescriptor.tempFactory("index",new TypeDescriptor(TypeDescriptor.INT)); - TempDescriptor tmpone=TempDescriptor.tempFactory("index",new TypeDescriptor(TypeDescriptor.INT)); - FlatNop fnop=new FlatNop();//last node - - //index=0 - FlatLiteralNode fln=new FlatLiteralNode(index.getType(),new Integer(0),index); - //tmpone=1 - FlatLiteralNode fln2=new FlatLiteralNode(tmpone.getType(),new Integer(1),tmpone); - - TempDescriptor tmpbool=TempDescriptor.tempFactory("comp",new TypeDescriptor(TypeDescriptor.BOOLEAN)); - - FlatOpNode fcomp=new FlatOpNode(tmpbool,index,temparray[i],new Operation(Operation.LT)); - FlatCondBranch fcb=new FlatCondBranch(tmpbool); - fcb.setTrueProb(State.TRUEPROB); - fcb.setLoop(); - //is index tempflagpairs; - Hashtable temptagpairs; - - int taskexit; - public static final int NEWOBJECT=0; - public static final int PRE=1; - public static final int TASKEXIT=2; - - Hashtable> cd2initfs; - Hashtable> cd2fs4new; - Hashtable> fs2fs; - - - public FlatFlagActionNode(int taskexit) { - tempflagpairs=new Hashtable(); - temptagpairs=new Hashtable(); - this.taskexit=taskexit; - - this.cd2initfs = null; - this.cd2fs4new = null; - this.fs2fs = null; - } + Hashtable tempflagpairs; + Hashtable temptagpairs; - public int getTaskType() { - return taskexit; - } - - public Vector getInitFStates(ClassDescriptor cd) { - if(this.cd2initfs == null) { - this.cd2initfs = new Hashtable>(); - } - if(this.cd2initfs.get(cd) == null) { - this.cd2initfs.put(cd, new Vector()); - } - return this.cd2initfs.get(cd); - } - - public Vector getTargetFStates4NewObj(ClassDescriptor cd) { - if(this.cd2fs4new == null) { - this.cd2fs4new = new Hashtable>(); - } - if(this.cd2fs4new.get(cd) == null) { - this.cd2fs4new.put(cd, new Vector()); - } - return this.cd2fs4new.get(cd); + int taskexit; + public static final int NEWOBJECT=0; + public static final int PRE=1; + public static final int TASKEXIT=2; + + Hashtable> cd2initfs; + Hashtable> cd2fs4new; + Hashtable> fs2fs; + + + public FlatFlagActionNode(int taskexit) { + tempflagpairs=new Hashtable(); + temptagpairs=new Hashtable(); + this.taskexit=taskexit; + + this.cd2initfs = null; + this.cd2fs4new = null; + this.fs2fs = null; + } + + public int getTaskType() { + return taskexit; + } + + public Vector getInitFStates(ClassDescriptor cd) { + if(this.cd2initfs == null) { + this.cd2initfs = new Hashtable>(); } - - public Vector getTargetFStates(FlagState fs) { - if(this.fs2fs == null) { - this.fs2fs = new Hashtable>(); - } - if(this.fs2fs.get(fs) == null) { - this.fs2fs.put(fs, new Vector()); - } - return this.fs2fs.get(fs); + if(this.cd2initfs.get(cd) == null) { + this.cd2initfs.put(cd, new Vector()); } + return this.cd2initfs.get(cd); + } - public void addFlagAction(TempDescriptor td, FlagDescriptor fd, boolean status) { - TempFlagPair tfp=new TempFlagPair(td,fd); - if (tempflagpairs.containsKey(tfp)) { - throw new Error("Temp/Flag combination used twice: "+tfp); - } - tempflagpairs.put(tfp, new Boolean(status)); + public Vector getTargetFStates4NewObj(ClassDescriptor cd) { + if(this.cd2fs4new == null) { + this.cd2fs4new = new Hashtable>(); } - - public void addTagAction(TempDescriptor td, TagDescriptor tagd, TempDescriptor tagt, boolean status) { - TempTagPair ttp=new TempTagPair(td,tagd, tagt); - if (temptagpairs.containsKey(ttp)) { - throw new Error("Temp/Tag combination used twice: "+ttp); - } - temptagpairs.put(ttp, new Boolean(status)); + if(this.cd2fs4new.get(cd) == null) { + this.cd2fs4new.put(cd, new Vector()); } + return this.cd2fs4new.get(cd); + } - public int kind() { - return FKind.FlatFlagActionNode; + public Vector getTargetFStates(FlagState fs) { + if(this.fs2fs == null) { + this.fs2fs = new Hashtable>(); } - - /** This method returns an iterator over the Temp/Flag pairs. */ - - public Iterator getTempFlagPairs() { - return tempflagpairs.keySet().iterator(); + if(this.fs2fs.get(fs) == null) { + this.fs2fs.put(fs, new Vector()); } + return this.fs2fs.get(fs); + } - public Iterator getTempTagPairs() { - return temptagpairs.keySet().iterator(); + public void addFlagAction(TempDescriptor td, FlagDescriptor fd, boolean status) { + TempFlagPair tfp=new TempFlagPair(td,fd); + if (tempflagpairs.containsKey(tfp)) { + throw new Error("Temp/Flag combination used twice: "+tfp); } + tempflagpairs.put(tfp, new Boolean(status)); + } - public boolean getFlagChange(TempFlagPair tfp) { - return ((Boolean)tempflagpairs.get(tfp)).booleanValue(); + public void addTagAction(TempDescriptor td, TagDescriptor tagd, TempDescriptor tagt, boolean status) { + TempTagPair ttp=new TempTagPair(td,tagd, tagt); + if (temptagpairs.containsKey(ttp)) { + throw new Error("Temp/Tag combination used twice: "+ttp); } + temptagpairs.put(ttp, new Boolean(status)); + } - public boolean getTagChange(TempTagPair ttp) { - return ((Boolean)temptagpairs.get(ttp)).booleanValue(); - } + public int kind() { + return FKind.FlatFlagActionNode; + } - public TempDescriptor [] readsTemps() { - if (tempflagpairs.size()==0) - return new TempDescriptor [0]; - else { - HashSet temps=new HashSet(); - for(Iterator it=tempflagpairs.keySet().iterator();it.hasNext();) { - TempFlagPair tfp=(TempFlagPair)it.next(); - temps.add(tfp.getTemp()); - } - for(Iterator it=temptagpairs.keySet().iterator();it.hasNext();) { - TempTagPair ttp=(TempTagPair)it.next(); - temps.add(ttp.getTemp()); - temps.add(ttp.getTagTemp()); - } - return (TempDescriptor[]) temps.toArray(new TempDescriptor [temps.size()]); - } - } + /** This method returns an iterator over the Temp/Flag pairs. */ + + public Iterator getTempFlagPairs() { + return tempflagpairs.keySet().iterator(); + } + + public Iterator getTempTagPairs() { + return temptagpairs.keySet().iterator(); + } + + public boolean getFlagChange(TempFlagPair tfp) { + return ((Boolean)tempflagpairs.get(tfp)).booleanValue(); + } - public int getFFANType() - { - throw new Error("Use getTaskType() instead and remove this method"); + public boolean getTagChange(TempTagPair ttp) { + return ((Boolean)temptagpairs.get(ttp)).booleanValue(); + } + + public TempDescriptor [] readsTemps() { + if (tempflagpairs.size()==0) + return new TempDescriptor [0]; + else { + HashSet temps=new HashSet(); + for(Iterator it=tempflagpairs.keySet().iterator(); it.hasNext();) { + TempFlagPair tfp=(TempFlagPair)it.next(); + temps.add(tfp.getTemp()); + } + for(Iterator it=temptagpairs.keySet().iterator(); it.hasNext();) { + TempTagPair ttp=(TempTagPair)it.next(); + temps.add(ttp.getTemp()); + temps.add(ttp.getTagTemp()); + } + return (TempDescriptor[])temps.toArray(new TempDescriptor [temps.size()]); } + } + + public int getFFANType() { + throw new Error("Use getTaskType() instead and remove this method"); + } - public String toString() { - String st="FlatFlagActionNode_"; - for(Iterator it=tempflagpairs.keySet().iterator();it.hasNext();) { - TempFlagPair tfp=(TempFlagPair)it.next(); - st+=getFlagChange(tfp)?"":"!"; - st+=tfp.getTemp()+" "+tfp.getFlag()+","; - } - for(Iterator it=temptagpairs.keySet().iterator();it.hasNext();) { - TempTagPair ttp=(TempTagPair)it.next(); - st+=getTagChange(ttp)?"":"!"; - st+=ttp.getTemp()+" "+ttp.getTag()+"("+ttp.getTagTemp()+"),"; - } - - return st; + public String toString() { + String st="FlatFlagActionNode_"; + for(Iterator it=tempflagpairs.keySet().iterator(); it.hasNext();) { + TempFlagPair tfp=(TempFlagPair)it.next(); + st+=getFlagChange(tfp) ? "" : "!"; + st+=tfp.getTemp()+" "+tfp.getFlag()+","; } + for(Iterator it=temptagpairs.keySet().iterator(); it.hasNext();) { + TempTagPair ttp=(TempTagPair)it.next(); + st+=getTagChange(ttp) ? "" : "!"; + st+=ttp.getTemp()+" "+ttp.getTag()+"("+ttp.getTagTemp()+"),"; + } + + return st; + } } diff --git a/Robust/src/IR/Flat/FlatGlobalConvNode.java b/Robust/src/IR/Flat/FlatGlobalConvNode.java index 0d189446..d3b5d107 100644 --- a/Robust/src/IR/Flat/FlatGlobalConvNode.java +++ b/Robust/src/IR/Flat/FlatGlobalConvNode.java @@ -3,46 +3,46 @@ import IR.TypeDescriptor; import Analysis.Locality.LocalityBinding; public class FlatGlobalConvNode extends FlatNode { - TempDescriptor src; - LocalityBinding lb; - boolean makePtr; - - public FlatGlobalConvNode(TempDescriptor src, LocalityBinding lb, boolean makePtr) { - this.src=src; - this.lb=lb; - this.makePtr=makePtr; - } - - public String toString() { - String str = "FlatGlobalConvNode_"+src.toString(); - if (makePtr) - str += "=(PTR)"; - else - str += "=(OID)"; - return str+src.toString()+" "+lb; - } - - public int kind() { - return FKind.FlatGlobalConvNode; - } - - public LocalityBinding getLocality() { - return lb; - } - - public boolean getMakePtr() { - return makePtr; - } - - public TempDescriptor getSrc() { - return src; - } - - public TempDescriptor [] writesTemps() { - return new TempDescriptor[] {src}; - } - - public TempDescriptor [] readsTemps() { - return new TempDescriptor[] {src}; - } + TempDescriptor src; + LocalityBinding lb; + boolean makePtr; + + public FlatGlobalConvNode(TempDescriptor src, LocalityBinding lb, boolean makePtr) { + this.src=src; + this.lb=lb; + this.makePtr=makePtr; + } + + public String toString() { + String str = "FlatGlobalConvNode_"+src.toString(); + if (makePtr) + str += "=(PTR)"; + else + str += "=(OID)"; + return str+src.toString()+" "+lb; + } + + public int kind() { + return FKind.FlatGlobalConvNode; + } + + public LocalityBinding getLocality() { + return lb; + } + + public boolean getMakePtr() { + return makePtr; + } + + public TempDescriptor getSrc() { + return src; + } + + public TempDescriptor [] writesTemps() { + return new TempDescriptor[] {src}; + } + + public TempDescriptor [] readsTemps() { + return new TempDescriptor[] {src}; + } } diff --git a/Robust/src/IR/Flat/FlatLiteralNode.java b/Robust/src/IR/Flat/FlatLiteralNode.java index 58514317..99c1087d 100644 --- a/Robust/src/IR/Flat/FlatLiteralNode.java +++ b/Robust/src/IR/Flat/FlatLiteralNode.java @@ -2,56 +2,56 @@ package IR.Flat; import IR.TypeDescriptor; public class FlatLiteralNode extends FlatNode { - Object value; - TypeDescriptor type; - TempDescriptor dst; - - public FlatLiteralNode(TypeDescriptor type, Object o, TempDescriptor dst) { - this.type=type; - value=o; - this.dst=dst; - } - - public TypeDescriptor getType() { - return type; - } - - public TempDescriptor getDst() { - return dst; - } - - public Object getValue() { - return value; - } - - public String toString() { - String str = "FlatLiteralNode_"+dst; - if (value==null) - str += "=null"; - else - str += "="+escapeString(value.toString()); - return str; - } - protected static String escapeString(String st) { - String new_st=""; - for(int i=0;i getNodeSet() { - HashSet tovisit=new HashSet(); - HashSet visited=new HashSet(); - tovisit.add(this); - while(!tovisit.isEmpty()) { - FlatNode fn=tovisit.iterator().next(); - tovisit.remove(fn); - visited.add(fn); - for(int i=0;i getNodeSet() { + HashSet tovisit=new HashSet(); + HashSet visited=new HashSet(); + tovisit.add(this); + while(!tovisit.isEmpty()) { + FlatNode fn=tovisit.iterator().next(); + tovisit.remove(fn); + visited.add(fn); + for(int i=0; i0) { + //1) Edge >1 of node + nodetolabel.put(nn,new Integer(labelindex++)); } - return visited; - } - - public String printMethod() { - return printMethod(null); - } - - /** This method returns a string that is a human readable - * representation of this method. */ - - public String printMethod(Hashtable map) { - String st=method+" {\n"; - HashSet tovisit=new HashSet(); - HashSet visited=new HashSet(); - int labelindex=0; - Hashtable nodetolabel=new Hashtable(); - tovisit.add(this); - FlatNode current_node=null; - //Assign labels 1st - //Node needs a label if it is - while(!tovisit.isEmpty()) { - FlatNode fn=(FlatNode)tovisit.iterator().next(); - tovisit.remove(fn); - visited.add(fn); - - 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++)); - } - } - } - - //Do the actual printing - tovisit=new HashSet(); - visited=new HashSet(); - tovisit.add(this); - while(current_node!=null||!tovisit.isEmpty()) { - if (current_node==null) { - current_node=(FlatNode)tovisit.iterator().next(); - tovisit.remove(current_node); - } - visited.add(current_node); - if (nodetolabel.containsKey(current_node)) - st+="L"+nodetolabel.get(current_node)+":\n"; - if (current_node.numNext()==0) { - if (map==null) - st+=" "+current_node.toString()+"\n"; - else - st+=" "+current_node.toString()+"["+map.get(current_node)+"]\n"; - current_node=null; - } else if(current_node.numNext()==1) { - if (map==null) - st+=" "+current_node.toString()+"\n"; - else - st+=" "+current_node.toString()+"["+map.get(current_node)+"]\n"; - FlatNode nextnode=current_node.getNext(0); - if (visited.contains(nextnode)) { - st+="goto L"+nodetolabel.get(nextnode)+"\n"; - current_node=null; - } else - current_node=nextnode; - } else if (current_node.numNext()==2) { - /* Branch */ - st+=" "+((FlatCondBranch)current_node).toString("L"+nodetolabel.get(current_node.getNext(1)))+"\n"; - if (!visited.contains(current_node.getNext(1))) - tovisit.add(current_node.getNext(1)); - if (visited.contains(current_node.getNext(0))) { - st+="goto L"+nodetolabel.get(current_node.getNext(0))+"\n"; - current_node=null; - } else - current_node=current_node.getNext(0); - } else throw new Error(); + if (!visited.contains(nn)&&!tovisit.contains(nn)) { + tovisit.add(nn); + } else { + //2) Join point + nodetolabel.put(nn,new Integer(labelindex++)); } - return st+"}\n"; - } - - public TempDescriptor [] writesTemps() { - return (TempDescriptor[]) parameterTemps.toArray(new TempDescriptor[ parameterTemps.size()]); - } + } + } + + //Do the actual printing + tovisit=new HashSet(); + visited=new HashSet(); + tovisit.add(this); + while(current_node!=null||!tovisit.isEmpty()) { + if (current_node==null) { + current_node=(FlatNode)tovisit.iterator().next(); + tovisit.remove(current_node); + } + visited.add(current_node); + if (nodetolabel.containsKey(current_node)) + st+="L"+nodetolabel.get(current_node)+":\n"; + if (current_node.numNext()==0) { + if (map==null) + st+=" "+current_node.toString()+"\n"; + else + st+=" "+current_node.toString()+"["+map.get(current_node)+"]\n"; + current_node=null; + } else if(current_node.numNext()==1) { + if (map==null) + st+=" "+current_node.toString()+"\n"; + else + st+=" "+current_node.toString()+"["+map.get(current_node)+"]\n"; + FlatNode nextnode=current_node.getNext(0); + if (visited.contains(nextnode)) { + st+="goto L"+nodetolabel.get(nextnode)+"\n"; + current_node=null; + } else + current_node=nextnode; + } else if (current_node.numNext()==2) { + /* Branch */ + st+=" "+((FlatCondBranch)current_node).toString("L"+nodetolabel.get(current_node.getNext(1)))+"\n"; + if (!visited.contains(current_node.getNext(1))) + tovisit.add(current_node.getNext(1)); + if (visited.contains(current_node.getNext(0))) { + st+="goto L"+nodetolabel.get(current_node.getNext(0))+"\n"; + current_node=null; + } else + current_node=current_node.getNext(0); + } else throw new Error(); + } + return st+"}\n"; + } + + public TempDescriptor [] writesTemps() { + return (TempDescriptor[])parameterTemps.toArray(new TempDescriptor[ parameterTemps.size()]); + } } diff --git a/Robust/src/IR/Flat/FlatNew.java b/Robust/src/IR/Flat/FlatNew.java index 48737ecb..eec4beb4 100644 --- a/Robust/src/IR/Flat/FlatNew.java +++ b/Robust/src/IR/Flat/FlatNew.java @@ -2,60 +2,60 @@ package IR.Flat; import IR.TypeDescriptor; public class FlatNew extends FlatNode { - TempDescriptor dst; - TypeDescriptor type; - TempDescriptor size; - boolean isglobal; - - public FlatNew(TypeDescriptor type, TempDescriptor dst, boolean isglobal) { - this.type=type; - this.dst=dst; - this.size=null; - this.isglobal=isglobal; - } - - public FlatNew(TypeDescriptor type, TempDescriptor dst, TempDescriptor size, boolean isglobal) { - this.type=type; - this.dst=dst; - this.size=size; - this.isglobal=isglobal; - } - - public boolean isGlobal() { - return isglobal; - } - - public String toString() { - String str = "FlatNew_"+dst.toString()+"= NEW "+type.toString(); - if (size!=null) - str += "["+size.toString()+"]"; - return str; - } - - public int kind() { - return FKind.FlatNew; - } - - public TempDescriptor [] writesTemps() { - return new TempDescriptor[] {dst}; - } - - public TempDescriptor [] readsTemps() { - if (size!=null) - return new TempDescriptor[] {size}; - else - return new TempDescriptor[0]; - } - - public TempDescriptor getDst() { - return dst; - } - - public TempDescriptor getSize() { - return size; - } - - public TypeDescriptor getType() { - return type; - } + TempDescriptor dst; + TypeDescriptor type; + TempDescriptor size; + boolean isglobal; + + public FlatNew(TypeDescriptor type, TempDescriptor dst, boolean isglobal) { + this.type=type; + this.dst=dst; + this.size=null; + this.isglobal=isglobal; + } + + public FlatNew(TypeDescriptor type, TempDescriptor dst, TempDescriptor size, boolean isglobal) { + this.type=type; + this.dst=dst; + this.size=size; + this.isglobal=isglobal; + } + + public boolean isGlobal() { + return isglobal; + } + + public String toString() { + String str = "FlatNew_"+dst.toString()+"= NEW "+type.toString(); + if (size!=null) + str += "["+size.toString()+"]"; + return str; + } + + public int kind() { + return FKind.FlatNew; + } + + public TempDescriptor [] writesTemps() { + return new TempDescriptor[] {dst}; + } + + public TempDescriptor [] readsTemps() { + if (size!=null) + return new TempDescriptor[] {size}; + else + return new TempDescriptor[0]; + } + + public TempDescriptor getDst() { + return dst; + } + + public TempDescriptor getSize() { + return size; + } + + public TypeDescriptor getType() { + return type; + } } diff --git a/Robust/src/IR/Flat/FlatNode.java b/Robust/src/IR/Flat/FlatNode.java index 714b894b..57dcb736 100644 --- a/Robust/src/IR/Flat/FlatNode.java +++ b/Robust/src/IR/Flat/FlatNode.java @@ -2,56 +2,56 @@ package IR.Flat; import java.util.Vector; public class FlatNode { - protected Vector next; - protected Vector prev; - - public FlatNode() { - next=new Vector(); - prev=new Vector(); - } - - public String toString() { - throw new Error(this.getClass().getName() + "does not implement toString!"); - } - public int numNext() { - return next.size(); - } - public FlatNode getNext(int i) { - return (FlatNode) next.get(i); - } - - public int numPrev() { - return prev.size(); - } - public FlatNode getPrev(int i) { - return (FlatNode) prev.get(i); - } - - public void addNext(FlatNode n) { - next.add(n); - n.addPrev(this); - } - - /** This function modifies the graph */ - public void setNext(int i, FlatNode n) { - FlatNode old=getNext(i); - next.set(i, n); - old.prev.remove(this); - n.addPrev(this); - } - - protected void addPrev(FlatNode p) { - prev.add(p); - } - public int kind() { - throw new Error(); - } - - public TempDescriptor [] readsTemps() { - return new TempDescriptor[0]; - } - - public TempDescriptor [] writesTemps() { - return new TempDescriptor[0]; - } + protected Vector next; + protected Vector prev; + + public FlatNode() { + next=new Vector(); + prev=new Vector(); + } + + public String toString() { + throw new Error(this.getClass().getName() + "does not implement toString!"); + } + public int numNext() { + return next.size(); + } + public FlatNode getNext(int i) { + return (FlatNode) next.get(i); + } + + public int numPrev() { + return prev.size(); + } + public FlatNode getPrev(int i) { + return (FlatNode) prev.get(i); + } + + public void addNext(FlatNode n) { + next.add(n); + n.addPrev(this); + } + + /** This function modifies the graph */ + public void setNext(int i, FlatNode n) { + FlatNode old=getNext(i); + next.set(i, n); + old.prev.remove(this); + n.addPrev(this); + } + + protected void addPrev(FlatNode p) { + prev.add(p); + } + public int kind() { + throw new Error(); + } + + public TempDescriptor [] readsTemps() { + return new TempDescriptor[0]; + } + + public TempDescriptor [] writesTemps() { + return new TempDescriptor[0]; + } } diff --git a/Robust/src/IR/Flat/FlatNop.java b/Robust/src/IR/Flat/FlatNop.java index 36079fbf..fdcab4ed 100644 --- a/Robust/src/IR/Flat/FlatNop.java +++ b/Robust/src/IR/Flat/FlatNop.java @@ -2,14 +2,14 @@ package IR.Flat; import java.util.Vector; public class FlatNop extends FlatNode { - public FlatNop() { - } + public FlatNop() { + } - public String toString() { - return "nop"; - } + public String toString() { + return "nop"; + } - public int kind() { - return FKind.FlatNop; - } + public int kind() { + return FKind.FlatNop; + } } diff --git a/Robust/src/IR/Flat/FlatOpNode.java b/Robust/src/IR/Flat/FlatOpNode.java index 5cd20068..ade59315 100644 --- a/Robust/src/IR/Flat/FlatOpNode.java +++ b/Robust/src/IR/Flat/FlatOpNode.java @@ -3,57 +3,57 @@ import java.util.Vector; import IR.*; public class FlatOpNode extends FlatNode { - TempDescriptor dest; - TempDescriptor left; - TempDescriptor right; - Operation op; - - public FlatOpNode(TempDescriptor dest, TempDescriptor left, TempDescriptor right, Operation op) { - this.dest=dest; - this.left=left; - this.right=right; - this.op=op; - } - - public TempDescriptor getDest() { - return dest; - } - - public TempDescriptor getLeft() { - return left; - } - - public TempDescriptor getRight() { - return right; - } - - public Operation getOp() { - return op; - } - - public String toString() { - String str = "FlatOpNode_"+dest.toString(); - if (right!=null) - str += "="+left.toString()+op.toString()+right.toString(); - else if (op.getOp()==Operation.ASSIGN) - str += " = "+left.toString(); - else - str += " "+op.toString() +" "+left.toString(); - return str; - } - - public int kind() { - return FKind.FlatOpNode; - } - - public TempDescriptor [] readsTemps() { - if (right!=null) - return new TempDescriptor [] {left,right}; - else - return new TempDescriptor [] {left}; - } - - public TempDescriptor [] writesTemps() { - return new TempDescriptor [] {dest}; - } + TempDescriptor dest; + TempDescriptor left; + TempDescriptor right; + Operation op; + + public FlatOpNode(TempDescriptor dest, TempDescriptor left, TempDescriptor right, Operation op) { + this.dest=dest; + this.left=left; + this.right=right; + this.op=op; + } + + public TempDescriptor getDest() { + return dest; + } + + public TempDescriptor getLeft() { + return left; + } + + public TempDescriptor getRight() { + return right; + } + + public Operation getOp() { + return op; + } + + public String toString() { + String str = "FlatOpNode_"+dest.toString(); + if (right!=null) + str += "="+left.toString()+op.toString()+right.toString(); + else if (op.getOp()==Operation.ASSIGN) + str += " = "+left.toString(); + else + str += " "+op.toString() +" "+left.toString(); + return str; + } + + public int kind() { + return FKind.FlatOpNode; + } + + public TempDescriptor [] readsTemps() { + if (right!=null) + return new TempDescriptor [] {left,right}; + else + return new TempDescriptor [] {left}; + } + + public TempDescriptor [] writesTemps() { + return new TempDescriptor [] {dest}; + } } diff --git a/Robust/src/IR/Flat/FlatPrefetchNode.java b/Robust/src/IR/Flat/FlatPrefetchNode.java index 4baaf6ad..03643115 100644 --- a/Robust/src/IR/Flat/FlatPrefetchNode.java +++ b/Robust/src/IR/Flat/FlatPrefetchNode.java @@ -3,44 +3,44 @@ import Analysis.Prefetch.*; import java.util.*; public class FlatPrefetchNode extends FlatNode { - public Integer siteid; - HashSet hspp; - - public FlatPrefetchNode() { - hspp = new HashSet(); - siteid = new Integer(1); - } - - public String toString() { - String st="prefetch("; - boolean first=true; - for(Iterator it=hspp.iterator();it.hasNext();) { - PrefetchPair pp=it.next(); - if (!first) - st+=", "; - first=false; - st+=pp; - } - return st+")"; - } - - public int kind() { - return FKind.FlatPrefetchNode; - } - - public void insPrefetchPair(PrefetchPair pp) { - hspp.add(pp); - } - - public void insAllpp(HashSet hspp) { - this.hspp.addAll(hspp); - } - - public HashSet getPrefetchPairs() { - return hspp; - } - - public int getNumPairs() { - return hspp.size(); - } + public Integer siteid; + HashSet hspp; + + public FlatPrefetchNode() { + hspp = new HashSet(); + siteid = new Integer(1); + } + + public String toString() { + String st="prefetch("; + boolean first=true; + for(Iterator it=hspp.iterator(); it.hasNext();) { + PrefetchPair pp=it.next(); + if (!first) + st+=", "; + first=false; + st+=pp; + } + return st+")"; + } + + public int kind() { + return FKind.FlatPrefetchNode; + } + + public void insPrefetchPair(PrefetchPair pp) { + hspp.add(pp); + } + + public void insAllpp(HashSet hspp) { + this.hspp.addAll(hspp); + } + + public HashSet getPrefetchPairs() { + return hspp; + } + + public int getNumPairs() { + return hspp.size(); + } } diff --git a/Robust/src/IR/Flat/FlatReturnNode.java b/Robust/src/IR/Flat/FlatReturnNode.java index fb2d3b97..f90fd751 100644 --- a/Robust/src/IR/Flat/FlatReturnNode.java +++ b/Robust/src/IR/Flat/FlatReturnNode.java @@ -1,28 +1,28 @@ package IR.Flat; public class FlatReturnNode extends FlatNode { - TempDescriptor tempdesc; + TempDescriptor tempdesc; - public FlatReturnNode(TempDescriptor td) { - this.tempdesc=td; - } + public FlatReturnNode(TempDescriptor td) { + this.tempdesc=td; + } - public String toString() { - return "FlatReturnNode_return "+tempdesc; - } + public String toString() { + return "FlatReturnNode_return "+tempdesc; + } - public int kind() { - return FKind.FlatReturnNode; - } + public int kind() { + return FKind.FlatReturnNode; + } - public TempDescriptor [] readsTemps() { - if (tempdesc==null) - return new TempDescriptor [0]; - else - return new TempDescriptor [] {tempdesc}; - } + public TempDescriptor [] readsTemps() { + if (tempdesc==null) + return new TempDescriptor [0]; + else + return new TempDescriptor [] {tempdesc}; + } - public TempDescriptor getReturnTemp() { - return tempdesc; - } + public TempDescriptor getReturnTemp() { + return tempdesc; + } } diff --git a/Robust/src/IR/Flat/FlatSetElementNode.java b/Robust/src/IR/Flat/FlatSetElementNode.java index d7e748e8..6dd4a624 100644 --- a/Robust/src/IR/Flat/FlatSetElementNode.java +++ b/Robust/src/IR/Flat/FlatSetElementNode.java @@ -2,41 +2,41 @@ package IR.Flat; import IR.FieldDescriptor; public class FlatSetElementNode extends FlatNode { - TempDescriptor src; - TempDescriptor dst; - TempDescriptor index; - - public FlatSetElementNode(TempDescriptor dst, TempDescriptor index, TempDescriptor src) { - this.index=index; - this.src=src; - this.dst=dst; - } - - public boolean needsBoundsCheck() { - return true; - } - - public TempDescriptor getSrc() { - return src; - } - - public TempDescriptor getIndex() { - return index; - } - - public TempDescriptor getDst() { - return dst; - } - - public String toString() { - return "FlatSetElementNode_"+dst.toString()+"["+index.toString()+"]="+src.toString(); - } - - public int kind() { - return FKind.FlatSetElementNode; - } - - public TempDescriptor [] readsTemps() { - return new TempDescriptor [] {src,dst,index}; - } + TempDescriptor src; + TempDescriptor dst; + TempDescriptor index; + + public FlatSetElementNode(TempDescriptor dst, TempDescriptor index, TempDescriptor src) { + this.index=index; + this.src=src; + this.dst=dst; + } + + public boolean needsBoundsCheck() { + return true; + } + + public TempDescriptor getSrc() { + return src; + } + + public TempDescriptor getIndex() { + return index; + } + + public TempDescriptor getDst() { + return dst; + } + + public String toString() { + return "FlatSetElementNode_"+dst.toString()+"["+index.toString()+"]="+src.toString(); + } + + public int kind() { + return FKind.FlatSetElementNode; + } + + public TempDescriptor [] readsTemps() { + return new TempDescriptor [] {src,dst,index}; + } } diff --git a/Robust/src/IR/Flat/FlatSetFieldNode.java b/Robust/src/IR/Flat/FlatSetFieldNode.java index e34de29b..50e834ed 100644 --- a/Robust/src/IR/Flat/FlatSetFieldNode.java +++ b/Robust/src/IR/Flat/FlatSetFieldNode.java @@ -2,37 +2,37 @@ package IR.Flat; import IR.FieldDescriptor; public class FlatSetFieldNode extends FlatNode { - TempDescriptor src; - TempDescriptor dst; - FieldDescriptor field; - - public FlatSetFieldNode(TempDescriptor dst, FieldDescriptor field, TempDescriptor src) { - this.field=field; - this.src=src; - this.dst=dst; - } - - public TempDescriptor getSrc() { - return src; - } - - public TempDescriptor getDst() { - return dst; - } - - public FieldDescriptor getField() { - return field; - } - - public String toString() { - return "FlatSetFieldNode_"+dst.toString()+"."+field.getSymbol()+"="+src.toString(); - } - - public int kind() { - return FKind.FlatSetFieldNode; - } - - public TempDescriptor [] readsTemps() { - return new TempDescriptor [] {src,dst}; - } + TempDescriptor src; + TempDescriptor dst; + FieldDescriptor field; + + public FlatSetFieldNode(TempDescriptor dst, FieldDescriptor field, TempDescriptor src) { + this.field=field; + this.src=src; + this.dst=dst; + } + + public TempDescriptor getSrc() { + return src; + } + + public TempDescriptor getDst() { + return dst; + } + + public FieldDescriptor getField() { + return field; + } + + public String toString() { + return "FlatSetFieldNode_"+dst.toString()+"."+field.getSymbol()+"="+src.toString(); + } + + public int kind() { + return FKind.FlatSetFieldNode; + } + + public TempDescriptor [] readsTemps() { + return new TempDescriptor [] {src,dst}; + } } diff --git a/Robust/src/IR/Flat/FlatTagDeclaration.java b/Robust/src/IR/Flat/FlatTagDeclaration.java index 0e48da4d..78cdcddc 100644 --- a/Robust/src/IR/Flat/FlatTagDeclaration.java +++ b/Robust/src/IR/Flat/FlatTagDeclaration.java @@ -2,35 +2,35 @@ package IR.Flat; import IR.TagDescriptor; public class FlatTagDeclaration extends FlatNode { - TempDescriptor dst; - TagDescriptor type; - - public FlatTagDeclaration(TagDescriptor type, TempDescriptor dst) { - this.type=type; - this.dst=dst; - } - - public String toString() { - return "FlatTagDeclaration_"+dst.toString()+"= new Tag("+type.toString()+")"; - } - - public int kind() { - return FKind.FlatTagDeclaration; - } - - public TempDescriptor [] writesTemps() { - return new TempDescriptor[] {dst}; - } - - public TempDescriptor [] readsTemps() { - return new TempDescriptor[0]; - } - - public TempDescriptor getDst() { - return dst; - } - - public TagDescriptor getType() { - return type; - } + TempDescriptor dst; + TagDescriptor type; + + public FlatTagDeclaration(TagDescriptor type, TempDescriptor dst) { + this.type=type; + this.dst=dst; + } + + public String toString() { + return "FlatTagDeclaration_"+dst.toString()+"= new Tag("+type.toString()+")"; + } + + public int kind() { + return FKind.FlatTagDeclaration; + } + + public TempDescriptor [] writesTemps() { + return new TempDescriptor[] {dst}; + } + + public TempDescriptor [] readsTemps() { + return new TempDescriptor[0]; + } + + public TempDescriptor getDst() { + return dst; + } + + public TagDescriptor getType() { + return type; + } } diff --git a/Robust/src/IR/Flat/NodePair.java b/Robust/src/IR/Flat/NodePair.java index f9164ffa..c3a826e0 100644 --- a/Robust/src/IR/Flat/NodePair.java +++ b/Robust/src/IR/Flat/NodePair.java @@ -1,19 +1,19 @@ package IR.Flat; public class NodePair { - FlatNode begin; - FlatNode end; + FlatNode begin; + FlatNode end; - public NodePair(FlatNode begin, FlatNode end) { - this.begin=begin; - this.end=end; - } + public NodePair(FlatNode begin, FlatNode end) { + this.begin=begin; + this.end=end; + } - public FlatNode getBegin() { - return begin; - } + public FlatNode getBegin() { + return begin; + } - public FlatNode getEnd() { - return end; - } + public FlatNode getEnd() { + return end; + } } diff --git a/Robust/src/IR/Flat/ParamsObject.java b/Robust/src/IR/Flat/ParamsObject.java index 8133a4a9..22c689c1 100644 --- a/Robust/src/IR/Flat/ParamsObject.java +++ b/Robust/src/IR/Flat/ParamsObject.java @@ -3,93 +3,93 @@ import IR.*; import java.util.*; public class ParamsObject { - private Vector pointerparams; - private Vector primitiveparams; - private MethodDescriptor method; - private TaskDescriptor task; - private int tag; - private Hashtable paramtotemp; - private Hashtable temptostore; - private int count; + private Vector pointerparams; + private Vector primitiveparams; + private MethodDescriptor method; + private TaskDescriptor task; + private int tag; + private Hashtable paramtotemp; + private Hashtable temptostore; + private int count; - public ParamsObject(MethodDescriptor md, int tag) { - pointerparams=new Vector(); - primitiveparams=new Vector(); - paramtotemp=new Hashtable(); - temptostore=new Hashtable(); - this.method=md; - this.tag=tag; - count=0; - } + public ParamsObject(MethodDescriptor md, int tag) { + pointerparams=new Vector(); + primitiveparams=new Vector(); + paramtotemp=new Hashtable(); + temptostore=new Hashtable(); + this.method=md; + this.tag=tag; + count=0; + } - public ParamsObject(TaskDescriptor task, int tag) { - pointerparams=new Vector(); - primitiveparams=new Vector(); - paramtotemp=new Hashtable(); - temptostore=new Hashtable(); - this.task=task; - this.tag=tag; - count=0; - } + public ParamsObject(TaskDescriptor task, int tag) { + pointerparams=new Vector(); + primitiveparams=new Vector(); + paramtotemp=new Hashtable(); + temptostore=new Hashtable(); + this.task=task; + this.tag=tag; + count=0; + } - public int getUID() { - return tag; - } + public int getUID() { + return tag; + } - public void addPtr(TempDescriptor t) { - Position p=new Position(true, pointerparams.size()); - pointerparams.add(t); - paramtotemp.put(new Integer(count++), t); - temptostore.put(t,p); - } + public void addPtr(TempDescriptor t) { + Position p=new Position(true, pointerparams.size()); + pointerparams.add(t); + paramtotemp.put(new Integer(count++), t); + temptostore.put(t,p); + } - public boolean isParamPtr(TempDescriptor t) { - if (containsTemp(t)) { - ParamsObject.Position p=(ParamsObject.Position)temptostore.get(t); - return p.inStruct; - } - return false; + public boolean isParamPtr(TempDescriptor t) { + if (containsTemp(t)) { + ParamsObject.Position p=(ParamsObject.Position)temptostore.get(t); + return p.inStruct; } + return false; + } - public boolean isParamPrim(TempDescriptor t) { - if (containsTemp(t)) { - ParamsObject.Position p=(ParamsObject.Position)temptostore.get(t); - return !p.inStruct; - } - return false; + public boolean isParamPrim(TempDescriptor t) { + if (containsTemp(t)) { + ParamsObject.Position p=(ParamsObject.Position)temptostore.get(t); + return !p.inStruct; } + return false; + } - public boolean containsTemp(TempDescriptor t) { - return temptostore.containsKey(t); - } + public boolean containsTemp(TempDescriptor t) { + return temptostore.containsKey(t); + } - public void addPrim(TempDescriptor t) { - Position p=new Position(false, primitiveparams.size()); - primitiveparams.add(t); - paramtotemp.put(new Integer(count++), t); - temptostore.put(t,p); - } + public void addPrim(TempDescriptor t) { + Position p=new Position(false, primitiveparams.size()); + primitiveparams.add(t); + paramtotemp.put(new Integer(count++), t); + temptostore.put(t,p); + } - int numPointers() { - return pointerparams.size(); - } + int numPointers() { + return pointerparams.size(); + } - TempDescriptor getPointer(int i) { - return (TempDescriptor) pointerparams.get(i); - } - int numPrimitives() { - return primitiveparams.size(); - } + TempDescriptor getPointer(int i) { + return (TempDescriptor) pointerparams.get(i); + } + int numPrimitives() { + return primitiveparams.size(); + } - TempDescriptor getPrimitive(int i) { - return (TempDescriptor) primitiveparams.get(i); - } - static class Position { - boolean inStruct; - int position; - Position(boolean inStruct, int position) { - this.inStruct=inStruct; - this.position=position; - } + TempDescriptor getPrimitive(int i) { + return (TempDescriptor) primitiveparams.get(i); + } + static class Position { + boolean inStruct; + int position; + Position(boolean inStruct, int position) { + this.inStruct=inStruct; + this.position=position; } + } } diff --git a/Robust/src/IR/Flat/TempDescriptor.java b/Robust/src/IR/Flat/TempDescriptor.java index 39bb16e0..d5eb728a 100644 --- a/Robust/src/IR/Flat/TempDescriptor.java +++ b/Robust/src/IR/Flat/TempDescriptor.java @@ -2,81 +2,81 @@ package IR.Flat; import IR.*; public class TempDescriptor extends Descriptor { - static int currentid=0; - int id; - // String safename; - TypeDescriptor type; - TagDescriptor tag; - - public TempDescriptor(String name) { - super(name); - id=currentid++; - } - - public TempDescriptor(String name, TypeDescriptor td) { - this(name); - type=td; - } - - public TempDescriptor(String name, ClassDescriptor cd) { - this(name); - type=new TypeDescriptor(cd); - } - - public TempDescriptor(String name, TypeDescriptor type, TagDescriptor td) { - this(name); - this.type=type; - tag=td; - } - - public TempDescriptor createNew() { - if (tag==null) - return new TempDescriptor(name+"_"+currentid, type); - else - return new TempDescriptor(name+"_"+currentid, type, tag); - } - - public static TempDescriptor tempFactory() { - return new TempDescriptor("temp_"+currentid); - } - - public static TempDescriptor tempFactory(String name) { - return new TempDescriptor(name+currentid); - } - - public static TempDescriptor tempFactory(String name, TypeDescriptor td) { - return new TempDescriptor(name+currentid,td); - } - - public static TempDescriptor tempFactory(String name, TypeDescriptor type, TagDescriptor tag) { - return new TempDescriptor(name+currentid,type,tag); - } - - public static TempDescriptor paramtempFactory(String name, TypeDescriptor td) { - return new TempDescriptor(name,td); - } - - public static TempDescriptor paramtempFactory(String name, TypeDescriptor tagtype, TagDescriptor tag) { - return new TempDescriptor(name, tagtype, tag); - } - - public String toString() { - return safename; - } - - public void setType(TypeDescriptor td) { - type=td; - } - - public TypeDescriptor getType() { - return type; - } - - public TagDescriptor getTag() { - return tag; - } - - public void setTag(TagDescriptor tag) { - this.tag=tag; - } + static int currentid=0; + int id; + // String safename; + TypeDescriptor type; + TagDescriptor tag; + + public TempDescriptor(String name) { + super(name); + id=currentid++; + } + + public TempDescriptor(String name, TypeDescriptor td) { + this(name); + type=td; + } + + public TempDescriptor(String name, ClassDescriptor cd) { + this(name); + type=new TypeDescriptor(cd); + } + + public TempDescriptor(String name, TypeDescriptor type, TagDescriptor td) { + this(name); + this.type=type; + tag=td; + } + + public TempDescriptor createNew() { + if (tag==null) + return new TempDescriptor(name+"_"+currentid, type); + else + return new TempDescriptor(name+"_"+currentid, type, tag); + } + + public static TempDescriptor tempFactory() { + return new TempDescriptor("temp_"+currentid); + } + + public static TempDescriptor tempFactory(String name) { + return new TempDescriptor(name+currentid); + } + + public static TempDescriptor tempFactory(String name, TypeDescriptor td) { + return new TempDescriptor(name+currentid,td); + } + + public static TempDescriptor tempFactory(String name, TypeDescriptor type, TagDescriptor tag) { + return new TempDescriptor(name+currentid,type,tag); + } + + public static TempDescriptor paramtempFactory(String name, TypeDescriptor td) { + return new TempDescriptor(name,td); + } + + public static TempDescriptor paramtempFactory(String name, TypeDescriptor tagtype, TagDescriptor tag) { + return new TempDescriptor(name, tagtype, tag); + } + + public String toString() { + return safename; + } + + public void setType(TypeDescriptor td) { + type=td; + } + + public TypeDescriptor getType() { + return type; + } + + public TagDescriptor getTag() { + return tag; + } + + public void setTag(TagDescriptor tag) { + this.tag=tag; + } } diff --git a/Robust/src/IR/Flat/TempFlagPair.java b/Robust/src/IR/Flat/TempFlagPair.java index 21915d2c..90d9f7b9 100644 --- a/Robust/src/IR/Flat/TempFlagPair.java +++ b/Robust/src/IR/Flat/TempFlagPair.java @@ -2,36 +2,36 @@ package IR.Flat; import IR.FlagDescriptor; public class TempFlagPair { - FlagDescriptor fd; - TempDescriptor td; + FlagDescriptor fd; + TempDescriptor td; - public TempFlagPair(TempDescriptor td, FlagDescriptor fd) { - this.fd=fd; - this.td=td; - } - public int hashCode() { - if (fd!=null) - return fd.hashCode()^td.hashCode(); - else - return td.hashCode(); - } + public TempFlagPair(TempDescriptor td, FlagDescriptor fd) { + this.fd=fd; + this.td=td; + } + public int hashCode() { + if (fd!=null) + return fd.hashCode()^td.hashCode(); + else + return td.hashCode(); + } - public TempDescriptor getTemp() { - return td; - } + public TempDescriptor getTemp() { + return td; + } - public FlagDescriptor getFlag() { - return fd; - } + public FlagDescriptor getFlag() { + return fd; + } - public boolean equals(Object o) { - if (!(o instanceof TempFlagPair)) - return false; - TempFlagPair tfp=(TempFlagPair)o; - return (tfp.fd==fd)&&(tfp.td==td); - } + public boolean equals(Object o) { + if (!(o instanceof TempFlagPair)) + return false; + TempFlagPair tfp=(TempFlagPair)o; + return (tfp.fd==fd)&&(tfp.td==td); + } - public String toString() { - return "<"+fd+","+td+">"; - } + public String toString() { + return "<"+fd+","+td+">"; + } } diff --git a/Robust/src/IR/Flat/TempObject.java b/Robust/src/IR/Flat/TempObject.java index f4e95e48..01589158 100644 --- a/Robust/src/IR/Flat/TempObject.java +++ b/Robust/src/IR/Flat/TempObject.java @@ -3,102 +3,102 @@ import IR.*; import java.util.*; public class TempObject { - ParamsObject params; - private Vector pointerparams; - private Vector primitiveparams; - private MethodDescriptor method; - private TaskDescriptor task; - private int tag; - private Hashtable paramtotemp; - private Hashtable temptostore; - private int count; + ParamsObject params; + private Vector pointerparams; + private Vector primitiveparams; + private MethodDescriptor method; + private TaskDescriptor task; + private int tag; + private Hashtable paramtotemp; + private Hashtable temptostore; + private int count; - public TempObject(ParamsObject p, MethodDescriptor md, int tag) { - params=p; - pointerparams=new Vector(); - primitiveparams=new Vector(); - paramtotemp=new Hashtable(); - temptostore=new Hashtable(); - this.method=md; - this.tag=tag; - count=0; - } + public TempObject(ParamsObject p, MethodDescriptor md, int tag) { + params=p; + pointerparams=new Vector(); + primitiveparams=new Vector(); + paramtotemp=new Hashtable(); + temptostore=new Hashtable(); + this.method=md; + this.tag=tag; + count=0; + } - public TempObject(ParamsObject p, TaskDescriptor task, int tag) { - params=p; - pointerparams=new Vector(); - primitiveparams=new Vector(); - paramtotemp=new Hashtable(); - temptostore=new Hashtable(); - this.task=task; - this.tag=tag; - count=0; - } + public TempObject(ParamsObject p, TaskDescriptor task, int tag) { + params=p; + pointerparams=new Vector(); + primitiveparams=new Vector(); + paramtotemp=new Hashtable(); + temptostore=new Hashtable(); + this.task=task; + this.tag=tag; + count=0; + } - public void addPtr(TempDescriptor t) { - if (!params.containsTemp(t)&&!pointerparams.contains(t)) { - Position p=new Position(true, pointerparams.size()); - pointerparams.add(t); - paramtotemp.put(new Integer(count++), t); - temptostore.put(t,p); - } + public void addPtr(TempDescriptor t) { + if (!params.containsTemp(t)&&!pointerparams.contains(t)) { + Position p=new Position(true, pointerparams.size()); + pointerparams.add(t); + paramtotemp.put(new Integer(count++), t); + temptostore.put(t,p); } + } - public void addPrim(TempDescriptor t) { - if (!params.containsTemp(t)&&!primitiveparams.contains(t)) { - Position p=new Position(false, primitiveparams.size()); - primitiveparams.add(t); - paramtotemp.put(new Integer(count++), t); - temptostore.put(t,p); - } + public void addPrim(TempDescriptor t) { + if (!params.containsTemp(t)&&!primitiveparams.contains(t)) { + Position p=new Position(false, primitiveparams.size()); + primitiveparams.add(t); + paramtotemp.put(new Integer(count++), t); + temptostore.put(t,p); } + } - public boolean isLocalPtr(TempDescriptor t) { - if (!params.containsTemp(t)) { - Position p=(Position)temptostore.get(t); - return p.inStruct; - } - return false; + public boolean isLocalPtr(TempDescriptor t) { + if (!params.containsTemp(t)) { + Position p=(Position)temptostore.get(t); + return p.inStruct; } + return false; + } - public boolean isLocalPrim(TempDescriptor t) { - if (!params.containsTemp(t)) { - Position p=(Position)temptostore.get(t); - return !p.inStruct; - } - return false; + public boolean isLocalPrim(TempDescriptor t) { + if (!params.containsTemp(t)) { + Position p=(Position)temptostore.get(t); + return !p.inStruct; } + return false; + } - public boolean isParamPtr(TempDescriptor t) { - return params.isParamPtr(t); - } + public boolean isParamPtr(TempDescriptor t) { + return params.isParamPtr(t); + } - public boolean isParamPrim(TempDescriptor t) { - return params.isParamPrim(t); - } + public boolean isParamPrim(TempDescriptor t) { + return params.isParamPrim(t); + } - int numPointers() { - return pointerparams.size(); - } + int numPointers() { + return pointerparams.size(); + } - TempDescriptor getPointer(int i) { - return (TempDescriptor) pointerparams.get(i); - } + TempDescriptor getPointer(int i) { + return (TempDescriptor) pointerparams.get(i); + } - int numPrimitives() { - return primitiveparams.size(); - } + int numPrimitives() { + return primitiveparams.size(); + } - TempDescriptor getPrimitive(int i) { - return (TempDescriptor) primitiveparams.get(i); - } + TempDescriptor getPrimitive(int i) { + return (TempDescriptor) primitiveparams.get(i); + } - static class Position { - boolean inStruct; - int position; - Position(boolean inStruct, int position) { - this.inStruct=inStruct; - this.position=position; - } + static class Position { + boolean inStruct; + int position; + Position(boolean inStruct, int position) { + this.inStruct=inStruct; + this.position=position; } + } } diff --git a/Robust/src/IR/Flat/TempTagPair.java b/Robust/src/IR/Flat/TempTagPair.java index 2231a000..e4d935d8 100644 --- a/Robust/src/IR/Flat/TempTagPair.java +++ b/Robust/src/IR/Flat/TempTagPair.java @@ -2,47 +2,47 @@ package IR.Flat; import IR.TagDescriptor; public class TempTagPair { - TagDescriptor tagd; - TempDescriptor td; - TempDescriptor tagt; - - public TempTagPair(TempDescriptor td, TagDescriptor tagd, TempDescriptor tagt) { - this.tagd=tagd; - this.tagt=tagt; - this.td=td; - } - public int hashCode() { - return td.hashCode()^tagt.hashCode(); - } - - public TempDescriptor getTemp() { - return td; - } - - public TagDescriptor getTag() { - return tagd; - } - - public TempDescriptor getTagTemp() { - return tagt; - } - - public boolean equals(Object o) { - if (!(o instanceof TempTagPair)) - return false; - TempTagPair ttp=(TempTagPair)o; - if (ttp.tagt==tagt&&ttp.td==td) { - if (ttp.tagd!=null) { - if (!ttp.tagd.equals(tagd)) - throw new Error(); - } else if (tagd!=null) - throw new Error(); - - return true; - } else return false; - } - - public String toString() { - return "<"+td+","+tagd+","+tagt+">"; - } + TagDescriptor tagd; + TempDescriptor td; + TempDescriptor tagt; + + public TempTagPair(TempDescriptor td, TagDescriptor tagd, TempDescriptor tagt) { + this.tagd=tagd; + this.tagt=tagt; + this.td=td; + } + public int hashCode() { + return td.hashCode()^tagt.hashCode(); + } + + public TempDescriptor getTemp() { + return td; + } + + public TagDescriptor getTag() { + return tagd; + } + + public TempDescriptor getTagTemp() { + return tagt; + } + + public boolean equals(Object o) { + if (!(o instanceof TempTagPair)) + return false; + TempTagPair ttp=(TempTagPair)o; + if (ttp.tagt==tagt&&ttp.td==td) { + if (ttp.tagd!=null) { + if (!ttp.tagd.equals(tagd)) + throw new Error(); + } else if (tagd!=null) + throw new Error(); + + return true; + } else return false; + } + + public String toString() { + return "<"+td+","+tagd+","+tagt+">"; + } } diff --git a/Robust/src/IR/MethodDescriptor.java b/Robust/src/IR/MethodDescriptor.java index 6091ea5a..27423619 100644 --- a/Robust/src/IR/MethodDescriptor.java +++ b/Robust/src/IR/MethodDescriptor.java @@ -4,184 +4,184 @@ import IR.Tree.ExpressionNode; import java.util.Vector; /** - * Descriptor + * Descriptor * * represents a symbol in the language (var name, function name, etc). */ public class MethodDescriptor extends Descriptor { - protected Modifiers modifier; - protected TypeDescriptor returntype; - protected String identifier; - protected Vector params; - protected SymbolTable paramtable; - protected ClassDescriptor cd; - protected VarDescriptor thisvd; - protected boolean isglobal; - - public MethodDescriptor(Modifiers m, TypeDescriptor rt, String identifier) { - super(identifier); - this.modifier=m; - this.returntype=rt; - this.identifier=identifier; - this.safename = "___" + name + "___"; - this.uniqueid=count++; - params=new Vector(); - paramtable=new SymbolTable(); - thisvd=null; - } - - public Modifiers getModifiers() { - return modifier; - } - - public boolean matches(MethodDescriptor md) { - /* Check the name */ - if (!identifier.equals(md.identifier)) - return false; - if (numParameters()!=md.numParameters()) - return false; - for(int i=0;i"; - else if (operation==LTE) - return "<="; - else if (operation==GTE) - return ">="; - else if (operation==LEFTSHIFT) - return "<<"; - else if (operation==RIGHTSHIFT) - return ">>"; - else if (operation==URIGHTSHIFT) - return ">>>"; - else if (operation==SUB) - return "-"; - else if (operation==ADD) - return "+"; - else if (operation==MULT) - return "*"; - else if (operation==DIV) - return "/"; - else if (operation==MOD) - return "%"; - else if (operation==UNARYPLUS) - return "unaryplus"; - else if (operation==UNARYMINUS) - return "unaryminus"; - else if (operation==POSTINC) - return "postinc"; - else if (operation==POSTDEC) - return "postdec"; - else if (operation==PREINC) - return "preinc"; - else if (operation==PREDEC) - return "predec"; - else if (operation==ASSIGN) - return "assign"; - else throw new Error(); - } + public static int parseOp(String st) { + if (st.equals("logical_or")) + return LOGIC_OR; + else if (st.equals("logical_and")) + return LOGIC_AND; + else if (st.equals("bitwise_or")) + return BIT_OR; + else if (st.equals("bitwise_xor")) + return BIT_XOR; + else if (st.equals("bitwise_and")) + return BIT_AND; + else if (st.equals("equal")) + return EQUAL; + else if (st.equals("not_equal")) + return NOTEQUAL; + else if (st.equals("comp_lt")) + return LT; + else if (st.equals("comp_gt")) + return GT; + else if (st.equals("comp_lte")) + return LTE; + else if (st.equals("comp_gte")) + return GTE; + else if (st.equals("leftshift")) + return LEFTSHIFT; + else if (st.equals("rightshift")) + return RIGHTSHIFT; + else if (st.equals("urightshift")) + return URIGHTSHIFT; + else if (st.equals("sub")) + return SUB; + else if (st.equals("add")) + return ADD; + else if (st.equals("mult")) + return MULT; + else if (st.equals("div")) + return DIV; + else if (st.equals("mod")) + return MOD; + else if (st.equals("unaryplus")) + return UNARYPLUS; + else if (st.equals("unaryminus")) + return UNARYMINUS; + else if (st.equals("postinc")) + return POSTINC; + else if (st.equals("postdec")) + return POSTDEC; + else if (st.equals("preinc")) + return PREINC; + else if (st.equals("predec")) + return PREDEC; + else if (st.equals("not")) + return LOGIC_NOT; + else if (st.equals("comp")) + return COMP; + else + throw new Error(); + } + + public String toString() { + if (operation==LOGIC_OR) + return "||"; + else if (operation==LOGIC_AND) + return "&&"; + else if (operation==LOGIC_NOT) + return "not"; + else if (operation==COMP) + return "~"; + else if (operation==BIT_OR) + return "|"; + else if (operation==BIT_XOR) + return "^"; + else if (operation==BIT_AND) + return "&"; + else if (operation==EQUAL) + return "=="; + else if (operation==NOTEQUAL) + return "!="; + else if (operation==LT) + return "<"; + else if (operation==GT) + return ">"; + else if (operation==LTE) + return "<="; + else if (operation==GTE) + return ">="; + else if (operation==LEFTSHIFT) + return "<<"; + else if (operation==RIGHTSHIFT) + return ">>"; + else if (operation==URIGHTSHIFT) + return ">>>"; + else if (operation==SUB) + return "-"; + else if (operation==ADD) + return "+"; + else if (operation==MULT) + return "*"; + else if (operation==DIV) + return "/"; + else if (operation==MOD) + return "%"; + else if (operation==UNARYPLUS) + return "unaryplus"; + else if (operation==UNARYMINUS) + return "unaryminus"; + else if (operation==POSTINC) + return "postinc"; + else if (operation==POSTDEC) + return "postdec"; + else if (operation==PREINC) + return "preinc"; + else if (operation==PREDEC) + return "predec"; + else if (operation==ASSIGN) + return "assign"; + else throw new Error(); + } } diff --git a/Robust/src/IR/State.java b/Robust/src/IR/State.java index 07bbae6e..c700c7ff 100644 --- a/Robust/src/IR/State.java +++ b/Robust/src/IR/State.java @@ -6,183 +6,183 @@ import java.util.*; import Analysis.TaskStateAnalysis.*; public class State { - public State() { - this.classes=new SymbolTable(); - this.tasks=new SymbolTable(); - this.treemethodmap=new Hashtable(); - this.flatmethodmap=new Hashtable(); - this.parsetrees=new HashSet(); - this.arraytypes=new HashSet(); - this.arraytonumber=new Hashtable(); - this.tagmap=new Hashtable(); - this.selfloops=new HashSet(); - this.excprefetch=new HashSet(); - } - - public void addParseNode(ParseNode parsetree) { - parsetrees.add(parsetree); - } - - public void storeAnalysisResult(Hashtable>> analysisresults) { - this.analysisresults=analysisresults; - } - - public Hashtable>> getAnalysisResult() { - return analysisresults; - } - - - public void storeOptionalTaskDescriptors(Hashtable> optionaltaskdescriptors){ - this.optionaltaskdescriptors=optionaltaskdescriptors; - } - - public Hashtable> getOptionalTaskDescriptors(){ - return optionaltaskdescriptors; - } - - /** Boolean flag which indicates whether compiler is compiling a task-based - * program. */ - public boolean WEBINTERFACE=false; - public boolean TASK=false; - public boolean DSM=false; - public boolean PREFETCH=false; - public boolean TASKSTATE=false; - public boolean TAGSTATE=false; - public boolean FLATIRGRAPH=false; - public boolean FLATIRGRAPHTASKS=false; - public boolean FLATIRGRAPHUSERMETHODS=false; - public boolean FLATIRGRAPHLIBMETHODS=false; - public boolean MULTICORE=false; - public boolean OWNERSHIP=false; - public boolean OPTIONAL=false; - public boolean RAW=false; - public boolean SCHEDULING=false; - public boolean THREAD=false; - public boolean CONSCHECK=false; - public boolean INSTRUCTIONFAILURE=false; - public static double TRUEPROB=0.8; - public static boolean PRINTFLAT=false; - public int CORENUM = 1; - public String structfile; - public String main; - - public HashSet selfloops; - public HashSet excprefetch; - public SymbolTable classes; - public SymbolTable tasks; - public Set parsetrees; - public Hashtable treemethodmap; - public Hashtable flatmethodmap; - private HashSet arraytypes; - public Hashtable arraytonumber; - private int numclasses=0; - private int numtasks=0; - private int arraycount=0; - - - private Hashtable> optionaltaskdescriptors; - private Hashtable>> analysisresults; - - private Hashtable tagmap; - private int numtags=0; - - public void addArrayType(TypeDescriptor td) { - if (!arraytypes.contains(td)) { - arraytypes.add(td); - arraytonumber.put(td,new Integer(arraycount++)); - } - } - - public Iterator getArrayIterator() { - return arraytypes.iterator(); - } - - public int getTagId(TagDescriptor tag) { - if (tagmap.containsKey(tag)) { - return ((Integer) tagmap.get(tag)).intValue(); - } else { - tagmap.put(tag, new Integer(numtags)); - return numtags++; - } - } - - public int getArrayNumber(TypeDescriptor td) { - return ((Integer)arraytonumber.get(td)).intValue(); - } - - public int numArrays() { - return arraytypes.size(); - } - - public static TypeDescriptor getTypeDescriptor(int t) { - TypeDescriptor td=new TypeDescriptor(t); - return td; - } - - public static TypeDescriptor getTypeDescriptor(NameDescriptor n) { - TypeDescriptor td=new TypeDescriptor(n); - return td; - } + public State() { + this.classes=new SymbolTable(); + this.tasks=new SymbolTable(); + this.treemethodmap=new Hashtable(); + this.flatmethodmap=new Hashtable(); + this.parsetrees=new HashSet(); + this.arraytypes=new HashSet(); + this.arraytonumber=new Hashtable(); + this.tagmap=new Hashtable(); + this.selfloops=new HashSet(); + this.excprefetch=new HashSet(); + } + + public void addParseNode(ParseNode parsetree) { + parsetrees.add(parsetree); + } + + public void storeAnalysisResult(Hashtable>> analysisresults) { + this.analysisresults=analysisresults; + } + + public Hashtable>> getAnalysisResult() { + return analysisresults; + } + + + public void storeOptionalTaskDescriptors(Hashtable> optionaltaskdescriptors) { + this.optionaltaskdescriptors=optionaltaskdescriptors; + } + + public Hashtable> getOptionalTaskDescriptors() { + return optionaltaskdescriptors; + } + + /** Boolean flag which indicates whether compiler is compiling a task-based + * program. */ + public boolean WEBINTERFACE=false; + public boolean TASK=false; + public boolean DSM=false; + public boolean PREFETCH=false; + public boolean TASKSTATE=false; + public boolean TAGSTATE=false; + public boolean FLATIRGRAPH=false; + public boolean FLATIRGRAPHTASKS=false; + public boolean FLATIRGRAPHUSERMETHODS=false; + public boolean FLATIRGRAPHLIBMETHODS=false; + public boolean MULTICORE=false; + public boolean OWNERSHIP=false; + public boolean OPTIONAL=false; + public boolean RAW=false; + public boolean SCHEDULING=false; + public boolean THREAD=false; + public boolean CONSCHECK=false; + public boolean INSTRUCTIONFAILURE=false; + public static double TRUEPROB=0.8; + public static boolean PRINTFLAT=false; + public int CORENUM = 1; + public String structfile; + public String main; + + public HashSet selfloops; + public HashSet excprefetch; + public SymbolTable classes; + public SymbolTable tasks; + public Set parsetrees; + public Hashtable treemethodmap; + public Hashtable flatmethodmap; + private HashSet arraytypes; + public Hashtable arraytonumber; + private int numclasses=0; + private int numtasks=0; + private int arraycount=0; + + + private Hashtable> optionaltaskdescriptors; + private Hashtable>> analysisresults; + + private Hashtable tagmap; + private int numtags=0; + + public void addArrayType(TypeDescriptor td) { + if (!arraytypes.contains(td)) { + arraytypes.add(td); + arraytonumber.put(td,new Integer(arraycount++)); + } + } + + public Iterator getArrayIterator() { + return arraytypes.iterator(); + } + + public int getTagId(TagDescriptor tag) { + if (tagmap.containsKey(tag)) { + return ((Integer) tagmap.get(tag)).intValue(); + } else { + tagmap.put(tag, new Integer(numtags)); + return numtags++; + } + } + + public int getArrayNumber(TypeDescriptor td) { + return ((Integer)arraytonumber.get(td)).intValue(); + } + + public int numArrays() { + return arraytypes.size(); + } + + public static TypeDescriptor getTypeDescriptor(int t) { + TypeDescriptor td=new TypeDescriptor(t); + return td; + } + + public static TypeDescriptor getTypeDescriptor(NameDescriptor n) { + TypeDescriptor td=new TypeDescriptor(n); + return td; + } + + public void addClass(ClassDescriptor tdn) { + if (classes.contains(tdn.getSymbol())) + throw new Error("Class "+tdn.getSymbol()+" defined twice"); + classes.add(tdn); + numclasses++; + } + + public int numClasses() { + return numclasses; + } + + public BlockNode getMethodBody(MethodDescriptor md) { + return (BlockNode)treemethodmap.get(md); + } + + public BlockNode getMethodBody(TaskDescriptor td) { + return (BlockNode)treemethodmap.get(td); + } + + public SymbolTable getClassSymbolTable() { + return classes; + } + + public SymbolTable getTaskSymbolTable() { + return tasks; + } + + /** Returns Flat IR representation of MethodDescriptor md. */ + + public FlatMethod getMethodFlat(MethodDescriptor md) { + return (FlatMethod)flatmethodmap.get(md); + } + + /** Returns Flat IR representation of TaskDescriptor td. */ + + public FlatMethod getMethodFlat(TaskDescriptor td) { + return (FlatMethod)flatmethodmap.get(td); + } + + public void addTreeCode(MethodDescriptor md, BlockNode bn) { + treemethodmap.put(md,bn); + } + + public void addTreeCode(TaskDescriptor td, BlockNode bn) { + treemethodmap.put(td,bn); + } + + public void addFlatCode(MethodDescriptor md, FlatMethod bn) { + flatmethodmap.put(md,bn); + } - public void addClass(ClassDescriptor tdn) { - if (classes.contains(tdn.getSymbol())) - throw new Error("Class "+tdn.getSymbol()+" defined twice"); - classes.add(tdn); - numclasses++; - } - - public int numClasses() { - return numclasses; - } - - public BlockNode getMethodBody(MethodDescriptor md) { - return (BlockNode)treemethodmap.get(md); - } - - public BlockNode getMethodBody(TaskDescriptor td) { - return (BlockNode)treemethodmap.get(td); - } - - public SymbolTable getClassSymbolTable() { - return classes; - } - - public SymbolTable getTaskSymbolTable() { - return tasks; - } - - /** Returns Flat IR representation of MethodDescriptor md. */ - - public FlatMethod getMethodFlat(MethodDescriptor md) { - return (FlatMethod)flatmethodmap.get(md); - } - - /** Returns Flat IR representation of TaskDescriptor td. */ - - public FlatMethod getMethodFlat(TaskDescriptor td) { - return (FlatMethod)flatmethodmap.get(td); - } + public void addFlatCode(TaskDescriptor td, FlatMethod bn) { + flatmethodmap.put(td,bn); + } - public void addTreeCode(MethodDescriptor md, BlockNode bn) { - treemethodmap.put(md,bn); - } - - public void addTreeCode(TaskDescriptor td, BlockNode bn) { - treemethodmap.put(td,bn); - } - - public void addFlatCode(MethodDescriptor md, FlatMethod bn) { - flatmethodmap.put(md,bn); - } - - public void addFlatCode(TaskDescriptor td, FlatMethod bn) { - flatmethodmap.put(td,bn); - } - - public void addTask(TaskDescriptor td) { - if (tasks.contains(td.getSymbol())) - throw new Error("Task "+td.getSymbol()+" defined twice"); - tasks.add(td); - numtasks++; - } + public void addTask(TaskDescriptor td) { + if (tasks.contains(td.getSymbol())) + throw new Error("Task "+td.getSymbol()+" defined twice"); + tasks.add(td); + numtasks++; + } } diff --git a/Robust/src/IR/SymbolTable.java b/Robust/src/IR/SymbolTable.java index 2c8bd2c5..ed1d1337 100644 --- a/Robust/src/IR/SymbolTable.java +++ b/Robust/src/IR/SymbolTable.java @@ -4,122 +4,122 @@ import java.util.*; public class SymbolTable { - private Hashtable table; - private SymbolTable parent; - private HashSet valueset; - - public SymbolTable() { - table = new Hashtable(); - valueset = new HashSet(); - this.parent = null; - } - - public SymbolTable(SymbolTable parent) { - table = new Hashtable(); - this.parent = parent; - } - - public void add(Descriptor d) { - add(d.getSymbol(), d); - } - - public void add(String name, Descriptor d) { - if (!table.containsKey(name)) - table.put(name, new HashSet()); - HashSet hs=(HashSet)table.get(name); - hs.add(d); - valueset.add(d); - } - - public Set getSet(String name) { - return getPSet(name); - } - - private HashSet getPSet(String name) { - HashSet hs=null; - if (parent!=null) - hs=parent.getPSet(name); - else - hs=new HashSet(); - if (table.containsKey(name)) { - hs.addAll((HashSet)table.get(name)); - } - return hs; - } - - public Set getSetFromSameScope(String name) { - return getPSetFromSameScope(name); - } - - private HashSet getPSetFromSameScope(String name) { - if (table.containsKey(name)) { - HashSet hs=(HashSet)table.get(name); - return hs; - } else - return new HashSet(); - } - - public Descriptor get(String name) { - Descriptor d = getFromSameScope(name); - if (d == null && parent != null) { - return parent.get(name); - } else { - return d; - } - } - - public Descriptor getFromSameScope(String name) { - if (table.containsKey(name)) { - HashSet hs=(HashSet) table.get(name); - return (Descriptor) hs.iterator().next(); - } else - return null; - - } - - public Enumeration getNames() { - return table.keys(); - } - - public Iterator getNamesIterator() { - return table.keySet().iterator(); - } - - public Set getValueSet() { - return valueset; - } - - public Iterator getDescriptorsIterator() { - return getValueSet().iterator(); - } - - public Set getAllValueSet() { - HashSet hs=null; - if (parent!=null) - hs=(HashSet) parent.getAllValueSet(); - else - hs=new HashSet(); - hs.addAll(valueset); - return hs; - } - - public Iterator getAllDescriptorsIterator() { - return getAllValueSet().iterator(); - } - - public boolean contains(String name) { - return (get(name) != null); - } - - public SymbolTable getParent() { - return parent; - } - - public void setParent(SymbolTable parent) { - this.parent = parent; - } - - public String toString() { - return "ST: " + table.toString(); - } + private Hashtable table; + private SymbolTable parent; + private HashSet valueset; + + public SymbolTable() { + table = new Hashtable(); + valueset = new HashSet(); + this.parent = null; + } + + public SymbolTable(SymbolTable parent) { + table = new Hashtable(); + this.parent = parent; + } + + public void add(Descriptor d) { + add(d.getSymbol(), d); + } + + public void add(String name, Descriptor d) { + if (!table.containsKey(name)) + table.put(name, new HashSet()); + HashSet hs=(HashSet)table.get(name); + hs.add(d); + valueset.add(d); + } + + public Set getSet(String name) { + return getPSet(name); + } + + private HashSet getPSet(String name) { + HashSet hs=null; + if (parent!=null) + hs=parent.getPSet(name); + else + hs=new HashSet(); + if (table.containsKey(name)) { + hs.addAll((HashSet)table.get(name)); + } + return hs; + } + + public Set getSetFromSameScope(String name) { + return getPSetFromSameScope(name); + } + + private HashSet getPSetFromSameScope(String name) { + if (table.containsKey(name)) { + HashSet hs=(HashSet)table.get(name); + return hs; + } else + return new HashSet(); + } + + public Descriptor get(String name) { + Descriptor d = getFromSameScope(name); + if (d == null && parent != null) { + return parent.get(name); + } else { + return d; + } + } + + public Descriptor getFromSameScope(String name) { + if (table.containsKey(name)) { + HashSet hs=(HashSet) table.get(name); + return (Descriptor) hs.iterator().next(); + } else + return null; + + } + + public Enumeration getNames() { + return table.keys(); + } + + public Iterator getNamesIterator() { + return table.keySet().iterator(); + } + + public Set getValueSet() { + return valueset; + } + + public Iterator getDescriptorsIterator() { + return getValueSet().iterator(); + } + + public Set getAllValueSet() { + HashSet hs=null; + if (parent!=null) + hs=(HashSet) parent.getAllValueSet(); + else + hs=new HashSet(); + hs.addAll(valueset); + return hs; + } + + public Iterator getAllDescriptorsIterator() { + return getAllValueSet().iterator(); + } + + public boolean contains(String name) { + return (get(name) != null); + } + + public SymbolTable getParent() { + return parent; + } + + public void setParent(SymbolTable parent) { + this.parent = parent; + } + + public String toString() { + return "ST: " + table.toString(); + } } diff --git a/Robust/src/IR/TagDescriptor.java b/Robust/src/IR/TagDescriptor.java index 48a2e70a..bb961d52 100644 --- a/Robust/src/IR/TagDescriptor.java +++ b/Robust/src/IR/TagDescriptor.java @@ -1,29 +1,29 @@ package IR; /** - * Descriptor + * Descriptor * * represents a symbol in the language (var name, function name, etc). */ public class TagDescriptor extends Descriptor { - public TagDescriptor(String identifier) { - super(identifier); - } + public TagDescriptor(String identifier) { + super(identifier); + } - public boolean equals(Object o) { - if (o instanceof TagDescriptor) { - TagDescriptor t=(TagDescriptor) o; - return getSymbol().equals(t.getSymbol()); - } else return false; - } - - public int hashCode() { - return getSymbol().hashCode(); - } + public boolean equals(Object o) { + if (o instanceof TagDescriptor) { + TagDescriptor t=(TagDescriptor) o; + return getSymbol().equals(t.getSymbol()); + } else return false; + } - public String toString() { - return "Tag "+getSymbol(); - } + public int hashCode() { + return getSymbol().hashCode(); + } + + public String toString() { + return "Tag "+getSymbol(); + } } diff --git a/Robust/src/IR/TagVarDescriptor.java b/Robust/src/IR/TagVarDescriptor.java index a478f447..4cca52da 100644 --- a/Robust/src/IR/TagVarDescriptor.java +++ b/Robust/src/IR/TagVarDescriptor.java @@ -1,56 +1,56 @@ package IR; /** - * Descriptor + * Descriptor * * represents a symbol in the language (var name, function name, etc). */ public class TagVarDescriptor extends Descriptor { - protected TagDescriptor td; - protected String identifier; - - public TagVarDescriptor(TagDescriptor t, String identifier) { - super(identifier); - this.td=t; - this.identifier=identifier; - this.safename = "___" + name + "___"; - this.uniqueid=count++; - } - - public String getName() { - return identifier; - } - - public TagDescriptor getTag() { - return td; - } - - public TypeDescriptor getType() { - return new TypeDescriptor(TypeDescriptor.TAG); - } - - /* public boolean equals(Object o) { - if (o instanceof TagVarDescriptor) { - TagVarDescriptor tvd=(TagVarDescriptor)o; - if (tvd.identifier.equals(identifier)) { - if (tvd.td!=null) { - if (!tvd.td.equals(td)) - throw new Error(); - } else if (td!=null) - throw new Error(); - return true; - } - } - return false; - } - - public int hashCode() { - return identifier.hashCode(); - }*/ - - public String toString() { - return td.toString()+" "+identifier; - } + protected TagDescriptor td; + protected String identifier; + + public TagVarDescriptor(TagDescriptor t, String identifier) { + super(identifier); + this.td=t; + this.identifier=identifier; + this.safename = "___" + name + "___"; + this.uniqueid=count++; + } + + public String getName() { + return identifier; + } + + public TagDescriptor getTag() { + return td; + } + + public TypeDescriptor getType() { + return new TypeDescriptor(TypeDescriptor.TAG); + } + + /* public boolean equals(Object o) { + if (o instanceof TagVarDescriptor) { + TagVarDescriptor tvd=(TagVarDescriptor)o; + if (tvd.identifier.equals(identifier)) { + if (tvd.td!=null) { + if (!tvd.td.equals(td)) + throw new Error(); + } else if (td!=null) + throw new Error(); + return true; + } + } + return false; + } + + public int hashCode() { + return identifier.hashCode(); + }*/ + + public String toString() { + return td.toString()+" "+identifier; + } } diff --git a/Robust/src/IR/TaskDescriptor.java b/Robust/src/IR/TaskDescriptor.java index 166f2284..a7152d91 100644 --- a/Robust/src/IR/TaskDescriptor.java +++ b/Robust/src/IR/TaskDescriptor.java @@ -8,106 +8,106 @@ import java.util.Iterator; import IR.Tree.Modifiers; /** - * Descriptor + * Descriptor * */ public class TaskDescriptor extends Descriptor { - protected Hashtable flagstable; - protected Hashtable tagstable; - protected Vector vfe; - protected String identifier; - protected Vector params; - protected Vector optionals; - protected SymbolTable paramtable; - - public TaskDescriptor(String identifier) { - super(identifier); - this.identifier=identifier; - this.uniqueid=count++; - flagstable=new Hashtable(); - tagstable=new Hashtable(); //BUGFIX - added initialization here - params=new Vector(); - optionals = new Vector(); - paramtable=new SymbolTable(); + protected Hashtable flagstable; + protected Hashtable tagstable; + protected Vector vfe; + protected String identifier; + protected Vector params; + protected Vector optionals; + protected SymbolTable paramtable; + + public TaskDescriptor(String identifier) { + super(identifier); + this.identifier=identifier; + this.uniqueid=count++; + flagstable=new Hashtable(); + tagstable=new Hashtable(); //BUGFIX - added initialization here + params=new Vector(); + optionals = new Vector(); + paramtable=new SymbolTable(); + } + + public void addFlagEffects(Vector vfe) { + this.vfe=vfe; + } + + public Vector getFlagEffects() { + return vfe; + } + + public SymbolTable getParameterTable() { + return paramtable; + } + + public void addParameter(TypeDescriptor type, String paramname, FlagExpressionNode fen, TagExpressionList tel, boolean isoptional) { + if (paramname.equals("this")) + throw new Error("Can't have parameter named this"); + VarDescriptor vd=new VarDescriptor(type, paramname); + params.add(vd); + if (isoptional) optionals.add(vd); + if (fen!=null) + flagstable.put(vd, fen); + if (tel!=null) { //BUGFIX - added null check here...test with any bristlecone program + tagstable.put(vd, tel); + for(int i=0; i0) - str+=","; - str+=getVar(i)+" : "; - str+=getArg(i).printNode(0); - } - return str+")"; - } + String specname; + Vector args; + Vector vars; + + public ConstraintCheck(String specname) { + this.specname=specname; + args=new Vector(); + vars=new Vector(); + } + + public void addVariable(String var) { + vars.add(var); + } + + public void addArgument(ExpressionNode en) { + args.add(en); + } + + public String getSpec() { + return specname; + } + + public int numArgs() { + return args.size(); + } + + public ExpressionNode getArg(int i) { + return (ExpressionNode) args.get(i); + } + + public String getVar(int i) { + return (String) vars.get(i); + } + + public String printNode(int indent) { + String str="assert("+specname+"("; + for(int i=0; i0) + str+=","; + str+=getVar(i)+" : "; + str+=getArg(i).printNode(0); + } + return str+")"; + } } diff --git a/Robust/src/IR/Tree/CreateObjectNode.java b/Robust/src/IR/Tree/CreateObjectNode.java index 5f19aae2..7c8230d4 100644 --- a/Robust/src/IR/Tree/CreateObjectNode.java +++ b/Robust/src/IR/Tree/CreateObjectNode.java @@ -4,78 +4,78 @@ import IR.TypeDescriptor; import IR.MethodDescriptor; public class CreateObjectNode extends ExpressionNode { - TypeDescriptor td; - Vector argumentlist; - MethodDescriptor md; - FlagEffects fe; - boolean isglobal; + TypeDescriptor td; + Vector argumentlist; + MethodDescriptor md; + FlagEffects fe; + boolean isglobal; - public CreateObjectNode(TypeDescriptor type, boolean isglobal) { - td=type; - argumentlist=new Vector(); - this.isglobal=isglobal; - } + public CreateObjectNode(TypeDescriptor type, boolean isglobal) { + td=type; + argumentlist=new Vector(); + this.isglobal=isglobal; + } - public boolean isGlobal() { - return isglobal; - } + public boolean isGlobal() { + return isglobal; + } - public void addFlagEffects(FlagEffects fe) { - this.fe=fe; - } + public void addFlagEffects(FlagEffects fe) { + this.fe=fe; + } - public FlagEffects getFlagEffects() { - return fe; - } + public FlagEffects getFlagEffects() { + return fe; + } - public void addArgument(ExpressionNode en) { - argumentlist.add(en); - } + public void addArgument(ExpressionNode en) { + argumentlist.add(en); + } - public void setConstructor(MethodDescriptor md) { - this.md=md; - } + public void setConstructor(MethodDescriptor md) { + this.md=md; + } - public MethodDescriptor getConstructor() { - return md; - } + public MethodDescriptor getConstructor() { + return md; + } - public TypeDescriptor getType() { - return td; - } + public TypeDescriptor getType() { + return td; + } - public int numArgs() { - return argumentlist.size(); - } + public int numArgs() { + return argumentlist.size(); + } - public ExpressionNode getArg(int i) { - return (ExpressionNode) argumentlist.get(i); - } + public ExpressionNode getArg(int i) { + return (ExpressionNode) argumentlist.get(i); + } - public String printNode(int indent) { - String st; - boolean isarray=td.isArray(); + public String printNode(int indent) { + String st; + boolean isarray=td.isArray(); + if (isarray) + st="new "+td.toString()+"["; + else + st="new "+td.toString()+"("; + for(int i=0; i= 0) { + return line; + } else { + if (parent != null) { + return parent.getLine(); + } else { + return 0; + } + } + } + + public void setParent(ParseNode parent) { + this.parent = parent; + } + + public ParseNode getParent() { + return parent; + } + + public ParseNode insertChild(ParseNode child) { + if (child == null) { + throw new NullPointerException("Can't add null node to parse tree"); + } + + children.insertElementAt(child, 0); + child.setParent(this); + return child; + } + + public ParseNode insertChild(String newlabel) { + ParseNode child = new ParseNode(newlabel, -1); + return insertChild(child); + } + + public ParseNode addChild(ParseNode child) { + + if (child == null) { + throw new NullPointerException("Can't add null node to parse tree: "+getLabel()); + } + + children.addElement(child); + child.setParent(this); + return child; + } + + public ParseNode addChild(String newlabel) { + + ParseNode child = new ParseNode(newlabel, -1); + children.addElement(child); + child.setParent(this); + return child; + } + + public ParseNode addChild(String newlabel, int line) { + ParseNode child = new ParseNode(newlabel, line); + children.addElement(child); + child.setParent(this); + return child; + } + + public ParseNodeVector getChildren() { + return children; + } + + public ParseNode getChild(String label) { + int i; + ParseNode p; + + for (i = 0; i < children.size(); i++) { + p = children.elementAt(i); + if (p.getLabel().equals(label)) { + return p; + } + } + + return null; + } + + public ParseNode getRoot() { + return (parent == null) ? this : parent.getRoot(); + } + + public String getTerminal() { + ParseNode pn = children.elementAt(0); + if (pn == null) { + return null; + } else { + return pn.getLabel(); + } + } - /* - public void setSymbolTable(SymbolTable st) { - if (st == null) { - throw new IRException("symboltable is null!"); - } - this.st = st; - } - - public SymbolTable getSymbolTable() { - if (st == null) { - if (parent != null) { - return parent.getSymbolTable(); - } else { - return null; - } - } else { - return st; - } - } - */ - - public int getLine() { - if (line >= 0) { - return line; - } else { - if (parent != null) { - return parent.getLine(); - } else { - return 0; - } - } - } - - public void setParent( ParseNode parent ) { - this.parent = parent; - } - - public ParseNode getParent() { - return parent; - } - - public ParseNode insertChild(ParseNode child) { - if (child == null) { - throw new NullPointerException("Can't add null node to parse tree"); - } + public ParseNode getFirstChild() { + return children.elementAt(0); + } - children.insertElementAt(child, 0); - child.setParent(this); - return child; - } + public ParseNodeVector getChildren(String label) { + int i; + ParseNodeVector v = new ParseNodeVector(); - public ParseNode insertChild(String newlabel) { - ParseNode child = new ParseNode(newlabel, -1); - return insertChild(child); + for (i = 0; i < children.size(); i++) { + ParseNode pn = children.elementAt(i); + if (pn.getLabel().equals(label)) + v.addElement(pn); } - public ParseNode addChild( ParseNode child ) { + return v; + } - if (child == null) { - throw new NullPointerException("Can't add null node to parse tree: "+getLabel()); - } + public String getNodeName() { + return label + " - " + getLine(); + } - children.addElement (child); - child.setParent(this); - return child; - } + public int getNeighborCount() { + return children.size(); + } - public ParseNode addChild( String newlabel ) { - - ParseNode child = new ParseNode(newlabel, -1); - children.addElement(child); - child.setParent(this); - return child; - } + public Object getNeighbor(int index) { + return children.elementAt(index); + } - public ParseNode addChild (String newlabel, int line) { - ParseNode child = new ParseNode(newlabel, line); - children.addElement(child); - child.setParent(this); - return child; - } - - public ParseNodeVector getChildren() { - return children; - } + public String doIndent(int indent) { - public ParseNode getChild (String label) { - int i; - ParseNode p; + String output = new String(); + for(int i=0; i\n"; + } else { + output += doIndent(indent) + "<" + label + ">\n"; + indent += 2; - public String getTerminal () { - ParseNode pn = children.elementAt(0); - if (pn == null) { - return null; - } else { - return pn.getLabel(); + if (recursive) { + for (int i = 0; i < children.size(); i++) { + Walkable w = (Walkable)children.elementAt(i); + output += w.PPrint(indent, true); } - } - - public ParseNode getFirstChild() { - return children.elementAt(0); - } - - public ParseNodeVector getChildren(String label) { - int i; - ParseNodeVector v = new ParseNodeVector(); - - for (i = 0; i < children.size(); i++) { - ParseNode pn = children.elementAt(i); - if (pn.getLabel().equals(label)) - v.addElement(pn); + } else { + for (int i = 0; i < children.size(); i++) { + Walkable w = (Walkable)children.elementAt(i); + output += doIndent(indent) + "<" + w.getNodeName() + "/>\n"; } + } - return v; - } - - public String getNodeName() { - return label + " - " + getLine(); - } - - public int getNeighborCount() { - return children.size(); - } - - public Object getNeighbor(int index) { - return children.elementAt(index); + indent -= 2; + output += doIndent(indent) + "\n"; } - public String doIndent(int indent) { - - String output = new String(); - for(int i=0;i\n"; - } else { - output += doIndent(indent) + "<" + label + ">\n"; - indent += 2; - - if (recursive) { - 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"; - } - } - - indent -= 2; - output += doIndent(indent) + "\n"; - } - - return output; - } + return output; + } } diff --git a/Robust/src/IR/Tree/ParseNodeDOTVisitor.java b/Robust/src/IR/Tree/ParseNodeDOTVisitor.java index e9907284..cbd2b653 100644 --- a/Robust/src/IR/Tree/ParseNodeDOTVisitor.java +++ b/Robust/src/IR/Tree/ParseNodeDOTVisitor.java @@ -1,71 +1,71 @@ /* - - Class: ParseNodeDOTVisitor - Author: Dan Roy - Purpose: Traverses a ParseNode tree and generates a DOT file that represents the parse + + Class: ParseNodeDOTVisitor + Author: Dan Roy + Purpose: Traverses a ParseNode tree and generates a DOT file that represents the parse tree. -*/ + */ package IR.Tree; import java.util.*; public class ParseNodeDOTVisitor { - - java.io.PrintWriter output; - int tokennumber; - int color; - private ParseNodeDOTVisitor(java.io.OutputStream output) { - tokennumber = 0; - color = 0; - this.output = new java.io.PrintWriter(output, true); - } + java.io.PrintWriter output; + int tokennumber; + int color; - private String getNewID(String name) { - tokennumber = tokennumber + 1; - return new String (name+tokennumber); - } + private ParseNodeDOTVisitor(java.io.OutputStream output) { + tokennumber = 0; + color = 0; + this.output = new java.io.PrintWriter(output, true); + } - public static void visit(java.io.OutputStream output, ParseNode root) { - ParseNodeDOTVisitor visitor = new ParseNodeDOTVisitor(output); - visitor.make(root); - } - - private void make(ParseNode root) { - output.println("digraph dotvisitor {"); - output.println("\tsize=\"7, 10\";"); - traverse(root, getNewID("root")); - output.println("}\n"); - } + private String getNewID(String name) { + tokennumber = tokennumber + 1; + return new String(name+tokennumber); + } + + public static void visit(java.io.OutputStream output, ParseNode root) { + ParseNodeDOTVisitor visitor = new ParseNodeDOTVisitor(output); + visitor.make(root); + } + + private void make(ParseNode root) { + output.println("digraph dotvisitor {"); + output.println("\tsize=\"7, 10\";"); + traverse(root, getNewID("root")); + output.println("}\n"); + } - private String newColor() { + private String newColor() { - if (color == 0) { - color++; - return new String("red"); - } else if (color == 1) { - color++; - return new String("green"); - } else { - color = 0; - return new String("blue"); - } + if (color == 0) { + color++; + return new String("red"); + } else if (color == 1) { + color++; + return new String("green"); + } else { + color = 0; + return new String("blue"); } + } - private void traverse(ParseNode node, String nodeid) { - output.println("\t" + nodeid + " [label=\"" + node.getLabel() + "\",shape=box];"); - ParseNodeVector children = node.getChildren(); - for (int i = 0; i < children.size(); i++) { - ParseNode child = children.elementAt(i); - String childid = getNewID("node"); - output.println("\t" + nodeid + " -> " + childid + ";"); - if (child.getLabel()=="rule") { - output.println("\tnode [color=" + newColor() + "];"); - } - traverse(child, childid); - } + private void traverse(ParseNode node, String nodeid) { + output.println("\t" + nodeid + " [label=\"" + node.getLabel() + "\",shape=box];"); + ParseNodeVector children = node.getChildren(); + for (int i = 0; i < children.size(); i++) { + ParseNode child = children.elementAt(i); + String childid = getNewID("node"); + output.println("\t" + nodeid + " -> " + childid + ";"); + if (child.getLabel()=="rule") { + output.println("\tnode [color=" + newColor() + "];"); + } + traverse(child, childid); } + } } diff --git a/Robust/src/IR/Tree/ParseNodeVector.java b/Robust/src/IR/Tree/ParseNodeVector.java index efedcf66..112392be 100644 --- a/Robust/src/IR/Tree/ParseNodeVector.java +++ b/Robust/src/IR/Tree/ParseNodeVector.java @@ -3,25 +3,25 @@ package IR.Tree; import java.util.Vector; public class ParseNodeVector { - private Vector v; + private Vector v; - public ParseNodeVector() { - v = new Vector(); - } + public ParseNodeVector() { + v = new Vector(); + } - public void addElement(ParseNode pn) { - v.addElement(pn); - } + public void addElement(ParseNode pn) { + v.addElement(pn); + } - public void insertElementAt(ParseNode pn, int n) { - v.insertElementAt(pn, n); - } + public void insertElementAt(ParseNode pn, int n) { + v.insertElementAt(pn, n); + } - public ParseNode elementAt(int i) { - return (ParseNode) v.elementAt(i); - } + public ParseNode elementAt(int i) { + return (ParseNode) v.elementAt(i); + } - public int size() { - return v.size(); - } + public int size() { + return v.size(); + } } diff --git a/Robust/src/IR/Tree/ReturnNode.java b/Robust/src/IR/Tree/ReturnNode.java index 780a4cbd..6697d1d5 100644 --- a/Robust/src/IR/Tree/ReturnNode.java +++ b/Robust/src/IR/Tree/ReturnNode.java @@ -1,27 +1,27 @@ package IR.Tree; public class ReturnNode extends BlockStatementNode { - ExpressionNode en; + ExpressionNode en; - public ReturnNode() { - en=null; - } + public ReturnNode() { + en=null; + } - public ReturnNode(ExpressionNode en) { - this.en=en; - } + public ReturnNode(ExpressionNode en) { + this.en=en; + } - public ExpressionNode getReturnExpression() { - return en; - } + public ExpressionNode getReturnExpression() { + return en; + } - public String printNode(int indent) { - if (en==null) - return "return"; - else - return "return "+en.printNode(indent); - } - public int kind() { - return Kind.ReturnNode; - } + public String printNode(int indent) { + if (en==null) + return "return"; + else + return "return "+en.printNode(indent); + } + public int kind() { + return Kind.ReturnNode; + } } diff --git a/Robust/src/IR/Tree/SemanticCheck.java b/Robust/src/IR/Tree/SemanticCheck.java index a12084d5..32577cc5 100644 --- a/Robust/src/IR/Tree/SemanticCheck.java +++ b/Robust/src/IR/Tree/SemanticCheck.java @@ -4,975 +4,989 @@ import java.util.*; import IR.*; public class SemanticCheck { - State state; - TypeUtil typeutil; - - public SemanticCheck(State state, TypeUtil tu) { - this.state=state; - this.typeutil=tu; - } - - public void semanticCheck() { - SymbolTable classtable=state.getClassSymbolTable(); - Iterator it=classtable.getDescriptorsIterator(); - // Do descriptors first - while(it.hasNext()) { - ClassDescriptor cd=(ClassDescriptor)it.next(); - //System.out.println("Checking class: "+cd); - //Set superclass link up - if (cd.getSuper()!=null) { - cd.setSuper(typeutil.getClass(cd.getSuper())); - // Link together Field, Method, and Flag tables so classes - // inherit these from their superclasses - cd.getFieldTable().setParent(cd.getSuperDesc().getFieldTable()); - cd.getMethodTable().setParent(cd.getSuperDesc().getMethodTable()); - cd.getFlagTable().setParent(cd.getSuperDesc().getFlagTable()); - } - - /* Check to see that fields are well typed */ - for(Iterator field_it=cd.getFields();field_it.hasNext();) { - FieldDescriptor fd=(FieldDescriptor)field_it.next(); - //System.out.println("Checking field: "+fd); - checkField(cd,fd); - } - - for(Iterator method_it=cd.getMethods();method_it.hasNext();) { - MethodDescriptor md=(MethodDescriptor)method_it.next(); - checkMethod(cd,md); - } + State state; + TypeUtil typeutil; + + public SemanticCheck(State state, TypeUtil tu) { + this.state=state; + this.typeutil=tu; + } + + public void semanticCheck() { + SymbolTable classtable=state.getClassSymbolTable(); + Iterator it=classtable.getDescriptorsIterator(); + // Do descriptors first + while(it.hasNext()) { + ClassDescriptor cd=(ClassDescriptor)it.next(); + //System.out.println("Checking class: "+cd); + //Set superclass link up + if (cd.getSuper()!=null) { + cd.setSuper(typeutil.getClass(cd.getSuper())); + // Link together Field, Method, and Flag tables so classes + // inherit these from their superclasses + cd.getFieldTable().setParent(cd.getSuperDesc().getFieldTable()); + cd.getMethodTable().setParent(cd.getSuperDesc().getMethodTable()); + cd.getFlagTable().setParent(cd.getSuperDesc().getFlagTable()); + } + + /* Check to see that fields are well typed */ + for(Iterator field_it=cd.getFields(); field_it.hasNext();) { + FieldDescriptor fd=(FieldDescriptor)field_it.next(); + //System.out.println("Checking field: "+fd); + checkField(cd,fd); + } + + for(Iterator method_it=cd.getMethods(); method_it.hasNext();) { + MethodDescriptor md=(MethodDescriptor)method_it.next(); + checkMethod(cd,md); + } + } + + it=classtable.getDescriptorsIterator(); + // Do descriptors first + while(it.hasNext()) { + ClassDescriptor cd=(ClassDescriptor)it.next(); + for(Iterator method_it=cd.getMethods(); method_it.hasNext();) { + MethodDescriptor md=(MethodDescriptor)method_it.next(); + checkMethodBody(cd,md); + } + } + + for(Iterator task_it=state.getTaskSymbolTable().getDescriptorsIterator(); task_it.hasNext();) { + TaskDescriptor td=(TaskDescriptor)task_it.next(); + checkTask(td); + + } + } + + public void checkTypeDescriptor(TypeDescriptor td) { + if (td.isPrimitive()) + return; /* Done */ + else if (td.isClass()) { + String name=td.toString(); + ClassDescriptor field_cd=(ClassDescriptor)state.getClassSymbolTable().get(name); + if (field_cd==null) + throw new Error("Undefined class "+name); + td.setClassDescriptor(field_cd); + return; + } else if (td.isTag()) + return; + else + throw new Error(); + } + + public void checkField(ClassDescriptor cd, FieldDescriptor fd) { + checkTypeDescriptor(fd.getType()); + } + + public void checkConstraintCheck(TaskDescriptor td, SymbolTable nametable, Vector ccs) { + if (ccs==null) + return; /* No constraint checks to check */ + for(int i=0; i=temps.size()) - temps.setSize(i+1); - temps.set(i, tmp); - } - - public TempDescriptor getTemp(int i) { - return (TempDescriptor) temps.get(i); - } - - public String getName(int i) { - return (String) names.get(i); - } - - public String getType(int i) { - return (String) types.get(i); - } + Vector names; + Vector types; + Vector temps; + + public TagExpressionList() { + names=new Vector(); + types=new Vector(); + temps=new Vector(); + } + + public void addTag(String type, String name) { + types.add(type); + names.add(name); + } + + public int numTags() { + return names.size(); + } + + public void setTemp(int i, TempDescriptor tmp) { + if (i>=temps.size()) + temps.setSize(i+1); + temps.set(i, tmp); + } + + public TempDescriptor getTemp(int i) { + return (TempDescriptor) temps.get(i); + } + + public String getName(int i) { + return (String) names.get(i); + } + + public String getType(int i) { + return (String) types.get(i); + } } diff --git a/Robust/src/IR/Tree/TaskExitNode.java b/Robust/src/IR/Tree/TaskExitNode.java index c26e0fc2..084b63bb 100644 --- a/Robust/src/IR/Tree/TaskExitNode.java +++ b/Robust/src/IR/Tree/TaskExitNode.java @@ -2,26 +2,26 @@ package IR.Tree; import java.util.Vector; public class TaskExitNode extends BlockStatementNode { - Vector vfe; - Vector ccs; - public TaskExitNode(Vector vfe, Vector ccs) { - this.vfe=vfe; - this.ccs=ccs; - } + Vector vfe; + Vector ccs; + public TaskExitNode(Vector vfe, Vector ccs) { + this.vfe=vfe; + this.ccs=ccs; + } - public String printNode(int indent) { - return "taskexit"; - } + public String printNode(int indent) { + return "taskexit"; + } - public Vector getFlagEffects() { - return vfe; - } + public Vector getFlagEffects() { + return vfe; + } - public Vector getChecks() { - return ccs; - } + public Vector getChecks() { + return ccs; + } - public int kind() { - return Kind.TaskExitNode; - } + public int kind() { + return Kind.TaskExitNode; + } } diff --git a/Robust/src/IR/Tree/TreeNode.java b/Robust/src/IR/Tree/TreeNode.java index 35233fc3..578cc6c6 100644 --- a/Robust/src/IR/Tree/TreeNode.java +++ b/Robust/src/IR/Tree/TreeNode.java @@ -1,18 +1,18 @@ package IR.Tree; public class TreeNode { - public static final int INDENT=2; + public static final int INDENT=2; - public String printNode(int indent) { - return null; - } - public static String printSpace(int x) { - String sp=""; - for(int i=0;i0) - return false; - if (!getSymbol().equals(TypeUtil.StringClass)) - return false; - return true; - } + public boolean isString() { + if (type!=CLASS) + return false; + if (arraycount>0) + return false; + if (!getSymbol().equals(TypeUtil.StringClass)) + return false; + return true; + } - public int hashCode() { - int hashcode=type^arraycount; - if (type==CLASS) - hashcode^=getSymbol().hashCode(); - return hashcode; - } + public int hashCode() { + int hashcode=type^arraycount; + if (type==CLASS) + hashcode^=getSymbol().hashCode(); + return hashcode; + } - public TypeDescriptor makeArray(State state) { - TypeDescriptor td=new TypeDescriptor(getSymbol()); - td.arraycount=arraycount+1; - td.type=type; - td.class_desc=class_desc; - state.addArrayType(td); - return td; - } + public TypeDescriptor makeArray(State state) { + TypeDescriptor td=new TypeDescriptor(getSymbol()); + td.arraycount=arraycount+1; + td.type=type; + td.class_desc=class_desc; + state.addArrayType(td); + return td; + } - public boolean isArray() { - return (arraycount>0); - } + public boolean isArray() { + return (arraycount>0); + } - public int getArrayCount() { - return arraycount; - } + public int getArrayCount() { + return arraycount; + } - public TypeDescriptor dereference() { - TypeDescriptor td=new TypeDescriptor(getSymbol()); - if (arraycount==0) - throw new Error(); - td.arraycount=arraycount-1; - td.type=type; - td.class_desc=class_desc; - return td; - } + public TypeDescriptor dereference() { + TypeDescriptor td=new TypeDescriptor(getSymbol()); + if (arraycount==0) + throw new Error(); + td.arraycount=arraycount-1; + td.type=type; + td.class_desc=class_desc; + return td; + } - public String getSafeSymbol() { - if (isArray()) - return IR.Flat.BuildCode.arraytype; - else if (isClass()) - return class_desc.getSafeSymbol(); - else if (isByte()) - return "char"; - else if (isChar()) - return "short"; - else if (isShort()) - return "short"; - else if (isInt()) - return "int"; - else if (isBoolean()) //Booleans are ints in C - return "int"; - else if (isLong()) - return "long long"; - else if (isVoid()) - return "void"; - else if (isDouble()) - return "double"; - else if (isFloat()) - return "float"; - else throw new Error("Error Type: "+type); - } + public String getSafeSymbol() { + if (isArray()) + return IR.Flat.BuildCode.arraytype; + else if (isClass()) + return class_desc.getSafeSymbol(); + else if (isByte()) + return "char"; + else if (isChar()) + return "short"; + else if (isShort()) + return "short"; + else if (isInt()) + return "int"; + else if (isBoolean()) //Booleans are ints in C + return "int"; + else if (isLong()) + return "long long"; + else if (isVoid()) + return "void"; + else if (isDouble()) + return "double"; + else if (isFloat()) + return "float"; + else throw new Error("Error Type: "+type); + } - public String getRepairSymbol() { - if (isArray()) - return IR.Flat.BuildCode.arraytype; - else if (isClass()) - return class_desc.getSymbol(); - else if (isByte()) - return "byte"; - else if (isChar()) - return "short"; - else if (isShort()) - return "short"; - else if (isInt()) - return "int"; - else if (isBoolean()) //Booleans are ints in C - return "int"; - else if (isLong()) - return "long long"; - else if (isVoid()) - return "void"; - else if (isDouble()) - return "double"; - else if (isFloat()) - return "float"; - else throw new Error("Error Type: "+type); - } + public String getRepairSymbol() { + if (isArray()) + return IR.Flat.BuildCode.arraytype; + else if (isClass()) + return class_desc.getSymbol(); + else if (isByte()) + return "byte"; + else if (isChar()) + return "short"; + else if (isShort()) + return "short"; + else if (isInt()) + return "int"; + else if (isBoolean()) //Booleans are ints in C + return "int"; + else if (isLong()) + return "long long"; + else if (isVoid()) + return "void"; + else if (isDouble()) + return "double"; + else if (isFloat()) + return "float"; + else throw new Error("Error Type: "+type); + } - public String getSafeDescriptor() { - //Can't safely use [ in C - if (isArray()) - return "_AR_"+this.dereference().getSafeDescriptor(); - else if (isClass()) - return class_desc.getSafeDescriptor(); - else if (isByte()) - return "B"; - else if (isChar()) - return "C"; - else if (isShort()) - return "S"; - else if (isBoolean()) - return "Z"; - else if (isInt()) - return "I"; - else if (isLong()) - return "J"; - else if (isDouble()) - return "D"; - else if (isFloat()) - return "F"; - else if (isTag()) - return "T"; - else throw new Error(); - } + public String getSafeDescriptor() { + //Can't safely use [ in C + if (isArray()) + return "_AR_"+this.dereference().getSafeDescriptor(); + else if (isClass()) + return class_desc.getSafeDescriptor(); + else if (isByte()) + return "B"; + else if (isChar()) + return "C"; + else if (isShort()) + return "S"; + else if (isBoolean()) + return "Z"; + else if (isInt()) + return "I"; + else if (isLong()) + return "J"; + else if (isDouble()) + return "D"; + else if (isFloat()) + return "F"; + else if (isTag()) + return "T"; + else throw new Error(); + } - public boolean isNumber() { - return (isIntegerType()||isFloat()||isDouble()); - } + public boolean isNumber() { + return (isIntegerType()||isFloat()||isDouble()); + } - public boolean isByte() { - return type==BYTE; - } - public boolean isNull() { - return type==NULL; - } - public boolean isShort() { - return type==SHORT; - } - public boolean isInt() { - return type==INT; - } - public boolean isLong() { - return type==LONG; - } - public boolean isChar() { - return type==CHAR; - } - public boolean isBoolean() { - return type==BOOLEAN; - } - public boolean isFloat() { - return type==FLOAT; - } - public boolean isDouble() { - return type==DOUBLE; - } - public boolean isVoid() { - return type==VOID; - } + public boolean isByte() { + return type==BYTE; + } + public boolean isNull() { + return type==NULL; + } + public boolean isShort() { + return type==SHORT; + } + public boolean isInt() { + return type==INT; + } + public boolean isLong() { + return type==LONG; + } + public boolean isChar() { + return type==CHAR; + } + public boolean isBoolean() { + return type==BOOLEAN; + } + public boolean isFloat() { + return type==FLOAT; + } + public boolean isDouble() { + return type==DOUBLE; + } + public boolean isVoid() { + return type==VOID; + } - public boolean isPtr() { - return (isClass()||isNull()||isTag()||isArray()); - } + public boolean isPtr() { + return (isClass()||isNull()||isTag()||isArray()); + } - public boolean isIntegerType() { - return (isInt()||isLong()||isShort()||isChar()||isByte()); - } + public boolean isIntegerType() { + return (isInt()||isLong()||isShort()||isChar()||isByte()); + } - public void setClassDescriptor(ClassDescriptor cd) { - class_desc=cd; - } - - public boolean isPrimitive() { - return ((type>=BYTE)&&(type<=DOUBLE)); - } + public void setClassDescriptor(ClassDescriptor cd) { + class_desc=cd; + } - public boolean isClass() { - return type==CLASS; - } - - public boolean isTag() { - return type==TAG; - } + public boolean isPrimitive() { + return ((type>=BYTE)&&(type<=DOUBLE)); + } - public TypeDescriptor(NameDescriptor name) { - super(name.toString()); - this.type=CLASS; - this.class_desc=null; - this.arraycount=0; - } + public boolean isClass() { + return type==CLASS; + } - public TypeDescriptor(String st) { - super(st); - this.type=CLASS; - this.class_desc=null; - this.arraycount=0; - } + public boolean isTag() { + return type==TAG; + } - public ClassDescriptor getClassDesc() { - return class_desc; - } + public TypeDescriptor(NameDescriptor name) { + super(name.toString()); + this.type=CLASS; + this.class_desc=null; + this.arraycount=0; + } - public TypeDescriptor(ClassDescriptor cd) { - super(cd.getSymbol()); - this.type=CLASS; - this.class_desc=cd; - this.arraycount=0; - } + public TypeDescriptor(String st) { + super(st); + this.type=CLASS; + this.class_desc=null; + this.arraycount=0; + } - public TypeDescriptor(int t) { - super(decodeInt(t)); - this.type=t; - this.arraycount=0; - } + public ClassDescriptor getClassDesc() { + return class_desc; + } - public String toString() { - if (type==CLASS) { - return name; - } else - return decodeInt(type); - } + public TypeDescriptor(ClassDescriptor cd) { + super(cd.getSymbol()); + this.type=CLASS; + this.class_desc=cd; + this.arraycount=0; + } - public String toPrettyString() { - if (type==CLASS) { - String str=name; - for(int i=0;i methodnumber; - Hashtable classmethodcount; - Hashtable localitynumber; + State state; + LocalityAnalysis locality; + Hashtable methodnumber; + Hashtable classmethodcount; + Hashtable localitynumber; - public int getMethodNumber(MethodDescriptor md) { - return methodnumber.get(md).intValue(); - } - - public int getMethodCount(ClassDescriptor md) { - return classmethodcount.get(md).intValue(); - } - - public int getLocalityNumber(LocalityBinding lb) { - return localitynumber.get(lb).intValue(); - } + public int getMethodNumber(MethodDescriptor md) { + return methodnumber.get(md).intValue(); + } - public Virtual(State state, LocalityAnalysis locality) { - this.state=state; - this.locality=locality; - classmethodcount=new Hashtable(); - if (state.DSM) - localitynumber=new Hashtable(); - else - methodnumber=new Hashtable(); - doAnalysis(); - } + public int getMethodCount(ClassDescriptor md) { + return classmethodcount.get(md).intValue(); + } - private void doAnalysis() { - Iterator classit=state.getClassSymbolTable().getDescriptorsIterator(); - while(classit.hasNext()) { - ClassDescriptor cd=(ClassDescriptor)classit.next(); - if (state.DSM) - numberLocality(cd); - else - numberMethods(cd); - } - } + public int getLocalityNumber(LocalityBinding lb) { + return localitynumber.get(lb).intValue(); + } - private int numberLocality(ClassDescriptor cd) { - if (classmethodcount.containsKey(cd)) - return classmethodcount.get(cd).intValue(); - ClassDescriptor superdesc=cd.getSuperDesc(); - int start=0; - if (superdesc!=null) - start=numberLocality(superdesc); + public Virtual(State state, LocalityAnalysis locality) { + this.state=state; + this.locality=locality; + classmethodcount=new Hashtable(); + if (state.DSM) + localitynumber=new Hashtable(); + else + methodnumber=new Hashtable(); + doAnalysis(); + } - 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++)); - } - } - classmethodcount.put(cd, new Integer(start)); - return start; + private void doAnalysis() { + Iterator classit=state.getClassSymbolTable().getDescriptorsIterator(); + while(classit.hasNext()) { + ClassDescriptor cd=(ClassDescriptor)classit.next(); + if (state.DSM) + numberLocality(cd); + else + numberMethods(cd); } + } + + private int numberLocality(ClassDescriptor cd) { + if (classmethodcount.containsKey(cd)) + return classmethodcount.get(cd).intValue(); + ClassDescriptor superdesc=cd.getSuperDesc(); + int start=0; + if (superdesc!=null) + start=numberLocality(superdesc); - private int numberMethods(ClassDescriptor cd) { - if (classmethodcount.containsKey(cd)) - return classmethodcount.get(cd).intValue(); - ClassDescriptor superdesc=cd.getSuperDesc(); - int start=0; - if (superdesc!=null) - start=numberMethods(superdesc); - for(Iterator it=cd.getMethods();it.hasNext();) { - MethodDescriptor md=(MethodDescriptor)it.next(); - 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)) { - int num=((Integer)methodnumber.get(matchmd)).intValue(); - methodnumber.put(md, new Integer(num)); - foundmatch=true; - break; - } + 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; + } } - if (!foundmatch) - methodnumber.put(md, new Integer(start++)); - } else { - methodnumber.put(md, new Integer(start++)); + break; } + } + if (!foundmatch) + localitynumber.put(lb, new Integer(start++)); + } else { + localitynumber.put(lb, new Integer(start++)); + } + } + classmethodcount.put(cd, new Integer(start)); + return start; + } + + private int numberMethods(ClassDescriptor cd) { + if (classmethodcount.containsKey(cd)) + return classmethodcount.get(cd).intValue(); + ClassDescriptor superdesc=cd.getSuperDesc(); + int start=0; + if (superdesc!=null) + start=numberMethods(superdesc); + for(Iterator it=cd.getMethods(); it.hasNext();) { + MethodDescriptor md=(MethodDescriptor)it.next(); + 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)) { + int num=((Integer)methodnumber.get(matchmd)).intValue(); + methodnumber.put(md, new Integer(num)); + foundmatch=true; + break; + } } - classmethodcount.put(cd, new Integer(start)); - return start; + if (!foundmatch) + methodnumber.put(md, new Integer(start++)); + } else { + methodnumber.put(md, new Integer(start++)); + } } + classmethodcount.put(cd, new Integer(start)); + return start; + } } diff --git a/Robust/src/Interface/HTTPHeader.java b/Robust/src/Interface/HTTPHeader.java index b862c5fc..d3e753fe 100644 --- a/Robust/src/Interface/HTTPHeader.java +++ b/Robust/src/Interface/HTTPHeader.java @@ -15,7 +15,7 @@ import java.io.*; // Purpose: constructs the header to be returned by the server //**************************************************************************** -public class HTTPHeader{ +public class HTTPHeader { // make a hashtable of return codes to messages static private HashStrings rc = new HashStrings(); @@ -51,32 +51,32 @@ public class HTTPHeader{ ct.put("class", "application/octet-stream"); ct.put("ps", "application/postscript"); } - + //************************************************************************* // Constructor: send_header(int, String, int) // Purpose: Send an HTTP header //************************************************************************* static public void send_header(OutputStream out, int returnCode, - String filename, long fileLength){ - String contentType = getContentTypeFor(filename); - String returnString = (String) rc.get(String.valueOf(returnCode)); - String header; - - header = "HTTP/1.0 " + returnCode + " " + returnString + "\n" + - "Date: " + "1/1/01" + "\n" + // date - "Expires: 1/1/00\n"+ - "Allow: GET\n" + // allowed methods - "MIME-Version: 1.0\n" + // mime version - "Server : SpinWeb Custom HTTP Server\n" + // server type - "Content-Type: " + contentType + "\n" + // type - "Content-Length: "+ fileLength + "\n\n"; // length - try{ - out.write(header.getBytes()); - } - catch(IOException e){ - e.printStackTrace(); // do nothing! - } + String filename, long fileLength) { + String contentType = getContentTypeFor(filename); + String returnString = (String) rc.get(String.valueOf(returnCode)); + String header; + + header = "HTTP/1.0 " + returnCode + " " + returnString + "\n" + + "Date: " + "1/1/01" + "\n" + // date + "Expires: 1/1/00\n"+ + "Allow: GET\n" + // allowed methods + "MIME-Version: 1.0\n" + // mime version + "Server : SpinWeb Custom HTTP Server\n" + // server type + "Content-Type: " + contentType + "\n" + // type + "Content-Length: "+ fileLength + "\n\n"; // length + try{ + out.write(header.getBytes()); + } + catch(IOException e){ + e.printStackTrace(); // do nothing! + } } //************************************************************************* @@ -85,26 +85,25 @@ public class HTTPHeader{ // file suffix. It removes any anchors (#) in case the string is // a URL and then operates on the name without path. //************************************************************************* - - static private String getContentTypeFor(String filename) - { + + static private String getContentTypeFor(String filename) { int position = filename.lastIndexOf('#'); if (position != -1) filename = filename.substring(0, position - 1); - + File f = new File(filename); String name = f.getName(); // name w/o directory position = name.lastIndexOf('.'); - + String contentType; if (position == -1) // if no extension, txt is assigned by default - contentType = "txt"; - else - contentType = name.substring(position + 1); - + contentType = "txt"; + else + contentType = name.substring(position + 1); + return (String) ct.get(contentType); - } + } } diff --git a/Robust/src/Interface/HTTPResponse.java b/Robust/src/Interface/HTTPResponse.java index 74c532fe..00ce3a16 100644 --- a/Robust/src/Interface/HTTPResponse.java +++ b/Robust/src/Interface/HTTPResponse.java @@ -1,7 +1,7 @@ package Interface; -public class HTTPResponse{ - public int returnCode; - public long sentBytes; +public class HTTPResponse { + public int returnCode; + public long sentBytes; } diff --git a/Robust/src/Interface/HTTPServices.java b/Robust/src/Interface/HTTPServices.java index 30804fb8..5a2b19a5 100644 --- a/Robust/src/Interface/HTTPServices.java +++ b/Robust/src/Interface/HTTPServices.java @@ -3,80 +3,80 @@ import java.net.*; import java.io.*; import java.util.*; -public class HTTPServices{ - - static private String webRoot = "."; - - static private FileInputStream get_reader(String fileName,HTTPResponse resp) throws IOException{ -// if(fileName.equals("/daytime")){ -// String date_str = (new Date()).toString(); -// resp.sentBytes = date_str.length(); -// return -// new StringReader(date_str); -// } - - if(fileName.equals("/viewlog")) - fileName = LogFile.log_file_name; - else - fileName = webRoot + fileName; - - File f = new File(fileName); - resp.sentBytes = f.length(); - return new FileInputStream(f); - } +public class HTTPServices { - public static void GET_handler(String fileName, OutputStream out, HTTPResponse resp){ - - FileInputStream reader = null; - byte buffer[]; - int size; + static private String webRoot = "."; - if((reader = HEAD_handler_int(fileName,out,resp)) == null) return; + static private FileInputStream get_reader(String fileName,HTTPResponse resp) throws IOException { +// if(fileName.equals("/daytime")){ +// String date_str = (new Date()).toString(); +// resp.sentBytes = date_str.length(); +// return +// new StringReader(date_str); +// } - buffer = new byte[1024]; + if(fileName.equals("/viewlog")) + fileName = LogFile.log_file_name; + else + fileName = webRoot + fileName; - try{ - while((size = reader.read(buffer,0,buffer.length)) != -1) - out.write(buffer,0,size); - reader.close(); - } - catch(IOException e){ - e.printStackTrace(); - resp.returnCode = 501; // error during transmision - } + File f = new File(fileName); + resp.sentBytes = f.length(); + return new FileInputStream(f); + } - } + public static void GET_handler(String fileName, OutputStream out, HTTPResponse resp) { + + FileInputStream reader = null; + byte buffer[]; + int size; + + if((reader = HEAD_handler_int(fileName,out,resp)) == null) return; - public static void POST_handler(String fileName, OutputStream out, HTTPResponse resp){ - GET_handler(fileName,out, resp); + buffer = new byte[1024]; + + try{ + while((size = reader.read(buffer,0,buffer.length)) != -1) + out.write(buffer,0,size); + reader.close(); + } + catch(IOException e){ + e.printStackTrace(); + resp.returnCode = 501; // error during transmision } - static private FileInputStream HEAD_handler_int(String fileName, - OutputStream out,HTTPResponse resp){ - FileInputStream reader = null; - - try{ - reader = get_reader(fileName, resp); - resp.returnCode = 200; - } - catch(IOException e){ - resp.returnCode = 404; // file not found - } - - if(resp.returnCode == 200) - HTTPHeader.send_header(out, resp.returnCode, fileName, resp.sentBytes); - else{ - HTTPHeader.send_header(out, resp.returnCode, fileName, 0); - return null; - } - - return reader; + } + + public static void POST_handler(String fileName, OutputStream out, HTTPResponse resp) { + GET_handler(fileName,out, resp); + } + + static private FileInputStream HEAD_handler_int(String fileName, + OutputStream out,HTTPResponse resp) { + FileInputStream reader = null; + + try{ + reader = get_reader(fileName, resp); + resp.returnCode = 200; + } + catch(IOException e){ + resp.returnCode = 404; // file not found } - - public static void HEAD_handler(String fileName, - OutputStream out, HTTPResponse resp){ - HEAD_handler_int(fileName,out,resp); + if(resp.returnCode == 200) + HTTPHeader.send_header(out, resp.returnCode, fileName, resp.sentBytes); + else{ + HTTPHeader.send_header(out, resp.returnCode, fileName, 0); + return null; } + + return reader; + } + + + public static void HEAD_handler(String fileName, + OutputStream out, HTTPResponse resp) { + HEAD_handler_int(fileName,out,resp); + } } diff --git a/Robust/src/Interface/HashStrings.java b/Robust/src/Interface/HashStrings.java index 67065786..0f3bd801 100644 --- a/Robust/src/Interface/HashStrings.java +++ b/Robust/src/Interface/HashStrings.java @@ -1,39 +1,43 @@ package Interface; class HashStrings { - Pair p[]; // entries in the hash table - int f; // number of full entries - public HashStrings() { p = new Pair[38]; f = 0; } + Pair p[]; // entries in the hash table + int f; // number of full entries + public HashStrings() { + p = new Pair[38]; f = 0; + } - public void put(String key, String value) { - int n = p.length; - if (f == n-1) return; // cheese -- a diary product - int i = key.hashCode() % n; - while (p[i] != null) { - if (key.equals(p[i].key)) { - p[i] = new Pair(key, value); - return; - } - i = (i+1) % n; - } + public void put(String key, String value) { + int n = p.length; + if (f == n-1) return; // cheese -- a diary product + int i = key.hashCode() % n; + while (p[i] != null) { + if (key.equals(p[i].key)) { p[i] = new Pair(key, value); - f = f + 1; + return; + } + i = (i+1) % n; } + p[i] = new Pair(key, value); + f = f + 1; + } - public String get(String key) { - int n = p.length; - int i = key.hashCode() % n; - while (p[i] != null) { - if (key.equals(p[i].key)) - return p[i].value; - i = (i+1) % n; - } - return null; + public String get(String key) { + int n = p.length; + int i = key.hashCode() % n; + while (p[i] != null) { + if (key.equals(p[i].key)) + return p[i].value; + i = (i+1) % n; } + return null; + } } class Pair { - String key, value; - Pair (String key, String value) { this.key = key; this.value = value; } + String key, value; + Pair (String key, String value) { + this.key = key; this.value = value; + } } diff --git a/Robust/src/Interface/IdentityRelation.java b/Robust/src/Interface/IdentityRelation.java index 04d28883..efe41fda 100644 --- a/Robust/src/Interface/IdentityRelation.java +++ b/Robust/src/Interface/IdentityRelation.java @@ -1,27 +1,27 @@ package Interface; -class IdentityRelation{ - String fieldname1; - String fieldname2; +class IdentityRelation { + String fieldname1; + String fieldname2; - public IdentityRelation(String fieldname1,String fieldname2) { - this.fieldname1=fieldname1; - this.fieldname2=fieldname2; - } - public String toString() { - return fieldname1+"."+fieldname2; - } + public IdentityRelation(String fieldname1,String fieldname2) { + this.fieldname1=fieldname1; + this.fieldname2=fieldname2; + } + public String toString() { + return fieldname1+"."+fieldname2; + } - public int hashCode() { - return fieldname1.hashCode()^fieldname2.hashCode(); - } + public int hashCode() { + return fieldname1.hashCode()^fieldname2.hashCode(); + } - public boolean equals(Object obj) { - if (obj instanceof IdentityRelation) { - IdentityRelation ir=(IdentityRelation) obj; - if (fieldname1.equals(ir.fieldname1)&& - fieldname2.equals(ir.fieldname2)) - return true; - } - return false; + public boolean equals(Object obj) { + if (obj instanceof IdentityRelation) { + IdentityRelation ir=(IdentityRelation) obj; + if (fieldname1.equals(ir.fieldname1)&& + fieldname2.equals(ir.fieldname2)) + return true; } + return false; + } } diff --git a/Robust/src/Interface/Imap.java b/Robust/src/Interface/Imap.java index 33763fd8..a20f43c2 100644 --- a/Robust/src/Interface/Imap.java +++ b/Robust/src/Interface/Imap.java @@ -4,145 +4,147 @@ import java.io.*; import java.util.*; class Imap { - private Rectangle[] rectangles; - private Point[] points; - long THRESHOLD=400; + private Rectangle[] rectangles; + private Point[] points; + long THRESHOLD=400; - public Imap(String filename) { - FileReader fr=null; - try { - fr=new FileReader(filename); - parseFile(fr); - fr.close(); - } catch (IOException e) { - System.out.println(e); - System.exit(-1); - } + public Imap(String filename) { + FileReader fr=null; + try { + fr=new FileReader(filename); + parseFile(fr); + fr.close(); + } catch (IOException e) { + System.out.println(e); + System.exit(-1); } - static class Rectangle { - String label; - int x1,y1,x2,y2; - public Rectangle(String label, int x1,int y1, int x2, int y2) { - this.label=label; - this.x1=x1; - this.y1=y1; - this.x2=x2; - this.y2=y2; - } + } + static class Rectangle { + String label; + int x1,y1,x2,y2; + public Rectangle(String label, int x1,int y1, int x2, int y2) { + this.label=label; + this.x1=x1; + this.y1=y1; + this.x2=x2; + this.y2=y2; } + } - String parseclick(int x,int y) { - System.out.println(x+","+y); - for(int i=0;i=y)&& - (r.x2>=x)&&(r.y2<=y)) - return r.label; - } - long mindistance=Long.MAX_VALUE; - int minindex=-1; - for(int i=0;iTHRESHOLD) - return null; - else - return points[minindex].label; + String parseclick(int x,int y) { + System.out.println(x+","+y); + for(int i=0; i=y)&& + (r.x2>=x)&&(r.y2<=y)) + return r.label; } + long mindistance=Long.MAX_VALUE; + int minindex=-1; + for(int i=0; iTHRESHOLD) + return null; + else + return points[minindex].label; + } - static class Point { - String label; - int x,y; - public Point(String label, int x,int y) { - this.label=label; - this.x=x; - this.y=y; - } + static class Point { + String label; + int x,y; + public Point(String label, int x,int y) { + this.label=label; + this.x=x; + this.y=y; } + } - void parseFile(FileReader fr) { - int firstchar=0; - ArrayList rectangles=new ArrayList(); - ArrayList points=new ArrayList(); - while(true) { - try { - firstchar=fr.read(); - } catch (Exception e) { - e.printStackTrace(); - System.exit(-1); - } - /* EOF?*/ - if (firstchar==-1) - break; - switch(firstchar) { - case'b': - case'#': - 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); - } - 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); - } - break; - } + void parseFile(FileReader fr) { + int firstchar=0; + ArrayList rectangles=new ArrayList(); + ArrayList points=new ArrayList(); + while(true) { + try { + firstchar=fr.read(); + } catch (Exception e) { + e.printStackTrace(); + System.exit(-1); + } + /* EOF?*/ + if (firstchar==-1) + break; + switch(firstchar) { + case 'b': + case '#': + while(firstchar!='\n') { + try { + firstchar=fr.read(); + } catch (IOException e) { + e.printStackTrace(); + System.exit(-1); + } } - this.rectangles=(Rectangle[]) rectangles.toArray(new Rectangle[rectangles.size()]); - this.points=(Point[]) points.toArray(new Point[points.size()]); + 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); + } + 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); + } + break; + } } + this.rectangles=(Rectangle[])rectangles.toArray(new Rectangle[rectangles.size()]); + this.points=(Point[])points.toArray(new Point[points.size()]); + } - String nexttoken(java.io.InputStreamReader isr,boolean commas) { - String string=""; - int c=0; - boolean looped=false; - while(true) { - try { - c=isr.read(); - } catch (IOException e) { - e.printStackTrace(); - System.exit(-1); - } - if ((c==' ')||(c=='\n')||(commas&&c==',')) { - if (!looped) { - looped=true; - continue; - } - return string; - } - string=string+new String(new char[]{(char)c}); - looped=true; + String nexttoken(java.io.InputStreamReader isr,boolean commas) { + String string=""; + int c=0; + boolean looped=false; + while(true) { + try { + c=isr.read(); + } catch (IOException e) { + e.printStackTrace(); + System.exit(-1); + } + if ((c==' ')||(c=='\n')||(commas&&c==',')) { + 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 9cf67269..59c675ce 100644 --- a/Robust/src/Interface/JhttpServer.java +++ b/Robust/src/Interface/JhttpServer.java @@ -9,41 +9,40 @@ package Interface; import java.net.*; import java.io.*; -public class JhttpServer extends Thread{ +public class JhttpServer extends Thread { - private ServerSocket server; - private WebInterface webinterface; + private ServerSocket server; + private WebInterface webinterface; //**************************************************************************** // Constructor: JhttpServer(int) //**************************************************************************** - public JhttpServer(int port, WebInterface webinterface) - { - System.out.println("starting..."); - this.webinterface=webinterface; - try{ - System.out.println("creating the port"); - server = new ServerSocket(port); - } - catch (IOException e){ - System.err.println(e); - System.exit(1); - } + public JhttpServer(int port, WebInterface webinterface) { + System.out.println("starting..."); + this.webinterface=webinterface; + try{ + System.out.println("creating the port"); + server = new ServerSocket(port); } - - private void startWorker(Socket client) throws Exception { - (new JhttpWorker(client,false,webinterface)).start(); + catch (IOException e){ + System.err.println(e); + System.exit(1); } + } + + private void startWorker(Socket client) throws Exception { + (new JhttpWorker(client,false,webinterface)).start(); + } - public void run(){ - // infinite loop - while (true){ - try{ - startWorker(server.accept()); - } - catch (Exception e){ - System.err.println(e); - } - } + public void run() { + // infinite loop + while (true){ + try{ + startWorker(server.accept()); + } + catch (Exception e){ + System.err.println(e); + } } + } } diff --git a/Robust/src/Interface/JhttpWorker.java b/Robust/src/Interface/JhttpWorker.java index 4613422f..c5e3bfc1 100644 --- a/Robust/src/Interface/JhttpWorker.java +++ b/Robust/src/Interface/JhttpWorker.java @@ -15,177 +15,168 @@ import java.util.*; // Purpose: Takes an HTTP request and executes it in a separate thread //**************************************************************************** -public class JhttpWorker extends Thread{ - public String fileName = null; - public String methodType = null; - public String httpVersion = "http/1.0"; - private Socket client; - public int fileLength, returnCode; - private boolean logging; - private WebInterface webinterface; - - public JhttpWorker(Socket client, boolean logging, WebInterface webinterface) { - this.client=client; - this.logging=logging; - this.webinterface=webinterface; - } - - public void run(){ - HTTPResponse resp = new HTTPResponse(); +public class JhttpWorker extends Thread { + public String fileName = null; + public String methodType = null; + public String httpVersion = "http/1.0"; + private Socket client; + public int fileLength, returnCode; + private boolean logging; + private WebInterface webinterface; + + public JhttpWorker(Socket client, boolean logging, WebInterface webinterface) { + this.client=client; + this.logging=logging; + this.webinterface=webinterface; + } - BufferedReader in = null; - OutputStream out = null; + public void run() { + HTTPResponse resp = new HTTPResponse(); - resp.returnCode = 200; - resp.sentBytes = 0; + BufferedReader in = null; + OutputStream out = null; - try { + resp.returnCode = 200; + resp.sentBytes = 0; - in = new BufferedReader( - new InputStreamReader( - client.getInputStream())); + try { - out = client.getOutputStream(); - } - catch(IOException e){ - // I'm not too good at HTTP. Normally, we should put some - // error code here. Anyway, I have assumed that an error - // is equivalent to an unhandled request / method (501) - resp.returnCode = 501; - } + in = new BufferedReader( + new InputStreamReader( + client.getInputStream())); - if(resp.returnCode == 200){ - // call the appropriate hanndler - 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; - case 1: - HTTPServices.HEAD_handler(fileName, out, resp); - break; - case 2: - HTTPServices.POST_handler(fileName, out, resp); - break; - default: - 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(); - } - catch(IOException e){ - ; // do nothing - } - } + out = client.getOutputStream(); + } + catch(IOException e){ + // I'm not too good at HTTP. Normally, we should put some + // error code here. Anyway, I have assumed that an error + // is equivalent to an unhandled request / method (501) + resp.returnCode = 501; + } + + if(resp.returnCode == 200){ + // call the appropriate hanndler + 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; + + case 1: + HTTPServices.HEAD_handler(fileName, out, resp); + break; + + case 2: + HTTPServices.POST_handler(fileName, out, resp); + break; + + default: + resp.returnCode = 501; //error + } - // System.out.println(fileName + " is going to finish"); // debug + try{ + 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 + } } - + + // System.out.println(fileName + " is going to finish"); // debug + } + //***************************************************************************** // Function: method() -// Purpose: Open an InputStream and parse the request made. +// Purpose: Open an InputStream and parse the request made. // Note: Regardless of what method is requested, right now it performs a // GET operation. -// Calls: +// Calls: // Returns: Boolean value for success or failure //***************************************************************************** - private int method(BufferedReader in){ - int ret = -1; + private int method(BufferedReader in) { + int ret = -1; + + try{ + String line; + + // read just the first line + line = in.readLine(); + // 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; + } + } else{ + // System.out.println("Request from browser was empty!"); + return -1; + } - try{ - String line; - - // read just the first line - line = in.readLine(); - // 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; - } - } - else{ - // 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"; - } - } - 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); - } - - // read the http version number - // - right now nothing is done with this information - if (tok.hasMoreTokens()) - { - httpVersion = tok.nextToken(); - } - else - { - 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," "); - - // do processing here - if(!token.hasMoreTokens()) - { - break; - } - } + // get the filename + if (tok.hasMoreTokens()){ + 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); } - catch(Exception e){ - System.err.println(e); - return -1; + + // read the http version number + // - right now nothing is done with this information + if (tok.hasMoreTokens()){ + httpVersion = tok.nextToken(); + } else + { + 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," "); + + // do processing here + if(!token.hasMoreTokens()){ + break; + } } - + } + catch(Exception e){ + System.err.println(e); + return -1; + } + return ret; } } diff --git a/Robust/src/Interface/LogFile.java b/Robust/src/Interface/LogFile.java index 667b5489..b52ea857 100644 --- a/Robust/src/Interface/LogFile.java +++ b/Robust/src/Interface/LogFile.java @@ -26,48 +26,48 @@ import java.net.*; public class LogFile { - static public final String log_file_name = "server.log"; + static public final String log_file_name = "server.log"; - static public String write_log(Socket s, String Method, String URI, - String Protocol, - int ReturnCode, long BytesSent){ + static public String write_log(Socket s, String Method, String URI, + String Protocol, + int ReturnCode, long BytesSent) { - // Socket.toString() calls (indirectly) some Hashtable.get - // method - I tool care of it! + // Socket.toString() calls (indirectly) some Hashtable.get + // method - I tool care of it! - /* - String addr = s.toString(); - String Address = addr.substring(addr.indexOf('/') + 1, - addr.indexOf(',')); - */ + /* + String addr = s.toString(); + String Address = addr.substring(addr.indexOf('/') + 1, + addr.indexOf(',')); + */ - // SimpleDateFormat sdf = - // new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); // RFC 1123 - // sdf.setTimeZone(TimeZone.getTimeZone("GMT")); - // String Date = sdf.format(new Date()); + // SimpleDateFormat sdf = + // new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); // RFC 1123 + // sdf.setTimeZone(TimeZone.getTimeZone("GMT")); + // String Date = sdf.format(new Date()); - String Entry = - /* Address + */ " - - [" + // IP address - "Date" + "] \"" + // date - Method + " " + // get, post, head - URI + " " + // filename - Protocol + "\" " + // http/1.? - ReturnCode + " " + // 200-500 - BytesSent + "\n"; // bytes sent + String Entry = + /* Address + */ " - - [" + // IP address + "Date" + "] \"" + // date + Method + " " + // get, post, head + URI + " " + // filename + Protocol + "\" " + // http/1.? + ReturnCode + " " + // 200-500 + BytesSent + "\n"; // bytes sent - try{ - BufferedWriter out = new BufferedWriter( - new OutputStreamWriter( - new FileOutputStream(log_file_name, true))); - - out.write(Entry,0,Entry.length()); - out.flush(); - out.close(); - } - catch (IOException e){ - System.err.println("Gicu " + e); - } + try{ + BufferedWriter out = new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(log_file_name, true))); - return Entry; + out.write(Entry,0,Entry.length()); + out.flush(); + out.close(); } + catch (IOException e){ + System.err.println("Gicu " + e); + } + + return Entry; + } } diff --git a/Robust/src/Interface/WebInterface.java b/Robust/src/Interface/WebInterface.java index 17b71df4..472e9fa8 100644 --- a/Robust/src/Interface/WebInterface.java +++ b/Robust/src/Interface/WebInterface.java @@ -6,275 +6,275 @@ import java.util.*; import Util.Namer; public class WebInterface { - TaskAnalysis taskanalysis; - TaskGraph taskgraph; - TagAnalysis taganalysis; - State state; - Hashtable flagstatemap; - Hashtable taskgraphmap; - Hashtable sourcenodemap; //to hold the filenames for each of the pages linked to the source nodes. - Hashtable taskmap; // to hold the filenames for each of the pages linked to tasks in the program. - GarbageAnalysis garbageanalysis; - - public WebInterface(State state, TaskAnalysis taskanalysis, TaskGraph taskgraph, GarbageAnalysis garbageanalysis, TagAnalysis taganalysis) { - this.state=state; - this.taskanalysis=taskanalysis; - this.taskgraph=taskgraph; - this.garbageanalysis=garbageanalysis; - this.taganalysis=taganalysis; - - flagstatemap=new Hashtable(); - taskgraphmap=new Hashtable(); - taskmap = new Hashtable(); - sourcenodemap=new Hashtable(); - - for(Iterator it_tasks=state.getTaskSymbolTable().getDescriptorsIterator();it_tasks.hasNext();){ - TaskDescriptor td=(TaskDescriptor)it_tasks.next(); - taskmap.put("/"+td.getSymbol()+".html",td); - } - - 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); - } - } - } - } - - public boolean specialRequest(String filename) { - System.out.println(filename); - if (filename.equals("/index.html")) - return true; - if (filename.equals("/UnifiedTaskGraph.html")) - return true; - if (flagstatemap.containsKey(filename)) - return true; - if (taskgraphmap.containsKey(filename)) - return true; - if (taskmap.containsKey(filename)) - return true; - if (sourcenodemap.containsKey(filename)) - return true; - return false; - } + TaskAnalysis taskanalysis; + TaskGraph taskgraph; + TagAnalysis taganalysis; + State state; + Hashtable flagstatemap; + Hashtable taskgraphmap; + Hashtable sourcenodemap; //to hold the filenames for each of the pages linked to the source nodes. + Hashtable taskmap; // to hold the filenames for each of the pages linked to tasks in the program. + GarbageAnalysis garbageanalysis; + + public WebInterface(State state, TaskAnalysis taskanalysis, TaskGraph taskgraph, GarbageAnalysis garbageanalysis, TagAnalysis taganalysis) { + this.state=state; + this.taskanalysis=taskanalysis; + this.taskgraph=taskgraph; + this.garbageanalysis=garbageanalysis; + this.taganalysis=taganalysis; + + flagstatemap=new Hashtable(); + taskgraphmap=new Hashtable(); + taskmap = new Hashtable(); + sourcenodemap=new Hashtable(); - public String handleresponse(String filename, OutputStream out, HTTPResponse resp) { - if (filename.equals("/index.html")) - return indexpage(out, resp); - if (filename.equals("/UnifiedTaskGraph.html")) - return unifiedTaskGraph(out,resp); - if (flagstatemap.containsKey(filename)) - return flagstate((ClassDescriptor) flagstatemap.get(filename), out, resp); - if (taskgraphmap.containsKey(filename)) - return taskstate((ClassDescriptor) taskgraphmap.get(filename), out, resp); - if (taskmap.containsKey(filename)) - return task((TaskDescriptor)taskmap.get(filename),out,resp); - if (sourcenodemap.containsKey(filename)) - return sourcenode((Vector) sourcenodemap.get(filename), out, resp); - return "NORESP"; + for(Iterator it_tasks=state.getTaskSymbolTable().getDescriptorsIterator(); it_tasks.hasNext();){ + TaskDescriptor td=(TaskDescriptor)it_tasks.next(); + taskmap.put("/"+td.getSymbol()+".html",td); } - private String task(TaskDescriptor td, OutputStream out, HTTPResponse resp){ - try{ - PrintWriter pw=new PrintWriter(out); - pw.println("

Task:   "+td.toString()+"


"); - printTask(td,pw); - - //printing out the classes that are instantiated by this task - 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()+"
"); - } - - pw.flush(); - } catch (Exception e) {e.printStackTrace();System.exit(-1);} - return null; + 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); + } + } } + } + + public boolean specialRequest(String filename) { + System.out.println(filename); + if (filename.equals("/index.html")) + return true; + if (filename.equals("/UnifiedTaskGraph.html")) + return true; + if (flagstatemap.containsKey(filename)) + return true; + if (taskgraphmap.containsKey(filename)) + return true; + if (taskmap.containsKey(filename)) + return true; + if (sourcenodemap.containsKey(filename)) + return true; + return false; + } + + public String handleresponse(String filename, OutputStream out, HTTPResponse resp) { + if (filename.equals("/index.html")) + return indexpage(out, resp); + if (filename.equals("/UnifiedTaskGraph.html")) + return unifiedTaskGraph(out,resp); + if (flagstatemap.containsKey(filename)) + return flagstate((ClassDescriptor) flagstatemap.get(filename), out, resp); + if (taskgraphmap.containsKey(filename)) + return taskstate((ClassDescriptor) taskgraphmap.get(filename), out, resp); + if (taskmap.containsKey(filename)) + return task((TaskDescriptor)taskmap.get(filename),out,resp); + if (sourcenodemap.containsKey(filename)) + return sourcenode((Vector) sourcenodemap.get(filename), out, resp); + return "NORESP"; + } + + private String task(TaskDescriptor td, OutputStream out, HTTPResponse resp) { + try{ + PrintWriter pw=new PrintWriter(out); + pw.println("

Task:   "+td.toString()+"


"); + printTask(td,pw); - private String printTask(TaskDescriptor td, PrintWriter pw){ + //printing out the classes that are instantiated by this task + 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()+"
"); + } + + pw.flush(); + } catch (Exception e) {e.printStackTrace(); System.exit(-1);} + return null; + } + + private String printTask(TaskDescriptor td, PrintWriter pw) { + try{ + + for(int i=0; i < td.numParameters(); i++){ + pw.println("FlagState Graph:  "+td.getParamType(i)+"
"); + pw.println("Task Graph:        " + +td.getParamType(i)+"
"); + } + pw.flush(); + } catch(Exception e) {e.printStackTrace(); System.exit(-1);} + return null; + } + + private String sourcenode(Vector cd_nodeid,OutputStream out, HTTPResponse resp) { + Vector rootnodes=taskanalysis.getRootNodes((ClassDescriptor)cd_nodeid.elementAt(0)); + 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); + } - for(int i=0; i < td.numParameters();i++){ - pw.println("FlagState Graph:  "+td.getParamType(i)+"
"); - pw.println("Task Graph:        " - +td.getParamType(i)+"
"); - } - pw.flush(); - }catch(Exception e) {e.printStackTrace();System.exit(-1);} - return null; - } - - private String sourcenode(Vector cd_nodeid,OutputStream out, HTTPResponse resp){ - Vector rootnodes=taskanalysis.getRootNodes((ClassDescriptor)cd_nodeid.elementAt(0)); - 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; - } - - } - return null; - } - - private String flagstate(ClassDescriptor cd, OutputStream out, HTTPResponse resp) { - Set objects=taskanalysis.getFlagStates(cd); - File file=new File(cd.getSymbol()+".dot"); - File mapfile; - String str; - Vector namers=new Vector(); - namers.add(new Namer()); - namers.add(garbageanalysis); - namers.add(new Allocations()); - namers.add(new TaskEdges()); - try { - //Generate jpg - Runtime r=Runtime.getRuntime(); - - FileOutputStream dotstream=new FileOutputStream(file,false); - FlagState.DOTVisitor.visit(dotstream, objects, namers); - dotstream.close(); - Process p=r.exec("dot -Tcmapx -o"+cd.getSymbol()+".map -Tjpg -o"+cd.getSymbol()+".jpg "+cd.getSymbol()+".dot"); - p.waitFor(); - p=r.exec("dot -Tps "+cd.getSymbol()+".dot -o"+cd.getSymbol()+".ps"); - p.waitFor(); - - mapfile=new File(cd.getSymbol()+".map"); - BufferedReader mapbr=new BufferedReader(new FileReader(mapfile)); - PrintWriter pw=new PrintWriter(out); - pw.println("ps
"); - //pw.println(""); - pw.println(""); - while((str=mapbr.readLine())!=null){ - pw.println(str); - } - - pw.flush(); - } catch (Exception e) {e.printStackTrace();System.exit(-1);} - return null; - } + } catch (Exception e) {e.printStackTrace(); System.exit(-1);} + break; + } - private String taskstate(ClassDescriptor cd, OutputStream out, HTTPResponse resp) { - Set objects=taskgraph.getTaskNodes(cd); - File file=new File(cd.getSymbol()+"-t.dot"); - File mapfile; - String str; - Vector namers=new Vector(); - namers.add(new Namer()); - namers.add(new TaskNodeNamer()); - - try { - //Generate jpg - Runtime r=Runtime.getRuntime(); - FileOutputStream dotstream=new FileOutputStream(file,false); - FlagState.DOTVisitor.visit(dotstream, objects,namers); - dotstream.close(); - Process p=r.exec("dot -Tcmapx -o"+cd.getSymbol()+"-t.map -Tjpg -o"+cd.getSymbol()+"-t.jpg "+cd.getSymbol()+"-t.dot"); - p.waitFor(); - p=r.exec("dot -Tps "+cd.getSymbol()+".dot -o"+cd.getSymbol()+"-t.ps"); - - p.waitFor(); - - mapfile=new File(cd.getSymbol()+"-t.map"); - BufferedReader mapbr=new BufferedReader(new FileReader(mapfile)); - PrintWriter pw=new PrintWriter(out); - pw.println("ps
"); - // pw.println(""); - pw.println(""); - - while((str=mapbr.readLine())!=null){ - pw.println(str); - } - pw.flush(); - } catch (Exception e) {e.printStackTrace();System.exit(-1);} - return null; } - - /* public void taskgraph( -*/ - - private String indexpage(OutputStream out, HTTPResponse resp) { - - PrintWriter pw=new PrintWriter(out); - 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); - } - } + return null; + } + + private String flagstate(ClassDescriptor cd, OutputStream out, HTTPResponse resp) { + Set objects=taskanalysis.getFlagStates(cd); + File file=new File(cd.getSymbol()+".dot"); + File mapfile; + String str; + Vector namers=new Vector(); + namers.add(new Namer()); + namers.add(garbageanalysis); + namers.add(new Allocations()); + namers.add(new TaskEdges()); + try { + //Generate jpg + Runtime r=Runtime.getRuntime(); + + FileOutputStream dotstream=new FileOutputStream(file,false); + FlagState.DOTVisitor.visit(dotstream, objects, namers); + dotstream.close(); + Process p=r.exec("dot -Tcmapx -o"+cd.getSymbol()+".map -Tjpg -o"+cd.getSymbol()+".jpg "+cd.getSymbol()+".dot"); + p.waitFor(); + p=r.exec("dot -Tps "+cd.getSymbol()+".dot -o"+cd.getSymbol()+".ps"); + p.waitFor(); + + mapfile=new File(cd.getSymbol()+".map"); + BufferedReader mapbr=new BufferedReader(new FileReader(mapfile)); + PrintWriter pw=new PrintWriter(out); + pw.println("ps
"); + //pw.println(""); + pw.println(""); + while((str=mapbr.readLine())!=null){ + pw.println(str); + } + + pw.flush(); + } catch (Exception e) {e.printStackTrace(); System.exit(-1);} + return null; + } + + private String taskstate(ClassDescriptor cd, OutputStream out, HTTPResponse resp) { + Set objects=taskgraph.getTaskNodes(cd); + File file=new File(cd.getSymbol()+"-t.dot"); + File mapfile; + String str; + Vector namers=new Vector(); + namers.add(new Namer()); + namers.add(new TaskNodeNamer()); + + try { + //Generate jpg + Runtime r=Runtime.getRuntime(); + FileOutputStream dotstream=new FileOutputStream(file,false); + FlagState.DOTVisitor.visit(dotstream, objects,namers); + dotstream.close(); + Process p=r.exec("dot -Tcmapx -o"+cd.getSymbol()+"-t.map -Tjpg -o"+cd.getSymbol()+"-t.jpg "+cd.getSymbol()+"-t.dot"); + p.waitFor(); + p=r.exec("dot -Tps "+cd.getSymbol()+".dot -o"+cd.getSymbol()+"-t.ps"); + + p.waitFor(); + + mapfile=new File(cd.getSymbol()+"-t.map"); + BufferedReader mapbr=new BufferedReader(new FileReader(mapfile)); + PrintWriter pw=new PrintWriter(out); + pw.println("ps
"); + // pw.println(""); + pw.println(""); + + while((str=mapbr.readLine())!=null){ + pw.println(str); + } + pw.flush(); + } catch (Exception e) {e.printStackTrace(); System.exit(-1);} + return null; + } + + /* public void taskgraph( + */ + + private String indexpage(OutputStream out, HTTPResponse resp) { + + PrintWriter pw=new PrintWriter(out); + 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); } - pw.println("

Program flow"); - pw.flush(); - return null; - } - - private String unifiedTaskGraph(OutputStream out, HTTPResponse resp){ - Set objects=taskgraph.getAllTaskNodes(); - File file=new File("UnifiedTaskGraph.dot"); - String str; - Vector namers=new Vector(); - namers.add(new Namer()); - namers.add(new TaskNodeNamer()); - - try { - //Generate jpg - Runtime r=Runtime.getRuntime(); - FileOutputStream dotstream=new FileOutputStream(file,false); - FlagState.DOTVisitor.visit(dotstream, objects, namers); - dotstream.close(); - Process p=r.exec("dot -Tjpg -oUnifiedTaskGraph.jpg -Tcmapx -oUnifiedTaskGraph.map UnifiedTaskGraph.dot"); - p.waitFor(); - p=r.exec("dot -Tps UnifiedTaskGraph.dot -oUnifiedTaskGraph.ps"); - - p.waitFor(); - - File mapfile=new File("UnifiedTaskGraph.map"); - BufferedReader mapbr=new BufferedReader(new FileReader(mapfile)); - PrintWriter pw=new PrintWriter(out); - pw.println("ps
"); - // pw.println(""); - pw.println(""); - - while((str=mapbr.readLine())!=null) - pw.println(str); - - pw.flush(); - } catch (Exception e) {e.printStackTrace();System.exit(-1);} - return null; + if (taskgraph.getTaskNodes(cd)!=null) { + pw.println("Task Graph "+ cd.getSymbol() +""); + pw.println("
"); + taskgraphmap.put("/"+cd.getSymbol()+"-t.html", cd); + } + } } + pw.println("

Program flow"); + pw.flush(); + return null; + } + + private String unifiedTaskGraph(OutputStream out, HTTPResponse resp) { + Set objects=taskgraph.getAllTaskNodes(); + File file=new File("UnifiedTaskGraph.dot"); + String str; + Vector namers=new Vector(); + namers.add(new Namer()); + namers.add(new TaskNodeNamer()); + + try { + //Generate jpg + Runtime r=Runtime.getRuntime(); + FileOutputStream dotstream=new FileOutputStream(file,false); + FlagState.DOTVisitor.visit(dotstream, objects, namers); + dotstream.close(); + Process p=r.exec("dot -Tjpg -oUnifiedTaskGraph.jpg -Tcmapx -oUnifiedTaskGraph.map UnifiedTaskGraph.dot"); + p.waitFor(); + p=r.exec("dot -Tps UnifiedTaskGraph.dot -oUnifiedTaskGraph.ps"); + + p.waitFor(); + + File mapfile=new File("UnifiedTaskGraph.map"); + BufferedReader mapbr=new BufferedReader(new FileReader(mapfile)); + PrintWriter pw=new PrintWriter(out); + pw.println("ps
"); + // pw.println(""); + pw.println(""); + + while((str=mapbr.readLine())!=null) + pw.println(str); + + pw.flush(); + } catch (Exception e) {e.printStackTrace(); System.exit(-1);} + return null; + } } diff --git a/Robust/src/Lex/BooleanLiteral.java b/Robust/src/Lex/BooleanLiteral.java index f013e641..2bda29c5 100644 --- a/Robust/src/Lex/BooleanLiteral.java +++ b/Robust/src/Lex/BooleanLiteral.java @@ -5,9 +5,15 @@ import Parse.Sym; class BooleanLiteral extends Literal { Boolean val; - BooleanLiteral(boolean b) { this.val = new Boolean(b); } + BooleanLiteral(boolean b) { + this.val = new Boolean(b); + } - Symbol token() { return new Symbol(Sym.BOOLEAN_LITERAL, val); } + Symbol token() { + return new Symbol(Sym.BOOLEAN_LITERAL, val); + } - public String toString() { return "BooleanLiteral <"+val.toString()+">"; } + public String toString() { + return "BooleanLiteral <"+val.toString()+">"; + } } diff --git a/Robust/src/Lex/CharacterLiteral.java b/Robust/src/Lex/CharacterLiteral.java index 87596f80..e7e4d820 100644 --- a/Robust/src/Lex/CharacterLiteral.java +++ b/Robust/src/Lex/CharacterLiteral.java @@ -5,11 +5,15 @@ import Parse.Sym; class CharacterLiteral extends Literal { Character val; - CharacterLiteral(char c) { this.val = new Character(c); } + CharacterLiteral(char c) { + this.val = new Character(c); + } - Symbol token() { return new Symbol(Sym.CHARACTER_LITERAL, val); } + Symbol token() { + return new Symbol(Sym.CHARACTER_LITERAL, val); + } - public String toString() { - return "CharacterLiteral <"+Token.escape(val.toString())+">"; + public String toString() { + return "CharacterLiteral <"+Token.escape(val.toString())+">"; } } diff --git a/Robust/src/Lex/Comment.java b/Robust/src/Lex/Comment.java index 6a0aae4b..2e02ff41 100644 --- a/Robust/src/Lex/Comment.java +++ b/Robust/src/Lex/Comment.java @@ -3,14 +3,16 @@ package Lex; abstract class Comment extends InputElement { private StringBuffer comment = new StringBuffer(); - String getComment() { return comment.toString(); } + String getComment() { + return comment.toString(); + } void appendLine(String more) { // 'more' is '\n' terminated. int i=0; // skip leading white space. for (; i"; } + public String toString() { + return "Identifier <"+identifier+">"; + } /* Ben Walter correctly pointed out that * the first released version of this grammar/lexer did not * return the string value of the identifier in the parser token. * Should be fixed now. ;-) */ - Symbol token() { return new Symbol(Sym.IDENTIFIER, identifier); } + Symbol token() { + return new Symbol(Sym.IDENTIFIER, identifier); + } } diff --git a/Robust/src/Lex/IntegerLiteral.java b/Robust/src/Lex/IntegerLiteral.java index ba3e4ee3..9ad2bb5f 100644 --- a/Robust/src/Lex/IntegerLiteral.java +++ b/Robust/src/Lex/IntegerLiteral.java @@ -4,7 +4,11 @@ import java_cup.runtime.Symbol; import Parse.Sym; class IntegerLiteral extends NumericLiteral { - IntegerLiteral(int i) { this.val = new Integer(i); } + IntegerLiteral(int i) { + this.val = new Integer(i); + } - Symbol token() { return new Symbol(Sym.INTEGER_LITERAL, val); } + Symbol token() { + return new Symbol(Sym.INTEGER_LITERAL, val); + } } diff --git a/Robust/src/Lex/Keyword.java b/Robust/src/Lex/Keyword.java index f39079a1..32ddff93 100644 --- a/Robust/src/Lex/Keyword.java +++ b/Robust/src/Lex/Keyword.java @@ -6,13 +6,17 @@ import Parse.Sym; class Keyword extends Token { String keyword; - Keyword(String s) { keyword = s; } + Keyword(String s) { + keyword = s; + } Symbol token() { Integer i = (Integer) key_table.get(keyword); return new Symbol(i.intValue()); } - public String toString() { return "Keyword <"+keyword+">"; } + public String toString() { + return "Keyword <"+keyword+">"; + } static private final Hashtable key_table = new Hashtable(); static { diff --git a/Robust/src/Lex/Lexer.java b/Robust/src/Lex/Lexer.java index 1d7e4610..fee2448e 100644 --- a/Robust/src/Lex/Lexer.java +++ b/Robust/src/Lex/Lexer.java @@ -19,13 +19,13 @@ public class Lexer { int line_pos = 1; int line_num = 0; LineList lineL = new LineList(-line_pos, null); // sentinel for line #0 - + public Lexer(Reader reader) { this.reader = new LineNumberReader(new EscapedUnicodeReader(reader)); this.isJava12 = true; this.isJava14 = true; } - + public java_cup.runtime.Symbol nextToken() throws java.io.IOException { java_cup.runtime.Symbol sym = lookahead==null ? _nextToken() : lookahead.get(); @@ -37,9 +37,9 @@ public class Lexer { if (last==null || last.sym!=Sym.IDENTIFIER) return false; if (lookahead==null) lookahead = new FIFO(new FIFO.Getter() { - java_cup.runtime.Symbol next() throws java.io.IOException - { return _nextToken(); } - }); + java_cup.runtime.Symbol next() throws java.io.IOException + { return _nextToken(); } + }); int i=0; // skip past IDENTIFIER (DOT IDENTIFIER)* if (lookahead.peek(i++).sym != Sym.IDENTIFIER) @@ -59,6 +59,7 @@ public class Lexer { switch(lookahead.peek(i).sym) { default: return false; + case Sym.LT: case Sym.GT: case Sym.COMMA: @@ -103,9 +104,13 @@ public class Lexer { } String comment; - public String lastComment() { return comment; } - public void clearComment() { comment=""; } - + public String lastComment() { + return comment; + } + public void clearComment() { + comment=""; + } + InputElement getInputElement() throws java.io.IOException { if (line_num == 0) nextLine(); @@ -116,14 +121,14 @@ public class Lexer { if (line==null) return new EOF(); } - + switch (line.charAt(line_pos)) { // White space: - case ' ': // ASCII SP - case '\t': // ASCII HT - case '\f': // ASCII FF - case '\n': // LineTerminator + case ' ': // ASCII SP + case '\t': // ASCII HT + case '\f': // ASCII FF + case '\n': // LineTerminator return new WhiteSpace(consume()); // EOF character: @@ -149,6 +154,7 @@ public class Lexer { comment = line.substring(line_pos+2); line_pos = line.length(); return new EndOfLineComment(comment); + case '*': // TraditionalComment or DocumentationComment line_pos += 2; if (line.charAt(line_pos)=='*') { // DocumentationComment @@ -156,6 +162,7 @@ public class Lexer { } else { // TraditionalComment return snarfComment(new TraditionalComment()); } + default: // it's a token, not a comment. return getToken(); } @@ -171,7 +178,7 @@ public class Lexer { c.appendLine(text.toString()); text.setLength(0); line_pos = line.length(); nextLine(); - if (line==null) + if (line==null) throw new Error("Unterminated comment at end of file."); } else { text.append(line.substring(line_pos, star_pos)); @@ -218,8 +225,10 @@ public class Lexer { case '^': case '%': return getOperator(); + case '\'': return getCharLiteral(); + case '\"': return getStringLiteral(); @@ -228,12 +237,13 @@ public class Lexer { if (Character.digit(line.charAt(line_pos+1),10)!=-1) return getNumericLiteral(); else if (isJava15 && - line.charAt(line_pos+1)=='.' && - line.charAt(line_pos+2)=='.') { + line.charAt(line_pos+1)=='.' && + line.charAt(line_pos+2)=='.') { consume(); consume(); consume(); return new Separator('\u2026'); // unicode ellipsis character. } else return new Separator(consume()); - default: + + default: break; } if (Character.isJavaIdentifierStart(line.charAt(line_pos))) @@ -246,16 +256,17 @@ public class Lexer { static final String[] keywords = new String[] { "abstract", "assert", "atomic", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", - "extends", "external", "final", "finally", + "extends", "external", "final", "finally", "flag", //keyword for failure aware computation - "float", "for", "global", "goto", "if", + "float", "for", "global", "goto", "if", "implements", "import", "instanceof", "int", "interface", "isavailable", - "long", - "native", "new", "optional", "package", "private", "protected", "public", + "long", + "native", "new", "optional", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "tag", "task", "taskexit", //keywords for failure aware computation "this", "throw", "throws", "transient", "try", "void", - "volatile", "while"}; + "volatile", "while" + }; Token getIdentifier() { // Get id string. StringBuffer sb = new StringBuffer().append(consume()); @@ -279,7 +290,7 @@ public class Lexer { // use binary search. for (int l=0, r=keywords.length; r > l; ) { int x = (l+r)/2, cmp = s.compareTo(keywords[x]); - if (cmp < 0) r=x; else l=x+1; + if (cmp < 0) r=x;else l=x+1; if (cmp== 0) return new Keyword(s); } // not a keyword. @@ -292,9 +303,9 @@ public class Lexer { return getFloatingPointLiteral(); // 0x indicates Hex. if (line.charAt(line_pos)=='0' && - (line.charAt(line_pos+1)=='x' || - line.charAt(line_pos+1)=='X')) { - line_pos+=2; return getIntegerLiteral(/*base*/16); + (line.charAt(line_pos+1)=='x' || + line.charAt(line_pos+1)=='X')) { + line_pos+=2; return getIntegerLiteral(/*base*/ 16); } // otherwise scan to first non-numeric for (i=line_pos; Character.digit(line.charAt(i),10)!=-1; ) @@ -308,12 +319,13 @@ public class Lexer { case 'e': case 'E': return getFloatingPointLiteral(); + case 'L': case 'l': default: if (line.charAt(line_pos)=='0') - return getIntegerLiteral(/*base*/8); - return getIntegerLiteral(/*base*/10); + return getIntegerLiteral(/*base*/ 8); + return getIntegerLiteral(/*base*/ 10); } } NumericLiteral getIntegerLiteral(int radix) { @@ -321,14 +333,14 @@ public class Lexer { while (Character.digit(line.charAt(line_pos),radix)!=-1) val = (val*radix) + Character.digit(consume(),radix); if (line.charAt(line_pos) == 'l' || - line.charAt(line_pos) == 'L') { + line.charAt(line_pos) == 'L') { consume(); return new LongLiteral(val); - } + } // we compare MAX_VALUE against val/2 to allow constants like // 0xFFFF0000 to get past the test. (unsigned long->signed int) if ((val/2) > Integer.MAX_VALUE || - val < Integer.MIN_VALUE) + val < Integer.MIN_VALUE) throw new Error("Constant does not fit in integer on line "+line_num); return new IntegerLiteral((int)val); } @@ -337,10 +349,10 @@ public class Lexer { if (line.charAt(line_pos)=='.') rep+=consume() + getDigits(); if (line.charAt(line_pos)=='e' || - line.charAt(line_pos)=='E') { + line.charAt(line_pos)=='E') { rep+=consume(); if (line.charAt(line_pos)=='+' || - line.charAt(line_pos)=='-') + line.charAt(line_pos)=='-') rep+=consume(); rep+=getDigits(); } @@ -350,9 +362,11 @@ public class Lexer { case 'F': consume(); return new FloatLiteral(Float.valueOf(rep).floatValue()); + case 'd': case 'D': consume(); + /* falls through */ default: return new DoubleLiteral(Double.valueOf(rep).doubleValue()); @@ -378,23 +392,25 @@ public class Lexer { case '?': case ':': return new Operator(new String(new char[] {first})); + // doubled operators case '+': case '-': case '&': case '|': - if (first==second) + if (first==second) return new Operator(new String(new char[] {first, consume()})); + default: break; } // Check for trailing '=' if (second=='=') - return new Operator(new String(new char[] {first, consume()})); + return new Operator(new String(new char[] {first, consume()})); // Special-case '<<', '>>' and '>>>' if ((first=='<' && second=='<') || // << - (first=='>' && second=='>')) { // >> + (first=='>' && second=='>')) { // >> String op = new String(new char[] {first, consume()}); if (first=='>' && line.charAt(line_pos)=='>') // >>> op += consume(); @@ -414,10 +430,13 @@ public class Lexer { case '\\': val = getEscapeSequence(); break; + case '\'': throw new Error("Invalid character literal on line "+line_num); + case '\n': throw new Error("Invalid character literal on line "+line_num); + default: val = consume(); break; @@ -435,8 +454,10 @@ public class Lexer { case '\\': val.append(getEscapeSequence()); break; + case '\n': throw new Error("Invalid string literal on line " + line_num); + default: val.append(consume()); break; @@ -445,7 +466,7 @@ public class Lexer { char closequote = consume(); if (openquote != '\"' || closequote != '\"') throw new Error("Invalid string literal on line " + line_num); - + return new StringLiteral(val.toString().intern()); } @@ -455,30 +476,40 @@ public class Lexer { switch(line.charAt(line_pos)) { case 'b': consume(); return '\b'; + case 't': consume(); return '\t'; + case 'n': consume(); return '\n'; + case 'f': consume(); return '\f'; + case 'r': consume(); return '\r'; + case '\"': consume(); return '\"'; + case '\'': consume(); return '\''; + case '\\': consume(); return '\\'; + case '0': case '1': case '2': case '3': return (char) getOctal(3); + case '4': case '5': case '6': case '7': return (char) getOctal(2); + default: throw new Error("Invalid escape sequence on line " + line_num); } @@ -494,29 +525,37 @@ public class Lexer { return val; } - char consume() { return line.charAt(line_pos++); } + char consume() { + return line.charAt(line_pos++); + } void nextLine() throws java.io.IOException { line=reader.readLine(); - if (line!=null) line=line+'\n'; + if (line!=null) line=line+'\n'; lineL = new LineList(lineL.head+line_pos, lineL); // for error reporting - line_pos=0; - line_num++; + line_pos=0; + line_num++; } // Deal with error messages. public void errorMsg(String msg, java_cup.runtime.Symbol info) { 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; } + if (p.head<=info.left) { + c=info.left-p.head; break; + } System.err.println(msg+" at line "+n); num_errors++; } private int num_errors = 0; - public int numErrors() { return num_errors; } - + public int numErrors() { + return num_errors; + } + class LineList { int head; LineList tail; - LineList(int head, LineList tail) { this.head = head; this.tail = tail; } + LineList(int head, LineList tail) { + this.head = head; this.tail = tail; + } } } diff --git a/Robust/src/Lex/LongLiteral.java b/Robust/src/Lex/LongLiteral.java index 25090aef..fc368807 100644 --- a/Robust/src/Lex/LongLiteral.java +++ b/Robust/src/Lex/LongLiteral.java @@ -4,7 +4,11 @@ import java_cup.runtime.Symbol; import Parse.Sym; class LongLiteral extends NumericLiteral { - LongLiteral(long l) { this.val = new Long(l); } + LongLiteral(long l) { + this.val = new Long(l); + } - Symbol token() { return new Symbol(Sym.INTEGER_LITERAL, val); } + Symbol token() { + return new Symbol(Sym.INTEGER_LITERAL, val); + } } diff --git a/Robust/src/Lex/NullLiteral.java b/Robust/src/Lex/NullLiteral.java index 20e69994..a20eb75d 100644 --- a/Robust/src/Lex/NullLiteral.java +++ b/Robust/src/Lex/NullLiteral.java @@ -4,9 +4,14 @@ import java_cup.runtime.Symbol; import Parse.Sym; class NullLiteral extends Literal { - NullLiteral() { } + NullLiteral() { + } - Symbol token() { return new Symbol(Sym.NULL_LITERAL); } + Symbol token() { + return new Symbol(Sym.NULL_LITERAL); + } - public String toString() { return "NullLiteral "; } + public String toString() { + return "NullLiteral "; + } } diff --git a/Robust/src/Lex/NumericLiteral.java b/Robust/src/Lex/NumericLiteral.java index f67a135a..4f37adbd 100644 --- a/Robust/src/Lex/NumericLiteral.java +++ b/Robust/src/Lex/NumericLiteral.java @@ -3,5 +3,7 @@ package Lex; abstract class NumericLiteral extends Literal { Number val; - public String toString() { return "NumericLiteral <"+val.toString()+">"; } + public String toString() { + return "NumericLiteral <"+val.toString()+">"; + } } diff --git a/Robust/src/Lex/Operator.java b/Robust/src/Lex/Operator.java index e1b26daf..7173b331 100644 --- a/Robust/src/Lex/Operator.java +++ b/Robust/src/Lex/Operator.java @@ -6,13 +6,17 @@ import Parse.Sym; class Operator extends Token { String which; - Operator(String which) { this.which = which; } + Operator(String which) { + this.which = which; + } - public String toString() { return "Operator <"+which+">"; } + public String toString() { + return "Operator <"+which+">"; + } - Symbol token() { + Symbol token() { Integer i = (Integer) op_table.get(which); - return new Symbol(i.intValue()); + return new Symbol(i.intValue()); } static private final Hashtable op_table = new Hashtable(); diff --git a/Robust/src/Lex/Separator.java b/Robust/src/Lex/Separator.java index 6a553bfd..f2b1ac12 100644 --- a/Robust/src/Lex/Separator.java +++ b/Robust/src/Lex/Separator.java @@ -5,20 +5,32 @@ import Parse.Sym; class Separator extends Token { char which; - Separator(char which) { this.which = which; } + Separator(char which) { + this.which = which; + } Symbol token() { switch(which) { case '(': return new Symbol(Sym.LPAREN); + case ')': return new Symbol(Sym.RPAREN); + case '{': return new Symbol(Sym.LBRACE); + case '}': return new Symbol(Sym.RBRACE); + case '[': return new Symbol(Sym.LBRACK); + case ']': return new Symbol(Sym.RBRACK); + case ';': return new Symbol(Sym.SEMICOLON); + case ',': return new Symbol(Sym.COMMA); + case '.': return new Symbol(Sym.DOT); + case '\u2026': return new Symbol(Sym.ELLIPSIS); + default: throw new Error("Invalid separator."); } diff --git a/Robust/src/Lex/StringLiteral.java b/Robust/src/Lex/StringLiteral.java index c4830203..8c5e1286 100644 --- a/Robust/src/Lex/StringLiteral.java +++ b/Robust/src/Lex/StringLiteral.java @@ -5,11 +5,15 @@ import Parse.Sym; class StringLiteral extends Literal { String val; - StringLiteral(String s) { this.val = s; } + StringLiteral(String s) { + this.val = s; + } - Symbol token() { return new Symbol(Sym.STRING_LITERAL, val); } + Symbol token() { + return new Symbol(Sym.STRING_LITERAL, val); + } - public String toString() { - return "StringLiteral <"+Token.escape(val)+">"; + public String toString() { + return "StringLiteral <"+Token.escape(val)+">"; } } diff --git a/Robust/src/Lex/Token.java b/Robust/src/Lex/Token.java index ec3a578d..8cfb5c59 100644 --- a/Robust/src/Lex/Token.java +++ b/Robust/src/Lex/Token.java @@ -8,8 +8,11 @@ abstract class Token extends InputElement { for (int i=0; i"; diff --git a/Robust/src/Main/Main.java b/Robust/src/Main/Main.java index 8f0d548a..07b3b717 100644 --- a/Robust/src/Main/Main.java +++ b/Robust/src/Main/Main.java @@ -44,446 +44,442 @@ import Interface.*; public class Main { - /** Main method for the compiler. */ + /** Main method for the compiler. */ public static void main(String args[]) throws Exception { - String ClassLibraryPrefix="./ClassLibrary/"; - State state=new State(); - - for(int i=0;i -- 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("-optional -- enable optional arguments"); - System.out.println("-webinterface -- enable web interface"); - System.out.println("-help -- print out help"); - System.exit(0); - } else { - readSourceFile(state, args[i]); - } - } - - - readSourceFile(state, ClassLibraryPrefix+"System.java"); - readSourceFile(state, ClassLibraryPrefix+"String.java"); - readSourceFile(state, ClassLibraryPrefix+"HashSet.java"); - readSourceFile(state, ClassLibraryPrefix+"HashMap.java"); - readSourceFile(state, ClassLibraryPrefix+"HashMapIterator.java"); - readSourceFile(state, ClassLibraryPrefix+"HashEntry.java"); - readSourceFile(state, ClassLibraryPrefix+"Integer.java"); - readSourceFile(state, ClassLibraryPrefix+"StringBuffer.java"); - //if(!state.RAW) { - readSourceFile(state, ClassLibraryPrefix+"FileInputStream.java"); - readSourceFile(state, ClassLibraryPrefix+"InputStream.java"); - readSourceFile(state, ClassLibraryPrefix+"OutputStream.java"); - readSourceFile(state, ClassLibraryPrefix+"FileOutputStream.java"); - readSourceFile(state, ClassLibraryPrefix+"File.java"); - readSourceFile(state, ClassLibraryPrefix+"InetAddress.java"); - readSourceFile(state, ClassLibraryPrefix+"SocketInputStream.java"); - readSourceFile(state, ClassLibraryPrefix+"SocketOutputStream.java"); - //} - readSourceFile(state, ClassLibraryPrefix+"Math.java"); - readSourceFile(state, ClassLibraryPrefix+"gnu/Random.java"); - readSourceFile(state, ClassLibraryPrefix+"Vector.java"); - readSourceFile(state, ClassLibraryPrefix+"Enumeration.java"); - - if (state.TASK) { - readSourceFile(state, ClassLibraryPrefix+"Object.java"); - readSourceFile(state, ClassLibraryPrefix+"TagDescriptor.java"); - } else if (state.DSM) { - readSourceFile(state, ClassLibraryPrefix+"ThreadDSM.java"); - readSourceFile(state, ClassLibraryPrefix+"ObjectJavaDSM.java"); - readSourceFile(state, ClassLibraryPrefix+"Barrier.java"); + String ClassLibraryPrefix="./ClassLibrary/"; + State state=new State(); + + for(int i=0; i -- 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("-optional -- enable optional arguments"); + System.out.println("-webinterface -- enable web interface"); + System.out.println("-help -- print out help"); + System.exit(0); } else { - if (state.THREAD) { - readSourceFile(state, ClassLibraryPrefix+"Thread.java"); - readSourceFile(state, ClassLibraryPrefix+"ObjectJava.java"); - } else - readSourceFile(state, ClassLibraryPrefix+"ObjectJavaNT.java"); + readSourceFile(state, args[i]); } + } - if (state.TASK) { - readSourceFile(state, ClassLibraryPrefix+"StartupObject.java"); - readSourceFile(state, ClassLibraryPrefix+"Socket.java"); - readSourceFile(state, ClassLibraryPrefix+"ServerSocket.java"); - } else { - readSourceFile(state, ClassLibraryPrefix+"SocketJava.java"); - readSourceFile(state, ClassLibraryPrefix+"ServerSocketJava.java"); + + readSourceFile(state, ClassLibraryPrefix+"System.java"); + readSourceFile(state, ClassLibraryPrefix+"String.java"); + readSourceFile(state, ClassLibraryPrefix+"HashSet.java"); + readSourceFile(state, ClassLibraryPrefix+"HashMap.java"); + readSourceFile(state, ClassLibraryPrefix+"HashMapIterator.java"); + readSourceFile(state, ClassLibraryPrefix+"HashEntry.java"); + readSourceFile(state, ClassLibraryPrefix+"Integer.java"); + readSourceFile(state, ClassLibraryPrefix+"StringBuffer.java"); + //if(!state.RAW) { + readSourceFile(state, ClassLibraryPrefix+"FileInputStream.java"); + readSourceFile(state, ClassLibraryPrefix+"InputStream.java"); + readSourceFile(state, ClassLibraryPrefix+"OutputStream.java"); + readSourceFile(state, ClassLibraryPrefix+"FileOutputStream.java"); + readSourceFile(state, ClassLibraryPrefix+"File.java"); + readSourceFile(state, ClassLibraryPrefix+"InetAddress.java"); + readSourceFile(state, ClassLibraryPrefix+"SocketInputStream.java"); + readSourceFile(state, ClassLibraryPrefix+"SocketOutputStream.java"); + //} + readSourceFile(state, ClassLibraryPrefix+"Math.java"); + readSourceFile(state, ClassLibraryPrefix+"gnu/Random.java"); + readSourceFile(state, ClassLibraryPrefix+"Vector.java"); + readSourceFile(state, ClassLibraryPrefix+"Enumeration.java"); + + if (state.TASK) { + readSourceFile(state, ClassLibraryPrefix+"Object.java"); + readSourceFile(state, ClassLibraryPrefix+"TagDescriptor.java"); + } else if (state.DSM) { + readSourceFile(state, ClassLibraryPrefix+"ThreadDSM.java"); + readSourceFile(state, ClassLibraryPrefix+"ObjectJavaDSM.java"); + readSourceFile(state, ClassLibraryPrefix+"Barrier.java"); + } else { + if (state.THREAD) { + readSourceFile(state, ClassLibraryPrefix+"Thread.java"); + readSourceFile(state, ClassLibraryPrefix+"ObjectJava.java"); + } else + readSourceFile(state, ClassLibraryPrefix+"ObjectJavaNT.java"); + } + + if (state.TASK) { + readSourceFile(state, ClassLibraryPrefix+"StartupObject.java"); + readSourceFile(state, ClassLibraryPrefix+"Socket.java"); + readSourceFile(state, ClassLibraryPrefix+"ServerSocket.java"); + } else { + readSourceFile(state, ClassLibraryPrefix+"SocketJava.java"); + readSourceFile(state, ClassLibraryPrefix+"ServerSocketJava.java"); + } + + BuildIR bir=new BuildIR(state); + bir.buildtree(); + + TypeUtil tu=new TypeUtil(state); + + SemanticCheck sc=new SemanticCheck(state,tu); + sc.semanticCheck(); + tu.createFullTable(); + + BuildFlat bf=new BuildFlat(state,tu); + bf.buildFlat(); + SafetyAnalysis sa=null; + PrefetchAnalysis pa=null; + + if (state.TAGSTATE) { + CallGraph callgraph=new CallGraph(state); + TagAnalysis taganalysis=new TagAnalysis(state, callgraph); + TaskTagAnalysis tta=new TaskTagAnalysis(state, taganalysis); + } + + if (state.TASKSTATE) { + CallGraph callgraph=new CallGraph(state); + TagAnalysis taganalysis=new TagAnalysis(state, callgraph); + TaskAnalysis ta=new TaskAnalysis(state, taganalysis); + ta.taskAnalysis(); + TaskGraph tg=new TaskGraph(state, ta); + tg.createDOTfiles(); + + if (state.OPTIONAL) { + ExecutionGraph et=new ExecutionGraph(state, ta); + et.createExecutionGraph(); + sa = new SafetyAnalysis(et.getExecutionGraph(), state, ta); + sa.doAnalysis(); + state.storeAnalysisResult(sa.getResult()); + state.storeOptionalTaskDescriptors(sa.getOptionalTaskDescriptors()); } - BuildIR bir=new BuildIR(state); - bir.buildtree(); - - TypeUtil tu=new TypeUtil(state); - - SemanticCheck sc=new SemanticCheck(state,tu); - sc.semanticCheck(); - tu.createFullTable(); - - BuildFlat bf=new BuildFlat(state,tu); - bf.buildFlat(); - SafetyAnalysis sa=null; - PrefetchAnalysis pa=null; - - if (state.TAGSTATE) { - CallGraph callgraph=new CallGraph(state); - TagAnalysis taganalysis=new TagAnalysis(state, callgraph); - TaskTagAnalysis tta=new TaskTagAnalysis(state, taganalysis); + if (state.WEBINTERFACE) { + GarbageAnalysis ga=new GarbageAnalysis(state, ta); + WebInterface wi=new WebInterface(state, ta, tg, ga, taganalysis); + JhttpServer serve=new JhttpServer(8000,wi); + serve.run(); } - if (state.TASKSTATE) { - CallGraph callgraph=new CallGraph(state); - TagAnalysis taganalysis=new TagAnalysis(state, callgraph); - TaskAnalysis ta=new TaskAnalysis(state, taganalysis); - ta.taskAnalysis(); - TaskGraph tg=new TaskGraph(state, ta); - tg.createDOTfiles(); - - if (state.OPTIONAL) { - ExecutionGraph et=new ExecutionGraph(state, ta); - et.createExecutionGraph(); - sa = new SafetyAnalysis(et.getExecutionGraph(), state, ta); - sa.doAnalysis(); - state.storeAnalysisResult(sa.getResult()); - state.storeOptionalTaskDescriptors(sa.getOptionalTaskDescriptors()); - } - - if (state.WEBINTERFACE) { - GarbageAnalysis ga=new GarbageAnalysis(state, ta); - WebInterface wi=new WebInterface(state, ta, tg, ga, taganalysis); - JhttpServer serve=new JhttpServer(8000,wi); - serve.run(); - } - - if (state.SCHEDULING) { - // Save the current standard input, output, and error streams - // for later restoration. - PrintStream origOut = System.out; - - // Create a new output stream for the standard output. - PrintStream stdout = null; - try { - stdout = new PrintStream (new FileOutputStream("SimulatorResult.out")); - } catch (Exception e) { - // Sigh. Couldn't open the file. - System.out.println ("Redirect: Unable to open output file!"); - System.exit (1); - } + if (state.SCHEDULING) { + // Save the current standard input, output, and error streams + // for later restoration. + PrintStream origOut = System.out; + + // Create a new output stream for the standard output. + PrintStream stdout = null; + try { + stdout = new PrintStream(new FileOutputStream("SimulatorResult.out")); + } catch (Exception e) { + // Sigh. Couldn't open the file. + System.out.println("Redirect: Unable to open output file!"); + System.exit(1); + } + + // Print stuff to the original output and error streams. + // On most systems all of this will end up on your console when you + // run this application. + //origOut.println ("\nRedirect: Round #1"); + //System.out.println ("Test output via 'System.out'."); + //origOut.println ("Test output via 'origOut' reference."); + + // Set the System out and err streams to use our replacements. + System.setOut(stdout); + + // Print stuff to the original output and error streams. + // The stuff printed through the 'origOut' and 'origErr' references + // should go to the console on most systems while the messages + // printed through the 'System.out' and 'System.err' will end up in + // the files we created for them. + //origOut.println ("\nRedirect: Round #2"); + //System.out.println ("Test output via 'SimulatorResult.out'."); + //origOut.println ("Test output via 'origOut' reference."); - // Print stuff to the original output and error streams. - // On most systems all of this will end up on your console when you - // run this application. - //origOut.println ("\nRedirect: Round #1"); - //System.out.println ("Test output via 'System.out'."); - //origOut.println ("Test output via 'origOut' reference."); - - // Set the System out and err streams to use our replacements. - System.setOut(stdout); - - // Print stuff to the original output and error streams. - // The stuff printed through the 'origOut' and 'origErr' references - // should go to the console on most systems while the messages - // printed through the 'System.out' and 'System.err' will end up in - // the files we created for them. - //origOut.println ("\nRedirect: Round #2"); - //System.out.println ("Test output via 'SimulatorResult.out'."); - //origOut.println ("Test output via 'origOut' reference."); - - // for test - // Randomly set the newRate and probability of FEdges - java.util.Random r=new java.util.Random(); - int tint = 0; - for(Iterator it_classes=state.getClassSymbolTable().getDescriptorsIterator();it_classes.hasNext();) { - ClassDescriptor cd=(ClassDescriptor) it_classes.next(); - if(cd.hasFlags()){ - Vector rootnodes=ta.getRootNodes(cd); - if(rootnodes!=null) - for(Iterator it_rootnodes=rootnodes.iterator();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)ta.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"))) { - newRate = 16; - } else if(cdname.equals("SentenceParser")) { - newRate = 4; - } - /*do { - tint = r.nextInt()%100; - } while(tint <= 0); - int probability = tint;*/ - int probability = 100; - pfe.addNewObjInfo(cd, newRate, probability); - } - } - } - } - - Iterator it_flags = ta.getFlagStates(cd).iterator(); - while(it_flags.hasNext()) { - FlagState fs = (FlagState)it_flags.next(); - Iterator it_edges = fs.edges(); - while(it_edges.hasNext()) { - /*do { - tint = r.nextInt()%10; - } while(tint <= 0);*/ - tint = 3; - ((FEdge)it_edges.next()).setExeTime(tint); - } + // for test + // Randomly set the newRate and probability of FEdges + java.util.Random r=new java.util.Random(); + int tint = 0; + for(Iterator it_classes=state.getClassSymbolTable().getDescriptorsIterator(); it_classes.hasNext();) { + ClassDescriptor cd=(ClassDescriptor) it_classes.next(); + if(cd.hasFlags()){ + Vector rootnodes=ta.getRootNodes(cd); + if(rootnodes!=null) + for(Iterator it_rootnodes=rootnodes.iterator(); 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)ta.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"))) { + newRate = 16; + } else if(cdname.equals("SentenceParser")) { + newRate = 4; + } + /*do { + tint = r.nextInt()%100; + } while(tint <= 0); + int probability = tint;*/ + int probability = 100; + pfe.addNewObjInfo(cd, newRate, probability); + } } + } } - - // generate multiple schedulings - ScheduleAnalysis scheduleAnalysis = new ScheduleAnalysis(state, ta); - scheduleAnalysis.preSchedule(); - scheduleAnalysis.scheduleAnalysis(); - //scheduleAnalysis.setCoreNum(scheduleAnalysis.getSEdges4Test().size()); - scheduleAnalysis.setCoreNum(state.CORENUM); - scheduleAnalysis.schedule(); - - //simulate these schedulings - ScheduleSimulator scheduleSimulator = new ScheduleSimulator(scheduleAnalysis.getCoreNum(), state, ta); - Iterator it_scheduling = scheduleAnalysis.getSchedulingsIter(); - int index = 0; - Vector selectedScheduling = new Vector(); - int processTime = Integer.MAX_VALUE; - while(it_scheduling.hasNext()) { - Vector scheduling = (Vector)it_scheduling.next(); - scheduleSimulator.setScheduling(scheduling); - int tmpTime = scheduleSimulator.process(); - if(tmpTime < processTime) { - selectedScheduling.clear(); - selectedScheduling.add(index); - processTime = tmpTime; - } else if(tmpTime == processTime) { - selectedScheduling.add(index); - } - index++; - } - System.out.print("Selected schedulings with least exectution time " + processTime + ": \n\t"); - for(int i = 0; i < selectedScheduling.size(); i++) { - System.out.print((selectedScheduling.elementAt(i) + 1) + ", "); - } - System.out.println(); - - /*ScheduleSimulator scheduleSimulator = new ScheduleSimulator(4, state, ta); - Vector scheduling = new Vector(); - for(int i = 0; i < 4; i++) { - Schedule schedule = new Schedule(i); - scheduling.add(schedule); - } - Iterator it_tasks = state.getTaskSymbolTable().getAllDescriptorsIterator(); - while(it_tasks.hasNext()) { - TaskDescriptor td = (TaskDescriptor)it_tasks.next(); - if(td.getSymbol().equals("t10")) { - scheduling.elementAt(1).addTask(td); - } else { - scheduling.elementAt(0).addTask(td); - } - } - ClassDescriptor cd = (ClassDescriptor)state.getClassSymbolTable().get("E"); - scheduling.elementAt(0).addTargetCore(cd, 1); - scheduleSimulator.setScheduling(scheduling); - scheduleSimulator.process(); - - Vector scheduling1 = new Vector(); - for(int i = 0; i < 4; i++) { - Schedule schedule = new Schedule(i); - scheduling1.add(schedule); - } - Iterator it_tasks1 = state.getTaskSymbolTable().getAllDescriptorsIterator(); - while(it_tasks1.hasNext()) { - TaskDescriptor td = (TaskDescriptor)it_tasks1.next(); - scheduling1.elementAt(0).addTask(td); - } - scheduleSimulator.setScheduling(scheduling1); - scheduleSimulator.process();*/ - - // Close the streams. - try { - stdout.close (); - System.setOut(origOut); - } catch (Exception e) { - origOut.println ("Redirect: Unable to close files!"); - } - - if(state.MULTICORE) { - //it_scheduling = scheduleAnalysis.getSchedulingsIter(); - //Vector scheduling = (Vector)it_scheduling.next(); - Vector scheduling = scheduleAnalysis.getSchedulings().elementAt(selectedScheduling.lastElement()); - BuildCodeMultiCore bcm=new BuildCodeMultiCore(state, bf.getMap(), tu, sa, scheduling, scheduleAnalysis.getCoreNum(), pa); - bcm.buildCode(); + + Iterator it_flags = ta.getFlagStates(cd).iterator(); + while(it_flags.hasNext()) { + FlagState fs = (FlagState)it_flags.next(); + Iterator it_edges = fs.edges(); + while(it_edges.hasNext()) { + /*do { + tint = r.nextInt()%10; + } while(tint <= 0);*/ + tint = 3; + ((FEdge)it_edges.next()).setExeTime(tint); } + } } - - } + } - if(!state.MULTICORE) { - if (state.DSM) { - CallGraph callgraph=new CallGraph(state); - 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); - } + // generate multiple schedulings + ScheduleAnalysis scheduleAnalysis = new ScheduleAnalysis(state, ta); + scheduleAnalysis.preSchedule(); + scheduleAnalysis.scheduleAnalysis(); + //scheduleAnalysis.setCoreNum(scheduleAnalysis.getSEdges4Test().size()); + scheduleAnalysis.setCoreNum(state.CORENUM); + scheduleAnalysis.schedule(); - LocalityAnalysis la=new LocalityAnalysis(state, callgraph, tu); - GenerateConversions gc=new GenerateConversions(la, state); - BuildCode bc=new BuildCode(state, bf.getMap(), tu, la, pa); - bc.buildCode(); - } else { - BuildCode bc=new BuildCode(state, bf.getMap(), tu, sa, pa); - bc.buildCode(); + //simulate these schedulings + ScheduleSimulator scheduleSimulator = new ScheduleSimulator(scheduleAnalysis.getCoreNum(), state, ta); + Iterator it_scheduling = scheduleAnalysis.getSchedulingsIter(); + int index = 0; + Vector selectedScheduling = new Vector(); + int processTime = Integer.MAX_VALUE; + while(it_scheduling.hasNext()) { + Vector scheduling = (Vector)it_scheduling.next(); + scheduleSimulator.setScheduling(scheduling); + int tmpTime = scheduleSimulator.process(); + if(tmpTime < processTime) { + selectedScheduling.clear(); + selectedScheduling.add(index); + processTime = tmpTime; + } else if(tmpTime == processTime) { + selectedScheduling.add(index); } - } + index++; + } + System.out.print("Selected schedulings with least exectution time " + processTime + ": \n\t"); + for(int i = 0; i < selectedScheduling.size(); i++) { + System.out.print((selectedScheduling.elementAt(i) + 1) + ", "); + } + System.out.println(); - if (state.FLATIRGRAPH) { - FlatIRGraph firg = new FlatIRGraph(state, - state.FLATIRGRAPHTASKS, - state.FLATIRGRAPHUSERMETHODS, - state.FLATIRGRAPHLIBMETHODS); - } + /*ScheduleSimulator scheduleSimulator = new ScheduleSimulator(4, state, ta); + Vector scheduling = new Vector(); + for(int i = 0; i < 4; i++) { + Schedule schedule = new Schedule(i); + scheduling.add(schedule); + } + Iterator it_tasks = state.getTaskSymbolTable().getAllDescriptorsIterator(); + while(it_tasks.hasNext()) { + TaskDescriptor td = (TaskDescriptor)it_tasks.next(); + if(td.getSymbol().equals("t10")) { + scheduling.elementAt(1).addTask(td); + } else { + scheduling.elementAt(0).addTask(td); + } + } + ClassDescriptor cd = (ClassDescriptor)state.getClassSymbolTable().get("E"); + scheduling.elementAt(0).addTargetCore(cd, 1); + scheduleSimulator.setScheduling(scheduling); + scheduleSimulator.process(); - if (state.OWNERSHIP) { - CallGraph callGraph = new CallGraph( state ); - int allocationDepth = 3; - OwnershipAnalysis oa = - new OwnershipAnalysis( state, callGraph, allocationDepth ); - //This was breaking the compile - // oa.writeAllAliases( "identifiedAliases.txt" ); - } + Vector scheduling1 = new Vector(); + for(int i = 0; i < 4; i++) { + Schedule schedule = new Schedule(i); + scheduling1.add(schedule); + } + Iterator it_tasks1 = state.getTaskSymbolTable().getAllDescriptorsIterator(); + while(it_tasks1.hasNext()) { + TaskDescriptor td = (TaskDescriptor)it_tasks1.next(); + scheduling1.elementAt(0).addTask(td); + } + scheduleSimulator.setScheduling(scheduling1); + scheduleSimulator.process();*/ - System.exit(0); - } - - /** Reads in a source file and adds the parse tree to the state object. */ - - private static void readSourceFile(State state, String sourcefile) throws Exception { - Reader fr = new BufferedReader(new FileReader(sourcefile)); - Lex.Lexer l = new Lex.Lexer(fr); - java_cup.runtime.lr_parser g; - g = new Parse.Parser(l); - ParseNode p=null; + // Close the streams. try { - p=(ParseNode) g./*debug_*/parse().value; + stdout.close(); + System.setOut(origOut); } catch (Exception e) { - System.err.println("Error parsing file:"+sourcefile); - e.printStackTrace(); - System.exit(-1); + origOut.println("Redirect: Unable to close files!"); + } + + if(state.MULTICORE) { + //it_scheduling = scheduleAnalysis.getSchedulingsIter(); + //Vector scheduling = (Vector)it_scheduling.next(); + Vector scheduling = scheduleAnalysis.getSchedulings().elementAt(selectedScheduling.lastElement()); + BuildCodeMultiCore bcm=new BuildCodeMultiCore(state, bf.getMap(), tu, sa, scheduling, scheduleAnalysis.getCoreNum(), pa); + bcm.buildCode(); } - state.addParseNode(p); - if (l.numErrors()!=0) { - System.out.println("Error parsing "+sourcefile); - System.exit(l.numErrors()); + } + + } + + if(!state.MULTICORE) { + if (state.DSM) { + CallGraph callgraph=new CallGraph(state); + 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); + BuildCode bc=new BuildCode(state, bf.getMap(), tu, la, pa); + bc.buildCode(); + } else { + BuildCode bc=new BuildCode(state, bf.getMap(), tu, sa, pa); + bc.buildCode(); + } + } + + if (state.FLATIRGRAPH) { + FlatIRGraph firg = new FlatIRGraph(state, + state.FLATIRGRAPHTASKS, + state.FLATIRGRAPHUSERMETHODS, + state.FLATIRGRAPHLIBMETHODS); } + + if (state.OWNERSHIP) { + CallGraph callGraph = new CallGraph(state); + int allocationDepth = 3; + OwnershipAnalysis oa = + new OwnershipAnalysis(state, callGraph, allocationDepth); + //This was breaking the compile + // oa.writeAllAliases( "identifiedAliases.txt" ); + } + + System.exit(0); + } + + /** Reads in a source file and adds the parse tree to the state object. */ + + private static void readSourceFile(State state, String sourcefile) throws Exception { + Reader fr = new BufferedReader(new FileReader(sourcefile)); + Lex.Lexer l = new Lex.Lexer(fr); + java_cup.runtime.lr_parser g; + g = new Parse.Parser(l); + ParseNode p=null; + try { + p=(ParseNode) g./*debug_*/ parse().value; + } catch (Exception e) { + 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()); + } + } } diff --git a/Robust/src/Runtime/DSTM/interface/addPrefetchEnhance.c b/Robust/src/Runtime/DSTM/interface/addPrefetchEnhance.c index a368e86f..e86b860e 100644 --- a/Robust/src/Runtime/DSTM/interface/addPrefetchEnhance.c +++ b/Robust/src/Runtime/DSTM/interface/addPrefetchEnhance.c @@ -7,7 +7,7 @@ extern objstr_t *prefetchcache; //Global Prefetch cache extern pthread_mutex_t prefetchcache_mutex; //Mutex to lock Prefetch Cache extern unsigned int myIpAddr; -/* This function creates and initializes the +/* This function creates and initializes the * evalPrefetch global array */ pfcstats_t *initPrefetchStats() { pfcstats_t *ptr; @@ -38,7 +38,7 @@ char getOperationMode(int siteid) { return evalPrefetch[siteid].operMode; } -/* This function updates counters and mode of operation of a +/* This function updates counters and mode of operation of a * prefetch site during runtime. When the prefetch call at a site * generates oids that are found/not found in the prefetch cache, * we take action accordingly */ @@ -51,13 +51,13 @@ void handleDynPrefetching(int numLocal, int ntuples, int siteid) { if(getOperationMode(siteid) != 0) { evalPrefetch[siteid].uselesscount--; if(evalPrefetch[siteid].uselesscount <= 0) { - evalPrefetch[siteid].operMode = 0; + evalPrefetch[siteid].operMode = 0; } } } } -/* This function clears from prefetch cache those +/* This function clears from prefetch cache those * entries that caused a transaction abort */ void cleanPCache(thread_data_array_t *tdata) { transrecord_t *rec = tdata->rec; @@ -67,13 +67,13 @@ void cleanPCache(thread_data_array_t *tdata) { for(i = 0; i < size; i++) { chashlistnode_t *curr = &ptr[i]; //for each entry in the cache lookupTable while(curr != NULL) { - if(curr->key == 0) - break; + if(curr->key == 0) + break; objheader_t *header1, *header2; if((header1 = mhashSearch(curr->key)) == NULL && ((header2 = prehashSearch(curr->key)) != NULL)) { - /* Not found in local machine's object store and found in prefetch cache */ - /* Remove from prefetch cache */ - prehashRemove(curr->key); + /* Not found in local machine's object store and found in prefetch cache */ + /* Remove from prefetch cache */ + prehashRemove(curr->key); } curr = curr->next; } @@ -81,9 +81,9 @@ void cleanPCache(thread_data_array_t *tdata) { } /* This function updates the prefetch cache with - * entires from the transaction cache when a - * transaction commits - * Return -1 on error else returns 0 */ + * entires from the transaction cache when a + * transaction commits + * Return -1 on error else returns 0 */ int updatePrefetchCache(thread_data_array_t* tdata) { int retval; char oidType; @@ -100,14 +100,14 @@ int updatePrefetchCache(thread_data_array_t* tdata) { return 0; } -int copyToCache(int numoid, unsigned int *oidarray, thread_data_array_t *tdata, char oidType) { +int copyToCache(int numoid, unsigned int *oidarray, thread_data_array_t *tdata, char oidType) { int i; for (i = 0; i < numoid; i++) { unsigned int oid; if(oidType == 'R') { char * objread = (char *) oidarray; oid = *((unsigned int *)(objread+(sizeof(unsigned int)+ - sizeof(unsigned short))*i)); + sizeof(unsigned short))*i)); } else { oid = oidarray[i]; } @@ -123,8 +123,8 @@ int copyToCache(int numoid, unsigned int *oidarray, thread_data_array_t *tdata, GETSIZE(size, header); objheader_t * newAddr; if((newAddr = prefetchobjstrAlloc(size + sizeof(objheader_t))) == NULL) { - printf("%s(): Error in getting memory from prefetch cache at %s, %d\n", __func__, - __FILE__, __LINE__); + printf("%s(): Error in getting memory from prefetch cache at %s, %d\n", __func__, + __FILE__, __LINE__); pthread_mutex_unlock(&prefetchcache_mutex); return -1; } diff --git a/Robust/src/Runtime/DSTM/interface/addPrefetchEnhance.h b/Robust/src/Runtime/DSTM/interface/addPrefetchEnhance.h index a335c0ac..5336451f 100644 --- a/Robust/src/Runtime/DSTM/interface/addPrefetchEnhance.h +++ b/Robust/src/Runtime/DSTM/interface/addPrefetchEnhance.h @@ -6,8 +6,8 @@ #include "gCollect.h" typedef struct prefetchCountStats { - int retrycount; /* keeps track of when to retry and check if we can turn on this prefetch site */ - int uselesscount; /* keeps track of how long was the prefetching at site useles */ + int retrycount; /* keeps track of when to retry and check if we can turn on this prefetch site */ + int uselesscount; /* keeps track of how long was the prefetching at site useles */ char operMode; /* 1 = on , 0 = off */ int callcount; } pfcstats_t; @@ -19,6 +19,6 @@ char getOperationMode(int); void handleDynPrefetching(int, int, int); void cleanPCache(thread_data_array_t *tdata); int updatePrefetchCache(thread_data_array_t *); -int copyToCache(int , unsigned int *, thread_data_array_t *, char ); +int copyToCache(int, unsigned int *, thread_data_array_t *, char); #endif diff --git a/Robust/src/Runtime/DSTM/interface/addUdpEnhance.c b/Robust/src/Runtime/DSTM/interface/addUdpEnhance.c index defb77f3..bd080de8 100644 --- a/Robust/src/Runtime/DSTM/interface/addUdpEnhance.c +++ b/Robust/src/Runtime/DSTM/interface/addUdpEnhance.c @@ -50,7 +50,7 @@ int udpInit() { exit(1); } -#ifdef MAC +#ifdef MAC if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &setsockflag, sizeof(setsockflag)) < 0) { perror("socket"); exit(1); @@ -89,14 +89,15 @@ void *udpListenBroadcast(void *sockfd) { } short status = *((short *) &readBuffer[0]); switch (status) { - case INVALIDATE_OBJS: - if((retval = invalidateFromPrefetchCache(readBuffer))!= 0) { - printf("Error: In invalidateFromPrefetchCache() at %s, %d\n", __FILE__, __LINE__); - break; - } - break; - default: - printf("Error: Cannot regcognize the status in file %s, at line %d\n", __FILE__, __LINE__); + case INVALIDATE_OBJS: + if((retval = invalidateFromPrefetchCache(readBuffer))!= 0) { + printf("Error: In invalidateFromPrefetchCache() at %s, %d\n", __FILE__, __LINE__); + break; + } + break; + + default: + printf("Error: Cannot regcognize the status in file %s, at line %d\n", __FILE__, __LINE__); } } @@ -132,15 +133,15 @@ int invalidateObj(thread_data_array_t *tdata) { int i; for(i = 1; i <= maxUdpMsg; i++) { if((retval = sendUdpMsg(tdata, &clientaddr, i)) < 0) { - printf("%s() error in sending udp message at %s, %d\n", __func__, __FILE__, __LINE__); - return -1; + printf("%s() error in sending udp message at %s, %d\n", __func__, __FILE__, __LINE__); + return -1; } } } return 0; } -/* Function sends a udp broadcast, also distinguishes +/* Function sends a udp broadcast, also distinguishes * msg size to be sent based on the iteration flag * returns -1 on error and 0 on success */ int sendUdpMsg(thread_data_array_t *tdata, struct sockaddr_in *clientaddr, int iteration) { @@ -152,7 +153,7 @@ int sendUdpMsg(thread_data_array_t *tdata, struct sockaddr_in *clientaddr, int i *((unsigned int *)(writeBuffer+offset)) = myIpAddr; //mid sending invalidation offset += sizeof(unsigned int); if(iteration == 0) { // iteration flag == zero, send single udp msg - *((short *) (writeBuffer+offset)) = (short) (sizeof(unsigned int) * (tdata->buffer->f.nummod)); //sizeof msg + *((short *)(writeBuffer+offset)) = (short) (sizeof(unsigned int) * (tdata->buffer->f.nummod)); //sizeof msg offset += sizeof(short); int i; for(i = 0; i < tdata->buffer->f.nummod; i++) { @@ -161,11 +162,11 @@ int sendUdpMsg(thread_data_array_t *tdata, struct sockaddr_in *clientaddr, int i } } else { // iteration flag > zero, send multiple udp msg int numObj; - if((tdata->buffer->f.nummod - (iteration * maxObjsPerMsg)) > 0) + if((tdata->buffer->f.nummod - (iteration * maxObjsPerMsg)) > 0) numObj = maxObjsPerMsg; - else + else numObj = tdata->buffer->f.nummod - ((iteration - 1)*maxObjsPerMsg); - *((short *) (writeBuffer+offset)) = (short) (sizeof(unsigned int) * numObj); + *((short *)(writeBuffer+offset)) = (short) (sizeof(unsigned int) * numObj); offset += sizeof(short); int index = (iteration - 1) * maxObjsPerMsg; int i; @@ -181,9 +182,9 @@ int sendUdpMsg(thread_data_array_t *tdata, struct sockaddr_in *clientaddr, int i return -1; } return 0; -} +} -/* Function searches given oid in prefetch cache and invalidates obj from cache +/* Function searches given oid in prefetch cache and invalidates obj from cache * returns -1 on error and 0 on success */ int invalidateFromPrefetchCache(char *buffer) { int offset = sizeof(short); @@ -202,7 +203,7 @@ int invalidateFromPrefetchCache(char *buffer) { objheader_t *header; /* Lookup Objects in prefetch cache and remove them */ if(((header = prehashSearch(oid)) != NULL)) { - prehashRemove(oid); + prehashRemove(oid); } offset += sizeof(unsigned int); } diff --git a/Robust/src/Runtime/DSTM/interface/addUdpEnhance.h b/Robust/src/Runtime/DSTM/interface/addUdpEnhance.h index 1691473d..21a4d12a 100644 --- a/Robust/src/Runtime/DSTM/interface/addUdpEnhance.h +++ b/Robust/src/Runtime/DSTM/interface/addUdpEnhance.h @@ -22,6 +22,6 @@ int createUdpSocket(); int udpInit(); void *udpListenBroadcast(void *); int invalidateObj(thread_data_array_t *); -int invalidateFromPrefetchCache(char *); +int invalidateFromPrefetchCache(char *); int sendUdpMsg(thread_data_array_t *, struct sockaddr_in *, int); #endif diff --git a/Robust/src/Runtime/DSTM/interface/clookup.c b/Robust/src/Runtime/DSTM/interface/clookup.c index 4d834071..0f6fa5c0 100644 --- a/Robust/src/Runtime/DSTM/interface/clookup.c +++ b/Robust/src/Runtime/DSTM/interface/clookup.c @@ -3,33 +3,33 @@ chashtable_t *chashCreate(unsigned int size, float loadfactor) { chashtable_t *ctable; - chashlistnode_t *nodes; - int i; - + chashlistnode_t *nodes; + int i; + if((ctable = calloc(1, sizeof(chashtable_t))) == NULL) { printf("Calloc error %s %d\n", __FILE__, __LINE__); return NULL; - } - - // Allocate space for the hash table - if((nodes = calloc(size, sizeof(chashlistnode_t))) == NULL) { + } + + // Allocate space for the hash table + if((nodes = calloc(size, sizeof(chashlistnode_t))) == NULL) { printf("Calloc error %s %d\n", __FILE__, __LINE__); free(ctable); return NULL; - } - + } + ctable->table = nodes; - ctable->size = size; + ctable->size = size; ctable->mask = (size << 1)-1; ctable->numelements = 0; // Initial number of elements in the hash ctable->loadfactor = loadfactor; - + return ctable; } //Finds the right bin in the hash table static INLINE unsigned int chashFunction(chashtable_t *table, unsigned int key) { - return ( key & (table->mask))>>1;//throw away low order bit + return ( key & (table->mask))>>1; //throw away low order bit } //Store objects and their pointers into hash @@ -37,7 +37,7 @@ unsigned int chashInsert(chashtable_t *table, unsigned int key, void *val) { unsigned int newsize; int index; chashlistnode_t *ptr, *node; - + if(table->numelements > (table->loadfactor * table->size)) { //Resize newsize = table->size << 1; @@ -50,7 +50,7 @@ unsigned int chashInsert(chashtable_t *table, unsigned int key, void *val) { #ifdef DEBUG printf("chashInsert(): DEBUG -> index = %d, key = %d, val = %x\n", index, key, val); #endif - if(ptr[index].next == NULL && ptr[index].key == 0) { // Insert at the first position in the hashtable + if(ptr[index].next == NULL && ptr[index].key == 0) { // Insert at the first position in the hashtable ptr[index].key = key; ptr[index].val = val; } else { // Insert in the beginning of linked list @@ -70,7 +70,7 @@ unsigned int chashInsert(chashtable_t *table, unsigned int key, void *val) { INLINE void * chashSearch(chashtable_t *table, unsigned int key) { //REMOVE HASH FUNCTION CALL TO MAKE SURE IT IS INLINED HERE chashlistnode_t *node = &table->table[(key & table->mask)>>1]; - + while(node != NULL) { if(node->key == key) { return node->val; @@ -84,7 +84,7 @@ unsigned int chashRemove(chashtable_t *table, unsigned int key) { int index; chashlistnode_t *curr, *prev; chashlistnode_t *ptr, *node; - + ptr = table->table; index = chashFunction(table,key); curr = &ptr[index]; @@ -92,87 +92,87 @@ unsigned int chashRemove(chashtable_t *table, unsigned int key) { for (; curr != NULL; curr = curr->next) { 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 + if ((curr == &ptr[index]) && (curr->next == NULL)) { // Delete the first item inside the hashtable with no linked list of chashlistnode_t curr->key = 0; curr->val = NULL; - } else if ((curr == &ptr[index]) && (curr->next != NULL)) { //Delete the first item with a linked list of chashlistnode_t connected + } 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; curr->val = curr->next->val; node = curr->next; curr->next = curr->next->next; free(node); - } else { // Regular delete from linked listed + } else { // Regular delete from linked listed prev->next = curr->next; free(curr); } return 0; - } - prev = curr; + } + prev = curr; } return 1; } unsigned int chashResize(chashtable_t *table, unsigned int newsize) { - chashlistnode_t *node, *ptr, *curr, *next; // curr and next keep track of the current and the next chashlistnodes in a linked list + chashlistnode_t *node, *ptr, *curr, *next; // curr and next keep track of the current and the next chashlistnodes in a linked list unsigned int oldsize; int isfirst; // Keeps track of the first element in the chashlistnode_t for each bin in hashtable - int i,index; - chashlistnode_t *newnode; - + int i,index; + chashlistnode_t *newnode; + ptr = table->table; oldsize = table->size; - + if((node = calloc(newsize, sizeof(chashlistnode_t))) == NULL) { printf("Calloc error %s %d\n", __FILE__, __LINE__); return 1; } - - table->table = node; //Update the global hashtable upon resize() + + table->table = node; //Update the global hashtable upon resize() table->size = newsize; table->mask = (newsize << 1)-1; table->numelements = 0; - - for(i = 0; i < oldsize; i++) { //Outer loop for each bin in hash table + + for(i = 0; i < oldsize; i++) { //Outer loop for each bin in hash table curr = &ptr[i]; - isfirst = 1; - while (curr != NULL) { //Inner loop to go through linked lists - if (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 + isfirst = 1; + while (curr != NULL) { //Inner loop to go through linked lists + if (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 } next = curr->next; - + index = chashFunction(table, curr->key); #ifdef DEBUG printf("DEBUG(resize) -> index = %d, key = %d, val = %x\n", index, curr->key, curr->val); #endif // Insert into the new table - if(table->table[index].next == NULL && table->table[index].key == 0) { + if(table->table[index].next == NULL && table->table[index].key == 0) { table->table[index].key = curr->key; table->table[index].val = curr->val; table->numelements++; - }else { - if((newnode = calloc(1, sizeof(chashlistnode_t))) == NULL) { + } else { + if((newnode = calloc(1, sizeof(chashlistnode_t))) == NULL) { printf("Calloc error %s, %d\n", __FILE__, __LINE__); return 1; - } + } newnode->key = curr->key; newnode->val = curr->val; newnode->next = table->table[index].next; - table->table[index].next = newnode; + table->table[index].next = newnode; table->numelements++; - } - + } + //free the linked list of chashlistnode_t if not the first element in the hash table if (isfirst != 1) { free(curr); - } - + } + isfirst = 0; curr = next; } } - - free(ptr); //Free the memory of the old hash table + + free(ptr); //Free the memory of the old hash table return 0; } @@ -181,7 +181,7 @@ void chashDelete(chashtable_t *ctable) { int i, isFirst; chashlistnode_t *ptr, *curr, *next; ptr = ctable->table; - + for(i=0 ; isize ; i++) { curr = &ptr[i]; isFirst = 1 ; @@ -194,7 +194,7 @@ void chashDelete(chashtable_t *ctable) { curr = next; } } - + free(ptr); ptr = NULL; free(ctable); diff --git a/Robust/src/Runtime/DSTM/interface/clookup.h b/Robust/src/Runtime/DSTM/interface/clookup.h index 475a66f0..4a078d2c 100644 --- a/Robust/src/Runtime/DSTM/interface/clookup.h +++ b/Robust/src/Runtime/DSTM/interface/clookup.h @@ -8,13 +8,13 @@ #define CHASH_SIZE 1024 typedef struct chashlistnode { - unsigned int key; - void *val; //this can be cast to another type or used to point to a larger structure - struct chashlistnode *next; + unsigned int key; + void *val; //this can be cast to another type or used to point to a larger structure + struct chashlistnode *next; } chashlistnode_t; typedef struct chashtable { - chashlistnode_t *table; // points to beginning of hash table + chashlistnode_t *table; // points to beginning of hash table unsigned int size; unsigned int mask; unsigned int numelements; diff --git a/Robust/src/Runtime/DSTM/interface/dht.c b/Robust/src/Runtime/DSTM/interface/dht.c index cccbcfcd..768a8e33 100644 --- a/Robust/src/Runtime/DSTM/interface/dht.c +++ b/Robust/src/Runtime/DSTM/interface/dht.c @@ -65,72 +65,71 @@ //make sure this matches msg_types global var enum { - INSERT_CMD, - INSERT_RES, - REMOVE_CMD, - REMOVE_RES, - SEARCH_CMD, - SEARCH_RES, - WHO_IS_LEADER_CMD, - WHO_IS_LEADER_RES, - JOIN_REQ, - JOIN_RES, - LEAVE_REQ, - LEAVE_RES, - DHT_UPDATE_CMD, - DHT_UPDATE_RES, - ELECT_LEADER_CMD, - ELECT_LEADER_RES, - CONGRATS_CMD, - REBUILD_REQ, - REBUILD_CMD, - FILL_DHT_CMD, - FILL_DHT_RES, - RESUME_NORMAL_CMD, - RESUME_NORMAL_RES, - NUM_MSG_TYPES + INSERT_CMD, + INSERT_RES, + REMOVE_CMD, + REMOVE_RES, + SEARCH_CMD, + SEARCH_RES, + WHO_IS_LEADER_CMD, + WHO_IS_LEADER_RES, + JOIN_REQ, + JOIN_RES, + LEAVE_REQ, + LEAVE_RES, + DHT_UPDATE_CMD, + DHT_UPDATE_RES, + ELECT_LEADER_CMD, + ELECT_LEADER_RES, + CONGRATS_CMD, + REBUILD_REQ, + REBUILD_CMD, + FILL_DHT_CMD, + FILL_DHT_RES, + RESUME_NORMAL_CMD, + RESUME_NORMAL_RES, + NUM_MSG_TYPES }; //states //make sure this matches state_names, timeout_vals, and retry_vals global vars enum { - INIT1_STATE, - INIT2_STATE, - NORMAL_STATE, - LEAD_NORMAL1_STATE, - LEAD_NORMAL2_STATE, - ELECT1_STATE, - ELECT2_STATE, - REBUILD0_STATE, - REBUILD1_STATE, - REBUILD2_STATE, - REBUILD3_STATE, - REBUILD4_STATE, - REBUILD5_STATE, - LEAD_REBUILD1_STATE, - LEAD_REBUILD2_STATE, - LEAD_REBUILD3_STATE, - LEAD_REBUILD4_STATE, - EXIT1_STATE, - EXIT2_STATE, - NUM_STATES + INIT1_STATE, + INIT2_STATE, + NORMAL_STATE, + LEAD_NORMAL1_STATE, + LEAD_NORMAL2_STATE, + ELECT1_STATE, + ELECT2_STATE, + REBUILD0_STATE, + REBUILD1_STATE, + REBUILD2_STATE, + REBUILD3_STATE, + REBUILD4_STATE, + REBUILD5_STATE, + LEAD_REBUILD1_STATE, + LEAD_REBUILD2_STATE, + LEAD_REBUILD3_STATE, + LEAD_REBUILD4_STATE, + EXIT1_STATE, + EXIT2_STATE, + NUM_STATES }; //status codes enum { - OPERATION_OK, - KEY_NOT_FOUND, - NOT_KEY_OWNER, - NOT_LEADER, - INTERNAL_ERROR + OPERATION_OK, + KEY_NOT_FOUND, + NOT_KEY_OWNER, + NOT_LEADER, + INTERNAL_ERROR }; -struct hostData -{ - unsigned int ipAddr; - unsigned int maxKeyCapacity; +struct hostData { + unsigned int ipAddr; + unsigned int maxKeyCapacity; }; /******************************************************************************* @@ -166,99 +165,98 @@ void *udpListen(); //make sure this matches enumeration above const char *msg_types[NUM_MSG_TYPES] = { - "INSERT_CMD", - "INSERT_RES", - "REMOVE_CMD", - "REMOVE_RES", - "SEARCH_CMD", - "SEARCH_RES", - "WHO_IS_LEADER_CMD", - "WHO_IS_LEADER_RES", - "JOIN_REQ", - "JOIN_RES", - "LEAVE_REQ", - "LEAVE_RES", - "DHT_UPDATE_CMD", - "DHT_UPDATE_RES", - "ELECT_LEADER_CMD", - "ELECT_LEADER_RES", - "CONGRATS_CMD", - "REBUILD_REQ", - "REBUILD_CMD", - "FILL_DHT_CMD", - "FILL_DHT_RES", - "RESUME_NORMAL_CMD", - "RESUME_NORMAL_RES" + "INSERT_CMD", + "INSERT_RES", + "REMOVE_CMD", + "REMOVE_RES", + "SEARCH_CMD", + "SEARCH_RES", + "WHO_IS_LEADER_CMD", + "WHO_IS_LEADER_RES", + "JOIN_REQ", + "JOIN_RES", + "LEAVE_REQ", + "LEAVE_RES", + "DHT_UPDATE_CMD", + "DHT_UPDATE_RES", + "ELECT_LEADER_CMD", + "ELECT_LEADER_RES", + "CONGRATS_CMD", + "REBUILD_REQ", + "REBUILD_CMD", + "FILL_DHT_CMD", + "FILL_DHT_RES", + "RESUME_NORMAL_CMD", + "RESUME_NORMAL_RES" }; const char *state_names[NUM_STATES] = { - "INIT1_STATE", - "INIT2_STATE", - "NORMAL_STATE", - "LEAD_NORMAL1_STATE", - "LEAD_NORMAL2_STATE", - "ELECT1_STATE", - "ELECT2_STATE", - "REBUILD0_STATE", - "REBUILD1_STATE", - "REBUILD2_STATE", - "REBUILD3_STATE", - "REBUILD4_STATE", - "REBUILD5_STATE", - "LEAD_REBUILD1_STATE", - "LEAD_REBUILD2_STATE", - "LEAD_REBUILD3_STATE", - "LEAD_REBUILD4_STATE", - "EXIT1_STATE", - "EXIT2_STATE", + "INIT1_STATE", + "INIT2_STATE", + "NORMAL_STATE", + "LEAD_NORMAL1_STATE", + "LEAD_NORMAL2_STATE", + "ELECT1_STATE", + "ELECT2_STATE", + "REBUILD0_STATE", + "REBUILD1_STATE", + "REBUILD2_STATE", + "REBUILD3_STATE", + "REBUILD4_STATE", + "REBUILD5_STATE", + "LEAD_REBUILD1_STATE", + "LEAD_REBUILD2_STATE", + "LEAD_REBUILD3_STATE", + "LEAD_REBUILD4_STATE", + "EXIT1_STATE", + "EXIT2_STATE", }; //note: { 0, 0 } means no timeout -struct timeval timeout_vals[NUM_STATES] = -{ - { 0, 500000 }, //INIT1_STATE - { 0, 500000 }, //INIT2_STATE - { 0, 0 }, //NORMAL_STATE - { 0, 0 }, //LEAD_NORMAL1_STATE - { 3, 0 }, //LEAD_NORMAL2_STATE - { 1, 0 }, //ELECT1_STATE - { 1, 0 }, //ELECT2_STATE - { 0, 500000 }, //REBUILD0_STATE - { 0, 500000 }, //REBUILD1_STATE - { 10, 0 }, //REBUILD2_STATE - { 10, 0 }, //REBUILD3_STATE - { 10, 0 }, //REBUILD4_STATE - { 1, 0 }, //REBUILD5_STATE - { 1, 0 }, //LEAD_REBUILD1_STATE - { 1, 0 }, //LEAD_REBUILD2_STATE - { 10, 0 }, //LEAD_REBUILD3_STATE - { 10, 0 }, //LEAD_REBUILD4_STATE - { 0, 500000 }, //EXIT1_STATE - { 0, 0 } //EXIT2_STATE +struct timeval timeout_vals[NUM_STATES] ={ + { 0, 500000 }, //INIT1_STATE + { 0, 500000 }, //INIT2_STATE + { 0, 0 }, //NORMAL_STATE + { 0, 0 }, //LEAD_NORMAL1_STATE + { 3, 0 }, //LEAD_NORMAL2_STATE + { 1, 0 }, //ELECT1_STATE + { 1, 0 }, //ELECT2_STATE + { 0, 500000 }, //REBUILD0_STATE + { 0, 500000 }, //REBUILD1_STATE + { 10, 0 }, //REBUILD2_STATE + { 10, 0 }, //REBUILD3_STATE + { 10, 0 }, //REBUILD4_STATE + { 1, 0 }, //REBUILD5_STATE + { 1, 0 }, //LEAD_REBUILD1_STATE + { 1, 0 }, //LEAD_REBUILD2_STATE + { 10, 0 }, //LEAD_REBUILD3_STATE + { 10, 0 }, //LEAD_REBUILD4_STATE + { 0, 500000 }, //EXIT1_STATE + { 0, 0 } //EXIT2_STATE }; int retry_vals[NUM_STATES] = { - 100, //INIT1_STATE - 10, //INIT2_STATE - 0, //NORMAL_STATE - 0, //LEAD_NORMAL1_STATE - 0, //LEAD_NORMAL2_STATE - 10, //ELECT1_STATE - 10, //ELECT2_STATE - 10, //REBUILD0_STATE - 10, //REBUILD1_STATE - 0, //REBUILD2_STATE - 0, //REBUILD3_STATE - 0, //REBUILD4_STATE - 10, //REBUILD5_STATE - 10, //LEAD_REBUILD1_STATE - 10, //LEAD_REBUILD2_STATE - 10, //LEAD_REBUILD3_STATE - 10, //LEAD_REBUILD4_STATE - 10, //EXIT1_STATE - 0 //EXIT2_STATE + 100, //INIT1_STATE + 10, //INIT2_STATE + 0, //NORMAL_STATE + 0, //LEAD_NORMAL1_STATE + 0, //LEAD_NORMAL2_STATE + 10, //ELECT1_STATE + 10, //ELECT2_STATE + 10, //REBUILD0_STATE + 10, //REBUILD1_STATE + 0, //REBUILD2_STATE + 0, //REBUILD3_STATE + 0, //REBUILD4_STATE + 10, //REBUILD5_STATE + 10, //LEAD_REBUILD1_STATE + 10, //LEAD_REBUILD2_STATE + 10, //LEAD_REBUILD3_STATE + 10, //LEAD_REBUILD4_STATE + 10, //EXIT1_STATE + 0 //EXIT2_STATE }; FILE *logfile; @@ -290,1461 +288,1365 @@ int timeoutCntr; * Interface Function Definitions *******************************************************************************/ -void dhtInit(unsigned int seedIpAddr, unsigned int maxKeyCapacity) -{ - struct in_addr tmpAddr; - char filename[23] = "dht-"; - struct sockaddr_in myAddr; - struct sockaddr_in seedAddr; - socklen_t socklen = sizeof(struct sockaddr_in); - char initMsg; - - tmpAddr.s_addr = htonl(getMyIpAddr(DEFAULT_INTERFACE)); - strcat(filename, inet_ntoa(tmpAddr)); - strcat(filename, ".log"); - printf("log file: %s\n", filename); - - logfile = fopen(filename, "w"); - dhtLog("dhtInit(): inializing...\n"); - - myHostData.ipAddr = getMyIpAddr(DEFAULT_INTERFACE); - myHostData.maxKeyCapacity = maxKeyCapacity; - - seed = seedIpAddr; - leader = 0; - electionOriginator = 0; - electionParent = 0; - hostArraySize = INIT_HOST_ALLOC; - hostArray = calloc(hostArraySize, sizeof(struct hostData)); - hostReplied = calloc(hostArraySize, sizeof(unsigned char)); - hostArray[0] = myHostData; - numHosts = 1; - numBlocks = INIT_NUM_BLOCKS; - blockOwnerArray = calloc(numBlocks, sizeof(unsigned short)); - pthread_mutex_init(&stateMutex, NULL); - pthread_cond_init(&stateCond, NULL); - myHashTable = chashCreate(HASH_SIZE, LOADFACTOR); - - udpPollSock.fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - if (udpPollSock.fd < 0) - perror("dhtInit():socket()"); - - udpPollSock.events = POLLIN; - - bzero(&myAddr, socklen); - myAddr.sin_family = AF_INET; - myAddr.sin_addr.s_addr = htonl(INADDR_ANY); - myAddr.sin_port = htons(UDP_PORT); - - if (bind(udpPollSock.fd, (struct sockaddr *)&myAddr, socklen) < 0) - perror("dhtInit():bind()"); - - if (seed == 0) - { - dhtLog("I am the leader\n"); - leader = myHostData.ipAddr; - setState(LEAD_NORMAL1_STATE); - } - else - { - initMsg = WHO_IS_LEADER_CMD; - udpSend(&initMsg, 1, seed); - setState(INIT1_STATE); - } - - if (pthread_create(&threadUdpListen, NULL, udpListen, NULL) != 0) - dhtLog("dhtInit() - ERROR creating threadUdpListen\n"); - - return; +void dhtInit(unsigned int seedIpAddr, unsigned int maxKeyCapacity) { + struct in_addr tmpAddr; + char filename[23] = "dht-"; + struct sockaddr_in myAddr; + struct sockaddr_in seedAddr; + socklen_t socklen = sizeof(struct sockaddr_in); + char initMsg; + + tmpAddr.s_addr = htonl(getMyIpAddr(DEFAULT_INTERFACE)); + strcat(filename, inet_ntoa(tmpAddr)); + strcat(filename, ".log"); + printf("log file: %s\n", filename); + + logfile = fopen(filename, "w"); + dhtLog("dhtInit(): inializing...\n"); + + myHostData.ipAddr = getMyIpAddr(DEFAULT_INTERFACE); + myHostData.maxKeyCapacity = maxKeyCapacity; + + seed = seedIpAddr; + leader = 0; + electionOriginator = 0; + electionParent = 0; + hostArraySize = INIT_HOST_ALLOC; + hostArray = calloc(hostArraySize, sizeof(struct hostData)); + hostReplied = calloc(hostArraySize, sizeof(unsigned char)); + hostArray[0] = myHostData; + numHosts = 1; + numBlocks = INIT_NUM_BLOCKS; + blockOwnerArray = calloc(numBlocks, sizeof(unsigned short)); + pthread_mutex_init(&stateMutex, NULL); + pthread_cond_init(&stateCond, NULL); + myHashTable = chashCreate(HASH_SIZE, LOADFACTOR); + + udpPollSock.fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (udpPollSock.fd < 0) + perror("dhtInit():socket()"); + + udpPollSock.events = POLLIN; + + bzero(&myAddr, socklen); + myAddr.sin_family = AF_INET; + myAddr.sin_addr.s_addr = htonl(INADDR_ANY); + myAddr.sin_port = htons(UDP_PORT); + + if (bind(udpPollSock.fd, (struct sockaddr *)&myAddr, socklen) < 0) + perror("dhtInit():bind()"); + + if (seed == 0){ + dhtLog("I am the leader\n"); + leader = myHostData.ipAddr; + setState(LEAD_NORMAL1_STATE); + } else + { + initMsg = WHO_IS_LEADER_CMD; + udpSend(&initMsg, 1, seed); + setState(INIT1_STATE); + } + + if (pthread_create(&threadUdpListen, NULL, udpListen, NULL) != 0) + dhtLog("dhtInit() - ERROR creating threadUdpListen\n"); + + return; } -void dhtExit() -{ //TODO: do this gracefully, wait for response from leader, etc. - char msg; +void dhtExit() { //TODO: do this gracefully, wait for response from leader, etc. + char msg; - msg = LEAVE_REQ; - udpSend(&msg, 1, leader); - dhtLog("dhtExit(): cleaning up...\n"); - pthread_cancel(threadUdpListen); - close(udpPollSock.fd); - free(hostArray); - free(hostReplied); - free(blockOwnerArray); - fclose(logfile); + msg = LEAVE_REQ; + udpSend(&msg, 1, leader); + dhtLog("dhtExit(): cleaning up...\n"); + pthread_cancel(threadUdpListen); + close(udpPollSock.fd); + free(hostArray); + free(hostReplied); + free(blockOwnerArray); + fclose(logfile); - return; + return; } -int dhtInsert(unsigned int key, unsigned int val) -{ - struct sockaddr_in toAddr; - struct sockaddr_in fromAddr; - socklen_t socklen = sizeof(struct sockaddr_in); - struct pollfd pollsock; - char inBuffer[2]; - char outBuffer[9]; - ssize_t bytesRcvd; - int i; - int retval; - int status = -1; - - bzero((char *)&toAddr, socklen); - toAddr.sin_family = AF_INET; - toAddr.sin_port = htons(UDP_PORT); - - while (status != OPERATION_OK) - { - pthread_mutex_lock(&stateMutex); - while (!(state == NORMAL_STATE || state == LEAD_NORMAL1_STATE - || state == LEAD_NORMAL2_STATE || state == REBUILD4_STATE - || state == LEAD_REBUILD3_STATE)) - pthread_cond_wait(&stateCond, &stateMutex); - toAddr.sin_addr.s_addr = htonl(getKeyOwner(key)); - pthread_mutex_unlock(&stateMutex); - - if ((pollsock.fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) - { - perror("dhtInsert():socket()"); - return -1; - } - pollsock.events = POLLIN; - - outBuffer[0] = INSERT_CMD; - write4(&outBuffer[1], key); - write4(&outBuffer[5], val); - - for (i = 0; i < INSERT_RETRIES; i++) - { - if (sendto(pollsock.fd, outBuffer, 9, 0, (struct sockaddr *)&toAddr, - socklen) < 0) - { - perror("dhtInsert():sendto()"); - break; - } - retval = poll(&pollsock, 1, INSERT_TIMEOUT_MS); - if (retval < 0) - { - 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; - } - } - } - if (status != OPERATION_OK) - { - pthread_mutex_lock(&stateMutex); - setState(REBUILD0_STATE); - outBuffer[0] = REBUILD_REQ; - udpSend(outBuffer, 1, leader); - pthread_mutex_unlock(&stateMutex); - } +int dhtInsert(unsigned int key, unsigned int val) { + struct sockaddr_in toAddr; + struct sockaddr_in fromAddr; + socklen_t socklen = sizeof(struct sockaddr_in); + struct pollfd pollsock; + char inBuffer[2]; + char outBuffer[9]; + ssize_t bytesRcvd; + int i; + int retval; + int status = -1; + + bzero((char *)&toAddr, socklen); + toAddr.sin_family = AF_INET; + toAddr.sin_port = htons(UDP_PORT); + + while (status != OPERATION_OK){ + pthread_mutex_lock(&stateMutex); + while (!(state == NORMAL_STATE || state == LEAD_NORMAL1_STATE + || state == LEAD_NORMAL2_STATE || state == REBUILD4_STATE + || state == LEAD_REBUILD3_STATE)) + pthread_cond_wait(&stateCond, &stateMutex); + toAddr.sin_addr.s_addr = htonl(getKeyOwner(key)); + pthread_mutex_unlock(&stateMutex); + + if ((pollsock.fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0){ + perror("dhtInsert():socket()"); + return -1; + } + pollsock.events = POLLIN; + + outBuffer[0] = INSERT_CMD; + write4(&outBuffer[1], key); + write4(&outBuffer[5], val); + + for (i = 0; i < INSERT_RETRIES; i++) + { + if (sendto(pollsock.fd, outBuffer, 9, 0, (struct sockaddr *)&toAddr, + socklen) < 0){ + perror("dhtInsert():sendto()"); + break; + } + retval = poll(&pollsock, 1, INSERT_TIMEOUT_MS); + if (retval < 0){ + 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; } - - close(pollsock.fd); - - return status; + } + } + if (status != OPERATION_OK){ + pthread_mutex_lock(&stateMutex); + setState(REBUILD0_STATE); + outBuffer[0] = REBUILD_REQ; + udpSend(outBuffer, 1, leader); + pthread_mutex_unlock(&stateMutex); + } + } + + close(pollsock.fd); + + return status; } -int dhtInsertMult(unsigned int numKeys, unsigned int *keys, unsigned int *vals) -{ - int status; - int i; - - status = 0; - for (i = 0; i < numKeys; i++) - { - if (dhtInsert(keys[i], vals[i]) != 0) - status = -1; - } - return status; +int dhtInsertMult(unsigned int numKeys, unsigned int *keys, unsigned int *vals) { + int status; + int i; + + status = 0; + for (i = 0; i < numKeys; i++) + { + if (dhtInsert(keys[i], vals[i]) != 0) + status = -1; + } + return status; } -int dhtRemove(unsigned int key) -{ - struct sockaddr_in toAddr; - struct sockaddr_in fromAddr; - socklen_t socklen = sizeof(struct sockaddr_in); - struct pollfd pollsock; - char inBuffer[2]; - char outBuffer[5]; - ssize_t bytesRcvd; - int i; - int retval; - int status = -1; - - bzero((char *)&toAddr, socklen); - toAddr.sin_family = AF_INET; - toAddr.sin_port = htons(UDP_PORT); - - while (!(status == OPERATION_OK || status == KEY_NOT_FOUND)) - { - pthread_mutex_lock(&stateMutex); - while (!(state == NORMAL_STATE || state == LEAD_NORMAL1_STATE - || state == LEAD_NORMAL2_STATE)) - pthread_cond_wait(&stateCond, &stateMutex); - toAddr.sin_addr.s_addr = htonl(getKeyOwner(key)); - pthread_mutex_unlock(&stateMutex); - - if ((pollsock.fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) - { - perror("dhtRemove():socket()"); - return -1; - } - pollsock.events = POLLIN; - - outBuffer[0] = REMOVE_CMD; - write4(&outBuffer[1], key); - - for (i = 0; i < REMOVE_RETRIES; i++) - { - if (sendto(pollsock.fd, outBuffer, 5, 0, (struct sockaddr *)&toAddr, - socklen) < 0) - { - perror("dhtRemove():sendto()"); - break; - } - retval = poll(&pollsock, 1, REMOVE_TIMEOUT_MS); - if (retval < 0) - { - 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; - } - } - } - if (!(status == OPERATION_OK || status == KEY_NOT_FOUND)) - { - pthread_mutex_lock(&stateMutex); - setState(REBUILD0_STATE); - outBuffer[0] = REBUILD_REQ; - udpSend(outBuffer, 1, leader); - pthread_mutex_unlock(&stateMutex); - } +int dhtRemove(unsigned int key) { + struct sockaddr_in toAddr; + struct sockaddr_in fromAddr; + socklen_t socklen = sizeof(struct sockaddr_in); + struct pollfd pollsock; + char inBuffer[2]; + char outBuffer[5]; + ssize_t bytesRcvd; + int i; + int retval; + int status = -1; + + bzero((char *)&toAddr, socklen); + toAddr.sin_family = AF_INET; + toAddr.sin_port = htons(UDP_PORT); + + while (!(status == OPERATION_OK || status == KEY_NOT_FOUND)){ + pthread_mutex_lock(&stateMutex); + while (!(state == NORMAL_STATE || state == LEAD_NORMAL1_STATE + || state == LEAD_NORMAL2_STATE)) + pthread_cond_wait(&stateCond, &stateMutex); + toAddr.sin_addr.s_addr = htonl(getKeyOwner(key)); + pthread_mutex_unlock(&stateMutex); + + if ((pollsock.fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0){ + perror("dhtRemove():socket()"); + return -1; + } + pollsock.events = POLLIN; + + outBuffer[0] = REMOVE_CMD; + write4(&outBuffer[1], key); + + for (i = 0; i < REMOVE_RETRIES; i++) + { + if (sendto(pollsock.fd, outBuffer, 5, 0, (struct sockaddr *)&toAddr, + socklen) < 0){ + perror("dhtRemove():sendto()"); + break; + } + retval = poll(&pollsock, 1, REMOVE_TIMEOUT_MS); + if (retval < 0){ + 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; } - - close(pollsock.fd); - - return status; + } + } + if (!(status == OPERATION_OK || status == KEY_NOT_FOUND)){ + pthread_mutex_lock(&stateMutex); + setState(REBUILD0_STATE); + outBuffer[0] = REBUILD_REQ; + udpSend(outBuffer, 1, leader); + pthread_mutex_unlock(&stateMutex); + } + } + + close(pollsock.fd); + + return status; } -int dhtRemoveMult(unsigned int numKeys, unsigned int *keys) -{ - int status; - int i; - - status = 0; - for (i = 0; i < numKeys; i++) - { - if (dhtRemove(keys[i]) != 0) - status = -1; - } - return status; +int dhtRemoveMult(unsigned int numKeys, unsigned int *keys) { + int status; + int i; + + status = 0; + for (i = 0; i < numKeys; i++) + { + if (dhtRemove(keys[i]) != 0) + status = -1; + } + return status; } -int dhtSearch(unsigned int key, unsigned int *val) -{ - struct sockaddr_in toAddr; - struct sockaddr_in fromAddr; - socklen_t socklen = sizeof(struct sockaddr_in); - struct pollfd pollsock; - char inBuffer[6]; - char outBuffer[5]; - ssize_t bytesRcvd; - int i; - int retval; - int status = -1; - - bzero((char *)&toAddr, socklen); - toAddr.sin_family = AF_INET; - toAddr.sin_port = htons(UDP_PORT); - - while (!(status == OPERATION_OK || status == KEY_NOT_FOUND)) - { - pthread_mutex_lock(&stateMutex); - while (numBlocks == 0) - pthread_cond_wait(&stateCond, &stateMutex); - toAddr.sin_addr.s_addr = htonl(getKeyOwner(key)); - pthread_mutex_unlock(&stateMutex); - - if ((pollsock.fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) - { - perror("dhtSearch():socket()"); - return -1; - } - pollsock.events = POLLIN; - - outBuffer[0] = SEARCH_CMD; - write4(&outBuffer[1], key); - - for (i = 0; i < SEARCH_RETRIES; i++) - { - if (sendto(pollsock.fd, outBuffer, 5, 0, (struct sockaddr *)&toAddr, - socklen) < 0) - { - perror("dhtSearch():sendto()"); - break; - } - retval = poll(&pollsock, 1, SEARCH_TIMEOUT_MS); - if (retval < 0) - { - 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; - } - } - } - if (!(status == OPERATION_OK || status == KEY_NOT_FOUND)) - { - pthread_mutex_lock(&stateMutex); - setState(REBUILD0_STATE); - outBuffer[0] = REBUILD_REQ; - udpSend(outBuffer, 1, leader); - pthread_mutex_unlock(&stateMutex); - } +int dhtSearch(unsigned int key, unsigned int *val) { + struct sockaddr_in toAddr; + struct sockaddr_in fromAddr; + socklen_t socklen = sizeof(struct sockaddr_in); + struct pollfd pollsock; + char inBuffer[6]; + char outBuffer[5]; + ssize_t bytesRcvd; + int i; + int retval; + int status = -1; + + bzero((char *)&toAddr, socklen); + toAddr.sin_family = AF_INET; + toAddr.sin_port = htons(UDP_PORT); + + while (!(status == OPERATION_OK || status == KEY_NOT_FOUND)){ + pthread_mutex_lock(&stateMutex); + while (numBlocks == 0) + pthread_cond_wait(&stateCond, &stateMutex); + toAddr.sin_addr.s_addr = htonl(getKeyOwner(key)); + pthread_mutex_unlock(&stateMutex); + + if ((pollsock.fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0){ + perror("dhtSearch():socket()"); + return -1; + } + pollsock.events = POLLIN; + + outBuffer[0] = SEARCH_CMD; + write4(&outBuffer[1], key); + + for (i = 0; i < SEARCH_RETRIES; i++) + { + if (sendto(pollsock.fd, outBuffer, 5, 0, (struct sockaddr *)&toAddr, + socklen) < 0){ + perror("dhtSearch():sendto()"); + break; + } + retval = poll(&pollsock, 1, SEARCH_TIMEOUT_MS); + if (retval < 0){ + 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; } - - close(pollsock.fd); - - return status; + } + } + if (!(status == OPERATION_OK || status == KEY_NOT_FOUND)){ + pthread_mutex_lock(&stateMutex); + setState(REBUILD0_STATE); + outBuffer[0] = REBUILD_REQ; + udpSend(outBuffer, 1, leader); + pthread_mutex_unlock(&stateMutex); + } + } + + close(pollsock.fd); + + return status; } -int dhtSearchMult(unsigned int numKeys, unsigned int *keys, unsigned int *vals) -{ - int i; - int status = 0; - for (i = 0; i < numKeys; i++) - { - if (dhtSearch(keys[i], &vals[i]) != 0) - status = -1; - } - return status; +int dhtSearchMult(unsigned int numKeys, unsigned int *keys, unsigned int *vals) { + int i; + int status = 0; + for (i = 0; i < numKeys; i++) + { + if (dhtSearch(keys[i], &vals[i]) != 0) + status = -1; + } + return status; } /******************************************************************************* * Local Function Definitions *******************************************************************************/ -int msgSizeOk(unsigned char *msg, unsigned int size) -{ - unsigned short tmpNumHosts; - unsigned short tmpNumBlocks; - - if (size < 1) - return 1; - - switch (msg[0]) - { - case WHO_IS_LEADER_CMD: - case LEAVE_REQ: - case LEAVE_RES: - case DHT_UPDATE_RES: - case REBUILD_REQ: - case REBUILD_CMD: - case FILL_DHT_CMD: - case FILL_DHT_RES: - case RESUME_NORMAL_CMD: - case RESUME_NORMAL_RES: - return (size == 1); - case INSERT_RES: - case REMOVE_RES: - case JOIN_RES: - return (size == 2); - case REMOVE_CMD: - case SEARCH_CMD: - case WHO_IS_LEADER_RES: - case JOIN_REQ: - case ELECT_LEADER_CMD: - return (size == 5); - case SEARCH_RES: - return (size == 6); - case INSERT_CMD: - return (size == 9); - case DHT_UPDATE_CMD: - if (size < 5) - return 1; - tmpNumHosts = read2(&msg[1]); - tmpNumBlocks = read2(&msg[3]); - return (size == (5+sizeof(struct hostData)*tmpNumHosts+2*tmpNumBlocks)); - case ELECT_LEADER_RES: - if (size < 2) - return 1; - if (msg[1] == 0xFF) - return (size == 2); - if (size < 4) - return 1; - tmpNumHosts = read2(&msg[2]); - return (size == (4 + sizeof(struct hostData) * tmpNumHosts)); - case CONGRATS_CMD: - if (size < 3) - return 1; - tmpNumHosts = read2(&msg[1]); - return (size == (3 + sizeof(struct hostData) * tmpNumHosts)); - default: - return 1; - } +int msgSizeOk(unsigned char *msg, unsigned int size) { + unsigned short tmpNumHosts; + unsigned short tmpNumBlocks; + + if (size < 1) + return 1; + + switch (msg[0]){ + case WHO_IS_LEADER_CMD: + case LEAVE_REQ: + case LEAVE_RES: + case DHT_UPDATE_RES: + case REBUILD_REQ: + case REBUILD_CMD: + case FILL_DHT_CMD: + case FILL_DHT_RES: + case RESUME_NORMAL_CMD: + case RESUME_NORMAL_RES: + return (size == 1); + + case INSERT_RES: + case REMOVE_RES: + case JOIN_RES: + return (size == 2); + + case REMOVE_CMD: + case SEARCH_CMD: + case WHO_IS_LEADER_RES: + case JOIN_REQ: + case ELECT_LEADER_CMD: + return (size == 5); + + case SEARCH_RES: + return (size == 6); + + case INSERT_CMD: + return (size == 9); + + case DHT_UPDATE_CMD: + if (size < 5) + return 1; + tmpNumHosts = read2(&msg[1]); + tmpNumBlocks = read2(&msg[3]); + return (size == (5+sizeof(struct hostData)*tmpNumHosts+2*tmpNumBlocks)); + + case ELECT_LEADER_RES: + if (size < 2) + return 1; + if (msg[1] == 0xFF) + return (size == 2); + if (size < 4) + return 1; + tmpNumHosts = read2(&msg[2]); + return (size == (4 + sizeof(struct hostData) * tmpNumHosts)); + + case CONGRATS_CMD: + if (size < 3) + return 1; + tmpNumHosts = read2(&msg[1]); + return (size == (3 + sizeof(struct hostData) * tmpNumHosts)); + + default: + return 1; + } } -unsigned short read2(unsigned char *ptr) -{ - unsigned short tmp = (ptr[1] << 8) | ptr[0]; - return tmp; +unsigned short read2(unsigned char *ptr) { + unsigned short tmp = (ptr[1] << 8) | ptr[0]; + return tmp; } -unsigned int read4(unsigned char *ptr) -{ - unsigned int tmp = (ptr[3] << 24) | (ptr[2] << 16) | (ptr[1] << 8) | ptr[0]; - return tmp; +unsigned int read4(unsigned char *ptr) { + unsigned int tmp = (ptr[3] << 24) | (ptr[2] << 16) | (ptr[1] << 8) | ptr[0]; + return tmp; } -void write2(unsigned char *ptr, unsigned short tmp) -{ - ptr[1] = (tmp >> 8) & 0xFF; - ptr[0] = tmp & 0xFF; - return; +void write2(unsigned char *ptr, unsigned short tmp) { + ptr[1] = (tmp >> 8) & 0xFF; + ptr[0] = tmp & 0xFF; + return; } -void write4(unsigned char *ptr, unsigned int tmp) -{ - ptr[3] = (tmp >> 24) & 0xFF; - ptr[2] = (tmp >> 16) & 0xFF; - ptr[1] = (tmp >> 8) & 0xFF; - ptr[0] = tmp & 0xFF; - return; +void write4(unsigned char *ptr, unsigned int tmp) { + ptr[3] = (tmp >> 24) & 0xFF; + ptr[2] = (tmp >> 16) & 0xFF; + ptr[1] = (tmp >> 8) & 0xFF; + ptr[0] = tmp & 0xFF; + return; } -unsigned int getMyIpAddr(const char *interfaceStr) -{ - int sock; - struct ifreq interfaceInfo; - struct sockaddr_in *myAddr = (struct sockaddr_in *)&interfaceInfo.ifr_addr; - - memset(&interfaceInfo, 0, sizeof(struct ifreq)); +unsigned int getMyIpAddr(const char *interfaceStr) { + int sock; + struct ifreq interfaceInfo; + struct sockaddr_in *myAddr = (struct sockaddr_in *)&interfaceInfo.ifr_addr; - if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) - { - perror("getMyIpAddr():socket()"); - return 1; - } - - strcpy(interfaceInfo.ifr_name, interfaceStr); - myAddr->sin_family = AF_INET; - - if(ioctl(sock, SIOCGIFADDR, &interfaceInfo) != 0) - { - perror("getMyIpAddr():ioctl()"); - return 1; - } + memset(&interfaceInfo, 0, sizeof(struct ifreq)); - return ntohl(myAddr->sin_addr.s_addr); -} + if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){ + perror("getMyIpAddr():socket()"); + return 1; + } -int udpSend(unsigned char *msg, unsigned int size, unsigned int destIp) -{ - struct sockaddr_in peerAddr; - socklen_t socklen = sizeof(struct sockaddr_in); + strcpy(interfaceInfo.ifr_name, interfaceStr); + myAddr->sin_family = AF_INET; - bzero(&peerAddr, socklen); - peerAddr.sin_family = AF_INET; - peerAddr.sin_addr.s_addr = htonl(destIp); - peerAddr.sin_port = htons(UDP_PORT); + if(ioctl(sock, SIOCGIFADDR, &interfaceInfo) != 0){ + perror("getMyIpAddr():ioctl()"); + return 1; + } - if (size >= 1) - { - if (msg[0] < NUM_MSG_TYPES) - dhtLog("udpSend(): sending %s to %s, %d bytes\n", msg_types[msg[0]], - inet_ntoa(peerAddr.sin_addr), size); - else - dhtLog("udpSend(): sending unknown message to %s, %d bytes\n", - inet_ntoa(peerAddr.sin_addr), size); - } + return ntohl(myAddr->sin_addr.s_addr); +} - if (sendto(udpPollSock.fd, (void *)msg, size, 0, (struct sockaddr *)&peerAddr, - socklen) < 0) - { - perror("udpSend():sendto()"); - return -1; - } - - return 0; +int udpSend(unsigned char *msg, unsigned int size, unsigned int destIp) { + struct sockaddr_in peerAddr; + socklen_t socklen = sizeof(struct sockaddr_in); + + bzero(&peerAddr, socklen); + peerAddr.sin_family = AF_INET; + peerAddr.sin_addr.s_addr = htonl(destIp); + peerAddr.sin_port = htons(UDP_PORT); + + if (size >= 1){ + if (msg[0] < NUM_MSG_TYPES) + dhtLog("udpSend(): sending %s to %s, %d bytes\n", msg_types[msg[0]], + inet_ntoa(peerAddr.sin_addr), size); + else + dhtLog("udpSend(): sending unknown message to %s, %d bytes\n", + inet_ntoa(peerAddr.sin_addr), size); + } + + if (sendto(udpPollSock.fd, (void *)msg, size, 0, (struct sockaddr *)&peerAddr, + socklen) < 0){ + perror("udpSend():sendto()"); + return -1; + } + + return 0; } -int udpSendAll(unsigned char *msg, unsigned int size) -{ - int i; - int status = 0; - 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; - } - } - return status; +int udpSendAll(unsigned char *msg, unsigned int size) { + int i; + int status = 0; + 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; + } + } + return status; } //note: make sure this is only executed in a valid state, where numBlocks != 0 -unsigned int hash(unsigned int x) -{ - return (x % numBlocks); +unsigned int hash(unsigned int x) { + return (x % numBlocks); } //note: make sure this is only executed in a valid state, where these arrays // are allocated and the index mappings are consistent -unsigned int getKeyOwner(unsigned int key) -{ - return hostArray[blockOwnerArray[hash(key)]].ipAddr; +unsigned int getKeyOwner(unsigned int key) { + return hostArray[blockOwnerArray[hash(key)]].ipAddr; } //sets state and timer, if applicable -void setState(unsigned int newState) -{ - struct timeval now; - int i; - - gettimeofday(&now, NULL); - - if (newState >= NUM_STATES) - { - dhtLog("setState(): ERROR: invalid state %d\n", newState); - } - else - { - if (timeout_vals[newState].tv_sec == 0 - && timeout_vals[newState].tv_usec == 0) - { //no timer - timerSet = 0; - } - else - { - timeradd(&now, &timeout_vals[newState], &timer); - timerSet = 1; - } - timeoutCntr = 0; - state = newState; - //TODO: only do this for states that require it - for (i = 0; i < numHosts; i++) - hostReplied[i] = 0; - - dhtLog("setState(): state set to %s\n", state_names[state]); - } - - return; +void setState(unsigned int newState) { + struct timeval now; + int i; + + gettimeofday(&now, NULL); + + if (newState >= NUM_STATES){ + dhtLog("setState(): ERROR: invalid state %d\n", newState); + } else + { + if (timeout_vals[newState].tv_sec == 0 + && timeout_vals[newState].tv_usec == 0){ //no timer + timerSet = 0; + } else + { + timeradd(&now, &timeout_vals[newState], &timer); + timerSet = 1; + } + timeoutCntr = 0; + state = newState; + //TODO: only do this for states that require it + for (i = 0; i < numHosts; i++) + hostReplied[i] = 0; + + dhtLog("setState(): state set to %s\n", state_names[state]); + } + + return; } //TODO: improve these simple and inefficient functions -int checkReplied(unsigned int ipAddr) -{ - int i; +int checkReplied(unsigned int ipAddr) { + int i; - i = findHost(ipAddr); + i = findHost(ipAddr); - if (i == -1) - return -1; + if (i == -1) + return -1; - hostReplied[i] = 1; + hostReplied[i] = 1; - return 0; + return 0; } -int allReplied() -{ - int i; +int allReplied() { + int i; - for (i = 0; i < numHosts; i++) - if ((hostReplied[i] == 0) && (hostArray[i].ipAddr != myHostData.ipAddr)) - return 0; - - return 1; + for (i = 0; i < numHosts; i++) + if ((hostReplied[i] == 0) && (hostArray[i].ipAddr != myHostData.ipAddr)) + return 0; + + return 1; } -int findHost(unsigned int ipAddr) -{ - int i; +int findHost(unsigned int ipAddr) { + int i; - for (i = 0; i < numHosts; i++) - if (hostArray[i].ipAddr == ipAddr) - return i; //found, return index - - return -1; //not found + for (i = 0; i < numHosts; i++) + if (hostArray[i].ipAddr == ipAddr) + return i; //found, return index + + return -1; //not found } -int removeHost(unsigned int ipAddr) -{ - int i, j; +int removeHost(unsigned int ipAddr) { + int i, j; - i = findHost(ipAddr); + i = findHost(ipAddr); - if (i == -1) - return -1; + if (i == -1) + return -1; - for (j = 0; j < numBlocks; j++) - { - if (blockOwnerArray[j] == i) - blockOwnerArray[j] = 0; //TODO: is this what I want to have happen? - else if (blockOwnerArray[j] > i) - blockOwnerArray[j]--; - } + for (j = 0; j < numBlocks; j++) + { + if (blockOwnerArray[j] == i) + blockOwnerArray[j] = 0; //TODO: is this what I want to have happen? + else if (blockOwnerArray[j] > i) + blockOwnerArray[j]--; + } - for (; i < numHosts - 1; i++) - { - hostArray[i] = hostArray[i+1]; - hostReplied[i] = hostReplied[i+1]; - } - numHosts--; + for (; i < numHosts - 1; i++) + { + hostArray[i] = hostArray[i+1]; + hostReplied[i] = hostReplied[i+1]; + } + numHosts--; - return 0; + return 0; } -void removeUnresponsiveHosts() -{ - int i; +void removeUnresponsiveHosts() { + int i; - for (i = 0; i < numHosts; i++) - { - if (!hostReplied[i] && hostArray[i].ipAddr != myHostData.ipAddr) - removeHost(hostArray[i].ipAddr); - } + for (i = 0; i < numHosts; i++) + { + if (!hostReplied[i] && hostArray[i].ipAddr != myHostData.ipAddr) + removeHost(hostArray[i].ipAddr); + } } -int addHost(struct hostData newHost) -{ - struct hostData *newHostArray; - unsigned char *newHostReplied; - int i; - int j; - - for (i = 0; i < numHosts; i++) - { - if (hostArray[i].ipAddr == newHost.ipAddr) - { - hostArray[i] = newHost; - hostReplied[i] = 0; - 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; - } - 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 = 0; j < numBlocks; j++) - { - if (blockOwnerArray[j] >= i) - blockOwnerArray[j]++; - } - numHosts++; - return 1; - } - } - - //nothing greater, add to end - if (numHosts == hostArraySize) +int addHost(struct hostData newHost) { + struct hostData *newHostArray; + unsigned char *newHostReplied; + int i; + int j; + + for (i = 0; i < numHosts; i++) + { + if (hostArray[i].ipAddr == newHost.ipAddr){ + hostArray[i] = newHost; + hostReplied[i] = 0; + 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; + } else + { + for (j = numHosts; j > i; j--) { - newHostArray = calloc(2 * hostArraySize, sizeof(struct hostData)); - newHostReplied = calloc(2 * hostArraySize, sizeof(unsigned char)); - memcpy(newHostArray, hostArray, (numHosts * sizeof(struct hostData))); - memcpy(newHostReplied, hostReplied, (numHosts * sizeof(unsigned char))); - free(hostArray); - free(hostReplied); - hostArray = newHostArray; - hostReplied = newHostReplied; - hostArraySize = 2 * hostArraySize; + hostArray[j] = hostArray[j-1]; + hostReplied[j] = hostReplied[j-1]; } - - hostArray[numHosts] = newHost; - hostReplied[numHosts] = 0; - numHosts++; - return 1; + hostArray[i] = newHost; + hostReplied[i] = 0; + } + for(j = 0; j < numBlocks; j++) + { + if (blockOwnerArray[j] >= i) + blockOwnerArray[j]++; + } + numHosts++; + return 1; + } + } + + //nothing greater, add to end + if (numHosts == hostArraySize){ + newHostArray = calloc(2 * hostArraySize, sizeof(struct hostData)); + newHostReplied = calloc(2 * hostArraySize, sizeof(unsigned char)); + memcpy(newHostArray, hostArray, (numHosts * sizeof(struct hostData))); + memcpy(newHostReplied, hostReplied, (numHosts * sizeof(unsigned char))); + free(hostArray); + free(hostReplied); + hostArray = newHostArray; + hostReplied = newHostReplied; + hostArraySize = 2 * hostArraySize; + } + + hostArray[numHosts] = newHost; + hostReplied[numHosts] = 0; + numHosts++; + return 1; } -void makeAssignments() -{ - int i; +void makeAssignments() { + int i; - if (numBlocks < numHosts) - { - free(blockOwnerArray); - while (numBlocks < numHosts) - numBlocks *= 2; - blockOwnerArray = calloc(numBlocks, sizeof(unsigned short)); - } + if (numBlocks < numHosts){ + free(blockOwnerArray); + while (numBlocks < numHosts) + numBlocks *= 2; + blockOwnerArray = calloc(numBlocks, sizeof(unsigned short)); + } - for (i = 0; i < numBlocks; i++) - blockOwnerArray[i] = i % numHosts; + for (i = 0; i < numBlocks; i++) + blockOwnerArray[i] = i % numHosts; - return; + return; } -void writeHostList() -{ - int i; - struct in_addr tmpAddr; - - fprintf(logfile, "numHosts = %d\n", numHosts); - for (i = 0; i < numHosts; i++) - { - tmpAddr.s_addr = htonl(hostArray[i].ipAddr); - fprintf(logfile, "%d) %s, %d\n", i, inet_ntoa(tmpAddr), - hostArray[i].maxKeyCapacity); - } - return; +void writeHostList() { + int i; + struct in_addr tmpAddr; + + fprintf(logfile, "numHosts = %d\n", numHosts); + for (i = 0; i < numHosts; i++) + { + tmpAddr.s_addr = htonl(hostArray[i].ipAddr); + fprintf(logfile, "%d) %s, %d\n", i, inet_ntoa(tmpAddr), + hostArray[i].maxKeyCapacity); + } + return; } -void dhtLog(const char *format, ...) -{ - va_list args; +void dhtLog(const char *format, ...) { + va_list args; // struct timeval now; // if (gettimeofday(&now, NULL) < 0) // { perror("dhtLog():gettimeofday()"); } - va_start(args, format); + va_start(args, format); // if (fprintf(logfile, "%d.%06d:", now.tv_sec, now.tv_usec) < 0) // { perror("dhtLog():fprintf()"); } - if (vfprintf(logfile, format, args) < 0) - { perror("dhtLog():vfprintf()"); } - if (fflush(logfile) == EOF) - { perror("dhtLog():fflush()"); } - va_end(args); - - return; + if (vfprintf(logfile, format, args) < 0){ + perror("dhtLog():vfprintf()"); + } + if (fflush(logfile) == EOF){ + perror("dhtLog():fflush()"); + } + va_end(args); + + return; } -void *fillTask() -{ - unsigned int *vals; - unsigned int *keys; - unsigned int numKeys; - int i; - - vals = mhashGetKeys(&numKeys); //note: key of mhash is val of dht - keys = calloc(numKeys, sizeof(unsigned int)); - - for (i = 0; i < numKeys; i++) - keys[i] = myHostData.ipAddr; - - if (dhtInsertMult(numKeys, keys, vals) == 0) - fillStatus = 2; - else - fillStatus = 3; - - pthread_exit(NULL); +void *fillTask() { + unsigned int *vals; + unsigned int *keys; + unsigned int numKeys; + int i; + + vals = mhashGetKeys(&numKeys); //note: key of mhash is val of dht + keys = calloc(numKeys, sizeof(unsigned int)); + + for (i = 0; i < numKeys; i++) + keys[i] = myHostData.ipAddr; + + if (dhtInsertMult(numKeys, keys, vals) == 0) + fillStatus = 2; + else + fillStatus = 3; + + pthread_exit(NULL); } -void *udpListen() -{ - ssize_t bytesRcvd; - struct sockaddr_in peerAddr; - unsigned int peerIp; - socklen_t socklen = sizeof(struct sockaddr_in); - unsigned char inBuffer[MAX_MSG_SIZE]; - unsigned char outBuffer[MAX_MSG_SIZE]; - int pollret; - struct timeval now; - struct in_addr tmpAddr; - struct hostData tmpHost; - unsigned int tmpKey; - unsigned int tmpVal; - struct hostData *hostDataPtr; - unsigned short *uShortPtr; - unsigned int tmpUInt; - unsigned int tmpUShort; - int i; - unsigned int oldState; - - dhtLog("udpListen(): linstening on port %d...\n", UDP_PORT); - - while (1) - { - pollret = poll(&udpPollSock, 1, TIMEOUT_PERIOD); - pthread_mutex_lock(&stateMutex); - oldState = state; - if (pollret < 0) - { - perror("udpListen():poll()"); - } - else if (pollret > 0) - { - bytesRcvd = recvfrom(udpPollSock.fd, inBuffer, MAX_MSG_SIZE, 0, - (struct sockaddr *)&peerAddr, &socklen); - if (bytesRcvd < 1) - { - dhtLog("udpListen(): ERROR: bytesRcvd = %d\n", bytesRcvd); - } - else if (inBuffer[0] >= NUM_MSG_TYPES) - { - 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); - } - else if (state == EXIT2_STATE) - { - //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); - } - } - } - 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; - } - } - } - if (state == REBUILD4_STATE) - { - switch (fillStatus) - { - case 0: dhtLog("udpListen(): ERROR: fillStatus=0 in REBUILD4_STATE\n"); - break; - case 1: //do nothing - break; - case 2: //done filling the dht, notify leader - 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; - } - } - if (state == LEAD_REBUILD3_STATE) - { - switch (fillStatus) - { - case 0: dhtLog("udpListen(): ERROR: fillStatus=0 in LEAD_REBUILD3_STATE\n"); - break; - case 1: //do nothing - 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; - case 3: //error encountered -> restart rebuild - 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; - } - } - } +void *udpListen() { + ssize_t bytesRcvd; + struct sockaddr_in peerAddr; + unsigned int peerIp; + socklen_t socklen = sizeof(struct sockaddr_in); + unsigned char inBuffer[MAX_MSG_SIZE]; + unsigned char outBuffer[MAX_MSG_SIZE]; + int pollret; + struct timeval now; + struct in_addr tmpAddr; + struct hostData tmpHost; + unsigned int tmpKey; + unsigned int tmpVal; + struct hostData *hostDataPtr; + unsigned short *uShortPtr; + unsigned int tmpUInt; + unsigned int tmpUShort; + int i; + unsigned int oldState; + + dhtLog("udpListen(): linstening on port %d...\n", UDP_PORT); + + while (1){ + pollret = poll(&udpPollSock, 1, TIMEOUT_PERIOD); + pthread_mutex_lock(&stateMutex); + oldState = state; + if (pollret < 0){ + perror("udpListen():poll()"); + } else if (pollret > 0) { + bytesRcvd = recvfrom(udpPollSock.fd, inBuffer, MAX_MSG_SIZE, 0, + (struct sockaddr *)&peerAddr, &socklen); + if (bytesRcvd < 1){ + dhtLog("udpListen(): ERROR: bytesRcvd = %d\n", bytesRcvd); + } else if (inBuffer[0] >= NUM_MSG_TYPES) { + 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); + } else if (state == EXIT2_STATE) { + //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); + } + } + } 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); } - if (state != oldState) - pthread_cond_broadcast(&stateCond); - pthread_mutex_unlock(&stateMutex); + } 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; + + case 1: //do nothing + break; + + case 2: //done filling the dht, notify leader + 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; + } + } + if (state == LEAD_REBUILD3_STATE){ + switch (fillStatus){ + case 0: dhtLog("udpListen(): ERROR: fillStatus=0 in LEAD_REBUILD3_STATE\n"); + break; + + case 1: //do nothing + 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; + + case 3: //error encountered -> restart rebuild + 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 (state != oldState) + pthread_cond_broadcast(&stateCond); + pthread_mutex_unlock(&stateMutex); + } } diff --git a/Robust/src/Runtime/DSTM/interface/dht.h b/Robust/src/Runtime/DSTM/interface/dht.h index 344ab530..2a955ba5 100644 --- a/Robust/src/Runtime/DSTM/interface/dht.h +++ b/Robust/src/Runtime/DSTM/interface/dht.h @@ -23,7 +23,7 @@ void dhtExit(); //returns 0 if successful, -1 if an error occurred int dhtInsert(unsigned int key, unsigned int val); //simultaneously inserts the key-val pairs in the given arrays -int dhtInsertMult(unsigned int numKeys, unsigned int *keys, unsigned int *vals); +int dhtInsertMult(unsigned int numKeys, unsigned int *keys, unsigned int *vals); //returns 0 if successful, -1 if an error occurred int dhtRemove(unsigned int key); //simultaneously delete the keys in the given array diff --git a/Robust/src/Runtime/DSTM/interface/dsmdebug.h b/Robust/src/Runtime/DSTM/interface/dsmdebug.h index e0d0a06b..c95695a4 100644 --- a/Robust/src/Runtime/DSTM/interface/dsmdebug.h +++ b/Robust/src/Runtime/DSTM/interface/dsmdebug.h @@ -1,14 +1,14 @@ #ifndef _DSMDEBUG_H_ #define _DSMDEBUG_H_ -#define TABORT1(s) {printf("%s\n", s); fflush(stdout);} -#define TABORT2(s, msg) {printf("%s(): %s\n", s, msg); fflush(stdout);} -#define TABORT3(func, s, msg, d) {printf("%s(): %s: for %s = %d\n", func, s, msg, d); fflush(stdout);} -#define TABORT4(s, d) {printf("%s = %d\n", s, d); fflush(stdout);} -#define TABORT5(func, msg1 , msg2, val1, val2) {printf("%s(): %s = %x, %s = %d\n", func, msg1, val1, msg2, val2); fflush(stdout);} +#define TABORT1(s) {printf("%s\n", s); fflush(stdout);} +#define TABORT2(s, msg) {printf("%s(): %s\n", s, msg); fflush(stdout);} +#define TABORT3(func, s, msg, d) {printf("%s(): %s: for %s = %d\n", func, s, msg, d); fflush(stdout);} +#define TABORT4(s, d) {printf("%s = %d\n", s, d); fflush(stdout);} +#define TABORT5(func, msg1, msg2, val1, val2) {printf("%s(): %s = %x, %s = %d\n", func, msg1, val1, msg2, val2); fflush(stdout);} #define TABORT6(a, b, c, val1, val2) {printf("%s = %x, %s for %s = %x\n", a, val1, b, c, val2); fflush(stdout);} #define TABORT7(func, a, b, c, val1, val2) {printf("%s(): %s for %s =%d, %s = %x\n", func, a, b, val1, c, val2); fflush(stdout);} -#define TABORT8(func, s, d) {printf("%s(): %s = %d\n", func, s, d); fflush(stdout);} +#define TABORT8(func, s, d) {printf("%s(): %s = %d\n", func, s, d); fflush(stdout);} #define TABORT9(func, a, b, c, d, val1, val2, val3) {printf("%s(): %s for %s =%x, %s = %d, %s = %x\n", func, a, b, val1, c, val2, d, val3); fflush(stdout);} diff --git a/Robust/src/Runtime/DSTM/interface/dstm.h b/Robust/src/Runtime/DSTM/interface/dstm.h index 2a347784..7724cf3e 100644 --- a/Robust/src/Runtime/DSTM/interface/dstm.h +++ b/Robust/src/Runtime/DSTM/interface/dstm.h @@ -9,8 +9,8 @@ * Macros **********************************************************/ #define GET_SITEID(x) ((int *)(x)) -#define GET_NTUPLES(x) ((int *)(x + sizeof(int))) -#define GET_PTR_OID(x) ((unsigned int *)(x + 2*sizeof(int))) +#define GET_NTUPLES(x) ((int *)(x + sizeof(int))) +#define GET_PTR_OID(x) ((unsigned int *)(x + 2*sizeof(int))) #define GET_PTR_EOFF(x,n) ((short *)(x + 2*sizeof(int) + (n*sizeof(unsigned int)))) #define GET_PTR_ARRYFLD(x,n) ((short *)(x + 2*sizeof(int) + (n*sizeof(unsigned int)) + (n*sizeof(short)))) #define ENDEBUG(s) { printf("Inside %s()\n", s); fflush(stdout);} @@ -18,36 +18,36 @@ /***************************************** * Coordinator Messages ***************************************/ -#define READ_REQUEST 1 -#define READ_MULT_REQUEST 2 -#define MOVE_REQUEST 3 -#define MOVE_MULT_REQUEST 4 -#define TRANS_REQUEST 5 -#define TRANS_ABORT 6 -#define TRANS_COMMIT 7 -#define TRANS_PREFETCH 8 -#define TRANS_ABORT_BUT_RETRY_COMMIT_WITH_RELOCATING 9 +#define READ_REQUEST 1 +#define READ_MULT_REQUEST 2 +#define MOVE_REQUEST 3 +#define MOVE_MULT_REQUEST 4 +#define TRANS_REQUEST 5 +#define TRANS_ABORT 6 +#define TRANS_COMMIT 7 +#define TRANS_PREFETCH 8 +#define TRANS_ABORT_BUT_RETRY_COMMIT_WITH_RELOCATING 9 /********************************* * Participant Messages *******************************/ -#define OBJECT_FOUND 10 -#define OBJECT_NOT_FOUND 11 -#define OBJECTS_FOUND 12 -#define OBJECTS_NOT_FOUND 13 -#define TRANS_AGREE 17 -#define TRANS_DISAGREE 18 -#define TRANS_AGREE_BUT_MISSING_OBJECTS 19 -#define TRANS_SOFT_ABORT 20 -#define TRANS_SUCESSFUL 21 -#define TRANS_PREFETCH_RESPONSE 22 -#define START_REMOTE_THREAD 23 -#define THREAD_NOTIFY_REQUEST 24 -#define THREAD_NOTIFY_RESPONSE 25 -#define TRANS_UNSUCESSFUL 26 +#define OBJECT_FOUND 10 +#define OBJECT_NOT_FOUND 11 +#define OBJECTS_FOUND 12 +#define OBJECTS_NOT_FOUND 13 +#define TRANS_AGREE 17 +#define TRANS_DISAGREE 18 +#define TRANS_AGREE_BUT_MISSING_OBJECTS 19 +#define TRANS_SOFT_ABORT 20 +#define TRANS_SUCESSFUL 21 +#define TRANS_PREFETCH_RESPONSE 22 +#define START_REMOTE_THREAD 23 +#define THREAD_NOTIFY_REQUEST 24 +#define THREAD_NOTIFY_RESPONSE 25 +#define TRANS_UNSUCESSFUL 26 #define CLOSE_CONNECTION 27 -//Max number of objects +//Max number of objects #define MAX_OBJECTS 20 #define DEFAULT_OBJ_STORE_SIZE 1048510 //1MB //Transaction id per machine @@ -55,7 +55,7 @@ #define LISTEN_PORT 2156 #define UDP_PORT 2158 //Prefetch tuning paramters -#define RETRYINTERVAL 20//N +#define RETRYINTERVAL 20 //N #define SHUTDOWNINTERVAL 3 //M #include @@ -96,44 +96,44 @@ extern int numprefetchsites; #include "structdefs.h" typedef struct objheader { - threadlist_t *notifylist; - unsigned short version; - unsigned short rcount; + threadlist_t *notifylist; + unsigned short version; + unsigned short rcount; } objheader_t; -#define OID(x)\ - (*((unsigned int *)&((struct ___Object___ *)((unsigned int) x + sizeof(objheader_t)))->___nextobject___)) +#define OID(x) \ + (*((unsigned int *)&((struct ___Object___ *)((unsigned int) x + sizeof(objheader_t)))->___nextobject___)) -#define COMPOID(x)\ - (*((unsigned int *)&((struct ___Object___ *) x)->___nextobject___)) +#define COMPOID(x) \ + (*((unsigned int *)&((struct ___Object___ *) x)->___nextobject___)) -#define STATUS(x)\ - *((unsigned int *) &(((struct ___Object___ *)((unsigned int) x + sizeof(objheader_t)))->___localcopy___)) +#define STATUS(x) \ + *((unsigned int *) &(((struct ___Object___ *)((unsigned int) x + sizeof(objheader_t)))->___localcopy___)) -#define STATUSPTR(x)\ - ((unsigned int *) &(((struct ___Object___ *)((unsigned int) x + sizeof(objheader_t)))->___localcopy___)) +#define STATUSPTR(x) \ + ((unsigned int *) &(((struct ___Object___ *)((unsigned int) x + sizeof(objheader_t)))->___localcopy___)) -#define TYPE(x)\ - ((struct ___Object___ *)((unsigned int) x + sizeof(objheader_t)))->type +#define TYPE(x) \ + ((struct ___Object___ *)((unsigned int) x + sizeof(objheader_t)))->type -#define GETSIZE(size, x) {\ - int type=TYPE(x);\ - if (type___length___+sizeof(struct ArrayObject);\ - }\ +#define GETSIZE(size, x) { \ + int type=TYPE(x); \ + if (type___length___+sizeof(struct ArrayObject); \ + } \ } #else typedef struct objheader { - threadlist_t *notifylist; - unsigned int oid; - unsigned short type; - unsigned short version; - unsigned short rcount; - char status; + threadlist_t *notifylist; + unsigned int oid; + unsigned short type; + unsigned short version; + unsigned short rcount; + char status; } objheader_t; #define OID(x) x->oid @@ -144,14 +144,14 @@ typedef struct objheader { #endif typedef struct objstr { - unsigned int size; //this many bytes are allocated after this header - void *top; - struct objstr *next; + unsigned int size; //this many bytes are allocated after this header + void *top; + struct objstr *next; } objstr_t; typedef struct oidmidpair { - unsigned int oid; - unsigned int mid; + unsigned int oid; + unsigned int mid; } oidmidpair_t; typedef struct transrecord { @@ -169,34 +169,34 @@ typedef struct thread_response { // Structure that holds fixed data to be sent along with TRANS_REQUEST typedef struct fixed_data { - char control; /* control message */ - char trans_id[TID_LEN]; /* transaction id */ - int mcount; /* participant count */ - unsigned int numread; /* no of objects read */ - unsigned int nummod; /* no of objects modified */ - unsigned int numcreated; /* no of objects created */ - int sum_bytes; /* total bytes of modified objects in a transaction */ + char control; /* control message */ + char trans_id[TID_LEN]; /* transaction id */ + int mcount; /* participant count */ + unsigned int numread; /* no of objects read */ + unsigned int nummod; /* no of objects modified */ + unsigned int numcreated; /* no of objects created */ + int sum_bytes; /* total bytes of modified objects in a transaction */ } fixed_data_t; /* Structure that holds trans request information for each participant */ typedef struct trans_req_data { - fixed_data_t f; /* Holds first few fixed bytes of data sent during TRANS_REQUEST protcol*/ - unsigned int *listmid; /* Pointer to array holding list of participants */ - char *objread; /* Pointer to array holding oid and version number of objects that are only read */ - unsigned int *oidmod; /* Pointer to array holding oids of objects that are modified */ - unsigned int *oidcreated; /* Pointer to array holding oids of objects that are newly created */ -} trans_req_data_t; + fixed_data_t f; /* Holds first few fixed bytes of data sent during TRANS_REQUEST protcol*/ + unsigned int *listmid; /* Pointer to array holding list of participants */ + char *objread; /* Pointer to array holding oid and version number of objects that are only read */ + unsigned int *oidmod; /* Pointer to array holding oids of objects that are modified */ + unsigned int *oidcreated; /* Pointer to array holding oids of objects that are newly created */ +} trans_req_data_t; /* Structure that holds information of objects that are not found in the participant * and objs locked within a transaction during commit process */ -typedef struct trans_commit_data{ - unsigned int *objlocked; /* Pointer to array holding oids of objects locked inside a transaction */ +typedef struct trans_commit_data { + unsigned int *objlocked; /* Pointer to array holding oids of objects locked inside a transaction */ unsigned int *objnotfound; /* Pointer to array holding oids of objects not found on the participant machine */ unsigned int *objvernotmatch; /* Pointer to array holding oids whose version doesn't match on the participant machine */ - void *modptr; /* Pointer to the address in the mainobject store of the participant that holds all modified objects */ - int numlocked; /* no of objects locked */ - int numnotfound; /* no of objects not found */ - int numvernotmatch; /* no of objects whose version doesn't match */ + void *modptr; /* Pointer to the address in the mainobject store of the participant that holds all modified objects */ + int numlocked; /* no of objects locked */ + int numnotfound; /* no of objects not found */ + int numvernotmatch; /* no of objects whose version doesn't match */ } trans_commit_data_t; @@ -204,29 +204,29 @@ typedef struct trans_commit_data{ /* Structure for passing multiple arguments to a thread * spawned to process each transaction on a machine */ typedef struct thread_data_array { - int thread_id; - int mid; - trans_req_data_t *buffer; /* Holds trans request information sent to a participant, based on threadid */ - thread_response_t *recvmsg; /* Shared datastructure to keep track of the participants response to a trans request */ + int thread_id; + int mid; + trans_req_data_t *buffer; /* Holds trans request information sent to a participant, based on threadid */ + thread_response_t *recvmsg; /* Shared datastructure to keep track of the participants response to a trans request */ pthread_cond_t *threshold; /* Condition var to waking up a thread */ - pthread_mutex_t *lock; /* Lock for counting participants response */ - int *count; /* Variable to count responses from all participants to the TRANS_REQUEST protocol */ - char *replyctrl; /* Shared ctrl message that stores the reply to be sent to participants, filled by decideResponse() */ - char *replyretry; /* Shared variable that keep track if coordinator needs retry */ - transrecord_t *rec; /* Shared variable transaction record send to all thread data */ + pthread_mutex_t *lock; /* Lock for counting participants response */ + int *count; /* Variable to count responses from all participants to the TRANS_REQUEST protocol */ + char *replyctrl; /* Shared ctrl message that stores the reply to be sent to participants, filled by decideResponse() */ + char *replyretry; /* Shared variable that keep track if coordinator needs retry */ + transrecord_t *rec; /* Shared variable transaction record send to all thread data */ } thread_data_array_t; //Structure for passing arguments to the local m/c thread typedef struct local_thread_data_array { - thread_data_array_t *tdata; /* Holds all the arguments send to a thread that is spawned when transaction commits */ - trans_commit_data_t *transinfo; /* Holds information of objects locked and not found in the participant */ + thread_data_array_t *tdata; /* Holds all the arguments send to a thread that is spawned when transaction commits */ + trans_commit_data_t *transinfo; /* Holds information of objects locked and not found in the participant */ } local_thread_data_array_t; //Structure to store mid and socketid information typedef struct midSocketInfo { - unsigned int mid; /* To communicate with mid use sockid in this data structure */ - int sockid; + unsigned int mid; /* To communicate with mid use sockid in this data structure */ + int sockid; } midSocketInfo_t; /* Initialize main object store and lookup tables, start server thread. */ @@ -273,11 +273,11 @@ transrecord_t *transStart(); objheader_t *transRead(transrecord_t *, unsigned int); objheader_t *transCreateObj(transrecord_t *, unsigned int); //returns oid header int transCommit(transrecord_t *record); //return 0 if successful -void *transRequest(void *); //the C routine that the thread will execute when TRANS_REQUEST begins -void decideResponse(thread_data_array_t *);// Coordinator decides what response to send to the participant +void *transRequest(void *); //the C routine that the thread will execute when TRANS_REQUEST begins +void decideResponse(thread_data_array_t *); // Coordinator decides what response to send to the participant char sendResponse(thread_data_array_t *, int); //Sends control message back to Participants -void *getRemoteObj(transrecord_t *, unsigned int, unsigned int);// returns object header from main object store after object is copied into it from remote machine -void *handleLocalReq(void *);//handles Local requests +void *getRemoteObj(transrecord_t *, unsigned int, unsigned int); // returns object header from main object store after object is copied into it from remote machine +void *handleLocalReq(void *); //handles Local requests int transComProcess(local_thread_data_array_t *); int transAbortProcess(local_thread_data_array_t *); void transAbort(transrecord_t *trans); @@ -285,7 +285,7 @@ void sendPrefetchResponse(int sd, char *control, char *sendbuffer, int *size); void prefetch(int, int, unsigned int *, unsigned short *, short*); void *transPrefetch(void *); void *mcqProcess(void *); -prefetchpile_t *foundLocal(char *);// returns node with prefetch elements(oids, offsets) +prefetchpile_t *foundLocal(char *); // returns node with prefetch elements(oids, offsets) int lookupObject(unsigned int * oid, short offset); int transPrefetchProcess(transrecord_t *, int **, short); void sendPrefetchReq(prefetchpile_t*, int); diff --git a/Robust/src/Runtime/DSTM/interface/dstmserver.c b/Robust/src/Runtime/DSTM/interface/dstmserver.c index 965b0a24..b6317037 100644 --- a/Robust/src/Runtime/DSTM/interface/dstmserver.c +++ b/Robust/src/Runtime/DSTM/interface/dstmserver.c @@ -24,33 +24,32 @@ pthread_mutexattr_t mainobjstore_mutex_attr; /* Attribute for lock to make it a sockPoolHashTable_t *transPResponseSocketPool; -/* This function initializes the main objects store and creates the +/* This function initializes the main objects store and creates the * global machine and location lookup table */ -int dstmInit(void) -{ - mainobjstore = objstrCreate(DEFAULT_OBJ_STORE_SIZE); - /* Initialize attribute for mutex */ - pthread_mutexattr_init(&mainobjstore_mutex_attr); - pthread_mutexattr_settype(&mainobjstore_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP); - pthread_mutex_init(&mainobjstore_mutex, &mainobjstore_mutex_attr); - pthread_mutex_init(&lockObjHeader,NULL); - if (mhashCreate(HASH_SIZE, LOADFACTOR)) - return 1; //failure - - if (lhashCreate(HASH_SIZE, LOADFACTOR)) - return 1; //failure - - if (notifyhashCreate(N_HASH_SIZE, N_LOADFACTOR)) - return 1; //failure - - //Initialize socket pool - if((transPResponseSocketPool = createSockPool(transPResponseSocketPool, DEFAULTSOCKPOOLSIZE)) == NULL) { - printf("Error in creating new socket pool at %s line %d\n", __FILE__, __LINE__); - return 0; - } +int dstmInit(void) { + mainobjstore = objstrCreate(DEFAULT_OBJ_STORE_SIZE); + /* Initialize attribute for mutex */ + pthread_mutexattr_init(&mainobjstore_mutex_attr); + pthread_mutexattr_settype(&mainobjstore_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP); + pthread_mutex_init(&mainobjstore_mutex, &mainobjstore_mutex_attr); + pthread_mutex_init(&lockObjHeader,NULL); + if (mhashCreate(HASH_SIZE, LOADFACTOR)) + return 1; //failure + + if (lhashCreate(HASH_SIZE, LOADFACTOR)) + return 1; //failure + + if (notifyhashCreate(N_HASH_SIZE, N_LOADFACTOR)) + return 1; //failure + + //Initialize socket pool + if((transPResponseSocketPool = createSockPool(transPResponseSocketPool, DEFAULTSOCKPOOLSIZE)) == NULL) { + printf("Error in creating new socket pool at %s line %d\n", __FILE__, __LINE__); + return 0; + } - return 0; + return 0; } @@ -59,13 +58,13 @@ int startlistening() { struct sockaddr_in my_addr; socklen_t addrlength = sizeof(struct sockaddr); int setsockflag=1; - + listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd == -1) { perror("socket"); exit(1); } - + if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &setsockflag, sizeof (setsockflag)) < 0) { perror("socket"); exit(1); @@ -76,17 +75,17 @@ int startlistening() { exit(1); } #endif - + my_addr.sin_family = AF_INET; my_addr.sin_port = htons(LISTEN_PORT); my_addr.sin_addr.s_addr = INADDR_ANY; memset(&(my_addr.sin_zero), '\0', 8); - + if (bind(listenfd, (struct sockaddr *)&my_addr, addrlength) == -1) { perror("bind"); exit(1); } - + if (listen(listenfd, BACKLOG) == -1) { perror("listen"); exit(1); @@ -94,7 +93,7 @@ int startlistening() { return listenfd; } -/* This function starts the thread to listen on a socket +/* This function starts the thread to listen on a socket * for tranaction calls */ void *dstmListen(void *lfd) { int listenfd=(int)lfd; @@ -102,7 +101,7 @@ void *dstmListen(void *lfd) { struct sockaddr_in client_addr; socklen_t addrlength = sizeof(struct sockaddr); pthread_t thread_dstm_accept; - + printf("Listening on port %d, fd = %d\n", LISTEN_PORT, listenfd); while(1) { int retval; @@ -115,7 +114,7 @@ void *dstmListen(void *lfd) { pthread_detach(thread_dstm_accept); } } -/* This function accepts a new connection request, decodes the control message in the connection +/* This function accepts a new connection request, decodes the control message in the connection * and accordingly calls other functions to process new requests */ void *dstmAccept(void *acceptfd) { int val, retval, size, sum, sockid; @@ -128,7 +127,7 @@ void *dstmAccept(void *acceptfd) { trans_commit_data_t transinfo; unsigned short objType, *versionarry, version; unsigned int *oidarry, numoid, mid, threadid; - + /* Receive control messages from other machines */ while(1) { int ret=recv_data_errorcode((int)acceptfd, &control, sizeof(char)); @@ -143,22 +142,22 @@ void *dstmAccept(void *acceptfd) { /* Read oid requested and search if available */ recv_data((int)acceptfd, &oid, sizeof(unsigned int)); if((srcObj = mhashSearch(oid)) == NULL) { - printf("Error: Object 0x%x is not found in Main Object Store %s, %d\n", oid, __FILE__, __LINE__); - break; + printf("Error: Object 0x%x is not found in Main Object Store %s, %d\n", oid, __FILE__, __LINE__); + break; } h = (objheader_t *) srcObj; 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; @@ -179,22 +178,25 @@ void *dstmAccept(void *acceptfd) { transinfo.numlocked = 0; transinfo.numnotfound = 0; if((val = readClientReq(&transinfo, (int)acceptfd)) != 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: if((val = prefetchReq((int)acceptfd)) != 0) { - printf("Error: In prefetchReq() %s, %d\n", __FILE__, __LINE__); - break; + printf("Error: In prefetchReq() %s, %d\n", __FILE__, __LINE__); + break; } break; + case TRANS_PREFETCH_RESPONSE: if((val = getPrefetchResponse((int) acceptfd)) != 0) { - printf("Error: In getPrefetchResponse() %s, %d\n", __FILE__, __LINE__); - break; + printf("Error: In getPrefetchResponse() %s, %d\n", __FILE__, __LINE__); + break; } break; + case START_REMOTE_THREAD: recv_data((int)acceptfd, &oid, sizeof(unsigned int)); objType = getObjType(oid); @@ -205,13 +207,13 @@ void *dstmAccept(void *acceptfd) { recv_data((int)acceptfd, &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((int)acceptfd, buffer, size); - oidarry = calloc(numoid, sizeof(unsigned int)); + oidarry = calloc(numoid, sizeof(unsigned int)); memcpy(oidarry, buffer, sizeof(unsigned int) * numoid); size = sizeof(unsigned int) * numoid; versionarry = calloc(numoid, sizeof(unsigned short)); @@ -228,8 +230,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((int)acceptfd, buffer, size); @@ -270,7 +272,7 @@ int readClientReq(trans_commit_data_t *transinfo, int acceptfd) { oidmod = NULL; - /* Read fixed_data_t data structure */ + /* Read fixed_data_t data structure */ size = sizeof(fixed) - 1; ptr = (char *)&fixed;; fixed.control = TRANS_REQUEST; @@ -287,9 +289,9 @@ int readClientReq(trans_commit_data_t *transinfo, int acceptfd) { int numread = fixed.numread; size = numread * (sizeof(unsigned int) + sizeof(unsigned short)); char objread[size]; - if(numread != 0) { //If pile contains more than one object to be read, + if(numread != 0) { //If pile contains more than one object to be read, // keep reading all objects - recv_data((int)acceptfd, objread, size); + recv_data((int)acceptfd, objread, size); } /* Read modified objects */ @@ -299,285 +301,285 @@ int readClientReq(trans_commit_data_t *transinfo, int acceptfd) { return 1; } size = fixed.sum_bytes; - recv_data((int)acceptfd, modptr, size); + recv_data((int)acceptfd, modptr, size); } - /* Create an array of oids for modified objects */ - oidmod = (unsigned int *) calloc(fixed.nummod, sizeof(unsigned int)); - if (oidmod == NULL) - { - printf("calloc error %s, %d\n", __FILE__, __LINE__); - return 1; - } - ptr = (char *) modptr; - for(i = 0 ; i < fixed.nummod; i++) { - int tmpsize; - headaddr = (objheader_t *) ptr; - oid = OID(headaddr); - oidmod[i] = oid; - GETSIZE(tmpsize, headaddr); - ptr += sizeof(objheader_t) + tmpsize; - } - - /*Process the information read */ - if((val = processClientReq(&fixed, transinfo, listmid, objread, modptr, oidmod, acceptfd)) != 0) { - printf("Error: In processClientReq() %s, %d\n", __FILE__, __LINE__); - /* Free resources */ - if(oidmod != NULL) { - free(oidmod); - } - return 1; - } + /* Create an array of oids for modified objects */ + oidmod = (unsigned int *) calloc(fixed.nummod, sizeof(unsigned int)); + if (oidmod == NULL){ + printf("calloc error %s, %d\n", __FILE__, __LINE__); + return 1; + } + ptr = (char *) modptr; + for(i = 0 ; i < fixed.nummod; i++) { + int tmpsize; + headaddr = (objheader_t *) ptr; + oid = OID(headaddr); + oidmod[i] = oid; + GETSIZE(tmpsize, headaddr); + ptr += sizeof(objheader_t) + tmpsize; + } - /* Free resources */ - if(oidmod != NULL) { - free(oidmod); - } + /*Process the information read */ + if((val = processClientReq(&fixed, transinfo, listmid, objread, modptr, oidmod, acceptfd)) != 0) { + printf("Error: In processClientReq() %s, %d\n", __FILE__, __LINE__); + /* Free resources */ + if(oidmod != NULL) { + free(oidmod); + } + return 1; + } + + /* Free resources */ + if(oidmod != NULL) { + free(oidmod); + } - return 0; + return 0; } -/* This function processes the Coordinator's transaction request using "handleTransReq" +/* This function processes the Coordinator's transaction request using "handleTransReq" * function and sends a reply to the co-ordinator. * Following this it also receives a new control message from the co-ordinator and processes this message*/ int processClientReq(fixed_data_t *fixed, trans_commit_data_t *transinfo, - unsigned int *listmid, char *objread, void *modptr, unsigned int *oidmod, int acceptfd) { - char control, sendctrl, retval; - objheader_t *tmp_header; - void *header; - int i = 0, val; - - /* Send reply to the Coordinator */ - if((retval = handleTransReq(fixed, transinfo, listmid, objread, modptr,acceptfd)) == 0 ) { - printf("Error: In handleTransReq() %s, %d\n", __FILE__, __LINE__); - return 1; - } + unsigned int *listmid, char *objread, void *modptr, unsigned int *oidmod, int acceptfd) { + char control, sendctrl, retval; + objheader_t *tmp_header; + void *header; + int i = 0, val; + + /* Send reply to the Coordinator */ + if((retval = handleTransReq(fixed, transinfo, listmid, objread, modptr,acceptfd)) == 0 ) { + printf("Error: In handleTransReq() %s, %d\n", __FILE__, __LINE__); + return 1; + } - recv_data((int)acceptfd, &control, sizeof(char)); - - /* Process the new control message */ - switch(control) { - case TRANS_ABORT: - if (fixed->nummod > 0) - free(modptr); - /* Unlock objects that was locked due to this transaction */ - for(i = 0; i< transinfo->numlocked; i++) { - if((header = mhashSearch(transinfo->objlocked[i])) == NULL) { - printf("mhashSearch returns NULL at %s, %d\n", __FILE__, __LINE__);// find the header address - return 1; - } - UnLock(STATUSPTR(header)); - } - - /* Send ack to Coordinator */ - sendctrl = TRANS_UNSUCESSFUL; - send_data((int)acceptfd, &sendctrl, sizeof(char)); - break; - - case TRANS_COMMIT: - /* Invoke the transCommit process() */ - if((val = transCommitProcess(modptr, oidmod, transinfo->objlocked, fixed->nummod, transinfo->numlocked, (int)acceptfd)) != 0) { - printf("Error: In transCommitProcess() %s, %d\n", __FILE__, __LINE__); - /* Free memory */ - if (transinfo->objlocked != NULL) { - free(transinfo->objlocked); - } - if (transinfo->objnotfound != NULL) { - free(transinfo->objnotfound); - } - return 1; - } - break; - - case TRANS_ABORT_BUT_RETRY_COMMIT_WITH_RELOCATING: - break; - default: - printf("Error: No response to TRANS_AGREE OR DISAGREE protocol %s, %d\n", __FILE__, __LINE__); - //TODO Use fixed.trans_id TID since Client may have died - break; - } + recv_data((int)acceptfd, &control, sizeof(char)); + + /* Process the new control message */ + switch(control) { + case TRANS_ABORT: + if (fixed->nummod > 0) + free(modptr); + /* Unlock objects that was locked due to this transaction */ + for(i = 0; i< transinfo->numlocked; i++) { + if((header = mhashSearch(transinfo->objlocked[i])) == NULL) { + printf("mhashSearch returns NULL at %s, %d\n", __FILE__, __LINE__); // find the header address + return 1; + } + UnLock(STATUSPTR(header)); + } - /* Free memory */ - if (transinfo->objlocked != NULL) { - free(transinfo->objlocked); - } - if (transinfo->objnotfound != NULL) { - free(transinfo->objnotfound); - } - return 0; + /* Send ack to Coordinator */ + sendctrl = TRANS_UNSUCESSFUL; + send_data((int)acceptfd, &sendctrl, sizeof(char)); + break; + + case TRANS_COMMIT: + /* Invoke the transCommit process() */ + if((val = transCommitProcess(modptr, oidmod, transinfo->objlocked, fixed->nummod, transinfo->numlocked, (int)acceptfd)) != 0) { + printf("Error: In transCommitProcess() %s, %d\n", __FILE__, __LINE__); + /* Free memory */ + if (transinfo->objlocked != NULL) { + free(transinfo->objlocked); + } + if (transinfo->objnotfound != NULL) { + free(transinfo->objnotfound); + } + return 1; + } + break; + + case TRANS_ABORT_BUT_RETRY_COMMIT_WITH_RELOCATING: + break; + + default: + printf("Error: No response to TRANS_AGREE OR DISAGREE protocol %s, %d\n", __FILE__, __LINE__); + //TODO Use fixed.trans_id TID since Client may have died + break; + } + + /* Free memory */ + if (transinfo->objlocked != NULL) { + free(transinfo->objlocked); + } + if (transinfo->objnotfound != NULL) { + free(transinfo->objnotfound); + } + return 0; } -/* This function increments counters while running a voting decision on all objects involved +/* This function increments counters while running a voting decision on all objects involved * in TRANS_REQUEST and If a TRANS_DISAGREE sends the response immediately back to the coordinator */ char handleTransReq(fixed_data_t *fixed, trans_commit_data_t *transinfo, unsigned int *listmid, char *objread, void *modptr, int acceptfd) { - int val, i = 0, j; - unsigned short version; - char control = 0, *ptr; - unsigned int oid; - unsigned int *oidnotfound, *oidlocked, *oidvernotmatch; - void *mobj; - objheader_t *headptr; - - /* Counters and arrays to formulate decision on control message to be sent */ - oidnotfound = (unsigned int *) calloc(fixed->numread + fixed->nummod, sizeof(unsigned int)); - oidlocked = (unsigned int *) calloc(fixed->numread + fixed->nummod, sizeof(unsigned int)); - oidvernotmatch = (unsigned int *) calloc(fixed->numread + fixed->nummod, sizeof(unsigned int)); - int objnotfound = 0, objlocked = 0, objvernotmatch = 0; - int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0; - int numBytes = 0; - /* modptr points to the beginning of the object store - * created at the Pariticipant. - * Object store holds the modified objects involved in the transaction request */ - ptr = (char *) modptr; - - /* Process each oid in the machine pile/ group per thread */ - for (i = 0; i < fixed->numread + fixed->nummod; i++) { - if (i < fixed->numread) {//Objs only read and not modified - int incr = sizeof(unsigned int) + sizeof(unsigned short);// Offset that points to next position in the objread array - incr *= i; - oid = *((unsigned int *)(objread + incr)); - incr += sizeof(unsigned int); - version = *((unsigned short *)(objread + incr)); - } else {//Objs modified - int tmpsize; - headptr = (objheader_t *) ptr; - oid = OID(headptr); - version = headptr->version; - GETSIZE(tmpsize, headptr); - ptr += sizeof(objheader_t) + tmpsize; - } - - /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */ - - if ((mobj = mhashSearch(oid)) == NULL) {/* Obj not found */ - /* Save the oids not found and number of oids not found for later use */ - oidnotfound[objnotfound] = oid; - objnotfound++; - } else { /* If Obj found in machine (i.e. has not moved) */ - /* Check if Obj is locked by any previous transaction */ - if (test_and_set(STATUSPTR(mobj))) { - //don't have lock - if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */ - v_matchlock++; - } 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; - } - } else {/* If Obj is not locked then lock object */ - /* Save all object oids that are locked on this machine during this transaction request call */ - oidlocked[objlocked] = OID(((objheader_t *)mobj)); - objlocked++; - if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */ - v_matchnolock++; - } 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; - } - } - } + int val, i = 0, j; + unsigned short version; + char control = 0, *ptr; + unsigned int oid; + unsigned int *oidnotfound, *oidlocked, *oidvernotmatch; + void *mobj; + objheader_t *headptr; + + /* Counters and arrays to formulate decision on control message to be sent */ + oidnotfound = (unsigned int *) calloc(fixed->numread + fixed->nummod, sizeof(unsigned int)); + oidlocked = (unsigned int *) calloc(fixed->numread + fixed->nummod, sizeof(unsigned int)); + oidvernotmatch = (unsigned int *) calloc(fixed->numread + fixed->nummod, sizeof(unsigned int)); + int objnotfound = 0, objlocked = 0, objvernotmatch = 0; + int v_nomatch = 0, v_matchlock = 0, v_matchnolock = 0; + int numBytes = 0; + /* modptr points to the beginning of the object store + * created at the Pariticipant. + * Object store holds the modified objects involved in the transaction request */ + ptr = (char *) modptr; + + /* Process each oid in the machine pile/ group per thread */ + for (i = 0; i < fixed->numread + fixed->nummod; i++) { + if (i < fixed->numread) { //Objs only read and not modified + int incr = sizeof(unsigned int) + sizeof(unsigned short); // Offset that points to next position in the objread array + incr *= i; + oid = *((unsigned int *)(objread + incr)); + incr += sizeof(unsigned int); + version = *((unsigned short *)(objread + incr)); + } else { //Objs modified + int tmpsize; + headptr = (objheader_t *) ptr; + oid = OID(headptr); + version = headptr->version; + GETSIZE(tmpsize, headptr); + ptr += sizeof(objheader_t) + tmpsize; + } + + /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */ + + if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */ + /* Save the oids not found and number of oids not found for later use */ + oidnotfound[objnotfound] = oid; + objnotfound++; + } else { /* If Obj found in machine (i.e. has not moved) */ + /* Check if Obj is locked by any previous transaction */ + if (test_and_set(STATUSPTR(mobj))) { + //don't have lock + if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */ + v_matchlock++; + } 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; + } + } else { /* If Obj is not locked then lock object */ + /* Save all object oids that are locked on this machine during this transaction request call */ + oidlocked[objlocked] = OID(((objheader_t *)mobj)); + objlocked++; + if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */ + v_matchnolock++; + } 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; } - - /* send TRANS_DISAGREE and objs*/ - if(v_nomatch > 0) { -#ifdef CACHE - char *objs = calloc(1, numBytes); - int j, offset = 0; - for(j = 0; j 0) { +#ifdef CACHE + char *objs = calloc(1, numBytes); + int j, offset = 0; + for(j = 0; j 0) { - for(j = 0; j < objlocked; j++) { - if((headptr = mhashSearch(oidlocked[j])) == NULL) { - printf("mhashSearch returns NULL at %s, %d\n", __FILE__, __LINE__); - return 0; - } - UnLock(STATUSPTR(headptr)); - } - free(oidlocked); + if (objlocked > 0) { + for(j = 0; j < objlocked; j++) { + if((headptr = mhashSearch(oidlocked[j])) == NULL) { + printf("mhashSearch returns NULL at %s, %d\n", __FILE__, __LINE__); + return 0; + } + UnLock(STATUSPTR(headptr)); } - send_data(acceptfd, &control, sizeof(char)); + free(oidlocked); + } + send_data(acceptfd, &control, sizeof(char)); #ifdef CACHE - send_data(acceptfd, &numBytes, sizeof(int)); - send_data(acceptfd, objs, numBytes); - transinfo->objvernotmatch = oidvernotmatch; - transinfo->numvernotmatch = objvernotmatch; - free(objs); - free(transinfo->objvernotmatch); + send_data(acceptfd, &numBytes, sizeof(int)); + send_data(acceptfd, objs, numBytes); + transinfo->objvernotmatch = oidvernotmatch; + transinfo->numvernotmatch = objvernotmatch; + free(objs); + free(transinfo->objvernotmatch); #endif - return control; - } + return control; + } - /* Decide what control message to send to Coordinator */ - if ((control = decideCtrlMessage(fixed, transinfo, &v_matchnolock, &v_matchlock, &v_nomatch, &objnotfound, &objlocked, - modptr, oidnotfound, oidlocked, acceptfd)) == 0) { - printf("Error: In decideCtrlMessage() %s, %d\n", __FILE__, __LINE__); - return 0; - } - - return control; + /* Decide what control message to send to Coordinator */ + if ((control = decideCtrlMessage(fixed, transinfo, &v_matchnolock, &v_matchlock, &v_nomatch, &objnotfound, &objlocked, + modptr, oidnotfound, oidlocked, acceptfd)) == 0) { + printf("Error: In decideCtrlMessage() %s, %d\n", __FILE__, __LINE__); + return 0; + } + + return control; } /* This function decides what control message such as TRANS_AGREE, TRANS_DISAGREE or TRANS_SOFT_ABORT * to send to Coordinator based on the votes of oids involved in the transaction */ -char decideCtrlMessage(fixed_data_t *fixed, trans_commit_data_t *transinfo, int *v_matchnolock, int *v_matchlock, - int *v_nomatch, int *objnotfound, int *objlocked, void *modptr, - unsigned int *oidnotfound, unsigned int *oidlocked, int acceptfd) { - int val; - char control = 0; - - /* Condition to send TRANS_AGREE */ - if(*(v_matchnolock) == fixed->numread + fixed->nummod) { - control = TRANS_AGREE; - /* Send control message */ - send_data(acceptfd, &control, sizeof(char)); - } - /* Condition to send TRANS_SOFT_ABORT */ - if((*(v_matchlock) > 0 && *(v_nomatch) == 0) || (*(objnotfound) > 0 && *(v_nomatch) == 0)) { - control = TRANS_SOFT_ABORT; - - /* Send control message */ - send_data(acceptfd, &control, sizeof(char)); - - /* FIXME how to send objs Send number of oids not found and the missing oids if objects are missing in the machine */ - if(*(objnotfound) != 0) { - int msg[1]; - msg[0] = *(objnotfound); - send_data(acceptfd, &msg, sizeof(int)); - int size = sizeof(unsigned int)* *(objnotfound); - send_data(acceptfd, oidnotfound, size); - } - } +char decideCtrlMessage(fixed_data_t *fixed, trans_commit_data_t *transinfo, int *v_matchnolock, int *v_matchlock, + int *v_nomatch, int *objnotfound, int *objlocked, void *modptr, + unsigned int *oidnotfound, unsigned int *oidlocked, int acceptfd) { + int val; + char control = 0; + + /* Condition to send TRANS_AGREE */ + if(*(v_matchnolock) == fixed->numread + fixed->nummod) { + control = TRANS_AGREE; + /* Send control message */ + send_data(acceptfd, &control, sizeof(char)); + } + /* Condition to send TRANS_SOFT_ABORT */ + if((*(v_matchlock) > 0 && *(v_nomatch) == 0) || (*(objnotfound) > 0 && *(v_nomatch) == 0)) { + control = TRANS_SOFT_ABORT; + + /* Send control message */ + send_data(acceptfd, &control, sizeof(char)); + + /* FIXME how to send objs Send number of oids not found and the missing oids if objects are missing in the machine */ + if(*(objnotfound) != 0) { + int msg[1]; + msg[0] = *(objnotfound); + send_data(acceptfd, &msg, sizeof(int)); + int size = sizeof(unsigned int)* *(objnotfound); + send_data(acceptfd, oidnotfound, size); + } + } - /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process - * if Participant receives a TRANS_COMMIT */ - transinfo->objlocked = oidlocked; - transinfo->objnotfound = oidnotfound; - transinfo->modptr = modptr; - transinfo->numlocked = *(objlocked); - transinfo->numnotfound = *(objnotfound); + /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process + * if Participant receives a TRANS_COMMIT */ + transinfo->objlocked = oidlocked; + transinfo->objnotfound = oidnotfound; + transinfo->modptr = modptr; + transinfo->numlocked = *(objlocked); + transinfo->numnotfound = *(objnotfound); - return control; + return control; } -/* This function processes all modified objects involved in a TRANS_COMMIT and updates pointer +/* This function processes all modified objects involved in a TRANS_COMMIT and updates pointer * addresses in lookup table and also changes version number * Sends an ACK back to Coordinator */ int transCommitProcess(void *modptr, unsigned int *oidmod, unsigned int *oidlocked, int nummod, int numlocked, int acceptfd) { @@ -586,7 +588,7 @@ int transCommitProcess(void *modptr, unsigned int *oidmod, unsigned int *oidlock int i = 0, offset = 0; char control; int tmpsize; - + /* Process each modified object saved in the mainobject store */ for(i = 0; i < nummod; i++) { if((header = (objheader_t *) mhashSearch(oidmod[i])) == NULL) { @@ -595,17 +597,17 @@ int transCommitProcess(void *modptr, unsigned int *oidmod, unsigned int *oidlock } GETSIZE(tmpsize,header); memcpy((char*)header + sizeof(objheader_t), ((char *)modptr + sizeof(objheader_t) + offset), tmpsize); - header->version += 1; + header->version += 1; /* If threads are waiting on this object to be updated, notify them */ if(header->notifylist != NULL) { notifyAll(&header->notifylist, OID(header), header->version); } offset += sizeof(objheader_t) + tmpsize; } - + if (nummod > 0) free(modptr); - + /* Unlock locked objects */ for(i = 0; i < numlocked; i++) { if((header = (objheader_t *) mhashSearch(oidlocked[i])) == NULL) { @@ -615,7 +617,7 @@ int transCommitProcess(void *modptr, unsigned int *oidmod, unsigned int *oidlock UnLock(STATUSPTR(header)); } //TODO Update location lookup table - + /* Send ack to coordinator */ control = TRANS_SUCESSFUL; send_data((int)acceptfd, &control, sizeof(char)); @@ -635,10 +637,10 @@ int prefetchReq(int acceptfd) { objheader_t *header; oidmidpair_t oidmid; int sd = -1; - + while(1) { recv_data((int)acceptfd, &numoffset, sizeof(int)); - if(numoffset == -1) + if(numoffset == -1) break; recv_data((int)acceptfd, &oidmid, 2*sizeof(unsigned int)); oid = oidmid.oid; @@ -651,9 +653,9 @@ int prefetchReq(int acceptfd) { } short offsetarry[numoffset]; recv_data((int) acceptfd, offsetarry, numoffset*sizeof(short)); - + /*Process each oid */ - if ((header = mhashSearch(oid)) == NULL) {/* Obj not found */ + if ((header = mhashSearch(oid)) == NULL) { /* Obj not found */ /* Save the oids not found in buffer for later use */ size = sizeof(int) + sizeof(char) + sizeof(unsigned int) ; char sendbuffer[size]; @@ -667,17 +669,17 @@ int prefetchReq(int acceptfd) { GETSIZE(objsize, header); size = sizeof(int) + sizeof(char) + sizeof(unsigned int) + sizeof(objheader_t) + objsize; char sendbuffer[size]; - *((int *) (sendbuffer + incr)) = size; + *((int *)(sendbuffer + incr)) = size; incr += sizeof(int); *((char *)(sendbuffer + incr)) = OBJECT_FOUND; incr += sizeof(char); *((unsigned int *)(sendbuffer+incr)) = oid; incr += sizeof(unsigned int); memcpy(sendbuffer + incr, header, objsize + sizeof(objheader_t)); - + control = TRANS_PREFETCH_RESPONSE; sendPrefetchResponse(sd, &control, sendbuffer, &size); - + /* Calculate the oid corresponding to the offset value */ for(i = 0 ; i< numoffset ; i++) { /* Check for arrays */ @@ -693,7 +695,7 @@ int prefetchReq(int acceptfd) { } else { oid = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + offsetarry[i])); } - + /* Don't continue if we hit a NULL pointer */ if (oid==0) break; @@ -704,23 +706,23 @@ int prefetchReq(int acceptfd) { *((int *) sendbuffer) = size; *((char *)(sendbuffer + sizeof(int))) = OBJECT_NOT_FOUND; *((unsigned int *)(sendbuffer + sizeof(int) + sizeof(char))) = oid; - + control = TRANS_PREFETCH_RESPONSE; sendPrefetchResponse(sd, &control, sendbuffer, &size); break; - } else {/* Obj Found */ + } else { /* Obj Found */ int incr = 0; GETSIZE(objsize, header); size = sizeof(int) + sizeof(char) + sizeof(unsigned int) + sizeof(objheader_t) + objsize; char sendbuffer[size]; - *((int *) (sendbuffer + incr)) = size; + *((int *)(sendbuffer + incr)) = size; incr += sizeof(int); *((char *)(sendbuffer + incr)) = OBJECT_FOUND; incr += sizeof(char); *((unsigned int *)(sendbuffer+incr)) = oid; incr += sizeof(unsigned int); memcpy(sendbuffer + incr, header, objsize + sizeof(objheader_t)); - + control = TRANS_PREFETCH_RESPONSE; sendPrefetchResponse(sd, &control, sendbuffer, &size); } @@ -730,15 +732,15 @@ int prefetchReq(int acceptfd) { //Release socket if (mid!=-1) freeSockWithLock(transPResponseSocketPool, mid, sd); - + return 0; } void sendPrefetchResponse(int sd, char *control, char *sendbuffer, int *size) { - send_data(sd, control, sizeof(char)); - /* Send the buffer with its size */ - int length = *(size); - send_data(sd, sendbuffer, length); + send_data(sd, control, sizeof(char)); + /* Send the buffer with its size */ + int length = *(size); + send_data(sd, sendbuffer, length); } void processReqNotify(unsigned int numoid, unsigned int *oidarry, unsigned short *versionarry, unsigned int mid, unsigned int threadid) { @@ -751,7 +753,7 @@ void processReqNotify(unsigned int numoid, unsigned int *oidarry, unsigned short int bytesSent; int size; int i = 0; - + while(i < numoid) { oid = *(oidarry + i); if((header = (objheader_t *) mhashSearch(oid)) == NULL) { @@ -759,14 +761,14 @@ void processReqNotify(unsigned int numoid, unsigned int *oidarry, unsigned short return; } else { /* Check to see if versions are same */ - checkversion: +checkversion: if (test_and_set(STATUSPTR(header))==0) { //have lock newversion = header->version; if(newversion == *(versionarry + i)) { - //Add to the notify list + //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__); + printf("Error: Obj notify list points to NULL %s, %d\n", __FILE__, __LINE__); return; } UnLock(STATUSPTR(header)); @@ -780,10 +782,10 @@ void processReqNotify(unsigned int numoid, unsigned int *oidarry, unsigned short 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); + inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT); close(sd); return; } else { diff --git a/Robust/src/Runtime/DSTM/interface/gCollect.c b/Robust/src/Runtime/DSTM/interface/gCollect.c index 1dd09c25..98b1fa80 100644 --- a/Robust/src/Runtime/DSTM/interface/gCollect.c +++ b/Robust/src/Runtime/DSTM/interface/gCollect.c @@ -17,7 +17,7 @@ void initializePCache() { void *prefetchobjstrAlloc(unsigned int size) { void * ptr = NULL; if(pNodeInfo->num_old_objstr <= PREFETCH_FLUSH_COUNT_THRESHOLD) { - //regular allocation + //regular allocation if((ptr = normalPrefetchAlloc(prefetchcache, size)) == NULL) { printf("Error: %s() prefetch cache alloc error %s, %d\n", __func__, __FILE__, __LINE__); return NULL; @@ -29,25 +29,25 @@ void *prefetchobjstrAlloc(unsigned int size) { return ptr; } else { //allocate new block if size not available if(size >= pNodeInfo->maxsize) { - if((ptr = allocateNew(size)) == NULL) { - printf("Error: %s() Calloc error %s %d\n", __func__, __FILE__, __LINE__); - return NULL; - } - return ptr; + if((ptr = allocateNew(size)) == NULL) { + printf("Error: %s() Calloc error %s %d\n", __func__, __FILE__, __LINE__); + return NULL; + } + return ptr; } else { //If size less then reclaim old blocks - clearNBlocks(pNodeInfo->oldptr, pNodeInfo->newptr); - //update oldptr and newptr - updatePtrs(); - //look for free space if available in the free blocks - if((ptr = lookUpFreeSpace(pNodeInfo->newptr, pNodeInfo->oldptr, size)) != NULL) { - return ptr; - } else { - if((ptr = allocateNew(size)) == NULL) { - printf("Error: %s() Calloc error %s %d\n", __func__, __FILE__, __LINE__); - return NULL; - } - return ptr; - } + clearNBlocks(pNodeInfo->oldptr, pNodeInfo->newptr); + //update oldptr and newptr + updatePtrs(); + //look for free space if available in the free blocks + if((ptr = lookUpFreeSpace(pNodeInfo->newptr, pNodeInfo->oldptr, size)) != NULL) { + return ptr; + } else { + if((ptr = allocateNew(size)) == NULL) { + printf("Error: %s() Calloc error %s %d\n", __func__, __FILE__, __LINE__); + return NULL; + } + return ptr; + } } } } @@ -60,32 +60,32 @@ void *normalPrefetchAlloc(objstr_t *store, unsigned int size) { tmp = store->top; store->top += size; return tmp; - } + } //store full if(store->next == NULL) { //end of list, all full if(size > DEFAULT_OBJ_STORE_SIZE) { - //in case of large objects - if((store->next = (objstr_t *) calloc(1,(sizeof(objstr_t) + size))) == NULL) { - printf("%s() Calloc error at line %d, %s\n", __func__, __LINE__, __FILE__); - return NULL; - } - store = store->next; - store->size = size; + //in case of large objects + if((store->next = (objstr_t *) calloc(1,(sizeof(objstr_t) + size))) == NULL) { + printf("%s() Calloc error at line %d, %s\n", __func__, __LINE__, __FILE__); + return NULL; + } + store = store->next; + store->size = size; } else { - if((store->next = (objstr_t *) calloc(1, (sizeof(objstr_t) + DEFAULT_OBJ_STORE_SIZE))) == NULL) { - printf("%s() Calloc error at line %d, %s\n", __func__, __LINE__, __FILE__); - return NULL; - } - store = store->next; - store->size = DEFAULT_OBJ_STORE_SIZE; + if((store->next = (objstr_t *) calloc(1, (sizeof(objstr_t) + DEFAULT_OBJ_STORE_SIZE))) == NULL) { + printf("%s() Calloc error at line %d, %s\n", __func__, __LINE__, __FILE__); + return NULL; + } + store = store->next; + store->size = DEFAULT_OBJ_STORE_SIZE; } - //Update maxsize of objstr blocks, num of blocks and newptr + //Update maxsize of objstr blocks, num of blocks and newptr pNodeInfo->num_old_objstr++; if(pNodeInfo->num_old_objstr <= PREFETCH_FLUSH_COUNT_THRESHOLD/2) - pNodeInfo->newptr = store; + pNodeInfo->newptr = store; if(pNodeInfo->maxsize < size) - pNodeInfo->maxsize = size; + pNodeInfo->maxsize = size; store->top = (void *)(((unsigned int)store) + sizeof(objstr_t) + size); return (void *)(((unsigned int)store) + sizeof(objstr_t)); } else { @@ -97,8 +97,8 @@ void *normalPrefetchAlloc(objstr_t *store, unsigned int size) { void *lookUpFreeSpace(void *startAddr, void *endAddr, int size) { objstr_t *ptr; void *tmp; - ptr = (objstr_t *) (startAddr); - while(ptr != NULL && ((unsigned long int)ptr!= (unsigned long int)endAddr)) { + ptr = (objstr_t *)(startAddr); + while(ptr != NULL && ((unsigned long int)ptr!= (unsigned long int)endAddr)) { if(((unsigned int)ptr->top - (((unsigned int)ptr) + sizeof(objstr_t)) + size) <= ptr->size) { //store not full tmp = ptr->top; ptr->top += size; @@ -136,11 +136,11 @@ void clearPLookUpTable(void *begin, void *end) { prehashlistnode_t *curr = &ptr[i]; for(; curr != NULL; curr = curr->next) { if(((unsigned long int)(curr->val) >= tmpbegin) && ((unsigned long int)(curr->val) < tmpend)) { - unsigned int oid = curr->key; - objheader_t *objheader; - if((objheader = prehashSearch(oid)) != NULL) { - prehashRemove(oid); - } + unsigned int oid = curr->key; + objheader_t *objheader; + if((objheader = prehashSearch(oid)) != NULL) { + prehashRemove(oid); + } } } } @@ -165,7 +165,7 @@ void *allocateNew(unsigned int size) { tmp->next = ((objstr_t *)(pNodeInfo->newptr))->next; ((objstr_t *)(pNodeInfo->newptr))->next = tmp; pNodeInfo->num_old_objstr++; - // Update maxsize of prefetch objstr blocks + // Update maxsize of prefetch objstr blocks if(pNodeInfo->maxsize < tmp->size) pNodeInfo->maxsize = tmp->size; return (void *)(((unsigned int)tmp) + sizeof(objstr_t)); diff --git a/Robust/src/Runtime/DSTM/interface/ip.c b/Robust/src/Runtime/DSTM/interface/ip.c index 9c97347e..81237854 100644 --- a/Robust/src/Runtime/DSTM/interface/ip.c +++ b/Robust/src/Runtime/DSTM/interface/ip.c @@ -12,93 +12,90 @@ #define LISTEN_PORT 2156 unsigned int iptoMid(char *addr) { - ip_t i; - unsigned int mid; + ip_t i; + unsigned int mid; - sscanf(addr, "%d.%d.%d.%d", &i.a, &i.b, &i.c, &i.d); - mid = (i.a << 24) | (i.b << 16) | (i.c << 8) | i.d; - fflush(stdout); - return mid; + sscanf(addr, "%d.%d.%d.%d", &i.a, &i.b, &i.c, &i.d); + mid = (i.a << 24) | (i.b << 16) | (i.c << 8) | i.d; + fflush(stdout); + return mid; } void midtoIP(unsigned int mid, char *ptr) { - ip_t i; + ip_t i; - i.a = (mid & 0xff000000) >> 24; - i.b = (mid & 0x00ff0000) >> 16; - i.c = (mid & 0x0000ff00) >> 8; - i.d = mid & 0x000000ff; - sprintf(ptr, "%d.%d.%d.%d", i.a, i.b, i.c, i.d); + i.a = (mid & 0xff000000) >> 24; + i.b = (mid & 0x00ff0000) >> 16; + i.c = (mid & 0x0000ff00) >> 8; + i.d = mid & 0x000000ff; + sprintf(ptr, "%d.%d.%d.%d", i.a, i.b, i.c, i.d); #ifdef DEBUG - printf("DEBUG-> midtoIP() mid = %d.%d.%d.%d\n", i.a, i.b, i.c, i.d); + printf("DEBUG-> midtoIP() mid = %d.%d.%d.%d\n", i.a, i.b, i.c, i.d); #endif - return; + return; } int checkServer(int mid, char *machineip) { - int tmpsd; - struct sockaddr_in serv_addr; - char m[20]; - - strncpy(m, machineip, strlen(machineip)); - // Foreach machine you want to transact with - // check if its up and running - if ((tmpsd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { - perror(""); - return(-1); - } - bzero((char*) &serv_addr, sizeof(serv_addr)); - serv_addr.sin_family = AF_INET; - serv_addr.sin_port = htons(LISTEN_PORT); - midtoIP(mid, m); - m[15] = '\0'; - serv_addr.sin_addr.s_addr = inet_addr(m); - while (connect(tmpsd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) { - sleep(1); - } - close(tmpsd); - return 0; + int tmpsd; + struct sockaddr_in serv_addr; + char m[20]; + + strncpy(m, machineip, strlen(machineip)); + // Foreach machine you want to transact with + // check if its up and running + if ((tmpsd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { + perror(""); + return(-1); + } + bzero((char*) &serv_addr, sizeof(serv_addr)); + serv_addr.sin_family = AF_INET; + serv_addr.sin_port = htons(LISTEN_PORT); + midtoIP(mid, m); + m[15] = '\0'; + serv_addr.sin_addr.s_addr = inet_addr(m); + while (connect(tmpsd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0) { + sleep(1); + } + close(tmpsd); + return 0; } -unsigned int getMyIpAddr(const char *interfaceStr) -{ - int sock; - struct ifreq interfaceInfo; - struct sockaddr_in *myAddr = (struct sockaddr_in *)&interfaceInfo.ifr_addr; +unsigned int getMyIpAddr(const char *interfaceStr) { + int sock; + struct ifreq interfaceInfo; + struct sockaddr_in *myAddr = (struct sockaddr_in *)&interfaceInfo.ifr_addr; + + memset(&interfaceInfo, 0, sizeof(struct ifreq)); - memset(&interfaceInfo, 0, sizeof(struct ifreq)); + if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){ + perror("getMyIpAddr():socket()"); + return 1; + } - if((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) - { - perror("getMyIpAddr():socket()"); - return 1; - } + strcpy(interfaceInfo.ifr_name, interfaceStr); + myAddr->sin_family = AF_INET; - strcpy(interfaceInfo.ifr_name, interfaceStr); - myAddr->sin_family = AF_INET; - - if(ioctl(sock, SIOCGIFADDR, &interfaceInfo) != 0) - { - perror("getMyIpAddr():ioctl()"); - return 1; - } + if(ioctl(sock, SIOCGIFADDR, &interfaceInfo) != 0){ + perror("getMyIpAddr():ioctl()"); + return 1; + } - close(sock); + close(sock); - return ntohl(myAddr->sin_addr.s_addr); + return ntohl(myAddr->sin_addr.s_addr); } /* -main() { - unsigned int mid; - ip_t i; - char ip[16]; - - memset(ip, 0, 16); - mid = iptoMid("192.10.0.1"); - printf("mid = %x\n", mid); - midtoIP(mid, ip); - ip[15] = '\0'; - printf("%s\n",ip); -} -*/ + main() { + unsigned int mid; + ip_t i; + char ip[16]; + + memset(ip, 0, 16); + mid = iptoMid("192.10.0.1"); + printf("mid = %x\n", mid); + midtoIP(mid, ip); + ip[15] = '\0'; + printf("%s\n",ip); + } + */ diff --git a/Robust/src/Runtime/DSTM/interface/ip.h b/Robust/src/Runtime/DSTM/interface/ip.h index 29db799c..cbac6e64 100644 --- a/Robust/src/Runtime/DSTM/interface/ip.h +++ b/Robust/src/Runtime/DSTM/interface/ip.h @@ -2,11 +2,11 @@ #define _ip_h_ typedef struct ip { - short a; - short b; - short c; - short d; -}ip_t; + short a; + short b; + short c; + short d; +} ip_t; unsigned int iptoMid(char *); void midtoIP(unsigned int, char *); diff --git a/Robust/src/Runtime/DSTM/interface/llookup.c b/Robust/src/Runtime/DSTM/interface/llookup.c index 30760978..ec49a90a 100644 --- a/Robust/src/Runtime/DSTM/interface/llookup.c +++ b/Robust/src/Runtime/DSTM/interface/llookup.c @@ -1,12 +1,12 @@ /************************************************************************************************ - IMP NOTE: + IMP NOTE: All llookup hash function prototypes returns 0 on sucess and 1 otherwise llookup hash is an array of lhashlistnode_t oid = mid = 0 in a given lhashlistnode_t for each bin in the hash table ONLY if the entry is empty => the OID's can be any unsigned int except 0 Uses pthreads. compile using -lpthread option -***************************************************************************************************/ + ***************************************************************************************************/ #include "llookup.h" #ifdef SIMPLE_LLOOKUP @@ -14,214 +14,210 @@ extern unsigned int *hostIpAddrs; extern unsigned int oidsPerBlock; -unsigned int lhashCreate(unsigned int size, float loadfactor) -{ - return 0; +unsigned int lhashCreate(unsigned int size, float loadfactor) { + return 0; } -unsigned int lhashInsert(unsigned int oid, unsigned int mid) -{ - return 0; +unsigned int lhashInsert(unsigned int oid, unsigned int mid) { + return 0; } -unsigned int lhashSearch(unsigned int oid) -{ - if (oidsPerBlock == 0) - return hostIpAddrs[0]; - else - return hostIpAddrs[oid / oidsPerBlock]; +unsigned int lhashSearch(unsigned int oid) { + if (oidsPerBlock == 0) + return hostIpAddrs[0]; + else + return hostIpAddrs[oid / oidsPerBlock]; } -unsigned int lhashRemove(unsigned int oid) -{ - return 0; +unsigned int lhashRemove(unsigned int oid) { + return 0; } #else -lhashtable_t llookup; //Global Hash table +lhashtable_t llookup; //Global Hash table -// Creates a hash table with size and an array of lhashlistnode_t +// Creates a hash table with size and an array of lhashlistnode_t unsigned int lhashCreate(unsigned int size, float loadfactor) { - lhashlistnode_t *nodes; - int i; - - // Allocate space for the hash table - if((nodes = calloc(size, sizeof(lhashlistnode_t))) == NULL) { - printf("Calloc error %s %d\n", __FILE__, __LINE__); - return 1; - } - - llookup.table = nodes; - llookup.size = size; - llookup.numelements = 0; // Initial number of elements in the hash - llookup.loadfactor = loadfactor; - //Initialize the pthread_mutex variable - pthread_mutex_init(&llookup.locktable, NULL); - return 0; + lhashlistnode_t *nodes; + int i; + + // Allocate space for the hash table + if((nodes = calloc(size, sizeof(lhashlistnode_t))) == NULL) { + printf("Calloc error %s %d\n", __FILE__, __LINE__); + return 1; + } + + llookup.table = nodes; + llookup.size = size; + llookup.numelements = 0; // Initial number of elements in the hash + llookup.loadfactor = loadfactor; + //Initialize the pthread_mutex variable + pthread_mutex_init(&llookup.locktable, NULL); + return 0; } // Assign to oids to bins inside hash table unsigned int lhashFunction(unsigned int oid) { - return( oid % (llookup.size)); + return( oid % (llookup.size)); } // Insert oid and mid mapping into the hash table unsigned int lhashInsert(unsigned int oid, unsigned int mid) { - unsigned int newsize; - int index; - lhashlistnode_t *ptr, *node; - - if (llookup.numelements > (llookup.loadfactor * llookup.size)) { - //Resize Table - newsize = 2 * llookup.size + 1; - pthread_mutex_lock(&llookup.locktable); - lhashResize(newsize); - pthread_mutex_unlock(&llookup.locktable); - } - - ptr = llookup.table; - llookup.numelements++; - - index = lhashFunction(oid); + unsigned int newsize; + int index; + lhashlistnode_t *ptr, *node; + + if (llookup.numelements > (llookup.loadfactor * llookup.size)) { + //Resize Table + newsize = 2 * llookup.size + 1; + pthread_mutex_lock(&llookup.locktable); + lhashResize(newsize); + pthread_mutex_unlock(&llookup.locktable); + } + + ptr = llookup.table; + llookup.numelements++; + + index = lhashFunction(oid); #ifdef DEBUG - printf("DEBUG(insert) oid = %d, mid =%d, index =%d\n",oid,mid, index); + printf("DEBUG(insert) oid = %d, mid =%d, index =%d\n",oid,mid, index); #endif - pthread_mutex_lock(&llookup.locktable); - if(ptr[index].next == NULL && ptr[index].oid == 0) { // Insert at the first position in the hashtable - ptr[index].oid = oid; - ptr[index].mid = mid; - } else { // Insert in the linked list - if ((node = calloc(1, sizeof(lhashlistnode_t))) == NULL) { - printf("Calloc error %s, %d\n", __FILE__, __LINE__); - pthread_mutex_unlock(&llookup.locktable); - return 1; - } - node->oid = oid; - node->mid = mid; - node->next = ptr[index].next; - ptr[index].next = node; - } - - pthread_mutex_unlock(&llookup.locktable); - return 0; + pthread_mutex_lock(&llookup.locktable); + if(ptr[index].next == NULL && ptr[index].oid == 0) { // Insert at the first position in the hashtable + ptr[index].oid = oid; + ptr[index].mid = mid; + } else { // Insert in the linked list + if ((node = calloc(1, sizeof(lhashlistnode_t))) == NULL) { + printf("Calloc error %s, %d\n", __FILE__, __LINE__); + pthread_mutex_unlock(&llookup.locktable); + return 1; + } + node->oid = oid; + node->mid = mid; + node->next = ptr[index].next; + ptr[index].next = node; + } + + pthread_mutex_unlock(&llookup.locktable); + return 0; } // Return mid for a given oid in the hash table unsigned int lhashSearch(unsigned int oid) { - int index; - lhashlistnode_t *ptr, *node; - - ptr = llookup.table; // Address of the beginning of hash table - index = lhashFunction(oid); - node = &ptr[index]; - pthread_mutex_lock(&llookup.locktable); - while(node != NULL) { - if(node->oid == oid) { - pthread_mutex_unlock(&llookup.locktable); - return node->mid; - } - node = node->next; - } - pthread_mutex_unlock(&llookup.locktable); - return 0; + int index; + lhashlistnode_t *ptr, *node; + + ptr = llookup.table; // Address of the beginning of hash table + index = lhashFunction(oid); + node = &ptr[index]; + pthread_mutex_lock(&llookup.locktable); + while(node != NULL) { + if(node->oid == oid) { + pthread_mutex_unlock(&llookup.locktable); + return node->mid; + } + node = node->next; + } + pthread_mutex_unlock(&llookup.locktable); + return 0; } // Remove an entry from the hash table unsigned int lhashRemove(unsigned int oid) { - int index; - lhashlistnode_t *curr, *prev; - lhashlistnode_t *ptr, *node; - - ptr = llookup.table; - index = lhashFunction(oid); - curr = &ptr[index]; - - pthread_mutex_lock(&llookup.locktable); - for (; curr != NULL; curr = curr->next) { - 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; - } 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); - } else { // Regular delete from linked listed - prev->next = curr->next; - free(curr); - } - pthread_mutex_unlock(&llookup.locktable); - return 0; - } - prev = curr; - } - pthread_mutex_unlock(&llookup.locktable); - return 1; + int index; + lhashlistnode_t *curr, *prev; + lhashlistnode_t *ptr, *node; + + ptr = llookup.table; + index = lhashFunction(oid); + curr = &ptr[index]; + + pthread_mutex_lock(&llookup.locktable); + for (; curr != NULL; curr = curr->next) { + 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; + } 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); + } else { // Regular delete from linked listed + prev->next = curr->next; + free(curr); + } + pthread_mutex_unlock(&llookup.locktable); + return 0; + } + prev = curr; + } + pthread_mutex_unlock(&llookup.locktable); + return 1; } // Resize table unsigned int lhashResize(unsigned int newsize) { - lhashlistnode_t *node, *ptr, *curr, *next; // curr and next keep track of the current and the next lhashlistnodes in a linked list - unsigned int oldsize; - int isfirst; // Keeps track of the first element in the lhashlistnode_t for each bin in hashtable - int i,index; - lhashlistnode_t *newnode; - - ptr = llookup.table; - oldsize = llookup.size; - - if((node = calloc(newsize, sizeof(lhashlistnode_t))) == NULL) { - printf("Calloc error %s %d\n", __FILE__, __LINE__); - return 1; + lhashlistnode_t *node, *ptr, *curr, *next; // curr and next keep track of the current and the next lhashlistnodes in a linked list + unsigned int oldsize; + int isfirst; // Keeps track of the first element in the lhashlistnode_t for each bin in hashtable + int i,index; + lhashlistnode_t *newnode; + + ptr = llookup.table; + oldsize = llookup.size; + + if((node = calloc(newsize, sizeof(lhashlistnode_t))) == NULL) { + printf("Calloc error %s %d\n", __FILE__, __LINE__); + return 1; + } + + llookup.table = node; //Update the global hashtable upon resize() + llookup.size = newsize; + llookup.numelements = 0; + + for(i = 0; i < oldsize; i++) { //Outer loop for each bin in hash table + curr = &ptr[i]; + 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 + } + 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++; + } 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++; + } - llookup.table = node; //Update the global hashtable upon resize() - llookup.size = newsize; - llookup.numelements = 0; - - for(i = 0; i < oldsize; i++) { //Outer loop for each bin in hash table - curr = &ptr[i]; - 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 - } - 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++; - }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++; - } - - //free the linked list of lhashlistnode_t if not the first element in the hash table - if (isfirst != 1) { - free(curr); - } - - isfirst = 0; - curr = next; - - } - } + //free the linked list of lhashlistnode_t if not the first element in the hash table + if (isfirst != 1) { + free(curr); + } + + isfirst = 0; + curr = next; + + } + } - free(ptr); //Free the memory of the old hash table - return 0; + free(ptr); //Free the memory of the old hash table + return 0; } #endif diff --git a/Robust/src/Runtime/DSTM/interface/llookup.h b/Robust/src/Runtime/DSTM/interface/llookup.h index 29c0d304..3f9f44c7 100644 --- a/Robust/src/Runtime/DSTM/interface/llookup.h +++ b/Robust/src/Runtime/DSTM/interface/llookup.h @@ -11,17 +11,17 @@ #define HASH_SIZE 100 typedef struct lhashlistnode { - unsigned int oid; - unsigned int mid; - struct lhashlistnode *next; + unsigned int oid; + unsigned int mid; + struct lhashlistnode *next; } lhashlistnode_t; typedef struct lhashtable { - lhashlistnode_t *table; // points to beginning of hash table - unsigned int size; - unsigned int numelements; - float loadfactor; - pthread_mutex_t locktable; + lhashlistnode_t *table; // points to beginning of hash table + unsigned int size; + unsigned int numelements; + float loadfactor; + pthread_mutex_t locktable; } lhashtable_t; //returns 0 for success and 1 for failure diff --git a/Robust/src/Runtime/DSTM/interface/localobjects.h b/Robust/src/Runtime/DSTM/interface/localobjects.h index 6b69ee87..c1c7be13 100644 --- a/Robust/src/Runtime/DSTM/interface/localobjects.h +++ b/Robust/src/Runtime/DSTM/interface/localobjects.h @@ -3,7 +3,7 @@ #include "structdefs.h" #include "garbage.h" void REVERT_OBJ(struct ___Object___ *); -#define COMMIT_OBJ(obj) obj->___localcopy___=NULL;\ +#define COMMIT_OBJ(obj) obj->___localcopy___=NULL; \ obj->___nextobject___=NULL #ifdef PRECISE_GC diff --git a/Robust/src/Runtime/DSTM/interface/machinepile.c b/Robust/src/Runtime/DSTM/interface/machinepile.c index 10b5aed8..9d4a15de 100644 --- a/Robust/src/Runtime/DSTM/interface/machinepile.c +++ b/Robust/src/Runtime/DSTM/interface/machinepile.c @@ -7,7 +7,7 @@ void insertPile(int mid, unsigned int oid, short numoffset, short *offset, prefe objpile_t **tmp; //Loop through the machines - for(;1;head=&((*head)->next)) { + for(; 1; head=&((*head)->next)) { int tmid; if ((*head)==NULL||(tmid=(*head)->mid)>mid) { prefetchpile_t * tmp = (prefetchpile_t *) malloc(sizeof(prefetchpile_t)); @@ -26,9 +26,9 @@ void insertPile(int mid, unsigned int oid, short numoffset, short *offset, prefe //keep looking if (tmid < mid) continue; - + //found mid list - for(tmp=&((*head)->objpiles);1;tmp=&((*tmp)->next)) { + for(tmp=&((*head)->objpiles); 1; tmp=&((*tmp)->next)) { int toid; int matchstatus; @@ -43,13 +43,13 @@ void insertPile(int mid, unsigned int oid, short numoffset, short *offset, prefe } if (toid < oid) continue; - + /* Fill objpiles DS */ int i; int onumoffset=(*tmp)->numoffset; short * ooffset=(*tmp)->offset; - for(i=0;ionumoffset) { //We've matched, let's just extend the current prefetch (*tmp)->numoffset=numoffset; @@ -71,10 +71,10 @@ void insertPile(int mid, unsigned int oid, short numoffset, short *offset, prefe } //if we get to the end, we're already covered by this prefetch return; - oidloop: +oidloop: ; } } - + } diff --git a/Robust/src/Runtime/DSTM/interface/main.c b/Robust/src/Runtime/DSTM/interface/main.c index 3a6f44f7..0f9e91f5 100644 --- a/Robust/src/Runtime/DSTM/interface/main.c +++ b/Robust/src/Runtime/DSTM/interface/main.c @@ -1,25 +1,25 @@ -#include -#include -#include +#include +#include +#include #include "dstm.h" #define size 1000000 - + obj_addr_table_t mlut; -int classsize[]={sizeof(int),sizeof(char),sizeof(short), sizeof(void *)}; +int classsize[]={sizeof(int),sizeof(char),sizeof(short), sizeof(void *)}; + +int main() { + int i; + + dstm_init(); + create_objstr(size); + createHash(&mlut, HASH_SIZE, 0.75); + + for(i=0; i< 4 ; i++) { + createObject(i); + } -int main() { - int i; - - dstm_init(); - create_objstr(size); - createHash(&mlut, HASH_SIZE, 0.75); - - for(i=0; i< 4 ; i++) { - createObject(i); - } - - createObject(3); - return 0; + createObject(3); + return 0; } diff --git a/Robust/src/Runtime/DSTM/interface/mcpileq.c b/Robust/src/Runtime/DSTM/interface/mcpileq.c index bb58ecef..f8929907 100644 --- a/Robust/src/Runtime/DSTM/interface/mcpileq.c +++ b/Robust/src/Runtime/DSTM/interface/mcpileq.c @@ -3,13 +3,13 @@ mcpileq_t mcqueue; //Global queue void mcpileqInit(void) { - /* Initialize machine queue that containing prefetch oids and offset values sorted by remote machineid */ + /* Initialize machine queue that containing prefetch oids and offset values sorted by remote machineid */ mcqueue.front = mcqueue.rear = NULL; //Intiliaze and set machile pile queue's mutex attribute pthread_mutexattr_init(&mcqueue.qlockattr); pthread_mutexattr_settype(&mcqueue.qlockattr, PTHREAD_MUTEX_RECURSIVE_NP); - pthread_mutex_init(&mcqueue.qlock,&mcqueue.qlockattr); - pthread_cond_init(&mcqueue.qcond, NULL); + pthread_mutex_init(&mcqueue.qlock,&mcqueue.qlockattr); + pthread_cond_init(&mcqueue.qcond, NULL); } /* Insert to the rear of machine pile queue */ @@ -34,13 +34,13 @@ prefetchpile_t *mcpiledequeue(void) { if (mcqueue.front == NULL) mcqueue.rear = NULL; retnode->next = NULL; - + return retnode; } void mcpiledisplay() { int mid; - + prefetchpile_t *tmp = mcqueue.front; while(tmp != NULL) { printf("Remote machine id = %d\n", tmp->mid); @@ -54,9 +54,9 @@ void mcdealloc(prefetchpile_t *node) { prefetchpile_t *prefetchpile_next_ptr; objpile_t *objpile_ptr; objpile_t *objpile_next_ptr; - + prefetchpile_ptr = node; - + while (prefetchpile_ptr != NULL) { prefetchpile_next_ptr = prefetchpile_ptr; while(prefetchpile_ptr->objpiles != NULL) { diff --git a/Robust/src/Runtime/DSTM/interface/mcpileq.h b/Robust/src/Runtime/DSTM/interface/mcpileq.h index f32c7b69..5c0ab8ba 100644 --- a/Robust/src/Runtime/DSTM/interface/mcpileq.h +++ b/Robust/src/Runtime/DSTM/interface/mcpileq.h @@ -1,13 +1,13 @@ #ifndef _MCPILEQ_H_ #define _MCPILEQ_H_ -#include -#include -#include -#include +#include +#include +#include +#include //Structure to make machine groups when prefetching -typedef struct objpile { +typedef struct objpile { unsigned int oid; short numoffset; short *offset; diff --git a/Robust/src/Runtime/DSTM/interface/mlookup.c b/Robust/src/Runtime/DSTM/interface/mlookup.c index 9000b80e..a554d62f 100644 --- a/Robust/src/Runtime/DSTM/interface/mlookup.c +++ b/Robust/src/Runtime/DSTM/interface/mlookup.c @@ -1,218 +1,215 @@ #include "mlookup.h" -mhashtable_t mlookup; //Global hash table - -// Creates a machine lookup table with size =" size" -unsigned int mhashCreate(unsigned int size, float loadfactor) { - mhashlistnode_t *nodes; - // Allocate space for the hash table - if((nodes = calloc(size, sizeof(mhashlistnode_t))) == NULL) { - printf("Calloc error %s %d\n", __FILE__, __LINE__); - return 1; - } - - mlookup.table = nodes; - mlookup.size = size; - mlookup.numelements = 0; // Initial number of elements in the hash - mlookup.loadfactor = loadfactor; - //Initialize the pthread_mutex variable - pthread_mutex_init(&mlookup.locktable, NULL); - return 0; +mhashtable_t mlookup; //Global hash table + +// Creates a machine lookup table with size =" size" +unsigned int mhashCreate(unsigned int size, float loadfactor) { + mhashlistnode_t *nodes; + // Allocate space for the hash table + if((nodes = calloc(size, sizeof(mhashlistnode_t))) == NULL) { + printf("Calloc error %s %d\n", __FILE__, __LINE__); + return 1; + } + + mlookup.table = nodes; + mlookup.size = size; + mlookup.numelements = 0; // Initial number of elements in the hash + mlookup.loadfactor = loadfactor; + //Initialize the pthread_mutex variable + pthread_mutex_init(&mlookup.locktable, NULL); + return 0; } // Assign to keys to bins inside hash table unsigned int mhashFunction(unsigned int key) { - return( key % (mlookup.size)); + return( key % (mlookup.size)); } // Insert value and key mapping into the hash table unsigned int mhashInsert(unsigned int key, void *val) { - unsigned int newsize; - int index; - mhashlistnode_t *ptr, *node; - - if (mlookup.numelements > (mlookup.loadfactor * mlookup.size)) { - //Resize Table - newsize = 2 * mlookup.size + 1; - pthread_mutex_lock(&mlookup.locktable); - mhashResize(newsize); - pthread_mutex_unlock(&mlookup.locktable); - } - ptr = mlookup.table; - mlookup.numelements++; - + unsigned int newsize; + int index; + mhashlistnode_t *ptr, *node; + + if (mlookup.numelements > (mlookup.loadfactor * mlookup.size)) { + //Resize Table + newsize = 2 * mlookup.size + 1; + pthread_mutex_lock(&mlookup.locktable); + mhashResize(newsize); + pthread_mutex_unlock(&mlookup.locktable); + } + ptr = mlookup.table; + mlookup.numelements++; + #ifdef DEBUG - printf("DEBUG -> index = %d, key = %d, val = %x\n", index, key, val); + printf("DEBUG -> index = %d, key = %d, val = %x\n", index, key, val); #endif - pthread_mutex_lock(&mlookup.locktable); - index = mhashFunction(key); - if(ptr[index].next == NULL && ptr[index].key == 0) { // Insert at the first position in the hashtable - ptr[index].key = key; - ptr[index].val = val; - } else { // Insert in the beginning of linked list - if ((node = calloc(1, sizeof(mhashlistnode_t))) == NULL) { - printf("Calloc error %s, %d\n", __FILE__, __LINE__); - pthread_mutex_unlock(&mlookup.locktable); - return 1; - } - node->key = key; - node->val = val; - node->next = ptr[index].next; - ptr[index].next = node; - } - pthread_mutex_unlock(&mlookup.locktable); - return 0; + pthread_mutex_lock(&mlookup.locktable); + index = mhashFunction(key); + if(ptr[index].next == NULL && ptr[index].key == 0) { // Insert at the first position in the hashtable + ptr[index].key = key; + ptr[index].val = val; + } else { // Insert in the beginning of linked list + if ((node = calloc(1, sizeof(mhashlistnode_t))) == NULL) { + printf("Calloc error %s, %d\n", __FILE__, __LINE__); + pthread_mutex_unlock(&mlookup.locktable); + return 1; + } + node->key = key; + node->val = val; + node->next = ptr[index].next; + ptr[index].next = node; + } + pthread_mutex_unlock(&mlookup.locktable); + return 0; } // Return val for a given key in the hash table void *mhashSearch(unsigned int key) { - int index; - mhashlistnode_t *ptr, *node; - - pthread_mutex_lock(&mlookup.locktable); - ptr = mlookup.table; // Address of the beginning of hash table - index = mhashFunction(key); - node = &ptr[index]; - while(node != NULL) { - if(node->key == key) { - pthread_mutex_unlock(&mlookup.locktable); - return node->val; - } - node = node->next; - } - pthread_mutex_unlock(&mlookup.locktable); - return NULL; + int index; + mhashlistnode_t *ptr, *node; + + pthread_mutex_lock(&mlookup.locktable); + ptr = mlookup.table; // Address of the beginning of hash table + index = mhashFunction(key); + node = &ptr[index]; + while(node != NULL) { + if(node->key == key) { + pthread_mutex_unlock(&mlookup.locktable); + return node->val; + } + node = node->next; + } + pthread_mutex_unlock(&mlookup.locktable); + return NULL; } // Remove an entry from the hash table unsigned int mhashRemove(unsigned int key) { - int index; - mhashlistnode_t *curr, *prev; - mhashlistnode_t *ptr, *node; - - pthread_mutex_lock(&mlookup.locktable); - ptr = mlookup.table; - index = mhashFunction(key); - curr = &ptr[index]; - for (; curr != NULL; curr = curr->next) { - 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; - } 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); - } else { // Regular delete from linked listed - prev->next = curr->next; - free(curr); - } - pthread_mutex_unlock(&mlookup.locktable); - return 0; - } - prev = curr; - } - pthread_mutex_unlock(&mlookup.locktable); - return 1; + int index; + mhashlistnode_t *curr, *prev; + mhashlistnode_t *ptr, *node; + + pthread_mutex_lock(&mlookup.locktable); + ptr = mlookup.table; + index = mhashFunction(key); + curr = &ptr[index]; + for (; curr != NULL; curr = curr->next) { + 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; + } 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); + } else { // Regular delete from linked listed + prev->next = curr->next; + free(curr); + } + pthread_mutex_unlock(&mlookup.locktable); + return 0; + } + prev = curr; + } + pthread_mutex_unlock(&mlookup.locktable); + return 1; } // Resize table unsigned int mhashResize(unsigned int newsize) { - mhashlistnode_t *node, *ptr, *curr, *next; // curr and next keep track of the current and the next mhashlistnodes in a linked list - unsigned int oldsize; - int isfirst; // Keeps track of the first element in the mhashlistnode_t for each bin in hashtable - int i,index; - mhashlistnode_t *newnode; - - ptr = mlookup.table; - oldsize = mlookup.size; - - if((node = calloc(newsize, sizeof(mhashlistnode_t))) == NULL) { - printf("Calloc error %s %d\n", __FILE__, __LINE__); - return 1; - } - - mlookup.table = node; //Update the global hashtable upon resize() - mlookup.size = newsize; - mlookup.numelements = 0; - - for(i = 0; i < oldsize; i++) { //Outer loop for each bin in hash table - curr = &ptr[i]; - isfirst = 1; - while (curr != NULL) { //Inner loop to go through linked lists - if (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 - } - next = curr->next; - - index = mhashFunction(curr->key); + mhashlistnode_t *node, *ptr, *curr, *next; // curr and next keep track of the current and the next mhashlistnodes in a linked list + unsigned int oldsize; + int isfirst; // Keeps track of the first element in the mhashlistnode_t for each bin in hashtable + int i,index; + mhashlistnode_t *newnode; + + ptr = mlookup.table; + oldsize = mlookup.size; + + if((node = calloc(newsize, sizeof(mhashlistnode_t))) == NULL) { + printf("Calloc error %s %d\n", __FILE__, __LINE__); + return 1; + } + + mlookup.table = node; //Update the global hashtable upon resize() + mlookup.size = newsize; + mlookup.numelements = 0; + + for(i = 0; i < oldsize; i++) { //Outer loop for each bin in hash table + curr = &ptr[i]; + isfirst = 1; + while (curr != NULL) { //Inner loop to go through linked lists + if (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 + } + next = curr->next; + + index = mhashFunction(curr->key); #ifdef DEBUG - printf("DEBUG(resize) -> index = %d, key = %d, val = %x\n", index, curr->key, curr->val); + printf("DEBUG(resize) -> index = %d, key = %d, val = %x\n", index, curr->key, curr->val); #endif - // Insert into the new table - if(mlookup.table[index].next == NULL && mlookup.table[index].key == 0) { - mlookup.table[index].key = curr->key; - mlookup.table[index].val = curr->val; - mlookup.numelements++; - }else { - if((newnode = calloc(1, sizeof(mhashlistnode_t))) == NULL) { - printf("Calloc error %s, %d\n", __FILE__, __LINE__); - return 1; - } - newnode->key = curr->key; - newnode->val = curr->val; - newnode->next = mlookup.table[index].next; - mlookup.table[index].next = newnode; - mlookup.numelements++; - } - - //free the linked list of mhashlistnode_t if not the first element in the hash table - if (isfirst != 1) { - free(curr); - } - - isfirst = 0; - curr = next; - - } + // Insert into the new table + if(mlookup.table[index].next == NULL && mlookup.table[index].key == 0) { + mlookup.table[index].key = curr->key; + mlookup.table[index].val = curr->val; + mlookup.numelements++; + } else { + if((newnode = calloc(1, sizeof(mhashlistnode_t))) == NULL) { + printf("Calloc error %s, %d\n", __FILE__, __LINE__); + return 1; } + newnode->key = curr->key; + newnode->val = curr->val; + newnode->next = mlookup.table[index].next; + mlookup.table[index].next = newnode; + mlookup.numelements++; + } - free(ptr); //Free the memory of the old hash table - return 0; -} + //free the linked list of mhashlistnode_t if not the first element in the hash table + if (isfirst != 1) { + free(curr); + } -unsigned int *mhashGetKeys(unsigned int *numKeys) -{ - unsigned int *keys; - int i, keyindex; - mhashlistnode_t *curr; - - pthread_mutex_lock(&mlookup.locktable); - - *numKeys = mlookup.numelements; - keys = calloc(*numKeys, sizeof(unsigned int)); - - keyindex = 0; - for (i = 0; i < mlookup.size; i++) - { - if (mlookup.table[i].key != 0) - { - curr = &mlookup.table[i]; - while (curr != NULL) - { - keys[keyindex++] = curr->key; - curr = curr->next; - } - } - } + isfirst = 0; + curr = next; - if (keyindex != *numKeys) - printf("mhashGetKeys(): WARNING: incorrect mlookup.numelements value!\n"); + } + } + + free(ptr); //Free the memory of the old hash table + return 0; +} - pthread_mutex_unlock(&mlookup.locktable); - return keys; +unsigned int *mhashGetKeys(unsigned int *numKeys) { + unsigned int *keys; + int i, keyindex; + mhashlistnode_t *curr; + + pthread_mutex_lock(&mlookup.locktable); + + *numKeys = mlookup.numelements; + keys = calloc(*numKeys, sizeof(unsigned int)); + + keyindex = 0; + for (i = 0; i < mlookup.size; i++) + { + if (mlookup.table[i].key != 0){ + curr = &mlookup.table[i]; + while (curr != NULL){ + keys[keyindex++] = curr->key; + curr = curr->next; + } + } + } + + if (keyindex != *numKeys) + printf("mhashGetKeys(): WARNING: incorrect mlookup.numelements value!\n"); + + pthread_mutex_unlock(&mlookup.locktable); + return keys; } diff --git a/Robust/src/Runtime/DSTM/interface/mlookup.h b/Robust/src/Runtime/DSTM/interface/mlookup.h index aec88798..f3360d4a 100644 --- a/Robust/src/Runtime/DSTM/interface/mlookup.h +++ b/Robust/src/Runtime/DSTM/interface/mlookup.h @@ -9,17 +9,17 @@ #define HASH_SIZE 100 typedef struct mhashlistnode { - unsigned int key; - void *val; //this can be cast to another type or used to point to a larger structure - struct mhashlistnode *next; + unsigned int key; + void *val; //this can be cast to another type or used to point to a larger structure + struct mhashlistnode *next; } mhashlistnode_t; typedef struct mhashtable { - mhashlistnode_t *table; // points to beginning of hash table - unsigned int size; - unsigned int numelements; - float loadfactor; - pthread_mutex_t locktable; + mhashlistnode_t *table; // points to beginning of hash table + unsigned int size; + unsigned int numelements; + float loadfactor; + pthread_mutex_t locktable; } mhashtable_t; unsigned int mhashCreate(unsigned int size, float loadfactor); diff --git a/Robust/src/Runtime/DSTM/interface/objstr.c b/Robust/src/Runtime/DSTM/interface/objstr.c index 32bf38de..b3d2cbdd 100644 --- a/Robust/src/Runtime/DSTM/interface/objstr.c +++ b/Robust/src/Runtime/DSTM/interface/objstr.c @@ -35,20 +35,20 @@ void *objstrAlloc(objstr_t *store, unsigned int size) { if (store->next == NULL) { //end of list, all full if (size > DEFAULT_OBJ_STORE_SIZE) { - //in case of large objects - if((store->next = (objstr_t *)calloc(1,(sizeof(objstr_t) + size))) == NULL) { - printf("%s() Calloc error at line %d, %s\n", __func__, __LINE__, __FILE__); - return NULL; - } - store = store->next; - store->size = size; + //in case of large objects + if((store->next = (objstr_t *)calloc(1,(sizeof(objstr_t) + size))) == NULL) { + printf("%s() Calloc error at line %d, %s\n", __func__, __LINE__, __FILE__); + return NULL; + } + store = store->next; + store->size = size; } else { - if((store->next = calloc(1,(sizeof(objstr_t) + DEFAULT_OBJ_STORE_SIZE))) == NULL) { - printf("%s() Calloc error at line %d, %s\n", __func__, __LINE__, __FILE__); - return NULL; - } - store = store->next; - store->size = DEFAULT_OBJ_STORE_SIZE; + if((store->next = calloc(1,(sizeof(objstr_t) + DEFAULT_OBJ_STORE_SIZE))) == NULL) { + printf("%s() Calloc error at line %d, %s\n", __func__, __LINE__, __FILE__); + return NULL; + } + store = store->next; + store->size = DEFAULT_OBJ_STORE_SIZE; } store->top = (void *)(((unsigned int)store) + sizeof(objstr_t) + size); return (void *)(((unsigned int)store) + sizeof(objstr_t)); diff --git a/Robust/src/Runtime/DSTM/interface/plookup.c b/Robust/src/Runtime/DSTM/interface/plookup.c index 683f11d4..3eee2cbd 100644 --- a/Robust/src/Runtime/DSTM/interface/plookup.c +++ b/Robust/src/Runtime/DSTM/interface/plookup.c @@ -1,7 +1,7 @@ #include "plookup.h" extern int classsize[]; -//NOTE: "pile" ptr points to the head of the linked list of the machine pile data structures +//NOTE: "pile" ptr points to the head of the linked list of the machine pile data structures /* This function creates a new pile data structure to hold * obj ids of objects modified or read inside a transaction, @@ -9,73 +9,73 @@ extern int classsize[]; * that belong to a single machine */ plistnode_t *pCreate(int objects) { - plistnode_t *pile; - - //Create main structure - if((pile = calloc(1, sizeof(plistnode_t))) == NULL) { - printf("Calloc error %s %d\n", __FILE__, __LINE__); - return NULL; - } - if ((pile->oidmod = calloc(objects, sizeof(unsigned int))) == NULL) { - printf("Calloc error %s %d\n", __FILE__, __LINE__); - free(pile); - return NULL; - } - if ((pile->oidcreated = calloc(objects, sizeof(unsigned int))) == NULL) { - printf("Calloc error %s %d\n", __FILE__, __LINE__); - free(pile); - free(pile->oidmod); - return NULL; - } - if ((pile->objread = calloc(objects, sizeof(unsigned int) + sizeof(short))) == NULL) { - printf("Calloc error %s %d\n", __FILE__, __LINE__); - free(pile); - free(pile->oidmod); - free(pile->oidcreated); - return NULL; - } + plistnode_t *pile; - pile->nummod = pile->numread = pile->numcreated = pile->sum_bytes = pile->mid = 0; - pile->next = NULL; - return pile; + //Create main structure + if((pile = calloc(1, sizeof(plistnode_t))) == NULL) { + printf("Calloc error %s %d\n", __FILE__, __LINE__); + return NULL; + } + if ((pile->oidmod = calloc(objects, sizeof(unsigned int))) == NULL) { + printf("Calloc error %s %d\n", __FILE__, __LINE__); + free(pile); + return NULL; + } + if ((pile->oidcreated = calloc(objects, sizeof(unsigned int))) == NULL) { + printf("Calloc error %s %d\n", __FILE__, __LINE__); + free(pile); + free(pile->oidmod); + return NULL; + } + if ((pile->objread = calloc(objects, sizeof(unsigned int) + sizeof(short))) == NULL) { + printf("Calloc error %s %d\n", __FILE__, __LINE__); + free(pile); + free(pile->oidmod); + free(pile->oidcreated); + return NULL; + } + + pile->nummod = pile->numread = pile->numcreated = pile->sum_bytes = pile->mid = 0; + pile->next = NULL; + return pile; } //Count the number of machine piles int pCount(plistnode_t *pile) { - plistnode_t *tmp; - int pcount = 0; - tmp = pile; - while(tmp != NULL) { - pcount++; - tmp = tmp->next; - } - return pcount; + plistnode_t *tmp; + int pcount = 0; + tmp = pile; + while(tmp != NULL) { + pcount++; + tmp = tmp->next; + } + return pcount; } //Make a list of mid's for each machine group int pListMid(plistnode_t *pile, unsigned int *list) { - int i = 0; - plistnode_t *tmp; - tmp = pile; - while (tmp != NULL) { - list[i] = tmp->mid; - i++; - tmp = tmp->next; - } - return 0; + int i = 0; + plistnode_t *tmp; + tmp = pile; + while (tmp != NULL) { + list[i] = tmp->mid; + i++; + tmp = tmp->next; + } + return 0; } //Delete the entire pile void pDelete(plistnode_t *pile) { - plistnode_t *next, *tmp; - tmp = pile; - while(tmp != NULL) { - next = tmp->next; - free(tmp->oidmod); - free(tmp->oidcreated); - free(tmp->objread); - free(tmp); - tmp = next; - } - return; + plistnode_t *next, *tmp; + tmp = pile; + while(tmp != NULL) { + next = tmp->next; + free(tmp->oidmod); + free(tmp->oidcreated); + free(tmp->objread); + free(tmp); + tmp = next; + } + return; } diff --git a/Robust/src/Runtime/DSTM/interface/plookup.h b/Robust/src/Runtime/DSTM/interface/plookup.h index 4d15b4a7..d4137839 100644 --- a/Robust/src/Runtime/DSTM/interface/plookup.h +++ b/Robust/src/Runtime/DSTM/interface/plookup.h @@ -5,18 +5,18 @@ #include /* This structure is created using a transaction record. - * It is filled out with pile information necessary for + * It is filled out with pile information necessary for * participants involved in a transaction. */ typedef struct plistnode { - unsigned int mid; - unsigned int numread; /* no of objects modified */ - unsigned int nummod; /* no of objects read */ - unsigned int numcreated; /* no of objects created */ - int sum_bytes; /* total bytes of objects modified */ - char *objread; /* Pointer to array containing oids of objects read and their version numbers*/ - unsigned int *oidmod; /* Pointer to array containing oids of modified objects */ - unsigned int *oidcreated; /* Pointer to array containing oids of newly created objects */ - struct plistnode *next; + unsigned int mid; + unsigned int numread; /* no of objects modified */ + unsigned int nummod; /* no of objects read */ + unsigned int numcreated; /* no of objects created */ + int sum_bytes; /* total bytes of objects modified */ + char *objread; /* Pointer to array containing oids of objects read and their version numbers*/ + unsigned int *oidmod; /* Pointer to array containing oids of modified objects */ + unsigned int *oidcreated; /* Pointer to array containing oids of newly created objects */ + struct plistnode *next; } plistnode_t; plistnode_t *pCreate(int); diff --git a/Robust/src/Runtime/DSTM/interface/prelookup.c b/Robust/src/Runtime/DSTM/interface/prelookup.c index f003e0f1..79a616f4 100644 --- a/Robust/src/Runtime/DSTM/interface/prelookup.c +++ b/Robust/src/Runtime/DSTM/interface/prelookup.c @@ -5,31 +5,31 @@ extern objstr_t *prefetchcache; prehashtable_t pflookup; //Global prefetch cache table unsigned int prehashCreate(unsigned int size, float loadfactor) { - prehashlistnode_t *nodes; - int i; - - // Allocate space for the hash table - if((nodes = calloc(size, sizeof(prehashlistnode_t))) == NULL) { + prehashlistnode_t *nodes; + int i; + + // Allocate space for the hash table + if((nodes = calloc(size, sizeof(prehashlistnode_t))) == NULL) { printf("Calloc error %s %d\n", __FILE__, __LINE__); return 1; } pflookup.hack=NULL; pflookup.hack2=NULL; pflookup.table = nodes; - pflookup.size = size; + pflookup.size = size; pflookup.numelements = 0; // Initial number of elements in the hash pflookup.loadfactor = loadfactor; - + //Intiliaze and set prefetch table mutex attribute pthread_mutexattr_init(&pflookup.prefetchmutexattr); //NOTE:PTHREAD_MUTEX_RECURSIVE is currently inside a #if_def UNIX98 in the pthread.h file //Therefore use PTHREAD_MUTEX_RECURSIVE_NP instead pthread_mutexattr_settype(&pflookup.prefetchmutexattr, PTHREAD_MUTEX_RECURSIVE_NP); - + //Initialize mutex var pthread_mutex_init(&pflookup.lock, &pflookup.prefetchmutexattr); //pthread_mutex_init(&pflookup.lock, NULL); - pthread_cond_init(&pflookup.cond, NULL); + pthread_cond_init(&pflookup.cond, NULL); return 0; } @@ -43,7 +43,7 @@ unsigned int prehashInsert(unsigned int key, void *val) { unsigned int newsize; int index; prehashlistnode_t *ptr, *node; - + if(pflookup.numelements > (pflookup.loadfactor * pflookup.size)) { //Resize newsize = 2 * pflookup.size + 1; @@ -51,16 +51,16 @@ unsigned int prehashInsert(unsigned int key, void *val) { prehashResize(newsize); pthread_mutex_unlock(&pflookup.lock); } - + ptr = pflookup.table; pflookup.numelements++; - + pthread_mutex_lock(&pflookup.lock); index = prehashFunction(key); - if(ptr[index].next == NULL && ptr[index].key == 0) { // Insert at the first position in the hashtable + if(ptr[index].next == NULL && ptr[index].key == 0) { // Insert at the first position in the hashtable ptr[index].key = key; ptr[index].val = val; - } else { // Insert in the beginning of linked list + } else { // Insert in the beginning of linked list if ((node = calloc(1, sizeof(prehashlistnode_t))) == NULL) { printf("Calloc error %s, %d\n", __FILE__, __LINE__); pthread_mutex_unlock(&pflookup.lock); @@ -79,7 +79,7 @@ unsigned int prehashInsert(unsigned int key, void *val) { void *prehashSearch(unsigned int key) { int index; prehashlistnode_t *ptr, *node; - + pthread_mutex_lock(&pflookup.lock); ptr = pflookup.table; index = prehashFunction(key); @@ -101,105 +101,105 @@ unsigned int prehashRemove(unsigned int key) { prehashlistnode_t *ptr, *node; pthread_mutex_lock(&pflookup.lock); - ptr = pflookup.table; + ptr = pflookup.table; index = prehashFunction(key); curr = &ptr[index]; - + for (; curr != NULL; curr = curr->next) { 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 + 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; - } else if ((curr == &ptr[index]) && (curr->next != NULL)) { //Delete the first item with a linked list of prehashlistnode_t connected + } 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); - } else { // Regular delete from linked listed + } else { // Regular delete from linked listed prev->next = curr->next; free(curr); } pthread_mutex_unlock(&pflookup.lock); return 0; - } - prev = curr; + } + prev = curr; } pthread_mutex_unlock(&pflookup.lock); return 1; } unsigned int prehashResize(unsigned int newsize) { - prehashlistnode_t *node, *ptr, *curr, *next; // curr and next keep track of the current and the next chashlistnodes in a linked list + prehashlistnode_t *node, *ptr, *curr, *next; // curr and next keep track of the current and the next chashlistnodes in a linked list unsigned int oldsize; int isfirst; // Keeps track of the first element in the prehashlistnode_t for each bin in hashtable - int i,index; - prehashlistnode_t *newnode; - + int i,index; + prehashlistnode_t *newnode; + ptr = pflookup.table; oldsize = pflookup.size; - + if((node = calloc(newsize, sizeof(prehashlistnode_t))) == NULL) { printf("Calloc error %s %d\n", __FILE__, __LINE__); return 1; } - - pflookup.table = node; //Update the global hashtable upon resize() + + pflookup.table = node; //Update the global hashtable upon resize() pflookup.size = newsize; pflookup.numelements = 0; - - for(i = 0; i < oldsize; i++) { //Outer loop for each bin in hash table + + for(i = 0; i < oldsize; i++) { //Outer loop for each bin in hash table curr = &ptr[i]; - isfirst = 1; - while (curr != NULL) { //Inner loop to go through linked lists - if (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 + isfirst = 1; + while (curr != NULL) { //Inner loop to go through linked lists + if (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 } next = curr->next; index = prehashFunction(curr->key); // Insert into the new table - if(pflookup.table[index].next == NULL && pflookup.table[index].key == 0) { + if(pflookup.table[index].next == NULL && pflookup.table[index].key == 0) { pflookup.table[index].key = curr->key; pflookup.table[index].val = curr->val; pflookup.numelements++; - }else { - if((newnode = calloc(1, sizeof(prehashlistnode_t))) == NULL) { + } else { + if((newnode = calloc(1, sizeof(prehashlistnode_t))) == NULL) { printf("Calloc error %s, %d\n", __FILE__, __LINE__); return 1; - } + } newnode->key = curr->key; newnode->val = curr->val; newnode->next = pflookup.table[index].next; - pflookup.table[index].next = newnode; + pflookup.table[index].next = newnode; pflookup.numelements++; - } - + } + //free the linked list of prehashlistnode_t if not the first element in the hash table if (isfirst != 1) { free(curr); - } - + } + isfirst = 0; curr = next; } } - - free(ptr); //Free the memory of the old hash table + + free(ptr); //Free the memory of the old hash table return 0; } -//Note: This is based on the implementation of the inserting a key in the first position of the hashtable +//Note: This is based on the implementation of the inserting a key in the first position of the hashtable void prehashClear() { #ifdef CACHE int i, isFirstBin; prehashlistnode_t *ptr, *prev, *curr; - + objstr_t *oldcache=prefetchcache; prefetchcache=objstrCreate(prefetchcache->size); pthread_mutex_lock(&pflookup.lock); - ptr = pflookup.table; + ptr = pflookup.table; for(i = 0; i < pflookup.size; i++) { prev = &ptr[i]; isFirstBin = 1; diff --git a/Robust/src/Runtime/DSTM/interface/prelookup.h b/Robust/src/Runtime/DSTM/interface/prelookup.h index 8b4c30be..023e53cc 100644 --- a/Robust/src/Runtime/DSTM/interface/prelookup.h +++ b/Robust/src/Runtime/DSTM/interface/prelookup.h @@ -10,15 +10,15 @@ #define HASH_SIZE 100 typedef struct prehashlistnode { - unsigned int key; - void *val; //this can be cast to another type or used to point to a larger structure - struct prehashlistnode *next; + unsigned int key; + void *val; //this can be cast to another type or used to point to a larger structure + struct prehashlistnode *next; } prehashlistnode_t; struct objstr; typedef struct prehashtable { - prehashlistnode_t *table; // points to beginning of hash table + prehashlistnode_t *table; // points to beginning of hash table unsigned int size; unsigned int numelements; float loadfactor; diff --git a/Robust/src/Runtime/DSTM/interface/queue.c b/Robust/src/Runtime/DSTM/interface/queue.c index 2fb7e990..c892a030 100644 --- a/Robust/src/Runtime/DSTM/interface/queue.c +++ b/Robust/src/Runtime/DSTM/interface/queue.c @@ -12,7 +12,7 @@ void queueInit(void) { /* Intitialize primary queue */ headoffset=0; tailoffset=0; - memory=malloc(QSIZE+sizeof(int));//leave space for -1 + memory=malloc(QSIZE+sizeof(int)); //leave space for -1 pthread_mutexattr_init(&qlockattr); pthread_mutexattr_settype(&qlockattr, PTHREAD_MUTEX_RECURSIVE_NP); pthread_mutex_init(&qlock, &qlockattr); @@ -25,20 +25,20 @@ void * getmemory(int size) { //Wait for tail to go past end tmpoffset=size+sizeof(int); if (headoffset -#include -#include -#include +#include +#include +#include +#include #include "dstm.h" void queueInit(void); diff --git a/Robust/src/Runtime/DSTM/interface/signal.c b/Robust/src/Runtime/DSTM/interface/signal.c index b670548a..f88b06d8 100644 --- a/Robust/src/Runtime/DSTM/interface/signal.c +++ b/Robust/src/Runtime/DSTM/interface/signal.c @@ -23,11 +23,11 @@ void transStatsHandler(int sig, siginfo_t* info, void *context) { printf("nRemoteReadSend = %d\n", nRemoteSend); //TODO Remove later /* - int i; - for(i=0; itable = nodelist; sockhash->inuse = NULL; sockhash->size = size; sockhash->mask = size - 1; sockhash->mylock=0; - + return sockhash; } @@ -83,10 +83,10 @@ int getSockWithLock(sockPoolHashTable_t *sockhash, unsigned int mid) { socknode_t **ptr; int key = mid&(sockhash->mask); int sd; - + Lock(&sockhash->mylock); ptr=&(sockhash->table[key]); - + while(*ptr!=NULL) { if (mid == (*ptr)->mid) { socknode_t *tmp=*ptr; @@ -115,9 +115,9 @@ int getSock(sockPoolHashTable_t *sockhash, unsigned int mid) { socknode_t **ptr; int key = mid&(sockhash->mask); int sd; - + ptr=&(sockhash->table[key]); - + while(*ptr!=NULL) { if (mid == (*ptr)->mid) { socknode_t *tmp=*ptr; @@ -143,9 +143,9 @@ int getSock2(sockPoolHashTable_t *sockhash, unsigned int mid) { socknode_t **ptr; int key = mid&(sockhash->mask); int sd; - + ptr=&(sockhash->table[key]); - + while(*ptr!=NULL) { if (mid == (*ptr)->mid) { return (*ptr)->sd; @@ -167,7 +167,7 @@ int getSock2WithLock(sockPoolHashTable_t *sockhash, unsigned int mid) { socknode_t **ptr; int key = mid&(sockhash->mask); int sd; - + Lock(&sockhash->mylock); ptr=&(sockhash->table[key]); while(*ptr!=NULL) { @@ -198,27 +198,27 @@ void addSockWithLock(sockPoolHashTable_t *sockhash, socknode_t *ptr) { } void insToListWithLock(sockPoolHashTable_t *sockhash, socknode_t *inusenode) { - Lock(&sockhash->mylock); - inusenode->next = sockhash->inuse; - sockhash->inuse = inusenode; - UnLock(&sockhash->mylock); -} + Lock(&sockhash->mylock); + inusenode->next = sockhash->inuse; + sockhash->inuse = inusenode; + UnLock(&sockhash->mylock); +} void freeSock(sockPoolHashTable_t *sockhash, unsigned int mid, int sd) { - int key = mid&(sockhash->mask); - socknode_t *ptr = sockhash->inuse; - sockhash->inuse = ptr->next; - ptr->mid = mid; - ptr->sd = sd; - ptr->next = sockhash->table[key]; - sockhash->table[key] = ptr; + int key = mid&(sockhash->mask); + socknode_t *ptr = sockhash->inuse; + sockhash->inuse = ptr->next; + ptr->mid = mid; + ptr->sd = sd; + ptr->next = sockhash->table[key]; + sockhash->table[key] = ptr; } void freeSockWithLock(sockPoolHashTable_t *sockhash, unsigned int mid, int sd) { int key = mid&(sockhash->mask); socknode_t *ptr; Lock(&sockhash->mylock); - ptr = sockhash->inuse; + ptr = sockhash->inuse; sockhash->inuse = ptr->next; ptr->mid = mid; ptr->sd = sd; @@ -229,94 +229,94 @@ void freeSockWithLock(sockPoolHashTable_t *sockhash, unsigned int mid, int sd) { #if 0 /*************************************** - * Array Implementation for socket reuse + * Array Implementation for socket reuse ****************************************/ int num_machines; sock_pool_t *initSockPool(unsigned int *mid, int machines) { - sock_pool_t *sockpool; - num_machines = machines; - if ((sockpool = calloc(num_machines, sizeof(sock_pool_t))) < 0) { - printf("%s(), Calloc error at %s, line %d\n", __func__, __FILE__, __LINE__); - return NULL; + sock_pool_t *sockpool; + num_machines = machines; + if ((sockpool = calloc(num_machines, sizeof(sock_pool_t))) < 0) { + printf("%s(), Calloc error at %s, line %d\n", __func__, __FILE__, __LINE__); + return NULL; + } + int i; + for (i = 0; i < num_machines; i++) { + if ((sockpool[i].sd = calloc(MAX_CONN_PER_MACHINE, sizeof(int))) < 0) { + printf("%s(), Calloc error at %s, line %d\n", __func__, __FILE__, __LINE__); + return NULL; } - int i; - for (i = 0; i < num_machines; i++) { - if ((sockpool[i].sd = calloc(MAX_CONN_PER_MACHINE, sizeof(int))) < 0) { - printf("%s(), Calloc error at %s, line %d\n", __func__, __FILE__, __LINE__); - return NULL; - } - if ((sockpool[i].inuse = calloc(MAX_CONN_PER_MACHINE, sizeof(char))) < 0) { - printf("%s(), Calloc error at %s, line %d\n", __func__, __FILE__, __LINE__); - return NULL; - } - sockpool[i].mid = mid[i]; - int j; - for(j = 0; j < MAX_CONN_PER_MACHINE; j++) { - sockpool[i].sd[j] = -1; - } + if ((sockpool[i].inuse = calloc(MAX_CONN_PER_MACHINE, sizeof(char))) < 0) { + printf("%s(), Calloc error at %s, line %d\n", __func__, __FILE__, __LINE__); + return NULL; } + sockpool[i].mid = mid[i]; + int j; + for(j = 0; j < MAX_CONN_PER_MACHINE; j++) { + sockpool[i].sd[j] = -1; + } + } - return sockpool; + return sockpool; } int getSock(sock_pool_t *sockpool, unsigned int mid) { - int i; - for (i = 0; i < num_machines; i++) { - 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]; - } - } - printf("%s()->Error: Less number of MAX_CONN_PER_MACHINE\n", __func__); - return -1; - } + int i; + for (i = 0; i < num_machines; i++) { + 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]; + } + } + printf("%s()->Error: Less number of MAX_CONN_PER_MACHINE\n", __func__); + return -1; } - printf("%s()-> Error: Machine id not found\n", __func__); + } + printf("%s()-> Error: Machine id not found\n", __func__); - return -1; + return -1; } int freeSock(sock_pool_t *sockpool, int sd) { - int i; - for (i = 0; i < num_machines; i++) { - int j; - for (j = 0; j < MAX_CONN_PER_MACHINE; j++) { - if (sockpool[i].sd[j] == sd) { - sockpool[i].inuse[j] = 0; - return 0; - } - } + int i; + for (i = 0; i < num_machines; i++) { + int j; + for (j = 0; j < MAX_CONN_PER_MACHINE; j++) { + if (sockpool[i].sd[j] == sd) { + sockpool[i].inuse[j] = 0; + return 0; + } } - printf("%s() Error: Illegal socket descriptor %d\n", __func__, sd); + } + printf("%s() Error: Illegal socket descriptor %d\n", __func__, sd); - return -1; + return -1; } #endif diff --git a/Robust/src/Runtime/DSTM/interface/sockpool.h b/Robust/src/Runtime/DSTM/interface/sockpool.h index 471774af..1494b0e2 100644 --- a/Robust/src/Runtime/DSTM/interface/sockpool.h +++ b/Robust/src/Runtime/DSTM/interface/sockpool.h @@ -9,24 +9,24 @@ int test_and_set(volatile unsigned int *addr); void UnLock(volatile unsigned int *addr); typedef struct socknode { - int sd; - unsigned int mid; - struct socknode *next; + int sd; + unsigned int mid; + struct socknode *next; } socknode_t; typedef struct sockPoolHashTable { - socknode_t **table; - socknode_t *inuse; - unsigned int size; + socknode_t **table; + socknode_t *inuse; + unsigned int size; unsigned int mask; - volatile unsigned int mylock; + volatile unsigned int mylock; } sockPoolHashTable_t; void addSockWithLock(sockPoolHashTable_t *sockhash, socknode_t *ptr); sockPoolHashTable_t *createSockPool(sockPoolHashTable_t *, unsigned int); int getSock(sockPoolHashTable_t *, unsigned int); int getSock2(sockPoolHashTable_t *, unsigned int); -int getSock2WithLock(sockPoolHashTable_t *h, unsigned int); +int getSock2WithLock(sockPoolHashTable_t *h, unsigned int); int getSockWithLock(sockPoolHashTable_t *, unsigned int); void freeSock(sockPoolHashTable_t *, unsigned int, int); void freeSockWithLock(sockPoolHashTable_t *, unsigned int, int); @@ -36,13 +36,13 @@ int createNewSocket(unsigned int); #if 0 /************************************************ - * Array Implementation data structures + * Array Implementation data structures ***********************************************/ #define MAX_CONN_PER_MACHINE 10 typedef struct sock_pool { - unsigned int mid; - int *sd; - char *inuse; + unsigned int mid; + int *sd; + char *inuse; } sock_pool_t; sock_pool_t *initSockPool(unsigned int *, int); diff --git a/Robust/src/Runtime/DSTM/interface/threadnotify.c b/Robust/src/Runtime/DSTM/interface/threadnotify.c index 9ff506e4..4df4dc43 100644 --- a/Robust/src/Runtime/DSTM/interface/threadnotify.c +++ b/Robust/src/Runtime/DSTM/interface/threadnotify.c @@ -41,13 +41,13 @@ void display(threadlist_t *head) { /* This function creates a new hash table that stores a mapping between the threadid and * a pointer to the thread notify data */ -unsigned int notifyhashCreate(unsigned int size, float loadfactor) { +unsigned int notifyhashCreate(unsigned int size, float loadfactor) { notifylistnode_t *nodes = calloc(size, sizeof(notifylistnode_t)); nlookup.table = nodes; nlookup.size = size; nlookup.numelements = 0; // Initial number of elements in the hash nlookup.loadfactor = loadfactor; - //Initialize the pthread_mutex variable + //Initialize the pthread_mutex variable pthread_mutex_init(&nlookup.locktable, NULL); return 0; } @@ -63,10 +63,10 @@ unsigned int notifyhashInsert(unsigned int tid, notifydata_t *ndata) { int index; notifylistnode_t *ptr, *node, *tmp; int isFound = 0; - + if (nlookup.numelements > (nlookup.loadfactor * nlookup.size)) { //Resize Table - newsize = 2 * nlookup.size + 1; + newsize = 2 * nlookup.size + 1; pthread_mutex_lock(&nlookup.locktable); notifyhashResize(newsize); pthread_mutex_unlock(&nlookup.locktable); @@ -100,14 +100,14 @@ unsigned int notifyhashInsert(unsigned int tid, notifydata_t *ndata) { } } pthread_mutex_unlock(&nlookup.locktable); - + return 0; } // Return pointer to thread notify data for a given threadid in the hash table notifydata_t *notifyhashSearch(unsigned int tid) { - // Address of the beginning of hash table - notifylistnode_t *ptr = nlookup.table; + // Address of the beginning of hash table + notifylistnode_t *ptr = nlookup.table; int index = notifyhashFunction(tid); pthread_mutex_lock(&nlookup.locktable); notifylistnode_t * node = &ptr[index]; @@ -125,31 +125,31 @@ notifydata_t *notifyhashSearch(unsigned int tid) { // Remove an entry from the hash table unsigned int notifyhashRemove(unsigned int tid) { notifylistnode_t *curr, *prev, *node; - + notifylistnode_t *ptr = nlookup.table; int index = notifyhashFunction(tid); - + pthread_mutex_lock(&nlookup.locktable); for (curr = &ptr[index]; curr != NULL; curr = curr->next) { 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 + 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; - } else if ((curr == &ptr[index]) && (curr->next != NULL)) { //Delete the first bin item with a linked list of notifylistnode_t connected + } 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); - } else { // Regular delete from linked listed + } else { // Regular delete from linked listed prev->next = curr->next; free(curr); } pthread_mutex_unlock(&nlookup.locktable); return 0; - } - prev = curr; + } + prev = curr; } pthread_mutex_unlock(&nlookup.locktable); return 1; @@ -157,30 +157,30 @@ unsigned int notifyhashRemove(unsigned int tid) { // Resize table unsigned int notifyhashResize(unsigned int newsize) { - notifylistnode_t *node, *ptr, *curr, *next; // curr and next keep track of the current and the next notifyhashlistnodes in a linked list + notifylistnode_t *node, *ptr, *curr, *next; // curr and next keep track of the current and the next notifyhashlistnodes in a linked list unsigned int oldsize; int isfirst; // Keeps track of the first element in the notifylistnode_t for each bin in hashtable - int i,index; - notifylistnode_t *newnode; + int i,index; + notifylistnode_t *newnode; ptr = nlookup.table; oldsize = nlookup.size; - + if((node = calloc(newsize, sizeof(notifylistnode_t))) == NULL) { printf("Calloc error %s %d\n", __FILE__, __LINE__); return 1; } - - nlookup.table = node; //Update the global hashtable upon resize() + + nlookup.table = node; //Update the global hashtable upon resize() nlookup.size = newsize; nlookup.numelements = 0; - - for(i = 0; i < oldsize; i++) { //Outer loop for each bin in hash table + + for(i = 0; i < oldsize; i++) { //Outer loop for each bin in hash table curr = &ptr[i]; - 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 + 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 } next = curr->next; index = notifyhashFunction(curr->threadid); @@ -188,33 +188,33 @@ unsigned int notifyhashResize(unsigned int newsize) { printf("DEBUG(resize) -> index = %d, threadid = %d\n", index, curr->threadid); #endif // Insert into the new table - if(nlookup.table[index].next == NULL && nlookup.table[index].threadid == 0) { + 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++; - }else { - if((newnode = calloc(1, sizeof(notifylistnode_t))) == NULL) { + } 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.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); - } - + } + isfirst = 0; curr = next; } } - - free(ptr); //Free the memory of the old hash table + + free(ptr); //Free the memory of the old hash table ptr = NULL; return 0; } diff --git a/Robust/src/Runtime/DSTM/interface/threadnotify.h b/Robust/src/Runtime/DSTM/interface/threadnotify.h index 7ed1c7a0..91f9c57d 100644 --- a/Robust/src/Runtime/DSTM/interface/threadnotify.h +++ b/Robust/src/Runtime/DSTM/interface/threadnotify.h @@ -10,40 +10,40 @@ //Structure to notify object of which other objects/threads are waiting on it typedef struct threadlist { - unsigned int threadid; - unsigned int mid; - struct threadlist *next; + unsigned int threadid; + unsigned int mid; + struct threadlist *next; } threadlist_t; //Structure for objects involved in wait-notify call typedef struct notifydata { - unsigned int numoid; /* Number of oids on which we are waiting for updated notification */ - unsigned int threadid; /* The threadid that is waiting for update notification response*/ - unsigned int *oidarry; /* Pointer to array of oids that this threadid is waiting on*/ - unsigned short *versionarry;/* Pointer to array of versions of the oids that we are waiting on */ - pthread_cond_t threadcond; /* Cond variable associated with each threadid that needs to be signaled*/ - pthread_mutex_t threadnotify; -}notifydata_t; + unsigned int numoid; /* Number of oids on which we are waiting for updated notification */ + unsigned int threadid; /* The threadid that is waiting for update notification response*/ + unsigned int *oidarry; /* Pointer to array of oids that this threadid is waiting on*/ + unsigned short *versionarry; /* Pointer to array of versions of the oids that we are waiting on */ + pthread_cond_t threadcond; /* Cond variable associated with each threadid that needs to be signaled*/ + pthread_mutex_t threadnotify; +} notifydata_t; typedef struct notifylistnode { - unsigned int threadid; - notifydata_t *ndata; - struct notifylistnode *next; + unsigned int threadid; + notifydata_t *ndata; + struct notifylistnode *next; } notifylistnode_t; typedef struct notifyhashtable { - notifylistnode_t *table; //Points to beginning of hash table - unsigned int size; - unsigned int numelements; - float loadfactor; - pthread_mutex_t locktable; //Lock for the hashtable + notifylistnode_t *table; //Points to beginning of hash table + unsigned int size; + unsigned int numelements; + float loadfactor; + pthread_mutex_t locktable; //Lock for the hashtable } notifyhashtable_t; -threadlist_t *insNode(threadlist_t *head, unsigned int threadid, unsigned int mid); //Inserts nodes for one object that - //needs to send notification to threads waiting on it -void display(threadlist_t *head);// Displays linked list of nodes for one object +threadlist_t *insNode(threadlist_t *head, unsigned int threadid, unsigned int mid); //Inserts nodes for one object that +//needs to send notification to threads waiting on it +void display(threadlist_t *head); // Displays linked list of nodes for one object unsigned int notifyhashCreate(unsigned int size, float loadfactor); //returns 1 if hashtable creation is not successful -unsigned int notifyhashFunction(unsigned int tid); //returns index in the hash table +unsigned int notifyhashFunction(unsigned int tid); //returns index in the hash table unsigned int notifyhashInsert(unsigned int tid, notifydata_t *ndata); //returns 1 if insert not successful notifydata_t *notifyhashSearch(unsigned int tid); //returns pointer to notify data, NULL if not found unsigned int notifyhashRemove(unsigned int tid); //returns 1 if not successful diff --git a/Robust/src/Runtime/DSTM/interface/trans.c b/Robust/src/Runtime/DSTM/interface/trans.c index 2334eca1..0fe01246 100644 --- a/Robust/src/Runtime/DSTM/interface/trans.c +++ b/Robust/src/Runtime/DSTM/interface/trans.c @@ -21,14 +21,14 @@ /* Global Variables */ extern int classsize[]; pfcstats_t *evalPrefetch; -extern int numprefetchsites; //Global variable containing number of prefetch sites -extern pthread_mutex_t mainobjstore_mutex;// Mutex to lock main Object store +extern int numprefetchsites; //Global variable containing number of prefetch sites +extern pthread_mutex_t mainobjstore_mutex; // Mutex to lock main Object store objstr_t *prefetchcache; //Global Prefetch cache -pthread_mutex_t prefetchcache_mutex;// Mutex to lock Prefetch Cache +pthread_mutex_t prefetchcache_mutex; // Mutex to lock Prefetch Cache pthread_mutexattr_t prefetchcache_mutex_attr; /* Attribute for lock to make it a recursive lock */ extern prehashtable_t pflookup; //Global Prefetch cache's lookup table pthread_t wthreads[NUM_THREADS]; //Worker threads for working on the prefetch queue -pthread_t tPrefetch; /* Primary Prefetch thread that processes the prefetch queue */ +pthread_t tPrefetch; /* Primary Prefetch thread that processes the prefetch queue */ extern objstr_t *mainobjstore; unsigned int myIpAddr; unsigned int *hostIpAddrs; @@ -59,12 +59,12 @@ void printhex(unsigned char *, int); plistnode_t *createPiles(transrecord_t *); /******************************* - * Send and Recv function calls - *******************************/ -void send_data(int fd , void *buf, int buflen) { - char *buffer = (char *)(buf); +* Send and Recv function calls +*******************************/ +void send_data(int fd, void *buf, int buflen) { + char *buffer = (char *)(buf); int size = buflen; - int numbytes; + int numbytes; while (size > 0) { numbytes = send(fd, buffer, size, MSG_NOSIGNAL); if (numbytes == -1) { @@ -76,10 +76,10 @@ void send_data(int fd , void *buf, int buflen) { } } -void recv_data(int fd , void *buf, int buflen) { - char *buffer = (char *)(buf); +void recv_data(int fd, void *buf, int buflen) { + char *buffer = (char *)(buf); int size = buflen; - int numbytes; + int numbytes; while (size > 0) { numbytes = recv(fd, buffer, size, 0); if (numbytes == -1) { @@ -91,10 +91,10 @@ void recv_data(int fd , void *buf, int buflen) { } } -int recv_data_errorcode(int fd , void *buf, int buflen) { - char *buffer = (char *)(buf); +int recv_data_errorcode(int fd, void *buf, int buflen) { + char *buffer = (char *)(buf); int size = buflen; - int numbytes; + int numbytes; while (size > 0) { numbytes = recv(fd, buffer, size, 0); if (numbytes==0) @@ -123,7 +123,7 @@ void printhex(unsigned char *ptr, int numBytes) { inline int arrayLength(int *array) { int i; - for(i=0 ;array[i] != -1; i++) + for(i=0 ; array[i] != -1; i++) ; return i; } @@ -147,8 +147,8 @@ void prefetch(int siteid, int ntuples, unsigned int *oids, unsigned short *endof int len; char * node= getmemory(qnodesize); int top=endoffsets[ntuples-1]; - - if (node==NULL) + + if (node==NULL) return; /* Set queue node values */ @@ -185,15 +185,15 @@ int dstmStartup(const char * option) { printf("Trans stats is on\n"); fflush(stdout); #endif - + //Initialize socket pool transReadSockPool = createSockPool(transReadSockPool, DEFAULTSOCKPOOLSIZE); transPrefetchSockPool = createSockPool(transPrefetchSockPool, DEFAULTSOCKPOOLSIZE); transRequestSockPool = createSockPool(transRequestSockPool, DEFAULTSOCKPOOLSIZE); - + dstmInit(); transInit(); - + fd=startlistening(); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); @@ -216,7 +216,7 @@ void *pCacheAlloc(objstr_t *store, unsigned int size) { objstr_t *ptr; ptr = store; int success = 0; - + while(ptr->next != NULL) { /* check if store is empty */ if(((unsigned int)ptr->top - (unsigned int)ptr - sizeof(objstr_t) + size) <= ptr->size) { @@ -225,10 +225,10 @@ void *pCacheAlloc(objstr_t *store, unsigned int size) { success = 1; return tmp; } else { - ptr = ptr-> next; + ptr = ptr->next; } } - + if(success == 0) { return NULL; } @@ -250,11 +250,11 @@ void transInit() { exit(0); } #endif - + /* Initialize attributes for mutex */ pthread_mutexattr_init(&prefetchcache_mutex_attr); pthread_mutexattr_settype(&prefetchcache_mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP); - + pthread_mutex_init(&prefetchcache_mutex, &prefetchcache_mutex_attr); pthread_mutex_init(¬ifymutex, NULL); pthread_mutex_init(&atomicObjLock, NULL); @@ -264,13 +264,13 @@ void transInit() { printf("ERROR\n"); return; //Failure } - + //Initialize primary shared queue queueInit(); //Initialize machine pile w/prefetch oids and offsets shared queue mcpileqInit(); - - //Create the primary prefetch thread + + //Create the primary prefetch thread int retval; do { retval=pthread_create(&tPrefetch, NULL, transPrefetch, NULL); @@ -287,7 +287,7 @@ void transExit() { for(t = 0; t < NUM_THREADS; t++) pthread_cancel(wthreads[t]); #endif - + return; } @@ -296,7 +296,7 @@ void transExit() { void randomdelay() { struct timespec req; time_t t; - + t = time(NULL); req.tv_sec = 0; req.tv_nsec = (long)(1000000 + (t%10000000)); //1-11 msec @@ -327,11 +327,11 @@ objheader_t *transRead(transrecord_t *record, unsigned int oid) { objheader_t *objcopy; int size; void *buf; - + if(oid == 0) { return NULL; } - + if((objheader = chashSearch(record->lookupTable, oid)) != NULL){ #ifdef TRANSSTATS nchashSearch++; @@ -353,7 +353,7 @@ objheader_t *transRead(transrecord_t *record, unsigned int oid) { memcpy(objcopy, objheader, size); /* Insert into cache's lookup table */ STATUS(objcopy)=0; - chashInsert(record->lookupTable, OID(objheader), objcopy); + chashInsert(record->lookupTable, OID(objheader), objcopy); #ifdef COMPILER return &objcopy[1]; #else @@ -361,7 +361,7 @@ objheader_t *transRead(transrecord_t *record, unsigned int oid) { #endif } else { #ifdef CACHE - if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { + if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) { #ifdef TRANSSTATS nprehashSearch++; #endif @@ -371,7 +371,7 @@ objheader_t *transRead(transrecord_t *record, unsigned int oid) { objcopy = (objheader_t *) objstrAlloc(record->cache, size); memcpy(objcopy, tmp, size); /* Insert into cache's lookup table */ - chashInsert(record->lookupTable, OID(tmp), objcopy); + chashInsert(record->lookupTable, OID(tmp), objcopy); #ifdef COMPILER return &objcopy[1]; #else @@ -393,7 +393,7 @@ objheader_t *transRead(transrecord_t *record, unsigned int oid) { #ifdef TRANSSTATS nRemoteSend++; #endif - STATUS(objcopy)=0; + STATUS(objcopy)=0; #ifdef COMPILER return &objcopy[1]; #else @@ -411,7 +411,7 @@ objheader_t *transCreateObj(transrecord_t *record, unsigned int size) { tmp->rcount = 1; STATUS(tmp) = NEW; chashInsert(record->lookupTable, OID(tmp), tmp); - + #ifdef COMPILER return &tmp[1]; //want space after object header #else @@ -429,7 +429,7 @@ plistnode_t *createPiles(transrecord_t *record) { chashlistnode_t * ptr = record->lookupTable->table; /* Represents number of bins in the chash table */ unsigned int size = record->lookupTable->size; - + for(i = 0; i < size ; i++) { chashlistnode_t * curr = &ptr[i]; /* Inner loop to traverse the linked list of the cache lookupTable */ @@ -437,12 +437,12 @@ plistnode_t *createPiles(transrecord_t *record) { //if the first bin in hash table is empty if(curr->key == 0) break; - + if ((headeraddr = (objheader_t *) chashSearch(record->lookupTable, curr->key)) == NULL) { printf("Error: No such oid %s, %d\n", __FILE__, __LINE__); return NULL; } - + //Get machine location for object id (and whether local or not) if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) { machinenum = myIpAddr; @@ -450,21 +450,21 @@ plistnode_t *createPiles(transrecord_t *record) { printf("Error: No such machine %s, %d\n", __FILE__, __LINE__); return NULL; } - + //Make machine groups pile = pInsert(pile, headeraddr, machinenum, record->lookupTable->numelements); curr = curr->next; } } - return pile; + return pile; } /* This function initiates the transaction commit process - * Spawns threads for each of the new connections with Participants - * and creates new piles by calling the createPiles(), - * Sends a transrequest() to each remote machines for objects found remotely + * Spawns threads for each of the new connections with Participants + * and creates new piles by calling the createPiles(), + * Sends a transrequest() to each remote machines for objects found remotely * and calls handleLocalReq() to process objects found locally */ -int transCommit(transrecord_t *record) { +int transCommit(transrecord_t *record) { unsigned int tot_bytes_mod, *listmid; plistnode_t *pile, *pile_ptr; int i, j, rc, val; @@ -479,15 +479,15 @@ int transCommit(transrecord_t *record) { local_thread_data_array_t *ltdata; int firsttime=1; - do { + do { treplyctrl=0; - trecvcount = 0; - threadnum = 0; + trecvcount = 0; + threadnum = 0; treplyretry = 0; thread_data_array = NULL; ltdata = NULL; - - /* Look through all the objects in the transaction record and make piles + + /* Look through all the objects in the transaction record and make piles * for each machine involved in the transaction*/ if (firsttime) pile_ptr = pile = createPiles(record); @@ -496,28 +496,28 @@ int transCommit(transrecord_t *record) { firsttime=0; /* Create the packet to be sent in TRANS_REQUEST */ - + /* Count the number of participants */ pilecount = pCount(pile); - + /* Create a list of machine ids(Participants) involved in transaction */ listmid = calloc(pilecount, sizeof(unsigned int)); pListMid(pile, listmid); - - + + /* Initialize thread variables, * Spawn a thread for each Participant involved in a transaction */ pthread_t thread[pilecount]; - pthread_attr_t attr; + pthread_attr_t attr; pthread_cond_t tcond; pthread_mutex_t tlock; pthread_mutex_t tlshrd; - + thread_data_array = (thread_data_array_t *) calloc(pilecount, sizeof(thread_data_array_t)); ltdata = calloc(1, sizeof(local_thread_data_array_t)); - - thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */ - + + thread_response_t rcvd_control_msg[pilecount]; /* Shared thread array that keeps track of responses of participants */ + /* Initialize and set thread detach attribute */ pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); @@ -553,7 +553,7 @@ int transCommit(transrecord_t *record) { /* If local do not create any extra connection */ if(pile->mid != myIpAddr) { /* Not local */ do { - rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]); + rc = pthread_create(&thread[threadnum], &attr, transRequest, (void *) &thread_data_array[threadnum]); } while(rc!=0); if(rc) { perror("Error in pthread create\n"); @@ -586,48 +586,47 @@ int transCommit(transrecord_t *record) { return 1; } } - - threadnum++; + + threadnum++; pile = pile->next; } /* Free attribute and wait for the other threads */ pthread_attr_destroy(&attr); - + for (i = 0; i < threadnum; i++) { rc = pthread_join(thread[i], NULL); - if(rc) - { - printf("Error: return code from pthread_join() is %d\n", rc); - pthread_cond_destroy(&tcond); - pthread_mutex_destroy(&tlock); - pDelete(pile_ptr); - free(listmid); - for (j = i; j < threadnum; j++) { - free(thread_data_array[j].buffer); - } - return 1; + if(rc){ + printf("Error: return code from pthread_join() is %d\n", rc); + pthread_cond_destroy(&tcond); + pthread_mutex_destroy(&tlock); + pDelete(pile_ptr); + free(listmid); + for (j = i; j < threadnum; j++) { + free(thread_data_array[j].buffer); } + return 1; + } free(thread_data_array[i].buffer); } - /* Free resources */ + /* Free resources */ pthread_cond_destroy(&tcond); pthread_mutex_destroy(&tlock); free(listmid); if (!treplyretry) pDelete(pile_ptr); - + /* wait a random amount of time before retrying to commit transaction*/ if(treplyretry) { free(thread_data_array); free(ltdata); randomdelay(); } - + /* Retry trans commit procedure during soft_abort case */ } while (treplyretry); - + if(treplyctrl == TRANS_ABORT) { #ifdef TRANSSTATS numTransAbort++; @@ -658,9 +657,9 @@ int transCommit(transrecord_t *record) { return 0; } -/* This function sends information involved in the transaction request +/* This function sends information involved in the transaction request * to participants and accepts a response from particpants. - * It calls decideresponse() to decide on what control message + * It calls decideresponse() to decide on what control message * to send next to participants and sends the message using sendResponse()*/ void *transRequest(void *threadarg) { int sd, i, n; @@ -685,13 +684,13 @@ void *transRequest(void *threadarg) { int size=sizeof(unsigned int)*tdata->buffer->f.mcount; send_data(sd, tdata->buffer->listmid, size); } - + /* Send oids and version number tuples for objects that are read */ { int size=(sizeof(unsigned int)+sizeof(unsigned short))*tdata->buffer->f.numread; send_data(sd, tdata->buffer->objread, size); } - + /* Send objects that are modified */ for(i = 0; i < tdata->buffer->f.nummod ; i++) { int size; @@ -703,7 +702,7 @@ void *transRequest(void *threadarg) { size+=sizeof(objheader_t); send_data(sd, headeraddr, size); } - + /* Read control message from Participant */ recv_data(sd, &control, sizeof(char)); /* Recv Objects if participant sends TRANS_DISAGREE */ @@ -723,7 +722,7 @@ void *transRequest(void *threadarg) { while(length != 0) { unsigned int oidToPrefetch; objheader_t * header; - header = (objheader_t *) (((char *)newAddr) + offset); + header = (objheader_t *)(((char *)newAddr) + offset); oidToPrefetch = OID(header); int size = 0; GETSIZE(size, header); @@ -731,10 +730,10 @@ void *transRequest(void *threadarg) { //make an entry in prefetch hash table void *oldptr; if((oldptr = prehashSearch(oidToPrefetch)) != NULL) { - prehashRemove(oidToPrefetch); - prehashInsert(oidToPrefetch, header); + prehashRemove(oidToPrefetch); + prehashInsert(oidToPrefetch, header); } else { - prehashInsert(oidToPrefetch, header); + prehashInsert(oidToPrefetch, header); } length = length - size; offset += size; @@ -745,16 +744,16 @@ void *transRequest(void *threadarg) { recvcontrol = control; /* Update common data structure and increment count */ tdata->recvmsg[tdata->thread_id].rcv_status = recvcontrol; - + /* Lock and update count */ /* Thread sleeps until all messages from pariticipants are received by coordinator */ pthread_mutex_lock(tdata->lock); - + (*(tdata->count))++; /* keeps track of no of messages received by the coordinator */ - + /* Wake up the threads and invoke decideResponse (once) */ if(*(tdata->count) == tdata->buffer->f.mcount) { - decideResponse(tdata); + decideResponse(tdata); pthread_cond_broadcast(tdata->threshold); } else { pthread_cond_wait(tdata->threshold, tdata->lock); @@ -763,16 +762,16 @@ void *transRequest(void *threadarg) { /* clear objects from prefetch cache */ /* - if(*(tdata->replyctrl) == TRANS_ABORT) { - int i; - for(i=0; ibuffer->f.nummod; i++) { + if(*(tdata->replyctrl) == TRANS_ABORT) { + int i; + for(i=0; ibuffer->f.nummod; i++) { unsigned int oid = tdata->buffer->oidmod[i]; objheader_t *header; if((header = prehashSearch(oid)) != NULL) { prehashRemove(oid); } - } - for(i=0; ibuffer->f.numread; i++) { + } + for(i=0; ibuffer->f.numread; i++) { char *objread = tdata->buffer->objread; unsigned int oid = *((unsigned int *)(objread+(sizeof(unsigned int) + sizeof(unsigned short))*i)); @@ -780,14 +779,14 @@ void *transRequest(void *threadarg) { if((header = prehashSearch(oid)) != NULL) { prehashRemove(oid); } - } - } - */ + } + } + */ #ifdef CACHE if(*(tdata->replyctrl) == TRANS_COMMIT) { int retval; - /* Update prefetch cache */ + /* Update prefetch cache */ if((retval = updatePrefetchCache(tdata)) != 0) { printf("Error: %s() in updating prefetch cache %s, %d\n", __func__, __FILE__, __LINE__); return; @@ -796,22 +795,22 @@ void *transRequest(void *threadarg) { /* Invalidate objects in other machine cache */ if(tdata->buffer->f.nummod > 0) { if((retval = invalidateObj(tdata)) != 0) { - printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__); - return; + printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__); + return; } } } #endif - - /* Send the final response such as TRANS_COMMIT or TRANS_ABORT + + /* Send the final response such as TRANS_COMMIT or TRANS_ABORT * to all participants in their respective socket */ - if (sendResponse(tdata, sd) == 0) { + if (sendResponse(tdata, sd) == 0) { printf("sendResponse returned error %s,%d\n", __FILE__, __LINE__); pthread_exit(NULL); } - - recv_data((int)sd, &control, sizeof(char)); - + + recv_data((int)sd, &control, sizeof(char)); + if(control == TRANS_UNSUCESSFUL) { //printf("DEBUG-> TRANS_ABORTED\n"); } else if(control == TRANS_SUCESSFUL) { @@ -822,34 +821,35 @@ void *transRequest(void *threadarg) { pthread_exit(NULL); } -/* This function decides the reponse that needs to be sent to +/* This function decides the reponse that needs to be sent to * all Participant machines after the TRANS_REQUEST protocol */ void decideResponse(thread_data_array_t *tdata) { char control; int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what message to send */ - + for (i = 0 ; i < tdata->buffer->f.mcount; i++) { control = tdata->recvmsg[i].rcv_status; /* tdata: keeps track of all participant responses written onto the shared array */ switch(control) { default: printf("Participant sent unknown message in %s, %d\n", __FILE__, __LINE__); + /* treat as disagree, pass thru */ case TRANS_DISAGREE: transdisagree++; break; - + case TRANS_AGREE: transagree++; break; - + case TRANS_SOFT_ABORT: transsoftabort++; break; } } - + if(transdisagree > 0) { /* Send Abort */ *(tdata->replyctrl) = TRANS_ABORT; @@ -870,7 +870,7 @@ void decideResponse(thread_data_array_t *tdata) { evalPrefetch[i].operMode = 1; #endif #endif - } else { + } else { /* Send Abort in soft abort case followed by retry commiting transaction again*/ *(tdata->replyctrl) = TRANS_ABORT; *(tdata->replyretry) = 1; @@ -887,29 +887,29 @@ char sendResponse(thread_data_array_t *tdata, int sd) { int n, size, sum, oidcount = 0, control; char *ptr, retval = 0; unsigned int *oidnotfound; - + control = *(tdata->replyctrl); send_data(sd, &control, sizeof(char)); - + //TODO read missing objects during object migration /* If response is a soft abort due to missing objects at the Participant's side */ - + /* If the decided response is TRANS_ABORT */ if(*(tdata->replyctrl) == TRANS_ABORT) { retval = TRANS_ABORT; - } else if(*(tdata->replyctrl) == TRANS_COMMIT) { - /* If the decided response is TRANS_COMMIT */ + } else if(*(tdata->replyctrl) == TRANS_COMMIT) { + /* If the decided response is TRANS_COMMIT */ retval = TRANS_COMMIT; } - + return retval; } /* This function opens a connection, places an object read request to * the remote machine, reads the control message and object if * available and copies the object and its header to the local - * cache. */ + * cache. */ void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) { int size, val; @@ -918,16 +918,16 @@ void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) { char control; objheader_t *h; void *objcopy = NULL; - + int sd = getSock2(transReadSockPool, mnum); char readrequest[sizeof(char)+sizeof(unsigned int)]; readrequest[0] = READ_REQUEST; *((unsigned int *)(&readrequest[1])) = oid; send_data(sd, readrequest, sizeof(readrequest)); - + /* Read response from the Participant */ recv_data(sd, &control, sizeof(char)); - + if (control==OBJECT_NOT_FOUND) { objcopy = NULL; } else { @@ -936,9 +936,9 @@ void *getRemoteObj(transrecord_t *record, unsigned int mnum, unsigned int oid) { objcopy = objstrAlloc(record->cache, size); recv_data(sd, objcopy, size); /* Insert into cache's lookup table */ - chashInsert(record->lookupTable, oid, objcopy); + chashInsert(record->lookupTable, oid, objcopy); } - + return objcopy; } @@ -962,16 +962,16 @@ void *handleLocalReq(void *threadarg) { objheader_t *headptr; localtdata = (local_thread_data_array_t *) threadarg; - + /* Counters and arrays to formulate decision on control message to be sent */ oidnotfound = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int)); oidlocked = (unsigned int *) calloc((localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod), sizeof(unsigned int)); - + numread = localtdata->tdata->buffer->f.numread; /* Process each oid in the machine pile/ group per thread */ for (i = 0; i < localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod; i++) { if (i < localtdata->tdata->buffer->f.numread) { - int incr = sizeof(unsigned int) + sizeof(unsigned short);// Offset that points to next position in the objread array + int incr = sizeof(unsigned int) + sizeof(unsigned short); // Offset that points to next position in the objread array incr *= i; oid = *((unsigned int *)(((char *)localtdata->tdata->buffer->objread) + incr)); version = *((unsigned short *)(((char *)localtdata->tdata->buffer->objread) + incr + sizeof(unsigned int))); @@ -979,14 +979,14 @@ void *handleLocalReq(void *threadarg) { int tmpsize; headptr = (objheader_t *) chashSearch(localtdata->tdata->rec->lookupTable, localtdata->tdata->buffer->oidmod[i-numread]); if (headptr == NULL) { - printf("Error: handleLocalReq() returning NULL, no such oid %s, %d\n", __FILE__, __LINE__); - return NULL; + printf("Error: handleLocalReq() returning NULL, no such oid %s, %d\n", __FILE__, __LINE__); + return NULL; } oid = OID(headptr); version = headptr->version; } /* Check if object is still present in the machine since the beginning of TRANS_REQUEST */ - + /* Save the oids not found and number of oids not found for later use */ if ((mobj = mhashSearch(oid)) == NULL) { /* Obj not found */ /* Save the oids not found and number of oids not found for later use */ @@ -995,31 +995,31 @@ void *handleLocalReq(void *threadarg) { } else { /* If Obj found in machine (i.e. has not moved) */ /* Check if Obj is locked by any previous transaction */ if (test_and_set(STATUSPTR(mobj))) { - if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */ - v_matchlock++; - } else {/* If versions don't match ...HARD ABORT */ - v_nomatch++; - /* Send TRANS_DISAGREE to Coordinator */ - localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE; - break; - } + if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */ + v_matchlock++; + } else { /* If versions don't match ...HARD ABORT */ + v_nomatch++; + /* Send TRANS_DISAGREE to Coordinator */ + localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE; + break; + } } else { //we're locked - /* Save all object oids that are locked on this machine during this transaction request call */ - oidlocked[numoidlocked] = OID(((objheader_t *)mobj)); - numoidlocked++; - if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */ - v_matchnolock++; - } else { /* If versions don't match ...HARD ABORT */ - v_nomatch++; - /* Send TRANS_DISAGREE to Coordinator */ - localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE; - break; - } + /* Save all object oids that are locked on this machine during this transaction request call */ + oidlocked[numoidlocked] = OID(((objheader_t *)mobj)); + numoidlocked++; + if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */ + v_matchnolock++; + } else { /* If versions don't match ...HARD ABORT */ + v_nomatch++; + /* Send TRANS_DISAGREE to Coordinator */ + localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_DISAGREE; + break; + } } } } // End for - /* Condition to send TRANS_AGREE */ + /* Condition to send TRANS_AGREE */ if(v_matchnolock == localtdata->tdata->buffer->f.numread + localtdata->tdata->buffer->f.nummod) { localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_AGREE; } @@ -1027,7 +1027,7 @@ void *handleLocalReq(void *threadarg) { if((v_matchlock > 0 && v_nomatch == 0) || (numoidnotfound > 0 && v_nomatch == 0)) { localtdata->tdata->recvmsg[localtdata->tdata->thread_id].rcv_status = TRANS_SOFT_ABORT; } - + /* Fill out the trans_commit_data_t data structure. This is required for a trans commit process * if Participant receives a TRANS_COMMIT */ localtdata->transinfo->objlocked = oidlocked; @@ -1039,10 +1039,10 @@ void *handleLocalReq(void *threadarg) { //Thread sleeps until all messages from pariticipants are received by coordinator pthread_mutex_lock(localtdata->tdata->lock); (*(localtdata->tdata->count))++; /* keeps track of no of messages received by the coordinator */ - + /* Wake up the threads and invoke decideResponse (once) */ if(*(localtdata->tdata->count) == localtdata->tdata->buffer->f.mcount) { - decideResponse(localtdata->tdata); + decideResponse(localtdata->tdata); pthread_cond_broadcast(localtdata->tdata->threshold); } else { pthread_cond_wait(localtdata->tdata->threshold, localtdata->tdata->lock); @@ -1060,8 +1060,8 @@ void *handleLocalReq(void *threadarg) { if(localtdata->tdata->buffer->f.nummod > 0) { int retval; if((retval = invalidateObj(localtdata->tdata)) != 0) { - printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__); - return; + printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__); + return; } } #endif @@ -1086,10 +1086,10 @@ int transAbortProcess(local_thread_data_array_t *localtdata) { int i, numlocked; unsigned int *objlocked; void *header; - + numlocked = localtdata->transinfo->numlocked; objlocked = localtdata->transinfo->objlocked; - + for (i = 0; i < numlocked; i++) { if((header = mhashSearch(objlocked[i])) == NULL) { printf("mhashsearch returns NULL at %s, %d\n", __FILE__, __LINE__); @@ -1107,7 +1107,7 @@ int transComProcess(local_thread_data_array_t *localtdata) { int i, nummod, tmpsize, numcreated, numlocked; unsigned int *oidmod, *oidcreated, *oidlocked; void *ptrcreate; - + nummod = localtdata->tdata->buffer->f.nummod; oidmod = localtdata->tdata->buffer->oidmod; numcreated = localtdata->tdata->buffer->f.numcreated; @@ -1160,7 +1160,7 @@ int transComProcess(local_thread_data_array_t *localtdata) { } UnLock(STATUSPTR(header)); } - + return 0; } @@ -1168,14 +1168,14 @@ prefetchpile_t *foundLocal(char *ptr) { int siteid = *(GET_SITEID(ptr)); int ntuples = *(GET_NTUPLES(ptr)); unsigned int * oidarray = GET_PTR_OID(ptr); - unsigned short * endoffsets = GET_PTR_EOFF(ptr, ntuples); + unsigned short * endoffsets = GET_PTR_EOFF(ptr, ntuples); short * arryfields = GET_PTR_ARRYFLD(ptr, ntuples); prefetchpile_t * head=NULL; int numLocal = 0; - + int i; - for(i=0;imid); - + /* Send Prefetch Request */ prefetchpile_t *ptr = pilehead; while(ptr != NULL) { sendPrefetchReq(ptr, sd); - ptr = ptr->next; + ptr = ptr->next; } - + /* Release socket */ // freeSock(transPrefetchSockPool, pilehead->mid, sd); - + /* Deallocated pilehead */ mcdealloc(pilehead); } @@ -1284,24 +1284,24 @@ void *transPrefetch(void *t) { void sendPrefetchReqnew(prefetchpile_t *mcpilenode, int sd) { objpile_t *tmp; - + int size=sizeof(char)+sizeof(int); - for(tmp=mcpilenode->objpiles;tmp!=NULL;tmp=tmp->next) { + for(tmp=mcpilenode->objpiles; tmp!=NULL; tmp=tmp->next) { size += sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short)); } - + char buft[size]; char *buf=buft; *buf=TRANS_PREFETCH; buf+=sizeof(char); - - for(tmp=mcpilenode->objpiles;tmp!=NULL;tmp=tmp->next) { + + for(tmp=mcpilenode->objpiles; tmp!=NULL; tmp=tmp->next) { int len = sizeof(int) + sizeof(unsigned int) + sizeof(unsigned int) + ((tmp->numoffset) * sizeof(short)); *((int*)buf)=len; buf+=sizeof(int); *((unsigned int *)buf)=tmp->oid; buf+=sizeof(unsigned int); - *((unsigned int *)(buf)) = myIpAddr; + *((unsigned int *)(buf)) = myIpAddr; buf+=sizeof(unsigned int); memcpy(buf, tmp->offset, tmp->numoffset*sizeof(short)); buf+=tmp->numoffset*sizeof(short); @@ -1315,11 +1315,11 @@ void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd) { int len, endpair; char control; objpile_t *tmp; - + /* Send TRANS_PREFETCH control message */ control = TRANS_PREFETCH; send_data(sd, &control, sizeof(char)); - + /* Send Oids and offsets in pairs */ tmp = mcpilenode->objpiles; while(tmp != NULL) { @@ -1330,17 +1330,17 @@ void sendPrefetchReq(prefetchpile_t *mcpilenode, int sd) { buf+=sizeof(int); *((unsigned int *)buf) = tmp->oid; buf+=sizeof(unsigned int); - *((unsigned int *)buf) = myIpAddr; + *((unsigned int *)buf) = myIpAddr; buf += sizeof(unsigned int); memcpy(buf, tmp->offset, (tmp->numoffset)*sizeof(short)); send_data(sd, oidnoffset, len); tmp = tmp->next; } - + /* Send a special char -1 to represent the end of sending oids + offset pair to remote machine */ endpair = -1; send_data(sd, &endpair, sizeof(int)); - + return; } @@ -1349,8 +1349,8 @@ int getPrefetchResponse(int sd) { char control; unsigned int oid; void *modptr, *oldptr; - - recv_data((int)sd, &length, sizeof(int)); + + recv_data((int)sd, &length, sizeof(int)); size = length - sizeof(int); char recvbuffer[size]; @@ -1377,12 +1377,12 @@ int getPrefetchResponse(int sd) { prehashRemove(oid); prehashInsert(oid, modptr); } - } else {/* Else add the object ptr to hash table*/ + } else { /* Else add the object ptr to hash table*/ prehashInsert(oid, modptr); } /* Lock the Prefetch Cache look up table*/ pthread_mutex_lock(&pflookup.lock); - /* Broadcast signal on prefetch cache condition variable */ + /* Broadcast signal on prefetch cache condition variable */ pthread_cond_broadcast(&pflookup.cond); /* Unlock the Prefetch Cache look up table*/ pthread_mutex_unlock(&pflookup.lock); @@ -1395,7 +1395,7 @@ int getPrefetchResponse(int sd) { } else { printf("Error: in decoding the control value %d, %s, %d\n",control, __FILE__, __LINE__); } - + return 0; } @@ -1408,206 +1408,190 @@ unsigned short getObjType(unsigned int oid) { #ifdef CACHE if ((objheader = (objheader_t *) prehashSearch(oid)) == NULL) { #endif - unsigned int mid = lhashSearch(oid); - int sd = getSock2(transReadSockPool, mid); - char remotereadrequest[sizeof(char)+sizeof(unsigned int)]; - remotereadrequest[0] = READ_REQUEST; - *((unsigned int *)(&remotereadrequest[1])) = oid; - send_data(sd, remotereadrequest, sizeof(remotereadrequest)); - - /* Read response from the Participant */ - char control; - recv_data(sd, &control, sizeof(char)); - - if (control==OBJECT_NOT_FOUND) { - printf("Error: in %s() THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n", __func__); - fflush(stdout); - exit(-1); - } else { - /* Read object if found into local cache */ - int size; - recv_data(sd, &size, sizeof(int)); + unsigned int mid = lhashSearch(oid); + int sd = getSock2(transReadSockPool, mid); + char remotereadrequest[sizeof(char)+sizeof(unsigned int)]; + remotereadrequest[0] = READ_REQUEST; + *((unsigned int *)(&remotereadrequest[1])) = oid; + send_data(sd, remotereadrequest, sizeof(remotereadrequest)); + + /* Read response from the Participant */ + char control; + recv_data(sd, &control, sizeof(char)); + + if (control==OBJECT_NOT_FOUND) { + printf("Error: in %s() THIS SHOULD NOT HAPPEN.....EXIT PROGRAM\n", __func__); + fflush(stdout); + exit(-1); + } else { + /* Read object if found into local cache */ + int size; + recv_data(sd, &size, sizeof(int)); #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); - } - pthread_mutex_unlock(&prefetchcache_mutex); - recv_data(sd, objheader, size); - prehashInsert(oid, objheader); - return TYPE(objheader); + 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); + } + pthread_mutex_unlock(&prefetchcache_mutex); + recv_data(sd, objheader, size); + prehashInsert(oid, objheader); + return TYPE(objheader); #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; - } - recv_data(sd, buffer, size); - objheader = (objheader_t *)buffer; - unsigned short type = TYPE(objheader); - free(buffer); - return type; -#endif + char *buffer; + if((buffer = calloc(1, size)) == NULL) { + printf("%s() Calloc Error %s at line %d\n", __func__, __FILE__, __LINE__); + fflush(stdout); + return 0; } -#ifdef CACHE + recv_data(sd, buffer, size); + objheader = (objheader_t *)buffer; + unsigned short type = TYPE(objheader); + free(buffer); + return type; +#endif } +#ifdef CACHE + } #endif } return TYPE(objheader); } -int startRemoteThread(unsigned int oid, unsigned int mid) -{ - int sock; - struct sockaddr_in remoteAddr; - char msg[1 + sizeof(unsigned int)]; - int bytesSent; - int status; - - if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) - { - perror("startRemoteThread():socket()"); - return -1; - } +int startRemoteThread(unsigned int oid, unsigned int mid) { + int sock; + struct sockaddr_in remoteAddr; + char msg[1 + sizeof(unsigned int)]; + int bytesSent; + int status; - bzero(&remoteAddr, sizeof(remoteAddr)); - remoteAddr.sin_family = AF_INET; - remoteAddr.sin_port = htons(LISTEN_PORT); - remoteAddr.sin_addr.s_addr = htonl(mid); - - if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) - { - printf("startRemoteThread():error %d connecting to %s:%d\n", errno, - inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT); - status = -1; - } - else - { - msg[0] = START_REMOTE_THREAD; - *((unsigned int *) &msg[1]) = oid; - send_data(sock, msg, 1 + sizeof(unsigned int)); - } + if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){ + perror("startRemoteThread():socket()"); + return -1; + } + + bzero(&remoteAddr, sizeof(remoteAddr)); + remoteAddr.sin_family = AF_INET; + remoteAddr.sin_port = htons(LISTEN_PORT); + remoteAddr.sin_addr.s_addr = htonl(mid); + + if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){ + printf("startRemoteThread():error %d connecting to %s:%d\n", errno, + inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT); + status = -1; + } else + { + msg[0] = START_REMOTE_THREAD; + *((unsigned int *) &msg[1]) = oid; + send_data(sock, msg, 1 + sizeof(unsigned int)); + } - close(sock); - return status; + close(sock); + return status; } //TODO: when reusing oids, make sure they are not already in use! static unsigned int id = 0xFFFFFFFF; unsigned int getNewOID(void) { - id += 2; - if (id > oidMax || id < oidMin) - { - id = (oidMin | 1); - } - return id; + id += 2; + if (id > oidMax || id < oidMin){ + id = (oidMin | 1); + } + return id; } -int processConfigFile() -{ - FILE *configFile; - const int maxLineLength = 200; - char lineBuffer[maxLineLength]; - char *token; - const char *delimiters = " \t\n"; - char *commentBegin; - in_addr_t tmpAddr; - - configFile = fopen(CONFIG_FILENAME, "r"); - if (configFile == NULL) - { - printf("error opening %s:\n", CONFIG_FILENAME); - perror(""); - return -1; - } - - numHostsInSystem = 0; - sizeOfHostArray = 8; - hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int)); - - while(fgets(lineBuffer, maxLineLength, configFile) != NULL) - { - commentBegin = strchr(lineBuffer, '#'); - if (commentBegin != NULL) - *commentBegin = '\0'; - token = strtok(lineBuffer, delimiters); - 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; - } - else - addHost(htonl(tmpAddr)); - token = strtok(NULL, delimiters); - } - } +int processConfigFile() { + FILE *configFile; + const int maxLineLength = 200; + char lineBuffer[maxLineLength]; + char *token; + const char *delimiters = " \t\n"; + char *commentBegin; + in_addr_t tmpAddr; + + configFile = fopen(CONFIG_FILENAME, "r"); + if (configFile == NULL){ + printf("error opening %s:\n", CONFIG_FILENAME); + perror(""); + return -1; + } + numHostsInSystem = 0; + sizeOfHostArray = 8; + hostIpAddrs = calloc(sizeOfHostArray, sizeof(unsigned int)); + + while(fgets(lineBuffer, maxLineLength, configFile) != NULL){ + commentBegin = strchr(lineBuffer, '#'); + if (commentBegin != NULL) + *commentBegin = '\0'; + token = strtok(lineBuffer, delimiters); + while (token != NULL){ + tmpAddr = inet_addr(token); + if ((int)tmpAddr == -1){ + printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token); fclose(configFile); - - if (numHostsInSystem < 1) - { - printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME); - return -1; - } + return -1; + } else + addHost(htonl(tmpAddr)); + token = strtok(NULL, delimiters); + } + } + + fclose(configFile); + + if (numHostsInSystem < 1){ + printf("error in %s: no IP Adresses found\n", CONFIG_FILENAME); + return -1; + } #ifdef MAC - myIpAddr = getMyIpAddr("en1"); + myIpAddr = getMyIpAddr("en1"); #else - myIpAddr = getMyIpAddr("eth0"); + myIpAddr = getMyIpAddr("eth0"); #endif - myIndexInHostArray = findHost(myIpAddr); - if (myIndexInHostArray == -1) - { - printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME); - return -1; - } - oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1; - oidMin = oidsPerBlock * myIndexInHostArray; - if (myIndexInHostArray == numHostsInSystem - 1) - oidMax = 0xFFFFFFFF; - else - oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1; + myIndexInHostArray = findHost(myIpAddr); + if (myIndexInHostArray == -1){ + printf("error in %s: IP Address of eth0 not found\n", CONFIG_FILENAME); + return -1; + } + oidsPerBlock = (0xFFFFFFFF / numHostsInSystem) + 1; + oidMin = oidsPerBlock * myIndexInHostArray; + if (myIndexInHostArray == numHostsInSystem - 1) + oidMax = 0xFFFFFFFF; + else + oidMax = oidsPerBlock * (myIndexInHostArray + 1) - 1; - return 0; + return 0; } -void addHost(unsigned int hostIp) -{ - unsigned int *tmpArray; +void addHost(unsigned int hostIp) { + unsigned int *tmpArray; - if (findHost(hostIp) != -1) - return; + if (findHost(hostIp) != -1) + return; - if (numHostsInSystem == sizeOfHostArray) - { - tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int)); - memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem); - free(hostIpAddrs); - hostIpAddrs = tmpArray; - } + if (numHostsInSystem == sizeOfHostArray){ + tmpArray = calloc(sizeOfHostArray * 2, sizeof(unsigned int)); + memcpy(tmpArray, hostIpAddrs, sizeof(unsigned int) * numHostsInSystem); + free(hostIpAddrs); + hostIpAddrs = tmpArray; + } - hostIpAddrs[numHostsInSystem++] = hostIp; + hostIpAddrs[numHostsInSystem++] = hostIp; - return; + return; } -int findHost(unsigned int hostIp) -{ - int i; - for (i = 0; i < numHostsInSystem; i++) - if (hostIpAddrs[i] == hostIp) - return i; +int findHost(unsigned int hostIp) { + int i; + for (i = 0; i < numHostsInSystem; i++) + if (hostIpAddrs[i] == hostIp) + return i; - //not found - return -1; + //not found + return -1; } -/* This function sends notification request per thread waiting on object(s) whose version +/* This function sends notification request per thread waiting on object(s) whose version * changes */ int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int numoid) { int sock,i; @@ -1623,26 +1607,26 @@ int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int n pthread_mutex_t threadnotify = PTHREAD_MUTEX_INITIALIZER; //Lock and condition var for threadjoin and notification pthread_cond_t threadcond = PTHREAD_COND_INITIALIZER; notifydata_t *ndata; - + oid = oidarry[0]; if((mid = lhashSearch(oid)) == 0) { printf("Error: %s() No such machine found for oid =%x\n",__func__, oid); return; } - + if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){ perror("reqNotify():socket()"); return -1; } - + bzero(&remoteAddr, sizeof(remoteAddr)); remoteAddr.sin_family = AF_INET; remoteAddr.sin_port = htons(LISTEN_PORT); remoteAddr.sin_addr.s_addr = htonl(mid); - + /* Generate unique threadid */ threadid++; - + /* Save threadid, numoid, oidarray, versionarray, pthread_cond_variable for later processing */ if((ndata = calloc(1, sizeof(notifydata_t))) == NULL) { printf("Calloc Error %s, %d\n", __FILE__, __LINE__); @@ -1657,13 +1641,13 @@ int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int n if((status = notifyhashInsert(threadid, ndata)) != 0) { printf("reqNotify(): Insert into notify hash table not successful %s, %d\n", __FILE__, __LINE__); free(ndata); - return -1; + return -1; } - - /* Send number of oids, oidarry, version array, machine id and threadid */ + + /* Send number of oids, oidarry, version array, machine id and threadid */ if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){ printf("reqNotify():error %d connecting to %s:%d\n", errno, - inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT); + inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT); free(ndata); return -1; } else { @@ -1680,7 +1664,7 @@ int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int n i++; } } - + /* Send array of version */ { i = 0; @@ -1691,7 +1675,7 @@ int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int n i++; } } - + *((unsigned int *)(&msg[1] + size)) = myIpAddr; size += sizeof(unsigned int); *((unsigned int *)(&msg[1] + size)) = threadid; @@ -1701,7 +1685,7 @@ int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int n pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify)); pthread_mutex_unlock(&(ndata->threadnotify)); } - + pthread_cond_destroy(&threadcond); pthread_mutex_destroy(&threadnotify); free(ndata); @@ -1710,40 +1694,40 @@ int reqNotify(unsigned int *oidarry, unsigned short *versionarry, unsigned int n } void threadNotify(unsigned int oid, unsigned short version, unsigned int tid) { - notifydata_t *ndata; - int i, objIsFound = 0, index; - void *ptr; - - //Look up the tid and call the corresponding pthread_cond_signal - if((ndata = notifyhashSearch(tid)) == NULL) { - printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__); - return; - } else { - for(i = 0; i < ndata->numoid; i++) { - if(ndata->oidarry[i] == oid){ - objIsFound = 1; - index = i; - } - } - if(objIsFound == 0){ - printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__); - 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; - } else { + notifydata_t *ndata; + int i, objIsFound = 0, index; + void *ptr; + + //Look up the tid and call the corresponding pthread_cond_signal + if((ndata = notifyhashSearch(tid)) == NULL) { + printf("threadnotify(): No such threadid is present %s, %d\n", __FILE__, __LINE__); + return; + } else { + for(i = 0; i < ndata->numoid; i++) { + if(ndata->oidarry[i] == oid){ + objIsFound = 1; + index = i; + } + } + if(objIsFound == 0){ + printf("threadNotify(): Oid not found %s, %d\n", __FILE__, __LINE__); + 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; + } else { #ifdef CACHE - /* Clear from prefetch cache and free thread related data structure */ - if((ptr = prehashSearch(oid)) != NULL) { - prehashRemove(oid); - } -#endif - pthread_cond_signal(&(ndata->threadcond)); - } - } + /* Clear from prefetch cache and free thread related data structure */ + if((ptr = prehashSearch(oid)) != NULL) { + prehashRemove(oid); } - return; +#endif + pthread_cond_signal(&(ndata->threadcond)); + } + } + } + return; } int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) { @@ -1752,16 +1736,16 @@ int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) { struct sockaddr_in remoteAddr; char msg[1 + sizeof(unsigned short) + 2*sizeof(unsigned int)]; int sock, status, size, bytesSent; - + while(*head != NULL) { ptr = *head; - mid = ptr->mid; + mid = ptr->mid; //create a socket connection to that machine if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0){ perror("notifyAll():socket()"); return -1; } - + bzero(&remoteAddr, sizeof(remoteAddr)); remoteAddr.sin_family = AF_INET; remoteAddr.sin_port = htons(LISTEN_PORT); @@ -1769,7 +1753,7 @@ int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) { //send Thread Notify response and threadid to that machine if (connect(sock, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0){ printf("notifyAll():error %d connecting to %s:%d\n", errno, - inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT); + inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT); fflush(stdout); status = -1; } else { @@ -1780,7 +1764,7 @@ int notifyAll(threadlist_t **head, unsigned int oid, unsigned int version) { *((unsigned short *)(&msg[1]+ size)) = version; size+= sizeof(unsigned short); *((unsigned int *)(&msg[1]+ size)) = ptr->threadid; - + size = 1 + 2*sizeof(unsigned int) + sizeof(unsigned short); send_data(sock, msg, size); } @@ -1799,7 +1783,7 @@ void transAbort(transrecord_t *trans) { free(trans); } -/* This function inserts necessary information into +/* This function inserts necessary information into * a machine pile data structure */ plistnode_t *pInsert(plistnode_t *pile, objheader_t *headeraddr, unsigned int mid, int num_objs) { plistnode_t *ptr, *tmp; @@ -1812,28 +1796,28 @@ 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; - }else if (STATUS(headeraddr) & DIRTY) { - tmp->oidmod[tmp->nummod] = OID(headeraddr); - tmp->nummod++; - 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; } 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; } tmp = tmp->next; } - //Add oid for any new machine + //Add oid for any new machine if (!found) { int tmpsize; if((ptr = pCreate(num_objs)) == NULL) { @@ -1842,26 +1826,26 @@ plistnode_t *pInsert(plistnode_t *pile, objheader_t *headeraddr, unsigned int mi ptr->mid = mid; if (STATUS(headeraddr) & NEW) { ptr->oidcreated[ptr->numcreated] = OID(headeraddr); - ptr->numcreated ++; + ptr->numcreated++; GETSIZE(tmpsize, headeraddr); ptr->sum_bytes += sizeof(objheader_t) + tmpsize; } else if (STATUS(headeraddr) & DIRTY) { ptr->oidmod[ptr->nummod] = OID(headeraddr); - ptr->nummod ++; + ptr->nummod++; GETSIZE(tmpsize, headeraddr); ptr->sum_bytes += sizeof(objheader_t) + tmpsize; } else { *((unsigned int *)ptr->objread)=OID(headeraddr); offset = sizeof(unsigned int); *((short *)(((char *)ptr->objread) + offset)) = headeraddr->version; - ptr->numread ++; + ptr->numread++; } ptr->next = pile; pile = ptr; } - + /* Clear Flags */ STATUS(headeraddr) =0; - + return pile; } diff --git a/Robust/src/Runtime/GenericHashtable.c b/Robust/src/Runtime/GenericHashtable.c index 7528b01e..aab1c63d 100755 --- a/Robust/src/Runtime/GenericHashtable.c +++ b/Robust/src/Runtime/GenericHashtable.c @@ -16,9 +16,9 @@ #endif void * getfirstkey(struct genhashtable *ht) { - if(ht->list == NULL) { - return NULL; - } + if(ht->list == NULL) { + return NULL; + } return ht->list->src; } @@ -43,21 +43,21 @@ int genputtable(struct genhashtable *ht, void * key, void * object) { ht->counter++; if(ht->counter>ht->currentsize&&ht->currentsize!=INT_MAX) { /* Expand hashtable */ - long newcurrentsize=(ht->currentsize<(INT_MAX/2))?ht->currentsize*2:INT_MAX; + long newcurrentsize=(ht->currentsize<(INT_MAX/2)) ? ht->currentsize*2 : INT_MAX; long oldcurrentsize=ht->currentsize; struct genpointerlist **newbins=(struct genpointerlist **) RUNMALLOC(sizeof (struct genpointerlist *)*newcurrentsize); struct genpointerlist **oldbins=ht->bins; long j,i; - for(j=0;jcurrentsize=newcurrentsize; - 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; @@ -88,21 +88,21 @@ int genputtable_I(struct genhashtable *ht, void * key, void * object) { ht->counter++; if(ht->counter>ht->currentsize&&ht->currentsize!=INT_MAX) { /* Expand hashtable */ - long newcurrentsize=(ht->currentsize<(INT_MAX/2))?ht->currentsize*2:INT_MAX; + long newcurrentsize=(ht->currentsize<(INT_MAX/2)) ? ht->currentsize*2 : INT_MAX; long oldcurrentsize=ht->currentsize; struct genpointerlist **newbins=(struct genpointerlist **) RUNMALLOC_I(sizeof (struct genpointerlist *)*newcurrentsize); struct genpointerlist **oldbins=ht->bins; long j,i; - for(j=0;jcurrentsize=newcurrentsize; - 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; @@ -121,7 +121,7 @@ void genrehash(struct genhashtable * ht) { struct genpointerlist **oldbins=ht->bins; long j,i; - for(i=0;icurrentsize;i++) { + for(i=0; icurrentsize; i++) { struct genpointerlist * tmpptr=oldbins[i]; while(tmpptr!=NULL) { unsigned int hashcode=genhashfunction(ht, tmpptr->src); @@ -178,7 +178,7 @@ int gencontains(struct genhashtable *ht, void * key) { void genfreekey(struct genhashtable *ht, void * key) { struct genpointerlist * ptr=ht->bins[genhashfunction(ht,key)]; - + if (((ht->comp_function==NULL)&&(ptr->src==key))||((ht->comp_function!=NULL)&&(*ht->comp_function)(ptr->src,key))) { ht->bins[genhashfunction(ht,key)]=ptr->next; @@ -192,7 +192,7 @@ void genfreekey(struct genhashtable *ht, void * key) { ptr->iprev->inext=ptr->inext; if (ptr->inext!=NULL) ptr->inext->iprev=ptr->iprev; - + RUNFREE(ptr); ht->counter--; return; @@ -240,7 +240,7 @@ struct genhashtable * genallocatehashtable(unsigned int (*hash_function)(void *) #ifdef RAWDEBUG raw_test_pass(0xf001); #endif - for(i=0;icurrentsize;i++) { + for (i=0; icurrentsize; i++) { if (ht->bins[i]!=NULL) { struct genpointerlist *genptr=ht->bins[i]; while(genptr!=NULL) { diff --git a/Robust/src/Runtime/ObjectHash.c b/Robust/src/Runtime/ObjectHash.c index affbc128..1a79be2c 100755 --- a/Robust/src/Runtime/ObjectHash.c +++ b/Robust/src/Runtime/ObjectHash.c @@ -10,7 +10,7 @@ /* SIMPLE HASH ********************************************************/ struct ObjectIterator* ObjectHashcreateiterator(struct ObjectHash * thisvar) { - return allocateObjectIterator(thisvar->listhead); + return allocateObjectIterator(thisvar->listhead); } void ObjectHashiterator(struct ObjectHash *thisvar, struct ObjectIterator * it) { @@ -18,43 +18,43 @@ void ObjectHashiterator(struct ObjectHash *thisvar, struct ObjectIterator * it) } struct ObjectHash * noargallocateObjectHash() { - return allocateObjectHash(100); + return allocateObjectHash(100); } struct ObjectHash * allocateObjectHash(int size) { - struct ObjectHash *thisvar;//=(struct ObjectHash *)RUNMALLOC(sizeof(struct ObjectHash)); - if (size <= 0) { + struct ObjectHash *thisvar; //=(struct ObjectHash *)RUNMALLOC(sizeof(struct ObjectHash)); + if (size <= 0) { #ifdef RAW - raw_test_done(0xc001); + raw_test_done(0xc001); #else - printf("Negative Hashtable size Exception\n"); - exit(-1); + printf("Negative Hashtable size Exception\n"); + exit(-1); #endif - } - thisvar=(struct ObjectHash *)RUNMALLOC(sizeof(struct ObjectHash)); - thisvar->size = size; - thisvar->bucket = (struct ObjectNode **) RUNMALLOC(sizeof(struct ObjectNode *)*size); - /* Set allocation blocks*/ - thisvar->listhead=NULL; - thisvar->listtail=NULL; - /*Set data counts*/ - thisvar->numelements = 0; - return thisvar; + } + thisvar=(struct ObjectHash *)RUNMALLOC(sizeof(struct ObjectHash)); + thisvar->size = size; + thisvar->bucket = (struct ObjectNode **) RUNMALLOC(sizeof(struct ObjectNode *)*size); + /* Set allocation blocks*/ + thisvar->listhead=NULL; + thisvar->listtail=NULL; + /*Set data counts*/ + thisvar->numelements = 0; + return thisvar; } void freeObjectHash(struct ObjectHash *thisvar) { - struct ObjectNode *ptr=thisvar->listhead; - RUNFREE(thisvar->bucket); - while(ptr) { - struct ObjectNode *next=ptr->lnext; - RUNFREE(ptr); - ptr=next; - } - RUNFREE(thisvar); + struct ObjectNode *ptr=thisvar->listhead; + RUNFREE(thisvar->bucket); + while(ptr) { + struct ObjectNode *next=ptr->lnext; + RUNFREE(ptr); + ptr=next; + } + RUNFREE(thisvar); } inline int ObjectHashcountset(struct ObjectHash * thisvar) { - return thisvar->numelements; + return thisvar->numelements; } int ObjectHashfirstkey(struct ObjectHash *thisvar) { @@ -63,44 +63,44 @@ int ObjectHashfirstkey(struct ObjectHash *thisvar) { } int ObjectHashremove(struct ObjectHash *thisvar, int key) { - unsigned int hashkey = (unsigned int)key % thisvar->size; + unsigned int hashkey = (unsigned int)key % thisvar->size; - struct ObjectNode **ptr = &thisvar->bucket[hashkey]; - int i; + struct ObjectNode **ptr = &thisvar->bucket[hashkey]; + int i; - while (*ptr) { - if ((*ptr)->key == key) { - struct ObjectNode *toremove=*ptr; - *ptr=(*ptr)->next; - - if (toremove->lprev!=NULL) { - toremove->lprev->lnext=toremove->lnext; - } else { - thisvar->listhead=toremove->lnext; - } - if (toremove->lnext!=NULL) { - toremove->lnext->lprev=toremove->lprev; - } else { - thisvar->listtail=toremove->lprev; - } - RUNFREE(toremove); - - thisvar->numelements--; - return 1; - } - ptr = &((*ptr)->next); + while (*ptr) { + if ((*ptr)->key == key) { + struct ObjectNode *toremove=*ptr; + *ptr=(*ptr)->next; + + if (toremove->lprev!=NULL) { + toremove->lprev->lnext=toremove->lnext; + } else { + thisvar->listhead=toremove->lnext; + } + if (toremove->lnext!=NULL) { + toremove->lnext->lprev=toremove->lprev; + } else { + thisvar->listtail=toremove->lprev; + } + RUNFREE(toremove); + + thisvar->numelements--; + return 1; } + ptr = &((*ptr)->next); + } - return 0; + return 0; } void ObjectHashrehash(struct ObjectHash * thisvar) { int newsize=thisvar->size; struct ObjectNode ** newbucket = (struct ObjectNode **) RUNMALLOC(sizeof(struct ObjectNode *)*newsize); int i; - for(i=thisvar->size-1;i>=0;i--) { + for(i=thisvar->size-1; i>=0; i--) { struct ObjectNode *ptr; - for(ptr=thisvar->bucket[i];ptr!=NULL;) { + for(ptr=thisvar->bucket[i]; ptr!=NULL;) { struct ObjectNode * nextptr=ptr->next; unsigned int newhashkey=(unsigned int)ptr->key % newsize; ptr->next=newbucket[newhashkey]; @@ -122,15 +122,15 @@ int ObjectHashadd(struct ObjectHash * thisvar,int key, int data, int data2, int int newsize=2*thisvar->size+1; struct ObjectNode ** newbucket = (struct ObjectNode **) RUNMALLOC(sizeof(struct ObjectNode *)*newsize); int i; - 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; - } + 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; + } } thisvar->size=newsize; RUNFREE(thisvar->bucket); @@ -176,15 +176,15 @@ int ObjectHashadd_I(struct ObjectHash * thisvar,int key, int data, int data2, in int newsize=2*thisvar->size+1; struct ObjectNode ** newbucket = (struct ObjectNode **) RUNMALLOC_I(sizeof(struct ObjectNode *)*newsize); int i; - 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; - } + 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; + } } thisvar->size=newsize; RUNFREE(thisvar->bucket); @@ -222,93 +222,93 @@ int ObjectHashadd_I(struct ObjectHash * thisvar,int key, int data, int data2, in #endif bool ObjectHashcontainskey(struct ObjectHash *thisvar,int key) { - unsigned int hashkey = (unsigned int)key % thisvar->size; - - struct ObjectNode *ptr = thisvar->bucket[hashkey]; - while (ptr) { - if (ptr->key == key) { - /* we already have thisvar object - stored in the hash so just return */ - return true; - } - ptr = ptr->next; + unsigned int hashkey = (unsigned int)key % thisvar->size; + + struct ObjectNode *ptr = thisvar->bucket[hashkey]; + while (ptr) { + if (ptr->key == key) { + /* we already have thisvar object + stored in the hash so just return */ + return true; } - return false; + ptr = ptr->next; + } + return false; } bool ObjectHashcontainskeydata(struct ObjectHash *thisvar, int key, int data) { - unsigned int hashkey = (unsigned int)key % thisvar->size; - - struct ObjectNode *ptr = thisvar->bucket[hashkey]; - while (ptr) { - if (ptr->key == key && ptr->data == data) { - /* we already have thisvar object - stored in the hash so just return*/ - return true; - } - ptr = ptr->next; + unsigned int hashkey = (unsigned int)key % thisvar->size; + + struct ObjectNode *ptr = thisvar->bucket[hashkey]; + while (ptr) { + if (ptr->key == key && ptr->data == data) { + /* we already have thisvar object + stored in the hash so just return*/ + return true; } - return false; + ptr = ptr->next; + } + return false; } int ObjectHashcount(struct ObjectHash *thisvar,int key) { - unsigned int hashkey = (unsigned int)key % thisvar->size; - int count = 0; - - struct ObjectNode *ptr = thisvar->bucket[hashkey]; - while (ptr) { - if (ptr->key == key) { - count++; - } - ptr = ptr->next; + unsigned int hashkey = (unsigned int)key % thisvar->size; + int count = 0; + + struct ObjectNode *ptr = thisvar->bucket[hashkey]; + while (ptr) { + if (ptr->key == key) { + count++; } - return count; + ptr = ptr->next; + } + return count; } int ObjectHashget(struct ObjectHash *thisvar, int key, int *data, int *data2, int *data3, int *data4) { - unsigned int hashkey = (unsigned int)key % thisvar->size; - - struct ObjectNode *ptr = thisvar->bucket[hashkey]; - while (ptr) { - if (ptr->key == key) { - *data = ptr->data; - *data2 = ptr->data2; - *data3 = ptr->data3; - *data4 = ptr->data4; - return 1; /* success */ - } - ptr = ptr->next; + unsigned int hashkey = (unsigned int)key % thisvar->size; + + struct ObjectNode *ptr = thisvar->bucket[hashkey]; + while (ptr) { + if (ptr->key == key) { + *data = ptr->data; + *data2 = ptr->data2; + *data3 = ptr->data3; + *data4 = ptr->data4; + return 1; /* success */ } + ptr = ptr->next; + } - return 0; /* failure */ + return 0; /* failure */ } int ObjectHashupdate(struct ObjectHash *thisvar, int key, int data, int data2, int data3, int data4) { - unsigned int hashkey = (unsigned int)key % thisvar->size; - - struct ObjectNode *ptr = thisvar->bucket[hashkey]; - while (ptr) { - if (ptr->key == key) { - ptr->data=data; - ptr->data2=data2; - ptr->data3=data3; - ptr->data4=data4; - return 1; /* success */ - } - ptr = ptr->next; + unsigned int hashkey = (unsigned int)key % thisvar->size; + + struct ObjectNode *ptr = thisvar->bucket[hashkey]; + while (ptr) { + if (ptr->key == key) { + ptr->data=data; + ptr->data2=data2; + ptr->data3=data3; + ptr->data4=data4; + return 1; /* success */ } - return 0; /* failure */ + ptr = ptr->next; + } + return 0; /* failure */ } inline struct ObjectIterator * noargallocateObjectIterator() { - return (struct ObjectIterator*)RUNMALLOC(sizeof(struct ObjectIterator)); + return (struct ObjectIterator*)RUNMALLOC(sizeof(struct ObjectIterator)); } inline struct ObjectIterator * allocateObjectIterator(struct ObjectNode *start) { - struct ObjectIterator *thisvar=(struct ObjectIterator*)RUNMALLOC(sizeof(struct ObjectIterator)); - thisvar->cur = start; - return thisvar; + struct ObjectIterator *thisvar=(struct ObjectIterator*)RUNMALLOC(sizeof(struct ObjectIterator)); + thisvar->cur = start; + return thisvar; } inline int ObjhasNext(struct ObjectIterator *thisvar) { diff --git a/Robust/src/Runtime/ObjectHash.h b/Robust/src/Runtime/ObjectHash.h index b3a565bd..a8315a8b 100755 --- a/Robust/src/Runtime/ObjectHash.h +++ b/Robust/src/Runtime/ObjectHash.h @@ -38,11 +38,11 @@ void ObjectHashiterator(struct ObjectHash *, struct ObjectIterator * it); int ObjectHashcount(struct ObjectHash *, int key); struct ObjectHash { - int numelements; - int size; - struct ObjectNode **bucket; - struct ObjectNode *listhead; - struct ObjectNode *listtail; + int numelements; + int size; + struct ObjectNode **bucket; + struct ObjectNode *listhead; + struct ObjectNode *listtail; }; inline int ObjectHashcountset(struct ObjectHash * thisvar); diff --git a/Robust/src/Runtime/SimpleHash.c b/Robust/src/Runtime/SimpleHash.c index 92fe695f..b43fb0ab 100755 --- a/Robust/src/Runtime/SimpleHash.c +++ b/Robust/src/Runtime/SimpleHash.c @@ -10,7 +10,7 @@ /* SIMPLE HASH ********************************************************/ struct RuntimeIterator* RuntimeHashcreateiterator(struct RuntimeHash * thisvar) { - return allocateRuntimeIterator(thisvar->listhead); + return allocateRuntimeIterator(thisvar->listhead); } void RuntimeHashiterator(struct RuntimeHash *thisvar, struct RuntimeIterator * it) { @@ -18,43 +18,43 @@ void RuntimeHashiterator(struct RuntimeHash *thisvar, struct RuntimeIterator * i } struct RuntimeHash * noargallocateRuntimeHash() { - return allocateRuntimeHash(100); + return allocateRuntimeHash(100); } struct RuntimeHash * allocateRuntimeHash(int size) { - struct RuntimeHash *thisvar;//=(struct RuntimeHash *)RUNMALLOC(sizeof(struct RuntimeHash)); - if (size <= 0) { + struct RuntimeHash *thisvar; //=(struct RuntimeHash *)RUNMALLOC(sizeof(struct RuntimeHash)); + if (size <= 0) { #ifdef RAW - raw_test_done(0xb001); + raw_test_done(0xb001); #else - printf("Negative Hashtable size Exception\n"); - exit(-1); + printf("Negative Hashtable size Exception\n"); + exit(-1); #endif - } - thisvar=(struct RuntimeHash *)RUNMALLOC(sizeof(struct RuntimeHash)); - thisvar->size = size; - thisvar->bucket = (struct RuntimeNode **) RUNMALLOC(sizeof(struct RuntimeNode *)*size); - /* Set allocation blocks*/ - thisvar->listhead=NULL; - thisvar->listtail=NULL; - /*Set data counts*/ - thisvar->numelements = 0; - return thisvar; + } + thisvar=(struct RuntimeHash *)RUNMALLOC(sizeof(struct RuntimeHash)); + thisvar->size = size; + thisvar->bucket = (struct RuntimeNode **) RUNMALLOC(sizeof(struct RuntimeNode *)*size); + /* Set allocation blocks*/ + thisvar->listhead=NULL; + thisvar->listtail=NULL; + /*Set data counts*/ + thisvar->numelements = 0; + return thisvar; } void freeRuntimeHash(struct RuntimeHash *thisvar) { - struct RuntimeNode *ptr=thisvar->listhead; - RUNFREE(thisvar->bucket); - while(ptr) { - struct RuntimeNode *next=ptr->lnext; - RUNFREE(ptr); - ptr=next; - } - RUNFREE(thisvar); + struct RuntimeNode *ptr=thisvar->listhead; + RUNFREE(thisvar->bucket); + while(ptr) { + struct RuntimeNode *next=ptr->lnext; + RUNFREE(ptr); + ptr=next; + } + RUNFREE(thisvar); } inline int RuntimeHashcountset(struct RuntimeHash * thisvar) { - return thisvar->numelements; + return thisvar->numelements; } int RuntimeHashfirstkey(struct RuntimeHash *thisvar) { @@ -63,76 +63,76 @@ int RuntimeHashfirstkey(struct RuntimeHash *thisvar) { } int RuntimeHashremovekey(struct RuntimeHash *thisvar, int key) { - unsigned int hashkey = (unsigned int)key % thisvar->size; + unsigned int hashkey = (unsigned int)key % thisvar->size; - struct RuntimeNode **ptr = &thisvar->bucket[hashkey]; - int i; + struct RuntimeNode **ptr = &thisvar->bucket[hashkey]; + int i; - while (*ptr) { - if ((*ptr)->key == key) { - struct RuntimeNode *toremove=*ptr; - *ptr=(*ptr)->next; - - if (toremove->lprev!=NULL) { - toremove->lprev->lnext=toremove->lnext; - } else { - thisvar->listhead=toremove->lnext; - } - if (toremove->lnext!=NULL) { - toremove->lnext->lprev=toremove->lprev; - } else{ - thisvar->listtail=toremove->lprev; - } - RUNFREE(toremove); - - thisvar->numelements--; - return 1; - } - ptr = &((*ptr)->next); + while (*ptr) { + if ((*ptr)->key == key) { + struct RuntimeNode *toremove=*ptr; + *ptr=(*ptr)->next; + + if (toremove->lprev!=NULL) { + toremove->lprev->lnext=toremove->lnext; + } else { + thisvar->listhead=toremove->lnext; + } + if (toremove->lnext!=NULL) { + toremove->lnext->lprev=toremove->lprev; + } else{ + thisvar->listtail=toremove->lprev; + } + RUNFREE(toremove); + + thisvar->numelements--; + return 1; } + ptr = &((*ptr)->next); + } - return 0; + return 0; } int RuntimeHashremove(struct RuntimeHash *thisvar, int key, int data) { - unsigned int hashkey = (unsigned int)key % thisvar->size; + unsigned int hashkey = (unsigned int)key % thisvar->size; - struct RuntimeNode **ptr = &thisvar->bucket[hashkey]; - int i; + struct RuntimeNode **ptr = &thisvar->bucket[hashkey]; + int i; - while (*ptr) { - if ((*ptr)->key == key && (*ptr)->data == data) { - struct RuntimeNode *toremove=*ptr; - *ptr=(*ptr)->next; - - if (toremove->lprev!=NULL) { - toremove->lprev->lnext=toremove->lnext; - } else { - thisvar->listhead=toremove->lnext; - } - if (toremove->lnext!=NULL) { - toremove->lnext->lprev=toremove->lprev; - } else { - thisvar->listtail=toremove->lprev; - } - RUNFREE(toremove); - - thisvar->numelements--; - return 1; - } - ptr = &((*ptr)->next); + while (*ptr) { + if ((*ptr)->key == key && (*ptr)->data == data) { + struct RuntimeNode *toremove=*ptr; + *ptr=(*ptr)->next; + + if (toremove->lprev!=NULL) { + toremove->lprev->lnext=toremove->lnext; + } else { + thisvar->listhead=toremove->lnext; + } + if (toremove->lnext!=NULL) { + toremove->lnext->lprev=toremove->lprev; + } else { + thisvar->listtail=toremove->lprev; + } + RUNFREE(toremove); + + thisvar->numelements--; + return 1; } + ptr = &((*ptr)->next); + } - return 0; + return 0; } void RuntimeHashrehash(struct RuntimeHash * thisvar) { int newsize=thisvar->size; struct RuntimeNode ** newbucket = (struct RuntimeNode **) RUNMALLOC(sizeof(struct RuntimeNode *)*newsize); int i; - for(i=thisvar->size-1;i>=0;i--) { + for(i=thisvar->size-1; i>=0; i--) { struct RuntimeNode *ptr; - for(ptr=thisvar->bucket[i];ptr!=NULL;) { + for(ptr=thisvar->bucket[i]; ptr!=NULL;) { struct RuntimeNode * nextptr=ptr->next; unsigned int newhashkey=(unsigned int)ptr->key % newsize; ptr->next=newbucket[newhashkey]; @@ -154,15 +154,15 @@ int RuntimeHashadd(struct RuntimeHash * thisvar,int key, int data) { int newsize=2*thisvar->size+1; struct RuntimeNode ** newbucket = (struct RuntimeNode **) RUNMALLOC(sizeof(struct RuntimeNode *)*newsize); int i; - 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; - } + 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; + } } thisvar->size=newsize; RUNFREE(thisvar->bucket); @@ -215,15 +215,15 @@ int RuntimeHashadd_I(struct RuntimeHash * thisvar,int key, int data) { int newsize=2*thisvar->size+1; struct RuntimeNode ** newbucket = (struct RuntimeNode **) RUNMALLOC_I(sizeof(struct RuntimeNode *)*newsize); int i; - 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; - } + 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; + } } thisvar->size=newsize; RUNFREE(thisvar->bucket); @@ -268,47 +268,47 @@ int RuntimeHashadd_I(struct RuntimeHash * thisvar,int key, int data) { #endif bool RuntimeHashcontainskey(struct RuntimeHash *thisvar,int key) { - unsigned int hashkey = (unsigned int)key % thisvar->size; - - struct RuntimeNode *ptr = thisvar->bucket[hashkey]; - while (ptr) { - if (ptr->key == key) { - /* we already have thisvar object - stored in the hash so just return */ - return true; - } - ptr = ptr->next; + unsigned int hashkey = (unsigned int)key % thisvar->size; + + struct RuntimeNode *ptr = thisvar->bucket[hashkey]; + while (ptr) { + if (ptr->key == key) { + /* we already have thisvar object + stored in the hash so just return */ + return true; } - return false; + ptr = ptr->next; + } + return false; } bool RuntimeHashcontainskeydata(struct RuntimeHash *thisvar, int key, int data) { - unsigned int hashkey = (unsigned int)key % thisvar->size; - - struct RuntimeNode *ptr = thisvar->bucket[hashkey]; - while (ptr) { - if (ptr->key == key && ptr->data == data) { - /* we already have thisvar object - stored in the hash so just return*/ - return true; - } - ptr = ptr->next; + unsigned int hashkey = (unsigned int)key % thisvar->size; + + struct RuntimeNode *ptr = thisvar->bucket[hashkey]; + while (ptr) { + if (ptr->key == key && ptr->data == data) { + /* we already have thisvar object + stored in the hash so just return*/ + return true; } - return false; + ptr = ptr->next; + } + return false; } int RuntimeHashcount(struct RuntimeHash *thisvar,int key) { - unsigned int hashkey = (unsigned int)key % thisvar->size; - int count = 0; - - struct RuntimeNode *ptr = thisvar->bucket[hashkey]; - while (ptr) { - if (ptr->key == key) { - count++; - } - ptr = ptr->next; + unsigned int hashkey = (unsigned int)key % thisvar->size; + int count = 0; + + struct RuntimeNode *ptr = thisvar->bucket[hashkey]; + while (ptr) { + if (ptr->key == key) { + count++; } - return count; + ptr = ptr->next; + } + return count; } struct RuntimeHash * RuntimeHashimageSet(struct RuntimeHash *thisvar, int key) { @@ -318,7 +318,7 @@ struct RuntimeHash * RuntimeHashimageSet(struct RuntimeHash *thisvar, int key) { struct RuntimeNode *ptr = thisvar->bucket[hashkey]; while (ptr) { if (ptr->key == key) { - RuntimeHashadd(newset,ptr->data,ptr->data); + RuntimeHashadd(newset,ptr->data,ptr->data); } ptr = ptr->next; } @@ -326,28 +326,28 @@ struct RuntimeHash * RuntimeHashimageSet(struct RuntimeHash *thisvar, int key) { } int RuntimeHashget(struct RuntimeHash *thisvar, int key, int *data) { - unsigned int hashkey = (unsigned int)key % thisvar->size; - - struct RuntimeNode *ptr = thisvar->bucket[hashkey]; - while (ptr) { - if (ptr->key == key) { - *data = ptr->data; - return 1; /* success */ - } - ptr = ptr->next; + unsigned int hashkey = (unsigned int)key % thisvar->size; + + struct RuntimeNode *ptr = thisvar->bucket[hashkey]; + while (ptr) { + if (ptr->key == key) { + *data = ptr->data; + return 1; /* success */ } + ptr = ptr->next; + } - return 0; /* failure */ + return 0; /* failure */ } inline struct RuntimeIterator * noargallocateRuntimeIterator() { - return (struct RuntimeIterator*)RUNMALLOC(sizeof(struct RuntimeIterator)); + return (struct RuntimeIterator*)RUNMALLOC(sizeof(struct RuntimeIterator)); } inline struct RuntimeIterator * allocateRuntimeIterator(struct RuntimeNode *start) { - struct RuntimeIterator *thisvar=(struct RuntimeIterator*)RUNMALLOC(sizeof(struct RuntimeIterator)); - thisvar->cur = start; - return thisvar; + struct RuntimeIterator *thisvar=(struct RuntimeIterator*)RUNMALLOC(sizeof(struct RuntimeIterator)); + thisvar->cur = start; + return thisvar; } inline int RunhasNext(struct RuntimeIterator *thisvar) { diff --git a/Robust/src/Runtime/SimpleHash.h b/Robust/src/Runtime/SimpleHash.h index e777d541..ec026904 100755 --- a/Robust/src/Runtime/SimpleHash.h +++ b/Robust/src/Runtime/SimpleHash.h @@ -40,11 +40,11 @@ int RuntimeHashcount(struct RuntimeHash *, int key); struct RuntimeHash * RuntimeHashimageSet(struct RuntimeHash *, int key); struct RuntimeHash { - int numelements; - int size; - struct RuntimeNode **bucket; - struct RuntimeNode *listhead; - struct RuntimeNode *listtail; + int numelements; + int size; + struct RuntimeNode **bucket; + struct RuntimeNode *listhead; + struct RuntimeNode *listtail; }; inline int RuntimeHashcountset(struct RuntimeHash * thisvar); diff --git a/Robust/src/Runtime/checkpoint.c b/Robust/src/Runtime/checkpoint.c index dd3be84d..51b577a3 100644 --- a/Robust/src/Runtime/checkpoint.c +++ b/Robust/src/Runtime/checkpoint.c @@ -65,55 +65,55 @@ void checkvalid(void * ptr) { } } -void validitycheck(struct RuntimeHash *forward, struct RuntimeHash *reverse) { - struct RuntimeIterator rit; - RuntimeHashiterator(forward, &rit); - while(RunhasNext(&rit)) { - struct ___Object___ * data=(struct ___Object___*) Runnext(&rit); - int type=data->type; - unsigned int * pointer=pointerarray[type]; - int size; - int i; - if (pointer!=0&&((int)pointer)!=1) { - size=pointer[0]; - for(i=1;i<=size;i++) { - int offset=pointer[i]; - void * ptr=*(void **) (((int) data) + offset); - if (ptr!=NULL&&!RuntimeHashcontainskey(reverse, (int) ptr)) { +void validitycheck(struct RuntimeHash *forward, struct RuntimeHash *reverse) { + struct RuntimeIterator rit; + RuntimeHashiterator(forward, &rit); + while(RunhasNext(&rit)) { + struct ___Object___ * data=(struct ___Object___*) Runnext(&rit); + int type=data->type; + unsigned int * pointer=pointerarray[type]; + int size; + int i; + if (pointer!=0&&((int)pointer)!=1) { + size=pointer[0]; + for(i=1; i<=size; i++) { + int offset=pointer[i]; + void * ptr=*(void **)(((int) data) + offset); + if (ptr!=NULL&&!RuntimeHashcontainskey(reverse, (int) ptr)) { #ifndef RAW - printf("Bad\n"); + printf("Bad\n"); #endif - } - checkvalid(ptr); } + checkvalid(ptr); } } + } - RuntimeHashiterator(reverse, &rit); - while(RunhasNext(&rit)) { - struct ___Object___ * data=(struct ___Object___*) Runkey(&rit); - int type=0; - unsigned int * pointer=NULL; - int size; - int i; - Runnext(&rit); - type=data->type; - pointer=pointerarray[type]; - if (pointer!=0&&((int)pointer)!=1) { - size=pointer[0]; - for(i=1;i<=size;i++) { - int offset=pointer[i]; - void * ptr=*(void **) (((int) data) + offset); - if (ptr!=NULL&&!RuntimeHashcontainskey(reverse, (int) ptr)) { + RuntimeHashiterator(reverse, &rit); + while(RunhasNext(&rit)) { + struct ___Object___ * data=(struct ___Object___*) Runkey(&rit); + int type=0; + unsigned int * pointer=NULL; + int size; + int i; + Runnext(&rit); + type=data->type; + pointer=pointerarray[type]; + if (pointer!=0&&((int)pointer)!=1) { + size=pointer[0]; + for(i=1; i<=size; i++) { + int offset=pointer[i]; + void * ptr=*(void **)(((int) data) + offset); + if (ptr!=NULL&&!RuntimeHashcontainskey(reverse, (int) ptr)) { #ifndef RAW - printf("Bad2\n"); + printf("Bad2\n"); #endif - } - checkvalid(ptr); } + checkvalid(ptr); } } } +} @@ -126,7 +126,7 @@ void ** makecheckpoint(int numparams, void ** srcpointer, struct RuntimeHash * f struct RuntimeHash *todo=allocateRuntimeHash(100); int i; - for(i=0;i___length___; int i; - for(i=0;i___length___)+sizeof(int)))[i]; + for(i=0; i___length___)+sizeof(int)))[i]; if (objptr==NULL) { - ((void **)(((char *)& ao_cpy->___length___)+sizeof(int)))[i]=NULL; + ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]=NULL; } else if (RuntimeHashcontainskey(forward, (int) objptr)) - RuntimeHashget(forward,(int) objptr,(int *) &((void **)(((char *)& ao_cpy->___length___)+sizeof(int)))[i]); + RuntimeHashget(forward,(int) objptr,(int *) &((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]); else { void * copy=createcopy(objptr); RuntimeHashadd(forward, (int) objptr, (int)copy); RuntimeHashadd(reverse, (int) copy, (int) objptr); RuntimeHashadd(todo, (int) objptr, (int) objptr); - ((void **)(((char *)& ao_cpy->___length___)+sizeof(int)))[i]=copy; + ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]=copy; } } } else { int size=pointer[0]; int i; - for(i=1;i<=size;i++) { + for(i=1; i<=size; i++) { int offset=pointer[i]; void * objptr=*((void **)(((int)ptr)+offset)); if (objptr==NULL) { - *((void **) (((int)cpy)+offset))=NULL; + *((void **)(((int)cpy)+offset))=NULL; } else if (RuntimeHashcontainskey(forward, (int) objptr)) RuntimeHashget(forward, (int) objptr, (int *) &(((char *)cpy)[offset])); else { @@ -202,7 +202,7 @@ void ** makecheckpoint(int numparams, void ** srcpointer, struct RuntimeHash * f RuntimeHashadd(forward, (int) objptr, (int) copy); RuntimeHashadd(reverse, (int) copy, (int) objptr); RuntimeHashadd(todo, (int) objptr, (int) objptr); - *((void **) (((int)cpy)+offset))=copy; + *((void **)(((int)cpy)+offset))=copy; } } } @@ -249,13 +249,13 @@ void restorecheckpoint(int numparams, void ** original, void ** checkpoint, stru struct RuntimeHash *visited=allocateRuntimeHash(100); int i; - for(i=0;iflagptr)); + RuntimeHashget(reverse, (int) objptr, (int *) &(((struct ___TagDescriptor___ *)cpy)->flagptr)); } } else #endif @@ -296,16 +296,16 @@ void restorecheckpoint(int numparams, void ** original, void ** checkpoint, stru int cpysize=sizeof(struct ArrayObject)+length*size; memcpy(ao_cpy, ao, cpysize); - for(i=0;i___length___)+sizeof(int)))[i]; + for(i=0; i___length___)+sizeof(int)))[i]; if (objptr==NULL) - ((void **)(((char *)& ao_cpy->___length___)+sizeof(int)))[i]=NULL; + ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]=NULL; else { if (!RuntimeHashcontainskey(visited, (int) objptr)) { RuntimeHashadd(visited, (int) objptr, (int) objptr); RuntimeHashadd(todo, (int) objptr, (int) objptr); } - RuntimeHashget(reverse, (int) objptr, (int *) &((void **)(((char *)& ao_cpy->___length___)+sizeof(int)))[i]); + RuntimeHashget(reverse, (int) objptr, (int *) &((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]); } } } else { @@ -315,16 +315,16 @@ void restorecheckpoint(int numparams, void ** original, void ** checkpoint, stru int oldflag; int currflag; if (hasflags[type]) { - flagptr=(void *) (((int *)cpy)[2]); + flagptr=(void *)(((int *)cpy)[2]); oldflag=(((int *)cpy)[1]); currflag=(((int *)ptr)[1]); } memcpy(cpy, ptr, size); - for(i=1;i<=numptr;i++) { + for(i=1; i<=numptr; i++) { int offset=pointer[i]; void * objptr=*((void **)(((int)ptr)+offset)); if (objptr==NULL) - *((void **) (((int)cpy)+offset))=NULL; + *((void **)(((int)cpy)+offset))=NULL; else { if (!RuntimeHashcontainskey(visited, (int) objptr)) { RuntimeHashadd(visited, (int) objptr, (int) objptr); @@ -340,7 +340,7 @@ void restorecheckpoint(int numparams, void ** original, void ** checkpoint, stru #ifdef MULTICORE enqueueObject(cpy, NULL,0); //TODO #else - enqueueObject(cpy); + enqueueObject(cpy); #endif } } diff --git a/Robust/src/Runtime/file.c b/Robust/src/Runtime/file.c index 6a13701d..ae4366cf 100644 --- a/Robust/src/Runtime/file.c +++ b/Robust/src/Runtime/file.c @@ -10,7 +10,7 @@ #include "runtime.h" void CALL34(___FileOutputStream______nativeWrite____I__AR_B_I_I, int fd, int off, int len, int fd, struct ArrayObject * ___array___, int off, int len) { - char * string= (((char *)& VAR(___array___)->___length___)+sizeof(int)); + char * string= (((char *)&VAR(___array___)->___length___)+sizeof(int)); int status=write(fd, &string[off], len); } @@ -19,7 +19,7 @@ void CALL11(___FileOutputStream______nativeClose____I, int fd, int fd) { } void CALL11(___FileOutputStream______nativeFlush____I, int fd, int fd) { - // not supported in RAW version + // not supported in RAW version #ifndef RAW fsync(fd); #endif @@ -27,21 +27,21 @@ void CALL11(___FileOutputStream______nativeFlush____I, int fd, int fd) { int CALL01(___FileOutputStream______nativeOpen_____AR_B, struct ArrayObject * ___filename___) { int length=VAR(___filename___)->___length___; - char* filename= (((char *)& VAR(___filename___)->___length___)+sizeof(int)); + char* filename= (((char *)&VAR(___filename___)->___length___)+sizeof(int)); int fd=open(filename, O_WRONLY|O_CREAT|O_TRUNC, S_IRWXU); return fd; } int CALL01(___FileOutputStream______nativeAppend_____AR_B, struct ArrayObject * ___filename___) { int length=VAR(___filename___)->___length___; - char* filename= (((char *)& VAR(___filename___)->___length___)+sizeof(int)); + char* filename= (((char *)&VAR(___filename___)->___length___)+sizeof(int)); int fd=open(filename, O_WRONLY|O_CREAT|O_APPEND, S_IRWXU); return fd; } int CALL01(___FileInputStream______nativeOpen_____AR_B, struct ArrayObject * ___filename___) { int length=VAR(___filename___)->___length___; - char* filename= (((char *)& VAR(___filename___)->___length___)+sizeof(int)); + char* filename= (((char *)&VAR(___filename___)->___length___)+sizeof(int)); int fd=open(filename, O_RDONLY, 0); return fd; } @@ -52,7 +52,7 @@ void CALL11(___FileInputStream______nativeClose____I, int fd, int fd) { int CALL23(___FileInputStream______nativeRead____I__AR_B_I, int fd, int numBytes, int fd, struct ArrayObject * ___array___, int numBytes) { int toread=VAR(___array___)->___length___; - char* string= (((char *)& VAR(___array___)->___length___)+sizeof(int)); + char* string= (((char *)&VAR(___array___)->___length___)+sizeof(int)); int status; if (numBytes___length___; - char* filename= (((char *)& VAR(___pathname___)->___length___)+sizeof(int)); + char* filename= (((char *)&VAR(___pathname___)->___length___)+sizeof(int)); struct stat st; stat(filename, &st); return st.st_size; diff --git a/Robust/src/Runtime/garbage.c b/Robust/src/Runtime/garbage.c index beb67c86..fb03fe5a 100644 --- a/Robust/src/Runtime/garbage.c +++ b/Robust/src/Runtime/garbage.c @@ -44,20 +44,20 @@ int listcount=0; //Need to check if pointers are transaction pointers #ifdef DSTM #define ENQUEUE(orig, dst) \ -if ((!(((unsigned int)orig)&0x1))) {\ -if (orig>=curr_heapbase&&orig=curr_heapbase&&orignext=tmp; head=tmp; @@ -159,14 +159,14 @@ void collect(struct garbagelist * stackptr) { /* Check current stack */ #if defined(THREADS)||defined(DSTM) - { - struct listitem *listptr=list; - while(1) { + { + struct listitem *listptr=list; + while(1) { #endif - + while(stackptr!=NULL) { int i; - for(i=0;isize;i++) { + for(i=0; isize; i++) { void * orig=stackptr->array[i]; ENQUEUE(orig, stackptr->array[i]); } @@ -181,15 +181,15 @@ void collect(struct garbagelist * stackptr) { listptr=listptr->next; } else break; - } - } +} +} #endif - + #ifdef TASK { /* Update objectsets */ int i; - for(i=0;ilisthead; while(ptr!=NULL) { @@ -239,20 +239,20 @@ void collect(struct garbagelist * stackptr) { { /* Update current task descriptor */ int i; - for(i=0;inumParameters;i++) { + for(i=0; inumParameters; i++) { void *orig=currtpd->parameterArray[i]; ENQUEUE(orig, currtpd->parameterArray[i]); } } - /* Update active tasks */ + /* Update active tasks */ { struct genpointerlist * ptr=activetasks->list; while(ptr!=NULL) { struct taskparamdescriptor *tpd=ptr->src; int i; - for(i=0;inumParameters;i++) { + for(i=0; inumParameters; i++) { void * orig=tpd->parameterArray[i]; ENQUEUE(orig, tpd->parameterArray[i]); } @@ -261,13 +261,13 @@ void collect(struct garbagelist * stackptr) { genrehash(activetasks); } - /* Update failed tasks */ + /* Update failed tasks */ { struct genpointerlist * ptr=failedtasks->list; while(ptr!=NULL) { struct taskparamdescriptor *tpd=ptr->src; int i; - for(i=0;inumParameters;i++) { + for(i=0; inumParameters; i++) { void * orig=tpd->parameterArray[i]; ENQUEUE(orig, tpd->parameterArray[i]); } @@ -310,17 +310,17 @@ void collect(struct garbagelist * stackptr) { #endif int length=ao->___length___; int i; - for(i=0;i___length___)+sizeof(int)))[i]; - ENQUEUE(objptr, ((void **)(((char *)& ao_cpy->___length___)+sizeof(int)))[i]); + for(i=0; i___length___)+sizeof(int)))[i]; + ENQUEUE(objptr, ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]); } } else { int size=pointer[0]; int i; - for(i=1;i<=size;i++) { + for(i=1; i<=size; i++) { unsigned int offset=pointer[i]; void * objptr=*((void **)(((int)ptr)+offset)); - ENQUEUE(objptr, *((void **) (((int)cpy)+offset))); + ENQUEUE(objptr, *((void **)(((int)cpy)+offset))); } } } @@ -342,7 +342,7 @@ void fixtags() { while(taghead!=NULL) { int i; struct pointerblock *tmp=taghead->next; - for(i=0;iptrs[i]; struct ___Object___ *obj=tagd->flagptr; struct ___TagDescriptor___ *copy=((struct ___TagDescriptor___**)tagd)[1]; @@ -358,21 +358,21 @@ void fixtags() { int j; int k=0; struct ArrayObject *aonew; - + /* Count live objects */ - for(j=0;j___cachedCode___;j++) { + 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++) { + 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]; @@ -380,7 +380,7 @@ void fixtags() { } } aonew->___cachedCode___=k; - for(;kcurr_heapgcpoint) { #if defined(THREADS)||defined(DSTM) @@ -541,7 +541,7 @@ void * mygcmalloc(struct garbagelist * stackptr, int size) { #endif return mygcmalloc(stackptr, size); } - + bzero(tmp, curr_heaptop-tmp); #if defined(THREADS)||defined(DSTM) pthread_mutex_unlock(&gclock); @@ -566,7 +566,8 @@ int gc_createcopy(void * orig, void ** copy_ptr) { if (type==-1) { *copy_ptr=((void **)orig)[1]; return 0; - } if (type /*void * m_calloc(int m, int size) { - void * p = malloc(m*size); - int i = 0; - for(i = 0; i < size; ++i) { - *(char *)(p+i) = 0; - } - return p; -}*/ + void * p = malloc(m*size); + int i = 0; + for(i = 0; i < size; ++i) { + *(char *)(p+i) = 0; + } + return p; + }*/ void * mycalloc(int m, int size) { - void * p = NULL; - int isize = 2*kCacheLineSize-4+(size-1)&(~kCacheLineMask); + void * p = NULL; + int isize = 2*kCacheLineSize-4+(size-1)&(~kCacheLineMask); #ifdef RAWDEBUG - raw_test_pass(0xdd00); + raw_test_pass(0xdd00); #endif #ifdef INTERRUPT - // shut down interrupt - raw_user_interrupts_off(); + // shut down interrupt + raw_user_interrupts_off(); #endif - p = calloc(m, isize); - //p = m_calloc(m, isize); + p = calloc(m, isize); + //p = m_calloc(m, isize); #ifdef RAWDEBUG - raw_test_pass_reg(p); - raw_test_pass_reg((kCacheLineSize+((int)p-1)&(~kCacheLineMask))); + raw_test_pass_reg(p); + raw_test_pass_reg((kCacheLineSize+((int)p-1)&(~kCacheLineMask))); #endif #ifdef INTERRUPT - // re-open interruption - raw_user_interrupts_on(); + // re-open interruption + raw_user_interrupts_on(); #endif - return (void *)(kCacheLineSize+((int)p-1)&(~kCacheLineMask)); + return (void *)(kCacheLineSize+((int)p-1)&(~kCacheLineMask)); } void * mycalloc_i(int m, int size) { - void * p = NULL; - int isize = 2*kCacheLineSize-4+(size-1)&(~kCacheLineMask); + void * p = NULL; + int isize = 2*kCacheLineSize-4+(size-1)&(~kCacheLineMask); #ifdef RAWDEBUG - raw_test_pass(0xdd00); + raw_test_pass(0xdd00); #endif - p = calloc(m, isize); - //p = m_calloc(m, isize); + p = calloc(m, isize); + //p = m_calloc(m, isize); #ifdef RAWDEBUG - raw_test_pass_reg(p); - raw_test_pass_reg((kCacheLineSize+((int)p-1)&(~kCacheLineMask))); + raw_test_pass_reg(p); + raw_test_pass_reg((kCacheLineSize+((int)p-1)&(~kCacheLineMask))); #endif - return (void *)(kCacheLineSize+((int)p-1)&(~kCacheLineMask)); + return (void *)(kCacheLineSize+((int)p-1)&(~kCacheLineMask)); } void myfree(void * ptr) { - return; + return; } #endif diff --git a/Robust/src/Runtime/mem.h b/Robust/src/Runtime/mem.h index fa82a2c3..18b64c25 100644 --- a/Robust/src/Runtime/mem.h +++ b/Robust/src/Runtime/mem.h @@ -1,8 +1,8 @@ #ifndef MEMH #define MEMH -#include +#include #ifndef RAW -#include +#include #endif #ifdef BOEHM_GC diff --git a/Robust/src/Runtime/multicoreruntime.c b/Robust/src/Runtime/multicoreruntime.c index a65f8c08..47a42648 100644 --- a/Robust/src/Runtime/multicoreruntime.c +++ b/Robust/src/Runtime/multicoreruntime.c @@ -2,11 +2,11 @@ #include "structdefs.h" #include #include "mem.h" -#include -#include -#include +#include +#include +#include #ifndef RAW -#include +#include #endif //#include "option.h" @@ -28,11 +28,12 @@ int instaccum=0; #endif #ifdef RAW -void initializeexithandler() {} +void initializeexithandler() { +} #else void exithandler(int sig, siginfo_t *info, void * uap) { #ifdef DEBUG - printf("exit in exithandler\n"); + printf("exit in exithandler\n"); #endif exit(0); } @@ -50,14 +51,14 @@ void initializeexithandler() { void injectinstructionfailure() { #ifdef RAW - // not supported in RAW version - return; + // not supported in RAW version + return; #else #ifdef TASK if (injectinstructionfailures) { if (numfailures==0) return; - instructioncount=failurecount; + instructioncount=failurecount; instaccum+=failurecount; if ((((double)random())/RAND_MAX)0) @@ -86,10 +87,10 @@ void injectinstructionfailure() { void CALL11(___System______exit____I,int ___status___, int ___status___) { #ifdef DEBUG - printf("exit in CALL11\n"); + printf("exit in CALL11\n"); #endif #ifdef RAW - raw_test_done(___status___); + raw_test_done(___status___); #else exit(___status___); #endif @@ -97,20 +98,20 @@ void CALL11(___System______exit____I,int ___status___, int ___status___) { void CALL11(___System______printI____I,int ___status___, int ___status___) { #ifdef DEBUG - printf("printI in CALL11\n"); + printf("printI in CALL11\n"); #endif #ifdef RAW - raw_test_pass(0x1111); - raw_test_pass_reg(___status___); + raw_test_pass(0x1111); + raw_test_pass_reg(___status___); #else - printf("%d\n", ___status___); + printf("%d\n", ___status___); #endif } long CALL00(___System______currentTimeMillis____) { #ifdef RAW - // not supported in RAW version - return -1; + // not supported in RAW version + return -1; #else struct timeval tv; long long retval; gettimeofday(&tv, NULL); @@ -124,13 +125,13 @@ long CALL00(___System______currentTimeMillis____) { void CALL01(___System______printString____L___String___,struct ___String___ * ___s___) { #ifdef RAW #else - struct ArrayObject * chararray=VAR(___s___)->___value___; - int i; - int offset=VAR(___s___)->___offset___; - for(i=0;i___count___;i++) { - short sc=((short *)(((char *)& chararray->___length___)+sizeof(int)))[i+offset]; - putchar(sc); - } + struct ArrayObject * chararray=VAR(___s___)->___value___; + int i; + int offset=VAR(___s___)->___offset___; + for(i=0; i___count___; i++) { + short sc=((short *)(((char *)&chararray->___length___)+sizeof(int)))[i+offset]; + putchar(sc); + } #endif } @@ -214,8 +215,9 @@ struct ___String___ * NewString(const char *str,int length) { strobj->___count___=length; strobj->___offset___=0; - for(i=0;i___length___)+sizeof(int)))[i]=(short)str[i]; } + for(i=0; i___length___)+sizeof(int)))[i]=(short)str[i]; + } return strobj; } diff --git a/Robust/src/Runtime/multicoretask.c b/Robust/src/Runtime/multicoretask.c index 2ca150d2..dd3bd789 100644 --- a/Robust/src/Runtime/multicoretask.c +++ b/Robust/src/Runtime/multicoretask.c @@ -27,9 +27,9 @@ #include #endif /* -extern int injectfailures; -extern float failurechance; -*/ + extern int injectfailures; + extern float failurechance; + */ extern int debugtask; extern int instaccum; @@ -51,7 +51,7 @@ struct RuntimeHash * reverse; int corestatus[NUMCORES]; // records status of each core // 1: running tasks - // 0: stall +// 0: stall int numsendobjs[NUMCORES]; // records how many objects a core has sent out int numreceiveobjs[NUMCORES]; // records how many objects a core has received #ifdef RAW @@ -82,11 +82,11 @@ void calCoords(int core_num, int* coordY, int* coordX); #elif defined THREADSIMULATE static struct RuntimeHash* locktbl; struct thread_data { - int corenum; - int argc; - char** argv; - int numsendobjs; - int numreceiveobjs; + int corenum; + int argc; + char** argv; + int numsendobjs; + int numreceiveobjs; }; struct thread_data thread_data_array[NUMCORES]; mqd_t mqd[NUMCORES]; @@ -115,167 +115,168 @@ void begin() { int main(int argc, char **argv) { #endif #ifdef RAW - int i = 0; - int argc = 1; - char ** argv = NULL; - bool sendStall = false; - bool isfirst = true; - bool tocontinue = false; - struct QueueItem * objitem = NULL; - struct transObjInfo * objInfo = NULL; - int grount = 0; - bool allStall = true; - int sumsendobj = 0; + int i = 0; + int argc = 1; + char ** argv = NULL; + bool sendStall = false; + bool isfirst = true; + bool tocontinue = false; + struct QueueItem * objitem = NULL; + struct transObjInfo * objInfo = NULL; + int grount = 0; + bool allStall = true; + int sumsendobj = 0; #ifdef RAWDEBUG - raw_test_pass(0xee01); + raw_test_pass(0xee01); #endif - corenum = raw_get_abs_pos_x() + 4 * raw_get_abs_pos_y(); + corenum = raw_get_abs_pos_x() + 4 * raw_get_abs_pos_y(); - // initialize the arrays - if(STARTUPCORE == corenum) { - // startup core to initialize corestatus[] - for(i = 0; i < NUMCORES; ++i) { - corestatus[i] = 1; - numsendobjs[i] = 0; // assume all variables in RAW are local variables! MAY BE WRONG!!! - numreceiveobjs[i] = 0; - } - } - self_numsendobjs = 0; - self_numreceiveobjs = 0; - for(i = 0; i < 30; ++i) { - msgdata[i] = -1; - } - //msgdata = NULL; - msgtype = -1; - msgdataindex = 0; - msglength = 30; + // initialize the arrays + if(STARTUPCORE == corenum) { + // startup core to initialize corestatus[] + for(i = 0; i < NUMCORES; ++i) { + corestatus[i] = 1; + numsendobjs[i] = 0; // assume all variables in RAW are local variables! MAY BE WRONG!!! + numreceiveobjs[i] = 0; + } + } + self_numsendobjs = 0; + self_numreceiveobjs = 0; + for(i = 0; i < 30; ++i) { + msgdata[i] = -1; + } + //msgdata = NULL; + msgtype = -1; + msgdataindex = 0; + msglength = 30; - for(i = 0; i < 30; ++i) { - outmsgdata[i] = -1; - } - outmsgindex = 0; - outmsglast = 0; - outmsgleft = 0; - isMsgHanging = false; - isMsgSending = false; -#ifdef RAWDEBUG - raw_test_pass(0xee02); -#endif - - // create the lock table, lockresult table and obj queue - locktable.size = 20; - locktable.bucket = (struct RuntimeNode **) RUNMALLOC_I(sizeof(struct RuntimeNode *)*20); - /* Set allocation blocks*/ - locktable.listhead=NULL; - locktable.listtail=NULL; - /*Set data counts*/ - locktable.numelements = 0; - lockobj = 0; - lockresult = 0; - lockflag = false; + for(i = 0; i < 30; ++i) { + outmsgdata[i] = -1; + } + outmsgindex = 0; + outmsglast = 0; + outmsgleft = 0; + isMsgHanging = false; + isMsgSending = false; +#ifdef RAWDEBUG + raw_test_pass(0xee02); +#endif + + // create the lock table, lockresult table and obj queue + locktable.size = 20; + locktable.bucket = (struct RuntimeNode **) RUNMALLOC_I(sizeof(struct RuntimeNode *)*20); + /* Set allocation blocks*/ + locktable.listhead=NULL; + locktable.listtail=NULL; + /*Set data counts*/ + locktable.numelements = 0; + lockobj = 0; + lockresult = 0; + lockflag = false; #ifndef INTERRUPT - reside = false; + reside = false; #endif - objqueue.head = NULL; - objqueue.tail = NULL; + objqueue.head = NULL; + objqueue.tail = NULL; #ifdef RAWDEBUG - raw_test_pass(0xee03); + raw_test_pass(0xee03); #endif #ifdef INTERRUPT - if (corenum < NUMCORES) { - // set up interrupts - setup_ints(); - //setup_interrupts(); - //start_gdn_avail_ints(recvMsg); - raw_user_interrupts_on(); + if (corenum < NUMCORES) { + // set up interrupts + setup_ints(); + //setup_interrupts(); + //start_gdn_avail_ints(recvMsg); + raw_user_interrupts_on(); #ifdef RAWDEBUG - raw_test_pass(0xee04); + raw_test_pass(0xee04); #endif - } + } #endif #elif defined THREADSIMULATE - errno = 0; - int tids[NUMCORES]; - int rc[NUMCORES]; - pthread_t threads[NUMCORES]; - int i = 0; - - // initialize three arrays and msg queue array - char * pathhead = "/msgqueue_"; - int targetlen = strlen(pathhead); - for(i = 0; i < NUMCORES; ++i) { - corestatus[i] = 1; - numsendobjs[i] = 0; - numreceiveobjs[i] = 0; - - char corenumstr[3]; - int sourcelen = 0; - if(i < 10) { - corenumstr[0] = i + '0'; - corenumstr[1] = '\0'; - sourcelen = 1; - } else if(i < 100) { - corenumstr[1] = i %10 + '0'; - corenumstr[0] = (i / 10) + '0'; - corenumstr[2] = '\0'; - sourcelen = 2; - } else { - printf("Error: i >= 100\n"); - fflush(stdout); - exit(-1); - } - char path[targetlen + sourcelen + 1]; - strcpy(path, pathhead); - strncat(path, corenumstr, sourcelen); - int oflags = O_RDONLY|O_CREAT|O_NONBLOCK; - int omodes = S_IRWXU|S_IRWXG|S_IRWXO; - mq_unlink(path); - mqd[i]= mq_open(path, oflags, omodes, NULL); - if(mqd[i] == -1) { - printf("[Main] mq_open %s fails: %d, error: %s\n", path, mqd[i], strerror(errno)); - exit(-1); - } else { - printf("[Main] mq_open %s returns: %d\n", path, mqd[i]); - } - } + errno = 0; + int tids[NUMCORES]; + int rc[NUMCORES]; + pthread_t threads[NUMCORES]; + int i = 0; - // create the key - pthread_key_create(&key, NULL); + // initialize three arrays and msg queue array + char * pathhead = "/msgqueue_"; + int targetlen = strlen(pathhead); + for(i = 0; i < NUMCORES; ++i) { + corestatus[i] = 1; + numsendobjs[i] = 0; + numreceiveobjs[i] = 0; + + char corenumstr[3]; + int sourcelen = 0; + if(i < 10) { + corenumstr[0] = i + '0'; + corenumstr[1] = '\0'; + sourcelen = 1; + } else if(i < 100) { + corenumstr[1] = i %10 + '0'; + corenumstr[0] = (i / 10) + '0'; + corenumstr[2] = '\0'; + sourcelen = 2; + } else { + printf("Error: i >= 100\n"); + fflush(stdout); + exit(-1); + } + char path[targetlen + sourcelen + 1]; + strcpy(path, pathhead); + strncat(path, corenumstr, sourcelen); + int oflags = O_RDONLY|O_CREAT|O_NONBLOCK; + int omodes = S_IRWXU|S_IRWXG|S_IRWXO; + mq_unlink(path); + mqd[i]= mq_open(path, oflags, omodes, NULL); + if(mqd[i] == -1) { + printf("[Main] mq_open %s fails: %d, error: %s\n", path, mqd[i], strerror(errno)); + exit(-1); + } else { + printf("[Main] mq_open %s returns: %d\n", path, mqd[i]); + } + } - // create the lock table and initialize its mutex - locktbl = allocateRuntimeHash(20); - int rc_locktbl = pthread_rwlock_init(&rwlock_tbl, NULL); - printf("[Main] initialize the rwlock for lock table: %d error: \n", rc_locktbl, strerror(rc_locktbl)); + // create the key + pthread_key_create(&key, NULL); + + // create the lock table and initialize its mutex + locktbl = allocateRuntimeHash(20); + int rc_locktbl = pthread_rwlock_init(&rwlock_tbl, NULL); + printf("[Main] initialize the rwlock for lock table: %d error: \n", rc_locktbl, strerror(rc_locktbl)); + + for(i = 0; i < NUMCORES; ++i) { + thread_data_array[i].corenum = i; + thread_data_array[i].argc = argc; + thread_data_array[i].argv = argv; + thread_data_array[i].numsendobjs = 0; + thread_data_array[i].numreceiveobjs = 0; + printf("[main] creating thread %d\n", i); + rc[i] = pthread_create(&threads[i], NULL, run, (void *)&thread_data_array[i]); + if (rc[i]){ + printf("[main] ERROR; return code from pthread_create() is %d\n", rc[i]); + fflush(stdout); + exit(-1); + } + } - for(i = 0; i < NUMCORES; ++i) { - thread_data_array[i].corenum = i; - thread_data_array[i].argc = argc; - thread_data_array[i].argv = argv; - thread_data_array[i].numsendobjs = 0; - thread_data_array[i].numreceiveobjs = 0; - printf("[main] creating thread %d\n", i); - rc[i] = pthread_create(&threads[i], NULL, run, (void *)&thread_data_array[i]); - if (rc[i]){ - printf("[main] ERROR; return code from pthread_create() is %d\n", rc[i]); - fflush(stdout); - exit(-1); - } - } - - //pthread_exit(NULL); - while(true) {} + //pthread_exit(NULL); + while(true) { + } } void run(void* arg) { - struct thread_data * my_tdata = (struct thread_data *)arg; - pthread_setspecific(key, (void *)my_tdata->corenum); - int argc = my_tdata->argc; - char** argv = my_tdata->argv; - printf("[run, %d] Thread %d runs: %x\n", my_tdata->corenum, my_tdata->corenum, (int)pthread_self()); - fflush(stdout); + struct thread_data * my_tdata = (struct thread_data *)arg; + pthread_setspecific(key, (void *)my_tdata->corenum); + int argc = my_tdata->argc; + char** argv = my_tdata->argv; + printf("[run, %d] Thread %d runs: %x\n", my_tdata->corenum, my_tdata->corenum, (int)pthread_self()); + fflush(stdout); #endif @@ -295,29 +296,29 @@ void run(void* arg) { /* Create table for failed tasks */ #ifdef RAW if(corenum > NUMCORES - 1) { - failedtasks = NULL; - activetasks = NULL; - while(true) { - receiveObject(); - } + failedtasks = NULL; + activetasks = NULL; + while(true) { + receiveObject(); + } } else { #ifdef RAWDEBUG - raw_test_pass(0xee06); + raw_test_pass(0xee06); #endif #endif - /*failedtasks=genallocatehashtable((unsigned int (*)(void *)) &hashCodetpd, - (int (*)(void *,void *)) &comparetpd);*/ - failedtasks = NULL; + /*failedtasks=genallocatehashtable((unsigned int (*)(void *)) &hashCodetpd, + (int (*)(void *,void *)) &comparetpd);*/ + failedtasks = NULL; #ifdef RAWDEBUG raw_test_pass(0xee07); #endif /* Create queue of active tasks */ - activetasks=genallocatehashtable((unsigned int (*)(void *)) &hashCodetpd, - (int (*)(void *,void *)) &comparetpd); + activetasks=genallocatehashtable((unsigned int(*) (void *)) &hashCodetpd, + (int(*) (void *,void *)) &comparetpd); #ifdef RAWDEBUG raw_test_pass(0xee08); #endif - + /* Process task information */ processtasks(); #ifdef RAWDEBUG @@ -325,8 +326,8 @@ void run(void* arg) { #endif if(STARTUPCORE == corenum) { - /* Create startup object */ - createstartupobject(argc, argv); + /* Create startup object */ + createstartupobject(argc, argv); } #ifdef RAWDEBUG raw_test_pass(0xee0a); @@ -336,203 +337,204 @@ void run(void* arg) { #ifdef RAWDEBUG raw_test_pass(0xee0b); #endif - + while(true) { /*#ifndef INTERRUPT - while(receiveObject() != -1) { - } -#endif*/ + while(receiveObject() != -1) { + } + #endif*/ - // check if there are new active tasks can be executed - executetasks(); + // check if there are new active tasks can be executed + executetasks(); #ifndef INTERRUPT - while(receiveObject() != -1) { - } + while(receiveObject() != -1) { + } #endif #ifdef RAWDEBUG - raw_test_pass(0xee0c); + raw_test_pass(0xee0c); #endif - // check if there are some pending objects, if yes, enqueue them and executetasks again - tocontinue = false; + // check if there are some pending objects, if yes, enqueue them and executetasks again + tocontinue = false; #ifdef RAWDEBUG - raw_test_pass(0xee0d); + raw_test_pass(0xee0d); #endif - while(!isEmpty(&objqueue)) { - void * obj = NULL; + while(!isEmpty(&objqueue)) { + void * obj = NULL; #ifdef INTERRUPT - raw_user_interrupts_off(); + raw_user_interrupts_off(); #endif #ifdef RAWDEBUG - raw_test_pass(0xeee1); + raw_test_pass(0xeee1); #endif - sendStall = false; - tocontinue = true; - objitem = getTail(&objqueue); - //obj = objitem->objectptr; - objInfo = (struct transObjInfo *)objitem->objectptr; - obj = objInfo->objptr; + sendStall = false; + tocontinue = true; + objitem = getTail(&objqueue); + //obj = objitem->objectptr; + objInfo = (struct transObjInfo *)objitem->objectptr; + obj = objInfo->objptr; #ifdef RAWDEBUG - raw_test_pass_reg((int)obj); + raw_test_pass_reg((int)obj); #endif - // grab lock and flush the obj - getreadlock_I(obj); - while(!lockflag) { - receiveObject(); - } - grount = lockresult; + // grab lock and flush the obj + getreadlock_I(obj); + while(!lockflag) { + receiveObject(); + } + grount = lockresult; #ifdef RAWDEBUG - raw_test_pass_reg(grount); + raw_test_pass_reg(grount); #endif - lockresult = 0; - lockobj = 0; - lockflag = false; + lockresult = 0; + lockobj = 0; + lockflag = false; #ifndef INTERRUPT - reside = false; -#endif - - if(grount == 1) { - int k = 0; - raw_invalidate_cache_range((int)obj, classsize[((struct ___Object___ *)obj)->type]); - // flush the obj - /*for(k = 0; k < classsize[((struct ___Object___ *)obj)->type]; ++k) { - invalidateAddr(obj + k); - }*/ - // enqueue the object - for(k = 0; k < objInfo->length; ++k) { - int taskindex = objInfo->queues[2 * k]; - int paramindex = objInfo->queues[2 * k + 1]; - struct parameterwrapper ** queues = &(paramqueues[corenum][taskindex][paramindex]); -#ifdef RAWDEBUG - raw_test_pass_reg(taskindex); - raw_test_pass_reg(paramindex); -#endif - enqueueObject_I(obj, queues, 1); - } - removeItem(&objqueue, objitem); - releasereadlock_I(obj); - RUNFREE(objInfo->queues); - RUNFREE(objInfo); - /*enqueueObject_I(obj, NULL, 0); - removeItem(&objqueue, objitem); - releasereadlock_I(obj);*/ - } else { - // can not get lock - // put it at the end of the queue - // and try to execute active tasks already enqueued first - removeItem(&objqueue, objitem); - addNewItem_I(&objqueue, objInfo); + reside = false; +#endif + + if(grount == 1) { + int k = 0; + raw_invalidate_cache_range((int)obj, classsize[((struct ___Object___ *)obj)->type]); + // flush the obj + /*for(k = 0; k < classsize[((struct ___Object___ *)obj)->type]; ++k) { + invalidateAddr(obj + k); + }*/ + // enqueue the object + for(k = 0; k < objInfo->length; ++k) { + int taskindex = objInfo->queues[2 * k]; + int paramindex = objInfo->queues[2 * k + 1]; + struct parameterwrapper ** queues = &(paramqueues[corenum][taskindex][paramindex]); +#ifdef RAWDEBUG + raw_test_pass_reg(taskindex); + raw_test_pass_reg(paramindex); +#endif + enqueueObject_I(obj, queues, 1); + } + removeItem(&objqueue, objitem); + releasereadlock_I(obj); + RUNFREE(objInfo->queues); + RUNFREE(objInfo); + /*enqueueObject_I(obj, NULL, 0); + removeItem(&objqueue, objitem); + releasereadlock_I(obj);*/ + } else { + // can not get lock + // put it at the end of the queue + // and try to execute active tasks already enqueued first + removeItem(&objqueue, objitem); + addNewItem_I(&objqueue, objInfo); #ifdef INTERRUPT - raw_user_interrupts_on(); + raw_user_interrupts_on(); #endif - break; - } + break; + } #ifdef INTERRUPT - raw_user_interrupts_on(); + raw_user_interrupts_on(); #endif #ifdef RAWDEBUG - raw_test_pass(0xee0e); + raw_test_pass(0xee0e); #endif - } + } #ifdef RAWDEBUG - raw_test_pass(0xee0f); + raw_test_pass(0xee0f); #endif - - if(!tocontinue) { - // check if stop - if(STARTUPCORE == corenum) { - if(isfirst) { + + if(!tocontinue) { + // check if stop + if(STARTUPCORE == corenum) { + if(isfirst) { #ifdef RAWDEBUG - raw_test_pass(0xee10); + raw_test_pass(0xee10); #endif - isfirst = false; - } + isfirst = false; + } #ifdef INTERRUPT - raw_user_interrupts_off(); + raw_user_interrupts_off(); #endif - corestatus[corenum] = 0; - numsendobjs[corenum] = self_numsendobjs; - numreceiveobjs[corenum] = self_numreceiveobjs; - // check the status of all cores - allStall = true; + corestatus[corenum] = 0; + numsendobjs[corenum] = self_numsendobjs; + numreceiveobjs[corenum] = self_numreceiveobjs; + // check the status of all cores + allStall = true; #ifdef RAWDEBUG - raw_test_pass_reg(NUMCORES); + raw_test_pass_reg(NUMCORES); #endif - for(i = 0; i < NUMCORES; ++i) { + for(i = 0; i < NUMCORES; ++i) { #ifdef RAWDEBUG - raw_test_pass(0xe000 + corestatus[i]); + raw_test_pass(0xe000 + corestatus[i]); #endif - if(corestatus[i] != 0) { - allStall = false; - break; - } - } - if(allStall) { - // check if the sum of send objs and receive obj are the same - // yes->terminate - // no->go on executing - sumsendobj = 0; - for(i = 0; i < NUMCORES; ++i) { - sumsendobj += numsendobjs[i]; + if(corestatus[i] != 0) { + allStall = false; + break; + } + } + if(allStall) { + // check if the sum of send objs and receive obj are the same + // yes->terminate + // no->go on executing + sumsendobj = 0; + for(i = 0; i < NUMCORES; ++i) { + sumsendobj += numsendobjs[i]; #ifdef RAWDEBUG - raw_test_pass(0xf000 + numsendobjs[i]); + raw_test_pass(0xf000 + numsendobjs[i]); #endif - } - for(i = 0; i < NUMCORES; ++i) { - sumsendobj -= numreceiveobjs[i]; + } + for(i = 0; i < NUMCORES; ++i) { + sumsendobj -= numreceiveobjs[i]; #ifdef RAWDEBUG - raw_test_pass(0xf000 + numreceiveobjs[i]); + raw_test_pass(0xf000 + numreceiveobjs[i]); #endif - } - if(0 == sumsendobj) { - // terminate + } + if(0 == sumsendobj) { + // terminate #ifdef RAWDEBUG - raw_test_pass(0xee11); + raw_test_pass(0xee11); #endif - raw_test_pass(raw_get_cycle()); - raw_test_done(1); // All done. - } - } + raw_test_pass(raw_get_cycle()); + raw_test_done(1); // All done. + } + } #ifdef INTERRUPT - raw_user_interrupts_on(); + raw_user_interrupts_on(); #endif - } else { - if(!sendStall) { + } else { + if(!sendStall) { #ifdef RAWDEBUG - raw_test_pass(0xee12); + raw_test_pass(0xee12); #endif - if(isfirst) { - // wait for some time - int halt = 10000; + if(isfirst) { + // wait for some time + int halt = 10000; #ifdef RAWDEBUG - raw_test_pass(0xee13); + raw_test_pass(0xee13); #endif - while(halt--){} - isfirst = false; + while(halt--){ + } + isfirst = false; #ifdef RAWDEBUG - raw_test_pass(0xee14); + raw_test_pass(0xee14); #endif - } else { - // send StallMsg to startup core + } else { + // send StallMsg to startup core #ifdef RAWDEBUG - raw_test_pass(0xee15); + raw_test_pass(0xee15); #endif - sendStall = transStallMsg(STARTUPCORE); - isfirst = true; - } - } else { - isfirst = true; + sendStall = transStallMsg(STARTUPCORE); + isfirst = true; + } + } else { + isfirst = true; #ifdef RAWDEBUG - raw_test_pass(0xee16); + raw_test_pass(0xee16); #endif - } - } - } - } + } + } + } } +} #elif defined THREADSIMULATE /* Start executing the tasks */ executetasks(); @@ -543,150 +545,153 @@ void run(void* arg) { int numofcore = pthread_getspecific(key); while(true) { - switch(receiveObject()) { - case 0: { - printf("[run, %d] receive an object\n", numofcore); - sendStall = false; - // received an object - // check if there are new active tasks can be executed - executetasks(); - break; - } - case 1: { - //printf("[run, %d] no msg\n", numofcore); - // no msg received - if(STARTUPCORE == numofcore) { - corestatus[numofcore] = 0; - // check the status of all cores - bool allStall = true; - for(i = 0; i < NUMCORES; ++i) { - if(corestatus[i] != 0) { - allStall = false; - break; - } - } - if(allStall) { - // check if the sum of send objs and receive obj are the same - // yes->terminate - // no->go on executing - int sumsendobj = 0; - for(i = 0; i < NUMCORES; ++i) { - sumsendobj += numsendobjs[i]; - } - for(i = 0; i < NUMCORES; ++i) { - sumsendobj -= numreceiveobjs[i]; - } - if(0 == sumsendobj) { - // terminate - - // release all locks - int rc_tbl = pthread_rwlock_wrlock(&rwlock_tbl); - printf("[run, %d] getting the write lock for locktbl: %d error: \n", numofcore, rc_tbl, strerror(rc_tbl)); - struct RuntimeIterator* it_lock = RuntimeHashcreateiterator(locktbl); - while(0 != RunhasNext(it_lock)) { - int key = Runkey(it_lock); - pthread_rwlock_t* rwlock_obj = (pthread_rwlock_t*)Runnext(it_lock); - int rc_des = pthread_rwlock_destroy(rwlock_obj); - printf("[run, %d] destroy the rwlock for object: %d error: \n", numofcore, key, strerror(rc_des)); - RUNFREE(rwlock_obj); - } - freeRuntimeHash(locktbl); - locktbl = NULL; - RUNFREE(it_lock); - - // destroy all message queues - char * pathhead = "/msgqueue_"; - int targetlen = strlen(pathhead); - for(i = 0; i < NUMCORES; ++i) { - char corenumstr[3]; - int sourcelen = 0; - if(i < 10) { - corenumstr[0] = i + '0'; - corenumstr[1] = '\0'; - sourcelen = 1; - } else if(i < 100) { - corenumstr[1] = i %10 + '0'; - corenumstr[0] = (i / 10) + '0'; - corenumstr[2] = '\0'; - sourcelen = 2; - } else { - printf("Error: i >= 100\n"); - fflush(stdout); - exit(-1); - } - char path[targetlen + sourcelen + 1]; - strcpy(path, pathhead); - strncat(path, corenumstr, sourcelen); - mq_unlink(path); - } - - printf("[run, %d] terminate!\n", numofcore); - fflush(stdout); - exit(0); - } - } - } else { - if(!sendStall) { - // send StallMsg to startup core - sendStall = transStallMsg(STARTUPCORE); - } - } - break; - } - case 2: { - printf("[run, %d] receive a stall msg\n", numofcore); - // receive a Stall Msg, do nothing - assert(STARTUPCORE == numofcore); // only startup core can receive such msg - sendStall = false; - break; - } - /* case 3: { - printf("[run, %d] receive a terminate msg\n", numofcore); - // receive a terminate Msg - assert(STARTUPCORE != corenum); // only non-startup core can receive such msg - mq_close(mqd[corenum]); - fflush(stdout); - exit(0); - break; - }*/ - default: { - printf("[run, %d] Error: invalid message type.\n", numofcore); - fflush(stdout); - exit(-1); - break; - } + switch(receiveObject()) { + case 0: { + printf("[run, %d] receive an object\n", numofcore); + sendStall = false; + // received an object + // check if there are new active tasks can be executed + executetasks(); + break; + } + + case 1: { + //printf("[run, %d] no msg\n", numofcore); + // no msg received + if(STARTUPCORE == numofcore) { + corestatus[numofcore] = 0; + // check the status of all cores + bool allStall = true; + for(i = 0; i < NUMCORES; ++i) { + if(corestatus[i] != 0) { + allStall = false; + break; + } + } + if(allStall) { + // check if the sum of send objs and receive obj are the same + // yes->terminate + // no->go on executing + int sumsendobj = 0; + for(i = 0; i < NUMCORES; ++i) { + sumsendobj += numsendobjs[i]; + } + for(i = 0; i < NUMCORES; ++i) { + sumsendobj -= numreceiveobjs[i]; } + if(0 == sumsendobj) { + // terminate + + // release all locks + int rc_tbl = pthread_rwlock_wrlock(&rwlock_tbl); + printf("[run, %d] getting the write lock for locktbl: %d error: \n", numofcore, rc_tbl, strerror(rc_tbl)); + struct RuntimeIterator* it_lock = RuntimeHashcreateiterator(locktbl); + while(0 != RunhasNext(it_lock)) { + int key = Runkey(it_lock); + pthread_rwlock_t* rwlock_obj = (pthread_rwlock_t*)Runnext(it_lock); + int rc_des = pthread_rwlock_destroy(rwlock_obj); + printf("[run, %d] destroy the rwlock for object: %d error: \n", numofcore, key, strerror(rc_des)); + RUNFREE(rwlock_obj); + } + freeRuntimeHash(locktbl); + locktbl = NULL; + RUNFREE(it_lock); + + // destroy all message queues + char * pathhead = "/msgqueue_"; + int targetlen = strlen(pathhead); + for(i = 0; i < NUMCORES; ++i) { + char corenumstr[3]; + int sourcelen = 0; + if(i < 10) { + corenumstr[0] = i + '0'; + corenumstr[1] = '\0'; + sourcelen = 1; + } else if(i < 100) { + corenumstr[1] = i %10 + '0'; + corenumstr[0] = (i / 10) + '0'; + corenumstr[2] = '\0'; + sourcelen = 2; + } else { + printf("Error: i >= 100\n"); + fflush(stdout); + exit(-1); + } + char path[targetlen + sourcelen + 1]; + strcpy(path, pathhead); + strncat(path, corenumstr, sourcelen); + mq_unlink(path); + } + + printf("[run, %d] terminate!\n", numofcore); + fflush(stdout); + exit(0); + } + } + } else { + if(!sendStall) { + // send StallMsg to startup core + sendStall = transStallMsg(STARTUPCORE); + } + } + break; + } + + case 2: { + printf("[run, %d] receive a stall msg\n", numofcore); + // receive a Stall Msg, do nothing + assert(STARTUPCORE == numofcore); // only startup core can receive such msg + sendStall = false; + break; + } + + /* case 3: { + printf("[run, %d] receive a terminate msg\n", numofcore); + // receive a terminate Msg + assert(STARTUPCORE != corenum); // only non-startup core can receive such msg + mq_close(mqd[corenum]); + fflush(stdout); + exit(0); + break; + }*/ + default: { + printf("[run, %d] Error: invalid message type.\n", numofcore); + fflush(stdout); + exit(-1); + break; + } + } } #endif } void createstartupobject(int argc, char ** argv) { int i; - + /* Allocate startup object */ #ifdef PRECISE_GC struct ___StartupObject___ *startupobject=(struct ___StartupObject___*) allocate_new(NULL, STARTUPTYPE); - struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1); + struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1); #else struct ___StartupObject___ *startupobject=(struct ___StartupObject___*) allocate_new(STARTUPTYPE); - struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1); + struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1); #endif /* Build array of strings */ startupobject->___parameters___=stringarray; - for(i=1;i___length___)+sizeof(int)))[i-1]=newstring; + ((void **)(((char *)&stringarray->___length___)+sizeof(int)))[i-1]=newstring; } - + startupobject->isolate = 1; startupobject->version = 0; - /* Set initialized flag for startup object */ + /* Set initialized flag for startup object */ flagorandinit(startupobject,1,0xFFFFFFFF); enqueueObject(startupobject, NULL, 0); #ifdef RAW @@ -698,7 +703,7 @@ void createstartupobject(int argc, char ** argv) { int hashCodetpd(struct taskparamdescriptor *ftd) { int hash=(int)ftd->task; int i; - for(i=0;inumParameters;i++){ + for(i=0; inumParameters; i++){ hash^=(int)ftd->parameterArray[i]; } return hash; @@ -708,7 +713,7 @@ int comparetpd(struct taskparamdescriptor *ftd1, struct taskparamdescriptor *ftd int i; if (ftd1->task!=ftd2->task) return 0; - for(i=0;inumParameters;i++) + for(i=0; inumParameters; i++) if(ftd1->parameterArray[i]!=ftd2->parameterArray[i]) return 0; return 1; @@ -720,14 +725,14 @@ void tagset(void *ptr, struct ___Object___ * obj, struct ___TagDescriptor___ * t #else void tagset(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { #endif - struct ArrayObject * ao=NULL; + struct ArrayObject * ao=NULL; struct ___Object___ * tagptr=obj->___tags___; #ifdef RAWDEBUG raw_test_pass(0xebb0); #endif if (tagptr==NULL) { #ifdef RAWDEBUG - raw_test_pass(0xebb1); + raw_test_pass(0xebb1); #endif obj->___tags___=(struct ___Object___ *)tagd; } else { @@ -735,14 +740,14 @@ void tagset(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { if (tagptr->type==TAGTYPE) { struct ___TagDescriptor___ * td=(struct ___TagDescriptor___ *) tagptr; #ifdef RAWDEBUG - raw_test_pass(0xebb2); + raw_test_pass(0xebb2); #endif if (td==tagd) { #ifdef RAWDEBUG - raw_test_pass(0xebb3); + raw_test_pass(0xebb3); #endif return; - } + } #ifdef PRECISE_GC int ptrarray[]={2, (int) ptr, (int) obj, (int)tagd}; struct ArrayObject * ao=allocate_newarray(&ptrarray,TAGARRAYTYPE,TAGARRAYINTERVAL); @@ -751,42 +756,42 @@ void tagset(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { td=(struct ___TagDescriptor___ *) obj->___tags___; #else #ifdef RAWDEBUG - raw_test_pass(0xebb4); + raw_test_pass(0xebb4); #endif ao=allocate_newarray(TAGARRAYTYPE,TAGARRAYINTERVAL); #endif #ifdef RAWDEBUG - raw_test_pass(0xebb5); + raw_test_pass(0xebb5); #endif ARRAYSET(ao, struct ___TagDescriptor___ *, 0, td); ARRAYSET(ao, struct ___TagDescriptor___ *, 1, tagd); obj->___tags___=(struct ___Object___ *) ao; ao->___cachedCode___=2; #ifdef RAWDEBUG - raw_test_pass(0xebb6); + raw_test_pass(0xebb6); #endif } else { /* Array Case */ int i; struct ArrayObject *ao=(struct ArrayObject *) tagptr; #ifdef RAWDEBUG - raw_test_pass(0xebb7); + raw_test_pass(0xebb7); #endif - for(i=0;i___cachedCode___;i++) { + for(i=0; i___cachedCode___; i++) { struct ___TagDescriptor___ * td=ARRAYGET(ao, struct ___TagDescriptor___*, i); #ifdef RAWDEBUG - raw_test_pass(0xebb8); + raw_test_pass(0xebb8); #endif if (td==tagd) { #ifdef RAWDEBUG - raw_test_pass(0xebb9); + raw_test_pass(0xebb9); #endif return; } } if (ao->___cachedCode______length___) { #ifdef RAWDEBUG - raw_test_pass(0xebba); + raw_test_pass(0xebba); #endif ARRAYSET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___, tagd); ao->___cachedCode___++; @@ -804,17 +809,17 @@ void tagset(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { struct ArrayObject * aonew=allocate_newarray(TAGARRAYTYPE,TAGARRAYINTERVAL+ao->___length___); #endif #ifdef RAWDEBUG - raw_test_pass(0xebbc); + raw_test_pass(0xebbc); #endif aonew->___cachedCode___=ao->___length___+1; - for(i=0;i___length___;i++) { + for(i=0; i___length___; i++) { #ifdef RAWDEBUG - raw_test_pass(0xebbd); + raw_test_pass(0xebbd); #endif ARRAYSET(aonew, struct ___TagDescriptor___*, i, ARRAYGET(ao, struct ___TagDescriptor___*, i)); } #ifdef RAWDEBUG - raw_test_pass(0xebbe); + raw_test_pass(0xebbe); #endif ARRAYSET(aonew, struct ___TagDescriptor___ *, ao->___length___, tagd); #ifdef RAWDEBUG @@ -827,11 +832,11 @@ void tagset(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { { struct ___Object___ * tagset=tagd->flagptr; #ifdef RAWDEBUG - raw_test_pass(0xb008); + raw_test_pass(0xb008); #endif if(tagset==NULL) { #ifdef RAWDEBUG - raw_test_pass(0xb009); + raw_test_pass(0xb009); #endif tagd->flagptr=obj; } else if (tagset->type!=OBJECTARRAYTYPE) { @@ -848,13 +853,13 @@ void tagset(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { ao->___cachedCode___=2; tagd->flagptr=(struct ___Object___ *)ao; #ifdef RAWDEBUG - raw_test_pass(0xb00a); + raw_test_pass(0xb00a); #endif } else { struct ArrayObject *ao=(struct ArrayObject *) tagset; if (ao->___cachedCode______length___) { #ifdef RAWDEBUG - raw_test_pass(0xb00b); + raw_test_pass(0xb00b); #endif ARRAYSET(ao, struct ___Object___*, ao->___cachedCode___++, obj); } else { @@ -869,7 +874,7 @@ void tagset(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { struct ArrayObject * aonew=allocate_newarray(OBJECTARRAYTYPE,OBJECTARRAYINTERVAL); #endif aonew->___cachedCode___=ao->___cachedCode___+1; - for(i=0;i___length___;i++) { + for(i=0; i___length___; i++) { ARRAYSET(aonew, struct ___Object___*, i, ARRAYGET(ao, struct ___Object___*, i)); } ARRAYSET(aonew, struct ___Object___ *, ao->___cachedCode___, obj); @@ -899,11 +904,11 @@ void tagclear(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { #ifndef RAW printf("ERROR 1 in tagclear\n"); #endif - ; + ; } else { struct ArrayObject *ao=(struct ArrayObject *) tagptr; int i; - for(i=0;i___cachedCode___;i++) { + for(i=0; i___cachedCode___; i++) { struct ___TagDescriptor___ * td=ARRAYGET(ao, struct ___TagDescriptor___ *, i); if (td==tagd) { ao->___cachedCode___--; @@ -918,9 +923,9 @@ void tagclear(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { #ifndef RAW printf("ERROR 2 in tagclear\n"); #endif - ; + ; } - PROCESSCLEAR: +PROCESSCLEAR: { struct ___Object___ *tagset=tagd->flagptr; if (tagset->type!=OBJECTARRAYTYPE) { @@ -930,11 +935,11 @@ void tagclear(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { #ifndef RAW printf("ERROR 3 in tagclear\n"); #endif - ; + ; } else { struct ArrayObject *ao=(struct ArrayObject *) tagset; int i; - for(i=0;i___cachedCode___;i++) { + for(i=0; i___cachedCode___; i++) { struct ___Object___ * tobj=ARRAYGET(ao, struct ___Object___ *, i); if (tobj==obj) { ao->___cachedCode___--; @@ -951,10 +956,10 @@ void tagclear(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { #endif } } - ENDCLEAR: +ENDCLEAR: return; } - + /* This function allocates a new tag. */ #ifdef PRECISE_GC struct ___TagDescriptor___ * allocate_tag(void *ptr, int index) { @@ -966,7 +971,7 @@ struct ___TagDescriptor___ * allocate_tag(int index) { v->type=TAGTYPE; v->flag=index; return v; -} +} @@ -974,37 +979,37 @@ struct ___TagDescriptor___ * allocate_tag(int index) { with the or mask and and's it with the andmask. */ void flagbody(struct ___Object___ *ptr, int flag, struct parameterwrapper ** queues, int length, bool isnew); - - int flagcomp(const int *val1, const int *val2) { - return (*val1)-(*val2); - } + +int flagcomp(const int *val1, const int *val2) { + return (*val1)-(*val2); +} void flagorand(void * ptr, int ormask, int andmask, struct parameterwrapper ** queues, int length) { - { - int oldflag=((int *)ptr)[1]; - int flag=ormask|oldflag; - flag&=andmask; + { + int oldflag=((int *)ptr)[1]; + int flag=ormask|oldflag; + flag&=andmask; #ifdef RAWDEBUG - raw_test_pass_reg((int)ptr); - raw_test_pass(0xaa000000 + oldflag); - raw_test_pass(0xaa000000 + flag); + raw_test_pass_reg((int)ptr); + raw_test_pass(0xaa000000 + oldflag); + raw_test_pass(0xaa000000 + flag); #endif - flagbody(ptr, flag, queues, length, false); - } + flagbody(ptr, flag, queues, length, false); + } } - + bool intflagorand(void * ptr, int ormask, int andmask) { - { - int oldflag=((int *)ptr)[1]; - int flag=ormask|oldflag; - flag&=andmask; - if (flag==oldflag) /* Don't do anything */ - return false; - else { - flagbody(ptr, flag, NULL, 0, false); - return true; - } + { + int oldflag=((int *)ptr)[1]; + int flag=ormask|oldflag; + flag&=andmask; + if (flag==oldflag) /* Don't do anything */ + return false; + else { + flagbody(ptr, flag, NULL, 0, false); + return true; } + } } void flagorandinit(void * ptr, int ormask, int andmask) { @@ -1012,8 +1017,8 @@ void flagorandinit(void * ptr, int ormask, int andmask) { int flag=ormask|oldflag; flag&=andmask; #ifdef RAWDEBUG - raw_test_pass(0xaa100000 + oldflag); - raw_test_pass(0xaa100000 + flag); + raw_test_pass(0xaa100000 + oldflag); + raw_test_pass(0xaa100000 + flag); #endif flagbody(ptr,flag,NULL,0,true); } @@ -1028,19 +1033,19 @@ void flagbody(struct ___Object___ *ptr, int flag, struct parameterwrapper ** vqu int * enterflags = NULL; if((!isnew) && (queues == NULL)) { #ifdef THREADSIMULATE - int numofcore = pthread_getspecific(key); - queues = objectqueues[numofcore][ptr->type]; - length = numqueues[numofcore][ptr->type]; + int numofcore = pthread_getspecific(key); + queues = objectqueues[numofcore][ptr->type]; + length = numqueues[numofcore][ptr->type]; #else #ifdef RAW - if(corenum < NUMCORES) { + if(corenum < NUMCORES) { #endif - queues = objectqueues[corenum][ptr->type]; - length = numqueues[corenum][ptr->type]; + queues = objectqueues[corenum][ptr->type]; + length = numqueues[corenum][ptr->type]; #ifdef RAW - } else { - return; - } + } else { + return; + } #endif #endif } @@ -1048,140 +1053,140 @@ void flagbody(struct ___Object___ *ptr, int flag, struct parameterwrapper ** vqu #ifdef RAWDEBUG raw_test_pass(0xbb000000 + ptr->flag); #endif - + /*Remove object from all queues */ for(i = 0; i < length; ++i) { - flagptr = queues[i]; + flagptr = queues[i]; ObjectHashget(flagptr->objectset, (int) ptr, (int *) &next, (int *) &enterflags, &UNUSED, &UNUSED2); ObjectHashremove(flagptr->objectset, (int)ptr); if (enterflags!=NULL) RUNFREE(enterflags); } - } +} + +void enqueueObject(void * vptr, struct parameterwrapper ** vqueues, int vlength) { + struct ___Object___ *ptr = (struct ___Object___ *)vptr; - void enqueueObject(void * vptr, struct parameterwrapper ** vqueues, int vlength) { - struct ___Object___ *ptr = (struct ___Object___ *)vptr; - { struct QueueItem *tmpptr; - struct parameterwrapper * parameter=NULL; - int j; - int i; + struct parameterwrapper * parameter=NULL; + int j; + int i; struct parameterwrapper * prevptr=NULL; struct ___Object___ *tagptr=NULL; - struct parameterwrapper ** queues = vqueues; - int length = vlength; + struct parameterwrapper ** queues = vqueues; + int length = vlength; #ifdef RAW - if(corenum > NUMCORES - 1) { - return; - } + if(corenum > NUMCORES - 1) { + return; + } #endif - if(queues == NULL) { + if(queues == NULL) { #ifdef THREADSIMULATE - int numofcore = pthread_getspecific(key); - queues = objectqueues[numofcore][ptr->type]; - length = numqueues[numofcore][ptr->type]; + int numofcore = pthread_getspecific(key); + queues = objectqueues[numofcore][ptr->type]; + length = numqueues[numofcore][ptr->type]; #else - queues = objectqueues[corenum][ptr->type]; - length = numqueues[corenum][ptr->type]; + queues = objectqueues[corenum][ptr->type]; + length = numqueues[corenum][ptr->type]; #endif - } + } tagptr=ptr->___tags___; - + /* Outer loop iterates through all parameter queues an object of this type could be in. */ for(j = 0; j < length; ++j) { - parameter = queues[j]; + parameter = queues[j]; /* 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 + 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++) { + 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 + goto nextloop; /*We don't have this tag */ + } + } else { //multiple tags struct ArrayObject * ao=(struct ArrayObject *) tagptr; - for(i=0;inumbertags;i++) { + 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++) { + for(j=0; j___cachedCode___; j++) { if (tagid==ARRAYGET(ao, struct ___TagDescriptor___*, j)->flag) goto foundtag; } goto nextloop; - foundtag: +foundtag: ; } } } - + /* Check flags */ - for(i=0;inumberofterms;i++) { + for(i=0; inumberofterms; i++) { int andmask=parameter->intarray[i*2]; int checkmask=parameter->intarray[i*2+1]; if ((ptr->flag&andmask)==checkmask) { #ifdef RAWDEBUG - raw_test_pass(0xcc000000 + andmask); - raw_test_pass_reg((int)ptr); - raw_test_pass(0xcc000000 + ptr->flag); - raw_test_pass(0xcc000000 + checkmask); + raw_test_pass(0xcc000000 + andmask); + raw_test_pass_reg((int)ptr); + raw_test_pass(0xcc000000 + ptr->flag); + raw_test_pass(0xcc000000 + checkmask); #endif enqueuetasks(parameter, prevptr, ptr, NULL, 0); prevptr=parameter; break; } } - nextloop: - ; +nextloop: + ; } } } #ifdef RAW void enqueueObject_I(void * vptr, struct parameterwrapper ** vqueues, int vlength) { - struct ___Object___ *ptr = (struct ___Object___ *)vptr; - + struct ___Object___ *ptr = (struct ___Object___ *)vptr; + { struct QueueItem *tmpptr; - struct parameterwrapper * parameter=NULL; - int j; - int i; + struct parameterwrapper * parameter=NULL; + int j; + int i; struct parameterwrapper * prevptr=NULL; struct ___Object___ *tagptr=NULL; - struct parameterwrapper ** queues = vqueues; - int length = vlength; + struct parameterwrapper ** queues = vqueues; + int length = vlength; #ifdef RAW - if(corenum > NUMCORES - 1) { - return; - } + if(corenum > NUMCORES - 1) { + return; + } #endif - if(queues == NULL) { + if(queues == NULL) { #ifdef THREADSIMULATE - int numofcore = pthread_getspecific(key); - queues = objectqueues[numofcore][ptr->type]; - length = numqueues[numofcore][ptr->type]; + int numofcore = pthread_getspecific(key); + queues = objectqueues[numofcore][ptr->type]; + length = numqueues[numofcore][ptr->type]; #else - queues = objectqueues[corenum][ptr->type]; - length = numqueues[corenum][ptr->type]; + queues = objectqueues[corenum][ptr->type]; + length = numqueues[corenum][ptr->type]; #endif - } + } #ifdef RAWDEBUG - raw_test_pass(0xeaa1); - raw_test_pass_reg(queues); - raw_test_pass_reg(length); + raw_test_pass(0xeaa1); + raw_test_pass_reg(queues); + raw_test_pass_reg(length); #endif tagptr=ptr->___tags___; - + /* Outer loop iterates through all parameter queues an object of this type could be in. */ for(j = 0; j < length; ++j) { - parameter = queues[j]; + parameter = queues[j]; /* Check tags */ if (parameter->numbertags>0) { #ifdef RAWDEBUG @@ -1189,48 +1194,48 @@ void enqueueObject_I(void * vptr, struct parameterwrapper ** vqueues, int vlengt raw_test_pass_reg(tagptr); #endif if (tagptr==NULL) - goto nextloop;//that means the object has no tag but that param needs tag - else if(tagptr->type==TAGTYPE) {//one tag + 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; #ifdef RAWDEBUG - raw_test_pass(0xeaa3); + raw_test_pass(0xeaa3); #endif - for(i=0;inumbertags;i++) { + for(i=0; inumbertags; i++) { //slotid is parameter->tagarray[2*i]; int tagid=parameter->tagarray[2*i+1]; if (tagid!=tagptr->flag) { #ifdef RAWDEBUG - raw_test_pass(0xeaa4); + raw_test_pass(0xeaa4); #endif goto nextloop; /*We don't have this tag */ - } - } - } else {//multiple tags + } + } + } else { //multiple tags struct ArrayObject * ao=(struct ArrayObject *) tagptr; #ifdef RAWDEBUG - raw_test_pass(0xeaa5); + raw_test_pass(0xeaa5); #endif - for(i=0;inumbertags;i++) { + 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++) { + for(j=0; j___cachedCode___; j++) { if (tagid==ARRAYGET(ao, struct ___TagDescriptor___*, j)->flag) { goto foundtag; - } + } } #ifdef RAWDEBUG - raw_test_pass(0xeaa6); + raw_test_pass(0xeaa6); #endif goto nextloop; - foundtag: +foundtag: ; } } } - + /* Check flags */ - for(i=0;inumberofterms;i++) { + for(i=0; inumberofterms; i++) { int andmask=parameter->intarray[i*2]; int checkmask=parameter->intarray[i*2+1]; #ifdef RAWDEBUG @@ -1242,28 +1247,28 @@ void enqueueObject_I(void * vptr, struct parameterwrapper ** vqueues, int vlengt #endif if ((ptr->flag&andmask)==checkmask) { #ifdef RAWDEBUG - raw_test_pass(0xeaa8); + raw_test_pass(0xeaa8); #endif enqueuetasks_I(parameter, prevptr, ptr, NULL, 0); prevptr=parameter; break; } } - nextloop: - ; +nextloop: + ; } } } // helper function to compute the coordinates of a core from the core number void calCoords(int core_num, int* coordY, int* coordX) { - *coordX = core_num % 4; - *coordY = core_num / 4; + *coordX = core_num % 4; + *coordY = core_num / 4; } #endif /* Message format for RAW version: - * type + Msgbody + * type + Msgbody * type: 0 -- transfer object * 1 -- transfer stall msg * 2 -- lock request @@ -1281,171 +1286,171 @@ void calCoords(int core_num, int* coordY, int* coordX) { // transfer an object to targetcore // format: object void transferObject(struct transObjInfo * transObj) { - void * obj = transObj->objptr; - int type=((int *)obj)[0]; - int size=classsize[type]; - int targetcore = transObj->targetcore; - //assert(type < NUMCLASSES); // can only transfer normal object + void * obj = transObj->objptr; + int type=((int *)obj)[0]; + int size=classsize[type]; + int targetcore = transObj->targetcore; + //assert(type < NUMCLASSES); // can only transfer normal object #ifdef RAW - unsigned msgHdr; - int self_y, self_x, target_y, target_x; - //int isshared = 0; - // for 32 bit machine, the size of fixed part is always 3 words - //int msgsize = sizeof(int) * 2 + sizeof(void *); - int msgsize = 3 + transObj->length * 2; - int i = 0; - - struct ___Object___ * newobj = (struct ___Object___ *)obj; - /*if(0 == newobj->isolate) { - isshared = 1; - }*/ + unsigned msgHdr; + int self_y, self_x, target_y, target_x; + //int isshared = 0; + // for 32 bit machine, the size of fixed part is always 3 words + //int msgsize = sizeof(int) * 2 + sizeof(void *); + int msgsize = 3 + transObj->length * 2; + int i = 0; - calCoords(corenum, &self_y, &self_x); - calCoords(targetcore, &target_y, &target_x); - // Build the message header - msgHdr = construct_dyn_hdr(0, msgsize, 0, // msgsize word sent. - self_y, self_x, - target_y, target_x); - // start sending msg, set sand msg flag - isMsgSending = true; - gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). -#ifdef RAWDEBUG - raw_test_pass(0xbbbb); - raw_test_pass(0xb000 + targetcore); // targetcore -#endif - gdn_send(0); -#ifdef RAWDEBUG - raw_test_pass(0); -#endif - gdn_send(msgsize); + struct ___Object___ * newobj = (struct ___Object___ *)obj; + /*if(0 == newobj->isolate) { + isshared = 1; + }*/ + + calCoords(corenum, &self_y, &self_x); + calCoords(targetcore, &target_y, &target_x); + // Build the message header + msgHdr = construct_dyn_hdr(0, msgsize, 0, // msgsize word sent. + self_y, self_x, + target_y, target_x); + // start sending msg, set sand msg flag + isMsgSending = true; + gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). #ifdef RAWDEBUG - raw_test_pass_reg(msgsize); + raw_test_pass(0xbbbb); + raw_test_pass(0xb000 + targetcore); // targetcore #endif - gdn_send(obj); + gdn_send(0); #ifdef RAWDEBUG - raw_test_pass_reg(obj); + raw_test_pass(0); #endif - for(i = 0; i < transObj->length; ++i) { - int taskindex = transObj->queues[2*i]; - int paramindex = transObj->queues[2*i+1]; - gdn_send(taskindex); + gdn_send(msgsize); #ifdef RAWDEBUG - raw_test_pass_reg(taskindex); + raw_test_pass_reg(msgsize); #endif - gdn_send(paramindex); + gdn_send(obj); #ifdef RAWDEBUG - raw_test_pass_reg(paramindex); + raw_test_pass_reg(obj); #endif - } + for(i = 0; i < transObj->length; ++i) { + int taskindex = transObj->queues[2*i]; + int paramindex = transObj->queues[2*i+1]; + gdn_send(taskindex); #ifdef RAWDEBUG - raw_test_pass(0xffff); + raw_test_pass_reg(taskindex); #endif - ++(self_numsendobjs); - // end of sending this msg, set sand msg flag false - isMsgSending = false; - // check if there are pending msgs - while(isMsgHanging) { - // get the msg from outmsgdata[] - // length + target + msg - outmsgleft = outmsgdata[outmsgindex++]; - targetcore = outmsgdata[outmsgindex++]; - calCoords(targetcore, &target_y, &target_x); - // Build the message header - msgHdr = construct_dyn_hdr(0, outmsgleft, 0, // msgsize word sent. - self_y, self_x, - target_y, target_x); - isMsgSending = true; - gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). + gdn_send(paramindex); #ifdef RAWDEBUG - raw_test_pass(0xbbbb); - raw_test_pass(0xb000 + targetcore); // targetcore + raw_test_pass_reg(paramindex); #endif - while(outmsgleft-- > 0) { - gdn_send(outmsgdata[outmsgindex++]); + } #ifdef RAWDEBUG - raw_test_pass_reg(outmsgdata[outmsgindex - 1]); + raw_test_pass(0xffff); +#endif + ++(self_numsendobjs); + // end of sending this msg, set sand msg flag false + isMsgSending = false; + // check if there are pending msgs + while(isMsgHanging) { + // get the msg from outmsgdata[] + // length + target + msg + outmsgleft = outmsgdata[outmsgindex++]; + targetcore = outmsgdata[outmsgindex++]; + calCoords(targetcore, &target_y, &target_x); + // Build the message header + msgHdr = construct_dyn_hdr(0, outmsgleft, 0, // msgsize word sent. + self_y, self_x, + target_y, target_x); + isMsgSending = true; + gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). +#ifdef RAWDEBUG + raw_test_pass(0xbbbb); + raw_test_pass(0xb000 + targetcore); // targetcore +#endif + while(outmsgleft-- > 0) { + gdn_send(outmsgdata[outmsgindex++]); +#ifdef RAWDEBUG + raw_test_pass_reg(outmsgdata[outmsgindex - 1]); #endif - } + } #ifdef RAWDEBUG - raw_test_pass(0xffff); + raw_test_pass(0xffff); #endif - isMsgSending = false; + isMsgSending = false; #ifdef INTERRUPT - raw_user_interrupts_off(); -#endif - // check if there are still msg hanging - if(outmsgindex == outmsglast) { - // no more msgs - outmsgindex = outmsglast = 0; - isMsgHanging = false; - } + raw_user_interrupts_off(); +#endif + // check if there are still msg hanging + if(outmsgindex == outmsglast) { + // no more msgs + outmsgindex = outmsglast = 0; + isMsgHanging = false; + } #ifdef INTERRUPT - raw_user_interrupts_on(); + raw_user_interrupts_on(); #endif - } + } #elif defined THREADSIMULATE - int numofcore = pthread_getspecific(key); - - // use POSIX message queue to transfer objects between cores - mqd_t mqdnum; - char corenumstr[3]; - int sourcelen = 0; - if(targetcore < 10) { - corenumstr[0] = targetcore + '0'; - corenumstr[1] = '\0'; - sourcelen = 1; - } else if(targetcore < 100) { - corenumstr[1] = targetcore % 10 + '0'; - corenumstr[0] = (targetcore / 10) + '0'; - corenumstr[2] = '\0'; - sourcelen = 2; - } else { - printf("Error: targetcore >= 100\n"); - fflush(stdout); - exit(-1); - } - char * pathhead = "/msgqueue_"; - int targetlen = strlen(pathhead); - char path[targetlen + sourcelen + 1]; - strcpy(path, pathhead); - strncat(path, corenumstr, sourcelen); - int oflags = O_WRONLY|O_NONBLOCK; - int omodes = S_IRWXU|S_IRWXG|S_IRWXO; - mqdnum = mq_open(path, oflags, omodes, NULL); - if(mqdnum==-1) { - printf("[transferObject, %d] mq_open %s fail: %d, error: %s\n", numofcore, path, mqdnum, strerror(errno)); - fflush(stdout); - exit(-1); - } - /*struct ___Object___ * newobj = (struct ___Object___ *)obj; - if(0 == newobj->isolate) { - newobj = RUNMALLOC(size); - memcpy(newobj, obj, size); - newobj->original=obj; - }*/ - struct transObjInfo * tmptransObj = RUNMALLOC(sizeof(struct transObjInfo)); - memcpy(tmptransObj, transObj, sizeof(struct transObjInfo)); - int * tmpqueue = RUNMALLOC(sizeof(int)*2*tmptransObj->length); - memcpy(tmpqueue, tmptransObj->queues, sizeof(int)*2*tmptransObj->length); - tmptransObj->queues = tmpqueue; - struct ___Object___ * newobj = RUNMALLOC(sizeof(struct ___Object___)); - newobj->type = ((struct ___Object___ *)obj)->type; - newobj->original = (struct ___Object___ *)tmptransObj; - int ret; - do { - ret=mq_send(mqdnum, (void *)newobj, sizeof(struct ___Object___), 0); // send the object into the queue - if(ret != 0) { - printf("[transferObject, %d] mq_send to %s returned: %d, error: %s\n", numofcore, path, ret, strerror(errno)); - } - }while(ret!=0); - RUNFREE(newobj); - if(numofcore == STARTUPCORE) { - ++numsendobjs[numofcore]; - } else { - ++(thread_data_array[numofcore].numsendobjs); - } - printf("[transferObject, %d] mq_send to %s returned: $%x\n", numofcore, path, ret); + int numofcore = pthread_getspecific(key); + + // use POSIX message queue to transfer objects between cores + mqd_t mqdnum; + char corenumstr[3]; + int sourcelen = 0; + if(targetcore < 10) { + corenumstr[0] = targetcore + '0'; + corenumstr[1] = '\0'; + sourcelen = 1; + } else if(targetcore < 100) { + corenumstr[1] = targetcore % 10 + '0'; + corenumstr[0] = (targetcore / 10) + '0'; + corenumstr[2] = '\0'; + sourcelen = 2; + } else { + printf("Error: targetcore >= 100\n"); + fflush(stdout); + exit(-1); + } + char * pathhead = "/msgqueue_"; + int targetlen = strlen(pathhead); + char path[targetlen + sourcelen + 1]; + strcpy(path, pathhead); + strncat(path, corenumstr, sourcelen); + int oflags = O_WRONLY|O_NONBLOCK; + int omodes = S_IRWXU|S_IRWXG|S_IRWXO; + mqdnum = mq_open(path, oflags, omodes, NULL); + if(mqdnum==-1) { + printf("[transferObject, %d] mq_open %s fail: %d, error: %s\n", numofcore, path, mqdnum, strerror(errno)); + fflush(stdout); + exit(-1); + } + /*struct ___Object___ * newobj = (struct ___Object___ *)obj; + if(0 == newobj->isolate) { + newobj = RUNMALLOC(size); + memcpy(newobj, obj, size); + newobj->original=obj; + }*/ + struct transObjInfo * tmptransObj = RUNMALLOC(sizeof(struct transObjInfo)); + memcpy(tmptransObj, transObj, sizeof(struct transObjInfo)); + int * tmpqueue = RUNMALLOC(sizeof(int)*2*tmptransObj->length); + memcpy(tmpqueue, tmptransObj->queues, sizeof(int)*2*tmptransObj->length); + tmptransObj->queues = tmpqueue; + struct ___Object___ * newobj = RUNMALLOC(sizeof(struct ___Object___)); + newobj->type = ((struct ___Object___ *)obj)->type; + newobj->original = (struct ___Object___ *)tmptransObj; + int ret; + do { + ret=mq_send(mqdnum, (void *)newobj, sizeof(struct ___Object___), 0); // send the object into the queue + if(ret != 0) { + printf("[transferObject, %d] mq_send to %s returned: %d, error: %s\n", numofcore, path, ret, strerror(errno)); + } + } while(ret!=0); + RUNFREE(newobj); + if(numofcore == STARTUPCORE) { + ++numsendobjs[numofcore]; + } else { + ++(thread_data_array[numofcore].numsendobjs); + } + printf("[transferObject, %d] mq_send to %s returned: $%x\n", numofcore, path, ret); #endif } @@ -1453,138 +1458,138 @@ void transferObject(struct transObjInfo * transObj) { // format: -1 bool transStallMsg(int targetcore) { #ifdef RAW - unsigned msgHdr; - int self_y, self_x, target_y, target_x; - // for 32 bit machine, the size is always 4 words - //int msgsize = sizeof(int) * 4; - int msgsize = 4; + unsigned msgHdr; + int self_y, self_x, target_y, target_x; + // for 32 bit machine, the size is always 4 words + //int msgsize = sizeof(int) * 4; + int msgsize = 4; - calCoords(corenum, &self_y, &self_x); - calCoords(targetcore, &target_y, &target_x); - // Build the message header - msgHdr = construct_dyn_hdr(0, msgsize, 0, // msgsize word sent. - self_y, self_x, - target_y, target_x); - // start sending msgs, set msg sending flag - isMsgSending = true; - gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). + calCoords(corenum, &self_y, &self_x); + calCoords(targetcore, &target_y, &target_x); + // Build the message header + msgHdr = construct_dyn_hdr(0, msgsize, 0, // msgsize word sent. + self_y, self_x, + target_y, target_x); + // start sending msgs, set msg sending flag + isMsgSending = true; + gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). #ifdef RAWDEBUG - raw_test_pass(0xbbbb); - raw_test_pass(0xb000 + targetcore); // targetcore + raw_test_pass(0xbbbb); + raw_test_pass(0xb000 + targetcore); // targetcore #endif - gdn_send(1); + gdn_send(1); #ifdef RAWDEBUG - raw_test_pass(1); + raw_test_pass(1); #endif - gdn_send(corenum); + gdn_send(corenum); #ifdef RAWDEBUG - raw_test_pass_reg(corenum); + raw_test_pass_reg(corenum); #endif - gdn_send(self_numsendobjs); + gdn_send(self_numsendobjs); #ifdef RAWDEBUG - raw_test_pass_reg(self_numsendobjs); + raw_test_pass_reg(self_numsendobjs); #endif - gdn_send(self_numreceiveobjs); + gdn_send(self_numreceiveobjs); #ifdef RAWDEBUG - raw_test_pass_reg(self_numreceiveobjs); - raw_test_pass(0xffff); + raw_test_pass_reg(self_numreceiveobjs); + raw_test_pass(0xffff); #endif - // end of sending this msg, set sand msg flag false - isMsgSending = false; - // check if there are pending msgs - while(isMsgHanging) { - // get the msg from outmsgdata[] - // length + target + msg - outmsgleft = outmsgdata[outmsgindex++]; - targetcore = outmsgdata[outmsgindex++]; - calCoords(targetcore, &target_y, &target_x); - // Build the message header - msgHdr = construct_dyn_hdr(0, outmsgleft, 0, // msgsize word sent. - self_y, self_x, - target_y, target_x); - isMsgSending = true; - gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). + // end of sending this msg, set sand msg flag false + isMsgSending = false; + // check if there are pending msgs + while(isMsgHanging) { + // get the msg from outmsgdata[] + // length + target + msg + outmsgleft = outmsgdata[outmsgindex++]; + targetcore = outmsgdata[outmsgindex++]; + calCoords(targetcore, &target_y, &target_x); + // Build the message header + msgHdr = construct_dyn_hdr(0, outmsgleft, 0, // msgsize word sent. + self_y, self_x, + target_y, target_x); + isMsgSending = true; + gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). #ifdef RAWDEBUG - raw_test_pass(0xbbbb); - raw_test_pass(0xb000 + targetcore); // targetcore + raw_test_pass(0xbbbb); + raw_test_pass(0xb000 + targetcore); // targetcore #endif - while(outmsgleft-- > 0) { - gdn_send(outmsgdata[outmsgindex++]); + while(outmsgleft-- > 0) { + gdn_send(outmsgdata[outmsgindex++]); #ifdef RAWDEBUG - raw_test_pass_reg(outmsgdata[outmsgindex - 1]); + raw_test_pass_reg(outmsgdata[outmsgindex - 1]); #endif - } + } #ifdef RAWDEBUG - raw_test_pass(0xffff); + raw_test_pass(0xffff); #endif - isMsgSending = false; + isMsgSending = false; #ifdef INTERRUPT - raw_user_interrupts_off(); -#endif - // check if there are still msg hanging - if(outmsgindex == outmsglast) { - // no more msgs - outmsgindex = outmsglast = 0; - isMsgHanging = false; - } + raw_user_interrupts_off(); +#endif + // check if there are still msg hanging + if(outmsgindex == outmsglast) { + // no more msgs + outmsgindex = outmsglast = 0; + isMsgHanging = false; + } #ifdef INTERRUPT - raw_user_interrupts_on(); + raw_user_interrupts_on(); #endif - } - return true; + } + return true; #elif defined THREADSIMULATE - struct ___Object___ *newobj = RUNMALLOC(sizeof(struct ___Object___)); - // use the first four int field to hold msgtype/corenum/sendobj/receiveobj - newobj->type = -1; - int numofcore = pthread_getspecific(key); - newobj->flag = numofcore; - newobj->___cachedHash___ = thread_data_array[numofcore].numsendobjs; - newobj->___cachedCode___ = thread_data_array[numofcore].numreceiveobjs; - - // use POSIX message queue to send stall msg to startup core - assert(targetcore == STARTUPCORE); - mqd_t mqdnum; - char corenumstr[3]; - int sourcelen = 0; - if(targetcore < 10) { - corenumstr[0] = targetcore + '0'; - corenumstr[1] = '\0'; - sourcelen = 1; - } else if(targetcore < 100) { - corenumstr[1] = targetcore % 10 + '0'; - corenumstr[0] = (targetcore / 10) + '0'; - corenumstr[2] = '\0'; - sourcelen = 2; - } else { - printf("Error: targetcore >= 100\n"); - fflush(stdout); - exit(-1); - } - char * pathhead = "/msgqueue_"; - int targetlen = strlen(pathhead); - char path[targetlen + sourcelen + 1]; - strcpy(path, pathhead); - strncat(path, corenumstr, sourcelen); - int oflags = O_WRONLY|O_NONBLOCK; - int omodes = S_IRWXU|S_IRWXG|S_IRWXO; - mqdnum = mq_open(path, oflags, omodes, NULL); - if(mqdnum==-1) { - printf("[transStallMsg, %d] mq_open %s fail: %d, error: %s\n", numofcore, path, mqdnum, strerror(errno)); - fflush(stdout); - exit(-1); - } - int ret; - ret=mq_send(mqdnum, (void *)newobj, sizeof(struct ___Object___), 0); // send the object into the queue - if(ret != 0) { - printf("[transStallMsg, %d] mq_send to %s returned: %d, error: %s\n", numofcore, path, ret, strerror(errno)); - RUNFREE(newobj); - return false; - } else { - printf("[transStallMsg, %d] mq_send to %s returned: $%x\n", numofcore, path, ret); - printf(" to %s index: %d, sendobjs: %d, receiveobjs: %d\n", path, newobj->flag, newobj->___cachedHash___, newobj->___cachedCode___); - RUNFREE(newobj); - return true; - } + struct ___Object___ *newobj = RUNMALLOC(sizeof(struct ___Object___)); + // use the first four int field to hold msgtype/corenum/sendobj/receiveobj + newobj->type = -1; + int numofcore = pthread_getspecific(key); + newobj->flag = numofcore; + newobj->___cachedHash___ = thread_data_array[numofcore].numsendobjs; + newobj->___cachedCode___ = thread_data_array[numofcore].numreceiveobjs; + + // use POSIX message queue to send stall msg to startup core + assert(targetcore == STARTUPCORE); + mqd_t mqdnum; + char corenumstr[3]; + int sourcelen = 0; + if(targetcore < 10) { + corenumstr[0] = targetcore + '0'; + corenumstr[1] = '\0'; + sourcelen = 1; + } else if(targetcore < 100) { + corenumstr[1] = targetcore % 10 + '0'; + corenumstr[0] = (targetcore / 10) + '0'; + corenumstr[2] = '\0'; + sourcelen = 2; + } else { + printf("Error: targetcore >= 100\n"); + fflush(stdout); + exit(-1); + } + char * pathhead = "/msgqueue_"; + int targetlen = strlen(pathhead); + char path[targetlen + sourcelen + 1]; + strcpy(path, pathhead); + strncat(path, corenumstr, sourcelen); + int oflags = O_WRONLY|O_NONBLOCK; + int omodes = S_IRWXU|S_IRWXG|S_IRWXO; + mqdnum = mq_open(path, oflags, omodes, NULL); + if(mqdnum==-1) { + printf("[transStallMsg, %d] mq_open %s fail: %d, error: %s\n", numofcore, path, mqdnum, strerror(errno)); + fflush(stdout); + exit(-1); + } + int ret; + ret=mq_send(mqdnum, (void *)newobj, sizeof(struct ___Object___), 0); // send the object into the queue + if(ret != 0) { + printf("[transStallMsg, %d] mq_send to %s returned: %d, error: %s\n", numofcore, path, ret, strerror(errno)); + RUNFREE(newobj); + return false; + } else { + printf("[transStallMsg, %d] mq_send to %s returned: $%x\n", numofcore, path, ret); + printf(" to %s index: %d, sendobjs: %d, receiveobjs: %d\n", path, newobj->flag, newobj->___cachedHash___, newobj->___cachedCode___); + RUNFREE(newobj); + return true; + } #endif } @@ -1603,856 +1608,863 @@ bool transStallMsg(int targetcore) { // otherwise -- received msg type int receiveObject() { #ifdef RAW - bool deny = false; - unsigned msgHdr; - int self_y, self_x, target_y, target_x; - int targetcore = 0; - if(gdn_input_avail() == 0) { + bool deny = false; + unsigned msgHdr; + int self_y, self_x, target_y, target_x; + int targetcore = 0; + if(gdn_input_avail() == 0) { +#ifdef RAWDEBUG + if(corenum < NUMCORES) { + raw_test_pass(0xd001); + } +#endif + return -1; + } +msg: +#ifdef RAWDEBUG + raw_test_pass(0xcccc); +#endif + while((gdn_input_avail() != 0) && (msgdataindex < msglength)) { + msgdata[msgdataindex] = gdn_receive(); + if(msgdataindex == 0) { + if(msgdata[0] > 2) { + msglength = 3; + } else if(msgdata[0] > 0) { + msglength = 4; + } + } else if((msgdataindex == 1) && (msgdata[0] == 0)) { + msglength = msgdata[msgdataindex]; + } +#ifdef RAWDEBUG + raw_test_pass_reg(msgdata[msgdataindex]); +#endif + msgdataindex++; + + /*if(msgdataindex == 0) { + // type + msgtype = gdn_receive(); + if(msgtype > 2) { + msglength = 3; + } else { + msglength = 4; + } + if(msgtype != 0) { + msgdata = (int *)RUNMALLOC_I(msglength * sizeof(int)); + msgdata[msgdataindex] = msgtype; + } + #ifdef RAWDEBUG + raw_test_pass_reg(msgtype); + #endif + } else if((msgdataindex == 1) && (msgtype == 0)) { + // object transfer msg + msglength = gdn_receive(); + msgdata = (int *)RUNMALLOC_I(msglength * sizeof(int)); + msgdata[0] = msgtype; + msgdata[msgdataindex] = msglength; + #ifdef RAWDEBUG + raw_test_pass_reg(msgdata[msgdataindex]); + #endif + } else { + msgdata[msgdataindex] = gdn_receive(); + #ifdef RAWDEBUG + raw_test_pass_reg(msgdata[msgdataindex]); + #endif + } + msgdataindex++;*/ + } +#ifdef RAWDEBUG + raw_test_pass(0xffff); +#endif + if(msgdataindex == msglength) { + // received a whole msg + int type, data1, data2; // will receive at least 3 words including type + type = msgdata[0]; + data1 = msgdata[1]; + data2 = msgdata[2]; + switch(type) { + case 0: { + // receive a object transfer msg + struct transObjInfo * transObj = RUNMALLOC_I(sizeof(struct transObjInfo)); + int k = 0; + if(corenum > NUMCORES - 1) { + raw_test_done(0xa00a); + } + // store the object and its corresponding queue info, enqueue it later + transObj->objptr = (void *)data2; // data1 is now size of the msg + transObj->length = (msglength - 3) / 2; + transObj->queues = RUNMALLOC_I(sizeof(int)*(msglength - 3)); + for(k = 0; k < transObj->length; ++k) { + transObj->queues[2*k] = msgdata[3+2*k]; +#ifdef RAWDEBUG + raw_test_pass_reg(transObj->queues[2*k]); +#endif + transObj->queues[2*k+1] = msgdata[3+2*k+1]; #ifdef RAWDEBUG - if(corenum < NUMCORES) { - raw_test_pass(0xd001); - } + raw_test_pass_reg(transObj->queues[2*k+1]); #endif - return -1; + } + // check if there is an existing duplicate item + { + struct QueueItem * qitem = getTail(&objqueue); + struct QueueItem * prev = NULL; + while(qitem != NULL) { + struct transObjInfo * tmpinfo = (struct transObjInfo *)(qitem->objectptr); + if(tmpinfo->objptr == transObj->objptr) { + // the same object, remove outdate one + removeItem(&objqueue, qitem); + } else { + prev = qitem; + } + if(prev == NULL) { + qitem = getTail(&objqueue); + } else { + qitem = getNext(prev); + } } -msg: + //memcpy(transObj->queues, msgdata[3], sizeof(int)*(msglength - 3)); + addNewItem_I(&objqueue, (void *)transObj); + } + ++(self_numreceiveobjs); +#ifdef RAWDEBUG + raw_test_pass(0xe881); +#endif + /* + addNewItem_I(&objqueue, (void *)data2); + ++(self_numreceiveobjs); + #ifdef RAWDEBUG + raw_test_pass(0xe881); + #endif + */ + break; + } + + case 1: { + // receive a stall msg + if(corenum != STARTUPCORE) { + // non startup core can not receive stall msg + // return -1 + raw_test_done(0xa001); + } + if(data1 < NUMCORES) { +#ifdef RAWDEBUG + raw_test_pass(0xe882); +#endif + corestatus[data1] = 0; + numsendobjs[data1] = data2; + numreceiveobjs[data1] = msgdata[3]; + } + break; + } + + case 2: { + // receive lock request msg + // for 32 bit machine, the size is always 3 words + //int msgsize = sizeof(int) * 3; + int msgsize = 3; + // lock request msg, handle it right now + // check to see if there is a lock exist in locktbl for the required obj + int data3 = msgdata[3]; + deny = false; + if(!RuntimeHashcontainskey(locktbl, data2)) { + // no locks for this object + // first time to operate on this shared object + // create a lock for it + // the lock is an integer: 0 -- stall, >0 -- read lock, -1 -- write lock +#ifdef RAWDEBUG + raw_test_pass(0xe883); +#endif + if(data1 == 0) { + RuntimeHashadd_I(locktbl, data2, 1); + } else { + RuntimeHashadd_I(locktbl, data2, -1); + } + } else { + int rwlock_obj = 0; +#ifdef RAWDEBUG + raw_test_pass(0xe884); +#endif + RuntimeHashget(locktbl, data2, &rwlock_obj); +#ifdef RAWDEBUG + raw_test_pass_reg(rwlock_obj); +#endif + if(0 == rwlock_obj) { + if(data1 == 0) { + rwlock_obj = 1; + } else { + rwlock_obj = -1; + } + RuntimeHashremovekey(locktbl, data2); + RuntimeHashadd_I(locktbl, data2, rwlock_obj); + } else if((rwlock_obj > 0) && (data1 == 0)) { + // read lock request and there are only read locks + rwlock_obj++; + RuntimeHashremovekey(locktbl, data2); + RuntimeHashadd_I(locktbl, data2, rwlock_obj); + } else { + deny = true; + } +#ifdef RAWDEBUG + raw_test_pass_reg(rwlock_obj); +#endif + } + targetcore = data3; + // check if there is still some msg on sending + if(isMsgSending) { +#ifdef RAWDEBUG + raw_test_pass(0xe885); +#endif + isMsgHanging = true; + // cache the msg in outmsgdata and send it later + // msglength + target core + msg + outmsgdata[outmsglast++] = msgsize; + outmsgdata[outmsglast++] = targetcore; + if(deny == true) { + outmsgdata[outmsglast++] = 4; + } else { + outmsgdata[outmsglast++] = 3; + } + outmsgdata[outmsglast++] = data1; + outmsgdata[outmsglast++] = data2; + } else { +#ifdef RAWDEBUG + raw_test_pass(0xe886); +#endif + // no msg on sending, send it out + calCoords(corenum, &self_y, &self_x); + calCoords(targetcore, &target_y, &target_x); + // Build the message header + msgHdr = construct_dyn_hdr(0, msgsize, 0, // msgsize word sent. + self_y, self_x, + target_y, target_x); + gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). +#ifdef RAWDEBUG + raw_test_pass(0xbbbb); + raw_test_pass(0xb000 + targetcore); // targetcore +#endif + if(deny == true) { + // deny the lock request + gdn_send(4); // lock request +#ifdef RAWDEBUG + raw_test_pass(4); +#endif + } else { + // grount the lock request + gdn_send(3); // lock request #ifdef RAWDEBUG - raw_test_pass(0xcccc); -#endif - while((gdn_input_avail() != 0) && (msgdataindex < msglength)) { - msgdata[msgdataindex] = gdn_receive(); - if(msgdataindex == 0) { - if(msgdata[0] > 2) { - msglength = 3; - } else if(msgdata[0] > 0) { - msglength = 4; - } - } else if((msgdataindex == 1) && (msgdata[0] == 0)) { - msglength = msgdata[msgdataindex]; - } -#ifdef RAWDEBUG - raw_test_pass_reg(msgdata[msgdataindex]); -#endif - msgdataindex++; - - /*if(msgdataindex == 0) { - // type - msgtype = gdn_receive(); - if(msgtype > 2) { - msglength = 3; - } else { - msglength = 4; - } - if(msgtype != 0) { - msgdata = (int *)RUNMALLOC_I(msglength * sizeof(int)); - msgdata[msgdataindex] = msgtype; - } -#ifdef RAWDEBUG - raw_test_pass_reg(msgtype); -#endif - } else if((msgdataindex == 1) && (msgtype == 0)) { - // object transfer msg - msglength = gdn_receive(); - msgdata = (int *)RUNMALLOC_I(msglength * sizeof(int)); - msgdata[0] = msgtype; - msgdata[msgdataindex] = msglength; -#ifdef RAWDEBUG - raw_test_pass_reg(msgdata[msgdataindex]); -#endif - } else { - msgdata[msgdataindex] = gdn_receive(); -#ifdef RAWDEBUG - raw_test_pass_reg(msgdata[msgdataindex]); -#endif - } - msgdataindex++;*/ + raw_test_pass(3); +#endif } + gdn_send(data1); // lock type +#ifdef RAWDEBUG + raw_test_pass_reg(data1); +#endif + gdn_send(data2); // lock target #ifdef RAWDEBUG + raw_test_pass_reg(data2); raw_test_pass(0xffff); #endif - if(msgdataindex == msglength) { - // received a whole msg - int type, data1, data2; // will receive at least 3 words including type - type = msgdata[0]; - data1 = msgdata[1]; - data2 = msgdata[2]; - switch(type) { - case 0: { - // receive a object transfer msg - struct transObjInfo * transObj = RUNMALLOC_I(sizeof(struct transObjInfo)); - int k = 0; - if(corenum > NUMCORES - 1) { - raw_test_done(0xa00a); - } - // store the object and its corresponding queue info, enqueue it later - transObj->objptr = (void *)data2; // data1 is now size of the msg - transObj->length = (msglength - 3) / 2; - transObj->queues = RUNMALLOC_I(sizeof(int)*(msglength - 3)); - for(k = 0; k < transObj->length; ++k) { - transObj->queues[2*k] = msgdata[3+2*k]; -#ifdef RAWDEBUG - raw_test_pass_reg(transObj->queues[2*k]); -#endif - transObj->queues[2*k+1] = msgdata[3+2*k+1]; -#ifdef RAWDEBUG - raw_test_pass_reg(transObj->queues[2*k+1]); -#endif - } - // check if there is an existing duplicate item - { - struct QueueItem * qitem = getTail(&objqueue); - struct QueueItem * prev = NULL; - while(qitem != NULL) { - struct transObjInfo * tmpinfo = (struct transObjInfo *)(qitem->objectptr); - if(tmpinfo->objptr == transObj->objptr) { - // the same object, remove outdate one - removeItem(&objqueue, qitem); - } else { - prev = qitem; - } - if(prev == NULL) { - qitem = getTail(&objqueue); - } else { - qitem = getNext(prev); - } - } - //memcpy(transObj->queues, msgdata[3], sizeof(int)*(msglength - 3)); - addNewItem_I(&objqueue, (void *)transObj); - } - ++(self_numreceiveobjs); -#ifdef RAWDEBUG - raw_test_pass(0xe881); -#endif - /* - addNewItem_I(&objqueue, (void *)data2); - ++(self_numreceiveobjs); -#ifdef RAWDEBUG - raw_test_pass(0xe881); -#endif - */ - break; - } - case 1: { - // receive a stall msg - if(corenum != STARTUPCORE) { - // non startup core can not receive stall msg - // return -1 - raw_test_done(0xa001); - } - if(data1 < NUMCORES) { -#ifdef RAWDEBUG - raw_test_pass(0xe882); -#endif - corestatus[data1] = 0; - numsendobjs[data1] = data2; - numreceiveobjs[data1] = msgdata[3]; - } - break; - } - case 2: { - // receive lock request msg - // for 32 bit machine, the size is always 3 words - //int msgsize = sizeof(int) * 3; - int msgsize = 3; - // lock request msg, handle it right now - // check to see if there is a lock exist in locktbl for the required obj - int data3 = msgdata[3]; - deny = false; - if(!RuntimeHashcontainskey(locktbl, data2)) { - // no locks for this object - // first time to operate on this shared object - // create a lock for it - // the lock is an integer: 0 -- stall, >0 -- read lock, -1 -- write lock -#ifdef RAWDEBUG - raw_test_pass(0xe883); -#endif - if(data1 == 0) { - RuntimeHashadd_I(locktbl, data2, 1); - } else { - RuntimeHashadd_I(locktbl, data2, -1); - } - } else { - int rwlock_obj = 0; -#ifdef RAWDEBUG - raw_test_pass(0xe884); -#endif - RuntimeHashget(locktbl, data2, &rwlock_obj); -#ifdef RAWDEBUG - raw_test_pass_reg(rwlock_obj); -#endif - if(0 == rwlock_obj) { - if(data1 == 0) { - rwlock_obj = 1; - } else { - rwlock_obj = -1; - } - RuntimeHashremovekey(locktbl, data2); - RuntimeHashadd_I(locktbl, data2, rwlock_obj); - } else if((rwlock_obj > 0) && (data1 == 0)) { - // read lock request and there are only read locks - rwlock_obj++; - RuntimeHashremovekey(locktbl, data2); - RuntimeHashadd_I(locktbl, data2, rwlock_obj); - } else { - deny = true; - } -#ifdef RAWDEBUG - raw_test_pass_reg(rwlock_obj); -#endif - } - targetcore = data3; - // check if there is still some msg on sending - if(isMsgSending) { -#ifdef RAWDEBUG - raw_test_pass(0xe885); -#endif - isMsgHanging = true; - // cache the msg in outmsgdata and send it later - // msglength + target core + msg - outmsgdata[outmsglast++] = msgsize; - outmsgdata[outmsglast++] = targetcore; - if(deny == true) { - outmsgdata[outmsglast++] = 4; - } else { - outmsgdata[outmsglast++] = 3; - } - outmsgdata[outmsglast++] = data1; - outmsgdata[outmsglast++] = data2; - } else { -#ifdef RAWDEBUG - raw_test_pass(0xe886); -#endif - // no msg on sending, send it out - calCoords(corenum, &self_y, &self_x); - calCoords(targetcore, &target_y, &target_x); - // Build the message header - msgHdr = construct_dyn_hdr(0, msgsize, 0, // msgsize word sent. - self_y, self_x, - target_y, target_x); - gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). -#ifdef RAWDEBUG - raw_test_pass(0xbbbb); - raw_test_pass(0xb000 + targetcore); // targetcore -#endif - if(deny == true) { - // deny the lock request - gdn_send(4); // lock request -#ifdef RAWDEBUG - raw_test_pass(4); -#endif - } else { - // grount the lock request - gdn_send(3); // lock request -#ifdef RAWDEBUG - raw_test_pass(3); -#endif - } - gdn_send(data1); // lock type -#ifdef RAWDEBUG - raw_test_pass_reg(data1); -#endif - gdn_send(data2); // lock target -#ifdef RAWDEBUG - raw_test_pass_reg(data2); - raw_test_pass(0xffff); -#endif - } - break; - } - case 3: { - // receive lock grount msg - if(corenum > NUMCORES - 1) { - raw_test_done(0xa00b); - } - if(lockobj == data2) { - lockresult = 1; - lockflag = true; + } + break; + } + + case 3: { + // receive lock grount msg + if(corenum > NUMCORES - 1) { + raw_test_done(0xa00b); + } + if(lockobj == data2) { + lockresult = 1; + lockflag = true; #ifndef INTERRUPT - reside = false; -#endif - } else { - // conflicts on lockresults - raw_test_done(0xa002); - } - break; - } - case 4: { - // receive lock grount/deny msg - if(corenum > NUMCORES - 1) { - raw_test_done(0xa00c); - } - if(lockobj == data2) { - lockresult = 0; - lockflag = true; + reside = false; +#endif + } else { + // conflicts on lockresults + raw_test_done(0xa002); + } + break; + } + + case 4: { + // receive lock grount/deny msg + if(corenum > NUMCORES - 1) { + raw_test_done(0xa00c); + } + if(lockobj == data2) { + lockresult = 0; + lockflag = true; #ifndef INTERRUPT - reside = false; -#endif - } else { - // conflicts on lockresults - raw_test_done(0xa003); - } - break; - } - case 5: { - // receive lock release msg - if(!RuntimeHashcontainskey(locktbl, data2)) { - // no locks for this object, something is wrong - raw_test_done(0xa004); - } else { - int rwlock_obj = 0; - RuntimeHashget(locktbl, data2, &rwlock_obj); -#ifdef RAWDEBUG - raw_test_pass(0xe887); - raw_test_pass_reg(rwlock_obj); -#endif - if(data1 == 0) { - rwlock_obj--; - } else { - rwlock_obj++; - } - RuntimeHashremovekey(locktbl, data2); - RuntimeHashadd_I(locktbl, data2, rwlock_obj); -#ifdef RAWDEBUG - raw_test_pass_reg(rwlock_obj); -#endif - } - break; - } - default: - break; - } - //RUNFREE(msgdata); - //msgdata = NULL; - for(msgdataindex--;msgdataindex > 0; --msgdataindex) { - msgdata[msgdataindex] = -1; - } - msgtype = -1; - //msgdataindex = 0; - msglength = 30; -#ifdef RAWDEBUG - raw_test_pass(0xe888); -#endif - if(gdn_input_avail() != 0) { - goto msg; - } - return type; - } else { - // not a whole msg + reside = false; +#endif + } else { + // conflicts on lockresults + raw_test_done(0xa003); + } + break; + } + + case 5: { + // receive lock release msg + if(!RuntimeHashcontainskey(locktbl, data2)) { + // no locks for this object, something is wrong + raw_test_done(0xa004); + } else { + int rwlock_obj = 0; + RuntimeHashget(locktbl, data2, &rwlock_obj); #ifdef RAWDEBUG - raw_test_pass(0xe889); + raw_test_pass(0xe887); + raw_test_pass_reg(rwlock_obj); #endif - return -2; + if(data1 == 0) { + rwlock_obj--; + } else { + rwlock_obj++; } + RuntimeHashremovekey(locktbl, data2); + RuntimeHashadd_I(locktbl, data2, rwlock_obj); +#ifdef RAWDEBUG + raw_test_pass_reg(rwlock_obj); +#endif + } + break; + } + + default: + break; + } + //RUNFREE(msgdata); + //msgdata = NULL; + for(msgdataindex--; msgdataindex > 0; --msgdataindex) { + msgdata[msgdataindex] = -1; + } + msgtype = -1; + //msgdataindex = 0; + msglength = 30; +#ifdef RAWDEBUG + raw_test_pass(0xe888); +#endif + if(gdn_input_avail() != 0) { + goto msg; + } + return type; + } else { + // not a whole msg +#ifdef RAWDEBUG + raw_test_pass(0xe889); +#endif + return -2; + } #elif defined THREADSIMULATE - int numofcore = pthread_getspecific(key); - // use POSIX message queue to transfer object - int msglen = 0; - struct mq_attr mqattr; - mq_getattr(mqd[numofcore], &mqattr); - void * msgptr =RUNMALLOC(mqattr.mq_msgsize); - msglen=mq_receive(mqd[numofcore], msgptr, mqattr.mq_msgsize, NULL); // receive the object into the queue - if(-1 == msglen) { - // no msg - free(msgptr); - return 1; - } - //printf("msg: %s\n",msgptr); - if(((int*)msgptr)[0] == -1) { - // StallMsg - struct ___Object___ * tmpptr = (struct ___Object___ *)msgptr; - int index = tmpptr->flag; - corestatus[index] = 0; - numsendobjs[index] = tmpptr->___cachedHash___; - numreceiveobjs[index] = tmpptr->___cachedCode___; - printf(" index: %d, sendobjs: %d, reveiveobjs: %d\n", index, numsendobjs[index], numreceiveobjs[index]); - free(msgptr); - return 2; - } /*else if(((int*)msgptr)[0] == -2) { - // terminate msg - return 3; - } */else { - // an object - if(numofcore == STARTUPCORE) { - ++(numreceiveobjs[numofcore]); - } else { - ++(thread_data_array[numofcore].numreceiveobjs); - } - struct ___Object___ * tmpptr = (struct ___Object___ *)msgptr; - struct transObjInfo * transObj = (struct transObjInfo *)tmpptr->original; - tmpptr = (struct ___Object___ *)(transObj->objptr); - int type = tmpptr->type; - int size=classsize[type]; - struct ___Object___ * newobj=RUNMALLOC(size); - memcpy(newobj, tmpptr, size); - if(0 == newobj->isolate) { - newobj->original=tmpptr; - } - RUNFREE(msgptr); - tmpptr = NULL; - int k = 0; - for(k = 0; k < transObj->length; ++k) { - int taskindex = transObj->queues[2 * k]; - int paramindex = transObj->queues[2 * k + 1]; - struct parameterwrapper ** queues = &(paramqueues[numofcore][taskindex][paramindex]); - enqueueObject(newobj, queues, 1); - } - RUNFREE(transObj->queues); - RUNFREE(transObj); - return 0; - } + int numofcore = pthread_getspecific(key); + // use POSIX message queue to transfer object + int msglen = 0; + struct mq_attr mqattr; + mq_getattr(mqd[numofcore], &mqattr); + void * msgptr =RUNMALLOC(mqattr.mq_msgsize); + msglen=mq_receive(mqd[numofcore], msgptr, mqattr.mq_msgsize, NULL); // receive the object into the queue + if(-1 == msglen) { + // no msg + free(msgptr); + return 1; + } + //printf("msg: %s\n",msgptr); + if(((int*)msgptr)[0] == -1) { + // StallMsg + struct ___Object___ * tmpptr = (struct ___Object___ *)msgptr; + int index = tmpptr->flag; + corestatus[index] = 0; + numsendobjs[index] = tmpptr->___cachedHash___; + numreceiveobjs[index] = tmpptr->___cachedCode___; + printf(" index: %d, sendobjs: %d, reveiveobjs: %d\n", index, numsendobjs[index], numreceiveobjs[index]); + free(msgptr); + return 2; + } /*else if(((int*)msgptr)[0] == -2) { + // terminate msg + return 3; + } */ + else { + // an object + if(numofcore == STARTUPCORE) { + ++(numreceiveobjs[numofcore]); + } else { + ++(thread_data_array[numofcore].numreceiveobjs); + } + struct ___Object___ * tmpptr = (struct ___Object___ *)msgptr; + struct transObjInfo * transObj = (struct transObjInfo *)tmpptr->original; + tmpptr = (struct ___Object___ *)(transObj->objptr); + int type = tmpptr->type; + int size=classsize[type]; + struct ___Object___ * newobj=RUNMALLOC(size); + memcpy(newobj, tmpptr, size); + if(0 == newobj->isolate) { + newobj->original=tmpptr; + } + RUNFREE(msgptr); + tmpptr = NULL; + int k = 0; + for(k = 0; k < transObj->length; ++k) { + int taskindex = transObj->queues[2 * k]; + int paramindex = transObj->queues[2 * k + 1]; + struct parameterwrapper ** queues = &(paramqueues[numofcore][taskindex][paramindex]); + enqueueObject(newobj, queues, 1); + } + RUNFREE(transObj->queues); + RUNFREE(transObj); + return 0; + } #endif } bool getreadlock(void * ptr) { #ifdef RAW - unsigned msgHdr; - int self_y, self_x, target_y, target_x; - int targetcore = 0; //((int)ptr >> 5) % TOTALCORE; - // for 32 bit machine, the size is always 4 words - //int msgsize = sizeof(int) * 4; - int msgsize = 4; - int tc = TOTALCORE; + unsigned msgHdr; + int self_y, self_x, target_y, target_x; + int targetcore = 0; //((int)ptr >> 5) % TOTALCORE; + // for 32 bit machine, the size is always 4 words + //int msgsize = sizeof(int) * 4; + int msgsize = 4; + int tc = TOTALCORE; #ifdef INTERRUPT - raw_user_interrupts_off(); + raw_user_interrupts_off(); #endif - targetcore = ((int)ptr >> 5) % tc; + targetcore = ((int)ptr >> 5) % tc; #ifdef INTERRUPT - raw_user_interrupts_on(); + raw_user_interrupts_on(); #endif - lockobj = (int)ptr; - lockflag = false; + lockobj = (int)ptr; + lockflag = false; #ifndef INTERRUPT - reside = false; + reside = false; #endif - lockresult = 0; + lockresult = 0; - if(targetcore == corenum) { - // reside on this core - bool deny = false; + if(targetcore == corenum) { + // reside on this core + bool deny = false; #ifdef INTERRUPT - raw_user_interrupts_off(); -#endif - if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { - // no locks for this object - // first time to operate on this shared object - // create a lock for it - // the lock is an integer: 0 -- stall, >0 -- read lock, -1 -- write lock - RuntimeHashadd_I(locktbl, (int)ptr, 1); - } else { - int rwlock_obj = 0; - RuntimeHashget(locktbl, (int)ptr, &rwlock_obj); - if(-1 != rwlock_obj) { - rwlock_obj++; - RuntimeHashremovekey(locktbl, (int)ptr); - RuntimeHashadd_I(locktbl, (int)ptr, rwlock_obj); - } else { - deny = true; - } - } + raw_user_interrupts_off(); +#endif + if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { + // no locks for this object + // first time to operate on this shared object + // create a lock for it + // the lock is an integer: 0 -- stall, >0 -- read lock, -1 -- write lock + RuntimeHashadd_I(locktbl, (int)ptr, 1); + } else { + int rwlock_obj = 0; + RuntimeHashget(locktbl, (int)ptr, &rwlock_obj); + if(-1 != rwlock_obj) { + rwlock_obj++; + RuntimeHashremovekey(locktbl, (int)ptr); + RuntimeHashadd_I(locktbl, (int)ptr, rwlock_obj); + } else { + deny = true; + } + } #ifdef INTERRUPT - raw_user_interrupts_on(); -#endif - if(lockobj == (int)ptr) { - if(deny) { - lockresult = 0; - } else { - lockresult = 1; - } - lockflag = true; + raw_user_interrupts_on(); +#endif + if(lockobj == (int)ptr) { + if(deny) { + lockresult = 0; + } else { + lockresult = 1; + } + lockflag = true; #ifndef INTERRUPT - reside = true; + reside = true; #endif - } else { - // conflicts on lockresults - raw_test_done(0xa005); - } - return true; - } + } else { + // conflicts on lockresults + raw_test_done(0xa005); + } + return true; + } - calCoords(corenum, &self_y, &self_x); - calCoords(targetcore, &target_y, &target_x); - // Build the message header - msgHdr = construct_dyn_hdr(0, msgsize, 0, // msgsize word sent. - self_y, self_x, - target_y, target_x); - // start sending the msg, set send msg flag - isMsgSending = true; - gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). + calCoords(corenum, &self_y, &self_x); + calCoords(targetcore, &target_y, &target_x); + // Build the message header + msgHdr = construct_dyn_hdr(0, msgsize, 0, // msgsize word sent. + self_y, self_x, + target_y, target_x); + // start sending the msg, set send msg flag + isMsgSending = true; + gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). #ifdef RAWDEBUG - raw_test_pass(0xbbbb); - raw_test_pass(0xb000 + targetcore); // targetcore + raw_test_pass(0xbbbb); + raw_test_pass(0xb000 + targetcore); // targetcore #endif - gdn_send(2); // lock request + gdn_send(2); // lock request #ifdef RAWDEBUG - raw_test_pass(2); + raw_test_pass(2); #endif - gdn_send(0); // read lock + gdn_send(0); // read lock #ifdef RAWDEBUG - raw_test_pass(0); + raw_test_pass(0); #endif - gdn_send(ptr); + gdn_send(ptr); #ifdef RAWDEBUG - raw_test_pass_reg(ptr); + raw_test_pass_reg(ptr); #endif - gdn_send(corenum); + gdn_send(corenum); #ifdef RAWDEBUG - raw_test_pass_reg(corenum); - raw_test_pass(0xffff); + raw_test_pass_reg(corenum); + raw_test_pass(0xffff); #endif - // end of sending this msg, set sand msg flag false - isMsgSending = false; - // check if there are pending msgs - while(isMsgHanging) { - // get the msg from outmsgdata[] - // length + target + msg - outmsgleft = outmsgdata[outmsgindex++]; - targetcore = outmsgdata[outmsgindex++]; - calCoords(targetcore, &target_y, &target_x); - // Build the message header - msgHdr = construct_dyn_hdr(0, outmsgleft, 0, // msgsize word sent. - self_y, self_x, - target_y, target_x); - isMsgSending = true; - gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). + // end of sending this msg, set sand msg flag false + isMsgSending = false; + // check if there are pending msgs + while(isMsgHanging) { + // get the msg from outmsgdata[] + // length + target + msg + outmsgleft = outmsgdata[outmsgindex++]; + targetcore = outmsgdata[outmsgindex++]; + calCoords(targetcore, &target_y, &target_x); + // Build the message header + msgHdr = construct_dyn_hdr(0, outmsgleft, 0, // msgsize word sent. + self_y, self_x, + target_y, target_x); + isMsgSending = true; + gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). #ifdef RAWDEBUG - raw_test_pass(0xbbbb); - raw_test_pass(0xb000 + targetcore); // targetcore + raw_test_pass(0xbbbb); + raw_test_pass(0xb000 + targetcore); // targetcore #endif - while(outmsgleft-- > 0) { - gdn_send(outmsgdata[outmsgindex++]); + while(outmsgleft-- > 0) { + gdn_send(outmsgdata[outmsgindex++]); #ifdef RAWDEBUG - raw_test_pass_reg(outmsgdata[outmsgindex - 1]); + raw_test_pass_reg(outmsgdata[outmsgindex - 1]); #endif - } + } #ifdef RAWDEBUG - raw_test_pass(0xffff); + raw_test_pass(0xffff); #endif - isMsgSending = false; + isMsgSending = false; #ifdef INTERRUPT - raw_user_interrupts_off(); -#endif - // check if there are still msg hanging - if(outmsgindex == outmsglast) { - // no more msgs - outmsgindex = outmsglast = 0; - isMsgHanging = false; - } + raw_user_interrupts_off(); +#endif + // check if there are still msg hanging + if(outmsgindex == outmsglast) { + // no more msgs + outmsgindex = outmsglast = 0; + isMsgHanging = false; + } #ifdef INTERRUPT - raw_user_interrupts_on(); + raw_user_interrupts_on(); #endif - } - return true; + } + return true; #elif defined THREADSIMULATE - int numofcore = pthread_getspecific(key); + int numofcore = pthread_getspecific(key); - int rc = pthread_rwlock_tryrdlock(&rwlock_tbl); - printf("[getreadlock, %d] getting the read lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); - if(0 != rc) { - return false; - } - if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { - // no locks for this object - // first time to operate on this shared object - // create a lock for it - rc = pthread_rwlock_unlock(&rwlock_tbl); - printf("[getreadlock, %d] release the read lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); - pthread_rwlock_t* rwlock = (pthread_rwlock_t *)RUNMALLOC(sizeof(pthread_rwlock_t)); - memcpy(rwlock, &rwlock_init, sizeof(pthread_rwlock_t)); - rc = pthread_rwlock_init(rwlock, NULL); - printf("[getreadlock, %d] initialize the rwlock for object %d: %d error: \n", numofcore, (int)ptr, rc, strerror(rc)); - rc = pthread_rwlock_trywrlock(&rwlock_tbl); - printf("[getreadlock, %d] getting the write lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); - if(0 != rc) { - RUNFREE(rwlock); - return false; - } else { - if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { - // check again - RuntimeHashadd(locktbl, (int)ptr, (int)rwlock); - } else { - RUNFREE(rwlock); - RuntimeHashget(locktbl, (int)ptr, (int*)&rwlock); - } - rc = pthread_rwlock_unlock(&rwlock_tbl); - printf("[getreadlock, %d] release the write lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); - } - rc = pthread_rwlock_tryrdlock(rwlock); - printf("[getreadlock, %d] getting read lock for object %d: %d error: \n", numofcore, (int)ptr, rc, strerror(rc)); - if(0 != rc) { - return false; - } else { - return true; - } - } else { - pthread_rwlock_t* rwlock_obj = NULL; - RuntimeHashget(locktbl, (int)ptr, (int*)&rwlock_obj); - rc = pthread_rwlock_unlock(&rwlock_tbl); - printf("[getreadlock, %d] release the read lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); - int rc_obj = pthread_rwlock_tryrdlock(rwlock_obj); - printf("[getreadlock, %d] getting read lock for object %d: %d error: \n", numofcore, (int)ptr, rc_obj, strerror(rc_obj)); - if(0 != rc_obj) { - return false; - } else { - return true; - } - } + int rc = pthread_rwlock_tryrdlock(&rwlock_tbl); + printf("[getreadlock, %d] getting the read lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); + if(0 != rc) { + return false; + } + if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { + // no locks for this object + // first time to operate on this shared object + // create a lock for it + rc = pthread_rwlock_unlock(&rwlock_tbl); + printf("[getreadlock, %d] release the read lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); + pthread_rwlock_t* rwlock = (pthread_rwlock_t *)RUNMALLOC(sizeof(pthread_rwlock_t)); + memcpy(rwlock, &rwlock_init, sizeof(pthread_rwlock_t)); + rc = pthread_rwlock_init(rwlock, NULL); + printf("[getreadlock, %d] initialize the rwlock for object %d: %d error: \n", numofcore, (int)ptr, rc, strerror(rc)); + rc = pthread_rwlock_trywrlock(&rwlock_tbl); + printf("[getreadlock, %d] getting the write lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); + if(0 != rc) { + RUNFREE(rwlock); + return false; + } else { + if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { + // check again + RuntimeHashadd(locktbl, (int)ptr, (int)rwlock); + } else { + RUNFREE(rwlock); + RuntimeHashget(locktbl, (int)ptr, (int*)&rwlock); + } + rc = pthread_rwlock_unlock(&rwlock_tbl); + printf("[getreadlock, %d] release the write lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); + } + rc = pthread_rwlock_tryrdlock(rwlock); + printf("[getreadlock, %d] getting read lock for object %d: %d error: \n", numofcore, (int)ptr, rc, strerror(rc)); + if(0 != rc) { + return false; + } else { + return true; + } + } else { + pthread_rwlock_t* rwlock_obj = NULL; + RuntimeHashget(locktbl, (int)ptr, (int*)&rwlock_obj); + rc = pthread_rwlock_unlock(&rwlock_tbl); + printf("[getreadlock, %d] release the read lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); + int rc_obj = pthread_rwlock_tryrdlock(rwlock_obj); + printf("[getreadlock, %d] getting read lock for object %d: %d error: \n", numofcore, (int)ptr, rc_obj, strerror(rc_obj)); + if(0 != rc_obj) { + return false; + } else { + return true; + } + } #endif } void releasereadlock(void * ptr) { #ifdef RAW - unsigned msgHdr; - int self_y, self_x, target_y, target_x; - int targetcore = 0; //((int)ptr >> 5) % TOTALCORE; - // for 32 bit machine, the size is always 3 words - //int msgsize = sizeof(int) * 3; - int msgsize = 3; - int tc = TOTALCORE; + unsigned msgHdr; + int self_y, self_x, target_y, target_x; + int targetcore = 0; //((int)ptr >> 5) % TOTALCORE; + // for 32 bit machine, the size is always 3 words + //int msgsize = sizeof(int) * 3; + int msgsize = 3; + int tc = TOTALCORE; #ifdef INTERRUPT - raw_user_interrupts_off(); + raw_user_interrupts_off(); #endif - targetcore = ((int)ptr >> 5) % tc; + targetcore = ((int)ptr >> 5) % tc; #ifdef INTERRUPT - raw_user_interrupts_on(); + raw_user_interrupts_on(); #endif - if(targetcore == corenum) { + if(targetcore == corenum) { #ifdef INTERRUPT - raw_user_interrupts_off(); -#endif - // reside on this core - if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { - // no locks for this object, something is wrong - raw_test_done(0xa006); - } else { - int rwlock_obj = 0; - RuntimeHashget(locktbl, (int)ptr, &rwlock_obj); - rwlock_obj--; - RuntimeHashremovekey(locktbl, (int)ptr); - RuntimeHashadd_I(locktbl, (int)ptr, rwlock_obj); - } + raw_user_interrupts_off(); +#endif + // reside on this core + if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { + // no locks for this object, something is wrong + raw_test_done(0xa006); + } else { + int rwlock_obj = 0; + RuntimeHashget(locktbl, (int)ptr, &rwlock_obj); + rwlock_obj--; + RuntimeHashremovekey(locktbl, (int)ptr); + RuntimeHashadd_I(locktbl, (int)ptr, rwlock_obj); + } #ifdef INTERRUPT - raw_user_interrupts_on(); + raw_user_interrupts_on(); #endif - return; - } + return; + } - calCoords(corenum, &self_y, &self_x); - calCoords(targetcore, &target_y, &target_x); - // Build the message header - msgHdr = construct_dyn_hdr(0, msgsize, 0, // msgsize word sent. - self_y, self_x, - target_y, target_x); - // start sending the msg, set send msg flag - isMsgSending = true; - gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). + calCoords(corenum, &self_y, &self_x); + calCoords(targetcore, &target_y, &target_x); + // Build the message header + msgHdr = construct_dyn_hdr(0, msgsize, 0, // msgsize word sent. + self_y, self_x, + target_y, target_x); + // start sending the msg, set send msg flag + isMsgSending = true; + gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). #ifdef RAWDEBUG - raw_test_pass(0xbbbb); - raw_test_pass(0xb000 + targetcore); // targetcore + raw_test_pass(0xbbbb); + raw_test_pass(0xb000 + targetcore); // targetcore #endif - gdn_send(5); // lock release + gdn_send(5); // lock release #ifdef RAWDEBUG - raw_test_pass(5); + raw_test_pass(5); #endif - gdn_send(0); // read lock + gdn_send(0); // read lock #ifdef RAWDEBUG - raw_test_pass(0); + raw_test_pass(0); #endif - gdn_send(ptr); + gdn_send(ptr); #ifdef RAWDEBUG - raw_test_pass_reg(ptr); - raw_test_pass(0xffff); + raw_test_pass_reg(ptr); + raw_test_pass(0xffff); #endif - // end of sending this msg, set sand msg flag false - isMsgSending = false; - // check if there are pending msgs - while(isMsgHanging) { - // get the msg from outmsgdata[] - // length + target + msg - outmsgleft = outmsgdata[outmsgindex++]; - targetcore = outmsgdata[outmsgindex++]; - calCoords(targetcore, &target_y, &target_x); - // Build the message header - msgHdr = construct_dyn_hdr(0, outmsgleft, 0, // msgsize word sent. - self_y, self_x, - target_y, target_x); - isMsgSending = true; - gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). + // end of sending this msg, set sand msg flag false + isMsgSending = false; + // check if there are pending msgs + while(isMsgHanging) { + // get the msg from outmsgdata[] + // length + target + msg + outmsgleft = outmsgdata[outmsgindex++]; + targetcore = outmsgdata[outmsgindex++]; + calCoords(targetcore, &target_y, &target_x); + // Build the message header + msgHdr = construct_dyn_hdr(0, outmsgleft, 0, // msgsize word sent. + self_y, self_x, + target_y, target_x); + isMsgSending = true; + gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). #ifdef RAWDEBUG - raw_test_pass(0xbbbb); - raw_test_pass(0xb000 + targetcore); // targetcore + raw_test_pass(0xbbbb); + raw_test_pass(0xb000 + targetcore); // targetcore #endif - while(outmsgleft-- > 0) { - gdn_send(outmsgdata[outmsgindex++]); + while(outmsgleft-- > 0) { + gdn_send(outmsgdata[outmsgindex++]); #ifdef RAWDEBUG - raw_test_pass_reg(outmsgdata[outmsgindex - 1]); + raw_test_pass_reg(outmsgdata[outmsgindex - 1]); #endif - } + } #ifdef RAWDEBUG - raw_test_pass(0xffff); + raw_test_pass(0xffff); #endif - isMsgSending = false; + isMsgSending = false; #ifdef INTERRUPT - raw_user_interrupts_off(); -#endif - // check if there are still msg hanging - if(outmsgindex == outmsglast) { - // no more msgs - outmsgindex = outmsglast = 0; - isMsgHanging = false; - } + raw_user_interrupts_off(); +#endif + // check if there are still msg hanging + if(outmsgindex == outmsglast) { + // no more msgs + outmsgindex = outmsglast = 0; + isMsgHanging = false; + } #ifdef INTERRUPT - raw_user_interrupts_on(); + raw_user_interrupts_on(); #endif - } + } #elif defined THREADSIMULATE - int numofcore = pthread_getspecific(key); - int rc = pthread_rwlock_rdlock(&rwlock_tbl); - printf("[releasereadlock, %d] getting the read lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); - if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { - printf("[releasereadlock, %d] Error: try to release a lock without previously grab it\n", numofcore); - exit(-1); - } - pthread_rwlock_t* rwlock_obj = NULL; - RuntimeHashget(locktbl, (int)ptr, (int*)&rwlock_obj); - int rc_obj = pthread_rwlock_unlock(rwlock_obj); - printf("[releasereadlock, %d] unlocked object %d: %d error: \n", numofcore, (int)ptr, rc_obj, strerror(rc_obj)); - rc = pthread_rwlock_unlock(&rwlock_tbl); - printf("[releasereadlock, %d] release the read lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); + int numofcore = pthread_getspecific(key); + int rc = pthread_rwlock_rdlock(&rwlock_tbl); + printf("[releasereadlock, %d] getting the read lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); + if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { + printf("[releasereadlock, %d] Error: try to release a lock without previously grab it\n", numofcore); + exit(-1); + } + pthread_rwlock_t* rwlock_obj = NULL; + RuntimeHashget(locktbl, (int)ptr, (int*)&rwlock_obj); + int rc_obj = pthread_rwlock_unlock(rwlock_obj); + printf("[releasereadlock, %d] unlocked object %d: %d error: \n", numofcore, (int)ptr, rc_obj, strerror(rc_obj)); + rc = pthread_rwlock_unlock(&rwlock_tbl); + printf("[releasereadlock, %d] release the read lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); #endif } #ifdef RAW bool getreadlock_I(void * ptr) { - unsigned msgHdr; - int self_y, self_x, target_y, target_x; - int targetcore = ((int)ptr >> 5) % TOTALCORE; - // for 32 bit machine, the size is always 4 words - //int msgsize = sizeof(int) * 4; - int msgsize = 4; - - lockobj = (int)ptr; - lockflag = false; + unsigned msgHdr; + int self_y, self_x, target_y, target_x; + int targetcore = ((int)ptr >> 5) % TOTALCORE; + // for 32 bit machine, the size is always 4 words + //int msgsize = sizeof(int) * 4; + int msgsize = 4; + + lockobj = (int)ptr; + lockflag = false; #ifndef INTERRUPT - reside = false; -#endif + reside = false; +#endif + lockresult = 0; + + if(targetcore == corenum) { + // reside on this core + bool deny = false; + if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { + // no locks for this object + // first time to operate on this shared object + // create a lock for it + // the lock is an integer: 0 -- stall, >0 -- read lock, -1 -- write lock + RuntimeHashadd_I(locktbl, (int)ptr, 1); + } else { + int rwlock_obj = 0; + RuntimeHashget(locktbl, (int)ptr, &rwlock_obj); + if(-1 != rwlock_obj) { + rwlock_obj++; + RuntimeHashremovekey(locktbl, (int)ptr); + RuntimeHashadd_I(locktbl, (int)ptr, rwlock_obj); + } else { + deny = true; + } + } + if(lockobj == (int)ptr) { + if(deny) { lockresult = 0; - - if(targetcore == corenum) { - // reside on this core - bool deny = false; - if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { - // no locks for this object - // first time to operate on this shared object - // create a lock for it - // the lock is an integer: 0 -- stall, >0 -- read lock, -1 -- write lock - RuntimeHashadd_I(locktbl, (int)ptr, 1); - } else { - int rwlock_obj = 0; - RuntimeHashget(locktbl, (int)ptr, &rwlock_obj); - if(-1 != rwlock_obj) { - rwlock_obj++; - RuntimeHashremovekey(locktbl, (int)ptr); - RuntimeHashadd_I(locktbl, (int)ptr, rwlock_obj); - } else { - deny = true; - } - } - if(lockobj == (int)ptr) { - if(deny) { - lockresult = 0; - } else { - lockresult = 1; - } - lockflag = true; + } else { + lockresult = 1; + } + lockflag = true; #ifndef INTERRUPT - reside = true; + reside = true; #endif - } else { - // conflicts on lockresults - raw_test_done(0xa005); - } - return true; - } + } else { + // conflicts on lockresults + raw_test_done(0xa005); + } + return true; + } - calCoords(corenum, &self_y, &self_x); - calCoords(targetcore, &target_y, &target_x); - // Build the message header - msgHdr = construct_dyn_hdr(0, msgsize, 0, // msgsize word sent. - self_y, self_x, - target_y, target_x); - gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). + calCoords(corenum, &self_y, &self_x); + calCoords(targetcore, &target_y, &target_x); + // Build the message header + msgHdr = construct_dyn_hdr(0, msgsize, 0, // msgsize word sent. + self_y, self_x, + target_y, target_x); + gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). #ifdef RAWDEBUG - raw_test_pass(0xbbbb); - raw_test_pass(0xb000 + targetcore); // targetcore + raw_test_pass(0xbbbb); + raw_test_pass(0xb000 + targetcore); // targetcore #endif - gdn_send(2); // lock request + gdn_send(2); // lock request #ifdef RAWDEBUG - raw_test_pass(2); + raw_test_pass(2); #endif - gdn_send(0); // read lock + gdn_send(0); // read lock #ifdef RAWDEBUG - raw_test_pass(0); + raw_test_pass(0); #endif - gdn_send(ptr); + gdn_send(ptr); #ifdef RAWDEBUG - raw_test_pass_reg(ptr); + raw_test_pass_reg(ptr); #endif - gdn_send(corenum); + gdn_send(corenum); #ifdef RAWDEBUG - raw_test_pass_reg(corenum); - raw_test_pass(0xffff); + raw_test_pass_reg(corenum); + raw_test_pass(0xffff); #endif - return true; + return true; } void releasereadlock_I(void * ptr) { - unsigned msgHdr; - int self_y, self_x, target_y, target_x; - int targetcore = ((int)ptr >> 5) % TOTALCORE; - // for 32 bit machine, the size is always 3 words - //int msgsize = sizeof(int) * 3; - int msgsize = 3; - - if(targetcore == corenum) { - // reside on this core - if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { - // no locks for this object, something is wrong - raw_test_done(0xa006); - } else { - int rwlock_obj = 0; - RuntimeHashget(locktbl, (int)ptr, &rwlock_obj); - rwlock_obj--; - RuntimeHashremovekey(locktbl, (int)ptr); - RuntimeHashadd_I(locktbl, (int)ptr, rwlock_obj); - } - return; - } + unsigned msgHdr; + int self_y, self_x, target_y, target_x; + int targetcore = ((int)ptr >> 5) % TOTALCORE; + // for 32 bit machine, the size is always 3 words + //int msgsize = sizeof(int) * 3; + int msgsize = 3; + + if(targetcore == corenum) { + // reside on this core + if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { + // no locks for this object, something is wrong + raw_test_done(0xa006); + } else { + int rwlock_obj = 0; + RuntimeHashget(locktbl, (int)ptr, &rwlock_obj); + rwlock_obj--; + RuntimeHashremovekey(locktbl, (int)ptr); + RuntimeHashadd_I(locktbl, (int)ptr, rwlock_obj); + } + return; + } - calCoords(corenum, &self_y, &self_x); - calCoords(targetcore, &target_y, &target_x); - // Build the message header - msgHdr = construct_dyn_hdr(0, msgsize, 0, // msgsize word sent. - self_y, self_x, - target_y, target_x); - gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). + calCoords(corenum, &self_y, &self_x); + calCoords(targetcore, &target_y, &target_x); + // Build the message header + msgHdr = construct_dyn_hdr(0, msgsize, 0, // msgsize word sent. + self_y, self_x, + target_y, target_x); + gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). #ifdef RAWDEBUG - raw_test_pass(0xbbbb); - raw_test_pass(0xb000 + targetcore); // targetcore + raw_test_pass(0xbbbb); + raw_test_pass(0xb000 + targetcore); // targetcore #endif - gdn_send(5); // lock release + gdn_send(5); // lock release #ifdef RAWDEBUG - raw_test_pass(5); + raw_test_pass(5); #endif - gdn_send(0); // read lock + gdn_send(0); // read lock #ifdef RAWDEBUG - raw_test_pass(0); + raw_test_pass(0); #endif - gdn_send(ptr); + gdn_send(ptr); #ifdef RAWDEBUG - raw_test_pass_reg(ptr); - raw_test_pass(0xffff); + raw_test_pass_reg(ptr); + raw_test_pass(0xffff); #endif } #endif @@ -2460,363 +2472,363 @@ void releasereadlock_I(void * ptr) { // not reentrant bool getwritelock(void * ptr) { #ifdef RAW - unsigned msgHdr; - int self_y, self_x, target_y, target_x; - int targetcore = 0; //((int)ptr >> 5) % TOTALCORE; - // for 32 bit machine, the size is always 4 words - //int msgsize = sizeof(int) * 4; - int msgsize= 4; - int tc = TOTALCORE; + unsigned msgHdr; + int self_y, self_x, target_y, target_x; + int targetcore = 0; //((int)ptr >> 5) % TOTALCORE; + // for 32 bit machine, the size is always 4 words + //int msgsize = sizeof(int) * 4; + int msgsize= 4; + int tc = TOTALCORE; #ifdef INTERRUPT - raw_user_interrupts_off(); + raw_user_interrupts_off(); #endif - targetcore = ((int)ptr >> 5) % tc; + targetcore = ((int)ptr >> 5) % tc; #ifdef INTERRUPT - raw_user_interrupts_on(); + raw_user_interrupts_on(); #endif #ifdef RAWDEBUG - raw_test_pass(0xe551); - raw_test_pass_reg(ptr); - raw_test_pass_reg(targetcore); - raw_test_pass_reg(tc); + raw_test_pass(0xe551); + raw_test_pass_reg(ptr); + raw_test_pass_reg(targetcore); + raw_test_pass_reg(tc); #endif - lockobj = (int)ptr; - lockflag = false; + lockobj = (int)ptr; + lockflag = false; #ifndef INTERRUPT - reside = false; + reside = false; #endif - lockresult = 0; + lockresult = 0; - if(targetcore == corenum) { - // reside on this core - bool deny = false; + if(targetcore == corenum) { + // reside on this core + bool deny = false; #ifdef INTERRUPT - raw_user_interrupts_off(); -#endif - if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { - // no locks for this object - // first time to operate on this shared object - // create a lock for it - // the lock is an integer: 0 -- stall, >0 -- read lock, -1 -- write lock -#ifdef RAWDEBUG - raw_test_pass(0xe552); -#endif - RuntimeHashadd_I(locktbl, (int)ptr, -1); - } else { - int rwlock_obj = 0; - RuntimeHashget(locktbl, (int)ptr, &rwlock_obj); -#ifdef RAWDEBUG - raw_test_pass(0xe553); - raw_test_pass_reg(rwlock_obj); -#endif - if(0 == rwlock_obj) { - rwlock_obj = -1; - RuntimeHashremovekey(locktbl, (int)ptr); - RuntimeHashadd_I(locktbl, (int)ptr, rwlock_obj); - } else { - deny = true; - } - } + raw_user_interrupts_off(); +#endif + if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { + // no locks for this object + // first time to operate on this shared object + // create a lock for it + // the lock is an integer: 0 -- stall, >0 -- read lock, -1 -- write lock +#ifdef RAWDEBUG + raw_test_pass(0xe552); +#endif + RuntimeHashadd_I(locktbl, (int)ptr, -1); + } else { + int rwlock_obj = 0; + RuntimeHashget(locktbl, (int)ptr, &rwlock_obj); +#ifdef RAWDEBUG + raw_test_pass(0xe553); + raw_test_pass_reg(rwlock_obj); +#endif + if(0 == rwlock_obj) { + rwlock_obj = -1; + RuntimeHashremovekey(locktbl, (int)ptr); + RuntimeHashadd_I(locktbl, (int)ptr, rwlock_obj); + } else { + deny = true; + } + } #ifdef INTERRUPT - raw_user_interrupts_on(); + raw_user_interrupts_on(); #endif #ifdef RAWDEBUG - raw_test_pass(0xe554); - raw_test_pass_reg(lockresult); + raw_test_pass(0xe554); + raw_test_pass_reg(lockresult); #endif - if(lockobj == (int)ptr) { - if(deny) { - lockresult = 0; + if(lockobj == (int)ptr) { + if(deny) { + lockresult = 0; #ifdef RAWDEBUG - raw_test_pass(0); + raw_test_pass(0); #endif - } else { - lockresult = 1; -#ifdef RAWDEBUG - raw_test_pass(1); + } else { + lockresult = 1; +#ifdef RAWDEBUG + raw_test_pass(1); #endif - } - lockflag = true; + } + lockflag = true; #ifndef INTERRUPT - reside = true; + reside = true; #endif - } else { - // conflicts on lockresults - raw_test_done(0xa007); - } - return true; - } + } else { + // conflicts on lockresults + raw_test_done(0xa007); + } + return true; + } #ifdef RAWDEBUG - raw_test_pass(0xe555); + raw_test_pass(0xe555); #endif - calCoords(corenum, &self_y, &self_x); - calCoords(targetcore, &target_y, &target_x); - // Build the message header - msgHdr = construct_dyn_hdr(0, msgsize, 0, // msgsize word sent. - self_y, self_x, - target_y, target_x); - // start sending the msg, set send msg flag - isMsgSending = true; - gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). + calCoords(corenum, &self_y, &self_x); + calCoords(targetcore, &target_y, &target_x); + // Build the message header + msgHdr = construct_dyn_hdr(0, msgsize, 0, // msgsize word sent. + self_y, self_x, + target_y, target_x); + // start sending the msg, set send msg flag + isMsgSending = true; + gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). #ifdef RAWDEBUG - raw_test_pass(0xbbbb); - raw_test_pass(0xb000 + targetcore); // targetcore + raw_test_pass(0xbbbb); + raw_test_pass(0xb000 + targetcore); // targetcore #endif - gdn_send(2); // lock request + gdn_send(2); // lock request #ifdef RAWDEBUG - raw_test_pass(2); + raw_test_pass(2); #endif - gdn_send(1); // write lock + gdn_send(1); // write lock #ifdef RAWDEBUG - raw_test_pass(1); + raw_test_pass(1); #endif - gdn_send(ptr); + gdn_send(ptr); #ifdef RAWDEBUG - raw_test_pass_reg(ptr); + raw_test_pass_reg(ptr); #endif - gdn_send(corenum); + gdn_send(corenum); #ifdef RAWDEBUG - raw_test_pass_reg(corenum); - raw_test_pass(0xffff); + raw_test_pass_reg(corenum); + raw_test_pass(0xffff); #endif - // end of sending this msg, set sand msg flag false - isMsgSending = false; - // check if there are pending msgs - while(isMsgHanging) { - // get the msg from outmsgdata[] - // length + target + msg - outmsgleft = outmsgdata[outmsgindex++]; - targetcore = outmsgdata[outmsgindex++]; - calCoords(targetcore, &target_y, &target_x); - // Build the message header - msgHdr = construct_dyn_hdr(0, outmsgleft, 0, // msgsize word sent. - self_y, self_x, - target_y, target_x); - isMsgSending = true; - gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). + // end of sending this msg, set sand msg flag false + isMsgSending = false; + // check if there are pending msgs + while(isMsgHanging) { + // get the msg from outmsgdata[] + // length + target + msg + outmsgleft = outmsgdata[outmsgindex++]; + targetcore = outmsgdata[outmsgindex++]; + calCoords(targetcore, &target_y, &target_x); + // Build the message header + msgHdr = construct_dyn_hdr(0, outmsgleft, 0, // msgsize word sent. + self_y, self_x, + target_y, target_x); + isMsgSending = true; + gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). #ifdef RAWDEBUG - raw_test_pass(0xbbbb); - raw_test_pass(0xb000 + targetcore); // targetcore + raw_test_pass(0xbbbb); + raw_test_pass(0xb000 + targetcore); // targetcore #endif - while(outmsgleft-- > 0) { - gdn_send(outmsgdata[outmsgindex++]); + while(outmsgleft-- > 0) { + gdn_send(outmsgdata[outmsgindex++]); #ifdef RAWDEBUG - raw_test_pass_reg(outmsgdata[outmsgindex - 1]); + raw_test_pass_reg(outmsgdata[outmsgindex - 1]); #endif - } + } #ifdef RAWDEBUG - raw_test_pass(0xffff); + raw_test_pass(0xffff); #endif - isMsgSending = false; + isMsgSending = false; #ifdef INTERRUPT - raw_user_interrupts_off(); -#endif - // check if there are still msg hanging - if(outmsgindex == outmsglast) { - // no more msgs - outmsgindex = outmsglast = 0; - isMsgHanging = false; - } + raw_user_interrupts_off(); +#endif + // check if there are still msg hanging + if(outmsgindex == outmsglast) { + // no more msgs + outmsgindex = outmsglast = 0; + isMsgHanging = false; + } #ifdef INTERRUPT - raw_user_interrupts_on(); + raw_user_interrupts_on(); #endif - } - return true; + } + return true; #elif defined THREADSIMULATE - int numofcore = pthread_getspecific(key); + int numofcore = pthread_getspecific(key); - int rc = pthread_rwlock_tryrdlock(&rwlock_tbl); - printf("[getwritelock, %d] getting the read lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); - if(0 != rc) { - return false; - } - if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { - // no locks for this object - // first time to operate on this shared object - // create a lock for it - rc = pthread_rwlock_unlock(&rwlock_tbl); - printf("[getwritelock, %d] release the read lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); - pthread_rwlock_t* rwlock = (pthread_rwlock_t *)RUNMALLOC(sizeof(pthread_rwlock_t)); - memcpy(rwlock, &rwlock_init, sizeof(pthread_rwlock_t)); - rc = pthread_rwlock_init(rwlock, NULL); - printf("[getwritelock, %d] initialize the rwlock for object %d: %d error: \n", numofcore, (int)ptr, rc, strerror(rc)); - rc = pthread_rwlock_trywrlock(&rwlock_tbl); - printf("[getwritelock, %d] getting the write lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); - if(0 != rc) { - pthread_rwlock_destroy(rwlock); - RUNFREE(rwlock); - return false; - } else { - if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { - // check again - RuntimeHashadd(locktbl, (int)ptr, (int)rwlock); - } else { - pthread_rwlock_destroy(rwlock); - RUNFREE(rwlock); - RuntimeHashget(locktbl, (int)ptr, (int*)&rwlock); - } - rc = pthread_rwlock_unlock(&rwlock_tbl); - printf("[getwritelock, %d] release the write lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); - } - rc = pthread_rwlock_trywrlock(rwlock); - printf("[getwritelock, %d] getting write lock for object %d: %d error: \n", numofcore, (int)ptr, rc, strerror(rc)); - if(0 != rc) { - return false; - } else { - return true; - } - } else { - pthread_rwlock_t* rwlock_obj = NULL; - RuntimeHashget(locktbl, (int)ptr, (int*)&rwlock_obj); - rc = pthread_rwlock_unlock(&rwlock_tbl); - printf("[getwritelock, %d] release the read lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); - int rc_obj = pthread_rwlock_trywrlock(rwlock_obj); - printf("[getwritelock, %d] getting write lock for object %d: %d error: \n", numofcore, (int)ptr, rc_obj, strerror(rc_obj)); - if(0 != rc_obj) { - return false; - } else { - return true; - } - } + int rc = pthread_rwlock_tryrdlock(&rwlock_tbl); + printf("[getwritelock, %d] getting the read lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); + if(0 != rc) { + return false; + } + if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { + // no locks for this object + // first time to operate on this shared object + // create a lock for it + rc = pthread_rwlock_unlock(&rwlock_tbl); + printf("[getwritelock, %d] release the read lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); + pthread_rwlock_t* rwlock = (pthread_rwlock_t *)RUNMALLOC(sizeof(pthread_rwlock_t)); + memcpy(rwlock, &rwlock_init, sizeof(pthread_rwlock_t)); + rc = pthread_rwlock_init(rwlock, NULL); + printf("[getwritelock, %d] initialize the rwlock for object %d: %d error: \n", numofcore, (int)ptr, rc, strerror(rc)); + rc = pthread_rwlock_trywrlock(&rwlock_tbl); + printf("[getwritelock, %d] getting the write lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); + if(0 != rc) { + pthread_rwlock_destroy(rwlock); + RUNFREE(rwlock); + return false; + } else { + if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { + // check again + RuntimeHashadd(locktbl, (int)ptr, (int)rwlock); + } else { + pthread_rwlock_destroy(rwlock); + RUNFREE(rwlock); + RuntimeHashget(locktbl, (int)ptr, (int*)&rwlock); + } + rc = pthread_rwlock_unlock(&rwlock_tbl); + printf("[getwritelock, %d] release the write lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); + } + rc = pthread_rwlock_trywrlock(rwlock); + printf("[getwritelock, %d] getting write lock for object %d: %d error: \n", numofcore, (int)ptr, rc, strerror(rc)); + if(0 != rc) { + return false; + } else { + return true; + } + } else { + pthread_rwlock_t* rwlock_obj = NULL; + RuntimeHashget(locktbl, (int)ptr, (int*)&rwlock_obj); + rc = pthread_rwlock_unlock(&rwlock_tbl); + printf("[getwritelock, %d] release the read lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); + int rc_obj = pthread_rwlock_trywrlock(rwlock_obj); + printf("[getwritelock, %d] getting write lock for object %d: %d error: \n", numofcore, (int)ptr, rc_obj, strerror(rc_obj)); + if(0 != rc_obj) { + return false; + } else { + return true; + } + } #endif } void releasewritelock(void * ptr) { #ifdef RAW - unsigned msgHdr; - int self_y, self_x, target_y, target_x; - int targetcore = 0; //((int)ptr >> 5) % TOTALCORE; - // for 32 bit machine, the size is always 3 words - //int msgsize = sizeof(int) * 3; - int msgsize = 3; - int tc = TOTALCORE; + unsigned msgHdr; + int self_y, self_x, target_y, target_x; + int targetcore = 0; //((int)ptr >> 5) % TOTALCORE; + // for 32 bit machine, the size is always 3 words + //int msgsize = sizeof(int) * 3; + int msgsize = 3; + int tc = TOTALCORE; #ifdef INTERRUPT - raw_user_interrupts_off(); + raw_user_interrupts_off(); #endif - targetcore = ((int)ptr >> 5) % tc; + targetcore = ((int)ptr >> 5) % tc; #ifdef INTERRUPT - raw_user_interrupts_on(); + raw_user_interrupts_on(); #endif - if(targetcore == corenum) { + if(targetcore == corenum) { #ifdef INTERRUPT - raw_user_interrupts_off(); + raw_user_interrupts_off(); #endif - // reside on this core - if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { - // no locks for this object, something is wrong - raw_test_done(0xa008); - } else { - int rwlock_obj = 0; + // reside on this core + if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { + // no locks for this object, something is wrong + raw_test_done(0xa008); + } else { + int rwlock_obj = 0; #ifdef RAWDEBUG - raw_test_pass(0xe662); + raw_test_pass(0xe662); #endif - RuntimeHashget(locktbl, (int)ptr, &rwlock_obj); + RuntimeHashget(locktbl, (int)ptr, &rwlock_obj); #ifdef RAWDEBUG - raw_test_pass_reg(rwlock_obj); + raw_test_pass_reg(rwlock_obj); #endif - rwlock_obj++; - RuntimeHashremovekey(locktbl, (int)ptr); - RuntimeHashadd_I(locktbl, (int)ptr, rwlock_obj); + rwlock_obj++; + RuntimeHashremovekey(locktbl, (int)ptr); + RuntimeHashadd_I(locktbl, (int)ptr, rwlock_obj); #ifdef RAWDEBUG - raw_test_pass_reg(rwlock_obj); + raw_test_pass_reg(rwlock_obj); #endif - } + } #ifdef INTERRUPT - raw_user_interrupts_on(); + raw_user_interrupts_on(); #endif - return; - } + return; + } #ifdef RAWDEBUG - raw_test_pass(0xe663); + raw_test_pass(0xe663); #endif - calCoords(corenum, &self_y, &self_x); - calCoords(targetcore, &target_y, &target_x); - // Build the message header - msgHdr = construct_dyn_hdr(0, msgsize, 0, // msgsize word sent. - self_y, self_x, - target_y, target_x); - // start sending the msg, set send msg flag - isMsgSending = true; - gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). + calCoords(corenum, &self_y, &self_x); + calCoords(targetcore, &target_y, &target_x); + // Build the message header + msgHdr = construct_dyn_hdr(0, msgsize, 0, // msgsize word sent. + self_y, self_x, + target_y, target_x); + // start sending the msg, set send msg flag + isMsgSending = true; + gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). #ifdef RAWDEBUG - raw_test_pass(0xbbbb); - raw_test_pass(0xb000 + targetcore); + raw_test_pass(0xbbbb); + raw_test_pass(0xb000 + targetcore); #endif - gdn_send(5); // lock release + gdn_send(5); // lock release #ifdef RAWDEBUG - raw_test_pass(5); + raw_test_pass(5); #endif - gdn_send(1); // write lock + gdn_send(1); // write lock #ifdef RAWDEBUG - raw_test_pass(1); + raw_test_pass(1); #endif - gdn_send(ptr); + gdn_send(ptr); #ifdef RAWDEBUG - raw_test_pass_reg(ptr); - raw_test_pass(0xffff); + raw_test_pass_reg(ptr); + raw_test_pass(0xffff); #endif - // end of sending this msg, set sand msg flag false - isMsgSending = false; - // check if there are pending msgs - while(isMsgHanging) { - // get the msg from outmsgdata[] - // length + target + msg - outmsgleft = outmsgdata[outmsgindex++]; - targetcore = outmsgdata[outmsgindex++]; - calCoords(targetcore, &target_y, &target_x); - // Build the message header - msgHdr = construct_dyn_hdr(0, outmsgleft, 0, // msgsize word sent. - self_y, self_x, - target_y, target_x); - isMsgSending = true; - gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). + // end of sending this msg, set sand msg flag false + isMsgSending = false; + // check if there are pending msgs + while(isMsgHanging) { + // get the msg from outmsgdata[] + // length + target + msg + outmsgleft = outmsgdata[outmsgindex++]; + targetcore = outmsgdata[outmsgindex++]; + calCoords(targetcore, &target_y, &target_x); + // Build the message header + msgHdr = construct_dyn_hdr(0, outmsgleft, 0, // msgsize word sent. + self_y, self_x, + target_y, target_x); + isMsgSending = true; + gdn_send(msgHdr); // Send the message header to EAST to handle fab(n - 1). #ifdef RAWDEBUG - raw_test_pass(0xbbbb); - raw_test_pass(0xb000 + targetcore); // targetcore + raw_test_pass(0xbbbb); + raw_test_pass(0xb000 + targetcore); // targetcore #endif - while(outmsgleft-- > 0) { - gdn_send(outmsgdata[outmsgindex++]); + while(outmsgleft-- > 0) { + gdn_send(outmsgdata[outmsgindex++]); #ifdef RAWDEBUG - raw_test_pass_reg(outmsgdata[outmsgindex - 1]); + raw_test_pass_reg(outmsgdata[outmsgindex - 1]); #endif - } + } #ifdef RAWDEBUG - raw_test_pass(0xffff); + raw_test_pass(0xffff); #endif - isMsgSending = false; + isMsgSending = false; #ifdef INTERRUPT - raw_user_interrupts_off(); -#endif - // check if there are still msg hanging - if(outmsgindex == outmsglast) { - // no more msgs - outmsgindex = outmsglast = 0; - isMsgHanging = false; - } + raw_user_interrupts_off(); +#endif + // check if there are still msg hanging + if(outmsgindex == outmsglast) { + // no more msgs + outmsgindex = outmsglast = 0; + isMsgHanging = false; + } #ifdef INTERRUPT - raw_user_interrupts_on(); + raw_user_interrupts_on(); #endif - } + } #elif defined THREADSIMULATE - int numofcore = pthread_getspecific(key); - int rc = pthread_rwlock_rdlock(&rwlock_tbl); - printf("[releasewritelock, %d] getting the read lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); - if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { - printf("[releasewritelock, %d] Error: try to release a lock without previously grab it\n", numofcore); - exit(-1); - } - pthread_rwlock_t* rwlock_obj = NULL; - RuntimeHashget(locktbl, (int)ptr, (int*)&rwlock_obj); - int rc_obj = pthread_rwlock_unlock(rwlock_obj); - printf("[releasewritelock, %d] unlocked object %d: %d error:\n", numofcore, (int)ptr, rc_obj, strerror(rc_obj)); - rc = pthread_rwlock_unlock(&rwlock_tbl); - printf("[releasewritelock, %d] release the read lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); + int numofcore = pthread_getspecific(key); + int rc = pthread_rwlock_rdlock(&rwlock_tbl); + printf("[releasewritelock, %d] getting the read lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); + if(!RuntimeHashcontainskey(locktbl, (int)ptr)) { + printf("[releasewritelock, %d] Error: try to release a lock without previously grab it\n", numofcore); + exit(-1); + } + pthread_rwlock_t* rwlock_obj = NULL; + RuntimeHashget(locktbl, (int)ptr, (int*)&rwlock_obj); + int rc_obj = pthread_rwlock_unlock(rwlock_obj); + printf("[releasewritelock, %d] unlocked object %d: %d error:\n", numofcore, (int)ptr, rc_obj, strerror(rc_obj)); + rc = pthread_rwlock_unlock(&rwlock_tbl); + printf("[releasewritelock, %d] release the read lock for locktbl: %d error: \n", numofcore, rc, strerror(rc)); #endif } @@ -2831,19 +2843,19 @@ int enqueuetasks(struct parameterwrapper *parameter, struct parameterwrapper *pr struct taskdescriptor * task=parameter->task; - ObjectHashadd(parameter->objectset, (int) ptr, 0, (int) enterflags, numenterflags, enterflags==NULL);//this add the object to parameterwrapper - + ObjectHashadd(parameter->objectset, (int) ptr, 0, (int) enterflags, numenterflags, enterflags==NULL); //this add the object to parameterwrapper + /* Add enqueued object to parameter vector */ taskpointerarray[parameter->slot]=ptr; /* Reset iterators */ - for(j=0;jiterators[j]); } /* Find initial state */ - for(j=0;jiterators[j], taskpointerarray OPTARG(failed))) toiNext(¶meter->iterators[j], taskpointerarray OPTARG(failed)); else if (j>0) { @@ -2857,7 +2869,7 @@ int enqueuetasks(struct parameterwrapper *parameter, struct parameterwrapper *pr } } - + while(1) { /* Enqueue current state */ int launch = 0; @@ -2865,23 +2877,23 @@ int enqueuetasks(struct parameterwrapper *parameter, struct parameterwrapper *pr tpd->task=task; tpd->numParameters=numiterators+1; tpd->parameterArray=RUNMALLOC(sizeof(void *)*(numiterators+1)); - for(j=0;j<=numiterators;j++){ - tpd->parameterArray[j]=taskpointerarray[j];//store the actual parameters + for(j=0; j<=numiterators; j++){ + tpd->parameterArray[j]=taskpointerarray[j]; //store the actual parameters } /* Enqueue task */ - if ((/*!gencontains(failedtasks, tpd)&&*/!gencontains(activetasks,tpd))) { + if ((/*!gencontains(failedtasks, tpd)&&*/ !gencontains(activetasks,tpd))) { genputtable(activetasks, tpd, tpd); } else { RUNFREE(tpd->parameterArray); RUNFREE(tpd); } - + /* This loop iterates to the next parameter combination */ if (numiterators==0) return retval; - for(j=numiterators-1; jiterators[j], taskpointerarray OPTARG(failed))) toiNext(¶meter->iterators[j], taskpointerarray OPTARG(failed)); else if (j>0) { @@ -2910,19 +2922,19 @@ int enqueuetasks_I(struct parameterwrapper *parameter, struct parameterwrapper * struct taskdescriptor * task=parameter->task; - ObjectHashadd_I(parameter->objectset, (int) ptr, 0, (int) enterflags, numenterflags, enterflags==NULL);//this add the object to parameterwrapper - + ObjectHashadd_I(parameter->objectset, (int) ptr, 0, (int) enterflags, numenterflags, enterflags==NULL); //this add the object to parameterwrapper + /* Add enqueued object to parameter vector */ taskpointerarray[parameter->slot]=ptr; /* Reset iterators */ - for(j=0;jiterators[j]); } /* Find initial state */ - for(j=0;jiterators[j], taskpointerarray OPTARG(failed))) toiNext(¶meter->iterators[j], taskpointerarray OPTARG(failed)); else if (j>0) { @@ -2935,7 +2947,7 @@ int enqueuetasks_I(struct parameterwrapper *parameter, struct parameterwrapper * return retval; } } - + while(1) { /* Enqueue current state */ int launch = 0; @@ -2943,23 +2955,23 @@ int enqueuetasks_I(struct parameterwrapper *parameter, struct parameterwrapper * tpd->task=task; tpd->numParameters=numiterators+1; tpd->parameterArray=RUNMALLOC_I(sizeof(void *)*(numiterators+1)); - for(j=0;j<=numiterators;j++){ - tpd->parameterArray[j]=taskpointerarray[j];//store the actual parameters + for(j=0; j<=numiterators; j++){ + tpd->parameterArray[j]=taskpointerarray[j]; //store the actual parameters } /* Enqueue task */ - if ((/*!gencontains(failedtasks, tpd)&&*/!gencontains(activetasks,tpd))) { + if ((/*!gencontains(failedtasks, tpd)&&*/ !gencontains(activetasks,tpd))) { genputtable_I(activetasks, tpd, tpd); } else { RUNFREE(tpd->parameterArray); RUNFREE(tpd); } - + /* This loop iterates to the next parameter combination */ if (numiterators==0) return retval; - for(j=numiterators-1; jiterators[j], taskpointerarray OPTARG(failed))) toiNext(¶meter->iterators[j], taskpointerarray OPTARG(failed)); else if (j>0) { @@ -2988,7 +3000,7 @@ void myhandler(int sig, siginfo_t *info, void *uap) { #endif sigemptyset(&toclear); sigaddset(&toclear, sig); - sigprocmask(SIG_UNBLOCK, &toclear,NULL); + sigprocmask(SIG_UNBLOCK, &toclear,NULL); longjmp(error_handler,1); } #endif @@ -3066,12 +3078,12 @@ void executetasks() { mmap(0, 0x1000, 0, MAP_SHARED|MAP_FIXED|MAP_ANON, -1, 0); #endif - newtask: +newtask: while((hashsize(activetasks)>0)||(maxreadfd>0)) { #ifdef RAW #ifdef RAWDEBUG - raw_test_pass(0xe992); + raw_test_pass(0xe992); #endif #else /* Check if any filedescriptors have IO pending */ @@ -3085,15 +3097,15 @@ void executetasks() { if (numselect>0) { /* Process ready fd's */ int fd; - for(fd=0;fdparameterArray); - RUNFREE(currtpd); - goto newtask; - }*/ + // Free up task parameter descriptor + RUNFREE(currtpd->parameterArray); + RUNFREE(currtpd); + goto newtask; + }*/ numparams=currtpd->task->numParameters; numtotal=currtpd->task->numTotal; - + #ifdef THREADSIMULATE - int isolateflags[numparams]; + int isolateflags[numparams]; #endif /* Make sure that the parameters are still in the queues */ - for(i=0;iparameterArray[i]; #ifdef RAW #ifdef RAWDEBUG raw_test_pass(0xe993); #endif - if(((struct ___Object___ *)parameter)->type == STARTUPTYPE) { - lock = false; - taskpointerarray[i+OFFSET]=parameter; - goto execute; + if(((struct ___Object___ *)parameter)->type == STARTUPTYPE) { + lock = false; + taskpointerarray[i+OFFSET]=parameter; + goto execute; } - lock = true; + lock = true; // require locks for this parameter if it is not a startup object getwritelock(parameter); grount = 0; @@ -3142,16 +3154,16 @@ void executetasks() { raw_user_interrupts_off(); #endif while(!lockflag) { - receiveObject(); + receiveObject(); } #ifndef INTERRUPT if(reside) { - while(receiveObject() != -1) { - } + while(receiveObject() != -1) { + } } #endif grount = lockresult; - + lockresult = 0; lockobj = 0; lockflag = false; @@ -3164,91 +3176,92 @@ void executetasks() { if(grount == 0) { #ifdef RAWDEBUG - raw_test_pass(0xe994); -#endif - // can not get the lock, try later - for(j = 0; j < i; ++j) { - releasewritelock(taskpointerarray[j+OFFSET]); - } - genputtable(activetasks, currtpd, currtpd); - if(hashsize(activetasks) == 1) { - // only one task right now, wait a little while before next try - int halt = 10000; - while(halt--){} - } - goto newtask; + raw_test_pass(0xe994); +#endif + // can not get the lock, try later + for(j = 0; j < i; ++j) { + releasewritelock(taskpointerarray[j+OFFSET]); + } + genputtable(activetasks, currtpd, currtpd); + if(hashsize(activetasks) == 1) { + // only one task right now, wait a little while before next try + int halt = 10000; + while(halt--){ + } + } + goto newtask; } // flush the object { - raw_invalidate_cache_range((int)parameter, classsize[((struct ___Object___ *)parameter)->type]); - /*int tmp = 0; - for(tmp = 0; tmp < classsize[((struct ___Object___ *)parameter)->type]; ++tmp) { - invalidateAddr(parameter + tmp); - }*/ + raw_invalidate_cache_range((int)parameter, classsize[((struct ___Object___ *)parameter)->type]); + /*int tmp = 0; + for(tmp = 0; tmp < classsize[((struct ___Object___ *)parameter)->type]; ++tmp) { + invalidateAddr(parameter + tmp); + }*/ } #endif tmpparam = (struct ___Object___ *)parameter; #ifdef THREADSIMULATE if(((struct ___Object___ *)parameter)->type == STARTUPTYPE) { - lock = false; - taskpointerarray[i+OFFSET]=parameter; - goto execute; + lock = false; + taskpointerarray[i+OFFSET]=parameter; + goto execute; } lock = true; if(0 == tmpparam->isolate) { - isolateflags[i] = 0; - // shared object, need to flush with current value - //if(!getreadlock(tmpparam->original)) { - // // fail to get read lock of the original object, try this task later - if(!getwritelock(tmpparam->original)) { - // fail to get write lock, release all obtained locks and try this task later - int j = 0; - for(j = 0; j < i; ++j) { - if(0 == isolateflags[j]) { - releasewritelock(((struct ___Object___ *)taskpointerarray[j+OFFSET])->original); - } - } - genputtable(activetasks, currtpd, currtpd); - goto newtask; - } - if(tmpparam->version != tmpparam->original->version) { - // some task on another core has changed this object - // flush this object - //memcpy(tmpparam, tmpparam->original, classsize[tmpparam->type]); - // release all obtained locks - int j = 0; - for(j = 0; j < i; ++j) { - if(0 == isolateflags[j]) { - releasewritelock(((struct ___Object___ *)taskpointerarray[j+OFFSET])->original); - } - } - releasewritelock(tmpparam->original); - - // dequeue this object - int numofcore = pthread_getspecific(key); - struct parameterwrapper ** queues = objectqueues[numofcore][tmpparam->type]; - int length = numqueues[numofcore][tmpparam->type]; - for(j = 0; j < length; ++j) { - struct parameterwrapper * pw = queues[j]; - if(ObjectHashcontainskey(pw->objectset, (int)tmpparam)) { - int next; - int UNUSED, UNUSED2; - int * enterflags; - ObjectHashget(pw->objectset, (int) tmpparam, (int *) &next, (int *) &enterflags, &UNUSED, &UNUSED2); - ObjectHashremove(pw->objectset, (int)tmpparam); - if (enterflags!=NULL) - free(enterflags); - } - } - // try to enqueue it again to check if it feeds other tasks; - //enqueueObject(tmpparam, NULL, 0); - // Free up task parameter descriptor - RUNFREE(currtpd->parameterArray); - RUNFREE(currtpd); - goto newtask; - } + isolateflags[i] = 0; + // shared object, need to flush with current value + //if(!getreadlock(tmpparam->original)) { + // // fail to get read lock of the original object, try this task later + if(!getwritelock(tmpparam->original)) { + // fail to get write lock, release all obtained locks and try this task later + int j = 0; + for(j = 0; j < i; ++j) { + if(0 == isolateflags[j]) { + releasewritelock(((struct ___Object___ *)taskpointerarray[j+OFFSET])->original); + } + } + genputtable(activetasks, currtpd, currtpd); + goto newtask; + } + if(tmpparam->version != tmpparam->original->version) { + // some task on another core has changed this object + // flush this object + //memcpy(tmpparam, tmpparam->original, classsize[tmpparam->type]); + // release all obtained locks + int j = 0; + for(j = 0; j < i; ++j) { + if(0 == isolateflags[j]) { + releasewritelock(((struct ___Object___ *)taskpointerarray[j+OFFSET])->original); + } + } + releasewritelock(tmpparam->original); + + // dequeue this object + int numofcore = pthread_getspecific(key); + struct parameterwrapper ** queues = objectqueues[numofcore][tmpparam->type]; + int length = numqueues[numofcore][tmpparam->type]; + for(j = 0; j < length; ++j) { + struct parameterwrapper * pw = queues[j]; + if(ObjectHashcontainskey(pw->objectset, (int)tmpparam)) { + int next; + int UNUSED, UNUSED2; + int * enterflags; + ObjectHashget(pw->objectset, (int) tmpparam, (int *) &next, (int *) &enterflags, &UNUSED, &UNUSED2); + ObjectHashremove(pw->objectset, (int)tmpparam); + if (enterflags!=NULL) + free(enterflags); + } + } + // try to enqueue it again to check if it feeds other tasks; + //enqueueObject(tmpparam, NULL, 0); + // Free up task parameter descriptor + RUNFREE(currtpd->parameterArray); + RUNFREE(currtpd); + goto newtask; + } } else { - isolateflags[i] = 1; + isolateflags[i] = 1; } #endif pd=currtpd->task->descriptorarray[i]; @@ -3257,13 +3270,13 @@ void executetasks() { { if (!ObjectHashcontainskey(pw->objectset, (int) parameter)) { #ifdef RAWDEBUG - raw_test_pass(0xe995); + raw_test_pass(0xe995); #endif - // release grabbed locks - for(j = 0; j < i; ++j) { - releasewritelock(taskpointerarray[j+OFFSET]); - } - releasewritelock(parameter); + // release grabbed locks + for(j = 0; j < i; ++j) { + releasewritelock(taskpointerarray[j+OFFSET]); + } + releasewritelock(parameter); RUNFREE(currtpd->parameterArray); RUNFREE(currtpd); goto newtask; @@ -3272,78 +3285,78 @@ void executetasks() { #ifdef RAW /* Check if the object's flags still meets requirements */ { - int tmpi = 0; - bool ismet = false; - for(tmpi = 0; tmpi < pw->numberofterms; ++tmpi) { - andmask=pw->intarray[tmpi*2]; - checkmask=pw->intarray[tmpi*2+1]; -#ifdef RAWDEBUG - raw_test_pass(0xdd000000 + andmask); - raw_test_pass_reg((int)parameter); - raw_test_pass(0xdd000000 + ((struct ___Object___ *)parameter)->flag); - raw_test_pass(0xdd000000 + checkmask); -#endif - if((((struct ___Object___ *)parameter)->flag&andmask)==checkmask) { - ismet = true; - break; - } - } - if (!ismet) { - // flags are never suitable - // remove this obj from the queue - int next; - int UNUSED, UNUSED2; - int * enterflags; -#ifdef RAWDEBUG - raw_test_pass(0xe996); -#endif - ObjectHashget(pw->objectset, (int) parameter, (int *) &next, (int *) &enterflags, &UNUSED, &UNUSED2); - ObjectHashremove(pw->objectset, (int)parameter); - if (enterflags!=NULL) - free(enterflags); - // release grabbed locks - for(j = 0; j < i; ++j) { - releasewritelock(taskpointerarray[j+OFFSET]); - } - releasewritelock(parameter); - RUNFREE(currtpd->parameterArray); - RUNFREE(currtpd); - goto newtask; - } + int tmpi = 0; + bool ismet = false; + for(tmpi = 0; tmpi < pw->numberofterms; ++tmpi) { + andmask=pw->intarray[tmpi*2]; + checkmask=pw->intarray[tmpi*2+1]; +#ifdef RAWDEBUG + raw_test_pass(0xdd000000 + andmask); + raw_test_pass_reg((int)parameter); + raw_test_pass(0xdd000000 + ((struct ___Object___ *)parameter)->flag); + raw_test_pass(0xdd000000 + checkmask); +#endif + if((((struct ___Object___ *)parameter)->flag&andmask)==checkmask) { + ismet = true; + break; + } + } + if (!ismet) { + // flags are never suitable + // remove this obj from the queue + int next; + int UNUSED, UNUSED2; + int * enterflags; +#ifdef RAWDEBUG + raw_test_pass(0xe996); +#endif + ObjectHashget(pw->objectset, (int) parameter, (int *) &next, (int *) &enterflags, &UNUSED, &UNUSED2); + ObjectHashremove(pw->objectset, (int)parameter); + if (enterflags!=NULL) + free(enterflags); + // release grabbed locks + for(j = 0; j < i; ++j) { + releasewritelock(taskpointerarray[j+OFFSET]); + } + releasewritelock(parameter); + RUNFREE(currtpd->parameterArray); + RUNFREE(currtpd); + goto newtask; + } } #endif - parameterpresent: +parameterpresent: ; /* Check that object still has necessary tags */ - for(j=0;jnumbertags;j++) { + for(j=0; jnumbertags; j++) { int slotid=pd->tagarray[2*j]+numparams; struct ___TagDescriptor___ *tagd=currtpd->parameterArray[slotid]; if (!containstag(parameter, tagd)) { #ifdef RAWDEBUG - raw_test_pass(0xe997); + raw_test_pass(0xe997); #endif RUNFREE(currtpd->parameterArray); RUNFREE(currtpd); goto newtask; } } - + taskpointerarray[i+OFFSET]=parameter; } /* Copy the tags */ - for(;iparameterArray[i]; } #ifdef THREADSIMULATE - for(i = 0; i < numparams; ++i) { - if(0 == isolateflags[i]) { - struct ___Object___ * tmpparam = (struct ___Object___ *)taskpointerarray[i+OFFSET]; - if(tmpparam != tmpparam->original) { - taskpointerarray[i+OFFSET] = tmpparam->original; - } - } + for(i = 0; i < numparams; ++i) { + if(0 == isolateflags[i]) { + struct ___Object___ * tmpparam = (struct ___Object___ *)taskpointerarray[i+OFFSET]; + if(tmpparam != tmpparam->original) { + taskpointerarray[i+OFFSET] = tmpparam->original; } + } + } #endif { @@ -3358,21 +3371,21 @@ void executetasks() { if (x=setjmp(error_handler)) { int counter; /* Recover */ -#ifndef RAW +#ifndef RAW #ifdef DEBUG printf("Fatal Error=%d, Recovering!\n",x); #endif #endif - /* - genputtable(failedtasks,currtpd,currtpd); - //restorecheckpoint(currtpd->task->numParameters, currtpd->parameterArray, checkpoint, forward, reverse); + /* + genputtable(failedtasks,currtpd,currtpd); + //restorecheckpoint(currtpd->task->numParameters, currtpd->parameterArray, checkpoint, forward, reverse); - freeRuntimeHash(forward); - freeRuntimeHash(reverse); - freemalloc(); - forward=NULL; - reverse=NULL; - */ + freeRuntimeHash(forward); + freeRuntimeHash(reverse); + freemalloc(); + forward=NULL; + reverse=NULL; + */ //fflush(stdout); #ifdef RAW #ifdef RAWDEBUG @@ -3384,14 +3397,14 @@ void executetasks() { #endif } 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; + ((int *)taskpointerarray)[0]=currtpd->numParameters; taskpointerarray[1]=NULL; #endif execute: @@ -3399,36 +3412,36 @@ execute: #ifndef RAW printf("ENTER %s count=%d\n",currtpd->task->name, (instaccum-instructioncount)); #endif - ((void (*) (void **)) currtpd->task->taskptr)(taskpointerarray); + ((void(*) (void **))currtpd->task->taskptr)(taskpointerarray); #ifndef RAW printf("EXIT %s count=%d\n",currtpd->task->name, (instaccum-instructioncount)); #endif } else { - ((void (*) (void **)) currtpd->task->taskptr)(taskpointerarray); + ((void(*) (void **))currtpd->task->taskptr)(taskpointerarray); } #ifdef RAWDEBUG raw_test_pass(0xe998); - raw_test_pass_reg(lock); + raw_test_pass_reg(lock); #endif if(lock) { #ifdef RAW - for(i = 0; i < numparams; ++i) { - int j = 0; - struct ___Object___ * tmpparam = (struct ___Object___ *)taskpointerarray[i+OFFSET]; + for(i = 0; i < numparams; ++i) { + int j = 0; + struct ___Object___ * tmpparam = (struct ___Object___ *)taskpointerarray[i+OFFSET]; #ifdef RAWDEBUG - raw_test_pass(0xe999); - raw_test_pass(0xdd100000 + tmpparam->flag); + raw_test_pass(0xe999); + raw_test_pass(0xdd100000 + tmpparam->flag); #endif - releasewritelock(tmpparam); - } + releasewritelock(tmpparam); + } #elif defined THREADSIMULATE - for(i = 0; i < numparams; ++i) { - if(0 == isolateflags[i]) { - struct ___Object___ * tmpparam = (struct ___Object___ *)taskpointerarray[i+OFFSET]; - releasewritelock(tmpparam); - } - } + for(i = 0; i < numparams; ++i) { + if(0 == isolateflags[i]) { + struct ___Object___ * tmpparam = (struct ___Object___ *)taskpointerarray[i+OFFSET]; + releasewritelock(tmpparam); + } + } #endif } @@ -3460,18 +3473,18 @@ execute: } } #ifdef RAWDEBUG - raw_test_pass(0xe999); + raw_test_pass(0xe999); #endif } - + /* This function processes an objects tags */ void processtags(struct parameterdescriptor *pd, int index, struct parameterwrapper *parameter, int * iteratorcount, int *statusarray, int numparams) { int i; - - for(i=0;inumbertags;i++) { + + for(i=0; inumbertags; i++) { int slotid=pd->tagarray[2*i]; int tagid=pd->tagarray[2*i+1]; - + if (statusarray[slotid+numparams]==0) { parameter->iterators[*iteratorcount].istag=1; parameter->iterators[*iteratorcount].tagid=tagid; @@ -3494,7 +3507,7 @@ void processobject(struct parameterwrapper *parameter, int index, struct paramet parameter->iterators[*iteratorcount].objectset=objectset; statusarray[index]=1; - for(i=0;inumbertags;i++) { + for(i=0; inumbertags; i++) { int slotid=pd->tagarray[2*i]; int tagid=pd->tagarray[2*i+1]; if (statusarray[slotid+numparams]!=0) { @@ -3515,21 +3528,21 @@ void builditerators(struct taskdescriptor * task, int index, struct parameterwra int i; int numparams=task->numParameters; int iteratorcount=0; - for(i=0;idescriptorarray[index], index, parameter, & iteratorcount, statusarray, numparams); - + + processtags(task->descriptorarray[index], index, parameter, &iteratorcount, statusarray, numparams); + while(1) { - loopstart: +loopstart: /* Check for objects with existing tags */ - for(i=0;idescriptorarray[i]; int j; - for(j=0;jnumbertags;j++) { + for(j=0; jnumbertags; j++) { int slotid=pd->tagarray[2*j]; if(statusarray[slotid+numparams]!=0) { processobject(parameter, i, pd, &iteratorcount, statusarray, numparams); @@ -3542,7 +3555,7 @@ void builditerators(struct taskdescriptor * task, int index, struct parameterwra /* Next do objects w/ unbound tags*/ - for(i=0;idescriptorarray[i]; if (pd->numbertags>0) { @@ -3555,7 +3568,7 @@ void builditerators(struct taskdescriptor * task, int index, struct parameterwra /* Nothing with a tag enqueued */ - for(i=0;idescriptorarray[i]; processobject(parameter, i, pd, &iteratorcount, statusarray, numparams); @@ -3569,65 +3582,65 @@ void builditerators(struct taskdescriptor * task, int index, struct parameterwra } } - void printdebug() { - int i; - int j; +void printdebug() { + int i; + int j; #ifdef THREADSIMULATE - int numofcore = pthread_getspecific(key); - for(i=0;i NUMCORES - 1) { - return; - } + if(corenum > NUMCORES - 1) { + return; + } #endif - for(i=0;iname); + printf("%s\n", task->name); #endif - for(j=0;jnumParameters;j++) { - struct parameterdescriptor *param=task->descriptorarray[j]; - struct parameterwrapper *parameter=param->queue; - struct ObjectHash * set=parameter->objectset; - struct ObjectIterator objit; + for(j=0; jnumParameters; j++) { + struct parameterdescriptor *param=task->descriptorarray[j]; + struct parameterwrapper *parameter=param->queue; + struct ObjectHash * set=parameter->objectset; + struct ObjectIterator objit; #ifndef RAW - printf(" Parameter %d\n", j); -#endif - 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(" Parameter %d\n", j); +#endif + 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); #ifndef RAW - printf(" Contains %lx\n", obj); - printf(" flag=%d\n", obj->flag); + printf(" Contains %lx\n", obj); + printf(" flag=%d\n", obj->flag); #endif - if (tagptr==NULL) { - } else if (tagptr->type==TAGTYPE) { + if (tagptr==NULL) { + } else if (tagptr->type==TAGTYPE) { #ifndef RAW - printf(" tag=%lx\n",tagptr); + printf(" tag=%lx\n",tagptr); #endif - ; - } else { - int tagindex=0; - struct ArrayObject *ao=(struct ArrayObject *)tagptr; - for(;tagindex___cachedCode___;tagindex++) { + ; + } else { + int tagindex=0; + struct ArrayObject *ao=(struct ArrayObject *)tagptr; + for(; tagindex___cachedCode___; tagindex++) { #ifndef RAW - printf(" tag=%lx\n",ARRAYGET(ao, struct ___TagDescriptor___*, tagindex)); + printf(" tag=%lx\n",ARRAYGET(ao, struct ___TagDescriptor___*, tagindex)); #endif - } - } - } - } - } - } - + } + } + } + } + } +} + /* This function processes the task information to create queues for each parameter type. */ @@ -3635,35 +3648,35 @@ void builditerators(struct taskdescriptor * task, int index, struct parameterwra void processtasks() { int i; #ifdef RAW - if(corenum > NUMCORES - 1) { - return; - } + if(corenum > NUMCORES - 1) { + return; + } #endif #ifdef THREADSIMULATE int numofcore = pthread_getspecific(key); - for(i=0;inumParameters;j++) { + /* Build objectsets */ + for(j=0; jnumParameters; j++) { struct parameterdescriptor *param=task->descriptorarray[j]; struct parameterwrapper *parameter=param->queue; - parameter->objectset=allocateObjectHash(10); - parameter->task=task; + parameter->objectset=allocateObjectHash(10); + parameter->task=task; } /* Build iterators for parameters */ - for(j=0;jnumParameters;j++) { + for(j=0; jnumParameters; j++) { struct parameterdescriptor *param=task->descriptorarray[j]; struct parameterwrapper *parameter=param->queue; builditerators(task, j, parameter); } - } + } } void toiReset(struct tagobjectiterator * it) { @@ -3684,14 +3697,14 @@ int toiHasNext(struct tagobjectiterator *it, void ** objectarray OPTARG(int * fa struct ___Object___ *tagptr=obj->___tags___; if (tagptr->type==TAGTYPE) { if ((it->tagobjindex==0)&& /* First object */ - (it->tagid==((struct ___TagDescriptor___ *)tagptr)->flag)) /* Right tag type */ + (it->tagid==((struct ___TagDescriptor___ *)tagptr)->flag)) /* Right tag type */ return 1; else return 0; } else { struct ArrayObject *ao=(struct ArrayObject *) tagptr; int tagindex=it->tagobjindex; - for(;tagindex___cachedCode___;tagindex++) { + 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 */ @@ -3710,7 +3723,7 @@ int toiHasNext(struct tagobjectiterator *it, void ** objectarray OPTARG(int * fa return 0; if (!ObjectHashcontainskey(it->objectset, (int) objptr)) return 0; - for(i=1;inumtags;i++) { + for(i=1; inumtags; i++) { struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]]; if (!containstag(objptr,tag2)) return 0; @@ -3720,18 +3733,18 @@ int toiHasNext(struct tagobjectiterator *it, void ** objectarray OPTARG(int * fa struct ArrayObject *ao=(struct ArrayObject *) objptr; int tagindex; int i; - for(tagindex=it->tagobjindex;tagindex___cachedCode___;tagindex++) { + 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++) { + for(i=1; inumtags; i++) { struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]]; if (!containstag(objptr,tag2)) goto nexttag; } it->tagobjindex=tagindex; return 1; - nexttag: +nexttag: ; } it->tagobjindex=tagindex; @@ -3747,7 +3760,7 @@ int containstag(struct ___Object___ *ptr, struct ___TagDescriptor___ *tag) { struct ___Object___ * objptr=tag->flagptr; if (objptr->type==OBJECTARRAYTYPE) { struct ArrayObject *ao=(struct ArrayObject *)objptr; - for(j=0;j___cachedCode___;j++) { + for(j=0; j___cachedCode___; j++) { if (ptr==ARRAYGET(ao, struct ___Object___*, j)) return 1; } @@ -3756,7 +3769,7 @@ int containstag(struct ___Object___ *ptr, struct ___TagDescriptor___ *tag) { return objptr==ptr; } -void toiNext(struct tagobjectiterator *it , void ** objectarray OPTARG(int * failed)) { +void toiNext(struct tagobjectiterator *it, void ** objectarray OPTARG(int * failed)) { /* hasNext has all of the intelligence */ if(it->istag) { /* Iterate tag */ diff --git a/Robust/src/Runtime/object.c b/Robust/src/Runtime/object.c index 0bff6175..32547f61 100644 --- a/Robust/src/Runtime/object.c +++ b/Robust/src/Runtime/object.c @@ -75,7 +75,7 @@ int CALL01(___Object______MonitorExit____, struct ___Object___ * ___this___) { pthread_mutex_unlock(&objlock); } else { #ifdef RAW - raw_test_done(-1); + raw_test_done(-1); #else printf("ERROR...UNLOCKING LOCK WE DON'T HAVE\n"); exit(-1); diff --git a/Robust/src/Runtime/object.h b/Robust/src/Runtime/object.h index f0d95d57..7f4cdb15 100644 --- a/Robust/src/Runtime/object.h +++ b/Robust/src/Runtime/object.h @@ -3,7 +3,7 @@ #include "runtime.h" #include "structdefs.h" -int CALL01(___Object______nativehashCode____, struct ___Object___ * ___this___);int CALL01(___Object______getType____, struct ___Object___ * ___this___); +int CALL01(___Object______nativehashCode____, struct ___Object___ * ___this___); int CALL01(___Object______getType____, struct ___Object___ * ___this___); #ifdef THREADS int CALL01(___Object______MonitorEnter____, struct ___Object___ * ___this___); int CALL01(___Object______MonitorExit____, struct ___Object___ * ___this___); diff --git a/Robust/src/Runtime/option.c b/Robust/src/Runtime/option.c index acb5079c..1d673874 100644 --- a/Robust/src/Runtime/option.c +++ b/Robust/src/Runtime/option.c @@ -19,13 +19,13 @@ extern char ** environ; void processOptions() { int i; options=NULL; - for(i=0;environ[i]!=0;i++) { + for(i=0; environ[i]!=0; i++) { if (strncmp(environ[i],"BRISTLECONE=",12)==0) { options=environ[i]+12; break; } } - + while(options!=NULL) { if (strncmp(options,"-injectfailures",sizeof("-injectfailures")-1)==0) { options=strchr(options,' '); diff --git a/Robust/src/Runtime/runtime.c b/Robust/src/Runtime/runtime.c index 0f84c36a..ead07d04 100644 --- a/Robust/src/Runtime/runtime.c +++ b/Robust/src/Runtime/runtime.c @@ -2,9 +2,9 @@ #include "structdefs.h" #include #include "mem.h" -#include -#include -#include +#include +#include +#include #include "option.h" #ifdef DSTM #include "dstm.h" @@ -48,7 +48,7 @@ void injectinstructionfailure() { if (injectinstructionfailures) { if (numfailures==0) return; - instructioncount=failurecount; + instructioncount=failurecount; instaccum+=failurecount; if ((((double)random())/RAND_MAX)0) @@ -92,13 +92,13 @@ long CALL00(___System______currentTimeMillis____) { } void CALL01(___System______printString____L___String___,struct ___String___ * ___s___) { - struct ArrayObject * chararray=VAR(___s___)->___value___; - int i; - int offset=VAR(___s___)->___offset___; - for(i=0;i___count___;i++) { - short sc=((short *)(((char *)& chararray->___length___)+sizeof(int)))[i+offset]; - putchar(sc); - } + struct ArrayObject * chararray=VAR(___s___)->___value___; + int i; + int offset=VAR(___s___)->___offset___; + for(i=0; i___count___; i++) { + short sc=((short *)(((char *)&chararray->___length___)+sizeof(int)))[i+offset]; + putchar(sc); + } } #ifdef DSTM @@ -221,8 +221,9 @@ struct ___String___ * NewString(const char *str,int length) { strobj->___count___=length; strobj->___offset___=0; - for(i=0;i___length___)+sizeof(int)))[i]=(short)str[i]; } + for(i=0; i___length___)+sizeof(int)))[i]=(short)str[i]; + } return strobj; } diff --git a/Robust/src/Runtime/runtime.h b/Robust/src/Runtime/runtime.h index fdad772e..fcc62a61 100644 --- a/Robust/src/Runtime/runtime.h +++ b/Robust/src/Runtime/runtime.h @@ -15,10 +15,10 @@ extern void * curr_heaptop; #define OBJECTARRAYINTERVAL 10 #define ARRAYSET(array, type, index, value) \ -((type *)(&(& array->___length___)[1]))[index]=value + ((type *)(& (& array->___length___)[1]))[index]=value #define ARRAYGET(array, type, index) \ -((type *)(&(& array->___length___)[1]))[index] + ((type *)(& (& array->___length___)[1]))[index] #ifdef OPTIONAL #define OPTARG(x) , x @@ -100,10 +100,10 @@ struct failedtasklist { #ifdef MULTICORE struct transObjInfo { - void * objptr; - int targetcore; - int * queues; - int length; + void * objptr; + int targetcore; + int * queues; + int length; }; #endif @@ -175,7 +175,7 @@ int comparetpd(struct taskparamdescriptor *, struct taskparamdescriptor *); void toiReset(struct tagobjectiterator * it); int toiHasNext(struct tagobjectiterator *it, void ** objectarray OPTARG(int * failed)); -void toiNext(struct tagobjectiterator *it , void ** objectarray OPTARG(int * failed)); +void toiNext(struct tagobjectiterator *it, void ** objectarray OPTARG(int * failed)); void processobject(struct parameterwrapper *parameter, int index, struct parameterdescriptor *pd, int *iteratorcount, int * statusarray, int numparams); void processtags(struct parameterdescriptor *pd, int index, struct parameterwrapper *parameter, int * iteratorcount, int *statusarray, int numparams); void builditerators(struct taskdescriptor * task, int index, struct parameterwrapper * parameter); diff --git a/Robust/src/Runtime/socket.c b/Robust/src/Runtime/socket.c index bb84411d..66f788de 100644 --- a/Robust/src/Runtime/socket.c +++ b/Robust/src/Runtime/socket.c @@ -13,14 +13,14 @@ struct RuntimeHash *fdtoobject; -int CALL24(___Socket______nativeConnect____I__AR_B_I, int ___fd___, int ___port___, struct ___Socket___ * ___this___, int ___fd___, struct ArrayObject * ___address___ ,int ___port___) { +int CALL24(___Socket______nativeConnect____I__AR_B_I, int ___fd___, int ___port___, struct ___Socket___ * ___this___, int ___fd___, struct ArrayObject * ___address___,int ___port___) { #ifdef RAW - // not supported in RAW version - return -1; + // not supported in RAW version + return -1; #else struct sockaddr_in sin; int rc; - + bzero(&sin, sizeof(sin)); sin.sin_family= AF_INET; sin.sin_port=htons(___port___); @@ -39,7 +39,7 @@ int CALL24(___Socket______nativeConnect____I__AR_B_I, int ___fd___, int ___port_ #endif #endif - + if (rc<0) goto error; #ifdef TASK @@ -51,8 +51,8 @@ int CALL24(___Socket______nativeConnect____I__AR_B_I, int ___fd___, int ___port_ #endif return 0; - - error: + +error: close(___fd___); return -1; #endif @@ -61,7 +61,7 @@ int CALL24(___Socket______nativeConnect____I__AR_B_I, int ___fd___, int ___port_ #ifdef TASK int CALL12(___Socket______nativeBindFD____I, int ___fd___, struct ___Socket___ * ___this___, int ___fd___) { if (RuntimeHashcontainskey(fdtoobject, ___fd___)) - RuntimeHashremovekey(fdtoobject, ___fd___); + RuntimeHashremovekey(fdtoobject, ___fd___); RuntimeHashadd(fdtoobject, ___fd___, (int) VAR(___this___)); addreadfd(___fd___); } @@ -70,8 +70,8 @@ int CALL12(___Socket______nativeBindFD____I, int ___fd___, struct ___Socket___ * int CALL12(___Socket______nativeBind_____AR_B_I, int ___port___, struct ArrayObject * ___address___, int ___port___) { #ifdef RAW - // not supported in RAW version - return -1; + // not supported in RAW version + return -1; #else int fd; int rc; @@ -81,7 +81,7 @@ int CALL12(___Socket______nativeBind_____AR_B_I, int ___port___, struct ArrayOb sin.sin_family= AF_INET; sin.sin_port=0; sin.sin_addr.s_addr=INADDR_ANY; - + fd=socket(AF_INET, SOCK_STREAM, 0); if (fd<0) { #ifdef DEBUG @@ -98,7 +98,7 @@ int CALL12(___Socket______nativeBind_____AR_B_I, int ___port___, struct ArrayOb #endif #endif } - + rc = bind(fd, (struct sockaddr *) &sin, sizeof(sin)); if (rc<0) goto error; @@ -108,7 +108,7 @@ int CALL12(___Socket______nativeBind_____AR_B_I, int ___port___, struct ArrayOb return fd; - error: +error: close(fd); #ifdef DEBUG perror(NULL); @@ -128,8 +128,8 @@ int CALL12(___Socket______nativeBind_____AR_B_I, int ___port___, struct ArrayOb struct ArrayObject * CALL01(___InetAddress______getHostByName_____AR_B, struct ArrayObject * ___hostname___) { #ifdef RAW - // not supported in RAW version - return NULL; + // not supported in RAW version + return NULL; #else //struct ArrayObject * CALL01(___InetAddress______getHostByName_____AR_B, struct ___ArrayObject___ * ___hostname___) { int length=VAR(___hostname___)->___length___; @@ -138,21 +138,21 @@ struct ArrayObject * CALL01(___InetAddress______getHostByName_____AR_B, struct A struct hostent *h; struct ArrayObject * arraybytearray; - for(i=0;i___length___)+sizeof(int))[i]; } str[length]=0; h=gethostbyname(str); free(str); - + for (n=0; h->h_addr_list[n]; n++) /* do nothing */ ; - + #ifdef PRECISE_GC arraybytearray=allocate_newarray(___params___,BYTEARRAYARRAYTYPE,n); #else arraybytearray=allocate_newarray(BYTEARRAYARRAYTYPE,n); #endif - for(i=0;i___length___)[1]=ha; } } - + return arraybytearray; #endif } @@ -177,8 +177,8 @@ struct ArrayObject * CALL01(___InetAddress______getHostByName_____AR_B, struct A int CALL12(___ServerSocket______createSocket____I, int port, struct ___ServerSocket___ * ___this___, int port) { #ifdef RAW - // not supported in RAW version - return -1; + // not supported in RAW version + return -1; #else int fd; @@ -187,8 +187,8 @@ int CALL12(___ServerSocket______createSocket____I, int port, struct ___ServerSoc bzero(&sin, sizeof(sin)); sin.sin_family = AF_INET; - sin.sin_port = htons (port); - sin.sin_addr.s_addr = htonl (INADDR_ANY); + sin.sin_port = htons(port); + sin.sin_addr.s_addr = htonl(INADDR_ANY); fd=socket(AF_INET, SOCK_STREAM, 0); if (fd<0) { #ifdef DEBUG @@ -206,7 +206,7 @@ int CALL12(___ServerSocket______createSocket____I, int port, struct ___ServerSoc #endif } - if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, (char *)&n, sizeof (n)) < 0) { + if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&n, sizeof (n)) < 0) { close(fd); #ifdef DEBUG perror(""); @@ -224,10 +224,10 @@ int CALL12(___ServerSocket______createSocket____I, int port, struct ___ServerSoc } #ifdef MAC - if (setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &n, sizeof (n)) < 0) { - perror("socket"); - exit(-1); - } + if (setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &n, sizeof (n)) < 0) { + perror("socket"); + exit(-1); + } #endif #ifdef TASK @@ -236,7 +236,7 @@ int CALL12(___ServerSocket______createSocket____I, int port, struct ___ServerSoc #endif /* bind to port */ - if (bind(fd, (struct sockaddr *) &sin, sizeof(sin))<0) { + if (bind(fd, (struct sockaddr *) &sin, sizeof(sin))<0) { close(fd); #ifdef DEBUG perror(""); @@ -254,8 +254,8 @@ int CALL12(___ServerSocket______createSocket____I, int port, struct ___ServerSoc } /* listen */ - if (listen(fd, 5)<0) { - close (fd); + if (listen(fd, 5)<0) { + close(fd); #ifdef DEBUG perror(""); printf("createSocket error #4\n"); @@ -282,8 +282,8 @@ int CALL12(___ServerSocket______createSocket____I, int port, struct ___ServerSoc int CALL02(___ServerSocket______nativeaccept____L___Socket___,struct ___ServerSocket___ * ___this___, struct ___Socket___ * ___s___) { #ifdef RAW - // not supported in RAW version - return -1; + // not supported in RAW version + return -1; #else struct sockaddr_in sin; unsigned int sinlen=sizeof(sin); @@ -300,7 +300,7 @@ int CALL02(___ServerSocket______nativeaccept____L___Socket___,struct ___ServerSo restartaftergc(tmp); #endif #endif - if (newfd<0) { + if (newfd<0) { #ifdef DEBUG perror(NULL); printf("acceptSocket error #1\n"); @@ -335,7 +335,7 @@ int CALL02(___ServerSocket______nativeaccept____L___Socket___,struct ___ServerSo void CALL24(___Socket______nativeWrite_____AR_B_I_I, int offset, int length, struct ___Socket___ * ___this___, struct ArrayObject * ___b___, int offset, int length) { int fd=VAR(___this___)->___fd___; - char * charstr=((char *)& VAR(___b___)->___length___)+sizeof(int)+offset; + char * charstr=((char *)&VAR(___b___)->___length___)+sizeof(int)+offset; while(1) { int offset=0; int bytewritten; @@ -345,12 +345,12 @@ void CALL24(___Socket______nativeWrite_____AR_B_I_I, int offset, int length, str break; length-=bytewritten; offset+=bytewritten; - } + } if (length!=0) { #ifndef RAW perror("ERROR IN NATIVEWRITE"); - printf("error=%d remaining bytes %d\n",errno, length); + printf("error=%d remaining bytes %d\n",errno, length); #endif } break; @@ -362,7 +362,7 @@ int CALL02(___Socket______nativeRead_____AR_B, struct ___Socket___ * ___this___, int length=VAR(___b___)->___length___; char * charstr=malloc(length); - + #if defined(THREADS)||defined(DSTM) #ifdef PRECISE_GC struct listitem *tmp=stopforgc((struct garbagelist *)___params___); @@ -379,11 +379,11 @@ int CALL02(___Socket______nativeRead_____AR_B, struct ___Socket___ * ___this___, restartaftergc(tmp); #endif #endif - + { int i; - for(i=0;i___length___)+sizeof(int))[i]=charstr[i]; + for(i=0; i___length___)+sizeof(int))[i]=charstr[i]; } free(charstr); } diff --git a/Robust/src/Runtime/task.c b/Robust/src/Runtime/task.c index 57bcbf07..e1430679 100644 --- a/Robust/src/Runtime/task.c +++ b/Robust/src/Runtime/task.c @@ -38,12 +38,12 @@ int main(int argc, char **argv) { processOptions(); initializeexithandler(); /* Create table for failed tasks */ - failedtasks=genallocatehashtable((unsigned int (*)(void *)) &hashCodetpd, - (int (*)(void *,void *)) &comparetpd); + failedtasks=genallocatehashtable((unsigned int(*) (void *)) &hashCodetpd, + (int(*) (void *,void *)) &comparetpd); /* Create queue of active tasks */ - activetasks=genallocatehashtable((unsigned int (*)(void *)) &hashCodetpd, - (int (*)(void *,void *)) &comparetpd); - + activetasks=genallocatehashtable((unsigned int(*) (void *)) &hashCodetpd, + (int(*) (void *,void *)) &comparetpd); + /* Process task information */ processtasks(); @@ -56,28 +56,28 @@ int main(int argc, char **argv) { void createstartupobject(int argc, char ** argv) { int i; - + /* Allocate startup object */ #ifdef PRECISE_GC struct ___StartupObject___ *startupobject=(struct ___StartupObject___*) allocate_new(NULL, STARTUPTYPE); - struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1); + struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1); #else struct ___StartupObject___ *startupobject=(struct ___StartupObject___*) allocate_new(STARTUPTYPE); - struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1); + struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1); #endif /* Build array of strings */ startupobject->___parameters___=stringarray; - for(i=1;i___length___)+sizeof(int)))[i-1]=newstring; + ((void **)(((char *)&stringarray->___length___)+sizeof(int)))[i-1]=newstring; } - - /* Set initialized flag for startup object */ + + /* Set initialized flag for startup object */ flagorand(startupobject,1,0xFFFFFFFF); enqueueObject(startupobject); } @@ -85,7 +85,7 @@ void createstartupobject(int argc, char ** argv) { int hashCodetpd(struct taskparamdescriptor *ftd) { int hash=(int)ftd->task; int i; - for(i=0;inumParameters;i++){ + for(i=0; inumParameters; i++){ hash^=(int)ftd->parameterArray[i]; } return hash; @@ -95,11 +95,11 @@ int comparetpd(struct taskparamdescriptor *ftd1, struct taskparamdescriptor *ftd int i; if (ftd1->task!=ftd2->task) return 0; - for(i=0;inumParameters;i++) + for(i=0; inumParameters; i++) if(ftd1->parameterArray[i]!=ftd2->parameterArray[i]) return 0; #ifdef OPTIONAL - for(i=0;inumParameters;i++) { + for(i=0; inumParameters; i++) { if(ftd1->failed[i]!=ftd2->failed[i]) return 0; } @@ -139,7 +139,7 @@ void tagset(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { /* Array Case */ int i; struct ArrayObject *ao=(struct ArrayObject *) tagptr; - for(i=0;i___cachedCode___;i++) { + for(i=0; i___cachedCode___; i++) { struct ___TagDescriptor___ * td=ARRAYGET(ao, struct ___TagDescriptor___*, i); if (td==tagd) return; @@ -158,7 +158,7 @@ void tagset(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { struct ArrayObject * aonew=allocate_newarray(TAGARRAYTYPE,TAGARRAYINTERVAL+ao->___length___); #endif aonew->___cachedCode___=ao->___length___+1; - for(i=0;i___length___;i++) { + for(i=0; i___length___; i++) { ARRAYSET(aonew, struct ___TagDescriptor___*, i, ARRAYGET(ao, struct ___TagDescriptor___*, i)); } ARRAYSET(aonew, struct ___TagDescriptor___ *, ao->___length___, tagd); @@ -199,7 +199,7 @@ void tagset(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { struct ArrayObject * aonew=allocate_newarray(OBJECTARRAYTYPE,OBJECTARRAYINTERVAL); #endif aonew->___cachedCode___=ao->___cachedCode___+1; - for(i=0;i___length___;i++) { + for(i=0; i___length___; i++) { ARRAYSET(aonew, struct ___Object___*, i, ARRAYGET(ao, struct ___Object___*, i)); } ARRAYSET(aonew, struct ___Object___ *, ao->___cachedCode___, obj); @@ -227,7 +227,7 @@ void tagclear(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { } else { struct ArrayObject *ao=(struct ArrayObject *) tagptr; int i; - for(i=0;i___cachedCode___;i++) { + for(i=0; i___cachedCode___; i++) { struct ___TagDescriptor___ * td=ARRAYGET(ao, struct ___TagDescriptor___ *, i); if (td==tagd) { ao->___cachedCode___--; @@ -241,7 +241,7 @@ void tagclear(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { } printf("ERROR 2 in tagclear\n"); } - PROCESSCLEAR: +PROCESSCLEAR: { struct ___Object___ *tagset=tagd->flagptr; if (tagset->type!=OBJECTARRAYTYPE) { @@ -252,7 +252,7 @@ void tagclear(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { } else { struct ArrayObject *ao=(struct ArrayObject *) tagset; int i; - for(i=0;i___cachedCode___;i++) { + for(i=0; i___cachedCode___; i++) { struct ___Object___ * tobj=ARRAYGET(ao, struct ___Object___ *, i); if (tobj==obj) { ao->___cachedCode___--; @@ -267,10 +267,10 @@ void tagclear(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) { printf("ERROR 4 in tagclear\n"); } } - ENDCLEAR: +ENDCLEAR: return; } - + /* This function allocates a new tag. */ #ifdef PRECISE_GC struct ___TagDescriptor___ * allocate_tag(void *ptr, int index) { @@ -282,7 +282,7 @@ struct ___TagDescriptor___ * allocate_tag(int index) { v->type=TAGTYPE; v->flag=index; return v; -} +} @@ -293,68 +293,66 @@ void flagbody(struct ___Object___ *ptr, int flag); #ifdef OPTIONAL void enqueueoptional(struct ___Object___ * currobj, int numfailedfses, int * failedfses, struct taskdescriptor * task, int index); #endif - - int flagcomp(const int *val1, const int *val2) { - return (*val1)-(*val2); - } + +int flagcomp(const int *val1, const int *val2) { + return (*val1)-(*val2); +} void flagorand(void * ptr, int ormask, int andmask) { #ifdef OPTIONAL struct ___Object___ * obj = (struct ___Object___ *)ptr; - if(obj->numfses){/*store the information about fses*/ + if(obj->numfses){ /*store the information about fses*/ int flag, i, j,counter, offset=0; - for(i=0;inumfses;i++) { + for(i=0; inumfses; i++) { int oldoffset; counter=obj->fses[offset++]; oldoffset=offset; - for(j=0;jfses[offset]; obj->fses[offset++]=(flag|ormask)&andmask; } - qsort(&obj->fses[oldoffset], sizeof(int), counter, (int (*)(const void *, const void *)) &flagcomp); + qsort(&obj->fses[oldoffset], sizeof(int), counter, (int(*) (const void *, const void *)) &flagcomp); } enqueueoptional(obj, 0, NULL, NULL, 0); - } - else + } else #endif - { - int oldflag=((int *)ptr)[1]; - int flag=ormask|oldflag; - flag&=andmask; - flagbody(ptr, flag); - } + { + int oldflag=((int *)ptr)[1]; + int flag=ormask|oldflag; + flag&=andmask; + flagbody(ptr, flag); + } } - + bool intflagorand(void * ptr, int ormask, int andmask) { #ifdef OPTIONAL struct ___Object___ * obj = (struct ___Object___ *)ptr; - if(obj->numfses) {/*store the information about fses*/ + if(obj->numfses) { /*store the information about fses*/ int flag, i, j,counter, offset=0; - for(i=0;inumfses;i++) { + for(i=0; inumfses; i++) { int oldoffset; counter=obj->fses[offset++]; oldoffset=offset; - for(j=0;jfses[offset]; obj->fses[offset++]=(flag|ormask)&andmask; } - qsort(&obj->fses[oldoffset], sizeof(int), counter, (int (*)(const void *, const void *)) &flagcomp); + qsort(&obj->fses[oldoffset], sizeof(int), counter, (int(*) (const void *, const void *)) &flagcomp); } enqueueoptional(obj, 0, NULL, NULL, 0); - } - else + } else #endif - { - int oldflag=((int *)ptr)[1]; - int flag=ormask|oldflag; - flag&=andmask; - if (flag==oldflag) /* Don't do anything */ - return false; - else { - flagbody(ptr, flag); - return true; - } + { + int oldflag=((int *)ptr)[1]; + int flag=ormask|oldflag; + flag&=andmask; + if (flag==oldflag) /* Don't do anything */ + return false; + else { + flagbody(ptr, flag); + return true; } + } } void flagorandinit(void * ptr, int ormask, int andmask) { @@ -367,7 +365,7 @@ void flagorandinit(void * ptr, int ormask, int andmask) { void flagbody(struct ___Object___ *ptr, int flag) { struct parameterwrapper *flagptr=(struct parameterwrapper *)ptr->flagptr; ptr->flag=flag; - + /*Remove object from all queues */ while(flagptr!=NULL) { struct parameterwrapper *next; @@ -379,53 +377,53 @@ void flagbody(struct ___Object___ *ptr, int flag) { free(enterflags); flagptr=next; } - } +} + +void enqueueObject(void *vptr) { + struct ___Object___ *ptr = (struct ___Object___ *)vptr; - void enqueueObject(void *vptr) { - struct ___Object___ *ptr = (struct ___Object___ *)vptr; - { struct QueueItem *tmpptr; struct parameterwrapper * parameter=objectqueues[ptr->type]; int i; struct parameterwrapper * prevptr=NULL; struct ___Object___ *tagptr=ptr->___tags___; - + /* Outer loop iterates through all parameter queues an object of this type could be in. */ - + 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 + 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++) { + 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 + goto nextloop; /*We don't have this tag */ + } + } else { //multiple tags struct ArrayObject * ao=(struct ArrayObject *) tagptr; - for(i=0;inumbertags;i++) { + 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++) { + for(j=0; j___cachedCode___; j++) { if (tagid==ARRAYGET(ao, struct ___TagDescriptor___*, j)->flag) goto foundtag; } goto nextloop; - foundtag: +foundtag: ; } } } - + /* Check flags */ - for(i=0;inumberofterms;i++) { + for(i=0; inumberofterms; i++) { int andmask=parameter->intarray[i*2]; int checkmask=parameter->intarray[i*2+1]; if ((ptr->flag&andmask)==checkmask) { @@ -434,7 +432,7 @@ void flagbody(struct ___Object___ *ptr, int flag) { break; } } - nextloop: +nextloop: parameter=parameter->next; } ptr->flagptr=prevptr; @@ -450,8 +448,8 @@ int checktags(struct ___Object___ * currobj, struct fsanalysiswrapper * fswrappe if (tagptr==NULL) return 0; //that means the object has no tag but that param //needs tag - else if(tagptr->type==TAGTYPE) {//one tag - if(fswrapper->numtags!=1) + else if(tagptr->type==TAGTYPE) { //one tag + if(fswrapper->numtags!=1) return 0; //we don't have the right number of tags struct ___TagDescriptor___ * tag=(struct ___TagDescriptor___*) tagptr; if (fswrapper->tags[0]!=tagptr->flag) @@ -460,13 +458,13 @@ int checktags(struct ___Object___ * currobj, struct fsanalysiswrapper * fswrappe 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 - for(tag_counter=0;tag_counternumtags;tag_counter++) { + + if(ao->___length___!=fswrapper->numtags) + 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++) { + for(j=0; j___cachedCode___; j++) { if (tagid==ARRAYGET(ao, struct ___TagDescriptor___*, tag_counter)->flag) return 1; } @@ -480,7 +478,7 @@ int checktags(struct ___Object___ * currobj, struct fsanalysiswrapper * fswrappe int getlength(int *flist, int len) { int count=0; int i; - for(i=0;inumflags;i++) { + for(i=0; inumflags; i++) { int len=ftl->flags[offset++]; int offsetmerge=0; - for(j=0;jnumflags;j++) { + for(j=0; jnumflags; j++) { int lenmerge=ftlmerge->flags[offsetmerge++]; length+=1+domerge(&ftl->flags[offset],len,&ftlmerge->flags[offsetmerge],lenmerge, NULL); offsetmerge+=lenmerge; @@ -542,13 +540,13 @@ void mergeitems(struct failedtasklist *ftl, struct failedtasklist *ftlmerge) { offset+=len; } mergedlist=RUNMALLOC(sizeof(int)*length); - + offset=0; length=0; - for(i=0;inumflags;i++) { + for(i=0; inumflags; i++) { int len=ftl->flags[offset++]; int offsetmerge=0; - for(j=0;jnumflags;j++) { + for(j=0; jnumflags; j++) { int lenmerge=ftlmerge->flags[offsetmerge++]; int size=domerge(&ftl->flags[offset],len,&ftlmerge->flags[offsetmerge],lenmerge,&mergedlist[length+1]); mergedlist[length]=size; @@ -566,7 +564,7 @@ void mergefailedlists(struct failedtasklist **andlist, struct failedtasklist *li struct failedtasklist *searchftl=list; while(searchftl!=NULL) { if ((*andlist)->task==searchftl->task&& - (*andlist)->index==searchftl->index) { + (*andlist)->index==searchftl->index) { mergeitems(*andlist, searchftl); break; } @@ -575,7 +573,7 @@ void mergefailedlists(struct failedtasklist **andlist, struct failedtasklist *li if (searchftl==NULL) { //didn't find andlist tmpptr=*andlist; - *andlist=(*andlist)->next;//splice item out of list + *andlist=(*andlist)->next; //splice item out of list RUNFREE(tmpptr->flags); //free the item RUNFREE(tmpptr); } else { @@ -595,7 +593,7 @@ struct failedtasklist * processfailstate(struct classanalysiswrapper * classwrap struct failedtasklist *list=NULL; int i,h; struct fsanalysiswrapper *fswrapper=NULL; - for(h=0;hnumfsanalysiswrappers;h++) { + for(h=0; hnumfsanalysiswrappers; h++) { struct fsanalysiswrapper * tmp=classwrapper->fsanalysiswrapperarray[h]; if (tmp->flags==flagstate&&checktags(currobj, tmp)) { //we only match exactly here @@ -605,7 +603,7 @@ struct failedtasklist * processfailstate(struct classanalysiswrapper * classwrap } if (fswrapper==NULL) return list; - for(i=0;inumtaskfailures;i++) { + for(i=0; inumtaskfailures; i++) { int j; struct taskfailure * taskfail=fswrapper->taskfailurearray[i]; if (taskfail->task==task&&taskfail->index==index) { @@ -618,7 +616,7 @@ struct failedtasklist * processfailstate(struct classanalysiswrapper * classwrap int *enterflags; int numenterflags, offset; struct parameterwrapper *pw; - for(j=start;jnumoptionaltaskdescriptors;j++) { + for(j=start; jnumoptionaltaskdescriptors; j++) { struct optionaltaskdescriptor *otd=taskfail->optionaltaskdescriptorarray[j]; if(currtask==NULL) { currtask=otd->task; @@ -631,7 +629,7 @@ struct failedtasklist * processfailstate(struct classanalysiswrapper * classwrap 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)); @@ -654,7 +652,7 @@ struct failedtasklist * processnormfailstate(struct classanalysiswrapper * class int i,h; int start=0; struct fsanalysiswrapper *fswrapper=NULL; - for(h=0;hnumfsanalysiswrappers;h++) { + for(h=0; hnumfsanalysiswrappers; h++) { struct fsanalysiswrapper * tmp=classwrapper->fsanalysiswrapperarray[h]; if (tmp->flags==flagstate&&checktags(currobj, tmp)) { //we only match exactly here @@ -674,7 +672,7 @@ struct failedtasklist * processnormfailstate(struct classanalysiswrapper * class int *enterflags; int numenterflags, offset; struct parameterwrapper *pw; - for(j=start;jnumoptionaltaskdescriptors;j++) { + for(j=start; jnumoptionaltaskdescriptors; j++) { struct optionaltaskdescriptor *otd=fswrapper->optionaltaskdescriptorarray[j]; if(currtask==NULL) { currtask=otd->task; @@ -687,7 +685,7 @@ struct failedtasklist * processnormfailstate(struct classanalysiswrapper * class 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)); @@ -713,26 +711,26 @@ void enqueuelist(struct ___Object___ * currobj, struct failedtasklist * andlist) int * flags; int numflags; int isnonfailed; - + if (enqueuetasks(pw, currobj->flagptr, currobj, tmp->flags, tmp->numflags)) currobj->flagptr=pw; - + andlist=andlist->next; RUNFREE(tmp); } } void enqueueoptional(struct ___Object___ * currobj, int numfailedfses, int * failedfses, struct taskdescriptor * task, int index) { - struct classanalysiswrapper * classwrapper=NULL; - + struct classanalysiswrapper * classwrapper=NULL; + /*test what optionaltaskdescriptors are available, find the class - corresponding*/ + corresponding*/ if (classanalysiswrapperarray[currobj->type]!=NULL) { classwrapper = classanalysiswrapperarray[currobj->type]; } else return; - - if(task!=NULL) { + + if(task!=NULL) { /* We have a failure */ if (failedfses==NULL) { /* Failed in normal state */ @@ -740,7 +738,7 @@ void enqueueoptional(struct ___Object___ * currobj, int numfailedfses, int * fai int i,h; struct fsanalysiswrapper *fswrapper=NULL; - for(h=0;hnumfsanalysiswrappers;h++) { + for(h=0; hnumfsanalysiswrappers; h++) { struct fsanalysiswrapper * tmp=classwrapper->fsanalysiswrapperarray[h]; if (tmp->flags==currobj->flag&&checktags(currobj, tmp)) { //we only match exactly here @@ -750,7 +748,7 @@ void enqueueoptional(struct ___Object___ * currobj, int numfailedfses, int * fai } if(fswrapper==NULL) //nothing to do in this state return; - for(i=0;inumtaskfailures;i++) { + for(i=0; inumtaskfailures; i++) { int j; struct taskfailure * taskfail=fswrapper->taskfailurearray[i]; if (taskfail->task==task&&taskfail->index==index) { @@ -762,21 +760,21 @@ void enqueueoptional(struct ___Object___ * currobj, int numfailedfses, int * fai int *enterflags; int numenterflags, offset; struct parameterwrapper *pw; - for(j=start;jnumoptionaltaskdescriptors;j++) { + 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 + totallength+=otd->numenterflags; //1 is to store the lengths } pw=currtask->descriptorarray[currindex]->queue; enterflags=RUNMALLOC((totallength+numenterflags)*sizeof(int)); numenterflags=j-start; offset=0; - for(start;startoptionaltaskdescriptorarray[start]; enterflags[offset++]=otd->numenterflags; memcpy(&enterflags[offset], otd->enterflags, otd->numenterflags*sizeof(int)); @@ -792,11 +790,11 @@ void enqueueoptional(struct ___Object___ * currobj, int numfailedfses, int * fai /* Failed in failed state */ int i; int offset=0; - for(i=0;inumfses;i++) { + for(i=0; inumfses; i++) { int numfses=currobj->fses[offset++]; int j; struct failedtasklist *andlist=NULL; - for(j=0;jfses[offset++]; struct failedtasklist *currlist=processnormfailstate(classwrapper, currobj, flagstate); if (andlist==NULL) @@ -841,11 +839,11 @@ void enqueueoptional(struct ___Object___ * currobj, int numfailedfses, int * fai enqueuelist(currobj, andlist); } } -} - - +} + + #endif - + int enqueuetasks(struct parameterwrapper *parameter, struct parameterwrapper *prevptr, struct ___Object___ *ptr, int * enterflags, int numenterflags) { void * taskpointerarray[MAXTASKPARAMS]; #ifdef OPTIONAL @@ -860,7 +858,7 @@ int enqueuetasks(struct parameterwrapper *parameter, struct parameterwrapper *pr struct taskdescriptor * task=parameter->task; -#ifdef OPTIONAL +#ifdef OPTIONAL if (ObjectHashcontainskey(parameter->objectset, (int) ptr)) { /* The object is already here...or it with the existing item */ int * oldflags; @@ -868,7 +866,7 @@ int enqueuetasks(struct parameterwrapper *parameter, struct parameterwrapper *pr int oldptr; int oldstatus; int *mergedflags; - ObjectHashget(parameter->objectset, (int) ptr, & oldptr, (int *) &oldflags, &oldnumflags, &oldstatus); + ObjectHashget(parameter->objectset, (int) ptr, &oldptr, (int *) &oldflags, &oldnumflags, &oldstatus); mergedflags=domergeor(oldflags, oldnumflags, enterflags, numenterflags); ObjectHashupdate(parameter->objectset, (int) ptr, oldptr, mergedflags, oldnumflags+numenterflags, oldstatus||(enterflags==NULL)); @@ -884,11 +882,11 @@ int enqueuetasks(struct parameterwrapper *parameter, struct parameterwrapper *pr retval=0; } else { #endif - ObjectHashadd(parameter->objectset, (int) ptr, (int) prevptr, (int) enterflags, numenterflags, enterflags==NULL);//this add the object to parameterwrapper + ObjectHashadd(parameter->objectset, (int) ptr, (int) prevptr, (int) enterflags, numenterflags, enterflags==NULL); //this add the object to parameterwrapper #ifdef OPTIONAL - } +} #endif - + /* Add enqueued object to parameter vector */ taskpointerarray[parameter->slot]=ptr; #ifdef OPTIONAL @@ -896,17 +894,16 @@ int enqueuetasks(struct parameterwrapper *parameter, struct parameterwrapper *pr #endif /* Reset iterators */ - for(j=0;jiterators[j]); } /* Find initial state */ - for(j=0;jiterators[j], taskpointerarray OPTARG(failed))){ toiNext(¶meter->iterators[j], taskpointerarray OPTARG(failed)); - } - else if (j>0) { + } else if (j>0) { /* Need to backtrack */ toiReset(¶meter->iterators[j]); j--; @@ -917,7 +914,7 @@ int enqueuetasks(struct parameterwrapper *parameter, struct parameterwrapper *pr } } - + while(1) { /* Enqueue current state */ int launch = 0; @@ -928,8 +925,8 @@ int enqueuetasks(struct parameterwrapper *parameter, struct parameterwrapper *pr #ifdef OPTIONAL tpd->failed=RUNMALLOC(sizeof(int)*(numiterators+1)); #endif - for(j=0;j<=numiterators;j++){ - tpd->parameterArray[j]=taskpointerarray[j];//store the actual parameters + for(j=0; j<=numiterators; j++){ + tpd->parameterArray[j]=taskpointerarray[j]; //store the actual parameters #ifdef OPTIONAL tpd->failed[j]=failed[j]; if (failed[j]!=0&&failed[j]!=1) { @@ -952,12 +949,11 @@ int enqueuetasks(struct parameterwrapper *parameter, struct parameterwrapper *pr if (numiterators==0) return retval; - for(j=numiterators-1; jiterators[j], taskpointerarray OPTARG(failed))){ toiNext(¶meter->iterators[j], taskpointerarray OPTARG(failed)); - } - else if (j>0) { + } else if (j>0) { /* Need to backtrack */ toiReset(¶meter->iterators[j]); j--; @@ -970,7 +966,7 @@ int enqueuetasks(struct parameterwrapper *parameter, struct parameterwrapper *pr } return retval; } - + /* Handler for signals. The signals catch null pointer errors and arithmatic errors. */ @@ -982,7 +978,7 @@ void myhandler(int sig, siginfo_t *info, void *uap) { #endif sigemptyset(&toclear); sigaddset(&toclear, sig); - sigprocmask(SIG_UNBLOCK, &toclear,NULL); + sigprocmask(SIG_UNBLOCK, &toclear,NULL); longjmp(error_handler,1); } @@ -1012,14 +1008,14 @@ void removereadfd(int fd) { #endif #ifdef OPTIONAL - int * fsescopy(int *src, int len) { - int *dst; - if (src==NULL) - return NULL; - dst=RUNMALLOC(len*sizeof(int)); - memcpy(dst, src, len*sizeof(int)); - return dst; - } +int * fsescopy(int *src, int len) { + int *dst; + if (src==NULL) + return NULL; + dst=RUNMALLOC(len*sizeof(int)); + memcpy(dst, src, len*sizeof(int)); + return dst; +} #endif void executetasks() { @@ -1028,7 +1024,7 @@ void executetasks() { int * fsesarray[MAXTASKPARAMS]; int * oldfsesarray[MAXTASKPARAMS]; int numfsesarray[MAXTASKPARAMS]; -#endif +#endif /* Set up signal handlers */ struct sigaction sig; @@ -1050,7 +1046,7 @@ void executetasks() { /* Map first block of memory to protected, anonymous page */ mmap(0, 0x1000, 0, MAP_SHARED|MAP_FIXED|MAP_ANON, -1, 0); - newtask: +newtask: while((hashsize(activetasks)>0)||(maxreadfd>0)) { /* Check if any filedescriptors have IO pending */ @@ -1064,15 +1060,15 @@ void executetasks() { if (numselect>0) { /* Process ready fd's */ int fd; - for(fd=0;fdtask->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; @@ -1142,10 +1138,10 @@ void executetasks() { } } #endif - parameterpresent: +parameterpresent: ; /* Check that object still has necessary tags */ - for(j=0;jnumbertags;j++) { + for(j=0; jnumbertags; j++) { int slotid=pd->tagarray[2*j]+numparams; struct ___TagDescriptor___ *tagd=currtpd->parameterArray[slotid]; if (!containstag(parameter, tagd)) { @@ -1157,11 +1153,11 @@ void executetasks() { goto newtask; } } - + taskpointerarray[i+OFFSET]=parameter; } /* Copy the tags */ - for(;iparameterArray[i]; } @@ -1204,32 +1200,32 @@ void executetasks() { } /* Actually call task */ #ifdef PRECISE_GC - ((int *)taskpointerarray)[0]=currtpd->numParameters; + ((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]; + ((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); + ((void(*) (void **))currtpd->task->taskptr)(taskpointerarray); printf("EXIT %s count=%d\n",currtpd->task->name, (instaccum-instructioncount)); } else - ((void (*) (void **)) currtpd->task->taskptr)(taskpointerarray); + ((void(*) (void **))currtpd->task->taskptr)(taskpointerarray); #ifdef OPTIONAL - for(i=0;inumbertags;i++) { + + for(i=0; inumbertags; i++) { int slotid=pd->tagarray[2*i]; int tagid=pd->tagarray[2*i+1]; - + if (statusarray[slotid+numparams]==0) { parameter->iterators[*iteratorcount].istag=1; parameter->iterators[*iteratorcount].tagid=tagid; @@ -1277,7 +1273,7 @@ void processobject(struct parameterwrapper *parameter, int index, struct paramet parameter->iterators[*iteratorcount].objectset=objectset; statusarray[index]=1; - for(i=0;inumbertags;i++) { + for(i=0; inumbertags; i++) { int slotid=pd->tagarray[2*i]; int tagid=pd->tagarray[2*i+1]; if (statusarray[slotid+numparams]!=0) { @@ -1298,21 +1294,21 @@ void builditerators(struct taskdescriptor * task, int index, struct parameterwra int i; int numparams=task->numParameters; int iteratorcount=0; - for(i=0;idescriptorarray[index], index, parameter, & iteratorcount, statusarray, numparams); - + + processtags(task->descriptorarray[index], index, parameter, &iteratorcount, statusarray, numparams); + while(1) { - loopstart: +loopstart: /* Check for objects with existing tags */ - for(i=0;idescriptorarray[i]; int j; - for(j=0;jnumbertags;j++) { + for(j=0; jnumbertags; j++) { int slotid=pd->tagarray[2*j]; if(statusarray[slotid+numparams]!=0) { processobject(parameter, i, pd, &iteratorcount, statusarray, numparams); @@ -1325,7 +1321,7 @@ void builditerators(struct taskdescriptor * task, int index, struct parameterwra /* Next do objects w/ unbound tags*/ - for(i=0;idescriptorarray[i]; if (pd->numbertags>0) { @@ -1338,7 +1334,7 @@ void builditerators(struct taskdescriptor * task, int index, struct parameterwra /* Nothing with a tag enqueued */ - for(i=0;idescriptorarray[i]; processobject(parameter, i, pd, &iteratorcount, statusarray, numparams); @@ -1352,59 +1348,59 @@ void builditerators(struct taskdescriptor * task, int index, struct parameterwra } } - void printdebug() { - int i; - int j; - for(i=0;iname); - for(j=0;jnumParameters;j++) { - struct parameterdescriptor *param=task->descriptorarray[j]; - struct parameterwrapper *parameter=param->queue; - struct ObjectHash * set=parameter->objectset; - struct ObjectIterator objit; - 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); +void printdebug() { + int i; + int j; + for(i=0; iname); + for(j=0; jnumParameters; j++) { + struct parameterdescriptor *param=task->descriptorarray[j]; + struct parameterwrapper *parameter=param->queue; + struct ObjectHash * set=parameter->objectset; + struct ObjectIterator objit; + 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); #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)); + } + } + } + } + } +} + /* This function processes the task information to create queues for each parameter type. */ void processtasks() { int i; - for(i=0;inumParameters;j++) { + for(j=0; jnumParameters; j++) { struct parameterdescriptor *param=task->descriptorarray[j]; struct parameterwrapper * parameter=RUNMALLOC(sizeof(struct parameterwrapper)); struct parameterwrapper ** ptr=&objectqueues[param->type]; @@ -1416,7 +1412,7 @@ void processtasks() { parameter->numbertags=param->numbertags; parameter->tagarray=param->tagarray; parameter->task=task; - parameter->slot=j; + parameter->slot=j; /* Link new queue in */ while((*ptr)!=NULL) ptr=&((*ptr)->next); @@ -1424,7 +1420,7 @@ void processtasks() { } /* Build iterators for parameters */ - for(j=0;jnumParameters;j++) { + for(j=0; jnumParameters; j++) { struct parameterdescriptor *param=task->descriptorarray[j]; struct parameterwrapper *parameter=param->queue; builditerators(task, j, parameter); @@ -1456,14 +1452,14 @@ int toiHasNext(struct tagobjectiterator *it, void ** objectarray OPTARG(int * fa struct ___Object___ *tagptr=obj->___tags___; if (tagptr->type==TAGTYPE) { if ((it->tagobjindex==0)&& /* First object */ - (it->tagid==((struct ___TagDescriptor___ *)tagptr)->flag)) /* Right tag type */ + (it->tagid==((struct ___TagDescriptor___ *)tagptr)->flag)) /* Right tag type */ return 1; else return 0; } else { struct ArrayObject *ao=(struct ArrayObject *) tagptr; int tagindex=it->tagobjindex; - for(;tagindex___cachedCode___;tagindex++) { + 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 */ @@ -1482,7 +1478,7 @@ int toiHasNext(struct tagobjectiterator *it, void ** objectarray OPTARG(int * fa return 0; if (!ObjectHashcontainskey(it->objectset, (int) objptr)) return 0; - for(i=1;inumtags;i++) { + for(i=1; inumtags; i++) { struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]]; if (!containstag(objptr,tag2)) return 0; @@ -1510,7 +1506,7 @@ int toiHasNext(struct tagobjectiterator *it, void ** objectarray OPTARG(int * fa } return 1; } -#endif +#endif return 1; } else { struct ArrayObject *ao=(struct ArrayObject *) objptr; @@ -1531,11 +1527,11 @@ int toiHasNext(struct tagobjectiterator *it, void ** objectarray OPTARG(int * fa } } #endif - for(tagindex=it->tagobjindex;tagindex___cachedCode___;tagindex++) { + 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++) { + for(i=1; inumtags; i++) { struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]]; if (!containstag(objptr,tag2)) goto nexttag; @@ -1553,7 +1549,7 @@ int toiHasNext(struct tagobjectiterator *it, void ** objectarray OPTARG(int * fa #endif it->tagobjindex=tagindex; return 1; - nexttag: +nexttag: ; } it->tagobjindex=tagindex; @@ -1588,7 +1584,7 @@ int containstag(struct ___Object___ *ptr, struct ___TagDescriptor___ *tag) { struct ___Object___ * objptr=tag->flagptr; if (objptr->type==OBJECTARRAYTYPE) { struct ArrayObject *ao=(struct ArrayObject *)objptr; - for(j=0;j___cachedCode___;j++) { + for(j=0; j___cachedCode___; j++) { if (ptr==ARRAYGET(ao, struct ___Object___*, j)) return 1; } @@ -1597,7 +1593,7 @@ int containstag(struct ___Object___ *ptr, struct ___TagDescriptor___ *tag) { return objptr==ptr; } -void toiNext(struct tagobjectiterator *it , void ** objectarray OPTARG(int * failed)) { +void toiNext(struct tagobjectiterator *it, void ** objectarray OPTARG(int * failed)) { /* hasNext has all of the intelligence */ if(it->istag) { /* Iterate tag */ @@ -1620,14 +1616,14 @@ void toiNext(struct tagobjectiterator *it , void ** objectarray OPTARG(int * fai struct ___Object___ *objptr=tag->flagptr; if (objptr->type!=OBJECTARRAYTYPE) { #ifdef OPTIONAL - failed[it->slot]=it->failedstate; - objectarray[it->slot]=objptr; - if (it->failedstate==0) { - it->failedstate=1; - } else { - it->failedstate=0; - it->tagobjindex++; - } + failed[it->slot]=it->failedstate; + objectarray[it->slot]=objptr; + if (it->failedstate==0) { + it->failedstate=1; + } else { + it->failedstate=0; + it->tagobjindex++; + } #else it->tagobjindex++; objectarray[it->slot]=objptr; @@ -1635,21 +1631,21 @@ void toiNext(struct tagobjectiterator *it , void ** objectarray OPTARG(int * fai } else { struct ArrayObject *ao=(struct ArrayObject *) objptr; #ifdef OPTIONAL - failed[it->slot]=it->failedstate; - objectarray[it->slot]=ARRAYGET(ao, struct ___Object___ *, it->tagobjindex); - if (it->failedstate==0) { - it->failedstate=1; - } else { - it->failedstate=0; - it->tagobjindex++; - } + failed[it->slot]=it->failedstate; + objectarray[it->slot]=ARRAYGET(ao, struct ___Object___ *, it->tagobjindex); + if (it->failedstate==0) { + it->failedstate=1; + } else { + it->failedstate=0; + it->tagobjindex++; + } #else objectarray[it->slot]=ARRAYGET(ao, struct ___Object___ *, it->tagobjindex++); #endif } } else { /* Iterate object */ - void * tmpp = (void *) Objkey(&it->it); + void * tmpp = (void *) Objkey(&it->it); objectarray[it->slot]=tmpp; #ifdef OPTIONAL failed[it->slot]=it->failedstate; diff --git a/Robust/src/Runtime/thread.c b/Robust/src/Runtime/thread.c index f7855d71..83b0746e 100644 --- a/Robust/src/Runtime/thread.c +++ b/Robust/src/Runtime/thread.c @@ -35,14 +35,14 @@ void threadexit() { #ifdef THREADS struct ___Object___ *ll=pthread_getspecific(threadlocks); while(ll!=NULL) { - struct ___Object___ *llnext=ll->___nextlockobject___; + struct ___Object___ *llnext=ll->___nextlockobject___; ll->___nextlockobject___=NULL; ll->___prevlockobject___=NULL; ll->lockcount=0; ll->tid=0; //unlock it ll=llnext; } - pthread_mutex_lock(&objlock);//wake everyone up + pthread_mutex_lock(&objlock); //wake everyone up pthread_cond_broadcast(&objcond); pthread_mutex_unlock(&objlock); #endif @@ -66,7 +66,7 @@ transstart: goto transstart; } } -#endif +#endif pthread_exit(NULL); } @@ -130,7 +130,7 @@ void CALL11(___Thread______sleep____J, long long ___millis___, long long ___mill struct listitem *tmp=stopforgc((struct garbagelist *)___params___); #endif #endif - usleep(___millis___); + usleep(___millis___); #ifdef THREADS #ifdef PRECISE_GC restartaftergc(tmp); @@ -164,36 +164,36 @@ transstart: #ifdef THREADJOINDEBUG printf("Thread oid = %x is done\n", (unsigned int) VAR(___this___)); #endif - transAbort(trans); - return; + transAbort(trans); + return; } else { - version = (ptr-1)->version; - if((oidarray = calloc(1, sizeof(unsigned int))) == NULL) { - printf("Calloc error %s, %d\n", __FILE__, __LINE__); - return; - } + version = (ptr-1)->version; + if((oidarray = calloc(1, sizeof(unsigned int))) == NULL) { + printf("Calloc error %s, %d\n", __FILE__, __LINE__); + return; + } - oidarray[0] = (unsigned int) VAR(___this___); + oidarray[0] = (unsigned int) VAR(___this___); - if((versionarray = calloc(1, sizeof(unsigned short))) == NULL) { - printf("Calloc error %s, %d\n", __FILE__, __LINE__); - free(oidarray); - return; - } - versionarray[0] = version; - /* Request Notification */ + if((versionarray = calloc(1, sizeof(unsigned short))) == NULL) { + printf("Calloc error %s, %d\n", __FILE__, __LINE__); + free(oidarray); + return; + } + versionarray[0] = version; + /* Request Notification */ #ifdef PRECISE_GC - struct listitem *tmp=stopforgc((struct garbagelist *)___params___); + struct listitem *tmp=stopforgc((struct garbagelist *)___params___); #endif - reqNotify(oidarray, versionarray, 1); + reqNotify(oidarray, versionarray, 1); #ifdef PRECISE_GC - restartaftergc(tmp); + restartaftergc(tmp); #endif - free(oidarray); - free(versionarray); - transAbort(trans); - goto transstart; + free(oidarray); + free(versionarray); + transAbort(trans); + goto transstart; } return; } @@ -204,7 +204,7 @@ void CALL01(___Thread______nativeJoin____, struct ___Thread___ * ___this___) { pthread_mutex_lock(&joinlock); while(!VAR(___this___)->___finished___) pthread_cond_wait(&joincond, &joinlock); - pthread_mutex_unlock(&joinlock); + pthread_mutex_unlock(&joinlock); } void CALL01(___Thread______nativeCreate____, struct ___Thread___ * ___this___) { @@ -217,7 +217,7 @@ void CALL01(___Thread______nativeCreate____, struct ___Thread___ * ___this___) { pthread_mutex_unlock(&gclistlock); pthread_attr_init(&nattr); pthread_attr_setdetachstate(&nattr, PTHREAD_CREATE_DETACHED); - + do { retval=pthread_create(&thread, &nattr, (void * (*)(void *)) &initthread, VAR(___this___)); if (retval!=0) @@ -237,12 +237,12 @@ void CALL12(___Thread______start____I, int ___mid___, struct ___Thread___ * ___t #ifdef DSTM void globalDestructor(void *value) { - free(value); - pthread_setspecific(oidval, NULL); + free(value); + pthread_setspecific(oidval, NULL); } void initDSMthread(int *ptr) { - objheader_t *tmp; + objheader_t *tmp; transrecord_t * trans; void *threadData; int oid=ptr[0]; @@ -250,9 +250,9 @@ void initDSMthread(int *ptr) { free(ptr); #ifdef PRECISE_GC int p[]={1, 0 /* NULL */, oid}; - ((void (*)(void *))virtualtable[type*MAXCOUNT+RUNMETHOD])(p); + ((void(*) (void *))virtualtable[type*MAXCOUNT+RUNMETHOD])(p); #else - ((void (*)(void *))virtualtable[type*MAXCOUNT+RUNMETHOD])(oid); + ((void(*) (void *))virtualtable[type*MAXCOUNT+RUNMETHOD])(oid); #endif threadData = calloc(1, sizeof(unsigned int)); *((unsigned int *) threadData) = oid; @@ -277,13 +277,13 @@ transstart: } void startDSMthread(int oid, int objType) { - pthread_t thread; - int retval; - pthread_attr_t nattr; + pthread_t thread; + int retval; + pthread_attr_t nattr; - pthread_mutex_lock(&gclistlock); - threadcount++; - pthread_mutex_unlock(&gclistlock); + pthread_mutex_lock(&gclistlock); + threadcount++; + pthread_mutex_unlock(&gclistlock); pthread_attr_init(&nattr); pthread_attr_setdetachstate(&nattr, PTHREAD_CREATE_DETACHED); int * ptr=malloc(sizeof(int)*2); diff --git a/Robust/src/Util/Edge.java b/Robust/src/Util/Edge.java index 8b13b03d..598572d5 100644 --- a/Robust/src/Util/Edge.java +++ b/Robust/src/Util/Edge.java @@ -3,70 +3,74 @@ package Util; /* Edge *****************/ public class Edge { - protected GraphNode target; - protected GraphNode source; + protected GraphNode target; + protected GraphNode source; - protected String dotnodeparams = new String(); - - public Edge(GraphNode target) { - this.target = target; - } - - public String getLabel() { - return ""; - } - - public void setSource(GraphNode s) { - this.source=s; - } - - public GraphNode getSource() { - return source; - } - - public GraphNode getTarget() { - return target; - } + protected String dotnodeparams = new String(); + + public Edge(GraphNode target) { + this.target = target; + } + + public String getLabel() { + return ""; + } + + public void setSource(GraphNode s) { + this.source=s; + } - public void setDotNodeParameters(String param) { - if (param == null) { - throw new NullPointerException(); - } - if (dotnodeparams.length() > 0) { - dotnodeparams += "," + param; - } else { - dotnodeparams = param; - } + public GraphNode getSource() { + return source; + } + + public GraphNode getTarget() { + return target; + } + + public void setDotNodeParameters(String param) { + if (param == null) { + throw new NullPointerException(); } - - public static final EdgeStatus UNVISITED = new EdgeStatus("UNVISITED"); - public static final EdgeStatus PROCESSING = new EdgeStatus("PROCESSING"); - public static final EdgeStatus FINISHED = new EdgeStatus("FINISHED"); - - public static class EdgeStatus { - private static String name; - private EdgeStatus(String name) { this.name = name; } - public String toString() { return name; } + if (dotnodeparams.length() > 0) { + dotnodeparams += "," + param; + } else { + dotnodeparams = param; } - - int discoverytime = -1; - int finishingtime = -1; /* used for searches */ - EdgeStatus status = UNVISITED; - - void reset() { - discoverytime = -1; - finishingtime = -1; - status = UNVISITED; + } + + public static final EdgeStatus UNVISITED = new EdgeStatus("UNVISITED"); + public static final EdgeStatus PROCESSING = new EdgeStatus("PROCESSING"); + public static final EdgeStatus FINISHED = new EdgeStatus("FINISHED"); + + public static class EdgeStatus { + private static String name; + private EdgeStatus(String name) { + this.name = name; } - - void discover(int time) { - discoverytime = time; - status = PROCESSING; + public String toString() { + return name; } + } - void finish(int time) { - assert status == PROCESSING; - finishingtime = time; - status = FINISHED; - } + int discoverytime = -1; + int finishingtime = -1; /* used for searches */ + EdgeStatus status = UNVISITED; + + void reset() { + discoverytime = -1; + finishingtime = -1; + status = UNVISITED; + } + + void discover(int time) { + discoverytime = time; + status = PROCESSING; + } + + void finish(int time) { + assert status == PROCESSING; + finishingtime = time; + status = FINISHED; + } } diff --git a/Robust/src/Util/GraphNode.java b/Robust/src/Util/GraphNode.java index 0028af76..ebc31d0e 100755 --- a/Robust/src/Util/GraphNode.java +++ b/Robust/src/Util/GraphNode.java @@ -4,538 +4,542 @@ import java.util.*; import java.io.*; public class GraphNode { - /* NodeStatus enumeration pattern ***********/ - - public static final NodeStatus UNVISITED = new NodeStatus("UNVISITED"); - public static final NodeStatus PROCESSING = new NodeStatus("PROCESSING"); - public static final NodeStatus FINISHED = new NodeStatus("FINISHED"); - - public static class NodeStatus { - private static String name; - private NodeStatus(String name) { this.name = name; } - public String toString() { return name; } - } + /* NodeStatus enumeration pattern ***********/ + + public static final NodeStatus UNVISITED = new NodeStatus("UNVISITED"); + public static final NodeStatus PROCESSING = new NodeStatus("PROCESSING"); + public static final NodeStatus FINISHED = new NodeStatus("FINISHED"); + + public static class NodeStatus { + private static String name; + private NodeStatus(String name) { + this.name = name; + } + public String toString() { + return name; + } + } + + int discoverytime = -1; + int finishingtime = -1; /* used for searches */ + + protected Vector edges = new Vector(); + protected Vector inedges = new Vector(); + + NodeStatus status = UNVISITED; + String dotnodeparams = new String(); + public boolean merge=false; + + public void setMerge() { + merge=true; + } + + public static void computeclosure(Collection nodes, Collection removed) { + Stack tovisit=new Stack(); + tovisit.addAll(nodes); + while(!tovisit.isEmpty()) { + GraphNode gn=(GraphNode)tovisit.pop(); + for(Iterator it=gn.edges(); it.hasNext();) { + Edge edge=(Edge)it.next(); + GraphNode target=edge.getTarget(); + if (!nodes.contains(target)) { + if ((removed==null)|| + (!removed.contains(target))) { + nodes.add(target); + tovisit.push(target); + } + } + } + } + } + + public static void boundedcomputeclosure(Collection nodes, Collection removed,int depth) { + Stack tovisit=new Stack(); + Stack newvisit=new Stack(); + tovisit.addAll(nodes); + for(int i=0; i 0) { + dotnodeparams += "," + param; + } else { + dotnodeparams = param; + } + } + + public void setStatus(NodeStatus status) { + if (status == null) { + throw new NullPointerException(); + } + this.status = status; + } + + public String getLabel() { + return ""; + } + + public String getTextLabel() { + return ""; + } + + public String getName() { + return ""; + } + + public NodeStatus getStatus() { + return this.status; + } + + public int numedges() { + return edges.size(); + } + + public int numinedges() { + return inedges.size(); + } + + public Edge getedge(int i) { + return (Edge) edges.get(i); + } - int discoverytime = -1; - int finishingtime = -1; /* used for searches */ + public Edge getinedge(int i) { + return (Edge) inedges.get(i); + } - protected Vector edges = new Vector(); - protected Vector inedges = new Vector(); + public Vector getEdgeVector() { + return edges; + } - NodeStatus status = UNVISITED; - String dotnodeparams = new String(); - public boolean merge=false; + public Vector getInedgeVector() { + return inedges; + } - public void setMerge() { - merge=true; - } + public Iterator edges() { + return edges.iterator(); + } - public static void computeclosure(Collection nodes, Collection removed) { - Stack tovisit=new Stack(); - tovisit.addAll(nodes); - while(!tovisit.isEmpty()) { - GraphNode gn=(GraphNode)tovisit.pop(); - for(Iterator it=gn.edges();it.hasNext();) { - Edge edge=(Edge)it.next(); - GraphNode target=edge.getTarget(); - if (!nodes.contains(target)) { - if ((removed==null)|| - (!removed.contains(target))) { - nodes.add(target); - tovisit.push(target); - } - } - } - } - } + public Iterator inedges() { + return inedges.iterator(); + } - public static void boundedcomputeclosure(Collection nodes, Collection removed,int depth) { - Stack tovisit=new Stack(); - Stack newvisit=new Stack(); - tovisit.addAll(nodes); - for(int i=0;i 0) { - dotnodeparams += "," + param; - } else { - dotnodeparams = param; - } - } + public boolean containsEdge(Edge e) { + return edges.contains(e); + } - public void setStatus(NodeStatus status) { - if (status == null) { - throw new NullPointerException(); - } - this.status = status; - } - - public String getLabel() { - return ""; - } + public void addEdge(Vector v) { + for (Iterator it = v.iterator(); it.hasNext();) + addEdge((Edge)it.next()); + } - public String getTextLabel() { - return ""; - } - - public String getName(){ - return ""; - } + public void removeEdge(Edge edge) { + edges.remove(edge); + } - public NodeStatus getStatus() { - return this.status; - } + public void removeInedge(Edge edge) { + inedges.remove(edge); + } - public int numedges() { - return edges.size(); - } + public void removeAllEdges() { + edges.removeAllElements(); + } - public int numinedges() { - return inedges.size(); - } + public void removeAllInedges() { + inedges.removeAllElements(); + } + void reset() { + discoverytime = -1; + finishingtime = -1; + status = UNVISITED; + } - public Edge getedge(int i) { - return (Edge) edges.get(i); - } + void resetscc() { + status = UNVISITED; + } - public Edge getinedge(int i) { - return (Edge) inedges.get(i); - } + void discover(int time) { + discoverytime = time; + status = PROCESSING; + } - public Vector getEdgeVector() { - return edges; - } + void finish(int time) { + assert status == PROCESSING; + finishingtime = time; + status = FINISHED; + } - public Vector getInedgeVector() { - return inedges; - } + /** Returns finishing time for dfs */ - public Iterator edges() { - return edges.iterator(); - } + public int getFinishingTime() { + return finishingtime; + } - public Iterator inedges() { - return inedges.iterator(); - } - - public void addEdge(Edge newedge) { - newedge.setSource(this); - edges.addElement(newedge); - GraphNode tonode=newedge.getTarget(); - tonode.inedges.addElement(newedge); - } - public boolean containsEdge(Edge e) { - return edges.contains(e); - } + public static class DOTVisitor { + + java.io.PrintWriter output; + int tokennumber; + int color; + Vector namers; - public void addEdge(Vector v) { - for (Iterator it = v.iterator(); it.hasNext();) - addEdge((Edge)it.next()); + private DOTVisitor(java.io.OutputStream output, Vector namers) { + tokennumber = 0; + color = 0; + this.output = new java.io.PrintWriter(output, true); + this.namers=namers; + } + + private String getNewID(String name) { + tokennumber = tokennumber + 1; + return new String(name+tokennumber); } - public void removeEdge(Edge edge) { - edges.remove(edge); - } + Collection nodes; - public void removeInedge(Edge edge) { - inedges.remove(edge); + + public static void visit(java.io.OutputStream output, Collection nodes, Vector namers) { + DOTVisitor visitor = new DOTVisitor(output, namers); + visitor.nodes = nodes; + visitor.make(); } - public void removeAllEdges() { - edges.removeAllElements(); + public static void visit(java.io.OutputStream output, Collection nodes) { + Vector v=new Vector(); + v.add(new Namer()); + DOTVisitor visitor = new DOTVisitor(output, v); + visitor.nodes = nodes; + visitor.make(); } - public void removeAllInedges() { - inedges.removeAllElements(); - } - void reset() { - discoverytime = -1; - finishingtime = -1; - status = UNVISITED; + private void make() { + output.println("digraph dotvisitor {"); + /* output.println("\tpage=\"8.5,11\";"); + output.println("\tnslimit=1000.0;"); + output.println("\tnslimit1=1000.0;"); + output.println("\tmclimit=1000.0;"); + output.println("\tremincross=true;");*/ + output.println("\tnode [fontsize=10,height=\"0.1\", width=\"0.1\"];"); + output.println("\tedge [fontsize=6];"); + traverse(); + output.println("}\n"); } - void resetscc() { - status = UNVISITED; - } - void discover(int time) { - discoverytime = time; - status = PROCESSING; - } - void finish(int time) { - assert status == PROCESSING; - finishingtime = time; - status = FINISHED; - } + private void traverse() { + Set cycleset=GraphNode.findcycles(nodes); - /** Returns finishing time for dfs */ + Iterator it = nodes.iterator(); + while (it.hasNext()) { + GraphNode gn = (GraphNode) it.next(); + Iterator edges = gn.edges(); + String label = ""; + String dotnodeparams=""; - public int getFinishingTime() { - return finishingtime; - } + for(int i=0; i " + node2.getLabel() + " [" + "label=\"" + edgelabel + "\"" + edgedotnodeparams + "];"); - } - } - } - } - } - - Set nonmerge(GraphNode gn) { - HashSet newset=new HashSet(); - 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); - } - } + output.println("\t" + gn.getLabel() + " -> " + node2.getLabel() + " [" + "label=\"" + edgelabel + "\"" + edgedotnodeparams + "];"); + } } - return newset; + } + } + } + + Set nonmerge(GraphNode gn) { + HashSet newset=new HashSet(); + 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); + } } - - } - - /** This function returns the set of nodes involved in cycles. - * It only considers cycles containing nodes in the set 'nodes'. - */ - public static Set findcycles(Collection nodes) { - HashSet cycleset=new HashSet(); - SCC scc=DFS.computeSCC(nodes); - if (!scc.hasCycles()) - return cycleset; - for(int i=0;i1) + 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 */ + } + return false; + } + } + + /** + * DFS encapsulates the depth first search algorithm + */ + public static class DFS { + + int time = 0; + int sccindex = 0; + Collection nodes; + Vector finishingorder=null; + Vector finishingorder_edge = null; + int edgetime = 0; + HashMap sccmap; + HashMap sccmaprev; + + private DFS(Collection nodes) { + this.nodes = nodes; + } + /** Calculates the strong connected components for the graph composed + * of the set of nodes 'nodes'*/ + public static SCC computeSCC(Collection nodes) { + if (nodes==null) { + throw new NullPointerException(); + } + DFS dfs=new DFS(nodes); + dfs.sccmap=new HashMap(); + dfs.sccmaprev=new HashMap(); + dfs.finishingorder=new Vector(); + boolean acyclic=dfs.go(); + for (Iterator it = nodes.iterator(); it.hasNext();) { + 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 */ } - return cycleset; - } - - public static class SCC { - boolean acyclic; - HashMap map,revmap; - int numscc; - public SCC(boolean acyclic, HashMap map,HashMap revmap,int numscc) { - this.acyclic=acyclic; - this.map=map; - this.revmap=revmap; - this.numscc=numscc; + } + return new SCC(acyclic,dfs.sccmap,dfs.sccmaprev,dfs.sccindex); + } + + void dfsprev(GraphNode gn) { + if (gn.getStatus()==FINISHED||!nodes.contains(gn)) + return; + gn.setStatus(FINISHED); + Integer i=new Integer(sccindex); + if (!sccmap.containsKey(i)) + 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); + } + } + + public static boolean depthFirstSearch(Collection nodes) { + if (nodes == null) { + throw new NullPointerException(); + } + + DFS dfs = new DFS(nodes); + return dfs.go(); + } + + private boolean go() { + Iterator i; + time = 0; + edgetime = 0; + boolean acyclic=true; + i = nodes.iterator(); + while (i.hasNext()) { + 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; } - - /** Returns whether the graph has any cycles */ - public boolean hasCycles() { - return !acyclic; + } + return acyclic; + } + + private boolean dfs(GraphNode gn) { + boolean acyclic=true; + gn.discover(time++); + 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; } - - /** Returns the number of Strongly Connected Components */ - public int numSCC() { - return numscc; + if (node.getStatus() == UNVISITED) { + if (!dfs(node)) + acyclic=false; + } else if (node.getStatus()==PROCESSING) { + acyclic=false; } - - /** Returns the strongly connected component number for the GraphNode gn*/ - public int getComponent(GraphNode gn) { - return ((Integer)revmap.get(gn)).intValue(); - } - - /** Returns the set of nodes in the strongly connected component i*/ - public Set getSCC(int i) { - Integer scc=new Integer(i); - return (Set)map.get(scc); - } - - /** Returns whether the strongly connected component i contains a cycle */ - boolean hasCycle(int i) { - Integer scc=new Integer(i); - Set s=(Set)map.get(scc); - if (s.size()>1) - 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 */ - } - return false; + if(finishingorder_edge != null) + finishingorder_edge.add(edge); + edge.finish(edgetime++); + } + if (finishingorder!=null) + finishingorder.add(gn); + gn.finish(time++); + return acyclic; + } + + public static Vector topology(Collection nodes, Vector finishingorder_edge) { + if (nodes==null) { + throw new NullPointerException(); + } + DFS dfs=new DFS(nodes); + dfs.finishingorder=new Vector(); + if(finishingorder_edge != null) { + 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); + } + 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); } + } + return topology; } - - /** - * DFS encapsulates the depth first search algorithm - */ - public static class DFS { - - int time = 0; - int sccindex = 0; - Collection nodes; - Vector finishingorder=null; - Vector finishingorder_edge = null; - int edgetime = 0; - HashMap sccmap; - HashMap sccmaprev; - - private DFS(Collection nodes) { - this.nodes = nodes; - } - /** Calculates the strong connected components for the graph composed - * of the set of nodes 'nodes'*/ - public static SCC computeSCC(Collection nodes) { - if (nodes==null) { - throw new NullPointerException(); - } - DFS dfs=new DFS(nodes); - dfs.sccmap=new HashMap(); - dfs.sccmaprev=new HashMap(); - dfs.finishingorder=new Vector(); - boolean acyclic=dfs.go(); - for (Iterator it = nodes.iterator();it.hasNext();) { - 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 */ - } - } - return new SCC(acyclic,dfs.sccmap,dfs.sccmaprev,dfs.sccindex); - } - - void dfsprev(GraphNode gn) { - if (gn.getStatus()==FINISHED||!nodes.contains(gn)) - return; - gn.setStatus(FINISHED); - Integer i=new Integer(sccindex); - if (!sccmap.containsKey(i)) - 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); - } - } - - public static boolean depthFirstSearch(Collection nodes) { - if (nodes == null) { - throw new NullPointerException(); - } - - DFS dfs = new DFS(nodes); - return dfs.go(); - } - - private boolean go() { - Iterator i; - time = 0; - edgetime = 0; - boolean acyclic=true; - i = nodes.iterator(); - while (i.hasNext()) { - 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; - } - } - return acyclic; - } - - private boolean dfs(GraphNode gn) { - boolean acyclic=true; - gn.discover(time++); - 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++); - } - if (finishingorder!=null) - finishingorder.add(gn); - gn.finish(time++); - return acyclic; - } - - public static Vector topology(Collection nodes, Vector finishingorder_edge) { - if (nodes==null) { - throw new NullPointerException(); - } - DFS dfs=new DFS(nodes); - dfs.finishingorder=new Vector(); - if(finishingorder_edge != null) { - 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); - } - 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); - } - } - return topology; - } - } /* end DFS */ + } /* end DFS */ } diff --git a/Robust/src/Util/Namer.java b/Robust/src/Util/Namer.java index 1e8d3c38..9616e730 100644 --- a/Robust/src/Util/Namer.java +++ b/Robust/src/Util/Namer.java @@ -1,21 +1,22 @@ package Util; public class Namer { - public Namer() {} + public Namer() { + } - public String nodeLabel(GraphNode gn) { - return gn.getTextLabel(); - } - - public String nodeOption(GraphNode gn) { - return gn.dotnodeparams; - } + public String nodeLabel(GraphNode gn) { + return gn.getTextLabel(); + } - public String edgeLabel(Edge e) { - return e.getLabel(); - } + public String nodeOption(GraphNode gn) { + return gn.dotnodeparams; + } - public String edgeOption(Edge e) { - return e.dotnodeparams; - } + public String edgeLabel(Edge e) { + return e.getLabel(); + } + + public String edgeOption(Edge e) { + return e.dotnodeparams; + } } diff --git a/Robust/src/Util/Relation.java b/Robust/src/Util/Relation.java index eea6f68a..00446b5c 100644 --- a/Robust/src/Util/Relation.java +++ b/Robust/src/Util/Relation.java @@ -3,43 +3,43 @@ import java.util.*; public class Relation { - private Hashtable table; - int size; + private Hashtable table; + int size; - public Relation() { - table=new Hashtable(); - size=0; - } + public Relation() { + table=new Hashtable(); + size=0; + } - public int size() { - return size; - } + public int size() { + return size; + } - public boolean containsKey(Object o) { - return table.containsKey(o); - } + public boolean containsKey(Object o) { + return table.containsKey(o); + } - public Set keySet() { - return table.keySet(); - } + public Set keySet() { + return table.keySet(); + } - public synchronized boolean put(Object key, Object value) { - HashSet s; - if (table.containsKey(key)) { - s=(HashSet) table.get(key); - } else { - s=new HashSet(); - table.put(key,s); - } - if (!s.contains(value)) { - size++; - s.add(value); - return true; - } else - return false; - } - - public Set get(Object key) { - return (Set)table.get(key); + public synchronized boolean put(Object key, Object value) { + HashSet s; + if (table.containsKey(key)) { + s=(HashSet) table.get(key); + } else { + s=new HashSet(); + table.put(key,s); } + if (!s.contains(value)) { + size++; + s.add(value); + return true; + } else + return false; + } + + public Set get(Object key) { + return (Set)table.get(key); + } } -- 2.34.1