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