import java.io.*;
public class CallGraph {
- private State state;
-
- // MethodDescriptor maps to HashSet<MethodDescriptor>
- private Hashtable mapVirtual2ImplementationSet;
-
- // MethodDescriptor or TaskDescriptor maps to HashSet<MethodDescriptor>
- private Hashtable mapCaller2CalleeSet;
-
- // MethodDescriptor maps to HashSet<MethodDescriptor or TaskDescriptor>
- 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<MethodDescriptor>
+ private Hashtable mapVirtual2ImplementationSet;
+
+ // MethodDescriptor or TaskDescriptor maps to HashSet<MethodDescriptor>
+ private Hashtable mapCaller2CalleeSet;
+
+ // MethodDescriptor maps to HashSet<MethodDescriptor or TaskDescriptor>
+ 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<fn.numNext(); i++) {
+ FlatNode fnnext=fn.getNext(i);
+ if (!explored.contains(fnnext))
+ toexplore.add(fnnext);
+ }
+ if (fn.kind()==FKind.FlatCall) {
+ FlatCall fc=(FlatCall)fn;
+ MethodDescriptor calledmethod=fc.getMethod();
+ Set methodsthatcouldbecalled=fc.getThis()==null ? getMethods(calledmethod) :
+ getMethods(calledmethod, fc.getThis().getType());
+
+ // add caller -> callee maps
+ if( !mapCaller2CalleeSet.containsKey(caller) ) {
+ mapCaller2CalleeSet.put(caller, new HashSet() );
}
- 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<fn.numNext();i++) {
- FlatNode fnnext=fn.getNext(i);
- if (!explored.contains(fnnext))
- toexplore.add(fnnext);
- }
- if (fn.kind()==FKind.FlatCall) {
- FlatCall fc=(FlatCall)fn;
- MethodDescriptor calledmethod=fc.getMethod();
- Set methodsthatcouldbecalled=fc.getThis()==null?getMethods(calledmethod):
- getMethods(calledmethod, fc.getThis().getType());
-
- // add caller -> callee maps
- if( !mapCaller2CalleeSet.containsKey( caller ) ) {
- mapCaller2CalleeSet.put( caller, new HashSet() );
- }
- ((HashSet)mapCaller2CalleeSet.get( caller )).addAll( methodsthatcouldbecalled );
-
- // add callee -> caller maps
- Iterator calleeItr = methodsthatcouldbecalled.iterator();
- while( calleeItr.hasNext() ) {
- MethodDescriptor callee = (MethodDescriptor) calleeItr.next();
- if( !mapCallee2CallerSet.containsKey( callee ) ) {
- mapCallee2CallerSet.put( callee, new HashSet() );
- }
- ((HashSet)mapCallee2CallerSet.get( callee )).add( caller );
- }
- }
+ }
+
+ 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();
+ }
}
public class FlatIRGraph {
- private State state;
+ private State state;
- private BufferedWriter flatbw;
+ private BufferedWriter flatbw;
- private HashSet<FlatNode> visited;
- private HashSet<FlatNode> toVisit;
-
- private int labelindex;
- private Hashtable<FlatNode, Integer> flatnodetolabel;
+ private HashSet<FlatNode> visited;
+ private HashSet<FlatNode> toVisit;
- public FlatIRGraph(State state, boolean tasks, boolean usermethods, boolean libmethods) throws java.io.IOException {
- this.state=state;
+ private int labelindex;
+ private Hashtable<FlatNode, Integer> 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<FlatNode, Integer>();
- visited=new HashSet<FlatNode>();
- 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<FlatNode>();
- toVisit=new HashSet<FlatNode>();
- 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<fn.numNext();i++) {
- FlatNode nn=fn.getNext(i);
- flatbw.write( " node"+flatnodetolabel.get(fn)+" -> 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<fn.numNext();i++) {
- FlatNode nn=fn.getNext(i);
- if(!visited.contains(nn)) {
- labelFlatNodes(nn);
- }
+ }
+
+ 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<FlatNode, Integer>();
+ visited=new HashSet<FlatNode>();
+ 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<FlatNode>();
+ toVisit=new HashSet<FlatNode>();
+ 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<fn.numNext(); i++) {
+ FlatNode nn=fn.getNext(i);
+ flatbw.write(" node"+flatnodetolabel.get(fn)+" -> 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<fn.numNext(); i++) {
+ FlatNode nn=fn.getNext(i);
+ if(!visited.contains(nn)) {
+ labelFlatNodes(nn);
+ }
}
-
- private String makeDotNodeDec( String graphname, Integer id, String type, String details ) {
- if( details == null ) {
- return " node"+id+"[label=\""+makeNodeName(graphname,id,type)+"\"];\n";
- } else {
- return " node"+id+"[label=\""+makeNodeName(graphname,id,type)+"\\n"+details+"\"];\n";
- }
+ }
+
+ private String makeNodeName(String graphname, Integer id, String type) {
+ String s = String.format("%05d", id);
+ return "FN"+s+"_"+type;
+ }
+
+ private String makeDotNodeDec(String graphname, Integer id, String type, String details) {
+ if( details == null ) {
+ return " node"+id+"[label=\""+makeNodeName(graphname,id,type)+"\"];\n";
+ } else {
+ return " node"+id+"[label=\""+makeNodeName(graphname,id,type)+"\\n"+details+"\"];\n";
}
+ }
}
public class GenerateConversions {
- LocalityAnalysis locality;
- State state;
-
- /** Warning: This class modifies the code in place. */
-
- public GenerateConversions(LocalityAnalysis la, State state) {
- locality=la;
- this.state=state;
- doConversion();
+ LocalityAnalysis locality;
+ State state;
+
+ /** Warning: This class modifies the code in place. */
+
+ public GenerateConversions(LocalityAnalysis la, State state) {
+ locality=la;
+ this.state=state;
+ doConversion();
+ }
+
+ private void doConversion() {
+ Set<LocalityBinding> bindings=locality.getLocalityBindings();
+ Iterator<LocalityBinding> 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<LocalityBinding> bindings=locality.getLocalityBindings();
- Iterator<LocalityBinding> 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<FlatNode, Integer> atomictab=locality.getAtomic(lb);
+ Hashtable<FlatNode, Hashtable<TempDescriptor, Integer>> temptab=locality.getNodeTempInfo(lb);
+ MethodDescriptor md=lb.getMethod();
+ FlatMethod fm=state.getMethodFlat(md);
+ Hashtable<FlatNode, Set<TempNodePair>> nodetotnpair=new Hashtable<FlatNode, Set<TempNodePair>>();
+ Hashtable<FlatNode, Set<TempDescriptor>> nodetoconvs=new Hashtable<FlatNode, Set<TempDescriptor>>();
+
+ Set<FlatNode> toprocess=fm.getNodeSet();
+
+ while(!toprocess.isEmpty()) {
+ FlatNode fn=toprocess.iterator().next();
+ toprocess.remove(fn);
+ boolean isatomic=atomictab.get(fn).intValue()>0;
+ Hashtable<TempDescriptor, Integer> nodetemptab=temptab.get(fn);
+
+ List<TempDescriptor> reads=Arrays.asList(fn.readsTemps());
+ List<TempDescriptor> writes=Arrays.asList(fn.writesTemps());
+
+ if (!isatomic&&fn.kind()==FKind.FlatAtomicExitNode
+ &&!nodetoconvs.containsKey(fn))
+ nodetoconvs.put(fn, new HashSet<TempDescriptor>());
+
+ HashSet<TempNodePair> tempset=new HashSet<TempNodePair>();
+
+ for(int i=0; i<fn.numPrev(); i++) {
+ FlatNode fnprev=fn.getPrev(i);
+ if (!nodetotnpair.containsKey(fnprev))
+ continue;
+
+ Set<TempNodePair> prevset=nodetotnpair.get(fnprev);
+ for(Iterator<TempNodePair> 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<FlatNode, Integer> atomictab=locality.getAtomic(lb);
- Hashtable<FlatNode, Hashtable<TempDescriptor, Integer>> temptab=locality.getNodeTempInfo(lb);
- MethodDescriptor md=lb.getMethod();
- FlatMethod fm=state.getMethodFlat(md);
- Hashtable<FlatNode, Set<TempNodePair>> nodetotnpair=new Hashtable<FlatNode, Set<TempNodePair>>();
- Hashtable<FlatNode, Set<TempDescriptor>> nodetoconvs=new Hashtable<FlatNode, Set<TempDescriptor>>();
-
- Set<FlatNode> toprocess=fm.getNodeSet();
-
- while(!toprocess.isEmpty()) {
- FlatNode fn=toprocess.iterator().next();
- toprocess.remove(fn);
- boolean isatomic=atomictab.get(fn).intValue()>0;
- Hashtable<TempDescriptor, Integer> nodetemptab=temptab.get(fn);
-
- List<TempDescriptor> reads=Arrays.asList(fn.readsTemps());
- List<TempDescriptor> writes=Arrays.asList(fn.writesTemps());
-
- if (!isatomic&&fn.kind()==FKind.FlatAtomicExitNode
- &&!nodetoconvs.containsKey(fn))
- nodetoconvs.put(fn, new HashSet<TempDescriptor>());
-
- HashSet<TempNodePair> tempset=new HashSet<TempNodePair>();
-
- for(int i=0;i<fn.numPrev();i++) {
- FlatNode fnprev=fn.getPrev(i);
- if (!nodetotnpair.containsKey(fnprev))
- continue;
-
- Set<TempNodePair> prevset=nodetotnpair.get(fnprev);
- for(Iterator<TempNodePair> 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<TempDescriptor> 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<fn.numNext();i++) {
- toprocess.add(fn.getNext(i));
- }
+ }
+ 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<TempDescriptor> 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<FlatNode> 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<TempDescriptor> tempset=nodetoconvs.get(fn);
- for(Iterator<TempDescriptor> tempit=tempset.iterator();tempit.hasNext();) {
- FlatGlobalConvNode fgcn=new FlatGlobalConvNode(tempit.next(), lb, false);
- atomictab.put(fgcn, atomictab.get(fn));
- temptab.put(fgcn, (Hashtable<TempDescriptor, Integer>) temptab.get(fn).clone());
-
- for(int i=0;i<fn.numPrev();i++) {
- FlatNode fnprev=fn.getPrev(i);
- for(int j=0;j<fnprev.numNext();j++) {
- if (fnprev.getNext(j)==fn) {
- //found index, change node
- fnprev.setNext(j, fgcn);
- break;
- }
- }
- }
- fgcn.addNext(fn);
- }
- }
+ }
+ 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<fn.numNext(); i++) {
+ toprocess.add(fn.getNext(i));
}
+ }
}
-
- /* 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<FlatNode, Set<TempDescriptor>> nodetotranstemps=new Hashtable<FlatNode, Set<TempDescriptor>>();
- Hashtable<FlatNode, Integer> atomictab=locality.getAtomic(lb);
- Hashtable<FlatNode, Hashtable<TempDescriptor, Integer>> temptab=locality.getNodeTempInfo(lb);
- MethodDescriptor md=lb.getMethod();
- FlatMethod fm=state.getMethodFlat(md);
- Set<FlatNode> 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<TempDescriptor> transtemps=new HashSet<TempDescriptor>();
- for(int i=0;i<fn.numNext();i++) {
- FlatNode fnnext=fn.getNext(i);
- if (nodetotranstemps.containsKey(fnnext))
- transtemps.addAll(nodetotranstemps.get(fnnext));
- }
- //subtract out the ones we write to
- transtemps.removeAll(Arrays.asList(fn.writesTemps()));
- //add in the globals we read from
- Hashtable<TempDescriptor, Integer> pretemptab=locality.getNodePreTempInfo(lb, fn);
- TempDescriptor []readtemps=fn.readsTemps();
- for(int i=0;i<readtemps.length;i++) {
- TempDescriptor tmp=readtemps[i];
- if (pretemptab.get(tmp).intValue()==LocalityAnalysis.GLOBAL) {
- transtemps.add(tmp);
- }
- }
- if (!nodetotranstemps.containsKey(fn)||!nodetotranstemps.get(fn).equals(transtemps)) {
- nodetotranstemps.put(fn, transtemps);
- for(int i=0;i<fn.numPrev();i++)
- toprocess.add(fn.getPrev(i));
- }
+ //Place Convert to Oid nodes
+ toprocess=fm.getNodeSet();
+ for(Iterator<FlatNode> 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<TempDescriptor> tempset=nodetoconvs.get(fn);
+ for(Iterator<TempDescriptor> tempit=tempset.iterator(); tempit.hasNext();) {
+ FlatGlobalConvNode fgcn=new FlatGlobalConvNode(tempit.next(), lb, false);
+ atomictab.put(fgcn, atomictab.get(fn));
+ temptab.put(fgcn, (Hashtable<TempDescriptor, Integer>)temptab.get(fn).clone());
+
+ for(int i=0; i<fn.numPrev(); i++) {
+ FlatNode fnprev=fn.getPrev(i);
+ for(int j=0; j<fnprev.numNext(); j++) {
+ if (fnprev.getNext(j)==fn) {
+ //found index, change node
+ fnprev.setNext(j, fgcn);
+ break;
+ }
}
+ }
+ fgcn.addNext(fn);
}
- toprocess=fm.getNodeSet();
- for(Iterator<FlatNode> 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<TempDescriptor> tempset=nodetotranstemps.get(fn);
- for(Iterator<TempDescriptor> tempit=tempset.iterator();tempit.hasNext();) {
- FlatGlobalConvNode fgcn=new FlatGlobalConvNode(tempit.next(), lb, true);
- atomictab.put(fgcn, atomictab.get(fn));
- temptab.put(fgcn, (Hashtable<TempDescriptor, Integer>) 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<FlatNode, Set<TempDescriptor>> nodetotranstemps=new Hashtable<FlatNode, Set<TempDescriptor>>();
+ Hashtable<FlatNode, Integer> atomictab=locality.getAtomic(lb);
+ Hashtable<FlatNode, Hashtable<TempDescriptor, Integer>> temptab=locality.getNodeTempInfo(lb);
+ MethodDescriptor md=lb.getMethod();
+ FlatMethod fm=state.getMethodFlat(md);
+ Set<FlatNode> 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<TempDescriptor> transtemps=new HashSet<TempDescriptor>();
+ for(int i=0; i<fn.numNext(); i++) {
+ FlatNode fnnext=fn.getNext(i);
+ if (nodetotranstemps.containsKey(fnnext))
+ transtemps.addAll(nodetotranstemps.get(fnnext));
+ }
+ //subtract out the ones we write to
+ transtemps.removeAll(Arrays.asList(fn.writesTemps()));
+ //add in the globals we read from
+ Hashtable<TempDescriptor, Integer> pretemptab=locality.getNodePreTempInfo(lb, fn);
+ TempDescriptor [] readtemps=fn.readsTemps();
+ for(int i=0; i<readtemps.length; i++) {
+ TempDescriptor tmp=readtemps[i];
+ if (pretemptab.get(tmp).intValue()==LocalityAnalysis.GLOBAL) {
+ transtemps.add(tmp);
+ }
+ }
+ if (!nodetotranstemps.containsKey(fn)||!nodetotranstemps.get(fn).equals(transtemps)) {
+ nodetotranstemps.put(fn, transtemps);
+ for(int i=0; i<fn.numPrev(); i++)
+ toprocess.add(fn.getPrev(i));
+ }
+ }
+ }
+ toprocess=fm.getNodeSet();
+ for(Iterator<FlatNode> 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<TempDescriptor> tempset=nodetotranstemps.get(fn);
+ for(Iterator<TempDescriptor> tempit=tempset.iterator(); tempit.hasNext();) {
+ FlatGlobalConvNode fgcn=new FlatGlobalConvNode(tempit.next(), lb, true);
+ atomictab.put(fgcn, atomictab.get(fn));
+ temptab.put(fgcn, (Hashtable<TempDescriptor, Integer>)temptab.get(fn).clone());
+ fgcn.addNext(fn.getNext(0));
+ fn.setNext(0, fgcn);
}
+ }
}
+ }
}
import IR.ClassDescriptor;
public class LocalityAnalysis {
- State state;
- Stack lbtovisit;
- Hashtable<LocalityBinding,LocalityBinding> discovered;
- Hashtable<LocalityBinding, Set<LocalityBinding>> dependence;
- Hashtable<LocalityBinding, Set<LocalityBinding>> calldep;
- Hashtable<LocalityBinding, Hashtable<FlatNode,Hashtable<TempDescriptor, Integer>>> temptab;
- Hashtable<LocalityBinding, Hashtable<FlatNode, Integer>> atomictab;
- Hashtable<LocalityBinding, Hashtable<FlatAtomicEnterNode, Set<TempDescriptor>>> tempstosave;
- Hashtable<ClassDescriptor, Set<LocalityBinding>> classtolb;
- Hashtable<MethodDescriptor, Set<LocalityBinding>> 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<LocalityBinding,LocalityBinding>();
- this.dependence=new Hashtable<LocalityBinding, Set<LocalityBinding>>();
- this.calldep=new Hashtable<LocalityBinding, Set<LocalityBinding>>();
- this.temptab=new Hashtable<LocalityBinding, Hashtable<FlatNode,Hashtable<TempDescriptor, Integer>>>();
- this.atomictab=new Hashtable<LocalityBinding, Hashtable<FlatNode, Integer>>();
- this.lbtovisit=new Stack();
- this.callgraph=callgraph;
- this.tempstosave=new Hashtable<LocalityBinding, Hashtable<FlatAtomicEnterNode, Set<TempDescriptor>>>();
- this.classtolb=new Hashtable<ClassDescriptor, Set<LocalityBinding>>();
- this.methodtolb=new Hashtable<MethodDescriptor, Set<LocalityBinding>>();
- 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<TempDescriptor, Integer> currtable=getNodePreTempInfo(currlb,fc);
- MethodDescriptor md=fc.getMethod();
-
- boolean isnative=md.getModifiers().isNative();
-
- LocalityBinding lb=new LocalityBinding(md, isatomic);
-
- for(int i=0;i<fc.numArgs();i++) {
- TempDescriptor arg=fc.getArg(i);
- lb.setGlobal(i,currtable.get(arg));
- }
- if (fc.getThis()!=null) {
- Integer thistype=currtable.get(fc.getThis());
- if (thistype==null)
- thistype=EITHER;
- lb.setGlobalThis(thistype);
- }// else
- // lb.setGlobalThis(EITHER);//default value
- if (discovered.containsKey(lb))
- lb=discovered.get(lb);
- else throw new Error();
- return lb;
- }
-
-
- /** This method returns a set of LocalityBindings for the parameter class. */
- public Set<LocalityBinding> getClassBindings(ClassDescriptor cd) {
- return classtolb.get(cd);
- }
-
- /** This method returns a set of LocalityBindings for the parameter method. */
-
- public Set<LocalityBinding> getMethodBindings(MethodDescriptor md) {
- return methodtolb.get(md);
- }
-
- public Set<MethodDescriptor> 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<LocalityBinding> 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<FlatNode, Hashtable<TempDescriptor, Integer>> 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<TempDescriptor, Integer> getNodePreTempInfo(LocalityBinding lb, FlatNode fn) {
- Hashtable<TempDescriptor, Integer> currtable=new Hashtable<TempDescriptor, Integer>();
- Hashtable<FlatNode, Hashtable<TempDescriptor, Integer>> temptable=getNodeTempInfo(lb);
-
- for(int i=0;i<fn.numPrev();i++) {
- FlatNode prevnode=fn.getPrev(i);
- Hashtable<TempDescriptor, Integer> prevtable=temptable.get(prevnode);
- for(Iterator<TempDescriptor> 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<FlatNode, Integer> 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<FlatAtomicEnterNode, Set<TempDescriptor>> getTemps(LocalityBinding lb) {
- return tempstosave.get(lb);
- }
-
- public Set<TempDescriptor> getTempSet(LocalityBinding lb) {
- HashSet<TempDescriptor> set=new HashSet<TempDescriptor>();
- Hashtable<FlatAtomicEnterNode, Set<TempDescriptor>> table=getTemps(lb);
- if (table!=null)
- for(Iterator<FlatAtomicEnterNode> 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<LocalityBinding> lbset=new HashSet<LocalityBinding>();
- Stack<LocalityBinding> lbstack=new Stack<LocalityBinding>();
- lbstack.add(lbmain);
- lbstack.add(lbrun);
- lbset.add(lbmain);
- lbset.add(lbrun);
- while(!lbstack.isEmpty()) {
- LocalityBinding lb=lbstack.pop();
- if (calldep.containsKey(lb)) {
- Set<LocalityBinding> set=new HashSet<LocalityBinding>();
- set.addAll(calldep.get(lb));
- set.removeAll(lbset);
- lbstack.addAll(set);
- lbset.addAll(set);
- }
- }
- for(Iterator<LocalityBinding> 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<LocalityBinding>());
- classtolb.get(lbmain.getMethod().getClassDesc()).add(lbmain);
-
- if (!methodtolb.containsKey(lbmain.getMethod()))
- methodtolb.put(lbmain.getMethod(), new HashSet<LocalityBinding>());
- 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<LocalityBinding>());
- classtolb.get(lbrun.getMethod().getClassDesc()).add(lbrun);
-
- if (!methodtolb.containsKey(lbrun.getMethod()))
- methodtolb.put(lbrun.getMethod(), new HashSet<LocalityBinding>());
- methodtolb.get(lbrun.getMethod()).add(lbrun);
-
- while(!lbtovisit.empty()) {
- LocalityBinding lb=(LocalityBinding) lbtovisit.pop();
- Integer returnglobal=lb.getGlobalReturn();
- MethodDescriptor md=lb.getMethod();
- Hashtable<FlatNode,Hashtable<TempDescriptor, Integer>> temptable=new Hashtable<FlatNode,Hashtable<TempDescriptor, Integer>>();
- Hashtable<FlatNode, Integer> atomictable=new Hashtable<FlatNode, Integer>();
- 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<FlatNode, Hashtable<TempDescriptor, Integer>> temptable, Hashtable<FlatNode, Integer> atomictable) {
- FlatMethod fm=state.getMethodFlat(md);
- HashSet<FlatNode> tovisit=new HashSet<FlatNode>();
- tovisit.add(fm.getNext(0));
- {
- // Build table for initial node
- Hashtable<TempDescriptor,Integer> table=new Hashtable<TempDescriptor,Integer>();
- 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<fm.numParameters();i++) {
- TempDescriptor temp=fm.getParameter(i);
- Integer b=lb.isGlobal(i-offset);
- table.put(temp,b);
- }
- }
-
- while(!tovisit.isEmpty()) {
- FlatNode fn=tovisit.iterator().next();
- tovisit.remove(fn);
- Hashtable<TempDescriptor, Integer> currtable=new Hashtable<TempDescriptor, Integer>();
- int atomicstate=0;
- for(int i=0;i<fn.numPrev();i++) {
- FlatNode prevnode=fn.getPrev(i);
- if (atomictable.containsKey(prevnode)) {
- atomicstate=atomictable.get(prevnode).intValue();
- }
- if (!temptable.containsKey(prevnode))
- continue;
- Hashtable<TempDescriptor, Integer> prevtable=temptable.get(prevnode);
- for(Iterator<TempDescriptor> 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<TempDescriptor,Integer> oldtable=temptable.get(fn);
- if (oldtable==null||!oldtable.equals(currtable)) {
- // Update table for this node
- temptable.put(fn, currtable);
- for(int i=0;i<fn.numNext();i++) {
- tovisit.add(fn.getNext(i));
- }
- }
- }
- }
-
- private static boolean isAtomic(Hashtable<FlatNode, Integer> 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<TempDescriptor, Integer> 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<LocalityBinding,LocalityBinding> discovered;
+ Hashtable<LocalityBinding, Set<LocalityBinding>> dependence;
+ Hashtable<LocalityBinding, Set<LocalityBinding>> calldep;
+ Hashtable<LocalityBinding, Hashtable<FlatNode,Hashtable<TempDescriptor, Integer>>> temptab;
+ Hashtable<LocalityBinding, Hashtable<FlatNode, Integer>> atomictab;
+ Hashtable<LocalityBinding, Hashtable<FlatAtomicEnterNode, Set<TempDescriptor>>> tempstosave;
+ Hashtable<ClassDescriptor, Set<LocalityBinding>> classtolb;
+ Hashtable<MethodDescriptor, Set<LocalityBinding>> 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<LocalityBinding,LocalityBinding>();
+ this.dependence=new Hashtable<LocalityBinding, Set<LocalityBinding>>();
+ this.calldep=new Hashtable<LocalityBinding, Set<LocalityBinding>>();
+ this.temptab=new Hashtable<LocalityBinding, Hashtable<FlatNode,Hashtable<TempDescriptor, Integer>>>();
+ this.atomictab=new Hashtable<LocalityBinding, Hashtable<FlatNode, Integer>>();
+ this.lbtovisit=new Stack();
+ this.callgraph=callgraph;
+ this.tempstosave=new Hashtable<LocalityBinding, Hashtable<FlatAtomicEnterNode, Set<TempDescriptor>>>();
+ this.classtolb=new Hashtable<ClassDescriptor, Set<LocalityBinding>>();
+ this.methodtolb=new Hashtable<MethodDescriptor, Set<LocalityBinding>>();
+ 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<TempDescriptor, Integer> currtable=getNodePreTempInfo(currlb,fc);
+ MethodDescriptor md=fc.getMethod();
+
+ boolean isnative=md.getModifiers().isNative();
+
+ LocalityBinding lb=new LocalityBinding(md, isatomic);
+
+ for(int i=0; i<fc.numArgs(); i++) {
+ TempDescriptor arg=fc.getArg(i);
+ lb.setGlobal(i,currtable.get(arg));
+ }
+ if (fc.getThis()!=null) {
+ Integer thistype=currtable.get(fc.getThis());
+ if (thistype==null)
+ thistype=EITHER;
+ lb.setGlobalThis(thistype);
+ } // else
+ // lb.setGlobalThis(EITHER);//default value
+ if (discovered.containsKey(lb))
+ lb=discovered.get(lb);
+ else throw new Error();
+ return lb;
+ }
+
+
+ /** This method returns a set of LocalityBindings for the parameter class. */
+ public Set<LocalityBinding> getClassBindings(ClassDescriptor cd) {
+ return classtolb.get(cd);
+ }
+
+ /** This method returns a set of LocalityBindings for the parameter method. */
+
+ public Set<LocalityBinding> getMethodBindings(MethodDescriptor md) {
+ return methodtolb.get(md);
+ }
+
+ public Set<MethodDescriptor> 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<LocalityBinding> 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<FlatNode, Hashtable<TempDescriptor, Integer>> 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<TempDescriptor, Integer> getNodePreTempInfo(LocalityBinding lb, FlatNode fn) {
+ Hashtable<TempDescriptor, Integer> currtable=new Hashtable<TempDescriptor, Integer>();
+ Hashtable<FlatNode, Hashtable<TempDescriptor, Integer>> temptable=getNodeTempInfo(lb);
+
+ for(int i=0; i<fn.numPrev(); i++) {
+ FlatNode prevnode=fn.getPrev(i);
+ Hashtable<TempDescriptor, Integer> prevtable=temptable.get(prevnode);
+ for(Iterator<TempDescriptor> 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<FlatNode, Integer> 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<FlatAtomicEnterNode, Set<TempDescriptor>> getTemps(LocalityBinding lb) {
+ return tempstosave.get(lb);
+ }
+
+ public Set<TempDescriptor> getTempSet(LocalityBinding lb) {
+ HashSet<TempDescriptor> set=new HashSet<TempDescriptor>();
+ Hashtable<FlatAtomicEnterNode, Set<TempDescriptor>> table=getTemps(lb);
+ if (table!=null)
+ for(Iterator<FlatAtomicEnterNode> 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<LocalityBinding> lbset=new HashSet<LocalityBinding>();
+ Stack<LocalityBinding> lbstack=new Stack<LocalityBinding>();
+ lbstack.add(lbmain);
+ lbstack.add(lbrun);
+ lbset.add(lbmain);
+ lbset.add(lbrun);
+ while(!lbstack.isEmpty()) {
+ LocalityBinding lb=lbstack.pop();
+ if (calldep.containsKey(lb)) {
+ Set<LocalityBinding> set=new HashSet<LocalityBinding>();
+ set.addAll(calldep.get(lb));
+ set.removeAll(lbset);
+ lbstack.addAll(set);
+ lbset.addAll(set);
+ }
+ }
+ for(Iterator<LocalityBinding> 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<LocalityBinding>());
+ classtolb.get(lbmain.getMethod().getClassDesc()).add(lbmain);
+
+ if (!methodtolb.containsKey(lbmain.getMethod()))
+ methodtolb.put(lbmain.getMethod(), new HashSet<LocalityBinding>());
+ 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<LocalityBinding>());
+ classtolb.get(lbrun.getMethod().getClassDesc()).add(lbrun);
+
+ if (!methodtolb.containsKey(lbrun.getMethod()))
+ methodtolb.put(lbrun.getMethod(), new HashSet<LocalityBinding>());
+ methodtolb.get(lbrun.getMethod()).add(lbrun);
+
+ while(!lbtovisit.empty()) {
+ LocalityBinding lb=(LocalityBinding) lbtovisit.pop();
+ Integer returnglobal=lb.getGlobalReturn();
+ MethodDescriptor md=lb.getMethod();
+ Hashtable<FlatNode,Hashtable<TempDescriptor, Integer>> temptable=new Hashtable<FlatNode,Hashtable<TempDescriptor, Integer>>();
+ Hashtable<FlatNode, Integer> atomictable=new Hashtable<FlatNode, Integer>();
+ 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<FlatNode, Hashtable<TempDescriptor, Integer>> temptable, Hashtable<FlatNode, Integer> atomictable) {
+ FlatMethod fm=state.getMethodFlat(md);
+ HashSet<FlatNode> tovisit=new HashSet<FlatNode>();
+ tovisit.add(fm.getNext(0));
+ {
+ // Build table for initial node
+ Hashtable<TempDescriptor,Integer> table=new Hashtable<TempDescriptor,Integer>();
+ 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<fm.numParameters(); i++) {
+ TempDescriptor temp=fm.getParameter(i);
+ Integer b=lb.isGlobal(i-offset);
+ table.put(temp,b);
+ }
+ }
+
+ while(!tovisit.isEmpty()) {
+ FlatNode fn=tovisit.iterator().next();
+ tovisit.remove(fn);
+ Hashtable<TempDescriptor, Integer> currtable=new Hashtable<TempDescriptor, Integer>();
+ int atomicstate=0;
+ for(int i=0; i<fn.numPrev(); i++) {
+ FlatNode prevnode=fn.getPrev(i);
+ if (atomictable.containsKey(prevnode)) {
+ atomicstate=atomictable.get(prevnode).intValue();
}
-
- 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<fc.numArgs();i++) {
- TempDescriptor arg=fc.getArg(i);
- if(isnative&&(currtable.get(arg).equals(GLOBAL)||
- currtable.get(arg).equals(CONFLICT)))
- throw new Error("Potential call to native method "+md+" with global parameter:\n"+currlb.getExplanation());
- lb.setGlobal(i,currtable.get(arg));
- }
- }
-
- 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
- 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<LocalityBinding>());
- classtolb.get(lb.getMethod().getClassDesc()).add(lb);
- if (!methodtolb.containsKey(lb.getMethod()))
- methodtolb.put(lb.getMethod(), new HashSet<LocalityBinding>());
- 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<LocalityBinding>());
- dependence.get(lb).add(currlb);
-
- if (!calldep.containsKey(currlb))
- calldep.put(currlb, new HashSet<LocalityBinding>());
- calldep.get(currlb).add(lb);
+ if (!temptable.containsKey(prevnode))
+ continue;
+ Hashtable<TempDescriptor, Integer> prevtable=temptable.get(prevnode);
+ for(Iterator<TempDescriptor> 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<TempDescriptor,Integer> oldtable=temptable.get(fn);
+ if (oldtable==null||!oldtable.equals(currtable)) {
+ // Update table for this node
+ temptable.put(fn, currtable);
+ for(int i=0; i<fn.numNext(); i++) {
+ tovisit.add(fn.getNext(i));
}
- }
-
- void processFieldNode(LocalityBinding lb, FlatFieldNode ffn, boolean transaction, Hashtable<TempDescriptor, Integer> 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<FlatNode, Integer> 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<TempDescriptor, Integer> 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<TempDescriptor, Integer> 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<fc.numArgs(); i++) {
+ TempDescriptor arg=fc.getArg(i);
+ if(isnative&&(currtable.get(arg).equals(GLOBAL)||
+ currtable.get(arg).equals(CONFLICT)))
+ throw new Error("Potential call to native method "+md+" with global parameter:\n"+currlb.getExplanation());
+ lb.setGlobal(i,currtable.get(arg));
}
- }
-
- void processNew(LocalityBinding lb, FlatNew fn, boolean transaction, Hashtable<TempDescriptor, Integer> 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<TempDescriptor, Integer> 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<TempDescriptor, Integer> currtable) {
- currtable.put(fcn.getDst(), currtable.get(fcn.getSrc()));
- }
-
- void processLiteralNode(FlatLiteralNode fln, Hashtable<TempDescriptor, Integer> 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<TempDescriptor, Integer> currtable) {
- if(frn.getReturnTemp()!=null) {
- Integer returntype=currtable.get(frn.getReturnTemp());
- lb.setGlobalReturn(merge(returntype, lb.getGlobalReturn()));
- }
- }
-
- void processSetElementNode(LocalityBinding lb, FlatSetElementNode fsen, Hashtable<TempDescriptor, Integer> 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<LocalityBinding>());
+ classtolb.get(lb.getMethod().getClassDesc()).add(lb);
+ if (!methodtolb.containsKey(lb.getMethod()))
+ methodtolb.put(lb.getMethod(), new HashSet<LocalityBinding>());
+ 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<LocalityBinding>());
+ dependence.get(lb).add(currlb);
+
+ if (!calldep.containsKey(currlb))
+ calldep.put(currlb, new HashSet<LocalityBinding>());
+ calldep.get(currlb).add(lb);
+ }
+ if (fc.getReturnTemp()!=null) {
+ currtable.put(fc.getReturnTemp(), currreturnval);
+ }
+ }
+
+ void processFieldNode(LocalityBinding lb, FlatFieldNode ffn, boolean transaction, Hashtable<TempDescriptor, Integer> 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<TempDescriptor, Integer> 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<TempDescriptor, Integer> 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<TempDescriptor, Integer> 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<TempDescriptor, Integer> currtable) {
+ currtable.put(fcn.getDst(), currtable.get(fcn.getSrc()));
+ }
+
+ void processLiteralNode(FlatLiteralNode fln, Hashtable<TempDescriptor, Integer> 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<TempDescriptor, Integer> currtable) {
+ if(frn.getReturnTemp()!=null) {
+ Integer returntype=currtable.get(frn.getReturnTemp());
+ lb.setGlobalReturn(merge(returntype, lb.getGlobalReturn()));
+ }
+ }
+
+ void processSetElementNode(LocalityBinding lb, FlatSetElementNode fsen, Hashtable<TempDescriptor, Integer> 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<TempDescriptor, Integer> 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<FlatNode, Integer> atomictable) {
+ int atomic=atomictable.get(fen).intValue();
+ atomictable.put(fen, new Integer(atomic+1));
+ }
+
+ void processAtomicExitNode(FlatAtomicExitNode fen, Hashtable<FlatNode, Integer> atomictable) {
+ int atomic=atomictable.get(fen).intValue();
+ atomictable.put(fen, new Integer(atomic-1));
+ }
+
+ private Hashtable<FlatNode, Set<TempDescriptor>> computeLiveTemps(FlatMethod fm) {
+ Hashtable<FlatNode, Set<TempDescriptor>> nodetotemps=new Hashtable<FlatNode, Set<TempDescriptor>>();
+
+ Set<FlatNode> toprocess=fm.getNodeSet();
+
+ while(!toprocess.isEmpty()) {
+ FlatNode fn=toprocess.iterator().next();
+ toprocess.remove(fn);
+
+ List<TempDescriptor> reads=Arrays.asList(fn.readsTemps());
+ List<TempDescriptor> writes=Arrays.asList(fn.writesTemps());
+
+ HashSet<TempDescriptor> tempset=new HashSet<TempDescriptor>();
+ for(int i=0; i<fn.numNext(); i++) {
+ FlatNode fnnext=fn.getNext(i);
+ if (nodetotemps.containsKey(fnnext))
+ tempset.addAll(nodetotemps.get(fnnext));
+ }
+ tempset.removeAll(writes);
+ tempset.addAll(reads);
+ if (!nodetotemps.containsKey(fn)||
+ !nodetotemps.get(fn).equals(tempset)) {
+ nodetotemps.put(fn, tempset);
+ for(int i=0; i<fn.numPrev(); i++)
+ toprocess.add(fn.getPrev(i));
+ }
+ }
+ return nodetotemps;
+ }
+
+ private void computeTempstoSave() {
+ for(Iterator<LocalityBinding> 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<TempDescriptors>
+ */
+
+ private void computeTempstoSave(LocalityBinding lb) {
+ if (lb.isAtomic())
+ return;
+ Hashtable<FlatNode, Integer> atomictab=getAtomic(lb);
+ Hashtable<FlatNode, Hashtable<TempDescriptor, Integer>> temptab=getNodeTempInfo(lb);
+ MethodDescriptor md=lb.getMethod();
+ FlatMethod fm=state.getMethodFlat(md);
+ Hashtable<FlatNode, Set<TempDescriptor>> nodetotemps=computeLiveTemps(fm);
+ Hashtable<FlatAtomicEnterNode, Set<TempDescriptor>> nodetosavetemps=new Hashtable<FlatAtomicEnterNode, Set<TempDescriptor>>();
+ tempstosave.put(lb, nodetosavetemps);
+ Hashtable<FlatNode, FlatAtomicEnterNode> nodemap=new Hashtable<FlatNode, FlatAtomicEnterNode>();
+ HashSet<FlatNode> toprocess=new HashSet<FlatNode>();
+ HashSet<FlatNode> discovered=new HashSet<FlatNode>();
+ 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<TempDescriptor>());
+ } else if (isatomic) {
+ FlatAtomicEnterNode atomicnode=nodemap.get(fn);
+ Set<TempDescriptor> livetemps=nodetotemps.get(fn);
+ List<TempDescriptor> reads=Arrays.asList(fn.readsTemps());
+ List<TempDescriptor> writes=Arrays.asList(fn.readsTemps());
+
+ for(Iterator<TempDescriptor> 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<TempDescriptor, Integer> 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<FlatNode, Integer> atomictable) {
- int atomic=atomictable.get(fen).intValue();
- atomictable.put(fen, new Integer(atomic+1));
- }
-
- void processAtomicExitNode(FlatAtomicExitNode fen, Hashtable<FlatNode, Integer> atomictable) {
- int atomic=atomictable.get(fen).intValue();
- atomictable.put(fen, new Integer(atomic-1));
- }
-
- private Hashtable<FlatNode, Set<TempDescriptor>> computeLiveTemps(FlatMethod fm) {
- Hashtable<FlatNode, Set<TempDescriptor>> nodetotemps=new Hashtable<FlatNode, Set<TempDescriptor>>();
-
- Set<FlatNode> toprocess=fm.getNodeSet();
-
- while(!toprocess.isEmpty()) {
- FlatNode fn=toprocess.iterator().next();
- toprocess.remove(fn);
-
- List<TempDescriptor> reads=Arrays.asList(fn.readsTemps());
- List<TempDescriptor> writes=Arrays.asList(fn.writesTemps());
-
- HashSet<TempDescriptor> tempset=new HashSet<TempDescriptor>();
- for(int i=0;i<fn.numNext();i++) {
- FlatNode fnnext=fn.getNext(i);
- if (nodetotemps.containsKey(fnnext))
- tempset.addAll(nodetotemps.get(fnnext));
- }
- tempset.removeAll(writes);
- tempset.addAll(reads);
- if (!nodetotemps.containsKey(fn)||
- !nodetotemps.get(fn).equals(tempset)) {
- nodetotemps.put(fn, tempset);
- for(int i=0;i<fn.numPrev();i++)
- toprocess.add(fn.getPrev(i));
- }
- }
- return nodetotemps;
- }
-
- private void computeTempstoSave() {
- for(Iterator<LocalityBinding> 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<TempDescriptors>
- */
-
- private void computeTempstoSave(LocalityBinding lb) {
- if (lb.isAtomic())
- return;
- Hashtable<FlatNode, Integer> atomictab=getAtomic(lb);
- Hashtable<FlatNode, Hashtable<TempDescriptor, Integer>> temptab=getNodeTempInfo(lb);
- MethodDescriptor md=lb.getMethod();
- FlatMethod fm=state.getMethodFlat(md);
- Hashtable<FlatNode, Set<TempDescriptor>> nodetotemps=computeLiveTemps(fm);
- Hashtable<FlatAtomicEnterNode, Set<TempDescriptor>> nodetosavetemps=new Hashtable<FlatAtomicEnterNode, Set<TempDescriptor>>();
- tempstosave.put(lb, nodetosavetemps);
- Hashtable<FlatNode, FlatAtomicEnterNode> nodemap=new Hashtable<FlatNode, FlatAtomicEnterNode>();
- HashSet<FlatNode> toprocess=new HashSet<FlatNode>();
- HashSet<FlatNode> discovered=new HashSet<FlatNode>();
- 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<TempDescriptor>());
- } else if (isatomic) {
- FlatAtomicEnterNode atomicnode=nodemap.get(fn);
- Set<TempDescriptor> livetemps=nodetotemps.get(fn);
- List<TempDescriptor> reads=Arrays.asList(fn.readsTemps());
- List<TempDescriptor> writes=Arrays.asList(fn.readsTemps());
-
- for(Iterator<TempDescriptor> 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<fn.numNext();i++) {
- FlatNode fnnext=fn.getNext(i);
- if (!discovered.contains(fnnext)) {
- discovered.add(fnnext);
- toprocess.add(fnnext);
- if(isatomic) {
- nodemap.put(fnnext, nodemap.get(fn));
- }
- }
- }
+ }
+ for(int i=0; i<fn.numNext(); i++) {
+ FlatNode fnnext=fn.getNext(i);
+ if (!discovered.contains(fnnext)) {
+ discovered.add(fnnext);
+ toprocess.add(fnnext);
+ if(isatomic) {
+ nodemap.put(fnnext, nodemap.get(fn));
+ }
}
+ }
}
+ }
}
import IR.MethodDescriptor;
public class LocalityBinding {
- private MethodDescriptor md;
- private Integer[] isglobal;
- private boolean isatomic;
- private Integer isglobalreturn;
- private Integer isglobalthis;
- private LocalityBinding parent;
- private boolean hasatomic;
-
- public LocalityBinding(MethodDescriptor md, boolean atomic) {
- this.md=md;
- isglobal=new Integer[md.numParameters()];
- isatomic=atomic;
- }
-
- public void setHasAtomic() {
- hasatomic=true;
- }
-
- public boolean getHasAtomic() {
- return hasatomic;
- }
-
- private static String globalToString(Integer g) {
- if (g==LocalityAnalysis.GLOBAL)
- return "G";
- else if (g==LocalityAnalysis.LOCAL)
- return "L";
- else if (g==LocalityAnalysis.EITHER)
- return "E";
- else if (g==LocalityAnalysis.CONFLICT)
- return "C";
- else throw new Error();
- }
-
- public String getSignature() {
- if (md.getModifiers().isNative())
- return "";
- String st="_";
- if (isatomic) {
- st+="A";
- } else
- st+="N";
- if (isglobalthis==null)
- st+="N";
- else
- st+=globalToString(isglobalthis);
- for(int i=0;i<isglobal.length;i++) {
- st+=globalToString(isglobal[i]);
- }
- st+="_";
- return st;
- }
-
- /* Use this for an explanation */
- public void setParent(LocalityBinding lb) {
- parent=lb;
- }
-
- public String getExplanation() {
- if (parent==null)
- return toString();
- else
- return parent.getExplanation()+"\n"+toString();
- }
-
- public String toString() {
- String st=md.toString()+" ";
- if (isglobalthis==null) {
- st+="[static] ";
- } else {
- if (isglobalthis.equals(LocalityAnalysis.LOCAL))
- st+="[local] ";
- else if (isglobalthis.equals(LocalityAnalysis.GLOBAL))
- st+="[global] ";
- else if (isglobalthis.equals(LocalityAnalysis.EITHER))
- st+="[either] ";
- else if (isglobalthis.equals(LocalityAnalysis.CONFLICT))
- st+="[conflict] ";
- }
- for(int i=0;i<isglobal.length;i++)
- if (isglobal[i].equals(LocalityAnalysis.LOCAL))
- st+="local ";
- else if (isglobal[i].equals(LocalityAnalysis.GLOBAL))
- st+="global ";
- else if (isglobal[i].equals(LocalityAnalysis.EITHER))
- st+="either ";
- else if (isglobal[i].equals(LocalityAnalysis.CONFLICT))
- st+="conflict ";
- return st;
- }
-
- public void setGlobal(int i, Integer global) {
- isglobal[i]=global;
- }
-
- public Integer isGlobal(int i) {
- return isglobal[i];
- }
-
- public void setGlobalReturn(Integer global) {
- isglobalreturn=global;
- }
-
- public Integer getGlobalReturn() {
- return isglobalreturn;
- }
-
- public void setGlobalThis(Integer global) {
- isglobalthis=global;
- }
-
- public Integer getGlobalThis() {
- return isglobalthis;
- }
-
- public MethodDescriptor getMethod() {
- return md;
- }
+ private MethodDescriptor md;
+ private Integer[] isglobal;
+ private boolean isatomic;
+ private Integer isglobalreturn;
+ private Integer isglobalthis;
+ private LocalityBinding parent;
+ private boolean hasatomic;
+
+ public LocalityBinding(MethodDescriptor md, boolean atomic) {
+ this.md=md;
+ isglobal=new Integer[md.numParameters()];
+ isatomic=atomic;
+ }
+
+ public void setHasAtomic() {
+ hasatomic=true;
+ }
+
+ public boolean getHasAtomic() {
+ return hasatomic;
+ }
+
+ private static String globalToString(Integer g) {
+ if (g==LocalityAnalysis.GLOBAL)
+ return "G";
+ else if (g==LocalityAnalysis.LOCAL)
+ return "L";
+ else if (g==LocalityAnalysis.EITHER)
+ return "E";
+ else if (g==LocalityAnalysis.CONFLICT)
+ return "C";
+ else throw new Error();
+ }
+
+ public String getSignature() {
+ if (md.getModifiers().isNative())
+ return "";
+ String st="_";
+ if (isatomic) {
+ st+="A";
+ } else
+ st+="N";
+ if (isglobalthis==null)
+ st+="N";
+ else
+ st+=globalToString(isglobalthis);
+ for(int i=0; i<isglobal.length; i++) {
+ st+=globalToString(isglobal[i]);
+ }
+ st+="_";
+ return st;
+ }
+
+ /* Use this for an explanation */
+ public void setParent(LocalityBinding lb) {
+ parent=lb;
+ }
+
+ public String getExplanation() {
+ if (parent==null)
+ return toString();
+ else
+ return parent.getExplanation()+"\n"+toString();
+ }
+
+ public String toString() {
+ String st=md.toString()+" ";
+ if (isglobalthis==null) {
+ st+="[static] ";
+ } else {
+ if (isglobalthis.equals(LocalityAnalysis.LOCAL))
+ st+="[local] ";
+ else if (isglobalthis.equals(LocalityAnalysis.GLOBAL))
+ st+="[global] ";
+ else if (isglobalthis.equals(LocalityAnalysis.EITHER))
+ st+="[either] ";
+ else if (isglobalthis.equals(LocalityAnalysis.CONFLICT))
+ st+="[conflict] ";
+ }
+ for(int i=0; i<isglobal.length; i++)
+ if (isglobal[i].equals(LocalityAnalysis.LOCAL))
+ st+="local ";
+ else if (isglobal[i].equals(LocalityAnalysis.GLOBAL))
+ st+="global ";
+ else if (isglobal[i].equals(LocalityAnalysis.EITHER))
+ st+="either ";
+ else if (isglobal[i].equals(LocalityAnalysis.CONFLICT))
+ st+="conflict ";
+ return st;
+ }
+
+ public void setGlobal(int i, Integer global) {
+ isglobal[i]=global;
+ }
+
+ public Integer isGlobal(int i) {
+ return isglobal[i];
+ }
+
+ public void setGlobalReturn(Integer global) {
+ isglobalreturn=global;
+ }
+
+ public Integer getGlobalReturn() {
+ return isglobalreturn;
+ }
+
+ public void setGlobalThis(Integer global) {
+ isglobalthis=global;
+ }
+
+ public Integer getGlobalThis() {
+ return isglobalthis;
+ }
+
+ public MethodDescriptor getMethod() {
+ return md;
+ }
+
+ public boolean isAtomic() {
+ return isatomic;
+ }
+
+ public boolean contextMatches(LocalityBinding lb) {
+ if (isglobal.length!=lb.isglobal.length)
+ return false;
+ for(int i=0; i<isglobal.length; i++)
+ if (!isglobal[i].equals(lb.isglobal[i]))
+ return false;
- public boolean isAtomic() {
- return isatomic;
- }
+ if (isglobalthis==null) {
+ if (lb.isglobalthis!=null)
+ return false;
+ } else
+ if (!isglobalthis.equals(lb.isglobalthis))
+ return false;
+ return (isatomic==lb.isatomic);
+ }
+
+ public boolean equals(Object o) {
+ if (o instanceof LocalityBinding) {
+ LocalityBinding lb=(LocalityBinding)o;
+ if (md!=lb.md)
+ return false;
- public boolean contextMatches(LocalityBinding lb) {
- if (isglobal.length!=lb.isglobal.length)
- return false;
- for(int i=0;i<isglobal.length;i++)
- if (!isglobal[i].equals(lb.isglobal[i]))
- return false;
-
- if (isglobalthis==null) {
- if (lb.isglobalthis!=null)
- return false;
- } else
- if (!isglobalthis.equals(lb.isglobalthis))
- return false;
- return (isatomic==lb.isatomic);
- }
+ for(int i=0; i<isglobal.length; i++)
+ if (!isglobal[i].equals(lb.isglobal[i]))
+ return false;
- public boolean equals(Object o) {
- if (o instanceof LocalityBinding) {
- LocalityBinding lb=(LocalityBinding)o;
- if (md!=lb.md)
- return false;
-
- for(int i=0;i<isglobal.length;i++)
- if (!isglobal[i].equals(lb.isglobal[i]))
- return false;
-
- if (isglobalthis==null) {
- if (lb.isglobalthis!=null)
- return false;
- } else
- if (!isglobalthis.equals(lb.isglobalthis))
- return false;
- return (isatomic==lb.isatomic);
- }
+ if (isglobalthis==null) {
+ if (lb.isglobalthis!=null)
+ return false;
+ } else
+ if (!isglobalthis.equals(lb.isglobalthis))
return false;
+ return (isatomic==lb.isatomic);
}
+ return false;
+ }
- public int hashCode() {
- int hashcode=md.hashCode();
- for(int i=0;i<isglobal.length;i++) {
- hashcode=hashcode*31+(isglobal[i].intValue());
- }
- hashcode=hashcode*31+(isatomic?1:0);
- return hashcode;
+ public int hashCode() {
+ int hashcode=md.hashCode();
+ for(int i=0; i<isglobal.length; i++) {
+ hashcode=hashcode*31+(isglobal[i].intValue());
}
+ hashcode=hashcode*31+(isatomic ? 1 : 0);
+ return hashcode;
+ }
}
public class TempNodePair {
- 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 "<null,"+getTemp()+">";
- 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 "<null,"+getTemp()+">";
+ else
+ return "<"+getNode()+","+getTemp()+">";
+ }
}
public class AllocationSite {
- static private int uniqueIDcount = 0;
+ static private int uniqueIDcount = 0;
- protected Integer id;
- protected int allocationDepth;
- protected Vector<Integer> ithOldest;
- protected Integer summary;
- protected TypeDescriptor type;
+ protected Integer id;
+ protected int allocationDepth;
+ protected Vector<Integer> 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<Integer>( allocationDepth );
- id = generateUniqueAllocationSiteID();
- }
+ ithOldest = new Vector<Integer>(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;
+ }
}
public class Canonical {
- private static Hashtable<Canonical, Canonical> canon = new Hashtable<Canonical, Canonical>();
+ private static Hashtable<Canonical, Canonical> canon = new Hashtable<Canonical, Canonical>();
- 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;
+ }
}
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+">");
+ }
}
public class ChangeTupleSet extends Canonical {
- private HashSet<ChangeTuple> changeTuples;
+ private HashSet<ChangeTuple> changeTuples;
- public ChangeTupleSet() {
- changeTuples = new HashSet<ChangeTuple>();
- }
+ public ChangeTupleSet() {
+ changeTuples = new HashSet<ChangeTuple>();
+ }
- public ChangeTupleSet( ChangeTuple ct ) {
- this();
- changeTuples.add( ct );
- }
+ public ChangeTupleSet(ChangeTuple ct) {
+ this();
+ changeTuples.add(ct);
+ }
- public ChangeTupleSet( ChangeTupleSet cts ) {
- changeTuples = (HashSet<ChangeTuple>) cts.changeTuples.clone();
- }
+ public ChangeTupleSet(ChangeTupleSet cts) {
+ changeTuples = (HashSet<ChangeTuple>)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;
+ }
}
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<ReferenceEdge> referencers;
+ protected HashSet<ReferenceEdge> 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<ReferenceEdge>();
- 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<ReferenceEdge>();
+ 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<ReferenceEdge> iteratorToReferencers() {
- return referencers.iterator();
- }
- public Iterator<ReferenceEdge> iteratorToReferencersClone() {
- HashSet<ReferenceEdge> clone = (HashSet<ReferenceEdge>) referencers.clone();
- return clone.iterator();
- }
- public int getNumReferencers() {
- return referencers.size();
- }
+ public Iterator<ReferenceEdge> iteratorToReferencers() {
+ return referencers.iterator();
+ }
+ public Iterator<ReferenceEdge> iteratorToReferencersClone() {
+ HashSet<ReferenceEdge> clone = (HashSet<ReferenceEdge>)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<ReferenceEdge> 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<ReferenceEdge> 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() );
+ }
}
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();
+ }
}
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<AllocationSite>
+ 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<AllocationSite> 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<AllocationSite>
- getFlaggedAllocationSitesReachableFromTask( TaskDescriptor td ) {
+ // look through every task for potential aliases
+ Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
+ while( taskItr.hasNext() ) {
+ TaskDescriptor td = (TaskDescriptor) taskItr.next();
+
+ HashSet<AllocationSite> 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 <Descriptor> descriptorsToVisit;
+ private Hashtable<Descriptor, OwnershipGraph> mapDescriptorToCompleteOwnershipGraph;
+ private Hashtable<FlatNew, AllocationSite> mapFlatNewToAllocationSite;
+ private Hashtable<Descriptor, HashSet<AllocationSite> > mapDescriptorToAllocationSiteSet;
+
+ // Use these data structures to track progress of one pass of
+ // processing the FlatNodes of a particular method
+ private HashSet <FlatNode> flatNodesToVisit;
+ private Hashtable<FlatNode, OwnershipGraph> mapFlatNodeToOwnershipGraph;
+ private HashSet <FlatReturnNode> 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<Descriptor>();
+
+ mapDescriptorToCompleteOwnershipGraph =
+ new Hashtable<Descriptor, OwnershipGraph>();
+
+ mapFlatNewToAllocationSite =
+ new Hashtable<FlatNew, AllocationSite>();
+
+ mapDescriptorToAllocationSiteSet =
+ new Hashtable<Descriptor, HashSet<AllocationSite> >();
+
+ // use this set to prevent infinite recursion when
+ // traversing the call graph
+ HashSet<Descriptor> calleesScheduled = new HashSet<Descriptor>();
+
- 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<Descriptor> 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<Descriptor> 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<AllocationSite> 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<AllocationSite> 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<FlatNode>();
+ 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<FlatNode, OwnershipGraph>();
- // 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<FlatReturnNode>();
+ 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 <Descriptor> descriptorsToVisit;
- private Hashtable<Descriptor, OwnershipGraph> mapDescriptorToCompleteOwnershipGraph;
- private Hashtable<FlatNew, AllocationSite> mapFlatNewToAllocationSite;
- private Hashtable<Descriptor, HashSet<AllocationSite> > 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 <FlatNode> flatNodesToVisit;
- private Hashtable<FlatNode, OwnershipGraph> mapFlatNodeToOwnershipGraph;
- private HashSet <FlatReturnNode> 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<Descriptor>();
- mapDescriptorToCompleteOwnershipGraph =
- new Hashtable<Descriptor, OwnershipGraph>();
- mapFlatNewToAllocationSite =
- new Hashtable<FlatNew, AllocationSite>();
+ x++;
+ if( x > 0 ) {
+ String s = String.format("debug%04d", x);
+ //og.writeGraph( s, true, true, true, false );
+ }
- mapDescriptorToAllocationSiteSet =
- new Hashtable<Descriptor, HashSet<AllocationSite> >();
- // use this set to prevent infinite recursion when
- // traversing the call graph
- HashSet<Descriptor> calleesScheduled = new HashSet<Descriptor>();
+ 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<FlatReturnNode> 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<AllocationSite> 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<Descriptor> 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<Descriptor> 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<FlatNode>();
- flatNodesToVisit.add( flatm );
-
- // initilize the mapping of flat nodes in this flat method to
- // ownership graph results to an empty mapping
- mapFlatNodeToOwnershipGraph = new Hashtable<FlatNode, OwnershipGraph>();
-
- // 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<FlatReturnNode>();
-
- 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<FlatReturnNode> 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<AllocationSite> 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<AllocationSite> getAllocationSiteSet(Descriptor d) {
+ if( !mapDescriptorToAllocationSiteSet.containsKey(d) ) {
+ buildAllocationSiteSet(d);
}
+ return mapDescriptorToAllocationSiteSet.get(d);
+ }
-
+ private void buildAllocationSiteSet(Descriptor d) {
+ HashSet<AllocationSite> s = new HashSet<AllocationSite>();
+ 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<FlatNode> visited = new HashSet<FlatNode>();
+ HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
+ 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<AllocationSite> getAllocationSiteSet( Descriptor d ) {
- if( !mapDescriptorToAllocationSiteSet.containsKey( d ) ) {
- buildAllocationSiteSet( d );
- }
- return mapDescriptorToAllocationSiteSet.get( d );
+ private HashSet<AllocationSite>
+ getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
- }
+ HashSet<AllocationSite> asSetTotal = new HashSet<AllocationSite>();
+ HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
+ HashSet<Descriptor> visited = new HashSet<Descriptor>();
- private void buildAllocationSiteSet( Descriptor d ) {
- HashSet<AllocationSite> s = new HashSet<AllocationSite>();
+ 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<FlatNode> visited = new HashSet<FlatNode>();
- HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
- 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<AllocationSite> 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<AllocationSite>
- getFlaggedAllocationSitesReachableFromTaskPRIVATE( TaskDescriptor td ) {
-
- HashSet<AllocationSite> asSetTotal = new HashSet<AllocationSite>();
- HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
- HashSet<Descriptor> visited = new HashSet<Descriptor>();
-
- 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<AllocationSite> 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<Integer> getHeapRegionIDset(OwnershipGraph og,
+ int paramIndex) {
- private HashSet<Integer> 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<Integer> idSet = new HashSet<Integer>();
- idSet.add( idParam );
+ HashSet<Integer> idSet = new HashSet<Integer>();
+ idSet.add(idParam);
- return idSet;
- }
+ return idSet;
+ }
- private HashSet<Integer> getHeapRegionIDset( AllocationSite alloc ) {
+ private HashSet<Integer> getHeapRegionIDset(AllocationSite alloc) {
- HashSet<Integer> idSet = new HashSet<Integer>();
-
- for( int i = 0; i < alloc.getAllocationDepth(); ++i ) {
- Integer id = alloc.getIthOldest( i );
- idSet.add( id );
- }
-
- Integer idSummary = alloc.getSummary();
- idSet.add( idSummary );
+ HashSet<Integer> idSet = new HashSet<Integer>();
- return idSet;
+ for( int i = 0; i < alloc.getAllocationDepth(); ++i ) {
+ Integer id = alloc.getIthOldest(i);
+ idSet.add(id);
}
- private HashSet<Integer> getHeapRegionIDset( HashSet<AllocationSite> allocSet ) {
+ Integer idSummary = alloc.getSummary();
+ idSet.add(idSummary);
- HashSet<Integer> idSet = new HashSet<Integer>();
+ return idSet;
+ }
- Iterator allocItr = allocSet.iterator();
- while( allocItr.hasNext() ) {
- AllocationSite alloc = (AllocationSite) allocItr.next();
+ private HashSet<Integer> getHeapRegionIDset(HashSet<AllocationSite> 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<Integer> idSet = new HashSet<Integer>();
- return idSet;
- }
+ Iterator allocItr = allocSet.iterator();
+ while( allocItr.hasNext() ) {
+ AllocationSite alloc = (AllocationSite) allocItr.next();
- private boolean createsPotentialAliases( OwnershipGraph og,
- HashSet<Integer> idSetA,
- HashSet<Integer> 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<Integer> 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<Integer> idSetA,
+ HashSet<Integer> 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<Integer> 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;
+ }
}
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<Integer, HeapRegionNode> id2hrn;
- public Hashtable<TempDescriptor, LabelNode > td2ln;
- public Hashtable<Integer, Integer > id2paramIndex;
- public Hashtable<Integer, Integer > paramIndex2id;
+ public Hashtable<Integer, HeapRegionNode> id2hrn;
+ public Hashtable<TempDescriptor, LabelNode > td2ln;
+ public Hashtable<Integer, Integer > id2paramIndex;
+ public Hashtable<Integer, Integer > paramIndex2id;
- public HashSet<AllocationSite> allocationSites;
+ public HashSet<AllocationSite> allocationSites;
- public OwnershipGraph( int allocationDepth ) {
- this.allocationDepth = allocationDepth;
-
- id2hrn = new Hashtable<Integer, HeapRegionNode>();
- td2ln = new Hashtable<TempDescriptor, LabelNode >();
- id2paramIndex = new Hashtable<Integer, Integer >();
- paramIndex2id = new Hashtable<Integer, Integer >();
+ public OwnershipGraph(int allocationDepth) {
+ this.allocationDepth = allocationDepth;
- allocationSites = new HashSet <AllocationSite>();
- }
-
-
- // 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<Integer, HeapRegionNode>();
+ td2ln = new Hashtable<TempDescriptor, LabelNode >();
+ id2paramIndex = new Hashtable<Integer, Integer >();
+ paramIndex2id = new Hashtable<Integer, Integer >();
+ allocationSites = new HashSet <AllocationSite>();
+ }
- // 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<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> 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<HeapRegionNode> nodesWithNewAlpha,
- HashSet<ReferenceEdge> edgesWithNewBeta ) {
-
- HashSet<HeapRegionNode> todoNodes
- = new HashSet<HeapRegionNode>();
- todoNodes.add( nPrime );
-
- HashSet<ReferenceEdge> todoEdges
- = new HashSet<ReferenceEdge>();
-
- Hashtable<HeapRegionNode, ChangeTupleSet> nodePlannedChanges
- = new Hashtable<HeapRegionNode, ChangeTupleSet>();
- nodePlannedChanges.put( nPrime, c0 );
-
- Hashtable<ReferenceEdge, ChangeTupleSet> edgePlannedChanges
- = new Hashtable<ReferenceEdge, ChangeTupleSet>();
-
-
- 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<ReferenceEdge> 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<HeapRegionNode> nodesWithNewAlpha,
+ HashSet<ReferenceEdge> edgesWithNewBeta) {
- edgePlannedChanges.put( edge, edgePlannedChanges.get( edge ).union( C ) );
- }
+ HashSet<HeapRegionNode> todoNodes
+ = new HashSet<HeapRegionNode>();
+ todoNodes.add(nPrime);
- Iterator<ReferenceEdge> refeeItr = n.iteratorToReferencees();
- while( refeeItr.hasNext() ) {
- ReferenceEdge edgeF = refeeItr.next();
- HeapRegionNode m = edgeF.getDst();
+ HashSet<ReferenceEdge> todoEdges
+ = new HashSet<ReferenceEdge>();
- ChangeTupleSet changesToPass = new ChangeTupleSet().makeCanonical();
+ Hashtable<HeapRegionNode, ChangeTupleSet> nodePlannedChanges
+ = new Hashtable<HeapRegionNode, ChangeTupleSet>();
+ nodePlannedChanges.put(nPrime, c0);
- Iterator<ChangeTuple> itrCprime = C.iterator();
- while( itrCprime.hasNext() ) {
- ChangeTuple c = itrCprime.next();
- if( edgeF.getBeta().contains( c.getSetToMatch() ) ) {
- changesToPass = changesToPass.union( c );
- }
- }
+ Hashtable<ReferenceEdge, ChangeTupleSet> edgePlannedChanges
+ = new Hashtable<ReferenceEdge, ChangeTupleSet>();
- 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<ReferenceEdge> 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<ReferenceEdge> refeeItr = n.iteratorToReferencees();
+ while( refeeItr.hasNext() ) {
+ ReferenceEdge edgeF = refeeItr.next();
+ HeapRegionNode m = edgeF.getDst();
- protected void propagateTokensOverEdges(
- HashSet<ReferenceEdge> todoEdges,
- Hashtable<ReferenceEdge, ChangeTupleSet> edgePlannedChanges,
- HashSet<HeapRegionNode> nodesWithNewAlpha,
- HashSet<ReferenceEdge> edgesWithNewBeta ) {
-
+ ChangeTupleSet changesToPass = new ChangeTupleSet().makeCanonical();
- while( !todoEdges.isEmpty() ) {
- ReferenceEdge edgeE = todoEdges.iterator().next();
- todoEdges.remove( edgeE );
+ Iterator<ChangeTuple> 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<ChangeTuple> 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<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> todoEdges,
+ Hashtable<ReferenceEdge, ChangeTupleSet> edgePlannedChanges,
+ HashSet<HeapRegionNode> nodesWithNewAlpha,
+ HashSet<ReferenceEdge> edgesWithNewBeta) {
- clearReferenceEdgesFrom( lnX, null, true );
- Iterator<ReferenceEdge> 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<ReferenceEdge> 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<ChangeTuple> 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<HeapRegionNode> nodesWithNewAlpha = new HashSet<HeapRegionNode>();
- HashSet<ReferenceEdge> edgesWithNewBeta = new HashSet<ReferenceEdge>();
-
- Iterator<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> todoEdges = new HashSet<ReferenceEdge>();
-
- Hashtable<ReferenceEdge, ChangeTupleSet> edgePlannedChanges =
- new Hashtable<ReferenceEdge, ChangeTupleSet>();
-
- Iterator<ReferenceEdge> 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<HeapRegionNode> nodeItr = nodesWithNewAlpha.iterator();
- while( nodeItr.hasNext() ) {
- nodeItr.next().applyAlphaNew();
- }
+ Iterator<ReferenceEdge> referItr = n.iteratorToReferencers();
+ while( referItr.hasNext() ) {
+ ReferenceEdge edgeF = referItr.next();
- Iterator<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> itrEdges = hrnToAge.iteratorToReferencees();
- while( itrEdges.hasNext() ) {
- ageTokens( as, itrEdges.next() );
- }
- }
+ LabelNode lnX = getLabelNodeFromTemp(x);
+ LabelNode lnY = getLabelNodeFromTemp(y);
+ HashSet<HeapRegionNode> nodesWithNewAlpha = new HashSet<HeapRegionNode>();
+ HashSet<ReferenceEdge> edgesWithNewBeta = new HashSet<ReferenceEdge>();
- // 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<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> todoEdges = new HashSet<ReferenceEdge>();
+
+ Hashtable<ReferenceEdge, ChangeTupleSet> edgePlannedChanges =
+ new Hashtable<ReferenceEdge, ChangeTupleSet>();
+
+ Iterator<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> 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<HeapRegionNode> nodeItr = nodesWithNewAlpha.iterator();
+ while( nodeItr.hasNext() ) {
+ nodeItr.next().applyAlphaNew();
}
+ Iterator<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> 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<AllocationSite> 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<ReferenceEdge> 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<ReferenceEdge> 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<TokenTupleSet> 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<HeapRegionNode> possibleCallerSrcs =
- getHRNSetThatPossiblyMapToCalleeHRN( ogCallee,
- idCallee,
- fc,
- isStatic );
-
- HashSet<HeapRegionNode> 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<HeapRegionNode> getHRNSetThatPossiblyMapToCalleeHRN( OwnershipGraph ogCallee,
- Integer idCallee,
- FlatCall fc,
- boolean isStatic ) {
-
- HashSet<HeapRegionNode> possibleCallerHRNs = new HashSet<HeapRegionNode>();
-
- 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<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> 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<AllocationSite> 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<TokenTupleSet> 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<HeapRegionNode> possibleCallerSrcs =
+ getHRNSetThatPossiblyMapToCalleeHRN( ogCallee,
+ idCallee,
+ fc,
+ isStatic );
+
+ HashSet<HeapRegionNode> 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<HeapRegionNode> getHRNSetThatPossiblyMapToCalleeHRN( OwnershipGraph ogCallee,
+ Integer idCallee,
+ FlatCall fc,
+ boolean isStatic ) {
+
+ HashSet<HeapRegionNode> possibleCallerHRNs = new HashSet<HeapRegionNode>();
+
+ 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<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> 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<ReferenceEdge> 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<Integer> getReachableSet( HashSet<Integer> idSetB ) {
-
- HashSet<HeapRegionNode> toVisit = new HashSet<HeapRegionNode>();
- HashSet<HeapRegionNode> visited = new HashSet<HeapRegionNode>();
-
- // 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<Integer> idSetReachableFromB = new HashSet<Integer>();
+ 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<ReferenceEdge> 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<ReferenceEdge> 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<Integer> idSet ) {
-
- assert id2hrn.contains( id );
- HeapRegionNode hrn = id2hrn.get( id );
-
-
- //HashSet<HeapRegionNode> hrnSet = new HashSet<HeapRegionNode>();
-
- //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<HeapRegionNode> toVisit = new HashSet<HeapRegionNode>();
- HashSet<HeapRegionNode> visited = new HashSet<HeapRegionNode>();
-
- 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<Integer> getReachableSet( HashSet<Integer> 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<HeapRegionNode> toVisit = new HashSet<HeapRegionNode>();
+ HashSet<HeapRegionNode> visited = new HashSet<HeapRegionNode>();
+
+ // 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<Integer> idSetReachableFromB = new HashSet<Integer>();
+
+ // 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<Integer> idSet ) {
+
+ assert id2hrn.contains( id );
+ HeapRegionNode hrn = id2hrn.get( id );
+
+
+ //HashSet<HeapRegionNode> hrnSet = new HashSet<HeapRegionNode>();
+
+ //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<HeapRegionNode> toVisit = new HashSet<HeapRegionNode>();
+ HashSet<HeapRegionNode> visited = new HashSet<HeapRegionNode>();
+
+ 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<HeapRegionNode> visited = new HashSet<HeapRegionNode>();
+
+ // 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<HeapRegionNode> visited = new HashSet<HeapRegionNode>();
-
- // 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<ReferenceEdge> 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<ReferenceEdge> 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<HeapRegionNode> 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<HeapRegionNode> 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<ReferenceEdge> 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<ReferenceEdge> 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);
}
+ }
}
import IR.Flat.*;
import java.util.*;
-public abstract class OwnershipNode {
+public abstract class OwnershipNode {
- protected HashSet<ReferenceEdge> referencees;
-
- public OwnershipNode() {
- referencees = new HashSet<ReferenceEdge>();
- }
+ protected HashSet<ReferenceEdge> referencees;
+ public OwnershipNode() {
+ referencees = new HashSet<ReferenceEdge>();
+ }
- public Iterator<ReferenceEdge> iteratorToReferencees() {
- return referencees.iterator();
- }
- public Iterator<ReferenceEdge> iteratorToReferenceesClone() {
- HashSet<ReferenceEdge> clone = (HashSet<ReferenceEdge>) referencees.clone();
- return clone.iterator();
- }
+ public Iterator<ReferenceEdge> iteratorToReferencees() {
+ return referencees.iterator();
+ }
- public int getNumReferencees() {
- return referencees.size();
- }
+ public Iterator<ReferenceEdge> iteratorToReferenceesClone() {
+ HashSet<ReferenceEdge> clone = (HashSet<ReferenceEdge>)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<ReferenceEdge> 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<ReferenceEdge> 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
public class ReachabilitySet extends Canonical {
- private HashSet<TokenTupleSet> possibleReachabilities;
-
- public ReachabilitySet() {
- possibleReachabilities = new HashSet<TokenTupleSet>();
+ private HashSet<TokenTupleSet> possibleReachabilities;
+
+ public ReachabilitySet() {
+ possibleReachabilities = new HashSet<TokenTupleSet>();
+ }
+
+ 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<TokenTupleSet> possibleReachabilities) {
+ assert possibleReachabilities != null;
+ this.possibleReachabilities = possibleReachabilities;
+ }
+
+ public ReachabilitySet(ReachabilitySet rs) {
+ assert rs != null;
+ // okay to clone, ReachabilitySet should be canonical
+ possibleReachabilities = (HashSet<TokenTupleSet>)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<TokenTupleSet> possibleReachabilities ) {
- assert possibleReachabilities != null;
- this.possibleReachabilities = possibleReachabilities;
- }
+ HashSet<TokenTupleSet> possibleReachabilitiesNew = new HashSet<TokenTupleSet>();
- public ReachabilitySet( ReachabilitySet rs ) {
- assert rs != null;
- // okay to clone, ReachabilitySet should be canonical
- possibleReachabilities = (HashSet<TokenTupleSet>) 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<TokenTupleSet> possibleReachabilitiesNew = new HashSet<TokenTupleSet>();
+ 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;
+ }
}
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;
+ }
}
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+">");
+ }
}
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;
+ }
}
public class TokenTupleSet extends Canonical {
- private HashSet<TokenTuple> tokenTuples;
+ private HashSet<TokenTuple> tokenTuples;
- public TokenTupleSet() {
- tokenTuples = new HashSet<TokenTuple>();
- }
+ public TokenTupleSet() {
+ tokenTuples = new HashSet<TokenTuple>();
+ }
- 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<TokenTuple>) tts.tokenTuples.clone();
- }
+ public TokenTupleSet(TokenTupleSet tts) {
+ assert tts != null;
+ // okay to clone, TokenTuple and TokenTupleSet should be canonical
+ tokenTuples = (HashSet<TokenTuple>)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();
+ }
}
* 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<TempDescriptor> tddesc;
- public Integer offset;
-
- public IndexDescriptor(Integer offset) {
- super(offset.toString());
- this.offset = offset;
- this.tddesc=new ArrayList<TempDescriptor>();
- }
-
- public IndexDescriptor(TempDescriptor tdesc, Integer offset) {
- super(tdesc.toString());
- tddesc = new ArrayList<TempDescriptor>();
- tddesc.add(tdesc);
- this.offset = offset;
- }
-
- public IndexDescriptor() {
- super("Empty");
- tddesc = new ArrayList<TempDescriptor>();
- offset = 0;
- }
+ public ArrayList<TempDescriptor> tddesc;
+ public Integer offset;
- public IndexDescriptor(ArrayList<TempDescriptor> tdesc, Integer offset) {
- super(tdesc.toString());
- tddesc = new ArrayList<TempDescriptor>();
- tddesc.addAll(tdesc);
- this.offset = offset;
- }
-
- public ArrayList<TempDescriptor> 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<TempDescriptor>();
+ }
+
+ public IndexDescriptor(TempDescriptor tdesc, Integer offset) {
+ super(tdesc.toString());
+ tddesc = new ArrayList<TempDescriptor>();
+ tddesc.add(tdesc);
+ this.offset = offset;
+ }
+
+ public IndexDescriptor() {
+ super("Empty");
+ tddesc = new ArrayList<TempDescriptor>();
+ offset = 0;
+ }
+
+ public IndexDescriptor(ArrayList<TempDescriptor> tdesc, Integer offset) {
+ super(tdesc.toString());
+ tddesc = new ArrayList<TempDescriptor>();
+ tddesc.addAll(tdesc);
+ this.offset = offset;
+ }
+
+ public ArrayList<TempDescriptor> 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;
+ }
}
public class LoopExit {
- State state;
- Hashtable<MethodDescriptor, Set<FlatCondBranch>> results;
+ State state;
+ Hashtable<MethodDescriptor, Set<FlatCondBranch>> results;
- public LoopExit(State state) {
- this.state=state;
- this.results=new Hashtable<MethodDescriptor, Set<FlatCondBranch>>();
- }
+ public LoopExit(State state) {
+ this.state=state;
+ this.results=new Hashtable<MethodDescriptor, Set<FlatCondBranch>>();
+ }
- public Set<FlatCondBranch> getLoopBranches(MethodDescriptor md) {
- if (!results.containsKey(md))
- doAnalysis(md);
- return results.get(md);
- }
+ public Set<FlatCondBranch> 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<FlatNode> nodeset=new HashSet<FlatNode>();
- nodeset.addAll(fm.getNodeSet());
- Hashtable<FlatNode, Set<FlatCondBranch>> table=new Hashtable<FlatNode, Set<FlatCondBranch>>();
+ private void doAnalysis(MethodDescriptor md) {
+ FlatMethod fm=state.getMethodFlat(md);
+ HashSet<FlatNode> nodeset=new HashSet<FlatNode>();
+ nodeset.addAll(fm.getNodeSet());
+ Hashtable<FlatNode, Set<FlatCondBranch>> table=new Hashtable<FlatNode, Set<FlatCondBranch>>();
- HashSet<FlatCondBranch> loopbranchset=new HashSet<FlatCondBranch>();
- HashSet<FlatCondBranch> exitset=new HashSet<FlatCondBranch>();
-
- 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<fn.numNext();i++)
- propagateset(nodeset, table, fn, fn.getNext(i), null);
- }
- }
- loopbranchset.removeAll(exitset);
- results.put(md, loopbranchset);
+ HashSet<FlatCondBranch> loopbranchset=new HashSet<FlatCondBranch>();
+ HashSet<FlatCondBranch> exitset=new HashSet<FlatCondBranch>();
+
+ 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<fn.numNext(); i++)
+ propagateset(nodeset, table, fn, fn.getNext(i), null);
+ }
}
+ loopbranchset.removeAll(exitset);
+ results.put(md, loopbranchset);
+ }
- void propagateset(Set<FlatNode> tovisit, Hashtable<FlatNode, Set<FlatCondBranch>> table, FlatNode fn, FlatNode fnnext, FlatCondBranch fcb) {
- boolean enqueuechange=false;
- if (table.containsKey(fn)) {
- if (!table.containsKey(fnnext))
- table.put(fnnext, new HashSet<FlatCondBranch>());
- HashSet<FlatCondBranch> toadd=new HashSet<FlatCondBranch>();
- 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<FlatCondBranch>());
- if (!table.get(fnnext).contains(fcb)) {
- table.get(fnnext).add(fcb);
- enqueuechange=true;
- }
- }
- if (enqueuechange)
- tovisit.add(fnnext);
+ void propagateset(Set<FlatNode> tovisit, Hashtable<FlatNode, Set<FlatCondBranch>> table, FlatNode fn, FlatNode fnnext, FlatCondBranch fcb) {
+ boolean enqueuechange=false;
+ if (table.containsKey(fn)) {
+ if (!table.containsKey(fnnext))
+ table.put(fnnext, new HashSet<FlatCondBranch>());
+ HashSet<FlatCondBranch> toadd=new HashSet<FlatCondBranch>();
+ 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<FlatCondBranch>());
+ if (!table.get(fnnext).contains(fcb)) {
+ table.get(fnnext).add(fcb);
+ enqueuechange=true;
+ }
}
+ if (enqueuechange)
+ tovisit.add(fnnext);
+ }
}
*/
public class PairMap {
- public HashMap<PrefetchPair, PrefetchPair> mappair;
-
- public PairMap() {
- mappair = new HashMap<PrefetchPair, PrefetchPair>();
- }
-
- 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<PrefetchPair, PrefetchPair> 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<PrefetchPair, PrefetchPair>();
+ }
- 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();
+ }
}
import IR.ClassDescriptor;
public class PrefetchAnalysis {
- State state;
- CallGraph callgraph;
- TypeUtil typeutil;
- LoopExit loop;
-
- Set<FlatNode> tovisit;
- public Hashtable<FlatNode, Hashtable<PrefetchPair, Double>> prefetch_hash;//holds all flatnodes and corresponding prefetch set
- public Hashtable<FlatNode, Hashtable<FlatNode, PairMap>> 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<FlatNode, Hashtable<PrefetchPair,Double>>();
- pmap_hash = new Hashtable<FlatNode, Hashtable<FlatNode, PairMap>>();
- 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<FlatNode, HashSet<PrefetchPair>> newprefetchset = new Hashtable<FlatNode, HashSet<PrefetchPair>>();
- 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<FlatNode> tovisit;
+ public Hashtable<FlatNode, Hashtable<PrefetchPair, Double>> prefetch_hash; //holds all flatnodes and corresponding prefetch set
+ public Hashtable<FlatNode, Hashtable<FlatNode, PairMap>> 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<FlatNode, Hashtable<PrefetchPair,Double>>();
+ pmap_hash = new Hashtable<FlatNode, Hashtable<FlatNode, PairMap>>();
+ 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<FlatNode, HashSet<PrefetchPair>> newprefetchset = new Hashtable<FlatNode, HashSet<PrefetchPair>>();
+ 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<PrefetchPair, Double> nodehash = new Hashtable<PrefetchPair, Double>();
- /* 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<PrefetchPair, Double> nodehash = new Hashtable<PrefetchPair, Double>();
+ /* 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<PrefetchPair, Double> child_prefetch_set_copy = new Hashtable<PrefetchPair, Double>();
- if(curr.numNext() != 0) {
- FlatNode child_node = curr.getNext(0);
- if(prefetch_hash.containsKey(child_node)) {
- child_prefetch_set_copy = (Hashtable<PrefetchPair,Double>) 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<PrefetchPair, Double> oldPrefetchSet, Hashtable<PrefetchPair, Double> 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<PrefetchPair, Double> child_prefetch_set_copy = new Hashtable<PrefetchPair, Double>();
+ if(curr.numNext() != 0) {
+ FlatNode child_node = curr.getNext(0);
+ if(prefetch_hash.containsKey(child_node)) {
+ child_prefetch_set_copy = (Hashtable<PrefetchPair,Double>)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<FlatNode, PairMap>());
- }
- 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<PrefetchPair, Double> oldPrefetchSet, Hashtable<PrefetchPair, Double> 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<PrefetchPair, Double> newset) {
- Hashtable<PrefetchPair, Double>oldset=prefetch_hash.get(curr);
- if (comparePrefetchSets(oldset, newset)) {
- for(int i=0;i<curr.numPrev();i++) {
- tovisit.add(curr.getPrev(i));
- }
- prefetch_hash.put(curr, newset);
- }
+ 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<FlatNode, PairMap>());
}
+ 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<PrefetchPair, Double> child_prefetch_set_copy) {
- Hashtable<PrefetchPair, Double> currcopy = new Hashtable<PrefetchPair, Double>();
- Hashtable<PrefetchPair, Double> tocompare = new Hashtable<PrefetchPair, Double>();
- 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<Descriptor> newdesc = new ArrayList<Descriptor>();
- 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<PrefetchPair, Double> newset) {
+ Hashtable<PrefetchPair, Double>oldset=prefetch_hash.get(curr);
+ if (comparePrefetchSets(oldset, newset)) {
+ for(int i=0; i<curr.numPrev(); i++) {
+ tovisit.add(curr.getPrev(i));
+ }
+ prefetch_hash.put(curr, newset);
+ }
+ }
- for(Iterator<PrefetchPair> it=tocompare.keySet().iterator();it.hasNext();) {
- PrefetchPair pp=it.next();
- if (tocompare.get(pp)<ANALYSIS_THRESHOLD_PROB)
- it.remove();
-
- }
-
- updatePairMap(curr, pm, 0);
- updatePrefetchSet(curr, tocompare);
- }
-
- /** This function processes the prefetch set of a FlatElementNode
- * 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 updates the global flatnode hash table
- * */
- private void processFlatElementNode(FlatNode curr, Hashtable<PrefetchPair, Double> child_prefetch_set_copy) {
-
- Hashtable<PrefetchPair, Double> currcopy = new Hashtable<PrefetchPair, Double>();
- Hashtable<PrefetchPair, Double> tocompare = new Hashtable<PrefetchPair, Double>();
- 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<Descriptor> newdesc = new ArrayList<Descriptor>();
- 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<PrefetchPair, Double> child_prefetch_set_copy) {
+ Hashtable<PrefetchPair, Double> currcopy = new Hashtable<PrefetchPair, Double>();
+ Hashtable<PrefetchPair, Double> tocompare = new Hashtable<PrefetchPair, Double>();
+ 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<Descriptor> newdesc = new ArrayList<Descriptor>();
+ 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<PrefetchPair> it=tocompare.keySet().iterator(); it.hasNext();) {
+ PrefetchPair pp=it.next();
+ if (tocompare.get(pp)<ANALYSIS_THRESHOLD_PROB)
+ it.remove();
+
+ }
+
+ updatePairMap(curr, pm, 0);
+ updatePrefetchSet(curr, tocompare);
+ }
+
+ /** This function processes the prefetch set of a FlatElementNode
+ * 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 updates the global flatnode hash table
+ * */
+ private void processFlatElementNode(FlatNode curr, Hashtable<PrefetchPair, Double> child_prefetch_set_copy) {
+
+ Hashtable<PrefetchPair, Double> currcopy = new Hashtable<PrefetchPair, Double>();
+ Hashtable<PrefetchPair, Double> tocompare = new Hashtable<PrefetchPair, Double>();
+ 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<Descriptor> newdesc = new ArrayList<Descriptor>();
+ 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<PrefetchPair, Double> child_prefetch_set_copy) {
- Hashtable<PrefetchPair, Double> tocompare = new Hashtable<PrefetchPair, Double>();
- 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<Descriptor> newdesc = new ArrayList<Descriptor>();
- 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<PrefetchPair, Double> child_prefetch_set_copy) {
+ Hashtable<PrefetchPair, Double> tocompare = new Hashtable<PrefetchPair, Double>();
+ 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<Descriptor> newdesc = new ArrayList<Descriptor>();
+ 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<PrefetchPair, Double> child_prefetch_set_copy) {
- Hashtable<PrefetchPair, Double> tocompare = new Hashtable<PrefetchPair, Double>();
- 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<Descriptor> newdesc = new ArrayList<Descriptor>();
- 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<PrefetchPair, Double> child_prefetch_set_copy) {
- int index;
- Hashtable<PrefetchPair, Double> tocompare = new Hashtable<PrefetchPair, Double>();
- 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<Descriptor> newdesc = new ArrayList<Descriptor>();
- 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<PrefetchPair, Double> child_prefetch_set_copy) {
+ Hashtable<PrefetchPair, Double> tocompare = new Hashtable<PrefetchPair, Double>();
+ 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<Descriptor> newdesc = new ArrayList<Descriptor>();
+ 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<PrefetchPair, Double> child_prefetch_set_copy) {
+ int index;
+ Hashtable<PrefetchPair, Double> tocompare = new Hashtable<PrefetchPair, Double>();
+ 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<Descriptor> newdesc = new ArrayList<Descriptor>();
+ 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<PrefetchPair, Double> child_prefetch_set_copy) {
- Hashtable<PrefetchPair, Double> tocompare = new Hashtable<PrefetchPair, Double>();
- 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<Descriptor> copychilddesc = (ArrayList<Descriptor>) copyofchildpp.getDesc();
- int sizetempdesc = copychilddesc.size();
- for(ListIterator it = copychilddesc.listIterator();it.hasNext();) {
- Object o = it.next();
- if(o instanceof IndexDescriptor) {
- ArrayList<TempDescriptor> td = (ArrayList<TempDescriptor>)((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<Descriptor> newdesc = new ArrayList<Descriptor>();
- 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<PrefetchPair, Double> child_prefetch_set_copy) {
- Hashtable<PrefetchPair, Double> tocompare = new Hashtable<PrefetchPair, Double>();
- 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<PrefetchPair, Double> tocompare = new Hashtable<PrefetchPair, Double>();//temporary hash table
- PairMap truepm = new PairMap();
- PairMap falsepm = new PairMap();
- Hashtable<PrefetchPair, Double> truechild=prefetch_hash.get(fcb.getNext(0));
- Hashtable<PrefetchPair, Double> falsechild=prefetch_hash.get(fcb.getNext(1));
-
- HashSet<PrefetchPair> allpp=new HashSet<PrefetchPair>();
- allpp.addAll(truechild.keySet());
- allpp.addAll(falsechild.keySet());
-
- for(Iterator<PrefetchPair> 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<falseprob) {
- newprob=falseprob;
- }
-
- if(newprob < ANALYSIS_THRESHOLD_PROB) //Skip pp that are below threshold
- continue;
+ }
+ } else {
+ //FIXME Is not taken care of for cases like x = -y followed by a[x].i
+ }
- tocompare.put(pp, newprob);
- if (truechild.containsKey(pp))
- truepm.addPair(pp, pp);
+ /* 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);
+ }
- if (falsechild.containsKey(pp))
- falsepm.addPair(pp, pp);
+ updatePairMap(curr, pm, 0);
+ updatePrefetchSet(curr, tocompare);
+ }
- }
-
- updatePairMap(fcb, truepm, 0);
- updatePairMap(fcb, falsepm, 1);
- updatePrefetchSet(fcb, tocompare);
- }
-
- /** If FlatNode is not concerned with the prefetch set of its Child then propagate
- * prefetches up the FlatNode*/
- private void processDefaultCase(FlatNode curr, Hashtable<PrefetchPair, Double> child_prefetch_set_copy) {
- PairMap pm = new PairMap();
- Hashtable<PrefetchPair, Double> tocompare = new Hashtable<PrefetchPair, Double>();
-
- /* 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<writearray.length;i++) {
- TempDescriptor wtd=writearray[i];
- if(childpp.base == wtd||
- childpp.containsTemp(wtd))
- continue nexttemp;
- }
- tocompare.put(childpp, child_prefetch_set_copy.get(childpp));
- pm.addPair(childpp, childpp);
- }
-
- updatePairMap(curr, pm, 0);
- updatePrefetchSet(curr, tocompare);
- }
-
- /** If FlatNode is not concerned with the prefetch set of its Child then propagate
- * prefetches up the FlatNode*/
- private void processCall(FlatCall curr, Hashtable<PrefetchPair, Double> child_prefetch_set_copy) {
- PairMap pm = new PairMap();
- Hashtable<PrefetchPair, Double> tocompare = new Hashtable<PrefetchPair, Double>();
-
- /* 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<writearray.length;i++) {
- TempDescriptor wtd=writearray[i];
- if(childpp.base == wtd||
- childpp.containsTemp(wtd))
- continue nexttemp;
+ /** 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<PrefetchPair, Double> child_prefetch_set_copy) {
+ Hashtable<PrefetchPair, Double> tocompare = new Hashtable<PrefetchPair, Double>();
+ 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<Descriptor> copychilddesc = (ArrayList<Descriptor>)copyofchildpp.getDesc();
+ int sizetempdesc = copychilddesc.size();
+ for(ListIterator it = copychilddesc.listIterator(); it.hasNext();) {
+ Object o = it.next();
+ if(o instanceof IndexDescriptor) {
+ ArrayList<TempDescriptor> td = (ArrayList<TempDescriptor>)((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<PrefetchPair, Double> currhash = (Hashtable) prefetch_hash.get(fn);
- for(Enumeration pphash= currhash.keys(); pphash.hasMoreElements();) {
- PrefetchPair pp = (PrefetchPair) pphash.nextElement();
- System.out.print(pp.toString() + ", ");
+ }
+ ArrayList<Descriptor> newdesc = new ArrayList<Descriptor>();
+ 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<FlatNode, HashSet<PrefetchPair>> newprefetchset) {
- Hashtable<FlatNode, HashSet<PrefetchPair>> pset1_hash = new Hashtable<FlatNode, HashSet<PrefetchPair>>();
- HashSet<PrefetchPair> pset1_init = new HashSet<PrefetchPair>();
- LinkedList<FlatNode> newtovisit = new LinkedList<FlatNode>();
- LinkedList<FlatNode> newvisited = new LinkedList<FlatNode>();
-
- 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<fn.numNext(); i++) {
- FlatNode nn = fn.getNext(i);
- if(!newtovisit.contains(nn) && !newvisited.contains(nn)){
- newtovisit.addLast(nn);
- }
- }
- }
-
- /* Start with a top down sorted order of nodes */
- while(!newvisited.isEmpty()) {
- applyPrefetchInsertRules((FlatNode) newvisited.getFirst(), newvisited, pset1_hash, newprefetchset);
- newvisited.remove(0);
- }
- delSubsetPPairs(newprefetchset);
- }
-
- /** This function deletes the smaller prefetch pair subset from a list of prefetch pairs
- * for e.g. if there are 2 prefetch pairs a.b.c.d and a.b.c for a given flatnode
- * then this function drops a.b.c from the prefetch set of the flatnode */
- private void delSubsetPPairs(Hashtable<FlatNode, HashSet<PrefetchPair>> newprefetchset) {
- for (Enumeration e = newprefetchset.keys();e.hasMoreElements();) {
- FlatNode fn = (FlatNode) e.nextElement();
- Set<PrefetchPair> ppairs = newprefetchset.get(fn);
- Set<PrefetchPair> toremove=new HashSet<PrefetchPair>();
-
- for(Iterator<PrefetchPair> it1=ppairs.iterator();it1.hasNext();) {
- PrefetchPair pp1=it1.next();
- if (toremove.contains(pp1))
- continue;
- int l1=pp1.desc.size()+1;
- for(Iterator<PrefetchPair> it2=ppairs.iterator();it2.hasNext();) {
- PrefetchPair pp2=it2.next();
- int l2=pp2.desc.size()+1;
-
- if (l1<l2&&isSubSet(pp1,pp2))
- toremove.add(pp1);
- else
- if (l2>l1&&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<PrefetchPair, Double> child_prefetch_set_copy) {
+ Hashtable<PrefetchPair, Double> tocompare = new Hashtable<PrefetchPair, Double>();
+ 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<PrefetchPair, Double> tocompare = new Hashtable<PrefetchPair, Double>(); //temporary hash table
+ PairMap truepm = new PairMap();
+ PairMap falsepm = new PairMap();
+ Hashtable<PrefetchPair, Double> truechild=prefetch_hash.get(fcb.getNext(0));
+ Hashtable<PrefetchPair, Double> falsechild=prefetch_hash.get(fcb.getNext(1));
+
+ HashSet<PrefetchPair> allpp=new HashSet<PrefetchPair>();
+ allpp.addAll(truechild.keySet());
+ allpp.addAll(falsechild.keySet());
+
+ for(Iterator<PrefetchPair> 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<falseprob) {
+ newprob=falseprob;
+ }
+
+ if(newprob < ANALYSIS_THRESHOLD_PROB) //Skip pp that are below threshold
+ continue;
+
+ tocompare.put(pp, newprob);
+ if (truechild.containsKey(pp))
+ truepm.addPair(pp, pp);
+
+ if (falsechild.containsKey(pp))
+ falsepm.addPair(pp, pp);
+
+ }
+
+ updatePairMap(fcb, truepm, 0);
+ updatePairMap(fcb, falsepm, 1);
+ updatePrefetchSet(fcb, tocompare);
+ }
+
+ /** If FlatNode is not concerned with the prefetch set of its Child then propagate
+ * prefetches up the FlatNode*/
+ private void processDefaultCase(FlatNode curr, Hashtable<PrefetchPair, Double> child_prefetch_set_copy) {
+ PairMap pm = new PairMap();
+ Hashtable<PrefetchPair, Double> tocompare = new Hashtable<PrefetchPair, Double>();
+
+ /* 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<writearray.length; i++) {
+ TempDescriptor wtd=writearray[i];
+ if(childpp.base == wtd||
+ childpp.containsTemp(wtd))
+ continue nexttemp;
+ }
+ tocompare.put(childpp, child_prefetch_set_copy.get(childpp));
+ pm.addPair(childpp, childpp);
+ }
+
+ updatePairMap(curr, pm, 0);
+ updatePrefetchSet(curr, tocompare);
+ }
+
+ /** If FlatNode is not concerned with the prefetch set of its Child then propagate
+ * prefetches up the FlatNode*/
+ private void processCall(FlatCall curr, Hashtable<PrefetchPair, Double> child_prefetch_set_copy) {
+ PairMap pm = new PairMap();
+ Hashtable<PrefetchPair, Double> tocompare = new Hashtable<PrefetchPair, Double>();
+
+ /* 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<writearray.length; i++) {
+ TempDescriptor wtd=writearray[i];
+ if(childpp.base == wtd||
+ childpp.containsTemp(wtd))
+ continue nexttemp;
+ }
+ 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<PrefetchPair, Double> 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<FlatNode, HashSet<PrefetchPair>> newprefetchset) {
+ Hashtable<FlatNode, HashSet<PrefetchPair>> pset1_hash = new Hashtable<FlatNode, HashSet<PrefetchPair>>();
+ HashSet<PrefetchPair> pset1_init = new HashSet<PrefetchPair>();
+ LinkedList<FlatNode> newtovisit = new LinkedList<FlatNode>();
+ LinkedList<FlatNode> newvisited = new LinkedList<FlatNode>();
+
+ 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<fn.numNext(); i++) {
+ FlatNode nn = fn.getNext(i);
+ if(!newtovisit.contains(nn) && !newvisited.contains(nn)){
+ newtovisit.addLast(nn);
+ }
+ }
+ }
+
+ /* Start with a top down sorted order of nodes */
+ while(!newvisited.isEmpty()) {
+ applyPrefetchInsertRules((FlatNode) newvisited.getFirst(), newvisited, pset1_hash, newprefetchset);
+ newvisited.remove(0);
+ }
+ delSubsetPPairs(newprefetchset);
+ }
+
+ /** This function deletes the smaller prefetch pair subset from a list of prefetch pairs
+ * for e.g. if there are 2 prefetch pairs a.b.c.d and a.b.c for a given flatnode
+ * then this function drops a.b.c from the prefetch set of the flatnode */
+ private void delSubsetPPairs(Hashtable<FlatNode, HashSet<PrefetchPair>> newprefetchset) {
+ for (Enumeration e = newprefetchset.keys(); e.hasMoreElements();) {
+ FlatNode fn = (FlatNode) e.nextElement();
+ Set<PrefetchPair> ppairs = newprefetchset.get(fn);
+ Set<PrefetchPair> toremove=new HashSet<PrefetchPair>();
+
+ for(Iterator<PrefetchPair> it1=ppairs.iterator(); it1.hasNext();) {
+ PrefetchPair pp1=it1.next();
+ if (toremove.contains(pp1))
+ continue;
+ int l1=pp1.desc.size()+1;
+ for(Iterator<PrefetchPair> it2=ppairs.iterator(); it2.hasNext();) {
+ PrefetchPair pp2=it2.next();
+ int l2=pp2.desc.size()+1;
+
+ if (l1<l2&&isSubSet(pp1,pp2))
+ toremove.add(pp1);
+ else
+ if (l2>l1&&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<PrefetchPair> oldPSet, HashSet<PrefetchPair>newPSet) {
- 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<PrefetchPair> oldPSet, HashSet<PrefetchPair>newPSet) {
+ 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<FlatNode> newvisited, Hashtable<FlatNode, HashSet<PrefetchPair>> pset1_hash, Hashtable<FlatNode, HashSet<PrefetchPair>> newprefetchset) {
+ if(fn.kind() == FKind.FlatMethod) {
+ HashSet<PrefetchPair> pset1 = new HashSet<PrefetchPair>();
+ Hashtable<PrefetchPair, Double> 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<fn.numNext(); j++) {
+ FlatNode nn = fn.getNext(j);
+ newvisited.addLast((FlatNode)nn);
+ }
+ pset1_hash.put(fn, pset1);
+ }
+ newprefetchset.put(fn, pset1);
+ } else { /* Nodes other than Flat Method Node */
+ HashSet<PrefetchPair> pset2 = new HashSet<PrefetchPair>();
+ HashSet<PrefetchPair> newpset = new HashSet<PrefetchPair>();
+ Hashtable<PrefetchPair, Double> prefetchset = prefetch_hash.get(fn);
+ Hashtable<FlatNode, PairMap> 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<fn.numPrev(); i++) {
+ FlatNode parentnode=fn.getPrev(i);
+ PairMap pm = (PairMap) ppairmaphash.get(parentnode);
+ //Find if probability is less for previous node
+ if(pm!=null&&pm.getPair(pp) != null) {
+ PrefetchPair mappedpp = pm.getPair(pp);
+ if(prefetch_hash.get(parentnode).containsKey(mappedpp)) {
+ double prob = prefetch_hash.get(parentnode).get(mappedpp).doubleValue();
+ if(prob < PREFETCH_THRESHOLD_PROB)
+ mapprobIsLess = true;
+ } else
+ mapprobIsLess = true;
+ } else {
+ mapprobIsLess = true;
+ }
+ /* Build pset2 */
+ if(pm !=null) {
+ HashSet pset = pset1_hash.get(parentnode);
+ if(pset.isEmpty()||!pset.contains((PrefetchPair) pm.getPair(pp)))
+ mapIsPresent = false;
+ } else
+ mapIsPresent=false;
}
- 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<FlatNode> newvisited, Hashtable<FlatNode, HashSet<PrefetchPair>> pset1_hash, Hashtable<FlatNode, HashSet<PrefetchPair>> newprefetchset) {
+
+ if(mapIsPresent)
+ pset2.add(pp);
+
+ if(pprobIsGreater && mapprobIsLess)
+ newpset.add(pp);
+ }
+
+ HashSet<PrefetchPair> pset1 = new HashSet<PrefetchPair>();
+ 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<fn.numNext(); i++) {
+ FlatNode nn = fn.getNext(i);
+ newvisited.addLast((FlatNode)nn);
+ }
+ pset1_hash.put(fn, pset1);
+ }
+
+ /* To insert prefetch, apply rule: if the newpset minus pset2 is nonempty
+ * then insert a new prefetch node here*/
+
+ HashSet<PrefetchPair> s = new HashSet<PrefetchPair>();
+ s.addAll(newpset);
+ s.removeAll(pset2);
+ newprefetchset.put(fn, s);
+ }
+ }
+
+ private void addFlatPrefetchNode(Hashtable<FlatNode, HashSet<PrefetchPair>> 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<PrefetchPair> pset1 = new HashSet<PrefetchPair>();
- Hashtable<PrefetchPair, Double> 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<fn.numNext(); j++) {
- FlatNode nn = fn.getNext(j);
- newvisited.addLast((FlatNode)nn);
- }
- pset1_hash.put(fn, pset1);
- }
- newprefetchset.put(fn, pset1);
- } else { /* Nodes other than Flat Method Node */
- HashSet<PrefetchPair> pset2 = new HashSet<PrefetchPair>();
- HashSet<PrefetchPair> newpset = new HashSet<PrefetchPair>();
- Hashtable<PrefetchPair, Double> prefetchset = prefetch_hash.get(fn);
- Hashtable<FlatNode, PairMap> 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<fn.numPrev();i++) {
- FlatNode parentnode=fn.getPrev(i);
- PairMap pm = (PairMap) ppairmaphash.get(parentnode);
- //Find if probability is less for previous node
- if(pm!=null&&pm.getPair(pp) != null) {
- PrefetchPair mappedpp = pm.getPair(pp);
- if(prefetch_hash.get(parentnode).containsKey(mappedpp)) {
- double prob = prefetch_hash.get(parentnode).get(mappedpp).doubleValue();
- if(prob < PREFETCH_THRESHOLD_PROB)
- mapprobIsLess = true;
- } else
- mapprobIsLess = true;
- } else {
- mapprobIsLess = true;
- }
- /* Build pset2 */
- if(pm !=null) {
- HashSet pset = pset1_hash.get(parentnode);
- if(pset.isEmpty()||!pset.contains((PrefetchPair) pm.getPair(pp)))
- mapIsPresent = false;
- } else
- mapIsPresent=false;
- }
-
- if(mapIsPresent)
- pset2.add(pp);
-
- if(pprobIsGreater && mapprobIsLess)
- newpset.add(pp);
+ 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;
}
-
- HashSet<PrefetchPair> pset1 = new HashSet<PrefetchPair>();
- 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<fn.numNext(); i++) {
- FlatNode nn = fn.getNext(i);
- newvisited.addLast((FlatNode)nn);
+ }
+ if(!isFNPresent) {
+ while(fn.numPrev() > 0) {
+ FlatNode nn = fn.getPrev(0);
+ for(int j = 0; j<nn.numNext(); j++) {
+ if(nn.getNext(j) == fn) {
+ nn.setNext(j, fpn);
}
- pset1_hash.put(fn, pset1);
+ }
}
-
- /* To insert prefetch, apply rule: if the newpset minus pset2 is nonempty
- * then insert a new prefetch node here*/
-
- HashSet<PrefetchPair> s = new HashSet<PrefetchPair>();
- s.addAll(newpset);
- s.removeAll(pset2);
- newprefetchset.put(fn, s);
- }
- }
-
- private void addFlatPrefetchNode(Hashtable<FlatNode, HashSet<PrefetchPair>> 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<nn.numNext(); j++) {
- if(nn.getNext(j) == fn) {
- nn.setNext(j, fpn);
- }
- }
- }
- fpn.addNext(fn);
- fpn.siteid = prefetchsiteid++;
- }
- } //end of else
- } //End of if
- } //end of for
- }
+ fpn.addNext(fn);
+ fpn.siteid = prefetchsiteid++;
+ }
+ } //end of else
+ } //End of if
+ } //end of for
+ }
}
import IR.*;
public class PrefetchPair {
- public TempDescriptor base;
- public ArrayList<Descriptor> desc;
-
- public PrefetchPair(){
- base = new TempDescriptor("");
- desc = new ArrayList<Descriptor>();
- }
-
- public PrefetchPair(TempDescriptor t, Descriptor f) {
- base = t;
- desc = new ArrayList<Descriptor>();
- desc.add(f);
- }
+ public TempDescriptor base;
+ public ArrayList<Descriptor> desc;
- public PrefetchPair(TempDescriptor t, ArrayList<Descriptor> descriptor) {
- base = t;
- desc = new ArrayList<Descriptor>();
- desc.addAll(descriptor);
- }
+ public PrefetchPair() {
+ base = new TempDescriptor("");
+ desc = new ArrayList<Descriptor>();
+ }
- public TempDescriptor getBase() {
- return base;
- }
-
- public Descriptor getDescAt(int index) {
- return desc.get(index);
- }
-
- public ArrayList<Descriptor> 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<Descriptor>();
+ desc.add(f);
+ }
+
+ public PrefetchPair(TempDescriptor t, ArrayList<Descriptor> descriptor) {
+ base = t;
+ desc = new ArrayList<Descriptor>();
+ desc.addAll(descriptor);
+ }
+
+ public TempDescriptor getBase() {
+ return base;
+ }
+
+ public Descriptor getDescAt(int index) {
+ return desc.get(index);
+ }
+
+ public ArrayList<Descriptor> 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<TempDescriptor> td = new ArrayList<TempDescriptor>();
- 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<TempDescriptor> td = new ArrayList<TempDescriptor>();
+ 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<Descriptor> desc = (ArrayList<Descriptor>) getDesc();
- for(ListIterator it = desc.listIterator();it.hasNext();) {
- Object o = it.next();
- if(o instanceof IndexDescriptor) {
- ArrayList<TempDescriptor> tdarray = (ArrayList<TempDescriptor>)((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<Descriptor> desc = (ArrayList<Descriptor>)getDesc();
+ for(ListIterator it = desc.listIterator(); it.hasNext();) {
+ Object o = it.next();
+ if(o instanceof IndexDescriptor) {
+ ArrayList<TempDescriptor> tdarray = (ArrayList<TempDescriptor>)((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<Descriptor> desc = (ArrayList<Descriptor>) npp.getDesc();
- for(ListIterator it = desc.listIterator();it.hasNext();) {
- Object currdesc = it.next();
- if(currdesc instanceof IndexDescriptor) {
- ArrayList<TempDescriptor> tdarray = (ArrayList<TempDescriptor>)((IndexDescriptor)currdesc).tddesc;
- if (tdarray.contains(td)) {
- int index = tdarray.indexOf(td);
- tdarray.set(index, newtd[0]);
- for(int i=1;i<newtd.length;i++) {
- tdarray.add(newtd[i]);
- }
- }
- }
+ /** 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<Descriptor> desc = (ArrayList<Descriptor>)npp.getDesc();
+ for(ListIterator it = desc.listIterator(); it.hasNext();) {
+ Object currdesc = it.next();
+ if(currdesc instanceof IndexDescriptor) {
+ ArrayList<TempDescriptor> tdarray = (ArrayList<TempDescriptor>)((IndexDescriptor)currdesc).tddesc;
+ if (tdarray.contains(td)) {
+ int index = tdarray.indexOf(td);
+ tdarray.set(index, newtd[0]);
+ for(int i=1; i<newtd.length; i++) {
+ tdarray.add(newtd[i]);
+ }
}
- return npp;
+ }
}
+ return npp;
+ }
}
/** This class holds a flag diagram for one class.
*/
-public class ClassNode extends GraphNode implements Cloneable{
-
- private int uid;
- private static int nodeID=0;
-
- private final ClassDescriptor cd;
- private ScheduleNode sn;
- private Vector<FlagState> flagStates;
- private boolean sorted = false;
- private boolean clone = false;
-
- private int transTime;
-
- /** Class constructor
- * @param cd ClassDescriptor
- * @param fStates
- */
- public ClassNode(ClassDescriptor cd, Vector<FlagState> 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<FlagState> 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<FlagState> 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<FlagState> 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<FlagState> 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();
}
+ }
}
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<Vector<ScheduleNode>> 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<Vector<ScheduleNode>> rootnodes, Vector<Vector<ScheduleNode>> node2combine) {
- return CombinationUtil.allocateCombinationUtil().new CombineGenerator(rootnodes, node2combine);
+ return cu;
+ }
+
+ public static RootsGenerator allocateRootsGenerator(Vector<Vector<ScheduleNode>> snodevecs, int rootNum) {
+ return CombinationUtil.allocateCombinationUtil().new RootsGenerator(snodevecs, rootNum);
+ }
+
+ public static CombineGenerator allocateCombineGenerator(Vector<Vector<ScheduleNode>> rootnodes, Vector<Vector<ScheduleNode>> node2combine) {
+ return CombinationUtil.allocateCombinationUtil().new CombineGenerator(rootnodes, node2combine);
+ }
+
+ public class RootsGenerator {
+ Vector<Vector<ScheduleNode>> sNodeVecs;
+ Vector<Vector<ScheduleNode>> node2Combine;
+ Vector<Vector<ScheduleNode>> rootNodes;
+ int rootNum;
+
+ public RootsGenerator(Vector<Vector<ScheduleNode>> snodevecs, int rootNum) {
+ this.sNodeVecs = snodevecs;
+ this.rootNum = rootNum;
+ this.node2Combine = null;
+ this.rootNodes = null;
}
-
- public class RootsGenerator {
- Vector<Vector<ScheduleNode>> sNodeVecs;
- Vector<Vector<ScheduleNode>> node2Combine;
- Vector<Vector<ScheduleNode>> rootNodes;
- int rootNum;
-
- public RootsGenerator(Vector<Vector<ScheduleNode>> 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<Vector<ScheduleNode>>();
+ this.rootNodes.add(new Vector<ScheduleNode>());
+ Vector<ScheduleNode> 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<Vector<ScheduleNode>>();
- this.rootNodes.add(new Vector<ScheduleNode>());
- Vector<ScheduleNode> 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<Vector<ScheduleNode>>();
+ 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<ScheduleNode> toadd = this.sNodeVecs.elementAt(next);
+ if(toadd != null) {
+ this.node2Combine.add(new Vector<ScheduleNode>());
+ 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<Vector<ScheduleNode>>();
- 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<ScheduleNode> toadd = this.sNodeVecs.elementAt(next);
- if(toadd != null) {
- this.node2Combine.add(new Vector<ScheduleNode>());
- for(index = 0; index < toadd.size(); index++) {
- this.node2Combine.lastElement().add(toadd.elementAt(index));
- }
- } else {
- this.node2Combine.add(null);
- }
- next++;
- }
- Vector<ScheduleNode> toadd = this.sNodeVecs.elementAt(tmp);
- if(toadd.size() > this.rootNodes.elementAt(i).size()) {
- this.node2Combine.add(new Vector<ScheduleNode>());
- 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<ScheduleNode> toadd = this.sNodeVecs.elementAt(next);
- if(toadd != null) {
- this.node2Combine.add(new Vector<ScheduleNode>());
- for(index = 0; index < toadd.size(); index++) {
- this.node2Combine.lastElement().add(toadd.elementAt(index));
- }
- } else {
- this.node2Combine.add(null);
- }
- next++;
- }
+ next++;
+ }
+ Vector<ScheduleNode> toadd = this.sNodeVecs.elementAt(tmp);
+ if(toadd.size() > this.rootNodes.elementAt(i).size()) {
+ this.node2Combine.add(new Vector<ScheduleNode>());
+ 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<ScheduleNode>());
- 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<ScheduleNode> toadd = this.sNodeVecs.elementAt(next);
+ if(toadd != null) {
+ this.node2Combine.add(new Vector<ScheduleNode>());
+ 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<Vector<ScheduleNode>> 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<ScheduleNode>());
+ 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<Vector<ScheduleNode>> getNode2Combine() {
+ return node2Combine;
+ }
+
+ public Vector<Vector<ScheduleNode>> 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<Vector<ScheduleNode>> rootNodes;
+ Vector<Vector<int[]>> rootNStates;
+ Vector<Vector<ScheduleNode>> node2Combine;
+ Vector<Vector<Combine>> combine;
+ int[] lastchoices;
+ boolean first4choice;
- public Vector<Vector<ScheduleNode>> getRootNodes() {
- return rootNodes;
+ public CombineGenerator(Vector<Vector<ScheduleNode>> rootnodes, Vector<Vector<ScheduleNode>> node2combine) {
+ this.rootNodes = rootnodes;
+ this.node2Combine = node2combine;
+ this.rootNStates = new Vector<Vector<int[]>>();
+ for(int i = 0; i < this.rootNodes.size(); i++) {
+ this.rootNStates.add(new Vector<int[]>());
+ 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<Vector<Combine>>();
+ 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<Combine>());
+ 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<Vector<Combine>> 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<Vector<ScheduleNode>> rootNodes;
- Vector<Vector<int[]>> rootNStates;
- Vector<Vector<ScheduleNode>> node2Combine;
- Vector<Vector<Combine>> combine;
- int[] lastchoices;
- boolean first4choice;
-
- public CombineGenerator(Vector<Vector<ScheduleNode>> rootnodes, Vector<Vector<ScheduleNode>> node2combine) {
- this.rootNodes = rootnodes;
- this.node2Combine = node2combine;
- this.rootNStates = new Vector<Vector<int[]>>();
- for(int i = 0; i < this.rootNodes.size(); i++) {
- this.rootNStates.add(new Vector<int[]>());
- 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<Vector<Combine>>();
- 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<Combine>());
- 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<Vector<Combine>> 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
import IR.TaskDescriptor;
public class CoreSimulator {
- Vector<TaskSimulator> tasks;
- RuntimeSchedule rSchedule;
- TaskSimulator rtask;
- Hashtable<FlagState, Queue<Integer>> targetCSimulator;
- Hashtable<FlagState, Vector<Integer>> allyCSimulator;
- Hashtable<FlagState, FlagState> 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<TaskDescriptor> tasks) {
- if(tasks == null) {
- return;
- }
-
- if(this.tasks == null) {
- this.tasks = new Vector<TaskSimulator>();
- } 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<Integer> getTargetCores(FlagState fstate) {
- if(targetCSimulator == null) {
- return null;
- }
- return targetCSimulator.get(fstate);
- }
+ Vector<TaskSimulator> tasks;
+ RuntimeSchedule rSchedule;
+ TaskSimulator rtask;
+ Hashtable<FlagState, Queue<Integer>> targetCSimulator;
+ Hashtable<FlagState, Vector<Integer>> allyCSimulator;
+ Hashtable<FlagState, FlagState> targetFState;
+ int coreNum;
+ int activeTime;
- public void setTargetCSimulator(Hashtable<FlagState, Queue<Integer>> 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<TaskDescriptor> tasks) {
+ if(tasks == null) {
+ return;
}
-
- public Vector<Integer> getAllyCores(FlagState fstate) {
- if(allyCSimulator == null) {
- return null;
- }
- return allyCSimulator.get(fstate);
+
+ if(this.tasks == null) {
+ this.tasks = new Vector<TaskSimulator>();
+ } else {
+ this.tasks.clear();
}
- public void setAllyCSimulator(Hashtable<FlagState, Vector<Integer>> 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<Integer> getTargetCores(FlagState fstate) {
+ if(targetCSimulator == null) {
+ return null;
}
+ return targetCSimulator.get(fstate);
+ }
- public void setTargetFState(Hashtable<FlagState, FlagState> targetFState) {
- this.targetFState = targetFState;
+ public void setTargetCSimulator(Hashtable<FlagState, Queue<Integer>> targetCSimulator) {
+ this.targetCSimulator = targetCSimulator;
+ }
+
+ public Vector<Integer> getAllyCores(FlagState fstate) {
+ if(allyCSimulator == null) {
+ return null;
}
+ return allyCSimulator.get(fstate);
+ }
+
+ public void setAllyCSimulator(Hashtable<FlagState, Vector<Integer>> 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<FlagState, FlagState> targetFState) {
+ this.targetFState = targetFState;
+ }
+
+ public int getActiveTime() {
+ return activeTime;
+ }
+
+ public int getCoreNum() {
+ return coreNum;
+ }
+
+ public Vector<TaskSimulator> 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<TaskSimulator> 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<ObjectSimulator> finishTask() {
+ assert(this.rtask != null);
- public void addObject(ObjectSimulator newObj) {
- if(this.tasks == null) {
- return;
+ Vector<ObjectSimulator> transObjs = null;
+ Vector<Queue<ObjectSimulator>> 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<ObjectSimulator>();
}
- 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<Integer> 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<ObjectSimulator>();
+ }
+ if(!transObjs.contains(obj)) {
+ transObjs.add(obj);
+ }
+ remove = false;
}
- }
-
- public Vector<ObjectSimulator> finishTask() {
- assert(this.rtask != null);
-
- Vector<ObjectSimulator> transObjs = null;
- Vector<Queue<ObjectSimulator>> 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<ObjectSimulator>();
- }
- if(!transObjs.contains(obj)) {
- transObjs.add(obj);
- }
- remove = true;
- }
- // check if this object becoming shared or not
- Vector<Integer> 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<ObjectSimulator>();
- }
- 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
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<TaskSimulator> 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<Queue<ObjectSimulator>> pqueues = next.getParaQueues();
- if((pqueues == null) || (pqueues.size() < paraNum)) {
- continue;
- }
- int j = 0;
- for(; j < pqueues.size(); j++) {
- Queue<ObjectSimulator> 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<TaskSimulator> 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<Queue<ObjectSimulator>> pqueues = next.getParaQueues();
+ if((pqueues == null) || (pqueues.size() < paraNum)) {
+ continue;
+ }
+ int j = 0;
+ for(; j < pqueues.size(); j++) {
+ Queue<ObjectSimulator> 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
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
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
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<TaskSimulator> tasks);
-
- public String algorithm() {
- return rsAlgorithm;
- }
+ public RuntimeSchedule(String rsAlgorithm) {
+ super();
+ this.rsAlgorithm = rsAlgorithm;
+ }
+
+ public abstract TaskSimulator schedule(Vector<TaskSimulator> tasks);
+
+ public String algorithm() {
+ return rsAlgorithm;
+ }
}
\ No newline at end of file
/** This class holds flag transition diagram(s) can be put on one core.
*/
public class Schedule {
- private int coreNum;
- private Vector<TaskDescriptor> tasks;
- private Hashtable<FlagState, Queue<Integer>> targetCores;
- private Hashtable<FlagState, FlagState> targetFState; // only affected by transimit edges
- private Hashtable<FlagState, Vector<Integer>> allyCores;
- private Hashtable<TaskDescriptor, Vector<FlagState>> 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<FlagState, Queue<Integer>> getTargetCoreTable() {
- return targetCores;
- }
-
- public Queue<Integer> getTargetCores(FlagState fstate) {
- if(targetCores == null) {
- return null;
- }
- return targetCores.get(fstate);
- }
-
- public Hashtable<FlagState, FlagState> getTargetFStateTable() {
- return targetFState;
- }
-
- public FlagState getTargetFState(FlagState fstate) {
- if(targetFState == null) {
- return null;
- }
- return targetFState.get(fstate);
- }
-
- public Hashtable<FlagState, Vector<Integer>> getAllyCoreTable() {
- return this.allyCores;
- }
-
- public Vector<Integer> getAllyCores(FlagState fstate) {
- if(this.allyCores == null) {
- return null;
- }
- return this.allyCores.get(fstate);
- }
-
- public Hashtable<TaskDescriptor, Vector<FlagState>> getTd2FsTable() {
- return this.td2fs;
- }
-
- public Vector<FlagState> 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<FlagState, Queue<Integer>>();
- }
- if(!this.targetCores.containsKey(fstate)) {
- this.targetCores.put(fstate, new LinkedList<Integer>());
- }
- 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<FlagState, Queue<Integer>>();
- }
- if(!this.targetCores.containsKey(fstate)) {
- this.targetCores.put(fstate, new LinkedList<Integer>());
- }
- this.targetCores.get(fstate).add(targetCore);
- if(this.targetFState == null) {
- this.targetFState = new Hashtable<FlagState, FlagState>();
- }
- this.targetFState.put(fstate, tfstate);
- }
-
- public void addAllyCore(FlagState fstate, Integer targetCore) {
- if(this.allyCores == null) {
- this.allyCores = new Hashtable<FlagState, Vector<Integer>>();
- }
- if(!this.allyCores.containsKey(fstate)) {
- this.allyCores.put(fstate, new Vector<Integer>());
- }
- 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<TaskDescriptor, Vector<FlagState>>();
- }
- if(!this.td2fs.containsKey(td)) {
- this.td2fs.put(td, new Vector<FlagState>());
- }
- if(!this.td2fs.get(td).contains(fstate)) {
- this.td2fs.get(td).add(fstate);
- }
- }
-
- public Vector<TaskDescriptor> getTasks() {
- return tasks;
- }
-
- public void addTask(TaskDescriptor task) {
- if(this.tasks == null) {
- this.tasks = new Vector<TaskDescriptor>();
- }
- if(!this.tasks.contains(task)) {
- this.tasks.add(task);
- }
- }
+ private int coreNum;
+ private Vector<TaskDescriptor> tasks;
+ private Hashtable<FlagState, Queue<Integer>> targetCores;
+ private Hashtable<FlagState, FlagState> targetFState; // only affected by transimit edges
+ private Hashtable<FlagState, Vector<Integer>> allyCores;
+ private Hashtable<TaskDescriptor, Vector<FlagState>> 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<FlagState, Queue<Integer>> getTargetCoreTable() {
+ return targetCores;
+ }
+
+ public Queue<Integer> getTargetCores(FlagState fstate) {
+ if(targetCores == null) {
+ return null;
+ }
+ return targetCores.get(fstate);
+ }
+
+ public Hashtable<FlagState, FlagState> getTargetFStateTable() {
+ return targetFState;
+ }
+
+ public FlagState getTargetFState(FlagState fstate) {
+ if(targetFState == null) {
+ return null;
+ }
+ return targetFState.get(fstate);
+ }
+
+ public Hashtable<FlagState, Vector<Integer>> getAllyCoreTable() {
+ return this.allyCores;
+ }
+
+ public Vector<Integer> getAllyCores(FlagState fstate) {
+ if(this.allyCores == null) {
+ return null;
+ }
+ return this.allyCores.get(fstate);
+ }
+
+ public Hashtable<TaskDescriptor, Vector<FlagState>> getTd2FsTable() {
+ return this.td2fs;
+ }
+
+ public Vector<FlagState> 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<FlagState, Queue<Integer>>();
+ }
+ if(!this.targetCores.containsKey(fstate)) {
+ this.targetCores.put(fstate, new LinkedList<Integer>());
+ }
+ 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<FlagState, Queue<Integer>>();
+ }
+ if(!this.targetCores.containsKey(fstate)) {
+ this.targetCores.put(fstate, new LinkedList<Integer>());
+ }
+ this.targetCores.get(fstate).add(targetCore);
+ if(this.targetFState == null) {
+ this.targetFState = new Hashtable<FlagState, FlagState>();
+ }
+ this.targetFState.put(fstate, tfstate);
+ }
+
+ public void addAllyCore(FlagState fstate, Integer targetCore) {
+ if(this.allyCores == null) {
+ this.allyCores = new Hashtable<FlagState, Vector<Integer>>();
+ }
+ if(!this.allyCores.containsKey(fstate)) {
+ this.allyCores.put(fstate, new Vector<Integer>());
+ }
+ 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<TaskDescriptor, Vector<FlagState>>();
+ }
+ if(!this.td2fs.containsKey(td)) {
+ this.td2fs.put(td, new Vector<FlagState>());
+ }
+ if(!this.td2fs.get(td).contains(fstate)) {
+ this.td2fs.get(td).add(fstate);
+ }
+ }
+
+ public Vector<TaskDescriptor> getTasks() {
+ return tasks;
+ }
+
+ public void addTask(TaskDescriptor task) {
+ if(this.tasks == null) {
+ this.tasks = new Vector<TaskDescriptor>();
+ }
+ if(!this.tasks.contains(task)) {
+ this.tasks.add(task);
+ }
+ }
}
\ No newline at end of file
/** This class holds flag transition diagram(s) can be put on one core.
*/
public class ScheduleAnalysis {
-
- State state;
- TaskAnalysis taskanalysis;
- Vector<ScheduleNode> scheduleNodes;
- Vector<ClassNode> classNodes;
- Vector<ScheduleEdge> scheduleEdges;
- Hashtable<ClassDescriptor, ClassNode> cd2ClassNode;
- boolean sorted = false;
-
- int transThreshold;
-
- int coreNum;
- Vector<Vector<ScheduleNode>> scheduleGraphs;
- Vector<Vector<Schedule>> schedulings;
-
- public ScheduleAnalysis(State state, TaskAnalysis taskanalysis) {
- this.state = state;
- this.taskanalysis = taskanalysis;
- this.scheduleNodes = new Vector<ScheduleNode>();
- this.classNodes = new Vector<ClassNode>();
- this.scheduleEdges = new Vector<ScheduleEdge>();
- this.cd2ClassNode = new Hashtable<ClassDescriptor, ClassNode>();
- 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<ScheduleNode> scheduleNodes;
+ Vector<ClassNode> classNodes;
+ Vector<ScheduleEdge> scheduleEdges;
+ Hashtable<ClassDescriptor, ClassNode> cd2ClassNode;
+ boolean sorted = false;
+
+ int transThreshold;
+
+ int coreNum;
+ Vector<Vector<ScheduleNode>> scheduleGraphs;
+ Vector<Vector<Schedule>> schedulings;
+
+ public ScheduleAnalysis(State state, TaskAnalysis taskanalysis) {
+ this.state = state;
+ this.taskanalysis = taskanalysis;
+ this.scheduleNodes = new Vector<ScheduleNode>();
+ this.classNodes = new Vector<ClassNode>();
+ this.scheduleEdges = new Vector<ScheduleEdge>();
+ this.cd2ClassNode = new Hashtable<ClassDescriptor, ClassNode>();
+ 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<Vector<Schedule>> getSchedulings() {
+ return this.schedulings;
+ }
+
+ // for test
+ public Vector<ScheduleEdge> getSEdges4Test() {
+ return scheduleEdges;
+ }
+
+ public void preSchedule() {
+ Hashtable<ClassDescriptor, ClassNode> cdToCNodes = new Hashtable<ClassDescriptor, ClassNode>();
+ // 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<FlagState> fStates = taskanalysis.getFlagStates(cd);
+
+ //Sort flagState nodes inside this ClassNode
+ Vector<FlagState> 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<ScheduleEdge> toBreakDown = new Vector<ScheduleEdge>();
+ 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<FEdge> fev = (Vector<FEdge>)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<Vector<Schedule>> 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<ScheduleEdge> getSEdges4Test() {
- return scheduleEdges;
+
+ // Do topology sort of the ClassNodes and ScheduleEdges.
+ Vector<ScheduleEdge> ssev = new Vector<ScheduleEdge>();
+ Vector<ScheduleNode> 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<ScheduleNode> toVisit = new LinkedList<ScheduleNode>();
+ 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<ClassDescriptor, ClassNode> cdToCNodes = new Hashtable<ClassDescriptor, ClassNode>();
- // 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<FlagState> fStates = taskanalysis.getFlagStates(cd);
-
- //Sort flagState nodes inside this ClassNode
- Vector<FlagState> 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<FEdge, Vector<ScheduleEdge>> fe2ses = new Hashtable<FEdge, Vector<ScheduleEdge>>();
+ Hashtable<ScheduleNode, Vector<FEdge>> sn2fes = new Hashtable<ScheduleNode, Vector<FEdge>>();
+ 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<ScheduleEdge> toBreakDown = new Vector<ScheduleEdge>();
- 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<FEdge> fev = (Vector<FEdge>)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<FEdge> fes = sn2fes.remove(preSNode);
+ for(int j = 0; j < fes.size(); j++) {
+ FEdge tempfe = fes.elementAt(j);
+ Vector<ScheduleEdge> 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<ScheduleEdge>());
}
- }
-
- // Do topology sort of the ClassNodes and ScheduleEdges.
- Vector<ScheduleEdge> ssev = new Vector<ScheduleEdge>();
- Vector<ScheduleNode> 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<ScheduleNode> toVisit = new LinkedList<ScheduleNode>();
- 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<FEdge, Vector<ScheduleEdge>> fe2ses = new Hashtable<FEdge, Vector<ScheduleEdge>>();
- Hashtable<ScheduleNode, Vector<FEdge>> sn2fes = new Hashtable<ScheduleNode, Vector<FEdge>>();
- 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<FEdge> fes = sn2fes.remove(preSNode);
- for(int j = 0; j < fes.size(); j++) {
- FEdge tempfe = fes.elementAt(j);
- Vector<ScheduleEdge> 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<ScheduleEdge>());
- }
- if(sn2fes.get((ScheduleNode)se.getSource()) == null) {
- sn2fes.put((ScheduleNode)se.getSource(), new Vector<FEdge>());
- }
- 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<FEdge> fes = sn2fes.remove(preSNode);
- for(int j = 0; j < fes.size(); j++) {
- FEdge tempfe = fes.elementAt(j);
- Vector<ScheduleEdge> 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<FEdge>());
}
- }
- if(!fe2ses.isEmpty()) {
- Set<FEdge> keys = fe2ses.keySet();
- Iterator it_keys = keys.iterator();
- while(it_keys.hasNext()) {
- FEdge tempfe = (FEdge)it_keys.next();
- Vector<ScheduleEdge> 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<FEdge> fes = sn2fes.remove(preSNode);
+ for(int j = 0; j < fes.size(); j++) {
+ FEdge tempfe = fes.elementAt(j);
+ Vector<ScheduleEdge> 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<ClassNode, ClassNode> cn2cn = new Hashtable<ClassNode, ClassNode>(); // 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<FEdge> keys = fe2ses.keySet();
+ Iterator it_keys = keys.iterator();
+ while(it_keys.hasNext()) {
+ FEdge tempfe = (FEdge)it_keys.next();
+ Vector<ScheduleEdge> 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<ScheduleNode> toClone = new LinkedList<ScheduleNode>(); // all nodes to be cloned
- Queue<ScheduleNode> clone = new LinkedList<ScheduleNode>(); //clone nodes
- Queue<Hashtable> qcn2cn = new LinkedList<Hashtable>(); // queue of the mappings of classnodes inside cloned ScheduleNode
- Vector<ScheduleNode> origins = new Vector<ScheduleNode>(); // queue of source ScheduleNode cloned
- Hashtable<ScheduleNode, ScheduleNode> sn2sn = new Hashtable<ScheduleNode, ScheduleNode>(); // 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<ClassNode, ClassNode> tocn2cn = new Hashtable<ClassNode, ClassNode>();
- 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<FlagState> sfss = sCNode.getFlagStates();
- Vector<FlagState> fStates = new Vector<FlagState>();
- Queue<FlagState> toiterate = new LinkedList<FlagState>();
- 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<FlagState> 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<ScheduleEdge> toremove = new Vector<ScheduleEdge>();
- Vector<ClassNode> rCNodes = new Vector<ClassNode>();
- 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<ClassNode, ClassNode> cn2cn = new Hashtable<ClassNode, ClassNode>(); // 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<ScheduleNode> toClone = new LinkedList<ScheduleNode>(); // all nodes to be cloned
+ Queue<ScheduleNode> clone = new LinkedList<ScheduleNode>(); //clone nodes
+ Queue<Hashtable> qcn2cn = new LinkedList<Hashtable>(); // queue of the mappings of classnodes inside cloned ScheduleNode
+ Vector<ScheduleNode> origins = new Vector<ScheduleNode>(); // queue of source ScheduleNode cloned
+ Hashtable<ScheduleNode, ScheduleNode> sn2sn = new Hashtable<ScheduleNode, ScheduleNode>(); // 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<ClassNode, ClassNode> tocn2cn = new Hashtable<ClassNode, ClassNode>();
+ 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<FlagState> sfss = sCNode.getFlagStates();
+ Vector<FlagState> fStates = new Vector<FlagState>();
+ Queue<FlagState> toiterate = new LinkedList<FlagState>();
+ 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<FlagState> 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<ScheduleEdge> toremove = new Vector<ScheduleEdge>();
+ Vector<ClassNode> rCNodes = new Vector<ClassNode>();
+ 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<Vector<ScheduleNode>>();
+ }
+ }
+ 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<Vector<ScheduleNode>> sNodeVecs = new Vector<Vector<ScheduleNode>>();
- 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<ScheduleNode>(), 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<Vector<ScheduleNode>> rootNodes = rGen.getRootNodes();
- Vector<Vector<ScheduleNode>> nodes2combine = rGen.getNode2Combine();
-
- CombinationUtil.CombineGenerator cGen = CombinationUtil.allocateCombineGenerator(rootNodes, nodes2combine);
- while (cGen.nextGen()) {
- Vector<Vector<CombinationUtil.Combine>> combine = cGen.getCombine();
- Vector<ScheduleNode> 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<Vector<ScheduleNode>>();
+ }
+
+ 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<Vector<ScheduleNode>> sNodeVecs = new Vector<Vector<ScheduleNode>>();
+ 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<Vector<Schedule>>();
+ if(sNodeVecs.elementAt(index) == null) {
+ sNodeVecs.setElementAt(new Vector<ScheduleNode>(), index);
}
-
- Vector<TaskDescriptor> multiparamtds = new Vector<TaskDescriptor>();
- 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<Vector<ScheduleNode>> rootNodes = rGen.getRootNodes();
+ Vector<Vector<ScheduleNode>> nodes2combine = rGen.getNode2Combine();
+
+ CombinationUtil.CombineGenerator cGen = CombinationUtil.allocateCombineGenerator(rootNodes, nodes2combine);
+ while (cGen.nextGen()) {
+ Vector<Vector<CombinationUtil.Combine>> combine = cGen.getCombine();
+ Vector<ScheduleNode> 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<Schedule>>();
+ }
+
+ Vector<TaskDescriptor> multiparamtds = new Vector<TaskDescriptor>();
+ 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<TaskDescriptor, Vector<Schedule>> td2cores = new Hashtable<TaskDescriptor, Vector<Schedule>>(); // multiparam tasks reside on which cores
+ Vector<ScheduleNode> scheduleGraph = this.scheduleGraphs.elementAt(i);
+ Vector<Schedule> scheduling = new Vector<Schedule>(scheduleGraph.size());
+ // for each ScheduleNode create a schedule node representing a core
+ Hashtable<ScheduleNode, Integer> sn2coreNum = new Hashtable<ScheduleNode, Integer>();
+ 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<ClassNode> 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<Schedule>());
+ }
+ Vector<Schedule> 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<TaskDescriptor, Vector<Schedule>> td2cores = new Hashtable<TaskDescriptor, Vector<Schedule>>(); // multiparam tasks reside on which cores
- Vector<ScheduleNode> scheduleGraph = this.scheduleGraphs.elementAt(i);
- Vector<Schedule> scheduling = new Vector<Schedule>(scheduleGraph.size());
- // for each ScheduleNode create a schedule node representing a core
- Hashtable<ScheduleNode, Integer> sn2coreNum = new Hashtable<ScheduleNode, Integer>();
- 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<ClassNode> 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<Schedule>());
- }
- Vector<Schedule> 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<FEdge> fes = (Vector<FEdge>) this.taskanalysis.getFEdgesFromTD(td);
+ Vector<Schedule> 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<TaskDescriptor> tmptds = new Vector<TaskDescriptor>();
+ 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<Schedule> 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<FEdge> fes = (Vector<FEdge>)this.taskanalysis.getFEdgesFromTD(td);
- Vector<Schedule> 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<TaskDescriptor> tmptds = new Vector<TaskDescriptor>();
- 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<Schedule> 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<FlagState> 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<FlagState> 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<ScheduleNode> generateScheduling(Vector<Vector<ScheduleNode>> rootnodes, Vector<Vector<CombinationUtil.Combine>> combine, int gid) {
- Vector<ScheduleNode> result = new Vector<ScheduleNode>();
-
- // clone the ScheduleNodes
- Hashtable<ScheduleNode, Hashtable<ClassNode, ClassNode>> sn2hash = new Hashtable<ScheduleNode, Hashtable<ClassNode, ClassNode>>();
- Hashtable<ScheduleNode, ScheduleNode> sn2sn = new Hashtable<ScheduleNode, ScheduleNode>();
- for(int i = 0; i < this.scheduleNodes.size(); i++) {
- Hashtable<ClassNode, ClassNode> cn2cn = new Hashtable<ClassNode, ClassNode>();
- 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<ClassNode, ClassNode> sourcecn2cn = sn2hash.get(csource);
- Hashtable<ClassNode, ClassNode> 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<ScheduleNode> generateScheduling(Vector<Vector<ScheduleNode>> rootnodes, Vector<Vector<CombinationUtil.Combine>> combine, int gid) {
+ Vector<ScheduleNode> result = new Vector<ScheduleNode>();
+
+ // clone the ScheduleNodes
+ Hashtable<ScheduleNode, Hashtable<ClassNode, ClassNode>> sn2hash = new Hashtable<ScheduleNode, Hashtable<ClassNode, ClassNode>>();
+ Hashtable<ScheduleNode, ScheduleNode> sn2sn = new Hashtable<ScheduleNode, ScheduleNode>();
+ for(int i = 0; i < this.scheduleNodes.size(); i++) {
+ Hashtable<ClassNode, ClassNode> cn2cn = new Hashtable<ClassNode, ClassNode>();
+ 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<ClassNode, ClassNode> sourcecn2cn = sn2hash.get(csource);
+ Hashtable<ClassNode, ClassNode> 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;
+ }
}
/* 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;
+ }
}
/** 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<ClassNode> classNodes;
- Vector<ScheduleEdge> 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<ClassNode> classNodes;
+ Vector<ScheduleEdge> 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<ClassNode>();
+ this.scheduleEdges = new Vector<ScheduleEdge>();
+ 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<ClassNode>();
- this.scheduleEdges = new Vector<ScheduleEdge>();
- 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<ClassNode, ClassNode> 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<ClassNode> tcns = new Vector<ClassNode>();
+ Vector<ScheduleEdge> tses = new Vector<ScheduleEdge>();
+ 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<ClassNode> targetCNodes = (Vector<ClassNode>)sn.getClassNodes();
+ Vector<ScheduleEdge> targetSEdges = (Vector<ScheduleEdge>)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<FlagState> 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<FlagState> toiterate = new LinkedList<FlagState>();
+ 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<ClassNode> targetCNodes = (Vector<ClassNode>)sn.getClassNodes();
+ Vector<ScheduleEdge> targetSEdges = (Vector<ScheduleEdge>)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<ClassNode, ClassNode> 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<ClassNode> tcns = new Vector<ClassNode>();
- Vector<ScheduleEdge> tses = new Vector<ScheduleEdge>();
- 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<ClassNode> targetCNodes = (Vector<ClassNode>)sn.getClassNodes();
- Vector<ScheduleEdge> targetSEdges = (Vector<ScheduleEdge>)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<FlagState> 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<FlagState> toiterate = new LinkedList<FlagState>();
- 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<ClassNode> targetCNodes = (Vector<ClassNode>)sn.getClassNodes();
- Vector<ScheduleEdge> targetSEdges = (Vector<ScheduleEdge>)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();
+
+ }
}
import IR.TypeUtil;
public class ScheduleSimulator {
- private int coreNum;
- private Vector<Schedule> scheduling;
- private Vector<CoreSimulator> cores;
- private Vector<TaskSimulator> tasks;
- private Vector<CheckPoint> 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<Schedule> scheduling;
+ private Vector<CoreSimulator> cores;
+ private Vector<TaskSimulator> tasks;
+ private Vector<CheckPoint> 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<Schedule> scheduling, State state, TaskAnalysis taskanalysis) {
+ super();
+ this.coreNum = coreNum;
+ this.scheduling = scheduling;
+ this.cores = new Vector<CoreSimulator>(this.coreNum);
+ for(int i = 0; i < this.coreNum; i++) {
+ this.cores.add(new CoreSimulator(FIFORSchedule.getFIFORSchedule(), i));
}
-
- public ScheduleSimulator(int coreNum, Vector<Schedule> scheduling, State state, TaskAnalysis taskanalysis) {
- super();
- this.coreNum = coreNum;
- this.scheduling = scheduling;
- this.cores = new Vector<CoreSimulator>(this.coreNum);
- for(int i = 0; i < this.coreNum; i++) {
- this.cores.add(new CoreSimulator(FIFORSchedule.getFIFORSchedule(), i));
- }
- this.tasks = new Vector<TaskSimulator>();
- this.checkpoints = null;
- this.processTime = 0;
- this.invoketime = 0;
- this.state = state;
- this.taskanalysis = taskanalysis;
- applyScheduling();
+ this.tasks = new Vector<TaskSimulator>();
+ this.checkpoints = null;
+ this.processTime = 0;
+ this.invoketime = 0;
+ this.state = state;
+ this.taskanalysis = taskanalysis;
+ applyScheduling();
+ }
+
+ public Vector<CheckPoint> 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<CheckPoint> getCheckpoints() {
- return checkpoints;
+ this.cores = new Vector<CoreSimulator>(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<CoreSimulator>(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<Schedule> getScheduling() {
+ return scheduling;
+ }
+
+ public void setScheduling(Vector<Schedule> scheduling) {
+ this.scheduling = scheduling;
+ if(this.tasks == null) {
+ this.tasks = new Vector<TaskSimulator>();
+ } 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<CoreSimulator>(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<Schedule> 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<Schedule> scheduling) {
- this.scheduling = scheduling;
- if(this.tasks == null) {
- this.tasks = new Vector<TaskSimulator>();
- } 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<CoreSimulator>(this.coreNum);
- for(int i = 0; i < this.coreNum; i++) {
- this.cores.add(new CoreSimulator(FIFORSchedule.getFIFORSchedule(), i));
- }
- }
-
- applyScheduling();
+ }
+
+ public Vector<TaskSimulator> getTasks() {
+ return tasks;
+ }
+
+ public int process() {
+ assert(this.scheduling != null);
+
+ this.invoketime++;
+
+ if(this.checkpoints == null) {
+ this.checkpoints = new Vector<CheckPoint>();
+ } 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<TaskSimulator> 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<CheckPoint>();
- } 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<TaskSimulator> finishTasks = new Vector<TaskSimulator>();
+ 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<TaskSimulator> finishTasks = new Vector<TaskSimulator>();
- 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<Integer, Queue<ObjectInfo>> transObjQueues = new Hashtable<Integer, Queue<ObjectInfo>>();
+ 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<ObjectSimulator> 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<Integer> 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<ObjectInfo>());
+ }
+ Queue<ObjectInfo> 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<Integer> 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<ObjectInfo>());
+ }
+ Queue<ObjectInfo> 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<ObjectSimulator> 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<Integer> 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<Integer, Queue<ObjectInfo>> transObjQueues = new Hashtable<Integer, Queue<ObjectInfo>>();
- 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<ObjectSimulator> 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<Integer> 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<ObjectInfo>());
- }
- Queue<ObjectInfo> 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<Integer> 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<ObjectInfo>());
- }
- Queue<ObjectInfo> tmpqueue = transObjQueues.get(allyCore);
- ObjectInfo nobjinfo = new ObjectInfo(nobj);
- if(!tmpqueue.contains(nobjinfo)) {
- tmpqueue.add(nobjinfo);
- }
- }
- }
- }
- }
- }
- cp.addAction(action);
- Vector<ObjectSimulator> 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<Integer> 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<ObjectInfo>());
- }
- Queue<ObjectInfo> tmpqueue = transObjQueues.get(targetCore);
- tmpqueue.add(new ObjectInfo(tobj));
- }
- }
- // check if this object becoming shared or not
- Vector<Integer> 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<ObjectInfo>());
- }
- Queue<ObjectInfo> 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<Integer, Queue<ObjectInfo>> tmpentry = (Entry<Integer, Queue<ObjectInfo>>)it_entries.next();
- Integer tmpCoreNum = tmpentry.getKey();
- Queue<ObjectInfo> 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<ObjectInfo>());
+ }
+ Queue<ObjectInfo> tmpqueue = transObjQueues.get(targetCore);
+ tmpqueue.add(new ObjectInfo(tobj));
+ }
+ }
+ // check if this object becoming shared or not
+ Vector<Integer> 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<ObjectInfo>());
+ }
+ Queue<ObjectInfo> 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<Integer, Queue<ObjectInfo>> tmpentry = (Entry<Integer, Queue<ObjectInfo>>)it_entries.next();
+ Integer tmpCoreNum = tmpentry.getKey();
+ Queue<ObjectInfo> 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<Action> actions;
-
- public CheckPoint(int timepoint) {
- super();
- this.timepoint = timepoint;
- this.actions = new Vector<Action>();
- }
- public Vector<Action> 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<Action> actions;
- public int getTimepoint() {
- return timepoint;
- }
+ public CheckPoint(int timepoint) {
+ super();
+ this.timepoint = timepoint;
+ this.actions = new Vector<Action>();
}
-
- 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<ClassDescriptor, Integer> 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<ClassDescriptor, Integer>();
- } 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<Action> 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<ClassDescriptor, Integer> 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<ClassDescriptor, Integer>();
+ } 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<ClassDescriptor, Integer> 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<ClassDescriptor, Integer> getNObjs() {
+ return nObjs;
+ }
+ }
+
}
\ No newline at end of file
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<ScheduleNode> 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<ScheduleNode> 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<ScheduleNode> 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<ScheduleNode> 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<namers.size();i++) {
+ }
+
+ 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<namers.size(); i++) {
+ Namer name=(Namer) namers.get(i);
+ String newlabel=name.nodeLabel(gn);
+ String newparams=name.nodeOption(gn);
+
+ if (!newlabel.equals("") && !label.equals("")) {
+ label+=", ";
+ }
+ if (!newparams.equals("")) {
+ dotnodeparams+=", " + name.nodeOption(gn);
+ }
+ label+=name.nodeLabel(gn);
+ }
+ 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<namers.size(); i++) {
Namer name=(Namer) namers.get(i);
- String newlabel=name.nodeLabel(gn);
- String newparams=name.nodeOption(gn);
-
- if (!newlabel.equals("") && !label.equals("")) {
- label+=", ";
+ String newlabel=name.edgeLabel(edge);
+ String newoption=name.edgeOption(edge);
+ if (!newlabel.equals("")&& !edgelabel.equals(""))
+ edgelabel+=", ";
+ edgelabel+=newlabel;
+ if (!newoption.equals(""))
+ edgedotnodeparams+=", "+newoption;
+ }
+ edgelabel+=":[" + ((FEdge)edge).getExeTime() + "]";
+ edgelabel+=":(" + ((FEdge)edge).getProbability() + "%)";
+ Hashtable<ClassDescriptor, NewObjInfo> hashtable = ((FEdge)edge).getNewObjInfoHashtable();
+ if(hashtable != null) {
+ Set<ClassDescriptor> 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<namers.size();i++) {
- Namer name=(Namer) namers.get(i);
- String newlabel=name.edgeLabel(edge);
- String newoption=name.edgeOption(edge);
- if (!newlabel.equals("")&& ! edgelabel.equals(""))
- edgelabel+=", ";
- edgelabel+=newlabel;
- if (!newoption.equals(""))
- edgedotnodeparams+=", "+newoption;
- }
- edgelabel+=":[" + ((FEdge)edge).getExeTime() + "]";
- edgelabel+=":(" + ((FEdge)edge).getProbability() + "%)";
- Hashtable<ClassDescriptor, NewObjInfo> hashtable = ((FEdge)edge).getNewObjInfoHashtable();
- if(hashtable != null) {
- Set<ClassDescriptor> 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<CheckPoint> 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<CheckPoint> 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<String> timeNodes = new Vector<String>();
+ 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<Integer, String> tmplastTasks = new Hashtable<Integer, String>();
+ Vector<Integer> tmpisTaskFinish = new Vector<Integer>();
+ Vector<Integer> tmpisset = new Vector<Integer>();
+ String tnode = String.valueOf(tcp.getTimepoint());
+ if(!timeNodes.contains(tnode)) {
+ timeNodes.add(tnode);
+ }
+ Vector<Action> actions = tcp.getActions();
+ Hashtable<String, StringBuffer> tmpTaskNodes = new Hashtable<String, StringBuffer>();
+ 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<String> timeNodes = new Vector<String>();
- 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<Integer, String> tmplastTasks = new Hashtable<Integer, String>();
- Vector<Integer> tmpisTaskFinish = new Vector<Integer>();
- Vector<Integer> tmpisset = new Vector<Integer>();
- String tnode = String.valueOf(tcp.getTimepoint());
- if(!timeNodes.contains(tnode)) {
- timeNodes.add(tnode);
- }
- Vector<Action> actions = tcp.getActions();
- Hashtable<String, StringBuffer> tmpTaskNodes = new Hashtable<String, StringBuffer>();
- 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<Entry<ClassDescriptor, Integer>> it_entry = (Iterator<Entry<ClassDescriptor, Integer>>)taction.getNObjs().entrySet().iterator();
- while(it_entry.hasNext()) {
- Entry<ClassDescriptor, Integer> 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<String> 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<Entry<ClassDescriptor, Integer>> it_entry = (Iterator<Entry<ClassDescriptor, Integer>>)taction.getNObjs().entrySet().iterator();
+ while(it_entry.hasNext()) {
+ Entry<ClassDescriptor, Integer> 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<String> 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
import IR.Tree.FlagExpressionNode;
public class TaskSimulator {
- TaskDescriptor td;
- Vector<Queue<ObjectSimulator>> paraQueues;
- Hashtable<ObjectSimulator, Integer> objVersionTbl;
- ExeResult currentRun;
- CoreSimulator cs;
- boolean finish;
-
- public class ExeResult {
- int finishTime;
- Vector<ObjectSimulator> 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<ObjectSimulator> getNewObjs() {
- return newObjs;
- }
-
- public void addNewObj(ObjectSimulator newObj) {
- if(this.newObjs == null) {
- this.newObjs = new Vector<ObjectSimulator>();
- }
-
- this.newObjs.add(newObj);
- }
+ TaskDescriptor td;
+ Vector<Queue<ObjectSimulator>> paraQueues;
+ Hashtable<ObjectSimulator, Integer> objVersionTbl;
+ ExeResult currentRun;
+ CoreSimulator cs;
+ boolean finish;
- public int getExetype() {
- return exetype;
- }
+ public class ExeResult {
+ int finishTime;
+ Vector<ObjectSimulator> 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<ObjectSimulator> getNewObjs() {
+ return newObjs;
}
- public Vector<Queue<ObjectSimulator>> getParaQueues() {
- return paraQueues;
+ public void addNewObj(ObjectSimulator newObj) {
+ if(this.newObjs == null) {
+ this.newObjs = new Vector<ObjectSimulator>();
+ }
+
+ this.newObjs.add(newObj);
}
-
- public Hashtable<ObjectSimulator, Integer> 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<Queue<ObjectSimulator>>();
- for(int j = 0; j < paraNum; j++) {
- this.paraQueues.add(null);
- }
- }
- if(this.paraQueues.elementAt(i) == null) {
- this.paraQueues.setElementAt(new LinkedList<ObjectSimulator>(), i);
- }
- if(this.objVersionTbl == null) {
- this.objVersionTbl = new Hashtable<ObjectSimulator, Integer>();
- }
- 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<Queue<ObjectSimulator>> getParaQueues() {
+ return paraQueues;
+ }
+
+ public Hashtable<ObjectSimulator, Integer> 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<Queue<ObjectSimulator>>();
- for(int j = 0; j < paraNum; j++) {
- this.paraQueues.add(null);
- }
- }
- if(this.paraQueues.elementAt(i) == null) {
- this.paraQueues.setElementAt(new LinkedList<ObjectSimulator>(), i);
- }
- this.paraQueues.elementAt(i).add(obj);
- if(this.objVersionTbl == null) {
- this.objVersionTbl = new Hashtable<ObjectSimulator, Integer>();
- }
- 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<Queue<ObjectSimulator>>();
+ for(int j = 0; j < paraNum; j++) {
+ this.paraQueues.add(null);
}
+ }
+ if(this.paraQueues.elementAt(i) == null) {
+ this.paraQueues.setElementAt(new LinkedList<ObjectSimulator>(), i);
+ }
+ if(this.objVersionTbl == null) {
+ this.objVersionTbl = new Hashtable<ObjectSimulator, Integer>();
+ }
+ 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<Queue<ObjectSimulator>>();
+ 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<ObjectSimulator>(), 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<ObjectSimulator, Integer>();
+ }
+ 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
-package Analysis.Scheduling;\r
-\r
-import java.util.Queue;\r
-\r
-public class TransTaskSimulator extends TaskSimulator {\r
- private int targetCoreNum;\r
- private Queue<ObjectInfo> newObjs;\r
-\r
- public TransTaskSimulator(CoreSimulator cs, int targetCoreNum, Queue<ObjectInfo> nobjs) {\r
- super(null, cs);\r
- this.targetCoreNum = targetCoreNum;\r
- this.newObjs = nobjs;\r
- }\r
- \r
- public void process() {\r
- if(this.currentRun == null) {\r
- this.currentRun = new ExeResult();\r
- }\r
-\r
- this.currentRun.finishTime = 1 * sizeof(this.newObjs.peek().obj.getCd());\r
- }\r
- \r
- public ObjectInfo refreshTask() {\r
- return this.newObjs.poll();\r
- }\r
- \r
- private int sizeof(Object obj) {\r
- return 1;\r
- }\r
-\r
- public boolean isFinished() {\r
- return this.newObjs.isEmpty();\r
- }\r
-\r
- public int getTargetCoreNum() {\r
- return targetCoreNum;\r
- }\r
+package Analysis.Scheduling;
+
+import java.util.Queue;
+
+public class TransTaskSimulator extends TaskSimulator {
+ private int targetCoreNum;
+ private Queue<ObjectInfo> newObjs;
+
+ public TransTaskSimulator(CoreSimulator cs, int targetCoreNum, Queue<ObjectInfo> 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
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 "";
+ }
}
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;
+ }
}
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;
+ }
}
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<EGTaskNode> 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<EGTaskNode> graph=exploreGraph(cdtemp);
- adapt(cdtemp,graph);
+ printDOTFile();
+ }
+
+ private HashSet<EGTaskNode> exploreGraph(ClassDescriptor cd) {
+ LinkedList<FlagState> fifo = new LinkedList<FlagState>();
+ HashSet<EGTaskNode> nodes=new HashSet<EGTaskNode>();
+ Hashtable<FEdge, EGTaskNode> map=new Hashtable<FEdge, EGTaskNode>();
+
+ // Go through nodes
+ Iterator<FlagState> 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<EGTaskNode> exploreGraph(ClassDescriptor cd) {
- LinkedList<FlagState> fifo = new LinkedList<FlagState>();
- HashSet<EGTaskNode> nodes=new HashSet<EGTaskNode>();
- Hashtable<FEdge, EGTaskNode> map=new Hashtable<FEdge, EGTaskNode>();
-
- // Go through nodes
- Iterator<FlagState> 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<FEdge, EGTaskNode> map, HashSet<EGTaskNode> 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<EGTaskNode> 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<FEdge, EGTaskNode> map, HashSet<EGTaskNode> 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<EGTaskNode> 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()+";");
+ }
}
+ }
}
public class FEdge extends Edge {
- private String label;
- private TaskDescriptor td;
- private int parameterindex;
-
- // jzhou
- private int executeTime;
- private Hashtable<ClassDescriptor, NewObjInfo> 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<ClassDescriptor, NewObjInfo> 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<ClassDescriptor, NewObjInfo> 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<ClassDescriptor, NewObjInfo>();
- }
- 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<ClassDescriptor, NewObjInfo> 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<ClassDescriptor, NewObjInfo>();
}
-
+ 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;
+ }
+
}
/**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;
+ }
}
public class FlagInfo {
- private Hashtable<ClassDescriptor, FlagDescriptor[]> flags;
- private State state;
+ private Hashtable<ClassDescriptor, FlagDescriptor[]> flags;
+ private State state;
- public FlagInfo(State state) {
- this.state=state;
- flags=new Hashtable<ClassDescriptor, FlagDescriptor[]>();
- getFlagsfromClasses();
- }
+ public FlagInfo(State state) {
+ this.state=state;
+ flags=new Hashtable<ClassDescriptor, FlagDescriptor[]>();
+ 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
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<TagDescriptor,Integer> 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<ScheduleEdge> 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<TagDescriptor,Integer>();
- 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 <CODE>HashSet</CODE> containing FlagDescriptors
- */
- private FlagState(HashSet flagstate, ClassDescriptor cd,Hashtable<TagDescriptor,Integer> 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<TagDescriptor,Integer> 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<ScheduleEdge> 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<TagDescriptor,Integer>();
+ 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 <CODE>HashSet</CODE> containing FlagDescriptors
+ */
+ private FlagState(HashSet flagstate, ClassDescriptor cd,Hashtable<TagDescriptor,Integer> 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<TagDescriptor,Integer> newtags1=(Hashtable<TagDescriptor,Integer>)tags.clone();
-
- if (set) {
- int count=0;
- if (tags.containsKey(tag))
- count=tags.get(tag).intValue();
- if (count<KLIMIT)
- count++;
- newtags1.put(tag, new Integer(count));
- return new FlagState[] {new FlagState(newset1, cd, newtags1)};
- } else {
- int count=1;
- if (tags.containsKey(tag))
- count=tags.get(tag).intValue();
- newtags1.put(tag, new Integer(count));
- if ((count+1)==KLIMIT)
- return new FlagState[] {this, new FlagState(newset1, cd, newtags1)};
- else
- return new FlagState[] {new FlagState(newset1, cd, newtags1)};
- }
- }
+ public int getuid() {
+ return uid;
+ }
+
+ public int getiuid() {
+ return iuid++;
+ }
+
+ public boolean isSetmask() {
+ return setmask;
+ }
+
+ public void setSetmask(boolean setmask) {
+ this.setmask = setmask;
+ }
+
+ /** 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 FlagState[] setTag(TagDescriptor tag){
+ 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();
+ }
+
+ /** @return Iterator over the flags in the flagstate.
+ */
+
+ public Iterator getFlags() {
+ return flagstate.iterator();
+ }
+
+ public int numFlags() {
+ return flagstate.size();
+ }
+
+ public FlagState[] setTag(TagDescriptor tag, boolean set) {
+ HashSet newset1=(HashSet)flagstate.clone();
+ Hashtable<TagDescriptor,Integer> newtags1=(Hashtable<TagDescriptor,Integer>)tags.clone();
+
+ if (set) {
+ int count=0;
+ if (tags.containsKey(tag))
+ count=tags.get(tag).intValue();
+ if (count<KLIMIT)
+ count++;
+ newtags1.put(tag, new Integer(count));
+ return new FlagState[] {new FlagState(newset1, cd, newtags1)};
+ } else {
+ int count=1;
+ if (tags.containsKey(tag))
+ count=tags.get(tag).intValue();
+ newtags1.put(tag, new Integer(count));
+ if ((count+1)==KLIMIT)
+ return new FlagState[] {this, new FlagState(newset1, cd, newtags1)};
+ else
+ return new FlagState[] {new FlagState(newset1, cd, newtags1)};
+ }
+ }
+
+ public FlagState[] setTag(TagDescriptor tag) {
+ HashSet newset1=(HashSet)flagstate.clone();
+ Hashtable<TagDescriptor,Integer> newtags1=(Hashtable<TagDescriptor,Integer>)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<TagDescriptor,Integer> newtags=(Hashtable<TagDescriptor,Integer>)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<TagDescriptor,Integer> newtags1=(Hashtable<TagDescriptor,Integer>)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<TagDescriptor,Integer> newtags2=(Hashtable<TagDescriptor,Integer>)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<TagDescriptor,Integer> newtags=(Hashtable<TagDescriptor,Integer>)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<TagDescriptor,Integer> newtags1=(Hashtable<TagDescriptor,Integer>)tags.clone();
-
- //1 case
- HashSet newset2=(HashSet)flagstate.clone();
- Hashtable<TagDescriptor,Integer> newtags2=(Hashtable<TagDescriptor,Integer>)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 <CODE>fd</CODE> set to <CODE>status</CODE>.
- */
-
- public FlagState setFlag(FlagDescriptor fd, boolean status) {
- HashSet newset=(HashSet) flagstate.clone();
- Hashtable<TagDescriptor,Integer> newtags=(Hashtable<TagDescriptor,Integer>)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 <CODE>fd</CODE> set to <CODE>status</CODE>.
+ */
+
+ public FlagState setFlag(FlagDescriptor fd, boolean status) {
+ HashSet newset=(HashSet) flagstate.clone();
+ Hashtable<TagDescriptor,Integer> newtags=(Hashtable<TagDescriptor,Integer>)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<ScheduleEdge> 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<ScheduleEdge>();
+ 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<ScheduleEdge> getAllys() {
+ return allys;
+ }
+
+ public void addAlly(ScheduleEdge se) {
+ if(this.allys == null) {
+ assert(this.isolate == true);
+ this.isolate = false;
+ this.allys = new Vector<ScheduleEdge>();
+ }
+ this.allys.addElement(se);
+ }
+
+ public boolean isIsolate() {
+ return isolate;
+ }*/
+
}
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();
+ }
}
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.numinedges();i++) {
- Edge e=fs.getinedge(i);
- FlagState fsnew=(FlagState) e.getSource();
- if (!possiblegarbage.contains(fsnew)) {
- possiblegarbage.add(fsnew);
- tovisit.push(fsnew);
- }
- }
+ Stack tovisit=new Stack();
+ tovisit.addAll(garbage);
+ possiblegarbage.addAll(garbage);
+ while(!tovisit.isEmpty()) {
+ FlagState fs=(FlagState)tovisit.pop();
+ for(int i=0; i<fs.numinedges(); i++) {
+ Edge e=fs.getinedge(i);
+ FlagState fsnew=(FlagState) e.getSource();
+ if (!possiblegarbage.contains(fsnew)) {
+ possiblegarbage.add(fsnew);
+ tovisit.push(fsnew);
}
- garbagestates.addAll(garbage);
- possiblegarbagestates.addAll(possiblegarbage);
- }
-
- public String nodeLabel(GraphNode gn) {
- return "";
- }
-
- public String nodeOption(GraphNode gn) {
- if (garbagestates.contains(gn)) {
- return "color=green";
- } else if (possiblegarbagestates.contains(gn)) {
- return "color=blue";
- } else
- return "color=red";
+ }
}
+ garbagestates.addAll(garbage);
+ possiblegarbagestates.addAll(possiblegarbage);
+ }
- public String edgeLabel(Edge e) {
- return "";
- }
+ public String nodeLabel(GraphNode gn) {
+ return "";
+ }
- public String edgeOption(Edge e) {
- return "";
- }
+ public String nodeOption(GraphNode gn) {
+ if (garbagestates.contains(gn)) {
+ return "color=green";
+ } else if (possiblegarbagestates.contains(gn)) {
+ return "color=blue";
+ } else
+ return "color=red";
+ }
+
+ public String edgeLabel(Edge e) {
+ return "";
+ }
+
+ public String edgeOption(Edge e) {
+ return "";
+ }
}
import IR.Flat.*;
import java.util.*;
-public class ObjWrapper implements Wrapper{
- FlagState initfs;
- HashSet<FlagState> fs;
- HashSet<TagWrapper> tags;
+public class ObjWrapper implements Wrapper {
+ FlagState initfs;
+ HashSet<FlagState> fs;
+ HashSet<TagWrapper> tags;
- public ObjWrapper(FlagState fs) {
- this.initfs=fs;
- this.fs=new HashSet<FlagState>();
- tags=new HashSet<TagWrapper>();
- }
+ public ObjWrapper(FlagState fs) {
+ this.initfs=fs;
+ this.fs=new HashSet<FlagState>();
+ tags=new HashSet<TagWrapper>();
+ }
+
+ public ObjWrapper() {
+ this.fs=new HashSet<FlagState>();
+ this.tags=new HashSet<TagWrapper>();
+ }
- public ObjWrapper() {
- this.fs=new HashSet<FlagState>();
- this.tags=new HashSet<TagWrapper>();
- }
-
}
import java.io.*;
import Util.Edge;
-public class OptionalTaskDescriptor {
- public TaskDescriptor td;
- public HashSet enterflagstates;
- public HashSet<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<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;
+ }
}
import Util.Edge;
public class Predicate {
- public HashSet<VarDescriptor> vardescriptors;
- public Hashtable<VarDescriptor, HashSet<FlagExpressionNode>> flags;
- public Hashtable<VarDescriptor, TagExpressionList> tags;
- //if there is a tag change, we stop the analysis
-
- public Predicate(){
- this.vardescriptors = new HashSet<VarDescriptor>();
- this.flags = new Hashtable<VarDescriptor, HashSet<FlagExpressionNode>>();
- this.tags = new Hashtable<VarDescriptor, TagExpressionList>();
- }
+ public HashSet<VarDescriptor> vardescriptors;
+ public Hashtable<VarDescriptor, HashSet<FlagExpressionNode>> flags;
+ public Hashtable<VarDescriptor, TagExpressionList> 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<VarDescriptor>();
+ this.flags = new Hashtable<VarDescriptor, HashSet<FlagExpressionNode>>();
+ this.tags = new Hashtable<VarDescriptor, TagExpressionList>();
+ }
+
+ 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();
+ }
}
import Util.Edge;
public class SafetyAnalysis {
- private Hashtable executiongraph;
- private Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution; //to use to build code
- private State state;
- private TaskAnalysis taskanalysis;
- private Hashtable<ClassDescriptor, Hashtable<OptionalTaskDescriptor, OptionalTaskDescriptor>> optionaltaskdescriptors;
- private Hashtable<FlagState, Hashtable<TaskIndex, Set<OptionalTaskDescriptor>>> fstotimap;
-
- private ClassDescriptor processedclass;
-
- public Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> getResult() {
- return safeexecution;
+ private Hashtable executiongraph;
+ private Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> safeexecution; //to use to build code
+ private State state;
+ private TaskAnalysis taskanalysis;
+ private Hashtable<ClassDescriptor, Hashtable<OptionalTaskDescriptor, OptionalTaskDescriptor>> optionaltaskdescriptors;
+ private Hashtable<FlagState, Hashtable<TaskIndex, Set<OptionalTaskDescriptor>>> fstotimap;
+
+ private ClassDescriptor processedclass;
+
+ public Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> getResult() {
+ return safeexecution;
+ }
+
+ public Hashtable<ClassDescriptor, Hashtable<OptionalTaskDescriptor, OptionalTaskDescriptor>> 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<FlagState, Hashtable<TaskIndex, Set<OptionalTaskDescriptor>>>();
+ }
+
+ /* Builds map of fs -> EGTasknodes that can fire on fs for class cd */
+
+ private Hashtable<FlagState, Set<EGTaskNode>> buildMap(ClassDescriptor cd) {
+ Hashtable<FlagState, Set<EGTaskNode>> table=new Hashtable<FlagState, Set<EGTaskNode>>();
+ 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<EGTaskNode>());
+ table.get(node.getFS()).add(node);
+ }
}
+ return table;
+ }
+
+
+ public Set<OptionalTaskDescriptor> getOptions(FlagState fs, TaskDescriptor td, int index) {
+ return fstotimap.get(fs).get(new TaskIndex(td, index));
+ }
+
+ public Set<OptionalTaskDescriptor> getOptions(FlagState fs, TaskIndex ti) {
+ return fstotimap.get(fs).get(ti);
+ }
+
+ public Set<TaskIndex> getTaskIndex(FlagState fs) {
+ return fstotimap.get(fs).keySet();
+ }
- public Hashtable<ClassDescriptor, Hashtable<OptionalTaskDescriptor, OptionalTaskDescriptor>> getOptionalTaskDescriptors() {
- return optionaltaskdescriptors;
+
+ /* Builds map of fs -> set of fs that depend on this fs */
+
+ private Hashtable<FlagState, Set<FlagState>> buildUseMap(ClassDescriptor cd) {
+ Hashtable<FlagState, Set<FlagState>> table=new Hashtable<FlagState, Set<FlagState>>();
+ 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<FlagState>());
+ 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<FlagState, Set<OptionalTaskDescriptor>> fstootd=new Hashtable<FlagState, Set<OptionalTaskDescriptor>>();
+ safeexecution.put(cd, fstootd);
+
+ optionaltaskdescriptors.put(cd, new Hashtable<OptionalTaskDescriptor, OptionalTaskDescriptor>());
+
+ Hashtable<FlagState, Set<EGTaskNode>> fstoegmap=buildMap(cd);
+ Hashtable<FlagState, Set<FlagState>> 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<FlagState, Hashtable<TaskIndex, Set<OptionalTaskDescriptor>>>();
+ HashSet<FlagState> tovisit=new HashSet<FlagState>();
+ 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<EGTaskNode> 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<FlagState, Set<EGTaskNode>> buildMap(ClassDescriptor cd) {
- Hashtable<FlagState, Set<EGTaskNode>> table=new Hashtable<FlagState, Set<EGTaskNode>>();
- 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<EGTaskNode>());
- table.get(node.getFS()).add(node);
+ printTEST();
+ }
+
+ public void analyzeFS(FlagState fs, Set<EGTaskNode> egset, Hashtable<FlagState, Set<OptionalTaskDescriptor>> fstootd, Hashtable<FlagState, Set<FlagState>> fsusemap, HashSet<FlagState> tovisit) {
+ Hashtable<TaskIndex, Set<OptionalTaskDescriptor>> timap=new Hashtable<TaskIndex, Set<OptionalTaskDescriptor>>();
+ Set<TaskIndex> tiselfloops=new HashSet<TaskIndex>();
+
+ for(Iterator<EGTaskNode> egit=egset.iterator(); egit.hasNext();) {
+ EGTaskNode egnode=egit.next();
+ Set<OptionalTaskDescriptor> setotd;
+ if (egnode.isOptional()) {
+ setotd=new HashSet<OptionalTaskDescriptor>();
+ HashSet<FlagState> enterfsset=new HashSet<FlagState>();
+ 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<OptionalTaskDescriptor>();
+ } else if(egnode.isMultipleParams()) {
+ if( goodMultiple(egnode)){
+ Predicate p=returnPredicate(egnode);
+ Set<OptionalTaskDescriptor> oldsetotd;
+ if (fstootd.containsKey(egnode.getPostFS()))
+ oldsetotd=fstootd.get(egnode.getPostFS());
+ else
+ oldsetotd=new HashSet<OptionalTaskDescriptor>();
+ setotd=new HashSet<OptionalTaskDescriptor>();
+ for(Iterator<OptionalTaskDescriptor> 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<OptionalTaskDescriptor>();
}
- return table;
+ } else {
+ if (fstootd.containsKey(egnode.getPostFS()))
+ setotd=fstootd.get(egnode.getPostFS());
+ else
+ setotd=new HashSet<OptionalTaskDescriptor>();
+ }
+ 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<OptionalTaskDescriptor> getOptions(FlagState fs, TaskDescriptor td, int index) {
- return fstotimap.get(fs).get(new TaskIndex(td, index));
+ //Combine all options
+ HashSet<OptionalTaskDescriptor> set=new HashSet<OptionalTaskDescriptor>();
+ for(Iterator<Set<OptionalTaskDescriptor>> it=timap.values().iterator(); it.hasNext();) {
+ Set<OptionalTaskDescriptor> otdset=it.next();
+ set.addAll(otdset);
}
- public Set<OptionalTaskDescriptor> 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<TaskIndex> 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<FlagState, Set<FlagState>> buildUseMap(ClassDescriptor cd) {
- Hashtable<FlagState, Set<FlagState>> table=new Hashtable<FlagState, Set<FlagState>>();
- 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<FlagState>());
- table.get(node.getPostFS()).add(node.getFS());
- }
+ Set<FlatNode> nodeset=fm.getNodeSet();
+
+ for(Iterator<FlatNode> 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<FlagState, Set<OptionalTaskDescriptor>> fstootd=new Hashtable<FlagState, Set<OptionalTaskDescriptor>>();
- safeexecution.put(cd, fstootd);
-
- optionaltaskdescriptors.put(cd, new Hashtable<OptionalTaskDescriptor, OptionalTaskDescriptor>());
-
- Hashtable<FlagState, Set<EGTaskNode>> fstoegmap=buildMap(cd);
- Hashtable<FlagState, Set<FlagState>> fsusemap=buildUseMap(cd);
-
- HashSet<FlagState> tovisit=new HashSet<FlagState>();
- 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<EGTaskNode> 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<td.numParameters(); i++) {
+ if(i!=tn.getIndex()) {
+ VarDescriptor vd = td.getParameter(i);
+ result.vardescriptors.add(vd);
+ HashSet<FlagExpressionNode> flaglist = new HashSet<FlagExpressionNode>();
+ 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<EGTaskNode> egset, Hashtable<FlagState, Set<OptionalTaskDescriptor>> fstootd, Hashtable<FlagState, Set<FlagState>> fsusemap, HashSet<FlagState> tovisit) {
- Hashtable<TaskIndex, Set<OptionalTaskDescriptor>> timap=new Hashtable<TaskIndex, Set<OptionalTaskDescriptor>>();
- Set<TaskIndex> tiselfloops=new HashSet<TaskIndex>();
-
- for(Iterator<EGTaskNode> egit=egset.iterator();egit.hasNext();) {
- EGTaskNode egnode=egit.next();
- Set<OptionalTaskDescriptor> setotd;
- if (egnode.isOptional()) {
- setotd=new HashSet<OptionalTaskDescriptor>();
- HashSet<FlagState> enterfsset=new HashSet<FlagState>();
- 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<OptionalTaskDescriptor>();
- } else if(egnode.isMultipleParams()) {
- if( goodMultiple(egnode)){
- Predicate p=returnPredicate(egnode);
- Set<OptionalTaskDescriptor> oldsetotd;
- if (fstootd.containsKey(egnode.getPostFS()))
- oldsetotd=fstootd.get(egnode.getPostFS());
- else
- oldsetotd=new HashSet<OptionalTaskDescriptor>();
- setotd=new HashSet<OptionalTaskDescriptor>();
- for(Iterator<OptionalTaskDescriptor> 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<OptionalTaskDescriptor>();
- }
- } else {
- if (fstootd.containsKey(egnode.getPostFS()))
- setotd=fstootd.get(egnode.getPostFS());
- else
- setotd=new HashSet<OptionalTaskDescriptor>();
- }
- 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<OptionalTaskDescriptor> set=new HashSet<OptionalTaskDescriptor>();
- for(Iterator<Set<OptionalTaskDescriptor>> it=timap.values().iterator();it.hasNext();) {
- Set<OptionalTaskDescriptor> 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<FlagState> processed=new Vector<FlagState>();
- 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<FlagState> oldprocess=processed;
+ processed=new Vector<FlagState>();
+
+ 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<FlatNode> nodeset=fm.getNodeSet();
-
- for(Iterator<FlatNode> 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<FlagState> oldprocess=processed;
+ processed=new Vector<FlagState>();
+
+ 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<td.numParameters(); i++) {
- if(i!=tn.getIndex()) {
- VarDescriptor vd = td.getParameter(i);
- result.vardescriptors.add(vd);
- HashSet<FlagExpressionNode> flaglist = new HashSet<FlagExpressionNode>();
- 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<fn1.numNext(); i++) {
+ FlatNode fnext=fn1.getNext(i);
+ if (!discovered.contains(fnext)) {
+ discovered.add(fnext);
+ nodestack.push(fnext);
}
- return result;
+ }
}
-
- 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);
+ otd.exitfses=result;
+ }
+
+ private void printTEST() {
+ Enumeration e = safeexecution.keys();
+ while (e.hasMoreElements()) {
+ ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
+ System.out.println("\nTesting class : "+cdtemp.getSymbol()+"\n");
+ Hashtable hashtbtemp = safeexecution.get(cdtemp);
+ Enumeration fses = hashtbtemp.keys();
+ while(fses.hasMoreElements()){
+ FlagState fs = (FlagState)fses.nextElement();
+ System.out.println("\t"+fs.getTextLabel()+"\n\tSafe tasks to execute :\n");
+ HashSet availabletasks = (HashSet)hashtbtemp.get(fs);
+ for(Iterator otd_it = availabletasks.iterator(); otd_it.hasNext();){
+ OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
+ System.out.println("\t\tTASK "+otd.td.getSymbol()+" UID : "+otd.getuid()+"\n");
+ System.out.println("\t\twith flags :");
+ for(Iterator myfses = otd.enterflagstates.iterator(); myfses.hasNext();){
+ System.out.println("\t\t\t"+((FlagState)myfses.next()).getTextLabel());
+ }
+ System.out.println("\t\tand exitflags :");
+ for(Iterator fseshash = otd.exitfses.iterator(); fseshash.hasNext();){
+ HashSet temphs = (HashSet)fseshash.next();
+ System.out.println("");
+ for(Iterator exfses = temphs.iterator(); exfses.hasNext();){
+ System.out.println("\t\t\t"+((FlagState)exfses.next()).getTextLabel());
}
+ }
+ Predicate predicate = otd.predicate;
+ System.out.println("\t\tPredicate constraints :");
+ Collection c = predicate.vardescriptors;
+ for(Iterator varit = c.iterator(); varit.hasNext();){
+ VarDescriptor vard = (VarDescriptor)varit.next();
+ System.out.println("\t\t\tClass "+vard.getType().getClassDesc().getSymbol());
+ }
+ System.out.println("\t\t------------");
}
- 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);
- }
+ }
+
+ System.out.println("\n\n\n\tOptionaltaskdescriptors contains : ");
+ Collection c_otd = optionaltaskdescriptors.get(cdtemp).values();
+ for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();){
+ OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
+ System.out.println("\t\tTASK "+otd.td.getSymbol()+" UID : "+otd.getuid()+"\n");
+ System.out.println("\t\twith flags :");
+ for(Iterator myfses = otd.enterflagstates.iterator(); myfses.hasNext();){
+ System.out.println("\t\t\t"+((FlagState)myfses.next()).getTextLabel());
}
- return result;
- }
+ System.out.println("\t\tand exitflags :");
+ for(Iterator fseshash = otd.exitfses.iterator(); fseshash.hasNext();){
+ HashSet temphs = (HashSet)fseshash.next();
+ System.out.println("");
+ for(Iterator exfses = temphs.iterator(); exfses.hasNext();){
+ System.out.println("\t\t\t"+((FlagState)exfses.next()).getTextLabel());
+ }
+ }
+ Predicate predicate = otd.predicate;
+ System.out.println("\t\tPredicate contains :");
+ Collection c = predicate.vardescriptors;
+ for(Iterator varit = c.iterator(); varit.hasNext();){
+ VarDescriptor vard = (VarDescriptor)varit.next();
+ System.out.println("\t\t\tClass "+vard.getType().getClassDesc().getSymbol());
+ HashSet temphash = predicate.flags.get(vard.getName());
+ if(temphash == null) System.out.println("null hashset");
+ else System.out.println("\t\t\t"+temphash.size()+" flag(s)");
- ////////////////////
- /* 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<FlagState> processed=new Vector<FlagState>();
-
- 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<FlagState> oldprocess=processed;
- processed=new Vector<FlagState>();
-
- 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<FlagState> oldprocess=processed;
- processed=new Vector<FlagState>();
-
- 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<fn1.numNext();i++) {
- FlatNode fnext=fn1.getNext(i);
- if (!discovered.contains(fnext)) {
- discovered.add(fnext);
- nodestack.push(fnext);
- }
- }
}
- otd.exitfses=result;
+ System.out.println("\t\t------------");
+ }
}
+ }
- private void printTEST(){
- Enumeration e = safeexecution.keys();
- while (e.hasMoreElements()) {
- ClassDescriptor cdtemp=(ClassDescriptor)e.nextElement();
- System.out.println("\nTesting class : "+cdtemp.getSymbol()+"\n");
- Hashtable hashtbtemp = safeexecution.get(cdtemp);
- Enumeration fses = hashtbtemp.keys();
- while(fses.hasMoreElements()){
- FlagState fs = (FlagState)fses.nextElement();
- System.out.println("\t"+fs.getTextLabel()+"\n\tSafe tasks to execute :\n");
- HashSet availabletasks = (HashSet)hashtbtemp.get(fs);
- for(Iterator otd_it = availabletasks.iterator(); otd_it.hasNext();){
- OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
- System.out.println("\t\tTASK "+otd.td.getSymbol()+" UID : "+otd.getuid()+"\n");
- System.out.println("\t\twith flags :");
- for(Iterator myfses = otd.enterflagstates.iterator(); myfses.hasNext();){
- System.out.println("\t\t\t"+((FlagState)myfses.next()).getTextLabel());
- }
- System.out.println("\t\tand exitflags :");
- for(Iterator fseshash = otd.exitfses.iterator(); fseshash.hasNext();){
- HashSet temphs = (HashSet)fseshash.next();
- System.out.println("");
- for(Iterator exfses = temphs.iterator(); exfses.hasNext();){
- System.out.println("\t\t\t"+((FlagState)exfses.next()).getTextLabel());
- }
- }
- Predicate predicate = otd.predicate;
- System.out.println("\t\tPredicate constraints :");
- Collection c = predicate.vardescriptors;
- for(Iterator varit = c.iterator(); varit.hasNext();){
- VarDescriptor vard = (VarDescriptor)varit.next();
- System.out.println("\t\t\tClass "+vard.getType().getClassDesc().getSymbol());
- }
- System.out.println("\t\t------------");
- }
- }
-
- System.out.println("\n\n\n\tOptionaltaskdescriptors contains : ");
- Collection c_otd = optionaltaskdescriptors.get(cdtemp).values();
- for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();){
- OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
- System.out.println("\t\tTASK "+otd.td.getSymbol()+" UID : "+otd.getuid()+"\n");
- System.out.println("\t\twith flags :");
- for(Iterator myfses = otd.enterflagstates.iterator(); myfses.hasNext();){
- System.out.println("\t\t\t"+((FlagState)myfses.next()).getTextLabel());
- }
- System.out.println("\t\tand exitflags :");
- for(Iterator fseshash = otd.exitfses.iterator(); fseshash.hasNext();){
- HashSet temphs = (HashSet)fseshash.next();
- System.out.println("");
- for(Iterator exfses = temphs.iterator(); exfses.hasNext();){
- System.out.println("\t\t\t"+((FlagState)exfses.next()).getTextLabel());
- }
- }
- Predicate predicate = otd.predicate;
- System.out.println("\t\tPredicate contains :");
- Collection c = predicate.vardescriptors;
- for(Iterator varit = c.iterator(); varit.hasNext();){
- VarDescriptor vard = (VarDescriptor)varit.next();
- System.out.println("\t\t\tClass "+vard.getType().getClassDesc().getSymbol());
- HashSet temphash = predicate.flags.get(vard.getName());
- if(temphash == null) System.out.println("null hashset");
- else System.out.println("\t\t\t"+temphash.size()+" flag(s)");
-
- }
- System.out.println("\t\t------------");
- }
+ /*check if there has been a tag Change*/
+ private boolean tagChange(EGTaskNode tn) {
+ if(tn.getTD() == null) return false; //to be fixed
+ FlatMethod fm = state.getMethodFlat(tn.getTD());
+ FlatNode fn = (FlatNode)fm;
+
+ 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.FlatFlagActionNode) {
+ FlatFlagActionNode ffan=(FlatFlagActionNode)fn1;
+ if (ffan.getTaskType() == FlatFlagActionNode.TASKEXIT) {
+ Iterator it_ttp=ffan.getTempTagPairs();
+ if(it_ttp.hasNext()){
+ System.out.println("Tag change detected in Task "+tn.getName());
+ return true;
+ } else continue; // avoid queueing the return node if reachable
}
- }
-
- /*check if there has been a tag Change*/
- private boolean tagChange(EGTaskNode tn){
- if(tn.getTD() == null) return false;//to be fixed
- FlatMethod fm = state.getMethodFlat(tn.getTD());
- FlatNode fn = (FlatNode)fm;
-
- 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.FlatFlagActionNode) {
- FlatFlagActionNode ffan=(FlatFlagActionNode)fn1;
- if (ffan.getTaskType() == FlatFlagActionNode.TASKEXIT) {
- Iterator it_ttp=ffan.getTempTagPairs();
- if(it_ttp.hasNext()){
- System.out.println("Tag change detected in Task "+tn.getName());
- return true;
- }
- else continue; // avoid queueing the return node if reachable
- }
- }
-
- /* Queue other nodes past this one */
- for(int i=0;i<fn1.numNext();i++) {
- FlatNode fnext=fn1.getNext(i);
- if (!discovered.contains(fnext)) {
- discovered.add(fnext);
- nodestack.push(fnext);
- }
- }
+ }
+
+ /* Queue other nodes past this one */
+ for(int i=0; i<fn1.numNext(); i++) {
+ FlatNode fnext=fn1.getNext(i);
+ if (!discovered.contains(fnext)) {
+ discovered.add(fnext);
+ nodestack.push(fnext);
}
- return false;
+ }
}
+ return false;
+ }
- /////////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()+";");
- }
- }
+ /////////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()+";");
+ }
}
+ }
}
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;
+ }
+
-
}
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<scc.numSCC(); i++) {
+ Set component=scc.getSCC(i);
+ HashSet flagset=new HashSet();
+ for(Iterator compit=component.iterator(); compit.hasNext();) {
+ TagBinding tb=(TagBinding)compit.next();
+ flagset.addAll(tb.getAllocations());
+ for(Iterator edgeit=tb.edges(); edgeit.hasNext();) {
+ Edge e=(Edge)edgeit.next();
+ TagBinding tb2=(TagBinding)e.getTarget();
+ flagset.addAll(tb2.getAllocations());
+ }
+ }
+ for(Iterator compit=component.iterator(); compit.hasNext();) {
+ TagBinding tb=(TagBinding)compit.next();
+ tb.getAllocations().addAll(flagset);
+ }
}
- public Set getFlagStates(TaskDescriptor task) {
- return (Set)tasktoflagstates.get(task);
+ SymbolTable tasktable=state.getTaskSymbolTable();
+ for(Iterator taskit=tasktable.getDescriptorsIterator(); taskit.hasNext();) {
+ TaskDescriptor task=(TaskDescriptor)taskit.next();
+ HashSet roottags=(HashSet)tasktotagbindings.get(task);
+ HashSet taskflags=(HashSet)tasktoflagstates.get(task);
+ for(Iterator tagit=roottags.iterator(); tagit.hasNext();) {
+ TagBinding tb=(TagBinding)tagit.next();
+ taskflags.addAll(tb.getAllocations());
+ }
+ }
+ }
+
+ 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 doAnalysis() {
- Set rootset=computeRootSet();
- computeTagBindings(rootset);
- TagBinding.SCC scc=TagBinding.DFS.computeSCC(discovered.keySet());
- for(int i=0;i<scc.numSCC();i++) {
- Set component=scc.getSCC(i);
- HashSet flagset=new HashSet();
- for(Iterator compit=component.iterator();compit.hasNext();) {
- TagBinding tb=(TagBinding)compit.next();
- flagset.addAll(tb.getAllocations());
- for(Iterator edgeit=tb.edges();edgeit.hasNext();) {
- Edge e=(Edge)edgeit.next();
- TagBinding tb2=(TagBinding)e.getTarget();
- flagset.addAll(tb2.getAllocations());
- }
- }
- for(Iterator compit=component.iterator();compit.hasNext();) {
- TagBinding tb=(TagBinding)compit.next();
- tb.getAllocations().addAll(flagset);
+ 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<md.numParameters(); i++) {
+ TempDescriptor temp=fc.getArg(i);
+ TagDescriptor tag=temp.getTag();
+ if (tag==null&¶mmap!=null&¶mmap.containsKey(temp)) {
+ tag=(TagDescriptor)parammap.get(temp);
}
+ if (tag!=null)
+ nodetb.setBinding(i,tag);
+ }
+ if (!discovered.containsKey(nodetb)) {
+ discovered.put(nodetb,nodetb);
+ tovisit.add(nodetb);
+ } else
+ nodetb=(TagBinding)discovered.get(nodetb);
+ tagbindings.add(nodetb);
}
-
- SymbolTable tasktable=state.getTaskSymbolTable();
- for(Iterator taskit=tasktable.getDescriptorsIterator();taskit.hasNext();) {
- TaskDescriptor task=(TaskDescriptor)taskit.next();
- HashSet roottags=(HashSet)tasktotagbindings.get(task);
- HashSet taskflags=(HashSet)tasktoflagstates.get(task);
- for(Iterator tagit=roottags.iterator();tagit.hasNext();) {
- TagBinding tb=(TagBinding)tagit.next();
- taskflags.addAll(tb.getAllocations());
+ } else if (fn.kind()==FKind.FlatFlagActionNode) {
+ FlatFlagActionNode ffan=(FlatFlagActionNode)fn;
+ if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
+ TempDescriptor ffantemp=null;
+ {
+ /* Compute type */
+
+ Iterator it=ffan.getTempFlagPairs();
+ if (it.hasNext()) {
+ TempFlagPair tfp=(TempFlagPair)it.next();
+ ffantemp=tfp.getTemp();
+ } else {
+ it=ffan.getTempTagPairs();
+ if (!it.hasNext())
+ throw new Error();
+ TempTagPair ttp=(TempTagPair)it.next();
+ ffantemp=ttp.getTemp();
}
+ }
+ Vector<FlagState> 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<md.numParameters();i++) {
- TempDescriptor temp=fc.getArg(i);
- TagDescriptor tag=temp.getTag();
- if (tag==null&¶mmap!=null&¶mmap.containsKey(temp)) {
- tag=(TagDescriptor)parammap.get(temp);
- }
- if (tag!=null)
- nodetb.setBinding(i,tag);
- }
- if (!discovered.containsKey(nodetb)) {
- discovered.put(nodetb,nodetb);
- tovisit.add(nodetb);
- } else
- nodetb=(TagBinding)discovered.get(nodetb);
- tagbindings.add(nodetb);
- }
- } else if (fn.kind()==FKind.FlatFlagActionNode) {
- FlatFlagActionNode ffan=(FlatFlagActionNode)fn;
- if (ffan.getTaskType()==FlatFlagActionNode.NEWOBJECT) {
- TempDescriptor ffantemp=null;
- {
- /* Compute type */
-
- Iterator it=ffan.getTempFlagPairs();
- if (it.hasNext()) {
- TempFlagPair tfp=(TempFlagPair)it.next();
- ffantemp=tfp.getTemp();
- } else {
- it=ffan.getTempTagPairs();
- if (!it.hasNext())
- throw new Error();
- TempTagPair ttp=(TempTagPair)it.next();
- ffantemp=ttp.getTemp();
- }
- }
- Vector<FlagState> 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<fm.numParameters();i++) {
- TempDescriptor temp=fm.getParameter(i);
- int offsetindex=i-offset;
- if (offsetindex>=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<fm.numParameters(); i++) {
+ TempDescriptor temp=fm.getParameter(i);
+ int offsetindex=i-offset;
+ if (offsetindex>=0) {
+ TagDescriptor tag=tb.getBinding(offsetindex);
+
+ if (tag!=null) {
+ parammap.put(temp,tag);
+ }
}
+ }
+
+ HashSet newtags=new HashSet();
+
+ 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);
+ }
}
+ }
}
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<tdarray.length;i++)
- st+=tdarray[i]+" ";
- return st;
- }
+ public String toString() {
+ String st=md.toString();
+ for(int i=0; i<tdarray.length; i++)
+ st+=tdarray[i]+" ";
+ return st;
+ }
- public Set getAllocations() {
- return allocations;
- }
+ public Set getAllocations() {
+ return allocations;
+ }
- public void setBinding(int i, TagDescriptor td) {
- tdarray[i]=td;
- }
+ public void setBinding(int i, TagDescriptor td) {
+ tdarray[i]=td;
+ }
- public MethodDescriptor getMethod() {
- return md;
- }
+ public MethodDescriptor getMethod() {
+ return md;
+ }
- public TagDescriptor getBinding(int i) {
- return tdarray[i];
- }
+ public TagDescriptor getBinding(int i) {
+ return tdarray[i];
+ }
- public boolean equals(Object o) {
- if (o instanceof TagBinding) {
- TagBinding tb=(TagBinding)o;
- if (md!=tb.md)
- return false;
- for(int i=0;i<tdarray.length;i++)
- if (tdarray[i]!=null) {
- if (!tdarray[i].equals(tb.tdarray[i]))
- return false;
- } else if(tb.tdarray[i]!=null)
- return false;
- return true;
- }
+ public boolean equals(Object o) {
+ if (o instanceof TagBinding) {
+ TagBinding tb=(TagBinding)o;
+ if (md!=tb.md)
return false;
+ for(int i=0; i<tdarray.length; i++)
+ if (tdarray[i]!=null) {
+ if (!tdarray[i].equals(tb.tdarray[i]))
+ return false;
+ } else if(tb.tdarray[i]!=null)
+ return false;
+ return true;
}
+ return false;
+ }
- public int hashCode() {
- int hashcode=md.hashCode();
- for(int i=0;i<tdarray.length;i++) {
- if (tdarray[i]!=null)
- hashcode^=tdarray[i].hashCode();
- }
- return hashcode;
+ public int hashCode() {
+ int hashcode=md.hashCode();
+ for(int i=0; i<tdarray.length; i++) {
+ if (tdarray[i]!=null)
+ hashcode^=tdarray[i].hashCode();
}
+ return hashcode;
+ }
}
public class TagEdge extends Edge {
- private TaskDescriptor td;
- /** Class Constructor
- *
- */
- public TagEdge(TagState target, TaskDescriptor td) {
- super(target);
- this.td=td;
- }
-
- public int hashCode(){
- return target.hashCode()^td.hashCode();
- }
+ private TaskDescriptor td;
+ /** Class Constructor
+ *
+ */
+ public TagEdge(TagState target, TaskDescriptor td) {
+ super(target);
+ this.td=td;
+ }
- public TaskDescriptor getTask() {
- return td;
- }
+ public int hashCode() {
+ return target.hashCode()^td.hashCode();
+ }
+
+ public TaskDescriptor getTask() {
+ return td;
+ }
- public boolean equals(Object o) {
- if (o instanceof TagEdge) {
- TagEdge e=(TagEdge)o;
- if (e.target.equals(target)&&
- e.td==td)
- return true;
- }
- return false;
+ public boolean equals(Object o) {
+ if (o instanceof TagEdge) {
+ TagEdge e=(TagEdge)o;
+ if (e.target.equals(target)&&
+ e.td==td)
+ return true;
}
+ return false;
+ }
}
public class TagState extends GraphNode {
- private TagDescriptor tag;
- private ClassDescriptor cd;
- private Hashtable<FlagState, Integer> flags;
- public static final int KLIMIT=2;
- public HashSet<TaskDescriptor> sourceset;
-
- public TagState(ClassDescriptor cd) {
- this.flags=new Hashtable<FlagState, Integer>();
- this.sourceset=new HashSet<TaskDescriptor>();
- this.cd=cd;
- }
+ private TagDescriptor tag;
+ private ClassDescriptor cd;
+ private Hashtable<FlagState, Integer> flags;
+ public static final int KLIMIT=2;
+ public HashSet<TaskDescriptor> sourceset;
- public void addSource(TaskDescriptor td) {
- sourceset.add(td);
- }
+ public TagState(ClassDescriptor cd) {
+ this.flags=new Hashtable<FlagState, Integer>();
+ this.sourceset=new HashSet<TaskDescriptor>();
+ this.cd=cd;
+ }
- public TagState(TagDescriptor tag) {
- this.tag=tag;
- this.flags=new Hashtable<FlagState, Integer>();
- this.sourceset=new HashSet<TaskDescriptor>();
- }
+ public void addSource(TaskDescriptor td) {
+ sourceset.add(td);
+ }
- public TagDescriptor getTag() {
- return tag;
- }
+ public TagState(TagDescriptor tag) {
+ this.tag=tag;
+ this.flags=new Hashtable<FlagState, Integer>();
+ this.sourceset=new HashSet<TaskDescriptor>();
+ }
- 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 (num<KLIMIT)
- num++;
-
- TagState ts=new TagState(tag);
- ts.flags.putAll(flags);
- ts.flags.put(fs, new Integer(num));
- return new TagState[] {ts};
- }
+ public TagState[] clearFS(FlagState fs) {
+ int num=0;
+ if (flags.containsKey(fs))
+ num=flags.get(fs).intValue();
+ if (num>0)
+ num--;
- public TagState[] addFS(FlagState fs) {
- int num=0;
- if (flags.containsKey(fs))
- num=flags.get(fs).intValue();
- if (num<KLIMIT)
- num++;
-
- TagState ts=new TagState(tag);
- ts.flags.putAll(flags);
- ts.flags.put(fs, new Integer(num));
- if (num==1)
- return new TagState[] {ts};
- else
- return new TagState[] {this, ts};
- }
+ TagState ts=new TagState(tag);
+ ts.flags.putAll(flags);
+ ts.flags.put(fs, new Integer(num));
- public boolean containsFS(FlagState fs) {
- return flags.containsKey(fs);
- }
+ if ((num+1)==KLIMIT)
+ return new TagState[] {ts, this};
+ else
+ return new TagState[] {ts};
+ }
- public Set<FlagState> getFS() {
- return flags.keySet();
- }
+ public TagState[] addnewFS(FlagState fs) {
+ int num=0;
+ if (flags.containsKey(fs))
+ num=flags.get(fs).intValue();
+ if (num<KLIMIT)
+ num++;
- 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;
+ TagState ts=new TagState(tag);
+ ts.flags.putAll(flags);
+ ts.flags.put(fs, new Integer(num));
+ return new TagState[] {ts};
+ }
+
+ public TagState[] addFS(FlagState fs) {
+ int num=0;
+ if (flags.containsKey(fs))
+ num=flags.get(fs).intValue();
+ if (num<KLIMIT)
+ num++;
+
+ TagState ts=new TagState(tag);
+ ts.flags.putAll(flags);
+ ts.flags.put(fs, new Integer(num));
+ if (num==1)
+ return new TagState[] {ts};
+ else
+ return new TagState[] {this, ts};
+ }
+
+ public boolean containsFS(FlagState fs) {
+ return flags.containsKey(fs);
+ }
+
+ public Set<FlagState> 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;
+ }
}
import java.util.*;
public class TagWrapper implements Wrapper {
- TagState initts;
- HashSet<TagState> ts;
+ TagState initts;
+ HashSet<TagState> ts;
- public TagWrapper(TagState ts) {
- this.initts=ts;
- this.ts=new HashSet<TagState>();
- this.ts.add(ts);
- }
+ public TagWrapper(TagState ts) {
+ this.initts=ts;
+ this.ts=new HashSet<TagState>();
+ 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<TagState>)ts.clone();
- return tw;
- }
+ public TagWrapper clone() {
+ TagWrapper tw=new TagWrapper();
+ tw.initts=initts;
+ tw.ts=(HashSet<TagState>)ts.clone();
+ return tw;
+ }
}
import java.io.FileOutputStream;
public class TaskAnalysis {
- State state;
- Hashtable flagstates;
- Hashtable flags;
- Hashtable extern_flags;
- Queue<FlagState> 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<FlagState> 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<FlagState,FlagState> sourcenodes;
- cdtorootnodes=new Hashtable();
- tdToFEdges=new Hashtable();
-
- getFlagsfromClasses();
-
- int externs;
- toprocess=new LinkedList<FlagState>();
-
- 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<FlagState,FlagState>());
- cdtorootnodes.put(cd,new Vector());
- }
-
-
- ClassDescriptor startupobject=typeutil.getClass(TypeUtil.StartupClass);
-
- sourcenodes=(Hashtable<FlagState,FlagState>)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<FlagState,FlagState> sourcenodes;
+ cdtorootnodes=new Hashtable();
+ tdToFEdges=new Hashtable();
+
+ getFlagsfromClasses();
+
+ int externs;
+ toprocess=new LinkedList<FlagState>();
+
+ 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<FlagState,FlagState>());
+ cdtorootnodes.put(cd,new Vector());
+ }
+
+
+ ClassDescriptor startupobject=typeutil.getClass(TypeUtil.StartupClass);
+
+ sourcenodes=(Hashtable<FlagState,FlagState>)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<FlagState,FlagState> sourcenodes=(Hashtable<FlagState,FlagState>)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<FEdge>());
+
+ 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<FEdge>());
+ }
+
+ /** 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<FlagState,FlagState>)flagstates.get(fsnew.getClassDescriptor())).containsKey(fsnew)) {
+ ((Hashtable<FlagState,FlagState>)flagstates.get(fsnew.getClassDescriptor())).put(fsnew, fsnew);
+ toprocess.add(fsnew);
+ } else {
+ fsnew=((Hashtable<FlagState, FlagState>)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<FlagState,FlagState>)flagstates.get(fsnew.getClassDescriptor())).containsKey(fsnew)) {
- ((Hashtable<FlagState,FlagState>)flagstates.get(fsnew.getClassDescriptor())).put(fsnew, fsnew);
- toprocess.add(fsnew);
- } else {
- fsnew=((Hashtable<FlagState, FlagState>)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<FEdge>)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<FlagState> fsv_taskexit=evalTaskExitNode(ffan,cd,fs,temp);
- Vector<FlagState> initFStates = ffan.getInitFStates(temp.getType().getClassDesc());
- if(!initFStates.contains(fs)) {
- initFStates.addElement(fs);
- }
- Vector<FlagState> 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<FEdge>)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<FEdge>)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<FlagState> fsv_taskexit=evalTaskExitNode(ffan,cd,fs,temp);
+ Vector<FlagState> initFStates = ffan.getInitFStates(temp.getType().getClassDesc());
+ if(!initFStates.contains(fs)) {
+ initFStates.addElement(fs);
}
- /* Queue other nodes past this one */
- for(int i=0;i<fn1.numNext();i++) {
- FlatNode fnext=fn1.getNext(i);
- if (!discovered.contains(fnext)) {
- discovered.add(fnext);
- nodestack.push(fnext);
- }
+ Vector<FlagState> 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<FEdge>)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<fn1.numNext(); i++) {
+ FlatNode fnext=fn1.getNext(i);
+ if (!discovered.contains(fnext)) {
+ discovered.add(fnext);
+ nodestack.push(fnext);
+ }
}
+ }
}
-}
+ }
-/** Determines whether the given flagstate satisfies a
+/** Determines whether the given flagstate satisfies a
* single parameter in the given task.
* @param fen FlagExpressionNode
* @see FlagExpressionNode
*/
-public static boolean isTaskTrigger_flag(FlagExpressionNode fen,FlagState fs) {
+ public static boolean isTaskTrigger_flag(FlagExpressionNode fen,FlagState fs) {
if (fen==null)
- return true;
+ return true;
else if (fen instanceof FlagNode)
- return fs.get(((FlagNode)fen).getFlag());
+ 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;
- }
-}
+ switch (((FlagOpNode)fen).getOp().getOp()) {
+ case Operation.LOGIC_AND:
+ return ((isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)) && (isTaskTrigger_flag(((FlagOpNode)fen).getRight(),fs)));
-private boolean isTaskTrigger_tag(TagExpressionList tel, FlagState fs){
-
- if (tel!=null){
- for (int i=0;i<tel.numTags() ; i++){
- switch (fs.getTagCount(tel.getType(i))){
- case FlagState.ONETAG:
- case FlagState.MULTITAGS:
- break;
- case FlagState.NOTAGS:
- return false;
- }
- }
- }
- return true;
-}
+ 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));
- private Vector<FlagState> evalTaskExitNode(FlatFlagActionNode ffan,ClassDescriptor cd,FlagState fs, TempDescriptor temp){
- FlagState fstemp=fs;
- Vector<FlagState> processed=new Vector<FlagState>();
+ 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<FlagState> oldprocess=processed;
- processed=new Vector<FlagState>();
-
- 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<FlagState> oldprocess=processed;
- processed=new Vector<FlagState>();
-
- 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<tel.numTags() ; i++){
+ switch (fs.getTagCount(tel.getType(i))){
+ case FlagState.ONETAG:
+ case FlagState.MULTITAGS:
+ break;
+
+ case FlagState.NOTAGS:
+ return false;
}
+ }
}
+ return true;
+ }
- /** 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<FlagState> getFlagStates(ClassDescriptor cd) {
- if (flagstates.containsKey(cd))
- return ((Hashtable<FlagState, FlagState>)flagstates.get(cd)).keySet();
- else
- return new HashSet<FlagState>();
+ private Vector<FlagState> evalTaskExitNode(FlatFlagActionNode ffan,ClassDescriptor cd,FlagState fs, TempDescriptor temp) {
+ FlagState fstemp=fs;
+ Vector<FlagState> processed=new Vector<FlagState>();
+
+ //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<FlagState> oldprocess=processed;
+ processed=new Vector<FlagState>();
- private void createPossibleRuntimeStates(FlagState fs) {
- ClassDescriptor cd = fs.getClassDescriptor();
- Hashtable<FlagState,FlagState> sourcenodes=(Hashtable<FlagState,FlagState>)flagstates.get(cd);
- FlagDescriptor[] fd=(FlagDescriptor[])flags.get(cd);
- int externs=((Integer)extern_flags.get(cd)).intValue();
-
- if(externs==0)
- return;
-
- int noOfIterations=(1<<externs) - 1;
- boolean BoolValTable[]=new boolean[externs];
-
-
- for(int i=0; i < externs ; i++) {
- BoolValTable[i]=fs.get(fd[i]);
+ 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);
}
-
- for(int k=0; k<noOfIterations; k++) {
- for(int j=0; j < externs ;j++) {
- if ((k% (1<<j)) == 0)
- BoolValTable[j]=(!BoolValTable[j]);
- }
-
- FlagState fstemp=fs;
-
- for(int i=0; i < externs;i++) {
- fstemp=fstemp.setFlag(fd[i],BoolValTable[i]);
- }
- if (!sourcenodes.containsKey(fstemp))
- toprocess.add(fstemp);
+ }
+ }
+ //Process sets next
+ for(Iterator it_ttp=ffan.getTempTagPairs(); it_ttp.hasNext();) {
+ TempTagPair ttp=(TempTagPair)it_ttp.next();
+
+ if (temp==ttp.getTemp()) {
+ Vector<FlagState> oldprocess=processed;
+ processed=new Vector<FlagState>();
- 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<FlagState> getFlagStates(ClassDescriptor cd) {
+ if (flagstates.containsKey(cd))
+ return ((Hashtable<FlagState, FlagState>)flagstates.get(cd)).keySet();
+ else
+ return new HashSet<FlagState>();
+ }
+
+
+ private void createPossibleRuntimeStates(FlagState fs) {
+ ClassDescriptor cd = fs.getClassDescriptor();
+ Hashtable<FlagState,FlagState> sourcenodes=(Hashtable<FlagState,FlagState>)flagstates.get(cd);
+ FlagDescriptor[] fd=(FlagDescriptor[])flags.get(cd);
+ int externs=((Integer)extern_flags.get(cd)).intValue();
+
+ if(externs==0)
+ return;
+
+ int noOfIterations=(1<<externs) - 1;
+ boolean BoolValTable[]=new boolean[externs];
+
+
+ for(int i=0; i < externs ; i++) {
+ BoolValTable[i]=fs.get(fd[i]);
+ }
+
+ for(int k=0; k<noOfIterations; k++) {
+ for(int j=0; j < externs ; j++) {
+ if ((k% (1<<j)) == 0)
+ BoolValTable[j]=(!BoolValTable[j]);
+ }
+
+ FlagState fstemp=fs;
+
+ for(int i=0; i < externs; i++) {
+ fstemp=fstemp.setFlag(fd[i],BoolValTable[i]);
+ }
+ if (!sourcenodes.containsKey(fstemp))
+ toprocess.add(fstemp);
+
+ fstemp=canonicalizeFlagState(sourcenodes,fstemp);
+ fs.addEdge(new FEdge(fstemp,"Runtime", null, -1));
}
-}
+ }
+
+ public Vector getRootNodes(ClassDescriptor cd) {
+ return (Vector)cdtorootnodes.get(cd);
+ }
+
+ public Vector getFEdgesFromTD(TaskDescriptor td) {
+ return (Vector)tdToFEdges.get(td);
+ }
+}
import java.util.*;
public class TaskBinding {
- TaskQueueIterator tqi;
- Vector<Integer> decisions;
- Hashtable<TempDescriptor, TagWrapper> temptotag;
- ObjWrapper[] parameterbindings;
- boolean increment;
+ TaskQueueIterator tqi;
+ Vector<Integer> decisions;
+ Hashtable<TempDescriptor, TagWrapper> temptotag;
+ ObjWrapper[] parameterbindings;
+ boolean increment;
- public TaskBinding(TaskQueueIterator tqi) {
- this.tqi=tqi;
- this.decisions=new Vector<Integer>();
- 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<Integer>();
+ 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<TempDescriptor> 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<TempDescriptor> 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<TagState, Vector<TagWrapper>> ttable=new Hashtable<TagState, Vector<TagWrapper>>();
+ temptotag=new Hashtable<TempDescriptor, TagWrapper>();
+ //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<TagWrapper>());
+ }
+ ttable.get(tag).add(tw);
+ } else {
+ //use old instance
+ tw=ttable.get(tag).get(index);
}
-
- mainloop:
- while(true) {
- Hashtable<TagState, Vector<TagWrapper>> ttable=new Hashtable<TagState, Vector<TagWrapper>>();
- temptotag=new Hashtable<TempDescriptor, TagWrapper>();
- //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<TagWrapper>());
- }
- 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 <TagState,Set<TagWrapper>> ctable=new Hashtable<TagState, Set<TagWrapper>>();
- ctable.put(tw.getState(), new HashSet<TagWrapper>());
- 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<tel.numTags();j++) {
- TempDescriptor tagtmp=tel.getTemp(j);
- TagWrapper twtmp=temptotag.get(tagtmp);
- if (!ctable.containsKey(twtmp.ts))
- ctable.put(twtmp.getState(), new HashSet<TagWrapper>());
- 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 <TagState,Set<TagWrapper>> ctable=new Hashtable<TagState, Set<TagWrapper>>();
+ ctable.put(tw.getState(), new HashSet<TagWrapper>());
+ 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<tel.numTags(); j++) {
+ TempDescriptor tagtmp=tel.getTemp(j);
+ TagWrapper twtmp=temptotag.get(tagtmp);
+ if (!ctable.containsKey(twtmp.ts))
+ ctable.put(twtmp.getState(), new HashSet<TagWrapper>());
+ 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;
}
+ }
}
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\"";
+ }
+
+}
import java.io.FileOutputStream;
public class TaskGraph {
- TaskAnalysis taskanalysis;
- State state;
- Hashtable cdtonodes;
- Hashtable nodes;
- Hashtable<TaskNode,TaskNode> 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<TaskNode,TaskNode>();
-
- 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<TaskNode,TaskNode> 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<TaskNode,TaskNode>();
+
+ 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<TaskNode,TaskNode> tasknodes=new Hashtable<TaskNode,TaskNode>();
+ 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<TaskNode,TaskNode> tasknodes=new Hashtable<TaskNode,TaskNode>();
- 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<TaskNode,TaskNode>();
-
- 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<TaskNode,TaskNode>();
+
+ 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<TaskNode,TaskNode> tasknodes){
-
- // Hashtable<TaskNode,TaskNode> tasknodes=(Hashtable<TaskNode,TaskNode>)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<TaskNode,TaskNode> 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<TaskNode,TaskNode> tasknodes) {
+
+ // Hashtable<TaskNode,TaskNode> tasknodes=(Hashtable<TaskNode,TaskNode>)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<TaskNode,TaskNode> 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);
+ }
+
+ }
+
}
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;
+ }
}
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);
+ }
+
}
-
-
-
+
+
+
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\"";
+ }
-}
+}
import java.util.*;
public class TaskQueue {
- protected TaskDescriptor task;
- protected HashSet<FlagTagState> []parameterset;
- protected Vector<TempDescriptor> tags;
- protected Hashtable <FlagState, Vector<FlagTagState>> map;
+ protected TaskDescriptor task;
+ protected HashSet<FlagTagState> [] parameterset;
+ protected Vector<TempDescriptor> tags;
+ protected Hashtable <FlagState, Vector<FlagTagState>> 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<FlagTagState>[])new HashSet[task.numParameters()];
- this.map=new Hashtable<FlagState, Vector<FlagTagState>>();
- this.tags=new Vector<TempDescriptor>();
- for(int i=0;i<task.numParameters();i++) {
- this.parameterset[i]=new HashSet<FlagTagState>();
- TagExpressionList tel=td.getTag(td.getParameter(i));
- if (tel!=null)
- for(int j=0;j<tel.numTags();j++) {
- TempDescriptor tagtmp=tel.getTemp(j);
- if (!tags.contains(tagtmp))
- tags.add(tagtmp);
- }
+ public TaskQueue(TaskDescriptor td) {
+ this.task=td;
+ this.parameterset=(HashSet<FlagTagState>[]) new HashSet[task.numParameters()];
+ this.map=new Hashtable<FlagState, Vector<FlagTagState>>();
+ this.tags=new Vector<TempDescriptor>();
+ for(int i=0; i<task.numParameters(); i++) {
+ this.parameterset[i]=new HashSet<FlagTagState>();
+ TagExpressionList tel=td.getTag(td.getParameter(i));
+ if (tel!=null)
+ for(int j=0; j<tel.numTags(); j++) {
+ TempDescriptor tagtmp=tel.getTemp(j);
+ if (!tags.contains(tagtmp))
+ tags.add(tagtmp);
}
}
-
- public TaskQueueIterator enqueue(int index, FlagTagState fts) {
- parameterset[index].add(fts);
- if (!map.containsKey(fts.fs)) {
- map.put(fts.fs, new Vector<FlagTagState>());
- }
- 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<FlagTagState>());
}
+ map.get(fts.fs).add(fts);
+ return new TaskQueueIterator(this, index, fts);
+ }
}
import java.util.*;
public class TaskQueueIterator {
- TaskQueue tq;
- int index;
- FlagTagState fts;
- FlagTagState ftsarray[];
- Hashtable<TempDescriptor, TagState> tsarray;
- Hashtable<TempDescriptor, Integer> tsindexarray;
- Iterator<FlagTagState> itarray[];
- boolean needit;
- boolean needinit;
+ TaskQueue tq;
+ int index;
+ FlagTagState fts;
+ FlagTagState ftsarray[];
+ Hashtable<TempDescriptor, TagState> tsarray;
+ Hashtable<TempDescriptor, Integer> tsindexarray;
+ Iterator<FlagTagState> 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<TempDescriptor, TagState>();
- this.tsindexarray=new Hashtable<TempDescriptor, Integer>();
- this.itarray=(Iterator<FlagTagState>[]) 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<tel.numTags();j++) {
- TempDescriptor tmp=tel.getTemp(j);
- if (!tsindexarray.containsKey(tmp)) {
- tsindexarray.put(tmp, new Integer(i));
- }
- }
+ 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<TempDescriptor, TagState>();
+ this.tsindexarray=new Hashtable<TempDescriptor, Integer>();
+ this.itarray=(Iterator<FlagTagState>[]) 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<tel.numTags(); j++) {
+ TempDescriptor tmp=tel.getTemp(j);
+ if (!tsindexarray.containsKey(tmp)) {
+ tsindexarray.put(tmp, new Integer(i));
+ }
}
}
+ }
- public boolean hasNext() {
- TaskDescriptor td=tq.task;
- int i;
- if (needinit) {
- i=ftsarray.length-1;
- if (i!=index)
- ftsarray[i]=itarray[i].next();
- } else {
- i=0;
- }
+ public boolean hasNext() {
+ TaskDescriptor td=tq.task;
+ int i;
+ if (needinit) {
+ i=ftsarray.length-1;
+ if (i!=index)
+ ftsarray[i]=itarray[i].next();
+ } else {
+ i=0;
+ }
- if (i==0&&index==0&&ftsarray[0]!=null&&!needit) {
- needinit=false;
- return true;
- }
+ if (i==0&&index==0&&ftsarray[0]!=null&&!needit) {
+ needinit=false;
+ return true;
+ }
- objloop:
- for(;i<ftsarray.length;i++) {
- FlagState currfs=ftsarray[i].fs;
- VarDescriptor vd=td.getParameter(i);
- TagExpressionList tel=td.getTag(vd);
- int j;
- if (needinit) {
- j=(tel!=null)&&tel.numTags()>0?tel.numTags()-1:0;
- needinit=false;
- } else
- j=0;
- tagloop:
- for(;tel!=null&&j<tel.numTags();j++) {
- TempDescriptor tmp=tel.getTemp(j);
- TagState currtag=tsarray.get(tmp);
- String type=tel.getType(j);
-
- if (tsindexarray.get(tmp).intValue()==i) {
- //doing the assignment right here!!!
- Vector<FlagTagState> possts=tq.map.get(currfs);
- int index=0;
- if (currtag!=null)
- index=possts.indexOf(new FlagTagState(currtag,currfs));
- if (needit) {
- index++;
- needit=false;
- }
- for(int k=index;k<possts.size();k++) {
- FlagTagState posstag=possts.get(k);
- if (posstag.ts.getTag().getSymbol().equals(type)) {
- tsarray.put(tmp, posstag.ts);
- if (j==0) {
- if (i==0) {
- //We are done!
- return true;
- } else {
- //Backtrack on objects
- i-=2;
- continue objloop;
- }
- } else {
- //Backtrack on tags
- j-=2;
- continue tagloop;
- }
- }
- }
- //couldn't find a tag
- tsarray.put(tmp, null);
- needit=true;
- } else {
- //check tag compatibility
- if (!currtag.containsFS(currfs)) {
- //incompatible tag set by previous level
- //need to increment object state
- needit=true;
- break;
- }
- }
- }
- if (index==i) {
- continue;
- }
- if (needit) {
- if (itarray[i].hasNext()) {
- ftsarray[i]=itarray[i].next();
- needit=false;
- i-=1;
- continue objloop; //backtrack and fix up everything
+objloop:
+ for(; i<ftsarray.length; i++) {
+ FlagState currfs=ftsarray[i].fs;
+ VarDescriptor vd=td.getParameter(i);
+ TagExpressionList tel=td.getTag(vd);
+ int j;
+ if (needinit) {
+ j=(tel!=null)&&tel.numTags()>0 ? tel.numTags()-1 : 0;
+ needinit=false;
+ } else
+ j=0;
+tagloop:
+ for(; tel!=null&&j<tel.numTags(); j++) {
+ TempDescriptor tmp=tel.getTemp(j);
+ TagState currtag=tsarray.get(tmp);
+ String type=tel.getType(j);
+
+ if (tsindexarray.get(tmp).intValue()==i) {
+ //doing the assignment right here!!!
+ Vector<FlagTagState> possts=tq.map.get(currfs);
+ int index=0;
+ if (currtag!=null)
+ index=possts.indexOf(new FlagTagState(currtag,currfs));
+ if (needit) {
+ index++;
+ needit=false;
+ }
+ for(int k=index; k<possts.size(); k++) {
+ FlagTagState posstag=possts.get(k);
+ if (posstag.ts.getTag().getSymbol().equals(type)) {
+ tsarray.put(tmp, posstag.ts);
+ if (j==0) {
+ if (i==0) {
+ //We are done!
+ return true;
} else {
- itarray[i]=tq.parameterset[i].iterator();//keep going backwards
+ //Backtrack on objects
+ i-=2;
+ continue objloop;
}
- } else {
- throw new Error();
+ } else {
+ //Backtrack on tags
+ j-=2;
+ continue tagloop;
+ }
}
+ }
+ //couldn't find a tag
+ tsarray.put(tmp, null);
+ needit=true;
+ } else {
+ //check tag compatibility
+ if (!currtag.containsFS(currfs)) {
+ //incompatible tag set by previous level
+ //need to increment object state
+ needit=true;
+ break;
+ }
+ }
+ }
+ if (index==i) {
+ continue;
+ }
+ if (needit) {
+ if (itarray[i].hasNext()) {
+ ftsarray[i]=itarray[i].next();
+ needit=false;
+ i-=1;
+ continue objloop; //backtrack and fix up everything
+ } else {
+ itarray[i]=tq.parameterset[i].iterator(); //keep going backwards
}
- return false;
+ } else {
+ throw new Error();
+ }
}
+ return false;
+ }
- public FlagTagState getFTS(int index) {
- return ftsarray[index];
- }
+ public FlagTagState getFTS(int index) {
+ return ftsarray[index];
+ }
- public TagState getTS(TempDescriptor tmp) {
- return tsarray.get(tmp);
- }
-
- public void next() {
- needit=true;
- }
+ public TagState getTS(TempDescriptor tmp) {
+ return tsarray.get(tmp);
+ }
+
+ public void next() {
+ needit=true;
+ }
}
import java.io.FileOutputStream;
public class TaskTagAnalysis {
- State state;
- TagAnalysis taganalysis;
- TypeUtil typeutil;
- FlagInfo flaginfo;
- HashSet<TagState> toprocess;
- HashSet<TagState> discovered;
- Hashtable<TaskDescriptor, TaskQueue> tasktable;
- Hashtable<TagDescriptor, Set<TagState>> tsresults;
- Hashtable<ClassDescriptor, Set<TagState>> 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<TagState>();
- this.discovered=new HashSet<TagState>();
- this.tasktable=new Hashtable<TaskDescriptor, TaskQueue>();
- this.tsresults=new Hashtable<TagDescriptor, Set<TagState>>();
- this.fsresults=new Hashtable<ClassDescriptor, Set<TagState>>();
-
-
- 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<TagState> toprocess;
+ HashSet<TagState> discovered;
+ Hashtable<TaskDescriptor, TaskQueue> tasktable;
+ Hashtable<TagDescriptor, Set<TagState>> tsresults;
+ Hashtable<ClassDescriptor, Set<TagState>> 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<TagState>();
+ this.discovered=new HashSet<TagState>();
+ this.tasktable=new Hashtable<TaskDescriptor, TaskQueue>();
+ this.tsresults=new Hashtable<TagDescriptor, Set<TagState>>();
+ this.fsresults=new Hashtable<ClassDescriptor, Set<TagState>>();
+
+
+ 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<TagDescriptor> tagit=tsresults.keySet().iterator();tagit.hasNext();) {
- TagDescriptor tag=tagit.next();
- Set<TagState> 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<ClassDescriptor> cdit=fsresults.keySet().iterator();cdit.hasNext();) {
- ClassDescriptor cd=cdit.next();
- Set<TagState> 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<TagDescriptor> tagit=tsresults.keySet().iterator(); tagit.hasNext();) {
+ TagDescriptor tag=tagit.next();
+ Set<TagState> 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<ClassDescriptor> cdit=fsresults.keySet().iterator(); cdit.hasNext();) {
+ ClassDescriptor cd=cdit.next();
+ Set<TagState> 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<FlagState> flagset=ts.getFS();
- for(Iterator<FlagState> fsit=flagset.iterator();fsit.hasNext();) {
- FlagState fs=fsit.next();
- FlagTagState fts=new FlagTagState(ts, fs);
- for(int i=0;i<td.numParameters();i++) {
- System.out.println("Trying to enqueue "+td);
- if (canEnqueue(td, i, fs)) {
- System.out.println("Enqueued");
- TaskQueueIterator tqi=tq.enqueue(i, fts);
- while(tqi.hasNext()) {
- System.out.println("binding");
- processBinding(tqi);
- tqi.next();
- }
- }
- }
+ }
+
+ private void processTask(TaskDescriptor td, TaskQueue tq, TagState ts) {
+ Set<FlagState> flagset=ts.getFS();
+ for(Iterator<FlagState> fsit=flagset.iterator(); fsit.hasNext();) {
+ FlagState fs=fsit.next();
+ FlagTagState fts=new FlagTagState(ts, fs);
+ for(int i=0; i<td.numParameters(); i++) {
+ System.out.println("Trying to enqueue "+td);
+ if (canEnqueue(td, i, fs)) {
+ System.out.println("Enqueued");
+ TaskQueueIterator tqi=tq.enqueue(i, fts);
+ while(tqi.hasNext()) {
+ System.out.println("binding");
+ processBinding(tqi);
+ tqi.next();
+ }
}
+ }
}
+ }
- private void processBinding(TaskQueueIterator tqi) {
- TaskBinding tb=new TaskBinding(tqi);
- while(tb.hasNext()) {
- doAnalysis(tb);
- tb.next();
- }
+ private void processBinding(TaskQueueIterator tqi) {
+ TaskBinding tb=new TaskBinding(tqi);
+ while(tb.hasNext()) {
+ doAnalysis(tb);
+ tb.next();
}
-
- private Hashtable<TempDescriptor, Wrapper> computeInitialState(Hashtable<FlatNode, Hashtable<TempDescriptor, Wrapper>> maintable, FlatNode fn) {
- Hashtable<TempDescriptor, Wrapper> table=new Hashtable<TempDescriptor, Wrapper>();
- Hashtable<TagWrapper,TagWrapper> tagtable=new Hashtable<TagWrapper, TagWrapper>();
- for(int i=0;i<fn.numPrev();i++) {
- FlatNode fnprev=fn.getPrev(i);
- Hashtable<TempDescriptor, Wrapper> prevtable=maintable.get(fn);
-
- //Iterator through the Tags
- for(Iterator<TempDescriptor> 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<TagState> 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<TempDescriptor> 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<TagWrapper> tagit=prevobj.tags.iterator();tagit.hasNext();) {
- TagWrapper tprev=tagit.next();
- TagWrapper t=tagtable.get(tprev);
- currobj.tags.add(t);
- }
- for(Iterator<FlagState> flagit=prevobj.fs.iterator();flagit.hasNext();) {
- FlagState fs=flagit.next();
- currobj.fs.add(fs);
- }
- }
- }
- return table;
- }
-
- private void processFlatFlag(FlatFlagActionNode fn, Hashtable<TempDescriptor, Wrapper> 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<FlagState> newstate=new HashSet<FlagState>();
- Hashtable<FlagState, FlagState> flagmap=new Hashtable<FlagState, FlagState>();
- for(Iterator<FlagState> 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<TagWrapper> tagit=ow.tags.iterator();tagit.hasNext();) {
- TagWrapper tw=tagit.next();
- HashSet<TagState> newstates=new HashSet<TagState>();
- for(Iterator<TagState> tgit=tw.ts.iterator();tgit.hasNext();) {
- TagState ts=tgit.next();
- for(Iterator<FlagState> 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<tsarray.length;i++) {
- TagState ts2=canonical(tsarray[i]);
- TagState tsarray2[]=ts2.addnewFS(flagmap.get(fs));
- for(int j=0;j<tsarray2.length;j++)
- newstates.add(canonical(tsarray2[j]));
- }
- }
- }
- }
- }
- 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;
+ }
+
+ private Hashtable<TempDescriptor, Wrapper> computeInitialState(Hashtable<FlatNode, Hashtable<TempDescriptor, Wrapper>> maintable, FlatNode fn) {
+ Hashtable<TempDescriptor, Wrapper> table=new Hashtable<TempDescriptor, Wrapper>();
+ Hashtable<TagWrapper,TagWrapper> tagtable=new Hashtable<TagWrapper, TagWrapper>();
+ for(int i=0; i<fn.numPrev(); i++) {
+ FlatNode fnprev=fn.getPrev(i);
+ Hashtable<TempDescriptor, Wrapper> prevtable=maintable.get(fn);
+
+ //Iterator through the Tags
+ for(Iterator<TempDescriptor> 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<TagState> 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<FlagState> newfsstates=new HashSet<FlagState>();
- Hashtable<FlagState, FlagState[]> flagmap=new Hashtable<FlagState, FlagState[]>();
- //Change the flag states
- for(Iterator<FlagState> 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<TempDescriptor> 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<TagWrapper> tagit=ow.tags.iterator();tagit.hasNext();) {
- TagWrapper tw=tagit.next();
- HashSet<TagState> newstates=new HashSet<TagState>();
- for(Iterator<TagState> tgit=tw.ts.iterator();tgit.hasNext();) {
- TagState ts=tgit.next();
- for(Iterator<FlagState> flagit=ts.getFS().iterator();flagit.hasNext();) {
- FlagState fs=flagit.next();
- if (flagmap.containsKey(fs)) {
- FlagState[] fmap=flagmap.get(fs);
- for(int i=0;i<fmap.length;i++) {
- FlagState fsnew=fmap[i];
- if (fsnew.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 j=0;j<tsarray.length;j++) {
- TagState ts2=canonical(tsarray[j]);
- TagState tsarray2[]=ts2.addnewFS(fsnew);
- for(int k=0;k<tsarray2.length;k++)
- newstates.add(canonical(tsarray2[k]));
- }
- }
- }
- }
- }
- }
- tw.ts=newstates;
+ ObjWrapper currobj=(ObjWrapper) table.get(tmp);
+ assert(currobj.initfs.equals(prevobj.initfs));
+ for(Iterator<TagWrapper> tagit=prevobj.tags.iterator(); tagit.hasNext();) {
+ TagWrapper tprev=tagit.next();
+ TagWrapper t=tagtable.get(tprev);
+ currobj.tags.add(t);
}
-
- {
- HashSet<TagState> newstates=new HashSet<TagState>();
- for(Iterator<TagState> tgit=twnew.ts.iterator();tgit.hasNext();) {
- TagState ts=tgit.next();
- for(Iterator<FlagState> 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<tsarray2.length;j++)
- newstates.add(canonical(tsarray2[j]));
- }
- }
- twnew.ts=newstates;
+ for(Iterator<FlagState> 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<TempDescriptor, Wrapper> table) {
- //Process clears first
- for(Iterator<TempTagPair> 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<TempFlagPair> 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<TempDescriptor, Wrapper> 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<FlagState> newstate=new HashSet<FlagState>();
+ Hashtable<FlagState, FlagState> flagmap=new Hashtable<FlagState, FlagState>();
+ for(Iterator<FlagState> 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<TempDescriptor, Wrapper> 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<TagWrapper> tagit=ow.tags.iterator(); tagit.hasNext();) {
+ TagWrapper tw=tagit.next();
+ HashSet<TagState> newstates=new HashSet<TagState>();
+ for(Iterator<TagState> tgit=tw.ts.iterator(); tgit.hasNext();) {
+ TagState ts=tgit.next();
+ for(Iterator<FlagState> 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<tsarray.length; i++) {
+ TagState ts2=canonical(tsarray[i]);
+ TagState tsarray2[]=ts2.addnewFS(flagmap.get(fs));
+ for(int j=0; j<tsarray2.length; j++)
+ newstates.add(canonical(tsarray2[j]));
+ }
}
+ }
}
- 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<TempFlagPair> 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<FlagState> 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<FlagState> newfsstates=new HashSet<FlagState>();
+ Hashtable<FlagState, FlagState[]> flagmap=new Hashtable<FlagState, FlagState[]>();
+ //Change the flag states
+ for(Iterator<FlagState> 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<TagWrapper> tagit=ow.tags.iterator(); tagit.hasNext();) {
+ TagWrapper tw=tagit.next();
+ HashSet<TagState> newstates=new HashSet<TagState>();
+ for(Iterator<TagState> tgit=tw.ts.iterator(); tgit.hasNext();) {
+ TagState ts=tgit.next();
+ for(Iterator<FlagState> flagit=ts.getFS().iterator(); flagit.hasNext();) {
+ FlagState fs=flagit.next();
+ if (flagmap.containsKey(fs)) {
+ FlagState[] fmap=flagmap.get(fs);
+ for(int i=0; i<fmap.length; i++) {
+ FlagState fsnew=fmap[i];
+ if (fsnew.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 j=0; j<tsarray.length; j++) {
+ TagState ts2=canonical(tsarray[j]);
+ TagState tsarray2[]=ts2.addnewFS(fsnew);
+ for(int k=0; k<tsarray2.length; k++)
+ newstates.add(canonical(tsarray2[k]));
+ }
+ }
}
+ }
}
+ }
+ tw.ts=newstates;
}
- private void processFlatTag(FlatTagDeclaration fn, Hashtable<TempDescriptor, Wrapper> table, TaskDescriptor td) {
- TempDescriptor tmp=fn.getDst();
- if (table.containsKey(tmp)) {
- recordtagchange((TagWrapper)table.get(tmp), td);
+ {
+ HashSet<TagState> newstates=new HashSet<TagState>();
+ for(Iterator<TagState> tgit=twnew.ts.iterator(); tgit.hasNext();) {
+ TagState ts=tgit.next();
+ for(Iterator<FlagState> 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<tsarray2.length; j++)
+ newstates.add(canonical(tsarray2[j]));
}
- TagDescriptor tag=fn.getType();
- TagState ts=canonical(new TagState(tag));
- TagWrapper tw=new TagWrapper(ts);
- tw.initts=null;
- table.put(tmp, tw);
+ }
+ twnew.ts=newstates;
}
- private void addresult(TagDescriptor td, TagState ts) {
- if (!tsresults.containsKey(td))
- tsresults.put(td, new HashSet<TagState>());
- 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<TempDescriptor, Wrapper> table) {
+ //Process clears first
+ for(Iterator<TempTagPair> 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<TagState>());
- fsresults.get(cd).add(ts);
+ //Do the flags next
+ for(Iterator<TempFlagPair> 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<TagState> 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<TempDescriptor, Wrapper> 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<TempFlagPair> 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<FlagState> 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<TagWrapper> twit=ow.tags.iterator();twit.hasNext();) {
- TagWrapper tw=twit.next();
- recordtagchange(tw, td);
+ private void processFlatTag(FlatTagDeclaration fn, Hashtable<TempDescriptor, Wrapper> 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<TagState>());
+ tsresults.get(td).add(ts);
+ }
+
+ private void addresult(ClassDescriptor cd, TagState ts) {
+ if (!fsresults.containsKey(cd))
+ fsresults.put(cd, new HashSet<TagState>());
+ fsresults.get(cd).add(ts);
+ }
+
+ public void recordtagchange(TagWrapper tw, TaskDescriptor td) {
+ TagState init=tw.initts;
+ for(Iterator<TagState> 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<TempDescriptor, Wrapper> table) {
- //Do nothing for now
+ private void recordobj(ObjWrapper ow, TaskDescriptor td) {
+ for(Iterator<TagWrapper> twit=ow.tags.iterator(); twit.hasNext();) {
+ TagWrapper tw=twit.next();
+ recordtagchange(tw, td);
}
-
- private void processFlatReturnNode(FlatReturnNode fr, Hashtable<TempDescriptor, Wrapper> table, TaskDescriptor td) {
- for(Iterator<TempDescriptor> 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<TempDescriptor, Wrapper> table) {
+ //Do nothing for now
+ }
+
+ private void processFlatReturnNode(FlatReturnNode fr, Hashtable<TempDescriptor, Wrapper> table, TaskDescriptor td) {
+ for(Iterator<TempDescriptor> 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<TempDescriptor, Wrapper> table1, Hashtable<TempDescriptor, Wrapper> table2) {
- Hashtable<Wrapper, Wrapper> emap=new Hashtable<Wrapper, Wrapper>();
+ private boolean equivalent(Hashtable<TempDescriptor, Wrapper> table1, Hashtable<TempDescriptor, Wrapper> table2) {
+ Hashtable<Wrapper, Wrapper> emap=new Hashtable<Wrapper, Wrapper>();
- if (table1.keySet().size()!=table2.keySet().size())
- return false;
+ if (table1.keySet().size()!=table2.keySet().size())
+ return false;
- for(Iterator<TempDescriptor> 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<TempDescriptor> 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<TagWrapper> twit=t1.tags.iterator();twit.hasNext();) {
- TagWrapper tw1=twit.next();
- if (!t2.tags.contains(emap.get(tw1)))
- return false;
- }
- }
- }
- return true;
+ for(Iterator<TempDescriptor> 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<FlatNode, Hashtable<TempDescriptor, Wrapper>> wtable=new Hashtable<FlatNode, Hashtable<TempDescriptor, Wrapper>>();
- wtable.put(fm, buildinittable(tb, fm));
- HashSet<FlatNode> visited=new HashSet<FlatNode>();
- HashSet<FlatNode> tovisit=new HashSet<FlatNode>();
- tovisit.add(fm.getNext(0));
- while(!tovisit.isEmpty()) {
- FlatNode fn=tovisit.iterator().next();
- tovisit.remove(fn);
- visited.add(fn);
- Hashtable<TempDescriptor, Wrapper> 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<fn.numNext();i++) {
- tovisit.add(fn.getNext(i));
- }
- } else {
- for(int i=0;i<fn.numNext();i++) {
- if (!visited.contains(fn.getNext(i)))
- tovisit.add(fn.getNext(i));
- }
- }
+ for(Iterator<TempDescriptor> 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<TagWrapper> twit=t1.tags.iterator(); twit.hasNext();) {
+ TagWrapper tw1=twit.next();
+ if (!t2.tags.contains(emap.get(tw1)))
+ return false;
}
-
+ }
}
-
- private Hashtable<TempDescriptor, Wrapper> buildinittable(TaskBinding tb, FlatMethod fm) {
- Hashtable<TempDescriptor, Wrapper> table=new Hashtable<TempDescriptor, Wrapper>();
- Vector<TempDescriptor> tagtmps=tb.tqi.tq.tags;
- for(int i=0;i<tagtmps.size();i++) {
- TempDescriptor tmp=tagtmps.get(i);
- table.put(tmp, tb.getTag(tmp));
+ return true;
+ }
+
+ private void doAnalysis(TaskBinding tb) {
+ TaskDescriptor td=tb.tqi.tq.getTask();
+ FlatMethod fm=state.getMethodFlat(td);
+ Hashtable<FlatNode, Hashtable<TempDescriptor, Wrapper>> wtable=new Hashtable<FlatNode, Hashtable<TempDescriptor, Wrapper>>();
+ wtable.put(fm, buildinittable(tb, fm));
+ HashSet<FlatNode> visited=new HashSet<FlatNode>();
+ HashSet<FlatNode> tovisit=new HashSet<FlatNode>();
+ tovisit.add(fm.getNext(0));
+ while(!tovisit.isEmpty()) {
+ FlatNode fn=tovisit.iterator().next();
+ tovisit.remove(fn);
+ visited.add(fn);
+ Hashtable<TempDescriptor, Wrapper> 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<fn.numNext(); i++) {
+ tovisit.add(fn.getNext(i));
}
- for(int i=0;i<fm.numParameters();i++) {
- TempDescriptor tmp=fm.getParameter(i);
- table.put(tmp, tb.getParameter(i));
+ } else {
+ for(int i=0; i<fn.numNext(); i++) {
+ if (!visited.contains(fn.getNext(i)))
+ tovisit.add(fn.getNext(i));
}
- return table;
+ }
}
- /*
- method summary:
- new flag states created
- new tag states created
- flag states bound to tag parameters
- */
-
- public boolean canEnqueue(TaskDescriptor td, int paramnum, FlagState fs) {
- return typeutil.isSuperorType(td.getParamType(paramnum).getClassDesc(),fs.getClassDescriptor())&&
- isTaskTrigger_flag(td.getFlag(td.getParameter(paramnum)),fs)&&
- isTaskTrigger_tag(td.getTag(td.getParameter(paramnum)),fs);
- }
+ }
- private 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;
- }
- }
-
-
- private static boolean isTaskTrigger_tag(TagExpressionList tel, FlagState fs){
- if (tel!=null){
- for (int i=0;i<tel.numTags() ; i++){
- switch (fs.getTagCount(tel.getType(i))){
- case FlagState.ONETAG:
- case FlagState.MULTITAGS:
- break;
- case FlagState.NOTAGS:
- return false;
- }
- }
- }
- return true;
+ private Hashtable<TempDescriptor, Wrapper> buildinittable(TaskBinding tb, FlatMethod fm) {
+ Hashtable<TempDescriptor, Wrapper> table=new Hashtable<TempDescriptor, Wrapper>();
+ Vector<TempDescriptor> tagtmps=tb.tqi.tq.tags;
+ for(int i=0; i<tagtmps.size(); i++) {
+ TempDescriptor tmp=tagtmps.get(i);
+ table.put(tmp, tb.getTag(tmp));
}
-
- TagState createInitialState() {
- ClassDescriptor startupobject=typeutil.getClass(TypeUtil.StartupClass);
- FlagDescriptor fd=(FlagDescriptor)startupobject.getFlagTable().get(FlagDescriptor.InitialFlag);
- FlagState fsstartup=(new FlagState(startupobject)).setFlag(fd,true);
- fsstartup.setAsSourceNode();
- fsstartup=canonical(fsstartup);
- TagState ts=new TagState(startupobject);
- TagState[] tsarray=ts.addFS(fsstartup);
- return canonical(tsarray[0]);
+ for(int i=0; i<fm.numParameters(); i++) {
+ TempDescriptor tmp=fm.getParameter(i);
+ table.put(tmp, tb.getParameter(i));
}
-
- FlagState[] canonical(FlagState[] fs) {
- FlagState[] fsarray=new FlagState[fs.length];
- for(int i=0;i<fs.length;i++)
- fsarray[i]=canonical(fs[i]);
- return fsarray;
- }
-
- FlagState canonical(FlagState fs) {
- return fs;
- }
-
- TagState canonical(TagState ts) {
- return ts;
+ return table;
+ }
+
+ /*
+ method summary:
+ new flag states created
+ new tag states created
+ flag states bound to tag parameters
+ */
+
+ public boolean canEnqueue(TaskDescriptor td, int paramnum, FlagState fs) {
+ return typeutil.isSuperorType(td.getParamType(paramnum).getClassDesc(),fs.getClassDescriptor())&&
+ isTaskTrigger_flag(td.getFlag(td.getParameter(paramnum)),fs)&&
+ isTaskTrigger_tag(td.getTag(td.getParameter(paramnum)),fs);
+ }
+
+ private 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;
+ }
+ }
+
+
+ private static boolean isTaskTrigger_tag(TagExpressionList tel, FlagState fs) {
+ if (tel!=null){
+ for (int i=0; i<tel.numTags() ; i++){
+ switch (fs.getTagCount(tel.getType(i))){
+ case FlagState.ONETAG:
+ case FlagState.MULTITAGS:
+ break;
+
+ case FlagState.NOTAGS:
+ return false;
+ }
+ }
}
+ return true;
+ }
+
+ TagState createInitialState() {
+ ClassDescriptor startupobject=typeutil.getClass(TypeUtil.StartupClass);
+ FlagDescriptor fd=(FlagDescriptor)startupobject.getFlagTable().get(FlagDescriptor.InitialFlag);
+ FlagState fsstartup=(new FlagState(startupobject)).setFlag(fd,true);
+ fsstartup.setAsSourceNode();
+ fsstartup=canonical(fsstartup);
+ TagState ts=new TagState(startupobject);
+ TagState[] tsarray=ts.addFS(fsstartup);
+ return canonical(tsarray[0]);
+ }
+
+ FlagState[] canonical(FlagState[] fs) {
+ FlagState[] fsarray=new FlagState[fs.length];
+ for(int i=0; i<fs.length; i++)
+ fsarray[i]=canonical(fs[i]);
+ return fsarray;
+ }
+
+ FlagState canonical(FlagState fs) {
+ return fs;
+ }
+
+ TagState canonical(TagState ts) {
+ return ts;
+ }
}
public class BarrierServer extends Thread {
- int numthreads;
- boolean done;
+ int numthreads;
+ boolean done;
- public BarrierServer(int n) {
- numthreads=n;
- done=false;
+ public BarrierServer(int n) {
+ numthreads=n;
+ done=false;
+ }
+
+ public void run() {
+ int n;
+ ServerSocket ss=new ServerSocket(2000);
+ atomic {
+ n=numthreads;
+ done=true;
}
-
- public void run() {
- int n;
- ServerSocket ss=new ServerSocket(2000);
- atomic {
- n=numthreads;
- done=true;
- }
- Socket ar[]=new Socket[n];
- for(int i=0;i<n;i++) {
- ar[i]=ss.accept();
- }
-
- while(true) {
- for(int j=0;j<n;j++) {
- Socket s=ar[j];
- byte b[]=new byte[1];
- while(s.read(b)!=1) {
- ;
- }
- }
- byte b[]=new byte[1];
- b[0]= (byte) 'A';
- for(int j=0;j<n;j++)
- ar[j].write(b);
+ Socket ar[]=new Socket[n];
+ for(int i=0; i<n; i++) {
+ ar[i]=ss.accept();
+ }
+
+ while(true) {
+ for(int j=0; j<n; j++) {
+ Socket s=ar[j];
+ byte b[]=new byte[1];
+ while(s.read(b)!=1) {
+ ;
}
+ }
+ byte b[]=new byte[1];
+ b[0]= (byte) 'A';
+ for(int j=0; j<n; j++)
+ ar[j].write(b);
}
+ }
}
public class Barrier {
- Socket s;
- public Barrier(String name) {
- s=new Socket(name, 2000);
- }
-
- public static void enterBarrier(Barrier barr) {
- byte b[]=new byte[1];
- b[0]=(byte)'A';
- barr.s.write(b);
- while(barr.s.read(b)!=1) {
+ Socket s;
+ public Barrier(String name) {
+ s=new Socket(name, 2000);
+ }
+
+ public static void enterBarrier(Barrier barr) {
+ byte b[]=new byte[1];
+ b[0]=(byte)'A';
+ barr.s.write(b);
+ while(barr.s.read(b)!=1) {
;
}
- }
+ }
}
public class BufferedInputStream extends InputStream {
- InputStream in;
- public BufferedInputStream(InputStream in) {
- this.in=in;
- }
- public int read() {
- return in.read();
- }
+ InputStream in;
+ public BufferedInputStream(InputStream in) {
+ this.in=in;
+ }
+ public int read() {
+ return in.read();
+ }
- public int read(byte[] b) {
- return in.read(b);
- }
+ public int read(byte[] b) {
+ return in.read(b);
+ }
- public void close() {
- in.close();
- }
+ public void close() {
+ in.close();
+ }
}
public class BufferedOutputStream extends OutputStream {
- OutputStream o;
+ OutputStream o;
- public BufferedOutputStream(OutputStream o) {
- this.o=o;
- }
+ public BufferedOutputStream(OutputStream o) {
+ this.o=o;
+ }
- public void write(byte []b, int off, int len) {
- o.write(b, off, len);
- }
+ public void write(byte [] b, int off, int len) {
+ o.write(b, off, len);
+ }
- public void flush() {
- o.flush();
- }
+ public void flush() {
+ o.flush();
+ }
- public void close() {
- o.close();
- }
+ public void close() {
+ o.close();
+ }
}
public class BufferedWriter extends Writer {
- Writer out;
+ Writer out;
- public BufferedWriter(Writer out) {
- this.out=out;
- }
+ public BufferedWriter(Writer out) {
+ this.out=out;
+ }
- public void write(String s) {
- out.write(s);
- }
+ public void write(String s) {
+ out.write(s);
+ }
- public void newLine() {
- out.write("\n");
- }
+ public void newLine() {
+ out.write("\n");
+ }
- public void flush() {
- out.flush();
- }
+ public void flush() {
+ out.flush();
+ }
- public void close() {
- out.close();
- }
+ public void close() {
+ out.close();
+ }
}
public class Character {
- public static int digit(char ch, int radix) {
- if (ch>='0'&&ch<='9')
- return ch-'0';
- else if (ch>='a'&&ch<='z') {
- int val=(ch-'a')+10;
- if (val<radix)
- return val;
- } else if (ch>='A'&&ch<='Z') {
- int val=(ch-'A')+10;
- if (val<radix)
- return val;
- }
- return -1;
+ public static int digit(char ch, int radix) {
+ if (ch>='0'&&ch<='9')
+ return ch-'0';
+ else if (ch>='a'&&ch<='z') {
+ int val=(ch-'a')+10;
+ if (val<radix)
+ return val;
+ } else if (ch>='A'&&ch<='Z') {
+ int val=(ch-'A')+10;
+ if (val<radix)
+ return val;
}
+ return -1;
+ }
}
public class Date {
- public Date() {}
+ public Date() {
+ }
+
-
}
public class File {
- String path;
+ String path;
- public File(String path) {
- this.path=path;
- }
+ public File(String path) {
+ this.path=path;
+ }
- String getPath() {
- return path;
- }
+ String getPath() {
+ return path;
+ }
- long length() {
- return nativeLength(path.getBytes());
- }
+ long length() {
+ return nativeLength(path.getBytes());
+ }
- private static native long nativeLength(byte[] pathname);
+ private static native long nativeLength(byte[] pathname);
}
public class FileInputStream extends InputStream {
- private int fd;
+ private int fd;
- public FileInputStream(String pathname) {
- fd=nativeOpen(pathname.getBytes());
- }
+ public FileInputStream(String pathname) {
+ fd=nativeOpen(pathname.getBytes());
+ }
- public FileInputStream(File path) {
- fd=nativeOpen(path.getPath().getBytes());
- }
- public int getfd() {
- return fd;
- }
+ public FileInputStream(File path) {
+ fd=nativeOpen(path.getPath().getBytes());
+ }
+ public int getfd() {
+ return fd;
+ }
- private static native int nativeOpen(byte[] filename);
- private static native int nativeRead(int fd, byte[] array, int numBytes);
- private static native void nativeClose(int fd);
-
- public int read() {
- byte b[]=new byte[1];
- int retval=read(b);
- if (retval==-1)
- return -1;
- return b[0];
- }
+ private static native int nativeOpen(byte[] filename);
+ private static native int nativeRead(int fd, byte[] array, int numBytes);
+ private static native void nativeClose(int fd);
- public int read(byte[] b) {
- return nativeRead(fd, b, b.length);
- }
+ public int read() {
+ byte b[]=new byte[1];
+ int retval=read(b);
+ if (retval==-1)
+ return -1;
+ return b[0];
+ }
- public void close() {
- nativeClose(fd);
- }
+ public int read(byte[] b) {
+ return nativeRead(fd, b, b.length);
+ }
+
+ public void close() {
+ nativeClose(fd);
+ }
}
public class FileOutputStream extends OutputStream {
- private int fd;
-
- public FileOutputStream(String pathname) {
- fd=nativeOpen(pathname.getBytes());
- }
-
- public FileOutputStream(String pathname, boolean append) {
- if(append)
- fd=nativeAppend(pathname.getBytes());
- else
- fd=nativeOpen(pathname.getBytes());
- }
-
- public FileOutputStream(String pathname, int mode) {
- if(mode==0)
- fd=nativeAppend(pathname.getBytes());
- if(mode==1)
- fd=nativeOpen(pathname.getBytes());
- }
-
- public FileOutputStream(File path) {
- fd=nativeOpen(path.getPath().getBytes());
- }
-
- public FileOutputStreamOpen(String pathname) {
- fd = nativeOpen(pathname.getBytes());
- }
-
- private static native int nativeOpen(byte[] filename);
- private static native int nativeAppend(byte[] filename);
- private static native void nativeWrite(int fd, byte[] array, int off, int len);
- private static native void nativeClose(int fd);
- private static native void nativeFlush(int fd);
-
- public void write(int ch) {
- byte b[]=new byte[1];
- b[0]=(byte)ch;
- write(b);
- }
-
- public void write(byte[] b) {
- nativeWrite(fd, b, 0, b.length);
- }
-
- public void write(byte[] b, int index, int len) {
- nativeWrite(fd, b, index, len);
- }
-
- public void flush() {
- nativeFlush(fd);
- }
-
- public void close() {
- nativeClose(fd);
- }
+ private int fd;
+
+ public FileOutputStream(String pathname) {
+ fd=nativeOpen(pathname.getBytes());
+ }
+
+ public FileOutputStream(String pathname, boolean append) {
+ if(append)
+ fd=nativeAppend(pathname.getBytes());
+ else
+ fd=nativeOpen(pathname.getBytes());
+ }
+
+ public FileOutputStream(String pathname, int mode) {
+ if(mode==0)
+ fd=nativeAppend(pathname.getBytes());
+ if(mode==1)
+ fd=nativeOpen(pathname.getBytes());
+ }
+
+ public FileOutputStream(File path) {
+ fd=nativeOpen(path.getPath().getBytes());
+ }
+
+ public FileOutputStreamOpen(String pathname) {
+ fd = nativeOpen(pathname.getBytes());
+ }
+
+ private static native int nativeOpen(byte[] filename);
+ private static native int nativeAppend(byte[] filename);
+ private static native void nativeWrite(int fd, byte[] array, int off, int len);
+ private static native void nativeClose(int fd);
+ private static native void nativeFlush(int fd);
+
+ public void write(int ch) {
+ byte b[]=new byte[1];
+ b[0]=(byte)ch;
+ write(b);
+ }
+
+ public void write(byte[] b) {
+ nativeWrite(fd, b, 0, b.length);
+ }
+
+ public void write(byte[] b, int index, int len) {
+ nativeWrite(fd, b, index, len);
+ }
+
+ public void flush() {
+ nativeFlush(fd);
+ }
+
+ public void close() {
+ nativeClose(fd);
+ }
}
public class FileWriter extends OutputStreamWriter {
- public FileWriter(String file, boolean append) {
- super(new FileOutputStream(file, append));
- }
+ public FileWriter(String file, boolean append) {
+ super(new FileOutputStream(file, append));
+ }
}
class HashEntry {
- public HashEntry() {}
- Object key;
- Object value;
- HashEntry next;
+ public HashEntry() {
+ }
+ Object key;
+ Object value;
+ HashEntry next;
}
public class HashMap {
- HashEntry[] table;
- float loadFactor;
- int numItems;
+ HashEntry[] table;
+ float loadFactor;
+ int numItems;
- public HashMap() {
- init(16, 0.75f);
- }
+ public HashMap() {
+ init(16, 0.75f);
+ }
- public HashMap(int initialCapacity) {
- init(initialCapacity, 0.75f);
- }
-
- public HashMap(int initialCapacity, float loadFactor) {
- init(initialCapacity, loadFactor);
- }
-
- private void init(int initialCapacity, float loadFactor) {
- table=new HashEntry[initialCapacity];
- this.loadFactor=loadFactor;
- this.numItems=0;
- }
+ public HashMap(int initialCapacity) {
+ init(initialCapacity, 0.75f);
+ }
- private int hash(Object o) {
- if (o==null)
- return 0;
- int value=o.hashCode()%table.length;
- if (value<0)
- return -value;
- return value;
- }
+ public HashMap(int initialCapacity, float loadFactor) {
+ init(initialCapacity, loadFactor);
+ }
- void resize() {
- int newCapacity=2*table.length+1;
- HashEntry[] oldtable=table;
- this.table=new HashEntry[newCapacity];
+ private void init(int initialCapacity, float loadFactor) {
+ table=new HashEntry[initialCapacity];
+ this.loadFactor=loadFactor;
+ this.numItems=0;
+ }
- for(int i=0;i<oldtable.length;i++) {
- HashEntry e=oldtable[i];
- while(e!=null) {
- HashEntry next=e.next;
- int bin=hash(e.key);
- e.next=table[bin];
- table[bin]=e;
- e=next;
- }
- }
- }
+ private int hash(Object o) {
+ if (o==null)
+ return 0;
+ int value=o.hashCode()%table.length;
+ if (value<0)
+ return -value;
+ return value;
+ }
- public boolean isEmpty() {
- return numItems==0;
- }
+ void resize() {
+ int newCapacity=2*table.length+1;
+ HashEntry[] oldtable=table;
+ this.table=new HashEntry[newCapacity];
- public int size() {
- return numItems;
+ for(int i=0; i<oldtable.length; i++) {
+ HashEntry e=oldtable[i];
+ while(e!=null) {
+ HashEntry next=e.next;
+ int bin=hash(e.key);
+ e.next=table[bin];
+ table[bin]=e;
+ e=next;
+ }
}
+ }
- /* 0=keys, 1=values */
- public HashMapIterator iterator(int type) {
- return new HashMapIterator(this, type);
- }
+ public boolean isEmpty() {
+ return numItems==0;
+ }
+
+ public int size() {
+ return numItems;
+ }
- Object remove(Object key) {
- int bin=hash(key);
- HashEntry ptr=table[bin];
- if (ptr!=null) {
- if (ptr.key.equals(key)) {
- table[bin]=ptr.next;
- numItems--;
- return ptr.value;
- }
- while(ptr.next!=null) {
- if (ptr.next.key.equals(key)) {
- Object oldvalue=ptr.value;
- ptr.next=ptr.next.next;
- numItems--;
- return oldvalue;
- }
- ptr=ptr.next;
- }
+ /* 0=keys, 1=values */
+ public HashMapIterator iterator(int type) {
+ return new HashMapIterator(this, type);
+ }
+
+ Object remove(Object key) {
+ int bin=hash(key);
+ HashEntry ptr=table[bin];
+ if (ptr!=null) {
+ if (ptr.key.equals(key)) {
+ table[bin]=ptr.next;
+ numItems--;
+ return ptr.value;
+ }
+ while(ptr.next!=null) {
+ if (ptr.next.key.equals(key)) {
+ Object oldvalue=ptr.value;
+ ptr.next=ptr.next.next;
+ numItems--;
+ return oldvalue;
}
- return null;
+ ptr=ptr.next;
+ }
}
+ return null;
+ }
- Object get(Object key) {
- int bin=hash(key);
- HashEntry ptr=table[bin];
- while(ptr!=null) {
- if (ptr.key.equals(key)) {
- return ptr.value;
- }
- ptr=ptr.next;
- }
- return null;
+ Object get(Object key) {
+ int bin=hash(key);
+ HashEntry ptr=table[bin];
+ while(ptr!=null) {
+ if (ptr.key.equals(key)) {
+ return ptr.value;
+ }
+ ptr=ptr.next;
}
+ return null;
+ }
- boolean containsKey(Object key) {
- int bin=hash(key);
- HashEntry ptr=table[bin];
- while(ptr!=null) {
- if (ptr.key.equals(key)) {
- return true;
- }
- ptr=ptr.next;
- }
- return false;
+ boolean containsKey(Object key) {
+ int bin=hash(key);
+ HashEntry ptr=table[bin];
+ while(ptr!=null) {
+ if (ptr.key.equals(key)) {
+ return true;
+ }
+ ptr=ptr.next;
}
+ return false;
+ }
- 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;
+ 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;
+ }
}
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((i<map.table.length)&&map.table[i]==null)
- i++;
- return (i<map.table.length);
- }
+ public boolean hasNext() {
+ if (he!=null&&he.next!=null)
+ return true;
+ int i=bin;
+ while((i<map.table.length)&&map.table[i]==null)
+ i++;
+ return (i<map.table.length);
+ }
- public Object next() {
- if (he!=null&&he.next!=null) {
- he=he.next;
- Object o;
- if (type==0)
- o=he.key;
- else
- o=he.value;
- return o;
- }
- while((bin<map.table.length)&&
- (map.table[bin]==null))
- bin++;
- if (bin<map.table.length) {
- he=map.table[bin++];
- Object o;
- if (type==0)
- o=he.key;
- else
- o=he.value;
- return o;
- } else System.error();
+ public Object next() {
+ if (he!=null&&he.next!=null) {
+ he=he.next;
+ Object o;
+ if (type==0)
+ o=he.key;
+ else
+ o=he.value;
+ return o;
}
+ while((bin<map.table.length)&&
+ (map.table[bin]==null))
+ bin++;
+ if (bin<map.table.length) {
+ he=map.table[bin++];
+ Object o;
+ if (type==0)
+ o=he.key;
+ else
+ o=he.value;
+ return o;
+ } else System.error();
+ }
}
public class HashSet {
- HashMap map;
- HashSet() {
- map=new HashMap();
- }
- HashSet(int initialCapacity) {
- map=new HashMap(initialCapacity);
- }
- HashSet(int initialCapacity, float loadFactor) {
- map=new HashMap(initialCapacity, loadFactor);
- }
- public boolean add(Object o) {
- return (map.put(o, this)==null);
- }
- public boolean remove(Object o) {
- return (map.remove(o)!=null);
- }
- public boolean isEmpty() {
- return map.isEmpty();
- }
- public boolean contains(Object o) {
- return map.containsKey(o);
- }
- public int size() {
- return map.size();
- }
- public HashMapIterator iterator() {
- return map.iterator(0);
- }
+ HashMap map;
+ HashSet() {
+ map=new HashMap();
+ }
+ HashSet(int initialCapacity) {
+ map=new HashMap(initialCapacity);
+ }
+ HashSet(int initialCapacity, float loadFactor) {
+ map=new HashMap(initialCapacity, loadFactor);
+ }
+ public boolean add(Object o) {
+ return (map.put(o, this)==null);
+ }
+ public boolean remove(Object o) {
+ return (map.remove(o)!=null);
+ }
+ public boolean isEmpty() {
+ return map.isEmpty();
+ }
+ public boolean contains(Object o) {
+ return map.containsKey(o);
+ }
+ public int size() {
+ return map.size();
+ }
+ public HashMapIterator iterator() {
+ return map.iterator(0);
+ }
}
public class InetAddress {
- String hostname;
- byte[] address;
+ String hostname;
+ byte[] address;
- public InetAddress(byte[] addr, String hostname) {
- this.hostname=hostname;
- this.address=addr;
- }
-
- public static InetAddress getByAddress(String host, byte[] addr) {
- return new InetAddress(addr, host);
- }
+ public InetAddress(byte[] addr, String hostname) {
+ this.hostname=hostname;
+ this.address=addr;
+ }
- public static InetAddress getByName(String hostname) {
- InetAddress[] addresses=getAllByName(hostname);
- return addresses[0];
- }
-
- public byte[] getAddress() {
- return address;
- }
+ public static InetAddress getByAddress(String host, byte[] addr) {
+ return new InetAddress(addr, host);
+ }
- public static InetAddress getLocalHost() {
- return getByName("localhost");
- }
+ public static InetAddress getByName(String hostname) {
+ InetAddress[] addresses=getAllByName(hostname);
+ return addresses[0];
+ }
- public boolean equals(InetAddress ia) {
- if (ia==null)
- return false;
- if (ia.address.length!=address.length)
- return false;
- for(int i=0;i<address.length;i++)
- if (ia.address[i]!=address[i])
- return false;
- return true;
- }
+ public byte[] getAddress() {
+ return address;
+ }
- public static InetAddress[] getAllByName(String hostname) {
- InetAddress[] addresses;
-
- byte[][] iplist = InetAddress.getHostByName(hostname.getBytes());
-
- addresses = new InetAddress[iplist.length];
-
- for (int i = 0; i < iplist.length; i++) {
- addresses[i] = new InetAddress(iplist[i], hostname);
- }
- return addresses;
- }
+ public static InetAddress getLocalHost() {
+ return getByName("localhost");
+ }
+
+ public boolean equals(InetAddress ia) {
+ if (ia==null)
+ return false;
+ if (ia.address.length!=address.length)
+ return false;
+ for(int i=0; i<address.length; i++)
+ if (ia.address[i]!=address[i])
+ return false;
+ return true;
+ }
+
+ public static InetAddress[] getAllByName(String hostname) {
+ InetAddress[] addresses;
- public static native byte[][] getHostByName(byte[] hostname);
+ byte[][] iplist = InetAddress.getHostByName(hostname.getBytes());
- public String toString() {
- String h=hostname+" ";
- for (int i=0;i<address.length;i++) {
- if (i>0)
- 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; i<address.length; i++) {
+ if (i>0)
+ h+=".";
+ h+=(int)address[i];
+ }
+ return h;
+ }
}
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");
+ }
}
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<str.length();i++) {
- byte b=chars[i];
- int val;
- if (b>='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<str.length(); i++) {
+ byte b=chars[i];
+ int val;
+ if (b>='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);
+ }
}
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);
}
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;
+ }
}
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;
+ }
}
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;
+ }
}
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;
+ }
}
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");
+ }
}
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();
+ }
}
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();
}
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();
}
public class Signal {
public Signal() {
}
- public native void nativeSigAction();
+ public native void nativeSigAction();
public void sigAction() {
nativeSigAction();
}
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();
+ }
}
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();
+ }
}
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();
+ }
}
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();
+ }
}
public class StartupObject {
- flag initialstate;
+ flag initialstate;
- String [] parameters;
+ String [] parameters;
}
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;i++)
- charstr[i]=str[i];
- this.value=charstr;
- this.count=str.length;
- this.offset=0;
- }
-
- public String(byte str[]) {
- char charstr[]=new char[str.length];
- for(int i=0;i<str.length;i++)
- charstr[i]=(char)str[i];
- this.value=charstr;
- this.count=str.length;
- this.offset=0;
- }
-
- public String(byte str[], int offset, int length) {
- if (length>(str.length-offset))
- length=str.length-offset;
- char charstr[]=new char[length];
- for(int i=0;i<length;i++)
- charstr[i]=(char)str[i+offset];
- this.value=charstr;
- this.count=length;
- this.offset=0;
- }
-
- public String(String str) {
- this.value=str.value;
- this.count=str.count;
- this.offset=str.offset;
- }
-
- public String(StringBuffer strbuf) {
- value=new char[strbuf.length()];
- count=strbuf.length();
- offset=0;
- for(int i=0;i<count;i++)
- value[i]=strbuf.value[i];
- }
-
- public boolean endsWith(String suffix) {
- return regionMatches(count - suffix.count, suffix, 0, suffix.count);
- }
-
-
- public String substring(int beginIndex) {
- return substring(beginIndex, this.count);
- }
-
- public String subString(int beginIndex, int endIndex) {
- return substring(beginIndex, endIndex);
- }
-
- public String substring(int beginIndex, int endIndex) {
- String str=new String();
- if (beginIndex>this.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;i<count;i++) {
- charstr[i]=value[i+offset];
- }
- for(int i=0;i<str.count;i++) {
- charstr[i+count]=str.value[i+str.offset];
- }
- return newstr;
- }
-
- public int lastindexOf(int ch, int fromIndex) {
- for(int i=fromIndex;i>0;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<count;i++) {
- char x=charAt(i);
- if (x==oldch)
- x=newch;
- buffer[i]=x;
- }
- return new String(buffer);
- }
-
- public String toUpperCase() {
- char[] buffer=new char[count];
- for(int i=0;i<count;i++) {
- char x=charAt(i);
- if (x>='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;i<count;i++)
- if (this.charAt(i)==ch)
- return i;
- return -1;
- }
-
- public int indexOf(String str) {
- return this.indexOf(str, 0);
- }
-
- public int indexOf(String str, int fromIndex) {
- if (fromIndex<0)
- fromIndex=0;
- for(int i=fromIndex;i<=(count-str.count);i++)
- if (regionMatches(i, str, 0, str.count))
- return i;
- return -1;
- }
-
- public int lastIndexOf(String str, int fromIndex) {
- int k=count-str.count;
- if (k>fromIndex)
- 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<len;i++)
- if (other.value[i+other.offset+ooffset]!=
- this.value[i+this.offset+toffset])
- return false;
- return true;
- }
-
- public char[] toCharArray() {
- char str[]=new char[count];
- for(int i=0;i<count;i++)
- str[i]=value[i+offset];
- return str;
- }
-
- public byte[] getBytes() {
- byte str[]=new byte[count];
- for(int i=0;i<count;i++)
- str[i]=(byte)value[i+offset];
- return str;
- }
-
- public int length() {
- return count;
- }
-
- public char charAt(int i) {
- return value[i+offset];
- }
-
- public String toString() {
- return this;
- }
-
- public static String valueOf(Object o) {
- if (o==null)
- return "null";
- else
- return o.toString();
- }
-
- public static String valueOf(boolean b) {
- if (b)
- return new String("true");
- else
- return new String("false");
- }
-
- public static String valueOf(char c) {
- char ar[]=new char[1];
- ar[0]=c;
- return new String(ar);
- }
-
- public static String valueOf(int x) {
- int length=0;
- int tmp;
- if (x<0)
- tmp=-x;
- else
- tmp=x;
- do {
- tmp=tmp/10;
- length=length+1;
- } while(tmp!=0);
-
- char chararray[];
- if (x<0)
- chararray=new char[length+1];
- else
- chararray=new char[length];
- int voffset;
- if (x<0) {
- chararray[0]='-';
- voffset=1;
- x=-x;
- } else
- voffset=0;
-
- do {
- chararray[--length+voffset]=(char)(x%10+'0');
- x=x/10;
- } while (length!=0);
- return new String(chararray);
- }
-
- public static String valueOf(long x) {
- int length=0;
- long tmp;
- if (x<0)
- tmp=-x;
- else
- tmp=x;
- do {
- tmp=tmp/10;
- length=length+1;
- } while(tmp!=0);
-
- char chararray[];
- if (x<0)
- chararray=new char[length+1];
- else
- chararray=new char[length];
- int voffset;
- if (x<0) {
- chararray[0]='-';
- voffset=1;
- x=-x;
- } else
- voffset=0;
-
- do {
- chararray[--length+voffset]=(char)(x%10+'0');
- x=x/10;
- } while (length!=0);
- return new String(chararray);
- }
-
- public int hashCode() {
- if (cachedHashcode!=0)
- return cachedHashcode;
- int hashcode=0;
- for(int i=0;i<count;i++)
- hashcode=hashcode*31+value[i+offset];
- cachedHashcode=hashcode;
- return hashcode;
- }
-
- public boolean equals(Object o) {
- if (o.getType()!=getType())
- return false;
- String s=(String)o;
- if (s.count!=count)
- return false;
- for(int i=0;i<count;i++) {
- if (s.value[i+s.offset]!=value[i+offset])
- return false;
- }
- return true;
- }
-
- public boolean equalsIgnoreCase(String s) {
- if (s.count!=count)
- return false;
- for(int i=0;i<count;i++) {
- char l=s.value[i+s.offset];
- char r=value[i+offset];
- if (l>='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; i++)
+ charstr[i]=str[i];
+ this.value=charstr;
+ this.count=str.length;
+ this.offset=0;
+ }
+
+ public String(byte str[]) {
+ char charstr[]=new char[str.length];
+ for(int i=0; i<str.length; i++)
+ charstr[i]=(char)str[i];
+ this.value=charstr;
+ this.count=str.length;
+ this.offset=0;
+ }
+
+ public String(byte str[], int offset, int length) {
+ if (length>(str.length-offset))
+ length=str.length-offset;
+ char charstr[]=new char[length];
+ for(int i=0; i<length; i++)
+ charstr[i]=(char)str[i+offset];
+ this.value=charstr;
+ this.count=length;
+ this.offset=0;
+ }
+
+ public String(String str) {
+ this.value=str.value;
+ this.count=str.count;
+ this.offset=str.offset;
+ }
+
+ public String(StringBuffer strbuf) {
+ value=new char[strbuf.length()];
+ count=strbuf.length();
+ offset=0;
+ for(int i=0; i<count; i++)
+ value[i]=strbuf.value[i];
+ }
+
+ public boolean endsWith(String suffix) {
+ return regionMatches(count - suffix.count, suffix, 0, suffix.count);
+ }
+
+
+ public String substring(int beginIndex) {
+ return substring(beginIndex, this.count);
+ }
+
+ public String subString(int beginIndex, int endIndex) {
+ return substring(beginIndex, endIndex);
+ }
+
+ public String substring(int beginIndex, int endIndex) {
+ String str=new String();
+ if (beginIndex>this.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; i<count; i++) {
+ charstr[i]=value[i+offset];
+ }
+ for(int i=0; i<str.count; i++) {
+ charstr[i+count]=str.value[i+str.offset];
+ }
+ return newstr;
+ }
+
+ public int lastindexOf(int ch, int fromIndex) {
+ for(int i=fromIndex; i>0; 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<count; i++) {
+ char x=charAt(i);
+ if (x==oldch)
+ x=newch;
+ buffer[i]=x;
+ }
+ return new String(buffer);
+ }
+
+ public String toUpperCase() {
+ char[] buffer=new char[count];
+ for(int i=0; i<count; i++) {
+ char x=charAt(i);
+ if (x>='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; i<count; i++)
+ if (this.charAt(i)==ch)
+ return i;
+ return -1;
+ }
+
+ public int indexOf(String str) {
+ return this.indexOf(str, 0);
+ }
+
+ public int indexOf(String str, int fromIndex) {
+ if (fromIndex<0)
+ fromIndex=0;
+ for(int i=fromIndex; i<=(count-str.count); i++)
+ if (regionMatches(i, str, 0, str.count))
+ return i;
+ return -1;
+ }
+
+ public int lastIndexOf(String str, int fromIndex) {
+ int k=count-str.count;
+ if (k>fromIndex)
+ 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<len; i++)
+ if (other.value[i+other.offset+ooffset]!=
+ this.value[i+this.offset+toffset])
+ return false;
+ return true;
+ }
+
+ public char[] toCharArray() {
+ char str[]=new char[count];
+ for(int i=0; i<count; i++)
+ str[i]=value[i+offset];
+ return str;
+ }
+
+ public byte[] getBytes() {
+ byte str[]=new byte[count];
+ for(int i=0; i<count; i++)
+ str[i]=(byte)value[i+offset];
+ return str;
+ }
+
+ public int length() {
+ return count;
+ }
+
+ public char charAt(int i) {
+ return value[i+offset];
+ }
+
+ public String toString() {
+ return this;
+ }
+
+ public static String valueOf(Object o) {
+ if (o==null)
+ return "null";
+ else
+ return o.toString();
+ }
+
+ public static String valueOf(boolean b) {
+ if (b)
+ return new String("true");
+ else
+ return new String("false");
+ }
+
+ public static String valueOf(char c) {
+ char ar[]=new char[1];
+ ar[0]=c;
+ return new String(ar);
+ }
+
+ public static String valueOf(int x) {
+ int length=0;
+ int tmp;
+ if (x<0)
+ tmp=-x;
+ else
+ tmp=x;
+ do {
+ tmp=tmp/10;
+ length=length+1;
+ } while(tmp!=0);
+
+ char chararray[];
+ if (x<0)
+ chararray=new char[length+1];
+ else
+ chararray=new char[length];
+ int voffset;
+ if (x<0) {
+ chararray[0]='-';
+ voffset=1;
+ x=-x;
+ } else
+ voffset=0;
+
+ do {
+ chararray[--length+voffset]=(char)(x%10+'0');
+ x=x/10;
+ } while (length!=0);
+ return new String(chararray);
+ }
+
+ public static String valueOf(long x) {
+ int length=0;
+ long tmp;
+ if (x<0)
+ tmp=-x;
+ else
+ tmp=x;
+ do {
+ tmp=tmp/10;
+ length=length+1;
+ } while(tmp!=0);
+
+ char chararray[];
+ if (x<0)
+ chararray=new char[length+1];
+ else
+ chararray=new char[length];
+ int voffset;
+ if (x<0) {
+ chararray[0]='-';
+ voffset=1;
+ x=-x;
+ } else
+ voffset=0;
+
+ do {
+ chararray[--length+voffset]=(char)(x%10+'0');
+ x=x/10;
+ } while (length!=0);
+ return new String(chararray);
+ }
+
+ public int hashCode() {
+ if (cachedHashcode!=0)
+ return cachedHashcode;
+ int hashcode=0;
+ for(int i=0; i<count; i++)
+ hashcode=hashcode*31+value[i+offset];
+ cachedHashcode=hashcode;
+ return hashcode;
+ }
+
+ public boolean equals(Object o) {
+ if (o.getType()!=getType())
+ return false;
+ String s=(String)o;
+ if (s.count!=count)
+ return false;
+ for(int i=0; i<count; i++) {
+ if (s.value[i+s.offset]!=value[i+offset])
+ return false;
+ }
+ return true;
+ }
+
+ public boolean equalsIgnoreCase(String s) {
+ if (s.count!=count)
+ return false;
+ for(int i=0; i<count; i++) {
+ char l=s.value[i+s.offset];
+ char r=value[i+offset];
+ if (l>='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;
+ }
}
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;i<count;i++)
- value[i]=str.value[i+str.offset];
- }
+ public StringBuffer(String str) {
+ value=new char[str.count+16]; //16 is DEFAULTSIZE
+ count=str.count;
+ for(int i=0; i<count; i++)
+ value[i]=str.value[i+str.offset];
+ }
- public StringBuffer() {
- value=new char[16];//16 is DEFAULTSIZE
- count=0;
- }
+ public StringBuffer() {
+ value=new char[16]; //16 is DEFAULTSIZE
+ count=0;
+ }
- public int length() {
- return count;
- }
+ public int length() {
+ return count;
+ }
- public int capacity() {
- return value.length;
- }
+ public int capacity() {
+ return value.length;
+ }
- public char charAt(int x) {
- return value[x];
- }
+ public char charAt(int x) {
+ return value[x];
+ }
- public StringBuffer append(char c) {
- return append(String.valueOf(c));
- }
+ public StringBuffer append(char c) {
+ return append(String.valueOf(c));
+ }
- public StringBuffer append(String s) {
- if ((s.count+count)>value.length) {
- // Need to allocate
- char newvalue[]=new char[s.count+count+16]; //16 is DEFAULTSIZE
- for(int i=0;i<count;i++)
- newvalue[i]=value[i];
- for(int i=0;i<s.count;i++)
- newvalue[i+count]=s.value[i+s.offset];
- value=newvalue;
- count+=s.count;
- } else {
- for(int i=0;i<s.count;i++) {
- value[i+count]=s.value[i+s.offset];
- }
- count+=s.count;
- }
- return this;
+ public StringBuffer append(String s) {
+ if ((s.count+count)>value.length) {
+ // Need to allocate
+ char newvalue[]=new char[s.count+count+16]; //16 is DEFAULTSIZE
+ for(int i=0; i<count; i++)
+ newvalue[i]=value[i];
+ for(int i=0; i<s.count; i++)
+ newvalue[i+count]=s.value[i+s.offset];
+ value=newvalue;
+ count+=s.count;
+ } else {
+ for(int i=0; i<s.count; i++) {
+ value[i+count]=s.value[i+s.offset];
+ }
+ count+=s.count;
}
+ return this;
+ }
- public StringBuffer append(StringBuffer s) {
- if ((s.count+count)>value.length) {
- // Need to allocate
- char newvalue[]=new char[s.count+count+16]; //16 is DEFAULTSIZE
- for(int i=0;i<count;i++)
- newvalue[i]=value[i];
- for(int i=0;i<s.count;i++)
- newvalue[i+count]=s.value[i];
- value=newvalue;
- count+=s.count;
- } else {
- for(int i=0;i<s.count;i++) {
- value[i+count]=s.value[i];
- }
- count+=s.count;
- }
- return this;
+ public StringBuffer append(StringBuffer s) {
+ if ((s.count+count)>value.length) {
+ // Need to allocate
+ char newvalue[]=new char[s.count+count+16]; //16 is DEFAULTSIZE
+ for(int i=0; i<count; i++)
+ newvalue[i]=value[i];
+ for(int i=0; i<s.count; i++)
+ newvalue[i+count]=s.value[i];
+ value=newvalue;
+ count+=s.count;
+ } else {
+ for(int i=0; i<s.count; i++) {
+ value[i+count]=s.value[i];
+ }
+ count+=s.count;
}
+ return this;
+ }
- public String toString() {
- return new String(this);
- }
+ public String toString() {
+ return new String(this);
+ }
}
public class System {
- public static void printInt(int x) {
- String s=String.valueOf(x);
- printString(s);
- }
+ public static void printInt(int x) {
+ String s=String.valueOf(x);
+ printString(s);
+ }
- public static native long currentTimeMillis();
+ public static native long currentTimeMillis();
- public static native void printString(String s);
+ public static native void printString(String s);
- public static void error() {
- System.printString("Error (Use Breakpoint on ___System______error method for more information!)\n");
- }
+ public static void error() {
+ System.printString("Error (Use Breakpoint on ___System______error method for more information!)\n");
+ }
- public static native void exit(int status);
-
- public static native void printI(int status);
+ public static native void exit(int status);
- public static native void clearPrefetchCache();
+ public static native void printI(int status);
+
+ public static native void clearPrefetchCache();
}
public class Thread {
- private boolean finished;
+ private boolean finished;
- public void start() {
- nativeCreate();
- }
+ public void start() {
+ nativeCreate();
+ }
- private static void staticStart(Thread t) {
- t.run();
- }
+ private static void staticStart(Thread t) {
+ t.run();
+ }
- public static native void yield();
+ public static native void yield();
- public void join() {
- nativeJoin();
- }
+ public void join() {
+ nativeJoin();
+ }
- private native void nativeJoin();
+ private native void nativeJoin();
- public native static void sleep(long millis);
-
- public void run() {}
+ public native static void sleep(long millis);
- private native void nativeCreate();
+ public void run() {
+ }
+
+ private native void nativeCreate();
}
public class Thread {
- /* Don't allow overriding this method. If you do, it will break dispatch
- * because we don't have the type information necessary. */
- public boolean threadDone;
+ /* Don't allow overriding this method. If you do, it will break dispatch
+ * because we don't have the type information necessary. */
+ public boolean threadDone;
- public Thread() {
- threadDone = false;
- }
+ public Thread() {
+ threadDone = false;
+ }
- public static native void yield();
+ public static native void yield();
- public final native void join();
+ public final native void join();
- public final native void start(int mid);
+ public final native void start(int mid);
- public native static void sleep(long millis);
-
- public void run() {
- }
+ public native static void sleep(long millis);
+
+ public void run() {
+ }
}
public class Vector {
- Object[] array;
- int size;
- int capacityIncrement;
+ Object[] array;
+ int size;
+ int capacityIncrement;
- public Vector() {
- capacityIncrement=0;
- size=0;
- array=new Object[10];
- }
+ public Vector() {
+ capacityIncrement=0;
+ size=0;
+ array=new Object[10];
+ }
- public void clear() {
- size=0;
- array=new Object[10];
- }
+ public void clear() {
+ size=0;
+ array=new Object[10];
+ }
- public int indexOf(Object elem) {
- return indexOf(elem, 0);
- }
+ public int indexOf(Object elem) {
+ return indexOf(elem, 0);
+ }
- public int indexOf(Object elem, int index) {
- for(int i=index;i<size;i++) {
- if (elem.equals(array[i]))
- return i;
- }
- return -1;
+ public int indexOf(Object elem, int index) {
+ for(int i=index; i<size; i++) {
+ if (elem.equals(array[i]))
+ return i;
}
+ return -1;
+ }
- public Object elementAt(int index) {
- if (index<0 || index >=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 <size)
- array[index]=obj;
- else
- System.printString("Illegal setElementAt");
- }
+ public void setElementAt(Object obj, int index) {
+ if (index>=0 && index <size)
+ array[index]=obj;
+ else
+ System.printString("Illegal setElementAt");
+ }
- private ensureCapacity(int minCapacity) {
- if (minCapacity>array.length) {
- int newsize;
- if (capacityIncrement<=0)
- newsize=array.length*2;
- else
- newsize=array.length+capacityIncrement;
- if (newsize<minCapacity)
- newsize=minCapacity;
- Object [] newarray=new Object[newsize];
- for(int i=0;i<size;i++)
- newarray[i]=array[i];
- array=newarray;
- }
+ private ensureCapacity(int minCapacity) {
+ if (minCapacity>array.length) {
+ int newsize;
+ if (capacityIncrement<=0)
+ newsize=array.length*2;
+ else
+ newsize=array.length+capacityIncrement;
+ if (newsize<minCapacity)
+ newsize=minCapacity;
+ Object [] newarray=new Object[newsize];
+ for(int i=0; i<size; i++)
+ newarray[i]=array[i];
+ array=newarray;
}
+ }
- public int size() {
- return size;
- }
+ public int size() {
+ return size;
+ }
- public Enumeration elements() {
- System.printString("Vector.elements not implemented");
- }
+ public Enumeration elements() {
+ System.printString("Vector.elements not implemented");
+ }
- public void addElement(Object obj) {
- if (size==array.length) {
- ensureCapacity(size+1);
- }
- array[size++]=obj;
+ public void addElement(Object obj) {
+ if (size==array.length) {
+ ensureCapacity(size+1);
}
+ array[size++]=obj;
+ }
- 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--;
+ 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--;
+ }
}
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");
+ }
}
/* 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. */
/**
*
* @see System#currentTimeMillis()
*/
- public Random()
- {
+ public Random() {
setSeed(System.currentTimeMillis());
}
*
* @param seed the initial seed
*/
- public Random(long seed)
- {
+ public Random(long seed) {
setSeed(seed);
}
* same seed, should produce the same results, if the same methods
* are called. The implementation for java.util.Random is:
*
-<pre>public synchronized void setSeed(long seed)
-{
- this.seed = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1);
- haveNextNextGaussian = false;
-}</pre>
+ <pre>public synchronized void setSeed(long seed)
+ {
+ this.seed = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1);
+ haveNextNextGaussian = false;
+ }</pre>
*
* @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;
}
* independent chosen random bits (0 and 1 are equally likely).
* The implementation for java.util.Random is:
*
-<pre>protected synchronized int next(int bits)
-{
- seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
- return (int) (seed >>> (48 - bits));
-}</pre>
+ <pre>protected synchronized int next(int bits)
+ {
+ seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
+ return (int) (seed >>> (48 - bits));
+ }</pre>
*
* @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));
}
* are (approximately) equally likely.
* The JDK documentation gives no implementation, but it seems to be:
*
-<pre>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++)
- {
+ <pre>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;
- }
- }
-}</pre>
+ }
+ }
+ }</pre>
*
* @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;
}
+ }
}
/**
* an int value whose 32 bits are independent chosen random bits
* (0 and 1 are equally likely). The implementation for
* java.util.Random is:
- *
-<pre>public int nextInt()
-{
- return next(32);
-}</pre>
+ *
+ <pre>public int nextInt()
+ {
+ return next(32);
+ }</pre>
*
* @return the next pseudorandom value
*/
- public int nextInt()
- {
+ public int nextInt() {
return next(32);
}
* each value has the same likelihodd (1/<code>n</code>).
* (0 and 1 are equally likely). The implementation for
* java.util.Random is:
- *
-<pre>
-public int nextInt(int n)
-{
- if (n <= 0)
- throw new IllegalArgumentException("n must be positive");
+ *
+ <pre>
+ 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;
-}</pre>
- *
+ return val;
+ }</pre>
+ *
* <p>This algorithm would return every value with exactly the same
* probability, if the next()-method would be a perfect random number
* generator.
* @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;
}
* long are independently chosen and 0 and 1 have equal likelihood.
* The implementation for java.util.Random is:
*
-<pre>public long nextLong()
-{
- return ((long) next(32) << 32) + next(32);
-}</pre>
+ <pre>public long nextLong()
+ {
+ return ((long) next(32) << 32) + next(32);
+ }</pre>
*
* @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:
- *
-<pre>public boolean nextBoolean()
-{
- return next(1) != 0;
-}</pre>
+ *
+ <pre>public boolean nextBoolean()
+ {
+ return next(1) != 0;
+ }</pre>
*
* @return the next pseudorandom boolean
* @since 1.2
*/
- public boolean nextBoolean()
- {
+ public boolean nextBoolean() {
return next(1) != 0;
}
* Generates the next pseudorandom float uniformly distributed
* between 0.0f (inclusive) and 1.0f (exclusive). The
* implementation is as follows.
- *
-<pre>public float nextFloat()
-{
- return next(24) / ((float)(1 << 24));
-}</pre>
+ *
+ <pre>public float nextFloat()
+ {
+ return next(24) / ((float)(1 << 24));
+ }</pre>
*
* @return the next pseudorandom float
*/
- public float nextFloat()
- {
+ public float nextFloat() {
return next(24) / (float) (1 << 24);
}
* between 0.0 (inclusive) and 1.0 (exclusive). The
* implementation is as follows.
*
-<pre>public double nextDouble()
-{
- return (((long) next(26) << 27) + next(27)) / (double)(1L << 53);
-}</pre>
+ <pre>public double nextDouble()
+ {
+ return (((long) next(26) << 27) + next(27)) / (double)(1L << 53);
+ }</pre>
*
* @return the next pseudorandom double
*/
- public double nextDouble()
- {
+ public double nextDouble() {
return (((long) next(26) << 27) + next(27)) / (double) (1L << 53);
}
* Generates the next pseudorandom, Gaussian (normally) distributed
* double value, with mean 0.0 and standard deviation 1.0.
* The algorithm is as follows.
- *
-<pre>public synchronized double nextGaussian()
-{
- if (haveNextNextGaussian)
- {
- haveNextNextGaussian = false;
- return nextNextGaussian;
- }
- else
- {
- double v1, v2, s;
- do
- {
+ *
+ <pre>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;
- }
-}</pre>
+ double norm = Math.sqrt(-2 * Math.log(s) / s);
+ nextNextGaussian = v2 * norm;
+ haveNextNextGaussian = true;
+ return v1 * norm;
+ }
+ }</pre>
*
* <p>This is described in section 3.4.1 of <em>The Art of Computer
* Programming, Volume 2</em> 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;
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();
+ }
}
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;
+ }
}
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 + "___";
+ }
}
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();
+ }
}
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();
+ }
}
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<TempDescriptor, TempDescriptor> backuptable;
- Hashtable<LocalityBinding, TempDescriptor> 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<TempDescriptor, TempDescriptor>();
- this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
- }
+ 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<TempDescriptor, TempDescriptor> backuptable;
+ Hashtable<LocalityBinding, TempDescriptor> 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<TempDescriptor, TempDescriptor>();
+ this.reverttable=new Hashtable<LocalityBinding, TempDescriptor>();
+ }
+ }
+
+ /** 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<argc;i++) {");
- } else
- outmethod.println(" for(i=1;i<argc;i++) {");
- outmethod.println(" int length=strlen(argv[i]);");
- if (GENERATEPRECISEGC) {
- outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
- } else {
- outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
- }
- if (state.DSM)
- outmethod.println(" ((void **)(((char *)& stringarray->___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<argc;i++) {");
+ } else
+ outmethod.println(" for(i=1;i<argc;i++) {");
+ outmethod.println(" int length=strlen(argv[i]);");
+ if (GENERATEPRECISEGC) {
+ outmethod.println(" struct ___String___ *newstring=NewString(NULL, argv[i], length);");
+ } else {
+ outmethod.println(" struct ___String___ *newstring=NewString(argv[i], length);");
+ }
+ if (state.DSM)
+ outmethod.println(" ((void **)(((char *)& stringarray->___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\");");
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 <thread.h>");
+ if (state.main!=null) {
+ outmethod.println("#include <string.h>");
}
+ 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<LocalityBinding> 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 <thread.h>");
- if (state.main!=null) {
- outmethod.println("#include <string.h>");
- }
- 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<LocalityBinding> 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 <pthread.h>");
- 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<state.numArrays();i++) {
- TypeDescriptor tdarray=arraytable[i];
- TypeDescriptor tdelement=tdarray.dereference();
- outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
- outrepairstructs.println(" int __type__;");
- printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
- outrepairstructs.println(" int length;");
- /*
- // Need to add support to repair tool for this
- if (tdelement.isClass()||tdelement.isArray())
- outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
- else
- outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
- */
- outrepairstructs.println("}\n");
- }
+ }
+
+ protected void outputClassDeclarations(PrintWriter outclassdefs) {
+ if (state.THREAD||state.DSM)
+ outclassdefs.println("#include <pthread.h>");
+ 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;i<fields.size();i++) {
- FieldDescriptor fd=(FieldDescriptor)fields.get(i);
- if (fd.getType().isArray()) {
- output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
- } else if (fd.getType().isClass())
- output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
- else if (fd.getType().isFloat())
- output.println(" int "+fd.getSymbol()+"; /* really float */");
- else
- output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
- }
+ 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");
}
- /** This method outputs TaskDescriptor information */
- private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
- for (int i=0;i<task.numParameters();i++) {
- VarDescriptor param_var=task.getParameter(i);
- TypeDescriptor param_type=task.getParamType(i);
- FlagExpressionNode param_flag=task.getFlag(param_var);
- TagExpressionList param_tag=task.getTag(param_var);
-
- int dnfterms;
- if (param_flag==null) {
- output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
- output.println("0x0, 0x0 };");
- dnfterms=1;
- } else {
- DNFFlag dflag=param_flag.getDNF();
- dnfterms=dflag.size();
-
- Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
- output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
- for(int j=0;j<dflag.size();j++) {
- if (j!=0)
- output.println(",");
- Vector term=dflag.get(j);
- int andmask=0;
- int checkmask=0;
- for(int k=0;k<term.size();k++) {
- DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
- FlagDescriptor fd=dfa.getFlag();
- boolean negated=dfa.getNegated();
- int flagid=1<<((Integer)flags.get(fd)).intValue();
- andmask|=flagid;
- if (!negated)
- checkmask|=flagid;
- }
- output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
- }
- output.println("};");
- }
-
- output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
- //BUG...added next line to fix, test with any task program
- if (param_tag!=null)
- for(int j=0;j<param_tag.numTags();j++) {
- if (j!=0)
- output.println(",");
- /* for each tag we need */
- /* which slot it is */
- /* what type it is */
- TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
- TempDescriptor tmp=param_tag.getTemp(j);
- int slot=fm.getTagInt(tmp);
- output.println(slot+", "+state.getTagId(tvd.getTag()));
- }
- output.println("};");
-
- output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
- output.println("/* type */"+param_type.getClassDesc().getId()+",");
- output.println("/* number of DNF terms */"+dnfterms+",");
- output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
- output.println("0,");
- //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.getSafeSymbol());
- output.println("};");
- }
-
-
- output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
- for (int i=0;i<task.numParameters();i++) {
- if (i!=0)
- output.println(",");
- output.print("¶meter_"+i+"_"+task.getSafeSymbol());
+ for(int i=0; i<state.numArrays(); i++) {
+ TypeDescriptor tdarray=arraytable[i];
+ TypeDescriptor tdelement=tdarray.dereference();
+ outrepairstructs.println("structure "+arraytype+"_"+state.getArrayNumber(tdarray)+" {");
+ outrepairstructs.println(" int __type__;");
+ printRepairStruct(typeutil.getClass(TypeUtil.ObjectClass), outrepairstructs);
+ outrepairstructs.println(" int length;");
+ /*
+ // Need to add support to repair tool for this
+ if (tdelement.isClass()||tdelement.isArray())
+ outrepairstructs.println(" "+tdelement.getRepairSymbol()+" * elem[this.length];");
+ else
+ outrepairstructs.println(" "+tdelement.getRepairSymbol()+" elem[this.length];");
+ */
+ outrepairstructs.println("}\n");
+ }
+ }
+
+ 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; i<fields.size(); i++) {
+ FieldDescriptor fd=(FieldDescriptor)fields.get(i);
+ if (fd.getType().isArray()) {
+ output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
+ } else if (fd.getType().isClass())
+ output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
+ else if (fd.getType().isFloat())
+ output.println(" int "+fd.getSymbol()+"; /* really float */");
+ else
+ output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
+ }
+ }
+
+ /** This method outputs TaskDescriptor information */
+ private void generateTaskDescriptor(PrintWriter output, FlatMethod fm, TaskDescriptor task) {
+ for (int i=0; i<task.numParameters(); i++) {
+ VarDescriptor param_var=task.getParameter(i);
+ TypeDescriptor param_type=task.getParamType(i);
+ FlagExpressionNode param_flag=task.getFlag(param_var);
+ TagExpressionList param_tag=task.getTag(param_var);
+
+ int dnfterms;
+ if (param_flag==null) {
+ output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
+ output.println("0x0, 0x0 };");
+ dnfterms=1;
+ } else {
+ DNFFlag dflag=param_flag.getDNF();
+ dnfterms=dflag.size();
+
+ Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
+ output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
+ for(int j=0; j<dflag.size(); j++) {
+ if (j!=0)
+ output.println(",");
+ Vector term=dflag.get(j);
+ int andmask=0;
+ int checkmask=0;
+ for(int k=0; k<term.size(); k++) {
+ DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
+ FlagDescriptor fd=dfa.getFlag();
+ boolean negated=dfa.getNegated();
+ int flagid=1<<((Integer)flags.get(fd)).intValue();
+ andmask|=flagid;
+ if (!negated)
+ checkmask|=flagid;
+ }
+ output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
}
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("};");
+ }
+
+ output.println("int parametertag_"+i+"_"+task.getSafeSymbol()+"[]={");
+ //BUG...added next line to fix, test with any task program
+ if (param_tag!=null)
+ for(int j=0; j<param_tag.numTags(); j++) {
+ if (j!=0)
+ output.println(",");
+ /* for each tag we need */
+ /* which slot it is */
+ /* what type it is */
+ TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
+ TempDescriptor tmp=param_tag.getTemp(j);
+ int slot=fm.getTagInt(tmp);
+ output.println(slot+", "+state.getTagId(tvd.getTag()));
+ }
+ output.println("};");
+
+ output.println("struct parameterdescriptor parameter_"+i+"_"+task.getSafeSymbol()+"={");
+ output.println("/* type */"+param_type.getClassDesc().getId()+",");
+ output.println("/* number of DNF terms */"+dnfterms+",");
+ output.println("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
+ output.println("0,");
+ //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.getSafeSymbol());
+ 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());
- }
-
- outvirtual.print("void * virtualtable[]={");
- boolean needcomma=false;
- for(int i=0;i<state.numClasses()+state.numArrays();i++) {
- for(int j=0;j<maxcount;j++) {
- if (needcomma)
- outvirtual.print(", ");
- if (state.DSM&&lbvirtualtable[i][j]!=null) {
- LocalityBinding lb=lbvirtualtable[i][j];
- MethodDescriptor md=lb.getMethod();
- outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
- } else if (!state.DSM&&virtualtable[i][j]!=null) {
- MethodDescriptor md=virtualtable[i][j];
- outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
- } else {
- outvirtual.print("0");
- }
- needcomma=true;
- }
- outvirtual.println("");
- }
- outvirtual.println("};");
- outvirtual.close();
- }
-
- private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
- /* Get inherited methods */
- if (cd.getSuperDesc()!=null)
- fillinRow(cd.getSuperDesc(), virtualtable, rownum);
- /* Override them with our methods */
- for(Iterator it=cd.getMethods();it.hasNext();) {
- MethodDescriptor md=(MethodDescriptor)it.next();
- if (md.isStatic()||md.getReturnType()==null)
- continue;
- int methodnum=virtualcalls.getMethodNumber(md);
- virtualtable[rownum][methodnum]=md;
- }
+ output.println("struct parameterdescriptor * parameterdescriptors_"+task.getSafeSymbol()+"[] = {");
+ for (int i=0; i<task.numParameters(); i++) {
+ if (i!=0)
+ output.println(",");
+ output.print("¶meter_"+i+"_"+task.getSafeSymbol());
}
-
- private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
- /* Get inherited methods */
- if (cd.getSuperDesc()!=null)
- fillinRow(cd.getSuperDesc(), virtualtable, rownum);
- /* Override them with our methods */
- if (locality.getClassBindings(cd)!=null)
- for(Iterator<LocalityBinding> 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<state.numClasses();i++) {
- if (needcomma)
- outclassdefs.print(", ");
- outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
- needcomma=true;
+ outvirtual.print("void * virtualtable[]={");
+ boolean needcomma=false;
+ for(int i=0; i<state.numClasses()+state.numArrays(); i++) {
+ for(int j=0; j<maxcount; j++) {
+ if (needcomma)
+ outvirtual.print(", ");
+ if (state.DSM&&lbvirtualtable[i][j]!=null) {
+ LocalityBinding lb=lbvirtualtable[i][j];
+ MethodDescriptor md=lb.getMethod();
+ outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
+ } else if (!state.DSM&&virtualtable[i][j]!=null) {
+ MethodDescriptor md=virtualtable[i][j];
+ outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
+ } else {
+ outvirtual.print("0");
}
+ needcomma=true;
+ }
+ outvirtual.println("");
+ }
+ outvirtual.println("};");
+ outvirtual.close();
+ }
+
+ private void fillinRow(ClassDescriptor cd, MethodDescriptor[][] virtualtable, int rownum) {
+ /* Get inherited methods */
+ if (cd.getSuperDesc()!=null)
+ fillinRow(cd.getSuperDesc(), virtualtable, rownum);
+ /* Override them with our methods */
+ for(Iterator it=cd.getMethods(); it.hasNext();) {
+ MethodDescriptor md=(MethodDescriptor)it.next();
+ if (md.isStatic()||md.getReturnType()==null)
+ continue;
+ int methodnum=virtualcalls.getMethodNumber(md);
+ virtualtable[rownum][methodnum]=md;
+ }
+ }
+
+ private void fillinRow(ClassDescriptor cd, LocalityBinding[][] virtualtable, int rownum) {
+ /* Get inherited methods */
+ if (cd.getSuperDesc()!=null)
+ fillinRow(cd.getSuperDesc(), virtualtable, rownum);
+ /* Override them with our methods */
+ if (locality.getClassBindings(cd)!=null)
+ for(Iterator<LocalityBinding> 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<state.numClasses(); i++) {
+ if (needcomma)
+ outclassdefs.print(", ");
+ outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
+ needcomma=true;
+ }
- arraytable=new TypeDescriptor[state.numArrays()];
+ arraytable=new TypeDescriptor[state.numArrays()];
- Iterator arrayit=state.getArrayIterator();
- while(arrayit.hasNext()) {
- TypeDescriptor td=(TypeDescriptor)arrayit.next();
- int id=state.getArrayNumber(td);
- arraytable[id]=td;
- }
-
- for(int i=0;i<state.numArrays();i++) {
- if (needcomma)
- outclassdefs.print(", ");
- TypeDescriptor tdelement=arraytable[i].dereference();
- if (tdelement.isArray()||tdelement.isClass())
- outclassdefs.print("sizeof(void *)");
- else
- outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
- needcomma=true;
- }
+ Iterator arrayit=state.getArrayIterator();
+ while(arrayit.hasNext()) {
+ TypeDescriptor td=(TypeDescriptor)arrayit.next();
+ int id=state.getArrayNumber(td);
+ arraytable[id]=td;
+ }
- outclassdefs.println("};");
+ for(int i=0; i<state.numArrays(); i++) {
+ if (needcomma)
+ outclassdefs.print(", ");
+ TypeDescriptor tdelement=arraytable[i].dereference();
+ if (tdelement.isArray()||tdelement.isClass())
+ outclassdefs.print("sizeof(void *)");
+ else
+ outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
+ needcomma=true;
}
- /** Constructs params and temp objects for each method or task.
- * These objects tell the compiler which temps need to be
- * allocated. */
+ outclassdefs.println("};");
+ }
+
+ /** Constructs params and temp objects for each method or task.
+ * These objects tell the compiler which temps need to be
+ * allocated. */
+
+ protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
+ MethodDescriptor md=fm.getMethod();
+ TaskDescriptor task=fm.getTask();
+ Set<TempDescriptor> 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<fm.numParameters(); i++) {
+ TempDescriptor temp=fm.getParameter(i);
+ TypeDescriptor type=temp.getType();
+ if (type.isPtr()&&GENERATEPRECISEGC)
+ objectparams.addPtr(temp);
+ else
+ objectparams.addPrim(temp);
+ if(lb!=null&&saveset.contains(temp)) {
+ backuptable.put(temp, temp.createNew());
+ }
+ }
- protected void generateTempStructs(FlatMethod fm, LocalityBinding lb) {
- MethodDescriptor md=fm.getMethod();
- TaskDescriptor task=fm.getTask();
- Set<TempDescriptor> saveset=lb!=null?locality.getTempSet(lb):null;
- ParamsObject objectparams=md!=null?new ParamsObject(md,tag++):new ParamsObject(task, tag++);
+ for(int i=0; i<fm.numTags(); i++) {
+ TempDescriptor temp=fm.getTag(i);
+ if (GENERATEPRECISEGC)
+ objectparams.addPtr(temp);
+ else
+ objectparams.addPrim(temp);
+ }
- if (lb!=null)
- paramstable.put(lb, objectparams);
- else if (md!=null)
- paramstable.put(md, objectparams);
+ TempObject objecttemps=md!=null ? new TempObject(objectparams,md,tag++) : new TempObject(objectparams, task, tag++);
+ if (lb!=null)
+ tempstable.put(lb, objecttemps);
+ else if (md!=null)
+ tempstable.put(md, objecttemps);
+ 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<writes.length; i++) {
+ TempDescriptor temp=writes[i];
+ TypeDescriptor type=temp.getType();
+ if (type.isPtr()&&GENERATEPRECISEGC)
+ objecttemps.addPtr(temp);
else
- paramstable.put(task, objectparams);
-
- for(int i=0;i<fm.numParameters();i++) {
- TempDescriptor temp=fm.getParameter(i);
- TypeDescriptor type=temp.getType();
- if (type.isPtr()&&GENERATEPRECISEGC)
- objectparams.addPtr(temp);
- else
- objectparams.addPrim(temp);
- if(lb!=null&&saveset.contains(temp)) {
- backuptable.put(temp, temp.createNew());
- }
- }
-
- for(int i=0;i<fm.numTags();i++) {
- TempDescriptor temp=fm.getTag(i);
- if (GENERATEPRECISEGC)
- objectparams.addPtr(temp);
- else
- objectparams.addPrim(temp);
- }
+ objecttemps.addPrim(temp);
+ if(lb!=null&&saveset.contains(temp)&&
+ !backuptable.containsKey(temp))
+ backuptable.put(temp, temp.createNew());
+ }
+ }
- TempObject objecttemps=md!=null?new TempObject(objectparams,md,tag++):new TempObject(objectparams, task, tag++);
- if (lb!=null)
- tempstable.put(lb, objecttemps);
- else if (md!=null)
- tempstable.put(md, objecttemps);
+ /* Create backup temps */
+ if (lb!=null) {
+ for(Iterator<TempDescriptor> 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<writes.length;i++) {
- TempDescriptor temp=writes[i];
- TypeDescriptor type=temp.getType();
- if (type.isPtr()&&GENERATEPRECISEGC)
- objecttemps.addPtr(temp);
- else
- objecttemps.addPrim(temp);
- if(lb!=null&&saveset.contains(temp)&&
- !backuptable.containsKey(temp))
- backuptable.put(temp, temp.createNew());
- }
- }
-
- /* Create backup temps */
- if (lb!=null) {
- for(Iterator<TempDescriptor> 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<state.numClasses();i++) {
- ClassDescriptor cn=cdarray[i];
- if (needcomma)
- output.println(",");
- needcomma=true;
- output.print(cn.getSafeSymbol()+"_pointers");
- }
-
- for(int i=0;i<state.numArrays();i++) {
- if (needcomma)
- output.println(", ");
- TypeDescriptor tdelement=arraytable[i].dereference();
- if (tdelement.isArray()||tdelement.isClass())
- output.print("((unsigned int *)1)");
- else
- output.print("0");
- needcomma=true;
- }
-
- output.println("};");
- needcomma=false;
- output.println("int hasflags[]={");
- for(int i=0;i<state.numClasses();i++) {
- ClassDescriptor cn=cdarray[i];
- if (needcomma)
- output.println(", ");
- needcomma=true;
- if (cn.hasFlags())
- output.print("1");
- else
- output.print("0");
- }
- output.println("};");
+ }
+
+ /** 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("};");
}
-
- /** Print out table to give us supertypes */
- private void generateSuperTypeTable(PrintWriter output) {
- output.println("int supertypes[]={");
- boolean needcomma=false;
- for(int i=0;i<state.numClasses();i++) {
- ClassDescriptor cn=cdarray[i];
- if (needcomma)
- output.println(",");
- needcomma=true;
- if (cn.getSuperDesc()!=null) {
- ClassDescriptor cdsuper=cn.getSuperDesc();
- output.print(cdsuper.getId());
- } else
- output.print("-1");
- }
- output.println("};");
+ output.println("unsigned int * pointerarray[]={");
+ boolean needcomma=false;
+ for(int i=0; i<state.numClasses(); i++) {
+ ClassDescriptor cn=cdarray[i];
+ if (needcomma)
+ output.println(",");
+ needcomma=true;
+ output.print(cn.getSafeSymbol()+"_pointers");
}
- /** Force consistent field ordering between inherited classes. */
-
- private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
-
- ClassDescriptor sp=cn.getSuperDesc();
- if (sp!=null)
- printClassStruct(sp, classdefout);
-
- if (!fieldorder.containsKey(cn)) {
- Vector fields=new Vector();
- fieldorder.put(cn,fields);
- if (sp==null&&!state.TASK) {
- fields.add(cn.getFieldTable().get("cachedCode"));
- }
- Iterator fieldit=cn.getFields();
- while(fieldit.hasNext()) {
- FieldDescriptor fd=(FieldDescriptor)fieldit.next();
- if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol()))&&
- (!fd.getSymbol().equals("cachedCode")||state.TASK))
- fields.add(fd);
- }
- }
- Vector fields=(Vector)fieldorder.get(cn);
-
- for(int i=0;i<fields.size();i++) {
- FieldDescriptor fd=(FieldDescriptor)fields.get(i);
- if (fd.getType().isClass()||fd.getType().isArray())
- classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
- else
- classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
- }
+ for(int i=0; i<state.numArrays(); i++) {
+ if (needcomma)
+ output.println(", ");
+ TypeDescriptor tdelement=arraytable[i].dereference();
+ if (tdelement.isArray()||tdelement.isClass())
+ output.print("((unsigned int *)1)");
+ else
+ output.print("0");
+ needcomma=true;
}
-
- /* Map flags to integers consistently between inherited
- * classes. */
-
- protected void mapFlags(ClassDescriptor cn) {
- ClassDescriptor sp=cn.getSuperDesc();
- if (sp!=null)
- mapFlags(sp);
- int max=0;
- if (!flagorder.containsKey(cn)) {
- Hashtable flags=new Hashtable();
- flagorder.put(cn,flags);
- if (sp!=null) {
- Hashtable superflags=(Hashtable)flagorder.get(sp);
- Iterator superflagit=superflags.keySet().iterator();
- while(superflagit.hasNext()) {
- FlagDescriptor fd=(FlagDescriptor)superflagit.next();
- Integer number=(Integer)superflags.get(fd);
- flags.put(fd, number);
- if ((number.intValue()+1)>max)
- max=number.intValue()+1;
- }
- }
-
- Iterator flagit=cn.getFlags();
- while(flagit.hasNext()) {
- FlagDescriptor fd=(FlagDescriptor)flagit.next();
- if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
- flags.put(fd, new Integer(max++));
- }
- }
+ output.println("};");
+ needcomma=false;
+ output.println("int hasflags[]={");
+ for(int i=0; i<state.numClasses(); i++) {
+ ClassDescriptor cn=cdarray[i];
+ if (needcomma)
+ output.println(", ");
+ needcomma=true;
+ if (cn.hasFlags())
+ output.print("1");
+ else
+ output.print("0");
}
+ 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; i<state.numClasses(); i++) {
+ ClassDescriptor cn=cdarray[i];
+ if (needcomma)
+ output.println(",");
+ needcomma=true;
+ if (cn.getSuperDesc()!=null) {
+ ClassDescriptor cdsuper=cn.getSuperDesc();
+ output.print(cdsuper.getId());
+ } else
+ output.print("-1");
+ }
+ output.println("};");
+ }
+
+ /** Force consistent field ordering between inherited classes. */
+
+ private void printClassStruct(ClassDescriptor cn, PrintWriter classdefout) {
+
+ ClassDescriptor sp=cn.getSuperDesc();
+ if (sp!=null)
+ printClassStruct(sp, classdefout);
+
+ if (!fieldorder.containsKey(cn)) {
+ Vector fields=new Vector();
+ fieldorder.put(cn,fields);
+ if (sp==null&&!state.TASK) {
+ fields.add(cn.getFieldTable().get("cachedCode"));
+ }
+ Iterator fieldit=cn.getFields();
+ while(fieldit.hasNext()) {
+ FieldDescriptor fd=(FieldDescriptor)fieldit.next();
+ if ((sp==null||!sp.getFieldTable().contains(fd.getSymbol()))&&
+ (!fd.getSymbol().equals("cachedCode")||state.TASK))
+ fields.add(fd);
+ }
+ }
+ Vector fields=(Vector)fieldorder.get(cn);
+
+ for(int i=0; i<fields.size(); i++) {
+ FieldDescriptor fd=(FieldDescriptor)fields.get(i);
+ if (fd.getType().isClass()||fd.getType().isArray())
+ classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
+ else
+ classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
+ }
+ }
+
+
+ /* Map flags to integers consistently between inherited
+ * classes. */
+
+ protected void mapFlags(ClassDescriptor cn) {
+ ClassDescriptor sp=cn.getSuperDesc();
+ if (sp!=null)
+ mapFlags(sp);
+ int max=0;
+ if (!flagorder.containsKey(cn)) {
+ Hashtable flags=new Hashtable();
+ flagorder.put(cn,flags);
+ if (sp!=null) {
+ Hashtable superflags=(Hashtable)flagorder.get(sp);
+ Iterator superflagit=superflags.keySet().iterator();
+ while(superflagit.hasNext()) {
+ FlagDescriptor fd=(FlagDescriptor)superflagit.next();
+ Integer number=(Integer)superflags.get(fd);
+ flags.put(fd, number);
+ if ((number.intValue()+1)>max)
+ max=number.intValue()+1;
+ }
+ }
+
+ Iterator flagit=cn.getFlags();
+ while(flagit.hasNext()) {
+ FlagDescriptor fd=(FlagDescriptor)flagit.next();
+ if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
+ flags.put(fd, new Integer(max++));
+ }
+ }
+ }
- /** 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<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
- Set<LocalityBinding> lbset=locality.getClassBindings(cn);
- if (lbset!=null) {
- for(Iterator<LocalityBinding> 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<objectparams.numPointers();i++) {
- TempDescriptor temp=objectparams.getPointer(i);
- output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
- }
- output.println("};\n");
- }
+ 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;");
+ }
}
-
-
- private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
- FlatMethod fm=state.getMethodFlat(md);
- generateTempStructs(fm, lb);
-
- ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null?lb:md);
- TempObject objecttemps=(TempObject) tempstable.get(lb!=null?lb:md);
-
- generateMethodParam(cn, md, lb, output);
-
- /* Output temp structure */
- if (GENERATEPRECISEGC) {
- if (state.DSM)
- output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
- else
- output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
- output.println(" int size;");
- output.println(" void * next;");
- for(int i=0;i<objecttemps.numPointers();i++) {
- TempDescriptor temp=objecttemps.getPointer(i);
- if (temp.getType().isNull())
- output.println(" void * "+temp.getSafeSymbol()+";");
- else
- output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
- }
- output.println("};\n");
- }
-
- /********* Output method declaration ***********/
-
- /* First the return type */
- if (md.getReturnType()!=null) {
- if (md.getReturnType().isClass()||md.getReturnType().isArray())
- headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
- else
- headersout.print(md.getReturnType().getSafeSymbol()+" ");
- } else
- //catch the constructor case
- headersout.print("void ");
-
- /* Next the method name */
- if (state.DSM) {
- headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
- } else
- headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
-
- boolean printcomma=false;
- if (GENERATEPRECISEGC) {
- if (state.DSM) {
- headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
+ printClassStruct(cn, classdefout);
+ classdefout.println("};\n");
+
+ if (state.DSM) {
+ /* Cycle through LocalityBindings */
+ HashSet<MethodDescriptor> nativemethods=new HashSet<MethodDescriptor>();
+ Set<LocalityBinding> lbset=locality.getClassBindings(cn);
+ if (lbset!=null) {
+ for(Iterator<LocalityBinding> 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;i<objectparams.numPrimitives();i++) {
- TempDescriptor temp=objectparams.getPrimitive(i);
- if (printcomma)
- headersout.print(", ");
- printcomma=true;
- if (temp.getType().isClass()||temp.getType().isArray())
- headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
- else
- headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
- }
- headersout.println(");\n");
+ 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);
+ }
+ }
+
+ } else
+ for(Iterator methodit=cn.getMethods(); methodit.hasNext();) {
+ MethodDescriptor md=(MethodDescriptor)methodit.next();
+ generateMethod(cn, md, null, headersout, output);
+ }
+ }
+
+ 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<objectparams.numPointers(); i++) {
+ TempDescriptor temp=objectparams.getPointer(i);
+ output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
+ }
+ output.println("};\n");
+ }
+ }
+
+
+ private void generateMethod(ClassDescriptor cn, MethodDescriptor md, LocalityBinding lb, PrintWriter headersout, PrintWriter output) {
+ FlatMethod fm=state.getMethodFlat(md);
+ generateTempStructs(fm, lb);
+
+ ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null ? lb : md);
+ TempObject objecttemps=(TempObject) tempstable.get(lb!=null ? lb : md);
+
+ generateMethodParam(cn, md, lb, output);
+
+ /* Output temp structure */
+ if (GENERATEPRECISEGC) {
+ if (state.DSM)
+ output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
+ else
+ output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals {");
+ output.println(" int size;");
+ output.println(" void * next;");
+ for(int i=0; i<objecttemps.numPointers(); i++) {
+ TempDescriptor temp=objecttemps.getPointer(i);
+ if (temp.getType().isNull())
+ output.println(" void * "+temp.getSafeSymbol()+";");
+ else
+ output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
+ }
+ output.println("};\n");
}
+ /********* Output method declaration ***********/
+
+ /* First the return type */
+ if (md.getReturnType()!=null) {
+ if (md.getReturnType().isClass()||md.getReturnType().isArray())
+ headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
+ else
+ headersout.print(md.getReturnType().getSafeSymbol()+" ");
+ } else
+ //catch the constructor case
+ headersout.print("void ");
+
+ /* Next the method name */
+ if (state.DSM) {
+ headersout.print(cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
+ } else
+ headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(");
+
+ boolean printcomma=false;
+ if (GENERATEPRECISEGC) {
+ if (state.DSM) {
+ headersout.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
+ } else
+ headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
+ printcomma=true;
+ }
- /** This function outputs (1) structures that parameters are
- * passed in (when PRECISE GC is enabled) and (2) function
- * prototypes for the tasks */
+ if (state.DSM&&lb.isAtomic()&&!md.getModifiers().isNative()) {
+ if (printcomma)
+ headersout.print(", ");
+ headersout.print("transrecord_t * trans");
+ printcomma=true;
+ }
- private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
- /* Cycle through tasks */
- Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
+ /* Output parameter list*/
+ for(int i=0; i<objectparams.numPrimitives(); i++) {
+ TempDescriptor temp=objectparams.getPrimitive(i);
+ if (printcomma)
+ headersout.print(", ");
+ printcomma=true;
+ if (temp.getType().isClass()||temp.getType().isArray())
+ headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
+ else
+ headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
+ }
+ headersout.println(");\n");
+ }
- while(taskit.hasNext()) {
- /* Classify parameters */
- TaskDescriptor task=(TaskDescriptor)taskit.next();
- FlatMethod fm=state.getMethodFlat(task);
- generateTempStructs(fm, null);
- ParamsObject objectparams=(ParamsObject) paramstable.get(task);
- TempObject objecttemps=(TempObject) tempstable.get(task);
+ /** This function outputs (1) structures that parameters are
+ * passed in (when PRECISE GC is enabled) and (2) function
+ * prototypes for the tasks */
- /* Output parameter structure */
- if (GENERATEPRECISEGC) {
- output.println("struct "+task.getSafeSymbol()+"_params {");
+ private void generateTaskStructs(PrintWriter output, PrintWriter headersout) {
+ /* Cycle through tasks */
+ Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator();
- output.println(" int size;");
- output.println(" void * next;");
- for(int i=0;i<objectparams.numPointers();i++) {
- TempDescriptor temp=objectparams.getPointer(i);
- output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
- }
+ while(taskit.hasNext()) {
+ /* Classify parameters */
+ TaskDescriptor task=(TaskDescriptor)taskit.next();
+ FlatMethod fm=state.getMethodFlat(task);
+ generateTempStructs(fm, null);
- output.println("};\n");
- if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
- 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;i<objecttemps.numPointers();i++) {
- TempDescriptor temp=objecttemps.getPointer(i);
- if (temp.getType().isNull())
- output.println(" void * "+temp.getSafeSymbol()+";");
- else if(temp.getType().isTag())
- output.println(" struct "+
- (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
- else
- output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
- }
- output.println("};\n");
- }
-
- /* Output task declaration */
- headersout.print("void " + task.getSafeSymbol()+"(");
-
- boolean printcomma=false;
- if (GENERATEPRECISEGC) {
- headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
- } else
- headersout.print("void * parameterarray[]");
- headersout.println(");\n");
- }
- }
+ /* Output parameter structure */
+ if (GENERATEPRECISEGC) {
+ output.println("struct "+task.getSafeSymbol()+"_params {");
- /***** Generate code for FlatMethod fm. *****/
-
- private void generateFlatMethod(FlatMethod fm, LocalityBinding lb, PrintWriter output) {
- if (State.PRINTFLAT)
- System.out.println(fm.printMethod());
- MethodDescriptor md=fm.getMethod();
-
- TaskDescriptor task=fm.getTask();
-
- ClassDescriptor cn=md!=null?md.getClassDesc():null;
-
- 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;");
+ output.println(" int size;");
+ output.println(" void * next;");
+ for(int i=0; i<objectparams.numPointers(); i++) {
+ TempDescriptor temp=objectparams.getPointer(i);
+ output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
}
- 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;j<objecttemp.numPointers();j++)
- output.print(", NULL");
- output.println("};");
- }
-
- for(int i=0;i<objecttemp.numPrimitives();i++) {
- TempDescriptor td=objecttemp.getPrimitive(i);
- TypeDescriptor type=td.getType();
- if (type.isNull())
- output.println(" void * "+td.getSafeSymbol()+";");
- else if (type.isClass()||type.isArray())
- output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
- else
- output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
+ output.println("};\n");
+ if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
+ 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<objecttemps.numPointers(); i++) {
+ TempDescriptor temp=objecttemps.getPointer(i);
+ if (temp.getType().isNull())
+ output.println(" void * "+temp.getSafeSymbol()+";");
+ else if(temp.getType().isTag())
+ output.println(" struct "+
+ (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
+ else
+ output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
}
+ output.println("};\n");
+ }
- /* Assign labels to FlatNode's if necessary.*/
-
- Hashtable<FlatNode, Integer> 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<FlatNode, Integer> assignLabels(FlatMethod fm) {
- HashSet tovisit=new HashSet();
- HashSet visited=new HashSet();
- int labelindex=0;
- Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
- 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;i<fn.numNext();i++) {
- FlatNode nn=fn.getNext(i);
- if(i>0) {
- //1) Edge >1 of node
- nodetolabel.put(nn,new Integer(labelindex++));
- }
- if (!visited.contains(nn)&&!tovisit.contains(nn)) {
- tovisit.add(nn);
- } else {
- //2) Join point
- nodetolabel.put(nn,new Integer(labelindex++));
- }
- }
- }
- 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(;breakindex<pp.desc.size();breakindex++) {
- Descriptor desc=pp.getDescAt(breakindex);
- if (desc instanceof FieldDescriptor) {
- FieldDescriptor fd=(FieldDescriptor)desc;
- if (fd.isGlobal()) {
- break;
- }
- }
- }
- breakindex++;
- }
-
- if (breakindex>pp.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<breakindex;i++) {
- String indexcheck="";
-
- Descriptor desc=pp.getDescAt(i);
- if (desc instanceof FieldDescriptor) {
- FieldDescriptor fd=(FieldDescriptor)desc;
- if (maybenull) {
- if (!teststr.equals(""))
- teststr+="&&";
- teststr+="((prefptr="+basestr+")!=NULL)";
- basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+fd.getSafeSymbol();
- } else {
- basestr=basestr+"->"+fd.getSafeSymbol();
- maybenull=true;
- }
- lasttype=fd.getType();
- } else {
- IndexDescriptor id=(IndexDescriptor)desc;
- indexcheck="((tmpindex=";
- for(int j=0;j<id.tddesc.size();j++) {
- indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
- }
- indexcheck+=id.offset+")>=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; j<objecttemp.numPointers(); j++)
+ output.print(", NULL");
+ output.println("};");
}
- 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<TempDescriptor> 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<objecttemp.numPrimitives(); i++) {
+ TempDescriptor td=objecttemp.getPrimitive(i);
+ TypeDescriptor type=td.getType();
+ if (type.isNull())
+ output.println(" void * "+td.getSafeSymbol()+";");
+ else if (type.isClass()||type.isArray())
+ output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
+ else
+ output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
+ }
- /* Restore temps */
- for(Iterator<TempDescriptor> 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<FlatNode, Integer> 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<FlatNode, Integer> assignLabels(FlatMethod fm) {
+ HashSet tovisit=new HashSet();
+ HashSet visited=new HashSet();
+ int labelindex=0;
+ Hashtable<FlatNode, Integer> nodetolabel=new Hashtable<FlatNode, Integer>();
+ 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; i<fn.numNext(); i++) {
+ FlatNode nn=fn.getNext(i);
+ if(i>0) {
+ //1) Edge >1 of node
+ nodetolabel.put(nn,new Integer(labelindex++));
+ }
+ if (!visited.contains(nn)&&!tovisit.contains(nn)) {
+ tovisit.add(nn);
+ } else {
+ //2) Join point
+ nodetolabel.put(nn,new Integer(labelindex++));
+ }
+ }
+ }
+ 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<temps.length;i++) {
- output.println(varname+"->"+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<fc.numArgs();i++) {
- Descriptor var=md.getParameter(i);
- TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
- if (objectparams.isParamPtr(paramtemp)) {
- TempDescriptor targ=fc.getArg(i);
- output.print(", ");
- TypeDescriptor td=md.getParamType(i);
- if (td.isTag())
- output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
- else
- output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
- }
- }
- output.println("};");
- }
- output.print(" ");
-
+ if (objecttemps.isLocalPtr(td)) {
+ return localsprefix+"."+td.getSafeSymbol();
+ }
- if (fc.getReturnTemp()!=null)
- output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
+ 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(; breakindex<pp.desc.size(); breakindex++) {
+ Descriptor desc=pp.getDescAt(breakindex);
+ if (desc instanceof FieldDescriptor) {
+ FieldDescriptor fd=(FieldDescriptor)desc;
+ if (fd.isGlobal()) {
+ break;
+ }
+ }
+ }
+ breakindex++;
+ }
- /* Do we need to do virtual dispatch? */
- if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
- //no
- if (state.DSM) {
- LocalityBinding fclb=locality.getBinding(lb, fc);
- output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
- } else {
- output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
- }
+ if (breakindex>pp.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<breakindex; i++) {
+ String indexcheck="";
+
+ Descriptor desc=pp.getDescAt(i);
+ if (desc instanceof FieldDescriptor) {
+ FieldDescriptor fd=(FieldDescriptor)desc;
+ if (maybenull) {
+ if (!teststr.equals(""))
+ teststr+="&&";
+ teststr+="((prefptr="+basestr+")!=NULL)";
+ basestr="((struct "+lasttype.getSafeSymbol()+" *)prefptr)->"+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<id.tddesc.size(); j++) {
+ indexcheck+=generateTemp(fm, id.getTempDescAt(j), lb)+"+";
+ }
+ indexcheck+=id.offset+")>=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<objectparams.numPrimitives();i++) {
- TempDescriptor temp=objectparams.getPrimitive(i);
- if (printcomma)
- output.print(", ");
- printcomma=true;
- if (temp.getType().isClass()||temp.getType().isArray())
- output.print("struct " + temp.getType().getSafeSymbol()+" * ");
- else
- output.print(temp.getType().getSafeSymbol());
- }
+ 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);
+ }
- 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<TempDescriptor> 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<fc.numArgs();i++) {
- Descriptor var=md.getParameter(i);
- TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
- if (objectparams.isParamPrim(paramtemp)) {
- TempDescriptor targ=fc.getArg(i);
- if (needcomma)
- output.print(", ");
-
- TypeDescriptor ptd=md.getParamType(i);
- if (ptd.isClass()&&!ptd.isArray())
- output.print("(struct "+ptd.getSafeSymbol()+" *) ");
- output.print(generateTemp(fm, targ,lb));
- needcomma=true;
- }
- }
- output.println(");");
- output.println(" }");
- }
-
- private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
- Set subclasses=typeutil.getSubClasses(thiscd);
- if (subclasses==null)
- return true;
- for(Iterator classit=subclasses.iterator();classit.hasNext();) {
- ClassDescriptor cd=(ClassDescriptor)classit.next();
- Set possiblematches=cd.getMethodTable().getSet(md.getSymbol());
- for(Iterator matchit=possiblematches.iterator();matchit.hasNext();) {
- MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
- if (md.matches(matchmd))
- return false;
- }
- }
- return true;
+ /* Restore temps */
+ for(Iterator<TempDescriptor> 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<temps.length; i++) {
+ output.println(varname+"->"+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<fc.numArgs(); i++) {
+ Descriptor var=md.getParameter(i);
+ TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
+ if (objectparams.isParamPtr(paramtemp)) {
+ TempDescriptor targ=fc.getArg(i);
+ output.print(", ");
+ TypeDescriptor td=md.getParamType(i);
+ if (td.isTag())
+ output.print("(struct "+(new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
+ else
+ output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ,lb));
+ }
+ }
+ output.println("};");
+ }
+ output.print(" ");
+
+
+ if (fc.getReturnTemp()!=null)
+ output.print(generateTemp(fm,fc.getReturnTemp(),lb)+"=");
+
+ /* Do we need to do virtual dispatch? */
+ if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
+ //no
+ if (state.DSM) {
+ LocalityBinding fclb=locality.getBinding(lb, fc);
+ output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
+ } else {
+ output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
+ }
+ } 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) {
- Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
- if (status==LocalityAnalysis.GLOBAL) {
- String field=ffn.getField().getSafeSymbol();
- String src=generateTemp(fm, ffn.getSrc(),lb);
- String dst=generateTemp(fm, ffn.getDst(),lb);
-
- if (ffn.getField().getType().isPtr()) {
-
- //TODO: Uncomment this when we have runtime support
- //if (ffn.getSrc()==ffn.getDst()) {
- //output.println("{");
- //output.println("void * temp="+src+";");
- //output.println("if (temp&0x1) {");
- //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
- //output.println(src+"->"+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; i<objectparams.numPrimitives(); i++) {
+ TempDescriptor temp=objectparams.getPrimitive(i);
+ if (printcomma)
+ output.print(", ");
+ printcomma=true;
+ if (temp.getType().isClass()||temp.getType().isArray())
+ output.print("struct " + temp.getType().getSafeSymbol()+" * ");
+ else
+ output.print(temp.getType().getSafeSymbol());
+ }
+
+ 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;
+ }
+
+ 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;
+ }
- 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<fc.numArgs(); i++) {
+ Descriptor var=md.getParameter(i);
+ TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
+ if (objectparams.isParamPrim(paramtemp)) {
+ TempDescriptor targ=fc.getArg(i);
+ if (needcomma)
+ output.print(", ");
+
+ TypeDescriptor ptd=md.getParamType(i);
+ if (ptd.isClass()&&!ptd.isArray())
+ output.print("(struct "+ptd.getSafeSymbol()+" *) ");
+ output.print(generateTemp(fm, targ,lb));
+ needcomma=true;
+ }
+ }
+ output.println(");");
+ output.println(" }");
+ }
+
+ private boolean singleCall(ClassDescriptor thiscd, MethodDescriptor md) {
+ Set subclasses=typeutil.getSubClasses(thiscd);
+ if (subclasses==null)
+ return true;
+ for(Iterator classit=subclasses.iterator(); classit.hasNext();) {
+ ClassDescriptor cd=(ClassDescriptor)classit.next();
+ Set possiblematches=cd.getMethodTable().getSet(md.getSymbol());
+ for(Iterator matchit=possiblematches.iterator(); matchit.hasNext();) {
+ MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
+ if (md.matches(matchmd))
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private void generateFlatFieldNode(FlatMethod fm, LocalityBinding lb, FlatFieldNode ffn, PrintWriter output) {
+ if (state.DSM) {
+ Integer status=locality.getNodePreTempInfo(lb,ffn).get(ffn.getSrc());
+ if (status==LocalityAnalysis.GLOBAL) {
+ String field=ffn.getField().getSafeSymbol();
+ String src=generateTemp(fm, ffn.getSrc(),lb);
+ String dst=generateTemp(fm, ffn.getDst(),lb);
+
+ if (ffn.getField().getType().isPtr()) {
+
+ //TODO: Uncomment this when we have runtime support
+ //if (ffn.getSrc()==ffn.getDst()) {
+ //output.println("{");
+ //output.println("void * temp="+src+";");
+ //output.println("if (temp&0x1) {");
+ //output.println("temp=(void *) transRead(trans, (unsigned int) temp);");
+ //output.println(src+"->"+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; i<objectparams.numPrimitives(); i++) {
+ TempDescriptor temp=objectparams.getPrimitive(i);
+ if (printcomma)
+ output.print(", ");
+ printcomma=true;
+ if (temp.getType().isClass()||temp.getType().isArray())
+ output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
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()+";");
+ output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
+ }
+ output.println(") {");
+ } else if (!GENERATEPRECISEGC) {
+ /* Imprecise Task */
+ output.println("void * parameterarray[]) {");
+ /* Unpack variables */
+ for(int i=0; i<objectparams.numPrimitives(); i++) {
+ TempDescriptor temp=objectparams.getPrimitive(i);
+ output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
+ }
+ for(int i=0; i<fm.numTags(); i++) {
+ TempDescriptor temp=fm.getTag(i);
+ int offset=i+objectparams.numPrimitives();
+ output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
+ }
+
+ if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
+ 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<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
+ 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<dflag.size(); j++) {
+ if (j!=0)
+ output.println(",");
+ Vector term=dflag.get(j);
+ int andmask=0;
+ int checkmask=0;
+ for(int k=0; k<term.size(); k++) {
+ DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
+ FlagDescriptor fd=dfa.getFlag();
+ boolean negated=dfa.getNegated();
+ int flagid=1<<((Integer)flags.get(fd)).intValue();
+ andmask|=flagid;
+ if (!negated)
+ checkmask|=flagid;
+ }
+ output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
+ }
+ }
+ }
+ }
+ output.println("};\n");
+
+ //generate for tags
+ TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
+ output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
+ int numtags = 0;
+ if (tagel!=null){
+ for(int j=0; j<tagel.numTags(); j++) {
+ if (j!=0)
+ output.println(",");
+ TempDescriptor tmp=tagel.getTemp(j);
+ if (!slotnumber.containsKey(tmp)) {
+ Integer slotint=new Integer(current_slot++);
+ slotnumber.put(tmp,slotint);
+ }
+ int slot=slotnumber.get(tmp).intValue();
+ output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
+ }
+ numtags = tagel.numTags();
+ }
+ output.println("};");
+
+ //store the result into a predicatemember struct
+ output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
+ output.println("/*type*/"+typed.getClassDesc().getId()+",");
+ output.println("/* number of dnf terms */"+numberterms+",");
+ output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
+ output.println("/* number of tag */"+numtags+",");
+ output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
+ output.println("};\n");
+ predicateindex++;
+ }
- 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.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
- } else
- output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
- printcomma=true;
- }
- if (state.DSM&&lb.isAtomic()) {
- if (printcomma)
- output.print(", ");
- output.print("transrecord_t * trans");
- printcomma=true;
+ //generate an array that stores the entire predicate
+ output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
+ for( int j = 0; j<predicateindex; j++){
+ if( j != predicateindex-1) output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
+ else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
+ }
+ output.println("};\n");
+ return predicateindex;
+ }
+
+
+ void generateOptionalArrays(PrintWriter output, PrintWriter headers, Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> 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<numotd) maxotd = numotd;
+ if( !c_otd.isEmpty() ){
+ for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();){
+ OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
+
+ //generate the int arrays for the predicate
+ Predicate predicate = otd.predicate;
+ int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
+ TreeSet<Integer> fsset=new TreeSet<Integer>();
+ //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<Integer> 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<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)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<OptionalTaskDescriptor> 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;i<objectparams.numPrimitives();i++) {
- TempDescriptor temp=objectparams.getPrimitive(i);
- if (printcomma)
- output.print(", ");
- printcomma=true;
- if (temp.getType().isClass()||temp.getType().isArray())
- output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
- else
- output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
- }
- output.println(") {");
- } else if (!GENERATEPRECISEGC) {
- /* Imprecise Task */
- output.println("void * parameterarray[]) {");
- /* Unpack variables */
- for(int i=0;i<objectparams.numPrimitives();i++) {
- TempDescriptor temp=objectparams.getPrimitive(i);
- output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
- }
- for(int i=0;i<fm.numTags();i++) {
- TempDescriptor temp=fm.getTag(i);
- int offset=i+objectparams.numPrimitives();
- output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+"=parameterarray["+offset+"];");
- }
+ output.println("};\n");
- if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
- 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<TaskIndex> tiset=sa.getTaskIndex(fs);
+ for(Iterator<TaskIndex> 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<OptionalTaskDescriptor> 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<OptionalTaskDescriptor> 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<TempDescriptor, Integer> slotnumber=new Hashtable<TempDescriptor, Integer>();
- 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<dflag.size();j++) {
- if (j!=0)
- output.println(",");
- Vector term=dflag.get(j);
- int andmask=0;
- int checkmask=0;
- for(int k=0;k<term.size();k++) {
- DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
- FlagDescriptor fd=dfa.getFlag();
- boolean negated=dfa.getNegated();
- int flagid=1<<((Integer)flags.get(fd)).intValue();
- andmask|=flagid;
- if (!negated)
- checkmask|=flagid;
- }
- output.print("/*andmask*/0x"+Integer.toHexString(andmask)+", /*checkmask*/0x"+Integer.toHexString(checkmask));
- }
- }
- }
- }
- output.println("};\n");
-
- //generate for tags
- TagExpressionList tagel = predicate.tags.get(vard.getSymbol());
- output.println("int predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
- int numtags = 0;
- if (tagel!=null){
- for(int j=0;j<tagel.numTags();j++) {
- if (j!=0)
- output.println(",");
- TempDescriptor tmp=tagel.getTemp(j);
- if (!slotnumber.containsKey(tmp)) {
- Integer slotint=new Integer(current_slot++);
- slotnumber.put(tmp,slotint);
- }
- int slot=slotnumber.get(tmp).intValue();
- output.println("/* slot */"+ slot+", /*tagid*/"+state.getTagId(tmp.getTag()));
- }
- numtags = tagel.numTags();
- }
- output.println("};");
-
- //store the result into a predicatemember struct
- output.println("struct predicatemember predicatemember_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"={");
- output.println("/*type*/"+typed.getClassDesc().getId()+",");
- output.println("/* number of dnf terms */"+numberterms+",");
- output.println("predicateflags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
- output.println("/* number of tag */"+numtags+",");
- output.println("predicatetags_"+predicateindex+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
- output.println("};\n");
- predicateindex++;
- }
-
-
- //generate an array that stores the entire predicate
- output.println("struct predicatemember * predicatememberarray_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+"[]={");
- for( int j = 0; j<predicateindex; j++){
- if( j != predicateindex-1)output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol()+",");
- else output.println("&predicatemember_"+j+"_OTD"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
+ tiset=sa.getTaskIndex(fs);
+ boolean needcomma=false;
+ int runtimeti=0;
+ output.println("struct taskfailure * taskfailurearray"+fscounter+"_"+cdtemp.getSafeSymbol()+"[]={");
+ for(Iterator<TaskIndex> 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<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> 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<numotd) maxotd = numotd;
- if( !c_otd.isEmpty() ){
- for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext();){
- OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
-
- //generate the int arrays for the predicate
- Predicate predicate = otd.predicate;
- int predicateindex = generateOptionalPredicate(predicate, otd, cdtemp, output);
- TreeSet<Integer> fsset=new TreeSet<Integer>();
- //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<Integer> 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<OptionalTaskDescriptor> availabletasks = (HashSet<OptionalTaskDescriptor>)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<OptionalTaskDescriptor> 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<TaskIndex> tiset=sa.getTaskIndex(fs);
- for(Iterator<TaskIndex> itti=tiset.iterator();itti.hasNext();) {
- TaskIndex ti=itti.next();
- if (ti.isRuntime())
- continue;
-
- Set<OptionalTaskDescriptor> otdset=sa.getOptions(fs, ti);
-
- output.print("struct optionaltaskdescriptor * optionaltaskfailure_FS"+fscounter+"_"+ti.getTask().getSafeSymbol()+"_"+ti.getIndex()+"_array[] = {");
- boolean needcomma=false;
- for(Iterator<OptionalTaskDescriptor> 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<TaskIndex> 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; i<fscounter; i++){
- if (needcomma) output.print(",");
- output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
- needcomma=true;
- }
- output.println("};");
-
- //Build the classanalysiswrapper referring to the previous array
- output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
- output.println("/*type*/"+cdtemp.getId()+",");
- output.println("/*numotd*/"+numotd+",");
- output.println("otdarray"+cdtemp.getSafeSymbol()+",");
- output.println("/* number of fsanalysiswrappers */"+fscounter+",");
- output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
- processedcd.add(cdtemp);
- }
-
- //build an array containing every classes for which code has been build
- output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
- for(int i=0;i<state.numClasses();i++) {
- ClassDescriptor cn=cdarray[i];
- if (i>0)
- 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<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
- Relation r=new Relation();
- for(Iterator<OptionalTaskDescriptor>otdit=otdset.iterator();otdit.hasNext();) {
- OptionalTaskDescriptor otd=otdit.next();
- TaskIndex ti=new TaskIndex(otd.td, otd.getIndex());
- r.put(ti, otd);
- }
- LinkedList<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
- 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; i<fscounter; i++){
+ if (needcomma) output.print(",");
+ output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
+ needcomma=true;
+ }
+ output.println("};");
+
+ //Build the classanalysiswrapper referring to the previous array
+ output.println("struct classanalysiswrapper classanalysiswrapper_"+cdtemp.getSafeSymbol()+"={");
+ output.println("/*type*/"+cdtemp.getId()+",");
+ output.println("/*numotd*/"+numotd+",");
+ output.println("otdarray"+cdtemp.getSafeSymbol()+",");
+ output.println("/* number of fsanalysiswrappers */"+fscounter+",");
+ output.println("fsanalysiswrapperarray_"+cdtemp.getSafeSymbol()+"};\n");
+ processedcd.add(cdtemp);
+ }
+
+ //build an array containing every classes for which code has been build
+ output.println("struct classanalysiswrapper * classanalysiswrapperarray[]={");
+ for(int i=0; i<state.numClasses(); i++) {
+ ClassDescriptor cn=cdarray[i];
+ if (i>0)
+ 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<OptionalTaskDescriptor> ordertd(Set<OptionalTaskDescriptor> otdset) {
+ Relation r=new Relation();
+ for(Iterator<OptionalTaskDescriptor>otdit=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<OptionalTaskDescriptor> l=new LinkedList<OptionalTaskDescriptor>();
+ 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) {
+ }
}
-
+
import IR.Tree.TagExpressionList;
public class BuildCodeMultiCore extends BuildCode {
- private Vector<Schedule> 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<Schedule> 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<Schedule> 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<Schedule> 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<TaskDescriptor> 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;j<objectparams.numPointers();j++) {
- TempDescriptor temp=objectparams.getPointer(j);
- output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
- }
-
- output.println("};\n");
- if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
- 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<objecttemps.numPointers();j++) {
- TempDescriptor temp=objecttemps.getPointer(j);
- if (temp.getType().isNull())
- output.println(" void * "+temp.getSafeSymbol()+";");
- else if(temp.getType().isTag())
- output.println(" struct "+
- (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
- else
- output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
- }
- output.println("};\n");
- }
-
- /* Output task declaration */
- headersout.print("void " + task.getCoreSafeSymbol(num)+"(");
-
- if (GENERATEPRECISEGC) {
- headersout.print("struct "+task.getCoreSafeSymbol(num)+"_params * "+paramsprefix);
- } else
- headersout.print("void * parameterarray[]");
- headersout.println(");\n");
- }
- }
-
+ /* 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);
}
- /* This method outputs code for each task. */
-
- 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\"");
-
- /* Output object transfer queues into method.c*/
- generateObjectTransQueues(outmethod);
-
- //Vector[] qnames = new Vector[2];
- int numclasses = numqueues[0].length;
- Vector qnames[]= new Vector[numclasses];
- for(int i = 0; i < qnames.length; ++i) {
- qnames[i] = null;
+ /* 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;
}
- Iterator<TaskDescriptor> 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 <string.h>");
- outtask.println("#ifdef RAW");
- outtask.println("#include <raw.h>");
- 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<FlagState, String> flag2qname = new Hashtable<FlagState, String>();
- this.fsate2qnames[num] = flag2qname;
- Hashtable<FlagState, Queue<Integer>> 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<TaskDescriptor> 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;j<objecttemp.numPointers();j++)
- output.print(", NULL");
- output.println("};");
+ output.println("struct "+task.getCoreSafeSymbol(num)+"_params {");
+ output.println(" int size;");
+ output.println(" void * next;");
+ for(int j=0; j<objectparams.numPointers(); j++) {
+ TempDescriptor temp=objectparams.getPointer(j);
+ output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
+ }
+
+ output.println("};\n");
+ if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
+ maxtaskparams=objectparams.numPointers()+fm.numTags();
+ }
}
- for(int i=0;i<objecttemp.numPrimitives();i++) {
- TempDescriptor td=objecttemp.getPrimitive(i);
- TypeDescriptor type=td.getType();
- if (type.isNull())
- output.println(" void * "+td.getSafeSymbol()+";");
- else if (type.isClass()||type.isArray())
- output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
+ /* 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<objecttemps.numPointers(); j++) {
+ TempDescriptor temp=objecttemps.getPointer(j);
+ if (temp.getType().isNull())
+ output.println(" void * "+temp.getSafeSymbol()+";");
+ else if(temp.getType().isTag())
+ output.println(" struct "+
+ (new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass))).getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
else
- output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
- }
-
- for(int i = 0; i < fm.numParameters(); ++i) {
- TempDescriptor temp = fm.getParameter(i);
- output.println(" int "+generateTempFlagName(fm, temp, lb)+" = "+super.generateTemp(fm, temp, lb)+
- "->flag;");
+ 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<FlatNode, Integer> 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<task.numParameters();i++) {
- VarDescriptor param_var=task.getParameter(i);
- TypeDescriptor param_type=task.getParamType(i);
- FlagExpressionNode param_flag=task.getFlag(param_var);
- TagExpressionList param_tag=task.getTag(param_var);
-
- int dnfterms;
- if (param_flag==null) {
- output.println("int parameterdnf_"+i+"_"+task.getCoreSafeSymbol(num)+"[]={");
- output.println("0x0, 0x0 };");
- dnfterms=1;
- } else {
- DNFFlag dflag=param_flag.getDNF();
- dnfterms=dflag.size();
-
- Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
- output.println("int parameterdnf_"+i+"_"+task.getCoreSafeSymbol(num)+"[]={");
- for(int j=0;j<dflag.size();j++) {
- if (j!=0)
- output.println(",");
- Vector term=dflag.get(j);
- int andmask=0;
- int checkmask=0;
- for(int k=0;k<term.size();k++) {
- DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
- FlagDescriptor fd=dfa.getFlag();
- boolean negated=dfa.getNegated();
- int flagid=1<<((Integer)flags.get(fd)).intValue();
- andmask|=flagid;
- if (!negated)
- checkmask|=flagid;
- }
- output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
- }
- output.println("};");
- }
+ /* Output object transfer queues into method.c*/
+ generateObjectTransQueues(outmethod);
- output.println("int parametertag_"+i+"_"+task.getCoreSafeSymbol(num)+"[]={");
- //BUG...added next line to fix, test with any task program
- if (param_tag!=null)
- for(int j=0;j<param_tag.numTags();j++) {
- if (j!=0)
- output.println(",");
- /* for each tag we need */
- /* which slot it is */
- /* what type it is */
- TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
- TempDescriptor tmp=param_tag.getTemp(j);
- int slot=fm.getTagInt(tmp);
- output.println(slot+", "+state.getTagId(tvd.getTag()));
- }
- output.println("};");
+ //Vector[] qnames = new Vector[2];
+ int numclasses = numqueues[0].length;
+ Vector qnames[]= new Vector[numclasses];
+ for(int i = 0; i < qnames.length; ++i) {
+ qnames[i] = null;
+ }
+ Iterator<TaskDescriptor> 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<task.numParameters();i++) {
- if (i!=0)
- output.println(",");
- output.print("&" + this.objqueueprefix + i + "_" + task.getCoreSafeSymbol(num));
- }
- output.println("};");
+ numqueues[num][i] = tmpvector.size();
+ } else {
+ numqueues[num][i] = 0;
+ }
+ outtaskdefs.println("};");
+ }
- output.println("struct parameterdescriptor * parameterdescriptors_"+task.getCoreSafeSymbol(num)+"[] = {");
- for (int i=0;i<task.numParameters();i++) {
- if (i!=0)
- output.println(",");
- output.print("¶meter_"+i+"_"+task.getCoreSafeSymbol(num));
+ /* All the queues for tasks residing on this core*/
+ 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.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 <string.h>");
+ outtask.println("#ifdef RAW");
+ outtask.println("#include <raw.h>");
+ 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<FlagState, String> flag2qname = new Hashtable<FlagState, String>();
+ this.fsate2qnames[num] = flag2qname;
+ Hashtable<FlagState, Queue<Integer>> 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; j<objecttemp.numPointers(); j++)
+ output.print(", NULL");
+ 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();
+ for(int i=0; i<objecttemp.numPrimitives(); i++) {
+ TempDescriptor td=objecttemp.getPrimitive(i);
+ TypeDescriptor type=td.getType();
+ if (type.isNull())
+ output.println(" void * "+td.getSafeSymbol()+";");
+ else if (type.isClass()||type.isArray())
+ output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
+ else
+ output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
}
- /** This method generates header information for the task
- * referenced by the Descriptor des. */
+ for(int i = 0; i < fm.numParameters(); ++i) {
+ TempDescriptor temp = fm.getParameter(i);
+ output.println(" int "+generateTempFlagName(fm, temp, lb)+" = "+super.generateTemp(fm, temp, lb)+
+ "->flag;");
+ }
- 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<FlatNode, Integer> 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; i<task.numParameters(); i++) {
+ VarDescriptor param_var=task.getParameter(i);
+ TypeDescriptor param_type=task.getParamType(i);
+ FlagExpressionNode param_flag=task.getFlag(param_var);
+ TagExpressionList param_tag=task.getTag(param_var);
+
+ int dnfterms;
+ if (param_flag==null) {
+ output.println("int parameterdnf_"+i+"_"+task.getCoreSafeSymbol(num)+"[]={");
+ output.println("0x0, 0x0 };");
+ dnfterms=1;
+ } else {
+ DNFFlag dflag=param_flag.getDNF();
+ dnfterms=dflag.size();
+
+ Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
+ output.println("int parameterdnf_"+i+"_"+task.getCoreSafeSymbol(num)+"[]={");
+ for(int j=0; j<dflag.size(); j++) {
+ if (j!=0)
+ output.println(",");
+ Vector term=dflag.get(j);
+ int andmask=0;
+ int checkmask=0;
+ for(int k=0; k<term.size(); k++) {
+ DNFFlagAtom dfa=(DNFFlagAtom)term.get(k);
+ FlagDescriptor fd=dfa.getFlag();
+ boolean negated=dfa.getNegated();
+ int flagid=1<<((Integer)flags.get(fd)).intValue();
+ andmask|=flagid;
+ if (!negated)
+ checkmask|=flagid;
+ }
+ output.print("0x"+Integer.toHexString(andmask)+", 0x"+Integer.toHexString(checkmask));
}
+ output.println("};");
+ }
+
+ output.println("int parametertag_"+i+"_"+task.getCoreSafeSymbol(num)+"[]={");
+ //BUG...added next line to fix, test with any task program
+ if (param_tag!=null)
+ for(int j=0; j<param_tag.numTags(); j++) {
+ if (j!=0)
+ output.println(",");
+ /* for each tag we need */
+ /* which slot it is */
+ /* what type it is */
+ TagVarDescriptor tvd=(TagVarDescriptor)task.getParameterTable().get(param_tag.getName(j));
+ TempDescriptor tmp=param_tag.getTemp(j);
+ int slot=fm.getTagInt(tmp);
+ output.println(slot+", "+state.getTagId(tvd.getTag()));
+ }
+ output.println("};");
+
+ // 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("};");
+ }
- /*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;i<objectparams.numPrimitives();i++) {
- TempDescriptor temp=objectparams.getPrimitive(i);
- output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
- }
- for(int i=0;i<fm.numTags();i++) {
- TempDescriptor temp=fm.getTag(i);
- int offset=i+objectparams.numPrimitives();
- output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+i+"___=parameterarray["+offset+"];");// add i to fix bugs of duplicate definition of tags
- }
+ /* parameter queues for this task*/
+ output.println("struct parameterwrapper * " + this.paramqarrayprefix + task.getCoreSafeSymbol(num)+"[] = {");
+ for (int i=0; i<task.numParameters(); i++) {
+ if (i!=0)
+ output.println(",");
+ output.print("&" + this.objqueueprefix + i + "_" + task.getCoreSafeSymbol(num));
+ }
+ output.println("};");
- if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
- maxtaskparams=objectparams.numPrimitives()+fm.numTags();
- } else output.println(") {");
+ output.println("struct parameterdescriptor * parameterdescriptors_"+task.getCoreSafeSymbol(num)+"[] = {");
+ for (int i=0; i<task.numParameters(); i++) {
+ if (i!=0)
+ output.println(",");
+ output.print("¶meter_"+i+"_"+task.getCoreSafeSymbol(num));
}
-
- 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<FlagState> 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; i<objectparams.numPrimitives(); i++) {
+ TempDescriptor temp=objectparams.getPrimitive(i);
+ output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
+ }
+ for(int i=0; i<fm.numTags(); i++) {
+ TempDescriptor temp=fm.getTag(i);
+ int offset=i+objectparams.numPrimitives();
+ output.println("struct ___TagDescriptor___ * "+temp.getSafeSymbol()+i+"___=parameterarray["+offset+"];"); // add i to fix bugs of duplicate definition of tags
+ }
+
+ if ((objectparams.numPrimitives()+fm.numTags())>maxtaskparams)
+ 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<FlagState> 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<FlagState> 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<FlagState> tmpfstates = (Vector<FlagState>)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<FlagState> 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<FlagState, Queue<Integer>> 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<FlagState> tmpfstates = (Vector<FlagState>)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<FlagState> tmpfstates = (Vector<FlagState>)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<FlagState, Queue<Integer>> 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<FlagState> tmpfstates = (Vector<FlagState>)targetFStates[j];
- for(int i = 0; i < tmpfstates.size(); ++i) {
- FlagState tmpFState = tmpfstates.elementAt(i);
-
- if(this.currentSchedule.getAllyCoreTable() == null) {
- isolate = true;
+
+ Vector<TranObjInfo> sendto = new Vector<TranObjInfo>();
+ Queue<Integer> 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<TranObjInfo> sendto = new Vector<TranObjInfo>();
- Queue<Integer> 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<Integer> 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<TaskDescriptor> residetasks = this.currentSchedule.getTasks();
- Vector<TaskDescriptor> tasks = new Vector<TaskDescriptor>();
- Vector<Integer> indexes = new Vector<Integer>();
- 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<TaskDescriptor> residetasks = this.scheduling.get(targetcore).getTasks();
- Vector<TaskDescriptor> tasks = new Vector<TaskDescriptor>();
- Vector<Integer> indexes = new Vector<Integer>();
- 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<Integer> 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<TaskDescriptor> residetasks = this.currentSchedule.getTasks();
+ Vector<TaskDescriptor> tasks = new Vector<TaskDescriptor>();
+ Vector<Integer> indexes = new Vector<Integer>();
+ 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<TaskDescriptor> residetasks = this.scheduling.get(targetcore).getTasks();
+ Vector<TaskDescriptor> tasks = new Vector<TaskDescriptor>();
+ Vector<Integer> indexes = new Vector<Integer>();
+ 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<TranObjInfo> sendto, TranObjInfo t) {
+ if(sendto.size() == 0) {
+ return false;
}
-
- private boolean contains(Vector<TranObjInfo> 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;
+ }
}
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; i<td.numParameters(); i++) {
+ VarDescriptor paramvd=td.getParameter(i);
+ fm.addParameterTemp(getTempforVar(paramvd));
+ TagExpressionList tel=td.getTag(paramvd);
+ //BUG added next line to fix...to test feed in any task program
+ if (tel!=null)
+ for(int j=0; j<tel.numTags(); j++) {
+ TagVarDescriptor tvd=(TagVarDescriptor) td.getParameterTable().getFromSameScope(tel.getName(j));
+ TempDescriptor tagtmp=getTempforVar(tvd);
+ if (!visitedset.containsKey(tvd.getName())) {
+ visitedset.put(tvd.getName(),tvd.getTag());
+ fm.addTagTemp(tagtmp);
+ } else {
+ TagDescriptor tmptd=(TagDescriptor) visitedset.get(tvd.getName());
+ if (!tmptd.equals(tvd.getTag()))
+ throw new Error("Two different tag types with same name as parameters to:"+td);
+ }
+ tel.setTemp(j, tagtmp);
}
}
-
- private void flattenTask(TaskDescriptor td) {
- BlockNode bn=state.getMethodBody(td);
- NodePair np=flattenBlockNode(bn);
- FlatNode fn=np.getBegin();
+
+ /* Flatten Vector of Flag Effects */
+ Vector flags=td.getFlagEffects();
+ updateFlagActionNode(ffan,flags);
+
+ state.addFlatCode(td,fm);
+ }
+
+
+ /* This method transforms a vector of FlagEffects into the FlatFlagActionNode */
+ private void updateFlagActionNode(FlatFlagActionNode ffan, Vector flags) {
+ if (flags==null) // Do nothing if the flag effects vector is empty
+ return;
+
+ for(int i=0; i<flags.size(); i++) {
+ FlagEffects fes=(FlagEffects)flags.get(i);
+ TempDescriptor flagtemp=getTempforVar(fes.getVar());
+ // Process the flags
+ for(int j=0; j<fes.numEffects(); j++) {
+ FlagEffect fe=fes.getEffect(j);
+ ffan.addFlagAction(flagtemp, fe.getFlag(), fe.getStatus());
+ }
+ // Process the tags
+ for(int j=0; j<fes.numTagEffects(); j++) {
+ TagEffect te=fes.getTagEffect(j);
+ TempDescriptor tagtemp=getTempforVar(te.getTag());
+
+ ffan.addTagAction(flagtemp, te.getTag().getTag(), tagtemp, te.getStatus());
+ }
+ }
+ }
+
+ FlatAtomicEnterNode curran=null;
+
+ private void flattenClass(ClassDescriptor cn) {
+ Iterator methodit=cn.getMethods();
+ while(methodit.hasNext()) {
+ currmd=(MethodDescriptor)methodit.next();
+ BlockNode bn=state.getMethodBody(currmd);
+
+ if (state.DSM&&currmd.getModifiers().isAtomic()) {
+ curran=new FlatAtomicEnterNode();
+ } else
+ curran=null;
+ NodePair np=flattenBlockNode(bn);
+ FlatNode fn=np.getBegin();
+ if (state.THREAD&&currmd.getModifiers().isSynchronized()) {
+ MethodDescriptor memd=(MethodDescriptor)typeutil.getClass("Object").getMethodTable().get("MonitorEnter");
+ TempDescriptor thistd=getTempforVar(currmd.getThis());
+ FlatCall fc=new FlatCall(memd, null, thistd, new TempDescriptor[0]);
+ fc.addNext(fn);
+ fn=fc;
if (np.getEnd().kind()!=FKind.FlatReturnNode) {
- FlatReturnNode rnflat=new FlatReturnNode(null);
- np.getEnd().addNext(rnflat);
+ MethodDescriptor memdex=(MethodDescriptor)typeutil.getClass("Object").getMethodTable().get("MonitorExit");
+ FlatCall fcunlock=new FlatCall(memdex, null, thistd, new TempDescriptor[0]);
+ np.getEnd().addNext(fcunlock);
+ FlatReturnNode rnflat=new FlatReturnNode(null);
+ fcunlock.addNext(rnflat);
}
-
- 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;i<td.numParameters();i++) {
- VarDescriptor paramvd=td.getParameter(i);
- fm.addParameterTemp(getTempforVar(paramvd));
- TagExpressionList tel=td.getTag(paramvd);
- //BUG added next line to fix...to test feed in any task program
- if (tel!=null)
- for(int j=0;j<tel.numTags();j++) {
- TagVarDescriptor tvd=(TagVarDescriptor) td.getParameterTable().getFromSameScope(tel.getName(j));
- TempDescriptor tagtmp=getTempforVar(tvd);
- if (!visitedset.containsKey(tvd.getName())) {
- visitedset.put(tvd.getName(),tvd.getTag());
- fm.addTagTemp(tagtmp);
- } else {
- TagDescriptor tmptd=(TagDescriptor) visitedset.get(tvd.getName());
- if (!tmptd.equals(tvd.getTag()))
- throw new Error("Two different tag types with same name as parameters to:"+td);
- }
- tel.setTemp(j, tagtmp);
- }
+ } else if (state.DSM&&currmd.getModifiers().isAtomic()) {
+ curran.addNext(fn);
+ fn=curran;
+ if (np.getEnd().kind()!=FKind.FlatReturnNode) {
+ FlatAtomicExitNode aen=new FlatAtomicExitNode(curran);
+ np.getEnd().addNext(aen);
+ FlatReturnNode rnflat=new FlatReturnNode(null);
+ aen.addNext(rnflat);
}
-
- /* Flatten Vector of Flag Effects */
- Vector flags=td.getFlagEffects();
- updateFlagActionNode(ffan,flags);
-
- state.addFlatCode(td,fm);
+ } else if (np.getEnd().kind()!=FKind.FlatReturnNode) {
+ FlatReturnNode rnflat=new FlatReturnNode(null);
+ np.getEnd().addNext(rnflat);
+ }
+
+ FlatMethod fm=new FlatMethod(currmd);
+ fm.addNext(fn);
+ if (!currmd.isStatic())
+ fm.addParameterTemp(getTempforParam(currmd.getThis()));
+ for(int i=0; i<currmd.numParameters(); i++) {
+ fm.addParameterTemp(getTempforParam(currmd.getParameter(i)));
+ }
+ state.addFlatCode(currmd,fm);
}
-
-
- /* This method transforms a vector of FlagEffects into the FlatFlagActionNode */
- private void updateFlagActionNode(FlatFlagActionNode ffan, Vector flags) {
- if (flags==null) // Do nothing if the flag effects vector is empty
- return;
-
- for(int i=0;i<flags.size();i++) {
- FlagEffects fes=(FlagEffects)flags.get(i);
- TempDescriptor flagtemp=getTempforVar(fes.getVar());
- // Process the flags
- for(int j=0;j<fes.numEffects();j++) {
- FlagEffect fe=fes.getEffect(j);
- ffan.addFlagAction(flagtemp, fe.getFlag(), fe.getStatus());
- }
- // Process the tags
- for(int j=0;j<fes.numTagEffects();j++) {
- TagEffect te=fes.getTagEffect(j);
- TempDescriptor tagtemp=getTempforVar(te.getTag());
-
- ffan.addTagAction(flagtemp, te.getTag().getTag(), tagtemp, te.getStatus());
- }
- }
+ }
+
+ private NodePair flattenBlockNode(BlockNode bn) {
+ FlatNode begin=null;
+ FlatNode end=null;
+ for(int i=0; i<bn.size(); i++) {
+ NodePair np=flattenBlockStatementNode(bn.get(i));
+ FlatNode np_begin=np.getBegin();
+ FlatNode np_end=np.getEnd();
+ if (begin==null) {
+ begin=np_begin;
+ }
+ if (end==null) {
+ end=np_end;
+ } else {
+ end.addNext(np_begin);
+ end=np_end;
+ }
}
-
- FlatAtomicEnterNode curran=null;
-
- private void flattenClass(ClassDescriptor cn) {
- Iterator methodit=cn.getMethods();
- while(methodit.hasNext()) {
- currmd=(MethodDescriptor)methodit.next();
- BlockNode bn=state.getMethodBody(currmd);
-
- if (state.DSM&&currmd.getModifiers().isAtomic()) {
- curran=new FlatAtomicEnterNode();
- } else
- curran=null;
- NodePair np=flattenBlockNode(bn);
- FlatNode fn=np.getBegin();
- if (state.THREAD&&currmd.getModifiers().isSynchronized()) {
- MethodDescriptor memd=(MethodDescriptor)typeutil.getClass("Object").getMethodTable().get("MonitorEnter");
- TempDescriptor thistd=getTempforVar(currmd.getThis());
- FlatCall fc=new FlatCall(memd, null, thistd, new TempDescriptor[0]);
- fc.addNext(fn);
- fn=fc;
- if (np.getEnd().kind()!=FKind.FlatReturnNode) {
- MethodDescriptor memdex=(MethodDescriptor)typeutil.getClass("Object").getMethodTable().get("MonitorExit");
- FlatCall fcunlock=new FlatCall(memdex, null, thistd, new TempDescriptor[0]);
- np.getEnd().addNext(fcunlock);
- FlatReturnNode rnflat=new FlatReturnNode(null);
- fcunlock.addNext(rnflat);
- }
- } else if (state.DSM&&currmd.getModifiers().isAtomic()) {
- curran.addNext(fn);
- fn=curran;
- if (np.getEnd().kind()!=FKind.FlatReturnNode) {
- FlatAtomicExitNode aen=new FlatAtomicExitNode(curran);
- np.getEnd().addNext(aen);
- FlatReturnNode rnflat=new FlatReturnNode(null);
- aen.addNext(rnflat);
- }
- } else if (np.getEnd().kind()!=FKind.FlatReturnNode) {
- FlatReturnNode rnflat=new FlatReturnNode(null);
- np.getEnd().addNext(rnflat);
- }
-
- FlatMethod fm=new FlatMethod(currmd);
- fm.addNext(fn);
- if (!currmd.isStatic())
- fm.addParameterTemp(getTempforParam(currmd.getThis()));
- for(int i=0;i<currmd.numParameters();i++) {
- fm.addParameterTemp(getTempforParam(currmd.getParameter(i)));
- }
- state.addFlatCode(currmd,fm);
- }
+ if (begin==null) {
+ end=begin=new FlatNop();
}
-
- private NodePair flattenBlockNode(BlockNode bn) {
- FlatNode begin=null;
- FlatNode end=null;
- for(int i=0;i<bn.size();i++) {
- NodePair np=flattenBlockStatementNode(bn.get(i));
- FlatNode np_begin=np.getBegin();
- FlatNode np_end=np.getEnd();
- if (begin==null) {
- begin=np_begin;
- }
- if (end==null) {
- end=np_end;
- } else {
- end.addNext(np_begin);
- end=np_end;
- }
- }
- if (begin==null) {
- end=begin=new FlatNop();
+ return new NodePair(begin,end);
+ }
+
+ private NodePair flattenBlockExpressionNode(BlockExpressionNode en) {
+ TempDescriptor tmp=TempDescriptor.tempFactory("neverused",en.getExpression().getType());
+ return flattenExpressionNode(en.getExpression(),tmp);
+ }
+
+ private NodePair flattenCastNode(CastNode cn,TempDescriptor out_temp) {
+ TempDescriptor tmp=TempDescriptor.tempFactory("tocast",cn.getExpression().getType());
+ NodePair np=flattenExpressionNode(cn.getExpression(), tmp);
+ FlatCastNode fcn=new FlatCastNode(cn.getType(), tmp, out_temp);
+ np.getEnd().addNext(fcn);
+ return new NodePair(np.getBegin(),fcn);
+ }
+
+ private NodePair flattenLiteralNode(LiteralNode ln,TempDescriptor out_temp) {
+ FlatLiteralNode fln=new FlatLiteralNode(ln.getType(), ln.getValue(), out_temp);
+ return new NodePair(fln,fln);
+ }
+
+ private NodePair flattenCreateObjectNode(CreateObjectNode con,TempDescriptor out_temp) {
+ TypeDescriptor td=con.getType();
+ if (!td.isArray()) {
+ FlatNew fn=new FlatNew(td, out_temp, con.isGlobal());
+ TempDescriptor[] temps=new TempDescriptor[con.numArgs()];
+ FlatNode last=fn;
+ // Build arguments
+ for(int i=0; i<con.numArgs(); i++) {
+ ExpressionNode en=con.getArg(i);
+ TempDescriptor tmp=TempDescriptor.tempFactory("arg",en.getType());
+ temps[i]=tmp;
+ NodePair np=flattenExpressionNode(en, tmp);
+ last.addNext(np.getBegin());
+ last=np.getEnd();
+ }
+ MethodDescriptor md=con.getConstructor();
+ //Call to constructor
+ FlatCall fc=new FlatCall(md, null, out_temp, temps);
+ last.addNext(fc);
+ last=fc;
+ if (td.getClassDesc().hasFlags()) {
+ // if (con.getFlagEffects()!=null) {
+ FlatFlagActionNode ffan=new FlatFlagActionNode(FlatFlagActionNode.NEWOBJECT);
+ FlagEffects fes=con.getFlagEffects();
+ TempDescriptor flagtemp=out_temp;
+ if (fes!=null) {
+ for(int j=0; j<fes.numEffects(); j++) {
+ FlagEffect fe=fes.getEffect(j);
+ ffan.addFlagAction(flagtemp, fe.getFlag(), fe.getStatus());
+ }
+ for(int j=0; j<fes.numTagEffects(); j++) {
+ TagEffect te=fes.getTagEffect(j);
+ TempDescriptor tagtemp=getTempforVar(te.getTag());
+
+ ffan.addTagAction(flagtemp, te.getTag().getTag(), tagtemp, te.getStatus());
+ }
+ } else {
+ ffan.addFlagAction(flagtemp, null, false);
}
- return new NodePair(begin,end);
+ last.addNext(ffan);
+ last=ffan;
+ }
+ return new NodePair(fn,last);
+ } else {
+ FlatNode first=null;
+ FlatNode last=null;
+ TempDescriptor[] temps=new TempDescriptor[con.numArgs()];
+ for (int i=0; i<con.numArgs(); i++) {
+ ExpressionNode en=con.getArg(i);
+ TempDescriptor tmp=TempDescriptor.tempFactory("arg",en.getType());
+ temps[i]=tmp;
+ NodePair np=flattenExpressionNode(en, tmp);
+ if (first==null)
+ first=np.getBegin();
+ else
+ last.addNext(np.getBegin());
+ last=np.getEnd();
+
+ TempDescriptor tmp2=(i==0) ?
+ out_temp :
+ TempDescriptor.tempFactory("arg",en.getType());
+ }
+ FlatNew fn=new FlatNew(td, out_temp, temps[0], con.isGlobal());
+ last.addNext(fn);
+ if (temps.length>1) {
+ 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 index<temp[i]
+ TempDescriptor new_tmp=TempDescriptor.tempFactory("tmp",td);
+ FlatNew fn=new FlatNew(td, new_tmp, temparray[i+1], isglobal);
+ FlatSetElementNode fsen=new FlatSetElementNode(tmp,index,new_tmp);
+ // index=index+1
+ FlatOpNode fon=new FlatOpNode(index,index,tmpone,new Operation(Operation.ADD));
+ //jump out
+ fln.addNext(fln2);
+ fln2.addNext(fcomp);
+ fcomp.addNext(fcb);
+ fcb.addTrueNext(fn);
+ fcb.addFalseNext(fnop);
+ fn.addNext(fsen);
+ //Recursive call here
+ if ((i+2)<temparray.length) {
+ NodePair np2=generateNewArrayLoop(temparray, td.dereference(), new_tmp, i+1, isglobal);
+ fsen.addNext(np2.getBegin());
+ np2.getEnd().addNext(fon);
+ } else {
+ fsen.addNext(fon);
}
-
- private NodePair flattenCastNode(CastNode cn,TempDescriptor out_temp) {
- TempDescriptor tmp=TempDescriptor.tempFactory("tocast",cn.getExpression().getType());
- NodePair np=flattenExpressionNode(cn.getExpression(), tmp);
- FlatCastNode fcn=new FlatCastNode(cn.getType(), tmp, out_temp);
- np.getEnd().addNext(fcn);
- return new NodePair(np.getBegin(),fcn);
+ fon.addNext(fcomp);
+ return new NodePair(fln, fnop);
+ }
+
+ private NodePair flattenMethodInvokeNode(MethodInvokeNode min,TempDescriptor out_temp) {
+ TempDescriptor[] temps=new TempDescriptor[min.numArgs()];
+ FlatNode first=null;
+ FlatNode last=null;
+ TempDescriptor thisarg=null;
+
+ if (min.getExpression()!=null) {
+ thisarg=TempDescriptor.tempFactory("thisarg",min.getExpression().getType());
+ NodePair np=flattenExpressionNode(min.getExpression(),thisarg);
+ first=np.getBegin();
+ last=np.getEnd();
}
- private NodePair flattenLiteralNode(LiteralNode ln,TempDescriptor out_temp) {
- FlatLiteralNode fln=new FlatLiteralNode(ln.getType(), ln.getValue(), out_temp);
- return new NodePair(fln,fln);
+ //Build arguments
+ for(int i=0; i<min.numArgs(); i++) {
+ ExpressionNode en=min.getArg(i);
+ TempDescriptor td=TempDescriptor.tempFactory("arg",en.getType());
+ temps[i]=td;
+ NodePair np=flattenExpressionNode(en, td);
+ if (first==null)
+ first=np.getBegin();
+ else
+ last.addNext(np.getBegin());
+ last=np.getEnd();
}
- private NodePair flattenCreateObjectNode(CreateObjectNode con,TempDescriptor out_temp) {
- TypeDescriptor td=con.getType();
- if (!td.isArray()) {
- FlatNew fn=new FlatNew(td, out_temp, con.isGlobal());
- TempDescriptor[] temps=new TempDescriptor[con.numArgs()];
- FlatNode last=fn;
- // Build arguments
- for(int i=0;i<con.numArgs();i++) {
- ExpressionNode en=con.getArg(i);
- TempDescriptor tmp=TempDescriptor.tempFactory("arg",en.getType());
- temps[i]=tmp;
- NodePair np=flattenExpressionNode(en, tmp);
- last.addNext(np.getBegin());
- last=np.getEnd();
- }
- MethodDescriptor md=con.getConstructor();
- //Call to constructor
- FlatCall fc=new FlatCall(md, null, out_temp, temps);
- last.addNext(fc);
- last=fc;
- if (td.getClassDesc().hasFlags()) {
- // if (con.getFlagEffects()!=null) {
- FlatFlagActionNode ffan=new FlatFlagActionNode(FlatFlagActionNode.NEWOBJECT);
- FlagEffects fes=con.getFlagEffects();
- TempDescriptor flagtemp=out_temp;
- if (fes!=null) {
- for(int j=0;j<fes.numEffects();j++) {
- FlagEffect fe=fes.getEffect(j);
- ffan.addFlagAction(flagtemp, fe.getFlag(), fe.getStatus());
- }
- for(int j=0;j<fes.numTagEffects();j++) {
- TagEffect te=fes.getTagEffect(j);
- TempDescriptor tagtemp=getTempforVar(te.getTag());
-
- ffan.addTagAction(flagtemp, te.getTag().getTag(), tagtemp, te.getStatus());
- }
- } else {
- ffan.addFlagAction(flagtemp, null, false);
- }
- last.addNext(ffan);
- last=ffan;
- }
- return new NodePair(fn,last);
- } else {
- FlatNode first=null;
- FlatNode last=null;
- TempDescriptor[] temps=new TempDescriptor[con.numArgs()];
- for (int i=0;i<con.numArgs();i++) {
- ExpressionNode en=con.getArg(i);
- TempDescriptor tmp=TempDescriptor.tempFactory("arg",en.getType());
- temps[i]=tmp;
- NodePair np=flattenExpressionNode(en, tmp);
- if (first==null)
- first=np.getBegin();
- else
- last.addNext(np.getBegin());
- last=np.getEnd();
-
- TempDescriptor tmp2=(i==0)?
- out_temp:
- TempDescriptor.tempFactory("arg",en.getType());
- }
- FlatNew fn=new FlatNew(td, out_temp, temps[0], con.isGlobal());
- last.addNext(fn);
- if (temps.length>1) {
- 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<temp[i]
- TempDescriptor new_tmp=TempDescriptor.tempFactory("tmp",td);
- FlatNew fn=new FlatNew(td, new_tmp, temparray[i+1], isglobal);
- FlatSetElementNode fsen=new FlatSetElementNode(tmp,index,new_tmp);
- // index=index+1
- FlatOpNode fon=new FlatOpNode(index,index,tmpone,new Operation(Operation.ADD));
- //jump out
- fln.addNext(fln2);
- fln2.addNext(fcomp);
- fcomp.addNext(fcb);
- fcb.addTrueNext(fn);
- fcb.addFalseNext(fnop);
- fn.addNext(fsen);
- //Recursive call here
- if ((i+2)<temparray.length) {
- NodePair np2=generateNewArrayLoop(temparray, td.dereference(), new_tmp, i+1, isglobal);
- fsen.addNext(np2.getBegin());
- np2.getEnd().addNext(fon);
+ if (an.getDest().kind()==Kind.FieldAccessNode) {
+ //We are assigning an object field
+
+ FieldAccessNode fan=(FieldAccessNode)an.getDest();
+ ExpressionNode en=fan.getExpression();
+ TempDescriptor dst_tmp=TempDescriptor.tempFactory("dst",en.getType());
+ NodePair np_baseexp=flattenExpressionNode(en, dst_tmp);
+ if (first==null)
+ first=np_baseexp.getBegin();
+ else
+ last.addNext(np_baseexp.getBegin());
+ last=np_baseexp.getEnd();
+
+ //See if we need to perform an operation
+ if (base!=null) {
+ //If it is a preinc we need to store the initial value
+ TempDescriptor src_tmp2=pre ? TempDescriptor.tempFactory("src",an.getDest().getType()) : out_temp;
+ TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3",an.getDest().getType());
+ FlatFieldNode ffn=new FlatFieldNode(fan.getField(), dst_tmp, src_tmp2);
+ last.addNext(ffn);
+ last=ffn;
+
+ if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) {
+ ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
+ MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)});
+ FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp});
+ src_tmp=tmp;
+ last.addNext(fc);
+ last=fc;
} else {
- fsen.addNext(fon);
+ FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base);
+ src_tmp=tmp;
+ last.addNext(fon);
+ last=fon;
}
- fon.addNext(fcomp);
- return new NodePair(fln, fnop);
- }
+ }
+
+ FlatSetFieldNode fsfn=new FlatSetFieldNode(dst_tmp, fan.getField(), src_tmp);
+ last.addNext(fsfn);
+ last=fsfn;
+ if (pre) {
+ FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN));
+ fsfn.addNext(fon2);
+ last=fon2;
+ }
+ return new NodePair(first, last);
+ } else if (an.getDest().kind()==Kind.ArrayAccessNode) {
+ //We are assigning an array element
+
+
+ ArrayAccessNode aan=(ArrayAccessNode)an.getDest();
+ ExpressionNode en=aan.getExpression();
+ ExpressionNode enindex=aan.getIndex();
+ TempDescriptor dst_tmp=TempDescriptor.tempFactory("dst",en.getType());
+ TempDescriptor index_tmp=TempDescriptor.tempFactory("index",enindex.getType());
+ NodePair np_baseexp=flattenExpressionNode(en, dst_tmp);
+ NodePair np_indexexp=flattenExpressionNode(enindex, index_tmp);
+ if (first==null)
+ first=np_baseexp.getBegin();
+ else
+ last.addNext(np_baseexp.getBegin());
+ np_baseexp.getEnd().addNext(np_indexexp.getBegin());
+ last=np_indexexp.getEnd();
+
+ //See if we need to perform an operation
+ if (base!=null) {
+ //If it is a preinc we need to store the initial value
+ TempDescriptor src_tmp2=pre ? TempDescriptor.tempFactory("src",an.getDest().getType()) : out_temp;
+ TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3",an.getDest().getType());
+
+ FlatElementNode fen=new FlatElementNode(dst_tmp, index_tmp, src_tmp2);
+ last.addNext(fen);
+ last=fen;
+
+ if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) {
+ ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
+ MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)});
+ FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp});
+ src_tmp=tmp;
+ last.addNext(fc);
+ last=fc;
+ } else {
- private NodePair flattenMethodInvokeNode(MethodInvokeNode min,TempDescriptor out_temp) {
- TempDescriptor[] temps=new TempDescriptor[min.numArgs()];
- FlatNode first=null;
- FlatNode last=null;
- TempDescriptor thisarg=null;
-
- if (min.getExpression()!=null) {
- thisarg=TempDescriptor.tempFactory("thisarg",min.getExpression().getType());
- NodePair np=flattenExpressionNode(min.getExpression(),thisarg);
- first=np.getBegin();
- last=np.getEnd();
- }
-
- //Build arguments
- for(int i=0;i<min.numArgs();i++) {
- ExpressionNode en=min.getArg(i);
- TempDescriptor td=TempDescriptor.tempFactory("arg",en.getType());
- temps[i]=td;
- NodePair np=flattenExpressionNode(en, td);
- if (first==null)
- first=np.getBegin();
- else
- last.addNext(np.getBegin());
- last=np.getEnd();
- }
- 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
+ FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base);
+ src_tmp=tmp;
+ last.addNext(fon);
+ last=fon;
+ }
+ }
+
+
+ FlatSetElementNode fsen=new FlatSetElementNode(dst_tmp, index_tmp, src_tmp);
+ last.addNext(fsen);
+ last=fsen;
+ if (pre) {
+ FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN));
+ fsen.addNext(fon2);
+ last=fon2;
+ }
+ return new NodePair(first, last);
+ } else if (an.getDest().kind()==Kind.NameNode) {
+ //We could be assigning a field or variable
+ NameNode nn=(NameNode)an.getDest();
+ if (nn.getExpression()!=null) {
+ //It is a field
+ FieldAccessNode fan=(FieldAccessNode)nn.getExpression();
+ ExpressionNode en=fan.getExpression();
+ TempDescriptor dst_tmp=TempDescriptor.tempFactory("dst",en.getType());
+ NodePair np_baseexp=flattenExpressionNode(en, dst_tmp);
+ if (first==null)
+ first=np_baseexp.getBegin();
+ else
+ last.addNext(np_baseexp.getBegin());
+ last=np_baseexp.getEnd();
+
+ //See if we need to perform an operation
+ if (base!=null) {
+ //If it is a preinc we need to store the initial value
+ TempDescriptor src_tmp2=pre ? TempDescriptor.tempFactory("src",an.getDest().getType()) : out_temp;
+ TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3",an.getDest().getType());
+
+ FlatFieldNode ffn=new FlatFieldNode(fan.getField(), dst_tmp, src_tmp2);
+ last.addNext(ffn);
+ last=ffn;
+
+
+ if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) {
+ ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
+ MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)});
+ FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp});
+ src_tmp=tmp;
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);
- }
+ last=fc;
+ } else {
+ FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base);
+ src_tmp=tmp;
+ last.addNext(fon);
+ last=fon;
+ }
+ }
- 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;
+ FlatSetFieldNode fsfn=new FlatSetFieldNode(dst_tmp, fan.getField(), src_tmp);
+ last.addNext(fsfn);
+ last=fsfn;
+ if (pre) {
+ FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN));
+ fsfn.addNext(fon2);
+ last=fon2;
}
-
- if (an.getDest().kind()==Kind.FieldAccessNode) {
- //We are assigning an object field
-
- FieldAccessNode fan=(FieldAccessNode)an.getDest();
- ExpressionNode en=fan.getExpression();
- TempDescriptor dst_tmp=TempDescriptor.tempFactory("dst",en.getType());
- NodePair np_baseexp=flattenExpressionNode(en, dst_tmp);
+ return new NodePair(first, last);
+ } else {
+ if (nn.getField()!=null) {
+ //It is a field
+ //Get src value
+
+ //See if we need to perform an operation
+ if (base!=null) {
+ //If it is a preinc we need to store the initial value
+ TempDescriptor src_tmp2=pre ? TempDescriptor.tempFactory("src",an.getDest().getType()) : out_temp;
+ TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3",an.getDest().getType());
+
+ FlatFieldNode ffn=new FlatFieldNode(nn.getField(), getTempforVar(nn.getVar()), src_tmp2);
if (first==null)
- first=np_baseexp.getBegin();
- else
- last.addNext(np_baseexp.getBegin());
- last=np_baseexp.getEnd();
-
- //See if we need to perform an operation
- if (base!=null) {
- //If it is a preinc we need to store the initial value
- TempDescriptor src_tmp2=pre?TempDescriptor.tempFactory("src",an.getDest().getType()):out_temp;
- TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3",an.getDest().getType());
- FlatFieldNode ffn=new FlatFieldNode(fan.getField(), dst_tmp, src_tmp2);
- last.addNext(ffn);
- last=ffn;
-
- if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) {
- ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
- MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)});
- FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp});
- src_tmp=tmp;
- last.addNext(fc);
- last=fc;
- } else {
- FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base);
- src_tmp=tmp;
- last.addNext(fon);
- last=fon;
- }
+ first=ffn;
+ else {
+ last.addNext(ffn);
}
+ last=ffn;
- FlatSetFieldNode fsfn=new FlatSetFieldNode(dst_tmp, fan.getField(), src_tmp);
- last.addNext(fsfn);
- last=fsfn;
- if (pre) {
- FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN));
- fsfn.addNext(fon2);
- last=fon2;
+
+ if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) {
+ ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
+ MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)});
+ FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp});
+ src_tmp=tmp;
+ last.addNext(fc);
+ last=fc;
+ } else {
+ FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base);
+ src_tmp=tmp;
+ last.addNext(fon);
+ last=fon;
}
- return new NodePair(first, last);
- } else if (an.getDest().kind()==Kind.ArrayAccessNode) {
- //We are assigning an array element
-
-
- ArrayAccessNode aan=(ArrayAccessNode)an.getDest();
- ExpressionNode en=aan.getExpression();
- ExpressionNode enindex=aan.getIndex();
- TempDescriptor dst_tmp=TempDescriptor.tempFactory("dst",en.getType());
- TempDescriptor index_tmp=TempDescriptor.tempFactory("index",enindex.getType());
- NodePair np_baseexp=flattenExpressionNode(en, dst_tmp);
- NodePair np_indexexp=flattenExpressionNode(enindex, index_tmp);
- if (first==null)
- first=np_baseexp.getBegin();
- else
- last.addNext(np_baseexp.getBegin());
- np_baseexp.getEnd().addNext(np_indexexp.getBegin());
- last=np_indexexp.getEnd();
-
- //See if we need to perform an operation
- if (base!=null) {
- //If it is a preinc we need to store the initial value
- TempDescriptor src_tmp2=pre?TempDescriptor.tempFactory("src",an.getDest().getType()):out_temp;
- TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3",an.getDest().getType());
-
- FlatElementNode fen=new FlatElementNode(dst_tmp, index_tmp, src_tmp2);
- last.addNext(fen);
- last=fen;
-
- if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) {
- ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
- MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)});
- FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp});
- src_tmp=tmp;
- last.addNext(fc);
- last=fc;
- } else {
-
-
- FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base);
- src_tmp=tmp;
- last.addNext(fon);
- last=fon;
- }
+ }
+
+ FlatSetFieldNode fsfn=new FlatSetFieldNode(getTempforVar(nn.getVar()), nn.getField(), src_tmp);
+ if (first==null) {
+ first=fsfn;
+ } else {
+ last.addNext(fsfn);
+ }
+ last=fsfn;
+ if (pre) {
+ FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN));
+ fsfn.addNext(fon2);
+ last=fon2;
+ }
+ return new NodePair(first, last);
+ } else {
+ //It is a variable
+ //See if we need to perform an operation
+
+ if (base!=null) {
+ //If it is a preinc we need to store the initial value
+ TempDescriptor src_tmp2=getTempforVar(nn.getVar());
+ TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3",an.getDest().getType());
+ if (!pre) {
+ FlatOpNode fon=new FlatOpNode(out_temp, src_tmp2, null, new Operation(Operation.ASSIGN));
+ if (first==null)
+ first=fon;
+ else
+ last.addNext(fon);
+ last=fon;
}
- FlatSetElementNode fsen=new FlatSetElementNode(dst_tmp, index_tmp, src_tmp);
- last.addNext(fsen);
- last=fsen;
- if (pre) {
- FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN));
- fsen.addNext(fon2);
- last=fon2;
- }
- return new NodePair(first, last);
- } else if (an.getDest().kind()==Kind.NameNode) {
- //We could be assigning a field or variable
- NameNode nn=(NameNode)an.getDest();
- if (nn.getExpression()!=null) {
- //It is a field
- FieldAccessNode fan=(FieldAccessNode)nn.getExpression();
- ExpressionNode en=fan.getExpression();
- TempDescriptor dst_tmp=TempDescriptor.tempFactory("dst",en.getType());
- NodePair np_baseexp=flattenExpressionNode(en, dst_tmp);
- if (first==null)
- first=np_baseexp.getBegin();
- else
- last.addNext(np_baseexp.getBegin());
- last=np_baseexp.getEnd();
-
- //See if we need to perform an operation
- if (base!=null) {
- //If it is a preinc we need to store the initial value
- TempDescriptor src_tmp2=pre?TempDescriptor.tempFactory("src",an.getDest().getType()):out_temp;
- TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3",an.getDest().getType());
-
- FlatFieldNode ffn=new FlatFieldNode(fan.getField(), dst_tmp, src_tmp2);
- last.addNext(ffn);
- last=ffn;
-
-
- if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) {
- ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
- MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)});
- FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp});
- src_tmp=tmp;
- last.addNext(fc);
- last=fc;
- } else {
- FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base);
- src_tmp=tmp;
- last.addNext(fon);
- last=fon;
- }
- }
-
-
- FlatSetFieldNode fsfn=new FlatSetFieldNode(dst_tmp, fan.getField(), src_tmp);
- last.addNext(fsfn);
- last=fsfn;
- if (pre) {
- FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN));
- fsfn.addNext(fon2);
- last=fon2;
- }
- return new NodePair(first, last);
+ if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) {
+ ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
+ MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)});
+ FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp});
+ if (first==null)
+ first=fc;
+ else
+ last.addNext(fc);
+ src_tmp=tmp;
+ last=fc;
} else {
- if (nn.getField()!=null) {
- //It is a field
- //Get src value
-
- //See if we need to perform an operation
- if (base!=null) {
- //If it is a preinc we need to store the initial value
- TempDescriptor src_tmp2=pre?TempDescriptor.tempFactory("src",an.getDest().getType()):out_temp;
- TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3",an.getDest().getType());
-
- FlatFieldNode ffn=new FlatFieldNode(nn.getField(), getTempforVar(nn.getVar()), src_tmp2);
- if (first==null)
- first=ffn;
- else {
- last.addNext(ffn);
- }
- last=ffn;
-
-
- if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) {
- ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
- MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)});
- FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp});
- src_tmp=tmp;
- last.addNext(fc);
- last=fc;
- } else {
- FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base);
- src_tmp=tmp;
- last.addNext(fon);
- last=fon;
- }
- }
-
- FlatSetFieldNode fsfn=new FlatSetFieldNode(getTempforVar(nn.getVar()), nn.getField(), src_tmp);
- if (first==null) {
- first=fsfn;
- } else {
- last.addNext(fsfn);
- }
- last=fsfn;
- if (pre) {
- FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN));
- fsfn.addNext(fon2);
- last=fon2;
- }
- return new NodePair(first, last);
- } else {
- //It is a variable
- //See if we need to perform an operation
-
- if (base!=null) {
- //If it is a preinc we need to store the initial value
- TempDescriptor src_tmp2=getTempforVar(nn.getVar());
- TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3",an.getDest().getType());
- if (!pre) {
- FlatOpNode fon=new FlatOpNode(out_temp, src_tmp2, null, new Operation(Operation.ASSIGN));
- if (first==null)
- first=fon;
- else
- last.addNext(fon);
- last=fon;
- }
-
-
- if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) {
- ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
- MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)});
- FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp});
- if (first==null)
- first=fc;
- else
- last.addNext(fc);
- src_tmp=tmp;
- last=fc;
- } else {
- FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base);
- if (first==null)
- first=fon;
- else
- last.addNext(fon);
- src_tmp=tmp;
- last=fon;
- }
- }
-
- FlatOpNode fon=new FlatOpNode(getTempforVar(nn.getVar()), src_tmp, null, new Operation(Operation.ASSIGN));
- last.addNext(fon);
- last=fon;
- if (pre) {
- FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN));
- fon.addNext(fon2);
- last=fon2;
- }
- return new NodePair(first, last);
- }
+ FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base);
+ if (first==null)
+ first=fon;
+ else
+ last.addNext(fon);
+ src_tmp=tmp;
+ last=fon;
}
- }
- throw new Error();
+ }
+
+ FlatOpNode fon=new FlatOpNode(getTempforVar(nn.getVar()), src_tmp, null, new Operation(Operation.ASSIGN));
+ last.addNext(fon);
+ last=fon;
+ if (pre) {
+ FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN));
+ fon.addNext(fon2);
+ last=fon2;
+ }
+ return new NodePair(first, last);
+ }
+ }
+ }
+ throw new Error();
+ }
+
+ private NodePair flattenNameNode(NameNode nn,TempDescriptor out_temp) {
+ if (nn.getExpression()!=null) {
+ /* Hack - use subtree instead */
+ return flattenExpressionNode(nn.getExpression(),out_temp);
+ } else if (nn.getField()!=null) {
+ TempDescriptor tmp=getTempforVar(nn.getVar());
+ FlatFieldNode ffn=new FlatFieldNode(nn.getField(), tmp, out_temp);
+ return new NodePair(ffn,ffn);
+ } else {
+ TempDescriptor tmp=getTempforVar(nn.isTag() ? nn.getTagVar() : nn.getVar());
+ if (nn.isTag()) {
+ //propagate tag
+ out_temp.setTag(tmp.getTag());
+ }
+ FlatOpNode fon=new FlatOpNode(out_temp, tmp, null, new Operation(Operation.ASSIGN));
+ return new NodePair(fon,fon);
+ }
+ }
+
+ private NodePair flattenOpNode(OpNode on,TempDescriptor out_temp) {
+ TempDescriptor temp_left=TempDescriptor.tempFactory("leftop",on.getLeft().getType());
+ TempDescriptor temp_right=null;
+
+ Operation op=on.getOp();
+
+ NodePair left=flattenExpressionNode(on.getLeft(),temp_left);
+ NodePair right;
+ if (on.getRight()!=null) {
+ temp_right=TempDescriptor.tempFactory("rightop",on.getRight().getType());
+ right=flattenExpressionNode(on.getRight(),temp_right);
+ } else {
+ FlatNop nop=new FlatNop();
+ right=new NodePair(nop,nop);
}
- private NodePair flattenNameNode(NameNode nn,TempDescriptor out_temp) {
- if (nn.getExpression()!=null) {
- /* Hack - use subtree instead */
- return flattenExpressionNode(nn.getExpression(),out_temp);
- } else if (nn.getField()!=null) {
- TempDescriptor tmp=getTempforVar(nn.getVar());
- FlatFieldNode ffn=new FlatFieldNode(nn.getField(), tmp, out_temp);
- return new NodePair(ffn,ffn);
- } else {
- TempDescriptor tmp=getTempforVar(nn.isTag()?nn.getTagVar():nn.getVar());
- if (nn.isTag()) {
- //propagate tag
- out_temp.setTag(tmp.getTag());
- }
- FlatOpNode fon=new FlatOpNode(out_temp, tmp, null, new Operation(Operation.ASSIGN));
- return new NodePair(fon,fon);
- }
+ if (op.getOp()==Operation.LOGIC_OR) {
+ /* Need to do shortcircuiting */
+ FlatCondBranch fcb=new FlatCondBranch(temp_left);
+ FlatOpNode fon1=new FlatOpNode(out_temp,temp_left,null,new Operation(Operation.ASSIGN));
+ FlatOpNode fon2=new FlatOpNode(out_temp,temp_right,null,new Operation(Operation.ASSIGN));
+ FlatNop fnop=new FlatNop();
+ left.getEnd().addNext(fcb);
+ fcb.addFalseNext(right.getBegin());
+ right.getEnd().addNext(fon2);
+ fon2.addNext(fnop);
+ fcb.addTrueNext(fon1);
+ fon1.addNext(fnop);
+ return new NodePair(left.getBegin(), fnop);
+ } else if (op.getOp()==Operation.LOGIC_AND) {
+ /* Need to do shortcircuiting */
+ FlatCondBranch fcb=new FlatCondBranch(temp_left);
+ FlatOpNode fon1=new FlatOpNode(out_temp,temp_left,null,new Operation(Operation.ASSIGN));
+ FlatOpNode fon2=new FlatOpNode(out_temp,temp_right,null,new Operation(Operation.ASSIGN));
+ FlatNop fnop=new FlatNop();
+ left.getEnd().addNext(fcb);
+ fcb.addTrueNext(right.getBegin());
+ right.getEnd().addNext(fon2);
+ fon2.addNext(fnop);
+ fcb.addFalseNext(fon1);
+ fon1.addNext(fnop);
+ return new NodePair(left.getBegin(), fnop);
+ } else if (op.getOp()==Operation.ADD&&on.getLeft().getType().isString()) {
+ //We have a string concatenate
+ ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
+ MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat", new TypeDescriptor[] {new TypeDescriptor(stringcd)});
+ FlatCall fc=new FlatCall(concatmd, out_temp, temp_left, new TempDescriptor[] {temp_right});
+ left.getEnd().addNext(right.getBegin());
+ right.getEnd().addNext(fc);
+ return new NodePair(left.getBegin(), fc);
}
- private NodePair flattenOpNode(OpNode on,TempDescriptor out_temp) {
- TempDescriptor temp_left=TempDescriptor.tempFactory("leftop",on.getLeft().getType());
- TempDescriptor temp_right=null;
+ FlatOpNode fon=new FlatOpNode(out_temp,temp_left,temp_right,op);
+ left.getEnd().addNext(right.getBegin());
+ right.getEnd().addNext(fon);
+ return new NodePair(left.getBegin(),fon);
+ }
- Operation op=on.getOp();
+ private NodePair flattenExpressionNode(ExpressionNode en, TempDescriptor out_temp) {
+ switch(en.kind()) {
+ case Kind.AssignmentNode:
+ return flattenAssignmentNode((AssignmentNode)en,out_temp);
- NodePair left=flattenExpressionNode(on.getLeft(),temp_left);
- NodePair right;
- if (on.getRight()!=null) {
- temp_right=TempDescriptor.tempFactory("rightop",on.getRight().getType());
- right=flattenExpressionNode(on.getRight(),temp_right);
- } else {
- FlatNop nop=new FlatNop();
- right=new NodePair(nop,nop);
- }
+ case Kind.CastNode:
+ return flattenCastNode((CastNode)en,out_temp);
- if (op.getOp()==Operation.LOGIC_OR) {
- /* Need to do shortcircuiting */
- FlatCondBranch fcb=new FlatCondBranch(temp_left);
- FlatOpNode fon1=new FlatOpNode(out_temp,temp_left,null,new Operation(Operation.ASSIGN));
- FlatOpNode fon2=new FlatOpNode(out_temp,temp_right,null,new Operation(Operation.ASSIGN));
- FlatNop fnop=new FlatNop();
- left.getEnd().addNext(fcb);
- fcb.addFalseNext(right.getBegin());
- right.getEnd().addNext(fon2);
- fon2.addNext(fnop);
- fcb.addTrueNext(fon1);
- fon1.addNext(fnop);
- return new NodePair(left.getBegin(), fnop);
- } else if (op.getOp()==Operation.LOGIC_AND) {
- /* Need to do shortcircuiting */
- FlatCondBranch fcb=new FlatCondBranch(temp_left);
- FlatOpNode fon1=new FlatOpNode(out_temp,temp_left,null,new Operation(Operation.ASSIGN));
- FlatOpNode fon2=new FlatOpNode(out_temp,temp_right,null,new Operation(Operation.ASSIGN));
- FlatNop fnop=new FlatNop();
- left.getEnd().addNext(fcb);
- fcb.addTrueNext(right.getBegin());
- right.getEnd().addNext(fon2);
- fon2.addNext(fnop);
- fcb.addFalseNext(fon1);
- fon1.addNext(fnop);
- return new NodePair(left.getBegin(), fnop);
- } else if (op.getOp()==Operation.ADD&&on.getLeft().getType().isString()) {
- //We have a string concatenate
- ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
- MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat", new TypeDescriptor[] {new TypeDescriptor(stringcd)});
- FlatCall fc=new FlatCall(concatmd, out_temp, temp_left, new TempDescriptor[] {temp_right});
- left.getEnd().addNext(right.getBegin());
- right.getEnd().addNext(fc);
- return new NodePair(left.getBegin(), fc);
- }
+ case Kind.CreateObjectNode:
+ return flattenCreateObjectNode((CreateObjectNode)en,out_temp);
- FlatOpNode fon=new FlatOpNode(out_temp,temp_left,temp_right,op);
- left.getEnd().addNext(right.getBegin());
- right.getEnd().addNext(fon);
- return new NodePair(left.getBegin(),fon);
- }
+ case Kind.FieldAccessNode:
+ return flattenFieldAccessNode((FieldAccessNode)en,out_temp);
- private NodePair flattenExpressionNode(ExpressionNode en, TempDescriptor out_temp) {
- switch(en.kind()) {
- case Kind.AssignmentNode:
- return flattenAssignmentNode((AssignmentNode)en,out_temp);
- case Kind.CastNode:
- return flattenCastNode((CastNode)en,out_temp);
- case Kind.CreateObjectNode:
- return flattenCreateObjectNode((CreateObjectNode)en,out_temp);
- case Kind.FieldAccessNode:
- return flattenFieldAccessNode((FieldAccessNode)en,out_temp);
- case Kind.ArrayAccessNode:
- return flattenArrayAccessNode((ArrayAccessNode)en,out_temp);
- case Kind.LiteralNode:
- return flattenLiteralNode((LiteralNode)en,out_temp);
- case Kind.MethodInvokeNode:
- return flattenMethodInvokeNode((MethodInvokeNode)en,out_temp);
- case Kind.NameNode:
- return flattenNameNode((NameNode)en,out_temp);
- case Kind.OpNode:
- return flattenOpNode((OpNode)en,out_temp);
- }
- throw new Error();
- }
+ case Kind.ArrayAccessNode:
+ return flattenArrayAccessNode((ArrayAccessNode)en,out_temp);
- private NodePair flattenDeclarationNode(DeclarationNode dn) {
- VarDescriptor vd=dn.getVarDescriptor();
- TempDescriptor td=getTempforVar(vd);
- if (dn.getExpression()!=null)
- return flattenExpressionNode(dn.getExpression(),td);
- else {
- FlatNop fn=new FlatNop();
- return new NodePair(fn,fn);
- }
- }
+ case Kind.LiteralNode:
+ return flattenLiteralNode((LiteralNode)en,out_temp);
- private NodePair flattenTagDeclarationNode(TagDeclarationNode dn) {
- TagVarDescriptor tvd=dn.getTagVarDescriptor();
- TagDescriptor tag=tvd.getTag();
- TempDescriptor tmp=getTempforVar(tvd);
- FlatTagDeclaration ftd=new FlatTagDeclaration(tag, tmp);
- return new NodePair(ftd,ftd);
- }
+ case Kind.MethodInvokeNode:
+ return flattenMethodInvokeNode((MethodInvokeNode)en,out_temp);
- private TempDescriptor getTempforParam(Descriptor d) {
- if (temptovar.containsKey(d))
- return (TempDescriptor)temptovar.get(d);
- else {
- if (d instanceof VarDescriptor) {
- VarDescriptor vd=(VarDescriptor)d;
- TempDescriptor td=TempDescriptor.paramtempFactory(vd.getName(),vd.getType());
- temptovar.put(vd,td);
- return td;
- } else if (d instanceof TagVarDescriptor) {
- TagVarDescriptor tvd=(TagVarDescriptor)d;
- TypeDescriptor tagtype=new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass));
- TempDescriptor td=TempDescriptor.paramtempFactory(tvd.getName(), tagtype, tvd.getTag());
- temptovar.put(tvd,td);
- return td;
- } else throw new Error("Unreconized Descriptor");
- }
+ case Kind.NameNode:
+ return flattenNameNode((NameNode)en,out_temp);
+
+ case Kind.OpNode:
+ return flattenOpNode((OpNode)en,out_temp);
}
-
- private TempDescriptor getTempforVar(Descriptor d) {
- if (temptovar.containsKey(d))
- return (TempDescriptor)temptovar.get(d);
- else {
- if (d instanceof VarDescriptor) {
- VarDescriptor vd=(VarDescriptor)d;
- TempDescriptor td=TempDescriptor.tempFactory(vd.getName(), vd.getType());
- temptovar.put(vd,td);
- return td;
- } else if (d instanceof TagVarDescriptor) {
- TagVarDescriptor tvd=(TagVarDescriptor)d;
- //BUGFIX TAGTYPE - add next line, modify following
- //line to tag this new type descriptor, modify
- //TempDescriptor constructor & factory to set type
- //using this Type To test, use any program with tags
- TypeDescriptor tagtype=new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass));
- TempDescriptor td=TempDescriptor.tempFactory(tvd.getName(),tagtype, tvd.getTag());
- temptovar.put(tvd,td);
- return td;
- } else throw new Error("Unrecognized Descriptor");
- }
+ throw new Error();
+ }
+
+ private NodePair flattenDeclarationNode(DeclarationNode dn) {
+ VarDescriptor vd=dn.getVarDescriptor();
+ TempDescriptor td=getTempforVar(vd);
+ if (dn.getExpression()!=null)
+ return flattenExpressionNode(dn.getExpression(),td);
+ else {
+ FlatNop fn=new FlatNop();
+ return new NodePair(fn,fn);
}
-
- private NodePair flattenIfStatementNode(IfStatementNode isn) {
- TempDescriptor cond_temp=TempDescriptor.tempFactory("condition",new TypeDescriptor(TypeDescriptor.BOOLEAN));
- NodePair cond=flattenExpressionNode(isn.getCondition(),cond_temp);
- FlatCondBranch fcb=new FlatCondBranch(cond_temp);
- NodePair true_np=flattenBlockNode(isn.getTrueBlock());
- NodePair false_np;
- FlatNop nopend=new FlatNop();
-
- if (isn.getFalseBlock()!=null)
- false_np=flattenBlockNode(isn.getFalseBlock());
- else {
- FlatNop nop=new FlatNop();
- false_np=new NodePair(nop,nop);
- }
-
- cond.getEnd().addNext(fcb);
- fcb.addTrueNext(true_np.getBegin());
- fcb.addFalseNext(false_np.getBegin());
- true_np.getEnd().addNext(nopend);
- false_np.getEnd().addNext(nopend);
- return new NodePair(cond.getBegin(), nopend);
+ }
+
+ private NodePair flattenTagDeclarationNode(TagDeclarationNode dn) {
+ TagVarDescriptor tvd=dn.getTagVarDescriptor();
+ TagDescriptor tag=tvd.getTag();
+ TempDescriptor tmp=getTempforVar(tvd);
+ FlatTagDeclaration ftd=new FlatTagDeclaration(tag, tmp);
+ return new NodePair(ftd,ftd);
+ }
+
+ private TempDescriptor getTempforParam(Descriptor d) {
+ if (temptovar.containsKey(d))
+ return (TempDescriptor)temptovar.get(d);
+ else {
+ if (d instanceof VarDescriptor) {
+ VarDescriptor vd=(VarDescriptor)d;
+ TempDescriptor td=TempDescriptor.paramtempFactory(vd.getName(),vd.getType());
+ temptovar.put(vd,td);
+ return td;
+ } else if (d instanceof TagVarDescriptor) {
+ TagVarDescriptor tvd=(TagVarDescriptor)d;
+ TypeDescriptor tagtype=new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass));
+ TempDescriptor td=TempDescriptor.paramtempFactory(tvd.getName(), tagtype, tvd.getTag());
+ temptovar.put(tvd,td);
+ return td;
+ } else throw new Error("Unreconized Descriptor");
}
-
- private NodePair flattenLoopNode(LoopNode ln) {
- if (ln.getType()==LoopNode.FORLOOP) {
- NodePair initializer=flattenBlockNode(ln.getInitializer());
- TempDescriptor cond_temp=TempDescriptor.tempFactory("condition", new TypeDescriptor(TypeDescriptor.BOOLEAN));
- NodePair condition=flattenExpressionNode(ln.getCondition(),cond_temp);
- NodePair update=flattenBlockNode(ln.getUpdate());
- NodePair body=flattenBlockNode(ln.getBody());
- FlatNode begin=initializer.getBegin();
- FlatCondBranch fcb=new FlatCondBranch(cond_temp);
- fcb.setTrueProb(State.TRUEPROB);
- fcb.setLoop();
- FlatNop nopend=new FlatNop();
- FlatBackEdge backedge=new FlatBackEdge();
-
- FlatNop nop2=new FlatNop();
- initializer.getEnd().addNext(nop2);
- nop2.addNext(condition.getBegin());
- body.getEnd().addNext(update.getBegin());
- update.getEnd().addNext(backedge);
- backedge.addNext(condition.getBegin());
- condition.getEnd().addNext(fcb);
- fcb.addFalseNext(nopend);
- fcb.addTrueNext(body.getBegin());
- return new NodePair(begin,nopend);
- } else if (ln.getType()==LoopNode.WHILELOOP) {
- TempDescriptor cond_temp=TempDescriptor.tempFactory("condition", new TypeDescriptor(TypeDescriptor.BOOLEAN));
- NodePair condition=flattenExpressionNode(ln.getCondition(),cond_temp);
- NodePair body=flattenBlockNode(ln.getBody());
- FlatNode begin=condition.getBegin();
- FlatCondBranch fcb=new FlatCondBranch(cond_temp);
- fcb.setTrueProb(State.TRUEPROB);
- fcb.setLoop();
- FlatNop nopend=new FlatNop();
- FlatBackEdge backedge=new FlatBackEdge();
-
- body.getEnd().addNext(backedge);
- backedge.addNext(condition.getBegin());
-
- condition.getEnd().addNext(fcb);
- fcb.addFalseNext(nopend);
- fcb.addTrueNext(body.getBegin());
- return new NodePair(begin,nopend);
- } else if (ln.getType()==LoopNode.DOWHILELOOP) {
- TempDescriptor cond_temp=TempDescriptor.tempFactory("condition", new TypeDescriptor(TypeDescriptor.BOOLEAN));
- NodePair condition=flattenExpressionNode(ln.getCondition(),cond_temp);
- NodePair body=flattenBlockNode(ln.getBody());
- FlatNode begin=body.getBegin();
- FlatCondBranch fcb=new FlatCondBranch(cond_temp);
- fcb.setTrueProb(State.TRUEPROB);
- fcb.setLoop();
- FlatNop nopend=new FlatNop();
- FlatBackEdge backedge=new FlatBackEdge();
-
- body.getEnd().addNext(condition.getBegin());
- condition.getEnd().addNext(fcb);
- fcb.addFalseNext(nopend);
- fcb.addTrueNext(backedge);
- backedge.addNext(body.getBegin());
- return new NodePair(begin,nopend);
- } else throw new Error();
+ }
+
+ private TempDescriptor getTempforVar(Descriptor d) {
+ if (temptovar.containsKey(d))
+ return (TempDescriptor)temptovar.get(d);
+ else {
+ if (d instanceof VarDescriptor) {
+ VarDescriptor vd=(VarDescriptor)d;
+ TempDescriptor td=TempDescriptor.tempFactory(vd.getName(), vd.getType());
+ temptovar.put(vd,td);
+ return td;
+ } else if (d instanceof TagVarDescriptor) {
+ TagVarDescriptor tvd=(TagVarDescriptor)d;
+ //BUGFIX TAGTYPE - add next line, modify following
+ //line to tag this new type descriptor, modify
+ //TempDescriptor constructor & factory to set type
+ //using this Type To test, use any program with tags
+ TypeDescriptor tagtype=new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass));
+ TempDescriptor td=TempDescriptor.tempFactory(tvd.getName(),tagtype, tvd.getTag());
+ temptovar.put(tvd,td);
+ return td;
+ } else throw new Error("Unrecognized Descriptor");
}
-
- private NodePair flattenReturnNode(ReturnNode rntree) {
- TempDescriptor retval=null;
- NodePair cond=null;
- if (rntree.getReturnExpression()!=null) {
- retval=TempDescriptor.tempFactory("ret_value", rntree.getReturnExpression().getType());
- cond=flattenExpressionNode(rntree.getReturnExpression(),retval);
- }
-
- FlatReturnNode rnflat=new FlatReturnNode(retval);
- FlatNode ln=rnflat;
- if (state.THREAD&&currmd.getModifiers().isSynchronized()) {
- MethodDescriptor memd=(MethodDescriptor)typeutil.getClass("Object").getMethodTable().get("MonitorExit");
- TempDescriptor thistd=getTempforVar(currmd.getThis());
- FlatCall fc=new FlatCall(memd, null, thistd, new TempDescriptor[0]);
- fc.addNext(ln);
- ln=fc;
- }
- if (state.DSM&&currmd.getModifiers().isAtomic()) {
- FlatAtomicExitNode faen=new FlatAtomicExitNode(curran);
- faen.addNext(ln);
- ln=faen;
- }
-
- if (cond!=null) {
- cond.getEnd().addNext(ln);
- return new NodePair(cond.getBegin(),rnflat);
- } else
- return new NodePair(ln,rnflat);
+ }
+
+ private NodePair flattenIfStatementNode(IfStatementNode isn) {
+ TempDescriptor cond_temp=TempDescriptor.tempFactory("condition",new TypeDescriptor(TypeDescriptor.BOOLEAN));
+ NodePair cond=flattenExpressionNode(isn.getCondition(),cond_temp);
+ FlatCondBranch fcb=new FlatCondBranch(cond_temp);
+ NodePair true_np=flattenBlockNode(isn.getTrueBlock());
+ NodePair false_np;
+ FlatNop nopend=new FlatNop();
+
+ if (isn.getFalseBlock()!=null)
+ false_np=flattenBlockNode(isn.getFalseBlock());
+ else {
+ FlatNop nop=new FlatNop();
+ false_np=new NodePair(nop,nop);
}
- private NodePair flattenTaskExitNode(TaskExitNode ten) {
- FlatFlagActionNode ffan=new FlatFlagActionNode(FlatFlagActionNode.TASKEXIT);
- updateFlagActionNode(ffan, ten.getFlagEffects());
- NodePair fcn=flattenConstraintCheck(ten.getChecks());
- ffan.addNext(fcn.getBegin());
- FlatReturnNode rnflat=new FlatReturnNode(null);
- fcn.getEnd().addNext(rnflat);
- return new NodePair(ffan, rnflat);
+ cond.getEnd().addNext(fcb);
+ fcb.addTrueNext(true_np.getBegin());
+ fcb.addFalseNext(false_np.getBegin());
+ true_np.getEnd().addNext(nopend);
+ false_np.getEnd().addNext(nopend);
+ return new NodePair(cond.getBegin(), nopend);
+ }
+
+ private NodePair flattenLoopNode(LoopNode ln) {
+ if (ln.getType()==LoopNode.FORLOOP) {
+ NodePair initializer=flattenBlockNode(ln.getInitializer());
+ TempDescriptor cond_temp=TempDescriptor.tempFactory("condition", new TypeDescriptor(TypeDescriptor.BOOLEAN));
+ NodePair condition=flattenExpressionNode(ln.getCondition(),cond_temp);
+ NodePair update=flattenBlockNode(ln.getUpdate());
+ NodePair body=flattenBlockNode(ln.getBody());
+ FlatNode begin=initializer.getBegin();
+ FlatCondBranch fcb=new FlatCondBranch(cond_temp);
+ fcb.setTrueProb(State.TRUEPROB);
+ fcb.setLoop();
+ FlatNop nopend=new FlatNop();
+ FlatBackEdge backedge=new FlatBackEdge();
+
+ FlatNop nop2=new FlatNop();
+ initializer.getEnd().addNext(nop2);
+ nop2.addNext(condition.getBegin());
+ body.getEnd().addNext(update.getBegin());
+ update.getEnd().addNext(backedge);
+ backedge.addNext(condition.getBegin());
+ condition.getEnd().addNext(fcb);
+ fcb.addFalseNext(nopend);
+ fcb.addTrueNext(body.getBegin());
+ return new NodePair(begin,nopend);
+ } else if (ln.getType()==LoopNode.WHILELOOP) {
+ TempDescriptor cond_temp=TempDescriptor.tempFactory("condition", new TypeDescriptor(TypeDescriptor.BOOLEAN));
+ NodePair condition=flattenExpressionNode(ln.getCondition(),cond_temp);
+ NodePair body=flattenBlockNode(ln.getBody());
+ FlatNode begin=condition.getBegin();
+ FlatCondBranch fcb=new FlatCondBranch(cond_temp);
+ fcb.setTrueProb(State.TRUEPROB);
+ fcb.setLoop();
+ FlatNop nopend=new FlatNop();
+ FlatBackEdge backedge=new FlatBackEdge();
+
+ body.getEnd().addNext(backedge);
+ backedge.addNext(condition.getBegin());
+
+ condition.getEnd().addNext(fcb);
+ fcb.addFalseNext(nopend);
+ fcb.addTrueNext(body.getBegin());
+ return new NodePair(begin,nopend);
+ } else if (ln.getType()==LoopNode.DOWHILELOOP) {
+ TempDescriptor cond_temp=TempDescriptor.tempFactory("condition", new TypeDescriptor(TypeDescriptor.BOOLEAN));
+ NodePair condition=flattenExpressionNode(ln.getCondition(),cond_temp);
+ NodePair body=flattenBlockNode(ln.getBody());
+ FlatNode begin=body.getBegin();
+ FlatCondBranch fcb=new FlatCondBranch(cond_temp);
+ fcb.setTrueProb(State.TRUEPROB);
+ fcb.setLoop();
+ FlatNop nopend=new FlatNop();
+ FlatBackEdge backedge=new FlatBackEdge();
+
+ body.getEnd().addNext(condition.getBegin());
+ condition.getEnd().addNext(fcb);
+ fcb.addFalseNext(nopend);
+ fcb.addTrueNext(backedge);
+ backedge.addNext(body.getBegin());
+ return new NodePair(begin,nopend);
+ } else throw new Error();
+ }
+
+ private NodePair flattenReturnNode(ReturnNode rntree) {
+ TempDescriptor retval=null;
+ NodePair cond=null;
+ if (rntree.getReturnExpression()!=null) {
+ retval=TempDescriptor.tempFactory("ret_value", rntree.getReturnExpression().getType());
+ cond=flattenExpressionNode(rntree.getReturnExpression(),retval);
}
- private NodePair flattenConstraintCheck(Vector ccs) {
- FlatNode begin=new FlatNop();
- if (ccs==null)
- return new NodePair(begin,begin);
- FlatNode last=begin;
- for(int i=0;i<ccs.size();i++) {
- ConstraintCheck cc=(ConstraintCheck) ccs.get(i);
- /* Flatten the arguments */
- TempDescriptor[] temps=new TempDescriptor[cc.numArgs()];
- String[] vars=new String[cc.numArgs()];
- for(int j=0;j<cc.numArgs();j++) {
- ExpressionNode en=cc.getArg(j);
- TempDescriptor td=TempDescriptor.tempFactory("arg",en.getType());
- temps[j]=td;
- vars[j]=cc.getVar(j);
- NodePair np=flattenExpressionNode(en, td);
- last.addNext(np.getBegin());
- last=np.getEnd();
- }
-
- FlatCheckNode fcn=new FlatCheckNode(cc.getSpec(), vars, temps);
- last.addNext(fcn);
- last=fcn;
- }
- return new NodePair(begin,last);
+ FlatReturnNode rnflat=new FlatReturnNode(retval);
+ FlatNode ln=rnflat;
+ if (state.THREAD&&currmd.getModifiers().isSynchronized()) {
+ MethodDescriptor memd=(MethodDescriptor)typeutil.getClass("Object").getMethodTable().get("MonitorExit");
+ TempDescriptor thistd=getTempforVar(currmd.getThis());
+ FlatCall fc=new FlatCall(memd, null, thistd, new TempDescriptor[0]);
+ fc.addNext(ln);
+ ln=fc;
}
-
- private NodePair flattenSubBlockNode(SubBlockNode sbn) {
- return flattenBlockNode(sbn.getBlockNode());
+ if (state.DSM&&currmd.getModifiers().isAtomic()) {
+ FlatAtomicExitNode faen=new FlatAtomicExitNode(curran);
+ faen.addNext(ln);
+ ln=faen;
}
- private NodePair flattenAtomicNode(AtomicNode sbn) {
- NodePair np=flattenBlockNode(sbn.getBlockNode());
- FlatAtomicEnterNode faen=new FlatAtomicEnterNode();
- FlatAtomicExitNode faexn=new FlatAtomicExitNode(faen);
- faen.addNext(np.getBegin());
- np.getEnd().addNext(faexn);
- return new NodePair(faen, faexn);
+ if (cond!=null) {
+ cond.getEnd().addNext(ln);
+ return new NodePair(cond.getBegin(),rnflat);
+ } else
+ return new NodePair(ln,rnflat);
+ }
+
+ private NodePair flattenTaskExitNode(TaskExitNode ten) {
+ FlatFlagActionNode ffan=new FlatFlagActionNode(FlatFlagActionNode.TASKEXIT);
+ updateFlagActionNode(ffan, ten.getFlagEffects());
+ NodePair fcn=flattenConstraintCheck(ten.getChecks());
+ ffan.addNext(fcn.getBegin());
+ FlatReturnNode rnflat=new FlatReturnNode(null);
+ fcn.getEnd().addNext(rnflat);
+ return new NodePair(ffan, rnflat);
+ }
+
+ private NodePair flattenConstraintCheck(Vector ccs) {
+ FlatNode begin=new FlatNop();
+ if (ccs==null)
+ return new NodePair(begin,begin);
+ FlatNode last=begin;
+ for(int i=0; i<ccs.size(); i++) {
+ ConstraintCheck cc=(ConstraintCheck) ccs.get(i);
+ /* Flatten the arguments */
+ TempDescriptor[] temps=new TempDescriptor[cc.numArgs()];
+ String[] vars=new String[cc.numArgs()];
+ for(int j=0; j<cc.numArgs(); j++) {
+ ExpressionNode en=cc.getArg(j);
+ TempDescriptor td=TempDescriptor.tempFactory("arg",en.getType());
+ temps[j]=td;
+ vars[j]=cc.getVar(j);
+ NodePair np=flattenExpressionNode(en, td);
+ last.addNext(np.getBegin());
+ last=np.getEnd();
+ }
+
+ FlatCheckNode fcn=new FlatCheckNode(cc.getSpec(), vars, temps);
+ last.addNext(fcn);
+ last=fcn;
}
+ return new NodePair(begin,last);
+ }
+
+ private NodePair flattenSubBlockNode(SubBlockNode sbn) {
+ return flattenBlockNode(sbn.getBlockNode());
+ }
+
+ private NodePair flattenAtomicNode(AtomicNode sbn) {
+ NodePair np=flattenBlockNode(sbn.getBlockNode());
+ FlatAtomicEnterNode faen=new FlatAtomicEnterNode();
+ FlatAtomicExitNode faexn=new FlatAtomicExitNode(faen);
+ faen.addNext(np.getBegin());
+ np.getEnd().addNext(faexn);
+ return new NodePair(faen, faexn);
+ }
+
+ private NodePair flattenBlockStatementNode(BlockStatementNode bsn) {
+ switch(bsn.kind()) {
+ case Kind.BlockExpressionNode:
+ return flattenBlockExpressionNode((BlockExpressionNode)bsn);
+
+ case Kind.DeclarationNode:
+ return flattenDeclarationNode((DeclarationNode)bsn);
+
+ case Kind.TagDeclarationNode:
+ return flattenTagDeclarationNode((TagDeclarationNode)bsn);
+
+ case Kind.IfStatementNode:
+ return flattenIfStatementNode((IfStatementNode)bsn);
+
+ case Kind.LoopNode:
+ return flattenLoopNode((LoopNode)bsn);
+
+ case Kind.ReturnNode:
+ return flattenReturnNode((IR.Tree.ReturnNode)bsn);
+
+ case Kind.TaskExitNode:
+ return flattenTaskExitNode((IR.Tree.TaskExitNode)bsn);
+
+ case Kind.SubBlockNode:
+ return flattenSubBlockNode((SubBlockNode)bsn);
+
+ case Kind.AtomicNode:
+ return flattenAtomicNode((AtomicNode)bsn);
- private NodePair flattenBlockStatementNode(BlockStatementNode bsn) {
- switch(bsn.kind()) {
- case Kind.BlockExpressionNode:
- return flattenBlockExpressionNode((BlockExpressionNode)bsn);
-
- case Kind.DeclarationNode:
- return flattenDeclarationNode((DeclarationNode)bsn);
-
- case Kind.TagDeclarationNode:
- return flattenTagDeclarationNode((TagDeclarationNode)bsn);
-
- case Kind.IfStatementNode:
- return flattenIfStatementNode((IfStatementNode)bsn);
-
- case Kind.LoopNode:
- return flattenLoopNode((LoopNode)bsn);
-
- case Kind.ReturnNode:
- return flattenReturnNode((IR.Tree.ReturnNode)bsn);
-
- case Kind.TaskExitNode:
- return flattenTaskExitNode((IR.Tree.TaskExitNode)bsn);
-
- case Kind.SubBlockNode:
- return flattenSubBlockNode((SubBlockNode)bsn);
-
- case Kind.AtomicNode:
- return flattenAtomicNode((AtomicNode)bsn);
-
- }
- throw new Error();
}
+ throw new Error();
+ }
}
package IR.Flat;
public class FKind {
- public static final int FlatCall=1;
- public static final int FlatFieldNode=2;
- public static final int FlatSetFieldNode=3;
- public static final int FlatNew=4;
- public static final int FlatOpNode=5;
- public static final int FlatCastNode=6;
- public static final int FlatLiteralNode=7;
- public static final int FlatReturnNode=8;
- public static final int FlatCondBranch=9;
- public static final int FlatNop=10;
- public static final int FlatSetElementNode=11;
- public static final int FlatElementNode=12;
- public static final int FlatFlagActionNode=13;
- public static final int FlatCheckNode=14;
- public static final int FlatBackEdge=15;
- public static final int FlatTagDeclaration=16;
- public static final int FlatMethod=17;
- public static final int FlatAtomicEnterNode=18;
- public static final int FlatAtomicExitNode=19;
- public static final int FlatGlobalConvNode=20;
- public static final int FlatPrefetchNode=21;
+ public static final int FlatCall=1;
+ public static final int FlatFieldNode=2;
+ public static final int FlatSetFieldNode=3;
+ public static final int FlatNew=4;
+ public static final int FlatOpNode=5;
+ public static final int FlatCastNode=6;
+ public static final int FlatLiteralNode=7;
+ public static final int FlatReturnNode=8;
+ public static final int FlatCondBranch=9;
+ public static final int FlatNop=10;
+ public static final int FlatSetElementNode=11;
+ public static final int FlatElementNode=12;
+ public static final int FlatFlagActionNode=13;
+ public static final int FlatCheckNode=14;
+ public static final int FlatBackEdge=15;
+ public static final int FlatTagDeclaration=16;
+ public static final int FlatMethod=17;
+ public static final int FlatAtomicEnterNode=18;
+ public static final int FlatAtomicExitNode=19;
+ public static final int FlatGlobalConvNode=20;
+ public static final int FlatPrefetchNode=21;
}
import java.util.Vector;
public class FlatAtomicEnterNode extends FlatNode {
- private static int identifier=0;
+ private static int identifier=0;
- private int id;
+ private int id;
- public FlatAtomicEnterNode() {
- this.id=identifier++;
- }
+ public FlatAtomicEnterNode() {
+ this.id=identifier++;
+ }
- /* Returns an unique identifier for this atomic enter node */
+ /* Returns an unique identifier for this atomic enter node */
- public int getIdentifier() {
- return id;
- }
+ public int getIdentifier() {
+ return id;
+ }
- public String toString() {
- return "atomicenter";
- }
+ public String toString() {
+ return "atomicenter";
+ }
- public int kind() {
- return FKind.FlatAtomicEnterNode;
- }
+ public int kind() {
+ return FKind.FlatAtomicEnterNode;
+ }
}
import java.util.Vector;
public class FlatAtomicExitNode extends FlatNode {
- FlatAtomicEnterNode faen;
- public FlatAtomicExitNode(FlatAtomicEnterNode faen) {
- this.faen=faen;
- }
+ FlatAtomicEnterNode faen;
+ public FlatAtomicExitNode(FlatAtomicEnterNode faen) {
+ this.faen=faen;
+ }
- public FlatAtomicEnterNode getAtomicEnter() {
- return faen;
- }
+ public FlatAtomicEnterNode getAtomicEnter() {
+ return faen;
+ }
- public String toString() {
- return "atomicexit";
- }
+ public String toString() {
+ return "atomicexit";
+ }
- public int kind() {
- return FKind.FlatAtomicExitNode;
- }
+ public int kind() {
+ return FKind.FlatAtomicExitNode;
+ }
}
import java.util.Vector;
public class FlatBackEdge extends FlatNode {
- public FlatBackEdge() {
- }
+ public FlatBackEdge() {
+ }
- public String toString() {
- return "backedge";
- }
+ public String toString() {
+ return "backedge";
+ }
- public int kind() {
- return FKind.FlatBackEdge;
- }
+ public int kind() {
+ return FKind.FlatBackEdge;
+ }
}
import IR.MethodDescriptor;
public class FlatCall extends FlatNode {
- TempDescriptor args[];
- TempDescriptor this_temp;
- TempDescriptor dst;
- MethodDescriptor method;
-
- public FlatCall(MethodDescriptor md, TempDescriptor dst, TempDescriptor this_temp, TempDescriptor[] args) {
- this.method=md;
- this.dst=dst;
- this.this_temp=this_temp;
- this.args=args;
- }
+ TempDescriptor args[];
+ TempDescriptor this_temp;
+ TempDescriptor dst;
+ MethodDescriptor method;
- public MethodDescriptor getMethod() {
- return method;
- }
+ public FlatCall(MethodDescriptor md, TempDescriptor dst, TempDescriptor this_temp, TempDescriptor[] args) {
+ this.method=md;
+ this.dst=dst;
+ this.this_temp=this_temp;
+ this.args=args;
+ }
- public TempDescriptor getThis() {
- return this_temp;
- }
+ public MethodDescriptor getMethod() {
+ return method;
+ }
- public TempDescriptor getReturnTemp() {
- return dst;
- }
+ public TempDescriptor getThis() {
+ return this_temp;
+ }
- public int numArgs() {
- return args.length;
- }
+ public TempDescriptor getReturnTemp() {
+ return dst;
+ }
- public TempDescriptor getArg(int i) {
- return args[i];
- }
+ public int numArgs() {
+ return args.length;
+ }
- public String toString() {
- String st="FlatCall_";
- if (dst==null) {
- if (method==null)
- st+="null(";
- else
- st+=method.getSymbol()+"(";
- } else
- st+=dst+"="+method.getSymbol()+"(";
- if (this_temp!=null) {
- st+=this_temp;
- if (args.length!=0)
- st+=", ";
- }
+ public TempDescriptor getArg(int i) {
+ return args[i];
+ }
- for(int i=0;i<args.length;i++) {
- st+=args[i].toString();
- if ((i+1)<args.length)
- st+=", ";
- }
- return st+")";
+ public String toString() {
+ String st="FlatCall_";
+ if (dst==null) {
+ if (method==null)
+ st+="null(";
+ else
+ st+=method.getSymbol()+"(";
+ } else
+ st+=dst+"="+method.getSymbol()+"(";
+ if (this_temp!=null) {
+ st+=this_temp;
+ if (args.length!=0)
+ st+=", ";
}
- public int kind() {
- return FKind.FlatCall;
+ for(int i=0; i<args.length; i++) {
+ st+=args[i].toString();
+ if ((i+1)<args.length)
+ st+=", ";
}
+ return st+")";
+ }
- public TempDescriptor [] readsTemps() {
- int size=args.length;
- if (this_temp!=null)
- size++;
- TempDescriptor [] t=new TempDescriptor[size];
- int offset=0;
- if (this_temp!=null)
- t[offset++]=this_temp;
- for(int i=0;i<args.length;i++)
- t[offset++]=args[i];
- return t;
- }
+ public int kind() {
+ return FKind.FlatCall;
+ }
- public TempDescriptor [] writesTemps() {
- if (dst!=null)
- return new TempDescriptor[] {dst};
- else
- return new TempDescriptor[0];
- }
+ public TempDescriptor [] readsTemps() {
+ int size=args.length;
+ if (this_temp!=null)
+ size++;
+ TempDescriptor [] t=new TempDescriptor[size];
+ int offset=0;
+ if (this_temp!=null)
+ t[offset++]=this_temp;
+ for(int i=0; i<args.length; i++)
+ t[offset++]=args[i];
+ return t;
+ }
+
+ public TempDescriptor [] writesTemps() {
+ if (dst!=null)
+ return new TempDescriptor[] {dst};
+ else
+ return new TempDescriptor[0];
+ }
}
import IR.TypeDescriptor;
public class FlatCastNode extends FlatNode {
- TempDescriptor src;
- TempDescriptor dst;
- TypeDescriptor type;
-
- public FlatCastNode(TypeDescriptor type, TempDescriptor src, TempDescriptor dst) {
- this.type=type;
- this.src=src;
- this.dst=dst;
- }
-
- public String toString() {
- return "FlatCastNode_"+dst.toString()+"=("+type.toString()+")"+src.toString();
- }
-
- public int kind() {
- return FKind.FlatCastNode;
- }
-
- public TypeDescriptor getType() {
- return type;
- }
-
- public TempDescriptor getSrc() {
- return src;
- }
-
- public TempDescriptor getDst() {
- return dst;
- }
-
- public TempDescriptor [] writesTemps() {
- return new TempDescriptor[] {dst};
- }
-
- public TempDescriptor [] readsTemps() {
- return new TempDescriptor[] {src};
- }
+ TempDescriptor src;
+ TempDescriptor dst;
+ TypeDescriptor type;
+
+ public FlatCastNode(TypeDescriptor type, TempDescriptor src, TempDescriptor dst) {
+ this.type=type;
+ this.src=src;
+ this.dst=dst;
+ }
+
+ public String toString() {
+ return "FlatCastNode_"+dst.toString()+"=("+type.toString()+")"+src.toString();
+ }
+
+ public int kind() {
+ return FKind.FlatCastNode;
+ }
+
+ public TypeDescriptor getType() {
+ return type;
+ }
+
+ public TempDescriptor getSrc() {
+ return src;
+ }
+
+ public TempDescriptor getDst() {
+ return dst;
+ }
+
+ public TempDescriptor [] writesTemps() {
+ return new TempDescriptor[] {dst};
+ }
+
+ public TempDescriptor [] readsTemps() {
+ return new TempDescriptor[] {src};
+ }
}
package IR.Flat;
public class FlatCheckNode extends FlatNode {
- TempDescriptor [] temps;
- String [] vars;
- String spec;
+ TempDescriptor [] temps;
+ String [] vars;
+ String spec;
- public FlatCheckNode(String spec, String[] vars, TempDescriptor[] temps) {
- this.spec=spec;
- this.vars=vars;
- this.temps=temps;
- }
+ public FlatCheckNode(String spec, String[] vars, TempDescriptor[] temps) {
+ this.spec=spec;
+ this.vars=vars;
+ this.temps=temps;
+ }
- public int kind() {
- return FKind.FlatCheckNode;
- }
+ public int kind() {
+ return FKind.FlatCheckNode;
+ }
- public String getSpec() {
- return spec;
- }
+ public String getSpec() {
+ return spec;
+ }
- public String[] getVars() {
- return vars;
- }
+ public String[] getVars() {
+ return vars;
+ }
- public TempDescriptor [] getTemps() {
- return temps;
- }
-
- public TempDescriptor [] readsTemps() {
- return temps;
- }
+ public TempDescriptor [] getTemps() {
+ return temps;
+ }
+
+ public TempDescriptor [] readsTemps() {
+ return temps;
+ }
}
import java.util.Vector;
public class FlatCondBranch extends FlatNode {
- TempDescriptor test_cond;
- double trueprob=0.5;
- boolean loop=false;
+ TempDescriptor test_cond;
+ double trueprob=0.5;
+ boolean loop=false;
- public FlatCondBranch(TempDescriptor td) {
- test_cond=td;
- }
+ public FlatCondBranch(TempDescriptor td) {
+ test_cond=td;
+ }
- public void setLoop() {
- loop=true;
- }
-
- public boolean isLoopBranch() {
- return loop;
- }
+ public void setLoop() {
+ loop=true;
+ }
- public void setTrueProb(double p) {
- trueprob=p;
- }
+ public boolean isLoopBranch() {
+ return loop;
+ }
- public double getTrueProb() {
- return trueprob;
- }
+ public void setTrueProb(double p) {
+ trueprob=p;
+ }
- public double getFalseProb() {
- return 1-trueprob;
- }
+ public double getTrueProb() {
+ return trueprob;
+ }
- public void addTrueNext(FlatNode n) {
- if (next.size()==0)
- next.setSize(1);
- next.setElementAt(n,0);
- n.addPrev(this);
- }
+ public double getFalseProb() {
+ return 1-trueprob;
+ }
- public void addFalseNext(FlatNode n) {
- next.setSize(2);
- next.setElementAt(n,1);
- n.addPrev(this);
- }
+ public void addTrueNext(FlatNode n) {
+ if (next.size()==0)
+ next.setSize(1);
+ next.setElementAt(n,0);
+ n.addPrev(this);
+ }
- public TempDescriptor getTest() {
- return test_cond;
- }
+ public void addFalseNext(FlatNode n) {
+ next.setSize(2);
+ next.setElementAt(n,1);
+ n.addPrev(this);
+ }
- public String toString() {
- return "conditional branch";
- }
+ public TempDescriptor getTest() {
+ return test_cond;
+ }
- public String toString(String negjump) {
- return "FlatCondBranch_if (!"+test_cond.toString()+") goto "+negjump;
- }
+ public String toString() {
+ return "conditional branch";
+ }
- public void addNext(FlatNode n) {
- throw new Error();
- }
+ public String toString(String negjump) {
+ return "FlatCondBranch_if (!"+test_cond.toString()+") goto "+negjump;
+ }
- public int kind() {
- return FKind.FlatCondBranch;
- }
+ public void addNext(FlatNode n) {
+ throw new Error();
+ }
- public TempDescriptor [] readsTemps() {
- return new TempDescriptor[] {test_cond};
- }
+ public int kind() {
+ return FKind.FlatCondBranch;
+ }
+
+ public TempDescriptor [] readsTemps() {
+ return new TempDescriptor[] {test_cond};
+ }
}
import IR.FieldDescriptor;
public class FlatElementNode extends FlatNode {
- TempDescriptor src;
- TempDescriptor dst;
- TempDescriptor index;
-
- public FlatElementNode(TempDescriptor src, TempDescriptor index, TempDescriptor dst) {
- this.index=index;
- this.src=src;
- this.dst=dst;
- }
-
- public boolean needsBoundsCheck() {
- return true;
- }
-
- public TempDescriptor getIndex() {
- return index;
- }
-
- public TempDescriptor getSrc() {
- return src;
- }
-
- public TempDescriptor getDst() {
- return dst;
- }
-
- public String toString() {
- return "FlatElementNode_"+dst.toString()+"="+src.toString()+"["+index.toString()+"]";
- }
-
- public int kind() {
- return FKind.FlatElementNode;
- }
-
- public TempDescriptor [] writesTemps() {
- return new TempDescriptor[] {dst};
- }
-
- public TempDescriptor [] readsTemps() {
- return new TempDescriptor[] {src,index};
- }
+ TempDescriptor src;
+ TempDescriptor dst;
+ TempDescriptor index;
+
+ public FlatElementNode(TempDescriptor src, TempDescriptor index, TempDescriptor dst) {
+ this.index=index;
+ this.src=src;
+ this.dst=dst;
+ }
+
+ public boolean needsBoundsCheck() {
+ return true;
+ }
+
+ public TempDescriptor getIndex() {
+ return index;
+ }
+
+ public TempDescriptor getSrc() {
+ return src;
+ }
+
+ public TempDescriptor getDst() {
+ return dst;
+ }
+
+ public String toString() {
+ return "FlatElementNode_"+dst.toString()+"="+src.toString()+"["+index.toString()+"]";
+ }
+
+ public int kind() {
+ return FKind.FlatElementNode;
+ }
+
+ public TempDescriptor [] writesTemps() {
+ return new TempDescriptor[] {dst};
+ }
+
+ public TempDescriptor [] readsTemps() {
+ return new TempDescriptor[] {src,index};
+ }
}
import IR.FieldDescriptor;
public class FlatFieldNode extends FlatNode {
- TempDescriptor src;
- TempDescriptor dst;
- FieldDescriptor field;
-
- public FlatFieldNode(FieldDescriptor field, TempDescriptor src, TempDescriptor dst) {
- this.field=field;
- this.src=src;
- this.dst=dst;
- }
-
- public FieldDescriptor getField() {
- return field;
- }
-
- public TempDescriptor getSrc() {
- return src;
- }
-
- public TempDescriptor getDst() {
- return dst;
- }
-
- public String toString() {
- return "FlatFieldNode_"+dst.toString()+"="+src.toString()+"."+field.getSymbol();
- }
-
- public int kind() {
- return FKind.FlatFieldNode;
- }
-
- public TempDescriptor [] writesTemps() {
- return new TempDescriptor[] {dst};
- }
-
- public TempDescriptor [] readsTemps() {
- return new TempDescriptor[] {src};
- }
+ TempDescriptor src;
+ TempDescriptor dst;
+ FieldDescriptor field;
+
+ public FlatFieldNode(FieldDescriptor field, TempDescriptor src, TempDescriptor dst) {
+ this.field=field;
+ this.src=src;
+ this.dst=dst;
+ }
+
+ public FieldDescriptor getField() {
+ return field;
+ }
+
+ public TempDescriptor getSrc() {
+ return src;
+ }
+
+ public TempDescriptor getDst() {
+ return dst;
+ }
+
+ public String toString() {
+ return "FlatFieldNode_"+dst.toString()+"="+src.toString()+"."+field.getSymbol();
+ }
+
+ public int kind() {
+ return FKind.FlatFieldNode;
+ }
+
+ public TempDescriptor [] writesTemps() {
+ return new TempDescriptor[] {dst};
+ }
+
+ public TempDescriptor [] readsTemps() {
+ return new TempDescriptor[] {src};
+ }
}
import java.util.Vector;
public class FlatFlagActionNode extends FlatNode {
- Hashtable<TempFlagPair, Boolean> tempflagpairs;
- Hashtable<TempTagPair, Boolean> temptagpairs;
-
- int taskexit;
- public static final int NEWOBJECT=0;
- public static final int PRE=1;
- public static final int TASKEXIT=2;
-
- Hashtable<ClassDescriptor, Vector<FlagState>> cd2initfs;
- Hashtable<ClassDescriptor, Vector<FlagState>> cd2fs4new;
- Hashtable<FlagState, Vector<FlagState>> fs2fs;
-
-
- public FlatFlagActionNode(int taskexit) {
- tempflagpairs=new Hashtable<TempFlagPair, Boolean>();
- temptagpairs=new Hashtable<TempTagPair, Boolean>();
- this.taskexit=taskexit;
-
- this.cd2initfs = null;
- this.cd2fs4new = null;
- this.fs2fs = null;
- }
+ Hashtable<TempFlagPair, Boolean> tempflagpairs;
+ Hashtable<TempTagPair, Boolean> temptagpairs;
- public int getTaskType() {
- return taskexit;
- }
-
- public Vector<FlagState> getInitFStates(ClassDescriptor cd) {
- if(this.cd2initfs == null) {
- this.cd2initfs = new Hashtable<ClassDescriptor, Vector<FlagState>>();
- }
- if(this.cd2initfs.get(cd) == null) {
- this.cd2initfs.put(cd, new Vector<FlagState>());
- }
- return this.cd2initfs.get(cd);
- }
-
- public Vector<FlagState> getTargetFStates4NewObj(ClassDescriptor cd) {
- if(this.cd2fs4new == null) {
- this.cd2fs4new = new Hashtable<ClassDescriptor, Vector<FlagState>>();
- }
- if(this.cd2fs4new.get(cd) == null) {
- this.cd2fs4new.put(cd, new Vector<FlagState>());
- }
- 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<ClassDescriptor, Vector<FlagState>> cd2initfs;
+ Hashtable<ClassDescriptor, Vector<FlagState>> cd2fs4new;
+ Hashtable<FlagState, Vector<FlagState>> fs2fs;
+
+
+ public FlatFlagActionNode(int taskexit) {
+ tempflagpairs=new Hashtable<TempFlagPair, Boolean>();
+ temptagpairs=new Hashtable<TempTagPair, Boolean>();
+ this.taskexit=taskexit;
+
+ this.cd2initfs = null;
+ this.cd2fs4new = null;
+ this.fs2fs = null;
+ }
+
+ public int getTaskType() {
+ return taskexit;
+ }
+
+ public Vector<FlagState> getInitFStates(ClassDescriptor cd) {
+ if(this.cd2initfs == null) {
+ this.cd2initfs = new Hashtable<ClassDescriptor, Vector<FlagState>>();
}
-
- public Vector<FlagState> getTargetFStates(FlagState fs) {
- if(this.fs2fs == null) {
- this.fs2fs = new Hashtable<FlagState, Vector<FlagState>>();
- }
- if(this.fs2fs.get(fs) == null) {
- this.fs2fs.put(fs, new Vector<FlagState>());
- }
- return this.fs2fs.get(fs);
+ if(this.cd2initfs.get(cd) == null) {
+ this.cd2initfs.put(cd, new Vector<FlagState>());
}
+ 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<FlagState> getTargetFStates4NewObj(ClassDescriptor cd) {
+ if(this.cd2fs4new == null) {
+ this.cd2fs4new = new Hashtable<ClassDescriptor, Vector<FlagState>>();
}
-
- 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<FlagState>());
}
+ return this.cd2fs4new.get(cd);
+ }
- public int kind() {
- return FKind.FlatFlagActionNode;
+ public Vector<FlagState> getTargetFStates(FlagState fs) {
+ if(this.fs2fs == null) {
+ this.fs2fs = new Hashtable<FlagState, Vector<FlagState>>();
}
-
- /** This method returns an iterator over the Temp/Flag pairs. */
-
- public Iterator<TempFlagPair> getTempFlagPairs() {
- return tempflagpairs.keySet().iterator();
+ if(this.fs2fs.get(fs) == null) {
+ this.fs2fs.put(fs, new Vector<FlagState>());
}
+ return this.fs2fs.get(fs);
+ }
- public Iterator<TempTagPair> 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<TempFlagPair> getTempFlagPairs() {
+ return tempflagpairs.keySet().iterator();
+ }
+
+ public Iterator<TempTagPair> 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;
+ }
}
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};
+ }
}
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<st.length();i++) {
- char x=st.charAt(i);
- if (x=='\n')
- new_st+="\\n";
- else if (x=='\r')
- new_st+="\\r";
- else if (x=='"')
- new_st+="\\\"";
- else new_st+=x;
- }
- return new_st;
- }
-
- public int kind() {
- return FKind.FlatLiteralNode;
- }
-
- public TempDescriptor [] writesTemps() {
- return new TempDescriptor[] {dst};
- }
+ 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<st.length(); i++) {
+ char x=st.charAt(i);
+ if (x=='\n')
+ new_st+="\\n";
+ else if (x=='\r')
+ new_st+="\\r";
+ else if (x=='"')
+ new_st+="\\\"";
+ else new_st+=x;
+ }
+ return new_st;
+ }
+
+ public int kind() {
+ return FKind.FlatLiteralNode;
+ }
+
+ public TempDescriptor [] writesTemps() {
+ return new TempDescriptor[] {dst};
+ }
}
import java.util.*;
public class FlatMethod extends FlatNode {
- MethodDescriptor method;
- TaskDescriptor task;
- Vector parameterTemps;
- Vector tagTemps;
- Hashtable tagtointmap;
-
- FlatMethod(MethodDescriptor md) {
- method=md;
- task=null;
- parameterTemps=new Vector();
- tagTemps=new Vector();
- tagtointmap=new Hashtable();
- }
-
- FlatMethod(TaskDescriptor td) {
- task=td;
- method=null;
- parameterTemps=new Vector();
- tagTemps=new Vector();
- tagtointmap=new Hashtable();
- }
-
- public String toString() {
- String ret = "FlatMethod_";
- if( method != null ) {
- ret += method.toString();
- } else {
- ret += task.toString();
- }
- return ret;
- }
-
- public MethodDescriptor getMethod() {
- return method;
- }
-
- public TaskDescriptor getTask() {
- return task;
- }
-
- public int kind() {
- return FKind.FlatMethod;
- }
-
- public void addParameterTemp(TempDescriptor t) {
- parameterTemps.add(t);
- }
-
- public int numParameters() {
- return parameterTemps.size();
- }
-
- public void addTagTemp(TempDescriptor t) {
- tagtointmap.put(t, new Integer(tagTemps.size()));
- tagTemps.add(t);
- }
-
- public int getTagInt(TempDescriptor t) {
- return ((Integer)tagtointmap.get(t)).intValue();
- }
-
- public int numTags() {
- return tagTemps.size();
- }
-
- public TempDescriptor getTag(int i) {
- return (TempDescriptor) tagTemps.get(i);
- }
-
- public TempDescriptor getParameter(int i) {
- return (TempDescriptor) parameterTemps.get(i);
- }
-
- /** This method returns a set of the nodes in this flat representation */
-
- public Set<FlatNode> getNodeSet() {
- HashSet<FlatNode> tovisit=new HashSet<FlatNode>();
- HashSet<FlatNode> visited=new HashSet<FlatNode>();
- tovisit.add(this);
- while(!tovisit.isEmpty()) {
- FlatNode fn=tovisit.iterator().next();
- tovisit.remove(fn);
- visited.add(fn);
- for(int i=0;i<fn.numNext();i++) {
- FlatNode nn=fn.getNext(i);
- if (!visited.contains(nn))
- tovisit.add(nn);
- }
+ MethodDescriptor method;
+ TaskDescriptor task;
+ Vector parameterTemps;
+ Vector tagTemps;
+ Hashtable tagtointmap;
+
+ FlatMethod(MethodDescriptor md) {
+ method=md;
+ task=null;
+ parameterTemps=new Vector();
+ tagTemps=new Vector();
+ tagtointmap=new Hashtable();
+ }
+
+ FlatMethod(TaskDescriptor td) {
+ task=td;
+ method=null;
+ parameterTemps=new Vector();
+ tagTemps=new Vector();
+ tagtointmap=new Hashtable();
+ }
+
+ public String toString() {
+ String ret = "FlatMethod_";
+ if( method != null ) {
+ ret += method.toString();
+ } else {
+ ret += task.toString();
+ }
+ return ret;
+ }
+
+ public MethodDescriptor getMethod() {
+ return method;
+ }
+
+ public TaskDescriptor getTask() {
+ return task;
+ }
+
+ public int kind() {
+ return FKind.FlatMethod;
+ }
+
+ public void addParameterTemp(TempDescriptor t) {
+ parameterTemps.add(t);
+ }
+
+ public int numParameters() {
+ return parameterTemps.size();
+ }
+
+ public void addTagTemp(TempDescriptor t) {
+ tagtointmap.put(t, new Integer(tagTemps.size()));
+ tagTemps.add(t);
+ }
+
+ public int getTagInt(TempDescriptor t) {
+ return ((Integer)tagtointmap.get(t)).intValue();
+ }
+
+ public int numTags() {
+ return tagTemps.size();
+ }
+
+ public TempDescriptor getTag(int i) {
+ return (TempDescriptor) tagTemps.get(i);
+ }
+
+ public TempDescriptor getParameter(int i) {
+ return (TempDescriptor) parameterTemps.get(i);
+ }
+
+ /** This method returns a set of the nodes in this flat representation */
+
+ public Set<FlatNode> getNodeSet() {
+ HashSet<FlatNode> tovisit=new HashSet<FlatNode>();
+ HashSet<FlatNode> visited=new HashSet<FlatNode>();
+ tovisit.add(this);
+ while(!tovisit.isEmpty()) {
+ FlatNode fn=tovisit.iterator().next();
+ tovisit.remove(fn);
+ visited.add(fn);
+ for(int i=0; i<fn.numNext(); i++) {
+ FlatNode nn=fn.getNext(i);
+ if (!visited.contains(nn))
+ tovisit.add(nn);
+ }
+ }
+ 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; i<fn.numNext(); i++) {
+ FlatNode nn=fn.getNext(i);
+ if(i>0) {
+ //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;i<fn.numNext();i++) {
- FlatNode nn=fn.getNext(i);
- if(i>0) {
- //1) Edge >1 of node
- nodetolabel.put(nn,new Integer(labelindex++));
- }
- if (!visited.contains(nn)&&!tovisit.contains(nn)) {
- tovisit.add(nn);
- } else {
- //2) Join point
- nodetolabel.put(nn,new Integer(labelindex++));
- }
- }
- }
-
- //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()]);
+ }
}
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;
+ }
}
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];
+ }
}
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;
+ }
}
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};
+ }
}
import java.util.*;
public class FlatPrefetchNode extends FlatNode {
- public Integer siteid;
- HashSet<PrefetchPair> hspp;
-
- public FlatPrefetchNode() {
- hspp = new HashSet<PrefetchPair>();
- siteid = new Integer(1);
- }
-
- public String toString() {
- String st="prefetch(";
- boolean first=true;
- for(Iterator<PrefetchPair> 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<PrefetchPair> hspp) {
- this.hspp.addAll(hspp);
- }
-
- public HashSet<PrefetchPair> getPrefetchPairs() {
- return hspp;
- }
-
- public int getNumPairs() {
- return hspp.size();
- }
+ public Integer siteid;
+ HashSet<PrefetchPair> hspp;
+
+ public FlatPrefetchNode() {
+ hspp = new HashSet<PrefetchPair>();
+ siteid = new Integer(1);
+ }
+
+ public String toString() {
+ String st="prefetch(";
+ boolean first=true;
+ for(Iterator<PrefetchPair> 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<PrefetchPair> hspp) {
+ this.hspp.addAll(hspp);
+ }
+
+ public HashSet<PrefetchPair> getPrefetchPairs() {
+ return hspp;
+ }
+
+ public int getNumPairs() {
+ return hspp.size();
+ }
}
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;
+ }
}
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};
+ }
}
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};
+ }
}
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;
+ }
}
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;
+ }
}
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;
}
+ }
}
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;
+ }
}
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+">";
+ }
}
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;
}
+ }
}
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+">";
+ }
}
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<numParameters();i++) {
- Descriptor d1=getParameter(i);
- Descriptor d2=md.getParameter(i);
- TypeDescriptor td1=(d1 instanceof TagVarDescriptor)?((TagVarDescriptor)d1).getType():((VarDescriptor)d1).getType();
- TypeDescriptor td2=(d2 instanceof TagVarDescriptor)?((TagVarDescriptor)d2).getType():((VarDescriptor)d2).getType();
- if (!td1.equals(td2))
- return false;
- }
- return true;
- }
-
- public MethodDescriptor(Modifiers m, String identifier) {
- this(m, identifier, false);
- }
-
- public MethodDescriptor(Modifiers m, String identifier, boolean isglobal) {
- super(identifier);
- this.isglobal=isglobal;
- this.modifier=m;
- this.returntype=null;
- this.identifier=identifier;
- this.safename = "___" + name + "___";
- this.uniqueid=count++;
- params=new Vector();
- paramtable=new SymbolTable();
- thisvd=null;
- }
-
-
- public boolean isGlobal() {
- return isglobal;
- }
-
- public void setThis(VarDescriptor vd) {
- thisvd=vd;
- paramtable.add(vd);
- }
-
- public VarDescriptor getThis() {
- return thisvd;
- }
-
- public String getClassMethodName() {
- return cd+"."+name;
- }
-
- public String getSafeMethodDescriptor() {
- String st="";
- for(int i=0;i<numParameters();i++) {
- st+=getParamType(i).getSafeDescriptor();
- if ((i+1)<numParameters())
- st+="_";
- }
- return st;
- }
-
- public boolean isStatic() {
- return modifier.isStatic();
- }
-
- public boolean isConstructor() {
- return (returntype==null);
- }
-
- public TypeDescriptor getReturnType() {
- return returntype;
- }
-
- public void setClassDesc(ClassDescriptor cd) {
- this.cd=cd;
- }
-
- public ClassDescriptor getClassDesc() {
- return cd;
- }
-
- public SymbolTable getParameterTable() {
- return paramtable;
- }
-
- public void addParameter(TypeDescriptor type, String paramname) {
- if (paramname.equals("this"))
- throw new Error("Can't have parameter named this");
- VarDescriptor vd=new VarDescriptor(type, paramname);
-
- params.add(vd);
- if (paramtable.getFromSameScope(paramname)!=null) {
- throw new Error("Parameter "+paramname+" already defined");
- }
- paramtable.add(vd);
- }
-
- public void addTagParameter(TypeDescriptor type, String paramname) {
- if (paramname.equals("this"))
- throw new Error("Can't have parameter named this");
- TagVarDescriptor vd=new TagVarDescriptor(null, paramname);
-
- params.add(vd);
- if (paramtable.getFromSameScope(paramname)!=null) {
- throw new Error("Parameter "+paramname+" already defined");
- }
- paramtable.add(vd);
- }
-
- public int numParameters() {
- return params.size();
- }
-
- public Descriptor getParameter(int i) {
- return (Descriptor) params.get(i);
- }
-
- public String getParamName(int i) {
- return ((Descriptor)params.get(i)).getSymbol();
- }
-
- public TypeDescriptor getParamType(int i) {
- Descriptor d=(Descriptor)params.get(i);
- if (d instanceof VarDescriptor)
- return ((VarDescriptor)params.get(i)).getType();
- else if (d instanceof TagVarDescriptor)
- return new TypeDescriptor(TypeDescriptor.TAG);
- else throw new Error();
- }
-
- public String toString() {
- String st="";
- String type="";
- if (cd!=null)
- type=cd+".";
- if (returntype!=null)
- st=modifier.toString()+returntype.toString()+" "+type+identifier+"(";
- else
- st=modifier.toString()+" "+type+identifier+"(";
- for(int i=0;i<params.size();i++) {
- st+=getParamType(i)+" "+getParamName(i);
- if ((i+1)!=params.size())
- st+=", ";
- }
- st+=")";
- return st;
- }
+ 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<numParameters(); i++) {
+ Descriptor d1=getParameter(i);
+ Descriptor d2=md.getParameter(i);
+ TypeDescriptor td1=(d1 instanceof TagVarDescriptor) ? ((TagVarDescriptor)d1).getType() : ((VarDescriptor)d1).getType();
+ TypeDescriptor td2=(d2 instanceof TagVarDescriptor) ? ((TagVarDescriptor)d2).getType() : ((VarDescriptor)d2).getType();
+ if (!td1.equals(td2))
+ return false;
+ }
+ return true;
+ }
+
+ public MethodDescriptor(Modifiers m, String identifier) {
+ this(m, identifier, false);
+ }
+
+ public MethodDescriptor(Modifiers m, String identifier, boolean isglobal) {
+ super(identifier);
+ this.isglobal=isglobal;
+ this.modifier=m;
+ this.returntype=null;
+ this.identifier=identifier;
+ this.safename = "___" + name + "___";
+ this.uniqueid=count++;
+ params=new Vector();
+ paramtable=new SymbolTable();
+ thisvd=null;
+ }
+
+
+ public boolean isGlobal() {
+ return isglobal;
+ }
+
+ public void setThis(VarDescriptor vd) {
+ thisvd=vd;
+ paramtable.add(vd);
+ }
+
+ public VarDescriptor getThis() {
+ return thisvd;
+ }
+
+ public String getClassMethodName() {
+ return cd+"."+name;
+ }
+
+ public String getSafeMethodDescriptor() {
+ String st="";
+ for(int i=0; i<numParameters(); i++) {
+ st+=getParamType(i).getSafeDescriptor();
+ if ((i+1)<numParameters())
+ st+="_";
+ }
+ return st;
+ }
+
+ public boolean isStatic() {
+ return modifier.isStatic();
+ }
+
+ public boolean isConstructor() {
+ return (returntype==null);
+ }
+
+ public TypeDescriptor getReturnType() {
+ return returntype;
+ }
+
+ public void setClassDesc(ClassDescriptor cd) {
+ this.cd=cd;
+ }
+
+ public ClassDescriptor getClassDesc() {
+ return cd;
+ }
+
+ public SymbolTable getParameterTable() {
+ return paramtable;
+ }
+
+ public void addParameter(TypeDescriptor type, String paramname) {
+ if (paramname.equals("this"))
+ throw new Error("Can't have parameter named this");
+ VarDescriptor vd=new VarDescriptor(type, paramname);
+
+ params.add(vd);
+ if (paramtable.getFromSameScope(paramname)!=null) {
+ throw new Error("Parameter "+paramname+" already defined");
+ }
+ paramtable.add(vd);
+ }
+
+ public void addTagParameter(TypeDescriptor type, String paramname) {
+ if (paramname.equals("this"))
+ throw new Error("Can't have parameter named this");
+ TagVarDescriptor vd=new TagVarDescriptor(null, paramname);
+
+ params.add(vd);
+ if (paramtable.getFromSameScope(paramname)!=null) {
+ throw new Error("Parameter "+paramname+" already defined");
+ }
+ paramtable.add(vd);
+ }
+
+ public int numParameters() {
+ return params.size();
+ }
+
+ public Descriptor getParameter(int i) {
+ return (Descriptor) params.get(i);
+ }
+
+ public String getParamName(int i) {
+ return ((Descriptor)params.get(i)).getSymbol();
+ }
+
+ public TypeDescriptor getParamType(int i) {
+ Descriptor d=(Descriptor)params.get(i);
+ if (d instanceof VarDescriptor)
+ return ((VarDescriptor)params.get(i)).getType();
+ else if (d instanceof TagVarDescriptor)
+ return new TypeDescriptor(TypeDescriptor.TAG);
+ else throw new Error();
+ }
+
+ public String toString() {
+ String st="";
+ String type="";
+ if (cd!=null)
+ type=cd+".";
+ if (returntype!=null)
+ st=modifier.toString()+returntype.toString()+" "+type+identifier+"(";
+ else
+ st=modifier.toString()+" "+type+identifier+"(";
+ for(int i=0; i<params.size(); i++) {
+ st+=getParamType(i)+" "+getParamName(i);
+ if ((i+1)!=params.size())
+ st+=", ";
+ }
+ st+=")";
+ return st;
+ }
}
package IR;
public class NameDescriptor extends Descriptor {
- String identifier;
- NameDescriptor nd;
- public NameDescriptor(NameDescriptor nd, String id) {
- super(nd.toString()+"."+id);
- identifier=id;
- this.nd=nd;
- }
+ String identifier;
+ NameDescriptor nd;
+ public NameDescriptor(NameDescriptor nd, String id) {
+ super(nd.toString()+"."+id);
+ identifier=id;
+ this.nd=nd;
+ }
- public NameDescriptor(String id) {
- super(id);
- identifier=id;
- nd=null;
- }
+ public NameDescriptor(String id) {
+ super(id);
+ identifier=id;
+ nd=null;
+ }
- public String getIdentifier() {
- return identifier;
- }
+ public String getIdentifier() {
+ return identifier;
+ }
- public NameDescriptor getBase() {
- return nd;
- }
+ public NameDescriptor getBase() {
+ return nd;
+ }
- public String getRoot() {
- if (nd==null)
- return identifier;
- else
- return nd.getRoot();
- }
+ public String getRoot() {
+ if (nd==null)
+ return identifier;
+ else
+ return nd.getRoot();
+ }
- public String toString() {
- if (nd==null)
- return identifier;
- else
- return nd+"."+identifier;
- }
+ public String toString() {
+ if (nd==null)
+ return identifier;
+ else
+ return nd+"."+identifier;
+ }
}
package IR;
public class Operation {
- public static final int LOGIC_OR=1;
- public static final int LOGIC_AND=2;
- public static final int BIT_OR=3;
- public static final int BIT_XOR=4;
- public static final int BIT_AND=5;
- public static final int EQUAL=6;
- public static final int NOTEQUAL=7;
- public static final int LT=8;
- public static final int GT=9;
- public static final int LTE=10;
- public static final int GTE=11;
- public static final int LEFTSHIFT=12;
- public static final int RIGHTSHIFT=13;
- public static final int SUB=14;
- public static final int ADD=15;
- public static final int MULT=16;
- public static final int DIV=17;
- public static final int MOD=18;
- public static final int UNARYPLUS=19;
- public static final int UNARYMINUS=20;
- public static final int POSTINC=21;
- public static final int POSTDEC=22;
- public static final int PREINC=23;
- public static final int PREDEC=24;
- public static final int LOGIC_NOT=25;
- public static final int ISAVAILABLE=26;
- public static final int URIGHTSHIFT=27;
- public static final int COMP=28;
- /* Flat Operations */
- public static final int ASSIGN=100;
+ public static final int LOGIC_OR=1;
+ public static final int LOGIC_AND=2;
+ public static final int BIT_OR=3;
+ public static final int BIT_XOR=4;
+ public static final int BIT_AND=5;
+ public static final int EQUAL=6;
+ public static final int NOTEQUAL=7;
+ public static final int LT=8;
+ public static final int GT=9;
+ public static final int LTE=10;
+ public static final int GTE=11;
+ public static final int LEFTSHIFT=12;
+ public static final int RIGHTSHIFT=13;
+ public static final int SUB=14;
+ public static final int ADD=15;
+ public static final int MULT=16;
+ public static final int DIV=17;
+ public static final int MOD=18;
+ public static final int UNARYPLUS=19;
+ public static final int UNARYMINUS=20;
+ public static final int POSTINC=21;
+ public static final int POSTDEC=22;
+ public static final int PREINC=23;
+ public static final int PREDEC=24;
+ public static final int LOGIC_NOT=25;
+ public static final int ISAVAILABLE=26;
+ public static final int URIGHTSHIFT=27;
+ public static final int COMP=28;
+ /* Flat Operations */
+ public static final int ASSIGN=100;
- private int operation;
- public Operation(int op) {
- this.operation=op;
- }
+ private int operation;
+ public Operation(int op) {
+ this.operation=op;
+ }
- public Operation(String op) {
- this.operation=parseOp(op);
- }
+ public Operation(String op) {
+ this.operation=parseOp(op);
+ }
- public int getOp() {
- return operation;
- }
-
- 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 int getOp() {
+ return operation;
+ }
- 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();
- }
+ 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();
+ }
}
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<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> analysisresults) {
- this.analysisresults=analysisresults;
- }
-
- public Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> getAnalysisResult() {
- return analysisresults;
- }
-
-
- public void storeOptionalTaskDescriptors(Hashtable<ClassDescriptor, Hashtable<OptionalTaskDescriptor, OptionalTaskDescriptor>> optionaltaskdescriptors){
- this.optionaltaskdescriptors=optionaltaskdescriptors;
- }
-
- public Hashtable<ClassDescriptor, Hashtable<OptionalTaskDescriptor, OptionalTaskDescriptor>> 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<ClassDescriptor, Hashtable<OptionalTaskDescriptor, OptionalTaskDescriptor>> optionaltaskdescriptors;
- private Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> 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<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> analysisresults) {
+ this.analysisresults=analysisresults;
+ }
+
+ public Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> getAnalysisResult() {
+ return analysisresults;
+ }
+
+
+ public void storeOptionalTaskDescriptors(Hashtable<ClassDescriptor, Hashtable<OptionalTaskDescriptor, OptionalTaskDescriptor>> optionaltaskdescriptors) {
+ this.optionaltaskdescriptors=optionaltaskdescriptors;
+ }
+
+ public Hashtable<ClassDescriptor, Hashtable<OptionalTaskDescriptor, OptionalTaskDescriptor>> 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<ClassDescriptor, Hashtable<OptionalTaskDescriptor, OptionalTaskDescriptor>> optionaltaskdescriptors;
+ private Hashtable<ClassDescriptor, Hashtable<FlagState, Set<OptionalTaskDescriptor>>> 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++;
+ }
}
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();
+ }
}
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();
+ }
}
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;
+ }
}
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; i<tel.numTags(); i++) {
+ TagVarDescriptor tvd=new TagVarDescriptor(new TagDescriptor(tel.getType(i)), tel.getName(i));
+ if (paramtable.getFromSameScope(tel.getName(i))==null) {
+ paramtable.add(tvd);
+ } else if (!((paramtable.getFromSameScope(tel.getName(i)) instanceof TagVarDescriptor)&&((TagVarDescriptor)paramtable.getFromSameScope(tel.getName(i))).getTag().equals(tvd.getTag())))
+ throw new Error("Parameter "+paramname+" already defined");
+ }
}
- public void addFlagEffects(Vector vfe) {
- this.vfe=vfe;
+ if (paramtable.getFromSameScope(paramname)!=null) {
+ throw new Error("Parameter "+paramname+" already defined");
}
-
- 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;i<tel.numTags();i++) {
- TagVarDescriptor tvd=new TagVarDescriptor(new TagDescriptor(tel.getType(i)), tel.getName(i));
- if (paramtable.getFromSameScope(tel.getName(i))==null) {
- paramtable.add(tvd);
- } else if (!((paramtable.getFromSameScope(tel.getName(i)) instanceof TagVarDescriptor)&&((TagVarDescriptor)paramtable.getFromSameScope(tel.getName(i))).getTag().equals(tvd.getTag())))
- throw new Error("Parameter "+paramname+" already defined");
- }
- }
-
- if (paramtable.getFromSameScope(paramname)!=null) {
- throw new Error("Parameter "+paramname+" already defined");
- }
- paramtable.add(vd);
- }
-
- public boolean isOptional(VarDescriptor vd) {
- return optionals.contains(vd);
- }
-
- public int numParameters() {
- return params.size();
- }
-
- public VarDescriptor getParameter(int i) {
- return (VarDescriptor)params.get(i);
- }
-
- public String getParamName(int i) {
- return ((VarDescriptor)params.get(i)).getName();
- }
-
- public TypeDescriptor getParamType(int i) {
- return ((VarDescriptor)params.get(i)).getType();
- }
-
- public FlagExpressionNode getFlag(VarDescriptor vd) {
- return (FlagExpressionNode) flagstable.get(vd);
- }
-
- public TagExpressionList getTag(VarDescriptor vd) {
- //BUG did lookup in wrong table (originally flagstable)...to
- //test, use any task program
- return (TagExpressionList) tagstable.get(vd);
- }
-
- public String toString() {
- String st=identifier+"(";
- for(int i=0;i<params.size();i++) {
- st+=getParamType(i)+" "+getParamName(i);
- if ((i+1)!=params.size())
- st+=", ";
- }
- st+=")";
- return st;
+ paramtable.add(vd);
+ }
+
+ public boolean isOptional(VarDescriptor vd) {
+ return optionals.contains(vd);
+ }
+
+ public int numParameters() {
+ return params.size();
+ }
+
+ public VarDescriptor getParameter(int i) {
+ return (VarDescriptor)params.get(i);
+ }
+
+ public String getParamName(int i) {
+ return ((VarDescriptor)params.get(i)).getName();
+ }
+
+ public TypeDescriptor getParamType(int i) {
+ return ((VarDescriptor)params.get(i)).getType();
+ }
+
+ public FlagExpressionNode getFlag(VarDescriptor vd) {
+ return (FlagExpressionNode) flagstable.get(vd);
+ }
+
+ public TagExpressionList getTag(VarDescriptor vd) {
+ //BUG did lookup in wrong table (originally flagstable)...to
+ //test, use any task program
+ return (TagExpressionList) tagstable.get(vd);
+ }
+
+ public String toString() {
+ String st=identifier+"(";
+ for(int i=0; i<params.size(); i++) {
+ st+=getParamType(i)+" "+getParamName(i);
+ if ((i+1)!=params.size())
+ st+=", ";
}
+ st+=")";
+ return st;
+ }
}
import IR.TypeDescriptor;
public class ArrayAccessNode extends ExpressionNode {
- ExpressionNode left;
- ExpressionNode index;
+ ExpressionNode left;
+ ExpressionNode index;
- public ArrayAccessNode(ExpressionNode l, ExpressionNode index) {
- this.index=index;
- left=l;
- }
+ public ArrayAccessNode(ExpressionNode l, ExpressionNode index) {
+ this.index=index;
+ left=l;
+ }
- public ExpressionNode getIndex() {
- return index;
- }
+ public ExpressionNode getIndex() {
+ return index;
+ }
- public ExpressionNode getExpression() {
- return left;
- }
+ public ExpressionNode getExpression() {
+ return left;
+ }
- public String printNode(int indent) {
- return left.printNode(indent)+"["+index.printNode(0)+"]";
- }
+ public String printNode(int indent) {
+ return left.printNode(indent)+"["+index.printNode(0)+"]";
+ }
- public int kind() {
- return Kind.ArrayAccessNode;
- }
+ public int kind() {
+ return Kind.ArrayAccessNode;
+ }
- public TypeDescriptor getType() {
- return left.getType().dereference();
- }
+ public TypeDescriptor getType() {
+ return left.getType().dereference();
+ }
}
import IR.TypeDescriptor;
public class AssignmentNode extends ExpressionNode {
- ExpressionNode left;
- ExpressionNode right;
- AssignOperation op;
-
- public AssignmentNode(ExpressionNode l, ExpressionNode r, AssignOperation op) {
- left=l;
- right=r;
- this.op=op;
- }
-
- public ExpressionNode getDest() {
- return left;
- }
-
- public ExpressionNode getSrc() {
- return right;
- }
-
- public AssignOperation getOperation() {
- return op;
- }
-
- public String printNode(int indent) {
- return left.printNode(indent)+" "+op.toString()+" "+right.printNode(indent);
- }
-
- public TypeDescriptor getType() {
- return left.getType();
- }
-
- public int kind() {
- return Kind.AssignmentNode;
- }
+ ExpressionNode left;
+ ExpressionNode right;
+ AssignOperation op;
+
+ public AssignmentNode(ExpressionNode l, ExpressionNode r, AssignOperation op) {
+ left=l;
+ right=r;
+ this.op=op;
+ }
+
+ public ExpressionNode getDest() {
+ return left;
+ }
+
+ public ExpressionNode getSrc() {
+ return right;
+ }
+
+ public AssignOperation getOperation() {
+ return op;
+ }
+
+ public String printNode(int indent) {
+ return left.printNode(indent)+" "+op.toString()+" "+right.printNode(indent);
+ }
+
+ public TypeDescriptor getType() {
+ return left.getType();
+ }
+
+ public int kind() {
+ return Kind.AssignmentNode;
+ }
}
package IR.Tree;
public class AtomicNode extends BlockStatementNode {
- BlockNode bn;
- public AtomicNode(BlockNode bn) {
- this.bn=bn;
- }
-
- public String printNode(int indent) {
- return printSpace(indent)+"atomic {\n"+bn.printNode(indent)+"\n"+printSpace(indent)+"}";
- }
+ BlockNode bn;
+ public AtomicNode(BlockNode bn) {
+ this.bn=bn;
+ }
- public BlockNode getBlockNode() {
- return bn;
- }
+ public String printNode(int indent) {
+ return printSpace(indent)+"atomic {\n"+bn.printNode(indent)+"\n"+printSpace(indent)+"}";
+ }
- public int kind() {
- return Kind.AtomicNode;
- }
+ public BlockNode getBlockNode() {
+ return bn;
+ }
+
+ public int kind() {
+ return Kind.AtomicNode;
+ }
}
package IR.Tree;
public class BlockExpressionNode extends BlockStatementNode {
- ExpressionNode en;
- public BlockExpressionNode(ExpressionNode e) {
- this.en=e;
- }
-
- public String printNode(int indent) {
- return en.printNode(indent);
- }
+ ExpressionNode en;
+ public BlockExpressionNode(ExpressionNode e) {
+ this.en=e;
+ }
- public ExpressionNode getExpression() {
- return en;
- }
+ public String printNode(int indent) {
+ return en.printNode(indent);
+ }
- public int kind() {
- return Kind.BlockExpressionNode;
- }
+ public ExpressionNode getExpression() {
+ return en;
+ }
+
+ public int kind() {
+ return Kind.BlockExpressionNode;
+ }
}
import IR.*;
public class BlockNode extends TreeNode {
- Vector blockstatements;
- int printStyle=0;
- protected SymbolTable table;
+ Vector blockstatements;
+ int printStyle=0;
+ protected SymbolTable table;
- public final static int NORMAL=0;
- public final static int NOBRACES=1;
- public final static int EXPRLIST=2;
-
- public BlockNode() {
- blockstatements=new Vector();
- table=new SymbolTable();
- }
+ public final static int NORMAL=0;
+ public final static int NOBRACES=1;
+ public final static int EXPRLIST=2;
- public SymbolTable getVarTable() {
- return table;
- }
+ public BlockNode() {
+ blockstatements=new Vector();
+ table=new SymbolTable();
+ }
- public void addBlockStatement(BlockStatementNode bsn) {
- blockstatements.add(bsn);
- }
+ public SymbolTable getVarTable() {
+ return table;
+ }
- public void addFirstBlockStatement(BlockStatementNode bsn) {
- blockstatements.insertElementAt(bsn,0);
- }
+ public void addBlockStatement(BlockStatementNode bsn) {
+ blockstatements.add(bsn);
+ }
- public void setStyle(int style) {
- printStyle=style;
- }
+ public void addFirstBlockStatement(BlockStatementNode bsn) {
+ blockstatements.insertElementAt(bsn,0);
+ }
- public int size() {
- return blockstatements.size();
- }
+ public void setStyle(int style) {
+ printStyle=style;
+ }
- public BlockStatementNode get(int i) {
- return (BlockStatementNode) blockstatements.get(i);
- }
+ public int size() {
+ return blockstatements.size();
+ }
- public String printNode(int indent) {
- if (printStyle==NORMAL) {
- String st="{\n";
- for(int i=0;i<blockstatements.size();i++) {
- BlockStatementNode bsn=(BlockStatementNode)blockstatements.get(i);
- st+=printSpace(indent+INDENT)+bsn.printNode(indent+INDENT);
- if (!((bsn instanceof SubBlockNode)||
- (bsn instanceof LoopNode)||
- (bsn instanceof IfStatementNode)))
- st+=";\n";
- if (bsn instanceof IfStatementNode)
- st+="\n";
- }
- st+=printSpace(indent)+"}";
- return st;
- } else if (printStyle==NOBRACES) {
- String st="";
- for(int i=0;i<blockstatements.size();i++) {
- BlockStatementNode bsn=(BlockStatementNode)blockstatements.get(i);
- st+=printSpace(indent)+bsn.printNode(indent);
- if (!((bsn instanceof SubBlockNode)||
- (bsn instanceof LoopNode)||
- (bsn instanceof IfStatementNode)))
- st+=";";
- }
- return st;
- } else if (printStyle==EXPRLIST) {
- String st="";
- for(int i=0;i<blockstatements.size();i++) {
- BlockStatementNode bsn=(BlockStatementNode)blockstatements.get(i);
- st+=bsn.printNode(0);
- if ((i+1)!=blockstatements.size())
- st+=", ";
- }
- return st;
- } else throw new Error();
- }
-
- public int kind() {
- return Kind.BlockNode;
- }
+ public BlockStatementNode get(int i) {
+ return (BlockStatementNode) blockstatements.get(i);
+ }
+
+ public String printNode(int indent) {
+ if (printStyle==NORMAL) {
+ String st="{\n";
+ for(int i=0; i<blockstatements.size(); i++) {
+ BlockStatementNode bsn=(BlockStatementNode)blockstatements.get(i);
+ st+=printSpace(indent+INDENT)+bsn.printNode(indent+INDENT);
+ if (!((bsn instanceof SubBlockNode)||
+ (bsn instanceof LoopNode)||
+ (bsn instanceof IfStatementNode)))
+ st+=";\n";
+ if (bsn instanceof IfStatementNode)
+ st+="\n";
+ }
+ st+=printSpace(indent)+"}";
+ return st;
+ } else if (printStyle==NOBRACES) {
+ String st="";
+ for(int i=0; i<blockstatements.size(); i++) {
+ BlockStatementNode bsn=(BlockStatementNode)blockstatements.get(i);
+ st+=printSpace(indent)+bsn.printNode(indent);
+ if (!((bsn instanceof SubBlockNode)||
+ (bsn instanceof LoopNode)||
+ (bsn instanceof IfStatementNode)))
+ st+=";";
+ }
+ return st;
+ } else if (printStyle==EXPRLIST) {
+ String st="";
+ for(int i=0; i<blockstatements.size(); i++) {
+ BlockStatementNode bsn=(BlockStatementNode)blockstatements.get(i);
+ st+=bsn.printNode(0);
+ if ((i+1)!=blockstatements.size())
+ st+=", ";
+ }
+ return st;
+ } else throw new Error();
+ }
+
+ public int kind() {
+ return Kind.BlockNode;
+ }
}
package IR.Tree;
public class BlockStatementNode extends TreeNode {
- public BlockStatementNode() {
- }
-
- public String printNode(int indent) {
- return null;
- }
+ public BlockStatementNode() {
+ }
+
+ public String printNode(int indent) {
+ return null;
+ }
}
public class BuildIR {
- State state;
- public BuildIR(State state) {
- this.state=state;
- }
- public void buildtree() {
- for(Iterator it=state.parsetrees.iterator();it.hasNext();) {
- ParseNode pn=(ParseNode)it.next();
- parseFile(pn);
- }
- }
-
- /** Parse the classes in this file */
- public void parseFile(ParseNode pn) {
- NameDescriptor packages;
- Vector singleimports=new Vector();
- Vector multiimports=new Vector();
-
- ParseNode ipn=pn.getChild("imports").getChild("import_decls_list");
- if (ipn!=null) {
- ParseNodeVector pnv=ipn.getChildren();
- for(int i=0;i<pnv.size();i++) {
- ParseNode pnimport=pnv.elementAt(i);
- NameDescriptor nd=parseName(pnimport.getChild("name"));
- if (isNode(pnimport,"import_single"))
- singleimports.add(nd);
- else
- multiimports.add(nd);
- }
- }
- ParseNode ppn=pn.getChild("packages").getChild("package");
- if (ppn!=null) {
- packages=parseName(pn.getChild("name"));
- }
- ParseNode tpn=pn.getChild("type_declaration_list");
- if (tpn!=null) {
- ParseNodeVector pnv=tpn.getChildren();
- for(int i=0;i<pnv.size();i++) {
- ParseNode type_pn=pnv.elementAt(i);
- if (isEmpty(type_pn)) /* Skip the semicolon */
- continue;
- if (isNode(type_pn,"class_declaration")) {
- ClassDescriptor cn=parseTypeDecl(type_pn);
- state.addClass(cn);
- } else if (isNode(type_pn,"task_declaration")) {
- TaskDescriptor td=parseTaskDecl(type_pn);
- state.addTask(td);
- } else {
- throw new Error(type_pn.getLabel());
- }
- }
- }
- }
-
- public TaskDescriptor parseTaskDecl(ParseNode pn) {
- TaskDescriptor td=new TaskDescriptor(pn.getChild("name").getTerminal());
- ParseNode bodyn=pn.getChild("body");
- BlockNode bn=parseBlock(bodyn);
- parseParameterList(td, pn);
- state.addTreeCode(td,bn);
- if (pn.getChild("flag_effects_list")!=null)
- td.addFlagEffects(parseFlags(pn.getChild("flag_effects_list")));
- return td;
- }
-
- public Vector parseFlags(ParseNode pn) {
- Vector vfe=new Vector();
- ParseNodeVector pnv=pn.getChildren();
- for(int i=0;i<pnv.size();i++) {
- ParseNode fn=pnv.elementAt(i);
- FlagEffects fe=parseFlagEffects(fn);
- vfe.add(fe);
- }
- return vfe;
- }
-
- public FlagEffects parseFlagEffects(ParseNode pn) {
- if (isNode(pn,"flag_effect")) {
- String flagname=pn.getChild("name").getTerminal();
- FlagEffects fe=new FlagEffects(flagname);
- if (pn.getChild("flag_list")!=null)
- parseFlagEffect(fe, pn.getChild("flag_list"));
- if (pn.getChild("tag_list")!=null)
- parseTagEffect(fe, pn.getChild("tag_list"));
- return fe;
- } else throw new Error();
- }
-
- public void parseTagEffect(FlagEffects fes, ParseNode pn) {
- ParseNodeVector pnv=pn.getChildren();
- for(int i=0;i<pnv.size();i++) {
- ParseNode pn2=pnv.elementAt(i);
- boolean status=true;
- if (isNode(pn2,"not")) {
- status=false;
- pn2=pn2.getChild("name");
- }
- String name=pn2.getTerminal();
- fes.addTagEffect(new TagEffect(name,status));
- }
- }
-
- public void parseFlagEffect(FlagEffects fes, ParseNode pn) {
- ParseNodeVector pnv=pn.getChildren();
- for(int i=0;i<pnv.size();i++) {
- ParseNode pn2=pnv.elementAt(i);
- boolean status=true;
- if (isNode(pn2,"not")) {
- status=false;
- pn2=pn2.getChild("name");
- }
- String name=pn2.getTerminal();
- fes.addEffect(new FlagEffect(name,status));
- }
- }
-
- public FlagExpressionNode parseFlagExpression(ParseNode pn) {
- if (isNode(pn,"or")) {
- ParseNodeVector pnv=pn.getChildren();
- ParseNode left=pnv.elementAt(0);
- ParseNode right=pnv.elementAt(1);
- return new FlagOpNode(parseFlagExpression(left), parseFlagExpression(right), new Operation(Operation.LOGIC_OR));
- } else if (isNode(pn,"and")) {
- ParseNodeVector pnv=pn.getChildren();
- ParseNode left=pnv.elementAt(0);
- ParseNode right=pnv.elementAt(1);
- return new FlagOpNode(parseFlagExpression(left), parseFlagExpression(right), new Operation(Operation.LOGIC_AND));
- } else if (isNode(pn, "not")) {
- ParseNodeVector pnv=pn.getChildren();
- ParseNode left=pnv.elementAt(0);
- return new FlagOpNode(parseFlagExpression(left), new Operation(Operation.LOGIC_NOT));
-
- } else if (isNode(pn,"name")) {
- return new FlagNode(pn.getTerminal());
+ State state;
+ public BuildIR(State state) {
+ this.state=state;
+ }
+ public void buildtree() {
+ for(Iterator it=state.parsetrees.iterator(); it.hasNext();) {
+ ParseNode pn=(ParseNode)it.next();
+ parseFile(pn);
+ }
+ }
+
+ /** Parse the classes in this file */
+ public void parseFile(ParseNode pn) {
+ NameDescriptor packages;
+ Vector singleimports=new Vector();
+ Vector multiimports=new Vector();
+
+ ParseNode ipn=pn.getChild("imports").getChild("import_decls_list");
+ if (ipn!=null) {
+ ParseNodeVector pnv=ipn.getChildren();
+ for(int i=0; i<pnv.size(); i++) {
+ ParseNode pnimport=pnv.elementAt(i);
+ NameDescriptor nd=parseName(pnimport.getChild("name"));
+ if (isNode(pnimport,"import_single"))
+ singleimports.add(nd);
+ else
+ multiimports.add(nd);
+ }
+ }
+ ParseNode ppn=pn.getChild("packages").getChild("package");
+ if (ppn!=null) {
+ packages=parseName(pn.getChild("name"));
+ }
+ ParseNode tpn=pn.getChild("type_declaration_list");
+ if (tpn!=null) {
+ ParseNodeVector pnv=tpn.getChildren();
+ for(int i=0; i<pnv.size(); i++) {
+ ParseNode type_pn=pnv.elementAt(i);
+ if (isEmpty(type_pn)) /* Skip the semicolon */
+ continue;
+ if (isNode(type_pn,"class_declaration")) {
+ ClassDescriptor cn=parseTypeDecl(type_pn);
+ state.addClass(cn);
+ } else if (isNode(type_pn,"task_declaration")) {
+ TaskDescriptor td=parseTaskDecl(type_pn);
+ state.addTask(td);
} else {
- throw new Error();
- }
- }
-
- public Vector parseChecks(ParseNode pn) {
- Vector ccs=new Vector();
- ParseNodeVector pnv=pn.getChildren();
- for(int i=0;i<pnv.size();i++) {
- ParseNode fn=pnv.elementAt(i);
- ConstraintCheck cc=parseConstraintCheck(fn);
- ccs.add(cc);
+ throw new Error(type_pn.getLabel());
}
- return ccs;
- }
-
- public ConstraintCheck parseConstraintCheck(ParseNode pn) {
- if (isNode(pn,"cons_check")) {
- String specname=pn.getChild("name").getChild("identifier").getTerminal();
- Vector[] args=parseConsArgumentList(pn);
- ConstraintCheck cc=new ConstraintCheck(specname);
- for(int i=0;i<args[0].size();i++) {
- cc.addVariable((String)args[0].get(i));
- cc.addArgument((ExpressionNode)args[1].get(i));
- }
- return cc;
+ }
+ }
+ }
+
+ public TaskDescriptor parseTaskDecl(ParseNode pn) {
+ TaskDescriptor td=new TaskDescriptor(pn.getChild("name").getTerminal());
+ ParseNode bodyn=pn.getChild("body");
+ BlockNode bn=parseBlock(bodyn);
+ parseParameterList(td, pn);
+ state.addTreeCode(td,bn);
+ if (pn.getChild("flag_effects_list")!=null)
+ td.addFlagEffects(parseFlags(pn.getChild("flag_effects_list")));
+ return td;
+ }
+
+ public Vector parseFlags(ParseNode pn) {
+ Vector vfe=new Vector();
+ ParseNodeVector pnv=pn.getChildren();
+ for(int i=0; i<pnv.size(); i++) {
+ ParseNode fn=pnv.elementAt(i);
+ FlagEffects fe=parseFlagEffects(fn);
+ vfe.add(fe);
+ }
+ return vfe;
+ }
+
+ public FlagEffects parseFlagEffects(ParseNode pn) {
+ if (isNode(pn,"flag_effect")) {
+ String flagname=pn.getChild("name").getTerminal();
+ FlagEffects fe=new FlagEffects(flagname);
+ if (pn.getChild("flag_list")!=null)
+ parseFlagEffect(fe, pn.getChild("flag_list"));
+ if (pn.getChild("tag_list")!=null)
+ parseTagEffect(fe, pn.getChild("tag_list"));
+ return fe;
+ } else throw new Error();
+ }
+
+ public void parseTagEffect(FlagEffects fes, ParseNode pn) {
+ ParseNodeVector pnv=pn.getChildren();
+ for(int i=0; i<pnv.size(); i++) {
+ ParseNode pn2=pnv.elementAt(i);
+ boolean status=true;
+ if (isNode(pn2,"not")) {
+ status=false;
+ pn2=pn2.getChild("name");
+ }
+ String name=pn2.getTerminal();
+ fes.addTagEffect(new TagEffect(name,status));
+ }
+ }
+
+ public void parseFlagEffect(FlagEffects fes, ParseNode pn) {
+ ParseNodeVector pnv=pn.getChildren();
+ for(int i=0; i<pnv.size(); i++) {
+ ParseNode pn2=pnv.elementAt(i);
+ boolean status=true;
+ if (isNode(pn2,"not")) {
+ status=false;
+ pn2=pn2.getChild("name");
+ }
+ String name=pn2.getTerminal();
+ fes.addEffect(new FlagEffect(name,status));
+ }
+ }
+
+ public FlagExpressionNode parseFlagExpression(ParseNode pn) {
+ if (isNode(pn,"or")) {
+ ParseNodeVector pnv=pn.getChildren();
+ ParseNode left=pnv.elementAt(0);
+ ParseNode right=pnv.elementAt(1);
+ return new FlagOpNode(parseFlagExpression(left), parseFlagExpression(right), new Operation(Operation.LOGIC_OR));
+ } else if (isNode(pn,"and")) {
+ ParseNodeVector pnv=pn.getChildren();
+ ParseNode left=pnv.elementAt(0);
+ ParseNode right=pnv.elementAt(1);
+ return new FlagOpNode(parseFlagExpression(left), parseFlagExpression(right), new Operation(Operation.LOGIC_AND));
+ } else if (isNode(pn, "not")) {
+ ParseNodeVector pnv=pn.getChildren();
+ ParseNode left=pnv.elementAt(0);
+ return new FlagOpNode(parseFlagExpression(left), new Operation(Operation.LOGIC_NOT));
+
+ } else if (isNode(pn,"name")) {
+ return new FlagNode(pn.getTerminal());
+ } else {
+ throw new Error();
+ }
+ }
+
+ public Vector parseChecks(ParseNode pn) {
+ Vector ccs=new Vector();
+ ParseNodeVector pnv=pn.getChildren();
+ for(int i=0; i<pnv.size(); i++) {
+ ParseNode fn=pnv.elementAt(i);
+ ConstraintCheck cc=parseConstraintCheck(fn);
+ ccs.add(cc);
+ }
+ return ccs;
+ }
+
+ public ConstraintCheck parseConstraintCheck(ParseNode pn) {
+ if (isNode(pn,"cons_check")) {
+ String specname=pn.getChild("name").getChild("identifier").getTerminal();
+ Vector[] args=parseConsArgumentList(pn);
+ ConstraintCheck cc=new ConstraintCheck(specname);
+ for(int i=0; i<args[0].size(); i++) {
+ cc.addVariable((String)args[0].get(i));
+ cc.addArgument((ExpressionNode)args[1].get(i));
+ }
+ return cc;
+ } else throw new Error();
+ }
+
+ public void parseParameterList(TaskDescriptor td, ParseNode pn) {
+
+ boolean optional;
+ ParseNode paramlist=pn.getChild("task_parameter_list");
+ if (paramlist==null)
+ return;
+ ParseNodeVector pnv=paramlist.getChildren();
+ for(int i=0; i<pnv.size(); i++) {
+ ParseNode paramn=pnv.elementAt(i);
+ if(paramn.getChild("optional")!=null){
+ optional = true;
+ paramn = paramn.getChild("optional").getFirstChild();
+ System.out.println("OPTIONAL FOUND!!!!!!!");
+ } else { optional = false;
+ System.out.println("NOT OPTIONAL");}
+
+ TypeDescriptor type=parseTypeDescriptor(paramn);
+
+ String paramname=paramn.getChild("single").getTerminal();
+ FlagExpressionNode fen=null;
+ if (paramn.getChild("flag")!=null)
+ fen=parseFlagExpression(paramn.getChild("flag").getFirstChild());
+
+ ParseNode tagnode=paramn.getChild("tag");
+
+ TagExpressionList tel=null;
+ if (tagnode!=null) {
+ tel=parseTagExpressionList(tagnode);
+ }
+
+ td.addParameter(type,paramname,fen, tel, optional);
+ }
+ }
+
+ public TagExpressionList parseTagExpressionList(ParseNode pn) {
+ //BUG FIX: change pn.getChildren() to pn.getChild("tag_expression_list").getChildren()
+ //To test, feed in any input program that uses tags
+ ParseNodeVector pnv=pn.getChild("tag_expression_list").getChildren();
+ TagExpressionList tel=new TagExpressionList();
+ for(int i=0; i<pnv.size(); i++) {
+ ParseNode tn=pnv.elementAt(i);
+ String type=tn.getChild("type").getTerminal();
+ String name=tn.getChild("single").getTerminal();
+ tel.addTag(type, name);
+ }
+ return tel;
+ }
+
+ public ClassDescriptor parseTypeDecl(ParseNode pn) {
+ ClassDescriptor cn=new ClassDescriptor(pn.getChild("name").getTerminal());
+ if (!isEmpty(pn.getChild("super").getTerminal())) {
+ /* parse superclass name */
+ ParseNode snn=pn.getChild("super").getChild("type").getChild("class").getChild("name");
+ NameDescriptor nd=parseName(snn);
+ cn.setSuper(nd.toString());
+ } else {
+ if (!(cn.getSymbol().equals(TypeUtil.ObjectClass)||
+ cn.getSymbol().equals(TypeUtil.TagClass)))
+ cn.setSuper(TypeUtil.ObjectClass);
+ }
+ cn.setModifiers(parseModifiersList(pn.getChild("modifiers")));
+ parseClassBody(cn, pn.getChild("classbody"));
+ return cn;
+ }
+
+ private void parseClassBody(ClassDescriptor cn, ParseNode pn) {
+ ParseNode decls=pn.getChild("class_body_declaration_list");
+ if (decls!=null) {
+ ParseNodeVector pnv=decls.getChildren();
+ for(int i=0; i<pnv.size(); i++) {
+ ParseNode decl=pnv.elementAt(i);
+ if (isNode(decl,"member")) {
+ parseClassMember(cn,decl);
+ } else if (isNode(decl,"constructor")) {
+ parseConstructorDecl(cn,decl.getChild("constructor_declaration"));
+ } else if (isNode(decl,"block")) {
} else throw new Error();
- }
-
- public void parseParameterList(TaskDescriptor td, ParseNode pn) {
-
- boolean optional;
- ParseNode paramlist=pn.getChild("task_parameter_list");
- if (paramlist==null)
- return;
- ParseNodeVector pnv=paramlist.getChildren();
- for(int i=0;i<pnv.size();i++) {
- ParseNode paramn=pnv.elementAt(i);
- if(paramn.getChild("optional")!=null){
- optional = true;
- paramn = paramn.getChild("optional").getFirstChild();
- System.out.println("OPTIONAL FOUND!!!!!!!");
- }
- else { optional = false;
- System.out.println("NOT OPTIONAL");
- }
-
- TypeDescriptor type=parseTypeDescriptor(paramn);
-
- String paramname=paramn.getChild("single").getTerminal();
- FlagExpressionNode fen=null;
- if (paramn.getChild("flag")!=null)
- fen=parseFlagExpression(paramn.getChild("flag").getFirstChild());
-
- ParseNode tagnode=paramn.getChild("tag");
-
- TagExpressionList tel=null;
- if (tagnode!=null) {
- tel=parseTagExpressionList(tagnode);
- }
-
- td.addParameter(type,paramname,fen, tel, optional);
- }
- }
-
- public TagExpressionList parseTagExpressionList(ParseNode pn) {
- //BUG FIX: change pn.getChildren() to pn.getChild("tag_expression_list").getChildren()
- //To test, feed in any input program that uses tags
- ParseNodeVector pnv=pn.getChild("tag_expression_list").getChildren();
- TagExpressionList tel=new TagExpressionList();
- for(int i=0;i<pnv.size();i++) {
- ParseNode tn=pnv.elementAt(i);
- String type=tn.getChild("type").getTerminal();
- String name=tn.getChild("single").getTerminal();
- tel.addTag(type, name);
- }
- return tel;
- }
-
- public ClassDescriptor parseTypeDecl(ParseNode pn) {
- ClassDescriptor cn=new ClassDescriptor(pn.getChild("name").getTerminal());
- if (!isEmpty(pn.getChild("super").getTerminal())) {
- /* parse superclass name */
- ParseNode snn=pn.getChild("super").getChild("type").getChild("class").getChild("name");
- NameDescriptor nd=parseName(snn);
- cn.setSuper(nd.toString());
- } else {
- if (!(cn.getSymbol().equals(TypeUtil.ObjectClass)||
- cn.getSymbol().equals(TypeUtil.TagClass)))
- cn.setSuper(TypeUtil.ObjectClass);
+ }
+ }
+ }
+
+ private void parseClassMember(ClassDescriptor cn, ParseNode pn) {
+ ParseNode fieldnode=pn.getChild("field");
+
+ if (fieldnode!=null) {
+ parseFieldDecl(cn,fieldnode.getChild("field_declaration"));
+ return;
+ }
+ ParseNode methodnode=pn.getChild("method");
+ if (methodnode!=null) {
+ parseMethodDecl(cn,methodnode.getChild("method_declaration"));
+ return;
+ }
+ ParseNode flagnode=pn.getChild("flag");
+ if (flagnode!=null) {
+ parseFlagDecl(cn, flagnode.getChild("flag_declaration"));
+ return;
+ }
+ throw new Error();
+ }
+
+ private TypeDescriptor parseTypeDescriptor(ParseNode pn) {
+ ParseNode tn=pn.getChild("type");
+
+ String type_st=tn.getTerminal();
+ if(type_st.equals("byte")) {
+ return state.getTypeDescriptor(TypeDescriptor.BYTE);
+ } else if(type_st.equals("short")) {
+ return state.getTypeDescriptor(TypeDescriptor.SHORT);
+ } else if(type_st.equals("boolean")) {
+ return state.getTypeDescriptor(TypeDescriptor.BOOLEAN);
+ } else if(type_st.equals("int")) {
+ return state.getTypeDescriptor(TypeDescriptor.INT);
+ } else if(type_st.equals("long")) {
+ return state.getTypeDescriptor(TypeDescriptor.LONG);
+ } else if(type_st.equals("char")) {
+ return state.getTypeDescriptor(TypeDescriptor.CHAR);
+ } else if(type_st.equals("float")) {
+ return state.getTypeDescriptor(TypeDescriptor.FLOAT);
+ } else if(type_st.equals("double")) {
+ return state.getTypeDescriptor(TypeDescriptor.DOUBLE);
+ } else if(type_st.equals("class")) {
+ ParseNode nn=tn.getChild("class");
+ return state.getTypeDescriptor(parseName(nn.getChild("name")));
+ } else if(type_st.equals("array")) {
+ ParseNode nn=tn.getChild("array");
+ TypeDescriptor td=parseTypeDescriptor(nn.getChild("basetype"));
+ Integer numdims=(Integer)nn.getChild("dims").getLiteral();
+ for(int i=0; i<numdims.intValue(); i++)
+ td=td.makeArray(state);
+ return td;
+ } else {
+ throw new Error();
+ }
+ }
+
+ private NameDescriptor parseName(ParseNode nn) {
+ ParseNode base=nn.getChild("base");
+ ParseNode id=nn.getChild("identifier");
+ if (base==null)
+ return new NameDescriptor(id.getTerminal());
+ return new NameDescriptor(parseName(base.getChild("name")),id.getTerminal());
+
+ }
+
+ private void parseFlagDecl(ClassDescriptor cn,ParseNode pn) {
+ String name=pn.getChild("name").getTerminal();
+ FlagDescriptor flag=new FlagDescriptor(name);
+ if (pn.getChild("external")!=null)
+ flag.makeExternal();
+ cn.addFlag(flag);
+ }
+
+ private void parseFieldDecl(ClassDescriptor cn,ParseNode pn) {
+ ParseNode mn=pn.getChild("modifier");
+ Modifiers m=parseModifiersList(mn);
+
+ ParseNode tn=pn.getChild("type");
+ TypeDescriptor t=parseTypeDescriptor(tn);
+ ParseNode vn=pn.getChild("variables").getChild("variable_declarators_list");
+ ParseNodeVector pnv=vn.getChildren();
+ boolean isglobal=pn.getChild("global")!=null;
+
+ for(int i=0; i<pnv.size(); i++) {
+ ParseNode vardecl=pnv.elementAt(i);
+ ParseNode tmp=vardecl;
+ TypeDescriptor arrayt=t;
+ while (tmp.getChild("single")==null) {
+ arrayt=arrayt.makeArray(state);
+ tmp=tmp.getChild("array");
+ }
+ String identifier=tmp.getChild("single").getTerminal();
+ ParseNode epn=vardecl.getChild("initializer");
+
+ ExpressionNode en=null;
+ if (epn!=null)
+ en=parseExpression(epn.getFirstChild());
+
+ cn.addField(new FieldDescriptor(m, arrayt, identifier, en, isglobal));
+ }
+ }
+
+ private ExpressionNode parseExpression(ParseNode pn) {
+ if (isNode(pn,"assignment"))
+ return parseAssignmentExpression(pn);
+ else if (isNode(pn,"logical_or")||isNode(pn,"logical_and")||
+ isNode(pn,"bitwise_or")||isNode(pn,"bitwise_xor")||
+ isNode(pn,"bitwise_and")||isNode(pn,"equal")||
+ isNode(pn,"not_equal")||isNode(pn,"comp_lt")||
+ isNode(pn,"comp_lte")||isNode(pn,"comp_gt")||
+ isNode(pn,"comp_gte")||isNode(pn,"leftshift")||
+ isNode(pn,"rightshift")||isNode(pn,"sub")||
+ isNode(pn,"urightshift")||isNode(pn,"sub")||
+ isNode(pn,"add")||isNode(pn,"mult")||
+ isNode(pn,"div")||isNode(pn,"mod")) {
+ ParseNodeVector pnv=pn.getChildren();
+ ParseNode left=pnv.elementAt(0);
+ ParseNode right=pnv.elementAt(1);
+ Operation op=new Operation(pn.getLabel());
+ return new OpNode(parseExpression(left),parseExpression(right),op);
+ } else if (isNode(pn,"unaryplus")||
+ isNode(pn,"unaryminus")||
+ isNode(pn,"not")||
+ isNode(pn,"comp")) {
+ ParseNode left=pn.getFirstChild();
+ Operation op=new Operation(pn.getLabel());
+ return new OpNode(parseExpression(left),op);
+ } else if (isNode(pn,"postinc")||
+ isNode(pn,"postdec")) {
+ ParseNode left=pn.getFirstChild();
+ AssignOperation op=new AssignOperation(pn.getLabel());
+ return new AssignmentNode(parseExpression(left),null,op);
+
+ } else if (isNode(pn,"preinc")||
+ isNode(pn,"predec")) {
+ ParseNode left=pn.getFirstChild();
+ AssignOperation op=isNode(pn,"preinc") ? new AssignOperation(AssignOperation.PLUSEQ) : new AssignOperation(AssignOperation.MINUSEQ);
+ return new AssignmentNode(parseExpression(left),
+ new LiteralNode("integer",new Integer(1)),op);
+ } else if (isNode(pn,"literal")) {
+ String literaltype=pn.getTerminal();
+ ParseNode literalnode=pn.getChild(literaltype);
+ Object literal_obj=literalnode.getLiteral();
+ return new LiteralNode(literaltype, literal_obj);
+ } else if (isNode(pn,"createobject")) {
+ TypeDescriptor td=parseTypeDescriptor(pn);
+ Vector args=parseArgumentList(pn);
+ boolean isglobal=pn.getChild("global")!=null;
+ CreateObjectNode con=new CreateObjectNode(td, isglobal);
+ for(int i=0; i<args.size(); i++) {
+ con.addArgument((ExpressionNode)args.get(i));
+ }
+ /* Could have flag set or tag added here */
+ if (pn.getChild("flag_list")!=null||pn.getChild("tag_list")!=null) {
+ FlagEffects fe=new FlagEffects(null);
+ if (pn.getChild("flag_list")!=null)
+ parseFlagEffect(fe, pn.getChild("flag_list"));
+
+ if (pn.getChild("tag_list")!=null)
+ parseTagEffect(fe, pn.getChild("tag_list"));
+ con.addFlagEffects(fe);
+ }
+
+ return con;
+ } else if (isNode(pn,"createarray")) {
+ //System.out.println(pn.PPrint(3,true));
+ boolean isglobal=pn.getChild("global")!=null;
+ TypeDescriptor td=parseTypeDescriptor(pn);
+ Vector args=parseDimExprs(pn);
+ int num=0;
+ if (pn.getChild("dims_opt").getLiteral()!=null)
+ num=((Integer)pn.getChild("dims_opt").getLiteral()).intValue();
+ for(int i=0; i<(args.size()+num); i++)
+ td=td.makeArray(state);
+ CreateObjectNode con=new CreateObjectNode(td, isglobal);
+ for(int i=0; i<args.size(); i++) {
+ con.addArgument((ExpressionNode)args.get(i));
+ }
+ return con;
+ } else if (isNode(pn,"name")) {
+ NameDescriptor nd=parseName(pn);
+ return new NameNode(nd);
+ } else if (isNode(pn,"this")) {
+ NameDescriptor nd=new NameDescriptor("this");
+ return new NameNode(nd);
+ } else if (isNode(pn,"isavailable")) {
+ NameDescriptor nd=new NameDescriptor(pn.getTerminal());
+ return new OpNode(new NameNode(nd),null,new Operation(Operation.ISAVAILABLE));
+ } else if (isNode(pn,"methodinvoke1")) {
+ NameDescriptor nd=parseName(pn.getChild("name"));
+ Vector args=parseArgumentList(pn);
+ MethodInvokeNode min=new MethodInvokeNode(nd);
+ for(int i=0; i<args.size(); i++) {
+ min.addArgument((ExpressionNode)args.get(i));
+ }
+ return min;
+ } else if (isNode(pn,"methodinvoke2")) {
+ String methodid=pn.getChild("id").getTerminal();
+ ExpressionNode exp=parseExpression(pn.getChild("base").getFirstChild());
+ Vector args=parseArgumentList(pn);
+ MethodInvokeNode min=new MethodInvokeNode(methodid,exp);
+ for(int i=0; i<args.size(); i++) {
+ min.addArgument((ExpressionNode)args.get(i));
+ }
+ return min;
+ } else if (isNode(pn,"fieldaccess")) {
+ ExpressionNode en=parseExpression(pn.getChild("base").getFirstChild()); String fieldname=pn.getChild("field").getTerminal();
+ return new FieldAccessNode(en,fieldname);
+ } else if (isNode(pn,"arrayaccess")) {
+ ExpressionNode en=parseExpression(pn.getChild("base").getFirstChild());
+ ExpressionNode index=parseExpression(pn.getChild("index").getFirstChild());
+ return new ArrayAccessNode(en,index);
+ } else if (isNode(pn,"cast1")) {
+ return new CastNode(parseTypeDescriptor(pn.getChild("type")),parseExpression(pn.getChild("exp").getFirstChild()));
+ } else if (isNode(pn,"cast2")) {
+ return new CastNode(parseExpression(pn.getChild("type").getFirstChild()),parseExpression(pn.getChild("exp").getFirstChild()));
+ } else {
+ System.out.println("---------------------");
+ System.out.println(pn.PPrint(3,true));
+ throw new Error();
+ }
+ }
+
+ private Vector parseDimExprs(ParseNode pn) {
+ Vector arglist=new Vector();
+ ParseNode an=pn.getChild("dim_exprs");
+ if (an==null) /* No argument list */
+ return arglist;
+ ParseNodeVector anv=an.getChildren();
+ for(int i=0; i<anv.size(); i++) {
+ arglist.add(parseExpression(anv.elementAt(i)));
+ }
+ return arglist;
+ }
+
+ private Vector parseArgumentList(ParseNode pn) {
+ Vector arglist=new Vector();
+ ParseNode an=pn.getChild("argument_list");
+ if (an==null) /* No argument list */
+ return arglist;
+ ParseNodeVector anv=an.getChildren();
+ for(int i=0; i<anv.size(); i++) {
+ arglist.add(parseExpression(anv.elementAt(i)));
+ }
+ return arglist;
+ }
+
+ private Vector[] parseConsArgumentList(ParseNode pn) {
+ Vector arglist=new Vector();
+ Vector varlist=new Vector();
+ ParseNode an=pn.getChild("cons_argument_list");
+ if (an==null) /* No argument list */
+ return new Vector[] {varlist, arglist};
+ ParseNodeVector anv=an.getChildren();
+ for(int i=0; i<anv.size(); i++) {
+ ParseNode cpn=anv.elementAt(i);
+ ParseNode var=cpn.getChild("var");
+ ParseNode exp=cpn.getChild("exp").getFirstChild();
+ varlist.add(var.getTerminal());
+ arglist.add(parseExpression(exp));
+ }
+ return new Vector[] {varlist, arglist};
+ }
+
+ private ExpressionNode parseAssignmentExpression(ParseNode pn) {
+ AssignOperation ao=new AssignOperation(pn.getChild("op").getTerminal());
+ ParseNodeVector pnv=pn.getChild("args").getChildren();
+
+ AssignmentNode an=new AssignmentNode(parseExpression(pnv.elementAt(0)),parseExpression(pnv.elementAt(1)),ao);
+ return an;
+ }
+
+
+ private void parseMethodDecl(ClassDescriptor cn, ParseNode pn) {
+ ParseNode headern=pn.getChild("method_header");
+ ParseNode bodyn=pn.getChild("body");
+ MethodDescriptor md=parseMethodHeader(headern);
+ BlockNode bn=parseBlock(bodyn);
+ cn.addMethod(md);
+ state.addTreeCode(md,bn);
+ }
+
+ private void parseConstructorDecl(ClassDescriptor cn, ParseNode pn) {
+ ParseNode mn=pn.getChild("modifiers");
+ Modifiers m=parseModifiersList(mn);
+ ParseNode cdecl=pn.getChild("constructor_declarator");
+ boolean isglobal=cdecl.getChild("global")!=null;
+ String name=cdecl.getChild("name").getChild("identifier").getTerminal();
+ MethodDescriptor md=new MethodDescriptor(m, name, isglobal);
+ ParseNode paramnode=cdecl.getChild("parameters");
+ parseParameterList(md,paramnode);
+ ParseNode bodyn0=pn.getChild("body");
+ ParseNode bodyn=bodyn0.getChild("constructor_body");
+ cn.addMethod(md);
+ BlockNode bn=null;
+ if (bodyn!=null&&bodyn.getChild("block_statement_list")!=null)
+ bn=parseBlock(bodyn);
+ else
+ bn=new BlockNode();
+ if (bodyn!=null&&bodyn.getChild("superinvoke")!=null) {
+ ParseNode sin=bodyn.getChild("superinvoke");
+ NameDescriptor nd=new NameDescriptor("super");
+ Vector args=parseArgumentList(sin);
+ MethodInvokeNode min=new MethodInvokeNode(nd);
+ for(int i=0; i<args.size(); i++) {
+ min.addArgument((ExpressionNode)args.get(i));
+ }
+ BlockExpressionNode ben=new BlockExpressionNode(min);
+ bn.addFirstBlockStatement(ben);
+ }
+ state.addTreeCode(md,bn);
+ }
+
+ public BlockNode parseBlock(ParseNode pn) {
+ if (pn==null||isEmpty(pn.getTerminal()))
+ return new BlockNode();
+ ParseNode bsn=pn.getChild("block_statement_list");
+ return parseBlockHelper(bsn);
+ }
+
+ private BlockNode parseBlockHelper(ParseNode pn) {
+ ParseNodeVector pnv=pn.getChildren();
+ BlockNode bn=new BlockNode();
+ for(int i=0; i<pnv.size(); i++) {
+ Vector bsv=parseBlockStatement(pnv.elementAt(i));
+ for(int j=0; j<bsv.size(); j++) {
+ bn.addBlockStatement((BlockStatementNode)bsv.get(j));
+ }
+ }
+ return bn;
+ }
+
+ public BlockNode parseSingleBlock(ParseNode pn) {
+ BlockNode bn=new BlockNode();
+ Vector bsv=parseBlockStatement(pn);
+ for(int j=0; j<bsv.size(); j++) {
+ bn.addBlockStatement((BlockStatementNode)bsv.get(j));
+ }
+ bn.setStyle(BlockNode.NOBRACES);
+ return bn;
+ }
+
+ public Vector parseBlockStatement(ParseNode pn) {
+ Vector blockstatements=new Vector();
+ if (isNode(pn,"tag_declaration")) {
+ String name=pn.getChild("single").getTerminal();
+ String type=pn.getChild("type").getTerminal();
+
+ blockstatements.add(new TagDeclarationNode(name, type));
+ } else if (isNode(pn,"local_variable_declaration")) {
+ TypeDescriptor t=parseTypeDescriptor(pn);
+ ParseNode vn=pn.getChild("variable_declarators_list");
+ ParseNodeVector pnv=vn.getChildren();
+ for(int i=0; i<pnv.size(); i++) {
+ ParseNode vardecl=pnv.elementAt(i);
+
+
+ ParseNode tmp=vardecl;
+ TypeDescriptor arrayt=t;
+ while (tmp.getChild("single")==null) {
+ arrayt=arrayt.makeArray(state);
+ tmp=tmp.getChild("array");
}
- cn.setModifiers(parseModifiersList(pn.getChild("modifiers")));
- parseClassBody(cn, pn.getChild("classbody"));
- return cn;
- }
-
- private void parseClassBody(ClassDescriptor cn, ParseNode pn) {
- ParseNode decls=pn.getChild("class_body_declaration_list");
- if (decls!=null) {
- ParseNodeVector pnv=decls.getChildren();
- for(int i=0;i<pnv.size();i++) {
- ParseNode decl=pnv.elementAt(i);
- if (isNode(decl,"member")) {
- parseClassMember(cn,decl);
- } else if (isNode(decl,"constructor")) {
- parseConstructorDecl(cn,decl.getChild("constructor_declaration"));
- } else if (isNode(decl,"block")) {
- } else throw new Error();
- }
+ String identifier=tmp.getChild("single").getTerminal();
+
+ ParseNode epn=vardecl.getChild("initializer");
+
+
+ ExpressionNode en=null;
+ if (epn!=null)
+ en=parseExpression(epn.getFirstChild());
+
+ blockstatements.add(new DeclarationNode(new VarDescriptor(arrayt, identifier),en));
+ }
+ } else if (isNode(pn,"nop")) {
+ /* Do Nothing */
+ } else if (isNode(pn,"expression")) {
+ blockstatements.add(new BlockExpressionNode(parseExpression(pn.getFirstChild())));
+ } else if (isNode(pn,"ifstatement")) {
+ blockstatements.add(new IfStatementNode(parseExpression(pn.getChild("condition").getFirstChild()),
+ parseSingleBlock(pn.getChild("statement").getFirstChild()),
+ pn.getChild("else_statement")!=null ? parseSingleBlock(pn.getChild("else_statement").getFirstChild()) : null));
+ } else if (isNode(pn,"taskexit")) {
+ Vector vfe=null;
+ if (pn.getChild("flag_effects_list")!=null)
+ vfe=parseFlags(pn.getChild("flag_effects_list"));
+ Vector ccs=null;
+ if (pn.getChild("cons_checks")!=null)
+ ccs=parseChecks(pn.getChild("cons_checks"));
+
+ blockstatements.add(new TaskExitNode(vfe, ccs));
+ } else if (isNode(pn,"atomic")) {
+ BlockNode bn=parseBlockHelper(pn);
+ blockstatements.add(new AtomicNode(bn));
+ } else if (isNode(pn,"return")) {
+ if (isEmpty(pn.getTerminal()))
+ blockstatements.add(new ReturnNode());
+ else {
+ ExpressionNode en=parseExpression(pn.getFirstChild());
+ blockstatements.add(new ReturnNode(en));
+ }
+ } else if (isNode(pn,"block_statement_list")) {
+ BlockNode bn=parseBlockHelper(pn);
+ blockstatements.add(new SubBlockNode(bn));
+ } else if (isNode(pn,"empty")) {
+ /* nop */
+ } else if (isNode(pn,"statement_expression_list")) {
+ ParseNodeVector pnv=pn.getChildren();
+ BlockNode bn=new BlockNode();
+ for(int i=0; i<pnv.size(); i++) {
+ ExpressionNode en=parseExpression(pnv.elementAt(i));
+ blockstatements.add(new BlockExpressionNode(en));
+ }
+ bn.setStyle(BlockNode.EXPRLIST);
+ } else if (isNode(pn,"forstatement")) {
+ BlockNode init=parseSingleBlock(pn.getChild("initializer").getFirstChild());
+ BlockNode update=parseSingleBlock(pn.getChild("update").getFirstChild());
+ ExpressionNode condition=parseExpression(pn.getChild("condition").getFirstChild());
+ BlockNode body=parseSingleBlock(pn.getChild("statement").getFirstChild());
+ blockstatements.add(new LoopNode(init,condition,update,body));
+ } else if (isNode(pn,"whilestatement")) {
+ ExpressionNode condition=parseExpression(pn.getChild("condition").getFirstChild());
+ BlockNode body=parseSingleBlock(pn.getChild("statement").getFirstChild());
+ blockstatements.add(new LoopNode(condition,body,LoopNode.WHILELOOP));
+ } else if (isNode(pn,"dowhilestatement")) {
+ ExpressionNode condition=parseExpression(pn.getChild("condition").getFirstChild());
+ BlockNode body=parseSingleBlock(pn.getChild("statement").getFirstChild());
+ blockstatements.add(new LoopNode(condition,body,LoopNode.DOWHILELOOP));
+ } else {
+ System.out.println("---------------");
+ System.out.println(pn.PPrint(3,true));
+ throw new Error();
+ }
+ return blockstatements;
+ }
+
+ public MethodDescriptor parseMethodHeader(ParseNode pn) {
+ ParseNode mn=pn.getChild("modifiers");
+ Modifiers m=parseModifiersList(mn);
+
+ ParseNode tn=pn.getChild("returntype");
+ TypeDescriptor returntype;
+ if (tn!=null)
+ returntype=parseTypeDescriptor(tn);
+ else
+ returntype=new TypeDescriptor(TypeDescriptor.VOID);
+
+ ParseNode pmd=pn.getChild("method_declarator");
+ String name=pmd.getChild("name").getTerminal();
+ MethodDescriptor md=new MethodDescriptor(m, returntype, name);
+
+ ParseNode paramnode=pmd.getChild("parameters");
+ parseParameterList(md,paramnode);
+ return md;
+ }
+
+ public void parseParameterList(MethodDescriptor md, ParseNode pn) {
+ ParseNode paramlist=pn.getChild("formal_parameter_list");
+ if (paramlist==null)
+ return;
+ ParseNodeVector pnv=paramlist.getChildren();
+ for(int i=0; i<pnv.size(); i++) {
+ ParseNode paramn=pnv.elementAt(i);
+
+ if (isNode(paramn, "tag_parameter")) {
+ String paramname=paramn.getChild("single").getTerminal();
+ TypeDescriptor type=new TypeDescriptor(TypeDescriptor.TAG);
+ md.addTagParameter(type, paramname);
+ } else {
+ TypeDescriptor type=parseTypeDescriptor(paramn);
+
+ ParseNode tmp=paramn;
+ while (tmp.getChild("single")==null) {
+ type=type.makeArray(state);
+ tmp=tmp.getChild("array");
}
- }
-
- private void parseClassMember(ClassDescriptor cn, ParseNode pn) {
- ParseNode fieldnode=pn.getChild("field");
-
- if (fieldnode!=null) {
- parseFieldDecl(cn,fieldnode.getChild("field_declaration"));
- return;
- }
- ParseNode methodnode=pn.getChild("method");
- if (methodnode!=null) {
- parseMethodDecl(cn,methodnode.getChild("method_declaration"));
- return;
- }
- ParseNode flagnode=pn.getChild("flag");
- if (flagnode!=null) {
- parseFlagDecl(cn, flagnode.getChild("flag_declaration"));
- return;
- }
- throw new Error();
- }
-
- private TypeDescriptor parseTypeDescriptor(ParseNode pn) {
- ParseNode tn=pn.getChild("type");
-
- String type_st=tn.getTerminal();
- if(type_st.equals("byte")) {
- return state.getTypeDescriptor(TypeDescriptor.BYTE);
- } else if(type_st.equals("short")) {
- return state.getTypeDescriptor(TypeDescriptor.SHORT);
- } else if(type_st.equals("boolean")) {
- return state.getTypeDescriptor(TypeDescriptor.BOOLEAN);
- } else if(type_st.equals("int")) {
- return state.getTypeDescriptor(TypeDescriptor.INT);
- } else if(type_st.equals("long")) {
- return state.getTypeDescriptor(TypeDescriptor.LONG);
- } else if(type_st.equals("char")) {
- return state.getTypeDescriptor(TypeDescriptor.CHAR);
- } else if(type_st.equals("float")) {
- return state.getTypeDescriptor(TypeDescriptor.FLOAT);
- } else if(type_st.equals("double")) {
- return state.getTypeDescriptor(TypeDescriptor.DOUBLE);
- } else if(type_st.equals("class")) {
- ParseNode nn=tn.getChild("class");
- return state.getTypeDescriptor(parseName(nn.getChild("name")));
- } else if(type_st.equals("array")) {
- ParseNode nn=tn.getChild("array");
- TypeDescriptor td=parseTypeDescriptor(nn.getChild("basetype"));
- Integer numdims=(Integer)nn.getChild("dims").getLiteral();
- for(int i=0;i<numdims.intValue();i++)
- td=td.makeArray(state);
- return td;
- } else {
- throw new Error();
- }
- }
-
- private NameDescriptor parseName(ParseNode nn) {
- ParseNode base=nn.getChild("base");
- ParseNode id=nn.getChild("identifier");
- if (base==null)
- return new NameDescriptor(id.getTerminal());
- return new NameDescriptor(parseName(base.getChild("name")),id.getTerminal());
-
- }
-
- private void parseFlagDecl(ClassDescriptor cn,ParseNode pn) {
- String name=pn.getChild("name").getTerminal();
- FlagDescriptor flag=new FlagDescriptor(name);
- if (pn.getChild("external")!=null)
- flag.makeExternal();
- cn.addFlag(flag);
- }
-
- private void parseFieldDecl(ClassDescriptor cn,ParseNode pn) {
- ParseNode mn=pn.getChild("modifier");
- Modifiers m=parseModifiersList(mn);
-
- ParseNode tn=pn.getChild("type");
- TypeDescriptor t=parseTypeDescriptor(tn);
- ParseNode vn=pn.getChild("variables").getChild("variable_declarators_list");
- ParseNodeVector pnv=vn.getChildren();
- boolean isglobal=pn.getChild("global")!=null;
-
- for(int i=0;i<pnv.size();i++) {
- ParseNode vardecl=pnv.elementAt(i);
- ParseNode tmp=vardecl;
- TypeDescriptor arrayt=t;
- while (tmp.getChild("single")==null) {
- arrayt=arrayt.makeArray(state);
- tmp=tmp.getChild("array");
- }
- String identifier=tmp.getChild("single").getTerminal();
- ParseNode epn=vardecl.getChild("initializer");
-
- ExpressionNode en=null;
- if (epn!=null)
- en=parseExpression(epn.getFirstChild());
-
- cn.addField(new FieldDescriptor(m, arrayt, identifier, en, isglobal));
- }
- }
-
- private ExpressionNode parseExpression(ParseNode pn) {
- if (isNode(pn,"assignment"))
- return parseAssignmentExpression(pn);
- else if (isNode(pn,"logical_or")||isNode(pn,"logical_and")||
- isNode(pn,"bitwise_or")||isNode(pn,"bitwise_xor")||
- isNode(pn,"bitwise_and")||isNode(pn,"equal")||
- isNode(pn,"not_equal")||isNode(pn,"comp_lt")||
- isNode(pn,"comp_lte")||isNode(pn,"comp_gt")||
- isNode(pn,"comp_gte")||isNode(pn,"leftshift")||
- isNode(pn,"rightshift")||isNode(pn,"sub")||
- isNode(pn,"urightshift")||isNode(pn,"sub")||
- isNode(pn,"add")||isNode(pn,"mult")||
- isNode(pn,"div")||isNode(pn,"mod")) {
- ParseNodeVector pnv=pn.getChildren();
- ParseNode left=pnv.elementAt(0);
- ParseNode right=pnv.elementAt(1);
- Operation op=new Operation(pn.getLabel());
- return new OpNode(parseExpression(left),parseExpression(right),op);
- } else if (isNode(pn,"unaryplus")||
- isNode(pn,"unaryminus")||
- isNode(pn,"not")||
- isNode(pn,"comp")) {
- ParseNode left=pn.getFirstChild();
- Operation op=new Operation(pn.getLabel());
- return new OpNode(parseExpression(left),op);
- } else if (isNode(pn,"postinc")||
- isNode(pn,"postdec")) {
- ParseNode left=pn.getFirstChild();
- AssignOperation op=new AssignOperation(pn.getLabel());
- return new AssignmentNode(parseExpression(left),null,op);
-
- } else if (isNode(pn,"preinc")||
- isNode(pn,"predec")) {
- ParseNode left=pn.getFirstChild();
- AssignOperation op=isNode(pn,"preinc")?new AssignOperation(AssignOperation.PLUSEQ):new AssignOperation(AssignOperation.MINUSEQ);
- return new AssignmentNode(parseExpression(left),
- new LiteralNode("integer",new Integer(1)),op);
- } else if (isNode(pn,"literal")) {
- String literaltype=pn.getTerminal();
- ParseNode literalnode=pn.getChild(literaltype);
- Object literal_obj=literalnode.getLiteral();
- return new LiteralNode(literaltype, literal_obj);
- } else if (isNode(pn,"createobject")) {
- TypeDescriptor td=parseTypeDescriptor(pn);
- Vector args=parseArgumentList(pn);
- boolean isglobal=pn.getChild("global")!=null;
- CreateObjectNode con=new CreateObjectNode(td, isglobal);
- for(int i=0;i<args.size();i++) {
- con.addArgument((ExpressionNode)args.get(i));
- }
- /* Could have flag set or tag added here */
- if (pn.getChild("flag_list")!=null||pn.getChild("tag_list")!=null) {
- FlagEffects fe=new FlagEffects(null);
- if (pn.getChild("flag_list")!=null)
- parseFlagEffect(fe, pn.getChild("flag_list"));
-
- if (pn.getChild("tag_list")!=null)
- parseTagEffect(fe, pn.getChild("tag_list"));
- con.addFlagEffects(fe);
- }
-
- return con;
- } else if (isNode(pn,"createarray")) {
- //System.out.println(pn.PPrint(3,true));
- boolean isglobal=pn.getChild("global")!=null;
- TypeDescriptor td=parseTypeDescriptor(pn);
- Vector args=parseDimExprs(pn);
- int num=0;
- if (pn.getChild("dims_opt").getLiteral()!=null)
- num=((Integer)pn.getChild("dims_opt").getLiteral()).intValue();
- for(int i=0;i<(args.size()+num);i++)
- td=td.makeArray(state);
- CreateObjectNode con=new CreateObjectNode(td, isglobal);
- for(int i=0;i<args.size();i++) {
- con.addArgument((ExpressionNode)args.get(i));
- }
- return con;
- } else if (isNode(pn,"name")) {
- NameDescriptor nd=parseName(pn);
- return new NameNode(nd);
- } else if (isNode(pn,"this")) {
- NameDescriptor nd=new NameDescriptor("this");
- return new NameNode(nd);
- } else if (isNode(pn,"isavailable")) {
- NameDescriptor nd=new NameDescriptor(pn.getTerminal());
- return new OpNode(new NameNode(nd),null,new Operation(Operation.ISAVAILABLE));
- } else if (isNode(pn,"methodinvoke1")) {
- NameDescriptor nd=parseName(pn.getChild("name"));
- Vector args=parseArgumentList(pn);
- MethodInvokeNode min=new MethodInvokeNode(nd);
- for(int i=0;i<args.size();i++) {
- min.addArgument((ExpressionNode)args.get(i));
- }
- return min;
- } else if (isNode(pn,"methodinvoke2")) {
- String methodid=pn.getChild("id").getTerminal();
- ExpressionNode exp=parseExpression(pn.getChild("base").getFirstChild());
- Vector args=parseArgumentList(pn);
- MethodInvokeNode min=new MethodInvokeNode(methodid,exp);
- for(int i=0;i<args.size();i++) {
- min.addArgument((ExpressionNode)args.get(i));
- }
- return min;
- } else if (isNode(pn,"fieldaccess")) {
- ExpressionNode en=parseExpression(pn.getChild("base").getFirstChild()); String fieldname=pn.getChild("field").getTerminal();
- return new FieldAccessNode(en,fieldname);
- } else if (isNode(pn,"arrayaccess")) {
- ExpressionNode en=parseExpression(pn.getChild("base").getFirstChild());
- ExpressionNode index=parseExpression(pn.getChild("index").getFirstChild());
- return new ArrayAccessNode(en,index);
- } else if (isNode(pn,"cast1")) {
- return new CastNode(parseTypeDescriptor(pn.getChild("type")),parseExpression(pn.getChild("exp").getFirstChild()));
- } else if (isNode(pn,"cast2")) {
- return new CastNode(parseExpression(pn.getChild("type").getFirstChild()),parseExpression(pn.getChild("exp").getFirstChild()));
- } else {
- System.out.println("---------------------");
- System.out.println(pn.PPrint(3,true));
- throw new Error();
- }
- }
-
- private Vector parseDimExprs(ParseNode pn) {
- Vector arglist=new Vector();
- ParseNode an=pn.getChild("dim_exprs");
- if (an==null) /* No argument list */
- return arglist;
- ParseNodeVector anv=an.getChildren();
- for(int i=0;i<anv.size();i++) {
- arglist.add(parseExpression(anv.elementAt(i)));
- }
- return arglist;
- }
-
- private Vector parseArgumentList(ParseNode pn) {
- Vector arglist=new Vector();
- ParseNode an=pn.getChild("argument_list");
- if (an==null) /* No argument list */
- return arglist;
- ParseNodeVector anv=an.getChildren();
- for(int i=0;i<anv.size();i++) {
- arglist.add(parseExpression(anv.elementAt(i)));
- }
- return arglist;
- }
-
- private Vector[] parseConsArgumentList(ParseNode pn) {
- Vector arglist=new Vector();
- Vector varlist=new Vector();
- ParseNode an=pn.getChild("cons_argument_list");
- if (an==null) /* No argument list */
- return new Vector[] {varlist, arglist};
- ParseNodeVector anv=an.getChildren();
- for(int i=0;i<anv.size();i++) {
- ParseNode cpn=anv.elementAt(i);
- ParseNode var=cpn.getChild("var");
- ParseNode exp=cpn.getChild("exp").getFirstChild();
- varlist.add(var.getTerminal());
- arglist.add(parseExpression(exp));
- }
- return new Vector[] {varlist, arglist};
- }
-
- private ExpressionNode parseAssignmentExpression(ParseNode pn) {
- AssignOperation ao=new AssignOperation(pn.getChild("op").getTerminal());
- ParseNodeVector pnv=pn.getChild("args").getChildren();
-
- AssignmentNode an=new AssignmentNode(parseExpression(pnv.elementAt(0)),parseExpression(pnv.elementAt(1)),ao);
- return an;
- }
-
-
- private void parseMethodDecl(ClassDescriptor cn, ParseNode pn) {
- ParseNode headern=pn.getChild("method_header");
- ParseNode bodyn=pn.getChild("body");
- MethodDescriptor md=parseMethodHeader(headern);
- BlockNode bn=parseBlock(bodyn);
- cn.addMethod(md);
- state.addTreeCode(md,bn);
- }
-
- private void parseConstructorDecl(ClassDescriptor cn, ParseNode pn) {
- ParseNode mn=pn.getChild("modifiers");
- Modifiers m=parseModifiersList(mn);
- ParseNode cdecl=pn.getChild("constructor_declarator");
- boolean isglobal=cdecl.getChild("global")!=null;
- String name=cdecl.getChild("name").getChild("identifier").getTerminal();
- MethodDescriptor md=new MethodDescriptor(m, name, isglobal);
- ParseNode paramnode=cdecl.getChild("parameters");
- parseParameterList(md,paramnode);
- ParseNode bodyn0=pn.getChild("body");
- ParseNode bodyn=bodyn0.getChild("constructor_body");
- cn.addMethod(md);
- BlockNode bn=null;
- if (bodyn!=null&&bodyn.getChild("block_statement_list")!=null)
- bn=parseBlock(bodyn);
- else
- bn=new BlockNode();
- if (bodyn!=null&&bodyn.getChild("superinvoke")!=null) {
- ParseNode sin=bodyn.getChild("superinvoke");
- NameDescriptor nd=new NameDescriptor("super");
- Vector args=parseArgumentList(sin);
- MethodInvokeNode min=new MethodInvokeNode(nd);
- for(int i=0;i<args.size();i++) {
- min.addArgument((ExpressionNode)args.get(i));
- }
- BlockExpressionNode ben=new BlockExpressionNode(min);
- bn.addFirstBlockStatement(ben);
- }
- state.addTreeCode(md,bn);
- }
-
- public BlockNode parseBlock(ParseNode pn) {
- if (pn==null||isEmpty(pn.getTerminal()))
- return new BlockNode();
- ParseNode bsn=pn.getChild("block_statement_list");
- return parseBlockHelper(bsn);
- }
-
- private BlockNode parseBlockHelper(ParseNode pn) {
- ParseNodeVector pnv=pn.getChildren();
- BlockNode bn=new BlockNode();
- for(int i=0;i<pnv.size();i++) {
- Vector bsv=parseBlockStatement(pnv.elementAt(i));
- for(int j=0;j<bsv.size();j++) {
- bn.addBlockStatement((BlockStatementNode)bsv.get(j));
- }
- }
- return bn;
- }
-
- public BlockNode parseSingleBlock(ParseNode pn) {
- BlockNode bn=new BlockNode();
- Vector bsv=parseBlockStatement(pn);
- for(int j=0;j<bsv.size();j++) {
- bn.addBlockStatement((BlockStatementNode)bsv.get(j));
- }
- bn.setStyle(BlockNode.NOBRACES);
- return bn;
- }
-
- public Vector parseBlockStatement(ParseNode pn) {
- Vector blockstatements=new Vector();
- if (isNode(pn,"tag_declaration")) {
- String name=pn.getChild("single").getTerminal();
- String type=pn.getChild("type").getTerminal();
-
- blockstatements.add(new TagDeclarationNode(name, type));
- } else if (isNode(pn,"local_variable_declaration")) {
- TypeDescriptor t=parseTypeDescriptor(pn);
- ParseNode vn=pn.getChild("variable_declarators_list");
- ParseNodeVector pnv=vn.getChildren();
- for(int i=0;i<pnv.size();i++) {
- ParseNode vardecl=pnv.elementAt(i);
-
-
- ParseNode tmp=vardecl;
- TypeDescriptor arrayt=t;
- while (tmp.getChild("single")==null) {
- arrayt=arrayt.makeArray(state);
- tmp=tmp.getChild("array");
- }
- String identifier=tmp.getChild("single").getTerminal();
-
- ParseNode epn=vardecl.getChild("initializer");
-
-
- ExpressionNode en=null;
- if (epn!=null)
- en=parseExpression(epn.getFirstChild());
-
- blockstatements.add(new DeclarationNode(new VarDescriptor(arrayt, identifier),en));
- }
- } else if (isNode(pn,"nop")) {
- /* Do Nothing */
- } else if (isNode(pn,"expression")) {
- blockstatements.add(new BlockExpressionNode(parseExpression(pn.getFirstChild())));
- } else if (isNode(pn,"ifstatement")) {
- blockstatements.add(new IfStatementNode(parseExpression(pn.getChild("condition").getFirstChild()),
- parseSingleBlock(pn.getChild("statement").getFirstChild()),
- pn.getChild("else_statement")!=null?parseSingleBlock(pn.getChild("else_statement").getFirstChild()):null));
- } else if (isNode(pn,"taskexit")) {
- Vector vfe=null;
- if (pn.getChild("flag_effects_list")!=null)
- vfe=parseFlags(pn.getChild("flag_effects_list"));
- Vector ccs=null;
- if (pn.getChild("cons_checks")!=null)
- ccs=parseChecks(pn.getChild("cons_checks"));
-
- blockstatements.add(new TaskExitNode(vfe, ccs));
- } else if (isNode(pn,"atomic")) {
- BlockNode bn=parseBlockHelper(pn);
- blockstatements.add(new AtomicNode(bn));
- } else if (isNode(pn,"return")) {
- if (isEmpty(pn.getTerminal()))
- blockstatements.add(new ReturnNode());
- else {
- ExpressionNode en=parseExpression(pn.getFirstChild());
- blockstatements.add(new ReturnNode(en));
- }
- } else if (isNode(pn,"block_statement_list")) {
- BlockNode bn=parseBlockHelper(pn);
- blockstatements.add(new SubBlockNode(bn));
- } else if (isNode(pn,"empty")) {
- /* nop */
- } else if (isNode(pn,"statement_expression_list")) {
- ParseNodeVector pnv=pn.getChildren();
- BlockNode bn=new BlockNode();
- for(int i=0;i<pnv.size();i++) {
- ExpressionNode en=parseExpression(pnv.elementAt(i));
- blockstatements.add(new BlockExpressionNode(en));
- }
- bn.setStyle(BlockNode.EXPRLIST);
- } else if (isNode(pn,"forstatement")) {
- BlockNode init=parseSingleBlock(pn.getChild("initializer").getFirstChild());
- BlockNode update=parseSingleBlock(pn.getChild("update").getFirstChild());
- ExpressionNode condition=parseExpression(pn.getChild("condition").getFirstChild());
- BlockNode body=parseSingleBlock(pn.getChild("statement").getFirstChild());
- blockstatements.add(new LoopNode(init,condition,update,body));
- } else if (isNode(pn,"whilestatement")) {
- ExpressionNode condition=parseExpression(pn.getChild("condition").getFirstChild());
- BlockNode body=parseSingleBlock(pn.getChild("statement").getFirstChild());
- blockstatements.add(new LoopNode(condition,body,LoopNode.WHILELOOP));
- } else if (isNode(pn,"dowhilestatement")) {
- ExpressionNode condition=parseExpression(pn.getChild("condition").getFirstChild());
- BlockNode body=parseSingleBlock(pn.getChild("statement").getFirstChild());
- blockstatements.add(new LoopNode(condition,body,LoopNode.DOWHILELOOP));
- } else {
- System.out.println("---------------");
- System.out.println(pn.PPrint(3,true));
- throw new Error();
- }
- return blockstatements;
- }
-
- public MethodDescriptor parseMethodHeader(ParseNode pn) {
- ParseNode mn=pn.getChild("modifiers");
- Modifiers m=parseModifiersList(mn);
-
- ParseNode tn=pn.getChild("returntype");
- TypeDescriptor returntype;
- if (tn!=null)
- returntype=parseTypeDescriptor(tn);
- else
- returntype=new TypeDescriptor(TypeDescriptor.VOID);
-
- ParseNode pmd=pn.getChild("method_declarator");
- String name=pmd.getChild("name").getTerminal();
- MethodDescriptor md=new MethodDescriptor(m, returntype, name);
-
- ParseNode paramnode=pmd.getChild("parameters");
- parseParameterList(md,paramnode);
- return md;
- }
-
- public void parseParameterList(MethodDescriptor md, ParseNode pn) {
- ParseNode paramlist=pn.getChild("formal_parameter_list");
- if (paramlist==null)
- return;
- ParseNodeVector pnv=paramlist.getChildren();
- for(int i=0;i<pnv.size();i++) {
- ParseNode paramn=pnv.elementAt(i);
-
- if (isNode(paramn, "tag_parameter")) {
- String paramname=paramn.getChild("single").getTerminal();
- TypeDescriptor type=new TypeDescriptor(TypeDescriptor.TAG);
- md.addTagParameter(type, paramname);
- } else {
- TypeDescriptor type=parseTypeDescriptor(paramn);
-
- ParseNode tmp=paramn;
- while (tmp.getChild("single")==null) {
- type=type.makeArray(state);
- tmp=tmp.getChild("array");
- }
- String paramname=tmp.getChild("single").getTerminal();
-
- md.addParameter(type, paramname);
- }
- }
- }
-
- public Modifiers parseModifiersList(ParseNode pn) {
- Modifiers m=new Modifiers();
- ParseNode modlist=pn.getChild("modifier_list");
- if (modlist!=null) {
- ParseNodeVector pnv=modlist.getChildren();
- for(int i=0;i<pnv.size();i++) {
- ParseNode modn=pnv.elementAt(i);
- if (isNode(modn,"public"))
- m.addModifier(Modifiers.PUBLIC);
- else if (isNode(modn,"protected"))
- m.addModifier(Modifiers.PROTECTED);
- else if (isNode(modn,"private"))
- m.addModifier(Modifiers.PRIVATE);
- else if (isNode(modn,"static"))
- m.addModifier(Modifiers.STATIC);
- else if (isNode(modn,"final"))
- m.addModifier(Modifiers.FINAL);
- else if (isNode(modn,"native"))
- m.addModifier(Modifiers.NATIVE);
- else if (isNode(modn,"synchronized"))
- m.addModifier(Modifiers.SYNCHRONIZED);
- else if (isNode(modn,"atomic"))
- m.addModifier(Modifiers.ATOMIC);
- else throw new Error("Unrecognized Modifier");
- }
- }
- return m;
- }
-
- private boolean isNode(ParseNode pn, String label) {
- if (pn.getLabel().equals(label))
- return true;
- else return false;
- }
-
- private static boolean isEmpty(ParseNode pn) {
- if (pn.getLabel().equals("empty"))
- return true;
- else
- return false;
- }
-
- private static boolean isEmpty(String s) {
- if (s.equals("empty"))
- return true;
- else
- return false;
- }
-
- /** Throw an exception if something is unexpected */
- private void check(ParseNode pn, String label) {
- if (pn == null) {
- throw new Error(pn+ "IE: Expected '" + label + "', got null");
- }
- if (! pn.getLabel().equals(label)) {
- throw new Error(pn+ "IE: Expected '" + label + "', got '"+pn.getLabel()+"'");
- }
- }
+ String paramname=tmp.getChild("single").getTerminal();
+
+ md.addParameter(type, paramname);
+ }
+ }
+ }
+
+ public Modifiers parseModifiersList(ParseNode pn) {
+ Modifiers m=new Modifiers();
+ ParseNode modlist=pn.getChild("modifier_list");
+ if (modlist!=null) {
+ ParseNodeVector pnv=modlist.getChildren();
+ for(int i=0; i<pnv.size(); i++) {
+ ParseNode modn=pnv.elementAt(i);
+ if (isNode(modn,"public"))
+ m.addModifier(Modifiers.PUBLIC);
+ else if (isNode(modn,"protected"))
+ m.addModifier(Modifiers.PROTECTED);
+ else if (isNode(modn,"private"))
+ m.addModifier(Modifiers.PRIVATE);
+ else if (isNode(modn,"static"))
+ m.addModifier(Modifiers.STATIC);
+ else if (isNode(modn,"final"))
+ m.addModifier(Modifiers.FINAL);
+ else if (isNode(modn,"native"))
+ m.addModifier(Modifiers.NATIVE);
+ else if (isNode(modn,"synchronized"))
+ m.addModifier(Modifiers.SYNCHRONIZED);
+ else if (isNode(modn,"atomic"))
+ m.addModifier(Modifiers.ATOMIC);
+ else throw new Error("Unrecognized Modifier");
+ }
+ }
+ return m;
+ }
+
+ private boolean isNode(ParseNode pn, String label) {
+ if (pn.getLabel().equals(label))
+ return true;
+ else return false;
+ }
+
+ private static boolean isEmpty(ParseNode pn) {
+ if (pn.getLabel().equals("empty"))
+ return true;
+ else
+ return false;
+ }
+
+ private static boolean isEmpty(String s) {
+ if (s.equals("empty"))
+ return true;
+ else
+ return false;
+ }
+
+ /** Throw an exception if something is unexpected */
+ private void check(ParseNode pn, String label) {
+ if (pn == null) {
+ throw new Error(pn+ "IE: Expected '" + label + "', got null");
+ }
+ if (!pn.getLabel().equals(label)) {
+ throw new Error(pn+ "IE: Expected '" + label + "', got '"+pn.getLabel()+"'");
+ }
+ }
}
import IR.TypeDescriptor;
public class CastNode extends ExpressionNode {
- TypeDescriptor td;
- ExpressionNode etd;
- ExpressionNode exp;
-
- public CastNode(TypeDescriptor type, ExpressionNode exp) {
- this.td=type;
- this.exp=exp;
- this.etd=null;
- }
-
- public CastNode(ExpressionNode type, ExpressionNode exp) {
- this.td=null;
- this.exp=exp;
- this.etd=type;
- }
-
- public TypeDescriptor getType() {
- return td;
- }
-
- public ExpressionNode getExpression() {
- return exp;
- }
-
- public void setType(TypeDescriptor td) {
- this.td=td;
- }
-
- public NameNode getTypeName() {
- return (NameNode) etd;
- }
-
- public String printNode(int indentlevel) {
- if (etd==null)
- return "("+td.toString()+")"+exp.printNode(indentlevel);
- else
- return "("+etd.printNode(indentlevel)+")"+exp.printNode(indentlevel);
- }
-
- public int kind() {
- return Kind.CastNode;
- }
+ TypeDescriptor td;
+ ExpressionNode etd;
+ ExpressionNode exp;
+
+ public CastNode(TypeDescriptor type, ExpressionNode exp) {
+ this.td=type;
+ this.exp=exp;
+ this.etd=null;
+ }
+
+ public CastNode(ExpressionNode type, ExpressionNode exp) {
+ this.td=null;
+ this.exp=exp;
+ this.etd=type;
+ }
+
+ public TypeDescriptor getType() {
+ return td;
+ }
+
+ public ExpressionNode getExpression() {
+ return exp;
+ }
+
+ public void setType(TypeDescriptor td) {
+ this.td=td;
+ }
+
+ public NameNode getTypeName() {
+ return (NameNode) etd;
+ }
+
+ public String printNode(int indentlevel) {
+ if (etd==null)
+ return "("+td.toString()+")"+exp.printNode(indentlevel);
+ else
+ return "("+etd.printNode(indentlevel)+")"+exp.printNode(indentlevel);
+ }
+
+ public int kind() {
+ return Kind.CastNode;
+ }
}
import java.util.Vector;
public class ConstraintCheck {
- 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;i<numArgs();i++) {
- if (i>0)
- 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; i<numArgs(); i++) {
+ if (i>0)
+ str+=",";
+ str+=getVar(i)+" : ";
+ str+=getArg(i).printNode(0);
+ }
+ return str+")";
+ }
}
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<argumentlist.size(); i++) {
+ ExpressionNode en=(ExpressionNode)argumentlist.get(i);
+ st+=en.printNode(indent);
+ if ((i+1)!=argumentlist.size()) {
if (isarray)
- st="new "+td.toString()+"[";
+ st+="][";
else
- st="new "+td.toString()+"(";
- for(int i=0;i<argumentlist.size();i++) {
- ExpressionNode en=(ExpressionNode)argumentlist.get(i);
- st+=en.printNode(indent);
- if ((i+1)!=argumentlist.size()) {
- if (isarray)
- st+="][";
- else
- st+=", ";
- }
- }
- if (isarray)
- return st+"]";
- else
- return st+")";
+ st+=", ";
+ }
}
+ if (isarray)
+ return st+"]";
+ else
+ return st+")";
+ }
- public int kind() {
- return Kind.CreateObjectNode;
- }
+ public int kind() {
+ return Kind.CreateObjectNode;
+ }
}
import IR.*;
public class DNFFlag {
- private Vector conjunctions;
- public DNFFlag(FlagNode flag) {
- DNFFlagAtom dfa=new DNFFlagAtom(flag, false);
- conjunctions=new Vector();
- Vector conjunct=new Vector();
- conjunct.add(dfa);
- conjunctions.add(conjunct);
- }
- private DNFFlag() {
- conjunctions=new Vector();
- }
+ private Vector conjunctions;
+ public DNFFlag(FlagNode flag) {
+ DNFFlagAtom dfa=new DNFFlagAtom(flag, false);
+ conjunctions=new Vector();
+ Vector conjunct=new Vector();
+ conjunct.add(dfa);
+ conjunctions.add(conjunct);
+ }
+ private DNFFlag() {
+ conjunctions=new Vector();
+ }
- /** Returns the number of conjunctions in the DNF form. */
+ /** Returns the number of conjunctions in the DNF form. */
- public int size() {
- return conjunctions.size();
- }
+ public int size() {
+ return conjunctions.size();
+ }
- /** Returns a Vector containing the terms in the n'th conjunction. */
+ /** Returns a Vector containing the terms in the n'th conjunction. */
- public Vector get(int n) {
- return (Vector) conjunctions.get(n);
- }
+ public Vector get(int n) {
+ return (Vector) conjunctions.get(n);
+ }
- /** This method negates a DNFFlag expression. */
+ /** This method negates a DNFFlag expression. */
- public DNFFlag not() {
- DNFFlag notflag=null;
- for (int i=0;i<conjunctions.size();i++) {
- Vector conj=(Vector)conjunctions.get(i);
- DNFFlag newflag=null;
- for (int j=0;j<conj.size();j++) {
- DNFFlagAtom dfa=(DNFFlagAtom) conj.get(j);
- DNFFlagAtom negdfa=new DNFFlagAtom(dfa.getFlagNode(),!dfa.getNegated());
- DNFFlag tmp=new DNFFlag();
- Vector v=new Vector();
- tmp.conjunctions.add(v);
- v.add(negdfa);
+ public DNFFlag not() {
+ DNFFlag notflag=null;
+ for (int i=0; i<conjunctions.size(); i++) {
+ Vector conj=(Vector)conjunctions.get(i);
+ DNFFlag newflag=null;
+ for (int j=0; j<conj.size(); j++) {
+ DNFFlagAtom dfa=(DNFFlagAtom) conj.get(j);
+ DNFFlagAtom negdfa=new DNFFlagAtom(dfa.getFlagNode(),!dfa.getNegated());
+ DNFFlag tmp=new DNFFlag();
+ Vector v=new Vector();
+ tmp.conjunctions.add(v);
+ v.add(negdfa);
- if (newflag==null)
- newflag=tmp;
- else
- newflag=newflag.or(tmp);
- }
- if (notflag==null)
- notflag=newflag;
- else
- notflag=notflag.and(newflag);
- }
- return notflag;
+ if (newflag==null)
+ newflag=tmp;
+ else
+ newflag=newflag.or(tmp);
+ }
+ if (notflag==null)
+ notflag=newflag;
+ else
+ notflag=notflag.and(newflag);
}
+ return notflag;
+ }
- /** This method or's two DNFFlag expressions together. */
- public DNFFlag or(DNFFlag dnf2) {
- DNFFlag result=new DNFFlag();
- for(int i=0;i<conjunctions.size();i++) {
- Vector conjunct=(Vector)conjunctions.get(i);
- Vector newvector=new Vector();
- result.conjunctions.add(newvector);
- for(int j=0;j<conjunct.size();j++) {
- newvector.add(conjunct.get(j));
- }
- }
+ /** This method or's two DNFFlag expressions together. */
+ public DNFFlag or(DNFFlag dnf2) {
+ DNFFlag result=new DNFFlag();
+ for(int i=0; i<conjunctions.size(); i++) {
+ Vector conjunct=(Vector)conjunctions.get(i);
+ Vector newvector=new Vector();
+ result.conjunctions.add(newvector);
+ for(int j=0; j<conjunct.size(); j++) {
+ newvector.add(conjunct.get(j));
+ }
+ }
- for(int i=0;i<dnf2.conjunctions.size();i++) {
- Vector conjunct=(Vector)dnf2.conjunctions.get(i);
- Vector newvector=new Vector();
- result.conjunctions.add(newvector);
- for(int j=0;j<conjunct.size();j++) {
- newvector.add(conjunct.get(j));
- }
- }
- return result;
+ for(int i=0; i<dnf2.conjunctions.size(); i++) {
+ Vector conjunct=(Vector)dnf2.conjunctions.get(i);
+ Vector newvector=new Vector();
+ result.conjunctions.add(newvector);
+ for(int j=0; j<conjunct.size(); j++) {
+ newvector.add(conjunct.get(j));
+ }
}
+ return result;
+ }
- /** This method and's two DNFFlag expressions together. */
- public DNFFlag and(DNFFlag dnf2) {
- DNFFlag result=new DNFFlag();
- for(int i=0;i<conjunctions.size();i++) {
- for(int i2=0;i2<dnf2.conjunctions.size();i2++) {
- Vector conjunct=(Vector)conjunctions.get(i);
- Vector conjunct2=(Vector)dnf2.conjunctions.get(i2);
- Vector newconjunct=new Vector();
- result.conjunctions.add(newconjunct);
- for(int j=0;j<conjunct.size();j++) {
- newconjunct.add(conjunct.get(j));
- }
- for(int j2=0;j2<conjunct2.size();j2++) {
- newconjunct.add(conjunct2.get(j2));
- }
- }
+ /** This method and's two DNFFlag expressions together. */
+ public DNFFlag and(DNFFlag dnf2) {
+ DNFFlag result=new DNFFlag();
+ for(int i=0; i<conjunctions.size(); i++) {
+ for(int i2=0; i2<dnf2.conjunctions.size(); i2++) {
+ Vector conjunct=(Vector)conjunctions.get(i);
+ Vector conjunct2=(Vector)dnf2.conjunctions.get(i2);
+ Vector newconjunct=new Vector();
+ result.conjunctions.add(newconjunct);
+ for(int j=0; j<conjunct.size(); j++) {
+ newconjunct.add(conjunct.get(j));
}
- return result;
+ for(int j2=0; j2<conjunct2.size(); j2++) {
+ newconjunct.add(conjunct2.get(j2));
+ }
+ }
}
+ return result;
+ }
- public String toString() {
- String value="";
- for(int i=0;i<conjunctions.size();i++) {
- if (i!=0)
- value+=" || ";
- Vector conjunct=(Vector)conjunctions.get(i);
- for(int j=0;j<conjunct.size();j++) {
- if (j!=0)
- value+="&&";
- value+=conjunct.get(j);
- }
- }
- return value;
+ public String toString() {
+ String value="";
+ for(int i=0; i<conjunctions.size(); i++) {
+ if (i!=0)
+ value+=" || ";
+ Vector conjunct=(Vector)conjunctions.get(i);
+ for(int j=0; j<conjunct.size(); j++) {
+ if (j!=0)
+ value+="&&";
+ value+=conjunct.get(j);
+ }
}
+ return value;
+ }
}
import IR.*;
public class DNFFlagAtom {
- private final FlagNode flag;
- private final boolean negated;
+ private final FlagNode flag;
+ private final boolean negated;
- public DNFFlagAtom(FlagNode flag, boolean negated) {
- this.flag=flag;
- this.negated=negated;
- }
+ public DNFFlagAtom(FlagNode flag, boolean negated) {
+ this.flag=flag;
+ this.negated=negated;
+ }
- public FlagNode getFlagNode() {
- return flag;
- }
+ public FlagNode getFlagNode() {
+ return flag;
+ }
- public FlagDescriptor getFlag() {
- return flag.getFlag();
- }
+ public FlagDescriptor getFlag() {
+ return flag.getFlag();
+ }
- public boolean getNegated() {
- return negated;
- }
+ public boolean getNegated() {
+ return negated;
+ }
- public String toString() {
- if (negated)
- return "!"+flag.toString();
- else
- return flag.toString();
- }
+ public String toString() {
+ if (negated)
+ return "!"+flag.toString();
+ else
+ return flag.toString();
+ }
}
import IR.VarDescriptor;
public class DeclarationNode extends BlockStatementNode {
- VarDescriptor vd;
- ExpressionNode init_en;
- public DeclarationNode(VarDescriptor var, ExpressionNode en) {
- vd=var;
- init_en=en;
- }
-
- public String printNode(int indent) {
- if (init_en==null)
- return vd.toString();
- else return vd.toString()+"="+init_en.printNode(0);
- }
+ VarDescriptor vd;
+ ExpressionNode init_en;
+ public DeclarationNode(VarDescriptor var, ExpressionNode en) {
+ vd=var;
+ init_en=en;
+ }
- public ExpressionNode getExpression() {
- return init_en;
- }
-
- public VarDescriptor getVarDescriptor() {
- return vd;
- }
+ public String printNode(int indent) {
+ if (init_en==null)
+ return vd.toString();
+ else return vd.toString()+"="+init_en.printNode(0);
+ }
- public int kind() {
- return Kind.DeclarationNode;
- }
+ public ExpressionNode getExpression() {
+ return init_en;
+ }
+
+ public VarDescriptor getVarDescriptor() {
+ return vd;
+ }
+
+ public int kind() {
+ return Kind.DeclarationNode;
+ }
}
import IR.TypeDescriptor;
public class ExpressionNode extends TreeNode {
- public TypeDescriptor getType() {
- throw new Error();
- }
+ public TypeDescriptor getType() {
+ throw new Error();
+ }
- public String printNode(int indentlevel) {
- return null;
- }
+ public String printNode(int indentlevel) {
+ return null;
+ }
}
import IR.TypeDescriptor;
public class FieldAccessNode extends ExpressionNode {
- ExpressionNode left;
- String fieldname;
- FieldDescriptor field;
-
- public FieldAccessNode(ExpressionNode l, String field) {
- fieldname=field;
- left=l;
- }
-
- public void setField(FieldDescriptor fd) {
- field=fd;
- }
-
- public String getFieldName() {
- return fieldname;
- }
-
- public FieldDescriptor getField() {
- return field;
- }
-
- public ExpressionNode getExpression() {
- return left;
- }
-
- public String printNode(int indent) {
- return left.printNode(indent)+"."+fieldname;
- }
- public int kind() {
- return Kind.FieldAccessNode;
- }
- public TypeDescriptor getType() {
- return getField().getType();
- }
+ ExpressionNode left;
+ String fieldname;
+ FieldDescriptor field;
+
+ public FieldAccessNode(ExpressionNode l, String field) {
+ fieldname=field;
+ left=l;
+ }
+
+ public void setField(FieldDescriptor fd) {
+ field=fd;
+ }
+
+ public String getFieldName() {
+ return fieldname;
+ }
+
+ public FieldDescriptor getField() {
+ return field;
+ }
+
+ public ExpressionNode getExpression() {
+ return left;
+ }
+
+ public String printNode(int indent) {
+ return left.printNode(indent)+"."+fieldname;
+ }
+ public int kind() {
+ return Kind.FieldAccessNode;
+ }
+ public TypeDescriptor getType() {
+ return getField().getType();
+ }
}
import IR.*;
public class FlagEffect {
- FlagDescriptor flag;
- boolean status;
- String name;
-
- public FlagEffect(String flag, boolean status) {
- this.name=flag;
- this.status=status;
- }
-
- public void setFlag(FlagDescriptor flag) {
- this.flag=flag;
- }
-
- public FlagDescriptor getFlag() {
- return flag;
- }
-
- public String getName() {
- return name;
- }
-
- public boolean getStatus() {
- return status;
- }
-
- public String printNode(int indent) {
- if (status)
- return name;
- else
- return "!"+name;
- }
+ FlagDescriptor flag;
+ boolean status;
+ String name;
+
+ public FlagEffect(String flag, boolean status) {
+ this.name=flag;
+ this.status=status;
+ }
+
+ public void setFlag(FlagDescriptor flag) {
+ this.flag=flag;
+ }
+
+ public FlagDescriptor getFlag() {
+ return flag;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public boolean getStatus() {
+ return status;
+ }
+
+ public String printNode(int indent) {
+ if (status)
+ return name;
+ else
+ return "!"+name;
+ }
}
import java.util.*;
public class FlagEffects {
- Vector effects;
- Vector tageffects;
- String name;
- VarDescriptor vd;
+ Vector effects;
+ Vector tageffects;
+ String name;
+ VarDescriptor vd;
- public FlagEffects(String name) {
- effects=new Vector();
- tageffects=new Vector();
- this.name=name;
- }
+ public FlagEffects(String name) {
+ effects=new Vector();
+ tageffects=new Vector();
+ this.name=name;
+ }
- public void setVar(VarDescriptor vd) {
- this.vd=vd;
- }
+ public void setVar(VarDescriptor vd) {
+ this.vd=vd;
+ }
- public VarDescriptor getVar() {
- return vd;
- }
+ public VarDescriptor getVar() {
+ return vd;
+ }
- public String getName() {
- return name;
- }
+ public String getName() {
+ return name;
+ }
- public void addEffect(FlagEffect fe) {
- effects.add(fe);
- }
+ public void addEffect(FlagEffect fe) {
+ effects.add(fe);
+ }
- public void addTagEffect(TagEffect te) {
- tageffects.add(te);
- }
+ public void addTagEffect(TagEffect te) {
+ tageffects.add(te);
+ }
- public int numTagEffects() {
- return tageffects.size();
- }
+ public int numTagEffects() {
+ return tageffects.size();
+ }
- public TagEffect getTagEffect(int i) {
- return (TagEffect) tageffects.get(i);
- }
+ public TagEffect getTagEffect(int i) {
+ return (TagEffect) tageffects.get(i);
+ }
- public int numEffects() {
- return effects.size();
- }
+ public int numEffects() {
+ return effects.size();
+ }
- public FlagEffect getEffect(int i) {
- return (FlagEffect) effects.get(i);
- }
+ public FlagEffect getEffect(int i) {
+ return (FlagEffect) effects.get(i);
+ }
- public String printNode(int indent) {
- String st=name+"(";
- for(int i=0;i<effects.size();i++) {
- FlagEffect fe=(FlagEffect)effects.get(i);
- st+=fe.printNode(0);
- if ((i+1)!=effects.size())
- st+=",";
- }
- return st+")";
+ public String printNode(int indent) {
+ String st=name+"(";
+ for(int i=0; i<effects.size(); i++) {
+ FlagEffect fe=(FlagEffect)effects.get(i);
+ st+=fe.printNode(0);
+ if ((i+1)!=effects.size())
+ st+=",";
}
+ return st+")";
+ }
}
import IR.TypeDescriptor;
public class FlagExpressionNode extends TreeNode {
- public String printNode(int indentlevel) {
- return null;
- }
+ public String printNode(int indentlevel) {
+ return null;
+ }
- public DNFFlag getDNF() {
- throw new Error();
- }
+ public DNFFlag getDNF() {
+ throw new Error();
+ }
}
import IR.*;
public class FlagNode extends FlagExpressionNode {
- FlagDescriptor flag;
- String name;
+ FlagDescriptor flag;
+ String name;
- public FlagNode(String flag) {
- this.name=flag;
- }
+ public FlagNode(String flag) {
+ this.name=flag;
+ }
- public void setFlag(FlagDescriptor flag) {
- this.flag=flag;
- }
+ public void setFlag(FlagDescriptor flag) {
+ this.flag=flag;
+ }
- public FlagDescriptor getFlag() {
- return flag;
- }
+ public FlagDescriptor getFlag() {
+ return flag;
+ }
- public String getFlagName() {
- return name;
- }
+ public String getFlagName() {
+ return name;
+ }
- public int kind() {
- return Kind.FlagNode;
- }
+ public int kind() {
+ return Kind.FlagNode;
+ }
- public String printNode(int indent) {
- return name;
- }
+ public String printNode(int indent) {
+ return name;
+ }
- public DNFFlag getDNF() {
- return new DNFFlag(this);
- }
+ public DNFFlag getDNF() {
+ return new DNFFlag(this);
+ }
- public String toString() {
- return name;
- }
+ public String toString() {
+ return name;
+ }
}
import IR.Operation;
public class FlagOpNode extends FlagExpressionNode {
- FlagExpressionNode left;
- FlagExpressionNode right;
- Operation op;
-
- public FlagOpNode(FlagExpressionNode l, FlagExpressionNode r, Operation o) {
- left=l;
- right=r;
- op=o;
- }
-
- public FlagOpNode(FlagExpressionNode l, Operation o) {
- left=l;
- right=null;
- op=o;
- }
-
- public FlagExpressionNode getLeft() {
- return left;
- }
-
- public FlagExpressionNode getRight() {
- return right;
- }
-
- public Operation getOp() {
- return op;
- }
-
- public String printNode(int indent) {
- if (right==null)
- return op.toString()+"("+left.printNode(indent)+")";
- else
- return left.printNode(indent)+" "+op.toString()+" "+right.printNode(indent);
- }
-
- public int kind() {
- return Kind.FlagOpNode;
- }
-
- public DNFFlag getDNF() {
- DNFFlag leftflag=left.getDNF();
- DNFFlag rightflag=right!=null?right.getDNF():null;
-
- if (op.getOp()==Operation.LOGIC_NOT) {
- return leftflag.not();
- } else if (op.getOp()==Operation.LOGIC_OR) {
- return leftflag.or(rightflag);
- } else if (op.getOp()==Operation.LOGIC_AND) {
- return leftflag.and(rightflag);
- } else throw new Error();
- }
+ FlagExpressionNode left;
+ FlagExpressionNode right;
+ Operation op;
+
+ public FlagOpNode(FlagExpressionNode l, FlagExpressionNode r, Operation o) {
+ left=l;
+ right=r;
+ op=o;
+ }
+
+ public FlagOpNode(FlagExpressionNode l, Operation o) {
+ left=l;
+ right=null;
+ op=o;
+ }
+
+ public FlagExpressionNode getLeft() {
+ return left;
+ }
+
+ public FlagExpressionNode getRight() {
+ return right;
+ }
+
+ public Operation getOp() {
+ return op;
+ }
+
+ public String printNode(int indent) {
+ if (right==null)
+ return op.toString()+"("+left.printNode(indent)+")";
+ else
+ return left.printNode(indent)+" "+op.toString()+" "+right.printNode(indent);
+ }
+
+ public int kind() {
+ return Kind.FlagOpNode;
+ }
+
+ public DNFFlag getDNF() {
+ DNFFlag leftflag=left.getDNF();
+ DNFFlag rightflag=right!=null ? right.getDNF() : null;
+
+ if (op.getOp()==Operation.LOGIC_NOT) {
+ return leftflag.not();
+ } else if (op.getOp()==Operation.LOGIC_OR) {
+ return leftflag.or(rightflag);
+ } else if (op.getOp()==Operation.LOGIC_AND) {
+ return leftflag.and(rightflag);
+ } else throw new Error();
+ }
}
package IR.Tree;
public class IfStatementNode extends BlockStatementNode {
- ExpressionNode cond;
- BlockNode true_st;
- BlockNode else_st;
-
- public IfStatementNode(ExpressionNode cond, BlockNode true_st, BlockNode else_st) {
- this.cond=cond;
- this.true_st=true_st;
- this.else_st=else_st;
- }
+ ExpressionNode cond;
+ BlockNode true_st;
+ BlockNode else_st;
- public ExpressionNode getCondition() {
- return cond;
- }
+ public IfStatementNode(ExpressionNode cond, BlockNode true_st, BlockNode else_st) {
+ this.cond=cond;
+ this.true_st=true_st;
+ this.else_st=else_st;
+ }
- public BlockNode getTrueBlock() {
- return true_st;
- }
+ public ExpressionNode getCondition() {
+ return cond;
+ }
- public BlockNode getFalseBlock() {
- return else_st;
- }
-
- public String printNode(int indent) {
- if (else_st==null)
- return "if("+cond.printNode(indent)+") "+true_st.printNode(indent);
- else
- return "if("+cond.printNode(indent)+") "+true_st.printNode(indent)+" else "+ else_st.printNode(indent);
- }
- public int kind() {
- return Kind.IfStatementNode;
- }
+ public BlockNode getTrueBlock() {
+ return true_st;
+ }
+
+ public BlockNode getFalseBlock() {
+ return else_st;
+ }
+
+ public String printNode(int indent) {
+ if (else_st==null)
+ return "if("+cond.printNode(indent)+") "+true_st.printNode(indent);
+ else
+ return "if("+cond.printNode(indent)+") "+true_st.printNode(indent)+" else "+ else_st.printNode(indent);
+ }
+ public int kind() {
+ return Kind.IfStatementNode;
+ }
}
package IR.Tree;
public class Kind {
- public final static int AssignmentNode=1;
- public final static int OpNode=2;
- public final static int BlockExpressionNode=3;
- public final static int FieldAccessNode=4;
- public final static int BlockNode=5;
- public final static int IfStatementNode=6;
- public final static int ReturnNode=7;
- public final static int LiteralNode=8;
- public final static int SubBlockNode=9;
- public final static int CastNode=10;
- public final static int LoopNode=11;
- public final static int CreateObjectNode=12;
- public final static int MethodInvokeNode=13;
- public final static int DeclarationNode=14;
- public final static int NameNode=15;
- public final static int ArrayAccessNode=16;
- public final static int FlagNode=17;
- public final static int FlagOpNode=18;
- public final static int TaskExitNode=19;
- public final static int TagDeclarationNode=20;
- public final static int AtomicNode=21;
+ public final static int AssignmentNode=1;
+ public final static int OpNode=2;
+ public final static int BlockExpressionNode=3;
+ public final static int FieldAccessNode=4;
+ public final static int BlockNode=5;
+ public final static int IfStatementNode=6;
+ public final static int ReturnNode=7;
+ public final static int LiteralNode=8;
+ public final static int SubBlockNode=9;
+ public final static int CastNode=10;
+ public final static int LoopNode=11;
+ public final static int CreateObjectNode=12;
+ public final static int MethodInvokeNode=13;
+ public final static int DeclarationNode=14;
+ public final static int NameNode=15;
+ public final static int ArrayAccessNode=16;
+ public final static int FlagNode=17;
+ public final static int FlagOpNode=18;
+ public final static int TaskExitNode=19;
+ public final static int TagDeclarationNode=20;
+ public final static int AtomicNode=21;
}
public class LiteralNode extends ExpressionNode {
- public final static int INTEGER=1;
- public final static int FLOAT=2;
- public final static int BOOLEAN=3;
- public final static int CHAR=4;
- public final static int STRING=5;
- public final static int NULL=6;
-
- Object value;
- TypeDescriptor type;
- String typestr;
-
- public LiteralNode(String type, Object o) {
- typestr=type;
- value=o;
- type=null;
- }
-
- public String getTypeString() {
- return typestr;
- }
-
- public TypeDescriptor getType() {
- return type;
- }
-
- public void setType(TypeDescriptor td) {
- type=td;
- }
-
- public Object getValue() {
- return value;
- }
-
- public String printNode(int indent) {
- if (typestr.equals("null"))
- return "null";
- if (typestr.equals("string")) {
- return '"'+escapeString(value.toString())+'"';
- }
- return "/*"+typestr+ "*/"+value.toString();
- }
- private static String escapeString(String st) {
- String new_st="";
- for(int i=0;i<st.length();i++) {
- char x=st.charAt(i);
- if (x=='\n')
- new_st+="\\n";
- else if (x=='"')
- new_st+="'"+'"'+"'";
- else new_st+=x;
- }
- return new_st;
- }
- public int kind() {
- return Kind.LiteralNode;
- }
+ public final static int INTEGER=1;
+ public final static int FLOAT=2;
+ public final static int BOOLEAN=3;
+ public final static int CHAR=4;
+ public final static int STRING=5;
+ public final static int NULL=6;
+
+ Object value;
+ TypeDescriptor type;
+ String typestr;
+
+ public LiteralNode(String type, Object o) {
+ typestr=type;
+ value=o;
+ type=null;
+ }
+
+ public String getTypeString() {
+ return typestr;
+ }
+
+ public TypeDescriptor getType() {
+ return type;
+ }
+
+ public void setType(TypeDescriptor td) {
+ type=td;
+ }
+
+ public Object getValue() {
+ return value;
+ }
+
+ public String printNode(int indent) {
+ if (typestr.equals("null"))
+ return "null";
+ if (typestr.equals("string")) {
+ return '"'+escapeString(value.toString())+'"';
+ }
+ return "/*"+typestr+ "*/"+value.toString();
+ }
+ private static String escapeString(String st) {
+ String new_st="";
+ for(int i=0; i<st.length(); i++) {
+ char x=st.charAt(i);
+ if (x=='\n')
+ new_st+="\\n";
+ else if (x=='"')
+ new_st+="'"+'"'+"'";
+ else new_st+=x;
+ }
+ return new_st;
+ }
+ public int kind() {
+ return Kind.LiteralNode;
+ }
}
package IR.Tree;
public class LoopNode extends BlockStatementNode {
- BlockNode initializer;
- ExpressionNode condition;
- BlockNode update;
- BlockNode body;
- int type=0;
- public static int FORLOOP=1;
- public static int WHILELOOP=2;
- public static int DOWHILELOOP=3;
+ BlockNode initializer;
+ ExpressionNode condition;
+ BlockNode update;
+ BlockNode body;
+ int type=0;
+ public static int FORLOOP=1;
+ public static int WHILELOOP=2;
+ public static int DOWHILELOOP=3;
- public LoopNode(BlockNode initializer,ExpressionNode condition, BlockNode update, BlockNode body) {
- this.initializer=initializer;
- this.condition=condition;
- this.update=update;
- this.body=body;
- initializer.setStyle(BlockNode.EXPRLIST);
- update.setStyle(BlockNode.EXPRLIST);
- type=FORLOOP;
- }
+ public LoopNode(BlockNode initializer,ExpressionNode condition, BlockNode update, BlockNode body) {
+ this.initializer=initializer;
+ this.condition=condition;
+ this.update=update;
+ this.body=body;
+ initializer.setStyle(BlockNode.EXPRLIST);
+ update.setStyle(BlockNode.EXPRLIST);
+ type=FORLOOP;
+ }
- public LoopNode(ExpressionNode condition, BlockNode body, int type) {
- this.condition=condition;
- this.body=body;
- this.type=type;
- }
-
- public BlockNode getInitializer() {
- return initializer;
- }
+ public LoopNode(ExpressionNode condition, BlockNode body, int type) {
+ this.condition=condition;
+ this.body=body;
+ this.type=type;
+ }
- public ExpressionNode getCondition() {
- return condition;
- }
+ public BlockNode getInitializer() {
+ return initializer;
+ }
- public BlockNode getUpdate() {
- return update;
- }
+ public ExpressionNode getCondition() {
+ return condition;
+ }
- public BlockNode getBody() {
- return body;
- }
+ public BlockNode getUpdate() {
+ return update;
+ }
- public String printNode(int indent) {
- if (type==FORLOOP) {
- return "for("+initializer.printNode(0)+";"+condition.printNode(0)+
- ";"+update.printNode(0)+") "+body.printNode(indent)+"\n";
- } else if (type==WHILELOOP) {
- return "while("+condition.printNode(0)+") "+body.printNode(indent+INDENT)+"\n";
- } else if (type==DOWHILELOOP) {
- return "do "+ body.printNode(indent+INDENT)+
- "while("+condition.printNode(0)+")\n";
- } else throw new Error();
- }
+ public BlockNode getBody() {
+ return body;
+ }
- public int getType() {
- return type;
- }
+ public String printNode(int indent) {
+ if (type==FORLOOP) {
+ return "for("+initializer.printNode(0)+";"+condition.printNode(0)+
+ ";"+update.printNode(0)+") "+body.printNode(indent)+"\n";
+ } else if (type==WHILELOOP) {
+ return "while("+condition.printNode(0)+") "+body.printNode(indent+INDENT)+"\n";
+ } else if (type==DOWHILELOOP) {
+ return "do "+ body.printNode(indent+INDENT)+
+ "while("+condition.printNode(0)+")\n";
+ } else throw new Error();
+ }
- public int kind() {
- return Kind.LoopNode;
- }
+ public int getType() {
+ return type;
+ }
+
+ public int kind() {
+ return Kind.LoopNode;
+ }
}
import IR.TypeDescriptor;
public class MethodInvokeNode extends ExpressionNode {
- Vector argumentlist;
- String methodid;
- NameDescriptor basename;
- ExpressionNode en;
- MethodDescriptor md;
+ Vector argumentlist;
+ String methodid;
+ NameDescriptor basename;
+ ExpressionNode en;
+ MethodDescriptor md;
- public MethodInvokeNode(NameDescriptor name) {
- methodid=name.getIdentifier();
- if (name.getBase()!=null) {
- basename=name.getBase();
- }
- argumentlist=new Vector();
- en=null;
- md=null;
+ public MethodInvokeNode(NameDescriptor name) {
+ methodid=name.getIdentifier();
+ if (name.getBase()!=null) {
+ basename=name.getBase();
}
+ argumentlist=new Vector();
+ en=null;
+ md=null;
+ }
- public MethodInvokeNode(String methodid, ExpressionNode exp) {
- this.methodid=methodid;
- this.en=exp;
- argumentlist=new Vector();
- md=null;
- this.basename=null;
- }
+ public MethodInvokeNode(String methodid, ExpressionNode exp) {
+ this.methodid=methodid;
+ this.en=exp;
+ argumentlist=new Vector();
+ md=null;
+ this.basename=null;
+ }
- public NameDescriptor getBaseName() {
- return basename;
- }
+ public NameDescriptor getBaseName() {
+ return basename;
+ }
- public String getMethodName() {
- return methodid;
- }
+ public String getMethodName() {
+ return methodid;
+ }
- public ExpressionNode getExpression() {
- return en;
- }
+ public ExpressionNode getExpression() {
+ return en;
+ }
- public TypeDescriptor getType() {
- return md.getReturnType();
- }
+ public TypeDescriptor getType() {
+ return md.getReturnType();
+ }
- public void setExpression(ExpressionNode en) {
- this.en=en;
- }
+ public void setExpression(ExpressionNode en) {
+ this.en=en;
+ }
- public void setMethod(MethodDescriptor md) {
- this.md=md;
- }
+ public void setMethod(MethodDescriptor md) {
+ this.md=md;
+ }
- public MethodDescriptor getMethod() {
- return md;
- }
+ public MethodDescriptor getMethod() {
+ return md;
+ }
- public void addArgument(ExpressionNode en) {
- argumentlist.add(en);
- }
+ public void addArgument(ExpressionNode en) {
+ argumentlist.add(en);
+ }
- 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;
- if (en!=null)
- st=en.printNode(indent)+"."+methodid+"(";
- else
- st=methodid+"(";
+ public String printNode(int indent) {
+ String st;
+ if (en!=null)
+ st=en.printNode(indent)+"."+methodid+"(";
+ else
+ st=methodid+"(";
- for(int i=0;i<argumentlist.size();i++) {
- ExpressionNode en=(ExpressionNode)argumentlist.get(i);
- st+=en.printNode(indent);
- if ((i+1)!=argumentlist.size())
- st+=", ";
- }
- return st+")";
- }
- public int kind() {
- return Kind.MethodInvokeNode;
+ for(int i=0; i<argumentlist.size(); i++) {
+ ExpressionNode en=(ExpressionNode)argumentlist.get(i);
+ st+=en.printNode(indent);
+ if ((i+1)!=argumentlist.size())
+ st+=", ";
}
+ return st+")";
+ }
+ public int kind() {
+ return Kind.MethodInvokeNode;
+ }
}
package IR.Tree;
public class Modifiers {
- public static final int PUBLIC=1;
- public static final int PROTECTED=2;
- public static final int PRIVATE=4;
- public static final int STATIC=8;
+ public static final int PUBLIC=1;
+ public static final int PROTECTED=2;
+ public static final int PRIVATE=4;
+ public static final int STATIC=8;
// ABSTRACT=16
- public static final int FINAL=32;
- public static final int NATIVE=64;
- public static final int SYNCHRONIZED=128;
- public static final int ATOMIC=2048;
+ public static final int FINAL=32;
+ public static final int NATIVE=64;
+ public static final int SYNCHRONIZED=128;
+ public static final int ATOMIC=2048;
// TRANSIENT=256
// VOLATILE=512
// STRICTFP=1024
- private int value;
+ private int value;
- public Modifiers() {
- value=0;
- }
+ public Modifiers() {
+ value=0;
+ }
- public Modifiers(int v) {
- value=v;
- }
+ public Modifiers(int v) {
+ value=v;
+ }
- public void addModifier(int mod) {
- value|=mod;
- if (isSynchronized()&&isNative())
- throw new Error("Synchronized native methods are not supported");
- }
+ public void addModifier(int mod) {
+ value|=mod;
+ if (isSynchronized()&&isNative())
+ throw new Error("Synchronized native methods are not supported");
+ }
- public boolean isAtomic() {
- return ((value&ATOMIC)!=0);
- }
+ public boolean isAtomic() {
+ return ((value&ATOMIC)!=0);
+ }
- public boolean isSynchronized() {
- return ((value&SYNCHRONIZED)!=0);
- }
+ public boolean isSynchronized() {
+ return ((value&SYNCHRONIZED)!=0);
+ }
- public boolean isStatic() {
- return ((value&STATIC)!=0);
- }
+ public boolean isStatic() {
+ return ((value&STATIC)!=0);
+ }
- public boolean isNative() {
- return ((value&NATIVE)!=0);
- }
+ public boolean isNative() {
+ return ((value&NATIVE)!=0);
+ }
- public boolean isFinal() {
- return ((value&FINAL)!=0);
- }
+ public boolean isFinal() {
+ return ((value&FINAL)!=0);
+ }
- public String toString() {
- String st="";
- if ((value&PUBLIC)!=0)
- st+="public ";
- if ((value&PROTECTED)!=0)
- st+="protected ";
- if ((value&PRIVATE)!=0)
- st+="private ";
- if ((value&STATIC)!=0)
- st+="static ";
- if ((value&FINAL)!=0)
- st+="final ";
- if ((value&NATIVE)!=0)
- st+="native ";
- if ((value&SYNCHRONIZED)!=0)
- st+="synchronized ";
- if ((value&ATOMIC)!=0)
- st+="atomic ";
- return st;
- }
+ public String toString() {
+ String st="";
+ if ((value&PUBLIC)!=0)
+ st+="public ";
+ if ((value&PROTECTED)!=0)
+ st+="protected ";
+ if ((value&PRIVATE)!=0)
+ st+="private ";
+ if ((value&STATIC)!=0)
+ st+="static ";
+ if ((value&FINAL)!=0)
+ st+="final ";
+ if ((value&NATIVE)!=0)
+ st+="native ";
+ if ((value&SYNCHRONIZED)!=0)
+ st+="synchronized ";
+ if ((value&ATOMIC)!=0)
+ st+="atomic ";
+ return st;
+ }
}
import IR.FieldDescriptor;
public class NameNode extends ExpressionNode {
- NameDescriptor name;
- Descriptor vd;
- FieldDescriptor fd;
- ExpressionNode en;
+ NameDescriptor name;
+ Descriptor vd;
+ FieldDescriptor fd;
+ ExpressionNode en;
- public NameNode(NameDescriptor nd) {
- this.name=nd;
- this.vd=null;
- this.fd=null;
- }
+ public NameNode(NameDescriptor nd) {
+ this.name=nd;
+ this.vd=null;
+ this.fd=null;
+ }
- public ExpressionNode getExpression() {
- return en;
- }
+ public ExpressionNode getExpression() {
+ return en;
+ }
- /* Gross hack */
- public void setExpression(ExpressionNode en) {
- this.en=en;
- }
+ /* Gross hack */
+ public void setExpression(ExpressionNode en) {
+ this.en=en;
+ }
- public void setVar(Descriptor vd) {
- this.vd=vd;
- }
+ public void setVar(Descriptor vd) {
+ this.vd=vd;
+ }
- public void setField(FieldDescriptor fd) {
- this.fd=fd;
- }
+ public void setField(FieldDescriptor fd) {
+ this.fd=fd;
+ }
- public FieldDescriptor getField() {
- return fd;
- }
+ public FieldDescriptor getField() {
+ return fd;
+ }
- public boolean isTag() {
- return (vd instanceof TagVarDescriptor);
- }
+ public boolean isTag() {
+ return (vd instanceof TagVarDescriptor);
+ }
- public VarDescriptor getVar() {
- return (VarDescriptor) vd;
- }
+ public VarDescriptor getVar() {
+ return (VarDescriptor) vd;
+ }
- public TagVarDescriptor getTagVar() {
- return (TagVarDescriptor) vd;
- }
+ public TagVarDescriptor getTagVar() {
+ return (TagVarDescriptor) vd;
+ }
- public TypeDescriptor getType() {
- if (en!=null)
- return en.getType();
- else if (fd!=null)
- return fd.getType();
- else if (isTag())
- return new TypeDescriptor(TypeDescriptor.TAG);
- else
- return ((VarDescriptor)vd).getType();
- }
+ public TypeDescriptor getType() {
+ if (en!=null)
+ return en.getType();
+ else if (fd!=null)
+ return fd.getType();
+ else if (isTag())
+ return new TypeDescriptor(TypeDescriptor.TAG);
+ else
+ return ((VarDescriptor)vd).getType();
+ }
- NameDescriptor getName() {
- return name;
- }
+ NameDescriptor getName() {
+ return name;
+ }
- public String printNode(int indent) {
- return name.toString();
- }
+ public String printNode(int indent) {
+ return name.toString();
+ }
- public int kind() {
- return Kind.NameNode;
- }
+ public int kind() {
+ return Kind.NameNode;
+ }
}
import IR.TypeDescriptor;
public class OpNode extends ExpressionNode {
- ExpressionNode left;
- ExpressionNode right;
- Operation op;
- TypeDescriptor td;
- TypeDescriptor lefttype;
- TypeDescriptor righttype;
+ ExpressionNode left;
+ ExpressionNode right;
+ Operation op;
+ TypeDescriptor td;
+ TypeDescriptor lefttype;
+ TypeDescriptor righttype;
- public OpNode(ExpressionNode l, ExpressionNode r, Operation o) {
- left=l;
- right=r;
- op=o;
- }
+ public OpNode(ExpressionNode l, ExpressionNode r, Operation o) {
+ left=l;
+ right=r;
+ op=o;
+ }
- public OpNode(ExpressionNode l, Operation o) {
- left=l;
- right=null;
- op=o;
- }
+ public OpNode(ExpressionNode l, Operation o) {
+ left=l;
+ right=null;
+ op=o;
+ }
- public ExpressionNode getLeft() {
- return left;
- }
+ public ExpressionNode getLeft() {
+ return left;
+ }
- public ExpressionNode getRight() {
- return right;
- }
+ public ExpressionNode getRight() {
+ return right;
+ }
- public Operation getOp() {
- return op;
- }
+ public Operation getOp() {
+ return op;
+ }
- public String printNode(int indent) {
- if (right==null)
- return op.toString()+"("+left.printNode(indent)+")";
- else
- return left.printNode(indent)+" "+op.toString()+" "+right.printNode(indent);
- }
+ public String printNode(int indent) {
+ if (right==null)
+ return op.toString()+"("+left.printNode(indent)+")";
+ else
+ return left.printNode(indent)+" "+op.toString()+" "+right.printNode(indent);
+ }
- public void setLeftType(TypeDescriptor argtype) {
- this.lefttype=argtype;
- }
+ public void setLeftType(TypeDescriptor argtype) {
+ this.lefttype=argtype;
+ }
- public TypeDescriptor getLeftType() {
- return lefttype;
- }
+ public TypeDescriptor getLeftType() {
+ return lefttype;
+ }
- public void setRightType(TypeDescriptor argtype) {
- this.righttype=argtype;
- }
+ public void setRightType(TypeDescriptor argtype) {
+ this.righttype=argtype;
+ }
- public TypeDescriptor getRightType() {
- return righttype;
- }
+ public TypeDescriptor getRightType() {
+ return righttype;
+ }
- public TypeDescriptor getType() {
- return td;
- }
+ public TypeDescriptor getType() {
+ return td;
+ }
- public void setType(TypeDescriptor td) {
- this.td=td;
- }
+ public void setType(TypeDescriptor td) {
+ this.td=td;
+ }
- public int kind() {
- return Kind.OpNode;
- }
+ public int kind() {
+ return Kind.OpNode;
+ }
}
/*
-
- Class: ParseNode
- Author: Dan Roy
- Purpose: ParseNode is used to represent a parse production
-*/
+ Class: ParseNode
+ Author: Dan Roy
+ Purpose: ParseNode is used to represent a parse production
+
+ */
package IR.Tree;
public class ParseNode implements Walkable {
- private String label;
- private ParseNode parent;
- private ParseNodeVector children;
- private int line;
- private Object literal;
-
- //private SymbolTable st;
-
- public ParseNode(String label) {
- this.label = label;
- this.line = -1;
- this.parent = null;
- this.literal=null;
- children = new ParseNodeVector();
- }
-
- public ParseNode ( String label, int line ) {
- this.label = label;
- this.line = line;
- this.parent = null;
- this.literal=null;
- children = new ParseNodeVector();
- }
-
- public void setLabel( String label ) {
- this.label = label;
- }
-
- public String getLabel() {
- return label;
- }
-
- public void setLiteral(Object o) {
- literal=o;
- }
-
- public Object getLiteral() {
- return literal;
- }
+ private String label;
+ private ParseNode parent;
+ private ParseNodeVector children;
+ private int line;
+ private Object literal;
+
+ //private SymbolTable st;
+
+ public ParseNode(String label) {
+ this.label = label;
+ this.line = -1;
+ this.parent = null;
+ this.literal=null;
+ children = new ParseNodeVector();
+ }
+
+ public ParseNode (String label, int line) {
+ this.label = label;
+ this.line = line;
+ this.parent = null;
+ this.literal=null;
+ children = new ParseNodeVector();
+ }
+
+ public void setLabel(String label) {
+ this.label = label;
+ }
+
+ public String getLabel() {
+ return label;
+ }
+
+ public void setLiteral(Object o) {
+ literal=o;
+ }
+
+ public Object getLiteral() {
+ return literal;
+ }
+
+ /*
+ 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");
+ }
+
+ 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<indent; i++) output += " ";
+ return output;
+ }
- for (i = 0; i < children.size(); i++) {
- p = children.elementAt(i);
- if (p.getLabel().equals(label)) {
- return p;
- }
- }
+ public String PPrint(int indent, boolean recursive) {
- return null;
- }
+ String output = new String();
- public ParseNode getRoot() {
- return (parent == null) ? this : parent.getRoot();
- }
+ if (children.size()==0) {
+ output += doIndent(indent) + "<" + label + "/>\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) + "</" + label + ">\n";
}
- public String doIndent(int indent) {
-
- String output = new String();
- for(int i=0;i<indent;i++) output += " ";
- return output;
- }
-
- public String PPrint(int indent, boolean recursive) {
-
- String output = new String();
-
- if (children.size()==0) {
- output += doIndent(indent) + "<" + label + "/>\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) + "</" + label + ">\n";
- }
-
- return output;
- }
+ return output;
+ }
}
/*
-
- 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);
}
+ }
}
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();
+ }
}
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;
+ }
}
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<ccs.size(); i++) {
+ ConstraintCheck cc=(ConstraintCheck) ccs.get(i);
+
+ for(int j=0; j<cc.numArgs(); j++) {
+ ExpressionNode en=cc.getArg(j);
+ checkExpressionNode(td,nametable,en,null);
+ }
+ }
+ }
+
+ public void checkFlagEffects(TaskDescriptor td, Vector vfe, SymbolTable nametable) {
+ if (vfe==null)
+ return; /* No flag effects to check */
+ for(int i=0; i<vfe.size(); i++) {
+ FlagEffects fe=(FlagEffects) vfe.get(i);
+ String varname=fe.getName();
+ //Make sure the variable is declared as a parameter to the task
+ VarDescriptor vd=(VarDescriptor)td.getParameterTable().get(varname);
+ if (vd==null)
+ throw new Error("Parameter "+varname+" in Flag Effects not declared in "+td);
+ fe.setVar(vd);
+
+ //Make sure it correspods to a class
+ TypeDescriptor type_d=vd.getType();
+ if (!type_d.isClass())
+ throw new Error("Cannot have non-object argument for flag_effect");
+
+ ClassDescriptor cd=type_d.getClassDesc();
+ for(int j=0; j<fe.numEffects(); j++) {
+ FlagEffect flag=fe.getEffect(j);
+ String name=flag.getName();
+ FlagDescriptor flag_d=(FlagDescriptor)cd.getFlagTable().get(name);
+ //Make sure the flag is declared
+ if (flag_d==null)
+ throw new Error("Flag descriptor "+name+" undefined in class: "+cd.getSymbol());
+ if (flag_d.getExternal())
+ throw new Error("Attempting to modify external flag: "+name);
+ flag.setFlag(flag_d);
+ }
+ for(int j=0; j<fe.numTagEffects(); j++) {
+ TagEffect tag=fe.getTagEffect(j);
+ String name=tag.getName();
+
+ Descriptor d=(Descriptor)nametable.get(name);
+ if (d==null)
+ throw new Error("Tag descriptor "+name+" undeclared");
+ else if (!(d instanceof TagVarDescriptor))
+ throw new Error(name+" is not a tag descriptor");
+ tag.setTag((TagVarDescriptor)d);
+ }
+ }
+ }
+
+ public void checkTask(TaskDescriptor td) {
+ for(int i=0; i<td.numParameters(); i++) {
+ /* Check that parameter is well typed */
+ TypeDescriptor param_type=td.getParamType(i);
+ checkTypeDescriptor(param_type);
+
+ /* Check the parameter's flag expression is well formed */
+ FlagExpressionNode fen=td.getFlag(td.getParameter(i));
+ if (!param_type.isClass())
+ throw new Error("Cannot have non-object argument to a task");
+ ClassDescriptor cd=param_type.getClassDesc();
+ if (fen!=null)
+ checkFlagExpressionNode(cd, fen);
+ }
+
+ checkFlagEffects(td, td.getFlagEffects(),td.getParameterTable());
+ /* Check that the task code is valid */
+ BlockNode bn=state.getMethodBody(td);
+ checkBlockNode(td, td.getParameterTable(),bn);
+ }
+
+ public void checkFlagExpressionNode(ClassDescriptor cd, FlagExpressionNode fen) {
+ switch(fen.kind()) {
+ case Kind.FlagOpNode:
+ {
+ FlagOpNode fon=(FlagOpNode)fen;
+ checkFlagExpressionNode(cd, fon.getLeft());
+ if (fon.getRight()!=null)
+ checkFlagExpressionNode(cd, fon.getRight());
+ break;
+ }
+
+ case Kind.FlagNode:
+ {
+ FlagNode fn=(FlagNode)fen;
+ String name=fn.getFlagName();
+ FlagDescriptor fd=(FlagDescriptor)cd.getFlagTable().get(name);
+ if (fd==null)
+ throw new Error("Undeclared flag: "+name);
+ fn.setFlag(fd);
+ break;
+ }
+
+ default:
+ throw new Error("Unrecognized FlagExpressionNode");
+ }
+ }
+
+ public void checkMethod(ClassDescriptor cd, MethodDescriptor md) {
+ /* Check return type */
+ if (!md.isConstructor())
+ if (!md.getReturnType().isVoid())
+ checkTypeDescriptor(md.getReturnType());
+
+ for(int i=0; i<md.numParameters(); i++) {
+ TypeDescriptor param_type=md.getParamType(i);
+ checkTypeDescriptor(param_type);
+ }
+ /* Link the naming environments */
+ if (!md.isStatic()) /* Fields aren't accessible directly in a static method, so don't link in this table */
+ md.getParameterTable().setParent(cd.getFieldTable());
+ md.setClassDesc(cd);
+ if (!md.isStatic()) {
+ VarDescriptor thisvd=new VarDescriptor(new TypeDescriptor(cd),"this");
+ md.setThis(thisvd);
+ }
+ }
+
+ public void checkMethodBody(ClassDescriptor cd, MethodDescriptor md) {
+ ClassDescriptor superdesc=cd.getSuperDesc();
+ if (superdesc!=null) {
+ Set possiblematches=superdesc.getMethodTable().getSet(md.getSymbol());
+ for(Iterator methodit=possiblematches.iterator(); methodit.hasNext();) {
+ MethodDescriptor matchmd=(MethodDescriptor)methodit.next();
+ if (md.matches(matchmd)) {
+ if (matchmd.getModifiers().isFinal()) {
+ throw new Error("Try to override final method in method:"+md+" declared in "+cd);
+ }
}
-
- 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<ccs.size();i++) {
- ConstraintCheck cc=(ConstraintCheck) ccs.get(i);
-
- for(int j=0;j<cc.numArgs();j++) {
- ExpressionNode en=cc.getArg(j);
- checkExpressionNode(td,nametable,en,null);
- }
- }
- }
-
- public void checkFlagEffects(TaskDescriptor td, Vector vfe, SymbolTable nametable) {
- if (vfe==null)
- return; /* No flag effects to check */
- for(int i=0;i<vfe.size();i++) {
- FlagEffects fe=(FlagEffects) vfe.get(i);
- String varname=fe.getName();
- //Make sure the variable is declared as a parameter to the task
- VarDescriptor vd=(VarDescriptor)td.getParameterTable().get(varname);
- if (vd==null)
- throw new Error("Parameter "+varname+" in Flag Effects not declared in "+td);
- fe.setVar(vd);
-
- //Make sure it correspods to a class
- TypeDescriptor type_d=vd.getType();
- if (!type_d.isClass())
- throw new Error("Cannot have non-object argument for flag_effect");
-
- ClassDescriptor cd=type_d.getClassDesc();
- for(int j=0;j<fe.numEffects();j++) {
- FlagEffect flag=fe.getEffect(j);
- String name=flag.getName();
- FlagDescriptor flag_d=(FlagDescriptor)cd.getFlagTable().get(name);
- //Make sure the flag is declared
- if (flag_d==null)
- throw new Error("Flag descriptor "+name+" undefined in class: "+cd.getSymbol());
- if (flag_d.getExternal())
- throw new Error("Attempting to modify external flag: "+name);
- flag.setFlag(flag_d);
- }
- for(int j=0;j<fe.numTagEffects();j++) {
- TagEffect tag=fe.getTagEffect(j);
- String name=tag.getName();
-
- Descriptor d=(Descriptor)nametable.get(name);
- if (d==null)
- throw new Error("Tag descriptor "+name+" undeclared");
- else if (!(d instanceof TagVarDescriptor))
- throw new Error(name+" is not a tag descriptor");
- tag.setTag((TagVarDescriptor)d);
- }
- }
- }
-
- public void checkTask(TaskDescriptor td) {
- for(int i=0;i<td.numParameters();i++) {
- /* Check that parameter is well typed */
- TypeDescriptor param_type=td.getParamType(i);
- checkTypeDescriptor(param_type);
-
- /* Check the parameter's flag expression is well formed */
- FlagExpressionNode fen=td.getFlag(td.getParameter(i));
- if (!param_type.isClass())
- throw new Error("Cannot have non-object argument to a task");
- ClassDescriptor cd=param_type.getClassDesc();
- if (fen!=null)
- checkFlagExpressionNode(cd, fen);
- }
-
- checkFlagEffects(td, td.getFlagEffects(),td.getParameterTable());
- /* Check that the task code is valid */
- BlockNode bn=state.getMethodBody(td);
- checkBlockNode(td, td.getParameterTable(),bn);
- }
-
- public void checkFlagExpressionNode(ClassDescriptor cd, FlagExpressionNode fen) {
- switch(fen.kind()) {
- case Kind.FlagOpNode:
- {
- FlagOpNode fon=(FlagOpNode)fen;
- checkFlagExpressionNode(cd, fon.getLeft());
- if (fon.getRight()!=null)
- checkFlagExpressionNode(cd, fon.getRight());
- break;
- }
- case Kind.FlagNode:
- {
- FlagNode fn=(FlagNode)fen;
- String name=fn.getFlagName();
- FlagDescriptor fd=(FlagDescriptor)cd.getFlagTable().get(name);
- if (fd==null)
- throw new Error("Undeclared flag: "+name);
- fn.setFlag(fd);
- break;
- }
- default:
- throw new Error("Unrecognized FlagExpressionNode");
- }
- }
-
- public void checkMethod(ClassDescriptor cd, MethodDescriptor md) {
- /* Check return type */
- if (!md.isConstructor())
- if (!md.getReturnType().isVoid())
- checkTypeDescriptor(md.getReturnType());
-
- for(int i=0;i<md.numParameters();i++) {
- TypeDescriptor param_type=md.getParamType(i);
- checkTypeDescriptor(param_type);
+ }
+ }
+ BlockNode bn=state.getMethodBody(md);
+ checkBlockNode(md, md.getParameterTable(),bn);
+ }
+
+ public void checkBlockNode(Descriptor md, SymbolTable nametable, BlockNode bn) {
+ /* Link in the naming environment */
+ bn.getVarTable().setParent(nametable);
+ for(int i=0; i<bn.size(); i++) {
+ BlockStatementNode bsn=bn.get(i);
+ checkBlockStatementNode(md, bn.getVarTable(),bsn);
+ }
+ }
+
+ public void checkBlockStatementNode(Descriptor md, SymbolTable nametable, BlockStatementNode bsn) {
+ switch(bsn.kind()) {
+ case Kind.BlockExpressionNode:
+ checkBlockExpressionNode(md, nametable,(BlockExpressionNode)bsn);
+ return;
+
+ case Kind.DeclarationNode:
+ checkDeclarationNode(md, nametable, (DeclarationNode)bsn);
+ return;
+
+ case Kind.TagDeclarationNode:
+ checkTagDeclarationNode(md, nametable, (TagDeclarationNode)bsn);
+ return;
+
+ case Kind.IfStatementNode:
+ checkIfStatementNode(md, nametable, (IfStatementNode)bsn);
+ return;
+
+ case Kind.LoopNode:
+ checkLoopNode(md, nametable, (LoopNode)bsn);
+ return;
+
+ case Kind.ReturnNode:
+ checkReturnNode(md, nametable, (ReturnNode)bsn);
+ return;
+
+ case Kind.TaskExitNode:
+ checkTaskExitNode(md, nametable, (TaskExitNode)bsn);
+ return;
+
+ case Kind.SubBlockNode:
+ checkSubBlockNode(md, nametable, (SubBlockNode)bsn);
+ return;
+
+ case Kind.AtomicNode:
+ checkAtomicNode(md, nametable, (AtomicNode)bsn);
+ return;
+ }
+ throw new Error();
+ }
+
+ void checkBlockExpressionNode(Descriptor md, SymbolTable nametable, BlockExpressionNode ben) {
+ checkExpressionNode(md, nametable, ben.getExpression(), null);
+ }
+
+ void checkDeclarationNode(Descriptor md, SymbolTable nametable, DeclarationNode dn) {
+ VarDescriptor vd=dn.getVarDescriptor();
+ checkTypeDescriptor(vd.getType());
+ Descriptor d=nametable.get(vd.getSymbol());
+ if ((d==null)||
+ (d instanceof FieldDescriptor)) {
+ nametable.add(vd);
+ } else
+ throw new Error(vd.getSymbol()+" in "+md+" defined a second time");
+ if (dn.getExpression()!=null)
+ checkExpressionNode(md, nametable, dn.getExpression(), vd.getType());
+ }
+
+ void checkTagDeclarationNode(Descriptor md, SymbolTable nametable, TagDeclarationNode dn) {
+ TagVarDescriptor vd=dn.getTagVarDescriptor();
+ Descriptor d=nametable.get(vd.getSymbol());
+ if ((d==null)||
+ (d instanceof FieldDescriptor)) {
+ nametable.add(vd);
+ } else
+ throw new Error(vd.getSymbol()+" defined a second time");
+ }
+
+ void checkSubBlockNode(Descriptor md, SymbolTable nametable, SubBlockNode sbn) {
+ checkBlockNode(md, nametable, sbn.getBlockNode());
+ }
+
+ void checkAtomicNode(Descriptor md, SymbolTable nametable, AtomicNode sbn) {
+ checkBlockNode(md, nametable, sbn.getBlockNode());
+ }
+
+ void checkReturnNode(Descriptor d, SymbolTable nametable, ReturnNode rn) {
+ if (d instanceof TaskDescriptor)
+ throw new Error("Illegal return appears in Task: "+d.getSymbol());
+ MethodDescriptor md=(MethodDescriptor)d;
+ if (rn.getReturnExpression()!=null)
+ if (md.getReturnType()==null)
+ throw new Error("Constructor can't return something.");
+ else if (md.getReturnType().isVoid())
+ throw new Error(md+" is void");
+ else
+ checkExpressionNode(md, nametable, rn.getReturnExpression(), md.getReturnType());
+ else
+ if (md.getReturnType()!=null&&!md.getReturnType().isVoid())
+ throw new Error("Need to return something for "+md);
+ }
+
+ void checkTaskExitNode(Descriptor md, SymbolTable nametable, TaskExitNode ten) {
+ if (md instanceof MethodDescriptor)
+ throw new Error("Illegal taskexit appears in Method: "+md.getSymbol());
+ checkFlagEffects((TaskDescriptor)md, ten.getFlagEffects(),nametable);
+ checkConstraintCheck((TaskDescriptor) md, nametable, ten.getChecks());
+ }
+
+ void checkIfStatementNode(Descriptor md, SymbolTable nametable, IfStatementNode isn) {
+ checkExpressionNode(md, nametable, isn.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
+ checkBlockNode(md, nametable, isn.getTrueBlock());
+ if (isn.getFalseBlock()!=null)
+ checkBlockNode(md, nametable, isn.getFalseBlock());
+ }
+
+ void checkExpressionNode(Descriptor md, SymbolTable nametable, ExpressionNode en, TypeDescriptor td) {
+ switch(en.kind()) {
+ case Kind.AssignmentNode:
+ checkAssignmentNode(md,nametable,(AssignmentNode)en,td);
+ return;
+
+ case Kind.CastNode:
+ checkCastNode(md,nametable,(CastNode)en,td);
+ return;
+
+ case Kind.CreateObjectNode:
+ checkCreateObjectNode(md,nametable,(CreateObjectNode)en,td);
+ return;
+
+ case Kind.FieldAccessNode:
+ checkFieldAccessNode(md,nametable,(FieldAccessNode)en,td);
+ return;
+
+ case Kind.ArrayAccessNode:
+ checkArrayAccessNode(md,nametable,(ArrayAccessNode)en,td);
+ return;
+
+ case Kind.LiteralNode:
+ checkLiteralNode(md,nametable,(LiteralNode)en,td);
+ return;
+
+ case Kind.MethodInvokeNode:
+ checkMethodInvokeNode(md,nametable,(MethodInvokeNode)en,td);
+ return;
+
+ case Kind.NameNode:
+ checkNameNode(md,nametable,(NameNode)en,td);
+ return;
+
+ case Kind.OpNode:
+ checkOpNode(md,nametable,(OpNode)en,td);
+ return;
+ }
+ throw new Error();
+ }
+
+ void checkCastNode(Descriptor md, SymbolTable nametable, CastNode cn, TypeDescriptor td) {
+ /* Get type descriptor */
+ if (cn.getType()==null) {
+ NameDescriptor typenamed=cn.getTypeName().getName();
+ String typename=typenamed.toString();
+ TypeDescriptor ntd=new TypeDescriptor(typeutil.getClass(typename));
+ cn.setType(ntd);
+ }
+
+ /* Check the type descriptor */
+ TypeDescriptor cast_type=cn.getType();
+ checkTypeDescriptor(cast_type);
+
+ /* Type check */
+ if (td!=null) {
+ if (!typeutil.isSuperorType(td,cast_type))
+ throw new Error("Cast node returns "+cast_type+", but need "+td);
+ }
+
+ ExpressionNode en=cn.getExpression();
+ checkExpressionNode(md, nametable, en, null);
+ TypeDescriptor etd=en.getType();
+ if (typeutil.isSuperorType(cast_type,etd)) /* Cast trivially succeeds */
+ return;
+
+ if (typeutil.isSuperorType(etd,cast_type)) /* Cast may succeed */
+ return;
+ if (typeutil.isCastable(etd, cast_type))
+ return;
+
+ /* Different branches */
+ /* TODO: change if add interfaces */
+ throw new Error("Cast will always fail\n"+cn.printNode(0));
+ }
+
+ void checkFieldAccessNode(Descriptor md, SymbolTable nametable, FieldAccessNode fan, TypeDescriptor td) {
+ ExpressionNode left=fan.getExpression();
+ checkExpressionNode(md,nametable,left,null);
+ TypeDescriptor ltd=left.getType();
+ String fieldname=fan.getFieldName();
+
+ FieldDescriptor fd=null;
+ if (ltd.isArray()&&fieldname.equals("length"))
+ fd=FieldDescriptor.arrayLength;
+ else
+ fd=(FieldDescriptor) ltd.getClassDesc().getFieldTable().get(fieldname);
+ if (fd==null)
+ throw new Error("Unknown field "+fieldname + " in "+fan.printNode(0)+" in "+md);
+ fan.setField(fd);
+ if (td!=null)
+ if (!typeutil.isSuperorType(td,fan.getType()))
+ throw new Error("Field node returns "+fan.getType()+", but need "+td);
+ }
+
+ void checkArrayAccessNode(Descriptor md, SymbolTable nametable, ArrayAccessNode aan, TypeDescriptor td) {
+ ExpressionNode left=aan.getExpression();
+ checkExpressionNode(md,nametable,left,null);
+
+ checkExpressionNode(md,nametable,aan.getIndex(),new TypeDescriptor(TypeDescriptor.INT));
+ TypeDescriptor ltd=left.getType();
+
+ if (td!=null)
+ if (!typeutil.isSuperorType(td,aan.getType()))
+ throw new Error("Field node returns "+aan.getType()+", but need "+td);
+ }
+
+ void checkLiteralNode(Descriptor md, SymbolTable nametable, LiteralNode ln, TypeDescriptor td) {
+ /* Resolve the type */
+ Object o=ln.getValue();
+ if (ln.getTypeString().equals("null")) {
+ ln.setType(new TypeDescriptor(TypeDescriptor.NULL));
+ } else if (o instanceof Integer) {
+ ln.setType(new TypeDescriptor(TypeDescriptor.INT));
+ } else if (o instanceof Long) {
+ ln.setType(new TypeDescriptor(TypeDescriptor.LONG));
+ } else if (o instanceof Float) {
+ ln.setType(new TypeDescriptor(TypeDescriptor.FLOAT));
+ } else if (o instanceof Boolean) {
+ ln.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
+ } else if (o instanceof Double) {
+ ln.setType(new TypeDescriptor(TypeDescriptor.DOUBLE));
+ } else if (o instanceof Character) {
+ ln.setType(new TypeDescriptor(TypeDescriptor.CHAR));
+ } else if (o instanceof String) {
+ ln.setType(new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass)));
+ }
+
+ if (td!=null)
+ if (!typeutil.isSuperorType(td,ln.getType()))
+ throw new Error("Field node returns "+ln.getType()+", but need "+td);
+ }
+
+ void checkNameNode(Descriptor md, SymbolTable nametable, NameNode nn, TypeDescriptor td) {
+ NameDescriptor nd=nn.getName();
+ if (nd.getBase()!=null) {
+ /* Big hack */
+ /* Rewrite NameNode */
+ ExpressionNode en=translateNameDescriptorintoExpression(nd);
+ nn.setExpression(en);
+ checkExpressionNode(md,nametable,en,td);
+ } else {
+ String varname=nd.toString();
+ Descriptor d=(Descriptor)nametable.get(varname);
+ if (d==null) {
+ throw new Error("Name "+varname+" undefined in: "+md);
+ }
+ if (d instanceof VarDescriptor) {
+ nn.setVar(d);
+ } else if (d instanceof FieldDescriptor) {
+ nn.setField((FieldDescriptor)d);
+ nn.setVar((VarDescriptor)nametable.get("this")); /* Need a pointer to this */
+ } else if (d instanceof TagVarDescriptor) {
+ nn.setVar(d);
+ } else throw new Error("Wrong type of descriptor");
+ if (td!=null)
+ if (!typeutil.isSuperorType(td,nn.getType()))
+ throw new Error("Field node returns "+nn.getType()+", but need "+td);
+ }
+ }
+
+ void checkAssignmentNode(Descriptor md, SymbolTable nametable, AssignmentNode an, TypeDescriptor td) {
+ boolean postinc=true;
+ if (an.getOperation().getBaseOp()==null||
+ (an.getOperation().getBaseOp().getOp()!=Operation.POSTINC&&
+ an.getOperation().getBaseOp().getOp()!=Operation.POSTDEC))
+ postinc=false;
+
+ if (!postinc)
+ checkExpressionNode(md, nametable, an.getSrc(),td);
+ //TODO: Need check on validity of operation here
+ if (!((an.getDest() instanceof FieldAccessNode)||
+ (an.getDest() instanceof ArrayAccessNode)||
+ (an.getDest() instanceof NameNode)))
+ throw new Error("Bad lside in "+an.printNode(0));
+ checkExpressionNode(md, nametable, an.getDest(), null);
+
+
+ /* We want parameter variables to tasks to be immutable */
+ if (md instanceof TaskDescriptor) {
+ if (an.getDest() instanceof NameNode) {
+ NameNode nn=(NameNode)an.getDest();
+ if (nn.getVar()!=null) {
+ if (((TaskDescriptor)md).getParameterTable().contains(nn.getVar().getSymbol()))
+ throw new Error("Can't modify parameter "+nn.getVar()+ " to task "+td.getSymbol());
}
- /* Link the naming environments */
- if (!md.isStatic()) /* Fields aren't accessible directly in a static method, so don't link in this table */
- md.getParameterTable().setParent(cd.getFieldTable());
- md.setClassDesc(cd);
- if (!md.isStatic()) {
- VarDescriptor thisvd=new VarDescriptor(new TypeDescriptor(cd),"this");
- md.setThis(thisvd);
+ }
+ }
+
+ if (an.getDest().getType().isString()&&an.getOperation().getOp()==AssignOperation.PLUSEQ) {
+ //String add
+ ClassDescriptor stringcl=typeutil.getClass(TypeUtil.StringClass);
+ TypeDescriptor stringtd=new TypeDescriptor(stringcl);
+ NameDescriptor nd=new NameDescriptor("String");
+ NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
+
+ if (!(an.getSrc().getType().isString()&&(an.getSrc() instanceof OpNode))) {
+ MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
+ rightmin.addArgument(an.getSrc());
+ an.right=rightmin;
+ checkExpressionNode(md, nametable, an.getSrc(), null);
+ }
+ }
+
+
+ if (!postinc&&!typeutil.isSuperorType(an.getDest().getType(),an.getSrc().getType())) {
+ throw new Error("Type of rside ("+an.getSrc().getType()+") not compatible with type of lside ("+an.getDest().getType()+")"+an.printNode(0));
+ }
+ }
+
+ void checkLoopNode(Descriptor md, SymbolTable nametable, LoopNode ln) {
+ if (ln.getType()==LoopNode.WHILELOOP||ln.getType()==LoopNode.DOWHILELOOP) {
+ checkExpressionNode(md, nametable, ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
+ checkBlockNode(md, nametable, ln.getBody());
+ } else {
+ //For loop case
+ /* Link in the initializer naming environment */
+ BlockNode bn=ln.getInitializer();
+ bn.getVarTable().setParent(nametable);
+ for(int i=0; i<bn.size(); i++) {
+ BlockStatementNode bsn=bn.get(i);
+ checkBlockStatementNode(md, bn.getVarTable(),bsn);
+ }
+ //check the condition
+ checkExpressionNode(md, bn.getVarTable(), ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
+ checkBlockNode(md, bn.getVarTable(), ln.getBody());
+ checkBlockNode(md, bn.getVarTable(), ln.getUpdate());
+ }
+ }
+
+
+ void checkCreateObjectNode(Descriptor md, SymbolTable nametable, CreateObjectNode con, TypeDescriptor td) {
+ TypeDescriptor[] tdarray=new TypeDescriptor[con.numArgs()];
+ for(int i=0; i<con.numArgs(); i++) {
+ ExpressionNode en=con.getArg(i);
+ checkExpressionNode(md,nametable,en,null);
+ tdarray[i]=en.getType();
+ }
+
+ TypeDescriptor typetolookin=con.getType();
+ checkTypeDescriptor(typetolookin);
+
+ if (td!=null&&!typeutil.isSuperorType(td, typetolookin))
+ throw new Error(typetolookin + " isn't a "+td);
+
+ /* Check flag effects */
+ if (con.getFlagEffects()!=null) {
+ FlagEffects fe=con.getFlagEffects();
+ ClassDescriptor cd=typetolookin.getClassDesc();
+
+ for(int j=0; j<fe.numEffects(); j++) {
+ FlagEffect flag=fe.getEffect(j);
+ String name=flag.getName();
+ FlagDescriptor flag_d=(FlagDescriptor)cd.getFlagTable().get(name);
+ //Make sure the flag is declared
+ if (flag_d==null)
+ throw new Error("Flag descriptor "+name+" undefined in class: "+cd.getSymbol());
+ if (flag_d.getExternal())
+ throw new Error("Attempting to modify external flag: "+name);
+ flag.setFlag(flag_d);
+ }
+ for(int j=0; j<fe.numTagEffects(); j++) {
+ TagEffect tag=fe.getTagEffect(j);
+ String name=tag.getName();
+
+ Descriptor d=(Descriptor)nametable.get(name);
+ if (d==null)
+ throw new Error("Tag descriptor "+name+" undeclared");
+ else if (!(d instanceof TagVarDescriptor))
+ throw new Error(name+" is not a tag descriptor");
+ tag.setTag((TagVarDescriptor)d);
+ }
+ }
+
+ if ((!typetolookin.isClass())&&(!typetolookin.isArray()))
+ throw new Error("Can't allocate primitive type:"+con.printNode(0));
+
+ if (!typetolookin.isArray()) {
+ //Array's don't need constructor calls
+ ClassDescriptor classtolookin=typetolookin.getClassDesc();
+
+ Set methoddescriptorset=classtolookin.getMethodTable().getSet(typetolookin.getSymbol());
+ MethodDescriptor bestmd=null;
+NextMethod:
+ for(Iterator methodit=methoddescriptorset.iterator(); methodit.hasNext();) {
+ MethodDescriptor currmd=(MethodDescriptor)methodit.next();
+ /* Need correct number of parameters */
+ if (con.numArgs()!=currmd.numParameters())
+ continue;
+ for(int i=0; i<con.numArgs(); i++) {
+ if (!typeutil.isSuperorType(currmd.getParamType(i),tdarray[i]))
+ continue NextMethod;
}
- }
+ /* Local allocations can't call global allocator */
+ if (!con.isGlobal()&&currmd.isGlobal())
+ continue;
- public void checkMethodBody(ClassDescriptor cd, MethodDescriptor md) {
- ClassDescriptor superdesc=cd.getSuperDesc();
- if (superdesc!=null) {
- Set possiblematches=superdesc.getMethodTable().getSet(md.getSymbol());
- for(Iterator methodit=possiblematches.iterator();methodit.hasNext();) {
- MethodDescriptor matchmd=(MethodDescriptor)methodit.next();
- if (md.matches(matchmd)) {
- if (matchmd.getModifiers().isFinal()) {
- throw new Error("Try to override final method in method:"+md+" declared in "+cd);
- }
- }
- }
- }
- BlockNode bn=state.getMethodBody(md);
- checkBlockNode(md, md.getParameterTable(),bn);
- }
-
- public void checkBlockNode(Descriptor md, SymbolTable nametable, BlockNode bn) {
- /* Link in the naming environment */
- bn.getVarTable().setParent(nametable);
- for(int i=0;i<bn.size();i++) {
- BlockStatementNode bsn=bn.get(i);
- checkBlockStatementNode(md, bn.getVarTable(),bsn);
- }
- }
-
- public void checkBlockStatementNode(Descriptor md, SymbolTable nametable, BlockStatementNode bsn) {
- switch(bsn.kind()) {
- case Kind.BlockExpressionNode:
- checkBlockExpressionNode(md, nametable,(BlockExpressionNode)bsn);
- return;
-
- case Kind.DeclarationNode:
- checkDeclarationNode(md, nametable, (DeclarationNode)bsn);
- return;
-
- case Kind.TagDeclarationNode:
- checkTagDeclarationNode(md, nametable, (TagDeclarationNode)bsn);
- return;
-
- case Kind.IfStatementNode:
- checkIfStatementNode(md, nametable, (IfStatementNode)bsn);
- return;
-
- case Kind.LoopNode:
- checkLoopNode(md, nametable, (LoopNode)bsn);
- return;
-
- case Kind.ReturnNode:
- checkReturnNode(md, nametable, (ReturnNode)bsn);
- return;
-
- case Kind.TaskExitNode:
- checkTaskExitNode(md, nametable, (TaskExitNode)bsn);
- return;
-
- case Kind.SubBlockNode:
- checkSubBlockNode(md, nametable, (SubBlockNode)bsn);
- return;
-
- case Kind.AtomicNode:
- checkAtomicNode(md, nametable, (AtomicNode)bsn);
- return;
+ /* Method okay so far */
+ if (bestmd==null)
+ bestmd=currmd;
+ else {
+ if (typeutil.isMoreSpecific(currmd,bestmd)) {
+ bestmd=currmd;
+ } else if (con.isGlobal()&&match(currmd, bestmd)) {
+ if (currmd.isGlobal()&&!bestmd.isGlobal())
+ bestmd=currmd;
+ else if (currmd.isGlobal()&&bestmd.isGlobal())
+ throw new Error();
+ } else if (!typeutil.isMoreSpecific(bestmd, currmd)) {
+ throw new Error("No method is most specific");
+ }
+
+ /* Is this more specific than bestmd */
}
+ }
+ if (bestmd==null)
+ throw new Error("No method found for "+con.printNode(0)+" in "+md);
+ con.setConstructor(bestmd);
+ }
+ }
+
+
+ /** Check to see if md1 is the same specificity as md2.*/
+
+ boolean match(MethodDescriptor md1, MethodDescriptor md2) {
+ /* Checks if md1 is more specific than md2 */
+ if (md1.numParameters()!=md2.numParameters())
+ throw new Error();
+ for(int i=0; i<md1.numParameters(); i++) {
+ if (!md2.getParamType(i).equals(md1.getParamType(i)))
+ return false;
+ }
+ if (!md2.getReturnType().equals(md1.getReturnType()))
+ return false;
+
+ if (!md2.getClassDesc().equals(md1.getClassDesc()))
+ return false;
+
+ return true;
+ }
+
+
+
+ ExpressionNode translateNameDescriptorintoExpression(NameDescriptor nd) {
+ String id=nd.getIdentifier();
+ NameDescriptor base=nd.getBase();
+ if (base==null)
+ return new NameNode(nd);
+ else
+ return new FieldAccessNode(translateNameDescriptorintoExpression(base),id);
+ }
+
+
+ void checkMethodInvokeNode(Descriptor md, SymbolTable nametable, MethodInvokeNode min, TypeDescriptor td) {
+ /*Typecheck subexpressions
+ and get types for expressions*/
+
+ TypeDescriptor[] tdarray=new TypeDescriptor[min.numArgs()];
+ for(int i=0; i<min.numArgs(); i++) {
+ ExpressionNode en=min.getArg(i);
+ checkExpressionNode(md,nametable,en,null);
+ tdarray[i]=en.getType();
+ }
+ TypeDescriptor typetolookin=null;
+ if (min.getExpression()!=null) {
+ checkExpressionNode(md,nametable,min.getExpression(),null);
+ typetolookin=min.getExpression().getType();
+ } else if (min.getBaseName()!=null) {
+ String rootname=min.getBaseName().getRoot();
+ if (rootname.equals("super")) {
+ ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
+ typetolookin=new TypeDescriptor(supercd);
+ } else if (nametable.get(rootname)!=null) {
+ //we have an expression
+ min.setExpression(translateNameDescriptorintoExpression(min.getBaseName()));
+ checkExpressionNode(md, nametable, min.getExpression(), null);
+ typetolookin=min.getExpression().getType();
+ } else {
+ //we have a type
+ ClassDescriptor cd=typeutil.getClass(min.getBaseName().getSymbol());
+ if (cd==null)
+ throw new Error("md = "+ md.toString()+ " "+min.getBaseName()+" undefined");
+ typetolookin=new TypeDescriptor(cd);
+ }
+ } else if ((md instanceof MethodDescriptor)&&min.getMethodName().equals("super")) {
+ ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
+ min.methodid=supercd.getSymbol();
+ typetolookin=new TypeDescriptor(supercd);
+ } else if (md instanceof MethodDescriptor) {
+ typetolookin=new TypeDescriptor(((MethodDescriptor)md).getClassDesc());
+ } else {
+ /* If this a task descriptor we throw an error at this point */
+ throw new Error("Unknown method call to "+min.getMethodName()+"in task"+md.getSymbol());
+ }
+ if (!typetolookin.isClass())
+ throw new Error("Error with method call to "+min.getMethodName());
+ ClassDescriptor classtolookin=typetolookin.getClassDesc();
+ //System.out.println("Method name="+min.getMethodName());
+
+ Set methoddescriptorset=classtolookin.getMethodTable().getSet(min.getMethodName());
+ MethodDescriptor bestmd=null;
+NextMethod:
+ for(Iterator methodit=methoddescriptorset.iterator(); methodit.hasNext();) {
+ MethodDescriptor currmd=(MethodDescriptor)methodit.next();
+ /* Need correct number of parameters */
+ if (min.numArgs()!=currmd.numParameters())
+ continue;
+ for(int i=0; i<min.numArgs(); i++) {
+ if (!typeutil.isSuperorType(currmd.getParamType(i),tdarray[i]))
+ continue NextMethod;
+ }
+ /* Method okay so far */
+ if (bestmd==null)
+ bestmd=currmd;
+ else {
+ if (typeutil.isMoreSpecific(currmd,bestmd)) {
+ bestmd=currmd;
+ } else if (!typeutil.isMoreSpecific(bestmd, currmd))
+ throw new Error("No method is most specific");
+
+ /* Is this more specific than bestmd */
+ }
+ }
+ if (bestmd==null)
+ throw new Error("No method found for :"+min.printNode(0)+" in class: " + classtolookin+" in "+md);
+ min.setMethod(bestmd);
+
+ if ((td!=null)&&(min.getType()!=null)&&!typeutil.isSuperorType(td, min.getType()))
+ throw new Error(min.getType()+ " is not equal to or a subclass of "+td);
+ /* Check whether we need to set this parameter to implied this */
+ if (!bestmd.isStatic()) {
+ if (min.getExpression()==null) {
+ ExpressionNode en=new NameNode(new NameDescriptor("this"));
+ min.setExpression(en);
+ checkExpressionNode(md, nametable, min.getExpression(), null);
+ }
+ }
+ }
+
+
+ void checkOpNode(Descriptor md, SymbolTable nametable, OpNode on, TypeDescriptor td) {
+ checkExpressionNode(md, nametable, on.getLeft(), null);
+ if (on.getRight()!=null)
+ checkExpressionNode(md, nametable, on.getRight(), null);
+ TypeDescriptor ltd=on.getLeft().getType();
+ TypeDescriptor rtd=on.getRight()!=null ? on.getRight().getType() : null;
+ TypeDescriptor lefttype=null;
+ TypeDescriptor righttype=null;
+ Operation op=on.getOp();
+
+ switch(op.getOp()) {
+ case Operation.LOGIC_OR:
+ case Operation.LOGIC_AND:
+ if (!(rtd.isBoolean()))
throw new Error();
- }
+ on.setRightType(rtd);
- void checkBlockExpressionNode(Descriptor md, SymbolTable nametable, BlockExpressionNode ben) {
- checkExpressionNode(md, nametable, ben.getExpression(), null);
- }
-
- void checkDeclarationNode(Descriptor md, SymbolTable nametable, DeclarationNode dn) {
- VarDescriptor vd=dn.getVarDescriptor();
- checkTypeDescriptor(vd.getType());
- Descriptor d=nametable.get(vd.getSymbol());
- if ((d==null)||
- (d instanceof FieldDescriptor)) {
- nametable.add(vd);
- } else
- throw new Error(vd.getSymbol()+" in "+md+" defined a second time");
- if (dn.getExpression()!=null)
- checkExpressionNode(md, nametable, dn.getExpression(), vd.getType());
- }
-
- void checkTagDeclarationNode(Descriptor md, SymbolTable nametable, TagDeclarationNode dn) {
- TagVarDescriptor vd=dn.getTagVarDescriptor();
- Descriptor d=nametable.get(vd.getSymbol());
- if ((d==null)||
- (d instanceof FieldDescriptor)) {
- nametable.add(vd);
- } else
- throw new Error(vd.getSymbol()+" defined a second time");
- }
-
- void checkSubBlockNode(Descriptor md, SymbolTable nametable, SubBlockNode sbn) {
- checkBlockNode(md, nametable, sbn.getBlockNode());
- }
-
- void checkAtomicNode(Descriptor md, SymbolTable nametable, AtomicNode sbn) {
- checkBlockNode(md, nametable, sbn.getBlockNode());
- }
-
- void checkReturnNode(Descriptor d, SymbolTable nametable, ReturnNode rn) {
- if (d instanceof TaskDescriptor)
- throw new Error("Illegal return appears in Task: "+d.getSymbol());
- MethodDescriptor md=(MethodDescriptor)d;
- if (rn.getReturnExpression()!=null)
- if (md.getReturnType()==null)
- throw new Error("Constructor can't return something.");
- else if (md.getReturnType().isVoid())
- throw new Error(md+" is void");
- else
- checkExpressionNode(md, nametable, rn.getReturnExpression(), md.getReturnType());
- else
- if (md.getReturnType()!=null&&!md.getReturnType().isVoid())
- throw new Error("Need to return something for "+md);
- }
-
- void checkTaskExitNode(Descriptor md, SymbolTable nametable, TaskExitNode ten) {
- if (md instanceof MethodDescriptor)
- throw new Error("Illegal taskexit appears in Method: "+md.getSymbol());
- checkFlagEffects((TaskDescriptor)md, ten.getFlagEffects(),nametable);
- checkConstraintCheck((TaskDescriptor) md, nametable, ten.getChecks());
- }
-
- void checkIfStatementNode(Descriptor md, SymbolTable nametable, IfStatementNode isn) {
- checkExpressionNode(md, nametable, isn.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
- checkBlockNode(md, nametable, isn.getTrueBlock());
- if (isn.getFalseBlock()!=null)
- checkBlockNode(md, nametable, isn.getFalseBlock());
- }
-
- void checkExpressionNode(Descriptor md, SymbolTable nametable, ExpressionNode en, TypeDescriptor td) {
- switch(en.kind()) {
- case Kind.AssignmentNode:
- checkAssignmentNode(md,nametable,(AssignmentNode)en,td);
- return;
- case Kind.CastNode:
- checkCastNode(md,nametable,(CastNode)en,td);
- return;
- case Kind.CreateObjectNode:
- checkCreateObjectNode(md,nametable,(CreateObjectNode)en,td);
- return;
- case Kind.FieldAccessNode:
- checkFieldAccessNode(md,nametable,(FieldAccessNode)en,td);
- return;
- case Kind.ArrayAccessNode:
- checkArrayAccessNode(md,nametable,(ArrayAccessNode)en,td);
- return;
- case Kind.LiteralNode:
- checkLiteralNode(md,nametable,(LiteralNode)en,td);
- return;
- case Kind.MethodInvokeNode:
- checkMethodInvokeNode(md,nametable,(MethodInvokeNode)en,td);
- return;
- case Kind.NameNode:
- checkNameNode(md,nametable,(NameNode)en,td);
- return;
- case Kind.OpNode:
- checkOpNode(md,nametable,(OpNode)en,td);
- return;
- }
+ case Operation.LOGIC_NOT:
+ if (!(ltd.isBoolean()))
throw new Error();
- }
+ //no promotion
+ on.setLeftType(ltd);
- void checkCastNode(Descriptor md, SymbolTable nametable, CastNode cn, TypeDescriptor td) {
- /* Get type descriptor */
- if (cn.getType()==null) {
- NameDescriptor typenamed=cn.getTypeName().getName();
- String typename=typenamed.toString();
- TypeDescriptor ntd=new TypeDescriptor(typeutil.getClass(typename));
- cn.setType(ntd);
- }
+ on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
+ break;
- /* Check the type descriptor */
- TypeDescriptor cast_type=cn.getType();
- checkTypeDescriptor(cast_type);
-
- /* Type check */
- if (td!=null) {
- if (!typeutil.isSuperorType(td,cast_type))
- throw new Error("Cast node returns "+cast_type+", but need "+td);
- }
-
- ExpressionNode en=cn.getExpression();
- checkExpressionNode(md, nametable, en, null);
- TypeDescriptor etd=en.getType();
- if (typeutil.isSuperorType(cast_type,etd)) /* Cast trivially succeeds */
- return;
-
- if (typeutil.isSuperorType(etd,cast_type)) /* Cast may succeed */
- return;
- if (typeutil.isCastable(etd, cast_type))
- return;
-
- /* Different branches */
- /* TODO: change if add interfaces */
- throw new Error("Cast will always fail\n"+cn.printNode(0));
- }
-
- void checkFieldAccessNode(Descriptor md, SymbolTable nametable, FieldAccessNode fan, TypeDescriptor td) {
- ExpressionNode left=fan.getExpression();
- checkExpressionNode(md,nametable,left,null);
- TypeDescriptor ltd=left.getType();
- String fieldname=fan.getFieldName();
-
- FieldDescriptor fd=null;
- if (ltd.isArray()&&fieldname.equals("length"))
- fd=FieldDescriptor.arrayLength;
- else
- fd=(FieldDescriptor) ltd.getClassDesc().getFieldTable().get(fieldname);
- if (fd==null)
- throw new Error("Unknown field "+fieldname + " in "+fan.printNode(0)+" in "+md);
- fan.setField(fd);
- if (td!=null)
- if (!typeutil.isSuperorType(td,fan.getType()))
- throw new Error("Field node returns "+fan.getType()+", but need "+td);
- }
-
- void checkArrayAccessNode(Descriptor md, SymbolTable nametable, ArrayAccessNode aan, TypeDescriptor td) {
- ExpressionNode left=aan.getExpression();
- checkExpressionNode(md,nametable,left,null);
-
- checkExpressionNode(md,nametable,aan.getIndex(),new TypeDescriptor(TypeDescriptor.INT));
- TypeDescriptor ltd=left.getType();
-
- if (td!=null)
- if (!typeutil.isSuperorType(td,aan.getType()))
- throw new Error("Field node returns "+aan.getType()+", but need "+td);
- }
-
- void checkLiteralNode(Descriptor md, SymbolTable nametable, LiteralNode ln, TypeDescriptor td) {
- /* Resolve the type */
- Object o=ln.getValue();
- if (ln.getTypeString().equals("null")) {
- ln.setType(new TypeDescriptor(TypeDescriptor.NULL));
- } else if (o instanceof Integer) {
- ln.setType(new TypeDescriptor(TypeDescriptor.INT));
- } else if (o instanceof Long) {
- ln.setType(new TypeDescriptor(TypeDescriptor.LONG));
- } else if (o instanceof Float) {
- ln.setType(new TypeDescriptor(TypeDescriptor.FLOAT));
- } else if (o instanceof Boolean) {
- ln.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
- } else if (o instanceof Double) {
- ln.setType(new TypeDescriptor(TypeDescriptor.DOUBLE));
- } else if (o instanceof Character) {
- ln.setType(new TypeDescriptor(TypeDescriptor.CHAR));
- } else if (o instanceof String) {
- ln.setType(new TypeDescriptor(typeutil.getClass(TypeUtil.StringClass)));
- }
-
- if (td!=null)
- if (!typeutil.isSuperorType(td,ln.getType()))
- throw new Error("Field node returns "+ln.getType()+", but need "+td);
- }
-
- void checkNameNode(Descriptor md, SymbolTable nametable, NameNode nn, TypeDescriptor td) {
- NameDescriptor nd=nn.getName();
- if (nd.getBase()!=null) {
- /* Big hack */
- /* Rewrite NameNode */
- ExpressionNode en=translateNameDescriptorintoExpression(nd);
- nn.setExpression(en);
- checkExpressionNode(md,nametable,en,td);
- } else {
- String varname=nd.toString();
- Descriptor d=(Descriptor)nametable.get(varname);
- if (d==null) {
- throw new Error("Name "+varname+" undefined in: "+md);
- }
- if (d instanceof VarDescriptor) {
- nn.setVar(d);
- } else if (d instanceof FieldDescriptor) {
- nn.setField((FieldDescriptor)d);
- nn.setVar((VarDescriptor)nametable.get("this")); /* Need a pointer to this */
- } else if (d instanceof TagVarDescriptor) {
- nn.setVar(d);
- } else throw new Error("Wrong type of descriptor");
- if (td!=null)
- if (!typeutil.isSuperorType(td,nn.getType()))
- throw new Error("Field node returns "+nn.getType()+", but need "+td);
- }
- }
-
- void checkAssignmentNode(Descriptor md, SymbolTable nametable, AssignmentNode an, TypeDescriptor td) {
- boolean postinc=true;
- if (an.getOperation().getBaseOp()==null||
- (an.getOperation().getBaseOp().getOp()!=Operation.POSTINC&&
- an.getOperation().getBaseOp().getOp()!=Operation.POSTDEC))
- postinc=false;
-
- if (!postinc)
- checkExpressionNode(md, nametable, an.getSrc() ,td);
- //TODO: Need check on validity of operation here
- if (!((an.getDest() instanceof FieldAccessNode)||
- (an.getDest() instanceof ArrayAccessNode)||
- (an.getDest() instanceof NameNode)))
- throw new Error("Bad lside in "+an.printNode(0));
- checkExpressionNode(md, nametable, an.getDest(), null);
-
-
- /* We want parameter variables to tasks to be immutable */
- if (md instanceof TaskDescriptor) {
- if (an.getDest() instanceof NameNode) {
- NameNode nn=(NameNode)an.getDest();
- if (nn.getVar()!=null) {
- if (((TaskDescriptor)md).getParameterTable().contains(nn.getVar().getSymbol()))
- throw new Error("Can't modify parameter "+nn.getVar()+ " to task "+td.getSymbol());
- }
- }
- }
-
- if (an.getDest().getType().isString()&&an.getOperation().getOp()==AssignOperation.PLUSEQ) {
- //String add
- ClassDescriptor stringcl=typeutil.getClass(TypeUtil.StringClass);
- TypeDescriptor stringtd=new TypeDescriptor(stringcl);
- NameDescriptor nd=new NameDescriptor("String");
- NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
-
- if (!(an.getSrc().getType().isString()&&(an.getSrc() instanceof OpNode))) {
- MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
- rightmin.addArgument(an.getSrc());
- an.right=rightmin;
- checkExpressionNode(md, nametable, an.getSrc(), null);
- }
- }
-
-
- if (!postinc&&!typeutil.isSuperorType(an.getDest().getType(),an.getSrc().getType())) {
- throw new Error("Type of rside ("+an.getSrc().getType()+") not compatible with type of lside ("+an.getDest().getType()+")"+an.printNode(0));
- }
- }
-
- void checkLoopNode(Descriptor md, SymbolTable nametable, LoopNode ln) {
- if (ln.getType()==LoopNode.WHILELOOP||ln.getType()==LoopNode.DOWHILELOOP) {
- checkExpressionNode(md, nametable, ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
- checkBlockNode(md, nametable, ln.getBody());
- } else {
- //For loop case
- /* Link in the initializer naming environment */
- BlockNode bn=ln.getInitializer();
- bn.getVarTable().setParent(nametable);
- for(int i=0;i<bn.size();i++) {
- BlockStatementNode bsn=bn.get(i);
- checkBlockStatementNode(md, bn.getVarTable(),bsn);
- }
- //check the condition
- checkExpressionNode(md, bn.getVarTable(), ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
- checkBlockNode(md, bn.getVarTable(), ln.getBody());
- checkBlockNode(md, bn.getVarTable(), ln.getUpdate());
- }
- }
-
-
- void checkCreateObjectNode(Descriptor md, SymbolTable nametable, CreateObjectNode con, TypeDescriptor td) {
- TypeDescriptor[] tdarray=new TypeDescriptor[con.numArgs()];
- for(int i=0;i<con.numArgs();i++) {
- ExpressionNode en=con.getArg(i);
- checkExpressionNode(md,nametable,en,null);
- tdarray[i]=en.getType();
- }
-
- TypeDescriptor typetolookin=con.getType();
- checkTypeDescriptor(typetolookin);
-
- if (td!=null&&!typeutil.isSuperorType(td, typetolookin))
- throw new Error(typetolookin + " isn't a "+td);
-
- /* Check flag effects */
- if (con.getFlagEffects()!=null) {
- FlagEffects fe=con.getFlagEffects();
- ClassDescriptor cd=typetolookin.getClassDesc();
-
- for(int j=0;j<fe.numEffects();j++) {
- FlagEffect flag=fe.getEffect(j);
- String name=flag.getName();
- FlagDescriptor flag_d=(FlagDescriptor)cd.getFlagTable().get(name);
- //Make sure the flag is declared
- if (flag_d==null)
- throw new Error("Flag descriptor "+name+" undefined in class: "+cd.getSymbol());
- if (flag_d.getExternal())
- throw new Error("Attempting to modify external flag: "+name);
- flag.setFlag(flag_d);
- }
- for(int j=0;j<fe.numTagEffects();j++) {
- TagEffect tag=fe.getTagEffect(j);
- String name=tag.getName();
-
- Descriptor d=(Descriptor)nametable.get(name);
- if (d==null)
- throw new Error("Tag descriptor "+name+" undeclared");
- else if (!(d instanceof TagVarDescriptor))
- throw new Error(name+" is not a tag descriptor");
- tag.setTag((TagVarDescriptor)d);
- }
- }
+ case Operation.COMP:
+ // 5.6.2 Binary Numeric Promotion
+ //TODO unboxing of reference objects
+ if (ltd.isDouble())
+ throw new Error();
+ else if (ltd.isFloat())
+ throw new Error();
+ else if (ltd.isLong())
+ lefttype=new TypeDescriptor(TypeDescriptor.LONG);
+ else
+ lefttype=new TypeDescriptor(TypeDescriptor.INT);
+ on.setLeftType(lefttype);
+ on.setType(lefttype);
+ break;
+
+ case Operation.BIT_OR:
+ case Operation.BIT_XOR:
+ case Operation.BIT_AND:
+ // 5.6.2 Binary Numeric Promotion
+ //TODO unboxing of reference objects
+ if (ltd.isDouble()||rtd.isDouble())
+ throw new Error();
+ else if (ltd.isFloat()||rtd.isFloat())
+ throw new Error();
+ else if (ltd.isLong()||rtd.isLong())
+ lefttype=new TypeDescriptor(TypeDescriptor.LONG);
+ else
+ lefttype=new TypeDescriptor(TypeDescriptor.INT);
+ righttype=lefttype;
+
+ on.setLeftType(lefttype);
+ on.setRightType(righttype);
+ on.setType(lefttype);
+ break;
+
+ case Operation.ISAVAILABLE:
+ if (!(ltd.isPtr())) {
+ throw new Error("Can't use isavailable on non-pointers/non-parameters.");
+ }
+ lefttype=ltd;
+ on.setLeftType(lefttype);
+ on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
+ break;
+
+ case Operation.EQUAL:
+ case Operation.NOTEQUAL:
+ // 5.6.2 Binary Numeric Promotion
+ //TODO unboxing of reference objects
+ if (ltd.isBoolean()||rtd.isBoolean()) {
+ if (!(ltd.isBoolean()&&rtd.isBoolean()))
+ throw new Error();
+ righttype=lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
+ } else if (ltd.isPtr()||rtd.isPtr()) {
+ if (!(ltd.isPtr()&&rtd.isPtr()))
+ throw new Error();
+ righttype=rtd;
+ lefttype=ltd;
+ } else if (ltd.isDouble()||rtd.isDouble())
+ righttype=lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
+ else if (ltd.isFloat()||rtd.isFloat())
+ righttype=lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
+ else if (ltd.isLong()||rtd.isLong())
+ righttype=lefttype=new TypeDescriptor(TypeDescriptor.LONG);
+ else
+ righttype=lefttype=new TypeDescriptor(TypeDescriptor.INT);
+
+ on.setLeftType(lefttype);
+ on.setRightType(righttype);
+ on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
+ break;
+
+
+
+ case Operation.LT:
+ case Operation.GT:
+ case Operation.LTE:
+ case Operation.GTE:
+ // 5.6.2 Binary Numeric Promotion
+ //TODO unboxing of reference objects
+ if (!ltd.isNumber()||!rtd.isNumber())
+ throw new Error();
- if ((!typetolookin.isClass())&&(!typetolookin.isArray()))
- throw new Error("Can't allocate primitive type:"+con.printNode(0));
-
- if (!typetolookin.isArray()) {
- //Array's don't need constructor calls
- ClassDescriptor classtolookin=typetolookin.getClassDesc();
-
- Set methoddescriptorset=classtolookin.getMethodTable().getSet(typetolookin.getSymbol());
- MethodDescriptor bestmd=null;
- NextMethod:
- for(Iterator methodit=methoddescriptorset.iterator();methodit.hasNext();) {
- MethodDescriptor currmd=(MethodDescriptor)methodit.next();
- /* Need correct number of parameters */
- if (con.numArgs()!=currmd.numParameters())
- continue;
- for(int i=0;i<con.numArgs();i++) {
- if (!typeutil.isSuperorType(currmd.getParamType(i),tdarray[i]))
- continue NextMethod;
- }
- /* Local allocations can't call global allocator */
- if (!con.isGlobal()&&currmd.isGlobal())
- continue;
-
- /* Method okay so far */
- if (bestmd==null)
- bestmd=currmd;
- else {
- if (typeutil.isMoreSpecific(currmd,bestmd)) {
- bestmd=currmd;
- } else if (con.isGlobal()&&match(currmd, bestmd)) {
- if (currmd.isGlobal()&&!bestmd.isGlobal())
- bestmd=currmd;
- else if (currmd.isGlobal()&&bestmd.isGlobal())
- throw new Error();
- } else if (!typeutil.isMoreSpecific(bestmd, currmd)) {
- throw new Error("No method is most specific");
- }
-
- /* Is this more specific than bestmd */
- }
- }
- if (bestmd==null)
- throw new Error("No method found for "+con.printNode(0)+" in "+md);
- con.setConstructor(bestmd);
+ if (ltd.isDouble()||rtd.isDouble())
+ lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
+ else if (ltd.isFloat()||rtd.isFloat())
+ lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
+ else if (ltd.isLong()||rtd.isLong())
+ lefttype=new TypeDescriptor(TypeDescriptor.LONG);
+ else
+ lefttype=new TypeDescriptor(TypeDescriptor.INT);
+ righttype=lefttype;
+ on.setLeftType(lefttype);
+ on.setRightType(righttype);
+ on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
+ break;
+
+ case Operation.ADD:
+ if (ltd.isString()||rtd.isString()) {
+ ClassDescriptor stringcl=typeutil.getClass(TypeUtil.StringClass);
+ TypeDescriptor stringtd=new TypeDescriptor(stringcl);
+ NameDescriptor nd=new NameDescriptor("String");
+ NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
+ if (!(ltd.isString()&&(on.getLeft() instanceof OpNode))) {
+ MethodInvokeNode leftmin=new MethodInvokeNode(valuend);
+ leftmin.addArgument(on.getLeft());
+ on.left=leftmin;
+ checkExpressionNode(md, nametable, on.getLeft(), null);
}
- }
-
- /** Check to see if md1 is the same specificity as md2.*/
-
- boolean match(MethodDescriptor md1, MethodDescriptor md2) {
- /* Checks if md1 is more specific than md2 */
- if (md1.numParameters()!=md2.numParameters())
- throw new Error();
- for(int i=0;i<md1.numParameters();i++) {
- if (!md2.getParamType(i).equals(md1.getParamType(i)))
- return false;
+ if (!(rtd.isString()&&(on.getRight() instanceof OpNode))) {
+ MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
+ rightmin.addArgument(on.getRight());
+ on.right=rightmin;
+ checkExpressionNode(md, nametable, on.getRight(), null);
}
- if (!md2.getReturnType().equals(md1.getReturnType()))
- return false;
-
- if (!md2.getClassDesc().equals(md1.getClassDesc()))
- return false;
-
- return true;
- }
-
-
-
- ExpressionNode translateNameDescriptorintoExpression(NameDescriptor nd) {
- String id=nd.getIdentifier();
- NameDescriptor base=nd.getBase();
- if (base==null)
- return new NameNode(nd);
- else
- return new FieldAccessNode(translateNameDescriptorintoExpression(base),id);
- }
-
-
- void checkMethodInvokeNode(Descriptor md, SymbolTable nametable, MethodInvokeNode min, TypeDescriptor td) {
- /*Typecheck subexpressions
- and get types for expressions*/
-
- TypeDescriptor[] tdarray=new TypeDescriptor[min.numArgs()];
- for(int i=0;i<min.numArgs();i++) {
- ExpressionNode en=min.getArg(i);
- checkExpressionNode(md,nametable,en,null);
- tdarray[i]=en.getType();
- }
- TypeDescriptor typetolookin=null;
- if (min.getExpression()!=null) {
- checkExpressionNode(md,nametable,min.getExpression(),null);
- typetolookin=min.getExpression().getType();
- } else if (min.getBaseName()!=null) {
- String rootname=min.getBaseName().getRoot();
- if (rootname.equals("super")) {
- ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
- typetolookin=new TypeDescriptor(supercd);
- } else if (nametable.get(rootname)!=null) {
- //we have an expression
- min.setExpression(translateNameDescriptorintoExpression(min.getBaseName()));
- checkExpressionNode(md, nametable, min.getExpression(), null);
- typetolookin=min.getExpression().getType();
- } else {
- //we have a type
- ClassDescriptor cd=typeutil.getClass(min.getBaseName().getSymbol());
- if (cd==null)
- throw new Error("md = "+ md.toString()+ " "+min.getBaseName()+" undefined");
- typetolookin=new TypeDescriptor(cd);
- }
- } else if ((md instanceof MethodDescriptor)&&min.getMethodName().equals("super")) {
- ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
- min.methodid=supercd.getSymbol();
- typetolookin=new TypeDescriptor(supercd);
- } else if (md instanceof MethodDescriptor) {
- typetolookin=new TypeDescriptor(((MethodDescriptor)md).getClassDesc());
- } else {
- /* If this a task descriptor we throw an error at this point */
- throw new Error("Unknown method call to "+min.getMethodName()+"in task"+md.getSymbol());
- }
- if (!typetolookin.isClass())
- throw new Error("Error with method call to "+min.getMethodName());
- ClassDescriptor classtolookin=typetolookin.getClassDesc();
- //System.out.println("Method name="+min.getMethodName());
-
- Set methoddescriptorset=classtolookin.getMethodTable().getSet(min.getMethodName());
- MethodDescriptor bestmd=null;
- NextMethod:
- for(Iterator methodit=methoddescriptorset.iterator();methodit.hasNext();) {
- MethodDescriptor currmd=(MethodDescriptor)methodit.next();
- /* Need correct number of parameters */
- if (min.numArgs()!=currmd.numParameters())
- continue;
- for(int i=0;i<min.numArgs();i++) {
- if (!typeutil.isSuperorType(currmd.getParamType(i),tdarray[i]))
- continue NextMethod;
- }
- /* Method okay so far */
- if (bestmd==null)
- bestmd=currmd;
- else {
- if (typeutil.isMoreSpecific(currmd,bestmd)) {
- bestmd=currmd;
- } else if (!typeutil.isMoreSpecific(bestmd, currmd))
- throw new Error("No method is most specific");
-
- /* Is this more specific than bestmd */
- }
- }
- if (bestmd==null)
- throw new Error("No method found for :"+min.printNode(0)+" in class: " + classtolookin+" in "+md);
- min.setMethod(bestmd);
-
- if ((td!=null)&&(min.getType()!=null)&&!typeutil.isSuperorType(td, min.getType()))
- throw new Error(min.getType()+ " is not equal to or a subclass of "+td);
- /* Check whether we need to set this parameter to implied this */
- if (!bestmd.isStatic()) {
- if (min.getExpression()==null) {
- ExpressionNode en=new NameNode(new NameDescriptor("this"));
- min.setExpression(en);
- checkExpressionNode(md, nametable, min.getExpression(), null);
- }
- }
- }
+ on.setLeftType(stringtd);
+ on.setRightType(stringtd);
+ on.setType(stringtd);
+ break;
+ }
+
+ case Operation.SUB:
+ case Operation.MULT:
+ case Operation.DIV:
+ case Operation.MOD:
+ // 5.6.2 Binary Numeric Promotion
+ //TODO unboxing of reference objects
+ if (ltd.isArray()||rtd.isArray()||!ltd.isNumber()||!rtd.isNumber())
+ throw new Error("Error in "+on.printNode(0));
+
+ if (ltd.isDouble()||rtd.isDouble())
+ lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
+ else if (ltd.isFloat()||rtd.isFloat())
+ lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
+ else if (ltd.isLong()||rtd.isLong())
+ lefttype=new TypeDescriptor(TypeDescriptor.LONG);
+ else
+ lefttype=new TypeDescriptor(TypeDescriptor.INT);
+ righttype=lefttype;
+ on.setLeftType(lefttype);
+ on.setRightType(righttype);
+ on.setType(lefttype);
+ break;
+
+ case Operation.LEFTSHIFT:
+ case Operation.RIGHTSHIFT:
+ case Operation.URIGHTSHIFT:
+ if (!rtd.isIntegerType())
+ throw new Error();
+ //5.6.1 Unary Numeric Promotion
+ if (rtd.isByte()||rtd.isShort()||rtd.isInt())
+ righttype=new TypeDescriptor(TypeDescriptor.INT);
+ else
+ righttype=rtd;
+
+ on.setRightType(righttype);
+ if (!ltd.isIntegerType())
+ throw new Error();
- void checkOpNode(Descriptor md, SymbolTable nametable, OpNode on, TypeDescriptor td) {
- checkExpressionNode(md, nametable, on.getLeft(), null);
- if (on.getRight()!=null)
- checkExpressionNode(md, nametable, on.getRight(), null);
- TypeDescriptor ltd=on.getLeft().getType();
- TypeDescriptor rtd=on.getRight()!=null?on.getRight().getType():null;
- TypeDescriptor lefttype=null;
- TypeDescriptor righttype=null;
- Operation op=on.getOp();
-
- switch(op.getOp()) {
- case Operation.LOGIC_OR:
- case Operation.LOGIC_AND:
- if (!(rtd.isBoolean()))
- throw new Error();
- on.setRightType(rtd);
- case Operation.LOGIC_NOT:
- if (!(ltd.isBoolean()))
- throw new Error();
- //no promotion
- on.setLeftType(ltd);
-
- on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
- break;
-
- case Operation.COMP:
- // 5.6.2 Binary Numeric Promotion
- //TODO unboxing of reference objects
- if (ltd.isDouble())
- throw new Error();
- else if (ltd.isFloat())
- throw new Error();
- else if (ltd.isLong())
- lefttype=new TypeDescriptor(TypeDescriptor.LONG);
- else
- lefttype=new TypeDescriptor(TypeDescriptor.INT);
- on.setLeftType(lefttype);
- on.setType(lefttype);
- break;
-
- case Operation.BIT_OR:
- case Operation.BIT_XOR:
- case Operation.BIT_AND:
- // 5.6.2 Binary Numeric Promotion
- //TODO unboxing of reference objects
- if (ltd.isDouble()||rtd.isDouble())
- throw new Error();
- else if (ltd.isFloat()||rtd.isFloat())
- throw new Error();
- else if (ltd.isLong()||rtd.isLong())
- lefttype=new TypeDescriptor(TypeDescriptor.LONG);
- else
- lefttype=new TypeDescriptor(TypeDescriptor.INT);
- righttype=lefttype;
-
- on.setLeftType(lefttype);
- on.setRightType(righttype);
- on.setType(lefttype);
- break;
-
- case Operation.ISAVAILABLE:
- if (!(ltd.isPtr())) {
- throw new Error("Can't use isavailable on non-pointers/non-parameters.");
- }
- lefttype=ltd;
- on.setLeftType(lefttype);
- on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
- break;
- case Operation.EQUAL:
- case Operation.NOTEQUAL:
- // 5.6.2 Binary Numeric Promotion
- //TODO unboxing of reference objects
- if (ltd.isBoolean()||rtd.isBoolean()) {
- if (!(ltd.isBoolean()&&rtd.isBoolean()))
- throw new Error();
- righttype=lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
- } else if (ltd.isPtr()||rtd.isPtr()) {
- if (!(ltd.isPtr()&&rtd.isPtr()))
- throw new Error();
- righttype=rtd;
- lefttype=ltd;
- } else if (ltd.isDouble()||rtd.isDouble())
- righttype=lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
- else if (ltd.isFloat()||rtd.isFloat())
- righttype=lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
- else if (ltd.isLong()||rtd.isLong())
- righttype=lefttype=new TypeDescriptor(TypeDescriptor.LONG);
- else
- righttype=lefttype=new TypeDescriptor(TypeDescriptor.INT);
-
- on.setLeftType(lefttype);
- on.setRightType(righttype);
- on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
- break;
-
-
-
- case Operation.LT:
- case Operation.GT:
- case Operation.LTE:
- case Operation.GTE:
- // 5.6.2 Binary Numeric Promotion
- //TODO unboxing of reference objects
- if (!ltd.isNumber()||!rtd.isNumber())
- throw new Error();
-
- if (ltd.isDouble()||rtd.isDouble())
- lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
- else if (ltd.isFloat()||rtd.isFloat())
- lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
- else if (ltd.isLong()||rtd.isLong())
- lefttype=new TypeDescriptor(TypeDescriptor.LONG);
- else
- lefttype=new TypeDescriptor(TypeDescriptor.INT);
- righttype=lefttype;
- on.setLeftType(lefttype);
- on.setRightType(righttype);
- on.setType(new TypeDescriptor(TypeDescriptor.BOOLEAN));
- break;
-
- case Operation.ADD:
- if (ltd.isString()||rtd.isString()) {
- ClassDescriptor stringcl=typeutil.getClass(TypeUtil.StringClass);
- TypeDescriptor stringtd=new TypeDescriptor(stringcl);
- NameDescriptor nd=new NameDescriptor("String");
- NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
- if (!(ltd.isString()&&(on.getLeft() instanceof OpNode))) {
- MethodInvokeNode leftmin=new MethodInvokeNode(valuend);
- leftmin.addArgument(on.getLeft());
- on.left=leftmin;
- checkExpressionNode(md, nametable, on.getLeft(), null);
- }
-
- if (!(rtd.isString()&&(on.getRight() instanceof OpNode))) {
- MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
- rightmin.addArgument(on.getRight());
- on.right=rightmin;
- checkExpressionNode(md, nametable, on.getRight(), null);
- }
-
- on.setLeftType(stringtd);
- on.setRightType(stringtd);
- on.setType(stringtd);
- break;
- }
-
- case Operation.SUB:
- case Operation.MULT:
- case Operation.DIV:
- case Operation.MOD:
- // 5.6.2 Binary Numeric Promotion
- //TODO unboxing of reference objects
- if (ltd.isArray()||rtd.isArray()||!ltd.isNumber()||!rtd.isNumber())
- throw new Error("Error in "+on.printNode(0));
-
- if (ltd.isDouble()||rtd.isDouble())
- lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
- else if (ltd.isFloat()||rtd.isFloat())
- lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
- else if (ltd.isLong()||rtd.isLong())
- lefttype=new TypeDescriptor(TypeDescriptor.LONG);
- else
- lefttype=new TypeDescriptor(TypeDescriptor.INT);
- righttype=lefttype;
- on.setLeftType(lefttype);
- on.setRightType(righttype);
- on.setType(lefttype);
- break;
-
- case Operation.LEFTSHIFT:
- case Operation.RIGHTSHIFT:
- case Operation.URIGHTSHIFT:
- if (!rtd.isIntegerType())
- throw new Error();
- //5.6.1 Unary Numeric Promotion
- if (rtd.isByte()||rtd.isShort()||rtd.isInt())
- righttype=new TypeDescriptor(TypeDescriptor.INT);
- else
- righttype=rtd;
-
- on.setRightType(righttype);
- if (!ltd.isIntegerType())
- throw new Error();
- case Operation.UNARYPLUS:
- case Operation.UNARYMINUS:
- /* case Operation.POSTINC:
- case Operation.POSTDEC:
- case Operation.PREINC:
- case Operation.PREDEC:*/
- if (!ltd.isNumber())
- throw new Error();
- //5.6.1 Unary Numeric Promotion
- if (ltd.isByte()||ltd.isShort()||ltd.isInt())
- lefttype=new TypeDescriptor(TypeDescriptor.INT);
- else
- lefttype=ltd;
- on.setLeftType(lefttype);
- on.setType(lefttype);
- break;
- default:
- throw new Error(op.toString());
- }
-
- if (td!=null)
- if (!typeutil.isSuperorType(td, on.getType())) {
- System.out.println(td);
- System.out.println(on.getType());
- throw new Error("Type of rside not compatible with type of lside"+on.printNode(0));
- }
- }
+ case Operation.UNARYPLUS:
+ case Operation.UNARYMINUS:
+ /* case Operation.POSTINC:
+ case Operation.POSTDEC:
+ case Operation.PREINC:
+ case Operation.PREDEC:*/
+ if (!ltd.isNumber())
+ throw new Error();
+ //5.6.1 Unary Numeric Promotion
+ if (ltd.isByte()||ltd.isShort()||ltd.isInt())
+ lefttype=new TypeDescriptor(TypeDescriptor.INT);
+ else
+ lefttype=ltd;
+ on.setLeftType(lefttype);
+ on.setType(lefttype);
+ break;
+
+ default:
+ throw new Error(op.toString());
+ }
+
+ if (td!=null)
+ if (!typeutil.isSuperorType(td, on.getType())) {
+ System.out.println(td);
+ System.out.println(on.getType());
+ throw new Error("Type of rside not compatible with type of lside"+on.printNode(0));
+ }
+ }
}
package IR.Tree;
public class SubBlockNode extends BlockStatementNode {
- BlockNode bn;
- public SubBlockNode(BlockNode bn) {
- this.bn=bn;
- }
-
- public String printNode(int indent) {
- return bn.printNode(indent);
- }
+ BlockNode bn;
+ public SubBlockNode(BlockNode bn) {
+ this.bn=bn;
+ }
- public BlockNode getBlockNode() {
- return bn;
- }
+ public String printNode(int indent) {
+ return bn.printNode(indent);
+ }
- public int kind() {
- return Kind.SubBlockNode;
- }
+ public BlockNode getBlockNode() {
+ return bn;
+ }
+
+ public int kind() {
+ return Kind.SubBlockNode;
+ }
}
import IR.TagDescriptor;
public class TagDeclarationNode extends BlockStatementNode {
- String name;
- String tagtype;
- TagVarDescriptor tvd;
+ String name;
+ String tagtype;
+ TagVarDescriptor tvd;
- public TagDeclarationNode(String name, String tagtype) {
- this.name=name;
- this.tagtype=tagtype;
- tvd=new TagVarDescriptor(new TagDescriptor(tagtype), name);
- }
-
- public String printNode(int indent) {
- return "Tag "+name+"=new("+tagtype+")";
- }
-
- public TagVarDescriptor getTagVarDescriptor() {
- return tvd;
- }
+ public TagDeclarationNode(String name, String tagtype) {
+ this.name=name;
+ this.tagtype=tagtype;
+ tvd=new TagVarDescriptor(new TagDescriptor(tagtype), name);
+ }
- public String getName() {
- return name;
- }
+ public String printNode(int indent) {
+ return "Tag "+name+"=new("+tagtype+")";
+ }
- public String getTagType() {
- return tagtype;
- }
+ public TagVarDescriptor getTagVarDescriptor() {
+ return tvd;
+ }
- public int kind() {
- return Kind.TagDeclarationNode;
- }
+ public String getName() {
+ return name;
+ }
+
+ public String getTagType() {
+ return tagtype;
+ }
+
+ public int kind() {
+ return Kind.TagDeclarationNode;
+ }
}
import IR.*;
public class TagEffect {
- TagVarDescriptor tag;
- boolean status;
- String name;
-
- public TagEffect(String tag, boolean status) {
- this.name=tag;
- this.status=status;
- }
-
- public void setTag(TagVarDescriptor tag) {
- this.tag=tag;
- }
-
- public TagVarDescriptor getTag() {
- return tag;
- }
-
- public String getName() {
- return name;
- }
-
- public boolean getStatus() {
- return status;
- }
-
- public String printNode(int indent) {
- if (status)
- return name;
- else
- return "!"+name;
- }
+ TagVarDescriptor tag;
+ boolean status;
+ String name;
+
+ public TagEffect(String tag, boolean status) {
+ this.name=tag;
+ this.status=status;
+ }
+
+ public void setTag(TagVarDescriptor tag) {
+ this.tag=tag;
+ }
+
+ public TagVarDescriptor getTag() {
+ return tag;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public boolean getStatus() {
+ return status;
+ }
+
+ public String printNode(int indent) {
+ if (status)
+ return name;
+ else
+ return "!"+name;
+ }
}
import IR.Flat.TempDescriptor;
public class TagExpressionList {
- 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);
- }
+ 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);
+ }
}
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;
+ }
}
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;i<x;i++)
- sp+=" ";
- return sp;
- }
- public int kind() {
- throw new Error();
- }
+ public String printNode(int indent) {
+ return null;
+ }
+ public static String printSpace(int x) {
+ String sp="";
+ for(int i=0; i<x; i++)
+ sp+=" ";
+ return sp;
+ }
+ public int kind() {
+ throw new Error();
+ }
}
package IR.Tree;
/**
- * The Walkable interface specifies a set of methods that defines a web.
+ * The Walkable interface specifies a set of methods that defines a web.
*/
public interface Walkable {
- /**
- * Returns the name of the node
- */
- public String getNodeName();
+ /**
+ * Returns the name of the node
+ */
+ public String getNodeName();
- /**
- * Returns the number of neighbors from this node
- */
- public int getNeighborCount();
+ /**
+ * Returns the number of neighbors from this node
+ */
+ public int getNeighborCount();
- /**
- * Returns a specific neighbor
- */
- public Object getNeighbor(int index);
+ /**
+ * Returns a specific neighbor
+ */
+ public Object getNeighbor(int index);
- /**
- * Returns a pretty print of the representation of the node.
- *
- * @param indent number of blank spaces to skip for a new line
- * @param recursive if true, recursively print children
- */
- public String PPrint(int indent, boolean recursive);
+ /**
+ * Returns a pretty print of the representation of the node.
+ *
+ * @param indent number of blank spaces to skip for a new line
+ * @param recursive if true, recursively print children
+ */
+ public String PPrint(int indent, boolean recursive);
}
package IR;
/**
- * Descriptor
+ * Descriptor
*
* represents a symbol in the language (var name, function name, etc).
*/
public class TypeDescriptor extends Descriptor {
- public static final int BYTE=1;
- public static final int SHORT=2;
- public static final int INT=3;
- public static final int LONG=4;
- public static final int CHAR=5;
- public static final int BOOLEAN=6;
- public static final int FLOAT=7;
- public static final int DOUBLE=8;
- public static final int VOID=9;
- public static final int NULL=10;
- public static final int TAG=11;
- public static final int CLASS=12;
+ public static final int BYTE=1;
+ public static final int SHORT=2;
+ public static final int INT=3;
+ public static final int LONG=4;
+ public static final int CHAR=5;
+ public static final int BOOLEAN=6;
+ public static final int FLOAT=7;
+ public static final int DOUBLE=8;
+ public static final int VOID=9;
+ public static final int NULL=10;
+ public static final int TAG=11;
+ public static final int CLASS=12;
- int arraycount;
- int type;
- ClassDescriptor class_desc;
+ int arraycount;
+ int type;
+ ClassDescriptor class_desc;
- public boolean equals(Object o) {
- if (o instanceof TypeDescriptor) {
- TypeDescriptor t=(TypeDescriptor)o;
- if (t.type!=type)
- return false;
- if ((type==CLASS)&&(!t.getSymbol().equals(getSymbol())))
- return false;
- if (t.arraycount!=arraycount)
- return false;
- return true;
- }
+ public boolean equals(Object o) {
+ if (o instanceof TypeDescriptor) {
+ TypeDescriptor t=(TypeDescriptor)o;
+ if (t.type!=type)
return false;
+ if ((type==CLASS)&&(!t.getSymbol().equals(getSymbol())))
+ return false;
+ if (t.arraycount!=arraycount)
+ return false;
+ return true;
}
+ return false;
+ }
- public boolean isString() {
- if (type!=CLASS)
- return false;
- if (arraycount>0)
- 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<arraycount;i++)
- str+="[]";
- return str;
- } else
- return decodeInt(type);
- }
+ public TypeDescriptor(int t) {
+ super(decodeInt(t));
+ this.type=t;
+ this.arraycount=0;
+ }
- private static String decodeInt(int type) {
- if (type==BYTE)
- return "byte";
- else if (type==BOOLEAN)
- return "boolean";
- else if (type==SHORT)
- return "short";
- else if (type==INT)
- return "int";
- else if (type==LONG)
- return "long";
- else if (type==CHAR)
- return "char";
- else if (type==FLOAT)
- return "float";
- else if (type==DOUBLE)
- return "double";
- else if (type==VOID)
- return "void";
- else if (type==NULL)
- return "null";
- else if (type==TAG)
- return TypeUtil.TagClass;
- else throw new Error();
- }
+ public String toString() {
+ if (type==CLASS) {
+ return name;
+ } else
+ return decodeInt(type);
+ }
+
+ public String toPrettyString() {
+ if (type==CLASS) {
+ String str=name;
+ for(int i=0; i<arraycount; i++)
+ str+="[]";
+ return str;
+ } else
+ return decodeInt(type);
+ }
+
+ private static String decodeInt(int type) {
+ if (type==BYTE)
+ return "byte";
+ else if (type==BOOLEAN)
+ return "boolean";
+ else if (type==SHORT)
+ return "short";
+ else if (type==INT)
+ return "int";
+ else if (type==LONG)
+ return "long";
+ else if (type==CHAR)
+ return "char";
+ else if (type==FLOAT)
+ return "float";
+ else if (type==DOUBLE)
+ return "double";
+ else if (type==VOID)
+ return "void";
+ else if (type==NULL)
+ return "null";
+ else if (type==TAG)
+ return TypeUtil.TagClass;
+ else throw new Error();
+ }
}
import java.util.*;
public class TypeUtil {
- public static final String StringClass="String";
- public static final String ObjectClass="Object";
- public static final String StartupClass="StartupObject";
- public static final String TagClass="TagDescriptor";
- public static final String ThreadClass="Thread";
- State state;
- Hashtable supertable;
- Hashtable subclasstable;
-
- public TypeUtil(State state) {
- this.state=state;
- createTables();
- }
+ public static final String StringClass="String";
+ public static final String ObjectClass="Object";
+ public static final String StartupClass="StartupObject";
+ public static final String TagClass="TagDescriptor";
+ public static final String ThreadClass="Thread";
+ State state;
+ Hashtable supertable;
+ Hashtable subclasstable;
- public ClassDescriptor getClass(String classname) {
- ClassDescriptor cd=(ClassDescriptor)state.getClassSymbolTable().get(classname);
- return cd;
- }
+ public TypeUtil(State state) {
+ this.state=state;
+ createTables();
+ }
+
+ public ClassDescriptor getClass(String classname) {
+ ClassDescriptor cd=(ClassDescriptor)state.getClassSymbolTable().get(classname);
+ return cd;
+ }
- private void createTables() {
- supertable=new Hashtable();
-
- Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
- while(classit.hasNext()) {
- ClassDescriptor cd=(ClassDescriptor)classit.next();
- String superc=cd.getSuper();
- if (superc!=null) {
- ClassDescriptor cd_super=getClass(superc);
- if (cd_super==null) {
- throw new Error("Couldn't find class:"+superc);
- }
- supertable.put(cd,cd_super);
- }
+ private void createTables() {
+ supertable=new Hashtable();
+
+ Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
+ while(classit.hasNext()) {
+ ClassDescriptor cd=(ClassDescriptor)classit.next();
+ String superc=cd.getSuper();
+ if (superc!=null) {
+ ClassDescriptor cd_super=getClass(superc);
+ if (cd_super==null) {
+ throw new Error("Couldn't find class:"+superc);
}
+ supertable.put(cd,cd_super);
+ }
}
+ }
+
+ public ClassDescriptor getMainClass() {
+ return getClass(state.main);
+ }
- public ClassDescriptor getMainClass() {
- return getClass(state.main);
+ public MethodDescriptor getRun() {
+ ClassDescriptor cd=getClass(TypeUtil.ThreadClass);
+ for(Iterator methodit=cd.getMethodTable().getSet("run").iterator(); methodit.hasNext();) {
+ MethodDescriptor md=(MethodDescriptor) methodit.next();
+ if (md.numParameters()!=0||md.getModifiers().isStatic())
+ continue;
+ return md;
}
+ throw new Error("Can't find Thread.run");
+ }
- public MethodDescriptor getRun() {
- ClassDescriptor cd=getClass(TypeUtil.ThreadClass);
- for(Iterator methodit=cd.getMethodTable().getSet("run").iterator();methodit.hasNext();) {
- MethodDescriptor md=(MethodDescriptor) methodit.next();
- if (md.numParameters()!=0||md.getModifiers().isStatic())
- continue;
- return md;
- }
- throw new Error("Can't find Thread.run");
+ public MethodDescriptor getMain() {
+ ClassDescriptor cd=getMainClass();
+ Set mainset=cd.getMethodTable().getSet("main");
+ for(Iterator mainit=mainset.iterator(); mainit.hasNext();) {
+ MethodDescriptor md=(MethodDescriptor)mainit.next();
+ if (md.numParameters()!=1)
+ continue;
+ Descriptor pd=md.getParameter(0);
+ TypeDescriptor tpd=(pd instanceof TagVarDescriptor) ? ((TagVarDescriptor)pd).getType() : ((VarDescriptor)pd)
+ .getType();
+ if (tpd.getArrayCount()!=1)
+ continue;
+ if (!tpd.getSymbol().equals("String"))
+ continue;
+
+ if (!md.getModifiers().isStatic())
+ throw new Error("Error: Non static main");
+ return md;
}
+ throw new Error(cd+" has no main");
+ }
- public MethodDescriptor getMain() {
- ClassDescriptor cd=getMainClass();
- Set mainset=cd.getMethodTable().getSet("main");
- for(Iterator mainit=mainset.iterator();mainit.hasNext();) {
- MethodDescriptor md=(MethodDescriptor)mainit.next();
- if (md.numParameters()!=1)
- continue;
- Descriptor pd=md.getParameter(0);
- TypeDescriptor tpd=(pd instanceof TagVarDescriptor)?((TagVarDescriptor)pd).getType():((VarDescriptor)pd)
- .getType();
- if (tpd.getArrayCount()!=1)
- continue;
- if (!tpd.getSymbol().equals("String"))
- continue;
-
- if (!md.getModifiers().isStatic())
- throw new Error("Error: Non static main");
- return md;
- }
- throw new Error(cd+" has no main");
+ /** Check to see if md1 is more specific than md2... Informally
+ if md2 could always be called given the arguments passed into
+ md1 */
+
+ public boolean isMoreSpecific(MethodDescriptor md1, MethodDescriptor md2) {
+ /* Checks if md1 is more specific than md2 */
+ if (md1.numParameters()!=md2.numParameters())
+ throw new Error();
+ for(int i=0; i<md1.numParameters(); i++) {
+ if (!this.isSuperorType(md2.getParamType(i), md1.getParamType(i)))
+ return false;
}
+ if (!this.isSuperorType(md2.getReturnType(), md1.getReturnType()))
+ return false;
- /** Check to see if md1 is more specific than md2... Informally
- if md2 could always be called given the arguments passed into
- md1 */
-
- public boolean isMoreSpecific(MethodDescriptor md1, MethodDescriptor md2) {
- /* Checks if md1 is more specific than md2 */
- if (md1.numParameters()!=md2.numParameters())
- throw new Error();
- for(int i=0;i<md1.numParameters();i++) {
- if (!this.isSuperorType(md2.getParamType(i), md1.getParamType(i)))
- return false;
- }
- if (!this.isSuperorType(md2.getReturnType(), md1.getReturnType()))
- return false;
+ if (!this.isSuperorType(md2.getClassDesc(), md1.getClassDesc()))
+ return false;
- if (!this.isSuperorType(md2.getClassDesc(), md1.getClassDesc()))
- return false;
+ return true;
+ }
- return true;
- }
+ public MethodDescriptor getMethod(ClassDescriptor cd, String name, TypeDescriptor[] types) {
+ Set methoddescriptorset=cd.getMethodTable().getSet(name);
+ MethodDescriptor bestmd=null;
+NextMethod:
+ for(Iterator methodit=methoddescriptorset.iterator(); methodit.hasNext();) {
+ MethodDescriptor currmd=(MethodDescriptor)methodit.next();
+ /* Need correct number of parameters */
+ if (types.length!=currmd.numParameters())
+ continue;
+ for(int i=0; i<types.length; i++) {
+ if (!this.isSuperorType(currmd.getParamType(i),types[i]))
+ continue NextMethod;
+ }
+ /* Method okay so far */
+ if (bestmd==null)
+ bestmd=currmd;
+ else {
+ if (isMoreSpecific(currmd,bestmd)) {
+ bestmd=currmd;
+ } else if (!isMoreSpecific(bestmd, currmd))
+ throw new Error("No method is most specific");
- public MethodDescriptor getMethod(ClassDescriptor cd, String name, TypeDescriptor[] types) {
- Set methoddescriptorset=cd.getMethodTable().getSet(name);
- MethodDescriptor bestmd=null;
- NextMethod:
- for(Iterator methodit=methoddescriptorset.iterator();methodit.hasNext();) {
- MethodDescriptor currmd=(MethodDescriptor)methodit.next();
- /* Need correct number of parameters */
- if (types.length!=currmd.numParameters())
- continue;
- for(int i=0;i<types.length;i++) {
- if (!this.isSuperorType(currmd.getParamType(i),types[i]))
- continue NextMethod;
- }
- /* Method okay so far */
- if (bestmd==null)
- bestmd=currmd;
- else {
- if (isMoreSpecific(currmd,bestmd)) {
- bestmd=currmd;
- } else if (!isMoreSpecific(bestmd, currmd))
- throw new Error("No method is most specific");
-
- /* Is this more specific than bestmd */
- }
- }
- if (bestmd==null)
- throw new Error("Could find: "+name + " in "+cd);
-
- return bestmd;
+ /* Is this more specific than bestmd */
+ }
}
+ if (bestmd==null)
+ throw new Error("Could find: "+name + " in "+cd);
- public void createFullTable() {
- subclasstable=new Hashtable();
-
- Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
- while(classit.hasNext()) {
- ClassDescriptor cd=(ClassDescriptor)classit.next();
- ClassDescriptor tmp=cd.getSuperDesc();
-
- while(tmp!=null) {
- if (!subclasstable.containsKey(tmp))
- subclasstable.put(tmp,new HashSet());
- HashSet hs=(HashSet)subclasstable.get(tmp);
- hs.add(cd);
- tmp=tmp.getSuperDesc();
- }
- }
- }
+ return bestmd;
+ }
- public Set getSubClasses(ClassDescriptor cd) {
- return (Set)subclasstable.get(cd);
- }
+ public void createFullTable() {
+ subclasstable=new Hashtable();
- public ClassDescriptor getSuper(ClassDescriptor cd) {
- return (ClassDescriptor)supertable.get(cd);
- }
+ Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
+ while(classit.hasNext()) {
+ ClassDescriptor cd=(ClassDescriptor)classit.next();
+ ClassDescriptor tmp=cd.getSuperDesc();
- public boolean isCastable(TypeDescriptor original, TypeDescriptor casttype) {
- if (original.isChar()&&
- (casttype.isByte()||
- casttype.isShort()))
- return true;
-
- if (casttype.isChar()&&
- (original.isByte()||
- original.isShort()||
- original.isInt()||
- original.isLong()||
- original.isFloat()||
- original.isDouble()))
- return true;
-
- return false;
+ while(tmp!=null) {
+ if (!subclasstable.containsKey(tmp))
+ subclasstable.put(tmp,new HashSet());
+ HashSet hs=(HashSet)subclasstable.get(tmp);
+ hs.add(cd);
+ tmp=tmp.getSuperDesc();
+ }
}
+ }
- public boolean isSuperorType(TypeDescriptor possiblesuper, TypeDescriptor cd2) {
- //Matching type are always okay
- if (possiblesuper.equals(cd2))
- return true;
-
- if ((possiblesuper.isTag() && !cd2.isTag())||
- (!possiblesuper.isTag() && cd2.isTag()))
- return false;
-
- //Handle arrays
- if (cd2.isArray()||possiblesuper.isArray()) {
- // Object is super class of all arrays
- if (possiblesuper.getSymbol().equals(ObjectClass)&&!possiblesuper.isArray())
- return true;
-
- // If we have the same dimensionality of arrays & both are classes, we can default to the normal test
- if (cd2.isClass()&&possiblesuper.isClass()
- &&(possiblesuper.getArrayCount()==cd2.getArrayCount())&&
- isSuperorType(possiblesuper.getClassDesc(), cd2.getClassDesc()))
- return true;
-
- // Object is superclass of all array classes
- if (possiblesuper.getSymbol().equals(ObjectClass)&&cd2.isClass()
- &&(possiblesuper.getArrayCount()<cd2.getArrayCount()))
- return true;
-
- return false;
- }
+ public Set getSubClasses(ClassDescriptor cd) {
+ return (Set)subclasstable.get(cd);
+ }
- if (possiblesuper.isClass()&&
- cd2.isClass())
- return isSuperorType(possiblesuper.getClassDesc(), cd2.getClassDesc());
- else if (possiblesuper.isClass()&&
- cd2.isNull())
- return true;
- else if (possiblesuper.isNull())
- throw new Error(); //not sure when this case would occur
- else if (possiblesuper.isPrimitive()&&
- cd2.isPrimitive()) {
- ///Primitive widenings from 5.1.2
- if (cd2.isByte()&&(possiblesuper.isByte()||possiblesuper.isShort()||
- possiblesuper.isInt()||possiblesuper.isLong()||
- possiblesuper.isFloat()||possiblesuper.isDouble()))
- return true;
- if (cd2.isShort()&&(possiblesuper.isShort()||
- possiblesuper.isInt()||possiblesuper.isLong()||
- possiblesuper.isFloat()||possiblesuper.isDouble()))
- return true;
- if (cd2.isChar()&&(possiblesuper.isChar()||
- possiblesuper.isInt()||possiblesuper.isLong()||
- possiblesuper.isFloat()||possiblesuper.isDouble()))
- return true;
- if (cd2.isInt()&&(possiblesuper.isInt()||possiblesuper.isLong()||
- possiblesuper.isFloat()||possiblesuper.isDouble()))
- return true;
- if (cd2.isLong()&&(possiblesuper.isLong()||
- possiblesuper.isFloat()||possiblesuper.isDouble()))
- return true;
- if (cd2.isFloat()&&(possiblesuper.isFloat()||possiblesuper.isDouble()))
- return true;
- if (cd2.isDouble()&&possiblesuper.isDouble())
-
- return true;
- if (cd2.isBoolean()&&possiblesuper.isBoolean())
- return true;
-
- return false;
- } else if (possiblesuper.isPrimitive()&&(!possiblesuper.isArray())&&
- cd2.isPtr())
- return false;
- else if (cd2.isPrimitive()&&(!cd2.isArray())&&
- possiblesuper.isPtr())
- return false;
- else
- throw new Error("Case not handled:"+possiblesuper+" "+cd2);
- }
+ public ClassDescriptor getSuper(ClassDescriptor cd) {
+ return (ClassDescriptor)supertable.get(cd);
+ }
+
+ public boolean isCastable(TypeDescriptor original, TypeDescriptor casttype) {
+ if (original.isChar()&&
+ (casttype.isByte()||
+ casttype.isShort()))
+ return true;
+
+ if (casttype.isChar()&&
+ (original.isByte()||
+ original.isShort()||
+ original.isInt()||
+ original.isLong()||
+ original.isFloat()||
+ original.isDouble()))
+ return true;
+
+ return false;
+ }
+
+ public boolean isSuperorType(TypeDescriptor possiblesuper, TypeDescriptor cd2) {
+ //Matching type are always okay
+ if (possiblesuper.equals(cd2))
+ return true;
-
- public boolean isSuperorType(ClassDescriptor possiblesuper, ClassDescriptor cd2) {
- if (possiblesuper==cd2)
- return true;
- else
- return isSuper(possiblesuper, cd2);
+ if ((possiblesuper.isTag() && !cd2.isTag())||
+ (!possiblesuper.isTag() && cd2.isTag()))
+ return false;
+
+ //Handle arrays
+ if (cd2.isArray()||possiblesuper.isArray()) {
+ // Object is super class of all arrays
+ if (possiblesuper.getSymbol().equals(ObjectClass)&&!possiblesuper.isArray())
+ return true;
+
+ // If we have the same dimensionality of arrays & both are classes, we can default to the normal test
+ if (cd2.isClass()&&possiblesuper.isClass()
+ &&(possiblesuper.getArrayCount()==cd2.getArrayCount())&&
+ isSuperorType(possiblesuper.getClassDesc(), cd2.getClassDesc()))
+ return true;
+
+ // Object is superclass of all array classes
+ if (possiblesuper.getSymbol().equals(ObjectClass)&&cd2.isClass()
+ &&(possiblesuper.getArrayCount()<cd2.getArrayCount()))
+ return true;
+
+ return false;
}
- private boolean isSuper(ClassDescriptor possiblesuper, ClassDescriptor cd2) {
- while(cd2!=null) {
- cd2=getSuper(cd2);
- if (cd2==possiblesuper)
- return true;
- }
- return false;
+ if (possiblesuper.isClass()&&
+ cd2.isClass())
+ return isSuperorType(possiblesuper.getClassDesc(), cd2.getClassDesc());
+ else if (possiblesuper.isClass()&&
+ cd2.isNull())
+ return true;
+ else if (possiblesuper.isNull())
+ throw new Error(); //not sure when this case would occur
+ else if (possiblesuper.isPrimitive()&&
+ cd2.isPrimitive()) {
+ ///Primitive widenings from 5.1.2
+ if (cd2.isByte()&&(possiblesuper.isByte()||possiblesuper.isShort()||
+ possiblesuper.isInt()||possiblesuper.isLong()||
+ possiblesuper.isFloat()||possiblesuper.isDouble()))
+ return true;
+ if (cd2.isShort()&&(possiblesuper.isShort()||
+ possiblesuper.isInt()||possiblesuper.isLong()||
+ possiblesuper.isFloat()||possiblesuper.isDouble()))
+ return true;
+ if (cd2.isChar()&&(possiblesuper.isChar()||
+ possiblesuper.isInt()||possiblesuper.isLong()||
+ possiblesuper.isFloat()||possiblesuper.isDouble()))
+ return true;
+ if (cd2.isInt()&&(possiblesuper.isInt()||possiblesuper.isLong()||
+ possiblesuper.isFloat()||possiblesuper.isDouble()))
+ return true;
+ if (cd2.isLong()&&(possiblesuper.isLong()||
+ possiblesuper.isFloat()||possiblesuper.isDouble()))
+ return true;
+ if (cd2.isFloat()&&(possiblesuper.isFloat()||possiblesuper.isDouble()))
+ return true;
+ if (cd2.isDouble()&&possiblesuper.isDouble())
+
+ return true;
+ if (cd2.isBoolean()&&possiblesuper.isBoolean())
+ return true;
+
+ return false;
+ } else if (possiblesuper.isPrimitive()&&(!possiblesuper.isArray())&&
+ cd2.isPtr())
+ return false;
+ else if (cd2.isPrimitive()&&(!cd2.isArray())&&
+ possiblesuper.isPtr())
+ return false;
+ else
+ throw new Error("Case not handled:"+possiblesuper+" "+cd2);
+ }
+
+
+ public boolean isSuperorType(ClassDescriptor possiblesuper, ClassDescriptor cd2) {
+ if (possiblesuper==cd2)
+ return true;
+ else
+ return isSuper(possiblesuper, cd2);
+ }
+
+ private boolean isSuper(ClassDescriptor possiblesuper, ClassDescriptor cd2) {
+ while(cd2!=null) {
+ cd2=getSuper(cd2);
+ if (cd2==possiblesuper)
+ return true;
}
+ return false;
+ }
}
import IR.Tree.ExpressionNode;
/**
- * Descriptor
+ * Descriptor
*
* represents a symbol in the language (var name, function name, etc).
*/
public class VarDescriptor extends Descriptor {
- protected TypeDescriptor td;
- protected String identifier;
-
- public VarDescriptor(TypeDescriptor t, String identifier) {
- super(identifier);
- this.td=t;
- this.identifier=identifier;
- this.safename = "___" + name + "___";
- this.uniqueid=count++;
- }
+ protected TypeDescriptor td;
+ protected String identifier;
- public String getName() {
- return identifier;
- }
+ public VarDescriptor(TypeDescriptor t, String identifier) {
+ super(identifier);
+ this.td=t;
+ this.identifier=identifier;
+ this.safename = "___" + name + "___";
+ this.uniqueid=count++;
+ }
- public TypeDescriptor getType() {
- return td;
- }
+ public String getName() {
+ return identifier;
+ }
- public String toString() {
- return td.toString()+" "+identifier;
- }
+ public TypeDescriptor getType() {
+ return td;
+ }
+
+ public String toString() {
+ return td.toString()+" "+identifier;
+ }
}
import Analysis.Locality.LocalityAnalysis;
public class Virtual {
- State state;
- LocalityAnalysis locality;
- Hashtable<MethodDescriptor, Integer> methodnumber;
- Hashtable<ClassDescriptor, Integer> classmethodcount;
- Hashtable<LocalityBinding, Integer> localitynumber;
+ State state;
+ LocalityAnalysis locality;
+ Hashtable<MethodDescriptor, Integer> methodnumber;
+ Hashtable<ClassDescriptor, Integer> classmethodcount;
+ Hashtable<LocalityBinding, Integer> 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<ClassDescriptor, Integer>();
- if (state.DSM)
- localitynumber=new Hashtable<LocalityBinding, Integer>();
- else
- methodnumber=new Hashtable<MethodDescriptor, Integer>();
- 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<ClassDescriptor, Integer>();
+ if (state.DSM)
+ localitynumber=new Hashtable<LocalityBinding, Integer>();
+ else
+ methodnumber=new Hashtable<MethodDescriptor, Integer>();
+ doAnalysis();
+ }
- if (locality.getClassBindings(cd)!=null)
- for(Iterator<LocalityBinding> 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<LocalityBinding> lbset=locality.getMethodBindings(matchmd);
- if (lbset!=null)
- for(Iterator<LocalityBinding> 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<LocalityBinding> 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<LocalityBinding> lbset=locality.getMethodBindings(matchmd);
+ if (lbset!=null)
+ for(Iterator<LocalityBinding> 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;
+ }
}
// 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();
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!
+ }
}
//*************************************************************************
// 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);
- }
+ }
}
package Interface;
-public class HTTPResponse{
- public int returnCode;
- public long sentBytes;
+public class HTTPResponse {
+ public int returnCode;
+ public long sentBytes;
}
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);
+ }
}
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;
+ }
}
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;
+ }
}
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<rectangles.length;i++) {
- Rectangle r=rectangles[i];
- if ((r.x1<=x)&&(r.y1>=y)&&
- (r.x2>=x)&&(r.y2<=y))
- return r.label;
- }
- long mindistance=Long.MAX_VALUE;
- int minindex=-1;
- for(int i=0;i<points.length;i++) {
- Point p=points[i];
- long dx=p.x-x;
- long dy=p.y-y;
- if ((dx*dx+dy*dy)<mindistance) {
- mindistance=dx*dx+dy*dy;
- minindex=i;
- }
- }
- if (mindistance>THRESHOLD)
- return null;
- else
- return points[minindex].label;
+ String parseclick(int x,int y) {
+ System.out.println(x+","+y);
+ for(int i=0; i<rectangles.length; i++) {
+ Rectangle r=rectangles[i];
+ if ((r.x1<=x)&&(r.y1>=y)&&
+ (r.x2>=x)&&(r.y2<=y))
+ return r.label;
}
+ long mindistance=Long.MAX_VALUE;
+ int minindex=-1;
+ for(int i=0; i<points.length; i++) {
+ Point p=points[i];
+ long dx=p.x-x;
+ long dy=p.y-y;
+ if ((dx*dx+dy*dy)<mindistance) {
+ mindistance=dx*dx+dy*dy;
+ minindex=i;
+ }
+ }
+ if (mindistance>THRESHOLD)
+ 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;
}
+ }
}
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);
+ }
}
+ }
}
// 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;
}
}
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;
+ }
}
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("<br><br><h3>Task: "+td.toString()+"</h3><br>");
- printTask(td,pw);
-
- //printing out the classes that are instantiated by this task
- pw.println("<br><h3>Instantiated Classes:</h3>");
- Set newstates=taganalysis.getFlagStates(td);
- for(Iterator fsit=newstates.iterator();fsit.hasNext();) {
- FlagState fsnew=(FlagState) fsit.next();
- ClassDescriptor cd=fsnew.getClassDescriptor();
- pw.println(" <a href=\"/"+cd.getSymbol()+".html\">"+cd.getSymbol()+"</a><br>");
- pw.println(" "+fsnew.getTextLabel()+"<br>");
- }
-
- 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("<br><br><h3>Task: "+td.toString()+"</h3><br>");
+ printTask(td,pw);
- private String printTask(TaskDescriptor td, PrintWriter pw){
+ //printing out the classes that are instantiated by this task
+ pw.println("<br><h3>Instantiated Classes:</h3>");
+ Set newstates=taganalysis.getFlagStates(td);
+ for(Iterator fsit=newstates.iterator(); fsit.hasNext();) {
+ FlagState fsnew=(FlagState) fsit.next();
+ ClassDescriptor cd=fsnew.getClassDescriptor();
+ pw.println(" <a href=\"/"+cd.getSymbol()+".html\">"+cd.getSymbol()+"</a><br>");
+ pw.println(" "+fsnew.getTextLabel()+"<br>");
+ }
+
+ 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: <a href=\"/"+td.getParamType(i)+".html\">"+td.getParamType(i)+"</a><br>");
+ pw.println("Task Graph: <a href=\"/"+td.getParamType(i)+"-t.html\">"
+ +td.getParamType(i)+"</a><br>");
+ }
+ 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("<br><br><h3>Allocating tasks for "+root.getTextLabel()+":</h3><br>");
+ Vector tasks=root.getAllocatingTasks();
+ for(Iterator it_tasks=tasks.iterator(); it_tasks.hasNext();){
+ TaskDescriptor td=(TaskDescriptor)it_tasks.next();
+ pw.println("<br><strong>Task: "+td.toString()+"</strong><br>");
+ printTask(td,pw);
+ }
- for(int i=0; i < td.numParameters();i++){
- pw.println("FlagState Graph: <a href=\"/"+td.getParamType(i)+".html\">"+td.getParamType(i)+"</a><br>");
- pw.println("Task Graph: <a href=\"/"+td.getParamType(i)+"-t.html\">"
- +td.getParamType(i)+"</a><br>");
- }
- 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("<br><br><h3>Allocating tasks for "+root.getTextLabel()+":</h3><br>");
- Vector tasks=root.getAllocatingTasks();
- for(Iterator it_tasks=tasks.iterator();it_tasks.hasNext();){
- TaskDescriptor td=(TaskDescriptor)it_tasks.next();
- pw.println("<br><strong>Task: "+td.toString()+"</strong><br>");
- 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("<a href=\"/"+ cd.getSymbol()+".ps\">ps</a><br>");
- //pw.println("<a href=\"/"+ cd.getSymbol()+".map\"><img src=\"/"+ cd.getSymbol()+".gif\" ismap=\"ismap\"></A>");
- pw.println("<img src=\""+cd.getSymbol()+".jpg\" usemap=\"#dotvisitor\" />");
- 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("<a href=\"/"+ cd.getSymbol()+"-t.ps\">ps</a><br>");
- // pw.println("<a href=\"/"+ cd.getSymbol()+"-t.map\"><img src=\"/"+ cd.getSymbol()+"-t.gif\" ismap=\"ismap\"></A>");
- pw.println("<img src=\""+cd.getSymbol()+"-t.jpg\" usemap=\"#dotvisitor\" />");
-
- 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("<a href=\""+cd.getSymbol()+".html\">"+ cd.getSymbol() +"</a>");
- pw.println("<br>");
- flagstatemap.put("/"+cd.getSymbol()+".html", cd);
- }
- if (taskgraph.getTaskNodes(cd)!=null) {
- pw.println("<a href=\""+cd.getSymbol()+"-t.html\">Task Graph "+ cd.getSymbol() +"</a>");
- pw.println("<br>");
- 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("<a href=\"/"+ cd.getSymbol()+".ps\">ps</a><br>");
+ //pw.println("<a href=\"/"+ cd.getSymbol()+".map\"><img src=\"/"+ cd.getSymbol()+".gif\" ismap=\"ismap\"></A>");
+ pw.println("<img src=\""+cd.getSymbol()+".jpg\" usemap=\"#dotvisitor\" />");
+ 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("<a href=\"/"+ cd.getSymbol()+"-t.ps\">ps</a><br>");
+ // pw.println("<a href=\"/"+ cd.getSymbol()+"-t.map\"><img src=\"/"+ cd.getSymbol()+"-t.gif\" ismap=\"ismap\"></A>");
+ pw.println("<img src=\""+cd.getSymbol()+"-t.jpg\" usemap=\"#dotvisitor\" />");
+
+ 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("<a href=\""+cd.getSymbol()+".html\">"+ cd.getSymbol() +"</a>");
+ pw.println("<br>");
+ flagstatemap.put("/"+cd.getSymbol()+".html", cd);
}
- pw.println("<br><br><a href=\"/UnifiedTaskGraph.html\">Program flow</a>");
- 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("<a href=\"/UnifiedTaskGraph.ps\">ps</a><br>");
- // pw.println("<a href=\"/"+ cd.getSymbol()+"-t.map\"><img src=\"/"+ cd.getSymbol()+"-t.gif\" ismap=\"ismap\"></A>");
- pw.println("<img src=\"/UnifiedTaskGraph.jpg\" usemap=\"#dotvisitor\" />");
-
- 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("<a href=\""+cd.getSymbol()+"-t.html\">Task Graph "+ cd.getSymbol() +"</a>");
+ pw.println("<br>");
+ taskgraphmap.put("/"+cd.getSymbol()+"-t.html", cd);
+ }
+ }
}
+ pw.println("<br><br><a href=\"/UnifiedTaskGraph.html\">Program flow</a>");
+ 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("<a href=\"/UnifiedTaskGraph.ps\">ps</a><br>");
+ // pw.println("<a href=\"/"+ cd.getSymbol()+"-t.map\"><img src=\"/"+ cd.getSymbol()+"-t.gif\" ismap=\"ismap\"></A>");
+ pw.println("<img src=\"/UnifiedTaskGraph.jpg\" usemap=\"#dotvisitor\" />");
+
+ while((str=mapbr.readLine())!=null)
+ pw.println(str);
+
+ pw.flush();
+ } catch (Exception e) {e.printStackTrace(); System.exit(-1);}
+ return null;
+ }
}
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()+">";
+ }
}
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())+">";
}
}
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<more.length(); i++)
- if (!Character.isSpaceChar(more.charAt(i)))
+ if (!Character.isSpaceChar(more.charAt(i)))
break;
// skip any leading stars.
package Lex;
class DocumentationComment extends Comment {
- DocumentationComment() { }
+ DocumentationComment() {
+ }
}
-
+
import Parse.Sym;
class DoubleLiteral extends NumericLiteral {
- DoubleLiteral(double d) { this.val = new Double(d); }
+ DoubleLiteral(double d) {
+ this.val = new Double(d);
+ }
- Symbol token() { return new Symbol(Sym.FLOATING_POINT_LITERAL, val); }
+ Symbol token() {
+ return new Symbol(Sym.FLOATING_POINT_LITERAL, val);
+ }
}
import Parse.Sym;
class EOF extends Token {
- EOF() {}
- Symbol token() { return new Symbol(Sym.EOF); }
- public String toString() { return "EOF"; }
+ EOF() {
+ }
+ Symbol token() {
+ return new Symbol(Sym.EOF);
+ }
+ public String toString() {
+ return "EOF";
+ }
}
package Lex;
class EndOfLineComment extends Comment {
- EndOfLineComment(String comment) { appendLine(comment); }
+ EndOfLineComment(String comment) {
+ appendLine(comment);
+ }
}
super(in);
}
public int read() throws IOException {
- int r = (pushback==-1)?in.read():pushback; pushback=-1;
-
+ int r = (pushback==-1) ? in.read() : pushback; pushback=-1;
+
if (r!='\\') {
isEvenSlash=true;
return r;
isEvenSlash=true;
return r;
}
-
+
// Check for the trailing u.
pushback=in.read();
if (pushback!='u') {
return '\\';
}
- // OK, we've found backslash-u.
+ // OK, we've found backslash-u.
// Reset pushback and snarf up all trailing u's.
pushback=-1;
while((r=in.read())=='u')
;
- // Now we should find 4 hex digits.
+ // Now we should find 4 hex digits.
// If we don't, we can raise bloody hell.
int val=0;
for (int i=0; i<4; i++, r=in.read()) {
public int read(char cbuf[], int off, int len) throws IOException {
for (int i=0; i<len; i++) {
int c = read();
- if (c==-1) return (i==0)?-1:i; // end of stream reached.
+ if (c==-1) return (i==0) ? -1 : i; // end of stream reached.
else cbuf[i+off] = (char) c;
}
return len;
}
- public boolean markSupported() { return false; }
+ public boolean markSupported() {
+ return false;
+ }
public boolean ready() throws IOException {
if (pushback!=-1) return true;
java_cup.runtime.Symbol[] backing = new java_cup.runtime.Symbol[10];
int start=0, end=0;
final Getter getter;
- FIFO(Getter getter) { this.getter = getter; }
- public boolean isEmpty() { return start==end; }
+ FIFO(Getter getter) {
+ this.getter = getter;
+ }
+ public boolean isEmpty() {
+ return start==end;
+ }
private boolean isFull() {
return start==end+1 || (start==0 && end==backing.length-1);
}
private int size() {
- return ((end<start)?end+backing.length:end)-start;
+ return ((end<start) ? end+backing.length : end)-start;
}
public void put(java_cup.runtime.Symbol o) {
if (isFull()) {
java_cup.runtime.Symbol[] nbacking =
- new java_cup.runtime.Symbol[backing.length*2];
+ new java_cup.runtime.Symbol[backing.length*2];
System.arraycopy(backing, start, nbacking, 0, backing.length-start);
System.arraycopy(backing, 0, nbacking, backing.length-start, start);
start = 0;
}
abstract static class Getter {
abstract java_cup.runtime.Symbol next()
- throws java.io.IOException;
+ throws java.io.IOException;
}
private static void ASSERT(boolean b) {
if (!b) throw new RuntimeException();
}
}
-
-
+
+
import Parse.Sym;
class FloatLiteral extends NumericLiteral {
- FloatLiteral(float f) { this.val = new Float(f); }
+ FloatLiteral(float f) {
+ this.val = new Float(f);
+ }
- Symbol token() { return new Symbol(Sym.FLOATING_POINT_LITERAL, val); }
+ Symbol token() {
+ return new Symbol(Sym.FLOATING_POINT_LITERAL, val);
+ }
}
public class Identifier extends Token {
String identifier;
- public Identifier(String identifier) { this.identifier=identifier; }
+ public Identifier(String identifier) {
+ this.identifier=identifier;
+ }
- public String toString() { return "Identifier <"+identifier+">"; }
+ public String toString() {
+ return "Identifier <"+identifier+">";
+ }
/* Ben Walter <bwalter@mit.edu> 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. ;-) <cananian@alumni.princeton.edu>
*/
- Symbol token() { return new Symbol(Sym.IDENTIFIER, identifier); }
+ Symbol token() {
+ return new Symbol(Sym.IDENTIFIER, identifier);
+ }
}
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);
+ }
}
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 {
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();
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)
switch(lookahead.peek(i).sym) {
default:
return false;
+
case Sym.LT:
case Sym.GT:
case Sym.COMMA:
}
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();
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:
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
} else { // TraditionalComment
return snarfComment(new TraditionalComment());
}
+
default: // it's a token, not a comment.
return getToken();
}
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));
case '^':
case '%':
return getOperator();
+
case '\'':
return getCharLiteral();
+
case '\"':
return getStringLiteral();
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)))
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());
// 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.
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; )
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) {
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);
}
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();
}
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());
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();
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;
case '\\':
val.append(getEscapeSequence());
break;
+
case '\n':
throw new Error("Invalid string literal on line " + line_num);
+
default:
val.append(consume());
break;
char closequote = consume();
if (openquote != '\"' || closequote != '\"')
throw new Error("Invalid string literal on line " + line_num);
-
+
return new StringLiteral(val.toString().intern());
}
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);
}
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;
+ }
}
}
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);
+ }
}
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 <null>"; }
+ public String toString() {
+ return "NullLiteral <null>";
+ }
}
abstract class NumericLiteral extends Literal {
Number val;
- public String toString() { return "NumericLiteral <"+val.toString()+">"; }
+ public String toString() {
+ return "NumericLiteral <"+val.toString()+">";
+ }
}
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();
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.");
}
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)+">";
}
}
for (int i=0; i<s.length(); i++)
switch(s.charAt(i)) {
case '\t': sb.append("\\t"); break;
+
case '\f': sb.append("\\f"); break;
+
case '\n': sb.append("\\n"); break;
+
default:
if ((int)s.charAt(i)<32)
sb.append("\\"+Integer.toOctalString((int)s.charAt(i)));
package Lex;
class TraditionalComment extends Comment {
- TraditionalComment() { }
+ TraditionalComment() {
+ }
}
class WhiteSpace extends InputElement {
char whitespace;
- WhiteSpace(char which) { this.whitespace=which; }
+ WhiteSpace(char which) {
+ this.whitespace=which;
+ }
- public String toString() {
+ public String toString() {
String s;
switch(whitespace) {
case ' ': s = "SP"; break;
+
case '\t': s = "HT"; break;
+
case '\f': s = "FF"; break;
+
case '\n': s = "LT"; break;
+
default: s = "Unknown Whitespace character."; break;
}
return "Whitespace <"+s+">";
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<args.length;i++) {
- String option=args[i];
- if (option.equals("-precise"))
- IR.Flat.BuildCode.GENERATEPRECISEGC=true;
- else if (option.equals("-prefetch"))
- state.PREFETCH=true;
- else if (option.equals("-dir"))
- IR.Flat.BuildCode.PREFIX=args[++i]+"/";
- else if (option.equals("-selfloop"))
- state.selfloops.add(args[++i]);
- else if (option.equals("-excprefetch"))
- state.excprefetch.add(args[++i]);
- else if (option.equals("-classlibrary"))
- ClassLibraryPrefix=args[++i]+"/";
- else if(option.equals("-numcore")) {
- ++i;
- state.CORENUM = Integer.parseInt(args[i]);
- }
- else if (option.equals("-mainclass"))
- state.main=args[++i];
- else if (option.equals("-trueprob")) {
- state.TRUEPROB=Double.parseDouble(args[++i]);
- } else if (option.equals("-printflat"))
- State.PRINTFLAT=true;
- else if (option.equals("-struct"))
- state.structfile=args[++i];
- else if (option.equals("-conscheck"))
- state.CONSCHECK=true;
- else if (option.equals("-task"))
- state.TASK=true;
- else if (option.equals("-taskstate"))
- state.TASKSTATE=true;
- else if (option.equals("-tagstate"))
- state.TAGSTATE=true;
- else if (option.equals("-flatirtasks")) {
- state.FLATIRGRAPH=true;
- state.FLATIRGRAPHTASKS=true;
- }
- else if (option.equals("-flatirusermethods")) {
- state.FLATIRGRAPH=true;
- state.FLATIRGRAPHUSERMETHODS=true;
- }
- else if (option.equals("-flatirlibmethods")) {
- state.FLATIRGRAPH=true;
- state.FLATIRGRAPHLIBMETHODS=true;
- }
- else if (option.equals("-multicore"))
- state.MULTICORE=true;
- else if (option.equals("-ownership"))
- state.OWNERSHIP=true;
- else if (option.equals("-optional"))
- state.OPTIONAL=true;
- else if (option.equals("-raw"))
- state.RAW=true;
- else if (option.equals("-scheduling"))
- state.SCHEDULING=true;
- else if (option.equals("-thread"))
- state.THREAD=true;
- else if (option.equals("-dsm"))
- state.DSM=true;
- else if (option.equals("-webinterface"))
- state.WEBINTERFACE=true;
- else if (option.equals("-instructionfailures"))
- state.INSTRUCTIONFAILURE=true;
- else if (option.equals("-help")) {
- System.out.println("-classlibrary classlibrarydirectory -- directory where classlibrary is located");
- System.out.println("-selfloop task -- this task doesn't self loop its parameters forever");
- System.out.println("-dir outputdirectory -- output code in outputdirectory");
- System.out.println("-struct structfile -- output structure declarations for repair tool");
- System.out.println("-mainclass -- main function to call");
- System.out.println("-dsm -- distributed shared memory support");
- System.out.println("-precise -- use precise garbage collection");
- System.out.println("-conscheck -- turn on consistency checking");
- System.out.println("-task -- compiler for tasks");
- System.out.println("-thread -- threads");
- System.out.println("-trueprob <d> -- 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<args.length; i++) {
+ String option=args[i];
+ if (option.equals("-precise"))
+ IR.Flat.BuildCode.GENERATEPRECISEGC=true;
+ else if (option.equals("-prefetch"))
+ state.PREFETCH=true;
+ else if (option.equals("-dir"))
+ IR.Flat.BuildCode.PREFIX=args[++i]+"/";
+ else if (option.equals("-selfloop"))
+ state.selfloops.add(args[++i]);
+ else if (option.equals("-excprefetch"))
+ state.excprefetch.add(args[++i]);
+ else if (option.equals("-classlibrary"))
+ ClassLibraryPrefix=args[++i]+"/";
+ else if(option.equals("-numcore")) {
+ ++i;
+ state.CORENUM = Integer.parseInt(args[i]);
+ } else if (option.equals("-mainclass"))
+ state.main=args[++i];
+ else if (option.equals("-trueprob")) {
+ state.TRUEPROB=Double.parseDouble(args[++i]);
+ } else if (option.equals("-printflat"))
+ State.PRINTFLAT=true;
+ else if (option.equals("-struct"))
+ state.structfile=args[++i];
+ else if (option.equals("-conscheck"))
+ state.CONSCHECK=true;
+ else if (option.equals("-task"))
+ state.TASK=true;
+ else if (option.equals("-taskstate"))
+ state.TASKSTATE=true;
+ else if (option.equals("-tagstate"))
+ state.TAGSTATE=true;
+ else if (option.equals("-flatirtasks")) {
+ state.FLATIRGRAPH=true;
+ state.FLATIRGRAPHTASKS=true;
+ } else if (option.equals("-flatirusermethods")) {
+ state.FLATIRGRAPH=true;
+ state.FLATIRGRAPHUSERMETHODS=true;
+ } else if (option.equals("-flatirlibmethods")) {
+ state.FLATIRGRAPH=true;
+ state.FLATIRGRAPHLIBMETHODS=true;
+ } else if (option.equals("-multicore"))
+ state.MULTICORE=true;
+ else if (option.equals("-ownership"))
+ state.OWNERSHIP=true;
+ else if (option.equals("-optional"))
+ state.OPTIONAL=true;
+ else if (option.equals("-raw"))
+ state.RAW=true;
+ else if (option.equals("-scheduling"))
+ state.SCHEDULING=true;
+ else if (option.equals("-thread"))
+ state.THREAD=true;
+ else if (option.equals("-dsm"))
+ state.DSM=true;
+ else if (option.equals("-webinterface"))
+ state.WEBINTERFACE=true;
+ else if (option.equals("-instructionfailures"))
+ state.INSTRUCTIONFAILURE=true;
+ else if (option.equals("-help")) {
+ System.out.println("-classlibrary classlibrarydirectory -- directory where classlibrary is located");
+ System.out.println("-selfloop task -- this task doesn't self loop its parameters forever");
+ System.out.println("-dir outputdirectory -- output code in outputdirectory");
+ System.out.println("-struct structfile -- output structure declarations for repair tool");
+ System.out.println("-mainclass -- main function to call");
+ System.out.println("-dsm -- distributed shared memory support");
+ System.out.println("-precise -- use precise garbage collection");
+ System.out.println("-conscheck -- turn on consistency checking");
+ System.out.println("-task -- compiler for tasks");
+ System.out.println("-thread -- threads");
+ System.out.println("-trueprob <d> -- 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<FEdge> fev = (Vector<FEdge>)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<FEdge> fev = (Vector<FEdge>)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<Integer> selectedScheduling = new Vector<Integer>();
- int processTime = Integer.MAX_VALUE;
- while(it_scheduling.hasNext()) {
- Vector<Schedule> scheduling = (Vector<Schedule>)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<Schedule> scheduling = new Vector<Schedule>();
- 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<Schedule> scheduling1 = new Vector<Schedule>();
- 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<Schedule> scheduling = (Vector<Schedule>)it_scheduling.next();
- Vector<Schedule> 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<Integer> selectedScheduling = new Vector<Integer>();
+ int processTime = Integer.MAX_VALUE;
+ while(it_scheduling.hasNext()) {
+ Vector<Schedule> scheduling = (Vector<Schedule>)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<Schedule> scheduling = new Vector<Schedule>();
+ 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<Schedule> scheduling1 = new Vector<Schedule>();
+ 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<Schedule> scheduling = (Vector<Schedule>)it_scheduling.next();
+ Vector<Schedule> 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());
+ }
+ }
}
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;
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 */
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;
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;
}
}
/* 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;
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];
}
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;
}
#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;
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
exit(1);
}
-#ifdef MAC
+#ifdef MAC
if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &setsockflag, sizeof(setsockflag)) < 0) {
perror("socket");
exit(1);
}
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__);
}
}
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) {
*((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++) {
}
} 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;
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);
objheader_t *header;
/* Lookup Objects in prefetch cache and remove them */
if(((header = prehashSearch(oid)) != NULL)) {
- prehashRemove(oid);
+ prehashRemove(oid);
}
offset += sizeof(unsigned int);
}
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
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
unsigned int newsize;
int index;
chashlistnode_t *ptr, *node;
-
+
if(table->numelements > (table->loadfactor * table->size)) {
//Resize
newsize = table->size << 1;
#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
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;
int index;
chashlistnode_t *curr, *prev;
chashlistnode_t *ptr, *node;
-
+
ptr = table->table;
index = chashFunction(table,key);
curr = &ptr[index];
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;
}
int i, isFirst;
chashlistnode_t *ptr, *curr, *next;
ptr = ctable->table;
-
+
for(i=0 ; i<ctable->size ; i++) {
curr = &ptr[i];
isFirst = 1 ;
curr = next;
}
}
-
+
free(ptr);
ptr = NULL;
free(ctable);
#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;
//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;
};
/*******************************************************************************
//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;
* 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);
+ }
}
//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
#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);}
* 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);}
/*****************************************
* 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
#define LISTEN_PORT 2156
#define UDP_PORT 2158
//Prefetch tuning paramters
-#define RETRYINTERVAL 20//N
+#define RETRYINTERVAL 20 //N
#define SHUTDOWNINTERVAL 3 //M
#include <stdlib.h>
#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<NUMCLASSES) {\
- size=classsize[type];\
- } else {\
- size=classsize[type]*((struct ArrayObject *)&((objheader_t *)x)[1])->___length___+sizeof(struct ArrayObject);\
- }\
+#define GETSIZE(size, x) { \
+ int type=TYPE(x); \
+ if (type<NUMCLASSES) { \
+ size=classsize[type]; \
+ } else { \
+ size=classsize[type]*((struct ArrayObject *)&((objheader_t *)x)[1])->___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
#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 {
// 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;
/* 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. */
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);
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);
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;
}
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);
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);
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;
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;
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;
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));
/* 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;
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);
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));
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);
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;
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 */
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<objvernotmatch; j++) {
- objheader_t *header = mhashSearch(oidvernotmatch[j]);
- int size = 0;
- GETSIZE(size, header);
- size += sizeof(objheader_t);
- memcpy(objs+offset, header, size);
- offset += size;
}
+ }
+ }
+
+ /* send TRANS_DISAGREE and objs*/
+ if(v_nomatch > 0) {
+#ifdef CACHE
+ char *objs = calloc(1, numBytes);
+ int j, offset = 0;
+ for(j = 0; j<objvernotmatch; j++) {
+ objheader_t *header = mhashSearch(oidvernotmatch[j]);
+ int size = 0;
+ GETSIZE(size, header);
+ size += sizeof(objheader_t);
+ memcpy(objs+offset, header, size);
+ offset += size;
+ }
#endif
- 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));
- }
- 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) {
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) {
}
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) {
UnLock(STATUSPTR(header));
}
//TODO Update location lookup table
-
+
/* Send ack to coordinator */
control = TRANS_SUCESSFUL;
send_data((int)acceptfd, &control, sizeof(char));
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;
}
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];
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 */
} else {
oid = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + offsetarry[i]));
}
-
+
/* Don't continue if we hit a NULL pointer */
if (oid==0)
break;
*((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);
}
//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) {
int bytesSent;
int size;
int i = 0;
-
+
while(i < numoid) {
oid = *(oidarry + i);
if((header = (objheader_t *) mhashSearch(oid)) == NULL) {
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));
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 {
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;
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;
+ }
}
}
}
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 {
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;
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);
+ }
}
}
}
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));
#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);
+ }
+ */
#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 *);
/************************************************************************************************
- 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
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
#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
#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
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));
//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;
}
if (toid < oid)
continue;
-
+
/* Fill objpiles DS */
int i;
int onumoffset=(*tmp)->numoffset;
short * ooffset=(*tmp)->offset;
- for(i=0;i<numoffset;i++) {
+ for(i=0; i<numoffset; i++) {
if (i>onumoffset) {
//We've matched, let's just extend the current prefetch
(*tmp)->numoffset=numoffset;
}
//if we get to the end, we're already covered by this prefetch
return;
- oidloop:
+oidloop:
;
}
}
-
+
}
-#include<stdio.h>
-#include<string.h>
-#include<stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
#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;
}
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 */
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);
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) {
#ifndef _MCPILEQ_H_
#define _MCPILEQ_H_
-#include<pthread.h>
-#include<stdio.h>
-#include<stdlib.h>
-#include<string.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
//Structure to make machine groups when prefetching
-typedef struct objpile {
+typedef struct objpile {
unsigned int oid;
short numoffset;
short *offset;
#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;
}
#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);
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));
#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,
* 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;
}
#include <stdio.h>
/* 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);
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;
}
unsigned int newsize;
int index;
prehashlistnode_t *ptr, *node;
-
+
if(pflookup.numelements > (pflookup.loadfactor * pflookup.size)) {
//Resize
newsize = 2 * pflookup.size + 1;
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);
void *prehashSearch(unsigned int key) {
int index;
prehashlistnode_t *ptr, *node;
-
+
pthread_mutex_lock(&pflookup.lock);
ptr = pflookup.table;
index = prehashFunction(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;
#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;
/* 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);
//Wait for tail to go past end
tmpoffset=size+sizeof(int);
if (headoffset<tailoffset) {
- pthread_cond_signal(&qcond);//wake the other thread up
+ pthread_cond_signal(&qcond); //wake the other thread up
return NULL;
}
//Wait for tail to go past new start
if (tailoffset<=tmpoffset) {
- pthread_cond_signal(&qcond);//wake the other thread up
+ pthread_cond_signal(&qcond); //wake the other thread up
return NULL;
}
- *((int *)(memory+headoffset))=-1;//safe because we left space
+ *((int *)(memory+headoffset))=-1; //safe because we left space
*((int*)memory)=size+sizeof(int);
return memory+sizeof(int);
} else {
if (headoffset<tailoffset&&tailoffset<=tmpoffset) {
- pthread_cond_signal(&qcond);//wake the other thread up
+ pthread_cond_signal(&qcond); //wake the other thread up
return NULL;
}
*((int*)(memory+headoffset))=size+sizeof(int);
headoffset=size+sizeof(int);
} else
headoffset=tmpoffset;
- pthread_cond_signal(&qcond);//wake the other thread up
+ pthread_cond_signal(&qcond); //wake the other thread up
}
void * gettail() {
pthread_mutex_unlock(&qlock);
}
if (*((int *)(memory+tailoffset))==-1) {
- tailoffset=0;//do loop
+ tailoffset=0; //do loop
}
return memory+tailoffset+sizeof(int);
#ifndef _QUEUE_H_
#define _QUEUE_H_
-#include<stdio.h>
-#include<stdlib.h>
-#include<pthread.h>
-#include<string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <pthread.h>
+#include <string.h>
#include "dstm.h"
void queueInit(void);
printf("nRemoteReadSend = %d\n", nRemoteSend);
//TODO Remove later
/*
- int i;
- for(i=0; i<numprefetchsites; i++) {
- printf("siteid = %d, callCount = %d\n", i, evalPrefetch[i].callcount);
- }
- */
+ int i;
+ for(i=0; i<numprefetchsites; i++) {
+ printf("siteid = %d, callCount = %d\n", i, evalPrefetch[i].callcount);
+ }
+ */
exit(0);
#endif
}
#if defined(__i386__)
inline int test_and_set(volatile unsigned int *addr) {
- int oldval;
- /* Note: the "xchg" instruction does not need a "lock" prefix */
- __asm__ __volatile__("xchgl %0, %1"
- : "=r"(oldval), "=m"(*(addr))
- : "0"(1), "m"(*(addr)));
- return oldval;
+ int oldval;
+ /* Note: the "xchg" instruction does not need a "lock" prefix */
+ __asm__ __volatile__ ("xchgl %0, %1"
+ : "=r" (oldval), "=m" (*(addr))
+ : "0" (1), "m" (*(addr)));
+ return oldval;
}
inline void UnLock(volatile unsigned int *addr) {
- int oldval;
- /* Note: the "xchg" instruction does not need a "lock" prefix */
- __asm__ __volatile__("xchgl %0, %1"
- : "=r"(oldval), "=m"(*(addr))
- : "0"(0), "m"(*(addr)));
+ int oldval;
+ /* Note: the "xchg" instruction does not need a "lock" prefix */
+ __asm__ __volatile__ ("xchgl %0, %1"
+ : "=r" (oldval), "=m" (*(addr))
+ : "0" (0), "m" (*(addr)));
}
#elif
# error need implementation of test_and_set
printf("Calloc error at %s line %d\n", __FILE__, __LINE__);
return NULL;
}
-
+
socknode_t **nodelist;
if ((nodelist = calloc(size, sizeof(socknode_t *))) < 0) {
printf("Calloc error at %s line %d\n", __FILE__, __LINE__);
free(sockhash);
return NULL;
}
-
+
sockhash->table = nodelist;
sockhash->inuse = NULL;
sockhash->size = size;
sockhash->mask = size - 1;
sockhash->mylock=0;
-
+
return sockhash;
}
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;
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;
socknode_t **ptr;
int key = mid&(sockhash->mask);
int sd;
-
+
ptr=&(sockhash->table[key]);
-
+
while(*ptr!=NULL) {
if (mid == (*ptr)->mid) {
return (*ptr)->sd;
socknode_t **ptr;
int key = mid&(sockhash->mask);
int sd;
-
+
Lock(&sockhash->mylock);
ptr=&(sockhash->table[key]);
while(*ptr!=NULL) {
}
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;
#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
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);
#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);
/* 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;
}
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);
}
}
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];
// 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;
// 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);
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;
}
//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
/* 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;
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) {
}
}
-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) {
}
}
-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)
inline int arrayLength(int *array) {
int i;
- for(i=0 ;array[i] != -1; i++)
+ for(i=0 ; array[i] != -1; i++)
;
return i;
}
int len;
char * node= getmemory(qnodesize);
int top=endoffsets[ntuples-1];
-
- if (node==NULL)
+
+ if (node==NULL)
return;
/* Set queue node values */
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);
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) {
success = 1;
return tmp;
} else {
- ptr = ptr-> next;
+ ptr = ptr->next;
}
}
-
+
if(success == 0) {
return NULL;
}
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);
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);
for(t = 0; t < NUM_THREADS; t++)
pthread_cancel(wthreads[t]);
#endif
-
+
return;
}
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
objheader_t *objcopy;
int size;
void *buf;
-
+
if(oid == 0) {
return NULL;
}
-
+
if((objheader = chashSearch(record->lookupTable, oid)) != NULL){
#ifdef TRANSSTATS
nchashSearch++;
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
#endif
} else {
#ifdef CACHE
- if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) {
+ if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) {
#ifdef TRANSSTATS
nprehashSearch++;
#endif
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
#ifdef TRANSSTATS
nRemoteSend++;
#endif
- STATUS(objcopy)=0;
+ STATUS(objcopy)=0;
#ifdef COMPILER
return &objcopy[1];
#else
tmp->rcount = 1;
STATUS(tmp) = NEW;
chashInsert(record->lookupTable, OID(tmp), tmp);
-
+
#ifdef COMPILER
return &tmp[1]; //want space after object header
#else
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 */
//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;
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;
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);
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);
/* 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");
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++;
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;
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;
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 */
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);
//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;
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);
/* clear objects from prefetch cache */
/*
- if(*(tdata->replyctrl) == TRANS_ABORT) {
- int i;
- for(i=0; i<tdata->buffer->f.nummod; i++) {
+ if(*(tdata->replyctrl) == TRANS_ABORT) {
+ int i;
+ for(i=0; i<tdata->buffer->f.nummod; i++) {
unsigned int oid = tdata->buffer->oidmod[i];
objheader_t *header;
if((header = prehashSearch(oid)) != NULL) {
prehashRemove(oid);
}
- }
- for(i=0; i<tdata->buffer->f.numread; i++) {
+ }
+ for(i=0; i<tdata->buffer->f.numread; i++) {
char *objread = tdata->buffer->objread;
unsigned int oid = *((unsigned int *)(objread+(sizeof(unsigned int) +
sizeof(unsigned short))*i));
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;
/* 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) {
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;
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;
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;
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 {
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;
}
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)));
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 */
} 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;
}
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;
//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);
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
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__);
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;
}
UnLock(STATUSPTR(header));
}
-
+
return 0;
}
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;i<ntuples; i++) {
- unsigned short baseindex=(i==0)?0:endoffsets[i-1];
+ for(i=0; i<ntuples; i++) {
+ unsigned short baseindex=(i==0) ? 0 : endoffsets[i-1];
unsigned short endindex=endoffsets[i];
unsigned int oid=oidarray[i];
int newbase;
if (oid==0)
continue;
//Look up fields locally
- for(newbase=baseindex;newbase<endindex;newbase++) {
+ for(newbase=baseindex; newbase<endindex; newbase++) {
if (!lookupObject(&oid, arryfields[newbase]))
break;
//Ended in a null pointer...
//Add to remote requests
machinenum=lhashSearch(oid);
insertPile(machinenum, oid, endindex-newbase, &arryfields[newbase], &head);
- tuple:
+tuple:
;
}
while(1) {
/* lock mutex of primary prefetch queue */
void *node=gettail();
- /* Check if the tuples are found locally, if yes then reduce them further*/
+ /* Check if the tuples are found locally, if yes then reduce them further*/
/* and group requests by remote machine ids by calling the makePreGroups() */
prefetchpile_t *pilehead = foundLocal(node);
if (pilehead!=NULL) {
- // Get sock from shared pool
+ // Get sock from shared pool
int sd = getSock2(transPrefetchSockPool, pilehead->mid);
-
+
/* 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);
}
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);
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) {
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;
}
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];
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);
} else {
printf("Error: in decoding the control value %d, %s, %d\n",control, __FILE__, __LINE__);
}
-
+
return 0;
}
#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;
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__);
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 {
i++;
}
}
-
+
/* Send array of version */
{
i = 0;
i++;
}
}
-
+
*((unsigned int *)(&msg[1] + size)) = myIpAddr;
size += sizeof(unsigned int);
*((unsigned int *)(&msg[1] + size)) = threadid;
pthread_cond_wait(&(ndata->threadcond), &(ndata->threadnotify));
pthread_mutex_unlock(&(ndata->threadnotify));
}
-
+
pthread_cond_destroy(&threadcond);
pthread_mutex_destroy(&threadnotify);
free(ndata);
}
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) {
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);
//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 {
*((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);
}
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;
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) {
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;
}
#endif
void * getfirstkey(struct genhashtable *ht) {
- if(ht->list == NULL) {
- return NULL;
- }
+ if(ht->list == NULL) {
+ return NULL;
+ }
return ht->list->src;
}
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;j<newcurrentsize;j++) newbins[j]=NULL;
+ for(j=0; j<newcurrentsize; j++) newbins[j]=NULL;
ht->currentsize=newcurrentsize;
- for(i=0;i<oldcurrentsize;i++) {
+ for(i=0; i<oldcurrentsize; i++) {
struct genpointerlist * tmpptr=oldbins[i];
while(tmpptr!=NULL) {
- unsigned int hashcode=genhashfunction(ht, tmpptr->src);
- 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;
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;j<newcurrentsize;j++) newbins[j]=NULL;
+ for(j=0; j<newcurrentsize; j++) newbins[j]=NULL;
ht->currentsize=newcurrentsize;
- for(i=0;i<oldcurrentsize;i++) {
+ for(i=0; i<oldcurrentsize; i++) {
struct genpointerlist * tmpptr=oldbins[i];
while(tmpptr!=NULL) {
- unsigned int hashcode=genhashfunction(ht, tmpptr->src);
- 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;
struct genpointerlist **oldbins=ht->bins;
long j,i;
- for(i=0;i<ht->currentsize;i++) {
+ for(i=0; i<ht->currentsize; i++) {
struct genpointerlist * tmpptr=oldbins[i];
while(tmpptr!=NULL) {
unsigned int hashcode=genhashfunction(ht, tmpptr->src);
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;
ptr->iprev->inext=ptr->inext;
if (ptr->inext!=NULL)
ptr->inext->iprev=ptr->iprev;
-
+
RUNFREE(ptr);
ht->counter--;
return;
#ifdef RAWDEBUG
raw_test_pass(0xf001);
#endif
- for(i=0;i<geninitialnumbins;i++) {
+ for(i=0; i<geninitialnumbins; i++) {
gpl[i]=NULL;
}
#ifdef RAWDEBUG
void genfreehashtable(struct genhashtable * ht) {
int i;
- for (i=0;i<ht->currentsize;i++) {
+ for (i=0; i<ht->currentsize; i++) {
if (ht->bins[i]!=NULL) {
struct genpointerlist *genptr=ht->bins[i];
while(genptr!=NULL) {
/* SIMPLE HASH ********************************************************/
struct ObjectIterator* ObjectHashcreateiterator(struct ObjectHash * thisvar) {
- return allocateObjectIterator(thisvar->listhead);
+ return allocateObjectIterator(thisvar->listhead);
}
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) {
}
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];
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);
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);
#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) {
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);
/* SIMPLE HASH ********************************************************/
struct RuntimeIterator* RuntimeHashcreateiterator(struct RuntimeHash * thisvar) {
- return allocateRuntimeIterator(thisvar->listhead);
+ return allocateRuntimeIterator(thisvar->listhead);
}
void RuntimeHashiterator(struct RuntimeHash *thisvar, struct RuntimeIterator * it) {
}
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) {
}
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];
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);
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);
#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) {
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;
}
}
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) {
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);
}
}
-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);
}
}
}
+}
struct RuntimeHash *todo=allocateRuntimeHash(100);
int i;
- for(i=0;i<numparams;i++) {
+ for(i=0; i<numparams; i++) {
void * objptr=srcpointer[i];
if (RuntimeHashcontainskey(forward, (int) objptr))
RuntimeHashget(forward,(int) objptr,(int *) &newarray[i]);
RuntimeHashremove(todo, (int) ptr, (int) ptr);
{
void *cpy;
- unsigned int * pointer=NULL;
+ unsigned int * pointer=NULL;
RuntimeHashget(forward, (int) ptr, (int *) &cpy);
pointer=pointerarray[type];
struct ArrayObject *ao_cpy=(struct ArrayObject *) cpy;
int length=ao->___length___;
int i;
- for(i=0;i<length;i++) {
- void *objptr=((void **)(((char *)& ao->___length___)+sizeof(int)))[i];
+ for(i=0; i<length; i++) {
+ void *objptr=((void **)(((char *)&ao->___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 {
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;
}
}
}
struct RuntimeHash *visited=allocateRuntimeHash(100);
int i;
- for(i=0;i<numparams;i++) {
+ for(i=0; i<numparams; i++) {
if (checkpoint[i]!=NULL) {
RuntimeHashadd(todo, (int) checkpoint[i], (int) checkpoint[i]);
RuntimeHashadd(visited, (int) checkpoint[i], (int) checkpoint[i]);
}
}
-
+
while(RuntimeHashcountset(todo)!=0) {
void * ptr=(void *) RuntimeHashfirstkey(todo);
int type=((int *)ptr)[0];
RuntimeHashadd(visited, (int) objptr, (int) objptr);
RuntimeHashadd(todo, (int) objptr, (int) objptr);
}
- RuntimeHashget(reverse, (int) objptr, (int *) & (((struct ___TagDescriptor___ *)cpy)->flagptr));
+ RuntimeHashget(reverse, (int) objptr, (int *) &(((struct ___TagDescriptor___ *)cpy)->flagptr));
}
} else
#endif
int cpysize=sizeof(struct ArrayObject)+length*size;
memcpy(ao_cpy, ao, cpysize);
- for(i=0;i<length;i++) {
- void *objptr=((void **)(((char *)& ao->___length___)+sizeof(int)))[i];
+ for(i=0; i<length; i++) {
+ void *objptr=((void **)(((char *)&ao->___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 {
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);
#ifdef MULTICORE
enqueueObject(cpy, NULL,0); //TODO
#else
- enqueueObject(cpy);
+ enqueueObject(cpy);
#endif
}
}
#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);
}
}
void CALL11(___FileOutputStream______nativeFlush____I, int fd, int fd) {
- // not supported in RAW version
+ // not supported in RAW version
#ifndef RAW
fsync(fd);
#endif
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;
}
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<toread)
long long CALL01(___File______nativeLength_____AR_B, struct ArrayObject * ___pathname___) {
int length=VAR(___pathname___)->___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;
//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_heaptop) {\
-void *copy;\
-if (gc_createcopy(orig,©))\
-enqueue(orig);\
-dst=copy;\
-}\
-}
+ if ((!(((unsigned int)orig)&0x1))) { \
+ if (orig>=curr_heapbase&&orig<curr_heaptop) { \
+ void *copy; \
+ if (gc_createcopy(orig,©)) \
+ enqueue(orig);\
+ dst=copy; \
+ } \
+ }
#else
#define ENQUEUE(orig, dst) \
-void *copy; \
-if (gc_createcopy(orig,©))\
-enqueue(orig);\
-dst=copy
+ void *copy; \
+ if (gc_createcopy(orig,©)) \
+ enqueue(orig);\
+ dst=copy
#endif
struct pointerblock {
void enqueue(void *ptr) {
if (headindex==NUMPTRS) {
struct pointerblock * tmp;
- if (spare!=NULL) {
+ if (spare!=NULL) {
tmp=spare;
spare=NULL;
- } else
+ } else
tmp=malloc(sizeof(struct pointerblock));
head->next=tmp;
head=tmp;
/* 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;i<stackptr->size;i++) {
+ for(i=0; i<stackptr->size; i++) {
void * orig=stackptr->array[i];
ENQUEUE(orig, stackptr->array[i]);
}
listptr=listptr->next;
} else
break;
- }
- }
+}
+}
#endif
-
+
#ifdef TASK
{
/* Update objectsets */
int i;
- for(i=0;i<NUMCLASSES;i++) {
+ for(i=0; i<NUMCLASSES; i++) {
#ifdef MULTICORE
#else
struct parameterwrapper * p=objectqueues[i];
#endif
}
}
-
+
if (forward!=NULL) {
struct RuntimeNode * ptr=forward->listhead;
while(ptr!=NULL) {
{
/* Update current task descriptor */
int i;
- for(i=0;i<currtpd->numParameters;i++) {
+ for(i=0; i<currtpd->numParameters; 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;i<tpd->numParameters;i++) {
+ for(i=0; i<tpd->numParameters; i++) {
void * orig=tpd->parameterArray[i];
ENQUEUE(orig, tpd->parameterArray[i]);
}
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;i<tpd->numParameters;i++) {
+ for(i=0; i<tpd->numParameters; i++) {
void * orig=tpd->parameterArray[i];
ENQUEUE(orig, tpd->parameterArray[i]);
}
#endif
int length=ao->___length___;
int i;
- for(i=0;i<length;i++) {
- void *objptr=((void **)(((char *)& ao->___length___)+sizeof(int)))[i];
- ENQUEUE(objptr, ((void **)(((char *)& ao_cpy->___length___)+sizeof(int)))[i]);
+ for(i=0; i<length; i++) {
+ void *objptr=((void **)(((char *)&ao->___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)));
}
}
}
while(taghead!=NULL) {
int i;
struct pointerblock *tmp=taghead->next;
- for(i=0;i<tagindex;i++) {
+ for(i=0; i<tagindex; i++) {
struct ___TagDescriptor___ *tagd=taghead->ptrs[i];
struct ___Object___ *obj=tagd->flagptr;
struct ___TagDescriptor___ *copy=((struct ___TagDescriptor___**)tagd)[1];
int j;
int k=0;
struct ArrayObject *aonew;
-
+
/* Count live objects */
- for(j=0;j<ao->___cachedCode___;j++) {
+ for(j=0; j<ao->___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<ao->___cachedCode___;j++) {
+ for(j=0; j<ao->___cachedCode___; j++) {
struct ___Object___ * tobj=ARRAYGET(ao, struct ___Object___ *, j);
if (tobj->type==-1) {
struct ___Object___ * tobjcpy=((struct ___Object___**)tobj)[1];
}
}
aonew->___cachedCode___=k;
- for(;k<livecount;k++) {
+ for(; k<livecount; k++) {
ARRAYSET(aonew, struct ___Object___*, k, NULL);
}
} else {
to_heapptr=to_heapbase;
}
}
-
+
/* Do our collection */
collect(stackptr);
tmp=to_heaptop;
to_heaptop=curr_heaptop;
curr_heaptop=tmp;
-
+
tmp=to_heapptr;
curr_heapptr=to_heapptr+size;
curr_heapgcpoint=((char *) curr_heapbase)+GCPOINT(curr_heaptop-curr_heapbase);
to_heapptr=to_heapbase;
-
+
/* Not enough room :(, redo gc */
if (curr_heapptr>curr_heapgcpoint) {
#if defined(THREADS)||defined(DSTM)
#endif
return mygcmalloc(stackptr, size);
}
-
+
bzero(tmp, curr_heaptop-tmp);
#if defined(THREADS)||defined(DSTM)
pthread_mutex_unlock(&gclock);
if (type==-1) {
*copy_ptr=((void **)orig)[1];
return 0;
- } if (type<NUMCLASSES) {
+ }
+ if (type<NUMCLASSES) {
/* We have a normal object */
int size=classsize[type];
void *newobj=tomalloc(size);
#include <raw.h>
/*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
#ifndef MEMH
#define MEMH
-#include<stdlib.h>
+#include <stdlib.h>
#ifndef RAW
-#include<stdio.h>
+#include <stdio.h>
#endif
#ifdef BOEHM_GC
#include "structdefs.h"
#include <signal.h>
#include "mem.h"
-#include<fcntl.h>
-#include<errno.h>
-#include<signal.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <signal.h>
#ifndef RAW
-#include<stdio.h>
+#include <stdio.h>
#endif
//#include "option.h"
#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);
}
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)<instfailurechance) {
if (numfailures>0)
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
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);
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<VAR(___s___)->___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<VAR(___s___)->___count___; i++) {
+ short sc=((short *)(((char *)&chararray->___length___)+sizeof(int)))[i+offset];
+ putchar(sc);
+ }
#endif
}
strobj->___count___=length;
strobj->___offset___=0;
- for(i=0;i<length;i++) {
- ((short *)(((char *)& chararray->___length___)+sizeof(int)))[i]=(short)str[i]; }
+ for(i=0; i<length; i++) {
+ ((short *)(((char *)&chararray->___length___)+sizeof(int)))[i]=(short)str[i];
+ }
return strobj;
}
#include <sys/stat.h>
#endif
/*
-extern int injectfailures;
-extern float failurechance;
-*/
+ extern int injectfailures;
+ extern float failurechance;
+ */
extern int debugtask;
extern int instaccum;
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
#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];
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
/* 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
#endif
if(STARTUPCORE == corenum) {
- /* Create startup object */
- createstartupobject(argc, argv);
+ /* Create startup object */
+ createstartupobject(argc, argv);
}
#ifdef RAWDEBUG
raw_test_pass(0xee0a);
#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();
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<argc;i++) {
+ for(i=1; i<argc; i++) {
int length=strlen(argv[i]);
#ifdef PRECISE_GC
struct ___String___ *newstring=NewString(NULL, argv[i],length);
#else
struct ___String___ *newstring=NewString(argv[i],length);
#endif
- ((void **)(((char *)& stringarray->___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
int hashCodetpd(struct taskparamdescriptor *ftd) {
int hash=(int)ftd->task;
int i;
- for(i=0;i<ftd->numParameters;i++){
+ for(i=0; i<ftd->numParameters; i++){
hash^=(int)ftd->parameterArray[i];
}
return hash;
int i;
if (ftd1->task!=ftd2->task)
return 0;
- for(i=0;i<ftd1->numParameters;i++)
+ for(i=0; i<ftd1->numParameters; i++)
if(ftd1->parameterArray[i]!=ftd2->parameterArray[i])
return 0;
return 1;
#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 {
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);
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<ao->___cachedCode___;i++) {
+ for(i=0; i<ao->___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___<ao->___length___) {
#ifdef RAWDEBUG
- raw_test_pass(0xebba);
+ raw_test_pass(0xebba);
#endif
ARRAYSET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___, tagd);
ao->___cachedCode___++;
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<ao->___length___;i++) {
+ for(i=0; i<ao->___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
{
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) {
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___<ao->___length___) {
#ifdef RAWDEBUG
- raw_test_pass(0xb00b);
+ raw_test_pass(0xb00b);
#endif
ARRAYSET(ao, struct ___Object___*, ao->___cachedCode___++, obj);
} else {
struct ArrayObject * aonew=allocate_newarray(OBJECTARRAYTYPE,OBJECTARRAYINTERVAL);
#endif
aonew->___cachedCode___=ao->___cachedCode___+1;
- for(i=0;i<ao->___length___;i++) {
+ for(i=0; i<ao->___length___; i++) {
ARRAYSET(aonew, struct ___Object___*, i, ARRAYGET(ao, struct ___Object___*, i));
}
ARRAYSET(aonew, struct ___Object___ *, ao->___cachedCode___, obj);
#ifndef RAW
printf("ERROR 1 in tagclear\n");
#endif
- ;
+ ;
} else {
struct ArrayObject *ao=(struct ArrayObject *) tagptr;
int i;
- for(i=0;i<ao->___cachedCode___;i++) {
+ for(i=0; i<ao->___cachedCode___; i++) {
struct ___TagDescriptor___ * td=ARRAYGET(ao, struct ___TagDescriptor___ *, i);
if (td==tagd) {
ao->___cachedCode___--;
#ifndef RAW
printf("ERROR 2 in tagclear\n");
#endif
- ;
+ ;
}
- PROCESSCLEAR:
+PROCESSCLEAR:
{
struct ___Object___ *tagset=tagd->flagptr;
if (tagset->type!=OBJECTARRAYTYPE) {
#ifndef RAW
printf("ERROR 3 in tagclear\n");
#endif
- ;
+ ;
} else {
struct ArrayObject *ao=(struct ArrayObject *) tagset;
int i;
- for(i=0;i<ao->___cachedCode___;i++) {
+ for(i=0; i<ao->___cachedCode___; i++) {
struct ___Object___ * tobj=ARRAYGET(ao, struct ___Object___ *, i);
if (tobj==obj) {
ao->___cachedCode___--;
#endif
}
}
- ENDCLEAR:
+ENDCLEAR:
return;
}
-
+
/* This function allocates a new tag. */
#ifdef PRECISE_GC
struct ___TagDescriptor___ * allocate_tag(void *ptr, int index) {
v->type=TAGTYPE;
v->flag=index;
return v;
-}
+}
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) {
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);
}
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
}
#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;i<parameter->numbertags;i++) {
+ for(i=0; i<parameter->numbertags; 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;i<parameter->numbertags;i++) {
+ for(i=0; i<parameter->numbertags; i++) {
//slotid is parameter->tagarray[2*i];
int tagid=parameter->tagarray[2*i+1];
int j;
- for(j=0;j<ao->___cachedCode___;j++) {
+ for(j=0; j<ao->___cachedCode___; j++) {
if (tagid==ARRAYGET(ao, struct ___TagDescriptor___*, j)->flag)
goto foundtag;
}
goto nextloop;
- foundtag:
+foundtag:
;
}
}
}
-
+
/* Check flags */
- for(i=0;i<parameter->numberofterms;i++) {
+ for(i=0; i<parameter->numberofterms; 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
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;i<parameter->numbertags;i++) {
+ for(i=0; i<parameter->numbertags; 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;i<parameter->numbertags;i++) {
+ for(i=0; i<parameter->numbertags; i++) {
//slotid is parameter->tagarray[2*i];
int tagid=parameter->tagarray[2*i+1];
int j;
- for(j=0;j<ao->___cachedCode___;j++) {
+ for(j=0; j<ao->___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;i<parameter->numberofterms;i++) {
+ for(i=0; i<parameter->numberofterms; i++) {
int andmask=parameter->intarray[i*2];
int checkmask=parameter->intarray[i*2+1];
#ifdef RAWDEBUG
#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
// 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
}
// 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("<transStallMsg> 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("<transStallMsg> to %s index: %d, sendobjs: %d, receiveobjs: %d\n", path, newobj->flag, newobj->___cachedHash___, newobj->___cachedCode___);
+ RUNFREE(newobj);
+ return true;
+ }
#endif
}
// 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("<receiveObject> 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("<receiveObject> 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
// 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
}
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;j<numiterators;j++) {
+ for(j=0; j<numiterators; j++) {
toiReset(¶meter->iterators[j]);
}
/* Find initial state */
- for(j=0;j<numiterators;j++) {
- backtrackinit:
+ for(j=0; j<numiterators; j++) {
+backtrackinit:
if(toiHasNext(¶meter->iterators[j], taskpointerarray OPTARG(failed)))
toiNext(¶meter->iterators[j], taskpointerarray OPTARG(failed));
else if (j>0) {
}
}
-
+
while(1) {
/* Enqueue current state */
int launch = 0;
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; j<numiterators;j++) {
- backtrackinc:
+ for(j=numiterators-1; j<numiterators; j++) {
+backtrackinc:
if(toiHasNext(¶meter->iterators[j], taskpointerarray OPTARG(failed)))
toiNext(¶meter->iterators[j], taskpointerarray OPTARG(failed));
else if (j>0) {
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;j<numiterators;j++) {
+ for(j=0; j<numiterators; j++) {
toiReset(¶meter->iterators[j]);
}
/* Find initial state */
- for(j=0;j<numiterators;j++) {
- backtrackinit:
+ for(j=0; j<numiterators; j++) {
+backtrackinit:
if(toiHasNext(¶meter->iterators[j], taskpointerarray OPTARG(failed)))
toiNext(¶meter->iterators[j], taskpointerarray OPTARG(failed));
else if (j>0) {
return retval;
}
}
-
+
while(1) {
/* Enqueue current state */
int launch = 0;
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; j<numiterators;j++) {
- backtrackinc:
+ for(j=numiterators-1; j<numiterators; j++) {
+backtrackinc:
if(toiHasNext(¶meter->iterators[j], taskpointerarray OPTARG(failed)))
toiNext(¶meter->iterators[j], taskpointerarray OPTARG(failed));
else if (j>0) {
#endif
sigemptyset(&toclear);
sigaddset(&toclear, sig);
- sigprocmask(SIG_UNBLOCK, &toclear,NULL);
+ sigprocmask(SIG_UNBLOCK, &toclear,NULL);
longjmp(error_handler,1);
}
#endif
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 */
if (numselect>0) {
/* Process ready fd's */
int fd;
- for(fd=0;fd<maxreadfd;fd++) {
+ for(fd=0; fd<maxreadfd; fd++) {
if (FD_ISSET(fd, &tmpreadfds)) {
/* Set ready flag on object */
void * objptr;
// printf("Setting fd %d\n",fd);
if (RuntimeHashget(fdtoobject, fd,(int *) &objptr)) {
if(intflagorand(objptr,1,0xFFFFFFFF)) { /* Set the first flag to 1 */
- enqueueObject(objptr, NULL, 0);
- }
+ enqueueObject(objptr, NULL, 0);
+ }
}
}
}
int i;
currtpd=(struct taskparamdescriptor *) getfirstkey(activetasks);
genfreekey(activetasks, currtpd);
-
+
/* Check if this task has failed, allow a task that contains optional objects to fire */
/*if (gencontains(failedtasks, currtpd)) {
- // Free up task parameter descriptor
- RUNFREE(currtpd->parameterArray);
- 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;i<numparams;i++) {
+ for(i=0; i<numparams; i++) {
void * parameter=currtpd->parameterArray[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;
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;
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];
{
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;
#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;j<pd->numbertags;j++) {
+ for(j=0; j<pd->numbertags; 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(;i<numtotal;i++) {
+ for(; i<numtotal; i++) {
taskpointerarray[i+OFFSET]=currtpd->parameterArray[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
{
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
#endif
} else {
/*if (injectfailures) {
- if ((((double)random())/RAND_MAX)<failurechance) {
+ if ((((double)random())/RAND_MAX)<failurechance) {
printf("\nINJECTING TASK FAILURE to %s\n", currtpd->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:
#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
}
}
}
#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;i<pd->numbertags;i++) {
+
+ for(i=0; i<pd->numbertags; 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;
parameter->iterators[*iteratorcount].objectset=objectset;
statusarray[index]=1;
- for(i=0;i<pd->numbertags;i++) {
+ for(i=0; i<pd->numbertags; i++) {
int slotid=pd->tagarray[2*i];
int tagid=pd->tagarray[2*i+1];
if (statusarray[slotid+numparams]!=0) {
int i;
int numparams=task->numParameters;
int iteratorcount=0;
- for(i=0;i<MAXTASKPARAMS;i++) statusarray[i]=0;
+ for(i=0; i<MAXTASKPARAMS; i++) statusarray[i]=0;
statusarray[index]=1; /* Initial parameter */
/* Process tags for initial iterator */
-
- processtags(task->descriptorarray[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;i<numparams;i++) {
+ for(i=0; i<numparams; i++) {
if (statusarray[i]==0) {
struct parameterdescriptor *pd=task->descriptorarray[i];
int j;
- for(j=0;j<pd->numbertags;j++) {
+ for(j=0; j<pd->numbertags; j++) {
int slotid=pd->tagarray[2*j];
if(statusarray[slotid+numparams]!=0) {
processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
/* Next do objects w/ unbound tags*/
- for(i=0;i<numparams;i++) {
+ for(i=0; i<numparams; i++) {
if (statusarray[i]==0) {
struct parameterdescriptor *pd=task->descriptorarray[i];
if (pd->numbertags>0) {
/* Nothing with a tag enqueued */
- for(i=0;i<numparams;i++) {
+ for(i=0; i<numparams; i++) {
if (statusarray[i]==0) {
struct parameterdescriptor *pd=task->descriptorarray[i];
processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
}
}
- void printdebug() {
- int i;
- int j;
+void printdebug() {
+ int i;
+ int j;
#ifdef THREADSIMULATE
- int numofcore = pthread_getspecific(key);
- for(i=0;i<numtasks[numofcore];i++) {
- struct taskdescriptor * task=taskarray[numofcore][i];
+ int numofcore = pthread_getspecific(key);
+ for(i=0; i<numtasks[numofcore]; i++) {
+ struct taskdescriptor * task=taskarray[numofcore][i];
#else
#ifdef RAW
- if(corenum > NUMCORES - 1) {
- return;
- }
+ if(corenum > NUMCORES - 1) {
+ return;
+ }
#endif
- for(i=0;i<numtasks[corenum];i++) {
- struct taskdescriptor * task=taskarray[corenum][i];
+ for(i=0; i<numtasks[corenum]; i++) {
+ struct taskdescriptor * task=taskarray[corenum][i];
#endif
#ifndef RAW
- printf("%s\n", task->name);
+ printf("%s\n", task->name);
#endif
- for(j=0;j<task->numParameters;j++) {
- struct parameterdescriptor *param=task->descriptorarray[j];
- struct parameterwrapper *parameter=param->queue;
- struct ObjectHash * set=parameter->objectset;
- struct ObjectIterator objit;
+ for(j=0; j<task->numParameters; 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<ao->___cachedCode___;tagindex++) {
+ ;
+ } else {
+ int tagindex=0;
+ struct ArrayObject *ao=(struct ArrayObject *)tagptr;
+ for(; tagindex<ao->___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. */
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;i<numtasks[numofcore];i++) {
- struct taskdescriptor *task=taskarray[numofcore][i];
+ for(i=0; i<numtasks[numofcore]; i++) {
+ struct taskdescriptor *task=taskarray[numofcore][i];
#else
- for(i=0;i<numtasks[corenum];i++) {
+ for(i=0; i<numtasks[corenum]; i++) {
struct taskdescriptor * task=taskarray[corenum][i];
#endif
int j;
- /* Build objectsets */
- for(j=0;j<task->numParameters;j++) {
+ /* Build objectsets */
+ for(j=0; j<task->numParameters; 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;j<task->numParameters;j++) {
+ for(j=0; j<task->numParameters; j++) {
struct parameterdescriptor *param=task->descriptorarray[j];
struct parameterwrapper *parameter=param->queue;
builditerators(task, j, parameter);
}
- }
+ }
}
void toiReset(struct tagobjectiterator * it) {
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<ao->___cachedCode___;tagindex++) {
+ for(; tagindex<ao->___cachedCode___; tagindex++) {
struct ___TagDescriptor___ *td=ARRAYGET(ao, struct ___TagDescriptor___ *, tagindex);
if (td->flag==it->tagid) {
it->tagobjindex=tagindex; /* Found right type of tag */
return 0;
if (!ObjectHashcontainskey(it->objectset, (int) objptr))
return 0;
- for(i=1;i<it->numtags;i++) {
+ for(i=1; i<it->numtags; i++) {
struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]];
if (!containstag(objptr,tag2))
return 0;
struct ArrayObject *ao=(struct ArrayObject *) objptr;
int tagindex;
int i;
- for(tagindex=it->tagobjindex;tagindex<ao->___cachedCode___;tagindex++) {
+ for(tagindex=it->tagobjindex; tagindex<ao->___cachedCode___; tagindex++) {
struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, tagindex);
if (!ObjectHashcontainskey(it->objectset, (int) objptr))
continue;
- for(i=1;i<it->numtags;i++) {
+ for(i=1; i<it->numtags; i++) {
struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]];
if (!containstag(objptr,tag2))
goto nexttag;
}
it->tagobjindex=tagindex;
return 1;
- nexttag:
+nexttag:
;
}
it->tagobjindex=tagindex;
struct ___Object___ * objptr=tag->flagptr;
if (objptr->type==OBJECTARRAYTYPE) {
struct ArrayObject *ao=(struct ArrayObject *)objptr;
- for(j=0;j<ao->___cachedCode___;j++) {
+ for(j=0; j<ao->___cachedCode___; j++) {
if (ptr==ARRAYGET(ao, struct ___Object___*, j))
return 1;
}
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 */
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);
#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___);
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,' ');
#include "structdefs.h"
#include <signal.h>
#include "mem.h"
-#include<fcntl.h>
-#include<errno.h>
-#include<stdio.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <stdio.h>
#include "option.h"
#ifdef DSTM
#include "dstm.h"
if (injectinstructionfailures) {
if (numfailures==0)
return;
- instructioncount=failurecount;
+ instructioncount=failurecount;
instaccum+=failurecount;
if ((((double)random())/RAND_MAX)<instfailurechance) {
if (numfailures>0)
}
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<VAR(___s___)->___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<VAR(___s___)->___count___; i++) {
+ short sc=((short *)(((char *)&chararray->___length___)+sizeof(int)))[i+offset];
+ putchar(sc);
+ }
}
#ifdef DSTM
strobj->___count___=length;
strobj->___offset___=0;
- for(i=0;i<length;i++) {
- ((short *)(((char *)& chararray->___length___)+sizeof(int)))[i]=(short)str[i]; }
+ for(i=0; i<length; i++) {
+ ((short *)(((char *)&chararray->___length___)+sizeof(int)))[i]=(short)str[i];
+ }
return strobj;
}
#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
#ifdef MULTICORE
struct transObjInfo {
- void * objptr;
- int targetcore;
- int * queues;
- int length;
+ void * objptr;
+ int targetcore;
+ int * queues;
+ int length;
};
#endif
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);
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___);
#endif
#endif
-
+
if (rc<0) goto error;
#ifdef TASK
#endif
return 0;
-
- error:
+
+error:
close(___fd___);
return -1;
#endif
#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___);
}
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;
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
#endif
#endif
}
-
+
rc = bind(fd, (struct sockaddr *) &sin, sizeof(sin));
if (rc<0) goto error;
return fd;
- error:
+error:
close(fd);
#ifdef DEBUG
perror(NULL);
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___;
struct hostent *h;
struct ArrayObject * arraybytearray;
- for(i=0;i<length;i++) {
+ for(i=0; i<length; i++) {
str[i]=(((char *)&VAR(___hostname___)->___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<n;i++) {
+ for(i=0; i<n; i++) {
struct ArrayObject *bytearray;
#ifdef PRECISE_GC
{
(&bytearray->___length___)[1]=ha;
}
}
-
+
return arraybytearray;
#endif
}
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;
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
#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("");
}
#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
#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("");
}
/* listen */
- if (listen(fd, 5)<0) {
- close (fd);
+ if (listen(fd, 5)<0) {
+ close(fd);
#ifdef DEBUG
perror("");
printf("createSocket error #4\n");
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);
restartaftergc(tmp);
#endif
#endif
- if (newfd<0) {
+ if (newfd<0) {
#ifdef DEBUG
perror(NULL);
printf("acceptSocket error #1\n");
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;
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;
int length=VAR(___b___)->___length___;
char * charstr=malloc(length);
-
+
#if defined(THREADS)||defined(DSTM)
#ifdef PRECISE_GC
struct listitem *tmp=stopforgc((struct garbagelist *)___params___);
restartaftergc(tmp);
#endif
#endif
-
+
{
int i;
- for(i=0;i<byteread;i++) {
- (((char *)& VAR(___b___)->___length___)+sizeof(int))[i]=charstr[i];
+ for(i=0; i<byteread; i++) {
+ (((char *)&VAR(___b___)->___length___)+sizeof(int))[i]=charstr[i];
}
free(charstr);
}
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();
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<argc;i++) {
+ for(i=1; i<argc; i++) {
int length=strlen(argv[i]);
#ifdef PRECISE_GC
struct ___String___ *newstring=NewString(NULL, argv[i],length);
#else
struct ___String___ *newstring=NewString(argv[i],length);
#endif
- ((void **)(((char *)& stringarray->___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);
}
int hashCodetpd(struct taskparamdescriptor *ftd) {
int hash=(int)ftd->task;
int i;
- for(i=0;i<ftd->numParameters;i++){
+ for(i=0; i<ftd->numParameters; i++){
hash^=(int)ftd->parameterArray[i];
}
return hash;
int i;
if (ftd1->task!=ftd2->task)
return 0;
- for(i=0;i<ftd1->numParameters;i++)
+ for(i=0; i<ftd1->numParameters; i++)
if(ftd1->parameterArray[i]!=ftd2->parameterArray[i])
return 0;
#ifdef OPTIONAL
- for(i=0;i<ftd1->numParameters;i++) {
+ for(i=0; i<ftd1->numParameters; i++) {
if(ftd1->failed[i]!=ftd2->failed[i])
return 0;
}
/* Array Case */
int i;
struct ArrayObject *ao=(struct ArrayObject *) tagptr;
- for(i=0;i<ao->___cachedCode___;i++) {
+ for(i=0; i<ao->___cachedCode___; i++) {
struct ___TagDescriptor___ * td=ARRAYGET(ao, struct ___TagDescriptor___*, i);
if (td==tagd)
return;
struct ArrayObject * aonew=allocate_newarray(TAGARRAYTYPE,TAGARRAYINTERVAL+ao->___length___);
#endif
aonew->___cachedCode___=ao->___length___+1;
- for(i=0;i<ao->___length___;i++) {
+ for(i=0; i<ao->___length___; i++) {
ARRAYSET(aonew, struct ___TagDescriptor___*, i, ARRAYGET(ao, struct ___TagDescriptor___*, i));
}
ARRAYSET(aonew, struct ___TagDescriptor___ *, ao->___length___, tagd);
struct ArrayObject * aonew=allocate_newarray(OBJECTARRAYTYPE,OBJECTARRAYINTERVAL);
#endif
aonew->___cachedCode___=ao->___cachedCode___+1;
- for(i=0;i<ao->___length___;i++) {
+ for(i=0; i<ao->___length___; i++) {
ARRAYSET(aonew, struct ___Object___*, i, ARRAYGET(ao, struct ___Object___*, i));
}
ARRAYSET(aonew, struct ___Object___ *, ao->___cachedCode___, obj);
} else {
struct ArrayObject *ao=(struct ArrayObject *) tagptr;
int i;
- for(i=0;i<ao->___cachedCode___;i++) {
+ for(i=0; i<ao->___cachedCode___; i++) {
struct ___TagDescriptor___ * td=ARRAYGET(ao, struct ___TagDescriptor___ *, i);
if (td==tagd) {
ao->___cachedCode___--;
}
printf("ERROR 2 in tagclear\n");
}
- PROCESSCLEAR:
+PROCESSCLEAR:
{
struct ___Object___ *tagset=tagd->flagptr;
if (tagset->type!=OBJECTARRAYTYPE) {
} else {
struct ArrayObject *ao=(struct ArrayObject *) tagset;
int i;
- for(i=0;i<ao->___cachedCode___;i++) {
+ for(i=0; i<ao->___cachedCode___; i++) {
struct ___Object___ * tobj=ARRAYGET(ao, struct ___Object___ *, i);
if (tobj==obj) {
ao->___cachedCode___--;
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) {
v->type=TAGTYPE;
v->flag=index;
return v;
-}
+}
#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;i<obj->numfses;i++) {
+ for(i=0; i<obj->numfses; i++) {
int oldoffset;
counter=obj->fses[offset++];
oldoffset=offset;
- for(j=0;j<counter;j++) {
+ for(j=0; j<counter; j++) {
flag=obj->fses[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;i<obj->numfses;i++) {
+ for(i=0; i<obj->numfses; i++) {
int oldoffset;
counter=obj->fses[offset++];
oldoffset=offset;
- for(j=0;j<counter;j++) {
+ for(j=0; j<counter; j++) {
flag=obj->fses[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) {
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;
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;i<parameter->numbertags;i++) {
+ for(i=0; i<parameter->numbertags; 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;i<parameter->numbertags;i++) {
+ for(i=0; i<parameter->numbertags; i++) {
//slotid is parameter->tagarray[2*i];
int tagid=parameter->tagarray[2*i+1];
int j;
- for(j=0;j<ao->___cachedCode___;j++) {
+ for(j=0; j<ao->___cachedCode___; j++) {
if (tagid==ARRAYGET(ao, struct ___TagDescriptor___*, j)->flag)
goto foundtag;
}
goto nextloop;
- foundtag:
+foundtag:
;
}
}
}
-
+
/* Check flags */
- for(i=0;i<parameter->numberofterms;i++) {
+ for(i=0; i<parameter->numberofterms; i++) {
int andmask=parameter->intarray[i*2];
int checkmask=parameter->intarray[i*2+1];
if ((ptr->flag&andmask)==checkmask) {
break;
}
}
- nextloop:
+nextloop:
parameter=parameter->next;
}
ptr->flagptr=prevptr;
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)
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_counter<fswrapper->numtags;tag_counter++) {
+
+ if(ao->___length___!=fswrapper->numtags)
+ return 0; //we don't have the right number of tags
+ for(tag_counter=0; tag_counter<fswrapper->numtags; tag_counter++) {
int tagid=fswrapper->tags[tag_counter];
int j;
- for(j=0;j<ao->___cachedCode___;j++) {
+ for(j=0; j<ao->___cachedCode___; j++) {
if (tagid==ARRAYGET(ao, struct ___TagDescriptor___*, tag_counter)->flag)
return 1;
}
int getlength(int *flist, int len) {
int count=0;
int i;
- for(i=0;i<len;i++) {
+ for(i=0; i<len; i++) {
int size=flist[count];
count+=1+size;
}
int i,j;
int *mergedlist;
int offset=0;
- for(i=0;i<ftl->numflags;i++) {
+ for(i=0; i<ftl->numflags; i++) {
int len=ftl->flags[offset++];
int offsetmerge=0;
- for(j=0;j<ftlmerge->numflags;j++) {
+ for(j=0; j<ftlmerge->numflags; j++) {
int lenmerge=ftlmerge->flags[offsetmerge++];
length+=1+domerge(&ftl->flags[offset],len,&ftlmerge->flags[offsetmerge],lenmerge, NULL);
offsetmerge+=lenmerge;
offset+=len;
}
mergedlist=RUNMALLOC(sizeof(int)*length);
-
+
offset=0;
length=0;
- for(i=0;i<ftl->numflags;i++) {
+ for(i=0; i<ftl->numflags; i++) {
int len=ftl->flags[offset++];
int offsetmerge=0;
- for(j=0;j<ftlmerge->numflags;j++) {
+ for(j=0; j<ftlmerge->numflags; j++) {
int lenmerge=ftlmerge->flags[offsetmerge++];
int size=domerge(&ftl->flags[offset],len,&ftlmerge->flags[offsetmerge],lenmerge,&mergedlist[length+1]);
mergedlist[length]=size;
struct failedtasklist *searchftl=list;
while(searchftl!=NULL) {
if ((*andlist)->task==searchftl->task&&
- (*andlist)->index==searchftl->index) {
+ (*andlist)->index==searchftl->index) {
mergeitems(*andlist, searchftl);
break;
}
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 {
struct failedtasklist *list=NULL;
int i,h;
struct fsanalysiswrapper *fswrapper=NULL;
- for(h=0;h<classwrapper->numfsanalysiswrappers;h++) {
+ for(h=0; h<classwrapper->numfsanalysiswrappers; h++) {
struct fsanalysiswrapper * tmp=classwrapper->fsanalysiswrapperarray[h];
if (tmp->flags==flagstate&&checktags(currobj, tmp)) {
//we only match exactly here
}
if (fswrapper==NULL)
return list;
- for(i=0;i<fswrapper->numtaskfailures;i++) {
+ for(i=0; i<fswrapper->numtaskfailures; i++) {
int j;
struct taskfailure * taskfail=fswrapper->taskfailurearray[i];
if (taskfail->task==task&&taskfail->index==index) {
int *enterflags;
int numenterflags, offset;
struct parameterwrapper *pw;
- for(j=start;j<taskfail->numoptionaltaskdescriptors;j++) {
+ for(j=start; j<taskfail->numoptionaltaskdescriptors; j++) {
struct optionaltaskdescriptor *otd=taskfail->optionaltaskdescriptorarray[j];
if(currtask==NULL) {
currtask=otd->task;
enterflags=RUNMALLOC(totallength*sizeof(int));
numenterflags=j-start;
offset=0;
- for(start;start<j;start++) {
+ for(start; start<j; start++) {
struct optionaltaskdescriptor *otd=taskfail->optionaltaskdescriptorarray[start];
enterflags[offset++]=otd->numenterflags;
memcpy(&enterflags[offset], otd->enterflags, otd->numenterflags*sizeof(int));
int i,h;
int start=0;
struct fsanalysiswrapper *fswrapper=NULL;
- for(h=0;h<classwrapper->numfsanalysiswrappers;h++) {
+ for(h=0; h<classwrapper->numfsanalysiswrappers; h++) {
struct fsanalysiswrapper * tmp=classwrapper->fsanalysiswrapperarray[h];
if (tmp->flags==flagstate&&checktags(currobj, tmp)) {
//we only match exactly here
int *enterflags;
int numenterflags, offset;
struct parameterwrapper *pw;
- for(j=start;j<fswrapper->numoptionaltaskdescriptors;j++) {
+ for(j=start; j<fswrapper->numoptionaltaskdescriptors; j++) {
struct optionaltaskdescriptor *otd=fswrapper->optionaltaskdescriptorarray[j];
if(currtask==NULL) {
currtask=otd->task;
enterflags=RUNMALLOC(totallength*sizeof(int));
numenterflags=j-start;
offset=0;
- for(start;start<j;start++) {
+ for(start; start<j; start++) {
struct optionaltaskdescriptor *otd=fswrapper->optionaltaskdescriptorarray[start];
enterflags[offset++]=otd->numenterflags;
memcpy(&enterflags[offset], otd->enterflags, otd->numenterflags*sizeof(int));
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 */
int i,h;
struct fsanalysiswrapper *fswrapper=NULL;
- for(h=0;h<classwrapper->numfsanalysiswrappers;h++) {
+ for(h=0; h<classwrapper->numfsanalysiswrappers; h++) {
struct fsanalysiswrapper * tmp=classwrapper->fsanalysiswrapperarray[h];
if (tmp->flags==currobj->flag&&checktags(currobj, tmp)) {
//we only match exactly here
}
if(fswrapper==NULL) //nothing to do in this state
return;
- for(i=0;i<fswrapper->numtaskfailures;i++) {
+ for(i=0; i<fswrapper->numtaskfailures; i++) {
int j;
struct taskfailure * taskfail=fswrapper->taskfailurearray[i];
if (taskfail->task==task&&taskfail->index==index) {
int *enterflags;
int numenterflags, offset;
struct parameterwrapper *pw;
- for(j=start;j<taskfail->numoptionaltaskdescriptors;j++) {
+ for(j=start; j<taskfail->numoptionaltaskdescriptors; 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;start<j;start++) {
+ for(start; start<j; start++) {
struct optionaltaskdescriptor *otd=taskfail->optionaltaskdescriptorarray[start];
enterflags[offset++]=otd->numenterflags;
memcpy(&enterflags[offset], otd->enterflags, otd->numenterflags*sizeof(int));
/* Failed in failed state */
int i;
int offset=0;
- for(i=0;i<numfailedfses;i++) {
+ for(i=0; i<numfailedfses; i++) {
int numfses=failedfses[offset++];
int j;
struct failedtasklist *andlist=NULL;
- for(j=0;j<numfses;j++) {
+ for(j=0; j<numfses; j++) {
int flagstate=failedfses[offset++];
struct failedtasklist *currlist=processfailstate(classwrapper, task, index, currobj, flagstate);
if (andlist==NULL)
/* Failed in failed state */
int i;
int offset=0;
- for(i=0;i<currobj->numfses;i++) {
+ for(i=0; i<currobj->numfses; i++) {
int numfses=currobj->fses[offset++];
int j;
struct failedtasklist *andlist=NULL;
- for(j=0;j<numfses;j++) {
+ for(j=0; j<numfses; j++) {
int flagstate=currobj->fses[offset++];
struct failedtasklist *currlist=processnormfailstate(classwrapper, currobj, flagstate);
if (andlist==NULL)
enqueuelist(currobj, andlist);
}
}
-}
-
-
+}
+
+
#endif
-
+
int enqueuetasks(struct parameterwrapper *parameter, struct parameterwrapper *prevptr, struct ___Object___ *ptr, int * enterflags, int numenterflags) {
void * taskpointerarray[MAXTASKPARAMS];
#ifdef OPTIONAL
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;
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));
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
#endif
/* Reset iterators */
- for(j=0;j<numiterators;j++) {
+ for(j=0; j<numiterators; j++) {
toiReset(¶meter->iterators[j]);
}
/* Find initial state */
- for(j=0;j<numiterators;j++) {
- backtrackinit:
+ for(j=0; j<numiterators; j++) {
+backtrackinit:
if(toiHasNext(¶meter->iterators[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--;
}
}
-
+
while(1) {
/* Enqueue current state */
int launch = 0;
#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) {
if (numiterators==0)
return retval;
- for(j=numiterators-1; j<numiterators;j++) {
- backtrackinc:
+ for(j=numiterators-1; j<numiterators; j++) {
+backtrackinc:
if(toiHasNext(¶meter->iterators[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--;
}
return retval;
}
-
+
/* Handler for signals. The signals catch null pointer errors and
arithmatic errors. */
#endif
sigemptyset(&toclear);
sigaddset(&toclear, sig);
- sigprocmask(SIG_UNBLOCK, &toclear,NULL);
+ sigprocmask(SIG_UNBLOCK, &toclear,NULL);
longjmp(error_handler,1);
}
#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() {
int * fsesarray[MAXTASKPARAMS];
int * oldfsesarray[MAXTASKPARAMS];
int numfsesarray[MAXTASKPARAMS];
-#endif
+#endif
/* Set up signal handlers */
struct sigaction sig;
/* 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 */
if (numselect>0) {
/* Process ready fd's */
int fd;
- for(fd=0;fd<maxreadfd;fd++) {
+ for(fd=0; fd<maxreadfd; fd++) {
if (FD_ISSET(fd, &tmpreadfds)) {
/* Set ready flag on object */
void * objptr;
// printf("Setting fd %d\n",fd);
if (RuntimeHashget(fdtoobject, fd,(int *) &objptr)) {
if(intflagorand(objptr,1,0xFFFFFFFF)) { /* Set the first flag to 1 */
- enqueueObject(objptr);
- }
+ enqueueObject(objptr);
+ }
}
}
}
int i;
currtpd=(struct taskparamdescriptor *) getfirstkey(activetasks);
genfreekey(activetasks, currtpd);
-
+
/* Check if this task has failed, allow a task that contains optional objects to fire */
if (gencontains(failedtasks, currtpd)) {
// Free up task parameter descriptor
}
int numparams=currtpd->task->numParameters;
int numtotal=currtpd->task->numTotal;
-
+
/* Make sure that the parameters are still in the queues */
- for(i=0;i<numparams;i++) {
+ for(i=0; i<numparams; i++) {
void * parameter=currtpd->parameterArray[i];
struct parameterdescriptor * pd=currtpd->task->descriptorarray[i];
struct parameterwrapper *pw=(struct parameterwrapper *) pd->queue;
}
}
#endif
- parameterpresent:
+parameterpresent:
;
/* Check that object still has necessary tags */
- for(j=0;j<pd->numbertags;j++) {
+ for(j=0; j<pd->numbertags; j++) {
int slotid=pd->tagarray[2*j]+numparams;
struct ___TagDescriptor___ *tagd=currtpd->parameterArray[slotid];
if (!containstag(parameter, tagd)) {
goto newtask;
}
}
-
+
taskpointerarray[i+OFFSET]=parameter;
}
/* Copy the tags */
- for(;i<numtotal;i++) {
+ for(; i<numtotal; i++) {
taskpointerarray[i+OFFSET]=currtpd->parameterArray[i];
}
}
/* 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;i<numparams;i++) {
+ for(i=0; i<numparams; i++) {
oldfsesarray[i]=((struct ___Object___ *)taskpointerarray[i+OFFSET])->fses;
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;i<numparams;i++) {
+ for(i=0; i<numparams; i++) {
//free old fses
if(oldfsesarray[i]!=NULL)
RUNFREE(oldfsesarray[i]);
}
#endif
-
+
freeRuntimeHash(forward);
freeRuntimeHash(reverse);
freemalloc();
}
}
}
-
+
/* 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;i<pd->numbertags;i++) {
+
+ for(i=0; i<pd->numbertags; 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;
parameter->iterators[*iteratorcount].objectset=objectset;
statusarray[index]=1;
- for(i=0;i<pd->numbertags;i++) {
+ for(i=0; i<pd->numbertags; i++) {
int slotid=pd->tagarray[2*i];
int tagid=pd->tagarray[2*i+1];
if (statusarray[slotid+numparams]!=0) {
int i;
int numparams=task->numParameters;
int iteratorcount=0;
- for(i=0;i<MAXTASKPARAMS;i++) statusarray[i]=0;
+ for(i=0; i<MAXTASKPARAMS; i++) statusarray[i]=0;
statusarray[index]=1; /* Initial parameter */
/* Process tags for initial iterator */
-
- processtags(task->descriptorarray[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;i<numparams;i++) {
+ for(i=0; i<numparams; i++) {
if (statusarray[i]==0) {
struct parameterdescriptor *pd=task->descriptorarray[i];
int j;
- for(j=0;j<pd->numbertags;j++) {
+ for(j=0; j<pd->numbertags; j++) {
int slotid=pd->tagarray[2*j];
if(statusarray[slotid+numparams]!=0) {
processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
/* Next do objects w/ unbound tags*/
- for(i=0;i<numparams;i++) {
+ for(i=0; i<numparams; i++) {
if (statusarray[i]==0) {
struct parameterdescriptor *pd=task->descriptorarray[i];
if (pd->numbertags>0) {
/* Nothing with a tag enqueued */
- for(i=0;i<numparams;i++) {
+ for(i=0; i<numparams; i++) {
if (statusarray[i]==0) {
struct parameterdescriptor *pd=task->descriptorarray[i];
processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
}
}
- void printdebug() {
- int i;
- int j;
- for(i=0;i<numtasks;i++) {
- struct taskdescriptor * task=taskarray[i];
- printf("%s\n", task->name);
- for(j=0;j<task->numParameters;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; i<numtasks; i++) {
+ struct taskdescriptor * task=taskarray[i];
+ printf("%s\n", task->name);
+ for(j=0; j<task->numParameters; 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<ao->___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<ao->___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;i<numtasks;i++) {
- struct taskdescriptor * task=taskarray[i];
+ for(i=0; i<numtasks; i++) {
+ struct taskdescriptor * task=taskarray[i];
int j;
- for(j=0;j<task->numParameters;j++) {
+ for(j=0; j<task->numParameters; j++) {
struct parameterdescriptor *param=task->descriptorarray[j];
struct parameterwrapper * parameter=RUNMALLOC(sizeof(struct parameterwrapper));
struct parameterwrapper ** ptr=&objectqueues[param->type];
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);
}
/* Build iterators for parameters */
- for(j=0;j<task->numParameters;j++) {
+ for(j=0; j<task->numParameters; j++) {
struct parameterdescriptor *param=task->descriptorarray[j];
struct parameterwrapper *parameter=param->queue;
builditerators(task, j, parameter);
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<ao->___cachedCode___;tagindex++) {
+ for(; tagindex<ao->___cachedCode___; tagindex++) {
struct ___TagDescriptor___ *td=ARRAYGET(ao, struct ___TagDescriptor___ *, tagindex);
if (td->flag==it->tagid) {
it->tagobjindex=tagindex; /* Found right type of tag */
return 0;
if (!ObjectHashcontainskey(it->objectset, (int) objptr))
return 0;
- for(i=1;i<it->numtags;i++) {
+ for(i=1; i<it->numtags; i++) {
struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]];
if (!containstag(objptr,tag2))
return 0;
}
return 1;
}
-#endif
+#endif
return 1;
} else {
struct ArrayObject *ao=(struct ArrayObject *) objptr;
}
}
#endif
- for(tagindex=it->tagobjindex;tagindex<ao->___cachedCode___;tagindex++) {
+ for(tagindex=it->tagobjindex; tagindex<ao->___cachedCode___; tagindex++) {
struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, tagindex);
if (!ObjectHashcontainskey(it->objectset, (int) objptr))
continue;
- for(i=1;i<it->numtags;i++) {
+ for(i=1; i<it->numtags; i++) {
struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]];
if (!containstag(objptr,tag2))
goto nexttag;
#endif
it->tagobjindex=tagindex;
return 1;
- nexttag:
+nexttag:
;
}
it->tagobjindex=tagindex;
struct ___Object___ * objptr=tag->flagptr;
if (objptr->type==OBJECTARRAYTYPE) {
struct ArrayObject *ao=(struct ArrayObject *)objptr;
- for(j=0;j<ao->___cachedCode___;j++) {
+ for(j=0; j<ao->___cachedCode___; j++) {
if (ptr==ARRAYGET(ao, struct ___Object___*, j))
return 1;
}
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 */
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;
} 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;
#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
goto transstart;
}
}
-#endif
+#endif
pthread_exit(NULL);
}
struct listitem *tmp=stopforgc((struct garbagelist *)___params___);
#endif
#endif
- usleep(___millis___);
+ usleep(___millis___);
#ifdef THREADS
#ifdef PRECISE_GC
restartaftergc(tmp);
#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;
}
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___) {
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)
#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];
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;
}
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);
/* 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;
+ }
}
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<depth&&!tovisit.isEmpty(); i++) {
+ 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);
+ newvisit.push(target);
+ }
+ }
+ }
+ }
+ tovisit=newvisit;
+ newvisit=new Stack();
+ }
+ }
+
+ public void setDotNodeParameters(String param) {
+ if (param == null) {
+ throw new NullPointerException();
+ }
+ if (dotnodeparams.length() > 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<depth&&!tovisit.isEmpty();i++) {
- 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);
- newvisit.push(target);
- }
- }
- }
- }
- tovisit=newvisit;
- newvisit=new Stack();
- }
- }
+ public void addEdge(Edge newedge) {
+ newedge.setSource(this);
+ edges.addElement(newedge);
+ GraphNode tonode=newedge.getTarget();
+ tonode.inedges.addElement(newedge);
+ }
- public void setDotNodeParameters(String param) {
- if (param == null) {
- throw new NullPointerException();
- }
- if (dotnodeparams.length() > 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<namers.size(); i++) {
+ Namer name=(Namer) namers.get(i);
+ String newlabel=name.nodeLabel(gn);
+ String newparams=name.nodeOption(gn);
+ if (!newlabel.equals("") && !label.equals("")) {
+ label+=", ";
+ }
+ if (!newparams.equals("")) {
+ dotnodeparams+=", " + name.nodeOption(gn);
+ }
+ label+=name.nodeLabel(gn);
+ }
- public static class DOTVisitor {
-
- java.io.PrintWriter output;
- int tokennumber;
- int color;
- Vector namers;
-
- 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);
- }
-
- Collection nodes;
-
-
- public static void visit(java.io.OutputStream output, Collection nodes, Vector namers) {
- DOTVisitor visitor = new DOTVisitor(output, namers);
- visitor.nodes = nodes;
- visitor.make();
- }
-
- 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();
- }
-
- 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");
- }
-
-
-
- private void traverse() {
- Set cycleset=GraphNode.findcycles(nodes);
-
- 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<namers.size();i++) {
- Namer name=(Namer) namers.get(i);
- String newlabel=name.nodeLabel(gn);
- String newparams=name.nodeOption(gn);
-
- if (!newlabel.equals("") && !label.equals("")) {
- label+=", ";
- }
- if (!newparams.equals("")) {
- dotnodeparams+=", " + name.nodeOption(gn);
- }
- label+=name.nodeLabel(gn);
+ 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).iterator(); nodeit.hasNext();) {
+ GraphNode node2=(GraphNode)nodeit.next();
+ String edgelabel = "";
+ String edgedotnodeparams="";
+
+ for(int i=0; i<namers.size(); i++) {
+ Namer name=(Namer) namers.get(i);
+ String newlabel=name.edgeLabel(edge);
+ String newoption=name.edgeOption(edge);
+ if (!newlabel.equals("")&& !edgelabel.equals(""))
+ edgelabel+=", ";
+ edgelabel+=newlabel;
+ if (!newoption.equals(""))
+ edgedotnodeparams+=", "+newoption;
}
- 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).iterator();nodeit.hasNext();) {
- GraphNode node2=(GraphNode)nodeit.next();
- String edgelabel = "";
- String edgedotnodeparams="";
-
- for(int i=0;i<namers.size();i++) {
- Namer name=(Namer) namers.get(i);
- String newlabel=name.edgeLabel(edge);
- String newoption=name.edgeOption(edge);
- if (!newlabel.equals("")&& ! edgelabel.equals(""))
- edgelabel+=", ";
- edgelabel+=newlabel;
- if (!newoption.equals(""))
- edgedotnodeparams+=", "+newoption;
- }
-
- output.println("\t" + gn.getLabel() + " -> " + 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;i<scc.numSCC();i++) {
- if (scc.hasCycle(i))
- cycleset.addAll(scc.getSCC(i));
+ }
+ return newset;
+ }
+
+ }
+
+ /** 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; i<scc.numSCC(); i++) {
+ if (scc.hasCycle(i))
+ cycleset.addAll(scc.getSCC(i));
+ }
+ 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;
+ }
+
+ /** Returns whether the graph has any cycles */
+ public boolean hasCycles() {
+ return !acyclic;
+ }
+
+ /** Returns the number of Strongly Connected Components */
+ public int numSCC() {
+ return numscc;
+ }
+
+ /** 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;
+ }
+ }
+
+ /**
+ * 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 */
}
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;
+ }
}
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);
+ }
}