1 package Analysis.Disjoint;
3 import Analysis.CallGraph.*;
4 import Analysis.Liveness;
5 import Analysis.ArrayReferencees;
6 import Analysis.OoOJava.Accessible;
7 import Analysis.OoOJava.RBlockRelationAnalysis;
10 import IR.Tree.Modifiers;
15 public class DisjointAnalysis implements HeapAnalysis {
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 TypeUtil typeUtil;
390 public int allocationDepth;
392 protected boolean doEffectsAnalysis = false;
393 protected EffectsAnalysis effectsAnalysis;
394 protected BuildStateMachines buildStateMachines;
397 // data structure for public interface
398 private Hashtable< Descriptor, HashSet<AllocSite> >
399 mapDescriptorToAllocSiteSet;
402 // for public interface methods to warn that they
403 // are grabbing results during analysis
404 private boolean analysisComplete;
407 // used to identify HeapRegionNode objects
408 // A unique ID equates an object in one
409 // ownership graph with an object in another
410 // graph that logically represents the same
412 // start at 10 and increment to reserve some
413 // IDs for special purposes
414 static protected int uniqueIDcount = 10;
417 // An out-of-scope method created by the
418 // analysis that has no parameters, and
419 // appears to allocate the command line
420 // arguments, then invoke the source code's
421 // main method. The purpose of this is to
422 // provide the analysis with an explicit
423 // top-level context with no parameters
424 protected MethodDescriptor mdAnalysisEntry;
425 protected FlatMethod fmAnalysisEntry;
427 // main method defined by source program
428 protected MethodDescriptor mdSourceEntry;
430 // the set of task and/or method descriptors
431 // reachable in call graph
432 protected Set<Descriptor>
433 descriptorsToAnalyze;
435 // current descriptors to visit in fixed-point
436 // interprocedural analysis, prioritized by
437 // dependency in the call graph
438 protected Stack<Descriptor>
439 descriptorsToVisitStack;
440 protected PriorityQueue<DescriptorQWrapper>
443 // a duplication of the above structure, but
444 // for efficient testing of inclusion
445 protected HashSet<Descriptor>
446 descriptorsToVisitSet;
448 // storage for priorities (doesn't make sense)
449 // to add it to the Descriptor class, just in
451 protected Hashtable<Descriptor, Integer>
452 mapDescriptorToPriority;
454 // when analyzing a method and scheduling more:
455 // remember set of callee's enqueued for analysis
456 // so they can be put on top of the callers in
457 // the stack-visit mode
458 protected Set<Descriptor>
461 // maps a descriptor to its current partial result
462 // from the intraprocedural fixed-point analysis--
463 // then the interprocedural analysis settles, this
464 // mapping will have the final results for each
466 protected Hashtable<Descriptor, ReachGraph>
467 mapDescriptorToCompleteReachGraph;
469 // maps a descriptor to its known dependents: namely
470 // methods or tasks that call the descriptor's method
471 // AND are part of this analysis (reachable from main)
472 protected Hashtable< Descriptor, Set<Descriptor> >
473 mapDescriptorToSetDependents;
475 // if the analysis client wants to flag allocation sites
476 // programmatically, it should provide a set of FlatNew
477 // statements--this may be null if unneeded
478 protected Set<FlatNew> sitesToFlag;
480 // maps each flat new to one analysis abstraction
481 // allocate site object, these exist outside reach graphs
482 protected Hashtable<FlatNew, AllocSite>
483 mapFlatNewToAllocSite;
485 // maps intergraph heap region IDs to intergraph
486 // allocation sites that created them, a redundant
487 // structure for efficiency in some operations
488 protected Hashtable<Integer, AllocSite>
491 // maps a method to its initial heap model (IHM) that
492 // is the set of reachability graphs from every caller
493 // site, all merged together. The reason that we keep
494 // them separate is that any one call site's contribution
495 // to the IHM may changed along the path to the fixed point
496 protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
497 mapDescriptorToIHMcontributions;
499 // additionally, keep a mapping from descriptors to the
500 // merged in-coming initial context, because we want this
501 // initial context to be STRICTLY MONOTONIC
502 protected Hashtable<Descriptor, ReachGraph>
503 mapDescriptorToInitialContext;
505 // make the result for back edges analysis-wide STRICTLY
506 // MONOTONIC as well, but notice we use FlatNode as the
507 // key for this map: in case we want to consider other
508 // nodes as back edge's in future implementations
509 protected Hashtable<FlatNode, ReachGraph>
510 mapBackEdgeToMonotone;
513 public static final String arrayElementFieldName = "___element_";
514 static protected Hashtable<TypeDescriptor, FieldDescriptor>
518 protected boolean suppressOutput;
520 // for controlling DOT file output
521 protected boolean writeFinalDOTs;
522 protected boolean writeAllIncrementalDOTs;
524 // supporting DOT output--when we want to write every
525 // partial method result, keep a tally for generating
527 protected Hashtable<Descriptor, Integer>
528 mapDescriptorToNumUpdates;
530 //map task descriptor to initial task parameter
531 protected Hashtable<Descriptor, ReachGraph>
532 mapDescriptorToReachGraph;
534 protected PointerMethod pm;
536 //Keeps track of all the reach graphs at every program point
537 //DO NOT USE UNLESS YOU REALLY NEED IT
538 static protected Hashtable<FlatNode, ReachGraph> fn2rgAtEnter =
539 new Hashtable<FlatNode, ReachGraph>();
541 private Hashtable<FlatCall, Descriptor> fc2enclosing;
543 Accessible accessible;
545 // allocate various structures that are not local
546 // to a single class method--should be done once
547 protected void allocateStructures() {
549 if( determinismDesired ) {
550 // use an ordered set
551 descriptorsToAnalyze = new TreeSet<Descriptor>( dComp );
553 // otherwise use a speedy hashset
554 descriptorsToAnalyze = new HashSet<Descriptor>();
557 mapDescriptorToCompleteReachGraph =
558 new Hashtable<Descriptor, ReachGraph>();
560 mapDescriptorToNumUpdates =
561 new Hashtable<Descriptor, Integer>();
563 mapDescriptorToSetDependents =
564 new Hashtable< Descriptor, Set<Descriptor> >();
566 mapFlatNewToAllocSite =
567 new Hashtable<FlatNew, AllocSite>();
569 mapDescriptorToIHMcontributions =
570 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
572 mapDescriptorToInitialContext =
573 new Hashtable<Descriptor, ReachGraph>();
575 mapBackEdgeToMonotone =
576 new Hashtable<FlatNode, ReachGraph>();
578 mapHrnIdToAllocSite =
579 new Hashtable<Integer, AllocSite>();
581 mapTypeToArrayField =
582 new Hashtable <TypeDescriptor, FieldDescriptor>();
584 if( state.DISJOINTDVISITSTACK ||
585 state.DISJOINTDVISITSTACKEESONTOP
587 descriptorsToVisitStack =
588 new Stack<Descriptor>();
591 if( state.DISJOINTDVISITPQUE ) {
592 descriptorsToVisitQ =
593 new PriorityQueue<DescriptorQWrapper>();
596 descriptorsToVisitSet =
597 new HashSet<Descriptor>();
599 mapDescriptorToPriority =
600 new Hashtable<Descriptor, Integer>();
603 new HashSet<Descriptor>();
605 mapDescriptorToAllocSiteSet =
606 new Hashtable<Descriptor, HashSet<AllocSite> >();
608 mapDescriptorToReachGraph =
609 new Hashtable<Descriptor, ReachGraph>();
611 pm = new PointerMethod();
613 fc2enclosing = new Hashtable<FlatCall, Descriptor>();
618 // this analysis generates a disjoint reachability
619 // graph for every reachable method in the program
620 public DisjointAnalysis( State s,
625 Set<FlatNew> sitesToFlag,
626 RBlockRelationAnalysis rra
628 init( s, tu, cg, l, ar, sitesToFlag, rra, null, false );
631 public DisjointAnalysis( State s,
636 Set<FlatNew> sitesToFlag,
637 RBlockRelationAnalysis rra,
638 boolean suppressOutput
640 init( s, tu, cg, l, ar, sitesToFlag, rra, null, suppressOutput );
643 public DisjointAnalysis( State s,
648 Set<FlatNew> sitesToFlag,
649 RBlockRelationAnalysis rra,
650 BuildStateMachines bsm,
651 boolean suppressOutput
653 init( s, tu, cg, l, ar, sitesToFlag, rra, bsm, suppressOutput );
656 protected void init( State state,
660 ArrayReferencees arrayReferencees,
661 Set<FlatNew> sitesToFlag,
662 RBlockRelationAnalysis rra,
663 BuildStateMachines bsm,
664 boolean suppressOutput
667 analysisComplete = false;
670 this.typeUtil = typeUtil;
671 this.callGraph = callGraph;
672 this.liveness = liveness;
673 this.arrayReferencees = arrayReferencees;
674 this.sitesToFlag = sitesToFlag;
675 this.rblockRel = rra;
676 this.suppressOutput = suppressOutput;
677 this.buildStateMachines = bsm;
679 if( rblockRel != null ) {
680 doEffectsAnalysis = true;
681 effectsAnalysis = new EffectsAnalysis();
683 //note: instead of reachgraph's isAccessible, using the result of accessible analysis
684 //since accessible gives us more accurate results
685 accessible=new Accessible(state, callGraph, rra, liveness);
686 accessible.doAnalysis();
689 this.allocationDepth = state.DISJOINTALLOCDEPTH;
690 this.releaseMode = state.DISJOINTRELEASEMODE;
691 this.determinismDesired = state.DISJOINTDETERMINISM;
693 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL && !suppressOutput;
694 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL && !suppressOutput;
696 this.takeDebugSnapshots = state.DISJOINTSNAPSYMBOL != null;
697 this.descSymbolDebug = state.DISJOINTSNAPSYMBOL;
698 this.visitStartCapture = state.DISJOINTSNAPVISITTOSTART;
699 this.numVisitsToCapture = state.DISJOINTSNAPNUMVISITS;
700 this.stopAfterCapture = state.DISJOINTSNAPSTOPAFTER;
701 this.snapVisitCounter = 1; // count visits from 1 (user will write 1, means 1st visit)
702 this.snapNodeCounter = 0; // count nodes from 0
705 state.DISJOINTDVISITSTACK ||
706 state.DISJOINTDVISITPQUE ||
707 state.DISJOINTDVISITSTACKEESONTOP;
708 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITPQUE);
709 assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITSTACKEESONTOP);
710 assert !(state.DISJOINTDVISITPQUE && state.DISJOINTDVISITSTACKEESONTOP);
712 // set some static configuration for ReachGraphs
713 ReachGraph.allocationDepth = allocationDepth;
714 ReachGraph.typeUtil = typeUtil;
715 ReachGraph.state = state;
717 ReachGraph.debugCallSiteVisitStartCapture
718 = state.DISJOINTDEBUGCALLVISITTOSTART;
720 ReachGraph.debugCallSiteNumVisitsToCapture
721 = state.DISJOINTDEBUGCALLNUMVISITS;
723 ReachGraph.debugCallSiteStopAfter
724 = state.DISJOINTDEBUGCALLSTOPAFTER;
726 ReachGraph.debugCallSiteVisitCounter
727 = 0; // count visits from 1, is incremented before first visit
730 EffectsAnalysis.state = state;
731 EffectsAnalysis.buildStateMachines = buildStateMachines;
734 if( suppressOutput ) {
735 System.out.println( "* Running disjoint reachability analysis with output suppressed! *" );
738 allocateStructures();
740 double timeStartAnalysis = (double) System.nanoTime();
742 // start interprocedural fixed-point computation
745 } catch( IOException e ) {
746 throw new Error( "IO Exception while writing disjointness analysis output." );
749 analysisComplete=true;
751 double timeEndAnalysis = (double) System.nanoTime();
752 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
755 if( sitesToFlag != null ) {
756 treport = String.format( "Disjoint reachability analysis flagged %d sites and took %.3f sec.", sitesToFlag.size(), dt );
757 if(sitesToFlag.size()>0){
758 treport+="\nFlagged sites:"+"\n"+sitesToFlag.toString();
761 treport = String.format( "Disjoint reachability analysis took %.3f sec.", dt );
763 String justtime = String.format( "%.2f", dt );
764 System.out.println( treport );
768 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
772 if( state.DISJOINTWRITEIHMS && !suppressOutput ) {
776 if( state.DISJOINTWRITEINITCONTEXTS && !suppressOutput ) {
777 writeInitialContexts();
780 if( state.DISJOINTALIASFILE != null && !suppressOutput ) {
782 writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
784 writeAllSharingJava(state.DISJOINTALIASFILE,
787 state.DISJOINTALIASTAB,
794 buildStateMachines.writeStateMachines();
797 } catch( IOException e ) {
798 throw new Error( "IO Exception while writing disjointness analysis output." );
803 protected boolean moreDescriptorsToVisit() {
804 if( state.DISJOINTDVISITSTACK ||
805 state.DISJOINTDVISITSTACKEESONTOP
807 return !descriptorsToVisitStack.isEmpty();
809 } else if( state.DISJOINTDVISITPQUE ) {
810 return !descriptorsToVisitQ.isEmpty();
813 throw new Error( "Neither descriptor visiting mode set" );
817 // fixed-point computation over the call graph--when a
818 // method's callees are updated, it must be reanalyzed
819 protected void analyzeMethods() throws java.io.IOException {
821 // task or non-task (java) mode determines what the roots
822 // of the call chain are, and establishes the set of methods
823 // reachable from the roots that will be analyzed
826 if( !suppressOutput ) {
827 System.out.println( "Bamboo mode..." );
830 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
831 while( taskItr.hasNext() ) {
832 TaskDescriptor td = (TaskDescriptor) taskItr.next();
833 if( !descriptorsToAnalyze.contains( td ) ) {
834 // add all methods transitively reachable from the
836 descriptorsToAnalyze.add( td );
837 descriptorsToAnalyze.addAll( callGraph.getAllMethods( td ) );
842 if( !suppressOutput ) {
843 System.out.println( "Java mode..." );
846 // add all methods transitively reachable from the
847 // source's main to set for analysis
848 mdSourceEntry = typeUtil.getMain();
849 descriptorsToAnalyze.add( mdSourceEntry );
850 descriptorsToAnalyze.addAll( callGraph.getAllMethods( mdSourceEntry ) );
852 // fabricate an empty calling context that will call
853 // the source's main, but call graph doesn't know
854 // about it, so explicitly add it
855 makeAnalysisEntryMethod( mdSourceEntry );
856 descriptorsToAnalyze.add( mdAnalysisEntry );
860 // now, depending on the interprocedural mode for visiting
861 // methods, set up the needed data structures
863 if( state.DISJOINTDVISITPQUE ) {
865 // topologically sort according to the call graph so
866 // leaf calls are last, helps build contexts up first
867 LinkedList<Descriptor> sortedDescriptors =
868 topologicalSort( descriptorsToAnalyze );
870 // add sorted descriptors to priority queue, and duplicate
871 // the queue as a set for efficiently testing whether some
872 // method is marked for analysis
874 Iterator<Descriptor> dItr;
876 // for the priority queue, give items at the head
877 // of the sorted list a low number (highest priority)
878 while( !sortedDescriptors.isEmpty() ) {
879 Descriptor d = sortedDescriptors.removeFirst();
880 mapDescriptorToPriority.put( d, new Integer( p ) );
881 descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
882 descriptorsToVisitSet.add( d );
886 } else if( state.DISJOINTDVISITSTACK ||
887 state.DISJOINTDVISITSTACKEESONTOP
889 // if we're doing the stack scheme, just throw the root
890 // method or tasks on the stack
892 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
893 while( taskItr.hasNext() ) {
894 TaskDescriptor td = (TaskDescriptor) taskItr.next();
895 descriptorsToVisitStack.add( td );
896 descriptorsToVisitSet.add( td );
900 descriptorsToVisitStack.add( mdAnalysisEntry );
901 descriptorsToVisitSet.add( mdAnalysisEntry );
905 throw new Error( "Unknown method scheduling mode" );
909 // analyze scheduled methods until there are no more to visit
910 while( moreDescriptorsToVisit() ) {
913 if( state.DISJOINTDVISITSTACK ||
914 state.DISJOINTDVISITSTACKEESONTOP
916 d = descriptorsToVisitStack.pop();
918 } else if( state.DISJOINTDVISITPQUE ) {
919 d = descriptorsToVisitQ.poll().getDescriptor();
922 assert descriptorsToVisitSet.contains( d );
923 descriptorsToVisitSet.remove( d );
925 // because the task or method descriptor just extracted
926 // was in the "to visit" set it either hasn't been analyzed
927 // yet, or some method that it depends on has been
928 // updated. Recompute a complete reachability graph for
929 // this task/method and compare it to any previous result.
930 // If there is a change detected, add any methods/tasks
931 // that depend on this one to the "to visit" set.
933 if( !suppressOutput ) {
934 System.out.println( "Analyzing " + d );
937 if( state.DISJOINTDVISITSTACKEESONTOP ) {
938 assert calleesToEnqueue.isEmpty();
941 ReachGraph rg = analyzeMethod( d );
942 ReachGraph rgPrev = getPartial( d );
944 if( !rg.equals( rgPrev ) ) {
947 if( state.DISJOINTDEBUGSCHEDULING ) {
948 System.out.println( " complete graph changed, scheduling callers for analysis:" );
951 // results for d changed, so enqueue dependents
952 // of d for further analysis
953 Iterator<Descriptor> depsItr = getDependents( d ).iterator();
954 while( depsItr.hasNext() ) {
955 Descriptor dNext = depsItr.next();
958 if( state.DISJOINTDEBUGSCHEDULING ) {
959 System.out.println( " "+dNext );
964 // whether or not the method under analysis changed,
965 // we may have some callees that are scheduled for
966 // more analysis, and they should go on the top of
967 // the stack now (in other method-visiting modes they
968 // are already enqueued at this point
969 if( state.DISJOINTDVISITSTACKEESONTOP ) {
970 Iterator<Descriptor> depsItr = calleesToEnqueue.iterator();
971 while( depsItr.hasNext() ) {
972 Descriptor dNext = depsItr.next();
975 calleesToEnqueue.clear();
981 protected ReachGraph analyzeMethod( Descriptor d )
982 throws java.io.IOException {
984 // get the flat code for this descriptor
986 if( d == mdAnalysisEntry ) {
987 fm = fmAnalysisEntry;
989 fm = state.getMethodFlat( d );
991 pm.analyzeMethod( fm );
993 // intraprocedural work set
994 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
995 flatNodesToVisit.add( fm );
997 // if determinism is desired by client, shadow the
998 // set with a queue to make visit order deterministic
999 Queue<FlatNode> flatNodesToVisitQ = null;
1000 if( determinismDesired ) {
1001 flatNodesToVisitQ = new LinkedList<FlatNode>();
1002 flatNodesToVisitQ.add( fm );
1005 // mapping of current partial results
1006 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
1007 new Hashtable<FlatNode, ReachGraph>();
1009 // the set of return nodes partial results that will be combined as
1010 // the final, conservative approximation of the entire method
1011 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
1013 while( !flatNodesToVisit.isEmpty() ) {
1016 if( determinismDesired ) {
1017 assert !flatNodesToVisitQ.isEmpty();
1018 fn = flatNodesToVisitQ.remove();
1020 fn = flatNodesToVisit.iterator().next();
1022 flatNodesToVisit.remove( fn );
1024 // effect transfer function defined by this node,
1025 // then compare it to the old graph at this node
1026 // to see if anything was updated.
1028 ReachGraph rg = new ReachGraph();
1029 TaskDescriptor taskDesc;
1030 if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null){
1031 if(mapDescriptorToReachGraph.containsKey(taskDesc)){
1032 // retrieve existing reach graph if it is not first time
1033 rg=mapDescriptorToReachGraph.get(taskDesc);
1035 // create initial reach graph for a task
1036 rg=createInitialTaskReachGraph((FlatMethod)fn);
1038 mapDescriptorToReachGraph.put(taskDesc, rg);
1042 // start by merging all node's parents' graphs
1043 for( int i = 0; i < pm.numPrev(fn); ++i ) {
1044 FlatNode pn = pm.getPrev(fn,i);
1045 if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
1046 ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
1047 rg.merge( rgParent );
1052 if( takeDebugSnapshots &&
1053 d.getSymbol().equals( descSymbolDebug )
1055 debugSnapshot( rg, fn, true );
1059 // modify rg with appropriate transfer function
1060 rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
1063 if( takeDebugSnapshots &&
1064 d.getSymbol().equals( descSymbolDebug )
1066 debugSnapshot( rg, fn, false );
1071 // if the results of the new graph are different from
1072 // the current graph at this node, replace the graph
1073 // with the update and enqueue the children
1074 ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
1075 if( !rg.equals( rgPrev ) ) {
1076 mapFlatNodeToReachGraph.put( fn, rg );
1078 for( int i = 0; i < pm.numNext( fn ); i++ ) {
1079 FlatNode nn = pm.getNext( fn, i );
1081 flatNodesToVisit.add( nn );
1082 if( determinismDesired ) {
1083 flatNodesToVisitQ.add( nn );
1090 // end by merging all return nodes into a complete
1091 // reach graph that represents all possible heap
1092 // states after the flat method returns
1093 ReachGraph completeGraph = new ReachGraph();
1095 assert !setReturns.isEmpty();
1096 Iterator retItr = setReturns.iterator();
1097 while( retItr.hasNext() ) {
1098 FlatReturnNode frn = (FlatReturnNode) retItr.next();
1100 assert mapFlatNodeToReachGraph.containsKey( frn );
1101 ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
1103 completeGraph.merge( rgRet );
1107 if( takeDebugSnapshots &&
1108 d.getSymbol().equals( descSymbolDebug )
1110 // increment that we've visited the debug snap
1111 // method, and reset the node counter
1112 System.out.println( " @@@ debug snap at visit "+snapVisitCounter );
1114 snapNodeCounter = 0;
1116 if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
1119 System.out.println( "!!! Stopping analysis after debug snap captures. !!!" );
1125 return completeGraph;
1129 protected ReachGraph
1130 analyzeFlatNode( Descriptor d,
1131 FlatMethod fmContaining,
1133 HashSet<FlatReturnNode> setRetNodes,
1135 ) throws java.io.IOException {
1138 // any variables that are no longer live should be
1139 // nullified in the graph to reduce edges
1140 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
1144 FieldDescriptor fld;
1145 TypeDescriptor tdElement;
1146 FieldDescriptor fdElement;
1147 FlatSESEEnterNode sese;
1148 FlatSESEExitNode fsexn;
1150 //Stores the flatnode's reach graph at enter
1151 ReachGraph rgOnEnter = new ReachGraph();
1152 rgOnEnter.merge( rg );
1153 fn2rgAtEnter.put(fn, rgOnEnter);
1155 // use node type to decide what transfer function
1156 // to apply to the reachability graph
1157 switch( fn.kind() ) {
1159 case FKind.FlatGenReachNode: {
1160 FlatGenReachNode fgrn = (FlatGenReachNode) fn;
1162 System.out.println( " Generating reach graph for program point: "+fgrn.getGraphName() );
1164 rg.writeGraph( "genReach"+fgrn.getGraphName(),
1165 true, // write labels (variables)
1166 true, // selectively hide intermediate temp vars
1167 true, // prune unreachable heap regions
1168 false, // hide reachability altogether
1169 false, // hide subset reachability states
1170 true, // hide predicates
1171 true ); // hide edge taints
1175 case FKind.FlatMethod: {
1176 // construct this method's initial heap model (IHM)
1177 // since we're working on the FlatMethod, we know
1178 // the incoming ReachGraph 'rg' is empty
1180 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1181 getIHMcontributions( d );
1183 Set entrySet = heapsFromCallers.entrySet();
1184 Iterator itr = entrySet.iterator();
1185 while( itr.hasNext() ) {
1186 Map.Entry me = (Map.Entry) itr.next();
1187 FlatCall fc = (FlatCall) me.getKey();
1188 ReachGraph rgContrib = (ReachGraph) me.getValue();
1190 assert fc.getMethod().equals( d );
1192 rg.merge( rgContrib );
1195 // additionally, we are enforcing STRICT MONOTONICITY for the
1196 // method's initial context, so grow the context by whatever
1197 // the previously computed context was, and put the most
1198 // up-to-date context back in the map
1199 ReachGraph rgPrevContext = mapDescriptorToInitialContext.get( d );
1200 rg.merge( rgPrevContext );
1201 mapDescriptorToInitialContext.put( d, rg );
1205 case FKind.FlatOpNode:
1206 FlatOpNode fon = (FlatOpNode) fn;
1207 if( fon.getOp().getOp() == Operation.ASSIGN ) {
1208 lhs = fon.getDest();
1209 rhs = fon.getLeft();
1211 // before transfer, do effects analysis support
1212 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1213 if(rblockRel.isPotentialStallSite(fn)){
1214 // x gets status of y
1215 // if(!rg.isAccessible(rhs)){
1216 if(!accessible.isAccessible(fn, rhs)){
1217 rg.makeInaccessible(lhs);
1223 rg.assignTempXEqualToTempY( lhs, rhs );
1227 case FKind.FlatCastNode:
1228 FlatCastNode fcn = (FlatCastNode) fn;
1232 TypeDescriptor td = fcn.getType();
1235 // before transfer, do effects analysis support
1236 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1237 if(rblockRel.isPotentialStallSite(fn)){
1238 // x gets status of y
1239 // if(!rg.isAccessible(rhs)){
1240 if(!accessible.isAccessible(fn,rhs)){
1241 rg.makeInaccessible(lhs);
1247 rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
1250 case FKind.FlatFieldNode:
1251 FlatFieldNode ffn = (FlatFieldNode) fn;
1255 fld = ffn.getField();
1257 // before graph transform, possible inject
1258 // a stall-site taint
1259 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1261 if(rblockRel.isPotentialStallSite(fn)){
1262 // x=y.f, stall y if not accessible
1263 // contributes read effects on stall site of y
1264 // if(!rg.isAccessible(rhs)) {
1265 if(!accessible.isAccessible(fn,rhs)) {
1266 rg.taintStallSite(fn, rhs);
1269 // after this, x and y are accessbile.
1270 rg.makeAccessible(lhs);
1271 rg.makeAccessible(rhs);
1275 if( shouldAnalysisTrack( fld.getType() ) ) {
1277 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld, fn );
1280 // after transfer, use updated graph to
1281 // do effects analysis
1282 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1283 effectsAnalysis.analyzeFlatFieldNode( rg, rhs, fld, fn );
1287 case FKind.FlatSetFieldNode:
1288 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
1290 lhs = fsfn.getDst();
1291 fld = fsfn.getField();
1292 rhs = fsfn.getSrc();
1294 boolean strongUpdate = false;
1296 // before transfer func, possibly inject
1297 // stall-site taints
1298 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1300 if(rblockRel.isPotentialStallSite(fn)){
1301 // x.y=f , stall x and y if they are not accessible
1302 // also contribute write effects on stall site of x
1303 // if(!rg.isAccessible(lhs)) {
1304 if(!accessible.isAccessible(fn,lhs)) {
1305 rg.taintStallSite(fn, lhs);
1308 // if(!rg.isAccessible(rhs)) {
1309 if(!accessible.isAccessible(fn,rhs)) {
1310 rg.taintStallSite(fn, rhs);
1313 // accessible status update
1314 rg.makeAccessible(lhs);
1315 rg.makeAccessible(rhs);
1319 if( shouldAnalysisTrack( fld.getType() ) ) {
1321 strongUpdate = rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs, fn );
1324 // use transformed graph to do effects analysis
1325 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1326 effectsAnalysis.analyzeFlatSetFieldNode( rg, lhs, fld, fn, strongUpdate );
1330 case FKind.FlatElementNode:
1331 FlatElementNode fen = (FlatElementNode) fn;
1336 assert rhs.getType() != null;
1337 assert rhs.getType().isArray();
1339 tdElement = rhs.getType().dereference();
1340 fdElement = getArrayField( tdElement );
1342 // before transfer func, possibly inject
1344 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1345 if(rblockRel.isPotentialStallSite(fn)){
1346 // x=y.f, stall y if not accessible
1347 // contributes read effects on stall site of y
1348 // after this, x and y are accessbile.
1349 // if(!rg.isAccessible(rhs)) {
1350 if(!accessible.isAccessible(fn,rhs)) {
1351 rg.taintStallSite(fn, rhs);
1354 rg.makeAccessible(lhs);
1355 rg.makeAccessible(rhs);
1359 if( shouldAnalysisTrack( lhs.getType() ) ) {
1361 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement, fn );
1364 // use transformed graph to do effects analysis
1365 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1366 effectsAnalysis.analyzeFlatFieldNode( rg, rhs, fdElement, fn );
1370 case FKind.FlatSetElementNode:
1371 FlatSetElementNode fsen = (FlatSetElementNode) fn;
1373 lhs = fsen.getDst();
1374 rhs = fsen.getSrc();
1376 assert lhs.getType() != null;
1377 assert lhs.getType().isArray();
1379 tdElement = lhs.getType().dereference();
1380 fdElement = getArrayField( tdElement );
1382 // before transfer func, possibly inject
1383 // stall-site taints
1384 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1386 if(rblockRel.isPotentialStallSite(fn)){
1387 // x.y=f , stall x and y if they are not accessible
1388 // also contribute write effects on stall site of x
1389 // if(!rg.isAccessible(lhs)) {
1390 if(!accessible.isAccessible(fn,lhs)) {
1391 rg.taintStallSite(fn, lhs);
1394 // if(!rg.isAccessible(rhs)) {
1395 if(!accessible.isAccessible(fn,rhs)) {
1396 rg.taintStallSite(fn, rhs);
1399 // accessible status update
1400 rg.makeAccessible(lhs);
1401 rg.makeAccessible(rhs);
1405 if( shouldAnalysisTrack( rhs.getType() ) ) {
1406 // transfer func, BUT
1407 // skip this node if it cannot create new reachability paths
1408 if( !arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
1409 rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs, fn );
1413 // use transformed graph to do effects analysis
1414 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1415 effectsAnalysis.analyzeFlatSetFieldNode( rg, lhs, fdElement, fn,
1421 FlatNew fnn = (FlatNew) fn;
1423 if( shouldAnalysisTrack( lhs.getType() ) ) {
1424 AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );
1426 // before transform, support effects analysis
1427 if (doEffectsAnalysis && fmContaining != fmAnalysisEntry) {
1428 if (rblockRel.isPotentialStallSite(fn)) {
1429 // after creating new object, lhs is accessible
1430 rg.makeAccessible(lhs);
1435 rg.assignTempEqualToNewAlloc( lhs, as );
1439 case FKind.FlatSESEEnterNode:
1440 sese = (FlatSESEEnterNode) fn;
1442 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1444 // always remove ALL stall site taints at enter
1445 rg.removeAllStallSiteTaints();
1447 // inject taints for in-set vars
1448 rg.taintInSetVars( sese );
1453 case FKind.FlatSESEExitNode:
1454 fsexn = (FlatSESEExitNode) fn;
1455 sese = fsexn.getFlatEnter();
1457 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1459 // @ sese exit make all live variables
1460 // inaccessible to later parent statements
1461 rg.makeInaccessible( liveness.getLiveInTemps( fmContaining, fn ) );
1463 // always remove ALL stall site taints at exit
1464 rg.removeAllStallSiteTaints();
1466 // remove in-set var taints for the exiting rblock
1467 rg.removeInContextTaints( sese );
1472 case FKind.FlatCall: {
1473 Descriptor mdCaller;
1474 if( fmContaining.getMethod() != null ){
1475 mdCaller = fmContaining.getMethod();
1477 mdCaller = fmContaining.getTask();
1479 FlatCall fc = (FlatCall) fn;
1480 MethodDescriptor mdCallee = fc.getMethod();
1481 FlatMethod fmCallee = state.getMethodFlat( mdCallee );
1484 if( mdCallee.getSymbol().equals( "genReach" ) ) {
1485 rg.writeGraph( "genReach"+d,
1486 true, // write labels (variables)
1487 true, // selectively hide intermediate temp vars
1488 true, // prune unreachable heap regions
1489 false, // hide reachability altogether
1490 true, // hide subset reachability states
1491 true, // hide predicates
1492 true ); // hide edge taints
1498 boolean debugCallSite =
1499 mdCaller.getSymbol().equals( state.DISJOINTDEBUGCALLER ) &&
1500 mdCallee.getSymbol().equals( state.DISJOINTDEBUGCALLEE );
1502 boolean writeDebugDOTs = false;
1503 boolean stopAfter = false;
1504 if( debugCallSite ) {
1505 ++ReachGraph.debugCallSiteVisitCounter;
1506 System.out.println( " $$$ Debug call site visit "+
1507 ReachGraph.debugCallSiteVisitCounter+
1511 (ReachGraph.debugCallSiteVisitCounter >=
1512 ReachGraph.debugCallSiteVisitStartCapture) &&
1514 (ReachGraph.debugCallSiteVisitCounter <
1515 ReachGraph.debugCallSiteVisitStartCapture +
1516 ReachGraph.debugCallSiteNumVisitsToCapture)
1518 writeDebugDOTs = true;
1519 System.out.println( " $$$ Capturing this call site visit $$$" );
1520 if( ReachGraph.debugCallSiteStopAfter &&
1521 (ReachGraph.debugCallSiteVisitCounter ==
1522 ReachGraph.debugCallSiteVisitStartCapture +
1523 ReachGraph.debugCallSiteNumVisitsToCapture - 1)
1531 // calculate the heap this call site can reach--note this is
1532 // not used for the current call site transform, we are
1533 // grabbing this heap model for future analysis of the callees,
1534 // so if different results emerge we will return to this site
1535 ReachGraph heapForThisCall_old =
1536 getIHMcontribution( mdCallee, fc );
1538 // the computation of the callee-reachable heap
1539 // is useful for making the callee starting point
1540 // and for applying the call site transfer function
1541 Set<Integer> callerNodeIDsCopiedToCallee =
1542 new HashSet<Integer>();
1544 ReachGraph heapForThisCall_cur =
1545 rg.makeCalleeView( fc,
1547 callerNodeIDsCopiedToCallee,
1551 // enforce that a call site contribution can only
1552 // monotonically increase
1553 heapForThisCall_cur.merge( heapForThisCall_old );
1555 if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {
1556 // if heap at call site changed, update the contribution,
1557 // and reschedule the callee for analysis
1558 addIHMcontribution( mdCallee, fc, heapForThisCall_cur );
1560 // map a FlatCall to its enclosing method/task descriptor
1561 // so we can write that info out later
1562 fc2enclosing.put( fc, mdCaller );
1564 if( state.DISJOINTDEBUGSCHEDULING ) {
1565 System.out.println( " context changed, scheduling callee: "+mdCallee );
1568 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1569 calleesToEnqueue.add( mdCallee );
1571 enqueue( mdCallee );
1576 // the transformation for a call site should update the
1577 // current heap abstraction with any effects from the callee,
1578 // or if the method is virtual, the effects from any possible
1579 // callees, so find the set of callees...
1580 Set<MethodDescriptor> setPossibleCallees;
1581 if( determinismDesired ) {
1582 // use an ordered set
1583 setPossibleCallees = new TreeSet<MethodDescriptor>( dComp );
1585 // otherwise use a speedy hashset
1586 setPossibleCallees = new HashSet<MethodDescriptor>();
1589 if( mdCallee.isStatic() ) {
1590 setPossibleCallees.add( mdCallee );
1592 TypeDescriptor typeDesc = fc.getThis().getType();
1593 setPossibleCallees.addAll( callGraph.getMethods( mdCallee,
1598 ReachGraph rgMergeOfPossibleCallers = new ReachGraph();
1600 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
1601 while( mdItr.hasNext() ) {
1602 MethodDescriptor mdPossible = mdItr.next();
1603 FlatMethod fmPossible = state.getMethodFlat( mdPossible );
1605 addDependent( mdPossible, // callee
1608 // don't alter the working graph (rg) until we compute a
1609 // result for every possible callee, merge them all together,
1610 // then set rg to that
1611 ReachGraph rgPossibleCaller = new ReachGraph();
1612 rgPossibleCaller.merge( rg );
1614 ReachGraph rgPossibleCallee = getPartial( mdPossible );
1616 if( rgPossibleCallee == null ) {
1617 // if this method has never been analyzed just schedule it
1618 // for analysis and skip over this call site for now
1619 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1620 calleesToEnqueue.add( mdPossible );
1622 enqueue( mdPossible );
1625 if( state.DISJOINTDEBUGSCHEDULING ) {
1626 System.out.println( " callee hasn't been analyzed, scheduling: "+mdPossible );
1630 // calculate the method call transform
1631 rgPossibleCaller.resolveMethodCall( fc,
1634 callerNodeIDsCopiedToCallee,
1638 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1639 // if( !rgPossibleCallee.isAccessible( ReachGraph.tdReturn ) ) {
1640 if( !accessible.isAccessible(fn, ReachGraph.tdReturn ) ) {
1641 rgPossibleCaller.makeInaccessible( fc.getReturnTemp() );
1647 rgMergeOfPossibleCallers.merge( rgPossibleCaller );
1652 System.out.println( "$$$ Exiting after requested captures of call site. $$$" );
1657 // now that we've taken care of building heap models for
1658 // callee analysis, finish this transformation
1659 rg = rgMergeOfPossibleCallers;
1662 // jjenista: what is this? It breaks compilation
1663 // of programs with no tasks/SESEs/rblocks...
1664 //XXXXXXXXXXXXXXXXXXXXXXXXX
1665 //need to consider more
1666 FlatNode nextFN=fmCallee.getNext(0);
1667 if( nextFN instanceof FlatSESEEnterNode ) {
1668 FlatSESEEnterNode calleeSESE=(FlatSESEEnterNode)nextFN;
1669 if(!calleeSESE.getIsLeafSESE()){
1670 rg.makeInaccessible( liveness.getLiveInTemps( fmContaining, fn ) );
1677 case FKind.FlatReturnNode:
1678 FlatReturnNode frn = (FlatReturnNode) fn;
1679 rhs = frn.getReturnTemp();
1681 // before transfer, do effects analysis support
1682 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1683 // if(!rg.isAccessible(rhs)){
1684 if(!accessible.isAccessible(fn,rhs)){
1685 rg.makeInaccessible(ReachGraph.tdReturn);
1689 if( rhs != null && shouldAnalysisTrack( rhs.getType() ) ) {
1690 rg.assignReturnEqualToTemp( rhs );
1693 setRetNodes.add( frn );
1699 // dead variables were removed before the above transfer function
1700 // was applied, so eliminate heap regions and edges that are no
1701 // longer part of the abstractly-live heap graph, and sweep up
1702 // and reachability effects that are altered by the reduction
1703 //rg.abstractGarbageCollect();
1707 // back edges are strictly monotonic
1708 if( pm.isBackEdge( fn ) ) {
1709 ReachGraph rgPrevResult = mapBackEdgeToMonotone.get( fn );
1710 rg.merge( rgPrevResult );
1711 mapBackEdgeToMonotone.put( fn, rg );
1714 // at this point rg should be the correct update
1715 // by an above transfer function, or untouched if
1716 // the flat node type doesn't affect the heap
1722 // this method should generate integers strictly greater than zero!
1723 // special "shadow" regions are made from a heap region by negating
1725 static public Integer generateUniqueHeapRegionNodeID() {
1727 return new Integer( uniqueIDcount );
1732 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
1733 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
1734 if( fdElement == null ) {
1735 fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
1737 arrayElementFieldName,
1740 mapTypeToArrayField.put( tdElement, fdElement );
1747 private void writeFinalGraphs() {
1748 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1749 Iterator itr = entrySet.iterator();
1750 while( itr.hasNext() ) {
1751 Map.Entry me = (Map.Entry) itr.next();
1752 Descriptor d = (Descriptor) me.getKey();
1753 ReachGraph rg = (ReachGraph) me.getValue();
1756 if( d instanceof TaskDescriptor ) {
1757 graphName = "COMPLETEtask"+d;
1759 graphName = "COMPLETE"+d;
1762 rg.writeGraph( graphName,
1763 true, // write labels (variables)
1764 true, // selectively hide intermediate temp vars
1765 true, // prune unreachable heap regions
1766 false, // hide reachability altogether
1767 true, // hide subset reachability states
1768 true, // hide predicates
1769 false ); // hide edge taints
1773 private void writeFinalIHMs() {
1774 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1775 while( d2IHMsItr.hasNext() ) {
1776 Map.Entry me1 = (Map.Entry) d2IHMsItr.next();
1777 Descriptor d = (Descriptor) me1.getKey();
1778 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1780 Iterator fc2rgItr = IHMs.entrySet().iterator();
1781 while( fc2rgItr.hasNext() ) {
1782 Map.Entry me2 = (Map.Entry) fc2rgItr.next();
1783 FlatCall fc = (FlatCall) me2.getKey();
1784 ReachGraph rg = (ReachGraph) me2.getValue();
1786 rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc2enclosing.get( fc )+fc,
1787 true, // write labels (variables)
1788 true, // selectively hide intermediate temp vars
1789 true, // hide reachability altogether
1790 true, // prune unreachable heap regions
1791 true, // hide subset reachability states
1792 false, // hide predicates
1793 true ); // hide edge taints
1798 private void writeInitialContexts() {
1799 Set entrySet = mapDescriptorToInitialContext.entrySet();
1800 Iterator itr = entrySet.iterator();
1801 while( itr.hasNext() ) {
1802 Map.Entry me = (Map.Entry) itr.next();
1803 Descriptor d = (Descriptor) me.getKey();
1804 ReachGraph rg = (ReachGraph) me.getValue();
1806 rg.writeGraph( "INITIAL"+d,
1807 true, // write labels (variables)
1808 true, // selectively hide intermediate temp vars
1809 true, // prune unreachable heap regions
1810 false, // hide all reachability
1811 true, // hide subset reachability states
1812 true, // hide predicates
1813 false );// hide edge taints
1818 protected ReachGraph getPartial( Descriptor d ) {
1819 return mapDescriptorToCompleteReachGraph.get( d );
1822 protected void setPartial( Descriptor d, ReachGraph rg ) {
1823 mapDescriptorToCompleteReachGraph.put( d, rg );
1825 // when the flag for writing out every partial
1826 // result is set, we should spit out the graph,
1827 // but in order to give it a unique name we need
1828 // to track how many partial results for this
1829 // descriptor we've already written out
1830 if( writeAllIncrementalDOTs ) {
1831 if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1832 mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1834 Integer n = mapDescriptorToNumUpdates.get( d );
1837 if( d instanceof TaskDescriptor ) {
1838 graphName = d+"COMPLETEtask"+String.format( "%05d", n );
1840 graphName = d+"COMPLETE"+String.format( "%05d", n );
1843 rg.writeGraph( graphName,
1844 true, // write labels (variables)
1845 true, // selectively hide intermediate temp vars
1846 true, // prune unreachable heap regions
1847 false, // hide all reachability
1848 true, // hide subset reachability states
1849 false, // hide predicates
1850 false); // hide edge taints
1852 mapDescriptorToNumUpdates.put( d, n + 1 );
1858 // return just the allocation site associated with one FlatNew node
1859 protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1861 boolean flagProgrammatically = false;
1862 if( sitesToFlag != null && sitesToFlag.contains( fnew ) ) {
1863 flagProgrammatically = true;
1866 if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1867 AllocSite as = AllocSite.factory( allocationDepth,
1869 fnew.getDisjointId(),
1870 flagProgrammatically
1873 // the newest nodes are single objects
1874 for( int i = 0; i < allocationDepth; ++i ) {
1875 Integer id = generateUniqueHeapRegionNodeID();
1876 as.setIthOldest( i, id );
1877 mapHrnIdToAllocSite.put( id, as );
1880 // the oldest node is a summary node
1881 as.setSummary( generateUniqueHeapRegionNodeID() );
1883 mapFlatNewToAllocSite.put( fnew, as );
1886 return mapFlatNewToAllocSite.get( fnew );
1890 public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1891 // don't track primitive types, but an array
1892 // of primitives is heap memory
1893 if( type.isImmutable() ) {
1894 return type.isArray();
1897 // everything else is an object
1901 protected int numMethodsAnalyzed() {
1902 return descriptorsToAnalyze.size();
1909 // Take in source entry which is the program's compiled entry and
1910 // create a new analysis entry, a method that takes no parameters
1911 // and appears to allocate the command line arguments and call the
1912 // source entry with them. The purpose of this analysis entry is
1913 // to provide a top-level method context with no parameters left.
1914 protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1916 Modifiers mods = new Modifiers();
1917 mods.addModifier( Modifiers.PUBLIC );
1918 mods.addModifier( Modifiers.STATIC );
1920 TypeDescriptor returnType =
1921 new TypeDescriptor( TypeDescriptor.VOID );
1923 this.mdAnalysisEntry =
1924 new MethodDescriptor( mods,
1926 "analysisEntryMethod"
1929 TempDescriptor cmdLineArgs =
1930 new TempDescriptor( "args",
1931 mdSourceEntry.getParamType( 0 )
1935 new FlatNew( mdSourceEntry.getParamType( 0 ),
1940 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1941 sourceEntryArgs[0] = cmdLineArgs;
1944 new FlatCall( mdSourceEntry,
1950 FlatReturnNode frn = new FlatReturnNode( null );
1952 FlatExit fe = new FlatExit();
1954 this.fmAnalysisEntry =
1955 new FlatMethod( mdAnalysisEntry,
1959 this.fmAnalysisEntry.addNext( fn );
1966 protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1968 Set<Descriptor> discovered;
1970 if( determinismDesired ) {
1971 // use an ordered set
1972 discovered = new TreeSet<Descriptor>( dComp );
1974 // otherwise use a speedy hashset
1975 discovered = new HashSet<Descriptor>();
1978 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
1980 Iterator<Descriptor> itr = toSort.iterator();
1981 while( itr.hasNext() ) {
1982 Descriptor d = itr.next();
1984 if( !discovered.contains( d ) ) {
1985 dfsVisit( d, toSort, sorted, discovered );
1992 // While we're doing DFS on call graph, remember
1993 // dependencies for efficient queuing of methods
1994 // during interprocedural analysis:
1996 // a dependent of a method decriptor d for this analysis is:
1997 // 1) a method or task that invokes d
1998 // 2) in the descriptorsToAnalyze set
1999 protected void dfsVisit( Descriptor d,
2000 Set <Descriptor> toSort,
2001 LinkedList<Descriptor> sorted,
2002 Set <Descriptor> discovered ) {
2003 discovered.add( d );
2005 // only methods have callers, tasks never do
2006 if( d instanceof MethodDescriptor ) {
2008 MethodDescriptor md = (MethodDescriptor) d;
2010 // the call graph is not aware that we have a fabricated
2011 // analysis entry that calls the program source's entry
2012 if( md == mdSourceEntry ) {
2013 if( !discovered.contains( mdAnalysisEntry ) ) {
2014 addDependent( mdSourceEntry, // callee
2015 mdAnalysisEntry // caller
2017 dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
2021 // otherwise call graph guides DFS
2022 Iterator itr = callGraph.getCallerSet( md ).iterator();
2023 while( itr.hasNext() ) {
2024 Descriptor dCaller = (Descriptor) itr.next();
2026 // only consider callers in the original set to analyze
2027 if( !toSort.contains( dCaller ) ) {
2031 if( !discovered.contains( dCaller ) ) {
2032 addDependent( md, // callee
2036 dfsVisit( dCaller, toSort, sorted, discovered );
2041 // for leaf-nodes last now!
2042 sorted.addLast( d );
2046 protected void enqueue( Descriptor d ) {
2048 if( !descriptorsToVisitSet.contains( d ) ) {
2050 if( state.DISJOINTDVISITSTACK ||
2051 state.DISJOINTDVISITSTACKEESONTOP
2053 descriptorsToVisitStack.add( d );
2055 } else if( state.DISJOINTDVISITPQUE ) {
2056 Integer priority = mapDescriptorToPriority.get( d );
2057 descriptorsToVisitQ.add( new DescriptorQWrapper( priority,
2062 descriptorsToVisitSet.add( d );
2067 // a dependent of a method decriptor d for this analysis is:
2068 // 1) a method or task that invokes d
2069 // 2) in the descriptorsToAnalyze set
2070 protected void addDependent( Descriptor callee, Descriptor caller ) {
2071 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
2072 if( deps == null ) {
2073 deps = new HashSet<Descriptor>();
2076 mapDescriptorToSetDependents.put( callee, deps );
2079 protected Set<Descriptor> getDependents( Descriptor callee ) {
2080 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
2081 if( deps == null ) {
2082 deps = new HashSet<Descriptor>();
2083 mapDescriptorToSetDependents.put( callee, deps );
2089 public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
2091 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2092 mapDescriptorToIHMcontributions.get( d );
2094 if( heapsFromCallers == null ) {
2095 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
2096 mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
2099 return heapsFromCallers;
2102 public ReachGraph getIHMcontribution( Descriptor d,
2105 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2106 getIHMcontributions( d );
2108 if( !heapsFromCallers.containsKey( fc ) ) {
2112 return heapsFromCallers.get( fc );
2116 public void addIHMcontribution( Descriptor d,
2120 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2121 getIHMcontributions( d );
2123 heapsFromCallers.put( fc, rg );
2127 private AllocSite createParameterAllocSite( ReachGraph rg,
2128 TempDescriptor tempDesc,
2134 flatNew = new FlatNew( tempDesc.getType(), // type
2135 tempDesc, // param temp
2136 false, // global alloc?
2137 "param"+tempDesc // disjoint site ID string
2140 flatNew = new FlatNew( tempDesc.getType(), // type
2141 tempDesc, // param temp
2142 false, // global alloc?
2143 null // disjoint site ID string
2147 // create allocation site
2148 AllocSite as = AllocSite.factory( allocationDepth,
2150 flatNew.getDisjointId(),
2153 for (int i = 0; i < allocationDepth; ++i) {
2154 Integer id = generateUniqueHeapRegionNodeID();
2155 as.setIthOldest(i, id);
2156 mapHrnIdToAllocSite.put(id, as);
2158 // the oldest node is a summary node
2159 as.setSummary( generateUniqueHeapRegionNodeID() );
2167 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc){
2169 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
2170 if(!typeDesc.isImmutable()){
2171 ClassDescriptor classDesc = typeDesc.getClassDesc();
2172 for (Iterator it = classDesc.getFields(); it.hasNext();) {
2173 FieldDescriptor field = (FieldDescriptor) it.next();
2174 TypeDescriptor fieldType = field.getType();
2175 if (shouldAnalysisTrack( fieldType )) {
2176 fieldSet.add(field);
2184 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha ){
2186 int dimCount=fd.getType().getArrayCount();
2187 HeapRegionNode prevNode=null;
2188 HeapRegionNode arrayEntryNode=null;
2189 for(int i=dimCount;i>0;i--){
2190 TypeDescriptor typeDesc=fd.getType().dereference();//hack to get instance of type desc
2191 typeDesc.setArrayCount(i);
2192 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
2193 HeapRegionNode hrnSummary ;
2194 if(!mapToExistingNode.containsKey(typeDesc)){
2199 as = createParameterAllocSite(rg, tempDesc, false);
2201 // make a new reference to allocated node
2203 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
2204 false, // single object?
2206 false, // out-of-context?
2207 as.getType(), // type
2208 as, // allocation site
2209 alpha, // inherent reach
2210 alpha, // current reach
2211 ExistPredSet.factory(rg.predTrue), // predicates
2212 tempDesc.toString() // description
2214 rg.id2hrn.put(as.getSummary(),hrnSummary);
2216 mapToExistingNode.put(typeDesc, hrnSummary);
2218 hrnSummary=mapToExistingNode.get(typeDesc);
2222 // make a new reference between new summary node and source
2223 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2226 fd.getSymbol(), // field name
2228 ExistPredSet.factory(rg.predTrue), // predicates
2232 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2233 prevNode=hrnSummary;
2234 arrayEntryNode=hrnSummary;
2236 // make a new reference between summary nodes of array
2237 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2240 arrayElementFieldName, // field name
2242 ExistPredSet.factory(rg.predTrue), // predicates
2246 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2247 prevNode=hrnSummary;
2252 // create a new obj node if obj has at least one non-primitive field
2253 TypeDescriptor type=fd.getType();
2254 if(getFieldSetTobeAnalyzed(type).size()>0){
2255 TypeDescriptor typeDesc=type.dereference();
2256 typeDesc.setArrayCount(0);
2257 if(!mapToExistingNode.containsKey(typeDesc)){
2258 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
2259 AllocSite as = createParameterAllocSite(rg, tempDesc, false);
2260 // make a new reference to allocated node
2261 HeapRegionNode hrnSummary =
2262 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
2263 false, // single object?
2265 false, // out-of-context?
2267 as, // allocation site
2268 alpha, // inherent reach
2269 alpha, // current reach
2270 ExistPredSet.factory(rg.predTrue), // predicates
2271 tempDesc.toString() // description
2273 rg.id2hrn.put(as.getSummary(),hrnSummary);
2274 mapToExistingNode.put(typeDesc, hrnSummary);
2275 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2278 arrayElementFieldName, // field name
2280 ExistPredSet.factory(rg.predTrue), // predicates
2283 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2284 prevNode=hrnSummary;
2286 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
2287 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null){
2288 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2291 arrayElementFieldName, // field name
2293 ExistPredSet.factory(rg.predTrue), // predicates
2296 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2298 prevNode=hrnSummary;
2302 map.put(arrayEntryNode, prevNode);
2303 return arrayEntryNode;
2306 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
2307 ReachGraph rg = new ReachGraph();
2308 TaskDescriptor taskDesc = fm.getTask();
2310 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
2311 Descriptor paramDesc = taskDesc.getParameter(idx);
2312 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
2314 // setup data structure
2315 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
2316 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
2317 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
2318 new Hashtable<TypeDescriptor, HeapRegionNode>();
2319 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
2320 new Hashtable<HeapRegionNode, HeapRegionNode>();
2321 Set<String> doneSet = new HashSet<String>();
2323 TempDescriptor tempDesc = fm.getParameter(idx);
2325 AllocSite as = createParameterAllocSite(rg, tempDesc, true);
2326 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
2327 Integer idNewest = as.getIthOldest(0);
2328 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
2330 // make a new reference to allocated node
2331 RefEdge edgeNew = new RefEdge(lnX, // source
2333 taskDesc.getParamType(idx), // type
2335 hrnNewest.getAlpha(), // beta
2336 ExistPredSet.factory(rg.predTrue), // predicates
2339 rg.addRefEdge(lnX, hrnNewest, edgeNew);
2341 // set-up a work set for class field
2342 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
2343 for (Iterator it = classDesc.getFields(); it.hasNext();) {
2344 FieldDescriptor fd = (FieldDescriptor) it.next();
2345 TypeDescriptor fieldType = fd.getType();
2346 if (shouldAnalysisTrack( fieldType )) {
2347 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
2348 newMap.put(hrnNewest, fd);
2349 workSet.add(newMap);
2353 int uniqueIdentifier = 0;
2354 while (!workSet.isEmpty()) {
2355 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
2357 workSet.remove(map);
2359 Set<HeapRegionNode> key = map.keySet();
2360 HeapRegionNode srcHRN = key.iterator().next();
2361 FieldDescriptor fd = map.get(srcHRN);
2362 TypeDescriptor type = fd.getType();
2363 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
2365 if (!doneSet.contains(doneSetIdentifier)) {
2366 doneSet.add(doneSetIdentifier);
2367 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
2368 // create new summary Node
2369 TempDescriptor td = new TempDescriptor("temp"
2370 + uniqueIdentifier, type);
2372 AllocSite allocSite;
2373 if(type.equals(paramTypeDesc)){
2374 //corresponding allocsite has already been created for a parameter variable.
2377 allocSite = createParameterAllocSite(rg, td, false);
2379 String strDesc = allocSite.toStringForDOT()
2381 TypeDescriptor allocType=allocSite.getType();
2383 HeapRegionNode hrnSummary;
2384 if(allocType.isArray() && allocType.getArrayCount()>0){
2385 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
2388 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
2389 false, // single object?
2391 false, // out-of-context?
2392 allocSite.getType(), // type
2393 allocSite, // allocation site
2394 hrnNewest.getAlpha(), // inherent reach
2395 hrnNewest.getAlpha(), // current reach
2396 ExistPredSet.factory(rg.predTrue), // predicates
2397 strDesc // description
2399 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
2401 // make a new reference to summary node
2402 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2405 fd.getSymbol(), // field name
2406 hrnNewest.getAlpha(), // beta
2407 ExistPredSet.factory(rg.predTrue), // predicates
2411 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2415 mapTypeToExistingSummaryNode.put(type, hrnSummary);
2417 // set-up a work set for fields of the class
2418 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
2419 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
2421 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
2423 HeapRegionNode newDstHRN;
2424 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)){
2425 //related heap region node is already exsited.
2426 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
2428 newDstHRN=hrnSummary;
2430 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
2431 if(!doneSet.contains(doneSetIdentifier)){
2432 // add new work item
2433 HashMap<HeapRegionNode, FieldDescriptor> newMap =
2434 new HashMap<HeapRegionNode, FieldDescriptor>();
2435 newMap.put(newDstHRN, fieldDescriptor);
2436 workSet.add(newMap);
2441 // if there exists corresponding summary node
2442 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
2444 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2446 fd.getType(), // type
2447 fd.getSymbol(), // field name
2448 srcHRN.getAlpha(), // beta
2449 ExistPredSet.factory(rg.predTrue), // predicates
2452 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
2462 // return all allocation sites in the method (there is one allocation
2463 // site per FlatNew node in a method)
2464 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
2465 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
2466 buildAllocationSiteSet(d);
2469 return mapDescriptorToAllocSiteSet.get(d);
2473 private void buildAllocationSiteSet(Descriptor d) {
2474 HashSet<AllocSite> s = new HashSet<AllocSite>();
2477 if( d instanceof MethodDescriptor ) {
2478 fm = state.getMethodFlat( (MethodDescriptor) d);
2480 assert d instanceof TaskDescriptor;
2481 fm = state.getMethodFlat( (TaskDescriptor) d);
2483 pm.analyzeMethod(fm);
2485 // visit every node in this FlatMethod's IR graph
2486 // and make a set of the allocation sites from the
2487 // FlatNew node's visited
2488 HashSet<FlatNode> visited = new HashSet<FlatNode>();
2489 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
2492 while( !toVisit.isEmpty() ) {
2493 FlatNode n = toVisit.iterator().next();
2495 if( n instanceof FlatNew ) {
2496 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
2502 for( int i = 0; i < pm.numNext(n); ++i ) {
2503 FlatNode child = pm.getNext(n, i);
2504 if( !visited.contains(child) ) {
2510 mapDescriptorToAllocSiteSet.put(d, s);
2513 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
2515 HashSet<AllocSite> out = new HashSet<AllocSite>();
2516 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2517 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2521 while (!toVisit.isEmpty()) {
2522 Descriptor d = toVisit.iterator().next();
2526 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2527 Iterator asItr = asSet.iterator();
2528 while (asItr.hasNext()) {
2529 AllocSite as = (AllocSite) asItr.next();
2530 if (as.getDisjointAnalysisId() != null) {
2535 // enqueue callees of this method to be searched for
2536 // allocation sites also
2537 Set callees = callGraph.getCalleeSet(d);
2538 if (callees != null) {
2539 Iterator methItr = callees.iterator();
2540 while (methItr.hasNext()) {
2541 MethodDescriptor md = (MethodDescriptor) methItr.next();
2543 if (!visited.contains(md)) {
2554 private HashSet<AllocSite>
2555 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
2557 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
2558 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2559 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2563 // traverse this task and all methods reachable from this task
2564 while( !toVisit.isEmpty() ) {
2565 Descriptor d = toVisit.iterator().next();
2569 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2570 Iterator asItr = asSet.iterator();
2571 while( asItr.hasNext() ) {
2572 AllocSite as = (AllocSite) asItr.next();
2573 TypeDescriptor typed = as.getType();
2574 if( typed != null ) {
2575 ClassDescriptor cd = typed.getClassDesc();
2576 if( cd != null && cd.hasFlags() ) {
2582 // enqueue callees of this method to be searched for
2583 // allocation sites also
2584 Set callees = callGraph.getCalleeSet(d);
2585 if( callees != null ) {
2586 Iterator methItr = callees.iterator();
2587 while( methItr.hasNext() ) {
2588 MethodDescriptor md = (MethodDescriptor) methItr.next();
2590 if( !visited.contains(md) ) {
2600 public Set<Descriptor> getDescriptorsToAnalyze() {
2601 return descriptorsToAnalyze;
2604 public EffectsAnalysis getEffectsAnalysis(){
2605 return effectsAnalysis;
2608 public ReachGraph getReachGraph(Descriptor d){
2609 return mapDescriptorToCompleteReachGraph.get(d);
2612 public ReachGraph getEnterReachGraph(FlatNode fn){
2613 return fn2rgAtEnter.get(fn);
2616 // get successive captures of the analysis state, use compiler
2618 boolean takeDebugSnapshots = false;
2619 String descSymbolDebug = null;
2620 boolean stopAfterCapture = false;
2621 int snapVisitCounter = 0;
2622 int snapNodeCounter = 0;
2623 int visitStartCapture = 0;
2624 int numVisitsToCapture = 0;
2627 void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
2628 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2636 if( snapVisitCounter >= visitStartCapture ) {
2637 System.out.println( " @@@ snapping visit="+snapVisitCounter+
2638 ", node="+snapNodeCounter+
2642 graphName = String.format( "snap%03d_%04din",
2646 graphName = String.format( "snap%03d_%04dout",
2651 graphName = graphName + fn;
2653 rg.writeGraph( graphName,
2654 true, // write labels (variables)
2655 true, // selectively hide intermediate temp vars
2656 true, // prune unreachable heap regions
2657 false, // hide reachability
2658 false, // hide subset reachability states
2659 true, // hide predicates
2660 true ); // hide edge taints