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