3 import java.io.FileNotFoundException;
4 import java.io.PrintWriter;
5 import java.util.ArrayList;
6 import java.util.Collection;
7 import java.util.HashSet;
8 import java.util.Hashtable;
9 import java.util.Iterator;
11 import java.util.Vector;
13 import Analysis.Disjoint.*;
14 import Analysis.MLP.CodePlan;
15 import IR.TypeDescriptor;
16 import Analysis.OoOJava.OoOJavaAnalysis;
18 /* An instance of this class manages all OoOJava coarse-grained runtime conflicts
19 * by generating C-code to either rule out the conflict at runtime or resolve one.
22 * 1) Instantiate singleton object (String input is to specify output dir)
23 * 2) Call setGlobalEffects setGlobalEffects(Hashtable<Taint, Set<Effect>> ) ONCE
24 * 3) Input SESE blocks, for each block:
25 * 3a) call addToTraverseToDoList(FlatSESEEnterNode , ReachGraph , Hashtable<Taint, Set<Effect>>) for the seseBlock
26 * 3b) call String getTraverserInvocation(TempDescriptor, String, FlatSESEEnterNode) to get the name of the traverse method in C
27 * 4) Call void close()
28 * Note: All computation is done upon closing the object. Steps 1-3 only input data
30 public class RuntimeConflictResolver {
31 public static final boolean generalDebug = true;
32 //Prints out effects and data structure used to steer RCR traversals
33 public static final boolean printEffectsAndEffectsTable = false;
34 //Prints steps taken to build internal representation of pruned reach graph
35 public static final boolean traceDataStructureBuild = false;
36 public static final boolean cSideDebug = false;
38 private PrintWriter cFile;
39 private PrintWriter headerFile;
40 private static final String hashAndQueueCFileDir = "oooJava/";
41 //This keeps track of taints we've traversed to prevent printing duplicate traverse functions
42 //The Integer keeps track of the weakly connected group it's in (used in enumerateHeapRoots)
43 private Hashtable<Taint, Integer> doneTaints;
44 private Hashtable<Tuple, Integer> idMap=new Hashtable<Tuple,Integer>();
45 private Hashtable<Tuple, Integer> weakMap=new Hashtable<Tuple,Integer>();
46 private Hashtable<Taint, Set<Effect>> globalEffects;
47 private Hashtable<Taint, Set<Effect>> globalConflicts;
48 private ArrayList<TraversalInfo> toTraverse;
50 public int currentID=1;
52 // initializing variables can be found in printHeader()
53 private static final String getAllocSiteInC = "->allocsite";
54 private static final String queryVistedHashtable = "hashRCRInsert";
55 private static final String addToQueueInC = "enqueueRCRQueue(";
56 private static final String dequeueFromQueueInC = "dequeueRCRQueue()";
57 private static final String clearQueue = "resetRCRQueue()";
58 // Make hashtable; hashRCRCreate(unsigned int size, double loadfactor)
59 private static final String mallocVisitedHashtable = "hashRCRCreate(128, 0.75)";
60 private static final String deallocVisitedHashTable = "hashRCRDelete()";
61 private static final String resetVisitedHashTable = "hashRCRreset()";
63 // Hashtable provides fast access to heaproot # lookups
64 private Hashtable<Taint, WeaklyConectedHRGroup> connectedHRHash;
65 private ArrayList<WeaklyConectedHRGroup> num2WeaklyConnectedHRGroup;
66 private int traverserIDCounter;
67 private int weaklyConnectedHRCounter;
68 private ArrayList<TaintAndInternalHeapStructure> pendingPrintout;
69 private EffectsTable effectsLookupTable;
70 private OoOJavaAnalysis oooa;
72 public RuntimeConflictResolver(String buildir, OoOJavaAnalysis oooa) throws FileNotFoundException {
73 String outputFile = buildir + "RuntimeConflictResolver";
76 cFile = new PrintWriter(new File(outputFile + ".c"));
77 headerFile = new PrintWriter(new File(outputFile + ".h"));
79 cFile.println("#include \"" + hashAndQueueCFileDir + "hashRCR.h\"\n#include \""
80 + hashAndQueueCFileDir + "Queue_RCR.h\"\n#include <stdlib.h>");
81 cFile.println("#include \"classdefs.h\"");
82 cFile.println("#include \"structdefs.h\"");
83 cFile.println("#include \"mlp_runtime.h\"");
84 cFile.println("#include \"RuntimeConflictResolver.h\"");
85 cFile.println("#include \"hashStructure.h\"");
87 headerFile.println("#ifndef __3_RCR_H_");
88 headerFile.println("#define __3_RCR_H_");
90 doneTaints = new Hashtable<Taint, Integer>();
91 connectedHRHash = new Hashtable<Taint, WeaklyConectedHRGroup>();
93 traverserIDCounter = 1;
94 weaklyConnectedHRCounter = 0;
95 pendingPrintout = new ArrayList<TaintAndInternalHeapStructure>();
96 toTraverse = new ArrayList<TraversalInfo>();
97 globalConflicts = new Hashtable<Taint, Set<Effect>>();
98 //Note: globalEffects is not instantiated since it'll be passed in whole while conflicts comes in chunks
101 public void setGlobalEffects(Hashtable<Taint, Set<Effect>> effects) {
102 globalEffects = effects;
104 if(printEffectsAndEffectsTable) {
105 System.out.println("============EFFECTS LIST AS PASSED IN============");
106 for(Taint t: globalEffects.keySet()) {
107 System.out.println("For Taint " + t);
108 for(Effect e: globalEffects.get(t)) {
109 System.out.println("\t" + e);
112 System.out.println("====================END LIST====================");
117 // Go through the SESE's
118 for (Iterator<FlatSESEEnterNode> seseit = oooa.getAllSESEs().iterator(); seseit.hasNext();) {
119 FlatSESEEnterNode fsen = seseit.next();
120 Analysis.OoOJava.ConflictGraph conflictGraph;
121 Hashtable<Taint, Set<Effect>> conflicts;
122 System.out.println("-------");
123 System.out.println(fsen);
124 System.out.println(fsen.getIsCallerSESEplaceholder());
125 System.out.println(fsen.getParent());
127 if (fsen.getParent() != null) {
128 conflictGraph = oooa.getConflictGraph(fsen.getParent());
129 System.out.println("CG=" + conflictGraph);
130 if (conflictGraph != null)
131 System.out.println("Conflicts=" + conflictGraph.getConflictEffectSet(fsen));
134 if (!fsen.getIsCallerSESEplaceholder() && fsen.getParent() != null
135 && (conflictGraph = oooa.getConflictGraph(fsen.getParent())) != null
136 && (conflicts = conflictGraph.getConflictEffectSet(fsen)) != null) {
137 FlatMethod fm = fsen.getfmEnclosing();
138 ReachGraph rg = oooa.getDisjointAnalysis().getReachGraph(fm.getMethod());
140 rg.writeGraph("RCR_RG_SESE_DEBUG");
142 addToTraverseToDoList(fsen, rg, conflicts);
145 // Go through the stall sites
146 for (Iterator<FlatNode> codeit = oooa.getNodesWithPlans().iterator(); codeit.hasNext();) {
147 FlatNode fn = codeit.next();
148 CodePlan cp = oooa.getCodePlan(fn);
149 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
150 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
153 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
154 Set<Analysis.OoOJava.WaitingElement> waitingElementSet =
155 graph.getStallSiteWaitingElementSet(fn, seseLockSet);
157 if (waitingElementSet.size() > 0) {
158 for (Iterator<Analysis.OoOJava.WaitingElement> iterator = waitingElementSet.iterator(); iterator.hasNext();) {
159 Analysis.OoOJava.WaitingElement waitingElement =
160 (Analysis.OoOJava.WaitingElement) iterator.next();
162 Analysis.OoOJava.ConflictGraph conflictGraph = graph;
163 Hashtable<Taint, Set<Effect>> conflicts;
164 ReachGraph rg = oooa.getDisjointAnalysis().getReachGraph(currentSESE.getmdEnclosing());
166 rg.writeGraph("RCR_RG_STALLSITE_DEBUG");
168 if ((conflictGraph != null) && (conflicts = graph.getConflictEffectSet(fn)) != null
170 addToTraverseToDoList(fn, waitingElement.getTempDesc(), rg, conflicts);
177 buildEffectsLookupStructure();
183 * 1) Get global effects and conflicts
184 * 2) Create a hash structure (EffectsTable) to manage effects (hashed by affected Allocsite, then taint, then field)
185 * 2a) Use Effects to verify we can access something (reads)
186 * 2b) Use conflicts to mark conflicts (read/write/strongupdate)
187 * 2c) At second level of hash, store Heaproots that can cause conflicts at the field
188 * 3) Walk hash structure to identify and enumerate weakly connected groups and generate waiting queue slots.
189 * 4) Build internal representation of the rgs (pruned)
190 * 5) Print c methods by walking internal representation
193 public void addToTraverseToDoList(FlatSESEEnterNode rblock, ReachGraph rg,
194 Hashtable<Taint, Set<Effect>> conflicts) {
196 toTraverse.add(new TraversalInfo(rblock, rg));
198 //Add to Global conflicts
199 for(Taint t: conflicts.keySet()) {
200 if(globalConflicts.containsKey(t)) {
201 globalConflicts.get(t).addAll(conflicts.get(t));
203 globalConflicts.put(t, conflicts.get(t));
209 public void addToTraverseToDoList(FlatNode fn, TempDescriptor tempDesc,
210 ReachGraph rg, Hashtable<Taint, Set<Effect>> conflicts) {
211 toTraverse.add(new TraversalInfo(fn, rg, tempDesc));
213 for(Taint t: conflicts.keySet()) {
214 if(globalConflicts.containsKey(t)) {
215 globalConflicts.get(t).addAll(conflicts.get(t));
217 globalConflicts.put(t, conflicts.get(t));
222 private void traverseSESEBlock(FlatSESEEnterNode rblock, ReachGraph rg) {
223 Collection<TempDescriptor> inVars = rblock.getInVarSet();
225 if (inVars.size() == 0)
227 System.out.println("RBLOCK:"+rblock);
228 System.out.println("["+inVars+"]");
230 // For every non-primitive variable, generate unique method
231 for (TempDescriptor invar : inVars) {
232 TypeDescriptor type = invar.getType();
233 if(isReallyAPrimitive(type)) {
236 System.out.println(invar);
237 //"created" stores nodes with specific alloc sites that have been traversed while building
238 //internal data structure. Created is later traversed sequentially to find inset variables and
240 //NOTE: Integer stores Allocation Site ID in hashtable
241 Hashtable<Integer, ConcreteRuntimeObjNode> created = new Hashtable<Integer, ConcreteRuntimeObjNode>();
242 VariableNode varNode = rg.getVariableNodeNoMutation(invar);
243 Taint taint = getProperTaintForFlatSESEEnterNode(rblock, varNode, globalEffects);
245 printDebug(generalDebug, "Null FOR " +varNode.getTempDescriptor().getSafeSymbol() + rblock.toPrettyString());
249 //This is to prevent duplicate traversals from being generated
250 if(doneTaints.containsKey(taint))
253 doneTaints.put(taint, traverserIDCounter++);
254 createConcreteGraph(effectsLookupTable, created, varNode, taint);
257 //This will add the taint to the printout, there will be NO duplicates (checked above)
258 if(!created.isEmpty()) {
259 for(Iterator<ConcreteRuntimeObjNode> it=created.values().iterator();it.hasNext();) {
260 ConcreteRuntimeObjNode obj=it.next();
261 if (obj.hasPrimitiveConflicts()||obj.decendantsConflict()||obj.hasDirectObjConflict) {
262 rblock.addInVarForDynamicCoarseConflictResolution(invar);
267 pendingPrintout.add(new TaintAndInternalHeapStructure(taint, created));
272 //This extends a tempDescriptor's isPrimitive test by also excluding primitive arrays.
273 private boolean isReallyAPrimitive(TypeDescriptor type) {
274 return (type.isPrimitive() && !type.isArray());
277 private void traverseStallSite(FlatNode enterNode, TempDescriptor invar, ReachGraph rg) {
278 TypeDescriptor type = invar.getType();
279 if(type == null || isReallyAPrimitive(type)) {
283 Hashtable<Integer, ConcreteRuntimeObjNode> created = new Hashtable<Integer, ConcreteRuntimeObjNode>();
284 VariableNode varNode = rg.getVariableNodeNoMutation(invar);
285 Taint taint = getProperTaintForEnterNode(enterNode, varNode, globalEffects);
288 printDebug(generalDebug, "Null FOR " +varNode.getTempDescriptor().getSafeSymbol() + enterNode.toString());
292 if(doneTaints.containsKey(taint))
295 doneTaints.put(taint, traverserIDCounter++);
296 createConcreteGraph(effectsLookupTable, created, varNode, taint);
298 if (!created.isEmpty()) {
299 pendingPrintout.add(new TaintAndInternalHeapStructure(taint, created));
303 public String getTraverserInvocation(TempDescriptor invar, String varString, FlatNode fn) {
305 if(fn instanceof FlatSESEEnterNode) {
306 flatname = ((FlatSESEEnterNode) fn).getPrettyIdentifier();
308 flatname = fn.toString();
311 return "traverse___" + invar.getSafeSymbol() +
312 removeInvalidChars(flatname) + "___("+varString+");";
315 public int getWeakID(TempDescriptor invar, FlatNode fn) {
316 return weakMap.get(new Tuple(invar, fn)).intValue();
319 public int getTraverserID(TempDescriptor invar, FlatNode fn) {
320 Tuple t=new Tuple(invar, fn);
321 if (idMap.containsKey(t))
322 return idMap.get(t).intValue();
323 int value=currentID++;
324 idMap.put(t, new Integer(value));
328 public String removeInvalidChars(String in) {
329 StringBuilder s = new StringBuilder(in);
330 for(int i = 0; i < s.length(); i++) {
331 if(s.charAt(i) == ' ' || s.charAt(i) == '.' || s.charAt(i) == '='||s.charAt(i)=='['||s.charAt(i)==']') {
339 public void close() {
340 //prints out all generated code
341 for(TaintAndInternalHeapStructure ths: pendingPrintout) {
342 printCMethod(ths.nodesInHeap, ths.t);
345 //Prints out the master traverser Invocation that'll call all other traversers
346 //based on traverserID
347 printMasterTraverserInvocation();
348 printResumeTraverserInvocation();
350 //TODO this is only temporary, remove when thread local vars implemented.
351 createMasterHashTableArray();
353 // Adds Extra supporting methods
354 cFile.println("void initializeStructsRCR() {\n " + mallocVisitedHashtable + ";\n " + clearQueue + ";\n}");
355 cFile.println("void destroyRCR() {\n " + deallocVisitedHashTable + ";\n}");
357 headerFile.println("void initializeStructsRCR();\nvoid destroyRCR();");
358 headerFile.println("#endif\n");
364 //Builds Effects Table and runs the analysis on them to get weakly connected HRs
365 //SPECIAL NOTE: Only runs after we've taken all the conflicts and effects
366 private void buildEffectsLookupStructure(){
367 effectsLookupTable = new EffectsTable(globalEffects, globalConflicts);
368 effectsLookupTable.runAnalysis();
369 enumerateHeaproots();
372 private void runAllTraversals() {
373 for(TraversalInfo t: toTraverse) {
374 printDebug(generalDebug, "Running Traversal a traversal on " + t.f);
376 if(t.f instanceof FlatSESEEnterNode) {
377 traverseSESEBlock((FlatSESEEnterNode)t.f, t.rg);
379 if(t.invar == null) {
380 System.out.println("RCR ERROR: Attempted to run a stall site traversal with NO INVAR");
382 traverseStallSite(t.f, t.invar, t.rg);
389 //TODO: This is only temporary, remove when thread local variables are functional.
390 private void createMasterHashTableArray() {
391 headerFile.println("struct Hashtable_rcr ** createAndFillMasterHashStructureArray();");
392 cFile.println("struct Hashtable_rcr ** createAndFillMasterHashStructureArray() {");
393 cFile.println(" struct Hashtable_rcr **table=rcr_createMasterHashTableArray("+weaklyConnectedHRCounter + ");");
395 for(int i = 0; i < weaklyConnectedHRCounter; i++) {
396 cFile.println(" table["+i+"] = (struct Hashtable_rcr *) rcr_createHashtable("+num2WeaklyConnectedHRGroup.get(i).connectedHRs.size()+");");
398 cFile.println(" return table;");
402 private void printMasterTraverserInvocation() {
403 headerFile.println("\nint tasktraverse(SESEcommon * record);");
404 cFile.println("\nint tasktraverse(SESEcommon * record) {");
405 cFile.println(" if(!CAS(&record->rcrstatus,1,2)) {");
406 //release traverser reference...no traversal necessary
407 cFile.println("#ifndef OOO_DISABLE_TASKMEMPOOL");
408 cFile.println(" RELEASE_REFERENCE_TO(record);");
409 cFile.println("#endif");
410 cFile.println(" return;");
412 cFile.println(" switch(record->classID) {");
414 for(Iterator<FlatSESEEnterNode> seseit=oooa.getAllSESEs().iterator();seseit.hasNext();) {
415 FlatSESEEnterNode fsen=seseit.next();
416 cFile.println( " /* "+fsen.getPrettyIdentifier()+" */");
417 cFile.println( " case "+fsen.getIdentifier()+": {");
418 cFile.println( " "+fsen.getSESErecordName()+" * rec=("+fsen.getSESErecordName()+" *) record;");
419 Vector<TempDescriptor> invars=fsen.getInVarsForDynamicCoarseConflictResolution();
420 for(int i=0;i<invars.size();i++) {
421 TempDescriptor tmp=invars.get(i);
422 cFile.println(" " + this.getTraverserInvocation(tmp, "rec->"+tmp+", rec", fsen));
424 //release traverser reference...traversal finished...
425 //executing thread will clean bins for us
426 cFile.println("#ifndef OOO_DISABLE_TASKMEMPOOL");
427 cFile.println(" RELEASE_REFERENCE_TO(record);");
428 cFile.println("#endif");
429 cFile.println( " }");
430 cFile.println( " break;");
433 for(Taint t: doneTaints.keySet()) {
434 if (t.isStallSiteTaint()){
435 cFile.println( " case -" + getTraverserID(t.getVar(), t.getStallSite())+ ": {");
436 cFile.println( " SESEstall * rec=(SESEstall*) record;");
437 cFile.println( " " + this.getTraverserInvocation(t.getVar(), "rec->___obj___, rec", t.getStallSite())+";");
438 cFile.println( " }");
439 cFile.println(" break;");
443 cFile.println(" default:\n printf(\"Invalid SESE ID was passed in: %d.\\n\",record->classID);\n break;");
449 //This will print the traverser invocation that takes in a traverserID and starting ptr
450 private void printResumeTraverserInvocation() {
451 headerFile.println("\nint traverse(void * startingPtr, SESEcommon * record, int traverserID);");
452 cFile.println("\nint traverse(void * startingPtr, SESEcommon *record, int traverserID) {");
453 cFile.println(" switch(traverserID) {");
455 for(Taint t: doneTaints.keySet()) {
456 cFile.println(" case " + doneTaints.get(t)+ ":");
457 if(t.isRBlockTaint()) {
458 cFile.println(" " + this.getTraverserInvocation(t.getVar(), "startingPtr, ("+t.getSESE().getSESErecordName()+" *)record", t.getSESE()));
459 } else if (t.isStallSiteTaint()){
460 cFile.println("/* " + this.getTraverserInvocation(t.getVar(), "startingPtr, record", t.getStallSite())+"*/");
462 System.out.println("RuntimeConflictResolver encountered a taint that is neither SESE nor stallsite: " + t);
464 cFile.println(" break;");
467 if(RuntimeConflictResolver.cSideDebug) {
468 cFile.println(" default:\n printf(\"Invalid traverser ID %u was passed in.\\n\", traverserID);\n break;");
470 cFile.println(" default:\n break;");
477 private void createConcreteGraph(
479 Hashtable<Integer, ConcreteRuntimeObjNode> created,
480 VariableNode varNode,
483 // if table is null that means there's no conflicts, therefore we need not
484 // create a traversal
488 Iterator<RefEdge> possibleEdges = varNode.iteratorToReferencees();
489 while (possibleEdges.hasNext()) {
490 RefEdge edge = possibleEdges.next();
493 ConcreteRuntimeObjNode singleRoot = new ConcreteRuntimeObjNode(edge.getDst(), true);
494 int rootKey = singleRoot.allocSite.getUniqueAllocSiteID();
496 if (!created.containsKey(rootKey)) {
497 created.put(rootKey, singleRoot);
498 createHelper(singleRoot, edge.getDst().iteratorToReferencees(), created, table, t);
503 // Plan is to add stuff to the tree depth-first sort of way. That way, we can
504 // propagate up conflicts
505 private void createHelper(ConcreteRuntimeObjNode curr,
506 Iterator<RefEdge> edges,
507 Hashtable<Integer, ConcreteRuntimeObjNode> created,
510 assert table != null;
511 AllocSite parentKey = curr.allocSite;
512 EffectsGroup currEffects = table.getEffects(parentKey, taint);
514 if (currEffects == null || currEffects.isEmpty())
517 //Handle Objects (and primitives if child is new)
518 if(currEffects.hasObjectEffects()) {
519 while(edges.hasNext()) {
520 RefEdge edge = edges.next();
521 String field = edge.getField();
522 CombinedObjEffects effectsForGivenField = currEffects.getObjEffect(field);
523 //If there are no effects, then there's no point in traversing this edge
524 if(effectsForGivenField != null) {
525 HeapRegionNode childHRN = edge.getDst();
526 int childKey = childHRN.getAllocSite().getUniqueAllocSiteID();
527 boolean isNewChild = !created.containsKey(childKey);
528 ConcreteRuntimeObjNode child;
531 child = new ConcreteRuntimeObjNode(childHRN, false);
532 created.put(childKey, child);
534 child = created.get(childKey);
537 curr.addObjChild(field, child, effectsForGivenField);
539 if (effectsForGivenField.hasConflict()) {
540 child.hasPotentialToBeIncorrectDueToConflict |= effectsForGivenField.hasReadConflict;
541 propagateObjConflict(curr, child);
544 if(effectsForGivenField.hasReadEffect) {
545 child.addReachableParent(curr);
547 //If isNewChild, flag propagation will be handled at recursive call
549 createHelper(child, childHRN.iteratorToReferencees(), created, table, taint);
551 //This makes sure that all conflicts below the child is propagated up the referencers.
552 if(child.decendantsPrimConflict || child.hasPrimitiveConflicts()) {
553 propagatePrimConflict(child, child.enqueueToWaitingQueueUponConflict);
556 if(child.decendantsObjConflict) {
557 propagateObjConflict(child, child.enqueueToWaitingQueueUponConflict);
566 curr.primitiveConflictingFields = currEffects.primitiveConflictingFields;
567 if(currEffects.hasPrimitiveConflicts()) {
568 //Reminder: primitive conflicts are abstracted to object.
569 propagatePrimConflict(curr, curr);
573 // This will propagate the conflict up the data structure.
574 private void propagateObjConflict(ConcreteRuntimeObjNode curr, HashSet<ConcreteRuntimeObjNode> pointsOfAccess) {
575 for(ConcreteRuntimeObjNode referencer: curr.parentsWithReadToNode) {
576 if(curr.parentsThatWillLeadToConflicts.add(referencer) || //case where referencee has never seen referncer
577 (pointsOfAccess != null && referencer.addPossibleWaitingQueueEnqueue(pointsOfAccess))) // case where referencer has never seen possible unresolved referencee below
579 referencer.decendantsObjConflict = true;
580 propagateObjConflict(referencer, pointsOfAccess);
585 private void propagateObjConflict(ConcreteRuntimeObjNode curr, ConcreteRuntimeObjNode pointOfAccess) {
586 for(ConcreteRuntimeObjNode referencer: curr.parentsWithReadToNode) {
587 if(curr.parentsThatWillLeadToConflicts.add(referencer) || //case where referencee has never seen referncer
588 (pointOfAccess != null && referencer.addPossibleWaitingQueueEnqueue(pointOfAccess))) // case where referencer has never seen possible unresolved referencee below
590 referencer.decendantsObjConflict = true;
591 propagateObjConflict(referencer, pointOfAccess);
596 private void propagatePrimConflict(ConcreteRuntimeObjNode curr, HashSet<ConcreteRuntimeObjNode> pointsOfAccess) {
597 for(ConcreteRuntimeObjNode referencer: curr.parentsWithReadToNode) {
598 if(curr.parentsThatWillLeadToConflicts.add(referencer) || //same cases as above
599 (pointsOfAccess != null && referencer.addPossibleWaitingQueueEnqueue(pointsOfAccess)))
601 referencer.decendantsPrimConflict = true;
602 propagatePrimConflict(referencer, pointsOfAccess);
607 private void propagatePrimConflict(ConcreteRuntimeObjNode curr, ConcreteRuntimeObjNode pointOfAccess) {
608 for(ConcreteRuntimeObjNode referencer: curr.parentsWithReadToNode) {
609 if(curr.parentsThatWillLeadToConflicts.add(referencer) || //same cases as above
610 (pointOfAccess != null && referencer.addPossibleWaitingQueueEnqueue(pointOfAccess)))
612 referencer.decendantsPrimConflict = true;
613 propagatePrimConflict(referencer, pointOfAccess);
619 * This method generates a C method for every inset variable and rblock.
621 * The C method works by generating a large switch statement that will run the appropriate
622 * checking code for each object based on its allocation site. The switch statement is
623 * surrounded by a while statement which dequeues objects to be checked from a queue. An
624 * object is added to a queue only if it contains a conflict (in itself or in its referencees)
625 * and we came across it while checking through it's referencer. Because of this property,
626 * conflicts will be signaled by the referencer; the only exception is the inset variable which can
627 * signal a conflict within itself.
630 private void printCMethod(Hashtable<Integer, ConcreteRuntimeObjNode> created, Taint taint) {
631 String inVar = taint.getVar().getSafeSymbol();
634 if(taint.isStallSiteTaint()) {
635 rBlock = taint.getStallSite().toString();
636 } else if(taint.isRBlockTaint()) {
637 rBlock = taint.getSESE().getPrettyIdentifier();
639 System.out.println("RCR CRITICAL ERROR: TAINT IS NEITHER A STALLSITE NOR SESE! " + taint.toString());
643 //This hash table keeps track of all the case statements generated.
644 Hashtable<AllocSite, StringBuilder> cases = new Hashtable<AllocSite, StringBuilder>();
647 for (ConcreteRuntimeObjNode node : created.values()) {
648 printDebug(generalDebug, "Considering " + node.allocSite + " for traversal");
649 if (!cases.containsKey(node.allocSite) && qualifiesForCaseStatement(node)) {
650 printDebug(generalDebug, "+\t" + node.allocSite + " qualified for case statement");
651 addChecker(taint, node, cases, null, "ptr", 0);
658 if (taint.isStallSiteTaint()) {
659 methodName= "void traverse___" + inVar + removeInvalidChars(rBlock) + "___(void * InVar, SESEstall *record)";
661 methodName= "void traverse___" + inVar + removeInvalidChars(rBlock) + "___(void * InVar, "+taint.getSESE().getSESErecordName() +" *record)";
662 FlatSESEEnterNode fsese=taint.getSESE();
663 TempDescriptor tmp=taint.getVar();
664 index=fsese.getInVarsForDynamicCoarseConflictResolution().indexOf(tmp);
667 cFile.println(methodName + " {");
668 headerFile.println(methodName + ";");
671 cFile.println("printf(\"The traverser ran for " + methodName + "\\n\");");
675 if(cases.size() == 0) {
676 cFile.println(" return;");
678 cFile.println(" int totalcount=RUNBIAS;");
679 if (taint.isStallSiteTaint()) {
680 cFile.println(" record->rcrRecords[0].count=RUNBIAS;");
682 cFile.println(" record->rcrRecords["+index+"].count=RUNBIAS;");
685 //clears queue and hashtable that keeps track of where we've been.
686 cFile.println(clearQueue + ";\n" + resetVisitedHashTable + ";");
687 //generic cast to ___Object___ to access ptr->allocsite field.
688 cFile.println("struct ___Object___ * ptr = (struct ___Object___ *) InVar;\nif (InVar != NULL) {\n " + queryVistedHashtable + "(ptr);\n do {");
689 if (taint.isRBlockTaint()) {
690 cFile.println(" if(unlikely(record->common.doneExecuting)) {");
691 cFile.println(" record->common.rcrstatus=0;");
692 cFile.println(" return;");
695 cFile.println(" switch(ptr->allocsite) {");
697 for(AllocSite singleCase: cases.keySet()) {
698 cFile.append(cases.get(singleCase));
701 cFile.println(" default:\n break; ");
702 cFile.println(" }\n } while((ptr = " + dequeueFromQueueInC + ") != NULL);\n}");
704 if (taint.isStallSiteTaint()) {
706 cFile.println(" if(atomic_sub_and_test(totalcount,&(record->rcrRecords[0].count))) {");
707 cFile.println(" psem_give_tag(record->common.parentsStallSem, record->tag);");
708 cFile.println(" BARRIER();");
710 cFile.println(" record->common.rcrstatus=0;");
712 cFile.println(" if(atomic_sub_and_test(totalcount,&(record->rcrRecords["+index+"].count))) {");
713 cFile.println(" int flag=LOCKXCHG32(&(record->rcrRecords["+index+"].flag),0);");
714 cFile.println(" if(flag) {");
715 //we have resolved a heap root...see if this was the last dependence
716 cFile.println(" if(atomic_sub_and_test(1, &(record->common.unresolvedDependencies))) workScheduleSubmit((void *)record);");
719 cFile.println(" record->common.rcrstatus=0;");
727 * addChecker creates a case statement for every object that is an inset variable, has more
728 * than 1 parent && has conflicts, or where resumes are possible (from waiting queue).
729 * See .qualifiesForCaseStatement
731 private void addChecker(Taint taint,
732 ConcreteRuntimeObjNode node,
733 Hashtable<AllocSite,StringBuilder> cases,
734 StringBuilder possibleContinuingCase,
737 StringBuilder currCase = possibleContinuingCase;
738 if(qualifiesForCaseStatement(node)) {
739 assert prefix.equals("ptr");
740 assert !cases.containsKey(node.allocSite);
741 currCase = new StringBuilder();
742 cases.put(node.allocSite, currCase);
743 currCase.append(" case " + node.getAllocationSite() + ": {\n");
745 //either currCase is continuing off a parent case or is its own.
746 assert currCase !=null;
748 insertEntriesIntoHashStructure(taint, node, prefix, depth, currCase);
750 //Handle conflicts further down.
751 if(node.decendantsConflict()) {
753 currCase.append("{\n");
756 if(node.isArray() && node.decendantsConflict()) {
757 String childPtr = "((struct ___Object___ **)(((char *) &(((struct ArrayObject *)"+ prefix+")->___length___))+sizeof(int)))[i]";
758 String currPtr = "arrayElement" + pdepth;
760 currCase.append("{\n int i;\n");
761 currCase.append(" struct ___Object___ * "+currPtr+";\n");
762 currCase.append(" for(i = 0; i<((struct ArrayObject *) " + prefix + " )->___length___; i++ ) {\n");
764 //There should be only one field, hence we only take the first field in the keyset.
765 assert node.objectRefs.keySet().size() <= 1;
766 ObjRefList refsAtParticularField = node.objectRefs.get(node.objectRefs.keySet().iterator().next());
767 printObjRefSwitchStatement(taint,cases,pdepth,currCase,refsAtParticularField,childPtr,currPtr);
768 currCase.append(" }}\n");
771 String currPtr = "myPtr" + pdepth;
772 currCase.append(" struct ___Object___ * "+currPtr+";\n");
773 for(String field: node.objectRefs.keySet()) {
774 ObjRefList refsAtParticularField = node.objectRefs.get(field);
776 if(refsAtParticularField.hasConflicts()) {
777 String childPtr = "((struct "+node.original.getType().getSafeSymbol()+" *)"+prefix +")->___" + field + "___";
778 printObjRefSwitchStatement(taint,cases, pdepth, currCase, refsAtParticularField, childPtr, currPtr);
783 currCase.append("}\n"); //For particular top level case statement.
785 if(qualifiesForCaseStatement(node)) {
786 currCase.append(" }\n break;\n");
790 private void insertEntriesIntoHashStructure(Taint taint, ConcreteRuntimeObjNode curr,
791 String prefix, int depth, StringBuilder currCase) {
792 boolean primConfRead=false;
793 boolean primConfWrite=false;
794 boolean objConfRead=false;
795 boolean objConfWrite=false;
797 //Direct Primitives Test
798 for(String field: curr.primitiveConflictingFields.keySet()) {
799 CombinedObjEffects effect=curr.primitiveConflictingFields.get(field);
800 primConfRead|=effect.hasReadConflict;
801 primConfWrite|=effect.hasWriteConflict;
804 //Direct Object Reference Test
805 for(String field: curr.objectRefs.keySet()) {
806 for(ObjRef ref: curr.objectRefs.get(field)) {
807 CombinedObjEffects effect=ref.myEffects;
808 objConfRead|=effect.hasReadConflict;
809 objConfWrite|=effect.hasWriteConflict;
814 if (taint.isRBlockTaint()) {
815 FlatSESEEnterNode fsese=taint.getSESE();
816 TempDescriptor tmp=taint.getVar();
817 index=fsese.getInVarsForDynamicCoarseConflictResolution().indexOf(tmp);
820 String strrcr=taint.isRBlockTaint()?"&record->rcrRecords["+index+"], ":"NULL, ";
821 String tasksrc=taint.isRBlockTaint()?"(SESEcommon *) record, ":"(SESEcommon *)(((INTPTR)record)|1LL), ";
823 //Do call if we need it.
824 if(primConfWrite||objConfWrite) {
825 int heaprootNum = connectedHRHash.get(taint).id;
826 assert heaprootNum != -1;
827 int allocSiteID = connectedHRHash.get(taint).getWaitingQueueBucketNum(curr);
828 int traverserID = doneTaints.get(taint);
829 currCase.append(" int tmpkey"+depth+"=rcr_generateKey("+prefix+");\n");
831 currCase.append(" int tmpvar"+depth+"=rcr_WTWRITEBINCASE(allHashStructures["+heaprootNum+"], tmpkey"+depth+", "+tasksrc+strrcr+index+");\n");
833 currCase.append(" int tmpvar"+depth+"=rcr_WRITEBINCASE(allHashStructures["+heaprootNum+"], tmpkey"+depth+", "+ tasksrc+strrcr+index+");\n");
834 } else if (primConfRead||objConfRead) {
835 int heaprootNum = connectedHRHash.get(taint).id;
836 assert heaprootNum != -1;
837 int allocSiteID = connectedHRHash.get(taint).getWaitingQueueBucketNum(curr);
838 int traverserID = doneTaints.get(taint);
839 currCase.append(" int tmpkey"+depth+"=rcr_generateKey("+prefix+");\n");
841 currCase.append(" int tmpvar"+depth+"=rcr_WTREADBINCASE(allHashStructures["+heaprootNum+"], tmpkey"+depth+", "+tasksrc+strrcr+index+");\n");
843 currCase.append(" int tmpvar"+depth+"=rcr_READBINCASE(allHashStructures["+heaprootNum+"], tmpkey"+depth+", "+tasksrc+strrcr+index+");\n");
846 if(primConfWrite||objConfWrite||primConfRead||objConfRead) {
847 currCase.append("if (!(tmpvar"+depth+"&READYMASK)) totalcount--;\n");
851 private void printObjRefSwitchStatement(Taint taint, Hashtable<AllocSite, StringBuilder> cases,
852 int pDepth, StringBuilder currCase, ObjRefList refsAtParticularField, String childPtr,
855 currCase.append(" "+currPtr+"= (struct ___Object___ * ) " + childPtr + ";\n");
856 currCase.append(" if (" + currPtr + " != NULL) { \n");
857 currCase.append(" switch(" + currPtr + getAllocSiteInC + ") {\n");
859 for(ObjRef ref: refsAtParticularField) {
860 if(ref.child.decendantsConflict() || ref.child.hasPrimitiveConflicts()) {
861 currCase.append(" case "+ref.allocSite+":\n {\n");
862 //The hash insert is here because we don't want to enqueue things unless we know it conflicts.
863 currCase.append(" if (" + queryVistedHashtable +"("+ currPtr + ")) {\n");
865 if(qualifiesForCaseStatement(ref.child)){
866 currCase.append(" " + addToQueueInC + childPtr + ");\n ");
868 addChecker(taint, ref.child, cases, currCase, currPtr, pDepth + 1);
871 currCase.append(" }\n"); //close for queryVistedHashtable
873 currCase.append("}\n"); //close for internal case statement
877 currCase.append(" default:\n" +
879 " }}\n"); //internal switch.
882 private boolean qualifiesForCaseStatement(ConcreteRuntimeObjNode node) {
885 (node.isInsetVar && (node.decendantsConflict() || node.hasPrimitiveConflicts()) || node.hasDirectObjConflict) ||
886 //non-inline-able code cases
887 (node.getNumOfReachableParents() != 1 && node.decendantsConflict()) ||
888 //Cases where resumes are possible
889 (node.hasPotentialToBeIncorrectDueToConflict) && node.decendantsObjConflict);
892 private Taint getProperTaintForFlatSESEEnterNode(FlatSESEEnterNode rblock, VariableNode var,
893 Hashtable<Taint, Set<Effect>> effects) {
894 Set<Taint> taints = effects.keySet();
895 for (Taint t : taints) {
896 FlatSESEEnterNode sese = t.getSESE();
897 if(sese != null && sese.equals(rblock) && t.getVar().equals(var.getTempDescriptor())) {
905 private Taint getProperTaintForEnterNode(FlatNode stallSite, VariableNode var,
906 Hashtable<Taint, Set<Effect>> effects) {
907 Set<Taint> taints = effects.keySet();
908 for (Taint t : taints) {
909 FlatNode flatnode = t.getStallSite();
910 if(flatnode != null && flatnode.equals(stallSite) && t.getVar().equals(var.getTempDescriptor())) {
917 private void printDebug(boolean guard, String debugStatements) {
919 System.out.println(debugStatements);
922 private void enumerateHeaproots() {
923 weaklyConnectedHRCounter = 0;
924 num2WeaklyConnectedHRGroup = new ArrayList<WeaklyConectedHRGroup>();
926 for(Taint t: connectedHRHash.keySet()) {
927 if(connectedHRHash.get(t).id == -1) {
928 WeaklyConectedHRGroup hg = connectedHRHash.get(t);
929 hg.id = weaklyConnectedHRCounter;
930 num2WeaklyConnectedHRGroup.add(weaklyConnectedHRCounter, hg);
931 weaklyConnectedHRCounter++;
934 if(t.isRBlockTaint()) {
935 int id=connectedHRHash.get(t).id;
936 Tuple tup=new Tuple(t.getVar(),t.getSESE());
937 if (weakMap.containsKey(tup)) {
938 if (weakMap.get(tup).intValue()!=id)
939 throw new Error("Var/SESE not unique for weak component.");
941 weakMap.put(tup, new Integer(id));
945 //output weakly connected groups for verification
947 System.out.println("==============Weakly Connected HeapRoots==============");
949 for(int i=0; i < num2WeaklyConnectedHRGroup.size(); i++){
950 System.out.println("Heap Group #" + i);
951 WeaklyConectedHRGroup hg = num2WeaklyConnectedHRGroup.get(i);
952 for(Taint t: hg.connectedHRs) {
953 System.out.println("\t" + t);
957 System.out.println("=======================END LIST=======================");
961 private void printoutTable(EffectsTable table) {
963 System.out.println("==============EFFECTS TABLE PRINTOUT==============");
964 for(AllocSite as: table.table.keySet()) {
965 System.out.println("\tFor AllocSite " + as.getUniqueAllocSiteID());
967 BucketOfEffects boe = table.table.get(as);
969 if(boe.potentiallyConflictingRoots != null && !boe.potentiallyConflictingRoots.isEmpty()) {
970 System.out.println("\t\tPotentially conflicting roots: ");
971 for(String key: boe.potentiallyConflictingRoots.keySet()) {
972 System.out.println("\t\t-Field: " + key);
973 System.out.println("\t\t\t" + boe.potentiallyConflictingRoots.get(key));
976 for(Taint t: boe.taint2EffectsGroup.keySet()) {
977 System.out.println("\t\t For Taint " + t);
978 EffectsGroup eg = boe.taint2EffectsGroup.get(t);
980 if(eg.hasPrimitiveConflicts()) {
981 System.out.print("\t\t\tPrimitive Conflicts at alloc " + as.getUniqueAllocSiteID() +" : ");
982 for(String field: eg.primitiveConflictingFields.keySet()) {
983 System.out.print(field + " ");
985 System.out.println();
987 for(String fieldKey: eg.myEffects.keySet()) {
988 CombinedObjEffects ce = eg.myEffects.get(fieldKey);
989 System.out.println("\n\t\t\tFor allocSite " + as.getUniqueAllocSiteID() + " && field " + fieldKey);
990 System.out.println("\t\t\t\tread " + ce.hasReadEffect + "/"+ce.hasReadConflict +
991 " write " + ce.hasWriteEffect + "/" + ce.hasWriteConflict +
992 " SU " + ce.hasStrongUpdateEffect + "/" + ce.hasStrongUpdateConflict);
993 for(Effect ef: ce.originalEffects) {
994 System.out.println("\t" + ef);
1003 private class EffectsGroup {
1004 Hashtable<String, CombinedObjEffects> myEffects;
1005 Hashtable<String, CombinedObjEffects> primitiveConflictingFields;
1007 public EffectsGroup() {
1008 myEffects = new Hashtable<String, CombinedObjEffects>();
1009 primitiveConflictingFields = new Hashtable<String, CombinedObjEffects>();
1012 public void addPrimitive(Effect e, boolean conflict) {
1013 CombinedObjEffects effects;
1014 if((effects = primitiveConflictingFields.get(e.getField().getSymbol())) == null) {
1015 effects = new CombinedObjEffects();
1016 primitiveConflictingFields.put(e.getField().getSymbol(), effects);
1018 effects.add(e, conflict);
1021 public void addObjEffect(Effect e, boolean conflict) {
1022 CombinedObjEffects effects;
1023 if((effects = myEffects.get(e.getField().getSymbol())) == null) {
1024 effects = new CombinedObjEffects();
1025 myEffects.put(e.getField().getSymbol(), effects);
1027 effects.add(e, conflict);
1030 public boolean isEmpty() {
1031 return myEffects.isEmpty() && primitiveConflictingFields.isEmpty();
1034 public boolean hasPrimitiveConflicts(){
1035 return !primitiveConflictingFields.isEmpty();
1038 public CombinedObjEffects getPrimEffect(String field) {
1039 return primitiveConflictingFields.get(field);
1042 public boolean hasObjectEffects() {
1043 return !myEffects.isEmpty();
1046 public CombinedObjEffects getObjEffect(String field) {
1047 return myEffects.get(field);
1051 //Is the combined effects for all effects with the same affectedAllocSite and field
1052 private class CombinedObjEffects {
1053 ArrayList<Effect> originalEffects;
1055 public boolean hasReadEffect;
1056 public boolean hasWriteEffect;
1057 public boolean hasStrongUpdateEffect;
1059 public boolean hasReadConflict;
1060 public boolean hasWriteConflict;
1061 public boolean hasStrongUpdateConflict;
1064 public CombinedObjEffects() {
1065 originalEffects = new ArrayList<Effect>();
1067 hasReadEffect = false;
1068 hasWriteEffect = false;
1069 hasStrongUpdateEffect = false;
1071 hasReadConflict = false;
1072 hasWriteConflict = false;
1073 hasStrongUpdateConflict = false;
1076 public boolean add(Effect e, boolean conflict) {
1077 if(!originalEffects.add(e))
1080 switch(e.getType()) {
1082 hasReadEffect = true;
1083 hasReadConflict = conflict;
1086 hasWriteEffect = true;
1087 hasWriteConflict = conflict;
1089 case Effect.strongupdate:
1090 hasStrongUpdateEffect = true;
1091 hasStrongUpdateConflict = conflict;
1094 System.out.println("RCR ERROR: An Effect Type never seen before has been encountered");
1101 public boolean hasConflict() {
1102 return hasReadConflict || hasWriteConflict || hasStrongUpdateConflict;
1105 public void mergeWith(CombinedObjEffects other) {
1106 for(Effect e: other.originalEffects) {
1107 if(!originalEffects.contains(e)){
1108 originalEffects.add(e);
1112 hasReadEffect |= other.hasReadEffect;
1113 hasWriteEffect |= other.hasWriteEffect;
1114 hasStrongUpdateEffect |= other.hasStrongUpdateEffect;
1116 hasReadConflict |= other.hasReadConflict;
1117 hasWriteConflict |= other.hasWriteConflict;
1118 hasStrongUpdateConflict |= other.hasStrongUpdateConflict;
1122 //This will keep track of a reference
1123 private class ObjRef {
1126 CombinedObjEffects myEffects;
1128 //This keeps track of the parent that we need to pass by inorder to get
1129 //to the conflicting child (if there is one).
1130 ConcreteRuntimeObjNode child;
1132 public ObjRef(String fieldname,
1133 ConcreteRuntimeObjNode ref,
1134 CombinedObjEffects myEffects) {
1136 allocSite = ref.getAllocationSite();
1139 this.myEffects = myEffects;
1142 public boolean hasConflictsDownThisPath() {
1143 return child.decendantsObjConflict || child.decendantsPrimConflict || child.hasPrimitiveConflicts() || myEffects.hasConflict();
1146 public boolean hasDirectObjConflict() {
1147 return myEffects.hasConflict();
1150 public boolean equals(Object other) {
1151 if(other == null || !(other instanceof ObjRef))
1154 ObjRef o = (ObjRef) other;
1156 if(o.field == this.field && o.allocSite == this.allocSite && this.child.equals(o.child))
1162 public int hashCode() {
1163 return child.allocSite.hashCode() ^ field.hashCode();
1166 public void mergeWith(ObjRef ref) {
1167 myEffects.mergeWith(ref.myEffects);
1171 private class ConcreteRuntimeObjNode {
1172 Hashtable<String, ObjRefList> objectRefs;
1173 Hashtable<String, CombinedObjEffects> primitiveConflictingFields;
1174 HashSet<ConcreteRuntimeObjNode> parentsWithReadToNode;
1175 HashSet<ConcreteRuntimeObjNode> parentsThatWillLeadToConflicts;
1176 //this set keeps track of references down the line that need to be enqueued if traverser is "paused"
1177 HashSet<ConcreteRuntimeObjNode> enqueueToWaitingQueueUponConflict;
1178 boolean decendantsPrimConflict;
1179 boolean decendantsObjConflict;
1180 boolean hasDirectObjConflict;
1181 boolean hasPotentialToBeIncorrectDueToConflict;
1183 AllocSite allocSite;
1184 HeapRegionNode original;
1186 public ConcreteRuntimeObjNode(HeapRegionNode me, boolean isInVar) {
1187 objectRefs = new Hashtable<String, ObjRefList>(5);
1188 primitiveConflictingFields = null;
1189 parentsThatWillLeadToConflicts = new HashSet<ConcreteRuntimeObjNode>();
1190 parentsWithReadToNode = new HashSet<ConcreteRuntimeObjNode>();
1191 enqueueToWaitingQueueUponConflict = new HashSet<ConcreteRuntimeObjNode>();
1192 allocSite = me.getAllocSite();
1194 isInsetVar = isInVar;
1195 decendantsPrimConflict = false;
1196 decendantsObjConflict = false;
1197 hasDirectObjConflict = false;
1198 hasPotentialToBeIncorrectDueToConflict = false;
1201 public void addReachableParent(ConcreteRuntimeObjNode curr) {
1202 parentsWithReadToNode.add(curr);
1206 public boolean equals(Object other) {
1207 if(other == null || !(other instanceof ConcreteRuntimeObjNode))
1210 return original.equals(((ConcreteRuntimeObjNode)other).original);
1213 public int getAllocationSite() {
1214 return allocSite.getUniqueAllocSiteID();
1217 public int getNumOfReachableParents() {
1218 return parentsThatWillLeadToConflicts.size();
1221 public boolean hasPrimitiveConflicts() {
1222 return primitiveConflictingFields != null && !primitiveConflictingFields.isEmpty();
1225 public boolean decendantsConflict() {
1226 return decendantsPrimConflict || decendantsObjConflict;
1229 //returns true if at least one of the objects in points of access has been added
1230 public boolean addPossibleWaitingQueueEnqueue(HashSet<ConcreteRuntimeObjNode> pointsOfAccess) {
1231 boolean addedNew = false;
1232 for(ConcreteRuntimeObjNode dec: pointsOfAccess) {
1233 if(dec != null && dec != this){
1234 addedNew = addedNew || enqueueToWaitingQueueUponConflict.add(dec);
1241 public boolean addPossibleWaitingQueueEnqueue(ConcreteRuntimeObjNode pointOfAccess) {
1242 if(pointOfAccess != null && pointOfAccess != this){
1243 return enqueueToWaitingQueueUponConflict.add(pointOfAccess);
1249 public void addObjChild(String field, ConcreteRuntimeObjNode child, CombinedObjEffects ce) {
1250 printDebug(traceDataStructureBuild,this.allocSite.getUniqueAllocSiteID() + " added child at " + child.getAllocationSite());
1251 hasDirectObjConflict |= ce.hasConflict();
1252 ObjRef ref = new ObjRef(field, child, ce);
1254 if(objectRefs.containsKey(field)){
1255 ObjRefList array = objectRefs.get(field);
1257 if(array.contains(ref)) {
1258 ObjRef other = array.get(array.indexOf(ref));
1259 other.mergeWith(ref);
1260 printDebug(traceDataStructureBuild," Merged with old");
1261 printDebug(traceDataStructureBuild," Old="+ other.child.original + "\n new="+ref.child.original);
1265 printDebug(traceDataStructureBuild," Just added new;\n Field: " + field);
1266 printDebug(traceDataStructureBuild," AllocSite: " + child.getAllocationSite());
1267 printDebug(traceDataStructureBuild," Child: "+child.original);
1271 ObjRefList array = new ObjRefList(3);
1274 objectRefs.put(field, array);
1278 public boolean isArray() {
1279 return original.getType().isArray();
1282 public ArrayList<Integer> getReferencedAllocSites() {
1283 ArrayList<Integer> list = new ArrayList<Integer>();
1285 for(String key: objectRefs.keySet()) {
1286 for(ObjRef r: objectRefs.get(key)) {
1287 if(r.hasDirectObjConflict() || (r.child.parentsWithReadToNode.contains(this) && r.hasConflictsDownThisPath())) {
1288 list.add(r.allocSite);
1296 public String toString() {
1297 return "AllocSite=" + getAllocationSite() + " myConflict=" + !parentsThatWillLeadToConflicts.isEmpty() +
1298 " decCon="+decendantsObjConflict+
1299 " NumOfConParents=" + getNumOfReachableParents() + " ObjectChildren=" + objectRefs.size();
1303 //Simple extension of the ArrayList to allow it to find if any ObjRefs conflict.
1304 private class ObjRefList extends ArrayList<ObjRef> {
1305 private static final long serialVersionUID = 326523675530835596L;
1307 public ObjRefList(int size) {
1311 public boolean add(ObjRef o){
1312 return super.add(o);
1315 public boolean hasConflicts() {
1316 for(ObjRef r: this) {
1317 if(r.hasConflictsDownThisPath() || r.child.hasPrimitiveConflicts())
1325 private class EffectsTable {
1326 private Hashtable<AllocSite, BucketOfEffects> table;
1328 public EffectsTable(Hashtable<Taint, Set<Effect>> effects,
1329 Hashtable<Taint, Set<Effect>> conflicts) {
1330 table = new Hashtable<AllocSite, BucketOfEffects>();
1332 // rehash all effects (as a 5-tuple) by their affected allocation site
1333 for (Taint t : effects.keySet()) {
1334 Set<Effect> localConflicts = conflicts.get(t);
1335 for (Effect e : effects.get(t)) {
1336 BucketOfEffects bucket;
1337 if ((bucket = table.get(e.getAffectedAllocSite())) == null) {
1338 bucket = new BucketOfEffects();
1339 table.put(e.getAffectedAllocSite(), bucket);
1341 printDebug(printEffectsAndEffectsTable, "Added Taint" + t + " Effect " + e + "Conflict Status = " + (localConflicts!=null?localConflicts.contains(e):false)+" localConflicts = "+localConflicts);
1342 bucket.add(t, e, localConflicts!=null?localConflicts.contains(e):false);
1347 public EffectsGroup getEffects(AllocSite parentKey, Taint taint) {
1348 //This would get the proper bucket of effects and then get all the effects
1349 //for a parent for a specific taint
1351 return table.get(parentKey).taint2EffectsGroup.get(taint);
1353 catch (NullPointerException e) {
1358 // Run Analysis will walk the data structure and figure out the weakly
1359 // connected heap roots.
1360 public void runAnalysis() {
1361 if(printEffectsAndEffectsTable) {
1362 printoutTable(this);
1365 for(AllocSite key: table.keySet()) {
1366 BucketOfEffects effects = table.get(key);
1367 //make sure there are actually conflicts in the bucket
1368 if(effects.potentiallyConflictingRoots != null && !effects.potentiallyConflictingRoots.isEmpty()){
1369 for(String field: effects.potentiallyConflictingRoots.keySet()){
1370 ArrayList<Taint> taints = effects.potentiallyConflictingRoots.get(field);
1371 //For simplicity, we just create a new group and add everything to it instead of
1372 //searching through all of them for the largest group and adding everyone in.
1373 WeaklyConectedHRGroup group = new WeaklyConectedHRGroup();
1374 group.add(taints); //This will automatically add the taint to the connectedHRhash
1381 private class WeaklyConectedHRGroup {
1382 HashSet<Taint> connectedHRs;
1383 //This is to keep track of unique waitingQueue positions for each allocsite.
1384 Hashtable<AllocSite, Integer> allocSiteToWaitingQueueMap;
1385 int waitingQueueCounter;
1388 public WeaklyConectedHRGroup() {
1389 connectedHRs = new HashSet<Taint>();
1390 id = -1; //this will be later modified
1391 waitingQueueCounter = 0;
1392 allocSiteToWaitingQueueMap = new Hashtable<AllocSite, Integer>();
1395 public void add(ArrayList<Taint> list) {
1396 for(Taint t: list) {
1401 public int getWaitingQueueBucketNum(ConcreteRuntimeObjNode node) {
1402 if(allocSiteToWaitingQueueMap.containsKey(node.allocSite)) {
1403 return allocSiteToWaitingQueueMap.get(node.allocSite);
1405 allocSiteToWaitingQueueMap.put(node.allocSite, waitingQueueCounter);
1406 return waitingQueueCounter++;
1410 public void add(Taint t) {
1411 connectedHRs.add(t);
1412 WeaklyConectedHRGroup oldGroup = connectedHRHash.get(t);
1413 connectedHRHash.put(t, this); //put new group into hash
1414 //If the taint was already in another group, move all its buddies over.
1415 if(oldGroup != this && oldGroup != null) {
1416 Iterator<Taint> it = oldGroup.connectedHRs.iterator();
1419 while(it.hasNext() && (relatedTaint = it.next()) != null) {
1420 if(!connectedHRs.contains(relatedTaint)){
1421 this.add(relatedTaint);
1428 //This is a class that stores all the effects for an affected allocation site
1429 //across ALL taints. The structure is a hashtable of EffectGroups (see above) hashed
1430 //by a Taint. This way, I can keep EffectsGroups so I can reuse most to all of my old code
1431 //and allows for easier tracking of effects. In addition, a hashtable (keyed by the string
1432 //of the field access) keeps track of an ArrayList of taints of SESEblocks that conflict on that
1434 private class BucketOfEffects {
1435 // This table is used for lookup while creating the traversal.
1436 Hashtable<Taint, EffectsGroup> taint2EffectsGroup;
1438 //This table is used to help identify weakly connected groups: Contains ONLY
1439 //conflicting effects AND is only initialized when needed
1440 //String stores the field
1441 Hashtable<String, ArrayList<Taint>> potentiallyConflictingRoots;
1443 public BucketOfEffects() {
1444 taint2EffectsGroup = new Hashtable<Taint, EffectsGroup>();
1447 public void add(Taint t, Effect e, boolean conflict) {
1448 EffectsGroup effectsForGivenTaint;
1450 if ((effectsForGivenTaint = taint2EffectsGroup.get(t)) == null) {
1451 effectsForGivenTaint = new EffectsGroup();
1452 taint2EffectsGroup.put(t, effectsForGivenTaint);
1455 if (isReallyAPrimitive(e.getField().getType())) {
1457 effectsForGivenTaint.addPrimitive(e, true);
1460 effectsForGivenTaint.addObjEffect(e, conflict);
1464 if(potentiallyConflictingRoots == null) {
1465 potentiallyConflictingRoots = new Hashtable<String, ArrayList<Taint>>();
1468 ArrayList<Taint> taintsForField = potentiallyConflictingRoots.get(e.getField().getSafeSymbol());
1469 if(taintsForField == null) {
1470 taintsForField = new ArrayList<Taint>();
1471 potentiallyConflictingRoots.put(e.getField().getSafeSymbol(), taintsForField);
1474 if(!taintsForField.contains(t)) {
1475 taintsForField.add(t);
1481 private class TaintAndInternalHeapStructure {
1483 public Hashtable<Integer, ConcreteRuntimeObjNode> nodesInHeap;
1485 public TaintAndInternalHeapStructure(Taint taint, Hashtable<Integer, ConcreteRuntimeObjNode> nodesInHeap) {
1487 this.nodesInHeap = nodesInHeap;
1491 private class TraversalInfo {
1493 public ReachGraph rg;
1494 public TempDescriptor invar;
1496 public TraversalInfo(FlatNode fn, ReachGraph g) {
1502 public TraversalInfo(FlatNode fn, ReachGraph rg2, TempDescriptor tempDesc) {