1 package Analysis.Disjoint;
3 import Analysis.CallGraph.*;
4 import Analysis.Liveness;
5 import Analysis.ArrayReferencees;
6 import Analysis.RBlockRelationAnalysis;
9 import IR.Tree.Modifiers;
14 public class DisjointAnalysis {
16 ///////////////////////////////////////////
18 // Public interface to discover possible
19 // aliases in the program under analysis
21 ///////////////////////////////////////////
23 public HashSet<AllocSite>
24 getFlaggedAllocationSitesReachableFromTask(TaskDescriptor td) {
25 checkAnalysisComplete();
26 return getFlaggedAllocationSitesReachableFromTaskPRIVATE(td);
29 public AllocSite getAllocationSiteFromFlatNew(FlatNew fn) {
30 checkAnalysisComplete();
31 return getAllocSiteFromFlatNewPRIVATE(fn);
34 public AllocSite getAllocationSiteFromHeapRegionNodeID(Integer id) {
35 checkAnalysisComplete();
36 return mapHrnIdToAllocSite.get(id);
39 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
42 checkAnalysisComplete();
43 ReachGraph rg=mapDescriptorToCompleteReachGraph.get(taskOrMethod);
44 FlatMethod fm=state.getMethodFlat(taskOrMethod);
46 return rg.mayReachSharedObjects(fm, paramIndex1, paramIndex2);
49 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
50 int paramIndex, AllocSite alloc) {
51 checkAnalysisComplete();
52 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
53 FlatMethod fm=state.getMethodFlat(taskOrMethod);
55 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
58 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
59 AllocSite alloc, int paramIndex) {
60 checkAnalysisComplete();
61 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
62 FlatMethod fm=state.getMethodFlat(taskOrMethod);
64 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
67 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
68 AllocSite alloc1, AllocSite alloc2) {
69 checkAnalysisComplete();
70 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
72 return rg.mayReachSharedObjects(alloc1, alloc2);
75 public String prettyPrintNodeSet(Set<HeapRegionNode> s) {
76 checkAnalysisComplete();
80 Iterator<HeapRegionNode> i = s.iterator();
82 HeapRegionNode n = i.next();
84 AllocSite as = n.getAllocSite();
86 out += " " + n.toString() + ",\n";
88 out += " " + n.toString() + ": " + as.toStringVerbose()
97 // use the methods given above to check every possible sharing class
98 // between task parameters and flagged allocation sites reachable
100 public void writeAllSharing(String outputFile,
103 boolean tabularOutput,
106 throws java.io.IOException {
107 checkAnalysisComplete();
109 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
111 if (!tabularOutput) {
112 bw.write("Conducting ownership analysis with allocation depth = "
113 + allocationDepth + "\n");
114 bw.write(timeReport + "\n");
119 // look through every task for potential sharing
120 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
121 while (taskItr.hasNext()) {
122 TaskDescriptor td = (TaskDescriptor) taskItr.next();
124 if (!tabularOutput) {
125 bw.write("\n---------" + td + "--------\n");
128 HashSet<AllocSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
130 Set<HeapRegionNode> common;
132 // for each task parameter, check for sharing classes with
133 // other task parameters and every allocation site
134 // reachable from this task
135 boolean foundSomeSharing = false;
137 FlatMethod fm = state.getMethodFlat(td);
138 for (int i = 0; i < fm.numParameters(); ++i) {
140 // skip parameters with types that cannot reference
142 if( !shouldAnalysisTrack( fm.getParameter( i ).getType() ) ) {
146 // for the ith parameter check for sharing classes to all
147 // higher numbered parameters
148 for (int j = i + 1; j < fm.numParameters(); ++j) {
150 // skip parameters with types that cannot reference
152 if( !shouldAnalysisTrack( fm.getParameter( j ).getType() ) ) {
157 common = hasPotentialSharing(td, i, j);
158 if (!common.isEmpty()) {
159 foundSomeSharing = true;
161 if (!tabularOutput) {
162 bw.write("Potential sharing between parameters " + i
163 + " and " + j + ".\n");
164 bw.write(prettyPrintNodeSet(common) + "\n");
169 // for the ith parameter, check for sharing classes against
170 // the set of allocation sites reachable from this
172 Iterator allocItr = allocSites.iterator();
173 while (allocItr.hasNext()) {
174 AllocSite as = (AllocSite) allocItr.next();
175 common = hasPotentialSharing(td, i, as);
176 if (!common.isEmpty()) {
177 foundSomeSharing = true;
179 if (!tabularOutput) {
180 bw.write("Potential sharing between parameter " + i
181 + " and " + as.getFlatNew() + ".\n");
182 bw.write(prettyPrintNodeSet(common) + "\n");
188 // for each allocation site check for sharing classes with
189 // other allocation sites in the context of execution
191 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
192 Iterator allocItr1 = allocSites.iterator();
193 while (allocItr1.hasNext()) {
194 AllocSite as1 = (AllocSite) allocItr1.next();
196 Iterator allocItr2 = allocSites.iterator();
197 while (allocItr2.hasNext()) {
198 AllocSite as2 = (AllocSite) allocItr2.next();
200 if (!outerChecked.contains(as2)) {
201 common = hasPotentialSharing(td, as1, as2);
203 if (!common.isEmpty()) {
204 foundSomeSharing = true;
206 if (!tabularOutput) {
207 bw.write("Potential sharing between "
208 + as1.getFlatNew() + " and "
209 + as2.getFlatNew() + ".\n");
210 bw.write(prettyPrintNodeSet(common) + "\n");
216 outerChecked.add(as1);
219 if (!foundSomeSharing) {
220 if (!tabularOutput) {
221 bw.write("No sharing between flagged objects in Task " + td
229 bw.write(" & " + numSharing + " & " + justTime + " & " + numLines
230 + " & " + numMethodsAnalyzed() + " \\\\\n");
232 bw.write("\nNumber sharing classes: "+numSharing);
238 // this version of writeAllSharing is for Java programs that have no tasks
239 public void writeAllSharingJava(String outputFile,
242 boolean tabularOutput,
245 throws java.io.IOException {
246 checkAnalysisComplete();
252 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
254 bw.write("Conducting disjoint reachability analysis with allocation depth = "
255 + allocationDepth + "\n");
256 bw.write(timeReport + "\n\n");
258 boolean foundSomeSharing = false;
260 Descriptor d = typeUtil.getMain();
261 HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
263 // for each allocation site check for sharing classes with
264 // other allocation sites in the context of execution
266 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
267 Iterator allocItr1 = allocSites.iterator();
268 while (allocItr1.hasNext()) {
269 AllocSite as1 = (AllocSite) allocItr1.next();
271 Iterator allocItr2 = allocSites.iterator();
272 while (allocItr2.hasNext()) {
273 AllocSite as2 = (AllocSite) allocItr2.next();
275 if (!outerChecked.contains(as2)) {
276 Set<HeapRegionNode> common = hasPotentialSharing(d,
279 if (!common.isEmpty()) {
280 foundSomeSharing = true;
281 bw.write("Potential sharing between "
282 + as1.getDisjointAnalysisId() + " and "
283 + as2.getDisjointAnalysisId() + ".\n");
284 bw.write(prettyPrintNodeSet(common) + "\n");
290 outerChecked.add(as1);
293 if (!foundSomeSharing) {
294 bw.write("No sharing classes between flagged objects found.\n");
296 bw.write("\nNumber sharing classes: "+numSharing);
299 bw.write("Number of methods analyzed: "+numMethodsAnalyzed()+"\n");
304 ///////////////////////////////////////////
306 // end public interface
308 ///////////////////////////////////////////
310 protected void checkAnalysisComplete() {
311 if( !analysisComplete ) {
312 throw new Error("Warning: public interface method called while analysis is running.");
317 // run in faster mode, only when bugs wrung out!
318 public static boolean releaseMode;
320 // use command line option to set this, analysis
321 // should attempt to be deterministic
322 public static boolean determinismDesired;
324 // when we want to enforce determinism in the
325 // analysis we need to sort descriptors rather
326 // than toss them in efficient sets, use this
327 public static DescriptorComparator dComp =
328 new DescriptorComparator();
331 // data from the compiler
333 public CallGraph callGraph;
334 public Liveness liveness;
335 public ArrayReferencees arrayReferencees;
336 public RBlockRelationAnalysis rblockRel;
337 public TypeUtil typeUtil;
338 public int allocationDepth;
340 protected boolean doEffectsAnalysis = false;
341 protected EffectsAnalysis effectsAnalysis;
343 // data structure for public interface
344 private Hashtable< Descriptor, HashSet<AllocSite> >
345 mapDescriptorToAllocSiteSet;
348 // for public interface methods to warn that they
349 // are grabbing results during analysis
350 private boolean analysisComplete;
353 // used to identify HeapRegionNode objects
354 // A unique ID equates an object in one
355 // ownership graph with an object in another
356 // graph that logically represents the same
358 // start at 10 and increment to reserve some
359 // IDs for special purposes
360 static protected int uniqueIDcount = 10;
363 // An out-of-scope method created by the
364 // analysis that has no parameters, and
365 // appears to allocate the command line
366 // arguments, then invoke the source code's
367 // main method. The purpose of this is to
368 // provide the analysis with an explicit
369 // top-level context with no parameters
370 protected MethodDescriptor mdAnalysisEntry;
371 protected FlatMethod fmAnalysisEntry;
373 // main method defined by source program
374 protected MethodDescriptor mdSourceEntry;
376 // the set of task and/or method descriptors
377 // reachable in call graph
378 protected Set<Descriptor>
379 descriptorsToAnalyze;
381 // current descriptors to visit in fixed-point
382 // interprocedural analysis, prioritized by
383 // dependency in the call graph
384 protected Stack<Descriptor>
385 descriptorsToVisitStack;
386 protected PriorityQueue<DescriptorQWrapper>
389 // a duplication of the above structure, but
390 // for efficient testing of inclusion
391 protected HashSet<Descriptor>
392 descriptorsToVisitSet;
394 // storage for priorities (doesn't make sense)
395 // to add it to the Descriptor class, just in
397 protected Hashtable<Descriptor, Integer>
398 mapDescriptorToPriority;
400 // when analyzing a method and scheduling more:
401 // remember set of callee's enqueued for analysis
402 // so they can be put on top of the callers in
403 // the stack-visit mode
404 protected Set<Descriptor>
407 // maps a descriptor to its current partial result
408 // from the intraprocedural fixed-point analysis--
409 // then the interprocedural analysis settles, this
410 // mapping will have the final results for each
412 protected Hashtable<Descriptor, ReachGraph>
413 mapDescriptorToCompleteReachGraph;
415 // maps a descriptor to its known dependents: namely
416 // methods or tasks that call the descriptor's method
417 // AND are part of this analysis (reachable from main)
418 protected Hashtable< Descriptor, Set<Descriptor> >
419 mapDescriptorToSetDependents;
421 // maps each flat new to one analysis abstraction
422 // allocate site object, these exist outside reach graphs
423 protected Hashtable<FlatNew, AllocSite>
424 mapFlatNewToAllocSite;
426 // maps intergraph heap region IDs to intergraph
427 // allocation sites that created them, a redundant
428 // structure for efficiency in some operations
429 protected Hashtable<Integer, AllocSite>
432 // maps a method to its initial heap model (IHM) that
433 // is the set of reachability graphs from every caller
434 // site, all merged together. The reason that we keep
435 // them separate is that any one call site's contribution
436 // to the IHM may changed along the path to the fixed point
437 protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
438 mapDescriptorToIHMcontributions;
440 // additionally, keep a mapping from descriptors to the
441 // merged in-coming initial context, because we want this
442 // initial context to be STRICTLY MONOTONIC
443 protected Hashtable<Descriptor, ReachGraph>
444 mapDescriptorToInitialContext;
446 // make the result for back edges analysis-wide STRICTLY
447 // MONOTONIC as well, but notice we use FlatNode as the
448 // key for this map: in case we want to consider other
449 // nodes as back edge's in future implementations
450 protected Hashtable<FlatNode, ReachGraph>
451 mapBackEdgeToMonotone;
454 public static final String arrayElementFieldName = "___element_";
455 static protected Hashtable<TypeDescriptor, FieldDescriptor>
458 // for controlling DOT file output
459 protected boolean writeFinalDOTs;
460 protected boolean writeAllIncrementalDOTs;
462 // supporting DOT output--when we want to write every
463 // partial method result, keep a tally for generating
465 protected Hashtable<Descriptor, Integer>
466 mapDescriptorToNumUpdates;
468 //map task descriptor to initial task parameter
469 protected Hashtable<Descriptor, ReachGraph>
470 mapDescriptorToReachGraph;
472 protected PointerMethod pm;
474 static protected Hashtable<FlatNode, ReachGraph> fn2rg =
475 new Hashtable<FlatNode, ReachGraph>();
477 private Hashtable<FlatCall, Descriptor> fc2enclosing;
480 // allocate various structures that are not local
481 // to a single class method--should be done once
482 protected void allocateStructures() {
484 if( determinismDesired ) {
485 // use an ordered set
486 descriptorsToAnalyze = new TreeSet<Descriptor>( dComp );
488 // otherwise use a speedy hashset
489 descriptorsToAnalyze = new HashSet<Descriptor>();
492 mapDescriptorToCompleteReachGraph =
493 new Hashtable<Descriptor, ReachGraph>();
495 mapDescriptorToNumUpdates =
496 new Hashtable<Descriptor, Integer>();
498 mapDescriptorToSetDependents =
499 new Hashtable< Descriptor, Set<Descriptor> >();
501 mapFlatNewToAllocSite =
502 new Hashtable<FlatNew, AllocSite>();
504 mapDescriptorToIHMcontributions =
505 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
507 mapDescriptorToInitialContext =
508 new Hashtable<Descriptor, ReachGraph>();
510 mapBackEdgeToMonotone =
511 new Hashtable<FlatNode, ReachGraph>();
513 mapHrnIdToAllocSite =
514 new Hashtable<Integer, AllocSite>();
516 mapTypeToArrayField =
517 new Hashtable <TypeDescriptor, FieldDescriptor>();
519 if( state.DISJOINTDVISITSTACK ||
520 state.DISJOINTDVISITSTACKEESONTOP
522 descriptorsToVisitStack =
523 new Stack<Descriptor>();
526 if( state.DISJOINTDVISITPQUE ) {
527 descriptorsToVisitQ =
528 new PriorityQueue<DescriptorQWrapper>();
531 descriptorsToVisitSet =
532 new HashSet<Descriptor>();
534 mapDescriptorToPriority =
535 new Hashtable<Descriptor, Integer>();
538 new HashSet<Descriptor>();
540 mapDescriptorToAllocSiteSet =
541 new Hashtable<Descriptor, HashSet<AllocSite> >();
543 mapDescriptorToReachGraph =
544 new Hashtable<Descriptor, ReachGraph>();
546 pm = new PointerMethod();
548 fc2enclosing = new Hashtable<FlatCall, Descriptor>();
553 // this analysis generates a disjoint reachability
554 // graph for every reachable method in the program
555 public DisjointAnalysis( State s,
560 RBlockRelationAnalysis rra
562 init( s, tu, cg, l, ar, rra );
565 protected void init( State state,
569 ArrayReferencees arrayReferencees,
570 RBlockRelationAnalysis rra
573 analysisComplete = false;
576 this.typeUtil = typeUtil;
577 this.callGraph = callGraph;
578 this.liveness = liveness;
579 this.arrayReferencees = arrayReferencees;
580 this.rblockRel = rra;
582 if( rblockRel != null ) {
583 doEffectsAnalysis = true;
584 effectsAnalysis = new EffectsAnalysis();
587 this.allocationDepth = state.DISJOINTALLOCDEPTH;
588 this.releaseMode = state.DISJOINTRELEASEMODE;
589 this.determinismDesired = state.DISJOINTDETERMINISM;
591 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
592 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL;
594 this.takeDebugSnapshots = state.DISJOINTSNAPSYMBOL != null;
595 this.descSymbolDebug = state.DISJOINTSNAPSYMBOL;
596 this.visitStartCapture = state.DISJOINTSNAPVISITTOSTART;
597 this.numVisitsToCapture = state.DISJOINTSNAPNUMVISITS;
598 this.stopAfterCapture = state.DISJOINTSNAPSTOPAFTER;
599 this.snapVisitCounter = 1; // count visits from 1 (user will write 1, means 1st visit)
600 this.snapNodeCounter = 0; // count nodes from 0
603 state.DISJOINTDVISITSTACK ||
604 state.DISJOINTDVISITPQUE ||
605 state.DISJOINTDVISITSTACKEESONTOP;
606 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITPQUE);
607 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITSTACKEESONTOP);
608 assert !(state.DISJOINTDVISITPQUE && state.DISJOINTDVISITSTACKEESONTOP);
610 // set some static configuration for ReachGraphs
611 ReachGraph.allocationDepth = allocationDepth;
612 ReachGraph.typeUtil = typeUtil;
614 ReachGraph.debugCallSiteVisitStartCapture
615 = state.DISJOINTDEBUGCALLVISITTOSTART;
617 ReachGraph.debugCallSiteNumVisitsToCapture
618 = state.DISJOINTDEBUGCALLNUMVISITS;
620 ReachGraph.debugCallSiteStopAfter
621 = state.DISJOINTDEBUGCALLSTOPAFTER;
623 ReachGraph.debugCallSiteVisitCounter
624 = 0; // count visits from 1, is incremented before first visit
628 allocateStructures();
630 double timeStartAnalysis = (double) System.nanoTime();
632 // start interprocedural fixed-point computation
635 } catch( IOException e ) {
636 throw new Error( "IO Exception while writing disjointness analysis output." );
639 analysisComplete=true;
641 double timeEndAnalysis = (double) System.nanoTime();
642 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
643 String treport = String.format( "The reachability analysis took %.3f sec.", dt );
644 String justtime = String.format( "%.2f", dt );
645 System.out.println( treport );
648 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
652 if( state.DISJOINTWRITEIHMS ) {
656 if( state.DISJOINTWRITEINITCONTEXTS ) {
657 writeInitialContexts();
660 if( state.DISJOINTALIASFILE != null ) {
662 writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
664 writeAllSharingJava(state.DISJOINTALIASFILE,
667 state.DISJOINTALIASTAB,
672 } catch( IOException e ) {
673 throw new Error( "IO Exception while writing disjointness analysis output." );
676 if( doEffectsAnalysis ) {
677 effectsAnalysis.writeEffectsPerMethod( "effects-per-method.txt" );
682 protected boolean moreDescriptorsToVisit() {
683 if( state.DISJOINTDVISITSTACK ||
684 state.DISJOINTDVISITSTACKEESONTOP
686 return !descriptorsToVisitStack.isEmpty();
688 } else if( state.DISJOINTDVISITPQUE ) {
689 return !descriptorsToVisitQ.isEmpty();
692 throw new Error( "Neither descriptor visiting mode set" );
696 // fixed-point computation over the call graph--when a
697 // method's callees are updated, it must be reanalyzed
698 protected void analyzeMethods() throws java.io.IOException {
700 // task or non-task (java) mode determines what the roots
701 // of the call chain are, and establishes the set of methods
702 // reachable from the roots that will be analyzed
705 System.out.println( "Bamboo mode..." );
707 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
708 while( taskItr.hasNext() ) {
709 TaskDescriptor td = (TaskDescriptor) taskItr.next();
710 if( !descriptorsToAnalyze.contains( td ) ) {
711 // add all methods transitively reachable from the
713 descriptorsToAnalyze.add( td );
714 descriptorsToAnalyze.addAll( callGraph.getAllMethods( td ) );
719 System.out.println( "Java mode..." );
721 // add all methods transitively reachable from the
722 // source's main to set for analysis
723 mdSourceEntry = typeUtil.getMain();
724 descriptorsToAnalyze.add( mdSourceEntry );
725 descriptorsToAnalyze.addAll( callGraph.getAllMethods( mdSourceEntry ) );
727 // fabricate an empty calling context that will call
728 // the source's main, but call graph doesn't know
729 // about it, so explicitly add it
730 makeAnalysisEntryMethod( mdSourceEntry );
731 descriptorsToAnalyze.add( mdAnalysisEntry );
735 // now, depending on the interprocedural mode for visiting
736 // methods, set up the needed data structures
738 if( state.DISJOINTDVISITPQUE ) {
740 // topologically sort according to the call graph so
741 // leaf calls are last, helps build contexts up first
742 LinkedList<Descriptor> sortedDescriptors =
743 topologicalSort( descriptorsToAnalyze );
745 // add sorted descriptors to priority queue, and duplicate
746 // the queue as a set for efficiently testing whether some
747 // method is marked for analysis
749 Iterator<Descriptor> dItr;
751 // for the priority queue, give items at the head
752 // of the sorted list a low number (highest priority)
753 while( !sortedDescriptors.isEmpty() ) {
754 Descriptor d = sortedDescriptors.removeFirst();
755 mapDescriptorToPriority.put( d, new Integer( p ) );
756 descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
757 descriptorsToVisitSet.add( d );
761 } else if( state.DISJOINTDVISITSTACK ||
762 state.DISJOINTDVISITSTACKEESONTOP
764 // if we're doing the stack scheme, just throw the root
765 // method or tasks on the stack
767 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
768 while( taskItr.hasNext() ) {
769 TaskDescriptor td = (TaskDescriptor) taskItr.next();
770 descriptorsToVisitStack.add( td );
771 descriptorsToVisitSet.add( td );
775 descriptorsToVisitStack.add( mdAnalysisEntry );
776 descriptorsToVisitSet.add( mdAnalysisEntry );
780 throw new Error( "Unknown method scheduling mode" );
784 // analyze scheduled methods until there are no more to visit
785 while( moreDescriptorsToVisit() ) {
788 if( state.DISJOINTDVISITSTACK ||
789 state.DISJOINTDVISITSTACKEESONTOP
791 d = descriptorsToVisitStack.pop();
793 } else if( state.DISJOINTDVISITPQUE ) {
794 d = descriptorsToVisitQ.poll().getDescriptor();
797 assert descriptorsToVisitSet.contains( d );
798 descriptorsToVisitSet.remove( d );
800 // because the task or method descriptor just extracted
801 // was in the "to visit" set it either hasn't been analyzed
802 // yet, or some method that it depends on has been
803 // updated. Recompute a complete reachability graph for
804 // this task/method and compare it to any previous result.
805 // If there is a change detected, add any methods/tasks
806 // that depend on this one to the "to visit" set.
808 System.out.println( "Analyzing " + d );
810 if( state.DISJOINTDVISITSTACKEESONTOP ) {
811 assert calleesToEnqueue.isEmpty();
814 ReachGraph rg = analyzeMethod( d );
815 ReachGraph rgPrev = getPartial( d );
817 if( !rg.equals( rgPrev ) ) {
820 if( state.DISJOINTDEBUGSCHEDULING ) {
821 System.out.println( " complete graph changed, scheduling callers for analysis:" );
824 // results for d changed, so enqueue dependents
825 // of d for further analysis
826 Iterator<Descriptor> depsItr = getDependents( d ).iterator();
827 while( depsItr.hasNext() ) {
828 Descriptor dNext = depsItr.next();
831 if( state.DISJOINTDEBUGSCHEDULING ) {
832 System.out.println( " "+dNext );
837 // whether or not the method under analysis changed,
838 // we may have some callees that are scheduled for
839 // more analysis, and they should go on the top of
840 // the stack now (in other method-visiting modes they
841 // are already enqueued at this point
842 if( state.DISJOINTDVISITSTACKEESONTOP ) {
843 Iterator<Descriptor> depsItr = calleesToEnqueue.iterator();
844 while( depsItr.hasNext() ) {
845 Descriptor dNext = depsItr.next();
848 calleesToEnqueue.clear();
854 protected ReachGraph analyzeMethod( Descriptor d )
855 throws java.io.IOException {
857 // get the flat code for this descriptor
859 if( d == mdAnalysisEntry ) {
860 fm = fmAnalysisEntry;
862 fm = state.getMethodFlat( d );
864 pm.analyzeMethod( fm );
866 // intraprocedural work set
867 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
868 flatNodesToVisit.add( fm );
870 // if determinism is desired by client, shadow the
871 // set with a queue to make visit order deterministic
872 Queue<FlatNode> flatNodesToVisitQ = null;
873 if( determinismDesired ) {
874 flatNodesToVisitQ = new LinkedList<FlatNode>();
875 flatNodesToVisitQ.add( fm );
878 // mapping of current partial results
879 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
880 new Hashtable<FlatNode, ReachGraph>();
882 // the set of return nodes partial results that will be combined as
883 // the final, conservative approximation of the entire method
884 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
886 while( !flatNodesToVisit.isEmpty() ) {
889 if( determinismDesired ) {
890 assert !flatNodesToVisitQ.isEmpty();
891 fn = flatNodesToVisitQ.remove();
893 fn = flatNodesToVisit.iterator().next();
895 flatNodesToVisit.remove( fn );
897 // effect transfer function defined by this node,
898 // then compare it to the old graph at this node
899 // to see if anything was updated.
901 ReachGraph rg = new ReachGraph();
902 TaskDescriptor taskDesc;
903 if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null){
904 if(mapDescriptorToReachGraph.containsKey(taskDesc)){
905 // retrieve existing reach graph if it is not first time
906 rg=mapDescriptorToReachGraph.get(taskDesc);
908 // create initial reach graph for a task
909 rg=createInitialTaskReachGraph((FlatMethod)fn);
911 mapDescriptorToReachGraph.put(taskDesc, rg);
915 // start by merging all node's parents' graphs
916 for( int i = 0; i < pm.numPrev(fn); ++i ) {
917 FlatNode pn = pm.getPrev(fn,i);
918 if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
919 ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
920 rg.merge( rgParent );
925 if( takeDebugSnapshots &&
926 d.getSymbol().equals( descSymbolDebug )
928 debugSnapshot( rg, fn, true );
932 // modify rg with appropriate transfer function
933 rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
936 if( takeDebugSnapshots &&
937 d.getSymbol().equals( descSymbolDebug )
939 debugSnapshot( rg, fn, false );
944 // if the results of the new graph are different from
945 // the current graph at this node, replace the graph
946 // with the update and enqueue the children
947 ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
948 if( !rg.equals( rgPrev ) ) {
949 mapFlatNodeToReachGraph.put( fn, rg );
951 for( int i = 0; i < pm.numNext( fn ); i++ ) {
952 FlatNode nn = pm.getNext( fn, i );
954 flatNodesToVisit.add( nn );
955 if( determinismDesired ) {
956 flatNodesToVisitQ.add( nn );
963 // end by merging all return nodes into a complete
964 // reach graph that represents all possible heap
965 // states after the flat method returns
966 ReachGraph completeGraph = new ReachGraph();
968 assert !setReturns.isEmpty();
969 Iterator retItr = setReturns.iterator();
970 while( retItr.hasNext() ) {
971 FlatReturnNode frn = (FlatReturnNode) retItr.next();
973 assert mapFlatNodeToReachGraph.containsKey( frn );
974 ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
976 completeGraph.merge( rgRet );
980 if( takeDebugSnapshots &&
981 d.getSymbol().equals( descSymbolDebug )
983 // increment that we've visited the debug snap
984 // method, and reset the node counter
985 System.out.println( " @@@ debug snap at visit "+snapVisitCounter );
989 if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
992 System.out.println( "!!! Stopping analysis after debug snap captures. !!!" );
998 return completeGraph;
1002 protected ReachGraph
1003 analyzeFlatNode( Descriptor d,
1004 FlatMethod fmContaining,
1006 HashSet<FlatReturnNode> setRetNodes,
1008 ) throws java.io.IOException {
1011 // any variables that are no longer live should be
1012 // nullified in the graph to reduce edges
1013 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
1016 if( doEffectsAnalysis &&
1017 rra.isEndOfRegion(fn)){
1018 rg.clearAccessibleVarSet();
1019 also need to clear stall mapping
1025 FieldDescriptor fld;
1027 // use node type to decide what transfer function
1028 // to apply to the reachability graph
1029 switch( fn.kind() ) {
1031 case FKind.FlatMethod: {
1032 // construct this method's initial heap model (IHM)
1033 // since we're working on the FlatMethod, we know
1034 // the incoming ReachGraph 'rg' is empty
1036 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1037 getIHMcontributions( d );
1039 Set entrySet = heapsFromCallers.entrySet();
1040 Iterator itr = entrySet.iterator();
1041 while( itr.hasNext() ) {
1042 Map.Entry me = (Map.Entry) itr.next();
1043 FlatCall fc = (FlatCall) me.getKey();
1044 ReachGraph rgContrib = (ReachGraph) me.getValue();
1046 assert fc.getMethod().equals( d );
1048 rg.merge( rgContrib );
1051 // additionally, we are enforcing STRICT MONOTONICITY for the
1052 // method's initial context, so grow the context by whatever
1053 // the previously computed context was, and put the most
1054 // up-to-date context back in the map
1055 ReachGraph rgPrevContext = mapDescriptorToInitialContext.get( d );
1056 rg.merge( rgPrevContext );
1057 mapDescriptorToInitialContext.put( d, rg );
1061 case FKind.FlatOpNode:
1062 FlatOpNode fon = (FlatOpNode) fn;
1063 if( fon.getOp().getOp() == Operation.ASSIGN ) {
1064 lhs = fon.getDest();
1065 rhs = fon.getLeft();
1066 rg.assignTempXEqualToTempY( lhs, rhs );
1069 if( doEffectsAnalysis ) {
1070 // current sese is top of stack at this program point
1071 FlatSESEEnterNode sese =
1072 rblockRel.getRBlockStacks( fmContaining, fn ).peek();
1074 // if we are assigning to an out-set var, the taint
1075 // on the out-set var edges should be TRUE (and propagate
1081 ReachGraph.predsTrue
1088 case FKind.FlatCastNode:
1089 FlatCastNode fcn = (FlatCastNode) fn;
1093 TypeDescriptor td = fcn.getType();
1096 rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
1099 case FKind.FlatFieldNode:
1100 FlatFieldNode ffn = (FlatFieldNode) fn;
1103 fld = ffn.getField();
1104 if( shouldAnalysisTrack( fld.getType() ) ) {
1105 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld );
1107 if( doEffectsAnalysis ) {
1108 effectsAnalysis.analyzeFlatFieldNode( fmContaining, rg, rhs, fld );
1113 case FKind.FlatSetFieldNode:
1114 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
1115 lhs = fsfn.getDst();
1116 fld = fsfn.getField();
1117 rhs = fsfn.getSrc();
1119 if( shouldAnalysisTrack( fld.getType() ) ) {
1120 boolean strongUpdate = rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs );
1122 if( doEffectsAnalysis ) {
1123 effectsAnalysis.analyzeFlatSetFieldNode( fmContaining, rg, lhs, fld, strongUpdate );
1128 case FKind.FlatElementNode:
1129 FlatElementNode fen = (FlatElementNode) fn;
1132 if( shouldAnalysisTrack( lhs.getType() ) ) {
1134 assert rhs.getType() != null;
1135 assert rhs.getType().isArray();
1137 TypeDescriptor tdElement = rhs.getType().dereference();
1138 FieldDescriptor fdElement = getArrayField( tdElement );
1140 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement );
1144 case FKind.FlatSetElementNode:
1145 FlatSetElementNode fsen = (FlatSetElementNode) fn;
1147 if( arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
1148 // skip this node if it cannot create new reachability paths
1152 lhs = fsen.getDst();
1153 rhs = fsen.getSrc();
1154 if( shouldAnalysisTrack( rhs.getType() ) ) {
1156 assert lhs.getType() != null;
1157 assert lhs.getType().isArray();
1159 TypeDescriptor tdElement = lhs.getType().dereference();
1160 FieldDescriptor fdElement = getArrayField( tdElement );
1162 rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs );
1167 FlatNew fnn = (FlatNew) fn;
1169 if( shouldAnalysisTrack( lhs.getType() ) ) {
1170 AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );
1171 rg.assignTempEqualToNewAlloc( lhs, as );
1175 case FKind.FlatSESEEnterNode:
1176 if( doEffectsAnalysis ) {
1177 FlatSESEEnterNode sese = (FlatSESEEnterNode) fn;
1178 rg.taintInSetVars( sese );
1182 case FKind.FlatSESEExitNode:
1183 if( doEffectsAnalysis ) {
1184 FlatSESEExitNode fsexn = (FlatSESEExitNode) fn;
1185 rg.removeInContextTaints( fsexn.getFlatEnter() );
1190 case FKind.FlatCall: {
1191 Descriptor mdCaller;
1192 if( fmContaining.getMethod() != null ){
1193 mdCaller = fmContaining.getMethod();
1195 mdCaller = fmContaining.getTask();
1197 FlatCall fc = (FlatCall) fn;
1198 MethodDescriptor mdCallee = fc.getMethod();
1199 FlatMethod fmCallee = state.getMethodFlat( mdCallee );
1202 boolean debugCallSite =
1203 mdCaller.getSymbol().equals( state.DISJOINTDEBUGCALLER ) &&
1204 mdCallee.getSymbol().equals( state.DISJOINTDEBUGCALLEE );
1206 boolean writeDebugDOTs = false;
1207 boolean stopAfter = false;
1208 if( debugCallSite ) {
1209 ++ReachGraph.debugCallSiteVisitCounter;
1210 System.out.println( " $$$ Debug call site visit "+
1211 ReachGraph.debugCallSiteVisitCounter+
1215 (ReachGraph.debugCallSiteVisitCounter >=
1216 ReachGraph.debugCallSiteVisitStartCapture) &&
1218 (ReachGraph.debugCallSiteVisitCounter <
1219 ReachGraph.debugCallSiteVisitStartCapture +
1220 ReachGraph.debugCallSiteNumVisitsToCapture)
1222 writeDebugDOTs = true;
1223 System.out.println( " $$$ Capturing this call site visit $$$" );
1224 if( ReachGraph.debugCallSiteStopAfter &&
1225 (ReachGraph.debugCallSiteVisitCounter ==
1226 ReachGraph.debugCallSiteVisitStartCapture +
1227 ReachGraph.debugCallSiteNumVisitsToCapture - 1)
1235 // calculate the heap this call site can reach--note this is
1236 // not used for the current call site transform, we are
1237 // grabbing this heap model for future analysis of the callees,
1238 // so if different results emerge we will return to this site
1239 ReachGraph heapForThisCall_old =
1240 getIHMcontribution( mdCallee, fc );
1242 // the computation of the callee-reachable heap
1243 // is useful for making the callee starting point
1244 // and for applying the call site transfer function
1245 Set<Integer> callerNodeIDsCopiedToCallee =
1246 new HashSet<Integer>();
1248 ReachGraph heapForThisCall_cur =
1249 rg.makeCalleeView( fc,
1251 callerNodeIDsCopiedToCallee,
1255 if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {
1256 // if heap at call site changed, update the contribution,
1257 // and reschedule the callee for analysis
1258 addIHMcontribution( mdCallee, fc, heapForThisCall_cur );
1260 // map a FlatCall to its enclosing method/task descriptor
1261 // so we can write that info out later
1262 fc2enclosing.put( fc, mdCaller );
1264 if( state.DISJOINTDEBUGSCHEDULING ) {
1265 System.out.println( " context changed, scheduling callee: "+mdCallee );
1268 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1269 calleesToEnqueue.add( mdCallee );
1271 enqueue( mdCallee );
1276 // the transformation for a call site should update the
1277 // current heap abstraction with any effects from the callee,
1278 // or if the method is virtual, the effects from any possible
1279 // callees, so find the set of callees...
1280 Set<MethodDescriptor> setPossibleCallees;
1281 if( determinismDesired ) {
1282 // use an ordered set
1283 setPossibleCallees = new TreeSet<MethodDescriptor>( dComp );
1285 // otherwise use a speedy hashset
1286 setPossibleCallees = new HashSet<MethodDescriptor>();
1289 if( mdCallee.isStatic() ) {
1290 setPossibleCallees.add( mdCallee );
1292 TypeDescriptor typeDesc = fc.getThis().getType();
1293 setPossibleCallees.addAll( callGraph.getMethods( mdCallee,
1298 ReachGraph rgMergeOfEffects = new ReachGraph();
1300 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
1301 while( mdItr.hasNext() ) {
1302 MethodDescriptor mdPossible = mdItr.next();
1303 FlatMethod fmPossible = state.getMethodFlat( mdPossible );
1305 addDependent( mdPossible, // callee
1308 // don't alter the working graph (rg) until we compute a
1309 // result for every possible callee, merge them all together,
1310 // then set rg to that
1311 ReachGraph rgCopy = new ReachGraph();
1314 ReachGraph rgEffect = getPartial( mdPossible );
1316 if( rgEffect == null ) {
1317 // if this method has never been analyzed just schedule it
1318 // for analysis and skip over this call site for now
1319 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1320 calleesToEnqueue.add( mdPossible );
1322 enqueue( mdPossible );
1325 if( state.DISJOINTDEBUGSCHEDULING ) {
1326 System.out.println( " callee hasn't been analyzed, scheduling: "+mdPossible );
1331 // calculate the method call transform
1333 Hashtable<Taint, TaintSet> tCallee2tsCaller = null;
1335 if( doEffectsAnalysis ) {
1336 tCallee2tsCaller = new Hashtable<Taint, TaintSet>();
1339 rgCopy.resolveMethodCall( fc,
1342 callerNodeIDsCopiedToCallee,
1347 if( doEffectsAnalysis ) {
1348 effectsAnalysis.analyzeFlatCall( fmContaining,
1354 rgMergeOfEffects.merge( rgCopy );
1359 System.out.println( "$$$ Exiting after requested captures of call site. $$$" );
1364 // now that we've taken care of building heap models for
1365 // callee analysis, finish this transformation
1366 rg = rgMergeOfEffects;
1370 case FKind.FlatReturnNode:
1371 FlatReturnNode frn = (FlatReturnNode) fn;
1372 rhs = frn.getReturnTemp();
1373 if( rhs != null && shouldAnalysisTrack( rhs.getType() ) ) {
1374 rg.assignReturnEqualToTemp( rhs );
1376 setRetNodes.add( frn );
1382 // dead variables were removed before the above transfer function
1383 // was applied, so eliminate heap regions and edges that are no
1384 // longer part of the abstractly-live heap graph, and sweep up
1385 // and reachability effects that are altered by the reduction
1386 //rg.abstractGarbageCollect();
1390 // back edges are strictly monotonic
1391 if( pm.isBackEdge( fn ) ) {
1392 ReachGraph rgPrevResult = mapBackEdgeToMonotone.get( fn );
1393 rg.merge( rgPrevResult );
1394 mapBackEdgeToMonotone.put( fn, rg );
1397 // at this point rg should be the correct update
1398 // by an above transfer function, or untouched if
1399 // the flat node type doesn't affect the heap
1405 // this method should generate integers strictly greater than zero!
1406 // special "shadow" regions are made from a heap region by negating
1408 static public Integer generateUniqueHeapRegionNodeID() {
1410 return new Integer( uniqueIDcount );
1415 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
1416 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
1417 if( fdElement == null ) {
1418 fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
1420 arrayElementFieldName,
1423 mapTypeToArrayField.put( tdElement, fdElement );
1430 private void writeFinalGraphs() {
1431 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1432 Iterator itr = entrySet.iterator();
1433 while( itr.hasNext() ) {
1434 Map.Entry me = (Map.Entry) itr.next();
1435 Descriptor d = (Descriptor) me.getKey();
1436 ReachGraph rg = (ReachGraph) me.getValue();
1438 rg.writeGraph( "COMPLETE"+d,
1439 true, // write labels (variables)
1440 true, // selectively hide intermediate temp vars
1441 true, // prune unreachable heap regions
1442 false, // hide reachability altogether
1443 true, // hide subset reachability states
1444 true, // hide predicates
1445 false ); // hide edge taints
1449 private void writeFinalIHMs() {
1450 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1451 while( d2IHMsItr.hasNext() ) {
1452 Map.Entry me1 = (Map.Entry) d2IHMsItr.next();
1453 Descriptor d = (Descriptor) me1.getKey();
1454 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1456 Iterator fc2rgItr = IHMs.entrySet().iterator();
1457 while( fc2rgItr.hasNext() ) {
1458 Map.Entry me2 = (Map.Entry) fc2rgItr.next();
1459 FlatCall fc = (FlatCall) me2.getKey();
1460 ReachGraph rg = (ReachGraph) me2.getValue();
1462 rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc2enclosing.get( fc )+fc,
1463 true, // write labels (variables)
1464 true, // selectively hide intermediate temp vars
1465 true, // hide reachability altogether
1466 true, // prune unreachable heap regions
1467 true, // hide subset reachability states
1468 false, // hide predicates
1469 true ); // hide edge taints
1474 private void writeInitialContexts() {
1475 Set entrySet = mapDescriptorToInitialContext.entrySet();
1476 Iterator itr = entrySet.iterator();
1477 while( itr.hasNext() ) {
1478 Map.Entry me = (Map.Entry) itr.next();
1479 Descriptor d = (Descriptor) me.getKey();
1480 ReachGraph rg = (ReachGraph) me.getValue();
1482 rg.writeGraph( "INITIAL"+d,
1483 true, // write labels (variables)
1484 true, // selectively hide intermediate temp vars
1485 true, // prune unreachable heap regions
1486 false, // hide all reachability
1487 true, // hide subset reachability states
1488 true, // hide predicates
1489 false );// hide edge taints
1494 protected ReachGraph getPartial( Descriptor d ) {
1495 return mapDescriptorToCompleteReachGraph.get( d );
1498 protected void setPartial( Descriptor d, ReachGraph rg ) {
1499 mapDescriptorToCompleteReachGraph.put( d, rg );
1501 // when the flag for writing out every partial
1502 // result is set, we should spit out the graph,
1503 // but in order to give it a unique name we need
1504 // to track how many partial results for this
1505 // descriptor we've already written out
1506 if( writeAllIncrementalDOTs ) {
1507 if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1508 mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1510 Integer n = mapDescriptorToNumUpdates.get( d );
1512 rg.writeGraph( d+"COMPLETE"+String.format( "%05d", n ),
1513 true, // write labels (variables)
1514 true, // selectively hide intermediate temp vars
1515 true, // prune unreachable heap regions
1516 false, // hide all reachability
1517 true, // hide subset reachability states
1518 false, // hide predicates
1519 false); // hide edge taints
1521 mapDescriptorToNumUpdates.put( d, n + 1 );
1527 // return just the allocation site associated with one FlatNew node
1528 protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1530 if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1531 AllocSite as = AllocSite.factory( allocationDepth,
1533 fnew.getDisjointId(),
1537 // the newest nodes are single objects
1538 for( int i = 0; i < allocationDepth; ++i ) {
1539 Integer id = generateUniqueHeapRegionNodeID();
1540 as.setIthOldest( i, id );
1541 mapHrnIdToAllocSite.put( id, as );
1544 // the oldest node is a summary node
1545 as.setSummary( generateUniqueHeapRegionNodeID() );
1547 mapFlatNewToAllocSite.put( fnew, as );
1550 return mapFlatNewToAllocSite.get( fnew );
1554 public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1555 // don't track primitive types, but an array
1556 // of primitives is heap memory
1557 if( type.isImmutable() ) {
1558 return type.isArray();
1561 // everything else is an object
1565 protected int numMethodsAnalyzed() {
1566 return descriptorsToAnalyze.size();
1573 // Take in source entry which is the program's compiled entry and
1574 // create a new analysis entry, a method that takes no parameters
1575 // and appears to allocate the command line arguments and call the
1576 // source entry with them. The purpose of this analysis entry is
1577 // to provide a top-level method context with no parameters left.
1578 protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1580 Modifiers mods = new Modifiers();
1581 mods.addModifier( Modifiers.PUBLIC );
1582 mods.addModifier( Modifiers.STATIC );
1584 TypeDescriptor returnType =
1585 new TypeDescriptor( TypeDescriptor.VOID );
1587 this.mdAnalysisEntry =
1588 new MethodDescriptor( mods,
1590 "analysisEntryMethod"
1593 TempDescriptor cmdLineArgs =
1594 new TempDescriptor( "args",
1595 mdSourceEntry.getParamType( 0 )
1599 new FlatNew( mdSourceEntry.getParamType( 0 ),
1604 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1605 sourceEntryArgs[0] = cmdLineArgs;
1608 new FlatCall( mdSourceEntry,
1614 FlatReturnNode frn = new FlatReturnNode( null );
1616 FlatExit fe = new FlatExit();
1618 this.fmAnalysisEntry =
1619 new FlatMethod( mdAnalysisEntry,
1623 this.fmAnalysisEntry.addNext( fn );
1630 protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1632 Set<Descriptor> discovered;
1634 if( determinismDesired ) {
1635 // use an ordered set
1636 discovered = new TreeSet<Descriptor>( dComp );
1638 // otherwise use a speedy hashset
1639 discovered = new HashSet<Descriptor>();
1642 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
1644 Iterator<Descriptor> itr = toSort.iterator();
1645 while( itr.hasNext() ) {
1646 Descriptor d = itr.next();
1648 if( !discovered.contains( d ) ) {
1649 dfsVisit( d, toSort, sorted, discovered );
1656 // While we're doing DFS on call graph, remember
1657 // dependencies for efficient queuing of methods
1658 // during interprocedural analysis:
1660 // a dependent of a method decriptor d for this analysis is:
1661 // 1) a method or task that invokes d
1662 // 2) in the descriptorsToAnalyze set
1663 protected void dfsVisit( Descriptor d,
1664 Set <Descriptor> toSort,
1665 LinkedList<Descriptor> sorted,
1666 Set <Descriptor> discovered ) {
1667 discovered.add( d );
1669 // only methods have callers, tasks never do
1670 if( d instanceof MethodDescriptor ) {
1672 MethodDescriptor md = (MethodDescriptor) d;
1674 // the call graph is not aware that we have a fabricated
1675 // analysis entry that calls the program source's entry
1676 if( md == mdSourceEntry ) {
1677 if( !discovered.contains( mdAnalysisEntry ) ) {
1678 addDependent( mdSourceEntry, // callee
1679 mdAnalysisEntry // caller
1681 dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1685 // otherwise call graph guides DFS
1686 Iterator itr = callGraph.getCallerSet( md ).iterator();
1687 while( itr.hasNext() ) {
1688 Descriptor dCaller = (Descriptor) itr.next();
1690 // only consider callers in the original set to analyze
1691 if( !toSort.contains( dCaller ) ) {
1695 if( !discovered.contains( dCaller ) ) {
1696 addDependent( md, // callee
1700 dfsVisit( dCaller, toSort, sorted, discovered );
1705 // for leaf-nodes last now!
1706 sorted.addLast( d );
1710 protected void enqueue( Descriptor d ) {
1712 if( !descriptorsToVisitSet.contains( d ) ) {
1714 if( state.DISJOINTDVISITSTACK ||
1715 state.DISJOINTDVISITSTACKEESONTOP
1717 descriptorsToVisitStack.add( d );
1719 } else if( state.DISJOINTDVISITPQUE ) {
1720 Integer priority = mapDescriptorToPriority.get( d );
1721 descriptorsToVisitQ.add( new DescriptorQWrapper( priority,
1726 descriptorsToVisitSet.add( d );
1731 // a dependent of a method decriptor d for this analysis is:
1732 // 1) a method or task that invokes d
1733 // 2) in the descriptorsToAnalyze set
1734 protected void addDependent( Descriptor callee, Descriptor caller ) {
1735 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1736 if( deps == null ) {
1737 deps = new HashSet<Descriptor>();
1740 mapDescriptorToSetDependents.put( callee, deps );
1743 protected Set<Descriptor> getDependents( Descriptor callee ) {
1744 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1745 if( deps == null ) {
1746 deps = new HashSet<Descriptor>();
1747 mapDescriptorToSetDependents.put( callee, deps );
1753 public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
1755 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1756 mapDescriptorToIHMcontributions.get( d );
1758 if( heapsFromCallers == null ) {
1759 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
1760 mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
1763 return heapsFromCallers;
1766 public ReachGraph getIHMcontribution( Descriptor d,
1769 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1770 getIHMcontributions( d );
1772 if( !heapsFromCallers.containsKey( fc ) ) {
1776 return heapsFromCallers.get( fc );
1780 public void addIHMcontribution( Descriptor d,
1784 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1785 getIHMcontributions( d );
1787 heapsFromCallers.put( fc, rg );
1791 private AllocSite createParameterAllocSite( ReachGraph rg,
1792 TempDescriptor tempDesc,
1798 flatNew = new FlatNew( tempDesc.getType(), // type
1799 tempDesc, // param temp
1800 false, // global alloc?
1801 "param"+tempDesc // disjoint site ID string
1804 flatNew = new FlatNew( tempDesc.getType(), // type
1805 tempDesc, // param temp
1806 false, // global alloc?
1807 null // disjoint site ID string
1811 // create allocation site
1812 AllocSite as = AllocSite.factory( allocationDepth,
1814 flatNew.getDisjointId(),
1817 for (int i = 0; i < allocationDepth; ++i) {
1818 Integer id = generateUniqueHeapRegionNodeID();
1819 as.setIthOldest(i, id);
1820 mapHrnIdToAllocSite.put(id, as);
1822 // the oldest node is a summary node
1823 as.setSummary( generateUniqueHeapRegionNodeID() );
1831 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc){
1833 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
1834 if(!typeDesc.isImmutable()){
1835 ClassDescriptor classDesc = typeDesc.getClassDesc();
1836 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1837 FieldDescriptor field = (FieldDescriptor) it.next();
1838 TypeDescriptor fieldType = field.getType();
1839 if (shouldAnalysisTrack( fieldType )) {
1840 fieldSet.add(field);
1848 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha ){
1850 int dimCount=fd.getType().getArrayCount();
1851 HeapRegionNode prevNode=null;
1852 HeapRegionNode arrayEntryNode=null;
1853 for(int i=dimCount;i>0;i--){
1854 TypeDescriptor typeDesc=fd.getType().dereference();//hack to get instance of type desc
1855 typeDesc.setArrayCount(i);
1856 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
1857 HeapRegionNode hrnSummary ;
1858 if(!mapToExistingNode.containsKey(typeDesc)){
1863 as = createParameterAllocSite(rg, tempDesc, false);
1865 // make a new reference to allocated node
1867 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1868 false, // single object?
1870 false, // out-of-context?
1871 as.getType(), // type
1872 as, // allocation site
1873 alpha, // inherent reach
1874 alpha, // current reach
1875 ExistPredSet.factory(rg.predTrue), // predicates
1876 tempDesc.toString() // description
1878 rg.id2hrn.put(as.getSummary(),hrnSummary);
1880 mapToExistingNode.put(typeDesc, hrnSummary);
1882 hrnSummary=mapToExistingNode.get(typeDesc);
1886 // make a new reference between new summary node and source
1887 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1890 fd.getSymbol(), // field name
1892 ExistPredSet.factory(rg.predTrue), // predicates
1896 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1897 prevNode=hrnSummary;
1898 arrayEntryNode=hrnSummary;
1900 // make a new reference between summary nodes of array
1901 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1904 arrayElementFieldName, // field name
1906 ExistPredSet.factory(rg.predTrue), // predicates
1910 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1911 prevNode=hrnSummary;
1916 // create a new obj node if obj has at least one non-primitive field
1917 TypeDescriptor type=fd.getType();
1918 if(getFieldSetTobeAnalyzed(type).size()>0){
1919 TypeDescriptor typeDesc=type.dereference();
1920 typeDesc.setArrayCount(0);
1921 if(!mapToExistingNode.containsKey(typeDesc)){
1922 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
1923 AllocSite as = createParameterAllocSite(rg, tempDesc, false);
1924 // make a new reference to allocated node
1925 HeapRegionNode hrnSummary =
1926 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1927 false, // single object?
1929 false, // out-of-context?
1931 as, // allocation site
1932 alpha, // inherent reach
1933 alpha, // current reach
1934 ExistPredSet.factory(rg.predTrue), // predicates
1935 tempDesc.toString() // description
1937 rg.id2hrn.put(as.getSummary(),hrnSummary);
1938 mapToExistingNode.put(typeDesc, hrnSummary);
1939 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1942 arrayElementFieldName, // field name
1944 ExistPredSet.factory(rg.predTrue), // predicates
1947 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1948 prevNode=hrnSummary;
1950 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
1951 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null){
1952 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1955 arrayElementFieldName, // field name
1957 ExistPredSet.factory(rg.predTrue), // predicates
1960 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1962 prevNode=hrnSummary;
1966 map.put(arrayEntryNode, prevNode);
1967 return arrayEntryNode;
1970 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
1971 ReachGraph rg = new ReachGraph();
1972 TaskDescriptor taskDesc = fm.getTask();
1974 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
1975 Descriptor paramDesc = taskDesc.getParameter(idx);
1976 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
1978 // setup data structure
1979 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
1980 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
1981 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
1982 new Hashtable<TypeDescriptor, HeapRegionNode>();
1983 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
1984 new Hashtable<HeapRegionNode, HeapRegionNode>();
1985 Set<String> doneSet = new HashSet<String>();
1987 TempDescriptor tempDesc = fm.getParameter(idx);
1989 AllocSite as = createParameterAllocSite(rg, tempDesc, true);
1990 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
1991 Integer idNewest = as.getIthOldest(0);
1992 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
1994 // make a new reference to allocated node
1995 RefEdge edgeNew = new RefEdge(lnX, // source
1997 taskDesc.getParamType(idx), // type
1999 hrnNewest.getAlpha(), // beta
2000 ExistPredSet.factory(rg.predTrue), // predicates
2003 rg.addRefEdge(lnX, hrnNewest, edgeNew);
2005 // set-up a work set for class field
2006 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
2007 for (Iterator it = classDesc.getFields(); it.hasNext();) {
2008 FieldDescriptor fd = (FieldDescriptor) it.next();
2009 TypeDescriptor fieldType = fd.getType();
2010 if (shouldAnalysisTrack( fieldType )) {
2011 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
2012 newMap.put(hrnNewest, fd);
2013 workSet.add(newMap);
2017 int uniqueIdentifier = 0;
2018 while (!workSet.isEmpty()) {
2019 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
2021 workSet.remove(map);
2023 Set<HeapRegionNode> key = map.keySet();
2024 HeapRegionNode srcHRN = key.iterator().next();
2025 FieldDescriptor fd = map.get(srcHRN);
2026 TypeDescriptor type = fd.getType();
2027 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
2029 if (!doneSet.contains(doneSetIdentifier)) {
2030 doneSet.add(doneSetIdentifier);
2031 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
2032 // create new summary Node
2033 TempDescriptor td = new TempDescriptor("temp"
2034 + uniqueIdentifier, type);
2036 AllocSite allocSite;
2037 if(type.equals(paramTypeDesc)){
2038 //corresponding allocsite has already been created for a parameter variable.
2041 allocSite = createParameterAllocSite(rg, td, false);
2043 String strDesc = allocSite.toStringForDOT()
2045 TypeDescriptor allocType=allocSite.getType();
2047 HeapRegionNode hrnSummary;
2048 if(allocType.isArray() && allocType.getArrayCount()>0){
2049 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
2052 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
2053 false, // single object?
2055 false, // out-of-context?
2056 allocSite.getType(), // type
2057 allocSite, // allocation site
2058 hrnNewest.getAlpha(), // inherent reach
2059 hrnNewest.getAlpha(), // current reach
2060 ExistPredSet.factory(rg.predTrue), // predicates
2061 strDesc // description
2063 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
2065 // make a new reference to summary node
2066 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2069 fd.getSymbol(), // field name
2070 hrnNewest.getAlpha(), // beta
2071 ExistPredSet.factory(rg.predTrue), // predicates
2075 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2079 mapTypeToExistingSummaryNode.put(type, hrnSummary);
2081 // set-up a work set for fields of the class
2082 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
2083 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
2085 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
2087 HeapRegionNode newDstHRN;
2088 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)){
2089 //related heap region node is already exsited.
2090 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
2092 newDstHRN=hrnSummary;
2094 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
2095 if(!doneSet.contains(doneSetIdentifier)){
2096 // add new work item
2097 HashMap<HeapRegionNode, FieldDescriptor> newMap =
2098 new HashMap<HeapRegionNode, FieldDescriptor>();
2099 newMap.put(newDstHRN, fieldDescriptor);
2100 workSet.add(newMap);
2105 // if there exists corresponding summary node
2106 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
2108 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2110 fd.getType(), // type
2111 fd.getSymbol(), // field name
2112 srcHRN.getAlpha(), // beta
2113 ExistPredSet.factory(rg.predTrue), // predicates
2116 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
2122 // debugSnapshot(rg, fm, true);
2126 // return all allocation sites in the method (there is one allocation
2127 // site per FlatNew node in a method)
2128 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
2129 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
2130 buildAllocationSiteSet(d);
2133 return mapDescriptorToAllocSiteSet.get(d);
2137 private void buildAllocationSiteSet(Descriptor d) {
2138 HashSet<AllocSite> s = new HashSet<AllocSite>();
2141 if( d instanceof MethodDescriptor ) {
2142 fm = state.getMethodFlat( (MethodDescriptor) d);
2144 assert d instanceof TaskDescriptor;
2145 fm = state.getMethodFlat( (TaskDescriptor) d);
2147 pm.analyzeMethod(fm);
2149 // visit every node in this FlatMethod's IR graph
2150 // and make a set of the allocation sites from the
2151 // FlatNew node's visited
2152 HashSet<FlatNode> visited = new HashSet<FlatNode>();
2153 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
2156 while( !toVisit.isEmpty() ) {
2157 FlatNode n = toVisit.iterator().next();
2159 if( n instanceof FlatNew ) {
2160 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
2166 for( int i = 0; i < pm.numNext(n); ++i ) {
2167 FlatNode child = pm.getNext(n, i);
2168 if( !visited.contains(child) ) {
2174 mapDescriptorToAllocSiteSet.put(d, s);
2177 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
2179 HashSet<AllocSite> out = new HashSet<AllocSite>();
2180 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2181 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2185 while (!toVisit.isEmpty()) {
2186 Descriptor d = toVisit.iterator().next();
2190 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2191 Iterator asItr = asSet.iterator();
2192 while (asItr.hasNext()) {
2193 AllocSite as = (AllocSite) asItr.next();
2194 if (as.getDisjointAnalysisId() != null) {
2199 // enqueue callees of this method to be searched for
2200 // allocation sites also
2201 Set callees = callGraph.getCalleeSet(d);
2202 if (callees != null) {
2203 Iterator methItr = callees.iterator();
2204 while (methItr.hasNext()) {
2205 MethodDescriptor md = (MethodDescriptor) methItr.next();
2207 if (!visited.contains(md)) {
2218 private HashSet<AllocSite>
2219 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
2221 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
2222 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2223 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2227 // traverse this task and all methods reachable from this task
2228 while( !toVisit.isEmpty() ) {
2229 Descriptor d = toVisit.iterator().next();
2233 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2234 Iterator asItr = asSet.iterator();
2235 while( asItr.hasNext() ) {
2236 AllocSite as = (AllocSite) asItr.next();
2237 TypeDescriptor typed = as.getType();
2238 if( typed != null ) {
2239 ClassDescriptor cd = typed.getClassDesc();
2240 if( cd != null && cd.hasFlags() ) {
2246 // enqueue callees of this method to be searched for
2247 // allocation sites also
2248 Set callees = callGraph.getCalleeSet(d);
2249 if( callees != null ) {
2250 Iterator methItr = callees.iterator();
2251 while( methItr.hasNext() ) {
2252 MethodDescriptor md = (MethodDescriptor) methItr.next();
2254 if( !visited.contains(md) ) {
2264 public Set<Descriptor> getDescriptorsToAnalyze() {
2265 return descriptorsToAnalyze;
2270 // get successive captures of the analysis state, use compiler
2272 boolean takeDebugSnapshots = false;
2273 String descSymbolDebug = null;
2274 boolean stopAfterCapture = false;
2275 int snapVisitCounter = 0;
2276 int snapNodeCounter = 0;
2277 int visitStartCapture = 0;
2278 int numVisitsToCapture = 0;
2281 void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
2282 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2290 if( snapVisitCounter >= visitStartCapture ) {
2291 System.out.println( " @@@ snapping visit="+snapVisitCounter+
2292 ", node="+snapNodeCounter+
2296 graphName = String.format( "snap%03d_%04din",
2300 graphName = String.format( "snap%03d_%04dout",
2305 graphName = graphName + fn;
2307 rg.writeGraph( graphName,
2308 true, // write labels (variables)
2309 true, // selectively hide intermediate temp vars
2310 true, // prune unreachable heap regions
2311 false, // hide reachability
2312 true, // hide subset reachability states
2313 true, // hide predicates
2314 false );// hide edge taints