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