improving debugging of call site contributions to initial contexts
[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                      true,  // hide subset reachability states         
1354                      true ); // hide edge taints                        
1355     }
1356   }
1357
1358   private void writeFinalIHMs() {
1359     Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1360     while( d2IHMsItr.hasNext() ) {
1361       Map.Entry                        me1 = (Map.Entry)                       d2IHMsItr.next();
1362       Descriptor                         d = (Descriptor)                      me1.getKey();
1363       Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1364
1365       Iterator fc2rgItr = IHMs.entrySet().iterator();
1366       while( fc2rgItr.hasNext() ) {
1367         Map.Entry  me2 = (Map.Entry)  fc2rgItr.next();
1368         FlatCall   fc  = (FlatCall)   me2.getKey();
1369         ReachGraph rg  = (ReachGraph) me2.getValue();
1370                 
1371         rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc2enclosing.get( fc )+fc,
1372                        true,   // write labels (variables)
1373                        true,   // selectively hide intermediate temp vars
1374                        true,   // prune unreachable heap regions
1375                        true,  // hide subset reachability states
1376                        true ); // hide edge taints
1377       }
1378     }
1379   }
1380
1381   private void writeInitialContexts() {
1382     Set entrySet = mapDescriptorToInitialContext.entrySet();
1383     Iterator itr = entrySet.iterator();
1384     while( itr.hasNext() ) {
1385       Map.Entry  me = (Map.Entry)  itr.next();
1386       Descriptor  d = (Descriptor) me.getKey();
1387       ReachGraph rg = (ReachGraph) me.getValue();
1388
1389       rg.writeGraph( "INITIAL"+d,
1390                      true,   // write labels (variables)                
1391                      true,   // selectively hide intermediate temp vars 
1392                      true,   // prune unreachable heap regions          
1393                      true,  // hide subset reachability states         
1394                      true ); // hide edge taints                        
1395     }
1396   }
1397    
1398
1399   protected ReachGraph getPartial( Descriptor d ) {
1400     return mapDescriptorToCompleteReachGraph.get( d );
1401   }
1402
1403   protected void setPartial( Descriptor d, ReachGraph rg ) {
1404     mapDescriptorToCompleteReachGraph.put( d, rg );
1405
1406     // when the flag for writing out every partial
1407     // result is set, we should spit out the graph,
1408     // but in order to give it a unique name we need
1409     // to track how many partial results for this
1410     // descriptor we've already written out
1411     if( writeAllIncrementalDOTs ) {
1412       if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1413         mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1414       }
1415       Integer n = mapDescriptorToNumUpdates.get( d );
1416       
1417       rg.writeGraph( d+"COMPLETE"+String.format( "%05d", n ),
1418                      true,   // write labels (variables)
1419                      true,   // selectively hide intermediate temp vars
1420                      true,   // prune unreachable heap regions
1421                      true,  // hide subset reachability states
1422                      true ); // hide edge taints
1423       
1424       mapDescriptorToNumUpdates.put( d, n + 1 );
1425     }
1426   }
1427
1428
1429
1430   // return just the allocation site associated with one FlatNew node
1431   protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1432
1433     if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1434       AllocSite as = AllocSite.factory( allocationDepth, 
1435                                         fnew, 
1436                                         fnew.getDisjointId() 
1437                                         );
1438
1439       // the newest nodes are single objects
1440       for( int i = 0; i < allocationDepth; ++i ) {
1441         Integer id = generateUniqueHeapRegionNodeID();
1442         as.setIthOldest( i, id );
1443         mapHrnIdToAllocSite.put( id, as );
1444       }
1445
1446       // the oldest node is a summary node
1447       as.setSummary( generateUniqueHeapRegionNodeID() );
1448
1449       mapFlatNewToAllocSite.put( fnew, as );
1450     }
1451
1452     return mapFlatNewToAllocSite.get( fnew );
1453   }
1454
1455
1456   public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1457     // don't track primitive types, but an array
1458     // of primitives is heap memory
1459     if( type.isImmutable() ) {
1460       return type.isArray();
1461     }
1462
1463     // everything else is an object
1464     return true;
1465   }
1466
1467   protected int numMethodsAnalyzed() {    
1468     return descriptorsToAnalyze.size();
1469   }
1470   
1471
1472   
1473   
1474   
1475   // Take in source entry which is the program's compiled entry and
1476   // create a new analysis entry, a method that takes no parameters
1477   // and appears to allocate the command line arguments and call the
1478   // source entry with them.  The purpose of this analysis entry is
1479   // to provide a top-level method context with no parameters left.
1480   protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1481
1482     Modifiers mods = new Modifiers();
1483     mods.addModifier( Modifiers.PUBLIC );
1484     mods.addModifier( Modifiers.STATIC );
1485
1486     TypeDescriptor returnType = 
1487       new TypeDescriptor( TypeDescriptor.VOID );
1488
1489     this.mdAnalysisEntry = 
1490       new MethodDescriptor( mods,
1491                             returnType,
1492                             "analysisEntryMethod"
1493                             );
1494
1495     TempDescriptor cmdLineArgs = 
1496       new TempDescriptor( "args",
1497                           mdSourceEntry.getParamType( 0 )
1498                           );
1499
1500     FlatNew fn = 
1501       new FlatNew( mdSourceEntry.getParamType( 0 ),
1502                    cmdLineArgs,
1503                    false // is global 
1504                    );
1505     
1506     TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1507     sourceEntryArgs[0] = cmdLineArgs;
1508     
1509     FlatCall fc = 
1510       new FlatCall( mdSourceEntry,
1511                     null, // dst temp
1512                     null, // this temp
1513                     sourceEntryArgs
1514                     );
1515
1516     FlatReturnNode frn = new FlatReturnNode( null );
1517
1518     FlatExit fe = new FlatExit();
1519
1520     this.fmAnalysisEntry = 
1521       new FlatMethod( mdAnalysisEntry, 
1522                       fe
1523                       );
1524
1525     this.fmAnalysisEntry.addNext( fn );
1526     fn.addNext( fc );
1527     fc.addNext( frn );
1528     frn.addNext( fe );
1529   }
1530
1531
1532   protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1533
1534     Set<Descriptor> discovered;
1535
1536     if( determinismDesired ) {
1537       // use an ordered set
1538       discovered = new TreeSet<Descriptor>( dComp );      
1539     } else {
1540       // otherwise use a speedy hashset
1541       discovered = new HashSet<Descriptor>();
1542     }
1543
1544     LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
1545   
1546     Iterator<Descriptor> itr = toSort.iterator();
1547     while( itr.hasNext() ) {
1548       Descriptor d = itr.next();
1549           
1550       if( !discovered.contains( d ) ) {
1551         dfsVisit( d, toSort, sorted, discovered );
1552       }
1553     }
1554     
1555     return sorted;
1556   }
1557   
1558   // While we're doing DFS on call graph, remember
1559   // dependencies for efficient queuing of methods
1560   // during interprocedural analysis:
1561   //
1562   // a dependent of a method decriptor d for this analysis is:
1563   //  1) a method or task that invokes d
1564   //  2) in the descriptorsToAnalyze set
1565   protected void dfsVisit( Descriptor             d,
1566                            Set       <Descriptor> toSort,                        
1567                            LinkedList<Descriptor> sorted,
1568                            Set       <Descriptor> discovered ) {
1569     discovered.add( d );
1570     
1571     // only methods have callers, tasks never do
1572     if( d instanceof MethodDescriptor ) {
1573
1574       MethodDescriptor md = (MethodDescriptor) d;
1575
1576       // the call graph is not aware that we have a fabricated
1577       // analysis entry that calls the program source's entry
1578       if( md == mdSourceEntry ) {
1579         if( !discovered.contains( mdAnalysisEntry ) ) {
1580           addDependent( mdSourceEntry,  // callee
1581                         mdAnalysisEntry // caller
1582                         );
1583           dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1584         }
1585       }
1586
1587       // otherwise call graph guides DFS
1588       Iterator itr = callGraph.getCallerSet( md ).iterator();
1589       while( itr.hasNext() ) {
1590         Descriptor dCaller = (Descriptor) itr.next();
1591         
1592         // only consider callers in the original set to analyze
1593         if( !toSort.contains( dCaller ) ) {
1594           continue;
1595         }
1596           
1597         if( !discovered.contains( dCaller ) ) {
1598           addDependent( md,     // callee
1599                         dCaller // caller
1600                         );
1601
1602           dfsVisit( dCaller, toSort, sorted, discovered );
1603         }
1604       }
1605     }
1606     
1607     // for leaf-nodes last now!
1608     sorted.addLast( d );
1609   }
1610
1611
1612   protected void enqueue( Descriptor d ) {
1613
1614     if( !descriptorsToVisitSet.contains( d ) ) {
1615
1616       if( state.DISJOINTDVISITSTACK ||
1617           state.DISJOINTDVISITSTACKEESONTOP
1618           ) {
1619         descriptorsToVisitStack.add( d );
1620
1621       } else if( state.DISJOINTDVISITPQUE ) {
1622         Integer priority = mapDescriptorToPriority.get( d );
1623         descriptorsToVisitQ.add( new DescriptorQWrapper( priority, 
1624                                                          d ) 
1625                                  );
1626       }
1627
1628       descriptorsToVisitSet.add( d );
1629     }
1630   }
1631
1632
1633   // a dependent of a method decriptor d for this analysis is:
1634   //  1) a method or task that invokes d
1635   //  2) in the descriptorsToAnalyze set
1636   protected void addDependent( Descriptor callee, Descriptor caller ) {
1637     Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1638     if( deps == null ) {
1639       deps = new HashSet<Descriptor>();
1640     }
1641     deps.add( caller );
1642     mapDescriptorToSetDependents.put( callee, deps );
1643   }
1644   
1645   protected Set<Descriptor> getDependents( Descriptor callee ) {
1646     Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1647     if( deps == null ) {
1648       deps = new HashSet<Descriptor>();
1649       mapDescriptorToSetDependents.put( callee, deps );
1650     }
1651     return deps;
1652   }
1653
1654   
1655   public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
1656
1657     Hashtable<FlatCall, ReachGraph> heapsFromCallers = 
1658       mapDescriptorToIHMcontributions.get( d );
1659     
1660     if( heapsFromCallers == null ) {
1661       heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
1662       mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
1663     }
1664     
1665     return heapsFromCallers;
1666   }
1667
1668   public ReachGraph getIHMcontribution( Descriptor d, 
1669                                         FlatCall   fc
1670                                         ) {
1671     Hashtable<FlatCall, ReachGraph> heapsFromCallers = 
1672       getIHMcontributions( d );
1673
1674     if( !heapsFromCallers.containsKey( fc ) ) {
1675       return null;
1676     }
1677
1678     return heapsFromCallers.get( fc );
1679   }
1680
1681
1682   public void addIHMcontribution( Descriptor d,
1683                                   FlatCall   fc,
1684                                   ReachGraph rg
1685                                   ) {
1686     Hashtable<FlatCall, ReachGraph> heapsFromCallers = 
1687       getIHMcontributions( d );
1688
1689     heapsFromCallers.put( fc, rg );
1690   }
1691
1692
1693   private AllocSite createParameterAllocSite( ReachGraph     rg, 
1694                                               TempDescriptor tempDesc,
1695                                               boolean        flagRegions
1696                                               ) {
1697     
1698     FlatNew flatNew;
1699     if( flagRegions ) {
1700       flatNew = new FlatNew( tempDesc.getType(), // type
1701                              tempDesc,           // param temp
1702                              false,              // global alloc?
1703                              "param"+tempDesc    // disjoint site ID string
1704                              );
1705     } else {
1706       flatNew = new FlatNew( tempDesc.getType(), // type
1707                              tempDesc,           // param temp
1708                              false,              // global alloc?
1709                              null                // disjoint site ID string
1710                              );
1711     }
1712
1713     // create allocation site
1714     AllocSite as = AllocSite.factory( allocationDepth, 
1715                                       flatNew, 
1716                                       flatNew.getDisjointId()
1717                                       );
1718     for (int i = 0; i < allocationDepth; ++i) {
1719         Integer id = generateUniqueHeapRegionNodeID();
1720         as.setIthOldest(i, id);
1721         mapHrnIdToAllocSite.put(id, as);
1722     }
1723     // the oldest node is a summary node
1724     as.setSummary( generateUniqueHeapRegionNodeID() );
1725     
1726     rg.age(as);
1727     
1728     return as;
1729     
1730   }
1731
1732 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc){
1733         
1734         Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
1735     if(!typeDesc.isImmutable()){
1736             ClassDescriptor classDesc = typeDesc.getClassDesc();                    
1737             for (Iterator it = classDesc.getFields(); it.hasNext();) {
1738                     FieldDescriptor field = (FieldDescriptor) it.next();
1739                     TypeDescriptor fieldType = field.getType();
1740                     if (shouldAnalysisTrack( fieldType )) {
1741                         fieldSet.add(field);                    
1742                     }
1743             }
1744     }
1745     return fieldSet;
1746         
1747 }
1748
1749   private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha ){
1750
1751         int dimCount=fd.getType().getArrayCount();
1752         HeapRegionNode prevNode=null;
1753         HeapRegionNode arrayEntryNode=null;
1754         for(int i=dimCount;i>0;i--){
1755                 TypeDescriptor typeDesc=fd.getType().dereference();//hack to get instance of type desc
1756                 typeDesc.setArrayCount(i);
1757                 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
1758                 HeapRegionNode hrnSummary ;
1759                 if(!mapToExistingNode.containsKey(typeDesc)){
1760                         AllocSite as;
1761                         if(i==dimCount){
1762                                 as = alloc;
1763                         }else{
1764                           as = createParameterAllocSite(rg, tempDesc, false);
1765                         }
1766                         // make a new reference to allocated node
1767                     hrnSummary = 
1768                                 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1769                                                            false, // single object?
1770                                                            true, // summary?
1771                                                            false, // out-of-context?
1772                                                            as.getType(), // type
1773                                                            as, // allocation site
1774                                                            alpha, // inherent reach
1775                                                            alpha, // current reach
1776                                                            ExistPredSet.factory(rg.predTrue), // predicates
1777                                                            tempDesc.toString() // description
1778                                                            );
1779                     rg.id2hrn.put(as.getSummary(),hrnSummary);
1780                     
1781                     mapToExistingNode.put(typeDesc, hrnSummary);
1782                 }else{
1783                         hrnSummary=mapToExistingNode.get(typeDesc);
1784                 }
1785             
1786             if(prevNode==null){
1787                     // make a new reference between new summary node and source
1788                     RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1789                                                         hrnSummary, // dest
1790                                                         typeDesc, // type
1791                                                         fd.getSymbol(), // field name
1792                                                         alpha, // beta
1793                                                         ExistPredSet.factory(rg.predTrue) // predicates
1794                                                         );
1795                     
1796                     rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1797                     prevNode=hrnSummary;
1798                     arrayEntryNode=hrnSummary;
1799             }else{
1800                     // make a new reference between summary nodes of array
1801                     RefEdge edgeToSummary = new RefEdge(prevNode, // source
1802                                                         hrnSummary, // dest
1803                                                         typeDesc, // type
1804                                                         arrayElementFieldName, // field name
1805                                                         alpha, // beta
1806                                                         ExistPredSet.factory(rg.predTrue) // predicates
1807                                                         );
1808                     
1809                     rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1810                     prevNode=hrnSummary;
1811             }
1812             
1813         }
1814         
1815         // create a new obj node if obj has at least one non-primitive field
1816         TypeDescriptor type=fd.getType();
1817     if(getFieldSetTobeAnalyzed(type).size()>0){
1818         TypeDescriptor typeDesc=type.dereference();
1819         typeDesc.setArrayCount(0);
1820         if(!mapToExistingNode.containsKey(typeDesc)){
1821                 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
1822                 AllocSite as = createParameterAllocSite(rg, tempDesc, false);
1823                 // make a new reference to allocated node
1824                     HeapRegionNode hrnSummary = 
1825                                 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1826                                                            false, // single object?
1827                                                            true, // summary?
1828                                                            false, // out-of-context?
1829                                                            typeDesc, // type
1830                                                            as, // allocation site
1831                                                            alpha, // inherent reach
1832                                                            alpha, // current reach
1833                                                            ExistPredSet.factory(rg.predTrue), // predicates
1834                                                            tempDesc.toString() // description
1835                                                            );
1836                     rg.id2hrn.put(as.getSummary(),hrnSummary);
1837                     mapToExistingNode.put(typeDesc, hrnSummary);
1838                     RefEdge edgeToSummary = new RefEdge(prevNode, // source
1839                                         hrnSummary, // dest
1840                                         typeDesc, // type
1841                                         arrayElementFieldName, // field name
1842                                         alpha, // beta
1843                                         ExistPredSet.factory(rg.predTrue) // predicates
1844                                         );
1845                     rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1846                     prevNode=hrnSummary;
1847         }else{
1848                 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
1849                 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null){
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                                         );
1857                     rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1858                 }
1859                  prevNode=hrnSummary;
1860         }
1861     }
1862         
1863         map.put(arrayEntryNode, prevNode);
1864         return arrayEntryNode;
1865 }
1866
1867 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
1868     ReachGraph rg = new ReachGraph();
1869     TaskDescriptor taskDesc = fm.getTask();
1870     
1871     for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
1872         Descriptor paramDesc = taskDesc.getParameter(idx);
1873         TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
1874         
1875         // setup data structure
1876         Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet = 
1877             new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
1878         Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode = 
1879             new Hashtable<TypeDescriptor, HeapRegionNode>();
1880         Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode = 
1881             new Hashtable<HeapRegionNode, HeapRegionNode>();
1882         Set<String> doneSet = new HashSet<String>();
1883         
1884         TempDescriptor tempDesc = fm.getParameter(idx);
1885         
1886         AllocSite as = createParameterAllocSite(rg, tempDesc, true);
1887         VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
1888         Integer idNewest = as.getIthOldest(0);
1889         HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
1890
1891         // make a new reference to allocated node
1892         RefEdge edgeNew = new RefEdge(lnX, // source
1893                                       hrnNewest, // dest
1894                                       taskDesc.getParamType(idx), // type
1895                                       null, // field name
1896                                       hrnNewest.getAlpha(), // beta
1897                                       ExistPredSet.factory(rg.predTrue) // predicates
1898                                       );
1899         rg.addRefEdge(lnX, hrnNewest, edgeNew);
1900
1901         // set-up a work set for class field
1902         ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
1903         for (Iterator it = classDesc.getFields(); it.hasNext();) {
1904             FieldDescriptor fd = (FieldDescriptor) it.next();
1905             TypeDescriptor fieldType = fd.getType();
1906             if (shouldAnalysisTrack( fieldType )) {
1907                 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
1908                 newMap.put(hrnNewest, fd);
1909                 workSet.add(newMap);
1910             }
1911         }
1912         
1913         int uniqueIdentifier = 0;
1914         while (!workSet.isEmpty()) {
1915             HashMap<HeapRegionNode, FieldDescriptor> map = workSet
1916                 .iterator().next();
1917             workSet.remove(map);
1918             
1919             Set<HeapRegionNode> key = map.keySet();
1920             HeapRegionNode srcHRN = key.iterator().next();
1921             FieldDescriptor fd = map.get(srcHRN);
1922             TypeDescriptor type = fd.getType();
1923             String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
1924             
1925             if (!doneSet.contains(doneSetIdentifier)) {
1926                 doneSet.add(doneSetIdentifier);
1927                 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
1928                     // create new summary Node
1929                     TempDescriptor td = new TempDescriptor("temp"
1930                                                            + uniqueIdentifier, type);
1931                     
1932                     AllocSite allocSite;
1933                     if(type.equals(paramTypeDesc)){
1934                     //corresponding allocsite has already been created for a parameter variable.
1935                         allocSite=as;
1936                     }else{
1937                       allocSite = createParameterAllocSite(rg, td, false);
1938                     }
1939                     String strDesc = allocSite.toStringForDOT()
1940                         + "\\nsummary";
1941                     TypeDescriptor allocType=allocSite.getType();
1942                     
1943                     HeapRegionNode      hrnSummary;
1944                     if(allocType.isArray() && allocType.getArrayCount()>0){
1945                       hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
1946                     }else{                  
1947                         hrnSummary = 
1948                                         rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
1949                                                                    false, // single object?
1950                                                                    true, // summary?
1951                                                                    false, // out-of-context?
1952                                                                    allocSite.getType(), // type
1953                                                                    allocSite, // allocation site
1954                                                                    hrnNewest.getAlpha(), // inherent reach
1955                                                                    hrnNewest.getAlpha(), // current reach
1956                                                                    ExistPredSet.factory(rg.predTrue), // predicates
1957                                                                    strDesc // description
1958                                                                    );
1959                                     rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
1960                     
1961                     // make a new reference to summary node
1962                     RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1963                                                         hrnSummary, // dest
1964                                                         type, // type
1965                                                         fd.getSymbol(), // field name
1966                                                         hrnNewest.getAlpha(), // beta
1967                                                         ExistPredSet.factory(rg.predTrue) // predicates
1968                                                         );
1969                     
1970                     rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1971                     }               
1972                     uniqueIdentifier++;
1973                     
1974                     mapTypeToExistingSummaryNode.put(type, hrnSummary);
1975                     
1976                     // set-up a work set for  fields of the class
1977                     Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
1978                     for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
1979                                         .hasNext();) {
1980                                 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
1981                                                 .next();
1982                                 HeapRegionNode newDstHRN;
1983                                 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)){
1984                                         //related heap region node is already exsited.
1985                                         newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
1986                                 }else{
1987                                         newDstHRN=hrnSummary;
1988                                 }
1989                                  doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;                                                            
1990                                  if(!doneSet.contains(doneSetIdentifier)){
1991                                  // add new work item
1992                                          HashMap<HeapRegionNode, FieldDescriptor> newMap = 
1993                                             new HashMap<HeapRegionNode, FieldDescriptor>();
1994                                          newMap.put(newDstHRN, fieldDescriptor);
1995                                          workSet.add(newMap);
1996                                   }                             
1997                         }
1998                     
1999                 }else{
2000                     // if there exists corresponding summary node
2001                     HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
2002                     
2003                     RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2004                                                         hrnDst, // dest
2005                                                         fd.getType(), // type
2006                                                         fd.getSymbol(), // field name
2007                                                         srcHRN.getAlpha(), // beta
2008                                                         ExistPredSet.factory(rg.predTrue) // predicates
2009                                                         );
2010                     rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
2011                     
2012                 }               
2013             }       
2014         }           
2015     }   
2016 //    debugSnapshot(rg, fm, true);
2017     return rg;
2018 }
2019
2020 // return all allocation sites in the method (there is one allocation
2021 // site per FlatNew node in a method)
2022 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
2023   if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
2024     buildAllocationSiteSet(d);
2025   }
2026
2027   return mapDescriptorToAllocSiteSet.get(d);
2028
2029 }
2030
2031 private void buildAllocationSiteSet(Descriptor d) {
2032     HashSet<AllocSite> s = new HashSet<AllocSite>();
2033
2034     FlatMethod fm;
2035     if( d instanceof MethodDescriptor ) {
2036       fm = state.getMethodFlat( (MethodDescriptor) d);
2037     } else {
2038       assert d instanceof TaskDescriptor;
2039       fm = state.getMethodFlat( (TaskDescriptor) d);
2040     }
2041     pm.analyzeMethod(fm);
2042
2043     // visit every node in this FlatMethod's IR graph
2044     // and make a set of the allocation sites from the
2045     // FlatNew node's visited
2046     HashSet<FlatNode> visited = new HashSet<FlatNode>();
2047     HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
2048     toVisit.add(fm);
2049
2050     while( !toVisit.isEmpty() ) {
2051       FlatNode n = toVisit.iterator().next();
2052
2053       if( n instanceof FlatNew ) {
2054         s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
2055       }
2056
2057       toVisit.remove(n);
2058       visited.add(n);
2059
2060       for( int i = 0; i < pm.numNext(n); ++i ) {
2061         FlatNode child = pm.getNext(n, i);
2062         if( !visited.contains(child) ) {
2063           toVisit.add(child);
2064         }
2065       }
2066     }
2067
2068     mapDescriptorToAllocSiteSet.put(d, s);
2069   }
2070
2071         private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
2072
2073                 HashSet<AllocSite> out = new HashSet<AllocSite>();
2074                 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2075                 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2076
2077                 toVisit.add(dIn);
2078
2079                 while (!toVisit.isEmpty()) {
2080                         Descriptor d = toVisit.iterator().next();
2081                         toVisit.remove(d);
2082                         visited.add(d);
2083
2084                         HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2085                         Iterator asItr = asSet.iterator();
2086                         while (asItr.hasNext()) {
2087                                 AllocSite as = (AllocSite) asItr.next();
2088                                 if (as.getDisjointAnalysisId() != null) {
2089                                         out.add(as);
2090                                 }
2091                         }
2092
2093                         // enqueue callees of this method to be searched for
2094                         // allocation sites also
2095                         Set callees = callGraph.getCalleeSet(d);
2096                         if (callees != null) {
2097                                 Iterator methItr = callees.iterator();
2098                                 while (methItr.hasNext()) {
2099                                         MethodDescriptor md = (MethodDescriptor) methItr.next();
2100
2101                                         if (!visited.contains(md)) {
2102                                                 toVisit.add(md);
2103                                         }
2104                                 }
2105                         }
2106                 }
2107
2108                 return out;
2109         }
2110  
2111     
2112 private HashSet<AllocSite>
2113 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
2114
2115   HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
2116   HashSet<Descriptor>     toVisit    = new HashSet<Descriptor>();
2117   HashSet<Descriptor>     visited    = new HashSet<Descriptor>();
2118
2119   toVisit.add(td);
2120
2121   // traverse this task and all methods reachable from this task
2122   while( !toVisit.isEmpty() ) {
2123     Descriptor d = toVisit.iterator().next();
2124     toVisit.remove(d);
2125     visited.add(d);
2126
2127     HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2128     Iterator asItr = asSet.iterator();
2129     while( asItr.hasNext() ) {
2130         AllocSite as = (AllocSite) asItr.next();
2131         TypeDescriptor typed = as.getType();
2132         if( typed != null ) {
2133           ClassDescriptor cd = typed.getClassDesc();
2134           if( cd != null && cd.hasFlags() ) {
2135             asSetTotal.add(as);
2136           }
2137         }
2138     }
2139
2140     // enqueue callees of this method to be searched for
2141     // allocation sites also
2142     Set callees = callGraph.getCalleeSet(d);
2143     if( callees != null ) {
2144         Iterator methItr = callees.iterator();
2145         while( methItr.hasNext() ) {
2146           MethodDescriptor md = (MethodDescriptor) methItr.next();
2147
2148           if( !visited.contains(md) ) {
2149             toVisit.add(md);
2150           }
2151         }
2152     }
2153   }
2154
2155   return asSetTotal;
2156 }
2157
2158
2159   
2160   
2161   // get successive captures of the analysis state, use compiler
2162   // flags to control
2163   boolean takeDebugSnapshots = false;
2164   String  descSymbolDebug    = null;
2165   boolean stopAfterCapture   = false;
2166   int     snapVisitCounter   = 0;
2167   int     snapNodeCounter    = 0;
2168   int     visitStartCapture  = 0;
2169   int     numVisitsToCapture = 0;
2170
2171
2172   void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
2173     if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2174       return;
2175     }
2176
2177     if( in ) {
2178
2179     }
2180
2181     if( snapVisitCounter >= visitStartCapture ) {
2182       System.out.println( "    @@@ snapping visit="+snapVisitCounter+
2183                           ", node="+snapNodeCounter+
2184                           " @@@" );
2185       String graphName;
2186       if( in ) {
2187         graphName = String.format( "snap%03d_%04din",
2188                                    snapVisitCounter,
2189                                    snapNodeCounter );
2190       } else {
2191         graphName = String.format( "snap%03d_%04dout",
2192                                    snapVisitCounter,
2193                                    snapNodeCounter );
2194       }
2195       if( fn != null ) {
2196         graphName = graphName + fn;
2197       }
2198       rg.writeGraph( graphName,
2199                      true,  // write labels (variables)
2200                      true,  // selectively hide intermediate temp vars
2201                      true,  // prune unreachable heap regions
2202                      true, // hide subset reachability states
2203                      true );// hide edge taints
2204     }
2205   }
2206
2207 }