1 package Analysis.Disjoint;
3 import Analysis.CallGraph.*;
4 import Analysis.Liveness;
5 import Analysis.ArrayReferencees;
8 import IR.Tree.Modifiers;
13 public class DisjointAnalysis {
15 ///////////////////////////////////////////
17 // Public interface to discover possible
18 // aliases in the program under analysis
20 ///////////////////////////////////////////
22 public HashSet<AllocSite>
23 getFlaggedAllocationSitesReachableFromTask(TaskDescriptor td) {
24 checkAnalysisComplete();
25 return getFlaggedAllocationSitesReachableFromTaskPRIVATE(td);
28 public AllocSite getAllocationSiteFromFlatNew(FlatNew fn) {
29 checkAnalysisComplete();
30 return getAllocSiteFromFlatNewPRIVATE(fn);
33 public AllocSite getAllocationSiteFromHeapRegionNodeID(Integer id) {
34 checkAnalysisComplete();
35 return mapHrnIdToAllocSite.get(id);
38 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
41 checkAnalysisComplete();
42 ReachGraph rg=mapDescriptorToCompleteReachGraph.get(taskOrMethod);
43 FlatMethod fm=state.getMethodFlat(taskOrMethod);
45 return rg.mayReachSharedObjects(fm, paramIndex1, paramIndex2);
48 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
49 int paramIndex, AllocSite alloc) {
50 checkAnalysisComplete();
51 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
52 FlatMethod fm=state.getMethodFlat(taskOrMethod);
54 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
57 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
58 AllocSite alloc, int paramIndex) {
59 checkAnalysisComplete();
60 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
61 FlatMethod fm=state.getMethodFlat(taskOrMethod);
63 return rg.mayReachSharedObjects(fm, paramIndex, alloc);
66 public Set<HeapRegionNode> hasPotentialSharing(Descriptor taskOrMethod,
67 AllocSite alloc1, AllocSite alloc2) {
68 checkAnalysisComplete();
69 ReachGraph rg = mapDescriptorToCompleteReachGraph.get(taskOrMethod);
71 return rg.mayReachSharedObjects(alloc1, alloc2);
74 public String prettyPrintNodeSet(Set<HeapRegionNode> s) {
75 checkAnalysisComplete();
79 Iterator<HeapRegionNode> i = s.iterator();
81 HeapRegionNode n = i.next();
83 AllocSite as = n.getAllocSite();
85 out += " " + n.toString() + ",\n";
87 out += " " + n.toString() + ": " + as.toStringVerbose()
96 // use the methods given above to check every possible alias
97 // between task parameters and flagged allocation sites reachable
99 public void writeAllAliases(String outputFile,
102 boolean tabularOutput,
105 throws java.io.IOException {
106 checkAnalysisComplete();
108 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
110 if (!tabularOutput) {
111 bw.write("Conducting ownership analysis with allocation depth = "
112 + allocationDepth + "\n");
113 bw.write(timeReport + "\n");
118 // look through every task for potential aliases
119 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
120 while (taskItr.hasNext()) {
121 TaskDescriptor td = (TaskDescriptor) taskItr.next();
123 if (!tabularOutput) {
124 bw.write("\n---------" + td + "--------\n");
127 HashSet<AllocSite> allocSites = getFlaggedAllocationSitesReachableFromTask(td);
129 Set<HeapRegionNode> common;
131 // for each task parameter, check for aliases with
132 // other task parameters and every allocation site
133 // reachable from this task
134 boolean foundSomeAlias = false;
136 FlatMethod fm = state.getMethodFlat(td);
137 for (int i = 0; i < fm.numParameters(); ++i) {
139 // skip parameters with types that cannot reference
141 if( !shouldAnalysisTrack( fm.getParameter( i ).getType() ) ) {
145 // for the ith parameter check for aliases to all
146 // higher numbered parameters
147 for (int j = i + 1; j < fm.numParameters(); ++j) {
149 // skip parameters with types that cannot reference
151 if( !shouldAnalysisTrack( fm.getParameter( j ).getType() ) ) {
156 common = hasPotentialSharing(td, i, j);
157 if (!common.isEmpty()) {
158 foundSomeAlias = true;
159 if (!tabularOutput) {
160 bw.write("Potential alias between parameters " + i
161 + " and " + j + ".\n");
162 bw.write(prettyPrintNodeSet(common) + "\n");
169 // for the ith parameter, check for aliases against
170 // the set of allocation sites reachable from this
172 Iterator allocItr = allocSites.iterator();
173 while (allocItr.hasNext()) {
174 AllocSite as = (AllocSite) allocItr.next();
175 common = hasPotentialSharing(td, i, as);
176 if (!common.isEmpty()) {
177 foundSomeAlias = true;
178 if (!tabularOutput) {
179 bw.write("Potential alias between parameter " + i
180 + " and " + as.getFlatNew() + ".\n");
181 bw.write(prettyPrintNodeSet(common) + "\n");
189 // for each allocation site check for aliases with
190 // other allocation sites in the context of execution
192 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
193 Iterator allocItr1 = allocSites.iterator();
194 while (allocItr1.hasNext()) {
195 AllocSite as1 = (AllocSite) allocItr1.next();
197 Iterator allocItr2 = allocSites.iterator();
198 while (allocItr2.hasNext()) {
199 AllocSite as2 = (AllocSite) allocItr2.next();
201 if (!outerChecked.contains(as2)) {
202 common = hasPotentialSharing(td, as1, as2);
204 if (!common.isEmpty()) {
205 foundSomeAlias = true;
206 if (!tabularOutput) {
207 bw.write("Potential alias between "
208 + as1.getFlatNew() + " and "
209 + as2.getFlatNew() + ".\n");
210 bw.write(prettyPrintNodeSet(common) + "\n");
218 outerChecked.add(as1);
221 if (!foundSomeAlias) {
222 if (!tabularOutput) {
223 bw.write("No aliases between flagged objects in Task " + td
230 if (!tabularOutput) {
231 bw.write("\n" + computeAliasContextHistogram());
233 bw.write(" & " + numAlias + " & " + justTime + " & " + numLines
234 + " & " + numMethodsAnalyzed() + " \\\\\n");
241 // this version of writeAllAliases is for Java programs that have no tasks
242 public void writeAllAliasesJava(String outputFile,
245 boolean tabularOutput,
248 throws java.io.IOException {
249 checkAnalysisComplete();
253 BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
255 bw.write("Conducting disjoint reachability analysis with allocation depth = "
256 + allocationDepth + "\n");
257 bw.write(timeReport + "\n\n");
259 boolean foundSomeAlias = false;
261 Descriptor d = typeUtil.getMain();
262 HashSet<AllocSite> allocSites = getFlaggedAllocationSites(d);
264 // for each allocation site check for aliases with
265 // other allocation sites in the context of execution
267 HashSet<AllocSite> outerChecked = new HashSet<AllocSite>();
268 Iterator allocItr1 = allocSites.iterator();
269 while (allocItr1.hasNext()) {
270 AllocSite as1 = (AllocSite) allocItr1.next();
272 Iterator allocItr2 = allocSites.iterator();
273 while (allocItr2.hasNext()) {
274 AllocSite as2 = (AllocSite) allocItr2.next();
276 if (!outerChecked.contains(as2)) {
277 Set<HeapRegionNode> common = hasPotentialSharing(d,
280 if (!common.isEmpty()) {
281 foundSomeAlias = true;
282 bw.write("Potential alias between "
283 + as1.getDisjointAnalysisId() + " and "
284 + as2.getDisjointAnalysisId() + ".\n");
285 bw.write(prettyPrintNodeSet(common) + "\n");
290 outerChecked.add(as1);
293 if (!foundSomeAlias) {
294 bw.write("No aliases between flagged objects found.\n");
297 // bw.write("\n" + computeAliasContextHistogram());
301 ///////////////////////////////////////////
303 // end public interface
305 ///////////////////////////////////////////
307 protected void checkAnalysisComplete() {
308 if( !analysisComplete ) {
309 throw new Error("Warning: public interface method called while analysis is running.");
314 // run in faster mode, only when bugs wrung out!
315 public static boolean releaseMode;
317 // data from the compiler
319 public CallGraph callGraph;
320 public Liveness liveness;
321 public ArrayReferencees arrayReferencees;
322 public TypeUtil typeUtil;
323 public int allocationDepth;
325 // data structure for public interface
326 private Hashtable<Descriptor, HashSet<AllocSite> > mapDescriptorToAllocSiteSet;
329 // for public interface methods to warn that they
330 // are grabbing results during analysis
331 private boolean analysisComplete;
334 // used to identify HeapRegionNode objects
335 // A unique ID equates an object in one
336 // ownership graph with an object in another
337 // graph that logically represents the same
339 // start at 10 and increment to reserve some
340 // IDs for special purposes
341 static protected int uniqueIDcount = 10;
344 // An out-of-scope method created by the
345 // analysis that has no parameters, and
346 // appears to allocate the command line
347 // arguments, then invoke the source code's
348 // main method. The purpose of this is to
349 // provide the analysis with an explicit
350 // top-level context with no parameters
351 protected MethodDescriptor mdAnalysisEntry;
352 protected FlatMethod fmAnalysisEntry;
354 // main method defined by source program
355 protected MethodDescriptor mdSourceEntry;
357 // the set of task and/or method descriptors
358 // reachable in call graph
359 protected Set<Descriptor>
360 descriptorsToAnalyze;
362 // current descriptors to visit in fixed-point
363 // interprocedural analysis, prioritized by
364 // dependency in the call graph
365 protected Stack<DescriptorQWrapper>
368 // a duplication of the above structure, but
369 // for efficient testing of inclusion
370 protected HashSet<Descriptor>
371 descriptorsToVisitSet;
373 // storage for priorities (doesn't make sense)
374 // to add it to the Descriptor class, just in
376 protected Hashtable<Descriptor, Integer>
377 mapDescriptorToPriority;
380 // maps a descriptor to its current partial result
381 // from the intraprocedural fixed-point analysis--
382 // then the interprocedural analysis settles, this
383 // mapping will have the final results for each
385 protected Hashtable<Descriptor, ReachGraph>
386 mapDescriptorToCompleteReachGraph;
388 // maps a descriptor to its known dependents: namely
389 // methods or tasks that call the descriptor's method
390 // AND are part of this analysis (reachable from main)
391 protected Hashtable< Descriptor, Set<Descriptor> >
392 mapDescriptorToSetDependents;
394 // maps each flat new to one analysis abstraction
395 // allocate site object, these exist outside reach graphs
396 protected Hashtable<FlatNew, AllocSite>
397 mapFlatNewToAllocSite;
399 // maps intergraph heap region IDs to intergraph
400 // allocation sites that created them, a redundant
401 // structure for efficiency in some operations
402 protected Hashtable<Integer, AllocSite>
405 // maps a method to its initial heap model (IHM) that
406 // is the set of reachability graphs from every caller
407 // site, all merged together. The reason that we keep
408 // them separate is that any one call site's contribution
409 // to the IHM may changed along the path to the fixed point
410 protected Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >
411 mapDescriptorToIHMcontributions;
413 // TODO -- CHANGE EDGE/TYPE/FIELD storage!
414 public static final String arrayElementFieldName = "___element_";
415 static protected Hashtable<TypeDescriptor, FieldDescriptor>
418 // for controlling DOT file output
419 protected boolean writeFinalDOTs;
420 protected boolean writeAllIncrementalDOTs;
422 // supporting DOT output--when we want to write every
423 // partial method result, keep a tally for generating
425 protected Hashtable<Descriptor, Integer>
426 mapDescriptorToNumUpdates;
428 //map task descriptor to initial task parameter
429 protected Hashtable<Descriptor, ReachGraph>
430 mapDescriptorToReachGraph;
432 protected PointerMethod pm;
434 protected Hashtable<FlatMethod, ReachGraph> hackmap;
437 // allocate various structures that are not local
438 // to a single class method--should be done once
439 protected void allocateStructures() {
440 descriptorsToAnalyze = new HashSet<Descriptor>();
442 mapDescriptorToCompleteReachGraph =
443 new Hashtable<Descriptor, ReachGraph>();
445 mapDescriptorToNumUpdates =
446 new Hashtable<Descriptor, Integer>();
448 mapDescriptorToSetDependents =
449 new Hashtable< Descriptor, Set<Descriptor> >();
451 mapFlatNewToAllocSite =
452 new Hashtable<FlatNew, AllocSite>();
454 mapDescriptorToIHMcontributions =
455 new Hashtable< Descriptor, Hashtable< FlatCall, ReachGraph > >();
457 mapHrnIdToAllocSite =
458 new Hashtable<Integer, AllocSite>();
460 mapTypeToArrayField =
461 new Hashtable <TypeDescriptor, FieldDescriptor>();
463 descriptorsToVisitQ =
464 new Stack<DescriptorQWrapper>();
466 descriptorsToVisitSet =
467 new HashSet<Descriptor>();
469 mapDescriptorToPriority =
470 new Hashtable<Descriptor, Integer>();
472 mapDescriptorToAllocSiteSet =
473 new Hashtable<Descriptor, HashSet<AllocSite> >();
475 mapDescriptorToReachGraph =
476 new Hashtable<Descriptor, ReachGraph>();
478 hackmap = new Hashtable<FlatMethod, ReachGraph>();
483 // this analysis generates a disjoint reachability
484 // graph for every reachable method in the program
485 public DisjointAnalysis( State s,
490 ) throws java.io.IOException {
491 init( s, tu, cg, l, ar );
494 protected void init( State state,
498 ArrayReferencees arrayReferencees
499 ) throws java.io.IOException {
501 analysisComplete = false;
504 this.typeUtil = typeUtil;
505 this.callGraph = callGraph;
506 this.liveness = liveness;
507 this.arrayReferencees = arrayReferencees;
508 this.allocationDepth = state.DISJOINTALLOCDEPTH;
509 this.releaseMode = state.DISJOINTRELEASEMODE;
511 this.writeFinalDOTs = state.DISJOINTWRITEDOTS && !state.DISJOINTWRITEALL;
512 this.writeAllIncrementalDOTs = state.DISJOINTWRITEDOTS && state.DISJOINTWRITEALL;
514 this.takeDebugSnapshots = state.DISJOINTSNAPSYMBOL != null;
515 this.descSymbolDebug = state.DISJOINTSNAPSYMBOL;
516 this.visitStartCapture = state.DISJOINTSNAPVISITTOSTART;
517 this.numVisitsToCapture = state.DISJOINTSNAPNUMVISITS;
518 this.stopAfterCapture = state.DISJOINTSNAPSTOPAFTER;
519 this.snapVisitCounter = 1; // count visits from 1 (user will write 1, means 1st visit)
520 this.snapNodeCounter = 0; // count nodes from 0
521 this.pm=new PointerMethod();
524 // set some static configuration for ReachGraphs
525 ReachGraph.allocationDepth = allocationDepth;
526 ReachGraph.typeUtil = typeUtil;
528 ReachGraph.debugCallSiteVisitsUntilExit = state.DISJOINTDEBUGCALLCOUNT;
530 allocateStructures();
532 double timeStartAnalysis = (double) System.nanoTime();
534 // start interprocedural fixed-point computation
536 analysisComplete=true;
538 double timeEndAnalysis = (double) System.nanoTime();
539 double dt = (timeEndAnalysis - timeStartAnalysis)/(Math.pow( 10.0, 9.0 ) );
540 String treport = String.format( "The reachability analysis took %.3f sec.", dt );
541 String justtime = String.format( "%.2f", dt );
542 System.out.println( treport );
544 if( writeFinalDOTs && !writeAllIncrementalDOTs ) {
548 if( state.DISJOINTWRITEIHMS ) {
552 if( state.DISJOINTALIASFILE != null ) {
554 writeAllAliases(state.DISJOINTALIASFILE, treport, justtime, state.DISJOINTALIASTAB, state.lines);
557 writeAllAliasesJava( aliasFile,
560 state.DISJOINTALIASTAB,
568 // fixed-point computation over the call graph--when a
569 // method's callees are updated, it must be reanalyzed
570 protected void analyzeMethods() throws java.io.IOException {
573 // This analysis does not support Bamboo at the moment,
574 // but if it does in the future we would initialize the
575 // set of descriptors to analyze as the program-reachable
576 // tasks and the methods callable by them. For Java,
577 // just methods reachable from the main method.
578 System.out.println( "Bamboo..." );
579 Iterator taskItr = state.getTaskSymbolTable().getDescriptorsIterator();
581 while (taskItr.hasNext()) {
582 TaskDescriptor td = (TaskDescriptor) taskItr.next();
583 if (!descriptorsToAnalyze.contains(td)) {
584 descriptorsToAnalyze.add(td);
585 descriptorsToAnalyze.addAll(callGraph.getAllMethods(td));
590 // add all methods transitively reachable from the
591 // source's main to set for analysis
592 mdSourceEntry = typeUtil.getMain();
593 descriptorsToAnalyze.add( mdSourceEntry );
594 descriptorsToAnalyze.addAll(
595 callGraph.getAllMethods( mdSourceEntry )
598 // fabricate an empty calling context that will call
599 // the source's main, but call graph doesn't know
600 // about it, so explicitly add it
601 makeAnalysisEntryMethod( mdSourceEntry );
602 descriptorsToAnalyze.add( mdAnalysisEntry );
605 // topologically sort according to the call graph so
606 // leaf calls are ordered first, smarter analysis order
607 // CHANGED: order leaf calls last!!
608 LinkedList<Descriptor> sortedDescriptors =
609 topologicalSort( descriptorsToAnalyze );
611 // add sorted descriptors to priority queue, and duplicate
612 // the queue as a set for efficiently testing whether some
613 // method is marked for analysis
615 Iterator<Descriptor> dItr = sortedDescriptors.iterator();
616 while( dItr.hasNext() ) {
617 Descriptor d = dItr.next();
618 mapDescriptorToPriority.put( d, new Integer( p ) );
619 descriptorsToVisitQ.add( new DescriptorQWrapper( p, d ) );
620 descriptorsToVisitSet.add( d );
624 // analyze methods from the priority queue until it is empty
625 while( !descriptorsToVisitQ.isEmpty() ) {
626 Descriptor d = descriptorsToVisitQ.pop().getDescriptor();
627 assert descriptorsToVisitSet.contains( d );
628 descriptorsToVisitSet.remove( d );
630 // because the task or method descriptor just extracted
631 // was in the "to visit" set it either hasn't been analyzed
632 // yet, or some method that it depends on has been
633 // updated. Recompute a complete reachability graph for
634 // this task/method and compare it to any previous result.
635 // If there is a change detected, add any methods/tasks
636 // that depend on this one to the "to visit" set.
638 System.out.println( "Analyzing " + d );
640 ReachGraph rg = analyzeMethod( d );
641 ReachGraph rgPrev = getPartial( d );
643 if( !rg.equals( rgPrev ) ) {
646 // results for d changed, so enqueue dependents
647 // of d for further analysis
648 Iterator<Descriptor> depsItr = getDependents( d ).iterator();
649 while( depsItr.hasNext() ) {
650 Descriptor dNext = depsItr.next();
657 protected ReachGraph analyzeMethod( Descriptor d )
658 throws java.io.IOException {
660 // get the flat code for this descriptor
662 if( d == mdAnalysisEntry ) {
663 fm = fmAnalysisEntry;
665 fm = state.getMethodFlat( d );
667 pm.analyzeMethod(fm);
668 // intraprocedural work set
669 Set<FlatNode> flatNodesToVisit = new HashSet<FlatNode>();
670 flatNodesToVisit.add( fm );
672 // mapping of current partial results
673 Hashtable<FlatNode, ReachGraph> mapFlatNodeToReachGraph =
674 new Hashtable<FlatNode, ReachGraph>();
676 // the set of return nodes partial results that will be combined as
677 // the final, conservative approximation of the entire method
678 HashSet<FlatReturnNode> setReturns = new HashSet<FlatReturnNode>();
680 while( !flatNodesToVisit.isEmpty() ) {
681 FlatNode fn = (FlatNode) flatNodesToVisit.iterator().next();
682 flatNodesToVisit.remove( fn );
684 // effect transfer function defined by this node,
685 // then compare it to the old graph at this node
686 // to see if anything was updated.
688 ReachGraph rg = new ReachGraph();
689 TaskDescriptor taskDesc;
690 if(fn instanceof FlatMethod && (taskDesc=((FlatMethod)fn).getTask())!=null){
691 if(mapDescriptorToReachGraph.containsKey(taskDesc)){
692 // retrieve existing reach graph if it is not first time
693 rg=mapDescriptorToReachGraph.get(taskDesc);
695 // create initial reach graph for a task
696 rg=createInitialTaskReachGraph((FlatMethod)fn);
698 mapDescriptorToReachGraph.put(taskDesc, rg);
702 // start by merging all node's parents' graphs
703 for( int i = 0; i < pm.numPrev(fn); ++i ) {
704 FlatNode pn = pm.getPrev(fn,i);
705 if( mapFlatNodeToReachGraph.containsKey( pn ) ) {
706 ReachGraph rgParent = mapFlatNodeToReachGraph.get( pn );
707 rg.merge( rgParent );
712 if( takeDebugSnapshots &&
713 d.getSymbol().equals( descSymbolDebug )
715 debugSnapshot( rg, fn, true );
719 // modify rg with appropriate transfer function
720 rg = analyzeFlatNode( d, fm, fn, setReturns, rg );
723 if( takeDebugSnapshots &&
724 d.getSymbol().equals( descSymbolDebug )
726 debugSnapshot( rg, fn, false );
731 // if the results of the new graph are different from
732 // the current graph at this node, replace the graph
733 // with the update and enqueue the children
734 ReachGraph rgPrev = mapFlatNodeToReachGraph.get( fn );
735 if( !rg.equals( rgPrev ) ) {
736 mapFlatNodeToReachGraph.put( fn, rg );
738 for( int i = 0; i < pm.numNext(fn); i++ ) {
739 FlatNode nn = pm.getNext(fn, i);
740 flatNodesToVisit.add( nn );
745 // end by merging all return nodes into a complete
746 // ownership graph that represents all possible heap
747 // states after the flat method returns
748 ReachGraph completeGraph = new ReachGraph();
750 assert !setReturns.isEmpty();
751 Iterator retItr = setReturns.iterator();
752 while( retItr.hasNext() ) {
753 FlatReturnNode frn = (FlatReturnNode) retItr.next();
755 assert mapFlatNodeToReachGraph.containsKey( frn );
756 ReachGraph rgRet = mapFlatNodeToReachGraph.get( frn );
758 completeGraph.merge( rgRet );
762 if( takeDebugSnapshots &&
763 d.getSymbol().equals( descSymbolDebug )
765 // increment that we've visited the debug snap
766 // method, and reset the node counter
767 System.out.println( " @@@ debug snap at visit "+snapVisitCounter );
771 if( snapVisitCounter == visitStartCapture + numVisitsToCapture &&
774 System.out.println( "!!! Stopping analysis after debug snap captures. !!!" );
780 return completeGraph;
785 analyzeFlatNode( Descriptor d,
786 FlatMethod fmContaining,
788 HashSet<FlatReturnNode> setRetNodes,
790 ) throws java.io.IOException {
793 // any variables that are no longer live should be
794 // nullified in the graph to reduce edges
795 //rg.nullifyDeadVars( liveness.getLiveInTemps( fmContaining, fn ) );
802 // use node type to decide what transfer function
803 // to apply to the reachability graph
804 switch( fn.kind() ) {
806 case FKind.FlatMethod: {
807 // construct this method's initial heap model (IHM)
808 // since we're working on the FlatMethod, we know
809 // the incoming ReachGraph 'rg' is empty
811 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
812 getIHMcontributions( d );
814 Set entrySet = heapsFromCallers.entrySet();
815 Iterator itr = entrySet.iterator();
816 while( itr.hasNext() ) {
817 Map.Entry me = (Map.Entry) itr.next();
818 FlatCall fc = (FlatCall) me.getKey();
819 ReachGraph rgContrib = (ReachGraph) me.getValue();
821 assert fc.getMethod().equals( d );
823 // some call sites are in same method context though,
824 // and all of them should be merged together first,
825 // then heaps from different contexts should be merged
826 // THIS ASSUMES DIFFERENT CONTEXTS NEED SPECIAL CONSIDERATION!
827 // such as, do allocation sites need to be aged?
829 rg.merge_diffMethodContext( rgContrib );
831 FlatMethod hackfm=(FlatMethod)fn;
832 if (hackmap.containsKey(hackfm)) {
833 rg.merge(hackmap.get(hackfm));
835 hackmap.put(hackfm, rg);
838 case FKind.FlatOpNode:
839 FlatOpNode fon = (FlatOpNode) fn;
840 if( fon.getOp().getOp() == Operation.ASSIGN ) {
843 rg.assignTempXEqualToTempY( lhs, rhs );
847 case FKind.FlatCastNode:
848 FlatCastNode fcn = (FlatCastNode) fn;
852 TypeDescriptor td = fcn.getType();
855 rg.assignTempXEqualToCastedTempY( lhs, rhs, td );
858 case FKind.FlatFieldNode:
859 FlatFieldNode ffn = (FlatFieldNode) fn;
862 fld = ffn.getField();
863 if( shouldAnalysisTrack( fld.getType() ) ) {
864 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fld );
868 case FKind.FlatSetFieldNode:
869 FlatSetFieldNode fsfn = (FlatSetFieldNode) fn;
871 fld = fsfn.getField();
873 if( shouldAnalysisTrack( fld.getType() ) ) {
874 rg.assignTempXFieldFEqualToTempY( lhs, fld, rhs );
878 case FKind.FlatElementNode:
879 FlatElementNode fen = (FlatElementNode) fn;
882 if( shouldAnalysisTrack( lhs.getType() ) ) {
884 assert rhs.getType() != null;
885 assert rhs.getType().isArray();
887 TypeDescriptor tdElement = rhs.getType().dereference();
888 FieldDescriptor fdElement = getArrayField( tdElement );
890 rg.assignTempXEqualToTempYFieldF( lhs, rhs, fdElement );
894 case FKind.FlatSetElementNode:
895 FlatSetElementNode fsen = (FlatSetElementNode) fn;
897 if( arrayReferencees.doesNotCreateNewReaching( fsen ) ) {
898 // skip this node if it cannot create new reachability paths
904 if( shouldAnalysisTrack( rhs.getType() ) ) {
906 assert lhs.getType() != null;
907 assert lhs.getType().isArray();
909 TypeDescriptor tdElement = lhs.getType().dereference();
910 FieldDescriptor fdElement = getArrayField( tdElement );
912 rg.assignTempXFieldFEqualToTempY( lhs, fdElement, rhs );
917 FlatNew fnn = (FlatNew) fn;
919 if( shouldAnalysisTrack( lhs.getType() ) ) {
920 AllocSite as = getAllocSiteFromFlatNewPRIVATE( fnn );
921 rg.assignTempEqualToNewAlloc( lhs, as );
925 case FKind.FlatCall: {
926 //TODO: temporal fix for task descriptor case
927 //MethodDescriptor mdCaller = fmContaining.getMethod();
929 if(fmContaining.getMethod()!=null){
930 mdCaller = fmContaining.getMethod();
932 mdCaller = fmContaining.getTask();
934 FlatCall fc = (FlatCall) fn;
935 MethodDescriptor mdCallee = fc.getMethod();
936 FlatMethod fmCallee = state.getMethodFlat( mdCallee );
938 boolean writeDebugDOTs =
939 mdCaller.getSymbol().equals( state.DISJOINTDEBUGCALLER ) &&
940 mdCallee.getSymbol().equals( state.DISJOINTDEBUGCALLEE );
943 // calculate the heap this call site can reach--note this is
944 // not used for the current call site transform, we are
945 // grabbing this heap model for future analysis of the callees,
946 // so if different results emerge we will return to this site
947 ReachGraph heapForThisCall_old =
948 getIHMcontribution( mdCallee, fc );
950 // the computation of the callee-reachable heap
951 // is useful for making the callee starting point
952 // and for applying the call site transfer function
953 Set<Integer> callerNodeIDsCopiedToCallee =
954 new HashSet<Integer>();
956 ReachGraph heapForThisCall_cur =
957 rg.makeCalleeView( fc,
959 callerNodeIDsCopiedToCallee,
963 if( !heapForThisCall_cur.equals( heapForThisCall_old ) ) {
964 // if heap at call site changed, update the contribution,
965 // and reschedule the callee for analysis
966 addIHMcontribution( mdCallee, fc, heapForThisCall_cur );
973 // the transformation for a call site should update the
974 // current heap abstraction with any effects from the callee,
975 // or if the method is virtual, the effects from any possible
976 // callees, so find the set of callees...
977 Set<MethodDescriptor> setPossibleCallees =
978 new HashSet<MethodDescriptor>();
980 if( mdCallee.isStatic() ) {
981 setPossibleCallees.add( mdCallee );
983 TypeDescriptor typeDesc = fc.getThis().getType();
984 setPossibleCallees.addAll( callGraph.getMethods( mdCallee,
989 ReachGraph rgMergeOfEffects = new ReachGraph();
991 Iterator<MethodDescriptor> mdItr = setPossibleCallees.iterator();
992 while( mdItr.hasNext() ) {
993 MethodDescriptor mdPossible = mdItr.next();
994 FlatMethod fmPossible = state.getMethodFlat( mdPossible );
996 addDependent( mdPossible, // callee
999 // don't alter the working graph (rg) until we compute a
1000 // result for every possible callee, merge them all together,
1001 // then set rg to that
1002 ReachGraph rgCopy = new ReachGraph();
1005 ReachGraph rgEffect = getPartial( mdPossible );
1007 if( rgEffect == null ) {
1008 // if this method has never been analyzed just schedule it
1009 // for analysis and skip over this call site for now
1010 enqueue( mdPossible );
1012 rgCopy.resolveMethodCall( fc,
1015 callerNodeIDsCopiedToCallee,
1020 rgMergeOfEffects.merge( rgCopy );
1024 // now that we've taken care of building heap models for
1025 // callee analysis, finish this transformation
1026 rg = rgMergeOfEffects;
1030 case FKind.FlatReturnNode:
1031 FlatReturnNode frn = (FlatReturnNode) fn;
1032 rhs = frn.getReturnTemp();
1033 if( rhs != null && shouldAnalysisTrack( rhs.getType() ) ) {
1034 rg.assignReturnEqualToTemp( rhs );
1036 setRetNodes.add( frn );
1042 // dead variables were removed before the above transfer function
1043 // was applied, so eliminate heap regions and edges that are no
1044 // longer part of the abstractly-live heap graph, and sweep up
1045 // and reachability effects that are altered by the reduction
1046 //rg.abstractGarbageCollect();
1050 // at this point rg should be the correct update
1051 // by an above transfer function, or untouched if
1052 // the flat node type doesn't affect the heap
1057 // this method should generate integers strictly greater than zero!
1058 // special "shadow" regions are made from a heap region by negating
1060 static public Integer generateUniqueHeapRegionNodeID() {
1062 return new Integer( uniqueIDcount );
1067 static public FieldDescriptor getArrayField( TypeDescriptor tdElement ) {
1068 FieldDescriptor fdElement = mapTypeToArrayField.get( tdElement );
1069 if( fdElement == null ) {
1070 fdElement = new FieldDescriptor( new Modifiers( Modifiers.PUBLIC ),
1072 arrayElementFieldName,
1075 mapTypeToArrayField.put( tdElement, fdElement );
1082 private void writeFinalGraphs() {
1083 Set entrySet = mapDescriptorToCompleteReachGraph.entrySet();
1084 Iterator itr = entrySet.iterator();
1085 while( itr.hasNext() ) {
1086 Map.Entry me = (Map.Entry) itr.next();
1087 Descriptor d = (Descriptor) me.getKey();
1088 ReachGraph rg = (ReachGraph) me.getValue();
1090 rg.writeGraph( "COMPLETE"+d,
1091 true, // write labels (variables)
1092 true, // selectively hide intermediate temp vars
1093 true, // prune unreachable heap regions
1094 false, // hide subset reachability states
1095 true ); // hide edge taints
1099 private void writeFinalIHMs() {
1100 Iterator d2IHMsItr = mapDescriptorToIHMcontributions.entrySet().iterator();
1101 while( d2IHMsItr.hasNext() ) {
1102 Map.Entry me1 = (Map.Entry) d2IHMsItr.next();
1103 Descriptor d = (Descriptor) me1.getKey();
1104 Hashtable<FlatCall, ReachGraph> IHMs = (Hashtable<FlatCall, ReachGraph>) me1.getValue();
1106 Iterator fc2rgItr = IHMs.entrySet().iterator();
1107 while( fc2rgItr.hasNext() ) {
1108 Map.Entry me2 = (Map.Entry) fc2rgItr.next();
1109 FlatCall fc = (FlatCall) me2.getKey();
1110 ReachGraph rg = (ReachGraph) me2.getValue();
1112 rg.writeGraph( "IHMPARTFOR"+d+"FROM"+fc,
1113 true, // write labels (variables)
1114 true, // selectively hide intermediate temp vars
1115 true, // prune unreachable heap regions
1116 false, // hide subset reachability states
1117 true ); // hide edge taints
1123 protected ReachGraph getPartial( Descriptor d ) {
1124 return mapDescriptorToCompleteReachGraph.get( d );
1127 protected void setPartial( Descriptor d, ReachGraph rg ) {
1128 mapDescriptorToCompleteReachGraph.put( d, rg );
1130 // when the flag for writing out every partial
1131 // result is set, we should spit out the graph,
1132 // but in order to give it a unique name we need
1133 // to track how many partial results for this
1134 // descriptor we've already written out
1135 if( writeAllIncrementalDOTs ) {
1136 if( !mapDescriptorToNumUpdates.containsKey( d ) ) {
1137 mapDescriptorToNumUpdates.put( d, new Integer( 0 ) );
1139 Integer n = mapDescriptorToNumUpdates.get( d );
1141 rg.writeGraph( d+"COMPLETE"+String.format( "%05d", n ),
1142 true, // write labels (variables)
1143 true, // selectively hide intermediate temp vars
1144 true, // prune unreachable heap regions
1145 false, // hide subset reachability states
1146 true ); // hide edge taints
1148 mapDescriptorToNumUpdates.put( d, n + 1 );
1154 // return just the allocation site associated with one FlatNew node
1155 protected AllocSite getAllocSiteFromFlatNewPRIVATE( FlatNew fnew ) {
1157 if( !mapFlatNewToAllocSite.containsKey( fnew ) ) {
1159 (AllocSite) Canonical.makeCanonical( new AllocSite( allocationDepth,
1161 fnew.getDisjointId()
1165 // the newest nodes are single objects
1166 for( int i = 0; i < allocationDepth; ++i ) {
1167 Integer id = generateUniqueHeapRegionNodeID();
1168 as.setIthOldest( i, id );
1169 mapHrnIdToAllocSite.put( id, as );
1172 // the oldest node is a summary node
1173 as.setSummary( generateUniqueHeapRegionNodeID() );
1175 mapFlatNewToAllocSite.put( fnew, as );
1178 return mapFlatNewToAllocSite.get( fnew );
1182 public static boolean shouldAnalysisTrack( TypeDescriptor type ) {
1183 // don't track primitive types, but an array
1184 // of primitives is heap memory
1185 if( type.isImmutable() ) {
1186 return type.isArray();
1189 // everything else is an object
1195 // return all allocation sites in the method (there is one allocation
1196 // site per FlatNew node in a method)
1197 protected HashSet<AllocSite> getAllocSiteSet(Descriptor d) {
1198 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
1199 buildAllocSiteSet(d);
1202 return mapDescriptorToAllocSiteSet.get(d);
1208 protected void buildAllocSiteSet(Descriptor d) {
1209 HashSet<AllocSite> s = new HashSet<AllocSite>();
1211 FlatMethod fm = state.getMethodFlat( d );
1213 // visit every node in this FlatMethod's IR graph
1214 // and make a set of the allocation sites from the
1215 // FlatNew node's visited
1216 HashSet<FlatNode> visited = new HashSet<FlatNode>();
1217 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
1220 while( !toVisit.isEmpty() ) {
1221 FlatNode n = toVisit.iterator().next();
1223 if( n instanceof FlatNew ) {
1224 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
1227 toVisit.remove( n );
1230 for( int i = 0; i < n.numNext(); ++i ) {
1231 FlatNode child = n.getNext( i );
1232 if( !visited.contains( child ) ) {
1233 toVisit.add( child );
1238 mapDescriptorToAllocSiteSet.put( d, s );
1242 protected HashSet<AllocSite> getFlaggedAllocSites(Descriptor dIn) {
1244 HashSet<AllocSite> out = new HashSet<AllocSite>();
1245 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1246 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1250 while( !toVisit.isEmpty() ) {
1251 Descriptor d = toVisit.iterator().next();
1255 HashSet<AllocSite> asSet = getAllocSiteSet(d);
1256 Iterator asItr = asSet.iterator();
1257 while( asItr.hasNext() ) {
1258 AllocSite as = (AllocSite) asItr.next();
1259 if( as.getDisjointAnalysisId() != null ) {
1264 // enqueue callees of this method to be searched for
1265 // allocation sites also
1266 Set callees = callGraph.getCalleeSet(d);
1267 if( callees != null ) {
1268 Iterator methItr = callees.iterator();
1269 while( methItr.hasNext() ) {
1270 MethodDescriptor md = (MethodDescriptor) methItr.next();
1272 if( !visited.contains(md) ) {
1284 protected HashSet<AllocSite>
1285 getFlaggedAllocSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
1287 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
1288 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1289 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1293 // traverse this task and all methods reachable from this task
1294 while( !toVisit.isEmpty() ) {
1295 Descriptor d = toVisit.iterator().next();
1299 HashSet<AllocSite> asSet = getAllocSiteSet(d);
1300 Iterator asItr = asSet.iterator();
1301 while( asItr.hasNext() ) {
1302 AllocSite as = (AllocSite) asItr.next();
1303 TypeDescriptor typed = as.getType();
1304 if( typed != null ) {
1305 ClassDescriptor cd = typed.getClassDesc();
1306 if( cd != null && cd.hasFlags() ) {
1312 // enqueue callees of this method to be searched for
1313 // allocation sites also
1314 Set callees = callGraph.getCalleeSet(d);
1315 if( callees != null ) {
1316 Iterator methItr = callees.iterator();
1317 while( methItr.hasNext() ) {
1318 MethodDescriptor md = (MethodDescriptor) methItr.next();
1320 if( !visited.contains(md) ) {
1334 protected String computeAliasContextHistogram() {
1336 Hashtable<Integer, Integer> mapNumContexts2NumDesc =
1337 new Hashtable<Integer, Integer>();
1339 Iterator itr = mapDescriptorToAllDescriptors.entrySet().iterator();
1340 while( itr.hasNext() ) {
1341 Map.Entry me = (Map.Entry) itr.next();
1342 HashSet<Descriptor> s = (HashSet<Descriptor>) me.getValue();
1344 Integer i = mapNumContexts2NumDesc.get( s.size() );
1346 i = new Integer( 0 );
1348 mapNumContexts2NumDesc.put( s.size(), i + 1 );
1354 itr = mapNumContexts2NumDesc.entrySet().iterator();
1355 while( itr.hasNext() ) {
1356 Map.Entry me = (Map.Entry) itr.next();
1357 Integer c0 = (Integer) me.getKey();
1358 Integer d0 = (Integer) me.getValue();
1360 s += String.format( "%4d methods had %4d unique alias contexts.\n", d0, c0 );
1363 s += String.format( "\n%4d total methods analayzed.\n", total );
1368 protected int numMethodsAnalyzed() {
1369 return descriptorsToAnalyze.size();
1376 // Take in source entry which is the program's compiled entry and
1377 // create a new analysis entry, a method that takes no parameters
1378 // and appears to allocate the command line arguments and call the
1379 // source entry with them. The purpose of this analysis entry is
1380 // to provide a top-level method context with no parameters left.
1381 protected void makeAnalysisEntryMethod( MethodDescriptor mdSourceEntry ) {
1383 Modifiers mods = new Modifiers();
1384 mods.addModifier( Modifiers.PUBLIC );
1385 mods.addModifier( Modifiers.STATIC );
1387 TypeDescriptor returnType =
1388 new TypeDescriptor( TypeDescriptor.VOID );
1390 this.mdAnalysisEntry =
1391 new MethodDescriptor( mods,
1393 "analysisEntryMethod"
1396 TempDescriptor cmdLineArgs =
1397 new TempDescriptor( "args",
1398 mdSourceEntry.getParamType( 0 )
1402 new FlatNew( mdSourceEntry.getParamType( 0 ),
1407 TempDescriptor[] sourceEntryArgs = new TempDescriptor[1];
1408 sourceEntryArgs[0] = cmdLineArgs;
1411 new FlatCall( mdSourceEntry,
1417 FlatReturnNode frn = new FlatReturnNode( null );
1419 FlatExit fe = new FlatExit();
1421 this.fmAnalysisEntry =
1422 new FlatMethod( mdAnalysisEntry,
1426 this.fmAnalysisEntry.addNext( fn );
1433 protected LinkedList<Descriptor> topologicalSort( Set<Descriptor> toSort ) {
1435 Set <Descriptor> discovered = new HashSet <Descriptor>();
1436 LinkedList<Descriptor> sorted = new LinkedList<Descriptor>();
1438 Iterator<Descriptor> itr = toSort.iterator();
1439 while( itr.hasNext() ) {
1440 Descriptor d = itr.next();
1442 if( !discovered.contains( d ) ) {
1443 dfsVisit( d, toSort, sorted, discovered );
1450 // While we're doing DFS on call graph, remember
1451 // dependencies for efficient queuing of methods
1452 // during interprocedural analysis:
1454 // a dependent of a method decriptor d for this analysis is:
1455 // 1) a method or task that invokes d
1456 // 2) in the descriptorsToAnalyze set
1457 protected void dfsVisit( Descriptor d,
1458 Set <Descriptor> toSort,
1459 LinkedList<Descriptor> sorted,
1460 Set <Descriptor> discovered ) {
1461 discovered.add( d );
1463 // only methods have callers, tasks never do
1464 if( d instanceof MethodDescriptor ) {
1466 MethodDescriptor md = (MethodDescriptor) d;
1468 // the call graph is not aware that we have a fabricated
1469 // analysis entry that calls the program source's entry
1470 if( md == mdSourceEntry ) {
1471 if( !discovered.contains( mdAnalysisEntry ) ) {
1472 addDependent( mdSourceEntry, // callee
1473 mdAnalysisEntry // caller
1475 dfsVisit( mdAnalysisEntry, toSort, sorted, discovered );
1479 // otherwise call graph guides DFS
1480 Iterator itr = callGraph.getCallerSet( md ).iterator();
1481 while( itr.hasNext() ) {
1482 Descriptor dCaller = (Descriptor) itr.next();
1484 // only consider callers in the original set to analyze
1485 if( !toSort.contains( dCaller ) ) {
1489 if( !discovered.contains( dCaller ) ) {
1490 addDependent( md, // callee
1494 dfsVisit( dCaller, toSort, sorted, discovered );
1499 // for leaf-nodes last now!
1500 sorted.addLast( d );
1504 protected void enqueue( Descriptor d ) {
1505 if( !descriptorsToVisitSet.contains( d ) ) {
1506 Integer priority = mapDescriptorToPriority.get( d );
1507 descriptorsToVisitQ.add( new DescriptorQWrapper( priority,
1510 descriptorsToVisitSet.add( d );
1515 // a dependent of a method decriptor d for this analysis is:
1516 // 1) a method or task that invokes d
1517 // 2) in the descriptorsToAnalyze set
1518 protected void addDependent( Descriptor callee, Descriptor caller ) {
1519 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1520 if( deps == null ) {
1521 deps = new HashSet<Descriptor>();
1524 mapDescriptorToSetDependents.put( callee, deps );
1527 protected Set<Descriptor> getDependents( Descriptor callee ) {
1528 Set<Descriptor> deps = mapDescriptorToSetDependents.get( callee );
1529 if( deps == null ) {
1530 deps = new HashSet<Descriptor>();
1531 mapDescriptorToSetDependents.put( callee, deps );
1537 public Hashtable<FlatCall, ReachGraph> getIHMcontributions( Descriptor d ) {
1539 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1540 mapDescriptorToIHMcontributions.get( d );
1542 if( heapsFromCallers == null ) {
1543 heapsFromCallers = new Hashtable<FlatCall, ReachGraph>();
1544 mapDescriptorToIHMcontributions.put( d, heapsFromCallers );
1547 return heapsFromCallers;
1550 public ReachGraph getIHMcontribution( Descriptor d,
1553 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1554 getIHMcontributions( d );
1556 if( !heapsFromCallers.containsKey( fc ) ) {
1557 heapsFromCallers.put( fc, new ReachGraph() );
1560 return heapsFromCallers.get( fc );
1563 public void addIHMcontribution( Descriptor d,
1567 Hashtable<FlatCall, ReachGraph> heapsFromCallers =
1568 getIHMcontributions( d );
1570 heapsFromCallers.put( fc, rg );
1573 private AllocSite createParameterAllocSite(ReachGraph rg, TempDescriptor tempDesc) {
1575 // create temp descriptor for each parameter variable
1576 FlatNew flatNew = new FlatNew(tempDesc.getType(), tempDesc, false);
1577 // create allocation site
1578 AllocSite as = (AllocSite) Canonical.makeCanonical(new AllocSite( allocationDepth, flatNew, flatNew.getDisjointId()));
1579 for (int i = 0; i < allocationDepth; ++i) {
1580 Integer id = generateUniqueHeapRegionNodeID();
1581 as.setIthOldest(i, id);
1582 mapHrnIdToAllocSite.put(id, as);
1584 // the oldest node is a summary node
1585 as.setSummary( generateUniqueHeapRegionNodeID() );
1593 private Set<FieldDescriptor> getFieldSetTobeAnalyzed(TypeDescriptor typeDesc){
1595 Set<FieldDescriptor> fieldSet=new HashSet<FieldDescriptor>();
1596 if(!typeDesc.isImmutable()){
1597 ClassDescriptor classDesc = typeDesc.getClassDesc();
1598 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1599 FieldDescriptor field = (FieldDescriptor) it.next();
1600 TypeDescriptor fieldType = field.getType();
1601 if (shouldAnalysisTrack( fieldType )) {
1602 fieldSet.add(field);
1610 private HeapRegionNode createMultiDeimensionalArrayHRN(ReachGraph rg, AllocSite alloc, HeapRegionNode srcHRN, FieldDescriptor fd, Hashtable<HeapRegionNode, HeapRegionNode> map, Hashtable<TypeDescriptor, HeapRegionNode> mapToExistingNode, ReachSet alpha ){
1612 int dimCount=fd.getType().getArrayCount();
1613 HeapRegionNode prevNode=null;
1614 HeapRegionNode arrayEntryNode=null;
1615 for(int i=dimCount;i>0;i--){
1616 TypeDescriptor typeDesc=fd.getType().dereference();//hack to get instance of type desc
1617 typeDesc.setArrayCount(i);
1618 TempDescriptor tempDesc=new TempDescriptor(typeDesc.getSymbol(),typeDesc);
1619 HeapRegionNode hrnSummary ;
1620 if(!mapToExistingNode.containsKey(typeDesc)){
1625 as = createParameterAllocSite(rg, tempDesc);
1627 // make a new reference to allocated node
1629 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1630 false, // single object?
1633 false, // out-of-context?
1634 as.getType(), // type
1635 as, // allocation site
1636 null, // inherent reach
1637 alpha, // current reach
1638 ExistPredSet.factory(rg.predTrue), // predicates
1639 tempDesc.toString() // description
1641 rg.id2hrn.put(as.getSummary(),hrnSummary);
1643 mapToExistingNode.put(typeDesc, hrnSummary);
1645 hrnSummary=mapToExistingNode.get(typeDesc);
1649 // make a new reference between new summary node and source
1650 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1653 fd.getSymbol(), // field name
1655 ExistPredSet.factory(rg.predTrue) // predicates
1658 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1659 prevNode=hrnSummary;
1660 arrayEntryNode=hrnSummary;
1662 // make a new reference between summary nodes of array
1663 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1666 arrayElementFieldName, // field name
1668 ExistPredSet.factory(rg.predTrue) // predicates
1671 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1672 prevNode=hrnSummary;
1677 // create a new obj node if obj has at least one non-primitive field
1678 TypeDescriptor type=fd.getType();
1679 if(getFieldSetTobeAnalyzed(type).size()>0){
1680 TypeDescriptor typeDesc=type.dereference();
1681 typeDesc.setArrayCount(0);
1682 if(!mapToExistingNode.containsKey(typeDesc)){
1683 TempDescriptor tempDesc=new TempDescriptor(type.getSymbol(),typeDesc);
1684 AllocSite as = createParameterAllocSite(rg, tempDesc);
1685 // make a new reference to allocated node
1686 HeapRegionNode hrnSummary =
1687 rg.createNewHeapRegionNode(as.getSummary(), // id or null to generate a new one
1688 false, // single object?
1691 false, // out-of-context?
1693 as, // allocation site
1694 null, // inherent reach
1695 alpha, // current reach
1696 ExistPredSet.factory(rg.predTrue), // predicates
1697 tempDesc.toString() // description
1699 rg.id2hrn.put(as.getSummary(),hrnSummary);
1700 mapToExistingNode.put(typeDesc, hrnSummary);
1701 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1704 arrayElementFieldName, // field name
1706 ExistPredSet.factory(rg.predTrue) // predicates
1708 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1709 prevNode=hrnSummary;
1711 HeapRegionNode hrnSummary=mapToExistingNode.get(typeDesc);
1712 if(prevNode.getReferenceTo(hrnSummary, typeDesc, arrayElementFieldName)==null){
1713 RefEdge edgeToSummary = new RefEdge(prevNode, // source
1716 arrayElementFieldName, // field name
1718 ExistPredSet.factory(rg.predTrue) // predicates
1720 rg.addRefEdge(prevNode, hrnSummary, edgeToSummary);
1722 prevNode=hrnSummary;
1726 map.put(arrayEntryNode, prevNode);
1727 return arrayEntryNode;
1730 private ReachGraph createInitialTaskReachGraph(FlatMethod fm) {
1731 ReachGraph rg = new ReachGraph();
1732 TaskDescriptor taskDesc = fm.getTask();
1734 for (int idx = 0; idx < taskDesc.numParameters(); idx++) {
1735 Descriptor paramDesc = taskDesc.getParameter(idx);
1736 TypeDescriptor paramTypeDesc = taskDesc.getParamType(idx);
1738 // setup data structure
1739 Set<HashMap<HeapRegionNode, FieldDescriptor>> workSet =
1740 new HashSet<HashMap<HeapRegionNode, FieldDescriptor>>();
1741 Hashtable<TypeDescriptor, HeapRegionNode> mapTypeToExistingSummaryNode =
1742 new Hashtable<TypeDescriptor, HeapRegionNode>();
1743 Hashtable<HeapRegionNode, HeapRegionNode> mapToFirstDimensionArrayNode =
1744 new Hashtable<HeapRegionNode, HeapRegionNode>();
1745 Set<String> doneSet = new HashSet<String>();
1747 TempDescriptor tempDesc = fm.getParameter(idx);
1749 AllocSite as = createParameterAllocSite(rg, tempDesc);
1750 VariableNode lnX = rg.getVariableNodeFromTemp(tempDesc);
1751 Integer idNewest = as.getIthOldest(0);
1752 HeapRegionNode hrnNewest = rg.id2hrn.get(idNewest);
1753 // make a new reference to allocated node
1754 RefEdge edgeNew = new RefEdge(lnX, // source
1756 taskDesc.getParamType(idx), // type
1758 hrnNewest.getAlpha(), // beta
1759 ExistPredSet.factory(rg.predTrue) // predicates
1761 rg.addRefEdge(lnX, hrnNewest, edgeNew);
1763 // set-up a work set for class field
1764 ClassDescriptor classDesc = paramTypeDesc.getClassDesc();
1765 for (Iterator it = classDesc.getFields(); it.hasNext();) {
1766 FieldDescriptor fd = (FieldDescriptor) it.next();
1767 TypeDescriptor fieldType = fd.getType();
1768 if (shouldAnalysisTrack( fieldType )) {
1769 HashMap<HeapRegionNode, FieldDescriptor> newMap = new HashMap<HeapRegionNode, FieldDescriptor>();
1770 newMap.put(hrnNewest, fd);
1771 workSet.add(newMap);
1775 int uniqueIdentifier = 0;
1776 while (!workSet.isEmpty()) {
1777 HashMap<HeapRegionNode, FieldDescriptor> map = workSet
1779 workSet.remove(map);
1781 Set<HeapRegionNode> key = map.keySet();
1782 HeapRegionNode srcHRN = key.iterator().next();
1783 FieldDescriptor fd = map.get(srcHRN);
1784 TypeDescriptor type = fd.getType();
1785 String doneSetIdentifier = srcHRN.getIDString() + "_" + fd;
1787 if (!doneSet.contains(doneSetIdentifier)) {
1788 doneSet.add(doneSetIdentifier);
1789 if (!mapTypeToExistingSummaryNode.containsKey(type)) {
1790 // create new summary Node
1791 TempDescriptor td = new TempDescriptor("temp"
1792 + uniqueIdentifier, type);
1794 AllocSite allocSite;
1795 if(type.equals(paramTypeDesc)){
1796 //corresponding allocsite has already been created for a parameter variable.
1799 allocSite = createParameterAllocSite(rg, td);
1801 String strDesc = allocSite.toStringForDOT()
1803 TypeDescriptor allocType=allocSite.getType();
1805 HeapRegionNode hrnSummary;
1806 if(allocType.isArray() && allocType.getArrayCount()>0){
1807 hrnSummary=createMultiDeimensionalArrayHRN(rg,allocSite,srcHRN,fd,mapToFirstDimensionArrayNode,mapTypeToExistingSummaryNode,hrnNewest.getAlpha());
1810 rg.createNewHeapRegionNode(allocSite.getSummary(), // id or null to generate a new one
1811 false, // single object?
1814 false, // out-of-context?
1815 allocSite.getType(), // type
1816 allocSite, // allocation site
1817 null, // inherent reach
1818 hrnNewest.getAlpha(), // current reach
1819 ExistPredSet.factory(rg.predTrue), // predicates
1820 strDesc // description
1822 rg.id2hrn.put(allocSite.getSummary(),hrnSummary);
1824 // make a new reference to summary node
1825 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1828 fd.getSymbol(), // field name
1829 hrnNewest.getAlpha(), // beta
1830 ExistPredSet.factory(rg.predTrue) // predicates
1833 rg.addRefEdge(srcHRN, hrnSummary, edgeToSummary);
1837 mapTypeToExistingSummaryNode.put(type, hrnSummary);
1839 // set-up a work set for fields of the class
1840 Set<FieldDescriptor> fieldTobeAnalyzed=getFieldSetTobeAnalyzed(type);
1841 for (Iterator iterator = fieldTobeAnalyzed.iterator(); iterator
1843 FieldDescriptor fieldDescriptor = (FieldDescriptor) iterator
1845 HeapRegionNode newDstHRN;
1846 if(mapToFirstDimensionArrayNode.containsKey(hrnSummary)){
1847 //related heap region node is already exsited.
1848 newDstHRN=mapToFirstDimensionArrayNode.get(hrnSummary);
1850 newDstHRN=hrnSummary;
1852 doneSetIdentifier = newDstHRN.getIDString() + "_" + fieldDescriptor;
1853 if(!doneSet.contains(doneSetIdentifier)){
1854 // add new work item
1855 HashMap<HeapRegionNode, FieldDescriptor> newMap =
1856 new HashMap<HeapRegionNode, FieldDescriptor>();
1857 newMap.put(newDstHRN, fieldDescriptor);
1858 workSet.add(newMap);
1863 // if there exists corresponding summary node
1864 HeapRegionNode hrnDst=mapTypeToExistingSummaryNode.get(type);
1866 RefEdge edgeToSummary = new RefEdge(srcHRN, // source
1868 fd.getType(), // type
1869 fd.getSymbol(), // field name
1870 srcHRN.getAlpha(), // beta
1871 ExistPredSet.factory(rg.predTrue) // predicates
1873 rg.addRefEdge(srcHRN, hrnDst, edgeToSummary);
1879 // debugSnapshot(rg, fm, true);
1883 // return all allocation sites in the method (there is one allocation
1884 // site per FlatNew node in a method)
1885 private HashSet<AllocSite> getAllocationSiteSet(Descriptor d) {
1886 if( !mapDescriptorToAllocSiteSet.containsKey(d) ) {
1887 buildAllocationSiteSet(d);
1890 return mapDescriptorToAllocSiteSet.get(d);
1894 private void buildAllocationSiteSet(Descriptor d) {
1895 HashSet<AllocSite> s = new HashSet<AllocSite>();
1898 if( d instanceof MethodDescriptor ) {
1899 fm = state.getMethodFlat( (MethodDescriptor) d);
1901 assert d instanceof TaskDescriptor;
1902 fm = state.getMethodFlat( (TaskDescriptor) d);
1904 pm.analyzeMethod(fm);
1906 // visit every node in this FlatMethod's IR graph
1907 // and make a set of the allocation sites from the
1908 // FlatNew node's visited
1909 HashSet<FlatNode> visited = new HashSet<FlatNode>();
1910 HashSet<FlatNode> toVisit = new HashSet<FlatNode>();
1913 while( !toVisit.isEmpty() ) {
1914 FlatNode n = toVisit.iterator().next();
1916 if( n instanceof FlatNew ) {
1917 s.add(getAllocSiteFromFlatNewPRIVATE( (FlatNew) n) );
1923 for( int i = 0; i < pm.numNext(n); ++i ) {
1924 FlatNode child = pm.getNext(n, i);
1925 if( !visited.contains(child) ) {
1931 mapDescriptorToAllocSiteSet.put(d, s);
1934 private HashSet<AllocSite> getFlaggedAllocationSites(Descriptor dIn) {
1936 HashSet<AllocSite> out = new HashSet<AllocSite>();
1937 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1938 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1942 while (!toVisit.isEmpty()) {
1943 Descriptor d = toVisit.iterator().next();
1947 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
1948 Iterator asItr = asSet.iterator();
1949 while (asItr.hasNext()) {
1950 AllocSite as = (AllocSite) asItr.next();
1951 if (as.getDisjointAnalysisId() != null) {
1956 // enqueue callees of this method to be searched for
1957 // allocation sites also
1958 Set callees = callGraph.getCalleeSet(d);
1959 if (callees != null) {
1960 Iterator methItr = callees.iterator();
1961 while (methItr.hasNext()) {
1962 MethodDescriptor md = (MethodDescriptor) methItr.next();
1964 if (!visited.contains(md)) {
1975 private HashSet<AllocSite>
1976 getFlaggedAllocationSitesReachableFromTaskPRIVATE(TaskDescriptor td) {
1978 HashSet<AllocSite> asSetTotal = new HashSet<AllocSite>();
1979 HashSet<Descriptor> toVisit = new HashSet<Descriptor>();
1980 HashSet<Descriptor> visited = new HashSet<Descriptor>();
1984 // traverse this task and all methods reachable from this task
1985 while( !toVisit.isEmpty() ) {
1986 Descriptor d = toVisit.iterator().next();
1990 HashSet<AllocSite> asSet = getAllocationSiteSet(d);
1991 Iterator asItr = asSet.iterator();
1992 while( asItr.hasNext() ) {
1993 AllocSite as = (AllocSite) asItr.next();
1994 TypeDescriptor typed = as.getType();
1995 if( typed != null ) {
1996 ClassDescriptor cd = typed.getClassDesc();
1997 if( cd != null && cd.hasFlags() ) {
2003 // enqueue callees of this method to be searched for
2004 // allocation sites also
2005 Set callees = callGraph.getCalleeSet(d);
2006 if( callees != null ) {
2007 Iterator methItr = callees.iterator();
2008 while( methItr.hasNext() ) {
2009 MethodDescriptor md = (MethodDescriptor) methItr.next();
2011 if( !visited.contains(md) ) {
2024 // get successive captures of the analysis state, use compiler
2026 boolean takeDebugSnapshots = false;
2027 String descSymbolDebug = null;
2028 boolean stopAfterCapture = false;
2029 int snapVisitCounter = 0;
2030 int snapNodeCounter = 0;
2031 int visitStartCapture = 0;
2032 int numVisitsToCapture = 0;
2035 void debugSnapshot( ReachGraph rg, FlatNode fn, boolean in ) {
2036 if( snapVisitCounter > visitStartCapture + numVisitsToCapture ) {
2044 if( snapVisitCounter >= visitStartCapture ) {
2045 System.out.println( " @@@ snapping visit="+snapVisitCounter+
2046 ", node="+snapNodeCounter+
2050 graphName = String.format( "snap%02d_%04din",
2054 graphName = String.format( "snap%02d_%04dout",
2059 graphName = graphName + fn;
2061 rg.writeGraph( graphName,
2062 true, // write labels (variables)
2063 true, // selectively hide intermediate temp vars
2064 true, // prune unreachable heap regions
2065 false, // hide subset reachability states
2066 true );// hide edge taints