changes
[IRC.git] / Robust / src / IR / Flat / RuntimeConflictResolver.java
1 package IR.Flat;
2 import java.io.File;
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;
10 import java.util.Set;
11 import java.util.Vector;
12 import Analysis.Disjoint.*;
13 import Analysis.MLP.CodePlan;
14 import IR.Flat.*;
15 import IR.TypeDescriptor;
16 import Analysis.OoOJava.OoOJavaAnalysis;
17
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.
20  * 
21  * How to Use:
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
29  */
30 public class RuntimeConflictResolver {
31   public static final boolean javaDebug = true;
32   public static final boolean cSideDebug = false;
33   
34   private PrintWriter cFile;
35   private PrintWriter headerFile;
36   private static final String hashAndQueueCFileDir = "oooJava/";
37   //This keeps track of taints we've traversed to prevent printing duplicate traverse functions
38   //The Integer keeps track of the weakly connected group it's in (used in enumerateHeapRoots)
39   private Hashtable<Taint, Integer> doneTaints;
40   private Hashtable<Taint, Set<Effect>> globalEffects;
41   private Hashtable<Taint, Set<Effect>> globalConflicts;
42   private ArrayList<TraversalInfo> toTraverse;
43
44   // initializing variables can be found in printHeader()
45   private static final String getAllocSiteInC = "->allocsite";
46   private static final String queryVistedHashtable = "hashRCRInsert";
47   private static final String addToQueueInC = "enqueueRCRQueue(";
48   private static final String dequeueFromQueueInC = "dequeueRCRQueue()";
49   private static final String clearQueue = "resetRCRQueue()";
50   // Make hashtable; hashRCRCreate(unsigned int size, double loadfactor)
51   private static final String mallocVisitedHashtable = "hashRCRCreate(128, 0.75)";
52   private static final String deallocVisitedHashTable = "hashRCRDelete()";
53   private static final String resetVisitedHashTable = "hashRCRreset()";
54   
55   //TODO find correct strings for these
56   private static final String addCheckFromHashStructure = "checkFromHashStructure(";
57   private static final String putWaitingQueueBlock = "putWaitingQueueBlock(";  //lifting of blocks will be done by hashtable.
58   private static final String putIntoAllocQueue = "putIntoWaitingQ(";
59   private static final int noConflict = 0;
60   private static final int conflictButTraverserCanContinue = 1;
61   private static final int conflictButTraverserCannotContinue = 2;
62   private static final int allocQueueIsNotEmpty = 0;
63   
64   // Hashtable provides fast access to heaproot # lookups
65   private Hashtable<Taint, WeaklyConectedHRGroup> connectedHRHash;
66   private ArrayList<WeaklyConectedHRGroup> num2WeaklyConnectedHRGroup;
67   private int traverserIDCounter;
68   private int weaklyConnectedHRCounter;
69   private ArrayList<TaintAndInternalHeapStructure> pendingPrintout;
70   private EffectsTable effectsLookupTable;
71   private OoOJavaAnalysis oooa;
72
73   public RuntimeConflictResolver(String buildir, OoOJavaAnalysis oooa) throws FileNotFoundException {
74     String outputFile = buildir + "RuntimeConflictResolver";
75     this.oooa=oooa;
76
77     cFile = new PrintWriter(new File(outputFile + ".c"));
78     headerFile = new PrintWriter(new File(outputFile + ".h"));
79     
80     cFile.println("#include \"" + hashAndQueueCFileDir + "hashRCR.h\"\n#include \""
81         + hashAndQueueCFileDir + "Queue_RCR.h\"\n#include <stdlib.h>");
82     cFile.println("#include \"classdefs.h\"");
83     cFile.println("#include \"structdefs.h\"");
84     cFile.println("#include \"mlp_runtime.h\"");
85     cFile.println("#include \"RuntimeConflictResolver.h\"");
86     cFile.println("#include \"hashStructure.h\"");
87     
88     headerFile.println("#ifndef __3_RCR_H_");
89     headerFile.println("#define __3_RCR_H_");
90     
91     doneTaints = new Hashtable<Taint, Integer>();
92     connectedHRHash = new Hashtable<Taint, WeaklyConectedHRGroup>();
93     
94     traverserIDCounter = 1;
95     weaklyConnectedHRCounter = 0;
96     pendingPrintout = new ArrayList<TaintAndInternalHeapStructure>();
97     toTraverse = new ArrayList<TraversalInfo>();
98     globalConflicts = new Hashtable<Taint, Set<Effect>>(); 
99     //Note: globalEffects is not instantiated since it'll be passed in whole while conflicts comes in chunks
100   }
101
102   public void setGlobalEffects(Hashtable<Taint, Set<Effect>> effects) {
103     globalEffects = effects;
104     
105     if(javaDebug) {
106       System.out.println("============EFFECTS LIST AS PASSED IN============");
107       for(Taint t: globalEffects.keySet()) {
108         System.out.println("For Taint " + t);
109         for(Effect e: globalEffects.get(t)) {
110           System.out.println("\t" + e);
111         }
112       }
113       System.out.println("====================END  LIST====================");
114     }
115   }
116
117   public void init() {
118     //Go through the SESE's
119     for(Iterator<FlatSESEEnterNode> seseit=oooa.getAllSESEs().iterator();seseit.hasNext();) {
120       FlatSESEEnterNode fsen=seseit.next();
121       Analysis.OoOJava.ConflictGraph conflictGraph;
122       Hashtable<Taint, Set<Effect>> conflicts;
123       System.out.println("-------");
124       System.out.println(fsen);
125       System.out.println(fsen.getIsCallerSESEplaceholder());
126       System.out.println(fsen.getParent());
127       
128       if (fsen.getParent()!=null) {
129         conflictGraph = oooa.getConflictGraph(fsen.getParent());
130         System.out.println("CG="+conflictGraph);
131         if (conflictGraph!=null)
132           System.out.println("Conflicts="+conflictGraph.getConflictEffectSet(fsen));
133       }
134       
135       if(!fsen.getIsCallerSESEplaceholder() && fsen.getParent()!=null && 
136          (conflictGraph = oooa.getConflictGraph(fsen.getParent())) != null && 
137          (conflicts = conflictGraph.getConflictEffectSet(fsen)) != null) {
138         FlatMethod fm=fsen.getfmEnclosing();
139         ReachGraph rg=oooa.getDisjointAnalysis().getReachGraph(fm.getMethod());
140         if(cSideDebug)
141           rg.writeGraph("RCR_RG_SESE_DEBUG");
142         
143         addToTraverseToDoList(fsen, rg, conflicts);
144       }
145     }
146     //Go through the stall sites
147     for(Iterator<FlatNode> codeit=oooa.getNodesWithPlans().iterator();codeit.hasNext();) {
148       FlatNode fn=codeit.next();
149       CodePlan cp=oooa.getCodePlan(fn);
150       FlatSESEEnterNode currentSESE=cp.getCurrentSESE();
151       Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
152
153       if(graph!=null){
154         Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
155         Set<Analysis.OoOJava.WaitingElement> waitingElementSet =
156           graph.getStallSiteWaitingElementSet(fn, seseLockSet);
157         
158         if(waitingElementSet.size()>0){
159           for (Iterator iterator = waitingElementSet.iterator(); iterator.hasNext();) {
160             Analysis.OoOJava.WaitingElement waitingElement = (Analysis.OoOJava.WaitingElement) iterator.next();
161             
162             Analysis.OoOJava.ConflictGraph conflictGraph = graph;
163             Hashtable<Taint, Set<Effect>> conflicts;
164             ReachGraph rg = oooa.getDisjointAnalysis().getReachGraph(currentSESE.getmdEnclosing());
165             if(cSideDebug) {
166               rg.writeGraph("RCR_RG_STALLSITE_DEBUG");
167             }
168             if((conflictGraph != null) && 
169                (conflicts = graph.getConflictEffectSet(fn)) != null &&
170                (rg != null)){
171               addToTraverseToDoList(fn, waitingElement.getTempDesc(), rg, conflicts);
172             }
173           }
174         }
175       }
176     }
177
178     buildEffectsLookupStructure();
179     runAllTraversals();
180   }
181   
182   /*
183    * Basic Strategy:
184    * 1) Get global effects and conflicts 
185    * 2) Create a hash structure (EffectsTable) to manage effects (hashed by affected Allocsite, then taint, then field)
186    *     2a) Use Effects to verify we can access something (reads)
187    *     2b) Use conflicts to mark conflicts (read/write/strongupdate)
188    *     2c) At second level of hash, store Heaproots that can cause conflicts at the field
189    * 3) Walk hash structure to identify and enumerate weakly connected groups and generate waiting queue slots. 
190    * 4) Build internal representation of the rgs (pruned)
191    * 5) Print c methods by walking internal representation
192    */
193   
194   public void addToTraverseToDoList(FlatSESEEnterNode rblock, ReachGraph rg, Hashtable<Taint, Set<Effect>> conflicts) {
195     //Add to todo list
196     toTraverse.add(new TraversalInfo(rblock, rg));
197
198     //Add to Global conflicts
199     for(Taint t: conflicts.keySet()) {
200       if(globalConflicts.containsKey(t)) {
201         globalConflicts.get(t).addAll(conflicts.get(t));
202       } else {
203         globalConflicts.put(t, conflicts.get(t));
204       }
205     }
206   }
207   
208
209   public void addToTraverseToDoList(FlatNode fn, TempDescriptor tempDesc, 
210       ReachGraph rg, Hashtable<Taint, Set<Effect>> conflicts) {
211     toTraverse.add(new TraversalInfo(fn, rg, tempDesc));
212     
213     for(Taint t: conflicts.keySet()) {
214       if(globalConflicts.containsKey(t)) {
215         globalConflicts.get(t).addAll(conflicts.get(t));
216       } else {
217         globalConflicts.put(t, conflicts.get(t));
218       }
219     }
220   }
221
222   private void traverseSESEBlock(FlatSESEEnterNode rblock, ReachGraph rg) {
223     Collection<TempDescriptor> inVars = rblock.getInVarSet();
224     
225     if (inVars.size() == 0)
226       return;
227     
228     // For every non-primitive variable, generate unique method
229     // Special Note: The Criteria for executing printCMethod in this loop should match
230     // exactly the criteria in buildcode.java to invoke the generated C method(s). 
231     for (TempDescriptor invar : inVars) {
232       TypeDescriptor type = invar.getType();
233       if(type == null || type.isPrimitive()) {
234         continue;
235       }
236
237       //created stores nodes with specific alloc sites that have been traversed while building
238       //internal data structure. It is later traversed sequentially to find inset variables and
239       //build output code.
240       Hashtable<AllocSite, ConcreteRuntimeObjNode> created = new Hashtable<AllocSite, ConcreteRuntimeObjNode>();
241       VariableNode varNode = rg.getVariableNodeNoMutation(invar);
242       Taint taint = getProperTaintForFlatSESEEnterNode(rblock, varNode, globalEffects);
243       if (taint == null) {
244         printDebug(javaDebug, "Null FOR " +varNode.getTempDescriptor().getSafeSymbol() + rblock.toPrettyString());
245         return;
246       }
247       
248       //This is to prevent duplicate traversals from being generated 
249       if(doneTaints.containsKey(taint))
250         return;
251       
252       doneTaints.put(taint, traverserIDCounter++);
253       createConcreteGraph(effectsLookupTable, created, varNode, taint);
254       
255       
256       //This will add the taint to the printout, there will be NO duplicates (checked above)
257       if(!created.isEmpty()) {
258         rblock.addInVarForDynamicCoarseConflictResolution(invar);
259         pendingPrintout.add(new TaintAndInternalHeapStructure(taint, created));
260       }
261     }
262   }
263   
264   private void traverseStallSite(FlatNode enterNode, TempDescriptor invar, ReachGraph rg) {
265     TypeDescriptor type = invar.getType();
266     if(type == null || type.isPrimitive()) {
267       return;
268     }
269     Hashtable<AllocSite, ConcreteRuntimeObjNode> created = new Hashtable<AllocSite, ConcreteRuntimeObjNode>();
270     VariableNode varNode = rg.getVariableNodeNoMutation(invar);
271     Taint taint = getProperTaintForEnterNode(enterNode, varNode, globalEffects);
272     
273     if (taint == null) {
274       printDebug(javaDebug, "Null FOR " +varNode.getTempDescriptor().getSafeSymbol() + enterNode.toString());
275       return;
276     }        
277     
278     if(doneTaints.containsKey(taint))
279       return;
280     
281     doneTaints.put(taint, traverserIDCounter++);
282     createConcreteGraph(effectsLookupTable, created, varNode, taint);
283     
284     if (!created.isEmpty()) {
285       pendingPrintout.add(new TaintAndInternalHeapStructure(taint, created));
286     }
287   }
288   
289   public String getTraverserInvocation(TempDescriptor invar, String varString, FlatNode fn) {
290     String flatname;
291     if(fn instanceof FlatSESEEnterNode) {
292       flatname = ((FlatSESEEnterNode) fn).getPrettyIdentifier();
293     } else {
294       flatname = fn.toString();
295     }
296     
297     return "traverse___" + removeInvalidChars(invar.getSafeSymbol()) + 
298     removeInvalidChars(flatname) + "___("+varString+");";
299   }
300   
301   public String removeInvalidChars(String in) {
302     StringBuilder s = new StringBuilder(in);
303     for(int i = 0; i < s.length(); i++) {
304       if(s.charAt(i) == ' ' || s.charAt(i) == '.' || s.charAt(i) == '=') {
305         s.deleteCharAt(i);
306         i--;
307       }
308     }
309     return s.toString();
310   }
311
312   public void close() {
313     //prints out all generated code
314     for(TaintAndInternalHeapStructure ths: pendingPrintout) {
315       printCMethod(ths.nodesInHeap, ths.t);
316     }
317     
318     //Prints out the master traverser Invocation that'll call all other traverser
319     //based on traverserID
320     printMasterTraverserInvocation();
321     printResumeTraverserInvocation();
322     
323     //TODO this is only temporary, remove when thread local vars implemented. 
324     createMasterHashTableArray();
325     
326     // Adds Extra supporting methods
327     cFile.println("void initializeStructsRCR() {\n  " + mallocVisitedHashtable + ";\n  " + clearQueue + ";\n}");
328     cFile.println("void destroyRCR() {\n  " + deallocVisitedHashTable + ";\n}");
329     
330     headerFile.println("void initializeStructsRCR();\nvoid destroyRCR();");
331     headerFile.println("#endif\n");
332
333     cFile.close();
334     headerFile.close();
335   }
336
337   //Builds Effects Table and runs the analysis on them to get weakly connected HRs
338   //SPECIAL NOTE: Only runs after we've taken all the conflicts 
339   private void buildEffectsLookupStructure(){
340     effectsLookupTable = new EffectsTable(globalEffects, globalConflicts);
341     effectsLookupTable.runAnaylsis();
342     enumerateHeaproots();
343   }
344
345   private void runAllTraversals() {
346     for(TraversalInfo t: toTraverse) {
347       printDebug(javaDebug, "Running Traversal a traversal on " + t.f);
348       
349       if(t.f instanceof FlatSESEEnterNode) {
350         traverseSESEBlock((FlatSESEEnterNode)t.f, t.rg);
351       } else {
352         if(t.invar == null) {
353           System.out.println("RCR ERROR: Attempted to run a stall site traversal with NO INVAR");
354         } else {
355           traverseStallSite(t.f, t.invar, t.rg);
356         }
357       }
358         
359     }
360   }
361
362   //TODO: This is only temporary, remove when thread local variables are functional. 
363   private void createMasterHashTableArray() {
364     headerFile.println("void createAndFillMasterHashStructureArray();");
365     cFile.println("void createAndFillMasterHashStructureArray() {\n" +
366                 "  rcr_createMasterHashTableArray("+weaklyConnectedHRCounter + ");");
367     
368     for(int i = 0; i < weaklyConnectedHRCounter; i++) {
369       cFile.println("  allHashStructures["+i+"] = (HashStructure *) rcr_createHashtable("+num2WeaklyConnectedHRGroup.get(i).connectedHRs.size()+");");
370     }
371     cFile.println("}");
372   }
373
374   private void printMasterTraverserInvocation() {
375     headerFile.println("\nint tasktraverse(SESEcommon * record);");
376     cFile.println("\nint tasktraverse(SESEcommon * record) {");
377     cFile.println("  switch(record->classID) {");
378     
379     for(Iterator<FlatSESEEnterNode> seseit=oooa.getAllSESEs().iterator();seseit.hasNext();) {
380       FlatSESEEnterNode fsen=seseit.next();
381       cFile.println(    "    /* "+fsen.getPrettyIdentifier()+" */");
382       cFile.println(    "    case "+fsen.getIdentifier()+": {");
383       cFile.println(    "      "+fsen.getSESErecordName()+" * rec=("+fsen.getSESErecordName()+" *) record;");
384       Vector<TempDescriptor> invars=fsen.getInVarsForDynamicCoarseConflictResolution();
385       for(int i=0;i<invars.size();i++) {
386         TempDescriptor tmp=invars.get(i);
387         cFile.println("      " + this.getTraverserInvocation(tmp, "rec->"+tmp+", rec", fsen));
388       }
389       cFile.println(    "    }");
390       cFile.println(    "    break;");
391     }
392     
393     cFile.println("    default:\n    printf(\"Invalid SESE ID was passed in.\\n\");\n    break;");
394     
395     cFile.println("  }");
396     cFile.println("}");
397   }
398
399
400   //This will print the traverser invocation that takes in a traverserID and 
401   //starting ptr
402   private void printResumeTraverserInvocation() {
403     headerFile.println("\nint traverse(void * startingPtr, SESEcommon * record, int traverserID);");
404     cFile.println("\nint traverse(void * startingPtr, SESEcommon *record, int traverserID) {");
405     cFile.println(" switch(traverserID) {");
406     
407     for(Taint t: doneTaints.keySet()) {
408       cFile.println("  case " + doneTaints.get(t)+ ":");
409       if(t.isRBlockTaint()) {
410         cFile.println("    " + this.getTraverserInvocation(t.getVar(), "startingPtr, ("+t.getSESE().getSESErecordName()+" *)record", t.getSESE()));
411       } else if (t.isStallSiteTaint()){
412         cFile.println("    " + this.getTraverserInvocation(t.getVar(), "startingPtr, record", t.getStallSite()));
413       } else {
414         System.out.println("RuntimeConflictResolver encountered a taint that is neither SESE nor stallsite: " + t);
415       }
416     }
417     
418     if(RuntimeConflictResolver.cSideDebug) {
419       cFile.println("  default:\n    printf(\"Invalid traverser ID %u was passed in.\\n\", traverserID);\n    break;");
420     } else {
421       cFile.println("  default:\n    break;");
422     }
423     
424     cFile.println(" }");
425     cFile.println("}");
426   }
427
428   private void createConcreteGraph(
429       EffectsTable table,
430       Hashtable<AllocSite, ConcreteRuntimeObjNode> created, 
431       VariableNode varNode, 
432       Taint t) {
433     
434     // if table is null that means there's no conflicts, therefore we need not
435     // create a traversal
436     if (table == null)
437       return;
438
439     Iterator<RefEdge> possibleEdges = varNode.iteratorToReferencees();
440     while (possibleEdges.hasNext()) {
441       RefEdge edge = possibleEdges.next();
442       assert edge != null;
443
444       ConcreteRuntimeObjNode singleRoot = new ConcreteRuntimeObjNode(edge.getDst(), true, false);
445       AllocSite rootKey = singleRoot.allocSite;
446
447       if (!created.containsKey(rootKey)) {
448         created.put(rootKey, singleRoot);
449         createHelper(singleRoot, edge.getDst().iteratorToReferencees(), created, table, t);
450       }
451     }
452   }
453   
454   //This code is the old way of generating an effects lookup table. 
455   //The new way is to instantiate an EffectsGroup
456   @Deprecated
457   private Hashtable<AllocSite, EffectsGroup> generateEffectsLookupTable(
458       Taint taint, Hashtable<Taint, 
459       Set<Effect>> effects,
460       Hashtable<Taint, Set<Effect>> conflicts) {
461     if(taint == null)
462       return null;
463     
464     Set<Effect> localEffects = effects.get(taint);
465     Set<Effect> localConflicts = conflicts.get(taint);
466     
467     //Debug Code for manually checking effects
468     if(javaDebug) {
469       printEffectsAndConflictsSets(taint, localEffects, localConflicts);
470     }
471     
472     if (localEffects == null || localEffects.isEmpty() || localConflicts == null || localConflicts.isEmpty())
473       return null;
474     
475     Hashtable<AllocSite, EffectsGroup> lookupTable = new Hashtable<AllocSite, EffectsGroup>();
476     
477     for (Effect e : localEffects) {
478       boolean conflict = localConflicts.contains(e);
479       AllocSite key = e.getAffectedAllocSite();
480       EffectsGroup myEffects = lookupTable.get(key);
481       
482       if(myEffects == null) {
483         myEffects = new EffectsGroup();
484         lookupTable.put(key, myEffects);
485       }
486       
487       if(e.getField().getType().isPrimitive()) {
488         if(conflict) {
489           myEffects.addPrimitive(e, true);
490         }
491       }
492       else {
493         myEffects.addObjEffect(e, conflict);
494       }      
495     }
496     
497     return lookupTable;
498   }
499
500   // Plan is to add stuff to the tree depth-first sort of way. That way, we can
501   // propagate up conflicts
502   private void createHelper(ConcreteRuntimeObjNode curr, 
503                             Iterator<RefEdge> edges, 
504                             Hashtable<AllocSite, ConcreteRuntimeObjNode> created,
505                             EffectsTable table, 
506                             Taint taint) {
507     assert table != null;
508     AllocSite parentKey = curr.allocSite;
509     EffectsGroup currEffects = table.getEffects(parentKey, taint); 
510     
511     if (currEffects == null || currEffects.isEmpty()) 
512       return;
513     
514     //Handle Objects (and primitives if child is new)
515     if(currEffects.hasObjectEffects()) {
516       while(edges.hasNext()) {
517         RefEdge edge = edges.next();
518         String field = edge.getField();
519         CombinedObjEffects effectsForGivenField = currEffects.getObjEffect(field);
520         //If there are no effects, then there's no point in traversing this edge
521         if(effectsForGivenField != null) {
522           HeapRegionNode childHRN = edge.getDst();
523           AllocSite childKey = childHRN.getAllocSite();
524           boolean isNewChild = !created.containsKey(childKey);
525           ConcreteRuntimeObjNode child; 
526           
527           if(isNewChild) {
528             child = new ConcreteRuntimeObjNode(childHRN, false, curr.isObjectArray());
529             created.put(childKey, child);
530           } else {
531             child = created.get(childKey);
532           }
533     
534           curr.addObjChild(field, child, effectsForGivenField);
535           
536           if (effectsForGivenField.hasConflict()) {
537             child.hasPotentialToBeIncorrectDueToConflict = true;
538             propogateObjConflict(curr, child);
539           }
540           
541           if(effectsForGivenField.hasReadEffect) {
542             child.addReachableParent(curr);
543             
544             //If isNewChild, flag propagation will be handled at recursive call
545             if(isNewChild) {
546               createHelper(child, childHRN.iteratorToReferencees(), created, table, taint);
547             } else {
548             //This makes sure that all conflicts below the child is propagated up the referencers.
549               if(child.decendantsPrimConflict || child.hasPrimitiveConflicts()) {
550                 propogatePrimConflict(child, child.enqueueToWaitingQueueUponConflict);
551               }
552               
553               if(child.decendantsObjConflict) {
554                 propogateObjConflict(child, child.enqueueToWaitingQueueUponConflict);
555               }
556             }
557           }
558         }
559       }
560     }
561     
562     //Handles primitives
563     curr.primitiveConflictingFields = currEffects.primitiveConflictingFields; 
564     if(currEffects.hasPrimitiveConflicts()) {
565       //Reminder: primitive conflicts are abstracted to object. 
566       propogatePrimConflict(curr, curr);
567     }
568   }
569
570   // This will propagate the conflict up the data structure.
571   private void propogateObjConflict(ConcreteRuntimeObjNode curr, HashSet<ConcreteRuntimeObjNode> pointsOfAccess) {
572     for(ConcreteRuntimeObjNode referencer: curr.parentsWithReadToNode) {
573       if(curr.parentsThatWillLeadToConflicts.add(referencer) || //case where referencee has never seen referncer
574           (pointsOfAccess != null && referencer.addPossibleWaitingQueueEnqueue(pointsOfAccess))) // case where referencer has never seen possible unresolved referencee below 
575       {
576         referencer.decendantsObjConflict = true;
577         propogateObjConflict(referencer, pointsOfAccess);
578       }
579     }
580   }
581   
582   private void propogateObjConflict(ConcreteRuntimeObjNode curr, ConcreteRuntimeObjNode pointOfAccess) {
583     for(ConcreteRuntimeObjNode referencer: curr.parentsWithReadToNode) {
584       if(curr.parentsThatWillLeadToConflicts.add(referencer) || //case where referencee has never seen referncer
585           (pointOfAccess != null && referencer.addPossibleWaitingQueueEnqueue(pointOfAccess))) // case where referencer has never seen possible unresolved referencee below 
586       {
587         referencer.decendantsObjConflict = true;
588         propogateObjConflict(referencer, pointOfAccess);
589       }
590     }
591   }
592   
593   private void propogatePrimConflict(ConcreteRuntimeObjNode curr, HashSet<ConcreteRuntimeObjNode> pointsOfAccess) {
594     for(ConcreteRuntimeObjNode referencer: curr.parentsWithReadToNode) {
595       if(curr.parentsThatWillLeadToConflicts.add(referencer) || //same cases as above
596           (pointsOfAccess != null && referencer.addPossibleWaitingQueueEnqueue(pointsOfAccess))) 
597       {
598         referencer.decendantsPrimConflict = true;
599         propogatePrimConflict(referencer, pointsOfAccess);
600       }
601     }
602   }
603   
604   private void propogatePrimConflict(ConcreteRuntimeObjNode curr, ConcreteRuntimeObjNode pointOfAccess) {
605     for(ConcreteRuntimeObjNode referencer: curr.parentsWithReadToNode) {
606       if(curr.parentsThatWillLeadToConflicts.add(referencer) || //same cases as above
607           (pointOfAccess != null && referencer.addPossibleWaitingQueueEnqueue(pointOfAccess))) 
608       {
609         referencer.decendantsPrimConflict = true;
610         propogatePrimConflict(referencer, pointOfAccess);
611       }
612     }
613   }
614   
615   
616
617   /*
618    * This method generates a C method for every inset variable and rblock. 
619    * 
620    * The C method works by generating a large switch statement that will run the appropriate 
621    * checking code for each object based on its allocation site. The switch statement is 
622    * surrounded by a while statement which dequeues objects to be checked from a queue. An
623    * object is added to a queue only if it contains a conflict (in itself or in its referencees)
624    *  and we came across it while checking through it's referencer. Because of this property, 
625    *  conflicts will be signaled by the referencer; the only exception is the inset variable which can 
626    *  signal a conflict within itself. 
627    */
628   
629   private void printCMethod(Hashtable<AllocSite, ConcreteRuntimeObjNode> created, Taint taint) {
630     //This hash table keeps track of all the case statements generated. Although it may seem a bit much 
631    //for its purpose, I think it may come in handy later down the road to do it this way. 
632     //(i.e. what if we want to eliminate some cases? Or build filter for 1 case)
633     String inVar = taint.getVar().getSafeSymbol();
634     String rBlock;
635     
636     if(taint.isStallSiteTaint()) {
637       rBlock = taint.getStallSite().toString();
638     } else if(taint.isRBlockTaint()) {
639       rBlock = taint.getSESE().getPrettyIdentifier();
640     } else {
641       System.out.println("RCR CRITICAL ERROR: TAINT IS NEITHER A STALLSITE NOR SESE! " + taint.toString());
642       return;
643     }
644     
645     Hashtable<AllocSite, StringBuilder> cases = new Hashtable<AllocSite, StringBuilder>();
646     
647     //Generate C cases 
648     for (ConcreteRuntimeObjNode node : created.values()) {
649       printDebug(javaDebug, "Considering " + node.allocSite + " for traversal");
650       if (!cases.containsKey(node.allocSite) && qualifiesForCaseStatement(node)) {
651         printDebug(javaDebug, "+\t" + node.allocSite + " qualified for case statement");
652         addChecker(taint, node, cases, null, "ptr", 0);
653       }
654     }
655     //IMPORTANT: remember to change getTraverserInvocation if you change the line below
656     String methodName;
657     if (taint.isStallSiteTaint()) {
658       methodName= "void traverse___" + removeInvalidChars(inVar) + 
659         removeInvalidChars(rBlock) + "___(void * InVar, SESEcommon *record)";
660     } else {
661       methodName= "void traverse___" + removeInvalidChars(inVar) + 
662         removeInvalidChars(rBlock) + "___(void * InVar, "+taint.getSESE().getSESErecordName() +" *record)";
663     }
664
665     cFile.println(methodName + " {");
666     headerFile.println(methodName + ";");
667     
668     if(cSideDebug) {
669       cFile.println("printf(\"The traverser ran for " + methodName + "\\n\");");
670     }
671     
672     if(cases.size() == 0) {
673       cFile.println(" return; }");
674     } else {
675       //clears queue and hashtable that keeps track of where we've been. 
676       cFile.println(clearQueue + ";\n" + resetVisitedHashTable + ";"); 
677       
678       //Casts the ptr to a generic object struct so we can get to the ptr->allocsite field. 
679       cFile.println("struct ___Object___ * ptr = (struct ___Object___ *) InVar;\nif (InVar != NULL) {\n " + queryVistedHashtable + "(ptr);\n do {");
680       
681       cFile.println("  switch(ptr->allocsite) {");
682       
683       for(AllocSite singleCase: cases.keySet())
684         cFile.append(cases.get(singleCase));
685       
686       cFile.println("  default:\n    break; ");
687       cFile.println("  }\n } while((ptr = " + dequeueFromQueueInC + ") != NULL);\n}\n}\n");
688     }
689     cFile.flush();
690   }
691   
692   /*
693    * addChecker creates a case statement for every object that is either an inset variable
694    * or has multiple referencers (incoming edges). Else it just prints the checker for that object
695    * so that its processing can be pushed up to the referencer node. 
696    */
697   private void addChecker(Taint taint, 
698                           ConcreteRuntimeObjNode node, 
699                           Hashtable<AllocSite,StringBuilder> cases, 
700                           StringBuilder possibleContinuingCase, 
701                           String prefix, 
702                           int depth) {
703     StringBuilder currCase = possibleContinuingCase;
704     // We don't need a case statement for things with either 1 incoming or 0 out
705     // going edges, because they can be processed when checking the parent. 
706     if(qualifiesForCaseStatement(node)) {
707       assert prefix.equals("ptr") && !cases.containsKey(node.allocSite);
708       currCase = new StringBuilder();
709       cases.put(node.allocSite, currCase);
710       currCase.append("  case " + node.getAllocationSite() + ": {\n");
711     }
712     //either currCase is continuing off a parent case or is its own. 
713     assert currCase !=null;
714     boolean primConfRead=false;
715     boolean primConfWrite=false;
716     boolean objConfRead=false;
717     boolean objConfWrite=false;
718
719     //Primitives Test
720     for(String field: node.primitiveConflictingFields.keySet()) {
721       CombinedObjEffects effect=node.primitiveConflictingFields.get(field);
722       primConfRead|=effect.hasReadConflict;
723       primConfWrite|=effect.hasWriteConflict;
724     }
725
726     //Object Reference Test
727     for(ObjRef ref: node.objectRefs) {
728       CombinedObjEffects effect=ref.myEffects;
729       objConfRead|=effect.hasReadConflict;
730       objConfWrite|=effect.hasWriteConflict;
731     }
732     currCase.append("     int tmpvar;");
733
734     if (objConfRead) {
735       currCase.append("    if(");
736       checkWaitingQueue(currCase, taint,  node);
737       currCase.append("||!");
738     }
739
740     int index=-1;
741     if (taint.isRBlockTaint()) {
742       FlatSESEEnterNode fsese=taint.getSESE();
743       TempDescriptor tmp=taint.getVar();
744       index=fsese.getInVarsForDynamicCoarseConflictResolution().indexOf(tmp);
745     }
746
747     //Do call if we need it.
748     if(primConfWrite||objConfWrite) {
749       int heaprootNum = connectedHRHash.get(taint).id;
750       assert heaprootNum != -1;
751       int allocSiteID = connectedHRHash.get(taint).getWaitingQueueBucketNum(node);
752       int traverserID = doneTaints.get(taint);
753       currCase.append("    (tmpvar=rcr_WRITEBINCASE(allHashStructures["+heaprootNum+"],"+prefix+", (SESEcommon *) record, "+index+"))");
754     } else if (primConfRead||objConfRead) {
755       int heaprootNum = connectedHRHash.get(taint).id;
756       assert heaprootNum != -1;
757       int allocSiteID = connectedHRHash.get(taint).getWaitingQueueBucketNum(node);
758       int traverserID = doneTaints.get(taint);
759       currCase.append("    (tmpvar=rcr_READBINCASE(allHashStructures["+heaprootNum+"],"+prefix+", (SESEcommon *) record, "+index+"))");
760     }
761
762     if(objConfRead) {
763       currCase.append("&READYMASK) {\n");
764       putIntoWaitingQueue(currCase, taint, node, prefix);        
765       currCase.append("    break;\n");
766       currCase.append("    }\n");
767     } else if(primConfRead||primConfWrite||objConfWrite) {
768       currCase.append(";\n");
769     }
770
771     
772     //Conflicts
773     
774     //Array Case
775     if(node.isObjectArray() && node.decendantsConflict()) {
776       //since each array element will get its own case statement, we just need to enqueue each item into the queue
777       //note that the ref would be the actual object and node would be of struct ArrayObject
778       
779       ArrayList<Integer> allocSitesWithProblems = node.getReferencedAllocSites();
780       if(!allocSitesWithProblems.isEmpty()) {
781         //This is done with the assumption that an array of object stores pointers. 
782         currCase.append("{\n  int i;\n");
783         currCase.append("  for(i = 0; i<((struct ArrayObject *) " + prefix + " )->___length___; i++ ) {\n");
784         currCase.append("    struct ___Object___ * arrayElement = ((INTPTR *)(&(((struct ArrayObject *) " + prefix + " )->___length___) + sizeof(int)))[i];\n");
785         currCase.append("    if( arrayElement != NULL && (");
786         
787         for(Integer i: allocSitesWithProblems) {
788           currCase.append("( arrayElement->allocsite == " + i.toString() +") ||");
789         }
790         //gets rid of the last ||
791         currCase.delete(currCase.length()-3, currCase.length());
792         
793         currCase.append(") && "+queryVistedHashtable +"(arrayElement)) {\n");
794         currCase.append("      " + addToQueueInC + "arrayElement); }}}\n");
795       }
796     } else {
797     //All other cases
798       for(ObjRef ref: node.objectRefs) {     
799         // Will only process edge if there is some sort of conflict with the Child
800         if (ref.hasConflictsDownThisPath()) {  
801           String childPtr = "((struct "+node.original.getType().getSafeSymbol()+" *)"+prefix +")->___" + ref.field + "___";
802           int pdepth=depth+1;
803           String currPtr = "myPtr" + pdepth;
804           String structType = ref.child.original.getType().getSafeSymbol();
805           currCase.append("    struct " + structType + " * "+currPtr+"= (struct "+ structType + " * ) " + childPtr + ";\n");
806   
807           // Checks if the child exists and has allocsite matching the conflict
808           currCase.append("    if (" + currPtr + " != NULL && " + currPtr + getAllocSiteInC + "==" + ref.allocSite + ") {\n");
809   
810           if (ref.child.decendantsConflict() || ref.child.hasPrimitiveConflicts()) {
811             // Checks if we have visited the child before
812
813             currCase.append("    if (" + queryVistedHashtable +"("+ currPtr + ")) {\n");
814             if (ref.child.getNumOfReachableParents() == 1 && !ref.child.isInsetVar) {
815               addChecker(taint, ref.child, cases, currCase, currPtr, depth + 1);
816             }
817             else {
818               currCase.append("      " + addToQueueInC + childPtr + ");\n ");
819             }
820             currCase.append("    }\n");
821           }
822           //one more brace for the opening if
823           if(ref.hasDirectObjConflict()) {
824             currCase.append("   }\n");
825           }
826           currCase.append("  }\n ");
827         }
828       }
829     }
830
831     if(qualifiesForCaseStatement(node)) {
832       currCase.append("  }\n  break;\n");
833     }
834   }
835   
836   private boolean qualifiesForCaseStatement(ConcreteRuntimeObjNode node) {
837     return (          
838         //insetVariable case
839         (node.isInsetVar && (node.decendantsConflict() || node.hasPrimitiveConflicts())) ||
840         //non-inline-able code cases
841         (node.getNumOfReachableParents() != 1 && node.decendantsConflict()) ||
842         //Cases where resumes are possible
843         (node.hasPotentialToBeIncorrectDueToConflict) && node.decendantsObjConflict) ||
844         //Array elements since we have to enqueue them all, we can't in line their checks
845         (node.canBeArrayElement() && (node.decendantsConflict() || node.hasPrimitiveConflicts()));
846   }
847
848   //This method will touch the waiting queues if necessary.
849   //IMPORTANT NOTE: This needs a closing } from the caller and the if is cannot continue
850   private void addCheckHashtableAndWaitingQ(StringBuilder currCase, Taint t, ConcreteRuntimeObjNode node, String ptr, int depth) {
851     Iterator<ConcreteRuntimeObjNode> it = node.enqueueToWaitingQueueUponConflict.iterator();
852     
853     currCase.append("    int retval"+depth+" = "+ addCheckFromHashStructure + ptr + ");\n");
854     currCase.append("    if (retval"+depth+" == " + conflictButTraverserCannotContinue + " || ");
855     checkWaitingQueue(currCase, t,  node);
856     currCase.append(") {\n");
857     //If cannot continue, then add all the undetermined references that lead from this child, including self.
858     //TODO need waitingQueue Side to automatically check the thing infront of it to prevent double adds. 
859     putIntoWaitingQueue(currCase, t, node, ptr);  
860     
861     ConcreteRuntimeObjNode related;
862     while(it.hasNext()) {
863       related = it.next();
864       //TODO maybe ptr won't even be needed since upon resume, the hashtable will remove obj. 
865       putIntoWaitingQueue(currCase, t, related, ptr);
866     }
867   }
868
869   /*
870   private void handleObjConflict(StringBuilder currCase, String childPtr, AllocSite allocSite, ObjRef ref) {
871     currCase.append("printf(\"Conflict detected with %p from parent with allocation site %u\\n\"," + childPtr + "," + allocSite.getUniqueAllocSiteID() + ");");
872   }
873   
874   private void handlePrimitiveConflict(StringBuilder currCase, String ptr, ArrayList<String> conflicts, AllocSite allocSite) {
875     currCase.append("printf(\"Primitive Conflict detected with %p with alloc site %u\\n\", "+ptr+", "+allocSite.getUniqueAllocSiteID()+"); ");
876   }
877   */
878   
879   private Taint getProperTaintForFlatSESEEnterNode(FlatSESEEnterNode rblock, VariableNode var,
880       Hashtable<Taint, Set<Effect>> effects) {
881     Set<Taint> taints = effects.keySet();
882     for (Taint t : taints) {
883       FlatSESEEnterNode sese = t.getSESE();
884       if(sese != null && sese.equals(rblock) && t.getVar().equals(var.getTempDescriptor())) {
885         return t;
886       }
887     }
888     return null;
889   }
890   
891   
892   private Taint getProperTaintForEnterNode(FlatNode stallSite, VariableNode var,
893       Hashtable<Taint, Set<Effect>> effects) {
894     Set<Taint> taints = effects.keySet();
895     for (Taint t : taints) {
896       FlatNode flatnode = t.getStallSite();
897       if(flatnode != null && flatnode.equals(stallSite) && t.getVar().equals(var.getTempDescriptor())) {
898         return t;
899       }
900     }
901     return null;
902   }
903   
904   private void printEffectsAndConflictsSets(Taint taint, Set<Effect> localEffects,
905       Set<Effect> localConflicts) {
906     System.out.println("#### List of Effects/Conflicts ####");
907     System.out.println("For Taint " + taint);
908     System.out.println("Effects");
909     if(localEffects != null) {
910       for(Effect e: localEffects) {
911        System.out.println(e); 
912       }
913     }
914     System.out.println("Conflicts");
915     if(localConflicts != null) {
916       for(Effect e: localConflicts) {
917         System.out.println(e); 
918       }
919     }
920   }
921
922   private void printDebug(boolean guard, String debugStatements) {
923     if(guard)
924       System.out.println(debugStatements);
925   }
926   
927   //TODO finish this once waitingQueue side is figured out
928   private void putIntoWaitingQueue(StringBuilder sb, Taint taint, ConcreteRuntimeObjNode node, String resumePtr ) {
929     //Method looks like this: void put(int allocSiteID,  x
930     //struct WaitingQueue * queue, //get this from hashtable
931     //int effectType, //not so sure we would actually need this one. 
932     //void * resumePtr, 
933     //int traverserID);  }
934     int heaprootNum = connectedHRHash.get(taint).id;
935     assert heaprootNum != -1;
936     int allocSiteID = connectedHRHash.get(taint).getWaitingQueueBucketNum(node);
937     int traverserID = doneTaints.get(taint);
938     
939     //NOTE if the C-side is changed, this will have to be changed accordingly
940     //TODO make sure this matches c-side
941     sb.append("      putIntoWaitingQueue("+allocSiteID+", " +
942                 "allHashStructures["+ heaprootNum +"]->waitingQueue, " +
943                 resumePtr + ", " +
944                 traverserID+");\n");
945   }
946   
947   //TODO finish waitingQueue side
948   /**
949    * Inserts check to see if waitingQueue is occupied.
950    * 
951    * On C-side, =0 means empty queue, else occupied. 
952    */
953   private void checkWaitingQueue(StringBuilder sb, Taint taint, ConcreteRuntimeObjNode node) {
954     //Method looks like int check(struct WaitingQueue * queue, int allocSiteID)
955     assert sb != null && taint !=null;    
956     int heaprootNum = connectedHRHash.get(taint).id;
957     assert heaprootNum != -1;
958     int allocSiteID = connectedHRHash.get(taint).getWaitingQueueBucketNum(node);
959     
960     sb.append(" (isEmptyForWaitingQ(allHashStructures["+ heaprootNum +"]->waitingQueue, " + allocSiteID + ") == "+ allocQueueIsNotEmpty+")");
961   }
962   
963   private void enumerateHeaproots() {
964     //reset numbers jsut in case
965     weaklyConnectedHRCounter = 0;
966     num2WeaklyConnectedHRGroup = new ArrayList<WeaklyConectedHRGroup>();
967     
968     for(Taint t: connectedHRHash.keySet()) {
969       if(connectedHRHash.get(t).id == -1) {
970         WeaklyConectedHRGroup hg = connectedHRHash.get(t);
971         hg.id = weaklyConnectedHRCounter;
972         num2WeaklyConnectedHRGroup.add(weaklyConnectedHRCounter, hg);
973         weaklyConnectedHRCounter++;
974       }
975     }
976   }
977   
978   private void printoutTable(EffectsTable table) {
979     
980     System.out.println("==============EFFECTS TABLE PRINTOUT==============");
981     for(AllocSite as: table.table.keySet()) {
982       System.out.println("\tFor AllocSite " + as.getUniqueAllocSiteID());
983       
984       BucketOfEffects boe = table.table.get(as);
985       
986       if(boe.potentiallyConflictingRoots != null && !boe.potentiallyConflictingRoots.isEmpty()) {
987         System.out.println("\t\tPotentially conflicting roots: ");
988         for(String key: boe.potentiallyConflictingRoots.keySet()) {
989           System.out.println("\t\t-Field: " + key);
990           System.out.println("\t\t\t" + boe.potentiallyConflictingRoots.get(key));
991         }
992       }
993       for(Taint t: boe.taint2EffectsGroup.keySet()) {
994         System.out.println("\t\t For Taint " + t);
995         EffectsGroup eg = boe.taint2EffectsGroup.get(t);
996           
997         if(eg.hasPrimitiveConflicts()) {
998           System.out.print("\t\t\tPrimitive Conflicts at alloc " + as.getUniqueAllocSiteID() +" : ");
999           for(String field: eg.primitiveConflictingFields.keySet()) {
1000             System.out.print(field + " ");
1001           }
1002           System.out.println();
1003         }
1004         for(String fieldKey: eg.myEffects.keySet()) {
1005           CombinedObjEffects ce = eg.myEffects.get(fieldKey);
1006           System.out.println("\n\t\t\tFor allocSite " + as.getUniqueAllocSiteID() + " && field " + fieldKey);
1007           System.out.println("\t\t\t\tread " + ce.hasReadEffect + "/"+ce.hasReadConflict + 
1008               " write " + ce.hasWriteEffect + "/" + ce.hasWriteConflict + 
1009               " SU " + ce.hasStrongUpdateEffect + "/" + ce.hasStrongUpdateConflict);
1010           for(Effect ef: ce.originalEffects) {
1011             System.out.println("\t" + ef);
1012           }
1013         }
1014       }
1015         
1016     }
1017     
1018   }
1019   
1020   private class EffectsGroup {
1021     Hashtable<String, CombinedObjEffects> myEffects;
1022     Hashtable<String, CombinedObjEffects> primitiveConflictingFields;
1023     
1024     public EffectsGroup() {
1025       myEffects = new Hashtable<String, CombinedObjEffects>();
1026       primitiveConflictingFields = new Hashtable<String, CombinedObjEffects>();
1027     }
1028
1029     public void addPrimitive(Effect e, boolean conflict) {
1030       CombinedObjEffects effects;
1031       if((effects = primitiveConflictingFields.get(e.getField().getSymbol())) == null) {
1032         effects = new CombinedObjEffects();
1033         primitiveConflictingFields.put(e.getField().getSymbol(), effects);
1034       }
1035       effects.add(e, conflict);
1036     }
1037     
1038     public void addObjEffect(Effect e, boolean conflict) {
1039       CombinedObjEffects effects;
1040       if((effects = myEffects.get(e.getField().getSymbol())) == null) {
1041         effects = new CombinedObjEffects();
1042         myEffects.put(e.getField().getSymbol(), effects);
1043       }
1044       effects.add(e, conflict);
1045     }
1046     
1047     public boolean isEmpty() {
1048       return myEffects.isEmpty() && primitiveConflictingFields.isEmpty();
1049     }
1050     
1051     public boolean hasPrimitiveConflicts(){
1052       return !primitiveConflictingFields.isEmpty();
1053     }
1054     
1055     public CombinedObjEffects getPrimEffect(String field) {
1056       return primitiveConflictingFields.get(field);
1057     }
1058
1059     public boolean hasObjectEffects() {
1060       return !myEffects.isEmpty();
1061     }
1062     
1063     public CombinedObjEffects getObjEffect(String field) {
1064       return myEffects.get(field);
1065     }
1066   }
1067   
1068   //Is the combined effects for all effects with the same affectedAllocSite and field
1069   private class CombinedObjEffects {
1070     ArrayList<Effect> originalEffects;
1071     
1072     public boolean hasReadEffect;
1073     public boolean hasWriteEffect;
1074     public boolean hasStrongUpdateEffect;
1075     
1076     public boolean hasReadConflict;
1077     public boolean hasWriteConflict;
1078     public boolean hasStrongUpdateConflict;
1079     
1080     
1081     public CombinedObjEffects() {
1082       originalEffects = new ArrayList<Effect>();
1083       
1084       hasReadEffect = false;
1085       hasWriteEffect = false;
1086       hasStrongUpdateEffect = false;
1087       
1088       hasReadConflict = false;
1089       hasWriteConflict = false;
1090       hasStrongUpdateConflict = false;
1091     }
1092     
1093     public boolean add(Effect e, boolean conflict) {
1094       if(!originalEffects.add(e))
1095         return false;
1096       
1097       switch(e.getType()) {
1098       case Effect.read:
1099         hasReadEffect = true;
1100         hasReadConflict = conflict;
1101         break;
1102       case Effect.write:
1103         hasWriteEffect = true;
1104         hasWriteConflict = conflict;
1105         break;
1106       case Effect.strongupdate:
1107         hasStrongUpdateEffect = true;
1108         hasStrongUpdateConflict = conflict;
1109         break;
1110       default:
1111         System.out.println("RCR ERROR: An Effect Type never seen before has been encountered");
1112         assert false;
1113         break;
1114       }
1115       return true;
1116     }
1117     
1118     public boolean hasConflict() {
1119       return hasReadConflict || hasWriteConflict || hasStrongUpdateConflict;
1120     }
1121   }
1122
1123   //This will keep track of a reference
1124   private class ObjRef {
1125     String field;
1126     int allocSite;
1127     CombinedObjEffects myEffects;
1128     
1129     //This keeps track of the parent that we need to pass by inorder to get
1130     //to the conflicting child (if there is one). 
1131     ConcreteRuntimeObjNode child;
1132
1133     public ObjRef(String fieldname, 
1134                   ConcreteRuntimeObjNode ref, 
1135                   CombinedObjEffects myEffects) {
1136       field = fieldname;
1137       allocSite = ref.getAllocationSite();
1138       child = ref;
1139       
1140       this.myEffects = myEffects;
1141     }
1142     
1143     public boolean hasConflictsDownThisPath() {
1144       return child.decendantsObjConflict || child.decendantsPrimConflict || child.hasPrimitiveConflicts() || myEffects.hasConflict(); 
1145     }
1146     
1147     public boolean hasDirectObjConflict() {
1148       return myEffects.hasConflict();
1149     }
1150   }
1151
1152   private class ConcreteRuntimeObjNode {
1153     ArrayList<ObjRef> objectRefs;
1154     Hashtable<String, CombinedObjEffects> primitiveConflictingFields;
1155     HashSet<ConcreteRuntimeObjNode> parentsWithReadToNode;
1156     HashSet<ConcreteRuntimeObjNode> parentsThatWillLeadToConflicts;
1157     //this set keeps track of references down the line that need to be enqueued if traverser is "paused"
1158     HashSet<ConcreteRuntimeObjNode> enqueueToWaitingQueueUponConflict;
1159     boolean decendantsPrimConflict;
1160     boolean decendantsObjConflict;
1161     boolean hasPotentialToBeIncorrectDueToConflict;
1162     boolean isInsetVar;
1163     boolean isArrayElement;
1164     AllocSite allocSite;
1165     HeapRegionNode original;
1166
1167     public ConcreteRuntimeObjNode(HeapRegionNode me, boolean isInVar, boolean isArrayElement) {
1168       objectRefs = new ArrayList<ObjRef>();
1169       primitiveConflictingFields = null;
1170       parentsThatWillLeadToConflicts = new HashSet<ConcreteRuntimeObjNode>();
1171       parentsWithReadToNode = new HashSet<ConcreteRuntimeObjNode>();
1172       enqueueToWaitingQueueUponConflict = new HashSet<ConcreteRuntimeObjNode>();
1173       allocSite = me.getAllocSite();
1174       original = me;
1175       isInsetVar = isInVar;
1176       decendantsPrimConflict = false;
1177       decendantsObjConflict = false;
1178       hasPotentialToBeIncorrectDueToConflict = false;
1179       this.isArrayElement = isArrayElement;
1180     }
1181
1182     public void addReachableParent(ConcreteRuntimeObjNode curr) {
1183       parentsWithReadToNode.add(curr);
1184     }
1185
1186     @Override
1187     public boolean equals(Object obj) {
1188       return original.equals(obj);
1189     }
1190
1191     public int getAllocationSite() {
1192       return allocSite.getUniqueAllocSiteID();
1193     }
1194
1195     public int getNumOfReachableParents() {
1196       return parentsThatWillLeadToConflicts.size();
1197     }
1198     
1199     public boolean hasPrimitiveConflicts() {
1200       return primitiveConflictingFields != null && !primitiveConflictingFields.isEmpty();
1201     }
1202     
1203     public boolean decendantsConflict() {
1204       return decendantsPrimConflict || decendantsObjConflict;
1205     }
1206     
1207     
1208     //returns true if at least one of the objects in points of access has been added
1209     public boolean addPossibleWaitingQueueEnqueue(HashSet<ConcreteRuntimeObjNode> pointsOfAccess) {
1210       boolean addedNew = false;
1211       for(ConcreteRuntimeObjNode dec: pointsOfAccess) {
1212         if(dec != null && dec != this){
1213           addedNew = addedNew || enqueueToWaitingQueueUponConflict.add(dec);
1214         }
1215       }
1216       
1217       return addedNew;
1218     }
1219     
1220     public boolean addPossibleWaitingQueueEnqueue(ConcreteRuntimeObjNode pointOfAccess) {
1221       if(pointOfAccess != null && pointOfAccess != this){
1222         return enqueueToWaitingQueueUponConflict.add(pointOfAccess);
1223       }
1224       
1225       return false;
1226     }
1227
1228     public void addObjChild(String field, ConcreteRuntimeObjNode child, CombinedObjEffects ce) {
1229       ObjRef ref = new ObjRef(field, child, ce);
1230       objectRefs.add(ref);
1231     }
1232     
1233     public boolean isObjectArray() {
1234       return original.getType().isArray() && !original.getType().isPrimitive() && !original.getType().isImmutable();
1235     }
1236     
1237     public boolean canBeArrayElement() {
1238       return isArrayElement;
1239     }
1240     
1241     public ArrayList<Integer> getReferencedAllocSites() {
1242       ArrayList<Integer> list = new ArrayList<Integer>();
1243       
1244       for(ObjRef r: objectRefs) {
1245         if(r.hasDirectObjConflict() || (r.child.parentsWithReadToNode.contains(this) && r.hasConflictsDownThisPath())) {
1246           list.add(r.allocSite);
1247         }
1248       }
1249       
1250       return list;
1251     }
1252     
1253     public String toString() {
1254       return "AllocSite=" + getAllocationSite() + " myConflict=" + !parentsThatWillLeadToConflicts.isEmpty() + 
1255               " decCon="+decendantsObjConflict+ 
1256               " NumOfConParents=" + getNumOfReachableParents() + " ObjectChildren=" + objectRefs.size();
1257     }
1258   }
1259   
1260   private class EffectsTable {
1261     private Hashtable<AllocSite, BucketOfEffects> table;
1262
1263     public EffectsTable(Hashtable<Taint, Set<Effect>> effects,
1264         Hashtable<Taint, Set<Effect>> conflicts) {
1265       table = new Hashtable<AllocSite, BucketOfEffects>();
1266
1267       // rehash all effects (as a 5-tuple) by their affected allocation site
1268       for (Taint t : effects.keySet()) {
1269         Set<Effect> localConflicts = conflicts.get(t);
1270         for (Effect e : effects.get(t)) {
1271           BucketOfEffects bucket;
1272           if ((bucket = table.get(e.getAffectedAllocSite())) == null) {
1273             bucket = new BucketOfEffects();
1274             table.put(e.getAffectedAllocSite(), bucket);
1275           }
1276           printDebug(javaDebug, "Added Taint" + t + " Effect " + e + "Conflict Status = " + (localConflicts!=null?localConflicts.contains(e):false)+" localConflicts = "+localConflicts);
1277           bucket.add(t, e, localConflicts!=null?localConflicts.contains(e):false);
1278         }
1279       }
1280     }
1281
1282     public EffectsGroup getEffects(AllocSite parentKey, Taint taint) {
1283       //This would get the proper bucket of effects and then get all the effects
1284       //for a parent for a specific taint
1285       try {
1286         return table.get(parentKey).taint2EffectsGroup.get(taint);
1287       }
1288       catch (NullPointerException e) {
1289         return null;
1290       }
1291     }
1292
1293     // Run Analysis will walk the data structure and figure out the weakly
1294     // connected heap roots. 
1295     public void runAnaylsis() {
1296       if(javaDebug) {
1297         printoutTable(this); 
1298       }
1299       
1300       //TODO is there a higher performance way to do this? 
1301       for(AllocSite key: table.keySet()) {
1302         BucketOfEffects effects = table.get(key);
1303         //make sure there are actually conflicts in the bucket
1304         if(effects.potentiallyConflictingRoots != null && !effects.potentiallyConflictingRoots.isEmpty()){
1305           for(String field: effects.potentiallyConflictingRoots.keySet()){
1306             ArrayList<Taint> taints = effects.potentiallyConflictingRoots.get(field);
1307             //For simplicity, we just create a new group and add everything to it instead of
1308             //searching through all of them for the largest group and adding everyone in. 
1309             WeaklyConectedHRGroup group = new WeaklyConectedHRGroup();
1310             group.add(taints); //This will automatically add the taint to the connectedHRhash
1311           }
1312         }
1313       }
1314     }
1315   }
1316   
1317   private class WeaklyConectedHRGroup {
1318     HashSet<Taint> connectedHRs;
1319     //This is to keep track of unique waitingQueue positions for each allocsite. 
1320     Hashtable<AllocSite, Integer> allocSiteToWaitingQueueMap;
1321     int waitingQueueCounter;
1322     int id;
1323     
1324     public WeaklyConectedHRGroup() {
1325       connectedHRs = new HashSet<Taint>();
1326       id = -1; //this will be later modified
1327       waitingQueueCounter = 0;
1328       allocSiteToWaitingQueueMap = new Hashtable<AllocSite, Integer>();
1329     }
1330     
1331     public void add(ArrayList<Taint> list) {
1332       for(Taint t: list) {
1333         this.add(t);
1334       }
1335     }
1336     
1337     public int getWaitingQueueBucketNum(ConcreteRuntimeObjNode node) {
1338       if(allocSiteToWaitingQueueMap.containsKey(node.allocSite)) {
1339         return allocSiteToWaitingQueueMap.get(node.allocSite);
1340       }
1341       else {
1342         allocSiteToWaitingQueueMap.put(node.allocSite, waitingQueueCounter);
1343         return waitingQueueCounter++;
1344       }
1345     }
1346     
1347     public void add(Taint t) {
1348       connectedHRs.add(t);
1349       WeaklyConectedHRGroup oldGroup = connectedHRHash.get(t);
1350       connectedHRHash.put(t, this); //put new group into hash
1351       //If the taint was already in another group, move all its buddies over. 
1352       if(oldGroup != this && oldGroup != null) {
1353         Iterator<Taint> it = oldGroup.connectedHRs.iterator();
1354         Taint relatedTaint;
1355         
1356         while((relatedTaint = it.next()) != null && !connectedHRs.contains(relatedTaint)) {
1357           this.add(relatedTaint);
1358         }
1359       }
1360     }
1361   }
1362   
1363   //This is a class that stores all the effects for an affected allocation site
1364   //across ALL taints. The structure is a hashtable of EffectGroups (see above) hashed
1365   //by a Taint. This way, I can keep EffectsGroups so I can reuse most to all of my old code
1366   //and allows for easier tracking of effects. In addition, a hashtable (keyed by the string
1367   //of the field access) keeps track of an ArrayList of taints of SESEblocks that conflict on that
1368   //field.
1369   private class BucketOfEffects {
1370     // This table is used for lookup while creating the traversal.
1371     Hashtable<Taint, EffectsGroup> taint2EffectsGroup;
1372     
1373     //This table is used to help identify weakly connected groups: Contains ONLY 
1374     //conflicting effects AND is only initialized when needed
1375     //String stores the field
1376     Hashtable<String, ArrayList<Taint>> potentiallyConflictingRoots;
1377
1378     public BucketOfEffects() {
1379       taint2EffectsGroup = new Hashtable<Taint, EffectsGroup>();
1380     }
1381
1382     public void add(Taint t, Effect e, boolean conflict) {
1383       EffectsGroup effectsForGivenTaint;
1384
1385       if ((effectsForGivenTaint = taint2EffectsGroup.get(t)) == null) {
1386         effectsForGivenTaint = new EffectsGroup();
1387         taint2EffectsGroup.put(t, effectsForGivenTaint);
1388       }
1389
1390       if (e.getField().getType().isPrimitive()) {
1391         if (conflict) {
1392           effectsForGivenTaint.addPrimitive(e, true);
1393         }
1394       } else {
1395         effectsForGivenTaint.addObjEffect(e, conflict);
1396       }
1397       
1398       if(conflict) {
1399         if(potentiallyConflictingRoots == null) {
1400           potentiallyConflictingRoots = new Hashtable<String, ArrayList<Taint>>();
1401         }
1402         
1403         ArrayList<Taint> taintsForField = potentiallyConflictingRoots.get(e.getField().getSafeSymbol());
1404         if(taintsForField == null) {
1405           taintsForField = new ArrayList<Taint>();
1406           potentiallyConflictingRoots.put(e.getField().getSafeSymbol(), taintsForField);
1407         }
1408         
1409         if(!taintsForField.contains(t)) {
1410           taintsForField.add(t);
1411         }
1412       }
1413     }
1414   }
1415   
1416   private class TaintAndInternalHeapStructure {
1417     public Taint t;
1418     public Hashtable<AllocSite, ConcreteRuntimeObjNode> nodesInHeap;
1419     
1420     public TaintAndInternalHeapStructure(Taint taint, Hashtable<AllocSite, ConcreteRuntimeObjNode> nodesInHeap) {
1421       t = taint;
1422       this.nodesInHeap = nodesInHeap;
1423     }
1424   }
1425   
1426   private class TraversalInfo {
1427     public FlatNode f;
1428     public ReachGraph rg;
1429     public TempDescriptor invar;
1430     
1431     public TraversalInfo(FlatNode fn, ReachGraph g) {
1432       f = fn;
1433       rg =g;
1434       invar = null;
1435     }
1436
1437     public TraversalInfo(FlatNode fn, ReachGraph rg2, TempDescriptor tempDesc) {
1438       f = fn;
1439       rg =rg2;
1440       invar = tempDesc;
1441     }
1442   }
1443 }