Create analysis model for string literals in disjointness analysis that supports...
[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(0);
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                     false, //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         assert fc.getMethod().equals(d);
1314
1315         rg.merge(rgContrib);
1316       }
1317
1318       // additionally, we are enforcing STRICT MONOTONICITY for the
1319       // method's initial context, so grow the context by whatever
1320       // the previously computed context was, and put the most
1321       // up-to-date context back in the map
1322       ReachGraph rgPrevContext = mapDescriptorToInitialContext.get(d);
1323       rg.merge(rgPrevContext);
1324       mapDescriptorToInitialContext.put(d, rg);
1325
1326     } break;
1327
1328     case FKind.FlatOpNode:
1329       FlatOpNode fon = (FlatOpNode) fn;
1330       if( fon.getOp().getOp() == Operation.ASSIGN ) {
1331         lhs = fon.getDest();
1332         rhs = fon.getLeft();
1333
1334         // before transfer, do effects analysis support
1335         if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1336           if(rblockRel.isPotentialStallSite(fn)) {
1337             // x gets status of y
1338 //            if(!rg.isAccessible(rhs)){
1339             if(!accessible.isAccessible(fn, rhs)) {
1340               rg.makeInaccessible(lhs);
1341             }
1342           }
1343         }
1344
1345         // transfer func
1346         rg.assignTempXEqualToTempY(lhs, rhs);
1347       }
1348       break;
1349
1350     case FKind.FlatCastNode:
1351       FlatCastNode fcn = (FlatCastNode) fn;
1352       lhs = fcn.getDst();
1353       rhs = fcn.getSrc();
1354
1355       TypeDescriptor td = fcn.getType();
1356       assert td != null;
1357
1358       // before transfer, do effects analysis support
1359       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1360         if(rblockRel.isPotentialStallSite(fn)) {
1361           // x gets status of y
1362 //          if(!rg.isAccessible(rhs)){
1363           if(!accessible.isAccessible(fn,rhs)) {
1364             rg.makeInaccessible(lhs);
1365           }
1366         }
1367       }
1368
1369       // transfer func
1370       rg.assignTempXEqualToCastedTempY(lhs, rhs, td);
1371       break;
1372
1373     case FKind.FlatFieldNode:
1374       FlatFieldNode ffn = (FlatFieldNode) fn;
1375
1376       lhs = ffn.getDst();
1377       rhs = ffn.getSrc();
1378       fld = ffn.getField();
1379
1380       // before graph transform, possible inject
1381       // a stall-site taint
1382       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1383
1384         if(rblockRel.isPotentialStallSite(fn)) {
1385           // x=y.f, stall y if not accessible
1386           // contributes read effects on stall site of y
1387 //          if(!rg.isAccessible(rhs)) {
1388           if(!accessible.isAccessible(fn,rhs)) {
1389             rg.taintStallSite(fn, rhs);
1390           }
1391
1392           // after this, x and y are accessbile.
1393           rg.makeAccessible(lhs);
1394           rg.makeAccessible(rhs);
1395         }
1396       }
1397
1398       if( shouldAnalysisTrack(fld.getType() ) ) {
1399         // transfer func
1400         rg.assignTempXEqualToTempYFieldF(lhs, rhs, fld, fn);
1401       }
1402
1403       // after transfer, use updated graph to
1404       // do effects analysis
1405       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1406         effectsAnalysis.analyzeFlatFieldNode(rg, rhs, fld, fn);
1407       }
1408       break;
1409
1410     case FKind.FlatSetFieldNode:
1411       FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
1412
1413       lhs = fsfn.getDst();
1414       fld = fsfn.getField();
1415       rhs = fsfn.getSrc();
1416
1417       boolean strongUpdate = false;
1418
1419       // before transfer func, possibly inject
1420       // stall-site taints
1421       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1422
1423         if(rblockRel.isPotentialStallSite(fn)) {
1424           // x.y=f , stall x and y if they are not accessible
1425           // also contribute write effects on stall site of x
1426 //          if(!rg.isAccessible(lhs)) {
1427           if(!accessible.isAccessible(fn,lhs)) {
1428             rg.taintStallSite(fn, lhs);
1429           }
1430
1431 //          if(!rg.isAccessible(rhs)) {
1432           if(!accessible.isAccessible(fn,rhs)) {
1433             rg.taintStallSite(fn, rhs);
1434           }
1435
1436           // accessible status update
1437           rg.makeAccessible(lhs);
1438           rg.makeAccessible(rhs);
1439         }
1440       }
1441
1442       if( shouldAnalysisTrack(fld.getType() ) ) {
1443         // transfer func
1444         strongUpdate = rg.assignTempXFieldFEqualToTempY(lhs, fld, rhs, fn);
1445       }
1446
1447       // use transformed graph to do effects analysis
1448       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1449         effectsAnalysis.analyzeFlatSetFieldNode(rg, lhs, fld, fn, strongUpdate);
1450       }
1451       break;
1452
1453     case FKind.FlatElementNode:
1454       FlatElementNode fen = (FlatElementNode) fn;
1455
1456       lhs = fen.getDst();
1457       rhs = fen.getSrc();
1458
1459       assert rhs.getType() != null;
1460       assert rhs.getType().isArray();
1461
1462       tdElement = rhs.getType().dereference();
1463       fdElement = getArrayField(tdElement);
1464
1465       // before transfer func, possibly inject
1466       // stall-site taint
1467       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1468         if(rblockRel.isPotentialStallSite(fn)) {
1469           // x=y.f, stall y if not accessible
1470           // contributes read effects on stall site of y
1471           // after this, x and y are accessbile.
1472 //          if(!rg.isAccessible(rhs)) {
1473           if(!accessible.isAccessible(fn,rhs)) {
1474             rg.taintStallSite(fn, rhs);
1475           }
1476
1477           rg.makeAccessible(lhs);
1478           rg.makeAccessible(rhs);
1479         }
1480       }
1481
1482       if( shouldAnalysisTrack(lhs.getType() ) ) {
1483         // transfer func
1484         rg.assignTempXEqualToTempYFieldF(lhs, rhs, fdElement, fn);
1485       }
1486
1487       // use transformed graph to do effects analysis
1488       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1489         effectsAnalysis.analyzeFlatFieldNode(rg, rhs, fdElement, fn);
1490       }
1491       break;
1492
1493     case FKind.FlatSetElementNode:
1494       FlatSetElementNode fsen = (FlatSetElementNode) fn;
1495
1496       lhs = fsen.getDst();
1497       rhs = fsen.getSrc();
1498
1499       assert lhs.getType() != null;
1500       assert lhs.getType().isArray();
1501
1502       tdElement = lhs.getType().dereference();
1503       fdElement = getArrayField(tdElement);
1504
1505       // before transfer func, possibly inject
1506       // stall-site taints
1507       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1508
1509         if(rblockRel.isPotentialStallSite(fn)) {
1510           // x.y=f , stall x and y if they are not accessible
1511           // also contribute write effects on stall site of x
1512 //          if(!rg.isAccessible(lhs)) {
1513           if(!accessible.isAccessible(fn,lhs)) {
1514             rg.taintStallSite(fn, lhs);
1515           }
1516
1517 //          if(!rg.isAccessible(rhs)) {
1518           if(!accessible.isAccessible(fn,rhs)) {
1519             rg.taintStallSite(fn, rhs);
1520           }
1521
1522           // accessible status update
1523           rg.makeAccessible(lhs);
1524           rg.makeAccessible(rhs);
1525         }
1526       }
1527
1528       if( shouldAnalysisTrack(rhs.getType() ) ) {
1529         // transfer func, BUT
1530         // skip this node if it cannot create new reachability paths
1531         if( !arrayReferencees.doesNotCreateNewReaching(fsen) ) {
1532           rg.assignTempXFieldFEqualToTempY(lhs, fdElement, rhs, fn);
1533         }
1534       }
1535
1536       // use transformed graph to do effects analysis
1537       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1538         effectsAnalysis.analyzeFlatSetFieldNode(rg, lhs, fdElement, fn,
1539                                                 false);
1540       }
1541       break;
1542
1543     case FKind.FlatNew:
1544       FlatNew fnn = (FlatNew) fn;
1545       lhs = fnn.getDst();
1546       if( shouldAnalysisTrack(lhs.getType() ) ) {
1547         AllocSite as = getAllocSiteFromFlatNewPRIVATE(fnn);
1548
1549         // before transform, support effects analysis
1550         if (doEffectsAnalysis && fmContaining != fmAnalysisEntry) {
1551           if (rblockRel.isPotentialStallSite(fn)) {
1552             // after creating new object, lhs is accessible
1553             rg.makeAccessible(lhs);
1554           }
1555         }
1556
1557         // transfer func
1558         rg.assignTempEqualToNewAlloc(lhs, as);
1559       }
1560       break;
1561
1562       
1563     case FKind.FlatLiteralNode:
1564       // BIG NOTE: this transfer function is only here for
1565       // points-to information for String literals.  That's it.
1566       // Effects and disjoint reachability and all of that don't
1567       // care about references to literals.
1568       FlatLiteralNode fln = (FlatLiteralNode) fn;
1569
1570       if( fln.getType().equals( stringType ) ) {
1571         rg.assignTempEqualToStringLiteral( fln.getDst(),
1572                                            newStringLiteralAlloc,
1573                                            newStringLiteralBytesAlloc,
1574                                            stringBytesField );
1575       }      
1576       break;
1577
1578
1579     case FKind.FlatSESEEnterNode:
1580       sese = (FlatSESEEnterNode) fn;
1581
1582       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1583
1584         // always remove ALL stall site taints at enter
1585         rg.removeAllStallSiteTaints();
1586
1587         // inject taints for in-set vars
1588         rg.taintInSetVars(sese);
1589
1590       }
1591       break;
1592
1593     case FKind.FlatSESEExitNode:
1594       fsexn = (FlatSESEExitNode) fn;
1595       sese  = fsexn.getFlatEnter();
1596
1597       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1598
1599         // @ sese exit make all live variables
1600         // inaccessible to later parent statements
1601         rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) );
1602
1603         // always remove ALL stall site taints at exit
1604         rg.removeAllStallSiteTaints();
1605
1606         // remove in-set var taints for the exiting rblock
1607         rg.removeInContextTaints(sese);
1608       }
1609       break;
1610
1611
1612     case FKind.FlatCall: {
1613       Descriptor mdCaller;
1614       if( fmContaining.getMethod() != null ) {
1615         mdCaller = fmContaining.getMethod();
1616       } else {
1617         mdCaller = fmContaining.getTask();
1618       }
1619       FlatCall fc       = (FlatCall) fn;
1620       MethodDescriptor mdCallee = fc.getMethod();
1621       FlatMethod fmCallee = state.getMethodFlat(mdCallee);
1622
1623
1624
1625       // all this jimma jamma to debug call sites is WELL WORTH the
1626       // effort, so so so many bugs or buggy info appears through call
1627       // sites
1628       boolean debugCallSite = false;
1629       if( state.DISJOINTDEBUGCALLEE != null &&
1630           state.DISJOINTDEBUGCALLER != null ) {
1631
1632         boolean debugCalleeMatches = false;
1633         boolean debugCallerMatches = false;
1634         
1635         ClassDescriptor cdCallee = mdCallee.getClassDesc();
1636         if( cdCallee != null ) {
1637           debugCalleeMatches = 
1638             state.DISJOINTDEBUGCALLEE.equals( cdCallee.getSymbol()+
1639                                               "."+
1640                                               mdCallee.getSymbol()
1641                                               );
1642         }
1643
1644
1645         if( mdCaller instanceof MethodDescriptor ) {
1646           ClassDescriptor cdCaller = ((MethodDescriptor)mdCaller).getClassDesc();
1647           if( cdCaller != null ) {
1648             debugCallerMatches = 
1649               state.DISJOINTDEBUGCALLER.equals( cdCaller.getSymbol()+
1650                                                 "."+
1651                                                 mdCaller.getSymbol()
1652                                                 );
1653           }        
1654         } else {
1655           // for bristlecone style tasks
1656           debugCallerMatches =
1657             state.DISJOINTDEBUGCALLER.equals( mdCaller.getSymbol() );
1658         }
1659
1660         debugCallSite = debugCalleeMatches && debugCallerMatches;
1661       }
1662
1663       
1664
1665
1666       boolean writeDebugDOTs = false;
1667       boolean stopAfter      = false;
1668       if( debugCallSite ) {
1669         ++ReachGraph.debugCallSiteVisitCounter;
1670         System.out.println("    $$$ Debug call site visit "+
1671                            ReachGraph.debugCallSiteVisitCounter+
1672                            " $$$"
1673                            );
1674         if(
1675           (ReachGraph.debugCallSiteVisitCounter >=
1676            ReachGraph.debugCallSiteVisitStartCapture)  &&
1677
1678           (ReachGraph.debugCallSiteVisitCounter <
1679            ReachGraph.debugCallSiteVisitStartCapture +
1680            ReachGraph.debugCallSiteNumVisitsToCapture)
1681           ) {
1682           writeDebugDOTs = true;
1683           System.out.println("      $$$ Capturing this call site visit $$$");
1684           if( ReachGraph.debugCallSiteStopAfter &&
1685               (ReachGraph.debugCallSiteVisitCounter ==
1686                ReachGraph.debugCallSiteVisitStartCapture +
1687                ReachGraph.debugCallSiteNumVisitsToCapture - 1)
1688               ) {
1689             stopAfter = true;
1690           }
1691         }
1692       }
1693
1694
1695       // calculate the heap this call site can reach--note this is
1696       // not used for the current call site transform, we are
1697       // grabbing this heap model for future analysis of the callees,
1698       // so if different results emerge we will return to this site
1699       ReachGraph heapForThisCall_old =
1700         getIHMcontribution(mdCallee, fc);
1701
1702       // the computation of the callee-reachable heap
1703       // is useful for making the callee starting point
1704       // and for applying the call site transfer function
1705       Set<Integer> callerNodeIDsCopiedToCallee =
1706         new HashSet<Integer>();
1707
1708       ReachGraph heapForThisCall_cur =
1709         rg.makeCalleeView(fc,
1710                           fmCallee,
1711                           callerNodeIDsCopiedToCallee,
1712                           writeDebugDOTs
1713                           );
1714
1715       // enforce that a call site contribution can only
1716       // monotonically increase
1717       heapForThisCall_cur.merge(heapForThisCall_old);
1718
1719       if( !heapForThisCall_cur.equals(heapForThisCall_old) ) {
1720         // if heap at call site changed, update the contribution,
1721         // and reschedule the callee for analysis
1722         addIHMcontribution(mdCallee, fc, heapForThisCall_cur);
1723
1724         // map a FlatCall to its enclosing method/task descriptor
1725         // so we can write that info out later
1726         fc2enclosing.put(fc, mdCaller);
1727
1728         if( state.DISJOINTDEBUGSCHEDULING ) {
1729           System.out.println("  context changed, scheduling callee: "+mdCallee);
1730         }
1731
1732         if( state.DISJOINTDVISITSTACKEESONTOP ) {
1733           calleesToEnqueue.add(mdCallee);
1734         } else {
1735           enqueue(mdCallee);
1736         }
1737
1738       }
1739
1740       // the transformation for a call site should update the
1741       // current heap abstraction with any effects from the callee,
1742       // or if the method is virtual, the effects from any possible
1743       // callees, so find the set of callees...
1744       Set<MethodDescriptor> setPossibleCallees;
1745       if( determinismDesired ) {
1746         // use an ordered set
1747         setPossibleCallees = new TreeSet<MethodDescriptor>(dComp);
1748       } else {
1749         // otherwise use a speedy hashset
1750         setPossibleCallees = new HashSet<MethodDescriptor>();
1751       }
1752
1753       if( mdCallee.isStatic() ) {
1754         setPossibleCallees.add(mdCallee);
1755       } else {
1756         TypeDescriptor typeDesc = fc.getThis().getType();
1757         setPossibleCallees.addAll(callGraph.getMethods(mdCallee,
1758                                                        typeDesc)
1759                                   );
1760       }
1761
1762
1763
1764       ReachGraph rgMergeOfPossibleCallers = new ReachGraph();
1765
1766       Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
1767       while( mdItr.hasNext() ) {
1768         MethodDescriptor mdPossible = mdItr.next();
1769         FlatMethod fmPossible = state.getMethodFlat(mdPossible);
1770
1771         addDependent(mdPossible,  // callee
1772                      d);          // caller
1773
1774         // don't alter the working graph (rg) until we compute a
1775         // result for every possible callee, merge them all together,
1776         // then set rg to that
1777         ReachGraph rgPossibleCaller = new ReachGraph();
1778         rgPossibleCaller.merge(rg);
1779
1780         ReachGraph rgPossibleCallee = getPartial(mdPossible);
1781
1782         if( rgPossibleCallee == null ) {
1783           // if this method has never been analyzed just schedule it
1784           // for analysis and skip over this call site for now
1785           if( state.DISJOINTDVISITSTACKEESONTOP ) {
1786             calleesToEnqueue.add(mdPossible);
1787           } else {
1788             enqueue(mdPossible);
1789           }
1790
1791           if( state.DISJOINTDEBUGSCHEDULING ) {
1792             System.out.println("  callee hasn't been analyzed, scheduling: "+mdPossible);
1793           }
1794
1795         } else {
1796           // calculate the method call transform
1797           rgPossibleCaller.resolveMethodCall(fc,
1798                                              fmPossible,
1799                                              rgPossibleCallee,
1800                                              callerNodeIDsCopiedToCallee,
1801                                              writeDebugDOTs
1802                                              );
1803
1804           if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1805 //            if( !rgPossibleCallee.isAccessible( ReachGraph.tdReturn ) ) {
1806             if( !accessible.isAccessible(fn, ReachGraph.tdReturn) ) {
1807               rgPossibleCaller.makeInaccessible(fc.getReturnTemp() );
1808             }
1809           }
1810
1811         }
1812
1813         rgMergeOfPossibleCallers.merge(rgPossibleCaller);
1814       }
1815
1816
1817       if( stopAfter ) {
1818         System.out.println("$$$ Exiting after requested captures of call site. $$$");
1819         System.exit(0);
1820       }
1821
1822
1823       // now that we've taken care of building heap models for
1824       // callee analysis, finish this transformation
1825       rg = rgMergeOfPossibleCallers;
1826
1827
1828       // jjenista: what is this?  It breaks compilation
1829       // of programs with no tasks/SESEs/rblocks...
1830       //XXXXXXXXXXXXXXXXXXXXXXXXX
1831       //need to consider more
1832       if( state.OOOJAVA ) {
1833         FlatNode nextFN=fmCallee.getNext(0);
1834         if( nextFN instanceof FlatSESEEnterNode ) {
1835           FlatSESEEnterNode calleeSESE=(FlatSESEEnterNode)nextFN;
1836           if(!calleeSESE.getIsLeafSESE()) {
1837             rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) );
1838           }
1839         }
1840       }
1841
1842     } break;
1843
1844
1845     case FKind.FlatReturnNode:
1846       FlatReturnNode frn = (FlatReturnNode) fn;
1847       rhs = frn.getReturnTemp();
1848
1849       // before transfer, do effects analysis support
1850       if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1851 //        if(!rg.isAccessible(rhs)){
1852         if(!accessible.isAccessible(fn,rhs)) {
1853           rg.makeInaccessible(ReachGraph.tdReturn);
1854         }
1855       }
1856
1857       if( rhs != null && shouldAnalysisTrack(rhs.getType() ) ) {
1858         rg.assignReturnEqualToTemp(rhs);
1859       }
1860
1861       setRetNodes.add(frn);
1862       break;
1863
1864     } // end switch
1865
1866
1867     // dead variables were removed before the above transfer function
1868     // was applied, so eliminate heap regions and edges that are no
1869     // longer part of the abstractly-live heap graph, and sweep up
1870     // and reachability effects that are altered by the reduction
1871     //rg.abstractGarbageCollect();
1872     //rg.globalSweep();
1873
1874
1875     // back edges are strictly monotonic
1876     if( pm.isBackEdge(fn) ) {
1877       ReachGraph rgPrevResult = mapBackEdgeToMonotone.get(fn);
1878       rg.merge(rgPrevResult);
1879       mapBackEdgeToMonotone.put(fn, rg);
1880     }
1881
1882
1883     ReachGraph rgOnExit = new ReachGraph();
1884     rgOnExit.merge(rg);
1885     fn2rgAtExit.put(fn, rgOnExit);
1886
1887
1888     // at this point rg should be the correct update
1889     // by an above transfer function, or untouched if
1890     // the flat node type doesn't affect the heap
1891     return rg;
1892   }
1893
1894
1895
1896   // this method should generate integers strictly greater than zero!
1897   // special "shadow" regions are made from a heap region by negating
1898   // the ID
1899   static public Integer generateUniqueHeapRegionNodeID() {
1900     ++uniqueIDcount;
1901     return new Integer(uniqueIDcount);
1902   }
1903
1904
1905
1906   static public FieldDescriptor getArrayField(TypeDescriptor tdElement) {
1907     FieldDescriptor fdElement = mapTypeToArrayField.get(tdElement);
1908     if( fdElement == null ) {
1909       fdElement = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC),
1910                                       tdElement,
1911                                       arrayElementFieldName,
1912                                       null,
1913                                       false);
1914       mapTypeToArrayField.put(tdElement, fdElement);
1915     }
1916     return fdElement;
1917   }
1918
1919
1920
1921   private void writeFinalGraphs() {
1922     Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1923     Iterator itr = entrySet.iterator();
1924     while( itr.hasNext() ) {
1925       Map.Entry me = (Map.Entry)itr.next();
1926       Descriptor d = (Descriptor) me.getKey();
1927       ReachGraph rg = (ReachGraph) me.getValue();
1928
1929       String graphName;
1930       if( d instanceof TaskDescriptor ) {
1931         graphName = "COMPLETEtask"+d;
1932       } else {
1933         graphName = "COMPLETE"+d;
1934       }
1935
1936       rg.writeGraph(graphName,
1937                     true,     // write labels (variables)
1938                     true,     // selectively hide intermediate temp vars
1939                     true,     // prune unreachable heap regions
1940                     true,     // hide reachability altogether
1941                     true,     // hide subset reachability states
1942                     true,     // hide predicates
1943                     false);   // hide edge taints
1944     }
1945   }
1946
1947   private void writeFinalIHMs() {
1948     Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1949     while( d2IHMsItr.hasNext() ) {
1950       Map.Entry me1 = (Map.Entry)d2IHMsItr.next();
1951       Descriptor d = (Descriptor)                      me1.getKey();
1952       Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>)me1.getValue();
1953
1954       Iterator fc2rgItr = IHMs.entrySet().iterator();
1955       while( fc2rgItr.hasNext() ) {
1956         Map.Entry me2 = (Map.Entry)fc2rgItr.next();
1957         FlatCall fc  = (FlatCall)   me2.getKey();
1958         ReachGraph rg  = (ReachGraph) me2.getValue();
1959
1960         rg.writeGraph("IHMPARTFOR"+d+"FROM"+fc2enclosing.get(fc)+fc,
1961                       true,    // write labels (variables)
1962                       true,    // selectively hide intermediate temp vars
1963                       true,    // hide reachability altogether
1964                       true,    // prune unreachable heap regions
1965                       true,    // hide subset reachability states
1966                       false,   // hide predicates
1967                       true);   // hide edge taints
1968       }
1969     }
1970   }
1971
1972   private void writeInitialContexts() {
1973     Set entrySet = mapDescriptorToInitialContext.entrySet();
1974     Iterator itr = entrySet.iterator();
1975     while( itr.hasNext() ) {
1976       Map.Entry me = (Map.Entry)itr.next();
1977       Descriptor d = (Descriptor) me.getKey();
1978       ReachGraph rg = (ReachGraph) me.getValue();
1979
1980       rg.writeGraph("INITIAL"+d,
1981                     true,    // write labels (variables)
1982                     true,    // selectively hide intermediate temp vars
1983                     true,    // prune unreachable heap regions
1984                     false,   // hide all reachability
1985                     true,    // hide subset reachability states
1986                     true,    // hide predicates
1987                     false);  // hide edge taints
1988     }
1989   }
1990
1991
1992   protected ReachGraph getPartial(Descriptor d) {
1993     return mapDescriptorToCompleteReachGraph.get(d);
1994   }
1995
1996   protected void setPartial(Descriptor d, ReachGraph rg) {
1997     mapDescriptorToCompleteReachGraph.put(d, rg);
1998
1999     // when the flag for writing out every partial
2000     // result is set, we should spit out the graph,
2001     // but in order to give it a unique name we need
2002     // to track how many partial results for this
2003     // descriptor we've already written out
2004     if( writeAllIncrementalDOTs ) {
2005       if( !mapDescriptorToNumUpdates.containsKey(d) ) {
2006         mapDescriptorToNumUpdates.put(d, new Integer(0) );
2007       }
2008       Integer n = mapDescriptorToNumUpdates.get(d);
2009
2010       String graphName;
2011       if( d instanceof TaskDescriptor ) {
2012         graphName = d+"COMPLETEtask"+String.format("%05d", n);
2013       } else {
2014         graphName = d+"COMPLETE"+String.format("%05d", n);
2015       }
2016
2017       rg.writeGraph(graphName,
2018                     true,    // write labels (variables)
2019                     true,    // selectively hide intermediate temp vars
2020                     true,    // prune unreachable heap regions
2021                     false,   // hide all reachability
2022                     true,    // hide subset reachability states
2023                     false,   // hide predicates
2024                     false);  // hide edge taints
2025
2026       mapDescriptorToNumUpdates.put(d, n + 1);
2027     }
2028   }
2029
2030
2031
2032   // return just the allocation site associated with one FlatNew node
2033   protected AllocSite getAllocSiteFromFlatNewPRIVATE(FlatNew fnew) {
2034
2035     boolean flagProgrammatically = false;
2036     if( sitesToFlag != null && sitesToFlag.contains(fnew) ) {
2037       flagProgrammatically = true;
2038     }
2039
2040     if( !mapFlatNewToAllocSite.containsKey(fnew) ) {
2041       AllocSite as = AllocSite.factory(allocationDepth,
2042                                        fnew,
2043                                        fnew.getDisjointId(),
2044                                        flagProgrammatically
2045                                        );
2046
2047       // the newest nodes are single objects
2048       for( int i = 0; i < allocationDepth; ++i ) {
2049         Integer id = generateUniqueHeapRegionNodeID();
2050         as.setIthOldest(i, id);
2051         mapHrnIdToAllocSite.put(id, as);
2052       }
2053
2054       // the oldest node is a summary node
2055       as.setSummary(generateUniqueHeapRegionNodeID() );
2056
2057       mapFlatNewToAllocSite.put(fnew, as);
2058     }
2059
2060     return mapFlatNewToAllocSite.get(fnew);
2061   }
2062
2063
2064   public static boolean shouldAnalysisTrack(TypeDescriptor type) {
2065     // don't track primitive types, but an array
2066     // of primitives is heap memory
2067     if( type.isImmutable() ) {
2068       return type.isArray();
2069     }
2070
2071     // everything else is an object
2072     return true;
2073   }
2074
2075   protected int numMethodsAnalyzed() {
2076     return descriptorsToAnalyze.size();
2077   }
2078
2079
2080
2081
2082   // Take in source entry which is the program's compiled entry and
2083   // create a new analysis entry, a method that takes no parameters
2084   // and appears to allocate the command line arguments and call the
2085   // source entry with them.  The purpose of this analysis entry is
2086   // to provide a top-level method context with no parameters left.
2087   protected void makeAnalysisEntryMethod(MethodDescriptor mdSourceEntry) {
2088
2089     Modifiers mods = new Modifiers();
2090     mods.addModifier(Modifiers.PUBLIC);
2091     mods.addModifier(Modifiers.STATIC);
2092
2093     TypeDescriptor returnType = new TypeDescriptor(TypeDescriptor.VOID);
2094     
2095     this.mdAnalysisEntry =
2096       new MethodDescriptor(mods,
2097                            returnType,
2098                            "analysisEntryMethod"
2099                            );
2100
2101     TypeDescriptor argsType = mdSourceEntry.getParamType(0);
2102     TempDescriptor cmdLineArgs =
2103       new TempDescriptor("analysisEntryTemp_args",
2104                          argsType
2105                          );
2106     FlatNew fnArgs =
2107       new FlatNew(argsType,
2108                   cmdLineArgs,
2109                   false  // is global
2110                   );
2111     this.constructedCmdLineArgsNew = fnArgs;
2112
2113     TypeDescriptor argType = argsType.dereference();
2114     TempDescriptor anArg =
2115       new TempDescriptor("analysisEntryTemp_arg",
2116                          argType
2117                          );
2118     FlatNew fnArg =
2119       new FlatNew(argType,
2120                   anArg,
2121                   false  // is global
2122                   );
2123     this.constructedCmdLineArgNew = fnArg;
2124
2125     TypeDescriptor typeIndex = new TypeDescriptor(TypeDescriptor.INT);
2126     TempDescriptor index =
2127       new TempDescriptor("analysisEntryTemp_index",
2128                          typeIndex
2129                          );
2130     FlatLiteralNode fli =
2131       new FlatLiteralNode(typeIndex,
2132                           new Integer( 0 ),
2133                           index
2134                           );
2135     
2136     FlatSetElementNode fse =
2137       new FlatSetElementNode(cmdLineArgs,
2138                              index,
2139                              anArg
2140                              );
2141
2142     TypeDescriptor typeSize = new TypeDescriptor(TypeDescriptor.INT);
2143     TempDescriptor sizeBytes =
2144       new TempDescriptor("analysisEntryTemp_size",
2145                          typeSize
2146                          );
2147     FlatLiteralNode fls =
2148       new FlatLiteralNode(typeSize,
2149                           new Integer( 1 ),
2150                           sizeBytes
2151                           );
2152
2153     TempDescriptor strBytes =
2154       new TempDescriptor("analysisEntryTemp_strBytes",
2155                          stringBytesType
2156                          );
2157     FlatNew fnBytes =
2158       new FlatNew(stringBytesType,
2159                   strBytes,
2160                   //sizeBytes,
2161                   false  // is global
2162                   );
2163     this.constructedCmdLineArgBytesNew = fnBytes;
2164
2165     FlatSetFieldNode fsf =
2166       new FlatSetFieldNode(anArg,
2167                            stringBytesField,
2168                            strBytes
2169                            );
2170
2171     // throw this in so you can always see what the initial heap context
2172     // looks like if you want to, its cheap
2173     FlatGenReachNode fgen = new FlatGenReachNode( "argContext" );
2174
2175     TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
2176     sourceEntryArgs[0] = cmdLineArgs;
2177     FlatCall fc =
2178       new FlatCall(mdSourceEntry,
2179                    null,  // dst temp
2180                    null,  // this temp
2181                    sourceEntryArgs
2182                    );
2183
2184     FlatReturnNode frn = new FlatReturnNode(null);
2185
2186     FlatExit fe = new FlatExit();
2187
2188     this.fmAnalysisEntry =
2189       new FlatMethod(mdAnalysisEntry,
2190                      fe
2191                      );
2192
2193     List<FlatNode> nodes = new LinkedList<FlatNode>();
2194     nodes.add( fnArgs );
2195     nodes.add( fnArg );
2196     nodes.add( fli );
2197     nodes.add( fse );
2198     nodes.add( fls );
2199     nodes.add( fnBytes );
2200     nodes.add( fsf );
2201     nodes.add( fgen );
2202     nodes.add( fc );
2203     nodes.add( frn );
2204     nodes.add( fe );
2205
2206     FlatNode current = this.fmAnalysisEntry;
2207     for( FlatNode next: nodes ) {
2208       current.addNext( next );
2209       current = next;
2210     }
2211
2212     
2213     // jjenista - this is useful for looking at the FlatIRGraph of the
2214     // analysis entry method constructed above if you have to modify it.
2215     // The usual method of writing FlatIRGraphs out doesn't work because
2216     // this flat method is private to the model of this analysis only.
2217     //try {
2218     //  FlatIRGraph flatMethodWriter = 
2219     //    new FlatIRGraph( state, false, false, false );
2220     //  flatMethodWriter.writeFlatIRGraph( fmAnalysisEntry, "analysisEntry" );
2221     //} catch( IOException e ) {}
2222   }
2223
2224
2225   protected LinkedList<Descriptor> topologicalSort(Set<Descriptor> toSort) {
2226
2227     Set<Descriptor> discovered;
2228
2229     if( determinismDesired ) {
2230       // use an ordered set
2231       discovered = new TreeSet<Descriptor>(dComp);
2232     } else {
2233       // otherwise use a speedy hashset
2234       discovered = new HashSet<Descriptor>();
2235     }
2236
2237     LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
2238
2239     Iterator<Descriptor> itr = toSort.iterator();
2240     while( itr.hasNext() ) {
2241       Descriptor d = itr.next();
2242
2243       if( !discovered.contains(d) ) {
2244         dfsVisit(d, toSort, sorted, discovered);
2245       }
2246     }
2247
2248     return sorted;
2249   }
2250
2251   // While we're doing DFS on call graph, remember
2252   // dependencies for efficient queuing of methods
2253   // during interprocedural analysis:
2254   //
2255   // a dependent of a method decriptor d for this analysis is:
2256   //  1) a method or task that invokes d
2257   //  2) in the descriptorsToAnalyze set
2258   protected void dfsVisit(Descriptor d,
2259                           Set       <Descriptor> toSort,
2260                           LinkedList<Descriptor> sorted,
2261                           Set       <Descriptor> discovered) {
2262     discovered.add(d);
2263
2264     // only methods have callers, tasks never do
2265     if( d instanceof MethodDescriptor ) {
2266
2267       MethodDescriptor md = (MethodDescriptor) d;
2268
2269       // the call graph is not aware that we have a fabricated
2270       // analysis entry that calls the program source's entry
2271       if( md == mdSourceEntry ) {
2272         if( !discovered.contains(mdAnalysisEntry) ) {
2273           addDependent(mdSourceEntry,   // callee
2274                        mdAnalysisEntry  // caller
2275                        );
2276           dfsVisit(mdAnalysisEntry, toSort, sorted, discovered);
2277         }
2278       }
2279
2280       // otherwise call graph guides DFS
2281       Iterator itr = callGraph.getCallerSet(md).iterator();
2282       while( itr.hasNext() ) {
2283         Descriptor dCaller = (Descriptor) itr.next();
2284
2285         // only consider callers in the original set to analyze
2286         if( !toSort.contains(dCaller) ) {
2287           continue;
2288         }
2289
2290         if( !discovered.contains(dCaller) ) {
2291           addDependent(md,      // callee
2292                        dCaller  // caller
2293                        );
2294
2295           dfsVisit(dCaller, toSort, sorted, discovered);
2296         }
2297       }
2298     }
2299
2300     // for leaf-nodes last now!
2301     sorted.addLast(d);
2302   }
2303
2304
2305   protected void enqueue(Descriptor d) {
2306
2307     if( !descriptorsToVisitSet.contains(d) ) {
2308
2309       if( state.DISJOINTDVISITSTACK ||
2310           state.DISJOINTDVISITSTACKEESONTOP
2311           ) {
2312         descriptorsToVisitStack.add(d);
2313
2314       } else if( state.DISJOINTDVISITPQUE ) {
2315         Integer priority = mapDescriptorToPriority.get(d);
2316         descriptorsToVisitQ.add(new DescriptorQWrapper(priority,
2317                                                        d)
2318                                 );
2319       }
2320
2321       descriptorsToVisitSet.add(d);
2322     }
2323   }
2324
2325
2326   // a dependent of a method decriptor d for this analysis is:
2327   //  1) a method or task that invokes d
2328   //  2) in the descriptorsToAnalyze set
2329   protected void addDependent(Descriptor callee, Descriptor caller) {
2330     Set<Descriptor> deps = mapDescriptorToSetDependents.get(callee);
2331     if( deps == null ) {
2332       deps = new HashSet<Descriptor>();
2333     }
2334     deps.add(caller);
2335     mapDescriptorToSetDependents.put(callee, deps);
2336   }
2337
2338   protected Set<Descriptor> getDependents(Descriptor callee) {
2339     Set<Descriptor> deps = mapDescriptorToSetDependents.get(callee);
2340     if( deps == null ) {
2341       deps = new HashSet<Descriptor>();
2342       mapDescriptorToSetDependents.put(callee, deps);
2343     }
2344     return deps;
2345   }
2346
2347
2348   public Hashtable<FlatCall, ReachGraph> getIHMcontributions(Descriptor d) {
2349
2350     Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2351       mapDescriptorToIHMcontributions.get(d);
2352
2353     if( heapsFromCallers == null ) {
2354       heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
2355       mapDescriptorToIHMcontributions.put(d, heapsFromCallers);
2356     }
2357
2358     return heapsFromCallers;
2359   }
2360
2361   public ReachGraph getIHMcontribution(Descriptor d,
2362                                        FlatCall fc
2363                                        ) {
2364     Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2365       getIHMcontributions(d);
2366
2367     if( !heapsFromCallers.containsKey(fc) ) {
2368       return null;
2369     }
2370
2371     return heapsFromCallers.get(fc);
2372   }
2373
2374
2375   public void addIHMcontribution(Descriptor d,
2376                                  FlatCall fc,
2377                                  ReachGraph rg
2378                                  ) {
2379     Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2380       getIHMcontributions(d);
2381
2382     heapsFromCallers.put(fc, rg);
2383   }
2384
2385
2386   private AllocSite createParameterAllocSite(ReachGraph rg,
2387                                              TempDescriptor tempDesc,
2388                                              boolean flagRegions
2389                                              ) {
2390
2391     FlatNew flatNew;
2392     if( flagRegions ) {
2393       flatNew = new FlatNew(tempDesc.getType(),  // type
2394                             tempDesc,            // param temp
2395                             false,               // global alloc?
2396                             "param"+tempDesc     // disjoint site ID string
2397                             );
2398     } else {
2399       flatNew = new FlatNew(tempDesc.getType(),  // type
2400                             tempDesc,            // param temp
2401                             false,               // global alloc?
2402                             null                 // disjoint site ID string
2403                             );
2404     }
2405
2406     // create allocation site
2407     AllocSite as = AllocSite.factory(allocationDepth,
2408                                      flatNew,
2409                                      flatNew.getDisjointId(),
2410                                      false
2411                                      );
2412     for (int i = 0; i < allocationDepth; ++i) {
2413       Integer id = generateUniqueHeapRegionNodeID();
2414       as.setIthOldest(i, id);
2415       mapHrnIdToAllocSite.put(id, as);
2416     }
2417     // the oldest node is a summary node
2418     as.setSummary(generateUniqueHeapRegionNodeID() );
2419
2420     rg.age(as);
2421
2422     return as;
2423
2424   }
2425
2426   private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc) {
2427
2428     Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
2429     if(!typeDesc.isImmutable()) {
2430       ClassDescriptor classDesc = typeDesc.getClassDesc();
2431       for (Iterator it = classDesc.getFields(); it.hasNext(); ) {
2432         FieldDescriptor field = (FieldDescriptor) it.next();
2433         TypeDescriptor fieldType = field.getType();
2434         if (shouldAnalysisTrack(fieldType)) {
2435           fieldSet.add(field);
2436         }
2437       }
2438     }
2439     return fieldSet;
2440
2441   }
2442
2443   private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha) {
2444
2445     int dimCount=fd.getType().getArrayCount();
2446     HeapRegionNode prevNode=null;
2447     HeapRegionNode arrayEntryNode=null;
2448     for(int i=dimCount; i>0; i--) {
2449       TypeDescriptor typeDesc=fd.getType().dereference();          //hack to get instance of type desc
2450       typeDesc.setArrayCount(i);
2451       TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
2452       HeapRegionNode hrnSummary;
2453       if(!mapToExistingNode.containsKey(typeDesc)) {
2454         AllocSite as;
2455         if(i==dimCount) {
2456           as = alloc;
2457         } else {
2458           as = createParameterAllocSite(rg, tempDesc, false);
2459         }
2460         // make a new reference to allocated node
2461         hrnSummary =
2462           rg.createNewHeapRegionNode(as.getSummary(),                       // id or null to generate a new one
2463                                      false,                       // single object?
2464                                      true,                       // summary?
2465                                      false,                       // out-of-context?
2466                                      as.getType(),                       // type
2467                                      as,                       // allocation site
2468                                      alpha,                       // inherent reach
2469                                      alpha,                       // current reach
2470                                      ExistPredSet.factory(rg.predTrue),                       // predicates
2471                                      tempDesc.toString()                       // description
2472                                      );
2473         rg.id2hrn.put(as.getSummary(),hrnSummary);
2474
2475         mapToExistingNode.put(typeDesc, hrnSummary);
2476       } else {
2477         hrnSummary=mapToExistingNode.get(typeDesc);
2478       }
2479
2480       if(prevNode==null) {
2481         // make a new reference between new summary node and source
2482         RefEdge edgeToSummary = new RefEdge(srcHRN,       // source
2483                                             hrnSummary,             // dest
2484                                             typeDesc,             // type
2485                                             fd.getSymbol(),             // field name
2486                                             alpha,             // beta
2487                                             ExistPredSet.factory(rg.predTrue),       // predicates
2488                                             null
2489                                             );
2490
2491         rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2492         prevNode=hrnSummary;
2493         arrayEntryNode=hrnSummary;
2494       } else {
2495         // make a new reference between summary nodes of array
2496         RefEdge edgeToSummary = new RefEdge(prevNode,             // source
2497                                             hrnSummary,             // dest
2498                                             typeDesc,             // type
2499                                             arrayElementFieldName,             // field name
2500                                             alpha,             // beta
2501                                             ExistPredSet.factory(rg.predTrue),             // predicates
2502                                             null
2503                                             );
2504
2505         rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2506         prevNode=hrnSummary;
2507       }
2508
2509     }
2510
2511     // create a new obj node if obj has at least one non-primitive field
2512     TypeDescriptor type=fd.getType();
2513     if(getFieldSetTobeAnalyzed(type).size()>0) {
2514       TypeDescriptor typeDesc=type.dereference();
2515       typeDesc.setArrayCount(0);
2516       if(!mapToExistingNode.containsKey(typeDesc)) {
2517         TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
2518         AllocSite as = createParameterAllocSite(rg, tempDesc, false);
2519         // make a new reference to allocated node
2520         HeapRegionNode hrnSummary =
2521           rg.createNewHeapRegionNode(as.getSummary(),                       // id or null to generate a new one
2522                                      false,                       // single object?
2523                                      true,                       // summary?
2524                                      false,                       // out-of-context?
2525                                      typeDesc,                       // type
2526                                      as,                       // allocation site
2527                                      alpha,                       // inherent reach
2528                                      alpha,                       // current reach
2529                                      ExistPredSet.factory(rg.predTrue),                       // predicates
2530                                      tempDesc.toString()                       // description
2531                                      );
2532         rg.id2hrn.put(as.getSummary(),hrnSummary);
2533         mapToExistingNode.put(typeDesc, hrnSummary);
2534         RefEdge edgeToSummary = new RefEdge(prevNode,             // source
2535                                             hrnSummary, // dest
2536                                             typeDesc, // type
2537                                             arrayElementFieldName, // field name
2538                                             alpha, // beta
2539                                             ExistPredSet.factory(rg.predTrue),             // predicates
2540                                             null
2541                                             );
2542         rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2543         prevNode=hrnSummary;
2544       } else {
2545         HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
2546         if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null) {
2547           RefEdge edgeToSummary = new RefEdge(prevNode,               // source
2548                                               hrnSummary, // dest
2549                                               typeDesc, // type
2550                                               arrayElementFieldName, // field name
2551                                               alpha, // beta
2552                                               ExistPredSet.factory(rg.predTrue),               // predicates
2553                                               null
2554                                               );
2555           rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2556         }
2557         prevNode=hrnSummary;
2558       }
2559     }
2560
2561     map.put(arrayEntryNode, prevNode);
2562     return arrayEntryNode;
2563   }
2564
2565   private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
2566     ReachGraph rg = new ReachGraph();
2567     TaskDescriptor taskDesc = fm.getTask();
2568
2569     for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
2570       Descriptor paramDesc = taskDesc.getParameter(idx);
2571       TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
2572
2573       // setup data structure
2574       Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
2575         new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
2576       Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
2577         new Hashtable<TypeDescriptor, HeapRegionNode>();
2578       Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
2579         new Hashtable<HeapRegionNode, HeapRegionNode>();
2580       Set<String> doneSet = new HashSet<String>();
2581
2582       TempDescriptor tempDesc = fm.getParameter(idx);
2583
2584       AllocSite as = createParameterAllocSite(rg, tempDesc, true);
2585       VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
2586       Integer idNewest = as.getIthOldest(0);
2587       HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
2588
2589       // make a new reference to allocated node
2590       RefEdge edgeNew = new RefEdge(lnX,   // source
2591                                     hrnNewest,   // dest
2592                                     taskDesc.getParamType(idx),   // type
2593                                     null,   // field name
2594                                     hrnNewest.getAlpha(),   // beta
2595                                     ExistPredSet.factory(rg.predTrue),   // predicates
2596                                     null
2597                                     );
2598       rg.addRefEdge(lnX, hrnNewest, edgeNew);
2599
2600       // set-up a work set for class field
2601       ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
2602       for (Iterator it = classDesc.getFields(); it.hasNext(); ) {
2603         FieldDescriptor fd = (FieldDescriptor) it.next();
2604         TypeDescriptor fieldType = fd.getType();
2605         if (shouldAnalysisTrack(fieldType)) {
2606           HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
2607           newMap.put(hrnNewest, fd);
2608           workSet.add(newMap);
2609         }
2610       }
2611
2612       int uniqueIdentifier = 0;
2613       while (!workSet.isEmpty()) {
2614         HashMap<HeapRegionNode, FieldDescriptor> map = workSet
2615                                                        .iterator().next();
2616         workSet.remove(map);
2617
2618         Set<HeapRegionNode> key = map.keySet();
2619         HeapRegionNode srcHRN = key.iterator().next();
2620         FieldDescriptor fd = map.get(srcHRN);
2621         TypeDescriptor type = fd.getType();
2622         String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
2623
2624         if (!doneSet.contains(doneSetIdentifier)) {
2625           doneSet.add(doneSetIdentifier);
2626           if (!mapTypeToExistingSummaryNode.containsKey(type)) {
2627             // create new summary Node
2628             TempDescriptor td = new TempDescriptor("temp"
2629                                                    + uniqueIdentifier, type);
2630
2631             AllocSite allocSite;
2632             if(type.equals(paramTypeDesc)) {
2633               //corresponding allocsite has already been created for a parameter variable.
2634               allocSite=as;
2635             } else {
2636               allocSite = createParameterAllocSite(rg, td, false);
2637             }
2638             String strDesc = allocSite.toStringForDOT()
2639                              + "\\nsummary";
2640             TypeDescriptor allocType=allocSite.getType();
2641
2642             HeapRegionNode hrnSummary;
2643             if(allocType.isArray() && allocType.getArrayCount()>0) {
2644               hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
2645             } else {
2646               hrnSummary =
2647                 rg.createNewHeapRegionNode(allocSite.getSummary(),                         // id or null to generate a new one
2648                                            false,                         // single object?
2649                                            true,                         // summary?
2650                                            false,                         // out-of-context?
2651                                            allocSite.getType(),                         // type
2652                                            allocSite,                         // allocation site
2653                                            hrnNewest.getAlpha(),                         // inherent reach
2654                                            hrnNewest.getAlpha(),                         // current reach
2655                                            ExistPredSet.factory(rg.predTrue),                         // predicates
2656                                            strDesc                         // description
2657                                            );
2658               rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
2659
2660               // make a new reference to summary node
2661               RefEdge edgeToSummary = new RefEdge(srcHRN,       // source
2662                                                   hrnSummary,       // dest
2663                                                   type,       // type
2664                                                   fd.getSymbol(),       // field name
2665                                                   hrnNewest.getAlpha(),       // beta
2666                                                   ExistPredSet.factory(rg.predTrue),       // predicates
2667                                                   null
2668                                                   );
2669
2670               rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2671             }
2672             uniqueIdentifier++;
2673
2674             mapTypeToExistingSummaryNode.put(type, hrnSummary);
2675
2676             // set-up a work set for  fields of the class
2677             Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
2678             for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
2679                  .hasNext(); ) {
2680               FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
2681                                                 .next();
2682               HeapRegionNode newDstHRN;
2683               if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)) {
2684                 //related heap region node is already exsited.
2685                 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
2686               } else {
2687                 newDstHRN=hrnSummary;
2688               }
2689               doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
2690               if(!doneSet.contains(doneSetIdentifier)) {
2691                 // add new work item
2692                 HashMap<HeapRegionNode, FieldDescriptor> newMap =
2693                   new HashMap<HeapRegionNode, FieldDescriptor>();
2694                 newMap.put(newDstHRN, fieldDescriptor);
2695                 workSet.add(newMap);
2696               }
2697             }
2698
2699           } else {
2700             // if there exists corresponding summary node
2701             HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
2702
2703             RefEdge edgeToSummary = new RefEdge(srcHRN,         // source
2704                                                 hrnDst,         // dest
2705                                                 fd.getType(),         // type
2706                                                 fd.getSymbol(),         // field name
2707                                                 srcHRN.getAlpha(),         // beta
2708                                                 ExistPredSet.factory(rg.predTrue),         // predicates
2709                                                 null
2710                                                 );
2711             rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
2712
2713           }
2714         }
2715       }
2716     }
2717
2718     return rg;
2719   }
2720
2721 // return all allocation sites in the method (there is one allocation
2722 // site per FlatNew node in a method)
2723   private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
2724     if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
2725       buildAllocationSiteSet(d);
2726     }
2727
2728     return mapDescriptorToAllocSiteSet.get(d);
2729
2730   }
2731
2732   private void buildAllocationSiteSet(Descriptor d) {
2733     HashSet<AllocSite> s = new HashSet<AllocSite>();
2734
2735     FlatMethod fm;
2736     if( d instanceof MethodDescriptor ) {
2737       fm = state.getMethodFlat( (MethodDescriptor) d);
2738     } else {
2739       assert d instanceof TaskDescriptor;
2740       fm = state.getMethodFlat( (TaskDescriptor) d);
2741     }
2742     pm.analyzeMethod(fm);
2743
2744     // visit every node in this FlatMethod's IR graph
2745     // and make a set of the allocation sites from the
2746     // FlatNew node's visited
2747     HashSet<FlatNode> visited = new HashSet<FlatNode>();
2748     HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
2749     toVisit.add(fm);
2750
2751     while( !toVisit.isEmpty() ) {
2752       FlatNode n = toVisit.iterator().next();
2753
2754       if( n instanceof FlatNew ) {
2755         s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
2756       }
2757
2758       toVisit.remove(n);
2759       visited.add(n);
2760
2761       for( int i = 0; i < pm.numNext(n); ++i ) {
2762         FlatNode child = pm.getNext(n, i);
2763         if( !visited.contains(child) ) {
2764           toVisit.add(child);
2765         }
2766       }
2767     }
2768
2769     mapDescriptorToAllocSiteSet.put(d, s);
2770   }
2771
2772   private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
2773
2774     HashSet<AllocSite> out = new HashSet<AllocSite>();
2775     HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2776     HashSet<Descriptor> visited = new HashSet<Descriptor>();
2777
2778     toVisit.add(dIn);
2779
2780     while (!toVisit.isEmpty()) {
2781       Descriptor d = toVisit.iterator().next();
2782       toVisit.remove(d);
2783       visited.add(d);
2784
2785       HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2786       Iterator asItr = asSet.iterator();
2787       while (asItr.hasNext()) {
2788         AllocSite as = (AllocSite) asItr.next();
2789         if (as.getDisjointAnalysisId() != null) {
2790           out.add(as);
2791         }
2792       }
2793
2794       // enqueue callees of this method to be searched for
2795       // allocation sites also
2796       Set callees = callGraph.getCalleeSet(d);
2797       if (callees != null) {
2798         Iterator methItr = callees.iterator();
2799         while (methItr.hasNext()) {
2800           MethodDescriptor md = (MethodDescriptor) methItr.next();
2801
2802           if (!visited.contains(md)) {
2803             toVisit.add(md);
2804           }
2805         }
2806       }
2807     }
2808
2809     return out;
2810   }
2811
2812
2813   private HashSet<AllocSite>
2814   getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
2815
2816     HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
2817     HashSet<Descriptor>     toVisit    = new HashSet<Descriptor>();
2818     HashSet<Descriptor>     visited    = new HashSet<Descriptor>();
2819
2820     toVisit.add(td);
2821
2822     // traverse this task and all methods reachable from this task
2823     while( !toVisit.isEmpty() ) {
2824       Descriptor d = toVisit.iterator().next();
2825       toVisit.remove(d);
2826       visited.add(d);
2827
2828       HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2829       Iterator asItr = asSet.iterator();
2830       while( asItr.hasNext() ) {
2831         AllocSite as = (AllocSite) asItr.next();
2832         TypeDescriptor typed = as.getType();
2833         if( typed != null ) {
2834           ClassDescriptor cd = typed.getClassDesc();
2835           if( cd != null && cd.hasFlags() ) {
2836             asSetTotal.add(as);
2837           }
2838         }
2839       }
2840
2841       // enqueue callees of this method to be searched for
2842       // allocation sites also
2843       Set callees = callGraph.getCalleeSet(d);
2844       if( callees != null ) {
2845         Iterator methItr = callees.iterator();
2846         while( methItr.hasNext() ) {
2847           MethodDescriptor md = (MethodDescriptor) methItr.next();
2848
2849           if( !visited.contains(md) ) {
2850             toVisit.add(md);
2851           }
2852         }
2853       }
2854     }
2855
2856     return asSetTotal;
2857   }
2858
2859   public Set<Descriptor> getDescriptorsToAnalyze() {
2860     return descriptorsToAnalyze;
2861   }
2862
2863   public EffectsAnalysis getEffectsAnalysis() {
2864     return effectsAnalysis;
2865   }
2866
2867   public ReachGraph getReachGraph(Descriptor d) {
2868     return mapDescriptorToCompleteReachGraph.get(d);
2869   }
2870
2871   public ReachGraph getEnterReachGraph(FlatNode fn) {
2872     return fn2rgAtEnter.get(fn);
2873   }
2874
2875   // get successive captures of the analysis state, use compiler
2876   // flags to control
2877   boolean takeDebugSnapshots = false;
2878   String descSymbolDebug    = null;
2879   boolean stopAfterCapture   = false;
2880   int snapVisitCounter   = 0;
2881   int snapNodeCounter    = 0;
2882   int visitStartCapture  = 0;
2883   int numVisitsToCapture = 0;
2884
2885
2886   void debugSnapshot(ReachGraph rg, FlatNode fn, boolean in) {
2887     if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2888       return;
2889     }
2890
2891     if( in ) {
2892
2893     }
2894
2895     if( snapVisitCounter >= visitStartCapture ) {
2896       System.out.println("    @@@ snapping visit="+snapVisitCounter+
2897                          ", node="+snapNodeCounter+
2898                          " @@@");
2899       String graphName;
2900       if( in ) {
2901         graphName = String.format("snap%03d_%04din",
2902                                   snapVisitCounter,
2903                                   snapNodeCounter);
2904       } else {
2905         graphName = String.format("snap%03d_%04dout",
2906                                   snapVisitCounter,
2907                                   snapNodeCounter);
2908       }
2909       if( fn != null ) {
2910         graphName = graphName + fn;
2911       }
2912       rg.writeGraph(graphName,
2913                     true,    // write labels (variables)
2914                     true,    // selectively hide intermediate temp vars
2915                     true,    // prune unreachable heap regions
2916                     false,   // hide reachability
2917                     false,   // hide subset reachability states
2918                     true,    // hide predicates
2919                     true);   // hide edge taints
2920     }
2921   }
2922
2923
2924
2925
2926   public Set<Alloc> canPointToAt( TempDescriptor x,
2927                                   FlatNode programPoint ) {
2928
2929     ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
2930     if( rgAtEnter == null ) {
2931       return null; 
2932     }
2933
2934     return rgAtEnter.canPointTo( x );
2935   }
2936
2937
2938   public Set<Alloc> canPointToAfter( TempDescriptor x,
2939                                      FlatNode programPoint ) {
2940
2941     ReachGraph rgAtExit = fn2rgAtExit.get( programPoint );
2942     if( rgAtExit == null ) {
2943       return null; 
2944     }
2945
2946     return rgAtExit.canPointTo( x );
2947   }
2948   
2949
2950   public Hashtable< Alloc, Set<Alloc> > canPointToAt( TempDescriptor x,
2951                                                       FieldDescriptor f,
2952                                                       FlatNode programPoint ) {
2953
2954     ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
2955     if( rgAtEnter == null ) {
2956       return null; 
2957     }
2958     
2959     return rgAtEnter.canPointTo( x, f.getSymbol(), f.getType() );
2960   }
2961
2962
2963   public Hashtable< Alloc, Set<Alloc> > canPointToAtElement( TempDescriptor x,
2964                                                              FlatNode programPoint ) {
2965
2966     ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
2967     if( rgAtEnter == null ) {
2968       return null; 
2969     }
2970
2971     assert x.getType() != null;
2972     assert x.getType().isArray();
2973
2974     return rgAtEnter.canPointTo( x, arrayElementFieldName, x.getType().dereference() );
2975   }
2976 }