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