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