1 package Analysis.Disjoint;
3 import Analysis.CallGraph.*;
4 import Analysis.Liveness;
5 import Analysis.ArrayReferencees;
6 import Analysis.OoOJava.RBlockRelationAnalysis;
9 import IR.Tree.Modifiers;
14 public class DisjointAnalysis {
16 ///////////////////////////////////////////
18 // Public interface to discover possible
19 // sharing in the program under analysis
21 ///////////////////////////////////////////
23 // if an object allocated at the target site may be
24 // reachable from both an object from root1 and an
25 // object allocated at root2, return TRUE
26 public boolean mayBothReachTarget( FlatMethod fm,
31 AllocSite asr1 = getAllocationSiteFromFlatNew( fnRoot1 );
32 AllocSite asr2 = getAllocationSiteFromFlatNew( fnRoot2 );
33 assert asr1.isFlagged();
34 assert asr2.isFlagged();
36 AllocSite ast = getAllocationSiteFromFlatNew( fnTarget );
37 ReachGraph rg = getPartial( fm.getMethod() );
39 return rg.mayBothReachTarget( asr1, asr2, ast );
42 // similar to the method above, return TRUE if ever
43 // more than one object from the root allocation site
44 // may reach an object from the target site
45 public boolean mayManyReachTarget( FlatMethod fm,
49 AllocSite asr = getAllocationSiteFromFlatNew( fnRoot );
50 assert asr.isFlagged();
52 AllocSite ast = getAllocationSiteFromFlatNew( fnTarget );
53 ReachGraph rg = getPartial( fm.getMethod() );
55 return rg.mayManyReachTarget( asr, ast );
61 public HashSet<AllocSite>
62 getFlaggedAllocationSitesReachableFromTask(TaskDescriptor td) {
63 checkAnalysisComplete();
64 return getFlaggedAllocationSitesReachableFromTaskPRIVATE(td);
67 public AllocSite getAllocationSiteFromFlatNew(FlatNew fn) {
68 checkAnalysisComplete();
69 return getAllocSiteFromFlatNewPRIVATE(fn);
72 public AllocSite getAllocationSiteFromHeapRegionNodeID(Integer id) {
73 checkAnalysisComplete();
74 return mapHrnIdToAllocSite.get(id);
77 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
80 checkAnalysisComplete();
81 ReachGraph rg=mapDescriptorToCompleteReachGraph.get(taskOrMethod);
82 FlatMethod fm=state.getMethodFlat(taskOrMethod);
84 return rg.mayReachSharedObjects(fm, paramIndex1, paramIndex2);
87 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
88 int paramIndex, AllocSite alloc) {
89 checkAnalysisComplete();
90 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
91 FlatMethod fm=state.getMethodFlat(taskOrMethod);
93 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
96 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
97 AllocSite alloc, int paramIndex) {
98 checkAnalysisComplete();
99 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
100 FlatMethod fm=state.getMethodFlat(taskOrMethod);
102 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
105 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
106 AllocSite alloc1, AllocSite alloc2) {
107 checkAnalysisComplete();
108 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
110 return rg.mayReachSharedObjects(alloc1, alloc2);
113 public String prettyPrintNodeSet(Set<HeapRegionNode> s) {
114 checkAnalysisComplete();
118 Iterator<HeapRegionNode> i = s.iterator();
119 while (i.hasNext()) {
120 HeapRegionNode n = i.next();
122 AllocSite as = n.getAllocSite();
124 out += " " + n.toString() + ",\n";
126 out += " " + n.toString() + ": " + as.toStringVerbose()
135 // use the methods given above to check every possible sharing class
136 // between task parameters and flagged allocation sites reachable
138 public void writeAllSharing(String outputFile,
141 boolean tabularOutput,
144 throws java.io.IOException {
145 checkAnalysisComplete();
147 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
149 if (!tabularOutput) {
150 bw.write("Conducting ownership analysis with allocation depth = "
151 + allocationDepth + "\n");
152 bw.write(timeReport + "\n");
157 // look through every task for potential sharing
158 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
159 while (taskItr.hasNext()) {
160 TaskDescriptor td = (TaskDescriptor) taskItr.next();
162 if (!tabularOutput) {
163 bw.write("\n---------" + td + "--------\n");
166 HashSet<AllocSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
168 Set<HeapRegionNode> common;
170 // for each task parameter, check for sharing classes with
171 // other task parameters and every allocation site
172 // reachable from this task
173 boolean foundSomeSharing = false;
175 FlatMethod fm = state.getMethodFlat(td);
176 for (int i = 0; i < fm.numParameters(); ++i) {
178 // skip parameters with types that cannot reference
180 if( !shouldAnalysisTrack( fm.getParameter( i ).getType() ) ) {
184 // for the ith parameter check for sharing classes to all
185 // higher numbered parameters
186 for (int j = i + 1; j < fm.numParameters(); ++j) {
188 // skip parameters with types that cannot reference
190 if( !shouldAnalysisTrack( fm.getParameter( j ).getType() ) ) {
195 common = hasPotentialSharing(td, i, j);
196 if (!common.isEmpty()) {
197 foundSomeSharing = true;
199 if (!tabularOutput) {
200 bw.write("Potential sharing between parameters " + i
201 + " and " + j + ".\n");
202 bw.write(prettyPrintNodeSet(common) + "\n");
207 // for the ith parameter, check for sharing classes against
208 // the set of allocation sites reachable from this
210 Iterator allocItr = allocSites.iterator();
211 while (allocItr.hasNext()) {
212 AllocSite as = (AllocSite) allocItr.next();
213 common = hasPotentialSharing(td, i, as);
214 if (!common.isEmpty()) {
215 foundSomeSharing = true;
217 if (!tabularOutput) {
218 bw.write("Potential sharing between parameter " + i
219 + " and " + as.getFlatNew() + ".\n");
220 bw.write(prettyPrintNodeSet(common) + "\n");
226 // for each allocation site check for sharing classes with
227 // other allocation sites in the context of execution
229 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
230 Iterator allocItr1 = allocSites.iterator();
231 while (allocItr1.hasNext()) {
232 AllocSite as1 = (AllocSite) allocItr1.next();
234 Iterator allocItr2 = allocSites.iterator();
235 while (allocItr2.hasNext()) {
236 AllocSite as2 = (AllocSite) allocItr2.next();
238 if (!outerChecked.contains(as2)) {
239 common = hasPotentialSharing(td, as1, as2);
241 if (!common.isEmpty()) {
242 foundSomeSharing = true;
244 if (!tabularOutput) {
245 bw.write("Potential sharing between "
246 + as1.getFlatNew() + " and "
247 + as2.getFlatNew() + ".\n");
248 bw.write(prettyPrintNodeSet(common) + "\n");
254 outerChecked.add(as1);
257 if (!foundSomeSharing) {
258 if (!tabularOutput) {
259 bw.write("No sharing between flagged objects in Task " + td
267 bw.write(" & " + numSharing + " & " + justTime + " & " + numLines
268 + " & " + numMethodsAnalyzed() + " \\\\\n");
270 bw.write("\nNumber sharing classes: "+numSharing);
278 // this version of writeAllSharing is for Java programs that have no tasks
279 // ***********************************
280 // WARNING: THIS DOES NOT DO THE RIGHT THING, REPORTS 0 ALWAYS!
281 // It should use mayBothReachTarget and mayManyReachTarget like
282 // OoOJava does to query analysis results
283 // ***********************************
284 public void writeAllSharingJava(String outputFile,
287 boolean tabularOutput,
290 throws java.io.IOException {
291 checkAnalysisComplete();
297 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
299 bw.write("Conducting disjoint reachability analysis with allocation depth = "
300 + allocationDepth + "\n");
301 bw.write(timeReport + "\n\n");
303 boolean foundSomeSharing = false;
305 Descriptor d = typeUtil.getMain();
306 HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
308 // for each allocation site check for sharing classes with
309 // other allocation sites in the context of execution
311 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
312 Iterator allocItr1 = allocSites.iterator();
313 while (allocItr1.hasNext()) {
314 AllocSite as1 = (AllocSite) allocItr1.next();
316 Iterator allocItr2 = allocSites.iterator();
317 while (allocItr2.hasNext()) {
318 AllocSite as2 = (AllocSite) allocItr2.next();
320 if (!outerChecked.contains(as2)) {
321 Set<HeapRegionNode> common = hasPotentialSharing(d,
324 if (!common.isEmpty()) {
325 foundSomeSharing = true;
326 bw.write("Potential sharing between "
327 + as1.getDisjointAnalysisId() + " and "
328 + as2.getDisjointAnalysisId() + ".\n");
329 bw.write(prettyPrintNodeSet(common) + "\n");
335 outerChecked.add(as1);
338 if (!foundSomeSharing) {
339 bw.write("No sharing classes between flagged objects found.\n");
341 bw.write("\nNumber sharing classes: "+numSharing);
344 bw.write("Number of methods analyzed: "+numMethodsAnalyzed()+"\n");
349 ///////////////////////////////////////////
351 // end public interface
353 ///////////////////////////////////////////
357 protected void checkAnalysisComplete() {
358 if( !analysisComplete ) {
359 throw new Error("Warning: public interface method called while analysis is running.");
368 // run in faster mode, only when bugs wrung out!
369 public static boolean releaseMode;
371 // use command line option to set this, analysis
372 // should attempt to be deterministic
373 public static boolean determinismDesired;
375 // when we want to enforce determinism in the
376 // analysis we need to sort descriptors rather
377 // than toss them in efficient sets, use this
378 public static DescriptorComparator dComp =
379 new DescriptorComparator();
382 // data from the compiler
384 public CallGraph callGraph;
385 public Liveness liveness;
386 public ArrayReferencees arrayReferencees;
387 public RBlockRelationAnalysis rblockRel;
388 public TypeUtil typeUtil;
389 public int allocationDepth;
391 protected boolean doEffectsAnalysis = false;
392 protected EffectsAnalysis effectsAnalysis;
393 protected BuildStateMachines buildStateMachines;
396 // data structure for public interface
397 private Hashtable< Descriptor, HashSet<AllocSite> >
398 mapDescriptorToAllocSiteSet;
401 // for public interface methods to warn that they
402 // are grabbing results during analysis
403 private boolean analysisComplete;
406 // used to identify HeapRegionNode objects
407 // A unique ID equates an object in one
408 // ownership graph with an object in another
409 // graph that logically represents the same
411 // start at 10 and increment to reserve some
412 // IDs for special purposes
413 static protected int uniqueIDcount = 10;
416 // An out-of-scope method created by the
417 // analysis that has no parameters, and
418 // appears to allocate the command line
419 // arguments, then invoke the source code's
420 // main method. The purpose of this is to
421 // provide the analysis with an explicit
422 // top-level context with no parameters
423 protected MethodDescriptor mdAnalysisEntry;
424 protected FlatMethod fmAnalysisEntry;
426 // main method defined by source program
427 protected MethodDescriptor mdSourceEntry;
429 // the set of task and/or method descriptors
430 // reachable in call graph
431 protected Set<Descriptor>
432 descriptorsToAnalyze;
434 // current descriptors to visit in fixed-point
435 // interprocedural analysis, prioritized by
436 // dependency in the call graph
437 protected Stack<Descriptor>
438 descriptorsToVisitStack;
439 protected PriorityQueue<DescriptorQWrapper>
442 // a duplication of the above structure, but
443 // for efficient testing of inclusion
444 protected HashSet<Descriptor>
445 descriptorsToVisitSet;
447 // storage for priorities (doesn't make sense)
448 // to add it to the Descriptor class, just in
450 protected Hashtable<Descriptor, Integer>
451 mapDescriptorToPriority;
453 // when analyzing a method and scheduling more:
454 // remember set of callee's enqueued for analysis
455 // so they can be put on top of the callers in
456 // the stack-visit mode
457 protected Set<Descriptor>
460 // maps a descriptor to its current partial result
461 // from the intraprocedural fixed-point analysis--
462 // then the interprocedural analysis settles, this
463 // mapping will have the final results for each
465 protected Hashtable<Descriptor, ReachGraph>
466 mapDescriptorToCompleteReachGraph;
468 // maps a descriptor to its known dependents: namely
469 // methods or tasks that call the descriptor's method
470 // AND are part of this analysis (reachable from main)
471 protected Hashtable< Descriptor, Set<Descriptor> >
472 mapDescriptorToSetDependents;
474 // if the analysis client wants to flag allocation sites
475 // programmatically, it should provide a set of FlatNew
476 // statements--this may be null if unneeded
477 protected Set<FlatNew> sitesToFlag;
479 // maps each flat new to one analysis abstraction
480 // allocate site object, these exist outside reach graphs
481 protected Hashtable<FlatNew, AllocSite>
482 mapFlatNewToAllocSite;
484 // maps intergraph heap region IDs to intergraph
485 // allocation sites that created them, a redundant
486 // structure for efficiency in some operations
487 protected Hashtable<Integer, AllocSite>
490 // maps a method to its initial heap model (IHM) that
491 // is the set of reachability graphs from every caller
492 // site, all merged together. The reason that we keep
493 // them separate is that any one call site's contribution
494 // to the IHM may changed along the path to the fixed point
495 protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
496 mapDescriptorToIHMcontributions;
498 // additionally, keep a mapping from descriptors to the
499 // merged in-coming initial context, because we want this
500 // initial context to be STRICTLY MONOTONIC
501 protected Hashtable<Descriptor, ReachGraph>
502 mapDescriptorToInitialContext;
504 // make the result for back edges analysis-wide STRICTLY
505 // MONOTONIC as well, but notice we use FlatNode as the
506 // key for this map: in case we want to consider other
507 // nodes as back edge's in future implementations
508 protected Hashtable<FlatNode, ReachGraph>
509 mapBackEdgeToMonotone;
512 public static final String arrayElementFieldName = "___element_";
513 static protected Hashtable<TypeDescriptor, FieldDescriptor>
517 protected boolean suppressOutput;
519 // for controlling DOT file output
520 protected boolean writeFinalDOTs;
521 protected boolean writeAllIncrementalDOTs;
523 // supporting DOT output--when we want to write every
524 // partial method result, keep a tally for generating
526 protected Hashtable<Descriptor, Integer>
527 mapDescriptorToNumUpdates;
529 //map task descriptor to initial task parameter
530 protected Hashtable<Descriptor, ReachGraph>
531 mapDescriptorToReachGraph;
533 protected PointerMethod pm;
535 //Keeps track of all the reach graphs at every program point
536 //DO NOT USE UNLESS YOU REALLY NEED IT
537 static protected Hashtable<FlatNode, ReachGraph> fn2rgAtEnter =
538 new Hashtable<FlatNode, ReachGraph>();
540 private Hashtable<FlatCall, Descriptor> fc2enclosing;
543 // allocate various structures that are not local
544 // to a single class method--should be done once
545 protected void allocateStructures() {
547 if( determinismDesired ) {
548 // use an ordered set
549 descriptorsToAnalyze = new TreeSet<Descriptor>( dComp );
551 // otherwise use a speedy hashset
552 descriptorsToAnalyze = new HashSet<Descriptor>();
555 mapDescriptorToCompleteReachGraph =
556 new Hashtable<Descriptor, ReachGraph>();
558 mapDescriptorToNumUpdates =
559 new Hashtable<Descriptor, Integer>();
561 mapDescriptorToSetDependents =
562 new Hashtable< Descriptor, Set<Descriptor> >();
564 mapFlatNewToAllocSite =
565 new Hashtable<FlatNew, AllocSite>();
567 mapDescriptorToIHMcontributions =
568 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
570 mapDescriptorToInitialContext =
571 new Hashtable<Descriptor, ReachGraph>();
573 mapBackEdgeToMonotone =
574 new Hashtable<FlatNode, ReachGraph>();
576 mapHrnIdToAllocSite =
577 new Hashtable<Integer, AllocSite>();
579 mapTypeToArrayField =
580 new Hashtable <TypeDescriptor, FieldDescriptor>();
582 if( state.DISJOINTDVISITSTACK ||
583 state.DISJOINTDVISITSTACKEESONTOP
585 descriptorsToVisitStack =
586 new Stack<Descriptor>();
589 if( state.DISJOINTDVISITPQUE ) {
590 descriptorsToVisitQ =
591 new PriorityQueue<DescriptorQWrapper>();
594 descriptorsToVisitSet =
595 new HashSet<Descriptor>();
597 mapDescriptorToPriority =
598 new Hashtable<Descriptor, Integer>();
601 new HashSet<Descriptor>();
603 mapDescriptorToAllocSiteSet =
604 new Hashtable<Descriptor, HashSet<AllocSite> >();
606 mapDescriptorToReachGraph =
607 new Hashtable<Descriptor, ReachGraph>();
609 pm = new PointerMethod();
611 fc2enclosing = new Hashtable<FlatCall, Descriptor>();
616 // this analysis generates a disjoint reachability
617 // graph for every reachable method in the program
618 public DisjointAnalysis( State s,
623 Set<FlatNew> sitesToFlag,
624 RBlockRelationAnalysis rra
626 init( s, tu, cg, l, ar, sitesToFlag, rra, false );
629 public DisjointAnalysis( State s,
634 Set<FlatNew> sitesToFlag,
635 RBlockRelationAnalysis rra,
636 boolean suppressOutput
638 init( s, tu, cg, l, ar, sitesToFlag, rra, suppressOutput );
641 protected void init( State state,
645 ArrayReferencees arrayReferencees,
646 Set<FlatNew> sitesToFlag,
647 RBlockRelationAnalysis rra,
648 boolean suppressOutput
651 analysisComplete = false;
654 this.typeUtil = typeUtil;
655 this.callGraph = callGraph;
656 this.liveness = liveness;
657 this.arrayReferencees = arrayReferencees;
658 this.sitesToFlag = sitesToFlag;
659 this.rblockRel = rra;
660 this.suppressOutput = suppressOutput;
662 if( rblockRel != null ) {
663 doEffectsAnalysis = true;
664 effectsAnalysis = new EffectsAnalysis();
668 buildStateMachines = new BuildStateMachines();
671 this.allocationDepth = state.DISJOINTALLOCDEPTH;
672 this.releaseMode = state.DISJOINTRELEASEMODE;
673 this.determinismDesired = state.DISJOINTDETERMINISM;
675 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL && !suppressOutput;
676 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL && !suppressOutput;
678 this.takeDebugSnapshots = state.DISJOINTSNAPSYMBOL != null;
679 this.descSymbolDebug = state.DISJOINTSNAPSYMBOL;
680 this.visitStartCapture = state.DISJOINTSNAPVISITTOSTART;
681 this.numVisitsToCapture = state.DISJOINTSNAPNUMVISITS;
682 this.stopAfterCapture = state.DISJOINTSNAPSTOPAFTER;
683 this.snapVisitCounter = 1; // count visits from 1 (user will write 1, means 1st visit)
684 this.snapNodeCounter = 0; // count nodes from 0
687 state.DISJOINTDVISITSTACK ||
688 state.DISJOINTDVISITPQUE ||
689 state.DISJOINTDVISITSTACKEESONTOP;
690 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITPQUE);
691 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITSTACKEESONTOP);
692 assert !(state.DISJOINTDVISITPQUE && state.DISJOINTDVISITSTACKEESONTOP);
694 // set some static configuration for ReachGraphs
695 ReachGraph.allocationDepth = allocationDepth;
696 ReachGraph.typeUtil = typeUtil;
697 ReachGraph.state = state;
699 ReachGraph.debugCallSiteVisitStartCapture
700 = state.DISJOINTDEBUGCALLVISITTOSTART;
702 ReachGraph.debugCallSiteNumVisitsToCapture
703 = state.DISJOINTDEBUGCALLNUMVISITS;
705 ReachGraph.debugCallSiteStopAfter
706 = state.DISJOINTDEBUGCALLSTOPAFTER;
708 ReachGraph.debugCallSiteVisitCounter
709 = 0; // count visits from 1, is incremented before first visit
712 EffectsAnalysis.state = state;
713 EffectsAnalysis.buildStateMachines = buildStateMachines;
716 if( suppressOutput ) {
717 System.out.println( "* Running disjoint reachability analysis with output suppressed! *" );
720 allocateStructures();
722 double timeStartAnalysis = (double) System.nanoTime();
724 // start interprocedural fixed-point computation
727 } catch( IOException e ) {
728 throw new Error( "IO Exception while writing disjointness analysis output." );
731 analysisComplete=true;
733 double timeEndAnalysis = (double) System.nanoTime();
734 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
737 if( sitesToFlag != null ) {
738 treport = String.format( "Disjoint reachability analysis flagged %d sites and took %.3f sec.", sitesToFlag.size(), dt );
739 if(sitesToFlag.size()>0){
740 treport+="\nFlagged sites:"+"\n"+sitesToFlag.toString();
743 treport = String.format( "Disjoint reachability analysis took %.3f sec.", dt );
745 String justtime = String.format( "%.2f", dt );
746 System.out.println( treport );
750 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
754 if( state.DISJOINTWRITEIHMS && !suppressOutput ) {
758 if( state.DISJOINTWRITEINITCONTEXTS && !suppressOutput ) {
759 writeInitialContexts();
762 if( state.DISJOINTALIASFILE != null && !suppressOutput ) {
764 writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
766 writeAllSharingJava(state.DISJOINTALIASFILE,
769 state.DISJOINTALIASTAB,
776 buildStateMachines.writeStateMachines();
779 } catch( IOException e ) {
780 throw new Error( "IO Exception while writing disjointness analysis output." );
785 protected boolean moreDescriptorsToVisit() {
786 if( state.DISJOINTDVISITSTACK ||
787 state.DISJOINTDVISITSTACKEESONTOP
789 return !descriptorsToVisitStack.isEmpty();
791 } else if( state.DISJOINTDVISITPQUE ) {
792 return !descriptorsToVisitQ.isEmpty();
795 throw new Error( "Neither descriptor visiting mode set" );
799 // fixed-point computation over the call graph--when a
800 // method's callees are updated, it must be reanalyzed
801 protected void analyzeMethods() throws java.io.IOException {
803 // task or non-task (java) mode determines what the roots
804 // of the call chain are, and establishes the set of methods
805 // reachable from the roots that will be analyzed
808 if( !suppressOutput ) {
809 System.out.println( "Bamboo mode..." );
812 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
813 while( taskItr.hasNext() ) {
814 TaskDescriptor td = (TaskDescriptor) taskItr.next();
815 if( !descriptorsToAnalyze.contains( td ) ) {
816 // add all methods transitively reachable from the
818 descriptorsToAnalyze.add( td );
819 descriptorsToAnalyze.addAll( callGraph.getAllMethods( td ) );
824 if( !suppressOutput ) {
825 System.out.println( "Java mode..." );
828 // add all methods transitively reachable from the
829 // source's main to set for analysis
830 mdSourceEntry = typeUtil.getMain();
831 descriptorsToAnalyze.add( mdSourceEntry );
832 descriptorsToAnalyze.addAll( callGraph.getAllMethods( mdSourceEntry ) );
834 // fabricate an empty calling context that will call
835 // the source's main, but call graph doesn't know
836 // about it, so explicitly add it
837 makeAnalysisEntryMethod( mdSourceEntry );
838 descriptorsToAnalyze.add( mdAnalysisEntry );
842 // now, depending on the interprocedural mode for visiting
843 // methods, set up the needed data structures
845 if( state.DISJOINTDVISITPQUE ) {
847 // topologically sort according to the call graph so
848 // leaf calls are last, helps build contexts up first
849 LinkedList<Descriptor> sortedDescriptors =
850 topologicalSort( descriptorsToAnalyze );
852 // add sorted descriptors to priority queue, and duplicate
853 // the queue as a set for efficiently testing whether some
854 // method is marked for analysis
856 Iterator<Descriptor> dItr;
858 // for the priority queue, give items at the head
859 // of the sorted list a low number (highest priority)
860 while( !sortedDescriptors.isEmpty() ) {
861 Descriptor d = sortedDescriptors.removeFirst();
862 mapDescriptorToPriority.put( d, new Integer( p ) );
863 descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
864 descriptorsToVisitSet.add( d );
868 } else if( state.DISJOINTDVISITSTACK ||
869 state.DISJOINTDVISITSTACKEESONTOP
871 // if we're doing the stack scheme, just throw the root
872 // method or tasks on the stack
874 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
875 while( taskItr.hasNext() ) {
876 TaskDescriptor td = (TaskDescriptor) taskItr.next();
877 descriptorsToVisitStack.add( td );
878 descriptorsToVisitSet.add( td );
882 descriptorsToVisitStack.add( mdAnalysisEntry );
883 descriptorsToVisitSet.add( mdAnalysisEntry );
887 throw new Error( "Unknown method scheduling mode" );
891 // analyze scheduled methods until there are no more to visit
892 while( moreDescriptorsToVisit() ) {
895 if( state.DISJOINTDVISITSTACK ||
896 state.DISJOINTDVISITSTACKEESONTOP
898 d = descriptorsToVisitStack.pop();
900 } else if( state.DISJOINTDVISITPQUE ) {
901 d = descriptorsToVisitQ.poll().getDescriptor();
904 assert descriptorsToVisitSet.contains( d );
905 descriptorsToVisitSet.remove( d );
907 // because the task or method descriptor just extracted
908 // was in the "to visit" set it either hasn't been analyzed
909 // yet, or some method that it depends on has been
910 // updated. Recompute a complete reachability graph for
911 // this task/method and compare it to any previous result.
912 // If there is a change detected, add any methods/tasks
913 // that depend on this one to the "to visit" set.
915 if( !suppressOutput ) {
916 System.out.println( "Analyzing " + d );
919 if( state.DISJOINTDVISITSTACKEESONTOP ) {
920 assert calleesToEnqueue.isEmpty();
923 ReachGraph rg = analyzeMethod( d );
924 ReachGraph rgPrev = getPartial( d );
926 if( !rg.equals( rgPrev ) ) {
929 if( state.DISJOINTDEBUGSCHEDULING ) {
930 System.out.println( " complete graph changed, scheduling callers for analysis:" );
933 // results for d changed, so enqueue dependents
934 // of d for further analysis
935 Iterator<Descriptor> depsItr = getDependents( d ).iterator();
936 while( depsItr.hasNext() ) {
937 Descriptor dNext = depsItr.next();
940 if( state.DISJOINTDEBUGSCHEDULING ) {
941 System.out.println( " "+dNext );
946 // whether or not the method under analysis changed,
947 // we may have some callees that are scheduled for
948 // more analysis, and they should go on the top of
949 // the stack now (in other method-visiting modes they
950 // are already enqueued at this point
951 if( state.DISJOINTDVISITSTACKEESONTOP ) {
952 Iterator<Descriptor> depsItr = calleesToEnqueue.iterator();
953 while( depsItr.hasNext() ) {
954 Descriptor dNext = depsItr.next();
957 calleesToEnqueue.clear();
963 protected ReachGraph analyzeMethod( Descriptor d )
964 throws java.io.IOException {
966 // get the flat code for this descriptor
968 if( d == mdAnalysisEntry ) {
969 fm = fmAnalysisEntry;
971 fm = state.getMethodFlat( d );
973 pm.analyzeMethod( fm );
975 // intraprocedural work set
976 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
977 flatNodesToVisit.add( fm );
979 // if determinism is desired by client, shadow the
980 // set with a queue to make visit order deterministic
981 Queue<FlatNode> flatNodesToVisitQ = null;
982 if( determinismDesired ) {
983 flatNodesToVisitQ = new LinkedList<FlatNode>();
984 flatNodesToVisitQ.add( fm );
987 // mapping of current partial results
988 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
989 new Hashtable<FlatNode, ReachGraph>();
991 // the set of return nodes partial results that will be combined as
992 // the final, conservative approximation of the entire method
993 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
995 while( !flatNodesToVisit.isEmpty() ) {
998 if( determinismDesired ) {
999 assert !flatNodesToVisitQ.isEmpty();
1000 fn = flatNodesToVisitQ.remove();
1002 fn = flatNodesToVisit.iterator().next();
1004 flatNodesToVisit.remove( fn );
1006 // effect transfer function defined by this node,
1007 // then compare it to the old graph at this node
1008 // to see if anything was updated.
1010 ReachGraph rg = new ReachGraph();
1011 TaskDescriptor taskDesc;
1012 if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null){
1013 if(mapDescriptorToReachGraph.containsKey(taskDesc)){
1014 // retrieve existing reach graph if it is not first time
1015 rg=mapDescriptorToReachGraph.get(taskDesc);
1017 // create initial reach graph for a task
1018 rg=createInitialTaskReachGraph((FlatMethod)fn);
1020 mapDescriptorToReachGraph.put(taskDesc, rg);
1024 // start by merging all node's parents' graphs
1025 for( int i = 0; i < pm.numPrev(fn); ++i ) {
1026 FlatNode pn = pm.getPrev(fn,i);
1027 if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
1028 ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
1029 rg.merge( rgParent );
1034 if( takeDebugSnapshots &&
1035 d.getSymbol().equals( descSymbolDebug )
1037 debugSnapshot( rg, fn, true );
1041 // modify rg with appropriate transfer function
1042 rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
1045 if( takeDebugSnapshots &&
1046 d.getSymbol().equals( descSymbolDebug )
1048 debugSnapshot( rg, fn, false );
1053 // if the results of the new graph are different from
1054 // the current graph at this node, replace the graph
1055 // with the update and enqueue the children
1056 ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
1057 if( !rg.equals( rgPrev ) ) {
1058 mapFlatNodeToReachGraph.put( fn, rg );
1060 for( int i = 0; i < pm.numNext( fn ); i++ ) {
1061 FlatNode nn = pm.getNext( fn, i );
1063 flatNodesToVisit.add( nn );
1064 if( determinismDesired ) {
1065 flatNodesToVisitQ.add( nn );
1072 // end by merging all return nodes into a complete
1073 // reach graph that represents all possible heap
1074 // states after the flat method returns
1075 ReachGraph completeGraph = new ReachGraph();
1077 assert !setReturns.isEmpty();
1078 Iterator retItr = setReturns.iterator();
1079 while( retItr.hasNext() ) {
1080 FlatReturnNode frn = (FlatReturnNode) retItr.next();
1082 assert mapFlatNodeToReachGraph.containsKey( frn );
1083 ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
1085 completeGraph.merge( rgRet );
1089 if( takeDebugSnapshots &&
1090 d.getSymbol().equals( descSymbolDebug )
1092 // increment that we've visited the debug snap
1093 // method, and reset the node counter
1094 System.out.println( " @@@ debug snap at visit "+snapVisitCounter );
1096 snapNodeCounter = 0;
1098 if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
1101 System.out.println( "!!! Stopping analysis after debug snap captures. !!!" );
1107 return completeGraph;
1111 protected ReachGraph
1112 analyzeFlatNode( Descriptor d,
1113 FlatMethod fmContaining,
1115 HashSet<FlatReturnNode> setRetNodes,
1117 ) throws java.io.IOException {
1120 // any variables that are no longer live should be
1121 // nullified in the graph to reduce edges
1122 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
1126 FieldDescriptor fld;
1127 TypeDescriptor tdElement;
1128 FieldDescriptor fdElement;
1129 FlatSESEEnterNode sese;
1130 FlatSESEExitNode fsexn;
1132 //Stores the flatnode's reach graph at enter
1133 ReachGraph rgOnEnter = new ReachGraph();
1134 rgOnEnter.merge( rg );
1135 fn2rgAtEnter.put(fn, rgOnEnter);
1137 // use node type to decide what transfer function
1138 // to apply to the reachability graph
1139 switch( fn.kind() ) {
1141 case FKind.FlatGenReachNode: {
1142 FlatGenReachNode fgrn = (FlatGenReachNode) fn;
1144 System.out.println( " Generating reach graph for program point: "+fgrn.getGraphName() );
1146 rg.writeGraph( "genReach"+fgrn.getGraphName(),
1147 true, // write labels (variables)
1148 true, // selectively hide intermediate temp vars
1149 true, // prune unreachable heap regions
1150 true, // hide reachability altogether
1151 false, // hide subset reachability states
1152 true, // hide predicates
1153 false ); // hide edge taints
1157 case FKind.FlatMethod: {
1158 // construct this method's initial heap model (IHM)
1159 // since we're working on the FlatMethod, we know
1160 // the incoming ReachGraph 'rg' is empty
1162 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1163 getIHMcontributions( d );
1165 Set entrySet = heapsFromCallers.entrySet();
1166 Iterator itr = entrySet.iterator();
1167 while( itr.hasNext() ) {
1168 Map.Entry me = (Map.Entry) itr.next();
1169 FlatCall fc = (FlatCall) me.getKey();
1170 ReachGraph rgContrib = (ReachGraph) me.getValue();
1172 assert fc.getMethod().equals( d );
1174 rg.merge( rgContrib );
1177 // additionally, we are enforcing STRICT MONOTONICITY for the
1178 // method's initial context, so grow the context by whatever
1179 // the previously computed context was, and put the most
1180 // up-to-date context back in the map
1181 ReachGraph rgPrevContext = mapDescriptorToInitialContext.get( d );
1182 rg.merge( rgPrevContext );
1183 mapDescriptorToInitialContext.put( d, rg );
1187 case FKind.FlatOpNode:
1188 FlatOpNode fon = (FlatOpNode) fn;
1189 if( fon.getOp().getOp() == Operation.ASSIGN ) {
1190 lhs = fon.getDest();
1191 rhs = fon.getLeft();
1193 // before transfer, do effects analysis support
1194 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1195 if(rblockRel.isPotentialStallSite(fn)){
1196 // x gets status of y
1197 if(!rg.isAccessible(rhs)){
1198 rg.makeInaccessible(lhs);
1204 rg.assignTempXEqualToTempY( lhs, rhs );
1208 case FKind.FlatCastNode:
1209 FlatCastNode fcn = (FlatCastNode) fn;
1213 TypeDescriptor td = fcn.getType();
1216 // before transfer, do effects analysis support
1217 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1218 if(rblockRel.isPotentialStallSite(fn)){
1219 // x gets status of y
1220 if(!rg.isAccessible(rhs)){
1221 rg.makeInaccessible(lhs);
1227 rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
1230 case FKind.FlatFieldNode:
1231 FlatFieldNode ffn = (FlatFieldNode) fn;
1235 fld = ffn.getField();
1237 // before graph transform, possible inject
1238 // a stall-site taint
1239 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1241 if(rblockRel.isPotentialStallSite(fn)){
1242 // x=y.f, stall y if not accessible
1243 // contributes read effects on stall site of y
1244 if(!rg.isAccessible(rhs)) {
1245 rg.taintStallSite(fn, rhs);
1248 // after this, x and y are accessbile.
1249 rg.makeAccessible(lhs);
1250 rg.makeAccessible(rhs);
1254 if( shouldAnalysisTrack( fld.getType() ) ) {
1256 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld, fn );
1259 // after transfer, use updated graph to
1260 // do effects analysis
1261 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1262 effectsAnalysis.analyzeFlatFieldNode( rg, rhs, fld, fn );
1266 case FKind.FlatSetFieldNode:
1267 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
1269 lhs = fsfn.getDst();
1270 fld = fsfn.getField();
1271 rhs = fsfn.getSrc();
1273 boolean strongUpdate = false;
1275 // before transfer func, possibly inject
1276 // stall-site taints
1277 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1279 if(rblockRel.isPotentialStallSite(fn)){
1280 // x.y=f , stall x and y if they are not accessible
1281 // also contribute write effects on stall site of x
1282 if(!rg.isAccessible(lhs)) {
1283 rg.taintStallSite(fn, lhs);
1286 if(!rg.isAccessible(rhs)) {
1287 rg.taintStallSite(fn, rhs);
1290 // accessible status update
1291 rg.makeAccessible(lhs);
1292 rg.makeAccessible(rhs);
1296 if( shouldAnalysisTrack( fld.getType() ) ) {
1298 strongUpdate = rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs, fn );
1301 // use transformed graph to do effects analysis
1302 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1303 effectsAnalysis.analyzeFlatSetFieldNode( rg, lhs, fld, fn, strongUpdate );
1307 case FKind.FlatElementNode:
1308 FlatElementNode fen = (FlatElementNode) fn;
1313 assert rhs.getType() != null;
1314 assert rhs.getType().isArray();
1316 tdElement = rhs.getType().dereference();
1317 fdElement = getArrayField( tdElement );
1319 // before transfer func, possibly inject
1321 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1322 if(rblockRel.isPotentialStallSite(fn)){
1323 // x=y.f, stall y if not accessible
1324 // contributes read effects on stall site of y
1325 // after this, x and y are accessbile.
1326 if(!rg.isAccessible(rhs)) {
1327 rg.taintStallSite(fn, rhs);
1330 rg.makeAccessible(lhs);
1331 rg.makeAccessible(rhs);
1335 if( shouldAnalysisTrack( lhs.getType() ) ) {
1337 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement, fn );
1340 // use transformed graph to do effects analysis
1341 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1342 effectsAnalysis.analyzeFlatFieldNode( rg, rhs, fdElement, fn );
1346 case FKind.FlatSetElementNode:
1347 FlatSetElementNode fsen = (FlatSetElementNode) fn;
1349 lhs = fsen.getDst();
1350 rhs = fsen.getSrc();
1352 assert lhs.getType() != null;
1353 assert lhs.getType().isArray();
1355 tdElement = lhs.getType().dereference();
1356 fdElement = getArrayField( tdElement );
1358 // before transfer func, possibly inject
1359 // stall-site taints
1360 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1362 if(rblockRel.isPotentialStallSite(fn)){
1363 // x.y=f , stall x and y if they are not accessible
1364 // also contribute write effects on stall site of x
1365 if(!rg.isAccessible(lhs)) {
1366 rg.taintStallSite(fn, lhs);
1369 if(!rg.isAccessible(rhs)) {
1370 rg.taintStallSite(fn, rhs);
1373 // accessible status update
1374 rg.makeAccessible(lhs);
1375 rg.makeAccessible(rhs);
1379 if( shouldAnalysisTrack( rhs.getType() ) ) {
1380 // transfer func, BUT
1381 // skip this node if it cannot create new reachability paths
1382 if( !arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
1383 rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs, fn );
1387 // use transformed graph to do effects analysis
1388 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1389 effectsAnalysis.analyzeFlatSetFieldNode( rg, lhs, fdElement, fn,
1395 FlatNew fnn = (FlatNew) fn;
1397 if( shouldAnalysisTrack( lhs.getType() ) ) {
1398 AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );
1400 // before transform, support effects analysis
1401 if (doEffectsAnalysis && fmContaining != fmAnalysisEntry) {
1402 if (rblockRel.isPotentialStallSite(fn)) {
1403 // after creating new object, lhs is accessible
1404 rg.makeAccessible(lhs);
1409 rg.assignTempEqualToNewAlloc( lhs, as );
1413 case FKind.FlatSESEEnterNode:
1414 sese = (FlatSESEEnterNode) fn;
1416 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1418 // always remove ALL stall site taints at enter
1419 rg.removeAllStallSiteTaints();
1421 // inject taints for in-set vars
1422 rg.taintInSetVars( sese );
1427 case FKind.FlatSESEExitNode:
1428 fsexn = (FlatSESEExitNode) fn;
1429 sese = fsexn.getFlatEnter();
1431 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1433 // @ sese exit make all live variables
1434 // inaccessible to later parent statements
1435 rg.makeInaccessible( liveness.getLiveInTemps( fmContaining, fn ) );
1437 // always remove ALL stall site taints at exit
1438 rg.removeAllStallSiteTaints();
1440 // remove in-set var taints for the exiting rblock
1441 rg.removeInContextTaints( sese );
1446 case FKind.FlatCall: {
1447 Descriptor mdCaller;
1448 if( fmContaining.getMethod() != null ){
1449 mdCaller = fmContaining.getMethod();
1451 mdCaller = fmContaining.getTask();
1453 FlatCall fc = (FlatCall) fn;
1454 MethodDescriptor mdCallee = fc.getMethod();
1455 FlatMethod fmCallee = state.getMethodFlat( mdCallee );
1458 if( mdCallee.getSymbol().equals( "genReach" ) ) {
1459 rg.writeGraph( "genReach"+d,
1460 true, // write labels (variables)
1461 true, // selectively hide intermediate temp vars
1462 true, // prune unreachable heap regions
1463 false, // hide reachability altogether
1464 true, // hide subset reachability states
1465 true, // hide predicates
1466 true ); // hide edge taints
1472 boolean debugCallSite =
1473 mdCaller.getSymbol().equals( state.DISJOINTDEBUGCALLER ) &&
1474 mdCallee.getSymbol().equals( state.DISJOINTDEBUGCALLEE );
1476 boolean writeDebugDOTs = false;
1477 boolean stopAfter = false;
1478 if( debugCallSite ) {
1479 ++ReachGraph.debugCallSiteVisitCounter;
1480 System.out.println( " $$$ Debug call site visit "+
1481 ReachGraph.debugCallSiteVisitCounter+
1485 (ReachGraph.debugCallSiteVisitCounter >=
1486 ReachGraph.debugCallSiteVisitStartCapture) &&
1488 (ReachGraph.debugCallSiteVisitCounter <
1489 ReachGraph.debugCallSiteVisitStartCapture +
1490 ReachGraph.debugCallSiteNumVisitsToCapture)
1492 writeDebugDOTs = true;
1493 System.out.println( " $$$ Capturing this call site visit $$$" );
1494 if( ReachGraph.debugCallSiteStopAfter &&
1495 (ReachGraph.debugCallSiteVisitCounter ==
1496 ReachGraph.debugCallSiteVisitStartCapture +
1497 ReachGraph.debugCallSiteNumVisitsToCapture - 1)
1505 // calculate the heap this call site can reach--note this is
1506 // not used for the current call site transform, we are
1507 // grabbing this heap model for future analysis of the callees,
1508 // so if different results emerge we will return to this site
1509 ReachGraph heapForThisCall_old =
1510 getIHMcontribution( mdCallee, fc );
1512 // the computation of the callee-reachable heap
1513 // is useful for making the callee starting point
1514 // and for applying the call site transfer function
1515 Set<Integer> callerNodeIDsCopiedToCallee =
1516 new HashSet<Integer>();
1518 ReachGraph heapForThisCall_cur =
1519 rg.makeCalleeView( fc,
1521 callerNodeIDsCopiedToCallee,
1525 // enforce that a call site contribution can only
1526 // monotonically increase
1527 heapForThisCall_cur.merge( heapForThisCall_old );
1529 if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {
1530 // if heap at call site changed, update the contribution,
1531 // and reschedule the callee for analysis
1532 addIHMcontribution( mdCallee, fc, heapForThisCall_cur );
1534 // map a FlatCall to its enclosing method/task descriptor
1535 // so we can write that info out later
1536 fc2enclosing.put( fc, mdCaller );
1538 if( state.DISJOINTDEBUGSCHEDULING ) {
1539 System.out.println( " context changed, scheduling callee: "+mdCallee );
1542 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1543 calleesToEnqueue.add( mdCallee );
1545 enqueue( mdCallee );
1550 // the transformation for a call site should update the
1551 // current heap abstraction with any effects from the callee,
1552 // or if the method is virtual, the effects from any possible
1553 // callees, so find the set of callees...
1554 Set<MethodDescriptor> setPossibleCallees;
1555 if( determinismDesired ) {
1556 // use an ordered set
1557 setPossibleCallees = new TreeSet<MethodDescriptor>( dComp );
1559 // otherwise use a speedy hashset
1560 setPossibleCallees = new HashSet<MethodDescriptor>();
1563 if( mdCallee.isStatic() ) {
1564 setPossibleCallees.add( mdCallee );
1566 TypeDescriptor typeDesc = fc.getThis().getType();
1567 setPossibleCallees.addAll( callGraph.getMethods( mdCallee,
1572 ReachGraph rgMergeOfPossibleCallers = new ReachGraph();
1574 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
1575 while( mdItr.hasNext() ) {
1576 MethodDescriptor mdPossible = mdItr.next();
1577 FlatMethod fmPossible = state.getMethodFlat( mdPossible );
1579 addDependent( mdPossible, // callee
1582 // don't alter the working graph (rg) until we compute a
1583 // result for every possible callee, merge them all together,
1584 // then set rg to that
1585 ReachGraph rgPossibleCaller = new ReachGraph();
1586 rgPossibleCaller.merge( rg );
1588 ReachGraph rgPossibleCallee = getPartial( mdPossible );
1590 if( rgPossibleCallee == null ) {
1591 // if this method has never been analyzed just schedule it
1592 // for analysis and skip over this call site for now
1593 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1594 calleesToEnqueue.add( mdPossible );
1596 enqueue( mdPossible );
1599 if( state.DISJOINTDEBUGSCHEDULING ) {
1600 System.out.println( " callee hasn't been analyzed, scheduling: "+mdPossible );
1604 // calculate the method call transform
1605 rgPossibleCaller.resolveMethodCall( fc,
1608 callerNodeIDsCopiedToCallee,
1612 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1613 if( !rgPossibleCallee.isAccessible( ReachGraph.tdReturn ) ) {
1614 rgPossibleCaller.makeInaccessible( fc.getReturnTemp() );
1620 rgMergeOfPossibleCallers.merge( rgPossibleCaller );
1625 System.out.println( "$$$ Exiting after requested captures of call site. $$$" );
1630 // now that we've taken care of building heap models for
1631 // callee analysis, finish this transformation
1632 rg = rgMergeOfPossibleCallers;
1635 // jjenista: what is this? It breaks compilation
1636 // of programs with no tasks/SESEs/rblocks...
1637 //XXXXXXXXXXXXXXXXXXXXXXXXX
1638 //need to consider more
1639 FlatNode nextFN=fmCallee.getNext(0);
1640 if( nextFN instanceof FlatSESEEnterNode ) {
1641 FlatSESEEnterNode calleeSESE=(FlatSESEEnterNode)nextFN;
1642 if(!calleeSESE.getIsLeafSESE()){
1643 rg.makeInaccessible( liveness.getLiveInTemps( fmContaining, fn ) );
1650 case FKind.FlatReturnNode:
1651 FlatReturnNode frn = (FlatReturnNode) fn;
1652 rhs = frn.getReturnTemp();
1654 // before transfer, do effects analysis support
1655 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1656 if(!rg.isAccessible(rhs)){
1657 rg.makeInaccessible(ReachGraph.tdReturn);
1661 if( rhs != null && shouldAnalysisTrack( rhs.getType() ) ) {
1662 rg.assignReturnEqualToTemp( rhs );
1665 setRetNodes.add( frn );
1671 // dead variables were removed before the above transfer function
1672 // was applied, so eliminate heap regions and edges that are no
1673 // longer part of the abstractly-live heap graph, and sweep up
1674 // and reachability effects that are altered by the reduction
1675 //rg.abstractGarbageCollect();
1679 // back edges are strictly monotonic
1680 if( pm.isBackEdge( fn ) ) {
1681 ReachGraph rgPrevResult = mapBackEdgeToMonotone.get( fn );
1682 rg.merge( rgPrevResult );
1683 mapBackEdgeToMonotone.put( fn, rg );
1686 // at this point rg should be the correct update
1687 // by an above transfer function, or untouched if
1688 // the flat node type doesn't affect the heap
1694 // this method should generate integers strictly greater than zero!
1695 // special "shadow" regions are made from a heap region by negating
1697 static public Integer generateUniqueHeapRegionNodeID() {
1699 return new Integer( uniqueIDcount );
1704 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
1705 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
1706 if( fdElement == null ) {
1707 fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
1709 arrayElementFieldName,
1712 mapTypeToArrayField.put( tdElement, fdElement );
1719 private void writeFinalGraphs() {
1720 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1721 Iterator itr = entrySet.iterator();
1722 while( itr.hasNext() ) {
1723 Map.Entry me = (Map.Entry) itr.next();
1724 Descriptor d = (Descriptor) me.getKey();
1725 ReachGraph rg = (ReachGraph) me.getValue();
1728 if( d instanceof TaskDescriptor ) {
1729 graphName = "COMPLETEtask"+d;
1731 graphName = "COMPLETE"+d;
1734 rg.writeGraph( graphName,
1735 true, // write labels (variables)
1736 true, // selectively hide intermediate temp vars
1737 true, // prune unreachable heap regions
1738 false, // hide reachability altogether
1739 true, // hide subset reachability states
1740 true, // hide predicates
1741 false ); // hide edge taints
1745 private void writeFinalIHMs() {
1746 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1747 while( d2IHMsItr.hasNext() ) {
1748 Map.Entry me1 = (Map.Entry) d2IHMsItr.next();
1749 Descriptor d = (Descriptor) me1.getKey();
1750 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1752 Iterator fc2rgItr = IHMs.entrySet().iterator();
1753 while( fc2rgItr.hasNext() ) {
1754 Map.Entry me2 = (Map.Entry) fc2rgItr.next();
1755 FlatCall fc = (FlatCall) me2.getKey();
1756 ReachGraph rg = (ReachGraph) me2.getValue();
1758 rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc2enclosing.get( fc )+fc,
1759 true, // write labels (variables)
1760 true, // selectively hide intermediate temp vars
1761 true, // hide reachability altogether
1762 true, // prune unreachable heap regions
1763 true, // hide subset reachability states
1764 false, // hide predicates
1765 true ); // hide edge taints
1770 private void writeInitialContexts() {
1771 Set entrySet = mapDescriptorToInitialContext.entrySet();
1772 Iterator itr = entrySet.iterator();
1773 while( itr.hasNext() ) {
1774 Map.Entry me = (Map.Entry) itr.next();
1775 Descriptor d = (Descriptor) me.getKey();
1776 ReachGraph rg = (ReachGraph) me.getValue();
1778 rg.writeGraph( "INITIAL"+d,
1779 true, // write labels (variables)
1780 true, // selectively hide intermediate temp vars
1781 true, // prune unreachable heap regions
1782 false, // hide all reachability
1783 true, // hide subset reachability states
1784 true, // hide predicates
1785 false );// hide edge taints
1790 protected ReachGraph getPartial( Descriptor d ) {
1791 return mapDescriptorToCompleteReachGraph.get( d );
1794 protected void setPartial( Descriptor d, ReachGraph rg ) {
1795 mapDescriptorToCompleteReachGraph.put( d, rg );
1797 // when the flag for writing out every partial
1798 // result is set, we should spit out the graph,
1799 // but in order to give it a unique name we need
1800 // to track how many partial results for this
1801 // descriptor we've already written out
1802 if( writeAllIncrementalDOTs ) {
1803 if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1804 mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1806 Integer n = mapDescriptorToNumUpdates.get( d );
1809 if( d instanceof TaskDescriptor ) {
1810 graphName = d+"COMPLETEtask"+String.format( "%05d", n );
1812 graphName = d+"COMPLETE"+String.format( "%05d", n );
1815 rg.writeGraph( graphName,
1816 true, // write labels (variables)
1817 true, // selectively hide intermediate temp vars
1818 true, // prune unreachable heap regions
1819 false, // hide all reachability
1820 true, // hide subset reachability states
1821 false, // hide predicates
1822 false); // hide edge taints
1824 mapDescriptorToNumUpdates.put( d, n + 1 );
1830 // return just the allocation site associated with one FlatNew node
1831 protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1833 boolean flagProgrammatically = false;
1834 if( sitesToFlag != null && sitesToFlag.contains( fnew ) ) {
1835 flagProgrammatically = true;
1838 if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1839 AllocSite as = AllocSite.factory( allocationDepth,
1841 fnew.getDisjointId(),
1842 flagProgrammatically
1845 // the newest nodes are single objects
1846 for( int i = 0; i < allocationDepth; ++i ) {
1847 Integer id = generateUniqueHeapRegionNodeID();
1848 as.setIthOldest( i, id );
1849 mapHrnIdToAllocSite.put( id, as );
1852 // the oldest node is a summary node
1853 as.setSummary( generateUniqueHeapRegionNodeID() );
1855 mapFlatNewToAllocSite.put( fnew, as );
1858 return mapFlatNewToAllocSite.get( fnew );
1862 public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1863 // don't track primitive types, but an array
1864 // of primitives is heap memory
1865 if( type.isImmutable() ) {
1866 return type.isArray();
1869 // everything else is an object
1873 protected int numMethodsAnalyzed() {
1874 return descriptorsToAnalyze.size();
1881 // Take in source entry which is the program's compiled entry and
1882 // create a new analysis entry, a method that takes no parameters
1883 // and appears to allocate the command line arguments and call the
1884 // source entry with them. The purpose of this analysis entry is
1885 // to provide a top-level method context with no parameters left.
1886 protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1888 Modifiers mods = new Modifiers();
1889 mods.addModifier( Modifiers.PUBLIC );
1890 mods.addModifier( Modifiers.STATIC );
1892 TypeDescriptor returnType =
1893 new TypeDescriptor( TypeDescriptor.VOID );
1895 this.mdAnalysisEntry =
1896 new MethodDescriptor( mods,
1898 "analysisEntryMethod"
1901 TempDescriptor cmdLineArgs =
1902 new TempDescriptor( "args",
1903 mdSourceEntry.getParamType( 0 )
1907 new FlatNew( mdSourceEntry.getParamType( 0 ),
1912 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1913 sourceEntryArgs[0] = cmdLineArgs;
1916 new FlatCall( mdSourceEntry,
1922 FlatReturnNode frn = new FlatReturnNode( null );
1924 FlatExit fe = new FlatExit();
1926 this.fmAnalysisEntry =
1927 new FlatMethod( mdAnalysisEntry,
1931 this.fmAnalysisEntry.addNext( fn );
1938 protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1940 Set<Descriptor> discovered;
1942 if( determinismDesired ) {
1943 // use an ordered set
1944 discovered = new TreeSet<Descriptor>( dComp );
1946 // otherwise use a speedy hashset
1947 discovered = new HashSet<Descriptor>();
1950 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
1952 Iterator<Descriptor> itr = toSort.iterator();
1953 while( itr.hasNext() ) {
1954 Descriptor d = itr.next();
1956 if( !discovered.contains( d ) ) {
1957 dfsVisit( d, toSort, sorted, discovered );
1964 // While we're doing DFS on call graph, remember
1965 // dependencies for efficient queuing of methods
1966 // during interprocedural analysis:
1968 // a dependent of a method decriptor d for this analysis is:
1969 // 1) a method or task that invokes d
1970 // 2) in the descriptorsToAnalyze set
1971 protected void dfsVisit( Descriptor d,
1972 Set <Descriptor> toSort,
1973 LinkedList<Descriptor> sorted,
1974 Set <Descriptor> discovered ) {
1975 discovered.add( d );
1977 // only methods have callers, tasks never do
1978 if( d instanceof MethodDescriptor ) {
1980 MethodDescriptor md = (MethodDescriptor) d;
1982 // the call graph is not aware that we have a fabricated
1983 // analysis entry that calls the program source's entry
1984 if( md == mdSourceEntry ) {
1985 if( !discovered.contains( mdAnalysisEntry ) ) {
1986 addDependent( mdSourceEntry, // callee
1987 mdAnalysisEntry // caller
1989 dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1993 // otherwise call graph guides DFS
1994 Iterator itr = callGraph.getCallerSet( md ).iterator();
1995 while( itr.hasNext() ) {
1996 Descriptor dCaller = (Descriptor) itr.next();
1998 // only consider callers in the original set to analyze
1999 if( !toSort.contains( dCaller ) ) {
2003 if( !discovered.contains( dCaller ) ) {
2004 addDependent( md, // callee
2008 dfsVisit( dCaller, toSort, sorted, discovered );
2013 // for leaf-nodes last now!
2014 sorted.addLast( d );
2018 protected void enqueue( Descriptor d ) {
2020 if( !descriptorsToVisitSet.contains( d ) ) {
2022 if( state.DISJOINTDVISITSTACK ||
2023 state.DISJOINTDVISITSTACKEESONTOP
2025 descriptorsToVisitStack.add( d );
2027 } else if( state.DISJOINTDVISITPQUE ) {
2028 Integer priority = mapDescriptorToPriority.get( d );
2029 descriptorsToVisitQ.add( new DescriptorQWrapper( priority,
2034 descriptorsToVisitSet.add( d );
2039 // a dependent of a method decriptor d for this analysis is:
2040 // 1) a method or task that invokes d
2041 // 2) in the descriptorsToAnalyze set
2042 protected void addDependent( Descriptor callee, Descriptor caller ) {
2043 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
2044 if( deps == null ) {
2045 deps = new HashSet<Descriptor>();
2048 mapDescriptorToSetDependents.put( callee, deps );
2051 protected Set<Descriptor> getDependents( Descriptor callee ) {
2052 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
2053 if( deps == null ) {
2054 deps = new HashSet<Descriptor>();
2055 mapDescriptorToSetDependents.put( callee, deps );
2061 public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
2063 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2064 mapDescriptorToIHMcontributions.get( d );
2066 if( heapsFromCallers == null ) {
2067 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
2068 mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
2071 return heapsFromCallers;
2074 public ReachGraph getIHMcontribution( Descriptor d,
2077 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2078 getIHMcontributions( d );
2080 if( !heapsFromCallers.containsKey( fc ) ) {
2084 return heapsFromCallers.get( fc );
2088 public void addIHMcontribution( Descriptor d,
2092 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2093 getIHMcontributions( d );
2095 heapsFromCallers.put( fc, rg );
2099 private AllocSite createParameterAllocSite( ReachGraph rg,
2100 TempDescriptor tempDesc,
2106 flatNew = new FlatNew( tempDesc.getType(), // type
2107 tempDesc, // param temp
2108 false, // global alloc?
2109 "param"+tempDesc // disjoint site ID string
2112 flatNew = new FlatNew( tempDesc.getType(), // type
2113 tempDesc, // param temp
2114 false, // global alloc?
2115 null // disjoint site ID string
2119 // create allocation site
2120 AllocSite as = AllocSite.factory( allocationDepth,
2122 flatNew.getDisjointId(),
2125 for (int i = 0; i < allocationDepth; ++i) {
2126 Integer id = generateUniqueHeapRegionNodeID();
2127 as.setIthOldest(i, id);
2128 mapHrnIdToAllocSite.put(id, as);
2130 // the oldest node is a summary node
2131 as.setSummary( generateUniqueHeapRegionNodeID() );
2139 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc){
2141 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
2142 if(!typeDesc.isImmutable()){
2143 ClassDescriptor classDesc = typeDesc.getClassDesc();
2144 for (Iterator it = classDesc.getFields(); it.hasNext();) {
2145 FieldDescriptor field = (FieldDescriptor) it.next();
2146 TypeDescriptor fieldType = field.getType();
2147 if (shouldAnalysisTrack( fieldType )) {
2148 fieldSet.add(field);
2156 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha ){
2158 int dimCount=fd.getType().getArrayCount();
2159 HeapRegionNode prevNode=null;
2160 HeapRegionNode arrayEntryNode=null;
2161 for(int i=dimCount;i>0;i--){
2162 TypeDescriptor typeDesc=fd.getType().dereference();//hack to get instance of type desc
2163 typeDesc.setArrayCount(i);
2164 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
2165 HeapRegionNode hrnSummary ;
2166 if(!mapToExistingNode.containsKey(typeDesc)){
2171 as = createParameterAllocSite(rg, tempDesc, false);
2173 // make a new reference to allocated node
2175 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
2176 false, // single object?
2178 false, // out-of-context?
2179 as.getType(), // type
2180 as, // allocation site
2181 alpha, // inherent reach
2182 alpha, // current reach
2183 ExistPredSet.factory(rg.predTrue), // predicates
2184 tempDesc.toString() // description
2186 rg.id2hrn.put(as.getSummary(),hrnSummary);
2188 mapToExistingNode.put(typeDesc, hrnSummary);
2190 hrnSummary=mapToExistingNode.get(typeDesc);
2194 // make a new reference between new summary node and source
2195 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2198 fd.getSymbol(), // field name
2200 ExistPredSet.factory(rg.predTrue), // predicates
2204 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2205 prevNode=hrnSummary;
2206 arrayEntryNode=hrnSummary;
2208 // make a new reference between summary nodes of array
2209 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2212 arrayElementFieldName, // field name
2214 ExistPredSet.factory(rg.predTrue), // predicates
2218 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2219 prevNode=hrnSummary;
2224 // create a new obj node if obj has at least one non-primitive field
2225 TypeDescriptor type=fd.getType();
2226 if(getFieldSetTobeAnalyzed(type).size()>0){
2227 TypeDescriptor typeDesc=type.dereference();
2228 typeDesc.setArrayCount(0);
2229 if(!mapToExistingNode.containsKey(typeDesc)){
2230 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
2231 AllocSite as = createParameterAllocSite(rg, tempDesc, false);
2232 // make a new reference to allocated node
2233 HeapRegionNode hrnSummary =
2234 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
2235 false, // single object?
2237 false, // out-of-context?
2239 as, // allocation site
2240 alpha, // inherent reach
2241 alpha, // current reach
2242 ExistPredSet.factory(rg.predTrue), // predicates
2243 tempDesc.toString() // description
2245 rg.id2hrn.put(as.getSummary(),hrnSummary);
2246 mapToExistingNode.put(typeDesc, hrnSummary);
2247 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2250 arrayElementFieldName, // field name
2252 ExistPredSet.factory(rg.predTrue), // predicates
2255 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2256 prevNode=hrnSummary;
2258 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
2259 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null){
2260 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2263 arrayElementFieldName, // field name
2265 ExistPredSet.factory(rg.predTrue), // predicates
2268 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2270 prevNode=hrnSummary;
2274 map.put(arrayEntryNode, prevNode);
2275 return arrayEntryNode;
2278 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
2279 ReachGraph rg = new ReachGraph();
2280 TaskDescriptor taskDesc = fm.getTask();
2282 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
2283 Descriptor paramDesc = taskDesc.getParameter(idx);
2284 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
2286 // setup data structure
2287 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
2288 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
2289 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
2290 new Hashtable<TypeDescriptor, HeapRegionNode>();
2291 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
2292 new Hashtable<HeapRegionNode, HeapRegionNode>();
2293 Set<String> doneSet = new HashSet<String>();
2295 TempDescriptor tempDesc = fm.getParameter(idx);
2297 AllocSite as = createParameterAllocSite(rg, tempDesc, true);
2298 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
2299 Integer idNewest = as.getIthOldest(0);
2300 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
2302 // make a new reference to allocated node
2303 RefEdge edgeNew = new RefEdge(lnX, // source
2305 taskDesc.getParamType(idx), // type
2307 hrnNewest.getAlpha(), // beta
2308 ExistPredSet.factory(rg.predTrue), // predicates
2311 rg.addRefEdge(lnX, hrnNewest, edgeNew);
2313 // set-up a work set for class field
2314 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
2315 for (Iterator it = classDesc.getFields(); it.hasNext();) {
2316 FieldDescriptor fd = (FieldDescriptor) it.next();
2317 TypeDescriptor fieldType = fd.getType();
2318 if (shouldAnalysisTrack( fieldType )) {
2319 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
2320 newMap.put(hrnNewest, fd);
2321 workSet.add(newMap);
2325 int uniqueIdentifier = 0;
2326 while (!workSet.isEmpty()) {
2327 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
2329 workSet.remove(map);
2331 Set<HeapRegionNode> key = map.keySet();
2332 HeapRegionNode srcHRN = key.iterator().next();
2333 FieldDescriptor fd = map.get(srcHRN);
2334 TypeDescriptor type = fd.getType();
2335 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
2337 if (!doneSet.contains(doneSetIdentifier)) {
2338 doneSet.add(doneSetIdentifier);
2339 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
2340 // create new summary Node
2341 TempDescriptor td = new TempDescriptor("temp"
2342 + uniqueIdentifier, type);
2344 AllocSite allocSite;
2345 if(type.equals(paramTypeDesc)){
2346 //corresponding allocsite has already been created for a parameter variable.
2349 allocSite = createParameterAllocSite(rg, td, false);
2351 String strDesc = allocSite.toStringForDOT()
2353 TypeDescriptor allocType=allocSite.getType();
2355 HeapRegionNode hrnSummary;
2356 if(allocType.isArray() && allocType.getArrayCount()>0){
2357 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
2360 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
2361 false, // single object?
2363 false, // out-of-context?
2364 allocSite.getType(), // type
2365 allocSite, // allocation site
2366 hrnNewest.getAlpha(), // inherent reach
2367 hrnNewest.getAlpha(), // current reach
2368 ExistPredSet.factory(rg.predTrue), // predicates
2369 strDesc // description
2371 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
2373 // make a new reference to summary node
2374 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2377 fd.getSymbol(), // field name
2378 hrnNewest.getAlpha(), // beta
2379 ExistPredSet.factory(rg.predTrue), // predicates
2383 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2387 mapTypeToExistingSummaryNode.put(type, hrnSummary);
2389 // set-up a work set for fields of the class
2390 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
2391 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
2393 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
2395 HeapRegionNode newDstHRN;
2396 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)){
2397 //related heap region node is already exsited.
2398 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
2400 newDstHRN=hrnSummary;
2402 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
2403 if(!doneSet.contains(doneSetIdentifier)){
2404 // add new work item
2405 HashMap<HeapRegionNode, FieldDescriptor> newMap =
2406 new HashMap<HeapRegionNode, FieldDescriptor>();
2407 newMap.put(newDstHRN, fieldDescriptor);
2408 workSet.add(newMap);
2413 // if there exists corresponding summary node
2414 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
2416 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2418 fd.getType(), // type
2419 fd.getSymbol(), // field name
2420 srcHRN.getAlpha(), // beta
2421 ExistPredSet.factory(rg.predTrue), // predicates
2424 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
2434 // return all allocation sites in the method (there is one allocation
2435 // site per FlatNew node in a method)
2436 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
2437 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
2438 buildAllocationSiteSet(d);
2441 return mapDescriptorToAllocSiteSet.get(d);
2445 private void buildAllocationSiteSet(Descriptor d) {
2446 HashSet<AllocSite> s = new HashSet<AllocSite>();
2449 if( d instanceof MethodDescriptor ) {
2450 fm = state.getMethodFlat( (MethodDescriptor) d);
2452 assert d instanceof TaskDescriptor;
2453 fm = state.getMethodFlat( (TaskDescriptor) d);
2455 pm.analyzeMethod(fm);
2457 // visit every node in this FlatMethod's IR graph
2458 // and make a set of the allocation sites from the
2459 // FlatNew node's visited
2460 HashSet<FlatNode> visited = new HashSet<FlatNode>();
2461 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
2464 while( !toVisit.isEmpty() ) {
2465 FlatNode n = toVisit.iterator().next();
2467 if( n instanceof FlatNew ) {
2468 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
2474 for( int i = 0; i < pm.numNext(n); ++i ) {
2475 FlatNode child = pm.getNext(n, i);
2476 if( !visited.contains(child) ) {
2482 mapDescriptorToAllocSiteSet.put(d, s);
2485 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
2487 HashSet<AllocSite> out = new HashSet<AllocSite>();
2488 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2489 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2493 while (!toVisit.isEmpty()) {
2494 Descriptor d = toVisit.iterator().next();
2498 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2499 Iterator asItr = asSet.iterator();
2500 while (asItr.hasNext()) {
2501 AllocSite as = (AllocSite) asItr.next();
2502 if (as.getDisjointAnalysisId() != null) {
2507 // enqueue callees of this method to be searched for
2508 // allocation sites also
2509 Set callees = callGraph.getCalleeSet(d);
2510 if (callees != null) {
2511 Iterator methItr = callees.iterator();
2512 while (methItr.hasNext()) {
2513 MethodDescriptor md = (MethodDescriptor) methItr.next();
2515 if (!visited.contains(md)) {
2526 private HashSet<AllocSite>
2527 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
2529 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
2530 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2531 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2535 // traverse this task and all methods reachable from this task
2536 while( !toVisit.isEmpty() ) {
2537 Descriptor d = toVisit.iterator().next();
2541 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2542 Iterator asItr = asSet.iterator();
2543 while( asItr.hasNext() ) {
2544 AllocSite as = (AllocSite) asItr.next();
2545 TypeDescriptor typed = as.getType();
2546 if( typed != null ) {
2547 ClassDescriptor cd = typed.getClassDesc();
2548 if( cd != null && cd.hasFlags() ) {
2554 // enqueue callees of this method to be searched for
2555 // allocation sites also
2556 Set callees = callGraph.getCalleeSet(d);
2557 if( callees != null ) {
2558 Iterator methItr = callees.iterator();
2559 while( methItr.hasNext() ) {
2560 MethodDescriptor md = (MethodDescriptor) methItr.next();
2562 if( !visited.contains(md) ) {
2572 public Set<Descriptor> getDescriptorsToAnalyze() {
2573 return descriptorsToAnalyze;
2576 public EffectsAnalysis getEffectsAnalysis(){
2577 return effectsAnalysis;
2580 public ReachGraph getReachGraph(Descriptor d){
2581 return mapDescriptorToCompleteReachGraph.get(d);
2584 public ReachGraph getEnterReachGraph(FlatNode fn){
2585 return fn2rgAtEnter.get(fn);
2588 // get successive captures of the analysis state, use compiler
2590 boolean takeDebugSnapshots = false;
2591 String descSymbolDebug = null;
2592 boolean stopAfterCapture = false;
2593 int snapVisitCounter = 0;
2594 int snapNodeCounter = 0;
2595 int visitStartCapture = 0;
2596 int numVisitsToCapture = 0;
2599 void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
2600 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2608 if( snapVisitCounter >= visitStartCapture ) {
2609 System.out.println( " @@@ snapping visit="+snapVisitCounter+
2610 ", node="+snapNodeCounter+
2614 graphName = String.format( "snap%03d_%04din",
2618 graphName = String.format( "snap%03d_%04dout",
2623 graphName = graphName + fn;
2625 rg.writeGraph( graphName,
2626 true, // write labels (variables)
2627 true, // selectively hide intermediate temp vars
2628 true, // prune unreachable heap regions
2629 false, // hide reachability
2630 false, // hide subset reachability states
2631 true, // hide predicates
2632 true ); // hide edge taints