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