Iterator methodit=cn.getMethods();
//Iterator through methods
while(methodit.hasNext()) {
- MethodDescriptor md=(MethodDescriptor)methodit.next();
- if (md.isStatic()||md.getReturnType()==null)
- continue;
- Stack<ClassDescriptor> possInterfaces=new Stack<ClassDescriptor>();
- ClassDescriptor tmpcd=cn;
- while(tmpcd!=null) {
- for(Iterator supit=tmpcd.getSuperInterfaces(); supit.hasNext(); ) {
- possInterfaces.add((ClassDescriptor)supit.next());
- }
- tmpcd=tmpcd.getSuperDesc();
- }
- while(!possInterfaces.isEmpty()) {
- ClassDescriptor IFdesc=possInterfaces.pop();
- for(Iterator supit=IFdesc.getSuperInterfaces(); supit.hasNext(); ) {
- possInterfaces.add((ClassDescriptor)supit.next());
- }
- Set possiblematches=IFdesc.getMethodTable().getSet(md.getSymbol());
- for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) {
- MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
- if (md.matches(matchmd)) {
- if (!mapVirtual2ImplementationSet.containsKey(matchmd))
- mapVirtual2ImplementationSet.put(matchmd,new HashSet());
- ((HashSet)mapVirtual2ImplementationSet.get(matchmd)).add(md);
- break;
- }
- }
- }
-
-
- ClassDescriptor superdesc=cn.getSuperDesc();
- if (superdesc!=null) {
- Set possiblematches=superdesc.getMethodTable().getSet(md.getSymbol());
- for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) {
- MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
- if (md.matches(matchmd)) {
- if (!mapVirtual2ImplementationSet.containsKey(matchmd))
- mapVirtual2ImplementationSet.put(matchmd,new HashSet());
- ((HashSet)mapVirtual2ImplementationSet.get(matchmd)).add(md);
- break;
- }
- }
- }
+ MethodDescriptor md=(MethodDescriptor)methodit.next();
+ if (md.isStatic()||md.getReturnType()==null)
+ continue;
+ Stack<ClassDescriptor> possInterfaces=new Stack<ClassDescriptor>();
+ ClassDescriptor tmpcd=cn;
+ while(tmpcd!=null) {
+ for(Iterator supit=tmpcd.getSuperInterfaces(); supit.hasNext(); ) {
+ possInterfaces.add((ClassDescriptor)supit.next());
+ }
+ tmpcd=tmpcd.getSuperDesc();
+ }
+ while(!possInterfaces.isEmpty()) {
+ ClassDescriptor IFdesc=possInterfaces.pop();
+ for(Iterator supit=IFdesc.getSuperInterfaces(); supit.hasNext(); ) {
+ possInterfaces.add((ClassDescriptor)supit.next());
+ }
+ Set possiblematches=IFdesc.getMethodTable().getSet(md.getSymbol());
+ for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) {
+ MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
+ if (md.matches(matchmd)) {
+ if (!mapVirtual2ImplementationSet.containsKey(matchmd))
+ mapVirtual2ImplementationSet.put(matchmd,new HashSet());
+ ((HashSet)mapVirtual2ImplementationSet.get(matchmd)).add(md);
+ break;
+ }
+ }
+ }
+
+
+ ClassDescriptor superdesc=cn.getSuperDesc();
+ if (superdesc!=null) {
+ Set possiblematches=superdesc.getMethodTable().getSet(md.getSymbol());
+ for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) {
+ MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
+ if (md.matches(matchmd)) {
+ if (!mapVirtual2ImplementationSet.containsKey(matchmd))
+ mapVirtual2ImplementationSet.put(matchmd,new HashSet());
+ ((HashSet)mapVirtual2ImplementationSet.get(matchmd)).add(md);
+ break;
+ }
+ }
+ }
}
}
}
Set s=(Set)mapVirtual2ImplementationSet.get(md);
if (s!=null)
for(Iterator it=s.iterator(); it.hasNext(); ) {
- MethodDescriptor md2=(MethodDescriptor)it.next();
- ns.addAll(getMethods(md2));
+ MethodDescriptor md2=(MethodDescriptor)it.next();
+ ns.addAll(getMethods(md2));
}
return ns;
}
Set s=(Set)mapCaller2CalleeSet.get(d);
if (s!=null)
for(Iterator it=s.iterator(); it.hasNext(); ) {
- MethodDescriptor md=(MethodDescriptor)it.next();
- if( !found.contains(md) ) {
- ns.addAll(getMoreMethodCalls(found, md));
- }
+ MethodDescriptor md=(MethodDescriptor)it.next();
+ if( !found.contains(md) ) {
+ ns.addAll(getMoreMethodCalls(found, md));
+ }
}
return ns;
}
Set s=(Set)mapCaller2CalleeSet.get(md);
if (s!=null) {
- for(Iterator it=s.iterator(); it.hasNext(); ) {
- MethodDescriptor md2=(MethodDescriptor)it.next();
- if( !callable.contains(md2) ) {
- callable.add(md2);
- tovisit.add(md2);
- }
- }
+ for(Iterator it=s.iterator(); it.hasNext(); ) {
+ MethodDescriptor md2=(MethodDescriptor)it.next();
+ if( !callable.contains(md2) ) {
+ callable.add(md2);
+ tovisit.add(md2);
+ }
+ }
}
}
return callable;
Set s = (Set) mapCaller2CalleeSet.get(md);
if (s != null) {
- for (Iterator it = s.iterator(); it.hasNext(); ) {
- MethodDescriptor md2 = (MethodDescriptor) it.next();
- if (!callable.contains(md2)) {
- callable.add(md2);
- if (!methodsContainingSESEs.contains(md2)) {
- // if current method has sese, do not need to go down
- tovisit.add(md2);
- }
- }
- }
+ for (Iterator it = s.iterator(); it.hasNext(); ) {
+ MethodDescriptor md2 = (MethodDescriptor) it.next();
+ if (!callable.contains(md2)) {
+ callable.add(md2);
+ if (!methodsContainingSESEs.contains(md2)) {
+ // if current method has sese, do not need to go down
+ tovisit.add(md2);
+ }
+ }
+ }
}
}
// callable.retainAll(methodsContainingSESEs);
Iterator methodit=cn.getMethods();
//Iterator through methods
while(methodit.hasNext()) {
- MethodDescriptor md=(MethodDescriptor)methodit.next();
- analyzeMethod( (Object)md, state.getMethodFlat(md) );
+ MethodDescriptor md=(MethodDescriptor)methodit.next();
+ analyzeMethod( (Object)md, state.getMethodFlat(md) );
}
}
it=state.getTaskSymbolTable().getDescriptorsIterator();
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);
+ 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);
- }
+ 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);
+ }
}
}
}
HashSet implemSet = (HashSet) me.getValue();
if( !labeledInDot.contains(virtual) ) {
- labeledInDot.add(virtual);
- bw.write(" "+virtual.getNum()+"[label=\""+virtual+"\"];\n");
+ labeledInDot.add(virtual);
+ bw.write(" "+virtual.getNum()+"[label=\""+virtual+"\"];\n");
}
Iterator implemItr = implemSet.iterator();
while( implemItr.hasNext() ) {
- Descriptor implem = (Descriptor) implemItr.next();
+ Descriptor implem = (Descriptor) implemItr.next();
- if( !labeledInDot.contains(implem) ) {
- labeledInDot.add(implem);
- bw.write(" "+implem.getNum()+"[label=\""+implem+"\"];\n");
- }
+ if( !labeledInDot.contains(implem) ) {
+ labeledInDot.add(implem);
+ bw.write(" "+implem.getNum()+"[label=\""+implem+"\"];\n");
+ }
- bw.write(" "+virtual.getNum()+"->"+implem.getNum()+";\n");
+ bw.write(" "+virtual.getNum()+"->"+implem.getNum()+";\n");
}
}
bw.write("}\n");
HashSet calleeSet = (HashSet) me.getValue();
if( !labeledInDot.contains(caller) ) {
- labeledInDot.add(caller);
- bw.write(" "+caller.getNum()+"[label=\"" +caller+"\"];\n");
+ labeledInDot.add(caller);
+ bw.write(" "+caller.getNum()+"[label=\"" +caller+"\"];\n");
}
Iterator calleeItr = calleeSet.iterator();
while( calleeItr.hasNext() ) {
- MethodDescriptor callee = (MethodDescriptor) calleeItr.next();
+ MethodDescriptor callee = (MethodDescriptor) calleeItr.next();
- if( !labeledInDot.contains(callee) ) {
- labeledInDot.add(callee);
- bw.write(" "+callee.getNum()+"[label=\""+callee+"\"];\n");
- }
+ if( !labeledInDot.contains(callee) ) {
+ labeledInDot.add(callee);
+ bw.write(" "+callee.getNum()+"[label=\""+callee+"\"];\n");
+ }
- bw.write(" "+caller.getNum()+"->"+callee.getNum()+";\n");
+ bw.write(" "+caller.getNum()+"->"+callee.getNum()+";\n");
}
}
bw.write("}\n");
HashSet callerSet = (HashSet) me.getValue();
if( !labeledInDot.contains(callee) ) {
- labeledInDot.add(callee);
- bw.write(" "+callee.getNum()+"[label=\""+callee+"\"];\n");
+ labeledInDot.add(callee);
+ bw.write(" "+callee.getNum()+"[label=\""+callee+"\"];\n");
}
Iterator callerItr = callerSet.iterator();
while( callerItr.hasNext() ) {
- Descriptor caller = (Descriptor) callerItr.next();
+ Descriptor caller = (Descriptor) callerItr.next();
- if( !labeledInDot.contains(caller) ) {
- labeledInDot.add(caller);
- bw.write(" "+caller.getNum()+"[label=\""+caller+"\"];\n");
- }
+ if( !labeledInDot.contains(caller) ) {
+ labeledInDot.add(caller);
+ bw.write(" "+caller.getNum()+"[label=\""+caller+"\"];\n");
+ }
- bw.write(" "+caller.getNum()+"->"+callee.getNum()+";\n");
+ bw.write(" "+caller.getNum()+"->"+callee.getNum()+";\n");
}
}
bw.write("}\n");
Iterator methodit=cn.getMethods();
//Iterator through methods
while(methodit.hasNext()) {
- MethodDescriptor md=(MethodDescriptor)methodit.next();
- if (md.isStaticBlock()) {
- tovisit.add(md);
- discovered.add(md);
- }
+ MethodDescriptor md=(MethodDescriptor)methodit.next();
+ if (md.isStaticBlock()) {
+ tovisit.add(md);
+ discovered.add(md);
+ }
}
}
tovisit.remove(md);
FlatMethod fm=state.getMethodFlat(md);
if (fm==null)
- continue;
+ continue;
analyzeMethod(md, fm);
for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator(); fnit.hasNext(); ) {
- FlatNode fn=fnit.next();
- if (fn.kind()==FKind.FlatCall) {
- FlatCall fcall=(FlatCall)fn;
- Set callees=fcall.getThis()==null?getMethods(fcall.getMethod()):getMethods(fcall.getMethod(),fcall.getThis().getType());
+ FlatNode fn=fnit.next();
+ if (fn.kind()==FKind.FlatCall) {
+ FlatCall fcall=(FlatCall)fn;
+ Set callees=fcall.getThis()==null?getMethods(fcall.getMethod()):getMethods(fcall.getMethod(),fcall.getThis().getType());
- if (fcall.getThis()!=null) {
- MethodDescriptor methodd=fcall.getMethod();
+ if (fcall.getThis()!=null) {
+ MethodDescriptor methodd=fcall.getMethod();
- if (methodd.getClassDesc()==tu.getClass(TypeUtil.ThreadClass)&&
- methodd.getSymbol().equals("start")&&methodd.numParameters()==0&&!methodd.getModifiers().isStatic()) {
- //Have call to start
- HashSet ns=new HashSet();
- ns.addAll(callees);
- ns.addAll(getMethods(tu.getRun(), fcall.getThis().getType()));
- ns.addAll(getMethods(tu.getStaticStart(), fcall.getThis().getType()));
- callees=ns;
- }
- }
+ if (methodd.getClassDesc()==tu.getClass(TypeUtil.ThreadClass)&&
+ methodd.getSymbol().equals("start")&&methodd.numParameters()==0&&!methodd.getModifiers().isStatic()) {
+ //Have call to start
+ HashSet ns=new HashSet();
+ ns.addAll(callees);
+ ns.addAll(getMethods(tu.getRun(), fcall.getThis().getType()));
+ ns.addAll(getMethods(tu.getStaticStart(), fcall.getThis().getType()));
+ callees=ns;
+ }
+ }
- for(Iterator mdit=callees.iterator(); mdit.hasNext(); ) {
- MethodDescriptor callee=(MethodDescriptor)mdit.next();
- if (!discovered.contains(callee)) {
- discovered.add(callee);
- tovisit.add(callee);
- }
- }
- }
+ for(Iterator mdit=callees.iterator(); mdit.hasNext(); ) {
+ MethodDescriptor callee=(MethodDescriptor)mdit.next();
+ if (!discovered.contains(callee)) {
+ discovered.add(callee);
+ tovisit.add(callee);
+ }
+ }
+ }
}
}
}
for( int i = 0; i < allocationDepth - 1; ++i ) {
if( id.equals(ithOldest.get(i) ) ) {
- return AGE_in_I;
+ return AGE_in_I;
}
}
public Integer getAge(Integer id) {
for( int i = 0; i < allocationDepth; ++i ) {
if( id.equals(ithOldest.get(i) ) ) {
- return new Integer(i);
+ return new Integer(i);
}
}
for( int i = 0; i < allocationDepth - 1; ++i ) {
if( id.equals(getIthOldestShadow(i) ) ) {
- return SHADOWAGE_in_I;
+ return SHADOWAGE_in_I;
}
}
public Integer getShadowAge(Integer id) {
for( int i = 0; i < allocationDepth - 1; ++i ) {
if( id.equals(getIthOldestShadow(i) ) ) {
- return new Integer(-i);
+ return new Integer(-i);
}
}
Iterator<TempDescriptor> varItr = var2smfe.keySet().iterator();
while( varItr.hasNext() ) {
- TempDescriptor var = varItr.next();
+ TempDescriptor var = varItr.next();
- StateMachineForEffects smfe = var2smfe.get(var);
+ StateMachineForEffects smfe = var2smfe.get(var);
- smfe.writeAsDOT(prefix+"statemachine_"+fn.toString()+var.toString() );
+ smfe.writeAsDOT(prefix+"statemachine_"+fn.toString()+var.toString() );
}
}
}
if( hasHash ) {
if( oldHash != hash ) {
- throw new Error("A CANONICAL HASH CHANGED");
+ throw new Error("A CANONICAL HASH CHANGED");
}
} else {
hasHash = true;
rt1.isOutOfContext()
);
if( rt2 != null ) {
- out.reachTuples.add(unionUpArity(rt1, rt2) );
+ out.reachTuples.add(unionUpArity(rt1, rt2) );
} else {
- out.reachTuples.add(rt1);
+ out.reachTuples.add(rt1);
}
}
rt2.isOutOfContext()
);
if( rt1 == null ) {
- out.reachTuples.add(rt2);
+ out.reachTuples.add(rt2);
}
}
if( age == AllocSite.AGE_notInThisSite ||
rt.isOutOfContext()
) {
- out.reachTuples.add(rt);
+ out.reachTuples.add(rt);
} else if( age == AllocSite.AGE_summary ) {
- // remember the summary tuple, but don't add it
- // we may combine it with the oldest tuple
- rtSummary = rt;
+ // remember the summary tuple, but don't add it
+ // we may combine it with the oldest tuple
+ rtSummary = rt;
} else if( age == AllocSite.AGE_oldest ) {
- // found an oldest hrnID, again just remember
- // for later
- rtOldest = rt;
+ // found an oldest hrnID, again just remember
+ // for later
+ rtOldest = rt;
} else {
- assert age == AllocSite.AGE_in_I;
+ assert age == AllocSite.AGE_in_I;
- Integer I = as.getAge(hrnID);
- assert I != null;
+ Integer I = as.getAge(hrnID);
+ assert I != null;
- // otherwise, we change this hrnID to the
- // next older hrnID
- Integer hrnIDToChangeTo = as.getIthOldest(I + 1);
- ReachTuple rtAged =
- Canonical.changeHrnIDTo(rt, hrnIDToChangeTo);
- out.reachTuples.add(rtAged);
+ // otherwise, we change this hrnID to the
+ // next older hrnID
+ Integer hrnIDToChangeTo = as.getIthOldest(I + 1);
+ ReachTuple rtAged =
+ Canonical.changeHrnIDTo(rt, hrnIDToChangeTo);
+ out.reachTuples.add(rtAged);
}
}
ReachState state2 = rs2.containsIgnorePreds(state1);
if( state2 != null ) {
- out.reachStates.add(ReachState.factory(state1.reachTuples,
- Canonical.join(state1.preds,
- state2.preds
- )
- ) );
+ out.reachStates.add(ReachState.factory(state1.reachTuples,
+ Canonical.join(state1.preds,
+ state2.preds
+ )
+ ) );
} else {
- out.reachStates.add(state1);
+ out.reachStates.add(state1);
}
}
ReachState state1 = rs1.containsIgnorePreds(state2);
if( state1 == null ) {
- out.reachStates.add(state2);
+ out.reachStates.add(state2);
}
}
ReachState state1 = (ReachState) itr.next();
ReachState state2 = rs2.containsIgnorePreds(state1);
if( state2 != null ) {
- // prefer the predicates on state1, an overapproximation
- // of state1 preds AND state2 preds
- out.reachStates.add(state1);
+ // prefer the predicates on state1, an overapproximation
+ // of state1 preds AND state2 preds
+ out.reachStates.add(state1);
}
}
Iterator<ChangeTuple> ctItr = cs.iterator();
while( ctItr.hasNext() ) {
- ChangeTuple ct = ctItr.next();
-
- if( stateOrig.equalsIgnorePreds(ct.getStateToMatch() ) ) {
- // use the new state, but the original predicates
- ReachState stateNew =
- ReachState.factory(ct.getStateToAdd().reachTuples,
- stateOrig.preds
- );
- out.reachStates.add(stateNew);
- changeFound = true;
- }
+ ChangeTuple ct = ctItr.next();
+
+ if( stateOrig.equalsIgnorePreds(ct.getStateToMatch() ) ) {
+ // use the new state, but the original predicates
+ ReachState stateNew =
+ ReachState.factory(ct.getStateToAdd().reachTuples,
+ stateOrig.preds
+ );
+ out.reachStates.add(stateNew);
+ changeFound = true;
+ }
}
if( keepSourceState || !changeFound ) {
- out.reachStates.add(stateOrig);
+ out.reachStates.add(stateOrig);
}
}
Iterator<ReachState> itrR = rsR.iterator();
while( itrR.hasNext() ) {
- ReachState r = itrR.next();
-
- ReachState theUnion = ReachState.factory();
-
- Iterator<ReachTuple> itrRelement = r.iterator();
- while( itrRelement.hasNext() ) {
- ReachTuple rtR = itrRelement.next();
- ReachTuple rtO = o.containsHrnID(rtR.getHrnID(),
- rtR.isOutOfContext()
- );
- if( rtO != null ) {
- theUnion = Canonical.add(theUnion,
- Canonical.unionUpArity(rtR,
- rtO
- )
- );
- } else {
- theUnion = Canonical.add(theUnion,
- rtR
- );
- }
- }
-
- Iterator<ReachTuple> itrOelement = o.iterator();
- while( itrOelement.hasNext() ) {
- ReachTuple rtO = itrOelement.next();
- ReachTuple rtR = theUnion.containsHrnID(rtO.getHrnID(),
- rtO.isOutOfContext()
- );
- if( rtR == null ) {
- theUnion = Canonical.add(theUnion,
- rtO
- );
- }
- }
-
- if( !theUnion.isEmpty() ) {
- out =
- Canonical.union(out,
- ChangeSet.factory(
- ChangeTuple.factory(o, theUnion)
- )
- );
- }
+ ReachState r = itrR.next();
+
+ ReachState theUnion = ReachState.factory();
+
+ Iterator<ReachTuple> itrRelement = r.iterator();
+ while( itrRelement.hasNext() ) {
+ ReachTuple rtR = itrRelement.next();
+ ReachTuple rtO = o.containsHrnID(rtR.getHrnID(),
+ rtR.isOutOfContext()
+ );
+ if( rtO != null ) {
+ theUnion = Canonical.add(theUnion,
+ Canonical.unionUpArity(rtR,
+ rtO
+ )
+ );
+ } else {
+ theUnion = Canonical.add(theUnion,
+ rtR
+ );
+ }
+ }
+
+ Iterator<ReachTuple> itrOelement = o.iterator();
+ while( itrOelement.hasNext() ) {
+ ReachTuple rtO = itrOelement.next();
+ ReachTuple rtR = theUnion.containsHrnID(rtO.getHrnID(),
+ rtO.isOutOfContext()
+ );
+ if( rtR == null ) {
+ theUnion = Canonical.add(theUnion,
+ rtO
+ );
+ }
+ }
+
+ if( !theUnion.isEmpty() ) {
+ out =
+ Canonical.union(out,
+ ChangeSet.factory(
+ ChangeTuple.factory(o, theUnion)
+ )
+ );
+ }
}
}
Iterator<ReachState> itrP = rsP.iterator();
while( itrP.hasNext() && !subsetExists ) {
- ReachState stateP = itrP.next();
+ ReachState stateP = itrP.next();
- if( stateP.isSubset(stateO) ) {
- subsetExists = true;
- }
+ if( stateP.isSubset(stateO) ) {
+ subsetExists = true;
+ }
}
if( subsetExists ) {
- out.reachStates.add(stateO);
+ out.reachStates.add(stateO);
}
}
int age = as.getAgeCategory(rt.getHrnID() );
if( age == AllocSite.AGE_notInThisSite ) {
- // things not from the site just go back in
- baseState = Canonical.addUpArity(baseState, rt);
+ // things not from the site just go back in
+ baseState = Canonical.addUpArity(baseState, rt);
} else if( age == AllocSite.AGE_summary ) {
- if( rt.isOutOfContext() ) {
- // if its out-of-context, we only deal here with the ZERO-OR-MORE
- // arity, if ARITY-ONE we'll branch the base state after the loop
- if( rt.getArity() == ReachTuple.ARITY_ZEROORMORE ) {
- // add two overly conservative symbols to reach state (PUNTING)
-
- baseState = Canonical.addUpArity(baseState,
- ReachTuple.factory(as.getSummary(),
- true, // multi
- ReachTuple.ARITY_ZEROORMORE,
- false // out-of-context
- )
- );
-
- baseState = Canonical.addUpArity(baseState,
- ReachTuple.factory(as.getSummary(),
- true, // multi
- ReachTuple.ARITY_ZEROORMORE,
- true // out-of-context
- )
- );
- } else {
- assert rt.getArity() == ReachTuple.ARITY_ONE;
- found2Sooc = true;
- }
-
- } else {
- // the in-context just becomes shadow
- baseState = Canonical.addUpArity(baseState,
- ReachTuple.factory(as.getSummaryShadow(),
- true, // multi
- rt.getArity(),
- false // out-of-context
- )
- );
- }
+ if( rt.isOutOfContext() ) {
+ // if its out-of-context, we only deal here with the ZERO-OR-MORE
+ // arity, if ARITY-ONE we'll branch the base state after the loop
+ if( rt.getArity() == ReachTuple.ARITY_ZEROORMORE ) {
+ // add two overly conservative symbols to reach state (PUNTING)
+
+ baseState = Canonical.addUpArity(baseState,
+ ReachTuple.factory(as.getSummary(),
+ true, // multi
+ ReachTuple.ARITY_ZEROORMORE,
+ false // out-of-context
+ )
+ );
+
+ baseState = Canonical.addUpArity(baseState,
+ ReachTuple.factory(as.getSummary(),
+ true, // multi
+ ReachTuple.ARITY_ZEROORMORE,
+ true // out-of-context
+ )
+ );
+ } else {
+ assert rt.getArity() == ReachTuple.ARITY_ONE;
+ found2Sooc = true;
+ }
+
+ } else {
+ // the in-context just becomes shadow
+ baseState = Canonical.addUpArity(baseState,
+ ReachTuple.factory(as.getSummaryShadow(),
+ true, // multi
+ rt.getArity(),
+ false // out-of-context
+ )
+ );
+ }
} else {
- // otherwise age is in range [0, k]
- Integer I = as.getAge(rt.getHrnID() );
- assert I != null;
- assert !rt.isMultiObject();
- assert rt.getArity() == ReachTuple.ARITY_ONE;
-
- if( rt.isOutOfContext() ) {
- // becomes the in-context version
- baseState = Canonical.addUpArity(baseState,
- ReachTuple.factory(rt.getHrnID(),
- false, // multi
- ReachTuple.ARITY_ONE,
- false // out-of-context
- )
- );
-
- } else {
- // otherwise the ith symbol becomes shadowed
- baseState = Canonical.addUpArity(baseState,
- ReachTuple.factory(-rt.getHrnID(),
- false, // multi
- ReachTuple.ARITY_ONE,
- false // out-of-context
- )
- );
- }
+ // otherwise age is in range [0, k]
+ Integer I = as.getAge(rt.getHrnID() );
+ assert I != null;
+ assert !rt.isMultiObject();
+ assert rt.getArity() == ReachTuple.ARITY_ONE;
+
+ if( rt.isOutOfContext() ) {
+ // becomes the in-context version
+ baseState = Canonical.addUpArity(baseState,
+ ReachTuple.factory(rt.getHrnID(),
+ false, // multi
+ ReachTuple.ARITY_ONE,
+ false // out-of-context
+ )
+ );
+
+ } else {
+ // otherwise the ith symbol becomes shadowed
+ baseState = Canonical.addUpArity(baseState,
+ ReachTuple.factory(-rt.getHrnID(),
+ false, // multi
+ ReachTuple.ARITY_ONE,
+ false // out-of-context
+ )
+ );
+ }
}
}
);
for( int i = 0; i < as.getAllocationDepth(); ++i ) {
- out = Canonical.add(out,
- Canonical.addUpArity(baseState,
- ReachTuple.factory(as.getIthOldest(i),
- false, // multi
- ReachTuple.ARITY_ONE,
- true // out-of-context
- )
- )
- );
+ out = Canonical.add(out,
+ Canonical.addUpArity(baseState,
+ ReachTuple.factory(as.getIthOldest(i),
+ false, // multi
+ ReachTuple.ARITY_ONE,
+ true // out-of-context
+ )
+ )
+ );
}
} else {
int age = as.getShadowAgeCategory(rt.getHrnID() );
if( age == AllocSite.SHADOWAGE_notInThisSite ) {
- // things not from the site just go back in
- out = Canonical.addUpArity(out, rt);
+ // things not from the site just go back in
+ out = Canonical.addUpArity(out, rt);
} else {
- assert !rt.isOutOfContext();
-
- // otherwise unshadow it
- out = Canonical.addUpArity(out,
- ReachTuple.factory(-rt.getHrnID(),
- rt.isMultiObject(),
- rt.getArity(),
- false
- )
- );
+ assert !rt.isOutOfContext();
+
+ // otherwise unshadow it
+ out = Canonical.addUpArity(out,
+ ReachTuple.factory(-rt.getHrnID(),
+ rt.isMultiObject(),
+ rt.getArity(),
+ false
+ )
+ );
}
}
Taint t2 = ts2.containsIgnorePreds(t1);
if( t2 != null ) {
- Taint tNew = new Taint(t1);
- tNew.preds = Canonical.join(t1.preds,
- t2.preds
- );
- tNew = (Taint) makeCanonical(tNew);
- out.taints.add(tNew);
+ Taint tNew = new Taint(t1);
+ tNew.preds = Canonical.join(t1.preds,
+ t2.preds
+ );
+ tNew = (Taint) makeCanonical(tNew);
+ out.taints.add(tNew);
} else {
- out.taints.add(t1);
+ out.taints.add(t1);
}
}
Taint t1 = ts1.containsIgnorePreds(t2);
if( t1 == null ) {
- out.taints.add(t2);
+ out.taints.add(t2);
}
}
Taint t2 = ts2.containsIgnorePreds(t1);
if( t2 != null ) {
- Taint tNew = new Taint(t1);
- tNew.preds = Canonical.join(t1.preds,
- t2.preds
- );
- tNew = (Taint) makeCanonical(tNew);
- out.taints.add(tNew);
+ Taint tNew = new Taint(t1);
+ tNew.preds = Canonical.join(t1.preds,
+ t2.preds
+ );
+ tNew = (Taint) makeCanonical(tNew);
+ out.taints.add(tNew);
} else {
- out.taints.add(t1);
+ out.taints.add(t1);
}
}
Taint t1 = ts1.containsIgnorePreds(t2);
if( t1 == null ) {
- out.taints.add(t2);
+ out.taints.add(t2);
}
}
!t.getSESE().equals(sese) ||
!t.getPreds().isEmpty()
) {
- out.taints.add(t);
+ out.taints.add(t);
}
}
// it is out of context so it should go through, too
if( t.getSESE() == null ||
!seseSet.contains(t)) {
- out.taints.add(t);
+ out.taints.add(t);
}
}
// unaffected, and if the taint has a non-empty predicate
// it is out of context so it should go through, too
if( t.getSESE()!=null && t.getSESE()!=sese) {
- out.taints.add(t);
+ out.taints.add(t);
}
}
// only take non-stall site taints onward
if( t.getStallSite() == null ) {
- out.taints.add(t);
+ out.taints.add(t);
}
}
AllocSite as = n.getAllocSite();
if (as == null) {
- out += " " + n.toString() + ",\n";
+ out += " " + n.toString() + ",\n";
} else {
- out += " " + n.toString() + ": " + as.toStringVerbose()
- + ",\n";
+ out += " " + n.toString() + ": " + as.toStringVerbose()
+ + ",\n";
}
}
TaskDescriptor td = (TaskDescriptor) taskItr.next();
if (!tabularOutput) {
- bw.write("\n---------" + td + "--------\n");
+ bw.write("\n---------" + td + "--------\n");
}
HashSet<AllocSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
FlatMethod fm = state.getMethodFlat(td);
for (int i = 0; i < fm.numParameters(); ++i) {
- // skip parameters with types that cannot reference
- // into the heap
- if( !shouldAnalysisTrack(fm.getParameter(i).getType() ) ) {
- continue;
- }
-
- // for the ith parameter check for sharing classes to all
- // higher numbered parameters
- for (int j = i + 1; j < fm.numParameters(); ++j) {
-
- // skip parameters with types that cannot reference
- // into the heap
- if( !shouldAnalysisTrack(fm.getParameter(j).getType() ) ) {
- continue;
- }
-
-
- common = hasPotentialSharing(td, i, j);
- if (!common.isEmpty()) {
- foundSomeSharing = true;
- ++numSharing;
- if (!tabularOutput) {
- bw.write("Potential sharing between parameters " + i
- + " and " + j + ".\n");
- bw.write(prettyPrintNodeSet(common) + "\n");
- }
- }
- }
-
- // for the ith parameter, check for sharing classes against
- // the set of allocation sites reachable from this
- // task context
- Iterator allocItr = allocSites.iterator();
- while (allocItr.hasNext()) {
- AllocSite as = (AllocSite) allocItr.next();
- common = hasPotentialSharing(td, i, as);
- if (!common.isEmpty()) {
- foundSomeSharing = true;
- ++numSharing;
- if (!tabularOutput) {
- bw.write("Potential sharing between parameter " + i
- + " and " + as.getFlatNew() + ".\n");
- bw.write(prettyPrintNodeSet(common) + "\n");
- }
- }
- }
+ // skip parameters with types that cannot reference
+ // into the heap
+ if( !shouldAnalysisTrack(fm.getParameter(i).getType() ) ) {
+ continue;
+ }
+
+ // for the ith parameter check for sharing classes to all
+ // higher numbered parameters
+ for (int j = i + 1; j < fm.numParameters(); ++j) {
+
+ // skip parameters with types that cannot reference
+ // into the heap
+ if( !shouldAnalysisTrack(fm.getParameter(j).getType() ) ) {
+ continue;
+ }
+
+
+ common = hasPotentialSharing(td, i, j);
+ if (!common.isEmpty()) {
+ foundSomeSharing = true;
+ ++numSharing;
+ if (!tabularOutput) {
+ bw.write("Potential sharing between parameters " + i
+ + " and " + j + ".\n");
+ bw.write(prettyPrintNodeSet(common) + "\n");
+ }
+ }
+ }
+
+ // for the ith parameter, check for sharing classes against
+ // the set of allocation sites reachable from this
+ // task context
+ Iterator allocItr = allocSites.iterator();
+ while (allocItr.hasNext()) {
+ AllocSite as = (AllocSite) allocItr.next();
+ common = hasPotentialSharing(td, i, as);
+ if (!common.isEmpty()) {
+ foundSomeSharing = true;
+ ++numSharing;
+ if (!tabularOutput) {
+ bw.write("Potential sharing between parameter " + i
+ + " and " + as.getFlatNew() + ".\n");
+ bw.write(prettyPrintNodeSet(common) + "\n");
+ }
+ }
+ }
}
// for each allocation site check for sharing classes with
HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
Iterator allocItr1 = allocSites.iterator();
while (allocItr1.hasNext()) {
- AllocSite as1 = (AllocSite) allocItr1.next();
+ AllocSite as1 = (AllocSite) allocItr1.next();
- Iterator allocItr2 = allocSites.iterator();
- while (allocItr2.hasNext()) {
- AllocSite as2 = (AllocSite) allocItr2.next();
+ Iterator allocItr2 = allocSites.iterator();
+ while (allocItr2.hasNext()) {
+ AllocSite as2 = (AllocSite) allocItr2.next();
- if (!outerChecked.contains(as2)) {
- common = hasPotentialSharing(td, as1, as2);
+ if (!outerChecked.contains(as2)) {
+ common = hasPotentialSharing(td, as1, as2);
- if (!common.isEmpty()) {
- foundSomeSharing = true;
- ++numSharing;
- if (!tabularOutput) {
- bw.write("Potential sharing between "
- + as1.getFlatNew() + " and "
- + as2.getFlatNew() + ".\n");
- bw.write(prettyPrintNodeSet(common) + "\n");
- }
- }
- }
- }
+ if (!common.isEmpty()) {
+ foundSomeSharing = true;
+ ++numSharing;
+ if (!tabularOutput) {
+ bw.write("Potential sharing between "
+ + as1.getFlatNew() + " and "
+ + as2.getFlatNew() + ".\n");
+ bw.write(prettyPrintNodeSet(common) + "\n");
+ }
+ }
+ }
+ }
- outerChecked.add(as1);
+ outerChecked.add(as1);
}
if (!foundSomeSharing) {
- if (!tabularOutput) {
- bw.write("No sharing between flagged objects in Task " + td
- + ".\n");
- }
+ if (!tabularOutput) {
+ bw.write("No sharing between flagged objects in Task " + td
+ + ".\n");
+ }
}
}
Iterator allocItr2 = allocSites.iterator();
while (allocItr2.hasNext()) {
- AllocSite as2 = (AllocSite) allocItr2.next();
+ AllocSite as2 = (AllocSite) allocItr2.next();
- if (!outerChecked.contains(as2)) {
- Set<HeapRegionNode> common = hasPotentialSharing(d,
- as1, as2);
+ if (!outerChecked.contains(as2)) {
+ Set<HeapRegionNode> common = hasPotentialSharing(d,
+ as1, as2);
- if (!common.isEmpty()) {
- foundSomeSharing = true;
- bw.write("Potential sharing between "
- + as1.getDisjointAnalysisId() + " and "
- + as2.getDisjointAnalysisId() + ".\n");
- bw.write(prettyPrintNodeSet(common) + "\n");
- ++numSharing;
- }
- }
+ if (!common.isEmpty()) {
+ foundSomeSharing = true;
+ bw.write("Potential sharing between "
+ + as1.getDisjointAnalysisId() + " and "
+ + as2.getDisjointAnalysisId() + ".\n");
+ bw.write(prettyPrintNodeSet(common) + "\n");
+ ++numSharing;
+ }
+ }
}
outerChecked.add(as1);
if( sitesToFlag != null ) {
treport = String.format("Disjoint reachability analysis flagged %d sites and took %.3f sec.", sitesToFlag.size(), dt);
if(sitesToFlag.size()>0) {
- treport+="\nFlagged sites:"+"\n"+sitesToFlag.toString();
+ treport+="\nFlagged sites:"+"\n"+sitesToFlag.toString();
}
} else {
treport = String.format("Disjoint reachability analysis took %.3f sec.", dt);
try {
if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
- writeFinalGraphs();
+ writeFinalGraphs();
}
if( state.DISJOINTWRITEIHMS && !suppressOutput ) {
- writeFinalIHMs();
+ writeFinalIHMs();
}
if( state.DISJOINTWRITEINITCONTEXTS && !suppressOutput ) {
- writeInitialContexts();
+ writeInitialContexts();
}
if( state.DISJOINTALIASFILE != null && !suppressOutput ) {
- if( state.TASK ) {
- writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
- } else {
- writeAllSharingJava(state.DISJOINTALIASFILE,
- treport,
- justtime,
- state.DISJOINTALIASTAB,
- state.lines
- );
- }
+ if( state.TASK ) {
+ writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
+ } else {
+ writeAllSharingJava(state.DISJOINTALIASFILE,
+ treport,
+ justtime,
+ state.DISJOINTALIASTAB,
+ state.lines
+ );
+ }
}
if( state.RCR ) {
- buildStateMachines.writeStateMachines();
+ buildStateMachines.writeStateMachines();
}
} catch( IOException e ) {
if( state.TASK ) {
if( !suppressOutput ) {
- System.out.println("Bamboo mode...");
+ System.out.println("Bamboo mode...");
}
Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
while( taskItr.hasNext() ) {
- TaskDescriptor td = (TaskDescriptor) taskItr.next();
- if( !descriptorsToAnalyze.contains(td) ) {
- // add all methods transitively reachable from the
- // tasks as well
- descriptorsToAnalyze.add(td);
- descriptorsToAnalyze.addAll(callGraph.getAllMethods(td) );
- }
+ TaskDescriptor td = (TaskDescriptor) taskItr.next();
+ if( !descriptorsToAnalyze.contains(td) ) {
+ // add all methods transitively reachable from the
+ // tasks as well
+ descriptorsToAnalyze.add(td);
+ descriptorsToAnalyze.addAll(callGraph.getAllMethods(td) );
+ }
}
} else {
if( !suppressOutput ) {
- System.out.println("Java mode...");
+ System.out.println("Java mode...");
}
// add all methods transitively reachable from the
// for the priority queue, give items at the head
// of the sorted list a low number (highest priority)
while( !sortedDescriptors.isEmpty() ) {
- Descriptor d = sortedDescriptors.removeFirst();
- mapDescriptorToPriority.put(d, new Integer(p) );
- descriptorsToVisitQ.add(new DescriptorQWrapper(p, d) );
- descriptorsToVisitSet.add(d);
- ++p;
+ Descriptor d = sortedDescriptors.removeFirst();
+ mapDescriptorToPriority.put(d, new Integer(p) );
+ descriptorsToVisitQ.add(new DescriptorQWrapper(p, d) );
+ descriptorsToVisitSet.add(d);
+ ++p;
}
} else if( state.DISJOINTDVISITSTACK ||
// if we're doing the stack scheme, just throw the root
// method or tasks on the stack
if( state.TASK ) {
- Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
- while( taskItr.hasNext() ) {
- TaskDescriptor td = (TaskDescriptor) taskItr.next();
- descriptorsToVisitStack.add(td);
- descriptorsToVisitSet.add(td);
- }
+ Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
+ while( taskItr.hasNext() ) {
+ TaskDescriptor td = (TaskDescriptor) taskItr.next();
+ descriptorsToVisitStack.add(td);
+ descriptorsToVisitSet.add(td);
+ }
} else {
- descriptorsToVisitStack.add(mdAnalysisEntry);
- descriptorsToVisitSet.add(mdAnalysisEntry);
+ descriptorsToVisitStack.add(mdAnalysisEntry);
+ descriptorsToVisitSet.add(mdAnalysisEntry);
}
} else {
if( state.DISJOINTDVISITSTACK ||
state.DISJOINTDVISITSTACKEESONTOP
) {
- d = descriptorsToVisitStack.pop();
+ d = descriptorsToVisitStack.pop();
} else if( state.DISJOINTDVISITPQUE ) {
- d = descriptorsToVisitQ.poll().getDescriptor();
+ d = descriptorsToVisitQ.poll().getDescriptor();
}
assert descriptorsToVisitSet.contains(d);
// that depend on this one to the "to visit" set.
if( !suppressOutput ) {
- System.out.println("Analyzing " + d);
+ System.out.println("Analyzing " + d);
}
if( state.DISJOINTDVISITSTACKEESONTOP ) {
- assert calleesToEnqueue.isEmpty();
+ assert calleesToEnqueue.isEmpty();
}
ReachGraph rg = analyzeMethod(d);
ReachGraph rgPrev = getPartial(d);
if( !rg.equals(rgPrev) ) {
- setPartial(d, rg);
+ setPartial(d, rg);
- if( state.DISJOINTDEBUGSCHEDULING ) {
- System.out.println(" complete graph changed, scheduling callers for analysis:");
- }
+ if( state.DISJOINTDEBUGSCHEDULING ) {
+ System.out.println(" complete graph changed, scheduling callers for analysis:");
+ }
- // results for d changed, so enqueue dependents
- // of d for further analysis
- Iterator<Descriptor> depsItr = getDependents(d).iterator();
- while( depsItr.hasNext() ) {
- Descriptor dNext = depsItr.next();
- enqueue(dNext);
+ // results for d changed, so enqueue dependents
+ // of d for further analysis
+ Iterator<Descriptor> depsItr = getDependents(d).iterator();
+ while( depsItr.hasNext() ) {
+ Descriptor dNext = depsItr.next();
+ enqueue(dNext);
- if( state.DISJOINTDEBUGSCHEDULING ) {
- System.out.println(" "+dNext);
- }
- }
+ if( state.DISJOINTDEBUGSCHEDULING ) {
+ System.out.println(" "+dNext);
+ }
+ }
}
// whether or not the method under analysis changed,
// the stack now (in other method-visiting modes they
// are already enqueued at this point
if( state.DISJOINTDVISITSTACKEESONTOP ) {
- Iterator<Descriptor> depsItr = calleesToEnqueue.iterator();
- while( depsItr.hasNext() ) {
- Descriptor dNext = depsItr.next();
- enqueue(dNext);
- }
- calleesToEnqueue.clear();
+ Iterator<Descriptor> depsItr = calleesToEnqueue.iterator();
+ while( depsItr.hasNext() ) {
+ Descriptor dNext = depsItr.next();
+ enqueue(dNext);
+ }
+ calleesToEnqueue.clear();
}
}
FlatNode fn;
if( determinismDesired ) {
- assert !flatNodesToVisitQ.isEmpty();
- fn = flatNodesToVisitQ.remove();
+ assert !flatNodesToVisitQ.isEmpty();
+ fn = flatNodesToVisitQ.remove();
} else {
- fn = flatNodesToVisit.iterator().next();
+ fn = flatNodesToVisit.iterator().next();
}
flatNodesToVisit.remove(fn);
ReachGraph rg = new ReachGraph();
TaskDescriptor taskDesc;
if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null) {
- if(mapDescriptorToReachGraph.containsKey(taskDesc)) {
- // retrieve existing reach graph if it is not first time
- rg=mapDescriptorToReachGraph.get(taskDesc);
- } else {
- // create initial reach graph for a task
- rg=createInitialTaskReachGraph((FlatMethod)fn);
- rg.globalSweep();
- mapDescriptorToReachGraph.put(taskDesc, rg);
- }
+ if(mapDescriptorToReachGraph.containsKey(taskDesc)) {
+ // retrieve existing reach graph if it is not first time
+ rg=mapDescriptorToReachGraph.get(taskDesc);
+ } else {
+ // create initial reach graph for a task
+ rg=createInitialTaskReachGraph((FlatMethod)fn);
+ rg.globalSweep();
+ mapDescriptorToReachGraph.put(taskDesc, rg);
+ }
}
// start by merging all node's parents' graphs
for( int i = 0; i < pm.numPrev(fn); ++i ) {
- FlatNode pn = pm.getPrev(fn,i);
- if( mapFlatNodeToReachGraph.containsKey(pn) ) {
- ReachGraph rgParent = mapFlatNodeToReachGraph.get(pn);
- rg.merge(rgParent);
- }
+ FlatNode pn = pm.getPrev(fn,i);
+ if( mapFlatNodeToReachGraph.containsKey(pn) ) {
+ ReachGraph rgParent = mapFlatNodeToReachGraph.get(pn);
+ rg.merge(rgParent);
+ }
}
if( takeDebugSnapshots &&
d.getSymbol().equals(descSymbolDebug)
) {
- debugSnapshot(rg, fn, true);
+ debugSnapshot(rg, fn, true);
}
if( takeDebugSnapshots &&
d.getSymbol().equals(descSymbolDebug)
) {
- debugSnapshot(rg, fn, false);
- ++snapNodeCounter;
+ debugSnapshot(rg, fn, false);
+ ++snapNodeCounter;
}
// with the update and enqueue the children
ReachGraph rgPrev = mapFlatNodeToReachGraph.get(fn);
if( !rg.equals(rgPrev) ) {
- mapFlatNodeToReachGraph.put(fn, rg);
+ mapFlatNodeToReachGraph.put(fn, rg);
- for( int i = 0; i < pm.numNext(fn); i++ ) {
- FlatNode nn = pm.getNext(fn, i);
+ for( int i = 0; i < pm.numNext(fn); i++ ) {
+ FlatNode nn = pm.getNext(fn, i);
- flatNodesToVisit.add(nn);
- if( determinismDesired ) {
- flatNodesToVisitQ.add(nn);
- }
- }
+ flatNodesToVisit.add(nn);
+ if( determinismDesired ) {
+ flatNodesToVisitQ.add(nn);
+ }
+ }
}
}
if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
stopAfterCapture
) {
- System.out.println("!!! Stopping analysis after debug snap captures. !!!");
- System.exit(0);
+ System.out.println("!!! Stopping analysis after debug snap captures. !!!");
+ System.exit(0);
}
}
Set entrySet = heapsFromCallers.entrySet();
Iterator itr = entrySet.iterator();
while( itr.hasNext() ) {
- Map.Entry me = (Map.Entry)itr.next();
- FlatCall fc = (FlatCall) me.getKey();
- ReachGraph rgContrib = (ReachGraph) me.getValue();
+ Map.Entry me = (Map.Entry)itr.next();
+ FlatCall fc = (FlatCall) me.getKey();
+ ReachGraph rgContrib = (ReachGraph) me.getValue();
- assert fc.getMethod().equals(d);
+ assert fc.getMethod().equals(d);
- rg.merge(rgContrib);
+ rg.merge(rgContrib);
}
// additionally, we are enforcing STRICT MONOTONICITY for the
case FKind.FlatOpNode:
FlatOpNode fon = (FlatOpNode) fn;
if( fon.getOp().getOp() == Operation.ASSIGN ) {
- lhs = fon.getDest();
- rhs = fon.getLeft();
+ lhs = fon.getDest();
+ rhs = fon.getLeft();
- // before transfer, do effects analysis support
- if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
- if(rblockRel.isPotentialStallSite(fn)) {
- // x gets status of y
+ // before transfer, do effects analysis support
+ if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
+ if(rblockRel.isPotentialStallSite(fn)) {
+ // x gets status of y
// if(!rg.isAccessible(rhs)){
- if(!accessible.isAccessible(fn, rhs)) {
- rg.makeInaccessible(lhs);
- }
- }
- }
+ if(!accessible.isAccessible(fn, rhs)) {
+ rg.makeInaccessible(lhs);
+ }
+ }
+ }
- // transfer func
- rg.assignTempXEqualToTempY(lhs, rhs);
+ // transfer func
+ rg.assignTempXEqualToTempY(lhs, rhs);
}
break;
// before transfer, do effects analysis support
if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
- if(rblockRel.isPotentialStallSite(fn)) {
- // x gets status of y
+ if(rblockRel.isPotentialStallSite(fn)) {
+ // x gets status of y
// if(!rg.isAccessible(rhs)){
- if(!accessible.isAccessible(fn,rhs)) {
- rg.makeInaccessible(lhs);
- }
- }
+ if(!accessible.isAccessible(fn,rhs)) {
+ rg.makeInaccessible(lhs);
+ }
+ }
}
// transfer func
// a stall-site taint
if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
- if(rblockRel.isPotentialStallSite(fn)) {
- // x=y.f, stall y if not accessible
- // contributes read effects on stall site of y
+ if(rblockRel.isPotentialStallSite(fn)) {
+ // x=y.f, stall y if not accessible
+ // contributes read effects on stall site of y
// if(!rg.isAccessible(rhs)) {
- if(!accessible.isAccessible(fn,rhs)) {
- rg.taintStallSite(fn, rhs);
- }
+ if(!accessible.isAccessible(fn,rhs)) {
+ rg.taintStallSite(fn, rhs);
+ }
- // after this, x and y are accessbile.
- rg.makeAccessible(lhs);
- rg.makeAccessible(rhs);
- }
+ // after this, x and y are accessbile.
+ rg.makeAccessible(lhs);
+ rg.makeAccessible(rhs);
+ }
}
if( shouldAnalysisTrack(fld.getType() ) ) {
- // transfer func
- rg.assignTempXEqualToTempYFieldF(lhs, rhs, fld, fn);
+ // transfer func
+ rg.assignTempXEqualToTempYFieldF(lhs, rhs, fld, fn);
}
// after transfer, use updated graph to
// do effects analysis
if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
- effectsAnalysis.analyzeFlatFieldNode(rg, rhs, fld, fn);
+ effectsAnalysis.analyzeFlatFieldNode(rg, rhs, fld, fn);
}
break;
// stall-site taints
if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
- if(rblockRel.isPotentialStallSite(fn)) {
- // x.y=f , stall x and y if they are not accessible
- // also contribute write effects on stall site of x
+ if(rblockRel.isPotentialStallSite(fn)) {
+ // x.y=f , stall x and y if they are not accessible
+ // also contribute write effects on stall site of x
// if(!rg.isAccessible(lhs)) {
- if(!accessible.isAccessible(fn,lhs)) {
- rg.taintStallSite(fn, lhs);
- }
+ if(!accessible.isAccessible(fn,lhs)) {
+ rg.taintStallSite(fn, lhs);
+ }
// if(!rg.isAccessible(rhs)) {
- if(!accessible.isAccessible(fn,rhs)) {
- rg.taintStallSite(fn, rhs);
- }
+ if(!accessible.isAccessible(fn,rhs)) {
+ rg.taintStallSite(fn, rhs);
+ }
- // accessible status update
- rg.makeAccessible(lhs);
- rg.makeAccessible(rhs);
- }
+ // accessible status update
+ rg.makeAccessible(lhs);
+ rg.makeAccessible(rhs);
+ }
}
if( shouldAnalysisTrack(fld.getType() ) ) {
- // transfer func
- strongUpdate = rg.assignTempXFieldFEqualToTempY(lhs, fld, rhs, fn);
+ // transfer func
+ strongUpdate = rg.assignTempXFieldFEqualToTempY(lhs, fld, rhs, fn);
}
// use transformed graph to do effects analysis
if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
- effectsAnalysis.analyzeFlatSetFieldNode(rg, lhs, fld, fn, strongUpdate);
+ effectsAnalysis.analyzeFlatSetFieldNode(rg, lhs, fld, fn, strongUpdate);
}
break;
// before transfer func, possibly inject
// stall-site taint
if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
- if(rblockRel.isPotentialStallSite(fn)) {
- // x=y.f, stall y if not accessible
- // contributes read effects on stall site of y
- // after this, x and y are accessbile.
+ if(rblockRel.isPotentialStallSite(fn)) {
+ // x=y.f, stall y if not accessible
+ // contributes read effects on stall site of y
+ // after this, x and y are accessbile.
// if(!rg.isAccessible(rhs)) {
- if(!accessible.isAccessible(fn,rhs)) {
- rg.taintStallSite(fn, rhs);
- }
+ if(!accessible.isAccessible(fn,rhs)) {
+ rg.taintStallSite(fn, rhs);
+ }
- rg.makeAccessible(lhs);
- rg.makeAccessible(rhs);
- }
+ rg.makeAccessible(lhs);
+ rg.makeAccessible(rhs);
+ }
}
if( shouldAnalysisTrack(lhs.getType() ) ) {
- // transfer func
- rg.assignTempXEqualToTempYFieldF(lhs, rhs, fdElement, fn);
+ // transfer func
+ rg.assignTempXEqualToTempYFieldF(lhs, rhs, fdElement, fn);
}
// use transformed graph to do effects analysis
if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
- effectsAnalysis.analyzeFlatFieldNode(rg, rhs, fdElement, fn);
+ effectsAnalysis.analyzeFlatFieldNode(rg, rhs, fdElement, fn);
}
break;
// stall-site taints
if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
- if(rblockRel.isPotentialStallSite(fn)) {
- // x.y=f , stall x and y if they are not accessible
- // also contribute write effects on stall site of x
+ if(rblockRel.isPotentialStallSite(fn)) {
+ // x.y=f , stall x and y if they are not accessible
+ // also contribute write effects on stall site of x
// if(!rg.isAccessible(lhs)) {
- if(!accessible.isAccessible(fn,lhs)) {
- rg.taintStallSite(fn, lhs);
- }
+ if(!accessible.isAccessible(fn,lhs)) {
+ rg.taintStallSite(fn, lhs);
+ }
// if(!rg.isAccessible(rhs)) {
- if(!accessible.isAccessible(fn,rhs)) {
- rg.taintStallSite(fn, rhs);
- }
+ if(!accessible.isAccessible(fn,rhs)) {
+ rg.taintStallSite(fn, rhs);
+ }
- // accessible status update
- rg.makeAccessible(lhs);
- rg.makeAccessible(rhs);
- }
+ // accessible status update
+ rg.makeAccessible(lhs);
+ rg.makeAccessible(rhs);
+ }
}
if( shouldAnalysisTrack(rhs.getType() ) ) {
- // transfer func, BUT
- // skip this node if it cannot create new reachability paths
- if( !arrayReferencees.doesNotCreateNewReaching(fsen) ) {
- rg.assignTempXFieldFEqualToTempY(lhs, fdElement, rhs, fn);
- }
+ // transfer func, BUT
+ // skip this node if it cannot create new reachability paths
+ if( !arrayReferencees.doesNotCreateNewReaching(fsen) ) {
+ rg.assignTempXFieldFEqualToTempY(lhs, fdElement, rhs, fn);
+ }
}
// use transformed graph to do effects analysis
if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
- effectsAnalysis.analyzeFlatSetFieldNode(rg, lhs, fdElement, fn,
- false);
+ effectsAnalysis.analyzeFlatSetFieldNode(rg, lhs, fdElement, fn,
+ false);
}
break;
FlatNew fnn = (FlatNew) fn;
lhs = fnn.getDst();
if( shouldAnalysisTrack(lhs.getType() ) ) {
- AllocSite as = getAllocSiteFromFlatNewPRIVATE(fnn);
+ AllocSite as = getAllocSiteFromFlatNewPRIVATE(fnn);
- // before transform, support effects analysis
- if (doEffectsAnalysis && fmContaining != fmAnalysisEntry) {
- if (rblockRel.isPotentialStallSite(fn)) {
- // after creating new object, lhs is accessible
- rg.makeAccessible(lhs);
- }
- }
+ // before transform, support effects analysis
+ if (doEffectsAnalysis && fmContaining != fmAnalysisEntry) {
+ if (rblockRel.isPotentialStallSite(fn)) {
+ // after creating new object, lhs is accessible
+ rg.makeAccessible(lhs);
+ }
+ }
- // transfer func
- rg.assignTempEqualToNewAlloc(lhs, as);
+ // transfer func
+ rg.assignTempEqualToNewAlloc(lhs, as);
}
break;
if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
- // always remove ALL stall site taints at enter
- rg.removeAllStallSiteTaints();
+ // always remove ALL stall site taints at enter
+ rg.removeAllStallSiteTaints();
- // inject taints for in-set vars
- rg.taintInSetVars(sese);
+ // inject taints for in-set vars
+ rg.taintInSetVars(sese);
}
break;
if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
- // @ sese exit make all live variables
- // inaccessible to later parent statements
- rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) );
+ // @ sese exit make all live variables
+ // inaccessible to later parent statements
+ rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) );
- // always remove ALL stall site taints at exit
- rg.removeAllStallSiteTaints();
+ // always remove ALL stall site taints at exit
+ rg.removeAllStallSiteTaints();
- // remove in-set var taints for the exiting rblock
- rg.removeInContextTaints(sese);
+ // remove in-set var taints for the exiting rblock
+ rg.removeInContextTaints(sese);
}
break;
case FKind.FlatCall: {
Descriptor mdCaller;
if( fmContaining.getMethod() != null ) {
- mdCaller = fmContaining.getMethod();
+ mdCaller = fmContaining.getMethod();
} else {
- mdCaller = fmContaining.getTask();
+ mdCaller = fmContaining.getTask();
}
FlatCall fc = (FlatCall) fn;
MethodDescriptor mdCallee = fc.getMethod();
if( mdCallee.getSymbol().equals("genReach") ) {
- rg.writeGraph("genReach"+d,
- true, // write labels (variables)
- true, // selectively hide intermediate temp vars
- true, // prune unreachable heap regions
- false, // hide reachability altogether
- true, // hide subset reachability states
- true, // hide predicates
- true); // hide edge taints
- break;
+ rg.writeGraph("genReach"+d,
+ true, // write labels (variables)
+ true, // selectively hide intermediate temp vars
+ true, // prune unreachable heap regions
+ false, // hide reachability altogether
+ true, // hide subset reachability states
+ true, // hide predicates
+ true); // hide edge taints
+ break;
}
boolean writeDebugDOTs = false;
boolean stopAfter = false;
if( debugCallSite ) {
- ++ReachGraph.debugCallSiteVisitCounter;
- System.out.println(" $$$ Debug call site visit "+
- ReachGraph.debugCallSiteVisitCounter+
- " $$$"
- );
- if(
- (ReachGraph.debugCallSiteVisitCounter >=
- ReachGraph.debugCallSiteVisitStartCapture) &&
-
- (ReachGraph.debugCallSiteVisitCounter <
- ReachGraph.debugCallSiteVisitStartCapture +
- ReachGraph.debugCallSiteNumVisitsToCapture)
- ) {
- writeDebugDOTs = true;
- System.out.println(" $$$ Capturing this call site visit $$$");
- if( ReachGraph.debugCallSiteStopAfter &&
- (ReachGraph.debugCallSiteVisitCounter ==
- ReachGraph.debugCallSiteVisitStartCapture +
- ReachGraph.debugCallSiteNumVisitsToCapture - 1)
- ) {
- stopAfter = true;
- }
- }
+ ++ReachGraph.debugCallSiteVisitCounter;
+ System.out.println(" $$$ Debug call site visit "+
+ ReachGraph.debugCallSiteVisitCounter+
+ " $$$"
+ );
+ if(
+ (ReachGraph.debugCallSiteVisitCounter >=
+ ReachGraph.debugCallSiteVisitStartCapture) &&
+
+ (ReachGraph.debugCallSiteVisitCounter <
+ ReachGraph.debugCallSiteVisitStartCapture +
+ ReachGraph.debugCallSiteNumVisitsToCapture)
+ ) {
+ writeDebugDOTs = true;
+ System.out.println(" $$$ Capturing this call site visit $$$");
+ if( ReachGraph.debugCallSiteStopAfter &&
+ (ReachGraph.debugCallSiteVisitCounter ==
+ ReachGraph.debugCallSiteVisitStartCapture +
+ ReachGraph.debugCallSiteNumVisitsToCapture - 1)
+ ) {
+ stopAfter = true;
+ }
+ }
}
heapForThisCall_cur.merge(heapForThisCall_old);
if( !heapForThisCall_cur.equals(heapForThisCall_old) ) {
- // if heap at call site changed, update the contribution,
- // and reschedule the callee for analysis
- addIHMcontribution(mdCallee, fc, heapForThisCall_cur);
+ // if heap at call site changed, update the contribution,
+ // and reschedule the callee for analysis
+ addIHMcontribution(mdCallee, fc, heapForThisCall_cur);
- // map a FlatCall to its enclosing method/task descriptor
- // so we can write that info out later
- fc2enclosing.put(fc, mdCaller);
+ // map a FlatCall to its enclosing method/task descriptor
+ // so we can write that info out later
+ fc2enclosing.put(fc, mdCaller);
- if( state.DISJOINTDEBUGSCHEDULING ) {
- System.out.println(" context changed, scheduling callee: "+mdCallee);
- }
+ if( state.DISJOINTDEBUGSCHEDULING ) {
+ System.out.println(" context changed, scheduling callee: "+mdCallee);
+ }
- if( state.DISJOINTDVISITSTACKEESONTOP ) {
- calleesToEnqueue.add(mdCallee);
- } else {
- enqueue(mdCallee);
- }
+ if( state.DISJOINTDVISITSTACKEESONTOP ) {
+ calleesToEnqueue.add(mdCallee);
+ } else {
+ enqueue(mdCallee);
+ }
}
// callees, so find the set of callees...
Set<MethodDescriptor> setPossibleCallees;
if( determinismDesired ) {
- // use an ordered set
- setPossibleCallees = new TreeSet<MethodDescriptor>(dComp);
+ // use an ordered set
+ setPossibleCallees = new TreeSet<MethodDescriptor>(dComp);
} else {
- // otherwise use a speedy hashset
- setPossibleCallees = new HashSet<MethodDescriptor>();
+ // otherwise use a speedy hashset
+ setPossibleCallees = new HashSet<MethodDescriptor>();
}
if( mdCallee.isStatic() ) {
- setPossibleCallees.add(mdCallee);
+ setPossibleCallees.add(mdCallee);
} else {
- TypeDescriptor typeDesc = fc.getThis().getType();
- setPossibleCallees.addAll(callGraph.getMethods(mdCallee,
- typeDesc)
- );
+ TypeDescriptor typeDesc = fc.getThis().getType();
+ setPossibleCallees.addAll(callGraph.getMethods(mdCallee,
+ typeDesc)
+ );
}
ReachGraph rgMergeOfPossibleCallers = new ReachGraph();
Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
while( mdItr.hasNext() ) {
- MethodDescriptor mdPossible = mdItr.next();
- FlatMethod fmPossible = state.getMethodFlat(mdPossible);
-
- addDependent(mdPossible, // callee
- d); // caller
-
- // don't alter the working graph (rg) until we compute a
- // result for every possible callee, merge them all together,
- // then set rg to that
- ReachGraph rgPossibleCaller = new ReachGraph();
- rgPossibleCaller.merge(rg);
-
- ReachGraph rgPossibleCallee = getPartial(mdPossible);
-
- if( rgPossibleCallee == null ) {
- // if this method has never been analyzed just schedule it
- // for analysis and skip over this call site for now
- if( state.DISJOINTDVISITSTACKEESONTOP ) {
- calleesToEnqueue.add(mdPossible);
- } else {
- enqueue(mdPossible);
- }
-
- if( state.DISJOINTDEBUGSCHEDULING ) {
- System.out.println(" callee hasn't been analyzed, scheduling: "+mdPossible);
- }
-
- } else {
- // calculate the method call transform
- rgPossibleCaller.resolveMethodCall(fc,
- fmPossible,
- rgPossibleCallee,
- callerNodeIDsCopiedToCallee,
- writeDebugDOTs
- );
-
- if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
+ MethodDescriptor mdPossible = mdItr.next();
+ FlatMethod fmPossible = state.getMethodFlat(mdPossible);
+
+ addDependent(mdPossible, // callee
+ d); // caller
+
+ // don't alter the working graph (rg) until we compute a
+ // result for every possible callee, merge them all together,
+ // then set rg to that
+ ReachGraph rgPossibleCaller = new ReachGraph();
+ rgPossibleCaller.merge(rg);
+
+ ReachGraph rgPossibleCallee = getPartial(mdPossible);
+
+ if( rgPossibleCallee == null ) {
+ // if this method has never been analyzed just schedule it
+ // for analysis and skip over this call site for now
+ if( state.DISJOINTDVISITSTACKEESONTOP ) {
+ calleesToEnqueue.add(mdPossible);
+ } else {
+ enqueue(mdPossible);
+ }
+
+ if( state.DISJOINTDEBUGSCHEDULING ) {
+ System.out.println(" callee hasn't been analyzed, scheduling: "+mdPossible);
+ }
+
+ } else {
+ // calculate the method call transform
+ rgPossibleCaller.resolveMethodCall(fc,
+ fmPossible,
+ rgPossibleCallee,
+ callerNodeIDsCopiedToCallee,
+ writeDebugDOTs
+ );
+
+ if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
// if( !rgPossibleCallee.isAccessible( ReachGraph.tdReturn ) ) {
- if( !accessible.isAccessible(fn, ReachGraph.tdReturn) ) {
- rgPossibleCaller.makeInaccessible(fc.getReturnTemp() );
- }
- }
+ if( !accessible.isAccessible(fn, ReachGraph.tdReturn) ) {
+ rgPossibleCaller.makeInaccessible(fc.getReturnTemp() );
+ }
+ }
- }
+ }
- rgMergeOfPossibleCallers.merge(rgPossibleCaller);
+ rgMergeOfPossibleCallers.merge(rgPossibleCaller);
}
if( stopAfter ) {
- System.out.println("$$$ Exiting after requested captures of call site. $$$");
- System.exit(0);
+ System.out.println("$$$ Exiting after requested captures of call site. $$$");
+ System.exit(0);
}
//need to consider more
FlatNode nextFN=fmCallee.getNext(0);
if( nextFN instanceof FlatSESEEnterNode ) {
- FlatSESEEnterNode calleeSESE=(FlatSESEEnterNode)nextFN;
- if(!calleeSESE.getIsLeafSESE()) {
- rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) );
- }
+ FlatSESEEnterNode calleeSESE=(FlatSESEEnterNode)nextFN;
+ if(!calleeSESE.getIsLeafSESE()) {
+ rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) );
+ }
}
} break;
// before transfer, do effects analysis support
if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
// if(!rg.isAccessible(rhs)){
- if(!accessible.isAccessible(fn,rhs)) {
- rg.makeInaccessible(ReachGraph.tdReturn);
- }
+ if(!accessible.isAccessible(fn,rhs)) {
+ rg.makeInaccessible(ReachGraph.tdReturn);
+ }
}
if( rhs != null && shouldAnalysisTrack(rhs.getType() ) ) {
- rg.assignReturnEqualToTemp(rhs);
+ rg.assignReturnEqualToTemp(rhs);
}
setRetNodes.add(frn);
String graphName;
if( d instanceof TaskDescriptor ) {
- graphName = "COMPLETEtask"+d;
+ graphName = "COMPLETEtask"+d;
} else {
- graphName = "COMPLETE"+d;
+ graphName = "COMPLETE"+d;
}
rg.writeGraph(graphName,
Iterator fc2rgItr = IHMs.entrySet().iterator();
while( fc2rgItr.hasNext() ) {
- Map.Entry me2 = (Map.Entry)fc2rgItr.next();
- FlatCall fc = (FlatCall) me2.getKey();
- ReachGraph rg = (ReachGraph) me2.getValue();
-
- rg.writeGraph("IHMPARTFOR"+d+"FROM"+fc2enclosing.get(fc)+fc,
- true, // write labels (variables)
- true, // selectively hide intermediate temp vars
- true, // hide reachability altogether
- true, // prune unreachable heap regions
- true, // hide subset reachability states
- false, // hide predicates
- true); // hide edge taints
+ Map.Entry me2 = (Map.Entry)fc2rgItr.next();
+ FlatCall fc = (FlatCall) me2.getKey();
+ ReachGraph rg = (ReachGraph) me2.getValue();
+
+ rg.writeGraph("IHMPARTFOR"+d+"FROM"+fc2enclosing.get(fc)+fc,
+ true, // write labels (variables)
+ true, // selectively hide intermediate temp vars
+ true, // hide reachability altogether
+ true, // prune unreachable heap regions
+ true, // hide subset reachability states
+ false, // hide predicates
+ true); // hide edge taints
}
}
}
// descriptor we've already written out
if( writeAllIncrementalDOTs ) {
if( !mapDescriptorToNumUpdates.containsKey(d) ) {
- mapDescriptorToNumUpdates.put(d, new Integer(0) );
+ mapDescriptorToNumUpdates.put(d, new Integer(0) );
}
Integer n = mapDescriptorToNumUpdates.get(d);
String graphName;
if( d instanceof TaskDescriptor ) {
- graphName = d+"COMPLETEtask"+String.format("%05d", n);
+ graphName = d+"COMPLETEtask"+String.format("%05d", n);
} else {
- graphName = d+"COMPLETE"+String.format("%05d", n);
+ graphName = d+"COMPLETE"+String.format("%05d", n);
}
rg.writeGraph(graphName,
// the newest nodes are single objects
for( int i = 0; i < allocationDepth; ++i ) {
- Integer id = generateUniqueHeapRegionNodeID();
- as.setIthOldest(i, id);
- mapHrnIdToAllocSite.put(id, as);
+ Integer id = generateUniqueHeapRegionNodeID();
+ as.setIthOldest(i, id);
+ mapHrnIdToAllocSite.put(id, as);
}
// the oldest node is a summary node
Descriptor d = itr.next();
if( !discovered.contains(d) ) {
- dfsVisit(d, toSort, sorted, discovered);
+ dfsVisit(d, toSort, sorted, discovered);
}
}
// the call graph is not aware that we have a fabricated
// analysis entry that calls the program source's entry
if( md == mdSourceEntry ) {
- if( !discovered.contains(mdAnalysisEntry) ) {
- addDependent(mdSourceEntry, // callee
- mdAnalysisEntry // caller
- );
- dfsVisit(mdAnalysisEntry, toSort, sorted, discovered);
- }
+ if( !discovered.contains(mdAnalysisEntry) ) {
+ addDependent(mdSourceEntry, // callee
+ mdAnalysisEntry // caller
+ );
+ dfsVisit(mdAnalysisEntry, toSort, sorted, discovered);
+ }
}
// otherwise call graph guides DFS
Iterator itr = callGraph.getCallerSet(md).iterator();
while( itr.hasNext() ) {
- Descriptor dCaller = (Descriptor) itr.next();
+ Descriptor dCaller = (Descriptor) itr.next();
- // only consider callers in the original set to analyze
- if( !toSort.contains(dCaller) ) {
- continue;
- }
+ // only consider callers in the original set to analyze
+ if( !toSort.contains(dCaller) ) {
+ continue;
+ }
- if( !discovered.contains(dCaller) ) {
- addDependent(md, // callee
- dCaller // caller
- );
+ if( !discovered.contains(dCaller) ) {
+ addDependent(md, // callee
+ dCaller // caller
+ );
- dfsVisit(dCaller, toSort, sorted, discovered);
- }
+ dfsVisit(dCaller, toSort, sorted, discovered);
+ }
}
}
if( state.DISJOINTDVISITSTACK ||
state.DISJOINTDVISITSTACKEESONTOP
) {
- descriptorsToVisitStack.add(d);
+ descriptorsToVisitStack.add(d);
} else if( state.DISJOINTDVISITPQUE ) {
- Integer priority = mapDescriptorToPriority.get(d);
- descriptorsToVisitQ.add(new DescriptorQWrapper(priority,
- d)
- );
+ Integer priority = mapDescriptorToPriority.get(d);
+ descriptorsToVisitQ.add(new DescriptorQWrapper(priority,
+ d)
+ );
}
descriptorsToVisitSet.add(d);
if(!typeDesc.isImmutable()) {
ClassDescriptor classDesc = typeDesc.getClassDesc();
for (Iterator it = classDesc.getFields(); it.hasNext(); ) {
- FieldDescriptor field = (FieldDescriptor) it.next();
- TypeDescriptor fieldType = field.getType();
- if (shouldAnalysisTrack(fieldType)) {
- fieldSet.add(field);
- }
+ FieldDescriptor field = (FieldDescriptor) it.next();
+ TypeDescriptor fieldType = field.getType();
+ if (shouldAnalysisTrack(fieldType)) {
+ fieldSet.add(field);
+ }
}
}
return fieldSet;
TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
HeapRegionNode hrnSummary;
if(!mapToExistingNode.containsKey(typeDesc)) {
- AllocSite as;
- if(i==dimCount) {
- as = alloc;
- } else {
- as = createParameterAllocSite(rg, tempDesc, false);
- }
- // make a new reference to allocated node
- hrnSummary =
- rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
- false, // single object?
- true, // summary?
- false, // out-of-context?
- as.getType(), // type
- as, // allocation site
- alpha, // inherent reach
- alpha, // current reach
- ExistPredSet.factory(rg.predTrue), // predicates
- tempDesc.toString() // description
- );
- rg.id2hrn.put(as.getSummary(),hrnSummary);
-
- mapToExistingNode.put(typeDesc, hrnSummary);
+ AllocSite as;
+ if(i==dimCount) {
+ as = alloc;
+ } else {
+ as = createParameterAllocSite(rg, tempDesc, false);
+ }
+ // make a new reference to allocated node
+ hrnSummary =
+ rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
+ false, // single object?
+ true, // summary?
+ false, // out-of-context?
+ as.getType(), // type
+ as, // allocation site
+ alpha, // inherent reach
+ alpha, // current reach
+ ExistPredSet.factory(rg.predTrue), // predicates
+ tempDesc.toString() // description
+ );
+ rg.id2hrn.put(as.getSummary(),hrnSummary);
+
+ mapToExistingNode.put(typeDesc, hrnSummary);
} else {
- hrnSummary=mapToExistingNode.get(typeDesc);
+ hrnSummary=mapToExistingNode.get(typeDesc);
}
if(prevNode==null) {
- // make a new reference between new summary node and source
- RefEdge edgeToSummary = new RefEdge(srcHRN, // source
- hrnSummary, // dest
- typeDesc, // type
- fd.getSymbol(), // field name
- alpha, // beta
- ExistPredSet.factory(rg.predTrue), // predicates
- null
- );
-
- rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
- prevNode=hrnSummary;
- arrayEntryNode=hrnSummary;
+ // make a new reference between new summary node and source
+ RefEdge edgeToSummary = new RefEdge(srcHRN, // source
+ hrnSummary, // dest
+ typeDesc, // type
+ fd.getSymbol(), // field name
+ alpha, // beta
+ ExistPredSet.factory(rg.predTrue), // predicates
+ null
+ );
+
+ rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
+ prevNode=hrnSummary;
+ arrayEntryNode=hrnSummary;
} else {
- // make a new reference between summary nodes of array
- RefEdge edgeToSummary = new RefEdge(prevNode, // source
- hrnSummary, // dest
- typeDesc, // type
- arrayElementFieldName, // field name
- alpha, // beta
- ExistPredSet.factory(rg.predTrue), // predicates
- null
- );
+ // make a new reference between summary nodes of array
+ RefEdge edgeToSummary = new RefEdge(prevNode, // source
+ hrnSummary, // dest
+ typeDesc, // type
+ arrayElementFieldName, // field name
+ alpha, // beta
+ ExistPredSet.factory(rg.predTrue), // predicates
+ null
+ );
- rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
- prevNode=hrnSummary;
+ rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
+ prevNode=hrnSummary;
}
}
TypeDescriptor typeDesc=type.dereference();
typeDesc.setArrayCount(0);
if(!mapToExistingNode.containsKey(typeDesc)) {
- TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
- AllocSite as = createParameterAllocSite(rg, tempDesc, false);
- // make a new reference to allocated node
- HeapRegionNode hrnSummary =
- rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
- false, // single object?
- true, // summary?
- false, // out-of-context?
- typeDesc, // type
- as, // allocation site
- alpha, // inherent reach
- alpha, // current reach
- ExistPredSet.factory(rg.predTrue), // predicates
- tempDesc.toString() // description
- );
- rg.id2hrn.put(as.getSummary(),hrnSummary);
- mapToExistingNode.put(typeDesc, hrnSummary);
- RefEdge edgeToSummary = new RefEdge(prevNode, // source
- hrnSummary, // dest
- typeDesc, // type
- arrayElementFieldName, // field name
- alpha, // beta
- ExistPredSet.factory(rg.predTrue), // predicates
- null
- );
- rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
- prevNode=hrnSummary;
+ TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
+ AllocSite as = createParameterAllocSite(rg, tempDesc, false);
+ // make a new reference to allocated node
+ HeapRegionNode hrnSummary =
+ rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
+ false, // single object?
+ true, // summary?
+ false, // out-of-context?
+ typeDesc, // type
+ as, // allocation site
+ alpha, // inherent reach
+ alpha, // current reach
+ ExistPredSet.factory(rg.predTrue), // predicates
+ tempDesc.toString() // description
+ );
+ rg.id2hrn.put(as.getSummary(),hrnSummary);
+ mapToExistingNode.put(typeDesc, hrnSummary);
+ RefEdge edgeToSummary = new RefEdge(prevNode, // source
+ hrnSummary, // dest
+ typeDesc, // type
+ arrayElementFieldName, // field name
+ alpha, // beta
+ ExistPredSet.factory(rg.predTrue), // predicates
+ null
+ );
+ rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
+ prevNode=hrnSummary;
} else {
- HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
- if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null) {
- RefEdge edgeToSummary = new RefEdge(prevNode, // source
- hrnSummary, // dest
- typeDesc, // type
- arrayElementFieldName, // field name
- alpha, // beta
- ExistPredSet.factory(rg.predTrue), // predicates
- null
- );
- rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
- }
- prevNode=hrnSummary;
+ HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
+ if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null) {
+ RefEdge edgeToSummary = new RefEdge(prevNode, // source
+ hrnSummary, // dest
+ typeDesc, // type
+ arrayElementFieldName, // field name
+ alpha, // beta
+ ExistPredSet.factory(rg.predTrue), // predicates
+ null
+ );
+ rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
+ }
+ prevNode=hrnSummary;
}
}
// set-up a work set for class field
ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
for (Iterator it = classDesc.getFields(); it.hasNext(); ) {
- FieldDescriptor fd = (FieldDescriptor) it.next();
- TypeDescriptor fieldType = fd.getType();
- if (shouldAnalysisTrack(fieldType)) {
- HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
- newMap.put(hrnNewest, fd);
- workSet.add(newMap);
- }
+ FieldDescriptor fd = (FieldDescriptor) it.next();
+ TypeDescriptor fieldType = fd.getType();
+ if (shouldAnalysisTrack(fieldType)) {
+ HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
+ newMap.put(hrnNewest, fd);
+ workSet.add(newMap);
+ }
}
int uniqueIdentifier = 0;
while (!workSet.isEmpty()) {
- HashMap<HeapRegionNode, FieldDescriptor> map = workSet
- .iterator().next();
- workSet.remove(map);
-
- Set<HeapRegionNode> key = map.keySet();
- HeapRegionNode srcHRN = key.iterator().next();
- FieldDescriptor fd = map.get(srcHRN);
- TypeDescriptor type = fd.getType();
- String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
-
- if (!doneSet.contains(doneSetIdentifier)) {
- doneSet.add(doneSetIdentifier);
- if (!mapTypeToExistingSummaryNode.containsKey(type)) {
- // create new summary Node
- TempDescriptor td = new TempDescriptor("temp"
- + uniqueIdentifier, type);
-
- AllocSite allocSite;
- if(type.equals(paramTypeDesc)) {
- //corresponding allocsite has already been created for a parameter variable.
- allocSite=as;
- } else {
- allocSite = createParameterAllocSite(rg, td, false);
- }
- String strDesc = allocSite.toStringForDOT()
- + "\\nsummary";
- TypeDescriptor allocType=allocSite.getType();
-
- HeapRegionNode hrnSummary;
- if(allocType.isArray() && allocType.getArrayCount()>0) {
- hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
- } else {
- hrnSummary =
- rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
- false, // single object?
- true, // summary?
- false, // out-of-context?
- allocSite.getType(), // type
- allocSite, // allocation site
- hrnNewest.getAlpha(), // inherent reach
- hrnNewest.getAlpha(), // current reach
- ExistPredSet.factory(rg.predTrue), // predicates
- strDesc // description
- );
- rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
-
- // make a new reference to summary node
- RefEdge edgeToSummary = new RefEdge(srcHRN, // source
- hrnSummary, // dest
- type, // type
- fd.getSymbol(), // field name
- hrnNewest.getAlpha(), // beta
- ExistPredSet.factory(rg.predTrue), // predicates
- null
- );
-
- rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
- }
- uniqueIdentifier++;
-
- mapTypeToExistingSummaryNode.put(type, hrnSummary);
-
- // set-up a work set for fields of the class
- Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
- for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
- .hasNext(); ) {
- FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
- .next();
- HeapRegionNode newDstHRN;
- if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)) {
- //related heap region node is already exsited.
- newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
- } else {
- newDstHRN=hrnSummary;
- }
- doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
- if(!doneSet.contains(doneSetIdentifier)) {
- // add new work item
- HashMap<HeapRegionNode, FieldDescriptor> newMap =
- new HashMap<HeapRegionNode, FieldDescriptor>();
- newMap.put(newDstHRN, fieldDescriptor);
- workSet.add(newMap);
- }
- }
-
- } else {
- // if there exists corresponding summary node
- HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
-
- RefEdge edgeToSummary = new RefEdge(srcHRN, // source
- hrnDst, // dest
- fd.getType(), // type
- fd.getSymbol(), // field name
- srcHRN.getAlpha(), // beta
- ExistPredSet.factory(rg.predTrue), // predicates
- null
- );
- rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
-
- }
- }
+ HashMap<HeapRegionNode, FieldDescriptor> map = workSet
+ .iterator().next();
+ workSet.remove(map);
+
+ Set<HeapRegionNode> key = map.keySet();
+ HeapRegionNode srcHRN = key.iterator().next();
+ FieldDescriptor fd = map.get(srcHRN);
+ TypeDescriptor type = fd.getType();
+ String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
+
+ if (!doneSet.contains(doneSetIdentifier)) {
+ doneSet.add(doneSetIdentifier);
+ if (!mapTypeToExistingSummaryNode.containsKey(type)) {
+ // create new summary Node
+ TempDescriptor td = new TempDescriptor("temp"
+ + uniqueIdentifier, type);
+
+ AllocSite allocSite;
+ if(type.equals(paramTypeDesc)) {
+ //corresponding allocsite has already been created for a parameter variable.
+ allocSite=as;
+ } else {
+ allocSite = createParameterAllocSite(rg, td, false);
+ }
+ String strDesc = allocSite.toStringForDOT()
+ + "\\nsummary";
+ TypeDescriptor allocType=allocSite.getType();
+
+ HeapRegionNode hrnSummary;
+ if(allocType.isArray() && allocType.getArrayCount()>0) {
+ hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
+ } else {
+ hrnSummary =
+ rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
+ false, // single object?
+ true, // summary?
+ false, // out-of-context?
+ allocSite.getType(), // type
+ allocSite, // allocation site
+ hrnNewest.getAlpha(), // inherent reach
+ hrnNewest.getAlpha(), // current reach
+ ExistPredSet.factory(rg.predTrue), // predicates
+ strDesc // description
+ );
+ rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
+
+ // make a new reference to summary node
+ RefEdge edgeToSummary = new RefEdge(srcHRN, // source
+ hrnSummary, // dest
+ type, // type
+ fd.getSymbol(), // field name
+ hrnNewest.getAlpha(), // beta
+ ExistPredSet.factory(rg.predTrue), // predicates
+ null
+ );
+
+ rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
+ }
+ uniqueIdentifier++;
+
+ mapTypeToExistingSummaryNode.put(type, hrnSummary);
+
+ // set-up a work set for fields of the class
+ Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
+ for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
+ .hasNext(); ) {
+ FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
+ .next();
+ HeapRegionNode newDstHRN;
+ if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)) {
+ //related heap region node is already exsited.
+ newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
+ } else {
+ newDstHRN=hrnSummary;
+ }
+ doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
+ if(!doneSet.contains(doneSetIdentifier)) {
+ // add new work item
+ HashMap<HeapRegionNode, FieldDescriptor> newMap =
+ new HashMap<HeapRegionNode, FieldDescriptor>();
+ newMap.put(newDstHRN, fieldDescriptor);
+ workSet.add(newMap);
+ }
+ }
+
+ } else {
+ // if there exists corresponding summary node
+ HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
+
+ RefEdge edgeToSummary = new RefEdge(srcHRN, // source
+ hrnDst, // dest
+ fd.getType(), // type
+ fd.getSymbol(), // field name
+ srcHRN.getAlpha(), // beta
+ ExistPredSet.factory(rg.predTrue), // predicates
+ null
+ );
+ rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
+
+ }
+ }
}
}
FlatNode n = toVisit.iterator().next();
if( n instanceof FlatNew ) {
- s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
+ s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
}
toVisit.remove(n);
visited.add(n);
for( int i = 0; i < pm.numNext(n); ++i ) {
- FlatNode child = pm.getNext(n, i);
- if( !visited.contains(child) ) {
- toVisit.add(child);
- }
+ FlatNode child = pm.getNext(n, i);
+ if( !visited.contains(child) ) {
+ toVisit.add(child);
+ }
}
}
HashSet<AllocSite> asSet = getAllocationSiteSet(d);
Iterator asItr = asSet.iterator();
while (asItr.hasNext()) {
- AllocSite as = (AllocSite) asItr.next();
- if (as.getDisjointAnalysisId() != null) {
- out.add(as);
- }
+ AllocSite as = (AllocSite) asItr.next();
+ if (as.getDisjointAnalysisId() != null) {
+ out.add(as);
+ }
}
// enqueue callees of this method to be searched for
// allocation sites also
Set callees = callGraph.getCalleeSet(d);
if (callees != null) {
- Iterator methItr = callees.iterator();
- while (methItr.hasNext()) {
- MethodDescriptor md = (MethodDescriptor) methItr.next();
+ Iterator methItr = callees.iterator();
+ while (methItr.hasNext()) {
+ MethodDescriptor md = (MethodDescriptor) methItr.next();
- if (!visited.contains(md)) {
- toVisit.add(md);
- }
- }
+ if (!visited.contains(md)) {
+ toVisit.add(md);
+ }
+ }
}
}
HashSet<AllocSite> asSet = getAllocationSiteSet(d);
Iterator asItr = asSet.iterator();
while( asItr.hasNext() ) {
- AllocSite as = (AllocSite) asItr.next();
- TypeDescriptor typed = as.getType();
- if( typed != null ) {
- ClassDescriptor cd = typed.getClassDesc();
- if( cd != null && cd.hasFlags() ) {
- asSetTotal.add(as);
- }
- }
+ AllocSite as = (AllocSite) asItr.next();
+ TypeDescriptor typed = as.getType();
+ if( typed != null ) {
+ ClassDescriptor cd = typed.getClassDesc();
+ if( cd != null && cd.hasFlags() ) {
+ asSetTotal.add(as);
+ }
+ }
}
// enqueue callees of this method to be searched for
// allocation sites also
Set callees = callGraph.getCalleeSet(d);
if( callees != null ) {
- Iterator methItr = callees.iterator();
- while( methItr.hasNext() ) {
- MethodDescriptor md = (MethodDescriptor) methItr.next();
+ Iterator methItr = callees.iterator();
+ while( methItr.hasNext() ) {
+ MethodDescriptor md = (MethodDescriptor) methItr.next();
- if( !visited.contains(md) ) {
- toVisit.add(md);
- }
- }
+ if( !visited.contains(md) ) {
+ toVisit.add(md);
+ }
+ }
}
}
" @@@");
String graphName;
if( in ) {
- graphName = String.format("snap%03d_%04din",
- snapVisitCounter,
- snapNodeCounter);
+ graphName = String.format("snap%03d_%04din",
+ snapVisitCounter,
+ snapNodeCounter);
} else {
- graphName = String.format("snap%03d_%04dout",
- snapVisitCounter,
- snapNodeCounter);
+ graphName = String.format("snap%03d_%04dout",
+ snapVisitCounter,
+ snapNodeCounter);
}
if( fn != null ) {
- graphName = graphName + fn;
+ graphName = graphName + fn;
}
rg.writeGraph(graphName,
true, // write labels (variables)
Hashtable<Taint, Set<Effect>> te = sese2te.get(sese);
if( te == null ) {
- te = new Hashtable<Taint, Set<Effect>>();
+ te = new Hashtable<Taint, Set<Effect>>();
}
Set<Effect> effects = te.get(tNoPreds);
if (effects == null) {
- effects = new HashSet<Effect>();
+ effects = new HashSet<Effect>();
}
effects.add(e);
te.put(tNoPreds, effects);
Hashtable<Taint, Set<Effect>> te = stallSite2te.get(stallSite);
if( te == null ) {
- te = new Hashtable<Taint, Set<Effect>>();
+ te = new Hashtable<Taint, Set<Effect>>();
}
Set<Effect> effects = te.get(tNoPreds);
if (effects == null) {
- effects = new HashSet<Effect>();
+ effects = new HashSet<Effect>();
}
effects.add(e);
te.put(tNoPreds, effects);
Effect effect = new Effect(affectedAlloc, Effect.read, fld);
for (Iterator<Taint> taintSetIter = taintSet.iterator(); taintSetIter.hasNext(); ) {
- Taint taint = taintSetIter.next();
- add(taint, effect, currentProgramPoint);
+ Taint taint = taintSetIter.next();
+ add(taint, effect, currentProgramPoint);
}
}
}
Effect effect = new Effect(affectedAlloc, Effect.read, fld);
if (taintSet!=null)
- for (Taint taint : taintSet.getTaints()) {
- add(taint, effect, currentProgramPoint);
- }
+ for (Taint taint : taintSet.getTaints()) {
+ add(taint, effect, currentProgramPoint);
+ }
}
}
Effect effectSU = null;
if (strongUpdate) {
- effectSU = new Effect(affectedAlloc, Effect.strongupdate, fld);
+ effectSU = new Effect(affectedAlloc, Effect.strongupdate, fld);
}
for (Iterator<Taint> taintSetIter = taintSet.iterator(); taintSetIter.hasNext(); ) {
- Taint taint = taintSetIter.next();
- add(taint, effect, currentProgramPoint);
+ Taint taint = taintSetIter.next();
+ add(taint, effect, currentProgramPoint);
- if (strongUpdate) {
- add(taint, effectSU, currentProgramPoint);
- }
+ if (strongUpdate) {
+ add(taint, effectSU, currentProgramPoint);
+ }
}
}
}
Alloc affectedAlloc = edge.getDst().getAllocSite();
Effect effect = new Effect(affectedAlloc, Effect.write, fld);
if (taintSet!=null)
- for (Taint taint : taintSet.getTaints()) {
- add(taint, effect, currentProgramPoint);
- }
+ for (Taint taint : taintSet.getTaints()) {
+ add(taint, effect, currentProgramPoint);
+ }
}
}
Iterator meItr = taint2effects.entrySet().iterator();
while( meItr.hasNext() ) {
- Map.Entry me = (Map.Entry)meItr.next();
- Taint taint = (Taint) me.getKey();
- Set<Effect> effects = (Set<Effect>)me.getValue();
+ Map.Entry me = (Map.Entry)meItr.next();
+ Taint taint = (Taint) me.getKey();
+ Set<Effect> effects = (Set<Effect>)me.getValue();
- Iterator<Effect> eItr = effects.iterator();
- while( eItr.hasNext() ) {
- Effect e = eItr.next();
+ Iterator<Effect> eItr = effects.iterator();
+ while( eItr.hasNext() ) {
+ Effect e = eItr.next();
- bw.write(taint+"-->"+e+"\n");
- }
+ bw.write(taint+"-->"+e+"\n");
+ }
}
bw.close();
// first find node
HeapRegionNode hrn = rg.id2hrn.get(n_hrnID);
if( hrn == null ) {
- return null;
+ return null;
}
if( !calleeReachableNodes.contains(n_hrnID) ) {
- return null;
+ return null;
}
// when the state is null we're done!
if( ne_state == null ) {
- return hrn.getPreds();
+ return hrn.getPreds();
} else {
- // otherwise look for state too
+ // otherwise look for state too
- // TODO: contains OR containsSuperSet OR containsWithZeroes??
- ReachState stateCaller = hrn.getAlpha().containsIgnorePreds(ne_state);
+ // TODO: contains OR containsSuperSet OR containsWithZeroes??
+ ReachState stateCaller = hrn.getAlpha().containsIgnorePreds(ne_state);
- if( stateCaller == null ) {
- return null;
+ if( stateCaller == null ) {
+ return null;
- } else {
- // it was here, return the predicates on the state!!
- return stateCaller.getPreds();
- }
+ } else {
+ // it was here, return the predicates on the state!!
+ return stateCaller.getPreds();
+ }
}
// unreachable program point!
// reference edge exists
VariableNode vnSrc = null;
if( e_tdSrc != null ) {
- vnSrc = rg.td2vn.get(e_tdSrc);
+ vnSrc = rg.td2vn.get(e_tdSrc);
}
HeapRegionNode hrnSrc = null;
if( e_hrnSrcID != null ) {
- hrnSrc = rg.id2hrn.get(e_hrnSrcID);
+ hrnSrc = rg.id2hrn.get(e_hrnSrcID);
}
assert(vnSrc == null) || (hrnSrc == null);
// the source is not present in graph
if( vnSrc == null && hrnSrc == null ) {
- return null;
+ return null;
}
RefSrcNode rsn;
if( vnSrc != null ) {
- rsn = vnSrc;
- assert e_srcOutCalleeContext;
- assert !e_srcOutCallerContext;
+ rsn = vnSrc;
+ assert e_srcOutCalleeContext;
+ assert !e_srcOutCallerContext;
} else {
- assert !(e_srcOutCalleeContext && e_srcOutCallerContext);
+ assert !(e_srcOutCalleeContext && e_srcOutCallerContext);
- if( e_srcOutCalleeContext ) {
- if( calleeReachableNodes.contains(e_hrnSrcID) ) {
- return null;
- }
+ if( e_srcOutCalleeContext ) {
+ if( calleeReachableNodes.contains(e_hrnSrcID) ) {
+ return null;
+ }
- } else if( e_srcOutCallerContext ) {
- if( !hrnSrc.isOutOfContext() ) {
- return null;
- }
+ } else if( e_srcOutCallerContext ) {
+ if( !hrnSrc.isOutOfContext() ) {
+ return null;
+ }
- } else {
+ } else {
- if( !calleeReachableNodes.contains(e_hrnSrcID) ) {
- return null;
- }
- if( hrnSrc.isOutOfContext() ) {
- return null;
- }
+ if( !calleeReachableNodes.contains(e_hrnSrcID) ) {
+ return null;
+ }
+ if( hrnSrc.isOutOfContext() ) {
+ return null;
+ }
- }
+ }
- rsn = hrnSrc;
+ rsn = hrnSrc;
}
// is the destination present?
HeapRegionNode hrnDst = rg.id2hrn.get(e_hrnDstID);
if( hrnDst == null ) {
- return null;
+ return null;
}
if( !calleeReachableNodes.contains(e_hrnDstID) ) {
- return null;
+ return null;
}
// is there an edge between them with the given
e_type,
e_field);
if( edge == null ) {
- return null;
+ return null;
}
// when the state and taint are null we're done!
if( ne_state == null &&
e_taint == null ) {
- return edge.getPreds();
+ return edge.getPreds();
} else if( ne_state != null ) {
- // otherwise look for state too
+ // otherwise look for state too
- // TODO: contains OR containsSuperSet OR containsWithZeroes??
- ReachState stateCaller = edge.getBeta().containsIgnorePreds(ne_state);
+ // TODO: contains OR containsSuperSet OR containsWithZeroes??
+ ReachState stateCaller = edge.getBeta().containsIgnorePreds(ne_state);
- if( stateCaller == null ) {
- return null;
+ if( stateCaller == null ) {
+ return null;
- } else {
- // it was here, return the predicates on the state!!
- return stateCaller.getPreds();
- }
+ } else {
+ // it was here, return the predicates on the state!!
+ return stateCaller.getPreds();
+ }
} else {
- // otherwise look for taint
+ // otherwise look for taint
- Taint tCaller = edge.getTaints().containsIgnorePreds(e_taint);
+ Taint tCaller = edge.getTaints().containsIgnorePreds(e_taint);
- if( tCaller == null ) {
- return null;
+ if( tCaller == null ) {
+ return null;
- } else {
- // it was here, return the predicates on the taint!!
- return tCaller.getPreds();
- }
+ } else {
+ // it was here, return the predicates on the taint!!
+ return tCaller.getPreds();
+ }
}
// unreachable program point!
if( ne_state == null ) {
if( pred.ne_state != null ) {
- return false;
+ return false;
}
} else if( !ne_state.equals(pred.ne_state) ) {
return false;
if( n_hrnID == null ) {
if( pred.n_hrnID != null ) {
- return false;
+ return false;
}
} else if( !n_hrnID.equals(pred.n_hrnID) ) {
return false;
if( e_tdSrc == null ) {
if( pred.e_tdSrc != null ) {
- return false;
+ return false;
}
} else if( !e_tdSrc.equals(pred.e_tdSrc) ) {
return false;
if( e_hrnSrcID == null ) {
if( pred.e_hrnSrcID != null ) {
- return false;
+ return false;
}
} else {
if( !e_hrnSrcID.equals(pred.e_hrnSrcID) ) {
- return false;
+ return false;
}
if( e_srcOutCalleeContext != pred.e_srcOutCalleeContext ) {
- return false;
+ return false;
}
if( e_srcOutCallerContext != pred.e_srcOutCallerContext ) {
- return false;
+ return false;
}
}
if( e_hrnDstID == null ) {
if( pred.e_hrnDstID != null ) {
- return false;
+ return false;
}
} else if( !e_hrnDstID.equals(pred.e_hrnDstID) ) {
return false;
if( e_type == null ) {
if( pred.e_type != null ) {
- return false;
+ return false;
}
} else if( !e_type.equals(pred.e_type) ) {
return false;
if( e_field == null ) {
if( pred.e_field != null ) {
- return false;
+ return false;
}
} else if( !e_field.equals(pred.e_field) ) {
return false;
if( e_taint == null ) {
if( pred.e_taint != null ) {
- return false;
+ return false;
}
} else if( !e_taint.equals(pred.e_taint) ) {
return false;
int hash = n_hrnID.intValue()*17;
if( ne_state != null ) {
- hash ^= ne_state.hashCode();
+ hash ^= ne_state.hashCode();
}
return hash;
hash += e_type.hashCode()*17;
if( e_field != null ) {
- hash += e_field.hashCode()*7;
+ hash += e_field.hashCode()*7;
}
if( e_tdSrc != null ) {
- hash ^= e_tdSrc.hashCode()*11;
+ hash ^= e_tdSrc.hashCode()*11;
} else {
- hash ^= e_hrnSrcID.hashCode()*11;
- if( e_srcOutCalleeContext ) {
- hash ^= 0xf1aeb;
- }
- if( e_srcOutCallerContext ) {
- hash ^= 0x875d;
- }
+ hash ^= e_hrnSrcID.hashCode()*11;
+ if( e_srcOutCalleeContext ) {
+ hash ^= 0xf1aeb;
+ }
+ if( e_srcOutCallerContext ) {
+ hash ^= 0x875d;
+ }
}
hash += e_hrnDstID.hashCode();
if( ne_state != null ) {
- hash ^= ne_state.hashCode();
+ hash ^= ne_state.hashCode();
}
if( e_taint != null ) {
- hash ^= e_taint.hashCode();
+ hash ^= e_taint.hashCode();
}
return hash;
if( predType == TYPE_NODE ) {
String s = n_hrnID.toString();
if( ne_state != null ) {
- s += "w"+ne_state;
+ s += "w"+ne_state;
}
return s;
}
String s = "(";
if( e_tdSrc != null ) {
- s += e_tdSrc.toString();
+ s += e_tdSrc.toString();
} else {
- s += e_hrnSrcID.toString();
+ s += e_hrnSrcID.toString();
}
if( e_srcOutCalleeContext ) {
- s += "(ooCLEEc)";
+ s += "(ooCLEEc)";
}
if( e_srcOutCallerContext ) {
- s += "(ooCLERc)";
+ s += "(ooCLERc)";
}
s += "-->"+e_hrnDstID+")";
if( ne_state != null ) {
- s += "w"+ne_state;
+ s += "w"+ne_state;
}
if( e_taint != null ) {
- s += "w"+e_taint;
+ s += "w"+e_taint;
}
return s;
calleeReachableNodes);
if( predsFromSatisfier != null ) {
- if( predsOut == null ) {
- predsOut = predsFromSatisfier;
- } else {
- predsOut = Canonical.join(predsOut,
- predsFromSatisfier);
- }
+ if( predsOut == null ) {
+ predsOut = predsFromSatisfier;
+ } else {
+ predsOut = Canonical.join(predsOut,
+ predsFromSatisfier);
+ }
}
}
ExistPred pred = predItr.next();
s += pred.toString();
if( predItr.hasNext() ) {
- s += " ||\\n";
+ s += " ||\\n";
}
}
s += "]";
ExistPred pred = predItr.next();
s += pred.toString();
if( predItr.hasNext() ) {
- s += " || ";
+ s += " || ";
}
}
s += "]";
edge.typeEquals(type) &&
edge.fieldEquals(field)
) {
- return edge;
+ return edge;
}
}
Iterator<ReachTuple> rtItr = state.iterator();
while( rtItr.hasNext() ) {
- ReachTuple rt = rtItr.next();
+ ReachTuple rt = rtItr.next();
- if( !rt.isOutOfContext() ) {
- return false;
- }
+ if( !rt.isOutOfContext() ) {
+ return false;
+ }
}
}
toprocess.remove(fn);
HashSet<FlatNode> myset=new HashSet<FlatNode>();
if (!analysisCares(fn)) {
- for(int i=0; i<fn.numPrev(); i++) {
- if (map.containsKey(fn.getPrev(i)))
- myset.addAll(map.get(fn.getPrev(i)));
- }
+ for(int i=0; i<fn.numPrev(); i++) {
+ if (map.containsKey(fn.getPrev(i)))
+ myset.addAll(map.get(fn.getPrev(i)));
+ }
} else {
- myset.add(fn);
+ myset.add(fn);
}
if (!map.containsKey(fn)||!map.get(fn).equals(myset)) {
- map.put(fn, myset);
- for(int i=0; i<fn.numNext(); i++) {
- toprocess.add(fn.getNext(i));
- }
+ map.put(fn, myset);
+ for(int i=0; i<fn.numNext(); i++) {
+ toprocess.add(fn.getNext(i));
+ }
}
}
for(Iterator<FlatNode> it=map.keySet().iterator(); it.hasNext(); ) {
FlatNode fn=it.next();
if (analysisCares(fn)) {
- HashSet<FlatNode> myset=new HashSet<FlatNode>();
- for(int i=0; i<fn.numPrev(); i++) {
- if (map.containsKey(fn.getPrev(i)))
- myset.addAll(map.get(fn.getPrev(i)));
- }
- if (!prevmap.containsKey(fn))
- prevmap.put(fn, new Vector());
- for(Iterator<FlatNode> it2=myset.iterator(); it2.hasNext(); ) {
- FlatNode fnprev=it2.next();
- if (!nextmap.containsKey(fnprev))
- nextmap.put(fnprev, new Vector());
- nextmap.get(fnprev).add(fn);
- prevmap.get(fn).add(fnprev);
- }
+ HashSet<FlatNode> myset=new HashSet<FlatNode>();
+ for(int i=0; i<fn.numPrev(); i++) {
+ if (map.containsKey(fn.getPrev(i)))
+ myset.addAll(map.get(fn.getPrev(i)));
+ }
+ if (!prevmap.containsKey(fn))
+ prevmap.put(fn, new Vector());
+ for(Iterator<FlatNode> it2=myset.iterator(); it2.hasNext(); ) {
+ FlatNode fnprev=it2.next();
+ if (!nextmap.containsKey(fnprev))
+ nextmap.put(fnprev, new Vector());
+ nextmap.get(fnprev).add(fn);
+ prevmap.get(fn).add(fnprev);
+ }
}
}
}
mergeAgain=false;
HashMap<Pair<SMFEState, FieldDescriptor>, Set<SMFEState>> revMap=buildReverse(backMap);
for(Map.Entry<Pair<SMFEState,FieldDescriptor>, Set<SMFEState>> entry : revMap.entrySet()) {
- if (entry.getValue().size()>1) {
- SMFEState first=null;
- for(SMFEState state : entry.getValue()) {
- if (removedStates.contains(state))
- continue;
- if (first==null) {
- first=state;
- } else {
- mergeAgain=true;
- System.out.println("MERGING:"+first+" and "+state);
- //Make sure we don't merge the initial state someplace else
- if (state==sm.initialState) {
- state=first;
- first=sm.initialState;
- }
- mergeTwoStates(first, state, backMap);
- removedStates.add(state);
- sm.fn2state.remove(state.whereDefined);
- }
- }
- }
+ if (entry.getValue().size()>1) {
+ SMFEState first=null;
+ for(SMFEState state : entry.getValue()) {
+ if (removedStates.contains(state))
+ continue;
+ if (first==null) {
+ first=state;
+ } else {
+ mergeAgain=true;
+ System.out.println("MERGING:"+first+" and "+state);
+ //Make sure we don't merge the initial state someplace else
+ if (state==sm.initialState) {
+ state=first;
+ first=sm.initialState;
+ }
+ mergeTwoStates(first, state, backMap);
+ removedStates.add(state);
+ sm.fn2state.remove(state.whereDefined);
+ }
+ }
+ }
}
} while(mergeAgain);
}
for(Map.Entry<SMFEState, Set<Pair<SMFEState, FieldDescriptor>>>entry : backMap.entrySet()) {
SMFEState state=entry.getKey();
for(Pair<SMFEState, FieldDescriptor> pair : entry.getValue()) {
- if (!revMap.containsKey(pair))
- revMap.put(pair, new HashSet<SMFEState>());
- revMap.get(pair).add(state);
+ if (!revMap.containsKey(pair))
+ revMap.put(pair, new HashSet<SMFEState>());
+ revMap.get(pair).add(state);
}
}
return revMap;
Effect e=entry.getKey();
Set<SMFEState> states=entry.getValue();
if (state1.e2states.containsKey(e)) {
- for(SMFEState statetoadd : states) {
- if (!state1.e2states.get(e).add(statetoadd)) {
- //already added...reduce reference count
- statetoadd.refCount--;
- }
- }
+ for(SMFEState statetoadd : states) {
+ if (!state1.e2states.get(e).add(statetoadd)) {
+ //already added...reduce reference count
+ statetoadd.refCount--;
+ }
+ }
} else {
- state1.e2states.put(e, states);
+ state1.e2states.put(e, states);
}
Set<SMFEState> states1=state1.e2states.get(e);
//move now-self edges
if (states1.contains(state2)) {
- states1.remove(state2);
- states1.add(state1);
+ states1.remove(state2);
+ states1.add(state1);
}
//fix up the backmap of the edges we point to
for(SMFEState st : states1) {
- HashSet<Pair<SMFEState, FieldDescriptor>> toRemove=new HashSet<Pair<SMFEState, FieldDescriptor>>();
- HashSet<Pair<SMFEState, FieldDescriptor>> toAdd=new HashSet<Pair<SMFEState, FieldDescriptor>>();
- for(Pair<SMFEState, FieldDescriptor> backpair : backMap.get(st)) {
- if (backpair.getFirst()==state2) {
- Pair<SMFEState, FieldDescriptor> newpair=new Pair<SMFEState, FieldDescriptor>(state1, backpair.getSecond());
- toRemove.add(backpair);
- toAdd.add(newpair);
- }
- }
- backMap.get(st).removeAll(toRemove);
- backMap.get(st).addAll(toAdd);
+ HashSet<Pair<SMFEState, FieldDescriptor>> toRemove=new HashSet<Pair<SMFEState, FieldDescriptor>>();
+ HashSet<Pair<SMFEState, FieldDescriptor>> toAdd=new HashSet<Pair<SMFEState, FieldDescriptor>>();
+ for(Pair<SMFEState, FieldDescriptor> backpair : backMap.get(st)) {
+ if (backpair.getFirst()==state2) {
+ Pair<SMFEState, FieldDescriptor> newpair=new Pair<SMFEState, FieldDescriptor>(state1, backpair.getSecond());
+ toRemove.add(backpair);
+ toAdd.add(newpair);
+ }
+ }
+ backMap.get(st).removeAll(toRemove);
+ backMap.get(st).addAll(toAdd);
}
}
for(Pair<SMFEState,FieldDescriptor> fromStatePair : backMap.get(state2)) {
SMFEState fromState=fromStatePair.getFirst();
for(Map.Entry<Effect, Set<SMFEState>> fromEntry : fromState.e2states.entrySet()) {
- Effect e=fromEntry.getKey();
- Set<SMFEState> states=fromEntry.getValue();
- if (states.contains(state2)) {
- states.remove(state2);
- if(states.add(state1) && !fromState.equals(state2)) {
- state1.refCount++;
- }
- }
+ Effect e=fromEntry.getKey();
+ Set<SMFEState> states=fromEntry.getValue();
+ if (states.contains(state2)) {
+ states.remove(state2);
+ if(states.add(state1) && !fromState.equals(state2)) {
+ state1.refCount++;
+ }
+ }
}
}
//Clear out unreachable state's backmap
FlatNode fn=fnit.next();
SMFEState state=sm.fn2state.get(fn);
for(Iterator<Effect> efit=state.effects.iterator(); efit.hasNext(); ) {
- Effect e=efit.next();
- //Is it a conflicting effecting
- if (state.getConflicts().contains(e))
- continue;
- //Does it still have transitions
- if (state.e2states.containsKey(e))
- continue;
- //If no to both, remove it
- efit.remove();
+ Effect e=efit.next();
+ //Is it a conflicting effecting
+ if (state.getConflicts().contains(e))
+ continue;
+ //Does it still have transitions
+ if (state.e2states.containsKey(e))
+ continue;
+ //If no to both, remove it
+ efit.remove();
}
}
}
FlatNode fn=fnit.next();
SMFEState state=sm.fn2state.get(fn);
if (canReachConflicts.contains(state)) {
- for(Iterator<Effect> efit=state.e2states.keySet().iterator(); efit.hasNext(); ) {
- Effect e=efit.next();
- Set<SMFEState> stateset=state.e2states.get(e);
- for(Iterator<SMFEState> stit=stateset.iterator(); stit.hasNext(); ) {
- SMFEState tostate=stit.next();
- if(!canReachConflicts.contains(tostate))
- stit.remove();
- }
- if (stateset.isEmpty())
- efit.remove();
- }
+ for(Iterator<Effect> efit=state.e2states.keySet().iterator(); efit.hasNext(); ) {
+ Effect e=efit.next();
+ Set<SMFEState> stateset=state.e2states.get(e);
+ for(Iterator<SMFEState> stit=stateset.iterator(); stit.hasNext(); ) {
+ SMFEState tostate=stit.next();
+ if(!canReachConflicts.contains(tostate))
+ stit.remove();
+ }
+ if (stateset.isEmpty())
+ efit.remove();
+ }
} else {
- fnit.remove();
+ fnit.remove();
}
}
}
while(!toprocess.isEmpty()) {
SMFEState state=toprocess.pop();
if (!state.getConflicts().isEmpty()&&conflictStates!=null) {
- conflictStates.add(state);
+ conflictStates.add(state);
}
for(Effect e : state.getEffectsAllowed()) {
- for(SMFEState stateout : state.transitionsTo(e)) {
- if (!backMap.containsKey(stateout)) {
- toprocess.add(stateout);
- backMap.put(stateout, new HashSet<Pair<SMFEState,FieldDescriptor>>());
- }
- Pair<SMFEState, FieldDescriptor> p=new Pair<SMFEState, FieldDescriptor>(state, e.getField());
- backMap.get(stateout).add(p);
- }
+ for(SMFEState stateout : state.transitionsTo(e)) {
+ if (!backMap.containsKey(stateout)) {
+ toprocess.add(stateout);
+ backMap.put(stateout, new HashSet<Pair<SMFEState,FieldDescriptor>>());
+ }
+ Pair<SMFEState, FieldDescriptor> p=new Pair<SMFEState, FieldDescriptor>(state, e.getField());
+ backMap.get(stateout).add(p);
+ }
}
}
return backMap;
SMFEState state=toprocess.pop();
for(Pair<SMFEState,FieldDescriptor> instatepair : backMap.get(state)) {
- SMFEState instate=instatepair.getFirst();
- if (!canReachConflicts.contains(instate)) {
- toprocess.add(instate);
- canReachConflicts.add(instate);
- }
+ SMFEState instate=instatepair.getFirst();
+ if (!canReachConflicts.contains(instate)) {
+ toprocess.add(instate);
+ canReachConflicts.add(instate);
+ }
}
}
return canReachConflicts;
StateMachineForEffects sm=bsm.getStateMachine(machinePair);
Set<FlatSESEEnterNode> taskSet=taskAnalysis.getPossibleExecutingRBlocks(fn);
for(FlatSESEEnterNode sese : taskSet) {
- if (!groupMap.containsKey(sese))
- groupMap.put(sese, new HashSet<StateMachineForEffects>());
- groupMap.get(sese).add(sm);
+ if (!groupMap.containsKey(sese))
+ groupMap.put(sese, new HashSet<StateMachineForEffects>());
+ groupMap.get(sese).add(sm);
}
}
}
StateMachineForEffects sm=bsm.getStateMachine(machinePair);
Set<FlatSESEEnterNode> taskSet=taskAnalysis.getPossibleExecutingRBlocks(fn);
for(FlatSESEEnterNode sese : taskSet) {
- Set<StateMachineForEffects> smgroup=groupMap.get(sese);
- computeConflictingEffects(sm, smgroup);
+ Set<StateMachineForEffects> smgroup=groupMap.get(sese);
+ computeConflictingEffects(sm, smgroup);
}
}
}
boolean isStall=sm.getStallorSESE().kind()!=FKind.FlatSESEEnterNode;
for(SMFEState state : sm.getStates()) {
for(Effect e : state.getEffectsAllowed()) {
- Alloc a=e.getAffectedAllocSite();
- FieldDescriptor fd=e.getField();
- int type=e.getType();
- boolean hasConflict=false;
- if (!isStall&&Effect.isWrite(type)) {
- hasConflict=true;
- } else {
- for(StateMachineForEffects othersm : smgroup) {
- boolean otherIsStall=othersm.getStallorSESE().kind()!=FKind.FlatSESEEnterNode;
- //Stall sites can't conflict with each other
- if (isStall&&otherIsStall) continue;
-
- int effectType=othersm.getEffects(a, fd);
- if (Effect.isWrite(type)&&effectType!=0) {
- //Original effect is a write and we have some effect on the same field/alloc site
- hasConflict=true;
- break;
- }
- if (Effect.isWrite(effectType)) {
- //We are a write
- hasConflict=true;
- break;
- }
- }
- }
- if (hasConflict) {
- state.addConflict(e);
- }
+ Alloc a=e.getAffectedAllocSite();
+ FieldDescriptor fd=e.getField();
+ int type=e.getType();
+ boolean hasConflict=false;
+ if (!isStall&&Effect.isWrite(type)) {
+ hasConflict=true;
+ } else {
+ for(StateMachineForEffects othersm : smgroup) {
+ boolean otherIsStall=othersm.getStallorSESE().kind()!=FKind.FlatSESEEnterNode;
+ //Stall sites can't conflict with each other
+ if (isStall&&otherIsStall) continue;
+
+ int effectType=othersm.getEffects(a, fd);
+ if (Effect.isWrite(type)&&effectType!=0) {
+ //Original effect is a write and we have some effect on the same field/alloc site
+ hasConflict=true;
+ break;
+ }
+ if (Effect.isWrite(effectType)) {
+ //We are a write
+ hasConflict=true;
+ break;
+ }
+ }
+ }
+ if (hasConflict) {
+ state.addConflict(e);
+ }
}
}
}
if( (effectType & Effect.read) != 0 &&
(effectType & Effect.write) != 0
) {
- allocAndFieldRW.add(new Effect(af.getFirst(),
- Effect.read,
- af.getSecond()
- )
- );
+ allocAndFieldRW.add(new Effect(af.getFirst(),
+ Effect.read,
+ af.getSecond()
+ )
+ );
}
}
// as... POSSIBLY EVIL!!!!!
for( SMFEState state : sm.getStates() ) {
for( Effect effect : state.getTransitionEffects() ) {
- if( allocAndFieldRW.contains(effect) ) {
- sm.addPossiblyEvilEffect(effect);
- }
+ if( allocAndFieldRW.contains(effect) ) {
+ sm.addPossiblyEvilEffect(effect);
+ }
}
}
}
if( inherent == null ) {
if( markForAnalysis ) {
- inherent =
- Canonical.changePredsTo(
- ReachSet.factory(
- ReachState.factory(
- ReachTuple.factory(id,
- !isSingleObject,
- ReachTuple.ARITY_ONE,
- false // out-of-context
- )
- )
- ),
- predsTrue
- );
+ inherent =
+ Canonical.changePredsTo(
+ ReachSet.factory(
+ ReachState.factory(
+ ReachTuple.factory(id,
+ !isSingleObject,
+ ReachTuple.ARITY_ONE,
+ false // out-of-context
+ )
+ )
+ ),
+ predsTrue
+ );
} else {
- inherent = rsetWithEmptyState;
+ inherent = rsetWithEmptyState;
}
}
(edge.typeEquals(type) && edge.fieldEquals(field))
) {
- HeapRegionNode referencee = edge.getDst();
+ HeapRegionNode referencee = edge.getDst();
- removeRefEdge(referencer,
- referencee,
- edge.getType(),
- edge.getField() );
+ removeRefEdge(referencer,
+ referencee,
+ edge.getType(),
+ edge.getField() );
- atLeastOneEdgeRemoved = true;
+ atLeastOneEdgeRemoved = true;
}
}
(edge.typeEquals(type) && edge.fieldEquals(field))
) {
- RefSrcNode referencer = edge.getSrc();
+ RefSrcNode referencer = edge.getSrc();
- removeRefEdge(referencer,
- referencee,
- edge.getType(),
- edge.getField() );
+ removeRefEdge(referencer,
+ referencee,
+ edge.getType(),
+ edge.getField() );
}
}
}
RefEdge edge = i.next();
RefSrcNode referencer = edge.getSrc();
if( !(referencer instanceof VariableNode) ) {
- removeRefEdge(referencer,
- referencee,
- edge.getType(),
- edge.getField() );
+ removeRefEdge(referencer,
+ referencee,
+ edge.getType(),
+ edge.getField() );
}
}
}
RefEdge edgeNew = edgeY.copy();
if( !isSuperiorType(x.getType(), edgeY.getType() ) ) {
- impossibleEdges.add(edgeY);
- continue;
+ impossibleEdges.add(edgeY);
+ continue;
}
edgeNew.setSrc(lnX);
if( tdCast == null ) {
- edgeNew.setType(mostSpecificType(y.getType(),
- edgeY.getType(),
- referencee.getType()
- )
- );
+ edgeNew.setType(mostSpecificType(y.getType(),
+ edgeY.getType(),
+ referencee.getType()
+ )
+ );
} else {
- edgeNew.setType(mostSpecificType(y.getType(),
- edgeY.getType(),
- referencee.getType(),
- tdCast
- )
- );
+ edgeNew.setType(mostSpecificType(y.getType(),
+ edgeY.getType(),
+ referencee.getType(),
+ tdCast
+ )
+ );
}
edgeNew.setField(null);
Iterator<RefEdge> itrHrnFhrn = hrnY.iteratorToReferencees();
while( itrHrnFhrn.hasNext() ) {
- RefEdge edgeHrn = itrHrnFhrn.next();
- HeapRegionNode hrnHrn = edgeHrn.getDst();
- ReachSet betaHrn = edgeHrn.getBeta();
-
- // prune edges that are not a matching field
- if( edgeHrn.getType() != null &&
- !edgeHrn.getField().equals(f.getSymbol() )
- ) {
- continue;
- }
-
- // check for impossible edges
- if( !isSuperiorType(x.getType(), edgeHrn.getType() ) ) {
- impossibleEdges.add(edgeHrn);
- continue;
- }
-
- TypeDescriptor tdNewEdge =
- mostSpecificType(edgeHrn.getType(),
- hrnHrn.getType()
- );
-
- TaintSet taints = Canonical.unionORpreds(edgeHrn.getTaints(),
- edgeY.getTaints()
- );
- if( state.RCR ) {
- // the DFJ way to generate taints changes for field statements
- taints = Canonical.changeWhereDefined(taints,
- currentProgramPoint);
- }
-
- RefEdge edgeNew = new RefEdge(lnX,
- hrnHrn,
- tdNewEdge,
- null,
- Canonical.intersection(betaY, betaHrn),
- predsTrue,
- taints
- );
-
- addEdgeOrMergeWithExisting(edgeNew);
+ RefEdge edgeHrn = itrHrnFhrn.next();
+ HeapRegionNode hrnHrn = edgeHrn.getDst();
+ ReachSet betaHrn = edgeHrn.getBeta();
+
+ // prune edges that are not a matching field
+ if( edgeHrn.getType() != null &&
+ !edgeHrn.getField().equals(f.getSymbol() )
+ ) {
+ continue;
+ }
+
+ // check for impossible edges
+ if( !isSuperiorType(x.getType(), edgeHrn.getType() ) ) {
+ impossibleEdges.add(edgeHrn);
+ continue;
+ }
+
+ TypeDescriptor tdNewEdge =
+ mostSpecificType(edgeHrn.getType(),
+ hrnHrn.getType()
+ );
+
+ TaintSet taints = Canonical.unionORpreds(edgeHrn.getTaints(),
+ edgeY.getTaints()
+ );
+ if( state.RCR ) {
+ // the DFJ way to generate taints changes for field statements
+ taints = Canonical.changeWhereDefined(taints,
+ currentProgramPoint);
+ }
+
+ RefEdge edgeNew = new RefEdge(lnX,
+ hrnHrn,
+ tdNewEdge,
+ null,
+ Canonical.intersection(betaY, betaHrn),
+ predsTrue,
+ taints
+ );
+
+ addEdgeOrMergeWithExisting(edgeNew);
}
}
// you must global sweep to clean up broken reachability
if( !impossibleEdges.isEmpty() ) {
if( !DISABLE_GLOBAL_SWEEP ) {
- globalSweep();
+ globalSweep();
}
}
(hrnX.isSingleObject() && lnX.getNumReferencees() == 1) // case 2
)
) {
- if( !DISABLE_STRONG_UPDATES ) {
- strongUpdateCond = true;
-
- boolean atLeastOne =
- clearRefEdgesFrom(hrnX,
- f.getType(),
- f.getSymbol(),
- false);
- if( atLeastOne ) {
- edgeRemovedByStrongUpdate = true;
- }
- }
+ if( !DISABLE_STRONG_UPDATES ) {
+ strongUpdateCond = true;
+
+ boolean atLeastOne =
+ clearRefEdgesFrom(hrnX,
+ f.getType(),
+ f.getSymbol(),
+ false);
+ if( atLeastOne ) {
+ edgeRemovedByStrongUpdate = true;
+ }
+ }
}
}
Iterator<RefEdge> itrYhrn = lnY.iteratorToReferencees();
while( itrYhrn.hasNext() ) {
- RefEdge edgeY = itrYhrn.next();
- HeapRegionNode hrnY = edgeY.getDst();
- ReachSet O = edgeY.getBeta();
-
- // check for impossible edges
- if( !isSuperiorType(f.getType(), edgeY.getType() ) ) {
- impossibleEdges.add(edgeY);
- continue;
- }
-
- // propagate tokens over nodes starting from hrnSrc, and it will
- // take care of propagating back up edges from any touched nodes
- ChangeSet Cy = Canonical.unionUpArityToChangeSet(O, R);
- propagateTokensOverNodes(hrnY, Cy, nodesWithNewAlpha, edgesWithNewBeta);
-
- // then propagate back just up the edges from hrn
- ChangeSet Cx = Canonical.unionUpArityToChangeSet(R, O);
- HashSet<RefEdge> todoEdges = new HashSet<RefEdge>();
-
- Hashtable<RefEdge, ChangeSet> edgePlannedChanges =
- new Hashtable<RefEdge, ChangeSet>();
-
- Iterator<RefEdge> referItr = hrnX.iteratorToReferencers();
- while( referItr.hasNext() ) {
- RefEdge edgeUpstream = referItr.next();
- todoEdges.add(edgeUpstream);
- edgePlannedChanges.put(edgeUpstream, Cx);
- }
-
- propagateTokensOverEdges(todoEdges,
- edgePlannedChanges,
- edgesWithNewBeta);
+ RefEdge edgeY = itrYhrn.next();
+ HeapRegionNode hrnY = edgeY.getDst();
+ ReachSet O = edgeY.getBeta();
+
+ // check for impossible edges
+ if( !isSuperiorType(f.getType(), edgeY.getType() ) ) {
+ impossibleEdges.add(edgeY);
+ continue;
+ }
+
+ // propagate tokens over nodes starting from hrnSrc, and it will
+ // take care of propagating back up edges from any touched nodes
+ ChangeSet Cy = Canonical.unionUpArityToChangeSet(O, R);
+ propagateTokensOverNodes(hrnY, Cy, nodesWithNewAlpha, edgesWithNewBeta);
+
+ // then propagate back just up the edges from hrn
+ ChangeSet Cx = Canonical.unionUpArityToChangeSet(R, O);
+ HashSet<RefEdge> todoEdges = new HashSet<RefEdge>();
+
+ Hashtable<RefEdge, ChangeSet> edgePlannedChanges =
+ new Hashtable<RefEdge, ChangeSet>();
+
+ Iterator<RefEdge> referItr = hrnX.iteratorToReferencers();
+ while( referItr.hasNext() ) {
+ RefEdge edgeUpstream = referItr.next();
+ todoEdges.add(edgeUpstream);
+ edgePlannedChanges.put(edgeUpstream, Cx);
+ }
+
+ propagateTokensOverEdges(todoEdges,
+ edgePlannedChanges,
+ edgesWithNewBeta);
}
}
Iterator<RefEdge> itrYhrn = lnY.iteratorToReferencees();
while( itrYhrn.hasNext() ) {
- RefEdge edgeY = itrYhrn.next();
- HeapRegionNode hrnY = edgeY.getDst();
-
- // skip impossible edges here, we already marked them
- // when computing reachability propagations above
- if( !isSuperiorType(f.getType(), edgeY.getType() ) ) {
- continue;
- }
-
- // prepare the new reference edge hrnX.f -> hrnY
- TypeDescriptor tdNewEdge =
- mostSpecificType(y.getType(),
- edgeY.getType(),
- hrnY.getType()
- );
-
- TaintSet taints = edgeY.getTaints();
-
- if( state.RCR ) {
- // the DFJ way to generate taints changes for field statements
- taints = Canonical.changeWhereDefined(taints,
- currentProgramPoint);
- }
-
- RefEdge edgeNew =
- new RefEdge(hrnX,
- hrnY,
- tdNewEdge,
- f.getSymbol(),
- Canonical.changePredsTo(
- Canonical.pruneBy(edgeY.getBeta(),
- hrnX.getAlpha()
- ),
- predsTrue
- ),
- predsTrue,
- taints
- );
-
- addEdgeOrMergeWithExisting(edgeNew);
+ RefEdge edgeY = itrYhrn.next();
+ HeapRegionNode hrnY = edgeY.getDst();
+
+ // skip impossible edges here, we already marked them
+ // when computing reachability propagations above
+ if( !isSuperiorType(f.getType(), edgeY.getType() ) ) {
+ continue;
+ }
+
+ // prepare the new reference edge hrnX.f -> hrnY
+ TypeDescriptor tdNewEdge =
+ mostSpecificType(y.getType(),
+ edgeY.getType(),
+ hrnY.getType()
+ );
+
+ TaintSet taints = edgeY.getTaints();
+
+ if( state.RCR ) {
+ // the DFJ way to generate taints changes for field statements
+ taints = Canonical.changeWhereDefined(taints,
+ currentProgramPoint);
+ }
+
+ RefEdge edgeNew =
+ new RefEdge(hrnX,
+ hrnY,
+ tdNewEdge,
+ f.getSymbol(),
+ Canonical.changePredsTo(
+ Canonical.pruneBy(edgeY.getBeta(),
+ hrnX.getAlpha()
+ ),
+ predsTrue
+ ),
+ predsTrue,
+ taints
+ );
+
+ addEdgeOrMergeWithExisting(edgeNew);
}
}
// reachability with a global sweep
if( edgeRemovedByStrongUpdate || !impossibleEdges.isEmpty() ) {
if( !DISABLE_GLOBAL_SWEEP ) {
- globalSweep();
+ globalSweep();
}
}
// only do the transfer if the i-1 node exists
Integer idImin1th = as.getIthOldest(i - 1);
if( id2hrn.containsKey(idImin1th) ) {
- HeapRegionNode hrnImin1 = id2hrn.get(idImin1th);
- if( hrnImin1.isWiped() ) {
- // there is no info on this node, just skip
- continue;
- }
+ HeapRegionNode hrnImin1 = id2hrn.get(idImin1th);
+ if( hrnImin1.isWiped() ) {
+ // there is no info on this node, just skip
+ continue;
+ }
- // either retrieve or make target of transfer
- HeapRegionNode hrnI = getIthNode(as, i, false);
+ // either retrieve or make target of transfer
+ HeapRegionNode hrnI = getIthNode(as, i, false);
- transferOnto(hrnImin1, hrnI);
+ transferOnto(hrnImin1, hrnI);
}
}
Iterator<RefEdge> itrEdges = hrnToAge.iteratorToReferencers();
while( itrEdges.hasNext() ) {
- ageTuplesFrom(as, itrEdges.next() );
+ ageTuplesFrom(as, itrEdges.next() );
}
}
);
if( edgeSummary == null ) {
- // the merge is trivial, nothing to be done
- addRefEdge(hrnSummary, hrnReferencee, edgeMerged);
+ // the merge is trivial, nothing to be done
+ addRefEdge(hrnSummary, hrnReferencee, edgeMerged);
} else {
- // otherwise an edge from the referencer to hrnSummary exists already
- // and the edge referencer->hrn should be merged with it
- edgeSummary.setBeta(
- Canonical.unionORpreds(edgeMerged.getBeta(),
- edgeSummary.getBeta()
- )
- );
- edgeSummary.setPreds(
- Canonical.join(edgeMerged.getPreds(),
- edgeSummary.getPreds()
- )
- );
+ // otherwise an edge from the referencer to hrnSummary exists already
+ // and the edge referencer->hrn should be merged with it
+ edgeSummary.setBeta(
+ Canonical.unionORpreds(edgeMerged.getBeta(),
+ edgeSummary.getBeta()
+ )
+ );
+ edgeSummary.setPreds(
+ Canonical.join(edgeMerged.getPreds(),
+ edgeSummary.getPreds()
+ )
+ );
}
}
);
if( edgeSummary == null ) {
- // the merge is trivial, nothing to be done
- addRefEdge(onReferencer, hrnSummary, edgeMerged);
+ // the merge is trivial, nothing to be done
+ addRefEdge(onReferencer, hrnSummary, edgeMerged);
} else {
- // otherwise an edge from the referencer to alpha_S exists already
- // and the edge referencer->alpha_K should be merged with it
- edgeSummary.setBeta(
- Canonical.unionORpreds(edgeMerged.getBeta(),
- edgeSummary.getBeta()
- )
- );
- edgeSummary.setPreds(
- Canonical.join(edgeMerged.getPreds(),
- edgeSummary.getPreds()
- )
- );
+ // otherwise an edge from the referencer to alpha_S exists already
+ // and the edge referencer->alpha_K should be merged with it
+ edgeSummary.setBeta(
+ Canonical.unionORpreds(edgeMerged.getBeta(),
+ edgeSummary.getBeta()
+ )
+ );
+ edgeSummary.setPreds(
+ Canonical.join(edgeMerged.getPreds(),
+ edgeSummary.getPreds()
+ )
+ );
}
}
Iterator<RefEdge> referItr = n.iteratorToReferencers();
while( referItr.hasNext() ) {
- RefEdge edge = referItr.next();
- todoEdges.add(edge);
-
- if( !edgePlannedChanges.containsKey(edge) ) {
- edgePlannedChanges.put(edge,
- ChangeSet.factory()
- );
- }
-
- edgePlannedChanges.put(edge,
- Canonical.union(edgePlannedChanges.get(edge),
- C
- )
- );
+ RefEdge edge = referItr.next();
+ todoEdges.add(edge);
+
+ if( !edgePlannedChanges.containsKey(edge) ) {
+ edgePlannedChanges.put(edge,
+ ChangeSet.factory()
+ );
+ }
+
+ edgePlannedChanges.put(edge,
+ Canonical.union(edgePlannedChanges.get(edge),
+ C
+ )
+ );
}
Iterator<RefEdge> refeeItr = n.iteratorToReferencees();
while( refeeItr.hasNext() ) {
- RefEdge edgeF = refeeItr.next();
- HeapRegionNode m = edgeF.getDst();
-
- ChangeSet changesToPass = ChangeSet.factory();
-
- Iterator<ChangeTuple> itrCprime = C.iterator();
- while( itrCprime.hasNext() ) {
- ChangeTuple c = itrCprime.next();
- if( edgeF.getBeta().containsIgnorePreds(c.getStateToMatch() )
- != null
- ) {
- changesToPass = Canonical.add(changesToPass, c);
- }
- }
-
- if( !changesToPass.isEmpty() ) {
- if( !nodePlannedChanges.containsKey(m) ) {
- nodePlannedChanges.put(m, ChangeSet.factory() );
- }
-
- ChangeSet currentChanges = nodePlannedChanges.get(m);
-
- if( !changesToPass.isSubset(currentChanges) ) {
-
- nodePlannedChanges.put(m,
- Canonical.union(currentChanges,
- changesToPass
- )
- );
- todoNodes.add(m);
- }
- }
+ RefEdge edgeF = refeeItr.next();
+ HeapRegionNode m = edgeF.getDst();
+
+ ChangeSet changesToPass = ChangeSet.factory();
+
+ Iterator<ChangeTuple> itrCprime = C.iterator();
+ while( itrCprime.hasNext() ) {
+ ChangeTuple c = itrCprime.next();
+ if( edgeF.getBeta().containsIgnorePreds(c.getStateToMatch() )
+ != null
+ ) {
+ changesToPass = Canonical.add(changesToPass, c);
+ }
+ }
+
+ if( !changesToPass.isEmpty() ) {
+ if( !nodePlannedChanges.containsKey(m) ) {
+ nodePlannedChanges.put(m, ChangeSet.factory() );
+ }
+
+ ChangeSet currentChanges = nodePlannedChanges.get(m);
+
+ if( !changesToPass.isSubset(currentChanges) ) {
+
+ nodePlannedChanges.put(m,
+ Canonical.union(currentChanges,
+ changesToPass
+ )
+ );
+ todoNodes.add(m);
+ }
+ }
}
todoNodes.remove(n);
todoEdges.remove(edgeE);
if( !edgePlannedChanges.containsKey(edgeE) ) {
- edgePlannedChanges.put(edgeE,
- ChangeSet.factory()
- );
+ edgePlannedChanges.put(edgeE,
+ ChangeSet.factory()
+ );
}
ChangeSet C = edgePlannedChanges.get(edgeE);
Iterator<ChangeTuple> itrC = C.iterator();
while( itrC.hasNext() ) {
- ChangeTuple c = itrC.next();
- if( edgeE.getBeta().containsIgnorePreds(c.getStateToMatch() )
- != null
- ) {
- changesToPass = Canonical.add(changesToPass, c);
- }
+ ChangeTuple c = itrC.next();
+ if( edgeE.getBeta().containsIgnorePreds(c.getStateToMatch() )
+ != null
+ ) {
+ changesToPass = Canonical.add(changesToPass, c);
+ }
}
RefSrcNode rsn = edgeE.getSrc();
if( !changesToPass.isEmpty() && rsn instanceof HeapRegionNode ) {
- HeapRegionNode n = (HeapRegionNode) rsn;
-
- Iterator<RefEdge> referItr = n.iteratorToReferencers();
- while( referItr.hasNext() ) {
- RefEdge edgeF = referItr.next();
-
- if( !edgePlannedChanges.containsKey(edgeF) ) {
- edgePlannedChanges.put(edgeF,
- ChangeSet.factory()
- );
- }
-
- ChangeSet currentChanges = edgePlannedChanges.get(edgeF);
-
- if( !changesToPass.isSubset(currentChanges) ) {
- todoEdges.add(edgeF);
- edgePlannedChanges.put(edgeF,
- Canonical.union(currentChanges,
- changesToPass
- )
- );
- }
- }
+ HeapRegionNode n = (HeapRegionNode) rsn;
+
+ Iterator<RefEdge> referItr = n.iteratorToReferencers();
+ while( referItr.hasNext() ) {
+ RefEdge edgeF = referItr.next();
+
+ if( !edgePlannedChanges.containsKey(edgeF) ) {
+ edgePlannedChanges.put(edgeF,
+ ChangeSet.factory()
+ );
+ }
+
+ ChangeSet currentChanges = edgePlannedChanges.get(edgeF);
+
+ if( !changesToPass.isSubset(currentChanges) ) {
+ todoEdges.add(edgeF);
+ edgePlannedChanges.put(edgeF,
+ Canonical.union(currentChanges,
+ changesToPass
+ )
+ );
+ }
+ }
}
}
// use this where defined flatnode to support RCR/DFJ
FlatNode whereDefined = null;
if( state.RCR ) {
- whereDefined = sese;
+ whereDefined = sese;
}
// in-set var taints should NOT propagate back into callers
Iterator<RefEdge> reItr = hrn.iteratorToReferencers();
while( reItr.hasNext() ) {
- RefEdge re = reItr.next();
+ RefEdge re = reItr.next();
- re.setTaints(Canonical.removeInContextTaints(re.getTaints(),
- sese
- )
- );
+ re.setTaints(Canonical.removeInContextTaints(re.getTaints(),
+ sese
+ )
+ );
}
}
}
Iterator<RefEdge> reItr = hrn.iteratorToReferencers();
while( reItr.hasNext() ) {
- RefEdge re = reItr.next();
+ RefEdge re = reItr.next();
- re.setTaints(Canonical.removeStallSiteTaints(re.getTaints()
- )
- );
+ re.setTaints(Canonical.removeStallSiteTaints(re.getTaints()
+ )
+ );
}
}
}
assert belongsToThis(re.getDst() );
if( !(re.getSrc() instanceof HeapRegionNode) ) {
- continue;
+ continue;
}
HeapRegionNode hrnSrc = (HeapRegionNode) re.getSrc();
if( !hrnSrc.isOutOfContext() ) {
- continue;
+ continue;
}
if( srcType == null ) {
- if( hrnSrc.getType() != null ) {
- continue;
- }
+ if( hrnSrc.getType() != null ) {
+ continue;
+ }
} else {
- if( !srcType.equals(hrnSrc.getType() ) ) {
- continue;
- }
+ if( !srcType.equals(hrnSrc.getType() ) ) {
+ continue;
+ }
}
if( !re.typeEquals(refType) ) {
- continue;
+ continue;
}
if( !re.fieldEquals(refField) ) {
- continue;
+ continue;
}
// tada! We found it!
Iterator<AllocSite> asItr = allocSites.iterator();
while( asItr.hasNext() ) {
- AllocSite as = asItr.next();
-
- ReachState stateNew = ReachState.factory();
- Iterator<ReachTuple> rtItr = stateCallee.iterator();
- while( rtItr.hasNext() ) {
- ReachTuple rt = rtItr.next();
-
- // only translate this tuple if it is
- // in the out-callee-context bag
- HrnIdOoc hio = new HrnIdOoc(rt.getHrnID(),
- rt.isOutOfContext()
- );
- if( !oocHrnIdOoc2callee.contains(hio) ) {
- stateNew = Canonical.addUpArity(stateNew, rt);
- continue;
- }
-
- int age = as.getAgeCategory(rt.getHrnID() );
-
- // this is the current mapping, where 0, 1, 2S were allocated
- // in the current context, 0?, 1? and 2S? were allocated in a
- // previous context, and we're translating to a future context
- //
- // 0 -> 0?
- // 1 -> 1?
- // 2S -> 2S?
- // 2S* -> 2S?*
- //
- // 0? -> 2S?
- // 1? -> 2S?
- // 2S? -> 2S?
- // 2S?* -> 2S?*
-
- if( age == AllocSite.AGE_notInThisSite ) {
- // things not from the site just go back in
- stateNew = Canonical.addUpArity(stateNew, rt);
-
- } else if( age == AllocSite.AGE_summary ||
- rt.isOutOfContext()
- ) {
-
- stateNew = Canonical.addUpArity(stateNew,
- ReachTuple.factory(as.getSummary(),
- true, // multi
- rt.getArity(),
- true // out-of-context
- )
- );
-
- } else {
- // otherwise everything else just goes to an out-of-context
- // version, everything else the same
- Integer I = as.getAge(rt.getHrnID() );
- assert I != null;
-
- assert !rt.isMultiObject();
-
- stateNew = Canonical.addUpArity(stateNew,
- ReachTuple.factory(rt.getHrnID(),
- rt.isMultiObject(), // multi
- rt.getArity(),
- true // out-of-context
- )
- );
- }
- }
-
- stateCallee = stateNew;
+ AllocSite as = asItr.next();
+
+ ReachState stateNew = ReachState.factory();
+ Iterator<ReachTuple> rtItr = stateCallee.iterator();
+ while( rtItr.hasNext() ) {
+ ReachTuple rt = rtItr.next();
+
+ // only translate this tuple if it is
+ // in the out-callee-context bag
+ HrnIdOoc hio = new HrnIdOoc(rt.getHrnID(),
+ rt.isOutOfContext()
+ );
+ if( !oocHrnIdOoc2callee.contains(hio) ) {
+ stateNew = Canonical.addUpArity(stateNew, rt);
+ continue;
+ }
+
+ int age = as.getAgeCategory(rt.getHrnID() );
+
+ // this is the current mapping, where 0, 1, 2S were allocated
+ // in the current context, 0?, 1? and 2S? were allocated in a
+ // previous context, and we're translating to a future context
+ //
+ // 0 -> 0?
+ // 1 -> 1?
+ // 2S -> 2S?
+ // 2S* -> 2S?*
+ //
+ // 0? -> 2S?
+ // 1? -> 2S?
+ // 2S? -> 2S?
+ // 2S?* -> 2S?*
+
+ if( age == AllocSite.AGE_notInThisSite ) {
+ // things not from the site just go back in
+ stateNew = Canonical.addUpArity(stateNew, rt);
+
+ } else if( age == AllocSite.AGE_summary ||
+ rt.isOutOfContext()
+ ) {
+
+ stateNew = Canonical.addUpArity(stateNew,
+ ReachTuple.factory(as.getSummary(),
+ true, // multi
+ rt.getArity(),
+ true // out-of-context
+ )
+ );
+
+ } else {
+ // otherwise everything else just goes to an out-of-context
+ // version, everything else the same
+ Integer I = as.getAge(rt.getHrnID() );
+ assert I != null;
+
+ assert !rt.isMultiObject();
+
+ stateNew = Canonical.addUpArity(stateNew,
+ ReachTuple.factory(rt.getHrnID(),
+ rt.isMultiObject(), // multi
+ rt.getArity(),
+ true // out-of-context
+ )
+ );
+ }
+ }
+
+ stateCallee = stateNew;
}
// make a predicate of the caller graph element
Iterator<ExistPred> predItr = predsNodeOrEdge.iterator();
while( predItr.hasNext() ) {
- ExistPred predNodeOrEdge = predItr.next();
-
- predsWithState =
- Canonical.add(predsWithState,
- ExistPred.factory(predNodeOrEdge.n_hrnID,
- predNodeOrEdge.e_tdSrc,
- predNodeOrEdge.e_hrnSrcID,
- predNodeOrEdge.e_hrnDstID,
- predNodeOrEdge.e_type,
- predNodeOrEdge.e_field,
- stateCallee,
- null,
- predNodeOrEdge.e_srcOutCalleeContext,
- predNodeOrEdge.e_srcOutCallerContext
- )
- );
+ ExistPred predNodeOrEdge = predItr.next();
+
+ predsWithState =
+ Canonical.add(predsWithState,
+ ExistPred.factory(predNodeOrEdge.n_hrnID,
+ predNodeOrEdge.e_tdSrc,
+ predNodeOrEdge.e_hrnSrcID,
+ predNodeOrEdge.e_hrnDstID,
+ predNodeOrEdge.e_type,
+ predNodeOrEdge.e_field,
+ stateCallee,
+ null,
+ predNodeOrEdge.e_srcOutCalleeContext,
+ predNodeOrEdge.e_srcOutCallerContext
+ )
+ );
}
stateCallee = Canonical.changePredsTo(stateCallee,
if( calleeStatesSatisfied.containsKey(stateCallee) ) {
- // starting from one callee state...
- ReachSet rsCaller = ReachSet.factory(stateCallee);
-
- // possibly branch it into many states, which any
- // allocation site might do, so lots of derived states
- Iterator<AllocSite> asItr = allocSites.iterator();
- while( asItr.hasNext() ) {
- AllocSite as = asItr.next();
- rsCaller = Canonical.toCallerContext(rsCaller, as);
- }
-
- // then before adding each derived, now caller-context
- // states to the output, attach the appropriate pred
- // based on the source callee state
- Iterator<ReachState> stateItr = rsCaller.iterator();
- while( stateItr.hasNext() ) {
- ReachState stateCaller = stateItr.next();
- stateCaller = Canonical.attach(stateCaller,
- calleeStatesSatisfied.get(stateCallee)
- );
- out = Canonical.add(out,
- stateCaller
- );
- }
+ // starting from one callee state...
+ ReachSet rsCaller = ReachSet.factory(stateCallee);
+
+ // possibly branch it into many states, which any
+ // allocation site might do, so lots of derived states
+ Iterator<AllocSite> asItr = allocSites.iterator();
+ while( asItr.hasNext() ) {
+ AllocSite as = asItr.next();
+ rsCaller = Canonical.toCallerContext(rsCaller, as);
+ }
+
+ // then before adding each derived, now caller-context
+ // states to the output, attach the appropriate pred
+ // based on the source callee state
+ Iterator<ReachState> stateItr = rsCaller.iterator();
+ while( stateItr.hasNext() ) {
+ ReachState stateCaller = stateItr.next();
+ stateCaller = Canonical.attach(stateCaller,
+ calleeStatesSatisfied.get(stateCallee)
+ );
+ out = Canonical.add(out,
+ stateCaller
+ );
+ }
}
}
Iterator<ExistPred> predItr = predsEdge.iterator();
while( predItr.hasNext() ) {
- ExistPred predEdge = predItr.next();
-
- predsWithTaint =
- Canonical.add(predsWithTaint,
- ExistPred.factory(predEdge.e_tdSrc,
- predEdge.e_hrnSrcID,
- predEdge.e_hrnDstID,
- predEdge.e_type,
- predEdge.e_field,
- null,
- tCaller,
- predEdge.e_srcOutCalleeContext,
- predEdge.e_srcOutCallerContext
- )
- );
+ ExistPred predEdge = predItr.next();
+
+ predsWithTaint =
+ Canonical.add(predsWithTaint,
+ ExistPred.factory(predEdge.e_tdSrc,
+ predEdge.e_hrnSrcID,
+ predEdge.e_hrnDstID,
+ predEdge.e_type,
+ predEdge.e_field,
+ null,
+ tCaller,
+ predEdge.e_srcOutCalleeContext,
+ predEdge.e_srcOutCallerContext
+ )
+ );
}
Taint tCallee = Canonical.changePredsTo(tCaller,
if( calleeTaintsSatisfied.containsKey(tCallee) ) {
- Taint tCaller =
- Canonical.attach(Taint.factory(tCallee.sese,
- tCallee.stallSite,
- tCallee.var,
- tCallee.allocSite,
- tCallee.fnDefined,
- ExistPredSet.factory() ),
- calleeTaintsSatisfied.get(tCallee)
- );
- out = Canonical.add(out,
- tCaller
- );
+ Taint tCaller =
+ Canonical.attach(Taint.factory(tCallee.sese,
+ tCallee.stallSite,
+ tCallee.var,
+ tCallee.allocSite,
+ tCallee.fnDefined,
+ ExistPredSet.factory() ),
+ calleeTaintsSatisfied.get(tCallee)
+ );
+ out = Canonical.add(out,
+ tCaller
+ );
}
}
toVisitInCaller.add(vnArgCaller);
while( !toVisitInCaller.isEmpty() ) {
- RefSrcNode rsnCaller = toVisitInCaller.iterator().next();
- toVisitInCaller.remove(rsnCaller);
- visitedInCaller.add(rsnCaller);
-
- Iterator<RefEdge> itrRefEdges = rsnCaller.iteratorToReferencees();
- while( itrRefEdges.hasNext() ) {
- RefEdge reCaller = itrRefEdges.next();
- HeapRegionNode hrnCaller = reCaller.getDst();
-
- callerNodeIDsCopiedToCallee.add(hrnCaller.getID() );
- reachableCallerNodes.add(hrnCaller);
-
- if( reCaller.getSrc() instanceof HeapRegionNode ) {
- reachableCallerEdges.add(reCaller);
- } else {
- if( rsnCaller.equals(vnArgCaller) ) {
- reachableCallerArgEdges2paramIndex.put(reCaller, i);
- } else {
- oocCallerEdges.add(reCaller);
- }
- }
-
- if( !visitedInCaller.contains(hrnCaller) ) {
- toVisitInCaller.add(hrnCaller);
- }
-
- } // end edge iteration
+ RefSrcNode rsnCaller = toVisitInCaller.iterator().next();
+ toVisitInCaller.remove(rsnCaller);
+ visitedInCaller.add(rsnCaller);
+
+ Iterator<RefEdge> itrRefEdges = rsnCaller.iteratorToReferencees();
+ while( itrRefEdges.hasNext() ) {
+ RefEdge reCaller = itrRefEdges.next();
+ HeapRegionNode hrnCaller = reCaller.getDst();
+
+ callerNodeIDsCopiedToCallee.add(hrnCaller.getID() );
+ reachableCallerNodes.add(hrnCaller);
+
+ if( reCaller.getSrc() instanceof HeapRegionNode ) {
+ reachableCallerEdges.add(reCaller);
+ } else {
+ if( rsnCaller.equals(vnArgCaller) ) {
+ reachableCallerArgEdges2paramIndex.put(reCaller, i);
+ } else {
+ oocCallerEdges.add(reCaller);
+ }
+ }
+
+ if( !visitedInCaller.contains(hrnCaller) ) {
+ toVisitInCaller.add(hrnCaller);
+ }
+
+ } // end edge iteration
} // end visiting heap nodes in caller
} // end iterating over parameters as starting points
Iterator<RefEdge> itrMightCross =
hrnCallerAndInContext.iteratorToReferencers();
while( itrMightCross.hasNext() ) {
- RefEdge edgeMightCross = itrMightCross.next();
-
- RefSrcNode rsnCallerAndOutContext =
- edgeMightCross.getSrc();
-
- if( rsnCallerAndOutContext instanceof VariableNode ) {
- // variables do not have out-of-context reach states,
- // so jump out now
- oocCallerEdges.add(edgeMightCross);
- continue;
- }
-
- HeapRegionNode hrnCallerAndOutContext =
- (HeapRegionNode) rsnCallerAndOutContext;
-
- // is this source node out-of-context?
- if( callerNodeIDsCopiedToCallee.contains(hrnCallerAndOutContext.getID() ) ) {
- // no, skip this edge
- continue;
- }
-
- // okay, we got one
- oocCallerEdges.add(edgeMightCross);
-
- // add all reach tuples on the node to list
- // of things that are out-of-context: insight
- // if this node is reachable from someting that WAS
- // in-context, then this node should already be in-context
- Iterator<ReachState> stateItr = hrnCallerAndOutContext.getAlpha().iterator();
- while( stateItr.hasNext() ) {
- ReachState state = stateItr.next();
-
- Iterator<ReachTuple> rtItr = state.iterator();
- while( rtItr.hasNext() ) {
- ReachTuple rt = rtItr.next();
-
- oocHrnIdOoc2callee.add(new HrnIdOoc(rt.getHrnID(),
- rt.isOutOfContext()
- )
- );
- }
- }
+ RefEdge edgeMightCross = itrMightCross.next();
+
+ RefSrcNode rsnCallerAndOutContext =
+ edgeMightCross.getSrc();
+
+ if( rsnCallerAndOutContext instanceof VariableNode ) {
+ // variables do not have out-of-context reach states,
+ // so jump out now
+ oocCallerEdges.add(edgeMightCross);
+ continue;
+ }
+
+ HeapRegionNode hrnCallerAndOutContext =
+ (HeapRegionNode) rsnCallerAndOutContext;
+
+ // is this source node out-of-context?
+ if( callerNodeIDsCopiedToCallee.contains(hrnCallerAndOutContext.getID() ) ) {
+ // no, skip this edge
+ continue;
+ }
+
+ // okay, we got one
+ oocCallerEdges.add(edgeMightCross);
+
+ // add all reach tuples on the node to list
+ // of things that are out-of-context: insight
+ // if this node is reachable from someting that WAS
+ // in-context, then this node should already be in-context
+ Iterator<ReachState> stateItr = hrnCallerAndOutContext.getAlpha().iterator();
+ while( stateItr.hasNext() ) {
+ ReachState state = stateItr.next();
+
+ Iterator<ReachTuple> rtItr = state.iterator();
+ while( rtItr.hasNext() ) {
+ ReachTuple rt = rtItr.next();
+
+ oocHrnIdOoc2callee.add(new HrnIdOoc(rt.getHrnID(),
+ rt.isOutOfContext()
+ )
+ );
+ }
+ }
}
}
boolean outOfCallerContext;
if( rsnCaller instanceof VariableNode ) {
- VariableNode vnCaller = (VariableNode) rsnCaller;
- oocNodeType = null;
- oocReach = rsetEmpty;
- oocPredSrcTemp = vnCaller.getTempDescriptor();
- outOfCalleeContext = true;
- outOfCallerContext = false;
+ VariableNode vnCaller = (VariableNode) rsnCaller;
+ oocNodeType = null;
+ oocReach = rsetEmpty;
+ oocPredSrcTemp = vnCaller.getTempDescriptor();
+ outOfCalleeContext = true;
+ outOfCallerContext = false;
} else {
- HeapRegionNode hrnSrcCaller = (HeapRegionNode) rsnCaller;
- assert !callerNodeIDsCopiedToCallee.contains(hrnSrcCaller.getID() );
- oocNodeType = hrnSrcCaller.getType();
- oocReach = hrnSrcCaller.getAlpha();
- oocPredSrcID = hrnSrcCaller.getID();
- if( hrnSrcCaller.isOutOfContext() ) {
- outOfCalleeContext = false;
- outOfCallerContext = true;
- } else {
- outOfCalleeContext = true;
- outOfCallerContext = false;
- }
+ HeapRegionNode hrnSrcCaller = (HeapRegionNode) rsnCaller;
+ assert !callerNodeIDsCopiedToCallee.contains(hrnSrcCaller.getID() );
+ oocNodeType = hrnSrcCaller.getType();
+ oocReach = hrnSrcCaller.getAlpha();
+ oocPredSrcID = hrnSrcCaller.getID();
+ if( hrnSrcCaller.isOutOfContext() ) {
+ outOfCalleeContext = false;
+ outOfCallerContext = true;
+ } else {
+ outOfCalleeContext = true;
+ outOfCallerContext = false;
+ }
}
ExistPred pred =
);
if( oocEdgeExisting == null ) {
- // for consistency, map one out-of-context "identifier"
- // to one heap region node id, otherwise no convergence
- String oocid = "oocid"+
- fmCallee+
- hrnDstCallee.getIDString()+
- oocNodeType+
- reCaller.getType()+
- reCaller.getField();
-
- Integer oocHrnID = oocid2hrnid.get(oocid);
-
- HeapRegionNode hrnCalleeAndOutContext;
-
- if( oocHrnID == null ) {
-
- hrnCalleeAndOutContext =
- rg.createNewHeapRegionNode(null, // ID
- false, // single object?
- false, // new summary?
- true, // out-of-context?
- oocNodeType,
- null, // alloc site, shouldn't be used
- toCalleeContext(oocReach,
- preds,
- oocHrnIdOoc2callee
- ),
- toCalleeContext(oocReach,
- preds,
- oocHrnIdOoc2callee
- ),
- preds,
- "out-of-context"
- );
-
- oocid2hrnid.put(oocid, hrnCalleeAndOutContext.getID() );
-
- } else {
-
- // the mapping already exists, so see if node is there
- hrnCalleeAndOutContext = rg.id2hrn.get(oocHrnID);
-
- if( hrnCalleeAndOutContext == null ) {
- // nope, make it
- hrnCalleeAndOutContext =
- rg.createNewHeapRegionNode(oocHrnID, // ID
- false, // single object?
- false, // new summary?
- true, // out-of-context?
- oocNodeType,
- null, // alloc site, shouldn't be used
- toCalleeContext(oocReach,
- preds,
- oocHrnIdOoc2callee
- ),
- toCalleeContext(oocReach,
- preds,
- oocHrnIdOoc2callee
- ),
- preds,
- "out-of-context"
- );
-
- } else {
- // otherwise it is there, so merge reachability
- hrnCalleeAndOutContext.setAlpha(Canonical.unionORpreds(hrnCalleeAndOutContext.getAlpha(),
- toCalleeContext(oocReach,
- preds,
- oocHrnIdOoc2callee
- )
- )
- );
- }
- }
-
- assert hrnCalleeAndOutContext.reachHasOnlyOOC();
-
- rg.addRefEdge(hrnCalleeAndOutContext,
- hrnDstCallee,
- new RefEdge(hrnCalleeAndOutContext,
- hrnDstCallee,
- reCaller.getType(),
- reCaller.getField(),
- toCalleeContext(reCaller.getBeta(),
- preds,
- oocHrnIdOoc2callee
- ),
- preds,
- toCalleeContext(reCaller.getTaints(),
- preds)
- )
- );
+ // for consistency, map one out-of-context "identifier"
+ // to one heap region node id, otherwise no convergence
+ String oocid = "oocid"+
+ fmCallee+
+ hrnDstCallee.getIDString()+
+ oocNodeType+
+ reCaller.getType()+
+ reCaller.getField();
+
+ Integer oocHrnID = oocid2hrnid.get(oocid);
+
+ HeapRegionNode hrnCalleeAndOutContext;
+
+ if( oocHrnID == null ) {
+
+ hrnCalleeAndOutContext =
+ rg.createNewHeapRegionNode(null, // ID
+ false, // single object?
+ false, // new summary?
+ true, // out-of-context?
+ oocNodeType,
+ null, // alloc site, shouldn't be used
+ toCalleeContext(oocReach,
+ preds,
+ oocHrnIdOoc2callee
+ ),
+ toCalleeContext(oocReach,
+ preds,
+ oocHrnIdOoc2callee
+ ),
+ preds,
+ "out-of-context"
+ );
+
+ oocid2hrnid.put(oocid, hrnCalleeAndOutContext.getID() );
+
+ } else {
+
+ // the mapping already exists, so see if node is there
+ hrnCalleeAndOutContext = rg.id2hrn.get(oocHrnID);
+
+ if( hrnCalleeAndOutContext == null ) {
+ // nope, make it
+ hrnCalleeAndOutContext =
+ rg.createNewHeapRegionNode(oocHrnID, // ID
+ false, // single object?
+ false, // new summary?
+ true, // out-of-context?
+ oocNodeType,
+ null, // alloc site, shouldn't be used
+ toCalleeContext(oocReach,
+ preds,
+ oocHrnIdOoc2callee
+ ),
+ toCalleeContext(oocReach,
+ preds,
+ oocHrnIdOoc2callee
+ ),
+ preds,
+ "out-of-context"
+ );
+
+ } else {
+ // otherwise it is there, so merge reachability
+ hrnCalleeAndOutContext.setAlpha(Canonical.unionORpreds(hrnCalleeAndOutContext.getAlpha(),
+ toCalleeContext(oocReach,
+ preds,
+ oocHrnIdOoc2callee
+ )
+ )
+ );
+ }
+ }
+
+ assert hrnCalleeAndOutContext.reachHasOnlyOOC();
+
+ rg.addRefEdge(hrnCalleeAndOutContext,
+ hrnDstCallee,
+ new RefEdge(hrnCalleeAndOutContext,
+ hrnDstCallee,
+ reCaller.getType(),
+ reCaller.getField(),
+ toCalleeContext(reCaller.getBeta(),
+ preds,
+ oocHrnIdOoc2callee
+ ),
+ preds,
+ toCalleeContext(reCaller.getTaints(),
+ preds)
+ )
+ );
} else {
- // the out-of-context edge already exists
- oocEdgeExisting.setBeta(Canonical.unionORpreds(oocEdgeExisting.getBeta(),
- toCalleeContext(reCaller.getBeta(),
- preds,
- oocHrnIdOoc2callee
- )
- )
- );
-
- oocEdgeExisting.setPreds(Canonical.join(oocEdgeExisting.getPreds(),
- preds
- )
- );
-
- oocEdgeExisting.setTaints(Canonical.unionORpreds(oocEdgeExisting.getTaints(),
- toCalleeContext(reCaller.getTaints(),
- preds
- )
- )
- );
-
- HeapRegionNode hrnCalleeAndOutContext =
- (HeapRegionNode) oocEdgeExisting.getSrc();
- hrnCalleeAndOutContext.setAlpha(Canonical.unionORpreds(hrnCalleeAndOutContext.getAlpha(),
- toCalleeContext(oocReach,
- preds,
- oocHrnIdOoc2callee
- )
- )
- );
-
- assert hrnCalleeAndOutContext.reachHasOnlyOOC();
+ // the out-of-context edge already exists
+ oocEdgeExisting.setBeta(Canonical.unionORpreds(oocEdgeExisting.getBeta(),
+ toCalleeContext(reCaller.getBeta(),
+ preds,
+ oocHrnIdOoc2callee
+ )
+ )
+ );
+
+ oocEdgeExisting.setPreds(Canonical.join(oocEdgeExisting.getPreds(),
+ preds
+ )
+ );
+
+ oocEdgeExisting.setTaints(Canonical.unionORpreds(oocEdgeExisting.getTaints(),
+ toCalleeContext(reCaller.getTaints(),
+ preds
+ )
+ )
+ );
+
+ HeapRegionNode hrnCalleeAndOutContext =
+ (HeapRegionNode) oocEdgeExisting.getSrc();
+ hrnCalleeAndOutContext.setAlpha(Canonical.unionORpreds(hrnCalleeAndOutContext.getAlpha(),
+ toCalleeContext(oocReach,
+ preds,
+ oocHrnIdOoc2callee
+ )
+ )
+ );
+
+ assert hrnCalleeAndOutContext.reachHasOnlyOOC();
}
}
);
if( predsIfSatis != null ) {
- calleeNodesSatisfied.put(hrnCallee, predsIfSatis);
+ calleeNodesSatisfied.put(hrnCallee, predsIfSatis);
} else {
- // otherwise don't bother looking at edges to this node
- continue;
+ // otherwise don't bother looking at edges to this node
+ continue;
}
// since the node is coming over, find out which reach
Iterator<ReachState> stateItr = hrnCallee.getAlpha().iterator();
while( stateItr.hasNext() ) {
- ReachState stateCallee = stateItr.next();
+ ReachState stateCallee = stateItr.next();
- predsIfSatis =
- stateCallee.getPreds().isSatisfiedBy(this,
- callerNodeIDsCopiedToCallee
- );
- if( predsIfSatis != null ) {
+ predsIfSatis =
+ stateCallee.getPreds().isSatisfiedBy(this,
+ callerNodeIDsCopiedToCallee
+ );
+ if( predsIfSatis != null ) {
- Hashtable<ReachState, ExistPredSet> calleeStatesSatisfied =
- calleeNode2calleeStatesSatisfied.get(hrnCallee);
+ Hashtable<ReachState, ExistPredSet> calleeStatesSatisfied =
+ calleeNode2calleeStatesSatisfied.get(hrnCallee);
- if( calleeStatesSatisfied == null ) {
- calleeStatesSatisfied =
- new Hashtable<ReachState, ExistPredSet>();
+ if( calleeStatesSatisfied == null ) {
+ calleeStatesSatisfied =
+ new Hashtable<ReachState, ExistPredSet>();
- calleeNode2calleeStatesSatisfied.put(hrnCallee, calleeStatesSatisfied);
- }
+ calleeNode2calleeStatesSatisfied.put(hrnCallee, calleeStatesSatisfied);
+ }
- calleeStatesSatisfied.put(stateCallee, predsIfSatis);
- }
+ calleeStatesSatisfied.put(stateCallee, predsIfSatis);
+ }
}
// then look at edges to the node
Iterator<RefEdge> reItr = hrnCallee.iteratorToReferencers();
while( reItr.hasNext() ) {
- RefEdge reCallee = reItr.next();
- RefSrcNode rsnCallee = reCallee.getSrc();
-
- // (caller local variables to in-context heap regions)
- // have an (out-of-context heap region -> in-context heap region)
- // abstraction in the callEE, so its true we never need to
- // look at a (var node -> heap region) edge in callee to bring
- // those over for the call site transfer, except for the special
- // case of *RETURN var* -> heap region edges.
- // What about (param var->heap region)
- // edges in callee? They are dealt with below this loop.
-
- if( rsnCallee instanceof VariableNode ) {
-
- // looking for the return-value variable only
- VariableNode vnCallee = (VariableNode) rsnCallee;
- if( vnCallee.getTempDescriptor() != tdReturn ) {
- continue;
- }
-
- TempDescriptor returnTemp = fc.getReturnTemp();
- if( returnTemp == null ||
- !DisjointAnalysis.shouldAnalysisTrack(returnTemp.getType() )
- ) {
- continue;
- }
-
- // note that the assignment of the return value is to a
- // variable in the caller which is out-of-context with
- // respect to the callee
- VariableNode vnLhsCaller = getVariableNodeFromTemp(returnTemp);
- Set<RefSrcNode> rsnCallers = new HashSet<RefSrcNode>();
- rsnCallers.add(vnLhsCaller);
- calleeEdges2oocCallerSrcMatches.put(reCallee, rsnCallers);
-
-
- } else {
- // for HeapRegionNode callee sources...
-
- // first see if the source is out-of-context, and only
- // proceed with this edge if we find some caller-context
- // matches
- HeapRegionNode hrnSrcCallee = (HeapRegionNode) rsnCallee;
- boolean matchedOutOfContext = false;
-
- if( !hrnSrcCallee.isOutOfContext() ) {
-
- predsIfSatis =
- hrnSrcCallee.getPreds().isSatisfiedBy(this,
- callerNodeIDsCopiedToCallee
- );
- if( predsIfSatis != null ) {
- calleeNodesSatisfied.put(hrnSrcCallee, predsIfSatis);
- } else {
- // otherwise forget this edge
- continue;
- }
-
- } else {
- // hrnSrcCallee is out-of-context
-
- assert !calleeEdges2oocCallerSrcMatches.containsKey(reCallee);
-
- Set<RefSrcNode> rsnCallers = new HashSet<RefSrcNode>();
-
- // is the target node in the caller?
- HeapRegionNode hrnDstCaller = this.id2hrn.get(hrnCallee.getID() );
- if( hrnDstCaller == null ) {
- continue;
- }
-
- Iterator<RefEdge> reDstItr = hrnDstCaller.iteratorToReferencers();
- while( reDstItr.hasNext() ) {
- // the edge and field (either possibly null) must match
- RefEdge reCaller = reDstItr.next();
-
- if( !reCaller.typeEquals(reCallee.getType() ) ||
- !reCaller.fieldEquals(reCallee.getField() )
- ) {
- continue;
- }
-
- RefSrcNode rsnCaller = reCaller.getSrc();
- if( rsnCaller instanceof VariableNode ) {
-
- // a variable node matches an OOC region with null type
- if( hrnSrcCallee.getType() != null ) {
- continue;
- }
-
- } else {
- // otherwise types should match
- HeapRegionNode hrnCallerSrc = (HeapRegionNode) rsnCaller;
- if( hrnSrcCallee.getType() == null ) {
- if( hrnCallerSrc.getType() != null ) {
- continue;
- }
- } else {
- if( !hrnSrcCallee.getType().equals(hrnCallerSrc.getType() ) ) {
- continue;
- }
- }
- }
-
- rsnCallers.add(rsnCaller);
- matchedOutOfContext = true;
- }
-
- if( !rsnCallers.isEmpty() ) {
- calleeEdges2oocCallerSrcMatches.put(reCallee, rsnCallers);
- }
- }
-
- if( hrnSrcCallee.isOutOfContext() &&
- !matchedOutOfContext ) {
- continue;
- }
- }
-
-
- predsIfSatis =
- reCallee.getPreds().isSatisfiedBy(this,
- callerNodeIDsCopiedToCallee
- );
-
- if( predsIfSatis != null ) {
- calleeEdgesSatisfied.put(reCallee, predsIfSatis);
-
- // since the edge is coming over, find out which reach
- // states on it should come over, too
- assert calleeEdge2calleeStatesSatisfied.get(reCallee) == null;
-
- stateItr = reCallee.getBeta().iterator();
- while( stateItr.hasNext() ) {
- ReachState stateCallee = stateItr.next();
-
- predsIfSatis =
- stateCallee.getPreds().isSatisfiedBy(this,
- callerNodeIDsCopiedToCallee
- );
- if( predsIfSatis != null ) {
-
- Hashtable<ReachState, ExistPredSet> calleeStatesSatisfied =
- calleeEdge2calleeStatesSatisfied.get(reCallee);
-
- if( calleeStatesSatisfied == null ) {
- calleeStatesSatisfied =
- new Hashtable<ReachState, ExistPredSet>();
-
- calleeEdge2calleeStatesSatisfied.put(reCallee, calleeStatesSatisfied);
- }
-
- calleeStatesSatisfied.put(stateCallee, predsIfSatis);
- }
- }
-
- // since the edge is coming over, find out which taints
- // on it should come over, too
- assert calleeEdge2calleeTaintsSatisfied.get(reCallee) == null;
-
- Iterator<Taint> tItr = reCallee.getTaints().iterator();
- while( tItr.hasNext() ) {
- Taint tCallee = tItr.next();
-
- predsIfSatis =
- tCallee.getPreds().isSatisfiedBy(this,
- callerNodeIDsCopiedToCallee
- );
- if( predsIfSatis != null ) {
-
- Hashtable<Taint, ExistPredSet> calleeTaintsSatisfied =
- calleeEdge2calleeTaintsSatisfied.get(reCallee);
-
- if( calleeTaintsSatisfied == null ) {
- calleeTaintsSatisfied =
- new Hashtable<Taint, ExistPredSet>();
-
- calleeEdge2calleeTaintsSatisfied.put(reCallee, calleeTaintsSatisfied);
- }
-
- calleeTaintsSatisfied.put(tCallee, predsIfSatis);
- }
- }
- }
+ RefEdge reCallee = reItr.next();
+ RefSrcNode rsnCallee = reCallee.getSrc();
+
+ // (caller local variables to in-context heap regions)
+ // have an (out-of-context heap region -> in-context heap region)
+ // abstraction in the callEE, so its true we never need to
+ // look at a (var node -> heap region) edge in callee to bring
+ // those over for the call site transfer, except for the special
+ // case of *RETURN var* -> heap region edges.
+ // What about (param var->heap region)
+ // edges in callee? They are dealt with below this loop.
+
+ if( rsnCallee instanceof VariableNode ) {
+
+ // looking for the return-value variable only
+ VariableNode vnCallee = (VariableNode) rsnCallee;
+ if( vnCallee.getTempDescriptor() != tdReturn ) {
+ continue;
+ }
+
+ TempDescriptor returnTemp = fc.getReturnTemp();
+ if( returnTemp == null ||
+ !DisjointAnalysis.shouldAnalysisTrack(returnTemp.getType() )
+ ) {
+ continue;
+ }
+
+ // note that the assignment of the return value is to a
+ // variable in the caller which is out-of-context with
+ // respect to the callee
+ VariableNode vnLhsCaller = getVariableNodeFromTemp(returnTemp);
+ Set<RefSrcNode> rsnCallers = new HashSet<RefSrcNode>();
+ rsnCallers.add(vnLhsCaller);
+ calleeEdges2oocCallerSrcMatches.put(reCallee, rsnCallers);
+
+
+ } else {
+ // for HeapRegionNode callee sources...
+
+ // first see if the source is out-of-context, and only
+ // proceed with this edge if we find some caller-context
+ // matches
+ HeapRegionNode hrnSrcCallee = (HeapRegionNode) rsnCallee;
+ boolean matchedOutOfContext = false;
+
+ if( !hrnSrcCallee.isOutOfContext() ) {
+
+ predsIfSatis =
+ hrnSrcCallee.getPreds().isSatisfiedBy(this,
+ callerNodeIDsCopiedToCallee
+ );
+ if( predsIfSatis != null ) {
+ calleeNodesSatisfied.put(hrnSrcCallee, predsIfSatis);
+ } else {
+ // otherwise forget this edge
+ continue;
+ }
+
+ } else {
+ // hrnSrcCallee is out-of-context
+
+ assert !calleeEdges2oocCallerSrcMatches.containsKey(reCallee);
+
+ Set<RefSrcNode> rsnCallers = new HashSet<RefSrcNode>();
+
+ // is the target node in the caller?
+ HeapRegionNode hrnDstCaller = this.id2hrn.get(hrnCallee.getID() );
+ if( hrnDstCaller == null ) {
+ continue;
+ }
+
+ Iterator<RefEdge> reDstItr = hrnDstCaller.iteratorToReferencers();
+ while( reDstItr.hasNext() ) {
+ // the edge and field (either possibly null) must match
+ RefEdge reCaller = reDstItr.next();
+
+ if( !reCaller.typeEquals(reCallee.getType() ) ||
+ !reCaller.fieldEquals(reCallee.getField() )
+ ) {
+ continue;
+ }
+
+ RefSrcNode rsnCaller = reCaller.getSrc();
+ if( rsnCaller instanceof VariableNode ) {
+
+ // a variable node matches an OOC region with null type
+ if( hrnSrcCallee.getType() != null ) {
+ continue;
+ }
+
+ } else {
+ // otherwise types should match
+ HeapRegionNode hrnCallerSrc = (HeapRegionNode) rsnCaller;
+ if( hrnSrcCallee.getType() == null ) {
+ if( hrnCallerSrc.getType() != null ) {
+ continue;
+ }
+ } else {
+ if( !hrnSrcCallee.getType().equals(hrnCallerSrc.getType() ) ) {
+ continue;
+ }
+ }
+ }
+
+ rsnCallers.add(rsnCaller);
+ matchedOutOfContext = true;
+ }
+
+ if( !rsnCallers.isEmpty() ) {
+ calleeEdges2oocCallerSrcMatches.put(reCallee, rsnCallers);
+ }
+ }
+
+ if( hrnSrcCallee.isOutOfContext() &&
+ !matchedOutOfContext ) {
+ continue;
+ }
+ }
+
+
+ predsIfSatis =
+ reCallee.getPreds().isSatisfiedBy(this,
+ callerNodeIDsCopiedToCallee
+ );
+
+ if( predsIfSatis != null ) {
+ calleeEdgesSatisfied.put(reCallee, predsIfSatis);
+
+ // since the edge is coming over, find out which reach
+ // states on it should come over, too
+ assert calleeEdge2calleeStatesSatisfied.get(reCallee) == null;
+
+ stateItr = reCallee.getBeta().iterator();
+ while( stateItr.hasNext() ) {
+ ReachState stateCallee = stateItr.next();
+
+ predsIfSatis =
+ stateCallee.getPreds().isSatisfiedBy(this,
+ callerNodeIDsCopiedToCallee
+ );
+ if( predsIfSatis != null ) {
+
+ Hashtable<ReachState, ExistPredSet> calleeStatesSatisfied =
+ calleeEdge2calleeStatesSatisfied.get(reCallee);
+
+ if( calleeStatesSatisfied == null ) {
+ calleeStatesSatisfied =
+ new Hashtable<ReachState, ExistPredSet>();
+
+ calleeEdge2calleeStatesSatisfied.put(reCallee, calleeStatesSatisfied);
+ }
+
+ calleeStatesSatisfied.put(stateCallee, predsIfSatis);
+ }
+ }
+
+ // since the edge is coming over, find out which taints
+ // on it should come over, too
+ assert calleeEdge2calleeTaintsSatisfied.get(reCallee) == null;
+
+ Iterator<Taint> tItr = reCallee.getTaints().iterator();
+ while( tItr.hasNext() ) {
+ Taint tCallee = tItr.next();
+
+ predsIfSatis =
+ tCallee.getPreds().isSatisfiedBy(this,
+ callerNodeIDsCopiedToCallee
+ );
+ if( predsIfSatis != null ) {
+
+ Hashtable<Taint, ExistPredSet> calleeTaintsSatisfied =
+ calleeEdge2calleeTaintsSatisfied.get(reCallee);
+
+ if( calleeTaintsSatisfied == null ) {
+ calleeTaintsSatisfied =
+ new Hashtable<Taint, ExistPredSet>();
+
+ calleeEdge2calleeTaintsSatisfied.put(reCallee, calleeTaintsSatisfied);
+ }
+
+ calleeTaintsSatisfied.put(tCallee, predsIfSatis);
+ }
+ }
+ }
}
}
// it to link everything up in caller context, so that's why we're
// skipping this... maybe that's a sillier way to do it?
if( hrnCallee.isOutOfContext() ) {
- continue;
+ continue;
}
AllocSite as = hrnCallee.getAllocSite();
HeapRegionNode hrnCaller = id2hrn.get(hrnIDshadow);
if( hrnCaller == null ) {
- hrnCaller =
- createNewHeapRegionNode(hrnIDshadow, // id or null to generate a new one
- hrnCallee.isSingleObject(), // single object?
- hrnCallee.isNewSummary(), // summary?
- false, // out-of-context?
- hrnCallee.getType(), // type
- hrnCallee.getAllocSite(), // allocation site
- toCallerContext(hrnCallee.getInherent(),
- calleeNode2calleeStatesSatisfied.get(hrnCallee) ), // inherent reach
- null, // current reach
- predsEmpty, // predicates
- hrnCallee.getDescription() // description
- );
+ hrnCaller =
+ createNewHeapRegionNode(hrnIDshadow, // id or null to generate a new one
+ hrnCallee.isSingleObject(), // single object?
+ hrnCallee.isNewSummary(), // summary?
+ false, // out-of-context?
+ hrnCallee.getType(), // type
+ hrnCallee.getAllocSite(), // allocation site
+ toCallerContext(hrnCallee.getInherent(),
+ calleeNode2calleeStatesSatisfied.get(hrnCallee) ), // inherent reach
+ null, // current reach
+ predsEmpty, // predicates
+ hrnCallee.getDescription() // description
+ );
} else {
- assert hrnCaller.isWiped();
+ assert hrnCaller.isWiped();
}
hrnCaller.setAlpha(toCallerContext(hrnCallee.getAlpha(),
calleeEdges2oocCallerSrcMatches.get(reCallee);
if( rsnCallee instanceof HeapRegionNode ) {
- HeapRegionNode hrnCalleeSrc = (HeapRegionNode) rsnCallee;
- if( hrnCalleeSrc.isOutOfContext() ) {
- assert oocCallers != null;
- }
+ HeapRegionNode hrnCalleeSrc = (HeapRegionNode) rsnCallee;
+ if( hrnCalleeSrc.isOutOfContext() ) {
+ assert oocCallers != null;
+ }
}
if( oocCallers == null ) {
- // there are no out-of-context matches, so it's
- // either a param/arg var or one in-context heap region
- if( rsnCallee instanceof VariableNode ) {
- // variable -> node in the callee should only
- // come into the caller if its from a param var
- VariableNode vnCallee = (VariableNode) rsnCallee;
- TempDescriptor tdParam = vnCallee.getTempDescriptor();
- TempDescriptor tdArg = fc.getArgMatchingParam(fmCallee,
- tdParam);
- if( tdArg == null ) {
- // this means the variable isn't a parameter, its local
- // to the callee so we ignore it in call site transfer
- // shouldn't this NEVER HAPPEN?
- assert false;
- }
+ // there are no out-of-context matches, so it's
+ // either a param/arg var or one in-context heap region
+ if( rsnCallee instanceof VariableNode ) {
+ // variable -> node in the callee should only
+ // come into the caller if its from a param var
+ VariableNode vnCallee = (VariableNode) rsnCallee;
+ TempDescriptor tdParam = vnCallee.getTempDescriptor();
+ TempDescriptor tdArg = fc.getArgMatchingParam(fmCallee,
+ tdParam);
+ if( tdArg == null ) {
+ // this means the variable isn't a parameter, its local
+ // to the callee so we ignore it in call site transfer
+ // shouldn't this NEVER HAPPEN?
+ assert false;
+ }
- rsnCallers.add(this.getVariableNodeFromTemp(tdArg) );
+ rsnCallers.add(this.getVariableNodeFromTemp(tdArg) );
- } else {
- // otherwise source is in context, one region
+ } else {
+ // otherwise source is in context, one region
- HeapRegionNode hrnSrcCallee = (HeapRegionNode) rsnCallee;
+ HeapRegionNode hrnSrcCallee = (HeapRegionNode) rsnCallee;
- // translate an in-context node to shadow
- AllocSite asSrc = hrnSrcCallee.getAllocSite();
- allocSites.add(asSrc);
+ // translate an in-context node to shadow
+ AllocSite asSrc = hrnSrcCallee.getAllocSite();
+ allocSites.add(asSrc);
- Integer hrnIDSrcShadow =
- asSrc.getShadowIDfromID(hrnSrcCallee.getID() );
+ Integer hrnIDSrcShadow =
+ asSrc.getShadowIDfromID(hrnSrcCallee.getID() );
- HeapRegionNode hrnSrcCallerShadow =
- this.id2hrn.get(hrnIDSrcShadow);
+ HeapRegionNode hrnSrcCallerShadow =
+ this.id2hrn.get(hrnIDSrcShadow);
- assert hrnSrcCallerShadow != null;
+ assert hrnSrcCallerShadow != null;
- rsnCallers.add(hrnSrcCallerShadow);
- }
+ rsnCallers.add(hrnSrcCallerShadow);
+ }
} else {
- // otherwise we have a set of out-of-context srcs
- // that should NOT be translated to shadow nodes
- assert !oocCallers.isEmpty();
- rsnCallers.addAll(oocCallers);
+ // otherwise we have a set of out-of-context srcs
+ // that should NOT be translated to shadow nodes
+ assert !oocCallers.isEmpty();
+ rsnCallers.addAll(oocCallers);
}
// now make all caller edges we've identified from
assert !rsnCallers.isEmpty();
Iterator<RefSrcNode> rsnItr = rsnCallers.iterator();
while( rsnItr.hasNext() ) {
- RefSrcNode rsnCaller = rsnItr.next();
-
- RefEdge reCaller = new RefEdge(rsnCaller,
- hrnDstCaller,
- reCallee.getType(),
- reCallee.getField(),
- toCallerContext(reCallee.getBeta(),
- calleeEdge2calleeStatesSatisfied.get(reCallee) ),
- preds,
- toCallerContext(reCallee.getTaints(),
- calleeEdge2calleeTaintsSatisfied.get(reCallee) )
- );
-
- ChangeSet cs = ChangeSet.factory();
- Iterator<ReachState> rsItr = reCaller.getBeta().iterator();
- while( rsItr.hasNext() ) {
- ReachState state = rsItr.next();
- ExistPredSet predsPreCallee = state.getPreds();
-
- if( state.isEmpty() ) {
- continue;
- }
-
- Iterator<ExistPred> predItr = predsPreCallee.iterator();
- while( predItr.hasNext() ) {
- ExistPred pred = predItr.next();
- ReachState old = pred.ne_state;
-
- if( old == null ) {
- old = rstateEmpty;
- }
-
- cs = Canonical.add(cs,
- ChangeTuple.factory(old,
- state
- )
- );
- }
- }
-
- // we're just going to use the convenient "merge-if-exists"
- // edge call below, but still take a separate look if there
- // is an existing caller edge to build change sets properly
- if( !cs.isEmpty() ) {
- RefEdge edgeExisting = rsnCaller.getReferenceTo(hrnDstCaller,
- reCallee.getType(),
- reCallee.getField()
- );
- if( edgeExisting != null ) {
- ChangeSet csExisting = edgePlannedChanges.get(edgeExisting);
- if( csExisting == null ) {
- csExisting = ChangeSet.factory();
- }
- edgePlannedChanges.put(edgeExisting,
- Canonical.union(csExisting,
- cs
- )
- );
- } else {
- edgesForPropagation.add(reCaller);
- assert !edgePlannedChanges.containsKey(reCaller);
- edgePlannedChanges.put(reCaller, cs);
- }
- }
-
- // then add new caller edge or merge
- addEdgeOrMergeWithExisting(reCaller);
+ RefSrcNode rsnCaller = rsnItr.next();
+
+ RefEdge reCaller = new RefEdge(rsnCaller,
+ hrnDstCaller,
+ reCallee.getType(),
+ reCallee.getField(),
+ toCallerContext(reCallee.getBeta(),
+ calleeEdge2calleeStatesSatisfied.get(reCallee) ),
+ preds,
+ toCallerContext(reCallee.getTaints(),
+ calleeEdge2calleeTaintsSatisfied.get(reCallee) )
+ );
+
+ ChangeSet cs = ChangeSet.factory();
+ Iterator<ReachState> rsItr = reCaller.getBeta().iterator();
+ while( rsItr.hasNext() ) {
+ ReachState state = rsItr.next();
+ ExistPredSet predsPreCallee = state.getPreds();
+
+ if( state.isEmpty() ) {
+ continue;
+ }
+
+ Iterator<ExistPred> predItr = predsPreCallee.iterator();
+ while( predItr.hasNext() ) {
+ ExistPred pred = predItr.next();
+ ReachState old = pred.ne_state;
+
+ if( old == null ) {
+ old = rstateEmpty;
+ }
+
+ cs = Canonical.add(cs,
+ ChangeTuple.factory(old,
+ state
+ )
+ );
+ }
+ }
+
+ // we're just going to use the convenient "merge-if-exists"
+ // edge call below, but still take a separate look if there
+ // is an existing caller edge to build change sets properly
+ if( !cs.isEmpty() ) {
+ RefEdge edgeExisting = rsnCaller.getReferenceTo(hrnDstCaller,
+ reCallee.getType(),
+ reCallee.getField()
+ );
+ if( edgeExisting != null ) {
+ ChangeSet csExisting = edgePlannedChanges.get(edgeExisting);
+ if( csExisting == null ) {
+ csExisting = ChangeSet.factory();
+ }
+ edgePlannedChanges.put(edgeExisting,
+ Canonical.union(csExisting,
+ cs
+ )
+ );
+ } else {
+ edgesForPropagation.add(reCaller);
+ assert !edgePlannedChanges.containsKey(reCaller);
+ edgePlannedChanges.put(reCaller, cs);
+ }
+ }
+
+ // then add new caller edge or merge
+ addEdgeOrMergeWithExisting(reCaller);
}
}
while( ageNorm < allocationDepth &&
ageShad < allocationDepth ) {
- // first, are there any normal nodes left?
- Integer idNorm = as.getIthOldest(ageNorm);
- HeapRegionNode hrnNorm = id2hrn.get(idNorm);
- if( hrnNorm == null ) {
- // no, this age of normal node not in the caller graph
- ageNorm++;
- continue;
- }
-
- // yes, a normal node exists, is there an empty shadow
- // "slot" to transfer it onto?
- HeapRegionNode hrnShad = getIthNode(as, ageShad, true);
- if( !hrnShad.isWiped() ) {
- // no, this age of shadow node is not empty
- ageShad++;
- continue;
- }
-
- // yes, this shadow node is empty
- transferOnto(hrnNorm, hrnShad);
- ageNorm++;
- ageShad++;
+ // first, are there any normal nodes left?
+ Integer idNorm = as.getIthOldest(ageNorm);
+ HeapRegionNode hrnNorm = id2hrn.get(idNorm);
+ if( hrnNorm == null ) {
+ // no, this age of normal node not in the caller graph
+ ageNorm++;
+ continue;
+ }
+
+ // yes, a normal node exists, is there an empty shadow
+ // "slot" to transfer it onto?
+ HeapRegionNode hrnShad = getIthNode(as, ageShad, true);
+ if( !hrnShad.isWiped() ) {
+ // no, this age of shadow node is not empty
+ ageShad++;
+ continue;
+ }
+
+ // yes, this shadow node is empty
+ transferOnto(hrnNorm, hrnShad);
+ ageNorm++;
+ ageShad++;
}
// now, while there are still normal nodes but no shadow
// slots, merge normal nodes into the shadow summary
while( ageNorm < allocationDepth ) {
- // first, are there any normal nodes left?
- Integer idNorm = as.getIthOldest(ageNorm);
- HeapRegionNode hrnNorm = id2hrn.get(idNorm);
- if( hrnNorm == null ) {
- // no, this age of normal node not in the caller graph
- ageNorm++;
- continue;
- }
-
- // yes, a normal node exists, so get the shadow summary
- HeapRegionNode summShad = getSummaryNode(as, true);
- mergeIntoSummary(hrnNorm, summShad);
-
- // now tokens in reachability sets need to age also
- Iterator itrAllHRNodes = id2hrn.entrySet().iterator();
- while( itrAllHRNodes.hasNext() ) {
- Map.Entry me = (Map.Entry)itrAllHRNodes.next();
- HeapRegionNode hrnToAge = (HeapRegionNode) me.getValue();
-
- ageTuplesFrom(as, hrnToAge);
-
- Iterator<RefEdge> itrEdges = hrnToAge.iteratorToReferencers();
- while( itrEdges.hasNext() ) {
- ageTuplesFrom(as, itrEdges.next() );
- }
- }
-
- ageNorm++;
+ // first, are there any normal nodes left?
+ Integer idNorm = as.getIthOldest(ageNorm);
+ HeapRegionNode hrnNorm = id2hrn.get(idNorm);
+ if( hrnNorm == null ) {
+ // no, this age of normal node not in the caller graph
+ ageNorm++;
+ continue;
+ }
+
+ // yes, a normal node exists, so get the shadow summary
+ HeapRegionNode summShad = getSummaryNode(as, true);
+ mergeIntoSummary(hrnNorm, summShad);
+
+ // now tokens in reachability sets need to age also
+ Iterator itrAllHRNodes = id2hrn.entrySet().iterator();
+ while( itrAllHRNodes.hasNext() ) {
+ Map.Entry me = (Map.Entry)itrAllHRNodes.next();
+ HeapRegionNode hrnToAge = (HeapRegionNode) me.getValue();
+
+ ageTuplesFrom(as, hrnToAge);
+
+ Iterator<RefEdge> itrEdges = hrnToAge.iteratorToReferencers();
+ while( itrEdges.hasNext() ) {
+ ageTuplesFrom(as, itrEdges.next() );
+ }
+ }
+
+ ageNorm++;
}
// if there is a normal summary, merge it into shadow summary
Integer idNorm = as.getSummary();
HeapRegionNode summNorm = id2hrn.get(idNorm);
if( summNorm != null ) {
- HeapRegionNode summShad = getSummaryNode(as, true);
- mergeIntoSummary(summNorm, summShad);
+ HeapRegionNode summShad = getSummaryNode(as, true);
+ mergeIntoSummary(summNorm, summShad);
}
// finally, flip all existing shadow nodes onto the normal
for( int i = 0; i < allocationDepth; ++i ) {
- Integer idShad = as.getIthOldestShadow(i);
- HeapRegionNode hrnShad = id2hrn.get(idShad);
- if( hrnShad != null ) {
- // flip it
- HeapRegionNode hrnNorm = getIthNode(as, i, false);
- assert hrnNorm.isWiped();
- transferOnto(hrnShad, hrnNorm);
- }
+ Integer idShad = as.getIthOldestShadow(i);
+ HeapRegionNode hrnShad = id2hrn.get(idShad);
+ if( hrnShad != null ) {
+ // flip it
+ HeapRegionNode hrnNorm = getIthNode(as, i, false);
+ assert hrnNorm.isWiped();
+ transferOnto(hrnShad, hrnNorm);
+ }
}
Integer idShad = as.getSummaryShadow();
HeapRegionNode summShad = id2hrn.get(idShad);
if( summShad != null ) {
- summNorm = getSummaryNode(as, false);
- transferOnto(summShad, summNorm);
+ summNorm = getSummaryNode(as, false);
+ transferOnto(summShad, summNorm);
}
}
Iterator<RefEdge> itrEdges = hrn.iteratorToReferencers();
while( itrEdges.hasNext() ) {
- RefEdge re = itrEdges.next();
- re.setBeta(unshadow(re.getBeta() ) );
+ RefEdge re = itrEdges.next();
+ re.setBeta(unshadow(re.getBeta() ) );
}
}
VariableNode vn = (VariableNode) me.getValue();
if( liveSet.contains(td) ) {
- toVisit.add(vn);
+ toVisit.add(vn);
} else {
- // dead var, remove completely from graph
- td2vn.remove(td);
- clearRefEdgesFrom(vn, null, null, true);
+ // dead var, remove completely from graph
+ td2vn.remove(td);
+ clearRefEdgesFrom(vn, null, null, true);
}
}
Iterator<RefEdge> hrnItr = rsn.iteratorToReferencees();
while( hrnItr.hasNext() ) {
- RefEdge edge = hrnItr.next();
- HeapRegionNode hrn = edge.getDst();
+ RefEdge edge = hrnItr.next();
+ HeapRegionNode hrn = edge.getDst();
- if( !visited.contains(hrn) ) {
- toVisit.add(hrn);
- }
+ if( !visited.contains(hrn) ) {
+ toVisit.add(hrn);
+ }
}
}
if( !visited.contains(hrn) ) {
- // heap region nodes are compared across ReachGraph
- // objects by their integer ID, so when discarding
- // garbage nodes we must also discard entries in
- // the ID -> heap region hashtable.
- id2hrn.remove(hrn.getID() );
-
- // RefEdge objects are two-way linked between
- // nodes, so when a node is identified as garbage,
- // actively clear references to and from it so
- // live nodes won't have dangling RefEdge's
- wipeOut(hrn, true);
-
- // if we just removed the last node from an allocation
- // site, it should be taken out of the ReachGraph's list
- AllocSite as = hrn.getAllocSite();
- if( !hasNodesOf(as) ) {
- allocSites.remove(as);
- }
+ // heap region nodes are compared across ReachGraph
+ // objects by their integer ID, so when discarding
+ // garbage nodes we must also discard entries in
+ // the ID -> heap region hashtable.
+ id2hrn.remove(hrn.getID() );
+
+ // RefEdge objects are two-way linked between
+ // nodes, so when a node is identified as garbage,
+ // actively clear references to and from it so
+ // live nodes won't have dangling RefEdge's
+ wipeOut(hrn, true);
+
+ // if we just removed the last node from an allocation
+ // site, it should be taken out of the ReachGraph's list
+ AllocSite as = hrn.getAllocSite();
+ if( !hasNodesOf(as) ) {
+ allocSites.remove(as);
+ }
}
}
}
for( int i = 0; i < allocationDepth; ++i ) {
if( id2hrn.containsKey(as.getIthOldest(i) ) ) {
- return true;
+ return true;
}
}
return false;
Iterator<RefEdge> itrRers = hrn.iteratorToReferencers();
while( itrRers.hasNext() ) {
- RefEdge edge = itrRers.next();
- assert rsetEmpty.equals(edge.getBetaNew() );
+ RefEdge edge = itrRers.next();
+ assert rsetEmpty.equals(edge.getBetaNew() );
}
// make a mapping of IDs to heap regions they propagate from
if( hrn.isFlagged() ) {
- assert !hrn.isOutOfContext();
- assert !icID2srcs.containsKey(hrn.getID() );
-
- // in-context flagged node IDs simply propagate from the
- // node they name
- Set<HeapRegionNode> srcs = new HashSet<HeapRegionNode>();
- srcs.add(hrn);
- icID2srcs.put(hrn.getID(), srcs);
+ assert !hrn.isOutOfContext();
+ assert !icID2srcs.containsKey(hrn.getID() );
+
+ // in-context flagged node IDs simply propagate from the
+ // node they name
+ Set<HeapRegionNode> srcs = new HashSet<HeapRegionNode>();
+ srcs.add(hrn);
+ icID2srcs.put(hrn.getID(), srcs);
}
if( hrn.isOutOfContext() ) {
- assert !hrn.isFlagged();
-
- // the reachability states on an out-of-context
- // node are not really important (combinations of
- // IDs or arity)--what matters is that the states
- // specify which nodes this out-of-context node
- // stands in for. For example, if the state [17?, 19*]
- // appears on the ooc node, it may serve as a source
- // for node 17? and a source for node 19.
- Iterator<ReachState> stateItr = hrn.getAlpha().iterator();
- while( stateItr.hasNext() ) {
- ReachState state = stateItr.next();
-
- Iterator<ReachTuple> rtItr = state.iterator();
- while( rtItr.hasNext() ) {
- ReachTuple rt = rtItr.next();
- assert rt.isOutOfContext();
-
- Set<HeapRegionNode> srcs = oocID2srcs.get(rt.getHrnID() );
- if( srcs == null ) {
- srcs = new HashSet<HeapRegionNode>();
- }
- srcs.add(hrn);
- oocID2srcs.put(rt.getHrnID(), srcs);
- }
- }
+ assert !hrn.isFlagged();
+
+ // the reachability states on an out-of-context
+ // node are not really important (combinations of
+ // IDs or arity)--what matters is that the states
+ // specify which nodes this out-of-context node
+ // stands in for. For example, if the state [17?, 19*]
+ // appears on the ooc node, it may serve as a source
+ // for node 17? and a source for node 19.
+ Iterator<ReachState> stateItr = hrn.getAlpha().iterator();
+ while( stateItr.hasNext() ) {
+ ReachState state = stateItr.next();
+
+ Iterator<ReachTuple> rtItr = state.iterator();
+ while( rtItr.hasNext() ) {
+ ReachTuple rt = rtItr.next();
+ assert rt.isOutOfContext();
+
+ Set<HeapRegionNode> srcs = oocID2srcs.get(rt.getHrnID() );
+ if( srcs == null ) {
+ srcs = new HashSet<HeapRegionNode>();
+ }
+ srcs.add(hrn);
+ oocID2srcs.put(rt.getHrnID(), srcs);
+ }
+ }
}
}
boolean inContext;
if( !icID2srcs.isEmpty() ) {
- Map.Entry me = (Map.Entry)icID2srcs.entrySet().iterator().next();
- hrnID = (Integer) me.getKey();
- srcs = (Set<HeapRegionNode>)me.getValue();
- inContext = true;
- icID2srcs.remove(hrnID);
+ Map.Entry me = (Map.Entry)icID2srcs.entrySet().iterator().next();
+ hrnID = (Integer) me.getKey();
+ srcs = (Set<HeapRegionNode>)me.getValue();
+ inContext = true;
+ icID2srcs.remove(hrnID);
} else {
- assert !oocID2srcs.isEmpty();
+ assert !oocID2srcs.isEmpty();
- Map.Entry me = (Map.Entry)oocID2srcs.entrySet().iterator().next();
- hrnID = (Integer) me.getKey();
- srcs = (Set<HeapRegionNode>)me.getValue();
- inContext = false;
- oocID2srcs.remove(hrnID);
+ Map.Entry me = (Map.Entry)oocID2srcs.entrySet().iterator().next();
+ hrnID = (Integer) me.getKey();
+ srcs = (Set<HeapRegionNode>)me.getValue();
+ inContext = false;
+ oocID2srcs.remove(hrnID);
}
Iterator<HeapRegionNode> hrnItr = srcs.iterator();
while( hrnItr.hasNext() ) {
- HeapRegionNode hrn = hrnItr.next();
-
- assert workSetEdges.isEmpty();
-
- // initial boldB_f constraints
- Iterator<RefEdge> itrRees = hrn.iteratorToReferencees();
- while( itrRees.hasNext() ) {
- RefEdge edge = itrRees.next();
-
- assert !boldB_f.containsKey(edge);
- boldB_f.put(edge, edge.getBeta() );
-
- assert !workSetEdges.contains(edge);
- workSetEdges.add(edge);
- }
-
- // enforce the boldB_f constraint at edges until we reach a fixed point
- while( !workSetEdges.isEmpty() ) {
- RefEdge edge = workSetEdges.iterator().next();
- workSetEdges.remove(edge);
-
- Iterator<RefEdge> itrPrime = edge.getDst().iteratorToReferencees();
- while( itrPrime.hasNext() ) {
- RefEdge edgePrime = itrPrime.next();
-
- ReachSet prevResult = boldB_f.get(edgePrime);
- ReachSet intersection = Canonical.intersection(boldB_f.get(edge),
- edgePrime.getBeta()
- );
-
- if( prevResult == null ||
- Canonical.unionORpreds(prevResult,
- intersection).size()
- > prevResult.size()
- ) {
-
- if( prevResult == null ) {
- boldB_f.put(edgePrime,
- Canonical.unionORpreds(edgePrime.getBeta(),
- intersection
- )
- );
- } else {
- boldB_f.put(edgePrime,
- Canonical.unionORpreds(prevResult,
- intersection
- )
- );
- }
- workSetEdges.add(edgePrime);
- }
- }
- }
+ HeapRegionNode hrn = hrnItr.next();
+
+ assert workSetEdges.isEmpty();
+
+ // initial boldB_f constraints
+ Iterator<RefEdge> itrRees = hrn.iteratorToReferencees();
+ while( itrRees.hasNext() ) {
+ RefEdge edge = itrRees.next();
+
+ assert !boldB_f.containsKey(edge);
+ boldB_f.put(edge, edge.getBeta() );
+
+ assert !workSetEdges.contains(edge);
+ workSetEdges.add(edge);
+ }
+
+ // enforce the boldB_f constraint at edges until we reach a fixed point
+ while( !workSetEdges.isEmpty() ) {
+ RefEdge edge = workSetEdges.iterator().next();
+ workSetEdges.remove(edge);
+
+ Iterator<RefEdge> itrPrime = edge.getDst().iteratorToReferencees();
+ while( itrPrime.hasNext() ) {
+ RefEdge edgePrime = itrPrime.next();
+
+ ReachSet prevResult = boldB_f.get(edgePrime);
+ ReachSet intersection = Canonical.intersection(boldB_f.get(edge),
+ edgePrime.getBeta()
+ );
+
+ if( prevResult == null ||
+ Canonical.unionORpreds(prevResult,
+ intersection).size()
+ > prevResult.size()
+ ) {
+
+ if( prevResult == null ) {
+ boldB_f.put(edgePrime,
+ Canonical.unionORpreds(edgePrime.getBeta(),
+ intersection
+ )
+ );
+ } else {
+ boldB_f.put(edgePrime,
+ Canonical.unionORpreds(prevResult,
+ intersection
+ )
+ );
+ }
+ workSetEdges.add(edgePrime);
+ }
+ }
+ }
}
if( inContext ) {
- boldBic.put(hrnID, boldB_f);
+ boldBic.put(hrnID, boldB_f);
} else {
- boldBooc.put(hrnID, boldB_f);
+ boldBooc.put(hrnID, boldB_f);
}
}
// global sweep, they serve as sources for the pass
// performed above
if( hrn.isOutOfContext() ) {
- continue;
+ continue;
}
// the inherent states of a region are the exception
// mark hrnIDs for removal
Iterator<ReachState> stateItr = hrn.getAlpha().iterator();
while( stateItr.hasNext() ) {
- ReachState stateOld = stateItr.next();
-
- ReachState markedHrnIDs = ReachState.factory();
-
- Iterator<ReachTuple> rtItr = stateOld.iterator();
- while( rtItr.hasNext() ) {
- ReachTuple rtOld = rtItr.next();
-
- // never remove the inherent hrnID from a flagged region
- // because it is trivially satisfied
- if( hrn.isFlagged() ) {
- if( rtOld == rtException ) {
- continue;
- }
- }
-
- // does boldB allow this hrnID?
- boolean foundState = false;
- Iterator<RefEdge> incidentEdgeItr = hrn.iteratorToReferencers();
- while( incidentEdgeItr.hasNext() ) {
- RefEdge incidentEdge = incidentEdgeItr.next();
-
- Hashtable<RefEdge, ReachSet> B;
- if( rtOld.isOutOfContext() ) {
- B = boldBooc.get(rtOld.getHrnID() );
- } else {
-
- if( !id2hrn.containsKey(rtOld.getHrnID() ) ) {
- // let symbols not in the graph get pruned
- break;
- }
-
- B = boldBic.get(rtOld.getHrnID() );
- }
-
- if( B != null ) {
- ReachSet boldB_rtOld_incident = B.get(incidentEdge);
- if( boldB_rtOld_incident != null &&
- boldB_rtOld_incident.containsIgnorePreds(stateOld) != null
- ) {
- foundState = true;
- }
- }
- }
-
- if( !foundState ) {
- markedHrnIDs = Canonical.addUpArity(markedHrnIDs, rtOld);
- }
- }
-
- // if there is nothing marked, just move on
- if( markedHrnIDs.isEmpty() ) {
- hrn.setAlphaNew(Canonical.add(hrn.getAlphaNew(),
- stateOld
- )
- );
- continue;
- }
-
- // remove all marked hrnIDs and establish a change set that should
- // propagate backwards over edges from this node
- ReachState statePruned = ReachState.factory();
- rtItr = stateOld.iterator();
- while( rtItr.hasNext() ) {
- ReachTuple rtOld = rtItr.next();
-
- if( !markedHrnIDs.containsTuple(rtOld) ) {
- statePruned = Canonical.addUpArity(statePruned, rtOld);
- }
- }
- assert !stateOld.equals(statePruned);
-
- hrn.setAlphaNew(Canonical.add(hrn.getAlphaNew(),
- statePruned
- )
- );
- ChangeTuple ct = ChangeTuple.factory(stateOld,
- statePruned
- );
- cts = Canonical.add(cts, ct);
+ ReachState stateOld = stateItr.next();
+
+ ReachState markedHrnIDs = ReachState.factory();
+
+ Iterator<ReachTuple> rtItr = stateOld.iterator();
+ while( rtItr.hasNext() ) {
+ ReachTuple rtOld = rtItr.next();
+
+ // never remove the inherent hrnID from a flagged region
+ // because it is trivially satisfied
+ if( hrn.isFlagged() ) {
+ if( rtOld == rtException ) {
+ continue;
+ }
+ }
+
+ // does boldB allow this hrnID?
+ boolean foundState = false;
+ Iterator<RefEdge> incidentEdgeItr = hrn.iteratorToReferencers();
+ while( incidentEdgeItr.hasNext() ) {
+ RefEdge incidentEdge = incidentEdgeItr.next();
+
+ Hashtable<RefEdge, ReachSet> B;
+ if( rtOld.isOutOfContext() ) {
+ B = boldBooc.get(rtOld.getHrnID() );
+ } else {
+
+ if( !id2hrn.containsKey(rtOld.getHrnID() ) ) {
+ // let symbols not in the graph get pruned
+ break;
+ }
+
+ B = boldBic.get(rtOld.getHrnID() );
+ }
+
+ if( B != null ) {
+ ReachSet boldB_rtOld_incident = B.get(incidentEdge);
+ if( boldB_rtOld_incident != null &&
+ boldB_rtOld_incident.containsIgnorePreds(stateOld) != null
+ ) {
+ foundState = true;
+ }
+ }
+ }
+
+ if( !foundState ) {
+ markedHrnIDs = Canonical.addUpArity(markedHrnIDs, rtOld);
+ }
+ }
+
+ // if there is nothing marked, just move on
+ if( markedHrnIDs.isEmpty() ) {
+ hrn.setAlphaNew(Canonical.add(hrn.getAlphaNew(),
+ stateOld
+ )
+ );
+ continue;
+ }
+
+ // remove all marked hrnIDs and establish a change set that should
+ // propagate backwards over edges from this node
+ ReachState statePruned = ReachState.factory();
+ rtItr = stateOld.iterator();
+ while( rtItr.hasNext() ) {
+ ReachTuple rtOld = rtItr.next();
+
+ if( !markedHrnIDs.containsTuple(rtOld) ) {
+ statePruned = Canonical.addUpArity(statePruned, rtOld);
+ }
+ }
+ assert !stateOld.equals(statePruned);
+
+ hrn.setAlphaNew(Canonical.add(hrn.getAlphaNew(),
+ statePruned
+ )
+ );
+ ChangeTuple ct = ChangeTuple.factory(stateOld,
+ statePruned
+ );
+ cts = Canonical.add(cts, ct);
}
// throw change tuple set on all incident edges
if( !cts.isEmpty() ) {
- Iterator<RefEdge> incidentEdgeItr = hrn.iteratorToReferencers();
- while( incidentEdgeItr.hasNext() ) {
- RefEdge incidentEdge = incidentEdgeItr.next();
-
- edgesForPropagation.add(incidentEdge);
-
- if( edgePlannedChanges.get(incidentEdge) == null ) {
- edgePlannedChanges.put(incidentEdge, cts);
- } else {
- edgePlannedChanges.put(
- incidentEdge,
- Canonical.union(edgePlannedChanges.get(incidentEdge),
- cts
- )
- );
- }
- }
+ Iterator<RefEdge> incidentEdgeItr = hrn.iteratorToReferencers();
+ while( incidentEdgeItr.hasNext() ) {
+ RefEdge incidentEdge = incidentEdgeItr.next();
+
+ edgesForPropagation.add(incidentEdge);
+
+ if( edgePlannedChanges.get(incidentEdge) == null ) {
+ edgePlannedChanges.put(incidentEdge, cts);
+ } else {
+ edgePlannedChanges.put(
+ incidentEdge,
+ Canonical.union(edgePlannedChanges.get(incidentEdge),
+ cts
+ )
+ );
+ }
+ }
}
}
// as sources of reach states for the sweep, not part
// of the changes
if( hrn.isOutOfContext() ) {
- assert hrn.getAlphaNew().equals(rsetEmpty);
+ assert hrn.getAlphaNew().equals(rsetEmpty);
} else {
- hrn.applyAlphaNew();
+ hrn.applyAlphaNew();
}
Iterator<RefEdge> itrRes = hrn.iteratorToReferencers();
while( itrRes.hasNext() ) {
- res.add(itrRes.next() );
+ res.add(itrRes.next() );
}
}
// commit results of last phase
if( edgesUpdated.contains(edge) ) {
- edge.applyBetaNew();
+ edge.applyBetaNew();
}
// compute intial condition of 2nd phase
RefSrcNode rsn = edgePrime.getSrc();
if( !(rsn instanceof HeapRegionNode) ) {
- continue;
+ continue;
}
HeapRegionNode hrn = (HeapRegionNode) rsn;
Iterator<RefEdge> itrEdge = hrn.iteratorToReferencers();
while( itrEdge.hasNext() ) {
- RefEdge edge = itrEdge.next();
-
- ReachSet prevResult = edge.getBetaNew();
- assert prevResult != null;
-
- ReachSet intersection =
- Canonical.intersection(edge.getBeta(),
- edgePrime.getBetaNew()
- );
-
- if( Canonical.unionORpreds(prevResult,
- intersection
- ).size()
- > prevResult.size()
- ) {
-
- edge.setBetaNew(
- Canonical.unionORpreds(prevResult,
- intersection
- )
- );
- edgeWorkSet.add(edge);
- }
+ RefEdge edge = itrEdge.next();
+
+ ReachSet prevResult = edge.getBetaNew();
+ assert prevResult != null;
+
+ ReachSet intersection =
+ Canonical.intersection(edge.getBeta(),
+ edgePrime.getBetaNew()
+ );
+
+ if( Canonical.unionORpreds(prevResult,
+ intersection
+ ).size()
+ > prevResult.size()
+ ) {
+
+ edge.setBetaNew(
+ Canonical.unionORpreds(prevResult,
+ intersection
+ )
+ );
+ edgeWorkSet.add(edge);
+ }
}
}
HeapRegionNode hrn = (HeapRegionNode) me.getValue();
{
- Iterator<ReachState> stateItr = hrn.getAlpha().iterator();
- while( stateItr.hasNext() ) {
- ReachState state = stateItr.next();
-
- Iterator<ReachTuple> rtItr = state.iterator();
- while( rtItr.hasNext() ) {
- ReachTuple rt = rtItr.next();
-
- if( !rt.isOutOfContext() ) {
- if( !id2hrn.containsKey(rt.getHrnID() ) ) {
- System.out.println(rt.getHrnID()+" is missing");
- return false;
- }
- }
- }
- }
+ Iterator<ReachState> stateItr = hrn.getAlpha().iterator();
+ while( stateItr.hasNext() ) {
+ ReachState state = stateItr.next();
+
+ Iterator<ReachTuple> rtItr = state.iterator();
+ while( rtItr.hasNext() ) {
+ ReachTuple rt = rtItr.next();
+
+ if( !rt.isOutOfContext() ) {
+ if( !id2hrn.containsKey(rt.getHrnID() ) ) {
+ System.out.println(rt.getHrnID()+" is missing");
+ return false;
+ }
+ }
+ }
+ }
}
Iterator<RefEdge> edgeItr = hrn.iteratorToReferencers();
while( edgeItr.hasNext() ) {
- RefEdge edge = edgeItr.next();
-
- Iterator<ReachState> stateItr = edge.getBeta().iterator();
- while( stateItr.hasNext() ) {
- ReachState state = stateItr.next();
-
- Iterator<ReachTuple> rtItr = state.iterator();
- while( rtItr.hasNext() ) {
- ReachTuple rt = rtItr.next();
-
- if( !rt.isOutOfContext() ) {
- if( !id2hrn.containsKey(rt.getHrnID() ) ) {
- System.out.println(rt.getHrnID()+" is missing");
- return false;
- }
- }
- }
- }
+ RefEdge edge = edgeItr.next();
+
+ Iterator<ReachState> stateItr = edge.getBeta().iterator();
+ while( stateItr.hasNext() ) {
+ ReachState state = stateItr.next();
+
+ Iterator<ReachTuple> rtItr = state.iterator();
+ while( rtItr.hasNext() ) {
+ ReachTuple rt = rtItr.next();
+
+ if( !rt.isOutOfContext() ) {
+ if( !id2hrn.containsKey(rt.getHrnID() ) ) {
+ System.out.println(rt.getHrnID()+" is missing");
+ return false;
+ }
+ }
+ }
+ }
}
}
!hrn.isWiped() &&
hrn.getAlpha().isEmpty()
) {
- System.out.println("!!! "+hrn+" has an empty ReachSet !!!");
- return false;
+ System.out.println("!!! "+hrn+" has an empty ReachSet !!!");
+ return false;
}
Iterator<RefEdge> edgeItr = hrn.iteratorToReferencers();
while( edgeItr.hasNext() ) {
- RefEdge edge = edgeItr.next();
+ RefEdge edge = edgeItr.next();
- if( edge.getBeta().isEmpty() ) {
- System.out.println("!!! "+edge+" has an empty ReachSet !!!");
- return false;
- }
+ if( edge.getBeta().isEmpty() ) {
+ System.out.println("!!! "+edge+" has an empty ReachSet !!!");
+ return false;
+ }
}
}
HeapRegionNode hrn = (HeapRegionNode) me.getValue();
{
- Iterator<ReachState> stateItr = hrn.getAlpha().iterator();
- while( stateItr.hasNext() ) {
- ReachState state = stateItr.next();
-
- if( !state.getPreds().equals(predsTrue) ) {
- return false;
- }
- }
+ Iterator<ReachState> stateItr = hrn.getAlpha().iterator();
+ while( stateItr.hasNext() ) {
+ ReachState state = stateItr.next();
+
+ if( !state.getPreds().equals(predsTrue) ) {
+ return false;
+ }
+ }
}
Iterator<RefEdge> edgeItr = hrn.iteratorToReferencers();
while( edgeItr.hasNext() ) {
- RefEdge edge = edgeItr.next();
+ RefEdge edge = edgeItr.next();
- Iterator<ReachState> stateItr = edge.getBeta().iterator();
- while( stateItr.hasNext() ) {
- ReachState state = stateItr.next();
+ Iterator<ReachState> stateItr = edge.getBeta().iterator();
+ while( stateItr.hasNext() ) {
+ ReachState state = stateItr.next();
- if( !state.getPreds().equals(predsTrue) ) {
- return false;
- }
- }
+ if( !state.getPreds().equals(predsTrue) ) {
+ return false;
+ }
+ }
}
}
// if this graph doesn't have a node the
// incoming graph has, allocate it
if( !id2hrn.containsKey(idA) ) {
- HeapRegionNode hrnB = hrnA.copy();
- id2hrn.put(idA, hrnB);
+ HeapRegionNode hrnB = hrnA.copy();
+ id2hrn.put(idA, hrnB);
} else {
- // otherwise this is a node present in both graphs
- // so make the new reachability set a union of the
- // nodes' reachability sets
- HeapRegionNode hrnB = id2hrn.get(idA);
- hrnB.setAlpha(Canonical.unionORpreds(hrnB.getAlpha(),
- hrnA.getAlpha()
- )
- );
+ // otherwise this is a node present in both graphs
+ // so make the new reachability set a union of the
+ // nodes' reachability sets
+ HeapRegionNode hrnB = id2hrn.get(idA);
+ hrnB.setAlpha(Canonical.unionORpreds(hrnB.getAlpha(),
+ hrnA.getAlpha()
+ )
+ );
- hrnB.setPreds(Canonical.join(hrnB.getPreds(),
- hrnA.getPreds()
- )
- );
+ hrnB.setPreds(Canonical.join(hrnB.getPreds(),
+ hrnA.getPreds()
+ )
+ );
- if( !hrnA.equals(hrnB) ) {
- rg.writeGraph("graphA");
- this.writeGraph("graphB");
- throw new Error("flagged not matching");
- }
+ if( !hrnA.equals(hrnB) ) {
+ rg.writeGraph("graphA");
+ this.writeGraph("graphB");
+ throw new Error("flagged not matching");
+ }
Iterator<RefEdge> heapRegionsItrA = hrnA.iteratorToReferencees();
while( heapRegionsItrA.hasNext() ) {
- RefEdge edgeA = heapRegionsItrA.next();
- HeapRegionNode hrnChildA = edgeA.getDst();
- Integer idChildA = hrnChildA.getID();
-
- // at this point we know an edge in graph A exists
- // idA -> idChildA, does this exist in B?
- assert id2hrn.containsKey(idA);
- HeapRegionNode hrnB = id2hrn.get(idA);
- RefEdge edgeToMerge = null;
-
- Iterator<RefEdge> heapRegionsItrB = hrnB.iteratorToReferencees();
- while( heapRegionsItrB.hasNext() &&
- edgeToMerge == null ) {
-
- RefEdge edgeB = heapRegionsItrB.next();
- HeapRegionNode hrnChildB = edgeB.getDst();
- Integer idChildB = hrnChildB.getID();
-
- // don't use the RefEdge.equals() here because
- // we're talking about existence between graphs,
- // not intragraph equal
- if( idChildB.equals(idChildA) &&
- edgeB.typeAndFieldEquals(edgeA) ) {
-
- edgeToMerge = edgeB;
- }
- }
-
- // if the edge from A was not found in B,
- // add it to B.
- if( edgeToMerge == null ) {
- assert id2hrn.containsKey(idChildA);
- HeapRegionNode hrnChildB = id2hrn.get(idChildA);
- edgeToMerge = edgeA.copy();
- edgeToMerge.setSrc(hrnB);
- edgeToMerge.setDst(hrnChildB);
- addRefEdge(hrnB, hrnChildB, edgeToMerge);
- }
- // otherwise, the edge already existed in both graphs
- // so merge their reachability sets
- else {
- // just replace this beta set with the union
- assert edgeToMerge != null;
- edgeToMerge.setBeta(
- Canonical.unionORpreds(edgeToMerge.getBeta(),
- edgeA.getBeta()
- )
- );
- edgeToMerge.setPreds(
- Canonical.join(edgeToMerge.getPreds(),
- edgeA.getPreds()
- )
- );
- edgeToMerge.setTaints(
- Canonical.union(edgeToMerge.getTaints(),
- edgeA.getTaints()
- )
- );
- }
+ RefEdge edgeA = heapRegionsItrA.next();
+ HeapRegionNode hrnChildA = edgeA.getDst();
+ Integer idChildA = hrnChildA.getID();
+
+ // at this point we know an edge in graph A exists
+ // idA -> idChildA, does this exist in B?
+ assert id2hrn.containsKey(idA);
+ HeapRegionNode hrnB = id2hrn.get(idA);
+ RefEdge edgeToMerge = null;
+
+ Iterator<RefEdge> heapRegionsItrB = hrnB.iteratorToReferencees();
+ while( heapRegionsItrB.hasNext() &&
+ edgeToMerge == null ) {
+
+ RefEdge edgeB = heapRegionsItrB.next();
+ HeapRegionNode hrnChildB = edgeB.getDst();
+ Integer idChildB = hrnChildB.getID();
+
+ // don't use the RefEdge.equals() here because
+ // we're talking about existence between graphs,
+ // not intragraph equal
+ if( idChildB.equals(idChildA) &&
+ edgeB.typeAndFieldEquals(edgeA) ) {
+
+ edgeToMerge = edgeB;
+ }
+ }
+
+ // if the edge from A was not found in B,
+ // add it to B.
+ if( edgeToMerge == null ) {
+ assert id2hrn.containsKey(idChildA);
+ HeapRegionNode hrnChildB = id2hrn.get(idChildA);
+ edgeToMerge = edgeA.copy();
+ edgeToMerge.setSrc(hrnB);
+ edgeToMerge.setDst(hrnChildB);
+ addRefEdge(hrnB, hrnChildB, edgeToMerge);
+ }
+ // otherwise, the edge already existed in both graphs
+ // so merge their reachability sets
+ else {
+ // just replace this beta set with the union
+ assert edgeToMerge != null;
+ edgeToMerge.setBeta(
+ Canonical.unionORpreds(edgeToMerge.getBeta(),
+ edgeA.getBeta()
+ )
+ );
+ edgeToMerge.setPreds(
+ Canonical.join(edgeToMerge.getPreds(),
+ edgeA.getPreds()
+ )
+ );
+ edgeToMerge.setTaints(
+ Canonical.union(edgeToMerge.getTaints(),
+ edgeA.getTaints()
+ )
+ );
+ }
}
}
Iterator<RefEdge> heapRegionsItrA = vnA.iteratorToReferencees();
while( heapRegionsItrA.hasNext() ) {
- RefEdge edgeA = heapRegionsItrA.next();
- HeapRegionNode hrnChildA = edgeA.getDst();
- Integer idChildA = hrnChildA.getID();
-
- // at this point we know an edge in graph A exists
- // tdA -> idChildA, does this exist in B?
- assert td2vn.containsKey(tdA);
- VariableNode vnB = td2vn.get(tdA);
- RefEdge edgeToMerge = null;
-
- Iterator<RefEdge> heapRegionsItrB = vnB.iteratorToReferencees();
- while( heapRegionsItrB.hasNext() &&
- edgeToMerge == null ) {
-
- RefEdge edgeB = heapRegionsItrB.next();
- HeapRegionNode hrnChildB = edgeB.getDst();
- Integer idChildB = hrnChildB.getID();
-
- // don't use the RefEdge.equals() here because
- // we're talking about existence between graphs
- if( idChildB.equals(idChildA) &&
- edgeB.typeAndFieldEquals(edgeA) ) {
-
- edgeToMerge = edgeB;
- }
- }
-
- // if the edge from A was not found in B,
- // add it to B.
- if( edgeToMerge == null ) {
- assert id2hrn.containsKey(idChildA);
- HeapRegionNode hrnChildB = id2hrn.get(idChildA);
- edgeToMerge = edgeA.copy();
- edgeToMerge.setSrc(vnB);
- edgeToMerge.setDst(hrnChildB);
- addRefEdge(vnB, hrnChildB, edgeToMerge);
- }
- // otherwise, the edge already existed in both graphs
- // so merge their reachability sets
- else {
- // just replace this beta set with the union
- edgeToMerge.setBeta(Canonical.unionORpreds(edgeToMerge.getBeta(),
- edgeA.getBeta()
- )
- );
- edgeToMerge.setPreds(Canonical.join(edgeToMerge.getPreds(),
- edgeA.getPreds()
- )
- );
- edgeToMerge.setTaints(
- Canonical.union(edgeToMerge.getTaints(),
- edgeA.getTaints()
- )
- );
- }
+ RefEdge edgeA = heapRegionsItrA.next();
+ HeapRegionNode hrnChildA = edgeA.getDst();
+ Integer idChildA = hrnChildA.getID();
+
+ // at this point we know an edge in graph A exists
+ // tdA -> idChildA, does this exist in B?
+ assert td2vn.containsKey(tdA);
+ VariableNode vnB = td2vn.get(tdA);
+ RefEdge edgeToMerge = null;
+
+ Iterator<RefEdge> heapRegionsItrB = vnB.iteratorToReferencees();
+ while( heapRegionsItrB.hasNext() &&
+ edgeToMerge == null ) {
+
+ RefEdge edgeB = heapRegionsItrB.next();
+ HeapRegionNode hrnChildB = edgeB.getDst();
+ Integer idChildB = hrnChildB.getID();
+
+ // don't use the RefEdge.equals() here because
+ // we're talking about existence between graphs
+ if( idChildB.equals(idChildA) &&
+ edgeB.typeAndFieldEquals(edgeA) ) {
+
+ edgeToMerge = edgeB;
+ }
+ }
+
+ // if the edge from A was not found in B,
+ // add it to B.
+ if( edgeToMerge == null ) {
+ assert id2hrn.containsKey(idChildA);
+ HeapRegionNode hrnChildB = id2hrn.get(idChildA);
+ edgeToMerge = edgeA.copy();
+ edgeToMerge.setSrc(vnB);
+ edgeToMerge.setDst(hrnChildB);
+ addRefEdge(vnB, hrnChildB, edgeToMerge);
+ }
+ // otherwise, the edge already existed in both graphs
+ // so merge their reachability sets
+ else {
+ // just replace this beta set with the union
+ edgeToMerge.setBeta(Canonical.unionORpreds(edgeToMerge.getBeta(),
+ edgeA.getBeta()
+ )
+ );
+ edgeToMerge.setPreds(Canonical.join(edgeToMerge.getPreds(),
+ edgeA.getPreds()
+ )
+ );
+ edgeToMerge.setTaints(
+ Canonical.union(edgeToMerge.getTaints(),
+ edgeA.getTaints()
+ )
+ );
+ }
}
}
}
if( rg == null ) {
if( dbgEquals ) {
- System.out.println("rg is null");
+ System.out.println("rg is null");
}
return false;
}
if( !areHeapRegionNodesEqual(rg) ) {
if( dbgEquals ) {
- System.out.println("hrn not equal");
+ System.out.println("hrn not equal");
}
return false;
}
if( !areVariableNodesEqual(rg) ) {
if( dbgEquals ) {
- System.out.println("vars not equal");
+ System.out.println("vars not equal");
}
return false;
}
if( !areRefEdgesEqual(rg) ) {
if( dbgEquals ) {
- System.out.println("edges not equal");
+ System.out.println("edges not equal");
}
return false;
}
HeapRegionNode hrnA = (HeapRegionNode) meA.getValue();
if( !rgB.id2hrn.containsKey(idA) ) {
- return false;
+ return false;
}
HeapRegionNode hrnB = rgB.id2hrn.get(idA);
if( !hrnA.equalsIncludingAlphaAndPreds(hrnB) ) {
- return false;
+ return false;
}
}
TempDescriptor tdA = (TempDescriptor) meA.getKey();
if( !rgB.td2vn.containsKey(tdA) ) {
- return false;
+ return false;
}
}
assert rgB.id2hrn.containsKey(idA);
if( !areallREfromAequaltoB(rgA, hrnA, rgB) ) {
- return false;
+ return false;
}
// then check every edge in B for presence in A, starting
HeapRegionNode hrnB = rgB.id2hrn.get(idA);
if( !areallREfromAequaltoB(rgB, hrnB, rgA) ) {
- return false;
+ return false;
}
}
assert rgB.td2vn.containsKey(tdA);
if( !areallREfromAequaltoB(rgA, vnA, rgB) ) {
- return false;
+ return false;
}
// then check every edge in B for presence in A, starting
VariableNode vnB = rgB.td2vn.get(tdA);
if( !areallREfromAequaltoB(rgB, vnB, rgA) ) {
- return false;
+ return false;
}
}
RefSrcNode rnB = null;
if( rnA instanceof HeapRegionNode ) {
- HeapRegionNode hrnA = (HeapRegionNode) rnA;
- rnB = rgB.id2hrn.get(hrnA.getID() );
+ HeapRegionNode hrnA = (HeapRegionNode) rnA;
+ rnB = rgB.id2hrn.get(hrnA.getID() );
} else {
- VariableNode vnA = (VariableNode) rnA;
- rnB = rgB.td2vn.get(vnA.getTempDescriptor() );
+ VariableNode vnA = (VariableNode) rnA;
+ rnB = rgB.td2vn.get(vnA.getTempDescriptor() );
}
Iterator<RefEdge> itrB = rnB.iteratorToReferencees();
while( itrB.hasNext() ) {
- RefEdge edgeB = itrB.next();
- HeapRegionNode hrnChildB = edgeB.getDst();
- Integer idChildB = hrnChildB.getID();
-
- if( idChildA.equals(idChildB) &&
- edgeA.typeAndFieldEquals(edgeB) ) {
-
- // there is an edge in the right place with the right field,
- // but do they have the same attributes?
- if( edgeA.getBeta().equals(edgeB.getBeta() ) &&
- edgeA.equalsPreds(edgeB)
- ) {
- edgeFound = true;
- }
- }
+ RefEdge edgeB = itrB.next();
+ HeapRegionNode hrnChildB = edgeB.getDst();
+ Integer idChildB = hrnChildB.getID();
+
+ if( idChildA.equals(idChildB) &&
+ edgeA.typeAndFieldEquals(edgeB) ) {
+
+ // there is an edge in the right place with the right field,
+ // but do they have the same attributes?
+ if( edgeA.getBeta().equals(edgeB.getBeta() ) &&
+ edgeA.equalsPreds(edgeB)
+ ) {
+ edgeFound = true;
+ }
+ }
}
if( !edgeFound ) {
- return false;
+ return false;
}
}
HeapRegionNode hrnA = (HeapRegionNode) meA.getValue();
if( !rgB.id2hrn.containsKey(idA) ) {
- System.out.println(" regions smaller");
- return false;
+ System.out.println(" regions smaller");
+ return false;
}
//HeapRegionNode hrnB = rgB.id2hrn.get( idA );
Iterator<RefEdge> reItr = hrnA.iteratorToReferencers();
while( reItr.hasNext() ) {
- RefEdge edgeA = reItr.next();
- RefSrcNode rsnA = edgeA.getSrc();
-
- // we already checked that nodes were present
- HeapRegionNode hrnB = rgB.id2hrn.get(hrnA.getID() );
- assert hrnB != null;
-
- RefSrcNode rsnB;
- if( rsnA instanceof VariableNode ) {
- VariableNode vnA = (VariableNode) rsnA;
- rsnB = rgB.td2vn.get(vnA.getTempDescriptor() );
-
- } else {
- HeapRegionNode hrnSrcA = (HeapRegionNode) rsnA;
- rsnB = rgB.id2hrn.get(hrnSrcA.getID() );
- }
- assert rsnB != null;
-
- RefEdge edgeB = rsnB.getReferenceTo(hrnB,
- edgeA.getType(),
- edgeA.getField()
- );
- if( edgeB == null ) {
- System.out.println(" edges smaller:");
- return false;
- }
-
- // REMEMBER, IS NO SMALLER THAN
- /*
- System.out.println( " edges smaller" );
- return false;
- }
- */
+ RefEdge edgeA = reItr.next();
+ RefSrcNode rsnA = edgeA.getSrc();
+
+ // we already checked that nodes were present
+ HeapRegionNode hrnB = rgB.id2hrn.get(hrnA.getID() );
+ assert hrnB != null;
+
+ RefSrcNode rsnB;
+ if( rsnA instanceof VariableNode ) {
+ VariableNode vnA = (VariableNode) rsnA;
+ rsnB = rgB.td2vn.get(vnA.getTempDescriptor() );
+
+ } else {
+ HeapRegionNode hrnSrcA = (HeapRegionNode) rsnA;
+ rsnB = rgB.id2hrn.get(hrnSrcA.getID() );
+ }
+ assert rsnB != null;
+
+ RefEdge edgeB = rsnB.getReferenceTo(hrnB,
+ edgeA.getType(),
+ edgeA.getField()
+ );
+ if( edgeB == null ) {
+ System.out.println(" edges smaller:");
+ return false;
+ }
+
+ // REMEMBER, IS NO SMALLER THAN
+ /*
+ System.out.println( " edges smaller" );
+ return false;
+ }
+ */
}
}
assert tdSrcDeref != null;
if( !typeUtil.isSuperorType(tdSrcDeref, td) ) {
- return false;
+ return false;
}
return edge.getField().equals(DisjointAnalysis.arrayElementFieldName);
Iterator fieldItr = cd.getFields();
while( fieldItr.hasNext() ) {
- FieldDescriptor fd = (FieldDescriptor) fieldItr.next();
+ FieldDescriptor fd = (FieldDescriptor) fieldItr.next();
- if( fd.getType().equals(edge.getType() ) &&
- fd.getSymbol().equals(edge.getField() ) ) {
- return true;
- }
+ if( fd.getType().equals(edge.getType() ) &&
+ fd.getSymbol().equals(edge.getField() ) ) {
+ return true;
+ }
}
cd = cd.getSuperDesc();
// "cut-out" into a DOT cluster for visualization
if( callerNodeIDsCopiedToCallee != null ) {
- bw.write(" subgraph cluster0 {\n");
- bw.write(" color=blue;\n");
-
- Iterator i = id2hrn.entrySet().iterator();
- while( i.hasNext() ) {
- Map.Entry me = (Map.Entry)i.next();
- HeapRegionNode hrn = (HeapRegionNode) me.getValue();
-
- if( callerNodeIDsCopiedToCallee.contains(hrn.getID() ) ) {
- bw.write(" "+
- hrn.toString()+
- hrn.toStringDOT(hideReachability,
- hideSubsetReachability,
- hidePredicates)+
- ";\n");
- }
- }
-
- bw.write(" }\n");
+ bw.write(" subgraph cluster0 {\n");
+ bw.write(" color=blue;\n");
+
+ Iterator i = id2hrn.entrySet().iterator();
+ while( i.hasNext() ) {
+ Map.Entry me = (Map.Entry)i.next();
+ HeapRegionNode hrn = (HeapRegionNode) me.getValue();
+
+ if( callerNodeIDsCopiedToCallee.contains(hrn.getID() ) ) {
+ bw.write(" "+
+ hrn.toString()+
+ hrn.toStringDOT(hideReachability,
+ hideSubsetReachability,
+ hidePredicates)+
+ ";\n");
+ }
+ }
+
+ bw.write(" }\n");
}
// then visit every heap region node
Iterator i = id2hrn.entrySet().iterator();
while( i.hasNext() ) {
- Map.Entry me = (Map.Entry)i.next();
- HeapRegionNode hrn = (HeapRegionNode) me.getValue();
-
- // only visit nodes worth writing out--for instance
- // not every node at an allocation is referenced
- // (think of it as garbage-collected), etc.
- if( !pruneGarbage ||
- hrn.isOutOfContext() ||
- (hrn.isFlagged() && hrn.getID() > 0 && !hrn.isWiped()) // a non-shadow flagged node
- ) {
-
- if( !visited.contains(hrn) ) {
- traverseHeapRegionNodes(hrn,
- bw,
- null,
- visited,
- hideReachability,
- hideSubsetReachability,
- hidePredicates,
- hideEdgeTaints,
- callerNodeIDsCopiedToCallee);
- }
- }
+ Map.Entry me = (Map.Entry)i.next();
+ HeapRegionNode hrn = (HeapRegionNode) me.getValue();
+
+ // only visit nodes worth writing out--for instance
+ // not every node at an allocation is referenced
+ // (think of it as garbage-collected), etc.
+ if( !pruneGarbage ||
+ hrn.isOutOfContext() ||
+ (hrn.isFlagged() && hrn.getID() > 0 && !hrn.isWiped()) // a non-shadow flagged node
+ ) {
+
+ if( !visited.contains(hrn) ) {
+ traverseHeapRegionNodes(hrn,
+ bw,
+ null,
+ visited,
+ hideReachability,
+ hideSubsetReachability,
+ hidePredicates,
+ hideEdgeTaints,
+ callerNodeIDsCopiedToCallee);
+ }
+ }
}
bw.write(" graphTitle[label=\""+graphName+"\",shape=box];\n");
// then visit every label node, useful for debugging
if( writeLabels ) {
- i = td2vn.entrySet().iterator();
- while( i.hasNext() ) {
- Map.Entry me = (Map.Entry)i.next();
- VariableNode vn = (VariableNode) me.getValue();
-
- if( labelSelect ) {
- String labelStr = vn.getTempDescriptorString();
- if( labelStr.startsWith("___temp") ||
- labelStr.startsWith("___dst") ||
- labelStr.startsWith("___srctmp") ||
- labelStr.startsWith("___neverused")
- ) {
- continue;
- }
- }
-
- Iterator<RefEdge> heapRegionsItr = vn.iteratorToReferencees();
- while( heapRegionsItr.hasNext() ) {
- RefEdge edge = heapRegionsItr.next();
- HeapRegionNode hrn = edge.getDst();
-
- if( !visited.contains(hrn) ) {
- traverseHeapRegionNodes(hrn,
- bw,
- null,
- visited,
- hideReachability,
- hideSubsetReachability,
- hidePredicates,
- hideEdgeTaints,
- callerNodeIDsCopiedToCallee);
- }
-
- bw.write(" "+vn.toString()+
- " -> "+hrn.toString()+
- edge.toStringDOT(hideReachability,
- hideSubsetReachability,
- hidePredicates,
- hideEdgeTaints,
- "")+
- ";\n");
- }
- }
+ i = td2vn.entrySet().iterator();
+ while( i.hasNext() ) {
+ Map.Entry me = (Map.Entry)i.next();
+ VariableNode vn = (VariableNode) me.getValue();
+
+ if( labelSelect ) {
+ String labelStr = vn.getTempDescriptorString();
+ if( labelStr.startsWith("___temp") ||
+ labelStr.startsWith("___dst") ||
+ labelStr.startsWith("___srctmp") ||
+ labelStr.startsWith("___neverused")
+ ) {
+ continue;
+ }
+ }
+
+ Iterator<RefEdge> heapRegionsItr = vn.iteratorToReferencees();
+ while( heapRegionsItr.hasNext() ) {
+ RefEdge edge = heapRegionsItr.next();
+ HeapRegionNode hrn = edge.getDst();
+
+ if( !visited.contains(hrn) ) {
+ traverseHeapRegionNodes(hrn,
+ bw,
+ null,
+ visited,
+ hideReachability,
+ hideSubsetReachability,
+ hidePredicates,
+ hideEdgeTaints,
+ callerNodeIDsCopiedToCallee);
+ }
+
+ bw.write(" "+vn.toString()+
+ " -> "+hrn.toString()+
+ edge.toStringDOT(hideReachability,
+ hideSubsetReachability,
+ hidePredicates,
+ hideEdgeTaints,
+ "")+
+ ";\n");
+ }
+ }
}
bw.write("}\n");
if( callerNodeIDsCopiedToCallee != null &&
(edge.getSrc() instanceof HeapRegionNode) ) {
- HeapRegionNode hrnSrc = (HeapRegionNode) edge.getSrc();
- if( callerNodeIDsCopiedToCallee.contains(hrnSrc.getID() ) &&
- callerNodeIDsCopiedToCallee.contains(edge.getDst().getID() )
- ) {
- bw.write(" "+hrn.toString()+
- " -> "+hrnChild.toString()+
- edge.toStringDOT(hideReachability,
- hideSubsetReachability,
- hidePredicates,
- hideEdgeTaints,
- ",color=blue")+
- ";\n");
- } else if( !callerNodeIDsCopiedToCallee.contains(hrnSrc.getID() ) &&
- callerNodeIDsCopiedToCallee.contains(edge.getDst().getID() )
- ) {
- bw.write(" "+hrn.toString()+
- " -> "+hrnChild.toString()+
- edge.toStringDOT(hideReachability,
- hideSubsetReachability,
- hidePredicates,
- hideEdgeTaints,
- ",color=blue,style=dashed")+
- ";\n");
- } else {
- bw.write(" "+hrn.toString()+
- " -> "+hrnChild.toString()+
- edge.toStringDOT(hideReachability,
- hideSubsetReachability,
- hidePredicates,
- hideEdgeTaints,
- "")+
- ";\n");
- }
+ HeapRegionNode hrnSrc = (HeapRegionNode) edge.getSrc();
+ if( callerNodeIDsCopiedToCallee.contains(hrnSrc.getID() ) &&
+ callerNodeIDsCopiedToCallee.contains(edge.getDst().getID() )
+ ) {
+ bw.write(" "+hrn.toString()+
+ " -> "+hrnChild.toString()+
+ edge.toStringDOT(hideReachability,
+ hideSubsetReachability,
+ hidePredicates,
+ hideEdgeTaints,
+ ",color=blue")+
+ ";\n");
+ } else if( !callerNodeIDsCopiedToCallee.contains(hrnSrc.getID() ) &&
+ callerNodeIDsCopiedToCallee.contains(edge.getDst().getID() )
+ ) {
+ bw.write(" "+hrn.toString()+
+ " -> "+hrnChild.toString()+
+ edge.toStringDOT(hideReachability,
+ hideSubsetReachability,
+ hidePredicates,
+ hideEdgeTaints,
+ ",color=blue,style=dashed")+
+ ";\n");
+ } else {
+ bw.write(" "+hrn.toString()+
+ " -> "+hrnChild.toString()+
+ edge.toStringDOT(hideReachability,
+ hideSubsetReachability,
+ hidePredicates,
+ hideEdgeTaints,
+ "")+
+ ";\n");
+ }
} else {
- bw.write(" "+hrn.toString()+
- " -> "+hrnChild.toString()+
- edge.toStringDOT(hideReachability,
- hideSubsetReachability,
- hidePredicates,
- hideEdgeTaints,
- "")+
- ";\n");
+ bw.write(" "+hrn.toString()+
+ " -> "+hrnChild.toString()+
+ edge.toStringDOT(hideReachability,
+ hideSubsetReachability,
+ hidePredicates,
+ hideEdgeTaints,
+ "")+
+ ";\n");
}
traverseHeapRegionNodes(hrnChild,
for( int i = 0; i < as.getAllocationDepth(); ++i ) {
Integer idI = as.getIthOldest(i);
if( id2hrn.containsKey(idI) ) {
- out.add(id2hrn.get(idI) );
+ out.add(id2hrn.get(idI) );
}
}
assert !hrn.isOutOfContext();
if( !includeARITY_ZEROORMORE ) {
- out.add(ReachTuple.factory(hrn.getID(),
- true, // multi-obj region
- ReachTuple.ARITY_ZEROORMORE,
- false) // ooc?
- );
+ out.add(ReachTuple.factory(hrn.getID(),
+ true, // multi-obj region
+ ReachTuple.ARITY_ZEROORMORE,
+ false) // ooc?
+ );
}
if( includeARITY_ONE ) {
- out.add(ReachTuple.factory(hrn.getID(),
- true, // multi-object region
- ReachTuple.ARITY_ONE,
- false) // ooc?
- );
+ out.add(ReachTuple.factory(hrn.getID(),
+ true, // multi-object region
+ ReachTuple.ARITY_ONE,
+ false) // ooc?
+ );
}
}
Integer idI = as.getIthOldest(i);
if( id2hrn.containsKey(idI) ) {
- HeapRegionNode hrn = id2hrn.get(idI);
- assert !hrn.isOutOfContext();
+ HeapRegionNode hrn = id2hrn.get(idI);
+ assert !hrn.isOutOfContext();
- out.add(ReachTuple.factory(hrn.getID(),
- false, // multi-object region
- ReachTuple.ARITY_ONE,
- false) // ooc?
- );
+ out.add(ReachTuple.factory(hrn.getID(),
+ false, // multi-object region
+ ReachTuple.ARITY_ONE,
+ false) // ooc?
+ );
}
}
Iterator<ReachTuple> rtItr1 = rtSet1.iterator();
while( rtItr1.hasNext() ) {
- ReachTuple rt1 = rtItr1.next();
+ ReachTuple rt1 = rtItr1.next();
- Iterator<ReachTuple> rtItr2 = rtSet2.iterator();
- while( rtItr2.hasNext() ) {
- ReachTuple rt2 = rtItr2.next();
+ Iterator<ReachTuple> rtItr2 = rtSet2.iterator();
+ while( rtItr2.hasNext() ) {
+ ReachTuple rt2 = rtItr2.next();
- if( !hrn.getAlpha().getStatesWithBoth(rt1, rt2).isEmpty() ) {
- return true;
- }
- }
+ if( !hrn.getAlpha().getStatesWithBoth(rt1, rt2).isEmpty() ) {
+ return true;
+ }
+ }
}
}
// if any ZERORMORE tuples are here, TRUE
Iterator<ReachTuple> rtItr = rtSetZOM.iterator();
while( rtItr.hasNext() ) {
- ReachTuple rtZOM = rtItr.next();
+ ReachTuple rtZOM = rtItr.next();
- if( hrn.getAlpha().containsTuple(rtZOM) ) {
- return true;
- }
+ if( hrn.getAlpha().containsTuple(rtZOM) ) {
+ return true;
+ }
}
// otherwise, look for any pair of ONE tuples
Iterator<ReachTuple> rtItr1 = rtSetONE.iterator();
while( rtItr1.hasNext() ) {
- ReachTuple rt1 = rtItr1.next();
+ ReachTuple rt1 = rtItr1.next();
- Iterator<ReachTuple> rtItr2 = rtSetONE.iterator();
- while( rtItr2.hasNext() ) {
- ReachTuple rt2 = rtItr2.next();
+ Iterator<ReachTuple> rtItr2 = rtSetONE.iterator();
+ while( rtItr2.hasNext() ) {
+ ReachTuple rt2 = rtItr2.next();
- if( rt1 == rt2 ) {
- continue;
- }
+ if( rt1 == rt2 ) {
+ continue;
+ }
- if( !hrn.getAlpha().getStatesWithBoth(rt1, rt2).isEmpty() ) {
- return true;
- }
- }
+ if( !hrn.getAlpha().getStatesWithBoth(rt1, rt2).isEmpty() ) {
+ return true;
+ }
+ }
}
}
hrn.getAlpha()
);
if( !intersection.isEmpty() ) {
- assert !hrn.isOutOfContext();
- exhibitProofState.add(hrn);
+ assert !hrn.isOutOfContext();
+ exhibitProofState.add(hrn);
}
}
if( !DISABLE_STRONG_UPDATES &&
!DISABLE_GLOBAL_SWEEP
) {
- assert !common.isEmpty();
+ assert !common.isEmpty();
}
}
if( !DISABLE_STRONG_UPDATES &&
!DISABLE_GLOBAL_SWEEP
) {
- assert !common.isEmpty();
+ assert !common.isEmpty();
}
}
// check sum2 against alloc1 nodes
if(hrnSum2!=null) {
for (int i = 0; i < as1.getAllocationDepth(); ++i) {
- Integer idI1 = as1.getIthOldest(i);
- assert id2hrn.containsKey(idI1);
- HeapRegionNode hrnI1 = id2hrn.get(idI1);
- assert hrnI1 != null;
- common.addAll(mayReachSharedObjects(hrnI1, hrnSum2));
+ Integer idI1 = as1.getIthOldest(i);
+ assert id2hrn.containsKey(idI1);
+ HeapRegionNode hrnI1 = id2hrn.get(idI1);
+ assert hrnI1 != null;
+ common.addAll(mayReachSharedObjects(hrnI1, hrnSum2));
}
// also ask if objects from this summary share among each other
assert hrnI2 != null;
if(hrnSum1!=null) {
- common.addAll(mayReachSharedObjects(hrnSum1, hrnI2));
+ common.addAll(mayReachSharedObjects(hrnSum1, hrnI2));
}
// while we're at it, do an inner loop for alloc2 vs alloc1 nodes
for (int j = 0; j < as1.getAllocationDepth(); ++j) {
- Integer idI1 = as1.getIthOldest(j);
+ Integer idI1 = as1.getIthOldest(j);
- // if these are the same site, don't look for the same token, no
- // alias.
- // different tokens of the same site could alias together though
- if (idI1.equals(idI2)) {
- continue;
- }
+ // if these are the same site, don't look for the same token, no
+ // alias.
+ // different tokens of the same site could alias together though
+ if (idI1.equals(idI2)) {
+ continue;
+ }
- HeapRegionNode hrnI1 = id2hrn.get(idI1);
+ HeapRegionNode hrnI1 = id2hrn.get(idI1);
- common.addAll(mayReachSharedObjects(hrnI1, hrnI2));
+ common.addAll(mayReachSharedObjects(hrnI1, hrnI2));
}
}
while( stateItr.hasNext() ) {
ReachState stateThis = stateItr.next();
if( stateThis.equalsIgnorePreds(state) ) {
- return stateThis;
+ return stateThis;
}
}
while( itr.hasNext() ) {
ReachState stateThis = itr.next();
if( strict ) {
- if( !state.equals(stateThis) &&
- state.isSubset(stateThis) ) {
- return true;
- }
+ if( !state.equals(stateThis) &&
+ state.isSubset(stateThis) ) {
+ return true;
+ }
} else {
- if( state.isSubset(stateThis) ) {
- return true;
- }
+ if( state.isSubset(stateThis) ) {
+ return true;
+ }
}
}
while( itr.hasNext() ) {
ReachState state = itr.next();
if( state.containsTuple(rt) ) {
- return true;
+ return true;
}
}
return false;
ReachState state = itr.next();
if( state.containsTuple(rt1) &&
state.containsTuple(rt2) ) {
- out.reachStates.add(state);
+ out.reachStates.add(state);
}
}
for( int i = 0; i < v.size(); ++i ) {
ReachState s1 = v.get(i);
for( int j = i+1; j < v.size(); ++j ) {
- ReachState s2 = v.get(j);
- if( s1.equals(s2) ) {
- assert s1.isCanonical();
- assert s2.isCanonical();
- return false;
- }
+ ReachState s2 = v.get(j);
+ if( s1.equals(s2) ) {
+ assert s1.isCanonical();
+ assert s2.isCanonical();
+ return false;
+ }
}
}
return true;
// skip this if there is a superset already
if( hideSubsetReachability &&
containsStrictSuperSet(state) ) {
- continue;
+ continue;
}
s += state;
if( i.hasNext() ) {
- s += "\\n";
+ s += "\\n";
}
}
Iterator<ReachState> i = this.iterator();
while( i.hasNext() ) {
- ReachState state = i.next();
+ ReachState state = i.next();
- if( containsStrictSuperSet(state) ) {
- continue;
- }
+ if( containsStrictSuperSet(state) ) {
+ continue;
+ }
- toPrint = Canonical.add(toPrint, state);
+ toPrint = Canonical.add(toPrint, state);
}
}
s += state;
if( i.hasNext() ) {
- s += "\n";
+ s += "\n";
}
}
if( hrnID.equals(rt.getHrnID() ) &&
isOutOfContext == rt.isOutOfContext()
) {
- return rt;
+ return rt;
}
}
if( !hideEdgeTaints ) {
if( !taints.isEmpty() ) {
- s += "\\n"+taints.toStringEscNewline();
+ s += "\\n"+taints.toStringEscNewline();
}
}
edge.typeEquals(type) &&
edge.fieldEquals(field)
) {
- return edge;
+ return edge;
}
}
Iterator<Effect> eItr = effects.iterator();
while( eItr.hasNext() ) {
- Effect e = eItr.next();
- if (conflicts.contains(e)) {
- s += "["+e.toString()+"]";
- } else {
- s += e.toString();
- }
- if( eItr.hasNext() ) {
- s += "\\n";
- }
+ Effect e = eItr.next();
+ if (conflicts.contains(e)) {
+ s += "["+e.toString()+"]";
+ } else {
+ s += e.toString();
+ }
+ if( eItr.hasNext() ) {
+ s += "\\n";
+ }
}
}
Iterator<SMFEState> sItr = states.iterator();
while( sItr.hasNext() ) {
- SMFEState state = sItr.next();
-
- s += "\n "+
- id+" -> "+state.id+
- "[label=\""+e+", RC="+refCount+"\"";
- if (conflicts.contains(e))
- s+=",style=dashed";
- s+="];";
+ SMFEState state = sItr.next();
+
+ s += "\n "+
+ id+" -> "+state.id+
+ "[label=\""+e+", RC="+refCount+"\"";
+ if (conflicts.contains(e))
+ s+=",style=dashed";
+ s+="];";
}
}
for(FlatNode fn : fn2state.keySet()) {
SMFEState state=fn2state.get(fn);
if (!state.getConflicts().isEmpty())
- return false;
+ return false;
}
return true;
}
Iterator<FlatNode> fnItr = fn2state.keySet().iterator();
while( fnItr.hasNext() ) {
- SMFEState state = fn2state.get(fnItr.next() );
- bw.write(state.toStringDOT()+"\n");
+ SMFEState state = fn2state.get(fnItr.next() );
+ bw.write(state.toStringDOT()+"\n");
}
bw.write("}\n");
HashSet<Taint> taintset=new HashSet<Taint>();
for(Taint t : taints) {
if (t.getWhereDefined()!=fn) {
- t=t.reTaint(fn);
+ t=t.reTaint(fn);
}
taintset.add(t);
}
while( tItr.hasNext() ) {
Taint tThis = tItr.next();
if( tThis.equalsIgnorePreds(t) ) {
- return tThis;
+ return tThis;
}
}
s += t.toString();
if( tItr.hasNext() ) {
- s += ",\\n";
+ s += ",\\n";
}
}
s += "]";
for(Iterator it_classes=state.getClassSymbolTable().getDescriptorsIterator(); it_classes.hasNext(); ) {
ClassDescriptor cd = (ClassDescriptor)it_classes.next();
for(Iterator it_methods=cd.getMethods(); it_methods.hasNext(); ) {
- MethodDescriptor md = (MethodDescriptor)it_methods.next();
- FlatMethod fm = state.getMethodFlat(md);
- writeFlatIRGraph(fm,cd.getSymbol()+"."+md.getSymbol());
+ MethodDescriptor md = (MethodDescriptor)it_methods.next();
+ FlatMethod fm = state.getMethodFlat(md);
+ writeFlatIRGraph(fm,cd.getSymbol()+"."+md.getSymbol());
}
}
}
visited.add(fn);
if( fn.kind() == FKind.FlatMethod ) {
- // FlatMethod does not have toString
- flatbw.write(makeDotNodeDec(graphname, flatnodetolabel.get(fn), fn.getClass().getName(), "FlatMethod") );
+ // FlatMethod does not have toString
+ flatbw.write(makeDotNodeDec(graphname, flatnodetolabel.get(fn), fn.getClass().getName(), "FlatMethod") );
} else {
- flatbw.write(makeDotNodeDec(graphname, flatnodetolabel.get(fn), fn.getClass().getName(), fn.toString() ) );
+ flatbw.write(makeDotNodeDec(graphname, flatnodetolabel.get(fn), fn.getClass().getName(), fn.toString() ) );
}
for(int i=0; i<fn.numNext(); i++) {
- FlatNode nn=fn.getNext(i);
- flatbw.write(" node"+flatnodetolabel.get(fn)+" -> node"+flatnodetolabel.get(nn)+";\n");
+ FlatNode nn=fn.getNext(i);
+ flatbw.write(" node"+flatnodetolabel.get(fn)+" -> node"+flatnodetolabel.get(nn)+";\n");
- if( !visited.contains(nn) ) {
- toVisit.add(nn);
- }
+ if( !visited.contains(nn) ) {
+ toVisit.add(nn);
+ }
}
}
for(int i=0; i<fn.numNext(); i++) {
FlatNode nn=fn.getNext(i);
if(!visited.contains(nn)) {
- labelFlatNodes(nn);
+ labelFlatNodes(nn);
}
}
}
String label=getGroup(fn);
output.println(label+":");
if (numJumps(fn)==1) {
- FlatNode fndst=getJumps(fn).get(0);
- output.println("goto L"+nodetolabels.get(fndst)+";");
+ FlatNode fndst=getJumps(fn).get(0);
+ output.println("goto L"+nodetolabels.get(fndst)+";");
} else if (numJumps(fn)==2) {
- Vector<FlatNode> exits=getJumps(fn);
- output.println("if(RESTOREBRANCH())");
- output.println("goto L"+nodetolabels.get(exits.get(1))+";");
- output.println("else");
- output.println("goto L"+nodetolabels.get(exits.get(0))+";");
+ Vector<FlatNode> exits=getJumps(fn);
+ output.println("if(RESTOREBRANCH())");
+ output.println("goto L"+nodetolabels.get(exits.get(1))+";");
+ output.println("else");
+ output.println("goto L"+nodetolabels.get(exits.get(0))+";");
} else {
- Vector<FlatNode> exits=getJumps(fn);
- output.println("switch(RESTOREBRANCH()) {");
- for(int i=0; i<exits.size(); i++) {
- output.println("case "+i+":");
- output.println("goto L"+nodetolabels.get(exits.get(i))+";");
- }
- output.println("}");
+ Vector<FlatNode> exits=getJumps(fn);
+ output.println("switch(RESTOREBRANCH()) {");
+ for(int i=0; i<exits.size(); i++) {
+ output.println("case "+i+":");
+ output.println("goto L"+nodetolabels.get(exits.get(i))+";");
+ }
+ output.println("}");
}
}
}
for(Iterator<FlatNode> fnit=transset.iterator(); fnit.hasNext(); ) {
FlatNode fn=fnit.next();
if ((fn.numNext()>1&&storeset.contains(fn))||fn.kind()==FKind.FlatBackEdge||fn.kind()==FKind.FlatNop) {
- FlatNode[] children=fnmap.get(fn);
- if (children==null)
- continue;
- if (!groupmap.containsKey(fn)) {
- groupmap.put(fn, new HashSet<FlatNode>());
- groupmap.get(fn).add(fn);
- }
- for(int i=0; i<children.length; i++) {
- FlatNode child=children[i];
- if ((child.numNext()>1&&storeset.contains(child))||child.kind()==FKind.FlatBackEdge||child.kind()==FKind.FlatNop) {
- mergegroups(fn, child, groupmap);
- }
- }
+ FlatNode[] children=fnmap.get(fn);
+ if (children==null)
+ continue;
+ if (!groupmap.containsKey(fn)) {
+ groupmap.put(fn, new HashSet<FlatNode>());
+ groupmap.get(fn).add(fn);
+ }
+ for(int i=0; i<children.length; i++) {
+ FlatNode child=children[i];
+ if ((child.numNext()>1&&storeset.contains(child))||child.kind()==FKind.FlatBackEdge||child.kind()==FKind.FlatNop) {
+ mergegroups(fn, child, groupmap);
+ }
+ }
}
}
//now we have groupings...
Vector<FlatNode> exits=new Vector<FlatNode>();
table.put(group, exits);
for(Iterator<FlatNode> fnit=group.iterator(); fnit.hasNext(); ) {
- FlatNode fn=fnit.next();
- FlatNode[] nextnodes=fnmap.get(fn);
- for(int i=0; i<nextnodes.length; i++) {
- FlatNode nextnode=nextnodes[i];
- if (!group.contains(nextnode)) {
- //outside edge
- if (!exits.contains(nextnode)) {
- exits.add(nextnode);
- }
- }
- }
+ FlatNode fn=fnit.next();
+ FlatNode[] nextnodes=fnmap.get(fn);
+ for(int i=0; i<nextnodes.length; i++) {
+ FlatNode nextnode=nextnodes[i];
+ if (!group.contains(nextnode)) {
+ //outside edge
+ if (!exits.contains(nextnode)) {
+ exits.add(nextnode);
+ }
+ }
+ }
}
}
}
if (groupmap.get(fn1)!=groupmap.get(fn2)) {
groupmap.get(fn1).addAll(groupmap.get(fn2));
for(Iterator<FlatNode> fnit=groupmap.get(fn2).iterator(); fnit.hasNext(); ) {
- FlatNode fn3=fnit.next();
- groupmap.put(fn3, groupmap.get(fn1));
+ FlatNode fn3=fnit.next();
+ groupmap.put(fn3, groupmap.get(fn1));
}
}
}
Set<Object[]> incomingtuples=new HashSet<Object[]>();
for(int i=0; i<fn.numPrev(); i++) {
- FlatNode fprev=fn.getPrev(i);
- if (nodeset.contains(fprev)||storeset.contains(fprev)) {
- for(int j=0; j<fprev.numNext(); j++) {
- if (fprev.getNext(j)==fn) {
- Object[] pair=new Object[2];
- pair[0]=new Integer(j); pair[1]=fprev;
- incomingtuples.add(pair);
- }
- }
- } else {
- Set<Object[]> tuple=fntotuple.get(fprev);
- if (tuple!=null)
- incomingtuples.addAll(tuple);
- }
+ FlatNode fprev=fn.getPrev(i);
+ if (nodeset.contains(fprev)||storeset.contains(fprev)) {
+ for(int j=0; j<fprev.numNext(); j++) {
+ if (fprev.getNext(j)==fn) {
+ Object[] pair=new Object[2];
+ pair[0]=new Integer(j); pair[1]=fprev;
+ incomingtuples.add(pair);
+ }
+ }
+ } else {
+ Set<Object[]> tuple=fntotuple.get(fprev);
+ if (tuple!=null)
+ incomingtuples.addAll(tuple);
+ }
}
if (nodeset.contains(fn)||storeset.contains(fn)||fn.kind()==FKind.FlatAtomicExitNode) {
- //nodeset contains this node
- for(Iterator<Object[]> it=incomingtuples.iterator(); it.hasNext(); ) {
- Object[] pair=it.next();
- int index=((Integer)pair[0]).intValue();
- FlatNode node=(FlatNode)pair[1];
- if (!fnmap.containsKey(node))
- fnmap.put(node, new FlatNode[node.numNext()]);
- fnmap.get(node)[index]=fn;
- }
- incomingtuples=new HashSet<Object[]>();
+ //nodeset contains this node
+ for(Iterator<Object[]> it=incomingtuples.iterator(); it.hasNext(); ) {
+ Object[] pair=it.next();
+ int index=((Integer)pair[0]).intValue();
+ FlatNode node=(FlatNode)pair[1];
+ if (!fnmap.containsKey(node))
+ fnmap.put(node, new FlatNode[node.numNext()]);
+ fnmap.get(node)[index]=fn;
+ }
+ incomingtuples=new HashSet<Object[]>();
}
//add if we need to update
if (!fntotuple.containsKey(fn)||
!fntotuple.get(fn).equals(incomingtuples)) {
- fntotuple.put(fn,incomingtuples);
- for(int i=0; i<fn.numNext(); i++) {
- if (transset.contains(fn.getNext(i)))
- toprocess.add(fn.getNext(i));
- }
+ fntotuple.put(fn,incomingtuples);
+ for(int i=0; i<fn.numNext(); i++) {
+ if (transset.contains(fn.getNext(i)))
+ toprocess.add(fn.getNext(i));
+ }
}
}
return fnmap;
FlatNode fn=tovisit.iterator().next();
tovisit.remove(fn);
if (locality.getAtomic(lb).get(fn).intValue()>0||fn.kind()==FKind.FlatAtomicExitNode)
- transset.add(fn);
+ transset.add(fn);
}
return transset;
}
FlatNode fn=fnit.next();
if (fn.kind()==FKind.FlatAtomicEnterNode&&
locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0) {
- Set<FlatNode> transSet=computeTrans(lb, fn);
- Set<FlatNode> tCheckSet=intersect(checkset, transSet);
- Set<FlatNode> tRecordSet=intersect(recordset, transSet);
- Set<FlatNode> tOtherSet=intersect(otherset, transSet);
- Set<FlatNode> tNotReadySet=intersect(notreadyset, transSet);
- HashSet<FlatNode> tCannotDelay=intersect(cannotdelay, transSet);
- Set<FlatNode> tderef=(state.STMARRAY&&!state.DUALVIEW)?intersect(derefset, transSet):null;
-
- if (checkSet(fn, tCheckSet, tRecordSet, lb)) {
- //We will convert this one
- nrecordset.addAll(tRecordSet);
- notherset.addAll(tOtherSet);
- nnotready.addAll(tNotReadySet);
- ncannotdelay.addAll(tCannotDelay);
- if (state.STMARRAY&&!state.DUALVIEW)
- nderef.addAll(tderef);
- transmap.get(lb).add(fn);
- convset.addAll(transSet);
- } else {
- ncannotdelay.addAll(transSet);
- }
- if (!lwmap.containsKey(lb))
- lwmap.put(lb, new HashSet<FlatNode>());
- lwmap.get(lb).add(fn);
+ Set<FlatNode> transSet=computeTrans(lb, fn);
+ Set<FlatNode> tCheckSet=intersect(checkset, transSet);
+ Set<FlatNode> tRecordSet=intersect(recordset, transSet);
+ Set<FlatNode> tOtherSet=intersect(otherset, transSet);
+ Set<FlatNode> tNotReadySet=intersect(notreadyset, transSet);
+ HashSet<FlatNode> tCannotDelay=intersect(cannotdelay, transSet);
+ Set<FlatNode> tderef=(state.STMARRAY&&!state.DUALVIEW)?intersect(derefset, transSet):null;
+
+ if (checkSet(fn, tCheckSet, tRecordSet, lb)) {
+ //We will convert this one
+ nrecordset.addAll(tRecordSet);
+ notherset.addAll(tOtherSet);
+ nnotready.addAll(tNotReadySet);
+ ncannotdelay.addAll(tCannotDelay);
+ if (state.STMARRAY&&!state.DUALVIEW)
+ nderef.addAll(tderef);
+ transmap.get(lb).add(fn);
+ convset.addAll(transSet);
+ } else {
+ ncannotdelay.addAll(transSet);
+ }
+ if (!lwmap.containsKey(lb))
+ lwmap.put(lb, new HashSet<FlatNode>());
+ lwmap.get(lb).add(fn);
} else {
- if (locality.getAtomic(lb).get(fn).intValue()==0)
- ncannotdelay.add(fn);
+ if (locality.getAtomic(lb).get(fn).intValue()==0)
+ ncannotdelay.add(fn);
}
}
}
FlatNode fn=fnit.next();
//needs transread
if (!state.READSET&&dc.getNeedTrans(lb, fn)||state.READSET&&dc.getNeedWriteTrans(lb, fn)||fn.kind()==FKind.FlatCall) {
- System.out.println("False because"+fn);
- if (!state.HYBRID)
- return true;
- return false;
+ System.out.println("False because"+fn);
+ if (!state.HYBRID)
+ return true;
+ return false;
}
}
optmap.get(lb).add(faen);
toProcess.remove(fn);
transSet.add(fn);
if (locality.getAtomic(lb).get(fn).intValue()==0)
- continue;
+ continue;
for(int i=0; i<fn.numNext(); i++) {
- if (!transSet.contains(fn.getNext(i)))
- toProcess.add(fn.getNext(i));
+ if (!transSet.contains(fn.getNext(i)))
+ toProcess.add(fn.getNext(i));
}
}
return transSet;
MethodDescriptor md=lb.getMethod();
FlatMethod fm=state.getMethodFlat(md);
if (lb.isAtomic())
- continue;
+ continue;
if (lb.getHasAtomic()) {
- HashSet<FlatNode> cannotdelay=cannotdelaymap.get(lb);
- HashSet<FlatNode> notreadyset=computeNotReadySet(lb, cannotdelay);
- HashSet<FlatNode> otherset=new HashSet<FlatNode>();
- otherset.addAll(fm.getNodeSet());
- otherset.removeAll(notreadyset);
- otherset.removeAll(cannotdelay);
- if (state.MINIMIZE) {
- Hashtable<FlatNode, Integer> atomicmap=locality.getAtomic(lb);
- for(Iterator<FlatNode> fnit=otherset.iterator(); fnit.hasNext(); ) {
- FlatNode fn=fnit.next();
- if (atomicmap.get(fn).intValue()>0&&
- fn.kind()!=FKind.FlatAtomicEnterNode&&
- fn.kind()!=FKind.FlatGlobalConvNode) {
- //remove non-atomic flatnodes
- fnit.remove();
- notreadyset.add(fn);
- }
- }
- }
-
- notreadymap.put(lb, notreadyset);
- othermap.put(lb, otherset);
+ HashSet<FlatNode> cannotdelay=cannotdelaymap.get(lb);
+ HashSet<FlatNode> notreadyset=computeNotReadySet(lb, cannotdelay);
+ HashSet<FlatNode> otherset=new HashSet<FlatNode>();
+ otherset.addAll(fm.getNodeSet());
+ otherset.removeAll(notreadyset);
+ otherset.removeAll(cannotdelay);
+ if (state.MINIMIZE) {
+ Hashtable<FlatNode, Integer> atomicmap=locality.getAtomic(lb);
+ for(Iterator<FlatNode> fnit=otherset.iterator(); fnit.hasNext(); ) {
+ FlatNode fn=fnit.next();
+ if (atomicmap.get(fn).intValue()>0&&
+ fn.kind()!=FKind.FlatAtomicEnterNode&&
+ fn.kind()!=FKind.FlatGlobalConvNode) {
+ //remove non-atomic flatnodes
+ fnit.remove();
+ notreadyset.add(fn);
+ }
+ }
+ }
+
+ notreadymap.put(lb, notreadyset);
+ othermap.put(lb, otherset);
}
//We now have:
FlatNode fn=fnit.next();
Hashtable<TempDescriptor, Set<TempFlatPair>> tempmap=fnmap.get(fn);
if (fn.kind()==FKind.FlatSetElementNode) {
- FlatSetElementNode fsen=(FlatSetElementNode) fn;
- Set<TempFlatPair> tfpset=tempmap.get(fsen.getDst());
- if (tfpset!=null) {
- for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
- TempFlatPair tfp=tfpit.next();
- if (storeset.contains(tfp.f))
- writeset.add(tfp.f);
- }
- }
+ FlatSetElementNode fsen=(FlatSetElementNode) fn;
+ Set<TempFlatPair> tfpset=tempmap.get(fsen.getDst());
+ if (tfpset!=null) {
+ for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
+ TempFlatPair tfp=tfpit.next();
+ if (storeset.contains(tfp.f))
+ writeset.add(tfp.f);
+ }
+ }
} else if (fn.kind()==FKind.FlatSetFieldNode) {
- FlatSetFieldNode fsfn=(FlatSetFieldNode) fn;
- Set<TempFlatPair> tfpset=tempmap.get(fsfn.getDst());
- if (tfpset!=null) {
- for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
- TempFlatPair tfp=tfpit.next();
- if (storeset.contains(tfp.f))
- writeset.add(tfp.f);
- }
- }
+ FlatSetFieldNode fsfn=(FlatSetFieldNode) fn;
+ Set<TempFlatPair> tfpset=tempmap.get(fsfn.getDst());
+ if (tfpset!=null) {
+ for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
+ TempFlatPair tfp=tfpit.next();
+ if (storeset.contains(tfp.f))
+ writeset.add(tfp.f);
+ }
+ }
}
}
return writeset;
List<TempDescriptor> writes=Arrays.asList(fn.writesTemps());
tempset.addAll(writes);
if (!recordset.contains(fn)) {
- List<TempDescriptor> reads=Arrays.asList(fn.readsTemps());
- tempset.addAll(reads);
+ List<TempDescriptor> reads=Arrays.asList(fn.readsTemps());
+ tempset.addAll(reads);
}
}
for(Iterator<FlatNode> fnit=secondpart.iterator(); fnit.hasNext(); ) {
FlatNode fn=fnit.next();
if (recordset.contains(fn))
- continue;
+ continue;
TempDescriptor readset[]=fn.readsTemps();
for(int i=0; i<readset.length; i++) {
- TempDescriptor rtmp=readset[i];
- Set<FlatNode> fnset=reachingdefs.get(fn).get(rtmp);
- for(Iterator<FlatNode> fnit2=fnset.iterator(); fnit2.hasNext(); ) {
- FlatNode fn2=fnit2.next();
- if (secondpart.contains(fn2))
- continue;
- //otherwise we mark this as live in
- liveinto.add(rtmp);
- break;
- }
+ TempDescriptor rtmp=readset[i];
+ Set<FlatNode> fnset=reachingdefs.get(fn).get(rtmp);
+ for(Iterator<FlatNode> fnit2=fnset.iterator(); fnit2.hasNext(); ) {
+ FlatNode fn2=fnit2.next();
+ if (secondpart.contains(fn2))
+ continue;
+ //otherwise we mark this as live in
+ liveinto.add(rtmp);
+ break;
+ }
}
}
return liveinto;
//Look for reaching defs for all live variables that are in the secondpart
for(Iterator<TempDescriptor> tmpit=tempset.iterator(); tmpit.hasNext(); ) {
- TempDescriptor tmp=tmpit.next();
- Set<FlatNode> fnset=reachmap.get(tmp);
- boolean outsidenode=false;
- boolean insidenode=false;
-
- for(Iterator<FlatNode> fnit2=fnset.iterator(); fnit2.hasNext(); ) {
- FlatNode fn2=fnit2.next();
- if (secondpart.contains(fn2)) {
- insidenode=true;
- } else if (!atomicnodes.contains(fn2)) {
- outsidenode=true;
- }
- if (outsidenode&&insidenode) {
- liveset.add(tmp);
- break;
- }
- }
+ TempDescriptor tmp=tmpit.next();
+ Set<FlatNode> fnset=reachmap.get(tmp);
+ boolean outsidenode=false;
+ boolean insidenode=false;
+
+ for(Iterator<FlatNode> fnit2=fnset.iterator(); fnit2.hasNext(); ) {
+ FlatNode fn2=fnit2.next();
+ if (secondpart.contains(fn2)) {
+ insidenode=true;
+ } else if (!atomicnodes.contains(fn2)) {
+ outsidenode=true;
+ }
+ if (outsidenode&&insidenode) {
+ liveset.add(tmp);
+ break;
+ }
+ }
}
}
return liveset;
//Look for reaching defs for all live variables that are in the secondpart
for(Iterator<TempDescriptor> tmpit=tempset.iterator(); tmpit.hasNext(); ) {
- TempDescriptor tmp=tmpit.next();
- Set<FlatNode> fnset=reachmap.get(tmp);
- if (fnset==null) {
- System.out.println("null temp set for"+fn+" tmp="+tmp);
- System.out.println(fm.printMethod());
- }
- for(Iterator<FlatNode> fnit2=fnset.iterator(); fnit2.hasNext(); ) {
- FlatNode fn2=fnit2.next();
- if (secondpart.contains(fn2)) {
- liveset.add(tmp);
- break;
- }
- }
+ TempDescriptor tmp=tmpit.next();
+ Set<FlatNode> fnset=reachmap.get(tmp);
+ if (fnset==null) {
+ System.out.println("null temp set for"+fn+" tmp="+tmp);
+ System.out.println(fm.printMethod());
+ }
+ for(Iterator<FlatNode> fnit2=fnset.iterator(); fnit2.hasNext(); ) {
+ FlatNode fn2=fnit2.next();
+ if (secondpart.contains(fn2)) {
+ liveset.add(tmp);
+ break;
+ }
+ }
}
}
return liveset;
for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator(); fnit.hasNext(); ) {
FlatNode fn=fnit.next();
if (fn.kind()==FKind.FlatAtomicExitNode) {
- Set<TempDescriptor> livetemps=livemap.get(fn);
- Hashtable<TempDescriptor, Set<FlatNode>> tempmap=reachingdefsmap.get(fn);
-
- //Iterate over the temps that are live into this node
- for(Iterator<TempDescriptor> tmpit=livetemps.iterator(); tmpit.hasNext(); ) {
- TempDescriptor tmp=tmpit.next();
- Set<FlatNode> fnset=tempmap.get(tmp);
- boolean inpart1=false;
- boolean inpart2=false;
-
- //iterate over the reaching definitions for the temp
- for(Iterator<FlatNode> fnit2=fnset.iterator(); fnit2.hasNext(); ) {
- FlatNode fn2=fnit2.next();
- if (delayedset.contains(fn2)) {
- inpart2=true;
- if (inpart1)
- break;
- } else if (otherset.contains(fn2)||cannotdelayset.contains(fn2)) {
- inpart1=true;
- if (inpart2)
- break;
- }
- }
- if (inpart1&&inpart2) {
- for(Iterator<FlatNode> fnit2=fnset.iterator(); fnit2.hasNext(); ) {
- FlatNode fn2=fnit2.next();
- if ((otherset.contains(fn2)||cannotdelayset.contains(fn2))&&
- locality.getAtomic(lb).get(fn2).intValue()>0) {
- unionset.add(fn2);
- livenodes.add(fn2);
- }
- }
- }
- }
+ Set<TempDescriptor> livetemps=livemap.get(fn);
+ Hashtable<TempDescriptor, Set<FlatNode>> tempmap=reachingdefsmap.get(fn);
+
+ //Iterate over the temps that are live into this node
+ for(Iterator<TempDescriptor> tmpit=livetemps.iterator(); tmpit.hasNext(); ) {
+ TempDescriptor tmp=tmpit.next();
+ Set<FlatNode> fnset=tempmap.get(tmp);
+ boolean inpart1=false;
+ boolean inpart2=false;
+
+ //iterate over the reaching definitions for the temp
+ for(Iterator<FlatNode> fnit2=fnset.iterator(); fnit2.hasNext(); ) {
+ FlatNode fn2=fnit2.next();
+ if (delayedset.contains(fn2)) {
+ inpart2=true;
+ if (inpart1)
+ break;
+ } else if (otherset.contains(fn2)||cannotdelayset.contains(fn2)) {
+ inpart1=true;
+ if (inpart2)
+ break;
+ }
+ }
+ if (inpart1&&inpart2) {
+ for(Iterator<FlatNode> fnit2=fnset.iterator(); fnit2.hasNext(); ) {
+ FlatNode fn2=fnit2.next();
+ if ((otherset.contains(fn2)||cannotdelayset.contains(fn2))&&
+ locality.getAtomic(lb).get(fn2).intValue()>0) {
+ unionset.add(fn2);
+ livenodes.add(fn2);
+ }
+ }
+ }
+ }
}
}
//Don't process non-atomic nodes
if (locality.getAtomic(lb).get(fn).intValue()==0) {
- if (!map.containsKey(fn)) {
- map.put(fn, new Hashtable<TempDescriptor, HashSet<FlatNode>>());
- //enqueue next nodes
- for(int i=0; i<fn.numNext(); i++)
- toanalyze.add(fn.getNext(i));
- }
- continue;
+ if (!map.containsKey(fn)) {
+ map.put(fn, new Hashtable<TempDescriptor, HashSet<FlatNode>>());
+ //enqueue next nodes
+ for(int i=0; i<fn.numNext(); i++)
+ toanalyze.add(fn.getNext(i));
+ }
+ continue;
}
Set<TempDescriptor> liveset=livemap.get(fn);
//Do merge on incoming edges
for(int i=0; i<fn.numPrev(); i++) {
- FlatNode fnprev=fn.getPrev(i);
- Hashtable<TempDescriptor, HashSet<FlatNode>> prevmap=map.get(fnprev);
- if (prevmap!=null)
- for(Iterator<TempDescriptor> tmpit=prevmap.keySet().iterator(); tmpit.hasNext(); ) {
- TempDescriptor tmp=tmpit.next();
- if (!liveset.contains(tmp)) //skip dead temps
- continue;
- if (!tmptofn.containsKey(tmp))
- tmptofn.put(tmp, new HashSet<FlatNode>());
- tmptofn.get(tmp).addAll(prevmap.get(tmp));
- }
+ FlatNode fnprev=fn.getPrev(i);
+ Hashtable<TempDescriptor, HashSet<FlatNode>> prevmap=map.get(fnprev);
+ if (prevmap!=null)
+ for(Iterator<TempDescriptor> tmpit=prevmap.keySet().iterator(); tmpit.hasNext(); ) {
+ TempDescriptor tmp=tmpit.next();
+ if (!liveset.contains(tmp)) //skip dead temps
+ continue;
+ if (!tmptofn.containsKey(tmp))
+ tmptofn.put(tmp, new HashSet<FlatNode>());
+ tmptofn.get(tmp).addAll(prevmap.get(tmp));
+ }
}
if (delayedset.contains(fn)) {
- if(state.STMARRAY&&!state.DUALVIEW&&derefset.contains(fn)) {
- //FlatElementNodes don't read anything...
- if (fn.kind()==FKind.FlatSetElementNode) {
- //check only the source read tmp
- TempDescriptor tmp=((FlatSetElementNode)fn).getSrc();
- if (tmptofn.containsKey(tmp)) {
- livenodes.addAll(tmptofn.get(tmp)); //Add live nodes
- unionset.addAll(tmptofn.get(tmp));
- }
- }
- } else {
- //If the node is in the second set, check our readset
- TempDescriptor readset[]=fn.readsTemps();
- for(int i=0; i<readset.length; i++) {
- TempDescriptor tmp=readset[i];
- if (tmptofn.containsKey(tmp)) {
- livenodes.addAll(tmptofn.get(tmp)); //Add live nodes
- unionset.addAll(tmptofn.get(tmp));
- }
- }
- }
- //Do kills
- TempDescriptor writeset[]=fn.writesTemps();
- for(int i=0; i<writeset.length; i++) {
- TempDescriptor tmp=writeset[i];
- tmptofn.remove(tmp);
- }
+ if(state.STMARRAY&&!state.DUALVIEW&&derefset.contains(fn)) {
+ //FlatElementNodes don't read anything...
+ if (fn.kind()==FKind.FlatSetElementNode) {
+ //check only the source read tmp
+ TempDescriptor tmp=((FlatSetElementNode)fn).getSrc();
+ if (tmptofn.containsKey(tmp)) {
+ livenodes.addAll(tmptofn.get(tmp)); //Add live nodes
+ unionset.addAll(tmptofn.get(tmp));
+ }
+ }
+ } else {
+ //If the node is in the second set, check our readset
+ TempDescriptor readset[]=fn.readsTemps();
+ for(int i=0; i<readset.length; i++) {
+ TempDescriptor tmp=readset[i];
+ if (tmptofn.containsKey(tmp)) {
+ livenodes.addAll(tmptofn.get(tmp)); //Add live nodes
+ unionset.addAll(tmptofn.get(tmp));
+ }
+ }
+ }
+ //Do kills
+ TempDescriptor writeset[]=fn.writesTemps();
+ for(int i=0; i<writeset.length; i++) {
+ TempDescriptor tmp=writeset[i];
+ tmptofn.remove(tmp);
+ }
} else {
- //If the node is in the first set, search over what we write
- //We write -- our reads are done
- TempDescriptor writeset[]=fn.writesTemps();
- for(int i=0; i<writeset.length; i++) {
- TempDescriptor tmp=writeset[i];
- HashSet<FlatNode> set=new HashSet<FlatNode>();
- tmptofn.put(tmp,set);
- set.add(fn);
- }
- if (fn.numNext()>1) {
- Set<FlatNode> branchset=branchmap.get((FlatCondBranch)fn);
- for(Iterator<FlatNode> brit=branchset.iterator(); brit.hasNext(); ) {
- FlatNode brfn=brit.next();
- if (unionset.contains(brfn)) {
- //This branch is important--need to remember how it goes
- livenodes.add(fn);
- unionset.add(fn);
- }
- }
- }
+ //If the node is in the first set, search over what we write
+ //We write -- our reads are done
+ TempDescriptor writeset[]=fn.writesTemps();
+ for(int i=0; i<writeset.length; i++) {
+ TempDescriptor tmp=writeset[i];
+ HashSet<FlatNode> set=new HashSet<FlatNode>();
+ tmptofn.put(tmp,set);
+ set.add(fn);
+ }
+ if (fn.numNext()>1) {
+ Set<FlatNode> branchset=branchmap.get((FlatCondBranch)fn);
+ for(Iterator<FlatNode> brit=branchset.iterator(); brit.hasNext(); ) {
+ FlatNode brfn=brit.next();
+ if (unionset.contains(brfn)) {
+ //This branch is important--need to remember how it goes
+ livenodes.add(fn);
+ unionset.add(fn);
+ }
+ }
+ }
}
if (!map.containsKey(fn)||!map.get(fn).equals(tmptofn)) {
- map.put(fn, tmptofn);
- //enqueue next ndoes
- for(int i=0; i<fn.numNext(); i++)
- toanalyze.add(fn.getNext(i));
+ map.put(fn, tmptofn);
+ //enqueue next ndoes
+ for(int i=0; i<fn.numNext(); i++)
+ toanalyze.add(fn.getNext(i));
}
}
return livenodes;
while(!nodes.isEmpty()) {
FlatNode fn2=nodes.pop();
if (visited.contains(fn2))
- continue;
+ continue;
visited.add(fn2);
for (int j=0; j<fn2.numNext(); j++) {
- FlatNode fn2next=fn2.getNext(j);
- if (delayset.contains(fn2next)||atomictable.get(fn2next).intValue()==0) {
- reachable.add(fn2next);
- } else
- nodes.push(fn2next);
+ FlatNode fn2next=fn2.getNext(j);
+ if (delayset.contains(fn2next)||atomictable.get(fn2next).intValue()==0) {
+ reachable.add(fn2next);
+ } else
+ nodes.push(fn2next);
}
}
return reachable;
boolean isatomic=atomictable.get(fn).intValue()>0;
if (!isatomic)
- continue;
+ continue;
boolean isnodelay=false;
/* Compute incoming nodelay sets */
HashSet<FieldDescriptor> nodelayfieldrdset=new HashSet<FieldDescriptor>();
HashSet<TypeDescriptor> nodelayarrayrdset=new HashSet<TypeDescriptor>();
for(int i=0; i<fn.numNext(); i++) {
- if (nodelaytemps.containsKey(fn.getNext(i)))
- nodelaytempset.addAll(nodelaytemps.get(fn.getNext(i)));
- //do field/array write sets
- if (nodelayfieldswr.containsKey(fn.getNext(i)))
- nodelayfieldwrset.addAll(nodelayfieldswr.get(fn.getNext(i)));
- if (nodelayarrayswr.containsKey(fn.getNext(i)))
- nodelayarraywrset.addAll(nodelayarrayswr.get(fn.getNext(i)));
- //do read sets
- if (nodelayfieldsrd.containsKey(fn.getNext(i)))
- nodelayfieldrdset.addAll(nodelayfieldsrd.get(fn.getNext(i)));
- if (nodelayarraysrd.containsKey(fn.getNext(i)))
- nodelayarrayrdset.addAll(nodelayarraysrd.get(fn.getNext(i)));
+ if (nodelaytemps.containsKey(fn.getNext(i)))
+ nodelaytempset.addAll(nodelaytemps.get(fn.getNext(i)));
+ //do field/array write sets
+ if (nodelayfieldswr.containsKey(fn.getNext(i)))
+ nodelayfieldwrset.addAll(nodelayfieldswr.get(fn.getNext(i)));
+ if (nodelayarrayswr.containsKey(fn.getNext(i)))
+ nodelayarraywrset.addAll(nodelayarrayswr.get(fn.getNext(i)));
+ //do read sets
+ if (nodelayfieldsrd.containsKey(fn.getNext(i)))
+ nodelayfieldrdset.addAll(nodelayfieldsrd.get(fn.getNext(i)));
+ if (nodelayarraysrd.containsKey(fn.getNext(i)))
+ nodelayarrayrdset.addAll(nodelayarraysrd.get(fn.getNext(i)));
}
/* Check our temp write set */
TempDescriptor writeset[]=fn.writesTemps();
for(int i=0; i<writeset.length; i++) {
- TempDescriptor tmp=writeset[i];
- if (nodelaytempset.contains(tmp)) {
- //We are writing to a nodelay temp
- //Therefore we are nodelay
- isnodelay=true;
- //Kill temp we wrote to
- nodelaytempset.remove(tmp);
- }
+ TempDescriptor tmp=writeset[i];
+ if (nodelaytempset.contains(tmp)) {
+ //We are writing to a nodelay temp
+ //Therefore we are nodelay
+ isnodelay=true;
+ //Kill temp we wrote to
+ nodelaytempset.remove(tmp);
+ }
}
//See if flatnode is definitely no delay
if (fn.kind()==FKind.FlatCall) {
- FlatCall fcall=(FlatCall)fn;
- MethodDescriptor mdcall=fcall.getMethod();
- if (!mdcall.getClassDesc().getSymbol().equals("System")||
- (!mdcall.getSymbol().equals("println")&&!mdcall.getSymbol().equals("printString")))
- isnodelay=true;
+ FlatCall fcall=(FlatCall)fn;
+ MethodDescriptor mdcall=fcall.getMethod();
+ if (!mdcall.getClassDesc().getSymbol().equals("System")||
+ (!mdcall.getSymbol().equals("println")&&!mdcall.getSymbol().equals("printString")))
+ isnodelay=true;
}
//Delay branches if possible
if (fn.kind()==FKind.FlatCondBranch) {
- Set<FlatNode> branchset=revbranchmap.get((FlatCondBranch)fn);
- for(Iterator<FlatNode> brit=branchset.iterator(); brit.hasNext(); ) {
- FlatNode branchnode=brit.next();
- if (cannotdelay.contains(branchnode)||(state.STMARRAY&&!state.DUALVIEW&&derefset.contains(branchnode))) {
- isnodelay=true;
- break;
- }
- }
+ Set<FlatNode> branchset=revbranchmap.get((FlatCondBranch)fn);
+ for(Iterator<FlatNode> brit=branchset.iterator(); brit.hasNext(); ) {
+ FlatNode branchnode=brit.next();
+ if (cannotdelay.contains(branchnode)||(state.STMARRAY&&!state.DUALVIEW&&derefset.contains(branchnode))) {
+ isnodelay=true;
+ break;
+ }
+ }
}
//Check for field conflicts
if (fn.kind()==FKind.FlatSetFieldNode) {
- FieldDescriptor fd=((FlatSetFieldNode)fn).getField();
- //write conflicts
- if (nodelayfieldwrset.contains(fd))
- isnodelay=true;
- //read
- if (nodelayfieldrdset.contains(fd))
- isnodelay=true;
+ FieldDescriptor fd=((FlatSetFieldNode)fn).getField();
+ //write conflicts
+ if (nodelayfieldwrset.contains(fd))
+ isnodelay=true;
+ //read
+ if (nodelayfieldrdset.contains(fd))
+ isnodelay=true;
}
if (fn.kind()==FKind.FlatFieldNode) {
- FieldDescriptor fd=((FlatFieldNode)fn).getField();
- //write conflicts
- if (nodelayfieldwrset.contains(fd))
- isnodelay=true;
+ FieldDescriptor fd=((FlatFieldNode)fn).getField();
+ //write conflicts
+ if (nodelayfieldwrset.contains(fd))
+ isnodelay=true;
}
//Check for array conflicts
if (fn.kind()==FKind.FlatSetElementNode) {
- TypeDescriptor td=((FlatSetElementNode)fn).getDst().getType();
- //check for write conflicts
- if (nodelayarraywrset.contains(td))
- isnodelay=true;
- //check for read conflicts
- if (nodelayarrayrdset.contains(td))
- isnodelay=true;
+ TypeDescriptor td=((FlatSetElementNode)fn).getDst().getType();
+ //check for write conflicts
+ if (nodelayarraywrset.contains(td))
+ isnodelay=true;
+ //check for read conflicts
+ if (nodelayarrayrdset.contains(td))
+ isnodelay=true;
}
if (fn.kind()==FKind.FlatElementNode) {
- TypeDescriptor td=((FlatElementNode)fn).getSrc().getType();
- //check for write conflicts
- if (nodelayarraywrset.contains(td))
- isnodelay=true;
+ TypeDescriptor td=((FlatElementNode)fn).getSrc().getType();
+ //check for write conflicts
+ if (nodelayarraywrset.contains(td))
+ isnodelay=true;
}
//If we are no delay, then the temps we read are no delay
if (isnodelay) {
- /* Add our read set */
- TempDescriptor readset[]=fn.readsTemps();
- for(int i=0; i<readset.length; i++) {
- TempDescriptor tmp=readset[i];
- nodelaytempset.add(tmp);
- }
- cannotdelay.add(fn);
-
- if (branchmap.containsKey(fn)) {
- Set<FlatCondBranch> fcbset=branchmap.get(fn);
- for(Iterator<FlatCondBranch> fcbit=fcbset.iterator(); fcbit.hasNext(); ) {
- FlatCondBranch fcb=fcbit.next();
- //enqueue flatcondbranch node for reanalysis
- if (!cannotdelay.contains(fcb)) {
- cannotdelay.add(fcb);
- toanalyze.add(fcb);
- }
- }
- }
- /* Do we write to fields */
- if (fn.kind()==FKind.FlatSetFieldNode) {
- nodelayfieldwrset.add(((FlatSetFieldNode)fn).getField());
- }
- /* Do we read from fields */
- if (fn.kind()==FKind.FlatFieldNode) {
- nodelayfieldrdset.add(((FlatFieldNode)fn).getField());
- }
- /* Do we write to arrays */
- if (fn.kind()==FKind.FlatSetElementNode) {
- //have to do expansion
- nodelayarraywrset.addAll(typeanalysis.expand(((FlatSetElementNode)fn).getDst().getType()));
- }
- /* Do we read from arrays */
- if (fn.kind()==FKind.FlatElementNode) {
- //have to do expansion
- nodelayarrayrdset.addAll(typeanalysis.expand(((FlatElementNode)fn).getSrc().getType()));
- }
-
- //See if flatnode is definitely no delay
- if (fn.kind()==FKind.FlatCall) {
- //Have to deal with fields/arrays
- FlatCall fcall=(FlatCall)fn;
- MethodDescriptor mdcall=fcall.getMethod();
- nodelayfieldwrset.addAll(gft.getFieldsAll(mdcall));
- nodelayarraywrset.addAll(typeanalysis.expandSet(gft.getArraysAll(mdcall)));
- //Have to deal with field/array reads
- nodelayfieldrdset.addAll(gft.getFieldsRdAll(mdcall));
- nodelayarrayrdset.addAll(typeanalysis.expandSet(gft.getArraysRdAll(mdcall)));
- }
+ /* Add our read set */
+ TempDescriptor readset[]=fn.readsTemps();
+ for(int i=0; i<readset.length; i++) {
+ TempDescriptor tmp=readset[i];
+ nodelaytempset.add(tmp);
+ }
+ cannotdelay.add(fn);
+
+ if (branchmap.containsKey(fn)) {
+ Set<FlatCondBranch> fcbset=branchmap.get(fn);
+ for(Iterator<FlatCondBranch> fcbit=fcbset.iterator(); fcbit.hasNext(); ) {
+ FlatCondBranch fcb=fcbit.next();
+ //enqueue flatcondbranch node for reanalysis
+ if (!cannotdelay.contains(fcb)) {
+ cannotdelay.add(fcb);
+ toanalyze.add(fcb);
+ }
+ }
+ }
+ /* Do we write to fields */
+ if (fn.kind()==FKind.FlatSetFieldNode) {
+ nodelayfieldwrset.add(((FlatSetFieldNode)fn).getField());
+ }
+ /* Do we read from fields */
+ if (fn.kind()==FKind.FlatFieldNode) {
+ nodelayfieldrdset.add(((FlatFieldNode)fn).getField());
+ }
+ /* Do we write to arrays */
+ if (fn.kind()==FKind.FlatSetElementNode) {
+ //have to do expansion
+ nodelayarraywrset.addAll(typeanalysis.expand(((FlatSetElementNode)fn).getDst().getType()));
+ }
+ /* Do we read from arrays */
+ if (fn.kind()==FKind.FlatElementNode) {
+ //have to do expansion
+ nodelayarrayrdset.addAll(typeanalysis.expand(((FlatElementNode)fn).getSrc().getType()));
+ }
+
+ //See if flatnode is definitely no delay
+ if (fn.kind()==FKind.FlatCall) {
+ //Have to deal with fields/arrays
+ FlatCall fcall=(FlatCall)fn;
+ MethodDescriptor mdcall=fcall.getMethod();
+ nodelayfieldwrset.addAll(gft.getFieldsAll(mdcall));
+ nodelayarraywrset.addAll(typeanalysis.expandSet(gft.getArraysAll(mdcall)));
+ //Have to deal with field/array reads
+ nodelayfieldrdset.addAll(gft.getFieldsRdAll(mdcall));
+ nodelayarrayrdset.addAll(typeanalysis.expandSet(gft.getArraysRdAll(mdcall)));
+ }
} else {
- //Need to know which objects to lock on
- Set<TempDescriptor> oldtemps=oldtempmap.get(fn);
- switch(fn.kind()) {
- case FKind.FlatSetFieldNode: {
- FlatSetFieldNode fsfn=(FlatSetFieldNode)fn;
- if (oldtemps.contains(fsfn.getDst())) {
- nodelaytempset.add(fsfn.getDst());
- }
- break;
- }
-
- case FKind.FlatSetElementNode: {
- FlatSetElementNode fsen=(FlatSetElementNode)fn;
- if (oldtemps.contains(fsen.getDst())) {
- nodelaytempset.add(fsen.getDst());
- //Word Array support requires index
- if (state.STMARRAY&&!state.DUALVIEW) {
- nodelaytempset.add(fsen.getIndex());
- derefset.add(fsen);
- }
- }
- break;
- }
-
- case FKind.FlatFieldNode: {
- FlatFieldNode ffn=(FlatFieldNode)fn;
- if (oldtemps.contains(ffn.getSrc())&&
- dcopts.getFields().contains(ffn.getField())) {
- nodelaytempset.add(ffn.getSrc());
- }
- break;
- }
-
- case FKind.FlatElementNode: {
- FlatElementNode fen=(FlatElementNode)fn;
- if (oldtemps.contains(fen.getSrc())&&
- dcopts.getArrays().contains(fen.getSrc().getType())) {
- nodelaytempset.add(fen.getSrc());
- //Word Array support requires index
- if (state.STMARRAY&&!state.DUALVIEW) {
- nodelaytempset.add(fen.getIndex());
- derefset.add(fen);
- }
- }
- break;
- }
- }
+ //Need to know which objects to lock on
+ Set<TempDescriptor> oldtemps=oldtempmap.get(fn);
+ switch(fn.kind()) {
+ case FKind.FlatSetFieldNode: {
+ FlatSetFieldNode fsfn=(FlatSetFieldNode)fn;
+ if (oldtemps.contains(fsfn.getDst())) {
+ nodelaytempset.add(fsfn.getDst());
+ }
+ break;
+ }
+
+ case FKind.FlatSetElementNode: {
+ FlatSetElementNode fsen=(FlatSetElementNode)fn;
+ if (oldtemps.contains(fsen.getDst())) {
+ nodelaytempset.add(fsen.getDst());
+ //Word Array support requires index
+ if (state.STMARRAY&&!state.DUALVIEW) {
+ nodelaytempset.add(fsen.getIndex());
+ derefset.add(fsen);
+ }
+ }
+ break;
+ }
+
+ case FKind.FlatFieldNode: {
+ FlatFieldNode ffn=(FlatFieldNode)fn;
+ if (oldtemps.contains(ffn.getSrc())&&
+ dcopts.getFields().contains(ffn.getField())) {
+ nodelaytempset.add(ffn.getSrc());
+ }
+ break;
+ }
+
+ case FKind.FlatElementNode: {
+ FlatElementNode fen=(FlatElementNode)fn;
+ if (oldtemps.contains(fen.getSrc())&&
+ dcopts.getArrays().contains(fen.getSrc().getType())) {
+ nodelaytempset.add(fen.getSrc());
+ //Word Array support requires index
+ if (state.STMARRAY&&!state.DUALVIEW) {
+ nodelaytempset.add(fen.getIndex());
+ derefset.add(fen);
+ }
+ }
+ break;
+ }
+ }
}
boolean changed=false;
//See if we need to propagate changes
if (!nodelaytemps.containsKey(fn)||
!nodelaytemps.get(fn).equals(nodelaytempset)) {
- nodelaytemps.put(fn, nodelaytempset);
- changed=true;
+ nodelaytemps.put(fn, nodelaytempset);
+ changed=true;
}
//See if we need to propagate changes
if (!nodelayfieldswr.containsKey(fn)||
!nodelayfieldswr.get(fn).equals(nodelayfieldwrset)) {
- nodelayfieldswr.put(fn, nodelayfieldwrset);
- changed=true;
+ nodelayfieldswr.put(fn, nodelayfieldwrset);
+ changed=true;
}
//See if we need to propagate changes
if (!nodelayfieldsrd.containsKey(fn)||
!nodelayfieldsrd.get(fn).equals(nodelayfieldrdset)) {
- nodelayfieldsrd.put(fn, nodelayfieldrdset);
- changed=true;
+ nodelayfieldsrd.put(fn, nodelayfieldrdset);
+ changed=true;
}
//See if we need to propagate changes
if (!nodelayarrayswr.containsKey(fn)||
!nodelayarrayswr.get(fn).equals(nodelayarraywrset)) {
- nodelayarrayswr.put(fn, nodelayarraywrset);
- changed=true;
+ nodelayarrayswr.put(fn, nodelayarraywrset);
+ changed=true;
}
//See if we need to propagate changes
if (!nodelayarraysrd.containsKey(fn)||
!nodelayarraysrd.get(fn).equals(nodelayarrayrdset)) {
- nodelayarraysrd.put(fn, nodelayarrayrdset);
- changed=true;
+ nodelayarraysrd.put(fn, nodelayarrayrdset);
+ changed=true;
}
if (changed)
- for(int i=0; i<fn.numPrev(); i++)
- toanalyze.add(fn.getPrev(i));
+ for(int i=0; i<fn.numPrev(); i++)
+ toanalyze.add(fn.getPrev(i));
} //end of while loop
if (lb.getHasAtomic()) {
if (state.STMARRAY&&!state.DUALVIEW)
- derefmap.put(lb, derefset);
+ derefmap.put(lb, derefset);
cannotdelaymap.put(lb, cannotdelay);
}
} //end of method
boolean isatomic=atomictable.get(fn).intValue()>0;
if (!isatomic)
- continue;
+ continue;
//Compute initial notready set
HashSet<TempDescriptor> notreadyset=new HashSet<TempDescriptor>();
for(int i=0; i<fn.numPrev(); i++) {
- if (notreadymap.containsKey(fn.getPrev(i)))
- notreadyset.addAll(notreadymap.get(fn.getPrev(i)));
+ if (notreadymap.containsKey(fn.getPrev(i)))
+ notreadyset.addAll(notreadymap.get(fn.getPrev(i)));
}
//Are we ready
//Test our read set first
TempDescriptor readset[]=fn.readsTemps();
for(int i=0; i<readset.length; i++) {
- TempDescriptor tmp=readset[i];
- if (notreadyset.contains(tmp)) {
- notready=true;
- break;
- }
+ TempDescriptor tmp=readset[i];
+ if (notreadyset.contains(tmp)) {
+ notready=true;
+ break;
+ }
}
if (!notready&&!cannotdelay.contains(fn)) {
- switch(fn.kind()) {
- case FKind.FlatFieldNode: {
- FlatFieldNode ffn=(FlatFieldNode)fn;
- if (!dcopts.getFields().contains(ffn.getField())) {
- break;
- }
- TempDescriptor tmp=ffn.getSrc();
- Set<TempFlatPair> tfpset=dcopts.getMap(lb).get(fn).get(tmp);
- if (tfpset!=null) {
- for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
- TempFlatPair tfp=tfpit.next();
- if (!dcopts.getNeedSrcTrans(lb, tfp.f)) {
- //if a source didn't need a translation and we are
- //accessing it, it did...so therefore we are note
- //ready
- notready=true;
- break;
- }
- }
- }
- break;
- }
-
- case FKind.FlatSetFieldNode: {
- FlatSetFieldNode fsfn=(FlatSetFieldNode)fn;
- TempDescriptor tmp=fsfn.getDst();
- Hashtable<TempDescriptor, Set<TempFlatPair>> tmpmap=dcopts.getMap(lb).get(fn);
- Set<TempFlatPair> tfpset=tmpmap!=null?tmpmap.get(tmp):null;
-
- if (tfpset!=null) {
- for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
- TempFlatPair tfp=tfpit.next();
- if (!dcopts.getNeedSrcTrans(lb, tfp.f)) {
- //if a source didn't need a translation and we are
- //accessing it, it did...so therefore we are note
- //ready
- notready=true;
- break;
- }
- }
- }
- break;
- }
-
- case FKind.FlatElementNode: {
- FlatElementNode fen=(FlatElementNode)fn;
- if (!dcopts.getArrays().contains(fen.getSrc().getType())) {
- break;
- }
- TempDescriptor tmp=fen.getSrc();
- Set<TempFlatPair> tfpset=dcopts.getMap(lb).get(fn).get(tmp);
- if (tfpset!=null) {
- for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
- TempFlatPair tfp=tfpit.next();
- if (!dcopts.getNeedSrcTrans(lb, tfp.f)) {
- //if a source didn't need a translation and we are
- //accessing it, it did...so therefore we are note
- //ready
- notready=true;
- break;
- }
- }
- }
- break;
- }
-
- case FKind.FlatSetElementNode: {
- FlatSetElementNode fsen=(FlatSetElementNode)fn;
- TempDescriptor tmp=fsen.getDst();
- Set<TempFlatPair> tfpset=dcopts.getMap(lb).get(fn).get(tmp);
- if (tfpset!=null) {
- for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
- TempFlatPair tfp=tfpit.next();
- if (!dcopts.getNeedSrcTrans(lb, tfp.f)) {
- //if a source didn't need a translation and we are
- //accessing it, it did...so therefore we are note
- //ready
- notready=true;
- break;
- }
- }
- }
- break;
- }
- }
+ switch(fn.kind()) {
+ case FKind.FlatFieldNode: {
+ FlatFieldNode ffn=(FlatFieldNode)fn;
+ if (!dcopts.getFields().contains(ffn.getField())) {
+ break;
+ }
+ TempDescriptor tmp=ffn.getSrc();
+ Set<TempFlatPair> tfpset=dcopts.getMap(lb).get(fn).get(tmp);
+ if (tfpset!=null) {
+ for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
+ TempFlatPair tfp=tfpit.next();
+ if (!dcopts.getNeedSrcTrans(lb, tfp.f)) {
+ //if a source didn't need a translation and we are
+ //accessing it, it did...so therefore we are note
+ //ready
+ notready=true;
+ break;
+ }
+ }
+ }
+ break;
+ }
+
+ case FKind.FlatSetFieldNode: {
+ FlatSetFieldNode fsfn=(FlatSetFieldNode)fn;
+ TempDescriptor tmp=fsfn.getDst();
+ Hashtable<TempDescriptor, Set<TempFlatPair>> tmpmap=dcopts.getMap(lb).get(fn);
+ Set<TempFlatPair> tfpset=tmpmap!=null?tmpmap.get(tmp):null;
+
+ if (tfpset!=null) {
+ for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
+ TempFlatPair tfp=tfpit.next();
+ if (!dcopts.getNeedSrcTrans(lb, tfp.f)) {
+ //if a source didn't need a translation and we are
+ //accessing it, it did...so therefore we are note
+ //ready
+ notready=true;
+ break;
+ }
+ }
+ }
+ break;
+ }
+
+ case FKind.FlatElementNode: {
+ FlatElementNode fen=(FlatElementNode)fn;
+ if (!dcopts.getArrays().contains(fen.getSrc().getType())) {
+ break;
+ }
+ TempDescriptor tmp=fen.getSrc();
+ Set<TempFlatPair> tfpset=dcopts.getMap(lb).get(fn).get(tmp);
+ if (tfpset!=null) {
+ for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
+ TempFlatPair tfp=tfpit.next();
+ if (!dcopts.getNeedSrcTrans(lb, tfp.f)) {
+ //if a source didn't need a translation and we are
+ //accessing it, it did...so therefore we are note
+ //ready
+ notready=true;
+ break;
+ }
+ }
+ }
+ break;
+ }
+
+ case FKind.FlatSetElementNode: {
+ FlatSetElementNode fsen=(FlatSetElementNode)fn;
+ TempDescriptor tmp=fsen.getDst();
+ Set<TempFlatPair> tfpset=dcopts.getMap(lb).get(fn).get(tmp);
+ if (tfpset!=null) {
+ for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
+ TempFlatPair tfp=tfpit.next();
+ if (!dcopts.getNeedSrcTrans(lb, tfp.f)) {
+ //if a source didn't need a translation and we are
+ //accessing it, it did...so therefore we are note
+ //ready
+ notready=true;
+ break;
+ }
+ }
+ }
+ break;
+ }
+ }
}
if (!notready) {
- //See if we depend on a conditional branch that is not ready
- Set<FlatCondBranch> branchset=branchmap.get(fn);
- if (branchset!=null)
- for(Iterator<FlatCondBranch> branchit=branchset.iterator(); branchit.hasNext(); ) {
- FlatCondBranch fcb=branchit.next();
- if (notreadynodes.contains(fcb)) {
- //if we depend on a branch that isn't ready, we aren't ready
- notready=true;
- break;
- }
- }
+ //See if we depend on a conditional branch that is not ready
+ Set<FlatCondBranch> branchset=branchmap.get(fn);
+ if (branchset!=null)
+ for(Iterator<FlatCondBranch> branchit=branchset.iterator(); branchit.hasNext(); ) {
+ FlatCondBranch fcb=branchit.next();
+ if (notreadynodes.contains(fcb)) {
+ //if we depend on a branch that isn't ready, we aren't ready
+ notready=true;
+ break;
+ }
+ }
}
//Fix up things based on our status
if (notready) {
- if (fn.kind()==FKind.FlatCondBranch&&!notreadynodes.contains(fn)) {
- //enqueue everything in our dependence set
- Set<FlatNode> branchdepset=revbranchmap.get((FlatCondBranch)fn);
- toanalyze.addAll(branchdepset);
- }
-
- //add us to the list
- notreadynodes.add(fn);
-
- //Add our writes
- TempDescriptor writeset[]=fn.writesTemps();
- for(int i=0; i<writeset.length; i++) {
- TempDescriptor tmp=writeset[i];
- notreadyset.add(tmp);
- }
+ if (fn.kind()==FKind.FlatCondBranch&&!notreadynodes.contains(fn)) {
+ //enqueue everything in our dependence set
+ Set<FlatNode> branchdepset=revbranchmap.get((FlatCondBranch)fn);
+ toanalyze.addAll(branchdepset);
+ }
+
+ //add us to the list
+ notreadynodes.add(fn);
+
+ //Add our writes
+ TempDescriptor writeset[]=fn.writesTemps();
+ for(int i=0; i<writeset.length; i++) {
+ TempDescriptor tmp=writeset[i];
+ notreadyset.add(tmp);
+ }
} else {
- //Kill our writes
- TempDescriptor writeset[]=fn.writesTemps();
- for(int i=0; i<writeset.length; i++) {
- TempDescriptor tmp=writeset[i];
- notreadyset.remove(tmp);
- }
+ //Kill our writes
+ TempDescriptor writeset[]=fn.writesTemps();
+ for(int i=0; i<writeset.length; i++) {
+ TempDescriptor tmp=writeset[i];
+ notreadyset.remove(tmp);
+ }
}
//See if we need to propagate changes
if (!notreadymap.containsKey(fn)||
!notreadymap.get(fn).equals(notreadyset)) {
- notreadymap.put(fn, notreadyset);
- for(int i=0; i<fn.numNext(); i++)
- toanalyze.add(fn.getNext(i));
+ notreadymap.put(fn, notreadyset);
+ for(int i=0; i<fn.numNext(); i++)
+ toanalyze.add(fn.getNext(i));
}
} //end of while
return notreadynodes;
for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator(); fnit.hasNext(); ) {
FlatNode fn=fnit.next();
if (fn.kind()!=FKind.FlatCondBranch)
- continue;
+ continue;
FlatCondBranch fcb=(FlatCondBranch)fn;
//only worry about fcb inside of transactions
if (locality.getAtomic(lb).get(fcb).intValue()==0)
- continue;
+ continue;
FlatNode postdom=postdt.idom(fcb);
//Reverse the mapping
for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator(); fnit.hasNext(); ) {
FlatNode fn=fnit.next();
if (fn.kind()!=FKind.FlatCondBranch)
- continue;
+ continue;
FlatCondBranch fcb=(FlatCondBranch)fn;
//only worry about fcb inside of transactions
if (locality.getAtomic(lb).get(fcb).intValue()==0)
- continue;
+ continue;
FlatNode postdom=postdt.idom(fcb);
//Reverse the mapping
Set<FlatNode> fnset=computeBranchSet(lb, fcb, postdom);
for(Iterator<FlatNode>fnit2=fnset.iterator(); fnit2.hasNext(); ) {
- FlatNode fn2=fnit2.next();
- if (!condmap.containsKey(fn2))
- condmap.put(fn2,new HashSet<FlatCondBranch>());
- condmap.get(fn2).add(fcb);
+ FlatNode fn2=fnit2.next();
+ if (!condmap.containsKey(fn2))
+ condmap.put(fn2,new HashSet<FlatCondBranch>());
+ condmap.get(fn2).add(fcb);
}
}
return condmap;
//already examined or exit node
if (visited.contains(fn)||fn==last)
- continue;
+ continue;
//out of transaction
if (locality.getAtomic(lb).get(fn).intValue()==0)
- continue;
+ continue;
visited.add(fn);
for(int i=0; i<fn.numNext(); i++) {
- FlatNode fnext=fn.getNext(i);
- toanalyze.add(fnext);
+ FlatNode fnext=fn.getNext(i);
+ toanalyze.add(fnext);
}
}
return visited;
//need to translate write map set
set=new HashSet<FlatNode>();
for(Iterator<TempFlatPair> it=writemap.get(lb).iterator(); it.hasNext(); ) {
- TempFlatPair tfp=it.next();
- set.add(tfp.f);
+ TempFlatPair tfp=it.next();
+ set.add(tfp.f);
}
twritemap.put(lb, set);
}
// Set<FlatNode> gwriteset=(state.READSET&&gft!=null)?twritemap.get(lb):treadmap.get(lb);
if (state.READSET&&gft!=null) {
if (twritemap.get(lb).size()==0) {
- getmap.put(lb, new HashSet<FlatNode>());
- return;
+ getmap.put(lb, new HashSet<FlatNode>());
+ return;
}
}
FlatNode fn=fnit.next();
Hashtable<FlatNode, Integer> atomictable=locality.getAtomic(lb);
if (atomictable.get(fn).intValue()>0&&fn.kind()==FKind.FlatElementNode) {
- FlatElementNode fen=(FlatElementNode)fn;
- Set<TempFlatPair> tfpset=fnmap.get(fen).get(fen.getSrc());
- if (tfpset!=null) {
- for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
- TempFlatPair tfp=tfpit.next();
- if (gwriteset.contains(tfp.f)) {
- needsget.add(fen);
- break;
- }
- }
- }
+ FlatElementNode fen=(FlatElementNode)fn;
+ Set<TempFlatPair> tfpset=fnmap.get(fen).get(fen.getSrc());
+ if (tfpset!=null) {
+ for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
+ TempFlatPair tfp=tfpit.next();
+ if (gwriteset.contains(tfp.f)) {
+ needsget.add(fen);
+ break;
+ }
+ }
+ }
}
}
getmap.put(lb, needsget);
FlatNode fprev=fn.getPrev(i);
Hashtable<TempDescriptor, Set<TempFlatPair>> tabset=tmptofnset.get(fprev);
if (tabset!=null) {
- for(Iterator<TempDescriptor> tmpit=tabset.keySet().iterator(); tmpit.hasNext(); ) {
- TempDescriptor td=tmpit.next();
- Set<TempFlatPair> fnset=tabset.get(td);
- if (!table.containsKey(td))
- table.put(td, new HashSet<TempFlatPair>());
- table.get(td).addAll(fnset);
- }
+ for(Iterator<TempDescriptor> tmpit=tabset.keySet().iterator(); tmpit.hasNext(); ) {
+ TempDescriptor td=tmpit.next();
+ Set<TempFlatPair> fnset=tabset.get(td);
+ if (!table.containsKey(td))
+ table.put(td, new HashSet<TempFlatPair>());
+ table.get(td).addAll(fnset);
+ }
}
}
return table;
FlatNode fn=fnit.next();
Hashtable<FlatNode, Integer> atomictable=locality.getAtomic(lb);
if (atomictable.get(fn).intValue()>0) {
- Hashtable<TempDescriptor, Set<TempFlatPair>> tmap=fnmap.get(fn);
- switch(fn.kind()) {
- //We might need to translate arguments to pointer comparison
-
- case FKind.FlatOpNode: {
- FlatOpNode fon=(FlatOpNode)fn;
- if (fon.getOp().getOp()==Operation.EQUAL||
- fon.getOp().getOp()==Operation.NOTEQUAL) {
- if (!fon.getLeft().getType().isPtr())
- break;
- Set<TempFlatPair> lefttfpset=tmap.get(fon.getLeft());
- Set<TempFlatPair> righttfpset=tmap.get(fon.getRight());
- //handle left operand
- if (lefttfpset!=null) {
- for(Iterator<TempFlatPair> tfpit=lefttfpset.iterator(); tfpit.hasNext(); ) {
- TempFlatPair tfp=tfpit.next();
- if (tfset.contains(tfp)||outofscope(tfp)) {
- leftsrctrans.add(fon);
- break;
- }
- }
- }
- //handle right operand
- if (righttfpset!=null) {
- for(Iterator<TempFlatPair> tfpit=righttfpset.iterator(); tfpit.hasNext(); ) {
- TempFlatPair tfp=tfpit.next();
- if (tfset.contains(tfp)||outofscope(tfp)) {
- rightsrctrans.add(fon);
- break;
- }
- }
- }
- }
- break;
- }
-
- case FKind.FlatGlobalConvNode: {
- //need to translate these if the value we read from may be a
- //shadow... check this by seeing if any of the values we
- //may read are in the transread set or came from our caller
- //or a method we called
-
- FlatGlobalConvNode fgcn=(FlatGlobalConvNode)fn;
- if (fgcn.getLocality()!=lb||
- fgcn.getMakePtr())
- break;
-
- Set<TempFlatPair> tfpset=tmap.get(fgcn.getSrc());
-
- if (tfpset!=null) {
- for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
- TempFlatPair tfp=tfpit.next();
- if (tfset.contains(tfp)||outofscope(tfp)) {
- srctrans.add(fgcn);
- break;
- }
- }
- }
- break;
- }
-
- case FKind.FlatSetFieldNode: {
- //need to translate these if the value we read from may be a
- //shadow... check this by seeing if any of the values we
- //may read are in the transread set or came from our caller
- //or a method we called
-
- FlatSetFieldNode fsfn=(FlatSetFieldNode)fn;
- if (!fsfn.getField().getType().isPtr())
- break;
- Set<TempFlatPair> tfpset=tmap.get(fsfn.getSrc());
- if (tfpset!=null) {
- for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
- TempFlatPair tfp=tfpit.next();
- if (tfset.contains(tfp)||outofscope(tfp)) {
- srctrans.add(fsfn);
- break;
- }
- }
- }
- break;
- }
-
- case FKind.FlatSetElementNode: {
- //need to translate these if the value we read from may be a
- //shadow... check this by seeing if any of the values we
- //may read are in the transread set or came from our caller
- //or a method we called
-
- FlatSetElementNode fsen=(FlatSetElementNode)fn;
- if (!fsen.getSrc().getType().isPtr())
- break;
- Set<TempFlatPair> tfpset=tmap.get(fsen.getSrc());
- if (tfpset!=null) {
- for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
- TempFlatPair tfp=tfpit.next();
- if (tfset.contains(tfp)||outofscope(tfp)) {
- srctrans.add(fsen);
- break;
- }
- }
- }
- break;
- }
-
- default:
- }
+ Hashtable<TempDescriptor, Set<TempFlatPair>> tmap=fnmap.get(fn);
+ switch(fn.kind()) {
+ //We might need to translate arguments to pointer comparison
+
+ case FKind.FlatOpNode: {
+ FlatOpNode fon=(FlatOpNode)fn;
+ if (fon.getOp().getOp()==Operation.EQUAL||
+ fon.getOp().getOp()==Operation.NOTEQUAL) {
+ if (!fon.getLeft().getType().isPtr())
+ break;
+ Set<TempFlatPair> lefttfpset=tmap.get(fon.getLeft());
+ Set<TempFlatPair> righttfpset=tmap.get(fon.getRight());
+ //handle left operand
+ if (lefttfpset!=null) {
+ for(Iterator<TempFlatPair> tfpit=lefttfpset.iterator(); tfpit.hasNext(); ) {
+ TempFlatPair tfp=tfpit.next();
+ if (tfset.contains(tfp)||outofscope(tfp)) {
+ leftsrctrans.add(fon);
+ break;
+ }
+ }
+ }
+ //handle right operand
+ if (righttfpset!=null) {
+ for(Iterator<TempFlatPair> tfpit=righttfpset.iterator(); tfpit.hasNext(); ) {
+ TempFlatPair tfp=tfpit.next();
+ if (tfset.contains(tfp)||outofscope(tfp)) {
+ rightsrctrans.add(fon);
+ break;
+ }
+ }
+ }
+ }
+ break;
+ }
+
+ case FKind.FlatGlobalConvNode: {
+ //need to translate these if the value we read from may be a
+ //shadow... check this by seeing if any of the values we
+ //may read are in the transread set or came from our caller
+ //or a method we called
+
+ FlatGlobalConvNode fgcn=(FlatGlobalConvNode)fn;
+ if (fgcn.getLocality()!=lb||
+ fgcn.getMakePtr())
+ break;
+
+ Set<TempFlatPair> tfpset=tmap.get(fgcn.getSrc());
+
+ if (tfpset!=null) {
+ for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
+ TempFlatPair tfp=tfpit.next();
+ if (tfset.contains(tfp)||outofscope(tfp)) {
+ srctrans.add(fgcn);
+ break;
+ }
+ }
+ }
+ break;
+ }
+
+ case FKind.FlatSetFieldNode: {
+ //need to translate these if the value we read from may be a
+ //shadow... check this by seeing if any of the values we
+ //may read are in the transread set or came from our caller
+ //or a method we called
+
+ FlatSetFieldNode fsfn=(FlatSetFieldNode)fn;
+ if (!fsfn.getField().getType().isPtr())
+ break;
+ Set<TempFlatPair> tfpset=tmap.get(fsfn.getSrc());
+ if (tfpset!=null) {
+ for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
+ TempFlatPair tfp=tfpit.next();
+ if (tfset.contains(tfp)||outofscope(tfp)) {
+ srctrans.add(fsfn);
+ break;
+ }
+ }
+ }
+ break;
+ }
+
+ case FKind.FlatSetElementNode: {
+ //need to translate these if the value we read from may be a
+ //shadow... check this by seeing if any of the values we
+ //may read are in the transread set or came from our caller
+ //or a method we called
+
+ FlatSetElementNode fsen=(FlatSetElementNode)fn;
+ if (!fsen.getSrc().getType().isPtr())
+ break;
+ Set<TempFlatPair> tfpset=tmap.get(fsen.getSrc());
+ if (tfpset!=null) {
+ for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
+ TempFlatPair tfp=tfpit.next();
+ if (tfset.contains(tfp)||outofscope(tfp)) {
+ srctrans.add(fsen);
+ break;
+ }
+ }
+ }
+ break;
+ }
+
+ default:
+ }
}
}
//Update results
//Stop if we aren't in a transaction
if (atomictable.get(fn).intValue()==0)
- continue;
+ continue;
//Do merge of all exits
for(int i=0; i<fn.numNext(); i++) {
- FlatNode fnnext=fn.getNext(i);
- if (updatedtypemap.containsKey(fnnext)) {
- updatetypeset.addAll(updatedtypemap.get(fnnext));
- }
- if (updatedfieldmap.containsKey(fnnext)) {
- updatefieldset.addAll(updatedfieldmap.get(fnnext));
- }
+ FlatNode fnnext=fn.getNext(i);
+ if (updatedtypemap.containsKey(fnnext)) {
+ updatetypeset.addAll(updatedtypemap.get(fnnext));
+ }
+ if (updatedfieldmap.containsKey(fnnext)) {
+ updatefieldset.addAll(updatedfieldmap.get(fnnext));
+ }
}
//process this node
if (cannotdelaymap!=null&&cannotdelaymap.containsKey(lb)&&cannotdelaymap.get(lb).contains(fn)!=inclusive) {
- switch(fn.kind()) {
- case FKind.FlatSetFieldNode: {
- FlatSetFieldNode fsfn=(FlatSetFieldNode)fn;
- updatefieldset.add(fsfn.getField());
- break;
- }
-
- case FKind.FlatSetElementNode: {
- FlatSetElementNode fsen=(FlatSetElementNode)fn;
- updatetypeset.addAll(typeanalysis.expand(fsen.getDst().getType()));
- break;
- }
-
- case FKind.FlatCall: {
- FlatCall fcall=(FlatCall)fn;
- MethodDescriptor mdfc=fcall.getMethod();
-
- //get modified fields
- Set<FieldDescriptor> fields=gft.getFieldsAll(mdfc);
- updatefieldset.addAll(fields);
-
- //get modified arrays
- Set<TypeDescriptor> arrays=gft.getArraysAll(mdfc);
- updatetypeset.addAll(typeanalysis.expandSet(arrays));
- break;
- }
- }
+ switch(fn.kind()) {
+ case FKind.FlatSetFieldNode: {
+ FlatSetFieldNode fsfn=(FlatSetFieldNode)fn;
+ updatefieldset.add(fsfn.getField());
+ break;
+ }
+
+ case FKind.FlatSetElementNode: {
+ FlatSetElementNode fsen=(FlatSetElementNode)fn;
+ updatetypeset.addAll(typeanalysis.expand(fsen.getDst().getType()));
+ break;
+ }
+
+ case FKind.FlatCall: {
+ FlatCall fcall=(FlatCall)fn;
+ MethodDescriptor mdfc=fcall.getMethod();
+
+ //get modified fields
+ Set<FieldDescriptor> fields=gft.getFieldsAll(mdfc);
+ updatefieldset.addAll(fields);
+
+ //get modified arrays
+ Set<TypeDescriptor> arrays=gft.getArraysAll(mdfc);
+ updatetypeset.addAll(typeanalysis.expandSet(arrays));
+ break;
+ }
+ }
}
if (!updatedtypemap.containsKey(fn)||!updatedfieldmap.containsKey(fn)||
!updatedtypemap.get(fn).equals(updatetypeset)||!updatedfieldmap.get(fn).equals(updatefieldset)) {
- updatedtypemap.put(fn, updatetypeset);
- updatedfieldmap.put(fn, updatefieldset);
- for(int i=0; i<fn.numPrev(); i++) {
- toanalyze.add(fn.getPrev(i));
- }
+ updatedtypemap.put(fn, updatetypeset);
+ updatedfieldmap.put(fn, updatefieldset);
+ for(int i=0; i<fn.numPrev(); i++) {
+ toanalyze.add(fn.getPrev(i));
+ }
}
}
}
FlatNode fn=fnit.next();
//Check whether this node matters for cannot delayed computation
if (cannotdelaymap!=null&&cannotdelaymap.containsKey(lb)&&cannotdelaymap.get(lb).contains(fn)==inclusive)
- continue;
+ continue;
Hashtable<FlatNode, Integer> atomictable=locality.getAtomic(lb);
if (atomictable.get(fn).intValue()>0) {
- Hashtable<TempDescriptor, Set<TempFlatPair>> tmap=fnmap.get(fn);
- switch(fn.kind()) {
- case FKind.FlatElementNode: {
- FlatElementNode fen=(FlatElementNode)fn;
- if (arrays.contains(fen.getSrc().getType())) {
- //this could cause conflict...figure out conflict set
- Set<TempFlatPair> tfpset=tmap.get(fen.getSrc());
- if (tfpset!=null)
- tfset.addAll(tfpset);
- }
- if (updatedtypemap!=null&&updatedtypemap.get(fen).contains(fen.getSrc().getType())) {
- //this could cause conflict...figure out conflict set
- Set<TempFlatPair> tfpset=tmap.get(fen.getSrc());
- if (tfpset!=null)
- tfset.addAll(tfpset);
- }
- break;
- }
-
- case FKind.FlatFieldNode: {
- FlatFieldNode ffn=(FlatFieldNode)fn;
- if (fields.contains(ffn.getField())) {
- //this could cause conflict...figure out conflict set
- Set<TempFlatPair> tfpset=tmap.get(ffn.getSrc());
- if (tfpset!=null)
- tfset.addAll(tfpset);
- }
- if (updatedfieldmap!=null&&updatedfieldmap.get(ffn).contains(ffn.getField())) {
- //this could cause conflict...figure out conflict set
- Set<TempFlatPair> tfpset=tmap.get(ffn.getSrc());
- if (tfpset!=null)
- tfset.addAll(tfpset);
- }
- break;
- }
-
- case FKind.FlatSetFieldNode: {
- //definitely need to translate these
- FlatSetFieldNode fsfn=(FlatSetFieldNode)fn;
- Set<TempFlatPair> tfpset=tmap.get(fsfn.getDst());
- if (tfpset!=null)
- tfset.addAll(tfpset);
- if (writeset!=null) {
- if (tfpset!=null)
- writeset.addAll(tfpset);
- }
- break;
- }
-
- case FKind.FlatSetElementNode: {
- //definitely need to translate these
- FlatSetElementNode fsen=(FlatSetElementNode)fn;
- Set<TempFlatPair> tfpset=tmap.get(fsen.getDst());
- if (tfpset!=null)
- tfset.addAll(tfpset);
- if (writeset!=null) {
- if (tfpset!=null)
- writeset.addAll(tfpset);
- }
- break;
- }
-
- case FKind.FlatCall: //assume pessimistically that calls do bad things
- case FKind.FlatReturnNode: {
- TempDescriptor [] readarray=fn.readsTemps();
- for(int i=0; i<readarray.length; i++) {
- TempDescriptor rtmp=readarray[i];
- Set<TempFlatPair> tfpset=tmap.get(rtmp);
- if (tfpset!=null)
- tfset.addAll(tfpset);
- if (writeset!=null) {
- if (tfpset!=null)
- writeset.addAll(tfpset);
- }
- }
- break;
- }
-
- default:
- //do nothing
- }
+ Hashtable<TempDescriptor, Set<TempFlatPair>> tmap=fnmap.get(fn);
+ switch(fn.kind()) {
+ case FKind.FlatElementNode: {
+ FlatElementNode fen=(FlatElementNode)fn;
+ if (arrays.contains(fen.getSrc().getType())) {
+ //this could cause conflict...figure out conflict set
+ Set<TempFlatPair> tfpset=tmap.get(fen.getSrc());
+ if (tfpset!=null)
+ tfset.addAll(tfpset);
+ }
+ if (updatedtypemap!=null&&updatedtypemap.get(fen).contains(fen.getSrc().getType())) {
+ //this could cause conflict...figure out conflict set
+ Set<TempFlatPair> tfpset=tmap.get(fen.getSrc());
+ if (tfpset!=null)
+ tfset.addAll(tfpset);
+ }
+ break;
+ }
+
+ case FKind.FlatFieldNode: {
+ FlatFieldNode ffn=(FlatFieldNode)fn;
+ if (fields.contains(ffn.getField())) {
+ //this could cause conflict...figure out conflict set
+ Set<TempFlatPair> tfpset=tmap.get(ffn.getSrc());
+ if (tfpset!=null)
+ tfset.addAll(tfpset);
+ }
+ if (updatedfieldmap!=null&&updatedfieldmap.get(ffn).contains(ffn.getField())) {
+ //this could cause conflict...figure out conflict set
+ Set<TempFlatPair> tfpset=tmap.get(ffn.getSrc());
+ if (tfpset!=null)
+ tfset.addAll(tfpset);
+ }
+ break;
+ }
+
+ case FKind.FlatSetFieldNode: {
+ //definitely need to translate these
+ FlatSetFieldNode fsfn=(FlatSetFieldNode)fn;
+ Set<TempFlatPair> tfpset=tmap.get(fsfn.getDst());
+ if (tfpset!=null)
+ tfset.addAll(tfpset);
+ if (writeset!=null) {
+ if (tfpset!=null)
+ writeset.addAll(tfpset);
+ }
+ break;
+ }
+
+ case FKind.FlatSetElementNode: {
+ //definitely need to translate these
+ FlatSetElementNode fsen=(FlatSetElementNode)fn;
+ Set<TempFlatPair> tfpset=tmap.get(fsen.getDst());
+ if (tfpset!=null)
+ tfset.addAll(tfpset);
+ if (writeset!=null) {
+ if (tfpset!=null)
+ writeset.addAll(tfpset);
+ }
+ break;
+ }
+
+ case FKind.FlatCall: //assume pessimistically that calls do bad things
+ case FKind.FlatReturnNode: {
+ TempDescriptor [] readarray=fn.readsTemps();
+ for(int i=0; i<readarray.length; i++) {
+ TempDescriptor rtmp=readarray[i];
+ Set<TempFlatPair> tfpset=tmap.get(rtmp);
+ if (tfpset!=null)
+ tfset.addAll(tfpset);
+ if (writeset!=null) {
+ if (tfpset!=null)
+ writeset.addAll(tfpset);
+ }
+ }
+ break;
+ }
+
+ default:
+ //do nothing
+ }
}
}
return tfset;
FlatNode fn=tovisit.iterator().next();
tovisit.remove(fn);
for(int i=0; i<fn.numNext(); i++) {
- FlatNode fnext=fn.getNext(i);
- if (!discovered.contains(fnext)) {
- discovered.add(fnext);
- tovisit.add(fnext);
- }
+ FlatNode fnext=fn.getNext(i);
+ if (!discovered.contains(fnext)) {
+ discovered.add(fnext);
+ tovisit.add(fnext);
+ }
}
Hashtable<TempDescriptor, Set<TempFlatPair>> ttofn=null;
if (atomictable.get(fn).intValue()!=0) {
- if ((fn.numPrev()>0)&&atomictable.get(fn.getPrev(0)).intValue()==0) {
- //atomic node, start with new set
- ttofn=new Hashtable<TempDescriptor, Set<TempFlatPair>>();
- } else {
- ttofn=doMerge(fn, tmptofnset);
- switch(fn.kind()) {
- case FKind.FlatGlobalConvNode: {
- FlatGlobalConvNode fgcn=(FlatGlobalConvNode)fn;
- if (lb==fgcn.getLocality()&&
- fgcn.getMakePtr()) {
- TempDescriptor[] writes=fn.writesTemps();
- for(int i=0; i<writes.length; i++) {
- TempDescriptor wtmp=writes[i];
- HashSet<TempFlatPair> set=new HashSet<TempFlatPair>();
- set.add(new TempFlatPair(wtmp, fn));
- ttofn.put(wtmp, set);
- }
- }
- break;
- }
-
- case FKind.FlatFieldNode:
- case FKind.FlatElementNode: {
- TempDescriptor[] writes=fn.writesTemps();
- for(int i=0; i<writes.length; i++) {
- TempDescriptor wtmp=writes[i];
- HashSet<TempFlatPair> set=new HashSet<TempFlatPair>();
- set.add(new TempFlatPair(wtmp, fn));
- ttofn.put(wtmp, set);
- }
- break;
- }
-
- case FKind.FlatCall:
- case FKind.FlatMethod: {
- TempDescriptor[] writes=fn.writesTemps();
- for(int i=0; i<writes.length; i++) {
- TempDescriptor wtmp=writes[i];
- HashSet<TempFlatPair> set=new HashSet<TempFlatPair>();
- set.add(new TempFlatPair(wtmp, fn));
- ttofn.put(wtmp, set);
- }
- break;
- }
-
- case FKind.FlatCastNode:
- case FKind.FlatOpNode:
- if (fn.kind()==FKind.FlatCastNode) {
- FlatCastNode fcn=(FlatCastNode)fn;
- if (fcn.getDst().getType().isPtr()) {
- HashSet<TempFlatPair> set=new HashSet<TempFlatPair>();
- if (ttofn.containsKey(fcn.getSrc()))
- set.addAll(ttofn.get(fcn.getSrc()));
- if (normalassign)
- set.add(new TempFlatPair(fcn.getDst(), fn));
- ttofn.put(fcn.getDst(), set);
- break;
- }
- } else if (fn.kind()==FKind.FlatOpNode) {
- FlatOpNode fon=(FlatOpNode)fn;
- if (fon.getOp().getOp()==Operation.ASSIGN&&fon.getDest().getType().isPtr()) {
- HashSet<TempFlatPair> set=new HashSet<TempFlatPair>();
- if (ttofn.containsKey(fon.getLeft()))
- set.addAll(ttofn.get(fon.getLeft()));
- if (normalassign)
- set.add(new TempFlatPair(fon.getDest(), fn));
- ttofn.put(fon.getDest(), set);
- break;
- }
- }
-
- default:
- //Do kill computation
- TempDescriptor[] writes=fn.writesTemps();
- for(int i=0; i<writes.length; i++) {
- TempDescriptor wtmp=writes[i];
- ttofn.remove(writes[i]);
- }
- }
- }
- if (ttofn!=null) {
- if (!tmptofnset.containsKey(fn)||
- !tmptofnset.get(fn).equals(ttofn)) {
- //enqueue nodes to process
- tmptofnset.put(fn, ttofn);
- for(int i=0; i<fn.numNext(); i++) {
- FlatNode fnext=fn.getNext(i);
- tovisit.add(fnext);
- }
- }
- }
+ if ((fn.numPrev()>0)&&atomictable.get(fn.getPrev(0)).intValue()==0) {
+ //atomic node, start with new set
+ ttofn=new Hashtable<TempDescriptor, Set<TempFlatPair>>();
+ } else {
+ ttofn=doMerge(fn, tmptofnset);
+ switch(fn.kind()) {
+ case FKind.FlatGlobalConvNode: {
+ FlatGlobalConvNode fgcn=(FlatGlobalConvNode)fn;
+ if (lb==fgcn.getLocality()&&
+ fgcn.getMakePtr()) {
+ TempDescriptor[] writes=fn.writesTemps();
+ for(int i=0; i<writes.length; i++) {
+ TempDescriptor wtmp=writes[i];
+ HashSet<TempFlatPair> set=new HashSet<TempFlatPair>();
+ set.add(new TempFlatPair(wtmp, fn));
+ ttofn.put(wtmp, set);
+ }
+ }
+ break;
+ }
+
+ case FKind.FlatFieldNode:
+ case FKind.FlatElementNode: {
+ TempDescriptor[] writes=fn.writesTemps();
+ for(int i=0; i<writes.length; i++) {
+ TempDescriptor wtmp=writes[i];
+ HashSet<TempFlatPair> set=new HashSet<TempFlatPair>();
+ set.add(new TempFlatPair(wtmp, fn));
+ ttofn.put(wtmp, set);
+ }
+ break;
+ }
+
+ case FKind.FlatCall:
+ case FKind.FlatMethod: {
+ TempDescriptor[] writes=fn.writesTemps();
+ for(int i=0; i<writes.length; i++) {
+ TempDescriptor wtmp=writes[i];
+ HashSet<TempFlatPair> set=new HashSet<TempFlatPair>();
+ set.add(new TempFlatPair(wtmp, fn));
+ ttofn.put(wtmp, set);
+ }
+ break;
+ }
+
+ case FKind.FlatCastNode:
+ case FKind.FlatOpNode:
+ if (fn.kind()==FKind.FlatCastNode) {
+ FlatCastNode fcn=(FlatCastNode)fn;
+ if (fcn.getDst().getType().isPtr()) {
+ HashSet<TempFlatPair> set=new HashSet<TempFlatPair>();
+ if (ttofn.containsKey(fcn.getSrc()))
+ set.addAll(ttofn.get(fcn.getSrc()));
+ if (normalassign)
+ set.add(new TempFlatPair(fcn.getDst(), fn));
+ ttofn.put(fcn.getDst(), set);
+ break;
+ }
+ } else if (fn.kind()==FKind.FlatOpNode) {
+ FlatOpNode fon=(FlatOpNode)fn;
+ if (fon.getOp().getOp()==Operation.ASSIGN&&fon.getDest().getType().isPtr()) {
+ HashSet<TempFlatPair> set=new HashSet<TempFlatPair>();
+ if (ttofn.containsKey(fon.getLeft()))
+ set.addAll(ttofn.get(fon.getLeft()));
+ if (normalassign)
+ set.add(new TempFlatPair(fon.getDest(), fn));
+ ttofn.put(fon.getDest(), set);
+ break;
+ }
+ }
+
+ default:
+ //Do kill computation
+ TempDescriptor[] writes=fn.writesTemps();
+ for(int i=0; i<writes.length; i++) {
+ TempDescriptor wtmp=writes[i];
+ ttofn.remove(writes[i]);
+ }
+ }
+ }
+ if (ttofn!=null) {
+ if (!tmptofnset.containsKey(fn)||
+ !tmptofnset.get(fn).equals(ttofn)) {
+ //enqueue nodes to process
+ tmptofnset.put(fn, ttofn);
+ for(int i=0; i<fn.numNext(); i++) {
+ FlatNode fnext=fn.getNext(i);
+ tovisit.add(fnext);
+ }
+ }
+ }
}
}
return tmptofnset;
FlatNode fn=fnit.next();
Hashtable<FlatNode, Integer> atomictable=locality.getAtomic(lb);
if (atomictable.get(fn).intValue()>0) {
- Set<TempDescriptor> oldtemp=oldtemps.get(fn);
- switch (fn.kind()) {
- case FKind.FlatSetFieldNode:
- FlatSetFieldNode fsfn=(FlatSetFieldNode) fn;
- if (oldtemp.contains(fsfn.getDst()))
- fields.add(fsfn.getField());
- break;
-
- case FKind.FlatSetElementNode:
- FlatSetElementNode fsen=(FlatSetElementNode) fn;
- if (oldtemp.contains(fsen.getDst()))
- arrays.add(fsen.getDst().getType());
- break;
-
- default:
- }
+ Set<TempDescriptor> oldtemp=oldtemps.get(fn);
+ switch (fn.kind()) {
+ case FKind.FlatSetFieldNode:
+ FlatSetFieldNode fsfn=(FlatSetFieldNode) fn;
+ if (oldtemp.contains(fsfn.getDst()))
+ fields.add(fsfn.getField());
+ break;
+
+ case FKind.FlatSetElementNode:
+ FlatSetElementNode fsen=(FlatSetElementNode) fn;
+ if (oldtemp.contains(fsen.getDst()))
+ arrays.add(fsen.getDst().getType());
+ break;
+
+ default:
+ }
}
}
}
FlatNode fn=tovisit.iterator().next();
tovisit.remove(fn);
for(int i=0; i<fn.numNext(); i++) {
- FlatNode fnext=fn.getNext(i);
- if (!discovered.contains(fnext)) {
- discovered.add(fnext);
- tovisit.add(fnext);
- }
+ FlatNode fnext=fn.getNext(i);
+ if (!discovered.contains(fnext)) {
+ discovered.add(fnext);
+ tovisit.add(fnext);
+ }
}
HashSet<TempDescriptor> oldtemps=null;
if (atomictable.get(fn).intValue()!=0) {
- if ((fn.numPrev()>0)&&atomictable.get(fn.getPrev(0)).intValue()==0) {
- //Everything live is old
- Set<TempDescriptor> lives=livetemps.get(fn);
- oldtemps=new HashSet<TempDescriptor>();
-
- for(Iterator<TempDescriptor> it=lives.iterator(); it.hasNext(); ) {
- TempDescriptor tmp=it.next();
- if (tmp.getType().isPtr()) {
- oldtemps.add(tmp);
- }
- }
- } else {
- oldtemps=new HashSet<TempDescriptor>();
- //Compute union of old temporaries
- for(int i=0; i<fn.numPrev(); i++) {
- Set<TempDescriptor> pset=fntooldtmp.get(fn.getPrev(i));
- if (pset!=null)
- oldtemps.addAll(pset);
- }
-
- switch (fn.kind()) {
- case FKind.FlatNew:
- oldtemps.removeAll(Arrays.asList(fn.readsTemps()));
- break;
-
- case FKind.FlatOpNode:
- case FKind.FlatCastNode:
- if (fn.kind()==FKind.FlatCastNode) {
- FlatCastNode fcn=(FlatCastNode)fn;
- if (fcn.getDst().getType().isPtr()) {
- if (oldtemps.contains(fcn.getSrc()))
- oldtemps.add(fcn.getDst());
- else
- oldtemps.remove(fcn.getDst());
- break;
- }
- } else if (fn.kind()==FKind.FlatOpNode) {
- FlatOpNode fon=(FlatOpNode)fn;
- if (fon.getOp().getOp()==Operation.ASSIGN&&fon.getDest().getType().isPtr()) {
- if (oldtemps.contains(fon.getLeft()))
- oldtemps.add(fon.getDest());
- else
- oldtemps.remove(fon.getDest());
- break;
- }
- }
-
- default: {
- TempDescriptor[] writes=fn.writesTemps();
- for(int i=0; i<writes.length; i++) {
- TempDescriptor wtemp=writes[i];
- if (wtemp.getType().isPtr())
- oldtemps.add(wtemp);
- }
- }
- }
- }
+ if ((fn.numPrev()>0)&&atomictable.get(fn.getPrev(0)).intValue()==0) {
+ //Everything live is old
+ Set<TempDescriptor> lives=livetemps.get(fn);
+ oldtemps=new HashSet<TempDescriptor>();
+
+ for(Iterator<TempDescriptor> it=lives.iterator(); it.hasNext(); ) {
+ TempDescriptor tmp=it.next();
+ if (tmp.getType().isPtr()) {
+ oldtemps.add(tmp);
+ }
+ }
+ } else {
+ oldtemps=new HashSet<TempDescriptor>();
+ //Compute union of old temporaries
+ for(int i=0; i<fn.numPrev(); i++) {
+ Set<TempDescriptor> pset=fntooldtmp.get(fn.getPrev(i));
+ if (pset!=null)
+ oldtemps.addAll(pset);
+ }
+
+ switch (fn.kind()) {
+ case FKind.FlatNew:
+ oldtemps.removeAll(Arrays.asList(fn.readsTemps()));
+ break;
+
+ case FKind.FlatOpNode:
+ case FKind.FlatCastNode:
+ if (fn.kind()==FKind.FlatCastNode) {
+ FlatCastNode fcn=(FlatCastNode)fn;
+ if (fcn.getDst().getType().isPtr()) {
+ if (oldtemps.contains(fcn.getSrc()))
+ oldtemps.add(fcn.getDst());
+ else
+ oldtemps.remove(fcn.getDst());
+ break;
+ }
+ } else if (fn.kind()==FKind.FlatOpNode) {
+ FlatOpNode fon=(FlatOpNode)fn;
+ if (fon.getOp().getOp()==Operation.ASSIGN&&fon.getDest().getType().isPtr()) {
+ if (oldtemps.contains(fon.getLeft()))
+ oldtemps.add(fon.getDest());
+ else
+ oldtemps.remove(fon.getDest());
+ break;
+ }
+ }
+
+ default: {
+ TempDescriptor[] writes=fn.writesTemps();
+ for(int i=0; i<writes.length; i++) {
+ TempDescriptor wtemp=writes[i];
+ if (wtemp.getType().isPtr())
+ oldtemps.add(wtemp);
+ }
+ }
+ }
+ }
}
if (oldtemps!=null) {
- if (!fntooldtmp.containsKey(fn)||!fntooldtmp.get(fn).equals(oldtemps)) {
- fntooldtmp.put(fn, oldtemps);
- //propagate changes
- for(int i=0; i<fn.numNext(); i++) {
- FlatNode fnext=fn.getNext(i);
- tovisit.add(fnext);
- }
- }
+ if (!fntooldtmp.containsKey(fn)||!fntooldtmp.get(fn).equals(oldtemps)) {
+ fntooldtmp.put(fn, oldtemps);
+ //propagate changes
+ for(int i=0; i<fn.numNext(); i++) {
+ FlatNode fnext=fn.getNext(i);
+ tovisit.add(fnext);
+ }
+ }
}
}
return fntooldtmp;
LocalityBinding lb=bindit.next();
//Don't need to do conversion if it is already atomic
if (lb.isAtomic())
- continue;
+ continue;
converttoPtr(lb);
converttoOid(lb);
}
if (!isatomic&&fn.kind()==FKind.FlatAtomicExitNode
&&!nodetoconvs.containsKey(fn)) {
- nodetoconvs.put(fn, new HashSet<TempDescriptor>());
- nodetoconvs2.put(fn, new HashSet<TempDescriptor>());
+ nodetoconvs.put(fn, new HashSet<TempDescriptor>());
+ nodetoconvs2.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);
- nodetoconvs2.get(fn).add(tnp.getTemp()); //have to hide cached copies from gc -- add unused converted temps
- } else
- tempset.add(tnp);
- } else
- tempset.add(tnp);
- }
+ FlatNode fnprev=fn.getPrev(i);
+ if (!nodetotnpair.containsKey(fnprev))
+ continue;
+
+ Set<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);
+ nodetoconvs2.get(fn).add(tnp.getTemp()); //have to hide cached copies from gc -- add unused converted temps
+ } else
+ tempset.add(tnp);
+ } else
+ tempset.add(tnp);
+ }
}
if (isatomic) {
- /* If this is in an atomic block, record temps that
- * are written to.*/
-
- /* NOTE: If this compiler is changed to maintain
- * OID/Ptr's in variables, then we need to use all
- * global temps that could be read and not just the
- * ones converted by globalconvnode*/
-
- if (fn.kind()!=FKind.FlatGlobalConvNode||
- ((FlatGlobalConvNode)fn).getLocality()==lb) {
- /*If globalconvnode, make sure we have the right
- * locality. */
- for(Iterator<TempDescriptor> writeit=writes.iterator(); writeit.hasNext(); ) {
- TempDescriptor wrtmp=writeit.next();
- if (state.SINGLETM) {
- if (wrtmp.getType().isPtr()&&
- (nodetemptab.get(wrtmp)!=LocalityAnalysis.SCRATCH)) {
- TempNodePair tnp=new TempNodePair(wrtmp);
- tempset.add(tnp);
- }
- } else if (nodetemptab.get(wrtmp)==LocalityAnalysis.GLOBAL) {
- TempNodePair tnp=new TempNodePair(wrtmp);
- tempset.add(tnp);
- }
- }
- }
+ /* If this is in an atomic block, record temps that
+ * are written to.*/
+
+ /* NOTE: If this compiler is changed to maintain
+ * OID/Ptr's in variables, then we need to use all
+ * global temps that could be read and not just the
+ * ones converted by globalconvnode*/
+
+ if (fn.kind()!=FKind.FlatGlobalConvNode||
+ ((FlatGlobalConvNode)fn).getLocality()==lb) {
+ /*If globalconvnode, make sure we have the right
+ * locality. */
+ for(Iterator<TempDescriptor> writeit=writes.iterator(); writeit.hasNext(); ) {
+ TempDescriptor wrtmp=writeit.next();
+ if (state.SINGLETM) {
+ if (wrtmp.getType().isPtr()&&
+ (nodetemptab.get(wrtmp)!=LocalityAnalysis.SCRATCH)) {
+ TempNodePair tnp=new TempNodePair(wrtmp);
+ tempset.add(tnp);
+ }
+ } else if (nodetemptab.get(wrtmp)==LocalityAnalysis.GLOBAL) {
+ TempNodePair tnp=new TempNodePair(wrtmp);
+ tempset.add(tnp);
+ }
+ }
+ }
}
if (!nodetotnpair.containsKey(fn)||!nodetotnpair.get(fn).equals(tempset)) {
- //changes to set, so enqueue next nodes
- nodetotnpair.put(fn, tempset); //update set
- for(int i=0; i<fn.numNext(); i++) {
- toprocess.add(fn.getNext(i));
- }
+ //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));
+ }
}
}
//Place Convert to Oid nodes
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=nodetoconvs2.get(fn);
- for(Iterator<TempDescriptor> tempit=tempset.iterator(); tempit.hasNext(); ) {
- TempDescriptor tmpd=tempit.next();
- FlatGlobalConvNode fgcn=new FlatGlobalConvNode(tmpd, lb, false, nodetoconvs.get(fn).contains(tmpd));
-
- //This loop makes sure that we have accurate atomic information for the new node
- for(Iterator<LocalityBinding> lbit=locality.getMethodBindings(lb.getMethod()).iterator(); lbit.hasNext(); ) {
- LocalityBinding fixlb=lbit.next();
- locality.getAtomic(fixlb).put(fgcn, locality.getAtomic(fixlb).get(fn.getPrev(0)));
- locality.getNodeTempInfo(fixlb).put(fgcn, (Hashtable<TempDescriptor, Integer>)locality.getNodeTempInfo(fixlb).get(fn).clone());
- }
-
- fgcn.setAtomicEnter(((FlatAtomicExitNode)fn).getAtomicEnter());
-
- FlatNode[] prevarray=new FlatNode[fn.numPrev()];
- for(int i=0; i<fn.numPrev(); i++) {
- FlatNode fnprev=fn.getPrev(i);
- prevarray[i]=fnprev;
- }
- for(int i=0; i<prevarray.length; i++) {
- for(int j=0; j<prevarray[i].numNext(); j++) {
- if (prevarray[i].getNext(j)==fn) {
- //found index, change node
- prevarray[i].setNext(j, fgcn);
- break;
- }
- }
- }
- fgcn.addNext(fn);
- }
+ //sanity check
+ assert(fn.kind()==FKind.FlatAtomicExitNode);
+ //insert calls here...
+ Set<TempDescriptor> tempset=nodetoconvs2.get(fn);
+ for(Iterator<TempDescriptor> tempit=tempset.iterator(); tempit.hasNext(); ) {
+ TempDescriptor tmpd=tempit.next();
+ FlatGlobalConvNode fgcn=new FlatGlobalConvNode(tmpd, lb, false, nodetoconvs.get(fn).contains(tmpd));
+
+ //This loop makes sure that we have accurate atomic information for the new node
+ for(Iterator<LocalityBinding> lbit=locality.getMethodBindings(lb.getMethod()).iterator(); lbit.hasNext(); ) {
+ LocalityBinding fixlb=lbit.next();
+ locality.getAtomic(fixlb).put(fgcn, locality.getAtomic(fixlb).get(fn.getPrev(0)));
+ locality.getNodeTempInfo(fixlb).put(fgcn, (Hashtable<TempDescriptor, Integer>)locality.getNodeTempInfo(fixlb).get(fn).clone());
+ }
+
+ fgcn.setAtomicEnter(((FlatAtomicExitNode)fn).getAtomicEnter());
+
+ FlatNode[] prevarray=new FlatNode[fn.numPrev()];
+ for(int i=0; i<fn.numPrev(); i++) {
+ FlatNode fnprev=fn.getPrev(i);
+ prevarray[i]=fnprev;
+ }
+ for(int i=0; i<prevarray.length; i++) {
+ for(int j=0; j<prevarray[i].numNext(); j++) {
+ if (prevarray[i].getNext(j)==fn) {
+ //found index, change node
+ prevarray[i].setNext(j, fgcn);
+ break;
+ }
+ }
+ }
+ fgcn.addNext(fn);
+ }
}
}
}
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);
- if (state.SINGLETM) {
- TempDescriptor [] readtemps=fn.readsTemps();
- for(int i=0; i<readtemps.length; i++) {
- TempDescriptor tmp=readtemps[i];
- if (tmp.getType().isPtr()&&
- pretemptab.get(tmp).intValue()!=LocalityAnalysis.SCRATCH) {
- transtemps.add(tmp);
- }
- }
- } else {
- 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));
- }
+ //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);
+ if (state.SINGLETM) {
+ TempDescriptor [] readtemps=fn.readsTemps();
+ for(int i=0; i<readtemps.length; i++) {
+ TempDescriptor tmp=readtemps[i];
+ if (tmp.getType().isPtr()&&
+ pretemptab.get(tmp).intValue()!=LocalityAnalysis.SCRATCH) {
+ transtemps.add(tmp);
+ }
+ }
+ } else {
+ 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();
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);
- fgcn.setAtomicEnter((FlatAtomicEnterNode)fn);
- //This loop makes sure that we have accurate atomic information for the new node
- for(Iterator<LocalityBinding> lbit=locality.getMethodBindings(lb.getMethod()).iterator(); lbit.hasNext(); ) {
- LocalityBinding fixlb=lbit.next();
- locality.getAtomic(fixlb).put(fgcn, locality.getAtomic(fixlb).get(fn));
- locality.getNodeTempInfo(fixlb).put(fgcn, (Hashtable<TempDescriptor, Integer>)locality.getNodeTempInfo(fixlb).get(fn).clone());
- }
- fgcn.addNext(fn.getNext(0));
- fn.setNext(0, fgcn);
- }
+ //sanity check
+ assert(fn.kind()==FKind.FlatAtomicEnterNode);
+
+ //insert calls here...
+ Set<TempDescriptor> tempset=nodetotranstemps.get(fn);
+ for(Iterator<TempDescriptor> tempit=tempset.iterator(); tempit.hasNext(); ) {
+ FlatGlobalConvNode fgcn=new FlatGlobalConvNode(tempit.next(), lb, true);
+ fgcn.setAtomicEnter((FlatAtomicEnterNode)fn);
+ //This loop makes sure that we have accurate atomic information for the new node
+ for(Iterator<LocalityBinding> lbit=locality.getMethodBindings(lb.getMethod()).iterator(); lbit.hasNext(); ) {
+ LocalityBinding fixlb=lbit.next();
+ locality.getAtomic(fixlb).put(fgcn, locality.getAtomic(fixlb).get(fn));
+ locality.getNodeTempInfo(fixlb).put(fgcn, (Hashtable<TempDescriptor, Integer>)locality.getNodeTempInfo(fixlb).get(fn).clone());
+ }
+ fgcn.addNext(fn.getNext(0));
+ fn.setNext(0, fgcn);
+ }
}
}
}
if (state.DSM&&fc.getThis()!=null) {
Integer thistype=currtable.get(fc.getThis());
if (thistype==null)
- thistype=EITHER;
+ thistype=EITHER;
lb.setGlobalThis(thistype);
} else if (state.SINGLETM&&fc.getThis()!=null) {
Integer thistype=currtable.get(fc.getThis());
if (thistype==null)
- thistype=STMEITHER;
+ thistype=STMEITHER;
lb.setGlobalThis(thistype);
}
// else
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):(state.DSM?EITHER:STMEITHER);
- Integer newint=state.DSM?merge(tmpint, oldint):mergestm(tmpint, oldint);
- currtable.put(temp, newint);
+ TempDescriptor temp=tempit.next();
+ Integer tmpint=prevtable.get(temp);
+ Integer oldint=currtable.containsKey(temp)?currtable.get(temp):(state.DSM?EITHER:STMEITHER);
+ Integer newint=state.DSM?merge(tmpint, oldint):mergestm(tmpint, oldint);
+ currtable.put(temp, newint);
}
}
return currtable;
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));
+ FlatAtomicEnterNode faen=faenit.next();
+ set.addAll(table.get(faen));
}
return set;
}
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);
+ 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);
+ lbit.remove();
+ classtolb.get(lb.getMethod().getClassDesc()).remove(lb);
+ methodtolb.get(lb.getMethod()).remove(lb);
}
}
}
.hasNext(); ) {
MethodDescriptor md=(MethodDescriptor) methodit.next();
if (md.numParameters()!=1||!md.getModifiers().isStatic()||!md.getParamType(0).getSymbol().equals(TypeUtil.ThreadClass))
- continue;
+ continue;
return md;
}
throw new Error("Can't find Thread.run");
Hashtable<FlatNode, Integer> atomictable=new Hashtable<FlatNode, Integer>();
calldep.remove(lb);
try {
- computeCallsFlagsSTM(md, lb, temptable, atomictable);
+ computeCallsFlagsSTM(md, lb, temptable, atomictable);
} catch (Error e) {
- System.out.println("Error in "+md+" context "+lb);
- e.printStackTrace();
- System.exit(-1);
+ System.out.println("Error in "+md+" context "+lb);
+ e.printStackTrace();
+ System.exit(-1);
}
temptab.put(lb, temptable);
atomictab.put(lb, atomictable);
if (md.getReturnType()!=null&&md.getReturnType().isPtr()&&!returnglobal.equals(lb.getGlobalReturn())) {
- //return type is more precise now
- //rerun everything that call us
- lbtovisit.addAll(dependence.get(lb));
+ //return type is more precise now
+ //rerun everything that call us
+ lbtovisit.addAll(dependence.get(lb));
}
}
}
atomictable.put(fm, lb.isAtomic()?1:0);
int offset=md.isStatic()?0:1;
if (!md.isStatic()) {
- table.put(fm.getParameter(0), lb.getGlobalThis());
+ table.put(fm.getParameter(0), lb.getGlobalThis());
}
for(int i=offset; i<fm.numParameters(); i++) {
- TempDescriptor temp=fm.getParameter(i);
- Integer b=lb.isGlobal(i-offset);
- if (b!=null)
- table.put(temp,b);
+ TempDescriptor temp=fm.getParameter(i);
+ Integer b=lb.isGlobal(i-offset);
+ if (b!=null)
+ table.put(temp,b);
}
}
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();
- if (!liveset.contains(temp))
- continue;
- Integer tmpint=prevtable.get(temp);
- Integer oldint=currtable.containsKey(temp)?currtable.get(temp):STMEITHER;
- Integer newint=mergestm(tmpint, oldint);
- currtable.put(temp, newint);
- }
+ FlatNode prevnode=fn.getPrev(i);
+ if (atomictable.containsKey(prevnode)) {
+ atomicstate=atomictable.get(prevnode).intValue();
+ }
+ if (!temptable.containsKey(prevnode))
+ continue;
+ Hashtable<TempDescriptor, Integer> prevtable=temptable.get(prevnode);
+ for(Iterator<TempDescriptor> tempit=prevtable.keySet().iterator(); tempit.hasNext(); ) {
+ TempDescriptor temp=tempit.next();
+ if (!liveset.contains(temp))
+ continue;
+ Integer tmpint=prevtable.get(temp);
+ Integer oldint=currtable.containsKey(temp)?currtable.get(temp):STMEITHER;
+ Integer newint=mergestm(tmpint, oldint);
+ currtable.put(temp, newint);
+ }
}
atomictable.put(fn, atomicstate);
// Process this node
switch(fn.kind()) {
case FKind.FlatAtomicEnterNode:
- processAtomicEnterNode((FlatAtomicEnterNode)fn, atomictable);
- if (!lb.isAtomic())
- lb.setHasAtomic();
- break;
+ processAtomicEnterNode((FlatAtomicEnterNode)fn, atomictable);
+ if (!lb.isAtomic())
+ lb.setHasAtomic();
+ break;
case FKind.FlatAtomicExitNode:
- processAtomicExitNode((FlatAtomicExitNode)fn, atomictable);
- break;
+ processAtomicExitNode((FlatAtomicExitNode)fn, atomictable);
+ break;
case FKind.FlatCall:
- processCallNodeSTM(lb, (FlatCall)fn, isAtomic(atomictable, fn), currtable, temptable.get(fn));
- break;
+ processCallNodeSTM(lb, (FlatCall)fn, isAtomic(atomictable, fn), currtable, temptable.get(fn));
+ break;
case FKind.FlatNew:
- processNewSTM(lb, (FlatNew) fn, currtable);
- break;
+ processNewSTM(lb, (FlatNew) fn, currtable);
+ break;
case FKind.FlatFieldNode:
- processFieldNodeSTM(lb, (FlatFieldNode) fn, currtable);
- break;
+ processFieldNodeSTM(lb, (FlatFieldNode) fn, currtable);
+ break;
case FKind.FlatSetFieldNode:
- processSetFieldNodeSTM(lb, (FlatSetFieldNode) fn, currtable);
- break;
+ processSetFieldNodeSTM(lb, (FlatSetFieldNode) fn, currtable);
+ break;
case FKind.FlatSetElementNode:
- processSetElementNodeSTM(lb, (FlatSetElementNode) fn, currtable);
- break;
+ processSetElementNodeSTM(lb, (FlatSetElementNode) fn, currtable);
+ break;
case FKind.FlatElementNode:
- processElementNodeSTM(lb, (FlatElementNode) fn, currtable);
- break;
+ processElementNodeSTM(lb, (FlatElementNode) fn, currtable);
+ break;
case FKind.FlatOpNode:
- processOpNodeSTM(lb, (FlatOpNode)fn, currtable);
- break;
+ processOpNodeSTM(lb, (FlatOpNode)fn, currtable);
+ break;
case FKind.FlatCastNode:
- processCastNodeSTM((FlatCastNode)fn, currtable);
- break;
+ processCastNodeSTM((FlatCastNode)fn, currtable);
+ break;
case FKind.FlatReturnNode:
- processReturnNodeSTM(lb, (FlatReturnNode)fn, currtable);
- break;
+ processReturnNodeSTM(lb, (FlatReturnNode)fn, currtable);
+ break;
case FKind.FlatLiteralNode:
- processLiteralNodeSTM((FlatLiteralNode)fn, currtable);
- break;
+ processLiteralNodeSTM((FlatLiteralNode)fn, currtable);
+ break;
case FKind.FlatMethod:
case FKind.FlatOffsetNode:
case FKind.FlatNop:
case FKind.FlatPrefetchNode:
case FKind.FlatExit:
- //No action needed for these
- break;
+ //No action needed for these
+ break;
case FKind.FlatFlagActionNode:
case FKind.FlatCheckNode:
case FKind.FlatTagDeclaration:
- throw new Error("Incompatible with tasks!");
+ throw new Error("Incompatible with tasks!");
default:
- throw new Error("In finding fn.kind()= " + fn.kind());
+ throw new Error("In finding fn.kind()= " + fn.kind());
}
Hashtable<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));
- }
+ // Update table for this node
+ temptable.put(fn, currtable);
+ for(int i=0; i<fn.numNext(); i++) {
+ tovisit.add(fn.getNext(i));
+ }
}
}
}
if (nodemd.getClassDesc().getSymbol().equals(TypeUtil.ThreadClass)&&
nodemd.getSymbol().equals("start")&&!nodemd.getModifiers().isStatic()&&
nodemd.numParameters()==0) {
- assert(nodemd.getModifiers().isNative());
-
- MethodDescriptor runmd=null;
- for(Iterator methodit=nodemd.getClassDesc().getMethodTable().getSet("staticStart").iterator(); methodit.hasNext(); ) {
- MethodDescriptor md=(MethodDescriptor) methodit.next();
- if (md.numParameters()!=1||!md.getModifiers().isStatic()||!md.getParamType(0).getSymbol().equals(TypeUtil.ThreadClass))
- 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");
+ assert(nodemd.getModifiers().isNative());
+
+ MethodDescriptor runmd=null;
+ for(Iterator methodit=nodemd.getClassDesc().getMethodTable().getSet("staticStart").iterator(); methodit.hasNext(); ) {
+ MethodDescriptor md=(MethodDescriptor) methodit.next();
+ if (md.numParameters()!=1||!md.getModifiers().isStatic()||!md.getParamType(0).getSymbol().equals(TypeUtil.ThreadClass))
+ 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");
}
}
LocalityBinding lb=new LocalityBinding(md, isatomic);
if (isnative&&isatomic) {
- System.out.println("Don't call native methods in atomic blocks!"+currlb.getMethod());
+ System.out.println("Don't call native methods in atomic blocks!"+currlb.getMethod());
}
if (runmethodset==null||!runmethodset.contains(md)) {
- for(int i=0; i<fc.numArgs(); i++) {
- TempDescriptor arg=fc.getArg(i);
- if (currtable.containsKey(arg))
- lb.setGlobal(i,currtable.get(arg));
- }
- if (fc.getThis()!=null) {
- Integer thistype=currtable.get(fc.getThis());
- if (thistype==null)
- thistype=STMEITHER;
-
- if(thistype.equals(STMCONFLICT))
- throw new Error("Using type that can be either normal or scratch in context:\n"+currlb.getExplanation());
- lb.setGlobalThis(thistype);
- }
+ for(int i=0; i<fc.numArgs(); i++) {
+ TempDescriptor arg=fc.getArg(i);
+ if (currtable.containsKey(arg))
+ lb.setGlobal(i,currtable.get(arg));
+ }
+ if (fc.getThis()!=null) {
+ Integer thistype=currtable.get(fc.getThis());
+ if (thistype==null)
+ thistype=STMEITHER;
+
+ if(thistype.equals(STMCONFLICT))
+ throw new Error("Using type that can be either normal or scratch in context:\n"+currlb.getExplanation());
+ lb.setGlobalThis(thistype);
+ }
} else {
- Integer thistype=currtable.get(fc.getThis());
- if (!thistype.equals(NORMAL)&&!thistype.equals(STMEITHER)) {
- throw new Error("Called start on possible scratch object"+thistype);
- }
- lb.setGlobal(0,currtable.get(fc.getThis()));
+ Integer thistype=currtable.get(fc.getThis());
+ if (!thistype.equals(NORMAL)&&!thistype.equals(STMEITHER)) {
+ throw new Error("Called start on possible scratch object"+thistype);
+ }
+ lb.setGlobal(0,currtable.get(fc.getThis()));
}
//lb is built
if (!discovered.containsKey(lb)) {
- if (isnative) {
- if (nodemd.getReturnType()!=null&&nodemd.getReturnType().isPtr())
- lb.setGlobalReturn(NORMAL);
- } else
- lb.setGlobalReturn(STMEITHER);
-
- lb.setParent(currlb);
- lbtovisit.add(lb);
- System.out.println("New lb:"+lb);
- discovered.put(lb, lb);
- if (!classtolb.containsKey(lb.getMethod().getClassDesc()))
- classtolb.put(lb.getMethod().getClassDesc(), new HashSet<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);
+ if (isnative) {
+ if (nodemd.getReturnType()!=null&&nodemd.getReturnType().isPtr())
+ lb.setGlobalReturn(NORMAL);
+ } else
+ lb.setGlobalReturn(STMEITHER);
+
+ lb.setParent(currlb);
+ lbtovisit.add(lb);
+ System.out.println("New lb:"+lb);
+ discovered.put(lb, lb);
+ if (!classtolb.containsKey(lb.getMethod().getClassDesc()))
+ classtolb.put(lb.getMethod().getClassDesc(), new HashSet<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);
+ lb=discovered.get(lb);
Integer returnval=lb.getGlobalReturn();
currreturnval=mergestm(returnval, currreturnval);
if (!dependence.containsKey(lb))
- dependence.put(lb, new HashSet<LocalityBinding>());
+ dependence.put(lb, new HashSet<LocalityBinding>());
dependence.get(lb).add(currlb);
if (!calldep.containsKey(currlb))
- calldep.put(currlb, new HashSet<LocalityBinding>());
+ calldep.put(currlb, new HashSet<LocalityBinding>());
calldep.get(currlb).add(lb);
}
if (fc.getReturnTemp()!=null&&fc.getReturnTemp().getType().isPtr()) {
System.out.println(fsfn);
if (dsttype.equals(SCRATCH)) {
if (!(srctype.equals(SCRATCH)||srctype.equals(STMEITHER)))
- throw new Error("Writing possible normal reference to scratch object in context: \n"+lb.getExplanation());
+ throw new Error("Writing possible normal reference to scratch object in context: \n"+lb.getExplanation());
} else if (dsttype.equals(NORMAL)) {
//okay to store primitives in global object
if (!(srctype.equals(NORMAL)||srctype.equals(STMEITHER)))
- throw new Error("Writing possible scratch reference to normal object in context:\n"+lb.getExplanation()+" for FlatFieldNode "+fsfn);
+ throw new Error("Writing possible scratch reference to normal object in context:\n"+lb.getExplanation()+" for FlatFieldNode "+fsfn);
} else if (dsttype.equals(STMEITHER)) {
if (srctype.equals(STMCONFLICT))
- throw new Error("Using reference that could be scratch or normal in context:\n"+lb.getExplanation());
+ throw new Error("Using reference that could be scratch or normal in context:\n"+lb.getExplanation());
} else if (dsttype.equals(STMCONFLICT)) {
throw new Error("Access to object that could be either scratch or normal in context:\n"+lb.getExplanation());
}
if (dsttype.equals(SCRATCH)) {
if (!(srctype.equals(SCRATCH)||srctype.equals(STMEITHER)))
- throw new Error("Writing possible normal reference to scratch object in context:\n"+lb.getExplanation()+fsen);
+ throw new Error("Writing possible normal reference to scratch object in context:\n"+lb.getExplanation()+fsen);
} else if (dsttype.equals(NORMAL)) {
if (!(srctype.equals(NORMAL)||srctype.equals(STMEITHER)))
- throw new Error("Writing possible scratch reference to normal object in context:\n"+lb.getExplanation());
+ throw new Error("Writing possible scratch reference to normal object in context:\n"+lb.getExplanation());
} else if (dsttype.equals(STMEITHER)) {
if (srctype.equals(STMCONFLICT))
- throw new Error("Using reference that could be scratch or normal in context:\n"+lb.getExplanation());
+ throw new Error("Using reference that could be scratch or normal in context:\n"+lb.getExplanation());
} else if (dsttype.equals(STMCONFLICT)) {
throw new Error("Access to object that could be either normal or scratch in context:\n"+lb.getExplanation());
}
lbtovisit.add(lbexecute);
discovered.put(lbexecute, lbexecute);
if (!classtolb.containsKey(lbexecute.getMethod().getClassDesc()))
- classtolb.put(lbexecute.getMethod().getClassDesc(), new HashSet<LocalityBinding>());
+ classtolb.put(lbexecute.getMethod().getClassDesc(), new HashSet<LocalityBinding>());
classtolb.get(lbexecute.getMethod().getClassDesc()).add(lbexecute);
if (!methodtolb.containsKey(lbexecute.getMethod()))
- methodtolb.put(lbexecute.getMethod(), new HashSet<LocalityBinding>());
+ methodtolb.put(lbexecute.getMethod(), new HashSet<LocalityBinding>());
methodtolb.get(lbexecute.getMethod()).add(lbexecute);
}
Hashtable<FlatNode, Integer> atomictable=new Hashtable<FlatNode, Integer>();
calldep.remove(lb);
try {
- computeCallsFlags(md, lb, temptable, atomictable);
+ computeCallsFlags(md, lb, temptable, atomictable);
} catch (Error e) {
- System.out.println("Error in "+md+" context "+lb);
- e.printStackTrace();
- System.exit(-1);
+ System.out.println("Error in "+md+" context "+lb);
+ e.printStackTrace();
+ System.exit(-1);
}
temptab.put(lb, temptable);
atomictab.put(lb, atomictable);
if (md.getReturnType()!=null&&!returnglobal.equals(lb.getGlobalReturn())) {
- //return type is more precise now
- //rerun everything that call us
- lbtovisit.addAll(dependence.get(lb));
+ //return type is more precise now
+ //rerun everything that call us
+ lbtovisit.addAll(dependence.get(lb));
}
}
}
atomictable.put(fm, lb.isAtomic()?1:0);
int offset=md.isStatic()?0:1;
if (!md.isStatic()) {
- table.put(fm.getParameter(0), lb.getGlobalThis());
+ table.put(fm.getParameter(0), lb.getGlobalThis());
}
for(int i=offset; i<fm.numParameters(); i++) {
- TempDescriptor temp=fm.getParameter(i);
- Integer b=lb.isGlobal(i-offset);
- table.put(temp,b);
+ TempDescriptor temp=fm.getParameter(i);
+ Integer b=lb.isGlobal(i-offset);
+ table.put(temp,b);
}
}
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);
- }
+ 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;
+ processAtomicEnterNode((FlatAtomicEnterNode)fn, atomictable);
+ if (!lb.isAtomic())
+ lb.setHasAtomic();
+ break;
case FKind.FlatAtomicExitNode:
- processAtomicExitNode((FlatAtomicExitNode)fn, atomictable);
- break;
+ processAtomicExitNode((FlatAtomicExitNode)fn, atomictable);
+ break;
case FKind.FlatCall:
- processCallNode(lb, (FlatCall)fn, currtable, isAtomic(atomictable, fn), temptable.get(fn));
- break;
+ processCallNode(lb, (FlatCall)fn, currtable, isAtomic(atomictable, fn), temptable.get(fn));
+ break;
case FKind.FlatFieldNode:
- processFieldNode(lb, (FlatFieldNode)fn, isAtomic(atomictable, fn), currtable);
- break;
+ processFieldNode(lb, (FlatFieldNode)fn, isAtomic(atomictable, fn), currtable);
+ break;
case FKind.FlatSetFieldNode:
- processSetFieldNode(lb, (FlatSetFieldNode)fn, isAtomic(atomictable,fn), currtable);
- break;
+ processSetFieldNode(lb, (FlatSetFieldNode)fn, isAtomic(atomictable,fn), currtable);
+ break;
case FKind.FlatNew:
- processNew(lb, (FlatNew)fn, isAtomic(atomictable, fn), currtable);
- break;
+ processNew(lb, (FlatNew)fn, isAtomic(atomictable, fn), currtable);
+ break;
case FKind.FlatOpNode:
- processOpNode((FlatOpNode)fn, currtable);
- break;
+ processOpNode((FlatOpNode)fn, currtable);
+ break;
case FKind.FlatCastNode:
- processCastNode((FlatCastNode)fn, currtable);
- break;
+ processCastNode((FlatCastNode)fn, currtable);
+ break;
case FKind.FlatLiteralNode:
- processLiteralNode((FlatLiteralNode)fn, currtable);
- break;
+ processLiteralNode((FlatLiteralNode)fn, currtable);
+ break;
case FKind.FlatReturnNode:
- processReturnNode(lb, (FlatReturnNode)fn, currtable);
- break;
+ processReturnNode(lb, (FlatReturnNode)fn, currtable);
+ break;
case FKind.FlatSetElementNode:
- processSetElementNode(lb, (FlatSetElementNode)fn, currtable, isAtomic(atomictable, fn));
- break;
+ processSetElementNode(lb, (FlatSetElementNode)fn, currtable, isAtomic(atomictable, fn));
+ break;
case FKind.FlatElementNode:
- processElementNode(lb, (FlatElementNode)fn, currtable, isAtomic(atomictable, fn));
- break;
+ processElementNode(lb, (FlatElementNode)fn, currtable, isAtomic(atomictable, fn));
+ break;
case FKind.FlatInstanceOfNode:
case FKind.FlatCondBranch:
case FKind.FlatNop:
case FKind.FlatExit:
case FKind.FlatPrefetchNode:
- //No action needed for these
- break;
+ //No action needed for these
+ break;
case FKind.FlatFlagActionNode:
case FKind.FlatCheckNode:
case FKind.FlatTagDeclaration:
- throw new Error("Incompatible with tasks!");
+ throw new Error("Incompatible with tasks!");
case FKind.FlatMethod:
- break;
+ break;
case FKind.FlatOffsetNode:
- processOffsetNode((FlatOffsetNode)fn, currtable);
- break;
+ processOffsetNode((FlatOffsetNode)fn, currtable);
+ break;
default:
- throw new Error("In finding fn.kind()= " + fn.kind());
+ throw new Error("In finding fn.kind()= " + fn.kind());
}
Hashtable<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));
- }
+ // Update table for this node
+ temptable.put(fn, currtable);
+ for(int i=0; i<fn.numNext(); i++) {
+ tovisit.add(fn.getNext(i));
+ }
}
}
}
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");
+ 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");
}
if(state.DSMTASK) {
- if (nodemd.getClassDesc().getSymbol().equals(TypeUtil.TaskClass) &&
- nodemd.getSymbol().equals("execution") && !nodemd.getModifiers().isStatic() &&
- nodemd.numParameters() == 0) {
-
- assert(nodemd.getModifiers().isNative());
- MethodDescriptor exemd = null;
-
- for(Iterator methodit=nodemd.getClassDesc().getMethodTable().getSet("execute").iterator(); methodit.hasNext(); ) {
- MethodDescriptor md = (MethodDescriptor) methodit.next();
-
- if (md.numParameters() != 0 || md.getModifiers().isStatic())
- continue;
- exemd = md;
- break;
- }
-
- if (exemd != null) {
- executemethodset = callgraph.getMethods(exemd, fc.getThis().getType());
- methodset.addAll(executemethodset);
- } else throw new Error("Can't find execute method");
- }
+ if (nodemd.getClassDesc().getSymbol().equals(TypeUtil.TaskClass) &&
+ nodemd.getSymbol().equals("execution") && !nodemd.getModifiers().isStatic() &&
+ nodemd.numParameters() == 0) {
+
+ assert(nodemd.getModifiers().isNative());
+ MethodDescriptor exemd = null;
+
+ for(Iterator methodit=nodemd.getClassDesc().getMethodTable().getSet("execute").iterator(); methodit.hasNext(); ) {
+ MethodDescriptor md = (MethodDescriptor) methodit.next();
+
+ if (md.numParameters() != 0 || md.getModifiers().isStatic())
+ continue;
+ exemd = md;
+ break;
+ }
+
+ if (exemd != null) {
+ executemethodset = callgraph.getMethods(exemd, fc.getThis().getType());
+ methodset.addAll(executemethodset);
+ } else throw new Error("Can't find execute method");
+ }
}
}
LocalityBinding lb=new LocalityBinding(md, isatomic);
if (isnative&&isatomic) {
- System.out.println("Don't call native methods in atomic blocks!"+currlb.getMethod());
+ System.out.println("Don't call native methods in atomic blocks!"+currlb.getMethod());
}
if ((runmethodset==null||!runmethodset.contains(md)) &&( executemethodset == null || !executemethodset.contains(md))) {
- //Skip this part if it is a run method or execute 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))&& !(nodemd.getSymbol().equals("rangePrefetch"))) {
- throw new Error("Potential call to native method "+md+" with global parameter:\n"+currlb.getExplanation());
- }
- lb.setGlobal(i,currtable.get(arg));
- }
+ //Skip this part if it is a run method or execute 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))&& !(nodemd.getSymbol().equals("rangePrefetch"))) {
+ 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) && executemethodset != null && executemethodset.contains(md))
- 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 && executemethodset == null) {
- throw new Error("Using global object outside of transaction in context:\n"+currlb.getExplanation());
- }
- if (runmethodset==null&&isnative&&thistype.equals(GLOBAL) && !isjoin && executemethodset == null && !isObjectgetType && !isObjecthashCode)
- throw new Error("Potential call to native method "+md+" on global objects:\n"+currlb.getExplanation());
- lb.setGlobalThis(thistype);
+ Integer thistype=currtable.get(fc.getThis());
+ if (thistype==null)
+ thistype=EITHER;
+
+ if(runmethodset!=null&&runmethodset.contains(md)&&thistype.equals(LOCAL) && executemethodset != null && executemethodset.contains(md))
+ 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 && executemethodset == null) {
+ throw new Error("Using global object outside of transaction in context:\n"+currlb.getExplanation());
+ }
+ if (runmethodset==null&&isnative&&thistype.equals(GLOBAL) && !isjoin && executemethodset == null && !isObjectgetType && !isObjecthashCode)
+ 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);
+ 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);
+ lb=discovered.get(lb);
Integer returnval=lb.getGlobalReturn();
currreturnval=merge(returnval, currreturnval);
if (!dependence.containsKey(lb))
- dependence.put(lb, new HashSet<LocalityBinding>());
+ dependence.put(lb, new HashSet<LocalityBinding>());
dependence.get(lb).add(currlb);
if (!calldep.containsKey(currlb))
- calldep.put(currlb, new HashSet<LocalityBinding>());
+ calldep.put(currlb, new HashSet<LocalityBinding>());
calldep.get(currlb).add(lb);
}
if (fc.getReturnTemp()!=null) {
TempDescriptor dst=ffn.getDst();
if (type.equals(LOCAL)) {
if (ffn.getField().isGlobal())
- currtable.put(dst,GLOBAL);
+ currtable.put(dst,GLOBAL);
else
- currtable.put(dst,LOCAL);
+ currtable.put(dst,LOCAL);
} else if (type.equals(GLOBAL)) {
if (!transaction)
- throw new Error("Global access outside of a transaction in context:\n"+lb.getExplanation());
+ throw new Error("Global access outside of a transaction in context:\n"+lb.getExplanation());
if (ffn.getField().getType().isPrimitive()&&!ffn.getField().getType().isArray())
- currtable.put(dst, LOCAL); // primitives are local
+ currtable.put(dst, LOCAL); // primitives are local
else
- currtable.put(dst, GLOBAL);
+ currtable.put(dst, GLOBAL);
} else if (type.equals(EITHER)) {
if (ffn.getField().getType().isPrimitive()&&!ffn.getField().getType().isArray())
- currtable.put(dst, LOCAL); // primitives are local
+ currtable.put(dst, LOCAL); // primitives are local
else if (ffn.getField().isGlobal())
- currtable.put(dst, GLOBAL);
+ currtable.put(dst, GLOBAL);
else
- currtable.put(dst, EITHER);
+ currtable.put(dst, EITHER);
} else if (type.equals(CONFLICT)) {
throw new Error("Access to object that could be either global or local in context:\n"+lb.getExplanation());
}
if (dsttype.equals(LOCAL)) {
if (fsfn.getField().isGlobal()) {
- if (!(srctype.equals(GLOBAL)||srctype.equals(EITHER)))
- throw new Error("Writing possible local reference to global field in context: \n"+lb.getExplanation());
+ if (!(srctype.equals(GLOBAL)||srctype.equals(EITHER)))
+ throw new Error("Writing possible local reference to global field in context: \n"+lb.getExplanation());
} else {
- if (!(srctype.equals(LOCAL)||srctype.equals(EITHER))) {
- throw new Error("Writing possible global reference to local object in context: \n"+lb.getExplanation());
- }
+ if (!(srctype.equals(LOCAL)||srctype.equals(EITHER))) {
+ throw new Error("Writing possible global reference to local object in context: \n"+lb.getExplanation());
+ }
}
} else if (dsttype.equals(GLOBAL)) {
if (!transaction)
- throw new Error("Global access outside of a transaction in context:\n"+lb.getExplanation());
+ throw new Error("Global access outside of a transaction in context:\n"+lb.getExplanation());
//okay to store primitives in global object
if (srctype.equals(LOCAL) && fsfn.getField().getType().isPrimitive() && !fsfn.getField().getType().isArray())
- return;
+ return;
if (!(srctype.equals(GLOBAL)||srctype.equals(EITHER)))
- throw new Error("Writing possible local reference to global object in context:\n"+lb.getExplanation()+" for FlatFieldNode "+fsfn);
+ throw new Error("Writing possible local reference to global object in context:\n"+lb.getExplanation()+" for FlatFieldNode "+fsfn);
} else if (dsttype.equals(EITHER)) {
if (srctype.equals(CONFLICT))
- throw new Error("Using reference that could be local or global in context:\n"+lb.getExplanation());
+ throw new Error("Using reference that could be local or global in context:\n"+lb.getExplanation());
} else if (dsttype.equals(CONFLICT)) {
throw new Error("Access to object that could be either global or local in context:\n"+lb.getExplanation());
}
if (srcvalue==null) {
if (!fon.getLeft().getType().isPtr()) {
- srcvalue=LOCAL;
+ srcvalue=LOCAL;
} else
- throw new Error(fon.getLeft()+" is undefined!");
+ throw new Error(fon.getLeft()+" is undefined!");
}
currtable.put(fon.getDest(), srcvalue);
}
if (dsttype.equals(LOCAL)) {
if (!(srctype.equals(LOCAL)||srctype.equals(EITHER))) {
- throw new Error("Writing possible global reference to local object in context:\n"+lb.getExplanation()+fsen);
+ throw new Error("Writing possible global reference to local object in context:\n"+lb.getExplanation()+fsen);
}
} else if (dsttype.equals(GLOBAL)) {
if (srctype.equals(LOCAL) && fsen.getDst().getType().dereference().isPrimitive() && !fsen.getDst().getType().dereference().isArray())
- return;
+ return;
if (!(srctype.equals(GLOBAL)||srctype.equals(EITHER)))
- throw new Error("Writing possible local reference to global object in context:\n"+lb.getExplanation());
+ throw new Error("Writing possible local reference to global object in context:\n"+lb.getExplanation());
if (!isatomic)
- throw new Error("Global access outside of a transaction in context:\n"+lb.getExplanation());
+ throw new Error("Global access outside of a transaction in context:\n"+lb.getExplanation());
} else if (dsttype.equals(EITHER)) {
if (srctype.equals(CONFLICT))
- throw new Error("Using reference that could be local or global in context:\n"+lb.getExplanation());
+ throw new Error("Using reference that could be local or global in context:\n"+lb.getExplanation());
} else if (dsttype.equals(CONFLICT)) {
throw new Error("Access to object that could be either global or local in context:\n"+lb.getExplanation());
}
currtable.put(dst,LOCAL);
} else if (type.equals(GLOBAL)) {
if (!isatomic)
- throw new Error("Global access outside of a transaction in context:\n"+lb.getExplanation());
+ throw new Error("Global access outside of a transaction in context:\n"+lb.getExplanation());
if(fen.getSrc().getType().dereference().isPrimitive()&&
!fen.getSrc().getType().dereference().isArray())
- currtable.put(dst, LOCAL);
+ currtable.put(dst, LOCAL);
else
- currtable.put(dst, GLOBAL);
+ currtable.put(dst, GLOBAL);
} else if (type.equals(EITHER)) {
if(fen.getSrc().getType().dereference().isPrimitive()&&
!fen.getSrc().getType().dereference().isArray())
- currtable.put(dst, LOCAL);
+ currtable.put(dst, LOCAL);
else
- currtable.put(dst, EITHER);
+ currtable.put(dst, EITHER);
} else if (type.equals(CONFLICT)) {
throw new Error("Access to object that could be either global or local in context:\n"+lb.getExplanation());
}
boolean isatomic=atomictab.get(fn).intValue()>0;
if (isatomic&&
atomictab.get(fn.getPrev(0)).intValue()==0) {
- assert(fn.kind()==FKind.FlatAtomicEnterNode);
- nodemap.put(fn, (FlatAtomicEnterNode)fn);
- nodetosavetemps.put((FlatAtomicEnterNode)fn, new HashSet<TempDescriptor>());
+ assert(fn.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(atomicnode);
- List<TempDescriptor> reads=Arrays.asList(fn.readsTemps());
- List<TempDescriptor> writes=Arrays.asList(fn.writesTemps());
-
- for(Iterator<TempDescriptor> tempit=livetemps.iterator(); tempit.hasNext(); ) {
- TempDescriptor tmp=tempit.next();
- if (writes.contains(tmp)) {
- nodetosavetemps.get(atomicnode).add(tmp);
- } else if (state.DSM) {
- if (reads.contains(tmp)&&temptab.get(fn).get(tmp)==GLOBAL) {
- nodetosavetemps.get(atomicnode).add(tmp);
- }
- } else if (state.SINGLETM) {
- if (reads.contains(tmp)&&tmp.getType().isPtr()&&temptab.get(fn).get(tmp)==NORMAL) {
- nodetosavetemps.get(atomicnode).add(tmp);
- }
- }
- }
+ FlatAtomicEnterNode atomicnode=nodemap.get(fn);
+ Set<TempDescriptor> livetemps=nodetotemps.get(atomicnode);
+ List<TempDescriptor> reads=Arrays.asList(fn.readsTemps());
+ List<TempDescriptor> writes=Arrays.asList(fn.writesTemps());
+
+ for(Iterator<TempDescriptor> tempit=livetemps.iterator(); tempit.hasNext(); ) {
+ TempDescriptor tmp=tempit.next();
+ if (writes.contains(tmp)) {
+ nodetosavetemps.get(atomicnode).add(tmp);
+ } else if (state.DSM) {
+ if (reads.contains(tmp)&&temptab.get(fn).get(tmp)==GLOBAL) {
+ nodetosavetemps.get(atomicnode).add(tmp);
+ }
+ } else if (state.SINGLETM) {
+ if (reads.contains(tmp)&&tmp.getType().isPtr()&&temptab.get(fn).get(tmp)==NORMAL) {
+ nodetosavetemps.get(atomicnode).add(tmp);
+ }
+ }
+ }
}
for(int i=0; i<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));
- }
- }
+ FlatNode fnnext=fn.getNext(i);
+ if (!discovered.contains(fnnext)) {
+ discovered.add(fnnext);
+ toprocess.add(fnnext);
+ if(isatomic) {
+ nodemap.put(fnnext, nodemap.get(fn));
+ }
+ }
}
}
}
st+="[static] ";
} else {
if (isglobalthis.equals(LocalityAnalysis.LOCAL))
- st+="[local] ";
+ st+="[local] ";
else if (isglobalthis.equals(LocalityAnalysis.GLOBAL))
- st+="[global] ";
+ st+="[global] ";
else if (isglobalthis.equals(LocalityAnalysis.EITHER))
- st+="[either] ";
+ st+="[either] ";
else if (isglobalthis.equals(LocalityAnalysis.CONFLICT))
- st+="[conflict] ";
+ st+="[conflict] ";
else
- st+="[this="+isglobalthis+"]";
+ st+="[this="+isglobalthis+"]";
}
for(int i=0; i<isglobal.length; i++)
if (isglobal[i]==null)
- st+="NULL";
+ st+="NULL";
else if (isglobal[i].equals(LocalityAnalysis.LOCAL))
- st+="local ";
+ st+="local ";
else if (isglobal[i].equals(LocalityAnalysis.GLOBAL))
- st+="global ";
+ st+="global ";
else if (isglobal[i].equals(LocalityAnalysis.EITHER))
- st+="either ";
+ st+="either ";
else if (isglobal[i].equals(LocalityAnalysis.CONFLICT))
- st+="conflict ";
+ st+="conflict ";
else
- st+="["+isglobal[i]+"]";
+ st+="["+isglobal[i]+"]";
return st;
}
return false;
for(int i=0; i<isglobal.length; i++)
if (!equiv(isglobal[i],lb.isglobal[i]))
- return false;
+ return false;
if (!equiv(isglobalthis, lb.isglobalthis))
return false;
if (o instanceof LocalityBinding) {
LocalityBinding lb=(LocalityBinding)o;
if (md!=lb.md)
- return false;
+ return false;
for(int i=0; i<isglobal.length; i++)
- if (!equiv(isglobal[i], lb.isglobal[i]))
- return false;
+ if (!equiv(isglobal[i], lb.isglobal[i]))
+ return false;
if (!equiv(isglobalthis, lb.isglobalthis))
- return false;
+ return false;
return (isatomic==lb.isatomic);
}
return false;
int hashcode=md.hashCode();
for(int i=0; i<isglobal.length; i++) {
if (isglobal[i]!=null)
- hashcode=hashcode*31+(isglobal[i].intValue());
+ hashcode=hashcode*31+(isglobal[i].intValue());
}
hashcode=hashcode*31+(isatomic?1:0);
return hashcode;
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;
+ // need to check flat node equivalence also
+ if (tnp.fn==null||fn==null||(!fn.equals(tnp.fn)))
+ return false;
}
return tmp.equals(tnp.tmp);
}
TypeDescriptor td=it.next();
Set<TypeDescriptor> set=transmap.get(td);
for(Iterator<TypeDescriptor> it2=set.iterator(); it2.hasNext(); ) {
- TypeDescriptor type=it2.next();
- if (!namemap.containsKey(type))
- namemap.put(type, new HashSet<TypeDescriptor>());
- namemap.get(type).addAll(set);
+ TypeDescriptor type=it2.next();
+ if (!namemap.containsKey(type))
+ namemap.put(type, new HashSet<TypeDescriptor>());
+ namemap.get(type).addAll(set);
}
}
}
transmap.get(td).add(td);
while(!tovisit.isEmpty()) {
- TypeDescriptor type=tovisit.iterator().next();
- tovisit.remove(type);
- //Is type a supertype of td...if not skip along
- if (!typeutil.isSuperorType(type,td))
- continue;
- //Check if we have seen it before
- if (!transmap.get(td).contains(type)) {
- //If not, add to set and continue processing
- transmap.get(td).add(type);
- tovisit.add(type);
- }
+ TypeDescriptor type=tovisit.iterator().next();
+ tovisit.remove(type);
+ //Is type a supertype of td...if not skip along
+ if (!typeutil.isSuperorType(type,td))
+ continue;
+ //Check if we have seen it before
+ if (!transmap.get(td).contains(type)) {
+ //If not, add to set and continue processing
+ transmap.get(td).add(type);
+ tovisit.add(type);
+ }
}
}
}
TypeDescriptor td=it.next();
Set<TypeDescriptor> etdset=expand(td);
if (etdset==null)
- expandedSet.add(td);
+ expandedSet.add(td);
else
- expandedSet.addAll(etdset);
+ expandedSet.addAll(etdset);
}
return expandedSet;
}
FlatNode fn=fnit.next();
switch(fn.kind()) {
case FKind.FlatOpNode: {
- FlatOpNode fon=(FlatOpNode)fn;
- if(fon.getOp().getOp()==Operation.ASSIGN) {
- addMapping(fon.getLeft().getType(),fon.getDest().getType());
- }
- break;
+ FlatOpNode fon=(FlatOpNode)fn;
+ if(fon.getOp().getOp()==Operation.ASSIGN) {
+ addMapping(fon.getLeft().getType(),fon.getDest().getType());
+ }
+ break;
}
case FKind.FlatNew: {
- FlatNew fnew=(FlatNew)fn;
- roottypes.add(fnew.getType());
- break;
+ FlatNew fnew=(FlatNew)fn;
+ roottypes.add(fnew.getType());
+ break;
}
case FKind.FlatCastNode: {
- FlatCastNode fcn=(FlatCastNode)fn;
- addMapping(fcn.getSrc().getType(), fcn.getDst().getType());
- break;
+ FlatCastNode fcn=(FlatCastNode)fn;
+ addMapping(fcn.getSrc().getType(), fcn.getDst().getType());
+ break;
}
case FKind.FlatFieldNode: {
- FlatFieldNode ffn=(FlatFieldNode)fn;
- addMapping(ffn.getField().getType(), ffn.getDst().getType());
- break;
+ FlatFieldNode ffn=(FlatFieldNode)fn;
+ addMapping(ffn.getField().getType(), ffn.getDst().getType());
+ break;
}
case FKind.FlatSetFieldNode: {
- FlatSetFieldNode fsfn=(FlatSetFieldNode) fn;
- addMapping(fsfn.getSrc().getType(), fsfn.getField().getType());
- break;
+ FlatSetFieldNode fsfn=(FlatSetFieldNode) fn;
+ addMapping(fsfn.getSrc().getType(), fsfn.getField().getType());
+ break;
}
case FKind.FlatElementNode: {
- FlatElementNode fen=(FlatElementNode)fn;
- addMapping(fen.getSrc().getType().dereference(), fen.getDst().getType());
- break;
+ FlatElementNode fen=(FlatElementNode)fn;
+ addMapping(fen.getSrc().getType().dereference(), fen.getDst().getType());
+ break;
}
case FKind.FlatSetElementNode: {
- FlatSetElementNode fsen=(FlatSetElementNode)fn;
- addMapping(fsen.getSrc().getType(), fsen.getDst().getType().dereference());
- break;
+ FlatSetElementNode fsen=(FlatSetElementNode)fn;
+ addMapping(fsen.getSrc().getType(), fsen.getDst().getType().dereference());
+ break;
}
case FKind.FlatCall: {
- FlatCall fc=(FlatCall)fn;
- if (fc.getReturnTemp()!=null) {
- addMapping(fc.getMethod().getReturnType(), fc.getReturnTemp().getType());
- }
- MethodDescriptor callmd=fc.getMethod();
- if (fc.getThis()!=null) {
- //complicated...need to deal with virtual dispatch here
- Set methods=cg.getMethods(callmd);
- for(Iterator mdit=methods.iterator(); mdit.hasNext(); ) {
- MethodDescriptor md2=(MethodDescriptor)mdit.next();
- if (fc.getThis()!=null) {
- TypeDescriptor ttype=new TypeDescriptor(md2.getClassDesc());
- if (!typeutil.isSuperorType(fc.getThis().getType(),ttype)&&
- !typeutil.isSuperorType(ttype,fc.getThis().getType()))
- continue;
- addMapping(fc.getThis().getType(), ttype);
- }
- }
- }
- for(int i=0; i<fc.numArgs(); i++) {
- TempDescriptor arg=fc.getArg(i);
- TypeDescriptor ptype=callmd.getParamType(i);
- addMapping(arg.getType(), ptype);
- }
- break;
+ FlatCall fc=(FlatCall)fn;
+ if (fc.getReturnTemp()!=null) {
+ addMapping(fc.getMethod().getReturnType(), fc.getReturnTemp().getType());
+ }
+ MethodDescriptor callmd=fc.getMethod();
+ if (fc.getThis()!=null) {
+ //complicated...need to deal with virtual dispatch here
+ Set methods=cg.getMethods(callmd);
+ for(Iterator mdit=methods.iterator(); mdit.hasNext(); ) {
+ MethodDescriptor md2=(MethodDescriptor)mdit.next();
+ if (fc.getThis()!=null) {
+ TypeDescriptor ttype=new TypeDescriptor(md2.getClassDesc());
+ if (!typeutil.isSuperorType(fc.getThis().getType(),ttype)&&
+ !typeutil.isSuperorType(ttype,fc.getThis().getType()))
+ continue;
+ addMapping(fc.getThis().getType(), ttype);
+ }
+ }
+ }
+ for(int i=0; i<fc.numArgs(); i++) {
+ TempDescriptor arg=fc.getArg(i);
+ TypeDescriptor ptype=callmd.getParamType(i);
+ addMapping(arg.getType(), ptype);
+ }
+ break;
}
//both inputs and output
case FKind.FlatReturnNode: {
- FlatReturnNode frn=(FlatReturnNode) fn;
- if (frn.getReturnTemp()!=null)
- addMapping(frn.getReturnTemp().getType(), md.getReturnType());
+ FlatReturnNode frn=(FlatReturnNode) fn;
+ if (frn.getReturnTemp()!=null)
+ addMapping(frn.getReturnTemp().getType(), md.getReturnType());
}
}
}
FlatNode fn=(FlatNode)toprocess.iterator().next();
toprocess.remove(fn);
for(int i=0; i<fn.numNext(); i++) {
- FlatNode nnext=fn.getNext(i);
- if (!discovered.contains(nnext)) {
- toprocess.add(nnext);
- discovered.add(nnext);
- }
+ FlatNode nnext=fn.getNext(i);
+ if (!discovered.contains(nnext)) {
+ toprocess.add(nnext);
+ discovered.add(nnext);
+ }
}
Hashtable<Expression, TempDescriptor> tab=computeIntersection(fn, availexpr);
//Do kills of expression/variable mappings
TempDescriptor[] write=fn.writesTemps();
for(int i=0; i<write.length; i++) {
- if (tab.containsKey(write[i]))
- tab.remove(write[i]);
+ if (tab.containsKey(write[i]))
+ tab.remove(write[i]);
}
switch(fn.kind()) {
case FKind.FlatAtomicEnterNode:
{
- killexpressions(tab, null, null, true);
- break;
+ killexpressions(tab, null, null, true);
+ break;
}
case FKind.FlatCall:
{
- FlatCall fc=(FlatCall) fn;
- MethodDescriptor md=fc.getMethod();
- Set<FieldDescriptor> fields=gft.getFieldsAll(md);
- Set<TypeDescriptor> arrays=gft.getArraysAll(md);
- killexpressions(tab, fields, arrays, gft.containsAtomicAll(md)||gft.containsBarrierAll(md));
- break;
+ FlatCall fc=(FlatCall) fn;
+ MethodDescriptor md=fc.getMethod();
+ Set<FieldDescriptor> fields=gft.getFieldsAll(md);
+ Set<TypeDescriptor> arrays=gft.getArraysAll(md);
+ killexpressions(tab, fields, arrays, gft.containsAtomicAll(md)||gft.containsBarrierAll(md));
+ break;
}
case FKind.FlatOpNode:
{
- FlatOpNode fon=(FlatOpNode) fn;
- Expression e=new Expression(fon.getLeft(), fon.getRight(), fon.getOp());
- tab.put(e, fon.getDest());
- break;
+ FlatOpNode fon=(FlatOpNode) fn;
+ Expression e=new Expression(fon.getLeft(), fon.getRight(), fon.getOp());
+ tab.put(e, fon.getDest());
+ break;
}
case FKind.FlatSetFieldNode:
{
- FlatSetFieldNode fsfn=(FlatSetFieldNode)fn;
- Set<FieldDescriptor> fields=new HashSet<FieldDescriptor>();
- fields.add(fsfn.getField());
- killexpressions(tab, fields, null, false);
- Expression e=new Expression(fsfn.getDst(), fsfn.getField());
- tab.put(e, fsfn.getSrc());
- break;
+ FlatSetFieldNode fsfn=(FlatSetFieldNode)fn;
+ Set<FieldDescriptor> fields=new HashSet<FieldDescriptor>();
+ fields.add(fsfn.getField());
+ killexpressions(tab, fields, null, false);
+ Expression e=new Expression(fsfn.getDst(), fsfn.getField());
+ tab.put(e, fsfn.getSrc());
+ break;
}
case FKind.FlatFieldNode:
{
- FlatFieldNode ffn=(FlatFieldNode)fn;
- Expression e=new Expression(ffn.getSrc(), ffn.getField());
- tab.put(e, ffn.getDst());
- break;
+ FlatFieldNode ffn=(FlatFieldNode)fn;
+ Expression e=new Expression(ffn.getSrc(), ffn.getField());
+ tab.put(e, ffn.getDst());
+ break;
}
case FKind.FlatSetElementNode:
{
- FlatSetElementNode fsen=(FlatSetElementNode)fn;
- Expression e=new Expression(fsen.getDst(),fsen.getIndex());
- tab.put(e, fsen.getSrc());
- break;
+ FlatSetElementNode fsen=(FlatSetElementNode)fn;
+ Expression e=new Expression(fsen.getDst(),fsen.getIndex());
+ tab.put(e, fsen.getSrc());
+ break;
}
case FKind.FlatElementNode:
{
- FlatElementNode fen=(FlatElementNode)fn;
- Expression e=new Expression(fen.getSrc(),fen.getIndex());
- tab.put(e, fen.getDst());
- break;
+ FlatElementNode fen=(FlatElementNode)fn;
+ Expression e=new Expression(fen.getSrc(),fen.getIndex());
+ tab.put(e, fen.getDst());
+ break;
}
default:
}
if (write.length==1) {
- TempDescriptor w=write[0];
- for(Iterator it=tab.entrySet().iterator(); it.hasNext(); ) {
- Map.Entry m=(Map.Entry)it.next();
- Expression e=(Expression)m.getKey();
- if (e.a==w||e.b==w)
- it.remove();
- }
+ TempDescriptor w=write[0];
+ for(Iterator it=tab.entrySet().iterator(); it.hasNext(); ) {
+ Map.Entry m=(Map.Entry)it.next();
+ Expression e=(Expression)m.getKey();
+ if (e.a==w||e.b==w)
+ it.remove();
+ }
}
if (!availexpr.containsKey(fn)||!availexpr.get(fn).equals(tab)) {
- availexpr.put(fn, tab);
- for(int i=0; i<fn.numNext(); i++) {
- FlatNode nnext=fn.getNext(i);
- toprocess.add(nnext);
- }
+ availexpr.put(fn, tab);
+ for(int i=0; i<fn.numNext(); i++) {
+ FlatNode nnext=fn.getNext(i);
+ toprocess.add(nnext);
+ }
}
}
switch(fn.kind()) {
case FKind.FlatOpNode:
{
- FlatOpNode fon=(FlatOpNode) fn;
- Expression e=new Expression(fon.getLeft(), fon.getRight(),fon.getOp());
- if (tab.containsKey(e)) {
- TempDescriptor t=tab.get(e);
- FlatNode newfon=new FlatOpNode(fon.getDest(),t,null,new Operation(Operation.ASSIGN));
- replacetable.put(fon,newfon);
- }
- break;
+ FlatOpNode fon=(FlatOpNode) fn;
+ Expression e=new Expression(fon.getLeft(), fon.getRight(),fon.getOp());
+ if (tab.containsKey(e)) {
+ TempDescriptor t=tab.get(e);
+ FlatNode newfon=new FlatOpNode(fon.getDest(),t,null,new Operation(Operation.ASSIGN));
+ replacetable.put(fon,newfon);
+ }
+ break;
}
case FKind.FlatFieldNode:
{
- FlatFieldNode ffn=(FlatFieldNode)fn;
- Expression e=new Expression(ffn.getSrc(), ffn.getField());
- if (tab.containsKey(e)) {
- TempDescriptor t=tab.get(e);
- FlatNode newfon=new FlatOpNode(ffn.getDst(),t,null,new Operation(Operation.ASSIGN));
- replacetable.put(ffn,newfon);
- }
- break;
+ FlatFieldNode ffn=(FlatFieldNode)fn;
+ Expression e=new Expression(ffn.getSrc(), ffn.getField());
+ if (tab.containsKey(e)) {
+ TempDescriptor t=tab.get(e);
+ FlatNode newfon=new FlatOpNode(ffn.getDst(),t,null,new Operation(Operation.ASSIGN));
+ replacetable.put(ffn,newfon);
+ }
+ break;
}
case FKind.FlatElementNode:
{
- FlatElementNode fen=(FlatElementNode)fn;
- Expression e=new Expression(fen.getSrc(),fen.getIndex());
- if (tab.containsKey(e)) {
- TempDescriptor t=tab.get(e);
- FlatNode newfon=new FlatOpNode(fen.getDst(),t,null,new Operation(Operation.ASSIGN));
- replacetable.put(fen,newfon);
- }
- break;
+ FlatElementNode fen=(FlatElementNode)fn;
+ Expression e=new Expression(fen.getSrc(),fen.getIndex());
+ if (tab.containsKey(e)) {
+ TempDescriptor t=tab.get(e);
+ FlatNode newfon=new FlatOpNode(fen.getDst(),t,null,new Operation(Operation.ASSIGN));
+ replacetable.put(fen,newfon);
+ }
+ break;
}
default:
for(int i=0; i<fn.numPrev(); i++) {
FlatNode prev=fn.getPrev(i);
if (first) {
- if (availexpr.containsKey(prev)) {
- tab.putAll(availexpr.get(prev));
- first=false;
- }
+ if (availexpr.containsKey(prev)) {
+ tab.putAll(availexpr.get(prev));
+ first=false;
+ }
} else {
- if (availexpr.containsKey(prev)) {
- Hashtable<Expression, TempDescriptor> table=availexpr.get(prev);
- for(Iterator mapit=tab.entrySet().iterator(); mapit.hasNext(); ) {
- Object entry=mapit.next();
- if (!table.contains(entry))
- mapit.remove();
- }
- }
+ if (availexpr.containsKey(prev)) {
+ Hashtable<Expression, TempDescriptor> table=availexpr.get(prev);
+ for(Iterator mapit=tab.entrySet().iterator(); mapit.hasNext(); ) {
+ Object entry=mapit.next();
+ if (!table.contains(entry))
+ mapit.remove();
+ }
+ }
}
}
return tab;
Map.Entry m=(Map.Entry)it.next();
Expression e=(Expression)m.getKey();
if (killall&&(e.f!=null||e.a!=null))
- it.remove();
+ it.remove();
else if (e.f!=null&&fields!=null&&fields.contains(e.f))
- it.remove();
+ it.remove();
else if ((e.a!=null)&&(arrays!=null)) {
- for(Iterator<TypeDescriptor> arit=arrays.iterator(); arit.hasNext(); ) {
- TypeDescriptor artd=arit.next();
- if (typeutil.isSuperorType(artd,e.a.getType())||
- typeutil.isSuperorType(e.a.getType(),artd)) {
- it.remove();
- break;
- }
- }
+ for(Iterator<TypeDescriptor> arit=arrays.iterator(); arit.hasNext(); ) {
+ TypeDescriptor artd=arit.next();
+ if (typeutil.isSuperorType(artd,e.a.getType())||
+ typeutil.isSuperorType(e.a.getType(),artd)) {
+ it.remove();
+ break;
+ }
+ }
}
}
}
HashSet tovisit=new HashSet();
tovisit.add(fm);
while(!tovisit.isEmpty()) {
- FlatNode fn=(FlatNode) tovisit.iterator().next();
- tovisit.remove(fn);
+ FlatNode fn=(FlatNode) tovisit.iterator().next();
+ tovisit.remove(fn);
- Hashtable<TempDescriptor, TempDescriptor> tab;
- if (fn.numPrev()>=1&&table.containsKey(fn.getPrev(0)))
- tab=new Hashtable<TempDescriptor, TempDescriptor>(table.get(fn.getPrev(0)));
- else
- tab=new Hashtable<TempDescriptor, TempDescriptor>();
- //Compute intersection
+ Hashtable<TempDescriptor, TempDescriptor> tab;
+ if (fn.numPrev()>=1&&table.containsKey(fn.getPrev(0)))
+ tab=new Hashtable<TempDescriptor, TempDescriptor>(table.get(fn.getPrev(0)));
+ else
+ tab=new Hashtable<TempDescriptor, TempDescriptor>();
+ //Compute intersection
- Set<TempDescriptor> liveset=livetemps.get(fn);
- for(int i=1; i<fn.numPrev(); i++) {
- Hashtable<TempDescriptor, TempDescriptor> tp=table.get(fn.getPrev(i));
- if (tp==null)
- continue;
- for(Iterator tmpit=tp.entrySet().iterator(); tmpit.hasNext(); ) {
- Map.Entry t=(Map.Entry)tmpit.next();
- TempDescriptor tmp=(TempDescriptor)t.getKey();
- if (!liveset.contains(tmp))
- continue;
- TempDescriptor dsttmp=tp.get(tmp);
- if (!tab.containsKey(tmp)) {
- tab.put(tmp, dsttmp);
- } else if (tab.get(tmp)!=dsttmp) {
- tab.put(tmp, bogustd);
- }
- }
- }
+ Set<TempDescriptor> liveset=livetemps.get(fn);
+ for(int i=1; i<fn.numPrev(); i++) {
+ Hashtable<TempDescriptor, TempDescriptor> tp=table.get(fn.getPrev(i));
+ if (tp==null)
+ continue;
+ for(Iterator tmpit=tp.entrySet().iterator(); tmpit.hasNext(); ) {
+ Map.Entry t=(Map.Entry)tmpit.next();
+ TempDescriptor tmp=(TempDescriptor)t.getKey();
+ if (!liveset.contains(tmp))
+ continue;
+ TempDescriptor dsttmp=tp.get(tmp);
+ if (!tab.containsKey(tmp)) {
+ tab.put(tmp, dsttmp);
+ } else if (tab.get(tmp)!=dsttmp) {
+ tab.put(tmp, bogustd);
+ }
+ }
+ }
- HashSet<TempDescriptor> toremove=new HashSet<TempDescriptor>();
- TempDescriptor[] writes=fn.writesTemps();
- for(int i=0; i<writes.length; i++) {
- TempDescriptor tmp=writes[i];
- toremove.add(tmp);
- for(Iterator<TempDescriptor> tmpit=tab.keySet().iterator(); tmpit.hasNext(); ) {
- TempDescriptor tmp2=tmpit.next();
- if (tmp==tab.get(tmp2))
- toremove.add(tmp2);
- }
- }
+ HashSet<TempDescriptor> toremove=new HashSet<TempDescriptor>();
+ TempDescriptor[] writes=fn.writesTemps();
+ for(int i=0; i<writes.length; i++) {
+ TempDescriptor tmp=writes[i];
+ toremove.add(tmp);
+ for(Iterator<TempDescriptor> tmpit=tab.keySet().iterator(); tmpit.hasNext(); ) {
+ TempDescriptor tmp2=tmpit.next();
+ if (tmp==tab.get(tmp2))
+ toremove.add(tmp2);
+ }
+ }
- for(Iterator<TempDescriptor> tmpit=toremove.iterator(); tmpit.hasNext(); ) {
- TempDescriptor tmp=tmpit.next();
- tab.put(tmp, bogustd);
- }
+ for(Iterator<TempDescriptor> tmpit=toremove.iterator(); tmpit.hasNext(); ) {
+ TempDescriptor tmp=tmpit.next();
+ tab.put(tmp, bogustd);
+ }
- if (fn.kind()==FKind.FlatOpNode) {
- FlatOpNode fon=(FlatOpNode)fn;
- if (fon.getOp().getOp()==Operation.ASSIGN) {
- tab.put(fon.getDest(), fon.getLeft());
- }
- }
- if (!table.containsKey(fn)||!table.get(fn).equals(tab)) {
- table.put(fn,tab);
- changed=true;
- for(int i=0; i<fn.numNext(); i++) {
- FlatNode nnext=fn.getNext(i);
- tovisit.add(nnext);
- }
- }
+ if (fn.kind()==FKind.FlatOpNode) {
+ FlatOpNode fon=(FlatOpNode)fn;
+ if (fon.getOp().getOp()==Operation.ASSIGN) {
+ tab.put(fon.getDest(), fon.getLeft());
+ }
+ }
+ if (!table.containsKey(fn)||!table.get(fn).equals(tab)) {
+ table.put(fn,tab);
+ changed=true;
+ for(int i=0; i<fn.numNext(); i++) {
+ FlatNode nnext=fn.getNext(i);
+ tovisit.add(nnext);
+ }
+ }
} //end of dataflow while loop
Set<FlatNode> nodeset=fm.getNodeSet();
for(Iterator<FlatNode> it=fm.getNodeSet().iterator(); it.hasNext(); ) {
- FlatNode fn=it.next();
- if (fn.numPrev()==0)
- continue;
+ FlatNode fn=it.next();
+ if (fn.numPrev()==0)
+ continue;
- Hashtable<TempDescriptor, TempDescriptor> tab=new Hashtable<TempDescriptor, TempDescriptor>();
+ Hashtable<TempDescriptor, TempDescriptor> tab=new Hashtable<TempDescriptor, TempDescriptor>();
- for(int i=0; i<fn.numPrev(); i++) {
- Hashtable<TempDescriptor, TempDescriptor> tp=table.get(fn.getPrev(i));
- for(Iterator tmpit=tp.entrySet().iterator(); tmpit.hasNext(); ) {
- Map.Entry t=(Map.Entry)tmpit.next();
- TempDescriptor tmp=(TempDescriptor)t.getKey();
+ for(int i=0; i<fn.numPrev(); i++) {
+ Hashtable<TempDescriptor, TempDescriptor> tp=table.get(fn.getPrev(i));
+ for(Iterator tmpit=tp.entrySet().iterator(); tmpit.hasNext(); ) {
+ Map.Entry t=(Map.Entry)tmpit.next();
+ TempDescriptor tmp=(TempDescriptor)t.getKey();
- if (!tab.containsKey(tmp))
- tab.put(tmp, tp.get(tmp));
- else if (tab.get(tmp)!=tp.get(tmp)) {
- tab.put(tmp, bogustd);
- }
- }
- }
+ if (!tab.containsKey(tmp))
+ tab.put(tmp, tp.get(tmp));
+ else if (tab.get(tmp)!=tp.get(tmp)) {
+ tab.put(tmp, bogustd);
+ }
+ }
+ }
- TempMap tmap=null;
- TempDescriptor[] reads=fn.readsTemps();
- for(int i=0; i<reads.length; i++) {
- TempDescriptor tmp=reads[i];
- if (tab.containsKey(tmp)&&tab.get(tmp)!=bogustd) {
- if (tmap==null)
- tmap=new TempMap();
- tmap.addPair(tmp, tab.get(tmp));
- }
- }
- if (tmap!=null)
- fn.rewriteUse(tmap);
+ TempMap tmap=null;
+ TempDescriptor[] reads=fn.readsTemps();
+ for(int i=0; i<reads.length; i++) {
+ TempDescriptor tmp=reads[i];
+ if (tab.containsKey(tmp)&&tab.get(tmp)!=bogustd) {
+ if (tmap==null)
+ tmap=new TempMap();
+ tmap.addPair(tmp, tab.get(tmp));
+ }
+ }
+ if (tmap!=null)
+ fn.rewriteUse(tmap);
} //end of remapping for loop
} while(changed);
}
changed=false;
nextfn:
for(Iterator<FlatNode> it=fm.getNodeSet().iterator(); it.hasNext(); ) {
- FlatNode fn=it.next();
- switch(fn.kind()) {
- case FKind.FlatCall:
- case FKind.FlatFieldNode:
- case FKind.FlatSetFieldNode:
- case FKind.FlatNew:
- case FKind.FlatCastNode:
- case FKind.FlatReturnNode:
- case FKind.FlatCondBranch:
- case FKind.FlatSetElementNode:
- case FKind.FlatElementNode:
- case FKind.FlatFlagActionNode:
- case FKind.FlatCheckNode:
- case FKind.FlatBackEdge:
- case FKind.FlatExit:
- case FKind.FlatTagDeclaration:
- case FKind.FlatMethod:
- case FKind.FlatAtomicEnterNode:
- case FKind.FlatAtomicExitNode:
- case FKind.FlatPrefetchNode:
- case FKind.FlatSESEEnterNode:
- case FKind.FlatSESEExitNode:
- case FKind.FlatGenReachNode:
- if (!useful.contains(fn)) {
- useful.add(fn);
- changed=true;
- }
- break;
+ FlatNode fn=it.next();
+ switch(fn.kind()) {
+ case FKind.FlatCall:
+ case FKind.FlatFieldNode:
+ case FKind.FlatSetFieldNode:
+ case FKind.FlatNew:
+ case FKind.FlatCastNode:
+ case FKind.FlatReturnNode:
+ case FKind.FlatCondBranch:
+ case FKind.FlatSetElementNode:
+ case FKind.FlatElementNode:
+ case FKind.FlatFlagActionNode:
+ case FKind.FlatCheckNode:
+ case FKind.FlatBackEdge:
+ case FKind.FlatExit:
+ case FKind.FlatTagDeclaration:
+ case FKind.FlatMethod:
+ case FKind.FlatAtomicEnterNode:
+ case FKind.FlatAtomicExitNode:
+ case FKind.FlatPrefetchNode:
+ case FKind.FlatSESEEnterNode:
+ case FKind.FlatSESEExitNode:
+ case FKind.FlatGenReachNode:
+ if (!useful.contains(fn)) {
+ useful.add(fn);
+ changed=true;
+ }
+ break;
- case FKind.FlatOpNode:
- FlatOpNode fon=(FlatOpNode)fn;
- if (fon.getOp().getOp()==Operation.DIV||
- fon.getOp().getOp()==Operation.MOD) {
- if (!useful.contains(fn)) {
- useful.add(fn);
- changed=true;
- }
- break;
- }
+ case FKind.FlatOpNode:
+ FlatOpNode fon=(FlatOpNode)fn;
+ if (fon.getOp().getOp()==Operation.DIV||
+ fon.getOp().getOp()==Operation.MOD) {
+ if (!useful.contains(fn)) {
+ useful.add(fn);
+ changed=true;
+ }
+ break;
+ }
- default:
- TempDescriptor[] writes=fn.writesTemps();
- if (!useful.contains(fn))
- for(int i=0; i<writes.length; i++) {
- for(Iterator<FlatNode> uit=ud.useMap(fn,writes[i]).iterator(); uit.hasNext(); ) {
- FlatNode ufn=uit.next();
- if (useful.contains(ufn)) {
- //we are useful
- useful.add(fn);
- changed=true;
- continue nextfn;
- }
- }
- }
- }
+ default:
+ TempDescriptor[] writes=fn.writesTemps();
+ if (!useful.contains(fn))
+ for(int i=0; i<writes.length; i++) {
+ for(Iterator<FlatNode> uit=ud.useMap(fn,writes[i]).iterator(); uit.hasNext(); ) {
+ FlatNode ufn=uit.next();
+ if (useful.contains(ufn)) {
+ //we are useful
+ useful.add(fn);
+ changed=true;
+ continue nextfn;
+ }
+ }
+ }
+ }
}
}
//get rid of useless nodes
for(Iterator<FlatNode> it=fm.getNodeSet().iterator(); it.hasNext(); ) {
FlatNode fn=it.next();
if (!useful.contains(fn)||isuseless(fn)) {
- //We have a useless node
- FlatNode fnnext=fn.getNext(0);
- for(int i=0; i<fn.numPrev(); i++) {
- FlatNode nprev=fn.getPrev(i);
+ //We have a useless node
+ FlatNode fnnext=fn.getNext(0);
+ for(int i=0; i<fn.numPrev(); i++) {
+ FlatNode nprev=fn.getPrev(i);
- for(int j=0; j<nprev.numNext(); j++) {
- if (nprev.getNext(j)==fn) {
- nprev.setnext(j, fnnext);
- fnnext.addPrev(nprev);
- }
- }
- }
- //fix up prev edge of fnnext
- fnnext.removePrev(fn);
+ for(int j=0; j<nprev.numNext(); j++) {
+ if (nprev.getNext(j)==fn) {
+ nprev.setnext(j, fnnext);
+ fnnext.addPrev(nprev);
+ }
+ }
+ }
+ //fix up prev edge of fnnext
+ fnnext.removePrev(fn);
}
}
}
if (fn.kind()==FKind.FlatOpNode) {
FlatOpNode fon=(FlatOpNode)fn;
if (fon.getOp().getOp()==Operation.ASSIGN&&fon.getLeft()==fon.getDest())
- return true;
+ return true;
}
return false;
}
Set<FlatNode> fnodes=fm.getNodeSet();
Vector<FlatNode> v=new Vector<FlatNode>();
for(Iterator<FlatNode> fit=fnodes.iterator(); fit.hasNext(); ) {
- FlatNode fn=fit.next();
- if (fn.numNext()==0) {
- v.add(fn);
- }
+ FlatNode fn=fit.next();
+ if (fn.numNext()==0) {
+ v.add(fn);
+ }
}
FlatNode[] fnarray=new FlatNode[v.size()];
for(int i=0; i<v.size(); i++) {
- fnarray[i]=v.elementAt(i);
- domtable.put(fnarray[i],fnarray[i]);
- HashSet<FlatNode> set=new HashSet<FlatNode> ();
- set.add(fnarray[i]);
- childtree.put(fnarray[i],set);
+ fnarray[i]=v.elementAt(i);
+ domtable.put(fnarray[i],fnarray[i]);
+ HashSet<FlatNode> set=new HashSet<FlatNode> ();
+ set.add(fnarray[i]);
+ childtree.put(fnarray[i],set);
}
DFS(fnarray, postdominator);
} else {
while(changed) {
changed=false;
for(int i=vec.size()-2; i>=0; i--) {
- FlatNode fn=vec.elementAt(i);
- FlatNode dom=null;
- for(int j=0; j<(postdominator?fn.numNext():fn.numPrev()); j++) {
- FlatNode np=postdominator?fn.getNext(j):fn.getPrev(j);
- FlatNode ndom=domtable.get(np);
- if (ndom!=null) {
- if (dom==null)
- dom=np;
- else
- dom=intersect(dom,np);
- }
- }
- if (!domtable.containsKey(fn)||
- !domtable.get(fn).equals(dom)) {
- domtable.put(fn,dom);
- if (!childtree.containsKey(dom))
- childtree.put(dom, new HashSet<FlatNode>());
- childtree.get(dom).add(fn);
- changed=true;
- }
+ FlatNode fn=vec.elementAt(i);
+ FlatNode dom=null;
+ for(int j=0; j<(postdominator?fn.numNext():fn.numPrev()); j++) {
+ FlatNode np=postdominator?fn.getNext(j):fn.getPrev(j);
+ FlatNode ndom=domtable.get(np);
+ if (ndom!=null) {
+ if (dom==null)
+ dom=np;
+ else
+ dom=intersect(dom,np);
+ }
+ }
+ if (!domtable.containsKey(fn)||
+ !domtable.get(fn).equals(dom)) {
+ domtable.put(fn,dom);
+ if (!childtree.containsKey(dom))
+ childtree.put(dom, new HashSet<FlatNode>());
+ childtree.get(dom).add(fn);
+ changed=true;
+ }
}
}
}
int ifb=vecindex.get(fb).intValue();
while(ifa!=ifb) {
while (ifa<ifb) {
- fa=domtable.get(fa);
- ifa=vecindex.get(fa).intValue();
+ fa=domtable.get(fa);
+ ifa=vecindex.get(fa).intValue();
}
while (ifb<ifa) {
- fb=domtable.get(fb);
- ifb=vecindex.get(fb).intValue();
+ fb=domtable.get(fb);
+ ifb=vecindex.get(fb).intValue();
}
}
return fa;
while(!stack.isEmpty()) {
FlatNode fn=stack.peek();
for(int i=0; i<(postdominator?fn.numPrev():fn.numNext()); i++) {
- FlatNode next=postdominator?fn.getPrev(i):fn.getNext(i);
- if (!visited.contains(next)) {
- visited.add(next);
- stack.push(next);
- continue mainloop;
- }
+ FlatNode next=postdominator?fn.getPrev(i):fn.getNext(i);
+ if (!visited.contains(next)) {
+ visited.add(next);
+ stack.push(next);
+ continue mainloop;
+ }
}
//We're done with this item, return
vecindex.put(fn, new Integer(vec.size()));
analyzeMethod(md);
Set callees=cg.getCalleeSet(md);
for(Iterator it=callees.iterator(); it.hasNext(); ) {
- MethodDescriptor md2=(MethodDescriptor)it.next();
- if (!discovered.contains(md2)) {
- discovered.add(md2);
- toprocess.add(md2);
- }
+ MethodDescriptor md2=(MethodDescriptor)it.next();
+ if (!discovered.contains(md2)) {
+ discovered.add(md2);
+ toprocess.add(md2);
+ }
}
if (md.getClassDesc().getSymbol().equals(TypeUtil.ThreadClass)&&
md.getSymbol().equals("start")&&!md.getModifiers().isStatic()&&
md.numParameters()==0) {
- //start -> run link
- MethodDescriptor runmd=null;
- for(Iterator methodit=md.getClassDesc().getMethodTable().getSet("run").iterator(); methodit.hasNext(); ) {
- MethodDescriptor mdrun=(MethodDescriptor) methodit.next();
- if (mdrun.numParameters()!=0||mdrun.getModifiers().isStatic())
- continue;
- runmd=mdrun;
- break;
- }
- if (runmd!=null) {
- Set runmethodset=cg.getMethods(runmd);
- for(Iterator it=runmethodset.iterator(); it.hasNext(); ) {
- MethodDescriptor md2=(MethodDescriptor)it.next();
- if (!discovered.contains(md2)) {
- discovered.add(md2);
- toprocess.add(md2);
- }
- }
- } else throw new Error("Can't find run method");
+ //start -> run link
+ MethodDescriptor runmd=null;
+ for(Iterator methodit=md.getClassDesc().getMethodTable().getSet("run").iterator(); methodit.hasNext(); ) {
+ MethodDescriptor mdrun=(MethodDescriptor) methodit.next();
+ if (mdrun.numParameters()!=0||mdrun.getModifiers().isStatic())
+ continue;
+ runmd=mdrun;
+ break;
+ }
+ if (runmd!=null) {
+ Set runmethodset=cg.getMethods(runmd);
+ for(Iterator it=runmethodset.iterator(); it.hasNext(); ) {
+ MethodDescriptor md2=(MethodDescriptor)it.next();
+ if (!discovered.contains(md2)) {
+ discovered.add(md2);
+ toprocess.add(md2);
+ }
+ }
+ } else throw new Error("Can't find run method");
}
}
boolean changed=true;
while(changed) {
changed=false;
for(Iterator it=discovered.iterator(); it.hasNext(); ) {
- MethodDescriptor md=(MethodDescriptor)it.next();
- Set callees=cg.getCalleeSet(md);
- for(Iterator cit=callees.iterator(); cit.hasNext(); ) {
- MethodDescriptor md2=(MethodDescriptor)cit.next();
- if (fields.get(md).addAll(fields.get(md2)))
- changed=true;
- if (arrays.get(md).addAll(arrays.get(md2)))
- changed=true;
- if (fieldsrd.get(md).addAll(fieldsrd.get(md2)))
- changed=true;
- if (arraysrd.get(md).addAll(arraysrd.get(md2)))
- changed=true;
- if (containsAtomic.contains(md2)) {
- if (containsAtomic.add(md))
- changed=true;
- }
- if (containsBarrier.contains(md2)) {
- if (containsBarrier.add(md))
- changed=true;
- }
- }
+ MethodDescriptor md=(MethodDescriptor)it.next();
+ Set callees=cg.getCalleeSet(md);
+ for(Iterator cit=callees.iterator(); cit.hasNext(); ) {
+ MethodDescriptor md2=(MethodDescriptor)cit.next();
+ if (fields.get(md).addAll(fields.get(md2)))
+ changed=true;
+ if (arrays.get(md).addAll(arrays.get(md2)))
+ changed=true;
+ if (fieldsrd.get(md).addAll(fieldsrd.get(md2)))
+ changed=true;
+ if (arraysrd.get(md).addAll(arraysrd.get(md2)))
+ changed=true;
+ if (containsAtomic.contains(md2)) {
+ if (containsAtomic.add(md))
+ changed=true;
+ }
+ if (containsBarrier.contains(md2)) {
+ if (containsBarrier.add(md))
+ changed=true;
+ }
+ }
}
}
}
for(Iterator it=methodset.iterator(); it.hasNext(); ) {
MethodDescriptor md2=(MethodDescriptor)it.next();
if (containsAtomic.contains(md2))
- return true;
+ return true;
}
return false;
}
for(Iterator it=methodset.iterator(); it.hasNext(); ) {
MethodDescriptor md2=(MethodDescriptor)it.next();
if (containsBarrier.contains(md2))
- return true;
+ return true;
}
return false;
}
for(Iterator it=methodset.iterator(); it.hasNext(); ) {
MethodDescriptor md2=(MethodDescriptor)it.next();
if (fields.containsKey(md2))
- s.addAll(fields.get(md2));
+ s.addAll(fields.get(md2));
}
return s;
}
for(Iterator it=methodset.iterator(); it.hasNext(); ) {
MethodDescriptor md2=(MethodDescriptor)it.next();
if (arrays.containsKey(md2))
- s.addAll(arrays.get(md2));
+ s.addAll(arrays.get(md2));
}
return s;
}
for(Iterator it=methodset.iterator(); it.hasNext(); ) {
MethodDescriptor md2=(MethodDescriptor)it.next();
if (fieldsrd.containsKey(md2))
- s.addAll(fieldsrd.get(md2));
+ s.addAll(fieldsrd.get(md2));
}
return s;
}
for(Iterator it=methodset.iterator(); it.hasNext(); ) {
MethodDescriptor md2=(MethodDescriptor)it.next();
if (arraysrd.containsKey(md2))
- s.addAll(arraysrd.get(md2));
+ s.addAll(arraysrd.get(md2));
}
return s;
}
for(Iterator it=fm.getNodeSet().iterator(); it.hasNext(); ) {
FlatNode fn=(FlatNode)it.next();
if (fn.kind()==FKind.FlatSetElementNode) {
- FlatSetElementNode fsen=(FlatSetElementNode)fn;
- arrays.get(md).add(fsen.getDst().getType());
+ FlatSetElementNode fsen=(FlatSetElementNode)fn;
+ arrays.get(md).add(fsen.getDst().getType());
} else if (fn.kind()==FKind.FlatElementNode) {
- FlatElementNode fen=(FlatElementNode)fn;
- arraysrd.get(md).add(fen.getSrc().getType());
+ FlatElementNode fen=(FlatElementNode)fn;
+ arraysrd.get(md).add(fen.getSrc().getType());
} else if (fn.kind()==FKind.FlatSetFieldNode) {
- FlatSetFieldNode fsfn=(FlatSetFieldNode)fn;
- fields.get(md).add(fsfn.getField());
+ FlatSetFieldNode fsfn=(FlatSetFieldNode)fn;
+ fields.get(md).add(fsfn.getField());
} else if (fn.kind()==FKind.FlatFieldNode) {
- FlatFieldNode ffn=(FlatFieldNode)fn;
- fieldsrd.get(md).add(ffn.getField());
+ FlatFieldNode ffn=(FlatFieldNode)fn;
+ fieldsrd.get(md).add(ffn.getField());
} else if (fn.kind()==FKind.FlatAtomicEnterNode) {
- containsAtomic.add(md);
+ containsAtomic.add(md);
} else if (fn.kind()==FKind.FlatCall) {
- MethodDescriptor mdcall=((FlatCall)fn).getMethod();
- if (mdcall.getSymbol().equals("enterBarrier")&&
- mdcall.getClassDesc().getSymbol().equals("Barrier")) {
- containsBarrier.add(md);
- containsBarrier.add(mdcall);
- }
- //treat lock acquire the same as a barrier
- if ((mdcall.getSymbol().equals("MonitorEnter")||mdcall.getSymbol().equals("MonitorExit")||mdcall.getSymbol().equals("wait"))&&
- mdcall.getClassDesc().getSymbol().equals("Object")) {
- containsBarrier.add(md);
- containsBarrier.add(mdcall);
- }
+ MethodDescriptor mdcall=((FlatCall)fn).getMethod();
+ if (mdcall.getSymbol().equals("enterBarrier")&&
+ mdcall.getClassDesc().getSymbol().equals("Barrier")) {
+ containsBarrier.add(md);
+ containsBarrier.add(mdcall);
+ }
+ //treat lock acquire the same as a barrier
+ if ((mdcall.getSymbol().equals("MonitorEnter")||mdcall.getSymbol().equals("MonitorExit")||mdcall.getSymbol().equals("wait"))&&
+ mdcall.getClassDesc().getSymbol().equals("Object")) {
+ containsBarrier.add(md);
+ containsBarrier.add(mdcall);
+ }
}
}
}
* <code>LoopFinder</code> implements Dominator Tree Loop detection.
*
* @author Brian Demsky <bdemsky@mit.edu>
- * @version $Id: LoopFinder.java,v 1.4 2011/04/27 20:34:22 bdemsky Exp $
+ * @version $Id: LoopFinder.java,v 1.5 2011/04/27 20:51:36 bdemsky Exp $
*/
public class LoopFinder implements Loops {
//Add it to the tree, complain if oddness
if (addnode(A, root)!=1)
- System.out.println("Evil Error in LoopFinder while building tree.");
+ System.out.println("Evil Error in LoopFinder while building tree.");
}
}
//Do we share headers?
if (treenode.header!=A.header) {
- //No... Loop through our children to see if they want this
- //node.
+ //No... Loop through our children to see if they want this
+ //node.
- //Use integers for tri-state:
- //0=not stored here, 1=stored and everything is good
- //2=combined 2 natural loops with same header...need cleanup
+ //Use integers for tri-state:
+ //0=not stored here, 1=stored and everything is good
+ //2=combined 2 natural loops with same header...need cleanup
- int stored=0;
- Iterator iterate=treenode.children.iterator();
- Loop temp=new Loop();
- while (iterate.hasNext()) {
- temp=(Loop) iterate.next();
- stored=addnode(A,temp);
- if (stored!=0) break;
- }
+ int stored=0;
+ Iterator iterate=treenode.children.iterator();
+ Loop temp=new Loop();
+ while (iterate.hasNext()) {
+ temp=(Loop) iterate.next();
+ stored=addnode(A,temp);
+ if (stored!=0) break;
+ }
- //See what our children did for us
+ //See what our children did for us
- if (stored==0) {
- //We get a new child...
- treenode.children.add(A);
- temp=A;
- }
+ if (stored==0) {
+ //We get a new child...
+ treenode.children.add(A);
+ temp=A;
+ }
- //Need to do cleanup for case 0 or 2
- //temp points to the new child
+ //Need to do cleanup for case 0 or 2
+ //temp points to the new child
- if (stored!=1) {
+ if (stored!=1) {
- //Have to make sure that none of the nodes under this one
- //are children of the new node
+ //Have to make sure that none of the nodes under this one
+ //are children of the new node
- Iterator iterate2=treenode.children.iterator();
- temp.parent=treenode;
+ Iterator iterate2=treenode.children.iterator();
+ temp.parent=treenode;
- //Loop through the children
- while (iterate2.hasNext()) {
- Loop temp2=(Loop)iterate2.next();
+ //Loop through the children
+ while (iterate2.hasNext()) {
+ Loop temp2=(Loop)iterate2.next();
- //Don't look at the new node...otherwise we will create
- //a unreachable subtree
+ //Don't look at the new node...otherwise we will create
+ //a unreachable subtree
- if (temp2!=temp)
- //If the new node has a childs header
- //give the child up to it...
+ if (temp2!=temp)
+ //If the new node has a childs header
+ //give the child up to it...
- if (temp.entries.contains(temp2.header)) {
- temp.children.add(temp2);
- iterate2.remove();
- }
- }
- }
+ if (temp.entries.contains(temp2.header)) {
+ temp.children.add(temp2);
+ iterate2.remove();
+ }
+ }
+ }
- //We fixed everything...let our parents know
- return 1;
+ //We fixed everything...let our parents know
+ return 1;
} else {
- //need to combine loops
- while (!A.entries.isEmpty()) {
- FlatNode node=(FlatNode)A.entries.iterator().next();
- A.entries.remove(node);
- treenode.entries.add(node);
- }
- //let the previous caller know that they have stuff todo
- return 2;
+ //need to combine loops
+ while (!A.entries.isEmpty()) {
+ FlatNode node=(FlatNode)A.entries.iterator().next();
+ A.entries.remove(node);
+ treenode.entries.add(node);
+ }
+ //let the previous caller know that they have stuff todo
+ return 2;
}
//We aren't adopting the new node
else return 0;
Set<FlatNode> children=dominator.children(current_node);
if (children!=null) {
- for(Iterator<FlatNode> it=children.iterator(); it.hasNext(); ) {
- FlatNode fn=it.next();
- if (fn!=current_node)
- stk.push(fn);
- }
+ for(Iterator<FlatNode> it=children.iterator(); it.hasNext(); ) {
+ FlatNode fn=it.next();
+ if (fn!=current_node)
+ stk.push(fn);
+ }
}
}
}
//find the node we jump back too
while ((temp!=hc)&&
(temp_to!=temp)) {
- temp=dominator.idom(temp);
+ temp=dominator.idom(temp);
}
//If we found the node we jumped back to
if (temp_to==temp) {
- //found a loop
- A.entries.add(temp); //Push the header
- A.header=temp;
- B.add(q); //Put the backedge in the todo list
-
- //Starting with the backedge, work on the incoming edges
- //until we get back to the loop header...
- //Then we have the entire natural loop
-
- while(!B.isEmpty()) {
- FlatNode newnode=(FlatNode)B.iterator().next();
- B.remove(newnode);
-
- //Add all of the new incoming edges that we haven't already
- //visited
- for (int j=0; j<newnode.numPrev(); j++) {
- FlatNode from=newnode.getPrev(j);
- if (!A.entries.contains(from))
- B.add(from);
- }
-
- //push the new node on our list of nodes in the loop
- A.entries.add(newnode);
- }
-
- //save our new loop
- setofloops.add(A);
+ //found a loop
+ A.entries.add(temp); //Push the header
+ A.header=temp;
+ B.add(q); //Put the backedge in the todo list
+
+ //Starting with the backedge, work on the incoming edges
+ //until we get back to the loop header...
+ //Then we have the entire natural loop
+
+ while(!B.isEmpty()) {
+ FlatNode newnode=(FlatNode)B.iterator().next();
+ B.remove(newnode);
+
+ //Add all of the new incoming edges that we haven't already
+ //visited
+ for (int j=0; j<newnode.numPrev(); j++) {
+ FlatNode from=newnode.getPrev(j);
+ if (!A.entries.contains(from))
+ B.add(from);
+ }
+
+ //push the new node on our list of nodes in the loop
+ A.entries.add(newnode);
+ }
+
+ //save our new loop
+ setofloops.add(A);
}
}
}
} else {
/* Check whether it is safe to reuse values. */
for(Iterator elit=elements.iterator(); elit.hasNext(); ) {
- FlatNode fn=(FlatNode)elit.next();
- if (fn.kind()==FKind.FlatAtomicEnterNode||
- fn.kind()==FKind.FlatAtomicExitNode) {
- unsafe=true;
- break;
- } else if (fn.kind()==FKind.FlatCall) {
- FlatCall fcall=(FlatCall)fn;
- MethodDescriptor md=fcall.getMethod();
- Set<FieldDescriptor> f=gft.getFieldsAll(md);
- Set<TypeDescriptor> t=gft.getArraysAll(md);
- if (f!=null)
- fields.addAll(f);
- if (t!=null)
- types.addAll(t);
- if (gft.containsAtomicAll(md)||gft.containsBarrierAll(md)) {
- unsafe=true;
- }
- } else if (fn.kind()==FKind.FlatSetFieldNode) {
- FlatSetFieldNode fsfn=(FlatSetFieldNode)fn;
- fields.add(fsfn.getField());
- } else if (fn.kind()==FKind.FlatSetElementNode) {
- FlatSetElementNode fsen=(FlatSetElementNode)fn;
- types.add(fsen.getDst().getType());
- }
+ FlatNode fn=(FlatNode)elit.next();
+ if (fn.kind()==FKind.FlatAtomicEnterNode||
+ fn.kind()==FKind.FlatAtomicExitNode) {
+ unsafe=true;
+ break;
+ } else if (fn.kind()==FKind.FlatCall) {
+ FlatCall fcall=(FlatCall)fn;
+ MethodDescriptor md=fcall.getMethod();
+ Set<FieldDescriptor> f=gft.getFieldsAll(md);
+ Set<TypeDescriptor> t=gft.getArraysAll(md);
+ if (f!=null)
+ fields.addAll(f);
+ if (t!=null)
+ types.addAll(t);
+ if (gft.containsAtomicAll(md)||gft.containsBarrierAll(md)) {
+ unsafe=true;
+ }
+ } else if (fn.kind()==FKind.FlatSetFieldNode) {
+ FlatSetFieldNode fsfn=(FlatSetFieldNode)fn;
+ fields.add(fsfn.getField());
+ } else if (fn.kind()==FKind.FlatSetElementNode) {
+ FlatSetElementNode fsen=(FlatSetElementNode)fn;
+ types.add(fsen.getDst().getType());
+ }
}
}
changed=false;
nextfn:
for(Iterator tpit=toprocess.iterator(); tpit.hasNext(); ) {
- FlatNode fn=(FlatNode)tpit.next();
- switch(fn.kind()) {
- case FKind.FlatOpNode:
- int op=((FlatOpNode)fn).getOp().getOp();
- if (op==Operation.DIV||op==Operation.MOD||
- checkNode(fn,elements)||
- !unsafe&&!dominatorset.contains(fn)) {
- continue nextfn;
- }
- break;
+ FlatNode fn=(FlatNode)tpit.next();
+ switch(fn.kind()) {
+ case FKind.FlatOpNode:
+ int op=((FlatOpNode)fn).getOp().getOp();
+ if (op==Operation.DIV||op==Operation.MOD||
+ checkNode(fn,elements)||
+ !unsafe&&!dominatorset.contains(fn)) {
+ continue nextfn;
+ }
+ break;
- case FKind.FlatInstanceOfNode:
- if (checkNode(fn,elements)||
- !unsafe&&!dominatorset.contains(fn)) {
- continue nextfn;
- }
- break;
+ case FKind.FlatInstanceOfNode:
+ if (checkNode(fn,elements)||
+ !unsafe&&!dominatorset.contains(fn)) {
+ continue nextfn;
+ }
+ break;
- case FKind.FlatElementNode:
- if (unsafe||dominatorset==null||
- !dominatorset.contains(fn)||
- checkNode(fn,elements))
- continue nextfn;
- TypeDescriptor td=((FlatElementNode)fn).getSrc().getType();
- for(Iterator<TypeDescriptor> tdit=types.iterator(); tdit.hasNext(); ) {
- TypeDescriptor td2=tdit.next();
- if (typeutil.isSuperorType(td,td2)||
- typeutil.isSuperorType(td2,td)) {
- continue nextfn;
- }
- }
- if (isLeaf)
- tounroll.add(entrance);
- break;
+ case FKind.FlatElementNode:
+ if (unsafe||dominatorset==null||
+ !dominatorset.contains(fn)||
+ checkNode(fn,elements))
+ continue nextfn;
+ TypeDescriptor td=((FlatElementNode)fn).getSrc().getType();
+ for(Iterator<TypeDescriptor> tdit=types.iterator(); tdit.hasNext(); ) {
+ TypeDescriptor td2=tdit.next();
+ if (typeutil.isSuperorType(td,td2)||
+ typeutil.isSuperorType(td2,td)) {
+ continue nextfn;
+ }
+ }
+ if (isLeaf)
+ tounroll.add(entrance);
+ break;
- case FKind.FlatFieldNode:
- if (unsafe||dominatorset==null||
- !dominatorset.contains(fn)||
- fields.contains(((FlatFieldNode)fn).getField())||
- checkNode(fn,elements)) {
- continue nextfn;
- }
- if (isLeaf)
- tounroll.add(entrance);
- break;
+ case FKind.FlatFieldNode:
+ if (unsafe||dominatorset==null||
+ !dominatorset.contains(fn)||
+ fields.contains(((FlatFieldNode)fn).getField())||
+ checkNode(fn,elements)) {
+ continue nextfn;
+ }
+ if (isLeaf)
+ tounroll.add(entrance);
+ break;
- default:
- continue nextfn;
- }
- //mark to hoist
- if (hoisted.add(fn))
- changed=true;
- table.get(entrance).add(fn);
+ default:
+ continue nextfn;
+ }
+ //mark to hoist
+ if (hoisted.add(fn))
+ changed=true;
+ table.get(entrance).add(fn);
}
}
}
for (int i=0; i<entrance.numPrev(); i++) {
FlatNode incoming=entrance.getPrev(i);
if (elements.contains(incoming)) {
- HashSet domset=new HashSet();
- domset.add(incoming);
- FlatNode tmp=incoming;
- while(tmp!=entrance) {
- tmp=domtree.idom(tmp);
- domset.add(tmp);
- }
- if (first) {
- dominatorset=domset;
- first=false;
- } else {
- for(Iterator it=dominatorset.iterator(); it.hasNext(); ) {
- FlatNode fn=(FlatNode)it.next();
- if (!domset.contains(fn))
- it.remove();
- }
- }
+ HashSet domset=new HashSet();
+ domset.add(incoming);
+ FlatNode tmp=incoming;
+ while(tmp!=entrance) {
+ tmp=domtree.idom(tmp);
+ domset.add(tmp);
+ }
+ if (first) {
+ dominatorset=domset;
+ first=false;
+ } else {
+ for(Iterator it=dominatorset.iterator(); it.hasNext(); ) {
+ FlatNode fn=(FlatNode)it.next();
+ if (!domset.contains(fn))
+ it.remove();
+ }
+ }
}
}
return dominatorset;
TempDescriptor t=uses[i];
Set<FlatNode> defset=usedef.defMap(fn, t);
for(Iterator<FlatNode> defit=defset.iterator(); defit.hasNext(); ) {
- FlatNode def=defit.next();
- if (elements.contains(def)&&defset.size()>1)
- return true;
- if (elements.contains(def)&&!hoisted.contains(def))
- return true;
+ FlatNode def=defit.next();
+ if (elements.contains(def)&&defset.size()>1)
+ return true;
+ if (elements.contains(def)&&!hoisted.contains(def))
+ return true;
}
}
return false;
//deal with the possiblity we already hoisted this node
if (clonemap.containsKey(fn)) {
- FlatNode fnnew=clonemap.get(fn);
- TempDescriptor writenew[]=fnnew.writesTemps();
- t.addPair(writes[0],writenew[0]);
- if (fn==entrance)
- entrance=map.get(fn);
- continue;
+ FlatNode fnnew=clonemap.get(fn);
+ TempDescriptor writenew[]=fnnew.writesTemps();
+ t.addPair(writes[0],writenew[0]);
+ if (fn==entrance)
+ entrance=map.get(fn);
+ continue;
}
//build hoisted version
fnnew.rewriteUse(t);
for(int j=0; j<writes.length; j++) {
- if (writes[j]!=null) {
- TempDescriptor cp=writes[j].createNew();
- t.addPair(writes[j],cp);
- }
+ if (writes[j]!=null) {
+ TempDescriptor cp=writes[j].createNew();
+ t.addPair(writes[j],cp);
+ }
}
fnnew.rewriteDef(t);
//add hoisted version to chain
if (first==null)
- first=fnnew;
+ first=fnnew;
else
- last.addNext(fnnew);
+ last.addNext(fnnew);
last=fnnew;
/* Splice out old node */
if (writes.length==1) {
- FlatOpNode fon=new FlatOpNode(writes[0], t.tempMap(writes[0]), null, new Operation(Operation.ASSIGN));
- fn.replace(fon);
- ntoomap.put(fon, fn);
- map.put(fn, fon);
- if (fn==entrance)
- entrance=fon;
+ FlatOpNode fon=new FlatOpNode(writes[0], t.tempMap(writes[0]), null, new Operation(Operation.ASSIGN));
+ fn.replace(fon);
+ ntoomap.put(fon, fn);
+ map.put(fn, fon);
+ if (fn==entrance)
+ entrance=fon;
} else if (writes.length>1) {
- throw new Error();
+ throw new Error();
}
}
/* If the chain is empty, we can exit now */
FlatNode prev=prevarray[i];
if (!lelements.contains(ntooremap(prev))) {
- //need to fix this edge
- for(int j=0; j<prev.numNext(); j++) {
- if (prev.getNext(j)==entrance)
- prev.setNext(j, first);
- }
+ //need to fix this edge
+ for(int j=0; j<prev.numNext(); j++) {
+ if (prev.getNext(j)==entrance)
+ prev.setNext(j, first);
+ }
}
}
last.addNext(entrance);
FlatNode copy=nfn.clone(t);
FlatNode copyend=copy;
if (tohoist.contains(fn)) {
- //deal with the possiblity we already hoisted this node
- if (clonemap.containsKey(fn)) {
- FlatNode fnnew=clonemap.get(fn);
- TempDescriptor writenew[]=fnnew.writesTemps();
- temptable.put(nfn, writenew[0]);
- } else {
- TempDescriptor[] writes=nfn.writesTemps();
- TempDescriptor tmp=writes[0];
- TempDescriptor ntmp=tmp.createNew();
- temptable.put(nfn, ntmp);
- copyend=new FlatOpNode(ntmp, tmp, null, new Operation(Operation.ASSIGN));
- copy.addNext(copyend);
- }
+ //deal with the possiblity we already hoisted this node
+ if (clonemap.containsKey(fn)) {
+ FlatNode fnnew=clonemap.get(fn);
+ TempDescriptor writenew[]=fnnew.writesTemps();
+ temptable.put(nfn, writenew[0]);
+ } else {
+ TempDescriptor[] writes=nfn.writesTemps();
+ TempDescriptor tmp=writes[0];
+ TempDescriptor ntmp=tmp.createNew();
+ temptable.put(nfn, ntmp);
+ copyend=new FlatOpNode(ntmp, tmp, null, new Operation(Operation.ASSIGN));
+ copy.addNext(copyend);
+ }
}
copytable.put(nfn, copy);
copyendtable.put(nfn, copyend);
fn=otonremap(fn);
FlatNode copyend=copyendtable.get(fn);
for(int i=0; i<fn.numNext(); i++) {
- FlatNode nnext=fn.getNext(i);
- if (nnext==entrance) {
- /* Back to loop header...point to old graph */
- copyend.setNewNext(i,nnext);
- } else if (lelements.contains(ntooremap(nnext))) {
- /* In graph...point to first graph */
- copyend.setNewNext(i,copytable.get(nnext));
- } else {
- /* Outside loop */
- /* Just goto same place as before */
- copyend.setNewNext(i,nnext);
- }
+ FlatNode nnext=fn.getNext(i);
+ if (nnext==entrance) {
+ /* Back to loop header...point to old graph */
+ copyend.setNewNext(i,nnext);
+ } else if (lelements.contains(ntooremap(nnext))) {
+ /* In graph...point to first graph */
+ copyend.setNewNext(i,copytable.get(nnext));
+ } else {
+ /* Outside loop */
+ /* Just goto same place as before */
+ copyend.setNewNext(i,nnext);
+ }
}
}
FlatNode prev=prevarray[i];
if (!lelements.contains(ntooremap(prev))) {
- //need to fix this edge
- for(int j=0; j<prev.numNext(); j++) {
- if (prev.getNext(j)==entrance) {
- prev.setNext(j, first);
- }
- }
+ //need to fix this edge
+ for(int j=0; j<prev.numNext(); j++) {
+ if (prev.getNext(j)==entrance) {
+ prev.setNext(j, first);
+ }
+ }
}
}
FlatNode fn=(FlatNode)it.next();
FlatNode nfn=otonremap(fn);
if (tohoist.contains(fn)) {
- TempDescriptor[] writes=nfn.writesTemps();
- TempDescriptor tmp=writes[0];
- FlatOpNode fon=new FlatOpNode(tmp, temptable.get(nfn), null, new Operation(Operation.ASSIGN));
- nfn.replace(fon);
+ TempDescriptor[] writes=nfn.writesTemps();
+ TempDescriptor tmp=writes[0];
+ FlatOpNode fon=new FlatOpNode(tmp, temptable.get(nfn), null, new Operation(Operation.ASSIGN));
+ nfn.replace(fon);
}
}
}
HashSet<TempFlatPair> s=new HashSet<TempFlatPair>();
Set<TempDescriptor> liveset=livemap.get(fn);
for(int i=0; i<fn.numPrev(); i++) {
- FlatNode prev=fn.getPrev(i);
- Set<TempFlatPair> prevs=tmp.get(prev);
- if (prevs!=null) {
+ FlatNode prev=fn.getPrev(i);
+ Set<TempFlatPair> prevs=tmp.get(prev);
+ if (prevs!=null) {
nexttfp:
- for(Iterator<TempFlatPair> tfit=prevs.iterator(); tfit.hasNext(); ) {
- TempFlatPair tfp=tfit.next();
- if (!liveset.contains(tfp.t))
- continue;
- for(int j=0; j<fnwrites.length; j++) {
- if (tfp.t==fnwrites[j])
- continue nexttfp;
- }
- s.add(tfp);
- }
- }
- for(int j=0; j<fnwrites.length; j++) {
- TempFlatPair tfp=new TempFlatPair(fnwrites[j], fn);
- s.add(tfp);
- }
+ for(Iterator<TempFlatPair> tfit=prevs.iterator(); tfit.hasNext(); ) {
+ TempFlatPair tfp=tfit.next();
+ if (!liveset.contains(tfp.t))
+ continue;
+ for(int j=0; j<fnwrites.length; j++) {
+ if (tfp.t==fnwrites[j])
+ continue nexttfp;
+ }
+ s.add(tfp);
+ }
+ }
+ for(int j=0; j<fnwrites.length; j++) {
+ TempFlatPair tfp=new TempFlatPair(fnwrites[j], fn);
+ s.add(tfp);
+ }
}
if (!tmp.containsKey(fn)||
!tmp.get(fn).equals(s)) {
- tmp.put(fn,s);
- for(int i=0; i<fn.numNext(); i++)
- toanalyze.add(fn.getNext(i));
+ tmp.put(fn,s);
+ for(int i=0; i<fn.numNext(); i++)
+ toanalyze.add(fn.getNext(i));
}
}
Set<FlatNode> fset=fm.getNodeSet();
Set<TempFlatPair> tfpset=tmp.get(fn);
for(int i=0; i<fnreads.length; i++) {
- TempDescriptor readt=fnreads[i];
- for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
- TempFlatPair tfp=tfpit.next();
- if (tfp.t==readt) {
- //have use
- if (!uses.containsKey(tfp))
- uses.put(tfp,new HashSet<FlatNode>());
- uses.get(tfp).add(fn);
- TempFlatPair readtfp=new TempFlatPair(readt,fn);
- if (!defs.containsKey(readtfp))
- defs.put(readtfp,new HashSet<FlatNode>());
- defs.get(readtfp).add(tfp.f);
- }
- }
+ TempDescriptor readt=fnreads[i];
+ for(Iterator<TempFlatPair> tfpit=tfpset.iterator(); tfpit.hasNext(); ) {
+ TempFlatPair tfp=tfpit.next();
+ if (tfp.t==readt) {
+ //have use
+ if (!uses.containsKey(tfp))
+ uses.put(tfp,new HashSet<FlatNode>());
+ uses.get(tfp).add(fn);
+ TempFlatPair readtfp=new TempFlatPair(readt,fn);
+ if (!defs.containsKey(readtfp))
+ defs.put(readtfp,new HashSet<FlatNode>());
+ defs.get(readtfp).add(tfp.f);
+ }
+ }
}
}
}
FlatNode fn=(FlatNode)toprocess.iterator().next();
toprocess.remove(fn);
for(int i=0; i<fn.numNext(); i++) {
- FlatNode nnext=fn.getNext(i);
- if (!discovered.contains(nnext)) {
- toprocess.add(nnext);
- discovered.add(nnext);
- }
+ FlatNode nnext=fn.getNext(i);
+ if (!discovered.contains(nnext)) {
+ toprocess.add(nnext);
+ discovered.add(nnext);
+ }
}
HashSet<TempDescriptor> nb=computeIntersection(fn);
TempDescriptor[] writes=fn.writesTemps();
for(int i=0; i<writes.length; i++) {
- nb.remove(writes[i]);
+ nb.remove(writes[i]);
}
switch(fn.kind()) {
case FKind.FlatSetElementNode:
{
- FlatSetElementNode fsen=(FlatSetElementNode)fn;
- if (!state.STMARRAY)
- nb.add(fsen.getDst());
- break;
+ FlatSetElementNode fsen=(FlatSetElementNode)fn;
+ if (!state.STMARRAY)
+ nb.add(fsen.getDst());
+ break;
}
case FKind.FlatSetFieldNode:
{
- FlatSetFieldNode fsfn=(FlatSetFieldNode)fn;
- nb.add(fsfn.getDst());
- break;
+ FlatSetFieldNode fsfn=(FlatSetFieldNode)fn;
+ nb.add(fsfn.getDst());
+ break;
}
case FKind.FlatOpNode:
{
- FlatOpNode fon=(FlatOpNode)fn;
- if (fon.getOp().getOp()==Operation.ASSIGN) {
- if (nb.contains(fon.getLeft())) {
- nb.add(fon.getDest());
- }
- }
- break;
+ FlatOpNode fon=(FlatOpNode)fn;
+ if (fon.getOp().getOp()==Operation.ASSIGN) {
+ if (nb.contains(fon.getLeft())) {
+ nb.add(fon.getDest());
+ }
+ }
+ break;
}
case FKind.FlatNew:
{
- FlatNew fnew=(FlatNew)fn;
- nb.add(fnew.getDst());
- break;
+ FlatNew fnew=(FlatNew)fn;
+ nb.add(fnew.getDst());
+ break;
}
default:
- //If we enter a transaction toss everything
- if (atomic.get(fn).intValue()>0&&
- atomic.get(fn.getPrev(0)).intValue()==0) {
- nb=new HashSet<TempDescriptor>();
- }
+ //If we enter a transaction toss everything
+ if (atomic.get(fn).intValue()>0&&
+ atomic.get(fn.getPrev(0)).intValue()==0) {
+ nb=new HashSet<TempDescriptor>();
+ }
}
if (!needbarrier.containsKey(fn)||
!needbarrier.get(fn).equals(nb)) {
- for(int i=0; i<fn.numNext(); i++) {
- FlatNode nnext=fn.getNext(i);
- toprocess.add(nnext);
- }
- needbarrier.put(fn,nb);
+ for(int i=0; i<fn.numNext(); i++) {
+ FlatNode nnext=fn.getNext(i);
+ toprocess.add(nnext);
+ }
+ needbarrier.put(fn,nb);
}
}
}
FlatNode fprev=fn.getPrev(i);
HashSet<TempDescriptor> hs=needbarrier.get(fprev);
if (hs!=null) {
- if (first) {
- tab.addAll(hs);
- first=false;
- } else {
- //Intersect sets
- for(Iterator<TempDescriptor> it=tab.iterator(); it.hasNext(); ) {
- TempDescriptor t=it.next();
- if (!hs.contains(t))
- it.remove();
- }
- }
+ if (first) {
+ tab.addAll(hs);
+ first=false;
+ } else {
+ //Intersect sets
+ for(Iterator<TempDescriptor> it=tab.iterator(); it.hasNext(); ) {
+ TempDescriptor t=it.next();
+ if (!hs.contains(t))
+ it.remove();
+ }
+ }
}
}
return tab;
for(Iterator it=g.set.iterator(); it.hasNext(); ) {
LocalExpression e=(LocalExpression)it.next();
if (e.t!=null)
- return e.t;
+ return e.t;
}
return null;
}
for(Iterator it=nodes.iterator(); it.hasNext(); ) {
FlatNode fn=(FlatNode)it.next();
if (fn.numPrev()>1)
- toanalyze.add(fn);
+ toanalyze.add(fn);
}
for(Iterator<FlatNode> it=toanalyze.iterator(); it.hasNext(); ) {
FlatNode fn=it.next();
Hashtable<LocalExpression, Group> table=new Hashtable<LocalExpression,Group>();
do {
- index=0;
- switch(fn.kind()) {
- case FKind.FlatOpNode: {
- FlatOpNode fon=(FlatOpNode)fn;
- Group left=getGroup(table, fon.getLeft());
- Group right=getGroup(table, fon.getRight());
- LocalExpression dst=new LocalExpression(fon.getDest());
- if (fon.getOp().getOp()==Operation.ASSIGN) {
- left.set.add(dst);
- kill(table, fon.getDest());
- table.put(dst, left);
- } else {
- LocalExpression e=new LocalExpression(left, right, fon.getOp());
- Group g=getGroup(table,e);
- TempDescriptor td=getTemp(g);
- if (td!=null) {
- FlatNode nfon=new FlatOpNode(fon.getDest(),td,null,new Operation(Operation.ASSIGN));
- fn.replace(nfon);
- }
- g.set.add(dst);
- kill(table, fon.getDest());
- table.put(dst,g);
- }
- break;
- }
+ index=0;
+ switch(fn.kind()) {
+ case FKind.FlatOpNode: {
+ FlatOpNode fon=(FlatOpNode)fn;
+ Group left=getGroup(table, fon.getLeft());
+ Group right=getGroup(table, fon.getRight());
+ LocalExpression dst=new LocalExpression(fon.getDest());
+ if (fon.getOp().getOp()==Operation.ASSIGN) {
+ left.set.add(dst);
+ kill(table, fon.getDest());
+ table.put(dst, left);
+ } else {
+ LocalExpression e=new LocalExpression(left, right, fon.getOp());
+ Group g=getGroup(table,e);
+ TempDescriptor td=getTemp(g);
+ if (td!=null) {
+ FlatNode nfon=new FlatOpNode(fon.getDest(),td,null,new Operation(Operation.ASSIGN));
+ fn.replace(nfon);
+ }
+ g.set.add(dst);
+ kill(table, fon.getDest());
+ table.put(dst,g);
+ }
+ break;
+ }
- case FKind.FlatLiteralNode: {
- FlatLiteralNode fln=(FlatLiteralNode)fn;
- LocalExpression e=new LocalExpression(fln.getValue());
- Group src=getGroup(table, e);
- LocalExpression dst=new LocalExpression(fln.getDst());
- src.set.add(dst);
- kill(table, fln.getDst());
- table.put(dst, src);
- break;
- }
+ case FKind.FlatLiteralNode: {
+ FlatLiteralNode fln=(FlatLiteralNode)fn;
+ LocalExpression e=new LocalExpression(fln.getValue());
+ Group src=getGroup(table, e);
+ LocalExpression dst=new LocalExpression(fln.getDst());
+ src.set.add(dst);
+ kill(table, fln.getDst());
+ table.put(dst, src);
+ break;
+ }
- case FKind.FlatFieldNode: {
- FlatFieldNode ffn=(FlatFieldNode) fn;
- Group src=getGroup(table, ffn.getSrc());
- LocalExpression e=new LocalExpression(src, ffn.getField());
- Group srcf=getGroup(table, e);
- LocalExpression dst=new LocalExpression(ffn.getDst());
- TempDescriptor td=getTemp(srcf);
- if (td!=null) {
- FlatOpNode fon=new FlatOpNode(ffn.getDst(),td,null,new Operation(Operation.ASSIGN));
- fn.replace(fon);
- }
- srcf.set.add(dst);
- kill(table, ffn.getDst());
- table.put(dst, srcf);
- break;
- }
+ case FKind.FlatFieldNode: {
+ FlatFieldNode ffn=(FlatFieldNode) fn;
+ Group src=getGroup(table, ffn.getSrc());
+ LocalExpression e=new LocalExpression(src, ffn.getField());
+ Group srcf=getGroup(table, e);
+ LocalExpression dst=new LocalExpression(ffn.getDst());
+ TempDescriptor td=getTemp(srcf);
+ if (td!=null) {
+ FlatOpNode fon=new FlatOpNode(ffn.getDst(),td,null,new Operation(Operation.ASSIGN));
+ fn.replace(fon);
+ }
+ srcf.set.add(dst);
+ kill(table, ffn.getDst());
+ table.put(dst, srcf);
+ break;
+ }
- case FKind.FlatElementNode: {
- FlatElementNode fen=(FlatElementNode) fn;
- Group src=getGroup(table, fen.getSrc());
- Group index=getGroup(table, fen.getIndex());
- LocalExpression e=new LocalExpression(src, fen.getSrc().getType(), index);
- Group srcf=getGroup(table, e);
- LocalExpression dst=new LocalExpression(fen.getDst());
- TempDescriptor td=getTemp(srcf);
- if (td!=null) {
- FlatOpNode fon=new FlatOpNode(fen.getDst(),td,null,new Operation(Operation.ASSIGN));
- fn.replace(fon);
- }
- srcf.set.add(dst);
- kill(table, fen.getDst());
- table.put(dst, srcf);
- break;
- }
+ case FKind.FlatElementNode: {
+ FlatElementNode fen=(FlatElementNode) fn;
+ Group src=getGroup(table, fen.getSrc());
+ Group index=getGroup(table, fen.getIndex());
+ LocalExpression e=new LocalExpression(src, fen.getSrc().getType(), index);
+ Group srcf=getGroup(table, e);
+ LocalExpression dst=new LocalExpression(fen.getDst());
+ TempDescriptor td=getTemp(srcf);
+ if (td!=null) {
+ FlatOpNode fon=new FlatOpNode(fen.getDst(),td,null,new Operation(Operation.ASSIGN));
+ fn.replace(fon);
+ }
+ srcf.set.add(dst);
+ kill(table, fen.getDst());
+ table.put(dst, srcf);
+ break;
+ }
- case FKind.FlatSetFieldNode: {
- FlatSetFieldNode fsfn=(FlatSetFieldNode)fn;
- Group dst=getGroup(table, fsfn.getDst());
- LocalExpression e=new LocalExpression(dst, fsfn.getField());
- Group dstf=getGroup(table, e);
- LocalExpression src=new LocalExpression(fsfn.getSrc());
- dstf.set.add(src);
- HashSet<FieldDescriptor> fields=new HashSet<FieldDescriptor>();
- fields.add(fsfn.getField());
- kill(table, fields, null, false, false);
- table.put(src, dstf);
- break;
- }
+ case FKind.FlatSetFieldNode: {
+ FlatSetFieldNode fsfn=(FlatSetFieldNode)fn;
+ Group dst=getGroup(table, fsfn.getDst());
+ LocalExpression e=new LocalExpression(dst, fsfn.getField());
+ Group dstf=getGroup(table, e);
+ LocalExpression src=new LocalExpression(fsfn.getSrc());
+ dstf.set.add(src);
+ HashSet<FieldDescriptor> fields=new HashSet<FieldDescriptor>();
+ fields.add(fsfn.getField());
+ kill(table, fields, null, false, false);
+ table.put(src, dstf);
+ break;
+ }
- case FKind.FlatSetElementNode: {
- FlatSetElementNode fsen=(FlatSetElementNode)fn;
- Group dst=getGroup(table, fsen.getDst());
- Group index=getGroup(table, fsen.getIndex());
- LocalExpression e=new LocalExpression(dst, fsen.getDst().getType(), index);
- Group dstf=getGroup(table, e);
- LocalExpression src=new LocalExpression(fsen.getSrc());
- dstf.set.add(src);
- HashSet<TypeDescriptor> arrays=new HashSet<TypeDescriptor>();
- arrays.add(fsen.getDst().getType());
- kill(table, null, arrays, false, false);
- table.put(src, dstf);
- break;
- }
+ case FKind.FlatSetElementNode: {
+ FlatSetElementNode fsen=(FlatSetElementNode)fn;
+ Group dst=getGroup(table, fsen.getDst());
+ Group index=getGroup(table, fsen.getIndex());
+ LocalExpression e=new LocalExpression(dst, fsen.getDst().getType(), index);
+ Group dstf=getGroup(table, e);
+ LocalExpression src=new LocalExpression(fsen.getSrc());
+ dstf.set.add(src);
+ HashSet<TypeDescriptor> arrays=new HashSet<TypeDescriptor>();
+ arrays.add(fsen.getDst().getType());
+ kill(table, null, arrays, false, false);
+ table.put(src, dstf);
+ break;
+ }
- case FKind.FlatCall: {
- //do side effects
- FlatCall fc=(FlatCall)fn;
- MethodDescriptor md=fc.getMethod();
- Set<FieldDescriptor> fields=gft.getFieldsAll(md);
- Set<TypeDescriptor> arrays=gft.getArraysAll(md);
- kill(table, fields, arrays, gft.containsAtomicAll(md), gft.containsBarrierAll(md));
- }
+ case FKind.FlatCall: {
+ //do side effects
+ FlatCall fc=(FlatCall)fn;
+ MethodDescriptor md=fc.getMethod();
+ Set<FieldDescriptor> fields=gft.getFieldsAll(md);
+ Set<TypeDescriptor> arrays=gft.getArraysAll(md);
+ kill(table, fields, arrays, gft.containsAtomicAll(md), gft.containsBarrierAll(md));
+ }
- default: {
- TempDescriptor[] writes=fn.writesTemps();
- for(int i=0; i<writes.length; i++) {
- kill(table,writes[i]);
- }
- }
- }
+ default: {
+ TempDescriptor[] writes=fn.writesTemps();
+ for(int i=0; i<writes.length; i++) {
+ kill(table,writes[i]);
+ }
+ }
+ }
} while(fn.numPrev()==1);
}
}
for(Iterator<LocalExpression> it=eset.iterator(); it.hasNext(); ) {
LocalExpression e=it.next();
if (isBarrier) {
- //make Barriers kill everything
- it.remove();
+ //make Barriers kill everything
+ it.remove();
} else if (isAtomic&&(e.td!=null||e.f!=null)) {
- Group g=tab.get(e);
- g.set.remove(e);
- it.remove();
+ Group g=tab.get(e);
+ g.set.remove(e);
+ it.remove();
} else if (e.td!=null) {
- //have array
- TypeDescriptor artd=e.td;
- for(Iterator<TypeDescriptor> arit=arrays.iterator(); arit.hasNext(); ) {
- TypeDescriptor td=arit.next();
- if (typeutil.isSuperorType(artd,td)||
- typeutil.isSuperorType(td,artd)) {
- Group g=tab.get(e);
- g.set.remove(e);
- it.remove();
- break;
- }
- }
+ //have array
+ TypeDescriptor artd=e.td;
+ for(Iterator<TypeDescriptor> arit=arrays.iterator(); arit.hasNext(); ) {
+ TypeDescriptor td=arit.next();
+ if (typeutil.isSuperorType(artd,td)||
+ typeutil.isSuperorType(td,artd)) {
+ Group g=tab.get(e);
+ g.set.remove(e);
+ it.remove();
+ break;
+ }
+ }
} else if (e.f!=null) {
- if (fields.contains(e.f)) {
- Group g=tab.get(e);
- g.set.remove(e);
- it.remove();
- }
+ if (fields.contains(e.f)) {
+ Group g=tab.get(e);
+ g.set.remove(e);
+ it.remove();
+ }
}
}
}
for(int i=0; i<fn.numPrev(); i++) {
FlatNode fprev=fn.getPrev(i);
if (inAccessible.containsKey(fprev)&&inAccessible.get(fprev).contains(tmp))
- return false;
+ return false;
}
return true;
}
MethodDescriptor pairmd=fnpair.getSecond();
HashSet<TempDescriptor> inAccessibleSet=new HashSet<TempDescriptor>();
for(int i=0; i<fn.numPrev(); i++) {
- Set<TempDescriptor> inAccess=inAccessible.get(fn.getPrev(i));
- if (inAccess!=null)
- inAccessibleSet.addAll(inAccess);
+ Set<TempDescriptor> inAccess=inAccessible.get(fn.getPrev(i));
+ if (inAccess!=null)
+ inAccessibleSet.addAll(inAccess);
}
switch(fn.kind()) {
case FKind.FlatSetFieldNode:
case FKind.FlatSetElementNode:
{
- TempDescriptor[] rdtmps=fn.readsTemps();
- for(int i=0; i<rdtmps.length; i++) {
- inAccessibleSet.remove(rdtmps[i]);
- }
- TempDescriptor[] wrtmps=fn.writesTemps();
- for(int i=0; i<wrtmps.length; i++) {
- inAccessibleSet.remove(wrtmps[i]);
- }
+ TempDescriptor[] rdtmps=fn.readsTemps();
+ for(int i=0; i<rdtmps.length; i++) {
+ inAccessibleSet.remove(rdtmps[i]);
+ }
+ TempDescriptor[] wrtmps=fn.writesTemps();
+ for(int i=0; i<wrtmps.length; i++) {
+ inAccessibleSet.remove(wrtmps[i]);
+ }
}
break;
case FKind.FlatCastNode:
case FKind.FlatOpNode:
{
- TempDescriptor[] rdtmps=fn.readsTemps();
- TempDescriptor[] wrtmps=fn.writesTemps();
- if (inAccessibleSet.contains(rdtmps[0]))
- inAccessibleSet.add(wrtmps[0]);
+ TempDescriptor[] rdtmps=fn.readsTemps();
+ TempDescriptor[] wrtmps=fn.writesTemps();
+ if (inAccessibleSet.contains(rdtmps[0]))
+ inAccessibleSet.add(wrtmps[0]);
}
break;
case FKind.FlatReturnNode:
{
- FlatReturnNode fr=(FlatReturnNode)fn;
- if (fr.getReturnTemp()!=null&&inAccessibleSet.contains(fr.getReturnTemp())) {
- //Need to inform callers
- Set<Pair<FlatCall, MethodDescriptor>> callset=methodmap.get(pairmd);
- for(Pair<FlatCall, MethodDescriptor> fcallpair : callset) {
- FlatCall fcall=fcallpair.getFirst();
- Set<TempDescriptor> inAccess=inAccessible.get(fcall);
- if (fcall.getReturnTemp()!=null&&!inAccess.contains(fcall.getReturnTemp())) {
- inAccess.add(fcall.getReturnTemp());
- for(int i=0; i<fcall.numNext(); i++) {
- toprocess.add(new Pair<FlatNode, MethodDescriptor>(fcall.getNext(i), fcallpair.getSecond()));
- }
- }
- }
- }
+ FlatReturnNode fr=(FlatReturnNode)fn;
+ if (fr.getReturnTemp()!=null&&inAccessibleSet.contains(fr.getReturnTemp())) {
+ //Need to inform callers
+ Set<Pair<FlatCall, MethodDescriptor>> callset=methodmap.get(pairmd);
+ for(Pair<FlatCall, MethodDescriptor> fcallpair : callset) {
+ FlatCall fcall=fcallpair.getFirst();
+ Set<TempDescriptor> inAccess=inAccessible.get(fcall);
+ if (fcall.getReturnTemp()!=null&&!inAccess.contains(fcall.getReturnTemp())) {
+ inAccess.add(fcall.getReturnTemp());
+ for(int i=0; i<fcall.numNext(); i++) {
+ toprocess.add(new Pair<FlatNode, MethodDescriptor>(fcall.getNext(i), fcallpair.getSecond()));
+ }
+ }
+ }
+ }
}
- continue nextNode;
+ continue nextNode;
case FKind.FlatSESEEnterNode:
case FKind.FlatSESEExitNode:
- continue nextNode;
+ continue nextNode;
case FKind.FlatCall: {
- FlatCall fcall=(FlatCall)fn;
- MethodDescriptor calledmethod=fcall.getMethod();
- Set methodsthatcouldbecalled=fcall.getThis()==null?callGraph.getMethods(calledmethod):
- callGraph.getMethods(calledmethod, fcall.getThis().getType());
- for(Object o : methodsthatcouldbecalled) {
- MethodDescriptor md=(MethodDescriptor)o;
- FlatMethod fm=state.getMethodFlat(md);
-
- if (!methodmap.containsKey(md))
- methodmap.put(md, new HashSet<Pair<FlatCall, MethodDescriptor>>());
-
- methodmap.get(md).add(new Pair<FlatCall, MethodDescriptor>(fcall, pairmd));
-
- HashSet<TempDescriptor> tmpinaccess=new HashSet<TempDescriptor>();
- for(int i=0; i<fm.numParameters(); i++) {
- TempDescriptor fmtmp=fm.getParameter(i);
- TempDescriptor tmpcall=fcall.getArgMatchingParamIndex(fm, i);
- if (inAccessibleSet.contains(tmpcall)) {
- tmpinaccess.add(fmtmp);
- }
- }
- if (!tmpinaccess.isEmpty()&&(!inAccessible.containsKey(fm)||!inAccessible.get(fm).containsAll(tmpinaccess))) {
- for(int i=0; i<fm.numNext(); i++)
- toprocess.add(new Pair<FlatNode, MethodDescriptor>(fm.getNext(i),md));
- if (!inAccessible.containsKey(fm))
- inAccessible.put(fm, new HashSet<TempDescriptor>());
- inAccessible.get(fm).addAll(tmpinaccess);
- }
- }
- //be sure not to wipe out return value or other inaccessible temps
- Set<TempDescriptor> oldtemps=inAccessible.get(fcall);
- if (oldtemps!=null)
- inAccessibleSet.addAll(oldtemps);
+ FlatCall fcall=(FlatCall)fn;
+ MethodDescriptor calledmethod=fcall.getMethod();
+ Set methodsthatcouldbecalled=fcall.getThis()==null?callGraph.getMethods(calledmethod):
+ callGraph.getMethods(calledmethod, fcall.getThis().getType());
+ for(Object o : methodsthatcouldbecalled) {
+ MethodDescriptor md=(MethodDescriptor)o;
+ FlatMethod fm=state.getMethodFlat(md);
+
+ if (!methodmap.containsKey(md))
+ methodmap.put(md, new HashSet<Pair<FlatCall, MethodDescriptor>>());
+
+ methodmap.get(md).add(new Pair<FlatCall, MethodDescriptor>(fcall, pairmd));
+
+ HashSet<TempDescriptor> tmpinaccess=new HashSet<TempDescriptor>();
+ for(int i=0; i<fm.numParameters(); i++) {
+ TempDescriptor fmtmp=fm.getParameter(i);
+ TempDescriptor tmpcall=fcall.getArgMatchingParamIndex(fm, i);
+ if (inAccessibleSet.contains(tmpcall)) {
+ tmpinaccess.add(fmtmp);
+ }
+ }
+ if (!tmpinaccess.isEmpty()&&(!inAccessible.containsKey(fm)||!inAccessible.get(fm).containsAll(tmpinaccess))) {
+ for(int i=0; i<fm.numNext(); i++)
+ toprocess.add(new Pair<FlatNode, MethodDescriptor>(fm.getNext(i),md));
+ if (!inAccessible.containsKey(fm))
+ inAccessible.put(fm, new HashSet<TempDescriptor>());
+ inAccessible.get(fm).addAll(tmpinaccess);
+ }
+ }
+ //be sure not to wipe out return value or other inaccessible temps
+ Set<TempDescriptor> oldtemps=inAccessible.get(fcall);
+ if (oldtemps!=null)
+ inAccessibleSet.addAll(oldtemps);
}
break;
default:
}
if (!inAccessibleSet.isEmpty()&&(!inAccessible.containsKey(fn)||!inAccessible.get(fn).equals(inAccessibleSet))) {
- inAccessible.put(fn, inAccessibleSet);
- for(int i=0; i<fn.numNext(); i++)
- toprocess.add(new Pair<FlatNode, MethodDescriptor>(fn.getNext(i),pairmd));
+ inAccessible.put(fn, inAccessibleSet);
+ for(int i=0; i<fn.numNext(); i++)
+ toprocess.add(new Pair<FlatNode, MethodDescriptor>(fn.getNext(i),pairmd));
}
}
}
FlatSESEExitNode seseexit=sese.getFlatExit();
HashSet<TempDescriptor> liveout=new HashSet<TempDescriptor>(liveness.getLiveOutTemps(sese.getfmEnclosing(), seseexit));
for(Iterator<TempDescriptor> tmpit=liveout.iterator(); tmpit.hasNext(); ) {
- TempDescriptor tmp=tmpit.next();
- if (!tmp.getType().isPtr())
- tmpit.remove();
+ TempDescriptor tmp=tmpit.next();
+ if (!tmp.getType().isPtr())
+ tmpit.remove();
}
inAccessible.put(seseexit, liveout);
for(int i=0; i<seseexit.numNext(); i++)
- toprocess.add(new Pair<FlatNode, MethodDescriptor>(seseexit.getNext(i),sese.getmdEnclosing()));
+ toprocess.add(new Pair<FlatNode, MethodDescriptor>(seseexit.getNext(i),sese.getmdEnclosing()));
}
Set<MethodDescriptor> methodSet=taskAnalysis.getMethodsWithSESEs();
MethodDescriptor md=methodStack.pop();
Set callers=callGraph.getCallerSet(md);
for(Object o : callers) {
- MethodDescriptor callermd=(MethodDescriptor)o;
- if (!canCallSESE.contains(callermd)) {
- //new method descriptor
- canCallSESE.add(callermd);
- methodStack.add(callermd);
- }
+ MethodDescriptor callermd=(MethodDescriptor)o;
+ if (!canCallSESE.contains(callermd)) {
+ //new method descriptor
+ canCallSESE.add(callermd);
+ methodStack.add(callermd);
+ }
}
}
for(MethodDescriptor md : canCallSESE) {
FlatMethod fm=state.getMethodFlat(md);
for(FlatNode fn : fm.getNodeSet()) {
- if (fn.kind()==FKind.FlatCall) {
- FlatCall fcall=(FlatCall)fn;
- MethodDescriptor calledmethod=fcall.getMethod();
- Set methodsthatcouldbecalled=fcall.getThis()==null?callGraph.getMethods(calledmethod):
- callGraph.getMethods(calledmethod, fcall.getThis().getType());
- boolean specialcall=false;
- for(Object o : methodsthatcouldbecalled) {
- MethodDescriptor callermd=(MethodDescriptor)o;
- if (canCallSESE.contains(callermd)) {
- //TODO: NEED TO BUILD MAP FROM MD -> CALLS
- specialcall=true;
- if (!methodmap.containsKey(callermd))
- methodmap.put(callermd, new HashSet<Pair<FlatCall, MethodDescriptor>>());
- methodmap.get(callermd).add(new Pair<FlatCall, MethodDescriptor>(fcall,md));
- }
- }
- if (specialcall) {
- Set<TempDescriptor> liveout=new HashSet<TempDescriptor>(liveness.getLiveOutTemps(fm, fcall));
- TempDescriptor returntmp=fcall.getReturnTemp();
- liveout.remove(returntmp);
- for(Iterator<TempDescriptor> tmpit=liveout.iterator(); tmpit.hasNext(); ) {
- TempDescriptor tmp=tmpit.next();
- if (!tmp.getType().isPtr())
- tmpit.remove();
- }
- inAccessible.put(fcall, liveout);
- for(int i=0; i<fcall.numNext(); i++)
- toprocess.add(new Pair<FlatNode, MethodDescriptor>(fcall.getNext(i),md));
- }
- }
+ if (fn.kind()==FKind.FlatCall) {
+ FlatCall fcall=(FlatCall)fn;
+ MethodDescriptor calledmethod=fcall.getMethod();
+ Set methodsthatcouldbecalled=fcall.getThis()==null?callGraph.getMethods(calledmethod):
+ callGraph.getMethods(calledmethod, fcall.getThis().getType());
+ boolean specialcall=false;
+ for(Object o : methodsthatcouldbecalled) {
+ MethodDescriptor callermd=(MethodDescriptor)o;
+ if (canCallSESE.contains(callermd)) {
+ //TODO: NEED TO BUILD MAP FROM MD -> CALLS
+ specialcall=true;
+ if (!methodmap.containsKey(callermd))
+ methodmap.put(callermd, new HashSet<Pair<FlatCall, MethodDescriptor>>());
+ methodmap.get(callermd).add(new Pair<FlatCall, MethodDescriptor>(fcall,md));
+ }
+ }
+ if (specialcall) {
+ Set<TempDescriptor> liveout=new HashSet<TempDescriptor>(liveness.getLiveOutTemps(fm, fcall));
+ TempDescriptor returntmp=fcall.getReturnTemp();
+ liveout.remove(returntmp);
+ for(Iterator<TempDescriptor> tmpit=liveout.iterator(); tmpit.hasNext(); ) {
+ TempDescriptor tmp=tmpit.next();
+ if (!tmp.getType().isPtr())
+ tmpit.remove();
+ }
+ inAccessible.put(fcall, liveout);
+ for(int i=0; i<fcall.numNext(); i++)
+ toprocess.add(new Pair<FlatNode, MethodDescriptor>(fcall.getNext(i),md));
+ }
+ }
}
}
computeFixPoint();
Taint taint = (Taint) entry.getKey();
Set<Effect> effectSet = (Set<Effect>)entry.getValue();
if (!effectSet.isEmpty()) {
- Iterator<Effect> effectIter = effectSet.iterator();
- while (effectIter.hasNext()) {
- Effect effect = (Effect) effectIter.next();
- addLiveInNodeEffect(taint, effect);
- }
+ Iterator<Effect> effectIter = effectSet.iterator();
+ while (effectIter.hasNext()) {
+ Effect effect = (Effect) effectIter.next();
+ addLiveInNodeEffect(taint, effect);
+ }
}
}
}
Taint taint = (Taint) entry.getKey();
Set<Effect> effectSet = (Set<Effect>)entry.getValue();
if (!effectSet.isEmpty()) {
- Iterator<Effect> effectIter = effectSet.iterator();
- while (effectIter.hasNext()) {
- Effect effect = (Effect) effectIter.next();
- if (taint.getVar().equals(var)) {
- addStallSiteEffect(taint, effect, cd);
- }
- }
+ Iterator<Effect> effectIter = effectSet.iterator();
+ while (effectIter.hasNext()) {
+ Effect effect = (Effect) effectIter.next();
+ if (taint.getVar().equals(var)) {
+ addStallSiteEffect(taint, effect, cd);
+ }
+ }
}
}
}
if ((conflictEdge.getVertexU().equals(nodeU) && conflictEdge.getVertexV().equals(nodeV))
|| (conflictEdge.getVertexU().equals(nodeV) && conflictEdge.getVertexV().equals(nodeU))) {
- if (conflictEdge.getType() == ConflictGraph.FINE_GRAIN_EDGE
- && type == ConflictGraph.COARSE_GRAIN_EDGE) {
- toBeRemoved = conflictEdge;
- break;
- } else if (conflictEdge.getType() == ConflictGraph.COARSE_GRAIN_EDGE
- && type == ConflictGraph.FINE_GRAIN_EDGE) {
- // ignore
- return;
- }
+ if (conflictEdge.getType() == ConflictGraph.FINE_GRAIN_EDGE
+ && type == ConflictGraph.COARSE_GRAIN_EDGE) {
+ toBeRemoved = conflictEdge;
+ break;
+ } else if (conflictEdge.getType() == ConflictGraph.COARSE_GRAIN_EDGE
+ && type == ConflictGraph.FINE_GRAIN_EDGE) {
+ // ignore
+ return;
+ }
}
}
if (currentNode.isInVarNode()) {
conflictType = calculateConflictType(currentNode, useReachInfo);
if (conflictType > ConflictGraph.NON_WRITE_CONFLICT) {
- addConflictEdge(conflictType, currentNode, currentNode);
- if (sitesToFlag != null) {
- sitesToFlag.addAll(currentNode.getFlatNewSet());
- }
+ addConflictEdge(conflictType, currentNode, currentNode);
+ if (sitesToFlag != null) {
+ sitesToFlag.addAll(currentNode.getFlatNewSet());
+ }
}
}
ConflictNode entryNode = entry.getValue();
if (currentNode.isStallSiteNode() && entryNode.isStallSiteNode()) {
- continue;
+ continue;
}
if ((currentNode.isInVarNode() && entryNode.isInVarNode())
&& (currentNode.getSESEIdentifier() == entryNode.getSESEIdentifier())
&& (currentNode.getVar().equals(entryNode.getVar()))) {
- continue;
+ continue;
}
if ((!currentNode.getID().equals(entryNodeID))
&& !(analyzedIDSet.contains(currentNode.getID() + entryNodeID) || analyzedIDSet
.contains(entryNodeID + currentNode.getID()))) {
- conflictType = calculateConflictType(currentNode, entryNode, useReachInfo);
- if (conflictType > ConflictGraph.NON_WRITE_CONFLICT) {
- addConflictEdge(conflictType, currentNode, entryNode);
- if (sitesToFlag != null) {
- sitesToFlag.addAll(currentNode.getFlatNewSet());
- sitesToFlag.addAll(entryNode.getFlatNewSet());
- }
- }
- analyzedIDSet.add(currentNode.getID() + entryNodeID);
+ conflictType = calculateConflictType(currentNode, entryNode, useReachInfo);
+ if (conflictType > ConflictGraph.NON_WRITE_CONFLICT) {
+ addConflictEdge(conflictType, currentNode, entryNode);
+ if (sitesToFlag != null) {
+ sitesToFlag.addAll(currentNode.getFlatNewSet());
+ sitesToFlag.addAll(entryNode.getFlatNewSet());
+ }
+ }
+ analyzedIDSet.add(currentNode.getID() + entryNodeID);
}
}
Iterator effectItrB = readTableB.entrySet().iterator();
while (effectItrB.hasNext()) {
- Map.Entry meB = (Map.Entry)effectItrB.next();
- Alloc asB = (Alloc) meB.getKey();
- Set<Effect> esB = (Set<Effect>)meB.getValue();
-
- for (Iterator iterator = strongUpdateSetA.iterator(); iterator.hasNext(); ) {
- Effect strongUpdateA = (Effect) iterator.next();
- for (Iterator iterator2 = esB.iterator(); iterator2.hasNext(); ) {
- Effect effectB = (Effect) iterator2.next();
-
- if (strongUpdateA.getAffectedAllocSite().equals(effectB.getAffectedAllocSite())
- && strongUpdateA.getField().equals(effectB.getField())) {
- if (useReachInfo) {
- FlatNew fnRoot1 = asA.getFlatNew();
- FlatNew fnRoot2 = asB.getFlatNew();
- FlatNew fnTarget = strongUpdateA.getAffectedAllocSite().getFlatNew();
- if (da.mayBothReachTarget(fmEnclosing, fnRoot1, fnRoot2, fnTarget)) {
- addCoarseEffect(nodeA, asA, strongUpdateA);
- if (!nodeA.equals(nodeB)) {
- addCoarseEffect(nodeB, asB, effectB);
- }
- conflictType = updateConflictType(conflictType, ConflictGraph.COARSE_GRAIN_EDGE);
- }
- } else {
- if (state.RCR) {
- // need coarse effects for RCR from just one pass
- addCoarseEffect(nodeA, asA, strongUpdateA);
- if (!nodeA.equals(nodeB)) {
- addCoarseEffect(nodeB, asB, effectB);
- }
- conflictType = ConflictGraph.COARSE_GRAIN_EDGE;
- } else {
- return ConflictGraph.COARSE_GRAIN_EDGE;
- }
- }
-
- }
-
- }
- }
+ Map.Entry meB = (Map.Entry)effectItrB.next();
+ Alloc asB = (Alloc) meB.getKey();
+ Set<Effect> esB = (Set<Effect>)meB.getValue();
+
+ for (Iterator iterator = strongUpdateSetA.iterator(); iterator.hasNext(); ) {
+ Effect strongUpdateA = (Effect) iterator.next();
+ for (Iterator iterator2 = esB.iterator(); iterator2.hasNext(); ) {
+ Effect effectB = (Effect) iterator2.next();
+
+ if (strongUpdateA.getAffectedAllocSite().equals(effectB.getAffectedAllocSite())
+ && strongUpdateA.getField().equals(effectB.getField())) {
+ if (useReachInfo) {
+ FlatNew fnRoot1 = asA.getFlatNew();
+ FlatNew fnRoot2 = asB.getFlatNew();
+ FlatNew fnTarget = strongUpdateA.getAffectedAllocSite().getFlatNew();
+ if (da.mayBothReachTarget(fmEnclosing, fnRoot1, fnRoot2, fnTarget)) {
+ addCoarseEffect(nodeA, asA, strongUpdateA);
+ if (!nodeA.equals(nodeB)) {
+ addCoarseEffect(nodeB, asB, effectB);
+ }
+ conflictType = updateConflictType(conflictType, ConflictGraph.COARSE_GRAIN_EDGE);
+ }
+ } else {
+ if (state.RCR) {
+ // need coarse effects for RCR from just one pass
+ addCoarseEffect(nodeA, asA, strongUpdateA);
+ if (!nodeA.equals(nodeB)) {
+ addCoarseEffect(nodeB, asB, effectB);
+ }
+ conflictType = ConflictGraph.COARSE_GRAIN_EDGE;
+ } else {
+ return ConflictGraph.COARSE_GRAIN_EDGE;
+ }
+ }
+
+ }
+
+ }
+ }
}
effectItrB = writeTableB.entrySet().iterator();
while (effectItrB.hasNext()) {
- Map.Entry meB = (Map.Entry)effectItrB.next();
- Alloc asB = (Alloc) meB.getKey();
- Set<Effect> esB = (Set<Effect>)meB.getValue();
-
- for (Iterator iterator = strongUpdateSetA.iterator(); iterator.hasNext(); ) {
- Effect strongUpdateA = (Effect) iterator.next();
- for (Iterator iterator2 = esB.iterator(); iterator2.hasNext(); ) {
- Effect effectB = (Effect) iterator2.next();
-
- if (strongUpdateA.getAffectedAllocSite().equals(effectB.getAffectedAllocSite())
- && strongUpdateA.getField().equals(effectB.getField())) {
-
- if (useReachInfo) {
- FlatNew fnRoot1 = asA.getFlatNew();
- FlatNew fnRoot2 = asB.getFlatNew();
- FlatNew fnTarget = strongUpdateA.getAffectedAllocSite().getFlatNew();
- if (da.mayBothReachTarget(fmEnclosing, fnRoot1, fnRoot2, fnTarget)) {
- addCoarseEffect(nodeA, asA, strongUpdateA);
- if (!nodeA.equals(nodeB)) {
- addCoarseEffect(nodeB, asB, effectB);
- }
- conflictType = updateConflictType(conflictType, ConflictGraph.COARSE_GRAIN_EDGE);
- }
- } else {
- return ConflictGraph.COARSE_GRAIN_EDGE;
- }
- }
-
- }
- }
+ Map.Entry meB = (Map.Entry)effectItrB.next();
+ Alloc asB = (Alloc) meB.getKey();
+ Set<Effect> esB = (Set<Effect>)meB.getValue();
+
+ for (Iterator iterator = strongUpdateSetA.iterator(); iterator.hasNext(); ) {
+ Effect strongUpdateA = (Effect) iterator.next();
+ for (Iterator iterator2 = esB.iterator(); iterator2.hasNext(); ) {
+ Effect effectB = (Effect) iterator2.next();
+
+ if (strongUpdateA.getAffectedAllocSite().equals(effectB.getAffectedAllocSite())
+ && strongUpdateA.getField().equals(effectB.getField())) {
+
+ if (useReachInfo) {
+ FlatNew fnRoot1 = asA.getFlatNew();
+ FlatNew fnRoot2 = asB.getFlatNew();
+ FlatNew fnTarget = strongUpdateA.getAffectedAllocSite().getFlatNew();
+ if (da.mayBothReachTarget(fmEnclosing, fnRoot1, fnRoot2, fnTarget)) {
+ addCoarseEffect(nodeA, asA, strongUpdateA);
+ if (!nodeA.equals(nodeB)) {
+ addCoarseEffect(nodeB, asB, effectB);
+ }
+ conflictType = updateConflictType(conflictType, ConflictGraph.COARSE_GRAIN_EDGE);
+ }
+ } else {
+ return ConflictGraph.COARSE_GRAIN_EDGE;
+ }
+ }
+
+ }
+ }
}
}
Iterator effectItrB = nodeBtable.entrySet().iterator();
while (effectItrB.hasNext()) {
- Map.Entry meB = (Map.Entry)effectItrB.next();
- Alloc asB = (Alloc) meB.getKey();
- Set<Effect> esB = (Set<Effect>)meB.getValue();
-
- for (Iterator iterator = esA.iterator(); iterator.hasNext(); ) {
- Effect effectA = (Effect) iterator.next();
- for (Iterator iterator2 = esB.iterator(); iterator2.hasNext(); ) {
- Effect effectB = (Effect) iterator2.next();
-
- if (effectA.getAffectedAllocSite().equals(effectB.getAffectedAllocSite())
- && ((effectA.getField() != null && effectB.getField() != null && effectA.getField()
- .equals(effectB.getField())) || (effectA.getField() == null && effectB
- .getField() == null))) {
-
- if (useReachInfo) {
- FlatNew fnRoot1 = asA.getFlatNew();
- FlatNew fnRoot2 = asB.getFlatNew();
- FlatNew fnTarget = effectA.getAffectedAllocSite().getFlatNew();
- if (fnRoot1.equals(fnRoot2)) {
- if (!da.mayManyReachTarget(fmEnclosing, fnRoot1, fnTarget)) {
- // fine-grained conflict case
- conflictType = updateConflictType(conflictType, ConflictGraph.FINE_GRAIN_EDGE);
- } else {
- // coarse-grained conflict case
- addCoarseEffect(nodeA, asA, effectA);
- if (!nodeA.equals(nodeB)) {
- addCoarseEffect(nodeB, asB, effectB);
- }
- conflictType =
- updateConflictType(conflictType, ConflictGraph.COARSE_GRAIN_EDGE);
- }
- } else {
- if (da.mayBothReachTarget(fmEnclosing, fnRoot1, fnRoot2, fnTarget)) {
- addCoarseEffect(nodeA, asA, effectA);
- if (!nodeA.equals(nodeB)) {
- addCoarseEffect(nodeB, asB, effectB);
- }
- conflictType =
- updateConflictType(conflictType, ConflictGraph.COARSE_GRAIN_EDGE);
- } else {
- }
- }
- } else {
- if (state.RCR) {
- // need coarse effects for RCR from just one pass
- addCoarseEffect(nodeA, asA, effectA);
- if (!nodeA.equals(nodeB)) {
- addCoarseEffect(nodeB, asB, effectB);
- }
- conflictType = ConflictGraph.COARSE_GRAIN_EDGE;
- } else {
- return ConflictGraph.COARSE_GRAIN_EDGE;
- }
- }
- }
- }
- }
+ Map.Entry meB = (Map.Entry)effectItrB.next();
+ Alloc asB = (Alloc) meB.getKey();
+ Set<Effect> esB = (Set<Effect>)meB.getValue();
+
+ for (Iterator iterator = esA.iterator(); iterator.hasNext(); ) {
+ Effect effectA = (Effect) iterator.next();
+ for (Iterator iterator2 = esB.iterator(); iterator2.hasNext(); ) {
+ Effect effectB = (Effect) iterator2.next();
+
+ if (effectA.getAffectedAllocSite().equals(effectB.getAffectedAllocSite())
+ && ((effectA.getField() != null && effectB.getField() != null && effectA.getField()
+ .equals(effectB.getField())) || (effectA.getField() == null && effectB
+ .getField() == null))) {
+
+ if (useReachInfo) {
+ FlatNew fnRoot1 = asA.getFlatNew();
+ FlatNew fnRoot2 = asB.getFlatNew();
+ FlatNew fnTarget = effectA.getAffectedAllocSite().getFlatNew();
+ if (fnRoot1.equals(fnRoot2)) {
+ if (!da.mayManyReachTarget(fmEnclosing, fnRoot1, fnTarget)) {
+ // fine-grained conflict case
+ conflictType = updateConflictType(conflictType, ConflictGraph.FINE_GRAIN_EDGE);
+ } else {
+ // coarse-grained conflict case
+ addCoarseEffect(nodeA, asA, effectA);
+ if (!nodeA.equals(nodeB)) {
+ addCoarseEffect(nodeB, asB, effectB);
+ }
+ conflictType =
+ updateConflictType(conflictType, ConflictGraph.COARSE_GRAIN_EDGE);
+ }
+ } else {
+ if (da.mayBothReachTarget(fmEnclosing, fnRoot1, fnRoot2, fnTarget)) {
+ addCoarseEffect(nodeA, asA, effectA);
+ if (!nodeA.equals(nodeB)) {
+ addCoarseEffect(nodeB, asB, effectB);
+ }
+ conflictType =
+ updateConflictType(conflictType, ConflictGraph.COARSE_GRAIN_EDGE);
+ } else {
+ }
+ }
+ } else {
+ if (state.RCR) {
+ // need coarse effects for RCR from just one pass
+ addCoarseEffect(nodeA, asA, effectA);
+ if (!nodeA.equals(nodeB)) {
+ addCoarseEffect(nodeB, asB, effectB);
+ }
+ conflictType = ConflictGraph.COARSE_GRAIN_EDGE;
+ } else {
+ return ConflictGraph.COARSE_GRAIN_EDGE;
+ }
+ }
+ }
+ }
+ }
}
}
String key = (String) iterator.next();
ConflictNode node = id2cn.get(key);
if (node.getEdgeSet().size() > 0) {
- return true;
+ return true;
}
}
return false;
ConflictNode node = (ConflictNode) entry.getValue();
if (node.isInVarNode()) {
- if (node.getSESEIdentifier() == seseID) {
-
- Set<ConflictEdge> edgeSet = node.getEdgeSet();
- for (Iterator iterator = edgeSet.iterator(); iterator.hasNext(); ) {
- ConflictEdge conflictEdge = (ConflictEdge) iterator.next();
-
- for (Iterator<SESELock> seseLockIter = seseLockSet.iterator(); seseLockIter.hasNext(); ) {
- SESELock seseLock = seseLockIter.next();
- if (seseLock.containsConflictNode(node)
- && seseLock.containsConflictEdge(conflictEdge)) {
- WaitingElement newElement = new WaitingElement();
- newElement.setQueueID(seseLock.getID());
- newElement.setStatus(seseLock.getNodeType(node));
- newElement.setTempDesc(node.getVar());
- if (isFineElement(newElement.getStatus())) {
- newElement.setDynID(node.getVar().toString());
- }
- if (!waitingElementSet.contains(newElement)) {
- waitingElementSet.add(newElement);
- }
-
- }
- }
- }
-
- }
+ if (node.getSESEIdentifier() == seseID) {
+
+ Set<ConflictEdge> edgeSet = node.getEdgeSet();
+ for (Iterator iterator = edgeSet.iterator(); iterator.hasNext(); ) {
+ ConflictEdge conflictEdge = (ConflictEdge) iterator.next();
+
+ for (Iterator<SESELock> seseLockIter = seseLockSet.iterator(); seseLockIter.hasNext(); ) {
+ SESELock seseLock = seseLockIter.next();
+ if (seseLock.containsConflictNode(node)
+ && seseLock.containsConflictEdge(conflictEdge)) {
+ WaitingElement newElement = new WaitingElement();
+ newElement.setQueueID(seseLock.getID());
+ newElement.setStatus(seseLock.getNodeType(node));
+ newElement.setTempDesc(node.getVar());
+ if (isFineElement(newElement.getStatus())) {
+ newElement.setDynID(node.getVar().toString());
+ }
+ if (!waitingElementSet.contains(newElement)) {
+ waitingElementSet.add(newElement);
+ }
+
+ }
+ }
+ }
+
+ }
}
}
WaitingElement waitingElement = (WaitingElement) iterator.next();
Set<WaitingElement> set = map.get(new Integer(waitingElement.getQueueID()));
if (set == null) {
- set = new HashSet<WaitingElement>();
+ set = new HashSet<WaitingElement>();
}
set.add(waitingElement);
map.put(new Integer(waitingElement.getQueueID()), set);
WaitingElement coarseElement = null;
for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext(); ) {
- WaitingElement waitingElement = (WaitingElement) iterator.next();
- if (waitingElement.getStatus() == ConflictNode.FINE_READ) {
- numRead++;
- } else if (waitingElement.getStatus() == ConflictNode.FINE_WRITE) {
- numWrite++;
- } else if (waitingElement.getStatus() == ConflictNode.COARSE) {
- numCoarse++;
- coarseElement = waitingElement;
- } else if (waitingElement.getStatus() == ConflictNode.SCC) {
- SCCelement = waitingElement;
- }
+ WaitingElement waitingElement = (WaitingElement) iterator.next();
+ if (waitingElement.getStatus() == ConflictNode.FINE_READ) {
+ numRead++;
+ } else if (waitingElement.getStatus() == ConflictNode.FINE_WRITE) {
+ numWrite++;
+ } else if (waitingElement.getStatus() == ConflictNode.COARSE) {
+ numCoarse++;
+ coarseElement = waitingElement;
+ } else if (waitingElement.getStatus() == ConflictNode.SCC) {
+ SCCelement = waitingElement;
+ }
}
if (SCCelement != null) {
- // if there is at lease one SCC element, just enqueue SCC and
- // ignore others.
- if (state.RCR) {
- // for rcr, we need to label all of coarse tempdescriptors
- // here assume that all waiting elements are coarse
- for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext(); ) {
- WaitingElement waitingElement = (WaitingElement) iterator.next();
- SCCelement.addTempDesc(waitingElement.getTempDesc());
- if (waitingElement != SCCelement) {
- waitingElement.setBogus(true);
- refinedSet.add(waitingElement);
- }
- }
- }
- refinedSet.add(SCCelement);
+ // if there is at lease one SCC element, just enqueue SCC and
+ // ignore others.
+ if (state.RCR) {
+ // for rcr, we need to label all of coarse tempdescriptors
+ // here assume that all waiting elements are coarse
+ for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext(); ) {
+ WaitingElement waitingElement = (WaitingElement) iterator.next();
+ SCCelement.addTempDesc(waitingElement.getTempDesc());
+ if (waitingElement != SCCelement) {
+ waitingElement.setBogus(true);
+ refinedSet.add(waitingElement);
+ }
+ }
+ }
+ refinedSet.add(SCCelement);
} else if (numCoarse == 1 && (numRead + numWrite == total)) {
- // if one is a coarse, the othere are reads/write, enqueue SCC.
- WaitingElement we = new WaitingElement();
- we.setQueueID(queueID);
- we.setStatus(ConflictNode.SCC);
- refinedSet.add(we);
+ // if one is a coarse, the othere are reads/write, enqueue SCC.
+ WaitingElement we = new WaitingElement();
+ we.setQueueID(queueID);
+ we.setStatus(ConflictNode.SCC);
+ refinedSet.add(we);
} else if (numCoarse == total) {
- // if there are multiple coarses, enqueue just one coarse.
- if (state.RCR) {
- // for rcr, we need to label all of coarse tempdescriptors
- for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext(); ) {
- WaitingElement waitingElement = (WaitingElement) iterator.next();
- if (waitingElement != coarseElement) {
- coarseElement.addTempDesc(waitingElement.getTempDesc());
- waitingElement.setBogus(true);
- refinedSet.add(waitingElement);
- }
- }
- }
- refinedSet.add(coarseElement);
+ // if there are multiple coarses, enqueue just one coarse.
+ if (state.RCR) {
+ // for rcr, we need to label all of coarse tempdescriptors
+ for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext(); ) {
+ WaitingElement waitingElement = (WaitingElement) iterator.next();
+ if (waitingElement != coarseElement) {
+ coarseElement.addTempDesc(waitingElement.getTempDesc());
+ waitingElement.setBogus(true);
+ refinedSet.add(waitingElement);
+ }
+ }
+ }
+ refinedSet.add(coarseElement);
} else if (numWrite == total || (numRead + numWrite) == total) {
- // code generator is going to handle the case for multiple writes &
- // read/writes.
- seseDS.setType(queueID, SESEWaitingQueue.EXCEPTION);
- refinedSet.addAll(waitingElementSet);
+ // code generator is going to handle the case for multiple writes &
+ // read/writes.
+ seseDS.setType(queueID, SESEWaitingQueue.EXCEPTION);
+ refinedSet.addAll(waitingElementSet);
} else {
- // otherwise, enqueue everything.
- refinedSet.addAll(waitingElementSet);
+ // otherwise, enqueue everything.
+ refinedSet.addAll(waitingElementSet);
}
seseDS.setWaitingElementSet(queueID, refinedSet);
} else {
ConflictNode node = (ConflictNode) entry.getValue();
if (node.isStallSiteNode() && node.getStallSiteFlatNode().equals(stallSite)) {
- Set<ConflictEdge> edgeSet = node.getEdgeSet();
- for (Iterator iter2 = edgeSet.iterator(); iter2.hasNext(); ) {
- ConflictEdge conflictEdge = (ConflictEdge) iter2.next();
-
- for (Iterator<SESELock> seseLockIter = seseLockSet.iterator(); seseLockIter.hasNext(); ) {
- SESELock seseLock = seseLockIter.next();
- if (seseLock.containsConflictNode(node) && seseLock.containsConflictEdge(conflictEdge)) {
- WaitingElement newElement = new WaitingElement();
- newElement.setQueueID(seseLock.getID());
- newElement.setStatus(seseLock.getNodeType(node));
- if (isFineElement(newElement.getStatus())) {
- newElement.setDynID(node.getVar().toString());
- }
- newElement.setTempDesc(node.getVar());
- waitingElementSet.add(newElement);
- }
- }
-
- }
+ Set<ConflictEdge> edgeSet = node.getEdgeSet();
+ for (Iterator iter2 = edgeSet.iterator(); iter2.hasNext(); ) {
+ ConflictEdge conflictEdge = (ConflictEdge) iter2.next();
+
+ for (Iterator<SESELock> seseLockIter = seseLockSet.iterator(); seseLockIter.hasNext(); ) {
+ SESELock seseLock = seseLockIter.next();
+ if (seseLock.containsConflictNode(node) && seseLock.containsConflictEdge(conflictEdge)) {
+ WaitingElement newElement = new WaitingElement();
+ newElement.setQueueID(seseLock.getID());
+ newElement.setStatus(seseLock.getNodeType(node));
+ if (isFineElement(newElement.getStatus())) {
+ newElement.setDynID(node.getVar().toString());
+ }
+ newElement.setTempDesc(node.getVar());
+ waitingElementSet.add(newElement);
+ }
+ }
+
+ }
}
ConflictNode node = entry.getValue();
if (filter) {
- if (node.getID().startsWith("___dst") || node.getID().startsWith("___srctmp")
- || node.getID().startsWith("___neverused") || node.getID().startsWith("___temp")) {
+ if (node.getID().startsWith("___dst") || node.getID().startsWith("___srctmp")
+ || node.getID().startsWith("___neverused") || node.getID().startsWith("___temp")) {
- continue;
- }
+ continue;
+ }
- if (node.getEdgeSet().isEmpty()) {
- continue;
- }
+ if (node.getEdgeSet().isEmpty()) {
+ continue;
+ }
}
attributes += "label=\"" + node.getID() + "\\n";
if (node.isStallSiteNode()) {
- String srcFileName = node.getSourceFileName();
- int separatorIdx = srcFileName.lastIndexOf(File.separator);
- if (separatorIdx > 0) {
- srcFileName = srcFileName.substring(separatorIdx + 1);
- }
- node.stallSite.getNumLine();
- attributes +=
- "STALL SITE" + "\\n" + srcFileName + ":" + node.getStallSiteFlatNode().getNumLine()
- + "\\n" + "\"]";
+ String srcFileName = node.getSourceFileName();
+ int separatorIdx = srcFileName.lastIndexOf(File.separator);
+ if (separatorIdx > 0) {
+ srcFileName = srcFileName.substring(separatorIdx + 1);
+ }
+ node.stallSite.getNumLine();
+ attributes +=
+ "STALL SITE" + "\\n" + srcFileName + ":" + node.getStallSiteFlatNode().getNumLine()
+ + "\\n" + "\"]";
} else {
- attributes += "LIVE-IN" + "\\n" + "\"]";
+ attributes += "LIVE-IN" + "\\n" + "\"]";
}
bw.write(entry.getKey() + attributes + ";\n");
Set<ConflictEdge> edgeSet = node.getEdgeSet();
for (Iterator iterator = edgeSet.iterator(); iterator.hasNext(); ) {
- ConflictEdge conflictEdge = (ConflictEdge) iterator.next();
-
- ConflictNode u = conflictEdge.getVertexU();
- ConflictNode v = conflictEdge.getVertexV();
-
- if (filter) {
- String uID = u.getID();
- String vID = v.getID();
- if (uID.startsWith("___dst") || uID.startsWith("___srctmp")
- || uID.startsWith("___neverused") || uID.startsWith("___temp")
- || vID.startsWith("___dst") || vID.startsWith("___srctmp")
- || vID.startsWith("___neverused") || vID.startsWith("___temp")) {
- continue;
- }
- }
-
- if (!addedSet.contains(conflictEdge)) {
- bw.write("" + u.getID() + "--" + v.getID() + "[label=" + conflictEdge.toGraphEdgeString()
- + ",decorate];\n");
- addedSet.add(conflictEdge);
- }
+ ConflictEdge conflictEdge = (ConflictEdge) iterator.next();
+
+ ConflictNode u = conflictEdge.getVertexU();
+ ConflictNode v = conflictEdge.getVertexV();
+
+ if (filter) {
+ String uID = u.getID();
+ String vID = v.getID();
+ if (uID.startsWith("___dst") || uID.startsWith("___srctmp")
+ || uID.startsWith("___neverused") || uID.startsWith("___temp")
+ || vID.startsWith("___dst") || vID.startsWith("___srctmp")
+ || vID.startsWith("___neverused") || vID.startsWith("___temp")) {
+ continue;
+ }
+ }
+
+ if (!addedSet.contains(conflictEdge)) {
+ bw.write("" + u.getID() + "--" + v.getID() + "[label=" + conflictEdge.toGraphEdgeString()
+ + ",decorate];\n");
+ addedSet.add(conflictEdge);
+ }
}
}
for (Iterator iterator = taintSet.iterator(); iterator.hasNext(); ) {
Taint t = (Taint) iterator.next();
if (t.getAllocSite().equals(as)) {
- return t;
+ return t;
}
}
return null;
ConflictEdge edge = (ConflictEdge) iterator.next();
if (edge.getVertexU() == edge.getVertexV()) {
- // self-conflict, need to generate traverser
- return false;
+ // self-conflict, need to generate traverser
+ return false;
} else {
- if (edge.getVertexU() == this) {
- if (edge.getVertexV().isInVarNode()) {
- // has a conflict with invar, need to generate traverser
- return false;
- }
- } else {
- if (edge.getVertexU().isInVarNode()) {
- // has a conflict with invar, need to generate traverser
- return false;
- }
- }
+ if (edge.getVertexU() == this) {
+ if (edge.getVertexV().isInVarNode()) {
+ // has a conflict with invar, need to generate traverser
+ return false;
+ }
+ } else {
+ if (edge.getVertexU().isInVarNode()) {
+ // has a conflict with invar, need to generate traverser
+ return false;
+ }
+ }
}
}
return true;
if (state.OOODEBUG) {
try {
- writeReports("");
- disjointAnalysisTaints.getEffectsAnalysis().writeEffects("effects.txt");
- writeConflictGraph();
+ writeReports("");
+ disjointAnalysisTaints.getEffectsAnalysis().writeEffects("effects.txt");
+ writeConflictGraph();
} catch (IOException e) {
}
}
fn2fm.put(fn, fm);
for (int i = 0; i < fn.numNext(); i++) {
- FlatNode nn = fn.getNext(i);
- if (!flatNodesVisited.contains(nn)) {
- flatNodesToVisit.add(nn);
- }
+ FlatNode nn = fn.getNext(i);
+ if (!flatNodesVisited.contains(nn)) {
+ flatNodesToVisit.add(nn);
+ }
}
}
}
BufferedWriter bw = new BufferedWriter(new FileWriter("sitesToFlag.txt"));
for (Iterator iterator = sitesToFlag.iterator(); iterator.hasNext(); ) {
- FlatNew fn = (FlatNew) iterator.next();
- bw.write(fn + "\n");
+ FlatNew fn = (FlatNew) iterator.next();
+ bw.write(fn + "\n");
}
bw.close();
} catch (IOException e) {
// merge sets from control flow joins
Set<TempDescriptor> livein = new HashSet<TempDescriptor>();
for (int i = 0; i < fn.numNext(); i++) {
- FlatNode nn = fn.getNext(i);
- Set<TempDescriptor> s = livenessGlobalView.get(nn);
- if (s != null) {
- livein.addAll(s);
- }
+ FlatNode nn = fn.getNext(i);
+ Set<TempDescriptor> s = livenessGlobalView.get(nn);
+ if (s != null) {
+ livein.addAll(s);
+ }
}
Set<TempDescriptor> curr = liveness_nodeActions(fn, livein);
// if a new result, schedule backward nodes for analysis
if (!curr.equals(prev)) {
- if (fn != fsen) {
- livenessGlobalView.put(fn, curr);
- for (int i = 0; i < fn.numPrev(); i++) {
- FlatNode nn = fn.getPrev(i);
- flatNodesToVisit.add(nn);
- }
- }
+ if (fn != fsen) {
+ livenessGlobalView.put(fn, curr);
+ for (int i = 0; i < fn.numPrev(); i++) {
+ FlatNode nn = fn.getPrev(i);
+ flatNodesToVisit.add(nn);
+ }
+ }
}
}
}
// task's in-var set
FlatSESEEnterNode fsen = (FlatSESEEnterNode) fn;
if (liveIn != null) {
- fsen.addInVarSet(liveIn);
+ fsen.addInVarSet(liveIn);
}
// no break, should also execute default actions
}
// handle effects of statement in reverse, writes then reads
TempDescriptor[] writeTemps = fn.writesTemps();
for (int i = 0; i < writeTemps.length; ++i) {
- liveIn.remove(writeTemps[i]);
-
- // if we are analyzing code declared directly in a task,
- FlatSESEEnterNode fsen = rblockRel.getLocalInnerRBlock(fn);
- if (fsen != null) {
- // check to see if we are writing to variables that will
- // be live-out at the task's exit (and therefore should
- // go in the task's out-var set)
- FlatSESEExitNode fsexn = fsen.getFlatExit();
- // note: liveness analysis can have corresponding decisions
- Set<TempDescriptor> livetemps = liveness.getLiveInTemps(fsen.getfmEnclosing(), fsexn);
- if (livetemps != null && livetemps.contains(writeTemps[i])) {
- fsen.addOutVar(writeTemps[i]);
- }
- }
+ liveIn.remove(writeTemps[i]);
+
+ // if we are analyzing code declared directly in a task,
+ FlatSESEEnterNode fsen = rblockRel.getLocalInnerRBlock(fn);
+ if (fsen != null) {
+ // check to see if we are writing to variables that will
+ // be live-out at the task's exit (and therefore should
+ // go in the task's out-var set)
+ FlatSESEExitNode fsexn = fsen.getFlatExit();
+ // note: liveness analysis can have corresponding decisions
+ Set<TempDescriptor> livetemps = liveness.getLiveInTemps(fsen.getfmEnclosing(), fsexn);
+ if (livetemps != null && livetemps.contains(writeTemps[i])) {
+ fsen.addOutVar(writeTemps[i]);
+ }
+ }
}
TempDescriptor[] readTemps = fn.readsTemps();
for (int i = 0; i < readTemps.length; ++i) {
- liveIn.add(readTemps[i]);
+ liveIn.add(readTemps[i]);
}
Set<TempDescriptor> virtualReadTemps = livenessVirtualReads.get(fn);
if (virtualReadTemps != null) {
- liveIn.addAll(virtualReadTemps);
+ liveIn.addAll(virtualReadTemps);
}
}
break;
// merge sets from control flow joins
VarSrcTokTable curr = new VarSrcTokTable();
for (int i = 0; i < fn.numPrev(); i++) {
- FlatNode nn = fn.getPrev(i);
- VarSrcTokTable incoming = variableResults.get(nn);
- curr.merge(incoming);
+ FlatNode nn = fn.getPrev(i);
+ VarSrcTokTable incoming = variableResults.get(nn);
+ curr.merge(incoming);
}
FlatSESEEnterNode currentSESE = rblockRel.getLocalInnerRBlock(fn);
if (currentSESE == null) {
- currentSESE = rblockRel.getCallerProxySESE();
+ currentSESE = rblockRel.getCallerProxySESE();
}
variable_nodeActions(fn, curr, currentSESE);
// if a new result, schedule forward nodes for analysis
if (!curr.equals(prev)) {
- variableResults.put(fn, curr);
+ variableResults.put(fn, curr);
- for (int i = 0; i < fn.numNext(); i++) {
- FlatNode nn = fn.getNext(i);
- flatNodesToVisit.add(nn);
- }
+ for (int i = 0; i < fn.numNext(); i++) {
+ FlatNode nn = fn.getNext(i);
+ flatNodesToVisit.add(nn);
+ }
}
}
}
Set<TempDescriptor> fsenVirtReadsOld = livenessVirtualReads.get(fn);
if (fsenVirtReadsOld != null) {
- fsenVirtReads.addAll(fsenVirtReadsOld);
+ fsenVirtReads.addAll(fsenVirtReadsOld);
}
livenessVirtualReads.put(fn, fsenVirtReads);
// the latest, clean sources
Iterator<TempDescriptor> outVarItr = fsen.getOutVarSet().iterator();
while (outVarItr.hasNext()) {
- TempDescriptor outVar = outVarItr.next();
- HashSet<TempDescriptor> ts = new HashSet<TempDescriptor>();
- ts.add(outVar);
- VariableSourceToken vst = new VariableSourceToken(ts, fsen, new Integer(0), outVar);
- vstTable.remove(outVar);
- vstTable.add(vst);
+ TempDescriptor outVar = outVarItr.next();
+ HashSet<TempDescriptor> ts = new HashSet<TempDescriptor>();
+ ts.add(outVar);
+ VariableSourceToken vst = new VariableSourceToken(ts, fsen, new Integer(0), outVar);
+ vstTable.remove(outVar);
+ vstTable.add(vst);
}
vstTable.assertConsistency();
}
FlatOpNode fon = (FlatOpNode) fn;
if (fon.getOp().getOp() == Operation.ASSIGN) {
- TempDescriptor lhs = fon.getDest();
- TempDescriptor rhs = fon.getLeft();
-
- vstTable.remove(lhs);
-
- Set<VariableSourceToken> forAddition = new HashSet<VariableSourceToken>();
-
- Iterator<VariableSourceToken> itr = vstTable.get(rhs).iterator();
- while (itr.hasNext()) {
- VariableSourceToken vst = itr.next();
-
- HashSet<TempDescriptor> ts = new HashSet<TempDescriptor>();
- ts.add(lhs);
-
- // when we do x = y for variables, just copy over from a child,
- // there are two cases:
- // 1. if the current task is the caller proxy, any local root is a
- // child
- boolean case1 =
- currentSESE.getIsCallerProxySESE()
- && rblockRel.getLocalRootSESEs().contains(vst.getSESE());
-
- // 2. if the child task is a locally-defined child of the current task
- boolean case2 = currentSESE.getLocalChildren().contains(vst.getSESE());
-
- if (case1 || case2) {
- // if the source comes from a child, copy it over
- forAddition.add(new VariableSourceToken(ts, vst.getSESE(), vst.getAge(), vst
- .getAddrVar()));
- } else {
- // otherwise, stamp it as us as the source
- forAddition.add(new VariableSourceToken(ts, currentSESE, new Integer(0), lhs));
- }
- }
-
- vstTable.addAll(forAddition);
-
- // only break if this is an ASSIGN op node,
- // otherwise fall through to default case
- vstTable.assertConsistency();
- break;
+ TempDescriptor lhs = fon.getDest();
+ TempDescriptor rhs = fon.getLeft();
+
+ vstTable.remove(lhs);
+
+ Set<VariableSourceToken> forAddition = new HashSet<VariableSourceToken>();
+
+ Iterator<VariableSourceToken> itr = vstTable.get(rhs).iterator();
+ while (itr.hasNext()) {
+ VariableSourceToken vst = itr.next();
+
+ HashSet<TempDescriptor> ts = new HashSet<TempDescriptor>();
+ ts.add(lhs);
+
+ // when we do x = y for variables, just copy over from a child,
+ // there are two cases:
+ // 1. if the current task is the caller proxy, any local root is a
+ // child
+ boolean case1 =
+ currentSESE.getIsCallerProxySESE()
+ && rblockRel.getLocalRootSESEs().contains(vst.getSESE());
+
+ // 2. if the child task is a locally-defined child of the current task
+ boolean case2 = currentSESE.getLocalChildren().contains(vst.getSESE());
+
+ if (case1 || case2) {
+ // if the source comes from a child, copy it over
+ forAddition.add(new VariableSourceToken(ts, vst.getSESE(), vst.getAge(), vst
+ .getAddrVar()));
+ } else {
+ // otherwise, stamp it as us as the source
+ forAddition.add(new VariableSourceToken(ts, currentSESE, new Integer(0), lhs));
+ }
+ }
+
+ vstTable.addAll(forAddition);
+
+ // only break if this is an ASSIGN op node,
+ // otherwise fall through to default case
+ vstTable.assertConsistency();
+ break;
}
}
TempDescriptor[] writeTemps = fn.writesTemps();
if (writeTemps.length > 0) {
- // for now, when writeTemps > 1, make sure
- // its a call node, programmer enforce only
- // doing stuff like calling a print routine
- if (writeTemps.length > 1) {
- assert fn.kind() == FKind.FlatCall || fn.kind() == FKind.FlatMethod;
- break;
- }
+ // for now, when writeTemps > 1, make sure
+ // its a call node, programmer enforce only
+ // doing stuff like calling a print routine
+ if (writeTemps.length > 1) {
+ assert fn.kind() == FKind.FlatCall || fn.kind() == FKind.FlatMethod;
+ break;
+ }
- vstTable.remove(writeTemps[0]);
+ vstTable.remove(writeTemps[0]);
- HashSet<TempDescriptor> ts = new HashSet<TempDescriptor>();
- ts.add(writeTemps[0]);
+ HashSet<TempDescriptor> ts = new HashSet<TempDescriptor>();
+ ts.add(writeTemps[0]);
- vstTable.add(new VariableSourceToken(ts, currentSESE, new Integer(0), writeTemps[0]));
+ vstTable.add(new VariableSourceToken(ts, currentSESE, new Integer(0), writeTemps[0]));
}
vstTable.assertConsistency();
Set<TempDescriptor> curr = new HashSet<TempDescriptor>();
for (int i = 0; i < fn.numPrev(); i++) {
- FlatNode nn = fn.getPrev(i);
- Set<TempDescriptor> notAvailIn = notAvailableResults.get(nn);
- if (notAvailIn != null) {
- curr.addAll(notAvailIn);
- }
+ FlatNode nn = fn.getPrev(i);
+ Set<TempDescriptor> notAvailIn = notAvailableResults.get(nn);
+ if (notAvailIn != null) {
+ curr.addAll(notAvailIn);
+ }
}
FlatSESEEnterNode currentSESE = rblockRel.getLocalInnerRBlock(fn);
if (currentSESE == null) {
- currentSESE = rblockRel.getCallerProxySESE();
+ currentSESE = rblockRel.getCallerProxySESE();
}
notAvailable_nodeActions(fn, curr, currentSESE);
// if a new result, schedule forward nodes for analysis
if (!curr.equals(prev)) {
- notAvailableResults.put(fn, curr);
+ notAvailableResults.put(fn, curr);
- for (int i = 0; i < fn.numNext(); i++) {
- FlatNode nn = fn.getNext(i);
- flatNodesToVisit.add(nn);
- }
+ for (int i = 0; i < fn.numNext(); i++) {
+ FlatNode nn = fn.getNext(i);
+ flatNodesToVisit.add(nn);
+ }
}
}
}
Set<TempDescriptor> notAvailCopy = new HashSet<TempDescriptor>();
Iterator<TempDescriptor> tdItr = notAvailSet.iterator();
while (tdItr.hasNext()) {
- notAvailCopy.add(tdItr.next());
+ notAvailCopy.add(tdItr.next());
}
notAvailableIntoSESE.put(fsen, notAvailCopy);
FlatOpNode fon = (FlatOpNode) fn;
if (fon.getOp().getOp() == Operation.ASSIGN) {
- TempDescriptor lhs = fon.getDest();
- TempDescriptor rhs = fon.getLeft();
-
- // copy makes lhs same availability as rhs
- if (notAvailSet.contains(rhs)) {
- notAvailSet.add(lhs);
- } else {
- notAvailSet.remove(lhs);
- }
-
- // only break if this is an ASSIGN op node,
- // otherwise fall through to default case
- break;
+ TempDescriptor lhs = fon.getDest();
+ TempDescriptor rhs = fon.getLeft();
+
+ // copy makes lhs same availability as rhs
+ if (notAvailSet.contains(rhs)) {
+ notAvailSet.add(lhs);
+ } else {
+ notAvailSet.remove(lhs);
+ }
+
+ // only break if this is an ASSIGN op node,
+ // otherwise fall through to default case
+ break;
}
}
default: {
TempDescriptor[] writeTemps = fn.writesTemps();
for (int i = 0; i < writeTemps.length; i++) {
- TempDescriptor wTemp = writeTemps[i];
- notAvailSet.remove(wTemp);
+ TempDescriptor wTemp = writeTemps[i];
+ notAvailSet.remove(wTemp);
}
TempDescriptor[] readTemps = fn.readsTemps();
for (int i = 0; i < readTemps.length; i++) {
- TempDescriptor rTemp = readTemps[i];
- notAvailSet.remove(rTemp);
-
- // if this variable has exactly one source, potentially
- // get other things from this source as well
- VarSrcTokTable vstTable = variableResults.get(fn);
-
- VSTWrapper vstIfStatic = new VSTWrapper();
- Integer srcType = vstTable.getRefVarSrcType(rTemp, currentSESE, vstIfStatic);
-
- if (srcType.equals(VarSrcTokTable.SrcType_STATIC)) {
-
- VariableSourceToken vst = vstIfStatic.vst;
-
- Iterator<VariableSourceToken> availItr =
- vstTable.get(vst.getSESE(), vst.getAge()).iterator();
-
- // look through things that are also available from same source
- while (availItr.hasNext()) {
- VariableSourceToken vstAlsoAvail = availItr.next();
-
- Iterator<TempDescriptor> refVarItr = vstAlsoAvail.getRefVars().iterator();
- while (refVarItr.hasNext()) {
- TempDescriptor refVarAlso = refVarItr.next();
-
- // if a variable is available from the same source, AND it ALSO
- // only comes from one statically known source, mark it available
- VSTWrapper vstIfStaticNotUsed = new VSTWrapper();
- Integer srcTypeAlso =
- vstTable.getRefVarSrcType(refVarAlso, currentSESE, vstIfStaticNotUsed);
- if (srcTypeAlso.equals(VarSrcTokTable.SrcType_STATIC)) {
- notAvailSet.remove(refVarAlso);
- }
- }
- }
- }
+ TempDescriptor rTemp = readTemps[i];
+ notAvailSet.remove(rTemp);
+
+ // if this variable has exactly one source, potentially
+ // get other things from this source as well
+ VarSrcTokTable vstTable = variableResults.get(fn);
+
+ VSTWrapper vstIfStatic = new VSTWrapper();
+ Integer srcType = vstTable.getRefVarSrcType(rTemp, currentSESE, vstIfStatic);
+
+ if (srcType.equals(VarSrcTokTable.SrcType_STATIC)) {
+
+ VariableSourceToken vst = vstIfStatic.vst;
+
+ Iterator<VariableSourceToken> availItr =
+ vstTable.get(vst.getSESE(), vst.getAge()).iterator();
+
+ // look through things that are also available from same source
+ while (availItr.hasNext()) {
+ VariableSourceToken vstAlsoAvail = availItr.next();
+
+ Iterator<TempDescriptor> refVarItr = vstAlsoAvail.getRefVars().iterator();
+ while (refVarItr.hasNext()) {
+ TempDescriptor refVarAlso = refVarItr.next();
+
+ // if a variable is available from the same source, AND it ALSO
+ // only comes from one statically known source, mark it available
+ VSTWrapper vstIfStaticNotUsed = new VSTWrapper();
+ Integer srcTypeAlso =
+ vstTable.getRefVarSrcType(refVarAlso, currentSESE, vstIfStaticNotUsed);
+ if (srcTypeAlso.equals(VarSrcTokTable.SrcType_STATIC)) {
+ notAvailSet.remove(refVarAlso);
+ }
+ }
+ }
+ }
}
}
break;
// before the current statement
VarSrcTokTable dotSTtable = new VarSrcTokTable();
for (int i = 0; i < fn.numPrev(); i++) {
- FlatNode nn = fn.getPrev(i);
- dotSTtable.merge(variableResults.get(nn));
+ FlatNode nn = fn.getPrev(i);
+ dotSTtable.merge(variableResults.get(nn));
}
// find dt-st notAvailableSet also
Set<TempDescriptor> dotSTnotAvailSet = new HashSet<TempDescriptor>();
for (int i = 0; i < fn.numPrev(); i++) {
- FlatNode nn = fn.getPrev(i);
- Set<TempDescriptor> notAvailIn = notAvailableResults.get(nn);
- if (notAvailIn != null) {
- dotSTnotAvailSet.addAll(notAvailIn);
- }
+ FlatNode nn = fn.getPrev(i);
+ Set<TempDescriptor> notAvailIn = notAvailableResults.get(nn);
+ if (notAvailIn != null) {
+ dotSTnotAvailSet.addAll(notAvailIn);
+ }
}
Set<TempDescriptor> dotSTlive = livenessGlobalView.get(fn);
FlatSESEEnterNode currentSESE = rblockRel.getLocalInnerRBlock(fn);
if (currentSESE == null) {
- currentSESE = rblockRel.getCallerProxySESE();
+ currentSESE = rblockRel.getCallerProxySESE();
}
codePlans_nodeActions(fm, fn, dotSTtable, dotSTnotAvailSet, currentSESE);
for (int i = 0; i < fn.numNext(); i++) {
- FlatNode nn = fn.getNext(i);
+ FlatNode nn = fn.getNext(i);
- if (!visited.contains(nn)) {
- flatNodesToVisit.add(nn);
- }
+ if (!visited.contains(nn)) {
+ flatNodesToVisit.add(nn);
+ }
}
}
}
// dependencies properly
Iterator<TempDescriptor> inVarItr = fsen.getInVarSet().iterator();
while (inVarItr.hasNext()) {
- TempDescriptor inVar = inVarItr.next();
-
- // when we get to an SESE enter node we change the
- // currentSESE variable of this analysis to the
- // child that is declared by the enter node, so
- // in order to classify in-vars correctly, pass
- // the parent SESE in--at other FlatNode types just
- // use the currentSESE
- FlatSESEEnterNode parent = rblockRel.getLocalInnerRBlock(fn);
- if (parent == null) {
- parent = rblockRel.getCallerProxySESE();
- }
-
- VSTWrapper vstIfStatic = new VSTWrapper();
- Integer srcType = vstTableIn.getRefVarSrcType(inVar, parent, vstIfStatic);
-
- // the current SESE needs a local space to track the dynamic
- // variable and the child needs space in its SESE record
- if (srcType.equals(VarSrcTokTable.SrcType_DYNAMIC)) {
- fsen.addDynamicInVar(inVar);
- addDynamicVar(parent, fm, inVar);
-
- } else if (srcType.equals(VarSrcTokTable.SrcType_STATIC)) {
- fsen.addStaticInVar(inVar);
- VariableSourceToken vst = vstIfStatic.vst;
- fsen.putStaticInVar2src(inVar, vst);
- fsen.addStaticInVarSrc(new SESEandAgePair(vst.getSESE(), vst.getAge()));
-
- } else {
- assert srcType.equals(VarSrcTokTable.SrcType_READY);
- fsen.addReadyInVar(inVar);
- }
+ TempDescriptor inVar = inVarItr.next();
+
+ // when we get to an SESE enter node we change the
+ // currentSESE variable of this analysis to the
+ // child that is declared by the enter node, so
+ // in order to classify in-vars correctly, pass
+ // the parent SESE in--at other FlatNode types just
+ // use the currentSESE
+ FlatSESEEnterNode parent = rblockRel.getLocalInnerRBlock(fn);
+ if (parent == null) {
+ parent = rblockRel.getCallerProxySESE();
+ }
+
+ VSTWrapper vstIfStatic = new VSTWrapper();
+ Integer srcType = vstTableIn.getRefVarSrcType(inVar, parent, vstIfStatic);
+
+ // the current SESE needs a local space to track the dynamic
+ // variable and the child needs space in its SESE record
+ if (srcType.equals(VarSrcTokTable.SrcType_DYNAMIC)) {
+ fsen.addDynamicInVar(inVar);
+ addDynamicVar(parent, fm, inVar);
+
+ } else if (srcType.equals(VarSrcTokTable.SrcType_STATIC)) {
+ fsen.addStaticInVar(inVar);
+ VariableSourceToken vst = vstIfStatic.vst;
+ fsen.putStaticInVar2src(inVar, vst);
+ fsen.addStaticInVarSrc(new SESEandAgePair(vst.getSESE(), vst.getAge()));
+
+ } else {
+ assert srcType.equals(VarSrcTokTable.SrcType_READY);
+ fsen.addReadyInVar(inVar);
+ }
}
}
break;
Iterator<TempDescriptor> outVarItr = exiter.getOutVarSet().iterator();
while (outVarItr.hasNext()) {
- TempDescriptor outVar = outVarItr.next();
-
- VSTWrapper vstIfStatic = new VSTWrapper();
- Integer srcType = vstTableIn.getRefVarSrcType(outVar, exiter, vstIfStatic);
-
- if (srcType.equals(VarSrcTokTable.SrcType_DYNAMIC)) {
- // if the out-var is dynamic, put it in the set of dyn out vars
- // so exiting code gen knows to look for the value, but also put
- // it in the set of dynamic vars the exiter must track!
- exiter.addDynamicOutVar(outVar);
- addDynamicVar(exiter, fm, outVar);
-
- } else if (srcType.equals(VarSrcTokTable.SrcType_STATIC)) {
- exiter.addStaticOutVar(outVar);
- VariableSourceToken vst = vstIfStatic.vst;
- exiter.putStaticOutVar2src(outVar, vst);
- exiter.addStaticOutVarSrc(new SESEandAgePair(vst.getSESE(), vst.getAge()));
-
- } else {
- assert srcType.equals(VarSrcTokTable.SrcType_READY);
- exiter.addReadyOutVar(outVar);
- }
+ TempDescriptor outVar = outVarItr.next();
+
+ VSTWrapper vstIfStatic = new VSTWrapper();
+ Integer srcType = vstTableIn.getRefVarSrcType(outVar, exiter, vstIfStatic);
+
+ if (srcType.equals(VarSrcTokTable.SrcType_DYNAMIC)) {
+ // if the out-var is dynamic, put it in the set of dyn out vars
+ // so exiting code gen knows to look for the value, but also put
+ // it in the set of dynamic vars the exiter must track!
+ exiter.addDynamicOutVar(outVar);
+ addDynamicVar(exiter, fm, outVar);
+
+ } else if (srcType.equals(VarSrcTokTable.SrcType_STATIC)) {
+ exiter.addStaticOutVar(outVar);
+ VariableSourceToken vst = vstIfStatic.vst;
+ exiter.putStaticOutVar2src(outVar, vst);
+ exiter.addStaticOutVarSrc(new SESEandAgePair(vst.getSESE(), vst.getAge()));
+
+ } else {
+ assert srcType.equals(VarSrcTokTable.SrcType_READY);
+ exiter.addReadyOutVar(outVar);
+ }
}
}
break;
FlatOpNode fon = (FlatOpNode) fn;
if (fon.getOp().getOp() == Operation.ASSIGN) {
- TempDescriptor lhs = fon.getDest();
- TempDescriptor rhs = fon.getLeft();
-
- // if this is an op node, don't stall, copy
- // source and delay until we need to use value
-
- // ask whether lhs and rhs sources are dynamic, static, etc.
- VSTWrapper vstIfStatic = new VSTWrapper();
- Integer lhsSrcType = vstTableIn.getRefVarSrcType(lhs, currentSESE, vstIfStatic);
- Integer rhsSrcType = vstTableIn.getRefVarSrcType(rhs, currentSESE, vstIfStatic);
-
- if (rhsSrcType.equals(VarSrcTokTable.SrcType_DYNAMIC)) {
- // if rhs is dynamic going in, lhs will definitely be dynamic
- // going out of this node, so track that here
- plan.addDynAssign(lhs, rhs);
- addDynamicVar(currentSESE, fm, lhs);
- addDynamicVar(currentSESE, fm, rhs);
-
- } else if (lhsSrcType.equals(VarSrcTokTable.SrcType_DYNAMIC)) {
- // otherwise, if the lhs is dynamic, but the rhs is not, we
- // need to update the variable's dynamic source as "current SESE"
- plan.addDynAssign(lhs);
- }
-
- // only break if this is an ASSIGN op node,
- // otherwise fall through to default case
- break;
+ TempDescriptor lhs = fon.getDest();
+ TempDescriptor rhs = fon.getLeft();
+
+ // if this is an op node, don't stall, copy
+ // source and delay until we need to use value
+
+ // ask whether lhs and rhs sources are dynamic, static, etc.
+ VSTWrapper vstIfStatic = new VSTWrapper();
+ Integer lhsSrcType = vstTableIn.getRefVarSrcType(lhs, currentSESE, vstIfStatic);
+ Integer rhsSrcType = vstTableIn.getRefVarSrcType(rhs, currentSESE, vstIfStatic);
+
+ if (rhsSrcType.equals(VarSrcTokTable.SrcType_DYNAMIC)) {
+ // if rhs is dynamic going in, lhs will definitely be dynamic
+ // going out of this node, so track that here
+ plan.addDynAssign(lhs, rhs);
+ addDynamicVar(currentSESE, fm, lhs);
+ addDynamicVar(currentSESE, fm, rhs);
+
+ } else if (lhsSrcType.equals(VarSrcTokTable.SrcType_DYNAMIC)) {
+ // otherwise, if the lhs is dynamic, but the rhs is not, we
+ // need to update the variable's dynamic source as "current SESE"
+ plan.addDynAssign(lhs);
+ }
+
+ // only break if this is an ASSIGN op node,
+ // otherwise fall through to default case
+ break;
}
}
TempDescriptor[] readarray = fn.readsTemps();
for (int i = 0; i < readarray.length; i++) {
- TempDescriptor readtmp = readarray[i];
-
- // ignore temps that are definitely available
- // when considering to stall on it
- if (!notAvailSetIn.contains(readtmp)) {
- continue;
- }
-
- // check the source type of this variable
- VSTWrapper vstIfStatic = new VSTWrapper();
- Integer srcType = vstTableIn.getRefVarSrcType(readtmp, currentSESE, vstIfStatic);
-
- if (srcType.equals(VarSrcTokTable.SrcType_DYNAMIC)) {
- // 1) It is not clear statically where this variable will
- // come from, so dynamically we must keep track
- // along various control paths, and therefore when we stall,
- // just stall for the exact thing we need and move on
- plan.addDynamicStall(readtmp);
- addDynamicVar(currentSESE, fm, readtmp);
-
- } else if (srcType.equals(VarSrcTokTable.SrcType_STATIC)) {
- // 2) Single token/age pair: Stall for token/age pair, and copy
- // all live variables with same token/age pair at the same
- // time. This is the same stuff that the notavaialable analysis
- // marks as now available.
- VariableSourceToken vst = vstIfStatic.vst;
-
- Iterator<VariableSourceToken> availItr =
- vstTableIn.get(vst.getSESE(), vst.getAge()).iterator();
-
- while (availItr.hasNext()) {
- VariableSourceToken vstAlsoAvail = availItr.next();
-
- // only grab additional stuff that is live
- Set<TempDescriptor> copySet = new HashSet<TempDescriptor>();
-
- Iterator<TempDescriptor> refVarItr = vstAlsoAvail.getRefVars().iterator();
-
- while (refVarItr.hasNext()) {
- TempDescriptor refVar = refVarItr.next();
- // note: this should just use normal liveness in...only want to
- // copy live variables...
- if (liveness.getLiveInTemps(fm, fn).contains(refVar)) {
- copySet.add(refVar);
- }
- }
-
- if (!copySet.isEmpty()) {
- plan.addStall2CopySet(vstAlsoAvail, copySet);
- }
- }
-
- } else {
- // the other case for srcs is READY, so do nothing
- }
-
- // assert that everything being stalled for is in the
- // "not available" set coming into this flat node and
- // that every VST identified is in the possible "stall set"
- // that represents VST's from children SESE's
+ TempDescriptor readtmp = readarray[i];
+
+ // ignore temps that are definitely available
+ // when considering to stall on it
+ if (!notAvailSetIn.contains(readtmp)) {
+ continue;
+ }
+
+ // check the source type of this variable
+ VSTWrapper vstIfStatic = new VSTWrapper();
+ Integer srcType = vstTableIn.getRefVarSrcType(readtmp, currentSESE, vstIfStatic);
+
+ if (srcType.equals(VarSrcTokTable.SrcType_DYNAMIC)) {
+ // 1) It is not clear statically where this variable will
+ // come from, so dynamically we must keep track
+ // along various control paths, and therefore when we stall,
+ // just stall for the exact thing we need and move on
+ plan.addDynamicStall(readtmp);
+ addDynamicVar(currentSESE, fm, readtmp);
+
+ } else if (srcType.equals(VarSrcTokTable.SrcType_STATIC)) {
+ // 2) Single token/age pair: Stall for token/age pair, and copy
+ // all live variables with same token/age pair at the same
+ // time. This is the same stuff that the notavaialable analysis
+ // marks as now available.
+ VariableSourceToken vst = vstIfStatic.vst;
+
+ Iterator<VariableSourceToken> availItr =
+ vstTableIn.get(vst.getSESE(), vst.getAge()).iterator();
+
+ while (availItr.hasNext()) {
+ VariableSourceToken vstAlsoAvail = availItr.next();
+
+ // only grab additional stuff that is live
+ Set<TempDescriptor> copySet = new HashSet<TempDescriptor>();
+
+ Iterator<TempDescriptor> refVarItr = vstAlsoAvail.getRefVars().iterator();
+
+ while (refVarItr.hasNext()) {
+ TempDescriptor refVar = refVarItr.next();
+ // note: this should just use normal liveness in...only want to
+ // copy live variables...
+ if (liveness.getLiveInTemps(fm, fn).contains(refVar)) {
+ copySet.add(refVar);
+ }
+ }
+
+ if (!copySet.isEmpty()) {
+ plan.addStall2CopySet(vstAlsoAvail, copySet);
+ }
+ }
+
+ } else {
+ // the other case for srcs is READY, so do nothing
+ }
+
+ // assert that everything being stalled for is in the
+ // "not available" set coming into this flat node and
+ // that every VST identified is in the possible "stall set"
+ // that represents VST's from children SESE's
}
}
// never need to generate another name for it in code (it is
// ALWAYS the task executing the local method context)
if (vst.getSESE().getIsCallerProxySESE()) {
- continue;
+ continue;
}
SESEandAgePair sap = new SESEandAgePair(vst.getSESE(), vst.getAge());
FlatSESEEnterNode sese = currentSESE;
while (sese != null) {
- addNeededStaticName(sese, fm, sap);
- sese = sese.getLocalParent();
+ addNeededStaticName(sese, fm, sap);
+ sese = sese.getLocalParent();
}
}
fsenDoingTracking = currentSESE.getLocalParent();
if (fsenDoingTracking == null) {
- // if there is no local parent, there are one of two cases
- // 1) the current task is main, in which case this FlatNode
- // is the main's exit, and doesn't need to do any of the
- // following dynamic tracking
- // 2) the current task is defined in a method, so use the
- // caller proxy in the variable source calcs below
- if (currentSESE.equals(rblockRel.getMainSESE())) {
- return;
- } else {
- fsenDoingTracking = rblockRel.getCallerProxySESE();
- }
+ // if there is no local parent, there are one of two cases
+ // 1) the current task is main, in which case this FlatNode
+ // is the main's exit, and doesn't need to do any of the
+ // following dynamic tracking
+ // 2) the current task is defined in a method, so use the
+ // caller proxy in the variable source calcs below
+ if (currentSESE.equals(rblockRel.getMainSESE())) {
+ return;
+ } else {
+ fsenDoingTracking = rblockRel.getCallerProxySESE();
+ }
}
} else {
fsenDoingTracking = currentSESE;
// completely outside of the root SESE scope
if (nextVstTable != null && nextLiveIn != null) {
- Hashtable<TempDescriptor, VSTWrapper> readyOrStatic2dynamicSet =
- thisVstTable.getReadyOrStatic2DynamicSet(nextVstTable, nextLiveIn, fsenDoingTracking);
+ Hashtable<TempDescriptor, VSTWrapper> readyOrStatic2dynamicSet =
+ thisVstTable.getReadyOrStatic2DynamicSet(nextVstTable, nextLiveIn, fsenDoingTracking);
- if (!readyOrStatic2dynamicSet.isEmpty()) {
+ if (!readyOrStatic2dynamicSet.isEmpty()) {
- // either add these results to partial fixed-point result
- // or make a new one if we haven't made any here yet
- FlatEdge fe = new FlatEdge(fn, nn);
- FlatWriteDynamicVarNode fwdvn = wdvNodesToSpliceIn.get(fe);
+ // either add these results to partial fixed-point result
+ // or make a new one if we haven't made any here yet
+ FlatEdge fe = new FlatEdge(fn, nn);
+ FlatWriteDynamicVarNode fwdvn = wdvNodesToSpliceIn.get(fe);
- if (fwdvn == null) {
- fwdvn =
- new FlatWriteDynamicVarNode(fn, nn, readyOrStatic2dynamicSet, fsenDoingTracking);
- wdvNodesToSpliceIn.put(fe, fwdvn);
- } else {
- fwdvn.addMoreVar2Src(readyOrStatic2dynamicSet);
- }
- }
+ if (fwdvn == null) {
+ fwdvn =
+ new FlatWriteDynamicVarNode(fn, nn, readyOrStatic2dynamicSet, fsenDoingTracking);
+ wdvNodesToSpliceIn.put(fe, fwdvn);
+ } else {
+ fwdvn.addMoreVar2Src(readyOrStatic2dynamicSet);
+ }
+ }
}
}
}
FlatSESEEnterNode parent = (FlatSESEEnterNode) iterator.next();
if (parent.getIsLeafSESE()) {
- continue;
+ continue;
}
EffectsAnalysis effectsAnalysis = disjointAnalysisTaints.getEffectsAnalysis();
Set<FlatSESEEnterNode> children = parent.getChildren();
for (Iterator iterator2 = children.iterator(); iterator2.hasNext(); ) {
- FlatSESEEnterNode child = (FlatSESEEnterNode) iterator2.next();
- Hashtable<Taint, Set<Effect>> taint2Effects = effectsAnalysis.get(child);
- conflictGraph.addLiveIn(taint2Effects);
+ FlatSESEEnterNode child = (FlatSESEEnterNode) iterator2.next();
+ Hashtable<Taint, Set<Effect>> taint2Effects = effectsAnalysis.get(child);
+ conflictGraph.addLiveIn(taint2Effects);
}
sese2conflictGraph.put(parent, conflictGraph);
MethodDescriptor md = descItr.next();
FlatMethod fm = state.getMethodFlat(md);
if (fm != null) {
- addStallSitesToConflictGraphs(fm);
+ addStallSitesToConflictGraphs(fm);
}
}
}
// schedule forward nodes for analysis
for (int i = 0; i < fn.numNext(); i++) {
- FlatNode nn = fn.getNext(i);
- if (!visited.contains(nn)) {
- flatNodesToVisit.add(nn);
- }
+ FlatNode nn = fn.getNext(i);
+ if (!visited.contains(nn)) {
+ flatNodesToVisit.add(nn);
+ }
}
}
}
ConflictGraph conflictGraph = sese2conflictGraph.get(currentSESE);
if (conflictGraph == null) {
- assert currentSESE.getIsLeafSESE();
- continue;
+ assert currentSESE.getIsLeafSESE();
+ continue;
}
TempDescriptor lhs;
case FKind.FlatFieldNode:
case FKind.FlatElementNode: {
- if (fn instanceof FlatFieldNode) {
- FlatFieldNode ffn = (FlatFieldNode) fn;
- rhs = ffn.getSrc();
- } else {
- FlatElementNode fen = (FlatElementNode) fn;
- rhs = fen.getSrc();
- }
+ if (fn instanceof FlatFieldNode) {
+ FlatFieldNode ffn = (FlatFieldNode) fn;
+ rhs = ffn.getSrc();
+ } else {
+ FlatElementNode fen = (FlatElementNode) fn;
+ rhs = fen.getSrc();
+ }
- conflictGraph.addStallSite(taint2Effects, rhs, cd);
+ conflictGraph.addStallSite(taint2Effects, rhs, cd);
}
break;
case FKind.FlatSetFieldNode:
case FKind.FlatSetElementNode: {
- if (fn instanceof FlatSetFieldNode) {
- FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
- lhs = fsfn.getDst();
- rhs = fsfn.getSrc();
- } else {
- FlatSetElementNode fsen = (FlatSetElementNode) fn;
- lhs = fsen.getDst();
- rhs = fsen.getSrc();
- }
-
- conflictGraph.addStallSite(taint2Effects, rhs, cd);
- conflictGraph.addStallSite(taint2Effects, lhs, cd);
+ if (fn instanceof FlatSetFieldNode) {
+ FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
+ lhs = fsfn.getDst();
+ rhs = fsfn.getSrc();
+ } else {
+ FlatSetElementNode fsen = (FlatSetElementNode) fn;
+ lhs = fsen.getDst();
+ rhs = fsen.getSrc();
+ }
+
+ conflictGraph.addStallSite(taint2Effects, rhs, cd);
+ conflictGraph.addStallSite(taint2Effects, lhs, cd);
}
break;
case FKind.FlatCall: {
- FlatCall fc = (FlatCall) fn;
- lhs = fc.getThis();
+ FlatCall fc = (FlatCall) fn;
+ lhs = fc.getThis();
- conflictGraph.addStallSite(taint2Effects, lhs, cd);
+ conflictGraph.addStallSite(taint2Effects, lhs, cd);
}
break;
}
if (conflictGraph.id2cn.size() > 0) {
- sese2conflictGraph.put(currentSESE, conflictGraph);
+ sese2conflictGraph.put(currentSESE, conflictGraph);
}
}
}
ConflictGraph conflictGraph = sese2conflictGraph.get(sese);
if (useReachInfo) {
- // clear current conflict before recalculating with reachability info
- conflictGraph.clearAllConflictEdge();
- conflictGraph.setDisJointAnalysis(disjointAnalysisReach);
- conflictGraph.setFMEnclosing(sese.getfmEnclosing());
+ // clear current conflict before recalculating with reachability info
+ conflictGraph.clearAllConflictEdge();
+ conflictGraph.setDisJointAnalysis(disjointAnalysisReach);
+ conflictGraph.setFMEnclosing(sese.getfmEnclosing());
}
conflictGraph.analyzeConflicts(sitesToFlag, useReachInfo);
sese2conflictGraph.put(sese, conflictGraph);
FlatNode key = (FlatNode) keyEnum.nextElement();
ConflictGraph cg = sese2conflictGraph.get(key);
try {
- if (cg.hasConflictEdge()) {
- cg.writeGraph("ConflictGraphFor" + key, false);
- }
+ if (cg.hasConflictEdge()) {
+ cg.writeGraph("ConflictGraphFor" + key, false);
+ }
} catch (IOException e) {
- System.out.println("Error writing");
- System.exit(0);
+ System.out.println("Error writing");
+ System.exit(0);
}
}
}
for (Iterator iterator = tempCover.iterator(); iterator.hasNext(); ) {
ConflictEdge conflictEdge = (ConflictEdge) iterator.next();
if (conflictEdge.isCoarseEdge()) {
- coarseToCover.add(conflictEdge);
+ coarseToCover.add(conflictEdge);
} else {
- fineToCover.add(conflictEdge);
+ fineToCover.add(conflictEdge);
}
}
do { // fine-grained edge
- changed = false;
-
- for (Iterator iterator = fineToCover.iterator(); iterator.hasNext(); ) {
-
- int type;
- ConflictEdge edge = (ConflictEdge) iterator.next();
- if (seseLock.getConflictNodeSet().size() == 0) {
- // initial setup
- if (seseLock.isWriteNode(edge.getVertexU())) {
- // mark as fine_write
- if (edge.getVertexU().isStallSiteNode()) {
- type = ConflictNode.PARENT_WRITE;
- } else {
- type = ConflictNode.FINE_WRITE;
- }
- seseLock.addConflictNode(edge.getVertexU(), type);
- } else {
- // mark as fine_read
- if (edge.getVertexU().isStallSiteNode()) {
- type = ConflictNode.PARENT_READ;
- } else {
- type = ConflictNode.FINE_READ;
- }
- seseLock.addConflictNode(edge.getVertexU(), type);
- }
- if (edge.getVertexV() != edge.getVertexU()) {
- if (seseLock.isWriteNode(edge.getVertexV())) {
- // mark as fine_write
- if (edge.getVertexV().isStallSiteNode()) {
- type = ConflictNode.PARENT_WRITE;
- } else {
- type = ConflictNode.FINE_WRITE;
- }
- seseLock.addConflictNode(edge.getVertexV(), type);
- } else {
- // mark as fine_read
- if (edge.getVertexV().isStallSiteNode()) {
- type = ConflictNode.PARENT_READ;
- } else {
- type = ConflictNode.FINE_READ;
- }
- seseLock.addConflictNode(edge.getVertexV(), type);
- }
- }
- changed = true;
- seseLock.addConflictEdge(edge);
- fineToCover.remove(edge);
- break; // exit iterator loop
- } // end of initial setup
-
- ConflictNode newNode;
- if ((newNode = seseLock.getNewNodeConnectedWithGroup(edge)) != null) {
- // new node has a fine-grained edge to all current node
- // If there is a coarse grained edge where need a fine edge, it's
- // okay to add the node
- // but the edge must remain uncovered.
-
- changed = true;
-
- if (seseLock.containsConflictNode(newNode)) {
- seseLock.addEdge(edge);
- fineToCover.remove(edge);
- break;
- }
-
- if (seseLock.isWriteNode(newNode)) {
- if (newNode.isStallSiteNode()) {
- type = ConflictNode.PARENT_WRITE;
- } else {
- type = ConflictNode.FINE_WRITE;
- }
- seseLock.setNodeType(newNode, type);
- } else {
- if (newNode.isStallSiteNode()) {
- type = ConflictNode.PARENT_READ;
- } else {
- type = ConflictNode.FINE_READ;
- }
- seseLock.setNodeType(newNode, type);
- }
-
- seseLock.addEdge(edge);
- Set<ConflictEdge> edgeSet = newNode.getEdgeSet();
- for (Iterator iterator2 = edgeSet.iterator(); iterator2.hasNext(); ) {
- ConflictEdge conflictEdge = (ConflictEdge) iterator2.next();
-
- // mark all fine edges between new node and nodes in the group as
- // covered
- if (!conflictEdge.getVertexU().equals(newNode)) {
- if (seseLock.containsConflictNode(conflictEdge.getVertexU())) {
- changed = true;
- seseLock.addConflictEdge(conflictEdge);
- fineToCover.remove(conflictEdge);
- }
- } else if (!conflictEdge.getVertexV().equals(newNode)) {
- if (seseLock.containsConflictNode(conflictEdge.getVertexV())) {
- changed = true;
- seseLock.addConflictEdge(conflictEdge);
- fineToCover.remove(conflictEdge);
- }
- }
-
- }
-
- break; // exit iterator loop
- }
- }
+ changed = false;
+
+ for (Iterator iterator = fineToCover.iterator(); iterator.hasNext(); ) {
+
+ int type;
+ ConflictEdge edge = (ConflictEdge) iterator.next();
+ if (seseLock.getConflictNodeSet().size() == 0) {
+ // initial setup
+ if (seseLock.isWriteNode(edge.getVertexU())) {
+ // mark as fine_write
+ if (edge.getVertexU().isStallSiteNode()) {
+ type = ConflictNode.PARENT_WRITE;
+ } else {
+ type = ConflictNode.FINE_WRITE;
+ }
+ seseLock.addConflictNode(edge.getVertexU(), type);
+ } else {
+ // mark as fine_read
+ if (edge.getVertexU().isStallSiteNode()) {
+ type = ConflictNode.PARENT_READ;
+ } else {
+ type = ConflictNode.FINE_READ;
+ }
+ seseLock.addConflictNode(edge.getVertexU(), type);
+ }
+ if (edge.getVertexV() != edge.getVertexU()) {
+ if (seseLock.isWriteNode(edge.getVertexV())) {
+ // mark as fine_write
+ if (edge.getVertexV().isStallSiteNode()) {
+ type = ConflictNode.PARENT_WRITE;
+ } else {
+ type = ConflictNode.FINE_WRITE;
+ }
+ seseLock.addConflictNode(edge.getVertexV(), type);
+ } else {
+ // mark as fine_read
+ if (edge.getVertexV().isStallSiteNode()) {
+ type = ConflictNode.PARENT_READ;
+ } else {
+ type = ConflictNode.FINE_READ;
+ }
+ seseLock.addConflictNode(edge.getVertexV(), type);
+ }
+ }
+ changed = true;
+ seseLock.addConflictEdge(edge);
+ fineToCover.remove(edge);
+ break; // exit iterator loop
+ } // end of initial setup
+
+ ConflictNode newNode;
+ if ((newNode = seseLock.getNewNodeConnectedWithGroup(edge)) != null) {
+ // new node has a fine-grained edge to all current node
+ // If there is a coarse grained edge where need a fine edge, it's
+ // okay to add the node
+ // but the edge must remain uncovered.
+
+ changed = true;
+
+ if (seseLock.containsConflictNode(newNode)) {
+ seseLock.addEdge(edge);
+ fineToCover.remove(edge);
+ break;
+ }
+
+ if (seseLock.isWriteNode(newNode)) {
+ if (newNode.isStallSiteNode()) {
+ type = ConflictNode.PARENT_WRITE;
+ } else {
+ type = ConflictNode.FINE_WRITE;
+ }
+ seseLock.setNodeType(newNode, type);
+ } else {
+ if (newNode.isStallSiteNode()) {
+ type = ConflictNode.PARENT_READ;
+ } else {
+ type = ConflictNode.FINE_READ;
+ }
+ seseLock.setNodeType(newNode, type);
+ }
+
+ seseLock.addEdge(edge);
+ Set<ConflictEdge> edgeSet = newNode.getEdgeSet();
+ for (Iterator iterator2 = edgeSet.iterator(); iterator2.hasNext(); ) {
+ ConflictEdge conflictEdge = (ConflictEdge) iterator2.next();
+
+ // mark all fine edges between new node and nodes in the group as
+ // covered
+ if (!conflictEdge.getVertexU().equals(newNode)) {
+ if (seseLock.containsConflictNode(conflictEdge.getVertexU())) {
+ changed = true;
+ seseLock.addConflictEdge(conflictEdge);
+ fineToCover.remove(conflictEdge);
+ }
+ } else if (!conflictEdge.getVertexV().equals(newNode)) {
+ if (seseLock.containsConflictNode(conflictEdge.getVertexV())) {
+ changed = true;
+ seseLock.addConflictEdge(conflictEdge);
+ fineToCover.remove(conflictEdge);
+ }
+ }
+
+ }
+
+ break; // exit iterator loop
+ }
+ }
} while (changed);
HashSet<ConflictEdge> notCovered = new HashSet<ConflictEdge>();
do { // coarse
- changed = false;
- int type;
- for (Iterator iterator = coarseToCover.iterator(); iterator.hasNext(); ) {
-
- ConflictEdge edge = (ConflictEdge) iterator.next();
- if (seseLock.getConflictNodeSet().size() == 0) {
- // initial setup
- if (seseLock.hasSelfCoarseEdge(edge.getVertexU())) {
- // node has a coarse-grained edge with itself
- if (!(edge.getVertexU().isStallSiteNode())) {
- // and it is not parent
- type = ConflictNode.SCC;
- } else {
- if (state.RCR) {
- type = ConflictNode.PARENT_COARSE;
- } else {
- type = ConflictNode.PARENT_WRITE;
- }
- }
- seseLock.addConflictNode(edge.getVertexU(), type);
- } else {
- if (edge.getVertexU().isStallSiteNode()) {
- if (state.RCR) {
- type = ConflictNode.PARENT_COARSE;
- } else {
- if (edge.getVertexU().getWriteEffectSet().isEmpty()) {
- type = ConflictNode.PARENT_READ;
- } else {
- type = ConflictNode.PARENT_WRITE;
- }
- }
- } else {
- type = ConflictNode.COARSE;
- }
- seseLock.addConflictNode(edge.getVertexU(), type);
- }
- if (seseLock.hasSelfCoarseEdge(edge.getVertexV())) {
- // node has a coarse-grained edge with itself
- if (!(edge.getVertexV().isStallSiteNode())) {
- // and it is not parent
- type = ConflictNode.SCC;
- } else {
- if (state.RCR) {
- type = ConflictNode.PARENT_COARSE;
- } else {
- type = ConflictNode.PARENT_WRITE;
- }
- }
- seseLock.addConflictNode(edge.getVertexV(), type);
- } else {
- if (edge.getVertexV().isStallSiteNode()) {
- if (state.RCR) {
- type = ConflictNode.PARENT_COARSE;
- } else {
- if (edge.getVertexV().getWriteEffectSet().isEmpty()) {
- type = ConflictNode.PARENT_READ;
- } else {
- type = ConflictNode.PARENT_WRITE;
- }
- }
- } else {
- type = ConflictNode.COARSE;
- }
- seseLock.addConflictNode(edge.getVertexV(), type);
- }
- changed = true;
- coarseToCover.remove(edge);
- seseLock.addConflictEdge(edge);
- break; // exit iterator loop
- } // end of initial setup
-
- ConflictNode newNode;
- if ((newNode = seseLock.getNewNodeConnectedWithGroup(edge)) != null) {
- // new node has a coarse-grained edge to all fine-read, fine-write,
- // parent
- changed = true;
-
- if (newNode.isInVarNode() && (!seseLock.hasSelfCoarseEdge(newNode))
- && seseLock.hasCoarseEdgeWithParentCoarse(newNode)) {
- // this case can't be covered by this queue
- coarseToCover.remove(edge);
- notCovered.add(edge);
- break;
- }
-
- if (seseLock.containsConflictNode(newNode)) {
- seseLock.addEdge(edge);
- coarseToCover.remove(edge);
- break;
- }
-
- if (seseLock.hasSelfCoarseEdge(newNode)) {
- // SCC
- if (newNode.isStallSiteNode()) {
- type = ConflictNode.PARENT_COARSE;
- } else {
- type = ConflictNode.SCC;
- }
- seseLock.setNodeType(newNode, type);
- } else {
- if (newNode.isStallSiteNode()) {
- type = ConflictNode.PARENT_COARSE;
- } else {
- type = ConflictNode.COARSE;
- }
- seseLock.setNodeType(newNode, type);
- }
-
- seseLock.addEdge(edge);
- Set<ConflictEdge> edgeSet = newNode.getEdgeSet();
- for (Iterator iterator2 = edgeSet.iterator(); iterator2.hasNext(); ) {
- ConflictEdge conflictEdge = (ConflictEdge) iterator2.next();
- // mark all coarse edges between new node and nodes in the group
- // as covered
- if (!conflictEdge.getVertexU().equals(newNode)) {
- if (seseLock.containsConflictNode(conflictEdge.getVertexU())) {
- changed = true;
- seseLock.addConflictEdge(conflictEdge);
- coarseToCover.remove(conflictEdge);
- }
- } else if (!conflictEdge.getVertexV().equals(newNode)) {
- if (seseLock.containsConflictNode(conflictEdge.getVertexV())) {
- changed = true;
- seseLock.addConflictEdge(conflictEdge);
- coarseToCover.remove(conflictEdge);
- }
- }
-
- }
- break; // exit iterator loop
- }
-
- }
+ changed = false;
+ int type;
+ for (Iterator iterator = coarseToCover.iterator(); iterator.hasNext(); ) {
+
+ ConflictEdge edge = (ConflictEdge) iterator.next();
+ if (seseLock.getConflictNodeSet().size() == 0) {
+ // initial setup
+ if (seseLock.hasSelfCoarseEdge(edge.getVertexU())) {
+ // node has a coarse-grained edge with itself
+ if (!(edge.getVertexU().isStallSiteNode())) {
+ // and it is not parent
+ type = ConflictNode.SCC;
+ } else {
+ if (state.RCR) {
+ type = ConflictNode.PARENT_COARSE;
+ } else {
+ type = ConflictNode.PARENT_WRITE;
+ }
+ }
+ seseLock.addConflictNode(edge.getVertexU(), type);
+ } else {
+ if (edge.getVertexU().isStallSiteNode()) {
+ if (state.RCR) {
+ type = ConflictNode.PARENT_COARSE;
+ } else {
+ if (edge.getVertexU().getWriteEffectSet().isEmpty()) {
+ type = ConflictNode.PARENT_READ;
+ } else {
+ type = ConflictNode.PARENT_WRITE;
+ }
+ }
+ } else {
+ type = ConflictNode.COARSE;
+ }
+ seseLock.addConflictNode(edge.getVertexU(), type);
+ }
+ if (seseLock.hasSelfCoarseEdge(edge.getVertexV())) {
+ // node has a coarse-grained edge with itself
+ if (!(edge.getVertexV().isStallSiteNode())) {
+ // and it is not parent
+ type = ConflictNode.SCC;
+ } else {
+ if (state.RCR) {
+ type = ConflictNode.PARENT_COARSE;
+ } else {
+ type = ConflictNode.PARENT_WRITE;
+ }
+ }
+ seseLock.addConflictNode(edge.getVertexV(), type);
+ } else {
+ if (edge.getVertexV().isStallSiteNode()) {
+ if (state.RCR) {
+ type = ConflictNode.PARENT_COARSE;
+ } else {
+ if (edge.getVertexV().getWriteEffectSet().isEmpty()) {
+ type = ConflictNode.PARENT_READ;
+ } else {
+ type = ConflictNode.PARENT_WRITE;
+ }
+ }
+ } else {
+ type = ConflictNode.COARSE;
+ }
+ seseLock.addConflictNode(edge.getVertexV(), type);
+ }
+ changed = true;
+ coarseToCover.remove(edge);
+ seseLock.addConflictEdge(edge);
+ break; // exit iterator loop
+ } // end of initial setup
+
+ ConflictNode newNode;
+ if ((newNode = seseLock.getNewNodeConnectedWithGroup(edge)) != null) {
+ // new node has a coarse-grained edge to all fine-read, fine-write,
+ // parent
+ changed = true;
+
+ if (newNode.isInVarNode() && (!seseLock.hasSelfCoarseEdge(newNode))
+ && seseLock.hasCoarseEdgeWithParentCoarse(newNode)) {
+ // this case can't be covered by this queue
+ coarseToCover.remove(edge);
+ notCovered.add(edge);
+ break;
+ }
+
+ if (seseLock.containsConflictNode(newNode)) {
+ seseLock.addEdge(edge);
+ coarseToCover.remove(edge);
+ break;
+ }
+
+ if (seseLock.hasSelfCoarseEdge(newNode)) {
+ // SCC
+ if (newNode.isStallSiteNode()) {
+ type = ConflictNode.PARENT_COARSE;
+ } else {
+ type = ConflictNode.SCC;
+ }
+ seseLock.setNodeType(newNode, type);
+ } else {
+ if (newNode.isStallSiteNode()) {
+ type = ConflictNode.PARENT_COARSE;
+ } else {
+ type = ConflictNode.COARSE;
+ }
+ seseLock.setNodeType(newNode, type);
+ }
+
+ seseLock.addEdge(edge);
+ Set<ConflictEdge> edgeSet = newNode.getEdgeSet();
+ for (Iterator iterator2 = edgeSet.iterator(); iterator2.hasNext(); ) {
+ ConflictEdge conflictEdge = (ConflictEdge) iterator2.next();
+ // mark all coarse edges between new node and nodes in the group
+ // as covered
+ if (!conflictEdge.getVertexU().equals(newNode)) {
+ if (seseLock.containsConflictNode(conflictEdge.getVertexU())) {
+ changed = true;
+ seseLock.addConflictEdge(conflictEdge);
+ coarseToCover.remove(conflictEdge);
+ }
+ } else if (!conflictEdge.getVertexV().equals(newNode)) {
+ if (seseLock.containsConflictNode(conflictEdge.getVertexV())) {
+ changed = true;
+ seseLock.addConflictEdge(conflictEdge);
+ coarseToCover.remove(conflictEdge);
+ }
+ }
+
+ }
+ break; // exit iterator loop
+ }
+
+ }
} while (changed);
lockSet.add(seseLock);
MethodDescriptor md = methItr.next();
FlatMethod fm = state.getMethodFlat(md);
if (fm != null) {
- bw =
- new BufferedWriter(new FileWriter("ooojReport_" + md.getClassMethodName()
- + md.getSafeMethodDescriptor() + ".txt"));
- bw.write("OoOJava Results for " + md + "\n-------------------\n");
-
- bw.write("Dynamic vars to manage:\n " + getContextTaskNames(fm).getDynamicVarSet());
-
- bw.write("\n\nLive-In, Root View\n------------------\n"
- + fm.printMethod(livenessGlobalView));
- bw.write("\n\nVariable Results-Out\n----------------\n" + fm.printMethod(variableResults));
- bw.write("\n\nNot Available Results-Out\n---------------------\n"
- + fm.printMethod(notAvailableResults));
- bw.write("\n\nCode Plans\n----------\n" + fm.printMethod(codePlans));
- bw.close();
+ bw =
+ new BufferedWriter(new FileWriter("ooojReport_" + md.getClassMethodName()
+ + md.getSafeMethodDescriptor() + ".txt"));
+ bw.write("OoOJava Results for " + md + "\n-------------------\n");
+
+ bw.write("Dynamic vars to manage:\n " + getContextTaskNames(fm).getDynamicVarSet());
+
+ bw.write("\n\nLive-In, Root View\n------------------\n"
+ + fm.printMethod(livenessGlobalView));
+ bw.write("\n\nVariable Results-Out\n----------------\n" + fm.printMethod(variableResults));
+ bw.write("\n\nNot Available Results-Out\n---------------------\n"
+ + fm.printMethod(notAvailableResults));
+ bw.write("\n\nCode Plans\n----------\n" + fm.printMethod(codePlans));
+ bw.close();
}
}
}
bw.write("SESE " + fsen.getPrettyIdentifier());
if (fsen.getIsLeafSESE()) {
- bw.write(" (leaf)");
+ bw.write(" (leaf)");
}
bw.write(" {\n");
bw.write(" in-set: " + fsen.getInVarSet() + "\n");
Iterator<TempDescriptor> tItr = fsen.getInVarSet().iterator();
while (tItr.hasNext()) {
- TempDescriptor inVar = tItr.next();
- if (fsen.getReadyInVarSet().contains(inVar)) {
- bw.write(" (ready) " + inVar + "\n");
- }
- if (fsen.getStaticInVarSet().contains(inVar)) {
- bw.write(" (static) " + inVar + " from " + fsen.getStaticInVarSrc(inVar) + "\n");
- }
- if (fsen.getDynamicInVarSet().contains(inVar)) {
- bw.write(" (dynamic)" + inVar + "\n");
- }
+ TempDescriptor inVar = tItr.next();
+ if (fsen.getReadyInVarSet().contains(inVar)) {
+ bw.write(" (ready) " + inVar + "\n");
+ }
+ if (fsen.getStaticInVarSet().contains(inVar)) {
+ bw.write(" (static) " + inVar + " from " + fsen.getStaticInVarSrc(inVar) + "\n");
+ }
+ if (fsen.getDynamicInVarSet().contains(inVar)) {
+ bw.write(" (dynamic)" + inVar + "\n");
+ }
}
bw.write(" Dynamic vars to manage: " + getContextTaskNames(fsen).getDynamicVarSet() + "\n");
bw.write(" out-set: " + fsen.getOutVarSet() + "\n");
tItr = fsen.getOutVarSet().iterator();
while (tItr.hasNext()) {
- TempDescriptor outVar = tItr.next();
- if (fsen.getReadyOutVarSet().contains(outVar)) {
- bw.write(" (ready) " + outVar + "\n");
- }
- if (fsen.getStaticOutVarSet().contains(outVar)) {
- bw.write(" (static) " + outVar + " from " + fsen.getStaticOutVarSrc(outVar) + "\n");
- }
- if (fsen.getDynamicOutVarSet().contains(outVar)) {
- bw.write(" (dynamic)" + outVar + "\n");
- }
+ TempDescriptor outVar = tItr.next();
+ if (fsen.getReadyOutVarSet().contains(outVar)) {
+ bw.write(" (ready) " + outVar + "\n");
+ }
+ if (fsen.getStaticOutVarSet().contains(outVar)) {
+ bw.write(" (static) " + outVar + " from " + fsen.getStaticOutVarSrc(outVar) + "\n");
+ }
+ if (fsen.getDynamicOutVarSet().contains(outVar)) {
+ bw.write(" (dynamic)" + outVar + "\n");
+ }
}
bw.write(" local parent: " + fsen.getLocalParent() + "\n");
FlatNode curr=toprocess.pop();
Set<FlatSESEEnterNode> callers=fn2currentSESEs.get(curr);
if (callers!=null) {
- for(FlatSESEEnterNode sese : callers) {
- if (!seseSet.contains(sese)) {
- seseSet.add(sese);
- toprocess.add(fn);
- }
- }
+ for(FlatSESEEnterNode sese : callers) {
+ if (!seseSet.contains(sese)) {
+ seseSet.add(sese);
+ toprocess.add(fn);
+ }
+ }
}
}
return seseSet;
seseStacks.put(fm, seseStackFirst);
while( !flatNodesToVisit.isEmpty() ) {
- Iterator<FlatNode> fnItr = flatNodesToVisit.iterator();
- FlatNode fn = fnItr.next();
+ Iterator<FlatNode> fnItr = flatNodesToVisit.iterator();
+ FlatNode fn = fnItr.next();
- Stack<FlatSESEEnterNode> seseStack = seseStacks.get(fn);
- assert seseStack != null;
+ Stack<FlatSESEEnterNode> seseStack = seseStacks.get(fn);
+ assert seseStack != null;
- flatNodesToVisit.remove(fn);
- visited.add(fn);
+ flatNodesToVisit.remove(fn);
+ visited.add(fn);
- if( !seseStack.isEmpty() ) {
- fn2localInnerSESE.put(fn, seseStack.peek() );
- }
+ if( !seseStack.isEmpty() ) {
+ fn2localInnerSESE.put(fn, seseStack.peek() );
+ }
- nodeActions(fn, seseStack, fm);
+ nodeActions(fn, seseStack, fm);
- for( int i = 0; i < fn.numNext(); i++ ) {
- FlatNode nn = fn.getNext(i);
+ for( int i = 0; i < fn.numNext(); i++ ) {
+ FlatNode nn = fn.getNext(i);
- if( !visited.contains(nn) ) {
- flatNodesToVisit.add(nn);
+ if( !visited.contains(nn) ) {
+ flatNodesToVisit.add(nn);
- // clone stack and send along each control path
- seseStacks.put(nn, (Stack<FlatSESEEnterNode>)seseStack.clone() );
- }
- }
+ // clone stack and send along each control path
+ seseStacks.put(nn, (Stack<FlatSESEEnterNode>)seseStack.clone() );
+ }
+ }
}
}
}
fsen.setcdEnclosing(fm.getMethod().getClassDesc() );
if( seseStack.empty() ) {
- // no local parent
- fsen.setLocalParent(null);
+ // no local parent
+ fsen.setLocalParent(null);
- allLocalRootSESEs.add(fsen);
+ allLocalRootSESEs.add(fsen);
- Set<FlatSESEEnterNode> seseSet = md2localRootSESEs.get(fm.getMethod() );
- if( seseSet == null ) {
- seseSet = new HashSet<FlatSESEEnterNode>();
- }
- seseSet.add(fsen);
- md2localRootSESEs.put(fm.getMethod(), seseSet);
+ Set<FlatSESEEnterNode> seseSet = md2localRootSESEs.get(fm.getMethod() );
+ if( seseSet == null ) {
+ seseSet = new HashSet<FlatSESEEnterNode>();
+ }
+ seseSet.add(fsen);
+ md2localRootSESEs.put(fm.getMethod(), seseSet);
} else {
- // otherwise a local parent/child relation
- // which is also the broader parent/child
- // relation as well
- seseStack.peek().addLocalChild(fsen);
- fsen.setLocalParent(seseStack.peek() );
-
- seseStack.peek().addChild(fsen);
- fsen.addParent(seseStack.peek() );
+ // otherwise a local parent/child relation
+ // which is also the broader parent/child
+ // relation as well
+ seseStack.peek().addLocalChild(fsen);
+ fsen.setLocalParent(seseStack.peek() );
+
+ seseStack.peek().addChild(fsen);
+ fsen.addParent(seseStack.peek() );
}
seseStack.push(fsen);
case FKind.FlatReturnNode: {
FlatReturnNode frn = (FlatReturnNode) fn;
if( !seseStack.empty() ) {
- throw new Error("Error: return statement enclosed within SESE "+
- seseStack.peek().getPrettyIdentifier() );
+ throw new Error("Error: return statement enclosed within SESE "+
+ seseStack.peek().getPrettyIdentifier() );
}
} break;
visited.add(fn);
if( fn.kind() == FKind.FlatCall ) {
- FlatCall fc = (FlatCall) fn;
- MethodDescriptor mdCallee = fc.getMethod();
- Set reachable = new HashSet();
-
- reachable.add(mdCallee);
- reachable.addAll(callGraph.getAllMethods(mdCallee) );
- reachable.retainAll(methodsContainingSESEs);
-
- if( !reachable.isEmpty() ) {
- hasChildrenByCall = true;
-
- Set reachableSESEMethodSet =
- callGraph.getFirstReachableMethodContainingSESE(mdCallee, methodsContainingSESEs);
-
- reachableSESEMethodSet.add(mdCallee);
- reachableSESEMethodSet.retainAll(methodsContainingSESEs);
-
- for( Iterator iterator = reachableSESEMethodSet.iterator(); iterator.hasNext(); ) {
- MethodDescriptor md = (MethodDescriptor) iterator.next();
- Set<FlatSESEEnterNode> seseSet = md2localRootSESEs.get(md);
- if( seseSet != null ) {
- fsen.addChildren(seseSet);
- for( Iterator iterator2 = seseSet.iterator(); iterator2.hasNext(); ) {
- FlatSESEEnterNode child = (FlatSESEEnterNode) iterator2.next();
- child.addParent(fsen);
- }
- }
- }
- }
+ FlatCall fc = (FlatCall) fn;
+ MethodDescriptor mdCallee = fc.getMethod();
+ Set reachable = new HashSet();
+
+ reachable.add(mdCallee);
+ reachable.addAll(callGraph.getAllMethods(mdCallee) );
+ reachable.retainAll(methodsContainingSESEs);
+
+ if( !reachable.isEmpty() ) {
+ hasChildrenByCall = true;
+
+ Set reachableSESEMethodSet =
+ callGraph.getFirstReachableMethodContainingSESE(mdCallee, methodsContainingSESEs);
+
+ reachableSESEMethodSet.add(mdCallee);
+ reachableSESEMethodSet.retainAll(methodsContainingSESEs);
+
+ for( Iterator iterator = reachableSESEMethodSet.iterator(); iterator.hasNext(); ) {
+ MethodDescriptor md = (MethodDescriptor) iterator.next();
+ Set<FlatSESEEnterNode> seseSet = md2localRootSESEs.get(md);
+ if( seseSet != null ) {
+ fsen.addChildren(seseSet);
+ for( Iterator iterator2 = seseSet.iterator(); iterator2.hasNext(); ) {
+ FlatSESEEnterNode child = (FlatSESEEnterNode) iterator2.next();
+ child.addParent(fsen);
+ }
+ }
+ }
+ }
}
if( fn == fsen.getFlatExit() ) {
- // don't enqueue any futher nodes
- continue;
+ // don't enqueue any futher nodes
+ continue;
}
for( int i = 0; i < fn.numNext(); i++ ) {
- FlatNode nn = fn.getNext(i);
+ FlatNode nn = fn.getNext(i);
- if( !visited.contains(nn) ) {
- flatNodesToVisit.add(nn);
- }
+ if( !visited.contains(nn) ) {
+ flatNodesToVisit.add(nn);
+ }
}
}
new Hashtable<FlatNode, FlatMethod>();
for( int i = 0; i < fsen.numNext(); i++ ) {
- FlatNode nn = fsen.getNext(i);
- flatNodesToVisit.put(nn, fsen.getfmEnclosing() );
+ FlatNode nn = fsen.getNext(i);
+ flatNodesToVisit.put(nn, fsen.getfmEnclosing() );
}
Set<FlatNode> visited = new HashSet<FlatNode>();
while (!flatNodesToVisit.isEmpty()) {
- Map.Entry me = (Map.Entry)flatNodesToVisit.entrySet().iterator().next();
- FlatNode fn = (FlatNode) me.getKey();
- FlatMethod fm = (FlatMethod) me.getValue();
-
- flatNodesToVisit.remove(fn);
- visited.add(fn);
-
- // the "is potential stall site" strategy is to propagate
- // "false" from the beginning of a task until you hit a
- // child, then from the child's exit propagate "true" for
- // the parent statements after children. When you pull a node
- // out of the bag for traversal and it happens to be an
- // enter or an exit node, fix the dumb propagation that
- // your IR predecessor pushed on you
- Boolean isPotentialStallSite = isPotentialStallSite(fn);
-
- if (fn == fsen.getFlatExit()) {
- // don't enqueue any further nodes when you find your exit,
- // NOR mark your own flat as a statement you are currently
- // executing, your parent(s) will mark it
- continue;
- }
-
- if (fn instanceof FlatSESEExitNode) {
- setIsPotentialStallSite(fn, false);
- isPotentialStallSite = true;
- }
-
- // the purpose of this traversal is to find program
- // points where rblock 'fsen' might be executing
- addPossibleExecutingRBlock(fn, fsen);
-
- if (fn instanceof FlatSESEEnterNode) {
- // don't visit internal nodes of child,
- // just enqueue the exit node
- FlatSESEEnterNode child = (FlatSESEEnterNode) fn;
- assert fsen.getChildren().contains(child);
- assert child.getParents().contains(fsen);
- flatNodesToVisit.put(child.getFlatExit(), fm);
- setIsPotentialStallSite(fn, false);
-
- // explicitly do this to handle the case that you
- // should mark yourself as possibly executing at
- // your own exit, because one instance can
- // recursively invoke another
- addPossibleExecutingRBlock(child.getFlatExit(), fsen);
-
- continue;
- }
-
- // if previous flat nodes have any changes,,
- // propagate predecessor's status of stall site potential
-
- if (fn instanceof FlatCall) {
-
- // start visiting nodes in other contexts
- FlatCall fc = (FlatCall) fn;
- MethodDescriptor mdCallee = fc.getMethod();
-
- Set<MethodDescriptor> implementations = new HashSet<MethodDescriptor>();
-
- if (mdCallee.isStatic()) {
- implementations.add(mdCallee);
- } else {
- TypeDescriptor typeDesc = fc.getThis().getType();
- implementations.addAll(callGraph.getMethods(mdCallee, typeDesc));
- }
-
- for (Iterator imps = implementations.iterator(); imps.hasNext(); ) {
- MethodDescriptor mdImp = (MethodDescriptor) imps.next();
- FlatMethod fmImp = state.getMethodFlat(mdImp);
-
- // keep mapping from fc's md to <fc,caller's md>
- // later, when return node of callee becomes a potential stall site,
- // following flat nodes of fc should be re-analyzied
- if(!methodmap.containsKey(fmImp)) {
- methodmap.put(mdImp, new HashSet<Pair<FlatCall,MethodDescriptor>>());
- }
- methodmap.get(mdImp).add(new Pair<FlatCall,MethodDescriptor>(fc,fm.getMethod()));
-
- if ((isPotentialStallSite && !isPotentialStallSite(fmImp)) || !visited.contains(fmImp)) {
- flatNodesToVisit.put(fmImp, fmImp);
-
- // propagate your IR graph predecessor's stall site potential
- mergeIsPotentialStallSite(fmImp, isPotentialStallSite);
- }
-
- }
- // don't 'continue' out of this loop, also enqueue
- // flat nodes that flow in the current method context
- }
-
- if (fn instanceof FlatReturnNode) {
- // if return node is potential stall site, need to inform its caller
- if (isPotentialStallSite) {
- Set<Pair<FlatCall, MethodDescriptor>> callset = methodmap.get(fm.getMethod());
- if (callset != null) {
- for (Pair<FlatCall, MethodDescriptor> fcallpair : callset) {
- FlatCall fcall = fcallpair.getFirst();
- MethodDescriptor mdcaller = fcallpair.getSecond();
- for (int i = 0; i < fcall.numNext(); i++) {
- FlatNode nn = fcall.getNext(i);
- if ( visited.contains(nn) && (!isPotentialStallSite(nn)) ) {
- mergeIsPotentialStallSite(nn, isPotentialStallSite);
- FlatMethod fmcaller = state.getMethodFlat(mdcaller);
- flatNodesToVisit.put(nn, fmcaller);
- }
- }
- }
- }
- }
- }
-
- // note: only when current flat node has a change on the status of potential
- // stall site, need to visit following flat nodes
- for (int i = 0; i < fn.numNext(); i++) {
- FlatNode nn = fn.getNext(i);
- if ((isPotentialStallSite && !isPotentialStallSite(nn)) || !visited.contains(nn)) {
- flatNodesToVisit.put(nn, fm);
- mergeIsPotentialStallSite(nn, isPotentialStallSite);
- }
- }
+ Map.Entry me = (Map.Entry)flatNodesToVisit.entrySet().iterator().next();
+ FlatNode fn = (FlatNode) me.getKey();
+ FlatMethod fm = (FlatMethod) me.getValue();
+
+ flatNodesToVisit.remove(fn);
+ visited.add(fn);
+
+ // the "is potential stall site" strategy is to propagate
+ // "false" from the beginning of a task until you hit a
+ // child, then from the child's exit propagate "true" for
+ // the parent statements after children. When you pull a node
+ // out of the bag for traversal and it happens to be an
+ // enter or an exit node, fix the dumb propagation that
+ // your IR predecessor pushed on you
+ Boolean isPotentialStallSite = isPotentialStallSite(fn);
+
+ if (fn == fsen.getFlatExit()) {
+ // don't enqueue any further nodes when you find your exit,
+ // NOR mark your own flat as a statement you are currently
+ // executing, your parent(s) will mark it
+ continue;
+ }
+
+ if (fn instanceof FlatSESEExitNode) {
+ setIsPotentialStallSite(fn, false);
+ isPotentialStallSite = true;
+ }
+
+ // the purpose of this traversal is to find program
+ // points where rblock 'fsen' might be executing
+ addPossibleExecutingRBlock(fn, fsen);
+
+ if (fn instanceof FlatSESEEnterNode) {
+ // don't visit internal nodes of child,
+ // just enqueue the exit node
+ FlatSESEEnterNode child = (FlatSESEEnterNode) fn;
+ assert fsen.getChildren().contains(child);
+ assert child.getParents().contains(fsen);
+ flatNodesToVisit.put(child.getFlatExit(), fm);
+ setIsPotentialStallSite(fn, false);
+
+ // explicitly do this to handle the case that you
+ // should mark yourself as possibly executing at
+ // your own exit, because one instance can
+ // recursively invoke another
+ addPossibleExecutingRBlock(child.getFlatExit(), fsen);
+
+ continue;
+ }
+
+ // if previous flat nodes have any changes,,
+ // propagate predecessor's status of stall site potential
+
+ if (fn instanceof FlatCall) {
+
+ // start visiting nodes in other contexts
+ FlatCall fc = (FlatCall) fn;
+ MethodDescriptor mdCallee = fc.getMethod();
+
+ Set<MethodDescriptor> implementations = new HashSet<MethodDescriptor>();
+
+ if (mdCallee.isStatic()) {
+ implementations.add(mdCallee);
+ } else {
+ TypeDescriptor typeDesc = fc.getThis().getType();
+ implementations.addAll(callGraph.getMethods(mdCallee, typeDesc));
+ }
+
+ for (Iterator imps = implementations.iterator(); imps.hasNext(); ) {
+ MethodDescriptor mdImp = (MethodDescriptor) imps.next();
+ FlatMethod fmImp = state.getMethodFlat(mdImp);
+
+ // keep mapping from fc's md to <fc,caller's md>
+ // later, when return node of callee becomes a potential stall site,
+ // following flat nodes of fc should be re-analyzied
+ if(!methodmap.containsKey(fmImp)) {
+ methodmap.put(mdImp, new HashSet<Pair<FlatCall,MethodDescriptor>>());
+ }
+ methodmap.get(mdImp).add(new Pair<FlatCall,MethodDescriptor>(fc,fm.getMethod()));
+
+ if ((isPotentialStallSite && !isPotentialStallSite(fmImp)) || !visited.contains(fmImp)) {
+ flatNodesToVisit.put(fmImp, fmImp);
+
+ // propagate your IR graph predecessor's stall site potential
+ mergeIsPotentialStallSite(fmImp, isPotentialStallSite);
+ }
+
+ }
+ // don't 'continue' out of this loop, also enqueue
+ // flat nodes that flow in the current method context
+ }
+
+ if (fn instanceof FlatReturnNode) {
+ // if return node is potential stall site, need to inform its caller
+ if (isPotentialStallSite) {
+ Set<Pair<FlatCall, MethodDescriptor>> callset = methodmap.get(fm.getMethod());
+ if (callset != null) {
+ for (Pair<FlatCall, MethodDescriptor> fcallpair : callset) {
+ FlatCall fcall = fcallpair.getFirst();
+ MethodDescriptor mdcaller = fcallpair.getSecond();
+ for (int i = 0; i < fcall.numNext(); i++) {
+ FlatNode nn = fcall.getNext(i);
+ if ( visited.contains(nn) && (!isPotentialStallSite(nn)) ) {
+ mergeIsPotentialStallSite(nn, isPotentialStallSite);
+ FlatMethod fmcaller = state.getMethodFlat(mdcaller);
+ flatNodesToVisit.put(nn, fmcaller);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // note: only when current flat node has a change on the status of potential
+ // stall site, need to visit following flat nodes
+ for (int i = 0; i < fn.numNext(); i++) {
+ FlatNode nn = fn.getNext(i);
+ if ((isPotentialStallSite && !isPotentialStallSite(nn)) || !visited.contains(nn)) {
+ flatNodesToVisit.put(nn, fm);
+ mergeIsPotentialStallSite(nn, isPotentialStallSite);
+ }
+ }
}
}
}
System.out.println(fn+"[["+isPotentialStallSite(fn)+"]]");
for (int i = 0; i < fn.numNext(); i++) {
- FlatNode nn = fn.getNext(i);
+ FlatNode nn = fn.getNext(i);
- if (!visited.contains(nn)) {
- flatNodesToVisit.add(nn);
- }
+ if (!visited.contains(nn)) {
+ flatNodesToVisit.add(nn);
+ }
}
}
}
ConflictEdge conflictEdge = (ConflictEdge) iterator.next();
if (conflictEdge.isCoarseEdge() && conflictEdge.getVertexU() == conflictEdge.getVertexV()) {
- return true;
+ return true;
}
}
return false;
ConflictEdge conflictEdge = (ConflictEdge) iterator.next();
if ((!conflictEdge.isCoarseEdge()) && conflictEdge.getVertexU() == conflictEdge.getVertexV()) {
- return true;
+ return true;
}
}
return false;
ConflictNode cNode;
if (conflictEdge.getVertexU() == node) {
- cNode = conflictEdge.getVertexV();
+ cNode = conflictEdge.getVertexV();
} else {
- cNode = conflictEdge.getVertexU();
+ cNode = conflictEdge.getVertexU();
}
Integer cNodeTypeIn = nodeTypeMap.get(cNode);
if (cNodeTypeIn != null && cNodeTypeIn.intValue() == ConflictNode.PARENT_COARSE) {
- return true;
+ return true;
}
}
return false;
ConflictEdge conflictEdge = (ConflictEdge) iterator.next();
if (!conflictEdge.getVertexU().equals(newNode)
&& conflictNodeSet.contains(conflictEdge.getVertexU())) {
- count++;
+ count++;
} else if (!conflictEdge.getVertexV().equals(newNode)
&& conflictNodeSet.contains(conflictEdge.getVertexV())) {
- count++;
+ count++;
}
}
if(isWriteNode(newNode)) {
if (count == conflictNodeSet.size()) {
- // connected to all current nodes in group
- return newNode;
+ // connected to all current nodes in group
+ return newNode;
}
} else {
// it is read node
int writeNodeCount=0;
for (Iterator iterator = conflictNodeSet.iterator(); iterator.hasNext(); ) {
- ConflictNode node = (ConflictNode) iterator.next();
- if(isWriteNode(node)) {
- writeNodeCount++;
- }
+ ConflictNode node = (ConflictNode) iterator.next();
+ if(isWriteNode(node)) {
+ writeNodeCount++;
+ }
}
if (count == writeNodeCount) {
- // connected to all current write nodes in group
- return newNode;
+ // connected to all current write nodes in group
+ return newNode;
}
}
}
ConflictNode nodeToAdd = conflictNodeSet.contains(newEdge.getVertexU())?newEdge.getVertexV()
- :newEdge.getVertexU();
+ :newEdge.getVertexU();
HashSet<ConflictNode> nodeSet = new HashSet<ConflictNode>(conflictNodeSet);
for (Iterator edgeIter = nodeToAdd.getEdgeSet().iterator(); edgeIter.hasNext(); ) {
ConflictEdge edge = (ConflictEdge) edgeIter.next();
if (nodeSet.contains(edge.getVertexU())) {
- nodeSet.remove(edge.getVertexU());
+ nodeSet.remove(edge.getVertexU());
} else if (nodeSet.contains(edge.getVertexV())) {
- nodeSet.remove(edge.getVertexV());
+ nodeSet.remove(edge.getVertexV());
}
}
WaitingElement we=wit.next();
TempDescriptor tmp=we.getTempDesc();
if (!tmp2WaitingElement.containsKey(tmp))
- tmp2WaitingElement.put(tmp, new HashSet<WaitingElement>());
+ tmp2WaitingElement.put(tmp, new HashSet<WaitingElement>());
tmp2WaitingElement.get(tmp).add(we);
}
}
VariableSourceToken vstAlready = trueSet.get(vst);
if (vstAlready!=null) {
- removePrivate(vstAlready);
- HashSet<TempDescriptor> toAddSet=new HashSet<TempDescriptor>();
- toAddSet.addAll(vstAlready.getRefVars());
- toAddSet.addAll(vst.getRefVars());
- vst.setRefVars(toAddSet);
+ removePrivate(vstAlready);
+ HashSet<TempDescriptor> toAddSet=new HashSet<TempDescriptor>();
+ toAddSet.addAll(vstAlready.getRefVars());
+ toAddSet.addAll(vst.getRefVars());
+ vst.setRefVars(toAddSet);
}
}
TempDescriptor refVar = refVarItr.next();
s = var2vst.get(refVar);
if( s == null ) {
- s = new HashSet<VariableSourceToken>();
- var2vst.put(refVar, s);
+ s = new HashSet<VariableSourceToken>();
+ var2vst.put(refVar, s);
}
s.add(vst);
SVKey key = new SVKey(vst.getSESE(), refVar);
s = sv2vst.get(key);
if( s == null ) {
- s = new HashSet<VariableSourceToken>();
- sv2vst.put(key, s);
+ s = new HashSet<VariableSourceToken>();
+ sv2vst.put(key, s);
}
s.add(vst);
}
while( sItr.hasNext() ) {
VariableSourceToken vst = sItr.next();
if( !vst.getAge().equals(age) ) {
- s.remove(vst);
+ s.remove(vst);
}
}
s = get(refVar);
if( s != null ) {
- s.remove(vst);
- if( s.isEmpty() ) {
- var2vst.remove(refVar);
- }
+ s.remove(vst);
+ if( s.isEmpty() ) {
+ var2vst.remove(refVar);
+ }
}
s = get(vst.getSESE(), refVar);
if( s != null ) {
- s.remove(vst);
- if( s.isEmpty() ) {
- sv2vst.remove(new SVKey(vst.getSESE(), refVar) );
- }
+ s.remove(vst);
+ if( s.isEmpty() ) {
+ sv2vst.remove(new SVKey(vst.getSESE(), refVar) );
+ }
}
}
}
// referencing this token, just take it
// out of the table all together
if( refVars.size() == 1 ) {
- removePrivate(vst);
+ removePrivate(vst);
}
sv2vst.remove(new SVKey(vst.getSESE(), refVar) );
if( vst.getSESE().equals(curr) ) {
- // only age if the token isn't already the maximum age
- if( vst.getAge() < MAX_AGE ) {
+ // only age if the token isn't already the maximum age
+ if( vst.getAge() < MAX_AGE ) {
- forRemoval.add(vst);
+ forRemoval.add(vst);
- forAddition.add(new VariableSourceToken(vst.getRefVars(),
- curr,
- vst.getAge() + 1,
- vst.getAddrVar()
- )
- );
- }
+ forAddition.add(new VariableSourceToken(vst.getRefVars(),
+ curr,
+ vst.getAge() + 1,
+ vst.getAddrVar()
+ )
+ );
+ }
}
}
Iterator<VariableSourceToken> vstItr = get(child).iterator();
while( vstItr.hasNext() ) {
- VariableSourceToken vst = vstItr.next();
- removalSet.add(vst);
-
- additionSet.add(new VariableSourceToken(vst.getRefVars(),
- curr,
- new Integer(0),
- vst.getAddrVar()
- )
- );
+ VariableSourceToken vst = vstItr.next();
+ removalSet.add(vst);
+
+ additionSet.add(new VariableSourceToken(vst.getRefVars(),
+ curr,
+ new Integer(0),
+ vst.getAddrVar()
+ )
+ );
}
// remove( eah item in forremoval )
vstItr = removalSet.iterator();
while( vstItr.hasNext() ) {
- VariableSourceToken vst = vstItr.next();
- remove(vst);
+ VariableSourceToken vst = vstItr.next();
+ remove(vst);
}
// add( each ite inm for additon _
vstItr = additionSet.iterator();
while( vstItr.hasNext() ) {
- VariableSourceToken vst = vstItr.next();
- add(vst);
+ VariableSourceToken vst = vstItr.next();
+ add(vst);
}
}
Iterator<FlatSESEEnterNode> childItr;
if( ancestor == null ) {
- // when some caller task is the next parent, the siblings
- // of the current task are other local root tasks
- ancestor = rblockRel.getCallerProxySESE();
- childItr = rblockRel.getLocalRootSESEs(exiter.getfmEnclosing() ).iterator();
- findMore = false;
+ // when some caller task is the next parent, the siblings
+ // of the current task are other local root tasks
+ ancestor = rblockRel.getCallerProxySESE();
+ childItr = rblockRel.getLocalRootSESEs(exiter.getfmEnclosing() ).iterator();
+ findMore = false;
} else {
- // otherwise, the siblings are locally-defined
- childItr = ancestor.getLocalChildren().iterator();
+ // otherwise, the siblings are locally-defined
+ childItr = ancestor.getLocalChildren().iterator();
- // and there is no further ancestry beyond the main task
- if( ancestor.equals(rblockRel.getMainSESE() ) ) {
- findMore = false;
- }
+ // and there is no further ancestry beyond the main task
+ if( ancestor.equals(rblockRel.getMainSESE() ) ) {
+ findMore = false;
+ }
}
// this ancestor and its children are valid alternate sources
alternateSESEs.add(ancestor);
while( childItr.hasNext() ) {
- FlatSESEEnterNode sibling = childItr.next();
- alternateSESEs.add(sibling);
+ FlatSESEEnterNode sibling = childItr.next();
+ alternateSESEs.add(sibling);
}
}
// only interested in sources from our current instance
if( vstExiterSrc.getAge() != 0 ) {
- continue;
+ continue;
}
// for each variable that might come from those sources...
Iterator<TempDescriptor> refVarItr = vstExiterSrc.getRefVars().iterator();
while( refVarItr.hasNext() ) {
- TempDescriptor refVar = refVarItr.next();
-
- // only matters for live variables at SESE exit program point
- if( !liveVars.contains(refVar) ) {
- continue;
- }
-
- // examine other sources for a variable...
- Iterator<VariableSourceToken> srcItr = get(refVar).iterator();
- while( srcItr.hasNext() ) {
- VariableSourceToken vstPossibleOtherSrc = srcItr.next();
-
- if( vstPossibleOtherSrc.getSESE().equals(exiter) &&
- vstPossibleOtherSrc.getAge() > 0
- ) {
- // this is an alternate source if its
- // an older instance of this SESE
- virtReadSet.add(refVar);
- forRemoval.add(vstPossibleOtherSrc);
-
- } else if( alternateSESEs.contains(vstPossibleOtherSrc.getSESE() ) ) {
- // this is an alternate source from ancestor or ancestor's sibling
- virtReadSet.add(refVar);
- forRemoval.add(vstPossibleOtherSrc);
-
- } else {
- if( !(vstPossibleOtherSrc.getSESE().equals(exiter) &&
- vstPossibleOtherSrc.getAge().equals(0)
- )
- ) {
- System.out.println("For refVar="+refVar+" at exit of "+exiter+
- ", unexpected possible variable source "+vstPossibleOtherSrc);
- assert false;
- }
- }
- }
+ TempDescriptor refVar = refVarItr.next();
+
+ // only matters for live variables at SESE exit program point
+ if( !liveVars.contains(refVar) ) {
+ continue;
+ }
+
+ // examine other sources for a variable...
+ Iterator<VariableSourceToken> srcItr = get(refVar).iterator();
+ while( srcItr.hasNext() ) {
+ VariableSourceToken vstPossibleOtherSrc = srcItr.next();
+
+ if( vstPossibleOtherSrc.getSESE().equals(exiter) &&
+ vstPossibleOtherSrc.getAge() > 0
+ ) {
+ // this is an alternate source if its
+ // an older instance of this SESE
+ virtReadSet.add(refVar);
+ forRemoval.add(vstPossibleOtherSrc);
+
+ } else if( alternateSESEs.contains(vstPossibleOtherSrc.getSESE() ) ) {
+ // this is an alternate source from ancestor or ancestor's sibling
+ virtReadSet.add(refVar);
+ forRemoval.add(vstPossibleOtherSrc);
+
+ } else {
+ if( !(vstPossibleOtherSrc.getSESE().equals(exiter) &&
+ vstPossibleOtherSrc.getAge().equals(0)
+ )
+ ) {
+ System.out.println("For refVar="+refVar+" at exit of "+exiter+
+ ", unexpected possible variable source "+vstPossibleOtherSrc);
+ assert false;
+ }
+ }
+ }
}
}
// only worth tracking if live
if( nextLiveIn.contains(var) ) {
- VSTWrapper vstIfStaticBefore = new VSTWrapper();
- VSTWrapper vstIfStaticAfter = new VSTWrapper();
-
- Integer srcTypeBefore = this.getRefVarSrcType(var, current, vstIfStaticBefore);
- Integer srcTypeAfter = nextTable.getRefVarSrcType(var, current, vstIfStaticAfter);
-
- if( !srcTypeBefore.equals(SrcType_DYNAMIC) &&
- srcTypeAfter.equals(SrcType_DYNAMIC)
- ) {
- // remember the variable and a source
- // it had before crossing the transition
- // 1) if it was ready, vstIfStatic.vst is null
- // 2) if is was static, use vstIfStatic.vst
- out.put(var, vstIfStaticBefore);
- }
+ VSTWrapper vstIfStaticBefore = new VSTWrapper();
+ VSTWrapper vstIfStaticAfter = new VSTWrapper();
+
+ Integer srcTypeBefore = this.getRefVarSrcType(var, current, vstIfStaticBefore);
+ Integer srcTypeAfter = nextTable.getRefVarSrcType(var, current, vstIfStaticAfter);
+
+ if( !srcTypeBefore.equals(SrcType_DYNAMIC) &&
+ srcTypeAfter.equals(SrcType_DYNAMIC)
+ ) {
+ // remember the variable and a source
+ // it had before crossing the transition
+ // 1) if it was ready, vstIfStatic.vst is null
+ // 2) if is was static, use vstIfStatic.vst
+ out.put(var, vstIfStaticBefore);
+ }
}
}
if( case1 || case2 ) {
- // if we ever have at least one child source with an
- // unknown age, have to treat var as dynamic
- if( vst.getAge().equals(OoOJavaAnalysis.maxSESEage) ) {
- return SrcType_DYNAMIC;
- }
-
- // if we have a known-age child source, this var is
- // either static or dynamic now: it's static if this
- // source is the only source, otherwise dynamic
- if( srcs.size() > 1 ) {
- return SrcType_DYNAMIC;
- }
-
- vstIfStatic.vst = vst;
- return SrcType_STATIC;
+ // if we ever have at least one child source with an
+ // unknown age, have to treat var as dynamic
+ if( vst.getAge().equals(OoOJavaAnalysis.maxSESEage) ) {
+ return SrcType_DYNAMIC;
+ }
+
+ // if we have a known-age child source, this var is
+ // either static or dynamic now: it's static if this
+ // source is the only source, otherwise dynamic
+ if( srcs.size() > 1 ) {
+ return SrcType_DYNAMIC;
+ }
+
+ vstIfStatic.vst = vst;
+ return SrcType_STATIC;
}
}
vstItr = s1.iterator();
while( vstItr.hasNext() ) {
- str += " "+tokHighlighter+" "+vstItr.next()+"\n";
+ str += " "+tokHighlighter+" "+vstItr.next()+"\n";
}
}
vstItr = s1.iterator();
while( vstItr.hasNext() ) {
- str += " "+tokHighlighter+" "+vstItr.next()+"\n";
+ str += " "+tokHighlighter+" "+vstItr.next()+"\n";
}
}
vstItr = s1.iterator();
while( vstItr.hasNext() ) {
- str += " "+tokHighlighter+" "+vstItr.next()+"\n";
+ str += " "+tokHighlighter+" "+vstItr.next()+"\n";
}
}
for( int i = 0; i < allocationDepth - 1; ++i ) {
if( id.equals(ithOldest.get(i) ) ) {
- return AGE_in_I;
+ return AGE_in_I;
}
}
public Integer getAge(Integer id) {
for( int i = 0; i < allocationDepth - 1; ++i ) {
if( id.equals(ithOldest.get(i) ) ) {
- return new Integer(i);
+ return new Integer(i);
}
}
for( int i = 0; i < allocationDepth - 1; ++i ) {
if( id.equals(getIthOldestShadow(i) ) ) {
- return SHADOWAGE_in_I;
+ return SHADOWAGE_in_I;
}
}
public Integer getShadowAge(Integer id) {
for( int i = 0; i < allocationDepth - 1; ++i ) {
if( id.equals(getIthOldestShadow(i) ) ) {
- return new Integer(-i);
+ return new Integer(-i);
}
}
oldHashSet = true;
} else {
if( oldHash != currentHash ) {
- System.out.println("IF YOU SEE THIS A CANONICAL ChangeTuple CHANGED");
- Integer x = null;
- x.toString();
+ System.out.println("IF YOU SEE THIS A CANONICAL ChangeTuple CHANGED");
+ Integer x = null;
+ x.toString();
}
}
oldHashSet = true;
} else {
if( oldHash != currentHash ) {
- System.out.println("IF YOU SEE THIS A CANONICAL ChangeTupleSet CHANGED");
- Integer x = null;
- x.toString();
+ System.out.println("IF YOU SEE THIS A CANONICAL ChangeTupleSet CHANGED");
+ Integer x = null;
+ x.toString();
}
}
if (newSet != null) {
HashSet<EffectsKey> aSet = readTable.get(idx);
if (aSet == null) {
- aSet = new HashSet<EffectsKey>();
+ aSet = new HashSet<EffectsKey>();
}
aSet.addAll(newSet);
readTable.put(idx, aSet);
if (newSet != null) {
HashSet<EffectsKey> aSet = writeTable.get(idx);
if (aSet == null) {
- aSet = new HashSet<EffectsKey>();
+ aSet = new HashSet<EffectsKey>();
}
aSet.addAll(newSet);
writeTable.put(idx, aSet);
if (newSet != null) {
HashSet<EffectsKey> aSet = strongUpdateTable.get(idx);
if (aSet == null) {
- aSet = new HashSet<EffectsKey>();
+ aSet = new HashSet<EffectsKey>();
}
aSet.addAll(newSet);
strongUpdateTable.put(idx, aSet);
Set<EffectsKey> effectSet = readTable.get(idx);
String keyStr = "{";
if (effectSet != null) {
- Iterator<EffectsKey> effectIter = effectSet.iterator();
- while (effectIter.hasNext()) {
- EffectsKey key = effectIter.next();
- keyStr += " " + key;
- }
+ Iterator<EffectsKey> effectIter = effectSet.iterator();
+ while (effectIter.hasNext()) {
+ EffectsKey key = effectIter.next();
+ keyStr += " " + key;
+ }
} else {
- keyStr = "null";
+ keyStr = "null";
}
System.out.println("param" + idx + " R=" + keyStr);
}
Set<EffectsKey> effectSet = writeTable.get(idx);
String keyStr = "{";
if (effectSet != null) {
- Iterator<EffectsKey> effectIter = effectSet.iterator();
- while (effectIter.hasNext()) {
- EffectsKey key = effectIter.next();
- keyStr += " " + key;
- }
+ Iterator<EffectsKey> effectIter = effectSet.iterator();
+ while (effectIter.hasNext()) {
+ EffectsKey key = effectIter.next();
+ keyStr += " " + key;
+ }
} else {
- keyStr = "null";
+ keyStr = "null";
}
System.out.println("param" + idx + " W=" + keyStr);
}
if( edge.getSrc().equals(on) &&
edge.typeEquals(type) &&
edge.fieldEquals(field) ) {
- return edge;
+ return edge;
}
}
while( i.hasNext() ) {
s += i.next();
if( i.hasNext() ) {
- s += "a";
+ s += "a";
}
}
Iterator<ReferenceEdge> heapRegionsItr = ln.iteratorToReferencees();
while (heapRegionsItr.hasNext()) {
- ReferenceEdge edge = heapRegionsItr.next();
- HeapRegionNode hrn = edge.getDst();
+ ReferenceEdge edge = heapRegionsItr.next();
+ HeapRegionNode hrn = edge.getDst();
- if (hrn.isParameter()) {
- Set<Integer> paramSet = og.idPrimary2paramIndexSet.get(hrn
- .getID());
+ if (hrn.isParameter()) {
+ Set<Integer> paramSet = og.idPrimary2paramIndexSet.get(hrn
+ .getID());
- if (paramSet != null) {
- Iterator<Integer> paramIter = paramSet.iterator();
- while (paramIter.hasNext()) {
- Integer paramID = paramIter.next();
- effectsSet.addReadingVar(paramID, new EffectsKey(
- fieldDesc.getSymbol(), srcDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0));
+ if (paramSet != null) {
+ Iterator<Integer> paramIter = paramSet.iterator();
+ while (paramIter.hasNext()) {
+ Integer paramID = paramIter.next();
+ effectsSet.addReadingVar(paramID, new EffectsKey(
+ fieldDesc.getSymbol(), srcDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0));
- }
- }
+ }
+ }
- // check weather this heap region is parameter
- // reachable...
+ // check weather this heap region is parameter
+ // reachable...
- paramSet = og.idSecondary2paramIndexSet.get(hrn.getID());
- if (paramSet != null) {
- Iterator<Integer> paramIter = paramSet.iterator();
+ paramSet = og.idSecondary2paramIndexSet.get(hrn.getID());
+ if (paramSet != null) {
+ Iterator<Integer> paramIter = paramSet.iterator();
- while (paramIter.hasNext()) {
- Integer paramID = paramIter.next();
- effectsSet.addReadingVar(paramID, new EffectsKey(
- fieldDesc.getSymbol(), srcDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),1));
+ while (paramIter.hasNext()) {
+ Integer paramID = paramIter.next();
+ effectsSet.addReadingVar(paramID, new EffectsKey(
+ fieldDesc.getSymbol(), srcDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),1));
- }
- }
+ }
+ }
- }
+ }
}
}
Iterator<ReferenceEdge> heapRegionsItr = ln.iteratorToReferencees();
while (heapRegionsItr.hasNext()) {
- ReferenceEdge edge = heapRegionsItr.next();
- HeapRegionNode hrn = edge.getDst();
-
- if (hrn.isParameter()) {
- Set<Integer> paramSet = og.idPrimary2paramIndexSet.get(hrn
- .getID());
-
- if (paramSet != null) {
- Iterator<Integer> paramIter = paramSet.iterator();
- while (paramIter.hasNext()) {
- Integer paramID = paramIter.next();
- effectsSet.addReadingVar(paramID, new EffectsKey(
- fieldDesc.getSymbol(), srcDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0));
- }
- }
-
- // check weather this heap region is parameter
- // reachable...
-
- paramSet = og.idSecondary2paramIndexSet.get(hrn.getID());
- if (paramSet != null) {
- Iterator<Integer> paramIter = paramSet.iterator();
-
- while (paramIter.hasNext()) {
- Integer paramID = paramIter.next();
- effectsSet.addReadingVar(paramID, new EffectsKey(
- fieldDesc.getSymbol(), srcDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),1));
- }
- }
-
- }
+ ReferenceEdge edge = heapRegionsItr.next();
+ HeapRegionNode hrn = edge.getDst();
+
+ if (hrn.isParameter()) {
+ Set<Integer> paramSet = og.idPrimary2paramIndexSet.get(hrn
+ .getID());
+
+ if (paramSet != null) {
+ Iterator<Integer> paramIter = paramSet.iterator();
+ while (paramIter.hasNext()) {
+ Integer paramID = paramIter.next();
+ effectsSet.addReadingVar(paramID, new EffectsKey(
+ fieldDesc.getSymbol(), srcDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0));
+ }
+ }
+
+ // check weather this heap region is parameter
+ // reachable...
+
+ paramSet = og.idSecondary2paramIndexSet.get(hrn.getID());
+ if (paramSet != null) {
+ Iterator<Integer> paramIter = paramSet.iterator();
+
+ while (paramIter.hasNext()) {
+ Integer paramID = paramIter.next();
+ effectsSet.addReadingVar(paramID, new EffectsKey(
+ fieldDesc.getSymbol(), srcDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),1));
+ }
+ }
+
+ }
}
}
boolean strongUpdate = false;
if (!fieldDesc.getType().isImmutable()
|| fieldDesc.getType().isArray()) {
- Iterator<ReferenceEdge> itrXhrn = ln.iteratorToReferencees();
- while (itrXhrn.hasNext()) {
- ReferenceEdge edgeX = itrXhrn.next();
- HeapRegionNode hrnX = edgeX.getDst();
-
- if (fieldDesc != null
- && fieldDesc != OwnershipAnalysis
- .getArrayField(fieldDesc.getType())
- && ((hrnX.getNumReferencers() == 1) || // case 1
- (hrnX.isSingleObject() && ln.getNumReferencees() == 1) // case
- // 2
- )) {
- strongUpdate = true;
- }
- }
+ Iterator<ReferenceEdge> itrXhrn = ln.iteratorToReferencees();
+ while (itrXhrn.hasNext()) {
+ ReferenceEdge edgeX = itrXhrn.next();
+ HeapRegionNode hrnX = edgeX.getDst();
+
+ if (fieldDesc != null
+ && fieldDesc != OwnershipAnalysis
+ .getArrayField(fieldDesc.getType())
+ && ((hrnX.getNumReferencers() == 1) || // case 1
+ (hrnX.isSingleObject() && ln.getNumReferencees() == 1) // case
+ // 2
+ )) {
+ strongUpdate = true;
+ }
+ }
}
// //
Iterator<ReferenceEdge> heapRegionsItr = ln.iteratorToReferencees();
while (heapRegionsItr.hasNext()) {
- ReferenceEdge edge = heapRegionsItr.next();
- HeapRegionNode hrn = edge.getDst();
-
- if (hrn.isParameter()) {
- Set<Integer> paramSet = og.idPrimary2paramIndexSet.get(hrn
- .getID());
-
- if (paramSet != null) {
- Iterator<Integer> paramIter = paramSet.iterator();
- while (paramIter.hasNext()) {
- Integer paramID = paramIter.next();
- effectsSet.addWritingVar(paramID, new EffectsKey(
- fieldDesc.getSymbol(), dstDesc.getType(),
- hrn.getID(), hrn
- .getGloballyUniqueIdentifier(), 0));
- if(strongUpdate) {
- effectsSet.addStrongUpdateVar(paramID, new EffectsKey(
- fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0));
- }
- }
- }
-
- // check weather this heap region is parameter
- // reachable...
-
- paramSet = og.idSecondary2paramIndexSet.get(hrn.getID());
- if (paramSet != null) {
- Iterator<Integer> paramIter = paramSet.iterator();
-
- while (paramIter.hasNext()) {
- Integer paramID = paramIter.next();
- effectsSet.addWritingVar(paramID, new EffectsKey(
- fieldDesc.getSymbol(), dstDesc.getType(),
- hrn.getID(), hrn
- .getGloballyUniqueIdentifier(), 1));
- if(strongUpdate) {
- effectsSet.addStrongUpdateVar(paramID, new EffectsKey(
- fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0));
- }
- }
- }
-
- }
+ ReferenceEdge edge = heapRegionsItr.next();
+ HeapRegionNode hrn = edge.getDst();
+
+ if (hrn.isParameter()) {
+ Set<Integer> paramSet = og.idPrimary2paramIndexSet.get(hrn
+ .getID());
+
+ if (paramSet != null) {
+ Iterator<Integer> paramIter = paramSet.iterator();
+ while (paramIter.hasNext()) {
+ Integer paramID = paramIter.next();
+ effectsSet.addWritingVar(paramID, new EffectsKey(
+ fieldDesc.getSymbol(), dstDesc.getType(),
+ hrn.getID(), hrn
+ .getGloballyUniqueIdentifier(), 0));
+ if(strongUpdate) {
+ effectsSet.addStrongUpdateVar(paramID, new EffectsKey(
+ fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0));
+ }
+ }
+ }
+
+ // check weather this heap region is parameter
+ // reachable...
+
+ paramSet = og.idSecondary2paramIndexSet.get(hrn.getID());
+ if (paramSet != null) {
+ Iterator<Integer> paramIter = paramSet.iterator();
+
+ while (paramIter.hasNext()) {
+ Integer paramID = paramIter.next();
+ effectsSet.addWritingVar(paramID, new EffectsKey(
+ fieldDesc.getSymbol(), dstDesc.getType(),
+ hrn.getID(), hrn
+ .getGloballyUniqueIdentifier(), 1));
+ if(strongUpdate) {
+ effectsSet.addStrongUpdateVar(paramID, new EffectsKey(
+ fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0));
+ }
+ }
+ }
+
+ }
}
}
/// check possible strong updates
boolean strongUpdate = false;
if( !fieldDesc.getType().isImmutable() || fieldDesc.getType().isArray() ) {
- Iterator<ReferenceEdge> itrXhrn = ln.iteratorToReferencees();
- while( itrXhrn.hasNext() ) {
- ReferenceEdge edgeX = itrXhrn.next();
- HeapRegionNode hrnX = edgeX.getDst();
-
- if( fieldDesc != null &&
- fieldDesc != OwnershipAnalysis.getArrayField(fieldDesc.getType() ) &&
- ( (hrnX.getNumReferencers() == 1) || // case 1
- (hrnX.isSingleObject() && ln.getNumReferencees() == 1) // case 2
- )
- ) {
- strongUpdate = true;
- }
- }
+ Iterator<ReferenceEdge> itrXhrn = ln.iteratorToReferencees();
+ while( itrXhrn.hasNext() ) {
+ ReferenceEdge edgeX = itrXhrn.next();
+ HeapRegionNode hrnX = edgeX.getDst();
+
+ if( fieldDesc != null &&
+ fieldDesc != OwnershipAnalysis.getArrayField(fieldDesc.getType() ) &&
+ ( (hrnX.getNumReferencers() == 1) || // case 1
+ (hrnX.isSingleObject() && ln.getNumReferencees() == 1) // case 2
+ )
+ ) {
+ strongUpdate = true;
+ }
+ }
}
////
Iterator<ReferenceEdge> heapRegionsItr = ln.iteratorToReferencees();
while (heapRegionsItr.hasNext()) {
- ReferenceEdge edge = heapRegionsItr.next();
- HeapRegionNode hrn = edge.getDst();
-
- if (hrn.isParameter()) {
-
- Set<Integer> paramSet = og.idPrimary2paramIndexSet.get(hrn
- .getID());
-
- if (paramSet != null) {
- Iterator<Integer> paramIter = paramSet.iterator();
- while (paramIter.hasNext()) {
- Integer paramID = paramIter.next();
- effectsSet.addWritingVar(paramID, new EffectsKey(
- fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0));
- if(strongUpdate) {
- effectsSet.addStrongUpdateVar(paramID, new EffectsKey(
- fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0));
- }
-
- }
- }
-
- // check weather this heap region is parameter
- // reachable...
-
- paramSet = og.idSecondary2paramIndexSet.get(hrn.getID());
- if (paramSet != null) {
- Iterator<Integer> paramIter = paramSet.iterator();
-
- while (paramIter.hasNext()) {
- Integer paramID = paramIter.next();
- effectsSet.addWritingVar(paramID, new EffectsKey(
- fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),1));
- if(strongUpdate) {
- effectsSet.addStrongUpdateVar(paramID, new EffectsKey(
- fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),1));
- }
-
- }
- }
-
- }
+ ReferenceEdge edge = heapRegionsItr.next();
+ HeapRegionNode hrn = edge.getDst();
+
+ if (hrn.isParameter()) {
+
+ Set<Integer> paramSet = og.idPrimary2paramIndexSet.get(hrn
+ .getID());
+
+ if (paramSet != null) {
+ Iterator<Integer> paramIter = paramSet.iterator();
+ while (paramIter.hasNext()) {
+ Integer paramID = paramIter.next();
+ effectsSet.addWritingVar(paramID, new EffectsKey(
+ fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0));
+ if(strongUpdate) {
+ effectsSet.addStrongUpdateVar(paramID, new EffectsKey(
+ fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),0));
+ }
+
+ }
+ }
+
+ // check weather this heap region is parameter
+ // reachable...
+
+ paramSet = og.idSecondary2paramIndexSet.get(hrn.getID());
+ if (paramSet != null) {
+ Iterator<Integer> paramIter = paramSet.iterator();
+
+ while (paramIter.hasNext()) {
+ Integer paramID = paramIter.next();
+ effectsSet.addWritingVar(paramID, new EffectsKey(
+ fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),1));
+ if(strongUpdate) {
+ effectsSet.addStrongUpdateVar(paramID, new EffectsKey(
+ fieldDesc.getSymbol(), dstDesc.getType(),hrn.getID(),hrn.getGloballyUniqueIdentifier(),1));
+ }
+
+ }
+ }
+
+ }
}
}
Iterator<ReferenceEdge> heapRegionsItr = ln.iteratorToReferencees();
while (heapRegionsItr.hasNext()) {
- ReferenceEdge edge = heapRegionsItr.next();
- HeapRegionNode hrn = edge.getDst();
+ ReferenceEdge edge = heapRegionsItr.next();
+ HeapRegionNode hrn = edge.getDst();
- if (hrn.isParameter()) {
+ if (hrn.isParameter()) {
- Set<Integer> paramSet = og.idPrimary2paramIndexSet.get(hrn
- .getID());
+ Set<Integer> paramSet = og.idPrimary2paramIndexSet.get(hrn
+ .getID());
- if (paramSet != null) {
- Iterator<Integer> paramIter = paramSet.iterator();
- while (paramIter.hasNext()) {
- Integer paramID = paramIter.next();
+ if (paramSet != null) {
+ Iterator<Integer> paramIter = paramSet.iterator();
+ while (paramIter.hasNext()) {
+ Integer paramID = paramIter.next();
- resultSet.add(paramID);
+ resultSet.add(paramID);
- }
- }
+ }
+ }
- // check weather this heap region is parameter
- // reachable...
+ // check weather this heap region is parameter
+ // reachable...
- paramSet = og.idSecondary2paramIndexSet.get(hrn.getID());
- if (paramSet != null) {
- Iterator<Integer> paramIter = paramSet.iterator();
+ paramSet = og.idSecondary2paramIndexSet.get(hrn.getID());
+ if (paramSet != null) {
+ Iterator<Integer> paramIter = paramSet.iterator();
- while (paramIter.hasNext()) {
- Integer paramID = paramIter.next();
+ while (paramIter.hasNext()) {
+ Integer paramID = paramIter.next();
- resultSet.add(paramID);
+ resultSet.add(paramID);
- }
- }
+ }
+ }
- }
+ }
}
}
// handle read effects
Iterator<Integer> paramIter = paramIDs.iterator();
while (paramIter.hasNext()) {
- Integer paramIdx = paramIter.next();
- HashSet<EffectsKey> newSet = callee.getEffects().getReadTable()
- .get(calleeParamIdx);
-
-
- if(newSet!=null) {
- HashSet<EffectsKey> thisSet=new HashSet<EffectsKey>();
- HeapRegionNode priHRN=og.id2hrn.get(og.paramIndex2idPrimary.get(paramIdx));
- Integer secIdx=og.paramIndex2idSecondary.get(paramIdx);
- HeapRegionNode secHRN=null;
- if(secIdx!=null) {
- secHRN=og.id2hrn.get(secIdx);
- } else {
- secHRN=priHRN;
- }
-
- for (Iterator iterator = newSet.iterator(); iterator.hasNext(); ) {
- EffectsKey effectsKey = (EffectsKey) iterator.next();
- HeapRegionNode hrnTemp;
- if(effectsKey.getParamIden()==0) { //primary
- hrnTemp=priHRN;
- } else { //secondary
- hrnTemp=secHRN;
- }
- EffectsKey newEffectsKey;
- if(secIdx==null) {
- newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),0);
- } else {
- newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),effectsKey.getParamIden());
- }
- thisSet.add(newEffectsKey);
- }
-
- effectsSet.addReadingEffectsSet(paramIdx, thisSet);
- }
+ Integer paramIdx = paramIter.next();
+ HashSet<EffectsKey> newSet = callee.getEffects().getReadTable()
+ .get(calleeParamIdx);
+
+
+ if(newSet!=null) {
+ HashSet<EffectsKey> thisSet=new HashSet<EffectsKey>();
+ HeapRegionNode priHRN=og.id2hrn.get(og.paramIndex2idPrimary.get(paramIdx));
+ Integer secIdx=og.paramIndex2idSecondary.get(paramIdx);
+ HeapRegionNode secHRN=null;
+ if(secIdx!=null) {
+ secHRN=og.id2hrn.get(secIdx);
+ } else {
+ secHRN=priHRN;
+ }
+
+ for (Iterator iterator = newSet.iterator(); iterator.hasNext(); ) {
+ EffectsKey effectsKey = (EffectsKey) iterator.next();
+ HeapRegionNode hrnTemp;
+ if(effectsKey.getParamIden()==0) { //primary
+ hrnTemp=priHRN;
+ } else { //secondary
+ hrnTemp=secHRN;
+ }
+ EffectsKey newEffectsKey;
+ if(secIdx==null) {
+ newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),0);
+ } else {
+ newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),effectsKey.getParamIden());
+ }
+ thisSet.add(newEffectsKey);
+ }
+
+ effectsSet.addReadingEffectsSet(paramIdx, thisSet);
+ }
}
// handle write effects
paramIter = paramIDs.iterator();
while (paramIter.hasNext()) {
- Integer paramIdx = paramIter.next();
- HashSet<EffectsKey> newSet = callee.getEffects()
- .getWriteTable().get(calleeParamIdx);
-
- if(newSet!=null) {
-
- HashSet<EffectsKey> thisSet=new HashSet<EffectsKey>();
- HeapRegionNode priHRN=og.id2hrn.get(og.paramIndex2idPrimary.get(paramIdx));
- Integer secIdx=og.paramIndex2idSecondary.get(paramIdx);
- HeapRegionNode secHRN=null;
- if(secIdx!=null) {
- secHRN=og.id2hrn.get(secIdx);
- } else {
- secHRN=priHRN;
- }
-
- for (Iterator iterator = newSet.iterator(); iterator.hasNext(); ) {
- EffectsKey effectsKey = (EffectsKey) iterator.next();
- HeapRegionNode hrnTemp;
- if(effectsKey.getParamIden()==0) { //primary
- hrnTemp=priHRN;
- } else { //secondary
- hrnTemp=secHRN;
- }
- EffectsKey newEffectsKey;
- if(secIdx==null) {
- newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),0);
- } else {
- newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),effectsKey.getParamIden());
- }
- thisSet.add(newEffectsKey);
- }
-
- effectsSet.addWritingEffectsSet(paramIdx, thisSet);
- }
+ Integer paramIdx = paramIter.next();
+ HashSet<EffectsKey> newSet = callee.getEffects()
+ .getWriteTable().get(calleeParamIdx);
+
+ if(newSet!=null) {
+
+ HashSet<EffectsKey> thisSet=new HashSet<EffectsKey>();
+ HeapRegionNode priHRN=og.id2hrn.get(og.paramIndex2idPrimary.get(paramIdx));
+ Integer secIdx=og.paramIndex2idSecondary.get(paramIdx);
+ HeapRegionNode secHRN=null;
+ if(secIdx!=null) {
+ secHRN=og.id2hrn.get(secIdx);
+ } else {
+ secHRN=priHRN;
+ }
+
+ for (Iterator iterator = newSet.iterator(); iterator.hasNext(); ) {
+ EffectsKey effectsKey = (EffectsKey) iterator.next();
+ HeapRegionNode hrnTemp;
+ if(effectsKey.getParamIden()==0) { //primary
+ hrnTemp=priHRN;
+ } else { //secondary
+ hrnTemp=secHRN;
+ }
+ EffectsKey newEffectsKey;
+ if(secIdx==null) {
+ newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),0);
+ } else {
+ newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),effectsKey.getParamIden());
+ }
+ thisSet.add(newEffectsKey);
+ }
+
+ effectsSet.addWritingEffectsSet(paramIdx, thisSet);
+ }
}
// handle strong update effects
paramIter = paramIDs.iterator();
while (paramIter.hasNext()) {
- Integer paramIdx = paramIter.next();
- HashSet<EffectsKey> newSet = callee.getEffects()
- .getStrongUpdateTable().get(calleeParamIdx);
- if(newSet!=null) {
-
- HashSet<EffectsKey> thisSet=new HashSet<EffectsKey>();
- HeapRegionNode priHRN=og.id2hrn.get(og.paramIndex2idPrimary.get(paramIdx));
- Integer secIdx=og.paramIndex2idSecondary.get(paramIdx);
- HeapRegionNode secHRN=null;
- if(secIdx!=null) {
- secHRN=og.id2hrn.get(secIdx);
- } else {
- secHRN=priHRN;
- }
-
- for (Iterator iterator = newSet.iterator(); iterator.hasNext(); ) {
- EffectsKey effectsKey = (EffectsKey) iterator.next();
- HeapRegionNode hrnTemp;
- if(effectsKey.getParamIden()==0) { //primary
- hrnTemp=priHRN;
- } else { //secondary
- hrnTemp=secHRN;
- }
- EffectsKey newEffectsKey;
- if(secIdx==null) {
- newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),0);
- } else {
- newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),effectsKey.getParamIden());
- }
- thisSet.add(newEffectsKey);
- }
-
- effectsSet.addStrongUpdateEffectsSet(paramIdx, thisSet);
- }
+ Integer paramIdx = paramIter.next();
+ HashSet<EffectsKey> newSet = callee.getEffects()
+ .getStrongUpdateTable().get(calleeParamIdx);
+ if(newSet!=null) {
+
+ HashSet<EffectsKey> thisSet=new HashSet<EffectsKey>();
+ HeapRegionNode priHRN=og.id2hrn.get(og.paramIndex2idPrimary.get(paramIdx));
+ Integer secIdx=og.paramIndex2idSecondary.get(paramIdx);
+ HeapRegionNode secHRN=null;
+ if(secIdx!=null) {
+ secHRN=og.id2hrn.get(secIdx);
+ } else {
+ secHRN=priHRN;
+ }
+
+ for (Iterator iterator = newSet.iterator(); iterator.hasNext(); ) {
+ EffectsKey effectsKey = (EffectsKey) iterator.next();
+ HeapRegionNode hrnTemp;
+ if(effectsKey.getParamIden()==0) { //primary
+ hrnTemp=priHRN;
+ } else { //secondary
+ hrnTemp=secHRN;
+ }
+ EffectsKey newEffectsKey;
+ if(secIdx==null) {
+ newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),0);
+ } else {
+ newEffectsKey=new EffectsKey(effectsKey.getFieldDescriptor(), effectsKey.getTypeDescriptor(), hrnTemp.getID(),hrnTemp.getGloballyUniqueIdentifier(),effectsKey.getParamIden());
+ }
+ thisSet.add(newEffectsKey);
+ }
+
+ effectsSet.addStrongUpdateEffectsSet(paramIdx, thisSet);
+ }
}
Set<MethodContext> mcSet = mapMethodContextToMethodEffects.keySet();
Iterator<MethodContext> mcIter = mcSet.iterator();
while (mcIter.hasNext()) {
- MethodContext mc = mcIter.next();
- MethodDescriptor md = (MethodDescriptor) mc.getDescriptor();
-
- int startIdx = 0;
- if (!md.isStatic()) {
- startIdx = 1;
- }
-
- MethodEffects me = mapMethodContextToMethodEffects.get(mc);
- EffectsSet effectsSet = me.getEffects();
-
- bw.write("Method " + mc + " :\n");
- for (int i = startIdx; i < md.numParameters() + startIdx; i++) {
-
- String paramName = md.getParamName(i - startIdx);
-
- Set<EffectsKey> effectSet = effectsSet.getReadingSet(i);
- String keyStr = "{";
- if (effectSet != null) {
- Iterator<EffectsKey> effectIter = effectSet.iterator();
- while (effectIter.hasNext()) {
- EffectsKey key = effectIter.next();
- keyStr += " " + key;
- }
- }
- keyStr += " }";
- bw.write(" Paramter " + paramName + " ReadingSet="
- + keyStr + "\n");
-
- effectSet = effectsSet.getWritingSet(new Integer(i));
- keyStr = "{";
- if (effectSet != null) {
- Iterator<EffectsKey> effectIter = effectSet.iterator();
- while (effectIter.hasNext()) {
- EffectsKey key = effectIter.next();
- keyStr += " " + key;
- }
- }
-
- keyStr += " }";
- bw.write(" Paramter " + paramName + " WritingngSet="
- + keyStr + "\n");
-
- }
- bw.write("\n");
+ MethodContext mc = mcIter.next();
+ MethodDescriptor md = (MethodDescriptor) mc.getDescriptor();
+
+ int startIdx = 0;
+ if (!md.isStatic()) {
+ startIdx = 1;
+ }
+
+ MethodEffects me = mapMethodContextToMethodEffects.get(mc);
+ EffectsSet effectsSet = me.getEffects();
+
+ bw.write("Method " + mc + " :\n");
+ for (int i = startIdx; i < md.numParameters() + startIdx; i++) {
+
+ String paramName = md.getParamName(i - startIdx);
+
+ Set<EffectsKey> effectSet = effectsSet.getReadingSet(i);
+ String keyStr = "{";
+ if (effectSet != null) {
+ Iterator<EffectsKey> effectIter = effectSet.iterator();
+ while (effectIter.hasNext()) {
+ EffectsKey key = effectIter.next();
+ keyStr += " " + key;
+ }
+ }
+ keyStr += " }";
+ bw.write(" Paramter " + paramName + " ReadingSet="
+ + keyStr + "\n");
+
+ effectSet = effectsSet.getWritingSet(new Integer(i));
+ keyStr = "{";
+ if (effectSet != null) {
+ Iterator<EffectsKey> effectIter = effectSet.iterator();
+ while (effectIter.hasNext()) {
+ EffectsKey key = effectIter.next();
+ keyStr += " " + key;
+ }
+ }
+
+ keyStr += " }";
+ bw.write(" Paramter " + paramName + " WritingngSet="
+ + keyStr + "\n");
+
+ }
+ bw.write("\n");
}
AllocationSite as = n.getAllocationSite();
if( as == null ) {
- out += " "+n.toString()+",\n";
+ out += " "+n.toString()+",\n";
} else {
- out += " "+n.toString()+": "+as.toStringVerbose()+",\n";
+ out += " "+n.toString()+": "+as.toStringVerbose()+",\n";
}
}
TaskDescriptor td = (TaskDescriptor) taskItr.next();
if( !tabularOutput ) {
- bw.write("\n---------"+td+"--------\n");
+ bw.write("\n---------"+td+"--------\n");
}
HashSet<AllocationSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
FlatMethod fm = state.getMethodFlat(td);
for( int i = 0; i < fm.numParameters(); ++i ) {
- // for the ith parameter check for aliases to all
- // higher numbered parameters
- for( int j = i + 1; j < fm.numParameters(); ++j ) {
- common = createsPotentialAliases(td, i, j);
- if( !common.isEmpty() ) {
- foundSomeAlias = true;
- if( !tabularOutput ) {
- bw.write("Potential alias between parameters "+i+" and "+j+".\n");
- bw.write(prettyPrintNodeSet(common)+"\n");
- } else {
- ++numAlias;
- }
- }
- }
-
- // for the ith parameter, check for aliases against
- // the set of allocation sites reachable from this
- // task context
- Iterator allocItr = allocSites.iterator();
- while( allocItr.hasNext() ) {
- AllocationSite as = (AllocationSite) allocItr.next();
- common = createsPotentialAliases(td, i, as);
- if( !common.isEmpty() ) {
- foundSomeAlias = true;
- if( !tabularOutput ) {
- bw.write("Potential alias between parameter "+i+" and "+as.getFlatNew()+".\n");
- bw.write(prettyPrintNodeSet(common)+"\n");
- } else {
- ++numAlias;
- }
- }
- }
+ // for the ith parameter check for aliases to all
+ // higher numbered parameters
+ for( int j = i + 1; j < fm.numParameters(); ++j ) {
+ common = createsPotentialAliases(td, i, j);
+ if( !common.isEmpty() ) {
+ foundSomeAlias = true;
+ if( !tabularOutput ) {
+ bw.write("Potential alias between parameters "+i+" and "+j+".\n");
+ bw.write(prettyPrintNodeSet(common)+"\n");
+ } else {
+ ++numAlias;
+ }
+ }
+ }
+
+ // for the ith parameter, check for aliases against
+ // the set of allocation sites reachable from this
+ // task context
+ Iterator allocItr = allocSites.iterator();
+ while( allocItr.hasNext() ) {
+ AllocationSite as = (AllocationSite) allocItr.next();
+ common = createsPotentialAliases(td, i, as);
+ if( !common.isEmpty() ) {
+ foundSomeAlias = true;
+ if( !tabularOutput ) {
+ bw.write("Potential alias between parameter "+i+" and "+as.getFlatNew()+".\n");
+ bw.write(prettyPrintNodeSet(common)+"\n");
+ } else {
+ ++numAlias;
+ }
+ }
+ }
}
// for each allocation site check for aliases with
HashSet<AllocationSite> outerChecked = new HashSet<AllocationSite>();
Iterator allocItr1 = allocSites.iterator();
while( allocItr1.hasNext() ) {
- AllocationSite as1 = (AllocationSite) allocItr1.next();
-
- Iterator allocItr2 = allocSites.iterator();
- while( allocItr2.hasNext() ) {
- AllocationSite as2 = (AllocationSite) allocItr2.next();
-
- if( !outerChecked.contains(as2) ) {
- common = createsPotentialAliases(td, as1, as2);
-
- if( !common.isEmpty() ) {
- foundSomeAlias = true;
- if( !tabularOutput ) {
- bw.write("Potential alias between "+as1.getFlatNew()+" and "+as2.getFlatNew()+".\n");
- bw.write(prettyPrintNodeSet(common)+"\n");
- } else {
- ++numAlias;
- }
- }
- }
- }
-
- outerChecked.add(as1);
+ AllocationSite as1 = (AllocationSite) allocItr1.next();
+
+ Iterator allocItr2 = allocSites.iterator();
+ while( allocItr2.hasNext() ) {
+ AllocationSite as2 = (AllocationSite) allocItr2.next();
+
+ if( !outerChecked.contains(as2) ) {
+ common = createsPotentialAliases(td, as1, as2);
+
+ if( !common.isEmpty() ) {
+ foundSomeAlias = true;
+ if( !tabularOutput ) {
+ bw.write("Potential alias between "+as1.getFlatNew()+" and "+as2.getFlatNew()+".\n");
+ bw.write(prettyPrintNodeSet(common)+"\n");
+ } else {
+ ++numAlias;
+ }
+ }
+ }
+ }
+
+ outerChecked.add(as1);
}
if( !foundSomeAlias ) {
- if( !tabularOutput ) {
- bw.write("No aliases between flagged objects in Task "+td+".\n");
- }
+ if( !tabularOutput ) {
+ bw.write("No aliases between flagged objects in Task "+td+".\n");
+ }
}
}
Iterator allocItr2 = allocSites.iterator();
while( allocItr2.hasNext() ) {
- AllocationSite as2 = (AllocationSite) allocItr2.next();
+ AllocationSite as2 = (AllocationSite) allocItr2.next();
- if( !outerChecked.contains(as2) ) {
- Set<HeapRegionNode> common = createsPotentialAliases(d, as1, as2);
+ if( !outerChecked.contains(as2) ) {
+ Set<HeapRegionNode> common = createsPotentialAliases(d, as1, as2);
- if( !common.isEmpty() ) {
- foundSomeAlias = true;
- bw.write("Potential alias between "+as1.getDisjointId()+" and "+as2.getDisjointId()+".\n");
- bw.write(prettyPrintNodeSet(common)+"\n");
- }
- }
+ if( !common.isEmpty() ) {
+ foundSomeAlias = true;
+ bw.write("Potential alias between "+as1.getDisjointId()+" and "+as2.getDisjointId()+".\n");
+ bw.write(prettyPrintNodeSet(common)+"\n");
+ }
+ }
}
outerChecked.add(as1);
// from those tasks
Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
while( taskItr.hasNext() ) {
- Descriptor d = (Descriptor) taskItr.next();
- scheduleAllCallees(d);
+ Descriptor d = (Descriptor) taskItr.next();
+ scheduleAllCallees(d);
}
} else {
FlatMethod fm;
if( d instanceof MethodDescriptor ) {
- fm = state.getMethodFlat( (MethodDescriptor) d);
+ fm = state.getMethodFlat( (MethodDescriptor) d);
} else {
- assert d instanceof TaskDescriptor;
- fm = state.getMethodFlat( (TaskDescriptor) d);
+ assert d instanceof TaskDescriptor;
+ fm = state.getMethodFlat( (TaskDescriptor) d);
}
MethodContext mc = new MethodContext(d);
if( aliasFile != null ) {
if( state.TASK ) {
- writeAllAliases(aliasFile, treport, justtime, state.OWNERSHIPALIASTAB, state.lines);
+ writeAllAliases(aliasFile, treport, justtime, state.OWNERSHIPALIASTAB, state.lines);
} else {
- writeAllAliasesJava(aliasFile, treport, justtime, state.OWNERSHIPALIASTAB, state.lines);
+ writeAllAliasesJava(aliasFile, treport, justtime, state.OWNERSHIPALIASTAB, state.lines);
}
}
Iterator<MethodContext> itrmc = mcs.iterator();
while( itrmc.hasNext() ) {
- allContexts.add(itrmc.next() );
+ allContexts.add(itrmc.next() );
}
}
Descriptor d = mc.getDescriptor();
FlatMethod fm;
if( d instanceof MethodDescriptor ) {
- fm = state.getMethodFlat( (MethodDescriptor) d);
+ fm = state.getMethodFlat( (MethodDescriptor) d);
} else {
- assert d instanceof TaskDescriptor;
- fm = state.getMethodFlat( (TaskDescriptor) d);
+ assert d instanceof TaskDescriptor;
+ fm = state.getMethodFlat( (TaskDescriptor) d);
}
OwnershipGraph og = analyzeFlatMethod(mc, fm);
OwnershipGraph ogPrev = mapMethodContextToCompleteOwnershipGraph.get(mc);
if( !og.equals(ogPrev) ) {
- setGraphForMethodContext(mc, og);
-
- Iterator<MethodContext> depsItr = iteratorDependents(mc);
- while( depsItr.hasNext() ) {
- MethodContext mcNext = depsItr.next();
-
- if( !methodContextsToVisitSet.contains(mcNext) ) {
- methodContextsToVisitQ.add(new MethodContextQWrapper(mapDescriptorToPriority.get(mcNext.getDescriptor() ),
- mcNext) );
- methodContextsToVisitSet.add(mcNext);
- }
- }
+ setGraphForMethodContext(mc, og);
+
+ Iterator<MethodContext> depsItr = iteratorDependents(mc);
+ while( depsItr.hasNext() ) {
+ MethodContext mcNext = depsItr.next();
+
+ if( !methodContextsToVisitSet.contains(mcNext) ) {
+ methodContextsToVisitQ.add(new MethodContextQWrapper(mapDescriptorToPriority.get(mcNext.getDescriptor() ),
+ mcNext) );
+ methodContextsToVisitSet.add(mcNext);
+ }
+ }
}
}
// start by merging all node's parents' graphs
for( int i = 0; i < fn.numPrev(); ++i ) {
- FlatNode pn = fn.getPrev(i);
- if( mapFlatNodeToOwnershipGraph.containsKey(pn) ) {
- OwnershipGraph ogParent = mapFlatNodeToOwnershipGraph.get(pn);
- og.merge(ogParent);
- }
+ FlatNode pn = fn.getPrev(i);
+ if( mapFlatNodeToOwnershipGraph.containsKey(pn) ) {
+ OwnershipGraph ogParent = mapFlatNodeToOwnershipGraph.get(pn);
+ og.merge(ogParent);
+ }
}
// apply the analysis of the flat node to the
if( takeDebugSnapshots &&
mc.getDescriptor().getSymbol().equals(mcDescSymbolDebug) ) {
- debugSnapshot(og,fn);
+ debugSnapshot(og,fn);
}
// processing
OwnershipGraph ogPrev = mapFlatNodeToOwnershipGraph.get(fn);
if( !og.equals(ogPrev) ) {
- mapFlatNodeToOwnershipGraph.put(fn, og);
+ mapFlatNodeToOwnershipGraph.put(fn, og);
- for( int i = 0; i < fn.numNext(); i++ ) {
- FlatNode nn = fn.getNext(i);
- flatNodesToVisit.add(nn);
- }
+ for( int i = 0; i < fn.numNext(); i++ ) {
+ FlatNode nn = fn.getNext(i);
+ flatNodesToVisit.add(nn);
+ }
}
}
OwnershipGraph ogInitParamAlloc = mapMethodContextToInitialParamAllocGraph.get(mc);
if( ogInitParamAlloc == null ) {
- // if the method context has aliased parameters, make sure
- // there is a blob region for all those param to reference
- Set<Integer> aliasedParamIndices = mc.getAliasedParamIndices();
-
- if( !aliasedParamIndices.isEmpty() ) {
- og.makeAliasedParamHeapRegionNode(fm);
- }
-
- // set up each parameter
- for( int i = 0; i < fm.numParameters(); ++i ) {
- TempDescriptor tdParam = fm.getParameter(i);
- TypeDescriptor typeParam = tdParam.getType();
- Integer paramIndex = new Integer(i);
-
- if( typeParam.isImmutable() && !typeParam.isArray() ) {
- // don't bother with this primitive parameter, it
- // cannot affect reachability
- continue;
- }
-
- if( aliasedParamIndices.contains(paramIndex) ) {
- // use the alias blob but give parameters their
- // own primary obj region
- og.assignTempEqualToAliasedParam(tdParam,
- paramIndex, fm);
- } else {
- // this parameter is not aliased to others, give it
- // a fresh primary obj and secondary object
- og.assignTempEqualToParamAlloc(tdParam,
- mc.getDescriptor() instanceof TaskDescriptor,
- paramIndex, fm);
- }
- }
-
- // add additional edges for aliased regions if necessary
- if( !aliasedParamIndices.isEmpty() ) {
- og.addParam2ParamAliasEdges(fm, aliasedParamIndices);
- }
-
- // clean up reachability on initial parameter shapes
- og.globalSweep();
-
- // this maps tokens to parameter indices and vice versa
- // for when this method is a callee
- og.prepareParamTokenMaps(fm);
-
- // cache the graph
- OwnershipGraph ogResult = new OwnershipGraph();
- ogResult.merge(og);
- mapMethodContextToInitialParamAllocGraph.put(mc, ogResult);
+ // if the method context has aliased parameters, make sure
+ // there is a blob region for all those param to reference
+ Set<Integer> aliasedParamIndices = mc.getAliasedParamIndices();
+
+ if( !aliasedParamIndices.isEmpty() ) {
+ og.makeAliasedParamHeapRegionNode(fm);
+ }
+
+ // set up each parameter
+ for( int i = 0; i < fm.numParameters(); ++i ) {
+ TempDescriptor tdParam = fm.getParameter(i);
+ TypeDescriptor typeParam = tdParam.getType();
+ Integer paramIndex = new Integer(i);
+
+ if( typeParam.isImmutable() && !typeParam.isArray() ) {
+ // don't bother with this primitive parameter, it
+ // cannot affect reachability
+ continue;
+ }
+
+ if( aliasedParamIndices.contains(paramIndex) ) {
+ // use the alias blob but give parameters their
+ // own primary obj region
+ og.assignTempEqualToAliasedParam(tdParam,
+ paramIndex, fm);
+ } else {
+ // this parameter is not aliased to others, give it
+ // a fresh primary obj and secondary object
+ og.assignTempEqualToParamAlloc(tdParam,
+ mc.getDescriptor() instanceof TaskDescriptor,
+ paramIndex, fm);
+ }
+ }
+
+ // add additional edges for aliased regions if necessary
+ if( !aliasedParamIndices.isEmpty() ) {
+ og.addParam2ParamAliasEdges(fm, aliasedParamIndices);
+ }
+
+ // clean up reachability on initial parameter shapes
+ og.globalSweep();
+
+ // this maps tokens to parameter indices and vice versa
+ // for when this method is a callee
+ og.prepareParamTokenMaps(fm);
+
+ // cache the graph
+ OwnershipGraph ogResult = new OwnershipGraph();
+ ogResult.merge(og);
+ mapMethodContextToInitialParamAllocGraph.put(mc, ogResult);
} else {
- // or just leverage the cached copy
- og.merge(ogInitParamAlloc);
+ // or just leverage the cached copy
+ og.merge(ogInitParamAlloc);
}
break;
case FKind.FlatOpNode:
FlatOpNode fon = (FlatOpNode) fn;
if( fon.getOp().getOp() == Operation.ASSIGN ) {
- lhs = fon.getDest();
- rhs = fon.getLeft();
- og.assignTempXEqualToTempY(lhs, rhs);
+ lhs = fon.getDest();
+ rhs = fon.getLeft();
+ og.assignTempXEqualToTempY(lhs, rhs);
}
break;
rhs = ffn.getSrc();
fld = ffn.getField();
if( !fld.getType().isImmutable() || fld.getType().isArray() ) {
- og.assignTempXEqualToTempYFieldF(lhs, rhs, fld);
+ og.assignTempXEqualToTempYFieldF(lhs, rhs, fld);
}
meAnalysis.analyzeFlatFieldNode(mc, og, rhs, fld);
fld = fsfn.getField();
rhs = fsfn.getSrc();
if( !fld.getType().isImmutable() || fld.getType().isArray() ) {
- og.assignTempXFieldFEqualToTempY(lhs, fld, rhs);
+ og.assignTempXFieldFEqualToTempY(lhs, fld, rhs);
}
meAnalysis.analyzeFlatSetFieldNode(mc, og, lhs, fld);
rhs = fen.getSrc();
if( !lhs.getType().isImmutable() || lhs.getType().isArray() ) {
- assert rhs.getType() != null;
- assert rhs.getType().isArray();
+ assert rhs.getType() != null;
+ assert rhs.getType().isArray();
- TypeDescriptor tdElement = rhs.getType().dereference();
- FieldDescriptor fdElement = getArrayField(tdElement);
- og.assignTempXEqualToTempYFieldF(lhs, rhs, fdElement);
- meAnalysis.analyzeFlatElementNode(mc, og, lhs, fdElement);
+ TypeDescriptor tdElement = rhs.getType().dereference();
+ FieldDescriptor fdElement = getArrayField(tdElement);
+ og.assignTempXEqualToTempYFieldF(lhs, rhs, fdElement);
+ meAnalysis.analyzeFlatElementNode(mc, og, lhs, fdElement);
}
break;
lhs = fsen.getDst();
rhs = fsen.getSrc();
if( !lhs.getType().isImmutable() || lhs.getType().isArray() ) {
- TypeDescriptor tdElement = lhs.getType().dereference();
- FieldDescriptor fdElement = getArrayField(tdElement);
- meAnalysis.analyzeFlatSetElementNode(mc, og, lhs, fdElement);
+ TypeDescriptor tdElement = lhs.getType().dereference();
+ FieldDescriptor fdElement = getArrayField(tdElement);
+ meAnalysis.analyzeFlatSetElementNode(mc, og, lhs, fdElement);
}
if( arrayReferencees.doesNotCreateNewReaching(fsen) ) {
- // skip this node if it cannot create new reachability paths
- break;
+ // skip this node if it cannot create new reachability paths
+ break;
}
lhs = fsen.getDst();
rhs = fsen.getSrc();
if( !rhs.getType().isImmutable() || rhs.getType().isArray() ) {
- assert lhs.getType() != null;
- assert lhs.getType().isArray();
+ assert lhs.getType() != null;
+ assert lhs.getType().isArray();
- TypeDescriptor tdElement = lhs.getType().dereference();
- FieldDescriptor fdElement = getArrayField(tdElement);
+ TypeDescriptor tdElement = lhs.getType().dereference();
+ FieldDescriptor fdElement = getArrayField(tdElement);
- og.assignTempXFieldFEqualToTempY(lhs, fdElement, rhs);
- meAnalysis.analyzeFlatSetElementNode(mc, og, lhs, fdElement);
+ og.assignTempXFieldFEqualToTempY(lhs, fdElement, rhs);
+ meAnalysis.analyzeFlatSetElementNode(mc, og, lhs, fdElement);
}
break;
FlatNew fnn = (FlatNew) fn;
lhs = fnn.getDst();
if( !lhs.getType().isImmutable() || lhs.getType().isArray() ) {
- AllocationSite as = getAllocationSiteFromFlatNewPRIVATE(fnn);
-
- if (mapMethodContextToLiveInAllocationSiteSet != null) {
- HashSet<AllocationSite> alllocSet=mapMethodContextToLiveInAllocationSiteSet.get(mc);
- if(alllocSet!=null) {
- for (Iterator iterator = alllocSet.iterator(); iterator
- .hasNext(); ) {
- AllocationSite allocationSite = (AllocationSite) iterator
- .next();
- if(allocationSite.flatNew.equals(as.flatNew)) {
- as.setFlag(true);
- }
- }
- }
- }
-
- og.assignTempEqualToNewAlloc(lhs, as);
+ AllocationSite as = getAllocationSiteFromFlatNewPRIVATE(fnn);
+
+ if (mapMethodContextToLiveInAllocationSiteSet != null) {
+ HashSet<AllocationSite> alllocSet=mapMethodContextToLiveInAllocationSiteSet.get(mc);
+ if(alllocSet!=null) {
+ for (Iterator iterator = alllocSet.iterator(); iterator
+ .hasNext(); ) {
+ AllocationSite allocationSite = (AllocationSite) iterator
+ .next();
+ if(allocationSite.flatNew.equals(as.flatNew)) {
+ as.setFlag(true);
+ }
+ }
+ }
+ }
+
+ og.assignTempEqualToNewAlloc(lhs, as);
}
break;
OwnershipGraph ogMergeOfAllPossibleCalleeResults = new OwnershipGraph();
if( md.isStatic() ) {
- // a static method is simply always the same, makes life easy
- ogMergeOfAllPossibleCalleeResults = og;
+ // a static method is simply always the same, makes life easy
+ ogMergeOfAllPossibleCalleeResults = og;
- Set<Integer> aliasedParamIndices =
- ogMergeOfAllPossibleCalleeResults.calculateAliasedParamSet(fc, md.isStatic(), flatm);
+ Set<Integer> aliasedParamIndices =
+ ogMergeOfAllPossibleCalleeResults.calculateAliasedParamSet(fc, md.isStatic(), flatm);
- MethodContext mcNew = new MethodContext(md, aliasedParamIndices);
- Set contexts = mapDescriptorToAllMethodContexts.get(md);
- assert contexts != null;
- contexts.add(mcNew);
+ MethodContext mcNew = new MethodContext(md, aliasedParamIndices);
+ Set contexts = mapDescriptorToAllMethodContexts.get(md);
+ assert contexts != null;
+ contexts.add(mcNew);
- addDependent(mc, mcNew);
+ addDependent(mc, mcNew);
- OwnershipGraph onlyPossibleCallee = mapMethodContextToCompleteOwnershipGraph.get(mcNew);
+ OwnershipGraph onlyPossibleCallee = mapMethodContextToCompleteOwnershipGraph.get(mcNew);
- if( onlyPossibleCallee == null ) {
- // if this method context has never been analyzed just schedule it for analysis
- // and skip over this call site for now
- if( !methodContextsToVisitSet.contains(mcNew) ) {
- methodContextsToVisitQ.add(new MethodContextQWrapper(mapDescriptorToPriority.get(md),
- mcNew) );
- methodContextsToVisitSet.add(mcNew);
- }
+ if( onlyPossibleCallee == null ) {
+ // if this method context has never been analyzed just schedule it for analysis
+ // and skip over this call site for now
+ if( !methodContextsToVisitSet.contains(mcNew) ) {
+ methodContextsToVisitQ.add(new MethodContextQWrapper(mapDescriptorToPriority.get(md),
+ mcNew) );
+ methodContextsToVisitSet.add(mcNew);
+ }
- } else {
- ogMergeOfAllPossibleCalleeResults.resolveMethodCall(fc, md.isStatic(), flatm, onlyPossibleCallee, mc, null);
- }
+ } else {
+ ogMergeOfAllPossibleCalleeResults.resolveMethodCall(fc, md.isStatic(), flatm, onlyPossibleCallee, mc, null);
+ }
- meAnalysis.createNewMapping(mcNew);
- meAnalysis.analyzeFlatCall(ogMergeOfAllPossibleCalleeResults, mcNew, mc, fc);
+ meAnalysis.createNewMapping(mcNew);
+ meAnalysis.analyzeFlatCall(ogMergeOfAllPossibleCalleeResults, mcNew, mc, fc);
} else {
- // if the method descriptor is virtual, then there could be a
- // set of possible methods that will actually be invoked, so
- // find all of them and merge all of their results together
- TypeDescriptor typeDesc = fc.getThis().getType();
- Set possibleCallees = callGraph.getMethods(md, typeDesc);
+ // if the method descriptor is virtual, then there could be a
+ // set of possible methods that will actually be invoked, so
+ // find all of them and merge all of their results together
+ TypeDescriptor typeDesc = fc.getThis().getType();
+ Set possibleCallees = callGraph.getMethods(md, typeDesc);
- Iterator i = possibleCallees.iterator();
- while( i.hasNext() ) {
- MethodDescriptor possibleMd = (MethodDescriptor) i.next();
- FlatMethod pflatm = state.getMethodFlat(possibleMd);
+ Iterator i = possibleCallees.iterator();
+ while( i.hasNext() ) {
+ MethodDescriptor possibleMd = (MethodDescriptor) i.next();
+ FlatMethod pflatm = state.getMethodFlat(possibleMd);
- // don't alter the working graph (og) until we compute a result for every
- // possible callee, merge them all together, then set og to that
- OwnershipGraph ogCopy = new OwnershipGraph();
- ogCopy.merge(og);
+ // don't alter the working graph (og) until we compute a result for every
+ // possible callee, merge them all together, then set og to that
+ OwnershipGraph ogCopy = new OwnershipGraph();
+ ogCopy.merge(og);
- Set<Integer> aliasedParamIndices =
- ogCopy.calculateAliasedParamSet(fc, possibleMd.isStatic(), pflatm);
+ Set<Integer> aliasedParamIndices =
+ ogCopy.calculateAliasedParamSet(fc, possibleMd.isStatic(), pflatm);
- MethodContext mcNew = new MethodContext(possibleMd, aliasedParamIndices);
- Set contexts = mapDescriptorToAllMethodContexts.get(md);
- assert contexts != null;
- contexts.add(mcNew);
+ MethodContext mcNew = new MethodContext(possibleMd, aliasedParamIndices);
+ Set contexts = mapDescriptorToAllMethodContexts.get(md);
+ assert contexts != null;
+ contexts.add(mcNew);
- meAnalysis.createNewMapping(mcNew);
+ meAnalysis.createNewMapping(mcNew);
- addDependent(mc, mcNew);
+ addDependent(mc, mcNew);
- OwnershipGraph ogPotentialCallee = mapMethodContextToCompleteOwnershipGraph.get(mcNew);
+ OwnershipGraph ogPotentialCallee = mapMethodContextToCompleteOwnershipGraph.get(mcNew);
- if( ogPotentialCallee == null ) {
- // if this method context has never been analyzed just schedule it for analysis
- // and skip over this call site for now
- if( !methodContextsToVisitSet.contains(mcNew) ) {
- methodContextsToVisitQ.add(new MethodContextQWrapper(mapDescriptorToPriority.get(md),
- mcNew) );
- methodContextsToVisitSet.add(mcNew);
- }
+ if( ogPotentialCallee == null ) {
+ // if this method context has never been analyzed just schedule it for analysis
+ // and skip over this call site for now
+ if( !methodContextsToVisitSet.contains(mcNew) ) {
+ methodContextsToVisitQ.add(new MethodContextQWrapper(mapDescriptorToPriority.get(md),
+ mcNew) );
+ methodContextsToVisitSet.add(mcNew);
+ }
- } else {
- ogCopy.resolveMethodCall(fc, possibleMd.isStatic(), pflatm, ogPotentialCallee, mc, null);
- }
+ } else {
+ ogCopy.resolveMethodCall(fc, possibleMd.isStatic(), pflatm, ogPotentialCallee, mc, null);
+ }
- ogMergeOfAllPossibleCalleeResults.merge(ogCopy);
+ ogMergeOfAllPossibleCalleeResults.merge(ogCopy);
- meAnalysis.analyzeFlatCall(ogMergeOfAllPossibleCalleeResults, mcNew, mc, fc);
- }
+ meAnalysis.analyzeFlatCall(ogMergeOfAllPossibleCalleeResults, mcNew, mc, fc);
+ }
}
FlatReturnNode frn = (FlatReturnNode) fn;
rhs = frn.getReturnTemp();
if( rhs != null && !rhs.getType().isImmutable() ) {
- og.assignReturnEqualToTemp(rhs);
+ og.assignReturnEqualToTemp(rhs);
}
setRetNodes.add(frn);
break;
if( methodEffects ) {
Hashtable<FlatNode, OwnershipGraph> table=mapMethodContextToFlatNodeOwnershipGraph.get(mc);
if(table==null) {
- table=new Hashtable<FlatNode, OwnershipGraph>();
+ table=new Hashtable<FlatNode, OwnershipGraph>();
}
table.put(fn, og);
mapMethodContextToFlatNodeOwnershipGraph.put(mc, table);
if( writeDOTs && writeAllDOTs ) {
if( !mapMethodContextToNumUpdates.containsKey(mc) ) {
- mapMethodContextToNumUpdates.put(mc, new Integer(0) );
+ mapMethodContextToNumUpdates.put(mc, new Integer(0) );
}
Integer n = mapMethodContextToNumUpdates.get(mc);
try {
- og.writeGraph(mc+"COMPLETE"+String.format("%05d", n),
- true, // write labels (variables)
- true, // selectively hide intermediate temp vars
- true, // prune unreachable heap regions
- false, // show back edges to confirm graph validity
- false, // show parameter indices (unmaintained!)
- true, // hide subset reachability states
- true); // hide edge taints
+ og.writeGraph(mc+"COMPLETE"+String.format("%05d", n),
+ true, // write labels (variables)
+ true, // selectively hide intermediate temp vars
+ true, // prune unreachable heap regions
+ false, // show back edges to confirm graph validity
+ false, // show parameter indices (unmaintained!)
+ true, // hide subset reachability states
+ true); // hide edge taints
} catch( IOException e ) {
}
mapMethodContextToNumUpdates.put(mc, n + 1);
OwnershipGraph og = (OwnershipGraph) me.getValue();
try {
- og.writeGraph(mc+"COMPLETE",
- true, // write labels (variables)
- true, // selectively hide intermediate temp vars
- true, // prune unreachable heap regions
- false, // show back edges to confirm graph validity
- false, // show parameter indices (unmaintained!)
- true, // hide subset reachability states
- true); // hide edge taints
+ og.writeGraph(mc+"COMPLETE",
+ true, // write labels (variables)
+ true, // selectively hide intermediate temp vars
+ true, // prune unreachable heap regions
+ false, // show back edges to confirm graph validity
+ false, // show parameter indices (unmaintained!)
+ true, // hide subset reachability states
+ true); // hide edge taints
} catch( IOException e ) {
}
}
// the newest nodes are single objects
for( int i = 0; i < allocationDepth; ++i ) {
- Integer id = generateUniqueHeapRegionNodeID();
- as.setIthOldest(i, id);
- mapHrnIdToAllocationSite.put(id, as);
+ Integer id = generateUniqueHeapRegionNodeID();
+ as.setIthOldest(i, id);
+ mapHrnIdToAllocationSite.put(id, as);
}
// the oldest node is a summary node
FlatNode n = toVisit.iterator().next();
if( n instanceof FlatNew ) {
- s.add(getAllocationSiteFromFlatNewPRIVATE( (FlatNew) n) );
+ s.add(getAllocationSiteFromFlatNewPRIVATE( (FlatNew) n) );
}
toVisit.remove(n);
visited.add(n);
for( int i = 0; i < n.numNext(); ++i ) {
- FlatNode child = n.getNext(i);
- if( !visited.contains(child) ) {
- toVisit.add(child);
- }
+ FlatNode child = n.getNext(i);
+ if( !visited.contains(child) ) {
+ toVisit.add(child);
+ }
}
}
HashSet<AllocationSite> asSet = getAllocationSiteSet(d);
Iterator asItr = asSet.iterator();
while( asItr.hasNext() ) {
- AllocationSite as = (AllocationSite) asItr.next();
- if( as.getDisjointId() != null ) {
- out.add(as);
- }
+ AllocationSite as = (AllocationSite) asItr.next();
+ if( as.getDisjointId() != null ) {
+ out.add(as);
+ }
}
// enqueue callees of this method to be searched for
// allocation sites also
Set callees = callGraph.getCalleeSet(d);
if( callees != null ) {
- Iterator methItr = callees.iterator();
- while( methItr.hasNext() ) {
- MethodDescriptor md = (MethodDescriptor) methItr.next();
-
- if( !visited.contains(md) ) {
- toVisit.add(md);
- }
- }
+ Iterator methItr = callees.iterator();
+ while( methItr.hasNext() ) {
+ MethodDescriptor md = (MethodDescriptor) methItr.next();
+
+ if( !visited.contains(md) ) {
+ toVisit.add(md);
+ }
+ }
}
}
HashSet<AllocationSite> asSet = getAllocationSiteSet(d);
Iterator asItr = asSet.iterator();
while( asItr.hasNext() ) {
- AllocationSite as = (AllocationSite) asItr.next();
- TypeDescriptor typed = as.getType();
- if( typed != null ) {
- ClassDescriptor cd = typed.getClassDesc();
- if( cd != null && cd.hasFlags() ) {
- asSetTotal.add(as);
- }
- }
+ AllocationSite as = (AllocationSite) asItr.next();
+ TypeDescriptor typed = as.getType();
+ if( typed != null ) {
+ ClassDescriptor cd = typed.getClassDesc();
+ if( cd != null && cd.hasFlags() ) {
+ asSetTotal.add(as);
+ }
+ }
}
// enqueue callees of this method to be searched for
// allocation sites also
Set callees = callGraph.getCalleeSet(d);
if( callees != null ) {
- Iterator methItr = callees.iterator();
- while( methItr.hasNext() ) {
- MethodDescriptor md = (MethodDescriptor) methItr.next();
-
- if( !visited.contains(md) ) {
- toVisit.add(md);
- }
- }
+ Iterator methItr = callees.iterator();
+ while( methItr.hasNext() ) {
+ MethodDescriptor md = (MethodDescriptor) methItr.next();
+
+ if( !visited.contains(md) ) {
+ toVisit.add(md);
+ }
+ }
}
}
MethodContext mc = itr.next();
if( !discovered.contains(mc) ) {
- dfsVisit(set, mc, sorted, discovered);
+ dfsVisit(set, mc, sorted, discovered);
}
}
MethodDescriptor md = (MethodDescriptor) d;
Iterator itr = callGraph.getCallerSet(md).iterator();
while( itr.hasNext() ) {
- Descriptor dCaller = (Descriptor) itr.next();
-
- // only consider the callers in the original set to analyze
- Set<MethodContext> callerContexts = mapDescriptorToAllMethodContexts.get(dCaller);
- if( callerContexts == null )
- continue;
-
- // since the analysis hasn't started, there should be exactly one
- // context if there are any at all
- assert callerContexts.size() == 1;
- MethodContext mcCaller = callerContexts.iterator().next();
- assert set.contains(mcCaller);
-
- if( !discovered.contains(mcCaller) ) {
- dfsVisit(set, mcCaller, sorted, discovered);
- }
+ Descriptor dCaller = (Descriptor) itr.next();
+
+ // only consider the callers in the original set to analyze
+ Set<MethodContext> callerContexts = mapDescriptorToAllMethodContexts.get(dCaller);
+ if( callerContexts == null )
+ continue;
+
+ // since the analysis hasn't started, there should be exactly one
+ // context if there are any at all
+ assert callerContexts.size() == 1;
+ MethodContext mcCaller = callerContexts.iterator().next();
+ assert set.contains(mcCaller);
+
+ if( !discovered.contains(mcCaller) ) {
+ dfsVisit(set, mcCaller, sorted, discovered);
+ }
}
}
Integer i = mapNumContexts2NumDesc.get(s.size() );
if( i == null ) {
- i = new Integer(0);
+ i = new Integer(0);
}
mapNumContexts2NumDesc.put(s.size(), i + 1);
}
System.out.println(" @@@ capturing debug "+(debugCounter-iterStartCapture)+" @@@");
String graphName = String.format("snap%04d",debugCounter-iterStartCapture);
if( fn != null ) {
- graphName = graphName+fn;
+ graphName = graphName+fn;
}
try {
- og.writeGraph(graphName,
- true, // write labels (variables)
- true, // selectively hide intermediate temp vars
- true, // prune unreachable heap regions
- false, // show back edges to confirm graph validity
- false, // show parameter indices (unmaintained!)
- true, // hide subset reachability states
- true); // hide edge taints
+ og.writeGraph(graphName,
+ true, // write labels (variables)
+ true, // selectively hide intermediate temp vars
+ true, // prune unreachable heap regions
+ false, // show back edges to confirm graph validity
+ false, // show parameter indices (unmaintained!)
+ true, // hide subset reachability states
+ true); // hide edge taints
} catch( Exception e ) {
- System.out.println("Error writing debug capture.");
- System.exit(0);
+ System.out.println("Error writing debug capture.");
+ System.exit(0);
}
}
for(int i=0; i<fc.numPrev(); i++) {
FlatNode prevNode=fc.getPrev(i);
if(prevNode!=null) {
- OwnershipGraph prevOG=table.get(prevNode);
- mergeOG.merge(prevOG);
+ OwnershipGraph prevOG=table.get(prevNode);
+ mergeOG.merge(prevOG);
}
}
if( alpha == null ) {
if( markForAnalysis ) {
- alpha = new ReachabilitySet(
- new TokenTuple(id,
- !isSingleObject,
- TokenTuple.ARITY_ONE
- ).makeCanonical()
- ).makeCanonical();
+ alpha = new ReachabilitySet(
+ new TokenTuple(id,
+ !isSingleObject,
+ TokenTuple.ARITY_ONE
+ ).makeCanonical()
+ ).makeCanonical();
} else {
- alpha = new ReachabilitySet(
- new TokenTupleSet().makeCanonical()
- ).makeCanonical();
+ alpha = new ReachabilitySet(
+ new TokenTupleSet().makeCanonical()
+ ).makeCanonical();
}
}
(edge.typeEquals(type) && edge.fieldEquals(field))
) {
- HeapRegionNode referencee = edge.getDst();
+ HeapRegionNode referencee = edge.getDst();
- removeReferenceEdge(referencer,
- referencee,
- edge.getType(),
- edge.getField() );
+ removeReferenceEdge(referencer,
+ referencee,
+ edge.getType(),
+ edge.getField() );
}
}
}
(edge.typeEquals(type) && edge.fieldEquals(field))
) {
- OwnershipNode referencer = edge.getSrc();
+ OwnershipNode referencer = edge.getSrc();
- removeReferenceEdge(referencer,
- referencee,
- edge.getType(),
- edge.getField() );
+ removeReferenceEdge(referencer,
+ referencee,
+ edge.getType(),
+ edge.getField() );
}
}
}
if( !outOfScope.contains(td) &&
!liveIn.contains(td)
) {
- clearReferenceEdgesFrom(ln, null, null, true);
+ clearReferenceEdgesFrom(ln, null, null, true);
}
}
}
ReferenceEdge edgeNew = edgeY.copy();
if( !isSuperiorType(x.getType(), edgeY.getType() ) ) {
- impossibleEdges.add(edgeY);
- continue;
+ impossibleEdges.add(edgeY);
+ continue;
}
edgeNew.setSrc(lnX);
Iterator<ReferenceEdge> itrHrnFhrn = hrnY.iteratorToReferencees();
while( itrHrnFhrn.hasNext() ) {
- ReferenceEdge edgeHrn = itrHrnFhrn.next();
- HeapRegionNode hrnHrn = edgeHrn.getDst();
- ReachabilitySet betaHrn = edgeHrn.getBeta();
-
- // prune edges that are not a matching field
- if( edgeHrn.getType() != null &&
- !edgeHrn.getField().equals(f.getSymbol() )
- ) {
- continue;
- }
-
- // check for impossible edges
- if( !isSuperiorType(x.getType(), edgeHrn.getType() ) ) {
- impossibleEdges.add(edgeHrn);
- continue;
- }
-
- TypeDescriptor tdNewEdge =
- mostSpecificType(edgeHrn.getType(),
- hrnHrn.getType()
- );
-
- ReferenceEdge edgeNew = new ReferenceEdge(lnX,
- hrnHrn,
- tdNewEdge,
- null,
- false,
- betaY.intersection(betaHrn)
- );
-
- int newTaintIdentifier=getTaintIdentifierFromHRN(hrnHrn);
- edgeNew.setTaintIdentifier(newTaintIdentifier);
-
- addReferenceEdge(lnX, hrnHrn, edgeNew);
+ ReferenceEdge edgeHrn = itrHrnFhrn.next();
+ HeapRegionNode hrnHrn = edgeHrn.getDst();
+ ReachabilitySet betaHrn = edgeHrn.getBeta();
+
+ // prune edges that are not a matching field
+ if( edgeHrn.getType() != null &&
+ !edgeHrn.getField().equals(f.getSymbol() )
+ ) {
+ continue;
+ }
+
+ // check for impossible edges
+ if( !isSuperiorType(x.getType(), edgeHrn.getType() ) ) {
+ impossibleEdges.add(edgeHrn);
+ continue;
+ }
+
+ TypeDescriptor tdNewEdge =
+ mostSpecificType(edgeHrn.getType(),
+ hrnHrn.getType()
+ );
+
+ ReferenceEdge edgeNew = new ReferenceEdge(lnX,
+ hrnHrn,
+ tdNewEdge,
+ null,
+ false,
+ betaY.intersection(betaHrn)
+ );
+
+ int newTaintIdentifier=getTaintIdentifierFromHRN(hrnHrn);
+ edgeNew.setTaintIdentifier(newTaintIdentifier);
+
+ addReferenceEdge(lnX, hrnHrn, edgeNew);
}
}
// you must global sweep to clean up broken reachability
if( !impossibleEdges.isEmpty() ) {
if( !DISABLE_GLOBAL_SWEEP ) {
- globalSweep();
+ globalSweep();
}
}
}
(hrnX.isSingleObject() && lnX.getNumReferencees() == 1) // case 2
)
) {
- if( !DISABLE_STRONG_UPDATES ) {
- strongUpdate = true;
- clearReferenceEdgesFrom(hrnX, f.getType(), f.getSymbol(), false);
- }
+ if( !DISABLE_STRONG_UPDATES ) {
+ strongUpdate = true;
+ clearReferenceEdgesFrom(hrnX, f.getType(), f.getSymbol(), false);
+ }
}
}
Iterator<ReferenceEdge> itrYhrn = lnY.iteratorToReferencees();
while( itrYhrn.hasNext() ) {
- ReferenceEdge edgeY = itrYhrn.next();
- HeapRegionNode hrnY = edgeY.getDst();
- ReachabilitySet O = edgeY.getBeta();
-
- // check for impossible edges
- if( !isSuperiorType(f.getType(), edgeY.getType() ) ) {
- impossibleEdges.add(edgeY);
- continue;
- }
-
- // propagate tokens over nodes starting from hrnSrc, and it will
- // take care of propagating back up edges from any touched nodes
- ChangeTupleSet Cy = O.unionUpArityToChangeSet(R);
- propagateTokensOverNodes(hrnY, Cy, nodesWithNewAlpha, edgesWithNewBeta);
-
-
- // then propagate back just up the edges from hrn
- ChangeTupleSet Cx = R.unionUpArityToChangeSet(O);
- HashSet<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,
- edgesWithNewBeta);
+ ReferenceEdge edgeY = itrYhrn.next();
+ HeapRegionNode hrnY = edgeY.getDst();
+ ReachabilitySet O = edgeY.getBeta();
+
+ // check for impossible edges
+ if( !isSuperiorType(f.getType(), edgeY.getType() ) ) {
+ impossibleEdges.add(edgeY);
+ continue;
+ }
+
+ // propagate tokens over nodes starting from hrnSrc, and it will
+ // take care of propagating back up edges from any touched nodes
+ ChangeTupleSet Cy = O.unionUpArityToChangeSet(R);
+ propagateTokensOverNodes(hrnY, Cy, nodesWithNewAlpha, edgesWithNewBeta);
+
+
+ // then propagate back just up the edges from hrn
+ ChangeTupleSet Cx = R.unionUpArityToChangeSet(O);
+ HashSet<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,
+ edgesWithNewBeta);
}
}
Iterator<ReferenceEdge> itrYhrn = lnY.iteratorToReferencees();
while( itrYhrn.hasNext() ) {
- ReferenceEdge edgeY = itrYhrn.next();
- HeapRegionNode hrnY = edgeY.getDst();
-
- // skip impossible edges here, we already marked them
- // when computing reachability propagations above
- if( !isSuperiorType(f.getType(), edgeY.getType() ) ) {
- continue;
- }
-
- // prepare the new reference edge hrnX.f -> hrnY
- TypeDescriptor tdNewEdge =
- mostSpecificType(y.getType(),
- edgeY.getType(),
- hrnY.getType()
- );
-
- ReferenceEdge edgeNew = new ReferenceEdge(hrnX,
- hrnY,
- tdNewEdge,
- f.getSymbol(),
- false,
- edgeY.getBeta().pruneBy(hrnX.getAlpha() )
- );
-
- // look to see if an edge with same field exists
- // and merge with it, otherwise just add the edge
- ReferenceEdge edgeExisting = hrnX.getReferenceTo(hrnY,
- tdNewEdge,
- f.getSymbol() );
-
- if( edgeExisting != null ) {
- edgeExisting.setBeta(
- edgeExisting.getBeta().union(edgeNew.getBeta() )
- );
-
- if((!hrnX.isParameter() && hrnY.isParameter()) || ( hrnX.isParameter() && hrnY.isParameter())) {
- int newTaintIdentifier=getTaintIdentifierFromHRN(hrnY);
- edgeExisting.unionTaintIdentifier(newTaintIdentifier);
- }
- // a new edge here cannot be reflexive, so existing will
- // always be also not reflexive anymore
- edgeExisting.setIsInitialParam(false);
- } else {
-
- if((!hrnX.isParameter() && hrnY.isParameter()) || ( hrnX.isParameter() && hrnY.isParameter())) {
- int newTaintIdentifier=getTaintIdentifierFromHRN(hrnY);
- edgeNew.setTaintIdentifier(newTaintIdentifier);
- }
- //currently, taint isn't propagated through the chain of refrences
- //propagateTaintIdentifier(hrnX,newTaintIdentifier,new HashSet<HeapRegionNode>());
-
- addReferenceEdge(hrnX, hrnY, edgeNew);
- }
+ ReferenceEdge edgeY = itrYhrn.next();
+ HeapRegionNode hrnY = edgeY.getDst();
+
+ // skip impossible edges here, we already marked them
+ // when computing reachability propagations above
+ if( !isSuperiorType(f.getType(), edgeY.getType() ) ) {
+ continue;
+ }
+
+ // prepare the new reference edge hrnX.f -> hrnY
+ TypeDescriptor tdNewEdge =
+ mostSpecificType(y.getType(),
+ edgeY.getType(),
+ hrnY.getType()
+ );
+
+ ReferenceEdge edgeNew = new ReferenceEdge(hrnX,
+ hrnY,
+ tdNewEdge,
+ f.getSymbol(),
+ false,
+ edgeY.getBeta().pruneBy(hrnX.getAlpha() )
+ );
+
+ // look to see if an edge with same field exists
+ // and merge with it, otherwise just add the edge
+ ReferenceEdge edgeExisting = hrnX.getReferenceTo(hrnY,
+ tdNewEdge,
+ f.getSymbol() );
+
+ if( edgeExisting != null ) {
+ edgeExisting.setBeta(
+ edgeExisting.getBeta().union(edgeNew.getBeta() )
+ );
+
+ if((!hrnX.isParameter() && hrnY.isParameter()) || ( hrnX.isParameter() && hrnY.isParameter())) {
+ int newTaintIdentifier=getTaintIdentifierFromHRN(hrnY);
+ edgeExisting.unionTaintIdentifier(newTaintIdentifier);
+ }
+ // a new edge here cannot be reflexive, so existing will
+ // always be also not reflexive anymore
+ edgeExisting.setIsInitialParam(false);
+ } else {
+
+ if((!hrnX.isParameter() && hrnY.isParameter()) || ( hrnX.isParameter() && hrnY.isParameter())) {
+ int newTaintIdentifier=getTaintIdentifierFromHRN(hrnY);
+ edgeNew.setTaintIdentifier(newTaintIdentifier);
+ }
+ //currently, taint isn't propagated through the chain of refrences
+ //propagateTaintIdentifier(hrnX,newTaintIdentifier,new HashSet<HeapRegionNode>());
+
+ addReferenceEdge(hrnX, hrnY, edgeNew);
+ }
}
}
// reachability with a global sweep
if( strongUpdate || !impossibleEdges.isEmpty() ) {
if( !DISABLE_GLOBAL_SWEEP ) {
- globalSweep();
+ globalSweep();
}
}
}
// affect reachability
TypeDescriptor typeDeref = typeParam.dereference();
if( !typeDeref.isImmutable() || typeDeref.isArray() ) {
- primary2secondaryFields.add(
- OwnershipAnalysis.getArrayField(typeDeref)
- );
- createSecondaryRegion = true;
-
- // also handle a special case where an array of objects
- // can point back to the array, which is an object!
- if( typeParam.toPrettyString().equals("Object[]") &&
- typeDeref.toPrettyString().equals("Object") ) {
-
- primary2primaryFields.add(
- OwnershipAnalysis.getArrayField(typeDeref)
- );
- }
+ primary2secondaryFields.add(
+ OwnershipAnalysis.getArrayField(typeDeref)
+ );
+ createSecondaryRegion = true;
+
+ // also handle a special case where an array of objects
+ // can point back to the array, which is an object!
+ if( typeParam.toPrettyString().equals("Object[]") &&
+ typeDeref.toPrettyString().equals("Object") ) {
+
+ primary2primaryFields.add(
+ OwnershipAnalysis.getArrayField(typeDeref)
+ );
+ }
}
}
ClassDescriptor cd = typeParam.getClassDesc();
while( cd != null ) {
- Iterator fieldItr = cd.getFields();
- while( fieldItr.hasNext() ) {
+ Iterator fieldItr = cd.getFields();
+ while( fieldItr.hasNext() ) {
- FieldDescriptor fd = (FieldDescriptor) fieldItr.next();
- TypeDescriptor typeField = fd.getType();
- assert typeField != null;
+ FieldDescriptor fd = (FieldDescriptor) fieldItr.next();
+ TypeDescriptor typeField = fd.getType();
+ assert typeField != null;
- if( !typeField.isImmutable() || typeField.isArray() ) {
- primary2secondaryFields.add(fd);
- createSecondaryRegion = true;
- }
+ if( !typeField.isImmutable() || typeField.isArray() ) {
+ primary2secondaryFields.add(fd);
+ createSecondaryRegion = true;
+ }
- if( typeUtil.isSuperorType(typeField, typeParam) ) {
- primary2primaryFields.add(fd);
- }
- }
+ if( typeUtil.isSuperorType(typeField, typeParam) ) {
+ primary2primaryFields.add(fd);
+ }
+ }
- cd = cd.getSuperDesc();
+ cd = cd.getSuperDesc();
}
}
// there might be an element reference for array types
if( typeI.isArray() ) {
- // only bother with this if the dereferenced type can
- // affect reachability
- TypeDescriptor typeDeref = typeI.dereference();
+ // only bother with this if the dereferenced type can
+ // affect reachability
+ TypeDescriptor typeDeref = typeI.dereference();
- /////////////////////////////////////////////////////////////
- // NOTE! For the KMeans benchmark a parameter of type float
- // array, which has an immutable dereferenced type, is causing
- // this assertion to fail. I'm commenting it out for now which
- // is safe, because it allows aliasing where no aliasing can occur,
- // so it can only get a worse-but-not-wrong answer. FIX!
- /////////////////////////////////////////////////////////////
- // for this parameter to be aliased the following must be true
- //assert !typeDeref.isImmutable() || typeDeref.isArray();
+ /////////////////////////////////////////////////////////////
+ // NOTE! For the KMeans benchmark a parameter of type float
+ // array, which has an immutable dereferenced type, is causing
+ // this assertion to fail. I'm commenting it out for now which
+ // is safe, because it allows aliasing where no aliasing can occur,
+ // so it can only get a worse-but-not-wrong answer. FIX!
+ /////////////////////////////////////////////////////////////
+ // for this parameter to be aliased the following must be true
+ //assert !typeDeref.isImmutable() || typeDeref.isArray();
- primary2secondaryFields.add(
- OwnershipAnalysis.getArrayField(typeDeref)
- );
+ primary2secondaryFields.add(
+ OwnershipAnalysis.getArrayField(typeDeref)
+ );
- // also handle a special case where an array of objects
- // can point back to the array, which is an object!
- if( typeI.toPrettyString().equals("Object[]") &&
- typeDeref.toPrettyString().equals("Object") ) {
- primary2primaryFields.add(
- OwnershipAnalysis.getArrayField(typeDeref)
- );
- }
+ // also handle a special case where an array of objects
+ // can point back to the array, which is an object!
+ if( typeI.toPrettyString().equals("Object[]") &&
+ typeDeref.toPrettyString().equals("Object") ) {
+ primary2primaryFields.add(
+ OwnershipAnalysis.getArrayField(typeDeref)
+ );
+ }
}
// there might be member references for class types
if( typeI.isClass() ) {
- ClassDescriptor cd = typeI.getClassDesc();
- while( cd != null ) {
+ ClassDescriptor cd = typeI.getClassDesc();
+ while( cd != null ) {
- Iterator fieldItr = cd.getFields();
- while( fieldItr.hasNext() ) {
+ Iterator fieldItr = cd.getFields();
+ while( fieldItr.hasNext() ) {
- FieldDescriptor fd = (FieldDescriptor) fieldItr.next();
- TypeDescriptor typeField = fd.getType();
- assert typeField != null;
+ FieldDescriptor fd = (FieldDescriptor) fieldItr.next();
+ TypeDescriptor typeField = fd.getType();
+ assert typeField != null;
- if( !typeField.isImmutable() || typeField.isArray() ) {
- primary2secondaryFields.add(fd);
- }
+ if( !typeField.isImmutable() || typeField.isArray() ) {
+ primary2secondaryFields.add(fd);
+ }
- if( typeUtil.isSuperorType(typeField, typeI) ) {
- primary2primaryFields.add(fd);
- }
- }
+ if( typeUtil.isSuperorType(typeField, typeI) ) {
+ primary2primaryFields.add(fd);
+ }
+ }
- cd = cd.getSuperDesc();
- }
+ cd = cd.getSuperDesc();
+ }
}
Iterator<FieldDescriptor> fieldItr = primary2primaryFields.iterator();
while( fieldItr.hasNext() ) {
- FieldDescriptor fd = fieldItr.next();
-
- ReferenceEdge edgePrimaryReflexive =
- new ReferenceEdge(primaryI, // src
- primaryI, // dst
- fd.getType(), // type
- fd.getSymbol(), // field
- true, // special param initial
- betaSoup); // reachability
- addReferenceEdge(primaryI, primaryI, edgePrimaryReflexive);
+ FieldDescriptor fd = fieldItr.next();
+
+ ReferenceEdge edgePrimaryReflexive =
+ new ReferenceEdge(primaryI, // src
+ primaryI, // dst
+ fd.getType(), // type
+ fd.getSymbol(), // field
+ true, // special param initial
+ betaSoup); // reachability
+ addReferenceEdge(primaryI, primaryI, edgePrimaryReflexive);
}
fieldItr = primary2secondaryFields.iterator();
while( fieldItr.hasNext() ) {
- FieldDescriptor fd = fieldItr.next();
- TypeDescriptor typeField = fd.getType();
- assert typeField != null;
-
- ReferenceEdge edgePrimary2Secondary =
- new ReferenceEdge(primaryI, // src
- hrnAliasBlob, // dst
- fd.getType(), // type
- fd.getSymbol(), // field
- true, // special param initial
- betaSoup); // reachability
- addReferenceEdge(primaryI, hrnAliasBlob, edgePrimary2Secondary);
-
- // ask whether these fields might match any of the other aliased
- // parameters and make those edges too
- Iterator<Integer> apItrJ = aliasedParamIndices.iterator();
- while( apItrJ.hasNext() ) {
- Integer j = apItrJ.next();
- TempDescriptor tdParamJ = fm.getParameter(j);
- TypeDescriptor typeJ = tdParamJ.getType();
-
- if( !i.equals(j) && typeUtil.isSuperorType(typeField, typeJ) ) {
-
- Integer idPrimaryJ = paramIndex2idPrimary.get(j);
- assert idPrimaryJ != null;
- HeapRegionNode primaryJ = id2hrn.get(idPrimaryJ);
- assert primaryJ != null;
-
- TokenTuple ttPrimaryJ = new TokenTuple(idPrimaryJ,
- false, // multi-object
- TokenTuple.ARITY_ONE).makeCanonical();
-
- TokenTupleSet ttsJ = new TokenTupleSet(ttPrimaryJ).makeCanonical();
- TokenTupleSet ttsIJ = ttsI.union(ttsJ);
- TokenTupleSet ttsAJ = ttsA.union(ttsJ);
- TokenTupleSet ttsIAJ = ttsIA.union(ttsJ);
- ReachabilitySet betaSoupWJ = ReachabilitySet.factory(ttsJ).union(ttsIJ).union(ttsAJ).union(ttsIAJ);
-
- ReferenceEdge edgePrimaryI2PrimaryJ =
- new ReferenceEdge(primaryI, // src
- primaryJ, // dst
- fd.getType(), // type
- fd.getSymbol(), // field
- true, // special param initial
- betaSoupWJ); // reachability
- addReferenceEdge(primaryI, primaryJ, edgePrimaryI2PrimaryJ);
- }
- }
+ FieldDescriptor fd = fieldItr.next();
+ TypeDescriptor typeField = fd.getType();
+ assert typeField != null;
+
+ ReferenceEdge edgePrimary2Secondary =
+ new ReferenceEdge(primaryI, // src
+ hrnAliasBlob, // dst
+ fd.getType(), // type
+ fd.getSymbol(), // field
+ true, // special param initial
+ betaSoup); // reachability
+ addReferenceEdge(primaryI, hrnAliasBlob, edgePrimary2Secondary);
+
+ // ask whether these fields might match any of the other aliased
+ // parameters and make those edges too
+ Iterator<Integer> apItrJ = aliasedParamIndices.iterator();
+ while( apItrJ.hasNext() ) {
+ Integer j = apItrJ.next();
+ TempDescriptor tdParamJ = fm.getParameter(j);
+ TypeDescriptor typeJ = tdParamJ.getType();
+
+ if( !i.equals(j) && typeUtil.isSuperorType(typeField, typeJ) ) {
+
+ Integer idPrimaryJ = paramIndex2idPrimary.get(j);
+ assert idPrimaryJ != null;
+ HeapRegionNode primaryJ = id2hrn.get(idPrimaryJ);
+ assert primaryJ != null;
+
+ TokenTuple ttPrimaryJ = new TokenTuple(idPrimaryJ,
+ false, // multi-object
+ TokenTuple.ARITY_ONE).makeCanonical();
+
+ TokenTupleSet ttsJ = new TokenTupleSet(ttPrimaryJ).makeCanonical();
+ TokenTupleSet ttsIJ = ttsI.union(ttsJ);
+ TokenTupleSet ttsAJ = ttsA.union(ttsJ);
+ TokenTupleSet ttsIAJ = ttsIA.union(ttsJ);
+ ReachabilitySet betaSoupWJ = ReachabilitySet.factory(ttsJ).union(ttsIJ).union(ttsAJ).union(ttsIAJ);
+
+ ReferenceEdge edgePrimaryI2PrimaryJ =
+ new ReferenceEdge(primaryI, // src
+ primaryJ, // dst
+ fd.getType(), // type
+ fd.getSymbol(), // field
+ true, // special param initial
+ betaSoupWJ); // reachability
+ addReferenceEdge(primaryI, primaryJ, edgePrimaryI2PrimaryJ);
+ }
+ }
}
// possibly be the same primary object, add edges
Iterator<Integer> apItrJ = aliasedParamIndices.iterator();
while( apItrJ.hasNext() ) {
- Integer j = apItrJ.next();
- TempDescriptor tdParamJ = fm.getParameter(j);
- TypeDescriptor typeJ = tdParamJ.getType();
- LabelNode lnParamJ = getLabelNodeFromTemp(tdParamJ);
-
- if( !i.equals(j) && typeUtil.isSuperorType(typeI, typeJ) ) {
-
- Integer idPrimaryJ = paramIndex2idPrimary.get(j);
- assert idPrimaryJ != null;
- HeapRegionNode primaryJ = id2hrn.get(idPrimaryJ);
- assert primaryJ != null;
-
- ReferenceEdge lnJ2PrimaryJ = lnParamJ.getReferenceTo(primaryJ,
- tdParamJ.getType(),
- null);
- assert lnJ2PrimaryJ != null;
-
- ReferenceEdge lnI2PrimaryJ = lnJ2PrimaryJ.copy();
- lnI2PrimaryJ.setSrc(lnParamI);
- lnI2PrimaryJ.setType(tdParamI.getType() );
- lnI2PrimaryJ.tainedBy(new Integer(j));
- addReferenceEdge(lnParamI, primaryJ, lnI2PrimaryJ);
- }
+ Integer j = apItrJ.next();
+ TempDescriptor tdParamJ = fm.getParameter(j);
+ TypeDescriptor typeJ = tdParamJ.getType();
+ LabelNode lnParamJ = getLabelNodeFromTemp(tdParamJ);
+
+ if( !i.equals(j) && typeUtil.isSuperorType(typeI, typeJ) ) {
+
+ Integer idPrimaryJ = paramIndex2idPrimary.get(j);
+ assert idPrimaryJ != null;
+ HeapRegionNode primaryJ = id2hrn.get(idPrimaryJ);
+ assert primaryJ != null;
+
+ ReferenceEdge lnJ2PrimaryJ = lnParamJ.getReferenceTo(primaryJ,
+ tdParamJ.getType(),
+ null);
+ assert lnJ2PrimaryJ != null;
+
+ ReferenceEdge lnI2PrimaryJ = lnJ2PrimaryJ.copy();
+ lnI2PrimaryJ.setSrc(lnParamI);
+ lnI2PrimaryJ.setType(tdParamI.getType() );
+ lnI2PrimaryJ.tainedBy(new Integer(j));
+ addReferenceEdge(lnParamI, primaryJ, lnI2PrimaryJ);
+ }
}
}
}
// immutable objects have no primary regions
if( paramIndex2idPrimary.containsKey(paramIndex) ) {
- Integer idPrimary = paramIndex2idPrimary.get(paramIndex);
+ Integer idPrimary = paramIndex2idPrimary.get(paramIndex);
- assert id2hrn.containsKey(idPrimary);
- HeapRegionNode hrnPrimary = id2hrn.get(idPrimary);
+ assert id2hrn.containsKey(idPrimary);
+ HeapRegionNode hrnPrimary = id2hrn.get(idPrimary);
- TokenTuple p_i = new TokenTuple(hrnPrimary.getID(),
- false, // multiple-object?
- TokenTuple.ARITY_ONE).makeCanonical();
- paramTokenPrimary2paramIndex.put(p_i, paramIndex);
- paramIndex2paramTokenPrimary.put(paramIndex, p_i);
+ TokenTuple p_i = new TokenTuple(hrnPrimary.getID(),
+ false, // multiple-object?
+ TokenTuple.ARITY_ONE).makeCanonical();
+ paramTokenPrimary2paramIndex.put(p_i, paramIndex);
+ paramIndex2paramTokenPrimary.put(paramIndex, p_i);
}
// any parameter object, by type, may have no secondary region
if( paramIndex2idSecondary.containsKey(paramIndex) ) {
- Integer idSecondary = paramIndex2idSecondary.get(paramIndex);
-
- assert id2hrn.containsKey(idSecondary);
- HeapRegionNode hrnSecondary = id2hrn.get(idSecondary);
-
- TokenTuple s_i = new TokenTuple(hrnSecondary.getID(),
- true, // multiple-object?
- TokenTuple.ARITY_ONE).makeCanonical();
- paramTokenSecondary2paramIndex.put(s_i, paramIndex);
- paramIndex2paramTokenSecondary.put(paramIndex, s_i);
-
- TokenTuple s_i_plus = new TokenTuple(hrnSecondary.getID(),
- true, // multiple-object?
- TokenTuple.ARITY_ONEORMORE).makeCanonical();
- paramTokenSecondaryPlus2paramIndex.put(s_i_plus, paramIndex);
- paramIndex2paramTokenSecondaryPlus.put(paramIndex, s_i_plus);
-
- TokenTuple s_i_star = new TokenTuple(hrnSecondary.getID(),
- true, // multiple-object?
- TokenTuple.ARITY_ZEROORMORE).makeCanonical();
- paramTokenSecondaryStar2paramIndex.put(s_i_star, paramIndex);
- paramIndex2paramTokenSecondaryStar.put(paramIndex, s_i_star);
+ Integer idSecondary = paramIndex2idSecondary.get(paramIndex);
+
+ assert id2hrn.containsKey(idSecondary);
+ HeapRegionNode hrnSecondary = id2hrn.get(idSecondary);
+
+ TokenTuple s_i = new TokenTuple(hrnSecondary.getID(),
+ true, // multiple-object?
+ TokenTuple.ARITY_ONE).makeCanonical();
+ paramTokenSecondary2paramIndex.put(s_i, paramIndex);
+ paramIndex2paramTokenSecondary.put(paramIndex, s_i);
+
+ TokenTuple s_i_plus = new TokenTuple(hrnSecondary.getID(),
+ true, // multiple-object?
+ TokenTuple.ARITY_ONEORMORE).makeCanonical();
+ paramTokenSecondaryPlus2paramIndex.put(s_i_plus, paramIndex);
+ paramIndex2paramTokenSecondaryPlus.put(paramIndex, s_i_plus);
+
+ TokenTuple s_i_star = new TokenTuple(hrnSecondary.getID(),
+ true, // multiple-object?
+ TokenTuple.ARITY_ZEROORMORE).makeCanonical();
+ paramTokenSecondaryStar2paramIndex.put(s_i_star, paramIndex);
+ paramIndex2paramTokenSecondaryStar.put(paramIndex, s_i_star);
}
}
}
Iterator<ReferenceEdge> itrEdges = ln.iteratorToReferencees();
while( itrEdges.hasNext() ) {
- ageTokens(as, itrEdges.next() );
+ ageTokens(as, itrEdges.next() );
}
}
Iterator<ReferenceEdge> itrEdges = hrnToAge.iteratorToReferencees();
while( itrEdges.hasNext() ) {
- ageTokens(as, itrEdges.next() );
+ ageTokens(as, itrEdges.next() );
}
}
boolean hasFlags = false;
if( as.getType().isClass() ) {
- hasFlags = as.getType().getClassDesc().hasFlags();
+ hasFlags = as.getType().getClassDesc().hasFlags();
}
if(as.getFlag()) {
- hasFlags=as.getFlag();
+ hasFlags=as.getFlag();
}
hrnSummary = createNewHeapRegionNode(idSummary, // id or null to generate a new one
generateUniqueIdentifier(as,0,true));
for( int i = 0; i < as.getAllocationDepth(); ++i ) {
- Integer idIth = as.getIthOldest(i);
- assert !id2hrn.containsKey(idIth);
- createNewHeapRegionNode(idIth, // id or null to generate a new one
- true, // single object?
- false, // summary?
- hasFlags, // flagged?
- false, // is a parameter?
- as.getType(), // type
- as, // allocation site
- null, // reachability set
- as.toStringForDOT() + "\\n" + i + " oldest",
- generateUniqueIdentifier(as,i,false));
+ Integer idIth = as.getIthOldest(i);
+ assert !id2hrn.containsKey(idIth);
+ createNewHeapRegionNode(idIth, // id or null to generate a new one
+ true, // single object?
+ false, // summary?
+ hasFlags, // flagged?
+ false, // is a parameter?
+ as.getType(), // type
+ as, // allocation site
+ null, // reachability set
+ as.toStringForDOT() + "\\n" + i + " oldest",
+ generateUniqueIdentifier(as,i,false));
}
}
boolean hasFlags = false;
if( as.getType().isClass() ) {
- hasFlags = as.getType().getClassDesc().hasFlags();
+ hasFlags = as.getType().getClassDesc().hasFlags();
}
hrnShadowSummary = createNewHeapRegionNode(idShadowSummary, // id or null to generate a new one
"");
for( int i = 0; i < as.getAllocationDepth(); ++i ) {
- Integer idShadowIth = as.getIthOldestShadow(i);
- assert !id2hrn.containsKey(idShadowIth);
- createNewHeapRegionNode(idShadowIth, // id or null to generate a new one
- true, // single object?
- false, // summary?
- hasFlags, // flagged?
- false, // is a parameter?
- as.getType(), // type
- as, // allocation site
- null, // reachability set
- as + "\\n" + as.getType() + "\\n" + i + " shadow",
- "");
+ Integer idShadowIth = as.getIthOldestShadow(i);
+ assert !id2hrn.containsKey(idShadowIth);
+ createNewHeapRegionNode(idShadowIth, // id or null to generate a new one
+ true, // single object?
+ false, // summary?
+ hasFlags, // flagged?
+ false, // is a parameter?
+ as.getType(), // type
+ as, // allocation site
+ null, // reachability set
+ as + "\\n" + as.getType() + "\\n" + i + " shadow",
+ "");
}
}
edge.getField() );
if( edgeSummary == null ) {
- // the merge is trivial, nothing to be done
+ // the merge is trivial, nothing to be done
} else {
- // otherwise an edge from the referencer to hrnSummary exists already
- // and the edge referencer->hrn should be merged with it
- edgeMerged.setBeta(edgeMerged.getBeta().union(edgeSummary.getBeta() ) );
+ // otherwise an edge from the referencer to hrnSummary exists already
+ // and the edge referencer->hrn should be merged with it
+ edgeMerged.setBeta(edgeMerged.getBeta().union(edgeSummary.getBeta() ) );
}
addReferenceEdge(hrnSummary, hrnReferencee, edgeMerged);
edge.getField() );
if( edgeSummary == null ) {
- // the merge is trivial, nothing to be done
+ // the merge is trivial, nothing to be done
} else {
- // otherwise an edge from the referencer to alpha_S exists already
- // and the edge referencer->alpha_K should be merged with it
- edgeMerged.setBeta(edgeMerged.getBeta().union(edgeSummary.getBeta() ) );
+ // otherwise an edge from the referencer to alpha_S exists already
+ // and the edge referencer->alpha_K should be merged with it
+ edgeMerged.setBeta(edgeMerged.getBeta().union(edgeSummary.getBeta() ) );
}
addReferenceEdge(onReferencer, hrnSummary, edgeMerged);
Iterator<ReferenceEdge> referItr = n.iteratorToReferencers();
while( referItr.hasNext() ) {
- ReferenceEdge edge = referItr.next();
- todoEdges.add(edge);
+ ReferenceEdge edge = referItr.next();
+ todoEdges.add(edge);
- if( !edgePlannedChanges.containsKey(edge) ) {
- edgePlannedChanges.put(edge, new ChangeTupleSet().makeCanonical() );
- }
+ if( !edgePlannedChanges.containsKey(edge) ) {
+ edgePlannedChanges.put(edge, new ChangeTupleSet().makeCanonical() );
+ }
- edgePlannedChanges.put(edge, edgePlannedChanges.get(edge).union(C) );
+ edgePlannedChanges.put(edge, edgePlannedChanges.get(edge).union(C) );
}
Iterator<ReferenceEdge> refeeItr = n.iteratorToReferencees();
while( refeeItr.hasNext() ) {
- ReferenceEdge edgeF = refeeItr.next();
- HeapRegionNode m = edgeF.getDst();
+ ReferenceEdge edgeF = refeeItr.next();
+ HeapRegionNode m = edgeF.getDst();
- ChangeTupleSet changesToPass = new ChangeTupleSet().makeCanonical();
+ ChangeTupleSet changesToPass = new ChangeTupleSet().makeCanonical();
- Iterator<ChangeTuple> itrCprime = C.iterator();
- while( itrCprime.hasNext() ) {
- ChangeTuple c = itrCprime.next();
- if( edgeF.getBeta().contains(c.getSetToMatch() ) ) {
- changesToPass = changesToPass.union(c);
- }
- }
+ Iterator<ChangeTuple> itrCprime = C.iterator();
+ while( itrCprime.hasNext() ) {
+ ChangeTuple c = itrCprime.next();
+ if( edgeF.getBeta().contains(c.getSetToMatch() ) ) {
+ changesToPass = changesToPass.union(c);
+ }
+ }
- if( !changesToPass.isEmpty() ) {
- if( !nodePlannedChanges.containsKey(m) ) {
- nodePlannedChanges.put(m, new ChangeTupleSet().makeCanonical() );
- }
+ if( !changesToPass.isEmpty() ) {
+ if( !nodePlannedChanges.containsKey(m) ) {
+ nodePlannedChanges.put(m, new ChangeTupleSet().makeCanonical() );
+ }
- ChangeTupleSet currentChanges = nodePlannedChanges.get(m);
+ ChangeTupleSet currentChanges = nodePlannedChanges.get(m);
- if( !changesToPass.isSubset(currentChanges) ) {
+ if( !changesToPass.isSubset(currentChanges) ) {
- nodePlannedChanges.put(m, currentChanges.union(changesToPass) );
- todoNodes.add(m);
- }
- }
+ nodePlannedChanges.put(m, currentChanges.union(changesToPass) );
+ todoNodes.add(m);
+ }
+ }
}
todoNodes.remove(n);
todoEdges.remove(edgeE);
if( !edgePlannedChanges.containsKey(edgeE) ) {
- edgePlannedChanges.put(edgeE, new ChangeTupleSet().makeCanonical() );
+ edgePlannedChanges.put(edgeE, new ChangeTupleSet().makeCanonical() );
}
ChangeTupleSet C = edgePlannedChanges.get(edgeE);
Iterator<ChangeTuple> itrC = C.iterator();
while( itrC.hasNext() ) {
- ChangeTuple c = itrC.next();
- if( edgeE.getBeta().contains(c.getSetToMatch() ) ) {
- changesToPass = changesToPass.union(c);
- }
+ ChangeTuple c = itrC.next();
+ if( edgeE.getBeta().contains(c.getSetToMatch() ) ) {
+ changesToPass = changesToPass.union(c);
+ }
}
OwnershipNode onSrc = edgeE.getSrc();
if( !changesToPass.isEmpty() && onSrc instanceof HeapRegionNode ) {
- HeapRegionNode n = (HeapRegionNode) onSrc;
+ HeapRegionNode n = (HeapRegionNode) onSrc;
- Iterator<ReferenceEdge> referItr = n.iteratorToReferencers();
- while( referItr.hasNext() ) {
- ReferenceEdge edgeF = referItr.next();
+ Iterator<ReferenceEdge> referItr = n.iteratorToReferencers();
+ while( referItr.hasNext() ) {
+ ReferenceEdge edgeF = referItr.next();
- if( !edgePlannedChanges.containsKey(edgeF) ) {
- edgePlannedChanges.put(edgeF, new ChangeTupleSet().makeCanonical() );
- }
+ if( !edgePlannedChanges.containsKey(edgeF) ) {
+ edgePlannedChanges.put(edgeF, new ChangeTupleSet().makeCanonical() );
+ }
- ChangeTupleSet currentChanges = edgePlannedChanges.get(edgeF);
+ ChangeTupleSet currentChanges = edgePlannedChanges.get(edgeF);
- if( !changesToPass.isSubset(currentChanges) ) {
- todoEdges.add(edgeF);
- edgePlannedChanges.put(edgeF, currentChanges.union(changesToPass) );
- }
- }
+ if( !changesToPass.isSubset(currentChanges) ) {
+ todoEdges.add(edgeF);
+ edgePlannedChanges.put(edgeF, currentChanges.union(changesToPass) );
+ }
+ }
}
}
TypeDescriptor typeParam = tdParam.getType();
if( typeParam.isImmutable() && !typeParam.isArray() ) {
- // don't bother with this primitive parameter, it
- // cannot affect reachability
- continue;
+ // don't bother with this primitive parameter, it
+ // cannot affect reachability
+ continue;
}
// now depending on whether the callee is static or not
// to find all reachable nodes, start with label referencees
Iterator<ReferenceEdge> edgeArgItr = lnArg_i.iteratorToReferencees();
while( edgeArgItr.hasNext() ) {
- ReferenceEdge edge = edgeArgItr.next();
- todoNodes.add(edge.getDst() );
+ ReferenceEdge edge = edgeArgItr.next();
+ todoNodes.add(edge.getDst() );
}
// then follow links until all reachable nodes have been found
while( !todoNodes.isEmpty() ) {
- HeapRegionNode hrn = todoNodes.iterator().next();
- todoNodes.remove(hrn);
- reachableNodes.add(hrn);
-
- Iterator<ReferenceEdge> edgeItr = hrn.iteratorToReferencees();
- while( edgeItr.hasNext() ) {
- ReferenceEdge edge = edgeItr.next();
-
- if( !reachableNodes.contains(edge.getDst() ) ) {
- todoNodes.add(edge.getDst() );
- }
- }
+ HeapRegionNode hrn = todoNodes.iterator().next();
+ todoNodes.remove(hrn);
+ reachableNodes.add(hrn);
+
+ Iterator<ReferenceEdge> edgeItr = hrn.iteratorToReferencees();
+ while( edgeItr.hasNext() ) {
+ ReferenceEdge edge = edgeItr.next();
+
+ if( !reachableNodes.contains(edge.getDst() ) ) {
+ todoNodes.add(edge.getDst() );
+ }
+ }
}
// save for later
// check for arguments that are aliased
for( int i = 0; i < fm.numParameters(); ++i ) {
for( int j = 0; j < i; ++j ) {
- HashSet<HeapRegionNode> s1 = paramIndex2reachableCallerNodes.get(i);
- HashSet<HeapRegionNode> s2 = paramIndex2reachableCallerNodes.get(j);
+ HashSet<HeapRegionNode> s1 = paramIndex2reachableCallerNodes.get(i);
+ HashSet<HeapRegionNode> s2 = paramIndex2reachableCallerNodes.get(j);
- // some parameters are immutable or primitive, so skip em
- if( s1 == null || s2 == null ) {
- continue;
- }
+ // some parameters are immutable or primitive, so skip em
+ if( s1 == null || s2 == null ) {
+ continue;
+ }
- Set<HeapRegionNode> intersection = new HashSet<HeapRegionNode>(s1);
- intersection.retainAll(s2);
+ Set<HeapRegionNode> intersection = new HashSet<HeapRegionNode>(s1);
+ intersection.retainAll(s2);
- if( !intersection.isEmpty() ) {
- aliasedIndices.add(new Integer(i) );
- aliasedIndices.add(new Integer(j) );
- }
+ if( !intersection.isEmpty() ) {
+ aliasedIndices.add(new Integer(i) );
+ aliasedIndices.add(new Integer(j) );
+ }
}
}
// skip this if there is no secondary token or the parameter
// is part of the aliasing context
if( s_i == null || mc.getAliasedParamIndices().contains(i) ) {
- continue;
+ continue;
}
rsOut = rsOut.removeTokenAIfTokenB(p_i, s_i);
Iterator fieldItr = cd.getFields();
while( fieldItr.hasNext() ) {
- FieldDescriptor fd = (FieldDescriptor) fieldItr.next();
- TypeDescriptor typeField = fd.getType();
- assert typeField != null;
+ FieldDescriptor fd = (FieldDescriptor) fieldItr.next();
+ TypeDescriptor typeField = fd.getType();
+ assert typeField != null;
- if( ogCallee.hasFieldBeenUpdated(hrnPrimary, fd.getSymbol() ) ) {
- clearReferenceEdgesFrom(hrnCaller, fd.getType(), fd.getSymbol(), false);
- }
+ if( ogCallee.hasFieldBeenUpdated(hrnPrimary, fd.getSymbol() ) ) {
+ clearReferenceEdgesFrom(hrnCaller, fd.getType(), fd.getSymbol(), false);
+ }
}
cd = cd.getSuperDesc();
while( itr.hasNext() ) {
ReferenceEdge e = itr.next();
if( e.fieldEquals(field) && e.isInitialParam() ) {
- return false;
+ return false;
}
}
) {
try {
- writeGraph("debug1BeforeCall",
- true, // write labels (variables)
- true, // selectively hide intermediate temp vars
- true, // prune unreachable heap regions
- false, // show back edges to confirm graph validity
- false, // show parameter indices (unmaintained!)
- true, // hide subset reachability states
- true); // hide edge taints
-
- ogCallee.writeGraph("debug0Callee",
- true, // write labels (variables)
- true, // selectively hide intermediate temp vars
- true, // prune unreachable heap regions
- false, // show back edges to confirm graph validity
- false, // show parameter indices (unmaintained!)
- true, // hide subset reachability states
- true); // hide edge taints
+ writeGraph("debug1BeforeCall",
+ true, // write labels (variables)
+ true, // selectively hide intermediate temp vars
+ true, // prune unreachable heap regions
+ false, // show back edges to confirm graph validity
+ false, // show parameter indices (unmaintained!)
+ true, // hide subset reachability states
+ true); // hide edge taints
+
+ ogCallee.writeGraph("debug0Callee",
+ true, // write labels (variables)
+ true, // selectively hide intermediate temp vars
+ true, // prune unreachable heap regions
+ false, // show back edges to confirm graph validity
+ false, // show parameter indices (unmaintained!)
+ true, // hide subset reachability states
+ true); // hide edge taints
} catch( IOException e ) {
}
Integer paramIndex = new Integer(i);
if( !ogCallee.paramIndex2idPrimary.containsKey(paramIndex) ) {
- // skip this immutable parameter
- continue;
+ // skip this immutable parameter
+ continue;
}
// setup H (primary)
// setup J (primary->X)
Iterator<ReferenceEdge> p2xItr = hrnPrimary.iteratorToReferencees();
while( p2xItr.hasNext() ) {
- ReferenceEdge p2xEdge = p2xItr.next();
-
- // we only care about initial parameter edges here
- if( !p2xEdge.isInitialParam() ) {
- continue;
- }
-
- HeapRegionNode hrnDst = p2xEdge.getDst();
-
- if( ogCallee.idPrimary2paramIndexSet.containsKey(hrnDst.getID() ) ) {
- Iterator<Integer> jItr = ogCallee.idPrimary2paramIndexSet.get(hrnDst.getID() ).iterator();
- while( jItr.hasNext() ) {
- Integer j = jItr.next();
- paramIndex2rewriteJ_p2p.put(makeMapKey(i, j, p2xEdge.getField() ),
- toShadowTokens(ogCallee, p2xEdge.getBeta() ) );
- }
-
- } else {
- assert ogCallee.idSecondary2paramIndexSet.containsKey(hrnDst.getID() );
- paramIndex2rewriteJ_p2s.put(makeMapKey(i, p2xEdge.getField() ),
- toShadowTokens(ogCallee, p2xEdge.getBeta() ) );
- }
+ ReferenceEdge p2xEdge = p2xItr.next();
+
+ // we only care about initial parameter edges here
+ if( !p2xEdge.isInitialParam() ) {
+ continue;
+ }
+
+ HeapRegionNode hrnDst = p2xEdge.getDst();
+
+ if( ogCallee.idPrimary2paramIndexSet.containsKey(hrnDst.getID() ) ) {
+ Iterator<Integer> jItr = ogCallee.idPrimary2paramIndexSet.get(hrnDst.getID() ).iterator();
+ while( jItr.hasNext() ) {
+ Integer j = jItr.next();
+ paramIndex2rewriteJ_p2p.put(makeMapKey(i, j, p2xEdge.getField() ),
+ toShadowTokens(ogCallee, p2xEdge.getBeta() ) );
+ }
+
+ } else {
+ assert ogCallee.idSecondary2paramIndexSet.containsKey(hrnDst.getID() );
+ paramIndex2rewriteJ_p2s.put(makeMapKey(i, p2xEdge.getField() ),
+ toShadowTokens(ogCallee, p2xEdge.getBeta() ) );
+ }
}
// setup K (primary)
ReachabilitySet K_p = new ReachabilitySet().makeCanonical();
ReachabilitySet K_p2 = new ReachabilitySet().makeCanonical();
if( s_i == null ) {
- K_p = qBeta;
+ K_p = qBeta;
} else {
- // sort qBeta into K_p1 and K_p2
- Iterator<TokenTupleSet> ttsItr = qBeta.iterator();
- while( ttsItr.hasNext() ) {
- TokenTupleSet tts = ttsItr.next();
- if( s_i != null && tts.containsBoth(p_i, s_i) ) {
- K_p2 = K_p2.union(tts);
- } else {
- K_p = K_p.union(tts);
- }
- }
+ // sort qBeta into K_p1 and K_p2
+ Iterator<TokenTupleSet> ttsItr = qBeta.iterator();
+ while( ttsItr.hasNext() ) {
+ TokenTupleSet tts = ttsItr.next();
+ if( s_i != null && tts.containsBoth(p_i, s_i) ) {
+ K_p2 = K_p2.union(tts);
+ } else {
+ K_p = K_p.union(tts);
+ }
+ }
}
paramIndex2rewriteK_p.put(paramIndex, K_p);
paramIndex2rewriteK_p2.put(paramIndex, K_p2);
// if there is a secondary node, compute the rest of the rewrite rules
if( ogCallee.paramIndex2idSecondary.containsKey(paramIndex) ) {
- // setup H (secondary)
- Integer idSecondary = ogCallee.paramIndex2idSecondary.get(paramIndex);
- assert ogCallee.id2hrn.containsKey(idSecondary);
- HeapRegionNode hrnSecondary = ogCallee.id2hrn.get(idSecondary);
- assert hrnSecondary != null;
- paramIndex2rewriteH_s.put(paramIndex, toShadowTokens(ogCallee, hrnSecondary.getAlpha() ) );
-
- // setup J (secondary->X)
- Iterator<ReferenceEdge> s2xItr = hrnSecondary.iteratorToReferencees();
- while( s2xItr.hasNext() ) {
- ReferenceEdge s2xEdge = s2xItr.next();
-
- if( !s2xEdge.isInitialParam() ) {
- continue;
- }
-
- HeapRegionNode hrnDst = s2xEdge.getDst();
-
- if( ogCallee.idPrimary2paramIndexSet.containsKey(hrnDst.getID() ) ) {
- Iterator<Integer> jItr = ogCallee.idPrimary2paramIndexSet.get(hrnDst.getID() ).iterator();
- while( jItr.hasNext() ) {
- Integer j = jItr.next();
- paramIndex2rewriteJ_s2p.put(i, toShadowTokens(ogCallee, s2xEdge.getBeta() ) );
- }
-
- } else {
- assert ogCallee.idSecondary2paramIndexSet.containsKey(hrnDst.getID() );
- paramIndex2rewriteJ_s2s.put(i, toShadowTokens(ogCallee, s2xEdge.getBeta() ) );
- }
- }
-
- // setup K (secondary)
- TempDescriptor tdParamR = ogCallee.paramIndex2tdR.get(paramIndex);
- assert tdParamR != null;
- LabelNode lnParamR = ogCallee.td2ln.get(tdParamR);
- assert lnParamR != null;
- ReferenceEdge edgeSpecialR_i = lnParamR.getReferenceTo(hrnSecondary, null, null);
- assert edgeSpecialR_i != null;
- paramIndex2rewriteK_s.put(paramIndex,
- toShadowTokens(ogCallee, edgeSpecialR_i.getBeta() ) );
+ // setup H (secondary)
+ Integer idSecondary = ogCallee.paramIndex2idSecondary.get(paramIndex);
+ assert ogCallee.id2hrn.containsKey(idSecondary);
+ HeapRegionNode hrnSecondary = ogCallee.id2hrn.get(idSecondary);
+ assert hrnSecondary != null;
+ paramIndex2rewriteH_s.put(paramIndex, toShadowTokens(ogCallee, hrnSecondary.getAlpha() ) );
+
+ // setup J (secondary->X)
+ Iterator<ReferenceEdge> s2xItr = hrnSecondary.iteratorToReferencees();
+ while( s2xItr.hasNext() ) {
+ ReferenceEdge s2xEdge = s2xItr.next();
+
+ if( !s2xEdge.isInitialParam() ) {
+ continue;
+ }
+
+ HeapRegionNode hrnDst = s2xEdge.getDst();
+
+ if( ogCallee.idPrimary2paramIndexSet.containsKey(hrnDst.getID() ) ) {
+ Iterator<Integer> jItr = ogCallee.idPrimary2paramIndexSet.get(hrnDst.getID() ).iterator();
+ while( jItr.hasNext() ) {
+ Integer j = jItr.next();
+ paramIndex2rewriteJ_s2p.put(i, toShadowTokens(ogCallee, s2xEdge.getBeta() ) );
+ }
+
+ } else {
+ assert ogCallee.idSecondary2paramIndexSet.containsKey(hrnDst.getID() );
+ paramIndex2rewriteJ_s2s.put(i, toShadowTokens(ogCallee, s2xEdge.getBeta() ) );
+ }
+ }
+
+ // setup K (secondary)
+ TempDescriptor tdParamR = ogCallee.paramIndex2tdR.get(paramIndex);
+ assert tdParamR != null;
+ LabelNode lnParamR = ogCallee.td2ln.get(tdParamR);
+ assert lnParamR != null;
+ ReferenceEdge edgeSpecialR_i = lnParamR.getReferenceTo(hrnSecondary, null, null);
+ assert edgeSpecialR_i != null;
+ paramIndex2rewriteK_s.put(paramIndex,
+ toShadowTokens(ogCallee, edgeSpecialR_i.getBeta() ) );
}
// do a callee-effect strong update pre-pass here
if( argTemp_i.getType().isClass() ) {
- Iterator<ReferenceEdge> edgeItr = argLabel_i.iteratorToReferencees();
- while( edgeItr.hasNext() ) {
- ReferenceEdge edge = edgeItr.next();
- HeapRegionNode hrn = edge.getDst();
-
- if( (hrn.getNumReferencers() == 1) || // case 1
- (hrn.isSingleObject() && argLabel_i.getNumReferencees() == 1) // case 2
- ) {
- if( !DISABLE_STRONG_UPDATES ) {
- effectCalleeStrongUpdates(paramIndex, ogCallee, hrn);
- }
- }
- }
+ Iterator<ReferenceEdge> edgeItr = argLabel_i.iteratorToReferencees();
+ while( edgeItr.hasNext() ) {
+ ReferenceEdge edge = edgeItr.next();
+ HeapRegionNode hrn = edge.getDst();
+
+ if( (hrn.getNumReferencers() == 1) || // case 1
+ (hrn.isSingleObject() && argLabel_i.getNumReferencees() == 1) // case 2
+ ) {
+ if( !DISABLE_STRONG_UPDATES ) {
+ effectCalleeStrongUpdates(paramIndex, ogCallee, hrn);
+ }
+ }
+ }
}
// then calculate the d and D rewrite rules
ReachabilitySet d_i_s = new ReachabilitySet().makeCanonical();
Iterator<ReferenceEdge> edgeItr = argLabel_i.iteratorToReferencees();
while( edgeItr.hasNext() ) {
- ReferenceEdge edge = edgeItr.next();
+ ReferenceEdge edge = edgeItr.next();
- d_i_p = d_i_p.union(edge.getBeta().intersection(edge.getDst().getAlpha() ) );
- d_i_s = d_i_s.union(edge.getBeta() );
+ d_i_p = d_i_p.union(edge.getBeta().intersection(edge.getDst().getAlpha() ) );
+ d_i_s = d_i_s.union(edge.getBeta() );
}
paramIndex2rewrite_d_p.put(paramIndex, d_i_p);
paramIndex2rewrite_d_s.put(paramIndex, d_i_s);
// find all reachable nodes starting with label referencees
Iterator<ReferenceEdge> edgeArgItr = lnArg_i.iteratorToReferencees();
while( edgeArgItr.hasNext() ) {
- ReferenceEdge edge = edgeArgItr.next();
- HeapRegionNode hrn = edge.getDst();
-
- dr.add(hrn);
-
- if( lnArg_i.getNumReferencees() == 1 && hrn.isSingleObject() ) {
- defParamObj.add(hrn);
- }
-
- Iterator<ReferenceEdge> edgeHrnItr = hrn.iteratorToReferencees();
- while( edgeHrnItr.hasNext() ) {
- ReferenceEdge edger = edgeHrnItr.next();
- todo.add(edger.getDst() );
- }
-
- // then follow links until all reachable nodes have been found
- while( !todo.isEmpty() ) {
- HeapRegionNode hrnr = todo.iterator().next();
- todo.remove(hrnr);
-
- r.add(hrnr);
-
- Iterator<ReferenceEdge> edgeItr = hrnr.iteratorToReferencees();
- while( edgeItr.hasNext() ) {
- ReferenceEdge edger = edgeItr.next();
- if( !r.contains(edger.getDst() ) ) {
- todo.add(edger.getDst() );
- }
- }
- }
-
- if( hrn.isSingleObject() ) {
- r.remove(hrn);
- }
+ ReferenceEdge edge = edgeArgItr.next();
+ HeapRegionNode hrn = edge.getDst();
+
+ dr.add(hrn);
+
+ if( lnArg_i.getNumReferencees() == 1 && hrn.isSingleObject() ) {
+ defParamObj.add(hrn);
+ }
+
+ Iterator<ReferenceEdge> edgeHrnItr = hrn.iteratorToReferencees();
+ while( edgeHrnItr.hasNext() ) {
+ ReferenceEdge edger = edgeHrnItr.next();
+ todo.add(edger.getDst() );
+ }
+
+ // then follow links until all reachable nodes have been found
+ while( !todo.isEmpty() ) {
+ HeapRegionNode hrnr = todo.iterator().next();
+ todo.remove(hrnr);
+
+ r.add(hrnr);
+
+ Iterator<ReferenceEdge> edgeItr = hrnr.iteratorToReferencees();
+ while( edgeItr.hasNext() ) {
+ ReferenceEdge edger = edgeItr.next();
+ if( !r.contains(edger.getDst() ) ) {
+ todo.add(edger.getDst() );
+ }
+ }
+ }
+
+ if( hrn.isSingleObject() ) {
+ r.remove(hrn);
+ }
}
pi2dr.put(index, dr);
// report primary parameter object mappings
mapItr = pi2dr.entrySet().iterator();
while( mapItr.hasNext() ) {
- Map.Entry me = (Map.Entry)mapItr.next();
- Integer paramIndex = (Integer) me.getKey();
- Set<HeapRegionNode> hrnAset = (Set<HeapRegionNode>)me.getValue();
-
- Iterator<HeapRegionNode> hrnItr = hrnAset.iterator();
- while( hrnItr.hasNext() ) {
- HeapRegionNode hrnA = hrnItr.next();
- pd.mapRegionToParamObject(hrnA, paramIndex);
- }
+ Map.Entry me = (Map.Entry)mapItr.next();
+ Integer paramIndex = (Integer) me.getKey();
+ Set<HeapRegionNode> hrnAset = (Set<HeapRegionNode>)me.getValue();
+
+ Iterator<HeapRegionNode> hrnItr = hrnAset.iterator();
+ while( hrnItr.hasNext() ) {
+ HeapRegionNode hrnA = hrnItr.next();
+ pd.mapRegionToParamObject(hrnA, paramIndex);
+ }
}
// report parameter-reachable mappings
mapItr = pi2r.entrySet().iterator();
while( mapItr.hasNext() ) {
- Map.Entry me = (Map.Entry)mapItr.next();
- Integer paramIndex = (Integer) me.getKey();
- Set<HeapRegionNode> hrnRset = (Set<HeapRegionNode>)me.getValue();
-
- Iterator<HeapRegionNode> hrnItr = hrnRset.iterator();
- while( hrnItr.hasNext() ) {
- HeapRegionNode hrnR = hrnItr.next();
- pd.mapRegionToParamReachable(hrnR, paramIndex);
- }
+ Map.Entry me = (Map.Entry)mapItr.next();
+ Integer paramIndex = (Integer) me.getKey();
+ Set<HeapRegionNode> hrnRset = (Set<HeapRegionNode>)me.getValue();
+
+ Iterator<HeapRegionNode> hrnItr = hrnRset.iterator();
+ while( hrnItr.hasNext() ) {
+ HeapRegionNode hrnR = hrnItr.next();
+ pd.mapRegionToParamReachable(hrnR, paramIndex);
+ }
}
// and we're done in this method for special param decomp mode
Set<HeapRegionNode> dr = pi2dr.get(index);
Iterator<HeapRegionNode> hrnItr = dr.iterator();
while( hrnItr.hasNext() ) {
- // this heap region is definitely an "a_i" or primary by virtue of being in dr
- HeapRegionNode hrn = hrnItr.next();
-
- tokens2states.clear();
- tokens2states.put(p_i, hrn.getAlpha() );
-
- rewriteCallerReachability(index,
- hrn,
- null,
- paramIndex2rewriteH_p.get(index),
- tokens2states,
- paramIndex2rewrite_d_p,
- paramIndex2rewrite_d_s,
- paramIndex2rewriteD,
- ogCallee,
- false,
- null);
-
- nodesWithNewAlpha.add(hrn);
-
- // sort edges
- Iterator<ReferenceEdge> edgeItr = hrn.iteratorToReferencers();
- while( edgeItr.hasNext() ) {
- ReferenceEdge edge = edgeItr.next();
- OwnershipNode on = edge.getSrc();
-
- boolean edge_classified = false;
-
-
- if( on instanceof HeapRegionNode ) {
- // hrn0 may be "a_j" and/or "r_j" or even neither
- HeapRegionNode hrn0 = (HeapRegionNode) on;
-
- Iterator itr = pi2dr.entrySet().iterator();
- while( itr.hasNext() ) {
- Map.Entry mo = (Map.Entry)itr.next();
- Integer pi = (Integer) mo.getKey();
- Set<HeapRegionNode> dr_i = (Set<HeapRegionNode>)mo.getValue();
-
- if( dr_i.contains(hrn0) ) {
- addEdgeIndexPair(edges_p2p, pi, edge, index);
- edge_classified = true;
- }
- }
-
- itr = pi2r.entrySet().iterator();
- while( itr.hasNext() ) {
- Map.Entry mo = (Map.Entry)itr.next();
- Integer pi = (Integer) mo.getKey();
- Set<HeapRegionNode> r_i = (Set<HeapRegionNode>)mo.getValue();
-
- if( r_i.contains(hrn0) ) {
- addEdgeIndexPair(edges_s2p, pi, edge, index);
- edge_classified = true;
- }
- }
- }
-
- // all of these edges are upstream of directly reachable objects
- if( !edge_classified ) {
- addEdgeIndexPair(edges_up_dr, index, edge, index);
- }
- }
+ // this heap region is definitely an "a_i" or primary by virtue of being in dr
+ HeapRegionNode hrn = hrnItr.next();
+
+ tokens2states.clear();
+ tokens2states.put(p_i, hrn.getAlpha() );
+
+ rewriteCallerReachability(index,
+ hrn,
+ null,
+ paramIndex2rewriteH_p.get(index),
+ tokens2states,
+ paramIndex2rewrite_d_p,
+ paramIndex2rewrite_d_s,
+ paramIndex2rewriteD,
+ ogCallee,
+ false,
+ null);
+
+ nodesWithNewAlpha.add(hrn);
+
+ // sort edges
+ Iterator<ReferenceEdge> edgeItr = hrn.iteratorToReferencers();
+ while( edgeItr.hasNext() ) {
+ ReferenceEdge edge = edgeItr.next();
+ OwnershipNode on = edge.getSrc();
+
+ boolean edge_classified = false;
+
+
+ if( on instanceof HeapRegionNode ) {
+ // hrn0 may be "a_j" and/or "r_j" or even neither
+ HeapRegionNode hrn0 = (HeapRegionNode) on;
+
+ Iterator itr = pi2dr.entrySet().iterator();
+ while( itr.hasNext() ) {
+ Map.Entry mo = (Map.Entry)itr.next();
+ Integer pi = (Integer) mo.getKey();
+ Set<HeapRegionNode> dr_i = (Set<HeapRegionNode>)mo.getValue();
+
+ if( dr_i.contains(hrn0) ) {
+ addEdgeIndexPair(edges_p2p, pi, edge, index);
+ edge_classified = true;
+ }
+ }
+
+ itr = pi2r.entrySet().iterator();
+ while( itr.hasNext() ) {
+ Map.Entry mo = (Map.Entry)itr.next();
+ Integer pi = (Integer) mo.getKey();
+ Set<HeapRegionNode> r_i = (Set<HeapRegionNode>)mo.getValue();
+
+ if( r_i.contains(hrn0) ) {
+ addEdgeIndexPair(edges_s2p, pi, edge, index);
+ edge_classified = true;
+ }
+ }
+ }
+
+ // all of these edges are upstream of directly reachable objects
+ if( !edge_classified ) {
+ addEdgeIndexPair(edges_up_dr, index, edge, index);
+ }
+ }
}
Set<HeapRegionNode> r = pi2r.get(index);
hrnItr = r.iterator();
while( hrnItr.hasNext() ) {
- // this heap region is definitely an "r_i" or secondary by virtue of being in r
- HeapRegionNode hrn = hrnItr.next();
-
- if( paramIndex2rewriteH_s.containsKey(index) ) {
-
- tokens2states.clear();
- tokens2states.put(p_i, new ReachabilitySet().makeCanonical() );
- tokens2states.put(s_i, hrn.getAlpha() );
-
- rewriteCallerReachability(index,
- hrn,
- null,
- paramIndex2rewriteH_s.get(index),
- tokens2states,
- paramIndex2rewrite_d_p,
- paramIndex2rewrite_d_s,
- paramIndex2rewriteD,
- ogCallee,
- false,
- null);
-
- nodesWithNewAlpha.add(hrn);
- }
-
- // sort edges
- Iterator<ReferenceEdge> edgeItr = hrn.iteratorToReferencers();
- while( edgeItr.hasNext() ) {
- ReferenceEdge edge = edgeItr.next();
- OwnershipNode on = edge.getSrc();
-
- boolean edge_classified = false;
-
- if( on instanceof HeapRegionNode ) {
- // hrn0 may be "a_j" and/or "r_j" or even neither
- HeapRegionNode hrn0 = (HeapRegionNode) on;
-
- Iterator itr = pi2dr.entrySet().iterator();
- while( itr.hasNext() ) {
- Map.Entry mo = (Map.Entry)itr.next();
- Integer pi = (Integer) mo.getKey();
- Set<HeapRegionNode> dr_i = (Set<HeapRegionNode>)mo.getValue();
-
- if( dr_i.contains(hrn0) ) {
- addEdgeIndexPair(edges_p2s, pi, edge, index);
- edge_classified = true;
- }
- }
-
- itr = pi2r.entrySet().iterator();
- while( itr.hasNext() ) {
- Map.Entry mo = (Map.Entry)itr.next();
- Integer pi = (Integer) mo.getKey();
- Set<HeapRegionNode> r_i = (Set<HeapRegionNode>)mo.getValue();
-
- if( r_i.contains(hrn0) ) {
- addEdgeIndexPair(edges_s2s, pi, edge, index);
- edge_classified = true;
- }
- }
- }
-
- // these edges are all upstream of some reachable node
- if( !edge_classified ) {
- addEdgeIndexPair(edges_up_r, index, edge, index);
- }
- }
+ // this heap region is definitely an "r_i" or secondary by virtue of being in r
+ HeapRegionNode hrn = hrnItr.next();
+
+ if( paramIndex2rewriteH_s.containsKey(index) ) {
+
+ tokens2states.clear();
+ tokens2states.put(p_i, new ReachabilitySet().makeCanonical() );
+ tokens2states.put(s_i, hrn.getAlpha() );
+
+ rewriteCallerReachability(index,
+ hrn,
+ null,
+ paramIndex2rewriteH_s.get(index),
+ tokens2states,
+ paramIndex2rewrite_d_p,
+ paramIndex2rewrite_d_s,
+ paramIndex2rewriteD,
+ ogCallee,
+ false,
+ null);
+
+ nodesWithNewAlpha.add(hrn);
+ }
+
+ // sort edges
+ Iterator<ReferenceEdge> edgeItr = hrn.iteratorToReferencers();
+ while( edgeItr.hasNext() ) {
+ ReferenceEdge edge = edgeItr.next();
+ OwnershipNode on = edge.getSrc();
+
+ boolean edge_classified = false;
+
+ if( on instanceof HeapRegionNode ) {
+ // hrn0 may be "a_j" and/or "r_j" or even neither
+ HeapRegionNode hrn0 = (HeapRegionNode) on;
+
+ Iterator itr = pi2dr.entrySet().iterator();
+ while( itr.hasNext() ) {
+ Map.Entry mo = (Map.Entry)itr.next();
+ Integer pi = (Integer) mo.getKey();
+ Set<HeapRegionNode> dr_i = (Set<HeapRegionNode>)mo.getValue();
+
+ if( dr_i.contains(hrn0) ) {
+ addEdgeIndexPair(edges_p2s, pi, edge, index);
+ edge_classified = true;
+ }
+ }
+
+ itr = pi2r.entrySet().iterator();
+ while( itr.hasNext() ) {
+ Map.Entry mo = (Map.Entry)itr.next();
+ Integer pi = (Integer) mo.getKey();
+ Set<HeapRegionNode> r_i = (Set<HeapRegionNode>)mo.getValue();
+
+ if( r_i.contains(hrn0) ) {
+ addEdgeIndexPair(edges_s2s, pi, edge, index);
+ edge_classified = true;
+ }
+ }
+ }
+
+ // these edges are all upstream of some reachable node
+ if( !edge_classified ) {
+ addEdgeIndexPair(edges_up_r, index, edge, index);
+ }
+ }
}
}
// update reachable edges
Iterator edgeItr = edges_p2p.get(index).iterator();
while( edgeItr.hasNext() ) {
- Vector mo = (Vector) edgeItr.next();
- ReferenceEdge edge = (ReferenceEdge) mo.get(0);
- Integer indexJ = (Integer) mo.get(1);
-
- if( !paramIndex2rewriteJ_p2p.containsKey(makeMapKey(index,
- indexJ,
- edge.getField() ) ) ) {
- continue;
- }
-
- TokenTuple p_j = ogCallee.paramIndex2paramTokenPrimary.get(indexJ);
- assert p_j != null;
-
- tokens2states.clear();
- tokens2states.put(p_j, edge.getBeta() );
-
- rewriteCallerReachability(index,
- null,
- edge,
- paramIndex2rewriteJ_p2p.get(makeMapKey(index,
- indexJ,
- edge.getField() ) ),
- tokens2states,
- paramIndex2rewrite_d_p,
- paramIndex2rewrite_d_s,
- paramIndex2rewriteD,
- ogCallee,
- false,
- null);
-
- edgesWithNewBeta.add(edge);
+ Vector mo = (Vector) edgeItr.next();
+ ReferenceEdge edge = (ReferenceEdge) mo.get(0);
+ Integer indexJ = (Integer) mo.get(1);
+
+ if( !paramIndex2rewriteJ_p2p.containsKey(makeMapKey(index,
+ indexJ,
+ edge.getField() ) ) ) {
+ continue;
+ }
+
+ TokenTuple p_j = ogCallee.paramIndex2paramTokenPrimary.get(indexJ);
+ assert p_j != null;
+
+ tokens2states.clear();
+ tokens2states.put(p_j, edge.getBeta() );
+
+ rewriteCallerReachability(index,
+ null,
+ edge,
+ paramIndex2rewriteJ_p2p.get(makeMapKey(index,
+ indexJ,
+ edge.getField() ) ),
+ tokens2states,
+ paramIndex2rewrite_d_p,
+ paramIndex2rewrite_d_s,
+ paramIndex2rewriteD,
+ ogCallee,
+ false,
+ null);
+
+ edgesWithNewBeta.add(edge);
}
edgeItr = edges_p2s.get(index).iterator();
while( edgeItr.hasNext() ) {
- Vector mo = (Vector) edgeItr.next();
- ReferenceEdge edge = (ReferenceEdge) mo.get(0);
- Integer indexJ = (Integer) mo.get(1);
-
- if( !paramIndex2rewriteJ_p2s.containsKey(makeMapKey(index,
- edge.getField() ) ) ) {
- continue;
- }
-
- TokenTuple s_j = ogCallee.paramIndex2paramTokenSecondary.get(indexJ);
- assert s_j != null;
-
- tokens2states.clear();
- tokens2states.put(s_j, edge.getBeta() );
-
- rewriteCallerReachability(index,
- null,
- edge,
- paramIndex2rewriteJ_p2s.get(makeMapKey(index,
- edge.getField() ) ),
- tokens2states,
- paramIndex2rewrite_d_p,
- paramIndex2rewrite_d_s,
- paramIndex2rewriteD,
- ogCallee,
- false,
- null);
-
- edgesWithNewBeta.add(edge);
+ Vector mo = (Vector) edgeItr.next();
+ ReferenceEdge edge = (ReferenceEdge) mo.get(0);
+ Integer indexJ = (Integer) mo.get(1);
+
+ if( !paramIndex2rewriteJ_p2s.containsKey(makeMapKey(index,
+ edge.getField() ) ) ) {
+ continue;
+ }
+
+ TokenTuple s_j = ogCallee.paramIndex2paramTokenSecondary.get(indexJ);
+ assert s_j != null;
+
+ tokens2states.clear();
+ tokens2states.put(s_j, edge.getBeta() );
+
+ rewriteCallerReachability(index,
+ null,
+ edge,
+ paramIndex2rewriteJ_p2s.get(makeMapKey(index,
+ edge.getField() ) ),
+ tokens2states,
+ paramIndex2rewrite_d_p,
+ paramIndex2rewrite_d_s,
+ paramIndex2rewriteD,
+ ogCallee,
+ false,
+ null);
+
+ edgesWithNewBeta.add(edge);
}
edgeItr = edges_s2p.get(index).iterator();
while( edgeItr.hasNext() ) {
- Vector mo = (Vector) edgeItr.next();
- ReferenceEdge edge = (ReferenceEdge) mo.get(0);
- Integer indexJ = (Integer) mo.get(1);
-
- if( !paramIndex2rewriteJ_s2p.containsKey(index) ) {
- continue;
- }
-
- TokenTuple p_j = ogCallee.paramIndex2paramTokenPrimary.get(indexJ);
- assert p_j != null;
-
- tokens2states.clear();
- tokens2states.put(p_j, edge.getBeta() );
-
- rewriteCallerReachability(index,
- null,
- edge,
- paramIndex2rewriteJ_s2p.get(index),
- tokens2states,
- paramIndex2rewrite_d_p,
- paramIndex2rewrite_d_s,
- paramIndex2rewriteD,
- ogCallee,
- false,
- null);
-
- edgesWithNewBeta.add(edge);
+ Vector mo = (Vector) edgeItr.next();
+ ReferenceEdge edge = (ReferenceEdge) mo.get(0);
+ Integer indexJ = (Integer) mo.get(1);
+
+ if( !paramIndex2rewriteJ_s2p.containsKey(index) ) {
+ continue;
+ }
+
+ TokenTuple p_j = ogCallee.paramIndex2paramTokenPrimary.get(indexJ);
+ assert p_j != null;
+
+ tokens2states.clear();
+ tokens2states.put(p_j, edge.getBeta() );
+
+ rewriteCallerReachability(index,
+ null,
+ edge,
+ paramIndex2rewriteJ_s2p.get(index),
+ tokens2states,
+ paramIndex2rewrite_d_p,
+ paramIndex2rewrite_d_s,
+ paramIndex2rewriteD,
+ ogCallee,
+ false,
+ null);
+
+ edgesWithNewBeta.add(edge);
}
edgeItr = edges_s2s.get(index).iterator();
while( edgeItr.hasNext() ) {
- Vector mo = (Vector) edgeItr.next();
- ReferenceEdge edge = (ReferenceEdge) mo.get(0);
- Integer indexJ = (Integer) mo.get(1);
-
- if( !paramIndex2rewriteJ_s2s.containsKey(index) ) {
- continue;
- }
-
- TokenTuple s_j = ogCallee.paramIndex2paramTokenSecondary.get(indexJ);
- assert s_j != null;
-
- tokens2states.clear();
- tokens2states.put(s_j, edge.getBeta() );
-
- rewriteCallerReachability(index,
- null,
- edge,
- paramIndex2rewriteJ_s2s.get(index),
- tokens2states,
- paramIndex2rewrite_d_p,
- paramIndex2rewrite_d_s,
- paramIndex2rewriteD,
- ogCallee,
- false,
- null);
-
- edgesWithNewBeta.add(edge);
+ Vector mo = (Vector) edgeItr.next();
+ ReferenceEdge edge = (ReferenceEdge) mo.get(0);
+ Integer indexJ = (Integer) mo.get(1);
+
+ if( !paramIndex2rewriteJ_s2s.containsKey(index) ) {
+ continue;
+ }
+
+ TokenTuple s_j = ogCallee.paramIndex2paramTokenSecondary.get(indexJ);
+ assert s_j != null;
+
+ tokens2states.clear();
+ tokens2states.put(s_j, edge.getBeta() );
+
+ rewriteCallerReachability(index,
+ null,
+ edge,
+ paramIndex2rewriteJ_s2s.get(index),
+ tokens2states,
+ paramIndex2rewrite_d_p,
+ paramIndex2rewrite_d_s,
+ paramIndex2rewriteD,
+ ogCallee,
+ false,
+ null);
+
+ edgesWithNewBeta.add(edge);
}
edgeItr = edges_up_dr.get(index).iterator();
while( edgeItr.hasNext() ) {
- Vector mo = (Vector) edgeItr.next();
- ReferenceEdge edge = (ReferenceEdge) mo.get(0);
- Integer indexJ = (Integer) mo.get(1);
-
- edgesDirectlyUpstream.add(edge);
-
- TokenTuple p_j = ogCallee.paramIndex2paramTokenPrimary.get(indexJ);
- assert p_j != null;
-
- // start with K_p2 and p_j
- tokens2states.clear();
- tokens2states.put(p_j, edge.getBeta() );
-
- rewriteCallerReachability(index,
- null,
- edge,
- paramIndex2rewriteK_p2.get(index),
- tokens2states,
- paramIndex2rewrite_d_p,
- paramIndex2rewrite_d_s,
- paramIndex2rewriteD,
- ogCallee,
- true,
- edgeUpstreamPlannedChanges);
-
- // and add in s_j, if required, and do K_p
- TokenTuple s_j = ogCallee.paramIndex2paramTokenSecondary.get(indexJ);
- if( s_j != null ) {
- tokens2states.put(s_j, edge.getBeta() );
- }
-
- rewriteCallerReachability(index,
- null,
- edge,
- paramIndex2rewriteK_p.get(index),
- tokens2states,
- paramIndex2rewrite_d_p,
- paramIndex2rewrite_d_s,
- paramIndex2rewriteD,
- ogCallee,
- true,
- edgeUpstreamPlannedChanges);
-
- edgesWithNewBeta.add(edge);
+ Vector mo = (Vector) edgeItr.next();
+ ReferenceEdge edge = (ReferenceEdge) mo.get(0);
+ Integer indexJ = (Integer) mo.get(1);
+
+ edgesDirectlyUpstream.add(edge);
+
+ TokenTuple p_j = ogCallee.paramIndex2paramTokenPrimary.get(indexJ);
+ assert p_j != null;
+
+ // start with K_p2 and p_j
+ tokens2states.clear();
+ tokens2states.put(p_j, edge.getBeta() );
+
+ rewriteCallerReachability(index,
+ null,
+ edge,
+ paramIndex2rewriteK_p2.get(index),
+ tokens2states,
+ paramIndex2rewrite_d_p,
+ paramIndex2rewrite_d_s,
+ paramIndex2rewriteD,
+ ogCallee,
+ true,
+ edgeUpstreamPlannedChanges);
+
+ // and add in s_j, if required, and do K_p
+ TokenTuple s_j = ogCallee.paramIndex2paramTokenSecondary.get(indexJ);
+ if( s_j != null ) {
+ tokens2states.put(s_j, edge.getBeta() );
+ }
+
+ rewriteCallerReachability(index,
+ null,
+ edge,
+ paramIndex2rewriteK_p.get(index),
+ tokens2states,
+ paramIndex2rewrite_d_p,
+ paramIndex2rewrite_d_s,
+ paramIndex2rewriteD,
+ ogCallee,
+ true,
+ edgeUpstreamPlannedChanges);
+
+ edgesWithNewBeta.add(edge);
}
propagateTokensOverEdges(edgesDirectlyUpstream,
edgeItr = edges_up_r.get(index).iterator();
while( edgeItr.hasNext() ) {
- Vector mo = (Vector) edgeItr.next();
- ReferenceEdge edge = (ReferenceEdge) mo.get(0);
- Integer indexJ = (Integer) mo.get(1);
-
- if( !paramIndex2rewriteK_s.containsKey(index) ) {
- continue;
- }
-
- edgesUpstream.add(edge);
-
- TokenTuple p_j = ogCallee.paramIndex2paramTokenPrimary.get(indexJ);
- assert p_j != null;
-
- TokenTuple s_j = ogCallee.paramIndex2paramTokenSecondary.get(indexJ);
- assert s_j != null;
-
- tokens2states.clear();
- tokens2states.put(p_j, rsWttsEmpty);
- tokens2states.put(s_j, edge.getBeta() );
-
- rewriteCallerReachability(index,
- null,
- edge,
- paramIndex2rewriteK_s.get(index),
- tokens2states,
- paramIndex2rewrite_d_p,
- paramIndex2rewrite_d_s,
- paramIndex2rewriteD,
- ogCallee,
- true,
- edgeUpstreamPlannedChanges);
-
- edgesWithNewBeta.add(edge);
+ Vector mo = (Vector) edgeItr.next();
+ ReferenceEdge edge = (ReferenceEdge) mo.get(0);
+ Integer indexJ = (Integer) mo.get(1);
+
+ if( !paramIndex2rewriteK_s.containsKey(index) ) {
+ continue;
+ }
+
+ edgesUpstream.add(edge);
+
+ TokenTuple p_j = ogCallee.paramIndex2paramTokenPrimary.get(indexJ);
+ assert p_j != null;
+
+ TokenTuple s_j = ogCallee.paramIndex2paramTokenSecondary.get(indexJ);
+ assert s_j != null;
+
+ tokens2states.clear();
+ tokens2states.put(p_j, rsWttsEmpty);
+ tokens2states.put(s_j, edge.getBeta() );
+
+ rewriteCallerReachability(index,
+ null,
+ edge,
+ paramIndex2rewriteK_s.get(index),
+ tokens2states,
+ paramIndex2rewrite_d_p,
+ paramIndex2rewrite_d_s,
+ paramIndex2rewriteD,
+ ogCallee,
+ true,
+ edgeUpstreamPlannedChanges);
+
+ edgesWithNewBeta.add(edge);
}
propagateTokensOverEdges(edgesUpstream,
for( int i = 0; i < allocSite.getAllocationDepth(); ++i ) {
- Integer idIth = allocSite.getIthOldest(i);
- assert id2hrn.containsKey(idIth);
- HeapRegionNode hrnIth = id2hrn.get(idIth);
-
- Integer idShadowIth = -(allocSite.getIthOldest(i));
- assert id2hrn.containsKey(idShadowIth);
- HeapRegionNode hrnIthShadow = id2hrn.get(idShadowIth);
- assert hrnIthShadow.getNumReferencers() == 0;
- assert hrnIthShadow.getNumReferencees() == 0;
-
- assert ogCallee.id2hrn.containsKey(idIth);
- HeapRegionNode hrnIthCallee = ogCallee.id2hrn.get(idIth);
- hrnIthShadow.setAlpha(toShadowTokens(ogCallee, hrnIthCallee.getAlpha() ) );
-
- rewriteCallerReachability(bogusIndex,
- hrnIthShadow,
- null,
- funcScriptR(hrnIthShadow.getAlpha(), ogCallee, mc),
- tokens2statesEmpty,
- paramIndex2rewrite_d_p,
- paramIndex2rewrite_d_s,
- paramIndex2rewriteD,
- ogCallee,
- false,
- null);
-
- hrnIthShadow.applyAlphaNew();
+ Integer idIth = allocSite.getIthOldest(i);
+ assert id2hrn.containsKey(idIth);
+ HeapRegionNode hrnIth = id2hrn.get(idIth);
+
+ Integer idShadowIth = -(allocSite.getIthOldest(i));
+ assert id2hrn.containsKey(idShadowIth);
+ HeapRegionNode hrnIthShadow = id2hrn.get(idShadowIth);
+ assert hrnIthShadow.getNumReferencers() == 0;
+ assert hrnIthShadow.getNumReferencees() == 0;
+
+ assert ogCallee.id2hrn.containsKey(idIth);
+ HeapRegionNode hrnIthCallee = ogCallee.id2hrn.get(idIth);
+ hrnIthShadow.setAlpha(toShadowTokens(ogCallee, hrnIthCallee.getAlpha() ) );
+
+ rewriteCallerReachability(bogusIndex,
+ hrnIthShadow,
+ null,
+ funcScriptR(hrnIthShadow.getAlpha(), ogCallee, mc),
+ tokens2statesEmpty,
+ paramIndex2rewrite_d_p,
+ paramIndex2rewrite_d_s,
+ paramIndex2rewriteD,
+ ogCallee,
+ false,
+ null);
+
+ hrnIthShadow.applyAlphaNew();
}
}
Iterator<ReferenceEdge> heapRegionsItrCallee = hrnCallee.iteratorToReferencees();
while( heapRegionsItrCallee.hasNext() ) {
- ReferenceEdge edgeCallee = heapRegionsItrCallee.next();
- HeapRegionNode hrnChildCallee = edgeCallee.getDst();
- Integer idChildCallee = hrnChildCallee.getID();
-
- // only address this edge if it is not a special initial edge
- if( !edgeCallee.isInitialParam() ) {
-
- // now we know that in the callee method's ownership graph
- // there is a heap region->heap region reference edge given
- // by heap region pointers:
- // hrnCallee -> heapChildCallee
- //
- // or by the ownership-graph independent ID's:
- // idCallee -> idChildCallee
-
- // make the edge with src and dst so beta info is
- // calculated once, then copy it for each new edge in caller
-
- ReferenceEdge edgeNewInCallerTemplate = new ReferenceEdge(null,
- null,
- edgeCallee.getType(),
- edgeCallee.getField(),
- false,
- funcScriptR(toShadowTokens(ogCallee,
- edgeCallee.getBeta()
- ),
- ogCallee,
- mc)
- );
-
- rewriteCallerReachability(bogusIndex,
- null,
- edgeNewInCallerTemplate,
- edgeNewInCallerTemplate.getBeta(),
- tokens2statesEmpty,
- paramIndex2rewrite_d_p,
- paramIndex2rewrite_d_s,
- paramIndex2rewriteD,
- ogCallee,
- false,
- null);
-
- edgeNewInCallerTemplate.applyBetaNew();
-
-
- // So now make a set of possible source heaps in the caller graph
- // and a set of destination heaps in the caller graph, and make
- // a reference edge in the caller for every possible (src,dst) pair
- HashSet<HeapRegionNode> possibleCallerSrcs =
- getHRNSetThatPossiblyMapToCalleeHRN(ogCallee,
- (HeapRegionNode) edgeCallee.getSrc(),
- pi2dr,
- pi2r);
-
- HashSet<HeapRegionNode> possibleCallerDsts =
- getHRNSetThatPossiblyMapToCalleeHRN(ogCallee,
- edgeCallee.getDst(),
- pi2dr,
- pi2r);
-
- // make every possible pair of {srcSet} -> {dstSet} edges in the caller
- Iterator srcItr = possibleCallerSrcs.iterator();
- while( srcItr.hasNext() ) {
- HeapRegionNode src = (HeapRegionNode) srcItr.next();
-
- if( !hasMatchingField(src, edgeCallee) ) {
- // prune this source node possibility
- continue;
- }
-
- Iterator dstItr = possibleCallerDsts.iterator();
- while( dstItr.hasNext() ) {
- HeapRegionNode dst = (HeapRegionNode) dstItr.next();
-
- if( !hasMatchingType(edgeCallee, dst) ) {
- // prune
- continue;
- }
-
-
- /*
- //// KEEP THIS HACK AROUND FOR EXPERIMENTING WITH EDGE REMOVAL
- TypeDescriptor tdX = src.getType();
- TypeDescriptor tdY = dst.getType();
- if( tdX != null && tdY != null ) {
- if( tdX.toPrettyString().equals( "Object[]" ) &&
- tdY.toPrettyString().equals( "D2" ) ) {
- System.out.println( "Skipping an edge from Object[] -> D2 during call mapping" );
- continue;
- }
- if( tdX.toPrettyString().equals( "Object[]" ) &&
- tdY.toPrettyString().equals( "MessageList" ) ) {
- System.out.println( "Skipping an edge from Object[] -> MessageList during call mapping" );
- continue;
- }
- }
- */
-
-
- // otherwise the caller src and dst pair can match the edge, so make it
- TypeDescriptor tdNewEdge =
- mostSpecificType(edgeCallee.getType(),
- hrnChildCallee.getType(),
- dst.getType()
- );
-
- ReferenceEdge edgeNewInCaller = edgeNewInCallerTemplate.copy();
- edgeNewInCaller.setSrc(src);
- edgeNewInCaller.setDst(dst);
- edgeNewInCaller.setType(tdNewEdge);
-
-
- // handle taint info if callee created this edge
- // added by eom
- Set<Integer> pParamSet=idPrimary2paramIndexSet.get(dst.getID());
- Set<Integer> sParamSet=idSecondary2paramIndexSet.get(dst.getID());
- HashSet<Integer> paramSet=new HashSet<Integer>();
- if(pParamSet!=null) {
- paramSet.addAll(pParamSet);
- }
- if(sParamSet!=null) {
- paramSet.addAll(sParamSet);
- }
- Iterator<Integer> paramIter=paramSet.iterator();
- int newTaintIdentifier=0;
- while(paramIter.hasNext()) {
- Integer paramIdx=paramIter.next();
- edgeNewInCaller.tainedBy(paramIdx);
- }
-
- ReferenceEdge edgeExisting = src.getReferenceTo(dst,
- edgeNewInCaller.getType(),
- edgeNewInCaller.getField() );
- if( edgeExisting == null ) {
- // if this edge doesn't exist in the caller, create it
- addReferenceEdge(src, dst, edgeNewInCaller);
-
- } else {
- // if it already exists, merge with it
- edgeExisting.setBeta(edgeExisting.getBeta().union(edgeNewInCaller.getBeta() ) );
- }
- }
- }
- }
+ ReferenceEdge edgeCallee = heapRegionsItrCallee.next();
+ HeapRegionNode hrnChildCallee = edgeCallee.getDst();
+ Integer idChildCallee = hrnChildCallee.getID();
+
+ // only address this edge if it is not a special initial edge
+ if( !edgeCallee.isInitialParam() ) {
+
+ // now we know that in the callee method's ownership graph
+ // there is a heap region->heap region reference edge given
+ // by heap region pointers:
+ // hrnCallee -> heapChildCallee
+ //
+ // or by the ownership-graph independent ID's:
+ // idCallee -> idChildCallee
+
+ // make the edge with src and dst so beta info is
+ // calculated once, then copy it for each new edge in caller
+
+ ReferenceEdge edgeNewInCallerTemplate = new ReferenceEdge(null,
+ null,
+ edgeCallee.getType(),
+ edgeCallee.getField(),
+ false,
+ funcScriptR(toShadowTokens(ogCallee,
+ edgeCallee.getBeta()
+ ),
+ ogCallee,
+ mc)
+ );
+
+ rewriteCallerReachability(bogusIndex,
+ null,
+ edgeNewInCallerTemplate,
+ edgeNewInCallerTemplate.getBeta(),
+ tokens2statesEmpty,
+ paramIndex2rewrite_d_p,
+ paramIndex2rewrite_d_s,
+ paramIndex2rewriteD,
+ ogCallee,
+ false,
+ null);
+
+ edgeNewInCallerTemplate.applyBetaNew();
+
+
+ // So now make a set of possible source heaps in the caller graph
+ // and a set of destination heaps in the caller graph, and make
+ // a reference edge in the caller for every possible (src,dst) pair
+ HashSet<HeapRegionNode> possibleCallerSrcs =
+ getHRNSetThatPossiblyMapToCalleeHRN(ogCallee,
+ (HeapRegionNode) edgeCallee.getSrc(),
+ pi2dr,
+ pi2r);
+
+ HashSet<HeapRegionNode> possibleCallerDsts =
+ getHRNSetThatPossiblyMapToCalleeHRN(ogCallee,
+ edgeCallee.getDst(),
+ pi2dr,
+ pi2r);
+
+ // make every possible pair of {srcSet} -> {dstSet} edges in the caller
+ Iterator srcItr = possibleCallerSrcs.iterator();
+ while( srcItr.hasNext() ) {
+ HeapRegionNode src = (HeapRegionNode) srcItr.next();
+
+ if( !hasMatchingField(src, edgeCallee) ) {
+ // prune this source node possibility
+ continue;
+ }
+
+ Iterator dstItr = possibleCallerDsts.iterator();
+ while( dstItr.hasNext() ) {
+ HeapRegionNode dst = (HeapRegionNode) dstItr.next();
+
+ if( !hasMatchingType(edgeCallee, dst) ) {
+ // prune
+ continue;
+ }
+
+
+ /*
+ //// KEEP THIS HACK AROUND FOR EXPERIMENTING WITH EDGE REMOVAL
+ TypeDescriptor tdX = src.getType();
+ TypeDescriptor tdY = dst.getType();
+ if( tdX != null && tdY != null ) {
+ if( tdX.toPrettyString().equals( "Object[]" ) &&
+ tdY.toPrettyString().equals( "D2" ) ) {
+ System.out.println( "Skipping an edge from Object[] -> D2 during call mapping" );
+ continue;
+ }
+ if( tdX.toPrettyString().equals( "Object[]" ) &&
+ tdY.toPrettyString().equals( "MessageList" ) ) {
+ System.out.println( "Skipping an edge from Object[] -> MessageList during call mapping" );
+ continue;
+ }
+ }
+ */
+
+
+ // otherwise the caller src and dst pair can match the edge, so make it
+ TypeDescriptor tdNewEdge =
+ mostSpecificType(edgeCallee.getType(),
+ hrnChildCallee.getType(),
+ dst.getType()
+ );
+
+ ReferenceEdge edgeNewInCaller = edgeNewInCallerTemplate.copy();
+ edgeNewInCaller.setSrc(src);
+ edgeNewInCaller.setDst(dst);
+ edgeNewInCaller.setType(tdNewEdge);
+
+
+ // handle taint info if callee created this edge
+ // added by eom
+ Set<Integer> pParamSet=idPrimary2paramIndexSet.get(dst.getID());
+ Set<Integer> sParamSet=idSecondary2paramIndexSet.get(dst.getID());
+ HashSet<Integer> paramSet=new HashSet<Integer>();
+ if(pParamSet!=null) {
+ paramSet.addAll(pParamSet);
+ }
+ if(sParamSet!=null) {
+ paramSet.addAll(sParamSet);
+ }
+ Iterator<Integer> paramIter=paramSet.iterator();
+ int newTaintIdentifier=0;
+ while(paramIter.hasNext()) {
+ Integer paramIdx=paramIter.next();
+ edgeNewInCaller.tainedBy(paramIdx);
+ }
+
+ ReferenceEdge edgeExisting = src.getReferenceTo(dst,
+ edgeNewInCaller.getType(),
+ edgeNewInCaller.getField() );
+ if( edgeExisting == null ) {
+ // if this edge doesn't exist in the caller, create it
+ addReferenceEdge(src, dst, edgeNewInCaller);
+
+ } else {
+ // if it already exists, merge with it
+ edgeExisting.setBeta(edgeExisting.getBeta().union(edgeNewInCaller.getBeta() ) );
+ }
+ }
+ }
+ }
}
}
LabelNode lnReturnCallee = ogCallee.getLabelNodeFromTemp(tdReturn);
Iterator<ReferenceEdge> edgeCalleeItr = lnReturnCallee.iteratorToReferencees();
while( edgeCalleeItr.hasNext() ) {
- ReferenceEdge edgeCallee = edgeCalleeItr.next();
- HeapRegionNode hrnChildCallee = edgeCallee.getDst();
-
- // some edge types are not possible return values when we can
- // see what type variable we are assigning it to
- if( !isSuperiorType(returnTemp.getType(), edgeCallee.getType() ) ) {
- System.out.println("*** NOT EXPECTING TO SEE THIS: Throwing out "+edgeCallee+" for return temp "+returnTemp);
- // prune
- continue;
- }
-
- ReferenceEdge edgeNewInCallerTemplate = new ReferenceEdge(null,
- null,
- edgeCallee.getType(),
- edgeCallee.getField(),
- false,
- funcScriptR(toShadowTokens(ogCallee,
- edgeCallee.getBeta() ),
- ogCallee,
- mc)
- );
- rewriteCallerReachability(bogusIndex,
- null,
- edgeNewInCallerTemplate,
- edgeNewInCallerTemplate.getBeta(),
- tokens2statesEmpty,
- paramIndex2rewrite_d_p,
- paramIndex2rewrite_d_s,
- paramIndex2rewriteD,
- ogCallee,
- false,
- null);
-
- edgeNewInCallerTemplate.applyBetaNew();
-
-
- HashSet<HeapRegionNode> assignCallerRhs =
- getHRNSetThatPossiblyMapToCalleeHRN(ogCallee,
- edgeCallee.getDst(),
- pi2dr,
- pi2r);
-
- Iterator<HeapRegionNode> itrHrn = assignCallerRhs.iterator();
- while( itrHrn.hasNext() ) {
- HeapRegionNode hrnCaller = itrHrn.next();
-
- // don't make edge in caller if it is disallowed by types
- if( !isSuperiorType(returnTemp.getType(), hrnCaller.getType() ) ) {
- // prune
- continue;
- }
-
- if( !isSuperiorType(returnTemp.getType(), hrnChildCallee.getType() ) ) {
- // prune
- continue;
- }
-
- if( !isSuperiorType(edgeCallee.getType(), hrnCaller.getType() ) ) {
- // prune
- continue;
- }
-
- TypeDescriptor tdNewEdge =
- mostSpecificType(edgeCallee.getType(),
- hrnChildCallee.getType(),
- hrnCaller.getType()
- );
-
- // otherwise caller node can match callee edge, so make it
- ReferenceEdge edgeNewInCaller = edgeNewInCallerTemplate.copy();
- edgeNewInCaller.setSrc(lnLhsCaller);
- edgeNewInCaller.setDst(hrnCaller);
- edgeNewInCaller.setType(tdNewEdge);
-
- ReferenceEdge edgeExisting = lnLhsCaller.getReferenceTo(hrnCaller,
- tdNewEdge,
- edgeNewInCaller.getField() );
- if( edgeExisting == null ) {
-
- // if this edge doesn't exist in the caller, create it
- addReferenceEdge(lnLhsCaller, hrnCaller, edgeNewInCaller);
- } else {
- // if it already exists, merge with it
- edgeExisting.setBeta(edgeExisting.getBeta().union(edgeNewInCaller.getBeta() ) );
- }
- }
+ ReferenceEdge edgeCallee = edgeCalleeItr.next();
+ HeapRegionNode hrnChildCallee = edgeCallee.getDst();
+
+ // some edge types are not possible return values when we can
+ // see what type variable we are assigning it to
+ if( !isSuperiorType(returnTemp.getType(), edgeCallee.getType() ) ) {
+ System.out.println("*** NOT EXPECTING TO SEE THIS: Throwing out "+edgeCallee+" for return temp "+returnTemp);
+ // prune
+ continue;
+ }
+
+ ReferenceEdge edgeNewInCallerTemplate = new ReferenceEdge(null,
+ null,
+ edgeCallee.getType(),
+ edgeCallee.getField(),
+ false,
+ funcScriptR(toShadowTokens(ogCallee,
+ edgeCallee.getBeta() ),
+ ogCallee,
+ mc)
+ );
+ rewriteCallerReachability(bogusIndex,
+ null,
+ edgeNewInCallerTemplate,
+ edgeNewInCallerTemplate.getBeta(),
+ tokens2statesEmpty,
+ paramIndex2rewrite_d_p,
+ paramIndex2rewrite_d_s,
+ paramIndex2rewriteD,
+ ogCallee,
+ false,
+ null);
+
+ edgeNewInCallerTemplate.applyBetaNew();
+
+
+ HashSet<HeapRegionNode> assignCallerRhs =
+ getHRNSetThatPossiblyMapToCalleeHRN(ogCallee,
+ edgeCallee.getDst(),
+ pi2dr,
+ pi2r);
+
+ Iterator<HeapRegionNode> itrHrn = assignCallerRhs.iterator();
+ while( itrHrn.hasNext() ) {
+ HeapRegionNode hrnCaller = itrHrn.next();
+
+ // don't make edge in caller if it is disallowed by types
+ if( !isSuperiorType(returnTemp.getType(), hrnCaller.getType() ) ) {
+ // prune
+ continue;
+ }
+
+ if( !isSuperiorType(returnTemp.getType(), hrnChildCallee.getType() ) ) {
+ // prune
+ continue;
+ }
+
+ if( !isSuperiorType(edgeCallee.getType(), hrnCaller.getType() ) ) {
+ // prune
+ continue;
+ }
+
+ TypeDescriptor tdNewEdge =
+ mostSpecificType(edgeCallee.getType(),
+ hrnChildCallee.getType(),
+ hrnCaller.getType()
+ );
+
+ // otherwise caller node can match callee edge, so make it
+ ReferenceEdge edgeNewInCaller = edgeNewInCallerTemplate.copy();
+ edgeNewInCaller.setSrc(lnLhsCaller);
+ edgeNewInCaller.setDst(hrnCaller);
+ edgeNewInCaller.setType(tdNewEdge);
+
+ ReferenceEdge edgeExisting = lnLhsCaller.getReferenceTo(hrnCaller,
+ tdNewEdge,
+ edgeNewInCaller.getField() );
+ if( edgeExisting == null ) {
+
+ // if this edge doesn't exist in the caller, create it
+ addReferenceEdge(lnLhsCaller, hrnCaller, edgeNewInCaller);
+ } else {
+ // if it already exists, merge with it
+ edgeExisting.setBeta(edgeExisting.getBeta().union(edgeNewInCaller.getBeta() ) );
+ }
+ }
}
}
// first age each allocation site enough times to make room for the shadow nodes
for( int i = 0; i < as.getAllocationDepth(); ++i ) {
- age(as);
+ age(as);
}
// then merge the shadow summary into the normal summary
// then transplant shadow nodes onto the now clean normal nodes
for( int i = 0; i < as.getAllocationDepth(); ++i ) {
- Integer idIth = as.getIthOldest(i);
- HeapRegionNode hrnIth = id2hrn.get(idIth);
- Integer idIthShadow = as.getIthOldestShadow(i);
- HeapRegionNode hrnIthShadow = id2hrn.get(idIthShadow);
+ Integer idIth = as.getIthOldest(i);
+ HeapRegionNode hrnIth = id2hrn.get(idIth);
+ Integer idIthShadow = as.getIthOldestShadow(i);
+ HeapRegionNode hrnIthShadow = id2hrn.get(idIthShadow);
- transferOnto(hrnIthShadow, hrnIth);
+ transferOnto(hrnIthShadow, hrnIth);
- // clear off shadow nodes after transfer
- clearReferenceEdgesFrom(hrnIthShadow, null, null, true);
- clearReferenceEdgesTo(hrnIthShadow, null, null, true);
- hrnIthShadow.setAlpha(new ReachabilitySet().makeCanonical() );
+ // clear off shadow nodes after transfer
+ clearReferenceEdgesFrom(hrnIthShadow, null, null, true);
+ clearReferenceEdgesTo(hrnIthShadow, null, null, true);
+ hrnIthShadow.setAlpha(new ReachabilitySet().makeCanonical() );
}
// finally, globally change shadow tokens into normal tokens
Iterator itrAllLabelNodes = td2ln.entrySet().iterator();
while( itrAllLabelNodes.hasNext() ) {
- Map.Entry me = (Map.Entry)itrAllLabelNodes.next();
- LabelNode ln = (LabelNode) me.getValue();
+ Map.Entry me = (Map.Entry)itrAllLabelNodes.next();
+ LabelNode ln = (LabelNode) me.getValue();
- Iterator<ReferenceEdge> itrEdges = ln.iteratorToReferencees();
- while( itrEdges.hasNext() ) {
- unshadowTokens(as, itrEdges.next() );
- }
+ Iterator<ReferenceEdge> itrEdges = ln.iteratorToReferencees();
+ while( itrEdges.hasNext() ) {
+ unshadowTokens(as, itrEdges.next() );
+ }
}
Iterator itrAllHRNodes = id2hrn.entrySet().iterator();
while( itrAllHRNodes.hasNext() ) {
- Map.Entry me = (Map.Entry)itrAllHRNodes.next();
- HeapRegionNode hrnToAge = (HeapRegionNode) me.getValue();
+ Map.Entry me = (Map.Entry)itrAllHRNodes.next();
+ HeapRegionNode hrnToAge = (HeapRegionNode) me.getValue();
- unshadowTokens(as, hrnToAge);
+ unshadowTokens(as, hrnToAge);
- Iterator<ReferenceEdge> itrEdges = hrnToAge.iteratorToReferencees();
- while( itrEdges.hasNext() ) {
- unshadowTokens(as, itrEdges.next() );
- }
+ Iterator<ReferenceEdge> itrEdges = hrnToAge.iteratorToReferencees();
+ while( itrEdges.hasNext() ) {
+ unshadowTokens(as, itrEdges.next() );
+ }
}
}
) {
try {
- writeGraph("debug9endResolveCall",
- true, // write labels (variables)
- true, // selectively hide intermediate temp vars
- true, // prune unreachable heap regions
- false, // show back edges to confirm graph validity
- false, // show parameter indices (unmaintained!)
- true, // hide subset reachability states
- true); // hide edge taints
+ writeGraph("debug9endResolveCall",
+ true, // write labels (variables)
+ true, // selectively hide intermediate temp vars
+ true, // prune unreachable heap regions
+ false, // show back edges to confirm graph validity
+ false, // show parameter indices (unmaintained!)
+ true, // hide subset reachability states
+ true); // hide edge taints
} catch( IOException e ) {
}
System.out.println(" "+mc+" done calling "+fm);
++x;
if( x == debugCallMapCount ) {
- System.exit(0);
+ System.exit(0);
}
}
}
assert tdSrcDeref != null;
if( !typeUtil.isSuperorType(tdSrcDeref, td) ) {
- return false;
+ return false;
}
return edge.getField().equals(OwnershipAnalysis.arrayElementFieldName);
Iterator fieldItr = cd.getFields();
while( fieldItr.hasNext() ) {
- FieldDescriptor fd = (FieldDescriptor) fieldItr.next();
+ FieldDescriptor fd = (FieldDescriptor) fieldItr.next();
- if( fd.getType().equals(edge.getType() ) &&
- fd.getSymbol().equals(edge.getField() ) ) {
- return true;
- }
+ if( fd.getType().equals(edge.getType() ) &&
+ fd.getSymbol().equals(edge.getField() ) ) {
+ return true;
+ }
}
cd = cd.getSuperDesc();
Iterator<TokenTuple> ruleItr = rule.iterator();
while(ruleItr.hasNext()) {
- TokenTuple ttCallee = ruleItr.next();
-
- // compute the possibilities for rewriting this callee token
- ReachabilitySet ttCalleeRewrites = null;
- boolean callerSourceUsed = false;
-
- if( tokens2states.containsKey(ttCallee) ) {
- callerSourceUsed = true;
- ttCalleeRewrites = tokens2states.get(ttCallee);
- assert ttCalleeRewrites != null;
-
- } else if( ogCallee.paramTokenPrimary2paramIndex.containsKey(ttCallee) ) {
- // use little d_p
- Integer paramIndex_j = ogCallee.paramTokenPrimary2paramIndex.get(ttCallee);
- assert paramIndex_j != null;
- ttCalleeRewrites = paramIndex2rewrite_d_p.get(paramIndex_j);
- assert ttCalleeRewrites != null;
-
- } else if( ogCallee.paramTokenSecondary2paramIndex.containsKey(ttCallee) ) {
- // use little d_s
- Integer paramIndex_j = ogCallee.paramTokenSecondary2paramIndex.get(ttCallee);
- assert paramIndex_j != null;
- ttCalleeRewrites = paramIndex2rewrite_d_s.get(paramIndex_j);
- assert ttCalleeRewrites != null;
-
- } else if( ogCallee.paramTokenSecondaryPlus2paramIndex.containsKey(ttCallee) ) {
- // worse, use big D
- Integer paramIndex_j = ogCallee.paramTokenSecondaryPlus2paramIndex.get(ttCallee);
- assert paramIndex_j != null;
- ttCalleeRewrites = paramIndex2rewriteD.get(paramIndex_j);
- assert ttCalleeRewrites != null;
-
- } else if( ogCallee.paramTokenSecondaryStar2paramIndex.containsKey(ttCallee) ) {
- // worse, use big D
- Integer paramIndex_j = ogCallee.paramTokenSecondaryStar2paramIndex.get(ttCallee);
- assert paramIndex_j != null;
- ttCalleeRewrites = paramIndex2rewriteD.get(paramIndex_j);
- assert ttCalleeRewrites != null;
-
- } else {
- // otherwise there's no need for a rewrite, just pass this one on
- TokenTupleSet ttsCaller = new TokenTupleSet(ttCallee).makeCanonical();
- ttCalleeRewrites = new ReachabilitySet(ttsCaller).makeCanonical();
- }
-
- // branch every version of the working rewritten rule with
- // the possibilities for rewriting the current callee token
- ReachabilitySet rewrittenRuleWithTTCallee = new ReachabilitySet().makeCanonical();
-
- Iterator<TokenTupleSet> rewrittenRuleItr = rewrittenRule.iterator();
- while( rewrittenRuleItr.hasNext() ) {
- TokenTupleSet ttsRewritten = rewrittenRuleItr.next();
-
- Iterator<TokenTupleSet> ttCalleeRewritesItr = ttCalleeRewrites.iterator();
- while( ttCalleeRewritesItr.hasNext() ) {
- TokenTupleSet ttsBranch = ttCalleeRewritesItr.next();
-
- TokenTupleSet ttsRewrittenNext = ttsRewritten.unionUpArity(ttsBranch);
-
- if( makeChangeSet ) {
- // in order to keep the list of source token tuple sets
- // start with the sets used to make the partially rewritten
- // rule up to this point
- HashSet<TokenTupleSet> sourceSets = rewritten2source.get(ttsRewritten);
- assert sourceSets != null;
-
- // make a shallow copy for possible modification
- sourceSets = (HashSet<TokenTupleSet>)sourceSets.clone();
-
- // if we used something from the caller to rewrite it, remember
- if( callerSourceUsed ) {
- sourceSets.add(ttsBranch);
- }
-
- // set mapping for the further rewritten rule
- rewritten2source.put(ttsRewrittenNext, sourceSets);
- }
-
- rewrittenRuleWithTTCallee =
- rewrittenRuleWithTTCallee.union(ttsRewrittenNext);
- }
- }
-
- // now the rewritten rule's possibilities have been extended by
- // rewriting the current callee token, remember result
- rewrittenRule = rewrittenRuleWithTTCallee;
+ TokenTuple ttCallee = ruleItr.next();
+
+ // compute the possibilities for rewriting this callee token
+ ReachabilitySet ttCalleeRewrites = null;
+ boolean callerSourceUsed = false;
+
+ if( tokens2states.containsKey(ttCallee) ) {
+ callerSourceUsed = true;
+ ttCalleeRewrites = tokens2states.get(ttCallee);
+ assert ttCalleeRewrites != null;
+
+ } else if( ogCallee.paramTokenPrimary2paramIndex.containsKey(ttCallee) ) {
+ // use little d_p
+ Integer paramIndex_j = ogCallee.paramTokenPrimary2paramIndex.get(ttCallee);
+ assert paramIndex_j != null;
+ ttCalleeRewrites = paramIndex2rewrite_d_p.get(paramIndex_j);
+ assert ttCalleeRewrites != null;
+
+ } else if( ogCallee.paramTokenSecondary2paramIndex.containsKey(ttCallee) ) {
+ // use little d_s
+ Integer paramIndex_j = ogCallee.paramTokenSecondary2paramIndex.get(ttCallee);
+ assert paramIndex_j != null;
+ ttCalleeRewrites = paramIndex2rewrite_d_s.get(paramIndex_j);
+ assert ttCalleeRewrites != null;
+
+ } else if( ogCallee.paramTokenSecondaryPlus2paramIndex.containsKey(ttCallee) ) {
+ // worse, use big D
+ Integer paramIndex_j = ogCallee.paramTokenSecondaryPlus2paramIndex.get(ttCallee);
+ assert paramIndex_j != null;
+ ttCalleeRewrites = paramIndex2rewriteD.get(paramIndex_j);
+ assert ttCalleeRewrites != null;
+
+ } else if( ogCallee.paramTokenSecondaryStar2paramIndex.containsKey(ttCallee) ) {
+ // worse, use big D
+ Integer paramIndex_j = ogCallee.paramTokenSecondaryStar2paramIndex.get(ttCallee);
+ assert paramIndex_j != null;
+ ttCalleeRewrites = paramIndex2rewriteD.get(paramIndex_j);
+ assert ttCalleeRewrites != null;
+
+ } else {
+ // otherwise there's no need for a rewrite, just pass this one on
+ TokenTupleSet ttsCaller = new TokenTupleSet(ttCallee).makeCanonical();
+ ttCalleeRewrites = new ReachabilitySet(ttsCaller).makeCanonical();
+ }
+
+ // branch every version of the working rewritten rule with
+ // the possibilities for rewriting the current callee token
+ ReachabilitySet rewrittenRuleWithTTCallee = new ReachabilitySet().makeCanonical();
+
+ Iterator<TokenTupleSet> rewrittenRuleItr = rewrittenRule.iterator();
+ while( rewrittenRuleItr.hasNext() ) {
+ TokenTupleSet ttsRewritten = rewrittenRuleItr.next();
+
+ Iterator<TokenTupleSet> ttCalleeRewritesItr = ttCalleeRewrites.iterator();
+ while( ttCalleeRewritesItr.hasNext() ) {
+ TokenTupleSet ttsBranch = ttCalleeRewritesItr.next();
+
+ TokenTupleSet ttsRewrittenNext = ttsRewritten.unionUpArity(ttsBranch);
+
+ if( makeChangeSet ) {
+ // in order to keep the list of source token tuple sets
+ // start with the sets used to make the partially rewritten
+ // rule up to this point
+ HashSet<TokenTupleSet> sourceSets = rewritten2source.get(ttsRewritten);
+ assert sourceSets != null;
+
+ // make a shallow copy for possible modification
+ sourceSets = (HashSet<TokenTupleSet>)sourceSets.clone();
+
+ // if we used something from the caller to rewrite it, remember
+ if( callerSourceUsed ) {
+ sourceSets.add(ttsBranch);
+ }
+
+ // set mapping for the further rewritten rule
+ rewritten2source.put(ttsRewrittenNext, sourceSets);
+ }
+
+ rewrittenRuleWithTTCallee =
+ rewrittenRuleWithTTCallee.union(ttsRewrittenNext);
+ }
+ }
+
+ // now the rewritten rule's possibilities have been extended by
+ // rewriting the current callee token, remember result
+ rewrittenRule = rewrittenRuleWithTTCallee;
}
// the rule has been entirely rewritten into the caller context
// caller sources mapped to it, use to create the change set
Iterator<TokenTupleSet> callerReachabilityItr = callerReachabilityNew.iterator();
while( callerReachabilityItr.hasNext() ) {
- TokenTupleSet ttsRewrittenFinal = callerReachabilityItr.next();
- HashSet<TokenTupleSet> sourceSets = rewritten2source.get(ttsRewrittenFinal);
- assert sourceSets != null;
+ TokenTupleSet ttsRewrittenFinal = callerReachabilityItr.next();
+ HashSet<TokenTupleSet> sourceSets = rewritten2source.get(ttsRewrittenFinal);
+ assert sourceSets != null;
- Iterator<TokenTupleSet> sourceSetsItr = sourceSets.iterator();
- while( sourceSetsItr.hasNext() ) {
- TokenTupleSet ttsSource = sourceSetsItr.next();
+ Iterator<TokenTupleSet> sourceSetsItr = sourceSets.iterator();
+ while( sourceSetsItr.hasNext() ) {
+ TokenTupleSet ttsSource = sourceSetsItr.next();
- callerChangeSet =
- callerChangeSet.union(new ChangeTuple(ttsSource, ttsRewrittenFinal) );
- }
+ callerChangeSet =
+ callerChangeSet.union(new ChangeTuple(ttsSource, ttsRewrittenFinal) );
+ }
}
assert edgePlannedChanges != null;
Integer idCaller;
if( age == AllocationSite.AGE_summary ) {
- idCaller = as.getSummaryShadow();
+ idCaller = as.getSummaryShadow();
} else if( age == AllocationSite.AGE_oldest ) {
- idCaller = as.getOldestShadow();
+ idCaller = as.getOldestShadow();
} else {
- assert age == AllocationSite.AGE_in_I;
+ assert age == AllocationSite.AGE_in_I;
- Integer I = as.getAge(hrnCallee.getID() );
- assert I != null;
+ Integer I = as.getAge(hrnCallee.getID() );
+ assert I != null;
- idCaller = as.getIthOldestShadow(I);
+ idCaller = as.getIthOldestShadow(I);
}
assert id2hrn.containsKey(idCaller);
// so it maps to some regions directly reachable from the arg labels
Iterator<Integer> itrIndex = paramIndicesCallee_p.iterator();
while( itrIndex.hasNext() ) {
- Integer paramIndexCallee = itrIndex.next();
- assert pi2dr.containsKey(paramIndexCallee);
- possibleCallerHRNs.addAll(pi2dr.get(paramIndexCallee) );
+ Integer paramIndexCallee = itrIndex.next();
+ assert pi2dr.containsKey(paramIndexCallee);
+ possibleCallerHRNs.addAll(pi2dr.get(paramIndexCallee) );
}
}
// some parameter, so it maps to regions reachable from the arg labels
Iterator<Integer> itrIndex = paramIndicesCallee_s.iterator();
while( itrIndex.hasNext() ) {
- Integer paramIndexCallee = itrIndex.next();
- assert pi2r.containsKey(paramIndexCallee);
- possibleCallerHRNs.addAll(pi2r.get(paramIndexCallee) );
+ Integer paramIndexCallee = itrIndex.next();
+ assert pi2r.containsKey(paramIndexCallee);
+ possibleCallerHRNs.addAll(pi2r.get(paramIndexCallee) );
}
}
Iterator<ReferenceEdge> itrRers = hrn.iteratorToReferencers();
while( itrRers.hasNext() ) {
- ReferenceEdge edge = itrRers.next();
- assert rsEmpty.equals(edge.getBetaNew() );
+ ReferenceEdge edge = itrRers.next();
+ assert rsEmpty.equals(edge.getBetaNew() );
}
// calculate boldB for this flagged node
if( hrn.isFlagged() || hrn.isParameter() ) {
- Hashtable<ReferenceEdge, ReachabilitySet> boldB_f =
- new Hashtable<ReferenceEdge, ReachabilitySet>();
-
- Set<ReferenceEdge> workSetEdges = new HashSet<ReferenceEdge>();
-
- // initial boldB_f constraints
- Iterator<ReferenceEdge> itrRees = hrn.iteratorToReferencees();
- while( itrRees.hasNext() ) {
- ReferenceEdge edge = itrRees.next();
-
- assert !boldB.containsKey(edge);
- boldB_f.put(edge, edge.getBeta() );
-
- assert !workSetEdges.contains(edge);
- workSetEdges.add(edge);
- }
+ Hashtable<ReferenceEdge, ReachabilitySet> boldB_f =
+ new Hashtable<ReferenceEdge, ReachabilitySet>();
- // enforce the boldB_f constraint at edges until we reach a fixed point
- while( !workSetEdges.isEmpty() ) {
- ReferenceEdge edge = workSetEdges.iterator().next();
- workSetEdges.remove(edge);
+ Set<ReferenceEdge> workSetEdges = new HashSet<ReferenceEdge>();
- Iterator<ReferenceEdge> itrPrime = edge.getDst().iteratorToReferencees();
- while( itrPrime.hasNext() ) {
- ReferenceEdge edgePrime = itrPrime.next();
+ // initial boldB_f constraints
+ Iterator<ReferenceEdge> itrRees = hrn.iteratorToReferencees();
+ while( itrRees.hasNext() ) {
+ ReferenceEdge edge = itrRees.next();
- ReachabilitySet prevResult = boldB_f.get(edgePrime);
- ReachabilitySet intersection = boldB_f.get(edge).intersection(edgePrime.getBeta() );
+ assert !boldB.containsKey(edge);
+ boldB_f.put(edge, edge.getBeta() );
- if( prevResult == null ||
- prevResult.union(intersection).size() > prevResult.size() ) {
+ assert !workSetEdges.contains(edge);
+ workSetEdges.add(edge);
+ }
- if( prevResult == null ) {
- boldB_f.put(edgePrime, edgePrime.getBeta().union(intersection) );
- } else {
- boldB_f.put(edgePrime, prevResult.union(intersection) );
- }
- workSetEdges.add(edgePrime);
- }
- }
- }
+ // enforce the boldB_f constraint at edges until we reach a fixed point
+ while( !workSetEdges.isEmpty() ) {
+ ReferenceEdge edge = workSetEdges.iterator().next();
+ workSetEdges.remove(edge);
+
+ Iterator<ReferenceEdge> itrPrime = edge.getDst().iteratorToReferencees();
+ while( itrPrime.hasNext() ) {
+ ReferenceEdge edgePrime = itrPrime.next();
+
+ ReachabilitySet prevResult = boldB_f.get(edgePrime);
+ ReachabilitySet intersection = boldB_f.get(edge).intersection(edgePrime.getBeta() );
+
+ if( prevResult == null ||
+ prevResult.union(intersection).size() > prevResult.size() ) {
+
+ if( prevResult == null ) {
+ boldB_f.put(edgePrime, edgePrime.getBeta().union(intersection) );
+ } else {
+ boldB_f.put(edgePrime, prevResult.union(intersection) );
+ }
+ workSetEdges.add(edgePrime);
+ }
+ }
+ }
- boldB.put(token, boldB_f);
+ boldB.put(token, boldB_f);
}
}
// mark tokens for removal
Iterator<TokenTupleSet> stateItr = hrn.getAlpha().iterator();
while( stateItr.hasNext() ) {
- TokenTupleSet ttsOld = stateItr.next();
-
- TokenTupleSet markedTokens = new TokenTupleSet().makeCanonical();
-
- Iterator<TokenTuple> ttItr = ttsOld.iterator();
- while( ttItr.hasNext() ) {
- TokenTuple ttOld = ttItr.next();
-
- // never remove the identity token from a flagged region
- // because it is trivially satisfied
- if( hrn.isFlagged() || hrn.isParameter() ) {
- if( ttOld == ttException ) {
- continue;
- }
- }
-
- // does boldB_ttOld allow this token?
- boolean foundState = false;
- Iterator<ReferenceEdge> incidentEdgeItr = hrn.iteratorToReferencers();
- while( incidentEdgeItr.hasNext() ) {
- ReferenceEdge incidentEdge = incidentEdgeItr.next();
-
- // if it isn't allowed, mark for removal
- Integer idOld = ttOld.getToken();
- assert id2hrn.containsKey(idOld);
- Hashtable<ReferenceEdge, ReachabilitySet> B = boldB.get(idOld);
- ReachabilitySet boldB_ttOld_incident = B.get(incidentEdge); // B is NULL!
- if( boldB_ttOld_incident != null &&
- boldB_ttOld_incident.contains(ttsOld) ) {
- foundState = true;
- }
- }
-
- if( !foundState ) {
- markedTokens = markedTokens.add(ttOld);
- }
- }
-
- // if there is nothing marked, just move on
- if( markedTokens.isEmpty() ) {
- hrn.setAlphaNew(hrn.getAlphaNew().union(ttsOld) );
- continue;
- }
-
- // remove all marked tokens and establish a change set that should
- // propagate backwards over edges from this node
- TokenTupleSet ttsPruned = new TokenTupleSet().makeCanonical();
- ttItr = ttsOld.iterator();
- while( ttItr.hasNext() ) {
- TokenTuple ttOld = ttItr.next();
-
- if( !markedTokens.containsTuple(ttOld) ) {
- ttsPruned = ttsPruned.union(ttOld);
- }
- }
- assert !ttsOld.equals(ttsPruned);
-
- hrn.setAlphaNew(hrn.getAlphaNew().union(ttsPruned) );
- ChangeTuple ct = new ChangeTuple(ttsOld, ttsPruned).makeCanonical();
- cts = cts.union(ct);
+ TokenTupleSet ttsOld = stateItr.next();
+
+ TokenTupleSet markedTokens = new TokenTupleSet().makeCanonical();
+
+ Iterator<TokenTuple> ttItr = ttsOld.iterator();
+ while( ttItr.hasNext() ) {
+ TokenTuple ttOld = ttItr.next();
+
+ // never remove the identity token from a flagged region
+ // because it is trivially satisfied
+ if( hrn.isFlagged() || hrn.isParameter() ) {
+ if( ttOld == ttException ) {
+ continue;
+ }
+ }
+
+ // does boldB_ttOld allow this token?
+ boolean foundState = false;
+ Iterator<ReferenceEdge> incidentEdgeItr = hrn.iteratorToReferencers();
+ while( incidentEdgeItr.hasNext() ) {
+ ReferenceEdge incidentEdge = incidentEdgeItr.next();
+
+ // if it isn't allowed, mark for removal
+ Integer idOld = ttOld.getToken();
+ assert id2hrn.containsKey(idOld);
+ Hashtable<ReferenceEdge, ReachabilitySet> B = boldB.get(idOld);
+ ReachabilitySet boldB_ttOld_incident = B.get(incidentEdge); // B is NULL!
+ if( boldB_ttOld_incident != null &&
+ boldB_ttOld_incident.contains(ttsOld) ) {
+ foundState = true;
+ }
+ }
+
+ if( !foundState ) {
+ markedTokens = markedTokens.add(ttOld);
+ }
+ }
+
+ // if there is nothing marked, just move on
+ if( markedTokens.isEmpty() ) {
+ hrn.setAlphaNew(hrn.getAlphaNew().union(ttsOld) );
+ continue;
+ }
+
+ // remove all marked tokens and establish a change set that should
+ // propagate backwards over edges from this node
+ TokenTupleSet ttsPruned = new TokenTupleSet().makeCanonical();
+ ttItr = ttsOld.iterator();
+ while( ttItr.hasNext() ) {
+ TokenTuple ttOld = ttItr.next();
+
+ if( !markedTokens.containsTuple(ttOld) ) {
+ ttsPruned = ttsPruned.union(ttOld);
+ }
+ }
+ assert !ttsOld.equals(ttsPruned);
+
+ hrn.setAlphaNew(hrn.getAlphaNew().union(ttsPruned) );
+ ChangeTuple ct = new ChangeTuple(ttsOld, ttsPruned).makeCanonical();
+ cts = cts.union(ct);
}
// throw change tuple set on all incident edges
if( !cts.isEmpty() ) {
- Iterator<ReferenceEdge> incidentEdgeItr = hrn.iteratorToReferencers();
- while( incidentEdgeItr.hasNext() ) {
- ReferenceEdge incidentEdge = incidentEdgeItr.next();
-
- edgesForPropagation.add(incidentEdge);
-
- if( edgePlannedChanges.get(incidentEdge) == null ) {
- edgePlannedChanges.put(incidentEdge, cts);
- } else {
- edgePlannedChanges.put(
- incidentEdge,
- edgePlannedChanges.get(incidentEdge).union(cts)
- );
- }
- }
+ Iterator<ReferenceEdge> incidentEdgeItr = hrn.iteratorToReferencers();
+ while( incidentEdgeItr.hasNext() ) {
+ ReferenceEdge incidentEdge = incidentEdgeItr.next();
+
+ edgesForPropagation.add(incidentEdge);
+
+ if( edgePlannedChanges.get(incidentEdge) == null ) {
+ edgePlannedChanges.put(incidentEdge, cts);
+ } else {
+ edgePlannedChanges.put(
+ incidentEdge,
+ edgePlannedChanges.get(incidentEdge).union(cts)
+ );
+ }
+ }
}
}
hrn.applyAlphaNew();
Iterator<ReferenceEdge> itrRes = hrn.iteratorToReferencers();
while( itrRes.hasNext() ) {
- res.add(itrRes.next() );
+ res.add(itrRes.next() );
}
}
// commit results of last phase
if( edgesUpdated.contains(edge) ) {
- edge.applyBetaNew();
+ edge.applyBetaNew();
}
// compute intial condition of 2nd phase
OwnershipNode on = edgePrime.getSrc();
if( !(on instanceof HeapRegionNode) ) {
- continue;
+ continue;
}
HeapRegionNode hrn = (HeapRegionNode) on;
Iterator<ReferenceEdge> itrEdge = hrn.iteratorToReferencers();
while( itrEdge.hasNext() ) {
- ReferenceEdge edge = itrEdge.next();
+ ReferenceEdge edge = itrEdge.next();
- ReachabilitySet prevResult = edge.getBetaNew();
- assert prevResult != null;
+ ReachabilitySet prevResult = edge.getBetaNew();
+ assert prevResult != null;
- ReachabilitySet intersection = edge.getBeta().intersection(edgePrime.getBetaNew() );
+ ReachabilitySet intersection = edge.getBeta().intersection(edgePrime.getBetaNew() );
- if( prevResult.union(intersection).size() > prevResult.size() ) {
- edge.setBetaNew(prevResult.union(intersection) );
- edgeWorkSet.add(edge);
- }
+ if( prevResult.union(intersection).size() > prevResult.size() ) {
+ edge.setBetaNew(prevResult.union(intersection) );
+ edgeWorkSet.add(edge);
+ }
}
}
// if this graph doesn't have a node the
// incoming graph has, allocate it
if( !id2hrn.containsKey(idA) ) {
- HeapRegionNode hrnB = hrnA.copy();
- id2hrn.put(idA, hrnB);
- gid2hrn.put(hrnA.getGloballyUniqueIdentifier(), hrnB);
+ HeapRegionNode hrnB = hrnA.copy();
+ id2hrn.put(idA, hrnB);
+ gid2hrn.put(hrnA.getGloballyUniqueIdentifier(), hrnB);
} else {
- // otherwise this is a node present in both graphs
- // so make the new reachability set a union of the
- // nodes' reachability sets
- HeapRegionNode hrnB = id2hrn.get(idA);
- hrnB.setAlpha(hrnB.getAlpha().union(hrnA.getAlpha() ) );
+ // otherwise this is a node present in both graphs
+ // so make the new reachability set a union of the
+ // nodes' reachability sets
+ HeapRegionNode hrnB = id2hrn.get(idA);
+ hrnB.setAlpha(hrnB.getAlpha().union(hrnA.getAlpha() ) );
}
}
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.typeAndFieldEquals(edgeA) ) {
-
- edgeToMerge = edgeB;
- }
- }
-
- // if the edge from A was not found in B,
- // add it to B.
- if( edgeToMerge == null ) {
- assert id2hrn.containsKey(idChildA);
- HeapRegionNode hrnChildB = id2hrn.get(idChildA);
- edgeToMerge = edgeA.copy();
- edgeToMerge.setSrc(hrnB);
- edgeToMerge.setDst(hrnChildB);
- addReferenceEdge(hrnB, hrnChildB, edgeToMerge);
- }
- // otherwise, the edge already existed in both graphs
- // so merge their reachability sets
- else {
- // just replace this beta set with the union
- assert edgeToMerge != null;
- edgeToMerge.setBeta(
- edgeToMerge.getBeta().union(edgeA.getBeta() )
- );
- //TODO eom
- edgeToMerge.unionTaintIdentifier(edgeA.getTaintIdentifier());
- if( !edgeA.isInitialParam() ) {
- edgeToMerge.setIsInitialParam(false);
- }
- }
+ ReferenceEdge edgeA = heapRegionsItrA.next();
+ HeapRegionNode hrnChildA = edgeA.getDst();
+ Integer idChildA = hrnChildA.getID();
+
+ // at this point we know an edge in graph A exists
+ // idA -> idChildA, does this exist in B?
+ assert id2hrn.containsKey(idA);
+ HeapRegionNode hrnB = id2hrn.get(idA);
+ ReferenceEdge edgeToMerge = null;
+
+ Iterator<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.typeAndFieldEquals(edgeA) ) {
+
+ edgeToMerge = edgeB;
+ }
+ }
+
+ // if the edge from A was not found in B,
+ // add it to B.
+ if( edgeToMerge == null ) {
+ assert id2hrn.containsKey(idChildA);
+ HeapRegionNode hrnChildB = id2hrn.get(idChildA);
+ edgeToMerge = edgeA.copy();
+ edgeToMerge.setSrc(hrnB);
+ edgeToMerge.setDst(hrnChildB);
+ addReferenceEdge(hrnB, hrnChildB, edgeToMerge);
+ }
+ // otherwise, the edge already existed in both graphs
+ // so merge their reachability sets
+ else {
+ // just replace this beta set with the union
+ assert edgeToMerge != null;
+ edgeToMerge.setBeta(
+ edgeToMerge.getBeta().union(edgeA.getBeta() )
+ );
+ //TODO eom
+ edgeToMerge.unionTaintIdentifier(edgeA.getTaintIdentifier());
+ if( !edgeA.isInitialParam() ) {
+ edgeToMerge.setIsInitialParam(false);
+ }
+ }
}
}
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;
-
- Iterator<ReferenceEdge> heapRegionsItrB = lnB.iteratorToReferencees();
- while( heapRegionsItrB.hasNext() &&
- edgeToMerge == null ) {
-
- ReferenceEdge edgeB = heapRegionsItrB.next();
- HeapRegionNode hrnChildB = edgeB.getDst();
- Integer idChildB = hrnChildB.getID();
-
- // don't use the ReferenceEdge.equals() here because
- // we're talking about existence between graphs
- if( idChildB.equals(idChildA) &&
- edgeB.typeAndFieldEquals(edgeA) ) {
-
- edgeToMerge = edgeB;
- }
- }
-
- // if the edge from A was not found in B,
- // add it to B.
- if( edgeToMerge == null ) {
- assert id2hrn.containsKey(idChildA);
- HeapRegionNode hrnChildB = id2hrn.get(idChildA);
- edgeToMerge = edgeA.copy();
- edgeToMerge.setSrc(lnB);
- edgeToMerge.setDst(hrnChildB);
- addReferenceEdge(lnB, hrnChildB, edgeToMerge);
- }
- // otherwise, the edge already existed in both graphs
- // so merge their reachability sets
- else {
- // just replace this beta set with the union
- edgeToMerge.setBeta(
- edgeToMerge.getBeta().union(edgeA.getBeta() )
- );
- edgeToMerge.unionTaintIdentifier(edgeA.getTaintIdentifier());
- if( !edgeA.isInitialParam() ) {
- edgeToMerge.setIsInitialParam(false);
- }
- }
+ ReferenceEdge edgeA = heapRegionsItrA.next();
+ HeapRegionNode hrnChildA = edgeA.getDst();
+ Integer idChildA = hrnChildA.getID();
+
+ // at this point we know an edge in graph A exists
+ // tdA -> idChildA, does this exist in B?
+ assert td2ln.containsKey(tdA);
+ LabelNode lnB = td2ln.get(tdA);
+ ReferenceEdge edgeToMerge = null;
+
+ Iterator<ReferenceEdge> heapRegionsItrB = lnB.iteratorToReferencees();
+ while( heapRegionsItrB.hasNext() &&
+ edgeToMerge == null ) {
+
+ ReferenceEdge edgeB = heapRegionsItrB.next();
+ HeapRegionNode hrnChildB = edgeB.getDst();
+ Integer idChildB = hrnChildB.getID();
+
+ // don't use the ReferenceEdge.equals() here because
+ // we're talking about existence between graphs
+ if( idChildB.equals(idChildA) &&
+ edgeB.typeAndFieldEquals(edgeA) ) {
+
+ edgeToMerge = edgeB;
+ }
+ }
+
+ // if the edge from A was not found in B,
+ // add it to B.
+ if( edgeToMerge == null ) {
+ assert id2hrn.containsKey(idChildA);
+ HeapRegionNode hrnChildB = id2hrn.get(idChildA);
+ edgeToMerge = edgeA.copy();
+ edgeToMerge.setSrc(lnB);
+ edgeToMerge.setDst(hrnChildB);
+ addReferenceEdge(lnB, hrnChildB, edgeToMerge);
+ }
+ // otherwise, the edge already existed in both graphs
+ // so merge their reachability sets
+ else {
+ // just replace this beta set with the union
+ edgeToMerge.setBeta(
+ edgeToMerge.getBeta().union(edgeA.getBeta() )
+ );
+ edgeToMerge.unionTaintIdentifier(edgeA.getTaintIdentifier());
+ if( !edgeA.isInitialParam() ) {
+ edgeToMerge.setIsInitialParam(false);
+ }
+ }
}
}
}
HeapRegionNode hrnA = (HeapRegionNode) meA.getValue();
if( !ogB.id2hrn.containsKey(idA) ) {
- return false;
+ return false;
}
HeapRegionNode hrnB = ogB.id2hrn.get(idA);
if( !hrnA.equalsIncludingAlpha(hrnB) ) {
- return false;
+ return false;
}
}
TempDescriptor tdA = (TempDescriptor) meA.getKey();
if( !ogB.td2ln.containsKey(tdA) ) {
- return false;
+ return false;
}
}
assert ogB.id2hrn.containsKey(idA);
if( !areallREfromAequaltoB(ogA, hrnA, ogB) ) {
- return false;
+ return false;
}
// then check every edge in B for presence in A, starting
HeapRegionNode hrnB = ogB.id2hrn.get(idA);
if( !areallREfromAequaltoB(ogB, hrnB, ogA) ) {
- return false;
+ return false;
}
}
assert ogB.td2ln.containsKey(tdA);
if( !areallREfromAequaltoB(ogA, lnA, ogB) ) {
- return false;
+ return false;
}
// then check every edge in B for presence in A, starting
LabelNode lnB = ogB.td2ln.get(tdA);
if( !areallREfromAequaltoB(ogB, lnB, ogA) ) {
- return false;
+ return false;
}
}
OwnershipNode onB = null;
if( onA instanceof HeapRegionNode ) {
- HeapRegionNode hrnA = (HeapRegionNode) onA;
- onB = ogB.id2hrn.get(hrnA.getID() );
+ HeapRegionNode hrnA = (HeapRegionNode) onA;
+ onB = ogB.id2hrn.get(hrnA.getID() );
} else {
- LabelNode lnA = (LabelNode) onA;
- onB = ogB.td2ln.get(lnA.getTempDescriptor() );
+ LabelNode lnA = (LabelNode) onA;
+ onB = ogB.td2ln.get(lnA.getTempDescriptor() );
}
Iterator<ReferenceEdge> itrB = onB.iteratorToReferencees();
while( itrB.hasNext() ) {
- ReferenceEdge edgeB = itrB.next();
- HeapRegionNode hrnChildB = edgeB.getDst();
- Integer idChildB = hrnChildB.getID();
-
- if( idChildA.equals(idChildB) &&
- edgeA.typeAndFieldEquals(edgeB) ) {
-
- // there is an edge in the right place with the right field,
- // but do they have the same attributes?
- if( edgeA.getBeta().equals(edgeB.getBeta() ) ) {
- edgeFound = true;
- }
- }
+ ReferenceEdge edgeB = itrB.next();
+ HeapRegionNode hrnChildB = edgeB.getDst();
+ Integer idChildB = hrnChildB.getID();
+
+ if( idChildA.equals(idChildB) &&
+ edgeA.typeAndFieldEquals(edgeB) ) {
+
+ // there is an edge in the right place with the right field,
+ // but do they have the same attributes?
+ if( edgeA.getBeta().equals(edgeB.getBeta() ) ) {
+ edgeFound = true;
+ }
+ }
}
if( !edgeFound ) {
- return false;
+ return false;
}
}
if( aliasDetected ) {
common = findCommonReachableNodes(hrn1, hrn2);
if( !(DISABLE_STRONG_UPDATES || DISABLE_GLOBAL_SWEEP) ) {
- assert !common.isEmpty();
+ assert !common.isEmpty();
}
}
common = hasPotentialAlias(hrnParamPri, hrnIthOldest);
if( hrnParamSec != null ) {
- common.addAll(hasPotentialAlias(hrnParamSec, hrnIthOldest) );
+ common.addAll(hasPotentialAlias(hrnParamSec, hrnIthOldest) );
}
}
// while we're at it, do an inner loop for alloc2 vs alloc1 nodes
for( int j = 0; j < as1.getAllocationDepth(); ++j ) {
- Integer idI1 = as1.getIthOldest(j);
+ Integer idI1 = as1.getIthOldest(j);
- // if these are the same site, don't look for the same token, no alias.
- // different tokens of the same site could alias together though
- if( idI1.equals(idI2) ) {
- continue;
- }
+ // if these are the same site, don't look for the same token, no alias.
+ // different tokens of the same site could alias together though
+ if( idI1.equals(idI2) ) {
+ continue;
+ }
- HeapRegionNode hrnI1 = id2hrn.get(idI1);
+ HeapRegionNode hrnI1 = id2hrn.get(idI1);
- common.addAll(hasPotentialAlias(hrnI1, hrnI2) );
+ common.addAll(hasPotentialAlias(hrnI1, hrnI2) );
}
}
Iterator<ReferenceEdge> edgeItr = hrn.iteratorToReferencees();
while( edgeItr.hasNext() ) {
- ReferenceEdge edge = edgeItr.next();
+ ReferenceEdge edge = edgeItr.next();
- if( !reachableNodes1.contains(edge.getDst() ) ) {
- todoNodes1.add(edge.getDst() );
- }
+ if( !reachableNodes1.contains(edge.getDst() ) ) {
+ todoNodes1.add(edge.getDst() );
+ }
}
}
Iterator<ReferenceEdge> edgeItr = hrn.iteratorToReferencees();
while( edgeItr.hasNext() ) {
- ReferenceEdge edge = edgeItr.next();
+ ReferenceEdge edge = edgeItr.next();
- if( !reachableNodes2.contains(edge.getDst() ) ) {
- todoNodes2.add(edge.getDst() );
- }
+ if( !reachableNodes2.contains(edge.getDst() ) ) {
+ todoNodes2.add(edge.getDst() );
+ }
}
}
hrn.getDescription().startsWith("param")
) {
- if( !visited.contains(hrn) ) {
- traverseHeapRegionNodes(VISIT_HRN_WRITE_FULL,
- hrn,
- bw,
- null,
- visited,
- writeReferencers,
- hideSubsetReachability,
- hideEdgeTaints);
- }
+ if( !visited.contains(hrn) ) {
+ traverseHeapRegionNodes(VISIT_HRN_WRITE_FULL,
+ hrn,
+ bw,
+ null,
+ visited,
+ writeReferencers,
+ hideSubsetReachability,
+ hideEdgeTaints);
+ }
}
}
s = td2ln.entrySet();
i = s.iterator();
while( i.hasNext() ) {
- Map.Entry me = (Map.Entry)i.next();
- LabelNode ln = (LabelNode) me.getValue();
-
- if( labelSelect ) {
- String labelStr = ln.getTempDescriptorString();
- if( labelStr.startsWith("___temp") ||
- labelStr.startsWith("___dst") ||
- labelStr.startsWith("___srctmp") ||
- labelStr.startsWith("___neverused") ||
- labelStr.contains(qString) ||
- labelStr.contains(rString) ||
- labelStr.contains(blobString)
- ) {
- continue;
- }
- }
-
- //bw.write(" "+ln.toString() + ";\n");
-
- Iterator<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,
- hideSubsetReachability,
- hideEdgeTaints);
- }
-
- bw.write(" " + ln.toString() +
- " -> " + hrn.toString() +
- "[label=\"" + edge.toGraphEdgeString(hideSubsetReachability,
- hideEdgeTaints) +
- "\",decorate];\n");
- }
+ Map.Entry me = (Map.Entry)i.next();
+ LabelNode ln = (LabelNode) me.getValue();
+
+ if( labelSelect ) {
+ String labelStr = ln.getTempDescriptorString();
+ if( labelStr.startsWith("___temp") ||
+ labelStr.startsWith("___dst") ||
+ labelStr.startsWith("___srctmp") ||
+ labelStr.startsWith("___neverused") ||
+ labelStr.contains(qString) ||
+ labelStr.contains(rString) ||
+ labelStr.contains(blobString)
+ ) {
+ continue;
+ }
+ }
+
+ //bw.write(" "+ln.toString() + ";\n");
+
+ Iterator<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,
+ hideSubsetReachability,
+ hideEdgeTaints);
+ }
+
+ bw.write(" " + ln.toString() +
+ " -> " + hrn.toString() +
+ "[label=\"" + edge.toGraphEdgeString(hideSubsetReachability,
+ hideEdgeTaints) +
+ "\",decorate];\n");
+ }
}
}
String attributes = "[";
if( hrn.isSingleObject() ) {
- attributes += "shape=box";
+ attributes += "shape=box";
} else {
- attributes += "shape=Msquare";
+ attributes += "shape=Msquare";
}
if( hrn.isFlagged() ) {
- attributes += ",style=filled,fillcolor=lightgrey";
+ attributes += ",style=filled,fillcolor=lightgrey";
}
attributes += ",label=\"ID" +
"\\n";
if( hrn.getType() != null ) {
- attributes += hrn.getType().toPrettyString() + "\\n";
+ attributes += hrn.getType().toPrettyString() + "\\n";
}
attributes += hrn.getDescription() +
switch( mode ) {
case VISIT_HRN_WRITE_FULL:
- bw.write(" " + hrn.toString() +
- " -> " + hrnChild.toString() +
- "[label=\"" + edge.toGraphEdgeString(hideSubsetReachability,
- hideEdgeTaints) +
- "\",decorate];\n");
- break;
+ bw.write(" " + hrn.toString() +
+ " -> " + hrnChild.toString() +
+ "[label=\"" + edge.toGraphEdgeString(hideSubsetReachability,
+ hideEdgeTaints) +
+ "\",decorate];\n");
+ break;
}
traverseHeapRegionNodes(mode,
edge.unionTaintIdentifier(newTaintIdentifier);
if(edge.getSrc() instanceof HeapRegionNode) {
- HeapRegionNode refHRN=(HeapRegionNode)edge.getSrc();
- //check whether it is reflexive edge
- if(!refHRN.equals(hrn) && !visitedSet.contains(refHRN)) {
- visitedSet.add(refHRN);
- propagateTaintIdentifier((HeapRegionNode)edge.getSrc(),newTaintIdentifier,visitedSet);
- }
+ HeapRegionNode refHRN=(HeapRegionNode)edge.getSrc();
+ //check whether it is reflexive edge
+ if(!refHRN.equals(hrn) && !visitedSet.contains(refHRN)) {
+ visitedSet.add(refHRN);
+ propagateTaintIdentifier((HeapRegionNode)edge.getSrc(),newTaintIdentifier,visitedSet);
+ }
}
}
edge.minusTaintIdentifier(newTaintIdentifier);
if(edge.getSrc() instanceof HeapRegionNode) {
- HeapRegionNode refHRN=(HeapRegionNode)edge.getSrc();
- //check whether it is reflexive edge
- if(!refHRN.equals(hrn) && !visitedSet.contains(refHRN)) {
- visitedSet.add(refHRN);
- depropagateTaintIdentifier((HeapRegionNode)edge.getSrc(),newTaintIdentifier,visitedSet);
- }
+ HeapRegionNode refHRN=(HeapRegionNode)edge.getSrc();
+ //check whether it is reflexive edge
+ if(!refHRN.equals(hrn) && !visitedSet.contains(refHRN)) {
+ visitedSet.add(refHRN);
+ depropagateTaintIdentifier((HeapRegionNode)edge.getSrc(),newTaintIdentifier,visitedSet);
+ }
}
}
while (elements.hasMoreElements()) {
HeapRegionNode hrn = elements.nextElement();
if (hrn.getGloballyUniqueIdentifier().equals(id)) {
- return hrn;
+ return hrn;
}
}
if( edge.getDst().equals(hrn) &&
edge.typeEquals(type) &&
edge.fieldEquals(field) ) {
- return edge;
+ return edge;
}
}
if( as != null ) {
Set<AllocationSite> asSet = pi2a_as.get(paramIndex);
if( asSet == null ) {
- asSet = new HashSet<AllocationSite>();
+ asSet = new HashSet<AllocationSite>();
}
asSet.add(as);
pi2a_as.put(paramIndex, asSet);
// and if there is an allocation site, grab type
Set<TypeDescriptor> tdSet = pi2a_td.get(paramIndex);
if( tdSet == null ) {
- tdSet = new HashSet<TypeDescriptor>();
+ tdSet = new HashSet<TypeDescriptor>();
}
tdSet.add(as.getType() );
pi2a_td.put(paramIndex, tdSet);
if( as != null ) {
Set<AllocationSite> asSet = pi2r_as.get(paramIndex);
if( asSet == null ) {
- asSet = new HashSet<AllocationSite>();
+ asSet = new HashSet<AllocationSite>();
}
asSet.add(as);
pi2r_as.put(paramIndex, asSet);
// and if there is an allocation site, grab type
Set<TypeDescriptor> tdSet = pi2r_td.get(paramIndex);
if( tdSet == null ) {
- tdSet = new HashSet<TypeDescriptor>();
+ tdSet = new HashSet<TypeDescriptor>();
}
tdSet.add(as.getType() );
pi2r_td.put(paramIndex, tdSet);
while( itr.hasNext() ) {
TokenTupleSet ttsThis = (TokenTupleSet) itr.next();
if( ttsThis.containsWithZeroes(tts) ) {
- return true;
+ return true;
}
}
while( itr.hasNext() ) {
TokenTupleSet ttsThis = (TokenTupleSet) itr.next();
if( strict ) {
- if( !tts.equals(ttsThis) && tts.isSubset(ttsThis) ) {
- return true;
- }
+ if( !tts.equals(ttsThis) && tts.isSubset(ttsThis) ) {
+ return true;
+ }
} else {
- if( tts.isSubset(ttsThis) ) {
- return true;
- }
+ if( tts.isSubset(ttsThis) ) {
+ return true;
+ }
}
}
while( itr.hasNext() ) {
TokenTupleSet tts = (TokenTupleSet) itr.next();
if( tts.containsTuple(tt) ) {
- return true;
+ return true;
}
}
return false;
while( itr.hasNext() ) {
TokenTupleSet tts = (TokenTupleSet) itr.next();
if( tts.containsTuple(tt1) && tts.containsTuple(tt2) ) {
- return true;
+ return true;
}
}
return false;
ReachabilitySet rsOut = new ReachabilitySet();
Iterator i = this.iterator();
while( i.hasNext() ) {
- TokenTupleSet tts = (TokenTupleSet) i.next();
- if( rsIn.possibleReachabilities.contains(tts) ) {
- rsOut.possibleReachabilities.add(tts);
- }
+ TokenTupleSet tts = (TokenTupleSet) i.next();
+ if( rsIn.possibleReachabilities.contains(tts) ) {
+ rsOut.possibleReachabilities.add(tts);
+ }
}
ro.c=rsOut=rsOut.makeCanonical();
interhash.put(ro,ro);
while( i.hasNext() ) {
TokenTupleSet tts = (TokenTupleSet) i.next();
if( tts.containsTuple(ttB) ) {
- rsOut.possibleReachabilities.add(tts.remove(ttA) );
+ rsOut.possibleReachabilities.add(tts.remove(ttA) );
} else {
- rsOut.possibleReachabilities.add(tts);
+ rsOut.possibleReachabilities.add(tts);
}
}
Iterator<ChangeTuple> itrC = C.iterator();
while( itrC.hasNext() ) {
- ChangeTuple c = itrC.next();
+ ChangeTuple c = itrC.next();
- if( tts.equals(c.getSetToMatch() ) ) {
- rsOut.possibleReachabilities.add(c.getSetToAdd() );
- changeFound = true;
- }
+ if( tts.equals(c.getSetToMatch() ) ) {
+ rsOut.possibleReachabilities.add(c.getSetToAdd() );
+ changeFound = true;
+ }
}
if( keepSourceState || !changeFound ) {
- rsOut.possibleReachabilities.add(tts);
+ rsOut.possibleReachabilities.add(tts);
}
}
Iterator itrR = rsIn.iterator();
while( itrR.hasNext() ) {
- TokenTupleSet r = (TokenTupleSet) itrR.next();
-
- TokenTupleSet theUnion = new TokenTupleSet().makeCanonical();
-
- Iterator itrRelement = r.iterator();
- while( itrRelement.hasNext() ) {
- TokenTuple ttR = (TokenTuple) itrRelement.next();
- TokenTuple ttO = o.containsToken(ttR.getToken() );
-
- if( ttO != null ) {
- theUnion = theUnion.union((new TokenTupleSet(ttR.unionArity(ttO)).makeCanonical() ) );
- } else {
- theUnion = theUnion.union((new TokenTupleSet(ttR)).makeCanonical() );
- }
- }
-
- Iterator itrOelement = o.iterator();
- while( itrOelement.hasNext() ) {
- TokenTuple ttO = (TokenTuple) itrOelement.next();
- TokenTuple ttR = theUnion.containsToken(ttO.getToken() );
-
- if( ttR == null ) {
- theUnion = theUnion.union(new TokenTupleSet(ttO).makeCanonical() );
- }
- }
-
- if( !theUnion.isEmpty() ) {
- ctsOut = ctsOut.union((new ChangeTupleSet(new ChangeTuple(o, theUnion) )).makeCanonical() );
- }
+ TokenTupleSet r = (TokenTupleSet) itrR.next();
+
+ TokenTupleSet theUnion = new TokenTupleSet().makeCanonical();
+
+ Iterator itrRelement = r.iterator();
+ while( itrRelement.hasNext() ) {
+ TokenTuple ttR = (TokenTuple) itrRelement.next();
+ TokenTuple ttO = o.containsToken(ttR.getToken() );
+
+ if( ttO != null ) {
+ theUnion = theUnion.union((new TokenTupleSet(ttR.unionArity(ttO)).makeCanonical() ) );
+ } else {
+ theUnion = theUnion.union((new TokenTupleSet(ttR)).makeCanonical() );
+ }
+ }
+
+ Iterator itrOelement = o.iterator();
+ while( itrOelement.hasNext() ) {
+ TokenTuple ttO = (TokenTuple) itrOelement.next();
+ TokenTuple ttR = theUnion.containsToken(ttO.getToken() );
+
+ if( ttR == null ) {
+ theUnion = theUnion.union(new TokenTupleSet(ttO).makeCanonical() );
+ }
+ }
+
+ if( !theUnion.isEmpty() ) {
+ ctsOut = ctsOut.union((new ChangeTupleSet(new ChangeTuple(o, theUnion) )).makeCanonical() );
+ }
}
}
Iterator itrA = rsIn.iterator();
while( itrA.hasNext() && !subsetExists ) {
- TokenTupleSet ttsA = (TokenTupleSet) itrA.next();
+ TokenTupleSet ttsA = (TokenTupleSet) itrA.next();
- if( ttsA.isSubset(ttsB) ) {
- subsetExists = true;
- }
+ if( ttsA.isSubset(ttsB) ) {
+ subsetExists = true;
+ }
}
if( subsetExists ) {
- rsOut.possibleReachabilities.add(ttsB);
+ rsOut.possibleReachabilities.add(ttsB);
}
}
Iterator<TokenTupleSet> itrThis = this.iterator();
while( itrThis.hasNext() ) {
- TokenTupleSet ttsUnit = itrThis.next();
- ttsImprecise = ttsImprecise.unionUpArity(ttsUnit.makeArityZeroOrMore() );
+ TokenTupleSet ttsUnit = itrThis.next();
+ ttsImprecise = ttsImprecise.unionUpArity(ttsUnit.makeArityZeroOrMore() );
}
//rsOut = this.union( ttsImprecise );
TokenTupleSet ttsCoordinate = new TokenTupleSet().makeCanonical();
Iterator<TokenTupleSet> ttsItr = this.iterator();
for( int i = 0; i < numDimensions; ++i ) {
- assert ttsItr.hasNext();
- TokenTupleSet ttsUnit = ttsItr.next();
- for( int j = 0; j < digits[i]; ++j ) {
- ttsCoordinate = ttsCoordinate.unionUpArity(ttsUnit);
- }
+ assert ttsItr.hasNext();
+ TokenTupleSet ttsUnit = ttsItr.next();
+ for( int j = 0; j < digits[i]; ++j ) {
+ ttsCoordinate = ttsCoordinate.unionUpArity(ttsUnit);
+ }
}
rsOut = rsOut.add(ttsCoordinate.makeCanonical() );
// increment
for( int i = 0; i < numDimensions+1; ++i ) {
- digits[i]++;
+ digits[i]++;
- if( digits[i] > maxArity ) {
- // this axis reached its max, so roll it back to min and increment next higher digit
- digits[i] = minArity;
+ if( digits[i] > maxArity ) {
+ // this axis reached its max, so roll it back to min and increment next higher digit
+ digits[i] = minArity;
- } else {
- // this axis did not reach its max so we just enumerated a new unique coordinate, stop
- break;
- }
+ } else {
+ // this axis did not reach its max so we just enumerated a new unique coordinate, stop
+ break;
+ }
}
}
oldHashSet = true;
} else {
if( oldHash != currentHash ) {
- System.out.println("IF YOU SEE THIS A CANONICAL ReachabilitySet CHANGED");
- Integer x = null;
- x.toString();
+ System.out.println("IF YOU SEE THIS A CANONICAL ReachabilitySet CHANGED");
+ Integer x = null;
+ x.toString();
}
}
// skip this if there is a superset already
if( hideSubsetReachability &&
containsStrictSuperSet(tts) ) {
- continue;
+ continue;
}
s += tts;
if( i.hasNext() ) {
- s += "\\n";
+ s += "\\n";
}
}
// skip this if there is a superset already
if( hideSubsetReachability &&
containsStrictSuperSet(tts) ) {
- continue;
+ continue;
}
s += tts;
if( i.hasNext() ) {
- s += "\n";
+ s += "\n";
}
}
arity=ARITY_ONE;
} else {
if (arity==ARITY_ONEORMORE)
- arity=ARITY_ZEROORMORE;
+ arity=ARITY_ZEROORMORE;
}
}
// when two tokens are present (absence of a token is arity=zero and is
// handled outside of this method)
if( arity == ARITY_ZEROORMORE && tt.arity == ARITY_ZEROORMORE ) {
- return new TokenTuple(token, true, ARITY_ZEROORMORE).makeCanonical();
+ return new TokenTuple(token, true, ARITY_ZEROORMORE).makeCanonical();
} else {
- return new TokenTuple(token, true, ARITY_ONEORMORE).makeCanonical();
+ return new TokenTuple(token, true, ARITY_ONEORMORE).makeCanonical();
}
} else {
// a single object region's token can only have ZEROORMORE or ONE
if( arity == ARITY_ZEROORMORE && tt.arity == ARITY_ZEROORMORE ) {
- return new TokenTuple(token, false, ARITY_ZEROORMORE).makeCanonical();
+ return new TokenTuple(token, false, ARITY_ZEROORMORE).makeCanonical();
} else {
- return new TokenTuple(token, false, ARITY_ONE).makeCanonical();
+ return new TokenTuple(token, false, ARITY_ONE).makeCanonical();
}
}
}
TokenTuple ttThis = this.containsToken(ttIn.getToken() );
if( ttThis == null ) {
- return false;
+ return false;
}
}
if( ttIn == null &&
ttThis.getArity() != TokenTuple.ARITY_ZEROORMORE ) {
- return false;
+ return false;
}
}
TokenTuple ttIn = ttsIn.containsToken(ttThis.getToken() );
if( ttIn != null ) {
- ttsOut.tokenTuples.add(ttThis.unionArity(ttIn) );
+ ttsOut.tokenTuples.add(ttThis.unionArity(ttIn) );
} else {
- ttsOut.tokenTuples.add(ttThis);
+ ttsOut.tokenTuples.add(ttThis);
}
}
TokenTuple ttThis = ttsOut.containsToken(ttIn.getToken() );
if( ttThis == null ) {
- ttsOut.tokenTuples.add(ttIn);
+ ttsOut.tokenTuples.add(ttIn);
}
}
while( itr.hasNext() ) {
TokenTuple tt = (TokenTuple) itr.next();
if( token.equals(tt.getToken() ) ) {
- return tt;
+ return tt;
}
}
return null;
// tokens not associated with
// the site should be left alone
if( age == AllocationSite.AGE_notInThisSite ) {
- ttsOut.tokenTuples.add(tt);
+ ttsOut.tokenTuples.add(tt);
} else if( age == AllocationSite.AGE_summary ) {
- // remember the summary tuple, but don't add it
- // we may combine it with the oldest tuple
- ttSummary = tt;
+ // remember the summary tuple, but don't add it
+ // we may combine it with the oldest tuple
+ ttSummary = tt;
} else if( age == AllocationSite.AGE_oldest ) {
- // found an oldest token, again just remember
- // for later
- ttOldest = tt;
+ // found an oldest token, again just remember
+ // for later
+ ttOldest = tt;
} else {
- assert age == AllocationSite.AGE_in_I;
+ assert age == AllocationSite.AGE_in_I;
- Integer I = as.getAge(token);
- assert I != null;
+ Integer I = as.getAge(token);
+ assert I != null;
- // otherwise, we change this token to the
- // next older token
- Integer tokenToChangeTo = as.getIthOldest(I + 1);
- TokenTuple ttAged = tt.changeTokenTo(tokenToChangeTo);
- ttsOut.tokenTuples.add(ttAged);
+ // otherwise, we change this token to the
+ // next older token
+ Integer tokenToChangeTo = as.getIthOldest(I + 1);
+ TokenTuple ttAged = tt.changeTokenTo(tokenToChangeTo);
+ ttsOut.tokenTuples.add(ttAged);
}
}
int shadowAge = as.getShadowAgeCategory(token);
if( shadowAge == AllocationSite.AGE_summary ) {
- // remember the summary tuple, but don't add it
- // we may combine it with the oldest tuple
- ttSummary = tt;
+ // remember the summary tuple, but don't add it
+ // we may combine it with the oldest tuple
+ ttSummary = tt;
} else if( shadowAge == AllocationSite.SHADOWAGE_notInThisSite ) {
- ttsOut.tokenTuples.add(tt);
+ ttsOut.tokenTuples.add(tt);
} else if( shadowAge == AllocationSite.SHADOWAGE_summary ) {
- // found the shadow summary token, again just remember
- // for later
- ttShadowSummary = tt;
+ // found the shadow summary token, again just remember
+ // for later
+ ttShadowSummary = tt;
} else if( shadowAge == AllocationSite.SHADOWAGE_oldest ) {
- Integer tokenToChangeTo = as.getOldest();
- TokenTuple ttNormal = tt.changeTokenTo(tokenToChangeTo);
- ttsOut.tokenTuples.add(ttNormal);
+ Integer tokenToChangeTo = as.getOldest();
+ TokenTuple ttNormal = tt.changeTokenTo(tokenToChangeTo);
+ ttsOut.tokenTuples.add(ttNormal);
} else {
- assert shadowAge == AllocationSite.SHADOWAGE_in_I;
+ assert shadowAge == AllocationSite.SHADOWAGE_in_I;
- Integer I = as.getShadowAge(token);
- assert I != null;
+ Integer I = as.getShadowAge(token);
+ assert I != null;
- Integer tokenToChangeTo = as.getIthOldest(-I);
- TokenTuple ttNormal = tt.changeTokenTo(tokenToChangeTo);
- ttsOut.tokenTuples.add(ttNormal);
+ Integer tokenToChangeTo = as.getIthOldest(-I);
+ TokenTuple ttNormal = tt.changeTokenTo(tokenToChangeTo);
+ ttsOut.tokenTuples.add(ttNormal);
}
}
// summary tokens and tokens not associated with
// the site should be left alone
if( age == AllocationSite.AGE_notInThisSite ) {
- ttsOut = ttsOut.union(tt);
+ ttsOut = ttsOut.union(tt);
} else if( age == AllocationSite.AGE_summary ) {
- ttsOut = ttsOut.union(tt.changeTokenTo(as.getSummaryShadow() ));
+ ttsOut = ttsOut.union(tt.changeTokenTo(as.getSummaryShadow() ));
} else if( age == AllocationSite.AGE_oldest ) {
- ttsOut = ttsOut.union(tt.changeTokenTo(as.getOldestShadow() ));
+ ttsOut = ttsOut.union(tt.changeTokenTo(as.getOldestShadow() ));
} else {
- assert age == AllocationSite.AGE_in_I;
+ assert age == AllocationSite.AGE_in_I;
- Integer I = as.getAge(token);
- assert I != null;
+ Integer I = as.getAge(token);
+ assert I != null;
- ttsOut = ttsOut.union(tt.changeTokenTo(as.getIthOldestShadow(I) ));
+ ttsOut = ttsOut.union(tt.changeTokenTo(as.getIthOldestShadow(I) ));
}
}
Iterator<TokenTupleSet> replaceItr = replacements.iterator();
while( replaceItr.hasNext() ) {
- TokenTupleSet replacement = replaceItr.next();
- TokenTupleSet replaced = new TokenTupleSet(ttsMinusToken).makeCanonical();
- replaced = replaced.unionUpArity(replacement);
- rsOut = rsOut.add(replaced);
+ TokenTupleSet replacement = replaceItr.next();
+ TokenTupleSet replaced = new TokenTupleSet(ttsMinusToken).makeCanonical();
+ replaced = replaced.unionUpArity(replacement);
+ rsOut = rsOut.add(replaced);
- if( makeChangeSet ) {
- assert forChangeSet != null;
+ if( makeChangeSet ) {
+ assert forChangeSet != null;
- if( forChangeSet.get(this) == null ) {
- forChangeSet.put(this, new HashSet<TokenTupleSet>() );
- }
+ if( forChangeSet.get(this) == null ) {
+ forChangeSet.put(this, new HashSet<TokenTupleSet>() );
+ }
- forChangeSet.get(this).add(replaced);
- }
+ forChangeSet.get(this).add(replaced);
+ }
}
}
public boolean equals(Object o) {
if (o instanceof AllocNode) {
- AllocNode an=(AllocNode)o;
- return (allocsite==an.allocsite)&&(summary==an.summary);
+ AllocNode an=(AllocNode)o;
+ return (allocsite==an.allocsite)&&(summary==an.summary);
}
return false;
}
public String getID() {
if (summary)
- return "SUM"+allocsite;
+ return "SUM"+allocsite;
else
- return "SING"+allocsite;
+ return "SING"+allocsite;
}
}
public boolean equals(Object o) {
if (o instanceof AllocSiteNode) {
- AllocSiteNode an=(AllocSiteNode)o;
- return (allocsite==an.allocsite);
+ AllocSiteNode an=(AllocSiteNode)o;
+ return (allocsite==an.allocsite);
}
return false;
}
BBlock block=map.get(fn);
block.nodes.add(fn);
if (fn.kind()==FKind.FlatExit)
- exit=block;
+ exit=block;
do {
- if (pm.numNext(fn)!=1) {
- for(int i=0; i<pm.numNext(fn); i++) {
- FlatNode fnext=pm.getNext(fn,i);
- if (!map.containsKey(fnext)) {
- BBlock newb=new BBlock();
- blockset.add(newb);
- map.put(fnext, newb);
- toprocess.add(fnext);
- }
- //link block in
- if (!block.nextb.contains(map.get(fnext))) {
- block.nextb.add(map.get(fnext));
- map.get(fnext).prevb.add(block);
- }
- }
- break;
- }
- fn=pm.getNext(fn,0);
- if (pm.numPrev(fn)>1) {
- //new basic block
- if (!map.containsKey(fn)) {
- BBlock newb=new BBlock();
- blockset.add(newb);
- map.put(fn, newb);
- toprocess.add(fn);
- }
- //link block in
- if (!block.nextb.contains(map.get(fn))) {
- block.nextb.add(map.get(fn));
- map.get(fn).prevb.add(block);
- }
- break;
- }
- block.nodes.add(fn);
- if (fn.kind()==FKind.FlatExit)
- exit=block;
+ if (pm.numNext(fn)!=1) {
+ for(int i=0; i<pm.numNext(fn); i++) {
+ FlatNode fnext=pm.getNext(fn,i);
+ if (!map.containsKey(fnext)) {
+ BBlock newb=new BBlock();
+ blockset.add(newb);
+ map.put(fnext, newb);
+ toprocess.add(fnext);
+ }
+ //link block in
+ if (!block.nextb.contains(map.get(fnext))) {
+ block.nextb.add(map.get(fnext));
+ map.get(fnext).prevb.add(block);
+ }
+ }
+ break;
+ }
+ fn=pm.getNext(fn,0);
+ if (pm.numPrev(fn)>1) {
+ //new basic block
+ if (!map.containsKey(fn)) {
+ BBlock newb=new BBlock();
+ blockset.add(newb);
+ map.put(fn, newb);
+ toprocess.add(fn);
+ }
+ //link block in
+ if (!block.nextb.contains(map.get(fn))) {
+ block.nextb.add(map.get(fn));
+ map.get(fn).prevb.add(block);
+ }
+ break;
+ }
+ block.nodes.add(fn);
+ if (fn.kind()==FKind.FlatExit)
+ exit=block;
} while(true);
}
return new BasicBlock(map.get(fm), exit, blockset);
for(Map.Entry<AllocNode, MySet<Edge>> entry : heapedgeadd.entrySet()) {
AllocNode node=entry.getKey();
if (node==null)
- throw new Error("null node key");
+ throw new Error("null node key");
for(Edge e : entry.getValue())
- if (e.src!=node)
- throw new Error(e.src+" is not equal to "+node);
+ if (e.src!=node)
+ throw new Error(e.src+" is not equal to "+node);
}
for(Map.Entry<TempDescriptor, MySet<Edge>> entry : varedgeadd.entrySet()) {
TempDescriptor tmp=entry.getKey();
if (tmp==null)
- throw new Error("null temp key");
+ throw new Error("null temp key");
for(Edge e : entry.getValue())
- if (e.srcvar!=tmp)
- throw new Error(e.srcvar+" is not equal to "+tmp);
+ if (e.srcvar!=tmp)
+ throw new Error(e.srcvar+" is not equal to "+tmp);
}
return this;
}
TempDescriptor newTmp=tmpMap.get(entry.getKey());
MySet<Edge> edgeset=entry.getValue();
if (!edgeset.isEmpty()) {
- newdelta.varedgeadd.put(newTmp, new MySet<Edge>());
- for(Edge e : edgeset) {
- newdelta.varedgeadd.get(newTmp).add(e.rewrite(origTmp, newTmp));
- }
+ newdelta.varedgeadd.put(newTmp, new MySet<Edge>());
+ for(Edge e : edgeset) {
+ newdelta.varedgeadd.get(newTmp).add(e.rewrite(origTmp, newTmp));
+ }
}
}
newdelta.varedgeremove=varedgeremove;
for(Edge e : edges) {
if (e.srcvar!=null) {
- if (!newdelta.varedgeadd.containsKey(e.srcvar)) {
- newdelta.varedgeadd.put(e.srcvar, new MySet<Edge>());
- }
- newdelta.varedgeadd.get(e.srcvar).add(e);
+ if (!newdelta.varedgeadd.containsKey(e.srcvar)) {
+ newdelta.varedgeadd.put(e.srcvar, new MySet<Edge>());
+ }
+ newdelta.varedgeadd.get(e.srcvar).add(e);
} else {
- if (!newdelta.heapedgeadd.containsKey(e.src)) {
- newdelta.heapedgeadd.put(e.src, new MySet<Edge>());
- }
- newdelta.heapedgeadd.get(e.src).add(e.makeOld());
+ if (!newdelta.heapedgeadd.containsKey(e.src)) {
+ newdelta.heapedgeadd.put(e.src, new MySet<Edge>());
+ }
+ newdelta.heapedgeadd.get(e.src).add(e.makeOld());
}
}
return newdelta;
if (o instanceof Edge) {
Edge e=(Edge) o;
if (srcvar!=null) {
- return (srcvar==e.srcvar)&&(dst==e.dst);
+ return (srcvar==e.srcvar)&&(dst==e.dst);
} else {
- return (src==e.src)&&(dst==e.dst)&&(fd==e.fd);
+ return (src==e.src)&&(dst==e.dst)&&(fd==e.fd);
}
}
return false;
newe.statuspredicate=mergeStatus(statuspredicate, e.statuspredicate);
if (e.taints!=null) {
if (newe.taints==null)
- newe.taints=e.taints;
+ newe.taints=e.taints;
else
- newe.taints=newe.taints.merge(e.taints);
+ newe.taints=newe.taints.merge(e.taints);
}
return newe;
}
int edgeindex=0;
for(int count=0; count<4; count++) {
if ((mask&statuspredicate)==mask) {
- Edge e=new Edge();
- e.fd=fd;
- e.src=factory.getAllocNode(src, (mask&3)==0);
- e.dst=factory.getAllocNode(dst, (mask&5)==0);
- earray[edgeindex++]=e;
+ Edge e=new Edge();
+ e.fd=fd;
+ e.src=factory.getAllocNode(src, (mask&3)==0);
+ e.dst=factory.getAllocNode(dst, (mask&5)==0);
+ earray[edgeindex++]=e;
}
mask=mask<<1;
}
return true;
if (ts1==null) {
if (ts2.isEmpty())
- return true;
+ return true;
else
- return false;
+ return false;
}
//Neither is null
//Do a set comparison
public static void mergeEdgesInto(MySet<Edge> orig, MySet<Edge> merge) {
for(Edge e : merge) {
if (orig.contains(e)) {
- Edge old=orig.get(e);
- e=e.merge(old);
+ Edge old=orig.get(e);
+ e=e.merge(old);
}
orig.add(e);
}
for(Map.Entry<AllocNode, MySet<Edge>> entry : nodeMap.entrySet()) {
AllocNode node=entry.getKey();
if (node==null)
- throw new Error("Null node key");
+ throw new Error("Null node key");
for(Edge e : entry.getValue())
- if (e.src!=node)
- throw new Error();
+ if (e.src!=node)
+ throw new Error();
}
for(Map.Entry<TempDescriptor, MySet<Edge>> entry : varMap.entrySet()) {
TempDescriptor tmp=entry.getKey();
if (tmp==null)
- throw new Error("Null tmp key");
+ throw new Error("Null tmp key");
for(Edge e : entry.getValue())
- if (e.srcvar!=tmp)
- throw new Error();
+ if (e.srcvar!=tmp)
+ throw new Error();
}
}
if (old.srcvar!=null) {
MySet<Edge> edges=varMap.get(old.srcvar);
if (edges==null)
- edges=parent.varMap.get(old.srcvar);
+ edges=parent.varMap.get(old.srcvar);
if (edges==null)
- return null;
+ return null;
return edges.get(old);
} else {
MySet<Edge> edges=nodeMap.get(old.src);
if (edges==null)
- edges=parent.nodeMap.get(old.src);
+ edges=parent.nodeMap.get(old.src);
if (edges==null)
- return null;
+ return null;
return edges.get(old);
}
}
for(Map.Entry<TempDescriptor, MySet<Edge>> entry : varMap.entrySet()) {
TempDescriptor tmp=entry.getKey();
if (childvarMap!=null&&childvarMap.containsKey(tmp))
- continue;
+ continue;
output.println(tmp.getSymbol()+"[shape=rectangle];");
for(Edge e : entry.getValue()) {
- if (e.srcvar!=tmp)
- throw new Error(e.srcvar +" is not equal to "+tmp);
- AllocNode n=e.dst;
- output.println("\t"+tmp.getSymbol()+"->"+n.getID()+"[label=\""+e.taintString()+"\"];");
+ if (e.srcvar!=tmp)
+ throw new Error(e.srcvar +" is not equal to "+tmp);
+ AllocNode n=e.dst;
+ output.println("\t"+tmp.getSymbol()+"->"+n.getID()+"[label=\""+e.taintString()+"\"];");
}
}
}
for(Map.Entry<AllocNode, MySet<Edge>> entry : nodeMap.entrySet()) {
AllocNode node=entry.getKey();
if (childNodeMap!=null&&childNodeMap.containsKey(node))
- continue;
+ continue;
for(Edge e : entry.getValue()) {
- if (e.src!=node)
- throw new Error(e.src+" is not equal to "+node);
- AllocNode n=e.dst;
- String src=node.getID();
- String dst=n.getID();
- String field=e.fd!=null?e.fd.getSymbol():"[]";
- String taint=e.taints!=null?":"+e.taintString():"";
- output.println("\t"+src+"->"+dst+"[label=\""+field+" "+taint+"\"];");
+ if (e.src!=node)
+ throw new Error(e.src+" is not equal to "+node);
+ AllocNode n=e.dst;
+ String src=node.getID();
+ String dst=n.getID();
+ String field=e.fd!=null?e.fd.getSymbol():"[]";
+ String taint=e.taints!=null?":"+e.taintString():"";
+ output.println("\t"+src+"->"+dst+"[label=\""+field+" "+taint+"\"];");
}
}
}
MySet<Edge> edgeset=new MySet<Edge>();
for(AllocNode srcnode : srcSet) {
for(AllocNode dstnode : dstSet) {
- edgeset.add(new Edge(srcnode, fd, dstnode, Edge.NEW));
+ edgeset.add(new Edge(srcnode, fd, dstnode, Edge.NEW));
}
}
return edgeset;
MySet<Edge> edgeset=new MySet<Edge>();
for(Edge srcedge : srcSet) {
for(Edge dstedge : dstSet) {
- edgeset.add(dstedge.changeSrc(fd, srcedge.dst));
+ edgeset.add(dstedge.changeSrc(fd, srcedge.dst));
}
}
return edgeset;
MySet<Edge> edgeset=new MySet<Edge>();
for(AllocNode srcnode : srcSet) {
for(Edge dstedge : dstSet) {
- edgeset.add(dstedge.changeSrc(fd, srcnode));
+ edgeset.add(dstedge.changeSrc(fd, srcnode));
}
}
return edgeset;
MySet<Edge> baseedges=delta.basevaredge.get(tmp);
if (baseedges!=null) {
for(Edge e : baseedges) {
- if (removeedges==null||!removeedges.contains(e))
- edges.add(e);
+ if (removeedges==null||!removeedges.contains(e))
+ edges.add(e);
}
}
if (delta.varedgeadd.containsKey(tmp))
for(Edge e : delta.varedgeadd.get(tmp)) {
- edges.add(e);
+ edges.add(e);
}
return edges;
}
for(Edge e : graph.getEdges(tmp)) {
if (removeedges==null||!removeedges.contains(e))
- edges.add(e);
+ edges.add(e);
}
if (delta.varedgeadd.containsKey(tmp))
for(Edge e : delta.varedgeadd.get(tmp)) {
- edges.add(e);
+ edges.add(e);
}
return edges;
}
for(Edge node : srcNodes) {
MySet<Edge> removeedges=delta.heapedgeremove.get(node.dst);
for(Edge e : graph.getEdges(node.dst)) {
- if (e.fd==fd&&(removeedges==null||!removeedges.contains(e)))
- nodes.add(e);
+ if (e.fd==fd&&(removeedges==null||!removeedges.contains(e)))
+ nodes.add(e);
}
if (delta.heapedgeadd.containsKey(node.dst))
- for(Edge e : delta.heapedgeadd.get(node.dst)) {
- if (e.fd==fd)
- nodes.add(e);
- }
+ for(Edge e : delta.heapedgeadd.get(node.dst)) {
+ if (e.fd==fd)
+ nodes.add(e);
+ }
}
return nodes;
}
for(AllocNode node : srcNodes) {
MySet<Edge> removeedges=delta.heapedgeremove.get(node);
for(Edge e : graph.getEdges(node)) {
- if (e.fd==fd&&(removeedges==null||!removeedges.contains(e)))
- nodes.add(e);
+ if (e.fd==fd&&(removeedges==null||!removeedges.contains(e)))
+ nodes.add(e);
}
if (delta.heapedgeadd.containsKey(node))
- for(Edge e : delta.heapedgeadd.get(node)) {
- if (e.fd==fd)
- nodes.add(e);
- }
+ for(Edge e : delta.heapedgeadd.get(node)) {
+ if (e.fd==fd)
+ nodes.add(e);
+ }
}
return nodes;
}
MySet<Edge> removeedges=delta.heapedgeremove.get(node);
for(Edge e : graph.getEdges(node)) {
if ((removeedges==null||!removeedges.contains(e)))
- nodes.add(e);
+ nodes.add(e);
}
if (delta.heapedgeadd.containsKey(node))
for(Edge e : delta.heapedgeadd.get(node)) {
- nodes.add(e);
+ nodes.add(e);
}
return nodes;
if (baseEdges!=null)
for(Edge e : baseEdges) {
- if (removeedges==null||!removeedges.contains(e))
- nodes.add(e.dst);
+ if (removeedges==null||!removeedges.contains(e))
+ nodes.add(e.dst);
}
if (delta.varedgeadd.containsKey(tmp))
for(Edge e : delta.varedgeadd.get(tmp)) {
- nodes.add(e.dst);
+ nodes.add(e.dst);
}
return nodes;
}
for(Edge e : graph.getEdges(tmp)) {
if (removeedges==null||!removeedges.contains(e))
- nodes.add(e.dst);
+ nodes.add(e.dst);
}
if (delta.varedgeadd.containsKey(tmp))
for(Edge e : delta.varedgeadd.get(tmp)) {
- nodes.add(e.dst);
+ nodes.add(e.dst);
}
return nodes;
}
MySet<Edge> removeedges=delta.heapedgeremove.get(node);
MySet<Edge> baseEdges=delta.baseheapedge.get(node);
if (baseEdges!=null)
- for(Edge e : baseEdges) {
- if (e.fd==fd&&(removeedges==null||!removeedges.contains(e)))
- nodes.add(e.dst);
- }
+ for(Edge e : baseEdges) {
+ if (e.fd==fd&&(removeedges==null||!removeedges.contains(e)))
+ nodes.add(e.dst);
+ }
if (delta.heapedgeadd.containsKey(node))
- for(Edge e : delta.heapedgeadd.get(node)) {
- if (e.fd==fd)
- nodes.add(e.dst);
- }
+ for(Edge e : delta.heapedgeadd.get(node)) {
+ if (e.fd==fd)
+ nodes.add(e.dst);
+ }
}
return nodes;
}
for(Map.Entry<AllocNode, MySet<Edge>> entry : delta.baseheapedge.entrySet()) {
AllocNode node=entry.getKey();
if (srcNodes.contains(node)) {
- MySet<Edge> edges=entry.getValue();
- MySet<Edge> removeedges=delta.heapedgeremove.get(node);
- for(Edge e : edges) {
- if (removeedges==null||!removeedges.contains(e)) {
- newedges.add(e);
- }
- }
+ MySet<Edge> edges=entry.getValue();
+ MySet<Edge> removeedges=delta.heapedgeremove.get(node);
+ for(Edge e : edges) {
+ if (removeedges==null||!removeedges.contains(e)) {
+ newedges.add(e);
+ }
+ }
}
}
for(Map.Entry<AllocNode, MySet<Edge>> entry : delta.heapedgeadd.entrySet()) {
AllocNode node=entry.getKey();
if (srcNodes.contains(node)) {
- MySet<Edge> edges=entry.getValue();
- newedges.addAll(edges);
+ MySet<Edge> edges=entry.getValue();
+ newedges.addAll(edges);
}
}
return newedges;
for(Map.Entry<AllocNode, MySet<Edge>> entry : delta.baseheapedge.entrySet()) {
AllocNode node=entry.getKey();
if (srcNodes.contains(node)) {
- MySet<Edge> edges=entry.getValue();
- MySet<Edge> removeedges=delta.heapedgeremove.get(node);
- for(Edge e : edges) {
- if ((removeedges==null||!removeedges.contains(e))&&(e.fd==fd)) {
- newedges.add(e);
- }
- }
+ MySet<Edge> edges=entry.getValue();
+ MySet<Edge> removeedges=delta.heapedgeremove.get(node);
+ for(Edge e : edges) {
+ if ((removeedges==null||!removeedges.contains(e))&&(e.fd==fd)) {
+ newedges.add(e);
+ }
+ }
}
}
for(Map.Entry<AllocNode, MySet<Edge>> entry : delta.heapedgeadd.entrySet()) {
AllocNode node=entry.getKey();
if (srcNodes.contains(node)) {
- MySet<Edge> edges=entry.getValue();
- for(Edge e : edges) {
- if (e.fd==fd)
- newedges.add(e);
- }
+ MySet<Edge> edges=entry.getValue();
+ for(Edge e : edges) {
+ if (e.fd==fd)
+ newedges.add(e);
+ }
}
}
return newedges;
for(Edge edge : srcEdges) {
TaintSet ts=edge.getTaints();
if (ts!=null) {
- ts=ts.reTaint(fn);
+ ts=ts.reTaint(fn);
}
MySet<Edge> removeedges=delta.heapedgeremove.get(edge.dst);
for(Edge e : graph.getEdges(edge.dst)) {
- if (e.fd==fd&&(removeedges==null||!removeedges.contains(e))) {
- e=e.changeSrcVar(dst, ts);
- if (!edgeset.contains(e))
- edgeset.add(e);
- else {
- Edge preve=edgeset.get(e);
- e=e.merge(preve);
- edgeset.add(e);
- }
- }
+ if (e.fd==fd&&(removeedges==null||!removeedges.contains(e))) {
+ e=e.changeSrcVar(dst, ts);
+ if (!edgeset.contains(e))
+ edgeset.add(e);
+ else {
+ Edge preve=edgeset.get(e);
+ e=e.merge(preve);
+ edgeset.add(e);
+ }
+ }
}
if (delta.heapedgeadd.containsKey(edge.dst))
- for(Edge e : delta.heapedgeadd.get(edge.dst)) {
- if (e.fd==fd) {
- e=e.changeSrcVar(dst, ts);
- if (!edgeset.contains(e))
- edgeset.add(e);
- else {
- Edge preve=edgeset.get(e);
- e=e.merge(preve);
- edgeset.add(e);
- }
- }
- }
+ for(Edge e : delta.heapedgeadd.get(edge.dst)) {
+ if (e.fd==fd) {
+ e=e.changeSrcVar(dst, ts);
+ if (!edgeset.contains(e))
+ edgeset.add(e);
+ else {
+ Edge preve=edgeset.get(e);
+ e=e.merge(preve);
+ edgeset.add(e);
+ }
+ }
+ }
}
return edgeset;
}
for(Edge edge : srcEdges) {
TaintSet ts=edge.getTaints();
if (ts!=null) {
- ts=ts.reTaint(fn);
+ ts=ts.reTaint(fn);
}
MySet<Edge> removeedges=delta.heapedgeremove.get(edge.dst);
if (delta.baseheapedge.containsKey(edge.dst)) {
- for(Edge e : delta.baseheapedge.get(edge.dst)) {
- if (e.fd==fd&&(removeedges==null||!removeedges.contains(e))) {
- e=e.changeSrcVar(dst, ts);
- if (!edgeset.contains(e))
- edgeset.add(e);
- else {
- Edge preve=edgeset.get(e);
- e=e.merge(preve);
- edgeset.add(e);
- }
- }
- }
+ for(Edge e : delta.baseheapedge.get(edge.dst)) {
+ if (e.fd==fd&&(removeedges==null||!removeedges.contains(e))) {
+ e=e.changeSrcVar(dst, ts);
+ if (!edgeset.contains(e))
+ edgeset.add(e);
+ else {
+ Edge preve=edgeset.get(e);
+ e=e.merge(preve);
+ edgeset.add(e);
+ }
+ }
+ }
}
if (delta.heapedgeadd.containsKey(edge.dst))
- for(Edge e : delta.heapedgeadd.get(edge.dst)) {
- if (e.fd==fd) {
- e=e.changeSrcVar(dst, ts);
- if (!edgeset.contains(e))
- edgeset.add(e);
- else {
- Edge preve=edgeset.get(e);
- e=e.merge(preve);
- edgeset.add(e);
- }
- }
- }
+ for(Edge e : delta.heapedgeadd.get(edge.dst)) {
+ if (e.fd==fd) {
+ e=e.changeSrcVar(dst, ts);
+ if (!edgeset.contains(e))
+ edgeset.add(e);
+ else {
+ Edge preve=edgeset.get(e);
+ e=e.merge(preve);
+ edgeset.add(e);
+ }
+ }
+ }
}
return edgeset;
}
for(AllocNode node : srcNodes) {
MySet<Edge> removeedges=delta.heapedgeremove.get(node);
for(Edge e : graph.getEdges(node)) {
- if (e.fd==fd&&(removeedges==null||!removeedges.contains(e)))
- nodes.add(e.dst);
+ if (e.fd==fd&&(removeedges==null||!removeedges.contains(e)))
+ nodes.add(e.dst);
}
if (delta.heapedgeadd.containsKey(node))
- for(Edge e : delta.heapedgeadd.get(node)) {
- if (e.fd==fd)
- nodes.add(e.dst);
- }
+ for(Edge e : delta.heapedgeadd.get(node)) {
+ if (e.fd==fd)
+ nodes.add(e.dst);
+ }
}
return nodes;
}
blockMap.put(fm, BasicBlock.getBBlock(fm));
Hashtable<FlatNode, Set<TempDescriptor>> livemap=Liveness.computeLiveTemps(fm);
for(BBlock bblock : blockMap.get(fm).getBlocks()) {
- FlatNode fn=bblock.nodes.get(0);
- if (fn==fm) {
- HashSet<TempDescriptor> fmset=new HashSet<TempDescriptor>();
- fmset.addAll((List<TempDescriptor>)Arrays.asList(fm.writesTemps()));
- bblivetemps.put(bblock, fmset);
- } else {
- Set<TempDescriptor> livetemps=livemap.get(fn);
- bblivetemps.put(bblock, livetemps);
- livetemps.add(returntmp);
- }
+ FlatNode fn=bblock.nodes.get(0);
+ if (fn==fm) {
+ HashSet<TempDescriptor> fmset=new HashSet<TempDescriptor>();
+ fmset.addAll((List<TempDescriptor>)Arrays.asList(fm.writesTemps()));
+ bblivetemps.put(bblock, fmset);
+ } else {
+ Set<TempDescriptor> livetemps=livemap.get(fn);
+ bblivetemps.put(bblock, livetemps);
+ livetemps.add(returntmp);
+ }
}
}
return blockMap.get(fm);
int startindex=0;
if (ppoint.getIndex()==-1) {
- //Build base graph for entrance to this basic block
- //System.out.println("Processing "+bblock.nodes.get(0).toString().replace(' ','_'));
- //delta.print();
- delta=applyInitDelta(delta, bblock);
- //System.out.println("Generating:");
- //delta.print();
+ //Build base graph for entrance to this basic block
+ //System.out.println("Processing "+bblock.nodes.get(0).toString().replace(' ','_'));
+ //delta.print();
+ delta=applyInitDelta(delta, bblock);
+ //System.out.println("Generating:");
+ //delta.print();
} else {
- //System.out.println("Processing Call "+bblock.nodes.get(ppoint.getIndex()).toString().replace(' ','_'));
- //delta.print();
+ //System.out.println("Processing Call "+bblock.nodes.get(ppoint.getIndex()).toString().replace(' ','_'));
+ //delta.print();
- startindex=ppoint.getIndex()+1;
- delta=applyCallDelta(delta, bblock);
- //System.out.println("Generating:");
- //delta.print();
+ startindex=ppoint.getIndex()+1;
+ delta=applyCallDelta(delta, bblock);
+ //System.out.println("Generating:");
+ //delta.print();
}
Graph graph=bbgraphMap.get(bblock);
Graph nodeGraph=null;
int lasti=-1;
//Compute delta at exit of each node
for(int i=startindex; i<nodes.size(); i++) {
- FlatNode currNode=nodes.get(i);
- //System.out.println("Start Processing "+currNode);
- boolean init=delta.getInit();
- if (!init&&delta.isEmpty())
- continue nextdelta;
-
-
- if (!graphMap.containsKey(currNode)) {
- if (isNEEDED(currNode)) {
- graphMap.put(currNode, new Graph(graph));
- } else {
- boolean fallthru=true;
- if (isINACC(currNode)&&((lasti==-1)||(lasti==i))) {
- if (lasti==-1) {
- for(lasti=nodes.size()-1; lasti>=i; lasti--) {
- FlatNode scurrNode=nodes.get(lasti);
- if (isNEEDED(scurrNode)||isINACC(scurrNode)) {
- break;
- }
- }
- }
- if (i==lasti) {
- mustProcess.add(currNode);
- graphMap.put(currNode, new Graph(graph));
- fallthru=false;
- }
- }
- if (fallthru) {
- if (i==0) {
- //base graph works for us
- graphMap.put(currNode, new Graph(graph));
- } else {
- //just use previous graph
- graphMap.put(currNode, graphMap.get(nodes.get(i-1)));
- }
- }
- }
- }
-
- nodeGraph=graphMap.get(currNode);
- delta=processNode(bblock, i, currNode, delta, nodeGraph);
- //System.out.println("Processing "+currNode+" and generating delta:");
- //delta.print();
+ FlatNode currNode=nodes.get(i);
+ //System.out.println("Start Processing "+currNode);
+ boolean init=delta.getInit();
+ if (!init&&delta.isEmpty())
+ continue nextdelta;
+
+
+ if (!graphMap.containsKey(currNode)) {
+ if (isNEEDED(currNode)) {
+ graphMap.put(currNode, new Graph(graph));
+ } else {
+ boolean fallthru=true;
+ if (isINACC(currNode)&&((lasti==-1)||(lasti==i))) {
+ if (lasti==-1) {
+ for(lasti=nodes.size()-1; lasti>=i; lasti--) {
+ FlatNode scurrNode=nodes.get(lasti);
+ if (isNEEDED(scurrNode)||isINACC(scurrNode)) {
+ break;
+ }
+ }
+ }
+ if (i==lasti) {
+ mustProcess.add(currNode);
+ graphMap.put(currNode, new Graph(graph));
+ fallthru=false;
+ }
+ }
+ if (fallthru) {
+ if (i==0) {
+ //base graph works for us
+ graphMap.put(currNode, new Graph(graph));
+ } else {
+ //just use previous graph
+ graphMap.put(currNode, graphMap.get(nodes.get(i-1)));
+ }
+ }
+ }
+ }
+
+ nodeGraph=graphMap.get(currNode);
+ delta=processNode(bblock, i, currNode, delta, nodeGraph);
+ //System.out.println("Processing "+currNode+" and generating delta:");
+ //delta.print();
}
generateFinalDelta(bblock, delta, nodeGraph);
}
if (false) {
int debugindex=0;
for(Map.Entry<BBlock, Graph> e : bbgraphMap.entrySet()) {
- Graph g=e.getValue();
- plotGraph(g,"BB"+e.getKey().nodes.get(0).toString().replace(' ','_'));
- debugindex++;
+ Graph g=e.getValue();
+ plotGraph(g,"BB"+e.getKey().nodes.get(0).toString().replace(' ','_'));
+ debugindex++;
}
for(FlatMethod fm : blockMap.keySet()) {
- System.out.println(fm.printMethod());
+ System.out.println(fm.printMethod());
}
for(Map.Entry<FlatNode, Graph> e : graphMap.entrySet()) {
- FlatNode fn=e.getKey();
- Graph g=e.getValue();
- plotGraph(g,"FN"+fn.toString()+debugindex);
- debugindex++;
+ FlatNode fn=e.getKey();
+ Graph g=e.getValue();
+ plotGraph(g,"FN"+fn.toString()+debugindex);
+ debugindex++;
}
}
MySet<Edge> edgeSet=new MySet<Edge>();
/* Get target set */
if (graph.varMap.containsKey(tmp))
- edgeSet.addAll(graph.varMap.get(tmp));
+ edgeSet.addAll(graph.varMap.get(tmp));
else
- edgeSet.addAll(graph.parent.varMap.get(tmp));
+ edgeSet.addAll(graph.parent.varMap.get(tmp));
newDelta.varedgeadd.put(tmp, edgeSet);
}
MySet<Edge> edgeSet=new MySet<Edge>();
/* Get edge set */
if (graph.nodeMap.containsKey(node))
- edgeSet.addAll(graph.nodeMap.get(node));
+ edgeSet.addAll(graph.nodeMap.get(node));
else
- edgeSet.addAll(graph.parent.nodeMap.get(node));
+ edgeSet.addAll(graph.parent.nodeMap.get(node));
newDelta.heapedgeadd.put(node, edgeSet);
/* Compute ages */
if (graph.oldNodes.containsKey(node)) {
- if (graph.oldNodes.get(node).booleanValue())
- newDelta.addOldNodes.put(node, Boolean.TRUE);
+ if (graph.oldNodes.get(node).booleanValue())
+ newDelta.addOldNodes.put(node, Boolean.TRUE);
} else if (graph.parent.oldNodes.containsKey(node)) {
- //parent graphs only contain true...no need to check
- newDelta.addOldNodes.put(node, Boolean.TRUE);
+ //parent graphs only contain true...no need to check
+ newDelta.addOldNodes.put(node, Boolean.TRUE);
}
}
tmpSet.addAll(delta.basevaredge.keySet());
tmpSet.addAll(delta.varedgeadd.keySet());
for(TempDescriptor tmp : tmpSet) {
- /* Start with the new incoming edges */
- MySet<Edge> newbaseedge=delta.basevaredge.get(tmp);
- /* Remove the remove set */
- if (newbaseedge==null)
- newbaseedge=new MySet<Edge>();
- newbaseedge.removeAll(delta.varedgeremove.get(tmp));
- /* Add in the new set*/
- newbaseedge.addAll(delta.varedgeadd.get(tmp));
- /* Store the results */
- newDelta.varedgeadd.put(tmp, newbaseedge);
+ /* Start with the new incoming edges */
+ MySet<Edge> newbaseedge=delta.basevaredge.get(tmp);
+ /* Remove the remove set */
+ if (newbaseedge==null)
+ newbaseedge=new MySet<Edge>();
+ newbaseedge.removeAll(delta.varedgeremove.get(tmp));
+ /* Add in the new set*/
+ newbaseedge.addAll(delta.varedgeadd.get(tmp));
+ /* Store the results */
+ newDelta.varedgeadd.put(tmp, newbaseedge);
}
delta.basevaredge.clear();
nodeSet.addAll(delta.heapedgeadd.keySet());
nodeSet.addAll(delta.heapedgeremove.keySet());
for(AllocNode node : nodeSet) {
- /* Start with the new incoming edges */
- MySet<Edge> newheapedge=new MySet<Edge>(delta.baseheapedge.get(node));
- /* Remove the remove set */
- MySet<Edge> removeset=delta.heapedgeremove.get(node);
+ /* Start with the new incoming edges */
+ MySet<Edge> newheapedge=new MySet<Edge>(delta.baseheapedge.get(node));
+ /* Remove the remove set */
+ MySet<Edge> removeset=delta.heapedgeremove.get(node);
- if (removeset!=null)
- newheapedge.removeAll(removeset);
+ if (removeset!=null)
+ newheapedge.removeAll(removeset);
- /* Add in the add set */
- MySet<Edge> settoadd=delta.heapedgeadd.get(node);
- if (settoadd!=null)
- newheapedge.addAll(settoadd);
- newDelta.heapedgeadd.put(node, newheapedge);
+ /* Add in the add set */
+ MySet<Edge> settoadd=delta.heapedgeadd.get(node);
+ if (settoadd!=null)
+ newheapedge.addAll(settoadd);
+ newDelta.heapedgeadd.put(node, newheapedge);
- /* Remove the newly created edges..no need to propagate a diff for those */
- if (removeset!=null) {
- removeset.removeAll(delta.baseheapedge.get(node));
- newDelta.heapedgeremove.put(node, removeset);
- }
+ /* Remove the newly created edges..no need to propagate a diff for those */
+ if (removeset!=null) {
+ removeset.removeAll(delta.baseheapedge.get(node));
+ newDelta.heapedgeremove.put(node, removeset);
+ }
}
/* Compute new ages */
oldNodes.addAll(delta.baseOldNodes.keySet());
oldNodes.addAll(delta.addOldNodes.keySet());
for(AllocNode node : oldNodes) {
- if (delta.addOldNodes.containsKey(node)) {
- if (delta.addOldNodes.get(node).booleanValue()) {
- newDelta.addOldNodes.put(node, Boolean.TRUE);
- }
- } else {
- if (delta.baseOldNodes.get(node).booleanValue()) {
- newDelta.addOldNodes.put(node, Boolean.TRUE);
- }
- }
+ if (delta.addOldNodes.containsKey(node)) {
+ if (delta.addOldNodes.get(node).booleanValue()) {
+ newDelta.addOldNodes.put(node, Boolean.TRUE);
+ }
+ } else {
+ if (delta.baseOldNodes.get(node).booleanValue()) {
+ newDelta.addOldNodes.put(node, Boolean.TRUE);
+ }
+ }
}
}
if (!newDelta.heapedgeadd.isEmpty()||!newDelta.heapedgeremove.isEmpty()||!newDelta.varedgeadd.isEmpty()||!newDelta.addNodeAges.isEmpty()||!newDelta.addOldNodes.isEmpty()) {
/* We have a delta to propagate */
if (returnMap.containsKey(bblock)) {
- //exit of call block
- boolean first=true;
-
- for(PPoint caller : returnMap.get(bblock)) {
- //System.out.println("Sending Return BBlock to "+caller.getBBlock().nodes.get(caller.getIndex()).toString().replace(' ','_'));
- //newDelta.print();
- if (first) {
- newDelta.setBlock(caller);
- toprocess.add(newDelta);
- first=false;
- } else {
- Delta d=newDelta.diffBlock(caller);
- toprocess.add(d);
- }
- }
+ //exit of call block
+ boolean first=true;
+
+ for(PPoint caller : returnMap.get(bblock)) {
+ //System.out.println("Sending Return BBlock to "+caller.getBBlock().nodes.get(caller.getIndex()).toString().replace(' ','_'));
+ //newDelta.print();
+ if (first) {
+ newDelta.setBlock(caller);
+ toprocess.add(newDelta);
+ first=false;
+ } else {
+ Delta d=newDelta.diffBlock(caller);
+ toprocess.add(d);
+ }
+ }
} else {
- //normal block
- Vector<BBlock> blockvector=bblock.next();
- for(int i=0; i<blockvector.size(); i++) {
- //System.out.println("Sending BBlock to "+blockvector.get(i).nodes.get(0).toString().replace(' ','_'));
- //newDelta.print();
- if (i==0) {
- newDelta.setBlock(new PPoint(blockvector.get(i)));
- toprocess.add(newDelta);
- } else {
- Delta d=newDelta.diffBlock(new PPoint(blockvector.get(i)));
- toprocess.add(d);
- }
- }
+ //normal block
+ Vector<BBlock> blockvector=bblock.next();
+ for(int i=0; i<blockvector.size(); i++) {
+ //System.out.println("Sending BBlock to "+blockvector.get(i).nodes.get(0).toString().replace(' ','_'));
+ //newDelta.print();
+ if (i==0) {
+ newDelta.setBlock(new PPoint(blockvector.get(i)));
+ toprocess.add(newDelta);
+ } else {
+ Delta d=newDelta.diffBlock(new PPoint(blockvector.get(i)));
+ toprocess.add(d);
+ }
+ }
}
} else {
//System.out.println("EMPTY DELTA");
if (delta.getInit()) {
removeInitTaints(null, delta, graph);
for (TempDescriptor tmp : sese.getInVarSet()) {
- Taint taint=Taint.factory(sese, null, tmp, AllocFactory.dummySite, null, ReachGraph.predsEmpty);
- MySet<Edge> edges=GraphManip.getEdges(graph, delta, tmp);
- for(Edge e : edges) {
- Edge newe=e.addTaint(taint);
- delta.addVarEdge(newe);
- }
+ Taint taint=Taint.factory(sese, null, tmp, AllocFactory.dummySite, null, ReachGraph.predsEmpty);
+ MySet<Edge> edges=GraphManip.getEdges(graph, delta, tmp);
+ for(Edge e : edges) {
+ Edge newe=e.addTaint(taint);
+ delta.addVarEdge(newe);
+ }
}
} else {
removeDiffTaints(null, delta);
for (TempDescriptor tmp : sese.getInVarSet()) {
- Taint taint=Taint.factory(sese, null, tmp, AllocFactory.dummySite, null, ReachGraph.predsEmpty);
- MySet<Edge> edges=GraphManip.getDiffEdges(delta, tmp);
- for(Edge e : edges) {
- Edge newe=e.addTaint(taint);
- delta.addVarEdge(newe);
- }
+ Taint taint=Taint.factory(sese, null, tmp, AllocFactory.dummySite, null, ReachGraph.predsEmpty);
+ MySet<Edge> edges=GraphManip.getDiffEdges(delta, tmp);
+ for(Edge e : edges) {
+ Edge newe=e.addTaint(taint);
+ delta.addVarEdge(newe);
+ }
}
}
//Process delta edges
processEdgeMap(sese, delta.varedgeadd, null, null, edgestoremove, edgestoadd);
for(Edge e : edgestoremove) {
- delta.removeVarEdge(e);
+ delta.removeVarEdge(e);
}
for(Edge e : edgestoadd) {
- delta.addVarEdge(e);
+ delta.addVarEdge(e);
}
}
//Process delta edges
processEdgeMap(sese, delta.heapedgeadd, null, null, edgestoremove, edgestoadd);
for(Edge e : edgestoremove) {
- delta.removeHeapEdge(e);
+ delta.removeHeapEdge(e);
}
for(Edge e : edgestoadd) {
- delta.addHeapEdge(e);
+ delta.addHeapEdge(e);
}
}
}
//Process delta edges
processEdgeMap(sese, delta.varedgeadd, null, null, edgestoremove, edgestoadd);
for(Edge e : edgestoremove) {
- delta.removeVarEdge(e);
+ delta.removeVarEdge(e);
}
for(Edge e : edgestoadd) {
- delta.addVarEdge(e);
+ delta.addVarEdge(e);
}
}
//Process delta edges
processEdgeMap(sese, delta.heapedgeadd, null, null, edgestoremove, edgestoadd);
for(Edge e : edgestoremove) {
- delta.removeHeapEdge(e);
+ delta.removeHeapEdge(e);
}
for(Edge e : edgestoadd) {
- delta.addHeapEdge(e);
+ delta.addHeapEdge(e);
}
}
}
for(Map.Entry<?, MySet<Edge>> entry:edgemap.entrySet()) {
//If the parent map exists and overrides this entry, skip it
if (childmap!=null&&childmap.containsKey(entry.getKey()))
- continue;
+ continue;
for(Edge e:entry.getValue()) {
- //check whether this edge has been removed
- if (removemap!=null&&removemap.containsKey(entry.getKey())&&
- removemap.get(entry.getKey()).contains(e))
- continue;
- //have real edge
- TaintSet ts=e.getTaints();
- TaintSet newts=null;
- //update non-null taint set
- if (ts!=null)
- newts=Canonical.removeInContextTaintsNP(ts, sese);
- if (newts!=null&&newts!=ts) {
- edgestoremove.add(e);
- edgestoadd.add(e.changeTaintSet(newts));
- }
+ //check whether this edge has been removed
+ if (removemap!=null&&removemap.containsKey(entry.getKey())&&
+ removemap.get(entry.getKey()).contains(e))
+ continue;
+ //have real edge
+ TaintSet ts=e.getTaints();
+ TaintSet newts=null;
+ //update non-null taint set
+ if (ts!=null)
+ newts=Canonical.removeInContextTaintsNP(ts, sese);
+ if (newts!=null&&newts!=ts) {
+ edgestoremove.add(e);
+ edgestoadd.add(e.changeTaintSet(newts));
+ }
}
}
}
newDelta.varedgeadd.put(tmpthis, (MySet<Edge>)edges.clone());
edgeset.addAll(edges);
for(Edge e:edges) {
- AllocNode dstnode=e.dst;
- if (!nodeset.contains(dstnode)&&(oldnodeset==null||!oldnodeset.contains(dstnode))) {
- TypeDescriptor type=dstnode.getType();
- if (!type.isArray()) {
- targetSet.add(type.getClassDesc());
- } else {
- //arrays don't have code
- targetSet.add(typeUtil.getClass(TypeUtil.ObjectClass));
- }
- nodeset.add(dstnode);
- tovisit.add(dstnode);
- }
+ AllocNode dstnode=e.dst;
+ if (!nodeset.contains(dstnode)&&(oldnodeset==null||!oldnodeset.contains(dstnode))) {
+ TypeDescriptor type=dstnode.getType();
+ if (!type.isArray()) {
+ targetSet.add(type.getClassDesc());
+ } else {
+ //arrays don't have code
+ targetSet.add(typeUtil.getClass(TypeUtil.ObjectClass));
+ }
+ nodeset.add(dstnode);
+ tovisit.add(dstnode);
+ }
}
}
}
newDelta.varedgeadd.put(tmp, (MySet<Edge>)edges.clone());
edgeset.addAll(edges);
for(Edge e:edges) {
- if (!nodeset.contains(e.dst)) {
- nodeset.add(e.dst);
- tovisit.add(e.dst);
- }
+ if (!nodeset.contains(e.dst)) {
+ nodeset.add(e.dst);
+ tovisit.add(e.dst);
+ }
}
}
}
AllocNode node=tovisit.pop();
MySet<Edge> edges=GraphManip.getEdges(graph, delta, node);
if (!edges.isEmpty()) {
- newDelta.heapedgeadd.put(node, Edge.makeOld(edges));
- edgeset.addAll(edges);
- for(Edge e : edges) {
- if (!nodeset.contains(e.dst)&&(oldnodeset==null||!oldnodeset.contains(e.dst))) {
- nodeset.add(e.dst);
- tovisit.add(e.dst);
- }
- }
+ newDelta.heapedgeadd.put(node, Edge.makeOld(edges));
+ edgeset.addAll(edges);
+ for(Edge e : edges) {
+ if (!nodeset.contains(e.dst)&&(oldnodeset==null||!oldnodeset.contains(e.dst))) {
+ nodeset.add(e.dst);
+ tovisit.add(e.dst);
+ }
+ }
}
}
}
} else {
//Compute Edges
for(Edge e : newDelta.varedgeadd.get(tmpthis)) {
- AllocNode node=e.dst;
- ClassDescriptor cd=node.getType().getClassDesc();
- //Figure out exact method called and add to set
- MethodDescriptor calledmd=cd.getCalledMethod(md);
- targets.add(calledmd);
+ AllocNode node=e.dst;
+ ClassDescriptor cd=node.getType().getClassDesc();
+ //Figure out exact method called and add to set
+ MethodDescriptor calledmd=cd.getCalledMethod(md);
+ targets.add(calledmd);
}
}
return targets;
HashMap<TempDescriptor, TempDescriptor> tmpMap=new HashMap<TempDescriptor, TempDescriptor>();
int offset=0;
if(tmpthis!=null) {
- tmpMap.put(tmpthis, fm.getParameter(offset++));
+ tmpMap.put(tmpthis, fm.getParameter(offset++));
}
for(int i=0; i<fcall.numArgs(); i++) {
- TempDescriptor tmp=fcall.getArg(i);
- tmpMap.put(tmp,fm.getParameter(i+offset));
+ TempDescriptor tmp=fcall.getArg(i);
+ tmpMap.put(tmp,fm.getParameter(i+offset));
}
//Get basicblock for the method
//Hook up exits
if (!callMap.containsKey(fcall)) {
- callMap.put(fcall, new HashSet<BBlock>());
+ callMap.put(fcall, new HashSet<BBlock>());
}
Delta returnDelta=null;
if (!callMap.get(fcall).contains(block.getStart())) {
- callMap.get(fcall).add(block.getStart());
- newmethod=true;
-
- //Hook up return
- if (!returnMap.containsKey(block.getExit())) {
- returnMap.put(block.getExit(), new HashSet<PPoint>());
- }
- returnMap.get(block.getExit()).add(new PPoint(callblock, callindex));
-
- if (bbgraphMap.containsKey(block.getExit())) {
- //Need to push existing results to current node
- if (returnDelta==null) {
- returnDelta=new Delta(null, false);
- Vector<FlatNode> exitblocknodes=block.getExit().nodes();
- FlatExit fexit=(FlatExit)exitblocknodes.get(exitblocknodes.size()-1);
- buildInitDelta(graphMap.get(fexit), returnDelta);
- if (!returnDelta.heapedgeadd.isEmpty()||!returnDelta.heapedgeremove.isEmpty()||!returnDelta.varedgeadd.isEmpty()) {
- returnDelta.setBlock(new PPoint(callblock, callindex));
- toprocess.add(returnDelta);
- }
- } else {
- if (!returnDelta.heapedgeadd.isEmpty()||!returnDelta.heapedgeremove.isEmpty()||!returnDelta.varedgeadd.isEmpty()) {
- toprocess.add(returnDelta.diffBlock(new PPoint(callblock, callindex)));
- }
- }
- }
+ callMap.get(fcall).add(block.getStart());
+ newmethod=true;
+
+ //Hook up return
+ if (!returnMap.containsKey(block.getExit())) {
+ returnMap.put(block.getExit(), new HashSet<PPoint>());
+ }
+ returnMap.get(block.getExit()).add(new PPoint(callblock, callindex));
+
+ if (bbgraphMap.containsKey(block.getExit())) {
+ //Need to push existing results to current node
+ if (returnDelta==null) {
+ returnDelta=new Delta(null, false);
+ Vector<FlatNode> exitblocknodes=block.getExit().nodes();
+ FlatExit fexit=(FlatExit)exitblocknodes.get(exitblocknodes.size()-1);
+ buildInitDelta(graphMap.get(fexit), returnDelta);
+ if (!returnDelta.heapedgeadd.isEmpty()||!returnDelta.heapedgeremove.isEmpty()||!returnDelta.varedgeadd.isEmpty()) {
+ returnDelta.setBlock(new PPoint(callblock, callindex));
+ toprocess.add(returnDelta);
+ }
+ } else {
+ if (!returnDelta.heapedgeadd.isEmpty()||!returnDelta.heapedgeremove.isEmpty()||!returnDelta.varedgeadd.isEmpty()) {
+ toprocess.add(returnDelta.diffBlock(new PPoint(callblock, callindex)));
+ }
+ }
+ }
}
if (oldedgeset==null) {
- //First build of this graph
- //Build and enqueue delta...safe to just use existing delta
- Delta d=newDelta.changeParams(tmpMap, new PPoint(block.getStart()));
- //System.out.println("AProcessing "+block.getStart().nodes.get(0).toString().replace(' ','_'));
- //d.print();
- toprocess.add(d);
+ //First build of this graph
+ //Build and enqueue delta...safe to just use existing delta
+ Delta d=newDelta.changeParams(tmpMap, new PPoint(block.getStart()));
+ //System.out.println("AProcessing "+block.getStart().nodes.get(0).toString().replace(' ','_'));
+ //d.print();
+ toprocess.add(d);
} else if (newmethod) {
- if (basedelta==null) {
- basedelta=newDelta.buildBase(oldedgeset);
- }
- //Build and enqueue delta
- Delta d=basedelta.changeParams(tmpMap, new PPoint(block.getStart()));
- //System.out.println("BProcessing "+block.getStart().nodes.get(0).toString().replace(' ','_'));
- //d.print();
- toprocess.add(d);
+ if (basedelta==null) {
+ basedelta=newDelta.buildBase(oldedgeset);
+ }
+ //Build and enqueue delta
+ Delta d=basedelta.changeParams(tmpMap, new PPoint(block.getStart()));
+ //System.out.println("BProcessing "+block.getStart().nodes.get(0).toString().replace(' ','_'));
+ //d.print();
+ toprocess.add(d);
} else {
- //Build and enqueue delta
- Delta d=newDelta.changeParams(tmpMap, new PPoint(block.getStart()));
- //System.out.println("CProcessing "+block.getStart().nodes.get(0).toString().replace(' ','_'));
- //d.print();
- toprocess.add(d);
+ //Build and enqueue delta
+ Delta d=newDelta.changeParams(tmpMap, new PPoint(block.getStart()));
+ //System.out.println("CProcessing "+block.getStart().nodes.get(0).toString().replace(' ','_'));
+ //d.print();
+ toprocess.add(d);
}
}
}
edges.addAll(delta.heapedgeadd.get(extNode));
for(Edge e : edges) {
- if (nodeset.contains(e.dst))
- externaledgeset.add(e);
+ if (nodeset.contains(e.dst))
+ externaledgeset.add(e);
}
}
edges.addAll(delta.varedgeadd.get(tmp));
for(Edge e : edges) {
- if (nodeset.contains(e.dst))
- externaledgeset.add(e);
+ if (nodeset.contains(e.dst))
+ externaledgeset.add(e);
}
}
}
//Want to remove the set of internal edges
for(Edge e : edgeset) {
if (e.src!=null&&!graph.callerEdges.contains(e)) {
- delta.removeHeapEdge(e);
+ delta.removeHeapEdge(e);
}
}
for(Edge e : externaledgeset) {
//want to remove the set of internal edges
if (!graph.callerEdges.contains(e))
- delta.removeEdge(e);
+ delta.removeEdge(e);
}
}
TempDescriptor tmpthis=fcall.getThis();
//Fix up delta to get rid of unnecessary heap edge removals
for(Map.Entry<AllocNode, MySet<Edge>> entry : delta.heapedgeremove.entrySet()) {
- for(Iterator<Edge> eit=entry.getValue().iterator(); eit.hasNext(); ) {
- Edge e=eit.next();
- if (graph.callerEdges.contains(e))
- eit.remove();
- }
+ for(Iterator<Edge> eit=entry.getValue().iterator(); eit.hasNext(); ) {
+ Edge e=eit.next();
+ if (graph.callerEdges.contains(e))
+ eit.remove();
+ }
}
//Fix up delta to get rid of unnecessary var edge removals
for(Map.Entry<TempDescriptor, MySet<Edge>> entry : delta.varedgeremove.entrySet()) {
- for(Iterator<Edge> eit=entry.getValue().iterator(); eit.hasNext(); ) {
- Edge e=eit.next();
- if (graph.callerEdges.contains(e))
- eit.remove();
- }
+ for(Iterator<Edge> eit=entry.getValue().iterator(); eit.hasNext(); ) {
+ Edge e=eit.next();
+ if (graph.callerEdges.contains(e))
+ eit.remove();
+ }
}
//Handle the this temp
MySet<Edge> newedges=GraphManip.getDiffEdges(delta, oldnodeset);
edgeset.addAll(newedges);
for(Edge e : newedges) {
- //Add new edges that start from old node to newDelta
- AllocNode src=e.src;
- if (!newDelta.heapedgeadd.containsKey(src)) {
- newDelta.heapedgeadd.put(src, new MySet<Edge>());
- }
- newDelta.heapedgeadd.get(src).add(e.makeOld());
- if (!nodeset.contains(e.dst)&&!oldnodeset.contains(e.dst)) {
- nodeset.add(e.dst);
- tovisit.add(e.dst);
- }
+ //Add new edges that start from old node to newDelta
+ AllocNode src=e.src;
+ if (!newDelta.heapedgeadd.containsKey(src)) {
+ newDelta.heapedgeadd.put(src, new MySet<Edge>());
+ }
+ newDelta.heapedgeadd.get(src).add(e.makeOld());
+ if (!nodeset.contains(e.dst)&&!oldnodeset.contains(e.dst)) {
+ nodeset.add(e.dst);
+ tovisit.add(e.dst);
+ }
}
//Traverse all reachable nodes
Set<FlatSESEEnterNode> seseCallers=OoOJava?taskAnalysis.getTransitiveExecutingRBlocks(fcall):null;
//Check if the new nodes allow us to insert a new edge
for(AllocNode node : nodeset) {
- if (graph.callNewEdges.containsKey(node)) {
- for(Iterator<Edge> eit=graph.callNewEdges.get(node).iterator(); eit.hasNext(); ) {
- Edge e=eit.next();
- if ((graph.callNodeAges.contains(e.src)||graph.reachNode.contains(e.src))&&
- (graph.callNodeAges.contains(e.dst)||graph.reachNode.contains(e.dst))) {
- Edge edgetoadd=e.copy(); //we need our own copy to modify below
- eit.remove();
- if (seseCallers!=null)
- edgetoadd.taintModify(seseCallers);
- mergeCallEdge(graph, delta, edgetoadd);
- }
- }
- }
+ if (graph.callNewEdges.containsKey(node)) {
+ for(Iterator<Edge> eit=graph.callNewEdges.get(node).iterator(); eit.hasNext(); ) {
+ Edge e=eit.next();
+ if ((graph.callNodeAges.contains(e.src)||graph.reachNode.contains(e.src))&&
+ (graph.callNodeAges.contains(e.dst)||graph.reachNode.contains(e.dst))) {
+ Edge edgetoadd=e.copy(); //we need our own copy to modify below
+ eit.remove();
+ if (seseCallers!=null)
+ edgetoadd.taintModify(seseCallers);
+ mergeCallEdge(graph, delta, edgetoadd);
+ }
+ }
+ }
}
for(Edge e : edgeset) {
- //See if these edges would allow an old edge to be added
- if (graph.callOldEdges.containsKey(e)) {
- for(Edge adde : graph.callOldEdges.get(e)) {
- Edge ecopy=adde.copy();
- ecopy.statuspredicate=e.statuspredicate;
- mergeCallEdge(graph, delta, ecopy);
- }
- }
+ //See if these edges would allow an old edge to be added
+ if (graph.callOldEdges.containsKey(e)) {
+ for(Edge adde : graph.callOldEdges.get(e)) {
+ Edge ecopy=adde.copy();
+ ecopy.statuspredicate=e.statuspredicate;
+ mergeCallEdge(graph, delta, ecopy);
+ }
+ }
}
//Add in new external edges
MySet<Edge> edgeset=entry.getValue();
for(Edge e : edgeset) {
- Edge copy=e.copy();
- boolean rewrite=false;
- if (copy.dst!=null&&graph.callNodeAges.contains(copy.dst)) {
- copy.dst=allocFactory.getAllocNode(copy.dst, true);
- rewrite=true;
- }
- if (rewrite) {
- edgestoremove.add(e);
- edgestoadd.add(copy);
- }
+ Edge copy=e.copy();
+ boolean rewrite=false;
+ if (copy.dst!=null&&graph.callNodeAges.contains(copy.dst)) {
+ copy.dst=allocFactory.getAllocNode(copy.dst, true);
+ rewrite=true;
+ }
+ if (rewrite) {
+ edgestoremove.add(e);
+ edgestoadd.add(copy);
+ }
}
}
for(Edge e : edgestoremove) {
if (!graph.callerEdges.contains(e))
- delta.removeVarEdge(e);
+ delta.removeVarEdge(e);
}
for(Edge e : edgestoadd) {
delta.addVarEdge(e);
MySet<Edge> edgeset=entry.getValue();
for(Edge e : edgeset) {
- Edge copy=e.copy();
- boolean rewrite=false;
- if (copy.src!=null&&graph.callNodeAges.contains(copy.src)) {
- copy.src=allocFactory.getAllocNode(copy.src, true);
- rewrite=true;
- }
- if (copy.dst!=null&&graph.callNodeAges.contains(copy.dst)) {
- copy.dst=allocFactory.getAllocNode(copy.dst, true);
- rewrite=true;
- }
- if (rewrite) {
- edgestoremove.add(e);
- edgestoadd.add(copy);
- }
+ Edge copy=e.copy();
+ boolean rewrite=false;
+ if (copy.src!=null&&graph.callNodeAges.contains(copy.src)) {
+ copy.src=allocFactory.getAllocNode(copy.src, true);
+ rewrite=true;
+ }
+ if (copy.dst!=null&&graph.callNodeAges.contains(copy.dst)) {
+ copy.dst=allocFactory.getAllocNode(copy.dst, true);
+ rewrite=true;
+ }
+ if (rewrite) {
+ edgestoremove.add(e);
+ edgestoadd.add(copy);
+ }
}
}
for(Edge e : edgestoremove) {
if (!graph.callerEdges.contains(e))
- delta.removeHeapEdge(e);
+ delta.removeHeapEdge(e);
}
for(Edge e : edgestoadd) {
delta.addHeapEdge(e);
//First did we age the source
Edge newedge=e.copy();
if (newedge.src!=null&&!e.src.isSummary()&&graph.callNodeAges.contains(e.src)) {
- AllocNode summaryNode=allocFactory.getAllocNode(newedge.src, true);
- newedge.src=summaryNode;
+ AllocNode summaryNode=allocFactory.getAllocNode(newedge.src, true);
+ newedge.src=summaryNode;
}
//Compute target
if (graph.callNodeAges.contains(e.dst)&&!e.dst.isSummary()) {
- if (graph.callOldNodes.contains(e.dst)) {
- //Need two edges
- Edge copy=newedge.copy();
- mergeEdge(graph, newDelta, copy);
- }
- //Now add summarized node
- newedge.dst=allocFactory.getAllocNode(newedge.dst, true);
- mergeCallEdge(graph, newDelta, newedge);
+ if (graph.callOldNodes.contains(e.dst)) {
+ //Need two edges
+ Edge copy=newedge.copy();
+ mergeEdge(graph, newDelta, copy);
+ }
+ //Now add summarized node
+ newedge.dst=allocFactory.getAllocNode(newedge.dst, true);
+ mergeCallEdge(graph, newDelta, newedge);
} else {
- //Add edge to single node
- mergeEdge(graph, newDelta, newedge);
+ //Add edge to single node
+ mergeEdge(graph, newDelta, newedge);
}
}
}
for(Iterator<AllocNode> nodeit=delta.addNodeAges.iterator(); nodeit.hasNext(); ) {
AllocNode node=nodeit.next();
if (!graph.callNodeAges.contains(node)) {
- graph.callNodeAges.add(node);
- newDelta.addNodeAges.add(node);
+ graph.callNodeAges.add(node);
+ newDelta.addNodeAges.add(node);
}
AllocNode summaryAdd=null;
if (!graph.reachNode.contains(node)&&!node.isSummary()) {
- /* Need to age node in existing graph*/
+ /* Need to age node in existing graph*/
- AllocNode summaryNode=allocFactory.getAllocNode(node, true);
+ AllocNode summaryNode=allocFactory.getAllocNode(node, true);
- if (!graph.callNodeAges.contains(summaryNode)) {
- graph.callNodeAges.add(summaryNode);
- newDelta.addNodeAges.add(summaryNode);
- summaryAdd=summaryNode;
- }
- summarizeInGraph(graph, newDelta, node);
+ if (!graph.callNodeAges.contains(summaryNode)) {
+ graph.callNodeAges.add(summaryNode);
+ newDelta.addNodeAges.add(summaryNode);
+ summaryAdd=summaryNode;
+ }
+ summarizeInGraph(graph, newDelta, node);
}
do {
- if (graph.callNewEdges.containsKey(node)) {
- for(Iterator<Edge> eit=graph.callNewEdges.get(node).iterator(); eit.hasNext(); ) {
- Edge e=eit.next();
- if ((graph.callNodeAges.contains(e.src)||graph.reachNode.contains(e.src))&&
- (graph.callNodeAges.contains(e.dst)||graph.reachNode.contains(e.dst))) {
- Edge edgetoadd=e.copy(); //we need our own copy to modify below
- eit.remove();
- if (seseCallers!=null)
- edgetoadd.taintModify(seseCallers);
- mergeCallEdge(graph, newDelta, edgetoadd);
- }
- }
- }
- //do the summary node if we added that also...
- node=summaryAdd;
- summaryAdd=null;
+ if (graph.callNewEdges.containsKey(node)) {
+ for(Iterator<Edge> eit=graph.callNewEdges.get(node).iterator(); eit.hasNext(); ) {
+ Edge e=eit.next();
+ if ((graph.callNodeAges.contains(e.src)||graph.reachNode.contains(e.src))&&
+ (graph.callNodeAges.contains(e.dst)||graph.reachNode.contains(e.dst))) {
+ Edge edgetoadd=e.copy(); //we need our own copy to modify below
+ eit.remove();
+ if (seseCallers!=null)
+ edgetoadd.taintModify(seseCallers);
+ mergeCallEdge(graph, newDelta, edgetoadd);
+ }
+ }
+ }
+ //do the summary node if we added that also...
+ node=summaryAdd;
+ summaryAdd=null;
} while(node!=null);
}
//Add heap edges in
for(Map.Entry<AllocNode, MySet<Edge>> entry : delta.heapedgeadd.entrySet()) {
for(Edge e : entry.getValue()) {
- boolean addedge=false;
- Edge edgetoadd=null;
- if (e.statuspredicate==Edge.NEW) {
- if ((graph.callNodeAges.contains(e.src)||graph.reachNode.contains(e.src))&&
- (graph.callNodeAges.contains(e.dst)||graph.reachNode.contains(e.dst))) {
- edgetoadd=e.copy(); //we need our own copy to modify below
- } else {
- graph.addCallEdge(e);
- }
- } else {
- Edge[] edgeArray=e.makeStatus(allocFactory);
-
- int statuspredicate=0;
- for(int i=0; i<edgeArray.length; i++) {
- Edge origEdgeKey=edgeArray[i];
- if (graph.reachEdge.contains(origEdgeKey)) {
- Edge origEdge=graph.reachEdge.get(origEdgeKey);
- //copy the predicate
- statuspredicate=statuspredicate|origEdge.statuspredicate;
- }
- if (!graph.callOldEdges.containsKey(origEdgeKey)) {
- graph.callOldEdges.put(origEdgeKey, new MySet<Edge>());
- }
- if (graph.callOldEdges.get(origEdgeKey).contains(e)) {
- Edge olde=graph.callOldEdges.get(origEdgeKey).get(e);
- graph.callOldEdges.get(origEdgeKey).add(olde.merge(e));
- } else {
- graph.callOldEdges.get(origEdgeKey).add(e);
- }
- }
- if (statuspredicate!=0) {
- Edge newe=e.copy();
- newe.statuspredicate=statuspredicate;
- edgetoadd=newe;
- }
- }
- if (seseCallers!=null&&edgetoadd!=null)
- edgetoadd.taintModify(seseCallers);
- mergeCallEdge(graph, newDelta, edgetoadd);
+ boolean addedge=false;
+ Edge edgetoadd=null;
+ if (e.statuspredicate==Edge.NEW) {
+ if ((graph.callNodeAges.contains(e.src)||graph.reachNode.contains(e.src))&&
+ (graph.callNodeAges.contains(e.dst)||graph.reachNode.contains(e.dst))) {
+ edgetoadd=e.copy(); //we need our own copy to modify below
+ } else {
+ graph.addCallEdge(e);
+ }
+ } else {
+ Edge[] edgeArray=e.makeStatus(allocFactory);
+
+ int statuspredicate=0;
+ for(int i=0; i<edgeArray.length; i++) {
+ Edge origEdgeKey=edgeArray[i];
+ if (graph.reachEdge.contains(origEdgeKey)) {
+ Edge origEdge=graph.reachEdge.get(origEdgeKey);
+ //copy the predicate
+ statuspredicate=statuspredicate|origEdge.statuspredicate;
+ }
+ if (!graph.callOldEdges.containsKey(origEdgeKey)) {
+ graph.callOldEdges.put(origEdgeKey, new MySet<Edge>());
+ }
+ if (graph.callOldEdges.get(origEdgeKey).contains(e)) {
+ Edge olde=graph.callOldEdges.get(origEdgeKey).get(e);
+ graph.callOldEdges.get(origEdgeKey).add(olde.merge(e));
+ } else {
+ graph.callOldEdges.get(origEdgeKey).add(e);
+ }
+ }
+ if (statuspredicate!=0) {
+ Edge newe=e.copy();
+ newe.statuspredicate=statuspredicate;
+ edgetoadd=newe;
+ }
+ }
+ if (seseCallers!=null&&edgetoadd!=null)
+ edgetoadd.taintModify(seseCallers);
+ mergeCallEdge(graph, newDelta, edgetoadd);
}
}
if (fcall.getReturnTemp()!=null) {
MySet<Edge> returnedge=delta.varedgeadd.get(returntmp);
if (returnedge!=null)
- for(Edge e : returnedge) {
- //skip the edge if types don't allow it...
- if (!typeUtil.isSuperorType(fcall.getReturnTemp().getType(), e.dst.getType()))
- continue;
- Edge newedge=e.copy();
- newedge.srcvar=fcall.getReturnTemp();
- if (seseCallers!=null)
- newedge.taintModify(seseCallers);
- mergeEdge(graph, newDelta, newedge);
- }
+ for(Edge e : returnedge) {
+ //skip the edge if types don't allow it...
+ if (!typeUtil.isSuperorType(fcall.getReturnTemp().getType(), e.dst.getType()))
+ continue;
+ Edge newedge=e.copy();
+ newedge.srcvar=fcall.getReturnTemp();
+ if (seseCallers!=null)
+ newedge.taintModify(seseCallers);
+ mergeEdge(graph, newDelta, newedge);
+ }
}
applyDiffs(graph, newDelta);
return newDelta;
Edge match=graph.getMatch(edgetoadd);
if (match==null||!match.subsumes(edgetoadd)) {
- Edge mergededge=edgetoadd.merge(match);
- newDelta.addEdge(mergededge);
+ Edge mergededge=edgetoadd.merge(match);
+ newDelta.addEdge(mergededge);
}
}
}
Edge match=graph.getMatch(edgetoadd);
if (match==null||!match.subsumes(edgetoadd)) {
- Edge mergededge=edgetoadd.merge(match);
- newDelta.addEdge(mergededge);
- graph.callerEdges.add(mergededge);
+ Edge mergededge=edgetoadd.merge(match);
+ newDelta.addEdge(mergededge);
+ graph.callerEdges.add(mergededge);
}
}
}
MySet<Edge> backedges=graph.getBackEdges(singleNode);
for(Edge e : backedges) {
if (e.dst==singleNode) {
- //Need to get original edge so that predicate will be correct
- Edge match=graph.getMatch(e);
- if (match!=null) {
- Edge rewrite=match.rewrite(singleNode, summaryNode);
- newDelta.removeEdge(match);
- mergeCallEdge(graph, newDelta, rewrite);
- }
+ //Need to get original edge so that predicate will be correct
+ Edge match=graph.getMatch(e);
+ if (match!=null) {
+ Edge rewrite=match.rewrite(singleNode, summaryNode);
+ newDelta.removeEdge(match);
+ mergeCallEdge(graph, newDelta, rewrite);
+ }
}
}
}
if (genbackwards&&graph.backMap==null) {
graph.backMap=new HashMap<AllocNode, MySet<Edge>>();
if (graph.parent.backMap==null) {
- graph.parent.backMap=new HashMap<AllocNode, MySet<Edge>>();
- for(Map.Entry<AllocNode, MySet<Edge>> entry : graph.nodeMap.entrySet()) {
- for(Edge e : entry.getValue()) {
- if (!graph.parent.backMap.containsKey(e.dst))
- graph.parent.backMap.put(e.dst, new MySet<Edge>());
- graph.parent.backMap.get(e.dst).add(e);
- }
- }
- for(Map.Entry<TempDescriptor, MySet<Edge>> entry : graph.varMap.entrySet()) {
- for(Edge e : entry.getValue()) {
- if (!graph.parent.backMap.containsKey(e.dst))
- graph.parent.backMap.put(e.dst, new MySet<Edge>());
- graph.parent.backMap.get(e.dst).add(e);
- }
- }
+ graph.parent.backMap=new HashMap<AllocNode, MySet<Edge>>();
+ for(Map.Entry<AllocNode, MySet<Edge>> entry : graph.nodeMap.entrySet()) {
+ for(Edge e : entry.getValue()) {
+ if (!graph.parent.backMap.containsKey(e.dst))
+ graph.parent.backMap.put(e.dst, new MySet<Edge>());
+ graph.parent.backMap.get(e.dst).add(e);
+ }
+ }
+ for(Map.Entry<TempDescriptor, MySet<Edge>> entry : graph.varMap.entrySet()) {
+ for(Edge e : entry.getValue()) {
+ if (!graph.parent.backMap.containsKey(e.dst))
+ graph.parent.backMap.put(e.dst, new MySet<Edge>());
+ graph.parent.backMap.get(e.dst).add(e);
+ }
+ }
}
}
AllocNode node=e.getKey();
MySet<Edge> edges=e.getValue();
if (graph.nodeMap.containsKey(node)) {
- MySet<Edge> nodeEdges=graph.nodeMap.get(node);
- nodeEdges.addAll(edges);
+ MySet<Edge> nodeEdges=graph.nodeMap.get(node);
+ nodeEdges.addAll(edges);
}
}
AllocNode node=e.getKey();
MySet<Edge> edgestoremove=e.getValue();
if (graph.nodeMap.containsKey(node)) {
- //Just apply diff to current map
- graph.nodeMap.get(node).removeAll(edgestoremove);
+ //Just apply diff to current map
+ graph.nodeMap.get(node).removeAll(edgestoremove);
} else {
- //Generate diff from parent graph
- MySet<Edge> parentedges=graph.parent.nodeMap.get(node);
- if (parentedges!=null) {
- MySet<Edge> newedgeset=Util.setSubtract(parentedges, edgestoremove);
- graph.nodeMap.put(node, newedgeset);
- }
+ //Generate diff from parent graph
+ MySet<Edge> parentedges=graph.parent.nodeMap.get(node);
+ if (parentedges!=null) {
+ MySet<Edge> newedgeset=Util.setSubtract(parentedges, edgestoremove);
+ graph.nodeMap.put(node, newedgeset);
+ }
}
}
MySet<Edge> edgestoadd=e.getValue();
//If we have not done a subtract, then
if (!graph.nodeMap.containsKey(node)) {
- //Copy the parent entry
- if (graph.parent.nodeMap.containsKey(node))
- graph.nodeMap.put(node, (MySet<Edge>)graph.parent.nodeMap.get(node).clone());
- else
- graph.nodeMap.put(node, new MySet<Edge>());
+ //Copy the parent entry
+ if (graph.parent.nodeMap.containsKey(node))
+ graph.nodeMap.put(node, (MySet<Edge>)graph.parent.nodeMap.get(node).clone());
+ else
+ graph.nodeMap.put(node, new MySet<Edge>());
}
Edge.mergeEdgesInto(graph.nodeMap.get(node),edgestoadd);
if (genbackwards) {
- for(Edge eadd : edgestoadd) {
- if (!graph.backMap.containsKey(eadd.dst))
- graph.backMap.put(eadd.dst, new MySet<Edge>());
- graph.backMap.get(eadd.dst).add(eadd);
- }
+ for(Edge eadd : edgestoadd) {
+ if (!graph.backMap.containsKey(eadd.dst))
+ graph.backMap.put(eadd.dst, new MySet<Edge>());
+ graph.backMap.get(eadd.dst).add(eadd);
+ }
}
}
MySet<Edge> edgestoremove=e.getValue();
if (graph.varMap.containsKey(tmp)) {
- //Just apply diff to current map
- graph.varMap.get(tmp).removeAll(edgestoremove);
+ //Just apply diff to current map
+ graph.varMap.get(tmp).removeAll(edgestoremove);
} else if (graph.parent.varMap.containsKey(tmp)) {
- //Generate diff from parent graph
- MySet<Edge> parentedges=graph.parent.varMap.get(tmp);
- MySet<Edge> newedgeset=Util.setSubtract(parentedges, edgestoremove);
- graph.varMap.put(tmp, newedgeset);
+ //Generate diff from parent graph
+ MySet<Edge> parentedges=graph.parent.varMap.get(tmp);
+ MySet<Edge> newedgeset=Util.setSubtract(parentedges, edgestoremove);
+ graph.varMap.put(tmp, newedgeset);
}
}
TempDescriptor tmp=e.getKey();
MySet<Edge> edgestoadd=e.getValue();
if (graph.varMap.containsKey(tmp)) {
- Edge.mergeEdgesInto(graph.varMap.get(tmp), edgestoadd);
+ Edge.mergeEdgesInto(graph.varMap.get(tmp), edgestoadd);
} else if (graph.parent.varMap.containsKey(tmp)) {
- graph.varMap.put(tmp, new MySet<Edge>(graph.parent.varMap.get(tmp)));
- Edge.mergeEdgesInto(graph.varMap.get(tmp), edgestoadd);
+ graph.varMap.put(tmp, new MySet<Edge>(graph.parent.varMap.get(tmp)));
+ Edge.mergeEdgesInto(graph.varMap.get(tmp), edgestoadd);
} else
- graph.varMap.put(tmp, (MySet<Edge>)edgestoadd.clone());
+ graph.varMap.put(tmp, (MySet<Edge>)edgestoadd.clone());
if (genbackwards) {
- for(Edge eadd : edgestoadd) {
- if (!graph.backMap.containsKey(eadd.dst))
- graph.backMap.put(eadd.dst, new MySet<Edge>());
- graph.backMap.get(eadd.dst).add(eadd);
- }
+ for(Edge eadd : edgestoadd) {
+ if (!graph.backMap.containsKey(eadd.dst))
+ graph.backMap.put(eadd.dst, new MySet<Edge>());
+ graph.backMap.get(eadd.dst).add(eadd);
+ }
}
}
MySet<Edge> dstEdges=GraphManip.getEdges(graph, delta, dst);
if (OoOJava&&!accessible.isAccessible(node, dst)) {
- Taint dstStallTaint=Taint.factory(node, dst, AllocFactory.dummySite, null, ReachGraph.predsEmpty);
- dstEdges=Edge.taintAll(dstEdges, dstStallTaint);
- updateVarDelta(graph, delta, dst, dstEdges, null);
+ Taint dstStallTaint=Taint.factory(node, dst, AllocFactory.dummySite, null, ReachGraph.predsEmpty);
+ dstEdges=Edge.taintAll(dstEdges, dstStallTaint);
+ updateVarDelta(graph, delta, dst, dstEdges, null);
}
if (OoOJava) {
- effectsAnalysis.analyzeFlatSetFieldNode(dstEdges, fd, node);
+ effectsAnalysis.analyzeFlatSetFieldNode(dstEdges, fd, node);
}
//Do nothing for non pointers
if (!src.getType().isPtr()) {
- if (mustProcess.contains(node)) {
- applyDiffs(graph, delta);
- }
- return delta;
+ if (mustProcess.contains(node)) {
+ applyDiffs(graph, delta);
+ }
+ return delta;
}
MySet<Edge> srcEdges=GraphManip.getEdges(graph, delta, src);
if (OoOJava&&!accessible.isAccessible(node, src)) {
- Taint srcStallTaint=Taint.factory(node, src, AllocFactory.dummySite, null, ReachGraph.predsEmpty);
- srcEdges=Edge.taintAll(srcEdges, srcStallTaint);
- updateVarDelta(graph, delta, src, srcEdges, null);
+ Taint srcStallTaint=Taint.factory(node, src, AllocFactory.dummySite, null, ReachGraph.predsEmpty);
+ srcEdges=Edge.taintAll(srcEdges, srcStallTaint);
+ updateVarDelta(graph, delta, src, srcEdges, null);
}
MySet<Edge> edgesToAdd=GraphManip.genEdges(dstEdges, fd, srcEdges);
MySet<Edge> edgesToRemove=null;
if (dstEdges.size()==1&&!dstEdges.iterator().next().dst.isSummary()&&fd!=null) {
- /* Can do a strong update */
- edgesToRemove=GraphManip.getEdges(graph, delta, dstEdges, fd);
- graph.strongUpdateSet=edgesToRemove;
+ /* Can do a strong update */
+ edgesToRemove=GraphManip.getEdges(graph, delta, dstEdges, fd);
+ graph.strongUpdateSet=edgesToRemove;
} else
- graph.strongUpdateSet=new MySet<Edge>();
+ graph.strongUpdateSet=new MySet<Edge>();
/* Update diff */
updateHeapDelta(graph, delta, edgesToAdd, edgesToRemove);
MySet<Edge> newDstEdges=GraphManip.getDiffEdges(delta, dst);
if (OoOJava&&!accessible.isAccessible(node, dst)) {
- Taint dstStallTaint=Taint.factory(node, dst, AllocFactory.dummySite, null, ReachGraph.predsEmpty);
- newDstEdges=Edge.taintAll(newDstEdges, dstStallTaint);
- updateVarDelta(graph, delta, dst, newDstEdges, null);
+ Taint dstStallTaint=Taint.factory(node, dst, AllocFactory.dummySite, null, ReachGraph.predsEmpty);
+ newDstEdges=Edge.taintAll(newDstEdges, dstStallTaint);
+ updateVarDelta(graph, delta, dst, newDstEdges, null);
}
if (OoOJava) {
- effectsAnalysis.analyzeFlatSetFieldNode(newDstEdges, fd, node);
+ effectsAnalysis.analyzeFlatSetFieldNode(newDstEdges, fd, node);
}
if (!src.getType().isPtr()) {
- if (mustProcess.contains(node)) {
- applyDiffs(graph, delta);
- }
- return delta;
+ if (mustProcess.contains(node)) {
+ applyDiffs(graph, delta);
+ }
+ return delta;
}
/* Next look at new sources */
HashSet<AllocNode> dstNodes=GraphManip.getNodes(graph, delta, dst);
if (OoOJava&&!accessible.isAccessible(node, src)) {
- Taint srcStallTaint=Taint.factory(node, src, AllocFactory.dummySite, null, ReachGraph.predsEmpty);
- newSrcEdges=Edge.taintAll(newSrcEdges, srcStallTaint);
- updateVarDelta(graph, delta, src, newSrcEdges, null);
+ Taint srcStallTaint=Taint.factory(node, src, AllocFactory.dummySite, null, ReachGraph.predsEmpty);
+ newSrcEdges=Edge.taintAll(newSrcEdges, srcStallTaint);
+ updateVarDelta(graph, delta, src, newSrcEdges, null);
}
MySet<Edge> edgesToRemove=null;
if (newDstEdges.size()!=0) {
- if (dstNodes.size()>1&&!dstNodes.iterator().next().isSummary()&&fd!=null) {
- /* Need to undo strong update */
- if (graph.strongUpdateSet!=null) {
- edgesToAdd.addAll(graph.strongUpdateSet);
- graph.strongUpdateSet=null; //Prevent future strong updates
- }
- } else if (dstNodes.size()==1&&newDstEdges.size()==1&&!newDstEdges.iterator().next().dst.isSummary()&&graph.strongUpdateSet!=null&&fd!=null) {
- edgesToRemove=GraphManip.getEdges(graph, delta, dstNodes, fd);
- graph.strongUpdateSet.addAll(edgesToRemove);
- }
- Edge.mergeEdgesInto(edgesToAdd, GraphManip.genEdges(newDstEdges, fd, srcEdges));
+ if (dstNodes.size()>1&&!dstNodes.iterator().next().isSummary()&&fd!=null) {
+ /* Need to undo strong update */
+ if (graph.strongUpdateSet!=null) {
+ edgesToAdd.addAll(graph.strongUpdateSet);
+ graph.strongUpdateSet=null; //Prevent future strong updates
+ }
+ } else if (dstNodes.size()==1&&newDstEdges.size()==1&&!newDstEdges.iterator().next().dst.isSummary()&&graph.strongUpdateSet!=null&&fd!=null) {
+ edgesToRemove=GraphManip.getEdges(graph, delta, dstNodes, fd);
+ graph.strongUpdateSet.addAll(edgesToRemove);
+ }
+ Edge.mergeEdgesInto(edgesToAdd, GraphManip.genEdges(newDstEdges, fd, srcEdges));
}
//Kill new edges
if (graph.strongUpdateSet!=null&&fd!=null) {
- MySet<Edge> otherEdgesToRemove=GraphManip.getDiffEdges(delta, dstNodes, fd);
- if (edgesToRemove!=null)
- edgesToRemove.addAll(otherEdgesToRemove);
- else
- edgesToRemove=otherEdgesToRemove;
- graph.strongUpdateSet.addAll(otherEdgesToRemove);
+ MySet<Edge> otherEdgesToRemove=GraphManip.getDiffEdges(delta, dstNodes, fd);
+ if (edgesToRemove!=null)
+ edgesToRemove.addAll(otherEdgesToRemove);
+ else
+ edgesToRemove=otherEdgesToRemove;
+ graph.strongUpdateSet.addAll(otherEdgesToRemove);
}
//Next look at new destinations
src=frn.getReturnTemp();
dst=returntmp;
if (src==null||!src.getType().isPtr()) {
- //This is a NOP
- applyDiffs(graph, delta);
- return delta;
+ //This is a NOP
+ applyDiffs(graph, delta);
+ return delta;
}
} else {
FlatCastNode fcn=(FlatCastNode) node;
if (delta.getInit()) {
MySet<Edge> srcedges=GraphManip.getEdges(graph, delta, src);
if (OoOJava) {
- if (taint!=null) {
- srcedges=Edge.taintAll(srcedges, taint);
- updateVarDelta(graph, delta, src, srcedges, null);
- }
- effectsAnalysis.analyzeFlatFieldNode(srcedges, fd, node);
+ if (taint!=null) {
+ srcedges=Edge.taintAll(srcedges, taint);
+ updateVarDelta(graph, delta, src, srcedges, null);
+ }
+ effectsAnalysis.analyzeFlatFieldNode(srcedges, fd, node);
}
if (!dst.getType().isPtr()) {
- if (mustProcess.contains(node)) {
- applyDiffs(graph, delta);
- }
- return delta;
+ if (mustProcess.contains(node)) {
+ applyDiffs(graph, delta);
+ }
+ return delta;
}
MySet<Edge> edgesToAdd=GraphManip.dereference(graph, delta, dst, srcedges, fd, node);
} else {
MySet<Edge> newsrcedges=GraphManip.getDiffEdges(delta, src);
if (OoOJava) {
- if (taint!=null) {
- newsrcedges=Edge.taintAll(newsrcedges, taint);
- updateVarDelta(graph, delta, src, newsrcedges, null);
- }
- effectsAnalysis.analyzeFlatFieldNode(newsrcedges, fd, node);
+ if (taint!=null) {
+ newsrcedges=Edge.taintAll(newsrcedges, taint);
+ updateVarDelta(graph, delta, src, newsrcedges, null);
+ }
+ effectsAnalysis.analyzeFlatFieldNode(newsrcedges, fd, node);
}
if (!dst.getType().isPtr()) {
- if (mustProcess.contains(node)) {
- applyDiffs(graph, delta);
- }
- return delta;
+ if (mustProcess.contains(node)) {
+ applyDiffs(graph, delta);
+ }
+ return delta;
}
/* First compute new objects we read fields of */
MySet<Edge> allsrcedges=GraphManip.getEdges(graph, delta, src);
MySet<Edge> existingEdges=graph.getEdges(tmp);
if (edgestoRemove!=null)
for(Edge e : edgestoRemove) {
- //remove edge from delta
- if (edgeAdd!=null)
- edgeAdd.remove(e);
- //if the edge is already in the graph, add an explicit remove to the delta
- if (existingEdges.contains(e))
- delta.removeVarEdge(e);
+ //remove edge from delta
+ if (edgeAdd!=null)
+ edgeAdd.remove(e);
+ //if the edge is already in the graph, add an explicit remove to the delta
+ if (existingEdges.contains(e))
+ delta.removeVarEdge(e);
}
for(Edge e : edgestoAdd) {
//Remove the edge from the remove set
if (edgeRemove!=null)
- edgeRemove.remove(e);
+ edgeRemove.remove(e);
//Explicitly add it to the add set unless it is already in the graph
if (typeUtil.isSuperorType(tmp.getType(), e.dst.getType())) {
- if (!existingEdges.contains(e)) {
- delta.addVarEdge(e);
- } else {
- //See if the old edge subsumes the new one
- Edge olde=existingEdges.get(e);
- if (!olde.subsumes(e)) {
- delta.addVarEdge(olde.merge(e));
- }
- }
+ if (!existingEdges.contains(e)) {
+ delta.addVarEdge(e);
+ } else {
+ //See if the old edge subsumes the new one
+ Edge olde=existingEdges.get(e);
+ if (!olde.subsumes(e)) {
+ delta.addVarEdge(olde.merge(e));
+ }
+ }
}
}
}
void updateHeapDelta(Graph graph, Delta delta, MySet<Edge> edgestoAdd, MySet<Edge> edgestoRemove) {
if (edgestoRemove!=null)
for(Edge e : edgestoRemove) {
- AllocNode src=e.src;
- MySet<Edge> edgeAdd=delta.heapedgeadd.get(src);
- MySet<Edge> existingEdges=graph.getEdges(src);
- //remove edge from delta
- if (edgeAdd!=null)
- edgeAdd.remove(e);
- //if the edge is already in the graph, add an explicit remove to the delta
- if (existingEdges.contains(e)) {
- delta.removeHeapEdge(e);
- }
+ AllocNode src=e.src;
+ MySet<Edge> edgeAdd=delta.heapedgeadd.get(src);
+ MySet<Edge> existingEdges=graph.getEdges(src);
+ //remove edge from delta
+ if (edgeAdd!=null)
+ edgeAdd.remove(e);
+ //if the edge is already in the graph, add an explicit remove to the delta
+ if (existingEdges.contains(e)) {
+ delta.removeHeapEdge(e);
+ }
}
if (edgestoAdd!=null)
for(Edge e : edgestoAdd) {
- AllocNode src=e.src;
- MySet<Edge> edgeRemove=delta.heapedgeremove.get(src);
- MySet<Edge> existingEdges=graph.getEdges(src);
- //Remove the edge from the remove set
- if (edgeRemove!=null)
- edgeRemove.remove(e);
- //Explicitly add it to the add set unless it is already in the graph
- if (!existingEdges.contains(e)) {
- delta.addHeapEdge(e);
- } else {
- //See if the old edge subsumes the new one
- Edge olde=existingEdges.get(e);
- if (!olde.subsumes(e)) {
- delta.addHeapEdge(olde.merge(e));
- }
- }
+ AllocNode src=e.src;
+ MySet<Edge> edgeRemove=delta.heapedgeremove.get(src);
+ MySet<Edge> existingEdges=graph.getEdges(src);
+ //Remove the edge from the remove set
+ if (edgeRemove!=null)
+ edgeRemove.remove(e);
+ //Explicitly add it to the add set unless it is already in the graph
+ if (!existingEdges.contains(e)) {
+ delta.addHeapEdge(e);
+ } else {
+ //See if the old edge subsumes the new one
+ Edge olde=existingEdges.get(e);
+ if (!olde.subsumes(e)) {
+ delta.addHeapEdge(olde.merge(e));
+ }
+ }
}
}
//Remove the old edges
MySet<Edge> oldedges=graph.getEdges(tmp);
if (!oldedges.isEmpty())
- delta.varedgeremove.put(tmp, (MySet<Edge>)oldedges);
+ delta.varedgeremove.put(tmp, (MySet<Edge>)oldedges);
//Note that we create a single node
delta.addNodeAges.add(single);
//Kill the old node
if (delta.addOldNodes.containsKey(single)||delta.baseOldNodes.containsKey(single)) {
- delta.addOldNodes.put(single, Boolean.FALSE);
+ delta.addOldNodes.put(single, Boolean.FALSE);
}
} else {
/* 1. Fix up the variable edge additions */
for(Iterator<Map.Entry<TempDescriptor, MySet<Edge>>> entryIt=delta.varedgeadd.entrySet().iterator(); entryIt.hasNext(); ) {
- Map.Entry<TempDescriptor, MySet<Edge>> entry=entryIt.next();
+ Map.Entry<TempDescriptor, MySet<Edge>> entry=entryIt.next();
- if (entry.getKey()==tmp) {
- /* Check if this is the tmp we overwrite */
- entryIt.remove();
- } else {
- /* Otherwise, check if the target of the edge is changed... */
- summarizeSet(entry.getValue(), graph.varMap.get(entry.getKey()), single, summary);
- }
+ if (entry.getKey()==tmp) {
+ /* Check if this is the tmp we overwrite */
+ entryIt.remove();
+ } else {
+ /* Otherwise, check if the target of the edge is changed... */
+ summarizeSet(entry.getValue(), graph.varMap.get(entry.getKey()), single, summary);
+ }
}
/* 2. Fix up the base variable edges */
for(Iterator<Map.Entry<TempDescriptor, MySet<Edge>>> entryIt=delta.basevaredge.entrySet().iterator(); entryIt.hasNext(); ) {
- Map.Entry<TempDescriptor, MySet<Edge>> entry=entryIt.next();
- TempDescriptor entrytmp=entry.getKey();
- if (entrytmp==tmp) {
- /* Check is this is the tmp we overwrite, if so add to remove set */
- Util.relationUpdate(delta.varedgeremove, tmp, null, entry.getValue());
- } else if (graph.varMap.containsKey(entrytmp)) {
- /* Check if the target of the edge is changed */
- MySet<Edge> newset=(MySet<Edge>)entry.getValue().clone();
- MySet<Edge> removeset=shrinkSet(newset, graph.varMap.get(entrytmp), single, summary);
- Util.relationUpdate(delta.varedgeremove, entrytmp, newset, removeset);
- Util.relationUpdate(delta.varedgeadd, entrytmp, null, newset);
- } else {
- /* Check if the target of the edge is changed */
- MySet<Edge> newset=(MySet<Edge>)entry.getValue().clone();
- MySet<Edge> removeset=shrinkSet(newset, graph.parent.varMap.get(entrytmp), single, summary);
- Util.relationUpdate(delta.varedgeremove, entrytmp, newset, removeset);
- Util.relationUpdate(delta.varedgeadd, entrytmp, null, newset);
- }
+ Map.Entry<TempDescriptor, MySet<Edge>> entry=entryIt.next();
+ TempDescriptor entrytmp=entry.getKey();
+ if (entrytmp==tmp) {
+ /* Check is this is the tmp we overwrite, if so add to remove set */
+ Util.relationUpdate(delta.varedgeremove, tmp, null, entry.getValue());
+ } else if (graph.varMap.containsKey(entrytmp)) {
+ /* Check if the target of the edge is changed */
+ MySet<Edge> newset=(MySet<Edge>)entry.getValue().clone();
+ MySet<Edge> removeset=shrinkSet(newset, graph.varMap.get(entrytmp), single, summary);
+ Util.relationUpdate(delta.varedgeremove, entrytmp, newset, removeset);
+ Util.relationUpdate(delta.varedgeadd, entrytmp, null, newset);
+ } else {
+ /* Check if the target of the edge is changed */
+ MySet<Edge> newset=(MySet<Edge>)entry.getValue().clone();
+ MySet<Edge> removeset=shrinkSet(newset, graph.parent.varMap.get(entrytmp), single, summary);
+ Util.relationUpdate(delta.varedgeremove, entrytmp, newset, removeset);
+ Util.relationUpdate(delta.varedgeadd, entrytmp, null, newset);
+ }
}
HashMap<AllocNode, MySet<Edge>> addheapedge=new HashMap<AllocNode, MySet<Edge>>();
for(Iterator<Map.Entry<AllocNode, MySet<Edge>>> entryIt=delta.heapedgeadd.entrySet().iterator(); entryIt.hasNext(); ) {
- Map.Entry<AllocNode, MySet<Edge>> entry=entryIt.next();
- MySet<Edge> edgeset=entry.getValue();
- AllocNode allocnode=entry.getKey();
- if (allocnode==single) {
- entryIt.remove();
- summarizeSet(edgeset, graph.nodeMap.get(summary), single, summary);
- addheapedge.put(summary, edgeset);
- } else {
- summarizeSet(edgeset, graph.nodeMap.get(allocnode), single, summary);
- }
+ Map.Entry<AllocNode, MySet<Edge>> entry=entryIt.next();
+ MySet<Edge> edgeset=entry.getValue();
+ AllocNode allocnode=entry.getKey();
+ if (allocnode==single) {
+ entryIt.remove();
+ summarizeSet(edgeset, graph.nodeMap.get(summary), single, summary);
+ addheapedge.put(summary, edgeset);
+ } else {
+ summarizeSet(edgeset, graph.nodeMap.get(allocnode), single, summary);
+ }
}
/* Merge in diffs */
for(Map.Entry<AllocNode, MySet<Edge>> entry : addheapedge.entrySet()) {
- AllocNode allocnode=entry.getKey();
- Util.relationUpdate(delta.heapedgeadd, allocnode, null, entry.getValue());
+ AllocNode allocnode=entry.getKey();
+ Util.relationUpdate(delta.heapedgeadd, allocnode, null, entry.getValue());
}
/* 4. Fix up the base heap edges */
for(Iterator<Map.Entry<AllocNode, MySet<Edge>>> entryIt=delta.baseheapedge.entrySet().iterator(); entryIt.hasNext(); ) {
- Map.Entry<AllocNode, MySet<Edge>> entry=entryIt.next();
- MySet<Edge> edgeset=entry.getValue();
- AllocNode allocnode=entry.getKey();
- if (allocnode==single) {
- entryIt.remove();
- }
- AllocNode addnode=(allocnode==single)?summary:allocnode;
+ Map.Entry<AllocNode, MySet<Edge>> entry=entryIt.next();
+ MySet<Edge> edgeset=entry.getValue();
+ AllocNode allocnode=entry.getKey();
+ if (allocnode==single) {
+ entryIt.remove();
+ }
+ AllocNode addnode=(allocnode==single)?summary:allocnode;
- MySet<Edge> newset=(MySet<Edge>)edgeset.clone();
- MySet<Edge> removeset=shrinkSet(newset, graph.nodeMap.get(addnode), single, summary);
- Util.relationUpdate(delta.heapedgeadd, addnode, null, newset);
- Util.relationUpdate(delta.heapedgeremove, allocnode, null, removeset);
+ MySet<Edge> newset=(MySet<Edge>)edgeset.clone();
+ MySet<Edge> removeset=shrinkSet(newset, graph.nodeMap.get(addnode), single, summary);
+ Util.relationUpdate(delta.heapedgeadd, addnode, null, newset);
+ Util.relationUpdate(delta.heapedgeremove, allocnode, null, removeset);
}
/* Update Node Ages...If the base or addNodeAges set contains a
* need to generate a single node as that has already been
* done. */
if (delta.baseNodeAges.contains(single)||delta.addNodeAges.contains(single)) {
- delta.addNodeAges.add(summary);
+ delta.addNodeAges.add(summary);
}
//Kill the old node if someone tries to add it
if (delta.addOldNodes.containsKey(single)||delta.baseOldNodes.containsKey(single)) {
- delta.addOldNodes.put(single, Boolean.FALSE);
+ delta.addOldNodes.put(single, Boolean.FALSE);
}
}
for(Iterator<Edge> edgeit=edgeset.iterator(); edgeit.hasNext(); ) {
Edge e=edgeit.next();
if (e.dst==oldnode||e.src==oldnode) {
- if (newSet==null) {
- newSet=new MySet<Edge>();
- }
- edgeit.remove();
- e=e.copy();
-
- if (e.dst==oldnode) {
- e.dst=sumnode;
- }
- if (e.src==oldnode) {
- e.src=sumnode;
- }
- if (oldedgeset==null||!oldedgeset.contains(e))
- newSet.add(e);
+ if (newSet==null) {
+ newSet=new MySet<Edge>();
+ }
+ edgeit.remove();
+ e=e.copy();
+
+ if (e.dst==oldnode) {
+ e.dst=sumnode;
+ }
+ if (e.src==oldnode) {
+ e.src=sumnode;
+ }
+ if (oldedgeset==null||!oldedgeset.contains(e))
+ newSet.add(e);
}
}
if (newSet!=null)
Edge e=edgeit.next();
edgeit.remove();
if (e.dst==oldnode||e.src==oldnode) {
- if (newSet==null) {
- newSet=new MySet<Edge>();
- removeSet=new MySet<Edge>();
- }
+ if (newSet==null) {
+ newSet=new MySet<Edge>();
+ removeSet=new MySet<Edge>();
+ }
- removeSet.add(e);
- e=e.copy();
- if (e.dst==oldnode)
- e.dst=newnode;
- if (e.src==oldnode)
- e.src=newnode;
- if (oldedgeset==null||!oldedgeset.contains(e))
- newSet.add(e);
+ removeSet.add(e);
+ e=e.copy();
+ if (e.dst==oldnode)
+ e.dst=newnode;
+ if (e.src==oldnode)
+ e.src=newnode;
+ if (oldedgeset==null||!oldedgeset.contains(e))
+ newSet.add(e);
}
}
if (newSet!=null)
//Add in heap edges and throw away original diff
for(Map.Entry<AllocNode, MySet<Edge>> entry : delta.heapedgeadd.entrySet()) {
- graph.nodeMap.put(entry.getKey(), new MySet<Edge>(entry.getValue()));
+ graph.nodeMap.put(entry.getKey(), new MySet<Edge>(entry.getValue()));
}
//Add in var edges and throw away original diff
Set<TempDescriptor> livetemps=bblivetemps.get(block);
for(Map.Entry<TempDescriptor, MySet<Edge>> entry : delta.varedgeadd.entrySet()) {
- if (livetemps.contains(entry.getKey()))
- graph.varMap.put(entry.getKey(), new MySet<Edge>(entry.getValue()));
+ if (livetemps.contains(entry.getKey()))
+ graph.varMap.put(entry.getKey(), new MySet<Edge>(entry.getValue()));
}
//Record that this is initial set...
graph.nodeAges.addAll(delta.addNodeAges);
//Add old nodes
for(Map.Entry<AllocNode, Boolean> oldentry : delta.addOldNodes.entrySet()) {
- if (oldentry.getValue().booleanValue()) {
- graph.oldNodes.put(oldentry.getKey(), Boolean.TRUE);
- }
+ if (oldentry.getValue().booleanValue()) {
+ graph.oldNodes.put(oldentry.getKey(), Boolean.TRUE);
+ }
}
return newdelta;
} else {
MySet<Edge> edges=heapedge.getValue();
if (graph.backMap!=null) {
- for(Edge e : edges) {
- if (!graph.backMap.containsKey(e.dst))
- graph.backMap.put(e.dst, new MySet<Edge>());
- graph.backMap.get(e.dst).add(e);
- }
+ for(Edge e : edges) {
+ if (!graph.backMap.containsKey(e.dst))
+ graph.backMap.put(e.dst, new MySet<Edge>());
+ graph.backMap.get(e.dst).add(e);
+ }
}
if (!graph.nodeMap.containsKey(nsrc)) {
- graph.nodeMap.put(nsrc, new MySet<Edge>());
+ graph.nodeMap.put(nsrc, new MySet<Edge>());
}
MySet<Edge> dstedges=graph.nodeMap.get(nsrc);
MySet<Edge> diffedges=new MySet<Edge>();
for(Edge e : edges) {
- if (!dstedges.contains(e)) {
- //We have a new edge
- diffedges.add(e);
- dstedges.add(e);
- } else {
- Edge origedge=dstedges.get(e);
- if (!origedge.subsumes(e)) {
- Edge mergededge=origedge.merge(e);
- diffedges.add(mergededge);
- dstedges.add(mergededge);
- }
- }
+ if (!dstedges.contains(e)) {
+ //We have a new edge
+ diffedges.add(e);
+ dstedges.add(e);
+ } else {
+ Edge origedge=dstedges.get(e);
+ if (!origedge.subsumes(e)) {
+ Edge mergededge=origedge.merge(e);
+ diffedges.add(mergededge);
+ dstedges.add(mergededge);
+ }
+ }
}
//Done with edge set...
if (diffedges.size()>0) {
- //completely new
- newdelta.baseheapedge.put(nsrc, diffedges);
+ //completely new
+ newdelta.baseheapedge.put(nsrc, diffedges);
}
}
}
for(Map.Entry<TempDescriptor, MySet<Edge>> varedge : delta.varedgeadd.entrySet()) {
TempDescriptor tmpsrc=varedge.getKey();
if (livetemps.contains(tmpsrc)) {
- MySet<Edge> edges=varedge.getValue();
- if (graph.backMap!=null) {
- for(Edge e : edges) {
- if (!graph.backMap.containsKey(e.dst))
- graph.backMap.put(e.dst, new MySet<Edge>());
- graph.backMap.get(e.dst).add(e);
- }
- }
-
- if (!graph.varMap.containsKey(tmpsrc)) {
- graph.varMap.put(tmpsrc, new MySet<Edge>());
- }
- MySet<Edge> dstedges=graph.varMap.get(tmpsrc);
- MySet<Edge> diffedges=new MySet<Edge>();
- for(Edge e : edges) {
- if (!dstedges.contains(e)) {
- //We have a new edge
- diffedges.add(e);
- dstedges.add(e);
- } else {
- Edge origedge=dstedges.get(e);
- if (!origedge.subsumes(e)) {
- Edge mergededge=origedge.merge(e);
- diffedges.add(mergededge);
- dstedges.add(mergededge);
- }
- }
- }
- //Done with edge set...
- if (diffedges.size()>0) {
- //completely new
- newdelta.basevaredge.put(tmpsrc,diffedges);
- }
+ MySet<Edge> edges=varedge.getValue();
+ if (graph.backMap!=null) {
+ for(Edge e : edges) {
+ if (!graph.backMap.containsKey(e.dst))
+ graph.backMap.put(e.dst, new MySet<Edge>());
+ graph.backMap.get(e.dst).add(e);
+ }
+ }
+
+ if (!graph.varMap.containsKey(tmpsrc)) {
+ graph.varMap.put(tmpsrc, new MySet<Edge>());
+ }
+ MySet<Edge> dstedges=graph.varMap.get(tmpsrc);
+ MySet<Edge> diffedges=new MySet<Edge>();
+ for(Edge e : edges) {
+ if (!dstedges.contains(e)) {
+ //We have a new edge
+ diffedges.add(e);
+ dstedges.add(e);
+ } else {
+ Edge origedge=dstedges.get(e);
+ if (!origedge.subsumes(e)) {
+ Edge mergededge=origedge.merge(e);
+ diffedges.add(mergededge);
+ dstedges.add(mergededge);
+ }
+ }
+ }
+ //Done with edge set...
+ if (diffedges.size()>0) {
+ //completely new
+ newdelta.basevaredge.put(tmpsrc,diffedges);
+ }
}
}
}
//Merge in edges
for(AllocNode node : delta.addNodeAges) {
if (!graph.nodeAges.contains(node)) {
- graph.nodeAges.add(node);
- newDelta.baseNodeAges.add(node);
+ graph.nodeAges.add(node);
+ newDelta.baseNodeAges.add(node);
}
}
for(Map.Entry<AllocNode, Boolean> oldentry : delta.addOldNodes.entrySet()) {
AllocNode node=oldentry.getKey();
boolean ispresent=oldentry.getValue().booleanValue();
if (ispresent&&!graph.oldNodes.containsKey(node)) {
- graph.oldNodes.put(node, Boolean.TRUE);
- newDelta.baseOldNodes.put(node, Boolean.TRUE);
+ graph.oldNodes.put(node, Boolean.TRUE);
+ newDelta.baseOldNodes.put(node, Boolean.TRUE);
}
}
}
MySet<T> newset=new MySet<T>();
for(T e : orig) {
if (!sub.contains(e))
- newset.add(e);
+ newset.add(e);
}
return newset;
}
public static <K,V> void relationUpdate(HashMap<K,MySet<V>> map, K key, MySet<V> toremove, MySet<V> toadd) {
if (map.containsKey(key)) {
if (toremove!=null)
- map.get(key).removeAll(toremove);
+ map.get(key).removeAll(toremove);
map.get(key).addAll(toadd);
} else {
if (toadd!=null)
- map.put(key, (MySet<V>)toadd.clone());
+ map.put(key, (MySet<V>)toadd.clone());
}
}
} else {
ListIterator lit = getTempDesc().listIterator();
for(; lit.hasNext(); ) {
- TempDescriptor td = (TempDescriptor) lit.next();
- label += td.toString()+"+";
+ TempDescriptor td = (TempDescriptor) lit.next();
+ label += td.toString()+"+";
}
label +=offset.toString();
}
FlatNode fn=nodeset.iterator().next();
nodeset.remove(fn);
if (fn.kind()==FKind.FlatCondBranch&&((FlatCondBranch)fn).isLoopBranch()) {
- FlatCondBranch fcb=(FlatCondBranch)fn;
- loopbranchset.add(fcb);
- //True edge
- propagateset(nodeset, table, fcb, fcb.getNext(0), fcb);
- //False edge
- propagateset(nodeset, table, fcb, fcb.getNext(1), null);
- loopbranchset.add(fcb);
+ FlatCondBranch fcb=(FlatCondBranch)fn;
+ loopbranchset.add(fcb);
+ //True edge
+ propagateset(nodeset, table, fcb, fcb.getNext(0), fcb);
+ //False edge
+ propagateset(nodeset, table, fcb, fcb.getNext(1), null);
+ loopbranchset.add(fcb);
} else if (fn.kind()==FKind.FlatReturnNode) {
- if (table.containsKey(fn))
- exitset.addAll(table.get(fn));
+ if (table.containsKey(fn))
+ exitset.addAll(table.get(fn));
} else {
- for(int i=0; i<fn.numNext(); i++)
- propagateset(nodeset, table, fn, fn.getNext(i), null);
+ for(int i=0; i<fn.numNext(); i++)
+ propagateset(nodeset, table, fn, fn.getNext(i), null);
}
}
loopbranchset.removeAll(exitset);
HashSet<FlatCondBranch> toadd=new HashSet<FlatCondBranch>();
toadd.addAll(table.get(fn));
if (toadd.contains(fnnext)) //can't propagate back to node
- toadd.remove(fnnext);
+ toadd.remove(fnnext);
if(!table.get(fnnext).containsAll(toadd)) {
- table.get(fnnext).addAll(toadd);
- enqueuechange=true;
+ table.get(fnnext).addAll(toadd);
+ enqueuechange=true;
}
}
if (fcb!=null&&!table.get(fnnext).contains(fcb)) {
for (Iterator methodit=locality.getMethods().iterator(); methodit.hasNext(); ) {
MethodDescriptor md=(MethodDescriptor)methodit.next();
if (state.excprefetch.contains(md.getClassMethodName()))
- continue; //Skip this method
+ continue; //Skip this method
Hashtable<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);
+ addFlatPrefetchNode(newprefetchset);
}
newprefetchset = null;
}
} 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();
- }
+ 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;
+ processCall((FlatCall)curr,child_prefetch_set_copy);
+ break;
case FKind.FlatBackEdge:
case FKind.FlatCheckNode:
case FKind.FlatCastNode:
case FKind.FlatTagDeclaration:
case FKind.FlatInstanceOfNode:
- processDefaultCase(curr,child_prefetch_set_copy);
- break;
+ processDefaultCase(curr,child_prefetch_set_copy);
+ break;
case FKind.FlatMethod:
- //TODO change it to take care of FlatMethod, Flatcalls
- processFlatMethod(curr, child_prefetch_set_copy);
- break;
+ //TODO change it to take care of FlatMethod, Flatcalls
+ processFlatMethod(curr, child_prefetch_set_copy);
+ break;
case FKind.FlatFieldNode:
- processFlatFieldNode(curr, child_prefetch_set_copy);
- break;
+ processFlatFieldNode(curr, child_prefetch_set_copy);
+ break;
case FKind.FlatElementNode:
- processFlatElementNode(curr, child_prefetch_set_copy);
- break;
+ processFlatElementNode(curr, child_prefetch_set_copy);
+ break;
case FKind.FlatOpNode:
- processFlatOpNode(curr, child_prefetch_set_copy);
- break;
+ processFlatOpNode(curr, child_prefetch_set_copy);
+ break;
case FKind.FlatLiteralNode:
- processFlatLiteralNode(curr, child_prefetch_set_copy);
- break;
+ processFlatLiteralNode(curr, child_prefetch_set_copy);
+ break;
case FKind.FlatSetElementNode:
- processFlatSetElementNode(curr, child_prefetch_set_copy);
- break;
+ processFlatSetElementNode(curr, child_prefetch_set_copy);
+ break;
case FKind.FlatSetFieldNode:
- processFlatSetFieldNode(curr, child_prefetch_set_copy);
- break;
+ processFlatSetFieldNode(curr, child_prefetch_set_copy);
+ break;
case FKind.FlatOffsetNode:
- processDefaultCase(curr,child_prefetch_set_copy);
- break;
+ processDefaultCase(curr,child_prefetch_set_copy);
+ break;
default:
- throw new Error("No such Flatnode kind");
+ throw new Error("No such Flatnode kind");
}
}
}
PrefetchPair pp = (PrefetchPair) e.nextElement();
double newprob = newPrefetchSet.get(pp).doubleValue();
if (!oldPrefetchSet.containsKey(pp))
- return true;
+ return true;
double oldprob = oldPrefetchSet.get(pp).doubleValue();
if((newprob - oldprob) > PROB_DIFF) {
- return true;
+ return true;
}
if (newprob >= PREFETCH_THRESHOLD_PROB && oldprob < PREFETCH_THRESHOLD_PROB) {
- return true;
+ return true;
}
if (oldprob>newprob) {
- System.out.println("ERROR:" + pp);
- System.out.println(oldprob + " -> "+ newprob);
+ System.out.println("ERROR:" + pp);
+ System.out.println(oldprob + " -> "+ newprob);
}
}
return false;
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));
+ tovisit.add(curr.getPrev(i));
}
prefetch_hash.put(curr, newset);
}
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
+ 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);
+ //covered by current prefetch
+ child_prefetch_set_copy.remove(childpp);
} else if(childpp.containsTemp(currffn.getDst())) {
- child_prefetch_set_copy.remove(childpp);
+ child_prefetch_set_copy.remove(childpp);
} else {
- Double newprob = child_prefetch_set_copy.get(childpp).doubleValue();
- if (tocompare.containsKey(childpp)) {
- Double oldprob=tocompare.get(childpp);
- newprob=1.0-(1.0-oldprob)*(1.0-newprob);
- }
- tocompare.put(childpp, newprob);
- pm.addPair(childpp, childpp);
+ Double newprob = child_prefetch_set_copy.get(childpp).doubleValue();
+ if (tocompare.containsKey(childpp)) {
+ Double oldprob=tocompare.get(childpp);
+ newprob=1.0-(1.0-oldprob)*(1.0-newprob);
+ }
+ tocompare.put(childpp, newprob);
+ pm.addPair(childpp, childpp);
}
}
for(Iterator<PrefetchPair> it=tocompare.keySet().iterator(); it.hasNext(); ) {
PrefetchPair pp=it.next();
if (tocompare.get(pp)<ANALYSIS_THRESHOLD_PROB)
- it.remove();
+ it.remove();
}
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);
- }
- }
+ 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);
+ child_prefetch_set_copy.remove(childpp);
} else if(childpp.containsTemp(currfen.getDst())) {
- child_prefetch_set_copy.remove(childpp);
+ child_prefetch_set_copy.remove(childpp);
} else {
- continue;
+ continue;
}
}
/* Check if curr prefetch set and the child prefetch set have same prefetch pairs
for(Enumeration ecld = child_prefetch_set_copy.keys(); ecld.hasMoreElements(); ) {
PrefetchPair childpp = (PrefetchPair) ecld.nextElement();
for(Enumeration e = currcopy.keys(); e.hasMoreElements(); ) {
- currpp = (PrefetchPair) e.nextElement();
- if(currpp.equals(childpp)) {
- pm.addPair(childpp, currpp);
- child_prefetch_set_copy.remove(childpp);
- break;
- }
+ currpp = (PrefetchPair) e.nextElement();
+ if(currpp.equals(childpp)) {
+ pm.addPair(childpp, currpp);
+ child_prefetch_set_copy.remove(childpp);
+ break;
+ }
}
}
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;
- }
+ 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;
+ }
}
}
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;
- }
- }
+ 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;
+ }
+ }
}
}
/* Merge child prefetch pairs */
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;
- } else {
- continue;
- }
+ PrefetchPair childpp = (PrefetchPair) ecld.nextElement();
+ PrefetchPair copyofchildpp = (PrefetchPair) childpp.clone();
+
+ /* For cases like x=y with child prefetch set x[i].z,x.g*/
+ if(childpp.base == currfopn.getDest()) {
+ ArrayList<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;
+ } else {
+ continue;
+ }
}
//case i = i+z with child prefetch set a[i].x
} else if(currfopn.getRight()!=null && (currfopn.getOp().getOp() == Operation.ADD)) {
for (Enumeration ecld = child_prefetch_set_copy.keys(); ecld.hasMoreElements(); ) {
- PrefetchPair childpp = (PrefetchPair) ecld.nextElement();
- PrefetchPair copyofchildpp = (PrefetchPair) childpp.clone();
-
- if(copyofchildpp.containsTemp(currfopn.getDest())) {
- PrefetchPair newpp=copyofchildpp.replaceTemp(currfopn.getDest(), new TempDescriptor[] {currfopn.getLeft(), currfopn.getRight()});
- Double newprob = child_prefetch_set_copy.get(childpp).doubleValue();
- tocompare.put(newpp, newprob);
- pm.addPair(childpp, newpp);
- child_prefetch_set_copy.remove(childpp);
- /* Check for independence of prefetch pairs to compute new probability*/
- if(child_prefetch_set_copy.containsKey(newpp)) {
- newprob = (1.0 - ((1.0 - child_prefetch_set_copy.get(newpp).doubleValue()) * (1.0 - tocompare.get(newpp).doubleValue())));
- if(newprob < ANALYSIS_THRESHOLD_PROB) {
- tocompare.remove(newpp);
- } else {
- tocompare.put(newpp, newprob);
- pm.addPair(newpp, newpp);
- }
- child_prefetch_set_copy.remove(newpp);
- }
- } else {
- continue;
- }
+ PrefetchPair childpp = (PrefetchPair) ecld.nextElement();
+ PrefetchPair copyofchildpp = (PrefetchPair) childpp.clone();
+
+ if(copyofchildpp.containsTemp(currfopn.getDest())) {
+ PrefetchPair newpp=copyofchildpp.replaceTemp(currfopn.getDest(), new TempDescriptor[] {currfopn.getLeft(), currfopn.getRight()});
+ Double newprob = child_prefetch_set_copy.get(childpp).doubleValue();
+ tocompare.put(newpp, newprob);
+ pm.addPair(childpp, newpp);
+ child_prefetch_set_copy.remove(childpp);
+ /* Check for independence of prefetch pairs to compute new probability*/
+ if(child_prefetch_set_copy.containsKey(newpp)) {
+ newprob = (1.0 - ((1.0 - child_prefetch_set_copy.get(newpp).doubleValue()) * (1.0 - tocompare.get(newpp).doubleValue())));
+ if(newprob < ANALYSIS_THRESHOLD_PROB) {
+ tocompare.remove(newpp);
+ } else {
+ tocompare.put(newpp, newprob);
+ pm.addPair(newpp, newpp);
+ }
+ child_prefetch_set_copy.remove(newpp);
+ }
+ } else {
+ continue;
+ }
}
} else if(currfopn.getRight()!=null && (currfopn.getOp().getOp() == Operation.SUB)) {
for(Enumeration ecld = child_prefetch_set_copy.keys(); ecld.hasMoreElements(); ) {
- PrefetchPair childpp = (PrefetchPair) ecld.nextElement();
- if(childpp.containsTemp(currfopn.getDest())) {
- child_prefetch_set_copy.remove(childpp);
- }
+ PrefetchPair childpp = (PrefetchPair) ecld.nextElement();
+ if(childpp.containsTemp(currfopn.getDest())) {
+ child_prefetch_set_copy.remove(childpp);
+ }
}
} else {
//FIXME Is not taken care of for cases like x = -y followed by a[x].i
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);
- }
- }
+ 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);
+ }
+ }
}
}
PrefetchPair pp=ppit.next();
double trueprob=0,falseprob=0;
if (truechild.containsKey(pp))
- trueprob=truechild.get(pp).doubleValue();
+ trueprob=truechild.get(pp).doubleValue();
if (falsechild.containsKey(pp))
- falseprob=falsechild.get(pp).doubleValue();
+ falseprob=falsechild.get(pp).doubleValue();
double newprob=trueprob*fcb.getTrueProb()+falseprob*fcb.getFalseProb();
if (loop.isLoopingBranch(md,fcb)&&
newprob<falseprob) {
- newprob=falseprob;
+ newprob=falseprob;
}
if(newprob < ANALYSIS_THRESHOLD_PROB) //Skip pp that are below threshold
- continue;
+ continue;
tocompare.put(pp, newprob);
if (truechild.containsKey(pp))
- truepm.addPair(pp, pp);
+ truepm.addPair(pp, pp);
if (falsechild.containsKey(pp))
- falsepm.addPair(pp, pp);
+ falsepm.addPair(pp, pp);
}
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;
+ 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);
/* 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);
+ 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);
}
}
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();
- double v=currhash.get(pp).doubleValue();
- if (v>.2)
- System.out.print(pp.toString() +"-"+v + ", ");
+ PrefetchPair pp = (PrefetchPair) pphash.nextElement();
+ double v=currhash.get(pp).doubleValue();
+ if (v>.2)
+ System.out.print(pp.toString() +"-"+v + ", ");
}
System.out.println(")");
} else {
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);
- }
+ 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);
}
for (int j = 0; j < shrt.desc.size(); j++) {
if(shrt.getDescAt(j) instanceof IndexDescriptor) {
- IndexDescriptor shrtid = (IndexDescriptor) shrt.getDescAt(j);
- if(lng.getDescAt(j) instanceof IndexDescriptor) {
- IndexDescriptor lngid = (IndexDescriptor) lng.getDescAt(j);
- if(shrtid.equals(lngid)) {
- continue;
- } else {
- return false;
- }
- } else {
- return false;
- }
+ IndexDescriptor shrtid = (IndexDescriptor) shrt.getDescAt(j);
+ if(lng.getDescAt(j) instanceof IndexDescriptor) {
+ IndexDescriptor lngid = (IndexDescriptor) lng.getDescAt(j);
+ if(shrtid.equals(lngid)) {
+ continue;
+ } else {
+ return false;
+ }
+ } else {
+ return false;
+ }
} else {
- if ((Descriptor)shrt.getDescAt(j) != (Descriptor)lng.getDescAt(j)) {
- return false;
- }
+ if ((Descriptor)shrt.getDescAt(j) != (Descriptor)lng.getDescAt(j)) {
+ return false;
+ }
}
}
return true;
return true;
} else {
for(Iterator it = newPSet.iterator(); it.hasNext(); ) {
- if(!oldPSet.contains((PrefetchPair)it.next())) {
- return true;
- }
+ if(!oldPSet.contains((PrefetchPair)it.next())) {
+ return true;
+ }
}
}
return false;
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);
- }
+ 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);
- tovisit.add(nn);
- }
- pset1_hash.put(fn, pset1);
+ for(int j=0; j<fn.numNext(); j++) {
+ FlatNode nn = fn.getNext(j);
+ tovisit.add(nn);
+ }
+ pset1_hash.put(fn, pset1);
}
newprefetchset.put(fn, pset1);
} else { /* Nodes other than Flat Method Node */
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.contains((PrefetchPair) pm.getPair(pp)))
- mapIsPresent = false;
- } else
- mapIsPresent=false;
- }
-
- if(mapIsPresent)
- pset2.add(pp);
-
- if(pprobIsGreater && mapprobIsLess)
- newpset.add(pp);
+ 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.contains((PrefetchPair) pm.getPair(pp)))
+ mapIsPresent = false;
+ } else
+ mapIsPresent=false;
+ }
+
+ if(mapIsPresent)
+ pset2.add(pp);
+
+ if(pprobIsGreater && mapprobIsLess)
+ newpset.add(pp);
}
HashSet<PrefetchPair> pset1 = new HashSet<PrefetchPair>();
/* 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);
- tovisit.add(nn);
- }
- pset1_hash.put(fn, pset1);
+ for(int i=0; i<fn.numNext(); i++) {
+ FlatNode nn = fn.getNext(i);
+ tovisit.add(nn);
+ }
+ pset1_hash.put(fn, pset1);
}
/* To insert prefetch, apply rule: if the newpset minus pset2 is nonempty
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*/
- 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
+ fpn.insAllpp((HashSet)newprefetchset.get(fn));
+ if(fn.kind() == FKind.FlatMethod) {
+ FlatNode nn = fn.getNext(0);
+ fn.setNext(0, fpn);
+ fpn.addNext(nn);
+ fpn.siteid = prefetchsiteid++;
+ } else {
+ /* Check if previous node of this FlatNode is a NEW node
+ * If yes, delete this flatnode and its prefetch set from hash table
+ * This eliminates prefetches for NULL ptrs*/
+ while(fn.numPrev() > 0) {
+ FlatNode nn = fn.getPrev(0);
+ for(int j = 0; j<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
}
for(; it.hasNext(); ) {
Object o = it.next();
if(o instanceof FieldDescriptor) {
- FieldDescriptor fd = (FieldDescriptor) o;
- label+="."+ fd.toString();
+ FieldDescriptor fd = (FieldDescriptor) o;
+ label+="."+ fd.toString();
} else {
- IndexDescriptor id = (IndexDescriptor) o;
- label+= id.toString();
+ IndexDescriptor id = (IndexDescriptor) o;
+ label+= id.toString();
}
}
return label;
for(int i = 0; i < this.desc.size(); i++) {
Object o = desc.get(i);
if(o instanceof FieldDescriptor) {
- newpp.desc.add((FieldDescriptor) o);
+ 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);
+ 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 newpp;
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;
- }
+ ArrayList<TempDescriptor> tdarray = (ArrayList<TempDescriptor>)((IndexDescriptor)o).tddesc;
+ if(tdarray.contains(td)) {
+ return true;
+ }
}
}
return false;
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]);
- }
- }
+ 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;
for (Iterator iterator = locSet.iterator(); iterator.hasNext(); ) {
Location location = (Location) iterator.next();
if (location.getClassDescriptor().equals(cd)) {
- return location;
+ return location;
}
}
Location locElement = locTuple.at(i);
if (locElement instanceof DeltaLocation) {
- // baseLocationSet.addAll(((DeltaLocation)
- // locElement).getDeltaOperandLocationVec());
- baseLocationTuple.addAll(((DeltaLocation) locElement).getBaseLocationTuple());
+ // baseLocationSet.addAll(((DeltaLocation)
+ // locElement).getDeltaOperandLocationVec());
+ baseLocationTuple.addAll(((DeltaLocation) locElement).getBaseLocationTuple());
} else {
- baseLocationTuple.addElement(locElement);
+ baseLocationTuple.addElement(locElement);
}
}
return baseLocationTuple;
Location locElement = locTuple.at(i);
if (locElement instanceof DeltaLocation) {
- // baseLocationSet.addAll(((DeltaLocation)
- // locElement).getDeltaOperandLocationVec());
- baseLocationSet.addAll(((DeltaLocation) locElement).getBaseLocationSet());
+ // baseLocationSet.addAll(((DeltaLocation)
+ // locElement).getDeltaOperandLocationVec());
+ baseLocationSet.addAll(((DeltaLocation) locElement).getBaseLocationSet());
} else {
- baseLocationSet.add(locElement);
+ baseLocationSet.add(locElement);
}
}
return baseLocationSet;
if (locTuple.size() == 1) {
Location locElement = locTuple.at(0);
if (locElement instanceof DeltaLocation) {
- result++;
- result += getNumofDelta((DeltaLocation) locElement);
+ result++;
+ result += getNumofDelta((DeltaLocation) locElement);
}
}
return result;
if (delta.getDeltaOperandLocationVec().size() == 1) {
Location locElement = delta.getDeltaOperandLocationVec().at(0);
if (locElement instanceof DeltaLocation) {
- result++;
- result += getNumofDelta((DeltaLocation) locElement);
+ result++;
+ result += getNumofDelta((DeltaLocation) locElement);
}
}
for (int i = 0; i < tupleSize; i++) {
Location locElement = locTuple.at(i);
if (i != 0) {
- rtr += ",";
+ rtr += ",";
}
rtr += locElement;
}
// continue;
// }
for (Iterator method_it = cd.getMethods(); method_it.hasNext(); ) {
- MethodDescriptor md = (MethodDescriptor) method_it.next();
- FlatMethod fm = state.getMethodFlat(md);
- if (fm != null) {
+ MethodDescriptor md = (MethodDescriptor) method_it.next();
+ FlatMethod fm = state.getMethodFlat(md);
+ if (fm != null) {
- }
+ }
}
}
// if a new result, schedule forward nodes for analysis
for (int i = 0; i < fn.numNext(); i++) {
- FlatNode nn = fn.getNext(i);
- if (!visited.contains(nn)) {
- flatNodesToVisit.add(nn);
- }
+ FlatNode nn = fn.getNext(i);
+ if (!visited.contains(nn)) {
+ flatNodesToVisit.add(nn);
+ }
}
}
FlatOpNode fon = (FlatOpNode) fn;
if (fon.getOp().getOp() == Operation.ASSIGN) {
- lhs = fon.getDest();
- rhs = fon.getLeft();
- // read(rhs)
- Hashtable<Descriptor, Hashtable<FlatNode, Boolean>> map = definitelyWrittenResults.get(fn);
- if (map != null) {
- if (map.get(rhs).get(fn).booleanValue()) {
- // throw new Error("variable " + rhs
- // +
- // " was not overwritten in-between the same read statement by the out-most loop.");
- }
- }
+ lhs = fon.getDest();
+ rhs = fon.getLeft();
+ // read(rhs)
+ Hashtable<Descriptor, Hashtable<FlatNode, Boolean>> map = definitelyWrittenResults.get(fn);
+ if (map != null) {
+ if (map.get(rhs).get(fn).booleanValue()) {
+ // throw new Error("variable " + rhs
+ // +
+ // " was not overwritten in-between the same read statement by the out-most loop.");
+ }
+ }
}
Hashtable<Descriptor, Hashtable<FlatNode, Boolean>> curr =
new Hashtable<Descriptor, Hashtable<FlatNode, Boolean>>();
for (int i = 0; i < fn.numPrev(); i++) {
- FlatNode nn = fn.getPrev(i);
- Hashtable<Descriptor, Hashtable<FlatNode, Boolean>> dwIn = definitelyWrittenResults.get(nn);
- if (dwIn != null) {
- mergeResults(curr, dwIn);
- }
+ FlatNode nn = fn.getPrev(i);
+ Hashtable<Descriptor, Hashtable<FlatNode, Boolean>> dwIn = definitelyWrittenResults.get(nn);
+ if (dwIn != null) {
+ mergeResults(curr, dwIn);
+ }
}
definitelyWritten_nodeActions(fn, curr, entrance);
// if a new result, schedule forward nodes for analysis
if (!curr.equals(prev)) {
- definitelyWrittenResults.put(fn, curr);
+ definitelyWrittenResults.put(fn, curr);
- for (int i = 0; i < fn.numNext(); i++) {
- FlatNode nn = fn.getNext(i);
- flatNodesToVisit.add(nn);
- }
+ for (int i = 0; i < fn.numNext(); i++) {
+ FlatNode nn = fn.getNext(i);
+ flatNodesToVisit.add(nn);
+ }
}
}
}
Set<FlatNode> pairKeySet = inPair.keySet();
for (Iterator iterator2 = pairKeySet.iterator(); iterator2.hasNext(); ) {
- FlatNode pairKey = (FlatNode) iterator2.next();
- Boolean inFlag = inPair.get(pairKey);
-
- Hashtable<FlatNode, Boolean> currPair = curr.get(inKey);
- if (currPair == null) {
- currPair = new Hashtable<FlatNode, Boolean>();
- curr.put(inKey, currPair);
- }
-
- Boolean currFlag = currPair.get(pairKey);
- // by default, flag is set by false
- if (currFlag == null) {
- currFlag = Boolean.FALSE;
- }
- currFlag = Boolean.valueOf(inFlag.booleanValue() | currFlag.booleanValue());
- currPair.put(pairKey, currFlag);
+ FlatNode pairKey = (FlatNode) iterator2.next();
+ Boolean inFlag = inPair.get(pairKey);
+
+ Hashtable<FlatNode, Boolean> currPair = curr.get(inKey);
+ if (currPair == null) {
+ currPair = new Hashtable<FlatNode, Boolean>();
+ curr.put(inKey, currPair);
+ }
+
+ Boolean currFlag = currPair.get(pairKey);
+ // by default, flag is set by false
+ if (currFlag == null) {
+ currFlag = Boolean.FALSE;
+ }
+ currFlag = Boolean.valueOf(inFlag.booleanValue() | currFlag.booleanValue());
+ currPair.put(pairKey, currFlag);
}
}
Set<Descriptor> keySet = curr.keySet();
for (Iterator iterator = keySet.iterator(); iterator.hasNext(); ) {
- Descriptor key = (Descriptor) iterator.next();
- Hashtable<FlatNode, Boolean> pair = curr.get(key);
- if (pair != null) {
- Set<FlatNode> pairKeySet = pair.keySet();
- for (Iterator iterator2 = pairKeySet.iterator(); iterator2.hasNext(); ) {
- FlatNode pairKey = (FlatNode) iterator2.next();
- pair.put(pairKey, Boolean.TRUE);
- }
- }
+ Descriptor key = (Descriptor) iterator.next();
+ Hashtable<FlatNode, Boolean> pair = curr.get(key);
+ if (pair != null) {
+ Set<FlatNode> pairKeySet = pair.keySet();
+ for (Iterator iterator2 = pairKeySet.iterator(); iterator2.hasNext(); ) {
+ FlatNode pairKey = (FlatNode) iterator2.next();
+ pair.put(pairKey, Boolean.TRUE);
+ }
+ }
}
} else {
case FKind.FlatOpNode: {
- FlatOpNode fon = (FlatOpNode) fn;
- lhs = fon.getDest();
- rhs = fon.getLeft();
- System.out.println("\nfon=" + fon);
-
- if (fon.getOp().getOp() == Operation.ASSIGN) {
-
- // read(rhs)
- Hashtable<FlatNode, Boolean> gen = curr.get(rhs);
- if (gen == null) {
- gen = new Hashtable<FlatNode, Boolean>();
- curr.put(rhs, gen);
- }
- System.out.println("READ LOC=" + rhs.getType().getExtension());
-
- Boolean currentStatus = gen.get(fn);
- if (currentStatus == null) {
- gen.put(fn, Boolean.FALSE);
- }
- }
- // write(lhs)
- curr.put(lhs, new Hashtable<FlatNode, Boolean>());
- System.out.println("WRITING LOC=" + lhs.getType().getExtension());
+ FlatOpNode fon = (FlatOpNode) fn;
+ lhs = fon.getDest();
+ rhs = fon.getLeft();
+ System.out.println("\nfon=" + fon);
+
+ if (fon.getOp().getOp() == Operation.ASSIGN) {
+
+ // read(rhs)
+ Hashtable<FlatNode, Boolean> gen = curr.get(rhs);
+ if (gen == null) {
+ gen = new Hashtable<FlatNode, Boolean>();
+ curr.put(rhs, gen);
+ }
+ System.out.println("READ LOC=" + rhs.getType().getExtension());
+
+ Boolean currentStatus = gen.get(fn);
+ if (currentStatus == null) {
+ gen.put(fn, Boolean.FALSE);
+ }
+ }
+ // write(lhs)
+ curr.put(lhs, new Hashtable<FlatNode, Boolean>());
+ System.out.println("WRITING LOC=" + lhs.getType().getExtension());
}
break;
case FKind.FlatLiteralNode: {
- FlatLiteralNode fln = (FlatLiteralNode) fn;
- lhs = fln.getDst();
+ FlatLiteralNode fln = (FlatLiteralNode) fn;
+ lhs = fln.getDst();
- // write(lhs)
- curr.put(lhs, new Hashtable<FlatNode, Boolean>());
+ // write(lhs)
+ curr.put(lhs, new Hashtable<FlatNode, Boolean>());
- System.out.println("WRITING LOC=" + lhs.getType().getExtension());
+ System.out.println("WRITING LOC=" + lhs.getType().getExtension());
}
break;
case FKind.FlatFieldNode:
case FKind.FlatElementNode: {
- FlatFieldNode ffn = (FlatFieldNode) fn;
- lhs = ffn.getSrc();
- fld = ffn.getField();
-
- // read field
- Hashtable<FlatNode, Boolean> gen = curr.get(fld);
- if (gen == null) {
- gen = new Hashtable<FlatNode, Boolean>();
- curr.put(fld, gen);
- }
- Boolean currentStatus = gen.get(fn);
- if (currentStatus == null) {
- gen.put(fn, Boolean.FALSE);
- }
-
- System.out.println("\nffn=" + ffn);
- System.out.println("READ LOCfld=" + fld.getType().getExtension());
- System.out.println("READ LOClhs=" + lhs.getType().getExtension());
+ FlatFieldNode ffn = (FlatFieldNode) fn;
+ lhs = ffn.getSrc();
+ fld = ffn.getField();
+
+ // read field
+ Hashtable<FlatNode, Boolean> gen = curr.get(fld);
+ if (gen == null) {
+ gen = new Hashtable<FlatNode, Boolean>();
+ curr.put(fld, gen);
+ }
+ Boolean currentStatus = gen.get(fn);
+ if (currentStatus == null) {
+ gen.put(fn, Boolean.FALSE);
+ }
+
+ System.out.println("\nffn=" + ffn);
+ System.out.println("READ LOCfld=" + fld.getType().getExtension());
+ System.out.println("READ LOClhs=" + lhs.getType().getExtension());
}
break;
case FKind.FlatSetFieldNode:
case FKind.FlatSetElementNode: {
- FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
- fld = fsfn.getField();
+ FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
+ fld = fsfn.getField();
- // write(field)
- curr.put(fld, new Hashtable<FlatNode, Boolean>());
+ // write(field)
+ curr.put(fld, new Hashtable<FlatNode, Boolean>());
- System.out.println("\nfsfn=" + fsfn);
- System.out.println("WRITELOC LOC=" + fld.getType().getExtension());
+ System.out.println("\nfsfn=" + fsfn);
+ System.out.println("WRITELOC LOC=" + fld.getType().getExtension());
}
break;
if (locTuple.size() != 0) {
int tupleSize = locTuple.size();
for (int i = 0; i < tupleSize; i++) {
- Location locElement = locTuple.at(i);
- if (i != 0) {
- rtr += ",";
- }
- rtr += locElement;
+ Location locElement = locTuple.at(i);
+ if (i != 0) {
+ rtr += ",";
+ }
+ rtr += locElement;
}
} else {
rtr += "LOC_REF";
Set<String> locIdSet = lattice.getKeySet();
for (Iterator iterator2 = locIdSet.iterator(); iterator2.hasNext(); ) {
- String locID = (String) iterator2.next();
- id2cd.put(locID, cd);
+ String locID = (String) iterator2.next();
+ id2cd.put(locID, cd);
}
}
// }
checkDeclarationInClass(cd);
for (Iterator method_it = cd.getMethods(); method_it.hasNext(); ) {
- MethodDescriptor md = (MethodDescriptor) method_it.next();
- try {
- checkDeclarationInMethodBody(cd, md);
- } catch (Error e) {
- System.out.println("Error in " + md);
- throw e;
- }
+ MethodDescriptor md = (MethodDescriptor) method_it.next();
+ try {
+ checkDeclarationInMethodBody(cd, md);
+ } catch (Error e) {
+ System.out.println("Error in " + md);
+ throw e;
+ }
}
}
Location loc = td2loc.get(td);
if (loc.getType() == Location.DELTA) {
- // if it contains delta reference pointing to another location element
- CompositeLocation compLoc = (CompositeLocation) loc;
+ // if it contains delta reference pointing to another location element
+ CompositeLocation compLoc = (CompositeLocation) loc;
- Location locElement = compLoc.getTuple().at(0);
- assert(locElement instanceof DeltaLocation);
+ Location locElement = compLoc.getTuple().at(0);
+ assert(locElement instanceof DeltaLocation);
- DeltaLocation delta = (DeltaLocation) locElement;
- Descriptor refType = delta.getRefLocationId();
- if (refType != null) {
- Location refLoc = td2loc.get(refType);
+ DeltaLocation delta = (DeltaLocation) locElement;
+ Descriptor refType = delta.getRefLocationId();
+ if (refType != null) {
+ Location refLoc = td2loc.get(refType);
- assert(refLoc instanceof CompositeLocation);
- CompositeLocation refCompLoc = (CompositeLocation) refLoc;
+ assert(refLoc instanceof CompositeLocation);
+ CompositeLocation refCompLoc = (CompositeLocation) refLoc;
- assert(refCompLoc.getTuple().at(0) instanceof DeltaLocation);
- DeltaLocation refDelta = (DeltaLocation) refCompLoc.getTuple().at(0);
+ assert(refCompLoc.getTuple().at(0) instanceof DeltaLocation);
+ DeltaLocation refDelta = (DeltaLocation) refCompLoc.getTuple().at(0);
- delta.addDeltaOperand(refDelta);
- // compLoc.addLocation(refDelta);
- }
+ delta.addDeltaOperand(refDelta);
+ // compLoc.addLocation(refDelta);
+ }
}
}
// }
checkClass(cd);
for (Iterator method_it = cd.getMethods(); method_it.hasNext(); ) {
- MethodDescriptor md = (MethodDescriptor) method_it.next();
- try {
- checkMethodBody(cd, md);
- } catch (Error e) {
- System.out.println("Error in " + md);
- throw e;
- }
+ MethodDescriptor md = (MethodDescriptor) method_it.next();
+ try {
+ checkMethodBody(cd, md);
+ } catch (Error e) {
+ System.out.println("Error in " + md);
+ throw e;
+ }
}
}
ClassDescriptor cd = md.getClassDesc();
BlockNode bn = ln.getInitializer();
for (int i = 0; i < bn.size(); i++) {
- BlockStatementNode bsn = bn.get(i);
- checkDeclarationInBlockStatementNode(md, nametable, bsn);
+ BlockStatementNode bsn = bn.get(i);
+ checkDeclarationInBlockStatementNode(md, nametable, bsn);
}
}
CompositeLocation bLoc = checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn);
if (lowestLoc == null) {
- lowestLoc = bLoc;
+ lowestLoc = bLoc;
} else {
- if (CompositeLattice.isGreaterThan(lowestLoc, bLoc, md.getClassDesc())) {
- lowestLoc = bLoc;
- }
+ if (CompositeLattice.isGreaterThan(lowestLoc, bLoc, md.getClassDesc())) {
+ lowestLoc = bLoc;
+ }
}
}
return lowestLoc;
CompositeLocation bodyLoc = checkLocationFromBlockNode(md, nametable, ln.getBody());
if (!CompositeLattice.isGreaterThan(condLoc, bodyLoc, cd)) {
- // loop condition should be higher than loop body
- throw new Error(
- "The location of the while-condition statement is lower than the loop body at "
- + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine());
+ // loop condition should be higher than loop body
+ throw new Error(
+ "The location of the while-condition statement is lower than the loop body at "
+ + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine());
}
return bodyLoc;
CompositeLocation blockLoc = checkLocationFromBlockNode(md, bn.getVarTable(), ln.getBody());
if (blockLoc == null) {
- // when there is no statement in the loop body
- return glbLocOfForLoopCond;
+ // when there is no statement in the loop body
+ return glbLocOfForLoopCond;
}
if (!CompositeLattice.isGreaterThan(glbLocOfForLoopCond, blockLoc, cd)) {
- throw new Error(
- "The location of the for-condition statement is lower than the for-loop body at "
- + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine());
+ throw new Error(
+ "The location of the for-condition statement is lower than the for-loop body at "
+ + cd.getSourceFileName() + ":" + ln.getCondition().getNumLine());
}
return blockLoc;
}
glbInputSet.add(locFalseBlock);
if (!CompositeLattice.isGreaterThan(condLoc, locFalseBlock, localCD)) {
- // error
- throw new Error(
- "The location of the if-condition statement is lower than the conditional block at "
- + localCD.getSourceFileName() + ":" + isn.getCondition().getNumLine());
+ // error
+ throw new Error(
+ "The location of the if-condition statement is lower than the conditional block at "
+ + localCD.getSourceFileName() + ":" + isn.getCondition().getNumLine());
}
}
addTypeLocation(dn.getExpression().getType(), expressionLoc);
if (expressionLoc != null) {
- // checking location order
- if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc, localCD)) {
- throw new Error("The value flow from " + expressionLoc + " to " + destLoc
- + " does not respect location hierarchy on the assignment " + dn.printNode(0));
- }
+ // checking location order
+ if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc, localCD)) {
+ throw new Error("The value flow from " + expressionLoc + " to " + destLoc
+ + " does not respect location hierarchy on the assignment " + dn.printNode(0));
+ }
}
return expressionLoc;
// callee's hierarchy
for (int i = 0; i < min.numArgs(); i++) {
- ExpressionNode en = min.getArg(i);
- CompositeLocation callerArg1 =
- checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(cd));
-
- ClassDescriptor calleecd = min.getMethod().getClassDesc();
- VarDescriptor calleevd = (VarDescriptor) min.getMethod().getParameter(i);
- Location calleeLoc1 = td2loc.get(calleevd);
-
- if (!callerArg1.getLocation(cd).isTop()) {
- // here, check if ordering relations among caller's args respect
- // ordering relations in-between callee's args
- for (int currentIdx = 0; currentIdx < min.numArgs(); currentIdx++) {
- if (currentIdx != i) { // skip itself
- ExpressionNode argExp = min.getArg(currentIdx);
- CompositeLocation callerArg2 =
- checkLocationFromExpressionNode(md, nametable, argExp, new CompositeLocation(cd));
-
- VarDescriptor calleevd2 = (VarDescriptor) min.getMethod().getParameter(currentIdx);
- Location calleeLoc2 = td2loc.get(calleevd2);
- boolean callerResult = CompositeLattice.isGreaterThan(callerArg1, callerArg2, cd);
- boolean calleeResult =
- CompositeLattice.isGreaterThan(calleeLoc1, calleeLoc2, calleecd);
-
- if (calleeResult && !callerResult) {
- // in callee, calleeLoc1 is higher than calleeLoc2
- // then, caller should have same ordering relation in-bet
- // callerLoc1 & callerLoc2
-
- throw new Error("Caller doesn't respect ordering relations among method arguments:"
- + cd.getSourceFileName() + ":" + min.getNumLine());
- }
-
- }
- }
- }
+ ExpressionNode en = min.getArg(i);
+ CompositeLocation callerArg1 =
+ checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(cd));
+
+ ClassDescriptor calleecd = min.getMethod().getClassDesc();
+ VarDescriptor calleevd = (VarDescriptor) min.getMethod().getParameter(i);
+ Location calleeLoc1 = td2loc.get(calleevd);
+
+ if (!callerArg1.getLocation(cd).isTop()) {
+ // here, check if ordering relations among caller's args respect
+ // ordering relations in-between callee's args
+ for (int currentIdx = 0; currentIdx < min.numArgs(); currentIdx++) {
+ if (currentIdx != i) { // skip itself
+ ExpressionNode argExp = min.getArg(currentIdx);
+ CompositeLocation callerArg2 =
+ checkLocationFromExpressionNode(md, nametable, argExp, new CompositeLocation(cd));
+
+ VarDescriptor calleevd2 = (VarDescriptor) min.getMethod().getParameter(currentIdx);
+ Location calleeLoc2 = td2loc.get(calleevd2);
+ boolean callerResult = CompositeLattice.isGreaterThan(callerArg1, callerArg2, cd);
+ boolean calleeResult =
+ CompositeLattice.isGreaterThan(calleeLoc1, calleeLoc2, calleecd);
+
+ if (calleeResult && !callerResult) {
+ // in callee, calleeLoc1 is higher than calleeLoc2
+ // then, caller should have same ordering relation in-bet
+ // callerLoc1 & callerLoc2
+
+ throw new Error("Caller doesn't respect ordering relations among method arguments:"
+ + cd.getSourceFileName() + ":" + min.getNumLine());
+ }
+
+ }
+ }
+ }
}
Location localLoc = null;
if (d instanceof VarDescriptor) {
- VarDescriptor vd = (VarDescriptor) d;
- localLoc = td2loc.get(vd);
+ VarDescriptor vd = (VarDescriptor) d;
+ localLoc = td2loc.get(vd);
} else if (d instanceof FieldDescriptor) {
- FieldDescriptor fd = (FieldDescriptor) d;
- localLoc = td2loc.get(fd);
+ FieldDescriptor fd = (FieldDescriptor) d;
+ localLoc = td2loc.get(fd);
}
assert(localLoc != null);
if (localLoc instanceof CompositeLocation) {
- loc = (CompositeLocation) localLoc;
+ loc = (CompositeLocation) localLoc;
} else {
- loc.addLocation(localLoc);
+ loc.addLocation(localLoc);
}
}
srcLocation = checkLocationFromExpressionNode(md, nametable, an.getSrc(), srcLocation);
if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, cd)) {
- throw new Error("The value flow from " + srcLocation + " to " + destLocation
- + " does not respect location hierarchy on the assignment " + an.printNode(0));
+ throw new Error("The value flow from " + srcLocation + " to " + destLocation
+ + " does not respect location hierarchy on the assignment " + an.printNode(0));
}
} else {
destLocation =
if (!((Set<String>)state.getCd2LocationPropertyMap().get(cd)).contains(destLocation
.getLocation(cd).getLocIdentifier())) {
- throw new Error("Location " + destLocation + " is not allowed to have spinning values at "
- + cd.getSourceFileName() + ":" + an.getNumLine());
+ throw new Error("Location " + destLocation + " is not allowed to have spinning values at "
+ + cd.getSourceFileName() + ":" + an.getNumLine());
}
}
Lattice<String> lattice = (Lattice<String>)state.getCd2LocationOrder().get(cd);
if (lattice == null || (!lattice.containsKey(locationID))) {
- throw new Error("Location " + locationID
- + " is not defined in the location hierarchy of class " + cd.getSymbol() + ".");
+ throw new Error("Location " + locationID
+ + " is not defined in the location hierarchy of class " + cd.getSymbol() + ".");
}
Location loc = new Location(cd, locationID);
} else if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
if (ad.getMarker().equals(SSJavaAnalysis.DELTA)) {
- CompositeLocation compLoc = new CompositeLocation(cd);
-
- if (ad.getData().length() == 0) {
- throw new Error("Delta function of " + vd.getSymbol() + " does not have any locations: "
- + cd.getSymbol() + ".");
- }
-
- String deltaStr = ad.getData();
- if (deltaStr.startsWith("LOC(")) {
-
- if (!deltaStr.endsWith(")")) {
- throw new Error("The declaration of the delta location is wrong at "
- + cd.getSourceFileName() + ":" + n.getNumLine());
- }
- String locationOperand = deltaStr.substring(4, deltaStr.length() - 1);
-
- nametable.get(locationOperand);
- Descriptor d = (Descriptor) nametable.get(locationOperand);
-
- if (d instanceof VarDescriptor) {
- VarDescriptor varDescriptor = (VarDescriptor) d;
- DeltaLocation deltaLoc = new DeltaLocation(cd, varDescriptor);
- // td2loc.put(vd.getType(), compLoc);
- compLoc.addLocation(deltaLoc);
- } else if (d instanceof FieldDescriptor) {
- throw new Error("Applying delta operation to the field " + locationOperand
- + " is not allowed at " + cd.getSourceFileName() + ":" + n.getNumLine());
- }
- } else {
- StringTokenizer token = new StringTokenizer(deltaStr, ",");
- DeltaLocation deltaLoc = new DeltaLocation(cd);
-
- while (token.hasMoreTokens()) {
- String deltaOperand = token.nextToken();
- ClassDescriptor deltaCD = id2cd.get(deltaOperand);
- if (deltaCD == null) {
- // delta operand is not defined in the location hierarchy
- throw new Error("Delta operand '" + deltaOperand + "' of declaration node '" + vd
- + "' is not defined by location hierarchies.");
- }
-
- Location loc = new Location(deltaCD, deltaOperand);
- deltaLoc.addDeltaOperand(loc);
- }
- compLoc.addLocation(deltaLoc);
-
- }
-
- td2loc.put(vd, compLoc);
- addTypeLocation(vd.getType(), compLoc);
+ CompositeLocation compLoc = new CompositeLocation(cd);
+
+ if (ad.getData().length() == 0) {
+ throw new Error("Delta function of " + vd.getSymbol() + " does not have any locations: "
+ + cd.getSymbol() + ".");
+ }
+
+ String deltaStr = ad.getData();
+ if (deltaStr.startsWith("LOC(")) {
+
+ if (!deltaStr.endsWith(")")) {
+ throw new Error("The declaration of the delta location is wrong at "
+ + cd.getSourceFileName() + ":" + n.getNumLine());
+ }
+ String locationOperand = deltaStr.substring(4, deltaStr.length() - 1);
+
+ nametable.get(locationOperand);
+ Descriptor d = (Descriptor) nametable.get(locationOperand);
+
+ if (d instanceof VarDescriptor) {
+ VarDescriptor varDescriptor = (VarDescriptor) d;
+ DeltaLocation deltaLoc = new DeltaLocation(cd, varDescriptor);
+ // td2loc.put(vd.getType(), compLoc);
+ compLoc.addLocation(deltaLoc);
+ } else if (d instanceof FieldDescriptor) {
+ throw new Error("Applying delta operation to the field " + locationOperand
+ + " is not allowed at " + cd.getSourceFileName() + ":" + n.getNumLine());
+ }
+ } else {
+ StringTokenizer token = new StringTokenizer(deltaStr, ",");
+ DeltaLocation deltaLoc = new DeltaLocation(cd);
+
+ while (token.hasMoreTokens()) {
+ String deltaOperand = token.nextToken();
+ ClassDescriptor deltaCD = id2cd.get(deltaOperand);
+ if (deltaCD == null) {
+ // delta operand is not defined in the location hierarchy
+ throw new Error("Delta operand '" + deltaOperand + "' of declaration node '" + vd
+ + "' is not defined by location hierarchies.");
+ }
+
+ Location loc = new Location(deltaCD, deltaOperand);
+ deltaLoc.addDeltaOperand(loc);
+ }
+ compLoc.addLocation(deltaLoc);
+
+ }
+
+ td2loc.put(vd, compLoc);
+ addTypeLocation(vd.getType(), compLoc);
}
}
Lattice<String> lattice = (Lattice<String>)state.getCd2LocationOrder().get(cd);
if (lattice == null || (!lattice.containsKey(locationID))) {
- throw new Error("Location " + locationID
- + " is not defined in the location hierarchy of class " + cd.getSymbol() + ".");
+ throw new Error("Location " + locationID
+ + " is not defined in the location hierarchy of class " + cd.getSymbol() + ".");
}
Location localLoc = new Location(cd, locationID);
} else if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
if (ad.getMarker().equals(SSJavaAnalysis.DELTA)) {
- if (ad.getData().length() == 0) {
- throw new Error("Delta function of " + fd.getSymbol() + " does not have any locations: "
- + cd.getSymbol() + ".");
- }
-
- CompositeLocation compLoc = new CompositeLocation(cd);
- DeltaLocation deltaLoc = new DeltaLocation(cd);
-
- StringTokenizer token = new StringTokenizer(ad.getData(), ",");
- while (token.hasMoreTokens()) {
- String deltaOperand = token.nextToken();
- ClassDescriptor deltaCD = id2cd.get(deltaOperand);
- if (deltaCD == null) {
- // delta operand is not defined in the location hierarchy
- throw new Error("Delta operand '" + deltaOperand + "' of field node '" + fd
- + "' is not defined by location hierarchies.");
- }
-
- Location loc = new Location(deltaCD, deltaOperand);
- deltaLoc.addDeltaOperand(loc);
- }
- compLoc.addLocation(deltaLoc);
- td2loc.put(fd, compLoc);
- addTypeLocation(fd.getType(), compLoc);
+ if (ad.getData().length() == 0) {
+ throw new Error("Delta function of " + fd.getSymbol() + " does not have any locations: "
+ + cd.getSymbol() + ".");
+ }
+
+ CompositeLocation compLoc = new CompositeLocation(cd);
+ DeltaLocation deltaLoc = new DeltaLocation(cd);
+
+ StringTokenizer token = new StringTokenizer(ad.getData(), ",");
+ while (token.hasMoreTokens()) {
+ String deltaOperand = token.nextToken();
+ ClassDescriptor deltaCD = id2cd.get(deltaOperand);
+ if (deltaCD == null) {
+ // delta operand is not defined in the location hierarchy
+ throw new Error("Delta operand '" + deltaOperand + "' of field node '" + fd
+ + "' is not defined by location hierarchies.");
+ }
+
+ Location loc = new Location(deltaCD, deltaOperand);
+ deltaLoc.addDeltaOperand(loc);
+ }
+ compLoc.addLocation(deltaLoc);
+ td2loc.put(fd, compLoc);
+ addTypeLocation(fd.getType(), compLoc);
}
}
CompositeLocation compLoc2;
if (loc1 instanceof CompositeLocation) {
- compLoc1 = (CompositeLocation) loc1;
+ compLoc1 = (CompositeLocation) loc1;
} else {
- // create a bogus composite location for a single location
- compLoc1 = new CompositeLocation(loc1.getClassDescriptor());
- compLoc1.addLocation(loc1);
+ // create a bogus composite location for a single location
+ compLoc1 = new CompositeLocation(loc1.getClassDescriptor());
+ compLoc1.addLocation(loc1);
}
if (loc2 instanceof CompositeLocation) {
- compLoc2 = (CompositeLocation) loc2;
+ compLoc2 = (CompositeLocation) loc2;
} else {
- // create a bogus composite location for a single location
- compLoc2 = new CompositeLocation(loc2.getClassDescriptor());
- compLoc2.addLocation(loc2);
+ // create a bogus composite location for a single location
+ compLoc2 = new CompositeLocation(loc2.getClassDescriptor());
+ compLoc2.addLocation(loc2);
}
// comparing two composite locations
int baseCompareResult = compareBaseLocationSet(compLoc1, compLoc2, priorityCD);
if (baseCompareResult == ComparisonResult.EQUAL) {
- if (compareDelta(compLoc1, compLoc2) == ComparisonResult.GREATER) {
- return true;
- } else {
- return false;
- }
+ if (compareDelta(compLoc1, compLoc2) == ComparisonResult.GREATER) {
+ return true;
+ } else {
+ return false;
+ }
} else if (baseCompareResult == ComparisonResult.GREATER) {
- return true;
+ return true;
} else {
- return false;
+ return false;
}
}
private static int compareDelta(CompositeLocation compLoc1, CompositeLocation compLoc2) {
if (compLoc1.getNumofDelta() < compLoc2.getNumofDelta()) {
- return ComparisonResult.GREATER;
+ return ComparisonResult.GREATER;
} else {
- return ComparisonResult.LESS;
+ return ComparisonResult.LESS;
}
}
Lattice<String> locationOrder = (Lattice<String>)state.getCd2LocationOrder().get(cd);
if (priorityLoc1.getLocIdentifier().equals(priorityLoc2.getLocIdentifier())) {
- // have the same level of local hierarchy
+ // have the same level of local hierarchy
- Set<String> spinSet = (Set<String>)state.getCd2LocationPropertyMap().get(cd);
- if (spinSet != null && spinSet.contains(priorityLoc1.getLocIdentifier())) {
- // this location can be spinning
- return ComparisonResult.GREATER;
- }
+ Set<String> spinSet = (Set<String>)state.getCd2LocationPropertyMap().get(cd);
+ if (spinSet != null && spinSet.contains(priorityLoc1.getLocIdentifier())) {
+ // this location can be spinning
+ return ComparisonResult.GREATER;
+ }
} else if (locationOrder.isGreaterThan(priorityLoc1.getLocIdentifier(),
priorityLoc2.getLocIdentifier())) {
- // if priority loc of compLoc1 is higher than compLoc2
- // then, compLoc 1 is higher than compLoc2
- return ComparisonResult.GREATER;
+ // if priority loc of compLoc1 is higher than compLoc2
+ // then, compLoc 1 is higher than compLoc2
+ return ComparisonResult.GREATER;
} else {
- // if priority loc of compLoc1 is NOT higher than compLoc2
- // then, compLoc 1 is NOT higher than compLoc2
- return ComparisonResult.LESS;
+ // if priority loc of compLoc1 is NOT higher than compLoc2
+ // then, compLoc 1 is NOT higher than compLoc2
+ return ComparisonResult.LESS;
}
// compare base locations except priority by class descriptor
int numEqualLoc = 0;
for (Iterator iterator = keySet1.iterator(); iterator.hasNext(); ) {
- ClassDescriptor cd1 = (ClassDescriptor) iterator.next();
-
- Location loc1 = cd2loc1.get(cd1);
- Location loc2 = cd2loc2.get(cd1);
-
- if (priorityLoc1.equals(loc1)) {
- continue;
- }
-
- if (loc2 == null) {
- // if comploc2 doesn't have corresponding location,
- // then we determines that comploc1 is lower than comploc 2
- return ComparisonResult.LESS;
- }
-
- System.out.println("lattice comparison:" + loc1.getLocIdentifier() + " ? "
- + loc2.getLocIdentifier());
- locationOrder = (Lattice<String>)state.getCd2LocationOrder().get(cd1);
- if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
- // have the same level of local hierarchy
- numEqualLoc++;
- } else if (!locationOrder.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
- // if one element of composite location 1 is not higher than composite
- // location 2
- // then, composite loc 1 is not higher than composite loc 2
-
- System.out.println(compLoc1 + " < " + compLoc2);
- return ComparisonResult.LESS;
- }
+ ClassDescriptor cd1 = (ClassDescriptor) iterator.next();
+
+ Location loc1 = cd2loc1.get(cd1);
+ Location loc2 = cd2loc2.get(cd1);
+
+ if (priorityLoc1.equals(loc1)) {
+ continue;
+ }
+
+ if (loc2 == null) {
+ // if comploc2 doesn't have corresponding location,
+ // then we determines that comploc1 is lower than comploc 2
+ return ComparisonResult.LESS;
+ }
+
+ System.out.println("lattice comparison:" + loc1.getLocIdentifier() + " ? "
+ + loc2.getLocIdentifier());
+ locationOrder = (Lattice<String>)state.getCd2LocationOrder().get(cd1);
+ if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
+ // have the same level of local hierarchy
+ numEqualLoc++;
+ } else if (!locationOrder.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
+ // if one element of composite location 1 is not higher than composite
+ // location 2
+ // then, composite loc 1 is not higher than composite loc 2
+
+ System.out.println(compLoc1 + " < " + compLoc2);
+ return ComparisonResult.LESS;
+ }
}
if (numEqualLoc == (compLoc1.getBaseLocationSize() - 1)) {
- return ComparisonResult.EQUAL;
+ return ComparisonResult.EQUAL;
}
System.out.println(compLoc1 + " > " + compLoc2);
// creating mapping from class to set of locations
for (Iterator iterator = inputSet.iterator(); iterator.hasNext(); ) {
- CompositeLocation compLoc = (CompositeLocation) iterator.next();
+ CompositeLocation compLoc = (CompositeLocation) iterator.next();
- int numOfDelta = compLoc.getNumofDelta();
- if (numOfDelta > maxDeltaFunction) {
- maxDeltaFunction = numOfDelta;
- }
+ int numOfDelta = compLoc.getNumofDelta();
+ if (numOfDelta > maxDeltaFunction) {
+ maxDeltaFunction = numOfDelta;
+ }
- Set<Location> baseLocationSet = compLoc.getBaseLocationSet();
- for (Iterator iterator2 = baseLocationSet.iterator(); iterator2.hasNext(); ) {
- Location locElement = (Location) iterator2.next();
- ClassDescriptor locCD = locElement.getClassDescriptor();
+ Set<Location> baseLocationSet = compLoc.getBaseLocationSet();
+ for (Iterator iterator2 = baseLocationSet.iterator(); iterator2.hasNext(); ) {
+ Location locElement = (Location) iterator2.next();
+ ClassDescriptor locCD = locElement.getClassDescriptor();
- Set<Location> locSet = cd2locSet.get(locCD);
- if (locSet == null) {
- locSet = new HashSet<Location>();
- }
- locSet.add(locElement);
+ Set<Location> locSet = cd2locSet.get(locCD);
+ if (locSet == null) {
+ locSet = new HashSet<Location>();
+ }
+ locSet.add(locElement);
- cd2locSet.put(locCD, locSet);
+ cd2locSet.put(locCD, locSet);
- }
+ }
}
Set<Location> locSetofClass = cd2locSet.get(priorityCD);
Set<String> locIdentifierSet = new HashSet<String>();
for (Iterator<Location> locIterator = locSetofClass.iterator(); locIterator.hasNext(); ) {
- Location locElement = locIterator.next();
- locIdentifierSet.add(locElement.getLocIdentifier());
+ Location locElement = locIterator.next();
+ locIdentifierSet.add(locElement.getLocIdentifier());
}
Lattice<String> locOrder = (Lattice<String>)state.getCd2LocationOrder().get(priorityCD);
Set<CompositeLocation> sameGLBLoc = new HashSet<CompositeLocation>();
for (Iterator<CompositeLocation> iterator = inputSet.iterator(); iterator.hasNext(); ) {
- CompositeLocation inputComploc = iterator.next();
- Location locElement = inputComploc.getLocation(priorityCD);
+ CompositeLocation inputComploc = iterator.next();
+ Location locElement = inputComploc.getLocation(priorityCD);
- if (locElement.equals(priorityGLB)) {
- sameGLBLoc.add(inputComploc);
- }
+ if (locElement.equals(priorityGLB)) {
+ sameGLBLoc.add(inputComploc);
+ }
}
glbCompLoc.addLocation(priorityGLB);
if (sameGLBLoc.size() > 0) {
- // if more than one location shares the same priority GLB
- // need to calculate the rest of GLB loc
-
- Set<Location> glbElementSet = new HashSet<Location>();
-
- for (Iterator<ClassDescriptor> iterator = cd2locSet.keySet().iterator(); iterator.hasNext(); ) {
- ClassDescriptor localCD = iterator.next();
- if (!localCD.equals(priorityCD)) {
- Set<Location> localLocSet = cd2locSet.get(localCD);
- Set<String> LocalLocIdSet = new HashSet<String>();
-
- for (Iterator<Location> locIterator = localLocSet.iterator(); locIterator.hasNext(); ) {
- Location locElement = locIterator.next();
- LocalLocIdSet.add(locElement.getLocIdentifier());
- }
-
- Lattice<String> localOrder = (Lattice<String>)state.getCd2LocationOrder().get(localCD);
- Location localGLBLoc = new Location(localCD, localOrder.getGLB(LocalLocIdSet));
- glbCompLoc.addLocation(localGLBLoc);
- }
- }
+ // if more than one location shares the same priority GLB
+ // need to calculate the rest of GLB loc
+
+ Set<Location> glbElementSet = new HashSet<Location>();
+
+ for (Iterator<ClassDescriptor> iterator = cd2locSet.keySet().iterator(); iterator.hasNext(); ) {
+ ClassDescriptor localCD = iterator.next();
+ if (!localCD.equals(priorityCD)) {
+ Set<Location> localLocSet = cd2locSet.get(localCD);
+ Set<String> LocalLocIdSet = new HashSet<String>();
+
+ for (Iterator<Location> locIterator = localLocSet.iterator(); locIterator.hasNext(); ) {
+ Location locElement = locIterator.next();
+ LocalLocIdSet.add(locElement.getLocIdentifier());
+ }
+
+ Lattice<String> localOrder = (Lattice<String>)state.getCd2LocationOrder().get(localCD);
+ Location localGLBLoc = new Location(localCD, localOrder.getGLB(LocalLocIdSet));
+ glbCompLoc.addLocation(localGLBLoc);
+ }
+ }
} else {
- // if priority glb loc is lower than all of input loc
- // assign top location to the rest of loc element
+ // if priority glb loc is lower than all of input loc
+ // assign top location to the rest of loc element
- for (Iterator<ClassDescriptor> iterator = cd2locSet.keySet().iterator(); iterator.hasNext(); ) {
- ClassDescriptor localCD = iterator.next();
- if (!localCD.equals(priorityCD)) {
- Location localGLBLoc = Location.createTopLocation(localCD);
- glbCompLoc.addLocation(localGLBLoc);
- }
+ for (Iterator<ClassDescriptor> iterator = cd2locSet.keySet().iterator(); iterator.hasNext(); ) {
+ ClassDescriptor localCD = iterator.next();
+ if (!localCD.equals(priorityCD)) {
+ Location localGLBLoc = Location.createTopLocation(localCD);
+ glbCompLoc.addLocation(localGLBLoc);
+ }
- }
+ }
}
if (loc.getClassDescriptor().equals(getClassDescriptor())) {
if (loc.getLocIdentifier() == null || getLocIdentifier() == null) {
- if (loc.getType() == getType()) {
- return true;
- }
+ if (loc.getType() == getType()) {
+ return true;
+ }
} else {
- if (loc.getLocIdentifier().equals(getLocIdentifier())) {
- return true;
- }
+ if (loc.getLocIdentifier().equals(getLocIdentifier())) {
+ return true;
+ }
}
}
(fs.isSorted() != sorted) ||
(fs.clone != this.clone) ||
(fs.transTime != this.transTime)) {
- return false;
+ return false;
}
return (fs.getFlagStates().equals(flagStates));
}
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);
- toadd = 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);
+ toadd = null;
} else {
- if(this.rootNodes.size() == 1) {
- return false;
- }
- int next = this.rootNodes.lastElement().elementAt(0).getCid() + 1;
- int num2choose = 0;
- while(next == this.sNodeVecs.size()) {
- // backtrack
- num2choose = this.rootNodes.lastElement().size();
- this.rootNodes.removeElementAt(this.rootNodes.size() - 1);
- if(this.rootNodes.size() == 1) {
- // only startup object left, no more choices
- return false;
- }
- next = this.rootNodes.lastElement().elementAt(0).getCid() + 1;
- }
- num2choose++;
- // reduce one from the last one
- this.rootNodes.lastElement().removeElementAt(this.rootNodes.lastElement().size() - 1);
- if(this.rootNodes.lastElement().size() == 0) {
- this.rootNodes.removeElementAt(this.rootNodes.size() - 1);
- }
-
- trial = trial(num2choose, next);
+ if(this.rootNodes.size() == 1) {
+ return false;
+ }
+ int next = this.rootNodes.lastElement().elementAt(0).getCid() + 1;
+ int num2choose = 0;
+ while(next == this.sNodeVecs.size()) {
+ // backtrack
+ num2choose = this.rootNodes.lastElement().size();
+ this.rootNodes.removeElementAt(this.rootNodes.size() - 1);
+ if(this.rootNodes.size() == 1) {
+ // only startup object left, no more choices
+ return false;
+ }
+ next = this.rootNodes.lastElement().elementAt(0).getCid() + 1;
+ }
+ num2choose++;
+ // reduce one from the last one
+ this.rootNodes.lastElement().removeElementAt(this.rootNodes.lastElement().size() - 1);
+ if(this.rootNodes.lastElement().size() == 0) {
+ this.rootNodes.removeElementAt(this.rootNodes.size() - 1);
+ }
+
+ trial = trial(num2choose, next);
}
if(trial) {
- // remaining nodes are all to be combined
- this.node2Combine = new Vector<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));
- }
- toadd = null;
- } 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));
- }
- }
- toadd = null;
- 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));
- }
- toadd = null;
- } else {
- this.node2Combine.add(null);
- }
- next++;
- }
+ // remaining 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));
+ }
+ toadd = null;
+ } 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));
+ }
+ }
+ toadd = null;
+ 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));
+ }
+ toadd = null;
+ } else {
+ this.node2Combine.add(null);
+ }
+ next++;
+ }
}
return trial;
}
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;
- }
+ 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;
}
this.rootNStates = new Vector<Vector<int[]>>();
int rootnum = 0;
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;
- }
- rootnum++;
- }
+ 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;
+ }
+ rootnum++;
+ }
}
this.combine = new Vector<Vector<Combine>>();
int tomapnum = 0;
for(int i = 0; i < this.node2Combine.size(); i++) {
- if(this.node2Combine.elementAt(i) == null) {
- this.combine.add(null);
- } else {
- this.combine.add(new Vector<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)));
- tomapnum++;
- }
- }
+ 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)));
+ tomapnum++;
+ }
+ }
}
this.lastchoices = null;
this.first4choice = false;
public boolean randomGenE() {
this.rootLoads = new int[this.rootNodes.size()][];
for(int i = 0; i < this.rootNodes.size(); i++) {
- this.rootLoads[i] = new int[this.rootNodes.elementAt(i).size()];
+ this.rootLoads[i] = new int[this.rootNodes.elementAt(i).size()];
}
int rootx = this.rootNodes.size();
for(int i = 0; i < this.node2Combine.size(); i++) {
- for(int j = 0; j < this.node2Combine.elementAt(i).size(); j++) {
- Combine tmp = this.combine.elementAt(i).elementAt(j);
- do {
- int x = Math.abs(rand.nextInt()) % rootx;
- int y = Math.abs(rand.nextInt()) % this.rootNodes.elementAt(x).size();
- if(this.rootLoads[x][y] < this.limit) {
- tmp.root = x;
- tmp.index = y;
- this.rootLoads[tmp.root][tmp.index]++;
- break;
- }
- } while(true);
- }
+ for(int j = 0; j < this.node2Combine.elementAt(i).size(); j++) {
+ Combine tmp = this.combine.elementAt(i).elementAt(j);
+ do {
+ int x = Math.abs(rand.nextInt()) % rootx;
+ int y = Math.abs(rand.nextInt()) % this.rootNodes.elementAt(x).size();
+ if(this.rootLoads[x][y] < this.limit) {
+ tmp.root = x;
+ tmp.index = y;
+ this.rootLoads[tmp.root][tmp.index]++;
+ break;
+ }
+ } while(true);
+ }
}
return true;
}
public boolean randomGen() {
int rootx = this.rootNodes.size();
for(int i = 0; i < this.node2Combine.size(); i++) {
- for(int j = 0; j < this.node2Combine.elementAt(i).size(); j++) {
- Combine tmp = this.combine.elementAt(i).elementAt(j);
- tmp.root = Math.abs(rand.nextInt()) % rootx;
- tmp.index = Math.abs(rand.nextInt()) % this.rootNodes.elementAt(tmp.root).size();
- }
+ for(int j = 0; j < this.node2Combine.elementAt(i).size(); j++) {
+ Combine tmp = this.combine.elementAt(i).elementAt(j);
+ tmp.root = Math.abs(rand.nextInt()) % rootx;
+ tmp.index = Math.abs(rand.nextInt()) % this.rootNodes.elementAt(tmp.root).size();
+ }
}
return true;
}
public boolean nextGen() {
boolean trial = false;
if(this.lastchoices == null) {
- // first time
- this.lastchoices = new int[this.node2Combine.size()];
- for(int i = 0; i < this.lastchoices.length; i++) {
- this.lastchoices[i] = 0;
- }
- this.first4choice = true;
- trial = trial();
+ // first time
+ this.lastchoices = new int[this.node2Combine.size()];
+ for(int i = 0; i < this.lastchoices.length; i++) {
+ this.lastchoices[i] = 0;
+ }
+ this.first4choice = true;
+ trial = trial();
} else {
- trial = trial();
- while(!trial) {
- // no more available combination under this choice
- // choose another choice
- int next = this.node2Combine.size() - 1;
- boolean iter = false;
- do {
- if(this.node2Combine.elementAt(next) != null) {
- this.lastchoices[next]++;
- if((this.lastchoices[next] == this.rootNodes.size() ||
- (this.rootNodes.elementAt(this.lastchoices[next]).elementAt(0).getCid() >
- this.node2Combine.elementAt(next).elementAt(0).getCid()))) {
- // break the rule that a node can only be combined to nodes with smaller colorid.
- // or no more buckets
- // backtrack
- next--;
- iter = true;
- } else {
- iter = false;
- }
- } else {
- next--;
- iter = true;
- }
- } while(iter && !(next < 0));
- if(next < 0) {
- return false;
- }
- for(next += 1; next < this.node2Combine.size(); next++) {
- this.lastchoices[next] = 0;
- }
- this.first4choice = true;
- trial = trial();
- }
+ trial = trial();
+ while(!trial) {
+ // no more available combination under this choice
+ // choose another choice
+ int next = this.node2Combine.size() - 1;
+ boolean iter = false;
+ do {
+ if(this.node2Combine.elementAt(next) != null) {
+ this.lastchoices[next]++;
+ if((this.lastchoices[next] == this.rootNodes.size() ||
+ (this.rootNodes.elementAt(this.lastchoices[next]).elementAt(0).getCid() >
+ this.node2Combine.elementAt(next).elementAt(0).getCid()))) {
+ // break the rule that a node can only be combined to nodes with smaller colorid.
+ // or no more buckets
+ // backtrack
+ next--;
+ iter = true;
+ } else {
+ iter = false;
+ }
+ } else {
+ next--;
+ iter = true;
+ }
+ } while(iter && !(next < 0));
+ if(next < 0) {
+ return false;
+ }
+ for(next += 1; next < this.node2Combine.size(); next++) {
+ this.lastchoices[next] = 0;
+ }
+ this.first4choice = true;
+ trial = trial();
+ }
}
return trial;
}
private boolean trial() {
boolean suc = false;
if(this.first4choice) {
- // first time for each choice
- // put all the objects of one color into the first bucket indicated by the choice
- int next = 0;
- suc = firstexpand(next, this.first4choice);
- this.first4choice = false;
+ // first time for each choice
+ // put all the objects of one color into the first bucket indicated by the choice
+ int next = 0;
+ suc = firstexpand(next, this.first4choice);
+ this.first4choice = false;
} else {
- int next = this.node2Combine.size() - 1;
- int layer = 0;
- suc = innertrial(next, layer);
+ int next = this.node2Combine.size() - 1;
+ int layer = 0;
+ suc = innertrial(next, layer);
}
return suc;
}
private boolean firstexpand(int next,
boolean first) {
for(int i = next; i < this.node2Combine.size(); i++) {
- if(this.node2Combine.elementAt(i) != null) {
- int choice = this.lastchoices[i];
- for(int j = 0; j < this.node2Combine.elementAt(i).size(); j++) {
- Combine tmp = this.combine.elementAt(i).elementAt(j);
- if(!first) {
- this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--;
- }
- tmp.root = choice;
- tmp.index = 0;
- if(!first) {
- this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++;
- }
- }
- if(first) {
- this.rootNStates.elementAt(choice).elementAt(0)[i] = this.node2Combine.elementAt(i).size();
- for(int j = 1; j < this.rootNodes.elementAt(choice).size(); j++) {
- this.rootNStates.elementAt(choice).elementAt(j)[i] = 0;
- }
- }
- }
+ if(this.node2Combine.elementAt(i) != null) {
+ int choice = this.lastchoices[i];
+ for(int j = 0; j < this.node2Combine.elementAt(i).size(); j++) {
+ Combine tmp = this.combine.elementAt(i).elementAt(j);
+ if(!first) {
+ this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--;
+ }
+ tmp.root = choice;
+ tmp.index = 0;
+ if(!first) {
+ this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++;
+ }
+ }
+ if(first) {
+ this.rootNStates.elementAt(choice).elementAt(0)[i] = this.node2Combine.elementAt(i).size();
+ for(int j = 1; j < this.rootNodes.elementAt(choice).size(); j++) {
+ this.rootNStates.elementAt(choice).elementAt(j)[i] = 0;
+ }
+ }
+ }
}
return true;
}
int layer) {
if((this.combine.elementAt(next) == null) ||
(this.combine.elementAt(next).size() < 2)) {
- // skip over empty buckets and bucket with only one obj ( make sure
- // at least one obj is existing in the chosen bucket)
- if(next - 1 < 0) {
- return false;
- } else {
- return innertrial(next - 1, ++layer);
- }
+ // skip over empty buckets and bucket with only one obj ( make sure
+ // at least one obj is existing in the chosen bucket)
+ if(next - 1 < 0) {
+ return false;
+ } else {
+ return innertrial(next - 1, ++layer);
+ }
}
Combine tmp = this.combine.elementAt(next).lastElement();
// try to move it backward
int index = tmp.index;
index++;
if(index == this.rootNodes.elementAt(root).size()) {
- // no more place in this color bucket
- index = 0;
- root++;
+ // no more place in this color bucket
+ index = 0;
+ root++;
} else if(this.rootNStates.elementAt(root).elementAt(index - 1)[next] <
this.rootNStates.elementAt(root).elementAt(index)[next] + 2) {
- // break the law of non-increase order inside one color bucket
- // try next bucket of another color
- index = 0;
- root++;
+ // break the law of non-increase order inside one color bucket
+ // try next bucket of another color
+ index = 0;
+ root++;
}
if(root == this.rootNodes.size()) {
- // no more bucket
- // backtrack
- root = tmp.root;
- index = tmp.index;
- int t = this.combine.elementAt(next).size() - 2;
- while(true) {
- while(!(t < 0)) {
- tmp = this.combine.elementAt(next).elementAt(t);
- if ((tmp.root != root) || (tmp.index != index)) {
- break;
- }
- t--;
- }
- if(t < 0) {
- // try the bucket in node2combine before
- if(next - 1 < 0) {
- return false;
- } else {
- return innertrial(next - 1, ++layer);
- }
- } else if(tmp.root != root) {
- if((tmp.root == this.lastchoices[next]) &&
- (this.rootNStates.elementAt(this.lastchoices[next]).elementAt(0)[next] == 1)) {
- // only 1 obj left in the chosen bucket
- // can not move this one
- // try the bucket in node2combine before
- if(next - 1 < 0) {
- return false;
- } else {
- return innertrial(next - 1, ++layer);
- }
- }
- this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--;
- //tmp.root = root;
- int newroot = tmp.root + 1;
- tmp.root = newroot;
- tmp.index = 0;
- this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++;
- // make all left things in this color bucket reset
- for(t++; t < this.combine.elementAt(next).size(); t++) {
- tmp = this.combine.elementAt(next).elementAt(t);
- this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--;
- tmp.root = newroot;
- tmp.index = 0;
- this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++;
- }
- if(layer != 0) {
- return firstexpand(next+1, this.first4choice);
- }
- return true;
- } else if(tmp.index != index) {
- if(this.rootNStates.elementAt(root).elementAt(tmp.index)[next] ==
- this.rootNStates.elementAt(root).elementAt(index)[next]) {
- // break the law of non-increase order inside one color bucket
- // go on search forward
- index = tmp.index;
- } else if(this.rootNStates.elementAt(root).elementAt(tmp.index)[next] <
- this.rootNStates.elementAt(root).elementAt(index)[next] + 2) {
- // break the law of non-increase order inside one color bucket
- // and now they only differ by 1
- // propagate this difference to see if it can fix
- boolean suc = propagateOne(next, root, index, t, tmp);
- if(suc) {
- return suc;
- } else {
- // go on search forward
- index = tmp.index;
- }
- } else {
- this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--;
- int tmproot = tmp.root;
- int tmpindex = tmp.index;
- tmp.root = root;
- tmp.index = index;
- this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++;
- int desroot = tmp.root;
- int desindex = tmp.index;
- // make all left things in this color bucket reset
- t++;
- boolean first = true;
- while(t < this.combine.elementAt(next).size()) {
- int k = 0;
- if(first) {
- k = 1;
- first = false;
- }
- for(; (k < this.rootNStates.elementAt(tmproot).elementAt(tmpindex)[next]) && (t < this.combine.elementAt(next).size()); t++) {
- tmp = this.combine.elementAt(next).elementAt(t);
- this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--;
- tmp.root = desroot;
- tmp.index = desindex;
- this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++;
- }
- if(k == this.rootNStates.elementAt(tmproot).elementAt(tmpindex)[next]) {
- desindex++;
- }
- }
- if(layer != 0) {
- return firstexpand(next+1, this.first4choice);
- }
- return true;
- }
- }
- }
+ // no more bucket
+ // backtrack
+ root = tmp.root;
+ index = tmp.index;
+ int t = this.combine.elementAt(next).size() - 2;
+ while(true) {
+ while(!(t < 0)) {
+ tmp = this.combine.elementAt(next).elementAt(t);
+ if ((tmp.root != root) || (tmp.index != index)) {
+ break;
+ }
+ t--;
+ }
+ if(t < 0) {
+ // try the bucket in node2combine before
+ if(next - 1 < 0) {
+ return false;
+ } else {
+ return innertrial(next - 1, ++layer);
+ }
+ } else if(tmp.root != root) {
+ if((tmp.root == this.lastchoices[next]) &&
+ (this.rootNStates.elementAt(this.lastchoices[next]).elementAt(0)[next] == 1)) {
+ // only 1 obj left in the chosen bucket
+ // can not move this one
+ // try the bucket in node2combine before
+ if(next - 1 < 0) {
+ return false;
+ } else {
+ return innertrial(next - 1, ++layer);
+ }
+ }
+ this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--;
+ //tmp.root = root;
+ int newroot = tmp.root + 1;
+ tmp.root = newroot;
+ tmp.index = 0;
+ this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++;
+ // make all left things in this color bucket reset
+ for(t++; t < this.combine.elementAt(next).size(); t++) {
+ tmp = this.combine.elementAt(next).elementAt(t);
+ this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--;
+ tmp.root = newroot;
+ tmp.index = 0;
+ this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++;
+ }
+ if(layer != 0) {
+ return firstexpand(next+1, this.first4choice);
+ }
+ return true;
+ } else if(tmp.index != index) {
+ if(this.rootNStates.elementAt(root).elementAt(tmp.index)[next] ==
+ this.rootNStates.elementAt(root).elementAt(index)[next]) {
+ // break the law of non-increase order inside one color bucket
+ // go on search forward
+ index = tmp.index;
+ } else if(this.rootNStates.elementAt(root).elementAt(tmp.index)[next] <
+ this.rootNStates.elementAt(root).elementAt(index)[next] + 2) {
+ // break the law of non-increase order inside one color bucket
+ // and now they only differ by 1
+ // propagate this difference to see if it can fix
+ boolean suc = propagateOne(next, root, index, t, tmp);
+ if(suc) {
+ return suc;
+ } else {
+ // go on search forward
+ index = tmp.index;
+ }
+ } else {
+ this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--;
+ int tmproot = tmp.root;
+ int tmpindex = tmp.index;
+ tmp.root = root;
+ tmp.index = index;
+ this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++;
+ int desroot = tmp.root;
+ int desindex = tmp.index;
+ // make all left things in this color bucket reset
+ t++;
+ boolean first = true;
+ while(t < this.combine.elementAt(next).size()) {
+ int k = 0;
+ if(first) {
+ k = 1;
+ first = false;
+ }
+ for(; (k < this.rootNStates.elementAt(tmproot).elementAt(tmpindex)[next]) && (t < this.combine.elementAt(next).size()); t++) {
+ tmp = this.combine.elementAt(next).elementAt(t);
+ this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--;
+ tmp.root = desroot;
+ tmp.index = desindex;
+ this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++;
+ }
+ if(k == this.rootNStates.elementAt(tmproot).elementAt(tmpindex)[next]) {
+ desindex++;
+ }
+ }
+ if(layer != 0) {
+ return firstexpand(next+1, this.first4choice);
+ }
+ return true;
+ }
+ }
+ }
} else {
- if((tmp.root != this.lastchoices[next]) ||
- (this.rootNStates.elementAt(this.lastchoices[next]).elementAt(0)[next] > 1)) {
- this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--;
- tmp.root = root;
- tmp.index = index;
- this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++;
- if(layer != 0) {
- return firstexpand(next+1, this.first4choice);
- }
- return true;
- } else {
- // only 1 obj with the color next exist on the chosen bucket this time,
- // can not move it, try objs in forward color bucket
- if(next - 1 < 0) {
- return false;
- } else {
- return innertrial(next - 1, ++layer);
- }
- }
+ if((tmp.root != this.lastchoices[next]) ||
+ (this.rootNStates.elementAt(this.lastchoices[next]).elementAt(0)[next] > 1)) {
+ this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--;
+ tmp.root = root;
+ tmp.index = index;
+ this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++;
+ if(layer != 0) {
+ return firstexpand(next+1, this.first4choice);
+ }
+ return true;
+ } else {
+ // only 1 obj with the color next exist on the chosen bucket this time,
+ // can not move it, try objs in forward color bucket
+ if(next - 1 < 0) {
+ return false;
+ } else {
+ return innertrial(next - 1, ++layer);
+ }
+ }
}
}
Combine tmpt = null;
if(this.rootNStates.elementAt(root).elementAt(index - 1)[next] <
this.rootNStates.elementAt(root).elementAt(index)[next]) {
- // need to continue propagate
- while(t < this.combine.elementAt(next).size()) {
- tmpt = this.combine.elementAt(next).elementAt(t);
- if ((tmpt.root != root) || (tmpt.index != index)) {
- break;
- }
- t++;
- }
- if(t == this.combine.elementAt(next).size()) {
- // last element of this color bucket
- if(index + 1 < this.rootNodes.elementAt(root).size()) {
- // there is available place inside the same color bucket
- Combine tmpbk = this.combine.elementAt(next).elementAt(t - 1);
- boolean suc = propagateOne(next, root, index + 1, t - 1, tmpbk);
- /*if(!suc) {
- // fail, roll back
- this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--;
- tmp.root = rootbk;
- tmp.index = indexbk;
- this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++;
- }*/
- return suc;
- } else if(root+1 < this.rootNodes.size()) { // check if there are another bucket
- // yes
- this.rootNStates.elementAt(tmpt.root).elementAt(tmpt.index)[next]--;
- tmpt.root = root + 1;
- tmpt.index = 0;
- this.rootNStates.elementAt(tmpt.root).elementAt(tmpt.index)[next]++;
- return firstexpand(next+1, this.first4choice);
- } else {
- // no, roll back
- this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--;
- tmp.root = rootbk;
- tmp.index = indexbk;
- this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++;
- return false;
- }
- } else if(tmpt.root != root) {
- Combine tmpbk = this.combine.elementAt(next).elementAt(t - 1);
- this.rootNStates.elementAt(tmpbk.root).elementAt(tmpbk.index)[next]--;
- tmpbk.root = tmpt.root;
- tmpbk.index = 0;
- this.rootNStates.elementAt(tmpbk.root).elementAt(tmpbk.index)[next]++;
- root = tmpt.root;
- index = tmpt.index;
- // make all left things in this color bucket reset
- for(t += 1; t < this.combine.elementAt(next).size(); t++) {
- tmpt = this.combine.elementAt(next).elementAt(t);
- this.rootNStates.elementAt(tmpt.root).elementAt(tmpt.index)[next]--;
- tmpt.root = root;
- tmpt.index = 0;
- this.rootNStates.elementAt(tmpt.root).elementAt(tmpt.index)[next]++;
- }
- return firstexpand(next+1, this.first4choice);
- } else if(tmpt.index != index) {
- Combine tmpbk = this.combine.elementAt(next).elementAt(t - 1);
- boolean suc = propagateOne(next, root, tmpt.index, t - 1, tmpbk);
- if(!suc) {
- // fail, roll back
- this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--;
- tmp.root = rootbk;
- tmp.index = indexbk;
- this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++;
- }
- return suc;
- }
- // won't reach here, only to avoid compiler's complain
- return true;
+ // need to continue propagate
+ while(t < this.combine.elementAt(next).size()) {
+ tmpt = this.combine.elementAt(next).elementAt(t);
+ if ((tmpt.root != root) || (tmpt.index != index)) {
+ break;
+ }
+ t++;
+ }
+ if(t == this.combine.elementAt(next).size()) {
+ // last element of this color bucket
+ if(index + 1 < this.rootNodes.elementAt(root).size()) {
+ // there is available place inside the same color bucket
+ Combine tmpbk = this.combine.elementAt(next).elementAt(t - 1);
+ boolean suc = propagateOne(next, root, index + 1, t - 1, tmpbk);
+ /*if(!suc) {
+ // fail, roll back
+ this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--;
+ tmp.root = rootbk;
+ tmp.index = indexbk;
+ this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++;
+ }*/
+ return suc;
+ } else if(root+1 < this.rootNodes.size()) { // check if there are another bucket
+ // yes
+ this.rootNStates.elementAt(tmpt.root).elementAt(tmpt.index)[next]--;
+ tmpt.root = root + 1;
+ tmpt.index = 0;
+ this.rootNStates.elementAt(tmpt.root).elementAt(tmpt.index)[next]++;
+ return firstexpand(next+1, this.first4choice);
+ } else {
+ // no, roll back
+ this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--;
+ tmp.root = rootbk;
+ tmp.index = indexbk;
+ this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++;
+ return false;
+ }
+ } else if(tmpt.root != root) {
+ Combine tmpbk = this.combine.elementAt(next).elementAt(t - 1);
+ this.rootNStates.elementAt(tmpbk.root).elementAt(tmpbk.index)[next]--;
+ tmpbk.root = tmpt.root;
+ tmpbk.index = 0;
+ this.rootNStates.elementAt(tmpbk.root).elementAt(tmpbk.index)[next]++;
+ root = tmpt.root;
+ index = tmpt.index;
+ // make all left things in this color bucket reset
+ for(t += 1; t < this.combine.elementAt(next).size(); t++) {
+ tmpt = this.combine.elementAt(next).elementAt(t);
+ this.rootNStates.elementAt(tmpt.root).elementAt(tmpt.index)[next]--;
+ tmpt.root = root;
+ tmpt.index = 0;
+ this.rootNStates.elementAt(tmpt.root).elementAt(tmpt.index)[next]++;
+ }
+ return firstexpand(next+1, this.first4choice);
+ } else if(tmpt.index != index) {
+ Combine tmpbk = this.combine.elementAt(next).elementAt(t - 1);
+ boolean suc = propagateOne(next, root, tmpt.index, t - 1, tmpbk);
+ if(!suc) {
+ // fail, roll back
+ this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]--;
+ tmp.root = rootbk;
+ tmp.index = indexbk;
+ this.rootNStates.elementAt(tmp.root).elementAt(tmp.index)[next]++;
+ }
+ return suc;
+ }
+ // won't reach here, only to avoid compiler's complain
+ return true;
} else {
- return true;
+ return true;
}
}
}
this.mapping = new Vector<Vector<ScheduleNode>>();
for(int i = 0; i < this.rootNum; i++) {
- this.mapping.add(null);
+ this.mapping.add(null);
}
this.rand = new Random();
}
this.mapping = null;
this.mapping = new Vector<Vector<ScheduleNode>>();
for(int i = 0; i < this.rootNum; i++) {
- this.mapping.add(null);
+ this.mapping.add(null);
}
// randomly choose a core for each node in sNodeVecs
for(int i = 0; i < this.sNodeVecs.size(); i++) {
- Vector<ScheduleNode> sNodes = this.sNodeVecs.elementAt(i);
- for(int j = 0; j < sNodes.size(); j++) {
- ScheduleNode snode = sNodes.elementAt(j);
- int core = Math.abs(rand.nextInt()) % this.rootNum;
- if(this.mapping.elementAt(core) == null) {
- this.mapping.setElementAt(new Vector<ScheduleNode>(), core);
- }
- this.mapping.elementAt(core).add(snode);
- }
+ Vector<ScheduleNode> sNodes = this.sNodeVecs.elementAt(i);
+ for(int j = 0; j < sNodes.size(); j++) {
+ ScheduleNode snode = sNodes.elementAt(j);
+ int core = Math.abs(rand.nextInt()) % this.rootNum;
+ if(this.mapping.elementAt(core) == null) {
+ this.mapping.setElementAt(new Vector<ScheduleNode>(), core);
+ }
+ this.mapping.elementAt(core).add(snode);
+ }
}
return true;
}
if(this.rtask.currentRun.getExetype() == 0) {
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;
- //}
- allycores = null;
- }
- // check if need to transfer to other cores
- Queue<Integer> targetcores = this.getTargetCores(obj.getCurrentFS());
- if(targetcores != null) {
- if(transObjs == null) {
- transObjs = new Vector<ObjectSimulator>();
- }
- if(!transObjs.contains(obj)) {
- transObjs.add(obj);
- }
- remove = true;
- }
- for(int j = 0; j < this.tasks.size(); j++) {
- this.tasks.elementAt(j).refreshPara(obj, remove);
- }
+ ObjectSimulator obj = paraQueues.elementAt(i).poll();
+ obj.setHold(false);
+ boolean remove = false;
+ if((this.targetFState != null)
+ && (this.targetFState.containsKey(obj.getCurrentFS()))) {
+ if(transObjs == null) {
+ transObjs = new Vector<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;
+ //}
+ allycores = null;
+ }
+ // check if need to transfer to other cores
+ Queue<Integer> targetcores = this.getTargetCores(obj.getCurrentFS());
+ if(targetcores != null) {
+ if(transObjs == null) {
+ transObjs = new Vector<ObjectSimulator>();
+ }
+ if(!transObjs.contains(obj)) {
+ transObjs.add(obj);
+ }
+ remove = true;
+ }
+ for(int j = 0; j < this.tasks.size(); j++) {
+ this.tasks.elementAt(j).refreshPara(obj, remove);
+ }
}
paraQueues = null;
}
int paraNum = next.getTd().numParameters();
Vector<Queue<ObjectSimulator>> pqueues = next.getParaQueues();
if((pqueues == null) || (pqueues.size() < paraNum)) {
- continue;
+ continue;
}
int j = 0;
for(; j < pqueues.size(); j++) {
- Queue<ObjectSimulator> objs = pqueues.elementAt(j);
- if((objs == null) || (objs.size() == 0)) {
- break;
- }
+ Queue<ObjectSimulator> objs = pqueues.elementAt(j);
+ if((objs == null) || (objs.size() == 0)) {
+ break;
+ }
}
if(j == pqueues.size()) {
- pqueues = null;
- return next;
+ pqueues = null;
+ return next;
}
pqueues = null;
}
PrintStream stdout = null;
try {
if(!state.BAMBOOCOMPILETIME) {
- stdout = new PrintStream(
- new FileOutputStream(this.state.outputdir + "SimulatorResult_"
- + this.coreNum + ".out"));
+ stdout = new PrintStream(
+ new FileOutputStream(this.state.outputdir + "SimulatorResult_"
+ + this.coreNum + ".out"));
}
} catch (Exception e) {
// Sigh. Couldn't open the file.
while(it_tasks.hasNext()) {
TaskDescriptor td = (TaskDescriptor)it_tasks.next();
if(td.numParameters() > 1) {
- multiparamtds.addElement(td);
+ multiparamtds.addElement(td);
}
}
it_tasks = null;
// simulate the generated schedulings and try to optimize it
do {
if(!state.BAMBOOCOMPILETIME) {
- System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n");
- System.out.print("Simulate and optimize round: #" + tryindex + ": \n");
+ System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n");
+ System.out.print("Simulate and optimize round: #" + tryindex + ": \n");
}
gid += newscheduleGraphs.size();
if(scheduleGraphs != null) {
- for(int i = 0; i < scheduleGraphs.size(); i++) {
- Vector<ScheduleNode> tmpgraph = scheduleGraphs.elementAt(i);
- for(int j = 0; j < tmpgraph.size(); j++) {
- ScheduleNode snode = tmpgraph.elementAt(j);
- snode.getEdgeVector().clear();
- snode.getInedgeVector().clear();
- snode.getScheduleEdges().clear();
- snode.getClassNodes().clear();
- }
- tmpgraph.clear();
- tmpgraph = null;
- }
- scheduleGraphs.clear();
+ for(int i = 0; i < scheduleGraphs.size(); i++) {
+ Vector<ScheduleNode> tmpgraph = scheduleGraphs.elementAt(i);
+ for(int j = 0; j < tmpgraph.size(); j++) {
+ ScheduleNode snode = tmpgraph.elementAt(j);
+ snode.getEdgeVector().clear();
+ snode.getInedgeVector().clear();
+ snode.getScheduleEdges().clear();
+ snode.getClassNodes().clear();
+ }
+ tmpgraph.clear();
+ tmpgraph = null;
+ }
+ scheduleGraphs.clear();
}
scheduleGraphs = newscheduleGraphs;
schedulings.clear();
// get scheduling layouts from schedule graphs
for(int i = 0; i < scheduleGraphs.size(); i++) {
- Vector<ScheduleNode> scheduleGraph = scheduleGraphs.elementAt(i);
- Vector<Schedule> tmpscheduling =
- generateScheduling(scheduleGraph, td2maincd);
- schedulings.add(tmpscheduling);
- scheduleGraph = null;
- tmpscheduling = null;
+ Vector<ScheduleNode> scheduleGraph = scheduleGraphs.elementAt(i);
+ Vector<Schedule> tmpscheduling =
+ generateScheduling(scheduleGraph, td2maincd);
+ schedulings.add(tmpscheduling);
+ scheduleGraph = null;
+ tmpscheduling = null;
}
selectedSchedulings.clear();
selectedSimExeGraphs.clear();
selectedSimExeGraphs);
boolean remove = false;
if(tmpexetime < bestexetime) {
- remove = true;
- bestexetime = tmpexetime;
- if(scheduling != null) {
- scheduling.clear();
- for(int j = 0; j < schedulinggraph.size(); j++) {
- ScheduleNode snode = schedulinggraph.elementAt(j);
- snode.getEdgeVector().clear();
- snode.getInedgeVector().clear();
- snode.getScheduleEdges().clear();
- snode.getClassNodes().clear();
- }
- schedulinggraph.clear();
- selectedSimExeGraph_bk = null;
- }
- scheduling = schedulings.elementAt(selectedSchedulings.elementAt(0));
- schedulinggraph = scheduleGraphs.elementAt(
- selectedSchedulings.elementAt(0));
- selectedSimExeGraph_bk = selectedSimExeGraphs.elementAt(0);
-
- if(!state.BAMBOOCOMPILETIME) {
- System.out.print("end of: #" + tryindex + " (bestexetime: "
- + bestexetime + ")\n");
- System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n");
- }
- tryindex++;
- threshold = this.scheduleThreshold;
+ remove = true;
+ bestexetime = tmpexetime;
+ if(scheduling != null) {
+ scheduling.clear();
+ for(int j = 0; j < schedulinggraph.size(); j++) {
+ ScheduleNode snode = schedulinggraph.elementAt(j);
+ snode.getEdgeVector().clear();
+ snode.getInedgeVector().clear();
+ snode.getScheduleEdges().clear();
+ snode.getClassNodes().clear();
+ }
+ schedulinggraph.clear();
+ selectedSimExeGraph_bk = null;
+ }
+ scheduling = schedulings.elementAt(selectedSchedulings.elementAt(0));
+ schedulinggraph = scheduleGraphs.elementAt(
+ selectedSchedulings.elementAt(0));
+ selectedSimExeGraph_bk = selectedSimExeGraphs.elementAt(0);
+
+ if(!state.BAMBOOCOMPILETIME) {
+ System.out.print("end of: #" + tryindex + " (bestexetime: "
+ + bestexetime + ")\n");
+ System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n");
+ }
+ tryindex++;
+ threshold = this.scheduleThreshold;
} else if(tmpexetime == bestexetime) {
- if(!state.BAMBOOCOMPILETIME) {
- System.out.print("end of: #" + tryindex + " (bestexetime: "
- + bestexetime + ")\n");
- System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n");
- }
- tryindex++;
- threshold += 10;
- if((threshold > 40) ||
- ((Math.abs(rand.nextInt()) % 100) < this.probThreshold + 10)) {
- break;
- }
+ if(!state.BAMBOOCOMPILETIME) {
+ System.out.print("end of: #" + tryindex + " (bestexetime: "
+ + bestexetime + ")\n");
+ System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n");
+ }
+ tryindex++;
+ threshold += 10;
+ if((threshold > 40) ||
+ ((Math.abs(rand.nextInt()) % 100) < this.probThreshold + 10)) {
+ break;
+ }
} else {
- if(!state.BAMBOOCOMPILETIME) {
- System.out.print("end of: #" + tryindex + " (bestexetime: "
- + bestexetime + ")\n");
- System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n");
- }
- tryindex++;
- if(threshold == this.scheduleThreshold) {
- if(scheduleGraphs != null) {
- scheduleGraphs.clear();
- }
- scheduleGraphs.addElement(schedulinggraph);
- if(selectedSchedulings != null) {
- selectedSchedulings.clear();
- }
- selectedSchedulings.addElement(Integer.valueOf(0));
- if(selectedSimExeGraphs != null) {
- selectedSimExeGraphs.clear();
- }
- selectedSimExeGraphs.addElement(selectedSimExeGraph_bk);
- }
- threshold += 10;
- if( (threshold > 40) ||
- ((Math.abs(rand.nextInt()) % 100) < this.probThreshold + 1)) {
- break;
- }
- break;
+ if(!state.BAMBOOCOMPILETIME) {
+ System.out.print("end of: #" + tryindex + " (bestexetime: "
+ + bestexetime + ")\n");
+ System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n");
+ }
+ tryindex++;
+ if(threshold == this.scheduleThreshold) {
+ if(scheduleGraphs != null) {
+ scheduleGraphs.clear();
+ }
+ scheduleGraphs.addElement(schedulinggraph);
+ if(selectedSchedulings != null) {
+ selectedSchedulings.clear();
+ }
+ selectedSchedulings.addElement(Integer.valueOf(0));
+ if(selectedSimExeGraphs != null) {
+ selectedSimExeGraphs.clear();
+ }
+ selectedSimExeGraphs.addElement(selectedSimExeGraph_bk);
+ }
+ threshold += 10;
+ if( (threshold > 40) ||
+ ((Math.abs(rand.nextInt()) % 100) < this.probThreshold + 1)) {
+ break;
+ }
+ break;
}
if(tooptimize) {
- // try to optimize the best one scheduling
- //do {
- newscheduleGraphs = optimizeScheduling(scheduleGraphs,
- selectedSchedulings,
- selectedSimExeGraphs,
- gid,
- threshold);
- /*if(newscheduleGraphs != null) {
- if(this.generateThreshold < 30) {
- this.generateThreshold = 30;
- }
- break;
- } else {
- threshold += 10;
- if(this.generateThreshold > 0) {
- this.generateThreshold -= 3;
- }
- if((Math.abs(rand.nextInt()) % 10000) < this.probThreshold + 1) {
- break;
- }
- }
- }while(true);*/
- if(remove) {
- scheduleGraphs.removeElementAt(selectedSchedulings.elementAt(0));
- selectedSimExeGraphs.removeElementAt(0);
- }
+ // try to optimize the best one scheduling
+ //do {
+ newscheduleGraphs = optimizeScheduling(scheduleGraphs,
+ selectedSchedulings,
+ selectedSimExeGraphs,
+ gid,
+ threshold);
+ /*if(newscheduleGraphs != null) {
+ if(this.generateThreshold < 30) {
+ this.generateThreshold = 30;
+ }
+ break;
+ } else {
+ threshold += 10;
+ if(this.generateThreshold > 0) {
+ this.generateThreshold -= 3;
+ }
+ if((Math.abs(rand.nextInt()) % 10000) < this.probThreshold + 1) {
+ break;
+ }
+ }
+ }while(true);*/
+ if(remove) {
+ scheduleGraphs.removeElementAt(selectedSchedulings.elementAt(0));
+ selectedSimExeGraphs.removeElementAt(0);
+ }
} else {
- break;
+ break;
}
} while(newscheduleGraphs != null); // TODO: could it possibly lead to endless loop?
// Close the streams.
try {
if(!state.BAMBOOCOMPILETIME) {
- stdout.close();
- stdout = null;
- System.setOut(origOut);
+ stdout.close();
+ stdout = null;
+ System.setOut(origOut);
}
} catch (Exception e) {
origOut.println("Redirect: Unable to close files!");
Iterator it_tasks =
this.state.getTaskSymbolTable().getDescriptorsIterator();
while(it_tasks.hasNext()) {
- TaskDescriptor td = (TaskDescriptor)it_tasks.next();
- if(td.numParameters() > 1) {
- multiparamtds.addElement(td);
- }
+ TaskDescriptor td = (TaskDescriptor)it_tasks.next();
+ if(td.numParameters() > 1) {
+ multiparamtds.addElement(td);
+ }
}
it_tasks = null;
+".out");
FileOutputStream dotstream = null;
try {
- dotstream = new FileOutputStream(file,false);
+ dotstream = new FileOutputStream(file,false);
} catch (Exception e) {
- e.printStackTrace();
- System.exit(-1);
+ e.printStackTrace();
+ System.exit(-1);
}
PrintWriter output = new java.io.PrintWriter(dotstream, true);
output.println("start time(1,000,000 cycles): "
+ totestscheduleGraphs.size());
for(int ii = 0; ii < totestscheduleGraphs.size(); ii++) {
- Vector<Vector<ScheduleNode>> newscheduleGraphs =
- new Vector<Vector<ScheduleNode>>();
- newscheduleGraphs.add(totestscheduleGraphs.elementAt(ii));
- // simulate the generated schedulings and try to optimize it
- schedulings.clear();
- // get scheduling layouts from schedule graphs
- for(int i = 0; i < newscheduleGraphs.size(); i++) {
- Vector<ScheduleNode> scheduleGraph = newscheduleGraphs.elementAt(i);
- Vector<Schedule> tmpscheduling =
- generateScheduling(scheduleGraph, td2maincd);
- schedulings.add(tmpscheduling);
- scheduleGraph = null;
- tmpscheduling = null;
- }
- selectedSchedulings.clear();
- selectedSimExeGraphs.clear();
- long tmpexetime = this.scheduleSimulator.simulate(schedulings,
- selectedSchedulings,
- selectedSimExeGraphs);
- output.println(((float)tmpexetime/100000000));
+ Vector<Vector<ScheduleNode>> newscheduleGraphs =
+ new Vector<Vector<ScheduleNode>>();
+ newscheduleGraphs.add(totestscheduleGraphs.elementAt(ii));
+ // simulate the generated schedulings and try to optimize it
+ schedulings.clear();
+ // get scheduling layouts from schedule graphs
+ for(int i = 0; i < newscheduleGraphs.size(); i++) {
+ Vector<ScheduleNode> scheduleGraph = newscheduleGraphs.elementAt(i);
+ Vector<Schedule> tmpscheduling =
+ generateScheduling(scheduleGraph, td2maincd);
+ schedulings.add(tmpscheduling);
+ scheduleGraph = null;
+ tmpscheduling = null;
+ }
+ selectedSchedulings.clear();
+ selectedSimExeGraphs.clear();
+ long tmpexetime = this.scheduleSimulator.simulate(schedulings,
+ selectedSchedulings,
+ selectedSimExeGraphs);
+ output.println(((float)tmpexetime/100000000));
}
} else {
Iterator it_tasks =
this.state.getTaskSymbolTable().getDescriptorsIterator();
while(it_tasks.hasNext()) {
- TaskDescriptor td = (TaskDescriptor)it_tasks.next();
- if(td.numParameters() > 1) {
- multiparamtds.addElement(td);
- }
+ TaskDescriptor td = (TaskDescriptor)it_tasks.next();
+ if(td.numParameters() > 1) {
+ multiparamtds.addElement(td);
+ }
}
it_tasks = null;
+ this.coreNum + ".out");
FileOutputStream dotstream2 = null;
try {
- dotstream = new FileOutputStream(file,false);
- dotstream2 = new FileOutputStream(file2,false);
+ dotstream = new FileOutputStream(file,false);
+ dotstream2 = new FileOutputStream(file2,false);
} catch (Exception e) {
- e.printStackTrace();
- System.exit(-1);
+ e.printStackTrace();
+ System.exit(-1);
}
PrintWriter output = new java.io.PrintWriter(dotstream, true);
PrintWriter output2 = new java.io.PrintWriter(dotstream2, true);
output2.println("optimized time(100,000,000 cycles): "
+ totestscheduleGraphs.size());
for(int ii = startnum; ii < totestscheduleGraphs.size(); ii++) {
- Vector<Vector<ScheduleNode>> newscheduleGraphs =
- new Vector<Vector<ScheduleNode>>();
- newscheduleGraphs.add(totestscheduleGraphs.elementAt(ii));
- int tryindex = 1;
- long bestexetime = Long.MAX_VALUE;
- int gid = 1;
- Vector<Schedule> scheduling = null;
- Vector<ScheduleNode> schedulinggraph = null;
- boolean isfirst = true;
- Random rand = new Random();
- int threshold = this.scheduleThreshold;
- // simulate the generated schedulings and try to optimize it
- System.out.print("=========================================================\n");
- System.out.print("# " + ii + ": \n");
- do {
- System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n");
- System.out.print("Simulate and optimize round: #" + tryindex + ": \n");
- gid += newscheduleGraphs.size();
- if(scheduleGraphs != null) {
- for(int i = 0; i < scheduleGraphs.size(); i++) {
- Vector<ScheduleNode> tmpgraph = scheduleGraphs.elementAt(i);
- for(int j = 0; j < tmpgraph.size(); j++) {
- ScheduleNode snode = tmpgraph.elementAt(j);
- snode.getEdgeVector().clear();
- snode.getInedgeVector().clear();
- snode.getScheduleEdges().clear();
- snode.getClassNodes().clear();
- }
- tmpgraph.clear();
- tmpgraph = null;
- }
- scheduleGraphs.clear();
- }
- scheduleGraphs = newscheduleGraphs;
- schedulings.clear();
- // get scheduling layouts from schedule graphs
- for(int i = 0; i < scheduleGraphs.size(); i++) {
- Vector<ScheduleNode> scheduleGraph = scheduleGraphs.elementAt(i);
- Vector<Schedule> tmpscheduling =
- generateScheduling(scheduleGraph, td2maincd);
- schedulings.add(tmpscheduling);
- scheduleGraph = null;
- tmpscheduling = null;
- }
- selectedSchedulings.clear();
- selectedSimExeGraphs.clear();
- long tmpexetime = this.scheduleSimulator.simulate(schedulings,
- selectedSchedulings,
- selectedSimExeGraphs);
- if(isfirst) {
- output.println(((float)tmpexetime/100000000));
- isfirst = false;
- }
- if(tmpexetime < bestexetime) {
- bestexetime = tmpexetime;
- if(scheduling != null) {
- scheduling.clear();
- for(int j = 0; j < schedulinggraph.size(); j++) {
- ScheduleNode snode = schedulinggraph.elementAt(j);
- snode.getEdgeVector().clear();
- snode.getInedgeVector().clear();
- snode.getScheduleEdges().clear();
- snode.getClassNodes().clear();
- }
- schedulinggraph.clear();
- selectedSimExeGraph_bk = null;
- }
- scheduling = schedulings.elementAt(selectedSchedulings.elementAt(0));
- schedulinggraph = scheduleGraphs.elementAt(
- selectedSchedulings.elementAt(0));
- selectedSimExeGraph_bk = selectedSimExeGraphs.elementAt(0);
- tryindex++;
- threshold = this.scheduleThreshold;
- System.out.print("end of: #" + tryindex + " (bestexetime: "
- + bestexetime + ")\n");
- System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n");
- } else if(tmpexetime == bestexetime) {
- System.out.print("end of: #" + tryindex + " (bestexetime: "
- + bestexetime + ")\n");
- System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n");
- tryindex++;
- threshold = this.scheduleThreshold;
- if((Math.abs(rand.nextInt()) % 100) < this.probThreshold) {
- break;
- }
- } else {
- System.out.print("end of: #" + tryindex + " (bestexetime: "
- + bestexetime + ")\n");
- System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n");
- tryindex++;
- if(threshold == this.scheduleThreshold) {
- if(scheduleGraphs != null) {
- scheduleGraphs.clear();
- }
- scheduleGraphs.addElement(schedulinggraph);
- if(selectedSchedulings != null) {
- selectedSchedulings.clear();
- }
- selectedSchedulings.addElement(Integer.valueOf(0));
- if(selectedSimExeGraphs != null) {
- selectedSimExeGraphs.clear();
- }
- selectedSimExeGraphs.addElement(selectedSimExeGraph_bk);
- }
- threshold += 10;
- if((Math.abs(rand.nextInt()) % 100) < this.probThreshold + 1) {
- break;
- }
- //break;
- }
-
- if(tooptimize) {
- // try to optimize theschedulings best one scheduling
- newscheduleGraphs = optimizeScheduling(scheduleGraphs,
- selectedSchedulings,
- selectedSimExeGraphs,
- gid,
- this.scheduleThreshold);
- if(tmpexetime < bestexetime) {
- scheduleGraphs.remove(selectedSchedulings.elementAt(0));
- }
- } else {
- break;
- }
- } while(newscheduleGraphs != null); // TODO: could it possibly lead to endless loop?
-
- scheduleGraphs.clear();
- scheduleGraphs = null;
- scheduling = null;
- schedulinggraph = null;
- if(newscheduleGraphs != null) {
- newscheduleGraphs.clear();
- }
- newscheduleGraphs = null;
- totestscheduleGraphs.elementAt(ii).clear();
- for(int i = 0; i < schedulings.size(); i++) {
- schedulings.elementAt(i).clear();
- }
- schedulings.clear();
- selectedSchedulings.clear();
- selectedSimExeGraphs.clear();
-
- output2.println(((float)bestexetime/100000000));
- System.out.print("=========================================================\n");
+ Vector<Vector<ScheduleNode>> newscheduleGraphs =
+ new Vector<Vector<ScheduleNode>>();
+ newscheduleGraphs.add(totestscheduleGraphs.elementAt(ii));
+ int tryindex = 1;
+ long bestexetime = Long.MAX_VALUE;
+ int gid = 1;
+ Vector<Schedule> scheduling = null;
+ Vector<ScheduleNode> schedulinggraph = null;
+ boolean isfirst = true;
+ Random rand = new Random();
+ int threshold = this.scheduleThreshold;
+ // simulate the generated schedulings and try to optimize it
+ System.out.print("=========================================================\n");
+ System.out.print("# " + ii + ": \n");
+ do {
+ System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n");
+ System.out.print("Simulate and optimize round: #" + tryindex + ": \n");
+ gid += newscheduleGraphs.size();
+ if(scheduleGraphs != null) {
+ for(int i = 0; i < scheduleGraphs.size(); i++) {
+ Vector<ScheduleNode> tmpgraph = scheduleGraphs.elementAt(i);
+ for(int j = 0; j < tmpgraph.size(); j++) {
+ ScheduleNode snode = tmpgraph.elementAt(j);
+ snode.getEdgeVector().clear();
+ snode.getInedgeVector().clear();
+ snode.getScheduleEdges().clear();
+ snode.getClassNodes().clear();
+ }
+ tmpgraph.clear();
+ tmpgraph = null;
+ }
+ scheduleGraphs.clear();
+ }
+ scheduleGraphs = newscheduleGraphs;
+ schedulings.clear();
+ // get scheduling layouts from schedule graphs
+ for(int i = 0; i < scheduleGraphs.size(); i++) {
+ Vector<ScheduleNode> scheduleGraph = scheduleGraphs.elementAt(i);
+ Vector<Schedule> tmpscheduling =
+ generateScheduling(scheduleGraph, td2maincd);
+ schedulings.add(tmpscheduling);
+ scheduleGraph = null;
+ tmpscheduling = null;
+ }
+ selectedSchedulings.clear();
+ selectedSimExeGraphs.clear();
+ long tmpexetime = this.scheduleSimulator.simulate(schedulings,
+ selectedSchedulings,
+ selectedSimExeGraphs);
+ if(isfirst) {
+ output.println(((float)tmpexetime/100000000));
+ isfirst = false;
+ }
+ if(tmpexetime < bestexetime) {
+ bestexetime = tmpexetime;
+ if(scheduling != null) {
+ scheduling.clear();
+ for(int j = 0; j < schedulinggraph.size(); j++) {
+ ScheduleNode snode = schedulinggraph.elementAt(j);
+ snode.getEdgeVector().clear();
+ snode.getInedgeVector().clear();
+ snode.getScheduleEdges().clear();
+ snode.getClassNodes().clear();
+ }
+ schedulinggraph.clear();
+ selectedSimExeGraph_bk = null;
+ }
+ scheduling = schedulings.elementAt(selectedSchedulings.elementAt(0));
+ schedulinggraph = scheduleGraphs.elementAt(
+ selectedSchedulings.elementAt(0));
+ selectedSimExeGraph_bk = selectedSimExeGraphs.elementAt(0);
+ tryindex++;
+ threshold = this.scheduleThreshold;
+ System.out.print("end of: #" + tryindex + " (bestexetime: "
+ + bestexetime + ")\n");
+ System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n");
+ } else if(tmpexetime == bestexetime) {
+ System.out.print("end of: #" + tryindex + " (bestexetime: "
+ + bestexetime + ")\n");
+ System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n");
+ tryindex++;
+ threshold = this.scheduleThreshold;
+ if((Math.abs(rand.nextInt()) % 100) < this.probThreshold) {
+ break;
+ }
+ } else {
+ System.out.print("end of: #" + tryindex + " (bestexetime: "
+ + bestexetime + ")\n");
+ System.out.print("+++++++++++++++++++++++++++++++++++++++++++++++++++\n");
+ tryindex++;
+ if(threshold == this.scheduleThreshold) {
+ if(scheduleGraphs != null) {
+ scheduleGraphs.clear();
+ }
+ scheduleGraphs.addElement(schedulinggraph);
+ if(selectedSchedulings != null) {
+ selectedSchedulings.clear();
+ }
+ selectedSchedulings.addElement(Integer.valueOf(0));
+ if(selectedSimExeGraphs != null) {
+ selectedSimExeGraphs.clear();
+ }
+ selectedSimExeGraphs.addElement(selectedSimExeGraph_bk);
+ }
+ threshold += 10;
+ if((Math.abs(rand.nextInt()) % 100) < this.probThreshold + 1) {
+ break;
+ }
+ //break;
+ }
+
+ if(tooptimize) {
+ // try to optimize theschedulings best one scheduling
+ newscheduleGraphs = optimizeScheduling(scheduleGraphs,
+ selectedSchedulings,
+ selectedSimExeGraphs,
+ gid,
+ this.scheduleThreshold);
+ if(tmpexetime < bestexetime) {
+ scheduleGraphs.remove(selectedSchedulings.elementAt(0));
+ }
+ } else {
+ break;
+ }
+ } while(newscheduleGraphs != null); // TODO: could it possibly lead to endless loop?
+
+ scheduleGraphs.clear();
+ scheduleGraphs = null;
+ scheduling = null;
+ schedulinggraph = null;
+ if(newscheduleGraphs != null) {
+ newscheduleGraphs.clear();
+ }
+ newscheduleGraphs = null;
+ totestscheduleGraphs.elementAt(ii).clear();
+ for(int i = 0; i < schedulings.size(); i++) {
+ schedulings.elementAt(i).clear();
+ }
+ schedulings.clear();
+ selectedSchedulings.clear();
+ selectedSimExeGraphs.clear();
+
+ output2.println(((float)bestexetime/100000000));
+ System.out.print("=========================================================\n");
}
if(scheduleGraphs != null) {
- scheduleGraphs.clear();
+ scheduleGraphs.clear();
}
scheduleGraphs = null;
totestscheduleGraphs = null;
for(int i = 0; i < schedulings.size(); i++) {
- schedulings.elementAt(i).clear();
+ schedulings.elementAt(i).clear();
}
schedulings.clear();
schedulings = null;
// Close the streams.
try {
- output.close();
- stdout.close();
- output = null;
- stdout = null;
- System.setOut(origOut);
+ output.close();
+ stdout.close();
+ output = null;
+ stdout = null;
+ System.setOut(origOut);
} catch (Exception e) {
- origOut.println("Redirect: Unable to close files!");
+ origOut.println("Redirect: Unable to close files!");
}
}
Vector<SimExecutionEdge> criticalPath = analyzeCriticalPath(startnode);
// for Test
if(this.state.PRINTCRITICALPATH) {
- System.err.println("gid: " + lgid + " endpoint: " + startnode.getTimepoint());
+ System.err.println("gid: " + lgid + " endpoint: " + startnode.getTimepoint());
}
Vector<Vector<ScheduleNode>> tmposchedulegraphs =
optimizeCriticalPath(schedulegraph,
lgid,
left);
if(tmposchedulegraphs != null) {
- if(optimizeschedulegraphs == null) {
- optimizeschedulegraphs = new Vector<Vector<ScheduleNode>>();
- }
- optimizeschedulegraphs.addAll(tmposchedulegraphs);
- lgid += tmposchedulegraphs.size();
- left -= tmposchedulegraphs.size();
- if(left == 0) {
- schedulegraph = null;
- criticalPath = null;
- tmposchedulegraphs = null;
- break;
- }
+ if(optimizeschedulegraphs == null) {
+ optimizeschedulegraphs = new Vector<Vector<ScheduleNode>>();
+ }
+ optimizeschedulegraphs.addAll(tmposchedulegraphs);
+ lgid += tmposchedulegraphs.size();
+ left -= tmposchedulegraphs.size();
+ if(left == 0) {
+ schedulegraph = null;
+ criticalPath = null;
+ tmposchedulegraphs = null;
+ break;
+ }
}
schedulegraph = null;
criticalPath = null;
Iterator<SimExecutionEdge> it_iedges =
(Iterator<SimExecutionEdge>)snode.inedges();
while(it_iedges.hasNext()) {
- SimExecutionEdge sedge = it_iedges.next();
- //if(sedge.getWeight() != 0) {
- SimExecutionNode tsnode = (SimExecutionNode)(sedge.getSource());
- if(tsnode.getTimepoint() + sedge.getWeight() == snode.getTimepoint()) {
- nsnode = tsnode;
- criticalPath.insertElementAt(sedge, 0);
- sum += sedge.getWeight();
- break;
- }
- //}
+ SimExecutionEdge sedge = it_iedges.next();
+ //if(sedge.getWeight() != 0) {
+ SimExecutionNode tsnode = (SimExecutionNode)(sedge.getSource());
+ if(tsnode.getTimepoint() + sedge.getWeight() == snode.getTimepoint()) {
+ nsnode = tsnode;
+ criticalPath.insertElementAt(sedge, 0);
+ sum += sedge.getWeight();
+ break;
+ }
+ //}
}
it_iedges = null;
snode = nsnode;
SimExecutionEdge seedge = criticalPath.elementAt(i);
Vector<SimExecutionEdge> predicates = seedge.getPredicates();
if(predicates != null) {
- // have predicates
- long starttime = 0;
- // check the latest finish time of all the predicates
- for(int j = 0; j < predicates.size(); j++) {
- SimExecutionEdge predicate = predicates.elementAt(j);
- long tmptime = predicate.getBestStartPoint() + predicate.getWeight();
- if(tmptime > starttime) {
- starttime = tmptime;
- seedge.setLastpredicateEdge(predicate);
- if(predicate.getTd() != null) {
- seedge.setLastpredicateNode(
- (SimExecutionNode)predicate.getTarget());
- } else {
- // transfer edge
- seedge.setLastpredicateNode(
- (SimExecutionNode)predicate.getSource());
- }
- }
- }
- seedge.setBestStartPoint(starttime);
+ // have predicates
+ long starttime = 0;
+ // check the latest finish time of all the predicates
+ for(int j = 0; j < predicates.size(); j++) {
+ SimExecutionEdge predicate = predicates.elementAt(j);
+ long tmptime = predicate.getBestStartPoint() + predicate.getWeight();
+ if(tmptime > starttime) {
+ starttime = tmptime;
+ seedge.setLastpredicateEdge(predicate);
+ if(predicate.getTd() != null) {
+ seedge.setLastpredicateNode(
+ (SimExecutionNode)predicate.getTarget());
+ } else {
+ // transfer edge
+ seedge.setLastpredicateNode(
+ (SimExecutionNode)predicate.getSource());
+ }
+ }
+ }
+ seedge.setBestStartPoint(starttime);
} else if(seedge.getSource().getInedgeVector().size() > 0) {
- // should have only one in edge
- long starttime = ((SimExecutionNode)seedge.getSource()).getTimepoint();
- seedge.setBestStartPoint(starttime);
+ // should have only one in edge
+ long starttime = ((SimExecutionNode)seedge.getSource()).getTimepoint();
+ seedge.setBestStartPoint(starttime);
} else {
- // no predicates
- seedge.setBestStartPoint(0);
+ // no predicates
+ seedge.setBestStartPoint(0);
}
predicates = null;
}
long starttime = seedge.getBestStartPoint();
if((starttime < ((SimExecutionNode)seedge.getSource()).getTimepoint())
&& (seedge.getTd() != null)) {
- // Note: must be a task related edge, can not be an object transfer edge
- // no restrictions due to data dependencies
- // have potential to be parallelled and start execution earlier
- seedge.setFixedTime(false);
- // consider to optimize it only when its predicates can NOT
- // be optimized, otherwise first considering optimize its predicates
- //SimExecutionEdge lastpredicateedge = seedge.getLastpredicateEdge();
- // TODO
- //if(lastpredicateedge.isFixedTime()) {
- int corenum = seedge.getCoreNum();
- if(!toselects.containsKey(starttime)) {
- toselects.put(starttime,
- new Hashtable<Integer, Vector<SimExecutionEdge>>());
- }
- if(!toselects.get(starttime).containsKey(corenum)) {
- toselects.get(starttime).put(corenum,
- new Vector<SimExecutionEdge>());
- }
- toselects.get(starttime).get(corenum).add(seedge);
- //}
+ // Note: must be a task related edge, can not be an object transfer edge
+ // no restrictions due to data dependencies
+ // have potential to be parallelled and start execution earlier
+ seedge.setFixedTime(false);
+ // consider to optimize it only when its predicates can NOT
+ // be optimized, otherwise first considering optimize its predicates
+ //SimExecutionEdge lastpredicateedge = seedge.getLastpredicateEdge();
+ // TODO
+ //if(lastpredicateedge.isFixedTime()) {
+ int corenum = seedge.getCoreNum();
+ if(!toselects.containsKey(starttime)) {
+ toselects.put(starttime,
+ new Hashtable<Integer, Vector<SimExecutionEdge>>());
+ }
+ if(!toselects.get(starttime).containsKey(corenum)) {
+ toselects.get(starttime).put(corenum,
+ new Vector<SimExecutionEdge>());
+ }
+ toselects.get(starttime).get(corenum).add(seedge);
+ //}
}
}
do {
int length = keys.size();
if(length == 0) {
- return optimizeschedulegraphs;
+ return optimizeschedulegraphs;
}
int tochoose = Math.abs(rand.nextInt()) % length;
opcheckpoint = (keys.elementAt(tochoose)).longValue();
SimExecutionEdge lastpredicateedge = seedge.getLastpredicateEdge();
long timepoint = lastpredicatenode.getTimepoint();
if(lastpredicateedge.getTd() == null) {
- // transfer edge
- timepoint += lastpredicateedge.getWeight();
+ // transfer edge
+ timepoint += lastpredicateedge.getWeight();
}
// mapping to critical path
for(int index = 0; index < criticalPath.size(); index++) {
- SimExecutionEdge tmpseedge = criticalPath.elementAt(index);
- SimExecutionNode tmpsenode =
- (SimExecutionNode)tmpseedge.getTarget();
- if(tmpsenode.getTimepoint() > timepoint) {
- // get the spare core info
- sparecores = tmpsenode.getSpareCores();
- break;
- }
+ SimExecutionEdge tmpseedge = criticalPath.elementAt(index);
+ SimExecutionNode tmpsenode =
+ (SimExecutionNode)tmpseedge.getTarget();
+ if(tmpsenode.getTimepoint() > timepoint) {
+ // get the spare core info
+ sparecores = tmpsenode.getSpareCores();
+ break;
+ }
}
if(tooptimize.size() > 0) {
- Iterator<Integer> it_cores = tooptimize.keySet().iterator();
- // check if it is possible to optimize these tasks
- if((sparecores == null) || (sparecores.size() == 0)) {
- // lack of spare cores
- while(it_cores.hasNext()) {
- int corenum = it_cores.next();
- Vector<SimExecutionEdge> tmptasks = tooptimize.get(corenum);
- // group the task instantiations according to whether it
- // has backward data dependences or not
- Vector<SimExecutionEdge> candidatetasks = new Vector();
- for(int ii= 0; ii < tmptasks.size(); ii++) {
- SimExecutionEdge tmpseedge = tmptasks.elementAt(ii);
- SimExecutionNode target = (SimExecutionNode)tmpseedge.getTarget();
- Vector<SimExecutionEdge> children =
- (Vector<SimExecutionEdge>)target.getEdgeVector();
- int jj = 0;
- for(; jj < children.size(); jj++) {
- SimExecutionEdge tmpedge = children.elementAt(jj);
- if(tmpedge.getTd() != null) {
- Vector<SimExecutionEdge> predicates =
- tmpedge.getPredicates();
- if((predicates != null) &&
- (predicates.contains(tmpseedge))) {
- break;
- }
- predicates = null;
- } else if(tmpedge.getWeight() != 0) {
- // transfer edge
- if(((SimExecutionNode)tmpedge.getTarget()).getTimepoint()
- == tmpedge.getWeight() + target.getTimepoint()) {
- break;
- }
- }
- }
- if(jj == children.size()) {
- candidatetasks.add(tmpseedge);
- }
- }
- if((candidatetasks.size() > 0) &&
- (candidatetasks.size() < tmptasks.size())) {
- // there are less important tasks which have no backward
- // data dependences at this timepoint, try to change
- // original execution order
- Hashtable<Integer, Vector<SimExecutionEdge>> tooptimize2 =
- new Hashtable<Integer, Vector<SimExecutionEdge>>();
- tooptimize2.put(corenum, candidatetasks);
- Vector<Vector<ScheduleNode>> ops =
- innerOptimizeCriticalPath(scheduleGraph,
- tooptimize2,
- null,
- lgid,
- left);
- if(ops != null) {
- if(optimizeschedulegraphs == null) {
- optimizeschedulegraphs = new Vector<Vector<ScheduleNode>>();
- }
- optimizeschedulegraphs.addAll(ops);
- lgid += ops.size();
- left -= ops.size();
- }
- tooptimize2 = null;
- ops = null;
- }
- tmptasks = null;
- candidatetasks = null;
- }
-
- if(left == 0) {
- it_cores = null;
- return optimizeschedulegraphs;
- }
-
- // flush the dependences and earliest start time
- if(!state.BAMBOOCOMPILETIME) {
- it_cores = tooptimize.keySet().iterator();
- while(it_cores.hasNext()) {
- int corenum = it_cores.next();
- Vector<SimExecutionEdge> edgevec =
- tooptimize.get(corenum);
- for(int j = 0; j < edgevec.size(); j++) {
- SimExecutionEdge edge = edgevec.elementAt(j);
- lastpredicateedge = edge.getLastpredicateEdge();
- lastpredicatenode = edge.getLastpredicateNode();
- // if(edge.getCoreNum() != lastpredicate.getCoreNum()) // should never hit this
- timepoint = lastpredicatenode.getTimepoint();
- if(lastpredicateedge.getTd() == null) {
- // transfer edge
- timepoint += lastpredicateedge.getWeight();
- }
- // mapping to critical path
- for(int index = 0; index < criticalPath.size(); index++) {
- SimExecutionEdge tmpseedge = criticalPath.elementAt(index);
- SimExecutionNode tmpsenode =
- (SimExecutionNode)tmpseedge.getTarget();
- if(tmpsenode.getTimepoint() > timepoint) {
- // update the predicate info
- if(edge.getPredicates() != null) {
- edge.getPredicates().remove(lastpredicateedge);
- }
- edge.addPredicate(criticalPath.elementAt(index));
- break;
- }
- }
- }
- edgevec = null;
- }
- it_cores = null;
- computeBestStartPoint(criticalPath);
- Vector<Vector<ScheduleNode>> ops = optimizeCriticalPath(scheduleGraph,
- criticalPath,
- lgid,
- left);
- if(ops != null) {
- if(optimizeschedulegraphs == null) {
- optimizeschedulegraphs = new Vector<Vector<ScheduleNode>>();
- }
- optimizeschedulegraphs.addAll(ops);
- lgid += ops.size();
- left -= ops.size();
- }
- ops = null;
- }
- } else {
- // there are spare cores, try to reorganize the tasks to the spare
- // cores
- Vector<Vector<ScheduleNode>> ops =
- innerOptimizeCriticalPath(scheduleGraph,
- tooptimize,
- sparecores,
- lgid,
- left);
- if(ops != null) {
- if(optimizeschedulegraphs == null) {
- optimizeschedulegraphs = new Vector<Vector<ScheduleNode>>();
- }
- optimizeschedulegraphs.addAll(ops);
- lgid += ops.size();
- left -= ops.size();
- }
- ops = null;
- }
+ Iterator<Integer> it_cores = tooptimize.keySet().iterator();
+ // check if it is possible to optimize these tasks
+ if((sparecores == null) || (sparecores.size() == 0)) {
+ // lack of spare cores
+ while(it_cores.hasNext()) {
+ int corenum = it_cores.next();
+ Vector<SimExecutionEdge> tmptasks = tooptimize.get(corenum);
+ // group the task instantiations according to whether it
+ // has backward data dependences or not
+ Vector<SimExecutionEdge> candidatetasks = new Vector();
+ for(int ii= 0; ii < tmptasks.size(); ii++) {
+ SimExecutionEdge tmpseedge = tmptasks.elementAt(ii);
+ SimExecutionNode target = (SimExecutionNode)tmpseedge.getTarget();
+ Vector<SimExecutionEdge> children =
+ (Vector<SimExecutionEdge>)target.getEdgeVector();
+ int jj = 0;
+ for(; jj < children.size(); jj++) {
+ SimExecutionEdge tmpedge = children.elementAt(jj);
+ if(tmpedge.getTd() != null) {
+ Vector<SimExecutionEdge> predicates =
+ tmpedge.getPredicates();
+ if((predicates != null) &&
+ (predicates.contains(tmpseedge))) {
+ break;
+ }
+ predicates = null;
+ } else if(tmpedge.getWeight() != 0) {
+ // transfer edge
+ if(((SimExecutionNode)tmpedge.getTarget()).getTimepoint()
+ == tmpedge.getWeight() + target.getTimepoint()) {
+ break;
+ }
+ }
+ }
+ if(jj == children.size()) {
+ candidatetasks.add(tmpseedge);
+ }
+ }
+ if((candidatetasks.size() > 0) &&
+ (candidatetasks.size() < tmptasks.size())) {
+ // there are less important tasks which have no backward
+ // data dependences at this timepoint, try to change
+ // original execution order
+ Hashtable<Integer, Vector<SimExecutionEdge>> tooptimize2 =
+ new Hashtable<Integer, Vector<SimExecutionEdge>>();
+ tooptimize2.put(corenum, candidatetasks);
+ Vector<Vector<ScheduleNode>> ops =
+ innerOptimizeCriticalPath(scheduleGraph,
+ tooptimize2,
+ null,
+ lgid,
+ left);
+ if(ops != null) {
+ if(optimizeschedulegraphs == null) {
+ optimizeschedulegraphs = new Vector<Vector<ScheduleNode>>();
+ }
+ optimizeschedulegraphs.addAll(ops);
+ lgid += ops.size();
+ left -= ops.size();
+ }
+ tooptimize2 = null;
+ ops = null;
+ }
+ tmptasks = null;
+ candidatetasks = null;
+ }
+
+ if(left == 0) {
+ it_cores = null;
+ return optimizeschedulegraphs;
+ }
+
+ // flush the dependences and earliest start time
+ if(!state.BAMBOOCOMPILETIME) {
+ it_cores = tooptimize.keySet().iterator();
+ while(it_cores.hasNext()) {
+ int corenum = it_cores.next();
+ Vector<SimExecutionEdge> edgevec =
+ tooptimize.get(corenum);
+ for(int j = 0; j < edgevec.size(); j++) {
+ SimExecutionEdge edge = edgevec.elementAt(j);
+ lastpredicateedge = edge.getLastpredicateEdge();
+ lastpredicatenode = edge.getLastpredicateNode();
+ // if(edge.getCoreNum() != lastpredicate.getCoreNum()) // should never hit this
+ timepoint = lastpredicatenode.getTimepoint();
+ if(lastpredicateedge.getTd() == null) {
+ // transfer edge
+ timepoint += lastpredicateedge.getWeight();
+ }
+ // mapping to critical path
+ for(int index = 0; index < criticalPath.size(); index++) {
+ SimExecutionEdge tmpseedge = criticalPath.elementAt(index);
+ SimExecutionNode tmpsenode =
+ (SimExecutionNode)tmpseedge.getTarget();
+ if(tmpsenode.getTimepoint() > timepoint) {
+ // update the predicate info
+ if(edge.getPredicates() != null) {
+ edge.getPredicates().remove(lastpredicateedge);
+ }
+ edge.addPredicate(criticalPath.elementAt(index));
+ break;
+ }
+ }
+ }
+ edgevec = null;
+ }
+ it_cores = null;
+ computeBestStartPoint(criticalPath);
+ Vector<Vector<ScheduleNode>> ops = optimizeCriticalPath(scheduleGraph,
+ criticalPath,
+ lgid,
+ left);
+ if(ops != null) {
+ if(optimizeschedulegraphs == null) {
+ optimizeschedulegraphs = new Vector<Vector<ScheduleNode>>();
+ }
+ optimizeschedulegraphs.addAll(ops);
+ lgid += ops.size();
+ left -= ops.size();
+ }
+ ops = null;
+ }
+ } else {
+ // there are spare cores, try to reorganize the tasks to the spare
+ // cores
+ Vector<Vector<ScheduleNode>> ops =
+ innerOptimizeCriticalPath(scheduleGraph,
+ tooptimize,
+ sparecores,
+ lgid,
+ left);
+ if(ops != null) {
+ if(optimizeschedulegraphs == null) {
+ optimizeschedulegraphs = new Vector<Vector<ScheduleNode>>();
+ }
+ optimizeschedulegraphs.addAll(ops);
+ lgid += ops.size();
+ left -= ops.size();
+ }
+ ops = null;
+ }
}
sparecores = null;
tooptimize.clear();
Vector<ScheduleNode> roots = new Vector<ScheduleNode>();
for(int i = 0; i < newscheduleGraph.size(); i++) {
if((sparecores == null) || (sparecores.contains(i))) {
- roots.add(newscheduleGraph.elementAt(i));
+ roots.add(newscheduleGraph.elementAt(i));
}
}
Vector<SimExecutionEdge> candidatetasks =
tooptimize.get(corenum);
for(int i = 0; i < candidatetasks.size(); i++) {
- TaskDescriptor td = candidatetasks.elementAt(i).getTd();
- // TODO: currently do not consider multi-param tasks
- if(td.numParameters() == 1) {
- ClassDescriptor cd = td.getParamType(0).getClassDesc();
- ScheduleNode snode = newscheduleGraph.elementAt(corenum); // corresponding ScheduleNode
- Iterator<ClassNode> it_cnodes = snode.getClassNodesIterator();
- ClassNode tosplit = null;
- while(it_cnodes.hasNext()) {
- ClassNode cnode = it_cnodes.next();
- if(cnode.getClassDescriptor().equals(cd)) {
- tosplit= cnode;
- break;
- }
- }
- it_cnodes = null;
-
- // split the node
- ScheduleNode splitnode = snode.spliteClassNode(tosplit);
- newscheduleGraph.add(splitnode);
- tocombines.add(splitnode);
- tosplit = null;
- }
+ TaskDescriptor td = candidatetasks.elementAt(i).getTd();
+ // TODO: currently do not consider multi-param tasks
+ if(td.numParameters() == 1) {
+ ClassDescriptor cd = td.getParamType(0).getClassDesc();
+ ScheduleNode snode = newscheduleGraph.elementAt(corenum); // corresponding ScheduleNode
+ Iterator<ClassNode> it_cnodes = snode.getClassNodesIterator();
+ ClassNode tosplit = null;
+ while(it_cnodes.hasNext()) {
+ ClassNode cnode = it_cnodes.next();
+ if(cnode.getClassDescriptor().equals(cd)) {
+ tosplit= cnode;
+ break;
+ }
+ }
+ it_cnodes = null;
+
+ // split the node
+ ScheduleNode splitnode = snode.spliteClassNode(tosplit);
+ newscheduleGraph.add(splitnode);
+ tocombines.add(splitnode);
+ tosplit = null;
+ }
}
candidatetasks = null;
}
while ((left > 0) && (cGen.nextGen())) {
//while ((left > 0) && (cGen.randomGenE())) {
if(Math.abs(rand.nextInt()) % 100 > this.generateThreshold) {
- Vector<Vector<CombinationUtil.Combine>> combine = cGen.getCombine();
- Vector<ScheduleNode> sNodes =
- SchedulingUtil.generateScheduleGraph(this.state,
- newscheduleGraph,
- scheduleEdges,
- rootNodes,
- combine,
- lgid++);
- if(optimizeschedulegraphs == null) {
- optimizeschedulegraphs = new Vector<Vector<ScheduleNode>>();
- }
- optimizeschedulegraphs.add(sNodes);
- combine = null;
- sNodes = null;
- left--;
+ Vector<Vector<CombinationUtil.Combine>> combine = cGen.getCombine();
+ Vector<ScheduleNode> sNodes =
+ SchedulingUtil.generateScheduleGraph(this.state,
+ newscheduleGraph,
+ scheduleEdges,
+ rootNodes,
+ combine,
+ lgid++);
+ if(optimizeschedulegraphs == null) {
+ optimizeschedulegraphs = new Vector<Vector<ScheduleNode>>();
+ }
+ optimizeschedulegraphs.add(sNodes);
+ combine = null;
+ sNodes = null;
+ left--;
}
}
cGen.clear();
for(int i = 0; i < rootNodes.size(); i++) {
if(rootNodes.elementAt(i) != null) {
- rootNodes.elementAt(i).clear();
+ rootNodes.elementAt(i).clear();
}
}
rootNodes = null;
for(int i = 0; i < nodes2combine.size(); i++) {
if(nodes2combine.elementAt(i) != null) {
- nodes2combine.elementAt(i).clear();
+ nodes2combine.elementAt(i).clear();
}
}
nodes2combine = null;
Vector<ClassNode> cNodes = sn.getClassNodes();
for(int k = 0; k < cNodes.size(); k++) {
- ClassNode cNode = cNodes.elementAt(k);
- ClassDescriptor cd = cNode.getClassDescriptor();
- Iterator it_flags = cNode.getFlags();
- while(it_flags.hasNext()) {
- FlagState fs = (FlagState)it_flags.next();
- Iterator it_edges = fs.edges();
- while(it_edges.hasNext()) {
- FEdge tmpfe = (FEdge)it_edges.next();
- TaskDescriptor td = (tmpfe).getTask();
- boolean contain = true;
- if(td.numParameters() > 1) {
- // td is a multi-param task, check if this core contains the
- // main cd of it
- ClassDescriptor cd1 = td2maincd.get(td);
- if(td2maincd.get(td).equals(cd)) {
- contain = true;
- td2maincore.put(td, tmpSchedule.getCoreNum());
- } else {
- contain = false;
- if(!td2allycores.containsKey(td)) {
- td2allycores.put(td, new Vector<Schedule>());
- }
- Vector<Schedule> allycores = td2allycores.get(td);
- if(!allycores.contains(tmpSchedule)) {
- allycores.addElement(tmpSchedule);
- }
- allycores = null;
- }
- // If the FlagState can be fed to some multi-param tasks,
- // need to record corresponding ally cores later.
- tmpSchedule.addFState4TD(td, fs);
- }
- if(contain) {
- tmpSchedule.addTask(td);
- if(!td2cores.containsKey(td)) {
- td2cores.put(td, new Vector<Schedule>());
- }
- Vector<Schedule> tmpcores = td2cores.get(td);
- if(!tmpcores.contains(tmpSchedule)) {
- tmpcores.add(tmpSchedule);
- }
- tmpcores = null;
- }
- if(td.getParamType(0).getClassDesc().getSymbol().equals(
- TypeUtil.StartupClass)) {
- assert(!setstartupcore);
- startupcore = j;
- startup = tmpSchedule;
- setstartupcore = true;
- }
- }
- it_edges = null;
- }
- it_flags = null;
+ ClassNode cNode = cNodes.elementAt(k);
+ ClassDescriptor cd = cNode.getClassDescriptor();
+ Iterator it_flags = cNode.getFlags();
+ while(it_flags.hasNext()) {
+ FlagState fs = (FlagState)it_flags.next();
+ Iterator it_edges = fs.edges();
+ while(it_edges.hasNext()) {
+ FEdge tmpfe = (FEdge)it_edges.next();
+ TaskDescriptor td = (tmpfe).getTask();
+ boolean contain = true;
+ if(td.numParameters() > 1) {
+ // td is a multi-param task, check if this core contains the
+ // main cd of it
+ ClassDescriptor cd1 = td2maincd.get(td);
+ if(td2maincd.get(td).equals(cd)) {
+ contain = true;
+ td2maincore.put(td, tmpSchedule.getCoreNum());
+ } else {
+ contain = false;
+ if(!td2allycores.containsKey(td)) {
+ td2allycores.put(td, new Vector<Schedule>());
+ }
+ Vector<Schedule> allycores = td2allycores.get(td);
+ if(!allycores.contains(tmpSchedule)) {
+ allycores.addElement(tmpSchedule);
+ }
+ allycores = null;
+ }
+ // If the FlagState can be fed to some multi-param tasks,
+ // need to record corresponding ally cores later.
+ tmpSchedule.addFState4TD(td, fs);
+ }
+ if(contain) {
+ tmpSchedule.addTask(td);
+ if(!td2cores.containsKey(td)) {
+ td2cores.put(td, new Vector<Schedule>());
+ }
+ Vector<Schedule> tmpcores = td2cores.get(td);
+ if(!tmpcores.contains(tmpSchedule)) {
+ tmpcores.add(tmpSchedule);
+ }
+ tmpcores = null;
+ }
+ if(td.getParamType(0).getClassDesc().getSymbol().equals(
+ TypeUtil.StartupClass)) {
+ assert(!setstartupcore);
+ startupcore = j;
+ startup = tmpSchedule;
+ setstartupcore = true;
+ }
+ }
+ it_edges = null;
+ }
+ it_flags = null;
}
cNodes = null;
// target ScheduleNode into the queue inside sn
Iterator it_edges = sn.edges();
while(it_edges.hasNext()) {
- ScheduleEdge se = (ScheduleEdge)it_edges.next();
- ScheduleNode target = (ScheduleNode)se.getTarget();
- Integer targetcore = sn2coreNum.get(target);
- switch(se.getType()) {
- case ScheduleEdge.NEWEDGE: {
- FlagState fs = se.getFstate();
- // Check if the new obj could be fed to some
- // multi-parameter task, if so, add for ally cores
- // checking
- Iterator it = fs.edges();
- boolean canTriggerSTask = false; // Flag indicates if fs can trigger
- // some single-param task
- while(it.hasNext()) {
- TaskDescriptor td = ((FEdge)it.next()).getTask();
- if(td.numParameters() > 1) {
- tmpSchedule.addFState4TD(td, fs); // TODO
- // add this core as a allycore of td
- if(!td2allycores.containsKey(td)) {
- td2allycores.put(td, new Vector<Schedule>());
- }
- Vector<Schedule> allycores = td2allycores.get(td);
- if(!allycores.contains(tmpSchedule)) {
- allycores.addElement(tmpSchedule);
- }
- } else {
- canTriggerSTask = true;
- }
- }
- if(canTriggerSTask) {
- // Only transfer the obj when it can trigger some single-parm task
- // TODO: ensure that multi-param tasks have these objects
- for(int k = 0; k < se.getNewRate(); k++) {
- tmpSchedule.addTargetCore(fs, targetcore);
- }
- }
- break;
- }
-
- case ScheduleEdge.TRANSEDGE: {
- // 'transmit' edge
- tmpSchedule.addTargetCore(se.getFstate(),
- targetcore,
- se.getTargetFState());
- // check if missed some FlagState associated with some
- // multi-parameter task, which has been cloned when
- // splitting a ClassNode
- FlagState fs = se.getSourceFState();
- FlagState tfs = se.getTargetFState();
- Iterator it = tfs.edges();
- while(it.hasNext()) {
- TaskDescriptor td = ((FEdge)it.next()).getTask();
- if(td.numParameters() > 1) {
- tmpSchedule.addFState4TD(td, fs);
- // add this core as a allycore of td
- if(!td2allycores.containsKey(td)) {
- td2allycores.put(td, new Vector<Schedule>());
- }
- Vector<Schedule> allycores = td2allycores.get(td);
- if(!allycores.contains(tmpSchedule)) {
- allycores.addElement(tmpSchedule);
- }
- }
- }
- break;
- }
- }
+ ScheduleEdge se = (ScheduleEdge)it_edges.next();
+ ScheduleNode target = (ScheduleNode)se.getTarget();
+ Integer targetcore = sn2coreNum.get(target);
+ switch(se.getType()) {
+ case ScheduleEdge.NEWEDGE: {
+ FlagState fs = se.getFstate();
+ // Check if the new obj could be fed to some
+ // multi-parameter task, if so, add for ally cores
+ // checking
+ Iterator it = fs.edges();
+ boolean canTriggerSTask = false; // Flag indicates if fs can trigger
+ // some single-param task
+ while(it.hasNext()) {
+ TaskDescriptor td = ((FEdge)it.next()).getTask();
+ if(td.numParameters() > 1) {
+ tmpSchedule.addFState4TD(td, fs); // TODO
+ // add this core as a allycore of td
+ if(!td2allycores.containsKey(td)) {
+ td2allycores.put(td, new Vector<Schedule>());
+ }
+ Vector<Schedule> allycores = td2allycores.get(td);
+ if(!allycores.contains(tmpSchedule)) {
+ allycores.addElement(tmpSchedule);
+ }
+ } else {
+ canTriggerSTask = true;
+ }
+ }
+ if(canTriggerSTask) {
+ // Only transfer the obj when it can trigger some single-parm task
+ // TODO: ensure that multi-param tasks have these objects
+ for(int k = 0; k < se.getNewRate(); k++) {
+ tmpSchedule.addTargetCore(fs, targetcore);
+ }
+ }
+ break;
+ }
+
+ case ScheduleEdge.TRANSEDGE: {
+ // 'transmit' edge
+ tmpSchedule.addTargetCore(se.getFstate(),
+ targetcore,
+ se.getTargetFState());
+ // check if missed some FlagState associated with some
+ // multi-parameter task, which has been cloned when
+ // splitting a ClassNode
+ FlagState fs = se.getSourceFState();
+ FlagState tfs = se.getTargetFState();
+ Iterator it = tfs.edges();
+ while(it.hasNext()) {
+ TaskDescriptor td = ((FEdge)it.next()).getTask();
+ if(td.numParameters() > 1) {
+ tmpSchedule.addFState4TD(td, fs);
+ // add this core as a allycore of td
+ if(!td2allycores.containsKey(td)) {
+ td2allycores.put(td, new Vector<Schedule>());
+ }
+ Vector<Schedule> allycores = td2allycores.get(td);
+ if(!allycores.contains(tmpSchedule)) {
+ allycores.addElement(tmpSchedule);
+ }
+ }
+ }
+ break;
+ }
+ }
}
it_edges = sn.getScheduleEdgesIterator();
while(it_edges.hasNext()) {
- ScheduleEdge se = (ScheduleEdge)it_edges.next();
- switch(se.getType()) {
- case ScheduleEdge.NEWEDGE: {
- // TODO, added 09/07/06
- FlagState fs = se.getFstate();
- // Check if the new obj could be fed to some
- // multi-parameter task, if so, add for ally cores
- // checking
- Iterator it = fs.edges();
- boolean canTriggerSTask = false; // Flag indicates if fs can trigger
- // some single-param task
- while(it.hasNext()) {
- TaskDescriptor td = ((FEdge)it.next()).getTask();
- if(td.numParameters() > 1) {
- tmpSchedule.addFState4TD(td, fs); // TODO
- // add this core as a allycore of td
- if(!td2allycores.containsKey(td)) {
- td2allycores.put(td, new Vector<Schedule>());
- }
- Vector<Schedule> allycores = td2allycores.get(td);
- if(!allycores.contains(tmpSchedule)) {
- allycores.addElement(tmpSchedule);
- }
- } else {
- canTriggerSTask = true;
- }
- }
- if(canTriggerSTask) {
- for(int k = 0; k < se.getNewRate(); k++) {
- tmpSchedule.addTargetCore(se.getFstate(), j);
- }
- }
- break;
- }
-
- case ScheduleEdge.TRANSEDGE: {
- // 'transmit' edge
- tmpSchedule.addTargetCore(se.getFstate(),
- j,
- se.getTargetFState());
- // check if missed some FlagState associated with some
- // multi-parameter task, which has been cloned when
- // splitting a ClassNode
- FlagState fs = se.getSourceFState();
- FlagState tfs = se.getTargetFState();
- Iterator it = tfs.edges();
- while(it.hasNext()) {
- TaskDescriptor td = ((FEdge)it.next()).getTask();
- if(td.numParameters() > 1) {
- tmpSchedule.addFState4TD(td, fs);
- // add this core as a allycore of td
- if(!td2allycores.containsKey(td)) {
- td2allycores.put(td, new Vector<Schedule>());
- }
- Vector<Schedule> allycores = td2allycores.get(td);
- if(!allycores.contains(tmpSchedule)) {
- allycores.addElement(tmpSchedule);
- }
- }
- }
- break;
- }
- }
+ ScheduleEdge se = (ScheduleEdge)it_edges.next();
+ switch(se.getType()) {
+ case ScheduleEdge.NEWEDGE: {
+ // TODO, added 09/07/06
+ FlagState fs = se.getFstate();
+ // Check if the new obj could be fed to some
+ // multi-parameter task, if so, add for ally cores
+ // checking
+ Iterator it = fs.edges();
+ boolean canTriggerSTask = false; // Flag indicates if fs can trigger
+ // some single-param task
+ while(it.hasNext()) {
+ TaskDescriptor td = ((FEdge)it.next()).getTask();
+ if(td.numParameters() > 1) {
+ tmpSchedule.addFState4TD(td, fs); // TODO
+ // add this core as a allycore of td
+ if(!td2allycores.containsKey(td)) {
+ td2allycores.put(td, new Vector<Schedule>());
+ }
+ Vector<Schedule> allycores = td2allycores.get(td);
+ if(!allycores.contains(tmpSchedule)) {
+ allycores.addElement(tmpSchedule);
+ }
+ } else {
+ canTriggerSTask = true;
+ }
+ }
+ if(canTriggerSTask) {
+ for(int k = 0; k < se.getNewRate(); k++) {
+ tmpSchedule.addTargetCore(se.getFstate(), j);
+ }
+ }
+ break;
+ }
+
+ case ScheduleEdge.TRANSEDGE: {
+ // 'transmit' edge
+ tmpSchedule.addTargetCore(se.getFstate(),
+ j,
+ se.getTargetFState());
+ // check if missed some FlagState associated with some
+ // multi-parameter task, which has been cloned when
+ // splitting a ClassNode
+ FlagState fs = se.getSourceFState();
+ FlagState tfs = se.getTargetFState();
+ Iterator it = tfs.edges();
+ while(it.hasNext()) {
+ TaskDescriptor td = ((FEdge)it.next()).getTask();
+ if(td.numParameters() > 1) {
+ tmpSchedule.addFState4TD(td, fs);
+ // add this core as a allycore of td
+ if(!td2allycores.containsKey(td)) {
+ td2allycores.put(td, new Vector<Schedule>());
+ }
+ Vector<Schedule> allycores = td2allycores.get(td);
+ if(!allycores.contains(tmpSchedule)) {
+ allycores.addElement(tmpSchedule);
+ }
+ }
+ }
+ break;
+ }
+ }
}
it_edges = null;
scheduling.add(tmpSchedule);
Vector<Schedule> cores = td2cores.get(td);
assert(cores.size() == 1); // should have only one core
for(int k = 0; k < cores.size(); ++k) {
- Schedule tmpSchedule = cores.elementAt(k);
-
- // Make sure all the parameter objs of a multi-parameter
- // task would be send to right place after the task finished
- for(int h = 0; h < fes.size(); ++h) {
- FEdge tmpfe = fes.elementAt(h);
- FlagState tmpfs = (FlagState)tmpfe.getTarget();
- Vector<TaskDescriptor> tmptds = new Vector<TaskDescriptor>();
- if((tmpSchedule.getTargetCoreTable() == null)
- || (!tmpSchedule.getTargetCoreTable().containsKey(tmpfs))) {
- // add up all possible cores' info
- Iterator it_edges = tmpfs.edges();
- while(it_edges.hasNext()) {
- TaskDescriptor tmptd = ((FEdge)it_edges.next()).getTask();
- if(!tmptds.contains(tmptd)) {
- tmptds.add(tmptd);
- // only multiparam task will be processed here!!! TODO
- Vector<Schedule> tmpcores = td2cores.get(tmptd);
- for(int m = 0; m < tmpcores.size(); ++m) {
- Schedule target = tmpcores.elementAt(m);
- int targetcore = target.getCoreNum();
- int num = target.getTaskNum(tmptd);
- for(int n = 0; n < num; n++) {
- tmpSchedule.addTargetCore(tmpfs, targetcore);
- }
- }
- tmpcores = null;
- }
- }
- it_edges = null;
- }
- tmptds = null;
- }
+ Schedule tmpSchedule = cores.elementAt(k);
+
+ // Make sure all the parameter objs of a multi-parameter
+ // task would be send to right place after the task finished
+ for(int h = 0; h < fes.size(); ++h) {
+ FEdge tmpfe = fes.elementAt(h);
+ FlagState tmpfs = (FlagState)tmpfe.getTarget();
+ Vector<TaskDescriptor> tmptds = new Vector<TaskDescriptor>();
+ if((tmpSchedule.getTargetCoreTable() == null)
+ || (!tmpSchedule.getTargetCoreTable().containsKey(tmpfs))) {
+ // add up all possible cores' info
+ Iterator it_edges = tmpfs.edges();
+ while(it_edges.hasNext()) {
+ TaskDescriptor tmptd = ((FEdge)it_edges.next()).getTask();
+ if(!tmptds.contains(tmptd)) {
+ tmptds.add(tmptd);
+ // only multiparam task will be processed here!!! TODO
+ Vector<Schedule> tmpcores = td2cores.get(tmptd);
+ for(int m = 0; m < tmpcores.size(); ++m) {
+ Schedule target = tmpcores.elementAt(m);
+ int targetcore = target.getCoreNum();
+ int num = target.getTaskNum(tmptd);
+ for(int n = 0; n < num; n++) {
+ tmpSchedule.addTargetCore(tmpfs, targetcore);
+ }
+ }
+ tmpcores = null;
+ }
+ }
+ it_edges = null;
+ }
+ tmptds = null;
+ }
}
fes = null;
cores = null;
TaskDescriptor td = it_mptds.next();
Vector<Schedule> allycores = td2allycores.get(td);
for(int i = 0; i < allycores.size(); i++) {
- Schedule tSchedule = allycores.elementAt(i);
- Vector<FlagState> tmpfss = tSchedule.getFStates4TD(td);
- int targetcore = td2maincore.get(td).intValue();
- for(int h = 0; h < tmpfss.size(); ++h) {
- tSchedule.addAllyCore(tmpfss.elementAt(h), targetcore);
- }
- tmpfss = null;
+ Schedule tSchedule = allycores.elementAt(i);
+ Vector<FlagState> tmpfss = tSchedule.getFStates4TD(td);
+ int targetcore = td2maincore.get(td).intValue();
+ for(int h = 0; h < tmpfss.size(); ++h) {
+ tSchedule.addAllyCore(tmpfss.elementAt(h), targetcore);
+ }
+ tmpfss = null;
}
}
it_mptds = null;
if ((oi.obj != obj) ||
(oi.fs != fs) ||
(oi.version != version)) {
- return false;
+ return false;
}
return true;
}
this.changed = true;
currentFS = (FlagState)fedge.getTarget();
if(this.counter > 0) {
- //System.err.println(this.counter);
- this.counter--;
+ //System.err.println(this.counter);
+ this.counter--;
}
if((this.cd.getSymbol().equals("Cluster")) && (this.counter == 0)) {
- // go to end state
- this.currentFS = new FlagState(this.cd);
+ // go to end state
+ this.currentFS = new FlagState(this.cd);
}
} else {
this.changed = false;
ScheduleNode startupNode = null;
if((multiparamtds != null) || (multiparamtds.size() > 0)) {
- this.td2maincd = new Hashtable<TaskDescriptor, ClassDescriptor>();
+ this.td2maincd = new Hashtable<TaskDescriptor, ClassDescriptor>();
}
// necessary preparation such as read profile info etc.
long tint = 0;
Iterator it_classes = state.getClassSymbolTable().getDescriptorsIterator();
while(it_classes.hasNext()) {
- ClassDescriptor cd = (ClassDescriptor) it_classes.next();
- if(cd.hasFlags()) {
- Vector rootnodes = this.taskanalysis.getRootNodes(cd);
- if(rootnodes!=null) {
- Iterator it_rootnodes = rootnodes.iterator();
- while(it_rootnodes.hasNext()) {
- FlagState root = (FlagState)it_rootnodes.next();
- Vector allocatingTasks = root.getAllocatingTasks();
- if(allocatingTasks != null) {
- for(int k = 0; k < allocatingTasks.size(); k++) {
- TaskDescriptor td =
- (TaskDescriptor)allocatingTasks.elementAt(k);
- Vector<FEdge> fev = this.taskanalysis.getFEdgesFromTD(td);
- int numEdges = fev.size();
- for(int j = 0; j < numEdges; j++) {
- FEdge pfe = fev.elementAt(j);
- TaskInfo taskinfo = taskinfos.get(td.getSymbol());
- tint = taskinfo.m_exetime[pfe.getTaskExitIndex()];
- pfe.setExeTime(tint);
- double idouble =
- taskinfo.m_probability[pfe.getTaskExitIndex()];
- pfe.setProbability(idouble);
- int newRate = 0;
- int tindex = pfe.getTaskExitIndex();
- if((taskinfo.m_newobjinfo.elementAt(tindex) != null)
- && (taskinfo.m_newobjinfo.elementAt(tindex).containsKey(
- cd.getSymbol()))) {
- newRate = taskinfo.m_newobjinfo.elementAt(tindex).get(
- cd.getSymbol());
- }
- pfe.addNewObjInfo(cd, newRate, idouble);
- if(taskinfo.m_byObj != -1) {
- ((FlagState)pfe.getSource()).setByObj(taskinfo.m_byObj);
- }
- // TODO for test
- /*System.err.println("task " + td.getSymbol() + " exit# " +
- pfe.getTaskExitIndex() + " exetime: " + pfe.getExeTime()
- + " prob: " + pfe.getProbability() + "% newobj: "
- + pfe.getNewObjInfoHashtable().size());*/
- }
- fev = null;
- }
- }
- }
- it_rootnodes = null;
- }
- Iterator it_flags = this.taskanalysis.getFlagStates(cd).iterator();
- while(it_flags.hasNext()) {
- FlagState fs = (FlagState)it_flags.next();
- Iterator it_edges = fs.edges();
- while(it_edges.hasNext()) {
- FEdge edge = (FEdge)it_edges.next();
- TaskInfo taskinfo = taskinfos.get(edge.getTask().getSymbol());
- double idouble = 0.0;
- if(edge.getTaskExitIndex() >= taskinfo.m_exetime.length) {
- tint = 0;
- } else {
- tint = taskinfo.m_exetime[edge.getTaskExitIndex()];
- idouble = taskinfo.m_probability[edge.getTaskExitIndex()];
- }
- edge.setExeTime(tint);
- edge.setProbability(idouble);
- if(taskinfo.m_byObj != -1) {
- ((FlagState)edge.getSource()).setByObj(taskinfo.m_byObj);
- }
- // TODO for test
- /*System.err.println("task " + edge.getTask().getSymbol() + " exit# " +
- edge.getTaskExitIndex() + " exetime: " + edge.getExeTime()
- + " prob: " + edge.getProbability());*/
- }
- it_edges = null;
- }
- it_flags = null;
- }
+ ClassDescriptor cd = (ClassDescriptor) it_classes.next();
+ if(cd.hasFlags()) {
+ Vector rootnodes = this.taskanalysis.getRootNodes(cd);
+ if(rootnodes!=null) {
+ Iterator it_rootnodes = rootnodes.iterator();
+ while(it_rootnodes.hasNext()) {
+ FlagState root = (FlagState)it_rootnodes.next();
+ Vector allocatingTasks = root.getAllocatingTasks();
+ if(allocatingTasks != null) {
+ for(int k = 0; k < allocatingTasks.size(); k++) {
+ TaskDescriptor td =
+ (TaskDescriptor)allocatingTasks.elementAt(k);
+ Vector<FEdge> fev = this.taskanalysis.getFEdgesFromTD(td);
+ int numEdges = fev.size();
+ for(int j = 0; j < numEdges; j++) {
+ FEdge pfe = fev.elementAt(j);
+ TaskInfo taskinfo = taskinfos.get(td.getSymbol());
+ tint = taskinfo.m_exetime[pfe.getTaskExitIndex()];
+ pfe.setExeTime(tint);
+ double idouble =
+ taskinfo.m_probability[pfe.getTaskExitIndex()];
+ pfe.setProbability(idouble);
+ int newRate = 0;
+ int tindex = pfe.getTaskExitIndex();
+ if((taskinfo.m_newobjinfo.elementAt(tindex) != null)
+ && (taskinfo.m_newobjinfo.elementAt(tindex).containsKey(
+ cd.getSymbol()))) {
+ newRate = taskinfo.m_newobjinfo.elementAt(tindex).get(
+ cd.getSymbol());
+ }
+ pfe.addNewObjInfo(cd, newRate, idouble);
+ if(taskinfo.m_byObj != -1) {
+ ((FlagState)pfe.getSource()).setByObj(taskinfo.m_byObj);
+ }
+ // TODO for test
+ /*System.err.println("task " + td.getSymbol() + " exit# " +
+ pfe.getTaskExitIndex() + " exetime: " + pfe.getExeTime()
+ + " prob: " + pfe.getProbability() + "% newobj: "
+ + pfe.getNewObjInfoHashtable().size());*/
+ }
+ fev = null;
+ }
+ }
+ }
+ it_rootnodes = null;
+ }
+ Iterator it_flags = this.taskanalysis.getFlagStates(cd).iterator();
+ while(it_flags.hasNext()) {
+ FlagState fs = (FlagState)it_flags.next();
+ Iterator it_edges = fs.edges();
+ while(it_edges.hasNext()) {
+ FEdge edge = (FEdge)it_edges.next();
+ TaskInfo taskinfo = taskinfos.get(edge.getTask().getSymbol());
+ double idouble = 0.0;
+ if(edge.getTaskExitIndex() >= taskinfo.m_exetime.length) {
+ tint = 0;
+ } else {
+ tint = taskinfo.m_exetime[edge.getTaskExitIndex()];
+ idouble = taskinfo.m_probability[edge.getTaskExitIndex()];
+ }
+ edge.setExeTime(tint);
+ edge.setProbability(idouble);
+ if(taskinfo.m_byObj != -1) {
+ ((FlagState)edge.getSource()).setByObj(taskinfo.m_byObj);
+ }
+ // TODO for test
+ /*System.err.println("task " + edge.getTask().getSymbol() + " exit# " +
+ edge.getTaskExitIndex() + " exetime: " + edge.getExeTime()
+ + " prob: " + edge.getProbability());*/
+ }
+ it_edges = null;
+ }
+ it_flags = null;
+ }
}
taskinfos = null;
it_classes = null;
while(it_classes.hasNext()) {
ClassDescriptor cd=(ClassDescriptor) it_classes.next();
if(cd.hasFlags()) {
- Set<FlagState> fss = this.taskanalysis.getFlagStates(cd);
- SCC scc=GraphNode.DFS.computeSCC(fss);
- if (scc.hasCycles()) {
- for(int i=0; i<scc.numSCC(); i++) {
- if (scc.hasCycle(i)) {
- Set cycleset = scc.getSCC(i);
- Iterator it_fs = cycleset.iterator();
- while(it_fs.hasNext()) {
- FlagState fs = (FlagState)it_fs.next();
- Iterator it_edges = fs.edges();
- while(it_edges.hasNext()) {
- FEdge edge = (FEdge)it_edges.next();
- if(cycleset.contains(edge.getTarget())) {
- // a backedge
- edge.setisbackedge(true);
- }
- }
- it_edges = null;
- }
- it_fs = null;
- }
- }
- }
- fss = null;
+ Set<FlagState> fss = this.taskanalysis.getFlagStates(cd);
+ SCC scc=GraphNode.DFS.computeSCC(fss);
+ if (scc.hasCycles()) {
+ for(int i=0; i<scc.numSCC(); i++) {
+ if (scc.hasCycle(i)) {
+ Set cycleset = scc.getSCC(i);
+ Iterator it_fs = cycleset.iterator();
+ while(it_fs.hasNext()) {
+ FlagState fs = (FlagState)it_fs.next();
+ Iterator it_edges = fs.edges();
+ while(it_edges.hasNext()) {
+ FEdge edge = (FEdge)it_edges.next();
+ if(cycleset.contains(edge.getTarget())) {
+ // a backedge
+ edge.setisbackedge(true);
+ }
+ }
+ it_edges = null;
+ }
+ it_fs = null;
+ }
+ }
+ }
+ fss = null;
}
}
it_classes = null;
byte[] b = new byte[1024 * 100];
int length = inStream.read(b);
if(length < 0) {
- System.out.print("No content in input file: /scratch/"
- + this.state.profilename + "\n");
- System.exit(-1);
+ System.out.print("No content in input file: /scratch/"
+ + this.state.profilename + "\n");
+ System.exit(-1);
}
String profiledata = new String(b, 0, length);
// newobj type, num of objs)+)+
int inindex = profiledata.indexOf('\n');
while((inindex != -1) ) {
- String inline = profiledata.substring(0, inindex);
- profiledata = profiledata.substring(inindex + 1);
- //System.printString(inline + "\n");
- int tmpinindex = inline.indexOf(',');
- if(tmpinindex == -1) {
- break;
- }
- String inname = inline.substring(0, tmpinindex);
- String inint = inline.substring(tmpinindex + 1);
- while(inint.startsWith(" ")) {
- inint = inint.substring(1);
- }
- tmpinindex = inint.indexOf(',');
- if(tmpinindex == -1) {
- break;
- }
- int numofexits = Integer.parseInt(inint.substring(0, tmpinindex));
- TaskInfo tinfo = new TaskInfo(numofexits);
- inint = inint.substring(tmpinindex + 1);
- while(inint.startsWith(" ")) {
- inint = inint.substring(1);
- }
- tmpinindex = inint.indexOf(';');
- int byObj = Integer.parseInt(inint.substring(0, tmpinindex));
- if(byObj != -1) {
- tinfo.m_byObj = byObj;
- }
- inint = inint.substring(tmpinindex + 1);
- while(inint.startsWith(" ")) {
- inint = inint.substring(1);
- }
- for(int i = 0; i < numofexits; i++) {
- String tmpinfo = null;
- if(i < numofexits - 1) {
- tmpinindex = inint.indexOf(';');
- tmpinfo = inint.substring(0, tmpinindex);
- inint = inint.substring(tmpinindex + 1);
- while(inint.startsWith(" ")) {
- inint = inint.substring(1);
- }
- } else {
- tmpinfo = inint;
- }
-
- tmpinindex = tmpinfo.indexOf(',');
- tinfo.m_exetime[i] = Long.parseLong(tmpinfo.substring(0, tmpinindex));
- tmpinfo = tmpinfo.substring(tmpinindex + 1);
- while(tmpinfo.startsWith(" ")) {
- tmpinfo = tmpinfo.substring(1);
- }
- tmpinindex = tmpinfo.indexOf(',');
- tinfo.m_probability[i] = Double.parseDouble(
- tmpinfo.substring(0,tmpinindex));
- tmpinfo = tmpinfo.substring(tmpinindex + 1);
- while(tmpinfo.startsWith(" ")) {
- tmpinfo = tmpinfo.substring(1);
- }
- tmpinindex = tmpinfo.indexOf(',');
- int numofnobjs = 0;
- if(tmpinindex == -1) {
- numofnobjs = Integer.parseInt(tmpinfo);
- if(numofnobjs != 0) {
- System.err.println("Error profile data format!");
- System.exit(-1);
- }
- } else {
- tinfo.m_newobjinfo.setElementAt(new Hashtable<String,Integer>(), i);
- numofnobjs = Integer.parseInt(tmpinfo.substring(0, tmpinindex));
- tmpinfo = tmpinfo.substring(tmpinindex + 1);
- while(tmpinfo.startsWith(" ")) {
- tmpinfo = tmpinfo.substring(1);
- }
- for(int j = 0; j < numofnobjs; j++) {
- tmpinindex = tmpinfo.indexOf(',');
- String nobjtype = tmpinfo.substring(0, tmpinindex);
- tmpinfo = tmpinfo.substring(tmpinindex + 1);
- while(tmpinfo.startsWith(" ")) {
- tmpinfo = tmpinfo.substring(1);
- }
- int objnum = 0;
- if(j < numofnobjs - 1) {
- tmpinindex = tmpinfo.indexOf(',');
- objnum = Integer.parseInt(tmpinfo.substring(0, tmpinindex));
- tmpinfo = tmpinfo.substring(tmpinindex + 1);
- while(tmpinfo.startsWith(" ")) {
- tmpinfo = tmpinfo.substring(1);
- }
- } else {
- objnum = Integer.parseInt(tmpinfo);
- }
- tinfo.m_newobjinfo.elementAt(i).put(nobjtype, objnum);
- }
- }
- }
- taskinfos.put(inname, tinfo);
- inindex = profiledata.indexOf('\n');
+ String inline = profiledata.substring(0, inindex);
+ profiledata = profiledata.substring(inindex + 1);
+ //System.printString(inline + "\n");
+ int tmpinindex = inline.indexOf(',');
+ if(tmpinindex == -1) {
+ break;
+ }
+ String inname = inline.substring(0, tmpinindex);
+ String inint = inline.substring(tmpinindex + 1);
+ while(inint.startsWith(" ")) {
+ inint = inint.substring(1);
+ }
+ tmpinindex = inint.indexOf(',');
+ if(tmpinindex == -1) {
+ break;
+ }
+ int numofexits = Integer.parseInt(inint.substring(0, tmpinindex));
+ TaskInfo tinfo = new TaskInfo(numofexits);
+ inint = inint.substring(tmpinindex + 1);
+ while(inint.startsWith(" ")) {
+ inint = inint.substring(1);
+ }
+ tmpinindex = inint.indexOf(';');
+ int byObj = Integer.parseInt(inint.substring(0, tmpinindex));
+ if(byObj != -1) {
+ tinfo.m_byObj = byObj;
+ }
+ inint = inint.substring(tmpinindex + 1);
+ while(inint.startsWith(" ")) {
+ inint = inint.substring(1);
+ }
+ for(int i = 0; i < numofexits; i++) {
+ String tmpinfo = null;
+ if(i < numofexits - 1) {
+ tmpinindex = inint.indexOf(';');
+ tmpinfo = inint.substring(0, tmpinindex);
+ inint = inint.substring(tmpinindex + 1);
+ while(inint.startsWith(" ")) {
+ inint = inint.substring(1);
+ }
+ } else {
+ tmpinfo = inint;
+ }
+
+ tmpinindex = tmpinfo.indexOf(',');
+ tinfo.m_exetime[i] = Long.parseLong(tmpinfo.substring(0, tmpinindex));
+ tmpinfo = tmpinfo.substring(tmpinindex + 1);
+ while(tmpinfo.startsWith(" ")) {
+ tmpinfo = tmpinfo.substring(1);
+ }
+ tmpinindex = tmpinfo.indexOf(',');
+ tinfo.m_probability[i] = Double.parseDouble(
+ tmpinfo.substring(0,tmpinindex));
+ tmpinfo = tmpinfo.substring(tmpinindex + 1);
+ while(tmpinfo.startsWith(" ")) {
+ tmpinfo = tmpinfo.substring(1);
+ }
+ tmpinindex = tmpinfo.indexOf(',');
+ int numofnobjs = 0;
+ if(tmpinindex == -1) {
+ numofnobjs = Integer.parseInt(tmpinfo);
+ if(numofnobjs != 0) {
+ System.err.println("Error profile data format!");
+ System.exit(-1);
+ }
+ } else {
+ tinfo.m_newobjinfo.setElementAt(new Hashtable<String,Integer>(), i);
+ numofnobjs = Integer.parseInt(tmpinfo.substring(0, tmpinindex));
+ tmpinfo = tmpinfo.substring(tmpinindex + 1);
+ while(tmpinfo.startsWith(" ")) {
+ tmpinfo = tmpinfo.substring(1);
+ }
+ for(int j = 0; j < numofnobjs; j++) {
+ tmpinindex = tmpinfo.indexOf(',');
+ String nobjtype = tmpinfo.substring(0, tmpinindex);
+ tmpinfo = tmpinfo.substring(tmpinindex + 1);
+ while(tmpinfo.startsWith(" ")) {
+ tmpinfo = tmpinfo.substring(1);
+ }
+ int objnum = 0;
+ if(j < numofnobjs - 1) {
+ tmpinindex = tmpinfo.indexOf(',');
+ objnum = Integer.parseInt(tmpinfo.substring(0, tmpinindex));
+ tmpinfo = tmpinfo.substring(tmpinindex + 1);
+ while(tmpinfo.startsWith(" ")) {
+ tmpinfo = tmpinfo.substring(1);
+ }
+ } else {
+ objnum = Integer.parseInt(tmpinfo);
+ }
+ tinfo.m_newobjinfo.elementAt(i).put(nobjtype, objnum);
+ }
+ }
+ }
+ taskinfos.put(inname, tinfo);
+ inindex = profiledata.indexOf('\n');
}
inStream.close();
inStream = null;
for(; it_classes.hasNext(); ) {
ClassDescriptor cd=(ClassDescriptor) it_classes.next();
if(cd.hasFlags()) {
- Vector rootnodes=this.taskanalysis.getRootNodes(cd);
- if(rootnodes!=null) {
- Iterator it_rootnodes=rootnodes.iterator();
- for(; it_rootnodes.hasNext(); ) {
- FlagState root=(FlagState)it_rootnodes.next();
- Vector allocatingTasks = root.getAllocatingTasks();
- if(allocatingTasks != null) {
- for(int k = 0; k < allocatingTasks.size(); k++) {
- TaskDescriptor td = (TaskDescriptor)allocatingTasks.elementAt(k);
- Vector<FEdge> fev =
- (Vector<FEdge>) this.taskanalysis.getFEdgesFromTD(td);
- int numEdges = fev.size();
- int total = 100;
- for(int j = 0; j < numEdges; j++) {
- FEdge pfe = fev.elementAt(j);
- if(numEdges - j == 1) {
- pfe.setProbability(total);
- } else {
- if((total != 0) && (total != 1)) {
- do {
- tint = r.nextInt()%total;
- } while(tint <= 0);
- }
- pfe.setProbability(tint);
- total -= tint;
- }
- //do {
- // tint = r.nextInt()%10;
- // } while(tint <= 0);
- //int newRate = tint;
- //int newRate = (j+1)%2+1;
- int newRate = 1;
- String cdname = cd.getSymbol();
- if((cdname.equals("SeriesRunner")) ||
- (cdname.equals("MDRunner")) ||
- (cdname.equals("Stage")) ||
- (cdname.equals("AppDemoRunner")) ||
- (cdname.equals("FilterBankAtom")) ||
- (cdname.equals("Grid")) ||
- (cdname.equals("Fractal")) ||
- (cdname.equals("KMeans")) ||
- (cdname.equals("ZTransform")) ||
- (cdname.equals("TestRunner")) ||
- (cdname.equals("TestRunner2")) ||
- (cdname.equals("LinkList")) ||
- (cdname.equals("BHRunner"))) {
- newRate = this.coreNum;
- } else if(cdname.equals("SentenceParser")) {
- newRate = 4;
- } else if(cdname.equals("BlurPiece")) {
- newRate = 4;
- } else if(cdname.equals("ImageX")) {
- newRate = 2 * 2;
- } else if(cdname.equals("ImageY")) {
- newRate = 1 * 4;
- }
- //do {
- // tint = r.nextInt()%100;
- // } while(tint <= 0);
- // int probability = tint;
- int probability = 100;
- pfe.addNewObjInfo(cd, newRate, probability);
- }
- fev = null;
- }
- }
- }
- it_rootnodes = null;
- }
-
- Iterator it_flags = this.taskanalysis.getFlagStates(cd).iterator();
- while(it_flags.hasNext()) {
- FlagState fs = (FlagState)it_flags.next();
- Iterator it_edges = fs.edges();
- int total = 100;
- while(it_edges.hasNext()) {
- //do {
- // tint = r.nextInt()%10;
- // } while(tint <= 0);
- tint = 3;
- FEdge edge = (FEdge)it_edges.next();
- edge.setExeTime(tint);
- if((fs.getClassDescriptor().getSymbol().equals("MD"))
- && (edge.getTask().getSymbol().equals("t6"))) {
- if(edge.isbackedge()) {
- if(edge.getTarget().equals(edge.getSource())) {
- edge.setProbability(93.75);
- } else {
- edge.setProbability(3.125);
- }
- } else {
- edge.setProbability(3.125);
- }
- continue;
- }
- if(!it_edges.hasNext()) {
- edge.setProbability(total);
- } else {
- if((total != 0) && (total != 1)) {
- do {
- tint = r.nextInt()%total;
- } while(tint <= 0);
- }
- edge.setProbability(tint);
- total -= tint;
- }
- }
- it_edges = null;
- }
- it_flags = null;
+ Vector rootnodes=this.taskanalysis.getRootNodes(cd);
+ if(rootnodes!=null) {
+ Iterator it_rootnodes=rootnodes.iterator();
+ for(; it_rootnodes.hasNext(); ) {
+ FlagState root=(FlagState)it_rootnodes.next();
+ Vector allocatingTasks = root.getAllocatingTasks();
+ if(allocatingTasks != null) {
+ for(int k = 0; k < allocatingTasks.size(); k++) {
+ TaskDescriptor td = (TaskDescriptor)allocatingTasks.elementAt(k);
+ Vector<FEdge> fev =
+ (Vector<FEdge>) this.taskanalysis.getFEdgesFromTD(td);
+ int numEdges = fev.size();
+ int total = 100;
+ for(int j = 0; j < numEdges; j++) {
+ FEdge pfe = fev.elementAt(j);
+ if(numEdges - j == 1) {
+ pfe.setProbability(total);
+ } else {
+ if((total != 0) && (total != 1)) {
+ do {
+ tint = r.nextInt()%total;
+ } while(tint <= 0);
+ }
+ pfe.setProbability(tint);
+ total -= tint;
+ }
+ //do {
+ // tint = r.nextInt()%10;
+ // } while(tint <= 0);
+ //int newRate = tint;
+ //int newRate = (j+1)%2+1;
+ int newRate = 1;
+ String cdname = cd.getSymbol();
+ if((cdname.equals("SeriesRunner")) ||
+ (cdname.equals("MDRunner")) ||
+ (cdname.equals("Stage")) ||
+ (cdname.equals("AppDemoRunner")) ||
+ (cdname.equals("FilterBankAtom")) ||
+ (cdname.equals("Grid")) ||
+ (cdname.equals("Fractal")) ||
+ (cdname.equals("KMeans")) ||
+ (cdname.equals("ZTransform")) ||
+ (cdname.equals("TestRunner")) ||
+ (cdname.equals("TestRunner2")) ||
+ (cdname.equals("LinkList")) ||
+ (cdname.equals("BHRunner"))) {
+ newRate = this.coreNum;
+ } else if(cdname.equals("SentenceParser")) {
+ newRate = 4;
+ } else if(cdname.equals("BlurPiece")) {
+ newRate = 4;
+ } else if(cdname.equals("ImageX")) {
+ newRate = 2 * 2;
+ } else if(cdname.equals("ImageY")) {
+ newRate = 1 * 4;
+ }
+ //do {
+ // tint = r.nextInt()%100;
+ // } while(tint <= 0);
+ // int probability = tint;
+ int probability = 100;
+ pfe.addNewObjInfo(cd, newRate, probability);
+ }
+ fev = null;
+ }
+ }
+ }
+ it_rootnodes = null;
+ }
+
+ Iterator it_flags = this.taskanalysis.getFlagStates(cd).iterator();
+ while(it_flags.hasNext()) {
+ FlagState fs = (FlagState)it_flags.next();
+ Iterator it_edges = fs.edges();
+ int total = 100;
+ while(it_edges.hasNext()) {
+ //do {
+ // tint = r.nextInt()%10;
+ // } while(tint <= 0);
+ tint = 3;
+ FEdge edge = (FEdge)it_edges.next();
+ edge.setExeTime(tint);
+ if((fs.getClassDescriptor().getSymbol().equals("MD"))
+ && (edge.getTask().getSymbol().equals("t6"))) {
+ if(edge.isbackedge()) {
+ if(edge.getTarget().equals(edge.getSource())) {
+ edge.setProbability(93.75);
+ } else {
+ edge.setProbability(3.125);
+ }
+ } else {
+ edge.setProbability(3.125);
+ }
+ continue;
+ }
+ if(!it_edges.hasNext()) {
+ edge.setProbability(total);
+ } else {
+ if((total != 0) && (total != 1)) {
+ do {
+ tint = r.nextInt()%total;
+ } while(tint <= 0);
+ }
+ edge.setProbability(tint);
+ total -= tint;
+ }
+ }
+ it_edges = null;
+ }
+ it_flags = null;
}
}
it_classes = null;
Vector rootnodes = taskanalysis.getRootNodes(cd);
if(((rootnodes != null) && (rootnodes.size() > 0))
|| (cd.getSymbol().equals(TypeUtil.StartupClass))) {
- ClassNode cNode = new ClassNode(cd, sFStates);
- cNode.setSorted(true);
- classNodes.add(cNode);
- cd2ClassNode.put(cd, cNode);
- cdToCNodes.put(cd, cNode);
- cNode.calExeTime();
+ ClassNode cNode = new ClassNode(cd, sFStates);
+ cNode.setSorted(true);
+ classNodes.add(cNode);
+ cd2ClassNode.put(cd, cNode);
+ cdToCNodes.put(cd, cNode);
+ cNode.calExeTime();
}
rootnodes = null;
fStates = null;
ClassNode cn = classNodes.elementAt(i);
ScheduleNode sn = new ScheduleNode(cn, 0);
if(cn.getClassDescriptor().getSymbol().equals(TypeUtil.StartupClass)) {
- startupNode = sn;
+ startupNode = sn;
}
cn.setScheduleNode(sn);
scheduleNodes.add(sn);
try {
- sn.calExeTime();
+ sn.calExeTime();
} catch (Exception e) {
- e.printStackTrace();
+ e.printStackTrace();
}
}
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;
+ 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;
}
}
cdToCNodes = null;
// Break down the 'cycle's
try {
for(i = 0; i < toBreakDown.size(); i++ ) {
- cloneSNodeList(toBreakDown.elementAt(i), false);
+ cloneSNodeList(toBreakDown.elementAt(i), false);
}
} catch (Exception e) {
e.printStackTrace();
for(i = 0; i < scheduleEdges.size(); i++) {
ScheduleEdge se = (ScheduleEdge)scheduleEdges.elementAt(i);
if((0 == se.getNewRate()) || (0 == se.getProbability())) {
- scheduleEdges.removeElement(se);
- scheduleNodes.removeElement(se.getTarget());
+ scheduleEdges.removeElement(se);
+ scheduleNodes.removeElement(se.getTarget());
}
}
while(!toVisit.isEmpty()) {
ScheduleNode sn = toVisit.poll();
if(sn.getCid() == -1) {
- // not visited before
- sn.setCid(ScheduleNode.colorID++);
- Iterator it_edge = sn.edges();
- while(it_edge.hasNext()) {
- toVisit.add((ScheduleNode)((ScheduleEdge)it_edge.next()).getTarget());
- }
- it_edge = null;
+ // not visited before
+ sn.setCid(ScheduleNode.colorID++);
+ Iterator it_edge = sn.edges();
+ while(it_edge.hasNext()) {
+ toVisit.add((ScheduleNode)((ScheduleEdge)it_edge.next()).getTarget());
+ }
+ it_edge = null;
}
}
toVisit = null;
long temptime = tempse.getListExeTime();
// find out the ScheduleEdge with least exeTime
for(int k = 1; k < ses.size(); k++) {
- long ttemp = ses.elementAt(k).getListExeTime();
- if(ttemp < temptime) {
- tempse = ses.elementAt(k);
- temptime = ttemp;
- } // if(ttemp < temptime)
+ long ttemp = ses.elementAt(k).getListExeTime();
+ if(ttemp < temptime) {
+ tempse = ses.elementAt(k);
+ temptime = ttemp;
+ } // if(ttemp < temptime)
} // for(int k = 1; k < ses.size(); k++)
// handle the tempse
handleScheduleEdge(tempse, true);
for(i = scheduleEdges.size(); i > 0; i--) {
ScheduleEdge se = (ScheduleEdge)scheduleEdges.elementAt(i-1);
if(ScheduleEdge.NEWEDGE == se.getType()) {
- if(preSNode == null) {
- preSNode = (ScheduleNode)se.getSource();
- }
-
- boolean split = false;
- FEdge fe = se.getFEdge();
- if(fe.getSource() == fe.getTarget()) {
- // the associated start fe is a back edge
- try {
- // check the number of newly created objs
- int repeat = (int)Math.ceil(se.getNewRate()*se.getProbability()/100);
- int rate = 0;
- /*if(repeat > 1) {
- // more than one new objs, expand the new edge
- for(int j = 1; j< repeat; j++ ) {
- cloneSNodeList(se, true);
- } // for(int j = 1; j< repeat; j++ )
- se.setNewRate(1);
- se.setProbability(100);
- } // if(repeat > 1)*/
- try {
- // match the rates of obj creation and new obj consumption
- rate = (int)Math.ceil(
- se.getListExeTime()/calInExeTime(se.getSourceFState()));
- } catch (Exception e) {
- e.printStackTrace();
- } // try-catch {}
- repeat = (rate > repeat)?rate:repeat;
- // expand the new edge
- for(int j = 1; j< repeat; j++ ) {
- cloneSNodeList(se, true);
- } // for(int j = 1; j< repeat; j++ )
- se.setNewRate(1);
- se.setProbability(100);
- /*for(int j = rate - 1; j > 0; j--) {
- for(int k = repeat; k > 0; k--) {
- cloneSNodeList(se, true);
- } // for(int k = repeat; k > 0; k--)
- } // for(int j = rate - 1; j > 0; j--)*/
- } catch (Exception e) {
- e.printStackTrace();
- System.exit(-1);
- } // try-catch{}
- } else { // if(fe.getSource() == fe.getTarget())
- // the associated start fe is not a back edge
- // Note: if preSNode is not the same as se's source ScheduleNode
- // handle any ScheduleEdges previously put into fe2ses whose source
- // ScheduleNode is preSNode
- boolean same = (preSNode == se.getSource());
- if(!same) {
- // check the topology sort, only process those after se.getSource()
- if(preSNode.getFinishingTime() < se.getSource().getFinishingTime()) {
- if(sn2fes.containsKey(preSNode)) {
- Vector<FEdge> fes = sn2fes.remove(preSNode);
- for(int j = 0; j < fes.size(); j++) {
- FEdge tempfe = fes.elementAt(j);
- Vector<ScheduleEdge> ses = fe2ses.get(tempfe);
- boolean isflag = !(preSNode.edges().hasNext());
- this.handleDescenSEs(ses, isflag);
- ses = null;
- fe2ses.remove(tempfe);
- } // for(int j = 0; j < fes.size(); j++)
- fes = null;
- }
- }
- preSNode = (ScheduleNode)se.getSource();
- } // if(!same)
-
- if(fe.getTarget().edges().hasNext()) {
- // not associated with the last task, check if to split the snode
- if((!(se.getTransTime() < this.transThreshold))
- && (se.getSourceCNode().getTransTime() < se.getTransTime())) {
- // it's better to transfer the other obj with preSnode
- split = true;
- splitSNode(se, true);
- }
- } // if(!fe.getTarget().edges().hasNext())
-
- if(!split) {
- // delay the expanding and merging until we find all such 'new'
- // edges associated with a last task inside this ClassNode
- if(fe2ses.get(fe) == null) {
- fe2ses.put(fe, new Vector<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);
- }
- } // if(!split)
- } // if(fe.getSource() == fe.getTarget())
+ if(preSNode == null) {
+ preSNode = (ScheduleNode)se.getSource();
+ }
+
+ boolean split = false;
+ FEdge fe = se.getFEdge();
+ if(fe.getSource() == fe.getTarget()) {
+ // the associated start fe is a back edge
+ try {
+ // check the number of newly created objs
+ int repeat = (int)Math.ceil(se.getNewRate()*se.getProbability()/100);
+ int rate = 0;
+ /*if(repeat > 1) {
+ // more than one new objs, expand the new edge
+ for(int j = 1; j< repeat; j++ ) {
+ cloneSNodeList(se, true);
+ } // for(int j = 1; j< repeat; j++ )
+ se.setNewRate(1);
+ se.setProbability(100);
+ } // if(repeat > 1)*/
+ try {
+ // match the rates of obj creation and new obj consumption
+ rate = (int)Math.ceil(
+ se.getListExeTime()/calInExeTime(se.getSourceFState()));
+ } catch (Exception e) {
+ e.printStackTrace();
+ } // try-catch {}
+ repeat = (rate > repeat)?rate:repeat;
+ // expand the new edge
+ for(int j = 1; j< repeat; j++ ) {
+ cloneSNodeList(se, true);
+ } // for(int j = 1; j< repeat; j++ )
+ se.setNewRate(1);
+ se.setProbability(100);
+ /*for(int j = rate - 1; j > 0; j--) {
+ for(int k = repeat; k > 0; k--) {
+ cloneSNodeList(se, true);
+ } // for(int k = repeat; k > 0; k--)
+ } // for(int j = rate - 1; j > 0; j--)*/
+ } catch (Exception e) {
+ e.printStackTrace();
+ System.exit(-1);
+ } // try-catch{}
+ } else { // if(fe.getSource() == fe.getTarget())
+ // the associated start fe is not a back edge
+ // Note: if preSNode is not the same as se's source ScheduleNode
+ // handle any ScheduleEdges previously put into fe2ses whose source
+ // ScheduleNode is preSNode
+ boolean same = (preSNode == se.getSource());
+ if(!same) {
+ // check the topology sort, only process those after se.getSource()
+ if(preSNode.getFinishingTime() < se.getSource().getFinishingTime()) {
+ if(sn2fes.containsKey(preSNode)) {
+ Vector<FEdge> fes = sn2fes.remove(preSNode);
+ for(int j = 0; j < fes.size(); j++) {
+ FEdge tempfe = fes.elementAt(j);
+ Vector<ScheduleEdge> ses = fe2ses.get(tempfe);
+ boolean isflag = !(preSNode.edges().hasNext());
+ this.handleDescenSEs(ses, isflag);
+ ses = null;
+ fe2ses.remove(tempfe);
+ } // for(int j = 0; j < fes.size(); j++)
+ fes = null;
+ }
+ }
+ preSNode = (ScheduleNode)se.getSource();
+ } // if(!same)
+
+ if(fe.getTarget().edges().hasNext()) {
+ // not associated with the last task, check if to split the snode
+ if((!(se.getTransTime() < this.transThreshold))
+ && (se.getSourceCNode().getTransTime() < se.getTransTime())) {
+ // it's better to transfer the other obj with preSnode
+ split = true;
+ splitSNode(se, true);
+ }
+ } // if(!fe.getTarget().edges().hasNext())
+
+ if(!split) {
+ // delay the expanding and merging until we find all such 'new'
+ // edges associated with a last task inside this ClassNode
+ if(fe2ses.get(fe) == null) {
+ fe2ses.put(fe, new Vector<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);
+ }
+ } // if(!split)
+ } // if(fe.getSource() == fe.getTarget())
} // if(ScheduleEdge.NEWEDGE == se.getType())
} // for(i = scheduleEdges.size(); i > 0; i--)
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);
- boolean isflag = !(tempfe.getTarget().edges().hasNext());
- this.handleDescenSEs(ses, isflag);
- ses = null;
+ FEdge tempfe = (FEdge)it_keys.next();
+ Vector<ScheduleEdge> ses = fe2ses.get(tempfe);
+ boolean isflag = !(tempfe.getTarget().edges().hasNext());
+ this.handleDescenSEs(ses, isflag);
+ ses = null;
}
keys = null;
it_keys = null;
int rate = 0;
int repeat = (int)Math.ceil(se.getNewRate() * se.getProbability() / 100);
if(merge) {
- try {
- if(se.getListExeTime() == 0) {
- rate = repeat;
- } else {
- rate = (int)Math.ceil(
- (se.getTransTime()-calInExeTime(se.getSourceFState()))
- /se.getListExeTime());
- }
- if(rate < 0 ) {
- rate = 0;
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- if(0 == rate) {
- // clone the whole ScheduleNode lists starting with se's target
- for(int j = 1; j < repeat; j++ ) {
- cloneSNodeList(se, true);
- }
- se.setNewRate(1);
- se.setProbability(100);
- } else {
- repeat -= rate;
- if(repeat > 0) {
- // clone the whole ScheduleNode lists starting with se's target
- for(int j = 0; j < repeat; j++ ) {
- cloneSNodeList(se, true);
- }
- se.setNewRate(rate);
- se.setProbability(100);
- }
- }
- // merge the original ScheduleNode to the source ScheduleNode
- ((ScheduleNode)se.getSource()).mergeSEdge(se);
- scheduleNodes.remove(se.getTarget());
- scheduleEdges.remove(se);
- // As se has been changed into an internal edge inside a ScheduleNode,
- // change the source and target of se from original ScheduleNodes
- // into ClassNodes.
- if(se.getType() == ScheduleEdge.NEWEDGE) {
- se.setTarget(se.getTargetCNode());
- //se.setSource(se.getSourceCNode());
- //se.getTargetCNode().addEdge(se);
- se.getSourceCNode().addEdge(se);
- }
+ try {
+ if(se.getListExeTime() == 0) {
+ rate = repeat;
+ } else {
+ rate = (int)Math.ceil(
+ (se.getTransTime()-calInExeTime(se.getSourceFState()))
+ /se.getListExeTime());
+ }
+ if(rate < 0 ) {
+ rate = 0;
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ if(0 == rate) {
+ // clone the whole ScheduleNode lists starting with se's target
+ for(int j = 1; j < repeat; j++ ) {
+ cloneSNodeList(se, true);
+ }
+ se.setNewRate(1);
+ se.setProbability(100);
+ } else {
+ repeat -= rate;
+ if(repeat > 0) {
+ // clone the whole ScheduleNode lists starting with se's target
+ for(int j = 0; j < repeat; j++ ) {
+ cloneSNodeList(se, true);
+ }
+ se.setNewRate(rate);
+ se.setProbability(100);
+ }
+ }
+ // merge the original ScheduleNode to the source ScheduleNode
+ ((ScheduleNode)se.getSource()).mergeSEdge(se);
+ scheduleNodes.remove(se.getTarget());
+ scheduleEdges.remove(se);
+ // As se has been changed into an internal edge inside a ScheduleNode,
+ // change the source and target of se from original ScheduleNodes
+ // into ClassNodes.
+ if(se.getType() == ScheduleEdge.NEWEDGE) {
+ se.setTarget(se.getTargetCNode());
+ //se.setSource(se.getSourceCNode());
+ //se.getTargetCNode().addEdge(se);
+ se.getSourceCNode().addEdge(se);
+ }
} else {
- // clone the whole ScheduleNode lists starting with se's target
- for(int j = 1; j < repeat; j++ ) {
- cloneSNodeList(se, true);
- }
- se.setNewRate(1);
- se.setProbability(100);
+ // clone the whole ScheduleNode lists starting with se's target
+ for(int j = 1; j < repeat; j++ ) {
+ cloneSNodeList(se, true);
+ }
+ se.setNewRate(1);
+ se.setProbability(100);
}
} catch (Exception e) {
e.printStackTrace();
if(copyIE) {
Vector inedges = sEdge.getTarget().getInedgeVector();
for(i = 0; i < inedges.size(); i++) {
- ScheduleEdge tse = (ScheduleEdge)inedges.elementAt(i);
- ScheduleEdge se;
- switch(tse.getType()) {
- case ScheduleEdge.NEWEDGE: {
- se = new ScheduleEdge(csNode,"new",tse.getFstate(),tse.getType(),0);
- se.setProbability(100);
- se.setNewRate(1);
- break;
- }
-
- case ScheduleEdge.TRANSEDGE: {
- se = new ScheduleEdge(csNode,"transmit",tse.getFstate(),tse.getType(),0);
- se.setProbability(tse.getProbability());
- se.setNewRate(tse.getNewRate());
- break;
- }
-
- default: {
- throw new Exception("Error: not valid ScheduleEdge here");
- }
- }
- se.setSourceCNode(tse.getSourceCNode());
- se.setTargetCNode(cn2cn.get(tse.getTargetCNode()));
- se.setFEdge(tse.getFEdge());
- se.setTargetFState(tse.getTargetFState());
- se.setIsclone(true);
- tse.getSource().addEdge(se);
- scheduleEdges.add(se);
+ ScheduleEdge tse = (ScheduleEdge)inedges.elementAt(i);
+ ScheduleEdge se;
+ switch(tse.getType()) {
+ case ScheduleEdge.NEWEDGE: {
+ se = new ScheduleEdge(csNode,"new",tse.getFstate(),tse.getType(),0);
+ se.setProbability(100);
+ se.setNewRate(1);
+ break;
+ }
+
+ case ScheduleEdge.TRANSEDGE: {
+ se = new ScheduleEdge(csNode,"transmit",tse.getFstate(),tse.getType(),0);
+ se.setProbability(tse.getProbability());
+ se.setNewRate(tse.getNewRate());
+ break;
+ }
+
+ default: {
+ throw new Exception("Error: not valid ScheduleEdge here");
+ }
+ }
+ se.setSourceCNode(tse.getSourceCNode());
+ se.setTargetCNode(cn2cn.get(tse.getTargetCNode()));
+ se.setFEdge(tse.getFEdge());
+ se.setTargetFState(tse.getTargetFState());
+ se.setIsclone(true);
+ tse.getSource().addEdge(se);
+ scheduleEdges.add(se);
}
inedges = null;
} else {
// Clone all the external ScheduleEdges and the following ScheduleNodes
Vector edges = osNode.getEdgeVector();
for(i = 0; i < edges.size(); i++) {
- ScheduleEdge tse = (ScheduleEdge)edges.elementAt(i);
- ScheduleNode tSNode =
- (ScheduleNode)((ScheduleNode)tse.getTarget()).clone(tocn2cn, 0);
- scheduleNodes.add(tSNode);
- clone.add(tSNode);
- toClone.add((ScheduleNode)tse.getTarget());
- origins.addElement((ScheduleNode)tse.getTarget());
- sn2sn.put((ScheduleNode)tse.getTarget(), tSNode);
- qcn2cn.add(tocn2cn);
- ScheduleEdge se = null;
- switch(tse.getType()) {
- case ScheduleEdge.NEWEDGE: {
- se = new ScheduleEdge(tSNode,"new",tse.getFstate(),tse.getType(),0);
- break;
- }
-
- case ScheduleEdge.TRANSEDGE: {
- se = new ScheduleEdge(tSNode,"transmit",tse.getFstate(),tse.getType(),0);
- break;
- }
-
- default: {
- throw new Exception("Error: not valid ScheduleEdge here");
- }
- }
- se.setSourceCNode(cn2cn.get(tse.getSourceCNode()));
- se.setTargetCNode(tocn2cn.get(tse.getTargetCNode()));
- se.setFEdge(tse.getFEdge());
- se.setTargetFState(tse.getTargetFState());
- se.setProbability(tse.getProbability());
- se.setNewRate(tse.getNewRate());
- se.setIsclone(true);
- csNode.addEdge(se);
- scheduleEdges.add(se);
+ ScheduleEdge tse = (ScheduleEdge)edges.elementAt(i);
+ ScheduleNode tSNode =
+ (ScheduleNode)((ScheduleNode)tse.getTarget()).clone(tocn2cn, 0);
+ scheduleNodes.add(tSNode);
+ clone.add(tSNode);
+ toClone.add((ScheduleNode)tse.getTarget());
+ origins.addElement((ScheduleNode)tse.getTarget());
+ sn2sn.put((ScheduleNode)tse.getTarget(), tSNode);
+ qcn2cn.add(tocn2cn);
+ ScheduleEdge se = null;
+ switch(tse.getType()) {
+ case ScheduleEdge.NEWEDGE: {
+ se = new ScheduleEdge(tSNode,"new",tse.getFstate(),tse.getType(),0);
+ break;
+ }
+
+ case ScheduleEdge.TRANSEDGE: {
+ se = new ScheduleEdge(tSNode,"transmit",tse.getFstate(),tse.getType(),0);
+ break;
+ }
+
+ default: {
+ throw new Exception("Error: not valid ScheduleEdge here");
+ }
+ }
+ se.setSourceCNode(cn2cn.get(tse.getSourceCNode()));
+ se.setTargetCNode(tocn2cn.get(tse.getTargetCNode()));
+ se.setFEdge(tse.getFEdge());
+ se.setTargetFState(tse.getTargetFState());
+ se.setProbability(tse.getProbability());
+ se.setNewRate(tse.getNewRate());
+ se.setIsclone(true);
+ csNode.addEdge(se);
+ scheduleEdges.add(se);
}
tocn2cn = null;
edges = null;
// Now that there are associate ScheduleEdges, there may be
// multiple inedges of a ClassNode
if(inedges.size() > 1) {
- throw new Exception("Error: ClassNode's inedges more than one!");
+ throw new Exception("Error: ClassNode's inedges more than one!");
}
if(inedges.size() > 0) {
- ScheduleEdge sEdge = (ScheduleEdge)inedges.elementAt(0);
- cNode = (ClassNode)sEdge.getSource();
- exeTime += cNode.getFlagStates().elementAt(0).getExeTime();
+ ScheduleEdge sEdge = (ScheduleEdge)inedges.elementAt(0);
+ cNode = (ClassNode)sEdge.getSource();
+ exeTime += cNode.getFlagStates().elementAt(0).getExeTime();
} else {
- break;
+ break;
}
inedges = null;
}
FlagState tfs = toiterate.poll();
Iterator it_edges = tfs.edges();
while(it_edges.hasNext()) {
- FlagState temp = (FlagState)((FEdge)it_edges.next()).getTarget();
- if(!fStates.contains(temp)) {
- fStates.add(temp);
- toiterate.add(temp);
- sfss.removeElement(temp);
- }
+ FlagState temp = (FlagState)((FEdge)it_edges.next()).getTarget();
+ if(!fStates.contains(temp)) {
+ fStates.add(temp);
+ toiterate.add(temp);
+ sfss.removeElement(temp);
+ }
}
it_edges = null;
}
long ttime = tfs.getExeTime();
Iterator it_inedges = tfs.inedges();
while(it_inedges.hasNext()) {
- FEdge fEdge = (FEdge)it_inedges.next();
- FlagState temp = (FlagState)fEdge.getSource();
- long time = fEdge.getExeTime() + ttime;
- if(temp.getExeTime() > time) {
- temp.setExeTime(time);
- toiterate.add(temp);
- }
+ FEdge fEdge = (FEdge)it_inedges.next();
+ FlagState temp = (FlagState)fEdge.getSource();
+ long time = fEdge.getExeTime() + ttime;
+ if(temp.getExeTime() > time) {
+ temp.setExeTime(time);
+ toiterate.add(temp);
+ }
}
it_inedges = null;
}
rCNodes.addElement(sCNode);
if(it_isEdges != null) {
while(it_isEdges.hasNext()) {
- ScheduleEdge tse = (ScheduleEdge)it_isEdges.next();
- if(rCNodes.contains(tse.getSourceCNode())) {
- if(sCNode.equals(tse.getSourceCNode())) {
- if (!(tse.getSourceFState().equals(fs))
- && (sFStates.contains(tse.getSourceFState()))) {
- tse.setSource(cNode);
- tse.setSourceCNode(cNode);
- } else {
- continue;
- }
- }
- sNode.getScheduleEdges().addElement(tse);
- sNode.getClassNodes().addElement(tse.getTargetCNode());
- rCNodes.addElement(tse.getTargetCNode());
- oldSNode.getClassNodes().removeElement(tse.getTargetCNode());
- toremove.addElement(tse);
- }
+ ScheduleEdge tse = (ScheduleEdge)it_isEdges.next();
+ if(rCNodes.contains(tse.getSourceCNode())) {
+ if(sCNode.equals(tse.getSourceCNode())) {
+ if (!(tse.getSourceFState().equals(fs))
+ && (sFStates.contains(tse.getSourceFState()))) {
+ tse.setSource(cNode);
+ tse.setSourceCNode(cNode);
+ } else {
+ continue;
+ }
+ }
+ sNode.getScheduleEdges().addElement(tse);
+ sNode.getClassNodes().addElement(tse.getTargetCNode());
+ rCNodes.addElement(tse.getTargetCNode());
+ oldSNode.getClassNodes().removeElement(tse.getTargetCNode());
+ toremove.addElement(tse);
+ }
}
}
it_isEdges = null;
ScheduleEdge tse = (ScheduleEdge)it_sEdges.next();
if(!(tse.equals(se)) && !(tse.equals(sEdge))
&& (tse.getSourceCNode().equals(sCNode))) {
- if(!(tse.getSourceFState().equals(fs))
- && (sFStates.contains(tse.getSourceFState()))) {
- tse.setSource(sNode);
- tse.setSourceCNode(cNode);
- sNode.getEdgeVector().addElement(tse);
- toremove.add(tse);
- }
+ if(!(tse.getSourceFState().equals(fs))
+ && (sFStates.contains(tse.getSourceFState()))) {
+ tse.setSource(sNode);
+ tse.setSourceCNode(cNode);
+ sNode.getEdgeVector().addElement(tse);
+ toremove.add(tse);
+ }
}
}
it_sEdges = null;
try {
if(!copy) {
- //merge se into its source ScheduleNode
- sNode.setCid(((ScheduleNode)se.getSource()).getCid());
- ((ScheduleNode)se.getSource()).mergeSEdge(se);
- scheduleNodes.remove(se.getTarget());
- scheduleEdges.removeElement(se);
- // As se has been changed into an internal edge inside a ScheduleNode,
- // change the source and target of se from original ScheduleNodes
- // into ClassNodes.
- if(se.getType() == ScheduleEdge.NEWEDGE) {
- se.setTarget(se.getTargetCNode());
- //se.setSource(se.getSourceCNode());
- //se.getTargetCNode().addEdge(se);
- se.getSourceCNode().addEdge(se);
- }
+ //merge se into its source ScheduleNode
+ sNode.setCid(((ScheduleNode)se.getSource()).getCid());
+ ((ScheduleNode)se.getSource()).mergeSEdge(se);
+ scheduleNodes.remove(se.getTarget());
+ scheduleEdges.removeElement(se);
+ // As se has been changed into an internal edge inside a ScheduleNode,
+ // change the source and target of se from original ScheduleNodes
+ // into ClassNodes.
+ if(se.getType() == ScheduleEdge.NEWEDGE) {
+ se.setTarget(se.getTargetCNode());
+ //se.setSource(se.getSourceCNode());
+ //se.getTargetCNode().addEdge(se);
+ se.getSourceCNode().addEdge(se);
+ }
} else {
- sNode.setCid(ScheduleNode.colorID++);
- handleScheduleEdge(se, true);
+ sNode.setCid(ScheduleNode.colorID++);
+ handleScheduleEdge(se, true);
}
} catch (Exception e) {
e.printStackTrace();
this.scheduleGraphs.addElement(this.scheduleNodes);
int gid = 1;
if(this.state.PRINTSCHEDULING) {
- String path = this.state.outputdir + "scheduling_" + gid + ".dot";
- SchedulingUtil.printScheduleGraph(path, this.scheduleNodes);
+ String path = this.state.outputdir + "scheduling_" + gid + ".dot";
+ SchedulingUtil.printScheduleGraph(path, this.scheduleNodes);
}
return false;
} else {
boolean isBig = Math.pow(this.coreNum, reduceNum) > 1000;
Random rand = new Random();
if(isBig && state.BAMBOOCOMPILETIME) {
- CombinationUtil.RootsGenerator rGen =
- CombinationUtil.allocateRootsGenerator(sNodeVecs,
- this.coreNum);
- while((gid <= this.scheduleThreshold) && (rGen.nextGen())) {
- // first get the chosen rootNodes
- Vector<Vector<ScheduleNode>> rootNodes = rGen.getRootNodes();
- Vector<Vector<ScheduleNode>> nodes2combine = rGen.getNode2Combine();
-
- CombinationUtil.CombineGenerator cGen =
- CombinationUtil.allocateCombineGenerator(rootNodes,
- nodes2combine);
- while((gid <= this.scheduleThreshold) && (cGen.randomGenE())) {
- boolean implement = true;
- /*if(isBig) {
- implement = Math.abs(rand.nextInt()) % 100 > generateThreshold;
- }*/
- if(implement) {
- Vector<Vector<CombinationUtil.Combine>> combine = cGen.getCombine();
- Vector<ScheduleNode> sNodes =
- SchedulingUtil.generateScheduleGraph(this.state,
- this.scheduleNodes,
- this.scheduleEdges,
- rootNodes,
- combine,
- gid++);
- this.scheduleGraphs.add(sNodes);
- sNodes = null;
- combine = null;
- } else if(Math.abs(rand.nextInt()) % 100 > skipThreshold) {
- break;
- }
- }
- cGen.clear();
- rootNodes = null;
- nodes2combine = null;
- }
- rGen.clear();
- sNodeVecs = null;
+ CombinationUtil.RootsGenerator rGen =
+ CombinationUtil.allocateRootsGenerator(sNodeVecs,
+ this.coreNum);
+ while((gid <= this.scheduleThreshold) && (rGen.nextGen())) {
+ // first get the chosen rootNodes
+ Vector<Vector<ScheduleNode>> rootNodes = rGen.getRootNodes();
+ Vector<Vector<ScheduleNode>> nodes2combine = rGen.getNode2Combine();
+
+ CombinationUtil.CombineGenerator cGen =
+ CombinationUtil.allocateCombineGenerator(rootNodes,
+ nodes2combine);
+ while((gid <= this.scheduleThreshold) && (cGen.randomGenE())) {
+ boolean implement = true;
+ /*if(isBig) {
+ implement = Math.abs(rand.nextInt()) % 100 > generateThreshold;
+ }*/
+ if(implement) {
+ Vector<Vector<CombinationUtil.Combine>> combine = cGen.getCombine();
+ Vector<ScheduleNode> sNodes =
+ SchedulingUtil.generateScheduleGraph(this.state,
+ this.scheduleNodes,
+ this.scheduleEdges,
+ rootNodes,
+ combine,
+ gid++);
+ this.scheduleGraphs.add(sNodes);
+ sNodes = null;
+ combine = null;
+ } else if(Math.abs(rand.nextInt()) % 100 > skipThreshold) {
+ break;
+ }
+ }
+ cGen.clear();
+ rootNodes = null;
+ nodes2combine = null;
+ }
+ rGen.clear();
+ sNodeVecs = null;
} else if (false) {
- CombinationUtil.RandomGenerator rGen =
- CombinationUtil.allocateRandomGenerator(sNodeVecs,
- this.coreNum);
- // random genenration
- while((gid <= this.scheduleThreshold) && (rGen.nextGen())) {
- Vector<Vector<ScheduleNode>> mapping = rGen.getMapping();
- boolean implement = true;
- if(isBig) {
- implement = Math.abs(rand.nextInt()) % 100 > generateThreshold;
- }
- if(implement) {
- Vector<ScheduleNode> sNodes =
- SchedulingUtil.generateScheduleGraph(this.state,
- this.scheduleNodes,
- this.scheduleEdges,
- mapping,
- gid++);
- this.scheduleGraphs.add(sNodes);
- sNodes = null;
- }
- mapping = null;
- }
- rGen.clear();
- sNodeVecs = null;
+ CombinationUtil.RandomGenerator rGen =
+ CombinationUtil.allocateRandomGenerator(sNodeVecs,
+ this.coreNum);
+ // random genenration
+ while((gid <= this.scheduleThreshold) && (rGen.nextGen())) {
+ Vector<Vector<ScheduleNode>> mapping = rGen.getMapping();
+ boolean implement = true;
+ if(isBig) {
+ implement = Math.abs(rand.nextInt()) % 100 > generateThreshold;
+ }
+ if(implement) {
+ Vector<ScheduleNode> sNodes =
+ SchedulingUtil.generateScheduleGraph(this.state,
+ this.scheduleNodes,
+ this.scheduleEdges,
+ mapping,
+ gid++);
+ this.scheduleGraphs.add(sNodes);
+ sNodes = null;
+ }
+ mapping = null;
+ }
+ rGen.clear();
+ sNodeVecs = null;
} else {
- CombinationUtil.RootsGenerator rGen =
- CombinationUtil.allocateRootsGenerator(sNodeVecs,
- this.coreNum);
- while((!isBig || (gid <= this.scheduleThreshold)) && (rGen.nextGen())) {
- // first get the chosen rootNodes
- Vector<Vector<ScheduleNode>> rootNodes = rGen.getRootNodes();
- Vector<Vector<ScheduleNode>> nodes2combine = rGen.getNode2Combine();
-
- CombinationUtil.CombineGenerator cGen =
- CombinationUtil.allocateCombineGenerator(rootNodes,
- nodes2combine);
- while((!isBig || (gid <= this.scheduleThreshold)) && (cGen.nextGen())) {
- boolean implement = true;
- if(isBig) {
- implement = Math.abs(rand.nextInt()) % 100 > generateThreshold;
- }
- if(implement) {
- Vector<Vector<CombinationUtil.Combine>> combine = cGen.getCombine();
- Vector<ScheduleNode> sNodes =
- SchedulingUtil.generateScheduleGraph(this.state,
- this.scheduleNodes,
- this.scheduleEdges,
- rootNodes,
- combine,
- gid++);
- this.scheduleGraphs.add(sNodes);
- sNodes = null;
- combine = null;
- } else if(Math.abs(rand.nextInt()) % 100 > skipThreshold) {
- break;
- }
- }
- cGen.clear();
- rootNodes = null;
- nodes2combine = null;
- }
- rGen.clear();
- sNodeVecs = null;
+ CombinationUtil.RootsGenerator rGen =
+ CombinationUtil.allocateRootsGenerator(sNodeVecs,
+ this.coreNum);
+ while((!isBig || (gid <= this.scheduleThreshold)) && (rGen.nextGen())) {
+ // first get the chosen rootNodes
+ Vector<Vector<ScheduleNode>> rootNodes = rGen.getRootNodes();
+ Vector<Vector<ScheduleNode>> nodes2combine = rGen.getNode2Combine();
+
+ CombinationUtil.CombineGenerator cGen =
+ CombinationUtil.allocateCombineGenerator(rootNodes,
+ nodes2combine);
+ while((!isBig || (gid <= this.scheduleThreshold)) && (cGen.nextGen())) {
+ boolean implement = true;
+ if(isBig) {
+ implement = Math.abs(rand.nextInt()) % 100 > generateThreshold;
+ }
+ if(implement) {
+ Vector<Vector<CombinationUtil.Combine>> combine = cGen.getCombine();
+ Vector<ScheduleNode> sNodes =
+ SchedulingUtil.generateScheduleGraph(this.state,
+ this.scheduleNodes,
+ this.scheduleEdges,
+ rootNodes,
+ combine,
+ gid++);
+ this.scheduleGraphs.add(sNodes);
+ sNodes = null;
+ combine = null;
+ } else if(Math.abs(rand.nextInt()) % 100 > skipThreshold) {
+ break;
+ }
+ }
+ cGen.clear();
+ rootNodes = null;
+ nodes2combine = null;
+ }
+ rGen.clear();
+ sNodeVecs = null;
}
return isBig;
}
this.m_probability = new double[this.m_numofexits];
this.m_newobjinfo = new Vector<Hashtable<String, Integer>>();
for(int i = 0; i < this.m_numofexits; i++) {
- this.m_newobjinfo.add(null);
+ this.m_newobjinfo.add(null);
}
this.m_byObj = -1;
}
if (o instanceof ScheduleEdge) {
ScheduleEdge e=(ScheduleEdge)o;
if(e.gid == this.gid) {
- if(e.uid != this.uid) {
- return false;
- }
+ if(e.uid != this.uid) {
+ return false;
+ }
}
if ((e.label.equals(label))&&
(e.target.equals(target))&&
(e.type == type) &&
(e.transTime == transTime) &&
(e.listExeTime == listExeTime))
- if(e.targetFState != null) {
- if(!e.targetFState.equals(targetFState)) {
- return false;
- }
- } else if(this.targetFState != null) {
- return false;
- }
+ if(e.targetFState != null) {
+ if(!e.targetFState.equals(targetFState)) {
+ return false;
+ }
+ } else if(this.targetFState != null) {
+ return false;
+ }
if(e.fedge != null) {
- return e.fedge.equals(fedge);
+ return e.fedge.equals(fedge);
} else if(this.fedge == null) {
- return true;
+ return true;
}
}
return false;
Iterator it_edges = this.getTarget().edges();
long temp = 0;
if(it_edges.hasNext()) {
- temp = ((ScheduleEdge)it_edges.next()).getListExeTime();
+ temp = ((ScheduleEdge)it_edges.next()).getListExeTime();
}
while(it_edges.hasNext()) {
- long tetime = ((ScheduleEdge)it_edges.next()).getListExeTime();
- if(temp < tetime) {
- temp = tetime;
- }
+ long tetime = ((ScheduleEdge)it_edges.next()).getListExeTime();
+ if(temp < tetime) {
+ temp = tetime;
+ }
}
listExeTime += temp;
}
// insert tomerge in accent order
int j = mergedcids.size() - 1;
for(; j > 0; j--) {
- int tmp = mergedcids.elementAt(j-1);
- if(tmp > tomerge) {
- mergedcids.setElementAt(tmp, j);
- } else {
- break;
- }
+ int tmp = mergedcids.elementAt(j-1);
+ if(tmp > tomerge) {
+ mergedcids.setElementAt(tmp, j);
+ } else {
+ break;
+ }
}
mergedcids.setElementAt(tomerge, j);
}
public long getExeTime() {
if(this.executionTime == -1) {
try {
- calExeTime();
+ calExeTime();
} catch (Exception e) {
- e.printStackTrace();
+ e.printStackTrace();
}
}
return this.executionTime;
if (o instanceof ScheduleNode) {
ScheduleNode fs=(ScheduleNode)o;
if(fs.gid == this.gid) {
- if(fs.uid != this.uid) {
- return false;
- }
- if(fs.cid != this.cid) {
- return false;
- }
+ if(fs.uid != this.uid) {
+ return false;
+ }
+ if(fs.cid != this.cid) {
+ return false;
+ }
}
if ((fs.executionTime != this.executionTime)) {
- return false;
+ return false;
}
if(fs.classNodes != null) {
- if(!fs.classNodes.equals(classNodes)) {
- return false;
- }
+ if(!fs.classNodes.equals(classNodes)) {
+ return false;
+ }
} else if(classNodes != null) {
- return false;
+ return false;
}
return true;
}
ScheduleEdge se = null;
switch(temp.getType()) {
case ScheduleEdge.NEWEDGE: {
- se = new ScheduleEdge(o,
- "new",
- temp.getFstate(),
- ScheduleEdge.NEWEDGE,
- gid);
- se.setProbability(temp.getProbability());
- se.setNewRate(temp.getNewRate());
- break;
+ se = new ScheduleEdge(o,
+ "new",
+ temp.getFstate(),
+ ScheduleEdge.NEWEDGE,
+ gid);
+ se.setProbability(temp.getProbability());
+ se.setNewRate(temp.getNewRate());
+ break;
}
case ScheduleEdge.TRANSEDGE: {
- se = new ScheduleEdge(o,
- "transmit",
- temp.getFstate(),
- ScheduleEdge.TRANSEDGE,
- gid);
- se.setProbability(temp.getProbability());
- se.setNewRate(temp.getNewRate());
- break;
+ se = new ScheduleEdge(o,
+ "transmit",
+ temp.getFstate(),
+ ScheduleEdge.TRANSEDGE,
+ gid);
+ se.setProbability(temp.getProbability());
+ se.setNewRate(temp.getNewRate());
+ break;
}
}
se.setSourceCNode(cn2cn.get(temp.getSourceCNode()));
scheduleEdges = targetSEdges;
} else {
if(targetCNodes.size() != 0) {
- classNodes.addAll(targetCNodes);
+ classNodes.addAll(targetCNodes);
}
if(targetSEdges.size() != 0) {
- scheduleEdges.addAll(targetSEdges);
+ scheduleEdges.addAll(targetSEdges);
}
}
targetCNodes = null;
Queue<FlagState> toiterate = new LinkedList<FlagState>();
toiterate.add(sfs);
while(!toiterate.isEmpty()) {
- FlagState tmpfs = toiterate.poll();
- long ttime = tmpfs.getExeTime();
- Iterator it_inedges = tmpfs.inedges();
- while(it_inedges.hasNext()) {
- FEdge fEdge = (FEdge)it_inedges.next();
- FlagState temp = (FlagState)fEdge.getSource();
- long time = fEdge.getExeTime() + ttime;
- if(temp.getExeTime() > time) {
- temp.setExeTime(time);
- toiterate.add(temp);
- }
- }
- it_inedges = null;
+ FlagState tmpfs = toiterate.poll();
+ long ttime = tmpfs.getExeTime();
+ Iterator it_inedges = tmpfs.inedges();
+ while(it_inedges.hasNext()) {
+ FEdge fEdge = (FEdge)it_inedges.next();
+ FlagState temp = (FlagState)fEdge.getSource();
+ long time = fEdge.getExeTime() + ttime;
+ if(temp.getExeTime() > time) {
+ temp.setExeTime(time);
+ toiterate.add(temp);
+ }
+ }
+ it_inedges = null;
}
toiterate = null;
// redirct internal ScheduleEdge from tcn to scn
for(int i = 0; i < targetSEdges.size(); ++i) {
- ScheduleEdge tmpse = targetSEdges.elementAt(i);
- if(tmpse.getSourceCNode().equals(tcn)) {
- tmpse.setSourceCNode(scn);
- }
+ ScheduleEdge tmpse = targetSEdges.elementAt(i);
+ if(tmpse.getSourceCNode().equals(tcn)) {
+ tmpse.setSourceCNode(scn);
+ }
}
// redirect external ScheduleEdges to this ScheduleNode
// and scn if it is originally from tcn
Iterator it_edges = sn.edges();
while(it_edges.hasNext()) {
- ScheduleEdge tse = (ScheduleEdge)it_edges.next();
- tse.setSource(this);
- if(tse.getSourceCNode().equals(tcn)) {
- tse.setSourceCNode(scn);
- }
- this.edges.addElement(tse);
+ ScheduleEdge tse = (ScheduleEdge)it_edges.next();
+ tse.setSource(this);
+ if(tse.getSourceCNode().equals(tcn)) {
+ tse.setSourceCNode(scn);
+ }
+ this.edges.addElement(tse);
}
it_edges = null;
// As all tasks inside one ScheduleNode are executed sequentially,
// simply add the execution time of all the ClassNodes inside one ScheduleNode.
if(this.executionTime == -1) {
- throw new Exception("Error: ScheduleNode without initiate execution time when analysising.");
+ throw new Exception("Error: ScheduleNode without initiate execution time when analysising.");
}
if(this.executionTime < sn.getExeTime()) {
- this.executionTime = sn.getExeTime();
+ this.executionTime = sn.getExeTime();
}
} else if(ScheduleEdge.NEWEDGE == se.getType()) {
targetSEdges = null;
this.removeEdge(se);
Iterator it_edges = sn.edges();
while(it_edges.hasNext()) {
- ScheduleEdge tse = (ScheduleEdge)it_edges.next();
- tse.setSource(this);
- this.edges.addElement(tse);
+ ScheduleEdge tse = (ScheduleEdge)it_edges.next();
+ tse.setSource(this);
+ this.edges.addElement(tse);
}
it_edges = null;
// As all tasks inside one ScheduleNode are executed sequentially,
// simply add the execution time of all the ClassNodes inside one ScheduleNode.
if(this.executionTime == -1) {
- this.executionTime = 0;
+ this.executionTime = 0;
}
this.executionTime += ((ScheduleNode)se.getTarget()).getExeTime();
}
scheduleEdges = targetSEdges;
} else {
if(targetCNodes.size() != 0) {
- classNodes.addAll(targetCNodes);
+ classNodes.addAll(targetCNodes);
}
if(targetSEdges.size() != 0) {
- scheduleEdges.addAll(targetSEdges);
+ scheduleEdges.addAll(targetSEdges);
}
}
targetCNodes = null;
Vector<ScheduleEdge> toremove = new Vector<ScheduleEdge>();
if(it_innersEdges != null) {
while(it_innersEdges.hasNext()) {
- ScheduleEdge tse = (ScheduleEdge)it_innersEdges.next();
- if((cd.equals(tse.getSourceCNode())) || (cd.equals(tse.getTargetCNode()))) {
- // related edge
- toremove.addElement(tse);
- }
+ ScheduleEdge tse = (ScheduleEdge)it_innersEdges.next();
+ if((cd.equals(tse.getSourceCNode())) || (cd.equals(tse.getTargetCNode()))) {
+ // related edge
+ toremove.addElement(tse);
+ }
}
}
it_innersEdges = null;
for(int i = 0; i < toremove.size(); i++) {
ScheduleEdge tse = toremove.elementAt(i);
if(cd.equals(tse.getSourceCNode())) {
- // outedge
- tse.setTarget(this);
- sNode.addEdge(tse);
+ // outedge
+ tse.setTarget(this);
+ sNode.addEdge(tse);
} else if(cd.equals(tse.getTargetCNode())) {
- // inedge
- tse.setTarget(sNode);
- this.addEdge(tse);
+ // inedge
+ tse.setTarget(sNode);
+ this.addEdge(tse);
}
}
toremove.clear();
while(it_exsEdges.hasNext()) {
ScheduleEdge tse = (ScheduleEdge)it_exsEdges.next();
if(tse.getSourceCNode().equals(cd)) {
- toremove.add(tse);
- //this.removeEdge(tse);
- //sNode.addEdge(tse);
- tse.setSource(sNode);
- sNode.edges.addElement(tse);
+ toremove.add(tse);
+ //this.removeEdge(tse);
+ //sNode.addEdge(tse);
+ tse.setSource(sNode);
+ sNode.edges.addElement(tse);
}
}
this.edges.removeAll(toremove);
while(it_insEdges.hasNext()) {
ScheduleEdge tse = (ScheduleEdge)it_insEdges.next();
if(tse.getTargetCNode().equals(cd)) {
- toremove.add(tse);
- tse.setTarget(sNode);
- sNode.inedges.addElement(tse);
+ toremove.add(tse);
+ tse.setTarget(sNode);
+ sNode.inedges.addElement(tse);
}
}
it_insEdges = null;
Iterator<FlagState> it_fStates = this.taskanalysis.getFlagStates(cd).iterator();
while(it_fStates.hasNext()) {
- FlagState fs = it_fStates.next();
- if(!this.fstates.contains(fs)) {
- this.fstates.addElement(fs);
- }
- Iterator<FEdge> it_fe = (Iterator<FEdge>)fs.edges();
- while(it_fe.hasNext()) {
- FEdge next = it_fe.next();
- if(!this.fedges.contains(next)) {
- this.fedges.addElement(next);
- }
- }
+ FlagState fs = it_fStates.next();
+ if(!this.fstates.contains(fs)) {
+ this.fstates.addElement(fs);
+ }
+ Iterator<FEdge> it_fe = (Iterator<FEdge>)fs.edges();
+ while(it_fe.hasNext()) {
+ FEdge next = it_fe.next();
+ if(!this.fedges.contains(next)) {
+ this.fedges.addElement(next);
+ }
+ }
}
}
}
Vector<Schedule> scheduling =
(Vector<Schedule>)it_scheduling.next();
if(!state.BAMBOOCOMPILETIME) {
- System.out.println("Scheduling index:" + scheduling.elementAt(0).getGid());
+ System.out.println("Scheduling index:" + scheduling.elementAt(0).getGid());
}
this.setScheduling(scheduling);
Vector<SimExecutionNode> simexegraph = new Vector<SimExecutionNode>();
Vector<CheckPoint> checkpoints = new Vector<CheckPoint>();
long tmpTime = process(checkpoints, simexegraph);
if(tmpTime < processTime) {
- selectedScheduling.clear();
- selectedScheduling.add(index);
- selectedSimExeGraphs.clear();
- selectedSimExeGraphs.add(simexegraph.elementAt(0));
- processTime = tmpTime;
+ selectedScheduling.clear();
+ selectedScheduling.add(index);
+ selectedSimExeGraphs.clear();
+ selectedSimExeGraphs.add(simexegraph.elementAt(0));
+ processTime = tmpTime;
} else if(tmpTime == processTime) {
- if(!selectedScheduling.contains(index)) {
- selectedScheduling.add(index);
- selectedSimExeGraphs.add(simexegraph.elementAt(0));
- }
+ if(!selectedScheduling.contains(index)) {
+ selectedScheduling.add(index);
+ selectedSimExeGraphs.add(simexegraph.elementAt(0));
+ }
}
scheduling = null;
checkpoints.clear();
if(!state.BAMBOOCOMPILETIME) {
System.out.print("Selected schedulings with least exectution time " + processTime + ": \n\t");
for(int i = 0; i < selectedScheduling.size(); i++) {
- int gid = schedulings.elementAt(selectedScheduling.elementAt(i)).elementAt(0).getGid();
- System.out.print(gid + ", ");
+ int gid = schedulings.elementAt(selectedScheduling.elementAt(i)).elementAt(0).getGid();
+ System.out.print(gid + ", ");
}
System.out.println();
}
}
if(this.cores != null) {
for(int i = 0; i < this.coreNum; i++) {
- CoreSimulator core = this.cores.elementAt(i);
- core.reset();
- core.setRSchedule(FIFORSchedule.getFIFORSchedule());
+ CoreSimulator core = this.cores.elementAt(i);
+ core.reset();
+ core.setRSchedule(FIFORSchedule.getFIFORSchedule());
}
} else {
this.cores = new Vector<CoreSimulator>(this.coreNum);
for(int i = 0; i < this.coreNum; i++) {
- this.cores.add(new CoreSimulator(FIFORSchedule.getFIFORSchedule(), i));
+ this.cores.add(new CoreSimulator(FIFORSchedule.getFIFORSchedule(), i));
}
}
CoreSimulator cs = this.cores.elementAt(i);
TaskSimulator task = cs.process();
if(task != null) {
- this.tasks.add(task);
+ this.tasks.add(task);
}
lastseNodes[i] = null;
}
task);
cp.addAction(action);
if(!(task instanceof TransTaskSimulator)) {
- cp.removeSpareCore(coreid);
- SimExecutionNode seNode = new SimExecutionNode(coreid, this.processTime);
- seNode.setSpareCores(cp.getSpareCores());
- senode2action.put(seNode, action);
- action2exetime.put(action, (long)-1);
- lastseNodes[coreid] = seNode;
+ cp.removeSpareCore(coreid);
+ SimExecutionNode seNode = new SimExecutionNode(coreid, this.processTime);
+ seNode.setSpareCores(cp.getSpareCores());
+ senode2action.put(seNode, action);
+ action2exetime.put(action, (long)-1);
+ lastseNodes[coreid] = seNode;
}
}
checkpoints.add(cp);
while(true) {
// if no more tasks on each core, simulation finish
if(this.tasks.size() == 0) {
- break;
+ break;
}
// for each task in todo queue, decide the execution path of this time
long finishTime = Long.MAX_VALUE;
Vector<TaskSimulator> finishTasks = new Vector<TaskSimulator>();
for(i = 0; i < this.tasks.size(); i++) {
- TaskSimulator task = this.tasks.elementAt(i);
- task.process();
- long tempTime = task.getCurrentRun().getFinishTime();
- if(tempTime < finishTime) {
- finishTime = tempTime;
- finishTasks.clear();
- finishTasks.add(task);
- } else if (tempTime == finishTime) {
- finishTasks.add(task);
- }
+ TaskSimulator task = this.tasks.elementAt(i);
+ task.process();
+ long tempTime = task.getCurrentRun().getFinishTime();
+ if(tempTime < finishTime) {
+ finishTime = tempTime;
+ finishTasks.clear();
+ finishTasks.add(task);
+ } else if (tempTime == finishTime) {
+ finishTasks.add(task);
+ }
}
// advance to next finish point
cp = new CheckPoint(this.processTime,
this.coreNum);
for(i = 0; i < this.tasks.size(); i++) {
- TaskSimulator task = this.tasks.elementAt(i);
- if(!finishTasks.contains(task)) {
- task.getCs().updateTask(finishTime);
- if(!(task instanceof TransTaskSimulator)) {
- cp.removeSpareCore(task.getCs().getCoreNum());
- }
- }
+ TaskSimulator task = this.tasks.elementAt(i);
+ if(!finishTasks.contains(task)) {
+ task.getCs().updateTask(finishTime);
+ if(!(task instanceof TransTaskSimulator)) {
+ cp.removeSpareCore(task.getCs().getCoreNum());
+ }
+ }
}
Action action = null;
for(i = 0; i < finishTasks.size(); i++) {
- TaskSimulator task = finishTasks.elementAt(i);
- this.tasks.removeElement(task);
- if(task instanceof TransTaskSimulator) {
- // handle TransTaskSimulator task's completion
- finishTransTaskSimulator(task,
- cp,
- senode2action,
- lastseNodes,
- action2exetime,
- tttask2senode,
- obj2transtime);
- } else {
- CoreSimulator cs = task.getCs();
- Vector<TransTaskSimulator> tttasks = new Vector<TransTaskSimulator>();
-
- Vector<ObjectSimulator> transObjs = null;
- if(task.getCurrentRun().getExetype() == 0) {
- // normal execution of a task
- transObjs = finishTaskNormal(task,
- cp,
- tttasks,
- senode2action,
- lastseNodes,
- action2exetime);
- } else if (task.getCurrentRun().getExetype() == 1) {
- // task abort
- finishTaskAbnormal(cs,
- cp,
- senode2action,
- lastseNodes,
- action2exetime,
- Action.TASKABORT);
- } else if (task.getCurrentRun().getExetype() == 2) {
- // task remove
- finishTaskAbnormal(cs,
- cp,
- senode2action,
- lastseNodes,
- action2exetime,
- Action.TASKREMOVE);
- }
-
- // Choose a new task for this core
- generateNewTask(cs,
- cp,
- transObjs,
- tttasks,
- senode2action,
- lastseNodes,
- action2exetime,
- tttask2senode,
- obj2transtime,
- obj2lastseedge);
- tttasks.clear();
- tttasks = null;
- transObjs = null;
- } // end of if(task instanceof TransTaskSimulator) else
+ TaskSimulator task = finishTasks.elementAt(i);
+ this.tasks.removeElement(task);
+ if(task instanceof TransTaskSimulator) {
+ // handle TransTaskSimulator task's completion
+ finishTransTaskSimulator(task,
+ cp,
+ senode2action,
+ lastseNodes,
+ action2exetime,
+ tttask2senode,
+ obj2transtime);
+ } else {
+ CoreSimulator cs = task.getCs();
+ Vector<TransTaskSimulator> tttasks = new Vector<TransTaskSimulator>();
+
+ Vector<ObjectSimulator> transObjs = null;
+ if(task.getCurrentRun().getExetype() == 0) {
+ // normal execution of a task
+ transObjs = finishTaskNormal(task,
+ cp,
+ tttasks,
+ senode2action,
+ lastseNodes,
+ action2exetime);
+ } else if (task.getCurrentRun().getExetype() == 1) {
+ // task abort
+ finishTaskAbnormal(cs,
+ cp,
+ senode2action,
+ lastseNodes,
+ action2exetime,
+ Action.TASKABORT);
+ } else if (task.getCurrentRun().getExetype() == 2) {
+ // task remove
+ finishTaskAbnormal(cs,
+ cp,
+ senode2action,
+ lastseNodes,
+ action2exetime,
+ Action.TASKREMOVE);
+ }
+
+ // Choose a new task for this core
+ generateNewTask(cs,
+ cp,
+ transObjs,
+ tttasks,
+ senode2action,
+ lastseNodes,
+ action2exetime,
+ tttask2senode,
+ obj2transtime,
+ obj2lastseedge);
+ tttasks.clear();
+ tttasks = null;
+ transObjs = null;
+ } // end of if(task instanceof TransTaskSimulator) else
}
checkpoints.add(cp);
finishTasks = null;
SimExecutionNode lastsenode = lastseNodes[j];
// create edges between previous senode on this core to this node
if(lastsenode != null) {
- Action tmpaction = senode2action.get(lastsenode);
- long weight = tmpaction != null?action2exetime.get(tmpaction):0; // TODO ????
- SimExecutionEdge seEdge = new SimExecutionEdge(seNode,
- lastsenode.getCoreNum(),
- tmpaction != null?tmpaction.getTd():null,
- weight,
- tmpaction != null?tmpaction.getTaskParams():null);
- lastsenode.addEdge(seEdge);
-
- // setup data dependencies for the task
- Vector<Integer> taskparams = seEdge.getTaskparams();
- if(taskparams != null) {
- for(int k = 0; k < taskparams.size(); k++) {
- Integer tparam = taskparams.elementAt(k);
- SimExecutionEdge lastedge = obj2lastseedge.get(tparam);
- if(lastedge != null) {
- if(lastedge.getCoreNum() != seEdge.getCoreNum()) {
- // the obj is transferred from another core
- // create an seEdge for this transfer
- long transweight = obj2transtime.get(tparam);
- SimExecutionEdge transseEdge = new SimExecutionEdge((SimExecutionNode)seEdge.getSource(),
- lastedge.getCoreNum(),
- null, // TODO: not sure if this is enough
- transweight,
- null);
- if(((SimExecutionNode)seEdge.getSource()).getTimepoint() <
- ((SimExecutionNode)lastedge.getTarget()).getTimepoint()) {
- System.err.println("ScheduleSimulator:393");
- System.exit(-1);
- }
- lastedge.getTarget().addEdge(transseEdge);
- transseEdge.addPredicate(lastedge);
- seEdge.addPredicate(transseEdge);
- } else {
- seEdge.addPredicate(lastedge);
- }
- }
- // update the last edge associated to the parameter obj
- obj2lastseedge.put(tparam, seEdge);
- }
- }
- taskparams = null;
+ Action tmpaction = senode2action.get(lastsenode);
+ long weight = tmpaction != null?action2exetime.get(tmpaction):0; // TODO ????
+ SimExecutionEdge seEdge = new SimExecutionEdge(seNode,
+ lastsenode.getCoreNum(),
+ tmpaction != null?tmpaction.getTd():null,
+ weight,
+ tmpaction != null?tmpaction.getTaskParams():null);
+ lastsenode.addEdge(seEdge);
+
+ // setup data dependencies for the task
+ Vector<Integer> taskparams = seEdge.getTaskparams();
+ if(taskparams != null) {
+ for(int k = 0; k < taskparams.size(); k++) {
+ Integer tparam = taskparams.elementAt(k);
+ SimExecutionEdge lastedge = obj2lastseedge.get(tparam);
+ if(lastedge != null) {
+ if(lastedge.getCoreNum() != seEdge.getCoreNum()) {
+ // the obj is transferred from another core
+ // create an seEdge for this transfer
+ long transweight = obj2transtime.get(tparam);
+ SimExecutionEdge transseEdge = new SimExecutionEdge((SimExecutionNode)seEdge.getSource(),
+ lastedge.getCoreNum(),
+ null, // TODO: not sure if this is enough
+ transweight,
+ null);
+ if(((SimExecutionNode)seEdge.getSource()).getTimepoint() <
+ ((SimExecutionNode)lastedge.getTarget()).getTimepoint()) {
+ System.err.println("ScheduleSimulator:393");
+ System.exit(-1);
+ }
+ lastedge.getTarget().addEdge(transseEdge);
+ transseEdge.addPredicate(lastedge);
+ seEdge.addPredicate(transseEdge);
+ } else {
+ seEdge.addPredicate(lastedge);
+ }
+ }
+ // update the last edge associated to the parameter obj
+ obj2lastseedge.put(tparam, seEdge);
+ }
+ }
+ taskparams = null;
}
lastseNodes[j] = null;
}
System.out.println("\tTotal execution time is: " + this.processTime);
System.out.println("\tUtility of cores: ");
for(int j = 0; j < this.cores.size(); j++) {
- System.out.println("\t\tcore" + j + ": " + getUtility(j) + "%");
+ System.out.println("\t\tcore" + j + ": " + getUtility(j) + "%");
}
}
if(this.cores.elementAt(targetCoreNum).getRtask() == null) {
TaskSimulator newTask = this.cores.elementAt(targetCoreNum).process();
if(newTask != null) {
- this.tasks.add(newTask);
- // add a TASKSTART action into this checkpoint
- action = new Action(targetCoreNum,
- Action.TASKSTART,
- newTask);
- cp.addAction(action);
- if(!(newTask instanceof TransTaskSimulator)) {
- cp.removeSpareCore(targetCoreNum);
- SimExecutionNode seNode = new SimExecutionNode(targetCoreNum, this.processTime);
- seNode.setSpareCores(cp.getSpareCores());
- senode2action.put(seNode, action);
- action2exetime.put(action, (long)-1);
-
- SimExecutionNode lastsenode = lastseNodes[targetCoreNum];
- // create edges between previous senode on this core to this node
- if(lastsenode != null) {
- Action tmpaction = senode2action.get(lastsenode);
- SimExecutionEdge seEdge = null;
- if(tmpaction == null) {
- seEdge = new SimExecutionEdge(seNode,
- lastsenode.getCoreNum(),
- null,
- 0,
- null);
- } else {
- long weight = action2exetime.get(tmpaction);
- seEdge = new SimExecutionEdge(seNode,
- lastsenode.getCoreNum(),
- tmpaction.getTd(),
- weight,
- tmpaction.getTaskParams());
- }
- lastsenode.addEdge(seEdge);
- }
- lastseNodes[targetCoreNum] = seNode;
- }
+ this.tasks.add(newTask);
+ // add a TASKSTART action into this checkpoint
+ action = new Action(targetCoreNum,
+ Action.TASKSTART,
+ newTask);
+ cp.addAction(action);
+ if(!(newTask instanceof TransTaskSimulator)) {
+ cp.removeSpareCore(targetCoreNum);
+ SimExecutionNode seNode = new SimExecutionNode(targetCoreNum, this.processTime);
+ seNode.setSpareCores(cp.getSpareCores());
+ senode2action.put(seNode, action);
+ action2exetime.put(action, (long)-1);
+
+ SimExecutionNode lastsenode = lastseNodes[targetCoreNum];
+ // create edges between previous senode on this core to this node
+ if(lastsenode != null) {
+ Action tmpaction = senode2action.get(lastsenode);
+ SimExecutionEdge seEdge = null;
+ if(tmpaction == null) {
+ seEdge = new SimExecutionEdge(seNode,
+ lastsenode.getCoreNum(),
+ null,
+ 0,
+ null);
+ } else {
+ long weight = action2exetime.get(tmpaction);
+ seEdge = new SimExecutionEdge(seNode,
+ lastsenode.getCoreNum(),
+ tmpaction.getTd(),
+ weight,
+ tmpaction.getTaskParams());
+ }
+ lastsenode.addEdge(seEdge);
+ }
+ lastseNodes[targetCoreNum] = seNode;
+ }
}
}
}
// get the infomation of how to send new objects
Vector<ObjectSimulator> nobjs = task.getCurrentRun().getNewObjs();
for(int j = 0; j < nobjs.size(); j++) {
- ObjectSimulator nobj = nobjs.elementAt(j);
- totransObjs.add(nobj);
-
- action.addNewObj(nobj.getCd(), Integer.valueOf(1));
- // send the new object to target core according to pre-decide scheduling
- Queue<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));
- tmpqueue = null;
- }
- // enqueue this core again
- cores.add(targetCore);
- }
- cores = null;
- // check if this object becoming shared or not
- Vector<Integer> allycores = cs.getAllyCores(nobj.getCurrentFS());
- if(allycores != null) {
- nobj.setShared(true);
- // TODO, temporarily send to at most 2 cores
- int numtosend = allycores.size() > 2?2:allycores.size();
- for(int k = 0; k < numtosend; ++k) {
- Integer allyCore = allycores.elementAt(k);
- if(allyCore == corenum) {
- cs.addObject(nobj);
- } else {
- if(!transObjQueues.containsKey(allyCore)) {
- transObjQueues.put(allyCore, new LinkedList<ObjectInfo>());
- }
- Queue<ObjectInfo> tmpqueue = transObjQueues.get(allyCore);
- ObjectInfo nobjinfo = new ObjectInfo(nobj);
- if(!tmpqueue.contains(nobjinfo)) {
- tmpqueue.add(nobjinfo);
- }
- tmpqueue = null;
- }
- }
- allycores = null;
- }
+ ObjectSimulator nobj = nobjs.elementAt(j);
+ totransObjs.add(nobj);
+
+ action.addNewObj(nobj.getCd(), Integer.valueOf(1));
+ // send the new object to target core according to pre-decide scheduling
+ Queue<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));
+ tmpqueue = null;
+ }
+ // enqueue this core again
+ cores.add(targetCore);
+ }
+ cores = null;
+ // check if this object becoming shared or not
+ Vector<Integer> allycores = cs.getAllyCores(nobj.getCurrentFS());
+ if(allycores != null) {
+ nobj.setShared(true);
+ // TODO, temporarily send to at most 2 cores
+ int numtosend = allycores.size() > 2?2:allycores.size();
+ for(int k = 0; k < numtosend; ++k) {
+ Integer allyCore = allycores.elementAt(k);
+ if(allyCore == corenum) {
+ cs.addObject(nobj);
+ } else {
+ if(!transObjQueues.containsKey(allyCore)) {
+ transObjQueues.put(allyCore, new LinkedList<ObjectInfo>());
+ }
+ Queue<ObjectInfo> tmpqueue = transObjQueues.get(allyCore);
+ ObjectInfo nobjinfo = new ObjectInfo(nobj);
+ if(!tmpqueue.contains(nobjinfo)) {
+ tmpqueue.add(nobjinfo);
+ }
+ tmpqueue = null;
+ }
+ }
+ allycores = null;
+ }
}
nobjs = null;
}
if(transObjs != null) {
totransObjs.addAll(transObjs);
for(int j = 0; j < transObjs.size(); j++) {
- ObjectSimulator tobj = transObjs.elementAt(j);
- // send the object to target core according to pre-decide scheduling
- Queue<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.poll();
- 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));
- tmpqueue = null;
- }
- cores.add(targetCore);
- }
- cores = null;
- // check if this object becoming shared or not
- Vector<Integer> allycores = cs.getAllyCores(tobj.getCurrentFS());
- if(allycores != null) {
- tobj.setShared(true);
- // TODO, temporarily send to at most 2 cores
- int numtosend = allycores.size() > 2?2:allycores.size();
- for(int k = 0; k < numtosend; ++k) {
- Integer allyCore = allycores.elementAt(k);
- if(allyCore == corenum) {
- cs.addObject(tobj);
- } else {
- if(!transObjQueues.containsKey(allyCore)) {
- transObjQueues.put(allyCore, new LinkedList<ObjectInfo>());
- }
- Queue<ObjectInfo> tmpqueue = transObjQueues.get(allyCore);
- ObjectInfo nobjinfo = new ObjectInfo(tobj);
- if(!tmpqueue.contains(nobjinfo)) {
- tmpqueue.add(nobjinfo);
- }
- tmpqueue = null;
- }
- }
- allycores = null;
- }
+ ObjectSimulator tobj = transObjs.elementAt(j);
+ // send the object to target core according to pre-decide scheduling
+ Queue<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.poll();
+ 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));
+ tmpqueue = null;
+ }
+ cores.add(targetCore);
+ }
+ cores = null;
+ // check if this object becoming shared or not
+ Vector<Integer> allycores = cs.getAllyCores(tobj.getCurrentFS());
+ if(allycores != null) {
+ tobj.setShared(true);
+ // TODO, temporarily send to at most 2 cores
+ int numtosend = allycores.size() > 2?2:allycores.size();
+ for(int k = 0; k < numtosend; ++k) {
+ Integer allyCore = allycores.elementAt(k);
+ if(allyCore == corenum) {
+ cs.addObject(tobj);
+ } else {
+ if(!transObjQueues.containsKey(allyCore)) {
+ transObjQueues.put(allyCore, new LinkedList<ObjectInfo>());
+ }
+ Queue<ObjectInfo> tmpqueue = transObjQueues.get(allyCore);
+ ObjectInfo nobjinfo = new ObjectInfo(tobj);
+ if(!tmpqueue.contains(nobjinfo)) {
+ tmpqueue.add(nobjinfo);
+ }
+ tmpqueue = null;
+ }
+ }
+ allycores = null;
+ }
}
}
transObjs = null;
newTask);
cp.addAction(action);
if(!(newTask instanceof TransTaskSimulator)) {
- cp.removeSpareCore(cs.getCoreNum());
- SimExecutionNode seNode = new SimExecutionNode(corenum, this.processTime);
- seNode.setSpareCores(cp.getSpareCores());
- senode2action.put(seNode, action);
- action2exetime.put(action, (long)-1);
- SimExecutionNode lastsenode = lastseNodes[corenum];
- // create edges between previous senode on this core to this node
- if(lastsenode != null) {
- Action tmpaction = senode2action.get(lastsenode);
- long weight = tmpaction != null?action2exetime.get(tmpaction):0;
- seEdge = new SimExecutionEdge(seNode,
- lastsenode.getCoreNum(),
- tmpaction!= null?tmpaction.getTd():null,
- weight,
- tmpaction!=null?tmpaction.getTaskParams():null);
- lastsenode.addEdge(seEdge);
- }
- lastseNodes[corenum] = seNode;
- for(int tmpindex = 0; tmpindex < tttasks.size(); tmpindex++) {
- tttask2senode.put(tttasks.elementAt(tmpindex), seNode);
- }
+ cp.removeSpareCore(cs.getCoreNum());
+ SimExecutionNode seNode = new SimExecutionNode(corenum, this.processTime);
+ seNode.setSpareCores(cp.getSpareCores());
+ senode2action.put(seNode, action);
+ action2exetime.put(action, (long)-1);
+ SimExecutionNode lastsenode = lastseNodes[corenum];
+ // create edges between previous senode on this core to this node
+ if(lastsenode != null) {
+ Action tmpaction = senode2action.get(lastsenode);
+ long weight = tmpaction != null?action2exetime.get(tmpaction):0;
+ seEdge = new SimExecutionEdge(seNode,
+ lastsenode.getCoreNum(),
+ tmpaction!= null?tmpaction.getTd():null,
+ weight,
+ tmpaction!=null?tmpaction.getTaskParams():null);
+ lastsenode.addEdge(seEdge);
+ }
+ lastseNodes[corenum] = seNode;
+ for(int tmpindex = 0; tmpindex < tttasks.size(); tmpindex++) {
+ tttask2senode.put(tttasks.elementAt(tmpindex), seNode);
+ }
}
} else if(tttasks.size() > 0) {
SimExecutionNode seNode = new SimExecutionNode(corenum, this.processTime);
SimExecutionNode lastsenode = lastseNodes[corenum];
// create edges between previous senode on this core to this node
if(lastsenode != null) {
- Action tmpaction = senode2action.get(lastsenode);
- long weight = action2exetime.get(tmpaction);
- seEdge = new SimExecutionEdge(seNode,
- lastsenode.getCoreNum(),
- tmpaction.getTd(),
- weight,
- tmpaction.getTaskParams());
- lastsenode.addEdge(seEdge);
+ Action tmpaction = senode2action.get(lastsenode);
+ long weight = action2exetime.get(tmpaction);
+ seEdge = new SimExecutionEdge(seNode,
+ lastsenode.getCoreNum(),
+ tmpaction.getTd(),
+ weight,
+ tmpaction.getTaskParams());
+ lastsenode.addEdge(seEdge);
}
lastseNodes[corenum] = seNode;
for(int tmpindex = 0; tmpindex < tttasks.size(); tmpindex++) {
- tttask2senode.put(tttasks.elementAt(tmpindex), seNode);
+ tttask2senode.put(tttasks.elementAt(tmpindex), seNode);
}
}
if(seEdge != null) {
// setup data dependencies for the task
Vector<Integer> taskparams = seEdge.getTaskparams();
if(taskparams != null) {
- for(int i = 0; i < taskparams.size(); i++) {
- Integer tparam = taskparams.elementAt(i);
- SimExecutionEdge lastedge = obj2lastseedge.get(tparam);
- if(lastedge != null) {
- if(lastedge.getCoreNum() != seEdge.getCoreNum()) {
- // the obj is transferred from another core
- // create an seEdge for this transfer
- long weight = obj2transtime.get(tparam);
- SimExecutionEdge transseEdge = new SimExecutionEdge((SimExecutionNode)seEdge.getSource(),
- lastedge.getCoreNum(),
- null, // TODO: not sure if this is enough
- weight,
- null);
- if(((SimExecutionNode)seEdge.getSource()).getTimepoint() <
- ((SimExecutionNode)lastedge.getTarget()).getTimepoint()) {
- System.err.println("ScheduleSimulator:757");
- System.exit(-1);
- }
- lastedge.getTarget().addEdge(transseEdge);
- transseEdge.addPredicate(lastedge);
- seEdge.addPredicate(transseEdge);
- } else {
- seEdge.addPredicate(lastedge);
- }
- }
- // update the last edge associated to the parameter obj
- obj2lastseedge.put(tparam, seEdge);
- }
+ for(int i = 0; i < taskparams.size(); i++) {
+ Integer tparam = taskparams.elementAt(i);
+ SimExecutionEdge lastedge = obj2lastseedge.get(tparam);
+ if(lastedge != null) {
+ if(lastedge.getCoreNum() != seEdge.getCoreNum()) {
+ // the obj is transferred from another core
+ // create an seEdge for this transfer
+ long weight = obj2transtime.get(tparam);
+ SimExecutionEdge transseEdge = new SimExecutionEdge((SimExecutionNode)seEdge.getSource(),
+ lastedge.getCoreNum(),
+ null, // TODO: not sure if this is enough
+ weight,
+ null);
+ if(((SimExecutionNode)seEdge.getSource()).getTimepoint() <
+ ((SimExecutionNode)lastedge.getTarget()).getTimepoint()) {
+ System.err.println("ScheduleSimulator:757");
+ System.exit(-1);
+ }
+ lastedge.getTarget().addEdge(transseEdge);
+ transseEdge.addPredicate(lastedge);
+ seEdge.addPredicate(transseEdge);
+ } else {
+ seEdge.addPredicate(lastedge);
+ }
+ }
+ // update the last edge associated to the parameter obj
+ obj2lastseedge.put(tparam, seEdge);
+ }
}
taskparams = null;
// set seEdge as the last execution edge for all newly created objs
if(nobjs != null) {
- for(int i = 0; i < nobjs.size(); i++) {
- ObjectSimulator nobj = nobjs.elementAt(i);
- obj2lastseedge.put(nobj.getOid(), seEdge);
- }
+ for(int i = 0; i < nobjs.size(); i++) {
+ ObjectSimulator nobj = nobjs.elementAt(i);
+ obj2lastseedge.put(nobj.getOid(), seEdge);
+ }
}
}
}
this.actions = new Vector<Action>();
this.spareCores = new Vector<Integer>();
for(int i = 0; i < corenum; i++) {
- this.spareCores.add(i);
+ this.spareCores.add(i);
}
}
public void removeSpareCore(int core) {
for(int i = 0; i < this.spareCores.size(); i++) {
- if(this.spareCores.elementAt(i) == core) {
- for(int j = i; j < this.spareCores.size() - 1; j++) {
- this.spareCores.setElementAt(this.spareCores.elementAt(j + 1), j);
- }
- this.spareCores.remove(this.spareCores.size() - 1);
- return;
- }
+ if(this.spareCores.elementAt(i) == core) {
+ for(int j = i; j < this.spareCores.size() - 1; j++) {
+ this.spareCores.setElementAt(this.spareCores.elementAt(j + 1), j);
+ }
+ this.spareCores.remove(this.spareCores.size() - 1);
+ return;
+ }
}
}
this.td = null;
this.taskparams = null;
if(this.type == TFWITHOBJ) {
- this.nObjs = new Hashtable<ClassDescriptor, Integer>();
+ this.nObjs = new Hashtable<ClassDescriptor, Integer>();
} else {
- this.nObjs = null;
+ this.nObjs = null;
}
this.nObjNum = -1;
this.transObj = null;
this.td = ts.getTd();
Vector<Queue<ObjectSimulator>> paraQueues = ts.getParaQueues();
if(this.type == TASKSTART) {
- this.taskparams = new Vector<Integer>();
- for(int i = 0; i < paraQueues.size(); i++) {
- ObjectSimulator tpara = paraQueues.elementAt(i).peek();
- this.taskparams.add(tpara.getOid());
- }
+ this.taskparams = new Vector<Integer>();
+ for(int i = 0; i < paraQueues.size(); i++) {
+ ObjectSimulator tpara = paraQueues.elementAt(i).peek();
+ this.taskparams.add(tpara.getOid());
+ }
} else {
- this.taskparams = null;
+ this.taskparams = null;
}
paraQueues = null;
if(this.type == TFWITHOBJ) {
- this.nObjs = new Hashtable<ClassDescriptor, Integer>();
+ this.nObjs = new Hashtable<ClassDescriptor, Integer>();
} else {
- this.nObjs = null;
+ this.nObjs = null;
}
this.nObjNum = -1;
this.transObj = null;
assert(this.type == TFWITHOBJ);
if(this.nObjs.containsKey(cd)) {
- Integer sum = this.nObjs.get(cd) + num;
- this.nObjs.put(cd, sum);
+ Integer sum = this.nObjs.get(cd) + num;
+ this.nObjs.put(cd, sum);
} else {
- this.nObjs.put(cd, num);
+ this.nObjs.put(cd, num);
}
}
for(int i = 0; i < mapping.size(); i++) {
Vector<ScheduleNode> sNodes = mapping.elementAt(i);
if(sNodes != null) {
- ScheduleNode rootnode = sNodes.elementAt(0);
- for(int j = 1; j < sNodes.size(); j++) {
- ScheduleNode tocombine = sn2sn.get(sNodes.elementAt(j));
- ScheduleNode root = sn2sn.get(rootnode);
- ScheduleEdge se = (ScheduleEdge)tocombine.inedges().next();
- try {
- if(root.equals(((ScheduleNode)se.getSource()))) {
- root.mergeSEdge(se);
- if(ScheduleEdge.NEWEDGE == se.getType()) {
- // As se has been changed into an internal edge inside a ScheduleNode,
- // change the source and target of se from original ScheduleNodes into ClassNodes.
- se.setTarget(se.getTargetCNode());
- //se.setSource(se.getSourceCNode());
- //se.getTargetCNode().addEdge(se);
- se.getSourceCNode().addEdge(se);
- }
- } else {
- root.mergeSNode(tocombine);
- }
- } catch(Exception e) {
- e.printStackTrace();
- System.exit(-1);
- }
- result.removeElement(tocombine);
- }
+ ScheduleNode rootnode = sNodes.elementAt(0);
+ for(int j = 1; j < sNodes.size(); j++) {
+ ScheduleNode tocombine = sn2sn.get(sNodes.elementAt(j));
+ ScheduleNode root = sn2sn.get(rootnode);
+ ScheduleEdge se = (ScheduleEdge)tocombine.inedges().next();
+ try {
+ if(root.equals(((ScheduleNode)se.getSource()))) {
+ root.mergeSEdge(se);
+ if(ScheduleEdge.NEWEDGE == se.getType()) {
+ // As se has been changed into an internal edge inside a ScheduleNode,
+ // change the source and target of se from original ScheduleNodes into ClassNodes.
+ se.setTarget(se.getTargetCNode());
+ //se.setSource(se.getSourceCNode());
+ //se.getTargetCNode().addEdge(se);
+ se.getSourceCNode().addEdge(se);
+ }
+ } else {
+ root.mergeSNode(tocombine);
+ }
+ } catch(Exception e) {
+ e.printStackTrace();
+ System.exit(-1);
+ }
+ result.removeElement(tocombine);
+ }
}
}
// combine those nodes in combine with corresponding rootnodes
for(int i = 0; i < combine.size(); i++) {
if(combine.elementAt(i) != null) {
- for(int j = 0; j < combine.elementAt(i).size(); j++) {
- CombinationUtil.Combine tmpcombine = combine.elementAt(i).elementAt(j);
- ScheduleNode tocombine = sn2sn.get(tmpcombine.node);
- ScheduleNode root = sn2sn.get(rootnodes.elementAt(tmpcombine.root).elementAt(tmpcombine.index));
- ScheduleEdge se = (ScheduleEdge)tocombine.inedges().next();
- try {
- if(root.equals(((ScheduleNode)se.getSource()))) {
- root.mergeSEdge(se);
- if(ScheduleEdge.NEWEDGE == se.getType()) {
- // As se has been changed into an internal edge inside a ScheduleNode,
- // change the source and target of se from original ScheduleNodes into ClassNodes.
- se.setTarget(se.getTargetCNode());
- //se.setSource(se.getSourceCNode());
- //se.getTargetCNode().addEdge(se);
- se.getSourceCNode().addEdge(se);
- }
- } else {
- root.mergeSNode(tocombine);
- }
- } catch(Exception e) {
- e.printStackTrace();
- System.exit(-1);
- }
- result.removeElement(tocombine);
- }
+ for(int j = 0; j < combine.elementAt(i).size(); j++) {
+ CombinationUtil.Combine tmpcombine = combine.elementAt(i).elementAt(j);
+ ScheduleNode tocombine = sn2sn.get(tmpcombine.node);
+ ScheduleNode root = sn2sn.get(rootnodes.elementAt(tmpcombine.root).elementAt(tmpcombine.index));
+ ScheduleEdge se = (ScheduleEdge)tocombine.inedges().next();
+ try {
+ if(root.equals(((ScheduleNode)se.getSource()))) {
+ root.mergeSEdge(se);
+ if(ScheduleEdge.NEWEDGE == se.getType()) {
+ // As se has been changed into an internal edge inside a ScheduleNode,
+ // change the source and target of se from original ScheduleNodes into ClassNodes.
+ se.setTarget(se.getTargetCNode());
+ //se.setSource(se.getSourceCNode());
+ //se.getTargetCNode().addEdge(se);
+ se.getSourceCNode().addEdge(se);
+ }
+ } else {
+ root.mergeSNode(tocombine);
+ }
+ } catch(Exception e) {
+ e.printStackTrace();
+ System.exit(-1);
+ }
+ result.removeElement(tocombine);
+ }
}
}
ScheduleEdge se = null;
switch(sse.getType()) {
case ScheduleEdge.NEWEDGE: {
- se = new ScheduleEdge(ctarget, "new", sse.getFstate(), sse.getType(), gid); //new ScheduleEdge(ctarget, "new", sse.getClassDescriptor(), sse.getIsNew(), gid);
- se.setProbability(sse.getProbability());
- se.setNewRate(sse.getNewRate());
- break;
+ se = new ScheduleEdge(ctarget, "new", sse.getFstate(), sse.getType(), gid); //new ScheduleEdge(ctarget, "new", sse.getClassDescriptor(), sse.getIsNew(), gid);
+ se.setProbability(sse.getProbability());
+ se.setNewRate(sse.getNewRate());
+ break;
}
case ScheduleEdge.TRANSEDGE: {
- se = new ScheduleEdge(ctarget, "transmit", sse.getFstate(), sse.getType(), gid); //new ScheduleEdge(ctarget, "transmit", sse.getClassDescriptor(), false, gid);
- break;
+ se = new ScheduleEdge(ctarget, "transmit", sse.getFstate(), sse.getType(), gid); //new ScheduleEdge(ctarget, "transmit", sse.getClassDescriptor(), false, gid);
+ break;
}
}
se.setSourceCNode(sourcecn2cn.get(sse.getSourceCNode()));
tmpnode.computeHashcid();
int hcid = tmpnode.getHashcid();
if(hcid2cid.containsKey(hcid)) {
- // already have a cid for this node
- tmpnode.setCid(hcid2cid.get(hcid));
+ // already have a cid for this node
+ tmpnode.setCid(hcid2cid.get(hcid));
} else {
- // generate a new cid for such node
- tmpnode.setCid(ncid);
- hcid2cid.put(hcid, ncid);
- ncid++;
+ // generate a new cid for such node
+ tmpnode.setCid(ncid);
+ hcid2cid.put(hcid, ncid);
+ ncid++;
}
}
hcid2cid.clear();
Vector<Vector<ScheduleNode>> sNodeVecs = new Vector<Vector<ScheduleNode>>();
for(int i = 0; i < scheduleNodes.size(); i++) {
- ScheduleNode tmpn = scheduleNodes.elementAt(i);
- int tmpcid = tmpn.getCid();
- int index = 0;
- for(index = 0; index < sNodeVecs.size(); index++) {
- if(sNodeVecs.elementAt(index).elementAt(0).getCid() > tmpcid) {
- // find the place to insert
- sNodeVecs.insertElementAt(new Vector<ScheduleNode>(), index);
- /*sNodeVecs.add(sNodeVecs.lastElement());
- for(int j = sNodeVecs.size() - 2; j > index; j--) {
- sNodeVecs.setElementAt(sNodeVecs.elementAt(j - 1), j);
- }
- sNodeVecs.setElementAt(new Vector<ScheduleNode>(), index);*/
- break;
- } else if(sNodeVecs.elementAt(index).elementAt(0).getCid() == tmpcid) {
- break;
- }
- }
- if(index == sNodeVecs.size()) {
- sNodeVecs.add(new Vector<ScheduleNode>());
- }
-
- /*int index = tmpcid;
- while(sNodeVecs.size() <= index) {
- sNodeVecs.add(null);
- }
- if(sNodeVecs.elementAt(index) == null) {
- sNodeVecs.setElementAt(new Vector<ScheduleNode>(), index);
- }*/
- if(!sNodeVecs.elementAt(index).contains(tmpn)) {
- sNodeVecs.elementAt(index).addElement(tmpn);
- }
+ ScheduleNode tmpn = scheduleNodes.elementAt(i);
+ int tmpcid = tmpn.getCid();
+ int index = 0;
+ for(index = 0; index < sNodeVecs.size(); index++) {
+ if(sNodeVecs.elementAt(index).elementAt(0).getCid() > tmpcid) {
+ // find the place to insert
+ sNodeVecs.insertElementAt(new Vector<ScheduleNode>(), index);
+ /*sNodeVecs.add(sNodeVecs.lastElement());
+ for(int j = sNodeVecs.size() - 2; j > index; j--) {
+ sNodeVecs.setElementAt(sNodeVecs.elementAt(j - 1), j);
+ }
+ sNodeVecs.setElementAt(new Vector<ScheduleNode>(), index);*/
+ break;
+ } else if(sNodeVecs.elementAt(index).elementAt(0).getCid() == tmpcid) {
+ break;
+ }
+ }
+ if(index == sNodeVecs.size()) {
+ sNodeVecs.add(new Vector<ScheduleNode>());
+ }
+
+ /*int index = tmpcid;
+ while(sNodeVecs.size() <= index) {
+ sNodeVecs.add(null);
+ }
+ if(sNodeVecs.elementAt(index) == null) {
+ sNodeVecs.setElementAt(new Vector<ScheduleNode>(), index);
+ }*/
+ if(!sNodeVecs.elementAt(index).contains(tmpn)) {
+ sNodeVecs.elementAt(index).addElement(tmpn);
+ }
}
return sNodeVecs;
else
switch (((FlagOpNode)fen).getOp().getOp()) {
case Operation.LOGIC_AND:
- return ((isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)) && (isTaskTrigger_flag(((FlagOpNode)fen).getRight(),fs)));
+ return ((isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)) && (isTaskTrigger_flag(((FlagOpNode)fen).getRight(),fs)));
case Operation.LOGIC_OR:
- return ((isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)) || (isTaskTrigger_flag(((FlagOpNode)fen).getRight(),fs)));
+ return ((isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)) || (isTaskTrigger_flag(((FlagOpNode)fen).getRight(),fs)));
case Operation.LOGIC_NOT:
- return !(isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs));
+ return !(isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs));
default:
- return false;
+ return false;
}
}
//Draw the internal 'new' edges
Iterator it_edges =gn.getScheduleEdgesIterator();
while(it_edges.hasNext()) {
- ScheduleEdge se = (ScheduleEdge)it_edges.next();
- output.print("\t");
- if(se.getSourceCNode().isclone()) {
- output.print(se.getSourceCNode().getLabel());
- } else {
- if(se.getSourceFState() == null) {
- output.print(se.getSourceCNode().getClusterLabel());
- } else {
- output.print(se.getSourceFState().getLabel());
- }
- }
-
- output.print(" -> ");
- if(se.isclone()) {
- if(se.getTargetCNode().isclone()) {
- output.print(se.getTargetCNode().getLabel());
- } else {
- output.print(se.getTargetCNode().getClusterLabel());
- }
- output.println(" [label=\"" + se.getLabel() + "\", color=red];");
- } else {
- output.print(se.getTargetFState().getLabel() + " [label=\"" + se.getLabel() + "\", color=red, ltail=");
- if(se.getSourceCNode().isclone()) {
- output.println(se.getSourceCNode().getLabel() + "];");
- } else {
- output.println(se.getSourceCNode().getClusterLabel() + "];");
- }
- }
+ ScheduleEdge se = (ScheduleEdge)it_edges.next();
+ output.print("\t");
+ if(se.getSourceCNode().isclone()) {
+ output.print(se.getSourceCNode().getLabel());
+ } else {
+ if(se.getSourceFState() == null) {
+ output.print(se.getSourceCNode().getClusterLabel());
+ } else {
+ output.print(se.getSourceFState().getLabel());
+ }
+ }
+
+ output.print(" -> ");
+ if(se.isclone()) {
+ if(se.getTargetCNode().isclone()) {
+ output.print(se.getTargetCNode().getLabel());
+ } else {
+ output.print(se.getTargetCNode().getClusterLabel());
+ }
+ output.println(" [label=\"" + se.getLabel() + "\", color=red];");
+ } else {
+ output.print(se.getTargetFState().getLabel() + " [label=\"" + se.getLabel() + "\", color=red, ltail=");
+ if(se.getSourceCNode().isclone()) {
+ output.println(se.getSourceCNode().getLabel() + "];");
+ } else {
+ output.println(se.getSourceCNode().getClusterLabel() + "];");
+ }
+ }
}
output.println("\t}\n");
it_edges = null;
//Draw 'new' edges of this ScheduleNode
while(edges.hasNext()) {
- ScheduleEdge se = (ScheduleEdge)edges.next();
- output.print("\t");
- if(se.getSourceCNode().isclone()) {
- output.print(se.getSourceCNode().getLabel());
- } else {
- if(se.getSourceFState() == null) {
- output.print(se.getSourceCNode().getClusterLabel());
- } else {
- output.print(se.getSourceFState().getLabel());
- }
- }
-
- output.print(" -> ");
- if(se.isclone()) {
- if(se.getTargetCNode().isclone()) {
- output.print(se.getTargetCNode().getLabel());
- } else {
- output.print(se.getTargetCNode().getClusterLabel());
- }
- output.println(" [label=\"" + se.getLabel() + "\", color=red, style=dashed];");
- } else {
- output.println(se.getTargetFState().getLabel() + " [label=\"" + se.getLabel() + "\", color=red, style=dashed];");
- }
+ ScheduleEdge se = (ScheduleEdge)edges.next();
+ output.print("\t");
+ if(se.getSourceCNode().isclone()) {
+ output.print(se.getSourceCNode().getLabel());
+ } else {
+ if(se.getSourceFState() == null) {
+ output.print(se.getSourceCNode().getClusterLabel());
+ } else {
+ output.print(se.getSourceFState().getLabel());
+ }
+ }
+
+ output.print(" -> ");
+ if(se.isclone()) {
+ if(se.getTargetCNode().isclone()) {
+ output.print(se.getTargetCNode().getLabel());
+ } else {
+ output.print(se.getTargetCNode().getClusterLabel());
+ }
+ output.println(" [label=\"" + se.getLabel() + "\", color=red, style=dashed];");
+ } else {
+ output.println(se.getTargetFState().getLabel() + " [label=\"" + se.getLabel() + "\", color=red, style=dashed];");
+ }
}
edges = null;
}
while (it.hasNext()) {
ClassNode gn = (ClassNode) it.next();
if(gn.isclone()) {
- output.println("\t\t" + gn.getLabel() + " [style=dashed, label=\"" + gn.getTextLabel() + "\", shape=box];");
+ output.println("\t\t" + gn.getLabel() + " [style=dashed, label=\"" + gn.getTextLabel() + "\", shape=box];");
} else {
- output.println("\tsubgraph " + gn.getClusterLabel() + "{");
- output.println("\t\tstyle=dashed;");
- output.println("\t\tlabel=\"" + gn.getTextLabel() + "\";");
- traverseFlagStates(output, gn.getFlagStates());
- output.println("\t}\n");
+ output.println("\tsubgraph " + gn.getClusterLabel() + "{");
+ output.println("\t\tstyle=dashed;");
+ output.println("\t\tlabel=\"" + gn.getTextLabel() + "\";");
+ traverseFlagStates(output, gn.getFlagStates());
+ output.println("\t}\n");
}
}
}
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);
+ 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 + "];");
+ 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)) {
- Iterator nodeit=nonmerge(node, nodes).iterator();
- for(; 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() + "%) }";
- }
- keys = null;
- it_keys = null;
- }
- output.println("\t" + gn.getLabel() + " -> " + node2.getLabel() + " [" + "label=\"" + edgelabel + "\"" + edgedotnodeparams + "];");
- }
- nodeit = null;
- }
- }
+ while (edges.hasNext()) {
+ Edge edge = (Edge) edges.next();
+ GraphNode node = edge.getTarget();
+ if (nodes.contains(node)) {
+ Iterator nodeit=nonmerge(node, nodes).iterator();
+ for(; nodeit.hasNext(); ) {
+ GraphNode node2=(GraphNode)nodeit.next();
+ String edgelabel = "";
+ String edgedotnodeparams="";
+
+ for(int i=0; i<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() + "%) }";
+ }
+ keys = null;
+ it_keys = null;
+ }
+ output.println("\t" + gn.getLabel() + " -> " + node2.getLabel() + " [" + "label=\"" + edgelabel + "\"" + edgedotnodeparams + "];");
+ }
+ nodeit = null;
+ }
+ }
edges = null;
}
cycleset = null;
GraphNode gn2=(GraphNode)toprocess.iterator().next();
toprocess.remove(gn2);
if (!gn2.merge)
- newset.add(gn2);
+ newset.add(gn2);
else {
- Iterator edges = gn2.edges();
- while (edges.hasNext()) {
- Edge edge = (Edge) edges.next();
- GraphNode node = edge.getTarget();
- if (!newset.contains(node)&&nodes.contains(node))
- toprocess.add(node);
- }
- edges = null;
+ Iterator edges = gn2.edges();
+ while (edges.hasNext()) {
+ Edge edge = (Edge) edges.next();
+ GraphNode node = edge.getTarget();
+ if (!newset.contains(node)&&nodes.contains(node))
+ toprocess.add(node);
+ }
+ edges = null;
}
}
toprocess = null;
// the capital line
output.print("{rank=source; \"Time\"; ");
for(j = 0; j < coreNum; j++) {
- output.print("\"core " + j + "\"; ");
+ output.print("\"core " + j + "\"; ");
}
output.println("}");
// time coordinate nodes
String[] lastTasks = new String[coreNum];
boolean[] isTaskFinish = new boolean[coreNum];
for(j = 0; j < coreNum; j++) {
- lastTaskNodes[j] = "first";
- isTaskFinish[j] = true;
- lastTasks[j] = "";
+ lastTaskNodes[j] = "first";
+ isTaskFinish[j] = true;
+ lastTasks[j] = "";
}
timeNodes.add("0");
for(j = 0; j < checkpoints.size(); j++) {
- CheckPoint tcp = checkpoints.elementAt(j);
- Hashtable<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.containsKey(cNum)) {
- tmplastTasks.put(cNum, lastTasks[cNum]);
- }
- if(!(tmpisset.contains(cNum))
- && (isTaskFinish[cNum])
- && !(tmpisTaskFinish.contains(cNum))) {
- tmpisTaskFinish.add(cNum); // records those with task finished the first time visit it
- }
- String tmpTaskNode = "\"" + tnode + "core" + cNum + "\"";
- StringBuffer tmpLabel = null;
- boolean isfirst = false;
- if(!tmpTaskNodes.containsKey(tmpTaskNode)) {
- tmpTaskNodes.put(tmpTaskNode, new StringBuffer(tnode + ":"));
- isfirst = true;
- }
- tmpLabel = tmpTaskNodes.get(tmpTaskNode);
- switch(taction.getType()) {
- case Action.ADDOBJ: {
- if(!isfirst) {
- tmpLabel.append("\\n");
- }
- tmpLabel.append("(" + taction.getTransObj().getSymbol() + ")arrives;");
- if(!(lastTaskNodes[cNum].equals(tmpTaskNode))) {
- output.print("\t");
- if(lastTaskNodes[cNum].equals("first")) {
- output.print("\"core " + cNum + "\"->" + tmpTaskNode);
- } else {
- output.print(lastTaskNodes[cNum] + "->" + tmpTaskNode);
- }
- if(tmpisTaskFinish.contains(cNum)) {
- output.print(" [style=invis]");
- }
- output.println(";");
- lastTaskNodes[cNum] = tmpTaskNode;
- }
- break;
- }
-
- case Action.TASKFINISH: {
- if(!isfirst) {
- tmpLabel.append("\\n");
- }
- tmpLabel.append("<" + taction.getTd().getSymbol() + "(");
- /*Vector<Integer> taskparams = taction.getTaskParams();
- for(int ii = 0; ii < taskparams.size(); ii++) {
- tmpLabel.append(taskparams.elementAt(ii));
- if(ii < taskparams.size() - 1) {
- tmpLabel.append(",");
- }
- }*/
- tmpLabel.append(")>finishes;");
- if(!(lastTaskNodes[cNum].equals("first"))) {
- if(!(lastTaskNodes[cNum].equals(tmpTaskNode))) {
- output.print("\t");
- output.println(lastTaskNodes[cNum] + "->" + tmpTaskNode + ";");
- lastTaskNodes[cNum] = tmpTaskNode;
- }
- if(tmpisset.contains(cNum)) {
- isTaskFinish[cNum] &= true;
- } else {
- isTaskFinish[cNum] = true;
- tmpisset.add(cNum);
- }
- lastTasks[cNum] = "";
- } else {
- throw new Exception("Error: unexpected task finish");
- }
- break;
- }
-
- case Action.TFWITHOBJ: {
- if(!isfirst) {
- tmpLabel.append("\\n");
- }
- tmpLabel.append("<" + taction.getTd().getSymbol() + "(");
- /*Vector<Integer> taskparams = taction.getTaskParams();
- for(int ii = 0; ii < taskparams.size(); ii++) {
- tmpLabel.append(taskparams.elementAt(ii));
- if(ii < taskparams.size() - 1) {
- tmpLabel.append(",");
- }
- }*/
- tmpLabel.append(")>finishes;");
- Iterator<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(";");
- }
- entry = null;
- }
- it_entry = null;
- if(!(lastTaskNodes[cNum].equals("first"))) {
- if (!(lastTaskNodes[cNum].equals(tmpTaskNode))) {
- output.print("\t");
- output.println(lastTaskNodes[cNum] + "->" + tmpTaskNode + ";");
- lastTaskNodes[cNum] = tmpTaskNode;
- }
- if(tmpisset.contains(cNum)) {
- isTaskFinish[cNum] &= true;
- } else {
- isTaskFinish[cNum] = true;
- tmpisset.add(cNum);
- }
- lastTasks[cNum] = "";
- } else {
- throw new Exception("Error: unexpected task finish");
- }
- break;
- }
-
- case Action.TASKSTART: {
- if(!isfirst) {
- tmpLabel.append("\\n");
- }
- tmpLabel.append("<" + taction.getTd().getSymbol() + "(");
- /*Vector<Integer> taskparams = taction.getTaskParams();
- for(int ii = 0; ii < taskparams.size(); ii++) {
- tmpLabel.append(taskparams.elementAt(ii));
- if(ii < taskparams.size() - 1) {
- tmpLabel.append(",");
- }
- }*/
- tmpLabel.append(")>starts;");
- lastTasks[cNum] = taction.getTd().getSymbol();
-
- if (!(lastTaskNodes[cNum].equals(tmpTaskNode))) {
- output.print("\t");
- if(lastTaskNodes[cNum].equals("first")) {
- output.print("\"core " + cNum + "\"->" + tmpTaskNode);
- } else {
- output.print(lastTaskNodes[cNum] + "->" + tmpTaskNode);
- }
- if(tmpisTaskFinish.contains(cNum)) {
- output.print(" [style=invis]");
- }
- output.println(";");
- lastTaskNodes[cNum] = tmpTaskNode;
- }
- isTaskFinish[cNum] &= false;
- break;
- }
-
- case Action.TASKABORT: {
- if(!isfirst) {
- tmpLabel.append("\\n");
- }
- tmpLabel.append("<" + taction.getTd().getSymbol() + "(");
- /*Vector<Integer> taskparams = taction.getTaskParams();
- for(int ii = 0; ii < taskparams.size(); ii++) {
- tmpLabel.append(taskparams.elementAt(ii));
- if(ii < taskparams.size() - 1) {
- tmpLabel.append(",");
- }
- }*/
- tmpLabel.append(")>aborts;");
- if(!(lastTaskNodes[cNum].equals("first")) &&
- (tmplastTasks.get(cNum).equals(taction.getTd().getSymbol()))) {
- if(!(lastTaskNodes[cNum].equals(tmpTaskNode))) {
- output.print("\t");
- output.println(lastTaskNodes[cNum] + "->" + tmpTaskNode + ";");
- lastTaskNodes[cNum] = tmpTaskNode;
- }
- if(tmpisset.contains(cNum)) {
- isTaskFinish[cNum] &= true;
- } else {
- isTaskFinish[cNum] = true;
- tmpisset.add(cNum);
- }
- lastTasks[cNum] = "";
- } else {
- throw new Exception("Error: unexpected task aborts");
- }
- break;
- }
-
- case Action.TASKREMOVE: {
- if(!isfirst) {
- tmpLabel.append("\\n");
- }
- tmpLabel.append("<" + taction.getTd().getSymbol() + "(");
- /*Vector<Integer> taskparams = taction.getTaskParams();
- for(int ii = 0; ii < taskparams.size(); ii++) {
- tmpLabel.append(taskparams.elementAt(ii));
- if(ii < taskparams.size() - 1) {
- tmpLabel.append(",");
- }
- }*/
- tmpLabel.append(")>removes;");
- if(!(lastTaskNodes[cNum].equals("first")) &&
- (tmplastTasks.get(cNum).equals(taction.getTd().getSymbol()))) {
- if(!(lastTaskNodes[cNum].equals(tmpTaskNode))) {
- output.print("\t");
- output.println(lastTaskNodes[cNum] + "->" + tmpTaskNode + ";");
- lastTaskNodes[cNum] = tmpTaskNode;
- }
- if(tmpisset.contains(cNum)) {
- isTaskFinish[cNum] &= true;
- } else {
- isTaskFinish[cNum] = true;
- tmpisset.add(cNum);
- }
- lastTasks[cNum] = "";
- } else {
- throw new Exception("Error: unexpected task remove");
- }
- break;
- }
- }
- }
- Enumeration<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("; ");
- }
- keys = null;
- output.println("}");
- output.print("\t");
- tmplastTasks = null;
- tmpisTaskFinish = null;
- tmpisset = null;
- actions = null;
- tmpTaskNodes = null;
+ 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.containsKey(cNum)) {
+ tmplastTasks.put(cNum, lastTasks[cNum]);
+ }
+ if(!(tmpisset.contains(cNum))
+ && (isTaskFinish[cNum])
+ && !(tmpisTaskFinish.contains(cNum))) {
+ tmpisTaskFinish.add(cNum); // records those with task finished the first time visit it
+ }
+ String tmpTaskNode = "\"" + tnode + "core" + cNum + "\"";
+ StringBuffer tmpLabel = null;
+ boolean isfirst = false;
+ if(!tmpTaskNodes.containsKey(tmpTaskNode)) {
+ tmpTaskNodes.put(tmpTaskNode, new StringBuffer(tnode + ":"));
+ isfirst = true;
+ }
+ tmpLabel = tmpTaskNodes.get(tmpTaskNode);
+ switch(taction.getType()) {
+ case Action.ADDOBJ: {
+ if(!isfirst) {
+ tmpLabel.append("\\n");
+ }
+ tmpLabel.append("(" + taction.getTransObj().getSymbol() + ")arrives;");
+ if(!(lastTaskNodes[cNum].equals(tmpTaskNode))) {
+ output.print("\t");
+ if(lastTaskNodes[cNum].equals("first")) {
+ output.print("\"core " + cNum + "\"->" + tmpTaskNode);
+ } else {
+ output.print(lastTaskNodes[cNum] + "->" + tmpTaskNode);
+ }
+ if(tmpisTaskFinish.contains(cNum)) {
+ output.print(" [style=invis]");
+ }
+ output.println(";");
+ lastTaskNodes[cNum] = tmpTaskNode;
+ }
+ break;
+ }
+
+ case Action.TASKFINISH: {
+ if(!isfirst) {
+ tmpLabel.append("\\n");
+ }
+ tmpLabel.append("<" + taction.getTd().getSymbol() + "(");
+ /*Vector<Integer> taskparams = taction.getTaskParams();
+ for(int ii = 0; ii < taskparams.size(); ii++) {
+ tmpLabel.append(taskparams.elementAt(ii));
+ if(ii < taskparams.size() - 1) {
+ tmpLabel.append(",");
+ }
+ }*/
+ tmpLabel.append(")>finishes;");
+ if(!(lastTaskNodes[cNum].equals("first"))) {
+ if(!(lastTaskNodes[cNum].equals(tmpTaskNode))) {
+ output.print("\t");
+ output.println(lastTaskNodes[cNum] + "->" + tmpTaskNode + ";");
+ lastTaskNodes[cNum] = tmpTaskNode;
+ }
+ if(tmpisset.contains(cNum)) {
+ isTaskFinish[cNum] &= true;
+ } else {
+ isTaskFinish[cNum] = true;
+ tmpisset.add(cNum);
+ }
+ lastTasks[cNum] = "";
+ } else {
+ throw new Exception("Error: unexpected task finish");
+ }
+ break;
+ }
+
+ case Action.TFWITHOBJ: {
+ if(!isfirst) {
+ tmpLabel.append("\\n");
+ }
+ tmpLabel.append("<" + taction.getTd().getSymbol() + "(");
+ /*Vector<Integer> taskparams = taction.getTaskParams();
+ for(int ii = 0; ii < taskparams.size(); ii++) {
+ tmpLabel.append(taskparams.elementAt(ii));
+ if(ii < taskparams.size() - 1) {
+ tmpLabel.append(",");
+ }
+ }*/
+ tmpLabel.append(")>finishes;");
+ Iterator<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(";");
+ }
+ entry = null;
+ }
+ it_entry = null;
+ if(!(lastTaskNodes[cNum].equals("first"))) {
+ if (!(lastTaskNodes[cNum].equals(tmpTaskNode))) {
+ output.print("\t");
+ output.println(lastTaskNodes[cNum] + "->" + tmpTaskNode + ";");
+ lastTaskNodes[cNum] = tmpTaskNode;
+ }
+ if(tmpisset.contains(cNum)) {
+ isTaskFinish[cNum] &= true;
+ } else {
+ isTaskFinish[cNum] = true;
+ tmpisset.add(cNum);
+ }
+ lastTasks[cNum] = "";
+ } else {
+ throw new Exception("Error: unexpected task finish");
+ }
+ break;
+ }
+
+ case Action.TASKSTART: {
+ if(!isfirst) {
+ tmpLabel.append("\\n");
+ }
+ tmpLabel.append("<" + taction.getTd().getSymbol() + "(");
+ /*Vector<Integer> taskparams = taction.getTaskParams();
+ for(int ii = 0; ii < taskparams.size(); ii++) {
+ tmpLabel.append(taskparams.elementAt(ii));
+ if(ii < taskparams.size() - 1) {
+ tmpLabel.append(",");
+ }
+ }*/
+ tmpLabel.append(")>starts;");
+ lastTasks[cNum] = taction.getTd().getSymbol();
+
+ if (!(lastTaskNodes[cNum].equals(tmpTaskNode))) {
+ output.print("\t");
+ if(lastTaskNodes[cNum].equals("first")) {
+ output.print("\"core " + cNum + "\"->" + tmpTaskNode);
+ } else {
+ output.print(lastTaskNodes[cNum] + "->" + tmpTaskNode);
+ }
+ if(tmpisTaskFinish.contains(cNum)) {
+ output.print(" [style=invis]");
+ }
+ output.println(";");
+ lastTaskNodes[cNum] = tmpTaskNode;
+ }
+ isTaskFinish[cNum] &= false;
+ break;
+ }
+
+ case Action.TASKABORT: {
+ if(!isfirst) {
+ tmpLabel.append("\\n");
+ }
+ tmpLabel.append("<" + taction.getTd().getSymbol() + "(");
+ /*Vector<Integer> taskparams = taction.getTaskParams();
+ for(int ii = 0; ii < taskparams.size(); ii++) {
+ tmpLabel.append(taskparams.elementAt(ii));
+ if(ii < taskparams.size() - 1) {
+ tmpLabel.append(",");
+ }
+ }*/
+ tmpLabel.append(")>aborts;");
+ if(!(lastTaskNodes[cNum].equals("first")) &&
+ (tmplastTasks.get(cNum).equals(taction.getTd().getSymbol()))) {
+ if(!(lastTaskNodes[cNum].equals(tmpTaskNode))) {
+ output.print("\t");
+ output.println(lastTaskNodes[cNum] + "->" + tmpTaskNode + ";");
+ lastTaskNodes[cNum] = tmpTaskNode;
+ }
+ if(tmpisset.contains(cNum)) {
+ isTaskFinish[cNum] &= true;
+ } else {
+ isTaskFinish[cNum] = true;
+ tmpisset.add(cNum);
+ }
+ lastTasks[cNum] = "";
+ } else {
+ throw new Exception("Error: unexpected task aborts");
+ }
+ break;
+ }
+
+ case Action.TASKREMOVE: {
+ if(!isfirst) {
+ tmpLabel.append("\\n");
+ }
+ tmpLabel.append("<" + taction.getTd().getSymbol() + "(");
+ /*Vector<Integer> taskparams = taction.getTaskParams();
+ for(int ii = 0; ii < taskparams.size(); ii++) {
+ tmpLabel.append(taskparams.elementAt(ii));
+ if(ii < taskparams.size() - 1) {
+ tmpLabel.append(",");
+ }
+ }*/
+ tmpLabel.append(")>removes;");
+ if(!(lastTaskNodes[cNum].equals("first")) &&
+ (tmplastTasks.get(cNum).equals(taction.getTd().getSymbol()))) {
+ if(!(lastTaskNodes[cNum].equals(tmpTaskNode))) {
+ output.print("\t");
+ output.println(lastTaskNodes[cNum] + "->" + tmpTaskNode + ";");
+ lastTaskNodes[cNum] = tmpTaskNode;
+ }
+ if(tmpisset.contains(cNum)) {
+ isTaskFinish[cNum] &= true;
+ } else {
+ isTaskFinish[cNum] = true;
+ tmpisset.add(cNum);
+ }
+ lastTasks[cNum] = "";
+ } else {
+ throw new Exception("Error: unexpected task remove");
+ }
+ break;
+ }
+ }
+ }
+ Enumeration<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("; ");
+ }
+ keys = null;
+ output.println("}");
+ output.print("\t");
+ tmplastTasks = null;
+ tmpisTaskFinish = null;
+ tmpisset = null;
+ actions = null;
+ tmpTaskNodes = null;
}
output.print("\t");
output.print("\t");
long max = 0;
long max2 = 0;
for(j = 1; j < timeNodes.size(); j++) {
- next = Long.parseLong(timeNodes.elementAt(j));
- long delta = next - prev;
- if(max < delta) {
- max2 = max;
- max = delta;
- } else if((max != delta) && (max2 < delta)) {
- max2 = delta;
- }
- prev = next;
+ next = Long.parseLong(timeNodes.elementAt(j));
+ long delta = next - prev;
+ if(max < delta) {
+ max2 = max;
+ max = delta;
+ } else if((max != delta) && (max2 < delta)) {
+ max2 = delta;
+ }
+ prev = next;
}
if(max2 == 0) {
- max2 = 1;
+ max2 = 1;
} else if(max/max2 > 100) {
- max2 = max/100;
+ max2 = max/100;
}
output.println("\"Time\"->" + timeNodes.elementAt(0) + "[style=invis];");
prev = Long.parseLong(timeNodes.elementAt(0));
next = 0;
for(j = 1; j < timeNodes.size(); j++) {
- next = Long.parseLong(timeNodes.elementAt(j));
- if(next - prev > max2) {
- do {
- output.print(prev + "->");
- prev += max2;
- } while(next - prev > max2);
- output.println(next + ";");
- } else {
- output.println("{rank=same; rankdir=LR; " + prev + "; " + next + "}");
- output.println(prev + "->" + next + "[style=invis];");
- }
- prev = next;
+ next = Long.parseLong(timeNodes.elementAt(j));
+ if(next - prev > max2) {
+ do {
+ output.print(prev + "->");
+ prev += max2;
+ } while(next - prev > max2);
+ output.println(next + ";");
+ } else {
+ output.println("{rank=same; rankdir=LR; " + prev + "; " + next + "}");
+ output.println(prev + "->" + next + "[style=invis];");
+ }
+ prev = next;
}
/*for(j = 0; j < time; j++) {
String dotnodeparams="";
for(int i = 0; i < criticalPath.size(); i++) {
- SimExecutionEdge seedge = criticalPath.elementAt(i);
- SimExecutionNode startnode = (SimExecutionNode)seedge.getSource();
- SimExecutionNode endnode = (SimExecutionNode)seedge.getTarget();
- if(!nodes.contains(startnode)) {
- label = startnode.getCoreNum() + ":" + startnode.getTimepoint();
- output.println("\t" + startnode.getLabel() + " [label=\""
- + label + "\" ];");
- nodes.addElement(startnode);
- }
- if(!nodes.contains(endnode)) {
- label = endnode.getCoreNum() + ":" + endnode.getTimepoint();
- output.println("\t" + endnode.getLabel() + " [label=\""
- + label + "\" ];");
- nodes.addElement(endnode);
- }
- output.println("\t" + startnode.getLabel() + " -> " + endnode.getLabel()
- + " [" + "label=\"" + seedge.getLabel() + "\"];");
+ SimExecutionEdge seedge = criticalPath.elementAt(i);
+ SimExecutionNode startnode = (SimExecutionNode)seedge.getSource();
+ SimExecutionNode endnode = (SimExecutionNode)seedge.getTarget();
+ if(!nodes.contains(startnode)) {
+ label = startnode.getCoreNum() + ":" + startnode.getTimepoint();
+ output.println("\t" + startnode.getLabel() + " [label=\""
+ + label + "\" ];");
+ nodes.addElement(startnode);
+ }
+ if(!nodes.contains(endnode)) {
+ label = endnode.getCoreNum() + ":" + endnode.getTimepoint();
+ output.println("\t" + endnode.getLabel() + " [label=\""
+ + label + "\" ];");
+ nodes.addElement(endnode);
+ }
+ output.println("\t" + startnode.getLabel() + " -> " + endnode.getLabel()
+ + " [" + "label=\"" + seedge.getLabel() + "\"];");
}
output.println("}");
output.close();
public long getBestStartPoint() {
if(this.bestStartPoint == -1) {
if((this.predicates != null) && (this.predicates.size() > 0)) {
- // have predicates
- long starttime = 0;
- // check the latest finish time of all the predicates
- for(int j = 0; j < this.predicates.size(); j++) {
- SimExecutionEdge predicate = this.predicates.elementAt(j);
- long tmptime = predicate.getBestStartPoint() + predicate.getWeight();
- if(tmptime > starttime) {
- starttime = tmptime;
- this.lastpredicateedge = predicate;
- if(predicate.getTd() != null) {
- this.lastpredicatenode = (SimExecutionNode)predicate.getTarget();
- } else {
- // transfer edge
- this.lastpredicatenode = (SimExecutionNode)predicate.getSource();
- }
- }
- }
- this.bestStartPoint = starttime;
+ // have predicates
+ long starttime = 0;
+ // check the latest finish time of all the predicates
+ for(int j = 0; j < this.predicates.size(); j++) {
+ SimExecutionEdge predicate = this.predicates.elementAt(j);
+ long tmptime = predicate.getBestStartPoint() + predicate.getWeight();
+ if(tmptime > starttime) {
+ starttime = tmptime;
+ this.lastpredicateedge = predicate;
+ if(predicate.getTd() != null) {
+ this.lastpredicatenode = (SimExecutionNode)predicate.getTarget();
+ } else {
+ // transfer edge
+ this.lastpredicatenode = (SimExecutionNode)predicate.getSource();
+ }
+ }
+ }
+ this.bestStartPoint = starttime;
} else {
- // no predicates
- this.bestStartPoint = 0;
+ // no predicates
+ this.bestStartPoint = 0;
}
}
return bestStartPoint;
public void addNewObj(ObjectSimulator newObj) {
if(this.newObjs == null) {
- this.newObjs = new Vector<ObjectSimulator>();
+ this.newObjs = new Vector<ObjectSimulator>();
}
this.newObjs.add(newObj);
public void init() {
finishTime = 0;
if(newObjs != null) {
- newObjs.clear();
+ newObjs.clear();
}
}
}
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);
- }
- }
- }
+ // 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);
+ }
+ }
+ }
}
}
}
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(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);
+ }
+ }
+ }
}
}
}
for(int i = 0; i < paraQueues.size(); i++) {
ObjectSimulator tpara = paraQueues.elementAt(i).peek();
if(tpara == null) {
- // the parameter is already removed, delete this task too
- finishTime = 800;
- this.currentRun.setFinishTime(finishTime);
- this.currentRun.setExetype(2);
- for(int j = 0; j < i; ++j) {
- tpara = this.paraQueues.elementAt(j).poll();
- if(tpara.isShared() && tpara.isHold()) {
- tpara.setHold(false);
- }
- this.paraQueues.elementAt(j).add(tpara);
- }
- return;
+ // the parameter is already removed, delete this task too
+ finishTime = 800;
+ this.currentRun.setFinishTime(finishTime);
+ this.currentRun.setExetype(2);
+ for(int j = 0; j < i; ++j) {
+ tpara = this.paraQueues.elementAt(j).poll();
+ if(tpara.isShared() && tpara.isHold()) {
+ tpara.setHold(false);
+ }
+ this.paraQueues.elementAt(j).add(tpara);
+ }
+ return;
}
if(tpara.isShared()) {
- if(tpara.isHold()) {
- // shared object held by other tasks
- finishTime = 800; // TODO currenly assume the effort on requesting locks are only 800
- /*this.currentRun.setFinishTime(finishTime);
- this.currentRun.setExetype(1);
- paraQueues.elementAt(i).poll();
- paraQueues.elementAt(i).add(tpara);
- for(int j = 0; j < i; ++j) {
- tpara = this.paraQueues.elementAt(j).poll();
- if(tpara.isShared() && tpara.isHold()) {
- tpara.setHold(false);
- }
- this.paraQueues.elementAt(j).add(tpara);
- }*/
- // remove it instead
- this.currentRun.setFinishTime(finishTime);
- this.currentRun.setExetype(2);
- paraQueues.elementAt(i).poll();
- // remove this object from the remaining parameter queues
- for(int j = i + 1; j < paraQueues.size(); j++) {
- paraQueues.elementAt(j).remove(tpara);
- }
- for(int j = 0; j < i; ++j) {
- tpara = this.paraQueues.elementAt(j).poll();
- if(tpara.isShared() && tpara.isHold()) {
- tpara.setHold(false);
- }
- this.paraQueues.elementAt(j).add(tpara);
- }
- return;
- } else if (tpara.getVersion() != this.objVersionTbl.get(tpara)) {
- // shared object has been updated and no longer fitted to this task
- finishTime = 800; // TODO currenly assume the effort on requesting locks are only 800
- this.currentRun.setFinishTime(finishTime);
- this.currentRun.setExetype(2);
- paraQueues.elementAt(i).poll();
- // remove this object from the remaining parameter queues
- for(int j = i + 1; j < paraQueues.size(); j++) {
- paraQueues.elementAt(j).remove(tpara);
- }
- for(int j = 0; j < i; ++j) {
- tpara = this.paraQueues.elementAt(j).poll();
- if(tpara.isShared() && tpara.isHold()) {
- tpara.setHold(false);
- }
- this.paraQueues.elementAt(j).add(tpara);
- }
- return;
- } else {
- tpara.setHold(true);
- }
+ if(tpara.isHold()) {
+ // shared object held by other tasks
+ finishTime = 800; // TODO currenly assume the effort on requesting locks are only 800
+ /*this.currentRun.setFinishTime(finishTime);
+ this.currentRun.setExetype(1);
+ paraQueues.elementAt(i).poll();
+ paraQueues.elementAt(i).add(tpara);
+ for(int j = 0; j < i; ++j) {
+ tpara = this.paraQueues.elementAt(j).poll();
+ if(tpara.isShared() && tpara.isHold()) {
+ tpara.setHold(false);
+ }
+ this.paraQueues.elementAt(j).add(tpara);
+ }*/
+ // remove it instead
+ this.currentRun.setFinishTime(finishTime);
+ this.currentRun.setExetype(2);
+ paraQueues.elementAt(i).poll();
+ // remove this object from the remaining parameter queues
+ for(int j = i + 1; j < paraQueues.size(); j++) {
+ paraQueues.elementAt(j).remove(tpara);
+ }
+ for(int j = 0; j < i; ++j) {
+ tpara = this.paraQueues.elementAt(j).poll();
+ if(tpara.isShared() && tpara.isHold()) {
+ tpara.setHold(false);
+ }
+ this.paraQueues.elementAt(j).add(tpara);
+ }
+ return;
+ } else if (tpara.getVersion() != this.objVersionTbl.get(tpara)) {
+ // shared object has been updated and no longer fitted to this task
+ finishTime = 800; // TODO currenly assume the effort on requesting locks are only 800
+ this.currentRun.setFinishTime(finishTime);
+ this.currentRun.setExetype(2);
+ paraQueues.elementAt(i).poll();
+ // remove this object from the remaining parameter queues
+ for(int j = i + 1; j < paraQueues.size(); j++) {
+ paraQueues.elementAt(j).remove(tpara);
+ }
+ for(int j = 0; j < i; ++j) {
+ tpara = this.paraQueues.elementAt(j).poll();
+ if(tpara.isShared() && tpara.isHold()) {
+ tpara.setHold(false);
+ }
+ this.paraQueues.elementAt(j).add(tpara);
+ }
+ return;
+ } else {
+ tpara.setHold(true);
+ }
}
// remove this object from the remaining parameter queues
for(int j = i + 1; j < paraQueues.size(); j++) {
- paraQueues.elementAt(j).remove(tpara);
+ paraQueues.elementAt(j).remove(tpara);
}
}
long ftime = 0;
finishTime += toexecute.getExeTime();
// TODO for test
if(ftime == 0) {
- ftime = toexecute.getExeTime();
+ ftime = toexecute.getExeTime();
} else if(ftime != toexecute.getExeTime()) {
- //System.err.println("error for simulation: " + td.getSymbol());
+ //System.err.println("error for simulation: " + td.getSymbol());
}
// TODO for test
/*if(td.getSymbol().equals("addIYLM")) {
}*/
if((toexecute.getNewObjInfoHashtable() != null)
&& (toexecute.getNewObjInfoHashtable().size() > 0)) {
- // have new objects
- Iterator it = toexecute.getNewObjInfoHashtable().keySet().iterator();
- int invokeNum = toexecute.getInvokeNum();
- while(it.hasNext()) {
- ClassDescriptor cd = (ClassDescriptor)it.next();
- NewObjInfo noi = toexecute.getNewObjInfo(cd);
- if(noi.getInvokeNum() < ((int)Math.round(((noi.getProbability() / 100) * noi.getNewRate() * invokeNum)))) {
- for(int j = 0; j < noi.getNewRate(); j++) {
- ObjectSimulator tmpObj = new ObjectSimulator(cd, noi.getRoot());
- this.currentRun.addNewObj(tmpObj);
- noi.incInvokeNum();
- }
- }
- }
+ // have new objects
+ Iterator it = toexecute.getNewObjInfoHashtable().keySet().iterator();
+ int invokeNum = toexecute.getInvokeNum();
+ while(it.hasNext()) {
+ ClassDescriptor cd = (ClassDescriptor)it.next();
+ NewObjInfo noi = toexecute.getNewObjInfo(cd);
+ if(noi.getInvokeNum() < ((int)Math.round(((noi.getProbability() / 100) * noi.getNewRate() * invokeNum)))) {
+ for(int j = 0; j < noi.getNewRate(); j++) {
+ ObjectSimulator tmpObj = new ObjectSimulator(cd, noi.getRoot());
+ this.currentRun.addNewObj(tmpObj);
+ noi.incInvokeNum();
+ }
+ }
+ }
}
tpara.applyEdge(toexecute);
tpara.increaseVersion();
while (it.hasNext()) {
FlagState fs = it.next();
if(fs.isSourceNode()) {
- for (Iterator allocit = ((Vector)fs.getAllocatingTasks()).iterator(); allocit.hasNext(); ) {
- TaskDescriptor alloctask=(TaskDescriptor)allocit.next();
- EGTaskNode srcnode=new EGTaskNode(alloctask.getSymbol(),alloctask, fs);
- nodes.add(srcnode);
- srcnode.setSource();
- for (Iterator edges = fs.edges(); edges.hasNext(); ) {
- FEdge edge = (FEdge)edges.next();
- EGTaskNode targetnode=getNode(edge, map, nodes);
- EGEdge newedge=new EGEdge(fs, targetnode);
- srcnode.addEdge(newedge);
- }
- }
+ for (Iterator allocit = ((Vector)fs.getAllocatingTasks()).iterator(); allocit.hasNext(); ) {
+ TaskDescriptor alloctask=(TaskDescriptor)allocit.next();
+ EGTaskNode srcnode=new EGTaskNode(alloctask.getSymbol(),alloctask, fs);
+ nodes.add(srcnode);
+ srcnode.setSource();
+ for (Iterator edges = fs.edges(); edges.hasNext(); ) {
+ FEdge edge = (FEdge)edges.next();
+ EGTaskNode targetnode=getNode(edge, map, nodes);
+ EGEdge newedge=new EGEdge(fs, targetnode);
+ srcnode.addEdge(newedge);
+ }
+ }
}
for(Iterator init=fs.inedges(); init.hasNext(); ) {
- FEdge inedge=(FEdge)init.next();
- EGTaskNode srcnode=getNode(inedge, map, nodes);
- for(Iterator outit=fs.edges(); outit.hasNext(); ) {
- FEdge outedge=(FEdge)outit.next();
- EGTaskNode dstnode=getNode(outedge, map, nodes);
- EGEdge newedge=new EGEdge(fs,dstnode);
- srcnode.addEdge(newedge);
- }
+ FEdge inedge=(FEdge)init.next();
+ EGTaskNode srcnode=getNode(inedge, map, nodes);
+ for(Iterator outit=fs.edges(); outit.hasNext(); ) {
+ FEdge outedge=(FEdge)outit.next();
+ EGTaskNode dstnode=getNode(outedge, map, nodes);
+ EGEdge newedge=new EGEdge(fs,dstnode);
+ srcnode.addEdge(newedge);
+ }
}
}
output.println("];");
for(Iterator it2 = tn.edges(); it2.hasNext(); ) {
- output.println("\t"+tn.getLabel()+" -> "+((EGTaskNode)((EGEdge)it2.next()).getTarget()).getLabel()+";");
+ output.println("\t"+tn.getLabel()+" -> "+((EGTaskNode)((EGEdge)it2.next()).getTarget()).getLabel()+";");
}
}
}
public boolean equals(Object o) {
if (o instanceof NewObjInfo) {
- NewObjInfo e=(NewObjInfo)o;
- if (e.newRate == this.newRate &&
- e.probability == this.probability &&
- e.invokeNum == this.invokeNum &&
- e.root.equals(this.root)) {
- return true;
- }
+ NewObjInfo e=(NewObjInfo)o;
+ if (e.newRate == this.newRate &&
+ e.probability == this.probability &&
+ e.invokeNum == this.invokeNum &&
+ e.root.equals(this.root)) {
+ return true;
+ }
}
return false;
}
e.executeTime == executeTime &&
e.m_taskexitindex == m_taskexitindex &&
e.m_isbackedge == m_isbackedge) {
- if(this.newObjInfos != null) {
- if(e.newObjInfos == null) {
- return false;
- } else {
- return e.newObjInfos.equals(this.newObjInfos);
- }
- }
- return true;
+ if(this.newObjInfos != null) {
+ if(e.newObjInfos == null) {
+ return false;
+ } else {
+ return e.newObjInfos.equals(this.newObjInfos);
+ }
+ }
+ return true;
}
}
return false;
if(this.newObjInfos != null) {
Iterator<NewObjInfo> it_nobjs = this.newObjInfos.values().iterator();
while(it_nobjs.hasNext()) {
- it_nobjs.next().invokeNum = 0;
+ it_nobjs.next().invokeNum = 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();
+ 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()];
if (set) {
int count=0;
if (tags.containsKey(tag))
- count=tags.get(tag).intValue();
+ count=tags.get(tag).intValue();
if (count<KLIMIT)
- count++;
+ 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();
+ count=tags.get(tag).intValue();
newtags1.put(tag, new Integer(count));
if ((count+1)==KLIMIT)
- return new FlagState[] {this, new FlagState(newset1, cd, newtags1)};
+ return new FlagState[] {this, new FlagState(newset1, cd, newtags1)};
else
- return new FlagState[] {new FlagState(newset1, cd, newtags1)};
+ return new FlagState[] {new FlagState(newset1, cd, newtags1)};
}
}
switch (tags.get(tag).intValue()) {
case ONETAG:
- newtags1.put(tag,new Integer(MULTITAGS));
- return new FlagState[] {this, new FlagState(newset1, cd, newtags1)};
+ newtags1.put(tag,new Integer(MULTITAGS));
+ return new FlagState[] {this, new FlagState(newset1, cd, newtags1)};
case MULTITAGS:
- return new FlagState[] {this};
+ return new FlagState[] {this};
default:
- throw new Error();
+ throw new Error();
}
} else {
newtags1.put(tag,new Integer(ONETAG));
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)};
+ 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)};
+ //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();
+ throw new Error();
}
} else {
throw new Error("Invalid Operation: Can not clear a tag that doesn't exist.");
StringBuffer sb = new StringBuffer(flagstate.size());
for(int i=0; i < flags.length; i++) {
if (get(flags[i]))
- sb.append(1);
+ sb.append(1);
else
- sb.append(0);
+ sb.append(0);
}
return new String(sb);
if (o instanceof FlagState) {
FlagState fs=(FlagState)o;
if (fs.cd!=cd)
- return false;
+ return false;
if(fs.byObj != this.byObj) {
- return false;
+ return false;
}
return (fs.flagstate.equals(flagstate) & fs.tags.equals(tags));
}
for(Iterator it=getFlags(); it.hasNext(); ) {
FlagDescriptor fd=(FlagDescriptor) it.next();
if (label==null)
- label=fd.toString();
+ label=fd.toString();
else
- label+=", "+fd.toString();
+ label+=", "+fd.toString();
}
for (Enumeration en_tags=getTags(); en_tags.hasMoreElements(); ) {
TagDescriptor td=(TagDescriptor)en_tags.nextElement();
switch (tags.get(td).intValue()) {
case ONETAG:
- if (label==null)
- label=td.toString()+"(1)";
- else
- label+=", "+td.toString()+"(1)";
- break;
+ if (label==null)
+ label=td.toString()+"(1)";
+ else
+ label+=", "+td.toString()+"(1)";
+ break;
case MULTITAGS:
- if (label==null)
- label=td.toString()+"(n)";
- else
- label+=", "+td.toString()+"(n)";
- break;
+ if (label==null)
+ label=td.toString()+"(n)";
+ else
+ label+=", "+td.toString()+"(n)";
+ break;
default:
- break;
+ break;
}
}
if (label==null)
public long getExeTime() {
try {
if(this.executeTime == -1) {
- if(this.visited4time == -1) {
- this.visited4time = 0;
- calExeTime();
- } else {
- // visited, this node is in a loop
- // TODO
- // currently set 10 as the largest time
- this.executeTime = FlagState.MAXTIME;
- }
+ if(this.visited4time == -1) {
+ this.visited4time = 0;
+ calExeTime();
+ } else {
+ // visited, this node is in a loop
+ // TODO
+ // currently set 10 as the largest time
+ this.executeTime = FlagState.MAXTIME;
+ }
}
} catch (Exception e) {
e.printStackTrace();
if(it.hasNext()) {
FEdge fe = (FEdge)it.next();
while((fe != null) && (fe.getTarget().equals(this))) {
- if(it.hasNext()) {
- fe = (FEdge)it.next();
- } else {
- fe = null;
- }
+ if(it.hasNext()) {
+ fe = (FEdge)it.next();
+ } else {
+ fe = null;
+ }
}
if(fe == null) {
- this.executeTime = 0;
+ this.executeTime = 0;
} else {
- if(fe.getExeTime() == -1) {
- throw new Exception("Error: Uninitiate FEdge!");
- }
- this.executeTime = fe.getExeTime() + ((FlagState)fe.getTarget()).getExeTime();
+ if(fe.getExeTime() == -1) {
+ throw new Exception("Error: Uninitiate FEdge!");
+ }
+ this.executeTime = fe.getExeTime() + ((FlagState)fe.getTarget()).getExeTime();
}
} else {
this.executeTime = 0;
FEdge fe = (FEdge)it.next();
long temp = fe.getExeTime() + ((FlagState)fe.getTarget()).getExeTime();
if(temp < this.executeTime) {
- this.executeTime = temp;
+ this.executeTime = temp;
}
}
}
for(int i = 0; i < this.edges.size(); i++) {
next = (FEdge) this.edges.elementAt(i);
if(this.byObj == 0) {
- next.setExpInvokeNum((int)(Math.ceil(this.invokeNum * next.getProbability() / 100)));
+ next.setExpInvokeNum((int)(Math.ceil(this.invokeNum * next.getProbability() / 100)));
} else {
- next.setExpInvokeNum((int)(Math.ceil(((this.invokeNum - 1) / this.byObj + 1) * next.getProbability() / 100)));
+ next.setExpInvokeNum((int)(Math.ceil(((this.invokeNum - 1) / this.byObj + 1) * next.getProbability() / 100)));
}
}
int temp = (this.byObj == 0)?next.getInvokeNumGap():next.getInvokeNumGapByObj(this.byObj);
boolean exchange = false;
if((temp > gap) && (next.getTask().equals(td))) {
- exchange = true;
+ exchange = true;
} else if(temp == gap) {
- if(next.getProbability() > prob) {
- exchange = true;
- } else if(next.getProbability() == prob) {
- if(!isbackedge && next.isbackedge()) {
- // backedge has higher priority
- exchange = true;
- }
- }
+ if(next.getProbability() > prob) {
+ exchange = true;
+ } else if(next.getProbability() == prob) {
+ if(!isbackedge && next.isbackedge()) {
+ // backedge has higher priority
+ exchange = true;
+ }
+ }
}
if(exchange) {
- index = i;
- gap = temp;
- prob = next.getProbability();
- isbackedge = next.isbackedge();
+ index = i;
+ gap = temp;
+ prob = next.getProbability();
+ isbackedge = next.isbackedge();
}
}
next = (FEdge) this.edges.elementAt(index);
for(Iterator it=state.getClassSymbolTable().getDescriptorsIterator(); it.hasNext(); ) {
ClassDescriptor cd=(ClassDescriptor) it.next();
if (taskanalysis.getFlagStates(cd)==null)
- continue;
+ continue;
analyzeClass(cd);
}
}
for(Iterator fsit=flagstatenodes.iterator(); fsit.hasNext(); ) {
FlagState fs=(FlagState)fsit.next();
if (fs.numedges()==0)
- garbage.add(fs);
+ garbage.add(fs);
}
Stack tovisit=new Stack();
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);
- }
+ Edge e=fs.getinedge(i);
+ FlagState fsnew=(FlagState) e.getSource();
+ if (!possiblegarbage.contains(fsnew)) {
+ possiblegarbage.add(fsnew);
+ tovisit.push(fsnew);
+ }
}
}
garbagestates.addAll(garbage);
otd.enterflagstates.equals(enterflagstates)&&
otd.predicate.equals(predicate)&&
otd.index==index)
- return true;
+ return true;
}
return false;
}
if (vardescriptors.equals(p.vardescriptors)&&
flags.equals(p.flags)&&
tags.equals(p.tags))
- return true;
+ return true;
}
return false;
}
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);
+ if (!table.containsKey(node.getFS()))
+ table.put(node.getFS(), new HashSet<EGTaskNode>());
+ table.get(node.getFS()).add(node);
}
}
return table;
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());
+ if (!table.containsKey(node.getPostFS()))
+ table.put(node.getPostFS(), new HashSet<FlagState>());
+ table.get(node.getPostFS()).add(node.getFS());
}
}
return table;
while (classit.hasMoreElements()) {
ClassDescriptor cd=(ClassDescriptor)classit.nextElement();
if (!executiongraph.containsKey(cd))
- continue;
+ continue;
Hashtable<FlagState, Set<OptionalTaskDescriptor>> fstootd=new Hashtable<FlagState, Set<OptionalTaskDescriptor>>();
safeexecution.put(cd, fstootd);
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);
+ 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();
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);
+ 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>();
+ //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>();
- }
+ 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>();
+ 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);
- }
+ //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);
+ }
}
}
fstootd.put(fs, set);
//Requeue all flagstates that may use our updated results
if (fsusemap.containsKey(fs)) {
- tovisit.addAll(fsusemap.get(fs));
+ tovisit.addAll(fsusemap.get(fs));
}
}
fstotimap.put(fs, timap);
for(Iterator b_it = B.iterator(); b_it.hasNext(); ) {
OptionalTaskDescriptor otd_b = (OptionalTaskDescriptor)b_it.next();
for(Iterator a_it = A.iterator(); a_it.hasNext(); ) {
- OptionalTaskDescriptor otd_a = (OptionalTaskDescriptor)a_it.next();
- if(otd_a.td==otd_b.td&&
- otd_a.getIndex()==otd_b.getIndex()) {
- HashSet newfs = new HashSet();
- newfs.addAll(otd_a.enterflagstates);
- newfs.addAll(otd_b.enterflagstates);
- OptionalTaskDescriptor newotd = new OptionalTaskDescriptor(otd_b.td, otd_b.getIndex(), newfs, combinePredicates(otd_a.predicate, otd_b.predicate));
- if(optionaltaskdescriptors.get(cd).get(newotd)!=null) {
- newotd = optionaltaskdescriptors.get(cd).get(newotd);
- } else {
- newotd.setuid();
- resultingFS(newotd);
- optionaltaskdescriptors.get(cd).put(newotd, newotd);
- }
- result.add(newotd);
- }
+ OptionalTaskDescriptor otd_a = (OptionalTaskDescriptor)a_it.next();
+ if(otd_a.td==otd_b.td&&
+ otd_a.getIndex()==otd_b.getIndex()) {
+ HashSet newfs = new HashSet();
+ newfs.addAll(otd_a.enterflagstates);
+ newfs.addAll(otd_b.enterflagstates);
+ OptionalTaskDescriptor newotd = new OptionalTaskDescriptor(otd_b.td, otd_b.getIndex(), newfs, combinePredicates(otd_a.predicate, otd_b.predicate));
+ if(optionaltaskdescriptors.get(cd).get(newotd)!=null) {
+ newotd = optionaltaskdescriptors.get(cd).get(newotd);
+ } else {
+ newotd.setuid();
+ resultingFS(newotd);
+ optionaltaskdescriptors.get(cd).put(newotd, newotd);
+ }
+ result.add(newotd);
+ }
}
}
return result;
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
- }
- }
+ FlatFlagActionNode ffan=(FlatFlagActionNode)fn;
+ if (ffan.getTaskType() == FlatFlagActionNode.TASKEXIT) {
+ for(Iterator it_tfp=ffan.getTempFlagPairs(); it_tfp.hasNext(); ) {
+ TempFlagPair tfp=(TempFlagPair)it_tfp.next();
+ TempDescriptor tempd = tfp.getTemp();
+ if(tempd!=tmp)
+ return false; //return false if a taskexit modifies one of the other parameters
+ }
+ }
}
}
return true;
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));
+ 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;
for(Iterator varit = c.iterator(); varit.hasNext(); ) { //maybe change that
VarDescriptor vd = (VarDescriptor)varit.next();
if(result.vardescriptors.contains(vd))
- System.out.println("Already in ");
+ System.out.println("Already in ");
else {
- result.vardescriptors.add(vd);
+ result.vardescriptors.add(vd);
}
}
Collection vardesc = result.vardescriptors;
VarDescriptor vd = (VarDescriptor)varit.next();
HashSet bflags = B.flags.get(vd);
if( bflags == null ) {
- continue;
+ continue;
} else {
- if (result.flags.containsKey(vd))
- ((HashSet)result.flags.get(vd)).addAll(bflags);
- else
- result.flags.put(vd, bflags);
+ if (result.flags.containsKey(vd))
+ ((HashSet)result.flags.get(vd)).addAll(bflags);
+ else
+ result.flags.put(vd, bflags);
}
TagExpressionList btags = B.tags.get(vd);
if( btags != null ) {
- if (result.tags.containsKey(vd))
- System.out.println("Tag found but there should be nothing to do because same tag");
- else
- result.tags.put(vd, btags);
+ if (result.tags.containsKey(vd))
+ System.out.println("Tag found but there should be nothing to do because same tag");
+ else
+ result.tags.put(vd, btags);
}
}
return result;
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
- }
+ 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);
+ 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);
- }
+ FlatNode fnext=fn1.getNext(i);
+ if (!discovered.contains(fnext)) {
+ discovered.add(fnext);
+ nodestack.push(fnext);
+ }
}
}
otd.exitfses=result;
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------------");
- }
+ 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------------");
+ 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------------");
}
}
}
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
- }
+ 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);
- }
+ FlatNode fnext=fn1.getNext(i);
+ if (!discovered.contains(fnext)) {
+ discovered.add(fnext);
+ nodestack.push(fnext);
+ }
}
}
return false;
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");
+ if (tn.isMultipleParams())
+ output.println(", shape = tripleoctagon");
+ else
+ output.println(", shape=doubleoctagon");
} else if (tn.isMultipleParams())
- output.println(", shape=octagon");
+ 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()+";");
+ EGTaskNode tn2 = (EGTaskNode)((Edge)it2.next()).getTarget();
+ output.println("\t"+tn.getLabel()+" -> "+tn2.getLabel()+";");
}
}
}
Set component=scc.getSCC(i);
HashSet flagset=new HashSet();
for(Iterator compit=component.iterator(); compit.hasNext(); ) {
- TagBinding tb=(TagBinding)compit.next();
- flagset.addAll(tb.getAllocations());
- for(Iterator edgeit=tb.edges(); edgeit.hasNext(); ) {
- Edge e=(Edge)edgeit.next();
- TagBinding tb2=(TagBinding)e.getTarget();
- flagset.addAll(tb2.getAllocations());
- }
+ TagBinding tb=(TagBinding)compit.next();
+ flagset.addAll(tb.getAllocations());
+ for(Iterator edgeit=tb.edges(); edgeit.hasNext(); ) {
+ Edge e=(Edge)edgeit.next();
+ TagBinding tb2=(TagBinding)e.getTarget();
+ flagset.addAll(tb2.getAllocations());
+ }
}
for(Iterator compit=component.iterator(); compit.hasNext(); ) {
- TagBinding tb=(TagBinding)compit.next();
- tb.getAllocations().addAll(flagset);
+ TagBinding tb=(TagBinding)compit.next();
+ tb.getAllocations().addAll(flagset);
}
}
HashSet roottags=(HashSet)tasktotagbindings.get(task);
HashSet taskflags=(HashSet)tasktoflagstates.get(task);
for(Iterator tagit=roottags.iterator(); tagit.hasNext(); ) {
- TagBinding tb=(TagBinding)tagit.next();
- taskflags.addAll(tb.getAllocations());
+ TagBinding tb=(TagBinding)tagit.next();
+ taskflags.addAll(tb.getAllocations());
}
}
}
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);
- }
+ 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);
- }
- }
- }
+ 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);
+ }
+ }
+ }
}
}
}
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);
- }
- }
+ 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);
+ TagBinding newtag=(TagBinding)tagit.next();
+ Edge e=new Edge(newtag);
+ tb.addEdge(e);
}
}
}
if (o instanceof TagBinding) {
TagBinding tb=(TagBinding)o;
if (md!=tb.md)
- return false;
+ 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;
+ 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;
int hashcode=md.hashCode();
for(int i=0; i<tdarray.length; i++) {
if (tdarray[i]!=null)
- hashcode^=tdarray[i].hashCode();
+ hashcode^=tdarray[i].hashCode();
}
return hashcode;
}
TagEdge e=(TagEdge)o;
if (e.target.equals(target)&&
e.td==td)
- return true;
+ return true;
}
return false;
}
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 flags.equals(t.flags);
}
}
return false;
/* Adding the flags of the super class */
ClassDescriptor tmp=cd;
while(tmp!=null) {
- for(Iterator it_cflags=tmp.getFlags(); it_cflags.hasNext(); ) {
- FlagDescriptor fd = (FlagDescriptor)it_cflags.next();
- vFlags.add(fd);
- }
- tmp=tmp.getSuperDesc();
+ for(Iterator it_cflags=tmp.getFlags(); it_cflags.hasNext(); ) {
+ FlagDescriptor fd = (FlagDescriptor)it_cflags.next();
+ vFlags.add(fd);
+ }
+ tmp=tmp.getSuperDesc();
}
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);
+ 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);
}
}
String taskname=td.getSymbol();
if(!tdToFEdges.containsKey(td)) {
- tdToFEdges.put(td, new Vector<FEdge>());
+ tdToFEdges.put(td, new Vector<FEdge>());
}
/** counter to keep track of the number of parameters (of the
int parameterindex=0;
for(int i=0; i < td.numParameters(); i++) {
- FlagExpressionNode fen=td.getFlag(td.getParameter(i));
- TagExpressionList tel=td.getTag(td.getParameter(i));
-
- /** Checking to see if the parameter is of the same
- * type/class as the flagstate's and also if the
- * flagstate fs triggers the given task*/
-
- if (typeutil.isSuperorType(td.getParamType(i).getClassDesc(),cd)
- && isTaskTrigger_flag(fen,fs)
- && isTaskTrigger_tag(tel,fs)) {
- temp=fm.getParameter(i);
- parameterindex=i;
- trigger_ctr++;
- }
+ FlagExpressionNode fen=td.getFlag(td.getParameter(i));
+ TagExpressionList tel=td.getTag(td.getParameter(i));
+
+ /** Checking to see if the parameter is of the same
+ * type/class as the flagstate's and also if the
+ * flagstate fs triggers the given task*/
+
+ if (typeutil.isSuperorType(td.getParamType(i).getClassDesc(),cd)
+ && isTaskTrigger_flag(fen,fs)
+ && isTaskTrigger_tag(tel,fs)) {
+ temp=fm.getParameter(i);
+ parameterindex=i;
+ trigger_ctr++;
+ }
}
if (trigger_ctr==0) //Look at next task
- continue;
+ continue;
if (trigger_ctr>1)
- System.out.println("Illegal Operation: A single flagstate cannot satisfy more than one parameter of a task:"+fs + " in "+td);
+ System.out.println("Illegal Operation: A single flagstate cannot satisfy more than one parameter of a task:"+fs + " in "+td);
Set newstates=taganalysis.getFlagStates(td);
for(Iterator fsit=newstates.iterator(); fsit.hasNext(); ) {
- FlagState fsnew=(FlagState) fsit.next();
- System.out.println("SOURCE:"+fsnew);
-
- if (!((Hashtable<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);
-
- if(!((Vector)cdtorootnodes.get(fsnew.getClassDescriptor())).contains(fsnew)) {
- ((Vector)cdtorootnodes.get(fsnew.getClassDescriptor())).add(fsnew);
- }
+ FlagState fsnew=(FlagState) fsit.next();
+ System.out.println("SOURCE:"+fsnew);
+
+ if (!((Hashtable<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);
+
+ if(!((Vector)cdtorootnodes.get(fsnew.getClassDescriptor())).contains(fsnew)) {
+ ((Vector)cdtorootnodes.get(fsnew.getClassDescriptor())).add(fsnew);
+ }
}
Stack nodestack=new Stack();
//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);
- newedge.setisbackedge(true);
- continue;
- } else if (fn1.kind()==FKind.FlatFlagActionNode) {
- FlatFlagActionNode ffan=(FlatFlagActionNode)fn1;
- if (ffan.getTaskType() == FlatFlagActionNode.PRE) {
- if (ffan.getTempFlagPairs().hasNext()||ffan.getTempTagPairs().hasNext())
- throw new Error("PRE FlagActions not supported");
-
- } else if (ffan.getTaskType() == FlatFlagActionNode.TASKEXIT) {
- Vector<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);
- newedge.setTaskExitIndex(ffan.getTaskExitIndex());
- ((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);
- }
- }
+ 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);
+ newedge.setisbackedge(true);
+ continue;
+ } else if (fn1.kind()==FKind.FlatFlagActionNode) {
+ FlatFlagActionNode ffan=(FlatFlagActionNode)fn1;
+ if (ffan.getTaskType() == FlatFlagActionNode.PRE) {
+ if (ffan.getTempFlagPairs().hasNext()||ffan.getTempTagPairs().hasNext())
+ throw new Error("PRE FlagActions not supported");
+
+ } else if (ffan.getTaskType() == FlatFlagActionNode.TASKEXIT) {
+ Vector<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);
+ newedge.setTaskExitIndex(ffan.getTaskExitIndex());
+ ((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);
+ }
+ }
}
}
}
else
switch (((FlagOpNode)fen).getOp().getOp()) {
case Operation.LOGIC_AND:
- return ((isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)) && (isTaskTrigger_flag(((FlagOpNode)fen).getRight(),fs)));
+ return ((isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)) && (isTaskTrigger_flag(((FlagOpNode)fen).getRight(),fs)));
case Operation.LOGIC_OR:
- return ((isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)) || (isTaskTrigger_flag(((FlagOpNode)fen).getRight(),fs)));
+ return ((isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)) || (isTaskTrigger_flag(((FlagOpNode)fen).getRight(),fs)));
case Operation.LOGIC_NOT:
- return !(isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs));
+ return !(isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs));
default:
- return false;
+ return false;
}
}
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;
- }
+ switch (fs.getTagCount(tel.getType(i))) {
+ case FlagState.ONETAG:
+ case FlagState.MULTITAGS:
+ break;
+
+ case FlagState.NOTAGS:
+ return false;
+ }
}
}
return true;
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));
+ fstemp=fstemp.setFlag(tfp.getFlag(),ffan.getFlagChange(tfp));
}
//Process the tag changes
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);
- }
+ 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
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);
- }
+ 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;
for(int k=0; k<noOfIterations; k++) {
for(int j=0; j < externs; j++) {
- if ((k% (1<<j)) == 0)
- BoolValTable[j]=(!BoolValTable[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]);
+ fstemp=fstemp.setFlag(fd[i],BoolValTable[i]);
}
if (!sourcenodes.containsKey(fstemp))
- toprocess.add(fstemp);
+ toprocess.add(fstemp);
fstemp=canonicalizeFlagState(sourcenodes,fstemp);
fs.addEdge(new FEdge(fstemp,"Runtime", null, -1));
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);
- }
+ 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);
+ }
}
return true;
}
for(Iterator classit=state.getClassSymbolTable().getDescriptorsIterator(); classit.hasNext(); ) {
ClassDescriptor cd=(ClassDescriptor) classit.next();
if (cd.hasFlags())
- produceTaskNodes(cd);
+ produceTaskNodes(cd);
}
produceAllTaskNodes();
}
ClassDescriptor cd=(ClassDescriptor) it_classes.next();
Set tasknodes=getTaskNodes(cd);
if (tasknodes!=null) {
- try {
- File dotfile_tasknodes=new File("graph"+cd.getSymbol()+"_task.dot");
- FileOutputStream dotstream=new FileOutputStream(dotfile_tasknodes,true);
- TaskNode.DOTVisitor.visit(dotstream,tasknodes);
- } catch(Exception e) {
- e.printStackTrace();
- throw new Error();
- }
+ try {
+ File dotfile_tasknodes=new File("graph"+cd.getSymbol()+"_task.dot");
+ FileOutputStream dotstream=new FileOutputStream(dotfile_tasknodes,true);
+ TaskNode.DOTVisitor.visit(dotstream,tasknodes);
+ } catch(Exception e) {
+ e.printStackTrace();
+ throw new Error();
+ }
}
}
}
TaskNode tn,sn;
if (fs.isSourceNode()) {
- Vector src=fs.getAllocatingTasks();
- for(Iterator it2=src.iterator(); it2.hasNext(); ) {
- TaskDescriptor td=(TaskDescriptor)it2.next();
- sn=new TaskNode(td.getSymbol());
- if(fs.edges().hasNext()) {
- addEdges(fs,sn,tasknodes);
- }
- }
+ Vector src=fs.getAllocatingTasks();
+ for(Iterator it2=src.iterator(); it2.hasNext(); ) {
+ TaskDescriptor td=(TaskDescriptor)it2.next();
+ sn=new TaskNode(td.getSymbol());
+ if(fs.edges().hasNext()) {
+ addEdges(fs,sn,tasknodes);
+ }
+ }
}
while(it_inedges.hasNext()) {
- FEdge inedge=(FEdge)it_inedges.next();
- tn=new TaskNode(inedge.getLabel());
- if(fs.edges().hasNext()) {
- addEdges(fs,tn,tasknodes);
- }
+ FEdge inedge=(FEdge)it_inedges.next();
+ tn=new TaskNode(inedge.getLabel());
+ if(fs.edges().hasNext()) {
+ addEdges(fs,tn,tasknodes);
+ }
}
}
}
Set fsnodes;
if (cd.hasFlags()&&((fsnodes=taskanalysis.getFlagStates(cd))!=null)) {
- //
- System.out.println("\nWorking on fses of Class: "+cd.getSymbol());
- //
- for(Iterator it=fsnodes.iterator(); it.hasNext(); ) {
- FlagState fs=(FlagState)it.next();
- //
- System.out.println("Evaluating fs: "+fs.getTextLabel());
- //
- Iterator it_inedges=fs.inedges();
- TaskNode tn,sn;
-
-
- if (fs.isSourceNode()) {
- //
- System.out.println("A sourcenode");
- //
- if(fs.edges().hasNext()) {
- Vector allocatingtasks=fs.getAllocatingTasks();
- //
- if (allocatingtasks.iterator().hasNext())
- System.out.println("has been allocated by "+allocatingtasks.size()+" tasks");
- //
- for(Iterator it_at=allocatingtasks.iterator(); it_at.hasNext(); ) {
- TaskDescriptor allocatingtd=(TaskDescriptor)it_at.next();
- //
- System.out.println(allocatingtd.getSymbol());
- //
- tn=new TaskNode(allocatingtd.getSymbol());
-
- addEdges(fs,tn,alltasknodes,ColorID);
- }
- }
- }
-
- while(it_inedges.hasNext()) {
- FEdge inedge=(FEdge)it_inedges.next();
- tn=new TaskNode(inedge.getLabel());
- if(fs.edges().hasNext()) {
- addEdges(fs,tn,alltasknodes,ColorID);
- }
- }
- }
- ColorID++;
+ //
+ System.out.println("\nWorking on fses of Class: "+cd.getSymbol());
+ //
+ for(Iterator it=fsnodes.iterator(); it.hasNext(); ) {
+ FlagState fs=(FlagState)it.next();
+ //
+ System.out.println("Evaluating fs: "+fs.getTextLabel());
+ //
+ Iterator it_inedges=fs.inedges();
+ TaskNode tn,sn;
+
+
+ if (fs.isSourceNode()) {
+ //
+ System.out.println("A sourcenode");
+ //
+ if(fs.edges().hasNext()) {
+ Vector allocatingtasks=fs.getAllocatingTasks();
+ //
+ if (allocatingtasks.iterator().hasNext())
+ System.out.println("has been allocated by "+allocatingtasks.size()+" tasks");
+ //
+ for(Iterator it_at=allocatingtasks.iterator(); it_at.hasNext(); ) {
+ TaskDescriptor allocatingtd=(TaskDescriptor)it_at.next();
+ //
+ System.out.println(allocatingtd.getSymbol());
+ //
+ tn=new TaskNode(allocatingtd.getSymbol());
+
+ addEdges(fs,tn,alltasknodes,ColorID);
+ }
+ }
+ }
+
+ while(it_inedges.hasNext()) {
+ FEdge inedge=(FEdge)it_inedges.next();
+ tn=new TaskNode(inedge.getLabel());
+ if(fs.edges().hasNext()) {
+ addEdges(fs,tn,alltasknodes,ColorID);
+ }
+ }
+ }
+ ColorID++;
}
}
TEdge newedge=new TEdge(target);
if (!tn.edgeExists(newedge))
- tn.addEdge(newedge);
+ tn.addEdge(newedge);
}
}
TEdge newedge=new TEdge(target);
newedge.setDotNodeParameters("style=bold, color = "+colors[ColorID]);
if (!tn.edgeExists(newedge))
- tn.addEdge(newedge);
+ tn.addEdge(newedge);
}
}
if (o instanceof TaskIndex) {
TaskIndex ti=(TaskIndex) o;
if (ti.runtime==runtime)
- return true;
+ return true;
if (ti.index==index && ti.td==td)
- return true;
+ return true;
}
return false;
}
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);
- }
+ for(int j=0; j<tel.numTags(); j++) {
+ TempDescriptor tagtmp=tel.getTemp(j);
+ if (!tags.contains(tagtmp))
+ tags.add(tagtmp);
+ }
}
}
private void init() {
for(int i=ftsarray.length-1; i>=0; i--) {
if (i!=index)
- itarray[i]=tq.parameterset[i].iterator();
+ itarray[i]=tq.parameterset[i].iterator();
VarDescriptor vd=tq.task.getParameter(i);
TagExpressionList tel=tq.task.getTag(vd);
if (tel!=null)
- for(int j=0; j<tel.numTags(); j++) {
- TempDescriptor tmp=tel.getTemp(j);
- if (!tsindexarray.containsKey(tmp)) {
- tsindexarray.put(tmp, new Integer(i));
- }
- }
+ for(int j=0; j<tel.numTags(); j++) {
+ TempDescriptor tmp=tel.getTemp(j);
+ if (!tsindexarray.containsKey(tmp)) {
+ tsindexarray.put(tmp, new Integer(i));
+ }
+ }
}
}
if (needinit) {
i=ftsarray.length-1;
if (i!=index)
- ftsarray[i]=itarray[i].next();
+ ftsarray[i]=itarray[i].next();
} else {
i=0;
}
TagExpressionList tel=td.getTag(vd);
int j;
if (needinit) {
- j=(tel!=null)&&tel.numTags()>0?tel.numTags()-1:0;
- needinit=false;
+ j=(tel!=null)&&tel.numTags()>0?tel.numTags()-1:0;
+ needinit=false;
} else
- j=0;
+ j=0;
tagloop:
for(; tel!=null&&j<tel.numTags(); j++) {
- TempDescriptor tmp=tel.getTemp(j);
- TagState currtag=tsarray.get(tmp);
- String type=tel.getType(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 (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;
+ 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
- }
+ 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
+ }
} else {
- throw new Error();
+ throw new Error();
}
}
return false;
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);
+ 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);
+ 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();
toprocess.remove(ts);
//Loop through each task
for(Iterator taskit=state.getTaskSymbolTable().getDescriptorsIterator(); taskit.hasNext(); ) {
- TaskDescriptor td=(TaskDescriptor)taskit.next();
- TaskQueue tq=tasktable.get(td);
- processTask(td, tq, ts);
+ TaskDescriptor td=(TaskDescriptor)taskit.next();
+ TaskQueue tq=tasktable.get(td);
+ processTask(td, tq, ts);
}
}
}
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();
- }
- }
+ 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();
+ }
+ }
}
}
}
//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);
- }
+ 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);
- }
+ 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;
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]));
- }
- }
- }
- }
+ 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;
+ System.out.println("Tag already bound to object.");
+ return;
}
} else {
if (!ow.tags.contains(twnew)) {
- System.out.println("Tag not bound to object.");
- return;
+ System.out.println("Tag not bound to object.");
+ return;
}
}
HashSet<FlagState> newfsstates=new HashSet<FlagState>();
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]));
- }
- }
- }
- }
- }
+ 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;
}
{
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]));
- }
+ 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;
}
boolean newtagstate=fn.getTagChange(ttp);
ObjWrapper ow=(ObjWrapper)table.get(tmp);
if (!newtagstate)
- setTag(ow, tagw, tag, newtagstate);
+ setTag(ow, tagw, tag, newtagstate);
}
//Do the flags next
boolean newtagstate=fn.getTagChange(ttp);
ObjWrapper ow=(ObjWrapper)table.get(tmp);
if (newtagstate)
- setTag(ow, tagw, tag, newtagstate);
+ setTag(ow, tagw, tag, newtagstate);
}
}
/* Compute type */
Iterator it=fn.getTempFlagPairs();
if (it.hasNext()) {
- TempFlagPair tfp=(TempFlagPair)it.next();
- fntemp=tfp.getTemp();
+ 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();
+ 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()));
boolean newtagstate=fn.getTagChange(ttp);
assert(ow==table.get(tmp));
if (newtagstate)
- setTag(ow, tagw, tag, newtagstate);
+ setTag(ow, tagw, tag, newtagstate);
else
- throw new Error("Can't clear tag in newly allocated object");
+ throw new Error("Can't clear tag in newly allocated object");
}
for(Iterator<FlagState> fsit=ow.fs.iterator(); fsit.hasNext(); ) {
FlagState fs2=fsit.next();
ts2.addSource(td);
addresult(fs2.getClassDescriptor(), ts2);
if (!discovered.contains(ts2)) {
- discovered.add(ts2);
- toprocess.add(ts2);
+ discovered.add(ts2);
+ toprocess.add(ts2);
}
}
}
for(Iterator<TagState> tsit=tw.ts.iterator(); tsit.hasNext(); ) {
TagState ts=tsit.next();
if (init==null) {
- ts.addSource(td);
+ ts.addSource(td);
} else {
- TagEdge te=new TagEdge(ts, td);
- if (!init.containsEdge(te)) {
- init.addEdge(te);
- }
+ TagEdge te=new TagEdge(ts, td);
+ if (!init.containsEdge(te)) {
+ init.addEdge(te);
+ }
}
if (ts.getTag()!=null)
- addresult(ts.getTag(), ts);
+ addresult(ts.getTag(), ts);
else
- addresult(ts.getClassDesc(), ts);
+ addresult(ts.getClassDesc(), ts);
if (!discovered.contains(ts)) {
- discovered.add(ts);
- toprocess.add(ts);
+ discovered.add(ts);
+ toprocess.add(ts);
}
}
}
TempDescriptor tmp=tmpit.next();
Wrapper w=table.get(tmp);
if (w instanceof TagWrapper) {
- TagWrapper tw=(TagWrapper)w;
- recordtagchange(tw, td);
+ TagWrapper tw=(TagWrapper)w;
+ recordtagchange(tw, td);
} else {
- ObjWrapper ow=(ObjWrapper)w;
- recordobj(ow, td);
+ ObjWrapper ow=(ObjWrapper)w;
+ recordobj(ow, td);
}
}
}
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));
+ emap.put(table1.get(tmp), table2.get(tmp));
} else return false;
}
Wrapper w1=table1.get(tmp);
Wrapper w2=table2.get(tmp);
if (w1 instanceof TagWrapper) {
- TagWrapper t1=(TagWrapper)w1;
- TagWrapper t2=(TagWrapper)w2;
- if (!t1.ts.equals(t2.ts))
- return false;
+ TagWrapper t1=(TagWrapper)w1;
+ TagWrapper t2=(TagWrapper)w2;
+ if (!t1.ts.equals(t2.ts))
+ return false;
} else {
- ObjWrapper t1=(ObjWrapper)w1;
- ObjWrapper t2=(ObjWrapper)w2;
- if (!t1.fs.equals(t2.fs))
- return false;
- if (t1.tags.size()!=t2.tags.size())
- return false;
- for(Iterator<TagWrapper> twit=t1.tags.iterator(); twit.hasNext(); ) {
- TagWrapper tw1=twit.next();
- if (!t2.tags.contains(emap.get(tw1)))
- return false;
- }
+ ObjWrapper t1=(ObjWrapper)w1;
+ ObjWrapper t2=(ObjWrapper)w2;
+ if (!t1.fs.equals(t2.fs))
+ return false;
+ if (t1.tags.size()!=t2.tags.size())
+ return false;
+ for(Iterator<TagWrapper> twit=t1.tags.iterator(); twit.hasNext(); ) {
+ TagWrapper tw1=twit.next();
+ if (!t2.tags.contains(emap.get(tw1)))
+ return false;
+ }
}
}
return true;
Hashtable<TempDescriptor, Wrapper> table=computeInitialState(wtable, fn);
switch(fn.kind()) {
case FKind.FlatFlagActionNode:
- processFlatFlag((FlatFlagActionNode)fn, table, td);
- break;
+ processFlatFlag((FlatFlagActionNode)fn, table, td);
+ break;
case FKind.FlatTagDeclaration:
- processFlatTag((FlatTagDeclaration)fn, table, td);
- break;
+ processFlatTag((FlatTagDeclaration)fn, table, td);
+ break;
case FKind.FlatCall:
- processFlatCall((FlatCall)fn, table);
- break;
+ processFlatCall((FlatCall)fn, table);
+ break;
case FKind.FlatReturnNode:
- processFlatReturnNode((FlatReturnNode)fn, table, td);
- break;
+ processFlatReturnNode((FlatReturnNode)fn, table, td);
+ break;
default:
}
if (!equivalent(table, wtable.get(fn))) {
- wtable.put(fn, table);
- for(int i=0; i<fn.numNext(); i++) {
- tovisit.add(fn.getNext(i));
- }
+ 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(int i=0; i<fn.numNext(); i++) {
+ if (!visited.contains(fn.getNext(i)))
+ tovisit.add(fn.getNext(i));
+ }
}
}
else
switch (((FlagOpNode)fen).getOp().getOp()) {
case Operation.LOGIC_AND:
- return ((isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)) && (isTaskTrigger_flag(((FlagOpNode)fen).getRight(),fs)));
+ return ((isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)) && (isTaskTrigger_flag(((FlagOpNode)fen).getRight(),fs)));
case Operation.LOGIC_OR:
- return ((isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)) || (isTaskTrigger_flag(((FlagOpNode)fen).getRight(),fs)));
+ return ((isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs)) || (isTaskTrigger_flag(((FlagOpNode)fen).getRight(),fs)));
case Operation.LOGIC_NOT:
- return !(isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs));
+ return !(isTaskTrigger_flag(((FlagOpNode)fen).getLeft(),fs));
default:
- return false;
+ return false;
}
}
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;
- }
+ switch (fs.getTagCount(tel.getType(i))) {
+ case FlagState.ONETAG:
+ case FlagState.MULTITAGS:
+ break;
+
+ case FlagState.NOTAGS:
+ return false;
+ }
}
}
return true;
else if (ch>='a'&&ch<='z') {
int val=(ch-'a')+10;
if (val<radix)
- return val;
+ return val;
} else if (ch>='A'&&ch<='Z') {
int val=(ch-'A')+10;
if (val<radix)
- return val;
+ return val;
}
return -1;
}
for(int i=0; i<oldtable.length; i++) {
HashEntry e=oldtable[i];
while(e!=null) {
- HashEntry next=e.next;
- int bin=hash(e.key, newCapacity);
- e.next=table[bin];
- table[bin]=e;
- e=next;
+ HashEntry next=e.next;
+ int bin=hash(e.key, newCapacity);
+ e.next=table[bin];
+ table[bin]=e;
+ e=next;
}
}
}
HashEntry ptr=table[bin];
if (ptr!=null) {
if (ptr.key.equals(key)) {
- table[bin]=ptr.next;
- numItems--;
- return ptr.value;
+ 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;
+ if (ptr.next.key.equals(key)) {
+ Object oldvalue=ptr.value;
+ ptr.next=ptr.next.next;
+ numItems--;
+ return oldvalue;
+ }
+ ptr=ptr.next;
}
}
return null;
HashEntry ptr=table[bin];
while(ptr!=null) {
if (ptr.key.equals(key)) {
- return ptr.value;
+ return ptr.value;
}
ptr=ptr.next;
}
HashEntry ptr=table[bin];
while(ptr!=null) {
if (ptr.key.equals(key)) {
- return true;
+ return true;
}
ptr=ptr.next;
}
HashEntry ptr=table[bin];
while(ptr!=null) {
if (ptr.key.equals(key)) {
- Object oldvalue=ptr.value;
- ptr.value=value;
- return oldvalue;
+ Object oldvalue=ptr.value;
+ ptr.value=value;
+ return oldvalue;
}
ptr=ptr.next;
}
he=he.next;
Object o;
if (type==0)
- o=he.key;
+ o=he.key;
else
- o=he.value;
+ o=he.value;
return o;
}
while((bin<map.table.length)&&
he=map.table[bin++];
Object o;
if (type==0)
- o=he.key;
+ o=he.key;
else
- o=he.value;
+ o=he.value;
return o;
} else System.error();
}
return false;
for(int i=0; i<address.length; i++)
if (ia.address[i]!=address[i])
- return false;
+ return false;
return true;
}
addresses = new InetAddress[iplist.length];
for (int i = 0; i < iplist.length; i++) {
- addresses[i] = new InetAddress(iplist[i], hostname);
+ addresses[i] = new InetAddress(iplist[i], hostname);
}
return addresses;
} else
String h=hostname+" ";
for (int i=0; i<address.length; i++) {
if (i>0)
- h+=".";
+ h+=".";
h+=(int)address[i];
}
return h;
byte b=chars[i];
int val;
if (b>='0'&&b<='9')
- val=b-'0';
+ val=b-'0';
else if (b>='a'&&b<='z')
- val=10+b-'a';
+ val=10+b-'a';
else if (b>='A'&&b<='Z')
- val=10+b-'A';
+ val=10+b-'A';
else {
- cont=false;
+ cont=false;
}
if (cont) {
- if (val>=radix)
- System.error();
- value=value*radix+val;
+ if (val>=radix)
+ System.error();
+ value=value*radix+val;
}
}
if (isNeg)
LinkedListElement e = head;
if (o==null) {
while(e!=null) {
- if (e.element==null) {
- return true;
- }
- e=e.next;
+ if (e.element==null) {
+ return true;
+ }
+ e=e.next;
}
return false;
} else {
while( e != null ) {
- if (o.equals(e.element)) {
- return true;
- }
- e = e.next;
+ if (o.equals(e.element)) {
+ return true;
+ }
+ e = e.next;
}
}
return false;
LinkedListElement e = head;
while (e != null) {
if (e.element == o) {
- if (e.prev != null) {
- e.prev.next = e.next;
- }
- if (e.next != null) {
- e.next.prev = e.prev;
- }
- size--;
- return true;
+ if (e.prev != null) {
+ e.prev.next = e.next;
+ }
+ if (e.next != null) {
+ e.next.prev = e.prev;
+ }
+ size--;
+ return true;
}
e = e.next;
}
double d = y - x;
if( d == 0.5 ) {
if( ((int)y)%2 == 0 ) {
- return y;
+ return y;
} else {
- return y - 1.0;
+ return y - 1.0;
}
} else if( d < 0.5 ) {
return y;
Object[] newElements = new Object[newCapacity];
if (newElements == null) {
- return false;
+ return false;
}
int dst = 0;
Object[] tmpelements = elements;
if (pop < push) {
- int src;
- for (src = (pop + 1); src < push; src++, dst++) {
- newElements[dst] = elements[src];
- }
+ int src;
+ for (src = (pop + 1); src < push; src++, dst++) {
+ newElements[dst] = elements[src];
+ }
} else {
- int src;
- for (src = (pop + 1); src < capacity; src++, dst++) {
- newElements[dst] = elements[src];
- }
- for (src = 0; src < push; src++, dst++) {
- newElements[dst] = elements[src];
- }
+ int src;
+ for (src = (pop + 1); src < capacity; src++, dst++) {
+ newElements[dst] = elements[src];
+ }
+ for (src = 0; src < push; src++, dst++) {
+ newElements[dst] = elements[src];
+ }
}
//elements = null;
byte[] t=new byte[toread];
int rd=read(t);
if (rd<0)
- return rd;
+ return rd;
for(int i=0; i<rd; i++)
- b[i+offset]=t[i];
+ b[i+offset]=t[i];
offset+=rd;
toread-=rd;
}
public int lastindexOf(int ch, int fromIndex) {
for(int i=fromIndex; i>0; i--)
if (this.charAt(i)==ch)
- return i;
+ return i;
return -1;
}
for(int i=0; i<count; i++) {
char x=charAt(i);
if (x==oldch)
- x=newch;
+ x=newch;
buffer[i]=x;
}
return new String(buffer);
for(int i=0; i<count; i++) {
char x=charAt(i);
if (x>='a'&&x<='z') {
- x=(char) ((x-'a')+'A');
+ x=(char) ((x-'a')+'A');
}
buffer[i]=x;
}
for(int i=0; i<count; i++) {
char x=charAt(i);
if (x>='A'&&x<='Z') {
- x=(char) ((x-'A')+'a');
+ x=(char) ((x-'A')+'a');
}
buffer[i]=x;
}
public int indexOf(int ch, int fromIndex) {
for(int i=fromIndex; i<count; i++)
if (this.charAt(i)==ch)
- return i;
+ return i;
return -1;
}
fromIndex=0;
for(int i=fromIndex; i<=(count-str.count); i++)
if (regionMatches(i, str, 0, str.count))
- return i;
+ return i;
return -1;
}
k=fromIndex;
for(; k>=0; k--) {
if (regionMatches(k, str, 0, str.count))
- return k;
+ return k;
}
return -1;
}
for(int i=0; i<len; i++)
if (other.value[i+other.offset+ooffset]!=
this.value[i+this.offset+toffset])
- return false;
+ return false;
return true;
}
for( int i = 0; i < smallerlength; i++ ) {
int valDiff = this.charAt(i) - s.charAt(i);
if( valDiff != 0 ) {
- return valDiff;
+ return valDiff;
}
}
return count-s.count;
return false;
for(int i=0; i<count; i++) {
if (s.value[i+s.offset]!=value[i+offset])
- return false;
+ return false;
}
return true;
}
char l=s.value[i+s.offset];
char r=value[i+offset];
if (l>='a'&&l<='z')
- l=(char)((l-'a')+'A');
+ l=(char)((l-'a')+'A');
if (r>='a'&&r<='z')
- r=(char)((r-'a')+'A');
+ r=(char)((r-'a')+'A');
if (l!=r)
- return false;
+ return false;
}
return true;
}
// skip first spaces
for(i = 0; i< count; i++) {
if(value[i+offset] != '\n' && value[i+offset] != '\t' && value[i+offset] != ' ')
- break;
+ break;
}
int oldi=i;
while(i<count) {
if(value[i+offset] == '\n' || value[i+offset] == '\t' || value[i+offset] == ' ') {
- String t=new String();
- t.value=value;
- t.offset=oldi;
- t.count=i-oldi;
- splitted.addElement(t);
-
- // skip extra spaces
- while( i < count && ( value[i+offset] == '\n' || value[i+offset] == '\t' || value[i+offset] == ' ')) {
- i++;
- }
- oldi=i;
+ String t=new String();
+ t.value=value;
+ t.offset=oldi;
+ t.count=i-oldi;
+ splitted.addElement(t);
+
+ // skip extra spaces
+ while( i < count && ( value[i+offset] == '\n' || value[i+offset] == '\t' || value[i+offset] == ' ')) {
+ i++;
+ }
+ oldi=i;
} else {
- i++;
+ i++;
}
}
for(i = 0; i < count; i++) {
if(value[i] == strChar[0]) {
- cnt=0;
- for(j=0; j < str.length() && i+j < count; j++) {
- if(value[i+j] == strChar[j])
- cnt++;
- }
- if(cnt == str.length())
- return true;
+ cnt=0;
+ for(j=0; j < str.length() && i+j < count; j++) {
+ if(value[i+j] == strChar[j])
+ cnt++;
+ }
+ if(cnt == str.length())
+ return true;
}
}
// 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];
+ newvalue[i]=value[i];
for(int i=0; i<s.count; i++)
- newvalue[i+count]=s.value[i+s.offset];
+ 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];
+ value[i+count]=s.value[i+s.offset];
}
count+=s.count;
}
if (i>value.length) {
char newvalue[]=new char[i];
for(int ii=0; ii<count; ii++)
- newvalue[ii]=value[ii];
+ newvalue[ii]=value[ii];
value=newvalue;
}
}
// 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];
+ newvalue[i]=value[i];
for(int i=0; i<s.count; i++)
- newvalue[i+count]=s.value[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];
+ value[i+count]=s.value[i];
}
count+=s.count;
}
public int indexOf(Object elem, int index) {
for(int i=index; i<size; i++) {
if (elem.equals(array[i]))
- return i;
+ return i;
}
return -1;
}
if (minCapacity>array.length) {
int newsize;
if (capacityIncrement<=0)
- newsize=array.length*2;
+ newsize=array.length*2;
else
- newsize=array.length+capacityIncrement;
+ newsize=array.length+capacityIncrement;
if (newsize<minCapacity)
- newsize=minCapacity;
+ newsize=minCapacity;
Object [] newarray=new Object[newsize];
for(int i=0; i<size; i++)
- newarray[i]=array[i];
+ newarray[i]=array[i];
array=newarray;
}
}
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;
}
}
}
public boolean hasMoreTokens() {
if (!retDelims) {
while (pos < len && delim.indexOf(str.charAt(pos)) >= 0)
- pos++;
+ pos++;
}
return pos < len;
}
public String nextToken() { //throws NoSuchElementException
if (pos < len && delim.indexOf(str.charAt(pos)) >= 0) {
if (retDelims)
- return str.substring(pos, ++pos);
+ return str.substring(pos, ++pos);
while (++pos < len && delim.indexOf(str.charAt(pos)) >= 0)
- ;
+ ;
}
if (pos < len) {
int start = pos;
while (++pos < len && delim.indexOf(str.charAt(pos)) < 0)
- ;
+ ;
return str.substring(start, pos);
}
// just do the conditional once at the end of the method
while (tmpPos < len) {
if (delim.indexOf(str.charAt(tmpPos++)) >= 0) {
- if (tokenFound) {
- // Got to the end of a token
- count++;
- tokenFound = false;
- }
- delimiterCount++; // Increment for this delimiter
+ if (tokenFound) {
+ // Got to the end of a token
+ count++;
+ tokenFound = false;
+ }
+ delimiterCount++; // Increment for this delimiter
} else
{
- tokenFound = true;
- // Get to the end of the token
- while (tmpPos < len
- && delim.indexOf(str.charAt(tmpPos)) < 0)
- ++tmpPos;
+ tokenFound = true;
+ // Get to the end of the token
+ while (tmpPos < len
+ && delim.indexOf(str.charAt(tmpPos)) < 0)
+ ++tmpPos;
}
}
if (o instanceof AnnotationDescriptor) {
AnnotationDescriptor a = (AnnotationDescriptor) o;
if (a.getType() != type)
- return false;
+ return false;
if (!a.getMarker().equals(getMarker()))
- return false;
+ return false;
return true;
}
st += "implements ";
boolean needcomma = false;
for(int i = 0; i < this.superinterfaces.size(); i++) {
- if(needcomma) {
- st += ", ";
- }
- st += this.superinterfaces.elementAt(i);
- needcomma = true;
+ if(needcomma) {
+ st += ", ";
+ }
+ st += this.superinterfaces.elementAt(i);
+ needcomma = true;
}
}
st+=" {\n";
String[] econstants = new String[keys.size()];
Iterator it_keys = keys.iterator();
while(it_keys.hasNext()) {
- String key = (String)it_keys.next();
- econstants[icd.getEnumConstant(key)] = key;
+ String key = (String)it_keys.next();
+ econstants[icd.getEnumConstant(key)] = key;
}
for(int i = 0; i < econstants.length; i++) {
- st += econstants[i];
- if(i < econstants.length-1) {
- st += ", ";
- }
+ st += econstants[i];
+ if(i < econstants.length-1) {
+ st += ", ";
+ }
}
st+="\n}\n";
printcr=true;
ClassDescriptor cn=this;
while(true) {
if (cn==null) {
- // TODO: the original code returned "null" if no super class
- // ever defines the method. Is there a situation where this is
- // fine and the client should take other actions? If not, we should
- // change this warning to an error.
- System.out.println("ClassDescriptor.java: WARNING "+md+
- " did not resolve to an actual method.");
- return null;
+ // TODO: the original code returned "null" if no super class
+ // ever defines the method. Is there a situation where this is
+ // fine and the client should take other actions? If not, we should
+ // change this warning to an error.
+ System.out.println("ClassDescriptor.java: WARNING "+md+
+ " did not resolve to an actual method.");
+ return null;
}
Set possiblematches=cn.getMethodTable().getSetFromSameScope(md.getSymbol());
for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) {
- MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
+ MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
- if (md.matches(matchmd)) {
- return matchmd;
- }
+ if (md.matches(matchmd)) {
+ return matchmd;
+ }
}
//Not found...walk one level up
outmethod=new CodePrinter(new FileOutputStream(PREFIX+"methods.c"), true);
outvirtual=new CodePrinter(new FileOutputStream(PREFIX+"virtualtable.h"), true);
if (state.TASK) {
- outtask=new CodePrinter(new FileOutputStream(PREFIX+"task.h"), true);
- outtaskdefs=new CodePrinter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
- if (state.OPTIONAL) {
- outoptionalarrays=new CodePrinter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
- optionalheaders=new CodePrinter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
- }
+ outtask=new CodePrinter(new FileOutputStream(PREFIX+"task.h"), true);
+ outtaskdefs=new CodePrinter(new FileOutputStream(PREFIX+"taskdefs.c"), true);
+ if (state.OPTIONAL) {
+ outoptionalarrays=new CodePrinter(new FileOutputStream(PREFIX+"optionalarrays.c"), true);
+ optionalheaders=new CodePrinter(new FileOutputStream(PREFIX+"optionalstruct.h"), true);
+ }
}
if (state.structfile!=null) {
- outrepairstructs=new CodePrinter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
+ outrepairstructs=new CodePrinter(new FileOutputStream(PREFIX+state.structfile+".struct"), true);
}
} catch (Exception e) {
e.printStackTrace();
/* The runtime keeps track of flags using these integers */
it=state.getClassSymbolTable().getDescriptorsIterator();
while(it.hasNext()) {
- ClassDescriptor cn=(ClassDescriptor)it.next();
- mapFlags(cn);
+ ClassDescriptor cn=(ClassDescriptor)it.next();
+ mapFlags(cn);
}
/* Generate Tasks */
generateTaskStructs(outstructs, outmethodheader);
ClassDescriptor cd = (ClassDescriptor)it_sclasses.next();
MethodDescriptor md = (MethodDescriptor)cd.getMethodTable().get("staticblocks");
if(md != null) {
- tovisit.add(md);
+ tovisit.add(md);
}
}
visited.add(current_md);
Iterator it_callee = this.callgraph.getCalleeSet(current_md).iterator();
while(it_callee.hasNext()) {
- Descriptor d = (Descriptor)it_callee.next();
- if(d instanceof MethodDescriptor) {
- if(!visited.contains(d)) {
- ((MethodDescriptor)d).setIsInvokedByStatic(true);
- tovisit.add(d);
- }
- }
+ Descriptor d = (Descriptor)it_callee.next();
+ if(d instanceof MethodDescriptor) {
+ if(!visited.contains(d)) {
+ ((MethodDescriptor)d).setIsInvokedByStatic(true);
+ tovisit.add(d);
+ }
+ }
}
}
}
Iterator it_sclasses = sctbl.getDescriptorsIterator();
if(it_sclasses.hasNext()) {
while(it_sclasses.hasNext()) {
- ClassDescriptor t_cd = (ClassDescriptor)it_sclasses.next();
- MethodDescriptor t_md = (MethodDescriptor)t_cd.getMethodTable().get("staticblocks");
+ ClassDescriptor t_cd = (ClassDescriptor)it_sclasses.next();
+ MethodDescriptor t_md = (MethodDescriptor)t_cd.getMethodTable().get("staticblocks");
- if(t_md != null&&callgraph.isInit(t_cd)) {
- outmethod.println(" {");
- if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- outmethod.print(" struct "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
- outmethod.println("0, NULL};");
- outmethod.println(" "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
- } else {
- outmethod.println(" "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
- }
- outmethod.println(" }");
- }
+ if(t_md != null&&callgraph.isInit(t_cd)) {
+ outmethod.println(" {");
+ if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
+ outmethod.print(" struct "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
+ outmethod.println("0, NULL};");
+ outmethod.println(" "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
+ } else {
+ outmethod.println(" "+t_cd.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
+ }
+ outmethod.println(" }");
+ }
}
}
}
while(taskit.hasNext()) {
TaskDescriptor td=(TaskDescriptor)taskit.next();
if (first)
- first=false;
+ first=false;
else
- outtaskdefs.println(",");
+ outtaskdefs.println(",");
outtaskdefs.print("&task_"+td.getSafeSymbol());
}
outtaskdefs.println("};");
}
if(state.MULTICORE) {
if(state.TASK) {
- outmethod.println("#include \"task.h\"");
+ outmethod.println("#include \"task.h\"");
}
outmethod.println("#include \"multicoreruntime.h\"");
outmethod.println("#include \"runtime_arch.h\"");
ClassDescriptor cn=(ClassDescriptor)classit.next();
Iterator methodit=cn.getMethods();
while(methodit.hasNext()) {
- /* Classify parameters */
- MethodDescriptor md=(MethodDescriptor)methodit.next();
- if (!callgraph.isCallable(md)&&(!md.isStaticBlock()||!callgraph.isInit(cn))) {
- continue;
- }
+ /* Classify parameters */
+ MethodDescriptor md=(MethodDescriptor)methodit.next();
+ if (!callgraph.isCallable(md)&&(!md.isStaticBlock()||!callgraph.isInit(cn))) {
+ continue;
+ }
- FlatMethod fm=state.getMethodFlat(md);
- if (!md.getModifiers().isNative()) {
- generateFlatMethod(fm, outmethod);
- } else if (state.JNI) {
- generateNativeFlatMethod(fm, outmethod);
- }
+ FlatMethod fm=state.getMethodFlat(md);
+ if (!md.getModifiers().isNative()) {
+ generateFlatMethod(fm, outmethod);
+ } else if (state.JNI) {
+ generateNativeFlatMethod(fm, outmethod);
+ }
}
}
}
outclassdefs.println("struct "+cn.getSafeSymbol()+";");
if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
- // this class has static fields/blocks, need to add a global flag to
- // indicate if its static fields have been initialized and/or if its
- // static blocks have been executed
- outglobaldefsprim.println(" int "+cn.getSafeSymbol()+"static_block_exe_flag;");
+ // this class has static fields/blocks, need to add a global flag to
+ // indicate if its static fields have been initialized and/or if its
+ // static blocks have been executed
+ outglobaldefsprim.println(" int "+cn.getSafeSymbol()+"static_block_exe_flag;");
}
}
outclassdefs.println("");
outclassdefs.println(" volatile int notifycount;");
outclassdefs.println(" volatile int objlock;");
if(state.MULTICOREGC) {
- outclassdefs.println(" int marked;");
+ outclassdefs.println(" int marked;");
}
}
if (state.TASK) {
outclassdefs.println(" int flag;");
outclassdefs.println(" int ___cachedCode___;");
if(!state.MULTICORE) {
- outclassdefs.println(" void * flagptr;");
+ outclassdefs.println(" void * flagptr;");
} else {
- outclassdefs.println(" int version;");
- outclassdefs.println(" int * lock;"); // lock entry for this obj
- outclassdefs.println(" int mutex;");
- outclassdefs.println(" volatile int lockcount;");
- if(state.MULTICOREGC) {
- outclassdefs.println(" int marked;");
- }
+ outclassdefs.println(" int version;");
+ outclassdefs.println(" int * lock;"); // lock entry for this obj
+ outclassdefs.println(" int mutex;");
+ outclassdefs.println(" volatile int lockcount;");
+ if(state.MULTICOREGC) {
+ outclassdefs.println(" int marked;");
+ }
}
if(state.OPTIONAL) {
- outclassdefs.println(" int numfses;");
- outclassdefs.println(" int * fses;");
+ outclassdefs.println(" int numfses;");
+ outclassdefs.println(" int * fses;");
}
}
outrepairstructs.println("structure "+cn.getSymbol()+" {");
outrepairstructs.println(" int __type__;");
if (state.TASK) {
- outrepairstructs.println(" int __flag__;");
- if(!state.MULTICORE) {
- outrepairstructs.println(" int __flagptr__;");
- }
+ outrepairstructs.println(" int __flag__;");
+ if(!state.MULTICORE) {
+ outrepairstructs.println(" int __flagptr__;");
+ }
}
printRepairStruct(cn, outrepairstructs);
outrepairstructs.println("}\n");
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()+";");
+ output.println(" "+arraytype+"_"+ state.getArrayNumber(fd.getType()) +" * "+fd.getSymbol()+";");
} else if (fd.getType().isClass())
- output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
+ output.println(" "+fd.getType().getRepairSymbol()+" * "+fd.getSymbol()+";");
else if (fd.getType().isFloat())
- output.println(" int "+fd.getSymbol()+"; /* really float */");
+ output.println(" int "+fd.getSymbol()+"; /* really float */");
else
- output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
+ output.println(" "+fd.getType().getRepairSymbol()+" "+fd.getSymbol()+";");
}
}
int dnfterms;
if (param_flag==null) {
- output.println("int parameterdnf_"+i+"_"+task.getSafeSymbol()+"[]={");
- output.println("0x0, 0x0 };");
- dnfterms=1;
+ 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("};");
+ 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()+"[]={");
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()));
- }
+ 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("parameterdnf_"+i+"_"+task.getSafeSymbol()+",");
output.println("0,");
if (param_tag!=null)
- output.println("/* number of tags */"+param_tag.numTags()+",");
+ output.println("/* number of tags */"+param_tag.numTags()+",");
else
- output.println("/* number of tags */ 0,");
+ 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.println(",");
output.print("¶meter_"+i+"_"+task.getSafeSymbol());
}
output.println("};");
while(classit.hasNext()) {
ClassDescriptor cd=(ClassDescriptor)classit.next();
if (virtualcalls.getMethodCount(cd)>maxcount)
- maxcount=virtualcalls.getMethodCount(cd);
+ maxcount=virtualcalls.getMethodCount(cd);
}
MethodDescriptor[][] virtualtable=null;
virtualtable=new MethodDescriptor[state.numClasses()+state.numArrays()][maxcount];
while(classit.hasNext()) {
ClassDescriptor cd=(ClassDescriptor)classit.next();
if(cd.isInterface()) {
- continue;
+ continue;
}
fillinRow(cd, virtualtable, cd.getId());
}
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 (virtualtable[i][j]!=null) {
- MethodDescriptor md=virtualtable[i][j];
- outvirtual.print("& "+md.getClassDesc().getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
- } else {
- outvirtual.print("0");
- }
- needcomma=true;
+ if (needcomma)
+ outvirtual.print(", ");
+ if (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("");
}
for(Iterator it=cd.getMethods(); it.hasNext(); ) {
MethodDescriptor md=(MethodDescriptor)it.next();
if (md.isStatic()||md.getReturnType()==null)
- continue;
+ continue;
if (!callgraph.isCallable(md)) {
- continue;
+ continue;
}
int methodnum = virtualcalls.getMethodNumber(md);
while(it.hasNext()) {
ClassDescriptor cd=(ClassDescriptor)it.next();
if(cd.isInterface()) {
- ifarray[cd.getId()] = cd;
+ ifarray[cd.getId()] = cd;
} else {
- cdarray[cd.getId()] = cd;
+ cdarray[cd.getId()] = cd;
}
}
for(int i=0; i<state.numClasses(); i++) {
ClassDescriptor cd=cdarray[i];
if(cd == null) {
- outclassdefs.println("NULL " + i);
+ outclassdefs.println("NULL " + i);
} else {
- outclassdefs.println(cd +" "+i);
+ outclassdefs.println(cd +" "+i);
}
}
boolean needcomma=false;
for(int i=0; i<state.numClasses(); i++) {
if (needcomma)
- outclassdefs.print(", ");
+ outclassdefs.print(", ");
if(i>0) {
- outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
+ outclassdefs.print("sizeof(struct "+cdarray[i].getSafeSymbol()+")");
} else {
- outclassdefs.print("0");
+ outclassdefs.print("0");
}
needcomma=true;
}
for(int i=0; i<state.numArrays(); i++) {
if (needcomma)
- outclassdefs.print(", ");
+ outclassdefs.print(", ");
TypeDescriptor tdelement=arraytable[i].dereference();
if (tdelement.isArray()||tdelement.isClass()||tdelement.isNull())
- outclassdefs.print("sizeof(void *)");
+ outclassdefs.print("sizeof(void *)");
else
- outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
+ outclassdefs.print("sizeof("+tdelement.getSafeSymbol()+")");
needcomma=true;
}
for(int i=0; i<state.numInterfaces(); i++) {
if (needcomma)
- outclassdefs.print(", ");
+ outclassdefs.print(", ");
outclassdefs.print("sizeof(struct "+ifarray[i].getSafeSymbol()+")");
needcomma=true;
}
ClassDescriptor cd=cdarray[i];
ClassDescriptor supercd=i>0?cd.getSuperDesc():null;
if(supercd != null && supercd.isInterface()) {
- throw new Error("Super class can not be interfaces");
+ throw new Error("Super class can not be interfaces");
}
if (needcomma)
- outclassdefs.print(", ");
+ outclassdefs.print(", ");
if (supercd==null)
- outclassdefs.print("-1");
+ outclassdefs.print("-1");
else
- outclassdefs.print(supercd.getId());
+ outclassdefs.print(supercd.getId());
needcomma=true;
}
TypeDescriptor arraytd=arraytable[i];
ClassDescriptor arraycd=arraytd.getClassDesc();
if (arraycd==null) {
- if (needcomma)
- outclassdefs.print(", ");
- outclassdefs.print(objectclass.getId());
- needcomma=true;
- continue;
+ if (needcomma)
+ outclassdefs.print(", ");
+ outclassdefs.print(objectclass.getId());
+ needcomma=true;
+ continue;
}
ClassDescriptor cd=arraycd.getSuperDesc();
int type=-1;
while(cd!=null) {
- TypeDescriptor supertd=new TypeDescriptor(cd);
- supertd.setArrayCount(arraytd.getArrayCount());
- type=state.getArrayNumber(supertd);
- if (type!=-1) {
- type+=state.numClasses();
- break;
- }
- cd=cd.getSuperDesc();
+ TypeDescriptor supertd=new TypeDescriptor(cd);
+ supertd.setArrayCount(arraytd.getArrayCount());
+ type=state.getArrayNumber(supertd);
+ if (type!=-1) {
+ type+=state.numClasses();
+ break;
+ }
+ cd=cd.getSuperDesc();
}
if (needcomma)
- outclassdefs.print(", ");
+ outclassdefs.print(", ");
outclassdefs.print(type);
needcomma=true;
}
ClassDescriptor cd=ifarray[i];
ClassDescriptor supercd=cd.getSuperDesc();
if(supercd != null && supercd.isInterface()) {
- throw new Error("Super class can not be interfaces");
+ throw new Error("Super class can not be interfaces");
}
if (needcomma)
- outclassdefs.print(", ");
+ outclassdefs.print(", ");
if (supercd==null)
- outclassdefs.print("-1");
+ outclassdefs.print("-1");
else
- outclassdefs.print(supercd.getId());
+ outclassdefs.print(supercd.getId());
needcomma=true;
}
TypeDescriptor arraytd=arraytable[i];
ClassDescriptor arraycd=arraytd.getClassDesc();
if (arraycd==null) {
- if (needcomma)
- outclassdefs.print(", ");
- outclassdefs.print("-1");
- needcomma=true;
- continue;
+ if (needcomma)
+ outclassdefs.print(", ");
+ outclassdefs.print("-1");
+ needcomma=true;
+ continue;
}
ClassDescriptor cd=arraycd.getSuperDesc();
int level=arraytd.getArrayCount()-1;
int type=-1;
for(; level>0; level--) {
- TypeDescriptor supertd=new TypeDescriptor(objectclass);
- supertd.setArrayCount(level);
- type=state.getArrayNumber(supertd);
- if (type!=-1) {
- type+=state.numClasses();
- break;
- }
+ TypeDescriptor supertd=new TypeDescriptor(objectclass);
+ supertd.setArrayCount(level);
+ type=state.getArrayNumber(supertd);
+ if (type!=-1) {
+ type+=state.numClasses();
+ break;
+ }
}
if (needcomma)
- outclassdefs.print(", ");
+ outclassdefs.print(", ");
outclassdefs.print(type);
needcomma=true;
}
TempDescriptor temp=fm.getParameter(i);
TypeDescriptor type=temp.getType();
if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
- objectparams.addPtr(temp);
+ objectparams.addPtr(temp);
else
- objectparams.addPrim(temp);
+ objectparams.addPrim(temp);
}
for(int i=0; i<fm.numTags(); i++) {
TempDescriptor temp=fm.getTag(i);
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
- objectparams.addPtr(temp);
+ objectparams.addPtr(temp);
else
- objectparams.addPrim(temp);
+ objectparams.addPrim(temp);
}
TempObject objecttemps=md!=null?new TempObject(objectparams,md,tag++):new TempObject(objectparams, task, tag++);
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) || (this.state.MULTICOREGC)))
- objecttemps.addPtr(temp);
- else
- objecttemps.addPrim(temp);
+ TempDescriptor temp=writes[i];
+ TypeDescriptor type=temp.getType();
+ if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
+ objecttemps.addPtr(temp);
+ else
+ objecttemps.addPrim(temp);
}
}
}
ClassDescriptor cn=(ClassDescriptor)it.next();
output.print("unsigned INTPTR "+cn.getSafeSymbol()+"_pointers[]={");
if (javabuilder!=null&&!javabuilder.hasLayout(cn)) {
- output.println("0};");
- continue;
+ output.println("0};");
+ continue;
}
int count=0;
for(Iterator allit=cn.getFieldTable().getAllDescriptorsIterator(); allit.hasNext(); ) {
- FieldDescriptor fd=(FieldDescriptor)allit.next();
- if(fd.isStatic()) {
- continue;
- }
- TypeDescriptor type=fd.getType();
- if (type.isPtr())
- count++;
+ FieldDescriptor fd=(FieldDescriptor)allit.next();
+ if(fd.isStatic()) {
+ continue;
+ }
+ TypeDescriptor type=fd.getType();
+ if (type.isPtr())
+ count++;
}
output.print(count);
for(Iterator allit=cn.getFieldTable().getAllDescriptorsIterator(); allit.hasNext(); ) {
- FieldDescriptor fd=(FieldDescriptor)allit.next();
- if(fd.isStatic()) {
- continue;
- }
- TypeDescriptor type=fd.getType();
- if (type.isPtr()) {
- output.print(", ");
- output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+
- fd.getSafeSymbol()+"))");
- }
+ FieldDescriptor fd=(FieldDescriptor)allit.next();
+ if(fd.isStatic()) {
+ continue;
+ }
+ TypeDescriptor type=fd.getType();
+ if (type.isPtr()) {
+ output.print(", ");
+ output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+
+ fd.getSafeSymbol()+"))");
+ }
}
output.println("};");
}
for(int i=0; i<state.numClasses(); i++) {
ClassDescriptor cn=cdarray[i];
if (needcomma)
- output.println(",");
+ output.println(",");
needcomma=true;
if(cn != null) {
- output.print(cn.getSafeSymbol()+"_pointers");
+ output.print(cn.getSafeSymbol()+"_pointers");
} else {
- output.print("NULL");
+ output.print("NULL");
}
}
for(int i=0; i<state.numArrays(); i++) {
if (needcomma)
- output.println(", ");
+ output.println(", ");
TypeDescriptor tdelement=arraytable[i].dereference();
if (tdelement.isArray()||tdelement.isClass())
- output.print("((unsigned INTPTR *)1)");
+ output.print("((unsigned INTPTR *)1)");
else
- output.print("0");
+ output.print("0");
needcomma=true;
}
for(int i=0; i<state.numClasses(); i++) {
ClassDescriptor cn=cdarray[i];
if (needcomma)
- output.println(", ");
+ output.println(", ");
needcomma=true;
if ((cn != null) && (cn.hasFlags()))
- output.print("1");
+ output.print("1");
else
- output.print("0");
+ output.print("0");
}
output.println("};");
}
if(cd != null) {
type = checkarraysupertype(cd, arraytd);
if(type != -1) {
- return type;
+ return type;
}
}
ClassDescriptor ifcd = (ClassDescriptor)it_sifs.next();
type = checkarraysupertype(ifcd, arraytd);
if(type != -1) {
- return type;
+ return type;
}
}
for(int i=0; i<state.numClasses(); i++) {
ClassDescriptor cn=cdarray[i];
if(cn == null) {
- continue;
+ continue;
}
output.print("int supertypes" + cn.getSafeSymbol() + "[] = {");
boolean ncomma = false;
int snum = 0;
if((cn != null) && (cn.getSuperDesc() != null)) {
- snum++;
+ snum++;
}
Iterator it_sifs = cn != null?cn.getSuperInterfaces():null;
while(it_sifs != null && it_sifs.hasNext()) {
- snum++;
- it_sifs.next();
+ snum++;
+ it_sifs.next();
}
output.print(snum);
ncomma = true;
if ((cn != null) && (cn.getSuperDesc()!=null)) {
- if(ncomma) {
- output.print(",");
- }
- ClassDescriptor cdsuper=cn.getSuperDesc();
- output.print(cdsuper.getId());
+ if(ncomma) {
+ output.print(",");
+ }
+ ClassDescriptor cdsuper=cn.getSuperDesc();
+ output.print(cdsuper.getId());
}
it_sifs = cn != null?cn.getSuperInterfaces():null;
while(it_sifs != null && it_sifs.hasNext()) {
- if(ncomma) {
- output.print(",");
- }
- output.print(((ClassDescriptor)it_sifs.next()).getId()+state.numClasses()+state.numArrays());
+ if(ncomma) {
+ output.print(",");
+ }
+ output.print(((ClassDescriptor)it_sifs.next()).getId()+state.numClasses()+state.numArrays());
}
output.println("};");
boolean ncomma = false;
int snum = 0;
if (arraycd==null) {
- snum++;
- output.print(snum);
- output.print(", ");
- output.print(objectclass.getId());
- output.println("};");
- continue;
+ snum++;
+ output.print(snum);
+ output.print(", ");
+ output.print(objectclass.getId());
+ output.println("};");
+ continue;
}
if((arraycd != null) && (arraycd.getSuperDesc() != null)) {
- snum++;
+ snum++;
}
Iterator it_sifs = arraycd != null?arraycd.getSuperInterfaces():null;
while(it_sifs != null && it_sifs.hasNext()) {
- snum++;
- it_sifs.next();
+ snum++;
+ it_sifs.next();
}
output.print(snum);
ncomma = true;
if ((arraycd != null) && (arraycd.getSuperDesc()!=null)) {
- ClassDescriptor cd=arraycd.getSuperDesc();
- int type=-1;
- if(cd!=null) {
- type = checkarraysupertype(cd, arraytd);
- if(type != -1) {
- type += state.numClasses();
- }
- }
- if (ncomma)
- output.print(", ");
- output.print(type);
+ ClassDescriptor cd=arraycd.getSuperDesc();
+ int type=-1;
+ if(cd!=null) {
+ type = checkarraysupertype(cd, arraytd);
+ if(type != -1) {
+ type += state.numClasses();
+ }
+ }
+ if (ncomma)
+ output.print(", ");
+ output.print(type);
}
it_sifs = arraycd != null?arraycd.getSuperInterfaces():null;
while(it_sifs != null && it_sifs.hasNext()) {
- ClassDescriptor ifcd = (ClassDescriptor)it_sifs.next();
- int type = checkarraysupertype(ifcd, arraytd);
- if(type != -1) {
- type += state.numClasses();
- }
- if (ncomma)
- output.print(", ");
- output.print(type);
+ ClassDescriptor ifcd = (ClassDescriptor)it_sifs.next();
+ int type = checkarraysupertype(ifcd, arraytd);
+ if(type != -1) {
+ type += state.numClasses();
+ }
+ if (ncomma)
+ output.print(", ");
+ output.print(type);
}
output.println("};");
}
for(int i=0; i<state.numInterfaces(); i++) {
ClassDescriptor cn=ifarray[i];
if(cn == null) {
- continue;
+ continue;
}
output.print("int supertypes" + cn.getSafeSymbol() + "[] = {");
boolean ncomma = false;
int snum = 0;
if((cn != null) && (cn.getSuperDesc() != null)) {
- snum++;
+ snum++;
}
Iterator it_sifs = cn != null?cn.getSuperInterfaces():null;
while(it_sifs != null && it_sifs.hasNext()) {
- snum++;
- it_sifs.next();
+ snum++;
+ it_sifs.next();
}
output.print(snum);
ncomma = true;
if ((cn != null) && (cn.getSuperDesc()!=null)) {
- if(ncomma) {
- output.print(",");
- }
- ClassDescriptor cdsuper=cn.getSuperDesc();
- output.print(cdsuper.getId());
+ if(ncomma) {
+ output.print(",");
+ }
+ ClassDescriptor cdsuper=cn.getSuperDesc();
+ output.print(cdsuper.getId());
}
it_sifs = cn != null?cn.getSuperInterfaces():null;
while(it_sifs != null && it_sifs.hasNext()) {
- if(ncomma) {
- output.print(",");
- }
- output.print(((ClassDescriptor)it_sifs.next()).getId()+state.numClasses()+state.numArrays());
+ if(ncomma) {
+ output.print(",");
+ }
+ output.print(((ClassDescriptor)it_sifs.next()).getId()+state.numClasses()+state.numArrays());
}
output.println("};");
for(int i=0; i<state.numClasses(); i++) {
ClassDescriptor cn=cdarray[i];
if (needcomma)
- output.println(",");
+ output.println(",");
needcomma=true;
if(cn != null) {
- output.print("supertypes" + cn.getSafeSymbol());
+ output.print("supertypes" + cn.getSafeSymbol());
} else {
- output.print(0);
+ output.print(0);
}
}
for(int i=0; i<state.numArrays(); i++) {
if (needcomma)
- output.println(",");
+ output.println(",");
needcomma = true;
output.print("supertypes___arraytype___" + (i+state.numClasses()));
}
for(int i=0; i<state.numInterfaces(); i++) {
ClassDescriptor cn=ifarray[i];
if (needcomma)
- output.println(",");
+ output.println(",");
needcomma=true;
output.print("supertypes" + cn.getSafeSymbol());
}
Vector fieldvec=cn.getFieldVec();
fldloop:
for(int i=0; i<fieldvec.size(); i++) {
- FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
- if((sp != null) && sp.getFieldTable().contains(fd.getSymbol())) {
- // a shadow field
- } else {
- it_sifs = sitbl.getDescriptorsIterator();
- while(it_sifs.hasNext()) {
- ClassDescriptor si = (ClassDescriptor)it_sifs.next();
- if(si.getFieldTable().contains(fd.getSymbol())) {
- continue fldloop;
- }
- }
- fields.add(fd);
- }
+ FieldDescriptor fd=(FieldDescriptor)fieldvec.get(i);
+ if((sp != null) && sp.getFieldTable().contains(fd.getSymbol())) {
+ // a shadow field
+ } else {
+ it_sifs = sitbl.getDescriptorsIterator();
+ while(it_sifs.hasNext()) {
+ ClassDescriptor si = (ClassDescriptor)it_sifs.next();
+ if(si.getFieldTable().contains(fd.getSymbol())) {
+ continue fldloop;
+ }
+ }
+ fields.add(fd);
+ }
}
}
//Vector fields=(Vector)fieldorder.get(cn);
FieldDescriptor fd=(FieldDescriptor)fields.get(i);
String fstring = fd.getSafeSymbol();
if(printedfieldstbl.containsKey(fstring)) {
- printedfieldstbl.put(fstring, cn);
- continue;
+ printedfieldstbl.put(fstring, cn);
+ continue;
} else {
- printedfieldstbl.put(fstring, cn);
+ printedfieldstbl.put(fstring, cn);
}
if (fd.getType().isClass()
&& fd.getType().getClassDesc().isEnum()) {
- classdefout.println(" int " + fd.getSafeSymbol() + ";");
+ classdefout.println(" int " + fd.getSafeSymbol() + ";");
} else if (fd.getType().isClass()||fd.getType().isArray()) {
- if (fd.isStatic()) {
- // TODO add version for normal Java later
- // static field
- if(globaldefout != null) {
- if(fd.isVolatile()) {
- globaldefout.println(" volatile struct "+fd.getType().getSafeSymbol()+ " * "+fd.getSafeSymbol()+";");
- } else {
- globaldefout.println(" struct "+fd.getType().getSafeSymbol()+ " * "+fd.getSafeSymbol()+";");
- }
- globaldefscount++;
- }
- } else if (fd.isVolatile()) {
- //volatile field
- classdefout.println(" volatile struct "+fd.getType().getSafeSymbol()+ " * "+fd.getSafeSymbol()+";");
- } else {
- classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
- }
+ if (fd.isStatic()) {
+ // TODO add version for normal Java later
+ // static field
+ if(globaldefout != null) {
+ if(fd.isVolatile()) {
+ globaldefout.println(" volatile struct "+fd.getType().getSafeSymbol()+ " * "+fd.getSafeSymbol()+";");
+ } else {
+ globaldefout.println(" struct "+fd.getType().getSafeSymbol()+ " * "+fd.getSafeSymbol()+";");
+ }
+ globaldefscount++;
+ }
+ } else if (fd.isVolatile()) {
+ //volatile field
+ classdefout.println(" volatile struct "+fd.getType().getSafeSymbol()+ " * "+fd.getSafeSymbol()+";");
+ } else {
+ classdefout.println(" struct "+fd.getType().getSafeSymbol()+" * "+fd.getSafeSymbol()+";");
+ }
} else if (fd.isStatic()) {
- // TODO add version for normal Java later
- // static field
- if(globaldefout != null) {
- if(fd.isVolatile()) {
- globaldefprimout.println(" volatile "+fd.getType().getSafeSymbol()+ " "+fd.getSafeSymbol()+";");
- } else {
- globaldefprimout.println(" "+fd.getType().getSafeSymbol()+ " "+fd.getSafeSymbol()+";");
- }
- }
+ // TODO add version for normal Java later
+ // static field
+ if(globaldefout != null) {
+ if(fd.isVolatile()) {
+ globaldefprimout.println(" volatile "+fd.getType().getSafeSymbol()+ " "+fd.getSafeSymbol()+";");
+ } else {
+ globaldefprimout.println(" "+fd.getType().getSafeSymbol()+ " "+fd.getSafeSymbol()+";");
+ }
+ }
} else if (fd.isVolatile()) {
- //volatile field
- classdefout.println(" volatile "+fd.getType().getSafeSymbol()+ " "+fd.getSafeSymbol()+";");
+ //volatile field
+ classdefout.println(" volatile "+fd.getType().getSafeSymbol()+ " "+fd.getSafeSymbol()+";");
} else
- classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
+ classdefout.println(" "+fd.getType().getSafeSymbol()+" "+fd.getSafeSymbol()+";");
}
}
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;
- }
+ Hashtable superflags=(Hashtable)flagorder.get(sp);
+ Iterator superflagit=superflags.keySet().iterator();
+ while(superflagit.hasNext()) {
+ FlagDescriptor fd=(FlagDescriptor)superflagit.next();
+ Integer number=(Integer)superflags.get(fd);
+ flags.put(fd, number);
+ if ((number.intValue()+1)>max)
+ max=number.intValue()+1;
+ }
}
Iterator flagit=cn.getFlags();
while(flagit.hasNext()) {
- FlagDescriptor fd=(FlagDescriptor)flagit.next();
- if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
- flags.put(fd, new Integer(max++));
+ FlagDescriptor fd=(FlagDescriptor)flagit.next();
+ if (sp==null||!sp.getFlagTable().contains(fd.getSymbol()))
+ flags.put(fd, new Integer(max++));
}
}
}
classdefout.println(" volatile int notifycount;");
classdefout.println(" volatile int objlock;");
if(state.MULTICOREGC) {
- classdefout.println(" int marked;");
+ classdefout.println(" int marked;");
}
}
if (state.TASK) {
classdefout.println(" int flag;");
classdefout.println(" int ___cachedCode___;");
if((!state.MULTICORE) || (cn.getSymbol().equals("TagDescriptor"))) {
- classdefout.println(" void * flagptr;");
+ classdefout.println(" void * flagptr;");
} else if (state.MULTICORE) {
- classdefout.println(" int version;");
- classdefout.println(" int * lock;"); // lock entry for this obj
- classdefout.println(" int mutex;");
- classdefout.println(" volatile int lockcount;");
- if(state.MULTICOREGC) {
- classdefout.println(" int marked;");
- }
+ classdefout.println(" int version;");
+ classdefout.println(" int * lock;"); // lock entry for this obj
+ classdefout.println(" int mutex;");
+ classdefout.println(" volatile int lockcount;");
+ if(state.MULTICOREGC) {
+ classdefout.println(" int marked;");
+ }
}
if (state.OPTIONAL) {
- classdefout.println(" int numfses;");
- classdefout.println(" int * fses;");
+ classdefout.println(" int numfses;");
+ classdefout.println(" int * fses;");
}
}
if (javabuilder==null||javabuilder.hasLayout(cn))
FlatMethod fm=state.getMethodFlat(md);
if (!callgraph.isCallable(md)&&(!md.isStaticBlock()||!callgraph.isInit(cn))) {
- if (callgraph.isCalled(md)) {
- generateTempStructs(fm);
- generateMethodParam(cn, md, output);
- }
- continue;
+ if (callgraph.isCalled(md)) {
+ generateTempStructs(fm);
+ generateMethodParam(cn, md, output);
+ }
+ continue;
}
generateTempStructs(fm);
/* Output parameter structure */
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
if(md.isInvokedByStatic() && !md.isStaticBlock() && !md.getModifiers().isNative()) {
- // generate the staticinit version
- String mdstring = md.getSafeMethodDescriptor() + "staticinit";
-
- ParamsObject objectparams=(ParamsObject) paramstable.get(md);
- output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params {");
- output.println(" int size;");
- output.println(" void * next;");
- for(int i=0; i<objectparams.numPointers(); i++) {
- TempDescriptor temp=objectparams.getPointer(i);
- if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
- output.println(" int " + temp.getSafeSymbol() + ";");
- } else {
- output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
- }
- }
- output.println("};\n");
+ // generate the staticinit version
+ String mdstring = md.getSafeMethodDescriptor() + "staticinit";
+
+ ParamsObject objectparams=(ParamsObject) paramstable.get(md);
+ output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params {");
+ output.println(" int size;");
+ output.println(" void * next;");
+ for(int i=0; i<objectparams.numPointers(); i++) {
+ TempDescriptor temp=objectparams.getPointer(i);
+ if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
+ output.println(" int " + temp.getSafeSymbol() + ";");
+ } else {
+ output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
+ }
+ }
+ output.println("};\n");
}
ParamsObject objectparams=(ParamsObject) paramstable.get(md);
output.println(" int size;");
output.println(" void * next;");
for(int i=0; i<objectparams.numPointers(); i++) {
- TempDescriptor temp=objectparams.getPointer(i);
- if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
- output.println(" int " + temp.getSafeSymbol() + ";");
- } else {
- output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
- }
+ TempDescriptor temp=objectparams.getPointer(i);
+ if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
+ output.println(" int " + temp.getSafeSymbol() + ";");
+ } else {
+ output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
+ }
}
output.println("};\n");
}
/* Output temp structure */
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_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().isArray() && temp.getType().isNull())
- output.println(" void * "+temp.getSafeSymbol()+";");
- else
- output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
- }
- output.println("};\n");
+ output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_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().isArray() && temp.getType().isNull())
+ output.println(" void * "+temp.getSafeSymbol()+";");
+ else
+ output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
+ }
+ output.println("};\n");
}
headersout.println("#define D"+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+" 1");
/* First the return type */
if (md.getReturnType()!=null) {
- if(md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
- headersout.println(" int ");
- } else if (md.getReturnType().isClass()||md.getReturnType().isArray())
- headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
- else
- headersout.print(md.getReturnType().getSafeSymbol()+" ");
+ if(md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
+ headersout.println(" int ");
+ } else 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 ");
+ //catch the constructor case
+ headersout.print("void ");
/* Next the method name */
headersout.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"(");
printcomma=false;
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params * "+paramsprefix);
- printcomma=true;
+ headersout.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params * "+paramsprefix);
+ 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().getClassDesc().isEnum()) {
- headersout.print("int " + temp.getSafeSymbol());
- } else if (temp.getType().isClass()||temp.getType().isArray())
- headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
- else
- headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
+ TempDescriptor temp=objectparams.getPrimitive(i);
+ if (printcomma)
+ headersout.print(", ");
+ printcomma=true;
+ if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
+ headersout.print("int " + temp.getSafeSymbol());
+ } else if (temp.getType().isClass()||temp.getType().isArray())
+ headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
+ else
+ headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
}
if(md.getSymbol().equals("MonitorEnter") && state.OBJECTLOCKDEBUG) {
- headersout.print(", int linenum");
+ headersout.print(", int linenum");
}
headersout.println(");\n");
}
output.println(" int size;");
output.println(" void * next;");
for(int i=0; i<objecttemps.numPointers(); i++) {
- TempDescriptor temp=objecttemps.getPointer(i);
- if (!temp.getType().isArray() && temp.getType().isNull())
- output.println(" void * "+temp.getSafeSymbol()+";");
- else
- output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
+ TempDescriptor temp=objecttemps.getPointer(i);
+ if (!temp.getType().isArray() && temp.getType().isNull())
+ output.println(" void * "+temp.getSafeSymbol()+";");
+ else
+ output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
}
output.println("};\n");
}
/* First the return type */
if (md.getReturnType()!=null) {
if(md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
- headersout.println(" int ");
+ headersout.println(" int ");
} else if (md.getReturnType().isClass()||md.getReturnType().isArray())
- headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
+ headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
else
- headersout.print(md.getReturnType().getSafeSymbol()+" ");
+ headersout.print(md.getReturnType().getSafeSymbol()+" ");
} else
//catch the constructor case
headersout.print("void ");
for(int i=0; i<objectparams.numPrimitives(); i++) {
TempDescriptor temp=objectparams.getPrimitive(i);
if (printcomma)
- headersout.print(", ");
+ headersout.print(", ");
printcomma=true;
if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
- headersout.print("int " + temp.getSafeSymbol());
+ headersout.print("int " + temp.getSafeSymbol());
} else if (temp.getType().isClass()||temp.getType().isArray())
- headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
+ headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
else
- headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
+ headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
}
if(md.getSymbol().equals("MonitorEnter") && state.OBJECTLOCKDEBUG) {
headersout.print(", int linenum");
/* Output parameter structure */
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- output.println("struct "+task.getSafeSymbol()+"_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("struct "+task.getSafeSymbol()+"_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 ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
- maxtaskparams=objectparams.numPointers()+fm.numTags();
- }
+ output.println("};\n");
+ if ((objectparams.numPointers()+fm.numTags())>maxtaskparams) {
+ maxtaskparams=objectparams.numPointers()+fm.numTags();
+ }
}
/* Output temp structure */
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- output.println("struct "+task.getSafeSymbol()+"_locals {");
- output.println(" int size;");
- output.println(" void * next;");
- for(int i=0; i<objecttemps.numPointers(); i++) {
- TempDescriptor temp=objecttemps.getPointer(i);
- if (!temp.getType().isArray() && 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.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().isArray() && 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 */
boolean printcomma=false;
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
+ headersout.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
} else
- headersout.print("void * parameterarray[]");
+ headersout.print("void * parameterarray[]");
headersout.println(");\n");
}
}
for(int i=startindex; i<fm.numParameters(); i++) {
TempDescriptor tmp=fm.getParameter(i);
if (tmp.getType().isPtr()) {
- outmethod.println("jobject param"+i+"=JNIWRAP("+generateTemp(fm, fm.getParameter(i))+");");
+ outmethod.println("jobject param"+i+"=JNIWRAP("+generateTemp(fm, fm.getParameter(i))+");");
}
}
if (GENERATEPRECISEGC) {
}
if (!md.getReturnType().isVoid()) {
if (md.getReturnType().isPtr())
- outmethod.print("jobject retval=");
+ outmethod.print("jobject retval=");
else
- outmethod.print(md.getReturnType().getSafeSymbol()+" retval=");
+ outmethod.print(md.getReturnType().getSafeSymbol()+" retval=");
}
outmethod.print("Java_");
outmethod.print(cd.getPackage().replace('.','_'));
outmethod.print(", ");
TempDescriptor tmp=fm.getParameter(i);
if (tmp.getType().isPtr()) {
- outmethod.print("param"+i);
+ outmethod.print("param"+i);
} else {
- outmethod.print(generateTemp(fm, tmp));
+ outmethod.print(generateTemp(fm, tmp));
}
}
outmethod.println(");");
}
if (!md.getReturnType().isVoid()) {
if (md.getReturnType().isPtr()) {
- outmethod.println("struct ___Object___ * retobj=JNIUNWRAP(retval);");
- outmethod.println("JNIPOPFRAME();");
- outmethod.println("return retobj;");
+ outmethod.println("struct ___Object___ * retobj=JNIUNWRAP(retval);");
+ outmethod.println("JNIPOPFRAME();");
+ outmethod.println("return retobj;");
} else {
- outmethod.println("JNIPOPFRAME();");
- outmethod.println("return retval;");
+ outmethod.println("JNIPOPFRAME();");
+ outmethod.println("return retval;");
}
} else
outmethod.println("JNIPOPFRAME();");
TempObject objecttemp=(TempObject) tempstable.get(md!=null?md:task);
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_locals "+localsprefix+"={");
- output.print(objecttemp.numPointers()+",");
- output.print(paramsprefix);
- for(int j=0; j<objecttemp.numPointers(); j++)
- output.print(", NULL");
- output.println("};");
+ output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_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() && !type.isArray())
- output.println(" void * "+td.getSafeSymbol()+";");
- else if (type.isClass() && type.getClassDesc().isEnum()) {
- output.println(" int " + td.getSafeSymbol() + ";");
- } else if (type.isClass()||type.isArray())
- output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
- else
- output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
+ TempDescriptor td=objecttemp.getPrimitive(i);
+ TypeDescriptor type=td.getType();
+ if (type.isNull() && !type.isArray())
+ output.println(" void * "+td.getSafeSymbol()+";");
+ else if (type.isClass() && type.getClassDesc().isEnum()) {
+ output.println(" int " + td.getSafeSymbol() + ";");
+ } else if (type.isClass()||type.isArray())
+ output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
+ else
+ output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
}
additionalCodeAtTopFlatMethodBody(output, fm);
* multi-threaded program...*/
if (((state.OOOJAVA||state.THREAD)&&GENERATEPRECISEGC) || state.MULTICOREGC) {
- //Don't bother if we aren't in recursive methods...The loops case will catch it
- if (callgraph.getAllMethods(md).contains(md)) {
- if (this.state.MULTICOREGC) {
- output.println("if(gcflag) gc("+localsprefixaddr+");");
- } else {
- output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
- }
- }
+ //Don't bother if we aren't in recursive methods...The loops case will catch it
+ if (callgraph.getAllMethods(md).contains(md)) {
+ if (this.state.MULTICOREGC) {
+ output.println("if(gcflag) gc("+localsprefixaddr+");");
+ } else {
+ output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
+ }
+ }
}
generateCode(fm.getNext(0), fm, null, output);
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
if (md!=null)
- output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
+ output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
else
- output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
+ output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
output.print(objecttemp.numPointers()+",");
output.print(paramsprefix);
for(int j=0; j<objecttemp.numPointers(); j++)
- output.print(", NULL");
+ output.print(", NULL");
output.println("};");
}
TempDescriptor td=objecttemp.getPrimitive(i);
TypeDescriptor type=td.getType();
if (type.isNull() && !type.isArray())
- output.println(" void * "+td.getSafeSymbol()+";");
+ output.println(" void * "+td.getSafeSymbol()+";");
else if (type.isClass() && type.getClassDesc().isEnum()) {
- output.println(" int " + td.getSafeSymbol() + ";");
+ output.println(" int " + td.getSafeSymbol() + ";");
} else if (type.isClass()||type.isArray())
- output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
+ output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
else
- output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
+ output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
}
additionalCodeAtTopFlatMethodBody(output, fm);
|| this.state.MULTICOREGC) {
//Don't bother if we aren't in recursive methods...The loops case will catch it
if (callgraph.getAllMethods(md).contains(md)) {
- if (this.state.MULTICOREGC) {
- output.println("if(gcflag) gc("+localsprefixaddr+");");
- } else {
- output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
- }
+ if (this.state.MULTICOREGC) {
+ output.println("if(gcflag) gc("+localsprefixaddr+");");
+ } else {
+ output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
+ }
}
}
tovisit.add(first);
while(current_node!=null||!tovisit.isEmpty()) {
if (current_node==null) {
- current_node=(FlatNode)tovisit.iterator().next();
- tovisit.remove(current_node);
+ current_node=(FlatNode)tovisit.iterator().next();
+ tovisit.remove(current_node);
} else if (tovisit.contains(current_node)) {
- tovisit.remove(current_node);
+ tovisit.remove(current_node);
}
visited.add(current_node);
if (nodetolabel.containsKey(current_node)) {
- output.println("L"+nodetolabel.get(current_node)+":");
+ output.println("L"+nodetolabel.get(current_node)+":");
}
if (state.INSTRUCTIONFAILURE) {
- if (state.THREAD) {
- output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
- } else
- output.println("if ((--instructioncount)==0) injectinstructionfailure();");
+ if (state.THREAD) {
+ output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
+ } else
+ output.println("if ((--instructioncount)==0) injectinstructionfailure();");
}
if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
- output.print(" ");
- generateFlatNode(fm, current_node, output);
-
- if (state.OOOJAVA && stopset!=null) {
- assert first.getPrev(0) instanceof FlatSESEEnterNode;
- assert current_node instanceof FlatSESEExitNode;
- FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev(0);
- FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
- assert fsen.getFlatExit().equals(fsxn);
- assert fsxn.getFlatEnter().equals(fsen);
- }
- if (current_node.kind()!=FKind.FlatReturnNode) {
- if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
- // a static block, check if it has been executed
- output.println(" global_defsprim_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
- output.println("");
- }
- output.println(" return;");
- }
- current_node=null;
+ output.print(" ");
+ generateFlatNode(fm, current_node, output);
+
+ if (state.OOOJAVA && stopset!=null) {
+ assert first.getPrev(0) instanceof FlatSESEEnterNode;
+ assert current_node instanceof FlatSESEExitNode;
+ FlatSESEEnterNode fsen = (FlatSESEEnterNode) first.getPrev(0);
+ FlatSESEExitNode fsxn = (FlatSESEExitNode) current_node;
+ assert fsen.getFlatExit().equals(fsxn);
+ assert fsxn.getFlatEnter().equals(fsen);
+ }
+ if (current_node.kind()!=FKind.FlatReturnNode) {
+ if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
+ // a static block, check if it has been executed
+ output.println(" global_defsprim_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
+ output.println("");
+ }
+ output.println(" return;");
+ }
+ current_node=null;
} else if(current_node.numNext()==1) {
- FlatNode nextnode;
- if (state.OOOJAVA &&
- current_node.kind()==FKind.FlatSESEEnterNode) {
- FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
- generateFlatNode(fm, current_node, output);
- nextnode=fsen.getFlatExit().getNext(0);
- } else {
- output.print(" ");
- generateFlatNode(fm, current_node, output);
- nextnode=current_node.getNext(0);
- }
- if (visited.contains(nextnode)) {
- output.println("goto L"+nodetolabel.get(nextnode)+";");
- current_node=null;
- } else
- current_node=nextnode;
+ FlatNode nextnode;
+ if (state.OOOJAVA &&
+ current_node.kind()==FKind.FlatSESEEnterNode) {
+ FlatSESEEnterNode fsen = (FlatSESEEnterNode)current_node;
+ generateFlatNode(fm, current_node, output);
+ nextnode=fsen.getFlatExit().getNext(0);
+ } else {
+ output.print(" ");
+ generateFlatNode(fm, current_node, output);
+ nextnode=current_node.getNext(0);
+ }
+ if (visited.contains(nextnode)) {
+ output.println("goto L"+nodetolabel.get(nextnode)+";");
+ current_node=null;
+ } else
+ current_node=nextnode;
} else if (current_node.numNext()==2) {
- /* Branch */
- output.print(" ");
- generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
- if (!visited.contains(current_node.getNext(1)))
- tovisit.add(current_node.getNext(1));
- if (visited.contains(current_node.getNext(0))) {
- output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
- current_node=null;
- } else
- current_node=current_node.getNext(0);
+ /* Branch */
+ output.print(" ");
+ generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
+ if (!visited.contains(current_node.getNext(1)))
+ tovisit.add(current_node.getNext(1));
+ if (visited.contains(current_node.getNext(0))) {
+ output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
+ current_node=null;
+ } else
+ current_node=current_node.getNext(0);
} else throw new Error();
}
}
if(lastset!=null&&lastset.contains(fn)) {
- // if last is not null and matches, don't go
- // any further for assigning labels
- continue;
+ // if last is not null and matches, don't go
+ // any further for assigning labels
+ continue;
}
for(int i=0; i<fn.numNext(); i++) {
- FlatNode nn=fn.getNext(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++));
- }
+ 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;
if (((state.OOOJAVA||state.THREAD)&&GENERATEPRECISEGC)
|| (this.state.MULTICOREGC)) {
if(this.state.MULTICOREGC) {
- output.println("if (gcflag) gc("+localsprefixaddr+");");
+ output.println("if (gcflag) gc("+localsprefixaddr+");");
} else {
- output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
+ output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
}
} else
output.println("/* nop */");
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])+";");
+ output.println(varname+"->"+vars[i]+"=(unsigned int)"+generateTemp(fm, temps[i])+";");
}
output.println("if (doanalysis"+specname+"("+varname+")) {");
if((md.isStatic() || md.isStaticBlock() || md.isConstructor()) &&
((fm.getMethod() != null) && ((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())))) {
if(!md.isInvokedByStatic()) {
- System.err.println("Error: a method that is invoked inside a static block is not tagged!");
+ System.err.println("Error: a method that is invoked inside a static block is not tagged!");
}
// is a static block or is invoked in some static block
ClassDescriptor cd = fm.getMethod().getClassDesc();
if(cd != cn && mgcstaticinit && callgraph.isInit(cn)) {
- // generate static init check code if it has not done static init in main()
- if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
- // need to check if the class' static fields have been initialized and/or
- // its static blocks have been executed
- output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
- if(cn.getNumStaticBlocks() != 0) {
- MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
- if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- output.print(" struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
- output.println("0, NULL};");
- output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
- } else {
- output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
- }
- } else {
- output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
- }
- output.println("}");
- }
+ // generate static init check code if it has not done static init in main()
+ if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
+ // need to check if the class' static fields have been initialized and/or
+ // its static blocks have been executed
+ output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
+ if(cn.getNumStaticBlocks() != 0) {
+ MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
+ if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
+ output.print(" struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
+ output.println("0, NULL};");
+ output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
+ } else {
+ output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
+ }
+ } else {
+ output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
+ }
+ output.println("}");
+ }
}
}
if((md.getSymbol().equals("MonitorEnter") || md.getSymbol().equals("MonitorExit")) && fc.getThis().getSymbol().equals("classobj")) {
output.println("{");
if(md.getSymbol().equals("MonitorEnter") && state.OBJECTLOCKDEBUG) {
- output.println("int monitorenterline = __LINE__;");
+ output.println("int monitorenterline = __LINE__;");
}
// call MonitorEnter/MonitorExit on a class obj
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
- output.println("1," + localsprefixaddr + ", ((void **)(((char *) &(global_defs_p->classobjs->___length___))+sizeof(int)))[" + fc.getThis().getType().getClassDesc().getId() + "]};");
- if(md.getSymbol().equals("MonitorEnter") && state.OBJECTLOCKDEBUG) {
- output.println(" "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__, monitorenterline);");
- } else {
- output.println(" "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
- }
+ output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
+ output.println("1," + localsprefixaddr + ", ((void **)(((char *) &(global_defs_p->classobjs->___length___))+sizeof(int)))[" + fc.getThis().getType().getClassDesc().getId() + "]};");
+ if(md.getSymbol().equals("MonitorEnter") && state.OBJECTLOCKDEBUG) {
+ output.println(" "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__, monitorenterline);");
+ } else {
+ output.println(" "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"(& __parameterlist__);");
+ }
} else {
- output.println(" " + cn.getSafeSymbol()+md.getSafeSymbol()+"_"
- + md.getSafeMethodDescriptor() + "((struct ___Object___*)(((void **)(((char *) &(global_defs_p->classobjs->___length___))+sizeof(int)))["
- + fc.getThis().getType().getClassDesc().getId() + "]));");
+ output.println(" " + cn.getSafeSymbol()+md.getSafeSymbol()+"_"
+ + md.getSafeMethodDescriptor() + "((struct ___Object___*)(((void **)(((char *) &(global_defs_p->classobjs->___length___))+sizeof(int)))["
+ + fc.getThis().getType().getClassDesc().getId() + "]));");
}
output.println("}");
return;
output.print(objectparams.numPointers());
output.print(", "+localsprefixaddr);
if (md.getThis()!=null) {
- output.print(", ");
- output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis()));
+ output.print(", ");
+ output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis()));
}
if (fc.getThis()!=null&&md.getThis()==null) {
- System.out.println("WARNING!!!!!!!!!!!!");
- System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
+ System.out.println("WARNING!!!!!!!!!!!!");
+ System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
}
for(int i=0; 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));
- else
- output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ));
- }
+ 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));
+ else
+ output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ));
+ }
}
output.println("};");
}
//yes
output.print("((");
if (md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
- output.print("int ");
+ output.print("int ");
} else if (md.getReturnType().isClass()||md.getReturnType().isArray())
- output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
+ output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
else
- output.print(md.getReturnType().getSafeSymbol()+" ");
+ output.print(md.getReturnType().getSafeSymbol()+" ");
output.print("(*)(");
boolean printcomma=false;
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params * ");
- printcomma=true;
+ output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_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().getClassDesc().isEnum()) {
- output.print("int ");
- } else if (temp.getType().isClass()||temp.getType().isArray())
- output.print("struct " + temp.getType().getSafeSymbol()+" * ");
- else
- output.print(temp.getType().getSafeSymbol());
+ TempDescriptor temp=objectparams.getPrimitive(i);
+ if (printcomma)
+ output.print(", ");
+ printcomma=true;
+ if (temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
+ output.print("int ");
+ } else if (temp.getType().isClass()||temp.getType().isArray())
+ output.print("struct " + temp.getType().getSafeSymbol()+" * ");
+ else
+ output.print(temp.getType().getSafeSymbol());
}
if(md.getSymbol().equals("MonitorEnter") && state.OBJECTLOCKDEBUG) {
- output.print(", int");
+ output.print(", int");
}
output.print("))virtualtable["+generateTemp(fm,fc.getThis())+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
}
if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
if (fc.getThis()!=null) {
- TypeDescriptor ptd=null;
- if(md.getThis() != null) {
- ptd = md.getThis().getType();
- } else {
- ptd = fc.getThis().getType();
- }
- if (needcomma)
- output.print(",");
- if(ptd.isClass() && ptd.getClassDesc().isEnum()) {
- // do nothing
- } else if (ptd.isClass()&&!ptd.isArray())
- output.print("(struct "+ptd.getSafeSymbol()+" *) ");
- output.print(generateTemp(fm,fc.getThis()));
- needcomma=true;
+ TypeDescriptor ptd=null;
+ if(md.getThis() != null) {
+ ptd = md.getThis().getType();
+ } else {
+ ptd = fc.getThis().getType();
+ }
+ if (needcomma)
+ output.print(",");
+ if(ptd.isClass() && ptd.getClassDesc().isEnum()) {
+ // do nothing
+ } else if (ptd.isClass()&&!ptd.isArray())
+ output.print("(struct "+ptd.getSafeSymbol()+" *) ");
+ output.print(generateTemp(fm,fc.getThis()));
+ needcomma=true;
}
}
Descriptor var=md.getParameter(i);
TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
if (objectparams.isParamPrim(paramtemp)) {
- TempDescriptor targ=fc.getArg(i);
- if (needcomma)
- output.print(", ");
+ TempDescriptor targ=fc.getArg(i);
+ if (needcomma)
+ output.print(", ");
- TypeDescriptor ptd=md.getParamType(i);
- if (ptd.isClass() && ptd.getClassDesc().isEnum()) {
- // do nothing
- } else if (ptd.isClass()&&!ptd.isArray())
- output.print("(struct "+ptd.getSafeSymbol()+" *) ");
- output.print(generateTemp(fm, targ));
- needcomma=true;
+ TypeDescriptor ptd=md.getParamType(i);
+ if (ptd.isClass() && ptd.getClassDesc().isEnum()) {
+ // do nothing
+ } else if (ptd.isClass()&&!ptd.isArray())
+ output.print("(struct "+ptd.getSafeSymbol()+" *) ");
+ output.print(generateTemp(fm, targ));
+ needcomma=true;
}
}
if(md.getSymbol().equals("MonitorEnter") && state.OBJECTLOCKDEBUG) {
} else {
Set subclasses=typeutil.getSubClasses(thiscd);
if (subclasses==null)
- return true;
+ return true;
for(Iterator classit=subclasses.iterator(); classit.hasNext(); ) {
- ClassDescriptor cd=(ClassDescriptor)classit.next();
- Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
- for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) {
- MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
- if (md.matches(matchmd))
- return false;
- }
+ ClassDescriptor cd=(ClassDescriptor)classit.next();
+ Set possiblematches=cd.getMethodTable().getSetFromSameScope(md.getSymbol());
+ for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) {
+ MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
+ if (md.matches(matchmd))
+ return false;
+ }
}
}
return true;
if(ffn.getField().isStatic()) {
// static field
if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) {
- // is a static block or is invoked in some static block
- ClassDescriptor cd = fm.getMethod().getClassDesc();
- ClassDescriptor cn = ffn.getSrc().getType().getClassDesc();
- if(cd != cn && mgcstaticinit && callgraph.isInit(cn)) {
- // generate the static init check code if has not done the static init in main()
- if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
- // need to check if the class' static fields have been initialized and/or
- // its static blocks have been executed
- output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
- if(cn.getNumStaticBlocks() != 0) {
- MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
- if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- output.print(" struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
- output.println("0, NULL};");
- output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
- } else {
- output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
- }
- } else {
- output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
- }
- output.println("}");
- }
- }
+ // is a static block or is invoked in some static block
+ ClassDescriptor cd = fm.getMethod().getClassDesc();
+ ClassDescriptor cn = ffn.getSrc().getType().getClassDesc();
+ if(cd != cn && mgcstaticinit && callgraph.isInit(cn)) {
+ // generate the static init check code if has not done the static init in main()
+ if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
+ // need to check if the class' static fields have been initialized and/or
+ // its static blocks have been executed
+ output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
+ if(cn.getNumStaticBlocks() != 0) {
+ MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
+ if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
+ output.print(" struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
+ output.println("0, NULL};");
+ output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
+ } else {
+ output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
+ }
+ } else {
+ output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
+ }
+ output.println("}");
+ }
+ }
}
// redirect to the global_defs_p structure
if (ffn.getField().getType().isPtr())
- output.println(generateTemp(fm, ffn.getDst())+"=global_defs_p->"+ffn.getField().getSafeSymbol()+";");
+ output.println(generateTemp(fm, ffn.getDst())+"=global_defs_p->"+ffn.getField().getSafeSymbol()+";");
else
- output.println(generateTemp(fm, ffn.getDst())+"=global_defsprim_p->"+ffn.getField().getSafeSymbol()+";");
+ output.println(generateTemp(fm, ffn.getDst())+"=global_defsprim_p->"+ffn.getField().getSafeSymbol()+";");
} else if (ffn.getField().isEnum()) {
// an Enum value, directly replace the field access as int
output.println(generateTemp(fm, ffn.getDst()) + "=" + ffn.getField().enumValue() + ";");
output.println("if (" + generateTemp(fm,ffn.getSrc()) + " == NULL) {");
output.println("printf(\" NULL ptr error: %s, %s, %d \\n\", __FILE__, __func__, __LINE__);");
if(state.MULTICOREGC) {
- output.println("failednullptr(&___locals___);");
+ output.println("failednullptr(&___locals___);");
} else {
- output.println("failednullptr(NULL);");
+ output.println("failednullptr(NULL);");
}
output.println("}");
output.println("#endif //MULTICORE_DEBUG");
output.println("if(!"+dst+"->"+localcopystr+") {");
/* Link object into list */
if (GENERATEPRECISEGC || this.state.MULTICOREGC)
- output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
+ output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
else
- output.println("COPY_OBJ("+dst+");");
+ output.println("COPY_OBJ("+dst+");");
output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
output.println("}");
if(fsfn.getField().isStatic()) {
// static field
if((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic())) {
- // is a static block or is invoked in some static block
- ClassDescriptor cd = fm.getMethod().getClassDesc();
- ClassDescriptor cn = fsfn.getDst().getType().getClassDesc();
- if(cd != cn && mgcstaticinit && callgraph.isInit(cn)) {
- // generate static init check code if has not done the static init in main()
- if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
- // need to check if the class' static fields have been initialized and/or
- // its static blocks have been executed
- output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
- if(cn.getNumStaticBlocks() != 0) {
- MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
- if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- output.print(" struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
- output.println("0, NULL};");
- output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
- } else {
- output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
- }
- } else {
- output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
- }
- output.println("}");
- }
- }
+ // is a static block or is invoked in some static block
+ ClassDescriptor cd = fm.getMethod().getClassDesc();
+ ClassDescriptor cn = fsfn.getDst().getType().getClassDesc();
+ if(cd != cn && mgcstaticinit && callgraph.isInit(cn)) {
+ // generate static init check code if has not done the static init in main()
+ if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
+ // need to check if the class' static fields have been initialized and/or
+ // its static blocks have been executed
+ output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
+ if(cn.getNumStaticBlocks() != 0) {
+ MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
+ if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
+ output.print(" struct "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"_params __parameterlist__={");
+ output.println("0, NULL};");
+ output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"(& __parameterlist__);");
+ } else {
+ output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
+ }
+ } else {
+ output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
+ }
+ output.println("}");
+ }
+ }
}
// redirect to the global_defs_p structure
if (fsfn.getField().getType().isPtr()) {
- if (fsfn.getField().getType()!=fsfn.getSrc().getType())
- output.println("global_defs_p->" +
- fsfn.getField().getSafeSymbol()+"=(struct "+ fsfn.getField().getType().getSafeSymbol()+" *)"+generateTemp(fm,fsfn.getSrc())+";");
- else
- output.println("global_defs_p->" +
- fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
+ if (fsfn.getField().getType()!=fsfn.getSrc().getType())
+ output.println("global_defs_p->" +
+ fsfn.getField().getSafeSymbol()+"=(struct "+ fsfn.getField().getType().getSafeSymbol()+" *)"+generateTemp(fm,fsfn.getSrc())+";");
+ else
+ output.println("global_defs_p->" +
+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
} else
- output.println("global_defsprim_p->" +
- fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
+ output.println("global_defsprim_p->" +
+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
} else {
output.println("#ifdef MULTICORE_DEBUG");
output.println("if (" + generateTemp(fm,fsfn.getDst()) + " == NULL) {");
output.println("printf(\" NULL ptr error: %s, %s, %d \\n\", __FILE__, __func__, __LINE__);");
if(state.MULTICOREGC) {
- output.println("failednullptr(&___locals___);");
+ output.println("failednullptr(&___locals___);");
} else {
- output.println("failednullptr(NULL);");
+ output.println("failednullptr(NULL);");
}
output.println("}");
output.println("#endif //MULTICORE_DEBUG");
if (fsfn.getSrc().getType().isPtr()&&fsfn.getSrc().getType()!=fsfn.getField().getType())
- output.println(generateTemp(fm, fsfn.getDst())+"->"+
- fsfn.getField().getSafeSymbol()+"=(struct "+ fsfn.getField().getType().getSafeSymbol()+"*)"+generateTemp(fm,fsfn.getSrc())+";");
+ output.println(generateTemp(fm, fsfn.getDst())+"->"+
+ fsfn.getField().getSafeSymbol()+"=(struct "+ fsfn.getField().getType().getSafeSymbol()+"*)"+generateTemp(fm,fsfn.getSrc())+";");
else
- output.println(generateTemp(fm, fsfn.getDst())+"->"+
- fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
+ output.println(generateTemp(fm, fsfn.getDst())+"->"+
+ fsfn.getField().getSafeSymbol()+"="+ generateTemp(fm,fsfn.getSrc())+";");
}
}
output.println("if(!"+dst+"->"+localcopystr+") {");
/* Link object into list */
if (GENERATEPRECISEGC || this.state.MULTICOREGC)
- output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
+ output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
else
- output.println("COPY_OBJ("+dst+");");
+ output.println("COPY_OBJ("+dst+");");
output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
output.println("}");
if (fn.getType().isArray()) {
int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");");
+ output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");");
} else {
- output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize())+");");
+ output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize())+");");
}
} else {
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
+ output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
} else {
- output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
+ output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
}
}
if (state.FASTCHECK) {
protected void generateFlatOpNode(FlatMethod fm, FlatOpNode fon, PrintWriter output) {
if (fon.getRight()!=null) {
if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
- if (fon.getLeft().getType().isLong())
- output.println(generateTemp(fm, fon.getDest())+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";");
- else
- output.println(generateTemp(fm, fon.getDest())+" = ((unsigned int)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";");
+ if (fon.getLeft().getType().isLong())
+ output.println(generateTemp(fm, fon.getDest())+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";");
+ else
+ output.println(generateTemp(fm, fon.getDest())+" = ((unsigned int)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";");
} else {
- if (fon.getLeft().getType().isPtr()&&fon.getLeft().getType()!=fon.getRight().getType()&&!fon.getRight().getType().isNull())
- output.println(generateTemp(fm, fon.getDest())+" = (struct "+fon.getRight().getType().getSafeSymbol()+"*)"+generateTemp(fm, fon.getLeft())+fon.getOp().toString()+generateTemp(fm,fon.getRight())+";");
- else
- output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+fon.getOp().toString()+generateTemp(fm,fon.getRight())+";");
+ if (fon.getLeft().getType().isPtr()&&fon.getLeft().getType()!=fon.getRight().getType()&&!fon.getRight().getType().isNull())
+ output.println(generateTemp(fm, fon.getDest())+" = (struct "+fon.getRight().getType().getSafeSymbol()+"*)"+generateTemp(fm, fon.getLeft())+fon.getOp().toString()+generateTemp(fm,fon.getRight())+";");
+ else
+ output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+fon.getOp().toString()+generateTemp(fm,fon.getRight())+";");
}
} else if (fon.getOp().getOp()==Operation.ASSIGN)
if (fon.getDest().getType().isPtr()&&fon.getDest().getType()!=fon.getLeft().getType())
- output.println(generateTemp(fm, fon.getDest())+" = (struct "+fon.getDest().getType().getSafeSymbol()+"*)"+generateTemp(fm, fon.getLeft())+";");
+ output.println(generateTemp(fm, fon.getDest())+" = (struct "+fon.getDest().getType().getSafeSymbol()+"*)"+generateTemp(fm, fon.getLeft())+";");
else
- output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+";");
+ output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+";");
else if (fon.getOp().getOp()==Operation.UNARYPLUS)
output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+";");
else if (fon.getOp().getOp()==Operation.UNARYMINUS)
output.println("{");
output.print("short str"+flncount+"[]={");
for(int i=0; i<str.length(); i++) {
- if (i!=0)
- output.print(", ");
- output.print(((int)str.charAt(i)));
+ if (i!=0)
+ output.print(", ");
+ output.print(((int)str.charAt(i)));
}
output.println("};");
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- output.println(generateTemp(fm, fln.getDst())+"=NewStringShort("+localsprefixaddr+", str"+flncount+", "+((String)fln.getValue()).length()+");");
+ output.println(generateTemp(fm, fln.getDst())+"=NewStringShort("+localsprefixaddr+", str"+flncount+", "+((String)fln.getValue()).length()+");");
} else {
- output.println(generateTemp(fm, fln.getDst())+"=NewStringShort(str"+flncount+" ,"+((String)fln.getValue()).length()+");");
+ output.println(generateTemp(fm, fln.getDst())+"=NewStringShort(str"+flncount+" ,"+((String)fln.getValue()).length()+");");
}
output.println("}");
flncount++;
} else if (fln.getType().isBoolean()) {
if (((Boolean)fln.getValue()).booleanValue())
- output.println(generateTemp(fm, fln.getDst())+"=1;");
+ output.println(generateTemp(fm, fln.getDst())+"=1;");
else
- output.println(generateTemp(fm, fln.getDst())+"=0;");
+ output.println(generateTemp(fm, fln.getDst())+"=0;");
} else if (fln.getType().isChar()) {
int val=(int)(((Character)fln.getValue()).charValue());
output.println(generateTemp(fm, fln.getDst())+"="+val+";");
if (frn.getReturnTemp()!=null) {
if (frn.getReturnTemp().getType().isPtr())
- output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp())+";");
+ output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp())+";");
else
- output.println("return "+generateTemp(fm, frn.getReturnTemp())+";");
+ output.println("return "+generateTemp(fm, frn.getReturnTemp())+";");
} else {
output.println("return;");
}
if (md!=null&&md.getReturnType()!=null) {
if (md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
- output.print("int ");
+ output.print("int ");
} else if (md.getReturnType().isClass()||md.getReturnType().isArray())
- output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
+ output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
else
- output.print(md.getReturnType().getSafeSymbol()+" ");
+ output.print(md.getReturnType().getSafeSymbol()+" ");
} else
//catch the constructor case
output.print("void ");
if (md!=null) {
if(mgcstaticinit && !md.isStaticBlock() && !md.getModifiers().isNative()) {
- mdstring += "staticinit";
+ mdstring += "staticinit";
}
output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"(");
} else
boolean printcomma=false;
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
if (md!=null) {
- output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params * "+paramsprefix);
+ output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+mdstring+"_params * "+paramsprefix);
} else
- output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
+ output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
printcomma=true;
}
if (md!=null) {
/* Method */
for(int i=0; i<objectparams.numPrimitives(); i++) {
- TempDescriptor temp=objectparams.getPrimitive(i);
- if (printcomma)
- output.print(", ");
- printcomma=true;
- if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
- output.print("int " + temp.getSafeSymbol());
- } else if (temp.getType().isClass()||temp.getType().isArray())
- output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
- else
- output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
+ TempDescriptor temp=objectparams.getPrimitive(i);
+ if (printcomma)
+ output.print(", ");
+ printcomma=true;
+ if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
+ output.print("int " + temp.getSafeSymbol());
+ } else 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 && !this.state.MULTICOREGC) {
output.println("void * parameterarray[]) {");
/* Unpack variables */
for(int i=0; i<objectparams.numPrimitives(); i++) {
- TempDescriptor temp=objectparams.getPrimitive(i);
- if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
- output.print("int " + temp.getSafeSymbol() + "=parameterarray["+i+"];");
- } else {
- output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
- }
+ TempDescriptor temp=objectparams.getPrimitive(i);
+ if(temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
+ output.print("int " + temp.getSafeSymbol() + "=parameterarray["+i+"];");
+ } else {
+ 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+"];");
+ 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();
+ maxtaskparams=objectparams.numPrimitives()+fm.numTags();
} else output.println(") {");
}
TempDescriptor tagtmp=ttp.getTagTemp();
boolean tagstatus=ffan.getTagChange(ttp);
if (tagstatus) {
- tagsettable.put(objtmp, tagtmp);
+ tagsettable.put(objtmp, tagtmp);
} else {
- tagcleartable.put(objtmp, tagtmp);
+ tagcleartable.put(objtmp, tagtmp);
}
}
Hashtable flagtable=(Hashtable)flagorder.get(temp.getType().getClassDesc());
FlagDescriptor flag=tfp.getFlag();
if (flag==null) {
- //Newly allocate objects that don't set any flags case
- if (flagortable.containsKey(temp)) {
- throw new Error();
- }
- int mask=0;
- flagortable.put(temp,new Integer(mask));
+ //Newly allocate objects that don't set any flags case
+ if (flagortable.containsKey(temp)) {
+ throw new Error();
+ }
+ int mask=0;
+ flagortable.put(temp,new Integer(mask));
} else {
- int flagid=1<<((Integer)flagtable.get(flag)).intValue();
- boolean flagstatus=ffan.getFlagChange(tfp);
- if (flagstatus) {
- int mask=0;
- if (flagortable.containsKey(temp)) {
- mask=((Integer)flagortable.get(temp)).intValue();
- }
- mask|=flagid;
- flagortable.put(temp,new Integer(mask));
- } else {
- int mask=0xFFFFFFFF;
- if (flagandtable.containsKey(temp)) {
- mask=((Integer)flagandtable.get(temp)).intValue();
- }
- mask&=(0xFFFFFFFF^flagid);
- flagandtable.put(temp,new Integer(mask));
- }
+ int flagid=1<<((Integer)flagtable.get(flag)).intValue();
+ boolean flagstatus=ffan.getFlagChange(tfp);
+ if (flagstatus) {
+ int mask=0;
+ if (flagortable.containsKey(temp)) {
+ mask=((Integer)flagortable.get(temp)).intValue();
+ }
+ mask|=flagid;
+ flagortable.put(temp,new Integer(mask));
+ } else {
+ int mask=0xFFFFFFFF;
+ if (flagandtable.containsKey(temp)) {
+ mask=((Integer)flagandtable.get(temp)).intValue();
+ }
+ mask&=(0xFFFFFFFF^flagid);
+ flagandtable.put(temp,new Integer(mask));
+ }
}
}
Set tagtmps=tagcleartable.get(temp);
if (tagtmps!=null) {
- Iterator tagit=tagtmps.iterator();
- while(tagit.hasNext()) {
- TempDescriptor tagtmp=(TempDescriptor)tagit.next();
- if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
- output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
- else
- output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
- }
+ Iterator tagit=tagtmps.iterator();
+ while(tagit.hasNext()) {
+ TempDescriptor tagtmp=(TempDescriptor)tagit.next();
+ if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
+ output.println("tagclear("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
+ else
+ output.println("tagclear((struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
+ }
}
tagtmps=tagsettable.get(temp);
if (tagtmps!=null) {
- Iterator tagit=tagtmps.iterator();
- while(tagit.hasNext()) {
- TempDescriptor tagtmp=(TempDescriptor)tagit.next();
- if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
- output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
- else
- output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
- }
+ Iterator tagit=tagtmps.iterator();
+ while(tagit.hasNext()) {
+ TempDescriptor tagtmp=(TempDescriptor)tagit.next();
+ if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
+ output.println("tagset("+localsprefixaddr+", (struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
+ else
+ output.println("tagset((struct ___Object___ *)"+generateTemp(fm, temp)+", "+generateTemp(fm,tagtmp)+");");
+ }
}
int ormask=0;
int andmask=0xFFFFFFF;
if (flagortable.containsKey(temp))
- ormask=((Integer)flagortable.get(temp)).intValue();
+ ormask=((Integer)flagortable.get(temp)).intValue();
if (flagandtable.containsKey(temp))
- andmask=((Integer)flagandtable.get(temp)).intValue();
+ andmask=((Integer)flagandtable.get(temp)).intValue();
generateFlagOrAnd(ffan, fm, temp, output, ormask, andmask);
generateObjectDistribute(ffan, fm, temp, output);
}
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));
- }
- }
- }
+ 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");
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();
+ 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("};");
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");
- }
+ 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;
+ continue;
// if there are no optionals, there is no need to build the rest of the struct
output.println("struct optionaltaskdescriptor * otdarray"+cdtemp.getSafeSymbol()+"[]={");
c_otd = ((Hashtable)optionaltaskdescriptors.get(cdtemp)).values();
if( !c_otd.isEmpty() ) {
- boolean needcomma=false;
- for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext(); ) {
- OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
- if(needcomma)
- output.println(",");
- needcomma=true;
- output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
- }
+ boolean needcomma=false;
+ for(Iterator otd_it = c_otd.iterator(); otd_it.hasNext(); ) {
+ OptionalTaskDescriptor otd = (OptionalTaskDescriptor)otd_it.next();
+ if(needcomma)
+ output.println(",");
+ needcomma=true;
+ output.println("&optionaltaskdescriptor_"+otd.getuid()+"_"+cdtemp.getSafeSymbol());
+ }
}
output.println("};\n");
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");
+ 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");
}
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;
+ if (needcomma) output.print(",");
+ output.println("&fsanalysiswrapper_FS"+(i+1)+"_"+cdtemp.getSafeSymbol());
+ needcomma=true;
}
output.println("};");
for(int i=0; i<state.numClasses(); i++) {
ClassDescriptor cn=cdarray[i];
if (i>0)
- output.print(", ");
+ output.print(", ");
if ((cn != null) && (processedcd.contains(cn)))
- output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
+ output.print("&classanalysiswrapper_"+cn.getSafeSymbol());
else
- output.print("NULL");
+ output.print("NULL");
}
output.println("};");
for(Iterator it=r.keySet().iterator(); it.hasNext(); ) {
Set s=r.get(it.next());
for(Iterator it2=s.iterator(); it2.hasNext(); ) {
- OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
- l.add(otd);
+ OptionalTaskDescriptor otd=(OptionalTaskDescriptor)it2.next();
+ l.add(otd);
}
}
// do not generate the line number if it is same as the previous one
boolean needtoprint;
if(fn.prev.size()==0) {
- needtoprint=true;
+ needtoprint=true;
} else {
- needtoprint=false;
+ needtoprint=false;
}
for(int i=0; i<fn.prev.size(); i++) {
- int prevLineNum=((FlatNode)fn.prev.get(i)).getNumLine();
- if(prevLineNum!=lineNum) {
- needtoprint=true;
- break;
- }
+ int prevLineNum=((FlatNode)fn.prev.get(i)).getNumLine();
+ if(prevLineNum!=lineNum) {
+ needtoprint=true;
+ break;
+ }
}
if(needtoprint) {
- output.println("// "+fm.getMethod().getClassDesc().getSourceFileName()+":"+fn.getNumLine());
+ output.println("// "+fm.getMethod().getClassDesc().getSourceFileName()+":"+fn.getNumLine());
}
}
}
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);
- } */
+ 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);
/* The runtime keeps track of flags using these integers */
it=state.getClassSymbolTable().getDescriptorsIterator();
while(it.hasNext()) {
- ClassDescriptor cn=(ClassDescriptor)it.next();
- mapFlags(cn);
+ ClassDescriptor cn=(ClassDescriptor)it.next();
+ mapFlags(cn);
}
/* Generate Tasks */
generateTaskStructs(outstructs, outmethodheader);
if (state.TASK) {
Iterator[] taskits = new Iterator[this.coreNum];
for(int i = 0; i < taskits.length; ++i) {
- taskits[i] = null;
+ 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);
+ this.currentSchedule = this.scheduling.elementAt(i);
+ outputTaskCode(outtaskdefs, outmethod, outtask, taskits, numtasks, numqueues);
}
// Output task descriptors
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("}");
+ 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("}");
+ 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("};");
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);
+ 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 * " + 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);
+ 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]);
+ if (comma)
+ outtaskdefs.print(",");
+ else
+ comma=true;
+ outtaskdefs.print(numtasks[i]);
}
outtaskdefs.println("};");
outtaskdefs.println("int corenum=0;");
Iterator<TaskDescriptor> taskit = tmpschedule.getTasks().iterator();
while(taskit.hasNext()) {
- /* Classify parameters */
- TaskDescriptor task=taskit.next();
- FlatMethod fm=state.getMethodFlat(task);
- generateTempStructs(fm);
-
- ParamsObject objectparams=(ParamsObject) paramstable.get(task);
- TempObject objecttemps=(TempObject) tempstable.get(task);
-
- /* Output parameter structure */
- if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- output.println("struct "+task.getCoreSafeSymbol(num)+"_params {");
- output.println(" int size;");
- output.println(" void * next;");
- for(int j=0; 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) || (this.state.MULTICOREGC)) {
- 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) || (this.state.MULTICOREGC)) {
- headersout.print("struct "+task.getCoreSafeSymbol(num)+"_params * "+paramsprefix);
- } else
- headersout.print("void * parameterarray[]");
- headersout.println(");\n");
+ /* Classify parameters */
+ TaskDescriptor task=taskit.next();
+ FlatMethod fm=state.getMethodFlat(task);
+ generateTempStructs(fm);
+
+ ParamsObject objectparams=(ParamsObject) paramstable.get(task);
+ TempObject objecttemps=(TempObject) tempstable.get(task);
+
+ /* Output parameter structure */
+ if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
+ output.println("struct "+task.getCoreSafeSymbol(num)+"_params {");
+ output.println(" int size;");
+ output.println(" void * next;");
+ for(int j=0; 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) || (this.state.MULTICOREGC)) {
+ 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) || (this.state.MULTICOREGC)) {
+ headersout.print("struct "+task.getCoreSafeSymbol(num)+"_params * "+paramsprefix);
+ } else
+ headersout.print("void * parameterarray[]");
+ headersout.println(");\n");
}
}
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();
+ 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;
+ numqueues[num][i] = 0;
}
outtaskdefs.println("};");
}
taskit=this.currentSchedule.getTasks().iterator();
while(taskit.hasNext()) {
if (comma) {
- outtaskdefs.println(",");
+ outtaskdefs.println(",");
} else {
- comma = true;
+ comma = true;
}
TaskDescriptor td=taskit.next();
outtaskdefs.print(this.paramqarrayprefix + td.getCoreSafeSymbol(num));
if(this.fsate2qnames == null) {
this.fsate2qnames = new Hashtable[this.coreNum];
for(int i = 0; i < this.fsate2qnames.length; ++i) {
- this.fsate2qnames[i] = null;
+ this.fsate2qnames[i] = null;
}
}
int num = this.currentSchedule.getCoreNum();
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 + "};");
+ 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();
output.print(objecttemp.numPointers()+",");
output.print(paramsprefix);
for(int j=0; j<objecttemp.numPointers(); j++)
- output.print(", NULL");
+ output.print(", NULL");
output.println("};");
}
TempDescriptor td=objecttemp.getPrimitive(i);
TypeDescriptor type=td.getType();
if (type.isNull())
- output.println(" void * "+td.getSafeSymbol()+";");
+ output.println(" void * "+td.getSafeSymbol()+";");
else if (state.MGC && type.isClass() && type.getClassDesc().isEnum()) {
- output.println(" int " + td.getSafeSymbol()+";");
+ output.println(" int " + td.getSafeSymbol()+";");
} else if (type.isClass()||type.isArray())
- output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
+ output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
else
- output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
+ output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
}
for(int i = 0; i < fm.numParameters(); ++i) {
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);
+ 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)+":");
+ output.println("L"+nodetolabel.get(current_node)+":");
/*if (state.INSTRUCTIONFAILURE) {
if (state.THREAD||state.DSM) {
output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
output.println("if ((--instructioncount)==0) injectinstructionfailure();");
}*/
if (current_node.numNext()==0) {
- output.print(" ");
- generateFlatNode(fm, current_node, output);
- if (current_node.kind()!=FKind.FlatReturnNode) {
- //output.println(" flushAll();");
- output.println("#ifdef CACHEFLUSH");
- output.println("BAMBOO_ENTER_RUNTIME_MODE_FROM_CLIENT();");
- output.println("#ifdef DEBUG");
- output.println("BAMBOO_DEBUGPRINT(0xec00);");
- output.println("#endif");
- output.println("BAMBOO_CACHE_FLUSH_ALL();");
- output.println("#ifdef DEBUG");
- output.println("BAMBOO_DEBUGPRINT(0xecff);");
- output.println("#endif");
- output.println("BAMBOO_ENTER_CLIENT_MODE_FROM_RUNTIME();");
- output.println("#endif");
- outputTransCode(output);
- output.println(" return;");
- }
- current_node=null;
+ output.print(" ");
+ generateFlatNode(fm, current_node, output);
+ if (current_node.kind()!=FKind.FlatReturnNode) {
+ //output.println(" flushAll();");
+ output.println("#ifdef CACHEFLUSH");
+ output.println("BAMBOO_ENTER_RUNTIME_MODE_FROM_CLIENT();");
+ output.println("#ifdef DEBUG");
+ output.println("BAMBOO_DEBUGPRINT(0xec00);");
+ output.println("#endif");
+ output.println("BAMBOO_CACHE_FLUSH_ALL();");
+ output.println("#ifdef DEBUG");
+ output.println("BAMBOO_DEBUGPRINT(0xecff);");
+ output.println("#endif");
+ output.println("BAMBOO_ENTER_CLIENT_MODE_FROM_RUNTIME();");
+ output.println("#endif");
+ outputTransCode(output);
+ output.println(" return;");
+ }
+ current_node=null;
} else if(current_node.numNext()==1) {
- output.print(" ");
- generateFlatNode(fm, current_node, output);
- FlatNode nextnode=current_node.getNext(0);
- if (visited.contains(nextnode)) {
- output.println("goto L"+nodetolabel.get(nextnode)+";");
- current_node=null;
- } else
- current_node=nextnode;
+ output.print(" ");
+ generateFlatNode(fm, current_node, output);
+ FlatNode nextnode=current_node.getNext(0);
+ if (visited.contains(nextnode)) {
+ output.println("goto L"+nodetolabel.get(nextnode)+";");
+ current_node=null;
+ } else
+ current_node=nextnode;
} else if (current_node.numNext()==2) {
- /* Branch */
- output.print(" ");
- generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
- if (!visited.contains(current_node.getNext(1)))
- tovisit.add(current_node.getNext(1));
- if (visited.contains(current_node.getNext(0))) {
- output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
- current_node=null;
- } else
- current_node=current_node.getNext(0);
+ /* Branch */
+ output.print(" ");
+ generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
+ if (!visited.contains(current_node.getNext(1)))
+ tovisit.add(current_node.getNext(1));
+ if (visited.contains(current_node.getNext(0))) {
+ output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
+ current_node=null;
+ } else
+ current_node=current_node.getNext(0);
} else throw new Error();
}
int dnfterms;
if (param_flag==null) {
- output.println("int parameterdnf_"+i+"_"+task.getCoreSafeSymbol(num)+"[]={");
- output.println("0x0, 0x0 };");
- dnfterms=1;
+ output.println("int parameterdnf_"+i+"_"+task.getCoreSafeSymbol(num)+"[]={");
+ output.println("0x0, 0x0 };");
+ dnfterms=1;
} else {
- DNFFlag dflag=param_flag.getDNF();
- dnfterms=dflag.size();
-
- Hashtable flags=(Hashtable)flagorder.get(param_type.getClassDesc());
- output.println("int parameterdnf_"+i+"_"+task.getCoreSafeSymbol(num)+"[]={");
- for(int j=0; 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("};");
+ 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()));
- }
+ 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;
+ this.startupcorenum = num;
}
if(qnames[param_type.getClassDesc().getId()] == null) {
- qnames[param_type.getClassDesc().getId()] = new Vector();
+ qnames[param_type.getClassDesc().getId()] = new Vector();
}
qnames[param_type.getClassDesc().getId()].addElement(qname);
outtask.println("extern struct parameterwrapper " + qname + ";");
output.println(".intarray = parameterdnf_"+i+"_"+task.getCoreSafeSymbol(num)+","); // intarray
// numbertags
if (param_tag!=null)
- output.println("/* number of tags */ .numbertags = "+param_tag.numTags()+",");
+ output.println("/* number of tags */ .numbertags = "+param_tag.numTags()+",");
else
- output.println("/* number of tags */ .numbertags = 0,");
+ 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
//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()+",");
+ output.println("/* number of tags */"+param_tag.numTags()+",");
else
- output.println("/* number of tags */ 0,");
+ output.println("/* number of tags */ 0,");
output.println("parametertag_"+i+"_"+task.getCoreSafeSymbol(num)); // tagarray
output.println("};");
}
output.println("struct parameterwrapper * " + this.paramqarrayprefix + task.getCoreSafeSymbol(num)+"[] = {");
for (int i=0; i<task.numParameters(); i++) {
if (i!=0)
- output.println(",");
+ output.println(",");
output.print("&" + this.objqueueprefix + i + "_" + task.getCoreSafeSymbol(num));
}
output.println("};");
output.println("struct parameterdescriptor * parameterdescriptors_"+task.getCoreSafeSymbol(num)+"[] = {");
for (int i=0; i<task.numParameters(); i++) {
if (i!=0)
- output.println(",");
+ output.println(",");
output.print("¶meter_"+i+"_"+task.getCoreSafeSymbol(num));
}
output.println("};");
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+"];");
+ 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
+ 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();
+ maxtaskparams=objectparams.numPrimitives()+fm.numTags();
} else output.println(") {");
}
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("+generateTemp(fm, temp)+", 0x"+Integer.toHexString(ormask)+
- ", 0x"+Integer.toHexString(andmask)+", " + qinfo.qname +
- ", " + qinfo.length + ");");
- output.println("}");
+ FlagState tmpFState = initfstates.elementAt(i);
+ output.println("{");
+ QueueInfo qinfo = outputqueues(tmpFState, num, output, false);
+ output.println("flagorand("+generateTemp(fm, temp)+", 0x"+Integer.toHexString(ormask)+
+ ", 0x"+Integer.toHexString(andmask)+", " + qinfo.qname +
+ ", " + qinfo.length + ");");
+ output.println("}");
}
if(ffan.getTaskType()==FlatFlagActionNode.TASKEXIT) {
- // generate codes for profiling, recording which task exit it is
- output.println("#ifdef PROFILE");
- output.println("setTaskExitIndex(" + ffan.getTaskExitIndex() + ");");
- output.println("#endif");
+ // generate codes for profiling, recording which task exit it is
+ output.println("#ifdef PROFILE");
+ output.println("setTaskExitIndex(" + ffan.getTaskExitIndex() + ");");
+ output.println("#endif");
}
}
}
initfstates = ffan.getInitFStates(cd);
targetFStates = new Vector[initfstates.size()];
for(int i = 0; i < initfstates.size(); ++i) {
- FlagState fs = initfstates.elementAt(i);
- targetFStates[i] = ffan.getTargetFStates(fs);
-
- if(!fs.isSetmask()) {
- Hashtable flags=(Hashtable)flagorder.get(cd);
- int andmask=0;
- int checkmask=0;
- Iterator it_flags = fs.getFlags();
- while(it_flags.hasNext()) {
- FlagDescriptor fd = (FlagDescriptor)it_flags.next();
- int flagid=1<<((Integer)flags.get(fd)).intValue();
- andmask|=flagid;
- checkmask|=flagid;
- }
- fs.setAndmask(andmask);
- fs.setCheckmask(checkmask);
- fs.setSetmask(true);
- }
+ FlagState fs = initfstates.elementAt(i);
+ targetFStates[i] = ffan.getTargetFStates(fs);
+
+ if(!fs.isSetmask()) {
+ Hashtable flags=(Hashtable)flagorder.get(cd);
+ int andmask=0;
+ int checkmask=0;
+ Iterator it_flags = fs.getFlags();
+ while(it_flags.hasNext()) {
+ FlagDescriptor fd = (FlagDescriptor)it_flags.next();
+ int flagid=1<<((Integer)flags.get(fd)).intValue();
+ andmask|=flagid;
+ checkmask|=flagid;
+ }
+ fs.setAndmask(andmask);
+ fs.setCheckmask(checkmask);
+ fs.setSetmask(true);
+ }
}
}
boolean isolate = true; // check if this flagstate can associate to some task with multiple params which can
if((this.currentSchedule == null) && (fm.getMethod().getClassDesc().getSymbol().equals("ServerSocket"))) {
// ServerSocket object will always reside on current core
for(int j = 0; j < targetFStates.length; ++j) {
- if(initfstates != null) {
- FlagState fs = initfstates.elementAt(j);
- output.println("if(" + generateTempFlagName(fm, temp) + "&(0x" + Integer.toHexString(fs.getAndmask())
- + ")==(0x" + Integer.toHexString(fs.getCheckmask()) + ")) {");
- }
- Vector<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("+generateTemp(fm, temp)+", NULL, 0);");
- }
- if(initfstates != null) {
- output.println("}");
- }
+ if(initfstates != null) {
+ FlagState fs = initfstates.elementAt(j);
+ output.println("if(" + generateTempFlagName(fm, temp) + "&(0x" + Integer.toHexString(fs.getAndmask())
+ + ")==(0x" + Integer.toHexString(fs.getCheckmask()) + ")) {");
+ }
+ Vector<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("+generateTemp(fm, temp)+", NULL, 0);");
+ }
+ if(initfstates != null) {
+ output.println("}");
+ }
}
return;
}
for(int j = 0; j < targetFStates.length; ++j) {
FlagState fs = null;
if(initfstates != null) {
- fs = initfstates.elementAt(j);
- output.println("if((" + generateTempFlagName(fm, temp) + "&(0x" + Integer.toHexString(fs.getAndmask())
- + "))==(0x" + Integer.toHexString(fs.getCheckmask()) + ")) {");
+ fs = initfstates.elementAt(j);
+ output.println("if((" + generateTempFlagName(fm, temp) + "&(0x" + Integer.toHexString(fs.getAndmask())
+ + "))==(0x" + Integer.toHexString(fs.getCheckmask()) + ")) {");
}
Vector<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 {
- isolate = (this.currentSchedule.getAllyCoreTable().get(tmpFState) == null) ||
- (this.currentSchedule.getAllyCoreTable().get(tmpFState).size() == 0);
- }
-
- Vector<Integer> sendto = new Vector<Integer>();
- 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("+generateTemp(fm, temp)+", " + qinfo.qname +
- ", " + qinfo.length + ");");
- output.println("}");
- } /*else {
- // TODO
- // really needed?
- output.println("/* possibly needed by multi-parameter tasks on this core*//*");
- output.println("enqueueObject("+generateTemp(fm, temp)+", NULL, 0);");
- }*/ // deleted 09/07/06, multi-param tasks are pinned to one core now
- } else {
- /*if(!isolate) {
- // TODO
- // Is it possible to decide the actual queues?
- output.println("/* possibly needed by multi-parameter tasks on this core*//*");
- output.println("enqueueObject("+generateTemp(fm, temp)+", NULL, 0);");
- }*/ // deleted 09/07/06, multi-param tasks are pinned to one core now
- output.println("/* transfer to core " + targetcore.toString() + "*/");
- output.println("{");
- // enqueue this object and its destinations for later process
- // all the possible queues
- QueueInfo qinfo = null;
- TranObjInfo tmpinfo = new TranObjInfo();
- tmpinfo.name = generateTemp(fm, temp);
- tmpinfo.targetcore = targetcore;
- FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState);
- if(targetFS != null) {
- tmpinfo.fs = targetFS;
- } else {
- tmpinfo.fs = tmpFState;
- }
- qinfo = outputtransqueues(tmpinfo.fs, targetcore, output);
- output.println("tmpObjInfo = RUNMALLOC(sizeof(struct transObjInfo));");
- output.println("tmpObjInfo->objptr = (void *)" + tmpinfo.name + ";");
- output.println("tmpObjInfo->targetcore = "+targetcore.toString()+";");
- output.println("tmpObjInfo->queues = " + qinfo.qname + ";");
- output.println("tmpObjInfo->length = " + qinfo.length + ";");
- output.println("addNewItem(totransobjqueue, (void*)tmpObjInfo);");
- output.println("}");
- }
- output.println("break;");
- }
- output.println("}");
- } else {
- /*if(!isolate) {
- // TODO
- // Is it possible to decide the actual queues?
- output.println("/* possibly needed by multi-parameter tasks on this core*//*");
- output.println("enqueueObject("+generateTemp(fm, temp)+", NULL, 0);");
- }*/ // deleted 09/07/06, multi-param tasks are pinned to one core now
- output.println("/* transfer to core " + targetcore.toString() + "*/");
- output.println("{");
- // enqueue this object and its destinations for later process
- // all the possible queues
- QueueInfo qinfo = null;
- TranObjInfo tmpinfo = new TranObjInfo();
- tmpinfo.name = generateTemp(fm, temp);
- tmpinfo.targetcore = targetcore;
- FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState);
- if(targetFS != null) {
- tmpinfo.fs = targetFS;
- } else {
- tmpinfo.fs = tmpFState;
- }
- qinfo = outputtransqueues(tmpinfo.fs, targetcore, output);
- output.println("tmpObjInfo = RUNMALLOC(sizeof(struct transObjInfo));");
- output.println("tmpObjInfo->objptr = (void *)" + tmpinfo.name + ";");
- output.println("tmpObjInfo->targetcore = "+targetcore.toString()+";");
- output.println("tmpObjInfo->queues = " + qinfo.qname + ";");
- output.println("tmpObjInfo->length = " + qinfo.length + ";");
- output.println("addNewItem(totransobjqueue, (void*)tmpObjInfo);");
- output.println("}");
- }
- output.println("/* increase index*/");
- output.println("++" + queueins + ".index;");
- } else {
- // this object will reside on current core
- output.println("/* reside on this core*/");
- if(isolate) {
- output.println("{");
- QueueInfo qinfo = outputqueues(tmpFState, num, output, true);
- output.println("enqueueObject("+generateTemp(fm, temp)+", " + qinfo.qname +
- ", " + qinfo.length + ");");
- output.println("}");
- } /*else {
- // TODO
- // really needed?
- output.println("enqueueObject("+generateTemp(fm, temp)+", NULL, 0);");
- }*/ // deleted 09/07/06, multi-param tasks are pinned to one core now
- }
-
- // codes for multi-params tasks
- if(!isolate) {
- // flagstate associated with some multi-params tasks
- // need to be send to other cores
- Vector<Integer> targetcores = this.currentSchedule.getAllyCores(tmpFState);
- output.println("/* send the shared object to possible queues on other cores*/");
- // TODO, temporary solution, send to mostly the first two
- int upperbound = targetcores.size() > 2?2:targetcores.size();
- for(int k = 0; k < upperbound; ++k) {
- // TODO
- // add the information of exactly which queue
- int targetcore = targetcores.elementAt(k).intValue();
- if(!sendto.contains(targetcore)) {
- // previously not sended to this target core
- // enqueue this object and its destinations for later process
- output.println("{");
- // all the possible queues
- QueueInfo qinfo = null;
- TranObjInfo tmpinfo = new TranObjInfo();
- tmpinfo.name = generateTemp(fm, temp);
- tmpinfo.targetcore = targetcore;
- FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState);
- if(targetFS != null) {
- tmpinfo.fs = targetFS;
- } else {
- tmpinfo.fs = tmpFState;
- }
- qinfo = outputtransqueues(tmpinfo.fs, targetcore, output);
- output.println("tmpObjInfo = RUNMALLOC(sizeof(struct transObjInfo));");
- output.println("tmpObjInfo->objptr = (void *)" + tmpinfo.name + ";");
- output.println("tmpObjInfo->targetcore = "+targetcore+";");
- output.println("tmpObjInfo->queues = " + qinfo.qname + ";");
- output.println("tmpObjInfo->length = " + qinfo.length + ";");
- output.println("addNewItem(totransobjqueue, (void*)tmpObjInfo);");
- output.println("}");
- sendto.addElement(targetcore);
- }
- }
- }
+ FlagState tmpFState = tmpfstates.elementAt(i);
+
+ if(this.currentSchedule.getAllyCoreTable() == null) {
+ isolate = true;
+ } else {
+ isolate = (this.currentSchedule.getAllyCoreTable().get(tmpFState) == null) ||
+ (this.currentSchedule.getAllyCoreTable().get(tmpFState).size() == 0);
+ }
+
+ Vector<Integer> sendto = new Vector<Integer>();
+ 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("+generateTemp(fm, temp)+", " + qinfo.qname +
+ ", " + qinfo.length + ");");
+ output.println("}");
+ } /*else {
+ // TODO
+ // really needed?
+ output.println("/* possibly needed by multi-parameter tasks on this core*//*");
+ output.println("enqueueObject("+generateTemp(fm, temp)+", NULL, 0);");
+ }*/ // deleted 09/07/06, multi-param tasks are pinned to one core now
+ } else {
+ /*if(!isolate) {
+ // TODO
+ // Is it possible to decide the actual queues?
+ output.println("/* possibly needed by multi-parameter tasks on this core*//*");
+ output.println("enqueueObject("+generateTemp(fm, temp)+", NULL, 0);");
+ }*/ // deleted 09/07/06, multi-param tasks are pinned to one core now
+ output.println("/* transfer to core " + targetcore.toString() + "*/");
+ output.println("{");
+ // enqueue this object and its destinations for later process
+ // all the possible queues
+ QueueInfo qinfo = null;
+ TranObjInfo tmpinfo = new TranObjInfo();
+ tmpinfo.name = generateTemp(fm, temp);
+ tmpinfo.targetcore = targetcore;
+ FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState);
+ if(targetFS != null) {
+ tmpinfo.fs = targetFS;
+ } else {
+ tmpinfo.fs = tmpFState;
+ }
+ qinfo = outputtransqueues(tmpinfo.fs, targetcore, output);
+ output.println("tmpObjInfo = RUNMALLOC(sizeof(struct transObjInfo));");
+ output.println("tmpObjInfo->objptr = (void *)" + tmpinfo.name + ";");
+ output.println("tmpObjInfo->targetcore = "+targetcore.toString()+";");
+ output.println("tmpObjInfo->queues = " + qinfo.qname + ";");
+ output.println("tmpObjInfo->length = " + qinfo.length + ";");
+ output.println("addNewItem(totransobjqueue, (void*)tmpObjInfo);");
+ output.println("}");
+ }
+ output.println("break;");
+ }
+ output.println("}");
+ } else {
+ /*if(!isolate) {
+ // TODO
+ // Is it possible to decide the actual queues?
+ output.println("/* possibly needed by multi-parameter tasks on this core*//*");
+ output.println("enqueueObject("+generateTemp(fm, temp)+", NULL, 0);");
+ }*/ // deleted 09/07/06, multi-param tasks are pinned to one core now
+ output.println("/* transfer to core " + targetcore.toString() + "*/");
+ output.println("{");
+ // enqueue this object and its destinations for later process
+ // all the possible queues
+ QueueInfo qinfo = null;
+ TranObjInfo tmpinfo = new TranObjInfo();
+ tmpinfo.name = generateTemp(fm, temp);
+ tmpinfo.targetcore = targetcore;
+ FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState);
+ if(targetFS != null) {
+ tmpinfo.fs = targetFS;
+ } else {
+ tmpinfo.fs = tmpFState;
+ }
+ qinfo = outputtransqueues(tmpinfo.fs, targetcore, output);
+ output.println("tmpObjInfo = RUNMALLOC(sizeof(struct transObjInfo));");
+ output.println("tmpObjInfo->objptr = (void *)" + tmpinfo.name + ";");
+ output.println("tmpObjInfo->targetcore = "+targetcore.toString()+";");
+ output.println("tmpObjInfo->queues = " + qinfo.qname + ";");
+ output.println("tmpObjInfo->length = " + qinfo.length + ";");
+ output.println("addNewItem(totransobjqueue, (void*)tmpObjInfo);");
+ output.println("}");
+ }
+ output.println("/* increase index*/");
+ output.println("++" + queueins + ".index;");
+ } else {
+ // this object will reside on current core
+ output.println("/* reside on this core*/");
+ if(isolate) {
+ output.println("{");
+ QueueInfo qinfo = outputqueues(tmpFState, num, output, true);
+ output.println("enqueueObject("+generateTemp(fm, temp)+", " + qinfo.qname +
+ ", " + qinfo.length + ");");
+ output.println("}");
+ } /*else {
+ // TODO
+ // really needed?
+ output.println("enqueueObject("+generateTemp(fm, temp)+", NULL, 0);");
+ }*/ // deleted 09/07/06, multi-param tasks are pinned to one core now
+ }
+
+ // codes for multi-params tasks
+ if(!isolate) {
+ // flagstate associated with some multi-params tasks
+ // need to be send to other cores
+ Vector<Integer> targetcores = this.currentSchedule.getAllyCores(tmpFState);
+ output.println("/* send the shared object to possible queues on other cores*/");
+ // TODO, temporary solution, send to mostly the first two
+ int upperbound = targetcores.size() > 2?2:targetcores.size();
+ for(int k = 0; k < upperbound; ++k) {
+ // TODO
+ // add the information of exactly which queue
+ int targetcore = targetcores.elementAt(k).intValue();
+ if(!sendto.contains(targetcore)) {
+ // previously not sended to this target core
+ // enqueue this object and its destinations for later process
+ output.println("{");
+ // all the possible queues
+ QueueInfo qinfo = null;
+ TranObjInfo tmpinfo = new TranObjInfo();
+ tmpinfo.name = generateTemp(fm, temp);
+ tmpinfo.targetcore = targetcore;
+ FlagState targetFS = this.currentSchedule.getTargetFState(tmpFState);
+ if(targetFS != null) {
+ tmpinfo.fs = targetFS;
+ } else {
+ tmpinfo.fs = tmpFState;
+ }
+ qinfo = outputtransqueues(tmpinfo.fs, targetcore, output);
+ output.println("tmpObjInfo = RUNMALLOC(sizeof(struct transObjInfo));");
+ output.println("tmpObjInfo->objptr = (void *)" + tmpinfo.name + ";");
+ output.println("tmpObjInfo->targetcore = "+targetcore+";");
+ output.println("tmpObjInfo->queues = " + qinfo.qname + ";");
+ output.println("tmpObjInfo->length = " + qinfo.length + ";");
+ output.println("addNewItem(totransobjqueue, (void*)tmpObjInfo);");
+ output.println("}");
+ sendto.addElement(targetcore);
+ }
+ }
+ }
}
if(initfstates != null) {
- output.println("}");
+ output.println("}");
}
}
}
TaskDescriptor td = fe.getTask();
int paraindex = fe.getIndex();
if((!isEnqueue) || (isEnqueue && residetasks.contains(td))) {
- if((!tasks.contains(td)) ||
- ((tasks.contains(td)) && (paraindex != indexes.elementAt(tasks.indexOf(td)).intValue()))) {
- tasks.addElement(td);
- indexes.addElement(paraindex);
- if(comma) {
- output.println(",");
- } else {
- comma = true;
- }
- output.print("&" + this.objqueueprefix + paraindex + "_" + td.getCoreSafeSymbol(num));
- ++qinfo.length;
- }
+ if((!tasks.contains(td)) ||
+ ((tasks.contains(td)) && (paraindex != indexes.elementAt(tasks.indexOf(td)).intValue()))) {
+ tasks.addElement(td);
+ indexes.addElement(paraindex);
+ if(comma) {
+ output.println(",");
+ } else {
+ comma = true;
+ }
+ output.print("&" + this.objqueueprefix + paraindex + "_" + td.getCoreSafeSymbol(num));
+ ++qinfo.length;
+ }
}
}
output.println("};");
TaskDescriptor td = fe.getTask();
int paraindex = fe.getIndex();
if(residetasks.contains(td)) {
- if((!tasks.contains(td)) ||
- ((tasks.contains(td)) && (paraindex != indexes.elementAt(tasks.indexOf(td)).intValue()))) {
- tasks.addElement(td);
- indexes.addElement(paraindex);
- if(comma) {
- output.println(",");
- } else {
- comma = true;
- }
- output.print(residetasks.indexOf(td) + ", ");
- output.print(paraindex);
- ++qinfo.length;
- }
+ if((!tasks.contains(td)) ||
+ ((tasks.contains(td)) && (paraindex != indexes.elementAt(tasks.indexOf(td)).intValue()))) {
+ tasks.addElement(td);
+ indexes.addElement(paraindex);
+ if(comma) {
+ output.println(",");
+ } else {
+ comma = true;
+ }
+ output.print(residetasks.indexOf(td) + ", ");
+ output.print(paraindex);
+ ++qinfo.length;
+ }
}
}
output.println("};");
// higher numbered parameters
aliasSets.add(null);
for( int j = i + 1; j < fm.numParameters(); ++j ) {
- common = this.m_oa.createsPotentialAliases(td, i, j);
- if(!common.isEmpty()) {
- // ith parameter and jth parameter has alias, create lock to protect them
- if(aliasSets.elementAt(i) == null) {
- aliasSets.setElementAt(new Vector<Integer>(), i);
- }
- aliasSets.elementAt(i).add(j);
- }
+ common = this.m_oa.createsPotentialAliases(td, i, j);
+ if(!common.isEmpty()) {
+ // ith parameter and jth parameter has alias, create lock to protect them
+ if(aliasSets.elementAt(i) == null) {
+ aliasSets.setElementAt(new Vector<Integer>(), i);
+ }
+ aliasSets.elementAt(i).add(j);
+ }
}
// for the ith parameter, check for aliases against
// task context
aliasFNSets.add(null);
for(int j = 0; j < allocSites.length; j++) {
- AllocationSite as = (AllocationSite)allocSites[j];
- common = this.m_oa.createsPotentialAliases(td, i, as);
- if( !common.isEmpty() ) {
- // ith parameter and allocationsite as has alias
- if(aliasFNSets.elementAt(i) == null) {
- aliasFNSets.setElementAt(new Vector<FlatNew>(), i);
- }
- aliasFNSets.elementAt(i).add(as.getFlatNew());
- }
+ AllocationSite as = (AllocationSite)allocSites[j];
+ common = this.m_oa.createsPotentialAliases(td, i, as);
+ if( !common.isEmpty() ) {
+ // ith parameter and allocationsite as has alias
+ if(aliasFNSets.elementAt(i) == null) {
+ aliasFNSets.setElementAt(new Vector<FlatNew>(), i);
+ }
+ aliasFNSets.elementAt(i).add(as.getFlatNew());
+ }
}
}
for( int i = 0; i < allocSites.length; ++i ) {
AllocationSite as1 = (AllocationSite)allocSites[i];
for(int j = i + 1; j < allocSites.length; j++) {
- AllocationSite as2 = (AllocationSite)allocSites[j];
-
- common = this.m_oa.createsPotentialAliases(td, as1, as2);
- if( !common.isEmpty() ) {
- // as1 and as2 has alias
- if(!aliasFNTbl.containsKey(as1.getFlatNew())) {
- aliasFNTbl.put(as1.getFlatNew(), new Vector<FlatNew>());
- }
- if(!aliasFNTbl.get(as1.getFlatNew()).contains(as2.getFlatNew())) {
- aliasFNTbl.get(as1.getFlatNew()).add(as2.getFlatNew());
- }
- }
+ AllocationSite as2 = (AllocationSite)allocSites[j];
+
+ common = this.m_oa.createsPotentialAliases(td, as1, as2);
+ if( !common.isEmpty() ) {
+ // as1 and as2 has alias
+ if(!aliasFNTbl.containsKey(as1.getFlatNew())) {
+ aliasFNTbl.put(as1.getFlatNew(), new Vector<FlatNew>());
+ }
+ if(!aliasFNTbl.get(as1.getFlatNew()).contains(as2.getFlatNew())) {
+ aliasFNTbl.get(as1.getFlatNew()).add(as2.getFlatNew());
+ }
+ }
}
}
while(it.hasNext()) {
FlatNew tmpfn = it.next();
if(visited.contains(tmpfn)) {
- continue;
+ continue;
}
visited.add(tmpfn);
Queue<FlatNew> tovisit = new LinkedList<FlatNew>();
Vector<FlatNew> tmpv = aliasFNTbl.get(tmpfn);
if(tmpv == null) {
- continue;
+ continue;
}
for(int j = 0; j < tmpv.size(); j++) {
- tovisit.add(tmpv.elementAt(j));
+ tovisit.add(tmpv.elementAt(j));
}
while(!tovisit.isEmpty()) {
- FlatNew fn = tovisit.poll();
- visited.add(fn);
- Vector<FlatNew> tmpset = aliasFNTbl.get(fn);
- if(tmpset != null) {
- // merge tmpset to the alias set of the ith parameter
- for(int j = 0; j < tmpset.size(); j++) {
- if(!tmpv.contains(tmpset.elementAt(j))) {
- tmpv.add(tmpset.elementAt(j));
- tovisit.add(tmpset.elementAt(j));
- }
- }
- aliasFNTbl.remove(fn);
- }
+ FlatNew fn = tovisit.poll();
+ visited.add(fn);
+ Vector<FlatNew> tmpset = aliasFNTbl.get(fn);
+ if(tmpset != null) {
+ // merge tmpset to the alias set of the ith parameter
+ for(int j = 0; j < tmpset.size(); j++) {
+ if(!tmpv.contains(tmpset.elementAt(j))) {
+ tmpv.add(tmpset.elementAt(j));
+ tovisit.add(tmpset.elementAt(j));
+ }
+ }
+ aliasFNTbl.remove(fn);
+ }
}
it = aliasFNTbl.keySet().iterator();
}
Queue<Integer> tovisit = new LinkedList<Integer>();
Vector<Integer> tmpv = aliasSets.elementAt(i);
if(tmpv == null) {
- continue;
+ continue;
}
for(int j = 0; j < tmpv.size(); j++) {
- tovisit.add(tmpv.elementAt(j));
+ tovisit.add(tmpv.elementAt(j));
}
while(!tovisit.isEmpty()) {
- int index = tovisit.poll().intValue();
- Vector<Integer> tmpset = aliasSets.elementAt(index);
- if(tmpset != null) {
- // merge tmpset to the alias set of the ith parameter
- for(int j = 0; j < tmpset.size(); j++) {
- if(!tmpv.contains(tmpset.elementAt(j))) {
- tmpv.add(tmpset.elementAt(j));
- tovisit.add(tmpset.elementAt(j));
- }
- }
- aliasSets.setElementAt(null, index);
- }
-
- Vector<FlatNew> tmpFNSet = aliasFNSets.elementAt(index);
- if(tmpFNSet != null) {
- // merge tmpFNSet to the aliasFNSet of the ith parameter
- if(aliasFNSets.elementAt(i) == null) {
- aliasFNSets.setElementAt(tmpFNSet, i);
- } else {
- Vector<FlatNew> tmpFNv = aliasFNSets.elementAt(i);
- for(int j = 0; j < tmpFNSet.size(); j++) {
- if(!tmpFNv.contains(tmpFNSet.elementAt(j))) {
- tmpFNv.add(tmpFNSet.elementAt(j));
- }
- }
- }
- aliasFNSets.setElementAt(null, index);
- }
+ int index = tovisit.poll().intValue();
+ Vector<Integer> tmpset = aliasSets.elementAt(index);
+ if(tmpset != null) {
+ // merge tmpset to the alias set of the ith parameter
+ for(int j = 0; j < tmpset.size(); j++) {
+ if(!tmpv.contains(tmpset.elementAt(j))) {
+ tmpv.add(tmpset.elementAt(j));
+ tovisit.add(tmpset.elementAt(j));
+ }
+ }
+ aliasSets.setElementAt(null, index);
+ }
+
+ Vector<FlatNew> tmpFNSet = aliasFNSets.elementAt(index);
+ if(tmpFNSet != null) {
+ // merge tmpFNSet to the aliasFNSet of the ith parameter
+ if(aliasFNSets.elementAt(i) == null) {
+ aliasFNSets.setElementAt(tmpFNSet, i);
+ } else {
+ Vector<FlatNew> tmpFNv = aliasFNSets.elementAt(i);
+ for(int j = 0; j < tmpFNSet.size(); j++) {
+ if(!tmpFNv.contains(tmpFNSet.elementAt(j))) {
+ tmpFNv.add(tmpFNSet.elementAt(j));
+ }
+ }
+ }
+ aliasFNSets.setElementAt(null, index);
+ }
}
}
for(int i = 0; i < aliasSets.size(); i++) {
Vector<Integer> tmpv = aliasSets.elementAt(i);
if(tmpv != null) {
- tmpv.add(0, i);
- tmpaliasSets.add(tmpv);
- numlock++;
+ tmpv.add(0, i);
+ tmpaliasSets.add(tmpv);
+ numlock++;
}
Vector<FlatNew> tmpFNv = aliasFNSets.elementAt(i);
if(tmpFNv != null) {
- aliasFNTbl4Para.put(i, tmpFNv);
- if(tmpv == null) {
- numlock++;
- }
+ aliasFNTbl4Para.put(i, tmpFNv);
+ if(tmpv == null) {
+ numlock++;
+ }
}
}
numparalock = numlock;
// associate locks with parameters
int lockindex = 0;
for(int i = 0; i < this.m_aliasSets.size(); i++) {
- Vector<Integer> toadd = this.m_aliasSets.elementAt(i);
-
- output.println("int tmplen_" + lockindex + " = " + toadd.size());
- output.println("void * tmpptrs_" + lockindex + "[] = {");
- for(int j = 0; j < toadd.size(); j++) {
- int para = toadd.elementAt(j).intValue();
- output.print(generateTemp(fm, fm.getParameter(para)));
- if(j < toadd.size() - 1) {
- output.print(", ");
- } else {
- output.println("};");
- }
- }
- output.println("aliaslocks[tmpi++] = getAliasLock(tmpptrs_" + lockindex + ", tmplen_" + lockindex + ", lockRedirectTbl);");
-
- for(int j = 0; j < toadd.size(); j++) {
- int para = toadd.elementAt(j).intValue();
- output.println("addAliasLock(" + generateTemp(fm, fm.getParameter(para)) + ", aliaslocks[" + i + "]);");
- }
- // check if this lock is also associated with any FlatNew nodes
- if(this.m_aliasFNTbl4Para.containsKey(toadd.elementAt(0))) {
- if(this.m_aliaslocksTbl4FN == null) {
- this.m_aliaslocksTbl4FN = new Hashtable<FlatNew, Vector<Integer>>();
- }
- Vector<FlatNew> tmpv = this.m_aliasFNTbl4Para.get(toadd.elementAt(0));
- for(int j = 0; j < tmpv.size(); j++) {
- FlatNew fn = tmpv.elementAt(j);
- if(!this.m_aliaslocksTbl4FN.containsKey(fn)) {
- this.m_aliaslocksTbl4FN.put(fn, new Vector<Integer>());
- }
- this.m_aliaslocksTbl4FN.get(fn).add(i);
- }
- this.m_aliasFNTbl4Para.remove(toadd.elementAt(0));
- }
- lockindex++;
+ Vector<Integer> toadd = this.m_aliasSets.elementAt(i);
+
+ output.println("int tmplen_" + lockindex + " = " + toadd.size());
+ output.println("void * tmpptrs_" + lockindex + "[] = {");
+ for(int j = 0; j < toadd.size(); j++) {
+ int para = toadd.elementAt(j).intValue();
+ output.print(generateTemp(fm, fm.getParameter(para)));
+ if(j < toadd.size() - 1) {
+ output.print(", ");
+ } else {
+ output.println("};");
+ }
+ }
+ output.println("aliaslocks[tmpi++] = getAliasLock(tmpptrs_" + lockindex + ", tmplen_" + lockindex + ", lockRedirectTbl);");
+
+ for(int j = 0; j < toadd.size(); j++) {
+ int para = toadd.elementAt(j).intValue();
+ output.println("addAliasLock(" + generateTemp(fm, fm.getParameter(para)) + ", aliaslocks[" + i + "]);");
+ }
+ // check if this lock is also associated with any FlatNew nodes
+ if(this.m_aliasFNTbl4Para.containsKey(toadd.elementAt(0))) {
+ if(this.m_aliaslocksTbl4FN == null) {
+ this.m_aliaslocksTbl4FN = new Hashtable<FlatNew, Vector<Integer>>();
+ }
+ Vector<FlatNew> tmpv = this.m_aliasFNTbl4Para.get(toadd.elementAt(0));
+ for(int j = 0; j < tmpv.size(); j++) {
+ FlatNew fn = tmpv.elementAt(j);
+ if(!this.m_aliaslocksTbl4FN.containsKey(fn)) {
+ this.m_aliaslocksTbl4FN.put(fn, new Vector<Integer>());
+ }
+ this.m_aliaslocksTbl4FN.get(fn).add(i);
+ }
+ this.m_aliasFNTbl4Para.remove(toadd.elementAt(0));
+ }
+ lockindex++;
}
Object[] key = this.m_aliasFNTbl4Para.keySet().toArray();
for(int i = 0; i < key.length; i++) {
- int para = ((Integer)key[i]).intValue();
-
- output.println("void * tmpptrs_" + lockindex + "[] = {" + generateTemp(fm, fm.getParameter(para)) + "};");
- output.println("aliaslocks[tmpi++] = getAliasLock(tmpptrs_" + lockindex + ", 1, lockRedirectTbl);");
-
- output.println("addAliasLock(" + generateTemp(fm, fm.getParameter(para)) + ", aliaslocks[" + lockindex + "]);");
- Vector<FlatNew> tmpv = this.m_aliasFNTbl4Para.get(para);
- for(int j = 0; j < tmpv.size(); j++) {
- FlatNew fn = tmpv.elementAt(j);
- if(this.m_aliaslocksTbl4FN == null) {
- this.m_aliaslocksTbl4FN = new Hashtable<FlatNew, Vector<Integer>>();
- }
- if(!this.m_aliaslocksTbl4FN.containsKey(fn)) {
- this.m_aliaslocksTbl4FN.put(fn, new Vector<Integer>());
- }
- this.m_aliaslocksTbl4FN.get(fn).add(lockindex);
- }
- lockindex++;
+ int para = ((Integer)key[i]).intValue();
+
+ output.println("void * tmpptrs_" + lockindex + "[] = {" + generateTemp(fm, fm.getParameter(para)) + "};");
+ output.println("aliaslocks[tmpi++] = getAliasLock(tmpptrs_" + lockindex + ", 1, lockRedirectTbl);");
+
+ output.println("addAliasLock(" + generateTemp(fm, fm.getParameter(para)) + ", aliaslocks[" + lockindex + "]);");
+ Vector<FlatNew> tmpv = this.m_aliasFNTbl4Para.get(para);
+ for(int j = 0; j < tmpv.size(); j++) {
+ FlatNew fn = tmpv.elementAt(j);
+ if(this.m_aliaslocksTbl4FN == null) {
+ this.m_aliaslocksTbl4FN = new Hashtable<FlatNew, Vector<Integer>>();
+ }
+ if(!this.m_aliaslocksTbl4FN.containsKey(fn)) {
+ this.m_aliaslocksTbl4FN.put(fn, new Vector<Integer>());
+ }
+ this.m_aliaslocksTbl4FN.get(fn).add(lockindex);
+ }
+ lockindex++;
}
// check m_aliasFNTbl for locks associated with FlatNew nodes
Object[] FNkey = this.m_aliasFNTbl.keySet().toArray();
for(int i = 0; i < FNkey.length; i++) {
- FlatNew fn = (FlatNew)FNkey[i];
- Vector<FlatNew> tmpv = this.m_aliasFNTbl.get(fn);
-
- output.println("aliaslocks[tmpi++] = (int)(RUNMALLOC(sizeof(int)));");
-
- if(this.m_aliaslocksTbl4FN == null) {
- this.m_aliaslocksTbl4FN = new Hashtable<FlatNew, Vector<Integer>>();
- }
- if(!this.m_aliaslocksTbl4FN.containsKey(fn)) {
- this.m_aliaslocksTbl4FN.put(fn, new Vector<Integer>());
- }
- this.m_aliaslocksTbl4FN.get(fn).add(lockindex);
- for(int j = 0; j < tmpv.size(); j++) {
- FlatNew tfn = tmpv.elementAt(j);
- if(!this.m_aliaslocksTbl4FN.containsKey(tfn)) {
- this.m_aliaslocksTbl4FN.put(tfn, new Vector<Integer>());
- }
- this.m_aliaslocksTbl4FN.get(tfn).add(lockindex);
- }
- lockindex++;
+ FlatNew fn = (FlatNew)FNkey[i];
+ Vector<FlatNew> tmpv = this.m_aliasFNTbl.get(fn);
+
+ output.println("aliaslocks[tmpi++] = (int)(RUNMALLOC(sizeof(int)));");
+
+ if(this.m_aliaslocksTbl4FN == null) {
+ this.m_aliaslocksTbl4FN = new Hashtable<FlatNew, Vector<Integer>>();
+ }
+ if(!this.m_aliaslocksTbl4FN.containsKey(fn)) {
+ this.m_aliaslocksTbl4FN.put(fn, new Vector<Integer>());
+ }
+ this.m_aliaslocksTbl4FN.get(fn).add(lockindex);
+ for(int j = 0; j < tmpv.size(); j++) {
+ FlatNew tfn = tmpv.elementAt(j);
+ if(!this.m_aliaslocksTbl4FN.containsKey(tfn)) {
+ this.m_aliaslocksTbl4FN.put(tfn, new Vector<Integer>());
+ }
+ this.m_aliaslocksTbl4FN.get(tfn).add(lockindex);
+ }
+ lockindex++;
}
}
}
PrintWriter output) {
if (frn.getReturnTemp()!=null) {
if (frn.getReturnTemp().getType().isPtr())
- output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp())+";");
+ output.println("return (struct "+fm.getMethod().getReturnType().getSafeSymbol()+"*)"+generateTemp(fm, frn.getReturnTemp())+";");
else
- output.println("return "+generateTemp(fm, frn.getReturnTemp())+";");
+ output.println("return "+generateTemp(fm, frn.getReturnTemp())+";");
} else {
if(fm.getTask() != null) {
- output.println("#ifdef CACHEFLUSH");
- output.println("BAMBOO_ENTER_RUNTIME_MODE_FROM_CLIENT();");
- output.println("#ifdef DEBUG");
- output.println("BAMBOO_DEBUGPRINT(0xec00);");
- output.println("#endif");
- output.println("BAMBOO_CACHE_FLUSH_ALL();");
- output.println("#ifdef DEBUG");
- output.println("BAMBOO_DEBUGPRINT(0xecff);");
- output.println("#endif");
- output.println("BAMBOO_ENTER_CLIENT_MODE_FROM_RUNTIME();");
- output.println("#endif");
- outputTransCode(output);
+ output.println("#ifdef CACHEFLUSH");
+ output.println("BAMBOO_ENTER_RUNTIME_MODE_FROM_CLIENT();");
+ output.println("#ifdef DEBUG");
+ output.println("BAMBOO_DEBUGPRINT(0xec00);");
+ output.println("#endif");
+ output.println("BAMBOO_CACHE_FLUSH_ALL();");
+ output.println("#ifdef DEBUG");
+ output.println("BAMBOO_DEBUGPRINT(0xecff);");
+ output.println("#endif");
+ output.println("BAMBOO_ENTER_CLIENT_MODE_FROM_RUNTIME();");
+ output.println("#endif");
+ outputTransCode(output);
}
output.println("return;");
}
int arrayid = state.getArrayNumber(fn.getType())
+ state.numClasses();
if (fn.isGlobal()) {
- output.println(generateTemp(fm, fn.getDst())
- + "=allocate_newarrayglobal(trans, " + arrayid + ", "
- + generateTemp(fm, fn.getSize()) + ");");
+ output.println(generateTemp(fm, fn.getDst())
+ + "=allocate_newarrayglobal(trans, " + arrayid + ", "
+ + generateTemp(fm, fn.getSize()) + ");");
} else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- output.println(generateTemp(fm, fn.getDst())
- + "=allocate_newarray(&" + localsprefix + ", "
- + arrayid + ", " + generateTemp(fm, fn.getSize())
- + ");");
+ output.println(generateTemp(fm, fn.getDst())
+ + "=allocate_newarray(&" + localsprefix + ", "
+ + arrayid + ", " + generateTemp(fm, fn.getSize())
+ + ");");
} else {
- output.println(generateTemp(fm, fn.getDst())
- + "=allocate_newarray(" + arrayid + ", "
- + generateTemp(fm, fn.getSize()) + ");");
+ output.println(generateTemp(fm, fn.getDst())
+ + "=allocate_newarray(" + arrayid + ", "
+ + generateTemp(fm, fn.getSize()) + ");");
}
} else {
if (fn.isGlobal()) {
- output.println(generateTemp(fm, fn.getDst())
- + "=allocate_newglobal(trans, "
- + fn.getType().getClassDesc().getId() + ");");
+ output.println(generateTemp(fm, fn.getDst())
+ + "=allocate_newglobal(trans, "
+ + fn.getType().getClassDesc().getId() + ");");
} else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- output.println(generateTemp(fm, fn.getDst())
- + "=allocate_new(&" + localsprefix + ", "
- + fn.getType().getClassDesc().getId() + ");");
+ output.println(generateTemp(fm, fn.getDst())
+ + "=allocate_new(&" + localsprefix + ", "
+ + fn.getType().getClassDesc().getId() + ");");
} else {
- output.println(generateTemp(fm, fn.getDst())
- + "=allocate_new("
- + fn.getType().getClassDesc().getId() + ");");
+ output.println(generateTemp(fm, fn.getDst())
+ + "=allocate_new("
+ + fn.getType().getClassDesc().getId() + ");");
}
}
// create alias lock if necessary
if((this.m_aliaslocksTbl4FN != null) && (this.m_aliaslocksTbl4FN.containsKey(fn))) {
Vector<Integer> tmpv = this.m_aliaslocksTbl4FN.get(fn);
for(int i = 0; i < tmpv.size(); i++) {
- output.println("addAliasLock(" + generateTemp(fm, fn.getDst()) + ", aliaslocks[" + tmpv.elementAt(i).intValue() + "]);");
+ output.println("addAliasLock(" + generateTemp(fm, fn.getDst()) + ", aliaslocks[" + tmpv.elementAt(i).intValue() + "]);");
}
}
// generate codes for profiling, recording how many new objects are created
for(int i = 0; i < sendto.size(); i++) {
TranObjInfo tmp = sendto.elementAt(i);
if(!tmp.name.equals(t.name)) {
- return false;
+ return false;
}
if(tmp.targetcore != t.targetcore) {
- return false;
+ return false;
}
if(tmp.fs != t.fs) {
- return false;
+ return false;
}
}
return true;
protected void buildCodeSetup() {
try {
if (state.SANDBOX) {
- outsandbox=new CodePrinter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
+ outsandbox=new CodePrinter(new FileOutputStream(PREFIX+"sandboxdefs.c"), true);
}
} catch (Exception e) {
e.printStackTrace();
if (state.DSM) {
if (state.DSMRECOVERYSTATS) {
- outmethod.println("#ifdef RECOVERYSTATS \n");
- outmethod.println("handle();\n");
- outmethod.println("#endif\n");
+ outmethod.println("#ifdef RECOVERYSTATS \n");
+ outmethod.println("handle();\n");
+ outmethod.println("#endif\n");
} else {
- outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
- outmethod.println("handle();\n");
- outmethod.println("#endif\n");
+ outmethod.println("#if defined(TRANSSTATS) || defined(RECOVERYSTATS) \n");
+ outmethod.println("handle();\n");
+ outmethod.println("#endif\n");
}
}
outmethod.println("initializethreads();");
if (state.DSM) {
outmethod.println("if (dstmStartup(argv[1])) {");
if (GENERATEPRECISEGC) {
- outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
+ outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-2);");
} else {
- outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
+ outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-2);");
}
} else {
if (GENERATEPRECISEGC) {
- outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
+ outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);");
} else {
- outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
+ outmethod.println(" struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);");
}
}
if (state.DSM) {
FlatMethod fm=state.getMethodFlat(md);
wb.analyze(lb);
if (!md.getModifiers().isNative()) {
- generateFlatMethod(fm, lb, outmethod);
+ generateFlatMethod(fm, lb, outmethod);
}
}
}
if (state.DSMTASK) {
LocalityBinding lbexecute = new LocalityBinding(typeutil.getExecute(), false);
if(state.DSM)
- lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
+ lbexecute.setGlobalThis(LocalityAnalysis.GLOBAL);
else if( state.SINGLETM)
- lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
+ lbexecute.setGlobalThis(LocalityAnalysis.NORMAL);
outstructs.println("#define EXECUTEMETHOD " + virtualcalls.getLocalityNumber(lbexecute));
}
}
while(classit.hasNext()) {
ClassDescriptor cd=(ClassDescriptor)classit.next();
if (virtualcalls.getMethodCount(cd)>maxcount)
- maxcount=virtualcalls.getMethodCount(cd);
+ maxcount=virtualcalls.getMethodCount(cd);
}
LocalityBinding[][] lbvirtualtable=null;
while(classit.hasNext()) {
ClassDescriptor cd=(ClassDescriptor)classit.next();
if(cd.isInterface()) {
- continue;
+ continue;
}
fillinRow(cd, lbvirtualtable, cd.getId());
}
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 (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 {
- outvirtual.print("0");
- }
- needcomma=true;
+ if (needcomma)
+ outvirtual.print(", ");
+ if (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 {
+ outvirtual.print("0");
+ }
+ needcomma=true;
}
outvirtual.println("");
}
/* 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;
+ 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;
}
}
TempDescriptor temp=fm.getParameter(i);
TypeDescriptor type=temp.getType();
if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
- objectparams.addPtr(temp);
+ objectparams.addPtr(temp);
else
- objectparams.addPrim(temp);
+ objectparams.addPrim(temp);
if(lb!=null&&saveset.contains(temp)) {
- backuptable.get(lb).put(temp, temp.createNew());
+ backuptable.get(lb).put(temp, temp.createNew());
}
}
for(int i=0; i<fm.numTags(); i++) {
TempDescriptor temp=fm.getTag(i);
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
- objectparams.addPtr(temp);
+ objectparams.addPtr(temp);
else
- objectparams.addPrim(temp);
+ objectparams.addPrim(temp);
}
TempObject objecttemps=md!=null?new TempObject(objectparams,md,tag++):new TempObject(objectparams, task, tag++);
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) || (this.state.MULTICOREGC)))
- objecttemps.addPtr(temp);
- else
- objecttemps.addPrim(temp);
- if(lb!=null&&saveset.contains(temp)&&
- !backuptable.get(lb).containsKey(temp))
- backuptable.get(lb).put(temp, temp.createNew());
+ TempDescriptor temp=writes[i];
+ TypeDescriptor type=temp.getType();
+ if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
+ objecttemps.addPtr(temp);
+ else
+ objecttemps.addPrim(temp);
+ if(lb!=null&&saveset.contains(temp)&&
+ !backuptable.get(lb).containsKey(temp))
+ backuptable.get(lb).put(temp, temp.createNew());
}
}
/* Create backup temps */
if (lb!=null) {
for(Iterator<TempDescriptor> tmpit=backuptable.get(lb).values().iterator(); tmpit.hasNext(); ) {
- TempDescriptor tmp=tmpit.next();
- TypeDescriptor type=tmp.getType();
- if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
- objecttemps.addPtr(tmp);
- else
- objecttemps.addPrim(tmp);
+ TempDescriptor tmp=tmpit.next();
+ TypeDescriptor type=tmp.getType();
+ if (type.isPtr()&&((GENERATEPRECISEGC) || (this.state.MULTICOREGC)))
+ objecttemps.addPtr(tmp);
+ else
+ objecttemps.addPrim(tmp);
}
/* Create temp to hold revert table */
if (state.DSM&&(lb.getHasAtomic()||lb.isAtomic())) {
- TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
- if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
- objecttemps.addPtr(reverttmp);
- else
- objecttemps.addPrim(reverttmp);
- reverttable.put(lb, reverttmp);
+ TempDescriptor reverttmp=new TempDescriptor("revertlist", typeutil.getClass(TypeUtil.ObjectClass));
+ if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC))
+ objecttemps.addPtr(reverttmp);
+ else
+ objecttemps.addPrim(reverttmp);
+ reverttable.put(lb, reverttmp);
}
}
}
Iterator allit=cn.getFieldTable().getAllDescriptorsIterator();
int count=0;
while(allit.hasNext()) {
- FieldDescriptor fd=(FieldDescriptor)allit.next();
- TypeDescriptor type=fd.getType();
- if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
- continue;
- if (type.isPtr())
- count++;
+ FieldDescriptor fd=(FieldDescriptor)allit.next();
+ TypeDescriptor type=fd.getType();
+ if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
+ continue;
+ if (type.isPtr())
+ count++;
}
output.print(count);
allit=cn.getFieldTable().getAllDescriptorsIterator();
while(allit.hasNext()) {
- FieldDescriptor fd=(FieldDescriptor)allit.next();
- TypeDescriptor type=fd.getType();
- if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
- continue;
- if (type.isPtr()) {
- output.println(",");
- output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+
- fd.getSafeSymbol()+"))");
- }
+ FieldDescriptor fd=(FieldDescriptor)allit.next();
+ TypeDescriptor type=fd.getType();
+ if (state.DSM&&fd.isGlobal()) //Don't GC the global objects for now
+ continue;
+ if (type.isPtr()) {
+ output.println(",");
+ output.print("((unsigned INTPTR)&(((struct "+cn.getSafeSymbol() +" *)0)->"+
+ fd.getSafeSymbol()+"))");
+ }
}
output.println("};");
}
for(int i=0; i<state.numClasses(); i++) {
ClassDescriptor cn=cdarray[i];
if (needcomma)
- output.println(",");
+ output.println(",");
needcomma=true;
if(cn != null) {
- output.print(cn.getSafeSymbol()+"_pointers");
+ output.print(cn.getSafeSymbol()+"_pointers");
} else {
- output.print("NULL");
+ output.print("NULL");
}
}
for(int i=0; i<state.numArrays(); i++) {
if (needcomma)
- output.println(", ");
+ output.println(", ");
TypeDescriptor tdelement=arraytable[i].dereference();
if (tdelement.isArray()||tdelement.isClass())
- output.print("((unsigned INTPTR *)1)");
+ output.print("((unsigned INTPTR *)1)");
else
- output.print("0");
+ output.print("0");
needcomma=true;
}
for(int i=0; i<state.numClasses(); i++) {
ClassDescriptor cn=cdarray[i];
if (needcomma)
- output.println(", ");
+ output.println(", ");
needcomma=true;
if ((cn != null) && (cn.hasFlags()))
- output.print("1");
+ output.print("1");
else
- output.print("0");
+ output.print("0");
}
output.println("};");
}
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);
+ LocalityBinding lb=lbit.next();
+ MethodDescriptor md=lb.getMethod();
+ if (md.getModifiers().isNative()) {
+ //make sure we only print a native method once
+ if (nativemethods.contains(md)) {
+ FlatMethod fm=state.getMethodFlat(md);
+ generateTempStructs(fm, lb);
+ continue;
+ } else
+ nativemethods.add(md);
+ }
+ generateMethod(cn, md, lb, headersout, output);
}
}
for(Iterator methodit=cn.getMethods(); methodit.hasNext(); ) {
MethodDescriptor md=(MethodDescriptor)methodit.next();
if (md.getModifiers().isNative()&&!nativemethods.contains(md)) {
- //Need to build param structure for library code
- FlatMethod fm=state.getMethodFlat(md);
- generateTempStructs(fm, null);
- generateMethodParam(cn, md, null, output);
+ //Need to build param structure for library code
+ FlatMethod fm=state.getMethodFlat(md);
+ generateTempStructs(fm, null);
+ generateMethodParam(cn, md, null, output);
}
}
}
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
ParamsObject objectparams=(ParamsObject) paramstable.get(lb!=null?lb:md);
if ((state.DSM||state.SINGLETM)&&lb!=null)
- output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
+ output.println("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
else
- output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
+ output.println("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params {");
output.println(" int size;");
output.println(" void * next;");
for(int i=0; i<objectparams.numPointers(); i++) {
- TempDescriptor temp=objectparams.getPointer(i);
- if(state.MGC && temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
- output.println(" int " + temp.getSafeSymbol() + ";");
- } else {
- output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
- }
+ TempDescriptor temp=objectparams.getPointer(i);
+ if(state.MGC && temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
+ output.println(" int " + temp.getSafeSymbol() + ";");
+ } else {
+ output.println(" struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+";");
+ }
}
output.println("};\n");
}
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()+";");
+ 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");
}
/* First the return type */
if (md.getReturnType()!=null) {
if(state.MGC && md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
- headersout.println(" int ");
+ headersout.println(" int ");
} else if (md.getReturnType().isClass()||md.getReturnType().isArray())
- headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
+ headersout.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
else
- headersout.print(md.getReturnType().getSafeSymbol()+" ");
+ headersout.print(md.getReturnType().getSafeSymbol()+" ");
} else
//catch the constructor case
headersout.print("void ");
for(int i=0; i<objectparams.numPrimitives(); i++) {
TempDescriptor temp=objectparams.getPrimitive(i);
if (printcomma)
- headersout.print(", ");
+ headersout.print(", ");
printcomma=true;
if(state.MGC && temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
- headersout.print("int " + temp.getSafeSymbol());
+ headersout.print("int " + temp.getSafeSymbol());
} else if (temp.getType().isClass()||temp.getType().isArray())
- headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
+ headersout.print("struct " + temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
else
- headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
+ headersout.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
}
headersout.println(");\n");
}
if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
//create map
if (atomicmethodmap==null)
- atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
+ atomicmethodmap=new Hashtable<FlatAtomicEnterNode, AtomicRecord>();
//fix these so we get right strings for local variables
localsprefixaddr=localsprefix;
//Generate commit methods here
for(Iterator<FlatNode> fnit=fm.getNodeSet().iterator(); fnit.hasNext(); ) {
- FlatNode fn=fnit.next();
- if (fn.kind()==FKind.FlatAtomicEnterNode&&
- locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
- delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
- //We have an atomic enter
- FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
- Set<FlatNode> exitset=faen.getExits();
- //generate header
- String methodname=md.getSymbol()+(atomicmethodcount++);
- AtomicRecord ar=new AtomicRecord();
- ar.name=methodname;
- arset.add(ar);
-
- atomicmethodmap.put(faen, ar);
-
- //build data structure declaration
- output.println("struct atomicprimitives_"+methodname+" {");
-
- Set<FlatNode> recordset=delaycomp.livecode(lb);
- Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
- Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
- Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
- ar.livein=liveinto;
- ar.reallivein=new HashSet(liveinto);
- ar.liveout=liveout;
- ar.liveoutvirtualread=liveoutvirtualread;
-
-
- for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext(); ) {
- TempDescriptor tmp=it.next();
- //remove the pointers
- if (tmp.getType().isPtr()) {
- it.remove();
- } else {
- //let's print it here
- output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
- }
- }
- for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext(); ) {
- TempDescriptor tmp=it.next();
- //remove the pointers
- if (tmp.getType().isPtr()) {
- it.remove();
- } else if (!liveinto.contains(tmp)) {
- //let's print it here
- output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
- }
- }
- output.println("};");
-
- //print out method name
- output.println("void "+methodname+"(struct "+ cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix+", struct "+ cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals *"+localsprefix+", struct atomicprimitives_"+methodname+" * primitives) {");
- //build code for commit method
-
- //first define local primitives
- Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
- for(Iterator<TempDescriptor> tmpit=alltemps.iterator(); tmpit.hasNext(); ) {
- TempDescriptor tmp=tmpit.next();
- if (!tmp.getType().isPtr()) {
- if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
- //read from live into set
- output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
- } else {
- //just define
- output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
- }
- }
- }
- //turn off write barrier generation
- wb.turnoff();
- state.SINGLETM=false;
- generateCode(faen, fm, lb, exitset, output, false);
- state.SINGLETM=true;
- //turn on write barrier generation
- wb.turnon();
- output.println("}\n\n");
- }
+ FlatNode fn=fnit.next();
+ if (fn.kind()==FKind.FlatAtomicEnterNode&&
+ locality.getAtomic(lb).get(fn.getPrev(0)).intValue()==0&&
+ delaycomp.needsFission(lb, (FlatAtomicEnterNode) fn)) {
+ //We have an atomic enter
+ FlatAtomicEnterNode faen=(FlatAtomicEnterNode) fn;
+ Set<FlatNode> exitset=faen.getExits();
+ //generate header
+ String methodname=md.getSymbol()+(atomicmethodcount++);
+ AtomicRecord ar=new AtomicRecord();
+ ar.name=methodname;
+ arset.add(ar);
+
+ atomicmethodmap.put(faen, ar);
+
+ //build data structure declaration
+ output.println("struct atomicprimitives_"+methodname+" {");
+
+ Set<FlatNode> recordset=delaycomp.livecode(lb);
+ Set<TempDescriptor> liveinto=delaycomp.liveinto(lb, faen, recordset);
+ Set<TempDescriptor> liveout=delaycomp.liveout(lb, faen);
+ Set<TempDescriptor> liveoutvirtualread=delaycomp.liveoutvirtualread(lb, faen);
+ ar.livein=liveinto;
+ ar.reallivein=new HashSet(liveinto);
+ ar.liveout=liveout;
+ ar.liveoutvirtualread=liveoutvirtualread;
+
+
+ for(Iterator<TempDescriptor> it=liveinto.iterator(); it.hasNext(); ) {
+ TempDescriptor tmp=it.next();
+ //remove the pointers
+ if (tmp.getType().isPtr()) {
+ it.remove();
+ } else {
+ //let's print it here
+ output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
+ }
+ }
+ for(Iterator<TempDescriptor> it=liveout.iterator(); it.hasNext(); ) {
+ TempDescriptor tmp=it.next();
+ //remove the pointers
+ if (tmp.getType().isPtr()) {
+ it.remove();
+ } else if (!liveinto.contains(tmp)) {
+ //let's print it here
+ output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
+ }
+ }
+ output.println("};");
+
+ //print out method name
+ output.println("void "+methodname+"(struct "+ cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix+", struct "+ cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals *"+localsprefix+", struct atomicprimitives_"+methodname+" * primitives) {");
+ //build code for commit method
+
+ //first define local primitives
+ Set<TempDescriptor> alltemps=delaycomp.alltemps(lb, faen, recordset);
+ for(Iterator<TempDescriptor> tmpit=alltemps.iterator(); tmpit.hasNext(); ) {
+ TempDescriptor tmp=tmpit.next();
+ if (!tmp.getType().isPtr()) {
+ if (liveinto.contains(tmp)||liveoutvirtualread.contains(tmp)) {
+ //read from live into set
+ output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+"=primitives->"+tmp.getSafeSymbol()+";");
+ } else {
+ //just define
+ output.println(tmp.getType().getSafeSymbol()+" "+tmp.getSafeSymbol()+";");
+ }
+ }
+ }
+ //turn off write barrier generation
+ wb.turnoff();
+ state.SINGLETM=false;
+ generateCode(faen, fm, lb, exitset, output, false);
+ state.SINGLETM=true;
+ //turn on write barrier generation
+ wb.turnon();
+ output.println("}\n\n");
+ }
}
}
//redefine these back to normal
if (state.DELAYCOMP&&!lb.isAtomic()&&lb.getHasAtomic()) {
for(Iterator<AtomicRecord> arit=arset.iterator(); arit.hasNext(); ) {
- AtomicRecord ar=arit.next();
- output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
+ AtomicRecord ar=arit.next();
+ output.println("struct atomicprimitives_"+ar.name+" primitives_"+ar.name+";");
}
}
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
if (md!=null&&(state.DSM||state.SINGLETM))
- output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
+ output.print(" struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
else if (md!=null&&!(state.DSM||state.SINGLETM))
- output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
+ output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_locals "+localsprefix+"={");
else
- output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
+ output.print(" struct "+task.getSafeSymbol()+"_locals "+localsprefix+"={");
output.print(objecttemp.numPointers()+",");
output.print(paramsprefix);
for(int j=0; j<objecttemp.numPointers(); j++)
- output.print(", NULL");
+ output.print(", NULL");
output.println("};");
}
TempDescriptor td=objecttemp.getPrimitive(i);
TypeDescriptor type=td.getType();
if (type.isNull() && !type.isArray())
- output.println(" void * "+td.getSafeSymbol()+";");
+ output.println(" void * "+td.getSafeSymbol()+";");
else if (state.MGC && type.isClass() && type.getClassDesc().isEnum()) {
- output.println(" int " + td.getSafeSymbol() + ";");
+ output.println(" int " + td.getSafeSymbol() + ";");
} else if (type.isClass()||type.isArray())
- output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
+ output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
else
- output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
+ output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
}
if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)) {
//Don't bother if we aren't in recursive methods...The loops case will catch it
if (callgraph.getAllMethods(md).contains(md)) {
- if (state.DSM&&lb.isAtomic())
- output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
- else {
- output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
- }
+ if (state.DSM&&lb.isAtomic())
+ output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
+ else {
+ output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
+ }
}
}
generateCode(fm.getNext(0), fm, lb, null, output, true);
storeset=delaycomp.livecode(lb);
genset=new HashSet<FlatNode>();
if (state.STMARRAY&&!state.DUALVIEW) {
- refset=new HashSet<FlatNode>();
- refset.addAll(delaycomp.getDeref(lb));
- refset.removeAll(delaycomp.getCannotDelay(lb));
- refset.removeAll(delaycomp.getOther(lb));
+ refset=new HashSet<FlatNode>();
+ refset.addAll(delaycomp.getDeref(lb));
+ refset.removeAll(delaycomp.getCannotDelay(lb));
+ refset.removeAll(delaycomp.getOther(lb));
}
if (firstpass) {
- genset.addAll(delaycomp.getCannotDelay(lb));
- genset.addAll(delaycomp.getOther(lb));
+ genset.addAll(delaycomp.getCannotDelay(lb));
+ genset.addAll(delaycomp.getOther(lb));
} else {
- genset.addAll(delaycomp.getNotReady(lb));
- if (state.STMARRAY&&!state.DUALVIEW) {
- genset.removeAll(refset);
- }
+ genset.addAll(delaycomp.getNotReady(lb));
+ if (state.STMARRAY&&!state.DUALVIEW) {
+ genset.removeAll(refset);
+ }
}
unionset=new HashSet<FlatNode>();
unionset.addAll(storeset);
unionset.addAll(genset);
if (state.STMARRAY&&!state.DUALVIEW)
- unionset.addAll(refset);
+ unionset.addAll(refset);
}
/* Do the actual code generation */
tovisit.add(first);
while(current_node!=null||!tovisit.isEmpty()) {
if (current_node==null) {
- current_node=(FlatNode)tovisit.iterator().next();
- tovisit.remove(current_node);
+ current_node=(FlatNode)tovisit.iterator().next();
+ tovisit.remove(current_node);
} else if (tovisit.contains(current_node)) {
- tovisit.remove(current_node);
+ tovisit.remove(current_node);
}
visited.add(current_node);
if (nodetolabel.containsKey(current_node)) {
- output.println("L"+nodetolabel.get(current_node)+":");
+ output.println("L"+nodetolabel.get(current_node)+":");
}
if (state.INSTRUCTIONFAILURE) {
- if (state.THREAD||state.DSM||state.SINGLETM) {
- output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
- } else
- output.println("if ((--instructioncount)==0) injectinstructionfailure();");
+ if (state.THREAD||state.DSM||state.SINGLETM) {
+ output.println("if ((++instructioncount)>failurecount) {instructioncount=0;injectinstructionfailure();}");
+ } else
+ output.println("if ((--instructioncount)==0) injectinstructionfailure();");
}
if (current_node.numNext()==0||stopset!=null&&stopset.contains(current_node)) {
- output.print(" ");
- if (!state.DELAYCOMP||firstpass) {
- generateFlatNode(fm, current_node, output);
- } else {
- //store primitive variables in out set
- AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
- Set<TempDescriptor> liveout=ar.liveout;
- for(Iterator<TempDescriptor> tmpit=liveout.iterator(); tmpit.hasNext(); ) {
- TempDescriptor tmp=tmpit.next();
- output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
- }
- }
-
- if (current_node.kind()!=FKind.FlatReturnNode) {
- if(state.MGC) {
- // TODO add version for normal Java later
- if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
- // a static block, check if it has been executed
- output.println(" global_defsprim_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
- output.println("");
- }
- }
- output.println(" return;");
- }
- current_node=null;
+ output.print(" ");
+ if (!state.DELAYCOMP||firstpass) {
+ generateFlatNode(fm, current_node, output);
+ } else {
+ //store primitive variables in out set
+ AtomicRecord ar=atomicmethodmap.get((FlatAtomicEnterNode)first);
+ Set<TempDescriptor> liveout=ar.liveout;
+ for(Iterator<TempDescriptor> tmpit=liveout.iterator(); tmpit.hasNext(); ) {
+ TempDescriptor tmp=tmpit.next();
+ output.println("primitives->"+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
+ }
+ }
+
+ if (current_node.kind()!=FKind.FlatReturnNode) {
+ if(state.MGC) {
+ // TODO add version for normal Java later
+ if((fm.getMethod() != null) && (fm.getMethod().isStaticBlock())) {
+ // a static block, check if it has been executed
+ output.println(" global_defsprim_p->" + fm.getMethod().getClassDesc().getSafeSymbol()+"static_block_exe_flag = 1;");
+ output.println("");
+ }
+ }
+ output.println(" return;");
+ }
+ current_node=null;
} else if(current_node.numNext()==1) {
- FlatNode nextnode;
- if (state.DELAYCOMP) {
- boolean specialprimitive=false;
- //skip literals...no need to add extra overhead
- if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
- TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
- if (!typedesc.isClass()&&!typedesc.isArray()) {
- specialprimitive=true;
- }
- }
-
- if (genset==null||genset.contains(current_node)||specialprimitive) {
- generateFlatNode(fm, current_node, output);
- }
- if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
- //need to acquire lock
- handleArrayDeref(fm, lb, current_node, output, firstpass);
- }
- if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
- TempDescriptor wrtmp=current_node.writesTemps()[0];
- if (firstpass) {
- //need to store value written by previous node
- if (wrtmp.getType().isPtr()) {
- //only lock the objects that may actually need locking
- if (recorddc.getNeedTrans(lb, current_node)&&
- (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
- wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
- output.println("STOREPTR("+generateTemp(fm, wrtmp)+");/* "+current_node.nodeid+" */");
- } else {
- output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp)+");/* "+current_node.nodeid+" */");
- }
- } else {
- output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp)+");/* "+current_node.nodeid+" */");
- }
- } else {
- //need to read value read by previous node
- if (wrtmp.getType().isPtr()) {
- output.println("RESTOREPTR("+generateTemp(fm, wrtmp)+");/* "+current_node.nodeid+" */");
- } else {
- output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp)+"); /* "+current_node.nodeid+" */");
- }
- }
- }
- nextnode=current_node.getNext(0);
- } else {
- output.print(" ");
- generateFlatNode(fm, current_node, output);
- nextnode=current_node.getNext(0);
- }
- if (visited.contains(nextnode)) {
- output.println("goto L"+nodetolabel.get(nextnode)+";");
- current_node=null;
- } else
- current_node=nextnode;
+ FlatNode nextnode;
+ if (state.DELAYCOMP) {
+ boolean specialprimitive=false;
+ //skip literals...no need to add extra overhead
+ if (storeset!=null&&storeset.contains(current_node)&¤t_node.kind()==FKind.FlatLiteralNode) {
+ TypeDescriptor typedesc=((FlatLiteralNode)current_node).getType();
+ if (!typedesc.isClass()&&!typedesc.isArray()) {
+ specialprimitive=true;
+ }
+ }
+
+ if (genset==null||genset.contains(current_node)||specialprimitive) {
+ generateFlatNode(fm, current_node, output);
+ }
+ if (state.STMARRAY&&!state.DUALVIEW&&refset!=null&&refset.contains(current_node)) {
+ //need to acquire lock
+ handleArrayDeref(fm, lb, current_node, output, firstpass);
+ }
+ if (storeset!=null&&storeset.contains(current_node)&&!specialprimitive) {
+ TempDescriptor wrtmp=current_node.writesTemps()[0];
+ if (firstpass) {
+ //need to store value written by previous node
+ if (wrtmp.getType().isPtr()) {
+ //only lock the objects that may actually need locking
+ if (recorddc.getNeedTrans(lb, current_node)&&
+ (!state.STMARRAY||state.DUALVIEW||!wrtmp.getType().isArray()||
+ wrtmp.getType().getSymbol().equals(TypeUtil.ObjectClass))) {
+ output.println("STOREPTR("+generateTemp(fm, wrtmp)+");/* "+current_node.nodeid+" */");
+ } else {
+ output.println("STOREPTRNOLOCK("+generateTemp(fm, wrtmp)+");/* "+current_node.nodeid+" */");
+ }
+ } else {
+ output.println("STORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp)+");/* "+current_node.nodeid+" */");
+ }
+ } else {
+ //need to read value read by previous node
+ if (wrtmp.getType().isPtr()) {
+ output.println("RESTOREPTR("+generateTemp(fm, wrtmp)+");/* "+current_node.nodeid+" */");
+ } else {
+ output.println("RESTORE"+wrtmp.getType().getSafeDescriptor()+"("+generateTemp(fm, wrtmp)+"); /* "+current_node.nodeid+" */");
+ }
+ }
+ }
+ nextnode=current_node.getNext(0);
+ } else {
+ output.print(" ");
+ generateFlatNode(fm, current_node, output);
+ nextnode=current_node.getNext(0);
+ }
+ if (visited.contains(nextnode)) {
+ output.println("goto L"+nodetolabel.get(nextnode)+";");
+ current_node=null;
+ } else
+ current_node=nextnode;
} else if (current_node.numNext()==2) {
- /* Branch */
- if (state.DELAYCOMP) {
- boolean computeside=false;
- if (firstpass) {
- //need to record which way it should go
- if (genset==null||genset.contains(current_node)) {
- if (storeset!=null&&storeset.contains(current_node)) {
- //need to store which way branch goes
- generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
- } else
- generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
- } else {
- //which side to execute
- computeside=true;
- }
- } else {
- if (genset.contains(current_node)) {
- generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
- } else if (storeset.contains(current_node)) {
- //need to do branch
- branchanalysis.generateGroupCode(current_node, output, nodetolabel);
- } else {
- //which side to execute
- computeside=true;
- }
- }
- if (computeside) {
- Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
- int branch=0;
- if (leftset.size()==0)
- branch=1;
- if (visited.contains(current_node.getNext(branch))) {
- //already visited -- build jump
- output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
- current_node=null;
- } else {
- current_node=current_node.getNext(branch);
- }
- } else {
- if (!visited.contains(current_node.getNext(1)))
- tovisit.add(current_node.getNext(1));
- if (visited.contains(current_node.getNext(0))) {
- output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
- current_node=null;
- } else
- current_node=current_node.getNext(0);
- }
- } else {
- output.print(" ");
- generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
- if (!visited.contains(current_node.getNext(1)))
- tovisit.add(current_node.getNext(1));
- if (visited.contains(current_node.getNext(0))) {
- output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
- current_node=null;
- } else
- current_node=current_node.getNext(0);
- }
+ /* Branch */
+ if (state.DELAYCOMP) {
+ boolean computeside=false;
+ if (firstpass) {
+ //need to record which way it should go
+ if (genset==null||genset.contains(current_node)) {
+ if (storeset!=null&&storeset.contains(current_node)) {
+ //need to store which way branch goes
+ generateStoreFlatCondBranch(fm, lb, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
+ } else
+ generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
+ } else {
+ //which side to execute
+ computeside=true;
+ }
+ } else {
+ if (genset.contains(current_node)) {
+ generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
+ } else if (storeset.contains(current_node)) {
+ //need to do branch
+ branchanalysis.generateGroupCode(current_node, output, nodetolabel);
+ } else {
+ //which side to execute
+ computeside=true;
+ }
+ }
+ if (computeside) {
+ Set<FlatNode> leftset=DelayComputation.getNext(current_node, 0, unionset, lb,locality, true);
+ int branch=0;
+ if (leftset.size()==0)
+ branch=1;
+ if (visited.contains(current_node.getNext(branch))) {
+ //already visited -- build jump
+ output.println("goto L"+nodetolabel.get(current_node.getNext(branch))+";");
+ current_node=null;
+ } else {
+ current_node=current_node.getNext(branch);
+ }
+ } else {
+ if (!visited.contains(current_node.getNext(1)))
+ tovisit.add(current_node.getNext(1));
+ if (visited.contains(current_node.getNext(0))) {
+ output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
+ current_node=null;
+ } else
+ current_node=current_node.getNext(0);
+ }
+ } else {
+ output.print(" ");
+ generateFlatCondBranch(fm, (FlatCondBranch)current_node, "L"+nodetolabel.get(current_node.getNext(1)), output);
+ if (!visited.contains(current_node.getNext(1)))
+ tovisit.add(current_node.getNext(1));
+ if (visited.contains(current_node.getNext(0))) {
+ output.println("goto L"+nodetolabel.get(current_node.getNext(0))+";");
+ current_node=null;
+ } else
+ current_node=current_node.getNext(0);
+ }
} else throw new Error();
}
}
TypeDescriptor elementtype=fsen.getDst().getType().dereference();
String type="";
if (elementtype.isArray()||elementtype.isClass())
- type="void *";
+ type="void *";
else
- type=elementtype.getSafeSymbol()+" ";
+ type=elementtype.getSafeSymbol()+" ";
if (firstpass) {
- output.println("STOREARRAY("+dst+","+index+","+type+")");
+ output.println("STOREARRAY("+dst+","+index+","+type+")");
} else {
- output.println("{");
- output.println(" struct ArrayObject *array;");
- output.println(" int index;");
- output.println(" RESTOREARRAY(array,index);");
- output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
- output.println("}");
+ output.println("{");
+ output.println(" struct ArrayObject *array;");
+ output.println(" int index;");
+ output.println(" RESTOREARRAY(array,index);");
+ output.println(" (("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index]="+src+";");
+ output.println("}");
}
} else if (fn.kind()==FKind.FlatElementNode) {
FlatElementNode fen=(FlatElementNode) fn;
String dst=generateTemp(fm, fen.getDst());
String type="";
if (elementtype.isArray()||elementtype.isClass())
- type="void *";
+ type="void *";
else
- type=elementtype.getSafeSymbol()+" ";
+ type=elementtype.getSafeSymbol()+" ";
if (firstpass) {
- output.println("STOREARRAY("+src+","+index+","+type+")");
+ output.println("STOREARRAY("+src+","+index+","+type+")");
} else {
- output.println("{");
- output.println(" struct ArrayObject *array;");
- output.println(" int index;");
- output.println(" RESTOREARRAY(array,index);");
- output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
- output.println("}");
+ output.println("{");
+ output.println(" struct ArrayObject *array;");
+ output.println(" int index;");
+ output.println(" RESTOREARRAY(array,index);");
+ output.println(" "+dst+"=(("+type+"*)(((char *)&array->___length___)+sizeof(int)))[index];");
+ output.println("}");
}
}
}
if(lastset!=null&&lastset.contains(fn)) {
- // if last is not null and matches, don't go
- // any further for assigning labels
- continue;
+ // if last is not null and matches, don't go
+ // any further for assigning labels
+ continue;
}
for(int i=0; i<fn.numNext(); i++) {
- FlatNode nn=fn.getNext(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++));
- }
+ 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;
}
if (((state.THREAD||state.DSM||state.SINGLETM)&&GENERATEPRECISEGC)) {
if(state.DSM&&locality.getAtomic(currlb).get(fn).intValue()>0) {
- output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
+ output.println("if (needtocollect) checkcollect2("+localsprefixaddr+");");
} else {
- output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
+ output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
}
} else
output.println("/* nop */");
Vector endoffset = new Vector();
int tuplecount = 0; //Keeps track of number of prefetch tuples that need to be generated
for(Iterator it = fpn.hspp.iterator(); it.hasNext(); ) {
- PrefetchPair pp = (PrefetchPair) it.next();
- Integer statusbase = locality.getNodePreTempInfo(currlb,fpn).get(pp.base);
- /* Find prefetches that can generate oid */
- if(statusbase == LocalityAnalysis.GLOBAL) {
- generateTransCode(fm, currlb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(currlb).get(fpn).intValue()>0, false);
- tuplecount++;
- } else if (statusbase == LocalityAnalysis.LOCAL) {
- generateTransCode(fm,currlb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
- } else {
- continue;
- }
+ PrefetchPair pp = (PrefetchPair) it.next();
+ Integer statusbase = locality.getNodePreTempInfo(currlb,fpn).get(pp.base);
+ /* Find prefetches that can generate oid */
+ if(statusbase == LocalityAnalysis.GLOBAL) {
+ generateTransCode(fm, currlb, pp, oids, fieldoffset, endoffset, tuplecount, locality.getAtomic(currlb).get(fpn).intValue()>0, false);
+ tuplecount++;
+ } else if (statusbase == LocalityAnalysis.LOCAL) {
+ generateTransCode(fm,currlb,pp,oids,fieldoffset,endoffset,tuplecount,false,true);
+ } else {
+ continue;
+ }
}
if (tuplecount==0)
- return;
+ return;
System.out.println("Adding prefetch "+fpn+ " to method:" +fm);
output.println("{");
output.println("/* prefetch */");
output.print(" unsigned int oidarray_[] = {");
boolean needcomma=false;
for (Iterator it = oids.iterator(); it.hasNext(); ) {
- if (needcomma)
- output.print(", ");
- output.print(it.next());
- needcomma=true;
+ if (needcomma)
+ output.print(", ");
+ output.print(it.next());
+ needcomma=true;
}
output.println("};");
output.print(" unsigned short endoffsetarry_[] = {");
needcomma=false;
for (Iterator it = endoffset.iterator(); it.hasNext(); ) {
- if (needcomma)
- output.print(", ");
- output.print(it.next());
- needcomma=true;
+ if (needcomma)
+ output.print(", ");
+ output.print(it.next());
+ needcomma=true;
}
output.println("};");
output.print(" short fieldarry_[] = {");
needcomma=false;
for (Iterator it = fieldoffset.iterator(); it.hasNext(); ) {
- if (needcomma)
- output.print(", ");
- output.print(it.next());
- needcomma=true;
+ if (needcomma)
+ output.print(", ");
+ output.print(it.next());
+ needcomma=true;
}
output.println("};");
/* make the prefetch call to Runtime */
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;
- }
- }
+ Descriptor desc=pp.getDescAt(breakindex);
+ if (desc instanceof FieldDescriptor) {
+ FieldDescriptor fd=(FieldDescriptor)desc;
+ if (fd.isGlobal()) {
+ break;
+ }
+ }
}
breakindex++;
}
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();
+ 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))+"+";
- }
- indexcheck+=id.offset+")>=0)&(tmpindex<((struct ArrayObject *)prefptr)->___length___)";
+ IndexDescriptor id=(IndexDescriptor)desc;
+ indexcheck="((tmpindex=";
+ for(int j=0; j<id.tddesc.size(); j++) {
+ indexcheck+=generateTemp(fm, id.getTempDescAt(j))+"+";
+ }
+ 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();
+ 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 newfieldoffset;
Object desc = pp.getDescAt(i);
if(desc instanceof FieldDescriptor) {
- FieldDescriptor fd=(FieldDescriptor)desc;
- newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
- lasttype=fd.getType();
+ FieldDescriptor fd=(FieldDescriptor)desc;
+ newfieldoffset = new String("(unsigned int)(&(((struct "+ lasttype.getSafeSymbol()+" *)0)->"+ fd.getSafeSymbol()+ "))");
+ lasttype=fd.getType();
} else {
- newfieldoffset = "";
- IndexDescriptor id=(IndexDescriptor)desc;
- for(int j = 0; j < id.tddesc.size(); j++) {
- newfieldoffset += generateTemp(fm, id.getTempDescAt(j)) + "+";
- }
- newfieldoffset += id.offset.toString();
- lasttype=lasttype.dereference();
+ newfieldoffset = "";
+ IndexDescriptor id=(IndexDescriptor)desc;
+ for(int j = 0; j < id.tddesc.size(); j++) {
+ newfieldoffset += generateTemp(fm, id.getTempDescAt(j)) + "+";
+ }
+ newfieldoffset += id.offset.toString();
+ lasttype=lasttype.dereference();
}
fieldoffset.add(newfieldoffset);
}
/* Have to generate flat globalconv */
if (fgcn.getMakePtr()) {
if (state.DSM) {
- output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc())+", (unsigned int) "+generateTemp(fm, fgcn.getSrc())+");");
+ output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc())+", (unsigned int) "+generateTemp(fm, fgcn.getSrc())+");");
} else {
- if ((dc==null)||!state.READSET&&dc.getNeedTrans(currlb, fgcn)||state.READSET&&dc.getNeedWriteTrans(currlb, fgcn)) {
- //need to do translation
- output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc())+", "+generateTemp(fm, fgcn.getSrc())+", (void *)("+localsprefixaddr+"));");
- } else if (state.READSET&&dc.getNeedTrans(currlb, fgcn)) {
- if (state.HYBRID&&delaycomp.getConv(currlb).contains(fgcn)) {
- output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc())+", "+generateTemp(fm, fgcn.getSrc())+");");
- } else
- output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc())+", "+generateTemp(fm, fgcn.getSrc())+");");
- }
+ if ((dc==null)||!state.READSET&&dc.getNeedTrans(currlb, fgcn)||state.READSET&&dc.getNeedWriteTrans(currlb, fgcn)) {
+ //need to do translation
+ output.println("TRANSREAD("+generateTemp(fm, fgcn.getSrc())+", "+generateTemp(fm, fgcn.getSrc())+", (void *)("+localsprefixaddr+"));");
+ } else if (state.READSET&&dc.getNeedTrans(currlb, fgcn)) {
+ if (state.HYBRID&&delaycomp.getConv(currlb).contains(fgcn)) {
+ output.println("TRANSREADRDFISSION("+generateTemp(fm, fgcn.getSrc())+", "+generateTemp(fm, fgcn.getSrc())+");");
+ } else
+ output.println("TRANSREADRD("+generateTemp(fm, fgcn.getSrc())+", "+generateTemp(fm, fgcn.getSrc())+");");
+ }
}
} else {
/* Need to convert to OID */
if ((dc==null)||dc.getNeedSrcTrans(currlb,fgcn)) {
- if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(currlb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
- output.println(generateTemp(fm, fgcn.getSrc())+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc())+");");
- } else {
- output.println(generateTemp(fm, fgcn.getSrc())+"=NULL;");
- }
+ if (fgcn.doConvert()||(delaycomp!=null&&delaycomp.needsFission(currlb, fgcn.getAtomicEnter())&&atomicmethodmap.get(fgcn.getAtomicEnter()).reallivein.contains(fgcn.getSrc()))) {
+ output.println(generateTemp(fm, fgcn.getSrc())+"=(void *)COMPOID("+generateTemp(fm, fgcn.getSrc())+");");
+ } else {
+ output.println(generateTemp(fm, fgcn.getSrc())+"=NULL;");
+ }
}
}
}
/* Check to see if we need to generate code for this atomic */
if (locality==null) {
if (GENERATEPRECISEGC) {
- output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
- output.println("stopforgc((struct garbagelist *) &___locals___);");
- output.println("pthread_mutex_lock(&atomiclock);");
- output.println("restartaftergc();");
- output.println("}");
+ output.println("if (pthread_mutex_trylock(&atomiclock)!=0) {");
+ output.println("stopforgc((struct garbagelist *) &___locals___);");
+ output.println("pthread_mutex_lock(&atomiclock);");
+ output.println("restartaftergc();");
+ output.println("}");
} else {
- output.println("pthread_mutex_lock(&atomiclock);");
+ output.println("pthread_mutex_lock(&atomiclock);");
}
return;
}
AtomicRecord ar=atomicmethodmap.get(faen);
//copy in
for(Iterator<TempDescriptor> tmpit=ar.livein.iterator(); tmpit.hasNext(); ) {
- TempDescriptor tmp=tmpit.next();
- output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
+ TempDescriptor tmp=tmpit.next();
+ output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
}
//copy outs that depend on path
for(Iterator<TempDescriptor> tmpit=ar.liveoutvirtualread.iterator(); tmpit.hasNext(); ) {
- TempDescriptor tmp=tmpit.next();
- if (!ar.livein.contains(tmp))
- output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
+ TempDescriptor tmp=tmpit.next();
+ if (!ar.livein.contains(tmp))
+ output.println("primitives_"+ar.name+"."+tmp.getSafeSymbol()+"="+tmp.getSafeSymbol()+";");
}
}
if (state.ABORTREADERS||state.SANDBOX) {
if (state.SANDBOX)
- output.println("abortenabled=1;");
+ output.println("abortenabled=1;");
output.println("if (_setjmp(aborttrans)) {");
output.println(" goto transretry"+faen.getIdentifier()+"; }");
}
output.println("}");
} else {
if (delaycomp.optimizeTrans(currlb, faen.getAtomicEnter())&&(!state.STMARRAY||state.DUALVIEW)) {
- AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
- output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
- //copy out
- for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator(); tmpit.hasNext(); ) {
- TempDescriptor tmp=tmpit.next();
- output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
- }
+ AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
+ output.println("LIGHTWEIGHTCOMMIT("+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+", transretry"+faen.getAtomicEnter().getIdentifier()+");");
+ //copy out
+ for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator(); tmpit.hasNext(); ) {
+ TempDescriptor tmp=tmpit.next();
+ output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
+ }
} else if (delaycomp.needsFission(currlb, faen.getAtomicEnter())) {
- AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
- //do call
- output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
- output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
- output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
- output.println("}");
- //copy out
- output.println("else {");
- for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator(); tmpit.hasNext(); ) {
- TempDescriptor tmp=tmpit.next();
- output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
- }
- output.println("}");
+ AtomicRecord ar=atomicmethodmap.get(faen.getAtomicEnter());
+ //do call
+ output.println("if (transCommit((void (*)(void *, void *, void *))&"+ar.name+", &primitives_"+ar.name+", &"+localsprefix+", "+paramsprefix+")) {");
+ output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
+ output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
+ output.println("}");
+ //copy out
+ output.println("else {");
+ for(Iterator<TempDescriptor> tmpit=ar.liveout.iterator(); tmpit.hasNext(); ) {
+ TempDescriptor tmp=tmpit.next();
+ output.println(tmp.getSafeSymbol()+"=primitives_"+ar.name+"."+tmp.getSafeSymbol()+";");
+ }
+ output.println("}");
} else {
- output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
- output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
- output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
- output.println("}");
+ output.println("if (transCommit(NULL, NULL, NULL, NULL)) {");
+ output.println("if (unlikely(needtocollect)) checkcollect("+localsprefixaddr+");");
+ output.println("goto transretry"+faen.getAtomicEnter().getIdentifier()+";");
+ output.println("}");
}
}
}
// TODO add version for normal Java later
if((md.isStatic() || md.isStaticBlock() || md.isConstructor()) &&
((fm.getMethod().isStaticBlock()) || (fm.getMethod().isInvokedByStatic()))) {
- if(!md.isInvokedByStatic()) {
- System.err.println("Error: a method that is invoked inside a static block is not tagged!");
- }
- // is a static block or is invoked in some static block
- ClassDescriptor cd = fm.getMethod().getClassDesc();
- if(cd == cn) {
- // the same class, do nothing
- // TODO may want to invoke static field initialization here
- } else {
- if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
- // need to check if the class' static fields have been initialized and/or
- // its static blocks have been executed
- output.println("#ifdef MGC_STATIC_INIT_CHECK");
- output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
- if(cn.getNumStaticBlocks() != 0) {
- MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
- output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
- } else {
- output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
- }
- output.println("}");
- output.println("#endif // MGC_STATIC_INIT_CHECK");
- }
- }
+ if(!md.isInvokedByStatic()) {
+ System.err.println("Error: a method that is invoked inside a static block is not tagged!");
+ }
+ // is a static block or is invoked in some static block
+ ClassDescriptor cd = fm.getMethod().getClassDesc();
+ if(cd == cn) {
+ // the same class, do nothing
+ // TODO may want to invoke static field initialization here
+ } else {
+ if((cn.getNumStaticFields() != 0) || (cn.getNumStaticBlocks() != 0)) {
+ // need to check if the class' static fields have been initialized and/or
+ // its static blocks have been executed
+ output.println("#ifdef MGC_STATIC_INIT_CHECK");
+ output.println("if(global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag == 0) {");
+ if(cn.getNumStaticBlocks() != 0) {
+ MethodDescriptor t_md = (MethodDescriptor)cn.getMethodTable().get("staticblocks");
+ output.println(" "+cn.getSafeSymbol()+t_md.getSafeSymbol()+"_"+t_md.getSafeMethodDescriptor()+"();");
+ } else {
+ output.println(" global_defsprim_p->" + cn.getSafeSymbol()+"static_block_exe_flag = 1;");
+ }
+ output.println("}");
+ output.println("#endif // MGC_STATIC_INIT_CHECK");
+ }
+ }
}
if((md.getSymbol().equals("MonitorEnter") || md.getSymbol().equals("MonitorExit")) && fc.getThis().getSymbol().equals("classobj")) {
- // call MonitorEnter/MonitorExit on a class obj
- output.println(" " + cn.getSafeSymbol()+md.getSafeSymbol()+"_"
- + md.getSafeMethodDescriptor() + "((struct ___Object___*)(((void **)(((char *) &(global_defs_p->classobjs->___length___))+sizeof(int)))["
- + fc.getThis().getType().getClassDesc().getId() + "]));");
- return;
+ // call MonitorEnter/MonitorExit on a class obj
+ output.println(" " + cn.getSafeSymbol()+md.getSafeSymbol()+"_"
+ + md.getSafeMethodDescriptor() + "((struct ___Object___*)(((void **)(((char *) &(global_defs_p->classobjs->___length___))+sizeof(int)))["
+ + fc.getThis().getType().getClassDesc().getId() + "]));");
+ return;
}
}
output.println("{");
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
if (currlb!=null) {
- LocalityBinding fclb=locality.getBinding(currlb, fc);
- output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
+ LocalityBinding fclb=locality.getBinding(currlb, fc);
+ output.print(" struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
} else
- output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
+ output.print(" struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params __parameterlist__={");
output.print(objectparams.numPointers());
output.print(", "+localsprefixaddr);
if (md.getThis()!=null) {
- output.print(", ");
- output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis()));
+ output.print(", ");
+ output.print("(struct "+md.getThis().getType().getSafeSymbol() +" *)"+ generateTemp(fm,fc.getThis()));
}
if (fc.getThis()!=null&&md.getThis()==null) {
- System.out.println("WARNING!!!!!!!!!!!!");
- System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
+ System.out.println("WARNING!!!!!!!!!!!!");
+ System.out.println("Source code calls static method "+md+" on an object in "+fm.getMethod()+"!");
}
for(int i=0; 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));
- else
- output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ));
- }
+ 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));
+ else
+ output.print("(struct "+md.getParamType(i).getSafeSymbol() +" *)"+generateTemp(fm, targ));
+ }
}
output.println("};");
}
if (md.isStatic()||md.getReturnType()==null||singleCall(fc.getThis().getType().getClassDesc(),md)) {
//no
if (currlb!=null) {
- LocalityBinding fclb=locality.getBinding(currlb, fc);
- output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
+ LocalityBinding fclb=locality.getBinding(currlb, fc);
+ output.print(cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
} else {
- output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
+ output.print(cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor());
}
} else {
//yes
output.print("((");
if (state.MGC && md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
- output.print("int ");
+ output.print("int ");
} else if (md.getReturnType().isClass()||md.getReturnType().isArray())
- output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
+ output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
else
- output.print(md.getReturnType().getSafeSymbol()+" ");
+ output.print(md.getReturnType().getSafeSymbol()+" ");
output.print("(*)(");
boolean printcomma=false;
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- if (currlb!=null) {
- LocalityBinding fclb=locality.getBinding(currlb, fc);
- output.print("struct "+cn.getSafeSymbol()+fclb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
- } else
- output.print("struct "+cn.getSafeSymbol()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * ");
- printcomma=true;
+ if (currlb!=null) {
+ LocalityBinding fclb=locality.getBinding(currlb, 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;
}
for(int i=0; i<objectparams.numPrimitives(); i++) {
- TempDescriptor temp=objectparams.getPrimitive(i);
- if (printcomma)
- output.print(", ");
- printcomma=true;
- if (state.MGC && temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
- output.print("int ");
- } else if (temp.getType().isClass()||temp.getType().isArray())
- output.print("struct " + temp.getType().getSafeSymbol()+" * ");
- else
- output.print(temp.getType().getSafeSymbol());
+ TempDescriptor temp=objectparams.getPrimitive(i);
+ if (printcomma)
+ output.print(", ");
+ printcomma=true;
+ if (state.MGC && temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
+ output.print("int ");
+ } else if (temp.getType().isClass()||temp.getType().isArray())
+ output.print("struct " + temp.getType().getSafeSymbol()+" * ");
+ else
+ output.print(temp.getType().getSafeSymbol());
}
if (currlb!=null) {
- LocalityBinding fclb=locality.getBinding(currlb, fc);
- output.print("))virtualtable["+generateTemp(fm,fc.getThis())+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
+ LocalityBinding fclb=locality.getBinding(currlb, fc);
+ output.print("))virtualtable["+generateTemp(fm,fc.getThis())+"->type*"+maxcount+"+"+virtualcalls.getLocalityNumber(fclb)+"])");
} else
- output.print("))virtualtable["+generateTemp(fm,fc.getThis())+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
+ output.print("))virtualtable["+generateTemp(fm,fc.getThis())+"->type*"+maxcount+"+"+virtualcalls.getMethodNumber(md)+"])");
}
output.print("(");
if (!GENERATEPRECISEGC && !this.state.MULTICOREGC) {
if (fc.getThis()!=null) {
- TypeDescriptor ptd=null;
- if(md.getThis() != null) {
- ptd = md.getThis().getType();
- } else {
- ptd = fc.getThis().getType();
- }
- if (needcomma)
- output.print(",");
- if(state.MGC && ptd.isClass() && ptd.getClassDesc().isEnum()) {
- // do nothing
- } else if (ptd.isClass()&&!ptd.isArray())
- output.print("(struct "+ptd.getSafeSymbol()+" *) ");
- output.print(generateTemp(fm,fc.getThis()));
- needcomma=true;
+ TypeDescriptor ptd=null;
+ if(md.getThis() != null) {
+ ptd = md.getThis().getType();
+ } else {
+ ptd = fc.getThis().getType();
+ }
+ if (needcomma)
+ output.print(",");
+ if(state.MGC && ptd.isClass() && ptd.getClassDesc().isEnum()) {
+ // do nothing
+ } else if (ptd.isClass()&&!ptd.isArray())
+ output.print("(struct "+ptd.getSafeSymbol()+" *) ");
+ output.print(generateTemp(fm,fc.getThis()));
+ needcomma=true;
}
}
Descriptor var=md.getParameter(i);
TempDescriptor paramtemp=(TempDescriptor)temptovar.get(var);
if (objectparams.isParamPrim(paramtemp)) {
- TempDescriptor targ=fc.getArg(i);
- if (needcomma)
- output.print(", ");
+ TempDescriptor targ=fc.getArg(i);
+ if (needcomma)
+ output.print(", ");
- TypeDescriptor ptd=md.getParamType(i);
- if (state.MGC && ptd.isClass() && ptd.getClassDesc().isEnum()) {
- // do nothing
- } else if (ptd.isClass()&&!ptd.isArray())
- output.print("(struct "+ptd.getSafeSymbol()+" *) ");
- output.print(generateTemp(fm, targ));
- needcomma=true;
+ TypeDescriptor ptd=md.getParamType(i);
+ if (state.MGC && ptd.isClass() && ptd.getClassDesc().isEnum()) {
+ // do nothing
+ } else if (ptd.isClass()&&!ptd.isArray())
+ output.print("(struct "+ptd.getSafeSymbol()+" *) ");
+ output.print(generateTemp(fm, targ));
+ needcomma=true;
}
}
output.println(");");
output.println(dst+"="+ src +"->"+field+ ";");
if (ffn.getField().getType().isPtr()&&locality.getAtomic(currlb).get(ffn).intValue()>0&&
locality.getNodePreTempInfo(currlb, ffn).get(ffn.getSrc())!=LocalityAnalysis.SCRATCH) {
- if ((dc==null)||(!state.READSET&&dc.getNeedTrans(currlb, ffn))||
- (state.READSET&&dc.getNeedWriteTrans(currlb, ffn))) {
- output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
- } else if (state.READSET&&dc.getNeedTrans(currlb, ffn)) {
- if (state.HYBRID&&delaycomp.getConv(currlb).contains(ffn)) {
- output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
- } else
- output.println("TRANSREADRD("+dst+", "+dst+");");
- }
+ if ((dc==null)||(!state.READSET&&dc.getNeedTrans(currlb, ffn))||
+ (state.READSET&&dc.getNeedWriteTrans(currlb, ffn))) {
+ output.println("TRANSREAD("+dst+", "+dst+", (void *) (" + localsprefixaddr + "));");
+ } else if (state.READSET&&dc.getNeedTrans(currlb, ffn)) {
+ if (state.HYBRID&&delaycomp.getConv(currlb).contains(ffn)) {
+ output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
+ } else
+ output.println("TRANSREADRD("+dst+", "+dst+");");
+ }
}
} else if (state.DSM) {
Integer status=locality.getNodePreTempInfo(currlb,ffn).get(ffn.getSrc());
if (status==LocalityAnalysis.GLOBAL) {
- String field=ffn.getField().getSafeSymbol();
- String src=generateTemp(fm, ffn.getSrc());
- String dst=generateTemp(fm, ffn.getDst());
-
- if (ffn.getField().getType().isPtr()) {
- output.println(dst+"="+ src +"->"+field+ ";");
- output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
- } else {
- output.println(dst+"="+ src+"->"+field+";");
- }
+ String field=ffn.getField().getSafeSymbol();
+ String src=generateTemp(fm, ffn.getSrc());
+ String dst=generateTemp(fm, ffn.getDst());
+
+ if (ffn.getField().getType().isPtr()) {
+ output.println(dst+"="+ src +"->"+field+ ";");
+ output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
+ } else {
+ output.println(dst+"="+ src+"->"+field+";");
+ }
} else if (status==LocalityAnalysis.LOCAL) {
- if (ffn.getField().getType().isPtr()&&
- ffn.getField().isGlobal()) {
- String field=ffn.getField().getSafeSymbol();
- String src=generateTemp(fm, ffn.getSrc());
- String dst=generateTemp(fm, ffn.getDst());
- output.println(dst+"="+ src +"->"+field+ ";");
- if (locality.getAtomic(currlb).get(ffn).intValue()>0)
- output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
- } else
- output.println(generateTemp(fm, ffn.getDst())+"="+ generateTemp(fm,ffn.getSrc())+"->"+ ffn.getField().getSafeSymbol()+";");
+ if (ffn.getField().getType().isPtr()&&
+ ffn.getField().isGlobal()) {
+ String field=ffn.getField().getSafeSymbol();
+ String src=generateTemp(fm, ffn.getSrc());
+ String dst=generateTemp(fm, ffn.getDst());
+ output.println(dst+"="+ src +"->"+field+ ";");
+ if (locality.getAtomic(currlb).get(ffn).intValue()>0)
+ output.println("TRANSREAD("+dst+", (unsigned int) "+dst+");");
+ } else
+ output.println(generateTemp(fm, ffn.getDst())+"="+ generateTemp(fm,ffn.getSrc())+"->"+ ffn.getField().getSafeSymbol()+";");
} else if (status==LocalityAnalysis.EITHER) {
- //Code is reading from a null pointer
- output.println("if ("+generateTemp(fm, ffn.getSrc())+") {");
- output.println("#ifndef RAW");
- output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
- output.println("#endif");
- //This should throw a suitable null pointer error
- output.println(generateTemp(fm, ffn.getDst())+"="+ generateTemp(fm,ffn.getSrc())+"->"+ ffn.getField().getSafeSymbol()+";");
+ //Code is reading from a null pointer
+ output.println("if ("+generateTemp(fm, ffn.getSrc())+") {");
+ output.println("#ifndef RAW");
+ output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
+ output.println("#endif");
+ //This should throw a suitable null pointer error
+ output.println(generateTemp(fm, ffn.getDst())+"="+ generateTemp(fm,ffn.getSrc())+"->"+ ffn.getField().getSafeSymbol()+";");
} else
- throw new Error("Read from non-global/non-local in:"+currlb.getExplanation());
+ throw new Error("Read from non-global/non-local in:"+currlb.getExplanation());
}
}
String dst=generateTemp(fm,fsfn.getDst());
output.println("//"+srcptr+" "+fsfn.getSrc().getType().isNull());
if (srcptr&&!fsfn.getSrc().getType().isNull()) {
- output.println("{");
- if ((dc==null)||dc.getNeedSrcTrans(currlb, fsfn)&&
- locality.getNodePreTempInfo(currlb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
- output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
- } else {
- output.println("INTPTR srcoid=(INTPTR)"+src+";");
- }
+ output.println("{");
+ if ((dc==null)||dc.getNeedSrcTrans(currlb, fsfn)&&
+ locality.getNodePreTempInfo(currlb, fsfn).get(fsfn.getSrc())!=LocalityAnalysis.SCRATCH) {
+ output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
+ } else {
+ output.println("INTPTR srcoid=(INTPTR)"+src+";");
+ }
}
if (wb.needBarrier(fsfn)&&
locality.getNodePreTempInfo(currlb, fsfn).get(fsfn.getDst())!=LocalityAnalysis.SCRATCH) {
- if (state.EVENTMONITOR) {
- output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
- }
- output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
+ if (state.EVENTMONITOR) {
+ output.println("if ("+dst+"->___objstatus___&DIRTY) EVLOGEVENTOBJ(EV_WRITE,"+dst+"->objuid)");
+ }
+ output.println("*((unsigned int *)&("+dst+"->___objstatus___))|=DIRTY;");
}
if (srcptr&!fsfn.getSrc().getType().isNull()) {
- output.println("*((unsigned INTPTR *)&("+dst+"->"+
- fsfn.getField().getSafeSymbol()+"))=srcoid;");
- output.println("}");
+ output.println("*((unsigned INTPTR *)&("+dst+"->"+
+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
+ output.println("}");
} else {
- output.println(dst+"->"+
- fsfn.getField().getSafeSymbol()+"="+ src+";");
+ output.println(dst+"->"+
+ fsfn.getField().getSafeSymbol()+"="+ src+";");
}
} else if (state.DSM && locality.getAtomic(currlb).get(fsfn).intValue()>0) {
Integer statussrc=locality.getNodePreTempInfo(currlb,fsfn).get(fsfn.getSrc());
String src=generateTemp(fm,fsfn.getSrc());
String dst=generateTemp(fm,fsfn.getDst());
if (srcglobal) {
- output.println("{");
- output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
+ output.println("{");
+ output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
}
if (statusdst.equals(LocalityAnalysis.GLOBAL)) {
- String glbdst=dst;
- //mark it dirty
- if (wb.needBarrier(fsfn))
- output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
- if (srcglobal) {
- output.println("*((unsigned INTPTR *)&("+glbdst+"->"+
- fsfn.getField().getSafeSymbol()+"))=srcoid;");
- } else
- output.println(glbdst+"->"+
- fsfn.getField().getSafeSymbol()+"="+ src+";");
+ String glbdst=dst;
+ //mark it dirty
+ if (wb.needBarrier(fsfn))
+ output.println("*((unsigned int *)&("+dst+"->___localcopy___))|=DIRTY;");
+ if (srcglobal) {
+ output.println("*((unsigned INTPTR *)&("+glbdst+"->"+
+ fsfn.getField().getSafeSymbol()+"))=srcoid;");
+ } else
+ output.println(glbdst+"->"+
+ fsfn.getField().getSafeSymbol()+"="+ src+";");
} else if (statusdst.equals(LocalityAnalysis.LOCAL)) {
- /** Check if we need to copy */
- output.println("if(!"+dst+"->"+localcopystr+") {");
- /* Link object into list */
- String revertptr=generateTemp(fm, reverttable.get(currlb));
- output.println(revertptr+"=revertlist;");
- if (GENERATEPRECISEGC || this.state.MULTICOREGC)
- output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
- else
- output.println("COPY_OBJ("+dst+");");
- output.println(dst+"->"+nextobjstr+"="+revertptr+";");
- output.println("revertlist=(struct ___Object___ *)"+dst+";");
- output.println("}");
- if (srcglobal)
- output.println(dst+"->"+
- fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
- else
- output.println(dst+"->"+
- fsfn.getField().getSafeSymbol()+"="+ src+";");
+ /** Check if we need to copy */
+ output.println("if(!"+dst+"->"+localcopystr+") {");
+ /* Link object into list */
+ String revertptr=generateTemp(fm, reverttable.get(currlb));
+ output.println(revertptr+"=revertlist;");
+ if (GENERATEPRECISEGC || this.state.MULTICOREGC)
+ output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
+ else
+ output.println("COPY_OBJ("+dst+");");
+ output.println(dst+"->"+nextobjstr+"="+revertptr+";");
+ output.println("revertlist=(struct ___Object___ *)"+dst+";");
+ output.println("}");
+ if (srcglobal)
+ output.println(dst+"->"+
+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
+ else
+ output.println(dst+"->"+
+ fsfn.getField().getSafeSymbol()+"="+ src+";");
} else if (statusdst.equals(LocalityAnalysis.EITHER)) {
- //writing to a null...bad
- output.println("if ("+dst+") {");
- output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
- if (srcglobal)
- output.println(dst+"->"+
- fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
- else
- output.println(dst+"->"+
- fsfn.getField().getSafeSymbol()+"="+ src+";");
+ //writing to a null...bad
+ output.println("if ("+dst+") {");
+ output.println("printf(\"BIG ERROR 2\\n\");exit(-1);}");
+ if (srcglobal)
+ output.println(dst+"->"+
+ fsfn.getField().getSafeSymbol()+"=(void *) srcoid;");
+ else
+ output.println(dst+"->"+
+ fsfn.getField().getSafeSymbol()+"="+ src+";");
}
if (srcglobal) {
- output.println("}");
+ output.println("}");
}
}
}
//Single machine transaction case
String dst=generateTemp(fm, fen.getDst());
if ((!state.STMARRAY)||(!wb.needBarrier(fen))||locality.getNodePreTempInfo(currlb, fen).get(fen.getSrc())==LocalityAnalysis.SCRATCH||locality.getAtomic(currlb).get(fen).intValue()==0||(state.READSET&&!dc.getNeedGet(currlb, fen))) {
- output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];");
+ output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];");
} else {
- output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc())+", "+generateTemp(fm, fen.getIndex())+", "+type+");");
+ output.println("STMGETARRAY("+dst+", "+ generateTemp(fm,fen.getSrc())+", "+generateTemp(fm, fen.getIndex())+", "+type+");");
}
if (elementtype.isPtr()&&locality.getAtomic(currlb).get(fen).intValue()>0&&
locality.getNodePreTempInfo(currlb, fen).get(fen.getSrc())!=LocalityAnalysis.SCRATCH) {
- if ((dc==null)||!state.READSET&&dc.getNeedTrans(currlb, fen)||state.READSET&&dc.getNeedWriteTrans(currlb, fen)) {
- output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
- } else if (state.READSET&&dc.getNeedTrans(currlb, fen)) {
- if (state.HYBRID&&delaycomp.getConv(currlb).contains(fen)) {
- output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
- } else
- output.println("TRANSREADRD("+dst+", "+dst+");");
- }
+ if ((dc==null)||!state.READSET&&dc.getNeedTrans(currlb, fen)||state.READSET&&dc.getNeedWriteTrans(currlb, fen)) {
+ output.println("TRANSREAD("+dst+", "+dst+", (void *)(" + localsprefixaddr+"));");
+ } else if (state.READSET&&dc.getNeedTrans(currlb, fen)) {
+ if (state.HYBRID&&delaycomp.getConv(currlb).contains(fen)) {
+ output.println("TRANSREADRDFISSION("+dst+", "+dst+");");
+ } else
+ output.println("TRANSREADRD("+dst+", "+dst+");");
+ }
}
} else if (state.DSM) {
Integer status=locality.getNodePreTempInfo(currlb,fen).get(fen.getSrc());
if (status==LocalityAnalysis.GLOBAL) {
- String dst=generateTemp(fm, fen.getDst());
- if (elementtype.isPtr()) {
- output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];");
- output.println("TRANSREAD("+dst+", "+dst+");");
- } else {
- output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];");
- }
+ String dst=generateTemp(fm, fen.getDst());
+ if (elementtype.isPtr()) {
+ output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];");
+ output.println("TRANSREAD("+dst+", "+dst+");");
+ } else {
+ output.println(dst +"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];");
+ }
} else if (status==LocalityAnalysis.LOCAL) {
- output.println(generateTemp(fm, fen.getDst())+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];");
+ output.println(generateTemp(fm, fen.getDst())+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];");
} else if (status==LocalityAnalysis.EITHER) {
- //Code is reading from a null pointer
- output.println("if ("+generateTemp(fm, fen.getSrc())+") {");
- output.println("#ifndef RAW");
- output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
- output.println("#endif");
- //This should throw a suitable null pointer error
- output.println(generateTemp(fm, fen.getDst())+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];");
+ //Code is reading from a null pointer
+ output.println("if ("+generateTemp(fm, fen.getSrc())+") {");
+ output.println("#ifndef RAW");
+ output.println("printf(\"BIG ERROR\\n\");exit(-1);}");
+ output.println("#endif");
+ //This should throw a suitable null pointer error
+ output.println(generateTemp(fm, fen.getDst())+"=(("+ type+"*)(((char *) &("+ generateTemp(fm,fen.getSrc())+"->___length___))+sizeof(int)))["+generateTemp(fm, fen.getIndex())+"];");
} else
- throw new Error("Read from non-global/non-local in:"+currlb.getExplanation());
+ throw new Error("Read from non-global/non-local in:"+currlb.getExplanation());
}
}
//Transaction set element case
if (wb.needBarrier(fsen)&&
locality.getNodePreTempInfo(currlb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH) {
- output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst())+"->___objstatus___))|=DIRTY;");
+ output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst())+"->___objstatus___))|=DIRTY;");
}
if (fsen.getSrc().getType().isPtr()&&!fsen.getSrc().getType().isNull()) {
- output.println("{");
- String src=generateTemp(fm, fsen.getSrc());
- if ((dc==null)||dc.getNeedSrcTrans(currlb, fsen)&&
- locality.getNodePreTempInfo(currlb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
- output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
- } else {
- output.println("INTPTR srcoid=(INTPTR)"+src+";");
- }
- if (state.STMARRAY&&locality.getNodePreTempInfo(currlb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(currlb).get(fsen).intValue()>0) {
- output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst())+", "+generateTemp(fm, fsen.getIndex())+", srcoid, INTPTR);");
- } else {
- output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]=srcoid;");
- }
- output.println("}");
+ output.println("{");
+ String src=generateTemp(fm, fsen.getSrc());
+ if ((dc==null)||dc.getNeedSrcTrans(currlb, fsen)&&
+ locality.getNodePreTempInfo(currlb, fsen).get(fsen.getSrc())!=LocalityAnalysis.SCRATCH) {
+ output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
+ } else {
+ output.println("INTPTR srcoid=(INTPTR)"+src+";");
+ }
+ if (state.STMARRAY&&locality.getNodePreTempInfo(currlb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(currlb).get(fsen).intValue()>0) {
+ output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst())+", "+generateTemp(fm, fsen.getIndex())+", srcoid, INTPTR);");
+ } else {
+ output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]=srcoid;");
+ }
+ output.println("}");
} else {
- if (state.STMARRAY&&locality.getNodePreTempInfo(currlb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(currlb).get(fsen).intValue()>0) {
- output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst())+", "+generateTemp(fm, fsen.getIndex())+", "+ generateTemp(fm, fsen.getSrc()) +", "+type+");");
- } else {
- output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]="+generateTemp(fm,fsen.getSrc())+";");
- }
+ if (state.STMARRAY&&locality.getNodePreTempInfo(currlb, fsen).get(fsen.getDst())!=LocalityAnalysis.SCRATCH&&wb.needBarrier(fsen)&&locality.getAtomic(currlb).get(fsen).intValue()>0) {
+ output.println("STMSETARRAY("+generateTemp(fm, fsen.getDst())+", "+generateTemp(fm, fsen.getIndex())+", "+ generateTemp(fm, fsen.getSrc()) +", "+type+");");
+ } else {
+ output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]="+generateTemp(fm,fsen.getSrc())+";");
+ }
}
} else if (state.DSM && locality.getAtomic(currlb).get(fsen).intValue()>0) {
Integer statussrc=locality.getNodePreTempInfo(currlb,fsen).get(fsen.getSrc());
boolean dstlocal=(statusdst==LocalityAnalysis.LOCAL)||(statusdst==LocalityAnalysis.EITHER);
if (dstglobal) {
- if (wb.needBarrier(fsen))
- output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst())+"->___localcopy___))|=DIRTY;");
+ if (wb.needBarrier(fsen))
+ output.println("*((unsigned int *)&("+generateTemp(fm,fsen.getDst())+"->___localcopy___))|=DIRTY;");
} else if (dstlocal) {
- /** Check if we need to copy */
- String dst=generateTemp(fm, fsen.getDst());
- output.println("if(!"+dst+"->"+localcopystr+") {");
- /* Link object into list */
- String revertptr=generateTemp(fm, reverttable.get(currlb));
- output.println(revertptr+"=revertlist;");
- if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
- output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
- else
- output.println("COPY_OBJ("+dst+");");
- output.println(dst+"->"+nextobjstr+"="+revertptr+";");
- output.println("revertlist=(struct ___Object___ *)"+dst+";");
- output.println("}");
+ /** Check if we need to copy */
+ String dst=generateTemp(fm, fsen.getDst());
+ output.println("if(!"+dst+"->"+localcopystr+") {");
+ /* Link object into list */
+ String revertptr=generateTemp(fm, reverttable.get(currlb));
+ output.println(revertptr+"=revertlist;");
+ if ((GENERATEPRECISEGC) || this.state.MULTICOREGC)
+ output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
+ else
+ output.println("COPY_OBJ("+dst+");");
+ output.println(dst+"->"+nextobjstr+"="+revertptr+";");
+ output.println("revertlist=(struct ___Object___ *)"+dst+";");
+ output.println("}");
} else {
- System.out.println("Node: "+fsen);
- System.out.println(currlb);
- System.out.println("statusdst="+statusdst);
- System.out.println(fm.printMethod());
- throw new Error("Unknown array type");
+ System.out.println("Node: "+fsen);
+ System.out.println(currlb);
+ System.out.println("statusdst="+statusdst);
+ System.out.println(fm.printMethod());
+ throw new Error("Unknown array type");
}
if (srcglobal) {
- output.println("{");
- String src=generateTemp(fm, fsen.getSrc());
- output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
- output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]=srcoid;");
- output.println("}");
+ output.println("{");
+ String src=generateTemp(fm, fsen.getSrc());
+ output.println("INTPTR srcoid=("+src+"!=NULL?((INTPTR)"+src+"->"+oidstr+"):0);");
+ output.println("((INTPTR*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]=srcoid;");
+ output.println("}");
} else {
- output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]="+generateTemp(fm,fsen.getSrc())+";");
+ output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]="+generateTemp(fm,fsen.getSrc())+";");
}
} else {
if (state.FASTCHECK) {
- String dst=generateTemp(fm, fsen.getDst());
- output.println("if(!"+dst+"->"+localcopystr+") {");
- /* Link object into list */
- if (GENERATEPRECISEGC || this.state.MULTICOREGC)
- output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
- else
- output.println("COPY_OBJ("+dst+");");
- output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
- output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
- output.println("}");
+ String dst=generateTemp(fm, fsen.getDst());
+ output.println("if(!"+dst+"->"+localcopystr+") {");
+ /* Link object into list */
+ if (GENERATEPRECISEGC || this.state.MULTICOREGC)
+ output.println("COPY_OBJ((struct garbagelist *)"+localsprefixaddr+",(struct ___Object___ *)"+dst+");");
+ else
+ output.println("COPY_OBJ("+dst+");");
+ output.println(dst+"->"+nextobjstr+"="+fcrevert+";");
+ output.println(fcrevert+"=(struct ___Object___ *)"+dst+";");
+ output.println("}");
}
output.println("(("+type +"*)(((char *) &("+ generateTemp(fm,fsen.getDst())+"->___length___))+sizeof(int)))["+generateTemp(fm, fsen.getIndex())+"]="+generateTemp(fm,fsen.getSrc())+";");
}
}
if (state.SINGLETM) {
if (fn.getType().isArray()) {
- int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
- if (locality.getAtomic(currlb).get(fn).intValue()>0) {
- //inside transaction
- output.println(generateTemp(fm,fn.getDst())+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");");
- } else {
- //outside transaction
- output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");");
- }
+ int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
+ if (locality.getAtomic(currlb).get(fn).intValue()>0) {
+ //inside transaction
+ output.println(generateTemp(fm,fn.getDst())+"=allocate_newarraytrans("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");");
+ } else {
+ //outside transaction
+ output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");");
+ }
} else {
- if (locality.getAtomic(currlb).get(fn).intValue()>0) {
- //inside transaction
- output.println(generateTemp(fm,fn.getDst())+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
- } else {
- //outside transaction
- output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
- }
+ if (locality.getAtomic(currlb).get(fn).intValue()>0) {
+ //inside transaction
+ output.println(generateTemp(fm,fn.getDst())+"=allocate_newtrans("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
+ } else {
+ //outside transaction
+ output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
+ }
}
} else if (fn.getType().isArray()) {
int arrayid=state.getArrayNumber(fn.getType())+state.numClasses();
if (fn.isGlobal()) {
- output.println(generateTemp(fm,fn.getDst())+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize())+");");
+ output.println(generateTemp(fm,fn.getDst())+"=allocate_newarrayglobal("+arrayid+", "+generateTemp(fm, fn.getSize())+");");
} else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");");
+ output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+localsprefixaddr+", "+arrayid+", "+generateTemp(fm, fn.getSize())+");");
} else {
- output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize())+");");
+ output.println(generateTemp(fm,fn.getDst())+"=allocate_newarray("+arrayid+", "+generateTemp(fm, fn.getSize())+");");
}
} else {
if (fn.isGlobal()) {
- output.println(generateTemp(fm,fn.getDst())+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
+ output.println(generateTemp(fm,fn.getDst())+"=allocate_newglobal("+fn.getType().getClassDesc().getId()+");");
} else if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
+ output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+localsprefixaddr+", "+fn.getType().getClassDesc().getId()+");");
} else {
- output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
+ output.println(generateTemp(fm,fn.getDst())+"=allocate_new("+fn.getType().getClassDesc().getId()+");");
}
}
if (state.DSM && locality.getAtomic(currlb).get(fn).intValue()>0&&!fn.isGlobal()) {
protected void generateFlatOpNode(FlatMethod fm, FlatOpNode fon, PrintWriter output) {
if (fon.getRight()!=null) {
if (fon.getOp().getOp()==Operation.URIGHTSHIFT) {
- if (fon.getLeft().getType().isLong())
- output.println(generateTemp(fm, fon.getDest())+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";");
- else
- output.println(generateTemp(fm, fon.getDest())+" = ((unsigned int)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";");
+ if (fon.getLeft().getType().isLong())
+ output.println(generateTemp(fm, fon.getDest())+" = ((unsigned long long)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";");
+ else
+ output.println(generateTemp(fm, fon.getDest())+" = ((unsigned int)"+generateTemp(fm, fon.getLeft())+")>>"+generateTemp(fm,fon.getRight())+";");
} else if (dc!=null) {
- output.print(generateTemp(fm, fon.getDest())+" = (");
- if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
- output.print("(void *)");
- if (dc.getNeedLeftSrcTrans(currlb, fon))
- output.print("("+generateTemp(fm, fon.getLeft())+"!=NULL?"+generateTemp(fm, fon.getLeft())+"->"+oidstr+":NULL)");
- else
- output.print(generateTemp(fm, fon.getLeft()));
- output.print(")"+fon.getOp().toString()+"(");
- if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
- output.print("(void *)");
- if (dc.getNeedRightSrcTrans(currlb, fon))
- output.println("("+generateTemp(fm, fon.getRight())+"!=NULL?"+generateTemp(fm, fon.getRight())+"->"+oidstr+":NULL));");
- else
- output.println(generateTemp(fm,fon.getRight())+");");
+ output.print(generateTemp(fm, fon.getDest())+" = (");
+ if (fon.getLeft().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
+ output.print("(void *)");
+ if (dc.getNeedLeftSrcTrans(currlb, fon))
+ output.print("("+generateTemp(fm, fon.getLeft())+"!=NULL?"+generateTemp(fm, fon.getLeft())+"->"+oidstr+":NULL)");
+ else
+ output.print(generateTemp(fm, fon.getLeft()));
+ output.print(")"+fon.getOp().toString()+"(");
+ if (fon.getRight().getType().isPtr()&&(fon.getOp().getOp()==Operation.EQUAL||fon.getOp().getOp()==Operation.NOTEQUAL))
+ output.print("(void *)");
+ if (dc.getNeedRightSrcTrans(currlb, fon))
+ output.println("("+generateTemp(fm, fon.getRight())+"!=NULL?"+generateTemp(fm, fon.getRight())+"->"+oidstr+":NULL));");
+ else
+ output.println(generateTemp(fm,fon.getRight())+");");
} else
- output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+fon.getOp().toString()+generateTemp(fm,fon.getRight())+";");
+ output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+fon.getOp().toString()+generateTemp(fm,fon.getRight())+";");
} else if (fon.getOp().getOp()==Operation.ASSIGN)
output.println(generateTemp(fm, fon.getDest())+" = "+generateTemp(fm, fon.getLeft())+";");
else if (fon.getOp().getOp()==Operation.UNARYPLUS)
output.println(generateTemp(fm, fln.getDst())+"=0;");
else if (fln.getType().getSymbol().equals(TypeUtil.StringClass)) {
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
- if (state.DSM && locality.getAtomic(currlb).get(fln).intValue()>0) {
- //Stash pointer in case of GC
- String revertptr=generateTemp(fm, reverttable.get(currlb));
- output.println(revertptr+"=revertlist;");
- }
- output.println(generateTemp(fm, fln.getDst())+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
- if (state.DSM && locality.getAtomic(currlb).get(fln).intValue()>0) {
- //Stash pointer in case of GC
- String revertptr=generateTemp(fm, reverttable.get(currlb));
- output.println("revertlist="+revertptr+";");
- }
+ if (state.DSM && locality.getAtomic(currlb).get(fln).intValue()>0) {
+ //Stash pointer in case of GC
+ String revertptr=generateTemp(fm, reverttable.get(currlb));
+ output.println(revertptr+"=revertlist;");
+ }
+ output.println(generateTemp(fm, fln.getDst())+"=NewString("+localsprefixaddr+", \""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
+ if (state.DSM && locality.getAtomic(currlb).get(fln).intValue()>0) {
+ //Stash pointer in case of GC
+ String revertptr=generateTemp(fm, reverttable.get(currlb));
+ output.println("revertlist="+revertptr+";");
+ }
} else {
- output.println(generateTemp(fm, fln.getDst())+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
+ output.println(generateTemp(fm, fln.getDst())+"=NewString(\""+FlatLiteralNode.escapeString((String)fln.getValue())+"\","+((String)fln.getValue()).length()+");");
}
} else if (fln.getType().isBoolean()) {
if (((Boolean)fln.getValue()).booleanValue())
- output.println(generateTemp(fm, fln.getDst())+"=1;");
+ output.println(generateTemp(fm, fln.getDst())+"=1;");
else
- output.println(generateTemp(fm, fln.getDst())+"=0;");
+ output.println(generateTemp(fm, fln.getDst())+"=0;");
} else if (fln.getType().isChar()) {
String st=FlatLiteralNode.escapeString(fln.getValue().toString());
output.println(generateTemp(fm, fln.getDst())+"='"+st+"';");
if (md!=null&&md.getReturnType()!=null) {
if (state.MGC && md.getReturnType().isClass() && md.getReturnType().getClassDesc().isEnum()) {
- output.print("int ");
+ output.print("int ");
} else if (md.getReturnType().isClass()||md.getReturnType().isArray())
- output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
+ output.print("struct " + md.getReturnType().getSafeSymbol()+" * ");
else
- output.print(md.getReturnType().getSafeSymbol()+" ");
+ output.print(md.getReturnType().getSafeSymbol()+" ");
} else
//catch the constructor case
output.print("void ");
boolean printcomma=false;
if ((GENERATEPRECISEGC) || (this.state.MULTICOREGC)) {
if (md!=null) {
- output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
+ output.print("struct "+cn.getSafeSymbol()+lb.getSignature()+md.getSafeSymbol()+"_"+md.getSafeMethodDescriptor()+"_params * "+paramsprefix);
} else
- output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
+ output.print("struct "+task.getSafeSymbol()+"_params * "+paramsprefix);
printcomma=true;
}
if (md!=null) {
/* Method */
for(int i=0; i<objectparams.numPrimitives(); i++) {
- TempDescriptor temp=objectparams.getPrimitive(i);
- if (printcomma)
- output.print(", ");
- printcomma=true;
- if(state.MGC && temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
- output.print("int " + temp.getSafeSymbol());
- } else if (temp.getType().isClass()||temp.getType().isArray())
- output.print("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol());
- else
- output.print(temp.getType().getSafeSymbol()+" "+temp.getSafeSymbol());
+ TempDescriptor temp=objectparams.getPrimitive(i);
+ if (printcomma)
+ output.print(", ");
+ printcomma=true;
+ if(state.MGC && temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
+ output.print("int " + temp.getSafeSymbol());
+ } else 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 && !this.state.MULTICOREGC) {
output.println("void * parameterarray[]) {");
/* Unpack variables */
for(int i=0; i<objectparams.numPrimitives(); i++) {
- TempDescriptor temp=objectparams.getPrimitive(i);
- if(state.MGC && temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
- output.print("int " + temp.getSafeSymbol() + "=parameterarray["+i+"];");
- } else {
- output.println("struct "+temp.getType().getSafeSymbol()+" * "+temp.getSafeSymbol()+"=parameterarray["+i+"];");
- }
+ TempDescriptor temp=objectparams.getPrimitive(i);
+ if(state.MGC && temp.getType().isClass() && temp.getType().getClassDesc().isEnum()) {
+ output.print("int " + temp.getSafeSymbol() + "=parameterarray["+i+"];");
+ } else {
+ 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+"];");
+ 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();
+ maxtaskparams=objectparams.numPrimitives()+fm.numTags();
} else output.println(") {");
}
}
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);
- }
+ 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);
+ }
}
/* Flatten Vector of Flag Effects */
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());
+ 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());
+ TagEffect te=fes.getTagEffect(j);
+ TempDescriptor tagtemp=getTempforVar(te.getTag());
- ffan.addTagAction(flagtemp, te.getTag().getTag(), tagtemp, te.getStatus());
+ ffan.addTagAction(flagtemp, te.getTag().getTag(), tagtemp, te.getStatus());
}
}
}
TempDescriptor tmp=TempDescriptor.tempFactory("rettmp",currmd.getReturnType());
Object o=null;
if (currmd.getReturnType().isPtr()) {
- o=null;
+ o=null;
} else if (currmd.getReturnType().isByte()) {
- o=new Byte((byte)0);
+ o=new Byte((byte)0);
} else if (currmd.getReturnType().isShort()) {
- o=new Short((short)0);
+ o=new Short((short)0);
} else if (currmd.getReturnType().isChar()) {
- o=new Character('\0');
+ o=new Character('\0');
} else if (currmd.getReturnType().isInt()) {
- o=new Integer(0);
+ o=new Integer(0);
} else if (currmd.getReturnType().isLong()) {
- o=new Long(0);
+ o=new Long(0);
} else if (currmd.getReturnType().isBoolean()) {
- o=new Boolean(false);
+ o=new Boolean(false);
} else if (currmd.getReturnType().isFloat()) {
- o=new Float(0.0);
+ o=new Float(0.0);
} else if (currmd.getReturnType().isDouble()) {
- o=new Double(0.0);
+ o=new Double(0.0);
}
if (state.getMethodFlat(md)==null) {
FlatMethod fm=new FlatMethod(md, fe);
if (!md.isStatic())
- fm.addParameterTemp(getTempforParam(md.getThis()));
+ fm.addParameterTemp(getTempforParam(md.getThis()));
for(int i=0; i<md.numParameters(); i++) {
- fm.addParameterTemp(getTempforParam(md.getParameter(i)));
+ fm.addParameterTemp(getTempforParam(md.getParameter(i)));
}
state.addFlatCode(md,fm);
}
if ((state.THREAD||state.MGC)&&currmd.getModifiers().isSynchronized()) {
TempDescriptor thistd = null;
if(currmd.getModifiers().isStatic()) {
- // need to lock the Class object
- thistd=new TempDescriptor("classobj", cn);
+ // need to lock the Class object
+ thistd=new TempDescriptor("classobj", cn);
} else {
- // lock this object
- thistd=getTempforVar(currmd.getThis());
+ // lock this object
+ thistd=getTempforVar(currmd.getThis());
}
if(!this.lockStack.isEmpty()) {
- throw new Error("The lock stack for synchronized blocks/methods is not empty!");
+ throw new Error("The lock stack for synchronized blocks/methods is not empty!");
}
this.lockStack.push(thistd);
}
FlatNode end = null;
{
- if (lockStack.size()!=1) {
- throw new Error("TOO MANY THINGS ON LOCKSTACK");
- }
- TempDescriptor thistd = this.lockStack.elementAt(0);
- FlatCall fc = new FlatCall(memd, null, thistd, new TempDescriptor[0]);
- fc.setNumLine(bn.getNumLine());
- first = end = fc;
+ if (lockStack.size()!=1) {
+ throw new Error("TOO MANY THINGS ON LOCKSTACK");
+ }
+ TempDescriptor thistd = this.lockStack.elementAt(0);
+ FlatCall fc = new FlatCall(memd, null, thistd, new TempDescriptor[0]);
+ fc.setNumLine(bn.getNumLine());
+ first = end = fc;
}
end.addNext(fn);
fn=first;
end = np.getEnd();
if (np.getEnd()!=null&&np.getEnd().kind()!=FKind.FlatReturnNode) {
- MethodDescriptor memdex=(MethodDescriptor)typeutil.getClass("Object").getMethodTable().get("MonitorExit");
- while(!this.lockStack.isEmpty()) {
- TempDescriptor thistd = this.lockStack.pop();
- FlatCall fcunlock = new FlatCall(memdex, null, thistd, new TempDescriptor[0]);
- fcunlock.setNumLine(bn.getNumLine());
- end.addNext(fcunlock);
- end = fcunlock;
- }
- FlatNode rnflat=spliceReturn(end);
- rnflat.addNext(fe);
+ MethodDescriptor memdex=(MethodDescriptor)typeutil.getClass("Object").getMethodTable().get("MonitorExit");
+ while(!this.lockStack.isEmpty()) {
+ TempDescriptor thistd = this.lockStack.pop();
+ FlatCall fcunlock = new FlatCall(memdex, null, thistd, new TempDescriptor[0]);
+ fcunlock.setNumLine(bn.getNumLine());
+ end.addNext(fcunlock);
+ end = fcunlock;
+ }
+ FlatNode rnflat=spliceReturn(end);
+ rnflat.addNext(fe);
} else {
- this.lockStack.clear();
+ this.lockStack.clear();
}
} else if (state.DSM&&currmd.getModifiers().isAtomic()) {
curran.addNext(fn);
fn=curran;
if (np.getEnd()!=null&&np.getEnd().kind()!=FKind.FlatReturnNode) {
- FlatAtomicExitNode aen=new FlatAtomicExitNode(curran);
- np.getEnd().addNext(aen);
- FlatNode rnflat=spliceReturn(aen);
- rnflat.addNext(fe);
+ FlatAtomicExitNode aen=new FlatAtomicExitNode(curran);
+ np.getEnd().addNext(aen);
+ FlatNode rnflat=spliceReturn(aen);
+ rnflat.addNext(fe);
}
} else if (np.getEnd()!=null&&np.getEnd().kind()!=FKind.FlatReturnNode) {
FlatNode rnflat=null;
if( spliceInImplicitMain ) {
- np.getEnd().addNext(spliceExit);
- rnflat=spliceReturn(spliceExit);
+ np.getEnd().addNext(spliceExit);
+ rnflat=spliceReturn(spliceExit);
} else {
- rnflat=spliceReturn(np.getEnd());
+ rnflat=spliceReturn(np.getEnd());
}
rnflat.addNext(fe);
} else if (np.getEnd()!=null) {
if( spliceInImplicitMain ) {
- FlatReturnNode rnflat=(FlatReturnNode)np.getEnd();
- np.getEnd().addNext(spliceExit);
- spliceExit.addNext(fe);
+ FlatReturnNode rnflat=(FlatReturnNode)np.getEnd();
+ np.getEnd().addNext(spliceExit);
+ spliceExit.addNext(fe);
}
}
if( spliceInImplicitMain ) {
FlatNode np_begin=np.getBegin();
FlatNode np_end=np.getEnd();
if(bn.getLabel()!=null) {
- // interim implementation to have the labeled statement
- state.fn2labelMap.put(np_begin, bn.getLabel());
+ // interim implementation to have the labeled statement
+ state.fn2labelMap.put(np_begin, bn.getLabel());
}
if (begin==null) {
- begin=np_begin;
+ begin=np_begin;
}
if (end==null) {
- end=np_end;
+ end=np_end;
} else {
- end.addNext(np_begin);
- if (np_end==null) {
- return new NodePair(begin, null);
- } else
- end=np_end;
+ end.addNext(np_begin);
+ if (np_end==null) {
+ return new NodePair(begin, null);
+ } else
+ end=np_end;
}
}
if (begin==null) {
//handle wrapper fields
ClassDescriptor cd=td.getClassDesc();
for(Iterator fieldit=cd.getFields(); fieldit.hasNext(); ) {
- FieldDescriptor fd=(FieldDescriptor)fieldit.next();
- if (fd.getType().iswrapper()) {
- TempDescriptor wrap_tmp=TempDescriptor.tempFactory("wrapper_obj",fd.getType());
- FlatNode fnwrapper=new FlatNew(fd.getType(), wrap_tmp, con.isGlobal());
- fnwrapper.setNumLine(con.getNumLine());
- FlatSetFieldNode fsfn=new FlatSetFieldNode(out_temp, fd, wrap_tmp);
- fsfn.setNumLine(con.getNumLine());
- last.addNext(fnwrapper);
- fnwrapper.addNext(fsfn);
- last=fsfn;
- }
+ FieldDescriptor fd=(FieldDescriptor)fieldit.next();
+ if (fd.getType().iswrapper()) {
+ TempDescriptor wrap_tmp=TempDescriptor.tempFactory("wrapper_obj",fd.getType());
+ FlatNode fnwrapper=new FlatNew(fd.getType(), wrap_tmp, con.isGlobal());
+ fnwrapper.setNumLine(con.getNumLine());
+ FlatSetFieldNode fsfn=new FlatSetFieldNode(out_temp, fd, wrap_tmp);
+ fsfn.setNumLine(con.getNumLine());
+ last.addNext(fnwrapper);
+ fnwrapper.addNext(fsfn);
+ last=fsfn;
+ }
}
TempDescriptor[] temps=new TempDescriptor[con.numArgs()];
// 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();
+ 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
last.addNext(fc);
last=fc;
if (td.getClassDesc().hasFlags()) {
- // if (con.getFlagEffects()!=null) {
- FlatFlagActionNode ffan=new FlatFlagActionNode(FlatFlagActionNode.NEWOBJECT);
- ffan.setNumLine(con.getNumLine());
- 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;
+ // if (con.getFlagEffects()!=null) {
+ FlatFlagActionNode ffan=new FlatFlagActionNode(FlatFlagActionNode.NEWOBJECT);
+ ffan.setNumLine(con.getNumLine());
+ 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 {
if(con.getArrayInitializer() == null) {
- 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(), con.getDisjointId());
- 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 if (td.isArray()&&td.dereference().iswrapper()) {
- NodePair np=generateNewArrayLoop(temps, td.dereference(), out_temp, 0, con.isGlobal());
- fn.addNext(np.getBegin());
- return new NodePair(first,np.getEnd());
- } else
- return new NodePair(first, fn);
+ FlatNode first=null;
+ FlatNode last=null;
+ TempDescriptor[] temps=new TempDescriptor[con.numArgs()];
+ for (int i=0; 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(), con.getDisjointId());
+ 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 if (td.isArray()&&td.dereference().iswrapper()) {
+ NodePair np=generateNewArrayLoop(temps, td.dereference(), out_temp, 0, con.isGlobal());
+ fn.addNext(np.getBegin());
+ return new NodePair(first,np.getEnd());
+ } else
+ return new NodePair(first, fn);
} else {
- // array creation with initializers
- return flattenArrayInitializerNode(con.getArrayInitializer(), out_temp);
+ // array creation with initializers
+ return flattenArrayInitializerNode(con.getArrayInitializer(), out_temp);
}
}
}
if (min.getExpression()!=null) {
TypeDescriptor mtd = min.getExpression().getType();
if(mtd.isClass() && mtd.getClassDesc().isEnum()) {
- mtd = new TypeDescriptor(TypeDescriptor.INT);
+ mtd = new TypeDescriptor(TypeDescriptor.INT);
}
thisarg=TempDescriptor.tempFactory("thisarg", mtd);
NodePair np=flattenExpressionNode(min.getExpression(),thisarg);
ExpressionNode en=min.getArg(i);
TypeDescriptor etd = en.getType();
if(etd.isClass() && etd.getClassDesc().isEnum()) {
- etd = new TypeDescriptor(TypeDescriptor.INT);
+ etd = new TypeDescriptor(TypeDescriptor.INT);
}
TempDescriptor td=TempDescriptor.tempFactory("arg", etd);
temps[i]=td;
NodePair np=flattenExpressionNode(en, td);
if (first==null)
- first=np.getBegin();
+ first=np.getBegin();
else
- last.addNext(np.getBegin());
+ last.addNext(np.getBegin());
last=np.getEnd();
}
//Get src value
if (an.getSrc()!=null) {
if(an.getSrc().getEval() != null) {
- FlatLiteralNode fln=new FlatLiteralNode(an.getSrc().getType(), an.getSrc().getEval().longValue(), src_tmp);
- fln.setNumLine(an.getSrc().getNumLine());
- first = last =fln;
+ FlatLiteralNode fln=new FlatLiteralNode(an.getSrc().getType(), an.getSrc().getEval().longValue(), src_tmp);
+ fln.setNumLine(an.getSrc().getNumLine());
+ first = last =fln;
} else {
- NodePair np_src=flattenExpressionNode(an.getSrc(),src_tmp);
- first=np_src.getBegin();
- last=np_src.getEnd();
+ NodePair np_src=flattenExpressionNode(an.getSrc(),src_tmp);
+ first=np_src.getBegin();
+ last=np_src.getEnd();
}
} else if (!pre) {
FlatLiteralNode fln=new FlatLiteralNode(new TypeDescriptor(TypeDescriptor.INT),new Integer(1),src_tmp);
TempDescriptor dst_tmp=null;
NodePair np_baseexp=null;
if(en.getType().isClassNameRef()) {
- // static field dereference with class name
- dst_tmp = new TempDescriptor(en.getType().getClassDesc().getSymbol(), en.getType());
- FlatNop nop=new FlatNop();
- np_baseexp = new NodePair(nop,nop);
+ // static field dereference with class name
+ dst_tmp = new TempDescriptor(en.getType().getClassDesc().getSymbol(), en.getType());
+ FlatNop nop=new FlatNop();
+ np_baseexp = new NodePair(nop,nop);
} else {
- dst_tmp=TempDescriptor.tempFactory("dst",en.getType());
- np_baseexp=flattenExpressionNode(en, dst_tmp);
+ dst_tmp=TempDescriptor.tempFactory("dst",en.getType());
+ np_baseexp=flattenExpressionNode(en, dst_tmp);
}
if (first==null)
- first=np_baseexp.getBegin();
+ first=np_baseexp.getBegin();
else
- last.addNext(np_baseexp.getBegin());
+ last.addNext(np_baseexp.getBegin());
last=np_baseexp.getEnd();
//See if we need to perform an operation
if (base!=null) {
- //If it is a preinc we need to store the initial value
- TempDescriptor src_tmp2=pre?TempDescriptor.tempFactory("src",an.getDest().getType()):out_temp;
- TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3_",an.getDest().getType());
- FlatFieldNode ffn=new FlatFieldNode(fan.getField(), dst_tmp, src_tmp2);
- ffn.setNumLine(an.getNumLine());
- last.addNext(ffn);
- last=ffn;
-
- if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) {
- ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
- MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)});
- FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp});
- fc.setNumLine(an.getNumLine());
- src_tmp=tmp;
- last.addNext(fc);
- last=fc;
- } else {
- FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base);
- fon.setNumLine(an.getNumLine());
- src_tmp=tmp;
- last.addNext(fon);
- last=fon;
- }
+ //If it is a preinc we need to store the initial value
+ TempDescriptor src_tmp2=pre?TempDescriptor.tempFactory("src",an.getDest().getType()):out_temp;
+ TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3_",an.getDest().getType());
+ FlatFieldNode ffn=new FlatFieldNode(fan.getField(), dst_tmp, src_tmp2);
+ ffn.setNumLine(an.getNumLine());
+ last.addNext(ffn);
+ last=ffn;
+
+ if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) {
+ ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
+ MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)});
+ FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp});
+ fc.setNumLine(an.getNumLine());
+ src_tmp=tmp;
+ last.addNext(fc);
+ last=fc;
+ } else {
+ FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base);
+ fon.setNumLine(an.getNumLine());
+ src_tmp=tmp;
+ last.addNext(fon);
+ last=fon;
+ }
}
FlatSetFieldNode fsfn=new FlatSetFieldNode(dst_tmp, fan.getField(), src_tmp);
last.addNext(fsfn);
last=fsfn;
if (pre) {
- FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN));
- fon2.setNumLine(an.getNumLine());
- fsfn.addNext(fon2);
- last=fon2;
+ FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN));
+ fon2.setNumLine(an.getNumLine());
+ fsfn.addNext(fon2);
+ last=fon2;
}
return new NodePair(first, last);
} else if (an.getDest().kind()==Kind.ArrayAccessNode) {
NodePair np_baseexp=flattenExpressionNode(en, dst_tmp);
NodePair np_indexexp=flattenExpressionNode(enindex, index_tmp);
if (first==null)
- first=np_baseexp.getBegin();
+ first=np_baseexp.getBegin();
else
- last.addNext(np_baseexp.getBegin());
+ last.addNext(np_baseexp.getBegin());
np_baseexp.getEnd().addNext(np_indexexp.getBegin());
last=np_indexexp.getEnd();
//See if we need to perform an operation
if (base!=null) {
- //If it is a preinc we need to store the initial value
- TempDescriptor src_tmp2=pre?TempDescriptor.tempFactory("src",an.getDest().getType()):out_temp;
- TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3_",an.getDest().getType());
-
- if (aan.iswrapper()) {
- TypeDescriptor arrayeltype=aan.getExpression().getType().dereference();
- TempDescriptor src_tmp3=TempDescriptor.tempFactory("src3",arrayeltype);
- FlatElementNode fen=new FlatElementNode(dst_tmp, index_tmp, src_tmp3);
- fen.setNumLine(aan.getNumLine());
- FlatFieldNode ffn=new FlatFieldNode((FieldDescriptor)arrayeltype.getClassDesc().getFieldTable().get("value"),src_tmp3,src_tmp2);
- ffn.setNumLine(aan.getNumLine());
- last.addNext(fen);
- fen.addNext(ffn);
- last=ffn;
- } else {
- FlatElementNode fen=new FlatElementNode(dst_tmp, index_tmp, src_tmp2);
- fen.setNumLine(aan.getNumLine());
- last.addNext(fen);
- last=fen;
- }
- if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) {
- ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
- MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)});
- FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp});
- fc.setNumLine(an.getNumLine());
- src_tmp=tmp;
- last.addNext(fc);
- last=fc;
- } else {
- FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base);
- fon.setNumLine(an.getNumLine());
- src_tmp=tmp;
- last.addNext(fon);
- last=fon;
- }
+ //If it is a preinc we need to store the initial value
+ TempDescriptor src_tmp2=pre?TempDescriptor.tempFactory("src",an.getDest().getType()):out_temp;
+ TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3_",an.getDest().getType());
+
+ if (aan.iswrapper()) {
+ TypeDescriptor arrayeltype=aan.getExpression().getType().dereference();
+ TempDescriptor src_tmp3=TempDescriptor.tempFactory("src3",arrayeltype);
+ FlatElementNode fen=new FlatElementNode(dst_tmp, index_tmp, src_tmp3);
+ fen.setNumLine(aan.getNumLine());
+ FlatFieldNode ffn=new FlatFieldNode((FieldDescriptor)arrayeltype.getClassDesc().getFieldTable().get("value"),src_tmp3,src_tmp2);
+ ffn.setNumLine(aan.getNumLine());
+ last.addNext(fen);
+ fen.addNext(ffn);
+ last=ffn;
+ } else {
+ FlatElementNode fen=new FlatElementNode(dst_tmp, index_tmp, src_tmp2);
+ fen.setNumLine(aan.getNumLine());
+ last.addNext(fen);
+ last=fen;
+ }
+ if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) {
+ ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
+ MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)});
+ FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp});
+ fc.setNumLine(an.getNumLine());
+ src_tmp=tmp;
+ last.addNext(fc);
+ last=fc;
+ } else {
+ FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base);
+ fon.setNumLine(an.getNumLine());
+ src_tmp=tmp;
+ last.addNext(fon);
+ last=fon;
+ }
}
if (aan.iswrapper()) {
- TypeDescriptor arrayeltype=aan.getExpression().getType().dereference();
- TempDescriptor src_tmp3=TempDescriptor.tempFactory("src3",arrayeltype);
- FlatElementNode fen=new FlatElementNode(dst_tmp, index_tmp, src_tmp3);
- fen.setNumLine(aan.getNumLine());
- FlatSetFieldNode fsfn=new FlatSetFieldNode(src_tmp3,(FieldDescriptor)arrayeltype.getClassDesc().getFieldTable().get("value"),src_tmp);
- fsfn.setNumLine(aan.getExpression().getNumLine());
- last.addNext(fen);
- fen.addNext(fsfn);
- last=fsfn;
+ TypeDescriptor arrayeltype=aan.getExpression().getType().dereference();
+ TempDescriptor src_tmp3=TempDescriptor.tempFactory("src3",arrayeltype);
+ FlatElementNode fen=new FlatElementNode(dst_tmp, index_tmp, src_tmp3);
+ fen.setNumLine(aan.getNumLine());
+ FlatSetFieldNode fsfn=new FlatSetFieldNode(src_tmp3,(FieldDescriptor)arrayeltype.getClassDesc().getFieldTable().get("value"),src_tmp);
+ fsfn.setNumLine(aan.getExpression().getNumLine());
+ last.addNext(fen);
+ fen.addNext(fsfn);
+ last=fsfn;
} else {
- FlatSetElementNode fsen=new FlatSetElementNode(dst_tmp, index_tmp, src_tmp);
- fsen.setNumLine(aan.getNumLine());
- last.addNext(fsen);
- last=fsen;
+ FlatSetElementNode fsen=new FlatSetElementNode(dst_tmp, index_tmp, src_tmp);
+ fsen.setNumLine(aan.getNumLine());
+ last.addNext(fsen);
+ last=fsen;
}
if (pre) {
- FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN));
- fon2.setNumLine(an.getNumLine());
- last.addNext(fon2);
- last=fon2;
+ FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN));
+ fon2.setNumLine(an.getNumLine());
+ last.addNext(fon2);
+ last=fon2;
}
return new NodePair(first, last);
} else if (an.getDest().kind()==Kind.NameNode) {
if (nn.getExpression()!=null) {
- //It is a field
- FieldAccessNode fan=(FieldAccessNode)nn.getExpression();
- ExpressionNode en=fan.getExpression();
- TempDescriptor dst_tmp=null;
- NodePair np_baseexp=null;
- if(en.getType().isClassNameRef()) {
- // static field dereference with class name
- dst_tmp = new TempDescriptor(en.getType().getClassDesc().getSymbol(), en.getType());
- FlatNop nop=new FlatNop();
- np_baseexp = new NodePair(nop,nop);
- } else {
- dst_tmp=TempDescriptor.tempFactory("dst",en.getType());
- np_baseexp=flattenExpressionNode(en, dst_tmp);
- }
- if (first==null)
- first=np_baseexp.getBegin();
- else
- last.addNext(np_baseexp.getBegin());
- last=np_baseexp.getEnd();
-
- //See if we need to perform an operation
- if (base!=null) {
- //If it is a preinc we need to store the initial value
- TempDescriptor src_tmp2=pre?TempDescriptor.tempFactory("src",an.getDest().getType()):out_temp;
- TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3_",an.getDest().getType());
-
- FlatFieldNode ffn=new FlatFieldNode(fan.getField(), dst_tmp, src_tmp2);
- ffn.setNumLine(an.getNumLine());
- last.addNext(ffn);
- last=ffn;
-
-
- if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) {
- ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
- MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)});
- FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp});
- fc.setNumLine(an.getNumLine());
- src_tmp=tmp;
- last.addNext(fc);
- last=fc;
- } else {
- FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base);
- fon.setNumLine(an.getNumLine());
- src_tmp=tmp;
- last.addNext(fon);
- last=fon;
- }
- }
-
-
- FlatSetFieldNode fsfn=new FlatSetFieldNode(dst_tmp, fan.getField(), src_tmp);
- fsfn.setNumLine(en.getNumLine());
- last.addNext(fsfn);
- last=fsfn;
- if (pre) {
- FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN));
- fon2.setNumLine(an.getNumLine());
- fsfn.addNext(fon2);
- last=fon2;
- }
- return new NodePair(first, last);
+ //It is a field
+ FieldAccessNode fan=(FieldAccessNode)nn.getExpression();
+ ExpressionNode en=fan.getExpression();
+ TempDescriptor dst_tmp=null;
+ NodePair np_baseexp=null;
+ if(en.getType().isClassNameRef()) {
+ // static field dereference with class name
+ dst_tmp = new TempDescriptor(en.getType().getClassDesc().getSymbol(), en.getType());
+ FlatNop nop=new FlatNop();
+ np_baseexp = new NodePair(nop,nop);
+ } else {
+ dst_tmp=TempDescriptor.tempFactory("dst",en.getType());
+ np_baseexp=flattenExpressionNode(en, dst_tmp);
+ }
+ if (first==null)
+ first=np_baseexp.getBegin();
+ else
+ last.addNext(np_baseexp.getBegin());
+ last=np_baseexp.getEnd();
+
+ //See if we need to perform an operation
+ if (base!=null) {
+ //If it is a preinc we need to store the initial value
+ TempDescriptor src_tmp2=pre?TempDescriptor.tempFactory("src",an.getDest().getType()):out_temp;
+ TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3_",an.getDest().getType());
+
+ FlatFieldNode ffn=new FlatFieldNode(fan.getField(), dst_tmp, src_tmp2);
+ ffn.setNumLine(an.getNumLine());
+ last.addNext(ffn);
+ last=ffn;
+
+
+ if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) {
+ ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
+ MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)});
+ FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp});
+ fc.setNumLine(an.getNumLine());
+ src_tmp=tmp;
+ last.addNext(fc);
+ last=fc;
+ } else {
+ FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base);
+ fon.setNumLine(an.getNumLine());
+ src_tmp=tmp;
+ last.addNext(fon);
+ last=fon;
+ }
+ }
+
+
+ FlatSetFieldNode fsfn=new FlatSetFieldNode(dst_tmp, fan.getField(), src_tmp);
+ fsfn.setNumLine(en.getNumLine());
+ last.addNext(fsfn);
+ last=fsfn;
+ if (pre) {
+ FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN));
+ fon2.setNumLine(an.getNumLine());
+ fsfn.addNext(fon2);
+ last=fon2;
+ }
+ return new NodePair(first, last);
} else {
- if (nn.getField()!=null) {
- //It is a field
- //Get src value
-
- //See if we need to perform an operation
- if (base!=null) {
- //If it is a preinc we need to store the initial value
- TempDescriptor src_tmp2=pre?TempDescriptor.tempFactory("src",an.getDest().getType()):out_temp;
- TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3_",an.getDest().getType());
-
- TempDescriptor ftmp= null;
- if((nn.getClassDesc() != null)) {
- // this is a static field
- ftmp = new TempDescriptor(nn.getClassDesc().getSymbol(), nn.getClassType());
-
- } else {
- ftmp=getTempforVar(nn.getVar());
- }
- FlatFieldNode ffn=new FlatFieldNode(nn.getField(), ftmp, src_tmp2);
- ffn.setNumLine(an.getNumLine());
-
- if (first==null)
- first=ffn;
- else {
- last.addNext(ffn);
- }
- last=ffn;
-
-
- if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) {
- ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
- MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)});
- FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp});
- fc.setNumLine(an.getNumLine());
- src_tmp=tmp;
- last.addNext(fc);
- last=fc;
- } else {
- FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base);
- fon.setNumLine(an.getNumLine());
- src_tmp=tmp;
- last.addNext(fon);
- last=fon;
- }
- }
-
- FlatSetFieldNode fsfn=null;
- if(nn.getClassDesc()!=null) {
- // this is a static field access inside of a static block
- fsfn=new FlatSetFieldNode(new TempDescriptor("sfsb", nn.getClassType()), nn.getField(), src_tmp);
- fsfn.setNumLine(nn.getNumLine());
- } else {
- fsfn=new FlatSetFieldNode(getTempforVar(nn.getVar()), nn.getField(), src_tmp);
- fsfn.setNumLine(nn.getNumLine());
- }
- if (first==null) {
- first=fsfn;
- } else {
- last.addNext(fsfn);
- }
- last=fsfn;
- if (pre) {
- FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN));
- fon2.setNumLine(an.getNumLine());
- fsfn.addNext(fon2);
- last=fon2;
- }
- return new NodePair(first, last);
- } else {
- //It is a variable
- //See if we need to perform an operation
-
- if (base!=null) {
- //If it is a preinc we need to store the initial value
- TempDescriptor src_tmp2=getTempforVar(nn.getVar());
- TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3_",an.getDest().getType());
- if (!pre) {
- FlatOpNode fon=new FlatOpNode(out_temp, src_tmp2, null, new Operation(Operation.ASSIGN));
- fon.setNumLine(an.getNumLine());
- if (first==null)
- first=fon;
- else
- last.addNext(fon);
- last=fon;
- }
-
-
- if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) {
- ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
- MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)});
- FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp});
- fc.setNumLine(an.getNumLine());
- if (first==null)
- first=fc;
- else
- last.addNext(fc);
- src_tmp=tmp;
- last=fc;
- } else {
- FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base);
- fon.setNumLine(an.getNumLine());
- if (first==null)
- first=fon;
- else
- last.addNext(fon);
- src_tmp=tmp;
- last=fon;
- }
- }
-
- FlatOpNode fon=new FlatOpNode(getTempforVar(nn.getVar()), src_tmp, null, new Operation(Operation.ASSIGN));
- fon.setNumLine(an.getNumLine());
-
- last.addNext(fon);
- last=fon;
- if (pre) {
- FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN));
- fon2.setNumLine(an.getNumLine());
- fon.addNext(fon2);
- last=fon2;
- }
- return new NodePair(first, last);
- } //end of else
+ if (nn.getField()!=null) {
+ //It is a field
+ //Get src value
+
+ //See if we need to perform an operation
+ if (base!=null) {
+ //If it is a preinc we need to store the initial value
+ TempDescriptor src_tmp2=pre?TempDescriptor.tempFactory("src",an.getDest().getType()):out_temp;
+ TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3_",an.getDest().getType());
+
+ TempDescriptor ftmp= null;
+ if((nn.getClassDesc() != null)) {
+ // this is a static field
+ ftmp = new TempDescriptor(nn.getClassDesc().getSymbol(), nn.getClassType());
+
+ } else {
+ ftmp=getTempforVar(nn.getVar());
+ }
+ FlatFieldNode ffn=new FlatFieldNode(nn.getField(), ftmp, src_tmp2);
+ ffn.setNumLine(an.getNumLine());
+
+ if (first==null)
+ first=ffn;
+ else {
+ last.addNext(ffn);
+ }
+ last=ffn;
+
+
+ if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) {
+ ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
+ MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)});
+ FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp});
+ fc.setNumLine(an.getNumLine());
+ src_tmp=tmp;
+ last.addNext(fc);
+ last=fc;
+ } else {
+ FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base);
+ fon.setNumLine(an.getNumLine());
+ src_tmp=tmp;
+ last.addNext(fon);
+ last=fon;
+ }
+ }
+
+ FlatSetFieldNode fsfn=null;
+ if(nn.getClassDesc()!=null) {
+ // this is a static field access inside of a static block
+ fsfn=new FlatSetFieldNode(new TempDescriptor("sfsb", nn.getClassType()), nn.getField(), src_tmp);
+ fsfn.setNumLine(nn.getNumLine());
+ } else {
+ fsfn=new FlatSetFieldNode(getTempforVar(nn.getVar()), nn.getField(), src_tmp);
+ fsfn.setNumLine(nn.getNumLine());
+ }
+ if (first==null) {
+ first=fsfn;
+ } else {
+ last.addNext(fsfn);
+ }
+ last=fsfn;
+ if (pre) {
+ FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN));
+ fon2.setNumLine(an.getNumLine());
+ fsfn.addNext(fon2);
+ last=fon2;
+ }
+ return new NodePair(first, last);
+ } else {
+ //It is a variable
+ //See if we need to perform an operation
+
+ if (base!=null) {
+ //If it is a preinc we need to store the initial value
+ TempDescriptor src_tmp2=getTempforVar(nn.getVar());
+ TempDescriptor tmp=TempDescriptor.tempFactory("srctmp3_",an.getDest().getType());
+ if (!pre) {
+ FlatOpNode fon=new FlatOpNode(out_temp, src_tmp2, null, new Operation(Operation.ASSIGN));
+ fon.setNumLine(an.getNumLine());
+ if (first==null)
+ first=fon;
+ else
+ last.addNext(fon);
+ last=fon;
+ }
+
+
+ if (base.getOp()==Operation.ADD&&an.getDest().getType().isString()) {
+ ClassDescriptor stringcd=typeutil.getClass(TypeUtil.StringClass);
+ MethodDescriptor concatmd=typeutil.getMethod(stringcd, "concat2", new TypeDescriptor[] {new TypeDescriptor(stringcd), new TypeDescriptor(stringcd)});
+ FlatCall fc=new FlatCall(concatmd, tmp, null, new TempDescriptor[] {src_tmp2, src_tmp});
+ fc.setNumLine(an.getNumLine());
+ if (first==null)
+ first=fc;
+ else
+ last.addNext(fc);
+ src_tmp=tmp;
+ last=fc;
+ } else {
+ FlatOpNode fon=new FlatOpNode(tmp, src_tmp2, src_tmp, base);
+ fon.setNumLine(an.getNumLine());
+ if (first==null)
+ first=fon;
+ else
+ last.addNext(fon);
+ src_tmp=tmp;
+ last=fon;
+ }
+ }
+
+ FlatOpNode fon=new FlatOpNode(getTempforVar(nn.getVar()), src_tmp, null, new Operation(Operation.ASSIGN));
+ fon.setNumLine(an.getNumLine());
+
+ last.addNext(fon);
+ last=fon;
+ if (pre) {
+ FlatOpNode fon2=new FlatOpNode(out_temp, src_tmp, null, new Operation(Operation.ASSIGN));
+ fon2.setNumLine(an.getNumLine());
+ fon.addNext(fon2);
+ last=fon2;
+ }
+ return new NodePair(first, last);
+ } //end of else
}
}
} else if (nn.getField()!=null) {
TempDescriptor tmp= null;
if((nn.getClassDesc() != null)) {
- // this is a static field
- tmp = new TempDescriptor(nn.getClassDesc().getSymbol(), nn.getClassType());
+ // this is a static field
+ tmp = new TempDescriptor(nn.getClassDesc().getSymbol(), nn.getClassType());
} else {
- tmp=getTempforVar(nn.getVar());
+ tmp=getTempforVar(nn.getVar());
}
FlatFieldNode ffn=new FlatFieldNode(nn.getField(), tmp, out_temp);
ffn.setNumLine(nn.getNumLine());
} else {
TempDescriptor tmp=getTempforVar(nn.isTag()?nn.getTagVar():nn.getVar());
if (nn.isTag()) {
- //propagate tag
- out_temp.setTag(tmp.getTag());
+ //propagate tag
+ out_temp.setTag(tmp.getTag());
}
FlatOpNode fon=new FlatOpNode(out_temp, tmp, null, new Operation(Operation.ASSIGN));
fon.setNumLine(nn.getNumLine());
return (TempDescriptor)temptovar.get(d);
else {
if (d instanceof VarDescriptor) {
- VarDescriptor vd=(VarDescriptor)d;
- TempDescriptor td=TempDescriptor.paramtempFactory(vd.getName(),vd.getType());
- temptovar.put(vd,td);
- return td;
+ VarDescriptor vd=(VarDescriptor)d;
+ TempDescriptor td=TempDescriptor.paramtempFactory(vd.getName(),vd.getType());
+ temptovar.put(vd,td);
+ return td;
} else if (d instanceof TagVarDescriptor) {
- TagVarDescriptor tvd=(TagVarDescriptor)d;
- TypeDescriptor tagtype=new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass));
- TempDescriptor td=TempDescriptor.paramtempFactory(tvd.getName(), tagtype, tvd.getTag());
- temptovar.put(tvd,td);
- return td;
+ TagVarDescriptor tvd=(TagVarDescriptor)d;
+ TypeDescriptor tagtype=new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass));
+ TempDescriptor td=TempDescriptor.paramtempFactory(tvd.getName(), tagtype, tvd.getTag());
+ temptovar.put(tvd,td);
+ return td;
} else throw new Error("Unreconized Descriptor");
}
}
return (TempDescriptor)temptovar.get(d);
else {
if (d instanceof VarDescriptor) {
- VarDescriptor vd=(VarDescriptor)d;
- TempDescriptor td=TempDescriptor.tempFactory(vd.getName(), vd.getType());
- temptovar.put(vd,td);
- return td;
+ VarDescriptor vd=(VarDescriptor)d;
+ TempDescriptor td=TempDescriptor.tempFactory(vd.getName(), vd.getType());
+ temptovar.put(vd,td);
+ return td;
} else if (d instanceof TagVarDescriptor) {
- TagVarDescriptor tvd=(TagVarDescriptor)d;
- //BUGFIX TAGTYPE - add next line, modify following
- //line to tag this new type descriptor, modify
- //TempDescriptor constructor & factory to set type
- //using this Type To test, use any program with tags
- TypeDescriptor tagtype=new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass));
- TempDescriptor td=TempDescriptor.tempFactory(tvd.getName(),tagtype, tvd.getTag());
- temptovar.put(tvd,td);
- return td;
+ TagVarDescriptor tvd=(TagVarDescriptor)d;
+ //BUGFIX TAGTYPE - add next line, modify following
+ //line to tag this new type descriptor, modify
+ //TempDescriptor constructor & factory to set type
+ //using this Type To test, use any program with tags
+ TypeDescriptor tagtype=new TypeDescriptor(typeutil.getClass(TypeUtil.TagClass));
+ TempDescriptor td=TempDescriptor.tempFactory(tvd.getName(),tagtype, tvd.getTag());
+ temptovar.put(tvd,td);
+ return td;
} else throw new Error("Unrecognized Descriptor");
}
}
FlatNode cond_begin = null;
NodePair prev_fnp = null;
for(int j = 0; j < slnv.size(); j++) {
- SwitchLabelNode sln = slnv.elementAt(j);
- NodePair left = null;
- NodePair false_np = null;
- if(sln.isDefault()) {
- left = body;
- } else {
- TempDescriptor cond_tmp=TempDescriptor.tempFactory("condition", new TypeDescriptor(TypeDescriptor.BOOLEAN));
- TempDescriptor temp_left=TempDescriptor.tempFactory("leftop", sln.getCondition().getType());
- Operation op=new Operation(Operation.EQUAL);
- left=flattenExpressionNode(sln.getCondition(), temp_left);
- FlatOpNode fon=new FlatOpNode(cond_tmp, temp_left, cond_temp, op);
- fon.setNumLine(sln.getNumLine());
- left.getEnd().addNext(fon);
-
- FlatCondBranch fcb=new FlatCondBranch(cond_tmp);
- fcb.setNumLine(bn.getNumLine());
- fcb.setTrueProb(State.TRUEPROB);
-
- FlatNop nop=new FlatNop();
- false_np=new NodePair(nop,nop);
-
- fon.addNext(fcb);
- fcb.addTrueNext(body.getBegin());
- fcb.addFalseNext(false_np.getBegin());
- }
- if((prev_fnp != null) && (prev_fnp.getEnd() != null)) {
- prev_fnp.getEnd().addNext(left.getBegin());
- }
- prev_fnp = false_np;
-
- if (begin==null) {
- begin = left.getBegin();
- }
- if(cond_begin == null) {
- cond_begin = left.getBegin();
- }
+ SwitchLabelNode sln = slnv.elementAt(j);
+ NodePair left = null;
+ NodePair false_np = null;
+ if(sln.isDefault()) {
+ left = body;
+ } else {
+ TempDescriptor cond_tmp=TempDescriptor.tempFactory("condition", new TypeDescriptor(TypeDescriptor.BOOLEAN));
+ TempDescriptor temp_left=TempDescriptor.tempFactory("leftop", sln.getCondition().getType());
+ Operation op=new Operation(Operation.EQUAL);
+ left=flattenExpressionNode(sln.getCondition(), temp_left);
+ FlatOpNode fon=new FlatOpNode(cond_tmp, temp_left, cond_temp, op);
+ fon.setNumLine(sln.getNumLine());
+ left.getEnd().addNext(fon);
+
+ FlatCondBranch fcb=new FlatCondBranch(cond_tmp);
+ fcb.setNumLine(bn.getNumLine());
+ fcb.setTrueProb(State.TRUEPROB);
+
+ FlatNop nop=new FlatNop();
+ false_np=new NodePair(nop,nop);
+
+ fon.addNext(fcb);
+ fcb.addTrueNext(body.getBegin());
+ fcb.addFalseNext(false_np.getBegin());
+ }
+ if((prev_fnp != null) && (prev_fnp.getEnd() != null)) {
+ prev_fnp.getEnd().addNext(left.getBegin());
+ }
+ prev_fnp = false_np;
+
+ if (begin==null) {
+ begin = left.getBegin();
+ }
+ if(cond_begin == null) {
+ cond_begin = left.getBegin();
+ }
}
if((prev_false_branch != null) && (prev_false_branch.getEnd() != null)) {
- prev_false_branch.getEnd().addNext(cond_begin);
+ prev_false_branch.getEnd().addNext(cond_begin);
}
prev_false_branch = prev_fnp;
if((prev_true_branch != null) && (prev_true_branch.getEnd() != null)) {
- prev_true_branch.getEnd().addNext(body.getBegin());
+ prev_true_branch.getEnd().addNext(body.getBegin());
}
prev_true_branch = body;
for(Iterator breakit=breakset.iterator(); breakit.hasNext(); ) {
- FlatNode fn=(FlatNode)breakit.next();
- breakit.remove();
- if (end==null)
- end=new FlatNop();
- fn.addNext(end);
+ FlatNode fn=(FlatNode)breakit.next();
+ breakit.remove();
+ if (end==null)
+ end=new FlatNop();
+ fn.addNext(end);
}
breakset=oldbs;
}
if((prev_true_branch != null) && (prev_true_branch.getEnd() != null)) {
if (end==null)
- end=new FlatNop();
+ end=new FlatNop();
prev_true_branch.getEnd().addNext(end);
}
if((prev_false_branch != null) && (prev_false_branch.getEnd() != null)) {
if (end==null)
- end=new FlatNop();
+ end=new FlatNop();
prev_false_branch.getEnd().addNext(end);
}
if(begin == null) {
initializer.getEnd().addNext(nop2);
nop2.addNext(condition.getBegin());
if (body.getEnd()!=null)
- body.getEnd().addNext(update.getBegin());
+ body.getEnd().addNext(update.getBegin());
update.getEnd().addNext(backedge);
backedge.addNext(condition.getBegin());
condition.getEnd().addNext(fcb);
fcb.addFalseNext(nopend);
fcb.addTrueNext(body.getBegin());
for(Iterator contit=continueset.iterator(); contit.hasNext(); ) {
- FlatNode fn=(FlatNode)contit.next();
- contit.remove();
- fn.addNext(update.getBegin());
+ FlatNode fn=(FlatNode)contit.next();
+ contit.remove();
+ fn.addNext(update.getBegin());
}
for(Iterator breakit=breakset.iterator(); breakit.hasNext(); ) {
- FlatNode fn=(FlatNode)breakit.next();
- breakit.remove();
- fn.addNext(nopend);
+ FlatNode fn=(FlatNode)breakit.next();
+ breakit.remove();
+ fn.addNext(nopend);
}
breakset=oldbs;
continueset=oldcs;
FlatBackEdge backedge=new FlatBackEdge();
if (body.getEnd()!=null)
- body.getEnd().addNext(backedge);
+ body.getEnd().addNext(backedge);
backedge.addNext(condition.getBegin());
condition.getEnd().addNext(fcb);
fcb.addTrueNext(body.getBegin());
for(Iterator contit=continueset.iterator(); contit.hasNext(); ) {
- FlatNode fn=(FlatNode)contit.next();
- contit.remove();
- fn.addNext(backedge);
+ FlatNode fn=(FlatNode)contit.next();
+ contit.remove();
+ fn.addNext(backedge);
}
for(Iterator breakit=breakset.iterator(); breakit.hasNext(); ) {
- FlatNode fn=(FlatNode)breakit.next();
- breakit.remove();
- fn.addNext(nopend);
+ FlatNode fn=(FlatNode)breakit.next();
+ breakit.remove();
+ fn.addNext(nopend);
}
breakset=oldbs;
continueset=oldcs;
FlatBackEdge backedge=new FlatBackEdge();
if (body.getEnd()!=null)
- body.getEnd().addNext(condition.getBegin());
+ body.getEnd().addNext(condition.getBegin());
condition.getEnd().addNext(fcb);
fcb.addFalseNext(nopend);
fcb.addTrueNext(backedge);
backedge.addNext(body.getBegin());
for(Iterator contit=continueset.iterator(); contit.hasNext(); ) {
- FlatNode fn=(FlatNode)contit.next();
- contit.remove();
- fn.addNext(condition.getBegin());
+ FlatNode fn=(FlatNode)contit.next();
+ contit.remove();
+ fn.addNext(condition.getBegin());
}
for(Iterator breakit=breakset.iterator(); breakit.hasNext(); ) {
- FlatNode fn=(FlatNode)breakit.next();
- breakit.remove();
- fn.addNext(nopend);
+ FlatNode fn=(FlatNode)breakit.next();
+ breakit.remove();
+ fn.addNext(nopend);
}
breakset=oldbs;
continueset=oldcs;
FlatNode end = null;
MethodDescriptor memdex=(MethodDescriptor)typeutil.getClass("Object").getMethodTable().get("MonitorExit");
for(int j = this.lockStack.size(); j > 0; j--) {
- TempDescriptor thistd = this.lockStack.elementAt(j-1);
- FlatCall fcunlock = new FlatCall(memdex, null, thistd, new TempDescriptor[0]);
- fcunlock.setNumLine(rntree.getNumLine());
- if(end != null) {
- end.addNext(fcunlock);
- }
- end = fcunlock;
+ TempDescriptor thistd = this.lockStack.elementAt(j-1);
+ FlatCall fcunlock = new FlatCall(memdex, null, thistd, new TempDescriptor[0]);
+ fcunlock.setNumLine(rntree.getNumLine());
+ if(end != null) {
+ end.addNext(fcunlock);
+ }
+ end = fcunlock;
}
end.addNext(ln);
ln=end;
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();
+ 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);
//TODO signal the object that will report errors
if( state.RCR ) {
try {
- rcr = new RuntimeConflictResolver(PREFIX,
- oooa,
- state);
- System.out.println("Runtime Conflict Resolver started.");
+ rcr = new RuntimeConflictResolver(PREFIX,
+ oooa,
+ state);
+ System.out.println("Runtime Conflict Resolver started.");
} catch (FileNotFoundException e) {
- System.out.println("Runtime Conflict Resolver could not create output file.");
+ System.out.println("Runtime Conflict Resolver could not create output file.");
}
}
}
TempDescriptor temp = itr.next();
TypeDescriptor type = temp.getType();
if( type.isPtr() ) {
- objectparams.addPtr(temp);
+ objectparams.addPtr(temp);
} else {
- objectparams.addPrim(temp);
+ objectparams.addPrim(temp);
}
}
TempDescriptor[] writes = fn.writesTemps();
for( int i = 0; i < writes.length; i++ ) {
- TempDescriptor temp = writes[i];
- TypeDescriptor type = temp.getType();
-
- if( type.isPtr() ) {
- objecttemps.addPtr(temp);
- } else {
- objecttemps.addPrim(temp);
- }
+ TempDescriptor temp = writes[i];
+ TypeDescriptor type = temp.getType();
+
+ if( type.isPtr() ) {
+ objecttemps.addPtr(temp);
+ } else {
+ objecttemps.addPrim(temp);
+ }
}
}
}
TempDescriptor temp=objecttemps.getPointer(i);
if (temp.getType().isNull())
- outputStructs.println(" void * "+temp.getSafeSymbol()+";");
+ outputStructs.println(" void * "+temp.getSafeSymbol()+";");
else
- outputStructs.println(" struct "+
- temp.getType().getSafeSymbol()+" * "+
- temp.getSafeSymbol()+";");
+ outputStructs.println(" struct "+
+ temp.getType().getSafeSymbol()+" * "+
+ temp.getSafeSymbol()+";");
}
outputStructs.println("};\n");
TempDescriptor temp = itr.next();
TypeDescriptor type = temp.getType();
if( type.isPtr() ) {
- inSetAndOutSetObjs.add(temp);
+ inSetAndOutSetObjs.add(temp);
} else {
- inSetAndOutSetPrims.add(temp);
+ inSetAndOutSetPrims.add(temp);
}
}
for(int i=0; i<inset.size(); i++) {
TempDescriptor temp=inset.get(i);
if (temp.getType().isNull())
- outputStructs.println(" void * "+temp.getSafeSymbol()+
- "; /* in-or-out-set obj in gl */");
+ outputStructs.println(" void * "+temp.getSafeSymbol()+
+ "; /* in-or-out-set obj in gl */");
else
- outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
- temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
+ outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
+ temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
}
for(int i=0; i<objectparams.numPointers(); i++) {
TempDescriptor temp=objectparams.getPointer(i);
if (!inset.contains(temp)) {
- if (temp.getType().isNull())
- outputStructs.println(" void * "+temp.getSafeSymbol()+
- "; /* in-or-out-set obj in gl */");
- else
- outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
- temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
+ if (temp.getType().isNull())
+ outputStructs.println(" void * "+temp.getSafeSymbol()+
+ "; /* in-or-out-set obj in gl */");
+ else
+ outputStructs.println(" struct "+temp.getType().getSafeSymbol()+" * "+
+ temp.getSafeSymbol()+"; /* in-or-out-set obj in gl */");
}
}
TempDescriptor temp = itrPrims.next();
TypeDescriptor type = temp.getType();
if(type.isPrimitive()) {
- outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+
- temp.getSafeSymbol()+"; /* in-set or out-set primitive */");
+ outputStructs.println(" "+temp.getType().getSafeSymbol()+" "+
+ temp.getSafeSymbol()+"; /* in-set or out-set primitive */");
}
}
if (state.RCR) {
if (inset.size()!=0) {
- outputStructs.println("struct rcrRecord rcrRecords["+inset.size()+"];");
+ outputStructs.println("struct rcrRecord rcrRecords["+inset.size()+"];");
}
}
output.print(objecttemp.numPointers()+",");
output.print("&(((SESEcommon*)(___params___))[1])");
for(int j=0; j<objecttemp.numPointers(); j++)
- output.print(", NULL");
+ output.print(", NULL");
output.println("};");
}
TempDescriptor td=objecttemp.getPrimitive(i);
TypeDescriptor type=td.getType();
if (type.isNull())
- output.println(" void * "+td.getSafeSymbol()+";");
+ output.println(" void * "+td.getSafeSymbol()+";");
else if (type.isClass()||type.isArray())
- output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
+ output.println(" struct "+type.getSafeSymbol()+" * "+td.getSafeSymbol()+";");
else
- output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
+ output.println(" "+type.getSafeSymbol()+" "+td.getSafeSymbol()+";");
}
TempDescriptor temp = itrInSet.next();
TypeDescriptor type = temp.getType();
if( !type.isPtr() ) {
- if( fsen.getReadyInVarSet().contains(temp) ) {
- output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
- } else {
- output.println(" "+type+" "+temp+";");
- }
+ if( fsen.getReadyInVarSet().contains(temp) ) {
+ output.println(" "+type+" "+temp+" = "+paramsprefix+"->"+temp+";");
+ } else {
+ output.println(" "+type+" "+temp+";");
+ }
}
}
TempDescriptor temp = itrOutSet.next();
TypeDescriptor type = temp.getType();
if( !type.isPtr() && !fsen.getInVarSet().contains(temp) ) {
- output.println(" "+type+" "+temp+";");
+ output.println(" "+type+" "+temp+";");
}
}
Set<Analysis.OoOJava.SESELock> lockSet = oooa.getLockMappings(graph);
System.out.println("#lockSet="+lockSet);
if( lockSet.size() > 0 ) {
- output.println(" numMemoryQueue=" + lockSet.size() + ";");
- output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
- output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
- output.println();
+ output.println(" numMemoryQueue=" + lockSet.size() + ";");
+ output.println(" runningSESE->numMemoryQueue=numMemoryQueue;");
+ output.println(" runningSESE->memoryQueueArray=mlpCreateMemoryQueueArray(numMemoryQueue);");
+ output.println();
}
output.println(" }");
}
output.println(" runningSESE->taskRecordMemPool = poolcreate( "+
maxTaskRecSizeStr+", freshTaskRecordInitializer );");
if (state.RCR && !rcr.hasEmptyTraversers(fsen)) {
- output.println(" createTR();");
- output.println(" runningSESE->allHashStructures=TRqueue->allHashStructures;");
+ output.println(" createTR();");
+ output.println(" runningSESE->allHashStructures=TRqueue->allHashStructures;");
}
} else {
// make it clear we purposefully did not initialize this
String typeStr;
if( type.isNull() ) {
- typeStr = "void*";
+ typeStr = "void*";
} else if( type.isClass() || type.isArray() ) {
- typeStr = "struct "+type.getSafeSymbol()+"*";
+ typeStr = "struct "+type.getSafeSymbol()+"*";
} else {
- typeStr = type.getSafeSymbol();
+ typeStr = type.getSafeSymbol();
}
output.println(" "+generateTemp(fsen.getfmBogus(), temp)+
outmethod.println(" "+fsen.getSESEmethodName()+"( seseRecord );");
if( fsen.getIsMainSESE() ) {
- outmethod.println(" workScheduleExit();");
+ outmethod.println(" workScheduleExit();");
}
outmethod.println(" break;");
for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext(); ) {
WaitingElement waitingElement =(WaitingElement) iterator.next();
if (waitingElement.getStatus() >= ConflictNode.COARSE) {
- output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["
- + waitingElement.getQueueID() + "]," + waitingElement.getStatus()
- + ", (SESEcommon *) stallrecord, 1LL);");
+ output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["
+ + waitingElement.getQueueID() + "]," + waitingElement.getStatus()
+ + ", (SESEcommon *) stallrecord, 1LL);");
} else {
- throw new Error("Fine-grained conflict: This should not happen in RCR");
+ throw new Error("Fine-grained conflict: This should not happen in RCR");
}
output.println(" rentry->queue=runningSESE->memoryQueueArray["
+ waitingElement.getQueueID() + "];");
"]->rentrypool, rentry);");
output.println("#endif");
if (stalltd==null) {
- stalltd=waitingElement.getTempDesc();
+ stalltd=waitingElement.getTempDesc();
} else if (stalltd!=waitingElement.getTempDesc()) {
- throw new Error("Multiple temp descriptors at stall site"+stalltd+"!="+waitingElement.getTempDesc());
+ throw new Error("Multiple temp descriptors at stall site"+stalltd+"!="+waitingElement.getTempDesc());
}
}
FlatMethod fmContext;
if( currentSESE.getIsCallerProxySESE() ) {
- fmContext = oooa.getContainingFlatMethod(fn);
+ fmContext = oooa.getContainingFlatMethod(fn);
} else {
- fmContext = currentSESE.getfmBogus();
+ fmContext = currentSESE.getfmBogus();
}
ContextTaskNames contextTaskNames;
if( currentSESE.getIsCallerProxySESE() ) {
- contextTaskNames = oooa.getContextTaskNames(oooa.getContainingFlatMethod(fn) );
+ contextTaskNames = oooa.getContextTaskNames(oooa.getContainingFlatMethod(fn) );
} else {
- contextTaskNames = oooa.getContextTaskNames(currentSESE);
+ contextTaskNames = oooa.getContextTaskNames(currentSESE);
}
// for each sese and age pair that this parent statement
// copying of values comes after the statement
Iterator<VariableSourceToken> vstItr = cp.getStallTokens().iterator();
while( vstItr.hasNext() ) {
- VariableSourceToken vst = vstItr.next();
-
- SESEandAgePair pair = new SESEandAgePair(vst.getSESE(), vst.getAge() );
-
- output.println(" {");
- output.println(" "+
- pair.getSESE().getSESErecordName()+"* child = ("+
- pair.getSESE().getSESErecordName()+"*) "+pair+";");
-
- output.println(" SESEcommon* childCom = (SESEcommon*) "+pair+";");
-
- if( state.COREPROF ) {
- output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
- output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
- output.println("#endif");
- }
-
- output.println(" pthread_mutex_lock( &(childCom->lock) );");
- output.println(" if( childCom->doneExecuting == FALSE ) {");
- output.println(" psem_reset( &runningSESEstallSem );");
- output.println(" childCom->parentsStallSem = &runningSESEstallSem;");
- output.println(" pthread_mutex_unlock( &(childCom->lock) );");
- output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
- output.println(" } else {");
- output.println(" pthread_mutex_unlock( &(childCom->lock) );");
- output.println(" }");
-
- // copy things we might have stalled for
- Iterator<TempDescriptor> tdItr = cp.getCopySet(vst).iterator();
- while( tdItr.hasNext() ) {
- TempDescriptor td = tdItr.next();
- output.println(" "+generateTemp(fmContext, td)+
- " = child->"+vst.getAddrVar().getSafeSymbol()+";");
- }
-
- if( state.COREPROF ) {
- output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
- output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
- output.println("#endif");
- }
-
- output.println(" }");
+ VariableSourceToken vst = vstItr.next();
+
+ SESEandAgePair pair = new SESEandAgePair(vst.getSESE(), vst.getAge() );
+
+ output.println(" {");
+ output.println(" "+
+ pair.getSESE().getSESErecordName()+"* child = ("+
+ pair.getSESE().getSESErecordName()+"*) "+pair+";");
+
+ output.println(" SESEcommon* childCom = (SESEcommon*) "+pair+";");
+
+ if( state.COREPROF ) {
+ output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
+ output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
+ output.println("#endif");
+ }
+
+ output.println(" pthread_mutex_lock( &(childCom->lock) );");
+ output.println(" if( childCom->doneExecuting == FALSE ) {");
+ output.println(" psem_reset( &runningSESEstallSem );");
+ output.println(" childCom->parentsStallSem = &runningSESEstallSem;");
+ output.println(" pthread_mutex_unlock( &(childCom->lock) );");
+ output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
+ output.println(" } else {");
+ output.println(" pthread_mutex_unlock( &(childCom->lock) );");
+ output.println(" }");
+
+ // copy things we might have stalled for
+ Iterator<TempDescriptor> tdItr = cp.getCopySet(vst).iterator();
+ while( tdItr.hasNext() ) {
+ TempDescriptor td = tdItr.next();
+ output.println(" "+generateTemp(fmContext, td)+
+ " = child->"+vst.getAddrVar().getSafeSymbol()+";");
+ }
+
+ if( state.COREPROF ) {
+ output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
+ output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
+ output.println("#endif");
+ }
+
+ output.println(" }");
}
// for each variable with a dynamic source, stall just for that variable
Iterator<TempDescriptor> dynItr = cp.getDynamicStallSet().iterator();
while( dynItr.hasNext() ) {
- TempDescriptor dynVar = dynItr.next();
-
- // only stall if the dynamic source is not yourself, denoted by src==NULL
- // otherwise the dynamic write nodes will have the local var up-to-date
- output.println(" {");
- output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
-
- output.println(" SESEcommon* childCom = (SESEcommon*) "+dynVar+"_srcSESE;");
-
- if( state.COREPROF ) {
- output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
- output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
- output.println("#endif");
- }
-
- output.println(" pthread_mutex_lock( &(childCom->lock) );");
- output.println(" if( childCom->doneExecuting == FALSE ) {");
- output.println(" psem_reset( &runningSESEstallSem );");
- output.println(" childCom->parentsStallSem = &runningSESEstallSem;");
- output.println(" pthread_mutex_unlock( &(childCom->lock) );");
- output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
- output.println(" } else {");
- output.println(" pthread_mutex_unlock( &(childCom->lock) );");
- output.println(" }");
-
- TypeDescriptor type = dynVar.getType();
- String typeStr;
- if( type.isNull() ) {
- typeStr = "void*";
- } else if( type.isClass() || type.isArray() ) {
- typeStr = "struct "+type.getSafeSymbol()+"*";
- } else {
- typeStr = type.getSafeSymbol();
- }
-
- output.println(" "+generateTemp(fmContext, dynVar)+
- " = *(("+typeStr+"*) ((void*)"+
- dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
-
- if( state.COREPROF ) {
- output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
- output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
- output.println("#endif");
- }
-
- output.println(" }");
- output.println(" }");
+ TempDescriptor dynVar = dynItr.next();
+
+ // only stall if the dynamic source is not yourself, denoted by src==NULL
+ // otherwise the dynamic write nodes will have the local var up-to-date
+ output.println(" {");
+ output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
+
+ output.println(" SESEcommon* childCom = (SESEcommon*) "+dynVar+"_srcSESE;");
+
+ if( state.COREPROF ) {
+ output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
+ output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_BEGIN );");
+ output.println("#endif");
+ }
+
+ output.println(" pthread_mutex_lock( &(childCom->lock) );");
+ output.println(" if( childCom->doneExecuting == FALSE ) {");
+ output.println(" psem_reset( &runningSESEstallSem );");
+ output.println(" childCom->parentsStallSem = &runningSESEstallSem;");
+ output.println(" pthread_mutex_unlock( &(childCom->lock) );");
+ output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
+ output.println(" } else {");
+ output.println(" pthread_mutex_unlock( &(childCom->lock) );");
+ output.println(" }");
+
+ TypeDescriptor type = dynVar.getType();
+ String typeStr;
+ if( type.isNull() ) {
+ typeStr = "void*";
+ } else if( type.isClass() || type.isArray() ) {
+ typeStr = "struct "+type.getSafeSymbol()+"*";
+ } else {
+ typeStr = type.getSafeSymbol();
+ }
+
+ output.println(" "+generateTemp(fmContext, dynVar)+
+ " = *(("+typeStr+"*) ((void*)"+
+ dynVar+"_srcSESE + "+dynVar+"_srcOffset));");
+
+ if( state.COREPROF ) {
+ output.println("#ifdef CP_EVENTID_TASKSTALLVAR");
+ output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLVAR, CP_EVENTTYPE_END );");
+ output.println("#endif");
+ }
+
+ output.println(" }");
+ output.println(" }");
}
// for each assignment of a variable to rhs that has a dynamic source,
// copy the dynamic sources
Iterator dynAssignItr = cp.getDynAssigns().entrySet().iterator();
while( dynAssignItr.hasNext() ) {
- Map.Entry me = (Map.Entry)dynAssignItr.next();
- TempDescriptor lhs = (TempDescriptor) me.getKey();
- TempDescriptor rhs = (TempDescriptor) me.getValue();
-
- output.println(" {");
- output.println(" SESEcommon* oldSrc = "+lhs+"_srcSESE;");
-
- output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
- output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
-
- // no matter what we did above, track reference count of whatever
- // this variable pointed to, do release last in case we're just
- // copying the same value in because 1->2->1 is safe but ref count
- // 1->0->1 has a window where it looks like it should be free'd
- output.println("#ifndef OOO_DISABLE_TASKMEMPOOL");
- output.println(" if( "+rhs+"_srcSESE != NULL ) {");
- output.println(" ADD_REFERENCE_TO( "+rhs+"_srcSESE );");
- output.println(" }");
- output.println(" if( oldSrc != NULL ) {");
- output.println(" RELEASE_REFERENCE_TO( oldSrc );");
- output.println(" }");
- output.println(" }");
- output.println("#endif // OOO_DISABLE_TASKMEMPOOL");
+ Map.Entry me = (Map.Entry)dynAssignItr.next();
+ TempDescriptor lhs = (TempDescriptor) me.getKey();
+ TempDescriptor rhs = (TempDescriptor) me.getValue();
+
+ output.println(" {");
+ output.println(" SESEcommon* oldSrc = "+lhs+"_srcSESE;");
+
+ output.println(" "+lhs+"_srcSESE = "+rhs+"_srcSESE;");
+ output.println(" "+lhs+"_srcOffset = "+rhs+"_srcOffset;");
+
+ // no matter what we did above, track reference count of whatever
+ // this variable pointed to, do release last in case we're just
+ // copying the same value in because 1->2->1 is safe but ref count
+ // 1->0->1 has a window where it looks like it should be free'd
+ output.println("#ifndef OOO_DISABLE_TASKMEMPOOL");
+ output.println(" if( "+rhs+"_srcSESE != NULL ) {");
+ output.println(" ADD_REFERENCE_TO( "+rhs+"_srcSESE );");
+ output.println(" }");
+ output.println(" if( oldSrc != NULL ) {");
+ output.println(" RELEASE_REFERENCE_TO( oldSrc );");
+ output.println(" }");
+ output.println(" }");
+ output.println("#endif // OOO_DISABLE_TASKMEMPOOL");
}
// for each lhs that is dynamic from a non-dynamic source, set the
// dynamic source vars to the current SESE
dynItr = cp.getDynAssignCurr().iterator();
while( dynItr.hasNext() ) {
- TempDescriptor dynVar = dynItr.next();
+ TempDescriptor dynVar = dynItr.next();
- assert contextTaskNames.getDynamicVarSet().contains(dynVar);
+ assert contextTaskNames.getDynamicVarSet().contains(dynVar);
- // first release a reference to current record
- output.println("#ifndef OOO_DISABLE_TASKMEMPOOL");
- output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
- output.println(" RELEASE_REFERENCE_TO( oldSrc );");
- output.println(" }");
- output.println("#endif // OOO_DISABLE_TASKMEMPOOL");
+ // first release a reference to current record
+ output.println("#ifndef OOO_DISABLE_TASKMEMPOOL");
+ output.println(" if( "+dynVar+"_srcSESE != NULL ) {");
+ output.println(" RELEASE_REFERENCE_TO( oldSrc );");
+ output.println(" }");
+ output.println("#endif // OOO_DISABLE_TASKMEMPOOL");
- output.println(" "+dynVar+"_srcSESE = NULL;");
+ output.println(" "+dynVar+"_srcSESE = NULL;");
}
// create a case for each class of task that might be executing
Iterator<FlatSESEEnterNode> taskItr = oooa.getPossibleExecutingRBlocks(fn).iterator();
while( taskItr.hasNext() ) {
- FlatSESEEnterNode parent = taskItr.next();
- ConflictGraph graph = oooa.getConflictGraph(parent);
-
- if( graph == null ) {
- continue;
- }
-
- Set<SESELock> seseLockSet = oooa.getLockMappings(graph);
- Set<WaitingElement> waitingElementSet = graph.getStallSiteWaitingElementSet(fn, seseLockSet);
-
- if( waitingElementSet.size() == 0 ) {
- continue;
- }
-
- // TODO: THIS STRATEGY CAN BE OPTIMIZED EVEN FURTHER, IF THERE
- // IS EXACTLY ONE CASE, DON'T GENERATE A SWITCH AT ALL
- if( atLeastOneCase == false ) {
- atLeastOneCase = true;
- output.println(" // potential stall site ");
- output.println(" switch( runningSESE->classID ) {");
- }
-
- output.println(" case "+parent.getIdentifier()+": {");
-
- if( state.RCR ) {
- stallMEMRCR(fm, fn, waitingElementSet, output);
- } else {
-
- output.println(" REntry* rentry;");
-
- for( Iterator iterator = waitingElementSet.iterator(); iterator.hasNext(); ) {
- WaitingElement waitingElement = (WaitingElement) iterator.next();
-
- if (waitingElement.getStatus() >= ConflictNode.COARSE) {
- output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["
- + waitingElement.getQueueID() + "]," + waitingElement.getStatus()
- + ", runningSESE);");
- } else {
- output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["
- + waitingElement.getQueueID() + "]," + waitingElement.getStatus()
- + ", runningSESE, (void*)&"
- + generateTemp(fm, waitingElement.getTempDesc()) + ");");
- }
- output.println(" rentry->parentStallSem=&runningSESEstallSem;");
- output.println(" psem_reset( &runningSESEstallSem);");
- output.println(" rentry->tag=runningSESEstallSem.tag;");
- output.println(" rentry->queue=runningSESE->memoryQueueArray["
- + waitingElement.getQueueID() + "];");
- output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
- + waitingElement.getQueueID() + "],rentry)==NOTREADY){");
- if (state.COREPROF) {
- output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
- output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
- output.println("#endif");
- }
-
- output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
-
- if (state.COREPROF) {
- output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
- output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
- output.println("#endif");
- }
- output.println(" } ");
- }
-
- }
- output.println(" } break; // end case "+parent.getIdentifier());
+ FlatSESEEnterNode parent = taskItr.next();
+ ConflictGraph graph = oooa.getConflictGraph(parent);
+
+ if( graph == null ) {
+ continue;
+ }
+
+ Set<SESELock> seseLockSet = oooa.getLockMappings(graph);
+ Set<WaitingElement> waitingElementSet = graph.getStallSiteWaitingElementSet(fn, seseLockSet);
+
+ if( waitingElementSet.size() == 0 ) {
+ continue;
+ }
+
+ // TODO: THIS STRATEGY CAN BE OPTIMIZED EVEN FURTHER, IF THERE
+ // IS EXACTLY ONE CASE, DON'T GENERATE A SWITCH AT ALL
+ if( atLeastOneCase == false ) {
+ atLeastOneCase = true;
+ output.println(" // potential stall site ");
+ output.println(" switch( runningSESE->classID ) {");
+ }
+
+ output.println(" case "+parent.getIdentifier()+": {");
+
+ if( state.RCR ) {
+ stallMEMRCR(fm, fn, waitingElementSet, output);
+ } else {
+
+ output.println(" REntry* rentry;");
+
+ for( Iterator iterator = waitingElementSet.iterator(); iterator.hasNext(); ) {
+ WaitingElement waitingElement = (WaitingElement) iterator.next();
+
+ if (waitingElement.getStatus() >= ConflictNode.COARSE) {
+ output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["
+ + waitingElement.getQueueID() + "]," + waitingElement.getStatus()
+ + ", runningSESE);");
+ } else {
+ output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["
+ + waitingElement.getQueueID() + "]," + waitingElement.getStatus()
+ + ", runningSESE, (void*)&"
+ + generateTemp(fm, waitingElement.getTempDesc()) + ");");
+ }
+ output.println(" rentry->parentStallSem=&runningSESEstallSem;");
+ output.println(" psem_reset( &runningSESEstallSem);");
+ output.println(" rentry->tag=runningSESEstallSem.tag;");
+ output.println(" rentry->queue=runningSESE->memoryQueueArray["
+ + waitingElement.getQueueID() + "];");
+ output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
+ + waitingElement.getQueueID() + "],rentry)==NOTREADY){");
+ if (state.COREPROF) {
+ output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
+ output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_BEGIN );");
+ output.println("#endif");
+ }
+
+ output.println(" psem_take( &runningSESEstallSem, (struct garbagelist *)&___locals___ );");
+
+ if (state.COREPROF) {
+ output.println("#ifdef CP_EVENTID_TASKSTALLMEM");
+ output.println(" CP_LOGEVENT( CP_EVENTID_TASKSTALLMEM, CP_EVENTTYPE_END );");
+ output.println("#endif");
+ }
+ output.println(" } ");
+ }
+
+ }
+ output.println(" } break; // end case "+parent.getIdentifier());
}
if( atLeastOneCase ) {
- output.println(" } // end stall site switch");
+ output.println(" } // end stall site switch");
}
}
}
// if we're using RCR, ref count is 3 because the traverser has
// a reference, too
if( !fsen.getIsMainSESE() && fsen.getInVarsForDynamicCoarseConflictResolution().size()>0) {
- output.println(" seseToIssue->common.refCount = 10003;");
+ output.println(" seseToIssue->common.refCount = 10003;");
} else {
- output.println(" seseToIssue->common.refCount = 10002;");
+ output.println(" seseToIssue->common.refCount = 10002;");
}
output.println(" int refCount=10000;");
} else {
assert !fsen.getIsCallerProxySESE();
FlatSESEEnterNode parent = fsen.getLocalParent();
if( parent != null && !parent.getIsCallerProxySESE() ) {
- output.println(" seseToIssue->"+temp+" = "+
- generateTemp(parent.getfmBogus(), temp)+";");
+ output.println(" seseToIssue->"+temp+" = "+
+ generateTemp(parent.getfmBogus(), temp)+";");
} else {
- output.println(" seseToIssue->"+temp+" = "+
- generateTemp(fsen.getfmEnclosing(), temp)+";");
+ output.println(" seseToIssue->"+temp+" = "+
+ generateTemp(fsen.getfmEnclosing(), temp)+";");
}
}
// count up outstanding dependencies, static first, then dynamic
Iterator<SESEandAgePair> staticSrcsItr = fsen.getStaticInVarSrcs().iterator();
while( staticSrcsItr.hasNext() ) {
- SESEandAgePair srcPair = staticSrcsItr.next();
- output.println(" {");
- output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
- output.println(" pthread_mutex_lock( &(src->lock) );");
- // FORWARD TODO - ...what? make it a chain of arrays instead of true linked-list?
- output.println(" if( !src->doneExecuting ) {");
- output.println(" addNewItem( &src->forwardList, seseToIssue );");
- output.println(" ++(localCount);");
- output.println(" }");
- output.println("#ifndef OOO_DISABLE_TASKMEMPOOL");
- output.println(" ADD_REFERENCE_TO( src );");
- output.println("#endif");
- output.println(" pthread_mutex_unlock( &(src->lock) );");
- output.println(" }");
-
- // whether or not it is an outstanding dependency, make sure
- // to pass the static name to the child's record
- output.println(" seseToIssue->"+srcPair+" = "+
- "("+srcPair.getSESE().getSESErecordName()+"*)"+
- srcPair+";");
+ SESEandAgePair srcPair = staticSrcsItr.next();
+ output.println(" {");
+ output.println(" SESEcommon* src = (SESEcommon*)"+srcPair+";");
+ output.println(" pthread_mutex_lock( &(src->lock) );");
+ // FORWARD TODO - ...what? make it a chain of arrays instead of true linked-list?
+ output.println(" if( !src->doneExecuting ) {");
+ output.println(" addNewItem( &src->forwardList, seseToIssue );");
+ output.println(" ++(localCount);");
+ output.println(" }");
+ output.println("#ifndef OOO_DISABLE_TASKMEMPOOL");
+ output.println(" ADD_REFERENCE_TO( src );");
+ output.println("#endif");
+ output.println(" pthread_mutex_unlock( &(src->lock) );");
+ output.println(" }");
+
+ // whether or not it is an outstanding dependency, make sure
+ // to pass the static name to the child's record
+ output.println(" seseToIssue->"+srcPair+" = "+
+ "("+srcPair.getSESE().getSESErecordName()+"*)"+
+ srcPair+";");
}
// dynamic sources might already be accounted for in the static list,
// so only add them to forwarding lists if they're not already there
Iterator<TempDescriptor> dynVarsItr = fsen.getDynamicInVarSet().iterator();
while( dynVarsItr.hasNext() ) {
- TempDescriptor dynInVar = dynVarsItr.next();
- output.println(" {");
- output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
-
- // the dynamic source is NULL if it comes from your own space--you can't pass
- // the address off to the new child, because you're not done executing and
- // might change the variable, so copy it right now
- output.println(" if( src != NULL ) {");
- output.println(" pthread_mutex_lock( &(src->lock) );");
-
- // FORWARD TODO
-
- output.println(" if( isEmpty( &src->forwardList ) ||");
- output.println(" seseToIssue != peekItem( &src->forwardList ) ) {");
- output.println(" if( !src->doneExecuting ) {");
- output.println(" addNewItem( &src->forwardList, seseToIssue );");
- output.println(" ++(localCount);");
- output.println(" }");
- output.println(" }");
- output.println("#ifndef OOO_DISABLE_TASKMEMPOOL");
- output.println(" ADD_REFERENCE_TO( src );");
- output.println("#endif");
- output.println(" pthread_mutex_unlock( &(src->lock) );");
- output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
- output.println(" } else {");
-
-
- // determine whether this new task instance is in a method context,
- // or within the body of another task
- assert !fsen.getIsCallerProxySESE();
- FlatSESEEnterNode parent = fsen.getLocalParent();
- if( parent != null && !parent.getIsCallerProxySESE() ) {
- output.println(" seseToIssue->"+dynInVar+" = "+
- generateTemp(parent.getfmBogus(), dynInVar)+";");
- } else {
- output.println(" seseToIssue->"+dynInVar+" = "+
- generateTemp(fsen.getfmEnclosing(), dynInVar)+";");
- }
-
- output.println(" }");
- output.println(" }");
-
- // even if the value is already copied, make sure your NULL source
- // gets passed so child knows it already has the dynamic value
- output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
+ TempDescriptor dynInVar = dynVarsItr.next();
+ output.println(" {");
+ output.println(" SESEcommon* src = (SESEcommon*)"+dynInVar+"_srcSESE;");
+
+ // the dynamic source is NULL if it comes from your own space--you can't pass
+ // the address off to the new child, because you're not done executing and
+ // might change the variable, so copy it right now
+ output.println(" if( src != NULL ) {");
+ output.println(" pthread_mutex_lock( &(src->lock) );");
+
+ // FORWARD TODO
+
+ output.println(" if( isEmpty( &src->forwardList ) ||");
+ output.println(" seseToIssue != peekItem( &src->forwardList ) ) {");
+ output.println(" if( !src->doneExecuting ) {");
+ output.println(" addNewItem( &src->forwardList, seseToIssue );");
+ output.println(" ++(localCount);");
+ output.println(" }");
+ output.println(" }");
+ output.println("#ifndef OOO_DISABLE_TASKMEMPOOL");
+ output.println(" ADD_REFERENCE_TO( src );");
+ output.println("#endif");
+ output.println(" pthread_mutex_unlock( &(src->lock) );");
+ output.println(" seseToIssue->"+dynInVar+"_srcOffset = "+dynInVar+"_srcOffset;");
+ output.println(" } else {");
+
+
+ // determine whether this new task instance is in a method context,
+ // or within the body of another task
+ assert !fsen.getIsCallerProxySESE();
+ FlatSESEEnterNode parent = fsen.getLocalParent();
+ if( parent != null && !parent.getIsCallerProxySESE() ) {
+ output.println(" seseToIssue->"+dynInVar+" = "+
+ generateTemp(parent.getfmBogus(), dynInVar)+";");
+ } else {
+ output.println(" seseToIssue->"+dynInVar+" = "+
+ generateTemp(fsen.getfmEnclosing(), dynInVar)+";");
+ }
+
+ output.println(" }");
+ output.println(" }");
+
+ // even if the value is already copied, make sure your NULL source
+ // gets passed so child knows it already has the dynamic value
+ output.println(" seseToIssue->"+dynInVar+"_srcSESE = "+dynInVar+"_srcSESE;");
}
// and also release references that have become too old
if( !fsen.getIsMainSESE() ) {
- FlatSESEEnterNode currentSESE = fsen.getLocalParent();
-
- ContextTaskNames contextTaskNames;
- if( currentSESE == null ) {
- contextTaskNames = oooa.getContextTaskNames(oooa.getContainingFlatMethod(fsen) );
- } else {
- contextTaskNames = oooa.getContextTaskNames(currentSESE);
- }
-
- SESEandAgePair pairNewest = new SESEandAgePair(fsen, 0);
- SESEandAgePair pairOldest = new SESEandAgePair(fsen, fsen.getOldestAgeToTrack() );
- if( contextTaskNames.getNeededStaticNames().contains(pairNewest) ) {
- output.println(" {");
- output.println("#ifndef OOO_DISABLE_TASKMEMPOOL");
- output.println(" SESEcommon* oldest = "+pairOldest+";");
- output.println("#endif // OOO_DISABLE_TASKMEMPOOL");
-
- for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
- SESEandAgePair pair1 = new SESEandAgePair(fsen, i);
- SESEandAgePair pair2 = new SESEandAgePair(fsen, i-1);
- output.println(" "+pair1+" = "+pair2+";");
- }
- output.println(" "+pairNewest+" = &(seseToIssue->common);");
-
- // no need to add a reference to whatever is the newest record, because
- // we initialized seseToIssue->refCount to *2*
- // but release a reference to whatever was the oldest BEFORE the shift
- output.println("#ifndef OOO_DISABLE_TASKMEMPOOL");
- output.println(" if( oldest != NULL ) {");
- output.println(" RELEASE_REFERENCE_TO( oldest );");
- output.println(" }");
- output.println("#endif // OOO_DISABLE_TASKMEMPOOL");
- output.println(" }");
- }
+ FlatSESEEnterNode currentSESE = fsen.getLocalParent();
+
+ ContextTaskNames contextTaskNames;
+ if( currentSESE == null ) {
+ contextTaskNames = oooa.getContextTaskNames(oooa.getContainingFlatMethod(fsen) );
+ } else {
+ contextTaskNames = oooa.getContextTaskNames(currentSESE);
+ }
+
+ SESEandAgePair pairNewest = new SESEandAgePair(fsen, 0);
+ SESEandAgePair pairOldest = new SESEandAgePair(fsen, fsen.getOldestAgeToTrack() );
+ if( contextTaskNames.getNeededStaticNames().contains(pairNewest) ) {
+ output.println(" {");
+ output.println("#ifndef OOO_DISABLE_TASKMEMPOOL");
+ output.println(" SESEcommon* oldest = "+pairOldest+";");
+ output.println("#endif // OOO_DISABLE_TASKMEMPOOL");
+
+ for( int i = fsen.getOldestAgeToTrack(); i > 0; --i ) {
+ SESEandAgePair pair1 = new SESEandAgePair(fsen, i);
+ SESEandAgePair pair2 = new SESEandAgePair(fsen, i-1);
+ output.println(" "+pair1+" = "+pair2+";");
+ }
+ output.println(" "+pairNewest+" = &(seseToIssue->common);");
+
+ // no need to add a reference to whatever is the newest record, because
+ // we initialized seseToIssue->refCount to *2*
+ // but release a reference to whatever was the oldest BEFORE the shift
+ output.println("#ifndef OOO_DISABLE_TASKMEMPOOL");
+ output.println(" if( oldest != NULL ) {");
+ output.println(" RELEASE_REFERENCE_TO( oldest );");
+ output.println(" }");
+ output.println("#endif // OOO_DISABLE_TASKMEMPOOL");
+ output.println(" }");
+ }
}
}
if( !fsen.getIsMainSESE() ) {
if( state.COREPROF ) {
- output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
- output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_BEGIN );");
- output.println("#endif");
+ output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
+ output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_BEGIN );");
+ output.println("#endif");
}
if(state.RCR) {
- dispatchMEMRC(fm, fsen, output);
+ dispatchMEMRC(fm, fsen, output);
} else {
- // there may be several task types that can get to this
- // program point (issue this new task) so create a switch
- // based on task ID, each type of task has a different index
- // scheme for its memory queue's, and the cases here drop the
- // new task instance in the right bucket
- boolean atLeastOneCase = false;
-
- // create a case for each class of task that might be executing
- Iterator<FlatSESEEnterNode> taskItr = oooa.getPossibleExecutingRBlocks(fsen).iterator();
- while( taskItr.hasNext() ) {
- FlatSESEEnterNode parent = taskItr.next();
- ConflictGraph graph = oooa.getConflictGraph(parent);
-
- if( graph == null || !graph.hasConflictEdge() ) {
- continue;
- }
-
- Set<SESELock> seseLockSet = oooa.getLockMappings(graph);
-
- SESEWaitingQueue seseWaitingQueue =
- graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
-
- if( seseWaitingQueue.getWaitingElementSize() == 0 ) {
- continue;
- }
-
- if( atLeastOneCase == false ) {
- atLeastOneCase = true;
- output.println(" // add new task instance to current task's memory queues if needed ");
- output.println(" switch( runningSESE->classID ) {");
- }
-
- output.println(" case "+parent.getIdentifier()+": {");
- output.println(" REntry* rentry=NULL;");
- output.println(" INTPTR* pointer=NULL;");
- output.println(" seseToIssue->common.rentryIdx=0;");
-
- Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
- for (Iterator iterator = queueIDSet.iterator(); iterator.hasNext(); ) {
- Integer key = (Integer) iterator.next();
- int queueID=key.intValue();
- Set<WaitingElement> waitingQueueSet =
- seseWaitingQueue.getWaitingElementSet(queueID);
- int enqueueType=seseWaitingQueue.getType(queueID);
- if(enqueueType==SESEWaitingQueue.EXCEPTION) {
- output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray[" + queueID+ "]);");
- }
- for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2.hasNext(); ) {
- WaitingElement waitingElement
- = (WaitingElement) iterator2.next();
- if (waitingElement.getStatus() >= ConflictNode.COARSE) {
- output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
- + waitingElement.getStatus()
- + ", &(seseToIssue->common));");
- } else {
- TempDescriptor td = waitingElement.getTempDesc();
- // decide whether waiting element is dynamic or static
- if (fsen.getDynamicInVarSet().contains(td)) {
- // dynamic in-var case
- output.println(" pointer=seseToIssue->"
- + waitingElement.getDynID()
- + "_srcSESE+seseToIssue->"
- + waitingElement.getDynID()
- + "_srcOffset;");
- output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
- + waitingElement.getStatus()
- + ", &(seseToIssue->common), pointer );");
- } else if (fsen.getStaticInVarSet().contains(td)) {
- // static in-var case
- VariableSourceToken vst = fsen.getStaticInVarSrc(td);
- if (vst != null) {
-
- String srcId = "SESE_" + vst.getSESE().getPrettyIdentifier()
- + vst.getSESE().getIdentifier()
- + "_" + vst.getAge();
- output.println(" pointer=(void*)&seseToIssue->"
- + srcId
- + "->"
- + waitingElement
- .getDynID()
- + ";");
- output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
- + waitingElement.getStatus()
- + ", &(seseToIssue->common), pointer );");
- }
- } else {
- output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
- + waitingElement.getStatus()
- + ", &(seseToIssue->common), (void*)&seseToIssue->"
- + waitingElement.getDynID()
- + ");");
- }
- }
- output.println(" rentry->queue=runningSESE->memoryQueueArray["
- + waitingElement.getQueueID()
- + "];");
-
- if(enqueueType==SESEWaitingQueue.NORMAL) {
- output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
- output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
- + waitingElement.getQueueID()
- + "],rentry)==NOTREADY) {");
- output.println(" localCount++;");
- output.println(" }");
- } else {
- output.println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray[" + waitingElement.getQueueID() + "],rentry);");
- }
- }
- if(enqueueType!=SESEWaitingQueue.NORMAL) {
- output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
- + queueID+ "],&seseToIssue->common);");
- }
- }
- output.println(" } break; // end case "+parent.getIdentifier());
- output.println();
- }
-
- if( atLeastOneCase ) {
- output.println(" } // end stall site switch");
- }
+ // there may be several task types that can get to this
+ // program point (issue this new task) so create a switch
+ // based on task ID, each type of task has a different index
+ // scheme for its memory queue's, and the cases here drop the
+ // new task instance in the right bucket
+ boolean atLeastOneCase = false;
+
+ // create a case for each class of task that might be executing
+ Iterator<FlatSESEEnterNode> taskItr = oooa.getPossibleExecutingRBlocks(fsen).iterator();
+ while( taskItr.hasNext() ) {
+ FlatSESEEnterNode parent = taskItr.next();
+ ConflictGraph graph = oooa.getConflictGraph(parent);
+
+ if( graph == null || !graph.hasConflictEdge() ) {
+ continue;
+ }
+
+ Set<SESELock> seseLockSet = oooa.getLockMappings(graph);
+
+ SESEWaitingQueue seseWaitingQueue =
+ graph.getWaitingElementSetBySESEID(fsen.getIdentifier(), seseLockSet);
+
+ if( seseWaitingQueue.getWaitingElementSize() == 0 ) {
+ continue;
+ }
+
+ if( atLeastOneCase == false ) {
+ atLeastOneCase = true;
+ output.println(" // add new task instance to current task's memory queues if needed ");
+ output.println(" switch( runningSESE->classID ) {");
+ }
+
+ output.println(" case "+parent.getIdentifier()+": {");
+ output.println(" REntry* rentry=NULL;");
+ output.println(" INTPTR* pointer=NULL;");
+ output.println(" seseToIssue->common.rentryIdx=0;");
+
+ Set<Integer> queueIDSet=seseWaitingQueue.getQueueIDSet();
+ for (Iterator iterator = queueIDSet.iterator(); iterator.hasNext(); ) {
+ Integer key = (Integer) iterator.next();
+ int queueID=key.intValue();
+ Set<WaitingElement> waitingQueueSet =
+ seseWaitingQueue.getWaitingElementSet(queueID);
+ int enqueueType=seseWaitingQueue.getType(queueID);
+ if(enqueueType==SESEWaitingQueue.EXCEPTION) {
+ output.println(" INITIALIZEBUF(runningSESE->memoryQueueArray[" + queueID+ "]);");
+ }
+ for (Iterator iterator2 = waitingQueueSet.iterator(); iterator2.hasNext(); ) {
+ WaitingElement waitingElement
+ = (WaitingElement) iterator2.next();
+ if (waitingElement.getStatus() >= ConflictNode.COARSE) {
+ output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
+ + waitingElement.getStatus()
+ + ", &(seseToIssue->common));");
+ } else {
+ TempDescriptor td = waitingElement.getTempDesc();
+ // decide whether waiting element is dynamic or static
+ if (fsen.getDynamicInVarSet().contains(td)) {
+ // dynamic in-var case
+ output.println(" pointer=seseToIssue->"
+ + waitingElement.getDynID()
+ + "_srcSESE+seseToIssue->"
+ + waitingElement.getDynID()
+ + "_srcOffset;");
+ output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
+ + waitingElement.getStatus()
+ + ", &(seseToIssue->common), pointer );");
+ } else if (fsen.getStaticInVarSet().contains(td)) {
+ // static in-var case
+ VariableSourceToken vst = fsen.getStaticInVarSrc(td);
+ if (vst != null) {
+
+ String srcId = "SESE_" + vst.getSESE().getPrettyIdentifier()
+ + vst.getSESE().getIdentifier()
+ + "_" + vst.getAge();
+ output.println(" pointer=(void*)&seseToIssue->"
+ + srcId
+ + "->"
+ + waitingElement
+ .getDynID()
+ + ";");
+ output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
+ + waitingElement.getStatus()
+ + ", &(seseToIssue->common), pointer );");
+ }
+ } else {
+ output.println(" rentry=mlpCreateFineREntry(runningSESE->memoryQueueArray["+ queueID+ "],"
+ + waitingElement.getStatus()
+ + ", &(seseToIssue->common), (void*)&seseToIssue->"
+ + waitingElement.getDynID()
+ + ");");
+ }
+ }
+ output.println(" rentry->queue=runningSESE->memoryQueueArray["
+ + waitingElement.getQueueID()
+ + "];");
+
+ if(enqueueType==SESEWaitingQueue.NORMAL) {
+ output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
+ output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["
+ + waitingElement.getQueueID()
+ + "],rentry)==NOTREADY) {");
+ output.println(" localCount++;");
+ output.println(" }");
+ } else {
+ output.println(" ADDRENTRYTOBUF(runningSESE->memoryQueueArray[" + waitingElement.getQueueID() + "],rentry);");
+ }
+ }
+ if(enqueueType!=SESEWaitingQueue.NORMAL) {
+ output.println(" localCount+=RESOLVEBUF(runningSESE->memoryQueueArray["
+ + queueID+ "],&seseToIssue->common);");
+ }
+ }
+ output.println(" } break; // end case "+parent.getIdentifier());
+ output.println();
+ }
+
+ if( atLeastOneCase ) {
+ output.println(" } // end stall site switch");
+ }
}
if( state.COREPROF ) {
- output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
- output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_END );");
- output.println("#endif");
+ output.println("#ifdef CP_EVENTID_PREPAREMEMQ");
+ output.println(" CP_LOGEVENT( CP_EVENTID_PREPAREMEMQ, CP_EVENTTYPE_END );");
+ output.println("#endif");
}
}
// Enqueue Task Record
if (state.RCR) {
if( fsen != oooa.getMainSESE() && fsen.getInVarsForDynamicCoarseConflictResolution().size()>0) {
- output.println(" enqueueTR(TRqueue, (void *)seseToIssue);");
+ output.println(" enqueueTR(TRqueue, (void *)seseToIssue);");
}
}
ConflictGraph graph = oooa.getConflictGraph(parent);
if( graph != null && graph.hasConflictEdge() ) {
- Set<SESELock> seseLockSet = oooa.getLockMappings(graph);
- SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(newChild.getIdentifier(), seseLockSet);
- if(seseWaitingQueue.getWaitingElementSize()>0) {
+ Set<SESELock> seseLockSet = oooa.getLockMappings(graph);
+ SESEWaitingQueue seseWaitingQueue=graph.getWaitingElementSetBySESEID(newChild.getIdentifier(), seseLockSet);
+ if(seseWaitingQueue.getWaitingElementSize()>0) {
- output.println(" /* "+parent.getPrettyIdentifier()+" */");
- output.println(" case "+parent.getIdentifier()+": {");
+ output.println(" /* "+parent.getPrettyIdentifier()+" */");
+ output.println(" case "+parent.getIdentifier()+": {");
- output.println(" REntry* rentry=NULL;");
- output.println(" INTPTR* pointer=NULL;");
- output.println(" seseToIssue->common.rentryIdx=0;");
- Vector<TempDescriptor> invars=newChild.getInVarsForDynamicCoarseConflictResolution();
- //System.out.println(fm.getMethod()+"["+invars+"]");
+ output.println(" REntry* rentry=NULL;");
+ output.println(" INTPTR* pointer=NULL;");
+ output.println(" seseToIssue->common.rentryIdx=0;");
+ Vector<TempDescriptor> invars=newChild.getInVarsForDynamicCoarseConflictResolution();
+ //System.out.println(fm.getMethod()+"["+invars+"]");
- Vector<Long> queuetovar=new Vector<Long>();
+ Vector<Long> queuetovar=new Vector<Long>();
- for(int i=0; i<invars.size(); i++) {
- TempDescriptor td=invars.get(i);
- Set<WaitingElement> weset=seseWaitingQueue.getWaitingElementSet(td);
+ for(int i=0; i<invars.size(); i++) {
+ TempDescriptor td=invars.get(i);
+ Set<WaitingElement> weset=seseWaitingQueue.getWaitingElementSet(td);
- //TODO FIX MEEEEE!!!!
- //Weset is sometimes null which breaks the following code and
- //we don't know what weset = null means. For now, we bail when it's null
- //until we find out what to do....
+ //TODO FIX MEEEEE!!!!
+ //Weset is sometimes null which breaks the following code and
+ //we don't know what weset = null means. For now, we bail when it's null
+ //until we find out what to do....
// if(weset == null) {
// continue;
// }
- //UPDATE: This hack DOES NOT FIX IT!.
-
-
-
- int numqueues=0;
- Set<Integer> queueSet=new HashSet<Integer>();
- for (Iterator iterator = weset.iterator(); iterator.hasNext(); ) {
- WaitingElement we = (WaitingElement) iterator.next();
- Integer queueID=new Integer(we.getQueueID());
- if(!queueSet.contains(queueID)) {
- numqueues++;
- queueSet.add(queueID);
- }
- }
-
- output.println(" seseToIssue->rcrRecords["+i+"].flag="+numqueues+";");
- output.println(" seseToIssue->rcrRecords["+i+"].index=0;");
- output.println(" seseToIssue->rcrRecords["+i+"].next=NULL;");
- output.println(" int dispCount"+i+"=0;");
-
- for (Iterator<WaitingElement> wtit = weset.iterator(); wtit.hasNext(); ) {
- WaitingElement waitingElement = wtit.next();
- int queueID = waitingElement.getQueueID();
- if (queueID >= queuetovar.size())
- queuetovar.setSize(queueID + 1);
- Long l = queuetovar.get(queueID);
- long val = (l != null)?l.longValue():0;
- val = val | (1 << i);
- queuetovar.set(queueID, new Long(val));
- }
- }
-
- HashSet generatedqueueentry=new HashSet();
- for(int i=0; i<invars.size(); i++) {
- TempDescriptor td=invars.get(i);
- Set<WaitingElement> weset=seseWaitingQueue.getWaitingElementSet(td);
-
-
-
- //TODO FIX MEEEEE!!!!
- //Weset is sometimes null which breaks the following code and
- //we don't know what weset = null means. For now, we bail when it's null
- //until we find out what to do....
+ //UPDATE: This hack DOES NOT FIX IT!.
+
+
+
+ int numqueues=0;
+ Set<Integer> queueSet=new HashSet<Integer>();
+ for (Iterator iterator = weset.iterator(); iterator.hasNext(); ) {
+ WaitingElement we = (WaitingElement) iterator.next();
+ Integer queueID=new Integer(we.getQueueID());
+ if(!queueSet.contains(queueID)) {
+ numqueues++;
+ queueSet.add(queueID);
+ }
+ }
+
+ output.println(" seseToIssue->rcrRecords["+i+"].flag="+numqueues+";");
+ output.println(" seseToIssue->rcrRecords["+i+"].index=0;");
+ output.println(" seseToIssue->rcrRecords["+i+"].next=NULL;");
+ output.println(" int dispCount"+i+"=0;");
+
+ for (Iterator<WaitingElement> wtit = weset.iterator(); wtit.hasNext(); ) {
+ WaitingElement waitingElement = wtit.next();
+ int queueID = waitingElement.getQueueID();
+ if (queueID >= queuetovar.size())
+ queuetovar.setSize(queueID + 1);
+ Long l = queuetovar.get(queueID);
+ long val = (l != null)?l.longValue():0;
+ val = val | (1 << i);
+ queuetovar.set(queueID, new Long(val));
+ }
+ }
+
+ HashSet generatedqueueentry=new HashSet();
+ for(int i=0; i<invars.size(); i++) {
+ TempDescriptor td=invars.get(i);
+ Set<WaitingElement> weset=seseWaitingQueue.getWaitingElementSet(td);
+
+
+
+ //TODO FIX MEEEEE!!!!
+ //Weset is sometimes null which breaks the following code and
+ //we don't know what weset = null means. For now, we bail when it's null
+ //until we find out what to do....
// if(weset == null) {
// continue;
// }
- //UPDATE: This hack DOES NOT FIX IT!.
-
-
-
- for(Iterator<WaitingElement> wtit=weset.iterator(); wtit.hasNext(); ) {
- WaitingElement waitingElement=wtit.next();
- int queueID=waitingElement.getQueueID();
-
- if(waitingElement.isBogus()) {
- continue;
- }
-
- if (generatedqueueentry.contains(queueID))
- continue;
- else
- generatedqueueentry.add(queueID);
-
- assert(waitingElement.getStatus()>=ConflictNode.COARSE);
- long mask=queuetovar.get(queueID);
- output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "]," + waitingElement.getStatus() + ", &(seseToIssue->common), "+mask+"LL);");
- output.println(" rentry->count=2;");
- output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
- output.println(" rentry->queue=runningSESE->memoryQueueArray[" + waitingElement.getQueueID()+"];");
-
- output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],rentry)==READY) {");
- for(int j=0; mask!=0; j++) {
- if ((mask&1)==1)
- output.println(" dispCount"+j+"++;");
- mask=mask>>1;
- }
- output.println(" } else ");
- output.println(" refCount--;");
- }
-
- if (newChild.getDynamicInVarSet().contains(td)) {
- // dynamic in-var case
- //output.println(" pointer=seseToIssue->"+waitingElement.getDynID()+
- // "_srcSESE+seseToIssue->"+waitingElement.getDynID()+
- // "_srcOffset;");
- //output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+
- // ", &(seseToIssue->common), pointer );");
- }
- }
- for(int i=0; i<invars.size(); i++) {
- output.println(" if(!dispCount"+i+" || !atomic_sub_and_test(dispCount"+i+",&(seseToIssue->rcrRecords["+i+"].flag)))");
- output.println(" localCount++;");
- }
- output.println(" } break;");
- }
+ //UPDATE: This hack DOES NOT FIX IT!.
+
+
+
+ for(Iterator<WaitingElement> wtit=weset.iterator(); wtit.hasNext(); ) {
+ WaitingElement waitingElement=wtit.next();
+ int queueID=waitingElement.getQueueID();
+
+ if(waitingElement.isBogus()) {
+ continue;
+ }
+
+ if (generatedqueueentry.contains(queueID))
+ continue;
+ else
+ generatedqueueentry.add(queueID);
+
+ assert(waitingElement.getStatus()>=ConflictNode.COARSE);
+ long mask=queuetovar.get(queueID);
+ output.println(" rentry=mlpCreateREntry(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "]," + waitingElement.getStatus() + ", &(seseToIssue->common), "+mask+"LL);");
+ output.println(" rentry->count=2;");
+ output.println(" seseToIssue->common.rentryArray[seseToIssue->common.rentryIdx++]=rentry;");
+ output.println(" rentry->queue=runningSESE->memoryQueueArray[" + waitingElement.getQueueID()+"];");
+
+ output.println(" if(ADDRENTRY(runningSESE->memoryQueueArray["+ waitingElement.getQueueID()+ "],rentry)==READY) {");
+ for(int j=0; mask!=0; j++) {
+ if ((mask&1)==1)
+ output.println(" dispCount"+j+"++;");
+ mask=mask>>1;
+ }
+ output.println(" } else ");
+ output.println(" refCount--;");
+ }
+
+ if (newChild.getDynamicInVarSet().contains(td)) {
+ // dynamic in-var case
+ //output.println(" pointer=seseToIssue->"+waitingElement.getDynID()+
+ // "_srcSESE+seseToIssue->"+waitingElement.getDynID()+
+ // "_srcOffset;");
+ //output.println(" rentry=mlpCreateFineREntry("+ waitingElement.getStatus()+
+ // ", &(seseToIssue->common), pointer );");
+ }
+ }
+ for(int i=0; i<invars.size(); i++) {
+ output.println(" if(!dispCount"+i+" || !atomic_sub_and_test(dispCount"+i+",&(seseToIssue->rcrRecords["+i+"].flag)))");
+ output.println(" localCount++;");
+ }
+ output.println(" } break;");
+ }
}
}
temp.getType().isPrimitive() && !temp.getType().isArray()
)
) {
- continue;
+ continue;
}
String from = generateTemp(fsen.getfmBogus(), temp);
output.println(" struct Hashtable_rcr ** hashstruct=runningSESE->parent->allHashStructures;");
for (int i = 0; i < inset.size(); i++) {
- output.println(" rec=&" + paramsprefix + "->rcrRecords[" + i + "];");
- output.println(" while(rec!=NULL) {");
- output.println(" for(idx2=0;idx2<rec->index;idx2++) {");
+ output.println(" rec=&" + paramsprefix + "->rcrRecords[" + i + "];");
+ output.println(" while(rec!=NULL) {");
+ output.println(" for(idx2=0;idx2<rec->index;idx2++) {");
- int weaklyConnectedComponentIndex = rcr.getWeakID(inset.get(i), fsen);
+ int weaklyConnectedComponentIndex = rcr.getWeakID(inset.get(i), fsen);
- output.println(" rcr_RETIREHASHTABLE(hashstruct[" + weaklyConnectedComponentIndex
- + "],&(___params___->common), rec->array[idx2], (BinItem_rcr *) rec->ptrarray[idx2]);");
+ output.println(" rcr_RETIREHASHTABLE(hashstruct[" + weaklyConnectedComponentIndex
+ + "],&(___params___->common), rec->array[idx2], (BinItem_rcr *) rec->ptrarray[idx2]);");
- output.println(" }"); // exit idx2 for loop
- output.println(" rec=rec->next;");
- output.println(" }"); // exit rec while loop
+ output.println(" }"); // exit idx2 for loop
+ output.println(" rec=rec->next;");
+ output.println(" }"); // exit rec while loop
}
output.println("}");
}
if( !fsen.getIsLeafSESE() ) {
output.println(" pooldestroy( runningSESE->taskRecordMemPool );");
if (state.RCR && fsen.getInVarsForDynamicCoarseConflictResolution().size() > 0 ) {
- output.println(" returnTR();");
+ output.println(" returnTR();");
}
}
output.println("#endif // OOO_DISABLE_TASKMEMPOOL");
output.println(" SESEcommon* oldSrc = "+refVar+"_srcSESE;");
if( vst == null ) {
- // if there is no given source, this variable is ready so
- // mark src pointer NULL to signify that the var is up-to-date
- output.println(" "+refVar+"_srcSESE = NULL;");
+ // if there is no given source, this variable is ready so
+ // mark src pointer NULL to signify that the var is up-to-date
+ output.println(" "+refVar+"_srcSESE = NULL;");
} else {
- // otherwise we track where it will come from
- SESEandAgePair instance = new SESEandAgePair(vst.getSESE(), vst.getAge() );
- output.println(" "+refVar+"_srcSESE = "+instance+";");
- output.println(" "+refVar+"_srcOffset = (INTPTR) &((("+
- vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
+ // otherwise we track where it will come from
+ SESEandAgePair instance = new SESEandAgePair(vst.getSESE(), vst.getAge() );
+ output.println(" "+refVar+"_srcSESE = "+instance+";");
+ output.println(" "+refVar+"_srcOffset = (INTPTR) &((("+
+ vst.getSESE().getSESErecordName()+"*)0)->"+vst.getAddrVar()+");");
}
// no matter what we did above, track reference count of whatever
int arrayid = state.getArrayNumber(fn.getType() )+state.numClasses();
if( GENERATEPRECISEGC ) {
- output.println(generateTemp(fm, fn.getDst())+
- "=allocate_newarray_mlp("+localsprefixaddr+
- ", "+arrayid+", "+generateTemp(fm, fn.getSize())+
- ", oid, "+
- oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+
- ");");
- output.println(" oid += oidIncrement;");
+ output.println(generateTemp(fm, fn.getDst())+
+ "=allocate_newarray_mlp("+localsprefixaddr+
+ ", "+arrayid+", "+generateTemp(fm, fn.getSize())+
+ ", oid, "+
+ oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+
+ ");");
+ output.println(" oid += oidIncrement;");
} else {
- output.println(generateTemp(fm, fn.getDst())+
- "=allocate_newarray("+arrayid+
- ", "+generateTemp(fm, fn.getSize())+
- ");");
+ output.println(generateTemp(fm, fn.getDst())+
+ "=allocate_newarray("+arrayid+
+ ", "+generateTemp(fm, fn.getSize())+
+ ");");
}
} else {
// not an array
if( GENERATEPRECISEGC ) {
- output.println(generateTemp(fm, fn.getDst())+
- "=allocate_new_mlp("+localsprefixaddr+
- ", "+fn.getType().getClassDesc().getId()+
- ", oid, "+
- oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+
- ");");
- output.println(" oid += oidIncrement;");
+ output.println(generateTemp(fm, fn.getDst())+
+ "=allocate_new_mlp("+localsprefixaddr+
+ ", "+fn.getType().getClassDesc().getId()+
+ ", oid, "+
+ oooa.getDisjointAnalysis().getAllocationSiteFromFlatNew(fn).getUniqueAllocSiteID()+
+ ");");
+ output.println(" oid += oidIncrement;");
} else {
- output.println(generateTemp(fm, fn.getDst())+
- "=allocate_new("+fn.getType().getClassDesc().getId()+
- ");");
+ output.println(generateTemp(fm, fn.getDst())+
+ "=allocate_new("+fn.getType().getClassDesc().getId()+
+ ");");
}
}
}
for (Iterator iterator = fsen.getInVarSet().iterator(); iterator.hasNext(); ) {
TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()) {
- tdSet.add(tempDescriptor);
+ tdSet.add(tempDescriptor);
}
}
for (Iterator iterator = fsen.getOutVarSet().iterator(); iterator.hasNext(); ) {
TempDescriptor tempDescriptor = (TempDescriptor) iterator.next();
if(!tempDescriptor.getType().isPrimitive() || tempDescriptor.getType().isArray()) {
- tdSet.add(tempDescriptor);
+ tdSet.add(tempDescriptor);
}
}
TempDescriptor temp = itr.next();
TypeDescriptor type = temp.getType();
if( !type.isPtr() ) {
- inSetAndOutSetPrims.add(temp);
+ inSetAndOutSetPrims.add(temp);
}
}
TempDescriptor temp = itrPrims.next();
TypeDescriptor type = temp.getType();
if(type.isPrimitive()) {
- Integer count=map.get(type.getSymbol());
- if(count==null) {
- count=new Integer(1);
- map.put(type.getSymbol(), count);
- } else {
- map.put(type.getSymbol(), new Integer(count.intValue()+1));
- }
+ Integer count=map.get(type.getSymbol());
+ if(count==null) {
+ count=new Integer(1);
+ map.put(type.getSymbol(), count);
+ } else {
+ map.put(type.getSymbol(), new Integer(count.intValue()+1));
+ }
}
}
while(it_sifs.hasNext()) {
ClassDescriptor sif = (ClassDescriptor)it_sifs.next();
if (!namemap.containsKey(sif))
- handleClass(sif, state, namemap);
+ handleClass(sif, state, namemap);
}
HashMap<String, Integer> supermap=cd.getSuperDesc()!=null?namemap.get(cd.getSuperDesc()):new HashMap<String, Integer>();
for(Iterator fieldit=cd.getFields(); fieldit.hasNext(); ) {
FieldDescriptor fd=(FieldDescriptor)fieldit.next();
if (supermap.containsKey(fd.getSymbol())) {
- Integer oldint=supermap.get(fd.getSymbol());
- int newint=oldint.intValue()+1;
- fieldmap.put(fd.getSymbol(), new Integer(newint));
- fd.changeSafeSymbol(newint);
+ Integer oldint=supermap.get(fd.getSymbol());
+ int newint=oldint.intValue()+1;
+ fieldmap.put(fd.getSymbol(), new Integer(newint));
+ fd.changeSafeSymbol(newint);
} else {
- // the fields in interfaces are defaultely static & final, so do not need to
- // check them, they will always have the interface name as prefix
- fieldmap.put(fd.getSymbol(), new Integer(0));
+ // the fields in interfaces are defaultely static & final, so do not need to
+ // check them, they will always have the interface name as prefix
+ fieldmap.put(fd.getSymbol(), new Integer(0));
}
}
}
if( tdParamI.equals(tdParam) ) {
- if( method.isStatic() ) {
- return args[i];
- }
+ if( method.isStatic() ) {
+ return args[i];
+ }
- if( i == 0 ) {
- return this_temp;
- }
+ if( i == 0 ) {
+ return this_temp;
+ }
- return args[i-1];
+ return args[i-1];
}
}
String st="FlatCall_";
if (dst==null) {
if (method==null)
- st+="null(";
+ st+="null(";
else
- st+=method.getSymbol()+"(";
+ st+=method.getSymbol()+"(";
} else
st+=dst+"="+method.getSymbol()+"(";
if (this_temp!=null) {
st+=this_temp;
if (args.length!=0)
- st+=", ";
+ st+=", ";
}
for(int i=0; i<args.length; i++) {
st+=args[i].toString();
if ((i+1)<args.length)
- st+=", ";
+ st+=", ";
}
return st+")";
}
else {
HashSet temps=new HashSet();
for(Iterator it=tempflagpairs.keySet().iterator(); it.hasNext(); ) {
- TempFlagPair tfp=(TempFlagPair)it.next();
- temps.add(tfp.getTemp());
+ 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());
+ TempTagPair ttp=(TempTagPair)it.next();
+ temps.add(ttp.getTemp());
+ temps.add(ttp.getTagTemp());
}
return (TempDescriptor[])temps.toArray(new TempDescriptor [temps.size()]);
}
for(int i=0; i<st.length(); i++) {
char x=st.charAt(i);
if (x=='\n')
- new_st+="\\n";
+ new_st+="\\n";
else if (x=='\r')
- new_st+="\\r";
+ new_st+="\\r";
else if (x=='"')
- new_st+="\\\"";
+ new_st+="\\\"";
else if (x=='\'')
- new_st+="\\\'";
+ new_st+="\\\'";
else if (x=='\\')
- new_st+="\\\\";
+ new_st+="\\\\";
else new_st+=x;
}
return new_st;
boolean first=true;
for(int i=0; i<numParameters(); i++) {
if (first) {
- first=false;
+ first=false;
} else
- ret+=", ";
+ ret+=", ";
ret+=getParameter(i);
}
ret+=")";
for(Iterator<FlatNode> setit=set.iterator(); setit.hasNext(); ) {
FlatNode fn=setit.next();
for(int i=0; i<fn.numPrev(); i++) {
- FlatNode fnprev=fn.getPrev(i);
- if (!set.contains(fnprev)) {
- System.out.println(fn+" has unreachable parent:"+i+" "+fnprev);
- System.out.println(printMethod());
- throw new Error();
+ FlatNode fnprev=fn.getPrev(i);
+ if (!set.contains(fnprev)) {
+ System.out.println(fn+" has unreachable parent:"+i+" "+fnprev);
+ System.out.println(printMethod());
+ throw new Error();
- }
+ }
}
}
}
tovisit.remove(fn);
visited.add(fn);
for(int i=0; i<fn.numNext(); i++) {
- FlatNode nn=fn.getNext(i);
- if (nn==null)
- continue;
- if (!visited.contains(nn))
- tovisit.add(nn);
+ FlatNode nn=fn.getNext(i);
+ if (nn==null)
+ continue;
+ if (!visited.contains(nn))
+ tovisit.add(nn);
}
}
return visited;
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++));
- }
+ 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++));
+ }
}
}
tovisit.add(this);
while(current_node!=null||!tovisit.isEmpty()) {
if (current_node==null) {
- current_node=(FlatNode)tovisit.iterator().next();
- tovisit.remove(current_node);
+ current_node=(FlatNode)tovisit.iterator().next();
+ tovisit.remove(current_node);
} else {
- if (tovisit.contains(current_node))
- tovisit.remove(current_node);
+ if (tovisit.contains(current_node))
+ tovisit.remove(current_node);
}
visited.add(current_node);
if (nodetolabel.containsKey(current_node)) {
- st+="L"+nodetolabel.get(current_node)+":\n";
- for(int i=0; i<current_node.numPrev(); i++) {
- st+="i="+i+" "+current_node.getPrev(i);
- }
- st+="\n";
+ st+="L"+nodetolabel.get(current_node)+":\n";
+ for(int i=0; i<current_node.numPrev(); i++) {
+ st+="i="+i+" "+current_node.getPrev(i);
+ }
+ st+="\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;
+ 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;
+ 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);
+ /* 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";
tovisit.remove(fn);
visited.add(fn);
if (endset!=null&&!endset.contains(fn)) {
- for(int i=0; i<fn.numNext(); i++) {
- FlatNode nn=fn.getNext(i);
- if (!visited.contains(nn))
- tovisit.add(nn);
- }
+ for(int i=0; i<fn.numNext(); i++) {
+ FlatNode nn=fn.getNext(i);
+ if (!visited.contains(nn))
+ tovisit.add(nn);
+ }
}
}
return visited;
FlatNode nprev=(FlatNode)prev.get(i);
fnnew.prev.set(i,nprev);
for(int j=0; j<nprev.numNext(); j++) {
- FlatNode n=nprev.getNext(j);
- if (n==this)
- nprev.next.set(j, fnnew);
+ FlatNode n=nprev.getNext(j);
+ if (n==this)
+ nprev.next.set(j, fnnew);
}
}
for(int i=0; i<next.size(); i++) {
FlatNode nnext=(FlatNode)next.get(i);
fnnew.next.set(i,nnext);
for(int j=0; j<nnext.numPrev(); j++) {
- FlatNode n=nnext.getPrev(j);
- if (n==this)
- nnext.prev.set(j, fnnew);
+ FlatNode n=nnext.getPrev(j);
+ if (n==this)
+ nnext.prev.set(j, fnnew);
}
}
next=null;
for(Iterator<PrefetchPair> it=hspp.iterator(); it.hasNext(); ) {
PrefetchPair pp=it.next();
if (!first)
- st+=", ";
+ st+=", ";
first=false;
st+=pp;
}
visited.add(fn);
if (fn!=exit) {
- for(int i=0; i<fn.numNext(); i++) {
- FlatNode nn=fn.getNext(i);
- if (!visited.contains(nn))
- tovisit.add(nn);
- }
+ for(int i=0; i<fn.numNext(); i++) {
+ FlatNode nn=fn.getNext(i);
+ if (!visited.contains(nn))
+ tovisit.add(nn);
+ }
}
}
return visited;
headNode.removePrev(tailNode);
if(tailNode.next.elementAt(0).equals(headNode)) {
- tailNode.removeNext(headNode);
- ((FlatCondBranch)tailNode).addTrueNext(this);
+ tailNode.removeNext(headNode);
+ ((FlatCondBranch)tailNode).addTrueNext(this);
} else {
- tailNode.removeNext(headNode);
- ((FlatCondBranch)tailNode).addFalseNext(this);
+ tailNode.removeNext(headNode);
+ ((FlatCondBranch)tailNode).addFalseNext(this);
}
this.addNext(headNode);
FlatNode fn=toprocess.pop();
int atomicval=atomictable.get(fn).intValue();
if (fn.kind()==FKind.FlatAtomicEnterNode)
- atomicval++;
+ atomicval++;
else if(fn.kind()==FKind.FlatAtomicExitNode)
- atomicval--;
+ atomicval--;
for(int i=0; i<fn.numNext(); i++) {
- FlatNode fnext=fn.getNext(i);
- if (!visited.contains(fnext)) {
- atomictable.put(fnext, new Integer(atomicval));
- if (atomicval>0)
- atomicset.add(fnext);
- visited.add(fnext);
- toprocess.push(fnext);
- }
+ FlatNode fnext=fn.getNext(i);
+ if (!visited.contains(fnext)) {
+ atomictable.put(fnext, new Integer(atomicval));
+ if (atomicval>0)
+ atomicset.add(fnext);
+ visited.add(fnext);
+ toprocess.push(fnext);
+ }
}
}
//make depth 0 be depth infinity
for(Iterator<FlatNode> fnit=fnset.iterator(); fnit.hasNext(); ) {
FlatNode fn=fnit.next();
if (fn.kind()==FKind.FlatCall) {
- FlatCall fc=(FlatCall)fn;
- MethodDescriptor md=fc.getMethod();
+ FlatCall fc=(FlatCall)fn;
+ MethodDescriptor md=fc.getMethod();
- if (toexclude.contains(md))
- continue;
+ if (toexclude.contains(md))
+ continue;
- Set<FlatNode> inlinefnset=inline(fc, typeutil, state);
- if (inlinefnset==null)
- continue;
+ Set<FlatNode> inlinefnset=inline(fc, typeutil, state);
+ if (inlinefnset==null)
+ continue;
- toexclude.push(md);
- if (depth>1)
- recursive(state, typeutil, inlinefnset, depth-1, toexclude);
- toexclude.pop();
+ toexclude.push(md);
+ if (depth>1)
+ recursive(state, typeutil, inlinefnset, depth-1, toexclude);
+ toexclude.pop();
}
}
}
//Build the clones
for(Iterator<FlatNode> fnit=nodeset.iterator(); fnit.hasNext(); ) {
- FlatNode fn=fnit.next();
- if (fn.kind()==FKind.FlatReturnNode) {
- //Convert FlatReturn node into move
- TempDescriptor rtmp=((FlatReturnNode)fn).getReturnTemp();
- if (rtmp!=null) {
- FlatOpNode fon=new FlatOpNode(rettmp, rtmp, null, new Operation(Operation.ASSIGN));
- flatmap.put(fn, fon);
- } else {
- flatmap.put(fn, aftercallnode);
- }
- } else {
- FlatNode clone=fn.clone(clonemap);
- newnodes.add(clone);
- flatmap.put(fn,clone);
- }
+ FlatNode fn=fnit.next();
+ if (fn.kind()==FKind.FlatReturnNode) {
+ //Convert FlatReturn node into move
+ TempDescriptor rtmp=((FlatReturnNode)fn).getReturnTemp();
+ if (rtmp!=null) {
+ FlatOpNode fon=new FlatOpNode(rettmp, rtmp, null, new Operation(Operation.ASSIGN));
+ flatmap.put(fn, fon);
+ } else {
+ flatmap.put(fn, aftercallnode);
+ }
+ } else {
+ FlatNode clone=fn.clone(clonemap);
+ newnodes.add(clone);
+ flatmap.put(fn,clone);
+ }
}
//Build the move chain
FlatNode first=new FlatNop();;
newnodes.add(first);
FlatNode last=first;
{
- int i=0;
- if (fc.getThis()!=null) {
- FlatOpNode fon=new FlatOpNode(fm.getParameter(i++), fc.getThis(), null, new Operation(Operation.ASSIGN));
- newnodes.add(fon);
- last.addNext(fon);
- last=fon;
- }
- for(int j=0; j<fc.numArgs(); i++,j++) {
- FlatOpNode fon=new FlatOpNode(fm.getParameter(i), fc.getArg(j), null, new Operation(Operation.ASSIGN));
- newnodes.add(fon);
- last.addNext(fon);
- last=fon;
- }
+ int i=0;
+ if (fc.getThis()!=null) {
+ FlatOpNode fon=new FlatOpNode(fm.getParameter(i++), fc.getThis(), null, new Operation(Operation.ASSIGN));
+ newnodes.add(fon);
+ last.addNext(fon);
+ last=fon;
+ }
+ for(int j=0; j<fc.numArgs(); i++,j++) {
+ FlatOpNode fon=new FlatOpNode(fm.getParameter(i), fc.getArg(j), null, new Operation(Operation.ASSIGN));
+ newnodes.add(fon);
+ last.addNext(fon);
+ last=fon;
+ }
}
//Add the edges
for(Iterator<FlatNode> fnit=nodeset.iterator(); fnit.hasNext(); ) {
- FlatNode fn=fnit.next();
- FlatNode fnclone=flatmap.get(fn);
-
- if (fn.kind()!=FKind.FlatReturnNode) {
- //don't build old edges out of a flat return node
- for(int i=0; i<fn.numNext(); i++) {
- FlatNode fnnext=fn.getNext(i);
- FlatNode fnnextclone=flatmap.get(fnnext);
- fnclone.setNewNext(i, fnnextclone);
- }
- } else {
- if (fnclone!=aftercallnode)
- fnclone.addNext(aftercallnode);
- }
+ FlatNode fn=fnit.next();
+ FlatNode fnclone=flatmap.get(fn);
+
+ if (fn.kind()!=FKind.FlatReturnNode) {
+ //don't build old edges out of a flat return node
+ for(int i=0; i<fn.numNext(); i++) {
+ FlatNode fnnext=fn.getNext(i);
+ FlatNode fnnextclone=flatmap.get(fnnext);
+ fnclone.setNewNext(i, fnnextclone);
+ }
+ } else {
+ if (fnclone!=aftercallnode)
+ fnclone.addNext(aftercallnode);
+ }
}
//Add edges to beginning of move chain
for(int i=0; i<fc.numPrev(); i++) {
- FlatNode fnprev=fc.getPrev(i);
- for(int j=0; j<fnprev.numNext(); j++) {
- if (fnprev.getNext(j)==fc) {
- //doing setnewnext to avoid changing the node we are
- //iterating over
- fnprev.setNewNext(j, first);
- break;
- }
- }
+ FlatNode fnprev=fc.getPrev(i);
+ for(int j=0; j<fnprev.numNext(); j++) {
+ if (fnprev.getNext(j)==fc) {
+ //doing setnewnext to avoid changing the node we are
+ //iterating over
+ fnprev.setNewNext(j, first);
+ break;
+ }
+ }
}
//Add in the edge from move chain to callee
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;
+ MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
+ if (md.matches(matchmd))
+ return false;
}
}
return true;
//if the task is the main task, there's no traverser
if(task.isMainSESE)
- return;
+ return;
blockName = task.getPrettyIdentifier();
}
for(SMFEState state : smfe.getStates()) {
if(state.getRefCount() != 1 || initialState == state) {
- if (needswitch) {
- cFile.println(" case "+state.getID()+":");
- } else {
- cFile.println(" if(traverserState=="+state.getID()+") {");
- }
+ if (needswitch) {
+ cFile.println(" case "+state.getID()+":");
+ } else {
+ cFile.println(" if(traverserState=="+state.getID()+") {");
+ }
- printAllocChecksInsideState(smfe, state, taskOrStallSite, var, "ptr", 0, weakID);
+ printAllocChecksInsideState(smfe, state, taskOrStallSite, var, "ptr", 0, weakID);
- cFile.println(" break;");
+ cFile.println(" break;");
}
}
//we assume that all allocs given in the effects are starting locs.
for(Alloc a : et.getAllAllocs()) {
if (needswitch) {
- cFile.println(" case "+a.getUniqueAllocSiteID()+": {");
+ cFile.println(" case "+a.getUniqueAllocSiteID()+": {");
} else {
- cFile.println(" if("+prefix+"->"+allocSite+"=="+a.getUniqueAllocSiteID()+") {");
+ cFile.println(" if("+prefix+"->"+allocSite+"=="+a.getUniqueAllocSiteID()+") {");
}
addChecker(smfe, a, fn, tmp, state, et, prefix, depth, weakID);
if (needswitch) {
- cFile.println(" }");
- cFile.println(" break;");
+ cFile.println(" }");
+ cFile.println(" break;");
}
}
if (needswitch) {
boolean first=true;
for(Effect e : et.getEffects(a)) {
- if (!state.transitionsTo(e).isEmpty()) {
- if (first) {
- cFile.println(" int i;");
- cFile.println(" struct ___Object___ * "+currPtr+";");
- cFile.println(" for(i = 0; i<((struct ArrayObject *) " + prefix + " )->___length___; i++ ) {");
- first=false;
- }
- printRefSwitch(smfe, fn, tmp, pdepth, childPtr, currPtr, state.transitionsTo(e), weakID);
-
- // only if we are traversing for a new task, not a stall site
- if( (fn instanceof FlatSESEEnterNode) &&
- smfe.getPossiblyEvilEffects().contains(e) ) {
-
- FlatSESEEnterNode evilTask = (FlatSESEEnterNode)fn;
-
- detectPossiblyEvilExecution(evilTask,
- evilTask.getInVarsForDynamicCoarseConflictResolution().indexOf(tmp)
- );
- }
- }
+ if (!state.transitionsTo(e).isEmpty()) {
+ if (first) {
+ cFile.println(" int i;");
+ cFile.println(" struct ___Object___ * "+currPtr+";");
+ cFile.println(" for(i = 0; i<((struct ArrayObject *) " + prefix + " )->___length___; i++ ) {");
+ first=false;
+ }
+ printRefSwitch(smfe, fn, tmp, pdepth, childPtr, currPtr, state.transitionsTo(e), weakID);
+
+ // only if we are traversing for a new task, not a stall site
+ if( (fn instanceof FlatSESEEnterNode) &&
+ smfe.getPossiblyEvilEffects().contains(e) ) {
+
+ FlatSESEEnterNode evilTask = (FlatSESEEnterNode)fn;
+
+ detectPossiblyEvilExecution(evilTask,
+ evilTask.getInVarsForDynamicCoarseConflictResolution().indexOf(tmp)
+ );
+ }
+ }
}
if (!first)
- cFile.println("}");
+ cFile.println("}");
} else {
//All other cases
String currPtr = "myPtr" + pdepth;
cFile.println(" struct ___Object___ * "+currPtr+";");
for(Effect e : et.getEffects(a)) {
- if (!state.transitionsTo(e).isEmpty()) {
- String childPtr = "((struct "+a.getType().getSafeSymbol()+" *)"+prefix +")->" + e.getField().getSafeSymbol();
- printRefSwitch(smfe, fn, tmp, pdepth, childPtr, currPtr, state.transitionsTo(e), weakID);
+ if (!state.transitionsTo(e).isEmpty()) {
+ String childPtr = "((struct "+a.getType().getSafeSymbol()+" *)"+prefix +")->" + e.getField().getSafeSymbol();
+ printRefSwitch(smfe, fn, tmp, pdepth, childPtr, currPtr, state.transitionsTo(e), weakID);
- // only if we are traversing for a new task, not a stall site
- if( (fn instanceof FlatSESEEnterNode) &&
- smfe.getPossiblyEvilEffects().contains(e) ) {
+ // only if we are traversing for a new task, not a stall site
+ if( (fn instanceof FlatSESEEnterNode) &&
+ smfe.getPossiblyEvilEffects().contains(e) ) {
- FlatSESEEnterNode evilTask = (FlatSESEEnterNode)fn;
+ FlatSESEEnterNode evilTask = (FlatSESEEnterNode)fn;
- detectPossiblyEvilExecution(evilTask,
- evilTask.getInVarsForDynamicCoarseConflictResolution().indexOf(tmp)
- );
- }
- }
+ detectPossiblyEvilExecution(evilTask,
+ evilTask.getInVarsForDynamicCoarseConflictResolution().indexOf(tmp)
+ );
+ }
+ }
}
}
}
for(SMFEState tr : transitions) {
if(tr.getRefCount() == 1) { //in-lineable case
- //Don't need to update state counter since we don't care really if it's inlined...
- cFile.println(" "+currPtr+"= (struct ___Object___ * ) " + childPtr + ";");
- cFile.println(" if (" + currPtr + " != NULL) { ");
+ //Don't need to update state counter since we don't care really if it's inlined...
+ cFile.println(" "+currPtr+"= (struct ___Object___ * ) " + childPtr + ";");
+ cFile.println(" if (" + currPtr + " != NULL) { ");
- printAllocChecksInsideState(smfe, tr, fn, tmp, currPtr, pdepth+1, weakID);
+ printAllocChecksInsideState(smfe, tr, fn, tmp, currPtr, pdepth+1, weakID);
- cFile.println(" }"); //break for internal switch and if
+ cFile.println(" }"); //break for internal switch and if
} else { //non-inlineable cases
- cFile.println(" "+currPtr+"= (struct ___Object___ * ) " + childPtr + ";");
- cFile.println(" if("+queryAndAddToVisitedHashtable+"("+currPtr+","+tr.getID()+"))");
- cFile.println(" " + enqueueInC +"("+ currPtr + ", "+tr.getID()+");");
+ cFile.println(" "+currPtr+"= (struct ___Object___ * ) " + childPtr + ";");
+ cFile.println(" if("+queryAndAddToVisitedHashtable+"("+currPtr+","+tr.getID()+"))");
+ cFile.println(" " + enqueueInC +"("+ currPtr + ", "+tr.getID()+");");
}
}
}
if(et.hasWriteConflict(a)) {
cFile.append(" int tmpkey" + depth + " = rcr_generateKey(" + prefix + ");\n");
if (et.conflictDereference(a))
- cFile.append(" int tmpvar" + depth + " = rcr_WTWRITEBINCASE(allHashStructures[" + weakID + "], tmpkey" + depth + ", " + tasksrc + strrcr + index + ");\n");
+ cFile.append(" int tmpvar" + depth + " = rcr_WTWRITEBINCASE(allHashStructures[" + weakID + "], tmpkey" + depth + ", " + tasksrc + strrcr + index + ");\n");
else
- cFile.append(" int tmpvar" + depth + " = rcr_WRITEBINCASE(allHashStructures["+ weakID + "], tmpkey" + depth + ", " + tasksrc + strrcr + index + ");\n");
+ cFile.append(" int tmpvar" + depth + " = rcr_WRITEBINCASE(allHashStructures["+ weakID + "], tmpkey" + depth + ", " + tasksrc + strrcr + index + ");\n");
} else if(et.hasReadConflict(a)) {
cFile.append(" int tmpkey" + depth + " = rcr_generateKey(" + prefix + ");\n");
if (et.conflictDereference(a))
- cFile.append(" int tmpvar" + depth + " = rcr_WTREADBINCASE(allHashStructures[" + weakID + "], tmpkey" + depth + ", " + tasksrc + strrcr + index + ");\n");
+ cFile.append(" int tmpvar" + depth + " = rcr_WTREADBINCASE(allHashStructures[" + weakID + "], tmpkey" + depth + ", " + tasksrc + strrcr + index + ");\n");
else
- cFile.append(" int tmpvar" + depth + " = rcr_READBINCASE(allHashStructures["+ weakID + "], tmpkey" + depth + ", " + tasksrc + strrcr + index + ");\n");
+ cFile.append(" int tmpvar" + depth + " = rcr_READBINCASE(allHashStructures["+ weakID + "], tmpkey" + depth + ", " + tasksrc + strrcr + index + ");\n");
}
if (et.hasReadConflict(a) || et.hasWriteConflict(a)) {
s.charAt(i) == '[' ||
s.charAt(i) == ']' ) {
- s.deleteCharAt(i);
- i--;
+ s.deleteCharAt(i);
+ i--;
}
}
return s.toString();
cFile.println(" "+fsen.getSESErecordName()+" * rec=("+fsen.getSESErecordName()+" *) record;");
Vector<TempDescriptor> invars=fsen.getInVarsForDynamicCoarseConflictResolution();
for(int i=0; i<invars.size(); i++) {
- TempDescriptor tmp=invars.get(i);
-
- /* In some cases we don't want to a dynamic traversal if it is
- * unlikely to increase parallelism...these are cases where we
- * are just enabling a stall site to possible clear faster*/
-
- boolean isValidToPrune=true;
- for( FlatSESEEnterNode parentSESE : fsen.getParents() ) {
- ConflictGraph graph = oooa.getConflictGraph(parentSESE);
- if(graph!=null) {
- String id = tmp + "_sese" + fsen.getPrettyIdentifier();
- ConflictNode node = graph.getId2cn().get(id);
- isValidToPrune &= node.IsValidToPrune();
- }
- }
-
- if(isValidToPrune) {
- // if node is valid to prune examiner,
- // also needs to turn off stall site examiners connected to this node
- for( FlatSESEEnterNode parentSESE : fsen.getParents() ) {
- ConflictGraph graph = oooa.getConflictGraph(parentSESE);
- String id = tmp + "_sese" + fsen.getPrettyIdentifier();
- ConflictNode node = graph.getId2cn().get(id);
-
- for (Iterator iterator = node.getEdgeSet().iterator(); iterator.hasNext(); ) {
- ConflictEdge edge = (ConflictEdge) iterator.next();
- if (edge.getVertexU() == node) {
- if (edge.getVertexV().isStallSiteNode()) {
- edge.getVertexV().setToBePruned(true);
- }
- } else {
- if (edge.getVertexU().isStallSiteNode()) {
- edge.getVertexU().setToBePruned(true);
- }
- }
- }
- }
- }
-
- if (i!=0) {
- cFile.println(" if (record->rcrstatus!=0)");
- }
-
- if(globalState.NOSTALLTR && isValidToPrune) {
- cFile.println(" /* " + getTraverserInvocation(tmp, "rec->"+tmp+", rec", fsen)+"*/");
- } else {
- cFile.println(" " + getTraverserInvocation(tmp, "rec->"+tmp+", rec", fsen));
- }
+ TempDescriptor tmp=invars.get(i);
+
+ /* In some cases we don't want to a dynamic traversal if it is
+ * unlikely to increase parallelism...these are cases where we
+ * are just enabling a stall site to possible clear faster*/
+
+ boolean isValidToPrune=true;
+ for( FlatSESEEnterNode parentSESE : fsen.getParents() ) {
+ ConflictGraph graph = oooa.getConflictGraph(parentSESE);
+ if(graph!=null) {
+ String id = tmp + "_sese" + fsen.getPrettyIdentifier();
+ ConflictNode node = graph.getId2cn().get(id);
+ isValidToPrune &= node.IsValidToPrune();
+ }
+ }
+
+ if(isValidToPrune) {
+ // if node is valid to prune examiner,
+ // also needs to turn off stall site examiners connected to this node
+ for( FlatSESEEnterNode parentSESE : fsen.getParents() ) {
+ ConflictGraph graph = oooa.getConflictGraph(parentSESE);
+ String id = tmp + "_sese" + fsen.getPrettyIdentifier();
+ ConflictNode node = graph.getId2cn().get(id);
+
+ for (Iterator iterator = node.getEdgeSet().iterator(); iterator.hasNext(); ) {
+ ConflictEdge edge = (ConflictEdge) iterator.next();
+ if (edge.getVertexU() == node) {
+ if (edge.getVertexV().isStallSiteNode()) {
+ edge.getVertexV().setToBePruned(true);
+ }
+ } else {
+ if (edge.getVertexU().isStallSiteNode()) {
+ edge.getVertexU().setToBePruned(true);
+ }
+ }
+ }
+ }
+ }
+
+ if (i!=0) {
+ cFile.println(" if (record->rcrstatus!=0)");
+ }
+
+ if(globalState.NOSTALLTR && isValidToPrune) {
+ cFile.println(" /* " + getTraverserInvocation(tmp, "rec->"+tmp+", rec", fsen)+"*/");
+ } else {
+ cFile.println(" " + getTraverserInvocation(tmp, "rec->"+tmp+", rec", fsen));
+ }
}
//release traverser reference...traversal finished...
//executing thread will clean bins for us
Set<FlatSESEEnterNode> seseSet=oooa.getPossibleExecutingRBlocks(stallsite);
boolean isValidToPrune=true;
for (Iterator iterator = seseSet.iterator(); iterator.hasNext(); ) {
- FlatSESEEnterNode sese = (FlatSESEEnterNode) iterator.next();
- ConflictGraph graph = oooa.getConflictGraph(sese);
- if(graph!=null) {
- String id = var + "_fn" + stallsite.hashCode();
- ConflictNode node = graph.getId2cn().get(id);
- isValidToPrune &= node.isTobePruned();
- }
+ FlatSESEEnterNode sese = (FlatSESEEnterNode) iterator.next();
+ ConflictGraph graph = oooa.getConflictGraph(sese);
+ if(graph!=null) {
+ String id = var + "_fn" + stallsite.hashCode();
+ ConflictNode node = graph.getId2cn().get(id);
+ isValidToPrune &= node.isTobePruned();
+ }
}
cFile.println(" case -" + getTraverserID(var, stallsite)+ ": {");
cFile.println(" SESEstall * rec=(SESEstall*) record;");
if(globalState.NOSTALLTR && isValidToPrune) {
- cFile.println(" /*" + getTraverserInvocation(var, "rec->___obj___, rec", stallsite)+";*/");
+ cFile.println(" /*" + getTraverserInvocation(var, "rec->___obj___, rec", stallsite)+";*/");
} else {
- cFile.println(" " + getTraverserInvocation(var, "rec->___obj___, rec", stallsite)+";");
+ cFile.println(" " + getTraverserInvocation(var, "rec->___obj___, rec", stallsite)+";");
}
cFile.println(" record->rcrstatus=0;");
cFile.println(" }");
table = new Hashtable<Alloc, Set<Effect>>();
this.state=state;
for(Effect e : state.getEffectsAllowed()) {
- Set<Effect> eg;
- if((eg = table.get(e.getAffectedAllocSite())) == null) {
- eg = new HashSet<Effect>();
- table.put(e.getAffectedAllocSite(), eg);
- }
- eg.add(e);
+ Set<Effect> eg;
+ if((eg = table.get(e.getAffectedAllocSite())) == null) {
+ eg = new HashSet<Effect>();
+ table.put(e.getAffectedAllocSite(), eg);
+ }
+ eg.add(e);
}
}
public boolean conflictDereference(Alloc a) {
for(Effect e : getEffects(a)) {
- if (!state.transitionsTo(e).isEmpty()&&state.getConflicts().contains(e))
- return true;
+ if (!state.transitionsTo(e).isEmpty()&&state.getConflicts().contains(e))
+ return true;
}
return false;
}
public boolean hasWriteConflict(Alloc a) {
for(Effect e : getEffects(a)) {
- if (e.isWrite() && state.getConflicts().contains(e))
- return true;
+ if (e.isWrite() && state.getConflicts().contains(e))
+ return true;
}
return false;
}
public boolean hasReadConflict(Alloc a) {
for(Effect e : getEffects(a)) {
- if (e.isRead() && state.getConflicts().contains(e))
- return true;
+ if (e.isRead() && state.getConflicts().contains(e))
+ return true;
}
return false;
}
if (!params.containsTemp(t)) {
Position p=(Position)temptostore.get(t);
if (p==null)
- System.out.println(t);
+ System.out.println(t);
return !p.inStruct;
}
return false;
TempTagPair ttp=(TempTagPair)o;
if (ttp.tagt==tagt&&ttp.td==td) {
if (ttp.tagd!=null) {
- if (!ttp.tagd.equals(tagd))
- throw new Error();
+ if (!ttp.tagd.equals(tagd))
+ throw new Error();
} else if (tagd!=null)
- throw new Error();
+ throw new Error();
return true;
} else return false;
TypeDescriptor td1=(d1 instanceof TagVarDescriptor)?((TagVarDescriptor)d1).getType():((VarDescriptor)d1).getType();
TypeDescriptor td2=(d2 instanceof TagVarDescriptor)?((TagVarDescriptor)d2).getType():((VarDescriptor)d2).getType();
if (!td1.equals(td2))
- return false;
+ return false;
}
return true;
}
for(int i=0; i<numParameters(); i++) {
st+=getParamType(i).getSafeDescriptor();
if ((i+1)<numParameters())
- st+="_";
+ st+="_";
}
return st;
}
for(int i=0; i<params.size(); i++) {
st+=getParamType(i)+" "+getParamName(i);
if ((i+1)!=params.size())
- st+=", ";
+ st+=", ";
}
st+=")";
return st;
hs=new HashSet();
if(this.parentIFs != null) {
for(int i = 0; i < this.parentIFs.size(); i++) {
- if(this.parentIFs.elementAt(i).contains(name)) {
- hs.addAll((HashSet)(this.parentIFs.elementAt(i).getPSet(name)));
- }
+ if(this.parentIFs.elementAt(i).contains(name)) {
+ hs.addAll((HashSet)(this.parentIFs.elementAt(i).getPSet(name)));
+ }
}
}
if (table.containsKey(name)) {
Descriptor d = getFromSameScope(name);
if (d == null) {
if(parent != null) {
- d = parent.get(name);
+ d = parent.get(name);
}
if((d == null) && (this.parentIFs != null)) {
- for(int i = 0; i < this.parentIFs.size(); i++) {
- d = this.parentIFs.elementAt(i).get(name);
- if(d != null) {
- return d;
- }
- }
+ for(int i = 0; i < this.parentIFs.size(); i++) {
+ d = this.parentIFs.elementAt(i).get(name);
+ if(d != null) {
+ return d;
+ }
+ }
}
}
return d;
hs=new HashSet();
if (this.parentIFs != null) {
for(int i = 0; i < this.parentIFs.size(); i++) {
- hs.addAll(this.parentIFs.elementAt(i).getAllValueSet());
+ hs.addAll(this.parentIFs.elementAt(i).getAllValueSet());
}
}
hs.addAll(valueset);
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");
+ 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");
}
}
for(int i=0; i<params.size(); i++) {
st+=getParamType(i)+" "+getParamName(i);
if ((i+1)!=params.size())
- st+=", ";
+ st+=", ";
}
st+=")";
return st;
ExpressionNode en=(ExpressionNode)varInitList.get(i);
st+=en.printNode(indent);
if ((i+1)!=varInitList.size()) {
- st+=", ";
+ st+=", ";
}
}
return st+"}";
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";
+ 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+=";";
+ 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+=", ";
+ BlockStatementNode bsn=(BlockStatementNode)blockstatements.get(i);
+ st+=bsn.printNode(0);
+ if ((i+1)!=blockstatements.size())
+ st+=", ";
}
return st;
} else throw new Error();
while(it_classes.hasNext()) {
ClassDescriptor cd = (ClassDescriptor)it_classes.next();
if(cd.isInterface()) {
- cd.setInterfaceId(if_num++);
+ cd.setInterfaceId(if_num++);
}
}
}
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")) {
- if (!mandatoryImports.containsKey(nd.getIdentifier())) {
- // map name to full name (includes package/directory
- mandatoryImports.put(nd.getIdentifier(), nd.getPathFromRootToHere());
- } else {
- throw new Error("An ambiguous class "+ nd.getIdentifier() +" has been found. It is included for " +
- ((String)mandatoryImports.get(nd.getIdentifier())) + " and " +
- nd.getPathFromRootToHere());
- }
- } else {
- addMultiImport(sourcefile, nd.getPathFromRootToHere(), false);
- }
+ ParseNode pnimport = pnv.elementAt(i);
+ NameDescriptor nd = parseName(pnimport.getChild("name"));
+ if (isNode(pnimport, "import_single")) {
+ if (!mandatoryImports.containsKey(nd.getIdentifier())) {
+ // map name to full name (includes package/directory
+ mandatoryImports.put(nd.getIdentifier(), nd.getPathFromRootToHere());
+ } else {
+ throw new Error("An ambiguous class "+ nd.getIdentifier() +" has been found. It is included for " +
+ ((String)mandatoryImports.get(nd.getIdentifier())) + " and " +
+ nd.getPathFromRootToHere());
+ }
+ } else {
+ addMultiImport(sourcefile, nd.getPathFromRootToHere(), false);
+ }
}
}
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, packageName);
- cn.setSourceFileName(sourcefile);
- parseInitializers(cn);
- if (toanalyze != null)
- toanalyze.add(cn);
- state.addClass(cn);
- // for inner classes/enum
- HashSet tovisit = new HashSet();
- Iterator it_icds = cn.getInnerClasses();
- while (it_icds.hasNext()) {
- tovisit.add(it_icds.next());
- }
-
- while (!tovisit.isEmpty()) {
- ClassDescriptor cd = (ClassDescriptor) tovisit.iterator().next();
- tovisit.remove(cd);
- parseInitializers(cd);
- if (toanalyze != null) {
- toanalyze.add(cd);
- }
- cd.setSourceFileName(sourcefile);
- state.addClass(cd);
-
- Iterator it_ics = cd.getInnerClasses();
- while (it_ics.hasNext()) {
- tovisit.add(it_ics.next());
- }
-
- Iterator it_ienums = cd.getEnum();
- while (it_ienums.hasNext()) {
- ClassDescriptor iecd = (ClassDescriptor) it_ienums.next();
- if (toanalyze != null) {
- toanalyze.add(iecd);
- }
- iecd.setSourceFileName(sourcefile);
- state.addClass(iecd);
- }
- }
-
- Iterator it_enums = cn.getEnum();
- while (it_enums.hasNext()) {
- ClassDescriptor ecd = (ClassDescriptor) it_enums.next();
- if (toanalyze != null) {
- toanalyze.add(ecd);
- }
- ecd.setSourceFileName(sourcefile);
- state.addClass(ecd);
- }
- } else if (isNode(type_pn, "task_declaration")) {
- TaskDescriptor td = parseTaskDecl(type_pn);
- if (toanalyze != null)
- toanalyze.add(td);
- state.addTask(td);
- } else if (isNode(type_pn, "interface_declaration")) {
- // TODO add version for normal Java later
- ClassDescriptor cn = parseInterfaceDecl(type_pn, packageName);
- if (toanalyze != null)
- toanalyze.add(cn);
- cn.setSourceFileName(sourcefile);
- state.addClass(cn);
-
- // for enum
- Iterator it_enums = cn.getEnum();
- while (it_enums.hasNext()) {
- ClassDescriptor ecd = (ClassDescriptor) it_enums.next();
- if (toanalyze != null) {
- toanalyze.add(ecd);
- }
- ecd.setSourceFileName(sourcefile);
- state.addClass(ecd);
- }
- } else if (isNode(type_pn, "enum_declaration")) {
- // TODO add version for normal Java later
- ClassDescriptor cn = parseEnumDecl(null, type_pn);
- if (toanalyze != null)
- toanalyze.add(cn);
- cn.setSourceFileName(sourcefile);
- state.addClass(cn);
- } else if(isNode(type_pn,"annotation_type_declaration")) {
- ClassDescriptor cn=parseAnnotationTypeDecl(type_pn);
- if (toanalyze != null)
- toanalyze.add(cn);
- cn.setSourceFileName(sourcefile);
- state.addClass(cn);
- } else {
- throw new Error(type_pn.getLabel());
- }
+ 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, packageName);
+ cn.setSourceFileName(sourcefile);
+ parseInitializers(cn);
+ if (toanalyze != null)
+ toanalyze.add(cn);
+ state.addClass(cn);
+ // for inner classes/enum
+ HashSet tovisit = new HashSet();
+ Iterator it_icds = cn.getInnerClasses();
+ while (it_icds.hasNext()) {
+ tovisit.add(it_icds.next());
+ }
+
+ while (!tovisit.isEmpty()) {
+ ClassDescriptor cd = (ClassDescriptor) tovisit.iterator().next();
+ tovisit.remove(cd);
+ parseInitializers(cd);
+ if (toanalyze != null) {
+ toanalyze.add(cd);
+ }
+ cd.setSourceFileName(sourcefile);
+ state.addClass(cd);
+
+ Iterator it_ics = cd.getInnerClasses();
+ while (it_ics.hasNext()) {
+ tovisit.add(it_ics.next());
+ }
+
+ Iterator it_ienums = cd.getEnum();
+ while (it_ienums.hasNext()) {
+ ClassDescriptor iecd = (ClassDescriptor) it_ienums.next();
+ if (toanalyze != null) {
+ toanalyze.add(iecd);
+ }
+ iecd.setSourceFileName(sourcefile);
+ state.addClass(iecd);
+ }
+ }
+
+ Iterator it_enums = cn.getEnum();
+ while (it_enums.hasNext()) {
+ ClassDescriptor ecd = (ClassDescriptor) it_enums.next();
+ if (toanalyze != null) {
+ toanalyze.add(ecd);
+ }
+ ecd.setSourceFileName(sourcefile);
+ state.addClass(ecd);
+ }
+ } else if (isNode(type_pn, "task_declaration")) {
+ TaskDescriptor td = parseTaskDecl(type_pn);
+ if (toanalyze != null)
+ toanalyze.add(td);
+ state.addTask(td);
+ } else if (isNode(type_pn, "interface_declaration")) {
+ // TODO add version for normal Java later
+ ClassDescriptor cn = parseInterfaceDecl(type_pn, packageName);
+ if (toanalyze != null)
+ toanalyze.add(cn);
+ cn.setSourceFileName(sourcefile);
+ state.addClass(cn);
+
+ // for enum
+ Iterator it_enums = cn.getEnum();
+ while (it_enums.hasNext()) {
+ ClassDescriptor ecd = (ClassDescriptor) it_enums.next();
+ if (toanalyze != null) {
+ toanalyze.add(ecd);
+ }
+ ecd.setSourceFileName(sourcefile);
+ state.addClass(ecd);
+ }
+ } else if (isNode(type_pn, "enum_declaration")) {
+ // TODO add version for normal Java later
+ ClassDescriptor cn = parseEnumDecl(null, type_pn);
+ if (toanalyze != null)
+ toanalyze.add(cn);
+ cn.setSourceFileName(sourcefile);
+ state.addClass(cn);
+ } else if(isNode(type_pn,"annotation_type_declaration")) {
+ ClassDescriptor cn=parseAnnotationTypeDecl(type_pn);
+ if (toanalyze != null)
+ toanalyze.add(cn);
+ cn.setSourceFileName(sourcefile);
+ state.addClass(cn);
+ } else {
+ throw new Error(type_pn.getLabel());
+ }
}
}
}
String path = (String) state.classpath.get(j);
File folder = new File(path, importPath.replace('.', '/'));
if (folder.exists()) {
- found = true;
- for (String file : folder.list()) {
- // if the file is of type *.java add to multiImport list.
- if (file.lastIndexOf('.') != -1 && file.substring(file.lastIndexOf('.')).equalsIgnoreCase(".java")) {
- String classname = file.substring(0, file.length() - 5);
- // single imports have precedence over multi-imports
- if (!mandatoryImports.containsKey(classname)) {
- //package files have precedence over multi-imports.
- if (multiimports.containsKey(classname) && !isPackageDirectory) {
- // put error in for later, in case we try to import
- multiimports.put(classname, new Error("Error: class " + classname + " is defined more than once in a multi-import in " + currentSource));
- } else {
- multiimports.put(classname, importPath + "." + classname);
- }
- }
- }
- }
+ found = true;
+ for (String file : folder.list()) {
+ // if the file is of type *.java add to multiImport list.
+ if (file.lastIndexOf('.') != -1 && file.substring(file.lastIndexOf('.')).equalsIgnoreCase(".java")) {
+ String classname = file.substring(0, file.length() - 5);
+ // single imports have precedence over multi-imports
+ if (!mandatoryImports.containsKey(classname)) {
+ //package files have precedence over multi-imports.
+ if (multiimports.containsKey(classname) && !isPackageDirectory) {
+ // put error in for later, in case we try to import
+ multiimports.put(classname, new Error("Error: class " + classname + " is defined more than once in a multi-import in " + currentSource));
+ } else {
+ multiimports.put(classname, importPath + "." + classname);
+ }
+ }
+ }
+ }
}
}
for(int i=0; i<fv.size(); i++) {
FieldDescriptor fd=(FieldDescriptor)fv.get(i);
if(fd.getExpressionNode()!=null) {
- Iterator methodit = cn.getMethods();
- while(methodit.hasNext()) {
- MethodDescriptor currmd=(MethodDescriptor)methodit.next();
- if(currmd.isConstructor()) {
- BlockNode bn=state.getMethodBody(currmd);
- NameNode nn=new NameNode(new NameDescriptor(fd.getSymbol()));
- AssignmentNode an=new AssignmentNode(nn,fd.getExpressionNode(),new AssignOperation(1));
- bn.addBlockStatementAt(new BlockExpressionNode(an), pos);
- }
- }
- pos++;
+ Iterator methodit = cn.getMethods();
+ while(methodit.hasNext()) {
+ MethodDescriptor currmd=(MethodDescriptor)methodit.next();
+ if(currmd.isConstructor()) {
+ BlockNode bn=state.getMethodBody(currmd);
+ NameNode nn=new NameNode(new NameDescriptor(fd.getSymbol()));
+ AssignmentNode an=new AssignmentNode(nn,fd.getExpressionNode(),new AssignOperation(1));
+ bn.addBlockStatementAt(new BlockExpressionNode(an), pos);
+ }
+ }
+ pos++;
}
}
}
if (decls!=null) {
ParseNodeVector pnv=decls.getChildren();
for(int i=0; i<pnv.size(); i++) {
- ParseNode decl=pnv.elementAt(i);
- if (isNode(decl,"enum_constant")) {
- parseEnumConstant(cn,decl);
- } else throw new Error();
+ ParseNode decl=pnv.elementAt(i);
+ if (isNode(decl,"enum_constant")) {
+ parseEnumConstant(cn,decl);
+ } else throw new Error();
}
}
}
if(list_node!=null) {
ParseNodeVector pnv = list_node.getChildren();
for (int i = 0; i < pnv.size(); i++) {
- ParseNode element_node = pnv.elementAt(i);
- if (isNode(element_node, "annotation_type_element_declaration")) {
- ParseNodeVector elementProps = element_node.getChildren();
- String identifier=null;
- TypeDescriptor type=null;
- Modifiers modifiers=new Modifiers();
- for(int eidx=0; eidx<elementProps.size(); eidx++) {
- ParseNode prop_node=elementProps.elementAt(eidx);
- if(isNode(prop_node,"name")) {
- identifier=prop_node.getTerminal();
- } else if(isNode(prop_node,"type")) {
- type=parseTypeDescriptor(prop_node);
- } else if(isNode(prop_node,"modifier")) {
- modifiers=parseModifiersList(prop_node);
- }
- }
- cn.addField(new FieldDescriptor(modifiers, type, identifier, null, false));
- }
+ ParseNode element_node = pnv.elementAt(i);
+ if (isNode(element_node, "annotation_type_element_declaration")) {
+ ParseNodeVector elementProps = element_node.getChildren();
+ String identifier=null;
+ TypeDescriptor type=null;
+ Modifiers modifiers=new Modifiers();
+ for(int eidx=0; eidx<elementProps.size(); eidx++) {
+ ParseNode prop_node=elementProps.elementAt(eidx);
+ if(isNode(prop_node,"name")) {
+ identifier=prop_node.getTerminal();
+ } else if(isNode(prop_node,"type")) {
+ type=parseTypeDescriptor(prop_node);
+ } else if(isNode(prop_node,"modifier")) {
+ modifiers=parseModifiersList(prop_node);
+ }
+ }
+ cn.addField(new FieldDescriptor(modifiers, type, identifier, null, false));
+ }
}
}
}
ParseNode snlist=pn.getChild("superIF").getChild("extend_interface_list");
ParseNodeVector pnv=snlist.getChildren();
for(int i=0; i<pnv.size(); i++) {
- ParseNode decl=pnv.elementAt(i);
- if (isNode(decl,"type")) {
- NameDescriptor nd=parseClassName(decl.getChild("class").getChild("name"));
- cn.addSuperInterface(nd.toString());
- }
+ ParseNode decl=pnv.elementAt(i);
+ if (isNode(decl,"type")) {
+ NameDescriptor nd=parseClassName(decl.getChild("class").getChild("name"));
+ cn.addSuperInterface(nd.toString());
+ }
}
}
cn.setModifiers(parseModifiersList(pn.getChild("modifiers")));
if (decls!=null) {
ParseNodeVector pnv=decls.getChildren();
for(int i=0; i<pnv.size(); i++) {
- ParseNode decl=pnv.elementAt(i);
- if (isNode(decl,"constant")) {
- parseInterfaceConstant(cn,decl);
- } else if (isNode(decl,"method")) {
- parseInterfaceMethod(cn,decl.getChild("method_declaration"));
- } else throw new Error();
+ ParseNode decl=pnv.elementAt(i);
+ if (isNode(decl,"constant")) {
+ parseInterfaceConstant(cn,decl);
+ } else if (isNode(decl,"method")) {
+ parseInterfaceMethod(cn,decl.getChild("method_declaration"));
+ } else throw new Error();
}
}
}
String flagname=pn.getChild("name").getTerminal();
FlagEffects fe=new FlagEffects(flagname);
if (pn.getChild("flag_list")!=null)
- parseFlagEffect(fe, pn.getChild("flag_list"));
+ parseFlagEffect(fe, pn.getChild("flag_list"));
if (pn.getChild("tag_list")!=null)
- parseTagEffect(fe, pn.getChild("tag_list"));
+ parseTagEffect(fe, pn.getChild("tag_list"));
return fe;
} else throw new Error();
}
ParseNode pn2=pnv.elementAt(i);
boolean status=true;
if (isNode(pn2,"not")) {
- status=false;
- pn2=pn2.getChild("name");
+ status=false;
+ pn2=pn2.getChild("name");
}
String name=pn2.getTerminal();
fes.addTagEffect(new TagEffect(name,status));
ParseNode pn2=pnv.elementAt(i);
boolean status=true;
if (isNode(pn2,"not")) {
- status=false;
- pn2=pn2.getChild("name");
+ status=false;
+ pn2=pn2.getChild("name");
}
String name=pn2.getTerminal();
fes.addEffect(new FlagEffect(name,status));
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));
+ cc.addVariable((String)args[0].get(i));
+ cc.addArgument((ExpressionNode)args[1].get(i));
}
return cc;
} else throw new Error();
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!!!!!!!");
+ optional = true;
+ paramn = paramn.getChild("optional").getFirstChild();
+ System.out.println("OPTIONAL FOUND!!!!!!!");
} else { optional = false;
- System.out.println("NOT OPTIONAL"); }
+ 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());
+ fen=parseFlagExpression(paramn.getChild("flag").getFirstChild());
ParseNode tagnode=paramn.getChild("tag");
TagExpressionList tel=null;
if (tagnode!=null) {
- tel=parseTagExpressionList(tagnode);
+ tel=parseTagExpressionList(tagnode);
}
td.addParameter(type,paramname,fen, tel, optional);
} else {
if (!(cn.getSymbol().equals(TypeUtil.ObjectClass)||
cn.getSymbol().equals(TypeUtil.TagClass)))
- cn.setSuper(TypeUtil.ObjectClass);
+ cn.setSuper(TypeUtil.ObjectClass);
}
// check inherited interfaces
if (!isEmpty(pn.getChild("superIF").getTerminal())) {
ParseNode snlist=pn.getChild("superIF").getChild("interface_type_list");
ParseNodeVector pnv=snlist.getChildren();
for(int i=0; i<pnv.size(); i++) {
- ParseNode decl=pnv.elementAt(i);
- if (isNode(decl,"type")) {
- NameDescriptor nd=parseClassName(decl.getChild("class").getChild("name"));
- cn.addSuperInterface(nd.toString());
- }
+ ParseNode decl=pnv.elementAt(i);
+ if (isNode(decl,"type")) {
+ NameDescriptor nd=parseClassName(decl.getChild("class").getChild("name"));
+ cn.addSuperInterface(nd.toString());
+ }
}
}
cn.setModifiers(parseModifiersList(pn.getChild("modifiers")));
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, "static_block")) {
- parseStaticBlockDecl(cn, decl.getChild("static_block_declaration"));
- } else if (isNode(decl,"block")) {
- } else if (isNode(decl,"location_order_declaration")) {
- parseLocationOrder(cn,decl.getChild("location_order_list"));
- } else throw new Error();
+ 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, "static_block")) {
+ parseStaticBlockDecl(cn, decl.getChild("static_block_declaration"));
+ } else if (isNode(decl,"block")) {
+ } else if (isNode(decl,"location_order_declaration")) {
+ parseLocationOrder(cn,decl.getChild("location_order_list"));
+ } else throw new Error();
}
}
}
for (int i = 0; i < pnv.size(); i++) {
ParseNode loc = pnv.elementAt(i);
if(isNode(loc,"location_property")) {
- String spinLoc=loc.getChildren().elementAt(0).getLabel();
- spinLocSet.add(spinLoc);
+ String spinLoc=loc.getChildren().elementAt(0).getLabel();
+ spinLocSet.add(spinLoc);
} else {
- String lowerLoc=loc.getChildren().elementAt(0).getLabel();
- String higherLoc= loc.getChildren().elementAt(1).getLabel();
- locOrder.put(higherLoc, lowerLoc);
- if (locOrder.isIntroducingCycle(higherLoc)) {
- throw new Error("Error: the order relation " + lowerLoc + " < " + higherLoc
- + " introduces a cycle.");
- }
+ String lowerLoc=loc.getChildren().elementAt(0).getLabel();
+ String higherLoc= loc.getChildren().elementAt(1).getLabel();
+ locOrder.put(higherLoc, lowerLoc);
+ if (locOrder.isIntroducingCycle(higherLoc)) {
+ throw new Error("Error: the order relation " + lowerLoc + " < " + higherLoc
+ + " introduces a cycle.");
+ }
}
}
if(spinLocSet.size()>0) {
//checking if location is actually defined in the hierarchy
for (Iterator iterator = spinLocSet.iterator(); iterator.hasNext(); ) {
- String locID = (String) iterator.next();
- if(!locOrder.containsKey(locID)) {
- throw new Error("Error: The spinning location '"+
- locID + "' is not defined in the hierarchy of the class '"+cd +"'.");
- }
+ String locID = (String) iterator.next();
+ if(!locOrder.containsKey(locID)) {
+ throw new Error("Error: The spinning location '"+
+ locID + "' is not defined in the hierarchy of the class '"+cd +"'.");
+ }
}
state.addLocationPropertySet(cd, spinLocSet);
}
} else {
if (!(icn.getSymbol().equals(TypeUtil.ObjectClass)||
icn.getSymbol().equals(TypeUtil.TagClass)))
- icn.setSuper(TypeUtil.ObjectClass);
+ icn.setSuper(TypeUtil.ObjectClass);
}
// check inherited interfaces
if (!isEmpty(pn.getChild("superIF").getTerminal())) {
ParseNode snlist=pn.getChild("superIF").getChild("interface_type_list");
ParseNodeVector pnv=snlist.getChildren();
for(int i=0; i<pnv.size(); i++) {
- ParseNode decl=pnv.elementAt(i);
- if (isNode(decl,"type")) {
- NameDescriptor nd=parseClassName(decl.getChild("class").getChild("name"));
- icn.addSuperInterface(nd.toString());
- }
+ ParseNode decl=pnv.elementAt(i);
+ if (isNode(decl,"type")) {
+ NameDescriptor nd=parseClassName(decl.getChild("class").getChild("name"));
+ icn.addSuperInterface(nd.toString());
+ }
}
}
icn.setModifiers(parseModifiersList(pn.getChild("modifiers")));
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);
+ td=td.makeArray(state);
return td;
} else {
System.out.println(pn.PPrint(2, true));
return (String) mandatoryImports.get(terminal);
} else {
if(multiimports.containsKey(terminal)) {
- //Test for error
- Object o = multiimports.get(terminal);
- if(o instanceof Error) {
- throw new Error("Class " + terminal + " is ambiguous. Cause: more than 1 package import contain the same class.");
- } else {
- //At this point, if we found a unique class
- //we can treat it as a single, mandatory import.
- mandatoryImports.put(terminal, o);
- return (String) o;
- }
+ //Test for error
+ Object o = multiimports.get(terminal);
+ if(o instanceof Error) {
+ throw new Error("Class " + terminal + " is ambiguous. Cause: more than 1 package import contain the same class.");
+ } else {
+ //At this point, if we found a unique class
+ //we can treat it as a single, mandatory import.
+ mandatoryImports.put(terminal, o);
+ return (String) o;
+ }
}
}
// Can only be PUBLIC or STATIC or FINAL
if((m.isAbstract()) || (m.isAtomic()) || (m.isNative())
|| (m.isSynchronized())) {
- throw new Error("Error: field in Interface " + cn.getSymbol() + "can only be PUBLIC or STATIC or FINAL");
+ throw new Error("Error: field in Interface " + cn.getSymbol() + "can only be PUBLIC or STATIC or FINAL");
}
m.addModifier(Modifiers.PUBLIC);
m.addModifier(Modifiers.STATIC);
ParseNode tmp=vardecl;
TypeDescriptor arrayt=t;
while (tmp.getChild("single")==null) {
- arrayt=arrayt.makeArray(state);
- tmp=tmp.getChild("array");
+ 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());
- en.setNumLine(epn.getFirstChild().getLine());
- if(m.isStatic()) {
- // for static field, the initializer should be considered as a
- // static block
- boolean isfirst = false;
- MethodDescriptor md = (MethodDescriptor)cn.getMethodTable().getFromSameScope("staticblocks");
- if(md == null) {
- // the first static block for this class
- Modifiers m_i=new Modifiers();
- m_i.addModifier(Modifiers.STATIC);
- md = new MethodDescriptor(m_i, "staticblocks", false);
- md.setAsStaticBlock();
- isfirst = true;
- }
- if(isfirst) {
- cn.addMethod(md);
- }
- cn.incStaticBlocks();
- BlockNode bn=new BlockNode();
- NameNode nn=new NameNode(new NameDescriptor(identifier));
- nn.setNumLine(en.getNumLine());
- AssignmentNode an=new AssignmentNode(nn,en,new AssignOperation(1));
- an.setNumLine(pn.getLine());
- bn.addBlockStatement(new BlockExpressionNode(an));
- if(isfirst) {
- state.addTreeCode(md,bn);
- } else {
- BlockNode obn = state.getMethodBody(md);
- for(int ii = 0; ii < bn.size(); ii++) {
- BlockStatementNode bsn = bn.get(ii);
- obn.addBlockStatement(bsn);
- }
- state.addTreeCode(md, obn);
- bn = null;
- }
- en = null;
- }
+ en=parseExpression(epn.getFirstChild());
+ en.setNumLine(epn.getFirstChild().getLine());
+ if(m.isStatic()) {
+ // for static field, the initializer should be considered as a
+ // static block
+ boolean isfirst = false;
+ MethodDescriptor md = (MethodDescriptor)cn.getMethodTable().getFromSameScope("staticblocks");
+ if(md == null) {
+ // the first static block for this class
+ Modifiers m_i=new Modifiers();
+ m_i.addModifier(Modifiers.STATIC);
+ md = new MethodDescriptor(m_i, "staticblocks", false);
+ md.setAsStaticBlock();
+ isfirst = true;
+ }
+ if(isfirst) {
+ cn.addMethod(md);
+ }
+ cn.incStaticBlocks();
+ BlockNode bn=new BlockNode();
+ NameNode nn=new NameNode(new NameDescriptor(identifier));
+ nn.setNumLine(en.getNumLine());
+ AssignmentNode an=new AssignmentNode(nn,en,new AssignOperation(1));
+ an.setNumLine(pn.getLine());
+ bn.addBlockStatement(new BlockExpressionNode(an));
+ if(isfirst) {
+ state.addTreeCode(md,bn);
+ } else {
+ BlockNode obn = state.getMethodBody(md);
+ for(int ii = 0; ii < bn.size(); ii++) {
+ BlockStatementNode bsn = bn.get(ii);
+ obn.addBlockStatement(bsn);
+ }
+ state.addTreeCode(md, obn);
+ bn = null;
+ }
+ en = null;
+ }
}
cn.addField(new FieldDescriptor(m, arrayt, identifier, en, isglobal));
boolean isglobal = pn.getChild("global") != null || pn.getChild("scratch") != null;
String disjointId = null;
if (pn.getChild("disjoint") != null) {
- disjointId = pn.getChild("disjoint").getTerminal();
+ disjointId = pn.getChild("disjoint").getTerminal();
}
CreateObjectNode con = new CreateObjectNode(td, isglobal, disjointId);
con.setNumLine(pn.getLine());
for (int i = 0; i < args.size(); i++) {
- con.addArgument((ExpressionNode) args.get(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"));
+ 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);
+ if (pn.getChild("tag_list") != null)
+ parseTagEffect(fe, pn.getChild("tag_list"));
+ con.addFlagEffects(fe);
}
return con;
CreateObjectNode con=new CreateObjectNode(td, false, null);
con.setNumLine(pn.getLine());
for(int i=0; i<args.size(); i++) {
- con.addArgument((ExpressionNode)args.get(i));
+ con.addArgument((ExpressionNode)args.get(i));
}
return con;
pn.getChild("scratch")!=null;
String disjointId=null;
if( pn.getChild("disjoint") != null) {
- disjointId = pn.getChild("disjoint").getTerminal();
+ disjointId = pn.getChild("disjoint").getTerminal();
}
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();
+ num=((Integer)pn.getChild("dims_opt").getLiteral()).intValue();
for(int i=0; i<(args.size()+num); i++)
- td=td.makeArray(state);
+ td=td.makeArray(state);
CreateObjectNode con=new CreateObjectNode(td, isglobal, disjointId);
con.setNumLine(pn.getLine());
for(int i=0; i<args.size(); i++) {
- con.addArgument((ExpressionNode)args.get(i));
+ con.addArgument((ExpressionNode)args.get(i));
}
return con;
}
TypeDescriptor td=parseTypeDescriptor(pn);
int num=0;
if (pn.getChild("dims_opt").getLiteral()!=null)
- num=((Integer)pn.getChild("dims_opt").getLiteral()).intValue();
+ num=((Integer)pn.getChild("dims_opt").getLiteral()).intValue();
for(int i=0; i<num; i++)
- td=td.makeArray(state);
+ td=td.makeArray(state);
CreateObjectNode con=new CreateObjectNode(td, false, null);
con.setNumLine(pn.getLine());
ParseNode ipn = pn.getChild("initializer");
MethodInvokeNode min=new MethodInvokeNode(nd);
min.setNumLine(pn.getLine());
for(int i=0; i<args.size(); i++) {
- min.addArgument((ExpressionNode)args.get(i));
+ min.addArgument((ExpressionNode)args.get(i));
}
return min;
} else if (isNode(pn,"methodinvoke2")) {
MethodInvokeNode min=new MethodInvokeNode(methodid,exp);
min.setNumLine(pn.getLine());
for(int i=0; i<args.size(); i++) {
- min.addArgument((ExpressionNode)args.get(i));
+ min.addArgument((ExpressionNode)args.get(i));
}
return min;
} else if (isNode(pn,"fieldaccess")) {
return aan;
} else if (isNode(pn,"cast1")) {
try {
- CastNode cn=new CastNode(parseTypeDescriptor(pn.getChild("type")),parseExpression(pn.getChild("exp").getFirstChild()));
- cn.setNumLine(pn.getLine());
- return cn;
+ CastNode cn=new CastNode(parseTypeDescriptor(pn.getChild("type")),parseExpression(pn.getChild("exp").getFirstChild()));
+ cn.setNumLine(pn.getLine());
+ return cn;
} catch (Exception e) {
- System.out.println(pn.PPrint(1,true));
- e.printStackTrace();
- throw new Error();
+ System.out.println(pn.PPrint(1,true));
+ e.printStackTrace();
+ throw new Error();
}
} else if (isNode(pn,"cast2")) {
CastNode cn=new CastNode(parseExpression(pn.getChild("type").getFirstChild()),parseExpression(pn.getChild("exp").getFirstChild()));
MethodInvokeNode min=new MethodInvokeNode(nd);
min.setNumLine(sin.getLine());
for(int i=0; i<args.size(); i++) {
- min.addArgument((ExpressionNode)args.get(i));
+ min.addArgument((ExpressionNode)args.get(i));
}
BlockExpressionNode ben=new BlockExpressionNode(min);
bn.addFirstBlockStatement(ben);
MethodInvokeNode min=new MethodInvokeNode(nd);
min.setNumLine(eci.getLine());
for(int i=0; i<args.size(); i++) {
- min.addArgument((ExpressionNode)args.get(i));
+ min.addArgument((ExpressionNode)args.get(i));
}
BlockExpressionNode ben=new BlockExpressionNode(min);
ben.setNumLine(eci.getLine());
} else {
BlockNode obn = state.getMethodBody(md);
for(int i = 0; i < bn.size(); i++) {
- BlockStatementNode bsn = bn.get(i);
- obn.addBlockStatement(bsn);
+ BlockStatementNode bsn = bn.get(i);
+ obn.addBlockStatement(bsn);
}
state.addTreeCode(md, obn);
bn = null;
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));
+ bn.addBlockStatement((BlockStatementNode)bsv.get(j));
}
}
return bn;
ParseNode mn=pn.getChild("modifiers");
TypeDescriptor t=parseTypeDescriptor(pn);
if(mn!=null) {
- Modifiers m=parseModifiersList(mn);
- assignAnnotationsToType(m, t);
+ Modifiers m=parseModifiersList(mn);
+ assignAnnotationsToType(m, t);
}
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 vardecl=pnv.elementAt(i);
- ParseNode tmp=vardecl;
- TypeDescriptor arrayt=t;
+ 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();
+ while (tmp.getChild("single")==null) {
+ arrayt=arrayt.makeArray(state);
+ tmp=tmp.getChild("array");
+ }
+ String identifier=tmp.getChild("single").getTerminal();
- ParseNode epn=vardecl.getChild("initializer");
+ ParseNode epn=vardecl.getChild("initializer");
- ExpressionNode en=null;
- if (epn!=null)
- en=parseExpression(epn.getFirstChild());
+ ExpressionNode en=null;
+ if (epn!=null)
+ en=parseExpression(epn.getFirstChild());
- DeclarationNode dn=new DeclarationNode(new VarDescriptor(arrayt, identifier),en);
- dn.setNumLine(tmp.getLine());
+ DeclarationNode dn=new DeclarationNode(new VarDescriptor(arrayt, identifier),en);
+ dn.setNumLine(tmp.getLine());
- blockstatements.add(dn);
+ blockstatements.add(dn);
}
} else if (isNode(pn,"nop")) {
/* Do Nothing */
// TODO add version for normal Java later
ParseNodeVector pnv=pn.getChildren();
for(int i=0; i<pnv.size(); i++) {
- ParseNode sblockdecl=pnv.elementAt(i);
-
- if(isNode(sblockdecl, "switch_block")) {
- ParseNode lpn=sblockdecl.getChild("switch_labels").getChild("switch_label_list");
- ParseNodeVector labelv=lpn.getChildren();
- Vector<SwitchLabelNode> slv = new Vector<SwitchLabelNode>();
- for(int j=0; j<labelv.size(); j++) {
- ParseNode labeldecl=labelv.elementAt(j);
- if(isNode(labeldecl, "switch_label")) {
- SwitchLabelNode sln=new SwitchLabelNode(parseExpression(labeldecl.getChild("constant_expression").getFirstChild()), false);
- sln.setNumLine(labeldecl.getLine());
- slv.addElement(sln);
- } else if(isNode(labeldecl, "default_switch_label")) {
- SwitchLabelNode sln=new SwitchLabelNode(null, true);
- sln.setNumLine(labeldecl.getLine());
- slv.addElement(sln);
- }
- }
-
- SwitchBlockNode sbn=new SwitchBlockNode(slv,
- parseSingleBlock(sblockdecl.getChild("switch_statements").getFirstChild()));
- sbn.setNumLine(sblockdecl.getLine());
-
- blockstatements.add(sbn);
-
- }
+ ParseNode sblockdecl=pnv.elementAt(i);
+
+ if(isNode(sblockdecl, "switch_block")) {
+ ParseNode lpn=sblockdecl.getChild("switch_labels").getChild("switch_label_list");
+ ParseNodeVector labelv=lpn.getChildren();
+ Vector<SwitchLabelNode> slv = new Vector<SwitchLabelNode>();
+ for(int j=0; j<labelv.size(); j++) {
+ ParseNode labeldecl=labelv.elementAt(j);
+ if(isNode(labeldecl, "switch_label")) {
+ SwitchLabelNode sln=new SwitchLabelNode(parseExpression(labeldecl.getChild("constant_expression").getFirstChild()), false);
+ sln.setNumLine(labeldecl.getLine());
+ slv.addElement(sln);
+ } else if(isNode(labeldecl, "default_switch_label")) {
+ SwitchLabelNode sln=new SwitchLabelNode(null, true);
+ sln.setNumLine(labeldecl.getLine());
+ slv.addElement(sln);
+ }
+ }
+
+ SwitchBlockNode sbn=new SwitchBlockNode(slv,
+ parseSingleBlock(sblockdecl.getChild("switch_statements").getFirstChild()));
+ sbn.setNumLine(sblockdecl.getLine());
+
+ blockstatements.add(sbn);
+
+ }
}
} else if (isNode(pn, "trycatchstatement")) {
// TODO add version for normal Java later
ParseNode fbk = pn.getChild("finallyblock");
if(fbk != null) {
- ParseNode fpn = fbk.getFirstChild();
- BlockNode fbn=parseBlockHelper(fpn);
- blockstatements.add(new SubBlockNode(fbn));
+ ParseNode fpn = fbk.getFirstChild();
+ BlockNode fbn=parseBlockHelper(fpn);
+ blockstatements.add(new SubBlockNode(fbn));
}
} else if (isNode(pn, "throwstatement")) {
// TODO Simply return here
} else if (isNode(pn,"taskexit")) {
Vector vfe=null;
if (pn.getChild("flag_effects_list")!=null)
- vfe=parseFlags(pn.getChild("flag_effects_list"));
+ vfe=parseFlags(pn.getChild("flag_effects_list"));
Vector ccs=null;
if (pn.getChild("cons_checks")!=null)
- ccs=parseChecks(pn.getChild("cons_checks"));
+ ccs=parseChecks(pn.getChild("cons_checks"));
TaskExitNode ten=new TaskExitNode(vfe, ccs, this.m_taskexitnum++);
ten.setNumLine(pn.getLine());
blockstatements.add(ten);
blockstatements.add(sn);
} else if (isNode(pn,"return")) {
if (isEmpty(pn.getTerminal()))
- blockstatements.add(new ReturnNode());
+ blockstatements.add(new ReturnNode());
else {
- ExpressionNode en=parseExpression(pn.getFirstChild());
- ReturnNode rn=new ReturnNode(en);
- rn.setNumLine(pn.getLine());
- blockstatements.add(rn);
+ ExpressionNode en=parseExpression(pn.getFirstChild());
+ ReturnNode rn=new ReturnNode(en);
+ rn.setNumLine(pn.getLine());
+ blockstatements.add(rn);
}
} else if (isNode(pn,"block_statement_list")) {
BlockNode bn=parseBlockHelper(pn);
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));
+ ExpressionNode en=parseExpression(pnv.elementAt(i));
+ blockstatements.add(new BlockExpressionNode(en));
}
bn.setStyle(BlockNode.EXPRLIST);
} else if (isNode(pn,"forstatement")) {
ExpressionNode condition=parseExpression(pn.getChild("condition").getFirstChild());
BlockNode body=parseSingleBlock(pn.getChild("statement").getFirstChild());
if(condition == null) {
- // no condition clause, make a 'true' expression as the condition
- condition = (ExpressionNode) new LiteralNode("boolean", new Boolean(true));
+ // no condition clause, make a 'true' expression as the condition
+ condition = (ExpressionNode) new LiteralNode("boolean", new Boolean(true));
}
LoopNode ln=new LoopNode(init,condition,update,body);
ln.setNumLine(pn.getLine());
ExpressionNode condition=parseExpression(pn.getChild("condition").getFirstChild());
BlockNode body=parseSingleBlock(pn.getChild("statement").getFirstChild());
if(condition == null) {
- // no condition clause, make a 'true' expression as the condition
- condition = (ExpressionNode) new LiteralNode("boolean", new Boolean(true));
+ // no condition clause, make a 'true' expression as the condition
+ condition = (ExpressionNode) new LiteralNode("boolean", new Boolean(true));
}
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());
if(condition == null) {
- // no condition clause, make a 'true' expression as the condition
- condition = (ExpressionNode) new LiteralNode("boolean", new Boolean(true));
+ // no condition clause, make a 'true' expression as the condition
+ condition = (ExpressionNode) new LiteralNode("boolean", new Boolean(true));
}
blockstatements.add(new LoopNode(condition,body,LoopNode.DOWHILELOOP));
} else if (isNode(pn,"sese")) {
ParseNode pnID=pn.getChild("identifier");
String stID=null;
if( pnID != null ) {
- stID=pnID.getFirstChild().getTerminal();
+ stID=pnID.getFirstChild().getTerminal();
}
SESENode start=new SESENode(stID);
start.setNumLine(pn.getLine());
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);
+ String paramname=paramn.getChild("single").getTerminal();
+ TypeDescriptor type=new TypeDescriptor(TypeDescriptor.TAG);
+ md.addTagParameter(type, paramname);
} else {
- TypeDescriptor type=parseTypeDescriptor(paramn);
+ 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();
+ 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);
- if(isNode(paramn, "annotation_parameter")) {
- ParseNode bodynode=paramn.getChild("annotation_body");
- parseParameterAnnotation(bodynode,type);
- }
+ md.addParameter(type, paramname);
+ if(isNode(paramn, "annotation_parameter")) {
+ ParseNode bodynode=paramn.getChild("annotation_body");
+ parseParameterAnnotation(bodynode,type);
+ }
}
}
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 if (isNode(modn,"abstract"))
- m.addModifier(Modifiers.ABSTRACT);
- else if (isNode(modn,"volatile"))
- m.addModifier(Modifiers.VOLATILE);
- else if (isNode(modn,"transient"))
- m.addModifier(Modifiers.TRANSIENT);
- else if(isNode(modn,"annotation_list"))
- parseAnnotationList(modn,m);
- else {
- throw new Error("Unrecognized Modifier:"+modn.getLabel());
- }
+ 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 if (isNode(modn,"abstract"))
+ m.addModifier(Modifiers.ABSTRACT);
+ else if (isNode(modn,"volatile"))
+ m.addModifier(Modifiers.VOLATILE);
+ else if (isNode(modn,"transient"))
+ m.addModifier(Modifiers.TRANSIENT);
+ else if(isNode(modn,"annotation_list"))
+ parseAnnotationList(modn,m);
+ else {
+ throw new Error("Unrecognized Modifier:"+modn.getLabel());
+ }
}
}
return m;
for (int i = 0; i < pnv.size(); i++) {
ParseNode body_list = pnv.elementAt(i);
if (isNode(body_list, "annotation_body")) {
- ParseNode body_node = body_list.getFirstChild();
- if (isNode(body_node, "marker_annotation")) {
- m.addAnnotation(new AnnotationDescriptor(body_node.getChild("name").getTerminal()));
- } else if (isNode(body_node, "single_annotation")) {
- m.addAnnotation(new AnnotationDescriptor(body_node.getChild("name").getTerminal(),
- body_node.getChild("element_value").getTerminal()));
- } else if (isNode(body_node, "normal_annotation")) {
- throw new Error("Annotation with multiple data members is not supported yet.");
- }
+ ParseNode body_node = body_list.getFirstChild();
+ if (isNode(body_node, "marker_annotation")) {
+ m.addAnnotation(new AnnotationDescriptor(body_node.getChild("name").getTerminal()));
+ } else if (isNode(body_node, "single_annotation")) {
+ m.addAnnotation(new AnnotationDescriptor(body_node.getChild("name").getTerminal(),
+ body_node.getChild("element_value").getTerminal()));
+ } else if (isNode(body_node, "normal_annotation")) {
+ throw new Error("Annotation with multiple data members is not supported yet.");
+ }
}
}
}
String str="assert("+specname+"(";
for(int i=0; i<numArgs(); i++) {
if (i>0)
- str+=",";
+ str+=",";
str+=getVar(i)+" : ";
str+=getArg(i).printNode(0);
}
ExpressionNode en=(ExpressionNode)argumentlist.get(i);
st+=en.printNode(indent);
if ((i+1)!=argumentlist.size()) {
- if (isarray)
- st+="][";
- else
- st+=", ";
+ if (isarray)
+ st+="][";
+ else
+ st+=", ";
}
}
if (isarray)
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);
+ 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 (newflag==null)
+ newflag=tmp;
+ else
+ newflag=newflag.or(tmp);
}
if (notflag==null)
- notflag=newflag;
+ notflag=newflag;
else
- notflag=notflag.and(newflag);
+ notflag=notflag.and(newflag);
}
return notflag;
}
Vector newvector=new Vector();
result.conjunctions.add(newvector);
for(int j=0; j<conjunct.size(); j++) {
- newvector.add(conjunct.get(j));
+ newvector.add(conjunct.get(j));
}
}
Vector newvector=new Vector();
result.conjunctions.add(newvector);
for(int j=0; j<conjunct.size(); j++) {
- newvector.add(conjunct.get(j));
+ newvector.add(conjunct.get(j));
}
}
return result;
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));
- }
+ 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));
+ }
}
}
return result;
String value="";
for(int i=0; i<conjunctions.size(); i++) {
if (i!=0)
- value+=" || ";
+ value+=" || ";
Vector conjunct=(Vector)conjunctions.get(i);
for(int j=0; j<conjunct.size(); j++) {
- if (j!=0)
- value+="&&";
- value+=conjunct.get(j);
+ if (j!=0)
+ value+="&&";
+ value+=conjunct.get(j);
}
}
return value;
FlagEffect fe=(FlagEffect)effects.get(i);
st+=fe.printNode(0);
if ((i+1)!=effects.size())
- st+=",";
+ st+=",";
}
return st+")";
}
Set s=getCalleeSet(md);
if (s!=null) {
- for(Iterator it=s.iterator(); it.hasNext(); ) {
- MethodDescriptor md2=(MethodDescriptor)it.next();
- if( !callable.contains(md2) ) {
- callable.add(md2);
- tovisit.add(md2);
- }
- }
+ for(Iterator it=s.iterator(); it.hasNext(); ) {
+ MethodDescriptor md2=(MethodDescriptor)it.next();
+ if( !callable.contains(md2) ) {
+ callable.add(md2);
+ tovisit.add(md2);
+ }
+ }
}
}
return callable;
void initClassDesc(ClassDescriptor cd, int init) {
if (classStatus.get(cd)==null||classStatus.get(cd)!=init) {
if (classStatus.get(cd)==null) {
- MethodDescriptor mdstaticinit = (MethodDescriptor)cd.getMethodTable().get("staticblocks");
- if (mdstaticinit!=null) {
- discovered.add(mdstaticinit);
- toprocess.push(mdstaticinit);
- }
+ MethodDescriptor mdstaticinit = (MethodDescriptor)cd.getMethodTable().get("staticblocks");
+ if (mdstaticinit!=null) {
+ discovered.add(mdstaticinit);
+ toprocess.push(mdstaticinit);
+ }
}
classStatus.put(cd, init);
}
//First handle easy cases...
if (callmd.isStatic()||callmd.isConstructor()) {
if (!discovered.contains(callmd)) {
- discovered.add(callmd);
- toprocess.push(callmd);
+ discovered.add(callmd);
+ toprocess.push(callmd);
}
if (!revCallMap.containsKey(callmd))
- revCallMap.put(callmd, new HashSet<MethodDescriptor>());
+ revCallMap.put(callmd, new HashSet<MethodDescriptor>());
revCallMap.get(callmd).add(md);
callMap.get(md).add(callmd);
canCall.get(callmd).add(callmd);
if (impSet!=null) {
for(ClassDescriptor cdactual : impSet) {
- searchimp :
- while(cdactual!=null) {
- Set possiblematches=cdactual.getMethodTable().getSetFromSameScope(callmd.getSymbol());
-
- for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) {
- MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
- if (callmd.matches(matchmd)) {
- //Found the method that will be called
- if (!discovered.contains(matchmd)) {
- discovered.add(matchmd);
- toprocess.push(matchmd);
- }
-
- if (!revCallMap.containsKey(matchmd))
- revCallMap.put(matchmd, new HashSet<MethodDescriptor>());
- revCallMap.get(matchmd).add(md);
-
- callMap.get(md).add(matchmd);
- canCall.get(callmd).add(matchmd);
- break searchimp;
- }
- }
-
- //Didn't find method...look in super class
- cdactual=cdactual.getSuperDesc();
- }
+ searchimp :
+ while(cdactual!=null) {
+ Set possiblematches=cdactual.getMethodTable().getSetFromSameScope(callmd.getSymbol());
+
+ for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) {
+ MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
+ if (callmd.matches(matchmd)) {
+ //Found the method that will be called
+ if (!discovered.contains(matchmd)) {
+ discovered.add(matchmd);
+ toprocess.push(matchmd);
+ }
+
+ if (!revCallMap.containsKey(matchmd))
+ revCallMap.put(matchmd, new HashSet<MethodDescriptor>());
+ revCallMap.get(matchmd).add(md);
+
+ callMap.get(md).add(matchmd);
+ canCall.get(callmd).add(matchmd);
+ break searchimp;
+ }
+ }
+
+ //Didn't find method...look in super class
+ cdactual=cdactual.getSuperDesc();
+ }
}
}
}
while(!tovisit.isEmpty()) {
ClassDescriptor cdcurr=tovisit.pop();
if (!implementationMap.containsKey(cdcurr))
- implementationMap.put(cdcurr, new HashSet<ClassDescriptor>());
+ implementationMap.put(cdcurr, new HashSet<ClassDescriptor>());
if (implementationMap.get(cdcurr).add(cdnew)) {
- //new implementation...see if it affects implementationmap
- if (invocationMap.containsKey(cdcurr)) {
- for(Pair<MethodDescriptor, MethodDescriptor> mdpair : invocationMap.get(cdcurr)) {
- MethodDescriptor md=mdpair.getFirst();
- MethodDescriptor callmd=mdpair.getSecond();
- ClassDescriptor cdactual=cdnew;
+ //new implementation...see if it affects implementationmap
+ if (invocationMap.containsKey(cdcurr)) {
+ for(Pair<MethodDescriptor, MethodDescriptor> mdpair : invocationMap.get(cdcurr)) {
+ MethodDescriptor md=mdpair.getFirst();
+ MethodDescriptor callmd=mdpair.getSecond();
+ ClassDescriptor cdactual=cdnew;
searchimp:
- while(cdactual!=null) {
- Set possiblematches=cdactual.getMethodTable().getSetFromSameScope(callmd.getSymbol());
- for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) {
- MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
- if (callmd.matches(matchmd)) {
- //Found the method that will be called
- if (!discovered.contains(matchmd)) {
- discovered.add(matchmd);
- toprocess.push(matchmd);
- }
- if (!revCallMap.containsKey(matchmd))
- revCallMap.put(matchmd, new HashSet<MethodDescriptor>());
- revCallMap.get(matchmd).add(md);
- callMap.get(md).add(matchmd);
- canCall.get(callmd).add(matchmd);
- break searchimp;
- }
- }
-
- //Didn't find method...look in super class
- cdactual=cdactual.getSuperDesc();
- }
- }
- }
+ while(cdactual!=null) {
+ Set possiblematches=cdactual.getMethodTable().getSetFromSameScope(callmd.getSymbol());
+ for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) {
+ MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
+ if (callmd.matches(matchmd)) {
+ //Found the method that will be called
+ if (!discovered.contains(matchmd)) {
+ discovered.add(matchmd);
+ toprocess.push(matchmd);
+ }
+ if (!revCallMap.containsKey(matchmd))
+ revCallMap.put(matchmd, new HashSet<MethodDescriptor>());
+ revCallMap.get(matchmd).add(md);
+ callMap.get(md).add(matchmd);
+ canCall.get(callmd).add(matchmd);
+ break searchimp;
+ }
+ }
+
+ //Didn't find method...look in super class
+ cdactual=cdactual.getSuperDesc();
+ }
+ }
+ }
}
if (cdcurr.getSuperDesc()!=null)
- tovisit.push(cdcurr.getSuperDesc());
+ tovisit.push(cdcurr.getSuperDesc());
for(Iterator interit=cdcurr.getSuperInterfaces(); interit.hasNext(); ) {
- ClassDescriptor cdinter=(ClassDescriptor) interit.next();
- tovisit.push(cdinter);
+ ClassDescriptor cdinter=(ClassDescriptor) interit.next();
+ tovisit.push(cdinter);
}
}
}
for(FlatNode fn : fm.getNodeSet()) {
switch(fn.kind()) {
case FKind.FlatCall : {
- FlatCall fcall=(FlatCall)fn;
- processCall(md, fcall);
- break;
+ FlatCall fcall=(FlatCall)fn;
+ processCall(md, fcall);
+ break;
}
case FKind.FlatNew: {
- FlatNew fnew=(FlatNew)fn;
- processNew(fnew);
- break;
+ FlatNew fnew=(FlatNew)fn;
+ processNew(fnew);
+ break;
}
}
}
for(int i=0; i<st.length(); i++) {
char x=st.charAt(i);
if (x=='\n')
- new_st+="\\n";
+ new_st+="\\n";
else if (x=='"')
- new_st+="'"+'"'+"'";
+ new_st+="'"+'"'+"'";
else new_st+=x;
}
return new_st;
ExpressionNode en=(ExpressionNode)argumentlist.get(i);
st+=en.printNode(indent);
if ((i+1)!=argumentlist.size())
- st+=", ";
+ st+=", ";
}
return st+")";
}
eval = null;
if(fd != null ) {
if(fd.isFinal() && fd.isStatic()) {
- eval = fd.getExpressionNode().evaluate();
+ eval = fd.getExpressionNode().evaluate();
} else if(fd.isEnum()) {
- eval = Long.valueOf((long)fd.enumValue());
+ eval = Long.valueOf((long)fd.enumValue());
}
} else if(en!= null) {
eval = en.evaluate();
Long l = this.left.evaluate();
if(l != null) {
if (this.op.getOp() == Operation.LOGIC_NOT)
- eval = Long.valueOf(l.longValue() > 0?0:1);
+ eval = Long.valueOf(l.longValue() > 0?0:1);
else if (this.op.getOp() == Operation.COMP)
- eval = Long.valueOf((long)(~l.longValue()));
+ eval = Long.valueOf((long)(~l.longValue()));
else if (this.op.getOp() == Operation.UNARYMINUS)
- eval = Long.valueOf(-l.longValue() );
+ eval = Long.valueOf(-l.longValue() );
else if (this.op.getOp() == Operation.UNARYPLUS)
- eval = Long.valueOf(+l.longValue());
+ eval = Long.valueOf(+l.longValue());
else {
- Long r = this.right.evaluate();
- if(r != null) {
- //if (this.op.getOp() == Operation.LOGIC_OR)
- // return Long.valueOf((long)(l.longValue() || r.longValue()));
- //else if (this.op.getOp() == Operation.LOGIC_AND)
- // return Long.valueOf((long)(l.longValue() && r.longValue()));
- /*else */ if (this.op.getOp() == Operation.BIT_OR)
- eval = Long.valueOf(l.longValue() | r.longValue());
- else if (this.op.getOp() == Operation.BIT_XOR)
- eval = Long.valueOf(l.longValue() ^ r.longValue());
- else if (this.op.getOp() == Operation.BIT_AND)
- eval = Long.valueOf(l.longValue() & r.longValue());
- else if (this.op.getOp() == Operation.EQUAL)
- eval = Long.valueOf((l.longValue() == r.longValue())?1:0);
- else if (this.op.getOp() == Operation.NOTEQUAL)
- eval = Long.valueOf((l.longValue() != r.longValue())?1:0);
- else if (this.op.getOp() == Operation.LT)
- eval = Long.valueOf((l.longValue() < r.longValue())?1:0);
- else if (this.op.getOp() == Operation.GT)
- eval = Long.valueOf((l.longValue() > r.longValue())?1:0);
- else if (this.op.getOp() == Operation.LTE)
- eval = Long.valueOf((l.longValue() <= r.longValue())?1:0);
- else if (this.op.getOp() == Operation.GTE)
- eval = Long.valueOf((l.longValue() >= r.longValue())?1:0);
- else if (this.op.getOp() == Operation.LEFTSHIFT)
- eval = Long.valueOf(l.longValue() << r.longValue());
- else if (this.op.getOp() == Operation.RIGHTSHIFT)
- eval = Long.valueOf(l.longValue() >> r.longValue());
- else if (this.op.getOp() == Operation.URIGHTSHIFT)
- eval = Long.valueOf(l.longValue() >>> r.longValue());
- else if (this.op.getOp() == Operation.SUB)
- eval = Long.valueOf(l.longValue() - r.longValue());
- else if (this.op.getOp() == Operation.ADD)
- eval = Long.valueOf(l.longValue() + r.longValue());
- else if (this.op.getOp() == Operation.MULT)
- eval = Long.valueOf(l.longValue() * r.longValue());
- else if (this.op.getOp() == Operation.DIV)
- eval = Long.valueOf(l.longValue() / r.longValue());
- else if (this.op.getOp() == Operation.MOD)
- eval = Long.valueOf(l.longValue() % r.longValue());
- else if (this.op.getOp() == Operation.ASSIGN)
- eval = Long.valueOf(r.longValue());
- }
+ Long r = this.right.evaluate();
+ if(r != null) {
+ //if (this.op.getOp() == Operation.LOGIC_OR)
+ // return Long.valueOf((long)(l.longValue() || r.longValue()));
+ //else if (this.op.getOp() == Operation.LOGIC_AND)
+ // return Long.valueOf((long)(l.longValue() && r.longValue()));
+ /*else */ if (this.op.getOp() == Operation.BIT_OR)
+ eval = Long.valueOf(l.longValue() | r.longValue());
+ else if (this.op.getOp() == Operation.BIT_XOR)
+ eval = Long.valueOf(l.longValue() ^ r.longValue());
+ else if (this.op.getOp() == Operation.BIT_AND)
+ eval = Long.valueOf(l.longValue() & r.longValue());
+ else if (this.op.getOp() == Operation.EQUAL)
+ eval = Long.valueOf((l.longValue() == r.longValue())?1:0);
+ else if (this.op.getOp() == Operation.NOTEQUAL)
+ eval = Long.valueOf((l.longValue() != r.longValue())?1:0);
+ else if (this.op.getOp() == Operation.LT)
+ eval = Long.valueOf((l.longValue() < r.longValue())?1:0);
+ else if (this.op.getOp() == Operation.GT)
+ eval = Long.valueOf((l.longValue() > r.longValue())?1:0);
+ else if (this.op.getOp() == Operation.LTE)
+ eval = Long.valueOf((l.longValue() <= r.longValue())?1:0);
+ else if (this.op.getOp() == Operation.GTE)
+ eval = Long.valueOf((l.longValue() >= r.longValue())?1:0);
+ else if (this.op.getOp() == Operation.LEFTSHIFT)
+ eval = Long.valueOf(l.longValue() << r.longValue());
+ else if (this.op.getOp() == Operation.RIGHTSHIFT)
+ eval = Long.valueOf(l.longValue() >> r.longValue());
+ else if (this.op.getOp() == Operation.URIGHTSHIFT)
+ eval = Long.valueOf(l.longValue() >>> r.longValue());
+ else if (this.op.getOp() == Operation.SUB)
+ eval = Long.valueOf(l.longValue() - r.longValue());
+ else if (this.op.getOp() == Operation.ADD)
+ eval = Long.valueOf(l.longValue() + r.longValue());
+ else if (this.op.getOp() == Operation.MULT)
+ eval = Long.valueOf(l.longValue() * r.longValue());
+ else if (this.op.getOp() == Operation.DIV)
+ eval = Long.valueOf(l.longValue() / r.longValue());
+ else if (this.op.getOp() == Operation.MOD)
+ eval = Long.valueOf(l.longValue() % r.longValue());
+ else if (this.op.getOp() == Operation.ASSIGN)
+ eval = Long.valueOf(r.longValue());
+ }
}
}
return eval;
return line;
} else {
if (parent != null) {
- return parent.getLine();
+ return parent.getLine();
} else {
- return 0;
+ return 0;
}
}
}
for (i = 0; i < children.size(); i++) {
p = children.elementAt(i);
if (p.getLabel().equals(label)) {
- return p;
+ return p;
}
}
for (i = 0; i < children.size(); i++) {
ParseNode pn = children.elementAt(i);
if (pn.getLabel().equals(label))
- v.addElement(pn);
+ v.addElement(pn);
}
return v;
indent += 2;
if (recursive) {
- for (int i = 0; i < children.size(); i++) {
- Walkable w = (Walkable)children.elementAt(i);
- output += w.PPrint(indent, true);
- }
+ for (int i = 0; i < children.size(); i++) {
+ Walkable w = (Walkable)children.elementAt(i);
+ output += w.PPrint(indent, true);
+ }
} else {
- for (int i = 0; i < children.size(); i++) {
- Walkable w = (Walkable)children.elementAt(i);
- output += doIndent(indent) + "<" + w.getNodeName() + "/>\n";
- }
+ for (int i = 0; i < children.size(); i++) {
+ Walkable w = (Walkable)children.elementAt(i);
+ output += doIndent(indent) + "<" + w.getNodeName() + "/>\n";
+ }
}
indent -= 2;
String childid = getNewID("node");
output.println("\t" + nodeid + " -> " + childid + ";");
if (child.getLabel()=="rule") {
- output.println("\tnode [color=" + newColor() + "];");
+ output.println("\tnode [color=" + newColor() + "];");
}
traverse(child, childid);
}
completed.put(cd, fullcheck);
if (fullcheck>=REFERENCE&&oldstatus<INIT) {
- //Set superclass link up
- if (cd.getSuper()!=null) {
- cd.setSuper(getClass(cd, cd.getSuper(), fullcheck));
- if(cd.getSuperDesc().isInterface()) {
- throw new Error("Error! Class " + cd.getSymbol() + " extends interface " + cd.getSuper());
- }
- // Link together Field, Method, and Flag tables so classes
- // inherit these from their superclasses
- if (oldstatus<REFERENCE) {
- cd.getFieldTable().setParent(cd.getSuperDesc().getFieldTable());
- cd.getMethodTable().setParent(cd.getSuperDesc().getMethodTable());
- cd.getFlagTable().setParent(cd.getSuperDesc().getFlagTable());
- }
- }
- // Link together Field, Method tables do classes inherit these from
- // their ancestor interfaces
- Vector<String> sifv = cd.getSuperInterface();
- for(int i = 0; i < sifv.size(); i++) {
- ClassDescriptor superif = getClass(cd, sifv.elementAt(i), fullcheck);
- if(!superif.isInterface()) {
- throw new Error("Error! Class " + cd.getSymbol() + " implements non-interface " + superif.getSymbol());
- }
- if (oldstatus<REFERENCE) {
- cd.addSuperInterfaces(superif);
- cd.getFieldTable().addParentIF(superif.getFieldTable());
- cd.getMethodTable().addParentIF(superif.getMethodTable());
- }
- }
+ //Set superclass link up
+ if (cd.getSuper()!=null) {
+ cd.setSuper(getClass(cd, cd.getSuper(), fullcheck));
+ if(cd.getSuperDesc().isInterface()) {
+ throw new Error("Error! Class " + cd.getSymbol() + " extends interface " + cd.getSuper());
+ }
+ // Link together Field, Method, and Flag tables so classes
+ // inherit these from their superclasses
+ if (oldstatus<REFERENCE) {
+ cd.getFieldTable().setParent(cd.getSuperDesc().getFieldTable());
+ cd.getMethodTable().setParent(cd.getSuperDesc().getMethodTable());
+ cd.getFlagTable().setParent(cd.getSuperDesc().getFlagTable());
+ }
+ }
+ // Link together Field, Method tables do classes inherit these from
+ // their ancestor interfaces
+ Vector<String> sifv = cd.getSuperInterface();
+ for(int i = 0; i < sifv.size(); i++) {
+ ClassDescriptor superif = getClass(cd, sifv.elementAt(i), fullcheck);
+ if(!superif.isInterface()) {
+ throw new Error("Error! Class " + cd.getSymbol() + " implements non-interface " + superif.getSymbol());
+ }
+ if (oldstatus<REFERENCE) {
+ cd.addSuperInterfaces(superif);
+ cd.getFieldTable().addParentIF(superif.getFieldTable());
+ cd.getMethodTable().addParentIF(superif.getMethodTable());
+ }
+ }
}
if (oldstatus<INIT&&fullcheck>=INIT) {
- /* Check to see that fields are well typed */
- for(Iterator field_it=cd.getFields(); field_it.hasNext(); ) {
- FieldDescriptor fd=(FieldDescriptor)field_it.next();
- checkField(cd,fd);
- }
- for(Iterator method_it=cd.getMethods(); method_it.hasNext(); ) {
- MethodDescriptor md=(MethodDescriptor)method_it.next();
- checkMethod(cd,md);
- }
+ /* Check to see that fields are well typed */
+ for(Iterator field_it=cd.getFields(); field_it.hasNext(); ) {
+ FieldDescriptor fd=(FieldDescriptor)field_it.next();
+ checkField(cd,fd);
+ }
+ for(Iterator method_it=cd.getMethods(); method_it.hasNext(); ) {
+ MethodDescriptor md=(MethodDescriptor)method_it.next();
+ checkMethod(cd,md);
+ }
}
}
}
while (!toanalyze.isEmpty()) {
Object obj = toanalyze.iterator().next();
if (obj instanceof TaskDescriptor) {
- toanalyze.remove(obj);
- TaskDescriptor td = (TaskDescriptor) obj;
- try {
- checkTask(td);
- } catch (Error e) {
- System.out.println("Error in " + td);
- throw e;
- }
+ toanalyze.remove(obj);
+ TaskDescriptor td = (TaskDescriptor) obj;
+ try {
+ checkTask(td);
+ } catch (Error e) {
+ System.out.println("Error in " + td);
+ throw e;
+ }
} else {
- ClassDescriptor cd = (ClassDescriptor) obj;
- toanalyze.remove(cd);
- //set the class mappings based on imports.
- singleImportMap = cd.getSingleImportMappings();
-
- // need to initialize typeutil object here...only place we can
- // get class descriptors without first calling getclass
- getClass(cd, cd.getSymbol());
- for (Iterator method_it = cd.getMethods(); method_it.hasNext(); ) {
- MethodDescriptor md = (MethodDescriptor) method_it.next();
- try {
- checkMethodBody(cd, md);
- } catch (Error e) {
- System.out.println("Error in " + md);
- throw e;
- }
- }
+ ClassDescriptor cd = (ClassDescriptor) obj;
+ toanalyze.remove(cd);
+ //set the class mappings based on imports.
+ singleImportMap = cd.getSingleImportMappings();
+
+ // need to initialize typeutil object here...only place we can
+ // get class descriptors without first calling getclass
+ getClass(cd, cd.getSymbol());
+ for (Iterator method_it = cd.getMethods(); method_it.hasNext(); ) {
+ MethodDescriptor md = (MethodDescriptor) method_it.next();
+ try {
+ checkMethodBody(cd, md);
+ } catch (Error e) {
+ System.out.println("Error in " + md);
+ throw e;
+ }
+ }
}
}
}
ClassDescriptor field_cd=checkAll?getClass(cd, name):getClass(cd, name, REFERENCE);
if (field_cd==null)
- throw new Error("Undefined class "+name);
+ throw new Error("Undefined class "+name);
td.setClassDescriptor(field_cd);
return;
} else if (td.isTag())
ConstraintCheck cc=(ConstraintCheck) ccs.get(i);
for(int j=0; j<cc.numArgs(); j++) {
- ExpressionNode en=cc.getArg(j);
- checkExpressionNode(td,nametable,en,null);
+ ExpressionNode en=cc.getArg(j);
+ checkExpressionNode(td,nametable,en,null);
}
}
}
//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);
+ 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");
+ 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);
+ 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);
+ 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);
}
}
}
/* 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");
+ throw new Error("Cannot have non-object argument to a task");
ClassDescriptor cd=param_type.getClassDesc();
if (fen!=null)
- checkFlagExpressionNode(cd, fen);
+ checkFlagExpressionNode(cd, fen);
}
checkFlagEffects(td, td.getFlagEffects(),td.getParameterTable());
FlagOpNode fon=(FlagOpNode)fen;
checkFlagExpressionNode(cd, fon.getLeft());
if (fon.getRight()!=null)
- checkFlagExpressionNode(cd, fon.getRight());
+ checkFlagExpressionNode(cd, fon.getRight());
break;
}
String name=fn.getFlagName();
FlagDescriptor fd=(FlagDescriptor)cd.getFlagTable().get(name);
if (fd==null)
- throw new Error("Undeclared flag: "+name);
+ throw new Error("Undeclared flag: "+name);
fn.setFlag(fd);
break;
}
/* Check for abstract methods */
if(md.isAbstract()) {
if(!cd.isAbstract() && !cd.isInterface()) {
- throw new Error("Error! The non-abstract Class " + cd.getSymbol() + " contains an abstract method " + md.getSymbol());
+ throw new Error("Error! The non-abstract Class " + cd.getSymbol() + " contains an abstract method " + md.getSymbol());
}
}
/* Check return type */
if (!md.isConstructor() && !md.isStaticBlock())
if (!md.getReturnType().isVoid()) {
- checkTypeDescriptor(cd, md.getReturnType());
+ checkTypeDescriptor(cd, md.getReturnType());
}
for(int i=0; i<md.numParameters(); i++) {
TypeDescriptor param_type=md.getParamType(i);
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);
- }
- }
+ 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);
MethodDescriptor md=(MethodDescriptor)d;
if (rn.getReturnExpression()!=null)
if (md.getReturnType()==null)
- throw new Error("Constructor can't return something.");
+ throw new Error("Constructor can't return something.");
else if (md.getReturnType().isVoid())
- throw new Error(md+" is void");
+ throw new Error(md+" is void");
else
- checkExpressionNode(md, nametable, rn.getReturnExpression(), md.getReturnType());
+ checkExpressionNode(md, nametable, rn.getReturnExpression(), md.getReturnType());
else
if (md.getReturnType()!=null&&!md.getReturnType().isVoid())
throw new Error("Need to return something for "+md);
for(int i = 0; i < sbn.size(); i++) {
boolean containdefault = checkSwitchBlockNode(md, nametable, (SwitchBlockNode)sbn.get(i));
if(hasdefault && containdefault) {
- throw new Error("Error: duplicate default branch in switch-case statement in Method: " + md.getSymbol());
+ throw new Error("Error: duplicate default branch in switch-case statement in Method: " + md.getSymbol());
}
hasdefault = containdefault;
}
int defaultb = 0;
for(int i = 0; i < slnv.size(); i++) {
if(slnv.elementAt(i).isdefault) {
- defaultb++;
+ defaultb++;
} else {
- checkConstantExpressionNode(md, nametable, slnv.elementAt(i).getCondition(), new TypeDescriptor(TypeDescriptor.INT));
+ checkConstantExpressionNode(md, nametable, slnv.elementAt(i).getCondition(), new TypeDescriptor(TypeDescriptor.INT));
}
}
if(defaultb > 1) {
/* Type check */
if (td!=null) {
if (!typeutil.isSuperorType(td,cast_type))
- throw new Error("Cast node returns "+cast_type+", but need "+td);
+ throw new Error("Cast node returns "+cast_type+", but need "+td);
}
ExpressionNode en=cn.getExpression();
if(ltd.isClassNameRef()) {
// the field access is using a class name directly
if(ltd.getClassDesc().isEnum()) {
- int value = ltd.getClassDesc().getEnumConstant(fieldname);
- if(-1 == value) {
- // check if this field is an enum constant
- throw new Error(fieldname + " is not an enum constant in "+fan.printNode(0)+" in "+md);
- }
- fd = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC|Modifiers.FINAL), new TypeDescriptor(TypeDescriptor.INT), fieldname, null, false);
- fd.setAsEnum();
- fd.setEnumValue(value);
+ int value = ltd.getClassDesc().getEnumConstant(fieldname);
+ if(-1 == value) {
+ // check if this field is an enum constant
+ throw new Error(fieldname + " is not an enum constant in "+fan.printNode(0)+" in "+md);
+ }
+ fd = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC|Modifiers.FINAL), new TypeDescriptor(TypeDescriptor.INT), fieldname, null, false);
+ fd.setAsEnum();
+ fd.setEnumValue(value);
} else if(fd == null) {
- throw new Error("Could not find field "+ fieldname + " in "+fan.printNode(0)+" in "+md + " (Line: "+fan.getNumLine()+")");
+ throw new Error("Could not find field "+ fieldname + " in "+fan.printNode(0)+" in "+md + " (Line: "+fan.getNumLine()+")");
} else if(fd.isStatic()) {
- // check if this field is a static field
- if(fd.getExpressionNode() != null) {
- checkExpressionNode(md,nametable,fd.getExpressionNode(),null);
- }
+ // check if this field is a static field
+ if(fd.getExpressionNode() != null) {
+ checkExpressionNode(md,nametable,fd.getExpressionNode(),null);
+ }
} else {
- throw new Error("Dereference of the non-static field "+ fieldname + " in "+fan.printNode(0)+" in "+md);
+ throw new Error("Dereference of the non-static field "+ fieldname + " in "+fan.printNode(0)+" in "+md);
}
}
FieldDescriptor fdwr=(FieldDescriptor) ltdwr.getClassDesc().getFieldTable().get(fieldnamewr);
fan.setField(fdwr);
if (fdwr==null)
- throw new Error("Unknown field "+fieldnamewr + " in "+fan.printNode(0)+" in "+md);
+ throw new Error("Unknown field "+fieldnamewr + " in "+fan.printNode(0)+" in "+md);
} else {
fan.setField(fd);
}
if (td!=null) {
if (!typeutil.isSuperorType(td,fan.getType()))
- throw new Error("Field node returns "+fan.getType()+", but need "+td);
+ throw new Error("Field node returns "+fan.getType()+", but need "+td);
}
}
if (td!=null)
if (!typeutil.isSuperorType(td,aan.getType()))
- throw new Error("Field node returns "+aan.getType()+", but need "+td);
+ throw new Error("Field node returns "+aan.getType()+", but need "+td);
}
void checkLiteralNode(Descriptor md, SymbolTable nametable, LiteralNode ln, TypeDescriptor td) {
if (td!=null)
if (!typeutil.isSuperorType(td,ln.getType())) {
- Long l = ln.evaluate();
- if((ln.getType().isByte() || ln.getType().isShort()
- || ln.getType().isChar() || ln.getType().isInt())
- && (l != null)
- && (td.isByte() || td.isShort() || td.isChar()
- || td.isInt() || td.isLong())) {
- long lnvalue = l.longValue();
- if((td.isByte() && ((lnvalue > 127) || (lnvalue < -128)))
- || (td.isShort() && ((lnvalue > 32767) || (lnvalue < -32768)))
- || (td.isChar() && ((lnvalue > 65535) || (lnvalue < 0)))
- || (td.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648)))
- || (td.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) {
- throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md);
- }
- } else {
- throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md);
- }
+ Long l = ln.evaluate();
+ if((ln.getType().isByte() || ln.getType().isShort()
+ || ln.getType().isChar() || ln.getType().isInt())
+ && (l != null)
+ && (td.isByte() || td.isShort() || td.isChar()
+ || td.isInt() || td.isLong())) {
+ long lnvalue = l.longValue();
+ if((td.isByte() && ((lnvalue > 127) || (lnvalue < -128)))
+ || (td.isShort() && ((lnvalue > 32767) || (lnvalue < -32768)))
+ || (td.isChar() && ((lnvalue > 65535) || (lnvalue < 0)))
+ || (td.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648)))
+ || (td.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) {
+ throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md);
+ }
+ } else {
+ throw new Error("Field node returns "+ln.getType()+", but need "+td+" in "+md);
+ }
}
}
} else {
String varname=nd.toString();
if(varname.equals("this")) {
- // "this"
- nn.setVar((VarDescriptor)nametable.get("this"));
- return;
+ // "this"
+ nn.setVar((VarDescriptor)nametable.get("this"));
+ return;
}
Descriptor d=(Descriptor)nametable.get(varname);
if (d==null) {
- ClassDescriptor cd = null;
- if((md instanceof MethodDescriptor) && ((MethodDescriptor)md).isStaticBlock()) {
- // this is a static block, all the accessed fields should be static field
- cd = ((MethodDescriptor)md).getClassDesc();
- SymbolTable fieldtbl = cd.getFieldTable();
- FieldDescriptor fd=(FieldDescriptor)fieldtbl.get(varname);
- if((fd == null) || (!fd.isStatic())) {
- // no such field in the class, check if this is a class
- if(varname.equals("this")) {
- throw new Error("Error: access this obj in a static block");
- }
- cd=getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), varname);
- if(cd != null) {
- // this is a class name
- nn.setClassDesc(cd);
- return;
- } else {
- throw new Error("Name "+varname+" should not be used in static block: "+md);
- }
- } else {
- // this is a static field
- nn.setField(fd);
- nn.setClassDesc(cd);
- return;
- }
- } else {
- // check if the var is a static field of the class
- if(md instanceof MethodDescriptor) {
- cd = ((MethodDescriptor)md).getClassDesc();
- FieldDescriptor fd = (FieldDescriptor)cd.getFieldTable().get(varname);
- if((fd != null) && (fd.isStatic())) {
- nn.setField(fd);
- nn.setClassDesc(cd);
- if (td!=null)
- if (!typeutil.isSuperorType(td,nn.getType()))
- throw new Error("Field node returns "+nn.getType()+", but need "+td);
- return;
- } else if(fd != null) {
- throw new Error("Name "+varname+" should not be used in " + md);
- }
- }
- cd=getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), varname);
- if(cd != null) {
- // this is a class name
- nn.setClassDesc(cd);
- return;
- } else {
- throw new Error("Name "+varname+" undefined in: "+md);
- }
- }
+ ClassDescriptor cd = null;
+ if((md instanceof MethodDescriptor) && ((MethodDescriptor)md).isStaticBlock()) {
+ // this is a static block, all the accessed fields should be static field
+ cd = ((MethodDescriptor)md).getClassDesc();
+ SymbolTable fieldtbl = cd.getFieldTable();
+ FieldDescriptor fd=(FieldDescriptor)fieldtbl.get(varname);
+ if((fd == null) || (!fd.isStatic())) {
+ // no such field in the class, check if this is a class
+ if(varname.equals("this")) {
+ throw new Error("Error: access this obj in a static block");
+ }
+ cd=getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), varname);
+ if(cd != null) {
+ // this is a class name
+ nn.setClassDesc(cd);
+ return;
+ } else {
+ throw new Error("Name "+varname+" should not be used in static block: "+md);
+ }
+ } else {
+ // this is a static field
+ nn.setField(fd);
+ nn.setClassDesc(cd);
+ return;
+ }
+ } else {
+ // check if the var is a static field of the class
+ if(md instanceof MethodDescriptor) {
+ cd = ((MethodDescriptor)md).getClassDesc();
+ FieldDescriptor fd = (FieldDescriptor)cd.getFieldTable().get(varname);
+ if((fd != null) && (fd.isStatic())) {
+ nn.setField(fd);
+ nn.setClassDesc(cd);
+ if (td!=null)
+ if (!typeutil.isSuperorType(td,nn.getType()))
+ throw new Error("Field node returns "+nn.getType()+", but need "+td);
+ return;
+ } else if(fd != null) {
+ throw new Error("Name "+varname+" should not be used in " + md);
+ }
+ }
+ cd=getClass(((md instanceof MethodDescriptor)?((MethodDescriptor)md).getClassDesc():null), varname);
+ if(cd != null) {
+ // this is a class name
+ nn.setClassDesc(cd);
+ return;
+ } else {
+ throw new Error("Name "+varname+" undefined in: "+md);
+ }
+ }
}
if (d instanceof VarDescriptor) {
- nn.setVar(d);
+ nn.setVar(d);
} else if (d instanceof FieldDescriptor) {
- FieldDescriptor fd=(FieldDescriptor)d;
- if (fd.getType().iswrapper()) {
- String id=nd.getIdentifier();
- NameDescriptor base=nd.getBase();
- NameNode n=new NameNode(nn.getName());
- n.setNumLine(nn.getNumLine());
- n.setField(fd);
- n.setVar((VarDescriptor)nametable.get("this")); /* Need a pointer to this */
- FieldAccessNode fan=new FieldAccessNode(n,"value");
- fan.setNumLine(n.getNumLine());
- FieldDescriptor fdval=(FieldDescriptor) fd.getType().getClassDesc().getFieldTable().get("value");
- fan.setField(fdval);
- nn.setExpression(fan);
- } else {
- nn.setField(fd);
- nn.setVar((VarDescriptor)nametable.get("this")); /* Need a pointer to this */
- }
+ FieldDescriptor fd=(FieldDescriptor)d;
+ if (fd.getType().iswrapper()) {
+ String id=nd.getIdentifier();
+ NameDescriptor base=nd.getBase();
+ NameNode n=new NameNode(nn.getName());
+ n.setNumLine(nn.getNumLine());
+ n.setField(fd);
+ n.setVar((VarDescriptor)nametable.get("this")); /* Need a pointer to this */
+ FieldAccessNode fan=new FieldAccessNode(n,"value");
+ fan.setNumLine(n.getNumLine());
+ FieldDescriptor fdval=(FieldDescriptor) fd.getType().getClassDesc().getFieldTable().get("value");
+ fan.setField(fdval);
+ nn.setExpression(fan);
+ } else {
+ nn.setField(fd);
+ nn.setVar((VarDescriptor)nametable.get("this")); /* Need a pointer to this */
+ }
} else if (d instanceof TagVarDescriptor) {
- nn.setVar(d);
+ nn.setVar(d);
} else throw new Error("Wrong type of descriptor");
if (td!=null)
- if (!typeutil.isSuperorType(td,nn.getType()))
- throw new Error("Field node returns "+nn.getType()+", but need "+td);
+ if (!typeutil.isSuperorType(td,nn.getType()))
+ throw new Error("Field node returns "+nn.getType()+", but need "+td);
}
}
if (td!=null) {
if (!typeutil.isSuperorType(td, ofn.getType())) {
- System.out.println(td);
- System.out.println(ofn.getType());
- throw new Error("Type of rside not compatible with type of lside"+ofn.printNode(0));
+ System.out.println(td);
+ System.out.println(ofn.getType());
+ throw new Error("Type of rside not compatible with type of lside"+ofn.printNode(0));
}
}
}
for(int i = 1; i < vec_type.size(); i++) {
TypeDescriptor tmp_type = vec_type.elementAt(i);
if(out_type == null) {
- if(tmp_type != null) {
- out_type = tmp_type;
- }
+ if(tmp_type != null) {
+ out_type = tmp_type;
+ }
} else if(out_type.isNull()) {
- if(!tmp_type.isNull() ) {
- if(!tmp_type.isArray()) {
- throw new Error("Error: mixed type in var initializer list");
- } else {
- out_type = tmp_type;
- }
- }
+ if(!tmp_type.isNull() ) {
+ if(!tmp_type.isArray()) {
+ throw new Error("Error: mixed type in var initializer list");
+ } else {
+ out_type = tmp_type;
+ }
+ }
} else if(out_type.isArray()) {
- if(tmp_type.isArray()) {
- if(tmp_type.getArrayCount() > out_type.getArrayCount()) {
- out_type = tmp_type;
- }
- } else if((tmp_type != null) && (!tmp_type.isNull())) {
- throw new Error("Error: mixed type in var initializer list");
- }
+ if(tmp_type.isArray()) {
+ if(tmp_type.getArrayCount() > out_type.getArrayCount()) {
+ out_type = tmp_type;
+ }
+ } else if((tmp_type != null) && (!tmp_type.isNull())) {
+ throw new Error("Error: mixed type in var initializer list");
+ }
} else if(out_type.isInt()) {
- if(!tmp_type.isInt()) {
- throw new Error("Error: mixed type in var initializer list");
- }
+ if(!tmp_type.isInt()) {
+ throw new Error("Error: mixed type in var initializer list");
+ }
} else if(out_type.isString()) {
- if(!tmp_type.isString()) {
- throw new Error("Error: mixed type in var initializer list");
- }
+ if(!tmp_type.isString()) {
+ throw new Error("Error: mixed type in var initializer list");
+ }
}
}
if(out_type != null) {
/* We want parameter variables to tasks to be immutable */
if (md instanceof TaskDescriptor) {
if (an.getDest() instanceof NameNode) {
- NameNode nn=(NameNode)an.getDest();
- if (nn.getVar()!=null) {
- if (((TaskDescriptor)md).getParameterTable().contains(nn.getVar().getSymbol()))
- throw new Error("Can't modify parameter "+nn.getVar()+ " to task "+td.getSymbol());
- }
+ NameNode nn=(NameNode)an.getDest();
+ if (nn.getVar()!=null) {
+ if (((TaskDescriptor)md).getParameterTable().contains(nn.getVar().getSymbol()))
+ throw new Error("Can't modify parameter "+nn.getVar()+ " to task "+td.getSymbol());
+ }
}
}
NameDescriptor valuend=new NameDescriptor(nd, "valueOf");
if (!(an.getSrc().getType().isString()&&(an.getSrc() instanceof OpNode))) {
- MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
- rightmin.setNumLine(an.getSrc().getNumLine());
- rightmin.addArgument(an.getSrc());
- an.right=rightmin;
- checkExpressionNode(md, nametable, an.getSrc(), null);
+ MethodInvokeNode rightmin=new MethodInvokeNode(valuend);
+ rightmin.setNumLine(an.getSrc().getNumLine());
+ rightmin.addArgument(an.getSrc());
+ an.right=rightmin;
+ checkExpressionNode(md, nametable, an.getSrc(), null);
}
}
TypeDescriptor dt = an.getDest().getType();
TypeDescriptor st = an.getSrc().getType();
if(an.getSrc().kind() == Kind.ArrayInitializerNode) {
- if(dt.getArrayCount() != st.getArrayCount()) {
- throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
- } else {
- do {
- dt = dt.dereference();
- st = st.dereference();
- } while(dt.isArray());
- if((st.isByte() || st.isShort() || st.isChar() || st.isInt())
- && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) {
- return;
- } else {
- throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
- }
- }
+ if(dt.getArrayCount() != st.getArrayCount()) {
+ throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
+ } else {
+ do {
+ dt = dt.dereference();
+ st = st.dereference();
+ } while(dt.isArray());
+ if((st.isByte() || st.isShort() || st.isChar() || st.isInt())
+ && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) {
+ return;
+ } else {
+ throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
+ }
+ }
} else {
- Long l = an.getSrc().evaluate();
- if((st.isByte() || st.isShort() || st.isChar() || st.isInt())
- && (l != null)
- && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) {
- long lnvalue = l.longValue();
- if((dt.isByte() && ((lnvalue > 127) || (lnvalue < -128)))
- || (dt.isShort() && ((lnvalue > 32767) || (lnvalue < -32768)))
- || (dt.isChar() && ((lnvalue > 65535) || (lnvalue < 0)))
- || (dt.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648)))
- || (dt.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) {
- throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
- }
- } else {
- throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
- }
+ Long l = an.getSrc().evaluate();
+ if((st.isByte() || st.isShort() || st.isChar() || st.isInt())
+ && (l != null)
+ && (dt.isByte() || dt.isShort() || dt.isChar() || dt.isInt() || dt.isLong())) {
+ long lnvalue = l.longValue();
+ if((dt.isByte() && ((lnvalue > 127) || (lnvalue < -128)))
+ || (dt.isShort() && ((lnvalue > 32767) || (lnvalue < -32768)))
+ || (dt.isChar() && ((lnvalue > 65535) || (lnvalue < 0)))
+ || (dt.isInt() && ((lnvalue > 2147483647) || (lnvalue < -2147483648)))
+ || (dt.isLong() && ((lnvalue > 9223372036854775807L) || (lnvalue < -9223372036854775808L)))) {
+ throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
+ }
+ } else {
+ throw new Error("Type of rside ("+an.getSrc().getType().toPrettyString()+") not compatible with type of lside ("+an.getDest().getType().toPrettyString()+")"+an.printNode(0));
+ }
}
}
}
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);
+ BlockStatementNode bsn=bn.get(i);
+ checkBlockStatementNode(md, bn.getVarTable(),bsn);
}
//check the condition
checkExpressionNode(md, bn.getVarTable(), ln.getCondition(), new TypeDescriptor(TypeDescriptor.BOOLEAN));
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);
+ 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);
+ 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);
}
}
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:" + bestmd + " and " + currmd);
- }
-
- /* Is this more specific than bestmd */
- }
+ 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:" + bestmd + " and " + currmd);
+ }
+
+ /* Is this more specific than bestmd */
+ }
}
if (bestmd == null)
- throw new Error("No method found for " + con.printNode(0) + " in " + md);
+ throw new Error("No method found for " + con.printNode(0) + " in " + md);
con.setConstructor(bestmd);
}
}
throw new Error();
for(int i=0; i<md1.numParameters(); i++) {
if (!md2.getParamType(i).equals(md1.getParamType(i)))
- return false;
+ return false;
}
if (!md2.getReturnType().equals(md1.getReturnType()))
return false;
checkExpressionNode(md,nametable,en,null);
tdarray[i]=en.getType();
if(en.getType().isClass() && en.getType().getClassDesc().isEnum()) {
- tdarray[i] = new TypeDescriptor(TypeDescriptor.INT);
+ tdarray[i] = new TypeDescriptor(TypeDescriptor.INT);
}
}
TypeDescriptor typetolookin=null;
} else if (min.getBaseName()!=null) {
String rootname=min.getBaseName().getRoot();
if (rootname.equals("super")) {
- ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
- typetolookin=new TypeDescriptor(supercd);
- min.setSuper();
+ ClassDescriptor supercd=((MethodDescriptor)md).getClassDesc().getSuperDesc();
+ typetolookin=new TypeDescriptor(supercd);
+ min.setSuper();
} else if (rootname.equals("this")) {
- if(isstatic) {
- throw new Error("use this object in static method md = "+ md.toString());
- }
- ClassDescriptor cd=((MethodDescriptor)md).getClassDesc();
- typetolookin=new TypeDescriptor(cd);
+ if(isstatic) {
+ throw new Error("use this object in static method md = "+ md.toString());
+ }
+ ClassDescriptor cd=((MethodDescriptor)md).getClassDesc();
+ typetolookin=new TypeDescriptor(cd);
} else if (nametable.get(rootname)!=null) {
- //we have an expression
- min.setExpression(translateNameDescriptorintoExpression(min.getBaseName(),min.getNumLine()));
- checkExpressionNode(md, nametable, min.getExpression(), null);
- typetolookin=min.getExpression().getType();
+ //we have an expression
+ min.setExpression(translateNameDescriptorintoExpression(min.getBaseName(),min.getNumLine()));
+ checkExpressionNode(md, nametable, min.getExpression(), null);
+ typetolookin=min.getExpression().getType();
} else {
- if(!min.getBaseName().getSymbol().equals("System.out")) {
- ExpressionNode nn = translateNameDescriptorintoExpression(min.getBaseName(),min.getNumLine());
- checkExpressionNode(md, nametable, nn, null);
- typetolookin = nn.getType();
- if(!((nn.kind()== Kind.NameNode) && (((NameNode)nn).getField() == null)
- && (((NameNode)nn).getVar() == null) && (((NameNode)nn).getExpression() == null))) {
- // this is not a pure class name, need to add to
- min.setExpression(nn);
- }
- } else {
- //we have a type
- ClassDescriptor cd = null;
- //if (min.getBaseName().getSymbol().equals("System.out"))
- cd=getClass(null, "System");
- /*else {
- cd=getClass(min.getBaseName().getSymbol());
- }*/
- if (cd==null)
- throw new Error("md = "+ md.toString()+ " "+min.getBaseName()+" undefined");
- typetolookin=new TypeDescriptor(cd);
- }
+ if(!min.getBaseName().getSymbol().equals("System.out")) {
+ ExpressionNode nn = translateNameDescriptorintoExpression(min.getBaseName(),min.getNumLine());
+ checkExpressionNode(md, nametable, nn, null);
+ typetolookin = nn.getType();
+ if(!((nn.kind()== Kind.NameNode) && (((NameNode)nn).getField() == null)
+ && (((NameNode)nn).getVar() == null) && (((NameNode)nn).getExpression() == null))) {
+ // this is not a pure class name, need to add to
+ min.setExpression(nn);
+ }
+ } else {
+ //we have a type
+ ClassDescriptor cd = null;
+ //if (min.getBaseName().getSymbol().equals("System.out"))
+ cd=getClass(null, "System");
+ /*else {
+ cd=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();
MethodDescriptor currmd=(MethodDescriptor)methodit.next();
/* Need correct number of parameters */
if (min.numArgs()!=currmd.numParameters())
- continue;
+ continue;
for(int i=0; i<min.numArgs(); i++) {
- if (!typeutil.isSuperorType(currmd.getParamType(i),tdarray[i]))
- if(((!tdarray[i].isArray() &&(tdarray[i].isInt() || tdarray[i].isLong()))
- && currmd.getParamType(i).isClass() && currmd.getParamType(i).getClassDesc().getSymbol().equals("Object"))) {
- // primitive parameters vs object
- } else {
- continue NextMethod;
- }
+ if (!typeutil.isSuperorType(currmd.getParamType(i),tdarray[i]))
+ if(((!tdarray[i].isArray() &&(tdarray[i].isInt() || tdarray[i].isLong()))
+ && currmd.getParamType(i).isClass() && currmd.getParamType(i).getClassDesc().getSymbol().equals("Object"))) {
+ // primitive parameters vs object
+ } else {
+ continue NextMethod;
+ }
}
/* Method okay so far */
if (bestmd==null)
- bestmd=currmd;
+ bestmd=currmd;
else {
- if (typeutil.isMoreSpecific(currmd,bestmd)) {
- bestmd=currmd;
- } else if (!typeutil.isMoreSpecific(bestmd, currmd))
- throw new Error("No method is most specific:"+bestmd+" and "+currmd);
+ if (typeutil.isMoreSpecific(currmd,bestmd)) {
+ bestmd=currmd;
+ } else if (!typeutil.isMoreSpecific(bestmd, currmd))
+ throw new Error("No method is most specific:"+bestmd+" and "+currmd);
- /* Is this more specific than bestmd */
+ /* Is this more specific than bestmd */
}
}
if (bestmd==null)
/* Check whether we need to set this parameter to implied this */
if (!isstatic && !bestmd.isStatic()) {
if (min.getExpression()==null) {
- ExpressionNode en=new NameNode(new NameDescriptor("this"));
- min.setExpression(en);
- checkExpressionNode(md, nametable, min.getExpression(), null);
+ ExpressionNode en=new NameNode(new NameDescriptor("this"));
+ min.setExpression(en);
+ checkExpressionNode(md, nametable, min.getExpression(), null);
}
}
for(int i=0; i<min.numArgs(); i++) {
if(!tdarray[i].isArray() && (tdarray[i].isInt() || tdarray[i].isLong())
&& min.getMethod().getParamType(i).isClass() && min.getMethod().getParamType(i).getClassDesc().getSymbol().equals("Object")) {
- // Shall wrap this primitive parameter as a object
- ExpressionNode exp = min.getArg(i);
- TypeDescriptor ptd = null;
- NameDescriptor nd=null;
- if(exp.getType().isInt()) {
- nd = new NameDescriptor("Integer");
- ptd = state.getTypeDescriptor(nd);
- } else if(exp.getType().isLong()) {
- nd = new NameDescriptor("Long");
- ptd = state.getTypeDescriptor(nd);
- }
- boolean isglobal = false;
- String disjointId = null;
- CreateObjectNode con=new CreateObjectNode(ptd, isglobal, disjointId);
- con.addArgument(exp);
- checkExpressionNode(md, nametable, con, null);
- min.setArgument(con, i);
+ // Shall wrap this primitive parameter as a object
+ ExpressionNode exp = min.getArg(i);
+ TypeDescriptor ptd = null;
+ NameDescriptor nd=null;
+ if(exp.getType().isInt()) {
+ nd = new NameDescriptor("Integer");
+ ptd = state.getTypeDescriptor(nd);
+ } else if(exp.getType().isLong()) {
+ nd = new NameDescriptor("Long");
+ ptd = state.getTypeDescriptor(nd);
+ }
+ boolean isglobal = false;
+ String disjointId = null;
+ CreateObjectNode con=new CreateObjectNode(ptd, isglobal, disjointId);
+ con.addArgument(exp);
+ checkExpressionNode(md, nametable, con, null);
+ min.setArgument(con, i);
}
}
}
case Operation.LOGIC_OR:
case Operation.LOGIC_AND:
if (!(rtd.isBoolean()))
- throw new Error();
+ throw new Error();
on.setRightType(rtd);
case Operation.LOGIC_NOT:
if (!(ltd.isBoolean()))
- throw new Error();
+ throw new Error();
//no promotion
on.setLeftType(ltd);
// 5.6.2 Binary Numeric Promotion
//TODO unboxing of reference objects
if (ltd.isDouble())
- throw new Error();
+ throw new Error();
else if (ltd.isFloat())
- throw new Error();
+ throw new Error();
else if (ltd.isLong())
- lefttype=new TypeDescriptor(TypeDescriptor.LONG);
+ lefttype=new TypeDescriptor(TypeDescriptor.LONG);
else
- lefttype=new TypeDescriptor(TypeDescriptor.INT);
+ lefttype=new TypeDescriptor(TypeDescriptor.INT);
on.setLeftType(lefttype);
on.setType(lefttype);
break;
// 5.6.2 Binary Numeric Promotion
//TODO unboxing of reference objects
if (ltd.isDouble()||rtd.isDouble())
- throw new Error();
+ throw new Error();
else if (ltd.isFloat()||rtd.isFloat())
- throw new Error();
+ throw new Error();
else if (ltd.isLong()||rtd.isLong())
- lefttype=new TypeDescriptor(TypeDescriptor.LONG);
+ lefttype=new TypeDescriptor(TypeDescriptor.LONG);
// 090205 hack for boolean
else if (ltd.isBoolean()||rtd.isBoolean())
- lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
+ lefttype=new TypeDescriptor(TypeDescriptor.BOOLEAN);
else
- lefttype=new TypeDescriptor(TypeDescriptor.INT);
+ lefttype=new TypeDescriptor(TypeDescriptor.INT);
righttype=lefttype;
on.setLeftType(lefttype);
case Operation.ISAVAILABLE:
if (!(ltd.isPtr())) {
- throw new Error("Can't use isavailable on non-pointers/non-parameters.");
+ throw new Error("Can't use isavailable on non-pointers/non-parameters.");
}
lefttype=ltd;
on.setLeftType(lefttype);
// 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);
+ 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())) {
- if(!rtd.isEnum()) {
- throw new Error();
- }
- }
- righttype=rtd;
- lefttype=ltd;
+ if (!(ltd.isPtr()&&rtd.isPtr())) {
+ if(!rtd.isEnum()) {
+ throw new Error();
+ }
+ }
+ righttype=rtd;
+ lefttype=ltd;
} else if (ltd.isDouble()||rtd.isDouble())
- righttype=lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
+ righttype=lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
else if (ltd.isFloat()||rtd.isFloat())
- righttype=lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
+ righttype=lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
else if (ltd.isLong()||rtd.isLong())
- righttype=lefttype=new TypeDescriptor(TypeDescriptor.LONG);
+ righttype=lefttype=new TypeDescriptor(TypeDescriptor.LONG);
else
- righttype=lefttype=new TypeDescriptor(TypeDescriptor.INT);
+ righttype=lefttype=new TypeDescriptor(TypeDescriptor.INT);
on.setLeftType(lefttype);
on.setRightType(righttype);
// 5.6.2 Binary Numeric Promotion
//TODO unboxing of reference objects
if (!ltd.isNumber()||!rtd.isNumber()) {
- if (!ltd.isNumber())
- throw new Error("Leftside is not number"+on.printNode(0)+"type="+ltd.toPrettyString());
- if (!rtd.isNumber())
- throw new Error("Rightside is not number"+on.printNode(0));
+ if (!ltd.isNumber())
+ throw new Error("Leftside is not number"+on.printNode(0)+"type="+ltd.toPrettyString());
+ if (!rtd.isNumber())
+ throw new Error("Rightside is not number"+on.printNode(0));
}
if (ltd.isDouble()||rtd.isDouble())
- lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
+ lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
else if (ltd.isFloat()||rtd.isFloat())
- lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
+ lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
else if (ltd.isLong()||rtd.isLong())
- lefttype=new TypeDescriptor(TypeDescriptor.LONG);
+ lefttype=new TypeDescriptor(TypeDescriptor.LONG);
else
- lefttype=new TypeDescriptor(TypeDescriptor.INT);
+ lefttype=new TypeDescriptor(TypeDescriptor.INT);
righttype=lefttype;
on.setLeftType(lefttype);
on.setRightType(righttype);
case Operation.ADD:
if (ltd.isString()||rtd.isString()) {
- ClassDescriptor stringcl=getClass(null, 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.setNumLine(on.getLeft().getNumLine());
- 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.setNumLine(on.getRight().getNumLine());
- rightmin.addArgument(on.getRight());
- on.right=rightmin;
- checkExpressionNode(md, nametable, on.getRight(), null);
- }
-
- on.setLeftType(stringtd);
- on.setRightType(stringtd);
- on.setType(stringtd);
- break;
+ ClassDescriptor stringcl=getClass(null, 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.setNumLine(on.getLeft().getNumLine());
+ 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.setNumLine(on.getRight().getNumLine());
+ 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:
// 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));
+ throw new Error("Error in "+on.printNode(0));
if (ltd.isDouble()||rtd.isDouble())
- lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
+ lefttype=new TypeDescriptor(TypeDescriptor.DOUBLE);
else if (ltd.isFloat()||rtd.isFloat())
- lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
+ lefttype=new TypeDescriptor(TypeDescriptor.FLOAT);
else if (ltd.isLong()||rtd.isLong())
- lefttype=new TypeDescriptor(TypeDescriptor.LONG);
+ lefttype=new TypeDescriptor(TypeDescriptor.LONG);
else
- lefttype=new TypeDescriptor(TypeDescriptor.INT);
+ lefttype=new TypeDescriptor(TypeDescriptor.INT);
righttype=lefttype;
on.setLeftType(lefttype);
on.setRightType(righttype);
case Operation.RIGHTSHIFT:
case Operation.URIGHTSHIFT:
if (!rtd.isIntegerType())
- throw new Error();
+ throw new Error();
//5.6.1 Unary Numeric Promotion
if (rtd.isByte()||rtd.isShort()||rtd.isInt())
- righttype=new TypeDescriptor(TypeDescriptor.INT);
+ righttype=new TypeDescriptor(TypeDescriptor.INT);
else
- righttype=rtd;
+ righttype=rtd;
on.setRightType(righttype);
if (!ltd.isIntegerType())
- throw new Error();
+ throw new Error();
case Operation.UNARYPLUS:
case Operation.UNARYMINUS:
case Operation.PREINC:
case Operation.PREDEC:*/
if (!ltd.isNumber())
- throw new Error();
+ throw new Error();
//5.6.1 Unary Numeric Promotion
if (ltd.isByte()||ltd.isShort()||ltd.isInt())
- lefttype=new TypeDescriptor(TypeDescriptor.INT);
+ lefttype=new TypeDescriptor(TypeDescriptor.INT);
else
- lefttype=ltd;
+ lefttype=ltd;
on.setLeftType(lefttype);
on.setType(lefttype);
break;
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));
+ System.out.println(td);
+ System.out.println(on.getType());
+ throw new Error("Type of rside not compatible with type of lside"+on.printNode(0));
}
}
if(c != null) {
Long t = this.trueExpr.evaluate();
if(t != null) {
- Long f = this.falseExpr.evaluate();
- if(f != null) {
- if(c.intValue() > 0) {
- eval = t;
- } else {
- eval = f;
- }
- }
+ Long f = this.falseExpr.evaluate();
+ if(f != null) {
+ if(c.intValue() > 0) {
+ eval = t;
+ } else {
+ eval = f;
+ }
+ }
}
}
return eval;
if (o instanceof TypeDescriptor) {
TypeDescriptor t=(TypeDescriptor)o;
if (t.type!=type)
- return false;
+ return false;
if ((type==CLASS)&&(!t.getSymbol().equals(getSymbol())))
- return false;
+ return false;
if (t.arraycount!=arraycount)
- return false;
+ return false;
if (t.isClassNameRef != this.isClassNameRef)
- return false;
+ return false;
return true;
}
return false;
String path = (String) state.classpath.get(i);
File f = new File(path, cl.replace('.', '/') + ".java");
if (f.exists()) {
- try {
- ParseNode pn = Main.readSourceFile(state, f.getCanonicalPath());
- bir.buildtree(pn, todo, f.getCanonicalPath());
- return;
- } catch (Exception e) {
- throw new Error(e);
- }
+ try {
+ ParseNode pn = Main.readSourceFile(state, f.getCanonicalPath());
+ bir.buildtree(pn, todo, f.getCanonicalPath());
+ return;
+ } catch (Exception e) {
+ throw new Error(e);
+ }
}
}
throw new Error("Couldn't find class " + cl);
if (!supertable.containsKey(cd)) {
String superc=cd.getSuper();
if (superc!=null) {
- ClassDescriptor cd_super=getClass(superc, todo);
- supertable.put(cd,cd_super);
+ ClassDescriptor cd_super=getClass(superc, todo);
+ supertable.put(cd,cd_super);
}
}
if (!superIFtbl.containsKey(cd)) {
HashSet hs=(HashSet)superIFtbl.get(cd);
Vector<String> superifv = cd.getSuperInterface();
for(int i = 0; i < superifv.size(); i++) {
- String superif = superifv.elementAt(i);
- ClassDescriptor if_super = getClass(superif, todo);
- hs.add(if_super);
+ String superif = superifv.elementAt(i);
+ ClassDescriptor if_super = getClass(superif, todo);
+ hs.add(if_super);
}
}
return cd;
for(Iterator methodit=cd.getMethodTable().getSet("run").iterator(); methodit.hasNext(); ) {
MethodDescriptor md=(MethodDescriptor) methodit.next();
if (md.numParameters()!=0||md.getModifiers().isStatic())
- continue;
+ continue;
return md;
}
throw new Error("Can't find Thread.run");
for(Iterator methodit=cd.getMethodTable().getSet("staticStart").iterator(); methodit.hasNext(); ) {
MethodDescriptor md=(MethodDescriptor) methodit.next();
if (md.numParameters()!=1||!md.getModifiers().isStatic()||!md.getParamType(0).isClass()||md.getParamType(0).getClassDesc()!=cd)
- continue;
+ continue;
return md;
}
throw new Error("Can't find Thread.run");
for(Iterator methodit = cd.getMethodTable().getSet("execute").iterator(); methodit.hasNext(); ) {
MethodDescriptor md = (MethodDescriptor) methodit.next();
if (md.numParameters()!=0 || md.getModifiers().isStatic())
- continue;
+ continue;
return md;
}
throw new Error("Can't find Task.execute");
for(Iterator mainit=mainset.iterator(); mainit.hasNext(); ) {
MethodDescriptor md=(MethodDescriptor)mainit.next();
if (md.numParameters()!=1)
- continue;
+ continue;
Descriptor pd=md.getParameter(0);
TypeDescriptor tpd=(pd instanceof TagVarDescriptor)?((TagVarDescriptor)pd).getType():((VarDescriptor)pd)
.getType();
if (tpd.getArrayCount()!=1)
- continue;
+ continue;
if (!tpd.getSymbol().equals(StringClass))
- continue;
+ continue;
if (!md.getModifiers().isStatic())
- throw new Error("Error: Non static main");
+ throw new Error("Error: Non static main");
return md;
}
throw new Error(cd+" has no main");
throw new Error();
for(int i=0; i<md1.numParameters(); i++) {
if (!this.isSuperorType(md2.getParamType(i), md1.getParamType(i))) {
- if(((!md1.getParamType(i).isArray() &&
- (md1.getParamType(i).isInt() || md1.getParamType(i).isLong() || md1.getParamType(i).isDouble() || md1.getParamType(i).isFloat()))
- && md2.getParamType(i).isClass() && md2.getParamType(i).getClassDesc().getSymbol().equals("Object"))) {
- // primitive parameters vs Object
- } else {
- return false;
- }
+ if(((!md1.getParamType(i).isArray() &&
+ (md1.getParamType(i).isInt() || md1.getParamType(i).isLong() || md1.getParamType(i).isDouble() || md1.getParamType(i).isFloat()))
+ && md2.getParamType(i).isClass() && md2.getParamType(i).getClassDesc().getSymbol().equals("Object"))) {
+ // primitive parameters vs Object
+ } else {
+ return false;
+ }
}
}
if (md1.getReturnType()==null||md2.getReturnType()==null) {
if (md1.getReturnType()!=md2.getReturnType())
- return false;
+ return false;
} else
if (!this.isSuperorType(md2.getReturnType(), md1.getReturnType()))
return false;
MethodDescriptor currmd=(MethodDescriptor)methodit.next();
/* Need correct number of parameters */
if (types.length!=currmd.numParameters())
- continue;
+ continue;
for(int i=0; i<types.length; i++) {
- if (!this.isSuperorType(currmd.getParamType(i),types[i]))
- continue NextMethod;
+ if (!this.isSuperorType(currmd.getParamType(i),types[i]))
+ continue NextMethod;
}
/* Method okay so far */
if (bestmd==null)
- bestmd=currmd;
+ bestmd=currmd;
else {
- if (isMoreSpecific(currmd,bestmd)) {
- bestmd=currmd;
- } else if (!isMoreSpecific(bestmd, currmd))
- throw new Error("No method is most specific");
+ 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 */
+ /* Is this more specific than bestmd */
}
}
if (bestmd==null)
// check cd's interface ancestors
{
- Iterator it_sifs = cd.getSuperInterfaces();
- while(it_sifs.hasNext()) {
- ClassDescriptor cdt = (ClassDescriptor)it_sifs.next();
- if(!tovisit.contains(cdt)) {
- tovisit.add(cdt);
- }
- }
+ Iterator it_sifs = cd.getSuperInterfaces();
+ while(it_sifs.hasNext()) {
+ ClassDescriptor cdt = (ClassDescriptor)it_sifs.next();
+ if(!tovisit.contains(cdt)) {
+ tovisit.add(cdt);
+ }
+ }
}
while(tmp!=null) {
- if (!subclasstable.containsKey(tmp))
- subclasstable.put(tmp,new HashSet());
- HashSet hs=(HashSet)subclasstable.get(tmp);
- hs.add(cd);
- // check tmp's interface ancestors
- Iterator it_sifs = tmp.getSuperInterfaces();
- while(it_sifs.hasNext()) {
- ClassDescriptor cdt = (ClassDescriptor)it_sifs.next();
- if(!tovisit.contains(cdt)) {
- tovisit.add(cdt);
- }
- }
-
- tmp=tmp.getSuperDesc();
+ if (!subclasstable.containsKey(tmp))
+ subclasstable.put(tmp,new HashSet());
+ HashSet hs=(HashSet)subclasstable.get(tmp);
+ hs.add(cd);
+ // check tmp's interface ancestors
+ Iterator it_sifs = tmp.getSuperInterfaces();
+ while(it_sifs.hasNext()) {
+ ClassDescriptor cdt = (ClassDescriptor)it_sifs.next();
+ if(!tovisit.contains(cdt)) {
+ tovisit.add(cdt);
+ }
+ }
+
+ tmp=tmp.getSuperDesc();
}
while(!tovisit.isEmpty()) {
- ClassDescriptor sif = (ClassDescriptor)tovisit.iterator().next();
- tovisit.remove(sif);
-
- if(!visited.contains(sif)) {
- if(!this.subclasstable.containsKey(sif)) {
- this.subclasstable.put(sif, new HashSet());
- }
- HashSet hs = (HashSet) this.subclasstable.get(sif);
- hs.add(cd);
-
- Iterator it_sifs = sif.getSuperInterfaces();
- while(it_sifs.hasNext()) {
- ClassDescriptor siftmp = (ClassDescriptor)it_sifs.next();
- if(!tovisit.contains(siftmp)) {
- tovisit.add(siftmp);
- }
- }
- visited.add(sif);
- }
+ ClassDescriptor sif = (ClassDescriptor)tovisit.iterator().next();
+ tovisit.remove(sif);
+
+ if(!visited.contains(sif)) {
+ if(!this.subclasstable.containsKey(sif)) {
+ this.subclasstable.put(sif, new HashSet());
+ }
+ HashSet hs = (HashSet) this.subclasstable.get(sif);
+ hs.add(cd);
+
+ Iterator it_sifs = sif.getSuperInterfaces();
+ while(it_sifs.hasNext()) {
+ ClassDescriptor siftmp = (ClassDescriptor)it_sifs.next();
+ if(!tovisit.contains(siftmp)) {
+ tovisit.add(siftmp);
+ }
+ }
+ visited.add(sif);
+ }
}
}
}
if (cd2.isArray()||possiblesuper.isArray()) {
// Object is super class of all arrays
if (possiblesuper.getSymbol().equals(ObjectClass)&&!possiblesuper.isArray())
- return true;
+ 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;
+ return true;
// Object is superclass of all array classes
if (possiblesuper.getSymbol().equals(ObjectClass)&&cd2.isClass()
&&(possiblesuper.getArrayCount()<cd2.getArrayCount()))
- return true;
+ return true;
//Allow arraytype=null statements
if (possiblesuper.isArray()&&cd2.isNull())
- return true;
+ return true;
return false;
}
if (cd2.isByte()&&(possiblesuper.isByte()||possiblesuper.isShort()||
possiblesuper.isInt()||possiblesuper.isLong()||
possiblesuper.isFloat()||possiblesuper.isDouble()))
- return true;
+ return true;
if (cd2.isShort()&&(possiblesuper.isShort()||
possiblesuper.isInt()||possiblesuper.isLong()||
possiblesuper.isFloat()||possiblesuper.isDouble()))
- return true;
+ return true;
if (cd2.isChar()&&(possiblesuper.isChar()||
possiblesuper.isInt()||possiblesuper.isLong()||
possiblesuper.isFloat()||possiblesuper.isDouble()))
- return true;
+ return true;
if (cd2.isInt()&&(possiblesuper.isInt()||possiblesuper.isLong()||
possiblesuper.isFloat()||possiblesuper.isDouble()
||possiblesuper.isEnum()))
- return true;
+ return true;
if (cd2.isEnum()&&(possiblesuper.isInt()||possiblesuper.isLong()||
possiblesuper.isFloat()||possiblesuper.isDouble()))
- return true;
+ return true;
if(cd2.isEnum()&&possiblesuper.isEnum()&&cd2.class_desc.equals(possiblesuper.class_desc))
- return true;
+ return true;
if (cd2.isLong()&&(possiblesuper.isLong()||
possiblesuper.isFloat()||possiblesuper.isDouble()))
- return true;
+ return true;
if (cd2.isFloat()&&(possiblesuper.isFloat()||possiblesuper.isDouble()))
- return true;
+ return true;
if (cd2.isDouble()&&possiblesuper.isDouble())
- return true;
+ return true;
if (cd2.isBoolean()&&possiblesuper.isBoolean())
- return true;
+ return true;
return false;
} else if (possiblesuper.isPrimitive()&&(!possiblesuper.isArray())&&
// check cd2's interface ancestors
Iterator<ClassDescriptor> it_sifs = getSuperIFs(cd2).iterator();
while(it_sifs.hasNext()) {
- ClassDescriptor cd = it_sifs.next();
- if(cd == possiblesuper) {
- return true;
- } else if(!tovisit.contains(cd)) {
- tovisit.add(cd);
- }
+ ClassDescriptor cd = it_sifs.next();
+ if(cd == possiblesuper) {
+ return true;
+ } else if(!tovisit.contains(cd)) {
+ tovisit.add(cd);
+ }
}
}
while(cd2!=null) {
cd2=getSuper(cd2);
if (cd2==possiblesuper)
- return true;
+ return true;
// check cd2's interface ancestors
if(cd2 != null) {
- Iterator it_sifs = getSuperIFs(cd2).iterator();
- while(it_sifs.hasNext()) {
- ClassDescriptor cd = (ClassDescriptor)it_sifs.next();
- if(cd == possiblesuper) {
- return true;
- } else if(!tovisit.contains(cd)) {
- tovisit.add(cd);
- }
- }
+ Iterator it_sifs = getSuperIFs(cd2).iterator();
+ while(it_sifs.hasNext()) {
+ ClassDescriptor cd = (ClassDescriptor)it_sifs.next();
+ if(cd == possiblesuper) {
+ return true;
+ } else if(!tovisit.contains(cd)) {
+ tovisit.add(cd);
+ }
+ }
}
}
tovisit.remove(cd);
if(!visited.contains(cd)) {
- Iterator it_sifs = getSuperIFs(cd).iterator();
- while(it_sifs.hasNext()) {
- ClassDescriptor cdt = (ClassDescriptor)it_sifs.next();
- if(cdt == possiblesuper) {
- return true;
- } else if(!tovisit.contains(cdt)) {
- tovisit.add(cdt);
- }
- }
- visited.add(cd);
+ Iterator it_sifs = getSuperIFs(cd).iterator();
+ while(it_sifs.hasNext()) {
+ ClassDescriptor cdt = (ClassDescriptor)it_sifs.next();
+ if(cdt == possiblesuper) {
+ return true;
+ } else if(!tovisit.contains(cdt)) {
+ tovisit.add(cdt);
+ }
+ }
+ visited.add(cd);
}
}
return false;
while(classit.hasNext()) {
ClassDescriptor cd=(ClassDescriptor)classit.next();
if (state.DSM||state.SINGLETM)
- numberLocality(cd);
+ numberLocality(cd);
else
- numberMethods(cd);
+ numberMethods(cd);
}
classit=state.getClassSymbolTable().getDescriptorsIterator();
while(classit.hasNext()) {
ClassDescriptor cd=(ClassDescriptor)classit.next();
if(!cd.isInterface()) {
- int count = classmethodcount.get(cd).intValue();
- classmethodcount.put(cd, new Integer(count+this.if_starts));
+ int count = classmethodcount.get(cd).intValue();
+ classmethodcount.put(cd, new Integer(count+this.if_starts));
}
}
}
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++));
- }
+ 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;
for(Iterator it=cd.getMethods(); it.hasNext(); ) {
MethodDescriptor md=(MethodDescriptor)it.next();
if (md.isStatic()||md.getReturnType()==null)
- continue;
+ continue;
if (!callgraph.isCallable(md)&&!callgraph.isCalled(md))
- continue;
+ continue;
boolean foundmatch=false;
// check if there is a matched method that has been assigned method num
Set possiblematches_if = if_methods.getSet(md.getSymbol());
for(Iterator matchit=possiblematches_if.iterator(); matchit.hasNext(); ) {
- MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
- if (md.matches(matchmd)) {
- int num=methodnumber.get(matchmd);
- methodnumber.put(md, new Integer(num));
- foundmatch=true;
- break;
- }
+ MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
+ if (md.matches(matchmd)) {
+ int num=methodnumber.get(matchmd);
+ methodnumber.put(md, new Integer(num));
+ foundmatch=true;
+ break;
+ }
}
if (!foundmatch) {
- methodnumber.put(md, new Integer(if_starts++));
- if_methods.add(md);
- mnum++;
+ methodnumber.put(md, new Integer(if_starts++));
+ if_methods.add(md);
+ mnum++;
}
}
classmethodcount.put(cd, new Integer(mnum));
for(Iterator it=cd.getMethods(); it.hasNext(); ) {
MethodDescriptor md=(MethodDescriptor)it.next();
if (md.isStatic()||md.getReturnType()==null)
- continue;
+ continue;
if (!callgraph.isCallable(md)&&!callgraph.isCalled(md))
- continue;
+ continue;
// check if there is a matched method in methods defined in interfaces
Set possiblematches_if=if_methods.getSet(md.getSymbol());
for(Iterator matchit=possiblematches_if.iterator(); matchit.hasNext(); ) {
- MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
- if (md.matches(matchmd)) {
- int num;
- if (!methodnumber.containsKey(matchmd)) {
- num=start++;
- mnum++;
- methodnumber.put(matchmd,num);
- } else
- num = methodnumber.get(matchmd);
- methodnumber.put(md, new Integer(num));
- continue methodit;
- }
+ MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
+ if (md.matches(matchmd)) {
+ int num;
+ if (!methodnumber.containsKey(matchmd)) {
+ num=start++;
+ mnum++;
+ methodnumber.put(matchmd,num);
+ } else
+ num = methodnumber.get(matchmd);
+ methodnumber.put(md, new Integer(num));
+ continue methodit;
+ }
}
if (superdesc!=null) {
- Set possiblematches=superdesc.getMethodTable().getSet(md.getSymbol());
- for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) {
- MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
- if (md.matches(matchmd)) {
- int num;
- if (!methodnumber.containsKey(matchmd)) {
- num=start++;
- mnum++;
- methodnumber.put(matchmd,num);
- } else
- num = methodnumber.get(matchmd);
- methodnumber.put(md, new Integer(num));
- continue methodit;
- }
- }
+ Set possiblematches=superdesc.getMethodTable().getSet(md.getSymbol());
+ for(Iterator matchit=possiblematches.iterator(); matchit.hasNext(); ) {
+ MethodDescriptor matchmd=(MethodDescriptor)matchit.next();
+ if (md.matches(matchmd)) {
+ int num;
+ if (!methodnumber.containsKey(matchmd)) {
+ num=start++;
+ mnum++;
+ methodnumber.put(matchmd,num);
+ } else
+ num = methodnumber.get(matchmd);
+ methodnumber.put(md, new Integer(num));
+ continue methodit;
+ }
+ }
}
methodnumber.put(md, new Integer(start++));
try {
while((size = reader.read(buffer,0,buffer.length)) != -1)
- out.write(buffer,0,size);
+ out.write(buffer,0,size);
reader.close();
} catch(IOException e) {
e.printStackTrace();
int i = key.hashCode() % n;
while (p[i] != null) {
if (key.equals(p[i].key)) {
- p[i] = new Pair(key, value);
- return;
+ p[i] = new Pair(key, value);
+ return;
}
i = (i+1) % n;
}
int i = key.hashCode() % n;
while (p[i] != null) {
if (key.equals(p[i].key))
- return p[i].value;
+ return p[i].value;
i = (i+1) % n;
}
return null;
IdentityRelation ir=(IdentityRelation) obj;
if (fieldname1.equals(ir.fieldname1)&&
fieldname2.equals(ir.fieldname2))
- return true;
+ return true;
}
return false;
}
Rectangle r=rectangles[i];
if ((r.x1<=x)&&(r.y1>=y)&&
(r.x2>=x)&&(r.y2<=y))
- return r.label;
+ return r.label;
}
long mindistance=Long.MAX_VALUE;
int minindex=-1;
long dx=p.x-x;
long dy=p.y-y;
if ((dx*dx+dy*dy)<mindistance) {
- mindistance=dx*dx+dy*dy;
- minindex=i;
+ mindistance=dx*dx+dy*dy;
+ minindex=i;
}
}
if (mindistance>THRESHOLD)
ArrayList points=new ArrayList();
while(true) {
try {
- firstchar=fr.read();
+ firstchar=fr.read();
} catch (Exception e) {
- e.printStackTrace();
- System.exit(-1);
+ e.printStackTrace();
+ System.exit(-1);
}
/* EOF?*/
if (firstchar==-1)
- break;
+ break;
switch(firstchar) {
case 'b':
case '#':
- while(firstchar!='\n') {
- try {
- firstchar=fr.read();
- } catch (IOException e) {
- e.printStackTrace();
- System.exit(-1);
- }
- }
- break;
+ while(firstchar!='\n') {
+ try {
+ firstchar=fr.read();
+ } catch (IOException e) {
+ e.printStackTrace();
+ System.exit(-1);
+ }
+ }
+ break;
case 'r':
{
- nexttoken(fr,false);
- String label=nexttoken(fr,false);
- String x1=nexttoken(fr,true);
- String y1=nexttoken(fr,true);
- String x2=nexttoken(fr,true);
- String y2=nexttoken(fr,true);
- Rectangle r=new Rectangle(label,Integer.parseInt(x1),Integer.parseInt(y1),
- Integer.parseInt(x2),Integer.parseInt(y2));
- rectangles.add(r);
+ nexttoken(fr,false);
+ String label=nexttoken(fr,false);
+ String x1=nexttoken(fr,true);
+ String y1=nexttoken(fr,true);
+ String x2=nexttoken(fr,true);
+ String y2=nexttoken(fr,true);
+ Rectangle r=new Rectangle(label,Integer.parseInt(x1),Integer.parseInt(y1),
+ Integer.parseInt(x2),Integer.parseInt(y2));
+ rectangles.add(r);
}
break;
case 'p':
{
- nexttoken(fr,false);
- String label=nexttoken(fr,false);
- String x=nexttoken(fr,true);
- String y=nexttoken(fr,true);
- Point p=new Point(label,Integer.parseInt(x),Integer.parseInt(y));
- points.add(p);
+ nexttoken(fr,false);
+ String label=nexttoken(fr,false);
+ String x=nexttoken(fr,true);
+ String y=nexttoken(fr,true);
+ Point p=new Point(label,Integer.parseInt(x),Integer.parseInt(y));
+ points.add(p);
}
break;
}
boolean looped=false;
while(true) {
try {
- c=isr.read();
+ c=isr.read();
} catch (IOException e) {
- e.printStackTrace();
- System.exit(-1);
+ e.printStackTrace();
+ System.exit(-1);
}
if ((c==' ')||(c=='\n')||(commas&&c==',')) {
- if (!looped) {
- looped=true;
- continue;
- }
- return string;
+ if (!looped) {
+ looped=true;
+ continue;
+ }
+ return string;
}
string=string+new String(new char[] {(char)c});
looped=true;
// infinite loop
while (true) {
try {
- startWorker(server.accept());
+ startWorker(server.accept());
} catch (Exception e) {
- System.err.println(e);
+ System.err.println(e);
}
}
}
switch(method(in)) {
case 0:
- if (webinterface.specialRequest(fileName)) {
- String newfile=webinterface.handleresponse(fileName, out, resp);
- if (newfile!=null) {
- HTTPServices.GET_handler(newfile, out, resp);
- }
- } else
- HTTPServices.GET_handler(fileName, out, resp);
- break;
+ if (webinterface.specialRequest(fileName)) {
+ String newfile=webinterface.handleresponse(fileName, out, resp);
+ if (newfile!=null) {
+ HTTPServices.GET_handler(newfile, out, resp);
+ }
+ } else
+ HTTPServices.GET_handler(fileName, out, resp);
+ break;
case 1:
- HTTPServices.HEAD_handler(fileName, out, resp);
- break;
+ HTTPServices.HEAD_handler(fileName, out, resp);
+ break;
case 2:
- HTTPServices.POST_handler(fileName, out, resp);
- break;
+ HTTPServices.POST_handler(fileName, out, resp);
+ break;
default:
- resp.returnCode = 501; //error
+ resp.returnCode = 501; //error
}
try {
- out.flush();
- if (logging)
- LogFile.write_log(client,methodType,fileName,httpVersion,
- resp.returnCode,resp.sentBytes);
-
- out.close();
- in.close();
- client.close();
+ out.flush();
+ if (logging)
+ LogFile.write_log(client,methodType,fileName,httpVersion,
+ resp.returnCode,resp.sentBytes);
+
+ out.close();
+ in.close();
+ client.close();
} catch(IOException e) {
- ; // do nothing
+ ; // do nothing
}
}
// only spaces used
StringTokenizer tok = new StringTokenizer(line, " ");
if (tok.hasMoreTokens()) { // make sure there is a request
- String str = tok.nextToken();
-
- if ( str.equals("GET") ) {
- ret = 0;
- methodType = "GET";
- } else if ( str.equals("HEAD") ) {
- ret = 1;
- methodType = "HEAD";
- } else if ( str.equals("POST") ) {
- ret = 2;
- methodType = "POST";
- } else {
- System.out.println("501 - unsupported request:" +str);
- return -1;
- }
+ String str = tok.nextToken();
+
+ if ( str.equals("GET") ) {
+ ret = 0;
+ methodType = "GET";
+ } else if ( str.equals("HEAD") ) {
+ ret = 1;
+ methodType = "HEAD";
+ } else if ( str.equals("POST") ) {
+ ret = 2;
+ methodType = "POST";
+ } else {
+ System.out.println("501 - unsupported request:" +str);
+ return -1;
+ }
} else {
- // System.out.println("Request from browser was empty!");
- return -1;
+ // System.out.println("Request from browser was empty!");
+ return -1;
}
// get the filename
if (tok.hasMoreTokens()) {
- fileName = tok.nextToken();
- if(fileName.equals("/")) {
- fileName = "/index.html";
- }
+ fileName = tok.nextToken();
+ if(fileName.equals("/")) {
+ fileName = "/index.html";
+ }
} else
{
- // this is weird... why am i taking the first character of
- // the filename if there are no more tokens?
- // - catch should take care of this
- fileName = fileName.substring(1);
+ // this is weird... why am i taking the first character of
+ // the filename if there are no more tokens?
+ // - catch should take care of this
+ fileName = fileName.substring(1);
}
// read the http version number
// - right now nothing is done with this information
if (tok.hasMoreTokens()) {
- httpVersion = tok.nextToken();
+ httpVersion = tok.nextToken();
} else
{
- httpVersion = "http/1.0"; // default
+ httpVersion = "http/1.0"; // default
}
// read remainder of the browser's header
// - nothing done right now with this info... placeholder
while((line = in.readLine()) != null) {
- StringTokenizer token = new StringTokenizer(line," ");
+ StringTokenizer token = new StringTokenizer(line," ");
- // do processing here
- if(!token.hasMoreTokens()) {
- break;
- }
+ // do processing here
+ if(!token.hasMoreTokens()) {
+ break;
+ }
}
} catch(Exception e) {
System.err.println(e);
for(Iterator it_classes=state.getClassSymbolTable().getDescriptorsIterator(); it_classes.hasNext(); ) {
ClassDescriptor cd=(ClassDescriptor) it_classes.next();
if(cd.hasFlags()) {
- Vector rootnodes=taskanalysis.getRootNodes(cd);
-
- if(rootnodes!=null)
- for(Iterator it_rootnodes=rootnodes.iterator(); it_rootnodes.hasNext(); ) {
- FlagState root=(FlagState)it_rootnodes.next();
- Vector cd_nodeid=new Vector(); //Vector is designed to contain only 2 elements: ClassDescriptor,Node label
- // Both the values are required to correctly resolve the rootnode.
- // Should think of a better way to do this, instead of using a vector(maybe a class)
- cd_nodeid.addElement(cd); //adding the ClassDescriptor
- cd_nodeid.addElement(root.getLabel()); //adding the Node label
- System.out.println(cd+" "+root.getLabel());
- sourcenodemap.put("/"+cd.getSymbol()+"_"+root.getLabel()+".html",cd_nodeid);
- }
+ Vector rootnodes=taskanalysis.getRootNodes(cd);
+
+ if(rootnodes!=null)
+ for(Iterator it_rootnodes=rootnodes.iterator(); it_rootnodes.hasNext(); ) {
+ FlagState root=(FlagState)it_rootnodes.next();
+ Vector cd_nodeid=new Vector(); //Vector is designed to contain only 2 elements: ClassDescriptor,Node label
+ // Both the values are required to correctly resolve the rootnode.
+ // Should think of a better way to do this, instead of using a vector(maybe a class)
+ cd_nodeid.addElement(cd); //adding the ClassDescriptor
+ cd_nodeid.addElement(root.getLabel()); //adding the Node label
+ System.out.println(cd+" "+root.getLabel());
+ sourcenodemap.put("/"+cd.getSymbol()+"_"+root.getLabel()+".html",cd_nodeid);
+ }
}
}
}
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>");
+ 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();
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.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) {
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;
+ 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;
}
}
//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.println(str);
}
pw.flush();
pw.println("<img src=\""+cd.getSymbol()+"-t.jpg\" usemap=\"#dotvisitor\" />");
while((str=mapbr.readLine())!=null) {
- pw.println(str);
+ pw.println(str);
}
pw.flush();
} catch (Exception e) {
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);
- }
+ 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);
+ }
}
}
pw.println("<br><br><a href=\"/UnifiedTaskGraph.html\">Program flow</a>");
pw.println("<img src=\"/UnifiedTaskGraph.jpg\" usemap=\"#dotvisitor\" />");
while((str=mapbr.readLine())!=null)
- pw.println(str);
+ pw.println(str);
pw.flush();
} catch (Exception e) {
// skip leading white space.
for (; i<more.length(); i++)
if (!Character.isSpaceChar(more.charAt(i)))
- break;
+ break;
// skip any leading stars.
for (; i<more.length(); i++)
if (more.charAt(i)!='*')
- break;
+ break;
// the rest of the string belongs to the comment.
if (i<more.length())
return r;
} else { // found a backslash;
if (!isEvenSlash) { // Only even slashes are eligible unicode escapes.
- isEvenSlash=true;
- return r;
+ isEvenSlash=true;
+ return r;
}
// Check for the trailing u.
pushback=in.read();
if (pushback!='u') {
- isEvenSlash=false;
- return '\\';
+ isEvenSlash=false;
+ return '\\';
}
// 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.
// If we don't, we can raise bloody hell.
int val=0;
for (int i=0; i<4; i++, r=in.read()) {
- int d=Character.digit((char)r, 16);
- if (r<0 || d<0)
- throw new Error("Invalid unicode escape character.");
- val = (val*16) + d;
+ int d=Character.digit((char)r, 16);
+ if (r<0 || d<0)
+ throw new Error("Invalid unicode escape character.");
+ val = (val*16) + d;
}
// yeah, we made it.
pushback = r;
if (lookahead==null) lookahead = new FIFO(new FIFO.Getter() {
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)
while (lookahead.peek(i).sym == Sym.DOT) {
i++;
if (lookahead.peek(i++).sym != Sym.IDENTIFIER)
- return false;
+ return false;
}
// skip past (LBRACK RBRACK)*
while (lookahead.peek(i).sym == Sym.LBRACK) {
i++;
if (lookahead.peek(i++).sym != Sym.RBRACK)
- return false;
+ return false;
}
// now the next sym has to be one of LT GT COMMA EXTENDS IMPLEMENTS
switch(lookahead.peek(i).sym) {
startpos = lineL.head + line_pos;
ie = getInputElement();
if (ie instanceof DocumentationComment)
- comment = ((Comment)ie).getComment();
+ comment = ((Comment)ie).getComment();
} while (!(ie instanceof Token));
endpos = lineL.head + line_pos - 1;
if (line.length()<=line_pos) { // end of line.
nextLine();
if (line==null)
- return new EOF();
+ return new EOF();
}
switch (line.charAt(line_pos)) {
case '*': // TraditionalComment or DocumentationComment
line_pos += 2;
if (line.charAt(line_pos)=='*') { // DocumentationComment
- return snarfComment(new DocumentationComment());
+ return snarfComment(new DocumentationComment());
} else { // TraditionalComment
- return snarfComment(new TraditionalComment());
+ return snarfComment(new TraditionalComment());
}
default: // it's a token, not a comment.
StringBuffer text=new StringBuffer();
while(true) { // Grab CommentTail
while (line.charAt(line_pos)!='*') { // Add NotStar to comment.
- int star_pos = line.indexOf('*', line_pos);
- if (star_pos<0) {
- text.append(line.substring(line_pos));
- c.appendLine(text.toString()); text.setLength(0);
- line_pos = line.length();
- nextLine();
- if (line==null)
- throw new IOException("Unterminated comment at end of file.");
- } else {
- text.append(line.substring(line_pos, star_pos));
- line_pos=star_pos;
- }
+ int star_pos = line.indexOf('*', line_pos);
+ if (star_pos<0) {
+ text.append(line.substring(line_pos));
+ c.appendLine(text.toString()); text.setLength(0);
+ line_pos = line.length();
+ nextLine();
+ if (line==null)
+ throw new IOException("Unterminated comment at end of file.");
+ } else {
+ text.append(line.substring(line_pos, star_pos));
+ line_pos=star_pos;
+ }
}
// At this point, line.charAt(line_pos)=='*'
// Grab CommentTailStar starting at line_pos+1.
if (line.charAt(line_pos+1)=='/') { // safe because line ends with '\n'
- c.appendLine(text.toString()); line_pos+=2; return c;
+ c.appendLine(text.toString()); line_pos+=2; return c;
}
text.append(line.charAt(line_pos++)); // add the '*'
}
// a period is a special case:
case '.':
if (Character.digit(line.charAt(line_pos+1),10)!=-1)
- return getNumericLiteral();
+ return getNumericLiteral();
else if (isJava15 &&
line.charAt(line_pos+1)=='.' &&
line.charAt(line_pos+2)=='.') {
- consume(); consume(); consume();
- return new Separator('\u2026'); // unicode ellipsis character.
+ consume(); consume(); consume();
+ return new Separator('\u2026'); // unicode ellipsis character.
} else return new Separator(consume());
default:
case 'l':
default:
if (line.charAt(line_pos)=='0')
- return getIntegerLiteral(/*base*/ 8);
+ return getIntegerLiteral(/*base*/ 8);
return getIntegerLiteral(/*base*/ 10);
}
}
rep+=consume();
if (line.charAt(line_pos)=='+' ||
line.charAt(line_pos)=='-')
- rep+=consume();
+ rep+=consume();
rep+=getDigits();
}
try {
switch (line.charAt(line_pos)) {
case 'f':
case 'F':
- consume();
- return new FloatLiteral(Float.valueOf(rep).floatValue());
+ consume();
+ return new FloatLiteral(Float.valueOf(rep).floatValue());
case 'd':
case 'D':
- consume();
+ consume();
/* falls through */
default:
- return new DoubleLiteral(Double.valueOf(rep).doubleValue());
+ return new DoubleLiteral(Double.valueOf(rep).doubleValue());
}
} catch (NumberFormatException e) {
throw new IOException("Illegal floating-point on line "+line_num+": "+e);
case '&':
case '|':
if (first==second)
- return new Operator(new String(new char[] {first, consume()}));
+ return new Operator(new String(new char[] {first, consume()}));
default:
break;
(first=='>' && second=='>')) { // >>
String op = new String(new char[] {first, consume()});
if (first=='>' && line.charAt(line_pos)=='>') // >>>
- op += consume();
+ op += consume();
if (line.charAt(line_pos)=='=') // <<=, >>=, >>>=
- op += consume();
+ op += consume();
return new Operator(op);
}
while (line.charAt(line_pos)!='\"') {
switch(line.charAt(line_pos)) {
case '\\':
- val.append(getEscapeSequence());
- break;
+ val.append(getEscapeSequence());
+ break;
case '\n':
- throw new IOException("Invalid string literal on line " + line_num);
+ throw new IOException("Invalid string literal on line " + line_num);
default:
- val.append(consume());
- break;
+ val.append(consume());
+ break;
}
}
char closequote = consume();
int i, val=0;
for (i=0; i<maxlength; i++)
if (Character.digit(line.charAt(line_pos), 8)!=-1) {
- val = (8*val) + Character.digit(consume(), 8);
+ val = (8*val) + Character.digit(consume(), 8);
} else break;
if ((i==0) || (val>0xFF)) // impossible.
throw new IOException("Invalid octal escape sequence in line " + line_num);
int n=line_num, c=info.left-lineL.head;
for (LineList p = lineL; p!=null; p=p.tail, n--)
if (p.head<=info.left) {
- c=info.left-p.head; break;
+ c=info.left-p.head; break;
}
System.err.println(msg+" at line "+n);
num_errors++;
case '\n': sb.append("\\n"); break;
default:
- if ((int)s.charAt(i)<32)
- sb.append("\\"+Integer.toOctalString((int)s.charAt(i)));
- else
- sb.append(s.charAt(i));
+ if ((int)s.charAt(i)<32)
+ sb.append("\\"+Integer.toOctalString((int)s.charAt(i)));
+ else
+ sb.append(s.charAt(i));
}
return sb.toString();
}
for(int i=0; i<args.length; i++) {
String option=args[i];
if (option.equals("-precise"))
- IR.Flat.BuildCode.GENERATEPRECISEGC=true;
+ IR.Flat.BuildCode.GENERATEPRECISEGC=true;
else if (option.equals("-jni"))
- state.JNI=true;
+ state.JNI=true;
else if (option.equals("-prefetch"))
- state.PREFETCH=true;
+ state.PREFETCH=true;
else if (option.equals("-dir"))
- IR.Flat.BuildCode.PREFIX=args[++i]+"/";
+ IR.Flat.BuildCode.PREFIX=args[++i]+"/";
else if (option.equals("-fastcheck"))
- state.FASTCHECK=true;
+ state.FASTCHECK=true;
else if (option.equals("-selfloop"))
- state.selfloops.add(args[++i]);
+ state.selfloops.add(args[++i]);
else if (option.equals("-outputdir"))
- state.outputdir = args[++i];
+ state.outputdir = args[++i];
else if (option.equals("-excprefetch"))
- state.excprefetch.add(args[++i]);
+ state.excprefetch.add(args[++i]);
else if (option.equals("-classlibrary"))
- state.classpath.add(args[++i]);
+ state.classpath.add(args[++i]);
else if (option.equals("-inlineatomic")) {
- state.INLINEATOMIC=true;
- state.inlineatomicdepth=Integer.parseInt(args[++i]);
+ state.INLINEATOMIC=true;
+ state.inlineatomicdepth=Integer.parseInt(args[++i]);
} else if(option.equals("-numcore")) {
- ++i;
- state.CORENUM = Integer.parseInt(args[i]);
+ ++i;
+ state.CORENUM = Integer.parseInt(args[i]);
} else if(option.equals("-numcore4gc")) {
- ++i;
- state.CORENUM4GC = Integer.parseInt(args[i]);
+ ++i;
+ state.CORENUM4GC = Integer.parseInt(args[i]);
} else if (option.equals("-mainclass"))
- state.main=args[++i];
+ state.main=args[++i];
else if (option.equals("-trueprob")) {
- state.TRUEPROB=Double.parseDouble(args[++i]);
+ state.TRUEPROB=Double.parseDouble(args[++i]);
} else if (option.equals("-printflat"))
- State.PRINTFLAT=true;
+ State.PRINTFLAT=true;
else if (option.equals("-printscheduling"))
- State.PRINTSCHEDULING=true;
+ State.PRINTSCHEDULING=true;
else if (option.equals("-minimize"))
- state.MINIMIZE=true;
+ state.MINIMIZE=true;
else if (option.equals("-printschedulesim"))
- State.PRINTSCHEDULESIM=true;
+ State.PRINTSCHEDULESIM=true;
else if (option.equals("-printcriticalpath"))
- State.PRINTCRITICALPATH=true;
+ State.PRINTCRITICALPATH=true;
else if (option.equals("-struct"))
- state.structfile=args[++i];
+ state.structfile=args[++i];
else if (option.equals("-conscheck"))
- state.CONSCHECK=true;
+ state.CONSCHECK=true;
else if (option.equals("-task"))
- state.TASK=true;
+ state.TASK=true;
else if (option.equals("-abortreaders"))
- state.ABORTREADERS=true;
+ state.ABORTREADERS=true;
else if (option.equals("-sandbox"))
- state.SANDBOX=true;
+ state.SANDBOX=true;
else if (option.equals("-taskstate"))
- state.TASKSTATE=true;
+ state.TASKSTATE=true;
else if (option.equals("-tagstate"))
- state.TAGSTATE=true;
+ state.TAGSTATE=true;
else if (option.equals("-stmarray"))
- state.STMARRAY=true;
+ state.STMARRAY=true;
else if (option.equals("-eventmonitor"))
- state.EVENTMONITOR=true;
+ state.EVENTMONITOR=true;
else if (option.equals("-dualview"))
- state.DUALVIEW=true;
+ state.DUALVIEW=true;
else if (option.equals("-hybrid"))
- state.HYBRID=true;
+ state.HYBRID=true;
else if (option.equals("-flatirtasks")) {
- state.FLATIRGRAPH=true;
- state.FLATIRGRAPHTASKS=true;
+ state.FLATIRGRAPH=true;
+ state.FLATIRGRAPHTASKS=true;
} else if (option.equals("-flatirusermethods")) {
- state.FLATIRGRAPH=true;
- state.FLATIRGRAPHUSERMETHODS=true;
+ state.FLATIRGRAPH=true;
+ state.FLATIRGRAPHUSERMETHODS=true;
} else if (option.equals("-flatirlibmethods")) {
- state.FLATIRGRAPH=true;
- state.FLATIRGRAPHLIBMETHODS=true;
+ state.FLATIRGRAPH=true;
+ state.FLATIRGRAPHLIBMETHODS=true;
} else if (option.equals("-bamboocompiletime")) {
- state.BAMBOOCOMPILETIME = true;
+ state.BAMBOOCOMPILETIME = true;
} else if (option.equals("-multicore"))
- state.MULTICORE=true;
+ state.MULTICORE=true;
else if (option.equals("-multicoregc"))
- state.MULTICOREGC=true;
+ state.MULTICOREGC=true;
else if (option.equals("-mgc")) {
- state.MGC = true;
+ state.MGC = true;
} else if (option.equals("-objectlockdebug")) {
- state.OBJECTLOCKDEBUG = true;
+ state.OBJECTLOCKDEBUG = true;
} else if (option.equals("-ownership"))
- state.OWNERSHIP=true;
+ state.OWNERSHIP=true;
else if (option.equals("-ownallocdepth")) {
- state.OWNERSHIPALLOCDEPTH=Integer.parseInt(args[++i]);
+ state.OWNERSHIPALLOCDEPTH=Integer.parseInt(args[++i]);
} else if (option.equals("-ownwritedots")) {
- state.OWNERSHIPWRITEDOTS=true;
- if (args[++i].equals("all")) {
- state.OWNERSHIPWRITEALL=true;
- }
+ state.OWNERSHIPWRITEDOTS=true;
+ if (args[++i].equals("all")) {
+ state.OWNERSHIPWRITEALL=true;
+ }
} else if (option.equals("-ownaliasfile")) {
- state.OWNERSHIPALIASFILE=args[++i];
+ state.OWNERSHIPALIASFILE=args[++i];
} else if (option.equals("-ownaliasfiletab")) {
- state.OWNERSHIPALIASFILE=args[++i];
- state.OWNERSHIPALIASTAB=true;
+ state.OWNERSHIPALIASFILE=args[++i];
+ state.OWNERSHIPALIASTAB=true;
} else if (option.equals("-owndebugcallee")) {
- state.OWNERSHIPDEBUGCALLEE=args[++i];
+ state.OWNERSHIPDEBUGCALLEE=args[++i];
} else if (option.equals("-owndebugcaller")) {
- state.OWNERSHIPDEBUGCALLER=args[++i];
+ state.OWNERSHIPDEBUGCALLER=args[++i];
} else if (option.equals("-owndebugcallcount")) {
- state.OWNERSHIPDEBUGCALLCOUNT=Integer.parseInt(args[++i]);
+ state.OWNERSHIPDEBUGCALLCOUNT=Integer.parseInt(args[++i]);
} else if (option.equals("-pointer")) {
- state.POINTER=true;
+ state.POINTER=true;
} else if (option.equals("-disjoint"))
- state.DISJOINT=true;
+ state.DISJOINT=true;
else if (option.equals("-disjoint-k")) {
- state.DISJOINTALLOCDEPTH=Integer.parseInt(args[++i]);
+ state.DISJOINTALLOCDEPTH=Integer.parseInt(args[++i]);
} else if (option.equals("-disjoint-write-dots")) {
- state.DISJOINTWRITEDOTS = true;
- String arg = args[++i];
- if( arg.equals("all") ) {
- state.DISJOINTWRITEALL = true;
- } else if( arg.equals("final") ) {
- state.DISJOINTWRITEALL = false;
- } else {
- throw new Error("disjoint-write-dots requires argument <all/final>");
- }
+ state.DISJOINTWRITEDOTS = true;
+ String arg = args[++i];
+ if( arg.equals("all") ) {
+ state.DISJOINTWRITEALL = true;
+ } else if( arg.equals("final") ) {
+ state.DISJOINTWRITEALL = false;
+ } else {
+ throw new Error("disjoint-write-dots requires argument <all/final>");
+ }
} else if (option.equals("-disjoint-write-initial-contexts")) {
- state.DISJOINTWRITEINITCONTEXTS = true;
+ state.DISJOINTWRITEINITCONTEXTS = true;
} else if (option.equals("-disjoint-write-ihms")) {
- state.DISJOINTWRITEIHMS = true;
+ state.DISJOINTWRITEIHMS = true;
} else if (option.equals("-disjoint-alias-file")) {
- state.DISJOINTALIASFILE = args[++i];
- String arg = args[++i];
- if( arg.equals("normal") ) {
- state.DISJOINTALIASTAB = false;
- } else if( arg.equals("tabbed") ) {
- state.DISJOINTALIASTAB = true;
- } else {
- throw new Error("disjoint-alias-file requires arguments: <filename> <normal/tabbed>");
- }
+ state.DISJOINTALIASFILE = args[++i];
+ String arg = args[++i];
+ if( arg.equals("normal") ) {
+ state.DISJOINTALIASTAB = false;
+ } else if( arg.equals("tabbed") ) {
+ state.DISJOINTALIASTAB = true;
+ } else {
+ throw new Error("disjoint-alias-file requires arguments: <filename> <normal/tabbed>");
+ }
} else if (option.equals("-disjoint-debug-callsite")) {
- state.DISJOINTDEBUGCALLEE=args[++i];
- state.DISJOINTDEBUGCALLER=args[++i];
- state.DISJOINTDEBUGCALLVISITTOSTART=Integer.parseInt(args[++i]);
- state.DISJOINTDEBUGCALLNUMVISITS=Integer.parseInt(args[++i]);
- String arg = args[++i];
- if( arg.equals("true") ) {
- state.DISJOINTDEBUGCALLSTOPAFTER = true;
- } else if( arg.equals("false") ) {
- state.DISJOINTDEBUGCALLSTOPAFTER = false;
- } else {
- throw new Error("disjoint-debug-callsite requires arguments:\n"+
- " <callee symbol> <caller symbol> <# visit to start> <# visits to capture> <T/F stop after>");
- }
+ state.DISJOINTDEBUGCALLEE=args[++i];
+ state.DISJOINTDEBUGCALLER=args[++i];
+ state.DISJOINTDEBUGCALLVISITTOSTART=Integer.parseInt(args[++i]);
+ state.DISJOINTDEBUGCALLNUMVISITS=Integer.parseInt(args[++i]);
+ String arg = args[++i];
+ if( arg.equals("true") ) {
+ state.DISJOINTDEBUGCALLSTOPAFTER = true;
+ } else if( arg.equals("false") ) {
+ state.DISJOINTDEBUGCALLSTOPAFTER = false;
+ } else {
+ throw new Error("disjoint-debug-callsite requires arguments:\n"+
+ " <callee symbol> <caller symbol> <# visit to start> <# visits to capture> <T/F stop after>");
+ }
} else if (option.equals("-disjoint-debug-snap-method")) {
- state.DISJOINTSNAPSYMBOL=args[++i];
- state.DISJOINTSNAPVISITTOSTART=Integer.parseInt(args[++i]);
- state.DISJOINTSNAPNUMVISITS=Integer.parseInt(args[++i]);
- String arg = args[++i];
- if( arg.equals("true") ) {
- state.DISJOINTSNAPSTOPAFTER = true;
- } else if( arg.equals("false") ) {
- state.DISJOINTSNAPSTOPAFTER = false;
- } else {
- throw new Error("disjoint-debug-snap-method requires arguments:\n"+
- " <method symbol> <# visit to start> <# visits to snap> <T/F stop after>");
- }
+ state.DISJOINTSNAPSYMBOL=args[++i];
+ state.DISJOINTSNAPVISITTOSTART=Integer.parseInt(args[++i]);
+ state.DISJOINTSNAPNUMVISITS=Integer.parseInt(args[++i]);
+ String arg = args[++i];
+ if( arg.equals("true") ) {
+ state.DISJOINTSNAPSTOPAFTER = true;
+ } else if( arg.equals("false") ) {
+ state.DISJOINTSNAPSTOPAFTER = false;
+ } else {
+ throw new Error("disjoint-debug-snap-method requires arguments:\n"+
+ " <method symbol> <# visit to start> <# visits to snap> <T/F stop after>");
+ }
} else if( option.equals("-disjoint-release-mode") ) {
- state.DISJOINTRELEASEMODE = true;
+ state.DISJOINTRELEASEMODE = true;
} else if( option.equals("-disjoint-dvisit-stack") ) {
- state.DISJOINTDVISITSTACK = true;
- state.DISJOINTDVISITPQUE = false;
- state.DISJOINTDVISITSTACKEESONTOP = false;
+ state.DISJOINTDVISITSTACK = true;
+ state.DISJOINTDVISITPQUE = false;
+ state.DISJOINTDVISITSTACKEESONTOP = false;
} else if( option.equals("-disjoint-dvisit-pqueue") ) {
- state.DISJOINTDVISITPQUE = true;
- state.DISJOINTDVISITSTACK = false;
- state.DISJOINTDVISITSTACKEESONTOP = false;
+ state.DISJOINTDVISITPQUE = true;
+ state.DISJOINTDVISITSTACK = false;
+ state.DISJOINTDVISITSTACKEESONTOP = false;
} else if( option.equals("-disjoint-dvisit-stack-callees-on-top") ) {
- state.DISJOINTDVISITSTACKEESONTOP = true;
- state.DISJOINTDVISITPQUE = false;
- state.DISJOINTDVISITSTACK = false;
+ state.DISJOINTDVISITSTACKEESONTOP = true;
+ state.DISJOINTDVISITPQUE = false;
+ state.DISJOINTDVISITSTACK = false;
} else if( option.equals("-disjoint-desire-determinism") ) {
- state.DISJOINTDETERMINISM = true;
+ state.DISJOINTDETERMINISM = true;
- // when asking analysis for a deterministic result, force
- // a stack-based visiting scheme, because the priority queue
- // requires a non-deterministic topological sort
- state.DISJOINTDVISITSTACKEESONTOP = true;
- state.DISJOINTDVISITPQUE = false;
- state.DISJOINTDVISITSTACK = false;
+ // when asking analysis for a deterministic result, force
+ // a stack-based visiting scheme, because the priority queue
+ // requires a non-deterministic topological sort
+ state.DISJOINTDVISITSTACKEESONTOP = true;
+ state.DISJOINTDVISITPQUE = false;
+ state.DISJOINTDVISITSTACK = false;
} else if( option.equals("-disjoint-debug-scheduling") ) {
- state.DISJOINTDEBUGSCHEDULING = true;
+ state.DISJOINTDEBUGSCHEDULING = true;
} else if (option.equals("-optional"))
- state.OPTIONAL=true;
+ state.OPTIONAL=true;
else if (option.equals("-optimize"))
- state.OPTIMIZE=true;
+ state.OPTIMIZE=true;
else if (option.equals("-noloop"))
- state.NOLOOP=true;
+ state.NOLOOP=true;
else if (option.equals("-dcopts"))
- state.DCOPTS=true;
+ state.DCOPTS=true;
else if (option.equals("-arraypad"))
- state.ARRAYPAD=true;
+ state.ARRAYPAD=true;
else if (option.equals("-delaycomp"))
- state.DELAYCOMP=true;
+ state.DELAYCOMP=true;
else if (option.equals("-raw"))
- state.RAW=true;
+ state.RAW=true;
else if (option.equals("-scheduling"))
- state.SCHEDULING=true;
+ state.SCHEDULING=true;
else if (option.equals("-distributioninfo"))
- isDistributeInfo=true;
+ isDistributeInfo=true;
else if (option.equals("-disall"))
- isDisAll=true;
+ isDisAll=true;
else if (option.equals("-disstart"))
- startnum = Integer.parseInt(args[++i]);
+ startnum = Integer.parseInt(args[++i]);
else if (option.equals("-useprofile")) {
- state.USEPROFILE=true;
- state.profilename = args[++i];
+ state.USEPROFILE=true;
+ state.profilename = args[++i];
} else if (option.equals("-thread"))
- state.THREAD=true;
+ state.THREAD=true;
else if (option.equals("-dsm"))
- state.DSM=true;
+ state.DSM=true;
else if (option.equals("-recoverystats"))
- state.DSMRECOVERYSTATS=true;
+ state.DSMRECOVERYSTATS=true;
else if (option.equals("-dsmtask"))
- state.DSMTASK=true;
+ state.DSMTASK=true;
else if (option.equals("-singleTM"))
- state.SINGLETM=true;
+ state.SINGLETM=true;
else if (option.equals("-readset"))
- state.READSET=true;
+ state.READSET=true;
else if (option.equals("-webinterface"))
- state.WEBINTERFACE=true;
+ state.WEBINTERFACE=true;
else if (option.equals("-instructionfailures"))
- state.INSTRUCTIONFAILURE=true;
+ state.INSTRUCTIONFAILURE=true;
else if (option.equals("-abcclose"))
- state.ARRAYBOUNDARYCHECK=false;
+ state.ARRAYBOUNDARYCHECK=false;
else if (option.equals("-methodeffects")) {
- state.METHODEFFECTS=true;
+ state.METHODEFFECTS=true;
} else if (option.equals("-coreprof")) {
- state.COREPROF=true;
+ state.COREPROF=true;
} else if (option.equals("-ooojava")) {
- state.OOOJAVA = true;
- state.DISJOINT = true;
- state.OOO_NUMCORES = Integer.parseInt(args[++i]);
- state.OOO_MAXSESEAGE = Integer.parseInt(args[++i]);
+ state.OOOJAVA = true;
+ state.DISJOINT = true;
+ state.OOO_NUMCORES = Integer.parseInt(args[++i]);
+ state.OOO_MAXSESEAGE = Integer.parseInt(args[++i]);
} else if (option.equals("-ooodebug") ) {
- state.OOODEBUG = true;
+ state.OOODEBUG = true;
} else if (option.equals("-rcr")) {
- state.RCR = true;
- state.KEEP_RG_FOR_ALL_PROGRAM_POINTS=true;
+ state.RCR = true;
+ state.KEEP_RG_FOR_ALL_PROGRAM_POINTS=true;
} else if (option.equals("-rcr_debug")) {
- state.RCR_DEBUG = true;
- state.KEEP_RG_FOR_ALL_PROGRAM_POINTS=true;
+ state.RCR_DEBUG = true;
+ state.KEEP_RG_FOR_ALL_PROGRAM_POINTS=true;
} else if (option.equals("-rcr_debug_verbose")) {
- state.RCR_DEBUG_VERBOSE = true;
- state.KEEP_RG_FOR_ALL_PROGRAM_POINTS=true;
+ state.RCR_DEBUG_VERBOSE = true;
+ state.KEEP_RG_FOR_ALL_PROGRAM_POINTS=true;
} else if (option.equals("-nostalltr")) {
- state.NOSTALLTR = true;
+ state.NOSTALLTR = true;
} else if (option.equals("-ssjava")) {
- state.SSJAVA = true;
+ state.SSJAVA = true;
} else if (option.equals("-printlinenum")) {
- state.LINENUM=true;
+ state.LINENUM=true;
} else if (option.equals("-help")) {
- System.out.println("-classlibrary classlibrarydirectory -- directory where classlibrary is located");
- System.out.println("-selfloop task -- this task doesn't self loop its parameters forever");
- System.out.println("-dir outputdirectory -- output code in outputdirectory");
- System.out.println("-struct structfile -- output structure declarations for repair tool");
- System.out.println("-mainclass -- main function to call");
- System.out.println("-dsm -- distributed shared memory support");
- System.out.println("-singleTM -- single machine committing transactions");
- System.out.println("-abortreaders -- abort readers");
- System.out.println("-precise -- use precise garbage collection");
- System.out.println("-conscheck -- turn on consistency checking");
- System.out.println("-task -- compiler for tasks");
- System.out.println("-fastcheck -- fastcheckpointing for Bristlecone");
- System.out.println("-thread -- threads");
- System.out.println("-trueprob <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("-ownallocdepth <d> -- set allocation depth for ownership analysis");
- System.out.println("-ownwritedots <all/final> -- write ownership graphs; can be all results or just final results");
- System.out.println("-ownaliasfile <filename> -- write a text file showing all detected aliases in program tasks");
- System.out.println("-optimize -- enable optimizations");
- System.out.println("-noloop -- disable loop optimizations");
- System.out.println("-optional -- enable optional arguments");
- System.out.println("-abcclose close the array boundary check");
- System.out.println("-scheduling do task scheduling");
- System.out.println("-mlp <num cores> <max sese age> build mlp code");
- System.out.println("-mlpdebug if mlp, report progress and interim results");
- System.out.println("-multicore generate multi-core version binary");
- System.out.println("-numcore set the number of cores (should be used together with -multicore), defaultly set as 1");
- System.out.println("-interrupt generate raw version binary with interruption (should be used togethere with -raw)");
- System.out.println("-rawconfig config raw simulator as 4xn (should be used together with -raw)");
- System.out.println("-rawpath print out execute path information for raw version (should be used together with -raw)");
- System.out.println("-useprofile use profiling data for scheduling (should be used together with -raw)");
- System.out.println("-threadsimulate generate multi-thread simulate version binary");
- System.out.println("-rawuseio use standard io to output profiling data (should be used together with -raw and -profile), it only works with single core version");
- System.out.println("-printscheduling -- print out scheduling graphs");
- System.out.println("-printschedulesim -- print out scheduling simulation result graphs");
- System.out.println("-webinterface -- enable web interface");
- System.out.println("-linenum print out line numbers in generated C codes");
- System.out.println("-help -- print out help");
- System.exit(0);
+ System.out.println("-classlibrary classlibrarydirectory -- directory where classlibrary is located");
+ System.out.println("-selfloop task -- this task doesn't self loop its parameters forever");
+ System.out.println("-dir outputdirectory -- output code in outputdirectory");
+ System.out.println("-struct structfile -- output structure declarations for repair tool");
+ System.out.println("-mainclass -- main function to call");
+ System.out.println("-dsm -- distributed shared memory support");
+ System.out.println("-singleTM -- single machine committing transactions");
+ System.out.println("-abortreaders -- abort readers");
+ System.out.println("-precise -- use precise garbage collection");
+ System.out.println("-conscheck -- turn on consistency checking");
+ System.out.println("-task -- compiler for tasks");
+ System.out.println("-fastcheck -- fastcheckpointing for Bristlecone");
+ System.out.println("-thread -- threads");
+ System.out.println("-trueprob <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("-ownallocdepth <d> -- set allocation depth for ownership analysis");
+ System.out.println("-ownwritedots <all/final> -- write ownership graphs; can be all results or just final results");
+ System.out.println("-ownaliasfile <filename> -- write a text file showing all detected aliases in program tasks");
+ System.out.println("-optimize -- enable optimizations");
+ System.out.println("-noloop -- disable loop optimizations");
+ System.out.println("-optional -- enable optional arguments");
+ System.out.println("-abcclose close the array boundary check");
+ System.out.println("-scheduling do task scheduling");
+ System.out.println("-mlp <num cores> <max sese age> build mlp code");
+ System.out.println("-mlpdebug if mlp, report progress and interim results");
+ System.out.println("-multicore generate multi-core version binary");
+ System.out.println("-numcore set the number of cores (should be used together with -multicore), defaultly set as 1");
+ System.out.println("-interrupt generate raw version binary with interruption (should be used togethere with -raw)");
+ System.out.println("-rawconfig config raw simulator as 4xn (should be used together with -raw)");
+ System.out.println("-rawpath print out execute path information for raw version (should be used together with -raw)");
+ System.out.println("-useprofile use profiling data for scheduling (should be used together with -raw)");
+ System.out.println("-threadsimulate generate multi-thread simulate version binary");
+ System.out.println("-rawuseio use standard io to output profiling data (should be used together with -raw and -profile), it only works with single core version");
+ System.out.println("-printscheduling -- print out scheduling graphs");
+ System.out.println("-printschedulesim -- print out scheduling simulation result graphs");
+ System.out.println("-webinterface -- enable web interface");
+ System.out.println("-linenum print out line numbers in generated C codes");
+ System.out.println("-help -- print out help");
+ System.exit(0);
} else {
- sourcefiles.add(args[i]);
+ sourcefiles.add(args[i]);
}
}
SemanticCheck sc=new SemanticCheck(state,tu);
for(int i=0; i<sourcefiles.size(); i++)
- loadClass(state, bir, sourcefiles.get(i));
+ loadClass(state, bir, sourcefiles.get(i));
//Stuff the runtime wants to see
if (state.TASK) {
- sc.getClass(null, "TagDescriptor");
+ sc.getClass(null, "TagDescriptor");
}
sc.semanticCheck();
if (state.INLINEATOMIC) {
Iterator classit=state.getClassSymbolTable().getDescriptorsIterator();
while(classit.hasNext()) {
- ClassDescriptor cn=(ClassDescriptor)classit.next();
- Iterator methodit=cn.getMethods();
- while(methodit.hasNext()) {
- // do inlining
- MethodDescriptor md=(MethodDescriptor)methodit.next();
- FlatMethod fm=state.getMethodFlat(md);
- Inliner.inlineAtomic(state, tu, fm, state.inlineatomicdepth);
- }
+ ClassDescriptor cn=(ClassDescriptor)classit.next();
+ Iterator methodit=cn.getMethods();
+ while(methodit.hasNext()) {
+ // do inlining
+ MethodDescriptor md=(MethodDescriptor)methodit.next();
+ FlatMethod fm=state.getMethodFlat(md);
+ Inliner.inlineAtomic(state, tu, fm, state.inlineatomicdepth);
+ }
}
}
localCSE lcse=new localCSE(gft, tu);
LoopOptimize lo=null;
if (!state.NOLOOP)
- lo=new LoopOptimize(gft, tu);
+ lo=new LoopOptimize(gft, tu);
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 (fm==null)
- continue;
- cp.optimize(fm);
- dc.optimize(fm);
- if (!state.NOLOOP)
- lo.optimize(fm);
- cp.optimize(fm);
- dc.optimize(fm);
- lcse.doAnalysis(fm);
- cse.doAnalysis(fm);
- cp.optimize(fm);
- dc.optimize(fm);
- cp.optimize(fm);
- dc.optimize(fm);
- }
+ 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 (fm==null)
+ continue;
+ cp.optimize(fm);
+ dc.optimize(fm);
+ if (!state.NOLOOP)
+ lo.optimize(fm);
+ cp.optimize(fm);
+ dc.optimize(fm);
+ lcse.doAnalysis(fm);
+ cse.doAnalysis(fm);
+ cp.optimize(fm);
+ dc.optimize(fm);
+ cp.optimize(fm);
+ dc.optimize(fm);
+ }
}
State.logEvent("Done Optimizing");
}
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());
+ 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();
+ 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) {
- // Use ownership analysis to get alias information
- Liveness liveness = new Liveness();
- ArrayReferencees ar = new ArrayReferencees(state, tu, callgraph);
- OwnershipAnalysis oa = null; /*new OwnershipAnalysis(state,
- tu,
- callGraph,
- liveness,
- ar,
- state.OWNERSHIPALLOCDEPTH,
- state.OWNERSHIPWRITEDOTS,
- state.OWNERSHIPWRITEALL,
- state.OWNERSHIPALIASFILE);*/
-
- // synthesis a layout according to target multicore processor
- MCImplSynthesis mcImplSynthesis = new MCImplSynthesis(state,
- ta,
- oa);
- if(isDistributeInfo) {
- mcImplSynthesis.distribution(isDisAll, startnum);
- } else {
- double timeStartAnalysis = (double) System.nanoTime();
- mcImplSynthesis.setScheduleThreshold(20);
- mcImplSynthesis.setProbThreshold(0);
- mcImplSynthesis.setGenerateThreshold(30);
- Vector<Schedule> scheduling = mcImplSynthesis.synthesis();
-
- double timeEndAnalysis = (double) System.nanoTime();
- if(state.BAMBOOCOMPILETIME) {
- double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow(10.0, 9.0) );
- System.err.println("The analysis took" + dt + "sec.");
- System.exit(0);
- }
-
- // generate multicore codes
- if(state.MULTICORE) {
- BuildCodeMultiCore bcm=new BuildCodeMultiCore(state,
- bf.getMap(),
- tu,
- sa,
- scheduling,
- mcImplSynthesis.getCoreNum(),
- state.CORENUM4GC, callgraph);
- bcm.setOwnershipAnalysis(oa);
- bcm.buildCode();
- }
- scheduling.clear();
- scheduling = null;
- }
+ // Use ownership analysis to get alias information
+ Liveness liveness = new Liveness();
+ ArrayReferencees ar = new ArrayReferencees(state, tu, callgraph);
+ OwnershipAnalysis oa = null; /*new OwnershipAnalysis(state,
+ tu,
+ callGraph,
+ liveness,
+ ar,
+ state.OWNERSHIPALLOCDEPTH,
+ state.OWNERSHIPWRITEDOTS,
+ state.OWNERSHIPWRITEALL,
+ state.OWNERSHIPALIASFILE);*/
+
+ // synthesis a layout according to target multicore processor
+ MCImplSynthesis mcImplSynthesis = new MCImplSynthesis(state,
+ ta,
+ oa);
+ if(isDistributeInfo) {
+ mcImplSynthesis.distribution(isDisAll, startnum);
+ } else {
+ double timeStartAnalysis = (double) System.nanoTime();
+ mcImplSynthesis.setScheduleThreshold(20);
+ mcImplSynthesis.setProbThreshold(0);
+ mcImplSynthesis.setGenerateThreshold(30);
+ Vector<Schedule> scheduling = mcImplSynthesis.synthesis();
+
+ double timeEndAnalysis = (double) System.nanoTime();
+ if(state.BAMBOOCOMPILETIME) {
+ double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow(10.0, 9.0) );
+ System.err.println("The analysis took" + dt + "sec.");
+ System.exit(0);
+ }
+
+ // generate multicore codes
+ if(state.MULTICORE) {
+ BuildCodeMultiCore bcm=new BuildCodeMultiCore(state,
+ bf.getMap(),
+ tu,
+ sa,
+ scheduling,
+ mcImplSynthesis.getCoreNum(),
+ state.CORENUM4GC, callgraph);
+ bcm.setOwnershipAnalysis(oa);
+ bcm.buildCode();
+ }
+ scheduling.clear();
+ scheduling = null;
+ }
}
}
if (state.MGC) {
// generate multicore codes
if(state.MULTICORE) {
- BuildCodeMGC bcmgc=new BuildCodeMGC(state,
- bf.getMap(),
- tu,
- sa,
- state.CORENUM,
- state.CORENUM,
- state.CORENUM4GC, callgraph);
- bcmgc.buildCode();
+ BuildCodeMGC bcmgc=new BuildCodeMGC(state,
+ bf.getMap(),
+ tu,
+ sa,
+ state.CORENUM,
+ state.CORENUM,
+ state.CORENUM4GC, callgraph);
+ bcmgc.buildCode();
}
}
BuildCode bc;
if (state.DSM||state.SINGLETM) {
- if (state.PREFETCH) {
- //speed up prefetch generation using locality analysis results
- LocalityAnalysis la=new LocalityAnalysis(state, callgraph, tu);
- pa=new PrefetchAnalysis(state, callgraph, tu, la);
- }
- LocalityAnalysis la=new LocalityAnalysis(state, callgraph, tu);
- GenerateConversions gc=new GenerateConversions(la, state);
- bc=new BuildCodeTran(state, bf.getMap(), tu, la, pa, callgraph);
+ if (state.PREFETCH) {
+ //speed up prefetch generation using locality analysis results
+ LocalityAnalysis la=new LocalityAnalysis(state, callgraph, tu);
+ pa=new PrefetchAnalysis(state, callgraph, tu, la);
+ }
+ LocalityAnalysis la=new LocalityAnalysis(state, callgraph, tu);
+ GenerateConversions gc=new GenerateConversions(la, state);
+ bc=new BuildCodeTran(state, bf.getMap(), tu, la, pa, callgraph);
} else {
- if( state.OOOJAVA ) {
- bc=new BuildOoOJavaCode(state, bf.getMap(), tu, sa, oooa, callgraph);
- } else {
- bc=new BuildCode(state, bf.getMap(), tu, sa, callgraph, jb);
- }
+ if( state.OOOJAVA ) {
+ bc=new BuildOoOJavaCode(state, bf.getMap(), tu, sa, oooa, callgraph);
+ } else {
+ bc=new BuildCode(state, bf.getMap(), tu, sa, callgraph, jb);
+ }
}
bc.buildCode();
g = new Parse.Parser(l);
ParseNode p=null;
try {
- p=(ParseNode) g./*debug_*/ parse().value;
+ p=(ParseNode) g./*debug_*/ parse().value;
} catch (Exception e) {
- System.err.println("Error parsing file:"+sourcefile);
- e.printStackTrace();
- System.exit(-1);
+ System.err.println("Error parsing file:"+sourcefile);
+ e.printStackTrace();
+ System.exit(-1);
}
state.addParseNode(p);
if (l.numErrors()!=0) {
- System.out.println("Error parsing "+sourcefile);
- System.exit(l.numErrors());
+ System.out.println("Error parsing "+sourcefile);
+ System.exit(l.numErrors());
}
state.lines+=l.line_num;
return p;
int count=rl->numreaders;
int j;
for(j=0; count; j++) {
- int *t_abort=rl->array[j];
- if (t_abort!=NULL) {
- *t_abort=1; //It's okay to set our own abort flag...it is
- //too late to abort us
- count--;
- }
+ int *t_abort=rl->array[j];
+ if (t_abort!=NULL) {
+ *t_abort=1; //It's okay to set our own abort flag...it is
+ //too late to abort us
+ count--;
+ }
}
tmp=rl;
rl=rl->next;
oidverread+=(sizeof(unsigned int)+sizeof(unsigned short));
while(rl!=NULL) {
for(j=0; j<READERSIZE; j++) {
- if (rl->array[j]==&t_abort) {
- rl->array[j]=NULL;
- if ((--rl->numreaders)==0) {
- if (first==rl) {
- chashRemove2(aborttable, oid);
- if (rl->next!=NULL)
- chashInsert(aborttable, oid, rl->next);
- rl->next=freelist;
- freelist=rl;
- } else {
- first->next=rl->next;
- rl->next=freelist;
- freelist=rl;
- }
- }
- goto nextitem;
- }
+ if (rl->array[j]==&t_abort) {
+ rl->array[j]=NULL;
+ if ((--rl->numreaders)==0) {
+ if (first==rl) {
+ chashRemove2(aborttable, oid);
+ if (rl->next!=NULL)
+ chashInsert(aborttable, oid, rl->next);
+ rl->next=freelist;
+ freelist=rl;
+ } else {
+ first->next=rl->next;
+ rl->next=freelist;
+ freelist=rl;
+ }
+ }
+ goto nextitem;
+ }
}
first=rl;
rl=rl->next;
do {
unsigned int oid=curr->key;
if (oid==0)
- break;
+ break;
struct readerlist * rl=chashSearch(aborttable, oid);
struct readerlist *first=rl;
while(rl!=NULL) {
- for(j=0; j<READERSIZE; j++) {
- if (rl->array[j]==&t_abort) {
- rl->array[j]=NULL;
- if ((--rl->numreaders)==0) {
- if (first==rl) {
- chashRemove2(aborttable, oid);
- if (rl->next!=NULL)
- chashInsert(aborttable, oid, rl->next);
- rl->next=freelist;
- freelist=rl;
- } else {
- first->next=rl->next;
- rl->next=freelist;
- freelist=rl;
- }
- }
- goto nextitem;
- }
- }
- first=rl;
- rl=rl->next;
+ for(j=0; j<READERSIZE; j++) {
+ if (rl->array[j]==&t_abort) {
+ rl->array[j]=NULL;
+ if ((--rl->numreaders)==0) {
+ if (first==rl) {
+ chashRemove2(aborttable, oid);
+ if (rl->next!=NULL)
+ chashInsert(aborttable, oid, rl->next);
+ rl->next=freelist;
+ freelist=rl;
+ } else {
+ first->next=rl->next;
+ rl->next=freelist;
+ freelist=rl;
+ }
+ }
+ goto nextitem;
+ }
+ }
+ first=rl;
+ rl=rl->next;
}
nextitem:
curr=curr->next;
struct readerlist *first=rl;
while(rl!=NULL) {
for(j=0; j<READERSIZE; j++) {
- if (rl->array[j]==&t_abort) {
- rl->array[j]=NULL;
- if ((--rl->numreaders)==0) {
- if (first==rl) {
- chashRemove2(aborttable, oid);
- if (rl->next!=NULL)
- chashInsert(aborttable, oid, rl->next);
- rl->next=freelist;
- freelist=rl;
- } else {
- first->next=rl->next;
- rl->next=freelist;
- freelist=rl;
- }
- }
- goto nextitem;
- }
+ if (rl->array[j]==&t_abort) {
+ rl->array[j]=NULL;
+ if ((--rl->numreaders)==0) {
+ if (first==rl) {
+ chashRemove2(aborttable, oid);
+ if (rl->next!=NULL)
+ chashInsert(aborttable, oid, rl->next);
+ rl->next=freelist;
+ freelist=rl;
+ } else {
+ first->next=rl->next;
+ rl->next=freelist;
+ freelist=rl;
+ }
+ }
+ goto nextitem;
+ }
}
first=rl;
rl=rl->next;
if(getOperationMode(siteid) != 0) {
evalPrefetch[siteid].uselesscount--;
if(evalPrefetch[siteid].uselesscount <= 0) {
- LOGEVENT('O');
- evalPrefetch[siteid].operMode = 0;
+ LOGEVENT('O');
+ evalPrefetch[siteid].operMode = 0;
}
}
}
chashlistnode_t *curr = &ptr[i]; //for each entry in the cache lookupTable
while(curr != NULL) {
if(curr->key == 0)
- break;
+ break;
objheader_t *header1, *header2;
/* Not found in local machine's object store and found in prefetch cache */
if((header1 = mhashSearch(curr->key)) == NULL && ((header2 = prehashSearch(curr->key)) != NULL)) {
- /* Remove from prefetch cache */
- prehashRemove(curr->key);
+ /* Remove from prefetch cache */
+ prehashRemove(curr->key);
}
curr = curr->next;
}
switch (status) {
case INVALIDATE_OBJS:
if((retval = invalidateFromPrefetchCache(readBuffer))!= 0) {
- printf("Error: In invalidateFromPrefetchCache() at %s, %d\n", __FILE__, __LINE__);
- break;
+ printf("Error: In invalidateFromPrefetchCache() at %s, %d\n", __FILE__, __LINE__);
+ break;
}
break;
for(; j < pilecount; j++) {
for(; i < tdata[j].f.nummod; i++) {
- *((unsigned int *) (writeBuffer+localoffset)) = tdata[j].oidmod[i]; //copy objects
- localoffset += sizeof(unsigned int);
- if ((++sentmsgs)==numtosend) {
- i++;
- goto send;
- }
+ *((unsigned int *) (writeBuffer+localoffset)) = tdata[j].oidmod[i]; //copy objects
+ localoffset += sizeof(unsigned int);
+ if ((++sentmsgs)==numtosend) {
+ i++;
+ goto send;
+ }
}
i=0;
}
objheader_t *header;
/* Lookup Objects in prefetch cache and remove them */
if(((header = prehashSearch(oid)) != NULL)) {
- //Keep invalid objects
- STATUS(header)=DIRTY;
- //prehashRemove(oid);
+ //Keep invalid objects
+ STATUS(header)=DIRTY;
+ //prehashRemove(oid);
}
offset += sizeof(unsigned int);
}
if (curr->key == key) {
atomic_dec(&(mlookup.numelements));
if ((curr == &ptr[index]) && (curr->next == NULL)) {
- curr->key = 0;
- curr->val = NULL;
+ curr->key = 0;
+ curr->val = NULL;
} else if ((curr == &ptr[index]) && (curr->next != NULL)) {
- curr->key = curr->next->key;
- curr->val = curr->next->val;
- node = curr->next;
- curr->next = curr->next->next;
- free(node);
+ curr->key = curr->next->key;
+ curr->val = curr->next->val;
+ node = curr->next;
+ curr->next = curr->next->next;
+ free(node);
} else {
- prev->next = curr->next;
- free(curr);
+ prev->next = curr->next;
+ free(curr);
}
write_unlock(lockptr);
return 0;
mhashlistnode_t *tmp,*next;
if ((key=curr->key) == 0) {
- break;
+ break;
}
next = curr->next;
index = (key >> 1) & mask;
tmp=&mlookup.table[index];
if(tmp->key ==0) {
- tmp->key=curr->key;
- tmp->val=curr->val;
- if (!isfirst)
- free(curr);
+ tmp->key=curr->key;
+ tmp->val=curr->val;
+ if (!isfirst)
+ free(curr);
} /*
- NOTE: Add this case if you change this...
- This case currently never happens because of the way things rehash....
- else if (isfirst) {
- mhashlistnode_t *newnode = calloc(1, sizeof(mhashlistnode_t));
- newnode->key = curr->key;
- newnode->val = curr->val;
- newnode->next = tmp->next;
- tmp->next=newnode;
- } */
+ NOTE: Add this case if you change this...
+ This case currently never happens because of the way things rehash....
+ else if (isfirst) {
+ mhashlistnode_t *newnode = calloc(1, sizeof(mhashlistnode_t));
+ newnode->key = curr->key;
+ newnode->val = curr->val;
+ newnode->next = tmp->next;
+ tmp->next=newnode;
+ } */
else {
- curr->next=tmp->next;
- tmp->next=curr;
+ curr->next=tmp->next;
+ tmp->next=curr;
}
isfirst = 0;
curr = next;
tmp = ptr;
while(tmp != NULL) {
if(tmp->key == key) {
- isFound=1;
- tmp->val = val; //Replace value for an exsisting key
- write_unlock(lockptr);
- return;
+ isFound=1;
+ tmp->val = val; //Replace value for an exsisting key
+ write_unlock(lockptr);
+ return;
}
tmp=tmp->next;
}
do {
unsigned int key;
if ((key=curr->key) == 0) { //Exit inner loop if there the first element for a given bin/index is NULL
- break; //key = val =0 for element if not present within the hash table
+ break; //key = val =0 for element if not present within the hash table
}
next = curr->next;
//index = (key & mask)>>1;
tmp=&pflookup.table[index];
// Insert into the new table
if(tmp->key==0) {
- tmp->key=curr->key;
- tmp->val=curr->val;
- if (!isfirst)
- free(curr);
+ tmp->key=curr->key;
+ tmp->val=curr->val;
+ if (!isfirst)
+ free(curr);
} /*
- NOTE: Add this case if you change this...
- This case currently never happens because of the way things rehash....
- else if (isfirst) {
- prehashlistnode_t * newnode = calloc(1, sizeof(prehashlistnode_t));
- newnode->key = curr->key;
- newnode->val = curr->val;
- newnode->next = tmp->next;
- tmp->next=newnode;
- } */
+ NOTE: Add this case if you change this...
+ This case currently never happens because of the way things rehash....
+ else if (isfirst) {
+ prehashlistnode_t * newnode = calloc(1, sizeof(prehashlistnode_t));
+ newnode->key = curr->key;
+ newnode->val = curr->val;
+ newnode->next = tmp->next;
+ tmp->next=newnode;
+ } */
else {
- curr->next=tmp->next;
- tmp->next=curr;
+ curr->next=tmp->next;
+ tmp->next=curr;
}
isfirst = 0;
int main() {
unsigned long long dir[DIRSIZE]; /* used for incomming dir name, and
- outgoing data */
+ outgoing data */
int sd, sd_current;
socklen_t addrlen;
struct sockaddr_in sin;
if (curr->key == key) { // Find a match in the hash table
table->numelements--; // Decrement the number of elements in the global hashtable
if ((curr == &ptr[index]) && (curr->next == NULL)) { // Delete the first item inside the hashtable with no linked list of chashlistnode_t
- curr->key = 0;
- value=curr->val;
- curr->val = NULL;
+ curr->key = 0;
+ value=curr->val;
+ curr->val = NULL;
} else if ((curr == &ptr[index]) && (curr->next != NULL)) { //Delete the first item with a linked list of chashlistnode_t connected
- curr->key = curr->next->key;
- value=curr->val;
- curr->val = curr->next->val;
- node = curr->next;
- curr->next = curr->next->next;
- free(node);
+ curr->key = curr->next->key;
+ value=curr->val;
+ curr->val = curr->next->val;
+ node = curr->next;
+ curr->next = curr->next->next;
+ free(node);
} else { // Regular delete from linked listed
- prev->next = curr->next;
- value=curr->val;
- free(curr);
+ prev->next = curr->next;
+ value=curr->val;
+ free(curr);
}
return value;
}
chashlistnode_t *tmp,*next;
if ((key=curr->key) == 0) { //Exit inner loop if there the first element is 0
- break; //key = val =0 for element if not present within the hash table
+ break; //key = val =0 for element if not present within the hash table
}
next = curr->next;
index = (key & mask) >>1;
tmp=&node[index];
// Insert into the new table
if(tmp->key == 0) {
- tmp->key = curr->key;
- tmp->val = curr->val;
- if (!isfirst) {
- free(curr);
- }
+ tmp->key = curr->key;
+ tmp->val = curr->val;
+ if (!isfirst) {
+ free(curr);
+ }
} /*
- NOTE: Add this case if you change this...
- This case currently never happens because of the way things rehash....
- else if (isfirst) {
- chashlistnode_t *newnode= calloc(1, sizeof(chashlistnode_t));
- newnode->key = curr->key;
- newnode->val = curr->val;
- newnode->next = tmp->next;
- tmp->next=newnode;
- } */
+ NOTE: Add this case if you change this...
+ This case currently never happens because of the way things rehash....
+ else if (isfirst) {
+ chashlistnode_t *newnode= calloc(1, sizeof(chashlistnode_t));
+ newnode->key = curr->key;
+ newnode->val = curr->val;
+ newnode->next = tmp->next;
+ tmp->next=newnode;
+ } */
else {
- curr->next=tmp->next;
- tmp->next=curr;
+ curr->next=tmp->next;
+ tmp->next=curr;
}
isfirst = 0;
chashlistnode_t *tmp,*next;
if ((key=curr->key) == 0) { //Exit inner loop if there the first element is 0
- break; //key = val =0 for element if not present within the hash table
+ break; //key = val =0 for element if not present within the hash table
}
index = (key & mask) >>1;
tmp=&node[index];
next = curr->next;
// Insert into the new table
if(tmp->key == 0) {
- tmp->key = key;
- tmp->val = curr->val;
+ tmp->key = key;
+ tmp->val = curr->val;
} /*
- NOTE: Add this case if you change this...
- This case currently never happens because of the way things rehash....
- else if (isfirst) {
- chashlistnode_t *newnode= calloc(1, sizeof(chashlistnode_t));
- newnode->key = curr->key;
- newnode->val = curr->val;
- newnode->next = tmp->next;
- tmp->next=newnode;
- } */
+ NOTE: Add this case if you change this...
+ This case currently never happens because of the way things rehash....
+ else if (isfirst) {
+ chashlistnode_t *newnode= calloc(1, sizeof(chashlistnode_t));
+ newnode->key = curr->key;
+ newnode->val = curr->val;
+ newnode->next = tmp->next;
+ tmp->next=newnode;
+ } */
else {
- curr->next=tmp->next;
- tmp->next=curr;
+ curr->next=tmp->next;
+ tmp->next=curr;
}
isfirst = 0;
if (key != 0) {
newnode= &table->table[(key&mask)>>1];
if (newnode->key==0) {
- newnode->key=key;
- newnode->ptr=curr->ptr;
- continue;
+ newnode->key=key;
+ newnode->ptr=curr->ptr;
+ continue;
}
for(bin=1; 1; bin++) {
- newnode = &table->table[((key+bin*331) & mask)>>1];
- if (newnode->key==0) {
- newnode->key=key;
- newnode->ptr=curr->ptr;
- break;
- }
+ newnode = &table->table[((key+bin*331) & mask)>>1];
+ if (newnode->key==0) {
+ newnode->key=key;
+ newnode->ptr=curr->ptr;
+ break;
+ }
}
}
}
for (i = 0; i < INSERT_RETRIES; i++) {
if (sendto(pollsock.fd, outBuffer, 9, 0, (struct sockaddr *)&toAddr,
socklen) < 0) {
- perror("dhtInsert():sendto()");
- break;
+ perror("dhtInsert():sendto()");
+ break;
}
retval = poll(&pollsock, 1, INSERT_TIMEOUT_MS);
if (retval < 0) {
- perror("dhtInsert():poll()");
- break;
+ perror("dhtInsert():poll()");
+ break;
}
if (retval > 0) {
- bytesRcvd = recvfrom(pollsock.fd, inBuffer, 2, 0,
- (struct sockaddr *)&fromAddr, &socklen);
- if (fromAddr.sin_addr.s_addr == toAddr.sin_addr.s_addr
- && fromAddr.sin_port == toAddr.sin_port
- && bytesRcvd == 2 && inBuffer[0] == INSERT_RES) {
- status = inBuffer[1]; //status from remote host
- break;
- }
+ bytesRcvd = recvfrom(pollsock.fd, inBuffer, 2, 0,
+ (struct sockaddr *)&fromAddr, &socklen);
+ if (fromAddr.sin_addr.s_addr == toAddr.sin_addr.s_addr
+ && fromAddr.sin_port == toAddr.sin_port
+ && bytesRcvd == 2 && inBuffer[0] == INSERT_RES) {
+ status = inBuffer[1]; //status from remote host
+ break;
+ }
}
}
if (status != OPERATION_OK) {
for (i = 0; i < REMOVE_RETRIES; i++) {
if (sendto(pollsock.fd, outBuffer, 5, 0, (struct sockaddr *)&toAddr,
socklen) < 0) {
- perror("dhtRemove():sendto()");
- break;
+ perror("dhtRemove():sendto()");
+ break;
}
retval = poll(&pollsock, 1, REMOVE_TIMEOUT_MS);
if (retval < 0) {
- perror("dhtRemove():poll()");
- break;
+ perror("dhtRemove():poll()");
+ break;
}
if (retval > 0) {
- bytesRcvd = recvfrom(pollsock.fd, inBuffer, 2, 0,
- (struct sockaddr *)&fromAddr, &socklen);
- if (fromAddr.sin_addr.s_addr == toAddr.sin_addr.s_addr
- && fromAddr.sin_port == toAddr.sin_port
- && bytesRcvd == 2 && inBuffer[0] == REMOVE_RES) {
- status = inBuffer[1]; //status from remote host
- break;
- }
+ bytesRcvd = recvfrom(pollsock.fd, inBuffer, 2, 0,
+ (struct sockaddr *)&fromAddr, &socklen);
+ if (fromAddr.sin_addr.s_addr == toAddr.sin_addr.s_addr
+ && fromAddr.sin_port == toAddr.sin_port
+ && bytesRcvd == 2 && inBuffer[0] == REMOVE_RES) {
+ status = inBuffer[1]; //status from remote host
+ break;
+ }
}
}
if (!(status == OPERATION_OK || status == KEY_NOT_FOUND)) {
for (i = 0; i < SEARCH_RETRIES; i++) {
if (sendto(pollsock.fd, outBuffer, 5, 0, (struct sockaddr *)&toAddr,
socklen) < 0) {
- perror("dhtSearch():sendto()");
- break;
+ perror("dhtSearch():sendto()");
+ break;
}
retval = poll(&pollsock, 1, SEARCH_TIMEOUT_MS);
if (retval < 0) {
- perror("dhtSearch():poll()");
- break;
+ perror("dhtSearch():poll()");
+ break;
}
if (retval > 0) {
- bytesRcvd = recvfrom(pollsock.fd, inBuffer, 6, 0,
- (struct sockaddr *)&fromAddr, &socklen);
- if (fromAddr.sin_addr.s_addr == toAddr.sin_addr.s_addr
- && fromAddr.sin_port == toAddr.sin_port
- && bytesRcvd == 6 && inBuffer[0] == SEARCH_RES) {
- status = inBuffer[1]; //status from remote host
- *val = read4(&inBuffer[2]);
- break;
- }
+ bytesRcvd = recvfrom(pollsock.fd, inBuffer, 6, 0,
+ (struct sockaddr *)&fromAddr, &socklen);
+ if (fromAddr.sin_addr.s_addr == toAddr.sin_addr.s_addr
+ && fromAddr.sin_port == toAddr.sin_port
+ && bytesRcvd == 6 && inBuffer[0] == SEARCH_RES) {
+ status = inBuffer[1]; //status from remote host
+ *val = read4(&inBuffer[2]);
+ break;
+ }
}
}
if (!(status == OPERATION_OK || status == KEY_NOT_FOUND)) {
for (i = 0; i < numHosts; i++) {
if ((hostReplied[i] == 0) && (hostArray[i].ipAddr != myHostData.ipAddr)) {
if (udpSend(msg, size, hostArray[i].ipAddr) != 0)
- status = -1;
+ status = -1;
}
}
return status;
return 0;
} else if (hostArray[i].ipAddr > newHost.ipAddr) {
if (numHosts == hostArraySize) {
- newHostArray = calloc(2 * hostArraySize, sizeof(struct hostData));
- newHostReplied = calloc(2 * hostArraySize, sizeof(unsigned char));
- memcpy(newHostArray, hostArray, (i * sizeof(struct hostData)));
- memcpy(newHostReplied, hostReplied, (i * sizeof(unsigned char)));
- newHostArray[i] = newHost;
- newHostReplied[i] = 0;
- memcpy(&newHostArray[i+1], &hostArray[i], ((numHosts - i) *
- sizeof(struct hostData)));
- memcpy(&newHostReplied[i+1], &hostReplied[i], ((numHosts - i) *
- sizeof(unsigned char)));
- free(hostArray);
- free(hostReplied);
- hostArray = newHostArray;
- hostReplied = newHostReplied;
- hostArraySize = 2 * hostArraySize;
+ newHostArray = calloc(2 * hostArraySize, sizeof(struct hostData));
+ newHostReplied = calloc(2 * hostArraySize, sizeof(unsigned char));
+ memcpy(newHostArray, hostArray, (i * sizeof(struct hostData)));
+ memcpy(newHostReplied, hostReplied, (i * sizeof(unsigned char)));
+ newHostArray[i] = newHost;
+ newHostReplied[i] = 0;
+ memcpy(&newHostArray[i+1], &hostArray[i], ((numHosts - i) *
+ sizeof(struct hostData)));
+ memcpy(&newHostReplied[i+1], &hostReplied[i], ((numHosts - i) *
+ sizeof(unsigned char)));
+ free(hostArray);
+ free(hostReplied);
+ hostArray = newHostArray;
+ hostReplied = newHostReplied;
+ hostArraySize = 2 * hostArraySize;
} else
{
- for (j = numHosts; j > i; j--) {
- hostArray[j] = hostArray[j-1];
- hostReplied[j] = hostReplied[j-1];
- }
- hostArray[i] = newHost;
- hostReplied[i] = 0;
+ for (j = numHosts; j > i; j--) {
+ hostArray[j] = hostArray[j-1];
+ hostReplied[j] = hostReplied[j-1];
+ }
+ hostArray[i] = newHost;
+ hostReplied[i] = 0;
}
for(j = 0; j < numBlocks; j++) {
- if (blockOwnerArray[j] >= i)
- blockOwnerArray[j]++;
+ if (blockOwnerArray[j] >= i)
+ blockOwnerArray[j]++;
}
numHosts++;
return 1;
bytesRcvd = recvfrom(udpPollSock.fd, inBuffer, MAX_MSG_SIZE, 0,
(struct sockaddr *)&peerAddr, &socklen);
if (bytesRcvd < 1) {
- dhtLog("udpListen(): ERROR: bytesRcvd = %d\n", bytesRcvd);
+ dhtLog("udpListen(): ERROR: bytesRcvd = %d\n", bytesRcvd);
} else if (inBuffer[0] >= NUM_MSG_TYPES) {
- dhtLog("udpListen(): ERROR: unknown msg type = %d\n", inBuffer[0]);
+ dhtLog("udpListen(): ERROR: unknown msg type = %d\n", inBuffer[0]);
} else if (!msgSizeOk(inBuffer, bytesRcvd)) {
- dhtLog("udpListen(): ERROR: msg size not ok: type = %s\n, size = %d\n",
- msg_types[inBuffer[0]], bytesRcvd);
+ dhtLog("udpListen(): ERROR: msg size not ok: type = %s\n, size = %d\n",
+ msg_types[inBuffer[0]], bytesRcvd);
} else if (state == EXIT2_STATE) {
- //do nothing
+ //do nothing
} else if (state == INIT1_STATE) { //after initialization with seed, do not proceed until seed replies
- dhtLog("udpListen(): received %s from %s, %d bytes\n",
- msg_types[inBuffer[0]], inet_ntoa(peerAddr.sin_addr), bytesRcvd);
- for (i = 0; i < bytesRcvd; i++)
- dhtLog(" %x", inBuffer[i]);
- dhtLog("\n");
- peerIp = ntohl(peerAddr.sin_addr.s_addr);
- if (peerIp == seed && inBuffer[0] == WHO_IS_LEADER_RES) {
- tmpHost.ipAddr = peerIp;
- tmpHost.maxKeyCapacity = 0;
- addHost(tmpHost);
- writeHostList();
- leader = read4(&inBuffer[1]);
- tmpAddr.s_addr = htonl(leader);
- dhtLog("leader = %s\n", inet_ntoa(tmpAddr));
- if (leader != 0) {
- setState(INIT2_STATE);
- outBuffer[0] = JOIN_REQ;
- write4(&outBuffer[1], myHostData.maxKeyCapacity);
- udpSend(outBuffer, 5, leader);
- } else
- {
- electionOriginator = myHostData.ipAddr;
- setState(ELECT1_STATE);
- outBuffer[0] = ELECT_LEADER_CMD;
- write4(&outBuffer[1], myHostData.ipAddr); //originator = me
- udpSendAll(outBuffer, 5);
- }
- }
+ dhtLog("udpListen(): received %s from %s, %d bytes\n",
+ msg_types[inBuffer[0]], inet_ntoa(peerAddr.sin_addr), bytesRcvd);
+ for (i = 0; i < bytesRcvd; i++)
+ dhtLog(" %x", inBuffer[i]);
+ dhtLog("\n");
+ peerIp = ntohl(peerAddr.sin_addr.s_addr);
+ if (peerIp == seed && inBuffer[0] == WHO_IS_LEADER_RES) {
+ tmpHost.ipAddr = peerIp;
+ tmpHost.maxKeyCapacity = 0;
+ addHost(tmpHost);
+ writeHostList();
+ leader = read4(&inBuffer[1]);
+ tmpAddr.s_addr = htonl(leader);
+ dhtLog("leader = %s\n", inet_ntoa(tmpAddr));
+ if (leader != 0) {
+ setState(INIT2_STATE);
+ outBuffer[0] = JOIN_REQ;
+ write4(&outBuffer[1], myHostData.maxKeyCapacity);
+ udpSend(outBuffer, 5, leader);
+ } else
+ {
+ electionOriginator = myHostData.ipAddr;
+ setState(ELECT1_STATE);
+ outBuffer[0] = ELECT_LEADER_CMD;
+ write4(&outBuffer[1], myHostData.ipAddr); //originator = me
+ udpSendAll(outBuffer, 5);
+ }
+ }
} else
{
- dhtLog("udpListen(): received %s from %s, %d bytes\n",
- msg_types[inBuffer[0]], inet_ntoa(peerAddr.sin_addr), bytesRcvd);
- for (i = 0; i < bytesRcvd; i++)
- dhtLog(" %x", inBuffer[i]);
- dhtLog("\n");
- peerIp = ntohl(peerAddr.sin_addr.s_addr);
- switch (inBuffer[0]) {
- case INSERT_CMD:
- if (state == NORMAL_STATE || state == LEAD_NORMAL1_STATE
- || state == LEAD_NORMAL2_STATE || state == REBUILD4_STATE
- || state == REBUILD5_STATE || state == LEAD_REBUILD3_STATE) {
- tmpKey = read4(&inBuffer[1]);
- tmpVal = read4(&inBuffer[5]);
- outBuffer[0] = INSERT_RES;
- if (getKeyOwner(tmpKey) == myHostData.ipAddr) {
- if (chashInsert(myHashTable, tmpKey, (void *)tmpVal) == 0)
- outBuffer[1] = OPERATION_OK;
- else
- outBuffer[1] = INTERNAL_ERROR;
- } else
- {
- outBuffer[1] = NOT_KEY_OWNER;
- }
- //reply to client socket
- sendto(udpPollSock.fd, outBuffer, 2, 0,
- (struct sockaddr *)&peerAddr, socklen);
- }
- break;
-
- case REMOVE_CMD:
- if (state == NORMAL_STATE || state == LEAD_NORMAL1_STATE
- || state == LEAD_NORMAL2_STATE) {
- tmpKey = read4(&inBuffer[1]);
- outBuffer[0] = REMOVE_RES;
- if (getKeyOwner(tmpKey) == myHostData.ipAddr) {
- if (chashRemove(myHashTable, tmpKey) == 0)
- outBuffer[1] = OPERATION_OK;
- else
- outBuffer[1] = KEY_NOT_FOUND;
- } else
- {
- outBuffer[1] = NOT_KEY_OWNER;
- }
- //reply to client socket
- sendto(udpPollSock.fd, outBuffer, 2, 0,
- (struct sockaddr *)&peerAddr, socklen);
- }
- break;
-
- case SEARCH_CMD:
- if (state == NORMAL_STATE || state == LEAD_NORMAL1_STATE
- || state == LEAD_NORMAL2_STATE) {
- tmpKey = read4(&inBuffer[1]);
- outBuffer[0] = SEARCH_RES;
- if (getKeyOwner(tmpKey) == myHostData.ipAddr) {
- if ((tmpVal = (unsigned int)chashSearch(myHashTable, tmpKey)) != 0) {
- outBuffer[1] = OPERATION_OK;
- write4(&outBuffer[2], tmpVal);
- } else
- {
- outBuffer[1] = KEY_NOT_FOUND;
- write4(&outBuffer[2], 0);
- }
- } else
- {
- outBuffer[1] = NOT_KEY_OWNER;
- write4(&outBuffer[2], 0);
- }
- //reply to client socket
- sendto(udpPollSock.fd, outBuffer, 6, 0,
- (struct sockaddr *)&peerAddr, socklen);
- }
- break;
-
- case WHO_IS_LEADER_CMD:
- tmpHost.ipAddr = peerIp;
- tmpHost.maxKeyCapacity = 0;
- addHost(tmpHost);
- writeHostList();
- outBuffer[0] = WHO_IS_LEADER_RES;
- //leader == 0 means I don't know who it is
- write4(&outBuffer[1], leader);
- udpSend(outBuffer, 5, peerIp);
- break;
-
- case JOIN_REQ:
- if (state == LEAD_NORMAL1_STATE || state == LEAD_NORMAL2_STATE) {
- tmpHost.ipAddr = peerIp;
- tmpHost.maxKeyCapacity = read4(&inBuffer[1]);
- addHost(tmpHost);
- writeHostList();
- if (state == LEAD_NORMAL1_STATE)
- setState(LEAD_NORMAL2_STATE);
- outBuffer[0] = JOIN_RES;
- outBuffer[1] = 0; //status, success
- udpSend(outBuffer, 2, peerIp);
- } else if (state == LEAD_REBUILD1_STATE) {
- //note: I don't need to addHost().
- checkReplied(peerIp);
- outBuffer[0] = JOIN_RES;
- outBuffer[1] = 0; //status, success
- udpSend(outBuffer, 2, peerIp);
- if (allReplied()) {
- makeAssignments();
- setState(LEAD_REBUILD2_STATE);
- outBuffer[0] = DHT_UPDATE_CMD;
- write2(&outBuffer[1], numHosts);
- write2(&outBuffer[3], numBlocks);
- memcpy(&outBuffer[5], hostArray, numHosts*sizeof(struct hostData));
- memcpy(&outBuffer[5+numHosts*sizeof(struct hostData)],
- blockOwnerArray, numBlocks*2);
- udpSendAll(outBuffer, 5 + sizeof(struct hostData) * numHosts
- + 2 * numBlocks);
- }
- }
- break;
-
- case JOIN_RES:
- if (state == REBUILD1_STATE) {
- setState(REBUILD2_STATE);
- } else if (state == INIT2_STATE) {
- setState(NORMAL_STATE);
- }
- break;
-
- case LEAVE_REQ:
- if (state == LEAD_NORMAL1_STATE || state == LEAD_NORMAL2_STATE) { //TODO: make this graceful, instead of just rebuilding
- removeHost(peerIp);
- if (state != LEAD_NORMAL2_STATE)
- setState(LEAD_NORMAL2_STATE);
- }
- break;
-
- case DHT_UPDATE_CMD:
- if (state == REBUILD2_STATE && peerIp == leader) {
- free(hostArray);
- free(blockOwnerArray);
- numHosts = read2(&inBuffer[1]);
- numBlocks = read2(&inBuffer[3]);
- while (hostArraySize < numHosts)
- hostArraySize *= 2;
- hostArray = calloc(hostArraySize, sizeof(struct hostData));
- blockOwnerArray = calloc(numBlocks, 2);
- memcpy(hostArray, &inBuffer[5], numHosts*sizeof(struct hostData));
- memcpy(blockOwnerArray, &inBuffer[5+numHosts*sizeof(struct hostData)], numBlocks*2);
- writeHostList();
- setState(REBUILD3_STATE);
- outBuffer[0] = DHT_UPDATE_RES;
- udpSend(outBuffer, 1, peerIp);
- }
- break;
-
- case DHT_UPDATE_RES:
- if (state == LEAD_REBUILD2_STATE) {
- checkReplied(peerIp);
- if (allReplied()) {
- setState(LEAD_REBUILD3_STATE);
- outBuffer[0] = FILL_DHT_CMD;
- udpSendAll(outBuffer, 1);
- if (fillStatus != 0)
- dhtLog("udpListen(): ERROR: fillTask already running\n");
- fillStatus = 1;
- if (pthread_create(&threadFillTask, NULL, fillTask, NULL) != 0)
- dhtLog("udpListen(): ERROR creating threadFillTask\n");
- }
- }
- break;
-
- case ELECT_LEADER_CMD:
- tmpUInt = read4(&inBuffer[1]);
- if ((state == ELECT1_STATE || state == ELECT2_STATE)
- && tmpUInt >= electionOriginator) { //already participating in a higher-priority election
- outBuffer[0] = ELECT_LEADER_RES;
- outBuffer[1] = 0xFF;
- udpSend(outBuffer, 2, peerIp);
- } else
- { //join election
- electionOriginator = tmpUInt;
- electionParent = peerIp;
- setState(ELECT1_STATE);
- outBuffer[0] = ELECT_LEADER_CMD;
- write4(&outBuffer[1], electionOriginator);
- //don't bother forwarding the message to originator or parent
- checkReplied(electionOriginator);
- checkReplied(electionParent);
- if (allReplied()) { //in case that is everybody I know of
- setState(ELECT2_STATE);
- outBuffer[0] = ELECT_LEADER_RES;
- outBuffer[1] = 0;
- write2(&outBuffer[2], numHosts);
- memcpy(&outBuffer[4], hostArray, sizeof(struct hostData)
- * numHosts);
- udpSend(outBuffer, 4 + sizeof(struct hostData) * numHosts,
- electionParent);
- } else
- {
- udpSendAll(outBuffer, 5);
- }
- }
- break;
-
- case ELECT_LEADER_RES:
- if (state == ELECT1_STATE) {
- checkReplied(peerIp);
- if (inBuffer[1] != 0xFF) {
- tmpUShort = read2(&inBuffer[2]);
- hostDataPtr = (struct hostData *)&inBuffer[4];
- for (i = 0; i < tmpUShort; i++)
- addHost(hostDataPtr[i]);
- writeHostList();
- }
- if (allReplied()) {
- setState(ELECT2_STATE);
- if (electionOriginator == myHostData.ipAddr) {
- leader = hostArray[0].ipAddr;
- if (leader == myHostData.ipAddr) { //I am the leader
- dhtLog("I am the leader!\n");
- setState(LEAD_REBUILD1_STATE);
- outBuffer[0] = REBUILD_CMD;
- udpSendAll(outBuffer, 1);
- } else
- { //notify leader
- outBuffer[0] = CONGRATS_CMD;
- write2(&outBuffer[1], numHosts);
- hostDataPtr = (struct hostData *)&outBuffer[3];
- for (i = 0; i < numHosts; i++)
- hostDataPtr[i] = hostArray[i];
- udpSend(outBuffer, 3 + sizeof(struct hostData) * numHosts,
- leader);
- }
- } else
- {
- outBuffer[0] = ELECT_LEADER_RES;
- outBuffer[1] = 0;
- write2(&outBuffer[2], numHosts);
- hostDataPtr = (struct hostData *)&outBuffer[4];
- for (i = 0; i < numHosts; i++)
- hostDataPtr[i] = hostArray[i];
- udpSend(outBuffer, 4 + sizeof(struct hostData) * numHosts,
- electionParent);
- }
- }
- }
- break;
-
- case CONGRATS_CMD:
- if (state == ELECT2_STATE) { //I am the leader
- leader = myHostData.ipAddr;
- dhtLog("I am the leader!\n");
- tmpUShort = read2(&inBuffer[1]);
- hostDataPtr = (struct hostData *)&inBuffer[3];
- for (i = 0; i < tmpUShort; i++)
- addHost(hostDataPtr[i]);
- writeHostList();
- setState(LEAD_REBUILD1_STATE);
- outBuffer[0] = REBUILD_CMD;
- udpSendAll(outBuffer, 1);
- }
- break;
-
- case REBUILD_REQ:
- if (state == LEAD_NORMAL1_STATE || state == LEAD_NORMAL2_STATE) {
- setState(LEAD_REBUILD1_STATE);
- outBuffer[0] = REBUILD_CMD;
- udpSendAll(outBuffer, 1);
- }
- break;
-
- case REBUILD_CMD:
- leader = peerIp; //consider this a declaration of authority
- setState(REBUILD1_STATE);
- outBuffer[0] = JOIN_REQ;
- write4(&outBuffer[1], myHostData.maxKeyCapacity);
- udpSend(outBuffer, 5, leader);
- break;
-
- case FILL_DHT_CMD:
- if (state == REBUILD3_STATE && peerIp == leader) {
- setState(REBUILD4_STATE);
- if (fillStatus != 0)
- dhtLog("udpListen(): ERROR: fillTask already running\n");
- fillStatus = 1;
- if (pthread_create(&threadFillTask, NULL, fillTask, NULL) != 0)
- dhtLog("udpListen(): ERROR creating threadFillTask\n");
- }
- break;
-
- case FILL_DHT_RES:
- if (state == LEAD_REBUILD3_STATE) {
- checkReplied(peerIp);
- if (allReplied() && fillStatus == 2) {
- fillStatus = 0;
- setState(LEAD_REBUILD4_STATE);
- outBuffer[0] = RESUME_NORMAL_CMD;
- udpSendAll(outBuffer, 1);
- }
- }
- break;
-
- case RESUME_NORMAL_CMD:
- if (state == REBUILD5_STATE && peerIp == leader) {
- setState(NORMAL_STATE);
- outBuffer[0] = RESUME_NORMAL_RES;
- udpSend(outBuffer, 1, leader);
- }
- break;
-
- case RESUME_NORMAL_RES:
- if (state == LEAD_REBUILD4_STATE) {
- checkReplied(peerIp);
- if (allReplied()) {
- setState(LEAD_NORMAL1_STATE);
- }
- }
- break;
- }
+ dhtLog("udpListen(): received %s from %s, %d bytes\n",
+ msg_types[inBuffer[0]], inet_ntoa(peerAddr.sin_addr), bytesRcvd);
+ for (i = 0; i < bytesRcvd; i++)
+ dhtLog(" %x", inBuffer[i]);
+ dhtLog("\n");
+ peerIp = ntohl(peerAddr.sin_addr.s_addr);
+ switch (inBuffer[0]) {
+ case INSERT_CMD:
+ if (state == NORMAL_STATE || state == LEAD_NORMAL1_STATE
+ || state == LEAD_NORMAL2_STATE || state == REBUILD4_STATE
+ || state == REBUILD5_STATE || state == LEAD_REBUILD3_STATE) {
+ tmpKey = read4(&inBuffer[1]);
+ tmpVal = read4(&inBuffer[5]);
+ outBuffer[0] = INSERT_RES;
+ if (getKeyOwner(tmpKey) == myHostData.ipAddr) {
+ if (chashInsert(myHashTable, tmpKey, (void *)tmpVal) == 0)
+ outBuffer[1] = OPERATION_OK;
+ else
+ outBuffer[1] = INTERNAL_ERROR;
+ } else
+ {
+ outBuffer[1] = NOT_KEY_OWNER;
+ }
+ //reply to client socket
+ sendto(udpPollSock.fd, outBuffer, 2, 0,
+ (struct sockaddr *)&peerAddr, socklen);
+ }
+ break;
+
+ case REMOVE_CMD:
+ if (state == NORMAL_STATE || state == LEAD_NORMAL1_STATE
+ || state == LEAD_NORMAL2_STATE) {
+ tmpKey = read4(&inBuffer[1]);
+ outBuffer[0] = REMOVE_RES;
+ if (getKeyOwner(tmpKey) == myHostData.ipAddr) {
+ if (chashRemove(myHashTable, tmpKey) == 0)
+ outBuffer[1] = OPERATION_OK;
+ else
+ outBuffer[1] = KEY_NOT_FOUND;
+ } else
+ {
+ outBuffer[1] = NOT_KEY_OWNER;
+ }
+ //reply to client socket
+ sendto(udpPollSock.fd, outBuffer, 2, 0,
+ (struct sockaddr *)&peerAddr, socklen);
+ }
+ break;
+
+ case SEARCH_CMD:
+ if (state == NORMAL_STATE || state == LEAD_NORMAL1_STATE
+ || state == LEAD_NORMAL2_STATE) {
+ tmpKey = read4(&inBuffer[1]);
+ outBuffer[0] = SEARCH_RES;
+ if (getKeyOwner(tmpKey) == myHostData.ipAddr) {
+ if ((tmpVal = (unsigned int)chashSearch(myHashTable, tmpKey)) != 0) {
+ outBuffer[1] = OPERATION_OK;
+ write4(&outBuffer[2], tmpVal);
+ } else
+ {
+ outBuffer[1] = KEY_NOT_FOUND;
+ write4(&outBuffer[2], 0);
+ }
+ } else
+ {
+ outBuffer[1] = NOT_KEY_OWNER;
+ write4(&outBuffer[2], 0);
+ }
+ //reply to client socket
+ sendto(udpPollSock.fd, outBuffer, 6, 0,
+ (struct sockaddr *)&peerAddr, socklen);
+ }
+ break;
+
+ case WHO_IS_LEADER_CMD:
+ tmpHost.ipAddr = peerIp;
+ tmpHost.maxKeyCapacity = 0;
+ addHost(tmpHost);
+ writeHostList();
+ outBuffer[0] = WHO_IS_LEADER_RES;
+ //leader == 0 means I don't know who it is
+ write4(&outBuffer[1], leader);
+ udpSend(outBuffer, 5, peerIp);
+ break;
+
+ case JOIN_REQ:
+ if (state == LEAD_NORMAL1_STATE || state == LEAD_NORMAL2_STATE) {
+ tmpHost.ipAddr = peerIp;
+ tmpHost.maxKeyCapacity = read4(&inBuffer[1]);
+ addHost(tmpHost);
+ writeHostList();
+ if (state == LEAD_NORMAL1_STATE)
+ setState(LEAD_NORMAL2_STATE);
+ outBuffer[0] = JOIN_RES;
+ outBuffer[1] = 0; //status, success
+ udpSend(outBuffer, 2, peerIp);
+ } else if (state == LEAD_REBUILD1_STATE) {
+ //note: I don't need to addHost().
+ checkReplied(peerIp);
+ outBuffer[0] = JOIN_RES;
+ outBuffer[1] = 0; //status, success
+ udpSend(outBuffer, 2, peerIp);
+ if (allReplied()) {
+ makeAssignments();
+ setState(LEAD_REBUILD2_STATE);
+ outBuffer[0] = DHT_UPDATE_CMD;
+ write2(&outBuffer[1], numHosts);
+ write2(&outBuffer[3], numBlocks);
+ memcpy(&outBuffer[5], hostArray, numHosts*sizeof(struct hostData));
+ memcpy(&outBuffer[5+numHosts*sizeof(struct hostData)],
+ blockOwnerArray, numBlocks*2);
+ udpSendAll(outBuffer, 5 + sizeof(struct hostData) * numHosts
+ + 2 * numBlocks);
+ }
+ }
+ break;
+
+ case JOIN_RES:
+ if (state == REBUILD1_STATE) {
+ setState(REBUILD2_STATE);
+ } else if (state == INIT2_STATE) {
+ setState(NORMAL_STATE);
+ }
+ break;
+
+ case LEAVE_REQ:
+ if (state == LEAD_NORMAL1_STATE || state == LEAD_NORMAL2_STATE) { //TODO: make this graceful, instead of just rebuilding
+ removeHost(peerIp);
+ if (state != LEAD_NORMAL2_STATE)
+ setState(LEAD_NORMAL2_STATE);
+ }
+ break;
+
+ case DHT_UPDATE_CMD:
+ if (state == REBUILD2_STATE && peerIp == leader) {
+ free(hostArray);
+ free(blockOwnerArray);
+ numHosts = read2(&inBuffer[1]);
+ numBlocks = read2(&inBuffer[3]);
+ while (hostArraySize < numHosts)
+ hostArraySize *= 2;
+ hostArray = calloc(hostArraySize, sizeof(struct hostData));
+ blockOwnerArray = calloc(numBlocks, 2);
+ memcpy(hostArray, &inBuffer[5], numHosts*sizeof(struct hostData));
+ memcpy(blockOwnerArray, &inBuffer[5+numHosts*sizeof(struct hostData)], numBlocks*2);
+ writeHostList();
+ setState(REBUILD3_STATE);
+ outBuffer[0] = DHT_UPDATE_RES;
+ udpSend(outBuffer, 1, peerIp);
+ }
+ break;
+
+ case DHT_UPDATE_RES:
+ if (state == LEAD_REBUILD2_STATE) {
+ checkReplied(peerIp);
+ if (allReplied()) {
+ setState(LEAD_REBUILD3_STATE);
+ outBuffer[0] = FILL_DHT_CMD;
+ udpSendAll(outBuffer, 1);
+ if (fillStatus != 0)
+ dhtLog("udpListen(): ERROR: fillTask already running\n");
+ fillStatus = 1;
+ if (pthread_create(&threadFillTask, NULL, fillTask, NULL) != 0)
+ dhtLog("udpListen(): ERROR creating threadFillTask\n");
+ }
+ }
+ break;
+
+ case ELECT_LEADER_CMD:
+ tmpUInt = read4(&inBuffer[1]);
+ if ((state == ELECT1_STATE || state == ELECT2_STATE)
+ && tmpUInt >= electionOriginator) { //already participating in a higher-priority election
+ outBuffer[0] = ELECT_LEADER_RES;
+ outBuffer[1] = 0xFF;
+ udpSend(outBuffer, 2, peerIp);
+ } else
+ { //join election
+ electionOriginator = tmpUInt;
+ electionParent = peerIp;
+ setState(ELECT1_STATE);
+ outBuffer[0] = ELECT_LEADER_CMD;
+ write4(&outBuffer[1], electionOriginator);
+ //don't bother forwarding the message to originator or parent
+ checkReplied(electionOriginator);
+ checkReplied(electionParent);
+ if (allReplied()) { //in case that is everybody I know of
+ setState(ELECT2_STATE);
+ outBuffer[0] = ELECT_LEADER_RES;
+ outBuffer[1] = 0;
+ write2(&outBuffer[2], numHosts);
+ memcpy(&outBuffer[4], hostArray, sizeof(struct hostData)
+ * numHosts);
+ udpSend(outBuffer, 4 + sizeof(struct hostData) * numHosts,
+ electionParent);
+ } else
+ {
+ udpSendAll(outBuffer, 5);
+ }
+ }
+ break;
+
+ case ELECT_LEADER_RES:
+ if (state == ELECT1_STATE) {
+ checkReplied(peerIp);
+ if (inBuffer[1] != 0xFF) {
+ tmpUShort = read2(&inBuffer[2]);
+ hostDataPtr = (struct hostData *)&inBuffer[4];
+ for (i = 0; i < tmpUShort; i++)
+ addHost(hostDataPtr[i]);
+ writeHostList();
+ }
+ if (allReplied()) {
+ setState(ELECT2_STATE);
+ if (electionOriginator == myHostData.ipAddr) {
+ leader = hostArray[0].ipAddr;
+ if (leader == myHostData.ipAddr) { //I am the leader
+ dhtLog("I am the leader!\n");
+ setState(LEAD_REBUILD1_STATE);
+ outBuffer[0] = REBUILD_CMD;
+ udpSendAll(outBuffer, 1);
+ } else
+ { //notify leader
+ outBuffer[0] = CONGRATS_CMD;
+ write2(&outBuffer[1], numHosts);
+ hostDataPtr = (struct hostData *)&outBuffer[3];
+ for (i = 0; i < numHosts; i++)
+ hostDataPtr[i] = hostArray[i];
+ udpSend(outBuffer, 3 + sizeof(struct hostData) * numHosts,
+ leader);
+ }
+ } else
+ {
+ outBuffer[0] = ELECT_LEADER_RES;
+ outBuffer[1] = 0;
+ write2(&outBuffer[2], numHosts);
+ hostDataPtr = (struct hostData *)&outBuffer[4];
+ for (i = 0; i < numHosts; i++)
+ hostDataPtr[i] = hostArray[i];
+ udpSend(outBuffer, 4 + sizeof(struct hostData) * numHosts,
+ electionParent);
+ }
+ }
+ }
+ break;
+
+ case CONGRATS_CMD:
+ if (state == ELECT2_STATE) { //I am the leader
+ leader = myHostData.ipAddr;
+ dhtLog("I am the leader!\n");
+ tmpUShort = read2(&inBuffer[1]);
+ hostDataPtr = (struct hostData *)&inBuffer[3];
+ for (i = 0; i < tmpUShort; i++)
+ addHost(hostDataPtr[i]);
+ writeHostList();
+ setState(LEAD_REBUILD1_STATE);
+ outBuffer[0] = REBUILD_CMD;
+ udpSendAll(outBuffer, 1);
+ }
+ break;
+
+ case REBUILD_REQ:
+ if (state == LEAD_NORMAL1_STATE || state == LEAD_NORMAL2_STATE) {
+ setState(LEAD_REBUILD1_STATE);
+ outBuffer[0] = REBUILD_CMD;
+ udpSendAll(outBuffer, 1);
+ }
+ break;
+
+ case REBUILD_CMD:
+ leader = peerIp; //consider this a declaration of authority
+ setState(REBUILD1_STATE);
+ outBuffer[0] = JOIN_REQ;
+ write4(&outBuffer[1], myHostData.maxKeyCapacity);
+ udpSend(outBuffer, 5, leader);
+ break;
+
+ case FILL_DHT_CMD:
+ if (state == REBUILD3_STATE && peerIp == leader) {
+ setState(REBUILD4_STATE);
+ if (fillStatus != 0)
+ dhtLog("udpListen(): ERROR: fillTask already running\n");
+ fillStatus = 1;
+ if (pthread_create(&threadFillTask, NULL, fillTask, NULL) != 0)
+ dhtLog("udpListen(): ERROR creating threadFillTask\n");
+ }
+ break;
+
+ case FILL_DHT_RES:
+ if (state == LEAD_REBUILD3_STATE) {
+ checkReplied(peerIp);
+ if (allReplied() && fillStatus == 2) {
+ fillStatus = 0;
+ setState(LEAD_REBUILD4_STATE);
+ outBuffer[0] = RESUME_NORMAL_CMD;
+ udpSendAll(outBuffer, 1);
+ }
+ }
+ break;
+
+ case RESUME_NORMAL_CMD:
+ if (state == REBUILD5_STATE && peerIp == leader) {
+ setState(NORMAL_STATE);
+ outBuffer[0] = RESUME_NORMAL_RES;
+ udpSend(outBuffer, 1, leader);
+ }
+ break;
+
+ case RESUME_NORMAL_RES:
+ if (state == LEAD_REBUILD4_STATE) {
+ checkReplied(peerIp);
+ if (allReplied()) {
+ setState(LEAD_NORMAL1_STATE);
+ }
+ }
+ break;
+ }
}
}
if (state == REBUILD4_STATE) {
switch (fillStatus) {
case 0: dhtLog("udpListen(): ERROR: fillStatus=0 in REBUILD4_STATE\n");
- break;
+ break;
case 1: //do nothing
- break;
+ break;
case 2: //done filling the dht, notify leader
- fillStatus = 0;
- setState(REBUILD5_STATE);
- outBuffer[0] = FILL_DHT_RES;
- udpSend(outBuffer, 1, leader);
- break;
+ fillStatus = 0;
+ setState(REBUILD5_STATE);
+ outBuffer[0] = FILL_DHT_RES;
+ udpSend(outBuffer, 1, leader);
+ break;
case 3: //error encountered -> restart rebuild
- fillStatus = 0;
- setState(REBUILD0_STATE);
- outBuffer[0] = REBUILD_REQ;
- udpSend(outBuffer, 1, leader);
- break;
+ fillStatus = 0;
+ setState(REBUILD0_STATE);
+ outBuffer[0] = REBUILD_REQ;
+ udpSend(outBuffer, 1, leader);
+ break;
}
}
if (state == LEAD_REBUILD3_STATE) {
switch (fillStatus) {
case 0: dhtLog("udpListen(): ERROR: fillStatus=0 in LEAD_REBUILD3_STATE\n");
- break;
+ break;
case 1: //do nothing
- break;
+ break;
case 2: //I'm done, now is everybody else also done?
- if (allReplied()) {
- fillStatus = 0;
- setState(LEAD_REBUILD4_STATE);
- outBuffer[0] = RESUME_NORMAL_CMD;
- udpSendAll(outBuffer, 1);
- }
- break;
+ if (allReplied()) {
+ fillStatus = 0;
+ setState(LEAD_REBUILD4_STATE);
+ outBuffer[0] = RESUME_NORMAL_CMD;
+ udpSendAll(outBuffer, 1);
+ }
+ break;
case 3: //error encountered -> restart rebuild
- fillStatus = 0;
- setState(LEAD_REBUILD1_STATE);
- outBuffer[0] = REBUILD_CMD;
- udpSendAll(outBuffer, 1);
- break;
+ fillStatus = 0;
+ setState(LEAD_REBUILD1_STATE);
+ outBuffer[0] = REBUILD_CMD;
+ udpSendAll(outBuffer, 1);
+ break;
}
}
if (timerSet) {
gettimeofday(&now, NULL);
if (timercmp(&now, &timer, >)) {
- if (timeoutCntr < retry_vals[state]) {
- timeoutCntr++;
- timeradd(&now, &timeout_vals[state], &timer);
- dhtLog("udpListen(): retry: %d\n", timeoutCntr);
- switch (state) {
- case INIT1_STATE:
- outBuffer[0] = WHO_IS_LEADER_CMD;
- udpSend(outBuffer, 1, seed);
- break;
-
- case INIT2_STATE:
- outBuffer[0] = JOIN_REQ;
- write4(&outBuffer[1], myHostData.maxKeyCapacity);
- udpSend(outBuffer, 5, leader);
- break;
-
- case ELECT1_STATE:
- outBuffer[0] = ELECT_LEADER_CMD;
- write4(&outBuffer[1], electionOriginator);
- udpSendAll(outBuffer, 5);
- break;
-
- case ELECT2_STATE:
- if (electionOriginator == myHostData.ipAddr) { //retry notify leader
- outBuffer[0] = CONGRATS_CMD;
- write2(&outBuffer[1], numHosts);
- memcpy(&outBuffer[3], hostArray, sizeof(struct hostData)
- * numHosts);
- udpSend(outBuffer, 3 + sizeof(struct hostData) * numHosts,
- leader);
- } else
- {
- outBuffer[0] = ELECT_LEADER_RES;
- outBuffer[1] = 0;
- write2(&outBuffer[2], numHosts);
- memcpy(&outBuffer[4], hostArray, sizeof(struct hostData)
- * numHosts);
- udpSend(outBuffer, 4 + sizeof(struct hostData) * numHosts,
- electionParent);
- }
- break;
-
- case REBUILD0_STATE:
- outBuffer[0] = REBUILD_REQ;
- udpSend(outBuffer, 1, leader);
- break;
-
- case REBUILD1_STATE:
- outBuffer[0] = JOIN_REQ;
- write4(&outBuffer[1], myHostData.maxKeyCapacity);
- udpSend(outBuffer, 5, leader);
- break;
-
- case REBUILD5_STATE:
- outBuffer[0] = FILL_DHT_RES;
- udpSend(outBuffer, 1, leader);
- break;
-
- case LEAD_REBUILD1_STATE:
- outBuffer[0] = REBUILD_CMD;
- udpSendAll(outBuffer, 1);
- break;
-
- case LEAD_REBUILD2_STATE:
- outBuffer[0] = DHT_UPDATE_CMD;
- write2(&outBuffer[1], numHosts);
- write2(&outBuffer[3], numBlocks);
- memcpy(&outBuffer[5], hostArray, numHosts
- * sizeof(struct hostData));
- memcpy(&outBuffer[5+numHosts*sizeof(struct hostData)],
- blockOwnerArray, numBlocks*2);
- udpSendAll(outBuffer, 5 + sizeof(struct hostData) * numHosts
- + 2 * numBlocks);
- break;
-
- case LEAD_REBUILD3_STATE:
- outBuffer[0] = FILL_DHT_CMD;
- udpSendAll(outBuffer, 1);
- break;
-
- case LEAD_REBUILD4_STATE:
- outBuffer[0] = RESUME_NORMAL_CMD;
- udpSendAll(outBuffer, 1);
- break;
-
- case EXIT1_STATE: //TODO...
- break;
-
- case NORMAL_STATE:
- case LEAD_NORMAL1_STATE:
- case LEAD_NORMAL2_STATE:
- case REBUILD2_STATE:
- case REBUILD3_STATE:
- case REBUILD4_STATE:
- case EXIT2_STATE: //we shouldn't get here
- break;
- }
- } else
- {
- dhtLog("udpListen(): timed out in state %s after %d retries\n",
- state_names[state], timeoutCntr);
- switch (state) {
- case INIT1_STATE:
- setState(EXIT2_STATE);
- break;
-
- case LEAD_NORMAL2_STATE:
- setState(LEAD_REBUILD1_STATE);
- outBuffer[0] = REBUILD_CMD;
- udpSendAll(outBuffer, 1);
- break;
-
- case ELECT1_STATE:
- dhtLog("removing unresponsive hosts, before:\n");
- writeHostList();
- removeUnresponsiveHosts();
- dhtLog("after\n");
- writeHostList();
- setState(ELECT2_STATE);
- if (electionOriginator == myHostData.ipAddr) {
- leader = hostArray[0].ipAddr;
- if (leader == myHostData.ipAddr) { //I am the leader
- dhtLog("I am the leader!\n");
- setState(LEAD_REBUILD1_STATE);
- outBuffer[0] = REBUILD_CMD;
- udpSendAll(outBuffer, 1);
- } else
- { //notify leader
- outBuffer[0] = CONGRATS_CMD;
- write2(&outBuffer[1], numHosts);
- memcpy(&outBuffer[3], hostArray, sizeof(struct hostData)
- * numHosts);
- udpSend(outBuffer, 3 + sizeof(struct hostData) * numHosts,
- leader);
- }
- } else
- {
- outBuffer[0] = ELECT_LEADER_RES;
- outBuffer[1] = 0;
- write2(&outBuffer[2], numHosts);
- memcpy(&outBuffer[4], hostArray, sizeof(struct hostData)
- * numHosts);
- udpSend(outBuffer, 4 + sizeof(struct hostData) * numHosts,
- electionParent);
- }
- break;
-
- case INIT2_STATE:
- case ELECT2_STATE:
- case REBUILD0_STATE:
- case REBUILD1_STATE:
- case REBUILD2_STATE:
- case REBUILD3_STATE:
- case REBUILD4_STATE:
- case REBUILD5_STATE:
- case LEAD_REBUILD1_STATE:
- case LEAD_REBUILD2_STATE:
- case LEAD_REBUILD3_STATE:
- case LEAD_REBUILD4_STATE:
- //start election
- electionOriginator = myHostData.ipAddr;
- setState(ELECT1_STATE);
- outBuffer[0] = ELECT_LEADER_CMD;
- write4(&outBuffer[1], myHostData.ipAddr); //originator = me
- udpSendAll(outBuffer, 5);
- break;
-
- case EXIT1_STATE:
- setState(EXIT2_STATE);
- break;
-
- case NORMAL_STATE:
- case LEAD_NORMAL1_STATE:
- case EXIT2_STATE: //we shouldn't get here
- break;
- }
- }
+ if (timeoutCntr < retry_vals[state]) {
+ timeoutCntr++;
+ timeradd(&now, &timeout_vals[state], &timer);
+ dhtLog("udpListen(): retry: %d\n", timeoutCntr);
+ switch (state) {
+ case INIT1_STATE:
+ outBuffer[0] = WHO_IS_LEADER_CMD;
+ udpSend(outBuffer, 1, seed);
+ break;
+
+ case INIT2_STATE:
+ outBuffer[0] = JOIN_REQ;
+ write4(&outBuffer[1], myHostData.maxKeyCapacity);
+ udpSend(outBuffer, 5, leader);
+ break;
+
+ case ELECT1_STATE:
+ outBuffer[0] = ELECT_LEADER_CMD;
+ write4(&outBuffer[1], electionOriginator);
+ udpSendAll(outBuffer, 5);
+ break;
+
+ case ELECT2_STATE:
+ if (electionOriginator == myHostData.ipAddr) { //retry notify leader
+ outBuffer[0] = CONGRATS_CMD;
+ write2(&outBuffer[1], numHosts);
+ memcpy(&outBuffer[3], hostArray, sizeof(struct hostData)
+ * numHosts);
+ udpSend(outBuffer, 3 + sizeof(struct hostData) * numHosts,
+ leader);
+ } else
+ {
+ outBuffer[0] = ELECT_LEADER_RES;
+ outBuffer[1] = 0;
+ write2(&outBuffer[2], numHosts);
+ memcpy(&outBuffer[4], hostArray, sizeof(struct hostData)
+ * numHosts);
+ udpSend(outBuffer, 4 + sizeof(struct hostData) * numHosts,
+ electionParent);
+ }
+ break;
+
+ case REBUILD0_STATE:
+ outBuffer[0] = REBUILD_REQ;
+ udpSend(outBuffer, 1, leader);
+ break;
+
+ case REBUILD1_STATE:
+ outBuffer[0] = JOIN_REQ;
+ write4(&outBuffer[1], myHostData.maxKeyCapacity);
+ udpSend(outBuffer, 5, leader);
+ break;
+
+ case REBUILD5_STATE:
+ outBuffer[0] = FILL_DHT_RES;
+ udpSend(outBuffer, 1, leader);
+ break;
+
+ case LEAD_REBUILD1_STATE:
+ outBuffer[0] = REBUILD_CMD;
+ udpSendAll(outBuffer, 1);
+ break;
+
+ case LEAD_REBUILD2_STATE:
+ outBuffer[0] = DHT_UPDATE_CMD;
+ write2(&outBuffer[1], numHosts);
+ write2(&outBuffer[3], numBlocks);
+ memcpy(&outBuffer[5], hostArray, numHosts
+ * sizeof(struct hostData));
+ memcpy(&outBuffer[5+numHosts*sizeof(struct hostData)],
+ blockOwnerArray, numBlocks*2);
+ udpSendAll(outBuffer, 5 + sizeof(struct hostData) * numHosts
+ + 2 * numBlocks);
+ break;
+
+ case LEAD_REBUILD3_STATE:
+ outBuffer[0] = FILL_DHT_CMD;
+ udpSendAll(outBuffer, 1);
+ break;
+
+ case LEAD_REBUILD4_STATE:
+ outBuffer[0] = RESUME_NORMAL_CMD;
+ udpSendAll(outBuffer, 1);
+ break;
+
+ case EXIT1_STATE: //TODO...
+ break;
+
+ case NORMAL_STATE:
+ case LEAD_NORMAL1_STATE:
+ case LEAD_NORMAL2_STATE:
+ case REBUILD2_STATE:
+ case REBUILD3_STATE:
+ case REBUILD4_STATE:
+ case EXIT2_STATE: //we shouldn't get here
+ break;
+ }
+ } else
+ {
+ dhtLog("udpListen(): timed out in state %s after %d retries\n",
+ state_names[state], timeoutCntr);
+ switch (state) {
+ case INIT1_STATE:
+ setState(EXIT2_STATE);
+ break;
+
+ case LEAD_NORMAL2_STATE:
+ setState(LEAD_REBUILD1_STATE);
+ outBuffer[0] = REBUILD_CMD;
+ udpSendAll(outBuffer, 1);
+ break;
+
+ case ELECT1_STATE:
+ dhtLog("removing unresponsive hosts, before:\n");
+ writeHostList();
+ removeUnresponsiveHosts();
+ dhtLog("after\n");
+ writeHostList();
+ setState(ELECT2_STATE);
+ if (electionOriginator == myHostData.ipAddr) {
+ leader = hostArray[0].ipAddr;
+ if (leader == myHostData.ipAddr) { //I am the leader
+ dhtLog("I am the leader!\n");
+ setState(LEAD_REBUILD1_STATE);
+ outBuffer[0] = REBUILD_CMD;
+ udpSendAll(outBuffer, 1);
+ } else
+ { //notify leader
+ outBuffer[0] = CONGRATS_CMD;
+ write2(&outBuffer[1], numHosts);
+ memcpy(&outBuffer[3], hostArray, sizeof(struct hostData)
+ * numHosts);
+ udpSend(outBuffer, 3 + sizeof(struct hostData) * numHosts,
+ leader);
+ }
+ } else
+ {
+ outBuffer[0] = ELECT_LEADER_RES;
+ outBuffer[1] = 0;
+ write2(&outBuffer[2], numHosts);
+ memcpy(&outBuffer[4], hostArray, sizeof(struct hostData)
+ * numHosts);
+ udpSend(outBuffer, 4 + sizeof(struct hostData) * numHosts,
+ electionParent);
+ }
+ break;
+
+ case INIT2_STATE:
+ case ELECT2_STATE:
+ case REBUILD0_STATE:
+ case REBUILD1_STATE:
+ case REBUILD2_STATE:
+ case REBUILD3_STATE:
+ case REBUILD4_STATE:
+ case REBUILD5_STATE:
+ case LEAD_REBUILD1_STATE:
+ case LEAD_REBUILD2_STATE:
+ case LEAD_REBUILD3_STATE:
+ case LEAD_REBUILD4_STATE:
+ //start election
+ electionOriginator = myHostData.ipAddr;
+ setState(ELECT1_STATE);
+ outBuffer[0] = ELECT_LEADER_CMD;
+ write4(&outBuffer[1], myHostData.ipAddr); //originator = me
+ udpSendAll(outBuffer, 5);
+ break;
+
+ case EXIT1_STATE:
+ setState(EXIT2_STATE);
+ break;
+
+ case NORMAL_STATE:
+ case LEAD_NORMAL1_STATE:
+ case EXIT2_STATE: //we shouldn't get here
+ break;
+ }
+ }
}
}
if (state != oldState)
inline void atomic_dec(volatile int *v) {
__asm__ __volatile__ (LOCK_PREFIX "decl %0"
- : "+m" (*v));
+ : "+m" (*v));
}
inline void atomic_inc(volatile int *v) {
__asm__ __volatile__ (LOCK_PREFIX "incl %0"
- : "+m" (*v));
+ : "+m" (*v));
}
static inline int atomic_sub_and_test(int i, volatile int *v) {
unsigned char c;
__asm__ __volatile__ (LOCK_PREFIX "subl %2,%0; sete %1"
- : "+m" (*v), "=qm" (c)
- : "ir" (i) : "memory");
+ : "+m" (*v), "=qm" (c)
+ : "ir" (i) : "memory");
return c;
}
*/
static inline void atomic_add(int i, volatile int *v) {
__asm__ __volatile__ (LOCK_PREFIX "addl %1,%0"
- : "+m" (*v)
- : "ir" (i));
+ : "+m" (*v)
+ : "ir" (i));
}
inline int read_trylock(volatile int *lock) {
inline void write_unlock(volatile int *rw) {
__asm__ __volatile__ (LOCK_PREFIX "addl %1, %0"
- : "+m" (*rw) : "i" (RW_LOCK_BIAS) : "memory");
+ : "+m" (*rw) : "i" (RW_LOCK_BIAS) : "memory");
}
inline int is_write_locked(volatile int *lock) {
//#define TRANSREAD(x,y,z) /* Use "z" which is program point at which TRANSREAD is generated, use this as transRead2(inputvalue,z) */
#define TRANSREAD(x,y) { \
unsigned int inputvalue; \
- if ((inputvalue=(unsigned int)y)==0) x=NULL; \
+ if ((inputvalue=(unsigned int)y)==0) x=NULL; \
else { \
chashlistnode_t * cnodetmp=&c_table[(inputvalue&c_mask)>>1]; \
do { \
if (cnodetmp->key==inputvalue) {x=(void *)& ((objheader_t*)cnodetmp->val)[1]; break; } \
cnodetmp=cnodetmp->next; \
if (cnodetmp==NULL) {x=(void *)transRead2(inputvalue); asm volatile ("" : "=m" (c_table),"=m" (c_mask)); break; } \
- } while(1); \
- }}
+ } while(1); \
+ }}
__attribute__((pure)) objheader_t *transRead(unsigned int);
__attribute__((pure)) objheader_t *transRead2(unsigned int);
/* Read oid requested and search if available */
recv_data_buf((int)acceptfd, &readbuffer, &oid, sizeof(unsigned int));
while((srcObj = mhashSearch(oid)) == NULL) {
- int ret;
- if((ret = sched_yield()) != 0) {
- printf("%s(): error no %d in thread yield\n", __func__, errno);
- }
+ int ret;
+ if((ret = sched_yield()) != 0) {
+ printf("%s(): error no %d in thread yield\n", __func__, errno);
+ }
}
h = (objheader_t *) srcObj;
/* If object is write locked, just wait */
/* May want to remove at some point */
while((*(volatile int *)STATUSPTR(h))<=0)
- sched_yield();
+ sched_yield();
GETSIZE(size, h);
size += sizeof(objheader_t);
sockid = (int) acceptfd;
if (h == NULL) {
- ctrl = OBJECT_NOT_FOUND;
- send_data(sockid, &ctrl, sizeof(char));
+ ctrl = OBJECT_NOT_FOUND;
+ send_data(sockid, &ctrl, sizeof(char));
} else {
- // Type
- char msg[]={OBJECT_FOUND, 0, 0, 0, 0};
- *((int *)&msg[1])=size;
- send_data(sockid, &msg, sizeof(msg));
- send_data(sockid, h, size);
+ // Type
+ char msg[]={OBJECT_FOUND, 0, 0, 0, 0};
+ *((int *)&msg[1])=size;
+ send_data(sockid, &msg, sizeof(msg));
+ send_data(sockid, h, size);
}
break;
transinfo.numlocked = 0;
transinfo.numnotfound = 0;
if((val = readClientReq(&transinfo, (int)acceptfd, &readbuffer)) != 0) {
- printf("Error: In readClientReq() %s, %d\n", __FILE__, __LINE__);
- pthread_exit(NULL);
+ printf("Error: In readClientReq() %s, %d\n", __FILE__, __LINE__);
+ pthread_exit(NULL);
}
break;
case TRANS_PREFETCH:
#ifdef RANGEPREFETCH
if((val = rangePrefetchReq((int)acceptfd, &readbuffer)) != 0) {
- printf("Error: In rangePrefetchReq() %s, %d\n", __FILE__, __LINE__);
- break;
+ printf("Error: In rangePrefetchReq() %s, %d\n", __FILE__, __LINE__);
+ break;
}
#else
LOGTIME('X',0,0,myrdtsc(),0);
if((val = prefetchReq((int)acceptfd, &readbuffer)) != 0) {
- printf("Error: In prefetchReq() %s, %d\n", __FILE__, __LINE__);
- break;
+ printf("Error: In prefetchReq() %s, %d\n", __FILE__, __LINE__);
+ break;
}
#endif
break;
case TRANS_PREFETCH_RESPONSE:
#ifdef RANGEPREFETCH
if((val = getRangePrefetchResponse((int)acceptfd, &readbuffer)) != 0) {
- printf("Error: In getRangePrefetchRespose() %s, %d\n", __FILE__, __LINE__);
- break;
+ printf("Error: In getRangePrefetchRespose() %s, %d\n", __FILE__, __LINE__);
+ break;
}
#else
if((val = getPrefetchResponse((int) acceptfd, &readbuffer)) != 0) {
- printf("Error: In getPrefetchResponse() %s, %d\n", __FILE__, __LINE__);
- break;
+ printf("Error: In getPrefetchResponse() %s, %d\n", __FILE__, __LINE__);
+ break;
}
#endif
break;
recv_data_buf((int)acceptfd, &readbuffer, &numoid, sizeof(unsigned int));
size = (sizeof(unsigned int) + sizeof(unsigned short)) * numoid + 2 * sizeof(unsigned int);
if((buffer = calloc(1,size)) == NULL) {
- printf("%s() Calloc error at %s, %d\n", __func__, __FILE__, __LINE__);
- pthread_exit(NULL);
+ printf("%s() Calloc error at %s, %d\n", __func__, __FILE__, __LINE__);
+ pthread_exit(NULL);
}
recv_data_buf((int)acceptfd, &readbuffer, buffer, size);
case THREAD_NOTIFY_RESPONSE:
size = sizeof(unsigned short) + 2 * sizeof(unsigned int);
if((buffer = calloc(1,size)) == NULL) {
- printf("%s() Calloc error at %s, %d\n", __func__, __FILE__, __LINE__);
- pthread_exit(NULL);
+ printf("%s() Calloc error at %s, %d\n", __func__, __FILE__, __LINE__);
+ pthread_exit(NULL);
}
recv_data_buf((int)acceptfd, &readbuffer, buffer, size);
int useWriteUnlock = 0; //TODO verify is this piece of unlocking code ever used
for(i = 0; i< transinfo->numlocked; i++) {
if(transinfo->objlocked[i] == -1) {
- useWriteUnlock = 1;
- continue;
+ useWriteUnlock = 1;
+ continue;
}
if((header = mhashSearch(transinfo->objlocked[i])) == NULL) {
- printf("mhashSearch returns NULL at %s, %d\n", __FILE__, __LINE__); // find the header address
- return 1;
+ printf("mhashSearch returns NULL at %s, %d\n", __FILE__, __LINE__); // find the header address
+ return 1;
}
if(useWriteUnlock) {
- write_unlock(STATUSPTR(header));
+ write_unlock(STATUSPTR(header));
} else {
- read_unlock(STATUSPTR(header));
+ read_unlock(STATUSPTR(header));
}
}
break;
printf("Error: In transCommitProcess() %s, %d\n", __FILE__, __LINE__);
/* Free memory */
if (transinfo->objlocked != NULL) {
- free(transinfo->objlocked);
+ free(transinfo->objlocked);
}
if (transinfo->objnotfound != NULL) {
- free(transinfo->objnotfound);
+ free(transinfo->objnotfound);
}
return 1;
}
&v_matchnolock, &v_matchlock, &v_nomatch, &numBytes, &control, oid, version);
} else { //Objs modified
if(i == fixed->numread) {
- oidlocked[objlocked++] = -1;
+ oidlocked[objlocked++] = -1;
}
int tmpsize;
headptr = (objheader_t *) ptr;
if(retval==TRANS_DISAGREE || retval==TRANS_SOFT_ABORT) {
//unlock objects as soon versions mismatch or locks cannot be acquired)
if (objlocked > 0) {
- int useWriteUnlock = 0;
- for(j = 0; j < objlocked; j++) {
- if(oidlocked[j] == -1) {
- useWriteUnlock = 1;
- continue;
- }
- if((headptr = mhashSearch(oidlocked[j])) == NULL) {
- printf("mhashSearch returns NULL at %s, %d\n", __FILE__, __LINE__);
- return 0;
- }
- if(useWriteUnlock) {
- write_unlock(STATUSPTR(headptr));
- } else {
- read_unlock(STATUSPTR(headptr));
- }
- }
- if(v_nomatch > 0)
- free(oidlocked);
+ int useWriteUnlock = 0;
+ for(j = 0; j < objlocked; j++) {
+ if(oidlocked[j] == -1) {
+ useWriteUnlock = 1;
+ continue;
+ }
+ if((headptr = mhashSearch(oidlocked[j])) == NULL) {
+ printf("mhashSearch returns NULL at %s, %d\n", __FILE__, __LINE__);
+ return 0;
+ }
+ if(useWriteUnlock) {
+ write_unlock(STATUSPTR(headptr));
+ } else {
+ read_unlock(STATUSPTR(headptr));
+ }
+ }
+ if(v_nomatch > 0)
+ free(oidlocked);
}
objlocked=0;
break;
/* Check if Obj is locked by any previous transaction */
if (write_trylock(STATUSPTR(mobj))) { // Can acquire write lock
if (version == ((objheader_t *)mobj)->version) { /* match versions */
- (*v_matchnolock)++;
- *control = TRANS_AGREE;
+ (*v_matchnolock)++;
+ *control = TRANS_AGREE;
} else { /* If versions don't match ...HARD ABORT */
- (*v_nomatch)++;
- oidvernotmatch[*objvernotmatch] = oid;
- (*objvernotmatch)++;
- int size;
- GETSIZE(size, mobj);
- size += sizeof(objheader_t);
- *numBytes += size;
- /* Send TRANS_DISAGREE to Coordinator */
- *control = TRANS_DISAGREE;
+ (*v_nomatch)++;
+ oidvernotmatch[*objvernotmatch] = oid;
+ (*objvernotmatch)++;
+ int size;
+ GETSIZE(size, mobj);
+ size += sizeof(objheader_t);
+ *numBytes += size;
+ /* Send TRANS_DISAGREE to Coordinator */
+ *control = TRANS_DISAGREE;
}
//Keep track of oid locked
oidlocked[(*objlocked)++] = OID(((objheader_t *)mobj));
} else { //we are locked
if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
- (*v_matchlock)++;
- *control=TRANS_SOFT_ABORT;
+ (*v_matchlock)++;
+ *control=TRANS_SOFT_ABORT;
} else { /* If versions don't match ...HARD ABORT */
- (*v_nomatch)++;
- oidvernotmatch[*objvernotmatch] = oid;
- (*objvernotmatch)++;
- int size;
- GETSIZE(size, mobj);
- size += sizeof(objheader_t);
- *numBytes += size;
- *control = TRANS_DISAGREE;
+ (*v_nomatch)++;
+ oidvernotmatch[*objvernotmatch] = oid;
+ (*objvernotmatch)++;
+ int size;
+ GETSIZE(size, mobj);
+ size += sizeof(objheader_t);
+ *numBytes += size;
+ *control = TRANS_DISAGREE;
}
}
}
/* Check if Obj is locked by any previous transaction */
if (read_trylock(STATUSPTR(mobj))) { //Can further acquire read locks
if (version == ((objheader_t *)mobj)->version) { /* match versions */
- (*v_matchnolock)++;
- *control=TRANS_AGREE;
+ (*v_matchnolock)++;
+ *control=TRANS_AGREE;
} else { /* If versions don't match ...HARD ABORT */
- (*v_nomatch)++;
- oidvernotmatch[(*objvernotmatch)++] = oid;
- int size;
- GETSIZE(size, mobj);
- size += sizeof(objheader_t);
- *numBytes += size;
- /* Send TRANS_DISAGREE to Coordinator */
- *control = TRANS_DISAGREE;
+ (*v_nomatch)++;
+ oidvernotmatch[(*objvernotmatch)++] = oid;
+ int size;
+ GETSIZE(size, mobj);
+ size += sizeof(objheader_t);
+ *numBytes += size;
+ /* Send TRANS_DISAGREE to Coordinator */
+ *control = TRANS_DISAGREE;
}
//Keep track of oid locked
oidlocked[(*objlocked)++] = OID(((objheader_t *)mobj));
} else { /* Some other transaction has aquired a write lock on this object */
if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
- (*v_matchlock)++;
- *control=TRANS_SOFT_ABORT;
+ (*v_matchlock)++;
+ *control=TRANS_SOFT_ABORT;
} else { /* If versions don't match ...HARD ABORT */
- (*v_nomatch)++;
- oidvernotmatch[*objvernotmatch] = oid;
- (*objvernotmatch)++;
- int size;
- GETSIZE(size, mobj);
- size += sizeof(objheader_t);
- *numBytes += size;
- *control = TRANS_DISAGREE;
+ (*v_nomatch)++;
+ oidvernotmatch[*objvernotmatch] = oid;
+ (*objvernotmatch)++;
+ int size;
+ GETSIZE(size, mobj);
+ size += sizeof(objheader_t);
+ *numBytes += size;
+ *control = TRANS_DISAGREE;
}
}
}
oid = oidmid.oid;
if (mid != oidmid.mid) {
if (mid!=-1) {
- forcesend_buf(sd, &writebuffer, NULL, 0);
- freeSockWithLock(transPResponseSocketPool, mid, sd);
+ forcesend_buf(sd, &writebuffer, NULL, 0);
+ freeSockWithLock(transPResponseSocketPool, mid, sd);
}
mid=oidmid.mid;
sd = getSockWithLock(transPResponseSocketPool, mid);
/* Calculate the oid corresponding to the offset value */
for(i = 0; i< numoffset; i++) {
- /* Check for arrays */
- if(TYPE(header) >= NUMCLASSES) {
- int elementsize = classsize[TYPE(header)];
- struct ArrayObject *ao = (struct ArrayObject *) (((char *)header) + sizeof(objheader_t));
- unsigned short length = ao->___length___;
- /* Check if array out of bounds */
- if(offsetarry[i]< 0 || offsetarry[i] >= length) {
- break;
- }
- oid = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*offsetarry[i])));
- } else {
- oid = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + offsetarry[i]));
- }
-
- /* Don't continue if we hit a NULL pointer */
- if (oid==0)
- break;
-
- LOGTIME('B',oid,0,myrdtsc(),gid); //send next oid found from prefetch request
-
- if((header = mhashSearch(oid)) == NULL) {
- size = sizeof(int)+sizeof(int) + sizeof(char) + sizeof(unsigned int);
- char sendbuffer[size+1];
- sendbuffer[0]=TRANS_PREFETCH_RESPONSE;
- *((int *) (sendbuffer+1)) = size;
- *((char *)(sendbuffer + sizeof(char)+sizeof(int))) = OBJECT_NOT_FOUND;
- *((unsigned int *)(sendbuffer + sizeof(char)+sizeof(int) + sizeof(char))) = oid;
- *((int *)(sendbuffer+sizeof(int) + sizeof(char)+sizeof(char)+sizeof(unsigned int))) = gid;
-
- send_buf(sd, &writebuffer, sendbuffer, size+1);
- LOGTIME('J',oid, 0,myrdtsc(), gid); //send first oid not found prefetch request
- break;
- } else { /* Obj Found */
- int incr = 1;
- GETSIZE(objsize, header);
- size = sizeof(int)+sizeof(int) + sizeof(char) + sizeof(unsigned int) + sizeof(objheader_t) + objsize;
- char sendbuffer[size+1];
- sendbuffer[0]=TRANS_PREFETCH_RESPONSE;
- *((int *)(sendbuffer + incr)) = size;
- incr += sizeof(int);
- *((char *)(sendbuffer + incr)) = OBJECT_FOUND;
- incr += sizeof(char);
- *((unsigned int *)(sendbuffer+incr)) = oid;
- incr += sizeof(unsigned int);
- *((int *)(sendbuffer+incr)) = gid;
- incr += sizeof(int);
- memcpy(sendbuffer + incr, header, objsize + sizeof(objheader_t));
- send_buf(sd, &writebuffer, sendbuffer, size+1);
- LOGOIDTYPE("SRES", oid, TYPE(header), (myrdtsc()-clockoffset));
- LOGTIME('C',oid,TYPE(header),myrdtsc(), gid); //send first oid found from prefetch request
- }
+ /* Check for arrays */
+ if(TYPE(header) >= NUMCLASSES) {
+ int elementsize = classsize[TYPE(header)];
+ struct ArrayObject *ao = (struct ArrayObject *) (((char *)header) + sizeof(objheader_t));
+ unsigned short length = ao->___length___;
+ /* Check if array out of bounds */
+ if(offsetarry[i]< 0 || offsetarry[i] >= length) {
+ break;
+ }
+ oid = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + sizeof(struct ArrayObject) + (elementsize*offsetarry[i])));
+ } else {
+ oid = *((unsigned int *)(((char *)header) + sizeof(objheader_t) + offsetarry[i]));
+ }
+
+ /* Don't continue if we hit a NULL pointer */
+ if (oid==0)
+ break;
+
+ LOGTIME('B',oid,0,myrdtsc(),gid); //send next oid found from prefetch request
+
+ if((header = mhashSearch(oid)) == NULL) {
+ size = sizeof(int)+sizeof(int) + sizeof(char) + sizeof(unsigned int);
+ char sendbuffer[size+1];
+ sendbuffer[0]=TRANS_PREFETCH_RESPONSE;
+ *((int *) (sendbuffer+1)) = size;
+ *((char *)(sendbuffer + sizeof(char)+sizeof(int))) = OBJECT_NOT_FOUND;
+ *((unsigned int *)(sendbuffer + sizeof(char)+sizeof(int) + sizeof(char))) = oid;
+ *((int *)(sendbuffer+sizeof(int) + sizeof(char)+sizeof(char)+sizeof(unsigned int))) = gid;
+
+ send_buf(sd, &writebuffer, sendbuffer, size+1);
+ LOGTIME('J',oid, 0,myrdtsc(), gid); //send first oid not found prefetch request
+ break;
+ } else { /* Obj Found */
+ int incr = 1;
+ GETSIZE(objsize, header);
+ size = sizeof(int)+sizeof(int) + sizeof(char) + sizeof(unsigned int) + sizeof(objheader_t) + objsize;
+ char sendbuffer[size+1];
+ sendbuffer[0]=TRANS_PREFETCH_RESPONSE;
+ *((int *)(sendbuffer + incr)) = size;
+ incr += sizeof(int);
+ *((char *)(sendbuffer + incr)) = OBJECT_FOUND;
+ incr += sizeof(char);
+ *((unsigned int *)(sendbuffer+incr)) = oid;
+ incr += sizeof(unsigned int);
+ *((int *)(sendbuffer+incr)) = gid;
+ incr += sizeof(int);
+ memcpy(sendbuffer + incr, header, objsize + sizeof(objheader_t));
+ send_buf(sd, &writebuffer, sendbuffer, size+1);
+ LOGOIDTYPE("SRES", oid, TYPE(header), (myrdtsc()-clockoffset));
+ LOGTIME('C',oid,TYPE(header),myrdtsc(), gid); //send first oid found from prefetch request
+ }
} //end of for
}
} //end of while
/* Check to see if versions are same */
checkversion:
if (write_trylock(STATUSPTR(header))) { // Can acquire write lock
- newversion = header->version;
- if(newversion == *(versionarry + i)) {
- //Add to the notify list
- if((header->notifylist = insNode(header->notifylist, threadid, mid)) == NULL) {
- printf("Error: Obj notify list points to NULL %s, %d\n", __FILE__, __LINE__);
- return;
- }
- write_unlock(STATUSPTR(header));
- } else {
- write_unlock(STATUSPTR(header));
- if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
- perror("processReqNotify():socket()");
- return;
- }
- bzero(&remoteAddr, sizeof(remoteAddr));
- remoteAddr.sin_family = AF_INET;
- remoteAddr.sin_port = htons(LISTEN_PORT);
- remoteAddr.sin_addr.s_addr = htonl(mid);
-
- if (connect(sd, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) {
- printf("Error: processReqNotify():error %d connecting to %s:%d\n", errno,
- inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
- close(sd);
- return;
- } else {
-
- //Send Update notification
- msg[0] = THREAD_NOTIFY_RESPONSE;
- *((unsigned int *)&msg[1]) = oid;
- size = sizeof(unsigned int);
- *((unsigned short *)(&msg[1]+size)) = newversion;
- size += sizeof(unsigned short);
- *((unsigned int *)(&msg[1]+size)) = threadid;
- size = 1+ 2*sizeof(unsigned int) + sizeof(unsigned short);
- send_data(sd, msg, size);
- }
- close(sd);
- }
+ newversion = header->version;
+ if(newversion == *(versionarry + i)) {
+ //Add to the notify list
+ if((header->notifylist = insNode(header->notifylist, threadid, mid)) == NULL) {
+ printf("Error: Obj notify list points to NULL %s, %d\n", __FILE__, __LINE__);
+ return;
+ }
+ write_unlock(STATUSPTR(header));
+ } else {
+ write_unlock(STATUSPTR(header));
+ if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
+ perror("processReqNotify():socket()");
+ return;
+ }
+ bzero(&remoteAddr, sizeof(remoteAddr));
+ remoteAddr.sin_family = AF_INET;
+ remoteAddr.sin_port = htons(LISTEN_PORT);
+ remoteAddr.sin_addr.s_addr = htonl(mid);
+
+ if (connect(sd, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) {
+ printf("Error: processReqNotify():error %d connecting to %s:%d\n", errno,
+ inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
+ close(sd);
+ return;
+ } else {
+
+ //Send Update notification
+ msg[0] = THREAD_NOTIFY_RESPONSE;
+ *((unsigned int *)&msg[1]) = oid;
+ size = sizeof(unsigned int);
+ *((unsigned short *)(&msg[1]+size)) = newversion;
+ size += sizeof(unsigned short);
+ *((unsigned int *)(&msg[1]+size)) = threadid;
+ size = 1+ 2*sizeof(unsigned int) + sizeof(unsigned short);
+ send_data(sd, msg, size);
+ }
+ close(sd);
+ }
} else {
- randomdelay();
- goto checkversion;
+ randomdelay();
+ goto checkversion;
}
}
i++;
for(; next != NULL; curr=next, next = next->next) {
unsigned int val=(unsigned int)next->val;
if ((val>=tmpbegin)&(val<tmpend)) {
- prehashlistnode_t *tmp=curr->next=next->next;
- free(next);
- next=curr;
- //loop condition is broken now...need to check before incrementing
- // if (next==NULL)
- // break;
+ prehashlistnode_t *tmp=curr->next=next->next;
+ free(next);
+ next=curr;
+ //loop condition is broken now...need to check before incrementing
+ // if (next==NULL)
+ // break;
}
}
{
unsigned int val=(unsigned int)orig->val;
if ((val>=tmpbegin)&(val<tmpend)) {
- if (orig->next==NULL) {
- orig->key=0;
- orig->val=NULL;
- } else {
- next=orig->next;
- orig->val=next->val;
- orig->key=next->key;
- orig->next=next->next;
- free(next);
- }
+ if (orig->next==NULL) {
+ orig->key=0;
+ orig->val=NULL;
+ } else {
+ next=orig->next;
+ orig->val=next->val;
+ orig->key=next->key;
+ orig->next=next->next;
+ free(next);
+ }
}
}
lockindex++;
volatile unsigned int * lockptr_new=&pflookup.larray[lockindex].lock;
while(!write_trylock(lockptr_new)) {
- sched_yield();
+ sched_yield();
}
write_unlock(lockptr_current);
lockptr_current=lockptr_new;
if (curr->oid == oid) { // Find a match in the hash table
llookup.numelements--; // Decrement the number of elements in the global hashtable
if ((curr == &ptr[index]) && (curr->next == NULL)) { // Delete the first item inside the hashtable with no linked list of lhashlistnode_t
- curr->oid = 0;
- curr->mid = 0;
+ curr->oid = 0;
+ curr->mid = 0;
} else if ((curr == &ptr[index]) && (curr->next != NULL)) { //Delete the first item with a linked list of lhashlistnode_t connected
- curr->oid = curr->next->oid;
- curr->mid = curr->next->mid;
- node = curr->next;
- curr->next = curr->next->next;
- free(node);
+ curr->oid = curr->next->oid;
+ curr->mid = curr->next->mid;
+ node = curr->next;
+ curr->next = curr->next->next;
+ free(node);
} else { // Regular delete from linked listed
- prev->next = curr->next;
- free(curr);
+ prev->next = curr->next;
+ free(curr);
}
pthread_mutex_unlock(&llookup.locktable);
return 0;
isfirst = 1;
while (curr != NULL) { //Inner loop to go through linked lists
if (curr->oid == 0) { //Exit inner loop if there the first element for a given bin/index is NULL
- break; //oid = mid =0 for element if not present within the hash table
+ break; //oid = mid =0 for element if not present within the hash table
}
next = curr->next;
index = lhashFunction(curr->oid);
// Insert into the new table
if(llookup.table[index].next == NULL && llookup.table[index].oid == 0) {
- llookup.table[index].oid = curr->oid;
- llookup.table[index].mid = curr->mid;
- llookup.numelements++;
+ llookup.table[index].oid = curr->oid;
+ llookup.table[index].mid = curr->mid;
+ llookup.numelements++;
} else {
- if((newnode = calloc(1, sizeof(lhashlistnode_t))) == NULL) {
- printf("Calloc error %s, %d\n", __FILE__, __LINE__);
- return 1;
- }
- newnode->oid = curr->oid;
- newnode->mid = curr->mid;
- newnode->next = llookup.table[index].next;
- llookup.table[index].next = newnode;
- llookup.numelements++;
+ if((newnode = calloc(1, sizeof(lhashlistnode_t))) == NULL) {
+ printf("Calloc error %s, %d\n", __FILE__, __LINE__);
+ return 1;
+ }
+ newnode->oid = curr->oid;
+ newnode->mid = curr->mid;
+ newnode->next = llookup.table[index].next;
+ llookup.table[index].next = newnode;
+ llookup.numelements++;
}
//free the linked list of lhashlistnode_t if not the first element in the hash table
if (isfirst != 1) {
- free(curr);
+ free(curr);
}
isfirst = 0;
int matchstatus;
if ((*tmp)==NULL||((toid=(*tmp)->oid)>oid)) {
- objnode = (objpile_t *) malloc(sizeof(objpile_t));
- objnode->offset = offset;
- objnode->oid = oid;
- objnode->numoffset = numoffset;
- objnode->siteid = siteid;
- objnode->next = *tmp;
- *tmp = objnode;
- return;
+ objnode = (objpile_t *) malloc(sizeof(objpile_t));
+ objnode->offset = offset;
+ objnode->oid = oid;
+ objnode->numoffset = numoffset;
+ objnode->siteid = siteid;
+ objnode->next = *tmp;
+ *tmp = objnode;
+ return;
}
if (toid < oid)
- continue;
+ continue;
/* Fill objpiles DS */
int i;
short * ooffset=(*tmp)->offset;
for(i=0; i<numoffset; i++) {
- if (i>onumoffset) {
- //We've matched, let's just extend the current prefetch
- (*tmp)->numoffset=numoffset;
- (*tmp)->offset=offset;
- return;
- }
- if (ooffset[i]<offset[i]) {
- goto oidloop;
- } else if (ooffset[i]>offset[i]) {
- //Place item before the current one
- objnode = (objpile_t *) malloc(sizeof(objpile_t));
- objnode->offset = offset;
- objnode->oid = oid;
- objnode->numoffset = numoffset;
- objnode->siteid = siteid;
- objnode->next = *tmp;
- *tmp = objnode;
- return;
- }
+ if (i>onumoffset) {
+ //We've matched, let's just extend the current prefetch
+ (*tmp)->numoffset=numoffset;
+ (*tmp)->offset=offset;
+ return;
+ }
+ if (ooffset[i]<offset[i]) {
+ goto oidloop;
+ } else if (ooffset[i]>offset[i]) {
+ //Place item before the current one
+ objnode = (objpile_t *) malloc(sizeof(objpile_t));
+ objnode->offset = offset;
+ objnode->oid = oid;
+ objnode->numoffset = numoffset;
+ objnode->siteid = siteid;
+ objnode->next = *tmp;
+ *tmp = objnode;
+ return;
+ }
}
//if we get to the end, we're already covered by this prefetch
return;
if (curr->key == key) { // Find a match in the hash table
mlookup.numelements--; // Decrement the number of elements in the global hashtable
if ((curr == &ptr[index]) && (curr->next == NULL)) { // Delete the first item inside the hashtable with no linked list of mhashlistnode_t
- curr->key = 0;
- curr->val = NULL;
+ curr->key = 0;
+ curr->val = NULL;
} else if ((curr == &ptr[index]) && (curr->next != NULL)) { //Delete the first item with a linked list of mhashlistnode_t connected
- curr->key = curr->next->key;
- curr->val = curr->next->val;
- node = curr->next;
- curr->next = curr->next->next;
- free(node);
+ curr->key = curr->next->key;
+ curr->val = curr->next->val;
+ node = curr->next;
+ curr->next = curr->next->next;
+ free(node);
} else { // Regular delete from linked listed
- prev->next = curr->next;
- free(curr);
+ prev->next = curr->next;
+ free(curr);
}
pthread_mutex_unlock(&mlookup.locktable);
return 0;
mhashlistnode_t *tmp,*next;
if ((key=curr->key) == 0) { //Exit inner loop if there the first element for a given bin/index is NULL
- break; //key = val =0 for element if not present within the hash table
+ break; //key = val =0 for element if not present within the hash table
}
next = curr->next;
index = (key & mask) >>1;
// Insert into the new table
if(tmp->key ==0) {
- tmp->key=curr->key;
- tmp->val=curr->val;
- if (!isfirst)
- free(curr);
+ tmp->key=curr->key;
+ tmp->val=curr->val;
+ if (!isfirst)
+ free(curr);
} /*
- NOTE: Add this case if you change this...
- This case currently never happens because of the way things rehash....
- else if (isfirst) {
- mhashlistnode_t *newnode = calloc(1, sizeof(mhashlistnode_t));
- newnode->key = curr->key;
- newnode->val = curr->val;
- newnode->next = tmp->next;
- tmp->next=newnode;
- } */
+ NOTE: Add this case if you change this...
+ This case currently never happens because of the way things rehash....
+ else if (isfirst) {
+ mhashlistnode_t *newnode = calloc(1, sizeof(mhashlistnode_t));
+ newnode->key = curr->key;
+ newnode->val = curr->val;
+ newnode->next = tmp->next;
+ tmp->next=newnode;
+ } */
else {
- curr->next=tmp->next;
- tmp->next=curr;
+ curr->next=tmp->next;
+ tmp->next=curr;
}
isfirst = 0;
curr = next;
if (mlookup.table[i].key != 0) {
curr = &mlookup.table[i];
while (curr != NULL) {
- keys[keyindex++] = curr->key;
- curr = curr->next;
+ keys[keyindex++] = curr->key;
+ curr = curr->next;
}
}
}
/* Send Prefetch Request */
perMcPrefetchList_t *ptr = pilehead;
while(ptr != NULL) {
- // Get sock from shared pool
- int sd = getSock2(transPrefetchSockPool, ptr->mid);
- sendRangePrefetchReq(ptr, sd, myIpAddr);
- ptr = ptr->next;
+ // Get sock from shared pool
+ int sd = getSock2(transPrefetchSockPool, ptr->mid);
+ sendRangePrefetchReq(ptr, sd, myIpAddr);
+ ptr = ptr->next;
}
/* Deallocated pilehead */
LOGTIME('b',oid,0,0,countInvalidObj);
//forward prefetch
if(oid!=0) {
- int machinenum = lhashSearch(oid);
- if(machinenum != myIpAddr) {
- insertPrefetch(machinenum, oid, numoffset, offsetarray, &head);
- }
+ int machinenum = lhashSearch(oid);
+ if(machinenum != myIpAddr) {
+ insertPrefetch(machinenum, oid, numoffset, offsetarray, &head);
+ }
}
//update ptr
ptr=((char *)&offsetarray[numoffset])+sizeof(int);
//Start searching the dfsList
for(top=0; top>=0; ) {
if(top == offstop) {
- isLastOffset=1;
+ isLastOffset=1;
}
oid=getNextOid(header, offsetarray, dfsList, top, &countInvalidObj, &isLastOffset);
LOGTIME('O',oid,0,0,countInvalidObj);
if (oid&1) {
- int oldisField=TYPE(header) < NUMCLASSES;
- top+=2;
- dfsList[top]=oid;
- dfsList[top+1]=0;
- header=searchObjInv(oid, top, &countInvalidObj, &isLastOffset);
- if (header==NULL) {
- LOGTIME('c',oid,top,0,countInvalidObj);
- //forward prefetch
- int machinenum = lhashSearch(oid);
- if(machinenum != myIpAddr) {
- if (oldisField&&(dfsList[top-1]!=GET_RANGE(offsetarray[top+1]))) {
- insertPrefetch(machinenum, oid, 2+numoffset-top, &offsetarray[top-2], &head);
- } else {
- insertPrefetch(machinenum, oid, numoffset-top, &offsetarray[top], &head);
- }
- }
- } else if (top<offstop) {
- LOGTIME('C',oid,TYPE(header),0,top);
- //okay to continue going down
- continue;
- }
+ int oldisField=TYPE(header) < NUMCLASSES;
+ top+=2;
+ dfsList[top]=oid;
+ dfsList[top+1]=0;
+ header=searchObjInv(oid, top, &countInvalidObj, &isLastOffset);
+ if (header==NULL) {
+ LOGTIME('c',oid,top,0,countInvalidObj);
+ //forward prefetch
+ int machinenum = lhashSearch(oid);
+ if(machinenum != myIpAddr) {
+ if (oldisField&&(dfsList[top-1]!=GET_RANGE(offsetarray[top+1]))) {
+ insertPrefetch(machinenum, oid, 2+numoffset-top, &offsetarray[top-2], &head);
+ } else {
+ insertPrefetch(machinenum, oid, numoffset-top, &offsetarray[top], &head);
+ }
+ }
+ } else if (top<offstop) {
+ LOGTIME('C',oid,TYPE(header),0,top);
+ //okay to continue going down
+ continue;
+ }
} else if (oid==2) {
- LOGTIME('D',oid,0,0,top);
- //send prefetch first
- int objindex=top+2;
- int machinenum = lhashSearch(dfsList[objindex]);
- if(machinenum != myIpAddr) {
- insertPrefetch(machinenum, dfsList[objindex], numoffset-top, &offsetarray[top], &head);
- }
+ LOGTIME('D',oid,0,0,top);
+ //send prefetch first
+ int objindex=top+2;
+ int machinenum = lhashSearch(dfsList[objindex]);
+ if(machinenum != myIpAddr) {
+ insertPrefetch(machinenum, dfsList[objindex], numoffset-top, &offsetarray[top], &head);
+ }
}
//oid is 0
//go backwards until we can increment
do {
- do {
- top-=2;
- if (top<0) {
- goto tuple;
- //return head;
- }
- } while(dfsList[top+1] == GET_RANGE(offsetarray[top + 3]));
-
- //we backtracked past the invalid obj...set out countInvalidObj=-1
- if (top<countInvalidObj)
- countInvalidObj=-1;
-
- header=searchObjInv(dfsList[top], top, &countInvalidObj, NULL);
- //header shouldn't be null unless the object moves away, but allow
- //ourselves the option to just continue on if we lose the object
+ do {
+ top-=2;
+ if (top<0) {
+ goto tuple;
+ //return head;
+ }
+ } while(dfsList[top+1] == GET_RANGE(offsetarray[top + 3]));
+
+ //we backtracked past the invalid obj...set out countInvalidObj=-1
+ if (top<countInvalidObj)
+ countInvalidObj=-1;
+
+ header=searchObjInv(dfsList[top], top, &countInvalidObj, NULL);
+ //header shouldn't be null unless the object moves away, but allow
+ //ourselves the option to just continue on if we lose the object
} while(header==NULL);
LOGTIME('F',OID(header),TYPE(header),0,top);
//increment
dfsList[top+1]=0;
header=searchObj(oid);
if (header==NULL) {
- LOGTIME('h',oid,top,0,0);
- //forward prefetch
- /*
- int machinenum = lhashSearch(oid);
- if (oldisField&&(dfsList[top-1]!=GET_RANGE(offsetarray[top+1]))) {
- insertPrefetch(machinenum, oid, 2+numoffset-top, &offsetarray[top-2], &head);
- } else {
- insertPrefetch(machinenum, oid, numoffset-top, &offsetarray[top], &head);
- }
- */
+ LOGTIME('h',oid,top,0,0);
+ //forward prefetch
+ /*
+ int machinenum = lhashSearch(oid);
+ if (oldisField&&(dfsList[top-1]!=GET_RANGE(offsetarray[top+1]))) {
+ insertPrefetch(machinenum, oid, 2+numoffset-top, &offsetarray[top-2], &head);
+ } else {
+ insertPrefetch(machinenum, oid, numoffset-top, &offsetarray[top], &head);
+ }
+ */
} else {
- sendOidFound(header, oid, sd,writebuffer);
- LOGTIME('H',oid,TYPE(header),0,top);
- if (top<offstop)
- //okay to continue going down
- continue;
+ sendOidFound(header, oid, sd,writebuffer);
+ LOGTIME('H',oid,TYPE(header),0,top);
+ if (top<offstop)
+ //okay to continue going down
+ continue;
}
} else if (oid==2) {
LOGTIME('I',oid,top,0,0);
//go backwards until we can increment
do {
do {
- top-=2;
- if (top<0) {
- flushResponses(sd, writebuffer);
- return head;
- }
+ top-=2;
+ if (top<0) {
+ flushResponses(sd, writebuffer);
+ return head;
+ }
} while(dfsList[top+1] == GET_RANGE(offsetarray[top + 3]));
header=searchObj(dfsList[top]);
header = prehashSearch(oid);
if(header != NULL) {
if((STATUS(header) & DIRTY) && (countInvalidObj!= NULL)) {
- if ((*countInvalidObj)==-1) {
- *countInvalidObj=top;
- } else {
- return NULL;
- }
+ if ((*countInvalidObj)==-1) {
+ *countInvalidObj=top;
+ } else {
+ return NULL;
+ }
}
if((STATUS(header) & DIRTY) && isLastOffset)
- return NULL;
+ return NULL;
}
return header;
}
int matchstatus;
if ((*tmp)==NULL||((toid=(*tmp)->oid)>oid)) {
- objnode = (objOffsetPile_t *) malloc(sizeof(objOffsetPile_t));
- objnode->offsets = offsets;
- objnode->oid = oid;
- objnode->numoffset = numoffset;
- objnode->next = *tmp;
- *tmp = objnode;
- return;
+ objnode = (objOffsetPile_t *) malloc(sizeof(objOffsetPile_t));
+ objnode->offsets = offsets;
+ objnode->oid = oid;
+ objnode->numoffset = numoffset;
+ objnode->next = *tmp;
+ *tmp = objnode;
+ return;
}
if (toid < oid)
- continue;
+ continue;
/* Fill list DS */
int i;
short * ooffset=(*tmp)->offsets;
for(i=0; i<numoffset; i++) {
- if (i>onumoffset) {
- //We've matched, let's just extend the current prefetch
- (*tmp)->numoffset=numoffset;
- (*tmp)->offsets=offsets;
- return;
- }
- if (ooffset[i]<offsets[i]) {
- goto oidloop;
- } else if (ooffset[i]>offsets[i]) {
- //Place item before the current one
- objnode = (objOffsetPile_t *) malloc(sizeof(objOffsetPile_t));
- objnode->offsets = offsets;
- objnode->oid = oid;
- objnode->numoffset = numoffset;
- objnode->next = *tmp;
- *tmp = objnode;
- return;
- }
+ if (i>onumoffset) {
+ //We've matched, let's just extend the current prefetch
+ (*tmp)->numoffset=numoffset;
+ (*tmp)->offsets=offsets;
+ return;
+ }
+ if (ooffset[i]<offsets[i]) {
+ goto oidloop;
+ } else if (ooffset[i]>offsets[i]) {
+ //Place item before the current one
+ objnode = (objOffsetPile_t *) malloc(sizeof(objOffsetPile_t));
+ objnode->offsets = offsets;
+ objnode->oid = oid;
+ objnode->numoffset = numoffset;
+ objnode->next = *tmp;
+ *tmp = objnode;
+ return;
+ }
}
//if we get to the end, we're already covered by this prefetch
return;
/* Insert into prefetch hash lookup table */
void * oldptr;
if((oldptr = prehashSearch(oid)) != NULL) {
- if(((objheader_t *)oldptr)->version < ((objheader_t *)ptr)->version) {
- prehashInsert(oid, ptr);
- }
+ if(((objheader_t *)oldptr)->version < ((objheader_t *)ptr)->version) {
+ prehashInsert(oid, ptr);
+ }
} else {
- prehashInsert(oid, ptr);
+ prehashInsert(oid, ptr);
}
ptr=(void *)(((unsigned int)ptr)+objsize);
size-=objsize;
baseoid = oidmid.oid;
if(mid != oidmid.mid) {
if(mid!= -1) {
- forcesend_buf(sd, &writebuffer, NULL, 0);
- freeSockWithLock(transPResponseSocketPool, mid, sd);
+ forcesend_buf(sd, &writebuffer, NULL, 0);
+ freeSockWithLock(transPResponseSocketPool, mid, sd);
}
mid = oidmid.mid;
sd = getSockWithLock(transPResponseSocketPool, mid);
if (pilehead!= NULL) {
perMcPrefetchList_t *ptr = pilehead;
while(ptr != NULL) {
- // Get sock from shared pool
- int sd = getSock2(transPrefetchSockPool, ptr->mid);
- sendRangePrefetchReq(ptr, sd, mid);
- ptr = ptr->next;
+ // Get sock from shared pool
+ int sd = getSock2(transPrefetchSockPool, ptr->mid);
+ sendRangePrefetchReq(ptr, sd, mid);
+ ptr = ptr->next;
}
proPrefetchQDealloc(pilehead);
//Negative
currindex=startindex-stride*currcount;
if (currindex<0)
- return 0;
+ return 0;
//Also have to check whether we will eventually index into array
if (currindex>=length) {
- //Skip to the point that we will index into array
- int delta=(currindex-length-1)/stride+1; //-1, +1 is to make sure that it rounds up
- if ((delta+currcount)>range)
- return 0;
- currindex-=delta*stride;
+ //Skip to the point that we will index into array
+ int delta=(currindex-length-1)/stride+1; //-1, +1 is to make sure that it rounds up
+ if ((delta+currcount)>range)
+ return 0;
+ currindex-=delta*stride;
}
} else {
//Going positive, compute current index
currindex=startindex+stride*currcount;
if(currindex >= length)
- return 0;
+ return 0;
}
int elementsize = classsize[TYPE(header)];
//go to the next offset
header=searchObjInv(dfsList[top+2], top, countInvalidObj, isLastOffset);
if (header==NULL)
- return 2;
+ return 2;
}
return *((unsigned int *)(((char *)header) + sizeof(objheader_t) + startindex));
tmp = ptr;
while(tmp != NULL) {
if(tmp->key == key) {
- isFound=1;
- tmp->val = val; //Replace value for an exsisting key
- pthread_mutex_unlock(&pflookup.lock);
- return;
+ isFound=1;
+ tmp->val = val; //Replace value for an exsisting key
+ pthread_mutex_unlock(&pflookup.lock);
+ return;
}
tmp=tmp->next;
}
if (curr->key == key) { // Find a match in the hash table
pflookup.numelements--; // Decrement the number of elements in the global hashtable
if ((curr == &ptr[index]) && (curr->next == NULL)) { // Delete the first item inside the hashtable with no linked list of prehashlistnode_t
- curr->key = 0;
- curr->val = NULL;
+ curr->key = 0;
+ curr->val = NULL;
} else if ((curr == &ptr[index]) && (curr->next != NULL)) { //Delete the first item with a linked list of prehashlistnode_t connected
- curr->key = curr->next->key;
- curr->val = curr->next->val;
- node = curr->next;
- curr->next = curr->next->next;
- free(node);
+ curr->key = curr->next->key;
+ curr->val = curr->next->val;
+ node = curr->next;
+ curr->next = curr->next->next;
+ free(node);
} else { // Regular delete from linked listed
- prev->next = curr->next;
- free(curr);
+ prev->next = curr->next;
+ free(curr);
}
pthread_mutex_unlock(&pflookup.lock);
return 0;
do {
unsigned int key;
if ((key=curr->key) == 0) { //Exit inner loop if there the first element for a given bin/index is NULL
- break; //key = val =0 for element if not present within the hash table
+ break; //key = val =0 for element if not present within the hash table
}
next = curr->next;
index = (key & mask)>>1;
tmp=&pflookup.table[index];
// Insert into the new table
if(tmp->key==0) {
- tmp->key=curr->key;
- tmp->val=curr->val;
- if (!isfirst)
- free(curr);
+ tmp->key=curr->key;
+ tmp->val=curr->val;
+ if (!isfirst)
+ free(curr);
} /*
- NOTE: Add this case if you change this...
- This case currently never happens because of the way things rehash....
- else if (isfirst) {
- prehashlistnode_t * newnode = calloc(1, sizeof(prehashlistnode_t));
- newnode->key = curr->key;
- newnode->val = curr->val;
- newnode->next = tmp->next;
- tmp->next=newnode;
- } */
+ NOTE: Add this case if you change this...
+ This case currently never happens because of the way things rehash....
+ else if (isfirst) {
+ prehashlistnode_t * newnode = calloc(1, sizeof(prehashlistnode_t));
+ newnode->key = curr->key;
+ newnode->val = curr->val;
+ newnode->next = tmp->next;
+ tmp->next=newnode;
+ } */
else {
- curr->next=tmp->next;
- tmp->next=curr;
+ curr->next=tmp->next;
+ tmp->next=curr;
}
isfirst = 0;
/* Inner loop to traverse the linked list of the cache lookupTable */
while(curr != NULL) {
if (curr->key == 0)
- break;
+ break;
objheader_t *headeraddr=(objheader_t*) curr->val;
unsigned int machinenum;
objheader_t *tmp;
if (STATUS(headeraddr) & NEW) {
- //new objects cannot be stale
+ //new objects cannot be stale
} else if ((tmp=mhashSearch(curr->key)) != NULL) {
- //memory barrier
- CFENCE;
- if (tmp->version!=headeraddr->version) {
- //version mismatch
- deletehead(head);
- return 1; //return 1 when objects are inconsistent
- }
+ //memory barrier
+ CFENCE;
+ if (tmp->version!=headeraddr->version) {
+ //version mismatch
+ deletehead(head);
+ return 1; //return 1 when objects are inconsistent
+ }
} else {
- machinenum = lhashSearch(curr->key);
- head = createList(head, headeraddr, machinenum, c_numelements);
+ machinenum = lhashSearch(curr->key);
+ head = createList(head, headeraddr, machinenum, c_numelements);
}
curr = curr->next;
while(tmp != NULL) {
if(tmp->mid == mid) {
if (STATUS(headeraddr) & DIRTY) {
- offset = (sizeof(unsigned int) + sizeof(short)) * tmp->nummod;
- *((unsigned int *)(((char *)tmp->objmod) + offset))=OID(headeraddr);
- offset += sizeof(unsigned int);
- *((unsigned short *)(((char *)tmp->objmod) + offset)) = headeraddr->version;
- tmp->nummod++;
+ offset = (sizeof(unsigned int) + sizeof(short)) * tmp->nummod;
+ *((unsigned int *)(((char *)tmp->objmod) + offset))=OID(headeraddr);
+ offset += sizeof(unsigned int);
+ *((unsigned short *)(((char *)tmp->objmod) + offset)) = headeraddr->version;
+ tmp->nummod++;
} else {
- offset = (sizeof(unsigned int) + sizeof(short)) * tmp->numread;
- *((unsigned int *)(((char *)tmp->objread) + offset))=OID(headeraddr);
- offset += sizeof(unsigned int);
- *((unsigned short *)(((char *)tmp->objread) + offset)) = headeraddr->version;
- tmp->numread++;
+ offset = (sizeof(unsigned int) + sizeof(short)) * tmp->numread;
+ *((unsigned int *)(((char *)tmp->objread) + offset))=OID(headeraddr);
+ offset += sizeof(unsigned int);
+ *((unsigned short *)(((char *)tmp->objread) + offset)) = headeraddr->version;
+ tmp->numread++;
}
found = 1;
break;
recv_data(sd, &control, sizeof(char));
getReplyCtrl[i] = control;
if(control == OBJ_INCONSISTENT) { /* Inconsistent */
- checkObj = 1;
- break;
+ checkObj = 1;
+ break;
}
countConsistent++;
}
return;
} else {
if(is_write_locked(STATUSPTR(header))) { //object write locked
- control = OBJ_INCONSISTENT;
- send_data(sd, &control, sizeof(char));
- return;
+ control = OBJ_INCONSISTENT;
+ send_data(sd, &control, sizeof(char));
+ return;
}
CFENCE;
//compare versions
if(version == header->version)
- v_match++;
+ v_match++;
else {
- control = OBJ_INCONSISTENT;
- send_data(sd, &control, sizeof(char));
- return;
+ control = OBJ_INCONSISTENT;
+ send_data(sd, &control, sizeof(char));
+ return;
}
}
} // end of objects read
return;
} else {
if(is_write_locked(STATUSPTR(header))) { //object write locked
- control = OBJ_INCONSISTENT;
- send_data(sd, &control, sizeof(char));
- return;
+ control = OBJ_INCONSISTENT;
+ send_data(sd, &control, sizeof(char));
+ return;
}
//compare versions
if(version == header->version)
- v_match++;
+ v_match++;
else {
- control = OBJ_INCONSISTENT;
- send_data(sd, &control, sizeof(char));
- return;
+ control = OBJ_INCONSISTENT;
+ send_data(sd, &control, sizeof(char));
+ return;
}
}
} // end of objects modified
int oldval;
/* Note: the "xchg" instruction does not need a "lock" prefix */
__asm__ __volatile__ ("xchgl %0, %1"
- : "=r" (oldval), "=m" (*(addr))
- : "0" (1), "m" (*(addr)));
+ : "=r" (oldval), "=m" (*(addr))
+ : "0" (1), "m" (*(addr)));
return oldval;
}
inline void UnLock(volatile unsigned int *addr) {
int oldval;
/* Note: the "xchg" instruction does not need a "lock" prefix */
__asm__ __volatile__ ("xchgl %0, %1"
- : "=r" (oldval), "=m" (*(addr))
- : "0" (0), "m" (*(addr)));
+ : "=r" (oldval), "=m" (*(addr))
+ : "0" (0), "m" (*(addr)));
}
#elif
# error need implementation of test_and_set
int i=0;
while(*s) {
if (i++>MAXSPINS) {
- sched_yield();
- i=0;
+ sched_yield();
+ i=0;
}
}
}
if (sockpool[i].mid == mid) {
int j;
for (j = 0; j < MAX_CONN_PER_MACHINE; j++) {
- if (sockpool[i].sd[j] != -1 && (sockpool[i].inuse[j] == 0)) {
- sockpool[i].inuse[j] = 1;
- return sockpool[i].sd[j];
- }
- if (sockpool[i].sd[j] == -1) {
- //Open Connection
- int sd;
- if((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
- printf("%s() Error: In creating socket at %s, %d\n", __func__, __FILE__, __LINE__);
- return -1;
- }
- struct sockaddr_in remoteAddr;
- bzero(&remoteAddr, sizeof(remoteAddr));
- remoteAddr.sin_family = AF_INET;
- remoteAddr.sin_port = htons(LISTEN_PORT);
- remoteAddr.sin_addr.s_addr = htonl(mid);
-
- if(connect(sd, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) {
- printf("%s(): Error %d connecting to %s:%d\n", __func__, errno, inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
- close(sd);
- return -1;
- }
- sockpool[i].sd[j] = sd;
- sockpool[i].inuse[j] = 1;
- return sockpool[i].sd[j];
- }
+ if (sockpool[i].sd[j] != -1 && (sockpool[i].inuse[j] == 0)) {
+ sockpool[i].inuse[j] = 1;
+ return sockpool[i].sd[j];
+ }
+ if (sockpool[i].sd[j] == -1) {
+ //Open Connection
+ int sd;
+ if((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
+ printf("%s() Error: In creating socket at %s, %d\n", __func__, __FILE__, __LINE__);
+ return -1;
+ }
+ struct sockaddr_in remoteAddr;
+ bzero(&remoteAddr, sizeof(remoteAddr));
+ remoteAddr.sin_family = AF_INET;
+ remoteAddr.sin_port = htons(LISTEN_PORT);
+ remoteAddr.sin_addr.s_addr = htonl(mid);
+
+ if(connect(sd, (struct sockaddr *)&remoteAddr, sizeof(remoteAddr)) < 0) {
+ printf("%s(): Error %d connecting to %s:%d\n", __func__, errno, inet_ntoa(remoteAddr.sin_addr), LISTEN_PORT);
+ close(sd);
+ return -1;
+ }
+ sockpool[i].sd[j] = sd;
+ sockpool[i].inuse[j] = 1;
+ return sockpool[i].sd[j];
+ }
}
printf("%s()->Error: Less number of MAX_CONN_PER_MACHINE\n", __func__);
return -1;
int j;
for (j = 0; j < MAX_CONN_PER_MACHINE; j++) {
if (sockpool[i].sd[j] == sd) {
- sockpool[i].inuse[j] = 0;
- return 0;
+ sockpool[i].inuse[j] = 0;
+ return 0;
}
}
}
tmp = &ptr[index];
while(tmp != NULL) {
if(tmp->threadid == tid) {
- isFound = 1;
- tmp->ndata = ndata;
- pthread_mutex_unlock(&nlookup.locktable);
- return 0;
+ isFound = 1;
+ tmp->ndata = ndata;
+ pthread_mutex_unlock(&nlookup.locktable);
+ return 0;
}
tmp = tmp->next;
}
if(!isFound) {
if ((node = calloc(1, sizeof(notifylistnode_t))) == NULL) {
- printf("Calloc error %s, %d\n", __FILE__, __LINE__);
- pthread_mutex_unlock(&nlookup.locktable);
- return 1;
+ printf("Calloc error %s, %d\n", __FILE__, __LINE__);
+ pthread_mutex_unlock(&nlookup.locktable);
+ return 1;
}
node->threadid = tid;
node->ndata = ndata;
if (curr->threadid == tid) { // Find a match in the hash table
nlookup.numelements--; // Decrement the number of elements in the global hashtable
if ((curr == &ptr[index]) && (curr->next == NULL)) { // Delete the first item inside the hashtable with no linked list of notifylistnode_t
- curr->threadid = 0;
- curr->ndata = NULL;
+ curr->threadid = 0;
+ curr->ndata = NULL;
} else if ((curr == &ptr[index]) && (curr->next != NULL)) { //Delete the first bin item with a linked list of notifylistnode_t connected
- curr->threadid = curr->next->threadid;
- curr->ndata = curr->next->ndata;
- node = curr->next;
- curr->next = curr->next->next;
- free(node);
+ curr->threadid = curr->next->threadid;
+ curr->ndata = curr->next->ndata;
+ node = curr->next;
+ curr->next = curr->next->next;
+ free(node);
} else { // Regular delete from linked listed
- prev->next = curr->next;
- free(curr);
+ prev->next = curr->next;
+ free(curr);
}
pthread_mutex_unlock(&nlookup.locktable);
return 0;
isfirst = 1;
while (curr != NULL) { //Inner loop to go through linked lists
if (curr->threadid == 0) { //Exit inner loop if there the first element for a given bin/index is NULL
- break; //threadid = threadcond =0 for element if not present within the hash table
+ break; //threadid = threadcond =0 for element if not present within the hash table
}
next = curr->next;
index = notifyhashFunction(curr->threadid);
#endif
// Insert into the new table
if(nlookup.table[index].next == NULL && nlookup.table[index].threadid == 0) {
- nlookup.table[index].threadid = curr->threadid;
- nlookup.table[index].ndata = curr->ndata;
- nlookup.numelements++;
+ nlookup.table[index].threadid = curr->threadid;
+ nlookup.table[index].ndata = curr->ndata;
+ nlookup.numelements++;
} else {
- if((newnode = calloc(1, sizeof(notifylistnode_t))) == NULL) {
- printf("Calloc error %s, %d\n", __FILE__, __LINE__);
- return 1;
- }
- newnode->threadid = curr->threadid;
- newnode->ndata = curr->ndata;
- newnode->next = nlookup.table[index].next;
- nlookup.table[index].next = newnode;
- nlookup.numelements++;
+ if((newnode = calloc(1, sizeof(notifylistnode_t))) == NULL) {
+ printf("Calloc error %s, %d\n", __FILE__, __LINE__);
+ return 1;
+ }
+ newnode->threadid = curr->threadid;
+ newnode->ndata = curr->ndata;
+ newnode->next = nlookup.table[index].next;
+ nlookup.table[index].next = newnode;
+ nlookup.numelements++;
}
//free the linked list of notifylistnode_t if not the first element in the hash table
if (isfirst != 1) {
- free(curr);
+ free(curr);
}
isfirst = 0;
int top=endoffsets[ntuples-1];
if (node==NULL) {
- LOGEVENT('D');
- return;
+ LOGEVENT('D');
+ return;
}
/* Set queue node values */
node=gettail();
prefetchpile_t *pilehead = foundLocal(node,numpref,siteid);
if (pilehead!=NULL) {
- // Get sock from shared pool
-
- /* Send Prefetch Request */
- prefetchpile_t *ptr = pilehead;
- while(ptr != NULL) {
- globalid++;
- int sd = getSock2(transPrefetchSockPool, ptr->mid);
- sendPrefetchReq(ptr, sd, globalid);
- ptr = ptr->next;
- }
-
- mcdealloc(pilehead);
+ // Get sock from shared pool
+
+ /* Send Prefetch Request */
+ prefetchpile_t *ptr = pilehead;
+ while(ptr != NULL) {
+ globalid++;
+ int sd = getSock2(transPrefetchSockPool, ptr->mid);
+ sendPrefetchReq(ptr, sd, globalid);
+ ptr = ptr->next;
+ }
+
+ mcdealloc(pilehead);
}
resetqueue();
} //end do prefetch if condition
if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) {
if(STATUS(tmp) & DIRTY) {
#ifdef TRANSSTATS
- ndirtyCacheObj++;
+ ndirtyCacheObj++;
#endif
- goto remoteread;
+ goto remoteread;
}
#ifdef TRANSSTATS
nprehashSearch++;
int size;
GETSIZE(size, objcopy);
if((headerObj = prefetchobjstrAlloc(size + sizeof(objheader_t))) == NULL) {
- printf("%s(): Error in getting memory from prefetch cache at %s, %d\n", __func__,
- __FILE__, __LINE__);
- pthread_mutex_unlock(&prefetchcache_mutex);
- return NULL;
+ printf("%s(): Error in getting memory from prefetch cache at %s, %d\n", __func__,
+ __FILE__, __LINE__);
+ pthread_mutex_unlock(&prefetchcache_mutex);
+ return NULL;
}
pthread_mutex_unlock(&prefetchcache_mutex);
memcpy(headerObj, objcopy, size+sizeof(objheader_t));
if((tmp = (objheader_t *) prehashSearch(oid)) != NULL) {
if(STATUS(tmp) & DIRTY) {
#ifdef TRANSSTATS
- ndirtyCacheObj++;
+ ndirtyCacheObj++;
#endif
- goto remoteread;
+ goto remoteread;
}
#ifdef TRANSSTATS
LOGEVENT('P')
int size;
GETSIZE(size, objcopy);
if((headerObj = prefetchobjstrAlloc(size+sizeof(objheader_t))) == NULL) {
- printf("%s(): Error in getting memory from prefetch cache at %s, %d\n", __func__,
- __FILE__, __LINE__);
- pthread_mutex_unlock(&prefetchcache_mutex);
- return NULL;
+ printf("%s(): Error in getting memory from prefetch cache at %s, %d\n", __func__,
+ __FILE__, __LINE__);
+ pthread_mutex_unlock(&prefetchcache_mutex);
+ return NULL;
}
pthread_mutex_unlock(&prefetchcache_mutex);
memcpy(headerObj, objcopy, size+sizeof(objheader_t));
while(curr != NULL) {
//if the first bin in hash table is empty
if(curr->key == 0)
- break;
+ break;
headeraddr=(objheader_t *) curr->val;
//Get machine location for object id (and whether local or not)
if (STATUS(headeraddr) & NEW || (mhashSearch(curr->key) != NULL)) {
- machinenum = myIpAddr;
+ machinenum = myIpAddr;
} else if ((machinenum = lhashSearch(curr->key)) == 0) {
- printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
- return NULL;
+ printf("Error: No such machine %s, %d\n", __FILE__, __LINE__);
+ return NULL;
}
//Make machine groups
tosend[sockindex].oidcreated = pile->oidcreated;
int sd = 0;
if(pile->mid != myIpAddr) {
- if((sd = getSock2WithLock(transRequestSockPool, pile->mid)) < 0) {
- printf("transRequest(): socket create error\n");
- free(listmid);
- free(tosend);
- return 1;
- }
- socklist[sockindex] = sd;
- /* Send bytes of data with TRANS_REQUEST control message */
- send_buf(sd, &writebuffer, &(tosend[sockindex].f), sizeof(fixed_data_t));
-
- /* Send list of machines involved in the transaction */
- {
- int size=sizeof(unsigned int)*(tosend[sockindex].f.mcount);
- send_buf(sd, &writebuffer, tosend[sockindex].listmid, size);
- }
-
- /* Send oids and version number tuples for objects that are read */
- {
- int size=(sizeof(unsigned int)+sizeof(unsigned short))*(tosend[sockindex].f.numread);
- send_buf(sd, &writebuffer, tosend[sockindex].objread, size);
- }
-
- /* Send objects that are modified */
- void *modptr;
- if((modptr = calloc(1, tosend[sockindex].f.sum_bytes)) == NULL) {
- printf("Calloc error for modified objects %s, %d\n", __FILE__, __LINE__);
- free(listmid);
- free(tosend);
- return 1;
- }
- int offset = 0;
- int i;
- for(i = 0; i < tosend[sockindex].f.nummod; i++) {
- int size;
- objheader_t *headeraddr;
- if((headeraddr = t_chashSearch(tosend[sockindex].oidmod[i])) == NULL) {
- printf("%s() Error: No such oid %s, %d\n", __func__, __FILE__, __LINE__);
- free(modptr);
- free(listmid);
- free(tosend);
- return 1;
- }
- GETSIZE(size,headeraddr);
- size+=sizeof(objheader_t);
- memcpy(modptr+offset, headeraddr, size);
- offset+=size;
- }
- forcesend_buf(sd, &writebuffer, modptr, tosend[sockindex].f.sum_bytes);
- free(modptr);
+ if((sd = getSock2WithLock(transRequestSockPool, pile->mid)) < 0) {
+ printf("transRequest(): socket create error\n");
+ free(listmid);
+ free(tosend);
+ return 1;
+ }
+ socklist[sockindex] = sd;
+ /* Send bytes of data with TRANS_REQUEST control message */
+ send_buf(sd, &writebuffer, &(tosend[sockindex].f), sizeof(fixed_data_t));
+
+ /* Send list of machines involved in the transaction */
+ {
+ int size=sizeof(unsigned int)*(tosend[sockindex].f.mcount);
+ send_buf(sd, &writebuffer, tosend[sockindex].listmid, size);
+ }
+
+ /* Send oids and version number tuples for objects that are read */
+ {
+ int size=(sizeof(unsigned int)+sizeof(unsigned short))*(tosend[sockindex].f.numread);
+ send_buf(sd, &writebuffer, tosend[sockindex].objread, size);
+ }
+
+ /* Send objects that are modified */
+ void *modptr;
+ if((modptr = calloc(1, tosend[sockindex].f.sum_bytes)) == NULL) {
+ printf("Calloc error for modified objects %s, %d\n", __FILE__, __LINE__);
+ free(listmid);
+ free(tosend);
+ return 1;
+ }
+ int offset = 0;
+ int i;
+ for(i = 0; i < tosend[sockindex].f.nummod; i++) {
+ int size;
+ objheader_t *headeraddr;
+ if((headeraddr = t_chashSearch(tosend[sockindex].oidmod[i])) == NULL) {
+ printf("%s() Error: No such oid %s, %d\n", __func__, __FILE__, __LINE__);
+ free(modptr);
+ free(listmid);
+ free(tosend);
+ return 1;
+ }
+ GETSIZE(size,headeraddr);
+ size+=sizeof(objheader_t);
+ memcpy(modptr+offset, headeraddr, size);
+ offset+=size;
+ }
+ forcesend_buf(sd, &writebuffer, modptr, tosend[sockindex].f.sum_bytes);
+ free(modptr);
} else { //handle request locally
- handleLocalReq(&tosend[sockindex], &transinfo, &getReplyCtrl[sockindex]);
+ handleLocalReq(&tosend[sockindex], &transinfo, &getReplyCtrl[sockindex]);
}
sockindex++;
pile = pile->next;
for(i = 0; i < pilecount; i++) {
int sd = socklist[i];
if(sd != 0) {
- char control;
- recv_data(sd, &control, sizeof(char));
- //Update common data structure with new ctrl msg
- getReplyCtrl[i] = control;
- /* Recv Objects if participant sends TRANS_DISAGREE */
+ char control;
+ recv_data(sd, &control, sizeof(char));
+ //Update common data structure with new ctrl msg
+ getReplyCtrl[i] = control;
+ /* Recv Objects if participant sends TRANS_DISAGREE */
#ifdef CACHE
- if(control == TRANS_DISAGREE) {
- int length;
- recv_data(sd, &length, sizeof(int));
- void *newAddr;
- pthread_mutex_lock(&prefetchcache_mutex);
- if ((newAddr = prefetchobjstrAlloc((unsigned int)length)) == NULL) {
- printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
- free(tosend);
- free(listmid);
- pthread_mutex_unlock(&prefetchcache_mutex);
- return 1;
- }
- pthread_mutex_unlock(&prefetchcache_mutex);
- recv_data(sd, newAddr, length);
- int offset = 0;
- while(length != 0) {
- unsigned int oidToPrefetch;
- objheader_t * header;
- header = (objheader_t *)(((char *)newAddr) + offset);
- oidToPrefetch = OID(header);
- STATUS(header)=0;
- int size = 0;
- GETSIZE(size, header);
- size += sizeof(objheader_t);
- //make an entry in prefetch hash table
- prehashInsert(oidToPrefetch, header);
- LOGEVENT('E');
- length = length - size;
- offset += size;
- }
- } //end of receiving objs
+ if(control == TRANS_DISAGREE) {
+ int length;
+ recv_data(sd, &length, sizeof(int));
+ void *newAddr;
+ pthread_mutex_lock(&prefetchcache_mutex);
+ if ((newAddr = prefetchobjstrAlloc((unsigned int)length)) == NULL) {
+ printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
+ free(tosend);
+ free(listmid);
+ pthread_mutex_unlock(&prefetchcache_mutex);
+ return 1;
+ }
+ pthread_mutex_unlock(&prefetchcache_mutex);
+ recv_data(sd, newAddr, length);
+ int offset = 0;
+ while(length != 0) {
+ unsigned int oidToPrefetch;
+ objheader_t * header;
+ header = (objheader_t *)(((char *)newAddr) + offset);
+ oidToPrefetch = OID(header);
+ STATUS(header)=0;
+ int size = 0;
+ GETSIZE(size, header);
+ size += sizeof(objheader_t);
+ //make an entry in prefetch hash table
+ prehashInsert(oidToPrefetch, header);
+ LOGEVENT('E');
+ length = length - size;
+ offset += size;
+ }
+ } //end of receiving objs
#endif
}
}
/* Invalidate objects in other machine cache */
int retval;
if((retval = invalidateObj(tosend, pilecount,finalResponse,socklist)) != 0) {
- printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__);
- free(tosend);
- free(listmid);
- return 1;
+ printf("Error: %s() in invalidating Objects %s, %d\n", __func__, __FILE__, __LINE__);
+ free(tosend);
+ free(listmid);
+ return 1;
}
}
#endif
int sd = socklist[i];
if(sd != 0) {
#ifdef CACHE
- if(finalResponse == TRANS_COMMIT) {
- int retval;
- /* Update prefetch cache */
- if((retval = updatePrefetchCache(&(tosend[i]))) != 0) {
- printf("Error: %s() in updating prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
- free(tosend);
- free(listmid);
- return 1;
- }
+ if(finalResponse == TRANS_COMMIT) {
+ int retval;
+ /* Update prefetch cache */
+ if((retval = updatePrefetchCache(&(tosend[i]))) != 0) {
+ printf("Error: %s() in updating prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
+ free(tosend);
+ free(listmid);
+ return 1;
+ }
#ifdef ABORTREADERS
- removetransaction(tosend[i].oidmod,tosend[i].f.nummod);
- removethisreadtransaction(tosend[i].objread, tosend[i].f.numread);
+ removetransaction(tosend[i].oidmod,tosend[i].f.nummod);
+ removethisreadtransaction(tosend[i].objread, tosend[i].f.numread);
#endif
- }
+ }
#ifdef ABORTREADERS
- else if (!treplyretry) {
- removethistransaction(tosend[i].oidmod,tosend[i].f.nummod);
- removethisreadtransaction(tosend[i].objread,tosend[i].f.numread);
- }
+ else if (!treplyretry) {
+ removethistransaction(tosend[i].oidmod,tosend[i].f.nummod);
+ removethisreadtransaction(tosend[i].objread,tosend[i].f.numread);
+ }
#endif
#endif
- send_data(sd, &finalResponse, sizeof(char));
+ send_data(sd, &finalResponse, sizeof(char));
} else {
- /* Complete local processing */
- doLocalProcess(finalResponse, &(tosend[i]), &transinfo);
+ /* Complete local processing */
+ doLocalProcess(finalResponse, &(tosend[i]), &transinfo);
#ifdef ABORTREADERS
- if(finalResponse == TRANS_COMMIT) {
- removetransaction(tosend[i].oidmod,tosend[i].f.nummod);
- removethisreadtransaction(tosend[i].objread,tosend[i].f.numread);
- } else if (!treplyretry) {
- removethistransaction(tosend[i].oidmod,tosend[i].f.nummod);
- removethisreadtransaction(tosend[i].objread,tosend[i].f.numread);
- }
+ if(finalResponse == TRANS_COMMIT) {
+ removetransaction(tosend[i].oidmod,tosend[i].f.nummod);
+ removethisreadtransaction(tosend[i].objread,tosend[i].f.numread);
+ } else if (!treplyretry) {
+ removethistransaction(tosend[i].oidmod,tosend[i].f.nummod);
+ removethisreadtransaction(tosend[i].objread,tosend[i].f.numread);
+ }
#endif
}
}
commitCountForObjRead(getReplyCtrl, oidnotfound, oidlocked, &numoidnotfound, &numoidlocked, &v_nomatch, &v_matchlock, &v_matchnolock, oid, version);
} else { // Objects Modified
if(i == tdata->f.numread) {
- oidlocked[numoidlocked++] = -1;
+ oidlocked[numoidlocked++] = -1;
}
int tmpsize;
objheader_t *headptr;
headptr = (objheader_t *) t_chashSearch(tdata->oidmod[i-numread]);
if (headptr == NULL) {
- printf("Error: handleLocalReq() returning NULL, no such oid %s, %d\n", __FILE__, __LINE__);
- return;
+ printf("Error: handleLocalReq() returning NULL, no such oid %s, %d\n", __FILE__, __LINE__);
+ return;
}
oid = OID(headptr);
version = headptr->version;
* all Participant machines after the TRANS_REQUEST protocol */
char decideResponse(char *getReplyCtrl, char *treplyretry, int pilecount) {
int i, transagree = 0, transdisagree = 0, transsoftabort = 0; /* Counters to formulate decision of what
- message to send */
+ message to send */
for (i = 0; i < pilecount; i++) {
char control;
control = getReplyCtrl[i];
/* Check if Obj is locked by any previous transaction */
if (write_trylock(STATUSPTR(mobj))) { // Can acquire write lock
if (version == ((objheader_t *)mobj)->version) { /* match versions */
- (*v_matchnolock)++;
- //Keep track of what is locked
- oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
+ (*v_matchnolock)++;
+ //Keep track of what is locked
+ oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
} else { /* If versions don't match ...HARD ABORT */
- (*v_nomatch)++;
- /* Send TRANS_DISAGREE to Coordinator */
- *getReplyCtrl = TRANS_DISAGREE;
+ (*v_nomatch)++;
+ /* Send TRANS_DISAGREE to Coordinator */
+ *getReplyCtrl = TRANS_DISAGREE;
- //Keep track of what is locked
- oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
- return;
+ //Keep track of what is locked
+ oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
+ return;
}
} else { //A lock is acquired some place else
if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
- (*v_matchlock)++;
+ (*v_matchlock)++;
} else { /* If versions don't match ...HARD ABORT */
- (*v_nomatch)++;
- /* Send TRANS_DISAGREE to Coordinator */
- *getReplyCtrl = TRANS_DISAGREE;
- return;
+ (*v_nomatch)++;
+ /* Send TRANS_DISAGREE to Coordinator */
+ *getReplyCtrl = TRANS_DISAGREE;
+ return;
}
}
}
/* Check if Obj is locked by any previous transaction */
if (read_trylock(STATUSPTR(mobj))) { // Can further acquire read locks
if (version == ((objheader_t *)mobj)->version) { /* If locked then match versions */
- (*v_matchnolock)++;
- //Keep track of what is locked
- oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
+ (*v_matchnolock)++;
+ //Keep track of what is locked
+ oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
} else { /* If versions don't match ...HARD ABORT */
- (*v_nomatch)++;
- /* Send TRANS_DISAGREE to Coordinator */
- *getReplyCtrl = TRANS_DISAGREE;
- //Keep track of what is locked
- oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
- return;
+ (*v_nomatch)++;
+ /* Send TRANS_DISAGREE to Coordinator */
+ *getReplyCtrl = TRANS_DISAGREE;
+ //Keep track of what is locked
+ oidlocked[(*numoidlocked)++] = OID(((objheader_t *)mobj));
+ return;
}
} else { //Has reached max number of readers or some other transaction
//has acquired a lock on this object
if (version == ((objheader_t *)mobj)->version) { /* Check if versions match */
- (*v_matchlock)++;
+ (*v_matchlock)++;
} else { /* If versions don't match ...HARD ABORT */
- (*v_nomatch)++;
- /* Send TRANS_DISAGREE to Coordinator */
- *getReplyCtrl = TRANS_DISAGREE;
- return;
+ (*v_nomatch)++;
+ /* Send TRANS_DISAGREE to Coordinator */
+ *getReplyCtrl = TRANS_DISAGREE;
+ return;
}
}
}
int countInvalidObj=0;
if (oid==0) {
- numLocal++;
- continue;
+ numLocal++;
+ continue;
}
//Look up fields locally
int isLastOffset=0;
if(endindex==0)
- isLastOffset=1;
+ isLastOffset=1;
for(newbase=baseindex; newbase<endindex; newbase++) {
- if(newbase==(endindex-1))
- isLastOffset=1;
- if (!lookupObject(&oid,arryfields[newbase],&countInvalidObj)) {
- break;
- }
- //Ended in a null pointer...
- if (oid==0) {
- numLocal++;
- goto tuple;
- }
+ if(newbase==(endindex-1))
+ isLastOffset=1;
+ if (!lookupObject(&oid,arryfields[newbase],&countInvalidObj)) {
+ break;
+ }
+ //Ended in a null pointer...
+ if (oid==0) {
+ numLocal++;
+ goto tuple;
+ }
}
//Entire prefetch is local
if (newbase==endindex&&checkoid(oid,isLastOffset)) {
- numLocal++;
- goto tuple;
+ numLocal++;
+ goto tuple;
}
//Add to remote requests
//only once because later old entries may still cause unnecessary roundtrips during prefetching
(*countInvalidObj)+=1;
if(*countInvalidObj > 1) {
- return 0;
+ return 0;
}
}
} else {
/* Send Prefetch Request */
prefetchpile_t *ptr = pilehead;
while(ptr != NULL) {
- globalid++;
- int sd = getSock2(transPrefetchSockPool, ptr->mid);
- sendPrefetchReq(ptr, sd,globalid);
- ptr = ptr->next;
+ globalid++;
+ int sd = getSock2(transPrefetchSockPool, ptr->mid);
+ sendPrefetchReq(ptr, sd,globalid);
+ ptr = ptr->next;
}
/* Release socket */
if((oldptr = prehashSearch(oid)) != NULL) {
/* If older version then update with new object ptr */
if(((objheader_t *)oldptr)->version < ((objheader_t *)modptr)->version) {
- prehashInsert(oid, modptr);
+ prehashInsert(oid, modptr);
}
} else { /* Else add the object ptr to hash table*/
prehashInsert(oid, modptr);
#ifdef CACHE
pthread_mutex_lock(&prefetchcache_mutex);
if ((objheader = prefetchobjstrAlloc(size)) == NULL) {
- printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
- pthread_exit(NULL);
+ printf("Error: %s() objstrAlloc error for copying into prefetch cache %s, %d\n", __func__, __FILE__, __LINE__);
+ pthread_exit(NULL);
}
pthread_mutex_unlock(&prefetchcache_mutex);
recv_data(sd, objheader, size);
#else
char *buffer;
if((buffer = calloc(1, size)) == NULL) {
- printf("%s() Calloc Error %s at line %d\n", __func__, __FILE__, __LINE__);
- fflush(stdout);
- return 0;
+ printf("%s() Calloc Error %s at line %d\n", __func__, __FILE__, __LINE__);
+ fflush(stdout);
+ return 0;
}
recv_data(sd, buffer, size);
objheader = (objheader_t *)buffer;
while (token != NULL) {
tmpAddr = inet_addr(token);
if ((int)tmpAddr == -1) {
- printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
- fclose(configFile);
- return -1;
+ printf("error in %s: bad token:%s\n", CONFIG_FILENAME, token);
+ fclose(configFile);
+ return -1;
} else
- addHost(htonl(tmpAddr));
+ addHost(htonl(tmpAddr));
token = strtok(NULL, delimiters);
}
}
} else {
for(i = 0; i < ndata->numoid; i++) {
if(ndata->oidarry[i] == oid) {
- objIsFound = 1;
- index = i;
+ objIsFound = 1;
+ index = i;
}
}
if(objIsFound == 0) {
return;
} else {
if(version <= ndata->versionarry[index]) {
- printf("threadNotify(): New version %d has not changed since last version for oid = %d, %s, %d\n", version, oid, __FILE__, __LINE__);
- return;
+ printf("threadNotify(): New version %d has not changed since last version for oid = %d, %s, %d\n", version, oid, __FILE__, __LINE__);
+ return;
} else {
#ifdef CACHE
- /* Clear from prefetch cache and free thread related data structure */
- if((ptr = prehashSearch(oid)) != NULL) {
- prehashRemove(oid);
- }
-#endif
- pthread_mutex_lock(&(ndata->threadnotify));
- pthread_cond_signal(&(ndata->threadcond));
- pthread_mutex_unlock(&(ndata->threadnotify));
+ /* Clear from prefetch cache and free thread related data structure */
+ if((ptr = prehashSearch(oid)) != NULL) {
+ prehashRemove(oid);
+ }
+#endif
+ pthread_mutex_lock(&(ndata->threadnotify));
+ pthread_cond_signal(&(ndata->threadcond));
+ pthread_mutex_unlock(&(ndata->threadnotify));
}
}
}
int tmpsize;
if (STATUS(headeraddr) & NEW) {
- tmp->oidcreated[tmp->numcreated] = OID(headeraddr);
- tmp->numcreated++;
- GETSIZE(tmpsize, headeraddr);
- tmp->sum_bytes += sizeof(objheader_t) + tmpsize;
+ tmp->oidcreated[tmp->numcreated] = OID(headeraddr);
+ tmp->numcreated++;
+ GETSIZE(tmpsize, headeraddr);
+ tmp->sum_bytes += sizeof(objheader_t) + tmpsize;
} else if (STATUS(headeraddr) & DIRTY) {
- tmp->oidmod[tmp->nummod] = OID(headeraddr);
- tmp->nummod++;
- GETSIZE(tmpsize, headeraddr);
- tmp->sum_bytes += sizeof(objheader_t) + tmpsize;
+ tmp->oidmod[tmp->nummod] = OID(headeraddr);
+ tmp->nummod++;
+ GETSIZE(tmpsize, headeraddr);
+ tmp->sum_bytes += sizeof(objheader_t) + tmpsize;
} else {
- offset = (sizeof(unsigned int) + sizeof(short)) * tmp->numread;
- *((unsigned int *)(((char *)tmp->objread) + offset))=OID(headeraddr);
- offset += sizeof(unsigned int);
- *((short *)(((char *)tmp->objread) + offset)) = headeraddr->version;
- tmp->numread++;
+ offset = (sizeof(unsigned int) + sizeof(short)) * tmp->numread;
+ *((unsigned int *)(((char *)tmp->objread) + offset))=OID(headeraddr);
+ offset += sizeof(unsigned int);
+ *((short *)(((char *)tmp->objread) + offset)) = headeraddr->version;
+ tmp->numread++;
}
found = 1;
break;
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;
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;
while(ptr!=NULL) {
if (((ht->comp_function==NULL)&&(ptr->src==key))||((ht->comp_function!=NULL)&&(*ht->comp_function)(ptr->src,key)))
if (ptr->inext!=NULL) {
- return ptr->inext->src;
+ return ptr->inext->src;
} else
- return NULL;
+ return NULL;
ptr=ptr->next;
}
#ifndef MULTICORE
struct genpointerlist *tmpptr=ptr->next;
ptr->next=tmpptr->next;
if (tmpptr==ht->list)
- ht->list=tmpptr->inext;
+ ht->list=tmpptr->inext;
if (tmpptr==ht->last)
- ht->last=tmpptr->iprev;
+ ht->last=tmpptr->iprev;
if (tmpptr->iprev!=NULL)
- tmpptr->iprev->inext=tmpptr->inext;
+ tmpptr->iprev->inext=tmpptr->inext;
if (tmpptr->inext!=NULL)
- tmpptr->inext->iprev=tmpptr->iprev;
+ tmpptr->inext->iprev=tmpptr->iprev;
RUNFREE(tmpptr);
ht->counter--;
return;
if (ht->bins[i]!=NULL) {
struct genpointerlist *genptr=ht->bins[i];
while(genptr!=NULL) {
- struct genpointerlist *tmpptr=genptr->next;
- RUNFREE(genptr);
- genptr=tmpptr;
+ struct genpointerlist *tmpptr=genptr->next;
+ RUNFREE(genptr);
+ genptr=tmpptr;
}
}
}
*ptr=(*ptr)->next;
if (toremove->lprev!=NULL) {
- toremove->lprev->lnext=toremove->lnext;
+ toremove->lprev->lnext=toremove->lnext;
} else {
- thisvar->listhead=toremove->lnext;
+ thisvar->listhead=toremove->lnext;
}
if (toremove->lnext!=NULL) {
- toremove->lnext->lprev=toremove->lprev;
+ toremove->lnext->lprev=toremove->lprev;
} else {
- thisvar->listtail=toremove->lprev;
+ thisvar->listtail=toremove->lprev;
}
RUNFREE(toremove);
for(i=thisvar->size-1; i>=0; i--) {
struct ObjectNode *ptr;
for(ptr=thisvar->bucket[i]; ptr!=NULL; ) {
- struct ObjectNode * nextptr=ptr->next;
- unsigned int newhashkey=(unsigned int)ptr->key % newsize;
- ptr->next=newbucket[newhashkey];
- newbucket[newhashkey]=ptr;
- ptr=nextptr;
+ struct ObjectNode * nextptr=ptr->next;
+ unsigned int newhashkey=(unsigned int)ptr->key % newsize;
+ ptr->next=newbucket[newhashkey];
+ newbucket[newhashkey]=ptr;
+ ptr=nextptr;
}
}
thisvar->size=newsize;
for(i=thisvar->size-1; i>=0; i--) {
struct ObjectNode *ptr;
for(ptr=thisvar->bucket[i]; ptr!=NULL; ) {
- struct ObjectNode * nextptr=ptr->next;
- unsigned int newhashkey=(unsigned int)ptr->key % newsize;
- ptr->next=newbucket[newhashkey];
- newbucket[newhashkey]=ptr;
- ptr=nextptr;
+ struct ObjectNode * nextptr=ptr->next;
+ unsigned int newhashkey=(unsigned int)ptr->key % newsize;
+ ptr->next=newbucket[newhashkey];
+ newbucket[newhashkey]=ptr;
+ ptr=nextptr;
}
}
thisvar->size=newsize;
if( i->prev == NULL ) {
if( queue->head != i ) {
- return 0;
+ return 0;
}
// i->prev != NULL
} else {
if( i->prev->next == NULL ) {
- return 0;
+ return 0;
} else if( i->prev->next != i ) {
- return 0;
+ return 0;
}
}
if( i->next == NULL ) {
if( queue->tail != i ) {
- return 0;
+ return 0;
}
// i->next != NULL
} else {
if( i->next->prev == NULL ) {
- return 0;
+ return 0;
} else if( i->next->prev != i ) {
- return 0;
+ return 0;
}
}
*ptr=(*ptr)->next;
if (toremove->lprev!=NULL) {
- toremove->lprev->lnext=toremove->lnext;
+ toremove->lprev->lnext=toremove->lnext;
} else {
- thisvar->listhead=toremove->lnext;
+ thisvar->listhead=toremove->lnext;
}
if (toremove->lnext!=NULL) {
- toremove->lnext->lprev=toremove->lprev;
+ toremove->lnext->lprev=toremove->lprev;
} else {
- thisvar->listtail=toremove->lprev;
+ thisvar->listtail=toremove->lprev;
}
RUNFREE(toremove);
*ptr=(*ptr)->next;
if (toremove->lprev!=NULL) {
- toremove->lprev->lnext=toremove->lnext;
+ toremove->lprev->lnext=toremove->lnext;
} else {
- thisvar->listhead=toremove->lnext;
+ thisvar->listhead=toremove->lnext;
}
if (toremove->lnext!=NULL) {
- toremove->lnext->lprev=toremove->lprev;
+ toremove->lnext->lprev=toremove->lprev;
} else {
- thisvar->listtail=toremove->lprev;
+ thisvar->listtail=toremove->lprev;
}
RUNFREE(toremove);
for(i=thisvar->size-1; i>=0; i--) {
struct RuntimeNode *ptr;
for(ptr=thisvar->bucket[i]; ptr!=NULL; ) {
- struct RuntimeNode * nextptr=ptr->next;
- unsigned int newhashkey=(unsigned int)ptr->key % newsize;
- ptr->next=newbucket[newhashkey];
- newbucket[newhashkey]=ptr;
- ptr=nextptr;
+ struct RuntimeNode * nextptr=ptr->next;
+ unsigned int newhashkey=(unsigned int)ptr->key % newsize;
+ ptr->next=newbucket[newhashkey];
+ newbucket[newhashkey]=ptr;
+ ptr=nextptr;
}
}
thisvar->size=newsize;
for(i=thisvar->size-1; i>=0; i--) {
struct RuntimeNode *ptr;
for(ptr=thisvar->bucket[i]; ptr!=NULL; ) {
- struct RuntimeNode * nextptr=ptr->next;
- unsigned int newhashkey=(unsigned int)ptr->key % newsize;
- ptr->next=newbucket[newhashkey];
- newbucket[newhashkey]=ptr;
- ptr=nextptr;
+ struct RuntimeNode * nextptr=ptr->next;
+ unsigned int newhashkey=(unsigned int)ptr->key % newsize;
+ ptr->next=newbucket[newhashkey];
+ newbucket[newhashkey]=ptr;
+ ptr=nextptr;
}
}
thisvar->size=newsize;
if (curr->key == key) { // Find a match in the hash table
table->numelements--; // Decrement the number of elements in the global hashtable
if ((curr == &ptr[index]) && (curr->next == NULL)) { // Delete the first item inside the hashtable with no linked list of cnode_t
- curr->key = 0;
- curr->val = NULL;
+ curr->key = 0;
+ curr->val = NULL;
} else if ((curr == &ptr[index]) && (curr->next != NULL)) { //Delete the first item with a linked list of cnode_t connected
- curr->key = curr->next->key;
- curr->val = curr->next->val;
- node = curr->next;
- curr->next = curr->next->next;
- free(node);
+ curr->key = curr->next->key;
+ curr->val = curr->next->val;
+ node = curr->next;
+ curr->next = curr->next->next;
+ free(node);
} else { // Regular delete from linked listed
- prev->next = curr->next;
- free(curr);
+ prev->next = curr->next;
+ free(curr);
}
return 0;
}
cnode_t * newnode=&ntable[index];
if(newnode->key==0) {
- newnode->key=curr->key;
- newnode->val=curr->val;
- newnode->lnext=last;
- last=newnode;
+ newnode->key=curr->key;
+ newnode->val=curr->val;
+ newnode->lnext=last;
+ last=newnode;
} else {
- cnode_t *tmp=malloc(sizeof(cnode_t));
- tmp->next=newnode->next;
- newnode->next=tmp;
- tmp->key=curr->key;
- tmp->val=curr->val;
- tmp->lnext=last;
- last=tmp;
+ cnode_t *tmp=malloc(sizeof(cnode_t));
+ tmp->next=newnode->next;
+ newnode->next=tmp;
+ tmp->key=curr->key;
+ tmp->val=curr->val;
+ tmp->lnext=last;
+ last=tmp;
}
if (isfirst) {
- isfirst=0;
+ isfirst=0;
} else {
- free(curr);
+ free(curr);
}
curr = next;
}
while(curr != NULL) {
next = curr->next;
if(isFirst != 1) {
- free(curr);
+ free(curr);
}
isFirst = 0;
curr = next;
pointer=pointerarray[type];
#ifdef TASK
if (type==TAGTYPE) {
- void *objptr=((struct ___TagDescriptor___*)ptr)->flagptr;
- if (objptr!=NULL) {
- void *dst;
- if ((dst=cSearch(forward, objptr))==NULL) {
- void *copy=createcopy(objptr);
- cInsert(forward, objptr, copy);
- cInsert(reverse, copy, objptr);
- addNewItem(todo, objptr);
- ((struct ___TagDescriptor___*)cpy)->flagptr=copy;
- } else {
- ((struct ___TagDescriptor___*) cpy)->flagptr=dst;
- }
- }
+ void *objptr=((struct ___TagDescriptor___*)ptr)->flagptr;
+ if (objptr!=NULL) {
+ void *dst;
+ if ((dst=cSearch(forward, objptr))==NULL) {
+ void *copy=createcopy(objptr);
+ cInsert(forward, objptr, copy);
+ cInsert(reverse, copy, objptr);
+ addNewItem(todo, objptr);
+ ((struct ___TagDescriptor___*)cpy)->flagptr=copy;
+ } else {
+ ((struct ___TagDescriptor___*) cpy)->flagptr=dst;
+ }
+ }
} else
#endif
if (pointer==0) {
- /* Array of primitives */
- /* Do nothing */
+ /* Array of primitives */
+ /* Do nothing */
} else if (((int)pointer)==1) {
- /* Array of pointers */
- struct ArrayObject *ao=(struct ArrayObject *) ptr;
- struct ArrayObject *ao_cpy=(struct ArrayObject *) cpy;
- int length=ao->___length___;
- int i;
- for(i=0; i<length; i++) {
- void *dst;
- void *objptr=((void **)(((char *)&ao->___length___)+sizeof(int)))[i];
- if (objptr==NULL) {
- ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]=NULL;
- } else if ((dst=cSearch(forward,objptr))!=NULL)
- ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]=dst;
- else {
- void * copy=createcopy(objptr);
- cInsert(forward, objptr, copy);
- cInsert(reverse, copy, objptr);
- addNewItem(todo, objptr);
- ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]=copy;
- }
- }
+ /* Array of pointers */
+ struct ArrayObject *ao=(struct ArrayObject *) ptr;
+ struct ArrayObject *ao_cpy=(struct ArrayObject *) cpy;
+ int length=ao->___length___;
+ int i;
+ for(i=0; i<length; i++) {
+ void *dst;
+ void *objptr=((void **)(((char *)&ao->___length___)+sizeof(int)))[i];
+ if (objptr==NULL) {
+ ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]=NULL;
+ } else if ((dst=cSearch(forward,objptr))!=NULL)
+ ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]=dst;
+ else {
+ void * copy=createcopy(objptr);
+ cInsert(forward, objptr, copy);
+ cInsert(reverse, copy, objptr);
+ addNewItem(todo, objptr);
+ ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]=copy;
+ }
+ }
} else {
- int size=pointer[0];
- int i;
- for(i=1; i<=size; i++) {
- int offset=pointer[i];
- void * objptr=*((void **)(((int)ptr)+offset));
- void *dst;
- if (objptr==NULL) {
- *((void **)(((int)cpy)+offset))=NULL;
- } else if ((dst=cSearch(forward, objptr))!=NULL)
- *((void **) &(((char *)cpy)[offset]))=dst;
- else {
- void * copy=createcopy(objptr);
- cInsert(forward, objptr, copy);
- cInsert(reverse, copy, objptr);
- addNewItem(todo, objptr);
- *((void **)(((int)cpy)+offset))=copy;
- }
- }
+ int size=pointer[0];
+ int i;
+ for(i=1; i<=size; i++) {
+ int offset=pointer[i];
+ void * objptr=*((void **)(((int)ptr)+offset));
+ void *dst;
+ if (objptr==NULL) {
+ *((void **)(((int)cpy)+offset))=NULL;
+ } else if ((dst=cSearch(forward, objptr))!=NULL)
+ *((void **) &(((char *)cpy)[offset]))=dst;
+ else {
+ void * copy=createcopy(objptr);
+ cInsert(forward, objptr, copy);
+ cInsert(reverse, copy, objptr);
+ addNewItem(todo, objptr);
+ *((void **)(((int)cpy)+offset))=copy;
+ }
+ }
}
}
}
size=classsize[type];
#ifdef TASK
if (type==TAGTYPE) {
- void *objptr=((struct ___TagDescriptor___*)ptr)->flagptr;
- memcpy(cpy, ptr, size);
- if (objptr!=NULL) {
- if (cSearch(visited, objptr)==NULL) {
- cInsert(visited, objptr, objptr);
- addNewItem(todo, objptr);
- }
- *((void **) &(((struct ___TagDescriptor___ *)cpy)->flagptr))=cSearch(reverse, objptr);
- }
+ void *objptr=((struct ___TagDescriptor___*)ptr)->flagptr;
+ memcpy(cpy, ptr, size);
+ if (objptr!=NULL) {
+ if (cSearch(visited, objptr)==NULL) {
+ cInsert(visited, objptr, objptr);
+ addNewItem(todo, objptr);
+ }
+ *((void **) &(((struct ___TagDescriptor___ *)cpy)->flagptr))=cSearch(reverse, objptr);
+ }
} else
#endif
if (pointer==0) {
- /* Array of primitives */
- struct ArrayObject *ao=(struct ArrayObject *) ptr;
- int length=ao->___length___;
- int cpysize=sizeof(struct ArrayObject)+length*size;
- memcpy(cpy, ptr, cpysize);
+ /* Array of primitives */
+ struct ArrayObject *ao=(struct ArrayObject *) ptr;
+ int length=ao->___length___;
+ int cpysize=sizeof(struct ArrayObject)+length*size;
+ memcpy(cpy, ptr, cpysize);
} else if ((int)pointer==1) {
- /* Array of pointers */
- struct ArrayObject *ao=(struct ArrayObject *) ptr;
- struct ArrayObject *ao_cpy=(struct ArrayObject *) cpy;
- int length=ao->___length___;
- int i;
- int cpysize=sizeof(struct ArrayObject)+length*size;
- memcpy(ao_cpy, ao, cpysize);
+ /* Array of pointers */
+ struct ArrayObject *ao=(struct ArrayObject *) ptr;
+ struct ArrayObject *ao_cpy=(struct ArrayObject *) cpy;
+ int length=ao->___length___;
+ int i;
+ int cpysize=sizeof(struct ArrayObject)+length*size;
+ memcpy(ao_cpy, ao, cpysize);
- for(i=0; i<length; i++) {
- void *objptr=((void **)(((char *)&ao->___length___)+sizeof(int)))[i];
- if (objptr==NULL)
- ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]=NULL;
- else {
- if (cSearch(visited, objptr)==NULL) {
- cInsert(visited, objptr, objptr);
- addNewItem(todo, objptr);
- }
- *((void **) &((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i])=cSearch(reverse, objptr);
- }
- }
+ for(i=0; i<length; i++) {
+ void *objptr=((void **)(((char *)&ao->___length___)+sizeof(int)))[i];
+ if (objptr==NULL)
+ ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]=NULL;
+ else {
+ if (cSearch(visited, objptr)==NULL) {
+ cInsert(visited, objptr, objptr);
+ addNewItem(todo, objptr);
+ }
+ *((void **) &((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i])=cSearch(reverse, objptr);
+ }
+ }
} else {
- int numptr=pointer[0];
- int i;
- void *flagptr;
- int oldflag;
- int currflag;
- if (hasflags[type]) {
- flagptr=(void *)(((int *)cpy)[2]);
- oldflag=(((int *)cpy)[1]);
- currflag=(((int *)ptr)[1]);
- }
- memcpy(cpy, ptr, size);
- for(i=1; i<=numptr; i++) {
- int offset=pointer[i];
- void * objptr=*((void **)(((int)ptr)+offset));
- if (objptr==NULL)
- *((void **)(((int)cpy)+offset))=NULL;
- else {
- if (cSearch(visited, objptr)==NULL) {
- cInsert(visited, objptr, objptr);
- addNewItem(todo, objptr);
- }
- *((void **) &(((char *)cpy)[offset]))=cSearch(reverse, objptr);
- }
- }
- if (hasflags[type]) {
- (((void **)cpy)[2])=flagptr;
- if (currflag!=oldflag) {
- flagorandinit(cpy, 0, 0xFFFFFFFF);
+ int numptr=pointer[0];
+ int i;
+ void *flagptr;
+ int oldflag;
+ int currflag;
+ if (hasflags[type]) {
+ flagptr=(void *)(((int *)cpy)[2]);
+ oldflag=(((int *)cpy)[1]);
+ currflag=(((int *)ptr)[1]);
+ }
+ memcpy(cpy, ptr, size);
+ for(i=1; i<=numptr; i++) {
+ int offset=pointer[i];
+ void * objptr=*((void **)(((int)ptr)+offset));
+ if (objptr==NULL)
+ *((void **)(((int)cpy)+offset))=NULL;
+ else {
+ if (cSearch(visited, objptr)==NULL) {
+ cInsert(visited, objptr, objptr);
+ addNewItem(todo, objptr);
+ }
+ *((void **) &(((char *)cpy)[offset]))=cSearch(reverse, objptr);
+ }
+ }
+ if (hasflags[type]) {
+ (((void **)cpy)[2])=flagptr;
+ if (currflag!=oldflag) {
+ flagorandinit(cpy, 0, 0xFFFFFFFF);
#ifdef MULTICORE
- enqueueObject(cpy, NULL,0); //TODO
+ enqueueObject(cpy, NULL,0); //TODO
#else
- enqueueObject(cpy);
+ enqueueObject(cpy);
#endif
- }
- }
+ }
+ }
}
}
}
if( actualTop == currTop ) {
// CAS succeeded
if( oldBotNode != newBotNode ) {
- poolfreeinto(dq->memPool, oldBotNode);
+ poolfreeinto(dq->memPool, oldBotNode);
}
return retVal;
chashlistnode_t *tmp,*next;
if ((key=(void *)curr->key) == 0) { //Exit inner loop if there the first element is 0
- break; //key = val =0 for element if not present within the hash table
+ break; //key = val =0 for element if not present within the hash table
}
SENQUEUE(key, key);
if (curr->val>=curr_heapbase&&curr->val<curr_heaptop) {
- SENQUEUE(curr->val, curr->val);
+ SENQUEUE(curr->val, curr->val);
} else {
- //rewrite transaction cache entry
- void *vptr=curr->val;
- int type=((int *)vptr)[0];
- unsigned INTPTR *pointer=pointerarray[type];
- if (pointer==0) {
- //array of primitives - do nothing
- struct ArrayObject *ao=(struct ArrayObject *) vptr;
- SENQUEUE((void *)ao->___objlocation___, *((void **)&ao->___objlocation___));
- } else if (((INTPTR)pointer)==1) {
- //array of pointers
- struct ArrayObject *ao=(struct ArrayObject *) vptr;
- int length=ao->___length___;
- int i;
- SENQUEUE((void *)ao->___objlocation___, *((void **)&ao->___objlocation___));
+ //rewrite transaction cache entry
+ void *vptr=curr->val;
+ int type=((int *)vptr)[0];
+ unsigned INTPTR *pointer=pointerarray[type];
+ if (pointer==0) {
+ //array of primitives - do nothing
+ struct ArrayObject *ao=(struct ArrayObject *) vptr;
+ SENQUEUE((void *)ao->___objlocation___, *((void **)&ao->___objlocation___));
+ } else if (((INTPTR)pointer)==1) {
+ //array of pointers
+ struct ArrayObject *ao=(struct ArrayObject *) vptr;
+ int length=ao->___length___;
+ int i;
+ SENQUEUE((void *)ao->___objlocation___, *((void **)&ao->___objlocation___));
#ifdef STMARRAY
- int lowindex=ao->lowindex;
- int highindex=ao->highindex;
- int j;
- for(j=lowindex; j<=highindex; j++) {
- unsigned int lockval;
- GETLOCKVAL(lockval, ao, j);
- if (lockval!=STMNONE) {
- int lowi=(j<<INDEXSHIFT)/sizeof(void *);
- int highi=lowi+(INDEXLENGTH/sizeof(void *));
- for(i=lowi; i<highi; i++) {
+ int lowindex=ao->lowindex;
+ int highindex=ao->highindex;
+ int j;
+ for(j=lowindex; j<=highindex; j++) {
+ unsigned int lockval;
+ GETLOCKVAL(lockval, ao, j);
+ if (lockval!=STMNONE) {
+ int lowi=(j<<INDEXSHIFT)/sizeof(void *);
+ int highi=lowi+(INDEXLENGTH/sizeof(void *));
+ for(i=lowi; i<highi; i++) {
#else
- for(i=0; i<length; i++) {
+ for(i=0; i<length; i++) {
#endif
- void *objptr=((void **)(((char *)&ao->___length___)+sizeof(int)))[i];
- SENQUEUE(objptr, ((void **)(((char *)&ao->___length___)+sizeof(int)))[i]);
- }
+ void *objptr=((void **)(((char *)&ao->___length___)+sizeof(int)))[i];
+ SENQUEUE(objptr, ((void **)(((char *)&ao->___length___)+sizeof(int)))[i]);
+ }
#ifdef STMARRAY
- }
- }
-#endif
- } else {
- INTPTR size=pointer[0];
- int i;
- for(i=1; i<=size; i++) {
- unsigned int offset=pointer[i];
- void * objptr=*((void **)(((char *)vptr)+offset));
- SENQUEUE(objptr, *((void **)(((char *)vptr)+offset)));
- }
- }
- }
-
- next = curr->next;
- index = (((unsigned INTPTR)key) & mask) >>4;
-
- curr->key=key;
- tmp=&node[index];
- // Insert into the new table
- if(tmp->key == 0) {
- tmp->key = curr->key;
- tmp->val = curr->val;
- tmp->lnext=newlist;
- newlist=tmp;
- } else if (isfirst) {
- chashlistnode_t *newnode;
- if ((*cstr)->num<NUMCLIST) {
- newnode=&(*cstr)->array[(*cstr)->num];
- (*cstr)->num++;
- } else {
- //get new list
- cliststruct_t *tcl=calloc(1,sizeof(cliststruct_t));
- tcl->next=*cstr;
- *cstr=tcl;
- newnode=&tcl->array[0];
- tcl->num=1;
- }
- newnode->key = curr->key;
- newnode->val = curr->val;
- newnode->next = tmp->next;
- newnode->lnext=newlist;
- newlist=newnode;
- tmp->next=newnode;
- } else {
- curr->lnext=newlist;
- newlist=curr;
- curr->next=tmp->next;
- tmp->next=curr;
- }
- isfirst = 0;
- curr = next;
- }
- while(curr!=NULL) ;
+ }
+ }
+#endif
+ } else {
+ INTPTR size=pointer[0];
+ int i;
+ for(i=1; i<=size; i++) {
+ unsigned int offset=pointer[i];
+ void * objptr=*((void **)(((char *)vptr)+offset));
+ SENQUEUE(objptr, *((void **)(((char *)vptr)+offset)));
+ }
+ }
+ }
+
+ next = curr->next;
+ index = (((unsigned INTPTR)key) & mask) >>4;
+
+ curr->key=key;
+ tmp=&node[index];
+ // Insert into the new table
+ if(tmp->key == 0) {
+ tmp->key = curr->key;
+ tmp->val = curr->val;
+ tmp->lnext=newlist;
+ newlist=tmp;
+ } else if (isfirst) {
+ chashlistnode_t *newnode;
+ if ((*cstr)->num<NUMCLIST) {
+ newnode=&(*cstr)->array[(*cstr)->num];
+ (*cstr)->num++;
+ } else {
+ //get new list
+ cliststruct_t *tcl=calloc(1,sizeof(cliststruct_t));
+ tcl->next=*cstr;
+ *cstr=tcl;
+ newnode=&tcl->array[0];
+ tcl->num=1;
+ }
+ newnode->key = curr->key;
+ newnode->val = curr->val;
+ newnode->next = tmp->next;
+ newnode->lnext=newlist;
+ newlist=newnode;
+ tmp->next=newnode;
+ } else {
+ curr->lnext=newlist;
+ newlist=curr;
+ curr->next=tmp->next;
+ tmp->next=curr;
+ }
+ isfirst = 0;
+ curr = next;
+ }
+ while(curr!=NULL) ;
}
free(ptr);
(*tc_table)=node;
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]);
+ void *objptr=((void **)(((char *)&ao->___length___)+sizeof(int)))[i];
+ ENQUEUE(objptr, ((void **)(((char *)&ao_cpy->___length___)+sizeof(int)))[i]);
}
} else {
INTPTR size=pointer[0];
int i;
for(i=1; i<=size; i++) {
- unsigned int offset=pointer[i];
- void * objptr=*((void **)(((char *)ptr)+offset));
- ENQUEUE(objptr, *((void **)(((char *)cpy)+offset)));
+ unsigned int offset=pointer[i];
+ void * objptr=*((void **)(((char *)ptr)+offset));
+ ENQUEUE(objptr, *((void **)(((char *)cpy)+offset)));
}
}
}
/* Need to allocate base heap */
curr_heapbase=malloc(INITIALHEAPSIZE);
if (curr_heapbase==NULL) {
- printf("malloc failed. Garbage colletcor couldn't get enough memory. Try changing heap size.\n");
- exit(-1);
+ printf("malloc failed. Garbage colletcor couldn't get enough memory. Try changing heap size.\n");
+ exit(-1);
}
#if defined(STM)||defined(THREADS)||defined(MLP)
#else
to_heapbase=malloc(INITIALHEAPSIZE);
if (to_heapbase==NULL) {
- printf("malloc failed. Garbage collector couldn't get enough memory. Try changing heap size.\n");
- exit(-1);
+ printf("malloc failed. Garbage collector couldn't get enough memory. Try changing heap size.\n");
+ exit(-1);
}
to_heaptop=to_heapbase+INITIALHEAPSIZE;
INTPTR to_heapsize=to_heaptop-to_heapbase;
INTPTR last_heapsize=0;
if (lastgcsize>0) {
- last_heapsize=HEAPSIZE(lastgcsize, size);
- if ((last_heapsize&7)!=0)
- last_heapsize+=(8-(last_heapsize%8));
+ last_heapsize=HEAPSIZE(lastgcsize, size);
+ if ((last_heapsize&7)!=0)
+ last_heapsize+=(8-(last_heapsize%8));
}
if (curr_heapsize>last_heapsize)
- last_heapsize=curr_heapsize;
+ last_heapsize=curr_heapsize;
if (last_heapsize>to_heapsize) {
- free(to_heapbase);
- to_heapbase=malloc(last_heapsize);
- if (to_heapbase==NULL) {
- printf("Error Allocating enough memory\n");
- exit(-1);
- }
- to_heaptop=to_heapbase+last_heapsize;
- to_heapptr=to_heapbase;
+ free(to_heapbase);
+ to_heapbase=malloc(last_heapsize);
+ if (to_heapbase==NULL) {
+ printf("Error Allocating enough memory\n");
+ exit(-1);
+ }
+ to_heaptop=to_heapbase+last_heapsize;
+ to_heapptr=to_heapbase;
}
}
{
int i;
for(i=0; i<MAXSTATS; i++) {
- if (garbagearray[i]!=0)
- printf("Type=%d Size=%u\n", i, garbagearray[i]);
+ if (garbagearray[i]!=0)
+ printf("Type=%d Size=%u\n", i, garbagearray[i]);
}
}
#endif
/* Not enough room :(, redo gc */
if (curr_heapptr>curr_heapgcpoint) {
#if defined(THREADS)||defined(DSTM)||defined(STM)||defined(MLP)
- pthread_mutex_unlock(&gclock);
+ pthread_mutex_unlock(&gclock);
#endif
- return mygcmalloc(stackptr, size);
+ return mygcmalloc(stackptr, size);
}
bzero(tmp, curr_heaptop-tmp);
if ((!(((unsigned int)orig)&0x1))) { \
if (orig>=curr_heapbase&&orig<curr_heaptop) { \
void *copy; \
- if (gc_createcopy(orig,©)) \
- enqueue(copy); \
+ if (gc_createcopy(orig,©)) \
+ enqueue(copy); \
dst=copy; \
} \
}
#define ENQUEUE(orig, dst) \
if (orig>=curr_heapbase&&orig<curr_heaptop) { \
void *copy; \
- if (gc_createcopy(orig,©)) \
- enqueue(copy); \
+ if (gc_createcopy(orig,©)) \
+ enqueue(copy); \
dst=copy; \
}
#define SENQUEUE(orig, dst) \
{ \
void *copy; \
- if (gc_createcopy(orig,©)) \
- enqueue(copy); \
+ if (gc_createcopy(orig,©)) \
+ enqueue(copy); \
dst=copy; \
}
#elif defined(FASTCHECK)
#define ENQUEUE(orig, dst) \
if (((unsigned int)orig)!=1) { \
void *copy; \
- if (gc_createcopy(orig,©)) \
- enqueue(copy); \
+ if (gc_createcopy(orig,©)) \
+ enqueue(copy); \
dst=copy; }
#else
#define ENQUEUE(orig, dst) \
if (orig!=NULL) { \
void *copy; \
- if (gc_createcopy(orig,©)) \
- enqueue(copy); \
+ if (gc_createcopy(orig,©)) \
+ enqueue(copy); \
dst=copy; \
}
#endif
if(hasgc < 5) {
// start gc
while(gcflag) {
- gc(stackptr);
+ gc(stackptr);
}
hasgc++;
} else {
static inline int atomicincandread(volatile unsigned int *lock) {
int retval=1;
__asm__ __volatile__ ("lock; xadd %0,%1"
- : "=r" (retval)
- : "m" (*lock), "0" (retval)
- : "memory");
+ : "=r" (retval)
+ : "m" (*lock), "0" (retval)
+ : "memory");
return retval;
}
static inline void atomic_dec(volatile int *v) {
__asm__ __volatile__ (LOCK_PREFIX "decl %0"
- : "+m" (*v));
+ : "+m" (*v));
}
static inline void atomic_inc(volatile int *v) {
__asm__ __volatile__ (LOCK_PREFIX "incl %0"
- : "+m" (*v));
+ : "+m" (*v));
}
// this returns TRUE if the atomic subtraction results in
unsigned char c;
__asm__ __volatile__ (LOCK_PREFIX "subl %2,%0; sete %1"
- : "+m" (*v), "=qm" (c)
- : "ir" (i) : "memory");
+ : "+m" (*v), "=qm" (c)
+ : "ir" (i) : "memory");
return c;
}
static inline void atomic_add(int i, volatile int *v) {
__asm__ __volatile__ (LOCK_PREFIX "addl %1,%0"
- : "+m" (*v)
- : "ir" (i));
+ : "+m" (*v)
+ : "ir" (i));
}
static inline int LOCKXCHG32(volatile int* ptr, int val) {
int retval;
//note: xchgl always implies lock
__asm__ __volatile__ ("xchgl %0,%1"
- : "=r" (retval)
- : "m" (*ptr), "0" (val)
- : "memory");
+ : "=r" (retval)
+ : "m" (*ptr), "0" (val)
+ : "memory");
return retval;
}
INTPTR retval;
//note: xchgl always implies lock
__asm__ __volatile__ ("xchgq %0,%1"
- : "=r" (retval)
- : "m" (*ptr), "0" (val)
- : "memory");
+ : "=r" (retval)
+ : "m" (*ptr), "0" (val)
+ : "memory");
return retval;
}
static inline INTPTR CAS(volatile void *ptr, unsigned INTPTR old, unsigned INTPTR new) {
unsigned INTPTR prev;
__asm__ __volatile__ ("lock; cmpxchgq %1,%2"
- : "=a" (prev)
- : "r" (new), "m" (*__xg(ptr)), "0" (old)
- : "memory");
+ : "=a" (prev)
+ : "r" (new), "m" (*__xg(ptr)), "0" (old)
+ : "memory");
return prev;
}
static inline long CAS32(volatile void *ptr, unsigned long old, unsigned long new) {
unsigned long prev;
__asm__ __volatile__ ("lock; cmpxchgl %k1,%2"
- : "=a" (prev)
- : "r" (new), "m" (*__xg(ptr)), "0" (old)
- : "memory");
+ : "=a" (prev)
+ : "r" (new), "m" (*__xg(ptr)), "0" (old)
+ : "memory");
return prev;
}
#else
static inline long CAS(volatile void *ptr, unsigned long old, unsigned long new) {
unsigned long prev;
__asm__ __volatile__ ("lock; cmpxchgl %k1,%2"
- : "=a" (prev)
- : "r" (new), "m" (*__xg(ptr)), "0" (old)
- : "memory");
+ : "=a" (prev)
+ : "r" (new), "m" (*__xg(ptr)), "0" (old)
+ : "memory");
return prev;
}
#define CAS32 CAS
if(val==NULL) {
//queue is null, first case
if(*(r->pointer)!=0) {
- // check whether pointer is already resolved, or not.
- table->unresolvedQueue=NULL; //released lock;
- return ADDTABLEITEM(table,r,TRUE);
+ // check whether pointer is already resolved, or not.
+ table->unresolvedQueue=NULL; //released lock;
+ return ADDTABLEITEM(table,r,TRUE);
}
struct Queue* queue=createQueue();
addNewItemBack(queue,r);
if (T->item.status==READY) {
for(; val!=NULL; val=val->next) {
if (val==((BinItem *)b)) {
- //ready to retire
- retval=READY;
- if (isParent(r)) {
- b->item.status=retval; //unsure if really needed at this point..
- be->head=NULL; // released lock
- return retval;
- }
- break;
+ //ready to retire
+ retval=READY;
+ if (isParent(r)) {
+ b->item.status=retval; //unsure if really needed at this point..
+ be->head=NULL; // released lock
+ return retval;
+ }
+ break;
} else if (val->total!=0) {
- break;
+ break;
}
}
}
flag=(void*)LOCKXCHG((unsigned INTPTR*)&(V->array[index]), (unsigned INTPTR)flag);
if (flag!=NULL) {
if (isParentCoarse(r)) { //parent's retire immediately
- atomic_dec(&V->item.total);
- V->index--;
+ atomic_dec(&V->item.total);
+ V->index--;
} else {
#if defined(RCR)&&!defined(OOO_DISABLE_TASKMEMPOOL)
- if (atomic_sub_and_test(1, &r->count))
- poolfreeinto(Q->rentrypool, r);
+ if (atomic_sub_and_test(1, &r->count))
+ poolfreeinto(Q->rentrypool, r);
#endif
}
return READY;
if (flag!=NULL) {
#if defined(RCR)&&!defined(OOO_DISABLE_TASKMEMPOOL)
if (atomic_sub_and_test(1, &r->count))
- poolfreeinto(Q->rentrypool, r);
+ poolfreeinto(Q->rentrypool, r);
#endif
return READY;
} else {
int i;
while (ptr!=NULL) {
if (isReadBinItem(ptr)) {
- ReadBinItem* rptr=(ReadBinItem*)ptr;
- if (rptr->item.status==NOTREADY) {
- for (i=0; i<rptr->index; i++) {
- resolveDependencies(rptr->array[i]);
- if (isParent(rptr->array[i])) {
- //parents go immediately
- atomic_dec(&rptr->item.total);
- atomic_dec(&T->item.total);
- }
- }
- }
- rptr->item.status=READY;
- if (rptr->item.next==NULL) {
- break;
- }
- if (rptr->item.total!=0) {
- haveread=TRUE;
- } else if ((BinItem*)rptr==val) {
- val=val->next;
- }
+ ReadBinItem* rptr=(ReadBinItem*)ptr;
+ if (rptr->item.status==NOTREADY) {
+ for (i=0; i<rptr->index; i++) {
+ resolveDependencies(rptr->array[i]);
+ if (isParent(rptr->array[i])) {
+ //parents go immediately
+ atomic_dec(&rptr->item.total);
+ atomic_dec(&T->item.total);
+ }
+ }
+ }
+ rptr->item.status=READY;
+ if (rptr->item.next==NULL) {
+ break;
+ }
+ if (rptr->item.total!=0) {
+ haveread=TRUE;
+ } else if ((BinItem*)rptr==val) {
+ val=val->next;
+ }
} else if(isWriteBinItem(ptr)) {
- if (haveread)
- break;
- if(ptr->status==NOTREADY) {
- resolveDependencies(((WriteBinItem*)ptr)->val);
- ptr->status=READY;
- if(isParent(((WriteBinItem*)ptr)->val)) {
- atomic_dec(&T->item.total);
- val=val->next;
- } else
- break;
- } else { // write bin is already resolved
- val=val->next;
- }
- /*
- if(ptr->status==NOTREADY) {
- resolveDependencies(((WriteBinItem*)ptr)->val);
- }
- ptr->status=READY;
- if (isParent(((WriteBinItem*)ptr)->val)) {
- atomic_dec(&T->item.total);
- //val=val->next;
- val=ptr->next;
- } else
- break;
- }
- */
+ if (haveread)
+ break;
+ if(ptr->status==NOTREADY) {
+ resolveDependencies(((WriteBinItem*)ptr)->val);
+ ptr->status=READY;
+ if(isParent(((WriteBinItem*)ptr)->val)) {
+ atomic_dec(&T->item.total);
+ val=val->next;
+ } else
+ break;
+ } else { // write bin is already resolved
+ val=val->next;
+ }
+ /*
+ if(ptr->status==NOTREADY) {
+ resolveDependencies(((WriteBinItem*)ptr)->val);
+ }
+ ptr->status=READY;
+ if (isParent(((WriteBinItem*)ptr)->val)) {
+ atomic_dec(&T->item.total);
+ //val=val->next;
+ val=ptr->next;
+ } else
+ break;
+ }
+ */
}
ptr=ptr->next;
}
if (head->next==NULL||head->total!=0) {
//item is not finished
if (head->status!=READY) {
- //need to update status
- head->status=READY;
- if (isHashtable(head)) {
- RESOLVEHASHTABLE(Q, (Hashtable *) head);
- } else if (isVector(head)) {
- RESOLVEVECTOR(Q, (Vector *) head);
- } else if (isSingleItem(head)) {
- RESOLVESCC(Q, (SCC *)head);
- }
- if (head->next==NULL)
- break;
- if (head->total!=0)
- break;
+ //need to update status
+ head->status=READY;
+ if (isHashtable(head)) {
+ RESOLVEHASHTABLE(Q, (Hashtable *) head);
+ } else if (isVector(head)) {
+ RESOLVEVECTOR(Q, (Vector *) head);
+ } else if (isSingleItem(head)) {
+ RESOLVESCC(Q, (SCC *)head);
+ }
+ if (head->next==NULL)
+ break;
+ if (head->total!=0)
+ break;
} else
- break;
+ break;
}
MemoryQueueItem* nextitem=head->next;
CAS((unsigned INTPTR*)&(Q->head), (unsigned INTPTR)head, (unsigned INTPTR)nextitem);
BinItem* ptr=val;
if(ptr!=NULL&&ptr->status==NOTREADY) {
do {
- if (isWriteBinItem(ptr)) {
- if (haveread)
- break;
- resolveDependencies(((WriteBinItem*)ptr)->val);
- ptr->status=READY;
- if (isParent(((WriteBinItem*)ptr)->val)) {
- atomic_dec(&T->item.total);
- val=val->next;
- } else
- break;
- } else if (isReadBinItem(ptr)) {
- int i;
- ReadBinItem* rptr=(ReadBinItem*)ptr;
- for(i=0; i<rptr->index; i++) {
- resolveDependencies(rptr->array[i]);
- if (isParent(rptr->array[i])) {
- atomic_dec(&rptr->item.total);
- atomic_dec(&T->item.total);
- }
- }
- if (rptr->item.next==NULL||rptr->item.total!=0) {
- haveread=TRUE;
- } else if((BinItem*)rptr==val) {
- val=val->next;
- }
- rptr->item.status=READY;
- }
- ptr=ptr->next;
+ if (isWriteBinItem(ptr)) {
+ if (haveread)
+ break;
+ resolveDependencies(((WriteBinItem*)ptr)->val);
+ ptr->status=READY;
+ if (isParent(((WriteBinItem*)ptr)->val)) {
+ atomic_dec(&T->item.total);
+ val=val->next;
+ } else
+ break;
+ } else if (isReadBinItem(ptr)) {
+ int i;
+ ReadBinItem* rptr=(ReadBinItem*)ptr;
+ for(i=0; i<rptr->index; i++) {
+ resolveDependencies(rptr->array[i]);
+ if (isParent(rptr->array[i])) {
+ atomic_dec(&rptr->item.total);
+ atomic_dec(&T->item.total);
+ }
+ }
+ if (rptr->item.next==NULL||rptr->item.total!=0) {
+ haveread=TRUE;
+ } else if((BinItem*)rptr==val) {
+ val=val->next;
+ }
+ rptr->item.status=READY;
+ }
+ ptr=ptr->next;
} while(ptr!=NULL);
}
bin->head=val; // released lock;
REntry* val=NULL;
val=(REntry*)LOCKXCHG((unsigned INTPTR*)&(tmp->array[i]), (unsigned INTPTR)val);
if (val!=NULL) {
- SESEcommon *seseCommon=val->seseRec;
- resolveDependencies(val);
- if (isParent(val)) {
- atomic_dec(&tmp->item.total);
+ SESEcommon *seseCommon=val->seseRec;
+ resolveDependencies(val);
+ if (isParent(val)) {
+ atomic_dec(&tmp->item.total);
#ifdef RCR
- poolfreeinto(q->rentrypool,val);
+ poolfreeinto(q->rentrypool,val);
#endif
- }
+ }
#if defined(RCR)&&!defined(OOO_DISABLE_TASKMEMPOOL)
- else if (atomic_sub_and_test(1, &((REntry *)val)->count))
- poolfreeinto(q->rentrypool,val);
- RELEASE_REFERENCE_TO(seseCommon);
+ else if (atomic_sub_and_test(1, &((REntry *)val)->count))
+ poolfreeinto(q->rentrypool,val);
+ RELEASE_REFERENCE_TO(seseCommon);
#endif
}
}
mask=mask>>shift;
index+=shift;
if(atomic_sub_and_test(1, &array[index].flag)) {
- if(atomic_sub_and_test(1, &(seseCommon->unresolvedDependencies)))
- workScheduleSubmit((void *)seseCommon);
+ if(atomic_sub_and_test(1, &(seseCommon->unresolvedDependencies)))
+ workScheduleSubmit((void *)seseCommon);
}
}
} else if (type==PARENTCOARSE) {
if(r->type==WRITE) {
int key=generateKey(OBJPTRPTR_2_OBJOID(r->pointer) );
if(q->binbuf[key]==NULL) {
- // for multiple writes, add only the first write that hashes to the same bin
- q->binbuf[key]=r;
+ // for multiple writes, add only the first write that hashes to the same bin
+ q->binbuf[key]=r;
} else {
- q->buf[i]=NULL;
+ q->buf[i]=NULL;
}
}
}
if(r!=NULL && r->type==READ) {
int key=generateKey(OBJPTRPTR_2_OBJOID(r->pointer) );
if(q->binbuf[key]==NULL) {
- // read item that hashes to the bin which doen't contain any write
- seseCommon->rentryArray[seseCommon->rentryIdx++]=r;
- if(ADDTABLEITEM(table, r, FALSE)==READY) {
- resolveDependencies(r);
- }
+ // read item that hashes to the bin which doen't contain any write
+ seseCommon->rentryArray[seseCommon->rentryIdx++]=r;
+ if(ADDTABLEITEM(table, r, FALSE)==READY) {
+ resolveDependencies(r);
+ }
}
q->buf[i]=NULL;
}
if(r!=NULL) {
seseCommon->rentryArray[seseCommon->rentryIdx++]=r;
if(ADDTABLEITEM(table, r, FALSE)==READY) {
- resolveDependencies(r);
+ resolveDependencies(r);
}
}
}
r->queue=q;
r->isBufMode=TRUE;
if(ADDRENTRY(q,r)==NOTREADY) {
- localCount++;
+ localCount++;
}
}
return localCount;
if(r->type==WRITE) {
int key=generateKey(OBJPTRPTR_2_OBJOID(r->pointer) );
if(q->binbuf[key]==NULL) {
- // for multiple writes, add only the first write that hashes to the same bin
- q->binbuf[key]=r;
+ // for multiple writes, add only the first write that hashes to the same bin
+ q->binbuf[key]=r;
} else {
- q->buf[i]=NULL;
+ q->buf[i]=NULL;
}
}
}
if(r!=NULL && r->type==READ) {
int key=generateKey(OBJPTRPTR_2_OBJOID(r->pointer) );
if(q->binbuf[key]==NULL) {
- // read item that hashes to the bin which doen't contain any write
- seseCommon->rentryArray[seseCommon->rentryIdx++]=r;
- if(ADDRENTRY(q,r)==NOTREADY) {
- localCount++;
- }
+ // read item that hashes to the bin which doen't contain any write
+ seseCommon->rentryArray[seseCommon->rentryIdx++]=r;
+ if(ADDRENTRY(q,r)==NOTREADY) {
+ localCount++;
+ }
}
q->buf[i]=NULL;
}
if(r!=NULL) {
seseCommon->rentryArray[seseCommon->rentryIdx++]=r;
if(ADDRENTRY(q,r)==NOTREADY) {
- localCount++;
+ localCount++;
}
}
}
do {
struct QueueItem* head=getHead(val);
if(head!=NULL) {
- REntry* rentry=(REntry*)head->objectptr;
- if(*(rentry->pointer)==0) {
- // encounters following unresolved pointer
- table->unresolvedQueue=val; //released lock
- break;
- }
- removeItem(val,head);
-
- //now, address is resolved
-
- //check if rentry is buffer mode
- if(rentry->isBufMode==TRUE) {
- if(currentSESE==0) {
- queue=rentry->queue;
- INITIALIZEBUF(queue);
- currentSESE=(INTPTR)rentry;
- ADDRENTRYTOBUF(queue,rentry);
- } else if(currentSESE==(INTPTR)rentry) {
- ADDRENTRYTOBUF(queue,rentry);
- } else if(currentSESE!=(INTPTR)rentry) {
- RESOLVEBUFFORHASHTABLE(queue,table,(SESEcommon*)rentry->seseRec);
- currentSESE=(INTPTR)rentry;
- INITIALIZEBUF(queue);
- ADDRENTRYTOBUF(rentry->queue,rentry);
- }
- } else {
- if(currentSESE!=0) {
- //previous SESE has buf mode, need to invoke resolve buffer
- RESOLVEBUFFORHASHTABLE(queue,table,(SESEcommon*)rentry->seseRec);
- currentSESE=0;
- }
- //normal mode
- if(ADDTABLEITEM(table, rentry, FALSE)==READY) {
- resolveDependencies(rentry);
- }
- }
+ REntry* rentry=(REntry*)head->objectptr;
+ if(*(rentry->pointer)==0) {
+ // encounters following unresolved pointer
+ table->unresolvedQueue=val; //released lock
+ break;
+ }
+ removeItem(val,head);
+
+ //now, address is resolved
+
+ //check if rentry is buffer mode
+ if(rentry->isBufMode==TRUE) {
+ if(currentSESE==0) {
+ queue=rentry->queue;
+ INITIALIZEBUF(queue);
+ currentSESE=(INTPTR)rentry;
+ ADDRENTRYTOBUF(queue,rentry);
+ } else if(currentSESE==(INTPTR)rentry) {
+ ADDRENTRYTOBUF(queue,rentry);
+ } else if(currentSESE!=(INTPTR)rentry) {
+ RESOLVEBUFFORHASHTABLE(queue,table,(SESEcommon*)rentry->seseRec);
+ currentSESE=(INTPTR)rentry;
+ INITIALIZEBUF(queue);
+ ADDRENTRYTOBUF(rentry->queue,rentry);
+ }
+ } else {
+ if(currentSESE!=0) {
+ //previous SESE has buf mode, need to invoke resolve buffer
+ RESOLVEBUFFORHASHTABLE(queue,table,(SESEcommon*)rentry->seseRec);
+ currentSESE=0;
+ }
+ //normal mode
+ if(ADDTABLEITEM(table, rentry, FALSE)==READY) {
+ resolveDependencies(rentry);
+ }
+ }
} else {
- table->unresolvedQueue=NULL; // set hashtable as normal-mode.
- break;
+ table->unresolvedQueue=NULL; // set hashtable as normal-mode.
+ break;
}
} while(TRUE);
} else {
lpair->islastlock=1;
while(1) {
if (VAR(___this___)->tid==0) {
- if (CAS32(&VAR(___this___)->tid, 0, self)==0) {
- return;
- }
+ if (CAS32(&VAR(___this___)->tid, 0, self)==0) {
+ return;
+ }
}
{
#ifdef PRECISE_GC
- if (unlikely(needtocollect))
- checkcollect((struct garbagelist *)___params___);
+ if (unlikely(needtocollect))
+ checkcollect((struct garbagelist *)___params___);
#endif
}
}
while(1) {
if (VAR(___this___)->tid==0) {
if (CAS32(&VAR(___this___)->tid, 0, self)==0) {
- BARRIER();
- return;
+ BARRIER();
+ return;
}
}
#ifdef PRECISE_GC
di=dq->head;
do {
- // check all the relevant indices of this
- // node in the deque, noting if we are in
- // the top/bottom node which can be partially
- // full
+ // check all the relevant indices of this
+ // node in the deque, noting if we are in
+ // the top/bottom node which can be partially
+ // full
- // WHAT?
- //SESEcommon* common = (SESEcommon*) n->itsDataArr[j];
- //if(common==seseCommon){
- // skip the current running SESE
- // continue;
- //}
- di=(dequeItem *) EXTRACTPTR((INTPTR)di);
- SESEcommon* seseRec = (SESEcommon*) di->work;
- if (seseRec!=NULL) {
- struct garbagelist* gl = (struct garbagelist*) &(seseRec[1]);
- struct garbagelist* glroot = gl;
+ // WHAT?
+ //SESEcommon* common = (SESEcommon*) n->itsDataArr[j];
+ //if(common==seseCommon){
+ // skip the current running SESE
+ // continue;
+ //}
+ di=(dequeItem *) EXTRACTPTR((INTPTR)di);
+ SESEcommon* seseRec = (SESEcommon*) di->work;
+ if (seseRec!=NULL) {
+ struct garbagelist* gl = (struct garbagelist*) &(seseRec[1]);
+ struct garbagelist* glroot = gl;
- updateAscendantSESE(seseRec);
+ updateAscendantSESE(seseRec);
- while( gl != NULL ) {
- int k;
- for( k = 0; k < gl->size; k++ ) {
- void* orig = gl->array[k];
- ENQUEUE(orig, gl->array[k]);
- }
- gl = gl->next;
- }
- }
- // we only have to move across the nodes
- // of the deque if the top and bottom are
- // not the same already
- di=di->next;
+ while( gl != NULL ) {
+ int k;
+ for( k = 0; k < gl->size; k++ ) {
+ void* orig = gl->array[k];
+ ENQUEUE(orig, gl->array[k]);
+ }
+ gl = gl->next;
+ }
+ }
+ // we only have to move across the nodes
+ // of the deque if the top and bottom are
+ // not the same already
+ di=di->next;
} while( di !=NULL);
}
}
n = botNode;
do {
- // check all the relevant indices of this
- // node in the deque, noting if we are in
- // the top/bottom node which can be partially
- // full
- if( n == botNode ) {
- jLo = botIndx;
- } else { jLo = 0; }
- if( n == topNode ) {
- jHi = topIndx;
- } else { jHi = DQNODE_ARRAYSIZE; }
+ // check all the relevant indices of this
+ // node in the deque, noting if we are in
+ // the top/bottom node which can be partially
+ // full
+ if( n == botNode ) {
+ jLo = botIndx;
+ } else { jLo = 0; }
+ if( n == topNode ) {
+ jHi = topIndx;
+ } else { jHi = DQNODE_ARRAYSIZE; }
- for( j = jLo; j < jHi; ++j ) {
+ for( j = jLo; j < jHi; ++j ) {
- // WHAT?
- //SESEcommon* common = (SESEcommon*) n->itsDataArr[j];
- //if(common==seseCommon){
- // continue;
- //}
+ // WHAT?
+ //SESEcommon* common = (SESEcommon*) n->itsDataArr[j];
+ //if(common==seseCommon){
+ // continue;
+ //}
- SESEcommon* seseRec = (SESEcommon*) n->itsDataArr[j];
+ SESEcommon* seseRec = (SESEcommon*) n->itsDataArr[j];
- struct garbagelist* gl = (struct garbagelist*) &(seseRec[1]);
- struct garbagelist* glroot = gl;
+ struct garbagelist* gl = (struct garbagelist*) &(seseRec[1]);
+ struct garbagelist* glroot = gl;
- updateAscendantSESE(seseRec);
+ updateAscendantSESE(seseRec);
- while( gl != NULL ) {
- int k;
- for( k = 0; k < gl->size; k++ ) {
- void* orig = gl->array[k];
- ENQUEUE(orig, gl->array[k]);
- }
- gl = gl->next;
- }
- }
+ while( gl != NULL ) {
+ int k;
+ for( k = 0; k < gl->size; k++ ) {
+ void* orig = gl->array[k];
+ ENQUEUE(orig, gl->array[k]);
+ }
+ gl = gl->next;
+ }
+ }
- // we only have to move across the nodes
- // of the deque if the top and bottom are
- // not the same already
- if( botNode != topNode ) {
- n = n->next;
- }
+ // we only have to move across the nodes
+ // of the deque if the top and bottom are
+ // not the same already
+ if( botNode != topNode ) {
+ n = n->next;
+ }
} while( n != topNode );
}
}
while(gl!=NULL) {
int i;
for(i=0; i<gl->size; i++) {
- void * orig=gl->array[i];
- ENQUEUE(orig, gl->array[i]);
+ void * orig=gl->array[i];
+ ENQUEUE(orig, gl->array[i]);
}
gl=gl->next;
}
MemoryQueueItem *memoryItem=memoryQueue->head;
while(memoryItem!=NULL) {
if(memoryItem->type==HASHTABLE) {
- Hashtable *ht=(Hashtable*)memoryItem;
- for(binidx=0; binidx<NUMBINS; binidx++) {
- BinElement *bin=ht->array[binidx];
- BinItem *binItem=bin->head;
- while(binItem!=NULL) {
- if(binItem->type==READBIN) {
- ReadBinItem* readBinItem=(ReadBinItem*)binItem;
- int ridx;
- for(ridx=0; ridx<readBinItem->index; ridx++) {
- REntry *rentry=readBinItem->array[ridx];
- SESEcommon* seseRec = (SESEcommon*)(rentry->seseRec);
- struct garbagelist * gl= (struct garbagelist *)&(seseRec[1]);
- updateAscendantSESE(seseRec);
- while(gl!=NULL) {
- int i;
- for(i=0; i<gl->size; i++) {
- void * orig=gl->array[i];
- ENQUEUE(orig, gl->array[i]);
- }
- gl=gl->next;
- }
- }
- } else { //writebin
- REntry *rentry=((WriteBinItem*)binItem)->val;
- SESEcommon* seseRec = (SESEcommon*)(rentry->seseRec);
- struct garbagelist * gl= (struct garbagelist *)&(seseRec[1]);
- updateAscendantSESE(seseRec);
- while(gl!=NULL) {
- int i;
- for(i=0; i<gl->size; i++) {
- void * orig=gl->array[i];
- ENQUEUE(orig, gl->array[i]);
- }
- gl=gl->next;
- }
- }
- binItem=binItem->next;
- }
- }
+ Hashtable *ht=(Hashtable*)memoryItem;
+ for(binidx=0; binidx<NUMBINS; binidx++) {
+ BinElement *bin=ht->array[binidx];
+ BinItem *binItem=bin->head;
+ while(binItem!=NULL) {
+ if(binItem->type==READBIN) {
+ ReadBinItem* readBinItem=(ReadBinItem*)binItem;
+ int ridx;
+ for(ridx=0; ridx<readBinItem->index; ridx++) {
+ REntry *rentry=readBinItem->array[ridx];
+ SESEcommon* seseRec = (SESEcommon*)(rentry->seseRec);
+ struct garbagelist * gl= (struct garbagelist *)&(seseRec[1]);
+ updateAscendantSESE(seseRec);
+ while(gl!=NULL) {
+ int i;
+ for(i=0; i<gl->size; i++) {
+ void * orig=gl->array[i];
+ ENQUEUE(orig, gl->array[i]);
+ }
+ gl=gl->next;
+ }
+ }
+ } else { //writebin
+ REntry *rentry=((WriteBinItem*)binItem)->val;
+ SESEcommon* seseRec = (SESEcommon*)(rentry->seseRec);
+ struct garbagelist * gl= (struct garbagelist *)&(seseRec[1]);
+ updateAscendantSESE(seseRec);
+ while(gl!=NULL) {
+ int i;
+ for(i=0; i<gl->size; i++) {
+ void * orig=gl->array[i];
+ ENQUEUE(orig, gl->array[i]);
+ }
+ gl=gl->next;
+ }
+ }
+ binItem=binItem->next;
+ }
+ }
} else if(memoryItem->type==VECTOR) {
- Vector *vt=(Vector*)memoryItem;
- int idx;
- for(idx=0; idx<vt->index; idx++) {
- REntry *rentry=vt->array[idx];
- if(rentry!=NULL) {
- SESEcommon* seseRec = (SESEcommon*)(rentry->seseRec);
- struct garbagelist * gl= (struct garbagelist *)&(seseRec[1]);
- updateAscendantSESE(seseRec);
- while(gl!=NULL) {
- int i;
- for(i=0; i<gl->size; i++) {
- void * orig=gl->array[i];
- ENQUEUE(orig, gl->array[i]);
- }
- gl=gl->next;
- }
- }
- }
+ Vector *vt=(Vector*)memoryItem;
+ int idx;
+ for(idx=0; idx<vt->index; idx++) {
+ REntry *rentry=vt->array[idx];
+ if(rentry!=NULL) {
+ SESEcommon* seseRec = (SESEcommon*)(rentry->seseRec);
+ struct garbagelist * gl= (struct garbagelist *)&(seseRec[1]);
+ updateAscendantSESE(seseRec);
+ while(gl!=NULL) {
+ int i;
+ for(i=0; i<gl->size; i++) {
+ void * orig=gl->array[i];
+ ENQUEUE(orig, gl->array[i]);
+ }
+ gl=gl->next;
+ }
+ }
+ }
} else if(memoryItem->type==SINGLEITEM) {
- SCC *scc=(SCC*)memoryItem;
- REntry *rentry=scc->val;
- if(rentry!=NULL) {
- SESEcommon* seseRec = (SESEcommon*)(rentry->seseRec);
- struct garbagelist * gl= (struct garbagelist *)&(seseRec[1]);
- updateAscendantSESE(seseRec);
- while(gl!=NULL) {
- int i;
- for(i=0; i<gl->size; i++) {
- void * orig=gl->array[i];
- ENQUEUE(orig, gl->array[i]);
- }
- gl=gl->next;
- }
- }
+ SCC *scc=(SCC*)memoryItem;
+ REntry *rentry=scc->val;
+ if(rentry!=NULL) {
+ SESEcommon* seseRec = (SESEcommon*)(rentry->seseRec);
+ struct garbagelist * gl= (struct garbagelist *)&(seseRec[1]);
+ updateAscendantSESE(seseRec);
+ while(gl!=NULL) {
+ int i;
+ for(i=0; i<gl->size; i++) {
+ void * orig=gl->array[i];
+ ENQUEUE(orig, gl->array[i]);
+ }
+ gl=gl->next;
+ }
+ }
}
memoryItem=memoryItem->next;
}
if(prevSESE!=NULL) {
struct garbagelist * prevgl=(struct garbagelist *)&(((SESEcommon*)(prevSESE))[1]);
while(prevgl!=NULL) {
- int i;
- for(i=0; i<prevgl->size; i++) {
- void * orig=prevgl->array[i];
- ENQUEUE(orig, prevgl->array[i]);
- }
- prevgl=prevgl->next;
+ int i;
+ for(i=0; i<prevgl->size; i++) {
+ void * orig=prevgl->array[i];
+ ENQUEUE(orig, prevgl->array[i]);
+ }
+ prevgl=prevgl->next;
}
}
}
options=strchr(options,' ');
if (options!=NULL) options++;
if (options==NULL)
- break;
+ break;
sscanf(options, "%f", &failurechance);
injectfailures=1;
printf("Injecting errors with chance=%f\n",failurechance);
options=strchr(options,' ');
if (options!=NULL) options++;
if (options==NULL)
- break;
+ break;
sscanf(options, "%d", &failurecount);
options=strchr(options,' ');
if (options!=NULL) options++;
if (options==NULL)
- break;
+ break;
sscanf(options, "%f", &instfailurechance);
options=strchr(options,' ');
if (options!=NULL) options++;
if (options==NULL)
- break;
+ break;
sscanf(options, "%d", &numfailures);
options=strchr(options,' ');
if (i>NUMCLASSES) {
do {
if (i==type)
- return 1;
+ return 1;
i=typearray2[i-NUMCLASSES];
} while(i!=-1);
}
instaccum+=failurecount;
if ((((double)random())/RAND_MAX)<instfailurechance) {
if (numfailures>0)
- numfailures--;
+ numfailures--;
printf("FAILURE!!! %d\n",numfailures);
longjmp(error_handler,11);
}
instaccum+=failurecount;
if ((((double)random())/RAND_MAX)<instfailurechance) {
if (numfailures>0)
- numfailures--;
+ numfailures--;
printf("FAILURE!!! %d\n",numfailures);
threadexit();
}
struct ___Object___ * ptr=((struct ___Object___**)(((char*) &aosrc->___length___)+sizeof(int)))[i];
int ptrtype=((int *)ptr)[0];
if (ptrtype>=NUMCLASSES) {
- struct ___Object___ * dstptr=((struct ___Object___**)(((char*) &aodst->___length___)+sizeof(int)))[i];
- deepArrayCopy(dstptr,ptr);
+ struct ___Object___ * dstptr=((struct ___Object___**)(((char*) &aodst->___length___)+sizeof(int)))[i];
+ deepArrayCopy(dstptr,ptr);
} else {
- //hit an object
- ((struct ___Object___ **)(((char*) &aodst->___length___)+sizeof(int)))[i]=ptr;
+ //hit an object
+ ((struct ___Object___ **)(((char*) &aodst->___length___)+sizeof(int)))[i]=ptr;
}
}
}
free(to_heapbase);
to_heapbase=malloc(curr_heapsize);
if (to_heapbase==NULL) {
- printf("Error Allocating enough memory\n");
- exit(-1);
+ printf("Error Allocating enough memory\n");
+ exit(-1);
}
to_heaptop=to_heapbase+curr_heapsize;
to_heapptr=to_heapbase;
struct ArrayObject *bytearray;
#ifdef PRECISE_GC
{
- INTPTR ptrarray[]={1, (INTPTR) ___params___, (INTPTR)arraybytearray};
- bytearray=allocate_newarray(&ptrarray,BYTEARRAYTYPE,h->h_length);
- arraybytearray=(struct ArrayObject *) ptrarray[2];
+ INTPTR ptrarray[]={1, (INTPTR) ___params___, (INTPTR)arraybytearray};
+ bytearray=allocate_newarray(&ptrarray,BYTEARRAYTYPE,h->h_length);
+ arraybytearray=(struct ArrayObject *) ptrarray[2];
}
#else
bytearray=allocate_newarray(BYTEARRAYTYPE,h->h_length);
#endif
((void **)&((&arraybytearray->___length___)[1]))[i]=bytearray;
{
- int ha=ntohl(*(int *)h->h_addr_list[i]);
- (&bytearray->___length___)[1]=ha;
+ int ha=ntohl(*(int *)h->h_addr_list[i]);
+ (&bytearray->___length___)[1]=ha;
}
}
while(length>0) {
bytewritten=write(fd, &charstr[offset], length);
if (bytewritten==-1&&errno!=EAGAIN)
- break;
+ break;
length-=bytewritten;
offset+=bytewritten;
}
//remove if we can..steal work no matter what
if (likely(next!=NULL)) {
if (((dequeItem *)CAS(&(p->head),(INTPTR)ptr, (INTPTR)next))!=ptr)
- return DQ_POP_EMPTY;
+ return DQ_POP_EMPTY;
void * item=NULL;
item=(void *)LOCKXCHG((unsigned INTPTR*) &(realptr->work), (unsigned INTPTR) item);
realptr->next=NULL;
BARRIER();
tagpoolfreeinto(&p->objret,ptr, realptr);
if (item==NULL&&tryagain) {
- tryagain=0;
- continue;
+ tryagain=0;
+ continue;
}
return item;
} else {
void * item=NULL;
if (realptr->work!=NULL)
- item=(void *) LOCKXCHG((unsigned INTPTR*) &(realptr->work), (unsigned INTPTR) item);
+ item=(void *) LOCKXCHG((unsigned INTPTR*) &(realptr->work), (unsigned INTPTR) item);
return item;
}
}
if (tagptr->type==TAGTYPE) {
struct ___TagDescriptor___ * td=(struct ___TagDescriptor___ *) tagptr;
if (td==tagd)
- return;
+ return;
#ifdef PRECISE_GC
int ptrarray[]={2, (int) ptr, (int) obj, (int)tagd};
struct ArrayObject * ao=allocate_newarray(&ptrarray,TAGARRAYTYPE,TAGARRAYINTERVAL);
int i;
struct ArrayObject *ao=(struct ArrayObject *) tagptr;
for(i=0; i<ao->___cachedCode___; i++) {
- struct ___TagDescriptor___ * td=ARRAYGET(ao, struct ___TagDescriptor___*, i);
- if (td==tagd)
- return;
+ struct ___TagDescriptor___ * td=ARRAYGET(ao, struct ___TagDescriptor___*, i);
+ if (td==tagd)
+ return;
}
if (ao->___cachedCode___<ao->___length___) {
- ARRAYSET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___, tagd);
- ao->___cachedCode___++;
+ ARRAYSET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___, tagd);
+ ao->___cachedCode___++;
} else {
#ifdef PRECISE_GC
- int ptrarray[]={2,(int) ptr, (int) obj, (int) tagd};
- struct ArrayObject * aonew=allocate_newarray(&ptrarray,TAGARRAYTYPE,TAGARRAYINTERVAL+ao->___length___);
- obj=(struct ___Object___ *)ptrarray[2];
- tagd=(struct ___TagDescriptor___ *) ptrarray[3];
- ao=(struct ArrayObject *)obj->___tags___;
+ int ptrarray[]={2,(int) ptr, (int) obj, (int) tagd};
+ struct ArrayObject * aonew=allocate_newarray(&ptrarray,TAGARRAYTYPE,TAGARRAYINTERVAL+ao->___length___);
+ obj=(struct ___Object___ *)ptrarray[2];
+ tagd=(struct ___TagDescriptor___ *) ptrarray[3];
+ ao=(struct ArrayObject *)obj->___tags___;
#else
- struct ArrayObject * aonew=allocate_newarray(TAGARRAYTYPE,TAGARRAYINTERVAL+ao->___length___);
+ struct ArrayObject * aonew=allocate_newarray(TAGARRAYTYPE,TAGARRAYINTERVAL+ao->___length___);
#endif
- aonew->___cachedCode___=ao->___length___+1;
- for(i=0; i<ao->___length___; i++) {
- ARRAYSET(aonew, struct ___TagDescriptor___*, i, ARRAYGET(ao, struct ___TagDescriptor___*, i));
- }
- ARRAYSET(aonew, struct ___TagDescriptor___ *, ao->___length___, tagd);
+ aonew->___cachedCode___=ao->___length___+1;
+ for(i=0; i<ao->___length___; i++) {
+ ARRAYSET(aonew, struct ___TagDescriptor___*, i, ARRAYGET(ao, struct ___TagDescriptor___*, i));
+ }
+ ARRAYSET(aonew, struct ___TagDescriptor___ *, ao->___length___, tagd);
}
}
}
} else {
struct ArrayObject *ao=(struct ArrayObject *) tagset;
if (ao->___cachedCode___<ao->___length___) {
- ARRAYSET(ao, struct ___Object___*, ao->___cachedCode___++, obj);
+ ARRAYSET(ao, struct ___Object___*, ao->___cachedCode___++, obj);
} else {
- int i;
+ int i;
#ifdef PRECISE_GC
- int ptrarray[]={2, (int) ptr, (int) obj, (int)tagd};
- struct ArrayObject * aonew=allocate_newarray(&ptrarray,OBJECTARRAYTYPE,OBJECTARRAYINTERVAL+ao->___length___);
- obj=(struct ___Object___ *)ptrarray[2];
- tagd=(struct ___TagDescriptor___ *)ptrarray[3];
- ao=(struct ArrayObject *)tagd->flagptr;
+ int ptrarray[]={2, (int) ptr, (int) obj, (int)tagd};
+ struct ArrayObject * aonew=allocate_newarray(&ptrarray,OBJECTARRAYTYPE,OBJECTARRAYINTERVAL+ao->___length___);
+ obj=(struct ___Object___ *)ptrarray[2];
+ tagd=(struct ___TagDescriptor___ *)ptrarray[3];
+ ao=(struct ArrayObject *)tagd->flagptr;
#else
- struct ArrayObject * aonew=allocate_newarray(OBJECTARRAYTYPE,OBJECTARRAYINTERVAL);
+ struct ArrayObject * aonew=allocate_newarray(OBJECTARRAYTYPE,OBJECTARRAYINTERVAL);
#endif
- aonew->___cachedCode___=ao->___cachedCode___+1;
- for(i=0; i<ao->___length___; i++) {
- ARRAYSET(aonew, struct ___Object___*, i, ARRAYGET(ao, struct ___Object___*, i));
- }
- ARRAYSET(aonew, struct ___Object___ *, ao->___cachedCode___, obj);
- tagd->flagptr=(struct ___Object___ *) aonew;
+ aonew->___cachedCode___=ao->___cachedCode___+1;
+ for(i=0; i<ao->___length___; i++) {
+ ARRAYSET(aonew, struct ___Object___*, i, ARRAYGET(ao, struct ___Object___*, i));
+ }
+ ARRAYSET(aonew, struct ___Object___ *, ao->___cachedCode___, obj);
+ tagd->flagptr=(struct ___Object___ *) aonew;
}
}
}
for(i=0; i<ao->___cachedCode___; i++) {
struct ___TagDescriptor___ * td=ARRAYGET(ao, struct ___TagDescriptor___ *, i);
if (td==tagd) {
- ao->___cachedCode___--;
- if (i<ao->___cachedCode___)
- ARRAYSET(ao, struct ___TagDescriptor___ *, i, ARRAYGET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___));
- ARRAYSET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___, NULL);
- if (ao->___cachedCode___==0)
- obj->___tags___=NULL;
- goto PROCESSCLEAR;
+ ao->___cachedCode___--;
+ if (i<ao->___cachedCode___)
+ ARRAYSET(ao, struct ___TagDescriptor___ *, i, ARRAYGET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___));
+ ARRAYSET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___, NULL);
+ if (ao->___cachedCode___==0)
+ obj->___tags___=NULL;
+ goto PROCESSCLEAR;
}
}
printf("ERROR 2 in tagclear\n");
struct ___Object___ *tagset=tagd->flagptr;
if (tagset->type!=OBJECTARRAYTYPE) {
if (tagset==obj)
- tagd->flagptr=NULL;
+ tagd->flagptr=NULL;
else
- printf("ERROR 3 in tagclear\n");
+ printf("ERROR 3 in tagclear\n");
} else {
struct ArrayObject *ao=(struct ArrayObject *) tagset;
int i;
for(i=0; i<ao->___cachedCode___; i++) {
- struct ___Object___ * tobj=ARRAYGET(ao, struct ___Object___ *, i);
- if (tobj==obj) {
- ao->___cachedCode___--;
- if (i<ao->___cachedCode___)
- ARRAYSET(ao, struct ___Object___ *, i, ARRAYGET(ao, struct ___Object___ *, ao->___cachedCode___));
- ARRAYSET(ao, struct ___Object___ *, ao->___cachedCode___, NULL);
- if (ao->___cachedCode___==0)
- tagd->flagptr=NULL;
- goto ENDCLEAR;
- }
+ struct ___Object___ * tobj=ARRAYGET(ao, struct ___Object___ *, i);
+ if (tobj==obj) {
+ ao->___cachedCode___--;
+ if (i<ao->___cachedCode___)
+ ARRAYSET(ao, struct ___Object___ *, i, ARRAYGET(ao, struct ___Object___ *, ao->___cachedCode___));
+ ARRAYSET(ao, struct ___Object___ *, ao->___cachedCode___, NULL);
+ if (ao->___cachedCode___==0)
+ tagd->flagptr=NULL;
+ goto ENDCLEAR;
+ }
}
printf("ERROR 4 in tagclear\n");
}
counter=obj->fses[offset++];
oldoffset=offset;
for(j=0; j<counter; j++) {
- flag=obj->fses[offset];
- obj->fses[offset++]=(flag|ormask)&andmask;
+ flag=obj->fses[offset];
+ obj->fses[offset++]=(flag|ormask)&andmask;
}
qsort(&obj->fses[oldoffset], sizeof(int), counter, (int (*)(const void *, const void *)) &flagcomp);
}
counter=obj->fses[offset++];
oldoffset=offset;
for(j=0; j<counter; j++) {
- flag=obj->fses[offset];
- obj->fses[offset++]=(flag|ormask)&andmask;
+ flag=obj->fses[offset];
+ obj->fses[offset++]=(flag|ormask)&andmask;
}
qsort(&obj->fses[oldoffset], sizeof(int), counter, (int (*)(const void *, const void *)) &flagcomp);
}
while(parameter!=NULL) {
/* Check tags */
if (parameter->numbertags>0) {
- if (tagptr==NULL)
- goto nextloop; //that means the object has no tag but that param needs tag
- else if(tagptr->type==TAGTYPE) { //one tag
- struct ___TagDescriptor___ * tag=(struct ___TagDescriptor___*) tagptr;
- for(i=0; 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
- struct ArrayObject * ao=(struct ArrayObject *) tagptr;
- 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++) {
- if (tagid==ARRAYGET(ao, struct ___TagDescriptor___*, j)->flag)
- goto foundtag;
- }
- goto nextloop;
+ if (tagptr==NULL)
+ goto nextloop; //that means the object has no tag but that param needs tag
+ else if(tagptr->type==TAGTYPE) { //one tag
+ struct ___TagDescriptor___ * tag=(struct ___TagDescriptor___*) tagptr;
+ for(i=0; 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
+ struct ArrayObject * ao=(struct ArrayObject *) tagptr;
+ 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++) {
+ if (tagid==ARRAYGET(ao, struct ___TagDescriptor___*, j)->flag)
+ goto foundtag;
+ }
+ goto nextloop;
foundtag:
- ;
- }
- }
+ ;
+ }
+ }
}
/* Check flags */
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) {
- enqueuetasks(parameter, prevptr, ptr, NULL, 0);
- prevptr=parameter;
- break;
- }
+ int andmask=parameter->intarray[i*2];
+ int checkmask=parameter->intarray[i*2+1];
+ if ((ptr->flag&andmask)==checkmask) {
+ enqueuetasks(parameter, prevptr, ptr, NULL, 0);
+ prevptr=parameter;
+ break;
+ }
}
nextloop:
parameter=parameter->next;
//needs tag
else if(tagptr->type==TAGTYPE) { //one tag
if(fswrapper->numtags!=1)
- return 0; //we don't have the right number of tags
+ return 0; //we don't have the right number of tags
struct ___TagDescriptor___ * tag=(struct ___TagDescriptor___*) tagptr;
if (fswrapper->tags[0]!=tagptr->flag)
- return 0;
+ return 0;
} else { //multiple tags
struct ArrayObject * ao=(struct ArrayObject *) tagptr;
int tag_counter=0;
int foundtag=0;
if(ao->___length___!=fswrapper->numtags)
- return 0; //we don't have the right number of tags
+ return 0; //we don't have the right number of tags
for(tag_counter=0; tag_counter<fswrapper->numtags; tag_counter++) {
- int tagid=fswrapper->tags[tag_counter];
- int j;
- for(j=0; j<ao->___cachedCode___; j++) {
- if (tagid==ARRAYGET(ao, struct ___TagDescriptor___*, tag_counter)->flag)
- return 1;
- }
- return 0;
+ int tagid=fswrapper->tags[tag_counter];
+ int j;
+ for(j=0; j<ao->___cachedCode___; j++) {
+ if (tagid==ARRAYGET(ao, struct ___TagDescriptor___*, tag_counter)->flag)
+ return 1;
+ }
+ return 0;
}
}
}
while(i<len1||j<len2) {
if (i<len1&&(j==len2||flist1[i]<flist2[j])) {
if(merge!=NULL) {
- merge[count]=flist1[i];
+ merge[count]=flist1[i];
}
i++;
count++;
} else if (j<len2&&(i==len1||flist2[j]<flist1[i])) {
if(merge!=NULL) {
- merge[count]=flist2[j];
+ merge[count]=flist2[j];
}
j++;
count++;
} else if (i<len1&&j<len2&&flist1[i]==flist2[j]) {
if(merge!=NULL) {
- merge[count]=flist1[i];
+ merge[count]=flist1[i];
}
i++;
j++;
while(searchftl!=NULL) {
if ((*andlist)->task==searchftl->task&&
(*andlist)->index==searchftl->index) {
- mergeitems(*andlist, searchftl);
- break;
+ mergeitems(*andlist, searchftl);
+ break;
}
searchftl=searchftl->next;
}
if (taskfail->task==task&&taskfail->index==index) {
int start=0;
while(start<taskfail->numoptionaltaskdescriptors) {
- struct taskdescriptor *currtask=NULL;
- struct failedtasklist *tmpftl;
- int currindex;
- int totallength=0;
- int *enterflags;
- int numenterflags, offset;
- struct parameterwrapper *pw;
- 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;
- }
- pw=currtask->descriptorarray[currindex]->queue;
- enterflags=RUNMALLOC(totallength*sizeof(int));
- numenterflags=j-start;
- offset=0;
- for(start; start<j; start++) {
- struct optionaltaskdescriptor *otd=taskfail->optionaltaskdescriptorarray[start];
- enterflags[offset++]=otd->numenterflags;
- memcpy(&enterflags[offset], otd->enterflags, otd->numenterflags*sizeof(int));
- offset+=otd->numenterflags;
- }
- tmpftl=RUNMALLOC(sizeof(struct failedtasklist));
- tmpftl->next=list;
- tmpftl->task=currtask;
- tmpftl->numflags=numenterflags;
- tmpftl->flags=enterflags;
- list=tmpftl;
+ struct taskdescriptor *currtask=NULL;
+ struct failedtasklist *tmpftl;
+ int currindex;
+ int totallength=0;
+ int *enterflags;
+ int numenterflags, offset;
+ struct parameterwrapper *pw;
+ for(j=start; 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;
+ }
+ pw=currtask->descriptorarray[currindex]->queue;
+ enterflags=RUNMALLOC(totallength*sizeof(int));
+ numenterflags=j-start;
+ offset=0;
+ for(start; start<j; start++) {
+ struct optionaltaskdescriptor *otd=taskfail->optionaltaskdescriptorarray[start];
+ enterflags[offset++]=otd->numenterflags;
+ memcpy(&enterflags[offset], otd->enterflags, otd->numenterflags*sizeof(int));
+ offset+=otd->numenterflags;
+ }
+ tmpftl=RUNMALLOC(sizeof(struct failedtasklist));
+ tmpftl->next=list;
+ tmpftl->task=currtask;
+ tmpftl->numflags=numenterflags;
+ tmpftl->flags=enterflags;
+ list=tmpftl;
}
}
}
for(j=start; j<fswrapper->numoptionaltaskdescriptors; j++) {
struct optionaltaskdescriptor *otd=fswrapper->optionaltaskdescriptorarray[j];
if(currtask==NULL) {
- currtask=otd->task;
- currindex=otd->index;
+ currtask=otd->task;
+ currindex=otd->index;
} else if (currtask!=otd->task||currindex!=otd->index)
- break;
+ break;
totallength+=otd->numenterflags;
}
pw=currtask->descriptorarray[currindex]->queue;
struct fsanalysiswrapper *fswrapper=NULL;
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
- fswrapper=tmp;
- break;
- }
+ struct fsanalysiswrapper * tmp=classwrapper->fsanalysiswrapperarray[h];
+ if (tmp->flags==currobj->flag&&checktags(currobj, tmp)) {
+ //we only match exactly here
+ fswrapper=tmp;
+ break;
+ }
}
if(fswrapper==NULL) //nothing to do in this state
- return;
+ return;
for(i=0; i<fswrapper->numtaskfailures; i++) {
- int j;
- struct taskfailure * taskfail=fswrapper->taskfailurearray[i];
- if (taskfail->task==task&&taskfail->index==index) {
- int start=0;
- while(start<taskfail->numoptionaltaskdescriptors) {
- struct taskdescriptor *currtask=NULL;
- int currindex;
- int totallength=0;
- int *enterflags;
- int numenterflags, offset;
- struct parameterwrapper *pw;
- 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
- }
- pw=currtask->descriptorarray[currindex]->queue;
- numenterflags=j-start;
- enterflags=RUNMALLOC((totallength+numenterflags)*sizeof(int));
-
- offset=0;
- for(start; start<j; start++) {
- struct optionaltaskdescriptor *otd=taskfail->optionaltaskdescriptorarray[start];
- enterflags[offset++]=otd->numenterflags;
- memcpy(&enterflags[offset], otd->enterflags, otd->numenterflags*sizeof(int));
- offset+=otd->numenterflags;
- }
- //Enqueue this one
- if (enqueuetasks(pw, currobj->flagptr, currobj, enterflags, numenterflags))
- currobj->flagptr=pw;
- }
- }
+ int j;
+ struct taskfailure * taskfail=fswrapper->taskfailurearray[i];
+ if (taskfail->task==task&&taskfail->index==index) {
+ int start=0;
+ while(start<taskfail->numoptionaltaskdescriptors) {
+ struct taskdescriptor *currtask=NULL;
+ int currindex;
+ int totallength=0;
+ int *enterflags;
+ int numenterflags, offset;
+ struct parameterwrapper *pw;
+ 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
+ }
+ pw=currtask->descriptorarray[currindex]->queue;
+ numenterflags=j-start;
+ enterflags=RUNMALLOC((totallength+numenterflags)*sizeof(int));
+
+ offset=0;
+ for(start; start<j; start++) {
+ struct optionaltaskdescriptor *otd=taskfail->optionaltaskdescriptorarray[start];
+ enterflags[offset++]=otd->numenterflags;
+ memcpy(&enterflags[offset], otd->enterflags, otd->numenterflags*sizeof(int));
+ offset+=otd->numenterflags;
+ }
+ //Enqueue this one
+ if (enqueuetasks(pw, currobj->flagptr, currobj, enterflags, numenterflags))
+ currobj->flagptr=pw;
+ }
+ }
}
} else {
/* Failed in failed state */
int i;
int offset=0;
for(i=0; i<numfailedfses; i++) {
- int numfses=failedfses[offset++];
- int j;
- struct failedtasklist *andlist=NULL;
- for(j=0; j<numfses; j++) {
- int flagstate=failedfses[offset++];
- struct failedtasklist *currlist=processfailstate(classwrapper, task, index, currobj, flagstate);
- if (andlist==NULL)
- andlist=currlist;
- else
- mergefailedlists(&andlist, currlist);
- }
- enqueuelist(currobj, andlist);
+ int numfses=failedfses[offset++];
+ int j;
+ struct failedtasklist *andlist=NULL;
+ for(j=0; j<numfses; j++) {
+ int flagstate=failedfses[offset++];
+ struct failedtasklist *currlist=processfailstate(classwrapper, task, index, currobj, flagstate);
+ if (andlist==NULL)
+ andlist=currlist;
+ else
+ mergefailedlists(&andlist, currlist);
+ }
+ enqueuelist(currobj, andlist);
}
}
} else {
ObjectHashget(flagptr->objectset, (int) currobj, (int *) &next, (int *) &enterflags, &UNUSED, &UNUSED2);
ObjectHashremove(flagptr->objectset, (int)currobj);
if (enterflags!=NULL)
- free(enterflags);
+ free(enterflags);
flagptr=next;
}
int j;
struct failedtasklist *andlist=NULL;
for(j=0; j<numfses; j++) {
- int flagstate=currobj->fses[offset++];
- struct failedtasklist *currlist=processnormfailstate(classwrapper, currobj, flagstate);
- if (andlist==NULL)
- andlist=currlist;
- else
- mergefailedlists(&andlist, currlist);
+ int flagstate=currobj->fses[offset++];
+ struct failedtasklist *currlist=processnormfailstate(classwrapper, currobj, flagstate);
+ if (andlist==NULL)
+ andlist=currlist;
+ else
+ mergefailedlists(&andlist, currlist);
}
enqueuelist(currobj, andlist);
}
#ifdef OPTIONAL
tpd->failed[j]=failed[j];
if (failed[j]!=0&&failed[j]!=1) {
- printf("BAD\n");
+ printf("BAD\n");
}
#endif
}
for(j=numiterators-1; j<numiterators; j++) {
backtrackinc:
if(toiHasNext(¶meter->iterators[j], taskpointerarray OPTARG(failed))) {
- toiNext(¶meter->iterators[j], taskpointerarray OPTARG(failed));
+ toiNext(¶meter->iterators[j], taskpointerarray OPTARG(failed));
} else if (j>0) {
- /* Need to backtrack */
- toiReset(¶meter->iterators[j]);
- j--;
- goto backtrackinc;
+ /* Need to backtrack */
+ toiReset(¶meter->iterators[j]);
+ j--;
+ goto backtrackinc;
} else {
- /* Nothing more to enqueue */
- return retval;
+ /* Nothing more to enqueue */
+ return retval;
}
}
}
tmpreadfds=readfds;
numselect=select(maxreadfd, &tmpreadfds, NULL, NULL, &timeout);
if (numselect>0) {
- /* Process ready fd's */
- int 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);
- }
- }
- }
- }
+ /* Process ready fd's */
+ int 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);
+ }
+ }
+ }
+ }
}
}
/* 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);
+ // Free up task parameter descriptor
+ RUNFREE(currtpd->parameterArray);
#ifdef OPTIONAL
- RUNFREE(currtpd->failed);
+ RUNFREE(currtpd->failed);
#endif
- RUNFREE(currtpd);
- goto newtask;
+ RUNFREE(currtpd);
+ goto newtask;
}
int numparams=currtpd->task->numParameters;
int numtotal=currtpd->task->numTotal;
/* Make sure that the parameters are still in the queues */
for(i=0; i<numparams; i++) {
- void * parameter=currtpd->parameterArray[i];
- struct parameterdescriptor * pd=currtpd->task->descriptorarray[i];
- struct parameterwrapper *pw=(struct parameterwrapper *) pd->queue;
- int j;
- /* Check that object is still in queue */
+ void * parameter=currtpd->parameterArray[i];
+ struct parameterdescriptor * pd=currtpd->task->descriptorarray[i];
+ struct parameterwrapper *pw=(struct parameterwrapper *) pd->queue;
+ int j;
+ /* Check that object is still in queue */
#ifdef OPTIONAL
- {
- int UNUSED, UNUSED2;
- int *flags;
- int numflags, isnonfailed;
- int failed=currtpd->failed[i];
- if (!ObjectHashget(pw->objectset, (int) parameter, &UNUSED, (int *) &flags, &numflags, &isnonfailed)) {
- RUNFREE(currtpd->parameterArray);
- RUNFREE(currtpd->failed);
- RUNFREE(currtpd);
- goto newtask;
- } else {
- if (failed&&(flags!=NULL)) {
- //Failed parameter
- fsesarray[i]=flags;
- numfsesarray[i]=numflags;
- } else if (!failed && isnonfailed) {
- //Non-failed parameter
- fsesarray[i]=NULL;
- numfsesarray[i]=0;
- } else {
- RUNFREE(currtpd->parameterArray);
- RUNFREE(currtpd->failed);
- RUNFREE(currtpd);
- goto newtask;
- }
- }
- }
+ {
+ int UNUSED, UNUSED2;
+ int *flags;
+ int numflags, isnonfailed;
+ int failed=currtpd->failed[i];
+ if (!ObjectHashget(pw->objectset, (int) parameter, &UNUSED, (int *) &flags, &numflags, &isnonfailed)) {
+ RUNFREE(currtpd->parameterArray);
+ RUNFREE(currtpd->failed);
+ RUNFREE(currtpd);
+ goto newtask;
+ } else {
+ if (failed&&(flags!=NULL)) {
+ //Failed parameter
+ fsesarray[i]=flags;
+ numfsesarray[i]=numflags;
+ } else if (!failed && isnonfailed) {
+ //Non-failed parameter
+ fsesarray[i]=NULL;
+ numfsesarray[i]=0;
+ } else {
+ RUNFREE(currtpd->parameterArray);
+ RUNFREE(currtpd->failed);
+ RUNFREE(currtpd);
+ goto newtask;
+ }
+ }
+ }
#else
- {
- if (!ObjectHashcontainskey(pw->objectset, (int) parameter)) {
- RUNFREE(currtpd->parameterArray);
- RUNFREE(currtpd);
- goto newtask;
- }
- }
+ {
+ if (!ObjectHashcontainskey(pw->objectset, (int) parameter)) {
+ RUNFREE(currtpd->parameterArray);
+ RUNFREE(currtpd);
+ goto newtask;
+ }
+ }
#endif
parameterpresent:
- ;
- /* Check that object still has necessary tags */
- for(j=0; j<pd->numbertags; j++) {
- int slotid=pd->tagarray[2*j]+numparams;
- struct ___TagDescriptor___ *tagd=currtpd->parameterArray[slotid];
- if (!containstag(parameter, tagd)) {
- RUNFREE(currtpd->parameterArray);
+ ;
+ /* Check that object still has necessary tags */
+ for(j=0; j<pd->numbertags; j++) {
+ int slotid=pd->tagarray[2*j]+numparams;
+ struct ___TagDescriptor___ *tagd=currtpd->parameterArray[slotid];
+ if (!containstag(parameter, tagd)) {
+ RUNFREE(currtpd->parameterArray);
#ifdef OPTIONAL
- RUNFREE(currtpd->failed);
+ RUNFREE(currtpd->failed);
#endif
- RUNFREE(currtpd);
- goto newtask;
- }
- }
+ RUNFREE(currtpd);
+ goto newtask;
+ }
+ }
- taskpointerarray[i+OFFSET]=parameter;
+ taskpointerarray[i+OFFSET]=parameter;
}
/* Copy the tags */
for(; i<numtotal; i++) {
- taskpointerarray[i+OFFSET]=currtpd->parameterArray[i];
+ taskpointerarray[i+OFFSET]=currtpd->parameterArray[i];
}
{
- /* Checkpoint the state */
+ /* Checkpoint the state */
#ifdef FASTCHECK
- ___fcrevert___=NULL;
+ ___fcrevert___=NULL;
#else
- forward=cCreate(256, 0.4);
- reverse=cCreate(256, 0.4);
- void ** checkpoint=makecheckpoint(currtpd->task->numParameters, currtpd->parameterArray, forward, reverse);
+ forward=cCreate(256, 0.4);
+ reverse=cCreate(256, 0.4);
+ void ** checkpoint=makecheckpoint(currtpd->task->numParameters, currtpd->parameterArray, forward, reverse);
#endif
- int x;
- if (x=setjmp(error_handler)) {
- int counter;
- /* Recover */
+ int x;
+ if (x=setjmp(error_handler)) {
+ int counter;
+ /* Recover */
#ifdef DEBUG
- printf("Fatal Error=%d, Recovering!\n",x);
+ printf("Fatal Error=%d, Recovering!\n",x);
#endif
- genputtable(failedtasks,currtpd,currtpd);
+ genputtable(failedtasks,currtpd,currtpd);
#ifdef FASTCHECK
- REVERT_OBJ(___fcrevert___);
+ REVERT_OBJ(___fcrevert___);
#else
- restorecheckpoint(currtpd->task->numParameters, currtpd->parameterArray, checkpoint, forward, reverse);
+ restorecheckpoint(currtpd->task->numParameters, currtpd->parameterArray, checkpoint, forward, reverse);
#endif
#ifdef OPTIONAL
- for(counter=0; counter<currtpd->task->numParameters; counter++) {
- //enqueue as failed
- enqueueoptional(currtpd->parameterArray[counter], numfsesarray[counter], fsesarray[counter], currtpd->task, counter);
-
- //free fses copies
- if (fsesarray[counter]!=NULL)
- RUNFREE(fsesarray[counter]);
- }
+ for(counter=0; counter<currtpd->task->numParameters; counter++) {
+ //enqueue as failed
+ enqueueoptional(currtpd->parameterArray[counter], numfsesarray[counter], fsesarray[counter], currtpd->task, counter);
+
+ //free fses copies
+ if (fsesarray[counter]!=NULL)
+ RUNFREE(fsesarray[counter]);
+ }
#endif
#ifndef FASTCHECK
- cDelete(forward);
- cDelete(reverse);
- freemalloc();
- forward=NULL;
- reverse=NULL;
+ cDelete(forward);
+ cDelete(reverse);
+ freemalloc();
+ forward=NULL;
+ reverse=NULL;
#endif
- } else {
- if (injectfailures) {
- if ((((double)random())/RAND_MAX)<failurechance) {
- printf("\nINJECTING TASK FAILURE to %s\n", currtpd->task->name);
- longjmp(error_handler,10);
- }
- }
- /* Actually call task */
+ } else {
+ if (injectfailures) {
+ 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;
- taskpointerarray[1]=NULL;
+ ((int *)taskpointerarray)[0]=currtpd->numParameters;
+ taskpointerarray[1]=NULL;
#endif
#ifdef OPTIONAL
- //get the task flags set
- 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];
- }
+ //get the task flags set
+ 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];
+ }
#endif
- if(debugtask) {
- printf("ENTER %s count=%d\n",currtpd->task->name, (instaccum-instructioncount));
- ((void (*)(void **))currtpd->task->taskptr)(taskpointerarray);
- printf("EXIT %s count=%d\n",currtpd->task->name, (instaccum-instructioncount));
- } else
- ((void (*)(void **))currtpd->task->taskptr)(taskpointerarray);
+ if(debugtask) {
+ printf("ENTER %s count=%d\n",currtpd->task->name, (instaccum-instructioncount));
+ ((void (*)(void **))currtpd->task->taskptr)(taskpointerarray);
+ printf("EXIT %s count=%d\n",currtpd->task->name, (instaccum-instructioncount));
+ } else
+ ((void (*)(void **))currtpd->task->taskptr)(taskpointerarray);
#ifdef OPTIONAL
- for(i=0; i<numparams; i++) {
- //free old fses
- if(oldfsesarray[i]!=NULL)
- RUNFREE(oldfsesarray[i]);
- }
+ for(i=0; i<numparams; i++) {
+ //free old fses
+ if(oldfsesarray[i]!=NULL)
+ RUNFREE(oldfsesarray[i]);
+ }
#endif
#ifdef FASTCHECK
- while(___fcrevert___) {
- struct ___Object___ *tmpptr=___fcrevert___->___nextobject___;
- COMMIT_OBJ(___fcrevert___);
- ___fcrevert___=tmpptr;
- }
+ while(___fcrevert___) {
+ struct ___Object___ *tmpptr=___fcrevert___->___nextobject___;
+ COMMIT_OBJ(___fcrevert___);
+ ___fcrevert___=tmpptr;
+ }
#else
- cDelete(forward);
- cDelete(reverse);
- freemalloc();
+ cDelete(forward);
+ cDelete(reverse);
+ freemalloc();
#endif
- // Free up task parameter descriptor
- RUNFREE(currtpd->parameterArray);
+ // Free up task parameter descriptor
+ RUNFREE(currtpd->parameterArray);
#ifdef OPTIONAL
- RUNFREE(currtpd->failed);
+ RUNFREE(currtpd->failed);
#endif
- RUNFREE(currtpd);
- forward=NULL;
- reverse=NULL;
- }
+ RUNFREE(currtpd);
+ forward=NULL;
+ reverse=NULL;
+ }
}
}
}
/* Check for objects with existing tags */
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++) {
- int slotid=pd->tagarray[2*j];
- if(statusarray[slotid+numparams]!=0) {
- processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
- processtags(pd, i, parameter, &iteratorcount, statusarray, numparams);
- goto loopstart;
- }
- }
+ struct parameterdescriptor *pd=task->descriptorarray[i];
+ int j;
+ for(j=0; j<pd->numbertags; j++) {
+ int slotid=pd->tagarray[2*j];
+ if(statusarray[slotid+numparams]!=0) {
+ processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
+ processtags(pd, i, parameter, &iteratorcount, statusarray, numparams);
+ goto loopstart;
+ }
+ }
}
}
for(i=0; i<numparams; i++) {
if (statusarray[i]==0) {
- struct parameterdescriptor *pd=task->descriptorarray[i];
- if (pd->numbertags>0) {
- processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
- processtags(pd, i, parameter, &iteratorcount, statusarray, numparams);
- goto loopstart;
- }
+ struct parameterdescriptor *pd=task->descriptorarray[i];
+ if (pd->numbertags>0) {
+ processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
+ processtags(pd, i, parameter, &iteratorcount, statusarray, numparams);
+ goto loopstart;
+ }
}
}
for(i=0; i<numparams; i++) {
if (statusarray[i]==0) {
- struct parameterdescriptor *pd=task->descriptorarray[i];
- processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
- processtags(pd, i, parameter, &iteratorcount, statusarray, numparams);
- goto loopstart;
+ struct parameterdescriptor *pd=task->descriptorarray[i];
+ processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
+ processtags(pd, i, parameter, &iteratorcount, statusarray, numparams);
+ goto loopstart;
}
}
printf(" Parameter %d\n", j);
ObjectHashiterator(set, &objit);
while(ObjhasNext(&objit)) {
- struct ___Object___ * obj=(struct ___Object___ *)Objkey(&objit);
- struct ___Object___ * tagptr=obj->___tags___;
- int nonfailed=Objdata4(&objit);
- int numflags=Objdata3(&objit);
- int flags=Objdata2(&objit);
- Objnext(&objit);
- printf(" Contains %lx\n", obj);
- printf(" flag=%d\n", obj->flag);
+ struct ___Object___ * obj=(struct ___Object___ *)Objkey(&objit);
+ struct ___Object___ * tagptr=obj->___tags___;
+ int nonfailed=Objdata4(&objit);
+ int numflags=Objdata3(&objit);
+ int flags=Objdata2(&objit);
+ Objnext(&objit);
+ printf(" Contains %lx\n", obj);
+ printf(" flag=%d\n", obj->flag);
#ifdef OPTIONAL
- printf(" flagsstored=%x\n",flags);
- printf(" numflags=%d\n", numflags);
- printf(" nonfailed=%d\n",nonfailed);
+ printf(" flagsstored=%x\n",flags);
+ printf(" numflags=%d\n", numflags);
+ printf(" nonfailed=%d\n",nonfailed);
#endif
- if (tagptr==NULL) {
- } else if (tagptr->type==TAGTYPE) {
- printf(" tag=%lx\n",tagptr);
- } else {
- int tagindex=0;
- struct ArrayObject *ao=(struct ArrayObject *)tagptr;
- for(; tagindex<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));
+ }
+ }
}
}
}
parameter->slot=j;
/* Link new queue in */
while((*ptr)!=NULL)
- ptr=&((*ptr)->next);
+ ptr=&((*ptr)->next);
(*ptr)=parameter;
}
if (tagptr->type==TAGTYPE) {
if ((it->tagobjindex==0)&& /* First object */
(it->tagid==((struct ___TagDescriptor___ *)tagptr)->flag)) /* Right tag type */
- return 1;
+ return 1;
else
- return 0;
+ return 0;
} else {
struct ArrayObject *ao=(struct ArrayObject *) tagptr;
int tagindex=it->tagobjindex;
for(; tagindex<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 1;
- }
+ struct ___TagDescriptor___ *td=ARRAYGET(ao, struct ___TagDescriptor___ *, tagindex);
+ if (td->flag==it->tagid) {
+ it->tagobjindex=tagindex; /* Found right type of tag */
+ return 1;
+ }
}
return 0;
}
int i;
if (objptr->type!=OBJECTARRAYTYPE) {
if (it->tagobjindex>0)
- return 0;
+ return 0;
if (!ObjectHashcontainskey(it->objectset, (int) objptr))
- return 0;
+ return 0;
for(i=1; i<it->numtags; i++) {
- struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]];
- if (!containstag(objptr,tag2))
- return 0;
+ struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]];
+ if (!containstag(objptr,tag2))
+ return 0;
}
#ifdef OPTIONAL
if (it->failedstate==1) {
- int UNUSED, UNUSED2;
- int * flags;
- int isnonfailed;
- ObjectHashget(it->objectset, (int) objptr, &UNUSED, (int *) &flags, &UNUSED2, &isnonfailed);
- if (flags!=NULL) {
- return 1;
- } else {
- it->tagobjindex++;
- it->failedstate=0;
- return 0;
- }
+ int UNUSED, UNUSED2;
+ int * flags;
+ int isnonfailed;
+ ObjectHashget(it->objectset, (int) objptr, &UNUSED, (int *) &flags, &UNUSED2, &isnonfailed);
+ if (flags!=NULL) {
+ return 1;
+ } else {
+ it->tagobjindex++;
+ it->failedstate=0;
+ return 0;
+ }
} else {
- int UNUSED, UNUSED2;
- int * flags;
- int isnonfailed;
- ObjectHashget(it->objectset, (int) objptr, &UNUSED, (int *) &flags, &UNUSED2, &isnonfailed);
- if (!isnonfailed) {
- it->failedstate=1;
- }
- return 1;
+ int UNUSED, UNUSED2;
+ int * flags;
+ int isnonfailed;
+ ObjectHashget(it->objectset, (int) objptr, &UNUSED, (int *) &flags, &UNUSED2, &isnonfailed);
+ if (!isnonfailed) {
+ it->failedstate=1;
+ }
+ return 1;
}
#endif
return 1;
int i;
#ifdef OPTIONAL
if (it->failedstate==1) {
- int UNUSED, UNUSED2;
- int * flags;
- int isnonfailed;
- struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, it->tagobjindex);
- ObjectHashget(it->objectset, (int) objptr, &UNUSED, (int *) &flags, &UNUSED2, &isnonfailed);
- if (flags!=NULL) {
- return 1;
- } else {
- it->failedstate=0;
- it->tagobjindex++;
- }
+ int UNUSED, UNUSED2;
+ int * flags;
+ int isnonfailed;
+ struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, it->tagobjindex);
+ ObjectHashget(it->objectset, (int) objptr, &UNUSED, (int *) &flags, &UNUSED2, &isnonfailed);
+ if (flags!=NULL) {
+ return 1;
+ } else {
+ it->failedstate=0;
+ it->tagobjindex++;
+ }
}
#endif
for(tagindex=it->tagobjindex; tagindex<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++) {
- struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]];
- if (!containstag(objptr,tag2))
- goto nexttag;
- }
+ struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, tagindex);
+ if (!ObjectHashcontainskey(it->objectset, (int) objptr))
+ continue;
+ for(i=1; i<it->numtags; i++) {
+ struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]];
+ if (!containstag(objptr,tag2))
+ goto nexttag;
+ }
#ifdef OPTIONAL
- {
- int UNUSED, UNUSED2;
- int flags, isnonfailed;
- struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, tagindex);
- ObjectHashget(it->objectset, (int) objptr, &UNUSED, &flags, &UNUSED2, &isnonfailed);
- if (!isnonfailed) {
- it->failedstate=1;
- }
- }
+ {
+ int UNUSED, UNUSED2;
+ int flags, isnonfailed;
+ struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, tagindex);
+ ObjectHashget(it->objectset, (int) objptr, &UNUSED, &flags, &UNUSED2, &isnonfailed);
+ if (!isnonfailed) {
+ it->failedstate=1;
+ }
+ }
#endif
- it->tagobjindex=tagindex;
- return 1;
+ it->tagobjindex=tagindex;
+ return 1;
nexttag:
- ;
+ ;
}
it->tagobjindex=tagindex;
return 0;
#ifdef OPTIONAL
if (it->failedstate==1) {
if (Objdata2(&it->it))
- return 1;
+ return 1;
else {
- it->failedstate=0;
- Objnext(&it->it);
+ it->failedstate=0;
+ Objnext(&it->it);
}
}
if (ObjhasNext(&it->it)) {
if (!Objdata4(&it->it)) {
- //failed state only
- it->failedstate=1;
+ //failed state only
+ it->failedstate=1;
}
return 1;
} else
struct ArrayObject *ao=(struct ArrayObject *)objptr;
for(j=0; j<ao->___cachedCode___; j++) {
if (ptr==ARRAYGET(ao, struct ___Object___*, j))
- return 1;
+ return 1;
}
return 0;
} else
failed[it->slot]=it->failedstate;
objectarray[it->slot]=objptr;
if (it->failedstate==0) {
- it->failedstate=1;
+ it->failedstate=1;
} else {
- it->failedstate=0;
- it->tagobjindex++;
+ it->failedstate=0;
+ it->tagobjindex++;
}
#else
it->tagobjindex++;
failed[it->slot]=it->failedstate;
objectarray[it->slot]=ARRAYGET(ao, struct ___Object___ *, it->tagobjindex);
if (it->failedstate==0) {
- it->failedstate=1;
+ it->failedstate=1;
} else {
- it->failedstate=0;
- it->tagobjindex++;
+ it->failedstate=0;
+ it->tagobjindex++;
}
#else
objectarray[it->slot]=ARRAYGET(ao, struct ___Object___ *, it->tagobjindex++);
#if !defined(MULTICORE)
struct parameterwrapper * p=objectqueues[i];
while(p!=NULL) {
- struct ObjectHash * set=p->objectset;
- struct ObjectNode * ptr=set->listhead;
- while(ptr!=NULL) {
- void *orig=(void *)ptr->key;
- ENQUEUE(orig, *((void **)(&ptr->key)));
- ptr=ptr->lnext;
- }
- ObjectHashrehash(set); /* Rehash the table */
- p=p->next;
+ struct ObjectHash * set=p->objectset;
+ struct ObjectNode * ptr=set->listhead;
+ while(ptr!=NULL) {
+ void *orig=(void *)ptr->key;
+ ENQUEUE(orig, *((void **)(&ptr->key)));
+ ptr=ptr->lnext;
+ }
+ ObjectHashrehash(set); /* Rehash the table */
+ p=p->next;
}
#endif
}
struct taskparamdescriptor *tpd=ptr->src;
int i;
for(i=0; i<tpd->numParameters; i++) {
- void * orig=tpd->parameterArray[i];
- ENQUEUE(orig, tpd->parameterArray[i]);
+ void * orig=tpd->parameterArray[i];
+ ENQUEUE(orig, tpd->parameterArray[i]);
}
ptr=ptr->inext;
}
struct taskparamdescriptor *tpd=ptr->src;
int i;
for(i=0; i<tpd->numParameters; i++) {
- void * orig=tpd->parameterArray[i];
- ENQUEUE(orig, tpd->parameterArray[i]);
+ void * orig=tpd->parameterArray[i];
+ ENQUEUE(orig, tpd->parameterArray[i]);
}
ptr=ptr->inext;
}
struct ___Object___ *obj=tagd->flagptr;
struct ___TagDescriptor___ *copy=((struct ___TagDescriptor___**)tagd)[1];
if (obj==NULL) {
- /* Zero object case */
+ /* Zero object case */
} else if (obj->type==-1) {
- /* Single object case */
- copy->flagptr=((struct ___Object___**)obj)[1];
+ /* Single object case */
+ copy->flagptr=((struct ___Object___**)obj)[1];
} else if (obj->type==OBJECTARRAYTYPE) {
- /* Array case */
- struct ArrayObject *ao=(struct ArrayObject *) obj;
- int livecount=0;
- int j;
- int k=0;
- struct ArrayObject *aonew;
-
- /* Count live objects */
- for(j=0; j<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++) {
- struct ___Object___ * tobj=ARRAYGET(ao, struct ___Object___ *, j);
- if (tobj->type==-1) {
- struct ___Object___ * tobjcpy=((struct ___Object___**)tobj)[1];
- ARRAYSET(aonew, struct ___Object___*, k++,tobjcpy);
- }
- }
- aonew->___cachedCode___=k;
- for(; k<livecount; k++) {
- ARRAYSET(aonew, struct ___Object___*, k, NULL);
- }
+ /* Array case */
+ struct ArrayObject *ao=(struct ArrayObject *) obj;
+ int livecount=0;
+ int j;
+ int k=0;
+ struct ArrayObject *aonew;
+
+ /* Count live objects */
+ for(j=0; j<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++) {
+ struct ___Object___ * tobj=ARRAYGET(ao, struct ___Object___ *, j);
+ if (tobj->type==-1) {
+ struct ___Object___ * tobjcpy=((struct ___Object___**)tobj)[1];
+ ARRAYSET(aonew, struct ___Object___*, k++,tobjcpy);
+ }
+ }
+ aonew->___cachedCode___=k;
+ for(; k<livecount; k++) {
+ ARRAYSET(aonew, struct ___Object___*, k, NULL);
+ }
} else {
- /* No object live anymore */
- copy->flagptr=NULL;
+ /* No object live anymore */
+ copy->flagptr=NULL;
}
}
free(taghead);
if( workUnit != DQ_POP_EMPTY ) {
- haveWork = TRUE;
- goto dowork;
+ haveWork = TRUE;
+ goto dowork;
} else {
- // try to steal from another queue, starting
- // with the last successful victim, don't check
- // your own deque
- int mynumWorkSchedWorkers=numWorkSchedWorkers;
- for( i = 0; i < mynumWorkSchedWorkers - 1; ++i ) {
+ // try to steal from another queue, starting
+ // with the last successful victim, don't check
+ // your own deque
+ int mynumWorkSchedWorkers=numWorkSchedWorkers;
+ for( i = 0; i < mynumWorkSchedWorkers - 1; ++i ) {
- workUnit = dqPopTop(&(deques[lastVictim]) );
+ workUnit = dqPopTop(&(deques[lastVictim]) );
#ifdef SQUEUE
- if( workUnit != DQ_POP_EMPTY ) {
+ if( workUnit != DQ_POP_EMPTY ) {
#else
- if( workUnit != DQ_POP_ABORT &&
- workUnit != DQ_POP_EMPTY ) {
+ if( workUnit != DQ_POP_ABORT &&
+ workUnit != DQ_POP_EMPTY ) {
#endif
- // successful steal!
- haveWork = TRUE;
- goto dowork;
- }
-
- // choose next victim
- lastVictim++; if( lastVictim == mynumWorkSchedWorkers ) {
- lastVictim = 0;
- }
-
- if( lastVictim == myWorkerID ) {
- lastVictim++; if( lastVictim == mynumWorkSchedWorkers ) {
- lastVictim = 0;
- }
- }
- }
- // end steal attempts
-
-
- // if we successfully stole work, break out of the
- // while-not-have-work loop, otherwise we looked
- // everywhere, so drop down to "I'm idle" code below
- if( haveWork ) {
- goto dowork;
- }
+ // successful steal!
+ haveWork = TRUE;
+ goto dowork;
+ }
+
+ // choose next victim
+ lastVictim++; if( lastVictim == mynumWorkSchedWorkers ) {
+ lastVictim = 0;
+ }
+
+ if( lastVictim == myWorkerID ) {
+ lastVictim++; if( lastVictim == mynumWorkSchedWorkers ) {
+ lastVictim = 0;
+ }
+ }
+ }
+ // end steal attempts
+
+
+ // if we successfully stole work, break out of the
+ // while-not-have-work loop, otherwise we looked
+ // everywhere, so drop down to "I'm idle" code below
+ if( haveWork ) {
+ goto dowork;
+ }
}
// if we drop down this far, we didn't find any work,
// so do a garbage collection, yield the processor,
// then check if the entire system is out of work
if( unlikely(needtocollect) ) {
- checkcollect(&emptygarbagelist);
+ checkcollect(&emptygarbagelist);
}
sched_yield();
if( mainTaskRetired ) {
- keepRunning = FALSE;
- break;
+ keepRunning = FALSE;
+ break;
}
} // end the while-not-have-work loop
#ifdef DEBUG_DEQUE
if( workUnit == NULL ) {
- printf("About to execute a null work item\n");
+ printf("About to execute a null work item\n");
}
#endif
for(; x<oidIncrement; x++) {
//not prime
if (oidIncrement%x==0) {
- oidIncrement++;
- break;
+ oidIncrement++;
+ break;
}
}
//have prime
switch (c) {
case '\n': {
- // get the cr
- sb.append(string, lastcr, (i - lastcr) + 1);
- super.write(sb.toString());
- sb = genSpacing();
- lastcr = i + 1; // skip carriage return
- seenChar = false;
- break;
+ // get the cr
+ sb.append(string, lastcr, (i - lastcr) + 1);
+ super.write(sb.toString());
+ sb = genSpacing();
+ lastcr = i + 1; // skip carriage return
+ seenChar = false;
+ break;
}
case '{':
- braceCount++;
- seenChar = true;
- break;
+ braceCount++;
+ seenChar = true;
+ break;
case '}':
- braceCount--;
- // fix up close brace...
- if (!seenChar)
- sb = genSpacing();
- seenChar = true;
- break;
+ braceCount--;
+ // fix up close brace...
+ if (!seenChar)
+ sb = genSpacing();
+ seenChar = true;
+ break;
case ' ':
- // skip leading whitespace
- if (!seenChar)
- lastcr = i + 1;
- break;
+ // skip leading whitespace
+ if (!seenChar)
+ lastcr = i + 1;
+ break;
default:
- seenChar = true;
+ seenChar = true;
}
}
if (lastcr < string.length) {
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);
- }
- }
+ 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);
+ }
+ }
}
}
}
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);
- }
- }
- }
+ 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();
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;
- }
-
- output.println("\t" + gn.getLabel() + " -> " + node2.getLabel() + " [" + "label=\"" + edgelabel + "\"" + edgedotnodeparams + "];");
- }
- }
- }
+ 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;
+ }
+
+ output.println("\t" + gn.getLabel() + " -> " + node2.getLabel() + " [" + "label=\"" + edgelabel + "\"" + edgedotnodeparams + "];");
+ }
+ }
+ }
}
}
HashSet toprocess=new HashSet();
toprocess.add(gn);
while(!toprocess.isEmpty()) {
- GraphNode gn2=(GraphNode)toprocess.iterator().next();
- toprocess.remove(gn2);
- if (!gn2.merge)
- newset.add(gn2);
- else {
- Iterator edges = gn2.edges();
- while (edges.hasNext()) {
- Edge edge = (Edge) edges.next();
- GraphNode node = edge.getTarget();
- if (!newset.contains(node)&&nodes.contains(node))
- toprocess.add(node);
- }
- }
+ GraphNode gn2=(GraphNode)toprocess.iterator().next();
+ toprocess.remove(gn2);
+ if (!gn2.merge)
+ newset.add(gn2);
+ else {
+ Iterator edges = gn2.edges();
+ while (edges.hasNext()) {
+ Edge edge = (Edge) edges.next();
+ GraphNode node = edge.getTarget();
+ if (!newset.contains(node)&&nodes.contains(node))
+ toprocess.add(node);
+ }
+ }
}
return newset;
}
return cycleset;
for(int i=0; i<scc.numSCC(); i++) {
if (scc.hasCycle(i))
- cycleset.addAll(scc.getSCC(i));
+ cycleset.addAll(scc.getSCC(i));
}
return cycleset;
}
Integer scc=new Integer(i);
Set s=(Set)map.get(scc);
if (s.size()>1)
- return true;
+ return true;
Object [] array=s.toArray();
GraphNode gn=(GraphNode)array[0];
for(Iterator it=gn.edges(); it.hasNext(); ) {
- Edge e=(Edge)it.next();
- if (e.getTarget()==gn)
- return true; /* Self Cycle */
+ Edge e=(Edge)it.next();
+ if (e.getTarget()==gn)
+ return true; /* Self Cycle */
}
return false;
}
* of the set of nodes 'nodes'*/
public static SCC computeSCC(Collection nodes) {
if (nodes==null) {
- throw new NullPointerException();
+ throw new NullPointerException();
}
DFS dfs=new DFS(nodes);
dfs.sccmap=new HashMap();
dfs.finishingorder=new Vector();
boolean acyclic=dfs.go();
for (Iterator it = nodes.iterator(); it.hasNext(); ) {
- GraphNode gn = (GraphNode) it.next();
- gn.resetscc();
+ GraphNode gn = (GraphNode) it.next();
+ gn.resetscc();
}
for(int i=dfs.finishingorder.size()-1; i>=0; i--) {
- GraphNode gn=(GraphNode)dfs.finishingorder.get(i);
- if (gn.getStatus() == UNVISITED) {
- dfs.dfsprev(gn);
- dfs.sccindex++; /* Increment scc index */
- }
+ GraphNode gn=(GraphNode)dfs.finishingorder.get(i);
+ if (gn.getStatus() == UNVISITED) {
+ dfs.dfsprev(gn);
+ dfs.sccindex++; /* Increment scc index */
+ }
}
return new SCC(acyclic,dfs.sccmap,dfs.sccmaprev,dfs.sccindex);
}
void dfsprev(GraphNode gn) {
if (gn.getStatus()==FINISHED||!nodes.contains(gn))
- return;
+ return;
gn.setStatus(FINISHED);
Integer i=new Integer(sccindex);
if (!sccmap.containsKey(i))
- sccmap.put(i,new HashSet());
+ sccmap.put(i,new HashSet());
((Set)sccmap.get(i)).add(gn);
sccmaprev.put(gn,i);
for(Iterator edgeit=gn.inedges(); edgeit.hasNext(); ) {
- Edge e=(Edge)edgeit.next();
- GraphNode gn2=e.getSource();
- dfsprev(gn2);
+ Edge e=(Edge)edgeit.next();
+ GraphNode gn2=e.getSource();
+ dfsprev(gn2);
}
}
public static boolean depthFirstSearch(Collection nodes) {
if (nodes == null) {
- throw new NullPointerException();
+ throw new NullPointerException();
}
DFS dfs = new DFS(nodes);
boolean acyclic=true;
i = nodes.iterator();
while (i.hasNext()) {
- GraphNode gn = (GraphNode) i.next();
- gn.reset();
+ GraphNode gn = (GraphNode) i.next();
+ gn.reset();
}
i = nodes.iterator();
while (i.hasNext()) {
- GraphNode gn = (GraphNode) i.next();
- assert gn.getStatus() != PROCESSING;
- if (gn.getStatus() == UNVISITED) {
- if (!dfs(gn))
- acyclic=false;
- }
+ GraphNode gn = (GraphNode) i.next();
+ assert gn.getStatus() != PROCESSING;
+ if (gn.getStatus() == UNVISITED) {
+ if (!dfs(gn))
+ acyclic=false;
+ }
}
return acyclic;
}
Iterator edges = gn.edges();
while (edges.hasNext()) {
- Edge edge = (Edge) edges.next();
- edge.discover(edgetime++);
- GraphNode node = edge.getTarget();
- if (!nodes.contains(node)) { /* Skip nodes which aren't in the set */
- if(finishingorder_edge != null)
- finishingorder_edge.add(edge);
- edge.finish(edgetime++);
- continue;
- }
- if (node.getStatus() == UNVISITED) {
- if (!dfs(node))
- acyclic=false;
- } else if (node.getStatus()==PROCESSING) {
- acyclic=false;
- }
- if(finishingorder_edge != null)
- finishingorder_edge.add(edge);
- edge.finish(edgetime++);
+ Edge edge = (Edge) edges.next();
+ edge.discover(edgetime++);
+ GraphNode node = edge.getTarget();
+ if (!nodes.contains(node)) { /* Skip nodes which aren't in the set */
+ if(finishingorder_edge != null)
+ finishingorder_edge.add(edge);
+ edge.finish(edgetime++);
+ continue;
+ }
+ if (node.getStatus() == UNVISITED) {
+ if (!dfs(node))
+ acyclic=false;
+ } else if (node.getStatus()==PROCESSING) {
+ acyclic=false;
+ }
+ if(finishingorder_edge != null)
+ finishingorder_edge.add(edge);
+ edge.finish(edgetime++);
}
if (finishingorder!=null)
- finishingorder.add(gn);
+ finishingorder.add(gn);
gn.finish(time++);
return acyclic;
}
public static Vector topology(Collection nodes, Vector finishingorder_edge) {
if (nodes==null) {
- throw new NullPointerException();
+ throw new NullPointerException();
}
DFS dfs=new DFS(nodes);
dfs.finishingorder=new Vector();
if(finishingorder_edge != null) {
- dfs.finishingorder_edge = new Vector();
+ dfs.finishingorder_edge = new Vector();
}
boolean acyclic=dfs.go();
Vector topology = new Vector();
for(int i=dfs.finishingorder.size()-1; i>=0; i--) {
- GraphNode gn=(GraphNode)dfs.finishingorder.get(i);
- topology.add(gn);
+ GraphNode gn=(GraphNode)dfs.finishingorder.get(i);
+ topology.add(gn);
}
if(finishingorder_edge != null) {
- for(int i=dfs.finishingorder_edge.size()-1; i>=0; i--) {
- Edge gn=(Edge)dfs.finishingorder_edge.get(i);
- finishingorder_edge.add(gn);
- }
+ for(int i=dfs.finishingorder_edge.size()-1; i>=0; i--) {
+ Edge gn=(Edge)dfs.finishingorder_edge.get(i);
+ finishingorder_edge.add(gn);
+ }
}
return topology;
}
s.add(value);
if (!table.containsKey(value)) {
- Set<T> lowerNeighbor = new HashSet<T>();
- lowerNeighbor.add(bottom);
- table.put(value, lowerNeighbor);
+ Set<T> lowerNeighbor = new HashSet<T>();
+ lowerNeighbor.add(bottom);
+ table.put(value, lowerNeighbor);
}
// if value is already connected with top, it is no longer to be
oldReachableSize = reachableSet.size();
Set<T> nextLevelNeighbors = new HashSet<T>();
for (Iterator<T> iterator = neighborSet.iterator(); iterator.hasNext(); ) {
- T element = iterator.next();
- Set<T> neighbors = get(element);
- if (neighbors != null) {
- nextLevelNeighbors.addAll(neighbors);
- reachableSet.addAll(neighbors);
- }
-
- if (reachableSet.contains(key)) {
- // found cycle
- return true;
- }
+ T element = iterator.next();
+ Set<T> neighbors = get(element);
+ if (neighbors != null) {
+ nextLevelNeighbors.addAll(neighbors);
+ reachableSet.addAll(neighbors);
+ }
+
+ if (reachableSet.contains(key)) {
+ // found cycle
+ return true;
+ }
}
neighborSet = nextLevelNeighbors;
} while (oldReachableSize != reachableSet.size());
if (a.equals(top)) {
if (b.equals(top)) {
- return false;
+ return false;
}
return true;
}
} else {
boolean reachable = false;
for (Iterator<T> iterator = neighborSet.iterator(); iterator.hasNext(); ) {
- T neighbor = iterator.next();
- reachable = reachable || isGreaterThan(neighbor, b);
+ T neighbor = iterator.next();
+ reachable = reachable || isGreaterThan(neighbor, b);
}
return reachable;
}
T inputElement = inputIterator.next();
for (Iterator iterator = lowerSet.iterator(); iterator.hasNext(); ) {
- T lowerElement = (T) iterator.next();
- if (!inputElement.equals(lowerElement)) {
- if (!isGreaterThan(inputElement, lowerElement)) {
- toberemoved.add(lowerElement);
- }
- }
+ T lowerElement = (T) iterator.next();
+ if (!inputElement.equals(lowerElement)) {
+ if (!isGreaterThan(inputElement, lowerElement)) {
+ toberemoved.add(lowerElement);
+ }
+ }
}
}
lowerSet.removeAll(toberemoved);
T lowerElement = iterator.next();
boolean isGreaterThanAll = true;
for (Iterator<T> iterator2 = lowerSet.iterator(); iterator2.hasNext(); ) {
- T e = iterator2.next();
- if (!lowerElement.equals(e)) {
- if (!isGreaterThan(lowerElement, e)) {
- isGreaterThanAll = false;
- break;
- }
- }
+ T e = iterator2.next();
+ if (!lowerElement.equals(e)) {
+ if (!isGreaterThan(lowerElement, e)) {
+ isGreaterThanAll = false;
+ break;
+ }
+ }
}
if (isGreaterThanAll) {
- return lowerElement;
+ return lowerElement;
}
}
return null;
if (neighborSet != null) {
lowerSet.addAll(neighborSet);
for (Iterator<T> iterator = neighborSet.iterator(); iterator.hasNext(); ) {
- T neighbor = iterator.next();
- lowerSet = getLowerSet(neighbor, lowerSet);
+ T neighbor = iterator.next();
+ lowerSet = getLowerSet(neighbor, lowerSet);
}
}
return lowerSet;
int tupleKey = generateTupleKey(o, views[i]);\r
Hashtable tuplesTable = (Hashtable) viewTable.get(views[i]);\r
if(tuplesTable.containsKey(tupleKey)) {\r
- Set tupleSet = (Set) tuplesTable.get(tupleKey);\r
- tupleSet.add(o);\r
+ Set tupleSet = (Set) tuplesTable.get(tupleKey);\r
+ tupleSet.add(o);\r
} else {\r
- Set tupleSet = new HashSet();\r
- tupleSet.add(o);\r
- tuplesTable.put(tupleKey, tupleSet);\r
+ Set tupleSet = new HashSet();\r
+ tupleSet.add(o);\r
+ tuplesTable.put(tupleKey, tupleSet);\r
}\r
}\r
}\r
ArrayList<Integer> indices = new ArrayList<Integer>();\r
for(int i = 0; i < 31; i++) {\r
if((mask & viewIndex) != 0) {\r
- indices.add(i);\r
+ indices.add(i);\r
}\r
mask = mask << 1;\r
}\r
int tupleKey = generateTupleKey(o, views[i]);\r
Hashtable tuplesTable = (Hashtable) viewTable.get(views[i]);\r
if(tuplesTable.containsKey(tupleKey)) {\r
- tuplesTable.remove(tupleKey);\r
+ tuplesTable.remove(tupleKey);\r
} else {\r
- System.out.println("Cannot find such key");\r
+ System.out.println("Cannot find such key");\r
}\r
}\r
}\r
System.out.println("Hashtable "+i+":\t"+tmp.keySet().toString());\r
Object[] keySets = tmp.keySet().toArray();\r
for(int j = 0; j < keySets.length; j++) {\r
- System.out.println(tmp.get(keySets[j]));\r
+ System.out.println(tmp.get(keySets[j]));\r
}\r
}\r
}\r
ArrayList<Integer> indices = new ArrayList<Integer>();\r
for(int i = 0; i < 31; i++) {\r
if((mask & viewIndex) != 0) {\r
- indices.add(i);\r
+ indices.add(i);\r
}\r
mask = mask << 1;\r
}\r
HashSet s2 = (HashSet) a.get(key);
if( s2 == null ) {
- a.put(key, s1.clone() );
+ a.put(key, s1.clone() );
} else {
- s2.addAll(s1);
+ s2.addAll(s1);
}
}
}
Set bvals = (Set) b.get(akey);
if( bvals == null ) {
- // if b doesn't have the key, mark it for
- // safe removal after we traverse the map
- keysToRemove.add(akey);
+ // if b doesn't have the key, mark it for
+ // safe removal after we traverse the map
+ keysToRemove.add(akey);
} else {
- // otherwise we have the key, but pare
- // down the value set, if needed, and if
- // nothing is left, remove the key, too
- avals.retainAll(bvals);
- if( avals.isEmpty() ) {
- keysToRemove.add(akey);
- }
+ // otherwise we have the key, but pare
+ // down the value set, if needed, and if
+ // nothing is left, remove the key, too
+ avals.retainAll(bvals);
+ if( avals.isEmpty() ) {
+ keysToRemove.add(akey);
+ }
}
}
+indent_with_tabs = 0
indent_columns = 2
nl_if_brace = Remove
nl_brace_else = Remove
+indent_with_tabs = 0
indent_columns = 2
indent_class = True
nl_if_brace = Remove