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 Set<HeapRegionNode> createsPotentialAliases(Descriptor taskOrMethod,
35 OwnershipGraph og = getGraphOfAllContextsFromDescriptor(taskOrMethod);
37 return og.hasPotentialAlias(paramIndex1, paramIndex2);
40 public Set<HeapRegionNode> createsPotentialAliases(Descriptor taskOrMethod,
42 AllocationSite alloc) {
44 OwnershipGraph og = getGraphOfAllContextsFromDescriptor(taskOrMethod);
46 return og.hasPotentialAlias(paramIndex, alloc);
49 public Set<HeapRegionNode> createsPotentialAliases(Descriptor taskOrMethod,
53 OwnershipGraph og = getGraphOfAllContextsFromDescriptor(taskOrMethod);
55 return og.hasPotentialAlias(paramIndex, alloc);
58 public Set<HeapRegionNode> 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 public String prettyPrintNodeSet( Set<HeapRegionNode> s ) {
92 Iterator<HeapRegionNode> i = s.iterator();
93 while( i.hasNext() ) {
94 HeapRegionNode n = i.next();
96 AllocationSite as = n.getAllocationSite();
98 out += " "+n.toString()+",\n";
100 out += " "+n.toString()+": "+as.toStringVerbose()+",\n";
109 // use the methods given above to check every possible alias
110 // between task parameters and flagged allocation sites reachable
112 public void writeAllAliases(String outputFile, String timeReport) throws java.io.IOException {
114 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile) );
116 bw.write("Conducting ownership analysis with allocation depth = "+allocationDepth+"\n");
117 bw.write(timeReport+"\n");
119 // look through every task for potential aliases
120 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
121 while( taskItr.hasNext() ) {
122 TaskDescriptor td = (TaskDescriptor) taskItr.next();
124 bw.write("\n---------"+td+"--------\n");
126 HashSet<AllocationSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
128 Set<HeapRegionNode> common;
130 // for each task parameter, check for aliases with
131 // other task parameters and every allocation site
132 // reachable from this task
133 boolean foundSomeAlias = false;
135 FlatMethod fm = state.getMethodFlat(td);
136 for( int i = 0; i < fm.numParameters(); ++i ) {
138 // for the ith parameter check for aliases to all
139 // higher numbered parameters
140 for( int j = i + 1; j < fm.numParameters(); ++j ) {
141 common = createsPotentialAliases(td, i, j);
142 if( !common.isEmpty() ) {
143 foundSomeAlias = true;
144 bw.write("Potential alias between parameters "+i+" and "+j+".\n");
145 bw.write(prettyPrintNodeSet( common )+"\n" );
149 // for the ith parameter, check for aliases against
150 // the set of allocation sites reachable from this
152 Iterator allocItr = allocSites.iterator();
153 while( allocItr.hasNext() ) {
154 AllocationSite as = (AllocationSite) allocItr.next();
155 common = createsPotentialAliases(td, i, as);
156 if( !common.isEmpty() ) {
157 foundSomeAlias = true;
158 bw.write("Potential alias between parameter "+i+" and "+as.getFlatNew()+".\n");
159 bw.write(prettyPrintNodeSet( common )+"\n" );
164 // for each allocation site check for aliases with
165 // other allocation sites in the context of execution
167 HashSet<AllocationSite> outerChecked = new HashSet<AllocationSite>();
168 Iterator allocItr1 = allocSites.iterator();
169 while( allocItr1.hasNext() ) {
170 AllocationSite as1 = (AllocationSite) allocItr1.next();
172 Iterator allocItr2 = allocSites.iterator();
173 while( allocItr2.hasNext() ) {
174 AllocationSite as2 = (AllocationSite) allocItr2.next();
176 if( !outerChecked.contains(as2) ) {
177 common = createsPotentialAliases(td, as1, as2);
179 if( !common.isEmpty() ) {
180 foundSomeAlias = true;
181 bw.write("Potential alias between "+as1.getFlatNew()+" and "+as2.getFlatNew()+".\n");
182 bw.write(prettyPrintNodeSet( common )+"\n" );
187 outerChecked.add(as1);
190 if( !foundSomeAlias ) {
191 bw.write("No aliases between flagged objects in Task "+td+".\n");
195 bw.write( "\n"+computeAliasContextHistogram() );
200 // this version of writeAllAliases is for Java programs that have no tasks
201 public void writeAllAliasesJava(String outputFile, String timeReport) throws java.io.IOException {
204 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile) );
206 bw.write("Conducting ownership analysis with allocation depth = "+allocationDepth+"\n");
207 bw.write(timeReport+"\n\n");
209 boolean foundSomeAlias = false;
211 Descriptor d = typeUtil.getMain();
212 HashSet<AllocationSite> allocSites = getFlaggedAllocationSites(d);
214 // for each allocation site check for aliases with
215 // other allocation sites in the context of execution
217 HashSet<AllocationSite> outerChecked = new HashSet<AllocationSite>();
218 Iterator allocItr1 = allocSites.iterator();
219 while( allocItr1.hasNext() ) {
220 AllocationSite as1 = (AllocationSite) allocItr1.next();
222 Iterator allocItr2 = allocSites.iterator();
223 while( allocItr2.hasNext() ) {
224 AllocationSite as2 = (AllocationSite) allocItr2.next();
226 if( !outerChecked.contains(as2) ) {
227 Set<HeapRegionNode> common = createsPotentialAliases(d, as1, as2);
229 if( !common.isEmpty() ) {
230 foundSomeAlias = true;
231 bw.write("Potential alias between "+as1.getDisjointId()+" and "+as2.getDisjointId()+".\n");
232 bw.write( prettyPrintNodeSet( common )+"\n" );
237 outerChecked.add(as1);
240 if( !foundSomeAlias ) {
241 bw.write("No aliases between flagged objects found.\n");
244 bw.write( "\n"+computeAliasContextHistogram() );
247 ///////////////////////////////////////////
249 // end public interface
251 ///////////////////////////////////////////
260 // data from the compiler
262 private TypeUtil typeUtil;
263 private CallGraph callGraph;
264 private int allocationDepth;
266 // used to identify HeapRegionNode objects
267 // A unique ID equates an object in one
268 // ownership graph with an object in another
269 // graph that logically represents the same
271 // start at 10 and increment to leave some
272 // reserved IDs for special purposes
273 static private int uniqueIDcount = 10;
276 // Use these data structures to track progress of
277 // processing all methods in the program, and by methods
278 // TaskDescriptor and MethodDescriptor are combined
279 // together, with a common parent class Descriptor
280 private Hashtable<MethodContext, OwnershipGraph> mapMethodContextToInitialParamAllocGraph;
281 private Hashtable<MethodContext, OwnershipGraph> mapMethodContextToCompleteOwnershipGraph;
282 private Hashtable<FlatNew, AllocationSite> mapFlatNewToAllocationSite;
283 private Hashtable<Descriptor, HashSet<AllocationSite> > mapDescriptorToAllocationSiteSet;
284 private Hashtable<MethodContext, Integer> mapMethodContextToNumUpdates;
285 private Hashtable<Descriptor, HashSet<MethodContext> > mapDescriptorToAllMethodContexts;
286 private Hashtable<MethodContext, HashSet<MethodContext> > mapMethodContextToDependentContexts;
288 // Use these data structures to track progress of one pass of
289 // processing the FlatNodes of a particular method
290 private HashSet <FlatNode> flatNodesToVisit;
291 private Hashtable<FlatNode, OwnershipGraph> mapFlatNodeToOwnershipGraph;
292 private HashSet <FlatReturnNode> returnNodesToCombineForCompleteOwnershipGraph;
294 // descriptorsToAnalyze identifies the set of tasks and methods
295 // that are reachable from the program tasks, this set is initialized
296 // and then remains static
297 private HashSet<Descriptor> descriptorsToAnalyze;
299 // descriptorsToVisit is initialized to descriptorsToAnalyze and is
300 // reduced by visiting a descriptor during analysis. When dependents
301 // must be scheduled, only those contained in descriptorsToAnalyze
302 // should be re-added to this queue
303 private PriorityQueue<MethodContextQWrapper> methodContextsToVisitQ;
304 private Set <MethodContext> methodContextsToVisitSet;
305 private Hashtable<Descriptor, Integer> mapDescriptorToPriority;
308 // special field descriptors for array elements
309 public static final String arrayElementFieldName = "___element_";
310 private static Hashtable<TypeDescriptor, FieldDescriptor> mapTypeToArrayField =
311 new Hashtable<TypeDescriptor, FieldDescriptor>();
314 // for controlling DOT file output
315 private boolean writeDOTs;
316 private boolean writeAllDOTs;
320 // this analysis generates an ownership graph for every task
322 public OwnershipAnalysis(State state,
327 boolean writeAllDOTs,
328 String aliasFile) throws java.io.IOException {
330 double timeStartAnalysis = (double) System.nanoTime();
334 this.callGraph = callGraph;
335 this.allocationDepth = allocationDepth;
336 this.writeDOTs = writeDOTs;
337 this.writeAllDOTs = writeAllDOTs;
339 descriptorsToAnalyze = new HashSet<Descriptor>();
341 mapMethodContextToInitialParamAllocGraph =
342 new Hashtable<MethodContext, OwnershipGraph>();
344 mapMethodContextToCompleteOwnershipGraph =
345 new Hashtable<MethodContext, OwnershipGraph>();
347 mapFlatNewToAllocationSite =
348 new Hashtable<FlatNew, AllocationSite>();
350 mapDescriptorToAllocationSiteSet =
351 new Hashtable<Descriptor, HashSet<AllocationSite> >();
353 mapDescriptorToAllMethodContexts =
354 new Hashtable<Descriptor, HashSet<MethodContext> >();
356 mapMethodContextToDependentContexts =
357 new Hashtable<MethodContext, HashSet<MethodContext> >();
359 mapDescriptorToPriority =
360 new Hashtable<Descriptor, Integer>();
364 mapMethodContextToNumUpdates = new Hashtable<MethodContext, Integer>();
369 // initialize methods to visit as the set of all tasks in the
370 // program and then any method that could be called starting
372 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
373 while( taskItr.hasNext() ) {
374 Descriptor d = (Descriptor) taskItr.next();
375 scheduleAllCallees(d);
379 // we are not in task mode, just normal Java, so start with
381 Descriptor d = typeUtil.getMain();
382 scheduleAllCallees(d);
386 // before beginning analysis, initialize every scheduled method
387 // with an ownership graph that has populated parameter index tables
388 // by analyzing the first node which is always a FlatMethod node
389 Iterator<Descriptor> dItr = descriptorsToAnalyze.iterator();
390 while( dItr.hasNext() ) {
391 Descriptor d = dItr.next();
392 OwnershipGraph og = new OwnershipGraph(allocationDepth, typeUtil);
395 if( d instanceof MethodDescriptor ) {
396 fm = state.getMethodFlat( (MethodDescriptor) d);
398 assert d instanceof TaskDescriptor;
399 fm = state.getMethodFlat( (TaskDescriptor) d);
402 MethodContext mc = new MethodContext( d );
403 assert !mapDescriptorToAllMethodContexts.containsKey( d );
404 HashSet<MethodContext> s = new HashSet<MethodContext>();
406 mapDescriptorToAllMethodContexts.put( d, s );
408 //System.out.println("Previsiting " + mc);
410 og = analyzeFlatNode(mc, fm, null, og);
414 og.writeGraph( "previsit"+mc, true, true, true, false, false );
415 } catch( Exception e ) {}
418 setGraphForMethodContext(mc, og);
421 // as mentioned above, analyze methods one-by-one, possibly revisiting
422 // a method if the methods that it calls are updated
425 double timeEndAnalysis = (double) System.nanoTime();
426 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
427 String treport = String.format( "The analysis took %.3f sec.", dt );
428 System.out.println( treport );
430 if( writeDOTs && !writeAllDOTs ) {
431 writeFinalContextGraphs();
434 if( aliasFile != null ) {
436 writeAllAliases(aliasFile, treport);
438 writeAllAliasesJava(aliasFile, treport);
443 // called from the constructor to help initialize the set
444 // of methods that needs to be analyzed by ownership analysis
445 private void scheduleAllCallees(Descriptor d) {
446 if( descriptorsToAnalyze.contains(d) ) {
449 descriptorsToAnalyze.add(d);
451 // start with all method calls to further schedule
452 Set moreMethodsToCheck = moreMethodsToCheck = callGraph.getMethodCalls(d);
454 if( d instanceof MethodDescriptor ) {
455 // see if this method has virtual dispatch
456 Set virtualMethods = callGraph.getMethods( (MethodDescriptor)d);
457 moreMethodsToCheck.addAll(virtualMethods);
460 // keep following any further methods identified in
462 Iterator methItr = moreMethodsToCheck.iterator();
463 while( methItr.hasNext() ) {
464 Descriptor m = (Descriptor) methItr.next();
465 scheduleAllCallees(m);
470 // manage the set of tasks and methods to be analyzed
471 // and be sure to reschedule tasks/methods when the methods
472 // they call are updated
473 private void analyzeMethods() throws java.io.IOException {
475 // first gather all of the method contexts to analyze
476 HashSet<MethodContext> allContexts = new HashSet<MethodContext>();
477 Iterator<Descriptor> itrd2a = descriptorsToAnalyze.iterator();
478 while( itrd2a.hasNext() ) {
479 HashSet<MethodContext> mcs = mapDescriptorToAllMethodContexts.get( itrd2a.next() );
482 Iterator<MethodContext> itrmc = mcs.iterator();
483 while( itrmc.hasNext() ) {
484 allContexts.add( itrmc.next() );
488 // topologically sort them according to the caller graph so leaf calls are
489 // ordered first; use that ordering to give method contexts priorities
490 LinkedList<MethodContext> sortedMethodContexts = topologicalSort( allContexts );
492 methodContextsToVisitQ = new PriorityQueue<MethodContextQWrapper>();
493 methodContextsToVisitSet = new HashSet<MethodContext>();
496 Iterator<MethodContext> mcItr = sortedMethodContexts.iterator();
497 while( mcItr.hasNext() ) {
498 MethodContext mc = mcItr.next();
499 mapDescriptorToPriority.put( mc.getDescriptor(), new Integer( p ) );
500 methodContextsToVisitQ.add( new MethodContextQWrapper( p, mc ) );
501 methodContextsToVisitSet.add( mc );
505 // analyze methods from the priority queue until it is empty
506 while( !methodContextsToVisitQ.isEmpty() ) {
507 MethodContext mc = methodContextsToVisitQ.poll().getMethodContext();
508 assert methodContextsToVisitSet.contains( mc );
509 methodContextsToVisitSet.remove( mc );
511 // because the task or method descriptor just extracted
512 // was in the "to visit" set it either hasn't been analyzed
513 // yet, or some method that it depends on has been
514 // updated. Recompute a complete ownership graph for
515 // this task/method and compare it to any previous result.
516 // If there is a change detected, add any methods/tasks
517 // that depend on this one to the "to visit" set.
519 System.out.println("Analyzing " + mc);
521 Descriptor d = mc.getDescriptor();
523 if( d instanceof MethodDescriptor ) {
524 fm = state.getMethodFlat( (MethodDescriptor) d);
526 assert d instanceof TaskDescriptor;
527 fm = state.getMethodFlat( (TaskDescriptor) d);
530 OwnershipGraph og = analyzeFlatMethod(mc, fm);
531 OwnershipGraph ogPrev = mapMethodContextToCompleteOwnershipGraph.get(mc);
532 if( !og.equals(ogPrev) ) {
533 setGraphForMethodContext(mc, og);
535 Iterator<MethodContext> depsItr = iteratorDependents( mc );
536 while( depsItr.hasNext() ) {
537 MethodContext mcNext = depsItr.next();
539 if( !methodContextsToVisitSet.contains( mcNext ) ) {
540 methodContextsToVisitQ.add( new MethodContextQWrapper( mapDescriptorToPriority.get( mcNext.getDescriptor() ),
542 methodContextsToVisitSet.add( mcNext );
551 // keep passing the Descriptor of the method along for debugging
552 // and dot file writing
553 private OwnershipGraph
554 analyzeFlatMethod(MethodContext mc,
555 FlatMethod flatm) throws java.io.IOException {
557 // initialize flat nodes to visit as the flat method
558 // because it is the entry point
560 flatNodesToVisit = new HashSet<FlatNode>();
561 flatNodesToVisit.add(flatm);
563 // initilize the mapping of flat nodes in this flat method to
564 // ownership graph results to an empty mapping
565 mapFlatNodeToOwnershipGraph = new Hashtable<FlatNode, OwnershipGraph>();
567 // initialize the set of return nodes that will be combined as
568 // the final ownership graph result to return as an empty set
569 returnNodesToCombineForCompleteOwnershipGraph = new HashSet<FlatReturnNode>();
572 while( !flatNodesToVisit.isEmpty() ) {
573 FlatNode fn = (FlatNode) flatNodesToVisit.iterator().next();
574 flatNodesToVisit.remove(fn);
576 //System.out.println( " "+fn );
578 // perform this node's contributions to the ownership
579 // graph on a new copy, then compare it to the old graph
580 // at this node to see if anything was updated.
581 OwnershipGraph og = new OwnershipGraph(allocationDepth, typeUtil);
583 // start by merging all node's parents' graphs
584 for( int i = 0; i < fn.numPrev(); ++i ) {
585 FlatNode pn = fn.getPrev(i);
586 if( mapFlatNodeToOwnershipGraph.containsKey(pn) ) {
587 OwnershipGraph ogParent = mapFlatNodeToOwnershipGraph.get(pn);
592 // apply the analysis of the flat node to the
593 // ownership graph made from the merge of the
595 og = analyzeFlatNode(mc,
597 returnNodesToCombineForCompleteOwnershipGraph,
603 if( takeDebugSnapshots &&
604 mc.getDescriptor().getSymbol().equals( mcDescSymbolDebug ) ) {
605 debugSnapshot(og,fn);
610 // if the results of the new graph are different from
611 // the current graph at this node, replace the graph
612 // with the update and enqueue the children for
614 OwnershipGraph ogPrev = mapFlatNodeToOwnershipGraph.get(fn);
615 if( !og.equals(ogPrev) ) {
616 mapFlatNodeToOwnershipGraph.put(fn, og);
618 for( int i = 0; i < fn.numNext(); i++ ) {
619 FlatNode nn = fn.getNext(i);
620 flatNodesToVisit.add(nn);
625 // end by merging all return nodes into a complete
626 // ownership graph that represents all possible heap
627 // states after the flat method returns
628 OwnershipGraph completeGraph = new OwnershipGraph(allocationDepth, typeUtil);
629 Iterator retItr = returnNodesToCombineForCompleteOwnershipGraph.iterator();
630 while( retItr.hasNext() ) {
631 FlatReturnNode frn = (FlatReturnNode) retItr.next();
632 assert mapFlatNodeToOwnershipGraph.containsKey(frn);
633 OwnershipGraph ogr = mapFlatNodeToOwnershipGraph.get(frn);
634 completeGraph.merge(ogr);
637 return completeGraph;
641 private OwnershipGraph
642 analyzeFlatNode(MethodContext mc,
644 HashSet<FlatReturnNode> setRetNodes,
645 OwnershipGraph og) throws java.io.IOException {
651 // use node type to decide what alterations to make
652 // to the ownership graph
653 switch( fn.kind() ) {
655 case FKind.FlatMethod:
656 FlatMethod fm = (FlatMethod) fn;
658 // there should only be one FlatMethod node as the
659 // parent of all other FlatNode objects, so take
660 // the opportunity to construct the initial graph by
661 // adding parameters labels to new heap regions
662 // AND this should be done once globally so that the
663 // parameter IDs are consistent between analysis
664 // iterations, so if this step has been done already
665 // just merge in the cached version
666 OwnershipGraph ogInitParamAlloc = mapMethodContextToInitialParamAllocGraph.get(mc);
667 if( ogInitParamAlloc == null ) {
669 // if the method context has aliased parameters, make sure
670 // there is a blob region for all those param to reference
671 Set<Integer> aliasedParamIndices = mc.getAliasedParamIndices();
673 if( !aliasedParamIndices.isEmpty() ) {
674 og.makeAliasedParamHeapRegionNode();
677 // set up each parameter
678 for( int i = 0; i < fm.numParameters(); ++i ) {
679 TempDescriptor tdParam = fm.getParameter( i );
680 TypeDescriptor typeParam = tdParam.getType();
681 Integer paramIndex = new Integer( i );
683 if( typeParam.isImmutable() && !typeParam.isArray() ) {
684 // don't bother with this primitive parameter, it
685 // cannot affect reachability
689 if( aliasedParamIndices.contains( paramIndex ) ) {
690 // use the alias blob but give parameters their
691 // own primary obj region
692 og.assignTempEqualToAliasedParam( tdParam,
695 // this parameter is not aliased to others, give it
696 // a fresh primary obj and secondary object
697 og.assignTempEqualToParamAlloc( tdParam,
698 mc.getDescriptor() instanceof TaskDescriptor,
703 // add additional edges for aliased regions if necessary
704 if( !aliasedParamIndices.isEmpty() ) {
705 og.addParam2ParamAliasEdges( fm, aliasedParamIndices );
708 // clean up reachability on initial parameter shapes
711 // this maps tokens to parameter indices and vice versa
712 // for when this method is a callee
713 og.prepareParamTokenMaps( fm );
716 OwnershipGraph ogResult = new OwnershipGraph(allocationDepth, typeUtil);
718 mapMethodContextToInitialParamAllocGraph.put(mc, ogResult);
721 // or just leverage the cached copy
722 og.merge(ogInitParamAlloc);
726 case FKind.FlatOpNode:
727 FlatOpNode fon = (FlatOpNode) fn;
728 if( fon.getOp().getOp() == Operation.ASSIGN ) {
731 og.assignTempXEqualToTempY(lhs, rhs);
735 case FKind.FlatCastNode:
736 FlatCastNode fcn = (FlatCastNode) fn;
740 TypeDescriptor td = fcn.getType();
743 og.assignTypedTempXEqualToTempY(lhs, rhs, td);
746 case FKind.FlatFieldNode:
747 FlatFieldNode ffn = (FlatFieldNode) fn;
750 fld = ffn.getField();
751 if( !fld.getType().isImmutable() || fld.getType().isArray() ) {
752 og.assignTempXEqualToTempYFieldF(lhs, rhs, fld);
756 case FKind.FlatSetFieldNode:
757 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
759 fld = fsfn.getField();
761 if( !fld.getType().isImmutable() || fld.getType().isArray() ) {
762 og.assignTempXFieldFEqualToTempY(lhs, fld, rhs);
766 case FKind.FlatElementNode:
767 FlatElementNode fen = (FlatElementNode) fn;
770 if( !lhs.getType().isImmutable() || lhs.getType().isArray() ) {
772 assert rhs.getType() != null;
773 assert rhs.getType().isArray();
775 TypeDescriptor tdElement = rhs.getType().dereference();
776 FieldDescriptor fdElement = getArrayField( tdElement );
778 og.assignTempXEqualToTempYFieldF(lhs, rhs, fdElement);
782 case FKind.FlatSetElementNode:
783 FlatSetElementNode fsen = (FlatSetElementNode) fn;
786 if( !rhs.getType().isImmutable() || rhs.getType().isArray() ) {
788 assert lhs.getType() != null;
789 assert lhs.getType().isArray();
791 TypeDescriptor tdElement = lhs.getType().dereference();
792 FieldDescriptor fdElement = getArrayField( tdElement );
794 og.assignTempXFieldFEqualToTempY(lhs, fdElement, rhs);
799 FlatNew fnn = (FlatNew) fn;
801 if( !lhs.getType().isImmutable() || lhs.getType().isArray() ) {
802 AllocationSite as = getAllocationSiteFromFlatNewPRIVATE(fnn);
803 og.assignTempEqualToNewAlloc(lhs, as);
808 FlatCall fc = (FlatCall) fn;
809 MethodDescriptor md = fc.getMethod();
810 FlatMethod flatm = state.getMethodFlat(md);
811 OwnershipGraph ogMergeOfAllPossibleCalleeResults = new OwnershipGraph(allocationDepth, typeUtil);
813 if( md.isStatic() ) {
814 // a static method is simply always the same, makes life easy
815 ogMergeOfAllPossibleCalleeResults = og;
817 Set<Integer> aliasedParamIndices =
818 ogMergeOfAllPossibleCalleeResults.calculateAliasedParamSet(fc, md.isStatic(), flatm);
820 MethodContext mcNew = new MethodContext( md, aliasedParamIndices );
821 Set contexts = mapDescriptorToAllMethodContexts.get( md );
822 assert contexts != null;
823 contexts.add( mcNew );
825 addDependent( mc, mcNew );
827 OwnershipGraph onlyPossibleCallee = mapMethodContextToCompleteOwnershipGraph.get( mcNew );
829 if( onlyPossibleCallee == null ) {
830 // if this method context has never been analyzed just schedule it for analysis
831 // and skip over this call site for now
832 if( !methodContextsToVisitSet.contains( mcNew ) ) {
833 methodContextsToVisitQ.add( new MethodContextQWrapper( mapDescriptorToPriority.get( md ),
835 methodContextsToVisitSet.add( mcNew );
839 ogMergeOfAllPossibleCalleeResults.resolveMethodCall(fc, md.isStatic(), flatm, onlyPossibleCallee, mc);
843 // if the method descriptor is virtual, then there could be a
844 // set of possible methods that will actually be invoked, so
845 // find all of them and merge all of their results together
846 TypeDescriptor typeDesc = fc.getThis().getType();
847 Set possibleCallees = callGraph.getMethods(md, typeDesc);
849 Iterator i = possibleCallees.iterator();
850 while( i.hasNext() ) {
851 MethodDescriptor possibleMd = (MethodDescriptor) i.next();
852 FlatMethod pflatm = state.getMethodFlat(possibleMd);
854 // don't alter the working graph (og) until we compute a result for every
855 // possible callee, merge them all together, then set og to that
856 OwnershipGraph ogCopy = new OwnershipGraph(allocationDepth, typeUtil);
859 Set<Integer> aliasedParamIndices =
860 ogCopy.calculateAliasedParamSet(fc, possibleMd.isStatic(), pflatm);
862 MethodContext mcNew = new MethodContext( possibleMd, aliasedParamIndices );
863 Set contexts = mapDescriptorToAllMethodContexts.get( md );
864 assert contexts != null;
865 contexts.add( mcNew );
867 addDependent( mc, mcNew );
869 OwnershipGraph ogPotentialCallee = mapMethodContextToCompleteOwnershipGraph.get( mcNew );
871 if( ogPotentialCallee == null ) {
872 // if this method context has never been analyzed just schedule it for analysis
873 // and skip over this call site for now
874 if( !methodContextsToVisitSet.contains( mcNew ) ) {
875 methodContextsToVisitQ.add( new MethodContextQWrapper( mapDescriptorToPriority.get( md ),
877 methodContextsToVisitSet.add( mcNew );
881 ogCopy.resolveMethodCall(fc, possibleMd.isStatic(), pflatm, ogPotentialCallee, mc);
884 ogMergeOfAllPossibleCalleeResults.merge(ogCopy);
888 og = ogMergeOfAllPossibleCalleeResults;
891 case FKind.FlatReturnNode:
892 FlatReturnNode frn = (FlatReturnNode) fn;
893 rhs = frn.getReturnTemp();
894 if( rhs != null && !rhs.getType().isImmutable() ) {
895 og.assignReturnEqualToTemp(rhs);
897 setRetNodes.add(frn);
905 // this method should generate integers strictly greater than zero!
906 // special "shadow" regions are made from a heap region by negating
908 static public Integer generateUniqueHeapRegionNodeID() {
910 return new Integer(uniqueIDcount);
914 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
915 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
916 if( fdElement == null ) {
917 fdElement = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC),
919 arrayElementFieldName,
922 mapTypeToArrayField.put( tdElement, fdElement );
928 private void setGraphForMethodContext(MethodContext mc, OwnershipGraph og) {
930 mapMethodContextToCompleteOwnershipGraph.put(mc, og);
932 if( writeDOTs && writeAllDOTs ) {
933 if( !mapMethodContextToNumUpdates.containsKey(mc) ) {
934 mapMethodContextToNumUpdates.put(mc, new Integer(0) );
936 Integer n = mapMethodContextToNumUpdates.get(mc);
938 og.writeGraph(mc, n, true, true, true, false, false);
939 } catch( IOException e ) {}
940 mapMethodContextToNumUpdates.put(mc, n + 1);
945 private void addDependent( MethodContext caller, MethodContext callee ) {
946 HashSet<MethodContext> deps = mapMethodContextToDependentContexts.get( callee );
948 deps = new HashSet<MethodContext>();
951 mapMethodContextToDependentContexts.put( callee, deps );
954 private Iterator<MethodContext> iteratorDependents( MethodContext callee ) {
955 HashSet<MethodContext> deps = mapMethodContextToDependentContexts.get( callee );
957 deps = new HashSet<MethodContext>();
958 mapMethodContextToDependentContexts.put( callee, deps );
960 return deps.iterator();
964 private void writeFinalContextGraphs() {
965 // arguments to writeGraph are:
966 // boolean writeLabels,
967 // boolean labelSelect,
968 // boolean pruneGarbage,
969 // boolean writeReferencers
970 // boolean writeParamMappings
972 Set entrySet = mapMethodContextToCompleteOwnershipGraph.entrySet();
973 Iterator itr = entrySet.iterator();
974 while( itr.hasNext() ) {
975 Map.Entry me = (Map.Entry) itr.next();
976 MethodContext mc = (MethodContext) me.getKey();
977 OwnershipGraph og = (OwnershipGraph) me.getValue();
980 og.writeGraph(mc, true, true, true, false, false);
981 } catch( IOException e ) {}
986 // return just the allocation site associated with one FlatNew node
987 private AllocationSite getAllocationSiteFromFlatNewPRIVATE(FlatNew fn) {
989 if( !mapFlatNewToAllocationSite.containsKey(fn) ) {
990 AllocationSite as = new AllocationSite(allocationDepth, fn, fn.getDisjointId());
992 // the newest nodes are single objects
993 for( int i = 0; i < allocationDepth; ++i ) {
994 Integer id = generateUniqueHeapRegionNodeID();
995 as.setIthOldest(i, id);
998 // the oldest node is a summary node
999 Integer idSummary = generateUniqueHeapRegionNodeID();
1000 as.setSummary(idSummary);
1002 mapFlatNewToAllocationSite.put(fn, as);
1005 return mapFlatNewToAllocationSite.get(fn);
1009 // return all allocation sites in the method (there is one allocation
1010 // site per FlatNew node in a method)
1011 private HashSet<AllocationSite> getAllocationSiteSet(Descriptor d) {
1012 if( !mapDescriptorToAllocationSiteSet.containsKey(d) ) {
1013 buildAllocationSiteSet(d);
1016 return mapDescriptorToAllocationSiteSet.get(d);
1020 private void buildAllocationSiteSet(Descriptor d) {
1021 HashSet<AllocationSite> s = new HashSet<AllocationSite>();
1024 if( d instanceof MethodDescriptor ) {
1025 fm = state.getMethodFlat( (MethodDescriptor) d);
1027 assert d instanceof TaskDescriptor;
1028 fm = state.getMethodFlat( (TaskDescriptor) d);
1031 // visit every node in this FlatMethod's IR graph
1032 // and make a set of the allocation sites from the
1033 // FlatNew node's visited
1034 HashSet<FlatNode> visited = new HashSet<FlatNode>();
1035 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
1038 while( !toVisit.isEmpty() ) {
1039 FlatNode n = toVisit.iterator().next();
1041 if( n instanceof FlatNew ) {
1042 s.add(getAllocationSiteFromFlatNewPRIVATE( (FlatNew) n) );
1048 for( int i = 0; i < n.numNext(); ++i ) {
1049 FlatNode child = n.getNext(i);
1050 if( !visited.contains(child) ) {
1056 mapDescriptorToAllocationSiteSet.put(d, s);
1060 private HashSet<AllocationSite> getFlaggedAllocationSites(Descriptor dIn) {
1062 HashSet<AllocationSite> out = new HashSet<AllocationSite>();
1063 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1064 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1068 while( !toVisit.isEmpty() ) {
1069 Descriptor d = toVisit.iterator().next();
1073 HashSet<AllocationSite> asSet = getAllocationSiteSet(d);
1074 Iterator asItr = asSet.iterator();
1075 while( asItr.hasNext() ) {
1076 AllocationSite as = (AllocationSite) asItr.next();
1077 if( as.getDisjointId() != null ) {
1082 // enqueue callees of this method to be searched for
1083 // allocation sites also
1084 Set callees = callGraph.getCalleeSet(d);
1085 if( callees != null ) {
1086 Iterator methItr = callees.iterator();
1087 while( methItr.hasNext() ) {
1088 MethodDescriptor md = (MethodDescriptor) methItr.next();
1090 if( !visited.contains(md) ) {
1101 private HashSet<AllocationSite>
1102 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
1104 HashSet<AllocationSite> asSetTotal = new HashSet<AllocationSite>();
1105 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1106 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1110 // traverse this task and all methods reachable from this task
1111 while( !toVisit.isEmpty() ) {
1112 Descriptor d = toVisit.iterator().next();
1116 HashSet<AllocationSite> asSet = getAllocationSiteSet(d);
1117 Iterator asItr = asSet.iterator();
1118 while( asItr.hasNext() ) {
1119 AllocationSite as = (AllocationSite) asItr.next();
1120 TypeDescriptor typed = as.getType();
1121 if( typed != null ) {
1122 ClassDescriptor cd = typed.getClassDesc();
1123 if( cd != null && cd.hasFlags() ) {
1129 // enqueue callees of this method to be searched for
1130 // allocation sites also
1131 Set callees = callGraph.getCalleeSet(d);
1132 if( callees != null ) {
1133 Iterator methItr = callees.iterator();
1134 while( methItr.hasNext() ) {
1135 MethodDescriptor md = (MethodDescriptor) methItr.next();
1137 if( !visited.contains(md) ) {
1149 private LinkedList<MethodContext> topologicalSort( HashSet<MethodContext> set ) {
1150 HashSet <MethodContext> discovered = new HashSet <MethodContext>();
1151 LinkedList<MethodContext> sorted = new LinkedList<MethodContext>();
1153 Iterator<MethodContext> itr = set.iterator();
1154 while( itr.hasNext() ) {
1155 MethodContext mc = itr.next();
1157 if( !discovered.contains( mc ) ) {
1158 dfsVisit( set, mc, sorted, discovered );
1165 private void dfsVisit( HashSet<MethodContext> set,
1167 LinkedList<MethodContext> sorted,
1168 HashSet <MethodContext> discovered ) {
1169 discovered.add( mc );
1171 Descriptor d = mc.getDescriptor();
1172 if( d instanceof MethodDescriptor ) {
1173 MethodDescriptor md = (MethodDescriptor) d;
1174 Iterator itr = callGraph.getCallerSet( md ).iterator();
1175 while( itr.hasNext() ) {
1176 Descriptor dCaller = (Descriptor) itr.next();
1178 // only consider the callers in the original set to analyze
1179 Set<MethodContext> callerContexts = mapDescriptorToAllMethodContexts.get( dCaller );
1180 if( callerContexts == null )
1183 // since the analysis hasn't started, there should be exactly one
1184 // context if there are any at all
1185 assert callerContexts.size() == 1;
1186 MethodContext mcCaller = callerContexts.iterator().next();
1187 assert set.contains( mcCaller );
1189 if( !discovered.contains( mcCaller ) ) {
1190 dfsVisit( set, mcCaller, sorted, discovered );
1195 sorted.addFirst( mc );
1200 private String computeAliasContextHistogram() {
1202 Hashtable<Integer, Integer> mapNumContexts2NumDesc =
1203 new Hashtable<Integer, Integer>();
1205 Iterator itr = mapDescriptorToAllMethodContexts.entrySet().iterator();
1206 while( itr.hasNext() ) {
1207 Map.Entry me = (Map.Entry) itr.next();
1208 HashSet<MethodContext> s = (HashSet<MethodContext>) me.getValue();
1210 Integer i = mapNumContexts2NumDesc.get( s.size() );
1212 i = new Integer( 0 );
1214 mapNumContexts2NumDesc.put( s.size(), i + 1 );
1220 itr = mapNumContexts2NumDesc.entrySet().iterator();
1221 while( itr.hasNext() ) {
1222 Map.Entry me = (Map.Entry) itr.next();
1223 Integer c0 = (Integer) me.getKey();
1224 Integer d0 = (Integer) me.getValue();
1226 s += String.format( "%4d methods had %4d unique alias contexts.\n", d0, c0 );
1229 s += String.format( "\n%4d total methods analayzed.\n", total );
1236 // insert a call to debugSnapshot() somewhere in the analysis
1237 // to get successive captures of the analysis state
1238 boolean takeDebugSnapshots = false;
1239 String mcDescSymbolDebug = "setFlightPlan";
1240 boolean stopAfterCapture = true;
1242 // increments every visit to debugSnapshot, don't fiddle with it
1243 int debugCounter = 0;
1245 // the value of debugCounter to start reporting the debugCounter
1246 // to the screen to let user know what debug iteration we're at
1247 int numStartCountReport = 0;
1249 // the frequency of debugCounter values to print out, 0 no report
1250 int freqCountReport = 0;
1252 // the debugCounter value at which to start taking snapshots
1253 int iterStartCapture = 0;
1255 // the number of snapshots to take
1256 int numIterToCapture = 10;
1258 void debugSnapshot(OwnershipGraph og, FlatNode fn) {
1259 if( debugCounter > iterStartCapture + numIterToCapture ) {
1264 if( debugCounter > numStartCountReport &&
1265 freqCountReport > 0 &&
1266 debugCounter % freqCountReport == 0 ) {
1267 System.out.println(" @@@ debug counter = "+debugCounter);
1269 if( debugCounter > iterStartCapture ) {
1270 System.out.println(" @@@ capturing debug "+(debugCounter-iterStartCapture)+" @@@");
1271 String graphName = String.format("snap%04d",debugCounter-iterStartCapture);
1273 graphName = graphName+fn;
1276 og.writeGraph(graphName, true, true, true, false, false);
1277 } catch( Exception e ) {
1278 System.out.println("Error writing debug capture.");
1283 if( debugCounter == iterStartCapture + numIterToCapture && stopAfterCapture ) {
1284 System.out.println("Stopping analysis after debug captures.");