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>();
472 private Hashtable<FlatCall, Descriptor> fc2enclosing;
476 // allocate various structures that are not local
477 // to a single class method--should be done once
478 protected void allocateStructures() {
480 if( determinismDesired ) {
481 // use an ordered set
482 descriptorsToAnalyze = new TreeSet<Descriptor>( dComp );
484 // otherwise use a speedy hashset
485 descriptorsToAnalyze = new HashSet<Descriptor>();
488 mapDescriptorToCompleteReachGraph =
489 new Hashtable<Descriptor, ReachGraph>();
491 mapDescriptorToNumUpdates =
492 new Hashtable<Descriptor, Integer>();
494 mapDescriptorToSetDependents =
495 new Hashtable< Descriptor, Set<Descriptor> >();
497 mapFlatNewToAllocSite =
498 new Hashtable<FlatNew, AllocSite>();
500 mapDescriptorToIHMcontributions =
501 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
503 mapDescriptorToInitialContext =
504 new Hashtable<Descriptor, ReachGraph>();
506 mapBackEdgeToMonotone =
507 new Hashtable<FlatNode, ReachGraph>();
509 mapHrnIdToAllocSite =
510 new Hashtable<Integer, AllocSite>();
512 mapTypeToArrayField =
513 new Hashtable <TypeDescriptor, FieldDescriptor>();
515 if( state.DISJOINTDVISITSTACK ||
516 state.DISJOINTDVISITSTACKEESONTOP
518 descriptorsToVisitStack =
519 new Stack<Descriptor>();
522 if( state.DISJOINTDVISITPQUE ) {
523 descriptorsToVisitQ =
524 new PriorityQueue<DescriptorQWrapper>();
527 descriptorsToVisitSet =
528 new HashSet<Descriptor>();
530 mapDescriptorToPriority =
531 new Hashtable<Descriptor, Integer>();
534 new HashSet<Descriptor>();
536 mapDescriptorToAllocSiteSet =
537 new Hashtable<Descriptor, HashSet<AllocSite> >();
539 mapDescriptorToReachGraph =
540 new Hashtable<Descriptor, ReachGraph>();
542 pm = new PointerMethod();
544 fc2enclosing = new Hashtable<FlatCall, Descriptor>();
549 // this analysis generates a disjoint reachability
550 // graph for every reachable method in the program
551 public DisjointAnalysis( State s,
556 ) throws java.io.IOException {
557 init( s, tu, cg, l, ar );
560 protected void init( State state,
564 ArrayReferencees arrayReferencees
565 ) throws java.io.IOException {
567 analysisComplete = false;
570 this.typeUtil = typeUtil;
571 this.callGraph = callGraph;
572 this.liveness = liveness;
573 this.arrayReferencees = arrayReferencees;
574 this.allocationDepth = state.DISJOINTALLOCDEPTH;
575 this.releaseMode = state.DISJOINTRELEASEMODE;
576 this.determinismDesired = state.DISJOINTDETERMINISM;
578 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
579 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL;
581 this.takeDebugSnapshots = state.DISJOINTSNAPSYMBOL != null;
582 this.descSymbolDebug = state.DISJOINTSNAPSYMBOL;
583 this.visitStartCapture = state.DISJOINTSNAPVISITTOSTART;
584 this.numVisitsToCapture = state.DISJOINTSNAPNUMVISITS;
585 this.stopAfterCapture = state.DISJOINTSNAPSTOPAFTER;
586 this.snapVisitCounter = 1; // count visits from 1 (user will write 1, means 1st visit)
587 this.snapNodeCounter = 0; // count nodes from 0
590 state.DISJOINTDVISITSTACK ||
591 state.DISJOINTDVISITPQUE ||
592 state.DISJOINTDVISITSTACKEESONTOP;
593 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITPQUE);
594 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITSTACKEESONTOP);
595 assert !(state.DISJOINTDVISITPQUE && state.DISJOINTDVISITSTACKEESONTOP);
597 // set some static configuration for ReachGraphs
598 ReachGraph.allocationDepth = allocationDepth;
599 ReachGraph.typeUtil = typeUtil;
601 ReachGraph.debugCallSiteVisitStartCapture
602 = state.DISJOINTDEBUGCALLVISITTOSTART;
604 ReachGraph.debugCallSiteNumVisitsToCapture
605 = state.DISJOINTDEBUGCALLNUMVISITS;
607 ReachGraph.debugCallSiteStopAfter
608 = state.DISJOINTDEBUGCALLSTOPAFTER;
610 ReachGraph.debugCallSiteVisitCounter
611 = 0; // count visits from 1, is incremented before first visit
615 allocateStructures();
617 double timeStartAnalysis = (double) System.nanoTime();
619 // start interprocedural fixed-point computation
621 analysisComplete=true;
623 double timeEndAnalysis = (double) System.nanoTime();
624 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
625 String treport = String.format( "The reachability analysis took %.3f sec.", dt );
626 String justtime = String.format( "%.2f", dt );
627 System.out.println( treport );
629 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
633 if( state.DISJOINTWRITEIHMS ) {
637 if( state.DISJOINTWRITEINITCONTEXTS ) {
638 writeInitialContexts();
641 if( state.DISJOINTALIASFILE != null ) {
643 writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
645 writeAllSharingJava(state.DISJOINTALIASFILE,
648 state.DISJOINTALIASTAB,
656 protected boolean moreDescriptorsToVisit() {
657 if( state.DISJOINTDVISITSTACK ||
658 state.DISJOINTDVISITSTACKEESONTOP
660 return !descriptorsToVisitStack.isEmpty();
662 } else if( state.DISJOINTDVISITPQUE ) {
663 return !descriptorsToVisitQ.isEmpty();
666 throw new Error( "Neither descriptor visiting mode set" );
670 // fixed-point computation over the call graph--when a
671 // method's callees are updated, it must be reanalyzed
672 protected void analyzeMethods() throws java.io.IOException {
674 // task or non-task (java) mode determines what the roots
675 // of the call chain are, and establishes the set of methods
676 // reachable from the roots that will be analyzed
679 System.out.println( "Bamboo mode..." );
681 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
682 while( taskItr.hasNext() ) {
683 TaskDescriptor td = (TaskDescriptor) taskItr.next();
684 if( !descriptorsToAnalyze.contains( td ) ) {
685 // add all methods transitively reachable from the
687 descriptorsToAnalyze.add( td );
688 descriptorsToAnalyze.addAll( callGraph.getAllMethods( td ) );
693 System.out.println( "Java mode..." );
695 // add all methods transitively reachable from the
696 // source's main to set for analysis
697 mdSourceEntry = typeUtil.getMain();
698 descriptorsToAnalyze.add( mdSourceEntry );
699 descriptorsToAnalyze.addAll( callGraph.getAllMethods( mdSourceEntry ) );
701 // fabricate an empty calling context that will call
702 // the source's main, but call graph doesn't know
703 // about it, so explicitly add it
704 makeAnalysisEntryMethod( mdSourceEntry );
705 descriptorsToAnalyze.add( mdAnalysisEntry );
709 // now, depending on the interprocedural mode for visiting
710 // methods, set up the needed data structures
712 if( state.DISJOINTDVISITPQUE ) {
714 // topologically sort according to the call graph so
715 // leaf calls are last, helps build contexts up first
716 LinkedList<Descriptor> sortedDescriptors =
717 topologicalSort( descriptorsToAnalyze );
719 // add sorted descriptors to priority queue, and duplicate
720 // the queue as a set for efficiently testing whether some
721 // method is marked for analysis
723 Iterator<Descriptor> dItr;
725 // for the priority queue, give items at the head
726 // of the sorted list a low number (highest priority)
727 while( !sortedDescriptors.isEmpty() ) {
728 Descriptor d = sortedDescriptors.removeFirst();
729 mapDescriptorToPriority.put( d, new Integer( p ) );
730 descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
731 descriptorsToVisitSet.add( d );
735 } else if( state.DISJOINTDVISITSTACK ||
736 state.DISJOINTDVISITSTACKEESONTOP
738 // if we're doing the stack scheme, just throw the root
739 // method or tasks on the stack
741 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
742 while( taskItr.hasNext() ) {
743 TaskDescriptor td = (TaskDescriptor) taskItr.next();
744 descriptorsToVisitStack.add( td );
745 descriptorsToVisitSet.add( td );
749 descriptorsToVisitStack.add( mdAnalysisEntry );
750 descriptorsToVisitSet.add( mdAnalysisEntry );
754 throw new Error( "Unknown method scheduling mode" );
758 // analyze scheduled methods until there are no more to visit
759 while( moreDescriptorsToVisit() ) {
762 if( state.DISJOINTDVISITSTACK ||
763 state.DISJOINTDVISITSTACKEESONTOP
765 d = descriptorsToVisitStack.pop();
767 } else if( state.DISJOINTDVISITPQUE ) {
768 d = descriptorsToVisitQ.poll().getDescriptor();
771 assert descriptorsToVisitSet.contains( d );
772 descriptorsToVisitSet.remove( d );
774 // because the task or method descriptor just extracted
775 // was in the "to visit" set it either hasn't been analyzed
776 // yet, or some method that it depends on has been
777 // updated. Recompute a complete reachability graph for
778 // this task/method and compare it to any previous result.
779 // If there is a change detected, add any methods/tasks
780 // that depend on this one to the "to visit" set.
782 System.out.println( "Analyzing " + d );
784 if( state.DISJOINTDVISITSTACKEESONTOP ) {
785 assert calleesToEnqueue.isEmpty();
788 ReachGraph rg = analyzeMethod( d );
789 ReachGraph rgPrev = getPartial( d );
791 if( !rg.equals( rgPrev ) ) {
794 if( state.DISJOINTDEBUGSCHEDULING ) {
795 System.out.println( " complete graph changed, scheduling callers for analysis:" );
798 // results for d changed, so enqueue dependents
799 // of d for further analysis
800 Iterator<Descriptor> depsItr = getDependents( d ).iterator();
801 while( depsItr.hasNext() ) {
802 Descriptor dNext = depsItr.next();
805 if( state.DISJOINTDEBUGSCHEDULING ) {
806 System.out.println( " "+dNext );
811 // whether or not the method under analysis changed,
812 // we may have some callees that are scheduled for
813 // more analysis, and they should go on the top of
814 // the stack now (in other method-visiting modes they
815 // are already enqueued at this point
816 if( state.DISJOINTDVISITSTACKEESONTOP ) {
817 Iterator<Descriptor> depsItr = calleesToEnqueue.iterator();
818 while( depsItr.hasNext() ) {
819 Descriptor dNext = depsItr.next();
822 calleesToEnqueue.clear();
828 protected ReachGraph analyzeMethod( Descriptor d )
829 throws java.io.IOException {
831 // get the flat code for this descriptor
833 if( d == mdAnalysisEntry ) {
834 fm = fmAnalysisEntry;
836 fm = state.getMethodFlat( d );
838 pm.analyzeMethod( fm );
840 // intraprocedural work set
841 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
842 flatNodesToVisit.add( fm );
844 // if determinism is desired by client, shadow the
845 // set with a queue to make visit order deterministic
846 Queue<FlatNode> flatNodesToVisitQ = null;
847 if( determinismDesired ) {
848 flatNodesToVisitQ = new LinkedList<FlatNode>();
849 flatNodesToVisitQ.add( fm );
852 // mapping of current partial results
853 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
854 new Hashtable<FlatNode, ReachGraph>();
856 // the set of return nodes partial results that will be combined as
857 // the final, conservative approximation of the entire method
858 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
860 while( !flatNodesToVisit.isEmpty() ) {
863 if( determinismDesired ) {
864 assert !flatNodesToVisitQ.isEmpty();
865 fn = flatNodesToVisitQ.remove();
867 fn = flatNodesToVisit.iterator().next();
869 flatNodesToVisit.remove( fn );
871 // effect transfer function defined by this node,
872 // then compare it to the old graph at this node
873 // to see if anything was updated.
875 ReachGraph rg = new ReachGraph();
876 TaskDescriptor taskDesc;
877 if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null){
878 if(mapDescriptorToReachGraph.containsKey(taskDesc)){
879 // retrieve existing reach graph if it is not first time
880 rg=mapDescriptorToReachGraph.get(taskDesc);
882 // create initial reach graph for a task
883 rg=createInitialTaskReachGraph((FlatMethod)fn);
885 mapDescriptorToReachGraph.put(taskDesc, rg);
889 // start by merging all node's parents' graphs
890 for( int i = 0; i < pm.numPrev(fn); ++i ) {
891 FlatNode pn = pm.getPrev(fn,i);
892 if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
893 ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
894 rg.merge( rgParent );
899 if( takeDebugSnapshots &&
900 d.getSymbol().equals( descSymbolDebug )
902 debugSnapshot( rg, fn, true );
906 // modify rg with appropriate transfer function
907 rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
910 if( takeDebugSnapshots &&
911 d.getSymbol().equals( descSymbolDebug )
913 debugSnapshot( rg, fn, false );
918 // if the results of the new graph are different from
919 // the current graph at this node, replace the graph
920 // with the update and enqueue the children
921 ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
922 if( !rg.equals( rgPrev ) ) {
923 mapFlatNodeToReachGraph.put( fn, rg );
925 for( int i = 0; i < pm.numNext( fn ); i++ ) {
926 FlatNode nn = pm.getNext( fn, i );
928 flatNodesToVisit.add( nn );
929 if( determinismDesired ) {
930 flatNodesToVisitQ.add( nn );
937 // end by merging all return nodes into a complete
938 // reach graph that represents all possible heap
939 // states after the flat method returns
940 ReachGraph completeGraph = new ReachGraph();
942 assert !setReturns.isEmpty();
943 Iterator retItr = setReturns.iterator();
944 while( retItr.hasNext() ) {
945 FlatReturnNode frn = (FlatReturnNode) retItr.next();
947 assert mapFlatNodeToReachGraph.containsKey( frn );
948 ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
950 completeGraph.merge( rgRet );
954 if( takeDebugSnapshots &&
955 d.getSymbol().equals( descSymbolDebug )
957 // increment that we've visited the debug snap
958 // method, and reset the node counter
959 System.out.println( " @@@ debug snap at visit "+snapVisitCounter );
963 if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
966 System.out.println( "!!! Stopping analysis after debug snap captures. !!!" );
972 return completeGraph;
977 analyzeFlatNode( Descriptor d,
978 FlatMethod fmContaining,
980 HashSet<FlatReturnNode> setRetNodes,
982 ) throws java.io.IOException {
985 // any variables that are no longer live should be
986 // nullified in the graph to reduce edges
987 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
994 // use node type to decide what transfer function
995 // to apply to the reachability graph
996 switch( fn.kind() ) {
998 case FKind.FlatMethod: {
999 // construct this method's initial heap model (IHM)
1000 // since we're working on the FlatMethod, we know
1001 // the incoming ReachGraph 'rg' is empty
1003 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1004 getIHMcontributions( d );
1006 Set entrySet = heapsFromCallers.entrySet();
1007 Iterator itr = entrySet.iterator();
1008 while( itr.hasNext() ) {
1009 Map.Entry me = (Map.Entry) itr.next();
1010 FlatCall fc = (FlatCall) me.getKey();
1011 ReachGraph rgContrib = (ReachGraph) me.getValue();
1013 assert fc.getMethod().equals( d );
1015 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 // map a FlatCall to its enclosing method/task descriptor
1186 // so we can write that info out later
1187 fc2enclosing.put( fc, mdCaller );
1189 if( state.DISJOINTDEBUGSCHEDULING ) {
1190 System.out.println( " context changed, scheduling callee: "+mdCallee );
1193 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1194 calleesToEnqueue.add( mdCallee );
1196 enqueue( mdCallee );
1202 // the transformation for a call site should update the
1203 // current heap abstraction with any effects from the callee,
1204 // or if the method is virtual, the effects from any possible
1205 // callees, so find the set of callees...
1206 Set<MethodDescriptor> setPossibleCallees;
1207 if( determinismDesired ) {
1208 // use an ordered set
1209 setPossibleCallees = new TreeSet<MethodDescriptor>( dComp );
1211 // otherwise use a speedy hashset
1212 setPossibleCallees = new HashSet<MethodDescriptor>();
1215 if( mdCallee.isStatic() ) {
1216 setPossibleCallees.add( mdCallee );
1218 TypeDescriptor typeDesc = fc.getThis().getType();
1219 setPossibleCallees.addAll( callGraph.getMethods( mdCallee,
1224 ReachGraph rgMergeOfEffects = new ReachGraph();
1226 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
1227 while( mdItr.hasNext() ) {
1228 MethodDescriptor mdPossible = mdItr.next();
1229 FlatMethod fmPossible = state.getMethodFlat( mdPossible );
1231 addDependent( mdPossible, // callee
1234 // don't alter the working graph (rg) until we compute a
1235 // result for every possible callee, merge them all together,
1236 // then set rg to that
1237 ReachGraph rgCopy = new ReachGraph();
1240 ReachGraph rgEffect = getPartial( mdPossible );
1242 if( rgEffect == null ) {
1243 // if this method has never been analyzed just schedule it
1244 // for analysis and skip over this call site for now
1245 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1246 calleesToEnqueue.add( mdPossible );
1248 enqueue( mdPossible );
1251 if( state.DISJOINTDEBUGSCHEDULING ) {
1252 System.out.println( " callee hasn't been analyzed, scheduling: "+mdPossible );
1257 rgCopy.resolveMethodCall( fc,
1260 callerNodeIDsCopiedToCallee,
1265 rgMergeOfEffects.merge( rgCopy );
1270 System.out.println( "$$$ Exiting after requested captures of call site. $$$" );
1275 // now that we've taken care of building heap models for
1276 // callee analysis, finish this transformation
1277 rg = rgMergeOfEffects;
1281 case FKind.FlatReturnNode:
1282 FlatReturnNode frn = (FlatReturnNode) fn;
1283 rhs = frn.getReturnTemp();
1284 if( rhs != null && shouldAnalysisTrack( rhs.getType() ) ) {
1285 rg.assignReturnEqualToTemp( rhs );
1287 setRetNodes.add( frn );
1293 // dead variables were removed before the above transfer function
1294 // was applied, so eliminate heap regions and edges that are no
1295 // longer part of the abstractly-live heap graph, and sweep up
1296 // and reachability effects that are altered by the reduction
1297 //rg.abstractGarbageCollect();
1301 // back edges are strictly monotonic
1302 if( pm.isBackEdge( fn ) ) {
1303 ReachGraph rgPrevResult = mapBackEdgeToMonotone.get( fn );
1304 rg.merge( rgPrevResult );
1305 mapBackEdgeToMonotone.put( fn, rg );
1308 // at this point rg should be the correct update
1309 // by an above transfer function, or untouched if
1310 // the flat node type doesn't affect the heap
1316 // this method should generate integers strictly greater than zero!
1317 // special "shadow" regions are made from a heap region by negating
1319 static public Integer generateUniqueHeapRegionNodeID() {
1321 return new Integer( uniqueIDcount );
1326 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
1327 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
1328 if( fdElement == null ) {
1329 fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
1331 arrayElementFieldName,
1334 mapTypeToArrayField.put( tdElement, fdElement );
1341 private void writeFinalGraphs() {
1342 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1343 Iterator itr = entrySet.iterator();
1344 while( itr.hasNext() ) {
1345 Map.Entry me = (Map.Entry) itr.next();
1346 Descriptor d = (Descriptor) me.getKey();
1347 ReachGraph rg = (ReachGraph) me.getValue();
1349 rg.writeGraph( "COMPLETE"+d,
1350 true, // write labels (variables)
1351 true, // selectively hide intermediate temp vars
1352 true, // prune unreachable heap regions
1353 false, // hide reachability altogether
1354 true, // hide subset reachability states
1355 true, // hide predicates
1356 false ); // hide edge taints
1360 private void writeFinalIHMs() {
1361 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1362 while( d2IHMsItr.hasNext() ) {
1363 Map.Entry me1 = (Map.Entry) d2IHMsItr.next();
1364 Descriptor d = (Descriptor) me1.getKey();
1365 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1367 Iterator fc2rgItr = IHMs.entrySet().iterator();
1368 while( fc2rgItr.hasNext() ) {
1369 Map.Entry me2 = (Map.Entry) fc2rgItr.next();
1370 FlatCall fc = (FlatCall) me2.getKey();
1371 ReachGraph rg = (ReachGraph) me2.getValue();
1373 rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc2enclosing.get( fc )+fc,
1374 true, // write labels (variables)
1375 true, // selectively hide intermediate temp vars
1376 true, // hide reachability altogether
1377 true, // prune unreachable heap regions
1378 true, // hide subset reachability states
1379 false, // hide predicates
1380 true ); // hide edge taints
1385 private void writeInitialContexts() {
1386 Set entrySet = mapDescriptorToInitialContext.entrySet();
1387 Iterator itr = entrySet.iterator();
1388 while( itr.hasNext() ) {
1389 Map.Entry me = (Map.Entry) itr.next();
1390 Descriptor d = (Descriptor) me.getKey();
1391 ReachGraph rg = (ReachGraph) me.getValue();
1393 rg.writeGraph( "INITIAL"+d,
1394 true, // write labels (variables)
1395 true, // selectively hide intermediate temp vars
1396 true, // prune unreachable heap regions
1397 false, // hide all reachability
1398 true, // hide subset reachability states
1399 true, // hide predicates
1400 false );// hide edge taints
1405 protected ReachGraph getPartial( Descriptor d ) {
1406 return mapDescriptorToCompleteReachGraph.get( d );
1409 protected void setPartial( Descriptor d, ReachGraph rg ) {
1410 mapDescriptorToCompleteReachGraph.put( d, rg );
1412 // when the flag for writing out every partial
1413 // result is set, we should spit out the graph,
1414 // but in order to give it a unique name we need
1415 // to track how many partial results for this
1416 // descriptor we've already written out
1417 if( writeAllIncrementalDOTs ) {
1418 if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1419 mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1421 Integer n = mapDescriptorToNumUpdates.get( d );
1423 rg.writeGraph( d+"COMPLETE"+String.format( "%05d", n ),
1424 true, // write labels (variables)
1425 true, // selectively hide intermediate temp vars
1426 true, // prune unreachable heap regions
1427 false, // hide all reachability
1428 true, // hide subset reachability states
1429 false, // hide predicates
1430 false); // hide edge taints
1432 mapDescriptorToNumUpdates.put( d, n + 1 );
1438 // return just the allocation site associated with one FlatNew node
1439 protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1441 if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1442 AllocSite as = AllocSite.factory( allocationDepth,
1444 fnew.getDisjointId(),
1448 // the newest nodes are single objects
1449 for( int i = 0; i < allocationDepth; ++i ) {
1450 Integer id = generateUniqueHeapRegionNodeID();
1451 as.setIthOldest( i, id );
1452 mapHrnIdToAllocSite.put( id, as );
1455 // the oldest node is a summary node
1456 as.setSummary( generateUniqueHeapRegionNodeID() );
1458 mapFlatNewToAllocSite.put( fnew, as );
1461 return mapFlatNewToAllocSite.get( fnew );
1465 public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1466 // don't track primitive types, but an array
1467 // of primitives is heap memory
1468 if( type.isImmutable() ) {
1469 return type.isArray();
1472 // everything else is an object
1476 protected int numMethodsAnalyzed() {
1477 return descriptorsToAnalyze.size();
1484 // Take in source entry which is the program's compiled entry and
1485 // create a new analysis entry, a method that takes no parameters
1486 // and appears to allocate the command line arguments and call the
1487 // source entry with them. The purpose of this analysis entry is
1488 // to provide a top-level method context with no parameters left.
1489 protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1491 Modifiers mods = new Modifiers();
1492 mods.addModifier( Modifiers.PUBLIC );
1493 mods.addModifier( Modifiers.STATIC );
1495 TypeDescriptor returnType =
1496 new TypeDescriptor( TypeDescriptor.VOID );
1498 this.mdAnalysisEntry =
1499 new MethodDescriptor( mods,
1501 "analysisEntryMethod"
1504 TempDescriptor cmdLineArgs =
1505 new TempDescriptor( "args",
1506 mdSourceEntry.getParamType( 0 )
1510 new FlatNew( mdSourceEntry.getParamType( 0 ),
1515 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1516 sourceEntryArgs[0] = cmdLineArgs;
1519 new FlatCall( mdSourceEntry,
1525 FlatReturnNode frn = new FlatReturnNode( null );
1527 FlatExit fe = new FlatExit();
1529 this.fmAnalysisEntry =
1530 new FlatMethod( mdAnalysisEntry,
1534 this.fmAnalysisEntry.addNext( fn );
1541 protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1543 Set<Descriptor> discovered;
1545 if( determinismDesired ) {
1546 // use an ordered set
1547 discovered = new TreeSet<Descriptor>( dComp );
1549 // otherwise use a speedy hashset
1550 discovered = new HashSet<Descriptor>();
1553 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
1555 Iterator<Descriptor> itr = toSort.iterator();
1556 while( itr.hasNext() ) {
1557 Descriptor d = itr.next();
1559 if( !discovered.contains( d ) ) {
1560 dfsVisit( d, toSort, sorted, discovered );
1567 // While we're doing DFS on call graph, remember
1568 // dependencies for efficient queuing of methods
1569 // during interprocedural analysis:
1571 // a dependent of a method decriptor d for this analysis is:
1572 // 1) a method or task that invokes d
1573 // 2) in the descriptorsToAnalyze set
1574 protected void dfsVisit( Descriptor d,
1575 Set <Descriptor> toSort,
1576 LinkedList<Descriptor> sorted,
1577 Set <Descriptor> discovered ) {
1578 discovered.add( d );
1580 // only methods have callers, tasks never do
1581 if( d instanceof MethodDescriptor ) {
1583 MethodDescriptor md = (MethodDescriptor) d;
1585 // the call graph is not aware that we have a fabricated
1586 // analysis entry that calls the program source's entry
1587 if( md == mdSourceEntry ) {
1588 if( !discovered.contains( mdAnalysisEntry ) ) {
1589 addDependent( mdSourceEntry, // callee
1590 mdAnalysisEntry // caller
1592 dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1596 // otherwise call graph guides DFS
1597 Iterator itr = callGraph.getCallerSet( md ).iterator();
1598 while( itr.hasNext() ) {
1599 Descriptor dCaller = (Descriptor) itr.next();
1601 // only consider callers in the original set to analyze
1602 if( !toSort.contains( dCaller ) ) {
1606 if( !discovered.contains( dCaller ) ) {
1607 addDependent( md, // callee
1611 dfsVisit( dCaller, toSort, sorted, discovered );
1616 // for leaf-nodes last now!
1617 sorted.addLast( d );
1621 protected void enqueue( Descriptor d ) {
1623 if( !descriptorsToVisitSet.contains( d ) ) {
1625 if( state.DISJOINTDVISITSTACK ||
1626 state.DISJOINTDVISITSTACKEESONTOP
1628 descriptorsToVisitStack.add( d );
1630 } else if( state.DISJOINTDVISITPQUE ) {
1631 Integer priority = mapDescriptorToPriority.get( d );
1632 descriptorsToVisitQ.add( new DescriptorQWrapper( priority,
1637 descriptorsToVisitSet.add( d );
1642 // a dependent of a method decriptor d for this analysis is:
1643 // 1) a method or task that invokes d
1644 // 2) in the descriptorsToAnalyze set
1645 protected void addDependent( Descriptor callee, Descriptor caller ) {
1646 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1647 if( deps == null ) {
1648 deps = new HashSet<Descriptor>();
1651 mapDescriptorToSetDependents.put( callee, deps );
1654 protected Set<Descriptor> getDependents( Descriptor callee ) {
1655 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1656 if( deps == null ) {
1657 deps = new HashSet<Descriptor>();
1658 mapDescriptorToSetDependents.put( callee, deps );
1664 public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
1666 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1667 mapDescriptorToIHMcontributions.get( d );
1669 if( heapsFromCallers == null ) {
1670 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
1671 mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
1674 return heapsFromCallers;
1677 public ReachGraph getIHMcontribution( Descriptor d,
1680 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1681 getIHMcontributions( d );
1683 if( !heapsFromCallers.containsKey( fc ) ) {
1687 return heapsFromCallers.get( fc );
1691 public void addIHMcontribution( Descriptor d,
1695 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1696 getIHMcontributions( d );
1698 heapsFromCallers.put( fc, rg );
1702 private AllocSite createParameterAllocSite( ReachGraph rg,
1703 TempDescriptor tempDesc,
1709 flatNew = new FlatNew( tempDesc.getType(), // type
1710 tempDesc, // param temp
1711 false, // global alloc?
1712 "param"+tempDesc // disjoint site ID string
1715 flatNew = new FlatNew( tempDesc.getType(), // type
1716 tempDesc, // param temp
1717 false, // global alloc?
1718 null // disjoint site ID string
1722 // create allocation site
1723 AllocSite as = AllocSite.factory( allocationDepth,
1725 flatNew.getDisjointId(),
1728 for (int i = 0; i < allocationDepth; ++i) {
1729 Integer id = generateUniqueHeapRegionNodeID();
1730 as.setIthOldest(i, id);
1731 mapHrnIdToAllocSite.put(id, as);
1733 // the oldest node is a summary node
1734 as.setSummary( generateUniqueHeapRegionNodeID() );
1742 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc){
1744 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
1745 if(!typeDesc.isImmutable()){
1746 ClassDescriptor classDesc = typeDesc.getClassDesc();
1747 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1748 FieldDescriptor field = (FieldDescriptor) it.next();
1749 TypeDescriptor fieldType = field.getType();
1750 if (shouldAnalysisTrack( fieldType )) {
1751 fieldSet.add(field);
1759 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha ){
1761 int dimCount=fd.getType().getArrayCount();
1762 HeapRegionNode prevNode=null;
1763 HeapRegionNode arrayEntryNode=null;
1764 for(int i=dimCount;i>0;i--){
1765 TypeDescriptor typeDesc=fd.getType().dereference();//hack to get instance of type desc
1766 typeDesc.setArrayCount(i);
1767 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
1768 HeapRegionNode hrnSummary ;
1769 if(!mapToExistingNode.containsKey(typeDesc)){
1774 as = createParameterAllocSite(rg, tempDesc, false);
1776 // make a new reference to allocated node
1778 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1779 false, // single object?
1781 false, // out-of-context?
1782 as.getType(), // type
1783 as, // allocation site
1784 alpha, // inherent reach
1785 alpha, // current reach
1786 ExistPredSet.factory(rg.predTrue), // predicates
1787 tempDesc.toString() // description
1789 rg.id2hrn.put(as.getSummary(),hrnSummary);
1791 mapToExistingNode.put(typeDesc, hrnSummary);
1793 hrnSummary=mapToExistingNode.get(typeDesc);
1797 // make a new reference between new summary node and source
1798 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1801 fd.getSymbol(), // field name
1803 ExistPredSet.factory(rg.predTrue), // predicates
1807 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1808 prevNode=hrnSummary;
1809 arrayEntryNode=hrnSummary;
1811 // make a new reference between summary nodes of array
1812 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1815 arrayElementFieldName, // field name
1817 ExistPredSet.factory(rg.predTrue), // predicates
1821 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1822 prevNode=hrnSummary;
1827 // create a new obj node if obj has at least one non-primitive field
1828 TypeDescriptor type=fd.getType();
1829 if(getFieldSetTobeAnalyzed(type).size()>0){
1830 TypeDescriptor typeDesc=type.dereference();
1831 typeDesc.setArrayCount(0);
1832 if(!mapToExistingNode.containsKey(typeDesc)){
1833 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
1834 AllocSite as = createParameterAllocSite(rg, tempDesc, false);
1835 // make a new reference to allocated node
1836 HeapRegionNode hrnSummary =
1837 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1838 false, // single object?
1840 false, // out-of-context?
1842 as, // allocation site
1843 alpha, // inherent reach
1844 alpha, // current reach
1845 ExistPredSet.factory(rg.predTrue), // predicates
1846 tempDesc.toString() // description
1848 rg.id2hrn.put(as.getSummary(),hrnSummary);
1849 mapToExistingNode.put(typeDesc, hrnSummary);
1850 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1853 arrayElementFieldName, // field name
1855 ExistPredSet.factory(rg.predTrue), // predicates
1858 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1859 prevNode=hrnSummary;
1861 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
1862 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null){
1863 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1866 arrayElementFieldName, // field name
1868 ExistPredSet.factory(rg.predTrue), // predicates
1871 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1873 prevNode=hrnSummary;
1877 map.put(arrayEntryNode, prevNode);
1878 return arrayEntryNode;
1881 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
1882 ReachGraph rg = new ReachGraph();
1883 TaskDescriptor taskDesc = fm.getTask();
1885 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
1886 Descriptor paramDesc = taskDesc.getParameter(idx);
1887 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
1889 // setup data structure
1890 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
1891 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
1892 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
1893 new Hashtable<TypeDescriptor, HeapRegionNode>();
1894 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
1895 new Hashtable<HeapRegionNode, HeapRegionNode>();
1896 Set<String> doneSet = new HashSet<String>();
1898 TempDescriptor tempDesc = fm.getParameter(idx);
1900 AllocSite as = createParameterAllocSite(rg, tempDesc, true);
1901 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
1902 Integer idNewest = as.getIthOldest(0);
1903 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
1905 // make a new reference to allocated node
1906 RefEdge edgeNew = new RefEdge(lnX, // source
1908 taskDesc.getParamType(idx), // type
1910 hrnNewest.getAlpha(), // beta
1911 ExistPredSet.factory(rg.predTrue), // predicates
1914 rg.addRefEdge(lnX, hrnNewest, edgeNew);
1916 // set-up a work set for class field
1917 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
1918 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1919 FieldDescriptor fd = (FieldDescriptor) it.next();
1920 TypeDescriptor fieldType = fd.getType();
1921 if (shouldAnalysisTrack( fieldType )) {
1922 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
1923 newMap.put(hrnNewest, fd);
1924 workSet.add(newMap);
1928 int uniqueIdentifier = 0;
1929 while (!workSet.isEmpty()) {
1930 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
1932 workSet.remove(map);
1934 Set<HeapRegionNode> key = map.keySet();
1935 HeapRegionNode srcHRN = key.iterator().next();
1936 FieldDescriptor fd = map.get(srcHRN);
1937 TypeDescriptor type = fd.getType();
1938 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
1940 if (!doneSet.contains(doneSetIdentifier)) {
1941 doneSet.add(doneSetIdentifier);
1942 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
1943 // create new summary Node
1944 TempDescriptor td = new TempDescriptor("temp"
1945 + uniqueIdentifier, type);
1947 AllocSite allocSite;
1948 if(type.equals(paramTypeDesc)){
1949 //corresponding allocsite has already been created for a parameter variable.
1952 allocSite = createParameterAllocSite(rg, td, false);
1954 String strDesc = allocSite.toStringForDOT()
1956 TypeDescriptor allocType=allocSite.getType();
1958 HeapRegionNode hrnSummary;
1959 if(allocType.isArray() && allocType.getArrayCount()>0){
1960 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
1963 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
1964 false, // single object?
1966 false, // out-of-context?
1967 allocSite.getType(), // type
1968 allocSite, // allocation site
1969 hrnNewest.getAlpha(), // inherent reach
1970 hrnNewest.getAlpha(), // current reach
1971 ExistPredSet.factory(rg.predTrue), // predicates
1972 strDesc // description
1974 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
1976 // make a new reference to summary node
1977 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1980 fd.getSymbol(), // field name
1981 hrnNewest.getAlpha(), // beta
1982 ExistPredSet.factory(rg.predTrue), // predicates
1986 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1990 mapTypeToExistingSummaryNode.put(type, hrnSummary);
1992 // set-up a work set for fields of the class
1993 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
1994 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
1996 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
1998 HeapRegionNode newDstHRN;
1999 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)){
2000 //related heap region node is already exsited.
2001 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
2003 newDstHRN=hrnSummary;
2005 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
2006 if(!doneSet.contains(doneSetIdentifier)){
2007 // add new work item
2008 HashMap<HeapRegionNode, FieldDescriptor> newMap =
2009 new HashMap<HeapRegionNode, FieldDescriptor>();
2010 newMap.put(newDstHRN, fieldDescriptor);
2011 workSet.add(newMap);
2016 // if there exists corresponding summary node
2017 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
2019 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2021 fd.getType(), // type
2022 fd.getSymbol(), // field name
2023 srcHRN.getAlpha(), // beta
2024 ExistPredSet.factory(rg.predTrue), // predicates
2027 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
2033 // debugSnapshot(rg, fm, true);
2037 // return all allocation sites in the method (there is one allocation
2038 // site per FlatNew node in a method)
2039 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
2040 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
2041 buildAllocationSiteSet(d);
2044 return mapDescriptorToAllocSiteSet.get(d);
2048 private void buildAllocationSiteSet(Descriptor d) {
2049 HashSet<AllocSite> s = new HashSet<AllocSite>();
2052 if( d instanceof MethodDescriptor ) {
2053 fm = state.getMethodFlat( (MethodDescriptor) d);
2055 assert d instanceof TaskDescriptor;
2056 fm = state.getMethodFlat( (TaskDescriptor) d);
2058 pm.analyzeMethod(fm);
2060 // visit every node in this FlatMethod's IR graph
2061 // and make a set of the allocation sites from the
2062 // FlatNew node's visited
2063 HashSet<FlatNode> visited = new HashSet<FlatNode>();
2064 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
2067 while( !toVisit.isEmpty() ) {
2068 FlatNode n = toVisit.iterator().next();
2070 if( n instanceof FlatNew ) {
2071 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
2077 for( int i = 0; i < pm.numNext(n); ++i ) {
2078 FlatNode child = pm.getNext(n, i);
2079 if( !visited.contains(child) ) {
2085 mapDescriptorToAllocSiteSet.put(d, s);
2088 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
2090 HashSet<AllocSite> out = new HashSet<AllocSite>();
2091 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2092 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2096 while (!toVisit.isEmpty()) {
2097 Descriptor d = toVisit.iterator().next();
2101 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2102 Iterator asItr = asSet.iterator();
2103 while (asItr.hasNext()) {
2104 AllocSite as = (AllocSite) asItr.next();
2105 if (as.getDisjointAnalysisId() != null) {
2110 // enqueue callees of this method to be searched for
2111 // allocation sites also
2112 Set callees = callGraph.getCalleeSet(d);
2113 if (callees != null) {
2114 Iterator methItr = callees.iterator();
2115 while (methItr.hasNext()) {
2116 MethodDescriptor md = (MethodDescriptor) methItr.next();
2118 if (!visited.contains(md)) {
2129 private HashSet<AllocSite>
2130 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
2132 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
2133 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2134 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2138 // traverse this task and all methods reachable from this task
2139 while( !toVisit.isEmpty() ) {
2140 Descriptor d = toVisit.iterator().next();
2144 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2145 Iterator asItr = asSet.iterator();
2146 while( asItr.hasNext() ) {
2147 AllocSite as = (AllocSite) asItr.next();
2148 TypeDescriptor typed = as.getType();
2149 if( typed != null ) {
2150 ClassDescriptor cd = typed.getClassDesc();
2151 if( cd != null && cd.hasFlags() ) {
2157 // enqueue callees of this method to be searched for
2158 // allocation sites also
2159 Set callees = callGraph.getCalleeSet(d);
2160 if( callees != null ) {
2161 Iterator methItr = callees.iterator();
2162 while( methItr.hasNext() ) {
2163 MethodDescriptor md = (MethodDescriptor) methItr.next();
2165 if( !visited.contains(md) ) {
2178 // get successive captures of the analysis state, use compiler
2180 boolean takeDebugSnapshots = false;
2181 String descSymbolDebug = null;
2182 boolean stopAfterCapture = false;
2183 int snapVisitCounter = 0;
2184 int snapNodeCounter = 0;
2185 int visitStartCapture = 0;
2186 int numVisitsToCapture = 0;
2189 void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
2190 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2198 if( snapVisitCounter >= visitStartCapture ) {
2199 System.out.println( " @@@ snapping visit="+snapVisitCounter+
2200 ", node="+snapNodeCounter+
2204 graphName = String.format( "snap%03d_%04din",
2208 graphName = String.format( "snap%03d_%04dout",
2213 graphName = graphName + fn;
2215 rg.writeGraph( graphName,
2216 true, // write labels (variables)
2217 true, // selectively hide intermediate temp vars
2218 true, // prune unreachable heap regions
2219 false, // hide reachability
2220 true, // hide subset reachability states
2221 true, // hide predicates
2222 false );// hide edge taints