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