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 sharing class
97 // between task parameters and flagged allocation sites reachable
99 public void writeAllSharing(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 sharing
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 sharing classes with
132 // other task parameters and every allocation site
133 // reachable from this task
134 boolean foundSomeSharing = 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 sharing classes 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 foundSomeSharing = true;
160 if (!tabularOutput) {
161 bw.write("Potential sharing between parameters " + i
162 + " and " + j + ".\n");
163 bw.write(prettyPrintNodeSet(common) + "\n");
168 // for the ith parameter, check for sharing classes against
169 // the set of allocation sites reachable from this
171 Iterator allocItr = allocSites.iterator();
172 while (allocItr.hasNext()) {
173 AllocSite as = (AllocSite) allocItr.next();
174 common = hasPotentialSharing(td, i, as);
175 if (!common.isEmpty()) {
176 foundSomeSharing = true;
178 if (!tabularOutput) {
179 bw.write("Potential sharing between parameter " + i
180 + " and " + as.getFlatNew() + ".\n");
181 bw.write(prettyPrintNodeSet(common) + "\n");
187 // for each allocation site check for sharing classes with
188 // other allocation sites in the context of execution
190 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
191 Iterator allocItr1 = allocSites.iterator();
192 while (allocItr1.hasNext()) {
193 AllocSite as1 = (AllocSite) allocItr1.next();
195 Iterator allocItr2 = allocSites.iterator();
196 while (allocItr2.hasNext()) {
197 AllocSite as2 = (AllocSite) allocItr2.next();
199 if (!outerChecked.contains(as2)) {
200 common = hasPotentialSharing(td, as1, as2);
202 if (!common.isEmpty()) {
203 foundSomeSharing = true;
205 if (!tabularOutput) {
206 bw.write("Potential sharing between "
207 + as1.getFlatNew() + " and "
208 + as2.getFlatNew() + ".\n");
209 bw.write(prettyPrintNodeSet(common) + "\n");
215 outerChecked.add(as1);
218 if (!foundSomeSharing) {
219 if (!tabularOutput) {
220 bw.write("No sharing between flagged objects in Task " + td
228 bw.write(" & " + numSharing + " & " + justTime + " & " + numLines
229 + " & " + numMethodsAnalyzed() + " \\\\\n");
231 bw.write("\nNumber sharing classes: "+numSharing);
237 // this version of writeAllSharing is for Java programs that have no tasks
238 public void writeAllSharingJava(String outputFile,
241 boolean tabularOutput,
244 throws java.io.IOException {
245 checkAnalysisComplete();
251 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
253 bw.write("Conducting disjoint reachability analysis with allocation depth = "
254 + allocationDepth + "\n");
255 bw.write(timeReport + "\n\n");
257 boolean foundSomeSharing = false;
259 Descriptor d = typeUtil.getMain();
260 HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
262 // for each allocation site check for sharing classes with
263 // other allocation sites in the context of execution
265 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
266 Iterator allocItr1 = allocSites.iterator();
267 while (allocItr1.hasNext()) {
268 AllocSite as1 = (AllocSite) allocItr1.next();
270 Iterator allocItr2 = allocSites.iterator();
271 while (allocItr2.hasNext()) {
272 AllocSite as2 = (AllocSite) allocItr2.next();
274 if (!outerChecked.contains(as2)) {
275 Set<HeapRegionNode> common = hasPotentialSharing(d,
278 if (!common.isEmpty()) {
279 foundSomeSharing = true;
280 bw.write("Potential sharing between "
281 + as1.getDisjointAnalysisId() + " and "
282 + as2.getDisjointAnalysisId() + ".\n");
283 bw.write(prettyPrintNodeSet(common) + "\n");
289 outerChecked.add(as1);
292 if (!foundSomeSharing) {
293 bw.write("No sharing classes between flagged objects found.\n");
295 bw.write("\nNumber sharing classes: "+numSharing);
298 bw.write("Number of methods analyzed: "+numMethodsAnalyzed()+"\n");
303 ///////////////////////////////////////////
305 // end public interface
307 ///////////////////////////////////////////
309 protected void checkAnalysisComplete() {
310 if( !analysisComplete ) {
311 throw new Error("Warning: public interface method called while analysis is running.");
316 // run in faster mode, only when bugs wrung out!
317 public static boolean releaseMode;
319 // use command line option to set this, analysis
320 // should attempt to be deterministic
321 public static boolean determinismDesired;
323 // when we want to enforce determinism in the
324 // analysis we need to sort descriptors rather
325 // than toss them in efficient sets, use this
326 public static DescriptorComparator dComp =
327 new DescriptorComparator();
330 // data from the compiler
332 public CallGraph callGraph;
333 public Liveness liveness;
334 public ArrayReferencees arrayReferencees;
335 public TypeUtil typeUtil;
336 public int allocationDepth;
338 // data structure for public interface
339 private Hashtable< Descriptor, HashSet<AllocSite> >
340 mapDescriptorToAllocSiteSet;
343 // for public interface methods to warn that they
344 // are grabbing results during analysis
345 private boolean analysisComplete;
348 // used to identify HeapRegionNode objects
349 // A unique ID equates an object in one
350 // ownership graph with an object in another
351 // graph that logically represents the same
353 // start at 10 and increment to reserve some
354 // IDs for special purposes
355 static protected int uniqueIDcount = 10;
358 // An out-of-scope method created by the
359 // analysis that has no parameters, and
360 // appears to allocate the command line
361 // arguments, then invoke the source code's
362 // main method. The purpose of this is to
363 // provide the analysis with an explicit
364 // top-level context with no parameters
365 protected MethodDescriptor mdAnalysisEntry;
366 protected FlatMethod fmAnalysisEntry;
368 // main method defined by source program
369 protected MethodDescriptor mdSourceEntry;
371 // the set of task and/or method descriptors
372 // reachable in call graph
373 protected Set<Descriptor>
374 descriptorsToAnalyze;
376 // current descriptors to visit in fixed-point
377 // interprocedural analysis, prioritized by
378 // dependency in the call graph
379 protected Stack<Descriptor>
380 descriptorsToVisitStack;
381 protected PriorityQueue<DescriptorQWrapper>
384 // a duplication of the above structure, but
385 // for efficient testing of inclusion
386 protected HashSet<Descriptor>
387 descriptorsToVisitSet;
389 // storage for priorities (doesn't make sense)
390 // to add it to the Descriptor class, just in
392 protected Hashtable<Descriptor, Integer>
393 mapDescriptorToPriority;
395 // when analyzing a method and scheduling more:
396 // remember set of callee's enqueued for analysis
397 // so they can be put on top of the callers in
398 // the stack-visit mode
399 protected Set<Descriptor>
402 // maps a descriptor to its current partial result
403 // from the intraprocedural fixed-point analysis--
404 // then the interprocedural analysis settles, this
405 // mapping will have the final results for each
407 protected Hashtable<Descriptor, ReachGraph>
408 mapDescriptorToCompleteReachGraph;
410 // maps a descriptor to its known dependents: namely
411 // methods or tasks that call the descriptor's method
412 // AND are part of this analysis (reachable from main)
413 protected Hashtable< Descriptor, Set<Descriptor> >
414 mapDescriptorToSetDependents;
416 // maps each flat new to one analysis abstraction
417 // allocate site object, these exist outside reach graphs
418 protected Hashtable<FlatNew, AllocSite>
419 mapFlatNewToAllocSite;
421 // maps intergraph heap region IDs to intergraph
422 // allocation sites that created them, a redundant
423 // structure for efficiency in some operations
424 protected Hashtable<Integer, AllocSite>
427 // maps a method to its initial heap model (IHM) that
428 // is the set of reachability graphs from every caller
429 // site, all merged together. The reason that we keep
430 // them separate is that any one call site's contribution
431 // to the IHM may changed along the path to the fixed point
432 protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
433 mapDescriptorToIHMcontributions;
435 // additionally, keep a mapping from descriptors to the
436 // merged in-coming initial context, because we want this
437 // initial context to be STRICTLY MONOTONIC
438 protected Hashtable<Descriptor, ReachGraph>
439 mapDescriptorToInitialContext;
441 // make the result for back edges analysis-wide STRICTLY
442 // MONOTONIC as well, but notice we use FlatNode as the
443 // key for this map: in case we want to consider other
444 // nodes as back edge's in future implementations
445 protected Hashtable<FlatNode, ReachGraph>
446 mapBackEdgeToMonotone;
449 public static final String arrayElementFieldName = "___element_";
450 static protected Hashtable<TypeDescriptor, FieldDescriptor>
453 // for controlling DOT file output
454 protected boolean writeFinalDOTs;
455 protected boolean writeAllIncrementalDOTs;
457 // supporting DOT output--when we want to write every
458 // partial method result, keep a tally for generating
460 protected Hashtable<Descriptor, Integer>
461 mapDescriptorToNumUpdates;
463 //map task descriptor to initial task parameter
464 protected Hashtable<Descriptor, ReachGraph>
465 mapDescriptorToReachGraph;
467 protected PointerMethod pm;
469 static protected Hashtable<FlatNode, ReachGraph> fn2rg =
470 new Hashtable<FlatNode, ReachGraph>();
473 // allocate various structures that are not local
474 // to a single class method--should be done once
475 protected void allocateStructures() {
477 if( determinismDesired ) {
478 // use an ordered set
479 descriptorsToAnalyze = new TreeSet<Descriptor>( dComp );
481 // otherwise use a speedy hashset
482 descriptorsToAnalyze = new HashSet<Descriptor>();
485 mapDescriptorToCompleteReachGraph =
486 new Hashtable<Descriptor, ReachGraph>();
488 mapDescriptorToNumUpdates =
489 new Hashtable<Descriptor, Integer>();
491 mapDescriptorToSetDependents =
492 new Hashtable< Descriptor, Set<Descriptor> >();
494 mapFlatNewToAllocSite =
495 new Hashtable<FlatNew, AllocSite>();
497 mapDescriptorToIHMcontributions =
498 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
500 mapDescriptorToInitialContext =
501 new Hashtable<Descriptor, ReachGraph>();
503 mapBackEdgeToMonotone =
504 new Hashtable<FlatNode, ReachGraph>();
506 mapHrnIdToAllocSite =
507 new Hashtable<Integer, AllocSite>();
509 mapTypeToArrayField =
510 new Hashtable <TypeDescriptor, FieldDescriptor>();
512 if( state.DISJOINTDVISITSTACK ||
513 state.DISJOINTDVISITSTACKEESONTOP
515 descriptorsToVisitStack =
516 new Stack<Descriptor>();
519 if( state.DISJOINTDVISITPQUE ) {
520 descriptorsToVisitQ =
521 new PriorityQueue<DescriptorQWrapper>();
524 descriptorsToVisitSet =
525 new HashSet<Descriptor>();
527 mapDescriptorToPriority =
528 new Hashtable<Descriptor, Integer>();
531 new HashSet<Descriptor>();
533 mapDescriptorToAllocSiteSet =
534 new Hashtable<Descriptor, HashSet<AllocSite> >();
536 mapDescriptorToReachGraph =
537 new Hashtable<Descriptor, ReachGraph>();
539 pm = new PointerMethod();
544 // this analysis generates a disjoint reachability
545 // graph for every reachable method in the program
546 public DisjointAnalysis( State s,
551 ) throws java.io.IOException {
552 init( s, tu, cg, l, ar );
555 protected void init( State state,
559 ArrayReferencees arrayReferencees
560 ) throws java.io.IOException {
562 analysisComplete = false;
565 this.typeUtil = typeUtil;
566 this.callGraph = callGraph;
567 this.liveness = liveness;
568 this.arrayReferencees = arrayReferencees;
569 this.allocationDepth = state.DISJOINTALLOCDEPTH;
570 this.releaseMode = state.DISJOINTRELEASEMODE;
571 this.determinismDesired = state.DISJOINTDETERMINISM;
573 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
574 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL;
576 this.takeDebugSnapshots = state.DISJOINTSNAPSYMBOL != null;
577 this.descSymbolDebug = state.DISJOINTSNAPSYMBOL;
578 this.visitStartCapture = state.DISJOINTSNAPVISITTOSTART;
579 this.numVisitsToCapture = state.DISJOINTSNAPNUMVISITS;
580 this.stopAfterCapture = state.DISJOINTSNAPSTOPAFTER;
581 this.snapVisitCounter = 1; // count visits from 1 (user will write 1, means 1st visit)
582 this.snapNodeCounter = 0; // count nodes from 0
585 state.DISJOINTDVISITSTACK ||
586 state.DISJOINTDVISITPQUE ||
587 state.DISJOINTDVISITSTACKEESONTOP;
588 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITPQUE);
589 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITSTACKEESONTOP);
590 assert !(state.DISJOINTDVISITPQUE && state.DISJOINTDVISITSTACKEESONTOP);
592 // set some static configuration for ReachGraphs
593 ReachGraph.allocationDepth = allocationDepth;
594 ReachGraph.typeUtil = typeUtil;
596 ReachGraph.debugCallSiteVisitStartCapture
597 = state.DISJOINTDEBUGCALLVISITTOSTART;
599 ReachGraph.debugCallSiteNumVisitsToCapture
600 = state.DISJOINTDEBUGCALLNUMVISITS;
602 ReachGraph.debugCallSiteStopAfter
603 = state.DISJOINTDEBUGCALLSTOPAFTER;
605 ReachGraph.debugCallSiteVisitCounter
606 = 0; // count visits from 1, is incremented before first visit
610 allocateStructures();
612 double timeStartAnalysis = (double) System.nanoTime();
614 // start interprocedural fixed-point computation
616 analysisComplete=true;
618 double timeEndAnalysis = (double) System.nanoTime();
619 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
620 String treport = String.format( "The reachability analysis took %.3f sec.", dt );
621 String justtime = String.format( "%.2f", dt );
622 System.out.println( treport );
624 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
628 if( state.DISJOINTWRITEIHMS ) {
632 if( state.DISJOINTWRITEINITCONTEXTS ) {
633 writeInitialContexts();
636 if( state.DISJOINTALIASFILE != null ) {
638 writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
640 writeAllSharingJava(state.DISJOINTALIASFILE,
643 state.DISJOINTALIASTAB,
651 protected boolean moreDescriptorsToVisit() {
652 if( state.DISJOINTDVISITSTACK ||
653 state.DISJOINTDVISITSTACKEESONTOP
655 return !descriptorsToVisitStack.isEmpty();
657 } else if( state.DISJOINTDVISITPQUE ) {
658 return !descriptorsToVisitQ.isEmpty();
661 throw new Error( "Neither descriptor visiting mode set" );
665 // fixed-point computation over the call graph--when a
666 // method's callees are updated, it must be reanalyzed
667 protected void analyzeMethods() throws java.io.IOException {
669 // task or non-task (java) mode determines what the roots
670 // of the call chain are, and establishes the set of methods
671 // reachable from the roots that will be analyzed
674 System.out.println( "Bamboo mode..." );
676 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
677 while( taskItr.hasNext() ) {
678 TaskDescriptor td = (TaskDescriptor) taskItr.next();
679 if( !descriptorsToAnalyze.contains( td ) ) {
680 // add all methods transitively reachable from the
682 descriptorsToAnalyze.add( td );
683 descriptorsToAnalyze.addAll( callGraph.getAllMethods( td ) );
688 System.out.println( "Java mode..." );
690 // add all methods transitively reachable from the
691 // source's main to set for analysis
692 mdSourceEntry = typeUtil.getMain();
693 descriptorsToAnalyze.add( mdSourceEntry );
694 descriptorsToAnalyze.addAll( callGraph.getAllMethods( mdSourceEntry ) );
696 // fabricate an empty calling context that will call
697 // the source's main, but call graph doesn't know
698 // about it, so explicitly add it
699 makeAnalysisEntryMethod( mdSourceEntry );
700 descriptorsToAnalyze.add( mdAnalysisEntry );
704 // now, depending on the interprocedural mode for visiting
705 // methods, set up the needed data structures
707 if( state.DISJOINTDVISITPQUE ) {
709 // topologically sort according to the call graph so
710 // leaf calls are last, helps build contexts up first
711 LinkedList<Descriptor> sortedDescriptors =
712 topologicalSort( descriptorsToAnalyze );
714 // add sorted descriptors to priority queue, and duplicate
715 // the queue as a set for efficiently testing whether some
716 // method is marked for analysis
718 Iterator<Descriptor> dItr;
720 // for the priority queue, give items at the head
721 // of the sorted list a low number (highest priority)
722 while( !sortedDescriptors.isEmpty() ) {
723 Descriptor d = sortedDescriptors.removeFirst();
724 mapDescriptorToPriority.put( d, new Integer( p ) );
725 descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
726 descriptorsToVisitSet.add( d );
730 } else if( state.DISJOINTDVISITSTACK ||
731 state.DISJOINTDVISITSTACKEESONTOP
733 // if we're doing the stack scheme, just throw the root
734 // method or tasks on the stack
736 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
737 while( taskItr.hasNext() ) {
738 TaskDescriptor td = (TaskDescriptor) taskItr.next();
739 descriptorsToVisitStack.add( td );
740 descriptorsToVisitSet.add( td );
744 descriptorsToVisitStack.add( mdAnalysisEntry );
745 descriptorsToVisitSet.add( mdAnalysisEntry );
749 throw new Error( "Unknown method scheduling mode" );
753 // analyze scheduled methods until there are no more to visit
754 while( moreDescriptorsToVisit() ) {
757 if( state.DISJOINTDVISITSTACK ||
758 state.DISJOINTDVISITSTACKEESONTOP
760 d = descriptorsToVisitStack.pop();
762 } else if( state.DISJOINTDVISITPQUE ) {
763 d = descriptorsToVisitQ.poll().getDescriptor();
766 assert descriptorsToVisitSet.contains( d );
767 descriptorsToVisitSet.remove( d );
769 // because the task or method descriptor just extracted
770 // was in the "to visit" set it either hasn't been analyzed
771 // yet, or some method that it depends on has been
772 // updated. Recompute a complete reachability graph for
773 // this task/method and compare it to any previous result.
774 // If there is a change detected, add any methods/tasks
775 // that depend on this one to the "to visit" set.
777 System.out.println( "Analyzing " + d );
779 if( state.DISJOINTDVISITSTACKEESONTOP ) {
780 assert calleesToEnqueue.isEmpty();
783 ReachGraph rg = analyzeMethod( d );
784 ReachGraph rgPrev = getPartial( d );
786 if( !rg.equals( rgPrev ) ) {
789 if( state.DISJOINTDEBUGSCHEDULING ) {
790 System.out.println( " complete graph changed, scheduling callers for analysis:" );
793 // results for d changed, so enqueue dependents
794 // of d for further analysis
795 Iterator<Descriptor> depsItr = getDependents( d ).iterator();
796 while( depsItr.hasNext() ) {
797 Descriptor dNext = depsItr.next();
800 if( state.DISJOINTDEBUGSCHEDULING ) {
801 System.out.println( " "+dNext );
805 if( state.DISJOINTDVISITSTACKEESONTOP ) {
807 depsItr = calleesToEnqueue.iterator();
808 while( depsItr.hasNext() ) {
809 Descriptor dNext = depsItr.next();
812 calleesToEnqueue.clear();
816 // we got the result result as the last visit
817 // to this method, but we might need to clean
819 if( state.DISJOINTDVISITSTACKEESONTOP ) {
820 calleesToEnqueue.clear();
827 protected ReachGraph analyzeMethod( Descriptor d )
828 throws java.io.IOException {
830 // get the flat code for this descriptor
832 if( d == mdAnalysisEntry ) {
833 fm = fmAnalysisEntry;
835 fm = state.getMethodFlat( d );
837 pm.analyzeMethod( fm );
839 // intraprocedural work set
840 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
841 flatNodesToVisit.add( fm );
843 // if determinism is desired by client, shadow the
844 // set with a queue to make visit order deterministic
845 Queue<FlatNode> flatNodesToVisitQ = null;
846 if( determinismDesired ) {
847 flatNodesToVisitQ = new LinkedList<FlatNode>();
848 flatNodesToVisitQ.add( fm );
851 // mapping of current partial results
852 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
853 new Hashtable<FlatNode, ReachGraph>();
855 // the set of return nodes partial results that will be combined as
856 // the final, conservative approximation of the entire method
857 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
859 while( !flatNodesToVisit.isEmpty() ) {
862 if( determinismDesired ) {
863 assert !flatNodesToVisitQ.isEmpty();
864 fn = flatNodesToVisitQ.remove();
866 fn = flatNodesToVisit.iterator().next();
868 flatNodesToVisit.remove( fn );
870 // effect transfer function defined by this node,
871 // then compare it to the old graph at this node
872 // to see if anything was updated.
874 ReachGraph rg = new ReachGraph();
875 TaskDescriptor taskDesc;
876 if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null){
877 if(mapDescriptorToReachGraph.containsKey(taskDesc)){
878 // retrieve existing reach graph if it is not first time
879 rg=mapDescriptorToReachGraph.get(taskDesc);
881 // create initial reach graph for a task
882 rg=createInitialTaskReachGraph((FlatMethod)fn);
884 mapDescriptorToReachGraph.put(taskDesc, rg);
888 // start by merging all node's parents' graphs
889 for( int i = 0; i < pm.numPrev(fn); ++i ) {
890 FlatNode pn = pm.getPrev(fn,i);
891 if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
892 ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
893 rg.merge( rgParent );
898 if( takeDebugSnapshots &&
899 d.getSymbol().equals( descSymbolDebug )
901 debugSnapshot( rg, fn, true );
905 // modify rg with appropriate transfer function
906 rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
909 if( takeDebugSnapshots &&
910 d.getSymbol().equals( descSymbolDebug )
912 debugSnapshot( rg, fn, false );
917 // if the results of the new graph are different from
918 // the current graph at this node, replace the graph
919 // with the update and enqueue the children
920 ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
921 if( !rg.equals( rgPrev ) ) {
922 mapFlatNodeToReachGraph.put( fn, rg );
924 for( int i = 0; i < pm.numNext( fn ); i++ ) {
925 FlatNode nn = pm.getNext( fn, i );
927 flatNodesToVisit.add( nn );
928 if( determinismDesired ) {
929 flatNodesToVisitQ.add( nn );
936 // end by merging all return nodes into a complete
937 // reach graph that represents all possible heap
938 // states after the flat method returns
939 ReachGraph completeGraph = new ReachGraph();
941 assert !setReturns.isEmpty();
942 Iterator retItr = setReturns.iterator();
943 while( retItr.hasNext() ) {
944 FlatReturnNode frn = (FlatReturnNode) retItr.next();
946 assert mapFlatNodeToReachGraph.containsKey( frn );
947 ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
949 completeGraph.merge( rgRet );
953 if( takeDebugSnapshots &&
954 d.getSymbol().equals( descSymbolDebug )
956 // increment that we've visited the debug snap
957 // method, and reset the node counter
958 System.out.println( " @@@ debug snap at visit "+snapVisitCounter );
962 if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
965 System.out.println( "!!! Stopping analysis after debug snap captures. !!!" );
971 return completeGraph;
976 analyzeFlatNode( Descriptor d,
977 FlatMethod fmContaining,
979 HashSet<FlatReturnNode> setRetNodes,
981 ) throws java.io.IOException {
984 // any variables that are no longer live should be
985 // nullified in the graph to reduce edges
986 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
993 // use node type to decide what transfer function
994 // to apply to the reachability graph
995 switch( fn.kind() ) {
997 case FKind.FlatMethod: {
998 // construct this method's initial heap model (IHM)
999 // since we're working on the FlatMethod, we know
1000 // the incoming ReachGraph 'rg' is empty
1002 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1003 getIHMcontributions( d );
1005 Set entrySet = heapsFromCallers.entrySet();
1006 Iterator itr = entrySet.iterator();
1007 while( itr.hasNext() ) {
1008 Map.Entry me = (Map.Entry) itr.next();
1009 FlatCall fc = (FlatCall) me.getKey();
1010 ReachGraph rgContrib = (ReachGraph) me.getValue();
1012 assert fc.getMethod().equals( d );
1014 rg.merge( rgContrib );
1018 // additionally, we are enforcing STRICT MONOTONICITY for the
1019 // method's initial context, so grow the context by whatever
1020 // the previously computed context was, and put the most
1021 // up-to-date context back in the map
1022 ReachGraph rgPrevContext = mapDescriptorToInitialContext.get( d );
1023 rg.merge( rgPrevContext );
1024 mapDescriptorToInitialContext.put( d, rg );
1028 case FKind.FlatOpNode:
1029 FlatOpNode fon = (FlatOpNode) fn;
1030 if( fon.getOp().getOp() == Operation.ASSIGN ) {
1031 lhs = fon.getDest();
1032 rhs = fon.getLeft();
1033 rg.assignTempXEqualToTempY( lhs, rhs );
1037 case FKind.FlatCastNode:
1038 FlatCastNode fcn = (FlatCastNode) fn;
1042 TypeDescriptor td = fcn.getType();
1045 rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
1048 case FKind.FlatFieldNode:
1049 FlatFieldNode ffn = (FlatFieldNode) fn;
1052 fld = ffn.getField();
1053 if( shouldAnalysisTrack( fld.getType() ) ) {
1054 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld );
1058 case FKind.FlatSetFieldNode:
1059 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
1060 lhs = fsfn.getDst();
1061 fld = fsfn.getField();
1062 rhs = fsfn.getSrc();
1063 if( shouldAnalysisTrack( fld.getType() ) ) {
1064 rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs );
1068 case FKind.FlatElementNode:
1069 FlatElementNode fen = (FlatElementNode) fn;
1072 if( shouldAnalysisTrack( lhs.getType() ) ) {
1074 assert rhs.getType() != null;
1075 assert rhs.getType().isArray();
1077 TypeDescriptor tdElement = rhs.getType().dereference();
1078 FieldDescriptor fdElement = getArrayField( tdElement );
1080 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement );
1084 case FKind.FlatSetElementNode:
1085 FlatSetElementNode fsen = (FlatSetElementNode) fn;
1087 if( arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
1088 // skip this node if it cannot create new reachability paths
1092 lhs = fsen.getDst();
1093 rhs = fsen.getSrc();
1094 if( shouldAnalysisTrack( rhs.getType() ) ) {
1096 assert lhs.getType() != null;
1097 assert lhs.getType().isArray();
1099 TypeDescriptor tdElement = lhs.getType().dereference();
1100 FieldDescriptor fdElement = getArrayField( tdElement );
1102 rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs );
1107 FlatNew fnn = (FlatNew) fn;
1109 if( shouldAnalysisTrack( lhs.getType() ) ) {
1110 AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );
1111 rg.assignTempEqualToNewAlloc( lhs, as );
1115 case FKind.FlatCall: {
1116 Descriptor mdCaller;
1117 if( fmContaining.getMethod() != null ){
1118 mdCaller = fmContaining.getMethod();
1120 mdCaller = fmContaining.getTask();
1122 FlatCall fc = (FlatCall) fn;
1123 MethodDescriptor mdCallee = fc.getMethod();
1124 FlatMethod fmCallee = state.getMethodFlat( mdCallee );
1127 boolean debugCallSite =
1128 mdCaller.getSymbol().equals( state.DISJOINTDEBUGCALLER ) &&
1129 mdCallee.getSymbol().equals( state.DISJOINTDEBUGCALLEE );
1131 boolean writeDebugDOTs = false;
1132 boolean stopAfter = false;
1133 if( debugCallSite ) {
1134 ++ReachGraph.debugCallSiteVisitCounter;
1135 System.out.println( " $$$ Debug call site visit "+
1136 ReachGraph.debugCallSiteVisitCounter+
1140 (ReachGraph.debugCallSiteVisitCounter >=
1141 ReachGraph.debugCallSiteVisitStartCapture) &&
1143 (ReachGraph.debugCallSiteVisitCounter <
1144 ReachGraph.debugCallSiteVisitStartCapture +
1145 ReachGraph.debugCallSiteNumVisitsToCapture)
1147 writeDebugDOTs = true;
1148 System.out.println( " $$$ Capturing this call site visit $$$" );
1149 if( ReachGraph.debugCallSiteStopAfter &&
1150 (ReachGraph.debugCallSiteVisitCounter ==
1151 ReachGraph.debugCallSiteVisitStartCapture +
1152 ReachGraph.debugCallSiteNumVisitsToCapture - 1)
1160 // calculate the heap this call site can reach--note this is
1161 // not used for the current call site transform, we are
1162 // grabbing this heap model for future analysis of the callees,
1163 // so if different results emerge we will return to this site
1164 ReachGraph heapForThisCall_old =
1165 getIHMcontribution( mdCallee, fc );
1167 // the computation of the callee-reachable heap
1168 // is useful for making the callee starting point
1169 // and for applying the call site transfer function
1170 Set<Integer> callerNodeIDsCopiedToCallee =
1171 new HashSet<Integer>();
1173 ReachGraph heapForThisCall_cur =
1174 rg.makeCalleeView( fc,
1176 callerNodeIDsCopiedToCallee,
1180 if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {
1181 // if heap at call site changed, update the contribution,
1182 // and reschedule the callee for analysis
1183 addIHMcontribution( mdCallee, fc, heapForThisCall_cur );
1185 if( state.DISJOINTDEBUGSCHEDULING ) {
1186 System.out.println( " context changed, scheduling callee: "+mdCallee );
1189 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1190 calleesToEnqueue.add( mdCallee );
1192 enqueue( mdCallee );
1198 // the transformation for a call site should update the
1199 // current heap abstraction with any effects from the callee,
1200 // or if the method is virtual, the effects from any possible
1201 // callees, so find the set of callees...
1202 Set<MethodDescriptor> setPossibleCallees;
1203 if( determinismDesired ) {
1204 // use an ordered set
1205 setPossibleCallees = new TreeSet<MethodDescriptor>( dComp );
1207 // otherwise use a speedy hashset
1208 setPossibleCallees = new HashSet<MethodDescriptor>();
1211 if( mdCallee.isStatic() ) {
1212 setPossibleCallees.add( mdCallee );
1214 TypeDescriptor typeDesc = fc.getThis().getType();
1215 setPossibleCallees.addAll( callGraph.getMethods( mdCallee,
1220 ReachGraph rgMergeOfEffects = new ReachGraph();
1222 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
1223 while( mdItr.hasNext() ) {
1224 MethodDescriptor mdPossible = mdItr.next();
1225 FlatMethod fmPossible = state.getMethodFlat( mdPossible );
1227 addDependent( mdPossible, // callee
1230 // don't alter the working graph (rg) until we compute a
1231 // result for every possible callee, merge them all together,
1232 // then set rg to that
1233 ReachGraph rgCopy = new ReachGraph();
1236 ReachGraph rgEffect = getPartial( mdPossible );
1238 if( rgEffect == null ) {
1239 // if this method has never been analyzed just schedule it
1240 // for analysis and skip over this call site for now
1241 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1242 calleesToEnqueue.add( mdPossible );
1244 enqueue( mdPossible );
1247 if( state.DISJOINTDEBUGSCHEDULING ) {
1248 System.out.println( " callee hasn't been analyzed, scheduling: "+mdPossible );
1253 rgCopy.resolveMethodCall( fc,
1256 callerNodeIDsCopiedToCallee,
1261 rgMergeOfEffects.merge( rgCopy );
1266 System.out.println( "$$$ Exiting after requested captures of call site. $$$" );
1271 // now that we've taken care of building heap models for
1272 // callee analysis, finish this transformation
1273 rg = rgMergeOfEffects;
1277 case FKind.FlatReturnNode:
1278 FlatReturnNode frn = (FlatReturnNode) fn;
1279 rhs = frn.getReturnTemp();
1280 if( rhs != null && shouldAnalysisTrack( rhs.getType() ) ) {
1281 rg.assignReturnEqualToTemp( rhs );
1283 setRetNodes.add( frn );
1289 // dead variables were removed before the above transfer function
1290 // was applied, so eliminate heap regions and edges that are no
1291 // longer part of the abstractly-live heap graph, and sweep up
1292 // and reachability effects that are altered by the reduction
1293 //rg.abstractGarbageCollect();
1297 // back edges are strictly monotonic
1298 if( pm.isBackEdge( fn ) ) {
1299 ReachGraph rgPrevResult = mapBackEdgeToMonotone.get( fn );
1300 rg.merge( rgPrevResult );
1301 mapBackEdgeToMonotone.put( fn, rg );
1304 // at this point rg should be the correct update
1305 // by an above transfer function, or untouched if
1306 // the flat node type doesn't affect the heap
1312 // this method should generate integers strictly greater than zero!
1313 // special "shadow" regions are made from a heap region by negating
1315 static public Integer generateUniqueHeapRegionNodeID() {
1317 return new Integer( uniqueIDcount );
1322 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
1323 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
1324 if( fdElement == null ) {
1325 fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
1327 arrayElementFieldName,
1330 mapTypeToArrayField.put( tdElement, fdElement );
1337 private void writeFinalGraphs() {
1338 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1339 Iterator itr = entrySet.iterator();
1340 while( itr.hasNext() ) {
1341 Map.Entry me = (Map.Entry) itr.next();
1342 Descriptor d = (Descriptor) me.getKey();
1343 ReachGraph rg = (ReachGraph) me.getValue();
1345 rg.writeGraph( "COMPLETE"+d,
1346 true, // write labels (variables)
1347 true, // selectively hide intermediate temp vars
1348 true, // prune unreachable heap regions
1349 false, // hide subset reachability states
1350 true ); // hide edge taints
1354 private void writeFinalIHMs() {
1355 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1356 while( d2IHMsItr.hasNext() ) {
1357 Map.Entry me1 = (Map.Entry) d2IHMsItr.next();
1358 Descriptor d = (Descriptor) me1.getKey();
1359 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1361 Iterator fc2rgItr = IHMs.entrySet().iterator();
1362 while( fc2rgItr.hasNext() ) {
1363 Map.Entry me2 = (Map.Entry) fc2rgItr.next();
1364 FlatCall fc = (FlatCall) me2.getKey();
1365 ReachGraph rg = (ReachGraph) me2.getValue();
1367 rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc,
1368 true, // write labels (variables)
1369 true, // selectively hide intermediate temp vars
1370 true, // prune unreachable heap regions
1371 false, // hide subset reachability states
1372 true ); // hide edge taints
1377 private void writeInitialContexts() {
1378 Set entrySet = mapDescriptorToInitialContext.entrySet();
1379 Iterator itr = entrySet.iterator();
1380 while( itr.hasNext() ) {
1381 Map.Entry me = (Map.Entry) itr.next();
1382 Descriptor d = (Descriptor) me.getKey();
1383 ReachGraph rg = (ReachGraph) me.getValue();
1385 rg.writeGraph( "INITIAL"+d,
1386 true, // write labels (variables)
1387 true, // selectively hide intermediate temp vars
1388 true, // prune unreachable heap regions
1389 false, // hide subset reachability states
1390 true ); // hide edge taints
1395 protected ReachGraph getPartial( Descriptor d ) {
1396 return mapDescriptorToCompleteReachGraph.get( d );
1399 protected void setPartial( Descriptor d, ReachGraph rg ) {
1400 mapDescriptorToCompleteReachGraph.put( d, rg );
1402 // when the flag for writing out every partial
1403 // result is set, we should spit out the graph,
1404 // but in order to give it a unique name we need
1405 // to track how many partial results for this
1406 // descriptor we've already written out
1407 if( writeAllIncrementalDOTs ) {
1408 if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1409 mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1411 Integer n = mapDescriptorToNumUpdates.get( d );
1413 rg.writeGraph( d+"COMPLETE"+String.format( "%05d", n ),
1414 true, // write labels (variables)
1415 true, // selectively hide intermediate temp vars
1416 true, // prune unreachable heap regions
1417 false, // hide subset reachability states
1418 true ); // hide edge taints
1420 mapDescriptorToNumUpdates.put( d, n + 1 );
1426 // return just the allocation site associated with one FlatNew node
1427 protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1429 if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1430 AllocSite as = AllocSite.factory( allocationDepth,
1432 fnew.getDisjointId()
1435 // the newest nodes are single objects
1436 for( int i = 0; i < allocationDepth; ++i ) {
1437 Integer id = generateUniqueHeapRegionNodeID();
1438 as.setIthOldest( i, id );
1439 mapHrnIdToAllocSite.put( id, as );
1442 // the oldest node is a summary node
1443 as.setSummary( generateUniqueHeapRegionNodeID() );
1445 mapFlatNewToAllocSite.put( fnew, as );
1448 return mapFlatNewToAllocSite.get( fnew );
1452 public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1453 // don't track primitive types, but an array
1454 // of primitives is heap memory
1455 if( type.isImmutable() ) {
1456 return type.isArray();
1459 // everything else is an object
1463 protected int numMethodsAnalyzed() {
1464 return descriptorsToAnalyze.size();
1471 // Take in source entry which is the program's compiled entry and
1472 // create a new analysis entry, a method that takes no parameters
1473 // and appears to allocate the command line arguments and call the
1474 // source entry with them. The purpose of this analysis entry is
1475 // to provide a top-level method context with no parameters left.
1476 protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1478 Modifiers mods = new Modifiers();
1479 mods.addModifier( Modifiers.PUBLIC );
1480 mods.addModifier( Modifiers.STATIC );
1482 TypeDescriptor returnType =
1483 new TypeDescriptor( TypeDescriptor.VOID );
1485 this.mdAnalysisEntry =
1486 new MethodDescriptor( mods,
1488 "analysisEntryMethod"
1491 TempDescriptor cmdLineArgs =
1492 new TempDescriptor( "args",
1493 mdSourceEntry.getParamType( 0 )
1497 new FlatNew( mdSourceEntry.getParamType( 0 ),
1502 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1503 sourceEntryArgs[0] = cmdLineArgs;
1506 new FlatCall( mdSourceEntry,
1512 FlatReturnNode frn = new FlatReturnNode( null );
1514 FlatExit fe = new FlatExit();
1516 this.fmAnalysisEntry =
1517 new FlatMethod( mdAnalysisEntry,
1521 this.fmAnalysisEntry.addNext( fn );
1528 protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1530 Set<Descriptor> discovered;
1532 if( determinismDesired ) {
1533 // use an ordered set
1534 discovered = new TreeSet<Descriptor>( dComp );
1536 // otherwise use a speedy hashset
1537 discovered = new HashSet<Descriptor>();
1540 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
1542 Iterator<Descriptor> itr = toSort.iterator();
1543 while( itr.hasNext() ) {
1544 Descriptor d = itr.next();
1546 if( !discovered.contains( d ) ) {
1547 dfsVisit( d, toSort, sorted, discovered );
1554 // While we're doing DFS on call graph, remember
1555 // dependencies for efficient queuing of methods
1556 // during interprocedural analysis:
1558 // a dependent of a method decriptor d for this analysis is:
1559 // 1) a method or task that invokes d
1560 // 2) in the descriptorsToAnalyze set
1561 protected void dfsVisit( Descriptor d,
1562 Set <Descriptor> toSort,
1563 LinkedList<Descriptor> sorted,
1564 Set <Descriptor> discovered ) {
1565 discovered.add( d );
1567 // only methods have callers, tasks never do
1568 if( d instanceof MethodDescriptor ) {
1570 MethodDescriptor md = (MethodDescriptor) d;
1572 // the call graph is not aware that we have a fabricated
1573 // analysis entry that calls the program source's entry
1574 if( md == mdSourceEntry ) {
1575 if( !discovered.contains( mdAnalysisEntry ) ) {
1576 addDependent( mdSourceEntry, // callee
1577 mdAnalysisEntry // caller
1579 dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1583 // otherwise call graph guides DFS
1584 Iterator itr = callGraph.getCallerSet( md ).iterator();
1585 while( itr.hasNext() ) {
1586 Descriptor dCaller = (Descriptor) itr.next();
1588 // only consider callers in the original set to analyze
1589 if( !toSort.contains( dCaller ) ) {
1593 if( !discovered.contains( dCaller ) ) {
1594 addDependent( md, // callee
1598 dfsVisit( dCaller, toSort, sorted, discovered );
1603 // for leaf-nodes last now!
1604 sorted.addLast( d );
1608 protected void enqueue( Descriptor d ) {
1610 if( !descriptorsToVisitSet.contains( d ) ) {
1612 if( state.DISJOINTDVISITSTACK ||
1613 state.DISJOINTDVISITSTACKEESONTOP
1615 descriptorsToVisitStack.add( d );
1617 } else if( state.DISJOINTDVISITPQUE ) {
1618 Integer priority = mapDescriptorToPriority.get( d );
1619 descriptorsToVisitQ.add( new DescriptorQWrapper( priority,
1624 descriptorsToVisitSet.add( d );
1629 // a dependent of a method decriptor d for this analysis is:
1630 // 1) a method or task that invokes d
1631 // 2) in the descriptorsToAnalyze set
1632 protected void addDependent( Descriptor callee, Descriptor caller ) {
1633 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1634 if( deps == null ) {
1635 deps = new HashSet<Descriptor>();
1638 mapDescriptorToSetDependents.put( callee, deps );
1641 protected Set<Descriptor> getDependents( Descriptor callee ) {
1642 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1643 if( deps == null ) {
1644 deps = new HashSet<Descriptor>();
1645 mapDescriptorToSetDependents.put( callee, deps );
1651 public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
1653 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1654 mapDescriptorToIHMcontributions.get( d );
1656 if( heapsFromCallers == null ) {
1657 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
1658 mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
1661 return heapsFromCallers;
1664 public ReachGraph getIHMcontribution( Descriptor d,
1667 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1668 getIHMcontributions( d );
1670 if( !heapsFromCallers.containsKey( fc ) ) {
1674 return heapsFromCallers.get( fc );
1677 public void addIHMcontribution( Descriptor d,
1681 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1682 getIHMcontributions( d );
1684 heapsFromCallers.put( fc, rg );
1687 private AllocSite createParameterAllocSite( ReachGraph rg,
1688 TempDescriptor tempDesc,
1694 flatNew = new FlatNew( tempDesc.getType(), // type
1695 tempDesc, // param temp
1696 false, // global alloc?
1697 "param"+tempDesc // disjoint site ID string
1700 flatNew = new FlatNew( tempDesc.getType(), // type
1701 tempDesc, // param temp
1702 false, // global alloc?
1703 null // disjoint site ID string
1707 // create allocation site
1708 AllocSite as = AllocSite.factory( allocationDepth,
1710 flatNew.getDisjointId()
1712 for (int i = 0; i < allocationDepth; ++i) {
1713 Integer id = generateUniqueHeapRegionNodeID();
1714 as.setIthOldest(i, id);
1715 mapHrnIdToAllocSite.put(id, as);
1717 // the oldest node is a summary node
1718 as.setSummary( generateUniqueHeapRegionNodeID() );
1726 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc){
1728 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
1729 if(!typeDesc.isImmutable()){
1730 ClassDescriptor classDesc = typeDesc.getClassDesc();
1731 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1732 FieldDescriptor field = (FieldDescriptor) it.next();
1733 TypeDescriptor fieldType = field.getType();
1734 if (shouldAnalysisTrack( fieldType )) {
1735 fieldSet.add(field);
1743 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha ){
1745 int dimCount=fd.getType().getArrayCount();
1746 HeapRegionNode prevNode=null;
1747 HeapRegionNode arrayEntryNode=null;
1748 for(int i=dimCount;i>0;i--){
1749 TypeDescriptor typeDesc=fd.getType().dereference();//hack to get instance of type desc
1750 typeDesc.setArrayCount(i);
1751 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
1752 HeapRegionNode hrnSummary ;
1753 if(!mapToExistingNode.containsKey(typeDesc)){
1758 as = createParameterAllocSite(rg, tempDesc, false);
1760 // make a new reference to allocated node
1762 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1763 false, // single object?
1765 false, // out-of-context?
1766 as.getType(), // type
1767 as, // allocation site
1768 alpha, // inherent reach
1769 alpha, // current reach
1770 ExistPredSet.factory(rg.predTrue), // predicates
1771 tempDesc.toString() // description
1773 rg.id2hrn.put(as.getSummary(),hrnSummary);
1775 mapToExistingNode.put(typeDesc, hrnSummary);
1777 hrnSummary=mapToExistingNode.get(typeDesc);
1781 // make a new reference between new summary node and source
1782 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1785 fd.getSymbol(), // field name
1787 ExistPredSet.factory(rg.predTrue) // predicates
1790 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1791 prevNode=hrnSummary;
1792 arrayEntryNode=hrnSummary;
1794 // make a new reference between summary nodes of array
1795 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1798 arrayElementFieldName, // field name
1800 ExistPredSet.factory(rg.predTrue) // predicates
1803 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1804 prevNode=hrnSummary;
1809 // create a new obj node if obj has at least one non-primitive field
1810 TypeDescriptor type=fd.getType();
1811 if(getFieldSetTobeAnalyzed(type).size()>0){
1812 TypeDescriptor typeDesc=type.dereference();
1813 typeDesc.setArrayCount(0);
1814 if(!mapToExistingNode.containsKey(typeDesc)){
1815 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
1816 AllocSite as = createParameterAllocSite(rg, tempDesc, false);
1817 // make a new reference to allocated node
1818 HeapRegionNode hrnSummary =
1819 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1820 false, // single object?
1822 false, // out-of-context?
1824 as, // allocation site
1825 alpha, // inherent reach
1826 alpha, // current reach
1827 ExistPredSet.factory(rg.predTrue), // predicates
1828 tempDesc.toString() // description
1830 rg.id2hrn.put(as.getSummary(),hrnSummary);
1831 mapToExistingNode.put(typeDesc, hrnSummary);
1832 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1835 arrayElementFieldName, // field name
1837 ExistPredSet.factory(rg.predTrue) // predicates
1839 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1840 prevNode=hrnSummary;
1842 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
1843 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null){
1844 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1847 arrayElementFieldName, // field name
1849 ExistPredSet.factory(rg.predTrue) // predicates
1851 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1853 prevNode=hrnSummary;
1857 map.put(arrayEntryNode, prevNode);
1858 return arrayEntryNode;
1861 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
1862 ReachGraph rg = new ReachGraph();
1863 TaskDescriptor taskDesc = fm.getTask();
1865 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
1866 Descriptor paramDesc = taskDesc.getParameter(idx);
1867 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
1869 // setup data structure
1870 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
1871 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
1872 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
1873 new Hashtable<TypeDescriptor, HeapRegionNode>();
1874 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
1875 new Hashtable<HeapRegionNode, HeapRegionNode>();
1876 Set<String> doneSet = new HashSet<String>();
1878 TempDescriptor tempDesc = fm.getParameter(idx);
1880 AllocSite as = createParameterAllocSite(rg, tempDesc, true);
1881 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
1882 Integer idNewest = as.getIthOldest(0);
1883 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
1885 // make a new reference to allocated node
1886 RefEdge edgeNew = new RefEdge(lnX, // source
1888 taskDesc.getParamType(idx), // type
1890 hrnNewest.getAlpha(), // beta
1891 ExistPredSet.factory(rg.predTrue) // predicates
1893 rg.addRefEdge(lnX, hrnNewest, edgeNew);
1895 // set-up a work set for class field
1896 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
1897 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1898 FieldDescriptor fd = (FieldDescriptor) it.next();
1899 TypeDescriptor fieldType = fd.getType();
1900 if (shouldAnalysisTrack( fieldType )) {
1901 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
1902 newMap.put(hrnNewest, fd);
1903 workSet.add(newMap);
1907 int uniqueIdentifier = 0;
1908 while (!workSet.isEmpty()) {
1909 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
1911 workSet.remove(map);
1913 Set<HeapRegionNode> key = map.keySet();
1914 HeapRegionNode srcHRN = key.iterator().next();
1915 FieldDescriptor fd = map.get(srcHRN);
1916 TypeDescriptor type = fd.getType();
1917 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
1919 if (!doneSet.contains(doneSetIdentifier)) {
1920 doneSet.add(doneSetIdentifier);
1921 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
1922 // create new summary Node
1923 TempDescriptor td = new TempDescriptor("temp"
1924 + uniqueIdentifier, type);
1926 AllocSite allocSite;
1927 if(type.equals(paramTypeDesc)){
1928 //corresponding allocsite has already been created for a parameter variable.
1931 allocSite = createParameterAllocSite(rg, td, false);
1933 String strDesc = allocSite.toStringForDOT()
1935 TypeDescriptor allocType=allocSite.getType();
1937 HeapRegionNode hrnSummary;
1938 if(allocType.isArray() && allocType.getArrayCount()>0){
1939 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
1942 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
1943 false, // single object?
1945 false, // out-of-context?
1946 allocSite.getType(), // type
1947 allocSite, // allocation site
1948 hrnNewest.getAlpha(), // inherent reach
1949 hrnNewest.getAlpha(), // current reach
1950 ExistPredSet.factory(rg.predTrue), // predicates
1951 strDesc // description
1953 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
1955 // make a new reference to summary node
1956 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1959 fd.getSymbol(), // field name
1960 hrnNewest.getAlpha(), // beta
1961 ExistPredSet.factory(rg.predTrue) // predicates
1964 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1968 mapTypeToExistingSummaryNode.put(type, hrnSummary);
1970 // set-up a work set for fields of the class
1971 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
1972 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
1974 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
1976 HeapRegionNode newDstHRN;
1977 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)){
1978 //related heap region node is already exsited.
1979 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
1981 newDstHRN=hrnSummary;
1983 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
1984 if(!doneSet.contains(doneSetIdentifier)){
1985 // add new work item
1986 HashMap<HeapRegionNode, FieldDescriptor> newMap =
1987 new HashMap<HeapRegionNode, FieldDescriptor>();
1988 newMap.put(newDstHRN, fieldDescriptor);
1989 workSet.add(newMap);
1994 // if there exists corresponding summary node
1995 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
1997 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1999 fd.getType(), // type
2000 fd.getSymbol(), // field name
2001 srcHRN.getAlpha(), // beta
2002 ExistPredSet.factory(rg.predTrue) // predicates
2004 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
2010 // debugSnapshot(rg, fm, true);
2014 // return all allocation sites in the method (there is one allocation
2015 // site per FlatNew node in a method)
2016 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
2017 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
2018 buildAllocationSiteSet(d);
2021 return mapDescriptorToAllocSiteSet.get(d);
2025 private void buildAllocationSiteSet(Descriptor d) {
2026 HashSet<AllocSite> s = new HashSet<AllocSite>();
2029 if( d instanceof MethodDescriptor ) {
2030 fm = state.getMethodFlat( (MethodDescriptor) d);
2032 assert d instanceof TaskDescriptor;
2033 fm = state.getMethodFlat( (TaskDescriptor) d);
2035 pm.analyzeMethod(fm);
2037 // visit every node in this FlatMethod's IR graph
2038 // and make a set of the allocation sites from the
2039 // FlatNew node's visited
2040 HashSet<FlatNode> visited = new HashSet<FlatNode>();
2041 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
2044 while( !toVisit.isEmpty() ) {
2045 FlatNode n = toVisit.iterator().next();
2047 if( n instanceof FlatNew ) {
2048 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
2054 for( int i = 0; i < pm.numNext(n); ++i ) {
2055 FlatNode child = pm.getNext(n, i);
2056 if( !visited.contains(child) ) {
2062 mapDescriptorToAllocSiteSet.put(d, s);
2065 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
2067 HashSet<AllocSite> out = new HashSet<AllocSite>();
2068 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2069 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2073 while (!toVisit.isEmpty()) {
2074 Descriptor d = toVisit.iterator().next();
2078 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2079 Iterator asItr = asSet.iterator();
2080 while (asItr.hasNext()) {
2081 AllocSite as = (AllocSite) asItr.next();
2082 if (as.getDisjointAnalysisId() != null) {
2087 // enqueue callees of this method to be searched for
2088 // allocation sites also
2089 Set callees = callGraph.getCalleeSet(d);
2090 if (callees != null) {
2091 Iterator methItr = callees.iterator();
2092 while (methItr.hasNext()) {
2093 MethodDescriptor md = (MethodDescriptor) methItr.next();
2095 if (!visited.contains(md)) {
2106 private HashSet<AllocSite>
2107 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
2109 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
2110 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2111 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2115 // traverse this task and all methods reachable from this task
2116 while( !toVisit.isEmpty() ) {
2117 Descriptor d = toVisit.iterator().next();
2121 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2122 Iterator asItr = asSet.iterator();
2123 while( asItr.hasNext() ) {
2124 AllocSite as = (AllocSite) asItr.next();
2125 TypeDescriptor typed = as.getType();
2126 if( typed != null ) {
2127 ClassDescriptor cd = typed.getClassDesc();
2128 if( cd != null && cd.hasFlags() ) {
2134 // enqueue callees of this method to be searched for
2135 // allocation sites also
2136 Set callees = callGraph.getCalleeSet(d);
2137 if( callees != null ) {
2138 Iterator methItr = callees.iterator();
2139 while( methItr.hasNext() ) {
2140 MethodDescriptor md = (MethodDescriptor) methItr.next();
2142 if( !visited.contains(md) ) {
2155 // get successive captures of the analysis state, use compiler
2157 boolean takeDebugSnapshots = false;
2158 String descSymbolDebug = null;
2159 boolean stopAfterCapture = false;
2160 int snapVisitCounter = 0;
2161 int snapNodeCounter = 0;
2162 int visitStartCapture = 0;
2163 int numVisitsToCapture = 0;
2166 void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
2167 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2175 if( snapVisitCounter >= visitStartCapture ) {
2176 System.out.println( " @@@ snapping visit="+snapVisitCounter+
2177 ", node="+snapNodeCounter+
2181 graphName = String.format( "snap%02d_%04din",
2185 graphName = String.format( "snap%02d_%04dout",
2190 graphName = graphName + fn;
2192 rg.writeGraph( graphName,
2193 true, // write labels (variables)
2194 true, // selectively hide intermediate temp vars
2195 true, // prune unreachable heap regions
2196 false, // hide subset reachability states
2197 true );// hide edge taints