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<FlatNode, OwnershipGraph> mappingFlatNodeToOwnershipGraph;
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 mappingFlatNodeToOwnershipGraph = new Hashtable<FlatNode, OwnershipGraph>();
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 og = analyzeFlatNode(mc, fm, null, og);
442 setGraphForMethodContext(mc, og);
445 // as mentioned above, analyze methods one-by-one, possibly revisiting
446 // a method if the methods that it calls are updated
448 analysisComplete = true;
451 double timeEndAnalysis = (double) System.nanoTime();
452 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
453 String treport = String.format( "The reachability analysis took %.3f sec.", dt );
454 System.out.println( treport );
456 if( writeDOTs && !writeAllDOTs ) {
457 writeFinalContextGraphs();
460 if( aliasFile != null ) {
462 writeAllAliases(aliasFile, treport);
464 writeAllAliasesJava(aliasFile, treport);
469 // called from the constructor to help initialize the set
470 // of methods that needs to be analyzed by ownership analysis
471 private void scheduleAllCallees(Descriptor d) {
472 if( descriptorsToAnalyze.contains(d) ) {
475 descriptorsToAnalyze.add(d);
477 // start with all method calls to further schedule
478 Set moreMethodsToCheck = moreMethodsToCheck = callGraph.getMethodCalls(d);
480 if( d instanceof MethodDescriptor ) {
481 // see if this method has virtual dispatch
482 Set virtualMethods = callGraph.getMethods( (MethodDescriptor)d);
483 moreMethodsToCheck.addAll(virtualMethods);
486 // keep following any further methods identified in
488 Iterator methItr = moreMethodsToCheck.iterator();
489 while( methItr.hasNext() ) {
490 Descriptor m = (Descriptor) methItr.next();
491 scheduleAllCallees(m);
496 // manage the set of tasks and methods to be analyzed
497 // and be sure to reschedule tasks/methods when the methods
498 // they call are updated
499 private void analyzeMethods() throws java.io.IOException {
501 // first gather all of the method contexts to analyze
502 HashSet<MethodContext> allContexts = new HashSet<MethodContext>();
503 Iterator<Descriptor> itrd2a = descriptorsToAnalyze.iterator();
504 while( itrd2a.hasNext() ) {
505 HashSet<MethodContext> mcs = mapDescriptorToAllMethodContexts.get( itrd2a.next() );
508 Iterator<MethodContext> itrmc = mcs.iterator();
509 while( itrmc.hasNext() ) {
510 allContexts.add( itrmc.next() );
514 // topologically sort them according to the caller graph so leaf calls are
515 // ordered first; use that ordering to give method contexts priorities
516 LinkedList<MethodContext> sortedMethodContexts = topologicalSort( allContexts );
518 methodContextsToVisitQ = new PriorityQueue<MethodContextQWrapper>();
519 methodContextsToVisitSet = new HashSet<MethodContext>();
522 Iterator<MethodContext> mcItr = sortedMethodContexts.iterator();
523 while( mcItr.hasNext() ) {
524 MethodContext mc = mcItr.next();
525 mapDescriptorToPriority.put( mc.getDescriptor(), new Integer( p ) );
526 methodContextsToVisitQ.add( new MethodContextQWrapper( p, mc ) );
527 methodContextsToVisitSet.add( mc );
531 // analyze methods from the priority queue until it is empty
532 while( !methodContextsToVisitQ.isEmpty() ) {
533 MethodContext mc = methodContextsToVisitQ.poll().getMethodContext();
534 assert methodContextsToVisitSet.contains( mc );
535 methodContextsToVisitSet.remove( mc );
537 // because the task or method descriptor just extracted
538 // was in the "to visit" set it either hasn't been analyzed
539 // yet, or some method that it depends on has been
540 // updated. Recompute a complete ownership graph for
541 // this task/method and compare it to any previous result.
542 // If there is a change detected, add any methods/tasks
543 // that depend on this one to the "to visit" set.
545 System.out.println("Analyzing " + mc);
547 Descriptor d = mc.getDescriptor();
549 if( d instanceof MethodDescriptor ) {
550 fm = state.getMethodFlat( (MethodDescriptor) d);
552 assert d instanceof TaskDescriptor;
553 fm = state.getMethodFlat( (TaskDescriptor) d);
556 OwnershipGraph og = analyzeFlatMethod(mc, fm);
557 OwnershipGraph ogPrev = mapMethodContextToCompleteOwnershipGraph.get(mc);
558 if( !og.equals(ogPrev) ) {
559 setGraphForMethodContext(mc, og);
561 Iterator<MethodContext> depsItr = iteratorDependents( mc );
562 while( depsItr.hasNext() ) {
563 MethodContext mcNext = depsItr.next();
565 if( !methodContextsToVisitSet.contains( mcNext ) ) {
566 methodContextsToVisitQ.add( new MethodContextQWrapper( mapDescriptorToPriority.get( mcNext.getDescriptor() ),
568 methodContextsToVisitSet.add( mcNext );
577 // keep passing the Descriptor of the method along for debugging
578 // and dot file writing
579 private OwnershipGraph
580 analyzeFlatMethod(MethodContext mc,
581 FlatMethod flatm) throws java.io.IOException {
583 // initialize flat nodes to visit as the flat method
584 // because it is the entry point
586 flatNodesToVisit = new HashSet<FlatNode>();
587 flatNodesToVisit.add(flatm);
589 // initilize the mapping of flat nodes in this flat method to
590 // ownership graph results to an empty mapping
591 mapFlatNodeToOwnershipGraph = new Hashtable<FlatNode, OwnershipGraph>();
593 // initialize the set of return nodes that will be combined as
594 // the final ownership graph result to return as an empty set
595 returnNodesToCombineForCompleteOwnershipGraph = new HashSet<FlatReturnNode>();
598 while( !flatNodesToVisit.isEmpty() ) {
599 FlatNode fn = (FlatNode) flatNodesToVisit.iterator().next();
600 flatNodesToVisit.remove(fn);
602 //System.out.println( " "+fn );
604 // perform this node's contributions to the ownership
605 // graph on a new copy, then compare it to the old graph
606 // at this node to see if anything was updated.
607 OwnershipGraph og = new OwnershipGraph(allocationDepth, typeUtil);
609 // start by merging all node's parents' graphs
610 for( int i = 0; i < fn.numPrev(); ++i ) {
611 FlatNode pn = fn.getPrev(i);
612 if( mapFlatNodeToOwnershipGraph.containsKey(pn) ) {
613 OwnershipGraph ogParent = mapFlatNodeToOwnershipGraph.get(pn);
618 // apply the analysis of the flat node to the
619 // ownership graph made from the merge of the
621 og = analyzeFlatNode(mc,
623 returnNodesToCombineForCompleteOwnershipGraph,
629 if( takeDebugSnapshots &&
630 mc.getDescriptor().getSymbol().equals( mcDescSymbolDebug ) ) {
631 debugSnapshot(og,fn);
636 // if the results of the new graph are different from
637 // the current graph at this node, replace the graph
638 // with the update and enqueue the children for
640 OwnershipGraph ogPrev = mapFlatNodeToOwnershipGraph.get(fn);
641 if( !og.equals(ogPrev) ) {
642 mapFlatNodeToOwnershipGraph.put(fn, og);
644 for( int i = 0; i < fn.numNext(); i++ ) {
645 FlatNode nn = fn.getNext(i);
646 flatNodesToVisit.add(nn);
651 // end by merging all return nodes into a complete
652 // ownership graph that represents all possible heap
653 // states after the flat method returns
654 OwnershipGraph completeGraph = new OwnershipGraph(allocationDepth, typeUtil);
655 Iterator retItr = returnNodesToCombineForCompleteOwnershipGraph.iterator();
656 while( retItr.hasNext() ) {
657 FlatReturnNode frn = (FlatReturnNode) retItr.next();
658 assert mapFlatNodeToOwnershipGraph.containsKey(frn);
659 OwnershipGraph ogr = mapFlatNodeToOwnershipGraph.get(frn);
660 completeGraph.merge(ogr);
663 return completeGraph;
667 private OwnershipGraph
668 analyzeFlatNode(MethodContext mc,
670 HashSet<FlatReturnNode> setRetNodes,
671 OwnershipGraph og) throws java.io.IOException {
677 // use node type to decide what alterations to make
678 // to the ownership graph
679 switch( fn.kind() ) {
681 case FKind.FlatMethod:
682 FlatMethod fm = (FlatMethod) fn;
684 // there should only be one FlatMethod node as the
685 // parent of all other FlatNode objects, so take
686 // the opportunity to construct the initial graph by
687 // adding parameters labels to new heap regions
688 // AND this should be done once globally so that the
689 // parameter IDs are consistent between analysis
690 // iterations, so if this step has been done already
691 // just merge in the cached version
692 OwnershipGraph ogInitParamAlloc = mapMethodContextToInitialParamAllocGraph.get(mc);
693 if( ogInitParamAlloc == null ) {
695 // if the method context has aliased parameters, make sure
696 // there is a blob region for all those param to reference
697 Set<Integer> aliasedParamIndices = mc.getAliasedParamIndices();
699 if( !aliasedParamIndices.isEmpty() ) {
700 og.makeAliasedParamHeapRegionNode();
703 // set up each parameter
704 for( int i = 0; i < fm.numParameters(); ++i ) {
705 TempDescriptor tdParam = fm.getParameter( i );
706 TypeDescriptor typeParam = tdParam.getType();
707 Integer paramIndex = new Integer( i );
709 if( typeParam.isImmutable() && !typeParam.isArray() ) {
710 // don't bother with this primitive parameter, it
711 // cannot affect reachability
715 if( aliasedParamIndices.contains( paramIndex ) ) {
716 // use the alias blob but give parameters their
717 // own primary obj region
718 og.assignTempEqualToAliasedParam( tdParam,
721 // this parameter is not aliased to others, give it
722 // a fresh primary obj and secondary object
723 og.assignTempEqualToParamAlloc( tdParam,
724 mc.getDescriptor() instanceof TaskDescriptor,
729 // add additional edges for aliased regions if necessary
730 if( !aliasedParamIndices.isEmpty() ) {
731 og.addParam2ParamAliasEdges( fm, aliasedParamIndices );
734 // clean up reachability on initial parameter shapes
737 // this maps tokens to parameter indices and vice versa
738 // for when this method is a callee
739 og.prepareParamTokenMaps( fm );
742 OwnershipGraph ogResult = new OwnershipGraph(allocationDepth, typeUtil);
744 mapMethodContextToInitialParamAllocGraph.put(mc, ogResult);
747 // or just leverage the cached copy
748 og.merge(ogInitParamAlloc);
752 case FKind.FlatOpNode:
753 FlatOpNode fon = (FlatOpNode) fn;
754 if( fon.getOp().getOp() == Operation.ASSIGN ) {
757 og.assignTempXEqualToTempY(lhs, rhs);
761 case FKind.FlatCastNode:
762 FlatCastNode fcn = (FlatCastNode) fn;
766 TypeDescriptor td = fcn.getType();
769 og.assignTypedTempXEqualToTempY(lhs, rhs, td);
772 case FKind.FlatFieldNode:
773 FlatFieldNode ffn = (FlatFieldNode) fn;
776 fld = ffn.getField();
777 if( !fld.getType().isImmutable() || fld.getType().isArray() ) {
778 og.assignTempXEqualToTempYFieldF(lhs, rhs, fld);
782 case FKind.FlatSetFieldNode:
783 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
785 fld = fsfn.getField();
787 if( !fld.getType().isImmutable() || fld.getType().isArray() ) {
788 og.assignTempXFieldFEqualToTempY(lhs, fld, rhs);
792 case FKind.FlatElementNode:
793 FlatElementNode fen = (FlatElementNode) fn;
796 if( !lhs.getType().isImmutable() || lhs.getType().isArray() ) {
798 assert rhs.getType() != null;
799 assert rhs.getType().isArray();
801 TypeDescriptor tdElement = rhs.getType().dereference();
802 FieldDescriptor fdElement = getArrayField( tdElement );
804 og.assignTempXEqualToTempYFieldF(lhs, rhs, fdElement);
808 case FKind.FlatSetElementNode:
809 FlatSetElementNode fsen = (FlatSetElementNode) fn;
812 if( !rhs.getType().isImmutable() || rhs.getType().isArray() ) {
814 assert lhs.getType() != null;
815 assert lhs.getType().isArray();
817 TypeDescriptor tdElement = lhs.getType().dereference();
818 FieldDescriptor fdElement = getArrayField( tdElement );
820 og.assignTempXFieldFEqualToTempY(lhs, fdElement, rhs);
825 FlatNew fnn = (FlatNew) fn;
827 if( !lhs.getType().isImmutable() || lhs.getType().isArray() ) {
828 AllocationSite as = getAllocationSiteFromFlatNewPRIVATE(fnn);
829 og.assignTempEqualToNewAlloc(lhs, as);
834 FlatCall fc = (FlatCall) fn;
835 MethodDescriptor md = fc.getMethod();
836 FlatMethod flatm = state.getMethodFlat(md);
837 OwnershipGraph ogMergeOfAllPossibleCalleeResults = new OwnershipGraph(allocationDepth, typeUtil);
839 if( md.isStatic() ) {
840 // a static method is simply always the same, makes life easy
841 ogMergeOfAllPossibleCalleeResults = og;
843 Set<Integer> aliasedParamIndices =
844 ogMergeOfAllPossibleCalleeResults.calculateAliasedParamSet(fc, md.isStatic(), flatm);
846 MethodContext mcNew = new MethodContext( md, aliasedParamIndices );
847 Set contexts = mapDescriptorToAllMethodContexts.get( md );
848 assert contexts != null;
849 contexts.add( mcNew );
851 addDependent( mc, mcNew );
853 OwnershipGraph onlyPossibleCallee = mapMethodContextToCompleteOwnershipGraph.get( mcNew );
855 if( onlyPossibleCallee == null ) {
856 // if this method context has never been analyzed just schedule it for analysis
857 // and skip over this call site for now
858 if( !methodContextsToVisitSet.contains( mcNew ) ) {
859 methodContextsToVisitQ.add( new MethodContextQWrapper( mapDescriptorToPriority.get( md ),
861 methodContextsToVisitSet.add( mcNew );
865 ogMergeOfAllPossibleCalleeResults.resolveMethodCall(fc, md.isStatic(), flatm, onlyPossibleCallee, mc, null);
869 // if the method descriptor is virtual, then there could be a
870 // set of possible methods that will actually be invoked, so
871 // find all of them and merge all of their results together
872 TypeDescriptor typeDesc = fc.getThis().getType();
873 Set possibleCallees = callGraph.getMethods(md, typeDesc);
875 Iterator i = possibleCallees.iterator();
876 while( i.hasNext() ) {
877 MethodDescriptor possibleMd = (MethodDescriptor) i.next();
878 FlatMethod pflatm = state.getMethodFlat(possibleMd);
880 // don't alter the working graph (og) until we compute a result for every
881 // possible callee, merge them all together, then set og to that
882 OwnershipGraph ogCopy = new OwnershipGraph(allocationDepth, typeUtil);
885 Set<Integer> aliasedParamIndices =
886 ogCopy.calculateAliasedParamSet(fc, possibleMd.isStatic(), pflatm);
888 MethodContext mcNew = new MethodContext( possibleMd, aliasedParamIndices );
889 Set contexts = mapDescriptorToAllMethodContexts.get( md );
890 assert contexts != null;
891 contexts.add( mcNew );
893 addDependent( mc, mcNew );
895 OwnershipGraph ogPotentialCallee = mapMethodContextToCompleteOwnershipGraph.get( mcNew );
897 if( ogPotentialCallee == null ) {
898 // if this method context has never been analyzed just schedule it for analysis
899 // and skip over this call site for now
900 if( !methodContextsToVisitSet.contains( mcNew ) ) {
901 methodContextsToVisitQ.add( new MethodContextQWrapper( mapDescriptorToPriority.get( md ),
903 methodContextsToVisitSet.add( mcNew );
907 ogCopy.resolveMethodCall(fc, possibleMd.isStatic(), pflatm, ogPotentialCallee, mc, null);
910 ogMergeOfAllPossibleCalleeResults.merge(ogCopy);
914 og = ogMergeOfAllPossibleCalleeResults;
917 case FKind.FlatReturnNode:
918 FlatReturnNode frn = (FlatReturnNode) fn;
919 rhs = frn.getReturnTemp();
920 if( rhs != null && !rhs.getType().isImmutable() ) {
921 og.assignReturnEqualToTemp(rhs);
923 setRetNodes.add(frn);
927 mappingFlatNodeToOwnershipGraph.put(fn, og);
933 // this method should generate integers strictly greater than zero!
934 // special "shadow" regions are made from a heap region by negating
936 static public Integer generateUniqueHeapRegionNodeID() {
938 return new Integer(uniqueIDcount);
942 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
943 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
944 if( fdElement == null ) {
945 fdElement = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC),
947 arrayElementFieldName,
950 mapTypeToArrayField.put( tdElement, fdElement );
956 private void setGraphForMethodContext(MethodContext mc, OwnershipGraph og) {
958 mapMethodContextToCompleteOwnershipGraph.put(mc, og);
960 if( writeDOTs && writeAllDOTs ) {
961 if( !mapMethodContextToNumUpdates.containsKey(mc) ) {
962 mapMethodContextToNumUpdates.put(mc, new Integer(0) );
964 Integer n = mapMethodContextToNumUpdates.get(mc);
966 og.writeGraph(mc, n, true, true, true, false, false);
967 } catch( IOException e ) {}
968 mapMethodContextToNumUpdates.put(mc, n + 1);
973 private void addDependent( MethodContext caller, MethodContext callee ) {
974 HashSet<MethodContext> deps = mapMethodContextToDependentContexts.get( callee );
976 deps = new HashSet<MethodContext>();
979 mapMethodContextToDependentContexts.put( callee, deps );
982 private Iterator<MethodContext> iteratorDependents( MethodContext callee ) {
983 HashSet<MethodContext> deps = mapMethodContextToDependentContexts.get( callee );
985 deps = new HashSet<MethodContext>();
986 mapMethodContextToDependentContexts.put( callee, deps );
988 return deps.iterator();
992 private void writeFinalContextGraphs() {
993 // arguments to writeGraph are:
994 // boolean writeLabels,
995 // boolean labelSelect,
996 // boolean pruneGarbage,
997 // boolean writeReferencers
998 // boolean writeParamMappings
1000 Set entrySet = mapMethodContextToCompleteOwnershipGraph.entrySet();
1001 Iterator itr = entrySet.iterator();
1002 while( itr.hasNext() ) {
1003 Map.Entry me = (Map.Entry) itr.next();
1004 MethodContext mc = (MethodContext) me.getKey();
1005 OwnershipGraph og = (OwnershipGraph) me.getValue();
1008 og.writeGraph(mc, true, true, true, false, false);
1009 } catch( IOException e ) {}
1014 // return just the allocation site associated with one FlatNew node
1015 private AllocationSite getAllocationSiteFromFlatNewPRIVATE(FlatNew fn) {
1017 if( !mapFlatNewToAllocationSite.containsKey(fn) ) {
1018 AllocationSite as = new AllocationSite(allocationDepth, fn, fn.getDisjointId());
1020 // the newest nodes are single objects
1021 for( int i = 0; i < allocationDepth; ++i ) {
1022 Integer id = generateUniqueHeapRegionNodeID();
1023 as.setIthOldest(i, id);
1024 mapHrnIdToAllocationSite.put( id, as );
1027 // the oldest node is a summary node
1028 Integer idSummary = generateUniqueHeapRegionNodeID();
1029 as.setSummary(idSummary);
1031 mapFlatNewToAllocationSite.put(fn, as);
1034 return mapFlatNewToAllocationSite.get(fn);
1038 // return all allocation sites in the method (there is one allocation
1039 // site per FlatNew node in a method)
1040 private HashSet<AllocationSite> getAllocationSiteSet(Descriptor d) {
1041 if( !mapDescriptorToAllocationSiteSet.containsKey(d) ) {
1042 buildAllocationSiteSet(d);
1045 return mapDescriptorToAllocationSiteSet.get(d);
1049 private void buildAllocationSiteSet(Descriptor d) {
1050 HashSet<AllocationSite> s = new HashSet<AllocationSite>();
1053 if( d instanceof MethodDescriptor ) {
1054 fm = state.getMethodFlat( (MethodDescriptor) d);
1056 assert d instanceof TaskDescriptor;
1057 fm = state.getMethodFlat( (TaskDescriptor) d);
1060 // visit every node in this FlatMethod's IR graph
1061 // and make a set of the allocation sites from the
1062 // FlatNew node's visited
1063 HashSet<FlatNode> visited = new HashSet<FlatNode>();
1064 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
1067 while( !toVisit.isEmpty() ) {
1068 FlatNode n = toVisit.iterator().next();
1070 if( n instanceof FlatNew ) {
1071 s.add(getAllocationSiteFromFlatNewPRIVATE( (FlatNew) n) );
1077 for( int i = 0; i < n.numNext(); ++i ) {
1078 FlatNode child = n.getNext(i);
1079 if( !visited.contains(child) ) {
1085 mapDescriptorToAllocationSiteSet.put(d, s);
1089 private HashSet<AllocationSite> getFlaggedAllocationSites(Descriptor dIn) {
1091 HashSet<AllocationSite> out = new HashSet<AllocationSite>();
1092 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1093 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1097 while( !toVisit.isEmpty() ) {
1098 Descriptor d = toVisit.iterator().next();
1102 HashSet<AllocationSite> asSet = getAllocationSiteSet(d);
1103 Iterator asItr = asSet.iterator();
1104 while( asItr.hasNext() ) {
1105 AllocationSite as = (AllocationSite) asItr.next();
1106 if( as.getDisjointId() != null ) {
1111 // enqueue callees of this method to be searched for
1112 // allocation sites also
1113 Set callees = callGraph.getCalleeSet(d);
1114 if( callees != null ) {
1115 Iterator methItr = callees.iterator();
1116 while( methItr.hasNext() ) {
1117 MethodDescriptor md = (MethodDescriptor) methItr.next();
1119 if( !visited.contains(md) ) {
1130 private HashSet<AllocationSite>
1131 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
1133 HashSet<AllocationSite> asSetTotal = new HashSet<AllocationSite>();
1134 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1135 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1139 // traverse this task and all methods reachable from this task
1140 while( !toVisit.isEmpty() ) {
1141 Descriptor d = toVisit.iterator().next();
1145 HashSet<AllocationSite> asSet = getAllocationSiteSet(d);
1146 Iterator asItr = asSet.iterator();
1147 while( asItr.hasNext() ) {
1148 AllocationSite as = (AllocationSite) asItr.next();
1149 TypeDescriptor typed = as.getType();
1150 if( typed != null ) {
1151 ClassDescriptor cd = typed.getClassDesc();
1152 if( cd != null && cd.hasFlags() ) {
1158 // enqueue callees of this method to be searched for
1159 // allocation sites also
1160 Set callees = callGraph.getCalleeSet(d);
1161 if( callees != null ) {
1162 Iterator methItr = callees.iterator();
1163 while( methItr.hasNext() ) {
1164 MethodDescriptor md = (MethodDescriptor) methItr.next();
1166 if( !visited.contains(md) ) {
1178 private LinkedList<MethodContext> topologicalSort( HashSet<MethodContext> set ) {
1179 HashSet <MethodContext> discovered = new HashSet <MethodContext>();
1180 LinkedList<MethodContext> sorted = new LinkedList<MethodContext>();
1182 Iterator<MethodContext> itr = set.iterator();
1183 while( itr.hasNext() ) {
1184 MethodContext mc = itr.next();
1186 if( !discovered.contains( mc ) ) {
1187 dfsVisit( set, mc, sorted, discovered );
1194 private void dfsVisit( HashSet<MethodContext> set,
1196 LinkedList<MethodContext> sorted,
1197 HashSet <MethodContext> discovered ) {
1198 discovered.add( mc );
1200 Descriptor d = mc.getDescriptor();
1201 if( d instanceof MethodDescriptor ) {
1202 MethodDescriptor md = (MethodDescriptor) d;
1203 Iterator itr = callGraph.getCallerSet( md ).iterator();
1204 while( itr.hasNext() ) {
1205 Descriptor dCaller = (Descriptor) itr.next();
1207 // only consider the callers in the original set to analyze
1208 Set<MethodContext> callerContexts = mapDescriptorToAllMethodContexts.get( dCaller );
1209 if( callerContexts == null )
1212 // since the analysis hasn't started, there should be exactly one
1213 // context if there are any at all
1214 assert callerContexts.size() == 1;
1215 MethodContext mcCaller = callerContexts.iterator().next();
1216 assert set.contains( mcCaller );
1218 if( !discovered.contains( mcCaller ) ) {
1219 dfsVisit( set, mcCaller, sorted, discovered );
1224 sorted.addFirst( mc );
1229 private String computeAliasContextHistogram() {
1231 Hashtable<Integer, Integer> mapNumContexts2NumDesc =
1232 new Hashtable<Integer, Integer>();
1234 Iterator itr = mapDescriptorToAllMethodContexts.entrySet().iterator();
1235 while( itr.hasNext() ) {
1236 Map.Entry me = (Map.Entry) itr.next();
1237 HashSet<MethodContext> s = (HashSet<MethodContext>) me.getValue();
1239 Integer i = mapNumContexts2NumDesc.get( s.size() );
1241 i = new Integer( 0 );
1243 mapNumContexts2NumDesc.put( s.size(), i + 1 );
1249 itr = mapNumContexts2NumDesc.entrySet().iterator();
1250 while( itr.hasNext() ) {
1251 Map.Entry me = (Map.Entry) itr.next();
1252 Integer c0 = (Integer) me.getKey();
1253 Integer d0 = (Integer) me.getValue();
1255 s += String.format( "%4d methods had %4d unique alias contexts.\n", d0, c0 );
1258 s += String.format( "\n%4d total methods analayzed.\n", total );
1263 public OwnershipGraph getMappingFlatNodeToOwnershipGraph(FlatNode fn) {
1264 return mappingFlatNodeToOwnershipGraph.get(fn);
1269 // insert a call to debugSnapshot() somewhere in the analysis
1270 // to get successive captures of the analysis state
1271 boolean takeDebugSnapshots = false;
1272 String mcDescSymbolDebug = "addFirst";
1273 boolean stopAfterCapture = true;
1275 // increments every visit to debugSnapshot, don't fiddle with it
1276 int debugCounter = 0;
1278 // the value of debugCounter to start reporting the debugCounter
1279 // to the screen to let user know what debug iteration we're at
1280 int numStartCountReport = 0;
1282 // the frequency of debugCounter values to print out, 0 no report
1283 int freqCountReport = 0;
1285 // the debugCounter value at which to start taking snapshots
1286 int iterStartCapture = 0;
1288 // the number of snapshots to take
1289 int numIterToCapture = 40;
1291 void debugSnapshot(OwnershipGraph og, FlatNode fn) {
1292 if( debugCounter > iterStartCapture + numIterToCapture ) {
1297 if( debugCounter > numStartCountReport &&
1298 freqCountReport > 0 &&
1299 debugCounter % freqCountReport == 0 ) {
1300 System.out.println(" @@@ debug counter = "+debugCounter);
1302 if( debugCounter > iterStartCapture ) {
1303 System.out.println(" @@@ capturing debug "+(debugCounter-iterStartCapture)+" @@@");
1304 String graphName = String.format("snap%04d",debugCounter-iterStartCapture);
1306 graphName = graphName+fn;
1309 // arguments to writeGraph are:
1310 // boolean writeLabels,
1311 // boolean labelSelect,
1312 // boolean pruneGarbage,
1313 // boolean writeReferencers
1314 // boolean writeParamMappings
1316 //og.writeGraph(graphName, true, true, true, false, false);
1317 og.writeGraph(graphName, true, true, true, false, false);
1318 } catch( Exception e ) {
1319 System.out.println("Error writing debug capture.");
1324 if( debugCounter == iterStartCapture + numIterToCapture && stopAfterCapture ) {
1325 System.out.println("Stopping analysis after debug captures.");