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