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