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
231 bw.write(" & " + numAlias + " & " + justTime + " & " + numLines
232 + " & " + numMethodsAnalyzed() + " \\\\\n");
238 // this version of writeAllAliases is for Java programs that have no tasks
239 public void writeAllAliasesJava(String outputFile,
242 boolean tabularOutput,
245 throws java.io.IOException {
246 checkAnalysisComplete();
250 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
252 bw.write("Conducting disjoint reachability analysis with allocation depth = "
253 + allocationDepth + "\n");
254 bw.write(timeReport + "\n\n");
256 boolean foundSomeAlias = false;
258 Descriptor d = typeUtil.getMain();
259 HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
261 // for each allocation site check for aliases with
262 // other allocation sites in the context of execution
264 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
265 Iterator allocItr1 = allocSites.iterator();
266 while (allocItr1.hasNext()) {
267 AllocSite as1 = (AllocSite) allocItr1.next();
269 Iterator allocItr2 = allocSites.iterator();
270 while (allocItr2.hasNext()) {
271 AllocSite as2 = (AllocSite) allocItr2.next();
273 if (!outerChecked.contains(as2)) {
274 Set<HeapRegionNode> common = hasPotentialSharing(d,
277 if (!common.isEmpty()) {
278 foundSomeAlias = true;
279 bw.write("Potential alias between "
280 + as1.getDisjointAnalysisId() + " and "
281 + as2.getDisjointAnalysisId() + ".\n");
282 bw.write(prettyPrintNodeSet(common) + "\n");
287 outerChecked.add(as1);
290 if (!foundSomeAlias) {
291 bw.write("No aliases between flagged objects found.\n");
294 bw.write("Number of methods analyzed: "+numMethodsAnalyzed()+"\n");
299 ///////////////////////////////////////////
301 // end public interface
303 ///////////////////////////////////////////
305 protected void checkAnalysisComplete() {
306 if( !analysisComplete ) {
307 throw new Error("Warning: public interface method called while analysis is running.");
312 // run in faster mode, only when bugs wrung out!
313 public static boolean releaseMode;
315 // data from the compiler
317 public CallGraph callGraph;
318 public Liveness liveness;
319 public ArrayReferencees arrayReferencees;
320 public TypeUtil typeUtil;
321 public int allocationDepth;
323 // data structure for public interface
324 private Hashtable<Descriptor, HashSet<AllocSite> > mapDescriptorToAllocSiteSet;
327 // for public interface methods to warn that they
328 // are grabbing results during analysis
329 private boolean analysisComplete;
332 // used to identify HeapRegionNode objects
333 // A unique ID equates an object in one
334 // ownership graph with an object in another
335 // graph that logically represents the same
337 // start at 10 and increment to reserve some
338 // IDs for special purposes
339 static protected int uniqueIDcount = 10;
342 // An out-of-scope method created by the
343 // analysis that has no parameters, and
344 // appears to allocate the command line
345 // arguments, then invoke the source code's
346 // main method. The purpose of this is to
347 // provide the analysis with an explicit
348 // top-level context with no parameters
349 protected MethodDescriptor mdAnalysisEntry;
350 protected FlatMethod fmAnalysisEntry;
352 // main method defined by source program
353 protected MethodDescriptor mdSourceEntry;
355 // the set of task and/or method descriptors
356 // reachable in call graph
357 protected Set<Descriptor>
358 descriptorsToAnalyze;
360 // current descriptors to visit in fixed-point
361 // interprocedural analysis, prioritized by
362 // dependency in the call graph
363 protected Stack<DescriptorQWrapper>
364 //protected PriorityQueue<DescriptorQWrapper>
367 // a duplication of the above structure, but
368 // for efficient testing of inclusion
369 protected HashSet<Descriptor>
370 descriptorsToVisitSet;
372 // storage for priorities (doesn't make sense)
373 // to add it to the Descriptor class, just in
375 protected Hashtable<Descriptor, Integer>
376 mapDescriptorToPriority;
379 // maps a descriptor to its current partial result
380 // from the intraprocedural fixed-point analysis--
381 // then the interprocedural analysis settles, this
382 // mapping will have the final results for each
384 protected Hashtable<Descriptor, ReachGraph>
385 mapDescriptorToCompleteReachGraph;
387 // maps a descriptor to its known dependents: namely
388 // methods or tasks that call the descriptor's method
389 // AND are part of this analysis (reachable from main)
390 protected Hashtable< Descriptor, Set<Descriptor> >
391 mapDescriptorToSetDependents;
393 // maps each flat new to one analysis abstraction
394 // allocate site object, these exist outside reach graphs
395 protected Hashtable<FlatNew, AllocSite>
396 mapFlatNewToAllocSite;
398 // maps intergraph heap region IDs to intergraph
399 // allocation sites that created them, a redundant
400 // structure for efficiency in some operations
401 protected Hashtable<Integer, AllocSite>
404 // maps a method to its initial heap model (IHM) that
405 // is the set of reachability graphs from every caller
406 // site, all merged together. The reason that we keep
407 // them separate is that any one call site's contribution
408 // to the IHM may changed along the path to the fixed point
409 protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
410 mapDescriptorToIHMcontributions;
412 // TODO -- CHANGE EDGE/TYPE/FIELD storage!
413 public static final String arrayElementFieldName = "___element_";
414 static protected Hashtable<TypeDescriptor, FieldDescriptor>
417 // for controlling DOT file output
418 protected boolean writeFinalDOTs;
419 protected boolean writeAllIncrementalDOTs;
421 // supporting DOT output--when we want to write every
422 // partial method result, keep a tally for generating
424 protected Hashtable<Descriptor, Integer>
425 mapDescriptorToNumUpdates;
427 //map task descriptor to initial task parameter
428 protected Hashtable<Descriptor, ReachGraph>
429 mapDescriptorToReachGraph;
431 protected PointerMethod pm;
433 protected Hashtable<FlatMethod, ReachGraph> hackmap;
436 // allocate various structures that are not local
437 // to a single class method--should be done once
438 protected void allocateStructures() {
439 descriptorsToAnalyze = new HashSet<Descriptor>();
441 mapDescriptorToCompleteReachGraph =
442 new Hashtable<Descriptor, ReachGraph>();
444 mapDescriptorToNumUpdates =
445 new Hashtable<Descriptor, Integer>();
447 mapDescriptorToSetDependents =
448 new Hashtable< Descriptor, Set<Descriptor> >();
450 mapFlatNewToAllocSite =
451 new Hashtable<FlatNew, AllocSite>();
453 mapDescriptorToIHMcontributions =
454 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
456 mapHrnIdToAllocSite =
457 new Hashtable<Integer, AllocSite>();
459 mapTypeToArrayField =
460 new Hashtable <TypeDescriptor, FieldDescriptor>();
462 descriptorsToVisitQ =
463 new Stack<DescriptorQWrapper>();
464 //new PriorityQueue<DescriptorQWrapper>();
466 descriptorsToVisitSet =
467 new HashSet<Descriptor>();
469 mapDescriptorToPriority =
470 new Hashtable<Descriptor, Integer>();
472 mapDescriptorToAllocSiteSet =
473 new Hashtable<Descriptor, HashSet<AllocSite> >();
475 mapDescriptorToReachGraph =
476 new Hashtable<Descriptor, ReachGraph>();
478 hackmap = new Hashtable<FlatMethod, ReachGraph>();
483 // this analysis generates a disjoint reachability
484 // graph for every reachable method in the program
485 public DisjointAnalysis( State s,
490 ) throws java.io.IOException {
491 init( s, tu, cg, l, ar );
494 protected void init( State state,
498 ArrayReferencees arrayReferencees
499 ) throws java.io.IOException {
501 analysisComplete = false;
504 this.typeUtil = typeUtil;
505 this.callGraph = callGraph;
506 this.liveness = liveness;
507 this.arrayReferencees = arrayReferencees;
508 this.allocationDepth = state.DISJOINTALLOCDEPTH;
509 this.releaseMode = state.DISJOINTRELEASEMODE;
511 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
512 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL;
514 this.takeDebugSnapshots = state.DISJOINTSNAPSYMBOL != null;
515 this.descSymbolDebug = state.DISJOINTSNAPSYMBOL;
516 this.visitStartCapture = state.DISJOINTSNAPVISITTOSTART;
517 this.numVisitsToCapture = state.DISJOINTSNAPNUMVISITS;
518 this.stopAfterCapture = state.DISJOINTSNAPSTOPAFTER;
519 this.snapVisitCounter = 1; // count visits from 1 (user will write 1, means 1st visit)
520 this.snapNodeCounter = 0; // count nodes from 0
521 this.pm=new PointerMethod();
524 // set some static configuration for ReachGraphs
525 ReachGraph.allocationDepth = allocationDepth;
526 ReachGraph.typeUtil = typeUtil;
528 ReachGraph.debugCallSiteVisitsUntilExit = state.DISJOINTDEBUGCALLCOUNT;
530 allocateStructures();
532 double timeStartAnalysis = (double) System.nanoTime();
534 // start interprocedural fixed-point computation
536 analysisComplete=true;
538 double timeEndAnalysis = (double) System.nanoTime();
539 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
540 String treport = String.format( "The reachability analysis took %.3f sec.", dt );
541 String justtime = String.format( "%.2f", dt );
542 System.out.println( treport );
544 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
548 if( state.DISJOINTWRITEIHMS ) {
552 if( state.DISJOINTALIASFILE != null ) {
554 writeAllAliases(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
556 writeAllAliasesJava(state.DISJOINTALIASFILE,
559 state.DISJOINTALIASTAB,
567 // fixed-point computation over the call graph--when a
568 // method's callees are updated, it must be reanalyzed
569 protected void analyzeMethods() throws java.io.IOException {
572 // This analysis does not support Bamboo at the moment,
573 // but if it does in the future we would initialize the
574 // set of descriptors to analyze as the program-reachable
575 // tasks and the methods callable by them. For Java,
576 // just methods reachable from the main method.
577 System.out.println( "Bamboo..." );
578 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
580 while (taskItr.hasNext()) {
581 TaskDescriptor td = (TaskDescriptor) taskItr.next();
582 if (!descriptorsToAnalyze.contains(td)) {
583 descriptorsToAnalyze.add(td);
584 descriptorsToAnalyze.addAll(callGraph.getAllMethods(td));
589 // add all methods transitively reachable from the
590 // source's main to set for analysis
591 mdSourceEntry = typeUtil.getMain();
592 descriptorsToAnalyze.add( mdSourceEntry );
593 descriptorsToAnalyze.addAll(
594 callGraph.getAllMethods( mdSourceEntry )
597 // fabricate an empty calling context that will call
598 // the source's main, but call graph doesn't know
599 // about it, so explicitly add it
600 makeAnalysisEntryMethod( mdSourceEntry );
601 descriptorsToAnalyze.add( mdAnalysisEntry );
604 // topologically sort according to the call graph so
605 // leaf calls are ordered first, smarter analysis order
606 // CHANGED: order leaf calls last!!
607 LinkedList<Descriptor> sortedDescriptors =
608 topologicalSort( descriptorsToAnalyze );
610 // add sorted descriptors to priority queue, and duplicate
611 // the queue as a set for efficiently testing whether some
612 // method is marked for analysis
614 Iterator<Descriptor> dItr = sortedDescriptors.iterator();
615 while( dItr.hasNext() ) {
616 Descriptor d = dItr.next();
617 mapDescriptorToPriority.put( d, new Integer( p ) );
618 descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
619 descriptorsToVisitSet.add( d );
623 // analyze methods from the priority queue until it is empty
624 while( !descriptorsToVisitQ.isEmpty() ) {
625 Descriptor d = descriptorsToVisitQ.pop().getDescriptor();
626 //Descriptor d = descriptorsToVisitQ.poll().getDescriptor();
628 assert descriptorsToVisitSet.contains( d );
629 descriptorsToVisitSet.remove( d );
631 // because the task or method descriptor just extracted
632 // was in the "to visit" set it either hasn't been analyzed
633 // yet, or some method that it depends on has been
634 // updated. Recompute a complete reachability graph for
635 // this task/method and compare it to any previous result.
636 // If there is a change detected, add any methods/tasks
637 // that depend on this one to the "to visit" set.
639 System.out.println( "Analyzing " + d );
641 ReachGraph rg = analyzeMethod( d );
642 ReachGraph rgPrev = getPartial( d );
644 if( !rg.equals( rgPrev ) ) {
647 // results for d changed, so enqueue dependents
648 // of d for further analysis
649 Iterator<Descriptor> depsItr = getDependents( d ).iterator();
650 while( depsItr.hasNext() ) {
651 Descriptor dNext = depsItr.next();
658 protected ReachGraph analyzeMethod( Descriptor d )
659 throws java.io.IOException {
661 // get the flat code for this descriptor
663 if( d == mdAnalysisEntry ) {
664 fm = fmAnalysisEntry;
666 fm = state.getMethodFlat( d );
668 pm.analyzeMethod(fm);
669 // intraprocedural work set
670 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
671 flatNodesToVisit.add( fm );
673 // mapping of current partial results
674 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
675 new Hashtable<FlatNode, ReachGraph>();
677 // the set of return nodes partial results that will be combined as
678 // the final, conservative approximation of the entire method
679 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
681 while( !flatNodesToVisit.isEmpty() ) {
682 FlatNode fn = (FlatNode) flatNodesToVisit.iterator().next();
683 flatNodesToVisit.remove( fn );
685 // effect transfer function defined by this node,
686 // then compare it to the old graph at this node
687 // to see if anything was updated.
689 ReachGraph rg = new ReachGraph();
690 TaskDescriptor taskDesc;
691 if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null){
692 if(mapDescriptorToReachGraph.containsKey(taskDesc)){
693 // retrieve existing reach graph if it is not first time
694 rg=mapDescriptorToReachGraph.get(taskDesc);
696 // create initial reach graph for a task
697 rg=createInitialTaskReachGraph((FlatMethod)fn);
699 mapDescriptorToReachGraph.put(taskDesc, rg);
703 // start by merging all node's parents' graphs
704 for( int i = 0; i < pm.numPrev(fn); ++i ) {
705 FlatNode pn = pm.getPrev(fn,i);
706 if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
707 ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
708 rg.merge( rgParent );
713 if( takeDebugSnapshots &&
714 d.getSymbol().equals( descSymbolDebug )
716 debugSnapshot( rg, fn, true );
720 // modify rg with appropriate transfer function
721 rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
724 if( takeDebugSnapshots &&
725 d.getSymbol().equals( descSymbolDebug )
727 debugSnapshot( rg, fn, false );
732 // if the results of the new graph are different from
733 // the current graph at this node, replace the graph
734 // with the update and enqueue the children
735 ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
736 if( !rg.equals( rgPrev ) ) {
737 mapFlatNodeToReachGraph.put( fn, rg );
739 for( int i = 0; i < pm.numNext(fn); i++ ) {
740 FlatNode nn = pm.getNext(fn, i);
741 flatNodesToVisit.add( nn );
746 // end by merging all return nodes into a complete
747 // ownership graph that represents all possible heap
748 // states after the flat method returns
749 ReachGraph completeGraph = new ReachGraph();
751 assert !setReturns.isEmpty();
752 Iterator retItr = setReturns.iterator();
753 while( retItr.hasNext() ) {
754 FlatReturnNode frn = (FlatReturnNode) retItr.next();
756 assert mapFlatNodeToReachGraph.containsKey( frn );
757 ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
759 completeGraph.merge( rgRet );
763 if( takeDebugSnapshots &&
764 d.getSymbol().equals( descSymbolDebug )
766 // increment that we've visited the debug snap
767 // method, and reset the node counter
768 System.out.println( " @@@ debug snap at visit "+snapVisitCounter );
772 if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
775 System.out.println( "!!! Stopping analysis after debug snap captures. !!!" );
781 return completeGraph;
786 analyzeFlatNode( Descriptor d,
787 FlatMethod fmContaining,
789 HashSet<FlatReturnNode> setRetNodes,
791 ) throws java.io.IOException {
794 // any variables that are no longer live should be
795 // nullified in the graph to reduce edges
796 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
803 // use node type to decide what transfer function
804 // to apply to the reachability graph
805 switch( fn.kind() ) {
807 case FKind.FlatMethod: {
808 // construct this method's initial heap model (IHM)
809 // since we're working on the FlatMethod, we know
810 // the incoming ReachGraph 'rg' is empty
812 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
813 getIHMcontributions( d );
815 Set entrySet = heapsFromCallers.entrySet();
816 Iterator itr = entrySet.iterator();
817 while( itr.hasNext() ) {
818 Map.Entry me = (Map.Entry) itr.next();
819 FlatCall fc = (FlatCall) me.getKey();
820 ReachGraph rgContrib = (ReachGraph) me.getValue();
822 assert fc.getMethod().equals( d );
824 // some call sites are in same method context though,
825 // and all of them should be merged together first,
826 // then heaps from different contexts should be merged
827 // THIS ASSUMES DIFFERENT CONTEXTS NEED SPECIAL CONSIDERATION!
828 // such as, do allocation sites need to be aged?
830 rg.merge_diffMethodContext( rgContrib );
832 FlatMethod hackfm=(FlatMethod)fn;
833 if (hackmap.containsKey(hackfm)) {
834 rg.merge(hackmap.get(hackfm));
836 hackmap.put(hackfm, rg);
839 case FKind.FlatOpNode:
840 FlatOpNode fon = (FlatOpNode) fn;
841 if( fon.getOp().getOp() == Operation.ASSIGN ) {
844 rg.assignTempXEqualToTempY( lhs, rhs );
848 case FKind.FlatCastNode:
849 FlatCastNode fcn = (FlatCastNode) fn;
853 TypeDescriptor td = fcn.getType();
856 rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
859 case FKind.FlatFieldNode:
860 FlatFieldNode ffn = (FlatFieldNode) fn;
863 fld = ffn.getField();
864 if( shouldAnalysisTrack( fld.getType() ) ) {
865 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld );
869 case FKind.FlatSetFieldNode:
870 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
872 fld = fsfn.getField();
874 if( shouldAnalysisTrack( fld.getType() ) ) {
875 rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs );
879 case FKind.FlatElementNode:
880 FlatElementNode fen = (FlatElementNode) fn;
883 if( shouldAnalysisTrack( lhs.getType() ) ) {
885 assert rhs.getType() != null;
886 assert rhs.getType().isArray();
888 TypeDescriptor tdElement = rhs.getType().dereference();
889 FieldDescriptor fdElement = getArrayField( tdElement );
891 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement );
895 case FKind.FlatSetElementNode:
896 FlatSetElementNode fsen = (FlatSetElementNode) fn;
898 if( arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
899 // skip this node if it cannot create new reachability paths
905 if( shouldAnalysisTrack( rhs.getType() ) ) {
907 assert lhs.getType() != null;
908 assert lhs.getType().isArray();
910 TypeDescriptor tdElement = lhs.getType().dereference();
911 FieldDescriptor fdElement = getArrayField( tdElement );
913 rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs );
918 FlatNew fnn = (FlatNew) fn;
920 if( shouldAnalysisTrack( lhs.getType() ) ) {
921 AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );
922 rg.assignTempEqualToNewAlloc( lhs, as );
926 case FKind.FlatCall: {
927 //TODO: temporal fix for task descriptor case
928 //MethodDescriptor mdCaller = fmContaining.getMethod();
930 if(fmContaining.getMethod()!=null){
931 mdCaller = fmContaining.getMethod();
933 mdCaller = fmContaining.getTask();
935 FlatCall fc = (FlatCall) fn;
936 MethodDescriptor mdCallee = fc.getMethod();
937 FlatMethod fmCallee = state.getMethodFlat( mdCallee );
939 boolean writeDebugDOTs =
940 mdCaller.getSymbol().equals( state.DISJOINTDEBUGCALLER ) &&
941 mdCallee.getSymbol().equals( state.DISJOINTDEBUGCALLEE );
944 // calculate the heap this call site can reach--note this is
945 // not used for the current call site transform, we are
946 // grabbing this heap model for future analysis of the callees,
947 // so if different results emerge we will return to this site
948 ReachGraph heapForThisCall_old =
949 getIHMcontribution( mdCallee, fc );
951 // the computation of the callee-reachable heap
952 // is useful for making the callee starting point
953 // and for applying the call site transfer function
954 Set<Integer> callerNodeIDsCopiedToCallee =
955 new HashSet<Integer>();
957 ReachGraph heapForThisCall_cur =
958 rg.makeCalleeView( fc,
960 callerNodeIDsCopiedToCallee,
964 if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {
965 // if heap at call site changed, update the contribution,
966 // and reschedule the callee for analysis
967 addIHMcontribution( mdCallee, fc, heapForThisCall_cur );
974 // the transformation for a call site should update the
975 // current heap abstraction with any effects from the callee,
976 // or if the method is virtual, the effects from any possible
977 // callees, so find the set of callees...
978 Set<MethodDescriptor> setPossibleCallees =
979 new HashSet<MethodDescriptor>();
981 if( mdCallee.isStatic() ) {
982 setPossibleCallees.add( mdCallee );
984 TypeDescriptor typeDesc = fc.getThis().getType();
985 setPossibleCallees.addAll( callGraph.getMethods( mdCallee,
990 ReachGraph rgMergeOfEffects = new ReachGraph();
992 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
993 while( mdItr.hasNext() ) {
994 MethodDescriptor mdPossible = mdItr.next();
995 FlatMethod fmPossible = state.getMethodFlat( mdPossible );
997 addDependent( mdPossible, // callee
1000 // don't alter the working graph (rg) until we compute a
1001 // result for every possible callee, merge them all together,
1002 // then set rg to that
1003 ReachGraph rgCopy = new ReachGraph();
1006 ReachGraph rgEffect = getPartial( mdPossible );
1008 if( rgEffect == null ) {
1009 // if this method has never been analyzed just schedule it
1010 // for analysis and skip over this call site for now
1011 enqueue( mdPossible );
1013 rgCopy.resolveMethodCall( fc,
1016 callerNodeIDsCopiedToCallee,
1021 rgMergeOfEffects.merge( rgCopy );
1025 // now that we've taken care of building heap models for
1026 // callee analysis, finish this transformation
1027 rg = rgMergeOfEffects;
1031 case FKind.FlatReturnNode:
1032 FlatReturnNode frn = (FlatReturnNode) fn;
1033 rhs = frn.getReturnTemp();
1034 if( rhs != null && shouldAnalysisTrack( rhs.getType() ) ) {
1035 rg.assignReturnEqualToTemp( rhs );
1037 setRetNodes.add( frn );
1043 // dead variables were removed before the above transfer function
1044 // was applied, so eliminate heap regions and edges that are no
1045 // longer part of the abstractly-live heap graph, and sweep up
1046 // and reachability effects that are altered by the reduction
1047 //rg.abstractGarbageCollect();
1051 // at this point rg should be the correct update
1052 // by an above transfer function, or untouched if
1053 // the flat node type doesn't affect the heap
1058 // this method should generate integers strictly greater than zero!
1059 // special "shadow" regions are made from a heap region by negating
1061 static public Integer generateUniqueHeapRegionNodeID() {
1063 return new Integer( uniqueIDcount );
1068 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
1069 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
1070 if( fdElement == null ) {
1071 fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
1073 arrayElementFieldName,
1076 mapTypeToArrayField.put( tdElement, fdElement );
1083 private void writeFinalGraphs() {
1084 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1085 Iterator itr = entrySet.iterator();
1086 while( itr.hasNext() ) {
1087 Map.Entry me = (Map.Entry) itr.next();
1088 Descriptor d = (Descriptor) me.getKey();
1089 ReachGraph rg = (ReachGraph) me.getValue();
1091 rg.writeGraph( "COMPLETE"+d,
1092 true, // write labels (variables)
1093 true, // selectively hide intermediate temp vars
1094 true, // prune unreachable heap regions
1095 false, // hide subset reachability states
1096 true ); // hide edge taints
1100 private void writeFinalIHMs() {
1101 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1102 while( d2IHMsItr.hasNext() ) {
1103 Map.Entry me1 = (Map.Entry) d2IHMsItr.next();
1104 Descriptor d = (Descriptor) me1.getKey();
1105 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1107 Iterator fc2rgItr = IHMs.entrySet().iterator();
1108 while( fc2rgItr.hasNext() ) {
1109 Map.Entry me2 = (Map.Entry) fc2rgItr.next();
1110 FlatCall fc = (FlatCall) me2.getKey();
1111 ReachGraph rg = (ReachGraph) me2.getValue();
1113 rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc,
1114 true, // write labels (variables)
1115 true, // selectively hide intermediate temp vars
1116 true, // prune unreachable heap regions
1117 false, // hide subset reachability states
1118 true ); // hide edge taints
1124 protected ReachGraph getPartial( Descriptor d ) {
1125 return mapDescriptorToCompleteReachGraph.get( d );
1128 protected void setPartial( Descriptor d, ReachGraph rg ) {
1129 mapDescriptorToCompleteReachGraph.put( d, rg );
1131 // when the flag for writing out every partial
1132 // result is set, we should spit out the graph,
1133 // but in order to give it a unique name we need
1134 // to track how many partial results for this
1135 // descriptor we've already written out
1136 if( writeAllIncrementalDOTs ) {
1137 if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1138 mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1140 Integer n = mapDescriptorToNumUpdates.get( d );
1142 rg.writeGraph( d+"COMPLETE"+String.format( "%05d", n ),
1143 true, // write labels (variables)
1144 true, // selectively hide intermediate temp vars
1145 true, // prune unreachable heap regions
1146 false, // hide subset reachability states
1147 true ); // hide edge taints
1149 mapDescriptorToNumUpdates.put( d, n + 1 );
1155 // return just the allocation site associated with one FlatNew node
1156 protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1158 if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1160 (AllocSite) Canonical.makeCanonical( new AllocSite( allocationDepth,
1162 fnew.getDisjointId()
1166 // the newest nodes are single objects
1167 for( int i = 0; i < allocationDepth; ++i ) {
1168 Integer id = generateUniqueHeapRegionNodeID();
1169 as.setIthOldest( i, id );
1170 mapHrnIdToAllocSite.put( id, as );
1173 // the oldest node is a summary node
1174 as.setSummary( generateUniqueHeapRegionNodeID() );
1176 mapFlatNewToAllocSite.put( fnew, as );
1179 return mapFlatNewToAllocSite.get( fnew );
1183 public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1184 // don't track primitive types, but an array
1185 // of primitives is heap memory
1186 if( type.isImmutable() ) {
1187 return type.isArray();
1190 // everything else is an object
1194 protected int numMethodsAnalyzed() {
1195 return descriptorsToAnalyze.size();
1202 // Take in source entry which is the program's compiled entry and
1203 // create a new analysis entry, a method that takes no parameters
1204 // and appears to allocate the command line arguments and call the
1205 // source entry with them. The purpose of this analysis entry is
1206 // to provide a top-level method context with no parameters left.
1207 protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1209 Modifiers mods = new Modifiers();
1210 mods.addModifier( Modifiers.PUBLIC );
1211 mods.addModifier( Modifiers.STATIC );
1213 TypeDescriptor returnType =
1214 new TypeDescriptor( TypeDescriptor.VOID );
1216 this.mdAnalysisEntry =
1217 new MethodDescriptor( mods,
1219 "analysisEntryMethod"
1222 TempDescriptor cmdLineArgs =
1223 new TempDescriptor( "args",
1224 mdSourceEntry.getParamType( 0 )
1228 new FlatNew( mdSourceEntry.getParamType( 0 ),
1233 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1234 sourceEntryArgs[0] = cmdLineArgs;
1237 new FlatCall( mdSourceEntry,
1243 FlatReturnNode frn = new FlatReturnNode( null );
1245 FlatExit fe = new FlatExit();
1247 this.fmAnalysisEntry =
1248 new FlatMethod( mdAnalysisEntry,
1252 this.fmAnalysisEntry.addNext( fn );
1259 protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1261 Set <Descriptor> discovered = new HashSet <Descriptor>();
1262 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
1264 Iterator<Descriptor> itr = toSort.iterator();
1265 while( itr.hasNext() ) {
1266 Descriptor d = itr.next();
1268 if( !discovered.contains( d ) ) {
1269 dfsVisit( d, toSort, sorted, discovered );
1276 // While we're doing DFS on call graph, remember
1277 // dependencies for efficient queuing of methods
1278 // during interprocedural analysis:
1280 // a dependent of a method decriptor d for this analysis is:
1281 // 1) a method or task that invokes d
1282 // 2) in the descriptorsToAnalyze set
1283 protected void dfsVisit( Descriptor d,
1284 Set <Descriptor> toSort,
1285 LinkedList<Descriptor> sorted,
1286 Set <Descriptor> discovered ) {
1287 discovered.add( d );
1289 // only methods have callers, tasks never do
1290 if( d instanceof MethodDescriptor ) {
1292 MethodDescriptor md = (MethodDescriptor) d;
1294 // the call graph is not aware that we have a fabricated
1295 // analysis entry that calls the program source's entry
1296 if( md == mdSourceEntry ) {
1297 if( !discovered.contains( mdAnalysisEntry ) ) {
1298 addDependent( mdSourceEntry, // callee
1299 mdAnalysisEntry // caller
1301 dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1305 // otherwise call graph guides DFS
1306 Iterator itr = callGraph.getCallerSet( md ).iterator();
1307 while( itr.hasNext() ) {
1308 Descriptor dCaller = (Descriptor) itr.next();
1310 // only consider callers in the original set to analyze
1311 if( !toSort.contains( dCaller ) ) {
1315 if( !discovered.contains( dCaller ) ) {
1316 addDependent( md, // callee
1320 dfsVisit( dCaller, toSort, sorted, discovered );
1325 // for leaf-nodes last now!
1326 sorted.addLast( d );
1330 protected void enqueue( Descriptor d ) {
1331 if( !descriptorsToVisitSet.contains( d ) ) {
1332 Integer priority = mapDescriptorToPriority.get( d );
1333 descriptorsToVisitQ.add( new DescriptorQWrapper( priority,
1336 descriptorsToVisitSet.add( d );
1341 // a dependent of a method decriptor d for this analysis is:
1342 // 1) a method or task that invokes d
1343 // 2) in the descriptorsToAnalyze set
1344 protected void addDependent( Descriptor callee, Descriptor caller ) {
1345 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1346 if( deps == null ) {
1347 deps = new HashSet<Descriptor>();
1350 mapDescriptorToSetDependents.put( callee, deps );
1353 protected Set<Descriptor> getDependents( Descriptor callee ) {
1354 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1355 if( deps == null ) {
1356 deps = new HashSet<Descriptor>();
1357 mapDescriptorToSetDependents.put( callee, deps );
1363 public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
1365 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1366 mapDescriptorToIHMcontributions.get( d );
1368 if( heapsFromCallers == null ) {
1369 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
1370 mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
1373 return heapsFromCallers;
1376 public ReachGraph getIHMcontribution( Descriptor d,
1379 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1380 getIHMcontributions( d );
1382 if( !heapsFromCallers.containsKey( fc ) ) {
1383 heapsFromCallers.put( fc, new ReachGraph() );
1386 return heapsFromCallers.get( fc );
1389 public void addIHMcontribution( Descriptor d,
1393 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1394 getIHMcontributions( d );
1396 heapsFromCallers.put( fc, rg );
1399 private AllocSite createParameterAllocSite(ReachGraph rg, TempDescriptor tempDesc) {
1401 // create temp descriptor for each parameter variable
1402 FlatNew flatNew = new FlatNew(tempDesc.getType(), tempDesc, false);
1403 // create allocation site
1404 AllocSite as = (AllocSite) Canonical.makeCanonical(new AllocSite( allocationDepth, flatNew, flatNew.getDisjointId()));
1405 for (int i = 0; i < allocationDepth; ++i) {
1406 Integer id = generateUniqueHeapRegionNodeID();
1407 as.setIthOldest(i, id);
1408 mapHrnIdToAllocSite.put(id, as);
1410 // the oldest node is a summary node
1411 as.setSummary( generateUniqueHeapRegionNodeID() );
1419 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc){
1421 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
1422 if(!typeDesc.isImmutable()){
1423 ClassDescriptor classDesc = typeDesc.getClassDesc();
1424 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1425 FieldDescriptor field = (FieldDescriptor) it.next();
1426 TypeDescriptor fieldType = field.getType();
1427 if (shouldAnalysisTrack( fieldType )) {
1428 fieldSet.add(field);
1436 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha ){
1438 int dimCount=fd.getType().getArrayCount();
1439 HeapRegionNode prevNode=null;
1440 HeapRegionNode arrayEntryNode=null;
1441 for(int i=dimCount;i>0;i--){
1442 TypeDescriptor typeDesc=fd.getType().dereference();//hack to get instance of type desc
1443 typeDesc.setArrayCount(i);
1444 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
1445 HeapRegionNode hrnSummary ;
1446 if(!mapToExistingNode.containsKey(typeDesc)){
1451 as = createParameterAllocSite(rg, tempDesc);
1453 // make a new reference to allocated node
1455 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1456 false, // single object?
1459 false, // out-of-context?
1460 as.getType(), // type
1461 as, // allocation site
1462 alpha, // inherent reach
1463 alpha, // current reach
1464 ExistPredSet.factory(rg.predTrue), // predicates
1465 tempDesc.toString() // description
1467 rg.id2hrn.put(as.getSummary(),hrnSummary);
1469 mapToExistingNode.put(typeDesc, hrnSummary);
1471 hrnSummary=mapToExistingNode.get(typeDesc);
1475 // make a new reference between new summary node and source
1476 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1479 fd.getSymbol(), // field name
1481 ExistPredSet.factory(rg.predTrue) // predicates
1484 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1485 prevNode=hrnSummary;
1486 arrayEntryNode=hrnSummary;
1488 // make a new reference between summary nodes of array
1489 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1492 arrayElementFieldName, // field name
1494 ExistPredSet.factory(rg.predTrue) // predicates
1497 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1498 prevNode=hrnSummary;
1503 // create a new obj node if obj has at least one non-primitive field
1504 TypeDescriptor type=fd.getType();
1505 if(getFieldSetTobeAnalyzed(type).size()>0){
1506 TypeDescriptor typeDesc=type.dereference();
1507 typeDesc.setArrayCount(0);
1508 if(!mapToExistingNode.containsKey(typeDesc)){
1509 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
1510 AllocSite as = createParameterAllocSite(rg, tempDesc);
1511 // make a new reference to allocated node
1512 HeapRegionNode hrnSummary =
1513 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1514 false, // single object?
1517 false, // out-of-context?
1519 as, // allocation site
1520 alpha, // inherent reach
1521 alpha, // current reach
1522 ExistPredSet.factory(rg.predTrue), // predicates
1523 tempDesc.toString() // description
1525 rg.id2hrn.put(as.getSummary(),hrnSummary);
1526 mapToExistingNode.put(typeDesc, hrnSummary);
1527 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1530 arrayElementFieldName, // field name
1532 ExistPredSet.factory(rg.predTrue) // predicates
1534 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1535 prevNode=hrnSummary;
1537 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
1538 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null){
1539 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1542 arrayElementFieldName, // field name
1544 ExistPredSet.factory(rg.predTrue) // predicates
1546 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1548 prevNode=hrnSummary;
1552 map.put(arrayEntryNode, prevNode);
1553 return arrayEntryNode;
1556 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
1557 ReachGraph rg = new ReachGraph();
1558 TaskDescriptor taskDesc = fm.getTask();
1560 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
1561 Descriptor paramDesc = taskDesc.getParameter(idx);
1562 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
1564 // setup data structure
1565 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
1566 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
1567 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
1568 new Hashtable<TypeDescriptor, HeapRegionNode>();
1569 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
1570 new Hashtable<HeapRegionNode, HeapRegionNode>();
1571 Set<String> doneSet = new HashSet<String>();
1573 TempDescriptor tempDesc = fm.getParameter(idx);
1575 AllocSite as = createParameterAllocSite(rg, tempDesc);
1576 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
1577 Integer idNewest = as.getIthOldest(0);
1578 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
1580 // make a new reference to allocated node
1581 RefEdge edgeNew = new RefEdge(lnX, // source
1583 taskDesc.getParamType(idx), // type
1585 hrnNewest.getAlpha(), // beta
1586 ExistPredSet.factory(rg.predTrue) // predicates
1588 rg.addRefEdge(lnX, hrnNewest, edgeNew);
1590 // set-up a work set for class field
1591 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
1592 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1593 FieldDescriptor fd = (FieldDescriptor) it.next();
1594 TypeDescriptor fieldType = fd.getType();
1595 if (shouldAnalysisTrack( fieldType )) {
1596 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
1597 newMap.put(hrnNewest, fd);
1598 workSet.add(newMap);
1602 int uniqueIdentifier = 0;
1603 while (!workSet.isEmpty()) {
1604 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
1606 workSet.remove(map);
1608 Set<HeapRegionNode> key = map.keySet();
1609 HeapRegionNode srcHRN = key.iterator().next();
1610 FieldDescriptor fd = map.get(srcHRN);
1611 TypeDescriptor type = fd.getType();
1612 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
1614 if (!doneSet.contains(doneSetIdentifier)) {
1615 doneSet.add(doneSetIdentifier);
1616 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
1617 // create new summary Node
1618 TempDescriptor td = new TempDescriptor("temp"
1619 + uniqueIdentifier, type);
1621 AllocSite allocSite;
1622 if(type.equals(paramTypeDesc)){
1623 //corresponding allocsite has already been created for a parameter variable.
1626 allocSite = createParameterAllocSite(rg, td);
1628 String strDesc = allocSite.toStringForDOT()
1630 TypeDescriptor allocType=allocSite.getType();
1632 HeapRegionNode hrnSummary;
1633 if(allocType.isArray() && allocType.getArrayCount()>0){
1634 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
1637 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
1638 false, // single object?
1641 false, // out-of-context?
1642 allocSite.getType(), // type
1643 allocSite, // allocation site
1644 hrnNewest.getAlpha(), // inherent reach
1645 hrnNewest.getAlpha(), // current reach
1646 ExistPredSet.factory(rg.predTrue), // predicates
1647 strDesc // description
1649 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
1651 // make a new reference to summary node
1652 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1655 fd.getSymbol(), // field name
1656 hrnNewest.getAlpha(), // beta
1657 ExistPredSet.factory(rg.predTrue) // predicates
1660 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1664 mapTypeToExistingSummaryNode.put(type, hrnSummary);
1666 // set-up a work set for fields of the class
1667 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
1668 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
1670 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
1672 HeapRegionNode newDstHRN;
1673 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)){
1674 //related heap region node is already exsited.
1675 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
1677 newDstHRN=hrnSummary;
1679 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
1680 if(!doneSet.contains(doneSetIdentifier)){
1681 // add new work item
1682 HashMap<HeapRegionNode, FieldDescriptor> newMap =
1683 new HashMap<HeapRegionNode, FieldDescriptor>();
1684 newMap.put(newDstHRN, fieldDescriptor);
1685 workSet.add(newMap);
1690 // if there exists corresponding summary node
1691 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
1693 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1695 fd.getType(), // type
1696 fd.getSymbol(), // field name
1697 srcHRN.getAlpha(), // beta
1698 ExistPredSet.factory(rg.predTrue) // predicates
1700 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
1706 // debugSnapshot(rg, fm, true);
1710 // return all allocation sites in the method (there is one allocation
1711 // site per FlatNew node in a method)
1712 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
1713 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
1714 buildAllocationSiteSet(d);
1717 return mapDescriptorToAllocSiteSet.get(d);
1721 private void buildAllocationSiteSet(Descriptor d) {
1722 HashSet<AllocSite> s = new HashSet<AllocSite>();
1725 if( d instanceof MethodDescriptor ) {
1726 fm = state.getMethodFlat( (MethodDescriptor) d);
1728 assert d instanceof TaskDescriptor;
1729 fm = state.getMethodFlat( (TaskDescriptor) d);
1731 pm.analyzeMethod(fm);
1733 // visit every node in this FlatMethod's IR graph
1734 // and make a set of the allocation sites from the
1735 // FlatNew node's visited
1736 HashSet<FlatNode> visited = new HashSet<FlatNode>();
1737 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
1740 while( !toVisit.isEmpty() ) {
1741 FlatNode n = toVisit.iterator().next();
1743 if( n instanceof FlatNew ) {
1744 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
1750 for( int i = 0; i < pm.numNext(n); ++i ) {
1751 FlatNode child = pm.getNext(n, i);
1752 if( !visited.contains(child) ) {
1758 mapDescriptorToAllocSiteSet.put(d, s);
1761 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
1763 HashSet<AllocSite> out = new HashSet<AllocSite>();
1764 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1765 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1769 while (!toVisit.isEmpty()) {
1770 Descriptor d = toVisit.iterator().next();
1774 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
1775 Iterator asItr = asSet.iterator();
1776 while (asItr.hasNext()) {
1777 AllocSite as = (AllocSite) asItr.next();
1778 if (as.getDisjointAnalysisId() != null) {
1783 // enqueue callees of this method to be searched for
1784 // allocation sites also
1785 Set callees = callGraph.getCalleeSet(d);
1786 if (callees != null) {
1787 Iterator methItr = callees.iterator();
1788 while (methItr.hasNext()) {
1789 MethodDescriptor md = (MethodDescriptor) methItr.next();
1791 if (!visited.contains(md)) {
1802 private HashSet<AllocSite>
1803 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
1805 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
1806 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1807 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1811 // traverse this task and all methods reachable from this task
1812 while( !toVisit.isEmpty() ) {
1813 Descriptor d = toVisit.iterator().next();
1817 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
1818 Iterator asItr = asSet.iterator();
1819 while( asItr.hasNext() ) {
1820 AllocSite as = (AllocSite) asItr.next();
1821 TypeDescriptor typed = as.getType();
1822 if( typed != null ) {
1823 ClassDescriptor cd = typed.getClassDesc();
1824 if( cd != null && cd.hasFlags() ) {
1830 // enqueue callees of this method to be searched for
1831 // allocation sites also
1832 Set callees = callGraph.getCalleeSet(d);
1833 if( callees != null ) {
1834 Iterator methItr = callees.iterator();
1835 while( methItr.hasNext() ) {
1836 MethodDescriptor md = (MethodDescriptor) methItr.next();
1838 if( !visited.contains(md) ) {
1851 // get successive captures of the analysis state, use compiler
1853 boolean takeDebugSnapshots = false;
1854 String descSymbolDebug = null;
1855 boolean stopAfterCapture = false;
1856 int snapVisitCounter = 0;
1857 int snapNodeCounter = 0;
1858 int visitStartCapture = 0;
1859 int numVisitsToCapture = 0;
1862 void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
1863 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
1871 if( snapVisitCounter >= visitStartCapture ) {
1872 System.out.println( " @@@ snapping visit="+snapVisitCounter+
1873 ", node="+snapNodeCounter+
1877 graphName = String.format( "snap%02d_%04din",
1881 graphName = String.format( "snap%02d_%04dout",
1886 graphName = graphName + fn;
1888 rg.writeGraph( graphName,
1889 true, // write labels (variables)
1890 true, // selectively hide intermediate temp vars
1891 true, // prune unreachable heap regions
1892 false, // hide subset reachability states
1893 true );// hide edge taints