1 package Analysis.OwnershipAnalysis;
3 import Analysis.CallGraph.*;
6 import IR.Tree.Modifiers;
11 public class OwnershipAnalysis {
14 ///////////////////////////////////////////
16 // Public interface to discover possible
17 // aliases in the program under analysis
19 ///////////////////////////////////////////
21 public HashSet<AllocationSite>
22 getFlaggedAllocationSitesReachableFromTask(TaskDescriptor td) {
23 return getFlaggedAllocationSitesReachableFromTaskPRIVATE(td);
26 public AllocationSite getAllocationSiteFromFlatNew(FlatNew fn) {
27 return getAllocationSiteFromFlatNewPRIVATE(fn);
31 public boolean createsPotentialAliases(Descriptor taskOrMethod,
35 OwnershipGraph og = getGraphOfAllContextsFromDescriptor(taskOrMethod);
37 return og.hasPotentialAlias(paramIndex1, paramIndex2);
40 public boolean createsPotentialAliases(Descriptor taskOrMethod,
42 AllocationSite alloc) {
44 OwnershipGraph og = getGraphOfAllContextsFromDescriptor(taskOrMethod);
46 return og.hasPotentialAlias(paramIndex, alloc);
49 public boolean createsPotentialAliases(Descriptor taskOrMethod,
53 OwnershipGraph og = getGraphOfAllContextsFromDescriptor(taskOrMethod);
55 return og.hasPotentialAlias(paramIndex, alloc);
58 public boolean createsPotentialAliases(Descriptor taskOrMethod,
59 AllocationSite alloc1,
60 AllocationSite alloc2) {
62 OwnershipGraph og = getGraphOfAllContextsFromDescriptor(taskOrMethod);
64 return og.hasPotentialAlias(alloc1, alloc2);
68 protected OwnershipGraph getGraphOfAllContextsFromDescriptor(Descriptor d) {
71 OwnershipGraph og = new OwnershipGraph( allocationDepth, typeUtil );
73 assert mapDescriptorToAllMethodContexts.containsKey( d );
74 HashSet<MethodContext> contexts = mapDescriptorToAllMethodContexts.get( d );
75 Iterator<MethodContext> mcItr = contexts.iterator();
76 while( mcItr.hasNext() ) {
77 MethodContext mc = mcItr.next();
79 OwnershipGraph ogContext = mapMethodContextToCompleteOwnershipGraph.get(mc);
80 assert ogContext != null;
82 og.merge( ogContext );
89 // use the methods given above to check every possible alias
90 // between task parameters and flagged allocation sites reachable
92 public void writeAllAliases(String outputFile) throws java.io.IOException {
94 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile) );
96 bw.write("Conducting ownership analysis with allocation depth = "+allocationDepth);
98 // look through every task for potential aliases
99 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
100 while( taskItr.hasNext() ) {
101 TaskDescriptor td = (TaskDescriptor) taskItr.next();
103 bw.write("\n---------"+td+"--------\n");
105 HashSet<AllocationSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
107 // for each task parameter, check for aliases with
108 // other task parameters and every allocation site
109 // reachable from this task
110 boolean foundSomeAlias = false;
112 FlatMethod fm = state.getMethodFlat(td);
113 for( int i = 0; i < fm.numParameters(); ++i ) {
115 // for the ith parameter check for aliases to all
116 // higher numbered parameters
117 for( int j = i + 1; j < fm.numParameters(); ++j ) {
118 if( createsPotentialAliases(td, i, j) ) {
119 foundSomeAlias = true;
120 bw.write("Potential alias between parameters "+i+" and "+j+".\n");
124 // for the ith parameter, check for aliases against
125 // the set of allocation sites reachable from this
127 Iterator allocItr = allocSites.iterator();
128 while( allocItr.hasNext() ) {
129 AllocationSite as = (AllocationSite) allocItr.next();
130 if( createsPotentialAliases(td, i, as) ) {
131 foundSomeAlias = true;
132 bw.write("Potential alias between parameter "+i+" and "+as.getFlatNew()+".\n");
137 // for each allocation site check for aliases with
138 // other allocation sites in the context of execution
140 HashSet<AllocationSite> outerChecked = new HashSet<AllocationSite>();
141 Iterator allocItr1 = allocSites.iterator();
142 while( allocItr1.hasNext() ) {
143 AllocationSite as1 = (AllocationSite) allocItr1.next();
145 Iterator allocItr2 = allocSites.iterator();
146 while( allocItr2.hasNext() ) {
147 AllocationSite as2 = (AllocationSite) allocItr2.next();
149 if( !outerChecked.contains(as2) &&
150 createsPotentialAliases(td, as1, as2) ) {
151 foundSomeAlias = true;
152 bw.write("Potential alias between "+as1.getFlatNew()+" and "+as2.getFlatNew()+".\n");
156 outerChecked.add(as1);
159 if( !foundSomeAlias ) {
160 bw.write("No aliases between flagged objects in Task "+td+".\n");
168 // this version of writeAllAliases is for Java programs that have no tasks
169 public void writeAllAliasesJava(String outputFile) throws java.io.IOException {
172 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile) );
174 bw.write("Conducting ownership analysis with allocation depth = "+allocationDepth+"\n");
175 boolean foundSomeAlias = false;
177 Descriptor d = typeUtil.getMain();
178 HashSet<AllocationSite> allocSites = getFlaggedAllocationSites(d);
180 // for each allocation site check for aliases with
181 // other allocation sites in the context of execution
183 HashSet<AllocationSite> outerChecked = new HashSet<AllocationSite>();
184 Iterator allocItr1 = allocSites.iterator();
185 while( allocItr1.hasNext() ) {
186 AllocationSite as1 = (AllocationSite) allocItr1.next();
188 Iterator allocItr2 = allocSites.iterator();
189 while( allocItr2.hasNext() ) {
190 AllocationSite as2 = (AllocationSite) allocItr2.next();
192 if( !outerChecked.contains(as2) &&
193 createsPotentialAliases(d, as1, as2) ) {
194 foundSomeAlias = true;
195 bw.write("Potential alias between "+as1.getDisjointId()+" and "+as2.getDisjointId()+".\n");
199 outerChecked.add(as1);
202 if( !foundSomeAlias ) {
203 bw.write("No aliases between flagged objects found.\n");
208 ///////////////////////////////////////////
210 // end public interface
212 ///////////////////////////////////////////
221 // data from the compiler
223 private TypeUtil typeUtil;
224 private CallGraph callGraph;
225 private int allocationDepth;
227 // used to identify HeapRegionNode objects
228 // A unique ID equates an object in one
229 // ownership graph with an object in another
230 // graph that logically represents the same
232 // start at 10 and increment to leave some
233 // reserved IDs for special purposes
234 static private int uniqueIDcount = 10;
237 // Use these data structures to track progress of
238 // processing all methods in the program, and by methods
239 // TaskDescriptor and MethodDescriptor are combined
240 // together, with a common parent class Descriptor
241 private Hashtable<MethodContext, OwnershipGraph> mapMethodContextToInitialParamAllocGraph;
242 private Hashtable<MethodContext, OwnershipGraph> mapMethodContextToCompleteOwnershipGraph;
243 private Hashtable<FlatNew, AllocationSite> mapFlatNewToAllocationSite;
244 private Hashtable<Descriptor, HashSet<AllocationSite> > mapDescriptorToAllocationSiteSet;
245 private Hashtable<MethodContext, Integer> mapMethodContextToNumUpdates;
246 private Hashtable<Descriptor, HashSet<MethodContext> > mapDescriptorToAllMethodContexts;
248 // Use these data structures to track progress of one pass of
249 // processing the FlatNodes of a particular method
250 private HashSet <FlatNode> flatNodesToVisit;
251 private Hashtable<FlatNode, OwnershipGraph> mapFlatNodeToOwnershipGraph;
252 private HashSet <FlatReturnNode> returnNodesToCombineForCompleteOwnershipGraph;
254 // descriptorsToAnalyze identifies the set of tasks and methods
255 // that are reachable from the program tasks, this set is initialized
256 // and then remains static
257 private HashSet<Descriptor> descriptorsToAnalyze;
259 // descriptorsToVisit is initialized to descriptorsToAnalyze and is
260 // reduced by visiting a descriptor during analysis. When dependents
261 // must be scheduled, only those contained in descriptorsToAnalyze
262 // should be re-added to this set
263 private HashSet <MethodContext> methodContextsToVisit;
265 // used in conjunction with the methodContextsToVisit set, fill with
266 // a topological sort of methodContextsToVisit and then empty that set
267 // algorithm should analyze something in the linked list until it is
268 // empty, and then work on the set as normal. The sorted linked list
269 // is just another, specially sorted bucket that is part of the
270 // methodContextsToVisit set
271 private LinkedList<MethodContext> sortedMethodContextsToVisit;
274 // a special field descriptor for all array elements
275 private static FieldDescriptor fdElement = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC),
276 new TypeDescriptor("Array[]"),
281 // a special temp descriptor for setting more than one parameter label
282 // to the all-aliased-parameters heap region node
283 protected static TempDescriptor tdAliasedParams = new TempDescriptor("_AllAliasedParams___");
286 // for controlling DOT file output
287 private boolean writeDOTs;
288 private boolean writeAllDOTs;
292 // this analysis generates an ownership graph for every task
294 public OwnershipAnalysis(State state,
299 boolean writeAllDOTs,
300 String aliasFile) throws java.io.IOException {
302 double timeStartAnalysis = (double) System.nanoTime();
306 this.callGraph = callGraph;
307 this.allocationDepth = allocationDepth;
308 this.writeDOTs = writeDOTs;
309 this.writeAllDOTs = writeAllDOTs;
311 descriptorsToAnalyze = new HashSet<Descriptor>();
313 mapMethodContextToInitialParamAllocGraph =
314 new Hashtable<MethodContext, OwnershipGraph>();
316 mapMethodContextToCompleteOwnershipGraph =
317 new Hashtable<MethodContext, OwnershipGraph>();
319 mapFlatNewToAllocationSite =
320 new Hashtable<FlatNew, AllocationSite>();
322 mapDescriptorToAllocationSiteSet =
323 new Hashtable<Descriptor, HashSet<AllocationSite> >();
325 mapDescriptorToAllMethodContexts =
326 new Hashtable<Descriptor, HashSet<MethodContext> >();
330 mapMethodContextToNumUpdates = new Hashtable<MethodContext, Integer>();
335 // initialize methods to visit as the set of all tasks in the
336 // program and then any method that could be called starting
338 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
339 while( taskItr.hasNext() ) {
340 Descriptor d = (Descriptor) taskItr.next();
341 scheduleAllCallees(d);
345 // we are not in task mode, just normal Java, so start with
347 Descriptor d = typeUtil.getMain();
348 scheduleAllCallees(d);
352 // before beginning analysis, initialize every scheduled method
353 // with an ownership graph that has populated parameter index tables
354 // by analyzing the first node which is always a FlatMethod node
355 Iterator<Descriptor> dItr = descriptorsToAnalyze.iterator();
356 while( dItr.hasNext() ) {
357 Descriptor d = dItr.next();
358 OwnershipGraph og = new OwnershipGraph(allocationDepth, typeUtil);
361 if( d instanceof MethodDescriptor ) {
362 fm = state.getMethodFlat( (MethodDescriptor) d);
364 assert d instanceof TaskDescriptor;
365 fm = state.getMethodFlat( (TaskDescriptor) d);
368 MethodContext mc = new MethodContext( d );
369 assert !mapDescriptorToAllMethodContexts.containsKey( d );
370 HashSet<MethodContext> s = new HashSet<MethodContext>();
372 mapDescriptorToAllMethodContexts.put( d, s );
374 //System.out.println("Previsiting " + mc);
376 og = analyzeFlatNode(mc, fm, null, og);
377 setGraphForMethodContext(mc, og);
380 // as mentioned above, analyze methods one-by-one, possibly revisiting
381 // a method if the methods that it calls are updated
384 double timeEndAnalysis = (double) System.nanoTime();
385 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
386 String treport = String.format( "The analysis took %.3f sec.", dt );
387 System.out.println( treport );
389 if( writeDOTs && !writeAllDOTs ) {
390 writeFinalContextGraphs();
393 if( aliasFile != null ) {
395 writeAllAliases(aliasFile);
397 writeAllAliasesJava(aliasFile);
402 // called from the constructor to help initialize the set
403 // of methods that needs to be analyzed by ownership analysis
404 private void scheduleAllCallees(Descriptor d) {
405 if( descriptorsToAnalyze.contains(d) ) {
408 descriptorsToAnalyze.add(d);
410 // start with all method calls to further schedule
411 Set moreMethodsToCheck = moreMethodsToCheck = callGraph.getMethodCalls(d);
413 if( d instanceof MethodDescriptor ) {
414 // see if this method has virtual dispatch
415 Set virtualMethods = callGraph.getMethods( (MethodDescriptor)d);
416 moreMethodsToCheck.addAll(virtualMethods);
419 // keep following any further methods identified in
421 Iterator methItr = moreMethodsToCheck.iterator();
422 while( methItr.hasNext() ) {
423 Descriptor m = (Descriptor) methItr.next();
424 scheduleAllCallees(m);
429 // manage the set of tasks and methods to be analyzed
430 // and be sure to reschedule tasks/methods when the methods
431 // they call are updated
432 private void analyzeMethods() throws java.io.IOException {
434 methodContextsToVisit = new HashSet <MethodContext>();
435 sortedMethodContextsToVisit = new LinkedList<MethodContext>();
437 Iterator<Descriptor> itrd2a = descriptorsToAnalyze.iterator();
438 while( itrd2a.hasNext() ) {
439 HashSet<MethodContext> mcs = mapDescriptorToAllMethodContexts.get( itrd2a.next() );
442 Iterator<MethodContext> itrmc = mcs.iterator();
443 while( itrmc.hasNext() ) {
444 methodContextsToVisit.add( itrmc.next() );
448 sortedMethodContextsToVisit = topologicalSort( methodContextsToVisit );
449 methodContextsToVisit.clear();
451 while( !methodContextsToVisit.isEmpty() ||
452 !sortedMethodContextsToVisit.isEmpty() ) {
454 MethodContext mc = null;
456 if( !sortedMethodContextsToVisit.isEmpty() ) {
457 mc = sortedMethodContextsToVisit.removeFirst();
459 mc = methodContextsToVisit.iterator().next();
460 methodContextsToVisit.remove(mc);
464 // because the task or method descriptor just extracted
465 // was in the "to visit" set it either hasn't been analyzed
466 // yet, or some method that it depends on has been
467 // updated. Recompute a complete ownership graph for
468 // this task/method and compare it to any previous result.
469 // If there is a change detected, add any methods/tasks
470 // that depend on this one to the "to visit" set.
472 System.out.println("Analyzing " + mc);
474 Descriptor d = mc.getDescriptor();
476 if( d instanceof MethodDescriptor ) {
477 fm = state.getMethodFlat( (MethodDescriptor) d);
479 assert d instanceof TaskDescriptor;
480 fm = state.getMethodFlat( (TaskDescriptor) d);
483 OwnershipGraph og = analyzeFlatMethod(mc, fm);
484 OwnershipGraph ogPrev = mapMethodContextToCompleteOwnershipGraph.get(mc);
485 if( !og.equals(ogPrev) ) {
486 setGraphForMethodContext(mc, og);
488 // only methods have dependents, tasks cannot
489 // be invoked by any user program calls
490 if( d instanceof MethodDescriptor ) {
491 MethodDescriptor md = (MethodDescriptor) d;
492 Set dependents = callGraph.getCallerSet(md);
493 if( dependents != null ) {
494 Iterator depItr = dependents.iterator();
495 while( depItr.hasNext() ) {
496 Descriptor dependent = (Descriptor) depItr.next();
497 if( descriptorsToAnalyze.contains(dependent) ) {
499 HashSet<MethodContext> mcs = mapDescriptorToAllMethodContexts.get( dependent );
502 Iterator<MethodContext> itrmc = mcs.iterator();
503 while( itrmc.hasNext() ) {
504 methodContextsToVisit.add( itrmc.next() );
516 // keep passing the Descriptor of the method along for debugging
517 // and dot file writing
518 private OwnershipGraph
519 analyzeFlatMethod(MethodContext mc,
520 FlatMethod flatm) throws java.io.IOException {
522 // initialize flat nodes to visit as the flat method
523 // because it is the entry point
525 flatNodesToVisit = new HashSet<FlatNode>();
526 flatNodesToVisit.add(flatm);
528 // initilize the mapping of flat nodes in this flat method to
529 // ownership graph results to an empty mapping
530 mapFlatNodeToOwnershipGraph = new Hashtable<FlatNode, OwnershipGraph>();
532 // initialize the set of return nodes that will be combined as
533 // the final ownership graph result to return as an empty set
534 returnNodesToCombineForCompleteOwnershipGraph = new HashSet<FlatReturnNode>();
537 while( !flatNodesToVisit.isEmpty() ) {
538 FlatNode fn = (FlatNode) flatNodesToVisit.iterator().next();
539 flatNodesToVisit.remove(fn);
541 //System.out.println( " "+fn );
543 // perform this node's contributions to the ownership
544 // graph on a new copy, then compare it to the old graph
545 // at this node to see if anything was updated.
546 OwnershipGraph og = new OwnershipGraph(allocationDepth, typeUtil);
548 // start by merging all node's parents' graphs
549 for( int i = 0; i < fn.numPrev(); ++i ) {
550 FlatNode pn = fn.getPrev(i);
551 if( mapFlatNodeToOwnershipGraph.containsKey(pn) ) {
552 OwnershipGraph ogParent = mapFlatNodeToOwnershipGraph.get(pn);
557 // apply the analysis of the flat node to the
558 // ownership graph made from the merge of the
560 og = analyzeFlatNode(mc,
562 returnNodesToCombineForCompleteOwnershipGraph,
566 if( mc.getDescriptor().getSymbol().equals( "addFlightPlan" ) ) {
567 debugSnapshot(og,fn);
572 // if the results of the new graph are different from
573 // the current graph at this node, replace the graph
574 // with the update and enqueue the children for
576 OwnershipGraph ogPrev = mapFlatNodeToOwnershipGraph.get(fn);
577 if( !og.equals(ogPrev) ) {
578 mapFlatNodeToOwnershipGraph.put(fn, og);
580 for( int i = 0; i < fn.numNext(); i++ ) {
581 FlatNode nn = fn.getNext(i);
582 flatNodesToVisit.add(nn);
587 // end by merging all return nodes into a complete
588 // ownership graph that represents all possible heap
589 // states after the flat method returns
590 OwnershipGraph completeGraph = new OwnershipGraph(allocationDepth, typeUtil);
591 Iterator retItr = returnNodesToCombineForCompleteOwnershipGraph.iterator();
592 while( retItr.hasNext() ) {
593 FlatReturnNode frn = (FlatReturnNode) retItr.next();
594 assert mapFlatNodeToOwnershipGraph.containsKey(frn);
595 OwnershipGraph ogr = mapFlatNodeToOwnershipGraph.get(frn);
596 completeGraph.merge(ogr);
599 return completeGraph;
603 private OwnershipGraph
604 analyzeFlatNode(MethodContext mc,
606 HashSet<FlatReturnNode> setRetNodes,
607 OwnershipGraph og) throws java.io.IOException {
613 // use node type to decide what alterations to make
614 // to the ownership graph
615 switch( fn.kind() ) {
617 case FKind.FlatMethod:
618 FlatMethod fm = (FlatMethod) fn;
620 // there should only be one FlatMethod node as the
621 // parent of all other FlatNode objects, so take
622 // the opportunity to construct the initial graph by
623 // adding parameters labels to new heap regions
624 // AND this should be done once globally so that the
625 // parameter IDs are consistent between analysis
626 // iterations, so if this step has been done already
627 // just merge in the cached version
628 OwnershipGraph ogInitParamAlloc = mapMethodContextToInitialParamAllocGraph.get(mc);
629 if( ogInitParamAlloc == null ) {
631 // if the method context has aliased parameters, make sure
632 // there is a blob region for all those param labels to
634 Set<Integer> aliasedParamIndices = mc.getAliasedParamIndices();
635 if( !aliasedParamIndices.isEmpty() ) {
636 og.makeAliasedParamHeapRegionNode( tdAliasedParams );
639 // set up each parameter
640 for( int i = 0; i < fm.numParameters(); ++i ) {
641 TempDescriptor tdParam = fm.getParameter( i );
642 Integer paramIndex = new Integer( i );
644 if( aliasedParamIndices.contains( paramIndex ) ) {
645 // just point this one to the alias blob
646 og.assignTempEqualToAliasedParam( tdParam,
650 // this parameter is not aliased to others, give it
651 // a fresh parameter heap region
653 og.assignTempEqualToParamAlloc(tdParam,
654 mc.getDescriptor() instanceof TaskDescriptor,
660 OwnershipGraph ogResult = new OwnershipGraph(allocationDepth, typeUtil);
662 mapMethodContextToInitialParamAllocGraph.put(mc, ogResult);
665 // or just leverage the cached copy
666 og.merge(ogInitParamAlloc);
670 case FKind.FlatOpNode:
671 FlatOpNode fon = (FlatOpNode) fn;
672 if( fon.getOp().getOp() == Operation.ASSIGN ) {
675 og.assignTempXEqualToTempY(lhs, rhs);
679 case FKind.FlatFieldNode:
680 FlatFieldNode ffn = (FlatFieldNode) fn;
683 fld = ffn.getField();
684 if( !fld.getType().isImmutable() || fld.getType().isArray() ) {
685 og.assignTempXEqualToTempYFieldF(lhs, rhs, fld);
689 case FKind.FlatSetFieldNode:
690 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
692 fld = fsfn.getField();
694 if( !fld.getType().isImmutable() || fld.getType().isArray() ) {
695 og.assignTempXFieldFEqualToTempY(lhs, fld, rhs);
699 case FKind.FlatElementNode:
700 FlatElementNode fen = (FlatElementNode) fn;
703 if( !lhs.getType().isImmutable() || lhs.getType().isArray() ) {
704 og.assignTempXEqualToTempYFieldF(lhs, rhs, fdElement);
708 case FKind.FlatSetElementNode:
709 FlatSetElementNode fsen = (FlatSetElementNode) fn;
712 if( !rhs.getType().isImmutable() || rhs.getType().isArray() ) {
713 og.assignTempXFieldFEqualToTempY(lhs, fdElement, rhs);
718 FlatNew fnn = (FlatNew) fn;
720 if( !lhs.getType().isImmutable() || lhs.getType().isArray() ) {
721 AllocationSite as = getAllocationSiteFromFlatNewPRIVATE(fnn);
722 og.assignTempEqualToNewAlloc(lhs, as);
727 FlatCall fc = (FlatCall) fn;
728 MethodDescriptor md = fc.getMethod();
729 FlatMethod flatm = state.getMethodFlat(md);
730 OwnershipGraph ogMergeOfAllPossibleCalleeResults = new OwnershipGraph(allocationDepth, typeUtil);
732 if( md.isStatic() ) {
733 // a static method is simply always the same, makes life easy
734 ogMergeOfAllPossibleCalleeResults = og;
736 Set<Integer> aliasedParamIndices =
737 ogMergeOfAllPossibleCalleeResults.calculateAliasedParamSet(fc, md.isStatic(), flatm);
738 MethodContext mcNew = new MethodContext( md, aliasedParamIndices );
739 OwnershipGraph onlyPossibleCallee = mapMethodContextToCompleteOwnershipGraph.get( mcNew );
741 if( onlyPossibleCallee == null ) {
742 // if this method context has never been analyzed just schedule it for analysis
743 // and skip over this call site for now
744 methodContextsToVisit.add( mcNew );
747 ogMergeOfAllPossibleCalleeResults.resolveMethodCall(fc, md.isStatic(), flatm, onlyPossibleCallee);
751 // if the method descriptor is virtual, then there could be a
752 // set of possible methods that will actually be invoked, so
753 // find all of them and merge all of their results together
754 TypeDescriptor typeDesc = fc.getThis().getType();
755 Set possibleCallees = callGraph.getMethods(md, typeDesc);
757 Iterator i = possibleCallees.iterator();
758 while( i.hasNext() ) {
759 MethodDescriptor possibleMd = (MethodDescriptor) i.next();
760 FlatMethod pflatm = state.getMethodFlat(possibleMd);
762 // don't alter the working graph (og) until we compute a result for every
763 // possible callee, merge them all together, then set og to that
764 OwnershipGraph ogCopy = new OwnershipGraph(allocationDepth, typeUtil);
767 Set<Integer> aliasedParamIndices =
768 ogCopy.calculateAliasedParamSet(fc, possibleMd.isStatic(), pflatm);
769 MethodContext mcNew = new MethodContext( possibleMd, aliasedParamIndices );
770 OwnershipGraph ogPotentialCallee = mapMethodContextToCompleteOwnershipGraph.get( mcNew );
772 if( ogPotentialCallee == null ) {
773 // if this method context has never been analyzed just schedule it for analysis
774 // and skip over this call site for now
775 methodContextsToVisit.add( mcNew );
778 ogCopy.resolveMethodCall(fc, possibleMd.isStatic(), pflatm, ogPotentialCallee);
781 ogMergeOfAllPossibleCalleeResults.merge(ogCopy);
785 og = ogMergeOfAllPossibleCalleeResults;
788 case FKind.FlatReturnNode:
789 FlatReturnNode frn = (FlatReturnNode) fn;
790 rhs = frn.getReturnTemp();
791 if( rhs != null && !rhs.getType().isImmutable() ) {
792 og.assignReturnEqualToTemp(rhs);
794 setRetNodes.add(frn);
802 // insert a call to debugSnapshot() somewhere in the analysis to get
803 // successive captures of the analysis state
804 int debugCounter = 0;
805 int numStartCountReport = 0;
806 int freqCountReport = 1;
807 int iterStartCapture = 0;
808 int numIterToCapture = 500;
809 void debugSnapshot(OwnershipGraph og, FlatNode fn) {
810 if( debugCounter > numStartCountReport + numIterToCapture ) {
815 if( debugCounter > numStartCountReport &&
816 debugCounter % freqCountReport == 0 ) {
817 System.out.println(" @@@ debug counter = "+debugCounter);
819 if( debugCounter > iterStartCapture ) {
820 System.out.println(" @@@ capturing debug "+(debugCounter-iterStartCapture)+" @@@");
821 String graphName = String.format("snap%04d",debugCounter-iterStartCapture);
823 graphName = graphName+fn;
826 og.writeGraph(graphName, true, true, false, false, false);
827 } catch( Exception e ) {
828 System.out.println("Error writing debug capture.");
833 if( debugCounter == iterStartCapture + numIterToCapture ) {
834 System.out.println("Stopping analysis after debug captures.");
842 // this method should generate integers strictly greater than zero!
843 // special "shadow" regions are made from a heap region by negating
845 static public Integer generateUniqueHeapRegionNodeID() {
847 return new Integer(uniqueIDcount);
851 private void setGraphForMethodContext(MethodContext mc, OwnershipGraph og) {
853 mapMethodContextToCompleteOwnershipGraph.put(mc, og);
855 if( writeDOTs && writeAllDOTs ) {
856 if( !mapMethodContextToNumUpdates.containsKey(mc) ) {
857 mapMethodContextToNumUpdates.put(mc, new Integer(0) );
859 Integer n = mapMethodContextToNumUpdates.get(mc);
861 og.writeGraph(mc, n, true, true, true, false, false);
862 } catch( IOException e ) {}
863 mapMethodContextToNumUpdates.put(mc, n + 1);
868 private void writeFinalContextGraphs() {
869 // arguments to writeGraph are:
870 // boolean writeLabels,
871 // boolean labelSelect,
872 // boolean pruneGarbage,
873 // boolean writeReferencers
874 // boolean writeParamMappings
876 Set entrySet = mapMethodContextToCompleteOwnershipGraph.entrySet();
877 Iterator itr = entrySet.iterator();
878 while( itr.hasNext() ) {
879 Map.Entry me = (Map.Entry) itr.next();
880 MethodContext mc = (MethodContext) me.getKey();
881 OwnershipGraph og = (OwnershipGraph) me.getValue();
884 og.writeGraph(mc, true, true, true, false, false);
885 } catch( IOException e ) {}
890 // return just the allocation site associated with one FlatNew node
891 private AllocationSite getAllocationSiteFromFlatNewPRIVATE(FlatNew fn) {
893 if( !mapFlatNewToAllocationSite.containsKey(fn) ) {
894 AllocationSite as = new AllocationSite(allocationDepth, fn, fn.getDisjointId());
896 // the newest nodes are single objects
897 for( int i = 0; i < allocationDepth; ++i ) {
898 Integer id = generateUniqueHeapRegionNodeID();
899 as.setIthOldest(i, id);
902 // the oldest node is a summary node
903 Integer idSummary = generateUniqueHeapRegionNodeID();
904 as.setSummary(idSummary);
906 mapFlatNewToAllocationSite.put(fn, as);
909 return mapFlatNewToAllocationSite.get(fn);
913 // return all allocation sites in the method (there is one allocation
914 // site per FlatNew node in a method)
915 private HashSet<AllocationSite> getAllocationSiteSet(Descriptor d) {
916 if( !mapDescriptorToAllocationSiteSet.containsKey(d) ) {
917 buildAllocationSiteSet(d);
920 return mapDescriptorToAllocationSiteSet.get(d);
924 private void buildAllocationSiteSet(Descriptor d) {
925 HashSet<AllocationSite> s = new HashSet<AllocationSite>();
928 if( d instanceof MethodDescriptor ) {
929 fm = state.getMethodFlat( (MethodDescriptor) d);
931 assert d instanceof TaskDescriptor;
932 fm = state.getMethodFlat( (TaskDescriptor) d);
935 // visit every node in this FlatMethod's IR graph
936 // and make a set of the allocation sites from the
937 // FlatNew node's visited
938 HashSet<FlatNode> visited = new HashSet<FlatNode>();
939 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
942 while( !toVisit.isEmpty() ) {
943 FlatNode n = toVisit.iterator().next();
945 if( n instanceof FlatNew ) {
946 s.add(getAllocationSiteFromFlatNewPRIVATE( (FlatNew) n) );
952 for( int i = 0; i < n.numNext(); ++i ) {
953 FlatNode child = n.getNext(i);
954 if( !visited.contains(child) ) {
960 mapDescriptorToAllocationSiteSet.put(d, s);
964 private HashSet<AllocationSite> getFlaggedAllocationSites(Descriptor dIn) {
966 HashSet<AllocationSite> out = new HashSet<AllocationSite>();
967 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
968 HashSet<Descriptor> visited = new HashSet<Descriptor>();
972 while( !toVisit.isEmpty() ) {
973 Descriptor d = toVisit.iterator().next();
977 HashSet<AllocationSite> asSet = getAllocationSiteSet(d);
978 Iterator asItr = asSet.iterator();
979 while( asItr.hasNext() ) {
980 AllocationSite as = (AllocationSite) asItr.next();
981 if( as.getDisjointId() != null ) {
986 // enqueue callees of this method to be searched for
987 // allocation sites also
988 Set callees = callGraph.getCalleeSet(d);
989 if( callees != null ) {
990 Iterator methItr = callees.iterator();
991 while( methItr.hasNext() ) {
992 MethodDescriptor md = (MethodDescriptor) methItr.next();
994 if( !visited.contains(md) ) {
1005 private HashSet<AllocationSite>
1006 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
1008 HashSet<AllocationSite> asSetTotal = new HashSet<AllocationSite>();
1009 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1010 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1014 // traverse this task and all methods reachable from this task
1015 while( !toVisit.isEmpty() ) {
1016 Descriptor d = toVisit.iterator().next();
1020 HashSet<AllocationSite> asSet = getAllocationSiteSet(d);
1021 Iterator asItr = asSet.iterator();
1022 while( asItr.hasNext() ) {
1023 AllocationSite as = (AllocationSite) asItr.next();
1024 TypeDescriptor typed = as.getType();
1025 if( typed != null ) {
1026 ClassDescriptor cd = typed.getClassDesc();
1027 if( cd != null && cd.hasFlags() ) {
1033 // enqueue callees of this method to be searched for
1034 // allocation sites also
1035 Set callees = callGraph.getCalleeSet(d);
1036 if( callees != null ) {
1037 Iterator methItr = callees.iterator();
1038 while( methItr.hasNext() ) {
1039 MethodDescriptor md = (MethodDescriptor) methItr.next();
1041 if( !visited.contains(md) ) {
1053 private LinkedList<MethodContext> topologicalSort( HashSet<MethodContext> set ) {
1054 HashSet <MethodContext> discovered = new HashSet <MethodContext>();
1055 LinkedList<MethodContext> sorted = new LinkedList<MethodContext>();
1057 Iterator<MethodContext> itr = set.iterator();
1058 while( itr.hasNext() ) {
1059 MethodContext mc = itr.next();
1061 if( !discovered.contains( mc ) ) {
1062 dfsVisit( set, mc, sorted, discovered );
1069 private void dfsVisit( HashSet<MethodContext> set,
1071 LinkedList<MethodContext> sorted,
1072 HashSet <MethodContext> discovered ) {
1073 discovered.add( mc );
1075 Descriptor d = mc.getDescriptor();
1076 if( d instanceof MethodDescriptor ) {
1077 MethodDescriptor md = (MethodDescriptor) d;
1078 Iterator itr = callGraph.getCallerSet( md ).iterator();
1079 while( itr.hasNext() ) {
1080 Descriptor dCaller = (Descriptor) itr.next();
1082 // only consider the callers in the original set to analyze
1083 Set<MethodContext> callerContexts = mapDescriptorToAllMethodContexts.get( dCaller );
1084 if( callerContexts == null )
1087 // since the analysis hasn't started, there should be exactly one
1088 // context if there are any at all
1089 assert callerContexts.size() == 1;
1090 MethodContext mcCaller = callerContexts.iterator().next();
1091 assert set.contains( mcCaller );
1093 if( !discovered.contains( mcCaller ) ) {
1094 dfsVisit( set, mcCaller, sorted, discovered );
1099 sorted.addFirst( mc );