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