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