bug fixes for unflagged heap regions becoming flagged
[IRC.git] / Robust / src / Analysis / Disjoint / DisjointAnalysis.java
1 package Analysis.Disjoint;
2
3 import Analysis.CallGraph.*;
4 import Analysis.Liveness;
5 import Analysis.ArrayReferencees;
6 import IR.*;
7 import IR.Flat.*;
8 import IR.Tree.Modifiers;
9 import java.util.*;
10 import java.io.*;
11
12
13 public class DisjointAnalysis {
14         
15           ///////////////////////////////////////////
16           //
17           //  Public interface to discover possible
18           //  aliases in the program under analysis
19           //
20           ///////////////////////////////////////////
21         
22           public HashSet<AllocSite>
23           getFlaggedAllocationSitesReachableFromTask(TaskDescriptor td) {
24             checkAnalysisComplete();
25             return getFlaggedAllocationSitesReachableFromTaskPRIVATE(td);
26           }
27           
28           public AllocSite getAllocationSiteFromFlatNew(FlatNew fn) {
29                     checkAnalysisComplete();
30                     return getAllocSiteFromFlatNewPRIVATE(fn);
31            }      
32           
33           public AllocSite getAllocationSiteFromHeapRegionNodeID(Integer id) {
34                     checkAnalysisComplete();
35                     return mapHrnIdToAllocSite.get(id);
36           }
37           
38           public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
39               int paramIndex1,
40               int paramIndex2) {
41                   checkAnalysisComplete();
42                   ReachGraph rg=mapDescriptorToCompleteReachGraph.get(taskOrMethod);
43                   FlatMethod fm=state.getMethodFlat(taskOrMethod);
44                   assert(rg != null);
45                   return rg.mayReachSharedObjects(fm, paramIndex1, paramIndex2);
46           }
47           
48         public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
49                         int paramIndex, AllocSite alloc) {
50                 checkAnalysisComplete();
51                 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
52             FlatMethod fm=state.getMethodFlat(taskOrMethod);
53                 assert (rg != null);
54                 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
55         }
56
57         public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
58                         AllocSite alloc, int paramIndex) {
59                 checkAnalysisComplete();
60                 ReachGraph rg  = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
61                 FlatMethod fm=state.getMethodFlat(taskOrMethod);
62                 assert (rg != null);
63                 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
64         }
65
66         public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
67                         AllocSite alloc1, AllocSite alloc2) {
68                 checkAnalysisComplete();
69                 ReachGraph rg  = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
70                 assert (rg != null);
71                 return rg.mayReachSharedObjects(alloc1, alloc2);
72         }
73         
74         public String prettyPrintNodeSet(Set<HeapRegionNode> s) {
75                 checkAnalysisComplete();
76
77                 String out = "{\n";
78
79                 Iterator<HeapRegionNode> i = s.iterator();
80                 while (i.hasNext()) {
81                         HeapRegionNode n = i.next();
82
83                         AllocSite as = n.getAllocSite();
84                         if (as == null) {
85                                 out += "  " + n.toString() + ",\n";
86                         } else {
87                                 out += "  " + n.toString() + ": " + as.toStringVerbose()
88                                                 + ",\n";
89                         }
90                 }
91
92                 out += "}\n";
93                 return out;
94         }
95         
96   // use the methods given above to check every possible sharing class
97   // between task parameters and flagged allocation sites reachable
98   // from the task
99   public void writeAllSharing(String outputFile, 
100                               String timeReport,
101                               String justTime,
102                               boolean tabularOutput,
103                               int numLines
104                               )
105     throws java.io.IOException {
106     checkAnalysisComplete();
107
108     BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
109
110     if (!tabularOutput) {
111       bw.write("Conducting ownership analysis with allocation depth = "
112                + allocationDepth + "\n");
113       bw.write(timeReport + "\n");
114     }
115
116     int numSharing = 0;
117
118     // look through every task for potential sharing
119     Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
120     while (taskItr.hasNext()) {
121       TaskDescriptor td = (TaskDescriptor) taskItr.next();
122
123       if (!tabularOutput) {
124         bw.write("\n---------" + td + "--------\n");
125       }
126
127       HashSet<AllocSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
128
129       Set<HeapRegionNode> common;
130
131       // for each task parameter, check for sharing classes with
132       // other task parameters and every allocation site
133       // reachable from this task
134       boolean foundSomeSharing = false;
135
136       FlatMethod fm = state.getMethodFlat(td);
137       for (int i = 0; i < fm.numParameters(); ++i) {
138
139         // skip parameters with types that cannot reference
140         // into the heap
141         if( !shouldAnalysisTrack( fm.getParameter( i ).getType() ) ) {
142           continue;
143         }
144                           
145         // for the ith parameter check for sharing classes to all
146         // higher numbered parameters
147         for (int j = i + 1; j < fm.numParameters(); ++j) {
148
149           // skip parameters with types that cannot reference
150           // into the heap
151           if( !shouldAnalysisTrack( fm.getParameter( j ).getType() ) ) {
152             continue;
153           }
154
155
156           common = hasPotentialSharing(td, i, j);
157           if (!common.isEmpty()) {
158             foundSomeSharing = true;
159             ++numSharing;
160             if (!tabularOutput) {
161               bw.write("Potential sharing between parameters " + i
162                        + " and " + j + ".\n");
163               bw.write(prettyPrintNodeSet(common) + "\n");
164             }
165           }
166         }
167
168         // for the ith parameter, check for sharing classes against
169         // the set of allocation sites reachable from this
170         // task context
171         Iterator allocItr = allocSites.iterator();
172         while (allocItr.hasNext()) {
173           AllocSite as = (AllocSite) allocItr.next();
174           common = hasPotentialSharing(td, i, as);
175           if (!common.isEmpty()) {
176             foundSomeSharing = true;
177             ++numSharing;
178             if (!tabularOutput) {
179               bw.write("Potential sharing between parameter " + i
180                        + " and " + as.getFlatNew() + ".\n");
181               bw.write(prettyPrintNodeSet(common) + "\n");
182             }
183           }
184         }
185       }
186
187       // for each allocation site check for sharing classes with
188       // other allocation sites in the context of execution
189       // of this task
190       HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
191       Iterator allocItr1 = allocSites.iterator();
192       while (allocItr1.hasNext()) {
193         AllocSite as1 = (AllocSite) allocItr1.next();
194
195         Iterator allocItr2 = allocSites.iterator();
196         while (allocItr2.hasNext()) {
197           AllocSite as2 = (AllocSite) allocItr2.next();
198
199           if (!outerChecked.contains(as2)) {
200             common = hasPotentialSharing(td, as1, as2);
201
202             if (!common.isEmpty()) {
203               foundSomeSharing = true;
204               ++numSharing;
205               if (!tabularOutput) {
206                 bw.write("Potential sharing between "
207                          + as1.getFlatNew() + " and "
208                          + as2.getFlatNew() + ".\n");
209                 bw.write(prettyPrintNodeSet(common) + "\n");
210               }
211             }
212           }
213         }
214
215         outerChecked.add(as1);
216       }
217
218       if (!foundSomeSharing) {
219         if (!tabularOutput) {
220           bw.write("No sharing between flagged objects in Task " + td
221                    + ".\n");
222         }
223       }
224     }
225
226                 
227     if (tabularOutput) {
228       bw.write(" & " + numSharing + " & " + justTime + " & " + numLines
229                + " & " + numMethodsAnalyzed() + " \\\\\n");
230     } else {
231       bw.write("\nNumber sharing classes: "+numSharing);
232     }
233
234     bw.close();
235   }
236         
237   // this version of writeAllSharing is for Java programs that have no tasks
238   public void writeAllSharingJava(String outputFile, 
239                                   String timeReport,
240                                   String justTime,
241                                   boolean tabularOutput,
242                                   int numLines
243                                   )
244     throws java.io.IOException {
245     checkAnalysisComplete();
246
247     assert !state.TASK;
248
249     int numSharing = 0;
250
251     BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
252     
253     bw.write("Conducting disjoint reachability analysis with allocation depth = "
254              + allocationDepth + "\n");
255     bw.write(timeReport + "\n\n");
256
257     boolean foundSomeSharing = false;
258
259     Descriptor d = typeUtil.getMain();
260     HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
261
262     // for each allocation site check for sharing classes with
263     // other allocation sites in the context of execution
264     // of this task
265     HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
266     Iterator allocItr1 = allocSites.iterator();
267     while (allocItr1.hasNext()) {
268       AllocSite as1 = (AllocSite) allocItr1.next();
269
270       Iterator allocItr2 = allocSites.iterator();
271       while (allocItr2.hasNext()) {
272         AllocSite as2 = (AllocSite) allocItr2.next();
273
274         if (!outerChecked.contains(as2)) {
275           Set<HeapRegionNode> common = hasPotentialSharing(d,
276                                                            as1, as2);
277
278           if (!common.isEmpty()) {
279             foundSomeSharing = true;
280             bw.write("Potential sharing between "
281                      + as1.getDisjointAnalysisId() + " and "
282                      + as2.getDisjointAnalysisId() + ".\n");
283             bw.write(prettyPrintNodeSet(common) + "\n");
284             ++numSharing;
285           }
286         }
287       }
288
289       outerChecked.add(as1);
290     }
291
292     if (!foundSomeSharing) {
293       bw.write("No sharing classes between flagged objects found.\n");
294     } else {
295       bw.write("\nNumber sharing classes: "+numSharing);
296     }
297
298     bw.write("Number of methods analyzed: "+numMethodsAnalyzed()+"\n");
299
300     bw.close();
301   }
302           
303   ///////////////////////////////////////////
304   //
305   // end public interface
306   //
307   ///////////////////////////////////////////
308
309   protected void checkAnalysisComplete() {
310     if( !analysisComplete ) {
311       throw new Error("Warning: public interface method called while analysis is running.");
312     }
313   } 
314
315
316   // run in faster mode, only when bugs wrung out!
317   public static boolean releaseMode;
318
319   // data from the compiler
320   public State            state;
321   public CallGraph        callGraph;
322   public Liveness         liveness;
323   public ArrayReferencees arrayReferencees;
324   public TypeUtil         typeUtil;
325   public int              allocationDepth;
326   
327   // data structure for public interface
328   private Hashtable<Descriptor,    HashSet<AllocSite> > mapDescriptorToAllocSiteSet;
329
330   
331   // for public interface methods to warn that they
332   // are grabbing results during analysis
333   private boolean analysisComplete;
334
335
336   // used to identify HeapRegionNode objects
337   // A unique ID equates an object in one
338   // ownership graph with an object in another
339   // graph that logically represents the same
340   // heap region
341   // start at 10 and increment to reserve some
342   // IDs for special purposes
343   static protected int uniqueIDcount = 10;
344
345
346   // An out-of-scope method created by the
347   // analysis that has no parameters, and
348   // appears to allocate the command line
349   // arguments, then invoke the source code's
350   // main method.  The purpose of this is to
351   // provide the analysis with an explicit
352   // top-level context with no parameters
353   protected MethodDescriptor mdAnalysisEntry;
354   protected FlatMethod       fmAnalysisEntry;
355
356   // main method defined by source program
357   protected MethodDescriptor mdSourceEntry;
358
359   // the set of task and/or method descriptors
360   // reachable in call graph
361   protected Set<Descriptor> 
362     descriptorsToAnalyze;
363
364   // current descriptors to visit in fixed-point
365   // interprocedural analysis, prioritized by
366   // dependency in the call graph
367   protected Stack<DescriptorQWrapper>
368     descriptorsToVisitStack;
369   protected PriorityQueue<DescriptorQWrapper> 
370     descriptorsToVisitQ;
371   
372   // a duplication of the above structure, but
373   // for efficient testing of inclusion
374   protected HashSet<Descriptor> 
375     descriptorsToVisitSet;
376
377   // storage for priorities (doesn't make sense)
378   // to add it to the Descriptor class, just in
379   // this analysis
380   protected Hashtable<Descriptor, Integer> 
381     mapDescriptorToPriority;
382
383
384   // maps a descriptor to its current partial result
385   // from the intraprocedural fixed-point analysis--
386   // then the interprocedural analysis settles, this
387   // mapping will have the final results for each
388   // method descriptor
389   protected Hashtable<Descriptor, ReachGraph> 
390     mapDescriptorToCompleteReachGraph;
391
392   // maps a descriptor to its known dependents: namely
393   // methods or tasks that call the descriptor's method
394   // AND are part of this analysis (reachable from main)
395   protected Hashtable< Descriptor, Set<Descriptor> >
396     mapDescriptorToSetDependents;
397
398   // maps each flat new to one analysis abstraction
399   // allocate site object, these exist outside reach graphs
400   protected Hashtable<FlatNew, AllocSite>
401     mapFlatNewToAllocSite;
402
403   // maps intergraph heap region IDs to intergraph
404   // allocation sites that created them, a redundant
405   // structure for efficiency in some operations
406   protected Hashtable<Integer, AllocSite>
407     mapHrnIdToAllocSite;
408
409   // maps a method to its initial heap model (IHM) that
410   // is the set of reachability graphs from every caller
411   // site, all merged together.  The reason that we keep
412   // them separate is that any one call site's contribution
413   // to the IHM may changed along the path to the fixed point
414   protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
415     mapDescriptorToIHMcontributions;
416
417   // additionally, keep a mapping from descriptors to the
418   // merged in-coming initial context, because we want this
419   // initial context to be STRICTLY MONOTONIC
420   protected Hashtable<Descriptor, ReachGraph>
421     mapDescriptorToInitialContext;
422
423   // make the result for back edges analysis-wide STRICTLY
424   // MONOTONIC as well, but notice we use FlatNode as the
425   // key for this map: in case we want to consider other
426   // nodes as back edge's in future implementations
427   protected Hashtable<FlatNode, ReachGraph>
428     mapBackEdgeToMonotone;
429
430
431   public static final String arrayElementFieldName = "___element_";
432   static protected Hashtable<TypeDescriptor, FieldDescriptor>
433     mapTypeToArrayField;
434
435   // for controlling DOT file output
436   protected boolean writeFinalDOTs;
437   protected boolean writeAllIncrementalDOTs;
438
439   // supporting DOT output--when we want to write every
440   // partial method result, keep a tally for generating
441   // unique filenames
442   protected Hashtable<Descriptor, Integer>
443     mapDescriptorToNumUpdates;
444   
445   //map task descriptor to initial task parameter 
446   protected Hashtable<Descriptor, ReachGraph>
447     mapDescriptorToReachGraph;
448
449   protected PointerMethod pm;
450
451   static protected Hashtable<FlatNode, ReachGraph> fn2rg =
452     new Hashtable<FlatNode, ReachGraph>();
453
454
455   // allocate various structures that are not local
456   // to a single class method--should be done once
457   protected void allocateStructures() {    
458     descriptorsToAnalyze = new HashSet<Descriptor>();
459
460     mapDescriptorToCompleteReachGraph =
461       new Hashtable<Descriptor, ReachGraph>();
462
463     mapDescriptorToNumUpdates =
464       new Hashtable<Descriptor, Integer>();
465
466     mapDescriptorToSetDependents =
467       new Hashtable< Descriptor, Set<Descriptor> >();
468
469     mapFlatNewToAllocSite = 
470       new Hashtable<FlatNew, AllocSite>();
471
472     mapDescriptorToIHMcontributions =
473       new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
474
475     mapDescriptorToInitialContext =
476       new Hashtable<Descriptor, ReachGraph>();    
477
478     mapBackEdgeToMonotone =
479       new Hashtable<FlatNode, ReachGraph>();
480
481     mapHrnIdToAllocSite =
482       new Hashtable<Integer, AllocSite>();
483
484     mapTypeToArrayField = 
485       new Hashtable <TypeDescriptor, FieldDescriptor>();
486
487     if( state.DISJOINTDVISITSTACK ) {
488       descriptorsToVisitStack =
489         new Stack<DescriptorQWrapper>();
490     }
491
492     if( state.DISJOINTDVISITPQUE ) {
493       descriptorsToVisitQ =
494         new PriorityQueue<DescriptorQWrapper>();
495     }
496
497     descriptorsToVisitSet =
498       new HashSet<Descriptor>();
499
500     mapDescriptorToPriority =
501       new Hashtable<Descriptor, Integer>();
502     
503     mapDescriptorToAllocSiteSet =
504         new Hashtable<Descriptor,    HashSet<AllocSite> >();
505     
506     mapDescriptorToReachGraph = 
507         new Hashtable<Descriptor, ReachGraph>();
508   }
509
510
511
512   // this analysis generates a disjoint reachability
513   // graph for every reachable method in the program
514   public DisjointAnalysis( State            s,
515                            TypeUtil         tu,
516                            CallGraph        cg,
517                            Liveness         l,
518                            ArrayReferencees ar
519                            ) throws java.io.IOException {
520     init( s, tu, cg, l, ar );
521   }
522   
523   protected void init( State            state,
524                        TypeUtil         typeUtil,
525                        CallGraph        callGraph,
526                        Liveness         liveness,
527                        ArrayReferencees arrayReferencees
528                        ) throws java.io.IOException {
529           
530     analysisComplete = false;
531     
532     this.state                   = state;
533     this.typeUtil                = typeUtil;
534     this.callGraph               = callGraph;
535     this.liveness                = liveness;
536     this.arrayReferencees        = arrayReferencees;
537     this.allocationDepth         = state.DISJOINTALLOCDEPTH;
538     this.releaseMode             = state.DISJOINTRELEASEMODE;
539
540     this.writeFinalDOTs          = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
541     this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS &&  state.DISJOINTWRITEALL;
542
543     this.takeDebugSnapshots      = state.DISJOINTSNAPSYMBOL != null;
544     this.descSymbolDebug         = state.DISJOINTSNAPSYMBOL;
545     this.visitStartCapture       = state.DISJOINTSNAPVISITTOSTART;
546     this.numVisitsToCapture      = state.DISJOINTSNAPNUMVISITS;
547     this.stopAfterCapture        = state.DISJOINTSNAPSTOPAFTER;
548     this.snapVisitCounter        = 1; // count visits from 1 (user will write 1, means 1st visit)
549     this.snapNodeCounter         = 0; // count nodes from 0
550     this.pm=new PointerMethod();
551
552     assert state.DISJOINTDVISITSTACK || state.DISJOINTDVISITPQUE;
553     assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITPQUE);
554             
555     // set some static configuration for ReachGraphs
556     ReachGraph.allocationDepth = allocationDepth;
557     ReachGraph.typeUtil        = typeUtil;
558
559     ReachGraph.debugCallSiteVisitsUntilExit = state.DISJOINTDEBUGCALLCOUNT;
560
561     allocateStructures();
562
563     double timeStartAnalysis = (double) System.nanoTime();
564
565     // start interprocedural fixed-point computation
566     analyzeMethods();
567     analysisComplete=true;
568
569     double timeEndAnalysis = (double) System.nanoTime();
570     double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
571     String treport = String.format( "The reachability analysis took %.3f sec.", dt );
572     String justtime = String.format( "%.2f", dt );
573     System.out.println( treport );
574
575     if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
576       writeFinalGraphs();      
577     }
578
579     if( state.DISJOINTWRITEIHMS ) {
580       writeFinalIHMs();
581     }
582
583     if( state.DISJOINTALIASFILE != null ) {
584       if( state.TASK ) {
585         writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
586       } else {
587         writeAllSharingJava(state.DISJOINTALIASFILE, 
588                             treport, 
589                             justtime, 
590                             state.DISJOINTALIASTAB, 
591                             state.lines
592                             );
593       }
594     }
595   }
596
597
598   protected boolean moreDescriptorsToVisit() {
599     if( state.DISJOINTDVISITSTACK ) {
600       return !descriptorsToVisitStack.isEmpty();
601
602     } else if( state.DISJOINTDVISITPQUE ) {
603       return !descriptorsToVisitQ.isEmpty();
604     }
605
606     throw new Error( "Neither descriptor visiting mode set" );
607   }
608
609
610   // fixed-point computation over the call graph--when a
611   // method's callees are updated, it must be reanalyzed
612   protected void analyzeMethods() throws java.io.IOException {  
613
614     if( state.TASK ) {
615       // This analysis does not support Bamboo at the moment,
616       // but if it does in the future we would initialize the
617       // set of descriptors to analyze as the program-reachable
618       // tasks and the methods callable by them.  For Java,
619       // just methods reachable from the main method.
620       System.out.println( "Bamboo..." );
621       Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
622       
623       while (taskItr.hasNext()) {
624           TaskDescriptor td = (TaskDescriptor) taskItr.next();
625           if (!descriptorsToAnalyze.contains(td)) {           
626               descriptorsToAnalyze.add(td);
627               descriptorsToAnalyze.addAll(callGraph.getAllMethods(td));
628           }       
629       }
630
631     } else {
632       // add all methods transitively reachable from the
633       // source's main to set for analysis
634       mdSourceEntry = typeUtil.getMain();
635       descriptorsToAnalyze.add( mdSourceEntry );
636       descriptorsToAnalyze.addAll( 
637         callGraph.getAllMethods( mdSourceEntry ) 
638                                    );
639
640       // fabricate an empty calling context that will call
641       // the source's main, but call graph doesn't know
642       // about it, so explicitly add it
643       makeAnalysisEntryMethod( mdSourceEntry );
644       descriptorsToAnalyze.add( mdAnalysisEntry );
645     }
646
647     // topologically sort according to the call graph so 
648     // leaf calls are ordered first, smarter analysis order
649     // CHANGED: order leaf calls last!!
650     LinkedList<Descriptor> sortedDescriptors = 
651       topologicalSort( descriptorsToAnalyze );
652
653     // add sorted descriptors to priority queue, and duplicate
654     // the queue as a set for efficiently testing whether some
655     // method is marked for analysis
656     int p = 0;
657     Iterator<Descriptor> dItr = sortedDescriptors.iterator();
658     while( dItr.hasNext() ) {
659       Descriptor d = dItr.next();
660
661       mapDescriptorToPriority.put( d, new Integer( p ) );
662
663       if( state.DISJOINTDVISITSTACK ) {
664         descriptorsToVisitStack.add( new DescriptorQWrapper( p, d ) );
665
666       } else if( state.DISJOINTDVISITPQUE ) {
667         descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
668       }
669
670       descriptorsToVisitSet.add( d );
671       ++p;
672     }
673
674     // analyze methods from the priority queue until it is empty
675     while( moreDescriptorsToVisit() ) {
676       Descriptor d = null;
677
678       if( state.DISJOINTDVISITSTACK ) {
679         d = descriptorsToVisitStack.pop().getDescriptor();
680
681       } else if( state.DISJOINTDVISITPQUE ) {
682         d = descriptorsToVisitQ.poll().getDescriptor();
683       }
684
685       assert descriptorsToVisitSet.contains( d );
686       descriptorsToVisitSet.remove( d );
687
688       // because the task or method descriptor just extracted
689       // was in the "to visit" set it either hasn't been analyzed
690       // yet, or some method that it depends on has been
691       // updated.  Recompute a complete reachability graph for
692       // this task/method and compare it to any previous result.
693       // If there is a change detected, add any methods/tasks
694       // that depend on this one to the "to visit" set.
695
696       System.out.println( "Analyzing " + d );
697
698       ReachGraph rg     = analyzeMethod( d );
699       ReachGraph rgPrev = getPartial( d );
700       
701       if( !rg.equals( rgPrev ) ) {
702         setPartial( d, rg );
703         
704         // results for d changed, so enqueue dependents
705         // of d for further analysis
706         Iterator<Descriptor> depsItr = getDependents( d ).iterator();
707         while( depsItr.hasNext() ) {
708           Descriptor dNext = depsItr.next();
709           enqueue( dNext );
710         }
711       }      
712     }
713   }
714
715   protected ReachGraph analyzeMethod( Descriptor d ) 
716     throws java.io.IOException {
717
718     // get the flat code for this descriptor
719     FlatMethod fm;
720     if( d == mdAnalysisEntry ) {
721       fm = fmAnalysisEntry;
722     } else {
723       fm = state.getMethodFlat( d );
724     }
725     pm.analyzeMethod( fm );
726
727     // intraprocedural work set
728     Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
729     flatNodesToVisit.add( fm );
730
731     Set<FlatNode> debugVisited = new HashSet<FlatNode>();
732     
733     // mapping of current partial results
734     Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
735       new Hashtable<FlatNode, ReachGraph>();
736
737     // the set of return nodes partial results that will be combined as
738     // the final, conservative approximation of the entire method
739     HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
740
741     while( !flatNodesToVisit.isEmpty() ) {
742       FlatNode fn = (FlatNode) flatNodesToVisit.iterator().next();
743       flatNodesToVisit.remove( fn );
744
745       debugVisited.add( fn );
746
747       // effect transfer function defined by this node,
748       // then compare it to the old graph at this node
749       // to see if anything was updated.
750
751       ReachGraph rg = new ReachGraph();
752       TaskDescriptor taskDesc;
753       if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null){
754           if(mapDescriptorToReachGraph.containsKey(taskDesc)){
755                   // retrieve existing reach graph if it is not first time
756                   rg=mapDescriptorToReachGraph.get(taskDesc);
757           }else{
758                   // create initial reach graph for a task
759                   rg=createInitialTaskReachGraph((FlatMethod)fn);
760                   rg.globalSweep();
761                   mapDescriptorToReachGraph.put(taskDesc, rg);
762           }
763       }
764
765       // start by merging all node's parents' graphs
766       for( int i = 0; i < pm.numPrev(fn); ++i ) {
767         FlatNode pn = pm.getPrev(fn,i);
768         if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
769           ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
770           rg.merge( rgParent );
771         }
772       }
773
774
775       if( takeDebugSnapshots && 
776           d.getSymbol().equals( descSymbolDebug ) 
777           ) {
778         debugSnapshot( rg, fn, true );
779       }
780
781
782       // modify rg with appropriate transfer function
783       rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
784
785
786       if( takeDebugSnapshots && 
787           d.getSymbol().equals( descSymbolDebug ) 
788           ) {
789         debugSnapshot( rg, fn, false );
790         ++snapNodeCounter;
791       }
792           
793
794       // if the results of the new graph are different from
795       // the current graph at this node, replace the graph
796       // with the update and enqueue the children
797       ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
798       if( !rg.equals( rgPrev ) ) {
799         mapFlatNodeToReachGraph.put( fn, rg );
800
801         for( int i = 0; i < pm.numNext(fn); i++ ) {
802           FlatNode nn = pm.getNext(fn, i);
803           flatNodesToVisit.add( nn );
804         }
805       }
806     }
807
808
809     // assert that the fixed-point results for each
810     // node in the method is no smaller than the last
811     // time this method was analyzed (monotonicity)
812     /*
813     Iterator<FlatNode> nItr = fm.getNodeSet().iterator();
814     while( nItr.hasNext() ) {
815       FlatNode   fn     = nItr.next();      
816       ReachGraph last   = fn2rg.get( fn );
817       ReachGraph newest = mapFlatNodeToReachGraph.get( fn );
818
819       if( newest == null ) {
820         System.out.println( "**********\nfn null result: "+fn+
821                             "\nnum visited="+debugVisited.size()+", num in set="+fm.getNodeSet().size()+
822                             "\nvisited:"+debugVisited );
823       }
824
825       assert newest != null;
826       if( last != null ) {
827         if( !ReachGraph.isNoSmallerThan( last, newest ) ) {
828           last.writeGraph( "last", true, false, false, true, true );
829           newest.writeGraph( "newest", true, false, false, true, true );
830           throw new Error( "transfer func for "+fn+" was not monotic" );
831         }
832       }
833       fn2rg.put( fn, newest );
834     }
835     */
836
837     // end by merging all return nodes into a complete
838     // reach graph that represents all possible heap
839     // states after the flat method returns
840     ReachGraph completeGraph = new ReachGraph();
841
842     assert !setReturns.isEmpty();
843     Iterator retItr = setReturns.iterator();
844     while( retItr.hasNext() ) {
845       FlatReturnNode frn = (FlatReturnNode) retItr.next();
846
847       assert mapFlatNodeToReachGraph.containsKey( frn );
848       ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
849
850       completeGraph.merge( rgRet );
851     }
852
853
854     if( takeDebugSnapshots && 
855         d.getSymbol().equals( descSymbolDebug ) 
856         ) {
857       // increment that we've visited the debug snap
858       // method, and reset the node counter
859       System.out.println( "    @@@ debug snap at visit "+snapVisitCounter );
860       ++snapVisitCounter;
861       snapNodeCounter = 0;
862
863       if( snapVisitCounter == visitStartCapture + numVisitsToCapture && 
864           stopAfterCapture 
865           ) {
866         System.out.println( "!!! Stopping analysis after debug snap captures. !!!" );
867         System.exit( 0 );
868       }
869     }
870
871
872     return completeGraph;
873   }
874
875   
876   protected ReachGraph
877     analyzeFlatNode( Descriptor              d,
878                      FlatMethod              fmContaining,
879                      FlatNode                fn,
880                      HashSet<FlatReturnNode> setRetNodes,
881                      ReachGraph              rg
882                      ) throws java.io.IOException {
883
884     
885     // any variables that are no longer live should be
886     // nullified in the graph to reduce edges
887     //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
888
889           
890     TempDescriptor  lhs;
891     TempDescriptor  rhs;
892     FieldDescriptor fld;
893
894     // use node type to decide what transfer function
895     // to apply to the reachability graph
896     switch( fn.kind() ) {
897
898     case FKind.FlatMethod: {
899       // construct this method's initial heap model (IHM)
900       // since we're working on the FlatMethod, we know
901       // the incoming ReachGraph 'rg' is empty
902
903       Hashtable<FlatCall, ReachGraph> heapsFromCallers = 
904         getIHMcontributions( d );
905
906       Set entrySet = heapsFromCallers.entrySet();
907       Iterator itr = entrySet.iterator();
908       while( itr.hasNext() ) {
909         Map.Entry  me        = (Map.Entry)  itr.next();
910         FlatCall   fc        = (FlatCall)   me.getKey();
911         ReachGraph rgContrib = (ReachGraph) me.getValue();
912
913         assert fc.getMethod().equals( d );
914
915         rg.merge( rgContrib );
916       }
917
918       // additionally, we are enforcing STRICT MONOTONICITY for the
919       // method's initial context, so grow the context by whatever
920       // the previously computed context was, and put the most
921       // up-to-date context back in the map
922       ReachGraph rgPrevContext = mapDescriptorToInitialContext.get( d );
923       rg.merge( rgPrevContext );      
924       mapDescriptorToInitialContext.put( d, rg );
925
926     } break;
927       
928     case FKind.FlatOpNode:
929       FlatOpNode fon = (FlatOpNode) fn;
930       if( fon.getOp().getOp() == Operation.ASSIGN ) {
931         lhs = fon.getDest();
932         rhs = fon.getLeft();
933         rg.assignTempXEqualToTempY( lhs, rhs );
934       }
935       break;
936
937     case FKind.FlatCastNode:
938       FlatCastNode fcn = (FlatCastNode) fn;
939       lhs = fcn.getDst();
940       rhs = fcn.getSrc();
941
942       TypeDescriptor td = fcn.getType();
943       assert td != null;
944       
945       rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
946       break;
947
948     case FKind.FlatFieldNode:
949       FlatFieldNode ffn = (FlatFieldNode) fn;
950       lhs = ffn.getDst();
951       rhs = ffn.getSrc();
952       fld = ffn.getField();
953       if( shouldAnalysisTrack( fld.getType() ) ) {
954         rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld );
955       }          
956       break;
957
958     case FKind.FlatSetFieldNode:
959       FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
960       lhs = fsfn.getDst();
961       fld = fsfn.getField();
962       rhs = fsfn.getSrc();
963       if( shouldAnalysisTrack( fld.getType() ) ) {
964         rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs );
965       }           
966       break;
967
968     case FKind.FlatElementNode:
969       FlatElementNode fen = (FlatElementNode) fn;
970       lhs = fen.getDst();
971       rhs = fen.getSrc();
972       if( shouldAnalysisTrack( lhs.getType() ) ) {
973
974         assert rhs.getType() != null;
975         assert rhs.getType().isArray();
976         
977         TypeDescriptor  tdElement = rhs.getType().dereference();
978         FieldDescriptor fdElement = getArrayField( tdElement );
979   
980         rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement );
981       }
982       break;
983
984     case FKind.FlatSetElementNode:
985       FlatSetElementNode fsen = (FlatSetElementNode) fn;
986
987       if( arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
988         // skip this node if it cannot create new reachability paths
989         break;
990       }
991
992       lhs = fsen.getDst();
993       rhs = fsen.getSrc();
994       if( shouldAnalysisTrack( rhs.getType() ) ) {
995
996         assert lhs.getType() != null;
997         assert lhs.getType().isArray();
998         
999         TypeDescriptor  tdElement = lhs.getType().dereference();
1000         FieldDescriptor fdElement = getArrayField( tdElement );
1001
1002         rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs );
1003       }
1004       break;
1005       
1006     case FKind.FlatNew:
1007       FlatNew fnn = (FlatNew) fn;
1008       lhs = fnn.getDst();
1009       if( shouldAnalysisTrack( lhs.getType() ) ) {
1010         AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );   
1011         rg.assignTempEqualToNewAlloc( lhs, as );
1012       }
1013       break;
1014
1015     case FKind.FlatCall: {
1016       //TODO: temporal fix for task descriptor case
1017       //MethodDescriptor mdCaller = fmContaining.getMethod();
1018       Descriptor mdCaller;
1019       if(fmContaining.getMethod()!=null){
1020           mdCaller  = fmContaining.getMethod();
1021       }else{
1022           mdCaller = fmContaining.getTask();
1023       }      
1024       FlatCall         fc       = (FlatCall) fn;
1025       MethodDescriptor mdCallee = fc.getMethod();
1026       FlatMethod       fmCallee = state.getMethodFlat( mdCallee );
1027
1028       boolean writeDebugDOTs = 
1029         mdCaller.getSymbol().equals( state.DISJOINTDEBUGCALLER ) &&
1030         mdCallee.getSymbol().equals( state.DISJOINTDEBUGCALLEE );      
1031
1032
1033       // calculate the heap this call site can reach--note this is
1034       // not used for the current call site transform, we are
1035       // grabbing this heap model for future analysis of the callees,
1036       // so if different results emerge we will return to this site
1037       ReachGraph heapForThisCall_old = 
1038         getIHMcontribution( mdCallee, fc );
1039
1040       // the computation of the callee-reachable heap
1041       // is useful for making the callee starting point
1042       // and for applying the call site transfer function
1043       Set<Integer> callerNodeIDsCopiedToCallee = 
1044         new HashSet<Integer>();
1045
1046       ReachGraph heapForThisCall_cur = 
1047         rg.makeCalleeView( fc, 
1048                            fmCallee,
1049                            callerNodeIDsCopiedToCallee,
1050                            writeDebugDOTs
1051                            );
1052
1053       if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {        
1054         // if heap at call site changed, update the contribution,
1055         // and reschedule the callee for analysis
1056         addIHMcontribution( mdCallee, fc, heapForThisCall_cur );        
1057         enqueue( mdCallee );
1058       }
1059
1060
1061
1062
1063       // the transformation for a call site should update the
1064       // current heap abstraction with any effects from the callee,
1065       // or if the method is virtual, the effects from any possible
1066       // callees, so find the set of callees...
1067       Set<MethodDescriptor> setPossibleCallees =
1068         new HashSet<MethodDescriptor>();
1069
1070       if( mdCallee.isStatic() ) {        
1071         setPossibleCallees.add( mdCallee );
1072       } else {
1073         TypeDescriptor typeDesc = fc.getThis().getType();
1074         setPossibleCallees.addAll( callGraph.getMethods( mdCallee, 
1075                                                          typeDesc )
1076                                    );
1077       }
1078
1079       ReachGraph rgMergeOfEffects = new ReachGraph();
1080
1081       Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
1082       while( mdItr.hasNext() ) {
1083         MethodDescriptor mdPossible = mdItr.next();
1084         FlatMethod       fmPossible = state.getMethodFlat( mdPossible );
1085
1086         addDependent( mdPossible, // callee
1087                       d );        // caller
1088
1089         // don't alter the working graph (rg) until we compute a 
1090         // result for every possible callee, merge them all together,
1091         // then set rg to that
1092         ReachGraph rgCopy = new ReachGraph();
1093         rgCopy.merge( rg );             
1094                 
1095         ReachGraph rgEffect = getPartial( mdPossible );
1096
1097         if( rgEffect == null ) {
1098           // if this method has never been analyzed just schedule it 
1099           // for analysis and skip over this call site for now
1100           enqueue( mdPossible );
1101         } else {
1102           rgCopy.resolveMethodCall( fc, 
1103                                     fmPossible, 
1104                                     rgEffect,
1105                                     callerNodeIDsCopiedToCallee,
1106                                     writeDebugDOTs
1107                                     );
1108         }
1109         
1110         rgMergeOfEffects.merge( rgCopy );
1111       }
1112
1113
1114       // now that we've taken care of building heap models for
1115       // callee analysis, finish this transformation
1116       rg = rgMergeOfEffects;
1117     } break;
1118       
1119
1120     case FKind.FlatReturnNode:
1121       FlatReturnNode frn = (FlatReturnNode) fn;
1122       rhs = frn.getReturnTemp();
1123       if( rhs != null && shouldAnalysisTrack( rhs.getType() ) ) {
1124         rg.assignReturnEqualToTemp( rhs );
1125       }
1126       setRetNodes.add( frn );
1127       break;
1128
1129     } // end switch
1130
1131     
1132     // dead variables were removed before the above transfer function
1133     // was applied, so eliminate heap regions and edges that are no
1134     // longer part of the abstractly-live heap graph, and sweep up
1135     // and reachability effects that are altered by the reduction
1136     //rg.abstractGarbageCollect();
1137     //rg.globalSweep();
1138
1139
1140     // back edges are strictly monotonic
1141     if( pm.isBackEdge( fn ) ) {
1142       ReachGraph rgPrevResult = mapBackEdgeToMonotone.get( fn );
1143       rg.merge( rgPrevResult );
1144       mapBackEdgeToMonotone.put( fn, rg );
1145     }
1146     
1147     // at this point rg should be the correct update
1148     // by an above transfer function, or untouched if
1149     // the flat node type doesn't affect the heap
1150     return rg;
1151   }
1152
1153
1154   
1155   // this method should generate integers strictly greater than zero!
1156   // special "shadow" regions are made from a heap region by negating
1157   // the ID
1158   static public Integer generateUniqueHeapRegionNodeID() {
1159     ++uniqueIDcount;
1160     return new Integer( uniqueIDcount );
1161   }
1162
1163
1164   
1165   static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
1166     FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
1167     if( fdElement == null ) {
1168       fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
1169                                        tdElement,
1170                                        arrayElementFieldName,
1171                                        null,
1172                                        false );
1173       mapTypeToArrayField.put( tdElement, fdElement );
1174     }
1175     return fdElement;
1176   }
1177
1178   
1179   
1180   private void writeFinalGraphs() {
1181     Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1182     Iterator itr = entrySet.iterator();
1183     while( itr.hasNext() ) {
1184       Map.Entry  me = (Map.Entry)  itr.next();
1185       Descriptor  d = (Descriptor) me.getKey();
1186       ReachGraph rg = (ReachGraph) me.getValue();
1187
1188       rg.writeGraph( "COMPLETE"+d,
1189                      true,   // write labels (variables)                
1190                      true,   // selectively hide intermediate temp vars 
1191                      true,   // prune unreachable heap regions          
1192                      false,  // hide subset reachability states         
1193                      true ); // hide edge taints                        
1194     }
1195   }
1196
1197   private void writeFinalIHMs() {
1198     Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1199     while( d2IHMsItr.hasNext() ) {
1200       Map.Entry                        me1 = (Map.Entry)                       d2IHMsItr.next();
1201       Descriptor                         d = (Descriptor)                      me1.getKey();
1202       Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1203
1204       Iterator fc2rgItr = IHMs.entrySet().iterator();
1205       while( fc2rgItr.hasNext() ) {
1206         Map.Entry  me2 = (Map.Entry)  fc2rgItr.next();
1207         FlatCall   fc  = (FlatCall)   me2.getKey();
1208         ReachGraph rg  = (ReachGraph) me2.getValue();
1209                 
1210         rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc,
1211                        true,   // write labels (variables)
1212                        true,   // selectively hide intermediate temp vars
1213                        true,   // prune unreachable heap regions
1214                        false,  // hide subset reachability states
1215                        true ); // hide edge taints
1216       }
1217     }
1218   }
1219    
1220
1221   protected ReachGraph getPartial( Descriptor d ) {
1222     return mapDescriptorToCompleteReachGraph.get( d );
1223   }
1224
1225   protected void setPartial( Descriptor d, ReachGraph rg ) {
1226     mapDescriptorToCompleteReachGraph.put( d, rg );
1227
1228     // when the flag for writing out every partial
1229     // result is set, we should spit out the graph,
1230     // but in order to give it a unique name we need
1231     // to track how many partial results for this
1232     // descriptor we've already written out
1233     if( writeAllIncrementalDOTs ) {
1234       if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1235         mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1236       }
1237       Integer n = mapDescriptorToNumUpdates.get( d );
1238       
1239       rg.writeGraph( d+"COMPLETE"+String.format( "%05d", n ),
1240                      true,   // write labels (variables)
1241                      true,   // selectively hide intermediate temp vars
1242                      true,   // prune unreachable heap regions
1243                      false,  // hide subset reachability states
1244                      true ); // hide edge taints
1245       
1246       mapDescriptorToNumUpdates.put( d, n + 1 );
1247     }
1248   }
1249
1250
1251
1252   // return just the allocation site associated with one FlatNew node
1253   protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1254
1255     if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1256       AllocSite as = AllocSite.factory( allocationDepth, 
1257                                         fnew, 
1258                                         fnew.getDisjointId() 
1259                                         );
1260
1261       // the newest nodes are single objects
1262       for( int i = 0; i < allocationDepth; ++i ) {
1263         Integer id = generateUniqueHeapRegionNodeID();
1264         as.setIthOldest( i, id );
1265         mapHrnIdToAllocSite.put( id, as );
1266       }
1267
1268       // the oldest node is a summary node
1269       as.setSummary( generateUniqueHeapRegionNodeID() );
1270
1271       mapFlatNewToAllocSite.put( fnew, as );
1272     }
1273
1274     return mapFlatNewToAllocSite.get( fnew );
1275   }
1276
1277
1278   public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1279     // don't track primitive types, but an array
1280     // of primitives is heap memory
1281     if( type.isImmutable() ) {
1282       return type.isArray();
1283     }
1284
1285     // everything else is an object
1286     return true;
1287   }
1288
1289   protected int numMethodsAnalyzed() {    
1290     return descriptorsToAnalyze.size();
1291   }
1292   
1293
1294   
1295   
1296   
1297   // Take in source entry which is the program's compiled entry and
1298   // create a new analysis entry, a method that takes no parameters
1299   // and appears to allocate the command line arguments and call the
1300   // source entry with them.  The purpose of this analysis entry is
1301   // to provide a top-level method context with no parameters left.
1302   protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1303
1304     Modifiers mods = new Modifiers();
1305     mods.addModifier( Modifiers.PUBLIC );
1306     mods.addModifier( Modifiers.STATIC );
1307
1308     TypeDescriptor returnType = 
1309       new TypeDescriptor( TypeDescriptor.VOID );
1310
1311     this.mdAnalysisEntry = 
1312       new MethodDescriptor( mods,
1313                             returnType,
1314                             "analysisEntryMethod"
1315                             );
1316
1317     TempDescriptor cmdLineArgs = 
1318       new TempDescriptor( "args",
1319                           mdSourceEntry.getParamType( 0 )
1320                           );
1321
1322     FlatNew fn = 
1323       new FlatNew( mdSourceEntry.getParamType( 0 ),
1324                    cmdLineArgs,
1325                    false // is global 
1326                    );
1327     
1328     TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1329     sourceEntryArgs[0] = cmdLineArgs;
1330     
1331     FlatCall fc = 
1332       new FlatCall( mdSourceEntry,
1333                     null, // dst temp
1334                     null, // this temp
1335                     sourceEntryArgs
1336                     );
1337
1338     FlatReturnNode frn = new FlatReturnNode( null );
1339
1340     FlatExit fe = new FlatExit();
1341
1342     this.fmAnalysisEntry = 
1343       new FlatMethod( mdAnalysisEntry, 
1344                       fe
1345                       );
1346
1347     this.fmAnalysisEntry.addNext( fn );
1348     fn.addNext( fc );
1349     fc.addNext( frn );
1350     frn.addNext( fe );
1351   }
1352
1353
1354   protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1355
1356     Set       <Descriptor> discovered = new HashSet   <Descriptor>();
1357     LinkedList<Descriptor> sorted     = new LinkedList<Descriptor>();
1358   
1359     Iterator<Descriptor> itr = toSort.iterator();
1360     while( itr.hasNext() ) {
1361       Descriptor d = itr.next();
1362           
1363       if( !discovered.contains( d ) ) {
1364         dfsVisit( d, toSort, sorted, discovered );
1365       }
1366     }
1367     
1368     return sorted;
1369   }
1370   
1371   // While we're doing DFS on call graph, remember
1372   // dependencies for efficient queuing of methods
1373   // during interprocedural analysis:
1374   //
1375   // a dependent of a method decriptor d for this analysis is:
1376   //  1) a method or task that invokes d
1377   //  2) in the descriptorsToAnalyze set
1378   protected void dfsVisit( Descriptor             d,
1379                            Set       <Descriptor> toSort,                        
1380                            LinkedList<Descriptor> sorted,
1381                            Set       <Descriptor> discovered ) {
1382     discovered.add( d );
1383     
1384     // only methods have callers, tasks never do
1385     if( d instanceof MethodDescriptor ) {
1386
1387       MethodDescriptor md = (MethodDescriptor) d;
1388
1389       // the call graph is not aware that we have a fabricated
1390       // analysis entry that calls the program source's entry
1391       if( md == mdSourceEntry ) {
1392         if( !discovered.contains( mdAnalysisEntry ) ) {
1393           addDependent( mdSourceEntry,  // callee
1394                         mdAnalysisEntry // caller
1395                         );
1396           dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1397         }
1398       }
1399
1400       // otherwise call graph guides DFS
1401       Iterator itr = callGraph.getCallerSet( md ).iterator();
1402       while( itr.hasNext() ) {
1403         Descriptor dCaller = (Descriptor) itr.next();
1404         
1405         // only consider callers in the original set to analyze
1406         if( !toSort.contains( dCaller ) ) {
1407           continue;
1408         }
1409           
1410         if( !discovered.contains( dCaller ) ) {
1411           addDependent( md,     // callee
1412                         dCaller // caller
1413                         );
1414
1415           dfsVisit( dCaller, toSort, sorted, discovered );
1416         }
1417       }
1418     }
1419     
1420     // for leaf-nodes last now!
1421     sorted.addLast( d );
1422   }
1423
1424
1425   protected void enqueue( Descriptor d ) {
1426     if( !descriptorsToVisitSet.contains( d ) ) {
1427       Integer priority = mapDescriptorToPriority.get( d );
1428
1429       if( state.DISJOINTDVISITSTACK ) {
1430         descriptorsToVisitStack.add( new DescriptorQWrapper( priority, 
1431                                                              d ) 
1432                                      );
1433
1434       } else if( state.DISJOINTDVISITPQUE ) {
1435         descriptorsToVisitQ.add( new DescriptorQWrapper( priority, 
1436                                                          d ) 
1437                                  );
1438       }
1439
1440       descriptorsToVisitSet.add( d );
1441     }
1442   }
1443
1444
1445   // a dependent of a method decriptor d for this analysis is:
1446   //  1) a method or task that invokes d
1447   //  2) in the descriptorsToAnalyze set
1448   protected void addDependent( Descriptor callee, Descriptor caller ) {
1449     Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1450     if( deps == null ) {
1451       deps = new HashSet<Descriptor>();
1452     }
1453     deps.add( caller );
1454     mapDescriptorToSetDependents.put( callee, deps );
1455   }
1456   
1457   protected Set<Descriptor> getDependents( Descriptor callee ) {
1458     Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1459     if( deps == null ) {
1460       deps = new HashSet<Descriptor>();
1461       mapDescriptorToSetDependents.put( callee, deps );
1462     }
1463     return deps;
1464   }
1465
1466   
1467   public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
1468
1469     Hashtable<FlatCall, ReachGraph> heapsFromCallers = 
1470       mapDescriptorToIHMcontributions.get( d );
1471     
1472     if( heapsFromCallers == null ) {
1473       heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
1474       mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
1475     }
1476     
1477     return heapsFromCallers;
1478   }
1479
1480   public ReachGraph getIHMcontribution( Descriptor d, 
1481                                         FlatCall   fc
1482                                         ) {
1483     Hashtable<FlatCall, ReachGraph> heapsFromCallers = 
1484       getIHMcontributions( d );
1485
1486     if( !heapsFromCallers.containsKey( fc ) ) {
1487       heapsFromCallers.put( fc, new ReachGraph() );
1488     }
1489
1490     return heapsFromCallers.get( fc );
1491   }
1492
1493   public void addIHMcontribution( Descriptor d,
1494                                   FlatCall   fc,
1495                                   ReachGraph rg
1496                                   ) {
1497     Hashtable<FlatCall, ReachGraph> heapsFromCallers = 
1498       getIHMcontributions( d );
1499
1500     heapsFromCallers.put( fc, rg );
1501   }
1502
1503   private AllocSite createParameterAllocSite( ReachGraph     rg, 
1504                                               TempDescriptor tempDesc
1505                                               ) {
1506     
1507     FlatNew flatNew = new FlatNew( tempDesc.getType(), // type
1508                                    tempDesc,           // param temp
1509                                    false,              // global alloc?
1510                                    "param"+tempDesc    // disjoint site ID string
1511                                    );
1512     // create allocation site
1513     AllocSite as = AllocSite.factory( allocationDepth, 
1514                                       flatNew, 
1515                                       flatNew.getDisjointId()
1516                                       );
1517     for (int i = 0; i < allocationDepth; ++i) {
1518         Integer id = generateUniqueHeapRegionNodeID();
1519         as.setIthOldest(i, id);
1520         mapHrnIdToAllocSite.put(id, as);
1521     }
1522     // the oldest node is a summary node
1523     as.setSummary( generateUniqueHeapRegionNodeID() );
1524     
1525     rg.age(as);
1526     
1527     return as;
1528     
1529   }
1530
1531 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc){
1532         
1533         Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
1534     if(!typeDesc.isImmutable()){
1535             ClassDescriptor classDesc = typeDesc.getClassDesc();                    
1536             for (Iterator it = classDesc.getFields(); it.hasNext();) {
1537                     FieldDescriptor field = (FieldDescriptor) it.next();
1538                     TypeDescriptor fieldType = field.getType();
1539                     if (shouldAnalysisTrack( fieldType )) {
1540                         fieldSet.add(field);                    
1541                     }
1542             }
1543     }
1544     return fieldSet;
1545         
1546 }
1547
1548   private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha ){
1549
1550         int dimCount=fd.getType().getArrayCount();
1551         HeapRegionNode prevNode=null;
1552         HeapRegionNode arrayEntryNode=null;
1553         for(int i=dimCount;i>0;i--){
1554                 TypeDescriptor typeDesc=fd.getType().dereference();//hack to get instance of type desc
1555                 typeDesc.setArrayCount(i);
1556                 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
1557                 HeapRegionNode hrnSummary ;
1558                 if(!mapToExistingNode.containsKey(typeDesc)){
1559                         AllocSite as;
1560                         if(i==dimCount){
1561                                 as = alloc;
1562                         }else{
1563                                 as = createParameterAllocSite(rg, tempDesc);
1564                         }
1565                         // make a new reference to allocated node
1566                     hrnSummary = 
1567                                 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1568                                                            false, // single object?
1569                                                            true, // summary?
1570                                                            false, // out-of-context?
1571                                                            as.getType(), // type
1572                                                            as, // allocation site
1573                                                            alpha, // inherent reach
1574                                                            alpha, // current reach
1575                                                            ExistPredSet.factory(rg.predTrue), // predicates
1576                                                            tempDesc.toString() // description
1577                                                            );
1578                     rg.id2hrn.put(as.getSummary(),hrnSummary);
1579                     
1580                     mapToExistingNode.put(typeDesc, hrnSummary);
1581                 }else{
1582                         hrnSummary=mapToExistingNode.get(typeDesc);
1583                 }
1584             
1585             if(prevNode==null){
1586                     // make a new reference between new summary node and source
1587                     RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1588                                                         hrnSummary, // dest
1589                                                         typeDesc, // type
1590                                                         fd.getSymbol(), // field name
1591                                                         alpha, // beta
1592                                                         ExistPredSet.factory(rg.predTrue) // predicates
1593                                                         );
1594                     
1595                     rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1596                     prevNode=hrnSummary;
1597                     arrayEntryNode=hrnSummary;
1598             }else{
1599                     // make a new reference between summary nodes of array
1600                     RefEdge edgeToSummary = new RefEdge(prevNode, // source
1601                                                         hrnSummary, // dest
1602                                                         typeDesc, // type
1603                                                         arrayElementFieldName, // field name
1604                                                         alpha, // beta
1605                                                         ExistPredSet.factory(rg.predTrue) // predicates
1606                                                         );
1607                     
1608                     rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1609                     prevNode=hrnSummary;
1610             }
1611             
1612         }
1613         
1614         // create a new obj node if obj has at least one non-primitive field
1615         TypeDescriptor type=fd.getType();
1616     if(getFieldSetTobeAnalyzed(type).size()>0){
1617         TypeDescriptor typeDesc=type.dereference();
1618         typeDesc.setArrayCount(0);
1619         if(!mapToExistingNode.containsKey(typeDesc)){
1620                 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
1621                 AllocSite as = createParameterAllocSite(rg, tempDesc);
1622                 // make a new reference to allocated node
1623                     HeapRegionNode hrnSummary = 
1624                                 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1625                                                            false, // single object?
1626                                                            true, // summary?
1627                                                            false, // out-of-context?
1628                                                            typeDesc, // type
1629                                                            as, // allocation site
1630                                                            alpha, // inherent reach
1631                                                            alpha, // current reach
1632                                                            ExistPredSet.factory(rg.predTrue), // predicates
1633                                                            tempDesc.toString() // description
1634                                                            );
1635                     rg.id2hrn.put(as.getSummary(),hrnSummary);
1636                     mapToExistingNode.put(typeDesc, hrnSummary);
1637                     RefEdge edgeToSummary = new RefEdge(prevNode, // source
1638                                         hrnSummary, // dest
1639                                         typeDesc, // type
1640                                         arrayElementFieldName, // field name
1641                                         alpha, // beta
1642                                         ExistPredSet.factory(rg.predTrue) // predicates
1643                                         );
1644                     rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1645                     prevNode=hrnSummary;
1646         }else{
1647                 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
1648                 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null){
1649                         RefEdge edgeToSummary = new RefEdge(prevNode, // source
1650                                         hrnSummary, // dest
1651                                         typeDesc, // type
1652                                         arrayElementFieldName, // field name
1653                                         alpha, // beta
1654                                         ExistPredSet.factory(rg.predTrue) // predicates
1655                                         );
1656                     rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1657                 }
1658                  prevNode=hrnSummary;
1659         }
1660     }
1661         
1662         map.put(arrayEntryNode, prevNode);
1663         return arrayEntryNode;
1664 }
1665
1666 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
1667     ReachGraph rg = new ReachGraph();
1668     TaskDescriptor taskDesc = fm.getTask();
1669     
1670     for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
1671         Descriptor paramDesc = taskDesc.getParameter(idx);
1672         TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
1673         
1674         // setup data structure
1675         Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet = 
1676             new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
1677         Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode = 
1678             new Hashtable<TypeDescriptor, HeapRegionNode>();
1679         Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode = 
1680             new Hashtable<HeapRegionNode, HeapRegionNode>();
1681         Set<String> doneSet = new HashSet<String>();
1682         
1683         TempDescriptor tempDesc = fm.getParameter(idx);
1684         
1685         AllocSite as = createParameterAllocSite(rg, tempDesc);
1686         VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
1687         Integer idNewest = as.getIthOldest(0);
1688         HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
1689
1690         // make a new reference to allocated node
1691         RefEdge edgeNew = new RefEdge(lnX, // source
1692                                       hrnNewest, // dest
1693                                       taskDesc.getParamType(idx), // type
1694                                       null, // field name
1695                                       hrnNewest.getAlpha(), // beta
1696                                       ExistPredSet.factory(rg.predTrue) // predicates
1697                                       );
1698         rg.addRefEdge(lnX, hrnNewest, edgeNew);
1699
1700         // set-up a work set for class field
1701         ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
1702         for (Iterator it = classDesc.getFields(); it.hasNext();) {
1703             FieldDescriptor fd = (FieldDescriptor) it.next();
1704             TypeDescriptor fieldType = fd.getType();
1705             if (shouldAnalysisTrack( fieldType )) {
1706                 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
1707                 newMap.put(hrnNewest, fd);
1708                 workSet.add(newMap);
1709             }
1710         }
1711         
1712         int uniqueIdentifier = 0;
1713         while (!workSet.isEmpty()) {
1714             HashMap<HeapRegionNode, FieldDescriptor> map = workSet
1715                 .iterator().next();
1716             workSet.remove(map);
1717             
1718             Set<HeapRegionNode> key = map.keySet();
1719             HeapRegionNode srcHRN = key.iterator().next();
1720             FieldDescriptor fd = map.get(srcHRN);
1721             TypeDescriptor type = fd.getType();
1722             String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
1723             
1724             if (!doneSet.contains(doneSetIdentifier)) {
1725                 doneSet.add(doneSetIdentifier);
1726                 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
1727                     // create new summary Node
1728                     TempDescriptor td = new TempDescriptor("temp"
1729                                                            + uniqueIdentifier, type);
1730                     
1731                     AllocSite allocSite;
1732                     if(type.equals(paramTypeDesc)){
1733                     //corresponding allocsite has already been created for a parameter variable.
1734                         allocSite=as;
1735                     }else{
1736                         allocSite = createParameterAllocSite(rg, td);
1737                     }
1738                     String strDesc = allocSite.toStringForDOT()
1739                         + "\\nsummary";
1740                     TypeDescriptor allocType=allocSite.getType();
1741                     
1742                     HeapRegionNode      hrnSummary;
1743                     if(allocType.isArray() && allocType.getArrayCount()>0){
1744                       hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
1745                     }else{                  
1746                         hrnSummary = 
1747                                         rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
1748                                                                    false, // single object?
1749                                                                    true, // summary?
1750                                                                    false, // out-of-context?
1751                                                                    allocSite.getType(), // type
1752                                                                    allocSite, // allocation site
1753                                                                    hrnNewest.getAlpha(), // inherent reach
1754                                                                    hrnNewest.getAlpha(), // current reach
1755                                                                    ExistPredSet.factory(rg.predTrue), // predicates
1756                                                                    strDesc // description
1757                                                                    );
1758                                     rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
1759                     
1760                     // make a new reference to summary node
1761                     RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1762                                                         hrnSummary, // dest
1763                                                         type, // type
1764                                                         fd.getSymbol(), // field name
1765                                                         hrnNewest.getAlpha(), // beta
1766                                                         ExistPredSet.factory(rg.predTrue) // predicates
1767                                                         );
1768                     
1769                     rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1770                     }               
1771                     uniqueIdentifier++;
1772                     
1773                     mapTypeToExistingSummaryNode.put(type, hrnSummary);
1774                     
1775                     // set-up a work set for  fields of the class
1776                     Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
1777                     for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
1778                                         .hasNext();) {
1779                                 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
1780                                                 .next();
1781                                 HeapRegionNode newDstHRN;
1782                                 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)){
1783                                         //related heap region node is already exsited.
1784                                         newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
1785                                 }else{
1786                                         newDstHRN=hrnSummary;
1787                                 }
1788                                  doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;                                                            
1789                                  if(!doneSet.contains(doneSetIdentifier)){
1790                                  // add new work item
1791                                          HashMap<HeapRegionNode, FieldDescriptor> newMap = 
1792                                             new HashMap<HeapRegionNode, FieldDescriptor>();
1793                                          newMap.put(newDstHRN, fieldDescriptor);
1794                                          workSet.add(newMap);
1795                                   }                             
1796                         }
1797                     
1798                 }else{
1799                     // if there exists corresponding summary node
1800                     HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
1801                     
1802                     RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1803                                                         hrnDst, // dest
1804                                                         fd.getType(), // type
1805                                                         fd.getSymbol(), // field name
1806                                                         srcHRN.getAlpha(), // beta
1807                                                         ExistPredSet.factory(rg.predTrue) // predicates
1808                                                         );
1809                     rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
1810                     
1811                 }               
1812             }       
1813         }           
1814     }   
1815 //    debugSnapshot(rg, fm, true);
1816     return rg;
1817 }
1818
1819 // return all allocation sites in the method (there is one allocation
1820 // site per FlatNew node in a method)
1821 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
1822   if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
1823     buildAllocationSiteSet(d);
1824   }
1825
1826   return mapDescriptorToAllocSiteSet.get(d);
1827
1828 }
1829
1830 private void buildAllocationSiteSet(Descriptor d) {
1831     HashSet<AllocSite> s = new HashSet<AllocSite>();
1832
1833     FlatMethod fm;
1834     if( d instanceof MethodDescriptor ) {
1835       fm = state.getMethodFlat( (MethodDescriptor) d);
1836     } else {
1837       assert d instanceof TaskDescriptor;
1838       fm = state.getMethodFlat( (TaskDescriptor) d);
1839     }
1840     pm.analyzeMethod(fm);
1841
1842     // visit every node in this FlatMethod's IR graph
1843     // and make a set of the allocation sites from the
1844     // FlatNew node's visited
1845     HashSet<FlatNode> visited = new HashSet<FlatNode>();
1846     HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
1847     toVisit.add(fm);
1848
1849     while( !toVisit.isEmpty() ) {
1850       FlatNode n = toVisit.iterator().next();
1851
1852       if( n instanceof FlatNew ) {
1853         s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
1854       }
1855
1856       toVisit.remove(n);
1857       visited.add(n);
1858
1859       for( int i = 0; i < pm.numNext(n); ++i ) {
1860         FlatNode child = pm.getNext(n, i);
1861         if( !visited.contains(child) ) {
1862           toVisit.add(child);
1863         }
1864       }
1865     }
1866
1867     mapDescriptorToAllocSiteSet.put(d, s);
1868   }
1869
1870         private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
1871
1872                 HashSet<AllocSite> out = new HashSet<AllocSite>();
1873                 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1874                 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1875
1876                 toVisit.add(dIn);
1877
1878                 while (!toVisit.isEmpty()) {
1879                         Descriptor d = toVisit.iterator().next();
1880                         toVisit.remove(d);
1881                         visited.add(d);
1882
1883                         HashSet<AllocSite> asSet = getAllocationSiteSet(d);
1884                         Iterator asItr = asSet.iterator();
1885                         while (asItr.hasNext()) {
1886                                 AllocSite as = (AllocSite) asItr.next();
1887                                 if (as.getDisjointAnalysisId() != null) {
1888                                         out.add(as);
1889                                 }
1890                         }
1891
1892                         // enqueue callees of this method to be searched for
1893                         // allocation sites also
1894                         Set callees = callGraph.getCalleeSet(d);
1895                         if (callees != null) {
1896                                 Iterator methItr = callees.iterator();
1897                                 while (methItr.hasNext()) {
1898                                         MethodDescriptor md = (MethodDescriptor) methItr.next();
1899
1900                                         if (!visited.contains(md)) {
1901                                                 toVisit.add(md);
1902                                         }
1903                                 }
1904                         }
1905                 }
1906
1907                 return out;
1908         }
1909  
1910     
1911 private HashSet<AllocSite>
1912 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
1913
1914   HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
1915   HashSet<Descriptor>     toVisit    = new HashSet<Descriptor>();
1916   HashSet<Descriptor>     visited    = new HashSet<Descriptor>();
1917
1918   toVisit.add(td);
1919
1920   // traverse this task and all methods reachable from this task
1921   while( !toVisit.isEmpty() ) {
1922     Descriptor d = toVisit.iterator().next();
1923     toVisit.remove(d);
1924     visited.add(d);
1925
1926     HashSet<AllocSite> asSet = getAllocationSiteSet(d);
1927     Iterator asItr = asSet.iterator();
1928     while( asItr.hasNext() ) {
1929         AllocSite as = (AllocSite) asItr.next();
1930         TypeDescriptor typed = as.getType();
1931         if( typed != null ) {
1932           ClassDescriptor cd = typed.getClassDesc();
1933           if( cd != null && cd.hasFlags() ) {
1934             asSetTotal.add(as);
1935           }
1936         }
1937     }
1938
1939     // enqueue callees of this method to be searched for
1940     // allocation sites also
1941     Set callees = callGraph.getCalleeSet(d);
1942     if( callees != null ) {
1943         Iterator methItr = callees.iterator();
1944         while( methItr.hasNext() ) {
1945           MethodDescriptor md = (MethodDescriptor) methItr.next();
1946
1947           if( !visited.contains(md) ) {
1948             toVisit.add(md);
1949           }
1950         }
1951     }
1952   }
1953
1954   return asSetTotal;
1955 }
1956
1957
1958   
1959   
1960   // get successive captures of the analysis state, use compiler
1961   // flags to control
1962   boolean takeDebugSnapshots = false;
1963   String  descSymbolDebug    = null;
1964   boolean stopAfterCapture   = false;
1965   int     snapVisitCounter   = 0;
1966   int     snapNodeCounter    = 0;
1967   int     visitStartCapture  = 0;
1968   int     numVisitsToCapture = 0;
1969
1970
1971   void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
1972     if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
1973       return;
1974     }
1975
1976     if( in ) {
1977
1978     }
1979
1980     if( snapVisitCounter >= visitStartCapture ) {
1981       System.out.println( "    @@@ snapping visit="+snapVisitCounter+
1982                           ", node="+snapNodeCounter+
1983                           " @@@" );
1984       String graphName;
1985       if( in ) {
1986         graphName = String.format( "snap%02d_%04din",
1987                                    snapVisitCounter,
1988                                    snapNodeCounter );
1989       } else {
1990         graphName = String.format( "snap%02d_%04dout",
1991                                    snapVisitCounter,
1992                                    snapNodeCounter );
1993       }
1994       if( fn != null ) {
1995         graphName = graphName + fn;
1996       }
1997       rg.writeGraph( graphName,
1998                      true,  // write labels (variables)
1999                      true,  // selectively hide intermediate temp vars
2000                      true,  // prune unreachable heap regions
2001                      false, // hide subset reachability states
2002                      true );// hide edge taints
2003     }
2004   }
2005
2006 }