1 package Analysis.Disjoint;
3 import Analysis.CallGraph.*;
4 import Analysis.Liveness;
5 import Analysis.ArrayReferencees;
6 import Analysis.OoOJava.RBlockRelationAnalysis;
7 import Analysis.OoOJava.RBlockStatusAnalysis;
10 import IR.Tree.Modifiers;
15 public class DisjointAnalysis {
17 ///////////////////////////////////////////
19 // Public interface to discover possible
20 // sharing in the program under analysis
22 ///////////////////////////////////////////
24 // if an object allocated at the target site may be
25 // reachable from both an object from root1 and an
26 // object allocated at root2, return TRUE
27 public boolean mayBothReachTarget( FlatMethod fm,
32 AllocSite asr1 = getAllocationSiteFromFlatNew( fnRoot1 );
33 AllocSite asr2 = getAllocationSiteFromFlatNew( fnRoot2 );
34 assert asr1.isFlagged();
35 assert asr2.isFlagged();
37 AllocSite ast = getAllocationSiteFromFlatNew( fnTarget );
38 ReachGraph rg = getPartial( fm.getMethod() );
40 return rg.mayBothReachTarget( asr1, asr2, ast );
43 // similar to the method above, return TRUE if ever
44 // more than one object from the root allocation site
45 // may reach an object from the target site
46 public boolean mayManyReachTarget( FlatMethod fm,
50 AllocSite asr = getAllocationSiteFromFlatNew( fnRoot );
51 assert asr.isFlagged();
53 AllocSite ast = getAllocationSiteFromFlatNew( fnTarget );
54 ReachGraph rg = getPartial( fm.getMethod() );
56 return rg.mayManyReachTarget( asr, ast );
62 public HashSet<AllocSite>
63 getFlaggedAllocationSitesReachableFromTask(TaskDescriptor td) {
64 checkAnalysisComplete();
65 return getFlaggedAllocationSitesReachableFromTaskPRIVATE(td);
68 public AllocSite getAllocationSiteFromFlatNew(FlatNew fn) {
69 checkAnalysisComplete();
70 return getAllocSiteFromFlatNewPRIVATE(fn);
73 public AllocSite getAllocationSiteFromHeapRegionNodeID(Integer id) {
74 checkAnalysisComplete();
75 return mapHrnIdToAllocSite.get(id);
78 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
81 checkAnalysisComplete();
82 ReachGraph rg=mapDescriptorToCompleteReachGraph.get(taskOrMethod);
83 FlatMethod fm=state.getMethodFlat(taskOrMethod);
85 return rg.mayReachSharedObjects(fm, paramIndex1, paramIndex2);
88 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
89 int paramIndex, AllocSite alloc) {
90 checkAnalysisComplete();
91 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
92 FlatMethod fm=state.getMethodFlat(taskOrMethod);
94 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
97 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
98 AllocSite alloc, int paramIndex) {
99 checkAnalysisComplete();
100 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
101 FlatMethod fm=state.getMethodFlat(taskOrMethod);
103 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
106 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
107 AllocSite alloc1, AllocSite alloc2) {
108 checkAnalysisComplete();
109 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
111 return rg.mayReachSharedObjects(alloc1, alloc2);
114 public String prettyPrintNodeSet(Set<HeapRegionNode> s) {
115 checkAnalysisComplete();
119 Iterator<HeapRegionNode> i = s.iterator();
120 while (i.hasNext()) {
121 HeapRegionNode n = i.next();
123 AllocSite as = n.getAllocSite();
125 out += " " + n.toString() + ",\n";
127 out += " " + n.toString() + ": " + as.toStringVerbose()
136 // use the methods given above to check every possible sharing class
137 // between task parameters and flagged allocation sites reachable
139 public void writeAllSharing(String outputFile,
142 boolean tabularOutput,
145 throws java.io.IOException {
146 checkAnalysisComplete();
148 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
150 if (!tabularOutput) {
151 bw.write("Conducting ownership analysis with allocation depth = "
152 + allocationDepth + "\n");
153 bw.write(timeReport + "\n");
158 // look through every task for potential sharing
159 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
160 while (taskItr.hasNext()) {
161 TaskDescriptor td = (TaskDescriptor) taskItr.next();
163 if (!tabularOutput) {
164 bw.write("\n---------" + td + "--------\n");
167 HashSet<AllocSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
169 Set<HeapRegionNode> common;
171 // for each task parameter, check for sharing classes with
172 // other task parameters and every allocation site
173 // reachable from this task
174 boolean foundSomeSharing = false;
176 FlatMethod fm = state.getMethodFlat(td);
177 for (int i = 0; i < fm.numParameters(); ++i) {
179 // skip parameters with types that cannot reference
181 if( !shouldAnalysisTrack( fm.getParameter( i ).getType() ) ) {
185 // for the ith parameter check for sharing classes to all
186 // higher numbered parameters
187 for (int j = i + 1; j < fm.numParameters(); ++j) {
189 // skip parameters with types that cannot reference
191 if( !shouldAnalysisTrack( fm.getParameter( j ).getType() ) ) {
196 common = hasPotentialSharing(td, i, j);
197 if (!common.isEmpty()) {
198 foundSomeSharing = true;
200 if (!tabularOutput) {
201 bw.write("Potential sharing between parameters " + i
202 + " and " + j + ".\n");
203 bw.write(prettyPrintNodeSet(common) + "\n");
208 // for the ith parameter, check for sharing classes against
209 // the set of allocation sites reachable from this
211 Iterator allocItr = allocSites.iterator();
212 while (allocItr.hasNext()) {
213 AllocSite as = (AllocSite) allocItr.next();
214 common = hasPotentialSharing(td, i, as);
215 if (!common.isEmpty()) {
216 foundSomeSharing = true;
218 if (!tabularOutput) {
219 bw.write("Potential sharing between parameter " + i
220 + " and " + as.getFlatNew() + ".\n");
221 bw.write(prettyPrintNodeSet(common) + "\n");
227 // for each allocation site check for sharing classes with
228 // other allocation sites in the context of execution
230 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
231 Iterator allocItr1 = allocSites.iterator();
232 while (allocItr1.hasNext()) {
233 AllocSite as1 = (AllocSite) allocItr1.next();
235 Iterator allocItr2 = allocSites.iterator();
236 while (allocItr2.hasNext()) {
237 AllocSite as2 = (AllocSite) allocItr2.next();
239 if (!outerChecked.contains(as2)) {
240 common = hasPotentialSharing(td, as1, as2);
242 if (!common.isEmpty()) {
243 foundSomeSharing = true;
245 if (!tabularOutput) {
246 bw.write("Potential sharing between "
247 + as1.getFlatNew() + " and "
248 + as2.getFlatNew() + ".\n");
249 bw.write(prettyPrintNodeSet(common) + "\n");
255 outerChecked.add(as1);
258 if (!foundSomeSharing) {
259 if (!tabularOutput) {
260 bw.write("No sharing between flagged objects in Task " + td
268 bw.write(" & " + numSharing + " & " + justTime + " & " + numLines
269 + " & " + numMethodsAnalyzed() + " \\\\\n");
271 bw.write("\nNumber sharing classes: "+numSharing);
279 // this version of writeAllSharing is for Java programs that have no tasks
280 // ***********************************
281 // WARNING: THIS DOES NOT DO THE RIGHT THING, REPORTS 0 ALWAYS!
282 // It should use mayBothReachTarget and mayManyReachTarget like
283 // OoOJava does to query analysis results
284 // ***********************************
285 public void writeAllSharingJava(String outputFile,
288 boolean tabularOutput,
291 throws java.io.IOException {
292 checkAnalysisComplete();
298 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
300 bw.write("Conducting disjoint reachability analysis with allocation depth = "
301 + allocationDepth + "\n");
302 bw.write(timeReport + "\n\n");
304 boolean foundSomeSharing = false;
306 Descriptor d = typeUtil.getMain();
307 HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
309 // for each allocation site check for sharing classes with
310 // other allocation sites in the context of execution
312 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
313 Iterator allocItr1 = allocSites.iterator();
314 while (allocItr1.hasNext()) {
315 AllocSite as1 = (AllocSite) allocItr1.next();
317 Iterator allocItr2 = allocSites.iterator();
318 while (allocItr2.hasNext()) {
319 AllocSite as2 = (AllocSite) allocItr2.next();
321 if (!outerChecked.contains(as2)) {
322 Set<HeapRegionNode> common = hasPotentialSharing(d,
325 if (!common.isEmpty()) {
326 foundSomeSharing = true;
327 bw.write("Potential sharing between "
328 + as1.getDisjointAnalysisId() + " and "
329 + as2.getDisjointAnalysisId() + ".\n");
330 bw.write(prettyPrintNodeSet(common) + "\n");
336 outerChecked.add(as1);
339 if (!foundSomeSharing) {
340 bw.write("No sharing classes between flagged objects found.\n");
342 bw.write("\nNumber sharing classes: "+numSharing);
345 bw.write("Number of methods analyzed: "+numMethodsAnalyzed()+"\n");
350 ///////////////////////////////////////////
352 // end public interface
354 ///////////////////////////////////////////
358 protected void checkAnalysisComplete() {
359 if( !analysisComplete ) {
360 throw new Error("Warning: public interface method called while analysis is running.");
369 // run in faster mode, only when bugs wrung out!
370 public static boolean releaseMode;
372 // use command line option to set this, analysis
373 // should attempt to be deterministic
374 public static boolean determinismDesired;
376 // when we want to enforce determinism in the
377 // analysis we need to sort descriptors rather
378 // than toss them in efficient sets, use this
379 public static DescriptorComparator dComp =
380 new DescriptorComparator();
383 // data from the compiler
385 public CallGraph callGraph;
386 public Liveness liveness;
387 public ArrayReferencees arrayReferencees;
388 public RBlockRelationAnalysis rblockRel;
389 public RBlockStatusAnalysis rblockStatus;
390 public TypeUtil typeUtil;
391 public int allocationDepth;
393 protected boolean doEffectsAnalysis = false;
394 protected EffectsAnalysis effectsAnalysis;
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>
516 // for controlling DOT file output
517 protected boolean writeFinalDOTs;
518 protected boolean writeAllIncrementalDOTs;
520 // supporting DOT output--when we want to write every
521 // partial method result, keep a tally for generating
523 protected Hashtable<Descriptor, Integer>
524 mapDescriptorToNumUpdates;
526 //map task descriptor to initial task parameter
527 protected Hashtable<Descriptor, ReachGraph>
528 mapDescriptorToReachGraph;
530 protected PointerMethod pm;
532 static protected Hashtable<FlatNode, ReachGraph> fn2rg =
533 new Hashtable<FlatNode, ReachGraph>();
535 private Hashtable<FlatCall, Descriptor> fc2enclosing;
538 // allocate various structures that are not local
539 // to a single class method--should be done once
540 protected void allocateStructures() {
542 if( determinismDesired ) {
543 // use an ordered set
544 descriptorsToAnalyze = new TreeSet<Descriptor>( dComp );
546 // otherwise use a speedy hashset
547 descriptorsToAnalyze = new HashSet<Descriptor>();
550 mapDescriptorToCompleteReachGraph =
551 new Hashtable<Descriptor, ReachGraph>();
553 mapDescriptorToNumUpdates =
554 new Hashtable<Descriptor, Integer>();
556 mapDescriptorToSetDependents =
557 new Hashtable< Descriptor, Set<Descriptor> >();
559 mapFlatNewToAllocSite =
560 new Hashtable<FlatNew, AllocSite>();
562 mapDescriptorToIHMcontributions =
563 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
565 mapDescriptorToInitialContext =
566 new Hashtable<Descriptor, ReachGraph>();
568 mapBackEdgeToMonotone =
569 new Hashtable<FlatNode, ReachGraph>();
571 mapHrnIdToAllocSite =
572 new Hashtable<Integer, AllocSite>();
574 mapTypeToArrayField =
575 new Hashtable <TypeDescriptor, FieldDescriptor>();
577 if( state.DISJOINTDVISITSTACK ||
578 state.DISJOINTDVISITSTACKEESONTOP
580 descriptorsToVisitStack =
581 new Stack<Descriptor>();
584 if( state.DISJOINTDVISITPQUE ) {
585 descriptorsToVisitQ =
586 new PriorityQueue<DescriptorQWrapper>();
589 descriptorsToVisitSet =
590 new HashSet<Descriptor>();
592 mapDescriptorToPriority =
593 new Hashtable<Descriptor, Integer>();
596 new HashSet<Descriptor>();
598 mapDescriptorToAllocSiteSet =
599 new Hashtable<Descriptor, HashSet<AllocSite> >();
601 mapDescriptorToReachGraph =
602 new Hashtable<Descriptor, ReachGraph>();
604 pm = new PointerMethod();
606 fc2enclosing = new Hashtable<FlatCall, Descriptor>();
611 // this analysis generates a disjoint reachability
612 // graph for every reachable method in the program
613 public DisjointAnalysis( State s,
618 Set<FlatNew> sitesToFlag,
619 RBlockRelationAnalysis rra,
620 RBlockStatusAnalysis rsa
622 init( s, tu, cg, l, ar, sitesToFlag, rra, rsa, false );
625 public DisjointAnalysis( State s,
630 Set<FlatNew> sitesToFlag,
631 RBlockRelationAnalysis rra,
632 RBlockStatusAnalysis rsa,
633 boolean suppressOutput
635 init( s, tu, cg, l, ar, sitesToFlag, rra, rsa, suppressOutput );
638 protected void init( State state,
642 ArrayReferencees arrayReferencees,
643 Set<FlatNew> sitesToFlag,
644 RBlockRelationAnalysis rra,
645 RBlockStatusAnalysis rsa,
646 boolean suppressOutput
649 analysisComplete = false;
652 this.typeUtil = typeUtil;
653 this.callGraph = callGraph;
654 this.liveness = liveness;
655 this.arrayReferencees = arrayReferencees;
656 this.sitesToFlag = sitesToFlag;
657 this.rblockRel = rra;
658 this.rblockStatus = rsa;
660 if( rblockRel != null ) {
661 doEffectsAnalysis = true;
662 effectsAnalysis = new EffectsAnalysis();
665 this.allocationDepth = state.DISJOINTALLOCDEPTH;
666 this.releaseMode = state.DISJOINTRELEASEMODE;
667 this.determinismDesired = state.DISJOINTDETERMINISM;
669 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL && !suppressOutput;
670 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL && !suppressOutput;
672 this.takeDebugSnapshots = state.DISJOINTSNAPSYMBOL != null;
673 this.descSymbolDebug = state.DISJOINTSNAPSYMBOL;
674 this.visitStartCapture = state.DISJOINTSNAPVISITTOSTART;
675 this.numVisitsToCapture = state.DISJOINTSNAPNUMVISITS;
676 this.stopAfterCapture = state.DISJOINTSNAPSTOPAFTER;
677 this.snapVisitCounter = 1; // count visits from 1 (user will write 1, means 1st visit)
678 this.snapNodeCounter = 0; // count nodes from 0
681 state.DISJOINTDVISITSTACK ||
682 state.DISJOINTDVISITPQUE ||
683 state.DISJOINTDVISITSTACKEESONTOP;
684 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITPQUE);
685 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITSTACKEESONTOP);
686 assert !(state.DISJOINTDVISITPQUE && state.DISJOINTDVISITSTACKEESONTOP);
688 // set some static configuration for ReachGraphs
689 ReachGraph.allocationDepth = allocationDepth;
690 ReachGraph.typeUtil = typeUtil;
692 ReachGraph.debugCallSiteVisitStartCapture
693 = state.DISJOINTDEBUGCALLVISITTOSTART;
695 ReachGraph.debugCallSiteNumVisitsToCapture
696 = state.DISJOINTDEBUGCALLNUMVISITS;
698 ReachGraph.debugCallSiteStopAfter
699 = state.DISJOINTDEBUGCALLSTOPAFTER;
701 ReachGraph.debugCallSiteVisitCounter
702 = 0; // count visits from 1, is incremented before first visit
706 allocateStructures();
708 double timeStartAnalysis = (double) System.nanoTime();
710 // start interprocedural fixed-point computation
713 } catch( IOException e ) {
714 throw new Error( "IO Exception while writing disjointness analysis output." );
717 analysisComplete=true;
720 double timeEndAnalysis = (double) System.nanoTime();
721 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
724 if( sitesToFlag != null ) {
725 treport = String.format( "Disjoint reachability analysis flagged %d sites and took %.3f sec.", sitesToFlag.size(), dt );
726 if(sitesToFlag.size()>0){
727 treport+="\nFlagged sites:"+"\n"+sitesToFlag.toString();
730 treport = String.format( "Disjoint reachability analysis took %.3f sec.", dt );
732 String justtime = String.format( "%.2f", dt );
733 System.out.println( treport );
737 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
741 if( state.DISJOINTWRITEIHMS && !suppressOutput ) {
745 if( state.DISJOINTWRITEINITCONTEXTS && !suppressOutput ) {
746 writeInitialContexts();
749 if( state.DISJOINTALIASFILE != null && !suppressOutput ) {
751 writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
753 writeAllSharingJava(state.DISJOINTALIASFILE,
756 state.DISJOINTALIASTAB,
761 } catch( IOException e ) {
762 throw new Error( "IO Exception while writing disjointness analysis output." );
768 protected boolean moreDescriptorsToVisit() {
769 if( state.DISJOINTDVISITSTACK ||
770 state.DISJOINTDVISITSTACKEESONTOP
772 return !descriptorsToVisitStack.isEmpty();
774 } else if( state.DISJOINTDVISITPQUE ) {
775 return !descriptorsToVisitQ.isEmpty();
778 throw new Error( "Neither descriptor visiting mode set" );
782 // fixed-point computation over the call graph--when a
783 // method's callees are updated, it must be reanalyzed
784 protected void analyzeMethods() throws java.io.IOException {
786 // task or non-task (java) mode determines what the roots
787 // of the call chain are, and establishes the set of methods
788 // reachable from the roots that will be analyzed
791 System.out.println( "Bamboo mode..." );
793 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
794 while( taskItr.hasNext() ) {
795 TaskDescriptor td = (TaskDescriptor) taskItr.next();
796 if( !descriptorsToAnalyze.contains( td ) ) {
797 // add all methods transitively reachable from the
799 descriptorsToAnalyze.add( td );
800 descriptorsToAnalyze.addAll( callGraph.getAllMethods( td ) );
805 System.out.println( "Java mode..." );
807 // add all methods transitively reachable from the
808 // source's main to set for analysis
809 mdSourceEntry = typeUtil.getMain();
810 descriptorsToAnalyze.add( mdSourceEntry );
811 descriptorsToAnalyze.addAll( callGraph.getAllMethods( mdSourceEntry ) );
813 // fabricate an empty calling context that will call
814 // the source's main, but call graph doesn't know
815 // about it, so explicitly add it
816 makeAnalysisEntryMethod( mdSourceEntry );
817 descriptorsToAnalyze.add( mdAnalysisEntry );
821 // now, depending on the interprocedural mode for visiting
822 // methods, set up the needed data structures
824 if( state.DISJOINTDVISITPQUE ) {
826 // topologically sort according to the call graph so
827 // leaf calls are last, helps build contexts up first
828 LinkedList<Descriptor> sortedDescriptors =
829 topologicalSort( descriptorsToAnalyze );
831 // add sorted descriptors to priority queue, and duplicate
832 // the queue as a set for efficiently testing whether some
833 // method is marked for analysis
835 Iterator<Descriptor> dItr;
837 // for the priority queue, give items at the head
838 // of the sorted list a low number (highest priority)
839 while( !sortedDescriptors.isEmpty() ) {
840 Descriptor d = sortedDescriptors.removeFirst();
841 mapDescriptorToPriority.put( d, new Integer( p ) );
842 descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
843 descriptorsToVisitSet.add( d );
847 } else if( state.DISJOINTDVISITSTACK ||
848 state.DISJOINTDVISITSTACKEESONTOP
850 // if we're doing the stack scheme, just throw the root
851 // method or tasks on the stack
853 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
854 while( taskItr.hasNext() ) {
855 TaskDescriptor td = (TaskDescriptor) taskItr.next();
856 descriptorsToVisitStack.add( td );
857 descriptorsToVisitSet.add( td );
861 descriptorsToVisitStack.add( mdAnalysisEntry );
862 descriptorsToVisitSet.add( mdAnalysisEntry );
866 throw new Error( "Unknown method scheduling mode" );
870 // analyze scheduled methods until there are no more to visit
871 while( moreDescriptorsToVisit() ) {
874 if( state.DISJOINTDVISITSTACK ||
875 state.DISJOINTDVISITSTACKEESONTOP
877 d = descriptorsToVisitStack.pop();
879 } else if( state.DISJOINTDVISITPQUE ) {
880 d = descriptorsToVisitQ.poll().getDescriptor();
883 assert descriptorsToVisitSet.contains( d );
884 descriptorsToVisitSet.remove( d );
886 // because the task or method descriptor just extracted
887 // was in the "to visit" set it either hasn't been analyzed
888 // yet, or some method that it depends on has been
889 // updated. Recompute a complete reachability graph for
890 // this task/method and compare it to any previous result.
891 // If there is a change detected, add any methods/tasks
892 // that depend on this one to the "to visit" set.
894 System.out.println( "Analyzing " + d );
896 if( state.DISJOINTDVISITSTACKEESONTOP ) {
897 assert calleesToEnqueue.isEmpty();
900 ReachGraph rg = analyzeMethod( d );
901 ReachGraph rgPrev = getPartial( d );
903 if( !rg.equals( rgPrev ) ) {
906 if( state.DISJOINTDEBUGSCHEDULING ) {
907 System.out.println( " complete graph changed, scheduling callers for analysis:" );
910 // results for d changed, so enqueue dependents
911 // of d for further analysis
912 Iterator<Descriptor> depsItr = getDependents( d ).iterator();
913 while( depsItr.hasNext() ) {
914 Descriptor dNext = depsItr.next();
917 if( state.DISJOINTDEBUGSCHEDULING ) {
918 System.out.println( " "+dNext );
923 // whether or not the method under analysis changed,
924 // we may have some callees that are scheduled for
925 // more analysis, and they should go on the top of
926 // the stack now (in other method-visiting modes they
927 // are already enqueued at this point
928 if( state.DISJOINTDVISITSTACKEESONTOP ) {
929 Iterator<Descriptor> depsItr = calleesToEnqueue.iterator();
930 while( depsItr.hasNext() ) {
931 Descriptor dNext = depsItr.next();
934 calleesToEnqueue.clear();
940 protected ReachGraph analyzeMethod( Descriptor d )
941 throws java.io.IOException {
943 // get the flat code for this descriptor
945 if( d == mdAnalysisEntry ) {
946 fm = fmAnalysisEntry;
948 fm = state.getMethodFlat( d );
950 pm.analyzeMethod( fm );
952 // intraprocedural work set
953 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
954 flatNodesToVisit.add( fm );
956 // if determinism is desired by client, shadow the
957 // set with a queue to make visit order deterministic
958 Queue<FlatNode> flatNodesToVisitQ = null;
959 if( determinismDesired ) {
960 flatNodesToVisitQ = new LinkedList<FlatNode>();
961 flatNodesToVisitQ.add( fm );
964 // mapping of current partial results
965 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
966 new Hashtable<FlatNode, ReachGraph>();
968 // the set of return nodes partial results that will be combined as
969 // the final, conservative approximation of the entire method
970 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
972 while( !flatNodesToVisit.isEmpty() ) {
975 if( determinismDesired ) {
976 assert !flatNodesToVisitQ.isEmpty();
977 fn = flatNodesToVisitQ.remove();
979 fn = flatNodesToVisit.iterator().next();
981 flatNodesToVisit.remove( fn );
983 // effect transfer function defined by this node,
984 // then compare it to the old graph at this node
985 // to see if anything was updated.
987 ReachGraph rg = new ReachGraph();
988 TaskDescriptor taskDesc;
989 if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null){
990 if(mapDescriptorToReachGraph.containsKey(taskDesc)){
991 // retrieve existing reach graph if it is not first time
992 rg=mapDescriptorToReachGraph.get(taskDesc);
994 // create initial reach graph for a task
995 rg=createInitialTaskReachGraph((FlatMethod)fn);
997 mapDescriptorToReachGraph.put(taskDesc, rg);
1001 // start by merging all node's parents' graphs
1002 for( int i = 0; i < pm.numPrev(fn); ++i ) {
1003 FlatNode pn = pm.getPrev(fn,i);
1004 if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
1005 ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
1006 rg.merge( rgParent );
1011 if( takeDebugSnapshots &&
1012 d.getSymbol().equals( descSymbolDebug )
1014 debugSnapshot( rg, fn, true );
1018 // modify rg with appropriate transfer function
1019 rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
1022 if( takeDebugSnapshots &&
1023 d.getSymbol().equals( descSymbolDebug )
1025 debugSnapshot( rg, fn, false );
1030 // if the results of the new graph are different from
1031 // the current graph at this node, replace the graph
1032 // with the update and enqueue the children
1033 ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
1034 if( !rg.equals( rgPrev ) ) {
1035 mapFlatNodeToReachGraph.put( fn, rg );
1037 for( int i = 0; i < pm.numNext( fn ); i++ ) {
1038 FlatNode nn = pm.getNext( fn, i );
1040 flatNodesToVisit.add( nn );
1041 if( determinismDesired ) {
1042 flatNodesToVisitQ.add( nn );
1049 // end by merging all return nodes into a complete
1050 // reach graph that represents all possible heap
1051 // states after the flat method returns
1052 ReachGraph completeGraph = new ReachGraph();
1054 assert !setReturns.isEmpty();
1055 Iterator retItr = setReturns.iterator();
1056 while( retItr.hasNext() ) {
1057 FlatReturnNode frn = (FlatReturnNode) retItr.next();
1059 assert mapFlatNodeToReachGraph.containsKey( frn );
1060 ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
1062 completeGraph.merge( rgRet );
1066 if( takeDebugSnapshots &&
1067 d.getSymbol().equals( descSymbolDebug )
1069 // increment that we've visited the debug snap
1070 // method, and reset the node counter
1071 System.out.println( " @@@ debug snap at visit "+snapVisitCounter );
1073 snapNodeCounter = 0;
1075 if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
1078 System.out.println( "!!! Stopping analysis after debug snap captures. !!!" );
1084 return completeGraph;
1088 protected ReachGraph
1089 analyzeFlatNode( Descriptor d,
1090 FlatMethod fmContaining,
1092 HashSet<FlatReturnNode> setRetNodes,
1094 ) throws java.io.IOException {
1097 // any variables that are no longer live should be
1098 // nullified in the graph to reduce edges
1099 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
1103 FieldDescriptor fld;
1104 TypeDescriptor tdElement;
1105 FieldDescriptor fdElement;
1106 FlatSESEEnterNode sese;
1107 FlatSESEExitNode fsexn;
1109 // use node type to decide what transfer function
1110 // to apply to the reachability graph
1111 switch( fn.kind() ) {
1113 case FKind.FlatGenReachNode: {
1114 System.out.println( "Generating a reach graph!" );
1115 rg.writeGraph( "genReach"+d,
1116 true, // write labels (variables)
1117 true, // selectively hide intermediate temp vars
1118 true, // prune unreachable heap regions
1119 false, // hide reachability altogether
1120 true, // hide subset reachability states
1121 true, // hide predicates
1122 true ); // hide edge taints
1126 case FKind.FlatMethod: {
1127 // construct this method's initial heap model (IHM)
1128 // since we're working on the FlatMethod, we know
1129 // the incoming ReachGraph 'rg' is empty
1131 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1132 getIHMcontributions( d );
1134 Set entrySet = heapsFromCallers.entrySet();
1135 Iterator itr = entrySet.iterator();
1136 while( itr.hasNext() ) {
1137 Map.Entry me = (Map.Entry) itr.next();
1138 FlatCall fc = (FlatCall) me.getKey();
1139 ReachGraph rgContrib = (ReachGraph) me.getValue();
1141 assert fc.getMethod().equals( d );
1143 rg.merge( rgContrib );
1146 // additionally, we are enforcing STRICT MONOTONICITY for the
1147 // method's initial context, so grow the context by whatever
1148 // the previously computed context was, and put the most
1149 // up-to-date context back in the map
1150 ReachGraph rgPrevContext = mapDescriptorToInitialContext.get( d );
1151 rg.merge( rgPrevContext );
1152 mapDescriptorToInitialContext.put( d, rg );
1156 case FKind.FlatOpNode:
1157 FlatOpNode fon = (FlatOpNode) fn;
1158 if( fon.getOp().getOp() == Operation.ASSIGN ) {
1159 lhs = fon.getDest();
1160 rhs = fon.getLeft();
1162 // before transfer, do effects analysis support
1163 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1164 if(rblockStatus.isInCriticalRegion(fmContaining, fn)){
1165 // x gets status of y
1166 if(!rg.isAccessible(rhs)){
1167 rg.makeInaccessible(lhs);
1173 rg.assignTempXEqualToTempY( lhs, rhs );
1177 case FKind.FlatCastNode:
1178 FlatCastNode fcn = (FlatCastNode) fn;
1182 TypeDescriptor td = fcn.getType();
1185 // before transfer, do effects analysis support
1186 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1187 if(rblockStatus.isInCriticalRegion(fmContaining, fn)){
1188 // x gets status of y
1189 if(!rg.isAccessible(rhs)){
1190 rg.makeInaccessible(lhs);
1196 rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
1199 case FKind.FlatFieldNode:
1200 FlatFieldNode ffn = (FlatFieldNode) fn;
1204 fld = ffn.getField();
1206 // before graph transform, possible inject
1207 // a stall-site taint
1208 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1210 if(rblockStatus.isInCriticalRegion(fmContaining, fn)){
1211 // x=y.f, stall y if not accessible
1212 // contributes read effects on stall site of y
1213 if(!rg.isAccessible(rhs)) {
1214 rg.taintStallSite(fn, rhs);
1217 // after this, x and y are accessbile.
1218 rg.makeAccessible(lhs);
1219 rg.makeAccessible(rhs);
1223 if( shouldAnalysisTrack( fld.getType() ) ) {
1225 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld );
1228 // after transfer, use updated graph to
1229 // do effects analysis
1230 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1231 effectsAnalysis.analyzeFlatFieldNode( rg, rhs, fld );
1235 case FKind.FlatSetFieldNode:
1236 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
1238 lhs = fsfn.getDst();
1239 fld = fsfn.getField();
1240 rhs = fsfn.getSrc();
1242 boolean strongUpdate = false;
1244 // before transfer func, possibly inject
1245 // stall-site taints
1246 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1248 if(rblockStatus.isInCriticalRegion(fmContaining, fn)){
1249 // x.y=f , stall x and y if they are not accessible
1250 // also contribute write effects on stall site of x
1251 if(!rg.isAccessible(lhs)) {
1252 rg.taintStallSite(fn, lhs);
1255 if(!rg.isAccessible(rhs)) {
1256 rg.taintStallSite(fn, rhs);
1259 // accessible status update
1260 rg.makeAccessible(lhs);
1261 rg.makeAccessible(rhs);
1265 if( shouldAnalysisTrack( fld.getType() ) ) {
1267 strongUpdate = rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs );
1270 // use transformed graph to do effects analysis
1271 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1272 effectsAnalysis.analyzeFlatSetFieldNode( rg, lhs, fld, strongUpdate );
1276 case FKind.FlatElementNode:
1277 FlatElementNode fen = (FlatElementNode) fn;
1282 assert rhs.getType() != null;
1283 assert rhs.getType().isArray();
1285 tdElement = rhs.getType().dereference();
1286 fdElement = getArrayField( tdElement );
1288 // before transfer func, possibly inject
1290 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1291 if(rblockStatus.isInCriticalRegion(fmContaining, fn)){
1292 // x=y.f, stall y if not accessible
1293 // contributes read effects on stall site of y
1294 // after this, x and y are accessbile.
1295 if(!rg.isAccessible(rhs)) {
1296 rg.taintStallSite(fn, rhs);
1299 rg.makeAccessible(lhs);
1300 rg.makeAccessible(rhs);
1304 if( shouldAnalysisTrack( lhs.getType() ) ) {
1306 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement );
1309 // use transformed graph to do effects analysis
1310 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1311 effectsAnalysis.analyzeFlatFieldNode( rg, rhs, fdElement );
1315 case FKind.FlatSetElementNode:
1316 FlatSetElementNode fsen = (FlatSetElementNode) fn;
1318 lhs = fsen.getDst();
1319 rhs = fsen.getSrc();
1321 assert lhs.getType() != null;
1322 assert lhs.getType().isArray();
1324 tdElement = lhs.getType().dereference();
1325 fdElement = getArrayField( tdElement );
1327 // before transfer func, possibly inject
1328 // stall-site taints
1329 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1331 if(rblockStatus.isInCriticalRegion(fmContaining, fn)){
1332 // x.y=f , stall x and y if they are not accessible
1333 // also contribute write effects on stall site of x
1334 if(!rg.isAccessible(lhs)) {
1335 rg.taintStallSite(fn, lhs);
1338 if(!rg.isAccessible(rhs)) {
1339 rg.taintStallSite(fn, rhs);
1342 // accessible status update
1343 rg.makeAccessible(lhs);
1344 rg.makeAccessible(rhs);
1348 if( shouldAnalysisTrack( rhs.getType() ) ) {
1349 // transfer func, BUT
1350 // skip this node if it cannot create new reachability paths
1351 if( !arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
1352 rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs );
1356 // use transformed graph to do effects analysis
1357 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1358 effectsAnalysis.analyzeFlatSetFieldNode( rg, lhs, fdElement,
1364 FlatNew fnn = (FlatNew) fn;
1366 if( shouldAnalysisTrack( lhs.getType() ) ) {
1367 AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );
1369 // before transform, support effects analysis
1370 if (doEffectsAnalysis && fmContaining != fmAnalysisEntry) {
1371 if (rblockStatus.isInCriticalRegion(fmContaining, fn)) {
1372 // after creating new object, lhs is accessible
1373 rg.makeAccessible(lhs);
1378 rg.assignTempEqualToNewAlloc( lhs, as );
1382 case FKind.FlatSESEEnterNode:
1383 sese = (FlatSESEEnterNode) fn;
1385 if( sese.getIsCallerSESEplaceholder() ) {
1386 // ignore these dummy rblocks!
1390 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1392 // always remove ALL stall site taints at enter
1393 rg.removeAllStallSiteTaints();
1395 // inject taints for in-set vars
1396 rg.taintInSetVars( sese );
1401 case FKind.FlatSESEExitNode:
1402 fsexn = (FlatSESEExitNode) fn;
1403 sese = fsexn.getFlatEnter();
1405 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1407 // @ sese exit make all live variables
1408 // inaccessible to later parent statements
1409 rg.makeInaccessible( liveness.getLiveInTemps( fmContaining, fn ) );
1411 // always remove ALL stall site taints at exit
1412 rg.removeAllStallSiteTaints();
1414 // remove in-set var taints for the exiting rblock
1415 rg.removeInContextTaints( sese );
1420 case FKind.FlatCall: {
1421 Descriptor mdCaller;
1422 if( fmContaining.getMethod() != null ){
1423 mdCaller = fmContaining.getMethod();
1425 mdCaller = fmContaining.getTask();
1427 FlatCall fc = (FlatCall) fn;
1428 MethodDescriptor mdCallee = fc.getMethod();
1429 FlatMethod fmCallee = state.getMethodFlat( mdCallee );
1432 if( mdCallee.getSymbol().equals( "genReach" ) ) {
1433 rg.writeGraph( "genReach"+d,
1434 true, // write labels (variables)
1435 true, // selectively hide intermediate temp vars
1436 true, // prune unreachable heap regions
1437 false, // hide reachability altogether
1438 true, // hide subset reachability states
1439 true, // hide predicates
1440 true ); // hide edge taints
1446 boolean debugCallSite =
1447 mdCaller.getSymbol().equals( state.DISJOINTDEBUGCALLER ) &&
1448 mdCallee.getSymbol().equals( state.DISJOINTDEBUGCALLEE );
1450 boolean writeDebugDOTs = false;
1451 boolean stopAfter = false;
1452 if( debugCallSite ) {
1453 ++ReachGraph.debugCallSiteVisitCounter;
1454 System.out.println( " $$$ Debug call site visit "+
1455 ReachGraph.debugCallSiteVisitCounter+
1459 (ReachGraph.debugCallSiteVisitCounter >=
1460 ReachGraph.debugCallSiteVisitStartCapture) &&
1462 (ReachGraph.debugCallSiteVisitCounter <
1463 ReachGraph.debugCallSiteVisitStartCapture +
1464 ReachGraph.debugCallSiteNumVisitsToCapture)
1466 writeDebugDOTs = true;
1467 System.out.println( " $$$ Capturing this call site visit $$$" );
1468 if( ReachGraph.debugCallSiteStopAfter &&
1469 (ReachGraph.debugCallSiteVisitCounter ==
1470 ReachGraph.debugCallSiteVisitStartCapture +
1471 ReachGraph.debugCallSiteNumVisitsToCapture - 1)
1479 // calculate the heap this call site can reach--note this is
1480 // not used for the current call site transform, we are
1481 // grabbing this heap model for future analysis of the callees,
1482 // so if different results emerge we will return to this site
1483 ReachGraph heapForThisCall_old =
1484 getIHMcontribution( mdCallee, fc );
1486 // the computation of the callee-reachable heap
1487 // is useful for making the callee starting point
1488 // and for applying the call site transfer function
1489 Set<Integer> callerNodeIDsCopiedToCallee =
1490 new HashSet<Integer>();
1492 ReachGraph heapForThisCall_cur =
1493 rg.makeCalleeView( fc,
1495 callerNodeIDsCopiedToCallee,
1499 // enforce that a call site contribution can only
1500 // monotonically increase
1501 heapForThisCall_cur.merge( heapForThisCall_old );
1503 if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {
1504 // if heap at call site changed, update the contribution,
1505 // and reschedule the callee for analysis
1506 addIHMcontribution( mdCallee, fc, heapForThisCall_cur );
1508 // map a FlatCall to its enclosing method/task descriptor
1509 // so we can write that info out later
1510 fc2enclosing.put( fc, mdCaller );
1512 if( state.DISJOINTDEBUGSCHEDULING ) {
1513 System.out.println( " context changed, scheduling callee: "+mdCallee );
1516 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1517 calleesToEnqueue.add( mdCallee );
1519 enqueue( mdCallee );
1524 // the transformation for a call site should update the
1525 // current heap abstraction with any effects from the callee,
1526 // or if the method is virtual, the effects from any possible
1527 // callees, so find the set of callees...
1528 Set<MethodDescriptor> setPossibleCallees;
1529 if( determinismDesired ) {
1530 // use an ordered set
1531 setPossibleCallees = new TreeSet<MethodDescriptor>( dComp );
1533 // otherwise use a speedy hashset
1534 setPossibleCallees = new HashSet<MethodDescriptor>();
1537 if( mdCallee.isStatic() ) {
1538 setPossibleCallees.add( mdCallee );
1540 TypeDescriptor typeDesc = fc.getThis().getType();
1541 setPossibleCallees.addAll( callGraph.getMethods( mdCallee,
1546 ReachGraph rgMergeOfPossibleCallers = new ReachGraph();
1548 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
1549 while( mdItr.hasNext() ) {
1550 MethodDescriptor mdPossible = mdItr.next();
1551 FlatMethod fmPossible = state.getMethodFlat( mdPossible );
1553 addDependent( mdPossible, // callee
1556 // don't alter the working graph (rg) until we compute a
1557 // result for every possible callee, merge them all together,
1558 // then set rg to that
1559 ReachGraph rgPossibleCaller = new ReachGraph();
1560 rgPossibleCaller.merge( rg );
1562 ReachGraph rgPossibleCallee = getPartial( mdPossible );
1564 if( rgPossibleCallee == null ) {
1565 // if this method has never been analyzed just schedule it
1566 // for analysis and skip over this call site for now
1567 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1568 calleesToEnqueue.add( mdPossible );
1570 enqueue( mdPossible );
1573 if( state.DISJOINTDEBUGSCHEDULING ) {
1574 System.out.println( " callee hasn't been analyzed, scheduling: "+mdPossible );
1579 // calculate the method call transform
1580 rgPossibleCaller.resolveMethodCall( fc,
1583 callerNodeIDsCopiedToCallee,
1587 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1588 if( !rgPossibleCallee.isAccessible( ReachGraph.tdReturn ) ) {
1589 rgPossibleCaller.makeInaccessible( fc.getReturnTemp() );
1595 rgMergeOfPossibleCallers.merge( rgPossibleCaller );
1600 System.out.println( "$$$ Exiting after requested captures of call site. $$$" );
1605 // now that we've taken care of building heap models for
1606 // callee analysis, finish this transformation
1607 rg = rgMergeOfPossibleCallers;
1609 //XXXXXXXXXXXXXXXXXXXXXXXXX
1610 //need to consider more
1611 FlatNode nextFN=fmCallee.getNext(0);
1612 assert nextFN instanceof FlatSESEEnterNode;
1613 FlatSESEEnterNode calleeSESE=(FlatSESEEnterNode)nextFN;
1614 if(!calleeSESE.getIsLeafSESE()){
1615 rg.makeInaccessible( liveness.getLiveInTemps( fmContaining, fn ) );
1621 case FKind.FlatReturnNode:
1622 FlatReturnNode frn = (FlatReturnNode) fn;
1623 rhs = frn.getReturnTemp();
1625 // before transfer, do effects analysis support
1626 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1627 if(!rg.isAccessible(rhs)){
1628 rg.makeInaccessible(ReachGraph.tdReturn);
1632 if( rhs != null && shouldAnalysisTrack( rhs.getType() ) ) {
1633 rg.assignReturnEqualToTemp( rhs );
1636 setRetNodes.add( frn );
1642 // dead variables were removed before the above transfer function
1643 // was applied, so eliminate heap regions and edges that are no
1644 // longer part of the abstractly-live heap graph, and sweep up
1645 // and reachability effects that are altered by the reduction
1646 //rg.abstractGarbageCollect();
1650 // back edges are strictly monotonic
1651 if( pm.isBackEdge( fn ) ) {
1652 ReachGraph rgPrevResult = mapBackEdgeToMonotone.get( fn );
1653 rg.merge( rgPrevResult );
1654 mapBackEdgeToMonotone.put( fn, rg );
1657 // at this point rg should be the correct update
1658 // by an above transfer function, or untouched if
1659 // the flat node type doesn't affect the heap
1665 // this method should generate integers strictly greater than zero!
1666 // special "shadow" regions are made from a heap region by negating
1668 static public Integer generateUniqueHeapRegionNodeID() {
1670 return new Integer( uniqueIDcount );
1675 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
1676 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
1677 if( fdElement == null ) {
1678 fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
1680 arrayElementFieldName,
1683 mapTypeToArrayField.put( tdElement, fdElement );
1690 private void writeFinalGraphs() {
1691 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1692 Iterator itr = entrySet.iterator();
1693 while( itr.hasNext() ) {
1694 Map.Entry me = (Map.Entry) itr.next();
1695 Descriptor d = (Descriptor) me.getKey();
1696 ReachGraph rg = (ReachGraph) me.getValue();
1699 if( d instanceof TaskDescriptor ) {
1700 graphName = "COMPLETEtask"+d;
1702 graphName = "COMPLETE"+d;
1705 rg.writeGraph( graphName,
1706 true, // write labels (variables)
1707 true, // selectively hide intermediate temp vars
1708 true, // prune unreachable heap regions
1709 false, // hide reachability altogether
1710 true, // hide subset reachability states
1711 true, // hide predicates
1712 false ); // hide edge taints
1716 private void writeFinalIHMs() {
1717 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1718 while( d2IHMsItr.hasNext() ) {
1719 Map.Entry me1 = (Map.Entry) d2IHMsItr.next();
1720 Descriptor d = (Descriptor) me1.getKey();
1721 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1723 Iterator fc2rgItr = IHMs.entrySet().iterator();
1724 while( fc2rgItr.hasNext() ) {
1725 Map.Entry me2 = (Map.Entry) fc2rgItr.next();
1726 FlatCall fc = (FlatCall) me2.getKey();
1727 ReachGraph rg = (ReachGraph) me2.getValue();
1729 rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc2enclosing.get( fc )+fc,
1730 true, // write labels (variables)
1731 true, // selectively hide intermediate temp vars
1732 true, // hide reachability altogether
1733 true, // prune unreachable heap regions
1734 true, // hide subset reachability states
1735 false, // hide predicates
1736 true ); // hide edge taints
1741 private void writeInitialContexts() {
1742 Set entrySet = mapDescriptorToInitialContext.entrySet();
1743 Iterator itr = entrySet.iterator();
1744 while( itr.hasNext() ) {
1745 Map.Entry me = (Map.Entry) itr.next();
1746 Descriptor d = (Descriptor) me.getKey();
1747 ReachGraph rg = (ReachGraph) me.getValue();
1749 rg.writeGraph( "INITIAL"+d,
1750 true, // write labels (variables)
1751 true, // selectively hide intermediate temp vars
1752 true, // prune unreachable heap regions
1753 false, // hide all reachability
1754 true, // hide subset reachability states
1755 true, // hide predicates
1756 false );// hide edge taints
1761 protected ReachGraph getPartial( Descriptor d ) {
1762 return mapDescriptorToCompleteReachGraph.get( d );
1765 protected void setPartial( Descriptor d, ReachGraph rg ) {
1766 mapDescriptorToCompleteReachGraph.put( d, rg );
1768 // when the flag for writing out every partial
1769 // result is set, we should spit out the graph,
1770 // but in order to give it a unique name we need
1771 // to track how many partial results for this
1772 // descriptor we've already written out
1773 if( writeAllIncrementalDOTs ) {
1774 if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1775 mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1777 Integer n = mapDescriptorToNumUpdates.get( d );
1780 if( d instanceof TaskDescriptor ) {
1781 graphName = d+"COMPLETEtask"+String.format( "%05d", n );
1783 graphName = d+"COMPLETE"+String.format( "%05d", n );
1786 rg.writeGraph( graphName,
1787 true, // write labels (variables)
1788 true, // selectively hide intermediate temp vars
1789 true, // prune unreachable heap regions
1790 false, // hide all reachability
1791 true, // hide subset reachability states
1792 false, // hide predicates
1793 false); // hide edge taints
1795 mapDescriptorToNumUpdates.put( d, n + 1 );
1801 // return just the allocation site associated with one FlatNew node
1802 protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1804 boolean flagProgrammatically = false;
1805 if( sitesToFlag != null && sitesToFlag.contains( fnew ) ) {
1806 flagProgrammatically = true;
1809 if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1810 AllocSite as = AllocSite.factory( allocationDepth,
1812 fnew.getDisjointId(),
1813 flagProgrammatically
1816 // the newest nodes are single objects
1817 for( int i = 0; i < allocationDepth; ++i ) {
1818 Integer id = generateUniqueHeapRegionNodeID();
1819 as.setIthOldest( i, id );
1820 mapHrnIdToAllocSite.put( id, as );
1823 // the oldest node is a summary node
1824 as.setSummary( generateUniqueHeapRegionNodeID() );
1826 mapFlatNewToAllocSite.put( fnew, as );
1829 return mapFlatNewToAllocSite.get( fnew );
1833 public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1834 // don't track primitive types, but an array
1835 // of primitives is heap memory
1836 if( type.isImmutable() ) {
1837 return type.isArray();
1840 // everything else is an object
1844 protected int numMethodsAnalyzed() {
1845 return descriptorsToAnalyze.size();
1852 // Take in source entry which is the program's compiled entry and
1853 // create a new analysis entry, a method that takes no parameters
1854 // and appears to allocate the command line arguments and call the
1855 // source entry with them. The purpose of this analysis entry is
1856 // to provide a top-level method context with no parameters left.
1857 protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1859 Modifiers mods = new Modifiers();
1860 mods.addModifier( Modifiers.PUBLIC );
1861 mods.addModifier( Modifiers.STATIC );
1863 TypeDescriptor returnType =
1864 new TypeDescriptor( TypeDescriptor.VOID );
1866 this.mdAnalysisEntry =
1867 new MethodDescriptor( mods,
1869 "analysisEntryMethod"
1872 TempDescriptor cmdLineArgs =
1873 new TempDescriptor( "args",
1874 mdSourceEntry.getParamType( 0 )
1878 new FlatNew( mdSourceEntry.getParamType( 0 ),
1883 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1884 sourceEntryArgs[0] = cmdLineArgs;
1887 new FlatCall( mdSourceEntry,
1893 FlatReturnNode frn = new FlatReturnNode( null );
1895 FlatExit fe = new FlatExit();
1897 this.fmAnalysisEntry =
1898 new FlatMethod( mdAnalysisEntry,
1902 this.fmAnalysisEntry.addNext( fn );
1909 protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1911 Set<Descriptor> discovered;
1913 if( determinismDesired ) {
1914 // use an ordered set
1915 discovered = new TreeSet<Descriptor>( dComp );
1917 // otherwise use a speedy hashset
1918 discovered = new HashSet<Descriptor>();
1921 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
1923 Iterator<Descriptor> itr = toSort.iterator();
1924 while( itr.hasNext() ) {
1925 Descriptor d = itr.next();
1927 if( !discovered.contains( d ) ) {
1928 dfsVisit( d, toSort, sorted, discovered );
1935 // While we're doing DFS on call graph, remember
1936 // dependencies for efficient queuing of methods
1937 // during interprocedural analysis:
1939 // a dependent of a method decriptor d for this analysis is:
1940 // 1) a method or task that invokes d
1941 // 2) in the descriptorsToAnalyze set
1942 protected void dfsVisit( Descriptor d,
1943 Set <Descriptor> toSort,
1944 LinkedList<Descriptor> sorted,
1945 Set <Descriptor> discovered ) {
1946 discovered.add( d );
1948 // only methods have callers, tasks never do
1949 if( d instanceof MethodDescriptor ) {
1951 MethodDescriptor md = (MethodDescriptor) d;
1953 // the call graph is not aware that we have a fabricated
1954 // analysis entry that calls the program source's entry
1955 if( md == mdSourceEntry ) {
1956 if( !discovered.contains( mdAnalysisEntry ) ) {
1957 addDependent( mdSourceEntry, // callee
1958 mdAnalysisEntry // caller
1960 dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1964 // otherwise call graph guides DFS
1965 Iterator itr = callGraph.getCallerSet( md ).iterator();
1966 while( itr.hasNext() ) {
1967 Descriptor dCaller = (Descriptor) itr.next();
1969 // only consider callers in the original set to analyze
1970 if( !toSort.contains( dCaller ) ) {
1974 if( !discovered.contains( dCaller ) ) {
1975 addDependent( md, // callee
1979 dfsVisit( dCaller, toSort, sorted, discovered );
1984 // for leaf-nodes last now!
1985 sorted.addLast( d );
1989 protected void enqueue( Descriptor d ) {
1991 if( !descriptorsToVisitSet.contains( d ) ) {
1993 if( state.DISJOINTDVISITSTACK ||
1994 state.DISJOINTDVISITSTACKEESONTOP
1996 descriptorsToVisitStack.add( d );
1998 } else if( state.DISJOINTDVISITPQUE ) {
1999 Integer priority = mapDescriptorToPriority.get( d );
2000 descriptorsToVisitQ.add( new DescriptorQWrapper( priority,
2005 descriptorsToVisitSet.add( d );
2010 // a dependent of a method decriptor d for this analysis is:
2011 // 1) a method or task that invokes d
2012 // 2) in the descriptorsToAnalyze set
2013 protected void addDependent( Descriptor callee, Descriptor caller ) {
2014 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
2015 if( deps == null ) {
2016 deps = new HashSet<Descriptor>();
2019 mapDescriptorToSetDependents.put( callee, deps );
2022 protected Set<Descriptor> getDependents( Descriptor callee ) {
2023 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
2024 if( deps == null ) {
2025 deps = new HashSet<Descriptor>();
2026 mapDescriptorToSetDependents.put( callee, deps );
2032 public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
2034 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2035 mapDescriptorToIHMcontributions.get( d );
2037 if( heapsFromCallers == null ) {
2038 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
2039 mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
2042 return heapsFromCallers;
2045 public ReachGraph getIHMcontribution( Descriptor d,
2048 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2049 getIHMcontributions( d );
2051 if( !heapsFromCallers.containsKey( fc ) ) {
2055 return heapsFromCallers.get( fc );
2059 public void addIHMcontribution( Descriptor d,
2063 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2064 getIHMcontributions( d );
2066 heapsFromCallers.put( fc, rg );
2070 private AllocSite createParameterAllocSite( ReachGraph rg,
2071 TempDescriptor tempDesc,
2077 flatNew = new FlatNew( tempDesc.getType(), // type
2078 tempDesc, // param temp
2079 false, // global alloc?
2080 "param"+tempDesc // disjoint site ID string
2083 flatNew = new FlatNew( tempDesc.getType(), // type
2084 tempDesc, // param temp
2085 false, // global alloc?
2086 null // disjoint site ID string
2090 // create allocation site
2091 AllocSite as = AllocSite.factory( allocationDepth,
2093 flatNew.getDisjointId(),
2096 for (int i = 0; i < allocationDepth; ++i) {
2097 Integer id = generateUniqueHeapRegionNodeID();
2098 as.setIthOldest(i, id);
2099 mapHrnIdToAllocSite.put(id, as);
2101 // the oldest node is a summary node
2102 as.setSummary( generateUniqueHeapRegionNodeID() );
2110 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc){
2112 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
2113 if(!typeDesc.isImmutable()){
2114 ClassDescriptor classDesc = typeDesc.getClassDesc();
2115 for (Iterator it = classDesc.getFields(); it.hasNext();) {
2116 FieldDescriptor field = (FieldDescriptor) it.next();
2117 TypeDescriptor fieldType = field.getType();
2118 if (shouldAnalysisTrack( fieldType )) {
2119 fieldSet.add(field);
2127 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha ){
2129 int dimCount=fd.getType().getArrayCount();
2130 HeapRegionNode prevNode=null;
2131 HeapRegionNode arrayEntryNode=null;
2132 for(int i=dimCount;i>0;i--){
2133 TypeDescriptor typeDesc=fd.getType().dereference();//hack to get instance of type desc
2134 typeDesc.setArrayCount(i);
2135 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
2136 HeapRegionNode hrnSummary ;
2137 if(!mapToExistingNode.containsKey(typeDesc)){
2142 as = createParameterAllocSite(rg, tempDesc, false);
2144 // make a new reference to allocated node
2146 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
2147 false, // single object?
2149 false, // out-of-context?
2150 as.getType(), // type
2151 as, // allocation site
2152 alpha, // inherent reach
2153 alpha, // current reach
2154 ExistPredSet.factory(rg.predTrue), // predicates
2155 tempDesc.toString() // description
2157 rg.id2hrn.put(as.getSummary(),hrnSummary);
2159 mapToExistingNode.put(typeDesc, hrnSummary);
2161 hrnSummary=mapToExistingNode.get(typeDesc);
2165 // make a new reference between new summary node and source
2166 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2169 fd.getSymbol(), // field name
2171 ExistPredSet.factory(rg.predTrue), // predicates
2175 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2176 prevNode=hrnSummary;
2177 arrayEntryNode=hrnSummary;
2179 // make a new reference between summary nodes of array
2180 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2183 arrayElementFieldName, // field name
2185 ExistPredSet.factory(rg.predTrue), // predicates
2189 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2190 prevNode=hrnSummary;
2195 // create a new obj node if obj has at least one non-primitive field
2196 TypeDescriptor type=fd.getType();
2197 if(getFieldSetTobeAnalyzed(type).size()>0){
2198 TypeDescriptor typeDesc=type.dereference();
2199 typeDesc.setArrayCount(0);
2200 if(!mapToExistingNode.containsKey(typeDesc)){
2201 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
2202 AllocSite as = createParameterAllocSite(rg, tempDesc, false);
2203 // make a new reference to allocated node
2204 HeapRegionNode hrnSummary =
2205 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
2206 false, // single object?
2208 false, // out-of-context?
2210 as, // allocation site
2211 alpha, // inherent reach
2212 alpha, // current reach
2213 ExistPredSet.factory(rg.predTrue), // predicates
2214 tempDesc.toString() // description
2216 rg.id2hrn.put(as.getSummary(),hrnSummary);
2217 mapToExistingNode.put(typeDesc, hrnSummary);
2218 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2221 arrayElementFieldName, // field name
2223 ExistPredSet.factory(rg.predTrue), // predicates
2226 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2227 prevNode=hrnSummary;
2229 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
2230 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null){
2231 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2234 arrayElementFieldName, // field name
2236 ExistPredSet.factory(rg.predTrue), // predicates
2239 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2241 prevNode=hrnSummary;
2245 map.put(arrayEntryNode, prevNode);
2246 return arrayEntryNode;
2249 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
2250 ReachGraph rg = new ReachGraph();
2251 TaskDescriptor taskDesc = fm.getTask();
2253 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
2254 Descriptor paramDesc = taskDesc.getParameter(idx);
2255 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
2257 // setup data structure
2258 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
2259 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
2260 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
2261 new Hashtable<TypeDescriptor, HeapRegionNode>();
2262 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
2263 new Hashtable<HeapRegionNode, HeapRegionNode>();
2264 Set<String> doneSet = new HashSet<String>();
2266 TempDescriptor tempDesc = fm.getParameter(idx);
2268 AllocSite as = createParameterAllocSite(rg, tempDesc, true);
2269 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
2270 Integer idNewest = as.getIthOldest(0);
2271 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
2273 // make a new reference to allocated node
2274 RefEdge edgeNew = new RefEdge(lnX, // source
2276 taskDesc.getParamType(idx), // type
2278 hrnNewest.getAlpha(), // beta
2279 ExistPredSet.factory(rg.predTrue), // predicates
2282 rg.addRefEdge(lnX, hrnNewest, edgeNew);
2284 // set-up a work set for class field
2285 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
2286 for (Iterator it = classDesc.getFields(); it.hasNext();) {
2287 FieldDescriptor fd = (FieldDescriptor) it.next();
2288 TypeDescriptor fieldType = fd.getType();
2289 if (shouldAnalysisTrack( fieldType )) {
2290 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
2291 newMap.put(hrnNewest, fd);
2292 workSet.add(newMap);
2296 int uniqueIdentifier = 0;
2297 while (!workSet.isEmpty()) {
2298 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
2300 workSet.remove(map);
2302 Set<HeapRegionNode> key = map.keySet();
2303 HeapRegionNode srcHRN = key.iterator().next();
2304 FieldDescriptor fd = map.get(srcHRN);
2305 TypeDescriptor type = fd.getType();
2306 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
2308 if (!doneSet.contains(doneSetIdentifier)) {
2309 doneSet.add(doneSetIdentifier);
2310 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
2311 // create new summary Node
2312 TempDescriptor td = new TempDescriptor("temp"
2313 + uniqueIdentifier, type);
2315 AllocSite allocSite;
2316 if(type.equals(paramTypeDesc)){
2317 //corresponding allocsite has already been created for a parameter variable.
2320 allocSite = createParameterAllocSite(rg, td, false);
2322 String strDesc = allocSite.toStringForDOT()
2324 TypeDescriptor allocType=allocSite.getType();
2326 HeapRegionNode hrnSummary;
2327 if(allocType.isArray() && allocType.getArrayCount()>0){
2328 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
2331 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
2332 false, // single object?
2334 false, // out-of-context?
2335 allocSite.getType(), // type
2336 allocSite, // allocation site
2337 hrnNewest.getAlpha(), // inherent reach
2338 hrnNewest.getAlpha(), // current reach
2339 ExistPredSet.factory(rg.predTrue), // predicates
2340 strDesc // description
2342 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
2344 // make a new reference to summary node
2345 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2348 fd.getSymbol(), // field name
2349 hrnNewest.getAlpha(), // beta
2350 ExistPredSet.factory(rg.predTrue), // predicates
2354 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2358 mapTypeToExistingSummaryNode.put(type, hrnSummary);
2360 // set-up a work set for fields of the class
2361 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
2362 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
2364 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
2366 HeapRegionNode newDstHRN;
2367 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)){
2368 //related heap region node is already exsited.
2369 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
2371 newDstHRN=hrnSummary;
2373 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
2374 if(!doneSet.contains(doneSetIdentifier)){
2375 // add new work item
2376 HashMap<HeapRegionNode, FieldDescriptor> newMap =
2377 new HashMap<HeapRegionNode, FieldDescriptor>();
2378 newMap.put(newDstHRN, fieldDescriptor);
2379 workSet.add(newMap);
2384 // if there exists corresponding summary node
2385 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
2387 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2389 fd.getType(), // type
2390 fd.getSymbol(), // field name
2391 srcHRN.getAlpha(), // beta
2392 ExistPredSet.factory(rg.predTrue), // predicates
2395 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
2405 // return all allocation sites in the method (there is one allocation
2406 // site per FlatNew node in a method)
2407 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
2408 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
2409 buildAllocationSiteSet(d);
2412 return mapDescriptorToAllocSiteSet.get(d);
2416 private void buildAllocationSiteSet(Descriptor d) {
2417 HashSet<AllocSite> s = new HashSet<AllocSite>();
2420 if( d instanceof MethodDescriptor ) {
2421 fm = state.getMethodFlat( (MethodDescriptor) d);
2423 assert d instanceof TaskDescriptor;
2424 fm = state.getMethodFlat( (TaskDescriptor) d);
2426 pm.analyzeMethod(fm);
2428 // visit every node in this FlatMethod's IR graph
2429 // and make a set of the allocation sites from the
2430 // FlatNew node's visited
2431 HashSet<FlatNode> visited = new HashSet<FlatNode>();
2432 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
2435 while( !toVisit.isEmpty() ) {
2436 FlatNode n = toVisit.iterator().next();
2438 if( n instanceof FlatNew ) {
2439 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
2445 for( int i = 0; i < pm.numNext(n); ++i ) {
2446 FlatNode child = pm.getNext(n, i);
2447 if( !visited.contains(child) ) {
2453 mapDescriptorToAllocSiteSet.put(d, s);
2456 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
2458 HashSet<AllocSite> out = new HashSet<AllocSite>();
2459 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2460 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2464 while (!toVisit.isEmpty()) {
2465 Descriptor d = toVisit.iterator().next();
2469 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2470 Iterator asItr = asSet.iterator();
2471 while (asItr.hasNext()) {
2472 AllocSite as = (AllocSite) asItr.next();
2473 if (as.getDisjointAnalysisId() != null) {
2478 // enqueue callees of this method to be searched for
2479 // allocation sites also
2480 Set callees = callGraph.getCalleeSet(d);
2481 if (callees != null) {
2482 Iterator methItr = callees.iterator();
2483 while (methItr.hasNext()) {
2484 MethodDescriptor md = (MethodDescriptor) methItr.next();
2486 if (!visited.contains(md)) {
2497 private HashSet<AllocSite>
2498 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
2500 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
2501 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2502 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2506 // traverse this task and all methods reachable from this task
2507 while( !toVisit.isEmpty() ) {
2508 Descriptor d = toVisit.iterator().next();
2512 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2513 Iterator asItr = asSet.iterator();
2514 while( asItr.hasNext() ) {
2515 AllocSite as = (AllocSite) asItr.next();
2516 TypeDescriptor typed = as.getType();
2517 if( typed != null ) {
2518 ClassDescriptor cd = typed.getClassDesc();
2519 if( cd != null && cd.hasFlags() ) {
2525 // enqueue callees of this method to be searched for
2526 // allocation sites also
2527 Set callees = callGraph.getCalleeSet(d);
2528 if( callees != null ) {
2529 Iterator methItr = callees.iterator();
2530 while( methItr.hasNext() ) {
2531 MethodDescriptor md = (MethodDescriptor) methItr.next();
2533 if( !visited.contains(md) ) {
2543 public Set<Descriptor> getDescriptorsToAnalyze() {
2544 return descriptorsToAnalyze;
2547 public EffectsAnalysis getEffectsAnalysis(){
2548 return effectsAnalysis;
2551 public ReachGraph getReachGraph(Descriptor d){
2552 return mapDescriptorToCompleteReachGraph.get(d);
2556 // get successive captures of the analysis state, use compiler
2558 boolean takeDebugSnapshots = false;
2559 String descSymbolDebug = null;
2560 boolean stopAfterCapture = false;
2561 int snapVisitCounter = 0;
2562 int snapNodeCounter = 0;
2563 int visitStartCapture = 0;
2564 int numVisitsToCapture = 0;
2567 void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
2568 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2576 if( snapVisitCounter >= visitStartCapture ) {
2577 System.out.println( " @@@ snapping visit="+snapVisitCounter+
2578 ", node="+snapNodeCounter+
2582 graphName = String.format( "snap%03d_%04din",
2586 graphName = String.format( "snap%03d_%04dout",
2591 graphName = graphName + fn;
2593 rg.writeGraph( graphName,
2594 true, // write labels (variables)
2595 true, // selectively hide intermediate temp vars
2596 true, // prune unreachable heap regions
2597 false, // hide reachability
2598 false, // hide subset reachability states
2599 true, // hide predicates
2600 true ); // hide edge taints