New tool to check points-to results of a heap analysis against runtime pointers....
[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 Analysis.OoOJava.Accessible;
7 import Analysis.OoOJava.RBlockRelationAnalysis;
8 import IR.*;
9 import IR.Flat.*;
10 import IR.Tree.Modifiers;
11 import java.util.*;
12 import java.io.*;
13
14
15 public class DisjointAnalysis implements HeapAnalysis {
16
17   ///////////////////////////////////////////
18   //
19   //  Public interface to discover possible
20   //  sharing in the program under analysis
21   //
22   ///////////////////////////////////////////
23
24   // if an object allocated at the target site may be
25   // reachable from both an object from root1 and an
26   // object allocated at root2, return TRUE
27   public boolean mayBothReachTarget(FlatMethod fm,
28                                     FlatNew fnRoot1,
29                                     FlatNew fnRoot2,
30                                     FlatNew fnTarget) {
31
32     AllocSite asr1 = getAllocationSiteFromFlatNew(fnRoot1);
33     AllocSite asr2 = getAllocationSiteFromFlatNew(fnRoot2);
34     assert asr1.isFlagged();
35     assert asr2.isFlagged();
36
37     AllocSite ast = getAllocationSiteFromFlatNew(fnTarget);
38     ReachGraph rg = getPartial(fm.getMethod() );
39
40     return rg.mayBothReachTarget(asr1, asr2, ast);
41   }
42
43   // similar to the method above, return TRUE if ever
44   // more than one object from the root allocation site
45   // may reach an object from the target site
46   public boolean mayManyReachTarget(FlatMethod fm,
47                                     FlatNew fnRoot,
48                                     FlatNew fnTarget) {
49
50     AllocSite asr = getAllocationSiteFromFlatNew(fnRoot);
51     assert asr.isFlagged();
52
53     AllocSite ast = getAllocationSiteFromFlatNew(fnTarget);
54     ReachGraph rg = getPartial(fm.getMethod() );
55
56     return rg.mayManyReachTarget(asr, ast);
57   }
58
59
60
61
62   public HashSet<AllocSite>
63   getFlaggedAllocationSitesReachableFromTask(TaskDescriptor td) {
64     checkAnalysisComplete();
65     return getFlaggedAllocationSitesReachableFromTaskPRIVATE(td);
66   }
67
68   public AllocSite getAllocationSiteFromFlatNew(FlatNew fn) {
69     checkAnalysisComplete();
70     return getAllocSiteFromFlatNewPRIVATE(fn);
71   }
72
73   public AllocSite getAllocationSiteFromHeapRegionNodeID(Integer id) {
74     checkAnalysisComplete();
75     return mapHrnIdToAllocSite.get(id);
76   }
77
78   public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
79                                                  int paramIndex1,
80                                                  int paramIndex2) {
81     checkAnalysisComplete();
82     ReachGraph rg=mapDescriptorToCompleteReachGraph.get(taskOrMethod);
83     FlatMethod fm=state.getMethodFlat(taskOrMethod);
84     assert(rg != null);
85     return rg.mayReachSharedObjects(fm, paramIndex1, paramIndex2);
86   }
87
88   public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
89                                                  int paramIndex, AllocSite alloc) {
90     checkAnalysisComplete();
91     ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
92     FlatMethod fm=state.getMethodFlat(taskOrMethod);
93     assert(rg != null);
94     return rg.mayReachSharedObjects(fm, paramIndex, alloc);
95   }
96
97   public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
98                                                  AllocSite alloc, int paramIndex) {
99     checkAnalysisComplete();
100     ReachGraph rg  = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
101     FlatMethod fm=state.getMethodFlat(taskOrMethod);
102     assert(rg != null);
103     return rg.mayReachSharedObjects(fm, paramIndex, alloc);
104   }
105
106   public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
107                                                  AllocSite alloc1, AllocSite alloc2) {
108     checkAnalysisComplete();
109     ReachGraph rg  = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
110     assert(rg != null);
111     return rg.mayReachSharedObjects(alloc1, alloc2);
112   }
113
114   public String prettyPrintNodeSet(Set<HeapRegionNode> s) {
115     checkAnalysisComplete();
116
117     String out = "{\n";
118
119     Iterator<HeapRegionNode> i = s.iterator();
120     while (i.hasNext()) {
121       HeapRegionNode n = i.next();
122
123       AllocSite as = n.getAllocSite();
124       if (as == null) {
125         out += "  " + n.toString() + ",\n";
126       } else {
127         out += "  " + n.toString() + ": " + as.toStringVerbose()
128                + ",\n";
129       }
130     }
131
132     out += "}\n";
133     return out;
134   }
135
136   // use the methods given above to check every possible sharing class
137   // between task parameters and flagged allocation sites reachable
138   // from the task
139   public void writeAllSharing(String outputFile,
140                               String timeReport,
141                               String justTime,
142                               boolean tabularOutput,
143                               int numLines
144                               )
145   throws java.io.IOException {
146     checkAnalysisComplete();
147
148     BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
149
150     if (!tabularOutput) {
151       bw.write("Conducting ownership analysis with allocation depth = "
152                + allocationDepth + "\n");
153       bw.write(timeReport + "\n");
154     }
155
156     int numSharing = 0;
157
158     // look through every task for potential sharing
159     Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
160     while (taskItr.hasNext()) {
161       TaskDescriptor td = (TaskDescriptor) taskItr.next();
162
163       if (!tabularOutput) {
164         bw.write("\n---------" + td + "--------\n");
165       }
166
167       HashSet<AllocSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
168
169       Set<HeapRegionNode> common;
170
171       // for each task parameter, check for sharing classes with
172       // other task parameters and every allocation site
173       // reachable from this task
174       boolean foundSomeSharing = false;
175
176       FlatMethod fm = state.getMethodFlat(td);
177       for (int i = 0; i < fm.numParameters(); ++i) {
178
179         // skip parameters with types that cannot reference
180         // into the heap
181         if( !shouldAnalysisTrack(fm.getParameter(i).getType() ) ) {
182           continue;
183         }
184
185         // for the ith parameter check for sharing classes to all
186         // higher numbered parameters
187         for (int j = i + 1; j < fm.numParameters(); ++j) {
188
189           // skip parameters with types that cannot reference
190           // into the heap
191           if( !shouldAnalysisTrack(fm.getParameter(j).getType() ) ) {
192             continue;
193           }
194
195
196           common = hasPotentialSharing(td, i, j);
197           if (!common.isEmpty()) {
198             foundSomeSharing = true;
199             ++numSharing;
200             if (!tabularOutput) {
201               bw.write("Potential sharing between parameters " + i
202                        + " and " + j + ".\n");
203               bw.write(prettyPrintNodeSet(common) + "\n");
204             }
205           }
206         }
207
208         // for the ith parameter, check for sharing classes against
209         // the set of allocation sites reachable from this
210         // task context
211         Iterator allocItr = allocSites.iterator();
212         while (allocItr.hasNext()) {
213           AllocSite as = (AllocSite) allocItr.next();
214           common = hasPotentialSharing(td, i, as);
215           if (!common.isEmpty()) {
216             foundSomeSharing = true;
217             ++numSharing;
218             if (!tabularOutput) {
219               bw.write("Potential sharing between parameter " + i
220                        + " and " + as.getFlatNew() + ".\n");
221               bw.write(prettyPrintNodeSet(common) + "\n");
222             }
223           }
224         }
225       }
226
227       // for each allocation site check for sharing classes with
228       // other allocation sites in the context of execution
229       // of this task
230       HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
231       Iterator allocItr1 = allocSites.iterator();
232       while (allocItr1.hasNext()) {
233         AllocSite as1 = (AllocSite) allocItr1.next();
234
235         Iterator allocItr2 = allocSites.iterator();
236         while (allocItr2.hasNext()) {
237           AllocSite as2 = (AllocSite) allocItr2.next();
238
239           if (!outerChecked.contains(as2)) {
240             common = hasPotentialSharing(td, as1, as2);
241
242             if (!common.isEmpty()) {
243               foundSomeSharing = true;
244               ++numSharing;
245               if (!tabularOutput) {
246                 bw.write("Potential sharing between "
247                          + as1.getFlatNew() + " and "
248                          + as2.getFlatNew() + ".\n");
249                 bw.write(prettyPrintNodeSet(common) + "\n");
250               }
251             }
252           }
253         }
254
255         outerChecked.add(as1);
256       }
257
258       if (!foundSomeSharing) {
259         if (!tabularOutput) {
260           bw.write("No sharing between flagged objects in Task " + td
261                    + ".\n");
262         }
263       }
264     }
265
266
267     if (tabularOutput) {
268       bw.write(" & " + numSharing + " & " + justTime + " & " + numLines
269                + " & " + numMethodsAnalyzed() + " \\\\\n");
270     } else {
271       bw.write("\nNumber sharing classes: "+numSharing);
272     }
273
274     bw.close();
275   }
276
277
278
279   // this version of writeAllSharing is for Java programs that have no tasks
280   // ***********************************
281   // WARNING: THIS DOES NOT DO THE RIGHT THING, REPORTS 0 ALWAYS!
282   // It should use mayBothReachTarget and mayManyReachTarget like
283   // OoOJava does to query analysis results
284   // ***********************************
285   public void writeAllSharingJava(String outputFile,
286                                   String timeReport,
287                                   String justTime,
288                                   boolean tabularOutput,
289                                   int numLines
290                                   )
291   throws java.io.IOException {
292     checkAnalysisComplete();
293
294     assert !state.TASK;
295
296     int numSharing = 0;
297
298     BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
299
300     bw.write("Conducting disjoint reachability analysis with allocation depth = "
301              + allocationDepth + "\n");
302     bw.write(timeReport + "\n\n");
303
304     boolean foundSomeSharing = false;
305
306     Descriptor d = typeUtil.getMain();
307     HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
308
309     // for each allocation site check for sharing classes with
310     // other allocation sites in the context of execution
311     // of this task
312     HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
313     Iterator allocItr1 = allocSites.iterator();
314     while (allocItr1.hasNext()) {
315       AllocSite as1 = (AllocSite) allocItr1.next();
316
317       Iterator allocItr2 = allocSites.iterator();
318       while (allocItr2.hasNext()) {
319         AllocSite as2 = (AllocSite) allocItr2.next();
320
321         if (!outerChecked.contains(as2)) {
322           Set<HeapRegionNode> common = hasPotentialSharing(d,
323                                                            as1, as2);
324
325           if (!common.isEmpty()) {
326             foundSomeSharing = true;
327             bw.write("Potential sharing between "
328                      + as1.getDisjointAnalysisId() + " and "
329                      + as2.getDisjointAnalysisId() + ".\n");
330             bw.write(prettyPrintNodeSet(common) + "\n");
331             ++numSharing;
332           }
333         }
334       }
335
336       outerChecked.add(as1);
337     }
338
339     if (!foundSomeSharing) {
340       bw.write("No sharing classes between flagged objects found.\n");
341     } else {
342       bw.write("\nNumber sharing classes: "+numSharing);
343     }
344
345     bw.write("Number of methods analyzed: "+numMethodsAnalyzed()+"\n");
346
347     bw.close();
348   }
349
350
351
352   public Alloc getCmdLineArgsAlloc() {
353     return getAllocationSiteFromFlatNew( constructedCmdLineArgsNew );
354   }
355   ///////////////////////////////////////////
356   //
357   // end public interface
358   //
359   ///////////////////////////////////////////
360
361
362
363   protected void checkAnalysisComplete() {
364     if( !analysisComplete ) {
365       throw new Error("Warning: public interface method called while analysis is running.");
366     }
367   }
368
369
370
371
372
373
374   // run in faster mode, only when bugs wrung out!
375   public static boolean releaseMode;
376
377   // use command line option to set this, analysis
378   // should attempt to be deterministic
379   public static boolean determinismDesired;
380
381   // when we want to enforce determinism in the
382   // analysis we need to sort descriptors rather
383   // than toss them in efficient sets, use this
384   public static DescriptorComparator dComp =
385     new DescriptorComparator();
386
387
388   // data from the compiler
389   public State state;
390   public CallGraph callGraph;
391   public Liveness liveness;
392   public ArrayReferencees arrayReferencees;
393   public RBlockRelationAnalysis rblockRel;
394   public TypeUtil typeUtil;
395   public int allocationDepth;
396
397   protected boolean doEffectsAnalysis = false;
398   protected EffectsAnalysis effectsAnalysis;
399   protected BuildStateMachines buildStateMachines;
400
401
402   // data structure for public interface
403   private Hashtable< Descriptor, HashSet<AllocSite> >
404   mapDescriptorToAllocSiteSet;
405
406
407   // for public interface methods to warn that they
408   // are grabbing results during analysis
409   private boolean analysisComplete;
410
411
412   // used to identify HeapRegionNode objects
413   // A unique ID equates an object in one
414   // ownership graph with an object in another
415   // graph that logically represents the same
416   // heap region
417   // start at 10 and increment to reserve some
418   // IDs for special purposes
419   static protected int uniqueIDcount = 10;
420
421
422   // An out-of-scope method created by the
423   // analysis that has no parameters, and
424   // appears to allocate the command line
425   // arguments, then invoke the source code's
426   // main method.  The purpose of this is to
427   // provide the analysis with an explicit
428   // top-level context with no parameters
429   protected MethodDescriptor mdAnalysisEntry;
430   protected FlatMethod fmAnalysisEntry;
431
432   // main method defined by source program
433   protected MethodDescriptor mdSourceEntry;
434
435   // the set of task and/or method descriptors
436   // reachable in call graph
437   protected Set<Descriptor>
438   descriptorsToAnalyze;
439
440   // current descriptors to visit in fixed-point
441   // interprocedural analysis, prioritized by
442   // dependency in the call graph
443   protected Stack<Descriptor>
444   descriptorsToVisitStack;
445   protected PriorityQueue<DescriptorQWrapper>
446   descriptorsToVisitQ;
447
448   // a duplication of the above structure, but
449   // for efficient testing of inclusion
450   protected HashSet<Descriptor>
451   descriptorsToVisitSet;
452
453   // storage for priorities (doesn't make sense)
454   // to add it to the Descriptor class, just in
455   // this analysis
456   protected Hashtable<Descriptor, Integer>
457   mapDescriptorToPriority;
458
459   // when analyzing a method and scheduling more:
460   // remember set of callee's enqueued for analysis
461   // so they can be put on top of the callers in
462   // the stack-visit mode
463   protected Set<Descriptor>
464   calleesToEnqueue;
465
466   // maps a descriptor to its current partial result
467   // from the intraprocedural fixed-point analysis--
468   // then the interprocedural analysis settles, this
469   // mapping will have the final results for each
470   // method descriptor
471   protected Hashtable<Descriptor, ReachGraph>
472   mapDescriptorToCompleteReachGraph;
473
474   // maps a descriptor to its known dependents: namely
475   // methods or tasks that call the descriptor's method
476   // AND are part of this analysis (reachable from main)
477   protected Hashtable< Descriptor, Set<Descriptor> >
478   mapDescriptorToSetDependents;
479
480   // if the analysis client wants to flag allocation sites
481   // programmatically, it should provide a set of FlatNew
482   // statements--this may be null if unneeded
483   protected Set<FlatNew> sitesToFlag;
484
485   // maps each flat new to one analysis abstraction
486   // allocate site object, these exist outside reach graphs
487   protected Hashtable<FlatNew, AllocSite>
488   mapFlatNewToAllocSite;
489
490   // maps intergraph heap region IDs to intergraph
491   // allocation sites that created them, a redundant
492   // structure for efficiency in some operations
493   protected Hashtable<Integer, AllocSite>
494   mapHrnIdToAllocSite;
495
496   // maps a method to its initial heap model (IHM) that
497   // is the set of reachability graphs from every caller
498   // site, all merged together.  The reason that we keep
499   // them separate is that any one call site's contribution
500   // to the IHM may changed along the path to the fixed point
501   protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
502   mapDescriptorToIHMcontributions;
503
504   // additionally, keep a mapping from descriptors to the
505   // merged in-coming initial context, because we want this
506   // initial context to be STRICTLY MONOTONIC
507   protected Hashtable<Descriptor, ReachGraph>
508   mapDescriptorToInitialContext;
509
510   // make the result for back edges analysis-wide STRICTLY
511   // MONOTONIC as well, but notice we use FlatNode as the
512   // key for this map: in case we want to consider other
513   // nodes as back edge's in future implementations
514   protected Hashtable<FlatNode, ReachGraph>
515   mapBackEdgeToMonotone;
516
517
518   public static final String arrayElementFieldName = "___element_";
519   static protected Hashtable<TypeDescriptor, FieldDescriptor>
520   mapTypeToArrayField;
521
522
523   protected boolean suppressOutput;
524
525   // for controlling DOT file output
526   protected boolean writeFinalDOTs;
527   protected boolean writeAllIncrementalDOTs;
528
529   // supporting DOT output--when we want to write every
530   // partial method result, keep a tally for generating
531   // unique filenames
532   protected Hashtable<Descriptor, Integer>
533   mapDescriptorToNumUpdates;
534
535   //map task descriptor to initial task parameter
536   protected Hashtable<Descriptor, ReachGraph>
537   mapDescriptorToReachGraph;
538
539   protected PointerMethod pm;
540
541   //Keeps track of all the reach graphs at every program point
542   //DO NOT USE UNLESS YOU REALLY NEED IT
543   static protected Hashtable<FlatNode, ReachGraph> fn2rgAtEnter =
544     new Hashtable<FlatNode, ReachGraph>();
545
546   static protected Hashtable<FlatNode, ReachGraph> fn2rgAtExit =
547     new Hashtable<FlatNode, ReachGraph>();
548
549
550   private Hashtable<FlatCall, Descriptor> fc2enclosing;
551
552   Accessible accessible;
553
554   
555   // we construct an entry method of flat nodes complete
556   // with a new allocation site to model the command line
557   // args creation just for the analysis, so remember that
558   // allocation site.  Later in code gen we might want to
559   // know if something is pointing-to to the cmd line args
560   // and we can verify by checking the allocation site field.
561   protected FlatNew constructedCmdLineArgsNew;
562
563
564
565
566   // allocate various structures that are not local
567   // to a single class method--should be done once
568   protected void allocateStructures() {
569
570     if( determinismDesired ) {
571       // use an ordered set
572       descriptorsToAnalyze = new TreeSet<Descriptor>(dComp);
573     } else {
574       // otherwise use a speedy hashset
575       descriptorsToAnalyze = new HashSet<Descriptor>();
576     }
577
578     mapDescriptorToCompleteReachGraph =
579       new Hashtable<Descriptor, ReachGraph>();
580
581     mapDescriptorToNumUpdates =
582       new Hashtable<Descriptor, Integer>();
583
584     mapDescriptorToSetDependents =
585       new Hashtable< Descriptor, Set<Descriptor> >();
586
587     mapFlatNewToAllocSite =
588       new Hashtable<FlatNew, AllocSite>();
589
590     mapDescriptorToIHMcontributions =
591       new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
592
593     mapDescriptorToInitialContext =
594       new Hashtable<Descriptor, ReachGraph>();
595
596     mapBackEdgeToMonotone =
597       new Hashtable<FlatNode, ReachGraph>();
598
599     mapHrnIdToAllocSite =
600       new Hashtable<Integer, AllocSite>();
601
602     mapTypeToArrayField =
603       new Hashtable <TypeDescriptor, FieldDescriptor>();
604
605     if( state.DISJOINTDVISITSTACK ||
606         state.DISJOINTDVISITSTACKEESONTOP
607         ) {
608       descriptorsToVisitStack =
609         new Stack<Descriptor>();
610     }
611
612     if( state.DISJOINTDVISITPQUE ) {
613       descriptorsToVisitQ =
614         new PriorityQueue<DescriptorQWrapper>();
615     }
616
617     descriptorsToVisitSet =
618       new HashSet<Descriptor>();
619
620     mapDescriptorToPriority =
621       new Hashtable<Descriptor, Integer>();
622
623     calleesToEnqueue =
624       new HashSet<Descriptor>();
625
626     mapDescriptorToAllocSiteSet =
627       new Hashtable<Descriptor,    HashSet<AllocSite> >();
628
629     mapDescriptorToReachGraph =
630       new Hashtable<Descriptor, ReachGraph>();
631
632     pm = new PointerMethod();
633
634     fc2enclosing = new Hashtable<FlatCall, Descriptor>();
635   }
636
637
638
639   // this analysis generates a disjoint reachability
640   // graph for every reachable method in the program
641   public DisjointAnalysis(State s,
642                           TypeUtil tu,
643                           CallGraph cg,
644                           Liveness l,
645                           ArrayReferencees ar,
646                           Set<FlatNew> sitesToFlag,
647                           RBlockRelationAnalysis rra
648                           ) {
649     init(s, tu, cg, l, ar, sitesToFlag, rra, null, false);
650   }
651
652   public DisjointAnalysis(State s,
653                           TypeUtil tu,
654                           CallGraph cg,
655                           Liveness l,
656                           ArrayReferencees ar,
657                           Set<FlatNew> sitesToFlag,
658                           RBlockRelationAnalysis rra,
659                           boolean suppressOutput
660                           ) {
661     init(s, tu, cg, l, ar, sitesToFlag, rra, null, suppressOutput);
662   }
663
664   public DisjointAnalysis(State s,
665                           TypeUtil tu,
666                           CallGraph cg,
667                           Liveness l,
668                           ArrayReferencees ar,
669                           Set<FlatNew> sitesToFlag,
670                           RBlockRelationAnalysis rra,
671                           BuildStateMachines bsm,
672                           boolean suppressOutput
673                           ) {
674     init(s, tu, cg, l, ar, sitesToFlag, rra, bsm, suppressOutput);
675   }
676
677   protected void init(State state,
678                       TypeUtil typeUtil,
679                       CallGraph callGraph,
680                       Liveness liveness,
681                       ArrayReferencees arrayReferencees,
682                       Set<FlatNew> sitesToFlag,
683                       RBlockRelationAnalysis rra,
684                       BuildStateMachines bsm,
685                       boolean suppressOutput
686                       ) {
687
688     analysisComplete = false;
689
690     this.state              = state;
691     this.typeUtil           = typeUtil;
692     this.callGraph          = callGraph;
693     this.liveness           = liveness;
694     this.arrayReferencees   = arrayReferencees;
695     this.sitesToFlag        = sitesToFlag;
696     this.rblockRel          = rra;
697     this.suppressOutput     = suppressOutput;
698     this.buildStateMachines = bsm;
699
700     if( rblockRel != null ) {
701       doEffectsAnalysis = true;
702       effectsAnalysis   = new EffectsAnalysis();
703
704       EffectsAnalysis.state              = state;
705       EffectsAnalysis.buildStateMachines = buildStateMachines;
706
707       //note: instead of reachgraph's isAccessible, using the result of accessible analysis
708       //since accessible gives us more accurate results
709       accessible=new Accessible(state, callGraph, rra, liveness);
710       accessible.doAnalysis();
711     }
712
713     this.allocationDepth         = state.DISJOINTALLOCDEPTH;
714     this.releaseMode             = state.DISJOINTRELEASEMODE;
715     this.determinismDesired      = state.DISJOINTDETERMINISM;
716
717     this.writeFinalDOTs          = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
718     this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS &&  state.DISJOINTWRITEALL;
719
720     this.takeDebugSnapshots      = state.DISJOINTSNAPSYMBOL != null;
721     this.descSymbolDebug         = state.DISJOINTSNAPSYMBOL;
722     this.visitStartCapture       = state.DISJOINTSNAPVISITTOSTART;
723     this.numVisitsToCapture      = state.DISJOINTSNAPNUMVISITS;
724     this.stopAfterCapture        = state.DISJOINTSNAPSTOPAFTER;
725     this.snapVisitCounter        = 1; // count visits from 1 (user will write 1, means 1st visit)
726     this.snapNodeCounter         = 0; // count nodes from 0
727
728     assert
729     state.DISJOINTDVISITSTACK ||
730     state.DISJOINTDVISITPQUE  ||
731     state.DISJOINTDVISITSTACKEESONTOP;
732     assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITPQUE);
733     assert !(state.DISJOINTDVISITSTACK && state.DISJOINTDVISITSTACKEESONTOP);
734     assert !(state.DISJOINTDVISITPQUE  && state.DISJOINTDVISITSTACKEESONTOP);
735
736     // set some static configuration for ReachGraphs
737     ReachGraph.allocationDepth = allocationDepth;
738     ReachGraph.typeUtil        = typeUtil;
739     ReachGraph.state           = state;
740
741     ReachGraph.debugCallSiteVisitStartCapture
742       = state.DISJOINTDEBUGCALLVISITTOSTART;
743
744     ReachGraph.debugCallSiteNumVisitsToCapture
745       = state.DISJOINTDEBUGCALLNUMVISITS;
746
747     ReachGraph.debugCallSiteStopAfter
748       = state.DISJOINTDEBUGCALLSTOPAFTER;
749
750     ReachGraph.debugCallSiteVisitCounter
751       = 0; // count visits from 1, is incremented before first visit
752
753     
754
755
756     if( suppressOutput ) {
757       System.out.println("* Running disjoint reachability analysis with output suppressed! *");
758     }
759
760     allocateStructures();
761
762     double timeStartAnalysis = (double) System.nanoTime();
763
764     // start interprocedural fixed-point computation
765     try {
766       analyzeMethods();
767     } catch( IOException e ) {
768       throw new Error("IO Exception while writing disjointness analysis output.");
769     }
770
771     analysisComplete=true;
772
773     double timeEndAnalysis = (double) System.nanoTime();
774     double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow(10.0, 9.0) );
775
776     String treport;
777     if( sitesToFlag != null ) {
778       treport = String.format("Disjoint reachability analysis flagged %d sites and took %.3f sec.", sitesToFlag.size(), dt);
779       if(sitesToFlag.size()>0) {
780         treport+="\nFlagged sites:"+"\n"+sitesToFlag.toString();
781       }
782     } else {
783       treport = String.format("Disjoint reachability analysis took %.3f sec.", dt);
784     }
785     String justtime = String.format("%.2f", dt);
786     System.out.println(treport);
787
788
789     try {
790       if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
791         writeFinalGraphs();
792       }
793
794       if( state.DISJOINTWRITEIHMS && !suppressOutput ) {
795         writeFinalIHMs();
796       }
797
798       if( state.DISJOINTWRITEINITCONTEXTS && !suppressOutput ) {
799         writeInitialContexts();
800       }
801
802       if( state.DISJOINTALIASFILE != null && !suppressOutput ) {
803         if( state.TASK ) {
804           writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
805         } else {
806           writeAllSharingJava(state.DISJOINTALIASFILE,
807                               treport,
808                               justtime,
809                               state.DISJOINTALIASTAB,
810                               state.lines
811                               );
812         }
813       }
814
815       if( state.RCR ) {
816         buildStateMachines.writeStateMachines();
817       }
818
819     } catch( IOException e ) {
820       throw new Error("IO Exception while writing disjointness analysis output.");
821     }
822   }
823
824
825   protected boolean moreDescriptorsToVisit() {
826     if( state.DISJOINTDVISITSTACK ||
827         state.DISJOINTDVISITSTACKEESONTOP
828         ) {
829       return !descriptorsToVisitStack.isEmpty();
830
831     } else if( state.DISJOINTDVISITPQUE ) {
832       return !descriptorsToVisitQ.isEmpty();
833     }
834
835     throw new Error("Neither descriptor visiting mode set");
836   }
837
838
839   // fixed-point computation over the call graph--when a
840   // method's callees are updated, it must be reanalyzed
841   protected void analyzeMethods() throws java.io.IOException {
842
843     // task or non-task (java) mode determines what the roots
844     // of the call chain are, and establishes the set of methods
845     // reachable from the roots that will be analyzed
846
847     if( state.TASK ) {
848       if( !suppressOutput ) {
849         System.out.println("Bamboo mode...");
850       }
851
852       Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
853       while( taskItr.hasNext() ) {
854         TaskDescriptor td = (TaskDescriptor) taskItr.next();
855         if( !descriptorsToAnalyze.contains(td) ) {
856           // add all methods transitively reachable from the
857           // tasks as well
858           descriptorsToAnalyze.add(td);
859           descriptorsToAnalyze.addAll(callGraph.getAllMethods(td) );
860         }
861       }
862
863     } else {
864       if( !suppressOutput ) {
865         System.out.println("Java mode...");
866       }
867
868       // add all methods transitively reachable from the
869       // source's main to set for analysis
870       mdSourceEntry = typeUtil.getMain();
871       descriptorsToAnalyze.add(mdSourceEntry);
872       descriptorsToAnalyze.addAll(callGraph.getAllMethods(mdSourceEntry) );
873
874       // fabricate an empty calling context that will call
875       // the source's main, but call graph doesn't know
876       // about it, so explicitly add it
877       makeAnalysisEntryMethod(mdSourceEntry);
878       descriptorsToAnalyze.add(mdAnalysisEntry);
879     }
880
881
882     // now, depending on the interprocedural mode for visiting
883     // methods, set up the needed data structures
884
885     if( state.DISJOINTDVISITPQUE ) {
886
887       // topologically sort according to the call graph so
888       // leaf calls are last, helps build contexts up first
889       LinkedList<Descriptor> sortedDescriptors =
890         topologicalSort(descriptorsToAnalyze);
891
892       // add sorted descriptors to priority queue, and duplicate
893       // the queue as a set for efficiently testing whether some
894       // method is marked for analysis
895       int p = 0;
896       Iterator<Descriptor> dItr;
897
898       // for the priority queue, give items at the head
899       // of the sorted list a low number (highest priority)
900       while( !sortedDescriptors.isEmpty() ) {
901         Descriptor d = sortedDescriptors.removeFirst();
902         mapDescriptorToPriority.put(d, new Integer(p) );
903         descriptorsToVisitQ.add(new DescriptorQWrapper(p, d) );
904         descriptorsToVisitSet.add(d);
905         ++p;
906       }
907
908     } else if( state.DISJOINTDVISITSTACK ||
909                state.DISJOINTDVISITSTACKEESONTOP
910                ) {
911       // if we're doing the stack scheme, just throw the root
912       // method or tasks on the stack
913       if( state.TASK ) {
914         Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
915         while( taskItr.hasNext() ) {
916           TaskDescriptor td = (TaskDescriptor) taskItr.next();
917           descriptorsToVisitStack.add(td);
918           descriptorsToVisitSet.add(td);
919         }
920
921       } else {
922         descriptorsToVisitStack.add(mdAnalysisEntry);
923         descriptorsToVisitSet.add(mdAnalysisEntry);
924       }
925
926     } else {
927       throw new Error("Unknown method scheduling mode");
928     }
929
930
931     // analyze scheduled methods until there are no more to visit
932     while( moreDescriptorsToVisit() ) {
933       Descriptor d = null;
934
935       if( state.DISJOINTDVISITSTACK ||
936           state.DISJOINTDVISITSTACKEESONTOP
937           ) {
938         d = descriptorsToVisitStack.pop();
939
940       } else if( state.DISJOINTDVISITPQUE ) {
941         d = descriptorsToVisitQ.poll().getDescriptor();
942       }
943
944       assert descriptorsToVisitSet.contains(d);
945       descriptorsToVisitSet.remove(d);
946
947       // because the task or method descriptor just extracted
948       // was in the "to visit" set it either hasn't been analyzed
949       // yet, or some method that it depends on has been
950       // updated.  Recompute a complete reachability graph for
951       // this task/method and compare it to any previous result.
952       // If there is a change detected, add any methods/tasks
953       // that depend on this one to the "to visit" set.
954
955       if( !suppressOutput ) {
956         System.out.println("Analyzing " + d);
957       }
958
959       if( state.DISJOINTDVISITSTACKEESONTOP ) {
960         assert calleesToEnqueue.isEmpty();
961       }
962
963       ReachGraph rg     = analyzeMethod(d);
964       ReachGraph rgPrev = getPartial(d);
965
966       if( !rg.equals(rgPrev) ) {
967         setPartial(d, rg);
968
969         if( state.DISJOINTDEBUGSCHEDULING ) {
970           System.out.println("  complete graph changed, scheduling callers for analysis:");
971         }
972
973         // results for d changed, so enqueue dependents
974         // of d for further analysis
975         Iterator<Descriptor> depsItr = getDependents(d).iterator();
976         while( depsItr.hasNext() ) {
977           Descriptor dNext = depsItr.next();
978           enqueue(dNext);
979
980           if( state.DISJOINTDEBUGSCHEDULING ) {
981             System.out.println("    "+dNext);
982           }
983         }
984       }
985
986       // whether or not the method under analysis changed,
987       // we may have some callees that are scheduled for
988       // more analysis, and they should go on the top of
989       // the stack now (in other method-visiting modes they
990       // are already enqueued at this point
991       if( state.DISJOINTDVISITSTACKEESONTOP ) {
992         Iterator<Descriptor> depsItr = calleesToEnqueue.iterator();
993         while( depsItr.hasNext() ) {
994           Descriptor dNext = depsItr.next();
995           enqueue(dNext);
996         }
997         calleesToEnqueue.clear();
998       }
999
1000     }
1001   }
1002
1003   protected ReachGraph analyzeMethod(Descriptor d)
1004   throws java.io.IOException {
1005
1006     // get the flat code for this descriptor
1007     FlatMethod fm;
1008     if( d == mdAnalysisEntry ) {
1009       fm = fmAnalysisEntry;
1010     } else {
1011       fm = state.getMethodFlat(d);
1012     }
1013     pm.analyzeMethod(fm);
1014
1015     // intraprocedural work set
1016     Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
1017     flatNodesToVisit.add(fm);
1018
1019     // if determinism is desired by client, shadow the
1020     // set with a queue to make visit order deterministic
1021     Queue<FlatNode> flatNodesToVisitQ = null;
1022     if( determinismDesired ) {
1023       flatNodesToVisitQ = new LinkedList<FlatNode>();
1024       flatNodesToVisitQ.add(fm);
1025     }
1026
1027     // mapping of current partial results
1028     Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
1029       new Hashtable<FlatNode, ReachGraph>();
1030
1031     // the set of return nodes partial results that will be combined as
1032     // the final, conservative approximation of the entire method
1033     HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
1034
1035
1036
1037     boolean snapThisMethod = false;
1038     if( takeDebugSnapshots && d instanceof MethodDescriptor ) {
1039       MethodDescriptor mdThisMethod = (MethodDescriptor)d;
1040       ClassDescriptor  cdThisMethod = mdThisMethod.getClassDesc();
1041       if( cdThisMethod != null ) {
1042         snapThisMethod = 
1043           descSymbolDebug.equals( cdThisMethod.getSymbol()+
1044                                   "."+
1045                                   mdThisMethod.getSymbol()
1046                                   );
1047       }
1048     }
1049
1050
1051
1052     while( !flatNodesToVisit.isEmpty() ) {
1053
1054       FlatNode fn;
1055       if( determinismDesired ) {
1056         assert !flatNodesToVisitQ.isEmpty();
1057         fn = flatNodesToVisitQ.remove();
1058       } else {
1059         fn = flatNodesToVisit.iterator().next();
1060       }
1061       flatNodesToVisit.remove(fn);
1062
1063       // effect transfer function defined by this node,
1064       // then compare it to the old graph at this node
1065       // to see if anything was updated.
1066
1067       ReachGraph rg = new ReachGraph();
1068       TaskDescriptor taskDesc;
1069       if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null) {
1070         if(mapDescriptorToReachGraph.containsKey(taskDesc)) {
1071           // retrieve existing reach graph if it is not first time
1072           rg=mapDescriptorToReachGraph.get(taskDesc);
1073         } else {
1074           // create initial reach graph for a task
1075           rg=createInitialTaskReachGraph((FlatMethod)fn);
1076           rg.globalSweep();
1077           mapDescriptorToReachGraph.put(taskDesc, rg);
1078         }
1079       }
1080
1081       // start by merging all node's parents' graphs
1082       for( int i = 0; i < pm.numPrev(fn); ++i ) {
1083         FlatNode pn = pm.getPrev(fn,i);
1084         if( mapFlatNodeToReachGraph.containsKey(pn) ) {
1085           ReachGraph rgParent = mapFlatNodeToReachGraph.get(pn);
1086           rg.merge(rgParent);
1087         }
1088       }
1089
1090
1091       if( snapThisMethod ) {
1092         debugSnapshot(rg, fn, true);
1093       }
1094
1095
1096       // modify rg with appropriate transfer function
1097       rg = analyzeFlatNode(d, fm, fn, setReturns, rg);
1098
1099
1100       if( snapThisMethod ) {
1101         debugSnapshot(rg, fn, false);
1102         ++snapNodeCounter;
1103       }
1104
1105
1106       // if the results of the new graph are different from
1107       // the current graph at this node, replace the graph
1108       // with the update and enqueue the children
1109       ReachGraph rgPrev = mapFlatNodeToReachGraph.get(fn);
1110       if( !rg.equals(rgPrev) ) {
1111         mapFlatNodeToReachGraph.put(fn, rg);
1112
1113         for( int i = 0; i < pm.numNext(fn); i++ ) {
1114           FlatNode nn = pm.getNext(fn, i);
1115
1116           flatNodesToVisit.add(nn);
1117           if( determinismDesired ) {
1118             flatNodesToVisitQ.add(nn);
1119           }
1120         }
1121       }
1122     }
1123
1124
1125     // end by merging all return nodes into a complete
1126     // reach graph that represents all possible heap
1127     // states after the flat method returns
1128     ReachGraph completeGraph = new ReachGraph();
1129
1130     assert !setReturns.isEmpty();
1131     Iterator retItr = setReturns.iterator();
1132     while( retItr.hasNext() ) {
1133       FlatReturnNode frn = (FlatReturnNode) retItr.next();
1134
1135       assert mapFlatNodeToReachGraph.containsKey(frn);
1136       ReachGraph rgRet = mapFlatNodeToReachGraph.get(frn);
1137
1138       completeGraph.merge(rgRet);
1139     }
1140
1141
1142     if( snapThisMethod ) {
1143       // increment that we've visited the debug snap
1144       // method, and reset the node counter
1145       System.out.println("    @@@ debug snap at visit "+snapVisitCounter);
1146       ++snapVisitCounter;
1147       snapNodeCounter = 0;
1148
1149       if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
1150           stopAfterCapture
1151           ) {
1152         System.out.println("!!! Stopping analysis after debug snap captures. !!!");
1153         System.exit(0);
1154       }
1155     }
1156
1157
1158     return completeGraph;
1159   }
1160
1161
1162   protected ReachGraph
1163   analyzeFlatNode(Descriptor d,
1164                   FlatMethod fmContaining,
1165                   FlatNode fn,
1166                   HashSet<FlatReturnNode> setRetNodes,
1167                   ReachGraph rg
1168                   ) throws java.io.IOException {
1169
1170
1171     // any variables that are no longer live should be
1172     // nullified in the graph to reduce edges
1173     //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
1174
1175     TempDescriptor lhs;
1176     TempDescriptor rhs;
1177     FieldDescriptor fld;
1178     TypeDescriptor tdElement;
1179     FieldDescriptor fdElement;
1180     FlatSESEEnterNode sese;
1181     FlatSESEExitNode fsexn;
1182
1183     //Stores the flatnode's reach graph at enter
1184     ReachGraph rgOnEnter = new ReachGraph();
1185     rgOnEnter.merge(rg);
1186     fn2rgAtEnter.put(fn, rgOnEnter);
1187
1188
1189
1190     // use node type to decide what transfer function
1191     // to apply to the reachability graph
1192     switch( fn.kind() ) {
1193
1194     case FKind.FlatGenReachNode: {
1195       FlatGenReachNode fgrn = (FlatGenReachNode) fn;
1196
1197       System.out.println("  Generating reach graph for program point: "+fgrn.getGraphName() );
1198
1199
1200       rg.writeGraph("genReach"+fgrn.getGraphName(),
1201                     true,     // write labels (variables)
1202                     true,    // selectively hide intermediate temp vars
1203                     true,     // prune unreachable heap regions
1204                     true,    // hide reachability altogether
1205                     true,    // hide subset reachability states
1206                     true,     // hide predicates
1207                     false);    // hide edge taints
1208     } break;
1209
1210
1211     case FKind.FlatMethod: {
1212       // construct this method's initial heap model (IHM)
1213       // since we're working on the FlatMethod, we know
1214       // the incoming ReachGraph 'rg' is empty
1215
1216       Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1217         getIHMcontributions(d);
1218
1219       Set entrySet = heapsFromCallers.entrySet();
1220       Iterator itr = entrySet.iterator();
1221       while( itr.hasNext() ) {
1222         Map.Entry me        = (Map.Entry)itr.next();
1223         FlatCall fc        = (FlatCall)   me.getKey();
1224         ReachGraph rgContrib = (ReachGraph) me.getValue();
1225
1226         assert fc.getMethod().equals(d);
1227
1228         rg.merge(rgContrib);
1229       }
1230
1231       // additionally, we are enforcing STRICT MONOTONICITY for the
1232       // method's initial context, so grow the context by whatever
1233       // the previously computed context was, and put the most
1234       // up-to-date context back in the map
1235       ReachGraph rgPrevContext = mapDescriptorToInitialContext.get(d);
1236       rg.merge(rgPrevContext);
1237       mapDescriptorToInitialContext.put(d, rg);
1238
1239     } break;
1240
1241     case FKind.FlatOpNode:
1242       FlatOpNode fon = (FlatOpNode) fn;
1243       if( fon.getOp().getOp() == Operation.ASSIGN ) {
1244         lhs = fon.getDest();
1245         rhs = fon.getLeft();
1246
1247         // before transfer, do effects analysis support
1248         if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1249           if(rblockRel.isPotentialStallSite(fn)) {
1250             // x gets status of y
1251 //            if(!rg.isAccessible(rhs)){
1252             if(!accessible.isAccessible(fn, rhs)) {
1253               rg.makeInaccessible(lhs);
1254             }
1255           }
1256         }
1257
1258         // transfer func
1259         rg.assignTempXEqualToTempY(lhs, rhs);
1260       }
1261       break;
1262
1263     case FKind.FlatCastNode:
1264       FlatCastNode fcn = (FlatCastNode) fn;
1265       lhs = fcn.getDst();
1266       rhs = fcn.getSrc();
1267
1268       TypeDescriptor td = fcn.getType();
1269       assert td != null;
1270
1271       // before transfer, do effects analysis support
1272       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1273         if(rblockRel.isPotentialStallSite(fn)) {
1274           // x gets status of y
1275 //          if(!rg.isAccessible(rhs)){
1276           if(!accessible.isAccessible(fn,rhs)) {
1277             rg.makeInaccessible(lhs);
1278           }
1279         }
1280       }
1281
1282       // transfer func
1283       rg.assignTempXEqualToCastedTempY(lhs, rhs, td);
1284       break;
1285
1286     case FKind.FlatFieldNode:
1287       FlatFieldNode ffn = (FlatFieldNode) fn;
1288
1289       lhs = ffn.getDst();
1290       rhs = ffn.getSrc();
1291       fld = ffn.getField();
1292
1293       // before graph transform, possible inject
1294       // a stall-site taint
1295       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1296
1297         if(rblockRel.isPotentialStallSite(fn)) {
1298           // x=y.f, stall y if not accessible
1299           // contributes read effects on stall site of y
1300 //          if(!rg.isAccessible(rhs)) {
1301           if(!accessible.isAccessible(fn,rhs)) {
1302             rg.taintStallSite(fn, rhs);
1303           }
1304
1305           // after this, x and y are accessbile.
1306           rg.makeAccessible(lhs);
1307           rg.makeAccessible(rhs);
1308         }
1309       }
1310
1311       if( shouldAnalysisTrack(fld.getType() ) ) {
1312         // transfer func
1313         rg.assignTempXEqualToTempYFieldF(lhs, rhs, fld, fn);
1314       }
1315
1316       // after transfer, use updated graph to
1317       // do effects analysis
1318       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1319         effectsAnalysis.analyzeFlatFieldNode(rg, rhs, fld, fn);
1320       }
1321       break;
1322
1323     case FKind.FlatSetFieldNode:
1324       FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
1325
1326       lhs = fsfn.getDst();
1327       fld = fsfn.getField();
1328       rhs = fsfn.getSrc();
1329
1330       boolean strongUpdate = false;
1331
1332       // before transfer func, possibly inject
1333       // stall-site taints
1334       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1335
1336         if(rblockRel.isPotentialStallSite(fn)) {
1337           // x.y=f , stall x and y if they are not accessible
1338           // also contribute write effects on stall site of x
1339 //          if(!rg.isAccessible(lhs)) {
1340           if(!accessible.isAccessible(fn,lhs)) {
1341             rg.taintStallSite(fn, lhs);
1342           }
1343
1344 //          if(!rg.isAccessible(rhs)) {
1345           if(!accessible.isAccessible(fn,rhs)) {
1346             rg.taintStallSite(fn, rhs);
1347           }
1348
1349           // accessible status update
1350           rg.makeAccessible(lhs);
1351           rg.makeAccessible(rhs);
1352         }
1353       }
1354
1355       if( shouldAnalysisTrack(fld.getType() ) ) {
1356         // transfer func
1357         strongUpdate = rg.assignTempXFieldFEqualToTempY(lhs, fld, rhs, fn);
1358       }
1359
1360       // use transformed graph to do effects analysis
1361       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1362         effectsAnalysis.analyzeFlatSetFieldNode(rg, lhs, fld, fn, strongUpdate);
1363       }
1364       break;
1365
1366     case FKind.FlatElementNode:
1367       FlatElementNode fen = (FlatElementNode) fn;
1368
1369       lhs = fen.getDst();
1370       rhs = fen.getSrc();
1371
1372       assert rhs.getType() != null;
1373       assert rhs.getType().isArray();
1374
1375       tdElement = rhs.getType().dereference();
1376       fdElement = getArrayField(tdElement);
1377
1378       // before transfer func, possibly inject
1379       // stall-site taint
1380       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1381         if(rblockRel.isPotentialStallSite(fn)) {
1382           // x=y.f, stall y if not accessible
1383           // contributes read effects on stall site of y
1384           // after this, x and y are accessbile.
1385 //          if(!rg.isAccessible(rhs)) {
1386           if(!accessible.isAccessible(fn,rhs)) {
1387             rg.taintStallSite(fn, rhs);
1388           }
1389
1390           rg.makeAccessible(lhs);
1391           rg.makeAccessible(rhs);
1392         }
1393       }
1394
1395       if( shouldAnalysisTrack(lhs.getType() ) ) {
1396         // transfer func
1397         rg.assignTempXEqualToTempYFieldF(lhs, rhs, fdElement, fn);
1398       }
1399
1400       // use transformed graph to do effects analysis
1401       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1402         effectsAnalysis.analyzeFlatFieldNode(rg, rhs, fdElement, fn);
1403       }
1404       break;
1405
1406     case FKind.FlatSetElementNode:
1407       FlatSetElementNode fsen = (FlatSetElementNode) fn;
1408
1409       lhs = fsen.getDst();
1410       rhs = fsen.getSrc();
1411
1412       assert lhs.getType() != null;
1413       assert lhs.getType().isArray();
1414
1415       tdElement = lhs.getType().dereference();
1416       fdElement = getArrayField(tdElement);
1417
1418       // before transfer func, possibly inject
1419       // stall-site taints
1420       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1421
1422         if(rblockRel.isPotentialStallSite(fn)) {
1423           // x.y=f , stall x and y if they are not accessible
1424           // also contribute write effects on stall site of x
1425 //          if(!rg.isAccessible(lhs)) {
1426           if(!accessible.isAccessible(fn,lhs)) {
1427             rg.taintStallSite(fn, lhs);
1428           }
1429
1430 //          if(!rg.isAccessible(rhs)) {
1431           if(!accessible.isAccessible(fn,rhs)) {
1432             rg.taintStallSite(fn, rhs);
1433           }
1434
1435           // accessible status update
1436           rg.makeAccessible(lhs);
1437           rg.makeAccessible(rhs);
1438         }
1439       }
1440
1441       if( shouldAnalysisTrack(rhs.getType() ) ) {
1442         // transfer func, BUT
1443         // skip this node if it cannot create new reachability paths
1444         if( !arrayReferencees.doesNotCreateNewReaching(fsen) ) {
1445           rg.assignTempXFieldFEqualToTempY(lhs, fdElement, rhs, fn);
1446         }
1447       }
1448
1449       // use transformed graph to do effects analysis
1450       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1451         effectsAnalysis.analyzeFlatSetFieldNode(rg, lhs, fdElement, fn,
1452                                                 false);
1453       }
1454       break;
1455
1456     case FKind.FlatNew:
1457       FlatNew fnn = (FlatNew) fn;
1458       lhs = fnn.getDst();
1459       if( shouldAnalysisTrack(lhs.getType() ) ) {
1460         AllocSite as = getAllocSiteFromFlatNewPRIVATE(fnn);
1461
1462         // before transform, support effects analysis
1463         if (doEffectsAnalysis && fmContaining != fmAnalysisEntry) {
1464           if (rblockRel.isPotentialStallSite(fn)) {
1465             // after creating new object, lhs is accessible
1466             rg.makeAccessible(lhs);
1467           }
1468         }
1469
1470         // transfer func
1471         rg.assignTempEqualToNewAlloc(lhs, as);
1472       }
1473       break;
1474
1475     case FKind.FlatSESEEnterNode:
1476       sese = (FlatSESEEnterNode) fn;
1477
1478       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1479
1480         // always remove ALL stall site taints at enter
1481         rg.removeAllStallSiteTaints();
1482
1483         // inject taints for in-set vars
1484         rg.taintInSetVars(sese);
1485
1486       }
1487       break;
1488
1489     case FKind.FlatSESEExitNode:
1490       fsexn = (FlatSESEExitNode) fn;
1491       sese  = fsexn.getFlatEnter();
1492
1493       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1494
1495         // @ sese exit make all live variables
1496         // inaccessible to later parent statements
1497         rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) );
1498
1499         // always remove ALL stall site taints at exit
1500         rg.removeAllStallSiteTaints();
1501
1502         // remove in-set var taints for the exiting rblock
1503         rg.removeInContextTaints(sese);
1504       }
1505       break;
1506
1507
1508     case FKind.FlatCall: {
1509       Descriptor mdCaller;
1510       if( fmContaining.getMethod() != null ) {
1511         mdCaller = fmContaining.getMethod();
1512       } else {
1513         mdCaller = fmContaining.getTask();
1514       }
1515       FlatCall fc       = (FlatCall) fn;
1516       MethodDescriptor mdCallee = fc.getMethod();
1517       FlatMethod fmCallee = state.getMethodFlat(mdCallee);
1518
1519
1520
1521       // all this jimma jamma to debug call sites is WELL WORTH the
1522       // effort, so many bugs or buggy info goes crazy through call
1523       // sites
1524       boolean debugCallSite = false;
1525       if( state.DISJOINTDEBUGCALLEE != null &&
1526           state.DISJOINTDEBUGCALLER != null ) {
1527
1528         boolean debugCalleeMatches = false;
1529         boolean debugCallerMatches = false;
1530         
1531         ClassDescriptor cdCallee = mdCallee.getClassDesc();
1532         if( cdCallee != null ) {
1533           debugCalleeMatches = 
1534             state.DISJOINTDEBUGCALLEE.equals( cdCallee.getSymbol()+
1535                                               "."+
1536                                               mdCallee.getSymbol()
1537                                               );
1538         }
1539
1540
1541         if( mdCaller instanceof MethodDescriptor ) {
1542           ClassDescriptor cdCaller = ((MethodDescriptor)mdCaller).getClassDesc();
1543           if( cdCaller != null ) {
1544             debugCallerMatches = 
1545               state.DISJOINTDEBUGCALLER.equals( cdCaller.getSymbol()+
1546                                                 "."+
1547                                                 mdCaller.getSymbol()
1548                                                 );
1549           }        
1550         } else {
1551           // for bristlecone style tasks
1552           debugCallerMatches =
1553             state.DISJOINTDEBUGCALLER.equals( mdCaller.getSymbol() );
1554         }
1555
1556         debugCallSite = debugCalleeMatches && debugCallerMatches;
1557       }
1558
1559       
1560
1561
1562       boolean writeDebugDOTs = false;
1563       boolean stopAfter      = false;
1564       if( debugCallSite ) {
1565         ++ReachGraph.debugCallSiteVisitCounter;
1566         System.out.println("    $$$ Debug call site visit "+
1567                            ReachGraph.debugCallSiteVisitCounter+
1568                            " $$$"
1569                            );
1570         if(
1571           (ReachGraph.debugCallSiteVisitCounter >=
1572            ReachGraph.debugCallSiteVisitStartCapture)  &&
1573
1574           (ReachGraph.debugCallSiteVisitCounter <
1575            ReachGraph.debugCallSiteVisitStartCapture +
1576            ReachGraph.debugCallSiteNumVisitsToCapture)
1577           ) {
1578           writeDebugDOTs = true;
1579           System.out.println("      $$$ Capturing this call site visit $$$");
1580           if( ReachGraph.debugCallSiteStopAfter &&
1581               (ReachGraph.debugCallSiteVisitCounter ==
1582                ReachGraph.debugCallSiteVisitStartCapture +
1583                ReachGraph.debugCallSiteNumVisitsToCapture - 1)
1584               ) {
1585             stopAfter = true;
1586           }
1587         }
1588       }
1589
1590
1591       // calculate the heap this call site can reach--note this is
1592       // not used for the current call site transform, we are
1593       // grabbing this heap model for future analysis of the callees,
1594       // so if different results emerge we will return to this site
1595       ReachGraph heapForThisCall_old =
1596         getIHMcontribution(mdCallee, fc);
1597
1598       // the computation of the callee-reachable heap
1599       // is useful for making the callee starting point
1600       // and for applying the call site transfer function
1601       Set<Integer> callerNodeIDsCopiedToCallee =
1602         new HashSet<Integer>();
1603
1604       ReachGraph heapForThisCall_cur =
1605         rg.makeCalleeView(fc,
1606                           fmCallee,
1607                           callerNodeIDsCopiedToCallee,
1608                           writeDebugDOTs
1609                           );
1610
1611       // enforce that a call site contribution can only
1612       // monotonically increase
1613       heapForThisCall_cur.merge(heapForThisCall_old);
1614
1615       if( !heapForThisCall_cur.equals(heapForThisCall_old) ) {
1616         // if heap at call site changed, update the contribution,
1617         // and reschedule the callee for analysis
1618         addIHMcontribution(mdCallee, fc, heapForThisCall_cur);
1619
1620         // map a FlatCall to its enclosing method/task descriptor
1621         // so we can write that info out later
1622         fc2enclosing.put(fc, mdCaller);
1623
1624         if( state.DISJOINTDEBUGSCHEDULING ) {
1625           System.out.println("  context changed, scheduling callee: "+mdCallee);
1626         }
1627
1628         if( state.DISJOINTDVISITSTACKEESONTOP ) {
1629           calleesToEnqueue.add(mdCallee);
1630         } else {
1631           enqueue(mdCallee);
1632         }
1633
1634       }
1635
1636       // the transformation for a call site should update the
1637       // current heap abstraction with any effects from the callee,
1638       // or if the method is virtual, the effects from any possible
1639       // callees, so find the set of callees...
1640       Set<MethodDescriptor> setPossibleCallees;
1641       if( determinismDesired ) {
1642         // use an ordered set
1643         setPossibleCallees = new TreeSet<MethodDescriptor>(dComp);
1644       } else {
1645         // otherwise use a speedy hashset
1646         setPossibleCallees = new HashSet<MethodDescriptor>();
1647       }
1648
1649       if( mdCallee.isStatic() ) {
1650         setPossibleCallees.add(mdCallee);
1651       } else {
1652         TypeDescriptor typeDesc = fc.getThis().getType();
1653         setPossibleCallees.addAll(callGraph.getMethods(mdCallee,
1654                                                        typeDesc)
1655                                   );
1656       }
1657
1658       ReachGraph rgMergeOfPossibleCallers = new ReachGraph();
1659
1660       Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
1661       while( mdItr.hasNext() ) {
1662         MethodDescriptor mdPossible = mdItr.next();
1663         FlatMethod fmPossible = state.getMethodFlat(mdPossible);
1664
1665         addDependent(mdPossible,  // callee
1666                      d);          // caller
1667
1668         // don't alter the working graph (rg) until we compute a
1669         // result for every possible callee, merge them all together,
1670         // then set rg to that
1671         ReachGraph rgPossibleCaller = new ReachGraph();
1672         rgPossibleCaller.merge(rg);
1673
1674         ReachGraph rgPossibleCallee = getPartial(mdPossible);
1675
1676         if( rgPossibleCallee == null ) {
1677           // if this method has never been analyzed just schedule it
1678           // for analysis and skip over this call site for now
1679           if( state.DISJOINTDVISITSTACKEESONTOP ) {
1680             calleesToEnqueue.add(mdPossible);
1681           } else {
1682             enqueue(mdPossible);
1683           }
1684
1685           if( state.DISJOINTDEBUGSCHEDULING ) {
1686             System.out.println("  callee hasn't been analyzed, scheduling: "+mdPossible);
1687           }
1688
1689         } else {
1690           // calculate the method call transform
1691           rgPossibleCaller.resolveMethodCall(fc,
1692                                              fmPossible,
1693                                              rgPossibleCallee,
1694                                              callerNodeIDsCopiedToCallee,
1695                                              writeDebugDOTs
1696                                              );
1697
1698           if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1699 //            if( !rgPossibleCallee.isAccessible( ReachGraph.tdReturn ) ) {
1700             if( !accessible.isAccessible(fn, ReachGraph.tdReturn) ) {
1701               rgPossibleCaller.makeInaccessible(fc.getReturnTemp() );
1702             }
1703           }
1704
1705         }
1706
1707         rgMergeOfPossibleCallers.merge(rgPossibleCaller);
1708       }
1709
1710
1711       if( stopAfter ) {
1712         System.out.println("$$$ Exiting after requested captures of call site. $$$");
1713         System.exit(0);
1714       }
1715
1716
1717       // now that we've taken care of building heap models for
1718       // callee analysis, finish this transformation
1719       rg = rgMergeOfPossibleCallers;
1720
1721
1722       // jjenista: what is this?  It breaks compilation
1723       // of programs with no tasks/SESEs/rblocks...
1724       //XXXXXXXXXXXXXXXXXXXXXXXXX
1725       //need to consider more
1726       FlatNode nextFN=fmCallee.getNext(0);
1727       if( nextFN instanceof FlatSESEEnterNode ) {
1728         FlatSESEEnterNode calleeSESE=(FlatSESEEnterNode)nextFN;
1729         if(!calleeSESE.getIsLeafSESE()) {
1730           rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) );
1731         }
1732       }
1733
1734     } break;
1735
1736
1737     case FKind.FlatReturnNode:
1738       FlatReturnNode frn = (FlatReturnNode) fn;
1739       rhs = frn.getReturnTemp();
1740
1741       // before transfer, do effects analysis support
1742       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1743 //        if(!rg.isAccessible(rhs)){
1744         if(!accessible.isAccessible(fn,rhs)) {
1745           rg.makeInaccessible(ReachGraph.tdReturn);
1746         }
1747       }
1748
1749       if( rhs != null && shouldAnalysisTrack(rhs.getType() ) ) {
1750         rg.assignReturnEqualToTemp(rhs);
1751       }
1752
1753       setRetNodes.add(frn);
1754       break;
1755
1756     } // end switch
1757
1758
1759     // dead variables were removed before the above transfer function
1760     // was applied, so eliminate heap regions and edges that are no
1761     // longer part of the abstractly-live heap graph, and sweep up
1762     // and reachability effects that are altered by the reduction
1763     //rg.abstractGarbageCollect();
1764     //rg.globalSweep();
1765
1766
1767     // back edges are strictly monotonic
1768     if( pm.isBackEdge(fn) ) {
1769       ReachGraph rgPrevResult = mapBackEdgeToMonotone.get(fn);
1770       rg.merge(rgPrevResult);
1771       mapBackEdgeToMonotone.put(fn, rg);
1772     }
1773
1774
1775     ReachGraph rgOnExit = new ReachGraph();
1776     rgOnExit.merge(rg);
1777     fn2rgAtExit.put(fn, rgOnExit);
1778
1779
1780     // at this point rg should be the correct update
1781     // by an above transfer function, or untouched if
1782     // the flat node type doesn't affect the heap
1783     return rg;
1784   }
1785
1786
1787
1788   // this method should generate integers strictly greater than zero!
1789   // special "shadow" regions are made from a heap region by negating
1790   // the ID
1791   static public Integer generateUniqueHeapRegionNodeID() {
1792     ++uniqueIDcount;
1793     return new Integer(uniqueIDcount);
1794   }
1795
1796
1797
1798   static public FieldDescriptor getArrayField(TypeDescriptor tdElement) {
1799     FieldDescriptor fdElement = mapTypeToArrayField.get(tdElement);
1800     if( fdElement == null ) {
1801       fdElement = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC),
1802                                       tdElement,
1803                                       arrayElementFieldName,
1804                                       null,
1805                                       false);
1806       mapTypeToArrayField.put(tdElement, fdElement);
1807     }
1808     return fdElement;
1809   }
1810
1811
1812
1813   private void writeFinalGraphs() {
1814     Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1815     Iterator itr = entrySet.iterator();
1816     while( itr.hasNext() ) {
1817       Map.Entry me = (Map.Entry)itr.next();
1818       Descriptor d = (Descriptor) me.getKey();
1819       ReachGraph rg = (ReachGraph) me.getValue();
1820
1821       String graphName;
1822       if( d instanceof TaskDescriptor ) {
1823         graphName = "COMPLETEtask"+d;
1824       } else {
1825         graphName = "COMPLETE"+d;
1826       }
1827
1828       rg.writeGraph(graphName,
1829                     true,     // write labels (variables)
1830                     true,     // selectively hide intermediate temp vars
1831                     true,     // prune unreachable heap regions
1832                     true,     // hide reachability altogether
1833                     true,     // hide subset reachability states
1834                     true,     // hide predicates
1835                     false);   // hide edge taints
1836     }
1837   }
1838
1839   private void writeFinalIHMs() {
1840     Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1841     while( d2IHMsItr.hasNext() ) {
1842       Map.Entry me1 = (Map.Entry)d2IHMsItr.next();
1843       Descriptor d = (Descriptor)                      me1.getKey();
1844       Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>)me1.getValue();
1845
1846       Iterator fc2rgItr = IHMs.entrySet().iterator();
1847       while( fc2rgItr.hasNext() ) {
1848         Map.Entry me2 = (Map.Entry)fc2rgItr.next();
1849         FlatCall fc  = (FlatCall)   me2.getKey();
1850         ReachGraph rg  = (ReachGraph) me2.getValue();
1851
1852         rg.writeGraph("IHMPARTFOR"+d+"FROM"+fc2enclosing.get(fc)+fc,
1853                       true,    // write labels (variables)
1854                       true,    // selectively hide intermediate temp vars
1855                       true,    // hide reachability altogether
1856                       true,    // prune unreachable heap regions
1857                       true,    // hide subset reachability states
1858                       false,   // hide predicates
1859                       true);   // hide edge taints
1860       }
1861     }
1862   }
1863
1864   private void writeInitialContexts() {
1865     Set entrySet = mapDescriptorToInitialContext.entrySet();
1866     Iterator itr = entrySet.iterator();
1867     while( itr.hasNext() ) {
1868       Map.Entry me = (Map.Entry)itr.next();
1869       Descriptor d = (Descriptor) me.getKey();
1870       ReachGraph rg = (ReachGraph) me.getValue();
1871
1872       rg.writeGraph("INITIAL"+d,
1873                     true,    // write labels (variables)
1874                     true,    // selectively hide intermediate temp vars
1875                     true,    // prune unreachable heap regions
1876                     false,   // hide all reachability
1877                     true,    // hide subset reachability states
1878                     true,    // hide predicates
1879                     false);  // hide edge taints
1880     }
1881   }
1882
1883
1884   protected ReachGraph getPartial(Descriptor d) {
1885     return mapDescriptorToCompleteReachGraph.get(d);
1886   }
1887
1888   protected void setPartial(Descriptor d, ReachGraph rg) {
1889     mapDescriptorToCompleteReachGraph.put(d, rg);
1890
1891     // when the flag for writing out every partial
1892     // result is set, we should spit out the graph,
1893     // but in order to give it a unique name we need
1894     // to track how many partial results for this
1895     // descriptor we've already written out
1896     if( writeAllIncrementalDOTs ) {
1897       if( !mapDescriptorToNumUpdates.containsKey(d) ) {
1898         mapDescriptorToNumUpdates.put(d, new Integer(0) );
1899       }
1900       Integer n = mapDescriptorToNumUpdates.get(d);
1901
1902       String graphName;
1903       if( d instanceof TaskDescriptor ) {
1904         graphName = d+"COMPLETEtask"+String.format("%05d", n);
1905       } else {
1906         graphName = d+"COMPLETE"+String.format("%05d", n);
1907       }
1908
1909       rg.writeGraph(graphName,
1910                     true,    // write labels (variables)
1911                     true,    // selectively hide intermediate temp vars
1912                     true,    // prune unreachable heap regions
1913                     false,   // hide all reachability
1914                     true,    // hide subset reachability states
1915                     false,   // hide predicates
1916                     false);  // hide edge taints
1917
1918       mapDescriptorToNumUpdates.put(d, n + 1);
1919     }
1920   }
1921
1922
1923
1924   // return just the allocation site associated with one FlatNew node
1925   protected AllocSite getAllocSiteFromFlatNewPRIVATE(FlatNew fnew) {
1926
1927     boolean flagProgrammatically = false;
1928     if( sitesToFlag != null && sitesToFlag.contains(fnew) ) {
1929       flagProgrammatically = true;
1930     }
1931
1932     if( !mapFlatNewToAllocSite.containsKey(fnew) ) {
1933       AllocSite as = AllocSite.factory(allocationDepth,
1934                                        fnew,
1935                                        fnew.getDisjointId(),
1936                                        flagProgrammatically
1937                                        );
1938
1939       // the newest nodes are single objects
1940       for( int i = 0; i < allocationDepth; ++i ) {
1941         Integer id = generateUniqueHeapRegionNodeID();
1942         as.setIthOldest(i, id);
1943         mapHrnIdToAllocSite.put(id, as);
1944       }
1945
1946       // the oldest node is a summary node
1947       as.setSummary(generateUniqueHeapRegionNodeID() );
1948
1949       mapFlatNewToAllocSite.put(fnew, as);
1950     }
1951
1952     return mapFlatNewToAllocSite.get(fnew);
1953   }
1954
1955
1956   public static boolean shouldAnalysisTrack(TypeDescriptor type) {
1957     // don't track primitive types, but an array
1958     // of primitives is heap memory
1959     if( type.isImmutable() ) {
1960       return type.isArray();
1961     }
1962
1963     // everything else is an object
1964     return true;
1965   }
1966
1967   protected int numMethodsAnalyzed() {
1968     return descriptorsToAnalyze.size();
1969   }
1970
1971
1972
1973
1974   // Take in source entry which is the program's compiled entry and
1975   // create a new analysis entry, a method that takes no parameters
1976   // and appears to allocate the command line arguments and call the
1977   // source entry with them.  The purpose of this analysis entry is
1978   // to provide a top-level method context with no parameters left.
1979   protected void makeAnalysisEntryMethod(MethodDescriptor mdSourceEntry) {
1980
1981     Modifiers mods = new Modifiers();
1982     mods.addModifier(Modifiers.PUBLIC);
1983     mods.addModifier(Modifiers.STATIC);
1984
1985     TypeDescriptor returnType =
1986       new TypeDescriptor(TypeDescriptor.VOID);
1987
1988     this.mdAnalysisEntry =
1989       new MethodDescriptor(mods,
1990                            returnType,
1991                            "analysisEntryMethod"
1992                            );
1993
1994     TempDescriptor cmdLineArgs =
1995       new TempDescriptor("args",
1996                          mdSourceEntry.getParamType(0)
1997                          );
1998
1999     FlatNew fn =
2000       new FlatNew(mdSourceEntry.getParamType(0),
2001                   cmdLineArgs,
2002                   false  // is global
2003                   );
2004     this.constructedCmdLineArgsNew = fn;
2005
2006     TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
2007     sourceEntryArgs[0] = cmdLineArgs;
2008
2009     FlatCall fc =
2010       new FlatCall(mdSourceEntry,
2011                    null,  // dst temp
2012                    null,  // this temp
2013                    sourceEntryArgs
2014                    );
2015
2016     FlatReturnNode frn = new FlatReturnNode(null);
2017
2018     FlatExit fe = new FlatExit();
2019
2020     this.fmAnalysisEntry =
2021       new FlatMethod(mdAnalysisEntry,
2022                      fe
2023                      );
2024
2025     this.fmAnalysisEntry.addNext(fn);
2026     fn.addNext(fc);
2027     fc.addNext(frn);
2028     frn.addNext(fe);
2029   }
2030
2031
2032   protected LinkedList<Descriptor> topologicalSort(Set<Descriptor> toSort) {
2033
2034     Set<Descriptor> discovered;
2035
2036     if( determinismDesired ) {
2037       // use an ordered set
2038       discovered = new TreeSet<Descriptor>(dComp);
2039     } else {
2040       // otherwise use a speedy hashset
2041       discovered = new HashSet<Descriptor>();
2042     }
2043
2044     LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
2045
2046     Iterator<Descriptor> itr = toSort.iterator();
2047     while( itr.hasNext() ) {
2048       Descriptor d = itr.next();
2049
2050       if( !discovered.contains(d) ) {
2051         dfsVisit(d, toSort, sorted, discovered);
2052       }
2053     }
2054
2055     return sorted;
2056   }
2057
2058   // While we're doing DFS on call graph, remember
2059   // dependencies for efficient queuing of methods
2060   // during interprocedural analysis:
2061   //
2062   // a dependent of a method decriptor d for this analysis is:
2063   //  1) a method or task that invokes d
2064   //  2) in the descriptorsToAnalyze set
2065   protected void dfsVisit(Descriptor d,
2066                           Set       <Descriptor> toSort,
2067                           LinkedList<Descriptor> sorted,
2068                           Set       <Descriptor> discovered) {
2069     discovered.add(d);
2070
2071     // only methods have callers, tasks never do
2072     if( d instanceof MethodDescriptor ) {
2073
2074       MethodDescriptor md = (MethodDescriptor) d;
2075
2076       // the call graph is not aware that we have a fabricated
2077       // analysis entry that calls the program source's entry
2078       if( md == mdSourceEntry ) {
2079         if( !discovered.contains(mdAnalysisEntry) ) {
2080           addDependent(mdSourceEntry,   // callee
2081                        mdAnalysisEntry  // caller
2082                        );
2083           dfsVisit(mdAnalysisEntry, toSort, sorted, discovered);
2084         }
2085       }
2086
2087       // otherwise call graph guides DFS
2088       Iterator itr = callGraph.getCallerSet(md).iterator();
2089       while( itr.hasNext() ) {
2090         Descriptor dCaller = (Descriptor) itr.next();
2091
2092         // only consider callers in the original set to analyze
2093         if( !toSort.contains(dCaller) ) {
2094           continue;
2095         }
2096
2097         if( !discovered.contains(dCaller) ) {
2098           addDependent(md,      // callee
2099                        dCaller  // caller
2100                        );
2101
2102           dfsVisit(dCaller, toSort, sorted, discovered);
2103         }
2104       }
2105     }
2106
2107     // for leaf-nodes last now!
2108     sorted.addLast(d);
2109   }
2110
2111
2112   protected void enqueue(Descriptor d) {
2113
2114     if( !descriptorsToVisitSet.contains(d) ) {
2115
2116       if( state.DISJOINTDVISITSTACK ||
2117           state.DISJOINTDVISITSTACKEESONTOP
2118           ) {
2119         descriptorsToVisitStack.add(d);
2120
2121       } else if( state.DISJOINTDVISITPQUE ) {
2122         Integer priority = mapDescriptorToPriority.get(d);
2123         descriptorsToVisitQ.add(new DescriptorQWrapper(priority,
2124                                                        d)
2125                                 );
2126       }
2127
2128       descriptorsToVisitSet.add(d);
2129     }
2130   }
2131
2132
2133   // a dependent of a method decriptor d for this analysis is:
2134   //  1) a method or task that invokes d
2135   //  2) in the descriptorsToAnalyze set
2136   protected void addDependent(Descriptor callee, Descriptor caller) {
2137     Set<Descriptor> deps = mapDescriptorToSetDependents.get(callee);
2138     if( deps == null ) {
2139       deps = new HashSet<Descriptor>();
2140     }
2141     deps.add(caller);
2142     mapDescriptorToSetDependents.put(callee, deps);
2143   }
2144
2145   protected Set<Descriptor> getDependents(Descriptor callee) {
2146     Set<Descriptor> deps = mapDescriptorToSetDependents.get(callee);
2147     if( deps == null ) {
2148       deps = new HashSet<Descriptor>();
2149       mapDescriptorToSetDependents.put(callee, deps);
2150     }
2151     return deps;
2152   }
2153
2154
2155   public Hashtable<FlatCall, ReachGraph> getIHMcontributions(Descriptor d) {
2156
2157     Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2158       mapDescriptorToIHMcontributions.get(d);
2159
2160     if( heapsFromCallers == null ) {
2161       heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
2162       mapDescriptorToIHMcontributions.put(d, heapsFromCallers);
2163     }
2164
2165     return heapsFromCallers;
2166   }
2167
2168   public ReachGraph getIHMcontribution(Descriptor d,
2169                                        FlatCall fc
2170                                        ) {
2171     Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2172       getIHMcontributions(d);
2173
2174     if( !heapsFromCallers.containsKey(fc) ) {
2175       return null;
2176     }
2177
2178     return heapsFromCallers.get(fc);
2179   }
2180
2181
2182   public void addIHMcontribution(Descriptor d,
2183                                  FlatCall fc,
2184                                  ReachGraph rg
2185                                  ) {
2186     Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2187       getIHMcontributions(d);
2188
2189     heapsFromCallers.put(fc, rg);
2190   }
2191
2192
2193   private AllocSite createParameterAllocSite(ReachGraph rg,
2194                                              TempDescriptor tempDesc,
2195                                              boolean flagRegions
2196                                              ) {
2197
2198     FlatNew flatNew;
2199     if( flagRegions ) {
2200       flatNew = new FlatNew(tempDesc.getType(),  // type
2201                             tempDesc,            // param temp
2202                             false,               // global alloc?
2203                             "param"+tempDesc     // disjoint site ID string
2204                             );
2205     } else {
2206       flatNew = new FlatNew(tempDesc.getType(),  // type
2207                             tempDesc,            // param temp
2208                             false,               // global alloc?
2209                             null                 // disjoint site ID string
2210                             );
2211     }
2212
2213     // create allocation site
2214     AllocSite as = AllocSite.factory(allocationDepth,
2215                                      flatNew,
2216                                      flatNew.getDisjointId(),
2217                                      false
2218                                      );
2219     for (int i = 0; i < allocationDepth; ++i) {
2220       Integer id = generateUniqueHeapRegionNodeID();
2221       as.setIthOldest(i, id);
2222       mapHrnIdToAllocSite.put(id, as);
2223     }
2224     // the oldest node is a summary node
2225     as.setSummary(generateUniqueHeapRegionNodeID() );
2226
2227     rg.age(as);
2228
2229     return as;
2230
2231   }
2232
2233   private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc) {
2234
2235     Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
2236     if(!typeDesc.isImmutable()) {
2237       ClassDescriptor classDesc = typeDesc.getClassDesc();
2238       for (Iterator it = classDesc.getFields(); it.hasNext(); ) {
2239         FieldDescriptor field = (FieldDescriptor) it.next();
2240         TypeDescriptor fieldType = field.getType();
2241         if (shouldAnalysisTrack(fieldType)) {
2242           fieldSet.add(field);
2243         }
2244       }
2245     }
2246     return fieldSet;
2247
2248   }
2249
2250   private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha) {
2251
2252     int dimCount=fd.getType().getArrayCount();
2253     HeapRegionNode prevNode=null;
2254     HeapRegionNode arrayEntryNode=null;
2255     for(int i=dimCount; i>0; i--) {
2256       TypeDescriptor typeDesc=fd.getType().dereference();          //hack to get instance of type desc
2257       typeDesc.setArrayCount(i);
2258       TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
2259       HeapRegionNode hrnSummary;
2260       if(!mapToExistingNode.containsKey(typeDesc)) {
2261         AllocSite as;
2262         if(i==dimCount) {
2263           as = alloc;
2264         } else {
2265           as = createParameterAllocSite(rg, tempDesc, false);
2266         }
2267         // make a new reference to allocated node
2268         hrnSummary =
2269           rg.createNewHeapRegionNode(as.getSummary(),                       // id or null to generate a new one
2270                                      false,                       // single object?
2271                                      true,                       // summary?
2272                                      false,                       // out-of-context?
2273                                      as.getType(),                       // type
2274                                      as,                       // allocation site
2275                                      alpha,                       // inherent reach
2276                                      alpha,                       // current reach
2277                                      ExistPredSet.factory(rg.predTrue),                       // predicates
2278                                      tempDesc.toString()                       // description
2279                                      );
2280         rg.id2hrn.put(as.getSummary(),hrnSummary);
2281
2282         mapToExistingNode.put(typeDesc, hrnSummary);
2283       } else {
2284         hrnSummary=mapToExistingNode.get(typeDesc);
2285       }
2286
2287       if(prevNode==null) {
2288         // make a new reference between new summary node and source
2289         RefEdge edgeToSummary = new RefEdge(srcHRN,       // source
2290                                             hrnSummary,             // dest
2291                                             typeDesc,             // type
2292                                             fd.getSymbol(),             // field name
2293                                             alpha,             // beta
2294                                             ExistPredSet.factory(rg.predTrue),       // predicates
2295                                             null
2296                                             );
2297
2298         rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2299         prevNode=hrnSummary;
2300         arrayEntryNode=hrnSummary;
2301       } else {
2302         // make a new reference between summary nodes of array
2303         RefEdge edgeToSummary = new RefEdge(prevNode,             // source
2304                                             hrnSummary,             // dest
2305                                             typeDesc,             // type
2306                                             arrayElementFieldName,             // field name
2307                                             alpha,             // beta
2308                                             ExistPredSet.factory(rg.predTrue),             // predicates
2309                                             null
2310                                             );
2311
2312         rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2313         prevNode=hrnSummary;
2314       }
2315
2316     }
2317
2318     // create a new obj node if obj has at least one non-primitive field
2319     TypeDescriptor type=fd.getType();
2320     if(getFieldSetTobeAnalyzed(type).size()>0) {
2321       TypeDescriptor typeDesc=type.dereference();
2322       typeDesc.setArrayCount(0);
2323       if(!mapToExistingNode.containsKey(typeDesc)) {
2324         TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
2325         AllocSite as = createParameterAllocSite(rg, tempDesc, false);
2326         // make a new reference to allocated node
2327         HeapRegionNode hrnSummary =
2328           rg.createNewHeapRegionNode(as.getSummary(),                       // id or null to generate a new one
2329                                      false,                       // single object?
2330                                      true,                       // summary?
2331                                      false,                       // out-of-context?
2332                                      typeDesc,                       // type
2333                                      as,                       // allocation site
2334                                      alpha,                       // inherent reach
2335                                      alpha,                       // current reach
2336                                      ExistPredSet.factory(rg.predTrue),                       // predicates
2337                                      tempDesc.toString()                       // description
2338                                      );
2339         rg.id2hrn.put(as.getSummary(),hrnSummary);
2340         mapToExistingNode.put(typeDesc, hrnSummary);
2341         RefEdge edgeToSummary = new RefEdge(prevNode,             // source
2342                                             hrnSummary, // dest
2343                                             typeDesc, // type
2344                                             arrayElementFieldName, // field name
2345                                             alpha, // beta
2346                                             ExistPredSet.factory(rg.predTrue),             // predicates
2347                                             null
2348                                             );
2349         rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2350         prevNode=hrnSummary;
2351       } else {
2352         HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
2353         if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null) {
2354           RefEdge edgeToSummary = new RefEdge(prevNode,               // source
2355                                               hrnSummary, // dest
2356                                               typeDesc, // type
2357                                               arrayElementFieldName, // field name
2358                                               alpha, // beta
2359                                               ExistPredSet.factory(rg.predTrue),               // predicates
2360                                               null
2361                                               );
2362           rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2363         }
2364         prevNode=hrnSummary;
2365       }
2366     }
2367
2368     map.put(arrayEntryNode, prevNode);
2369     return arrayEntryNode;
2370   }
2371
2372   private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
2373     ReachGraph rg = new ReachGraph();
2374     TaskDescriptor taskDesc = fm.getTask();
2375
2376     for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
2377       Descriptor paramDesc = taskDesc.getParameter(idx);
2378       TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
2379
2380       // setup data structure
2381       Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
2382         new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
2383       Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
2384         new Hashtable<TypeDescriptor, HeapRegionNode>();
2385       Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
2386         new Hashtable<HeapRegionNode, HeapRegionNode>();
2387       Set<String> doneSet = new HashSet<String>();
2388
2389       TempDescriptor tempDesc = fm.getParameter(idx);
2390
2391       AllocSite as = createParameterAllocSite(rg, tempDesc, true);
2392       VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
2393       Integer idNewest = as.getIthOldest(0);
2394       HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
2395
2396       // make a new reference to allocated node
2397       RefEdge edgeNew = new RefEdge(lnX,   // source
2398                                     hrnNewest,   // dest
2399                                     taskDesc.getParamType(idx),   // type
2400                                     null,   // field name
2401                                     hrnNewest.getAlpha(),   // beta
2402                                     ExistPredSet.factory(rg.predTrue),   // predicates
2403                                     null
2404                                     );
2405       rg.addRefEdge(lnX, hrnNewest, edgeNew);
2406
2407       // set-up a work set for class field
2408       ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
2409       for (Iterator it = classDesc.getFields(); it.hasNext(); ) {
2410         FieldDescriptor fd = (FieldDescriptor) it.next();
2411         TypeDescriptor fieldType = fd.getType();
2412         if (shouldAnalysisTrack(fieldType)) {
2413           HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
2414           newMap.put(hrnNewest, fd);
2415           workSet.add(newMap);
2416         }
2417       }
2418
2419       int uniqueIdentifier = 0;
2420       while (!workSet.isEmpty()) {
2421         HashMap<HeapRegionNode, FieldDescriptor> map = workSet
2422                                                        .iterator().next();
2423         workSet.remove(map);
2424
2425         Set<HeapRegionNode> key = map.keySet();
2426         HeapRegionNode srcHRN = key.iterator().next();
2427         FieldDescriptor fd = map.get(srcHRN);
2428         TypeDescriptor type = fd.getType();
2429         String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
2430
2431         if (!doneSet.contains(doneSetIdentifier)) {
2432           doneSet.add(doneSetIdentifier);
2433           if (!mapTypeToExistingSummaryNode.containsKey(type)) {
2434             // create new summary Node
2435             TempDescriptor td = new TempDescriptor("temp"
2436                                                    + uniqueIdentifier, type);
2437
2438             AllocSite allocSite;
2439             if(type.equals(paramTypeDesc)) {
2440               //corresponding allocsite has already been created for a parameter variable.
2441               allocSite=as;
2442             } else {
2443               allocSite = createParameterAllocSite(rg, td, false);
2444             }
2445             String strDesc = allocSite.toStringForDOT()
2446                              + "\\nsummary";
2447             TypeDescriptor allocType=allocSite.getType();
2448
2449             HeapRegionNode hrnSummary;
2450             if(allocType.isArray() && allocType.getArrayCount()>0) {
2451               hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
2452             } else {
2453               hrnSummary =
2454                 rg.createNewHeapRegionNode(allocSite.getSummary(),                         // id or null to generate a new one
2455                                            false,                         // single object?
2456                                            true,                         // summary?
2457                                            false,                         // out-of-context?
2458                                            allocSite.getType(),                         // type
2459                                            allocSite,                         // allocation site
2460                                            hrnNewest.getAlpha(),                         // inherent reach
2461                                            hrnNewest.getAlpha(),                         // current reach
2462                                            ExistPredSet.factory(rg.predTrue),                         // predicates
2463                                            strDesc                         // description
2464                                            );
2465               rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
2466
2467               // make a new reference to summary node
2468               RefEdge edgeToSummary = new RefEdge(srcHRN,       // source
2469                                                   hrnSummary,       // dest
2470                                                   type,       // type
2471                                                   fd.getSymbol(),       // field name
2472                                                   hrnNewest.getAlpha(),       // beta
2473                                                   ExistPredSet.factory(rg.predTrue),       // predicates
2474                                                   null
2475                                                   );
2476
2477               rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2478             }
2479             uniqueIdentifier++;
2480
2481             mapTypeToExistingSummaryNode.put(type, hrnSummary);
2482
2483             // set-up a work set for  fields of the class
2484             Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
2485             for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
2486                  .hasNext(); ) {
2487               FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
2488                                                 .next();
2489               HeapRegionNode newDstHRN;
2490               if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)) {
2491                 //related heap region node is already exsited.
2492                 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
2493               } else {
2494                 newDstHRN=hrnSummary;
2495               }
2496               doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
2497               if(!doneSet.contains(doneSetIdentifier)) {
2498                 // add new work item
2499                 HashMap<HeapRegionNode, FieldDescriptor> newMap =
2500                   new HashMap<HeapRegionNode, FieldDescriptor>();
2501                 newMap.put(newDstHRN, fieldDescriptor);
2502                 workSet.add(newMap);
2503               }
2504             }
2505
2506           } else {
2507             // if there exists corresponding summary node
2508             HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
2509
2510             RefEdge edgeToSummary = new RefEdge(srcHRN,         // source
2511                                                 hrnDst,         // dest
2512                                                 fd.getType(),         // type
2513                                                 fd.getSymbol(),         // field name
2514                                                 srcHRN.getAlpha(),         // beta
2515                                                 ExistPredSet.factory(rg.predTrue),         // predicates
2516                                                 null
2517                                                 );
2518             rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
2519
2520           }
2521         }
2522       }
2523     }
2524
2525     return rg;
2526   }
2527
2528 // return all allocation sites in the method (there is one allocation
2529 // site per FlatNew node in a method)
2530   private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
2531     if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
2532       buildAllocationSiteSet(d);
2533     }
2534
2535     return mapDescriptorToAllocSiteSet.get(d);
2536
2537   }
2538
2539   private void buildAllocationSiteSet(Descriptor d) {
2540     HashSet<AllocSite> s = new HashSet<AllocSite>();
2541
2542     FlatMethod fm;
2543     if( d instanceof MethodDescriptor ) {
2544       fm = state.getMethodFlat( (MethodDescriptor) d);
2545     } else {
2546       assert d instanceof TaskDescriptor;
2547       fm = state.getMethodFlat( (TaskDescriptor) d);
2548     }
2549     pm.analyzeMethod(fm);
2550
2551     // visit every node in this FlatMethod's IR graph
2552     // and make a set of the allocation sites from the
2553     // FlatNew node's visited
2554     HashSet<FlatNode> visited = new HashSet<FlatNode>();
2555     HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
2556     toVisit.add(fm);
2557
2558     while( !toVisit.isEmpty() ) {
2559       FlatNode n = toVisit.iterator().next();
2560
2561       if( n instanceof FlatNew ) {
2562         s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
2563       }
2564
2565       toVisit.remove(n);
2566       visited.add(n);
2567
2568       for( int i = 0; i < pm.numNext(n); ++i ) {
2569         FlatNode child = pm.getNext(n, i);
2570         if( !visited.contains(child) ) {
2571           toVisit.add(child);
2572         }
2573       }
2574     }
2575
2576     mapDescriptorToAllocSiteSet.put(d, s);
2577   }
2578
2579   private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
2580
2581     HashSet<AllocSite> out = new HashSet<AllocSite>();
2582     HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2583     HashSet<Descriptor> visited = new HashSet<Descriptor>();
2584
2585     toVisit.add(dIn);
2586
2587     while (!toVisit.isEmpty()) {
2588       Descriptor d = toVisit.iterator().next();
2589       toVisit.remove(d);
2590       visited.add(d);
2591
2592       HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2593       Iterator asItr = asSet.iterator();
2594       while (asItr.hasNext()) {
2595         AllocSite as = (AllocSite) asItr.next();
2596         if (as.getDisjointAnalysisId() != null) {
2597           out.add(as);
2598         }
2599       }
2600
2601       // enqueue callees of this method to be searched for
2602       // allocation sites also
2603       Set callees = callGraph.getCalleeSet(d);
2604       if (callees != null) {
2605         Iterator methItr = callees.iterator();
2606         while (methItr.hasNext()) {
2607           MethodDescriptor md = (MethodDescriptor) methItr.next();
2608
2609           if (!visited.contains(md)) {
2610             toVisit.add(md);
2611           }
2612         }
2613       }
2614     }
2615
2616     return out;
2617   }
2618
2619
2620   private HashSet<AllocSite>
2621   getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
2622
2623     HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
2624     HashSet<Descriptor>     toVisit    = new HashSet<Descriptor>();
2625     HashSet<Descriptor>     visited    = new HashSet<Descriptor>();
2626
2627     toVisit.add(td);
2628
2629     // traverse this task and all methods reachable from this task
2630     while( !toVisit.isEmpty() ) {
2631       Descriptor d = toVisit.iterator().next();
2632       toVisit.remove(d);
2633       visited.add(d);
2634
2635       HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2636       Iterator asItr = asSet.iterator();
2637       while( asItr.hasNext() ) {
2638         AllocSite as = (AllocSite) asItr.next();
2639         TypeDescriptor typed = as.getType();
2640         if( typed != null ) {
2641           ClassDescriptor cd = typed.getClassDesc();
2642           if( cd != null && cd.hasFlags() ) {
2643             asSetTotal.add(as);
2644           }
2645         }
2646       }
2647
2648       // enqueue callees of this method to be searched for
2649       // allocation sites also
2650       Set callees = callGraph.getCalleeSet(d);
2651       if( callees != null ) {
2652         Iterator methItr = callees.iterator();
2653         while( methItr.hasNext() ) {
2654           MethodDescriptor md = (MethodDescriptor) methItr.next();
2655
2656           if( !visited.contains(md) ) {
2657             toVisit.add(md);
2658           }
2659         }
2660       }
2661     }
2662
2663     return asSetTotal;
2664   }
2665
2666   public Set<Descriptor> getDescriptorsToAnalyze() {
2667     return descriptorsToAnalyze;
2668   }
2669
2670   public EffectsAnalysis getEffectsAnalysis() {
2671     return effectsAnalysis;
2672   }
2673
2674   public ReachGraph getReachGraph(Descriptor d) {
2675     return mapDescriptorToCompleteReachGraph.get(d);
2676   }
2677
2678   public ReachGraph getEnterReachGraph(FlatNode fn) {
2679     return fn2rgAtEnter.get(fn);
2680   }
2681
2682   // get successive captures of the analysis state, use compiler
2683   // flags to control
2684   boolean takeDebugSnapshots = false;
2685   String descSymbolDebug    = null;
2686   boolean stopAfterCapture   = false;
2687   int snapVisitCounter   = 0;
2688   int snapNodeCounter    = 0;
2689   int visitStartCapture  = 0;
2690   int numVisitsToCapture = 0;
2691
2692
2693   void debugSnapshot(ReachGraph rg, FlatNode fn, boolean in) {
2694     if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2695       return;
2696     }
2697
2698     if( in ) {
2699
2700     }
2701
2702     if( snapVisitCounter >= visitStartCapture ) {
2703       System.out.println("    @@@ snapping visit="+snapVisitCounter+
2704                          ", node="+snapNodeCounter+
2705                          " @@@");
2706       String graphName;
2707       if( in ) {
2708         graphName = String.format("snap%03d_%04din",
2709                                   snapVisitCounter,
2710                                   snapNodeCounter);
2711       } else {
2712         graphName = String.format("snap%03d_%04dout",
2713                                   snapVisitCounter,
2714                                   snapNodeCounter);
2715       }
2716       if( fn != null ) {
2717         graphName = graphName + fn;
2718       }
2719       rg.writeGraph(graphName,
2720                     true,    // write labels (variables)
2721                     true,    // selectively hide intermediate temp vars
2722                     true,    // prune unreachable heap regions
2723                     false,   // hide reachability
2724                     false,   // hide subset reachability states
2725                     true,    // hide predicates
2726                     true);   // hide edge taints
2727     }
2728   }
2729
2730
2731
2732
2733   public Set<Alloc> canPointToAt( TempDescriptor x,
2734                                   FlatNode programPoint ) {
2735
2736     ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
2737     if( rgAtEnter == null ) {
2738       return null; 
2739     }
2740
2741     return rgAtEnter.canPointTo( x );
2742   }
2743
2744
2745   public Set<Alloc> canPointToAfter( TempDescriptor x,
2746                                      FlatNode programPoint ) {
2747
2748     ReachGraph rgAtExit = fn2rgAtExit.get( programPoint );
2749     if( rgAtExit == null ) {
2750       return null; 
2751     }
2752
2753     return rgAtExit.canPointTo( x );
2754   }
2755   
2756
2757   public Hashtable< Alloc, Set<Alloc> > canPointToAt( TempDescriptor x,
2758                                                       FieldDescriptor f,
2759                                                       FlatNode programPoint ) {
2760
2761     ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
2762     if( rgAtEnter == null ) {
2763       return null; 
2764     }
2765     
2766     return rgAtEnter.canPointTo( x, f.getSymbol() );
2767   }
2768
2769
2770   public Hashtable< Alloc, Set<Alloc> > canPointToAtElement( TempDescriptor x,
2771                                                              FlatNode programPoint ) {
2772
2773     ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
2774     if( rgAtEnter == null ) {
2775       return null; 
2776     }
2777
2778     assert x.getType() != null;
2779     assert x.getType().isArray();
2780
2781     return rgAtEnter.canPointTo( x, arrayElementFieldName );
2782   }
2783 }