1 package Analysis.Disjoint;
3 import Analysis.CallGraph.*;
4 import Analysis.Liveness;
5 import Analysis.ArrayReferencees;
8 import IR.Tree.Modifiers;
13 public class DisjointAnalysis {
15 ///////////////////////////////////////////
17 // Public interface to discover possible
18 // aliases in the program under analysis
20 ///////////////////////////////////////////
22 public HashSet<AllocSite>
23 getFlaggedAllocationSitesReachableFromTask(TaskDescriptor td) {
24 checkAnalysisComplete();
25 return getFlaggedAllocationSitesReachableFromTaskPRIVATE(td);
28 public AllocSite getAllocationSiteFromFlatNew(FlatNew fn) {
29 checkAnalysisComplete();
30 return getAllocSiteFromFlatNewPRIVATE(fn);
33 public AllocSite getAllocationSiteFromHeapRegionNodeID(Integer id) {
34 checkAnalysisComplete();
35 return mapHrnIdToAllocSite.get(id);
38 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
41 checkAnalysisComplete();
42 ReachGraph rg=mapDescriptorToCompleteReachGraph.get(taskOrMethod);
43 FlatMethod fm=state.getMethodFlat(taskOrMethod);
45 return rg.mayReachSharedObjects(fm, paramIndex1, paramIndex2);
48 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
49 int paramIndex, AllocSite alloc) {
50 checkAnalysisComplete();
51 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
52 FlatMethod fm=state.getMethodFlat(taskOrMethod);
54 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
57 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
58 AllocSite alloc, int paramIndex) {
59 checkAnalysisComplete();
60 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
61 FlatMethod fm=state.getMethodFlat(taskOrMethod);
63 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
66 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
67 AllocSite alloc1, AllocSite alloc2) {
68 checkAnalysisComplete();
69 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
71 return rg.mayReachSharedObjects(alloc1, alloc2);
74 public String prettyPrintNodeSet(Set<HeapRegionNode> s) {
75 checkAnalysisComplete();
79 Iterator<HeapRegionNode> i = s.iterator();
81 HeapRegionNode n = i.next();
83 AllocSite as = n.getAllocSite();
85 out += " " + n.toString() + ",\n";
87 out += " " + n.toString() + ": " + as.toStringVerbose()
96 // use the methods given above to check every possible alias
97 // between task parameters and flagged allocation sites reachable
99 public void writeAllAliases(String outputFile,
102 boolean tabularOutput,
105 throws java.io.IOException {
106 checkAnalysisComplete();
108 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
110 if (!tabularOutput) {
111 bw.write("Conducting ownership analysis with allocation depth = "
112 + allocationDepth + "\n");
113 bw.write(timeReport + "\n");
118 // look through every task for potential aliases
119 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
120 while (taskItr.hasNext()) {
121 TaskDescriptor td = (TaskDescriptor) taskItr.next();
123 if (!tabularOutput) {
124 bw.write("\n---------" + td + "--------\n");
127 HashSet<AllocSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
129 Set<HeapRegionNode> common;
131 // for each task parameter, check for aliases with
132 // other task parameters and every allocation site
133 // reachable from this task
134 boolean foundSomeAlias = false;
136 FlatMethod fm = state.getMethodFlat(td);
137 for (int i = 0; i < fm.numParameters(); ++i) {
139 // skip parameters with types that cannot reference
141 if( !shouldAnalysisTrack( fm.getParameter( i ).getType() ) ) {
145 // for the ith parameter check for aliases to all
146 // higher numbered parameters
147 for (int j = i + 1; j < fm.numParameters(); ++j) {
149 // skip parameters with types that cannot reference
151 if( !shouldAnalysisTrack( fm.getParameter( j ).getType() ) ) {
156 common = hasPotentialSharing(td, i, j);
157 if (!common.isEmpty()) {
158 foundSomeAlias = true;
159 if (!tabularOutput) {
160 bw.write("Potential alias between parameters " + i
161 + " and " + j + ".\n");
162 bw.write(prettyPrintNodeSet(common) + "\n");
169 // for the ith parameter, check for aliases against
170 // the set of allocation sites reachable from this
172 Iterator allocItr = allocSites.iterator();
173 while (allocItr.hasNext()) {
174 AllocSite as = (AllocSite) allocItr.next();
175 common = hasPotentialSharing(td, i, as);
176 if (!common.isEmpty()) {
177 foundSomeAlias = true;
178 if (!tabularOutput) {
179 bw.write("Potential alias between parameter " + i
180 + " and " + as.getFlatNew() + ".\n");
181 bw.write(prettyPrintNodeSet(common) + "\n");
189 // for each allocation site check for aliases with
190 // other allocation sites in the context of execution
192 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
193 Iterator allocItr1 = allocSites.iterator();
194 while (allocItr1.hasNext()) {
195 AllocSite as1 = (AllocSite) allocItr1.next();
197 Iterator allocItr2 = allocSites.iterator();
198 while (allocItr2.hasNext()) {
199 AllocSite as2 = (AllocSite) allocItr2.next();
201 if (!outerChecked.contains(as2)) {
202 common = hasPotentialSharing(td, as1, as2);
204 if (!common.isEmpty()) {
205 foundSomeAlias = true;
206 if (!tabularOutput) {
207 bw.write("Potential alias between "
208 + as1.getFlatNew() + " and "
209 + as2.getFlatNew() + ".\n");
210 bw.write(prettyPrintNodeSet(common) + "\n");
218 outerChecked.add(as1);
221 if (!foundSomeAlias) {
222 if (!tabularOutput) {
223 bw.write("No aliases between flagged objects in Task " + td
230 if (!tabularOutput) {
231 bw.write("\n" + computeAliasContextHistogram());
233 bw.write(" & " + numAlias + " & " + justTime + " & " + numLines
234 + " & " + numMethodsAnalyzed() + " \\\\\n");
241 // this version of writeAllAliases is for Java programs that have no tasks
242 public void writeAllAliasesJava(String outputFile,
245 boolean tabularOutput,
248 throws java.io.IOException {
249 checkAnalysisComplete();
253 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
255 bw.write("Conducting disjoint reachability analysis with allocation depth = "
256 + allocationDepth + "\n");
257 bw.write(timeReport + "\n\n");
259 boolean foundSomeAlias = false;
261 Descriptor d = typeUtil.getMain();
262 HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
264 // for each allocation site check for aliases with
265 // other allocation sites in the context of execution
267 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
268 Iterator allocItr1 = allocSites.iterator();
269 while (allocItr1.hasNext()) {
270 AllocSite as1 = (AllocSite) allocItr1.next();
272 Iterator allocItr2 = allocSites.iterator();
273 while (allocItr2.hasNext()) {
274 AllocSite as2 = (AllocSite) allocItr2.next();
276 if (!outerChecked.contains(as2)) {
277 Set<HeapRegionNode> common = hasPotentialSharing(d,
280 if (!common.isEmpty()) {
281 foundSomeAlias = true;
282 bw.write("Potential alias between "
283 + as1.getDisjointAnalysisId() + " and "
284 + as2.getDisjointAnalysisId() + ".\n");
285 bw.write(prettyPrintNodeSet(common) + "\n");
290 outerChecked.add(as1);
293 if (!foundSomeAlias) {
294 bw.write("No aliases between flagged objects found.\n");
297 // bw.write("\n" + computeAliasContextHistogram());
301 ///////////////////////////////////////////
303 // end public interface
305 ///////////////////////////////////////////
307 protected void checkAnalysisComplete() {
308 if( !analysisComplete ) {
309 throw new Error("Warning: public interface method called while analysis is running.");
314 // data from the compiler
316 public CallGraph callGraph;
317 public Liveness liveness;
318 public ArrayReferencees arrayReferencees;
319 public TypeUtil typeUtil;
320 public int allocationDepth;
322 // data structure for public interface
323 private Hashtable<Descriptor, HashSet<AllocSite> > mapDescriptorToAllocSiteSet;
326 // for public interface methods to warn that they
327 // are grabbing results during analysis
328 private boolean analysisComplete;
331 // used to identify HeapRegionNode objects
332 // A unique ID equates an object in one
333 // ownership graph with an object in another
334 // graph that logically represents the same
336 // start at 10 and increment to reserve some
337 // IDs for special purposes
338 static protected int uniqueIDcount = 10;
341 // An out-of-scope method created by the
342 // analysis that has no parameters, and
343 // appears to allocate the command line
344 // arguments, then invoke the source code's
345 // main method. The purpose of this is to
346 // provide the analysis with an explicit
347 // top-level context with no parameters
348 protected MethodDescriptor mdAnalysisEntry;
349 protected FlatMethod fmAnalysisEntry;
351 // main method defined by source program
352 protected MethodDescriptor mdSourceEntry;
354 // the set of task and/or method descriptors
355 // reachable in call graph
356 protected Set<Descriptor>
357 descriptorsToAnalyze;
359 // current descriptors to visit in fixed-point
360 // interprocedural analysis, prioritized by
361 // dependency in the call graph
362 protected PriorityQueue<DescriptorQWrapper>
365 // a duplication of the above structure, but
366 // for efficient testing of inclusion
367 protected HashSet<Descriptor>
368 descriptorsToVisitSet;
370 // storage for priorities (doesn't make sense)
371 // to add it to the Descriptor class, just in
373 protected Hashtable<Descriptor, Integer>
374 mapDescriptorToPriority;
377 // maps a descriptor to its current partial result
378 // from the intraprocedural fixed-point analysis--
379 // then the interprocedural analysis settles, this
380 // mapping will have the final results for each
382 protected Hashtable<Descriptor, ReachGraph>
383 mapDescriptorToCompleteReachGraph;
385 // maps a descriptor to its known dependents: namely
386 // methods or tasks that call the descriptor's method
387 // AND are part of this analysis (reachable from main)
388 protected Hashtable< Descriptor, Set<Descriptor> >
389 mapDescriptorToSetDependents;
391 // maps each flat new to one analysis abstraction
392 // allocate site object, these exist outside reach graphs
393 protected Hashtable<FlatNew, AllocSite>
394 mapFlatNewToAllocSite;
396 // maps intergraph heap region IDs to intergraph
397 // allocation sites that created them, a redundant
398 // structure for efficiency in some operations
399 protected Hashtable<Integer, AllocSite>
402 // maps a method to its initial heap model (IHM) that
403 // is the set of reachability graphs from every caller
404 // site, all merged together. The reason that we keep
405 // them separate is that any one call site's contribution
406 // to the IHM may changed along the path to the fixed point
407 protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
408 mapDescriptorToIHMcontributions;
410 // TODO -- CHANGE EDGE/TYPE/FIELD storage!
411 public static final String arrayElementFieldName = "___element_";
412 static protected Hashtable<TypeDescriptor, FieldDescriptor>
415 // for controlling DOT file output
416 protected boolean writeFinalDOTs;
417 protected boolean writeAllIncrementalDOTs;
419 // supporting DOT output--when we want to write every
420 // partial method result, keep a tally for generating
422 protected Hashtable<Descriptor, Integer>
423 mapDescriptorToNumUpdates;
425 //map task descriptor to initial task parameter
426 protected Hashtable<Descriptor, ReachGraph>
427 mapDescriptorToReachGraph;
430 // allocate various structures that are not local
431 // to a single class method--should be done once
432 protected void allocateStructures() {
433 descriptorsToAnalyze = new HashSet<Descriptor>();
435 mapDescriptorToCompleteReachGraph =
436 new Hashtable<Descriptor, ReachGraph>();
438 mapDescriptorToNumUpdates =
439 new Hashtable<Descriptor, Integer>();
441 mapDescriptorToSetDependents =
442 new Hashtable< Descriptor, Set<Descriptor> >();
444 mapFlatNewToAllocSite =
445 new Hashtable<FlatNew, AllocSite>();
447 mapDescriptorToIHMcontributions =
448 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
450 mapHrnIdToAllocSite =
451 new Hashtable<Integer, AllocSite>();
453 mapTypeToArrayField =
454 new Hashtable <TypeDescriptor, FieldDescriptor>();
456 descriptorsToVisitQ =
457 new PriorityQueue<DescriptorQWrapper>();
459 descriptorsToVisitSet =
460 new HashSet<Descriptor>();
462 mapDescriptorToPriority =
463 new Hashtable<Descriptor, Integer>();
465 mapDescriptorToAllocSiteSet =
466 new Hashtable<Descriptor, HashSet<AllocSite> >();
468 mapDescriptorToReachGraph =
469 new Hashtable<Descriptor, ReachGraph>();
474 // this analysis generates a disjoint reachability
475 // graph for every reachable method in the program
476 public DisjointAnalysis( State s,
481 ) throws java.io.IOException {
482 init( s, tu, cg, l, ar );
485 protected void init( State state,
489 ArrayReferencees arrayReferencees
490 ) throws java.io.IOException {
492 analysisComplete = false;
495 this.typeUtil = typeUtil;
496 this.callGraph = callGraph;
497 this.liveness = liveness;
498 this.arrayReferencees = arrayReferencees;
499 this.allocationDepth = state.DISJOINTALLOCDEPTH;
500 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
501 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL;
503 // set some static configuration for ReachGraphs
504 ReachGraph.allocationDepth = allocationDepth;
505 ReachGraph.typeUtil = typeUtil;
507 allocateStructures();
509 double timeStartAnalysis = (double) System.nanoTime();
511 // start interprocedural fixed-point computation
513 analysisComplete=true;
515 double timeEndAnalysis = (double) System.nanoTime();
516 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
517 String treport = String.format( "The reachability analysis took %.3f sec.", dt );
518 String justtime = String.format( "%.2f", dt );
519 System.out.println( treport );
521 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
525 if( state.DISJOINTWRITEIHMS ) {
529 if( state.DISJOINTALIASFILE != null ) {
531 writeAllAliases(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
534 writeAllAliasesJava( aliasFile,
537 state.DISJOINTALIASTAB,
545 // fixed-point computation over the call graph--when a
546 // method's callees are updated, it must be reanalyzed
547 protected void analyzeMethods() throws java.io.IOException {
550 // This analysis does not support Bamboo at the moment,
551 // but if it does in the future we would initialize the
552 // set of descriptors to analyze as the program-reachable
553 // tasks and the methods callable by them. For Java,
554 // just methods reachable from the main method.
555 System.out.println( "Bamboo..." );
556 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
558 while (taskItr.hasNext()) {
559 TaskDescriptor td = (TaskDescriptor) taskItr.next();
560 if (!descriptorsToAnalyze.contains(td)) {
561 descriptorsToAnalyze.add(td);
562 descriptorsToAnalyze.addAll(callGraph.getAllMethods(td));
567 // add all methods transitively reachable from the
568 // source's main to set for analysis
569 mdSourceEntry = typeUtil.getMain();
570 descriptorsToAnalyze.add( mdSourceEntry );
571 descriptorsToAnalyze.addAll(
572 callGraph.getAllMethods( mdSourceEntry )
575 // fabricate an empty calling context that will call
576 // the source's main, but call graph doesn't know
577 // about it, so explicitly add it
578 makeAnalysisEntryMethod( mdSourceEntry );
579 descriptorsToAnalyze.add( mdAnalysisEntry );
582 // topologically sort according to the call graph so
583 // leaf calls are ordered first, smarter analysis order
584 // CHANGED: order leaf calls last!!
585 LinkedList<Descriptor> sortedDescriptors =
586 topologicalSort( descriptorsToAnalyze );
588 // add sorted descriptors to priority queue, and duplicate
589 // the queue as a set for efficiently testing whether some
590 // method is marked for analysis
592 Iterator<Descriptor> dItr = sortedDescriptors.iterator();
593 while( dItr.hasNext() ) {
594 Descriptor d = dItr.next();
595 mapDescriptorToPriority.put( d, new Integer( p ) );
596 descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
597 descriptorsToVisitSet.add( d );
601 // analyze methods from the priority queue until it is empty
602 while( !descriptorsToVisitQ.isEmpty() ) {
603 Descriptor d = descriptorsToVisitQ.poll().getDescriptor();
604 assert descriptorsToVisitSet.contains( d );
605 descriptorsToVisitSet.remove( d );
607 // because the task or method descriptor just extracted
608 // was in the "to visit" set it either hasn't been analyzed
609 // yet, or some method that it depends on has been
610 // updated. Recompute a complete reachability graph for
611 // this task/method and compare it to any previous result.
612 // If there is a change detected, add any methods/tasks
613 // that depend on this one to the "to visit" set.
615 System.out.println( "Analyzing " + d );
617 ReachGraph rg = analyzeMethod( d );
618 ReachGraph rgPrev = getPartial( d );
620 if( !rg.equals( rgPrev ) ) {
624 if( d.getSymbol().equals( "getInterpolatePatch" ) ) {
625 ReachGraph.dbgEquals = true;
627 ReachGraph.dbgEquals = false;
631 // results for d changed, so enqueue dependents
632 // of d for further analysis
633 Iterator<Descriptor> depsItr = getDependents( d ).iterator();
634 while( depsItr.hasNext() ) {
635 Descriptor dNext = depsItr.next();
642 protected ReachGraph analyzeMethod( Descriptor d )
643 throws java.io.IOException {
645 // get the flat code for this descriptor
647 if( d == mdAnalysisEntry ) {
648 fm = fmAnalysisEntry;
650 fm = state.getMethodFlat( d );
653 // intraprocedural work set
654 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
655 flatNodesToVisit.add( fm );
657 // mapping of current partial results
658 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
659 new Hashtable<FlatNode, ReachGraph>();
661 // the set of return nodes partial results that will be combined as
662 // the final, conservative approximation of the entire method
663 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
665 while( !flatNodesToVisit.isEmpty() ) {
666 FlatNode fn = (FlatNode) flatNodesToVisit.iterator().next();
667 flatNodesToVisit.remove( fn );
669 //System.out.println( " "+fn );
671 // effect transfer function defined by this node,
672 // then compare it to the old graph at this node
673 // to see if anything was updated.
675 ReachGraph rg = new ReachGraph();
676 TaskDescriptor taskDesc;
677 if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null){
678 if(mapDescriptorToReachGraph.containsKey(taskDesc)){
679 // retrieve existing reach graph if it is not first time
680 rg=mapDescriptorToReachGraph.get(taskDesc);
682 // create initial reach graph for a task
683 rg=createInitialTaskReachGraph((FlatMethod)fn);
685 mapDescriptorToReachGraph.put(taskDesc, rg);
689 // start by merging all node's parents' graphs
690 for( int i = 0; i < fn.numPrev(); ++i ) {
691 FlatNode pn = fn.getPrev( i );
692 if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
693 ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
694 // System.out.println("parent="+pn+"->"+rgParent);
695 rg.merge( rgParent );
700 if( takeDebugSnapshots &&
701 d.getSymbol().equals( descSymbolDebug )
703 debugSnapshot( rg, fn, true );
707 // modify rg with appropriate transfer function
708 rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
711 if( takeDebugSnapshots &&
712 d.getSymbol().equals( descSymbolDebug )
714 debugSnapshot( rg, fn, false );
718 // if the results of the new graph are different from
719 // the current graph at this node, replace the graph
720 // with the update and enqueue the children
721 ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
722 if( !rg.equals( rgPrev ) ) {
723 mapFlatNodeToReachGraph.put( fn, rg );
725 for( int i = 0; i < fn.numNext(); i++ ) {
726 FlatNode nn = fn.getNext( i );
727 flatNodesToVisit.add( nn );
732 // end by merging all return nodes into a complete
733 // ownership graph that represents all possible heap
734 // states after the flat method returns
735 ReachGraph completeGraph = new ReachGraph();
737 assert !setReturns.isEmpty();
738 Iterator retItr = setReturns.iterator();
739 while( retItr.hasNext() ) {
740 FlatReturnNode frn = (FlatReturnNode) retItr.next();
742 assert mapFlatNodeToReachGraph.containsKey( frn );
743 ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
745 completeGraph.merge( rgRet );
747 return completeGraph;
752 analyzeFlatNode( Descriptor d,
753 FlatMethod fmContaining,
755 HashSet<FlatReturnNode> setRetNodes,
757 ) throws java.io.IOException {
760 // any variables that are no longer live should be
761 // nullified in the graph to reduce edges
762 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
769 // use node type to decide what transfer function
770 // to apply to the reachability graph
771 switch( fn.kind() ) {
773 case FKind.FlatMethod: {
774 // construct this method's initial heap model (IHM)
775 // since we're working on the FlatMethod, we know
776 // the incoming ReachGraph 'rg' is empty
778 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
779 getIHMcontributions( d );
781 Set entrySet = heapsFromCallers.entrySet();
782 Iterator itr = entrySet.iterator();
783 while( itr.hasNext() ) {
784 Map.Entry me = (Map.Entry) itr.next();
785 FlatCall fc = (FlatCall) me.getKey();
786 ReachGraph rgContrib = (ReachGraph) me.getValue();
788 assert fc.getMethod().equals( d );
790 // some call sites are in same method context though,
791 // and all of them should be merged together first,
792 // then heaps from different contexts should be merged
793 // THIS ASSUMES DIFFERENT CONTEXTS NEED SPECIAL CONSIDERATION!
794 // such as, do allocation sites need to be aged?
796 rg.merge_diffMethodContext( rgContrib );
800 case FKind.FlatOpNode:
801 FlatOpNode fon = (FlatOpNode) fn;
802 if( fon.getOp().getOp() == Operation.ASSIGN ) {
805 rg.assignTempXEqualToTempY( lhs, rhs );
809 case FKind.FlatCastNode:
810 FlatCastNode fcn = (FlatCastNode) fn;
814 TypeDescriptor td = fcn.getType();
817 rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
820 case FKind.FlatFieldNode:
821 FlatFieldNode ffn = (FlatFieldNode) fn;
824 fld = ffn.getField();
825 if( shouldAnalysisTrack( fld.getType() ) ) {
826 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld );
830 case FKind.FlatSetFieldNode:
831 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
833 fld = fsfn.getField();
835 if( shouldAnalysisTrack( fld.getType() ) ) {
836 rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs );
840 case FKind.FlatElementNode:
841 FlatElementNode fen = (FlatElementNode) fn;
844 if( shouldAnalysisTrack( lhs.getType() ) ) {
846 assert rhs.getType() != null;
847 assert rhs.getType().isArray();
849 TypeDescriptor tdElement = rhs.getType().dereference();
850 FieldDescriptor fdElement = getArrayField( tdElement );
852 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement );
856 case FKind.FlatSetElementNode:
857 FlatSetElementNode fsen = (FlatSetElementNode) fn;
859 if( arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
860 // skip this node if it cannot create new reachability paths
866 if( shouldAnalysisTrack( rhs.getType() ) ) {
868 assert lhs.getType() != null;
869 assert lhs.getType().isArray();
871 TypeDescriptor tdElement = lhs.getType().dereference();
872 FieldDescriptor fdElement = getArrayField( tdElement );
874 rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs );
879 FlatNew fnn = (FlatNew) fn;
881 if( shouldAnalysisTrack( lhs.getType() ) ) {
882 AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );
883 rg.assignTempEqualToNewAlloc( lhs, as );
887 case FKind.FlatCall: {
888 //TODO: temporal fix for task descriptor case
889 //MethodDescriptor mdCaller = fmContaining.getMethod();
891 if(fmContaining.getMethod()!=null){
892 mdCaller = fmContaining.getMethod();
894 mdCaller = fmContaining.getTask();
896 FlatCall fc = (FlatCall) fn;
897 MethodDescriptor mdCallee = fc.getMethod();
898 FlatMethod fmCallee = state.getMethodFlat( mdCallee );
900 boolean writeDebugDOTs =
901 mdCaller.getSymbol().equals( state.DISJOINTDEBUGCALLER ) &&
902 mdCallee.getSymbol().equals( state.DISJOINTDEBUGCALLEE );
905 // calculate the heap this call site can reach--note this is
906 // not used for the current call site transform, we are
907 // grabbing this heap model for future analysis of the callees,
908 // so if different results emerge we will return to this site
909 ReachGraph heapForThisCall_old =
910 getIHMcontribution( mdCallee, fc );
912 // the computation of the callee-reachable heap
913 // is useful for making the callee starting point
914 // and for applying the call site transfer function
915 Set<Integer> callerNodeIDsCopiedToCallee =
916 new HashSet<Integer>();
918 ReachGraph heapForThisCall_cur =
919 rg.makeCalleeView( fc,
921 callerNodeIDsCopiedToCallee,
925 if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {
926 // if heap at call site changed, update the contribution,
927 // and reschedule the callee for analysis
928 addIHMcontribution( mdCallee, fc, heapForThisCall_cur );
935 // the transformation for a call site should update the
936 // current heap abstraction with any effects from the callee,
937 // or if the method is virtual, the effects from any possible
938 // callees, so find the set of callees...
939 Set<MethodDescriptor> setPossibleCallees =
940 new HashSet<MethodDescriptor>();
942 if( mdCallee.isStatic() ) {
943 setPossibleCallees.add( mdCallee );
945 TypeDescriptor typeDesc = fc.getThis().getType();
946 setPossibleCallees.addAll( callGraph.getMethods( mdCallee,
951 ReachGraph rgMergeOfEffects = new ReachGraph();
953 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
954 while( mdItr.hasNext() ) {
955 MethodDescriptor mdPossible = mdItr.next();
956 FlatMethod fmPossible = state.getMethodFlat( mdPossible );
958 addDependent( mdPossible, // callee
961 // don't alter the working graph (rg) until we compute a
962 // result for every possible callee, merge them all together,
963 // then set rg to that
964 ReachGraph rgCopy = new ReachGraph();
967 ReachGraph rgEffect = getPartial( mdPossible );
969 if( rgEffect == null ) {
970 // if this method has never been analyzed just schedule it
971 // for analysis and skip over this call site for now
972 enqueue( mdPossible );
974 rgCopy.resolveMethodCall( fc,
977 callerNodeIDsCopiedToCallee,
982 rgMergeOfEffects.merge( rgCopy );
986 // now that we've taken care of building heap models for
987 // callee analysis, finish this transformation
988 rg = rgMergeOfEffects;
992 case FKind.FlatReturnNode:
993 FlatReturnNode frn = (FlatReturnNode) fn;
994 rhs = frn.getReturnTemp();
995 if( rhs != null && shouldAnalysisTrack( rhs.getType() ) ) {
996 rg.assignReturnEqualToTemp( rhs );
998 setRetNodes.add( frn );
1004 // dead variables were removed before the above transfer function
1005 // was applied, so eliminate heap regions and edges that are no
1006 // longer part of the abstractly-live heap graph, and sweep up
1007 // and reachability effects that are altered by the reduction
1008 //rg.abstractGarbageCollect();
1012 // at this point rg should be the correct update
1013 // by an above transfer function, or untouched if
1014 // the flat node type doesn't affect the heap
1019 // this method should generate integers strictly greater than zero!
1020 // special "shadow" regions are made from a heap region by negating
1022 static public Integer generateUniqueHeapRegionNodeID() {
1024 return new Integer( uniqueIDcount );
1029 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
1030 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
1031 if( fdElement == null ) {
1032 fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
1034 arrayElementFieldName,
1037 mapTypeToArrayField.put( tdElement, fdElement );
1044 private void writeFinalGraphs() {
1045 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1046 Iterator itr = entrySet.iterator();
1047 while( itr.hasNext() ) {
1048 Map.Entry me = (Map.Entry) itr.next();
1049 Descriptor d = (Descriptor) me.getKey();
1050 ReachGraph rg = (ReachGraph) me.getValue();
1052 rg.writeGraph( "COMPLETE"+d,
1053 true, // write labels (variables)
1054 true, // selectively hide intermediate temp vars
1055 true, // prune unreachable heap regions
1056 false, // hide subset reachability states
1057 true ); // hide edge taints
1061 private void writeFinalIHMs() {
1062 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1063 while( d2IHMsItr.hasNext() ) {
1064 Map.Entry me1 = (Map.Entry) d2IHMsItr.next();
1065 Descriptor d = (Descriptor) me1.getKey();
1066 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1068 Iterator fc2rgItr = IHMs.entrySet().iterator();
1069 while( fc2rgItr.hasNext() ) {
1070 Map.Entry me2 = (Map.Entry) fc2rgItr.next();
1071 FlatCall fc = (FlatCall) me2.getKey();
1072 ReachGraph rg = (ReachGraph) me2.getValue();
1074 rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc,
1075 true, // write labels (variables)
1076 false, // selectively hide intermediate temp vars
1077 false, // prune unreachable heap regions
1078 false, // hide subset reachability states
1079 true ); // hide edge taints
1085 protected ReachGraph getPartial( Descriptor d ) {
1086 return mapDescriptorToCompleteReachGraph.get( d );
1089 protected void setPartial( Descriptor d, ReachGraph rg ) {
1090 mapDescriptorToCompleteReachGraph.put( d, rg );
1092 // when the flag for writing out every partial
1093 // result is set, we should spit out the graph,
1094 // but in order to give it a unique name we need
1095 // to track how many partial results for this
1096 // descriptor we've already written out
1097 if( writeAllIncrementalDOTs ) {
1098 if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1099 mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1101 Integer n = mapDescriptorToNumUpdates.get( d );
1103 rg.writeGraph( d+"COMPLETE"+String.format( "%05d", n ),
1104 true, // write labels (variables)
1105 true, // selectively hide intermediate temp vars
1106 true, // prune unreachable heap regions
1107 false, // hide subset reachability states
1108 true ); // hide edge taints
1110 mapDescriptorToNumUpdates.put( d, n + 1 );
1116 // return just the allocation site associated with one FlatNew node
1117 protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1119 if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1121 (AllocSite) Canonical.makeCanonical( new AllocSite( allocationDepth,
1123 fnew.getDisjointId()
1127 // the newest nodes are single objects
1128 for( int i = 0; i < allocationDepth; ++i ) {
1129 Integer id = generateUniqueHeapRegionNodeID();
1130 as.setIthOldest( i, id );
1131 mapHrnIdToAllocSite.put( id, as );
1134 // the oldest node is a summary node
1135 as.setSummary( generateUniqueHeapRegionNodeID() );
1137 mapFlatNewToAllocSite.put( fnew, as );
1140 return mapFlatNewToAllocSite.get( fnew );
1144 public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1145 // don't track primitive types, but an array
1146 // of primitives is heap memory
1147 if( type.isImmutable() ) {
1148 return type.isArray();
1151 // everything else is an object
1157 // return all allocation sites in the method (there is one allocation
1158 // site per FlatNew node in a method)
1159 protected HashSet<AllocSite> getAllocSiteSet(Descriptor d) {
1160 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
1161 buildAllocSiteSet(d);
1164 return mapDescriptorToAllocSiteSet.get(d);
1170 protected void buildAllocSiteSet(Descriptor d) {
1171 HashSet<AllocSite> s = new HashSet<AllocSite>();
1173 FlatMethod fm = state.getMethodFlat( d );
1175 // visit every node in this FlatMethod's IR graph
1176 // and make a set of the allocation sites from the
1177 // FlatNew node's visited
1178 HashSet<FlatNode> visited = new HashSet<FlatNode>();
1179 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
1182 while( !toVisit.isEmpty() ) {
1183 FlatNode n = toVisit.iterator().next();
1185 if( n instanceof FlatNew ) {
1186 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
1189 toVisit.remove( n );
1192 for( int i = 0; i < n.numNext(); ++i ) {
1193 FlatNode child = n.getNext( i );
1194 if( !visited.contains( child ) ) {
1195 toVisit.add( child );
1200 mapDescriptorToAllocSiteSet.put( d, s );
1204 protected HashSet<AllocSite> getFlaggedAllocSites(Descriptor dIn) {
1206 HashSet<AllocSite> out = new HashSet<AllocSite>();
1207 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1208 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1212 while( !toVisit.isEmpty() ) {
1213 Descriptor d = toVisit.iterator().next();
1217 HashSet<AllocSite> asSet = getAllocSiteSet(d);
1218 Iterator asItr = asSet.iterator();
1219 while( asItr.hasNext() ) {
1220 AllocSite as = (AllocSite) asItr.next();
1221 if( as.getDisjointAnalysisId() != null ) {
1226 // enqueue callees of this method to be searched for
1227 // allocation sites also
1228 Set callees = callGraph.getCalleeSet(d);
1229 if( callees != null ) {
1230 Iterator methItr = callees.iterator();
1231 while( methItr.hasNext() ) {
1232 MethodDescriptor md = (MethodDescriptor) methItr.next();
1234 if( !visited.contains(md) ) {
1246 protected HashSet<AllocSite>
1247 getFlaggedAllocSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
1249 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
1250 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1251 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1255 // traverse this task and all methods reachable from this task
1256 while( !toVisit.isEmpty() ) {
1257 Descriptor d = toVisit.iterator().next();
1261 HashSet<AllocSite> asSet = getAllocSiteSet(d);
1262 Iterator asItr = asSet.iterator();
1263 while( asItr.hasNext() ) {
1264 AllocSite as = (AllocSite) asItr.next();
1265 TypeDescriptor typed = as.getType();
1266 if( typed != null ) {
1267 ClassDescriptor cd = typed.getClassDesc();
1268 if( cd != null && cd.hasFlags() ) {
1274 // enqueue callees of this method to be searched for
1275 // allocation sites also
1276 Set callees = callGraph.getCalleeSet(d);
1277 if( callees != null ) {
1278 Iterator methItr = callees.iterator();
1279 while( methItr.hasNext() ) {
1280 MethodDescriptor md = (MethodDescriptor) methItr.next();
1282 if( !visited.contains(md) ) {
1296 protected String computeAliasContextHistogram() {
1298 Hashtable<Integer, Integer> mapNumContexts2NumDesc =
1299 new Hashtable<Integer, Integer>();
1301 Iterator itr = mapDescriptorToAllDescriptors.entrySet().iterator();
1302 while( itr.hasNext() ) {
1303 Map.Entry me = (Map.Entry) itr.next();
1304 HashSet<Descriptor> s = (HashSet<Descriptor>) me.getValue();
1306 Integer i = mapNumContexts2NumDesc.get( s.size() );
1308 i = new Integer( 0 );
1310 mapNumContexts2NumDesc.put( s.size(), i + 1 );
1316 itr = mapNumContexts2NumDesc.entrySet().iterator();
1317 while( itr.hasNext() ) {
1318 Map.Entry me = (Map.Entry) itr.next();
1319 Integer c0 = (Integer) me.getKey();
1320 Integer d0 = (Integer) me.getValue();
1322 s += String.format( "%4d methods had %4d unique alias contexts.\n", d0, c0 );
1325 s += String.format( "\n%4d total methods analayzed.\n", total );
1330 protected int numMethodsAnalyzed() {
1331 return descriptorsToAnalyze.size();
1338 // Take in source entry which is the program's compiled entry and
1339 // create a new analysis entry, a method that takes no parameters
1340 // and appears to allocate the command line arguments and call the
1341 // source entry with them. The purpose of this analysis entry is
1342 // to provide a top-level method context with no parameters left.
1343 protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1345 Modifiers mods = new Modifiers();
1346 mods.addModifier( Modifiers.PUBLIC );
1347 mods.addModifier( Modifiers.STATIC );
1349 TypeDescriptor returnType =
1350 new TypeDescriptor( TypeDescriptor.VOID );
1352 this.mdAnalysisEntry =
1353 new MethodDescriptor( mods,
1355 "analysisEntryMethod"
1358 TempDescriptor cmdLineArgs =
1359 new TempDescriptor( "args",
1360 mdSourceEntry.getParamType( 0 )
1364 new FlatNew( mdSourceEntry.getParamType( 0 ),
1369 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1370 sourceEntryArgs[0] = cmdLineArgs;
1373 new FlatCall( mdSourceEntry,
1379 FlatReturnNode frn = new FlatReturnNode( null );
1381 FlatExit fe = new FlatExit();
1383 this.fmAnalysisEntry =
1384 new FlatMethod( mdAnalysisEntry,
1388 this.fmAnalysisEntry.addNext( fn );
1395 protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1397 Set <Descriptor> discovered = new HashSet <Descriptor>();
1398 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
1400 Iterator<Descriptor> itr = toSort.iterator();
1401 while( itr.hasNext() ) {
1402 Descriptor d = itr.next();
1404 if( !discovered.contains( d ) ) {
1405 dfsVisit( d, toSort, sorted, discovered );
1412 // While we're doing DFS on call graph, remember
1413 // dependencies for efficient queuing of methods
1414 // during interprocedural analysis:
1416 // a dependent of a method decriptor d for this analysis is:
1417 // 1) a method or task that invokes d
1418 // 2) in the descriptorsToAnalyze set
1419 protected void dfsVisit( Descriptor d,
1420 Set <Descriptor> toSort,
1421 LinkedList<Descriptor> sorted,
1422 Set <Descriptor> discovered ) {
1423 discovered.add( d );
1425 // only methods have callers, tasks never do
1426 if( d instanceof MethodDescriptor ) {
1428 MethodDescriptor md = (MethodDescriptor) d;
1430 // the call graph is not aware that we have a fabricated
1431 // analysis entry that calls the program source's entry
1432 if( md == mdSourceEntry ) {
1433 if( !discovered.contains( mdAnalysisEntry ) ) {
1434 addDependent( mdSourceEntry, // callee
1435 mdAnalysisEntry // caller
1437 dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1441 // otherwise call graph guides DFS
1442 Iterator itr = callGraph.getCallerSet( md ).iterator();
1443 while( itr.hasNext() ) {
1444 Descriptor dCaller = (Descriptor) itr.next();
1446 // only consider callers in the original set to analyze
1447 if( !toSort.contains( dCaller ) ) {
1451 if( !discovered.contains( dCaller ) ) {
1452 addDependent( md, // callee
1456 dfsVisit( dCaller, toSort, sorted, discovered );
1461 // for leaf-nodes last now!
1462 sorted.addLast( d );
1466 protected void enqueue( Descriptor d ) {
1467 if( !descriptorsToVisitSet.contains( d ) ) {
1468 Integer priority = mapDescriptorToPriority.get( d );
1469 descriptorsToVisitQ.add( new DescriptorQWrapper( priority,
1472 descriptorsToVisitSet.add( d );
1477 // a dependent of a method decriptor d for this analysis is:
1478 // 1) a method or task that invokes d
1479 // 2) in the descriptorsToAnalyze set
1480 protected void addDependent( Descriptor callee, Descriptor caller ) {
1481 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1482 if( deps == null ) {
1483 deps = new HashSet<Descriptor>();
1486 mapDescriptorToSetDependents.put( callee, deps );
1489 protected Set<Descriptor> getDependents( Descriptor callee ) {
1490 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1491 if( deps == null ) {
1492 deps = new HashSet<Descriptor>();
1493 mapDescriptorToSetDependents.put( callee, deps );
1499 public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
1501 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1502 mapDescriptorToIHMcontributions.get( d );
1504 if( heapsFromCallers == null ) {
1505 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
1506 mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
1509 return heapsFromCallers;
1512 public ReachGraph getIHMcontribution( Descriptor d,
1515 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1516 getIHMcontributions( d );
1518 if( !heapsFromCallers.containsKey( fc ) ) {
1519 heapsFromCallers.put( fc, new ReachGraph() );
1522 return heapsFromCallers.get( fc );
1525 public void addIHMcontribution( Descriptor d,
1529 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1530 getIHMcontributions( d );
1532 heapsFromCallers.put( fc, rg );
1535 private AllocSite createParameterAllocSite(ReachGraph rg, TempDescriptor tempDesc) {
1537 // create temp descriptor for each parameter variable
1538 FlatNew flatNew = new FlatNew(tempDesc.getType(), tempDesc, false);
1539 // create allocation site
1540 AllocSite as = (AllocSite) Canonical.makeCanonical(new AllocSite( allocationDepth, flatNew, flatNew.getDisjointId()));
1541 for (int i = 0; i < allocationDepth; ++i) {
1542 Integer id = generateUniqueHeapRegionNodeID();
1543 as.setIthOldest(i, id);
1544 mapHrnIdToAllocSite.put(id, as);
1546 // the oldest node is a summary node
1547 as.setSummary( generateUniqueHeapRegionNodeID() );
1555 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
1556 ReachGraph rg = new ReachGraph();
1557 TaskDescriptor taskDesc = fm.getTask();
1559 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
1560 Descriptor paramDesc = taskDesc.getParameter(idx);
1561 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
1563 // setup data structure
1564 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
1565 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
1566 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
1567 new Hashtable<TypeDescriptor, HeapRegionNode>();
1568 Set<String> doneSet = new HashSet<String>();
1570 TempDescriptor tempDesc = fm.getParameter(idx);
1572 AllocSite as = createParameterAllocSite(rg, tempDesc);
1573 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
1574 Integer idNewest = as.getIthOldest(0);
1575 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
1576 // make a new reference to allocated node
1577 RefEdge edgeNew = new RefEdge(lnX, // source
1579 taskDesc.getParamType(idx), // type
1581 hrnNewest.getAlpha(), // beta
1582 ExistPredSet.factory(rg.predTrue) // predicates
1584 rg.addRefEdge(lnX, hrnNewest, edgeNew);
1586 // set-up a work set for class field
1587 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
1588 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1589 FieldDescriptor fd = (FieldDescriptor) it.next();
1590 TypeDescriptor fieldType = fd.getType();
1591 if (shouldAnalysisTrack( fieldType )) {
1592 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
1593 newMap.put(hrnNewest, fd);
1594 workSet.add(newMap);
1598 int uniqueIdentifier = 0;
1599 while (!workSet.isEmpty()) {
1600 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
1602 workSet.remove(map);
1604 Set<HeapRegionNode> key = map.keySet();
1605 HeapRegionNode srcHRN = key.iterator().next();
1606 FieldDescriptor fd = map.get(srcHRN);
1607 TypeDescriptor type = fd.getType();
1608 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
1610 if (!doneSet.contains(doneSetIdentifier)) {
1611 doneSet.add(doneSetIdentifier);
1612 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
1613 // create new summary Node
1614 TempDescriptor td = new TempDescriptor("temp"
1615 + uniqueIdentifier, type);
1617 AllocSite allocSite;
1618 if(type.equals(paramTypeDesc)){
1619 //corresponding allocsite has already been created for a parameter variable.
1622 allocSite = createParameterAllocSite(rg, td);
1624 String strDesc = allocSite.toStringForDOT()
1626 HeapRegionNode hrnSummary =
1627 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
1628 false, // single object?
1631 false, // out-of-context?
1632 allocSite.getType(), // type
1633 allocSite, // allocation site
1634 null, // inherent reach
1635 srcHRN.getAlpha(), // current reach
1636 ExistPredSet.factory(), // predicates
1637 strDesc // description
1639 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
1641 // make a new reference to summary node
1642 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1644 fd.getType(), // type
1645 fd.getSymbol(), // field name
1646 srcHRN.getAlpha(), // beta
1647 ExistPredSet.factory(rg.predTrue) // predicates
1650 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1654 mapTypeToExistingSummaryNode.put(type, hrnSummary);
1656 // set-up a work set for fields of the class
1657 if(!type.isImmutable()){
1658 classDesc = type.getClassDesc();
1659 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1660 FieldDescriptor typeFieldDesc = (FieldDescriptor) it.next();
1661 TypeDescriptor fieldType = typeFieldDesc.getType();
1662 if (!fieldType.isImmutable()) {
1663 doneSetIdentifier = hrnSummary.getIDString() + "_" + typeFieldDesc;
1664 if(!doneSet.contains(doneSetIdentifier)){
1665 // add new work item
1666 HashMap<HeapRegionNode, FieldDescriptor> newMap =
1667 new HashMap<HeapRegionNode, FieldDescriptor>();
1668 newMap.put(hrnSummary, typeFieldDesc);
1669 workSet.add(newMap);
1676 // if there exists corresponding summary node
1677 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
1679 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1681 fd.getType(), // type
1682 fd.getSymbol(), // field name
1683 srcHRN.getAlpha(), // beta
1684 ExistPredSet.factory(rg.predTrue) // predicates
1686 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
1692 // debugSnapshot(rg, fm, true);
1696 // return all allocation sites in the method (there is one allocation
1697 // site per FlatNew node in a method)
1698 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
1699 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
1700 buildAllocationSiteSet(d);
1703 return mapDescriptorToAllocSiteSet.get(d);
1707 private void buildAllocationSiteSet(Descriptor d) {
1708 HashSet<AllocSite> s = new HashSet<AllocSite>();
1711 if( d instanceof MethodDescriptor ) {
1712 fm = state.getMethodFlat( (MethodDescriptor) d);
1714 assert d instanceof TaskDescriptor;
1715 fm = state.getMethodFlat( (TaskDescriptor) d);
1718 // visit every node in this FlatMethod's IR graph
1719 // and make a set of the allocation sites from the
1720 // FlatNew node's visited
1721 HashSet<FlatNode> visited = new HashSet<FlatNode>();
1722 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
1725 while( !toVisit.isEmpty() ) {
1726 FlatNode n = toVisit.iterator().next();
1728 if( n instanceof FlatNew ) {
1729 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
1735 for( int i = 0; i < n.numNext(); ++i ) {
1736 FlatNode child = n.getNext(i);
1737 if( !visited.contains(child) ) {
1743 mapDescriptorToAllocSiteSet.put(d, s);
1746 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
1748 HashSet<AllocSite> out = new HashSet<AllocSite>();
1749 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1750 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1754 while (!toVisit.isEmpty()) {
1755 Descriptor d = toVisit.iterator().next();
1759 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
1760 Iterator asItr = asSet.iterator();
1761 while (asItr.hasNext()) {
1762 AllocSite as = (AllocSite) asItr.next();
1763 if (as.getDisjointAnalysisId() != null) {
1768 // enqueue callees of this method to be searched for
1769 // allocation sites also
1770 Set callees = callGraph.getCalleeSet(d);
1771 if (callees != null) {
1772 Iterator methItr = callees.iterator();
1773 while (methItr.hasNext()) {
1774 MethodDescriptor md = (MethodDescriptor) methItr.next();
1776 if (!visited.contains(md)) {
1787 private HashSet<AllocSite>
1788 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
1790 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
1791 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1792 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1796 // traverse this task and all methods reachable from this task
1797 while( !toVisit.isEmpty() ) {
1798 Descriptor d = toVisit.iterator().next();
1802 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
1803 Iterator asItr = asSet.iterator();
1804 while( asItr.hasNext() ) {
1805 AllocSite as = (AllocSite) asItr.next();
1806 TypeDescriptor typed = as.getType();
1807 if( typed != null ) {
1808 ClassDescriptor cd = typed.getClassDesc();
1809 if( cd != null && cd.hasFlags() ) {
1815 // enqueue callees of this method to be searched for
1816 // allocation sites also
1817 Set callees = callGraph.getCalleeSet(d);
1818 if( callees != null ) {
1819 Iterator methItr = callees.iterator();
1820 while( methItr.hasNext() ) {
1821 MethodDescriptor md = (MethodDescriptor) methItr.next();
1823 if( !visited.contains(md) ) {
1836 // get successive captures of the analysis state
1837 boolean takeDebugSnapshots = true;
1838 String descSymbolDebug = "calcGoodFeature";
1839 boolean stopAfterCapture = false;
1841 // increments every visit to debugSnapshot, don't fiddle with it
1842 int debugCounter = 0;
1844 // the value of debugCounter to start reporting the debugCounter
1845 // to the screen to let user know what debug iteration we're at
1846 int numStartCountReport = 0;
1848 // the frequency of debugCounter values to print out, 0 no report
1849 int freqCountReport = 0;
1851 // the debugCounter value at which to start taking snapshots
1852 int iterStartCapture = 0;
1854 // the number of snapshots to take
1855 int numIterToCapture = 4000;
1858 void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
1859 if( debugCounter > iterStartCapture + numIterToCapture ) {
1867 if( debugCounter > numStartCountReport &&
1868 freqCountReport > 0 &&
1869 debugCounter % freqCountReport == 0 &&
1872 System.out.println( " @@@ debug counter = "+
1876 if( debugCounter > iterStartCapture ) {
1877 System.out.println( " @@@ capturing debug "+
1878 (debugCounter /*- iterStartCapture*/)+
1882 graphName = String.format( "snap%04din",
1883 debugCounter ); //- iterStartCapture );
1885 graphName = String.format( "snap%04dout",
1886 debugCounter ); //- iterStartCapture );
1889 graphName = graphName + fn;
1891 rg.writeGraph( graphName,
1892 true, // write labels (variables)
1893 true, // selectively hide intermediate temp vars
1894 true, // prune unreachable heap regions
1895 false, // hide subset reachability states
1896 true );// hide edge taints
1899 if( debugCounter == iterStartCapture + numIterToCapture &&
1902 System.out.println( "Stopping analysis after debug captures." );