more implementation
[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 IR.*;
7 import IR.Flat.*;
8 import IR.Tree.Modifiers;
9 import java.util.*;
10 import java.io.*;
11
12
13 public class DisjointAnalysis {
14
15
16   // data from the compiler
17   public State            state;
18   public CallGraph        callGraph;
19   public Liveness         liveness;
20   public ArrayReferencees arrayReferencees;
21   public TypeUtil         typeUtil;
22   public int              allocationDepth;
23
24
25   // used to identify HeapRegionNode objects
26   // A unique ID equates an object in one
27   // ownership graph with an object in another
28   // graph that logically represents the same
29   // heap region
30   // start at 10 and increment to reserve some
31   // IDs for special purposes
32   static protected int uniqueIDcount = 10;
33
34
35   // An out-of-scope method created by the
36   // analysis that has no parameters, and
37   // appears to allocate the command line
38   // arguments, then invoke the source code's
39   // main method.  The purpose of this is to
40   // provide the analysis with an explicit
41   // top-level context with no parameters
42   protected MethodDescriptor mdAnalysisEntry;
43   protected FlatMethod       fmAnalysisEntry;
44
45   // main method defined by source program
46   protected MethodDescriptor mdSourceEntry;
47
48   // the set of task and/or method descriptors
49   // reachable in call graph
50   protected Set<Descriptor> 
51     descriptorsToAnalyze;
52
53   // current descriptors to visit in fixed-point
54   // interprocedural analysis, prioritized by
55   // dependency in the call graph
56   protected PriorityQueue<DescriptorQWrapper> 
57     descriptorsToVisitQ;
58   
59   // a duplication of the above structure, but
60   // for efficient testing of inclusion
61   protected HashSet<Descriptor> 
62     descriptorsToVisitSet;
63
64   // storage for priorities (doesn't make sense)
65   // to add it to the Descriptor class, just in
66   // this analysis
67   protected Hashtable<Descriptor, Integer> 
68     mapDescriptorToPriority;
69
70
71   // maps a descriptor to its current partial result
72   // from the intraprocedural fixed-point analysis--
73   // then the interprocedural analysis settles, this
74   // mapping will have the final results for each
75   // method descriptor
76   protected Hashtable<Descriptor, ReachGraph> 
77     mapDescriptorToCompleteReachGraph;
78
79   // maps a descriptor to its known dependents: namely
80   // methods or tasks that call the descriptor's method
81   // AND are part of this analysis (reachable from main)
82   protected Hashtable< Descriptor, Set<Descriptor> >
83     mapDescriptorToSetDependents;
84
85   // maps each flat new to one analysis abstraction
86   // allocate site object, these exist outside reach graphs
87   protected Hashtable<FlatNew, AllocSite>
88     mapFlatNewToAllocSite;
89
90   // maps intergraph heap region IDs to intergraph
91   // allocation sites that created them, a redundant
92   // structure for efficiency in some operations
93   protected Hashtable<Integer, AllocSite>
94     mapHrnIdToAllocSite;
95
96   // maps a method to its initial heap model (IHM) that
97   // is the set of reachability graphs from every caller
98   // site, all merged together.  The reason that we keep
99   // them separate is that any one call site's contribution
100   // to the IHM may changed along the path to the fixed point
101   protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
102     mapDescriptorToIHMcontributions;
103
104   // TODO -- CHANGE EDGE/TYPE/FIELD storage!
105   public static final String arrayElementFieldName = "___element_";
106   static protected Hashtable<TypeDescriptor, FieldDescriptor>
107     mapTypeToArrayField;
108
109   // for controlling DOT file output
110   protected boolean writeFinalDOTs;
111   protected boolean writeAllIncrementalDOTs;
112
113   // supporting DOT output--when we want to write every
114   // partial method result, keep a tally for generating
115   // unique filenames
116   protected Hashtable<Descriptor, Integer>
117     mapDescriptorToNumUpdates;
118
119
120   // allocate various structures that are not local
121   // to a single class method--should be done once
122   protected void allocateStructures() {    
123     descriptorsToAnalyze = new HashSet<Descriptor>();
124
125     mapDescriptorToCompleteReachGraph =
126       new Hashtable<Descriptor, ReachGraph>();
127
128     mapDescriptorToNumUpdates =
129       new Hashtable<Descriptor, Integer>();
130
131     mapDescriptorToSetDependents =
132       new Hashtable< Descriptor, Set<Descriptor> >();
133
134     mapFlatNewToAllocSite = 
135       new Hashtable<FlatNew, AllocSite>();
136
137     mapDescriptorToIHMcontributions =
138       new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
139
140     mapHrnIdToAllocSite =
141       new Hashtable<Integer, AllocSite>();
142
143     mapTypeToArrayField = 
144       new Hashtable <TypeDescriptor, FieldDescriptor>();
145
146     descriptorsToVisitQ =
147       new PriorityQueue<DescriptorQWrapper>();
148
149     descriptorsToVisitSet =
150       new HashSet<Descriptor>();
151
152     mapDescriptorToPriority =
153       new Hashtable<Descriptor, Integer>();
154   }
155
156
157
158   // this analysis generates a disjoint reachability
159   // graph for every reachable method in the program
160   public DisjointAnalysis( State s,
161                            TypeUtil tu,
162                            CallGraph cg,
163                            Liveness l,
164                            ArrayReferencees ar
165                            ) throws java.io.IOException {
166     init( s, tu, cg, l, ar );
167   }
168   
169   protected void init( State state,
170                        TypeUtil typeUtil,
171                        CallGraph callGraph,
172                        Liveness liveness,
173                        ArrayReferencees arrayReferencees
174                        ) throws java.io.IOException {
175     
176     this.state                   = state;
177     this.typeUtil                = typeUtil;
178     this.callGraph               = callGraph;
179     this.liveness                = liveness;
180     this.arrayReferencees        = arrayReferencees;
181     this.allocationDepth         = state.DISJOINTALLOCDEPTH;
182     this.writeFinalDOTs          = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
183     this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS &&  state.DISJOINTWRITEALL;
184             
185     // set some static configuration for ReachGraphs
186     ReachGraph.allocationDepth = allocationDepth;
187     ReachGraph.typeUtil        = typeUtil;
188
189     allocateStructures();
190
191     double timeStartAnalysis = (double) System.nanoTime();
192
193     // start interprocedural fixed-point computation
194     analyzeMethods();
195
196     double timeEndAnalysis = (double) System.nanoTime();
197     double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
198     String treport = String.format( "The reachability analysis took %.3f sec.", dt );
199     String justtime = String.format( "%.2f", dt );
200     System.out.println( treport );
201
202     if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
203       writeFinalGraphs();      
204     }  
205
206     if( state.DISJOINTALIASFILE != null ) {
207       if( state.TASK ) {
208         // not supporting tasks yet...
209       } else {
210         /*
211         writeAllAliasesJava( aliasFile, 
212                              treport, 
213                              justtime, 
214                              state.DISJOINTALIASTAB, 
215                              state.lines );
216         */
217       }
218     }
219   }
220
221
222   // fixed-point computation over the call graph--when a
223   // method's callees are updated, it must be reanalyzed
224   protected void analyzeMethods() throws java.io.IOException {  
225
226     if( state.TASK ) {
227       // This analysis does not support Bamboo at the moment,
228       // but if it does in the future we would initialize the
229       // set of descriptors to analyze as the program-reachable
230       // tasks and the methods callable by them.  For Java,
231       // just methods reachable from the main method.
232       System.out.println( "No Bamboo support yet..." );
233       System.exit( -1 );
234
235     } else {
236       // add all methods transitively reachable from the
237       // source's main to set for analysis
238       mdSourceEntry = typeUtil.getMain();
239       descriptorsToAnalyze.add( mdSourceEntry );
240       descriptorsToAnalyze.addAll( 
241         callGraph.getAllMethods( mdSourceEntry ) 
242                                    );
243
244       // fabricate an empty calling context that will call
245       // the source's main, but call graph doesn't know
246       // about it, so explicitly add it
247       makeAnalysisEntryMethod( mdSourceEntry );
248       descriptorsToAnalyze.add( mdAnalysisEntry );
249     }
250
251     // topologically sort according to the call graph so 
252     // leaf calls are ordered first, smarter analysis order
253     LinkedList<Descriptor> sortedDescriptors = 
254       topologicalSort( descriptorsToAnalyze );
255
256     // add sorted descriptors to priority queue, and duplicate
257     // the queue as a set for efficiently testing whether some
258     // method is marked for analysis
259     int p = 0;
260     Iterator<Descriptor> dItr = sortedDescriptors.iterator();
261     while( dItr.hasNext() ) {
262       Descriptor d = dItr.next();
263       mapDescriptorToPriority.put( d, new Integer( p ) );
264       descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
265       descriptorsToVisitSet.add( d );
266       ++p;
267     }
268
269     // analyze methods from the priority queue until it is empty
270     while( !descriptorsToVisitQ.isEmpty() ) {
271       Descriptor d = descriptorsToVisitQ.poll().getDescriptor();
272       assert descriptorsToVisitSet.contains( d );
273       descriptorsToVisitSet.remove( d );
274
275       // because the task or method descriptor just extracted
276       // was in the "to visit" set it either hasn't been analyzed
277       // yet, or some method that it depends on has been
278       // updated.  Recompute a complete reachability graph for
279       // this task/method and compare it to any previous result.
280       // If there is a change detected, add any methods/tasks
281       // that depend on this one to the "to visit" set.
282
283       System.out.println( "Analyzing " + d );
284
285       ReachGraph rg     = analyzeMethod( d );
286       ReachGraph rgPrev = getPartial( d );
287
288       if( !rg.equals( rgPrev ) ) {
289         setPartial( d, rg );
290
291         // results for d changed, so enqueue dependents
292         // of d for further analysis
293         Iterator<Descriptor> depsItr = getDependents( d ).iterator();
294         while( depsItr.hasNext() ) {
295           Descriptor dNext = depsItr.next();
296           enqueue( dNext );
297         }
298       }      
299     }
300   }
301
302
303   protected ReachGraph analyzeMethod( Descriptor d ) 
304     throws java.io.IOException {
305
306     // get the flat code for this descriptor
307     FlatMethod fm;
308     if( d == mdAnalysisEntry ) {
309       fm = fmAnalysisEntry;
310     } else {
311       fm = state.getMethodFlat( d );
312     }
313       
314     // intraprocedural work set
315     Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
316     flatNodesToVisit.add( fm );
317     
318     // mapping of current partial results
319     Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
320       new Hashtable<FlatNode, ReachGraph>();
321
322     // the set of return nodes partial results that will be combined as
323     // the final, conservative approximation of the entire method
324     HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
325
326     while( !flatNodesToVisit.isEmpty() ) {
327       FlatNode fn = (FlatNode) flatNodesToVisit.iterator().next();
328       flatNodesToVisit.remove( fn );
329
330       //System.out.println( "  "+fn );
331
332       // effect transfer function defined by this node,
333       // then compare it to the old graph at this node
334       // to see if anything was updated.
335
336       ReachGraph rg = new ReachGraph();
337
338       // start by merging all node's parents' graphs
339       for( int i = 0; i < fn.numPrev(); ++i ) {
340         FlatNode pn = fn.getPrev( i );
341         if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
342           ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
343           rg.merge( rgParent );
344         }
345       }
346
347       // modify rg with appropriate transfer function
348       analyzeFlatNode( d, fm, fn, setReturns, rg );
349           
350       /*
351       if( takeDebugSnapshots && 
352           d.getSymbol().equals( descSymbolDebug ) ) {
353         debugSnapshot(og,fn);
354       }
355       */
356
357       // if the results of the new graph are different from
358       // the current graph at this node, replace the graph
359       // with the update and enqueue the children
360       ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
361       if( !rg.equals( rgPrev ) ) {
362         mapFlatNodeToReachGraph.put( fn, rg );
363
364         for( int i = 0; i < fn.numNext(); i++ ) {
365           FlatNode nn = fn.getNext( i );
366           flatNodesToVisit.add( nn );
367         }
368       }
369     }
370
371     // end by merging all return nodes into a complete
372     // ownership graph that represents all possible heap
373     // states after the flat method returns
374     ReachGraph completeGraph = new ReachGraph();
375
376     assert !setReturns.isEmpty();
377     Iterator retItr = setReturns.iterator();
378     while( retItr.hasNext() ) {
379       FlatReturnNode frn = (FlatReturnNode) retItr.next();
380
381       assert mapFlatNodeToReachGraph.containsKey( frn );
382       ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
383
384       completeGraph.merge( rgRet );
385     }
386     
387     return completeGraph;
388   }
389
390   
391   protected void
392     analyzeFlatNode( Descriptor              d,
393                      FlatMethod              fmContaining,
394                      FlatNode                fn,
395                      HashSet<FlatReturnNode> setRetNodes,
396                      ReachGraph              rg
397                      ) throws java.io.IOException {
398
399     
400     // any variables that are no longer live should be
401     // nullified in the graph to reduce edges
402     // NOTE: it is not clear we need this.  It costs a
403     // liveness calculation for every method, so only
404     // turn it on if we find we actually need it.
405     // rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
406
407           
408     TempDescriptor  lhs;
409     TempDescriptor  rhs;
410     FieldDescriptor fld;
411
412     // use node type to decide what transfer function
413     // to apply to the reachability graph
414     switch( fn.kind() ) {
415
416     case FKind.FlatMethod: {
417       // construct this method's initial heap model (IHM)
418       // since we're working on the FlatMethod, we know
419       // the incoming ReachGraph 'rg' is empty
420
421       Hashtable<FlatCall, ReachGraph> heapsFromCallers = 
422         getIHMcontributions( d );
423
424       Set entrySet = heapsFromCallers.entrySet();
425       Iterator itr = entrySet.iterator();
426       while( itr.hasNext() ) {
427         Map.Entry  me        = (Map.Entry)  itr.next();
428         FlatCall   fc        = (FlatCall)   me.getKey();
429         ReachGraph rgContrib = (ReachGraph) me.getValue();
430
431         assert fc.getMethod().equals( d );
432
433         // some call sites are in same method context though,
434         // and all of them should be merged together first,
435         // then heaps from different contexts should be merged
436         // THIS ASSUMES DIFFERENT CONTEXTS NEED SPECIAL CONSIDERATION!
437         // such as, do allocation sites need to be aged?
438
439         rg.merge_diffMethodContext( rgContrib );
440       }
441       
442       FlatMethod fm = (FlatMethod) fn;      
443       for( int i = 0; i < fm.numParameters(); ++i ) {
444         TempDescriptor tdParam = fm.getParameter( i );
445         //assert rg.hasVariable( tdParam );
446       }
447     } break;
448       
449     case FKind.FlatOpNode:
450       FlatOpNode fon = (FlatOpNode) fn;
451       if( fon.getOp().getOp() == Operation.ASSIGN ) {
452         lhs = fon.getDest();
453         rhs = fon.getLeft();
454         rg.assignTempXEqualToTempY( lhs, rhs );
455       }
456       break;
457
458     case FKind.FlatCastNode:
459       FlatCastNode fcn = (FlatCastNode) fn;
460       lhs = fcn.getDst();
461       rhs = fcn.getSrc();
462
463       TypeDescriptor td = fcn.getType();
464       assert td != null;
465       
466       rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
467       break;
468
469     case FKind.FlatFieldNode:
470       FlatFieldNode ffn = (FlatFieldNode) fn;
471       lhs = ffn.getDst();
472       rhs = ffn.getSrc();
473       fld = ffn.getField();
474       if( !fld.getType().isImmutable() || fld.getType().isArray() ) {
475         rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld );
476       }          
477       break;
478
479     case FKind.FlatSetFieldNode:
480       FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
481       lhs = fsfn.getDst();
482       fld = fsfn.getField();
483       rhs = fsfn.getSrc();
484       if( !fld.getType().isImmutable() || fld.getType().isArray() ) {
485         rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs );
486       }           
487       break;
488
489     case FKind.FlatElementNode:
490       FlatElementNode fen = (FlatElementNode) fn;
491       lhs = fen.getDst();
492       rhs = fen.getSrc();
493       if( !lhs.getType().isImmutable() || lhs.getType().isArray() ) {
494
495         assert rhs.getType() != null;
496         assert rhs.getType().isArray();
497         
498         TypeDescriptor  tdElement = rhs.getType().dereference();
499         FieldDescriptor fdElement = getArrayField( tdElement );
500   
501         rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement );
502       }
503       break;
504
505     case FKind.FlatSetElementNode:
506       FlatSetElementNode fsen = (FlatSetElementNode) fn;
507
508       if( arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
509         // skip this node if it cannot create new reachability paths
510         break;
511       }
512
513       lhs = fsen.getDst();
514       rhs = fsen.getSrc();
515       if( !rhs.getType().isImmutable() || rhs.getType().isArray() ) {
516
517         assert lhs.getType() != null;
518         assert lhs.getType().isArray();
519         
520         TypeDescriptor  tdElement = lhs.getType().dereference();
521         FieldDescriptor fdElement = getArrayField( tdElement );
522
523         rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs );
524       }
525       break;
526       
527     case FKind.FlatNew:
528       FlatNew fnn = (FlatNew) fn;
529       lhs = fnn.getDst();
530       if( !lhs.getType().isImmutable() || lhs.getType().isArray() ) {
531         AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );   
532         rg.assignTempEqualToNewAlloc( lhs, as );
533       }
534       break;
535
536     case FKind.FlatCall: {
537       FlatCall         fc       = (FlatCall) fn;
538       MethodDescriptor mdCallee = fc.getMethod();
539       FlatMethod       fmCallee = state.getMethodFlat( mdCallee );
540
541       // the transformation for a call site should update the
542       // current heap abstraction with any effects from the callee,
543       // or if the method is virtual, the effects from any possible
544       // callees, so find the set of callees...
545       Set<MethodDescriptor> setPossibleCallees =
546         new HashSet<MethodDescriptor>();
547
548       if( mdCallee.isStatic() ) {        
549         setPossibleCallees.add( mdCallee );
550       } else {
551         TypeDescriptor typeDesc = fc.getThis().getType();
552         setPossibleCallees.addAll( callGraph.getMethods( mdCallee, typeDesc ) );
553       }
554
555       ReachGraph rgMergeOfEffects = new ReachGraph();
556
557       Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
558       while( mdItr.hasNext() ) {
559         MethodDescriptor mdPossible = mdItr.next();
560         FlatMethod       fmPossible = state.getMethodFlat( mdPossible );
561
562         addDependent( mdPossible, // callee
563                       d );        // caller
564
565         // don't alter the working graph (rg) until we compute a 
566         // result for every possible callee, merge them all together,
567         // then set rg to that
568         ReachGraph rgCopy = new ReachGraph();
569         rgCopy.merge( rg );             
570                 
571         ReachGraph rgEffect = getPartial( mdPossible );
572
573         if( rgEffect == null ) {
574           // if this method has never been analyzed just schedule it 
575           // for analysis and skip over this call site for now
576           enqueue( mdPossible );
577         } else {
578           rgCopy.resolveMethodCall( fc, fmPossible, rgEffect );
579         }
580         
581         rgMergeOfEffects.merge( rgCopy );        
582       }
583
584         
585       // now we're done, but BEFORE we set rg = rgMergeOfEffects:
586       // calculate the heap this call site can reach--note this is
587       // not used for the current call site transform, we are
588       // grabbing this heap model for future analysis of the callees,
589       // of if different results emerge we will return to this site
590       ReachGraph heapForThisCall_old = 
591         getIHMcontribution( mdCallee, fc );
592
593       ReachGraph heapForThisCall_cur = rg.makeCalleeView( fc, 
594                                                           fmCallee );
595
596       if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {
597         // if heap at call site changed, update the contribution,
598         // and reschedule the callee for analysis
599         addIHMcontribution( mdCallee, fc, heapForThisCall_cur );        
600         enqueue( mdCallee );
601       }
602
603
604       // now that we've taken care of building heap models for
605       // callee analysis, finish this transformation
606       rg = rgMergeOfEffects;
607     } break;
608       
609
610     case FKind.FlatReturnNode:
611       FlatReturnNode frn = (FlatReturnNode) fn;
612       rhs = frn.getReturnTemp();
613       if( rhs != null && !rhs.getType().isImmutable() ) {
614         rg.assignReturnEqualToTemp( rhs );
615       }
616       setRetNodes.add( frn );
617       break;
618
619     } // end switch
620     
621     // at this point rg should be the correct update
622     // by an above transfer function, or untouched if
623     // the flat node type doesn't affect the heap
624   }
625
626   
627   // this method should generate integers strictly greater than zero!
628   // special "shadow" regions are made from a heap region by negating
629   // the ID
630   static public Integer generateUniqueHeapRegionNodeID() {
631     ++uniqueIDcount;
632     return new Integer( uniqueIDcount );
633   }
634
635
636   
637   static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
638     FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
639     if( fdElement == null ) {
640       fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
641                                        tdElement,
642                                        arrayElementFieldName,
643                                        null,
644                                        false );
645       mapTypeToArrayField.put( tdElement, fdElement );
646     }
647     return fdElement;
648   }
649
650   
651   
652   private void writeFinalGraphs() {
653     Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
654     Iterator itr = entrySet.iterator();
655     while( itr.hasNext() ) {
656       Map.Entry  me = (Map.Entry)  itr.next();
657       Descriptor  d = (Descriptor) me.getKey();
658       ReachGraph rg = (ReachGraph) me.getValue();
659
660       try {        
661         rg.writeGraph( d+"COMPLETE",
662                        true,   // write labels (variables)
663                        true,   // selectively hide intermediate temp vars
664                        true,   // prune unreachable heap regions
665                        false,  // show back edges to confirm graph validity
666                        true,   // hide subset reachability states
667                        true ); // hide edge taints
668       } catch( IOException e ) {}    
669     }
670   }
671    
672
673   // return just the allocation site associated with one FlatNew node
674   protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
675
676     if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
677       AllocSite as = 
678         new AllocSite( allocationDepth, fnew, fnew.getDisjointId() );
679
680       // the newest nodes are single objects
681       for( int i = 0; i < allocationDepth; ++i ) {
682         Integer id = generateUniqueHeapRegionNodeID();
683         as.setIthOldest( i, id );
684         mapHrnIdToAllocSite.put( id, as );
685       }
686
687       // the oldest node is a summary node
688       as.setSummary( generateUniqueHeapRegionNodeID() );
689
690       // and one special node is older than all
691       // nodes and shadow nodes for the site
692       as.setSiteSummary( generateUniqueHeapRegionNodeID() );
693
694       mapFlatNewToAllocSite.put( fnew, as );
695     }
696
697     return mapFlatNewToAllocSite.get( fnew );
698   }
699
700
701   /*
702   // return all allocation sites in the method (there is one allocation
703   // site per FlatNew node in a method)
704   protected HashSet<AllocSite> getAllocSiteSet(Descriptor d) {
705     if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
706       buildAllocSiteSet(d);
707     }
708
709     return mapDescriptorToAllocSiteSet.get(d);
710
711   }
712   */
713
714   /*
715   protected void buildAllocSiteSet(Descriptor d) {
716     HashSet<AllocSite> s = new HashSet<AllocSite>();
717
718     FlatMethod fm = state.getMethodFlat( d );
719
720     // visit every node in this FlatMethod's IR graph
721     // and make a set of the allocation sites from the
722     // FlatNew node's visited
723     HashSet<FlatNode> visited = new HashSet<FlatNode>();
724     HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
725     toVisit.add( fm );
726
727     while( !toVisit.isEmpty() ) {
728       FlatNode n = toVisit.iterator().next();
729
730       if( n instanceof FlatNew ) {
731         s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
732       }
733
734       toVisit.remove( n );
735       visited.add( n );
736
737       for( int i = 0; i < n.numNext(); ++i ) {
738         FlatNode child = n.getNext( i );
739         if( !visited.contains( child ) ) {
740           toVisit.add( child );
741         }
742       }
743     }
744
745     mapDescriptorToAllocSiteSet.put( d, s );
746   }
747   */
748   /*
749   protected HashSet<AllocSite> getFlaggedAllocSites(Descriptor dIn) {
750     
751     HashSet<AllocSite> out     = new HashSet<AllocSite>();
752     HashSet<Descriptor>     toVisit = new HashSet<Descriptor>();
753     HashSet<Descriptor>     visited = new HashSet<Descriptor>();
754
755     toVisit.add(dIn);
756
757     while( !toVisit.isEmpty() ) {
758       Descriptor d = toVisit.iterator().next();
759       toVisit.remove(d);
760       visited.add(d);
761
762       HashSet<AllocSite> asSet = getAllocSiteSet(d);
763       Iterator asItr = asSet.iterator();
764       while( asItr.hasNext() ) {
765         AllocSite as = (AllocSite) asItr.next();
766         if( as.getDisjointAnalysisId() != null ) {
767           out.add(as);
768         }
769       }
770
771       // enqueue callees of this method to be searched for
772       // allocation sites also
773       Set callees = callGraph.getCalleeSet(d);
774       if( callees != null ) {
775         Iterator methItr = callees.iterator();
776         while( methItr.hasNext() ) {
777           MethodDescriptor md = (MethodDescriptor) methItr.next();
778
779           if( !visited.contains(md) ) {
780             toVisit.add(md);
781           }
782         }
783       }
784     }
785     
786     return out;
787   }
788   */
789
790   /*
791   protected HashSet<AllocSite>
792   getFlaggedAllocSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
793
794     HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
795     HashSet<Descriptor>     toVisit    = new HashSet<Descriptor>();
796     HashSet<Descriptor>     visited    = new HashSet<Descriptor>();
797
798     toVisit.add(td);
799
800     // traverse this task and all methods reachable from this task
801     while( !toVisit.isEmpty() ) {
802       Descriptor d = toVisit.iterator().next();
803       toVisit.remove(d);
804       visited.add(d);
805
806       HashSet<AllocSite> asSet = getAllocSiteSet(d);
807       Iterator asItr = asSet.iterator();
808       while( asItr.hasNext() ) {
809         AllocSite as = (AllocSite) asItr.next();
810         TypeDescriptor typed = as.getType();
811         if( typed != null ) {
812           ClassDescriptor cd = typed.getClassDesc();
813           if( cd != null && cd.hasFlags() ) {
814             asSetTotal.add(as);
815           }
816         }
817       }
818
819       // enqueue callees of this method to be searched for
820       // allocation sites also
821       Set callees = callGraph.getCalleeSet(d);
822       if( callees != null ) {
823         Iterator methItr = callees.iterator();
824         while( methItr.hasNext() ) {
825           MethodDescriptor md = (MethodDescriptor) methItr.next();
826
827           if( !visited.contains(md) ) {
828             toVisit.add(md);
829           }
830         }
831       }
832     }
833
834
835     return asSetTotal;
836   }
837   */
838
839
840   /*
841   protected String computeAliasContextHistogram() {
842     
843     Hashtable<Integer, Integer> mapNumContexts2NumDesc = 
844       new Hashtable<Integer, Integer>();
845   
846     Iterator itr = mapDescriptorToAllDescriptors.entrySet().iterator();
847     while( itr.hasNext() ) {
848       Map.Entry me = (Map.Entry) itr.next();
849       HashSet<Descriptor> s = (HashSet<Descriptor>) me.getValue();
850       
851       Integer i = mapNumContexts2NumDesc.get( s.size() );
852       if( i == null ) {
853         i = new Integer( 0 );
854       }
855       mapNumContexts2NumDesc.put( s.size(), i + 1 );
856     }   
857
858     String s = "";
859     int total = 0;
860
861     itr = mapNumContexts2NumDesc.entrySet().iterator();
862     while( itr.hasNext() ) {
863       Map.Entry me = (Map.Entry) itr.next();
864       Integer c0 = (Integer) me.getKey();
865       Integer d0 = (Integer) me.getValue();
866       total += d0;
867       s += String.format( "%4d methods had %4d unique alias contexts.\n", d0, c0 );
868     }
869
870     s += String.format( "\n%4d total methods analayzed.\n", total );
871
872     return s;
873   }
874
875   protected int numMethodsAnalyzed() {    
876     return descriptorsToAnalyze.size();
877   }
878   */
879
880
881   /*
882   // insert a call to debugSnapshot() somewhere in the analysis 
883   // to get successive captures of the analysis state
884   boolean takeDebugSnapshots = false;
885   String mcDescSymbolDebug = "setRoute";
886   boolean stopAfterCapture = true;
887
888   // increments every visit to debugSnapshot, don't fiddle with it
889   // IMPORTANT NOTE FOR SETTING THE FOLLOWING VALUES: this
890   // counter increments just after every node is analyzed
891   // from the body of the method whose symbol is specified
892   // above.
893   int debugCounter = 0;
894
895   // the value of debugCounter to start reporting the debugCounter
896   // to the screen to let user know what debug iteration we're at
897   int numStartCountReport = 0;
898
899   // the frequency of debugCounter values to print out, 0 no report
900   int freqCountReport = 0;
901
902   // the debugCounter value at which to start taking snapshots
903   int iterStartCapture = 0;
904
905   // the number of snapshots to take
906   int numIterToCapture = 300;
907
908   void debugSnapshot(ReachabilityGraph og, FlatNode fn) {
909     if( debugCounter > iterStartCapture + numIterToCapture ) {
910       return;
911     }
912
913     ++debugCounter;
914     if( debugCounter > numStartCountReport &&
915         freqCountReport > 0 &&
916         debugCounter % freqCountReport == 0 ) {
917       System.out.println("    @@@ debug counter = "+debugCounter);
918     }
919     if( debugCounter > iterStartCapture ) {
920       System.out.println("    @@@ capturing debug "+(debugCounter-iterStartCapture)+" @@@");
921       String graphName = String.format("snap%04d",debugCounter-iterStartCapture);
922       if( fn != null ) {
923         graphName = graphName+fn;
924       }
925       try {
926         og.writeGraph(graphName,
927                       true,  // write labels (variables)
928                       true,  // selectively hide intermediate temp vars
929                       true,  // prune unreachable heap regions
930                       false, // show back edges to confirm graph validity
931                       false, // show parameter indices (unmaintained!)
932                       true,  // hide subset reachability states
933                       true); // hide edge taints
934       } catch( Exception e ) {
935         System.out.println("Error writing debug capture.");
936         System.exit(0);
937       }
938     }
939
940     if( debugCounter == iterStartCapture + numIterToCapture && stopAfterCapture ) {
941       System.out.println("Stopping analysis after debug captures.");
942       System.exit(0);
943     }
944   }
945   */
946   
947   
948   // Take in source entry which is the program's compiled entry and
949   // create a new analysis entry, a method that takes no parameters
950   // and appears to allocate the command line arguments and call the
951   // source entry with them.  The purpose of this analysis entry is
952   // to provide a top-level method context with no parameters left.
953   protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
954
955     Modifiers mods = new Modifiers();
956     mods.addModifier( Modifiers.PUBLIC );
957     mods.addModifier( Modifiers.STATIC );
958
959     TypeDescriptor returnType = 
960       new TypeDescriptor( TypeDescriptor.VOID );
961
962     this.mdAnalysisEntry = 
963       new MethodDescriptor( mods,
964                             returnType,
965                             "analysisEntryMethod"
966                             );
967
968     TempDescriptor cmdLineArgs = 
969       new TempDescriptor( "args",
970                           mdSourceEntry.getParamType( 0 )
971                           );
972
973     FlatNew fn = 
974       new FlatNew( mdSourceEntry.getParamType( 0 ),
975                    cmdLineArgs,
976                    false // is global 
977                    );
978     
979     TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
980     sourceEntryArgs[0] = cmdLineArgs;
981     
982     FlatCall fc = 
983       new FlatCall( mdSourceEntry,
984                     null, // dst temp
985                     null, // this temp
986                     sourceEntryArgs
987                     );
988
989     FlatReturnNode frn = new FlatReturnNode( null );
990
991     FlatExit fe = new FlatExit();
992
993     this.fmAnalysisEntry = 
994       new FlatMethod( mdAnalysisEntry, 
995                       fe
996                       );
997
998     this.fmAnalysisEntry.addNext( fn );
999     fn.addNext( fc );
1000     fc.addNext( frn );
1001     frn.addNext( fe );
1002   }
1003
1004
1005   protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1006
1007     Set       <Descriptor> discovered = new HashSet   <Descriptor>();
1008     LinkedList<Descriptor> sorted     = new LinkedList<Descriptor>();
1009   
1010     Iterator<Descriptor> itr = toSort.iterator();
1011     while( itr.hasNext() ) {
1012       Descriptor d = itr.next();
1013           
1014       if( !discovered.contains( d ) ) {
1015         dfsVisit( d, toSort, sorted, discovered );
1016       }
1017     }
1018     
1019     return sorted;
1020   }
1021   
1022   // While we're doing DFS on call graph, remember
1023   // dependencies for efficient queuing of methods
1024   // during interprocedural analysis:
1025   //
1026   // a dependent of a method decriptor d for this analysis is:
1027   //  1) a method or task that invokes d
1028   //  2) in the descriptorsToAnalyze set
1029   protected void dfsVisit( Descriptor             d,
1030                            Set       <Descriptor> toSort,                        
1031                            LinkedList<Descriptor> sorted,
1032                            Set       <Descriptor> discovered ) {
1033     discovered.add( d );
1034     
1035     // only methods have callers, tasks never do
1036     if( d instanceof MethodDescriptor ) {
1037
1038       MethodDescriptor md = (MethodDescriptor) d;
1039
1040       // the call graph is not aware that we have a fabricated
1041       // analysis entry that calls the program source's entry
1042       if( md == mdSourceEntry ) {
1043         if( !discovered.contains( mdAnalysisEntry ) ) {
1044           addDependent( mdSourceEntry,  // callee
1045                         mdAnalysisEntry // caller
1046                         );
1047           dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1048         }
1049       }
1050
1051       // otherwise call graph guides DFS
1052       Iterator itr = callGraph.getCallerSet( md ).iterator();
1053       while( itr.hasNext() ) {
1054         Descriptor dCaller = (Descriptor) itr.next();
1055         
1056         // only consider callers in the original set to analyze
1057         if( !toSort.contains( dCaller ) ) {
1058           continue;
1059         }
1060           
1061         if( !discovered.contains( dCaller ) ) {
1062           addDependent( md,     // callee
1063                         dCaller // caller
1064                         );
1065
1066           dfsVisit( dCaller, toSort, sorted, discovered );
1067         }
1068       }
1069     }
1070     
1071     sorted.addFirst( d );
1072   }
1073
1074
1075   protected void enqueue( Descriptor d ) {
1076     if( !descriptorsToVisitSet.contains( d ) ) {
1077       Integer priority = mapDescriptorToPriority.get( d );
1078       descriptorsToVisitQ.add( new DescriptorQWrapper( priority, 
1079                                                        d ) 
1080                                );
1081       descriptorsToVisitSet.add( d );
1082     }
1083   }
1084
1085
1086   protected ReachGraph getPartial( Descriptor d ) {
1087     return mapDescriptorToCompleteReachGraph.get( d );
1088   }
1089
1090   protected void setPartial( Descriptor d, ReachGraph rg ) {
1091     mapDescriptorToCompleteReachGraph.put( d, rg );
1092
1093     // when the flag for writing out every partial
1094     // result is set, we should spit out the graph,
1095     // but in order to give it a unique name we need
1096     // to track how many partial results for this
1097     // descriptor we've already written out
1098     if( writeAllIncrementalDOTs ) {
1099       if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1100         mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1101       }
1102       Integer n = mapDescriptorToNumUpdates.get( d );
1103       /*
1104       try {
1105         rg.writeGraph( d+"COMPLETE"+String.format( "%05d", n ),
1106                        true,  // write labels (variables)
1107                        true,  // selectively hide intermediate temp vars
1108                        true,  // prune unreachable heap regions
1109                        false, // show back edges to confirm graph validity
1110                        false, // show parameter indices (unmaintained!)
1111                        true,  // hide subset reachability states
1112                        true); // hide edge taints
1113       } catch( IOException e ) {}
1114       */
1115       mapDescriptorToNumUpdates.put( d, n + 1 );
1116     }
1117   }
1118
1119
1120   // a dependent of a method decriptor d for this analysis is:
1121   //  1) a method or task that invokes d
1122   //  2) in the descriptorsToAnalyze set
1123   protected void addDependent( Descriptor callee, Descriptor caller ) {
1124     Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1125     if( deps == null ) {
1126       deps = new HashSet<Descriptor>();
1127     }
1128     deps.add( caller );
1129     mapDescriptorToSetDependents.put( callee, deps );
1130   }
1131   
1132   protected Set<Descriptor> getDependents( Descriptor callee ) {
1133     Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1134     if( deps == null ) {
1135       deps = new HashSet<Descriptor>();
1136       mapDescriptorToSetDependents.put( callee, deps );
1137     }
1138     return deps;
1139   }
1140
1141   
1142   public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
1143
1144     Hashtable<FlatCall, ReachGraph> heapsFromCallers = 
1145       mapDescriptorToIHMcontributions.get( d );
1146     
1147     if( heapsFromCallers == null ) {
1148       heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
1149     }
1150     
1151     return heapsFromCallers;
1152   }
1153
1154   public ReachGraph getIHMcontribution( Descriptor d, 
1155                                         FlatCall   fc
1156                                         ) {
1157     Hashtable<FlatCall, ReachGraph> heapsFromCallers = 
1158       getIHMcontributions( d );
1159
1160     if( !heapsFromCallers.containsKey( fc ) ) {
1161       heapsFromCallers.put( fc, new ReachGraph() );
1162     }
1163
1164     return heapsFromCallers.get( fc );
1165   }
1166
1167   public void addIHMcontribution( Descriptor d,
1168                                   FlatCall   fc,
1169                                   ReachGraph rg
1170                                   ) {
1171     Hashtable<FlatCall, ReachGraph> heapsFromCallers = 
1172       getIHMcontributions( d );
1173
1174     heapsFromCallers.put( fc, rg );
1175   }
1176
1177 }