1 package Analysis.Disjoint;
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.*;
11 import IR.Tree.Modifiers;
16 public class DisjointAnalysis implements HeapAnalysis {
18 ///////////////////////////////////////////
20 // Public interface to discover possible
21 // sharing in the program under analysis
23 ///////////////////////////////////////////
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,
33 AllocSite asr1 = getAllocationSiteFromFlatNew(fnRoot1);
34 AllocSite asr2 = getAllocationSiteFromFlatNew(fnRoot2);
35 assert asr1.isFlagged();
36 assert asr2.isFlagged();
38 AllocSite ast = getAllocationSiteFromFlatNew(fnTarget);
39 ReachGraph rg = getPartial(fm.getMethod() );
41 return rg.mayBothReachTarget(asr1, asr2, ast);
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,
51 AllocSite asr = getAllocationSiteFromFlatNew(fnRoot);
52 assert asr.isFlagged();
54 AllocSite ast = getAllocationSiteFromFlatNew(fnTarget);
55 ReachGraph rg = getPartial(fm.getMethod() );
57 return rg.mayManyReachTarget(asr, ast);
63 public HashSet<AllocSite>
64 getFlaggedAllocationSitesReachableFromTask(TaskDescriptor td) {
65 checkAnalysisComplete();
66 return getFlaggedAllocationSitesReachableFromTaskPRIVATE(td);
69 public AllocSite getAllocationSiteFromFlatNew(FlatNew fn) {
70 checkAnalysisComplete();
71 return getAllocSiteFromFlatNewPRIVATE(fn);
74 public AllocSite getAllocationSiteFromHeapRegionNodeID(Integer id) {
75 checkAnalysisComplete();
76 return mapHrnIdToAllocSite.get(id);
79 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
82 checkAnalysisComplete();
83 ReachGraph rg=mapDescriptorToCompleteReachGraph.get(taskOrMethod);
84 FlatMethod fm=state.getMethodFlat(taskOrMethod);
86 return rg.mayReachSharedObjects(fm, paramIndex1, paramIndex2);
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);
95 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
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);
104 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
107 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
108 AllocSite alloc1, AllocSite alloc2) {
109 checkAnalysisComplete();
110 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
112 return rg.mayReachSharedObjects(alloc1, alloc2);
115 public String prettyPrintNodeSet(Set<HeapRegionNode> s) {
116 checkAnalysisComplete();
120 Iterator<HeapRegionNode> i = s.iterator();
121 while (i.hasNext()) {
122 HeapRegionNode n = i.next();
124 AllocSite as = n.getAllocSite();
126 out += " " + n.toString() + ",\n";
128 out += " " + n.toString() + ": " + as.toStringVerbose()
137 // use the methods given above to check every possible sharing class
138 // between task parameters and flagged allocation sites reachable
140 public void writeAllSharing(String outputFile,
143 boolean tabularOutput,
146 throws java.io.IOException {
147 checkAnalysisComplete();
149 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
151 if (!tabularOutput) {
152 bw.write("Conducting ownership analysis with allocation depth = "
153 + allocationDepth + "\n");
154 bw.write(timeReport + "\n");
159 // look through every task for potential sharing
160 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
161 while (taskItr.hasNext()) {
162 TaskDescriptor td = (TaskDescriptor) taskItr.next();
164 if (!tabularOutput) {
165 bw.write("\n---------" + td + "--------\n");
168 HashSet<AllocSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
170 Set<HeapRegionNode> common;
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;
177 FlatMethod fm = state.getMethodFlat(td);
178 for (int i = 0; i < fm.numParameters(); ++i) {
180 // skip parameters with types that cannot reference
182 if( !shouldAnalysisTrack(fm.getParameter(i).getType() ) ) {
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) {
190 // skip parameters with types that cannot reference
192 if( !shouldAnalysisTrack(fm.getParameter(j).getType() ) ) {
197 common = hasPotentialSharing(td, i, j);
198 if (!common.isEmpty()) {
199 foundSomeSharing = true;
201 if (!tabularOutput) {
202 bw.write("Potential sharing between parameters " + i
203 + " and " + j + ".\n");
204 bw.write(prettyPrintNodeSet(common) + "\n");
209 // for the ith parameter, check for sharing classes against
210 // the set of allocation sites reachable from this
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;
219 if (!tabularOutput) {
220 bw.write("Potential sharing between parameter " + i
221 + " and " + as.getFlatNew() + ".\n");
222 bw.write(prettyPrintNodeSet(common) + "\n");
228 // for each allocation site check for sharing classes with
229 // other allocation sites in the context of execution
231 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
232 Iterator allocItr1 = allocSites.iterator();
233 while (allocItr1.hasNext()) {
234 AllocSite as1 = (AllocSite) allocItr1.next();
236 Iterator allocItr2 = allocSites.iterator();
237 while (allocItr2.hasNext()) {
238 AllocSite as2 = (AllocSite) allocItr2.next();
240 if (!outerChecked.contains(as2)) {
241 common = hasPotentialSharing(td, as1, as2);
243 if (!common.isEmpty()) {
244 foundSomeSharing = true;
246 if (!tabularOutput) {
247 bw.write("Potential sharing between "
248 + as1.getFlatNew() + " and "
249 + as2.getFlatNew() + ".\n");
250 bw.write(prettyPrintNodeSet(common) + "\n");
256 outerChecked.add(as1);
259 if (!foundSomeSharing) {
260 if (!tabularOutput) {
261 bw.write("No sharing between flagged objects in Task " + td
269 bw.write(" & " + numSharing + " & " + justTime + " & " + numLines
270 + " & " + numMethodsAnalyzed() + " \\\\\n");
272 bw.write("\nNumber sharing classes: "+numSharing);
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,
289 boolean tabularOutput,
292 throws java.io.IOException {
293 checkAnalysisComplete();
299 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
301 bw.write("Conducting disjoint reachability analysis with allocation depth = "
302 + allocationDepth + "\n");
303 bw.write(timeReport + "\n\n");
305 boolean foundSomeSharing = false;
307 Descriptor d = typeUtil.getMain();
308 HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
310 // for each allocation site check for sharing classes with
311 // other allocation sites in the context of execution
313 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
314 Iterator allocItr1 = allocSites.iterator();
315 while (allocItr1.hasNext()) {
316 AllocSite as1 = (AllocSite) allocItr1.next();
318 Iterator allocItr2 = allocSites.iterator();
319 while (allocItr2.hasNext()) {
320 AllocSite as2 = (AllocSite) allocItr2.next();
322 if (!outerChecked.contains(as2)) {
323 Set<HeapRegionNode> common = hasPotentialSharing(d,
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");
337 outerChecked.add(as1);
340 if (!foundSomeSharing) {
341 bw.write("No sharing classes between flagged objects found.\n");
343 bw.write("\nNumber sharing classes: "+numSharing);
346 bw.write("Number of methods analyzed: "+numMethodsAnalyzed()+"\n");
353 public Alloc getCmdLineArgsAlloc() {
354 return getAllocationSiteFromFlatNew( constructedCmdLineArgsNew );
356 public Alloc getCmdLineArgAlloc() {
357 return getAllocationSiteFromFlatNew( constructedCmdLineArgNew );
359 public Alloc getCmdLineArgBytesAlloc() {
360 return getAllocationSiteFromFlatNew( constructedCmdLineArgBytesNew );
362 public Alloc getNewStringLiteralAlloc() {
363 return newStringLiteralAlloc;
365 public Alloc getNewStringLiteralBytesAlloc() {
366 return newStringLiteralBytesAlloc;
369 ///////////////////////////////////////////
371 // end public interface
373 ///////////////////////////////////////////
377 protected void checkAnalysisComplete() {
378 if( !analysisComplete ) {
379 throw new Error("Warning: public interface method called while analysis is running.");
388 // run in faster mode, only when bugs wrung out!
389 public static boolean releaseMode;
391 // use command line option to set this, analysis
392 // should attempt to be deterministic
393 public static boolean determinismDesired;
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();
402 // data from the compiler
404 public CallGraph callGraph;
405 public Liveness liveness;
406 public ArrayReferencees arrayReferencees;
407 public RBlockRelationAnalysis rblockRel;
408 public TypeUtil typeUtil;
409 public int allocationDepth;
411 protected boolean doEffectsAnalysis = false;
412 protected EffectsAnalysis effectsAnalysis;
413 protected BuildStateMachines buildStateMachines;
416 // data structure for public interface
417 private Hashtable< Descriptor, HashSet<AllocSite> >
418 mapDescriptorToAllocSiteSet;
421 // for public interface methods to warn that they
422 // are grabbing results during analysis
423 private boolean analysisComplete;
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
431 // start at 10 and increment to reserve some
432 // IDs for special purposes
433 static protected int uniqueIDcount = 10;
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;
446 // main method defined by source program
447 protected MethodDescriptor mdSourceEntry;
449 // the set of task and/or method descriptors
450 // reachable in call graph
451 protected Set<Descriptor>
452 descriptorsToAnalyze;
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>
462 // a duplication of the above structure, but
463 // for efficient testing of inclusion
464 protected HashSet<Descriptor>
465 descriptorsToVisitSet;
467 // storage for priorities (doesn't make sense)
468 // to add it to the Descriptor class, just in
470 protected Hashtable<Descriptor, Integer>
471 mapDescriptorToPriority;
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>
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
485 protected Hashtable<Descriptor, ReachGraph>
486 mapDescriptorToCompleteReachGraph;
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;
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;
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;
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>
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;
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;
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;
532 public static final String arrayElementFieldName = "___element_";
533 static protected Hashtable<TypeDescriptor, FieldDescriptor>
537 protected boolean suppressOutput;
539 // for controlling DOT file output
540 protected boolean writeFinalDOTs;
541 protected boolean writeAllIncrementalDOTs;
543 // supporting DOT output--when we want to write every
544 // partial method result, keep a tally for generating
546 protected Hashtable<Descriptor, Integer>
547 mapDescriptorToNumUpdates;
549 //map task descriptor to initial task parameter
550 protected Hashtable<Descriptor, ReachGraph>
551 mapDescriptorToReachGraph;
553 protected PointerMethod pm;
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>();
560 static protected Hashtable<FlatNode, ReachGraph> fn2rgAtExit =
561 new Hashtable<FlatNode, ReachGraph>();
564 private Hashtable<FlatCall, Descriptor> fc2enclosing;
566 Accessible accessible;
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;
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;
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;
592 protected void initImplicitStringsModel() {
594 ClassDescriptor cdString = typeUtil.getClass( typeUtil.StringClass );
595 assert cdString != null;
599 new TypeDescriptor( cdString );
602 new TypeDescriptor(TypeDescriptor.CHAR).makeArray( state );
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;
614 assert stringBytesField != null;
617 TempDescriptor throwAway1 =
618 new TempDescriptor("stringLiteralTemp_dummy1",
621 FlatNew fnStringLiteral =
622 new FlatNew(stringType,
626 newStringLiteralAlloc
627 = getAllocSiteFromFlatNewPRIVATE( fnStringLiteral );
630 TempDescriptor throwAway2 =
631 new TempDescriptor("stringLiteralTemp_dummy2",
634 FlatNew fnStringLiteralBytes =
635 new FlatNew(stringBytesType,
639 newStringLiteralBytesAlloc
640 = getAllocSiteFromFlatNewPRIVATE( fnStringLiteralBytes );
646 // allocate various structures that are not local
647 // to a single class method--should be done once
648 protected void allocateStructures() {
650 if( determinismDesired ) {
651 // use an ordered set
652 descriptorsToAnalyze = new TreeSet<Descriptor>(dComp);
654 // otherwise use a speedy hashset
655 descriptorsToAnalyze = new HashSet<Descriptor>();
658 mapDescriptorToCompleteReachGraph =
659 new Hashtable<Descriptor, ReachGraph>();
661 mapDescriptorToNumUpdates =
662 new Hashtable<Descriptor, Integer>();
664 mapDescriptorToSetDependents =
665 new Hashtable< Descriptor, Set<Descriptor> >();
667 mapFlatNewToAllocSite =
668 new Hashtable<FlatNew, AllocSite>();
670 mapDescriptorToIHMcontributions =
671 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
673 mapDescriptorToInitialContext =
674 new Hashtable<Descriptor, ReachGraph>();
676 mapBackEdgeToMonotone =
677 new Hashtable<FlatNode, ReachGraph>();
679 mapHrnIdToAllocSite =
680 new Hashtable<Integer, AllocSite>();
682 mapTypeToArrayField =
683 new Hashtable <TypeDescriptor, FieldDescriptor>();
685 if( state.DISJOINTDVISITSTACK ||
686 state.DISJOINTDVISITSTACKEESONTOP
688 descriptorsToVisitStack =
689 new Stack<Descriptor>();
692 if( state.DISJOINTDVISITPQUE ) {
693 descriptorsToVisitQ =
694 new PriorityQueue<DescriptorQWrapper>();
697 descriptorsToVisitSet =
698 new HashSet<Descriptor>();
700 mapDescriptorToPriority =
701 new Hashtable<Descriptor, Integer>();
704 new HashSet<Descriptor>();
706 mapDescriptorToAllocSiteSet =
707 new Hashtable<Descriptor, HashSet<AllocSite> >();
709 mapDescriptorToReachGraph =
710 new Hashtable<Descriptor, ReachGraph>();
712 pm = new PointerMethod();
714 fc2enclosing = new Hashtable<FlatCall, Descriptor>();
719 // this analysis generates a disjoint reachability
720 // graph for every reachable method in the program
721 public DisjointAnalysis(State s,
726 Set<FlatNew> sitesToFlag,
727 RBlockRelationAnalysis rra
729 init(s, tu, cg, l, ar, sitesToFlag, rra, null, false);
732 public DisjointAnalysis(State s,
737 Set<FlatNew> sitesToFlag,
738 RBlockRelationAnalysis rra,
739 boolean suppressOutput
741 init(s, tu, cg, l, ar, sitesToFlag, rra, null, suppressOutput);
744 public DisjointAnalysis(State s,
749 Set<FlatNew> sitesToFlag,
750 RBlockRelationAnalysis rra,
751 BuildStateMachines bsm,
752 boolean suppressOutput
754 init(s, tu, cg, l, ar, sitesToFlag, rra, bsm, suppressOutput);
757 protected void init(State state,
761 ArrayReferencees arrayReferencees,
762 Set<FlatNew> sitesToFlag,
763 RBlockRelationAnalysis rra,
764 BuildStateMachines bsm,
765 boolean suppressOutput
768 analysisComplete = false;
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;
780 if( rblockRel != null ) {
781 doEffectsAnalysis = true;
782 effectsAnalysis = new EffectsAnalysis();
784 EffectsAnalysis.state = state;
785 EffectsAnalysis.buildStateMachines = buildStateMachines;
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();
793 this.allocationDepth = state.DISJOINTALLOCDEPTH;
794 this.releaseMode = state.DISJOINTRELEASEMODE;
795 this.determinismDesired = state.DISJOINTDETERMINISM;
797 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
798 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL;
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
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);
816 // set some static configuration for ReachGraphs
817 ReachGraph.allocationDepth = allocationDepth;
818 ReachGraph.typeUtil = typeUtil;
819 ReachGraph.state = state;
821 ReachGraph.initOutOfScopeTemps();
823 ReachGraph.debugCallSiteVisitStartCapture
824 = state.DISJOINTDEBUGCALLVISITTOSTART;
826 ReachGraph.debugCallSiteNumVisitsToCapture
827 = state.DISJOINTDEBUGCALLNUMVISITS;
829 ReachGraph.debugCallSiteStopAfter
830 = state.DISJOINTDEBUGCALLSTOPAFTER;
832 ReachGraph.debugCallSiteVisitCounter
833 = 0; // count visits from 1, is incremented before first visit
837 if( suppressOutput ) {
838 System.out.println("* Running disjoint reachability analysis with output suppressed! *");
842 allocateStructures();
844 initImplicitStringsModel();
848 double timeStartAnalysis = (double) System.nanoTime();
850 // start interprocedural fixed-point computation
853 } catch( IOException e ) {
854 throw new Error("IO Exception while writing disjointness analysis output.");
857 analysisComplete=true;
859 double timeEndAnalysis = (double) System.nanoTime();
860 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow(10.0, 9.0) );
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();
869 treport = String.format("Disjoint reachability analysis took %.3f sec.", dt);
871 String justtime = String.format("%.2f", dt);
872 System.out.println(treport);
876 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
880 if( state.DISJOINTWRITEIHMS && !suppressOutput ) {
884 if( state.DISJOINTWRITEINITCONTEXTS && !suppressOutput ) {
885 writeInitialContexts();
888 if( state.DISJOINTALIASFILE != null && !suppressOutput ) {
890 writeAllSharing(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
892 writeAllSharingJava(state.DISJOINTALIASFILE,
895 state.DISJOINTALIASTAB,
902 buildStateMachines.writeStateMachines();
905 } catch( IOException e ) {
906 throw new Error("IO Exception while writing disjointness analysis output.");
911 protected boolean moreDescriptorsToVisit() {
912 if( state.DISJOINTDVISITSTACK ||
913 state.DISJOINTDVISITSTACKEESONTOP
915 return !descriptorsToVisitStack.isEmpty();
917 } else if( state.DISJOINTDVISITPQUE ) {
918 return !descriptorsToVisitQ.isEmpty();
921 throw new Error("Neither descriptor visiting mode set");
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 {
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
934 if( !suppressOutput ) {
935 System.out.println("Bamboo mode...");
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
944 descriptorsToAnalyze.add(td);
945 descriptorsToAnalyze.addAll(callGraph.getAllMethods(td) );
950 if( !suppressOutput ) {
951 System.out.println("Java mode...");
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) );
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);
969 // now, depending on the interprocedural mode for visiting
970 // methods, set up the needed data structures
972 if( state.DISJOINTDVISITPQUE ) {
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);
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
983 Iterator<Descriptor> dItr;
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);
995 } else if( state.DISJOINTDVISITSTACK ||
996 state.DISJOINTDVISITSTACKEESONTOP
998 // if we're doing the stack scheme, just throw the root
999 // method or tasks on the stack
1001 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
1002 while( taskItr.hasNext() ) {
1003 TaskDescriptor td = (TaskDescriptor) taskItr.next();
1004 descriptorsToVisitStack.add(td);
1005 descriptorsToVisitSet.add(td);
1009 descriptorsToVisitStack.add(mdAnalysisEntry);
1010 descriptorsToVisitSet.add(mdAnalysisEntry);
1014 throw new Error("Unknown method scheduling mode");
1018 // analyze scheduled methods until there are no more to visit
1019 while( moreDescriptorsToVisit() ) {
1020 Descriptor d = null;
1022 if( state.DISJOINTDVISITSTACK ||
1023 state.DISJOINTDVISITSTACKEESONTOP
1025 d = descriptorsToVisitStack.pop();
1027 } else if( state.DISJOINTDVISITPQUE ) {
1028 d = descriptorsToVisitQ.poll().getDescriptor();
1031 assert descriptorsToVisitSet.contains(d);
1032 descriptorsToVisitSet.remove(d);
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.
1042 if( !suppressOutput ) {
1043 System.out.println("Analyzing " + d);
1046 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1047 assert calleesToEnqueue.isEmpty();
1050 ReachGraph rg = analyzeMethod(d);
1051 ReachGraph rgPrev = getPartial(d);
1053 if( !rg.equals(rgPrev) ) {
1056 if( state.DISJOINTDEBUGSCHEDULING ) {
1057 System.out.println(" complete graph changed, scheduling callers for analysis:");
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();
1067 if( state.DISJOINTDEBUGSCHEDULING ) {
1068 System.out.println(" "+dNext);
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();
1084 calleesToEnqueue.clear();
1090 protected ReachGraph analyzeMethod(Descriptor d)
1091 throws java.io.IOException {
1093 // get the flat code for this descriptor
1095 if( d == mdAnalysisEntry ) {
1096 fm = fmAnalysisEntry;
1098 fm = state.getMethodFlat(d);
1100 pm.analyzeMethod(fm);
1102 // intraprocedural work set
1103 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
1104 flatNodesToVisit.add(fm);
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);
1114 // mapping of current partial results
1115 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
1116 new Hashtable<FlatNode, ReachGraph>();
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>();
1124 boolean snapThisMethod = false;
1125 if( takeDebugSnapshots && d instanceof MethodDescriptor ) {
1126 MethodDescriptor mdThisMethod = (MethodDescriptor)d;
1127 ClassDescriptor cdThisMethod = mdThisMethod.getClassDesc();
1128 if( cdThisMethod != null ) {
1130 descSymbolDebug.equals( cdThisMethod.getSymbol()+
1132 mdThisMethod.getSymbol()
1139 while( !flatNodesToVisit.isEmpty() ) {
1142 if( determinismDesired ) {
1143 assert !flatNodesToVisitQ.isEmpty();
1144 fn = flatNodesToVisitQ.remove();
1146 fn = flatNodesToVisit.iterator().next();
1148 flatNodesToVisit.remove(fn);
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.
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);
1161 // create initial reach graph for a task
1162 rg=createInitialTaskReachGraph((FlatMethod)fn);
1164 mapDescriptorToReachGraph.put(taskDesc, rg);
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);
1178 if( snapThisMethod ) {
1179 debugSnapshot(rg, fn, true);
1183 // modify rg with appropriate transfer function
1184 rg = analyzeFlatNode(d, fm, fn, setReturns, rg);
1187 if( snapThisMethod ) {
1188 debugSnapshot(rg, fn, false);
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);
1200 for( int i = 0; i < pm.numNext(fn); i++ ) {
1201 FlatNode nn = pm.getNext(fn, i);
1203 flatNodesToVisit.add(nn);
1204 if( determinismDesired ) {
1205 flatNodesToVisitQ.add(nn);
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();
1217 assert !setReturns.isEmpty();
1218 Iterator retItr = setReturns.iterator();
1219 while( retItr.hasNext() ) {
1220 FlatReturnNode frn = (FlatReturnNode) retItr.next();
1222 assert mapFlatNodeToReachGraph.containsKey(frn);
1223 ReachGraph rgRet = mapFlatNodeToReachGraph.get(frn);
1225 completeGraph.merge(rgRet);
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);
1234 snapNodeCounter = 0;
1236 if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
1239 System.out.println("!!! Stopping analysis after debug snap captures. !!!");
1245 return completeGraph;
1249 protected ReachGraph
1250 analyzeFlatNode(Descriptor d,
1251 FlatMethod fmContaining,
1253 HashSet<FlatReturnNode> setRetNodes,
1255 ) throws java.io.IOException {
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 ) );
1264 FieldDescriptor fld;
1265 TypeDescriptor tdElement;
1266 FieldDescriptor fdElement;
1267 FlatSESEEnterNode sese;
1268 FlatSESEExitNode fsexn;
1270 //Stores the flatnode's reach graph at enter
1271 ReachGraph rgOnEnter = new ReachGraph();
1272 rgOnEnter.merge(rg);
1273 fn2rgAtEnter.put(fn, rgOnEnter);
1277 // use node type to decide what transfer function
1278 // to apply to the reachability graph
1279 switch( fn.kind() ) {
1281 case FKind.FlatGenReachNode: {
1282 FlatGenReachNode fgrn = (FlatGenReachNode) fn;
1284 System.out.println(" Generating reach graph for program point: "+fgrn.getGraphName() );
1287 rg.writeGraph("genReach"+fgrn.getGraphName(),
1288 true, // write labels (variables)
1289 false, //true, // selectively hide intermediate temp vars
1290 true, // prune unreachable heap regions
1291 true, // hide reachability altogether
1292 true, // hide subset reachability states
1293 true, // hide predicates
1294 true); //false); // hide edge taints
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
1303 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1304 getIHMcontributions(d);
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();
1313 // note that "fc.getMethod()" like (Object.toString)
1314 // might not be equal to "d" like (String.toString)
1315 // because the mapping gets set up when we resolve
1317 rg.merge(rgContrib);
1320 // additionally, we are enforcing STRICT MONOTONICITY for the
1321 // method's initial context, so grow the context by whatever
1322 // the previously computed context was, and put the most
1323 // up-to-date context back in the map
1324 ReachGraph rgPrevContext = mapDescriptorToInitialContext.get(d);
1325 rg.merge(rgPrevContext);
1326 mapDescriptorToInitialContext.put(d, rg);
1330 case FKind.FlatOpNode:
1331 FlatOpNode fon = (FlatOpNode) fn;
1332 if( fon.getOp().getOp() == Operation.ASSIGN ) {
1333 lhs = fon.getDest();
1334 rhs = fon.getLeft();
1336 // before transfer, do effects analysis support
1337 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1338 if(rblockRel.isPotentialStallSite(fn)) {
1339 // x gets status of y
1340 // if(!rg.isAccessible(rhs)){
1341 if(!accessible.isAccessible(fn, rhs)) {
1342 rg.makeInaccessible(lhs);
1348 rg.assignTempXEqualToTempY(lhs, rhs);
1352 case FKind.FlatCastNode:
1353 FlatCastNode fcn = (FlatCastNode) fn;
1357 TypeDescriptor td = fcn.getType();
1360 // before transfer, do effects analysis support
1361 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1362 if(rblockRel.isPotentialStallSite(fn)) {
1363 // x gets status of y
1364 // if(!rg.isAccessible(rhs)){
1365 if(!accessible.isAccessible(fn,rhs)) {
1366 rg.makeInaccessible(lhs);
1372 rg.assignTempXEqualToCastedTempY(lhs, rhs, td);
1375 case FKind.FlatFieldNode:
1376 FlatFieldNode ffn = (FlatFieldNode) fn;
1380 fld = ffn.getField();
1382 // before graph transform, possible inject
1383 // a stall-site taint
1384 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1386 if(rblockRel.isPotentialStallSite(fn)) {
1387 // x=y.f, stall y if not accessible
1388 // contributes read effects on stall site of y
1389 // if(!rg.isAccessible(rhs)) {
1390 if(!accessible.isAccessible(fn,rhs)) {
1391 rg.taintStallSite(fn, rhs);
1394 // after this, x and y are accessbile.
1395 rg.makeAccessible(lhs);
1396 rg.makeAccessible(rhs);
1400 if( shouldAnalysisTrack(fld.getType() ) ) {
1402 rg.assignTempXEqualToTempYFieldF(lhs, rhs, fld, fn);
1405 // after transfer, use updated graph to
1406 // do effects analysis
1407 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1408 effectsAnalysis.analyzeFlatFieldNode(rg, rhs, fld, fn);
1412 case FKind.FlatSetFieldNode:
1413 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
1415 lhs = fsfn.getDst();
1416 fld = fsfn.getField();
1417 rhs = fsfn.getSrc();
1419 boolean strongUpdate = false;
1421 // before transfer func, possibly inject
1422 // stall-site taints
1423 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1425 if(rblockRel.isPotentialStallSite(fn)) {
1426 // x.y=f , stall x and y if they are not accessible
1427 // also contribute write effects on stall site of x
1428 // if(!rg.isAccessible(lhs)) {
1429 if(!accessible.isAccessible(fn,lhs)) {
1430 rg.taintStallSite(fn, lhs);
1433 // if(!rg.isAccessible(rhs)) {
1434 if(!accessible.isAccessible(fn,rhs)) {
1435 rg.taintStallSite(fn, rhs);
1438 // accessible status update
1439 rg.makeAccessible(lhs);
1440 rg.makeAccessible(rhs);
1444 if( shouldAnalysisTrack(fld.getType() ) ) {
1446 strongUpdate = rg.assignTempXFieldFEqualToTempY(lhs, fld, rhs, fn);
1449 // use transformed graph to do effects analysis
1450 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1451 effectsAnalysis.analyzeFlatSetFieldNode(rg, lhs, fld, fn, strongUpdate);
1455 case FKind.FlatElementNode:
1456 FlatElementNode fen = (FlatElementNode) fn;
1461 assert rhs.getType() != null;
1462 assert rhs.getType().isArray();
1464 tdElement = rhs.getType().dereference();
1465 fdElement = getArrayField(tdElement);
1467 // before transfer func, possibly inject
1469 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1470 if(rblockRel.isPotentialStallSite(fn)) {
1471 // x=y.f, stall y if not accessible
1472 // contributes read effects on stall site of y
1473 // after this, x and y are accessbile.
1474 // if(!rg.isAccessible(rhs)) {
1475 if(!accessible.isAccessible(fn,rhs)) {
1476 rg.taintStallSite(fn, rhs);
1479 rg.makeAccessible(lhs);
1480 rg.makeAccessible(rhs);
1484 if( shouldAnalysisTrack(lhs.getType() ) ) {
1486 rg.assignTempXEqualToTempYFieldF(lhs, rhs, fdElement, fn);
1489 // use transformed graph to do effects analysis
1490 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1491 effectsAnalysis.analyzeFlatFieldNode(rg, rhs, fdElement, fn);
1495 case FKind.FlatSetElementNode:
1496 FlatSetElementNode fsen = (FlatSetElementNode) fn;
1498 lhs = fsen.getDst();
1499 rhs = fsen.getSrc();
1501 assert lhs.getType() != null;
1502 assert lhs.getType().isArray();
1504 tdElement = lhs.getType().dereference();
1505 fdElement = getArrayField(tdElement);
1507 // before transfer func, possibly inject
1508 // stall-site taints
1509 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1511 if(rblockRel.isPotentialStallSite(fn)) {
1512 // x.y=f , stall x and y if they are not accessible
1513 // also contribute write effects on stall site of x
1514 // if(!rg.isAccessible(lhs)) {
1515 if(!accessible.isAccessible(fn,lhs)) {
1516 rg.taintStallSite(fn, lhs);
1519 // if(!rg.isAccessible(rhs)) {
1520 if(!accessible.isAccessible(fn,rhs)) {
1521 rg.taintStallSite(fn, rhs);
1524 // accessible status update
1525 rg.makeAccessible(lhs);
1526 rg.makeAccessible(rhs);
1530 if( shouldAnalysisTrack(rhs.getType() ) ) {
1531 // transfer func, BUT
1532 // skip this node if it cannot create new reachability paths
1533 if( !arrayReferencees.doesNotCreateNewReaching(fsen) ) {
1534 rg.assignTempXFieldFEqualToTempY(lhs, fdElement, rhs, fn);
1538 // use transformed graph to do effects analysis
1539 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1540 effectsAnalysis.analyzeFlatSetFieldNode(rg, lhs, fdElement, fn,
1546 FlatNew fnn = (FlatNew) fn;
1548 if( shouldAnalysisTrack(lhs.getType() ) ) {
1549 AllocSite as = getAllocSiteFromFlatNewPRIVATE(fnn);
1551 // before transform, support effects analysis
1552 if (doEffectsAnalysis && fmContaining != fmAnalysisEntry) {
1553 if (rblockRel.isPotentialStallSite(fn)) {
1554 // after creating new object, lhs is accessible
1555 rg.makeAccessible(lhs);
1560 rg.assignTempEqualToNewAlloc(lhs, as);
1565 case FKind.FlatLiteralNode:
1566 // BIG NOTE: this transfer function is only here for
1567 // points-to information for String literals. That's it.
1568 // Effects and disjoint reachability and all of that don't
1569 // care about references to literals.
1570 FlatLiteralNode fln = (FlatLiteralNode) fn;
1572 if( fln.getType().equals( stringType ) ) {
1573 rg.assignTempEqualToStringLiteral( fln.getDst(),
1574 newStringLiteralAlloc,
1575 newStringLiteralBytesAlloc,
1581 case FKind.FlatSESEEnterNode:
1582 sese = (FlatSESEEnterNode) fn;
1584 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1586 // always remove ALL stall site taints at enter
1587 rg.removeAllStallSiteTaints();
1589 // inject taints for in-set vars
1590 rg.taintInSetVars(sese);
1595 case FKind.FlatSESEExitNode:
1596 fsexn = (FlatSESEExitNode) fn;
1597 sese = fsexn.getFlatEnter();
1599 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1601 // @ sese exit make all live variables
1602 // inaccessible to later parent statements
1603 rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) );
1605 // always remove ALL stall site taints at exit
1606 rg.removeAllStallSiteTaints();
1608 // remove in-set var taints for the exiting rblock
1609 rg.removeInContextTaints(sese);
1614 case FKind.FlatCall: {
1615 Descriptor mdCaller;
1616 if( fmContaining.getMethod() != null ) {
1617 mdCaller = fmContaining.getMethod();
1619 mdCaller = fmContaining.getTask();
1621 FlatCall fc = (FlatCall) fn;
1622 MethodDescriptor mdCallee = fc.getMethod();
1623 FlatMethod fmCallee = state.getMethodFlat(mdCallee);
1627 // the transformation for a call site should update the
1628 // current heap abstraction with any effects from the callee,
1629 // or if the method is virtual, the effects from any possible
1630 // callees, so find the set of callees...
1631 Set<MethodDescriptor> setPossibleCallees;
1632 if( determinismDesired ) {
1633 // use an ordered set
1634 setPossibleCallees = new TreeSet<MethodDescriptor>(dComp);
1636 // otherwise use a speedy hashset
1637 setPossibleCallees = new HashSet<MethodDescriptor>();
1640 if( mdCallee.isStatic() ) {
1641 setPossibleCallees.add(mdCallee);
1643 TypeDescriptor typeDesc = fc.getThis().getType();
1644 setPossibleCallees.addAll(callGraph.getMethods(mdCallee,
1650 DebugCallSiteData dcsd = new DebugCallSiteData();
1652 ReachGraph rgMergeOfPossibleCallers = new ReachGraph();
1655 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
1656 while( mdItr.hasNext() ) {
1657 MethodDescriptor mdPossible = mdItr.next();
1658 FlatMethod fmPossible = state.getMethodFlat(mdPossible);
1660 addDependent(mdPossible, // callee
1664 // decide for each possible resolution of the method whether we
1665 // want to debug this call site
1666 decideDebugCallSite( dcsd, mdCaller, mdPossible );
1670 // calculate the heap this call site can reach--note this is
1671 // not used for the current call site transform, we are
1672 // grabbing this heap model for future analysis of the callees,
1673 // so if different results emerge we will return to this site
1674 ReachGraph heapForThisCall_old =
1675 getIHMcontribution(mdPossible, fc);
1677 // the computation of the callee-reachable heap
1678 // is useful for making the callee starting point
1679 // and for applying the call site transfer function
1680 Set<Integer> callerNodeIDsCopiedToCallee =
1681 new HashSet<Integer>();
1683 ReachGraph heapForThisCall_cur =
1684 rg.makeCalleeView(fc,
1686 callerNodeIDsCopiedToCallee,
1690 // enforce that a call site contribution can only
1691 // monotonically increase
1692 heapForThisCall_cur.merge(heapForThisCall_old);
1694 if( !heapForThisCall_cur.equals(heapForThisCall_old) ) {
1695 // if heap at call site changed, update the contribution,
1696 // and reschedule the callee for analysis
1697 addIHMcontribution(mdPossible, fc, heapForThisCall_cur);
1699 // map a FlatCall to its enclosing method/task descriptor
1700 // so we can write that info out later
1701 fc2enclosing.put(fc, mdCaller);
1703 if( state.DISJOINTDEBUGSCHEDULING ) {
1704 System.out.println(" context changed, scheduling callee: "+mdPossible);
1707 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1708 calleesToEnqueue.add(mdPossible);
1710 enqueue(mdPossible);
1717 // don't alter the working graph (rg) until we compute a
1718 // result for every possible callee, merge them all together,
1719 // then set rg to that
1720 ReachGraph rgPossibleCaller = new ReachGraph();
1721 rgPossibleCaller.merge(rg);
1723 ReachGraph rgPossibleCallee = getPartial(mdPossible);
1725 if( rgPossibleCallee == null ) {
1726 // if this method has never been analyzed just schedule it
1727 // for analysis and skip over this call site for now
1728 if( state.DISJOINTDVISITSTACKEESONTOP ) {
1729 calleesToEnqueue.add(mdPossible);
1731 enqueue(mdPossible);
1734 if( state.DISJOINTDEBUGSCHEDULING ) {
1735 System.out.println(" callee hasn't been analyzed, scheduling: "+mdPossible);
1741 // calculate the method call transform
1742 rgPossibleCaller.resolveMethodCall(fc,
1745 callerNodeIDsCopiedToCallee,
1750 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1751 if( !accessible.isAccessible(fn, ReachGraph.tdReturn) ) {
1752 rgPossibleCaller.makeInaccessible(fc.getReturnTemp() );
1758 rgMergeOfPossibleCallers.merge(rgPossibleCaller);
1762 statusDebugCallSite( dcsd );
1765 // now that we've taken care of building heap models for
1766 // callee analysis, finish this transformation
1767 rg = rgMergeOfPossibleCallers;
1770 // jjenista: what is this? It breaks compilation
1771 // of programs with no tasks/SESEs/rblocks...
1772 //XXXXXXXXXXXXXXXXXXXXXXXXX
1773 //need to consider more
1774 if( state.OOOJAVA ) {
1775 FlatNode nextFN=fmCallee.getNext(0);
1776 if( nextFN instanceof FlatSESEEnterNode ) {
1777 FlatSESEEnterNode calleeSESE=(FlatSESEEnterNode)nextFN;
1778 if(!calleeSESE.getIsLeafSESE()) {
1779 rg.makeInaccessible(liveness.getLiveInTemps(fmContaining, fn) );
1787 case FKind.FlatReturnNode:
1788 FlatReturnNode frn = (FlatReturnNode) fn;
1789 rhs = frn.getReturnTemp();
1791 // before transfer, do effects analysis support
1792 if( doEffectsAnalysis && fmContaining != fmAnalysisEntry ) {
1793 // if(!rg.isAccessible(rhs)){
1794 if(!accessible.isAccessible(fn,rhs)) {
1795 rg.makeInaccessible(ReachGraph.tdReturn);
1799 if( rhs != null && shouldAnalysisTrack(rhs.getType() ) ) {
1800 rg.assignReturnEqualToTemp(rhs);
1803 setRetNodes.add(frn);
1809 // dead variables were removed before the above transfer function
1810 // was applied, so eliminate heap regions and edges that are no
1811 // longer part of the abstractly-live heap graph, and sweep up
1812 // and reachability effects that are altered by the reduction
1813 //rg.abstractGarbageCollect();
1817 // back edges are strictly monotonic
1818 if( pm.isBackEdge(fn) ) {
1819 ReachGraph rgPrevResult = mapBackEdgeToMonotone.get(fn);
1820 rg.merge(rgPrevResult);
1821 mapBackEdgeToMonotone.put(fn, rg);
1825 ReachGraph rgOnExit = new ReachGraph();
1827 fn2rgAtExit.put(fn, rgOnExit);
1830 // at this point rg should be the correct update
1831 // by an above transfer function, or untouched if
1832 // the flat node type doesn't affect the heap
1838 // this method should generate integers strictly greater than zero!
1839 // special "shadow" regions are made from a heap region by negating
1841 static public Integer generateUniqueHeapRegionNodeID() {
1843 return new Integer(uniqueIDcount);
1848 static public FieldDescriptor getArrayField(TypeDescriptor tdElement) {
1849 FieldDescriptor fdElement = mapTypeToArrayField.get(tdElement);
1850 if( fdElement == null ) {
1851 fdElement = new FieldDescriptor(new Modifiers(Modifiers.PUBLIC),
1853 arrayElementFieldName,
1856 mapTypeToArrayField.put(tdElement, fdElement);
1863 private void writeFinalGraphs() {
1864 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1865 Iterator itr = entrySet.iterator();
1866 while( itr.hasNext() ) {
1867 Map.Entry me = (Map.Entry)itr.next();
1868 Descriptor d = (Descriptor) me.getKey();
1869 ReachGraph rg = (ReachGraph) me.getValue();
1872 if( d instanceof TaskDescriptor ) {
1873 graphName = "COMPLETEtask"+d;
1875 graphName = "COMPLETE"+d;
1878 rg.writeGraph(graphName,
1879 true, // write labels (variables)
1880 true, // selectively hide intermediate temp vars
1881 true, // prune unreachable heap regions
1882 true, // hide reachability altogether
1883 true, // hide subset reachability states
1884 true, // hide predicates
1885 false); // hide edge taints
1889 private void writeFinalIHMs() {
1890 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1891 while( d2IHMsItr.hasNext() ) {
1892 Map.Entry me1 = (Map.Entry)d2IHMsItr.next();
1893 Descriptor d = (Descriptor) me1.getKey();
1894 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>)me1.getValue();
1896 Iterator fc2rgItr = IHMs.entrySet().iterator();
1897 while( fc2rgItr.hasNext() ) {
1898 Map.Entry me2 = (Map.Entry)fc2rgItr.next();
1899 FlatCall fc = (FlatCall) me2.getKey();
1900 ReachGraph rg = (ReachGraph) me2.getValue();
1902 rg.writeGraph("IHMPARTFOR"+d+"FROM"+fc2enclosing.get(fc)+fc,
1903 true, // write labels (variables)
1904 true, // selectively hide intermediate temp vars
1905 true, // hide reachability altogether
1906 true, // prune unreachable heap regions
1907 true, // hide subset reachability states
1908 false, // hide predicates
1909 true); // hide edge taints
1914 private void writeInitialContexts() {
1915 Set entrySet = mapDescriptorToInitialContext.entrySet();
1916 Iterator itr = entrySet.iterator();
1917 while( itr.hasNext() ) {
1918 Map.Entry me = (Map.Entry)itr.next();
1919 Descriptor d = (Descriptor) me.getKey();
1920 ReachGraph rg = (ReachGraph) me.getValue();
1922 rg.writeGraph("INITIAL"+d,
1923 true, // write labels (variables)
1924 true, // selectively hide intermediate temp vars
1925 true, // prune unreachable heap regions
1926 false, // hide all reachability
1927 true, // hide subset reachability states
1928 true, // hide predicates
1929 false); // hide edge taints
1934 protected ReachGraph getPartial(Descriptor d) {
1935 return mapDescriptorToCompleteReachGraph.get(d);
1938 protected void setPartial(Descriptor d, ReachGraph rg) {
1939 mapDescriptorToCompleteReachGraph.put(d, rg);
1941 // when the flag for writing out every partial
1942 // result is set, we should spit out the graph,
1943 // but in order to give it a unique name we need
1944 // to track how many partial results for this
1945 // descriptor we've already written out
1946 if( writeAllIncrementalDOTs ) {
1947 if( !mapDescriptorToNumUpdates.containsKey(d) ) {
1948 mapDescriptorToNumUpdates.put(d, new Integer(0) );
1950 Integer n = mapDescriptorToNumUpdates.get(d);
1953 if( d instanceof TaskDescriptor ) {
1954 graphName = d+"COMPLETEtask"+String.format("%05d", n);
1956 graphName = d+"COMPLETE"+String.format("%05d", n);
1959 rg.writeGraph(graphName,
1960 true, // write labels (variables)
1961 true, // selectively hide intermediate temp vars
1962 true, // prune unreachable heap regions
1963 false, // hide all reachability
1964 true, // hide subset reachability states
1965 false, // hide predicates
1966 false); // hide edge taints
1968 mapDescriptorToNumUpdates.put(d, n + 1);
1974 // return just the allocation site associated with one FlatNew node
1975 protected AllocSite getAllocSiteFromFlatNewPRIVATE(FlatNew fnew) {
1977 boolean flagProgrammatically = false;
1978 if( sitesToFlag != null && sitesToFlag.contains(fnew) ) {
1979 flagProgrammatically = true;
1982 if( !mapFlatNewToAllocSite.containsKey(fnew) ) {
1983 AllocSite as = AllocSite.factory(allocationDepth,
1985 fnew.getDisjointId(),
1986 flagProgrammatically
1989 // the newest nodes are single objects
1990 for( int i = 0; i < allocationDepth; ++i ) {
1991 Integer id = generateUniqueHeapRegionNodeID();
1992 as.setIthOldest(i, id);
1993 mapHrnIdToAllocSite.put(id, as);
1996 // the oldest node is a summary node
1997 as.setSummary(generateUniqueHeapRegionNodeID() );
1999 mapFlatNewToAllocSite.put(fnew, as);
2002 return mapFlatNewToAllocSite.get(fnew);
2006 public static boolean shouldAnalysisTrack(TypeDescriptor type) {
2007 // don't track primitive types, but an array
2008 // of primitives is heap memory
2009 if( type.isImmutable() ) {
2010 return type.isArray();
2013 // everything else is an object
2017 protected int numMethodsAnalyzed() {
2018 return descriptorsToAnalyze.size();
2024 // Take in source entry which is the program's compiled entry and
2025 // create a new analysis entry, a method that takes no parameters
2026 // and appears to allocate the command line arguments and call the
2027 // source entry with them. The purpose of this analysis entry is
2028 // to provide a top-level method context with no parameters left.
2029 protected void makeAnalysisEntryMethod(MethodDescriptor mdSourceEntry) {
2031 Modifiers mods = new Modifiers();
2032 mods.addModifier(Modifiers.PUBLIC);
2033 mods.addModifier(Modifiers.STATIC);
2035 TypeDescriptor returnType = new TypeDescriptor(TypeDescriptor.VOID);
2037 this.mdAnalysisEntry =
2038 new MethodDescriptor(mods,
2040 "analysisEntryMethod"
2043 TypeDescriptor argsType = mdSourceEntry.getParamType(0);
2044 TempDescriptor cmdLineArgs =
2045 new TempDescriptor("analysisEntryTemp_args",
2049 new FlatNew(argsType,
2053 this.constructedCmdLineArgsNew = fnArgs;
2055 TypeDescriptor argType = argsType.dereference();
2056 TempDescriptor anArg =
2057 new TempDescriptor("analysisEntryTemp_arg",
2061 new FlatNew(argType,
2065 this.constructedCmdLineArgNew = fnArg;
2067 TypeDescriptor typeIndex = new TypeDescriptor(TypeDescriptor.INT);
2068 TempDescriptor index =
2069 new TempDescriptor("analysisEntryTemp_index",
2072 FlatLiteralNode fli =
2073 new FlatLiteralNode(typeIndex,
2078 FlatSetElementNode fse =
2079 new FlatSetElementNode(cmdLineArgs,
2084 TypeDescriptor typeSize = new TypeDescriptor(TypeDescriptor.INT);
2085 TempDescriptor sizeBytes =
2086 new TempDescriptor("analysisEntryTemp_size",
2089 FlatLiteralNode fls =
2090 new FlatLiteralNode(typeSize,
2095 TempDescriptor strBytes =
2096 new TempDescriptor("analysisEntryTemp_strBytes",
2100 new FlatNew(stringBytesType,
2105 this.constructedCmdLineArgBytesNew = fnBytes;
2107 FlatSetFieldNode fsf =
2108 new FlatSetFieldNode(anArg,
2113 // throw this in so you can always see what the initial heap context
2114 // looks like if you want to, its cheap
2115 FlatGenReachNode fgen = new FlatGenReachNode( "argContext" );
2117 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
2118 sourceEntryArgs[0] = cmdLineArgs;
2120 new FlatCall(mdSourceEntry,
2126 FlatReturnNode frn = new FlatReturnNode(null);
2128 FlatExit fe = new FlatExit();
2130 this.fmAnalysisEntry =
2131 new FlatMethod(mdAnalysisEntry,
2135 List<FlatNode> nodes = new LinkedList<FlatNode>();
2136 nodes.add( fnArgs );
2141 nodes.add( fnBytes );
2148 FlatNode current = this.fmAnalysisEntry;
2149 for( FlatNode next: nodes ) {
2150 current.addNext( next );
2155 // jjenista - this is useful for looking at the FlatIRGraph of the
2156 // analysis entry method constructed above if you have to modify it.
2157 // The usual method of writing FlatIRGraphs out doesn't work because
2158 // this flat method is private to the model of this analysis only.
2160 // FlatIRGraph flatMethodWriter =
2161 // new FlatIRGraph( state, false, false, false );
2162 // flatMethodWriter.writeFlatIRGraph( fmAnalysisEntry, "analysisEntry" );
2163 //} catch( IOException e ) {}
2167 protected LinkedList<Descriptor> topologicalSort(Set<Descriptor> toSort) {
2169 Set<Descriptor> discovered;
2171 if( determinismDesired ) {
2172 // use an ordered set
2173 discovered = new TreeSet<Descriptor>(dComp);
2175 // otherwise use a speedy hashset
2176 discovered = new HashSet<Descriptor>();
2179 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
2181 Iterator<Descriptor> itr = toSort.iterator();
2182 while( itr.hasNext() ) {
2183 Descriptor d = itr.next();
2185 if( !discovered.contains(d) ) {
2186 dfsVisit(d, toSort, sorted, discovered);
2193 // While we're doing DFS on call graph, remember
2194 // dependencies for efficient queuing of methods
2195 // during interprocedural analysis:
2197 // a dependent of a method decriptor d for this analysis is:
2198 // 1) a method or task that invokes d
2199 // 2) in the descriptorsToAnalyze set
2200 protected void dfsVisit(Descriptor d,
2201 Set <Descriptor> toSort,
2202 LinkedList<Descriptor> sorted,
2203 Set <Descriptor> discovered) {
2206 // only methods have callers, tasks never do
2207 if( d instanceof MethodDescriptor ) {
2209 MethodDescriptor md = (MethodDescriptor) d;
2211 // the call graph is not aware that we have a fabricated
2212 // analysis entry that calls the program source's entry
2213 if( md == mdSourceEntry ) {
2214 if( !discovered.contains(mdAnalysisEntry) ) {
2215 addDependent(mdSourceEntry, // callee
2216 mdAnalysisEntry // caller
2218 dfsVisit(mdAnalysisEntry, toSort, sorted, discovered);
2222 // otherwise call graph guides DFS
2223 Iterator itr = callGraph.getCallerSet(md).iterator();
2224 while( itr.hasNext() ) {
2225 Descriptor dCaller = (Descriptor) itr.next();
2227 // only consider callers in the original set to analyze
2228 if( !toSort.contains(dCaller) ) {
2232 if( !discovered.contains(dCaller) ) {
2233 addDependent(md, // callee
2237 dfsVisit(dCaller, toSort, sorted, discovered);
2242 // for leaf-nodes last now!
2247 protected void enqueue(Descriptor d) {
2249 if( !descriptorsToVisitSet.contains(d) ) {
2251 if( state.DISJOINTDVISITSTACK ||
2252 state.DISJOINTDVISITSTACKEESONTOP
2254 descriptorsToVisitStack.add(d);
2256 } else if( state.DISJOINTDVISITPQUE ) {
2257 Integer priority = mapDescriptorToPriority.get(d);
2258 descriptorsToVisitQ.add(new DescriptorQWrapper(priority,
2263 descriptorsToVisitSet.add(d);
2268 // a dependent of a method decriptor d for this analysis is:
2269 // 1) a method or task that invokes d
2270 // 2) in the descriptorsToAnalyze set
2271 protected void addDependent(Descriptor callee, Descriptor caller) {
2272 Set<Descriptor> deps = mapDescriptorToSetDependents.get(callee);
2273 if( deps == null ) {
2274 deps = new HashSet<Descriptor>();
2277 mapDescriptorToSetDependents.put(callee, deps);
2280 protected Set<Descriptor> getDependents(Descriptor callee) {
2281 Set<Descriptor> deps = mapDescriptorToSetDependents.get(callee);
2282 if( deps == null ) {
2283 deps = new HashSet<Descriptor>();
2284 mapDescriptorToSetDependents.put(callee, deps);
2290 public Hashtable<FlatCall, ReachGraph> getIHMcontributions(Descriptor d) {
2292 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2293 mapDescriptorToIHMcontributions.get(d);
2295 if( heapsFromCallers == null ) {
2296 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
2297 mapDescriptorToIHMcontributions.put(d, heapsFromCallers);
2300 return heapsFromCallers;
2303 public ReachGraph getIHMcontribution(Descriptor d,
2306 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2307 getIHMcontributions(d);
2309 if( !heapsFromCallers.containsKey(fc) ) {
2313 return heapsFromCallers.get(fc);
2317 public void addIHMcontribution(Descriptor d,
2321 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
2322 getIHMcontributions(d);
2324 heapsFromCallers.put(fc, rg);
2328 private AllocSite createParameterAllocSite(ReachGraph rg,
2329 TempDescriptor tempDesc,
2335 flatNew = new FlatNew(tempDesc.getType(), // type
2336 tempDesc, // param temp
2337 false, // global alloc?
2338 "param"+tempDesc // disjoint site ID string
2341 flatNew = new FlatNew(tempDesc.getType(), // type
2342 tempDesc, // param temp
2343 false, // global alloc?
2344 null // disjoint site ID string
2348 // create allocation site
2349 AllocSite as = AllocSite.factory(allocationDepth,
2351 flatNew.getDisjointId(),
2354 for (int i = 0; i < allocationDepth; ++i) {
2355 Integer id = generateUniqueHeapRegionNodeID();
2356 as.setIthOldest(i, id);
2357 mapHrnIdToAllocSite.put(id, as);
2359 // the oldest node is a summary node
2360 as.setSummary(generateUniqueHeapRegionNodeID() );
2368 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc) {
2370 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
2371 if(!typeDesc.isImmutable()) {
2372 ClassDescriptor classDesc = typeDesc.getClassDesc();
2373 for (Iterator it = classDesc.getFields(); it.hasNext(); ) {
2374 FieldDescriptor field = (FieldDescriptor) it.next();
2375 TypeDescriptor fieldType = field.getType();
2376 if (shouldAnalysisTrack(fieldType)) {
2377 fieldSet.add(field);
2385 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha) {
2387 int dimCount=fd.getType().getArrayCount();
2388 HeapRegionNode prevNode=null;
2389 HeapRegionNode arrayEntryNode=null;
2390 for(int i=dimCount; i>0; i--) {
2391 TypeDescriptor typeDesc=fd.getType().dereference(); //hack to get instance of type desc
2392 typeDesc.setArrayCount(i);
2393 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
2394 HeapRegionNode hrnSummary;
2395 if(!mapToExistingNode.containsKey(typeDesc)) {
2400 as = createParameterAllocSite(rg, tempDesc, false);
2402 // make a new reference to allocated node
2404 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
2405 false, // single object?
2407 false, // out-of-context?
2408 as.getType(), // type
2409 as, // allocation site
2410 alpha, // inherent reach
2411 alpha, // current reach
2412 ExistPredSet.factory(rg.predTrue), // predicates
2413 tempDesc.toString() // description
2415 rg.id2hrn.put(as.getSummary(),hrnSummary);
2417 mapToExistingNode.put(typeDesc, hrnSummary);
2419 hrnSummary=mapToExistingNode.get(typeDesc);
2422 if(prevNode==null) {
2423 // make a new reference between new summary node and source
2424 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2427 fd.getSymbol(), // field name
2429 ExistPredSet.factory(rg.predTrue), // predicates
2433 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2434 prevNode=hrnSummary;
2435 arrayEntryNode=hrnSummary;
2437 // make a new reference between summary nodes of array
2438 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2441 arrayElementFieldName, // field name
2443 ExistPredSet.factory(rg.predTrue), // predicates
2447 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2448 prevNode=hrnSummary;
2453 // create a new obj node if obj has at least one non-primitive field
2454 TypeDescriptor type=fd.getType();
2455 if(getFieldSetTobeAnalyzed(type).size()>0) {
2456 TypeDescriptor typeDesc=type.dereference();
2457 typeDesc.setArrayCount(0);
2458 if(!mapToExistingNode.containsKey(typeDesc)) {
2459 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
2460 AllocSite as = createParameterAllocSite(rg, tempDesc, false);
2461 // make a new reference to allocated node
2462 HeapRegionNode hrnSummary =
2463 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
2464 false, // single object?
2466 false, // out-of-context?
2468 as, // allocation site
2469 alpha, // inherent reach
2470 alpha, // current reach
2471 ExistPredSet.factory(rg.predTrue), // predicates
2472 tempDesc.toString() // description
2474 rg.id2hrn.put(as.getSummary(),hrnSummary);
2475 mapToExistingNode.put(typeDesc, hrnSummary);
2476 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2479 arrayElementFieldName, // field name
2481 ExistPredSet.factory(rg.predTrue), // predicates
2484 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2485 prevNode=hrnSummary;
2487 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
2488 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null) {
2489 RefEdge edgeToSummary = new RefEdge(prevNode, // source
2492 arrayElementFieldName, // field name
2494 ExistPredSet.factory(rg.predTrue), // predicates
2497 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
2499 prevNode=hrnSummary;
2503 map.put(arrayEntryNode, prevNode);
2504 return arrayEntryNode;
2507 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
2508 ReachGraph rg = new ReachGraph();
2509 TaskDescriptor taskDesc = fm.getTask();
2511 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
2512 Descriptor paramDesc = taskDesc.getParameter(idx);
2513 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
2515 // setup data structure
2516 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
2517 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
2518 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
2519 new Hashtable<TypeDescriptor, HeapRegionNode>();
2520 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
2521 new Hashtable<HeapRegionNode, HeapRegionNode>();
2522 Set<String> doneSet = new HashSet<String>();
2524 TempDescriptor tempDesc = fm.getParameter(idx);
2526 AllocSite as = createParameterAllocSite(rg, tempDesc, true);
2527 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
2528 Integer idNewest = as.getIthOldest(0);
2529 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
2531 // make a new reference to allocated node
2532 RefEdge edgeNew = new RefEdge(lnX, // source
2534 taskDesc.getParamType(idx), // type
2536 hrnNewest.getAlpha(), // beta
2537 ExistPredSet.factory(rg.predTrue), // predicates
2540 rg.addRefEdge(lnX, hrnNewest, edgeNew);
2542 // set-up a work set for class field
2543 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
2544 for (Iterator it = classDesc.getFields(); it.hasNext(); ) {
2545 FieldDescriptor fd = (FieldDescriptor) it.next();
2546 TypeDescriptor fieldType = fd.getType();
2547 if (shouldAnalysisTrack(fieldType)) {
2548 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
2549 newMap.put(hrnNewest, fd);
2550 workSet.add(newMap);
2554 int uniqueIdentifier = 0;
2555 while (!workSet.isEmpty()) {
2556 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
2558 workSet.remove(map);
2560 Set<HeapRegionNode> key = map.keySet();
2561 HeapRegionNode srcHRN = key.iterator().next();
2562 FieldDescriptor fd = map.get(srcHRN);
2563 TypeDescriptor type = fd.getType();
2564 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
2566 if (!doneSet.contains(doneSetIdentifier)) {
2567 doneSet.add(doneSetIdentifier);
2568 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
2569 // create new summary Node
2570 TempDescriptor td = new TempDescriptor("temp"
2571 + uniqueIdentifier, type);
2573 AllocSite allocSite;
2574 if(type.equals(paramTypeDesc)) {
2575 //corresponding allocsite has already been created for a parameter variable.
2578 allocSite = createParameterAllocSite(rg, td, false);
2580 String strDesc = allocSite.toStringForDOT()
2582 TypeDescriptor allocType=allocSite.getType();
2584 HeapRegionNode hrnSummary;
2585 if(allocType.isArray() && allocType.getArrayCount()>0) {
2586 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
2589 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
2590 false, // single object?
2592 false, // out-of-context?
2593 allocSite.getType(), // type
2594 allocSite, // allocation site
2595 hrnNewest.getAlpha(), // inherent reach
2596 hrnNewest.getAlpha(), // current reach
2597 ExistPredSet.factory(rg.predTrue), // predicates
2598 strDesc // description
2600 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
2602 // make a new reference to summary node
2603 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2606 fd.getSymbol(), // field name
2607 hrnNewest.getAlpha(), // beta
2608 ExistPredSet.factory(rg.predTrue), // predicates
2612 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
2616 mapTypeToExistingSummaryNode.put(type, hrnSummary);
2618 // set-up a work set for fields of the class
2619 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
2620 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
2622 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
2624 HeapRegionNode newDstHRN;
2625 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)) {
2626 //related heap region node is already exsited.
2627 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
2629 newDstHRN=hrnSummary;
2631 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
2632 if(!doneSet.contains(doneSetIdentifier)) {
2633 // add new work item
2634 HashMap<HeapRegionNode, FieldDescriptor> newMap =
2635 new HashMap<HeapRegionNode, FieldDescriptor>();
2636 newMap.put(newDstHRN, fieldDescriptor);
2637 workSet.add(newMap);
2642 // if there exists corresponding summary node
2643 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
2645 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
2647 fd.getType(), // type
2648 fd.getSymbol(), // field name
2649 srcHRN.getAlpha(), // beta
2650 ExistPredSet.factory(rg.predTrue), // predicates
2653 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
2663 // return all allocation sites in the method (there is one allocation
2664 // site per FlatNew node in a method)
2665 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
2666 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
2667 buildAllocationSiteSet(d);
2670 return mapDescriptorToAllocSiteSet.get(d);
2674 private void buildAllocationSiteSet(Descriptor d) {
2675 HashSet<AllocSite> s = new HashSet<AllocSite>();
2678 if( d instanceof MethodDescriptor ) {
2679 fm = state.getMethodFlat( (MethodDescriptor) d);
2681 assert d instanceof TaskDescriptor;
2682 fm = state.getMethodFlat( (TaskDescriptor) d);
2684 pm.analyzeMethod(fm);
2686 // visit every node in this FlatMethod's IR graph
2687 // and make a set of the allocation sites from the
2688 // FlatNew node's visited
2689 HashSet<FlatNode> visited = new HashSet<FlatNode>();
2690 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
2693 while( !toVisit.isEmpty() ) {
2694 FlatNode n = toVisit.iterator().next();
2696 if( n instanceof FlatNew ) {
2697 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
2703 for( int i = 0; i < pm.numNext(n); ++i ) {
2704 FlatNode child = pm.getNext(n, i);
2705 if( !visited.contains(child) ) {
2711 mapDescriptorToAllocSiteSet.put(d, s);
2714 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
2716 HashSet<AllocSite> out = new HashSet<AllocSite>();
2717 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2718 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2722 while (!toVisit.isEmpty()) {
2723 Descriptor d = toVisit.iterator().next();
2727 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2728 Iterator asItr = asSet.iterator();
2729 while (asItr.hasNext()) {
2730 AllocSite as = (AllocSite) asItr.next();
2731 if (as.getDisjointAnalysisId() != null) {
2736 // enqueue callees of this method to be searched for
2737 // allocation sites also
2738 Set callees = callGraph.getCalleeSet(d);
2739 if (callees != null) {
2740 Iterator methItr = callees.iterator();
2741 while (methItr.hasNext()) {
2742 MethodDescriptor md = (MethodDescriptor) methItr.next();
2744 if (!visited.contains(md)) {
2755 private HashSet<AllocSite>
2756 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
2758 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
2759 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
2760 HashSet<Descriptor> visited = new HashSet<Descriptor>();
2764 // traverse this task and all methods reachable from this task
2765 while( !toVisit.isEmpty() ) {
2766 Descriptor d = toVisit.iterator().next();
2770 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
2771 Iterator asItr = asSet.iterator();
2772 while( asItr.hasNext() ) {
2773 AllocSite as = (AllocSite) asItr.next();
2774 TypeDescriptor typed = as.getType();
2775 if( typed != null ) {
2776 ClassDescriptor cd = typed.getClassDesc();
2777 if( cd != null && cd.hasFlags() ) {
2783 // enqueue callees of this method to be searched for
2784 // allocation sites also
2785 Set callees = callGraph.getCalleeSet(d);
2786 if( callees != null ) {
2787 Iterator methItr = callees.iterator();
2788 while( methItr.hasNext() ) {
2789 MethodDescriptor md = (MethodDescriptor) methItr.next();
2791 if( !visited.contains(md) ) {
2801 public Set<Descriptor> getDescriptorsToAnalyze() {
2802 return descriptorsToAnalyze;
2805 public EffectsAnalysis getEffectsAnalysis() {
2806 return effectsAnalysis;
2809 public ReachGraph getReachGraph(Descriptor d) {
2810 return mapDescriptorToCompleteReachGraph.get(d);
2813 public ReachGraph getEnterReachGraph(FlatNode fn) {
2814 return fn2rgAtEnter.get(fn);
2819 protected class DebugCallSiteData {
2820 public boolean debugCallSite;
2821 public boolean didOneDebug;
2822 public boolean writeDebugDOTs;
2823 public boolean stopAfter;
2825 public DebugCallSiteData() {
2826 debugCallSite = false;
2827 didOneDebug = false;
2828 writeDebugDOTs = false;
2833 protected void decideDebugCallSite( DebugCallSiteData dcsd,
2834 Descriptor taskOrMethodCaller,
2835 MethodDescriptor mdCallee ) {
2837 // all this jimma jamma to debug call sites is WELL WORTH the
2838 // effort, so so so many bugs or buggy info appears through call
2841 if( state.DISJOINTDEBUGCALLEE == null ||
2842 state.DISJOINTDEBUGCALLER == null ) {
2847 boolean debugCalleeMatches = false;
2848 boolean debugCallerMatches = false;
2850 ClassDescriptor cdCallee = mdCallee.getClassDesc();
2851 if( cdCallee != null ) {
2852 debugCalleeMatches =
2853 state.DISJOINTDEBUGCALLEE.equals( cdCallee.getSymbol()+
2855 mdCallee.getSymbol()
2860 if( taskOrMethodCaller instanceof MethodDescriptor ) {
2861 ClassDescriptor cdCaller = ((MethodDescriptor)taskOrMethodCaller).getClassDesc();
2862 if( cdCaller != null ) {
2863 debugCallerMatches =
2864 state.DISJOINTDEBUGCALLER.equals( cdCaller.getSymbol()+
2866 taskOrMethodCaller.getSymbol()
2870 // for bristlecone style tasks
2871 debugCallerMatches =
2872 state.DISJOINTDEBUGCALLER.equals( taskOrMethodCaller.getSymbol() );
2875 dcsd.debugCallSite = debugCalleeMatches && debugCallerMatches;
2876 dcsd.writeDebugDOTs = dcsd.debugCallSite;
2878 if( dcsd.debugCallSite ) {
2879 dcsd.didOneDebug = true;
2880 System.out.println( " --> Debugging "+taskOrMethodCaller+" calling "+mdCallee );
2884 protected void statusDebugCallSite( DebugCallSiteData dcsd ) {
2886 dcsd.writeDebugDOTs = false;
2887 dcsd.stopAfter = false;
2889 if( dcsd.didOneDebug ) {
2890 ++ReachGraph.debugCallSiteVisitCounter;
2891 System.out.println(" $$$ Debug call site visit "+
2892 ReachGraph.debugCallSiteVisitCounter+
2896 (ReachGraph.debugCallSiteVisitCounter >=
2897 ReachGraph.debugCallSiteVisitStartCapture) &&
2899 (ReachGraph.debugCallSiteVisitCounter <
2900 ReachGraph.debugCallSiteVisitStartCapture +
2901 ReachGraph.debugCallSiteNumVisitsToCapture)
2903 dcsd.writeDebugDOTs = true;
2904 System.out.println(" $$$ Capturing this call site visit $$$");
2905 if( ReachGraph.debugCallSiteStopAfter &&
2906 (ReachGraph.debugCallSiteVisitCounter ==
2907 ReachGraph.debugCallSiteVisitStartCapture +
2908 ReachGraph.debugCallSiteNumVisitsToCapture - 1)
2910 dcsd.stopAfter = true;
2915 if( dcsd.stopAfter ) {
2916 System.out.println("$$$ Exiting after requested captures of call site. $$$");
2925 // get successive captures of the analysis state, use compiler
2927 boolean takeDebugSnapshots = false;
2928 String descSymbolDebug = null;
2929 boolean stopAfterCapture = false;
2930 int snapVisitCounter = 0;
2931 int snapNodeCounter = 0;
2932 int visitStartCapture = 0;
2933 int numVisitsToCapture = 0;
2936 void debugSnapshot(ReachGraph rg, FlatNode fn, boolean in) {
2937 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2945 if( snapVisitCounter >= visitStartCapture ) {
2946 System.out.println(" @@@ snapping visit="+snapVisitCounter+
2947 ", node="+snapNodeCounter+
2951 graphName = String.format("snap%03d_%04din",
2955 graphName = String.format("snap%03d_%04dout",
2960 graphName = graphName + fn;
2962 rg.writeGraph(graphName,
2963 true, // write labels (variables)
2964 true, // selectively hide intermediate temp vars
2965 true, // prune unreachable heap regions
2966 false, // hide reachability
2967 false, // hide subset reachability states
2968 true, // hide predicates
2969 true); // hide edge taints
2976 public Set<Alloc> canPointToAt( TempDescriptor x,
2977 FlatNode programPoint ) {
2979 ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
2980 if( rgAtEnter == null ) {
2984 return rgAtEnter.canPointTo( x );
2988 public Set<Alloc> canPointToAfter( TempDescriptor x,
2989 FlatNode programPoint ) {
2991 ReachGraph rgAtExit = fn2rgAtExit.get( programPoint );
2992 if( rgAtExit == null ) {
2996 return rgAtExit.canPointTo( x );
3000 public Hashtable< Alloc, Set<Alloc> > canPointToAt( TempDescriptor x,
3002 FlatNode programPoint ) {
3004 ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
3005 if( rgAtEnter == null ) {
3009 return rgAtEnter.canPointTo( x, f.getSymbol(), f.getType() );
3013 public Hashtable< Alloc, Set<Alloc> > canPointToAtElement( TempDescriptor x,
3014 FlatNode programPoint ) {
3016 ReachGraph rgAtEnter = fn2rgAtEnter.get( programPoint );
3017 if( rgAtEnter == null ) {
3021 assert x.getType() != null;
3022 assert x.getType().isArray();
3024 return rgAtEnter.canPointTo( x, arrayElementFieldName, x.getType().dereference() );