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 checkAnalysisComplete();
24 return getFlaggedAllocationSitesReachableFromTaskPRIVATE(td);
27 public AllocationSite getAllocationSiteFromFlatNew(FlatNew fn) {
28 checkAnalysisComplete();
29 return getAllocationSiteFromFlatNewPRIVATE(fn);
32 public AllocationSite getAllocationSiteFromHeapRegionNodeID(Integer id) {
33 checkAnalysisComplete();
34 return mapHrnIdToAllocationSite.get(id);
37 public Set<HeapRegionNode> createsPotentialAliases(Descriptor taskOrMethod,
40 checkAnalysisComplete();
41 OwnershipGraph og = getGraphOfAllContextsFromDescriptor(taskOrMethod);
43 return og.hasPotentialAlias(paramIndex1, paramIndex2);
46 public Set<HeapRegionNode> createsPotentialAliases(Descriptor taskOrMethod,
48 AllocationSite alloc) {
49 checkAnalysisComplete();
50 OwnershipGraph og = getGraphOfAllContextsFromDescriptor(taskOrMethod);
52 return og.hasPotentialAlias(paramIndex, alloc);
55 public Set<HeapRegionNode> createsPotentialAliases(Descriptor taskOrMethod,
58 checkAnalysisComplete();
59 OwnershipGraph og = getGraphOfAllContextsFromDescriptor(taskOrMethod);
61 return og.hasPotentialAlias(paramIndex, alloc);
64 public Set<HeapRegionNode> createsPotentialAliases(Descriptor taskOrMethod,
65 AllocationSite alloc1,
66 AllocationSite alloc2) {
67 checkAnalysisComplete();
68 OwnershipGraph og = getGraphOfAllContextsFromDescriptor(taskOrMethod);
70 return og.hasPotentialAlias(alloc1, alloc2);
74 protected OwnershipGraph getGraphOfAllContextsFromDescriptor(Descriptor d) {
75 checkAnalysisComplete();
79 OwnershipGraph og = new OwnershipGraph( allocationDepth, typeUtil );
81 assert mapDescriptorToAllMethodContexts.containsKey( d );
82 HashSet<MethodContext> contexts = mapDescriptorToAllMethodContexts.get( d );
83 Iterator<MethodContext> mcItr = contexts.iterator();
84 while( mcItr.hasNext() ) {
85 MethodContext mc = mcItr.next();
87 OwnershipGraph ogContext = mapMethodContextToCompleteOwnershipGraph.get(mc);
88 assert ogContext != null;
90 og.merge( ogContext );
97 public String prettyPrintNodeSet( Set<HeapRegionNode> s ) {
98 checkAnalysisComplete();
102 Iterator<HeapRegionNode> i = s.iterator();
103 while( i.hasNext() ) {
104 HeapRegionNode n = i.next();
106 AllocationSite as = n.getAllocationSite();
108 out += " "+n.toString()+",\n";
110 out += " "+n.toString()+": "+as.toStringVerbose()+",\n";
119 // use the methods given above to check every possible alias
120 // between task parameters and flagged allocation sites reachable
122 public void writeAllAliases(String outputFile, String timeReport) throws java.io.IOException {
123 checkAnalysisComplete();
125 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile) );
127 bw.write("Conducting ownership analysis with allocation depth = "+allocationDepth+"\n");
128 bw.write(timeReport+"\n");
130 // look through every task for potential aliases
131 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
132 while( taskItr.hasNext() ) {
133 TaskDescriptor td = (TaskDescriptor) taskItr.next();
135 bw.write("\n---------"+td+"--------\n");
137 HashSet<AllocationSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
139 Set<HeapRegionNode> common;
141 // for each task parameter, check for aliases with
142 // other task parameters and every allocation site
143 // reachable from this task
144 boolean foundSomeAlias = false;
146 FlatMethod fm = state.getMethodFlat(td);
147 for( int i = 0; i < fm.numParameters(); ++i ) {
149 // for the ith parameter check for aliases to all
150 // higher numbered parameters
151 for( int j = i + 1; j < fm.numParameters(); ++j ) {
152 common = createsPotentialAliases(td, i, j);
153 if( !common.isEmpty() ) {
154 foundSomeAlias = true;
155 bw.write("Potential alias between parameters "+i+" and "+j+".\n");
156 bw.write(prettyPrintNodeSet( common )+"\n" );
160 // for the ith parameter, check for aliases against
161 // the set of allocation sites reachable from this
163 Iterator allocItr = allocSites.iterator();
164 while( allocItr.hasNext() ) {
165 AllocationSite as = (AllocationSite) allocItr.next();
166 common = createsPotentialAliases(td, i, as);
167 if( !common.isEmpty() ) {
168 foundSomeAlias = true;
169 bw.write("Potential alias between parameter "+i+" and "+as.getFlatNew()+".\n");
170 bw.write(prettyPrintNodeSet( common )+"\n" );
175 // for each allocation site check for aliases with
176 // other allocation sites in the context of execution
178 HashSet<AllocationSite> outerChecked = new HashSet<AllocationSite>();
179 Iterator allocItr1 = allocSites.iterator();
180 while( allocItr1.hasNext() ) {
181 AllocationSite as1 = (AllocationSite) allocItr1.next();
183 Iterator allocItr2 = allocSites.iterator();
184 while( allocItr2.hasNext() ) {
185 AllocationSite as2 = (AllocationSite) allocItr2.next();
187 if( !outerChecked.contains(as2) ) {
188 common = createsPotentialAliases(td, as1, as2);
190 if( !common.isEmpty() ) {
191 foundSomeAlias = true;
192 bw.write("Potential alias between "+as1.getFlatNew()+" and "+as2.getFlatNew()+".\n");
193 bw.write(prettyPrintNodeSet( common )+"\n" );
198 outerChecked.add(as1);
201 if( !foundSomeAlias ) {
202 bw.write("No aliases between flagged objects in Task "+td+".\n");
206 bw.write( "\n"+computeAliasContextHistogram() );
211 // this version of writeAllAliases is for Java programs that have no tasks
212 public void writeAllAliasesJava(String outputFile, String timeReport) throws java.io.IOException {
213 checkAnalysisComplete();
217 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile) );
219 bw.write("Conducting ownership analysis with allocation depth = "+allocationDepth+"\n");
220 bw.write(timeReport+"\n\n");
222 boolean foundSomeAlias = false;
224 Descriptor d = typeUtil.getMain();
225 HashSet<AllocationSite> allocSites = getFlaggedAllocationSites(d);
227 // for each allocation site check for aliases with
228 // other allocation sites in the context of execution
230 HashSet<AllocationSite> outerChecked = new HashSet<AllocationSite>();
231 Iterator allocItr1 = allocSites.iterator();
232 while( allocItr1.hasNext() ) {
233 AllocationSite as1 = (AllocationSite) allocItr1.next();
235 Iterator allocItr2 = allocSites.iterator();
236 while( allocItr2.hasNext() ) {
237 AllocationSite as2 = (AllocationSite) allocItr2.next();
239 if( !outerChecked.contains(as2) ) {
240 Set<HeapRegionNode> common = createsPotentialAliases(d, as1, as2);
242 if( !common.isEmpty() ) {
243 foundSomeAlias = true;
244 bw.write("Potential alias between "+as1.getDisjointId()+" and "+as2.getDisjointId()+".\n");
245 bw.write( prettyPrintNodeSet( common )+"\n" );
250 outerChecked.add(as1);
253 if( !foundSomeAlias ) {
254 bw.write("No aliases between flagged objects found.\n");
257 bw.write( "\n"+computeAliasContextHistogram() );
260 ///////////////////////////////////////////
262 // end public interface
264 ///////////////////////////////////////////
266 protected void checkAnalysisComplete() {
267 if( !analysisComplete ) {
268 throw new Error("Warning: public interface method called while analysis is running.");
276 // data from the compiler
278 public CallGraph callGraph;
279 public TypeUtil typeUtil;
280 public int allocationDepth;
282 // for public interface methods to warn that they
283 // are grabbing results during analysis
284 private boolean analysisComplete;
286 // used to identify HeapRegionNode objects
287 // A unique ID equates an object in one
288 // ownership graph with an object in another
289 // graph that logically represents the same
291 // start at 10 and increment to leave some
292 // reserved IDs for special purposes
293 static private int uniqueIDcount = 10;
295 // Use these data structures to track progress of
296 // processing all methods in the program, and by methods
297 // TaskDescriptor and MethodDescriptor are combined
298 // together, with a common parent class Descriptor
299 private Hashtable<MethodContext, OwnershipGraph> mapMethodContextToInitialParamAllocGraph;
300 public Hashtable<MethodContext, OwnershipGraph> mapMethodContextToCompleteOwnershipGraph;
301 private Hashtable<FlatNew, AllocationSite> mapFlatNewToAllocationSite;
302 private Hashtable<Descriptor, HashSet<AllocationSite> > mapDescriptorToAllocationSiteSet;
303 private Hashtable<MethodContext, Integer> mapMethodContextToNumUpdates;
304 private Hashtable<Descriptor, HashSet<MethodContext> > mapDescriptorToAllMethodContexts;
305 private Hashtable<MethodContext, HashSet<MethodContext> > mapMethodContextToDependentContexts;
306 private Hashtable<Integer, AllocationSite> mapHrnIdToAllocationSite;
308 // Use these data structures to track progress of one pass of
309 // processing the FlatNodes of a particular method
310 private HashSet <FlatNode> flatNodesToVisit;
311 private Hashtable<FlatNode, OwnershipGraph> mapFlatNodeToOwnershipGraph;
312 private HashSet <FlatReturnNode> returnNodesToCombineForCompleteOwnershipGraph;
314 // descriptorsToAnalyze identifies the set of tasks and methods
315 // that are reachable from the program tasks, this set is initialized
316 // and then remains static
317 public HashSet<Descriptor> descriptorsToAnalyze;
319 // descriptorsToVisit is initialized to descriptorsToAnalyze and is
320 // reduced by visiting a descriptor during analysis. When dependents
321 // must be scheduled, only those contained in descriptorsToAnalyze
322 // should be re-added to this queue
323 private PriorityQueue<MethodContextQWrapper> methodContextsToVisitQ;
324 private Set <MethodContext> methodContextsToVisitSet;
325 private Hashtable<Descriptor, Integer> mapDescriptorToPriority;
328 // special field descriptors for array elements
329 public static final String arrayElementFieldName = "___element_";
330 private static Hashtable<TypeDescriptor, FieldDescriptor> mapTypeToArrayField =
331 new Hashtable<TypeDescriptor, FieldDescriptor>();
334 // for controlling DOT file output
335 private boolean writeDOTs;
336 private boolean writeAllDOTs;
338 //map each FlatNode to its own internal ownership graph
339 private Hashtable<MethodContext, MethodEffects> mapMethodContextToMethodEffects;
343 // this analysis generates an ownership graph for every task
345 public OwnershipAnalysis(State state,
350 boolean writeAllDOTs,
351 String aliasFile) throws java.io.IOException {
353 analysisComplete = false;
357 this.callGraph = callGraph;
358 this.allocationDepth = allocationDepth;
359 this.writeDOTs = writeDOTs;
360 this.writeAllDOTs = writeAllDOTs;
362 descriptorsToAnalyze = new HashSet<Descriptor>();
364 mapMethodContextToInitialParamAllocGraph =
365 new Hashtable<MethodContext, OwnershipGraph>();
367 mapMethodContextToCompleteOwnershipGraph =
368 new Hashtable<MethodContext, OwnershipGraph>();
370 mapFlatNewToAllocationSite =
371 new Hashtable<FlatNew, AllocationSite>();
373 mapDescriptorToAllocationSiteSet =
374 new Hashtable<Descriptor, HashSet<AllocationSite> >();
376 mapDescriptorToAllMethodContexts =
377 new Hashtable<Descriptor, HashSet<MethodContext> >();
379 mapMethodContextToDependentContexts =
380 new Hashtable<MethodContext, HashSet<MethodContext> >();
382 mapDescriptorToPriority =
383 new Hashtable<Descriptor, Integer>();
385 mapHrnIdToAllocationSite =
386 new Hashtable<Integer, AllocationSite>();
388 mapMethodContextToMethodEffects = new Hashtable<MethodContext, MethodEffects>();
392 mapMethodContextToNumUpdates = new Hashtable<MethodContext, Integer>();
396 double timeStartAnalysis = (double) System.nanoTime();
400 // initialize methods to visit as the set of all tasks in the
401 // program and then any method that could be called starting
403 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
404 while( taskItr.hasNext() ) {
405 Descriptor d = (Descriptor) taskItr.next();
406 scheduleAllCallees(d);
410 // we are not in task mode, just normal Java, so start with
412 Descriptor d = typeUtil.getMain();
413 scheduleAllCallees(d);
417 // before beginning analysis, initialize every scheduled method
418 // with an ownership graph that has populated parameter index tables
419 // by analyzing the first node which is always a FlatMethod node
420 Iterator<Descriptor> dItr = descriptorsToAnalyze.iterator();
421 while( dItr.hasNext() ) {
422 Descriptor d = dItr.next();
423 OwnershipGraph og = new OwnershipGraph(allocationDepth, typeUtil);
426 if( d instanceof MethodDescriptor ) {
427 fm = state.getMethodFlat( (MethodDescriptor) d);
429 assert d instanceof TaskDescriptor;
430 fm = state.getMethodFlat( (TaskDescriptor) d);
433 MethodContext mc = new MethodContext( d );
434 assert !mapDescriptorToAllMethodContexts.containsKey( d );
435 HashSet<MethodContext> s = new HashSet<MethodContext>();
437 mapDescriptorToAllMethodContexts.put( d, s );
439 //System.out.println("Previsiting " + mc);
441 if(!mapMethodContextToMethodEffects.containsKey(mc)){
442 MethodEffects me=new MethodEffects();
443 mapMethodContextToMethodEffects.put(mc, me);
446 og = analyzeFlatNode(mc, fm, null, og);
447 setGraphForMethodContext(mc, og);
450 // as mentioned above, analyze methods one-by-one, possibly revisiting
451 // a method if the methods that it calls are updated
453 analysisComplete = true;
456 double timeEndAnalysis = (double) System.nanoTime();
457 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
458 String treport = String.format( "The reachability analysis took %.3f sec.", dt );
459 System.out.println( treport );
461 if( writeDOTs && !writeAllDOTs ) {
462 writeFinalContextGraphs();
465 writeMethodEffectsResult();
467 if( aliasFile != null ) {
469 writeAllAliases(aliasFile, treport);
471 writeAllAliasesJava(aliasFile, treport);
476 // called from the constructor to help initialize the set
477 // of methods that needs to be analyzed by ownership analysis
478 private void scheduleAllCallees(Descriptor d) {
479 if( descriptorsToAnalyze.contains(d) ) {
482 descriptorsToAnalyze.add(d);
484 // start with all method calls to further schedule
485 Set moreMethodsToCheck = moreMethodsToCheck = callGraph.getMethodCalls(d);
487 if( d instanceof MethodDescriptor ) {
488 // see if this method has virtual dispatch
489 Set virtualMethods = callGraph.getMethods( (MethodDescriptor)d);
490 moreMethodsToCheck.addAll(virtualMethods);
493 // keep following any further methods identified in
495 Iterator methItr = moreMethodsToCheck.iterator();
496 while( methItr.hasNext() ) {
497 Descriptor m = (Descriptor) methItr.next();
498 scheduleAllCallees(m);
503 // manage the set of tasks and methods to be analyzed
504 // and be sure to reschedule tasks/methods when the methods
505 // they call are updated
506 private void analyzeMethods() throws java.io.IOException {
508 // first gather all of the method contexts to analyze
509 HashSet<MethodContext> allContexts = new HashSet<MethodContext>();
510 Iterator<Descriptor> itrd2a = descriptorsToAnalyze.iterator();
511 while( itrd2a.hasNext() ) {
512 HashSet<MethodContext> mcs = mapDescriptorToAllMethodContexts.get( itrd2a.next() );
515 Iterator<MethodContext> itrmc = mcs.iterator();
516 while( itrmc.hasNext() ) {
517 allContexts.add( itrmc.next() );
521 // topologically sort them according to the caller graph so leaf calls are
522 // ordered first; use that ordering to give method contexts priorities
523 LinkedList<MethodContext> sortedMethodContexts = topologicalSort( allContexts );
525 methodContextsToVisitQ = new PriorityQueue<MethodContextQWrapper>();
526 methodContextsToVisitSet = new HashSet<MethodContext>();
529 Iterator<MethodContext> mcItr = sortedMethodContexts.iterator();
530 while( mcItr.hasNext() ) {
531 MethodContext mc = mcItr.next();
532 mapDescriptorToPriority.put( mc.getDescriptor(), new Integer( p ) );
533 methodContextsToVisitQ.add( new MethodContextQWrapper( p, mc ) );
534 methodContextsToVisitSet.add( mc );
538 // analyze methods from the priority queue until it is empty
539 while( !methodContextsToVisitQ.isEmpty() ) {
540 MethodContext mc = methodContextsToVisitQ.poll().getMethodContext();
541 assert methodContextsToVisitSet.contains( mc );
542 methodContextsToVisitSet.remove( mc );
544 // because the task or method descriptor just extracted
545 // was in the "to visit" set it either hasn't been analyzed
546 // yet, or some method that it depends on has been
547 // updated. Recompute a complete ownership graph for
548 // this task/method and compare it to any previous result.
549 // If there is a change detected, add any methods/tasks
550 // that depend on this one to the "to visit" set.
552 System.out.println("Analyzing " + mc);
554 Descriptor d = mc.getDescriptor();
556 if( d instanceof MethodDescriptor ) {
557 fm = state.getMethodFlat( (MethodDescriptor) d);
559 assert d instanceof TaskDescriptor;
560 fm = state.getMethodFlat( (TaskDescriptor) d);
563 OwnershipGraph og = analyzeFlatMethod(mc, fm);
564 OwnershipGraph ogPrev = mapMethodContextToCompleteOwnershipGraph.get(mc);
565 if( !og.equals(ogPrev) ) {
566 setGraphForMethodContext(mc, og);
568 Iterator<MethodContext> depsItr = iteratorDependents( mc );
569 while( depsItr.hasNext() ) {
570 MethodContext mcNext = depsItr.next();
572 if( !methodContextsToVisitSet.contains( mcNext ) ) {
573 methodContextsToVisitQ.add( new MethodContextQWrapper( mapDescriptorToPriority.get( mcNext.getDescriptor() ),
575 methodContextsToVisitSet.add( mcNext );
584 // keep passing the Descriptor of the method along for debugging
585 // and dot file writing
586 private OwnershipGraph
587 analyzeFlatMethod(MethodContext mc,
588 FlatMethod flatm) throws java.io.IOException {
590 // initialize flat nodes to visit as the flat method
591 // because it is the entry point
593 flatNodesToVisit = new HashSet<FlatNode>();
594 flatNodesToVisit.add(flatm);
596 // initilize the mapping of flat nodes in this flat method to
597 // ownership graph results to an empty mapping
598 mapFlatNodeToOwnershipGraph = new Hashtable<FlatNode, OwnershipGraph>();
600 // initialize the set of return nodes that will be combined as
601 // the final ownership graph result to return as an empty set
602 returnNodesToCombineForCompleteOwnershipGraph = new HashSet<FlatReturnNode>();
605 while( !flatNodesToVisit.isEmpty() ) {
606 FlatNode fn = (FlatNode) flatNodesToVisit.iterator().next();
607 flatNodesToVisit.remove(fn);
609 //System.out.println( " "+fn );
611 // perform this node's contributions to the ownership
612 // graph on a new copy, then compare it to the old graph
613 // at this node to see if anything was updated.
614 OwnershipGraph og = new OwnershipGraph(allocationDepth, typeUtil);
616 // start by merging all node's parents' graphs
617 for( int i = 0; i < fn.numPrev(); ++i ) {
618 FlatNode pn = fn.getPrev(i);
619 if( mapFlatNodeToOwnershipGraph.containsKey(pn) ) {
620 OwnershipGraph ogParent = mapFlatNodeToOwnershipGraph.get(pn);
625 // apply the analysis of the flat node to the
626 // ownership graph made from the merge of the
628 og = analyzeFlatNode(mc,
630 returnNodesToCombineForCompleteOwnershipGraph,
636 if( takeDebugSnapshots &&
637 mc.getDescriptor().getSymbol().equals( mcDescSymbolDebug ) ) {
638 debugSnapshot(og,fn);
643 // if the results of the new graph are different from
644 // the current graph at this node, replace the graph
645 // with the update and enqueue the children for
647 OwnershipGraph ogPrev = mapFlatNodeToOwnershipGraph.get(fn);
648 if( !og.equals(ogPrev) ) {
649 mapFlatNodeToOwnershipGraph.put(fn, og);
651 for( int i = 0; i < fn.numNext(); i++ ) {
652 FlatNode nn = fn.getNext(i);
653 flatNodesToVisit.add(nn);
658 // end by merging all return nodes into a complete
659 // ownership graph that represents all possible heap
660 // states after the flat method returns
661 OwnershipGraph completeGraph = new OwnershipGraph(allocationDepth, typeUtil);
662 Iterator retItr = returnNodesToCombineForCompleteOwnershipGraph.iterator();
663 while( retItr.hasNext() ) {
664 FlatReturnNode frn = (FlatReturnNode) retItr.next();
665 assert mapFlatNodeToOwnershipGraph.containsKey(frn);
666 OwnershipGraph ogr = mapFlatNodeToOwnershipGraph.get(frn);
667 completeGraph.merge(ogr);
670 return completeGraph;
674 private OwnershipGraph
675 analyzeFlatNode(MethodContext mc,
677 HashSet<FlatReturnNode> setRetNodes,
678 OwnershipGraph og) throws java.io.IOException {
680 MethodEffects me=mapMethodContextToMethodEffects.get(mc);
686 // use node type to decide what alterations to make
687 // to the ownership graph
688 switch( fn.kind() ) {
690 case FKind.FlatMethod:
691 FlatMethod fm = (FlatMethod) fn;
693 // there should only be one FlatMethod node as the
694 // parent of all other FlatNode objects, so take
695 // the opportunity to construct the initial graph by
696 // adding parameters labels to new heap regions
697 // AND this should be done once globally so that the
698 // parameter IDs are consistent between analysis
699 // iterations, so if this step has been done already
700 // just merge in the cached version
701 OwnershipGraph ogInitParamAlloc = mapMethodContextToInitialParamAllocGraph.get(mc);
702 if( ogInitParamAlloc == null ) {
704 // if the method context has aliased parameters, make sure
705 // there is a blob region for all those param to reference
706 Set<Integer> aliasedParamIndices = mc.getAliasedParamIndices();
708 if( !aliasedParamIndices.isEmpty() ) {
709 og.makeAliasedParamHeapRegionNode();
712 // set up each parameter
713 for( int i = 0; i < fm.numParameters(); ++i ) {
714 TempDescriptor tdParam = fm.getParameter( i );
715 TypeDescriptor typeParam = tdParam.getType();
716 Integer paramIndex = new Integer( i );
718 if( typeParam.isImmutable() && !typeParam.isArray() ) {
719 // don't bother with this primitive parameter, it
720 // cannot affect reachability
724 if( aliasedParamIndices.contains( paramIndex ) ) {
725 // use the alias blob but give parameters their
726 // own primary obj region
727 og.assignTempEqualToAliasedParam( tdParam,
730 // this parameter is not aliased to others, give it
731 // a fresh primary obj and secondary object
732 og.assignTempEqualToParamAlloc( tdParam,
733 mc.getDescriptor() instanceof TaskDescriptor,
738 // add additional edges for aliased regions if necessary
739 if( !aliasedParamIndices.isEmpty() ) {
740 og.addParam2ParamAliasEdges( fm, aliasedParamIndices );
743 // clean up reachability on initial parameter shapes
746 // this maps tokens to parameter indices and vice versa
747 // for when this method is a callee
748 og.prepareParamTokenMaps( fm );
751 OwnershipGraph ogResult = new OwnershipGraph(allocationDepth, typeUtil);
753 mapMethodContextToInitialParamAllocGraph.put(mc, ogResult);
756 // or just leverage the cached copy
757 og.merge(ogInitParamAlloc);
761 case FKind.FlatOpNode:
762 FlatOpNode fon = (FlatOpNode) fn;
763 if( fon.getOp().getOp() == Operation.ASSIGN ) {
766 og.assignTempXEqualToTempY(lhs, rhs);
770 case FKind.FlatCastNode:
771 FlatCastNode fcn = (FlatCastNode) fn;
775 TypeDescriptor td = fcn.getType();
778 og.assignTypedTempXEqualToTempY(lhs, rhs, td);
781 case FKind.FlatFieldNode:
782 FlatFieldNode ffn = (FlatFieldNode) fn;
785 fld = ffn.getField();
786 if( !fld.getType().isImmutable() || fld.getType().isArray() ) {
787 og.assignTempXEqualToTempYFieldF(lhs, rhs, fld);
790 me.analyzeFlatFieldNode(og, rhs, fld);
794 case FKind.FlatSetFieldNode:
795 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
797 fld = fsfn.getField();
799 if( !fld.getType().isImmutable() || fld.getType().isArray() ) {
800 og.assignTempXFieldFEqualToTempY(lhs, fld, rhs);
803 me.analyzeFlatSetFieldNode(og, lhs, fld);
807 case FKind.FlatElementNode:
808 FlatElementNode fen = (FlatElementNode) fn;
811 if( !lhs.getType().isImmutable() || lhs.getType().isArray() ) {
813 assert rhs.getType() != null;
814 assert rhs.getType().isArray();
816 TypeDescriptor tdElement = rhs.getType().dereference();
817 FieldDescriptor fdElement = getArrayField( tdElement );
819 og.assignTempXEqualToTempYFieldF(lhs, rhs, fdElement);
823 case FKind.FlatSetElementNode:
824 FlatSetElementNode fsen = (FlatSetElementNode) fn;
827 if( !rhs.getType().isImmutable() || rhs.getType().isArray() ) {
829 assert lhs.getType() != null;
830 assert lhs.getType().isArray();
832 TypeDescriptor tdElement = lhs.getType().dereference();
833 FieldDescriptor fdElement = getArrayField( tdElement );
835 og.assignTempXFieldFEqualToTempY(lhs, fdElement, rhs);
840 FlatNew fnn = (FlatNew) fn;
842 if( !lhs.getType().isImmutable() || lhs.getType().isArray() ) {
843 AllocationSite as = getAllocationSiteFromFlatNewPRIVATE(fnn);
844 og.assignTempEqualToNewAlloc(lhs, as);
849 FlatCall fc = (FlatCall) fn;
850 MethodDescriptor md = fc.getMethod();
851 FlatMethod flatm = state.getMethodFlat(md);
852 OwnershipGraph ogMergeOfAllPossibleCalleeResults = new OwnershipGraph(allocationDepth, typeUtil);
854 if( md.isStatic() ) {
855 // a static method is simply always the same, makes life easy
856 ogMergeOfAllPossibleCalleeResults = og;
858 Set<Integer> aliasedParamIndices =
859 ogMergeOfAllPossibleCalleeResults.calculateAliasedParamSet(fc, md.isStatic(), flatm);
861 MethodContext mcNew = new MethodContext( md, aliasedParamIndices );
862 Set contexts = mapDescriptorToAllMethodContexts.get( md );
863 assert contexts != null;
864 contexts.add( mcNew );
866 addDependent( mc, mcNew );
868 OwnershipGraph onlyPossibleCallee = mapMethodContextToCompleteOwnershipGraph.get( mcNew );
870 if( onlyPossibleCallee == null ) {
871 // if this method context has never been analyzed just schedule it for analysis
872 // and skip over this call site for now
873 if( !methodContextsToVisitSet.contains( mcNew ) ) {
874 methodContextsToVisitQ.add( new MethodContextQWrapper( mapDescriptorToPriority.get( md ),
876 methodContextsToVisitSet.add( mcNew );
880 ogMergeOfAllPossibleCalleeResults.resolveMethodCall(fc, md.isStatic(), flatm, onlyPossibleCallee, mc, null);
883 if(!mapMethodContextToMethodEffects.containsKey(mcNew)){
884 MethodEffects meNew=new MethodEffects();
885 mapMethodContextToMethodEffects.put(mcNew, meNew);
888 MethodEffects meFlatCall=mapMethodContextToMethodEffects.get(mcNew);
889 me.analyzeFlatCall(ogMergeOfAllPossibleCalleeResults,fc,mc,meFlatCall);
893 // if the method descriptor is virtual, then there could be a
894 // set of possible methods that will actually be invoked, so
895 // find all of them and merge all of their results together
896 TypeDescriptor typeDesc = fc.getThis().getType();
897 Set possibleCallees = callGraph.getMethods(md, typeDesc);
899 Iterator i = possibleCallees.iterator();
900 while( i.hasNext() ) {
901 MethodDescriptor possibleMd = (MethodDescriptor) i.next();
902 FlatMethod pflatm = state.getMethodFlat(possibleMd);
904 // don't alter the working graph (og) until we compute a result for every
905 // possible callee, merge them all together, then set og to that
906 OwnershipGraph ogCopy = new OwnershipGraph(allocationDepth, typeUtil);
909 Set<Integer> aliasedParamIndices =
910 ogCopy.calculateAliasedParamSet(fc, possibleMd.isStatic(), pflatm);
912 MethodContext mcNew = new MethodContext( possibleMd, aliasedParamIndices );
913 Set contexts = mapDescriptorToAllMethodContexts.get( md );
914 assert contexts != null;
915 contexts.add( mcNew );
918 if(!mapMethodContextToMethodEffects.containsKey(mcNew)){
919 MethodEffects meNew=new MethodEffects();
920 mapMethodContextToMethodEffects.put(mcNew, meNew);
924 addDependent( mc, mcNew );
926 OwnershipGraph ogPotentialCallee = mapMethodContextToCompleteOwnershipGraph.get( mcNew );
928 if( ogPotentialCallee == null ) {
929 // if this method context has never been analyzed just schedule it for analysis
930 // and skip over this call site for now
931 if( !methodContextsToVisitSet.contains( mcNew ) ) {
932 methodContextsToVisitQ.add( new MethodContextQWrapper( mapDescriptorToPriority.get( md ),
934 methodContextsToVisitSet.add( mcNew );
938 ogCopy.resolveMethodCall(fc, possibleMd.isStatic(), pflatm, ogPotentialCallee, mc, null);
941 MethodEffects meFlatCall=mapMethodContextToMethodEffects.get(mcNew);
942 meFlatCall.analyzeFlatCall(ogMergeOfAllPossibleCalleeResults,fc,mcNew,meFlatCall);
944 ogMergeOfAllPossibleCalleeResults.merge(ogCopy);
948 og = ogMergeOfAllPossibleCalleeResults;
951 case FKind.FlatReturnNode:
952 FlatReturnNode frn = (FlatReturnNode) fn;
953 rhs = frn.getReturnTemp();
954 if( rhs != null && !rhs.getType().isImmutable() ) {
955 og.assignReturnEqualToTemp(rhs);
957 setRetNodes.add(frn);
961 setMethodEffectsForMethodContext(mc, me);
967 // this method should generate integers strictly greater than zero!
968 // special "shadow" regions are made from a heap region by negating
970 static public Integer generateUniqueHeapRegionNodeID() {
972 return new Integer(uniqueIDcount);
976 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
977 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
978 if( fdElement == null ) {
979 fdElement = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC),
981 arrayElementFieldName,
984 mapTypeToArrayField.put( tdElement, fdElement );
990 private void setMethodEffectsForMethodContext(MethodContext mc, MethodEffects me){
991 mapMethodContextToMethodEffects.put(mc,me);
994 private void setGraphForMethodContext(MethodContext mc, OwnershipGraph og) {
996 mapMethodContextToCompleteOwnershipGraph.put(mc, og);
998 if( writeDOTs && writeAllDOTs ) {
999 if( !mapMethodContextToNumUpdates.containsKey(mc) ) {
1000 mapMethodContextToNumUpdates.put(mc, new Integer(0) );
1002 Integer n = mapMethodContextToNumUpdates.get(mc);
1004 og.writeGraph(mc, n, true, true, true, false, false);
1005 } catch( IOException e ) {}
1006 mapMethodContextToNumUpdates.put(mc, n + 1);
1011 private void addDependent( MethodContext caller, MethodContext callee ) {
1012 HashSet<MethodContext> deps = mapMethodContextToDependentContexts.get( callee );
1013 if( deps == null ) {
1014 deps = new HashSet<MethodContext>();
1017 mapMethodContextToDependentContexts.put( callee, deps );
1020 private Iterator<MethodContext> iteratorDependents( MethodContext callee ) {
1021 HashSet<MethodContext> deps = mapMethodContextToDependentContexts.get( callee );
1022 if( deps == null ) {
1023 deps = new HashSet<MethodContext>();
1024 mapMethodContextToDependentContexts.put( callee, deps );
1026 return deps.iterator();
1030 private void writeFinalContextGraphs() {
1031 // arguments to writeGraph are:
1032 // boolean writeLabels,
1033 // boolean labelSelect,
1034 // boolean pruneGarbage,
1035 // boolean writeReferencers
1036 // boolean writeParamMappings
1038 Set entrySet = mapMethodContextToCompleteOwnershipGraph.entrySet();
1039 Iterator itr = entrySet.iterator();
1040 while( itr.hasNext() ) {
1041 Map.Entry me = (Map.Entry) itr.next();
1042 MethodContext mc = (MethodContext) me.getKey();
1043 OwnershipGraph og = (OwnershipGraph) me.getValue();
1046 og.writeGraph(mc, true, true, true, false, false);
1047 } catch( IOException e ) {}
1051 public void writeMethodEffectsResult() throws IOException {
1054 BufferedWriter bw = new BufferedWriter(new FileWriter(
1055 "MethodEffects_resport.txt"));
1057 Set<MethodContext> mcSet = mapMethodContextToMethodEffects.keySet();
1058 Iterator<MethodContext> mcIter = mcSet.iterator();
1059 while (mcIter.hasNext()) {
1060 MethodContext mc = mcIter.next();
1061 MethodDescriptor md = (MethodDescriptor) mc.getDescriptor();
1063 MethodEffects me = mapMethodContextToMethodEffects.get(mc);
1064 EffectsSet effectsSet = me.getEffects();
1066 bw.write("Method " + mc +"::"+mc.hashCode() + " :\n");
1067 for (int i = 0; i < md.numParameters(); i++) {
1069 String paramName = md.getParamName(i);
1071 Set<EffectsKey> effectSet = effectsSet
1073 String keyStr = "{";
1074 if (effectSet != null) {
1075 Iterator<EffectsKey> effectIter = effectSet.iterator();
1076 while (effectIter.hasNext()) {
1077 EffectsKey key = effectIter.next();
1078 keyStr += " " + key;
1082 bw.write(" Paramter " + paramName + " ReadingSet="
1085 effectSet = effectsSet.getWritingSet(new Integer(i));
1087 if (effectSet != null) {
1088 Iterator<EffectsKey> effectIter = effectSet.iterator();
1089 while (effectIter.hasNext()) {
1090 EffectsKey key = effectIter.next();
1091 keyStr += " " + key;
1096 bw.write(" Paramter " + paramName + " WritingngSet="
1105 } catch (IOException e) {
1106 System.err.println(e);
1109 // Set entrySet = mapMethodContextToMethodEffects.entrySet();
1110 // Iterator itr = entrySet.iterator();
1111 // while( itr.hasNext() ) {
1112 // Map.Entry me = (Map.Entry) itr.next();
1113 // MethodContext mc = (MethodContext) me.getKey();
1114 // MethodEffects og = (MethodEffects) me.getValue();
1117 // og.writeGraph(mc, true, true, true, false, false);
1118 // } catch( IOException e ) {}
1124 // return just the allocation site associated with one FlatNew node
1125 private AllocationSite getAllocationSiteFromFlatNewPRIVATE(FlatNew fn) {
1127 if( !mapFlatNewToAllocationSite.containsKey(fn) ) {
1128 AllocationSite as = new AllocationSite(allocationDepth, fn, fn.getDisjointId());
1130 // the newest nodes are single objects
1131 for( int i = 0; i < allocationDepth; ++i ) {
1132 Integer id = generateUniqueHeapRegionNodeID();
1133 as.setIthOldest(i, id);
1134 mapHrnIdToAllocationSite.put( id, as );
1137 // the oldest node is a summary node
1138 Integer idSummary = generateUniqueHeapRegionNodeID();
1139 as.setSummary(idSummary);
1141 mapFlatNewToAllocationSite.put(fn, as);
1144 return mapFlatNewToAllocationSite.get(fn);
1148 // return all allocation sites in the method (there is one allocation
1149 // site per FlatNew node in a method)
1150 private HashSet<AllocationSite> getAllocationSiteSet(Descriptor d) {
1151 if( !mapDescriptorToAllocationSiteSet.containsKey(d) ) {
1152 buildAllocationSiteSet(d);
1155 return mapDescriptorToAllocationSiteSet.get(d);
1159 private void buildAllocationSiteSet(Descriptor d) {
1160 HashSet<AllocationSite> s = new HashSet<AllocationSite>();
1163 if( d instanceof MethodDescriptor ) {
1164 fm = state.getMethodFlat( (MethodDescriptor) d);
1166 assert d instanceof TaskDescriptor;
1167 fm = state.getMethodFlat( (TaskDescriptor) d);
1170 // visit every node in this FlatMethod's IR graph
1171 // and make a set of the allocation sites from the
1172 // FlatNew node's visited
1173 HashSet<FlatNode> visited = new HashSet<FlatNode>();
1174 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
1177 while( !toVisit.isEmpty() ) {
1178 FlatNode n = toVisit.iterator().next();
1180 if( n instanceof FlatNew ) {
1181 s.add(getAllocationSiteFromFlatNewPRIVATE( (FlatNew) n) );
1187 for( int i = 0; i < n.numNext(); ++i ) {
1188 FlatNode child = n.getNext(i);
1189 if( !visited.contains(child) ) {
1195 mapDescriptorToAllocationSiteSet.put(d, s);
1199 private HashSet<AllocationSite> getFlaggedAllocationSites(Descriptor dIn) {
1201 HashSet<AllocationSite> out = new HashSet<AllocationSite>();
1202 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1203 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1207 while( !toVisit.isEmpty() ) {
1208 Descriptor d = toVisit.iterator().next();
1212 HashSet<AllocationSite> asSet = getAllocationSiteSet(d);
1213 Iterator asItr = asSet.iterator();
1214 while( asItr.hasNext() ) {
1215 AllocationSite as = (AllocationSite) asItr.next();
1216 if( as.getDisjointId() != null ) {
1221 // enqueue callees of this method to be searched for
1222 // allocation sites also
1223 Set callees = callGraph.getCalleeSet(d);
1224 if( callees != null ) {
1225 Iterator methItr = callees.iterator();
1226 while( methItr.hasNext() ) {
1227 MethodDescriptor md = (MethodDescriptor) methItr.next();
1229 if( !visited.contains(md) ) {
1240 private HashSet<AllocationSite>
1241 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
1243 HashSet<AllocationSite> asSetTotal = new HashSet<AllocationSite>();
1244 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1245 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1249 // traverse this task and all methods reachable from this task
1250 while( !toVisit.isEmpty() ) {
1251 Descriptor d = toVisit.iterator().next();
1255 HashSet<AllocationSite> asSet = getAllocationSiteSet(d);
1256 Iterator asItr = asSet.iterator();
1257 while( asItr.hasNext() ) {
1258 AllocationSite as = (AllocationSite) asItr.next();
1259 TypeDescriptor typed = as.getType();
1260 if( typed != null ) {
1261 ClassDescriptor cd = typed.getClassDesc();
1262 if( cd != null && cd.hasFlags() ) {
1268 // enqueue callees of this method to be searched for
1269 // allocation sites also
1270 Set callees = callGraph.getCalleeSet(d);
1271 if( callees != null ) {
1272 Iterator methItr = callees.iterator();
1273 while( methItr.hasNext() ) {
1274 MethodDescriptor md = (MethodDescriptor) methItr.next();
1276 if( !visited.contains(md) ) {
1288 private LinkedList<MethodContext> topologicalSort( HashSet<MethodContext> set ) {
1289 HashSet <MethodContext> discovered = new HashSet <MethodContext>();
1290 LinkedList<MethodContext> sorted = new LinkedList<MethodContext>();
1292 Iterator<MethodContext> itr = set.iterator();
1293 while( itr.hasNext() ) {
1294 MethodContext mc = itr.next();
1296 if( !discovered.contains( mc ) ) {
1297 dfsVisit( set, mc, sorted, discovered );
1304 private void dfsVisit( HashSet<MethodContext> set,
1306 LinkedList<MethodContext> sorted,
1307 HashSet <MethodContext> discovered ) {
1308 discovered.add( mc );
1310 Descriptor d = mc.getDescriptor();
1311 if( d instanceof MethodDescriptor ) {
1312 MethodDescriptor md = (MethodDescriptor) d;
1313 Iterator itr = callGraph.getCallerSet( md ).iterator();
1314 while( itr.hasNext() ) {
1315 Descriptor dCaller = (Descriptor) itr.next();
1317 // only consider the callers in the original set to analyze
1318 Set<MethodContext> callerContexts = mapDescriptorToAllMethodContexts.get( dCaller );
1319 if( callerContexts == null )
1322 // since the analysis hasn't started, there should be exactly one
1323 // context if there are any at all
1324 assert callerContexts.size() == 1;
1325 MethodContext mcCaller = callerContexts.iterator().next();
1326 assert set.contains( mcCaller );
1328 if( !discovered.contains( mcCaller ) ) {
1329 dfsVisit( set, mcCaller, sorted, discovered );
1334 sorted.addFirst( mc );
1339 private String computeAliasContextHistogram() {
1341 Hashtable<Integer, Integer> mapNumContexts2NumDesc =
1342 new Hashtable<Integer, Integer>();
1344 Iterator itr = mapDescriptorToAllMethodContexts.entrySet().iterator();
1345 while( itr.hasNext() ) {
1346 Map.Entry me = (Map.Entry) itr.next();
1347 HashSet<MethodContext> s = (HashSet<MethodContext>) me.getValue();
1349 Integer i = mapNumContexts2NumDesc.get( s.size() );
1351 i = new Integer( 0 );
1353 mapNumContexts2NumDesc.put( s.size(), i + 1 );
1359 itr = mapNumContexts2NumDesc.entrySet().iterator();
1360 while( itr.hasNext() ) {
1361 Map.Entry me = (Map.Entry) itr.next();
1362 Integer c0 = (Integer) me.getKey();
1363 Integer d0 = (Integer) me.getValue();
1365 s += String.format( "%4d methods had %4d unique alias contexts.\n", d0, c0 );
1368 s += String.format( "\n%4d total methods analayzed.\n", total );
1376 // insert a call to debugSnapshot() somewhere in the analysis
1377 // to get successive captures of the analysis state
1378 boolean takeDebugSnapshots = false;
1379 String mcDescSymbolDebug = "addFirst";
1380 boolean stopAfterCapture = true;
1382 // increments every visit to debugSnapshot, don't fiddle with it
1383 int debugCounter = 0;
1385 // the value of debugCounter to start reporting the debugCounter
1386 // to the screen to let user know what debug iteration we're at
1387 int numStartCountReport = 0;
1389 // the frequency of debugCounter values to print out, 0 no report
1390 int freqCountReport = 0;
1392 // the debugCounter value at which to start taking snapshots
1393 int iterStartCapture = 0;
1395 // the number of snapshots to take
1396 int numIterToCapture = 40;
1398 void debugSnapshot(OwnershipGraph og, FlatNode fn) {
1399 if( debugCounter > iterStartCapture + numIterToCapture ) {
1404 if( debugCounter > numStartCountReport &&
1405 freqCountReport > 0 &&
1406 debugCounter % freqCountReport == 0 ) {
1407 System.out.println(" @@@ debug counter = "+debugCounter);
1409 if( debugCounter > iterStartCapture ) {
1410 System.out.println(" @@@ capturing debug "+(debugCounter-iterStartCapture)+" @@@");
1411 String graphName = String.format("snap%04d",debugCounter-iterStartCapture);
1413 graphName = graphName+fn;
1416 // arguments to writeGraph are:
1417 // boolean writeLabels,
1418 // boolean labelSelect,
1419 // boolean pruneGarbage,
1420 // boolean writeReferencers
1421 // boolean writeParamMappings
1423 //og.writeGraph(graphName, true, true, true, false, false);
1424 og.writeGraph(graphName, true, true, true, false, false);
1425 } catch( Exception e ) {
1426 System.out.println("Error writing debug capture.");
1431 if( debugCounter == iterStartCapture + numIterToCapture && stopAfterCapture ) {
1432 System.out.println("Stopping analysis after debug captures.");