Added allocsite check for array elements before inserting into visitedhash.
[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   
733     if (objConfRead) {
734       currCase.append("    if(");
735       checkWaitingQueue(currCase, taint,  node);
736       currCase.append("||");
737     }
738
739     int index=-1;
740     if (taint.isRBlockTaint()) {
741       FlatSESEEnterNode fsese=taint.getSESE();
742       TempDescriptor tmp=taint.getVar();
743       index=fsese.getInVarsForDynamicCoarseConflictResolution().indexOf(tmp);
744     }
745
746     //Do call if we need it.
747     if(primConfWrite||objConfWrite) {
748       int heaprootNum = connectedHRHash.get(taint).id;
749       assert heaprootNum != -1;
750       int allocSiteID = connectedHRHash.get(taint).getWaitingQueueBucketNum(node);
751       int traverserID = doneTaints.get(taint);
752       currCase.append("    rcr_WRITEBINCASE(allHashStructures["+heaprootNum+"],"+prefix+", (SESEcommon *) record, "+index+")");
753     } else if (primConfRead||objConfRead) {
754       int heaprootNum = connectedHRHash.get(taint).id;
755       assert heaprootNum != -1;
756       int allocSiteID = connectedHRHash.get(taint).getWaitingQueueBucketNum(node);
757       int traverserID = doneTaints.get(taint);
758       currCase.append("    rcr_READBINCASE(allHashStructures["+heaprootNum+"],"+prefix+", (SESEcommon *) record, "+index+")");
759     }
760
761     if(objConfRead) {
762       currCase.append(") {\n");
763       putIntoWaitingQueue(currCase, taint, node, prefix);        
764       currCase.append("    break;\n");
765       currCase.append("    }\n");
766     } else if(primConfRead||primConfWrite||objConfWrite) {
767       currCase.append(";\n");
768     }
769
770     
771     //Conflicts
772     
773     //Array Case
774     if(node.isObjectArray() && node.decendantsConflict()) {
775       //since each array element will get its own case statement, we just need to enqueue each item into the queue
776       //note that the ref would be the actual object and node would be of struct ArrayObject
777       
778       ArrayList<Integer> allocSitesWithProblems = node.getReferencedAllocSites();
779       if(!allocSitesWithProblems.isEmpty()) {
780         //This is done with the assumption that an array of object stores pointers. 
781         currCase.append("{\n  int i;\n");
782         currCase.append("  for(i = 0; i<((struct ArrayObject *) " + prefix + " )->___length___; i++ ) {\n");
783         currCase.append("    struct ___Object___ * arrayElement = ((INTPTR *)(&(((struct ArrayObject *) " + prefix + " )->___length___) + sizeof(int)))[i];\n");
784         currCase.append("    if( arrayElement != NULL && (");
785         
786         for(Integer i: allocSitesWithProblems) {
787           currCase.append("( arrayElement->allocsite == " + i.toString() +") ||");
788         }
789         //gets rid of the last ||
790         currCase.delete(currCase.length()-3, currCase.length());
791         
792         currCase.append(") && "+queryVistedHashtable +"(arrayElement)) {\n");
793         currCase.append("      " + addToQueueInC + "arrayElement); }}}\n");
794       }
795     } else {
796     //All other cases
797       for(ObjRef ref: node.objectRefs) {     
798         // Will only process edge if there is some sort of conflict with the Child
799         if (ref.hasConflictsDownThisPath()) {  
800           String childPtr = "((struct "+node.original.getType().getSafeSymbol()+" *)"+prefix +")->___" + ref.field + "___";
801           int pdepth=depth+1;
802           String currPtr = "myPtr" + pdepth;
803           String structType = ref.child.original.getType().getSafeSymbol();
804           currCase.append("    struct " + structType + " * "+currPtr+"= (struct "+ structType + " * ) " + childPtr + ";\n");
805   
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             
821             currCase.append("    }\n");
822           }
823           //one more brace for the opening if
824           if(ref.hasDirectObjConflict()) {
825             currCase.append("   }\n");
826           }
827           
828           currCase.append("  }\n ");
829         }
830       }
831     }
832
833     if(qualifiesForCaseStatement(node)) {
834       currCase.append("  }\n  break;\n");
835     }
836   }
837   
838   private boolean qualifiesForCaseStatement(ConcreteRuntimeObjNode node) {
839     return (          
840         //insetVariable case
841         (node.isInsetVar && (node.decendantsConflict() || node.hasPrimitiveConflicts())) ||
842         //non-inline-able code cases
843         (node.getNumOfReachableParents() != 1 && node.decendantsConflict()) ||
844         //Cases where resumes are possible
845         (node.hasPotentialToBeIncorrectDueToConflict) && node.decendantsObjConflict) ||
846         //Array elements since we have to enqueue them all, we can't in line their checks
847         (node.canBeArrayElement() && (node.decendantsConflict() || node.hasPrimitiveConflicts()));
848   }
849
850   //This method will touch the waiting queues if necessary.
851   //IMPORTANT NOTE: This needs a closing } from the caller and the if is cannot continue
852   private void addCheckHashtableAndWaitingQ(StringBuilder currCase, Taint t, ConcreteRuntimeObjNode node, String ptr, int depth) {
853     Iterator<ConcreteRuntimeObjNode> it = node.enqueueToWaitingQueueUponConflict.iterator();
854     
855     currCase.append("    int retval"+depth+" = "+ addCheckFromHashStructure + ptr + ");\n");
856     currCase.append("    if (retval"+depth+" == " + conflictButTraverserCannotContinue + " || ");
857     checkWaitingQueue(currCase, t,  node);
858     currCase.append(") {\n");
859     //If cannot continue, then add all the undetermined references that lead from this child, including self.
860     //TODO need waitingQueue Side to automatically check the thing infront of it to prevent double adds. 
861     putIntoWaitingQueue(currCase, t, node, ptr);  
862     
863     ConcreteRuntimeObjNode related;
864     while(it.hasNext()) {
865       related = it.next();
866       //TODO maybe ptr won't even be needed since upon resume, the hashtable will remove obj. 
867       putIntoWaitingQueue(currCase, t, related, ptr);
868     }
869   }
870
871   /*
872   private void handleObjConflict(StringBuilder currCase, String childPtr, AllocSite allocSite, ObjRef ref) {
873     currCase.append("printf(\"Conflict detected with %p from parent with allocation site %u\\n\"," + childPtr + "," + allocSite.getUniqueAllocSiteID() + ");");
874   }
875   
876   private void handlePrimitiveConflict(StringBuilder currCase, String ptr, ArrayList<String> conflicts, AllocSite allocSite) {
877     currCase.append("printf(\"Primitive Conflict detected with %p with alloc site %u\\n\", "+ptr+", "+allocSite.getUniqueAllocSiteID()+"); ");
878   }
879   */
880   
881   private Taint getProperTaintForFlatSESEEnterNode(FlatSESEEnterNode rblock, VariableNode var,
882       Hashtable<Taint, Set<Effect>> effects) {
883     Set<Taint> taints = effects.keySet();
884     for (Taint t : taints) {
885       FlatSESEEnterNode sese = t.getSESE();
886       if(sese != null && sese.equals(rblock) && t.getVar().equals(var.getTempDescriptor())) {
887         return t;
888       }
889     }
890     return null;
891   }
892   
893   
894   private Taint getProperTaintForEnterNode(FlatNode stallSite, VariableNode var,
895       Hashtable<Taint, Set<Effect>> effects) {
896     Set<Taint> taints = effects.keySet();
897     for (Taint t : taints) {
898       FlatNode flatnode = t.getStallSite();
899       if(flatnode != null && flatnode.equals(stallSite) && t.getVar().equals(var.getTempDescriptor())) {
900         return t;
901       }
902     }
903     return null;
904   }
905   
906   private void printEffectsAndConflictsSets(Taint taint, Set<Effect> localEffects,
907       Set<Effect> localConflicts) {
908     System.out.println("#### List of Effects/Conflicts ####");
909     System.out.println("For Taint " + taint);
910     System.out.println("Effects");
911     if(localEffects != null) {
912       for(Effect e: localEffects) {
913        System.out.println(e); 
914       }
915     }
916     System.out.println("Conflicts");
917     if(localConflicts != null) {
918       for(Effect e: localConflicts) {
919         System.out.println(e); 
920       }
921     }
922   }
923
924   private void printDebug(boolean guard, String debugStatements) {
925     if(guard)
926       System.out.println(debugStatements);
927   }
928   
929   //TODO finish this once waitingQueue side is figured out
930   private void putIntoWaitingQueue(StringBuilder sb, Taint taint, ConcreteRuntimeObjNode node, String resumePtr ) {
931     //Method looks like this: void put(int allocSiteID,  x
932     //struct WaitingQueue * queue, //get this from hashtable
933     //int effectType, //not so sure we would actually need this one. 
934     //void * resumePtr, 
935     //int traverserID);  }
936     int heaprootNum = connectedHRHash.get(taint).id;
937     assert heaprootNum != -1;
938     int allocSiteID = connectedHRHash.get(taint).getWaitingQueueBucketNum(node);
939     int traverserID = doneTaints.get(taint);
940     
941     //NOTE if the C-side is changed, this will have to be changed accordingly
942     //TODO make sure this matches c-side
943     sb.append("      putIntoWaitingQueue("+allocSiteID+", " +
944                 "allHashStructures["+ heaprootNum +"]->waitingQueue, " +
945                 resumePtr + ", " +
946                 traverserID+");\n");
947   }
948   
949   //TODO finish waitingQueue side
950   /**
951    * Inserts check to see if waitingQueue is occupied.
952    * 
953    * On C-side, =0 means empty queue, else occupied. 
954    */
955   private void checkWaitingQueue(StringBuilder sb, Taint taint, ConcreteRuntimeObjNode node) {
956     //Method looks like int check(struct WaitingQueue * queue, int allocSiteID)
957     assert sb != null && taint !=null;    
958     int heaprootNum = connectedHRHash.get(taint).id;
959     assert heaprootNum != -1;
960     int allocSiteID = connectedHRHash.get(taint).getWaitingQueueBucketNum(node);
961     
962     sb.append(" (isEmptyForWaitingQ(allHashStructures["+ heaprootNum +"]->waitingQueue, " + allocSiteID + ") == "+ allocQueueIsNotEmpty+")");
963   }
964   
965   private void enumerateHeaproots() {
966     //reset numbers jsut in case
967     weaklyConnectedHRCounter = 0;
968     num2WeaklyConnectedHRGroup = new ArrayList<WeaklyConectedHRGroup>();
969     
970     for(Taint t: connectedHRHash.keySet()) {
971       if(connectedHRHash.get(t).id == -1) {
972         WeaklyConectedHRGroup hg = connectedHRHash.get(t);
973         hg.id = weaklyConnectedHRCounter;
974         num2WeaklyConnectedHRGroup.add(weaklyConnectedHRCounter, hg);
975         weaklyConnectedHRCounter++;
976       }
977     }
978   }
979   
980   private void printoutTable(EffectsTable table) {
981     
982     System.out.println("==============EFFECTS TABLE PRINTOUT==============");
983     for(AllocSite as: table.table.keySet()) {
984       System.out.println("\tFor AllocSite " + as.getUniqueAllocSiteID());
985       
986       BucketOfEffects boe = table.table.get(as);
987       
988       if(boe.potentiallyConflictingRoots != null && !boe.potentiallyConflictingRoots.isEmpty()) {
989         System.out.println("\t\tPotentially conflicting roots: ");
990         for(String key: boe.potentiallyConflictingRoots.keySet()) {
991           System.out.println("\t\t-Field: " + key);
992           System.out.println("\t\t\t" + boe.potentiallyConflictingRoots.get(key));
993         }
994       }
995       for(Taint t: boe.taint2EffectsGroup.keySet()) {
996         System.out.println("\t\t For Taint " + t);
997         EffectsGroup eg = boe.taint2EffectsGroup.get(t);
998           
999         if(eg.hasPrimitiveConflicts()) {
1000           System.out.print("\t\t\tPrimitive Conflicts at alloc " + as.getUniqueAllocSiteID() +" : ");
1001           for(String field: eg.primitiveConflictingFields.keySet()) {
1002             System.out.print(field + " ");
1003           }
1004           System.out.println();
1005         }
1006         for(String fieldKey: eg.myEffects.keySet()) {
1007           CombinedObjEffects ce = eg.myEffects.get(fieldKey);
1008           System.out.println("\n\t\t\tFor allocSite " + as.getUniqueAllocSiteID() + " && field " + fieldKey);
1009           System.out.println("\t\t\t\tread " + ce.hasReadEffect + "/"+ce.hasReadConflict + 
1010               " write " + ce.hasWriteEffect + "/" + ce.hasWriteConflict + 
1011               " SU " + ce.hasStrongUpdateEffect + "/" + ce.hasStrongUpdateConflict);
1012           for(Effect ef: ce.originalEffects) {
1013             System.out.println("\t" + ef);
1014           }
1015         }
1016       }
1017         
1018     }
1019     
1020   }
1021   
1022   private class EffectsGroup {
1023     Hashtable<String, CombinedObjEffects> myEffects;
1024     Hashtable<String, CombinedObjEffects> primitiveConflictingFields;
1025     
1026     public EffectsGroup() {
1027       myEffects = new Hashtable<String, CombinedObjEffects>();
1028       primitiveConflictingFields = new Hashtable<String, CombinedObjEffects>();
1029     }
1030
1031     public void addPrimitive(Effect e, boolean conflict) {
1032       CombinedObjEffects effects;
1033       if((effects = primitiveConflictingFields.get(e.getField().getSymbol())) == null) {
1034         effects = new CombinedObjEffects();
1035         primitiveConflictingFields.put(e.getField().getSymbol(), effects);
1036       }
1037       effects.add(e, conflict);
1038     }
1039     
1040     public void addObjEffect(Effect e, boolean conflict) {
1041       CombinedObjEffects effects;
1042       if((effects = myEffects.get(e.getField().getSymbol())) == null) {
1043         effects = new CombinedObjEffects();
1044         myEffects.put(e.getField().getSymbol(), effects);
1045       }
1046       effects.add(e, conflict);
1047     }
1048     
1049     public boolean isEmpty() {
1050       return myEffects.isEmpty() && primitiveConflictingFields.isEmpty();
1051     }
1052     
1053     public boolean hasPrimitiveConflicts(){
1054       return !primitiveConflictingFields.isEmpty();
1055     }
1056     
1057     public CombinedObjEffects getPrimEffect(String field) {
1058       return primitiveConflictingFields.get(field);
1059     }
1060
1061     public boolean hasObjectEffects() {
1062       return !myEffects.isEmpty();
1063     }
1064     
1065     public CombinedObjEffects getObjEffect(String field) {
1066       return myEffects.get(field);
1067     }
1068   }
1069   
1070   //Is the combined effects for all effects with the same affectedAllocSite and field
1071   private class CombinedObjEffects {
1072     ArrayList<Effect> originalEffects;
1073     
1074     public boolean hasReadEffect;
1075     public boolean hasWriteEffect;
1076     public boolean hasStrongUpdateEffect;
1077     
1078     public boolean hasReadConflict;
1079     public boolean hasWriteConflict;
1080     public boolean hasStrongUpdateConflict;
1081     
1082     
1083     public CombinedObjEffects() {
1084       originalEffects = new ArrayList<Effect>();
1085       
1086       hasReadEffect = false;
1087       hasWriteEffect = false;
1088       hasStrongUpdateEffect = false;
1089       
1090       hasReadConflict = false;
1091       hasWriteConflict = false;
1092       hasStrongUpdateConflict = false;
1093     }
1094     
1095     public boolean add(Effect e, boolean conflict) {
1096       if(!originalEffects.add(e))
1097         return false;
1098       
1099       switch(e.getType()) {
1100       case Effect.read:
1101         hasReadEffect = true;
1102         hasReadConflict = conflict;
1103         break;
1104       case Effect.write:
1105         hasWriteEffect = true;
1106         hasWriteConflict = conflict;
1107         break;
1108       case Effect.strongupdate:
1109         hasStrongUpdateEffect = true;
1110         hasStrongUpdateConflict = conflict;
1111         break;
1112       default:
1113         System.out.println("RCR ERROR: An Effect Type never seen before has been encountered");
1114         assert false;
1115         break;
1116       }
1117       return true;
1118     }
1119     
1120     public boolean hasConflict() {
1121       return hasReadConflict || hasWriteConflict || hasStrongUpdateConflict;
1122     }
1123   }
1124
1125   //This will keep track of a reference
1126   private class ObjRef {
1127     String field;
1128     int allocSite;
1129     CombinedObjEffects myEffects;
1130     
1131     //This keeps track of the parent that we need to pass by inorder to get
1132     //to the conflicting child (if there is one). 
1133     ConcreteRuntimeObjNode child;
1134
1135     public ObjRef(String fieldname, 
1136                   ConcreteRuntimeObjNode ref, 
1137                   CombinedObjEffects myEffects) {
1138       field = fieldname;
1139       allocSite = ref.getAllocationSite();
1140       child = ref;
1141       
1142       this.myEffects = myEffects;
1143     }
1144     
1145     public boolean hasConflictsDownThisPath() {
1146       return child.decendantsObjConflict || child.decendantsPrimConflict || child.hasPrimitiveConflicts() || myEffects.hasConflict(); 
1147     }
1148     
1149     public boolean hasDirectObjConflict() {
1150       return myEffects.hasConflict();
1151     }
1152   }
1153
1154   private class ConcreteRuntimeObjNode {
1155     ArrayList<ObjRef> objectRefs;
1156     Hashtable<String, CombinedObjEffects> primitiveConflictingFields;
1157     HashSet<ConcreteRuntimeObjNode> parentsWithReadToNode;
1158     HashSet<ConcreteRuntimeObjNode> parentsThatWillLeadToConflicts;
1159     //this set keeps track of references down the line that need to be enqueued if traverser is "paused"
1160     HashSet<ConcreteRuntimeObjNode> enqueueToWaitingQueueUponConflict;
1161     boolean decendantsPrimConflict;
1162     boolean decendantsObjConflict;
1163     boolean hasPotentialToBeIncorrectDueToConflict;
1164     boolean isInsetVar;
1165     boolean isArrayElement;
1166     AllocSite allocSite;
1167     HeapRegionNode original;
1168
1169     public ConcreteRuntimeObjNode(HeapRegionNode me, boolean isInVar, boolean isArrayElement) {
1170       objectRefs = new ArrayList<ObjRef>();
1171       primitiveConflictingFields = null;
1172       parentsThatWillLeadToConflicts = new HashSet<ConcreteRuntimeObjNode>();
1173       parentsWithReadToNode = new HashSet<ConcreteRuntimeObjNode>();
1174       enqueueToWaitingQueueUponConflict = new HashSet<ConcreteRuntimeObjNode>();
1175       allocSite = me.getAllocSite();
1176       original = me;
1177       isInsetVar = isInVar;
1178       decendantsPrimConflict = false;
1179       decendantsObjConflict = false;
1180       hasPotentialToBeIncorrectDueToConflict = false;
1181       this.isArrayElement = isArrayElement;
1182     }
1183
1184     public void addReachableParent(ConcreteRuntimeObjNode curr) {
1185       parentsWithReadToNode.add(curr);
1186     }
1187
1188     @Override
1189     public boolean equals(Object obj) {
1190       return original.equals(obj);
1191     }
1192
1193     public int getAllocationSite() {
1194       return allocSite.getUniqueAllocSiteID();
1195     }
1196
1197     public int getNumOfReachableParents() {
1198       return parentsThatWillLeadToConflicts.size();
1199     }
1200     
1201     public boolean hasPrimitiveConflicts() {
1202       return primitiveConflictingFields != null && !primitiveConflictingFields.isEmpty();
1203     }
1204     
1205     public boolean decendantsConflict() {
1206       return decendantsPrimConflict || decendantsObjConflict;
1207     }
1208     
1209     
1210     //returns true if at least one of the objects in points of access has been added
1211     public boolean addPossibleWaitingQueueEnqueue(HashSet<ConcreteRuntimeObjNode> pointsOfAccess) {
1212       boolean addedNew = false;
1213       for(ConcreteRuntimeObjNode dec: pointsOfAccess) {
1214         if(dec != null && dec != this){
1215           addedNew = addedNew || enqueueToWaitingQueueUponConflict.add(dec);
1216         }
1217       }
1218       
1219       return addedNew;
1220     }
1221     
1222     public boolean addPossibleWaitingQueueEnqueue(ConcreteRuntimeObjNode pointOfAccess) {
1223       if(pointOfAccess != null && pointOfAccess != this){
1224         return enqueueToWaitingQueueUponConflict.add(pointOfAccess);
1225       }
1226       
1227       return false;
1228     }
1229
1230     public void addObjChild(String field, ConcreteRuntimeObjNode child, CombinedObjEffects ce) {
1231       ObjRef ref = new ObjRef(field, child, ce);
1232       objectRefs.add(ref);
1233     }
1234     
1235     public boolean isObjectArray() {
1236       return original.getType().isArray() && !original.getType().isPrimitive() && !original.getType().isImmutable();
1237     }
1238     
1239     public boolean canBeArrayElement() {
1240       return isArrayElement;
1241     }
1242     
1243     public ArrayList<Integer> getReferencedAllocSites() {
1244       ArrayList<Integer> list = new ArrayList<Integer>();
1245       
1246       for(ObjRef r: objectRefs) {
1247         if(r.hasDirectObjConflict() || (r.child.parentsWithReadToNode.contains(this) && r.hasConflictsDownThisPath())) {
1248           list.add(r.allocSite);
1249         }
1250       }
1251       
1252       return list;
1253     }
1254     
1255     public String toString() {
1256       return "AllocSite=" + getAllocationSite() + " myConflict=" + !parentsThatWillLeadToConflicts.isEmpty() + 
1257               " decCon="+decendantsObjConflict+ 
1258               " NumOfConParents=" + getNumOfReachableParents() + " ObjectChildren=" + objectRefs.size();
1259     }
1260   }
1261   
1262   private class EffectsTable {
1263     private Hashtable<AllocSite, BucketOfEffects> table;
1264
1265     public EffectsTable(Hashtable<Taint, Set<Effect>> effects,
1266         Hashtable<Taint, Set<Effect>> conflicts) {
1267       table = new Hashtable<AllocSite, BucketOfEffects>();
1268
1269       // rehash all effects (as a 5-tuple) by their affected allocation site
1270       for (Taint t : effects.keySet()) {
1271         Set<Effect> localConflicts = conflicts.get(t);
1272         for (Effect e : effects.get(t)) {
1273           BucketOfEffects bucket;
1274           if ((bucket = table.get(e.getAffectedAllocSite())) == null) {
1275             bucket = new BucketOfEffects();
1276             table.put(e.getAffectedAllocSite(), bucket);
1277           }
1278           printDebug(javaDebug, "Added Taint" + t + " Effect " + e + "Conflict Status = " + (localConflicts!=null?localConflicts.contains(e):false)+" localConflicts = "+localConflicts);
1279           bucket.add(t, e, localConflicts!=null?localConflicts.contains(e):false);
1280         }
1281       }
1282     }
1283
1284     public EffectsGroup getEffects(AllocSite parentKey, Taint taint) {
1285       //This would get the proper bucket of effects and then get all the effects
1286       //for a parent for a specific taint
1287       try {
1288         return table.get(parentKey).taint2EffectsGroup.get(taint);
1289       }
1290       catch (NullPointerException e) {
1291         return null;
1292       }
1293     }
1294
1295     // Run Analysis will walk the data structure and figure out the weakly
1296     // connected heap roots. 
1297     public void runAnaylsis() {
1298       if(javaDebug) {
1299         printoutTable(this); 
1300       }
1301       
1302       //TODO is there a higher performance way to do this? 
1303       for(AllocSite key: table.keySet()) {
1304         BucketOfEffects effects = table.get(key);
1305         //make sure there are actually conflicts in the bucket
1306         if(effects.potentiallyConflictingRoots != null && !effects.potentiallyConflictingRoots.isEmpty()){
1307           for(String field: effects.potentiallyConflictingRoots.keySet()){
1308             ArrayList<Taint> taints = effects.potentiallyConflictingRoots.get(field);
1309             //For simplicity, we just create a new group and add everything to it instead of
1310             //searching through all of them for the largest group and adding everyone in. 
1311             WeaklyConectedHRGroup group = new WeaklyConectedHRGroup();
1312             group.add(taints); //This will automatically add the taint to the connectedHRhash
1313           }
1314         }
1315       }
1316     }
1317   }
1318   
1319   private class WeaklyConectedHRGroup {
1320     HashSet<Taint> connectedHRs;
1321     //This is to keep track of unique waitingQueue positions for each allocsite. 
1322     Hashtable<AllocSite, Integer> allocSiteToWaitingQueueMap;
1323     int waitingQueueCounter;
1324     int id;
1325     
1326     public WeaklyConectedHRGroup() {
1327       connectedHRs = new HashSet<Taint>();
1328       id = -1; //this will be later modified
1329       waitingQueueCounter = 0;
1330       allocSiteToWaitingQueueMap = new Hashtable<AllocSite, Integer>();
1331     }
1332     
1333     public void add(ArrayList<Taint> list) {
1334       for(Taint t: list) {
1335         this.add(t);
1336       }
1337     }
1338     
1339     public int getWaitingQueueBucketNum(ConcreteRuntimeObjNode node) {
1340       if(allocSiteToWaitingQueueMap.containsKey(node.allocSite)) {
1341         return allocSiteToWaitingQueueMap.get(node.allocSite);
1342       }
1343       else {
1344         allocSiteToWaitingQueueMap.put(node.allocSite, waitingQueueCounter);
1345         return waitingQueueCounter++;
1346       }
1347     }
1348     
1349     public void add(Taint t) {
1350       connectedHRs.add(t);
1351       WeaklyConectedHRGroup oldGroup = connectedHRHash.get(t);
1352       connectedHRHash.put(t, this); //put new group into hash
1353       //If the taint was already in another group, move all its buddies over. 
1354       if(oldGroup != this && oldGroup != null) {
1355         Iterator<Taint> it = oldGroup.connectedHRs.iterator();
1356         Taint relatedTaint;
1357         
1358         while((relatedTaint = it.next()) != null && !connectedHRs.contains(relatedTaint)) {
1359           this.add(relatedTaint);
1360         }
1361       }
1362     }
1363   }
1364   
1365   //This is a class that stores all the effects for an affected allocation site
1366   //across ALL taints. The structure is a hashtable of EffectGroups (see above) hashed
1367   //by a Taint. This way, I can keep EffectsGroups so I can reuse most to all of my old code
1368   //and allows for easier tracking of effects. In addition, a hashtable (keyed by the string
1369   //of the field access) keeps track of an ArrayList of taints of SESEblocks that conflict on that
1370   //field.
1371   private class BucketOfEffects {
1372     // This table is used for lookup while creating the traversal.
1373     Hashtable<Taint, EffectsGroup> taint2EffectsGroup;
1374     
1375     //This table is used to help identify weakly connected groups: Contains ONLY 
1376     //conflicting effects AND is only initialized when needed
1377     //String stores the field
1378     Hashtable<String, ArrayList<Taint>> potentiallyConflictingRoots;
1379
1380     public BucketOfEffects() {
1381       taint2EffectsGroup = new Hashtable<Taint, EffectsGroup>();
1382     }
1383
1384     public void add(Taint t, Effect e, boolean conflict) {
1385       EffectsGroup effectsForGivenTaint;
1386
1387       if ((effectsForGivenTaint = taint2EffectsGroup.get(t)) == null) {
1388         effectsForGivenTaint = new EffectsGroup();
1389         taint2EffectsGroup.put(t, effectsForGivenTaint);
1390       }
1391
1392       if (e.getField().getType().isPrimitive()) {
1393         if (conflict) {
1394           effectsForGivenTaint.addPrimitive(e, true);
1395         }
1396       } else {
1397         effectsForGivenTaint.addObjEffect(e, conflict);
1398       }
1399       
1400       if(conflict) {
1401         if(potentiallyConflictingRoots == null) {
1402           potentiallyConflictingRoots = new Hashtable<String, ArrayList<Taint>>();
1403         }
1404         
1405         ArrayList<Taint> taintsForField = potentiallyConflictingRoots.get(e.getField().getSafeSymbol());
1406         if(taintsForField == null) {
1407           taintsForField = new ArrayList<Taint>();
1408           potentiallyConflictingRoots.put(e.getField().getSafeSymbol(), taintsForField);
1409         }
1410         
1411         if(!taintsForField.contains(t)) {
1412           taintsForField.add(t);
1413         }
1414       }
1415     }
1416   }
1417   
1418   private class TaintAndInternalHeapStructure {
1419     public Taint t;
1420     public Hashtable<AllocSite, ConcreteRuntimeObjNode> nodesInHeap;
1421     
1422     public TaintAndInternalHeapStructure(Taint taint, Hashtable<AllocSite, ConcreteRuntimeObjNode> nodesInHeap) {
1423       t = taint;
1424       this.nodesInHeap = nodesInHeap;
1425     }
1426   }
1427   
1428   private class TraversalInfo {
1429     public FlatNode f;
1430     public ReachGraph rg;
1431     public TempDescriptor invar;
1432     
1433     public TraversalInfo(FlatNode fn, ReachGraph g) {
1434       f = fn;
1435       rg =g;
1436       invar = null;
1437     }
1438
1439     public TraversalInfo(FlatNode fn, ReachGraph rg2, TempDescriptor tempDesc) {
1440       f = fn;
1441       rg =rg2;
1442       invar = tempDesc;
1443     }
1444   }
1445 }