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