594829080a3ef30b4f04fe746f2ab4a38d4fb01e
[jpf-core.git] / src / main / gov / nasa / jpf / listener / DPORStateReducerEfficient.java
1 /*
2  * Copyright (C) 2014, United States Government, as represented by the
3  * Administrator of the National Aeronautics and Space Administration.
4  * All rights reserved.
5  *
6  * The Java Pathfinder core (jpf-core) platform is licensed under the
7  * Apache License, Version 2.0 (the "License"); you may not use this file except
8  * in compliance with the License. You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0.
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 package gov.nasa.jpf.listener;
19
20 import gov.nasa.jpf.Config;
21 import gov.nasa.jpf.JPF;
22 import gov.nasa.jpf.ListenerAdapter;
23 import gov.nasa.jpf.jvm.bytecode.INVOKEINTERFACE;
24 import gov.nasa.jpf.jvm.bytecode.JVMFieldInstruction;
25 import gov.nasa.jpf.search.Search;
26 import gov.nasa.jpf.vm.*;
27 import gov.nasa.jpf.vm.bytecode.ReadInstruction;
28 import gov.nasa.jpf.vm.bytecode.WriteInstruction;
29 import gov.nasa.jpf.vm.choice.IntChoiceFromSet;
30 import gov.nasa.jpf.vm.choice.IntIntervalGenerator;
31
32 import java.io.FileWriter;
33 import java.io.IOException;
34 import java.io.PrintWriter;
35 import java.util.*;
36 import java.util.logging.Logger;
37
38 /**
39  * This a DPOR implementation for event-driven applications with loops that create cycles of state matching
40  * In this new DPOR algorithm/implementation, each run is terminated iff:
41  * - we find a state that matches a state in a previous run, or
42  * - we have a matched state in the current run that consists of cycles that contain all choices/events.
43  */
44 public class DPORStateReducerEfficient extends ListenerAdapter {
45
46   // Information printout fields for verbose mode
47   private boolean verboseMode;
48   private boolean stateReductionMode;
49   private final PrintWriter out;
50   private PrintWriter fileWriter;
51   private String detail;
52   private int depth;
53   private int id;
54   private Transition transition;
55
56   // DPOR-related fields
57   // Basic information
58   private Integer[] choices;
59   private Integer[] refChoices; // Second reference to a copy of choices (choices may be modified for fair scheduling)
60   private int choiceCounter;
61   private int maxEventChoice;
62   // Data structure to track the events seen by each state to track cycles (containing all events) for termination
63   private HashSet<Integer> currVisitedStates;   // States being visited in the current execution
64   private HashSet<Integer> justVisitedStates;   // States just visited in the previous choice/event
65   private HashSet<Integer> prevVisitedStates;   // States visited in the previous execution
66   private HashSet<ClassInfo> nonRelevantClasses;// Class info objects of non-relevant classes
67   private HashSet<FieldInfo> nonRelevantFields; // Field info objects of non-relevant fields
68   private HashSet<FieldInfo> relevantFields;    // Field info objects of relevant fields
69   private HashMap<Integer, HashSet<Integer>> stateToEventMap;
70   // Data structure to analyze field Read/Write accesses and conflicts
71   private HashMap<Integer, LinkedList<BacktrackExecution>> backtrackMap;  // Track created backtracking points
72   private PriorityQueue<Integer> backtrackStateQ;                 // Heap that returns the latest state
73   private Execution currentExecution;                             // Holds the information about the current execution
74   private HashMap<Integer, HashSet<Integer>> doneBacktrackMap;    // Record state ID and trace already constructed
75   private HashMap<Integer, RestorableVMState> restorableStateMap; // Maps state IDs to the restorable state object
76   private RGraph rGraph;                                          // R-Graph for past executions
77
78   // Boolean states
79   private boolean isBooleanCGFlipped;
80   private boolean isEndOfExecution;
81
82   // Statistics
83   private int numOfTransitions;
84
85   public DPORStateReducerEfficient(Config config, JPF jpf) {
86     verboseMode = config.getBoolean("printout_state_transition", false);
87     stateReductionMode = config.getBoolean("activate_state_reduction", true);
88     if (verboseMode) {
89       out = new PrintWriter(System.out, true);
90     } else {
91       out = null;
92     }
93     String outputFile = config.getString("file_output");
94     if (!outputFile.isEmpty()) {
95       try {
96         fileWriter = new PrintWriter(new FileWriter(outputFile, true), true);
97       } catch (IOException e) {
98       }
99     }
100     isBooleanCGFlipped = false;
101                 numOfTransitions = 0;
102                 nonRelevantClasses = new HashSet<>();
103                 nonRelevantFields = new HashSet<>();
104                 relevantFields = new HashSet<>();
105     restorableStateMap = new HashMap<>();
106     initializeStatesVariables();
107   }
108
109   @Override
110   public void stateRestored(Search search) {
111     if (verboseMode) {
112       id = search.getStateId();
113       depth = search.getDepth();
114       transition = search.getTransition();
115       detail = null;
116       out.println("\n==> DEBUG: The state is restored to state with id: " + id + " -- Transition: " + transition +
117               " and depth: " + depth + "\n");
118     }
119   }
120
121   @Override
122   public void searchStarted(Search search) {
123     if (verboseMode) {
124       out.println("\n==> DEBUG: ----------------------------------- search started" + "\n");
125     }
126   }
127
128   @Override
129   public void stateAdvanced(Search search) {
130     if (verboseMode) {
131       id = search.getStateId();
132       depth = search.getDepth();
133       transition = search.getTransition();
134       if (search.isNewState()) {
135         detail = "new";
136       } else {
137         detail = "visited";
138       }
139
140       if (search.isEndState()) {
141         out.println("\n==> DEBUG: This is the last state!\n");
142         detail += " end";
143       }
144       out.println("\n==> DEBUG: The state is forwarded to state with id: " + id + " with depth: " + depth +
145               " which is " + detail + " Transition: " + transition + "\n");
146     }
147     if (stateReductionMode) {
148       updateStateInfo(search);
149     }
150   }
151
152   @Override
153   public void stateBacktracked(Search search) {
154     if (verboseMode) {
155       id = search.getStateId();
156       depth = search.getDepth();
157       transition = search.getTransition();
158       detail = null;
159
160       out.println("\n==> DEBUG: The state is backtracked to state with id: " + id + " -- Transition: " + transition +
161               " and depth: " + depth + "\n");
162     }
163     if (stateReductionMode) {
164       updateStateInfo(search);
165     }
166   }
167
168   static Logger log = JPF.getLogger("report");
169
170   @Override
171   public void searchFinished(Search search) {
172     if (verboseMode) {
173       out.println("\n==> DEBUG: ----------------------------------- search finished");
174       out.println("\n==> DEBUG: State reduction mode  : " + stateReductionMode);
175       out.println("\n==> DEBUG: Number of transitions : " + numOfTransitions);
176       out.println("\n==> DEBUG: ----------------------------------- search finished" + "\n");
177
178       fileWriter.println("==> DEBUG: State reduction mode  : " + stateReductionMode);
179       fileWriter.println("==> DEBUG: Number of transitions : " + numOfTransitions);
180       fileWriter.println();
181       fileWriter.close();
182     }
183   }
184
185   @Override
186   public void choiceGeneratorRegistered(VM vm, ChoiceGenerator<?> nextCG, ThreadInfo currentThread, Instruction executedInstruction) {
187     if (stateReductionMode) {
188       // Initialize with necessary information from the CG
189       if (nextCG instanceof IntChoiceFromSet) {
190         IntChoiceFromSet icsCG = (IntChoiceFromSet) nextCG;
191         // Tell JPF that we are performing DPOR
192         icsCG.setDpor();
193         if (!isEndOfExecution) {
194           // Check if CG has been initialized, otherwise initialize it
195           Integer[] cgChoices = icsCG.getAllChoices();
196           // Record the events (from choices)
197           if (choices == null) {
198             choices = cgChoices;
199             // Make a copy of choices as reference
200             refChoices = copyChoices(choices);
201             // Record the max event choice (the last element of the choice array)
202             maxEventChoice = choices[choices.length - 1];
203           }
204           icsCG.setNewValues(choices);
205           icsCG.reset();
206           // Use a modulo since choiceCounter is going to keep increasing
207           int choiceIndex = choiceCounter % choices.length;
208           icsCG.advance(choices[choiceIndex]);
209         } else {
210           // Set done all CGs while transitioning to a new execution
211           icsCG.setDone();
212         }
213       }
214     }
215   }
216
217   @Override
218   public void choiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
219     if (stateReductionMode) {
220       // Check the boolean CG and if it is flipped, we are resetting the analysis
221       if (currentCG instanceof BooleanChoiceGenerator) {
222         if (!isBooleanCGFlipped) {
223           isBooleanCGFlipped = true;
224         } else {
225           // Allocate new objects for data structure when the boolean is flipped from "false" to "true"
226           initializeStatesVariables();
227         }
228       }
229       // Check every choice generated and ensure fair scheduling!
230       if (currentCG instanceof IntChoiceFromSet) {
231         IntChoiceFromSet icsCG = (IntChoiceFromSet) currentCG;
232         // If this is a new CG then we need to update data structures
233         resetStatesForNewExecution(icsCG, vm);
234         // If we don't see a fair scheduling of events/choices then we have to enforce it
235         ensureFairSchedulingAndSetupTransition(icsCG, vm);
236         // Update backtrack set of an executed event (transition): one transition before this one
237         updateBacktrackSet(currentExecution, choiceCounter - 1);
238         // Explore the next backtrack point:
239         // 1) if we have seen this state or this state contains cycles that involve all events, and
240         // 2) after the current CG is advanced at least once
241         if (terminateCurrentExecution() && choiceCounter > 0) {
242           exploreNextBacktrackPoints(vm, icsCG);
243         } else {
244           numOfTransitions++;
245         }
246         // Map state to event
247         mapStateToEvent(icsCG.getNextChoice());
248         justVisitedStates.clear();
249         choiceCounter++;
250       }
251     } else {
252       numOfTransitions++;
253     }
254   }
255
256   @Override
257   public void instructionExecuted(VM vm, ThreadInfo ti, Instruction nextInsn, Instruction executedInsn) {
258     if (stateReductionMode) {
259       if (!isEndOfExecution) {
260         // Has to be initialized and a integer CG
261         ChoiceGenerator<?> cg = vm.getChoiceGenerator();
262         if (cg instanceof IntChoiceFromSet || cg instanceof IntIntervalGenerator) {
263           int currentChoice = choiceCounter - 1;  // Accumulative choice w.r.t the current trace
264           if (currentChoice < 0) { // If choice is -1 then skip
265             return;
266           }
267           currentChoice = checkAndAdjustChoice(currentChoice, vm);
268           // Record accesses from executed instructions
269           if (executedInsn instanceof JVMFieldInstruction) {
270             // We don't care about libraries
271             if (!isFieldExcluded(executedInsn)) {
272               analyzeReadWriteAccesses(executedInsn, currentChoice);
273             }
274           } else if (executedInsn instanceof INVOKEINTERFACE) {
275             // Handle the read/write accesses that occur through iterators
276             analyzeReadWriteAccesses(executedInsn, ti, currentChoice);
277           }
278         }
279       }
280     }
281   }
282
283
284   // == HELPERS
285
286   // -- INNER CLASSES
287
288   // This class compactly stores backtrack execution:
289   // 1) backtrack choice list, and
290   // 2) first backtrack point (linking with predecessor execution)
291   private class BacktrackExecution {
292     private Integer[] choiceList;
293     private TransitionEvent firstTransition;
294
295     public BacktrackExecution(Integer[] choList, TransitionEvent fTransition) {
296       choiceList = choList;
297       firstTransition = fTransition;
298     }
299
300     public Integer[] getChoiceList() {
301       return choiceList;
302     }
303
304     public TransitionEvent getFirstTransition() {
305       return firstTransition;
306     }
307   }
308
309   // This class stores a representation of an execution
310   // TODO: We can modify this class to implement some optimization (e.g., clock-vector)
311   // TODO: We basically need to keep track of:
312   // TODO:    (1) last read/write access to each memory location
313   // TODO:    (2) last state with two or more incoming events/transitions
314   private class Execution {
315     private HashMap<IntChoiceFromSet, Integer> cgToChoiceMap;   // Map between CG to choice numbers for O(1) access
316     private ArrayList<TransitionEvent> executionTrace;          // The BacktrackPoint objects of this execution
317     private boolean isNew;                                      // Track if this is the first time it is accessed
318     private HashMap<Integer, ReadWriteSet> readWriteFieldsMap;  // Record fields that are accessed
319
320     public Execution() {
321       cgToChoiceMap = new HashMap<>();
322       executionTrace = new ArrayList<>();
323       isNew = true;
324       readWriteFieldsMap = new HashMap<>();
325     }
326
327     public void addTransition(TransitionEvent newBacktrackPoint) {
328       executionTrace.add(newBacktrackPoint);
329     }
330
331     public void clearCGToChoiceMap() {
332       cgToChoiceMap = null;
333     }
334
335     public int getChoiceFromCG(IntChoiceFromSet icsCG) {
336       return cgToChoiceMap.get(icsCG);
337     }
338
339     public ArrayList<TransitionEvent> getExecutionTrace() {
340       return executionTrace;
341     }
342
343     public TransitionEvent getFirstTransition() {
344       return executionTrace.get(0);
345     }
346
347     public TransitionEvent getLastTransition() {
348       return executionTrace.get(executionTrace.size() - 1);
349     }
350
351     public HashMap<Integer, ReadWriteSet> getReadWriteFieldsMap() {
352       return readWriteFieldsMap;
353     }
354
355     public boolean isNew() {
356       if (isNew) {
357         // Right after this is accessed, it is no longer new
358         isNew = false;
359         return true;
360       }
361       return false;
362     }
363
364     public void mapCGToChoice(IntChoiceFromSet icsCG, int choice) {
365       cgToChoiceMap.put(icsCG, choice);
366     }
367   }
368
369   // This class compactly stores a predecessor
370   // 1) a predecessor execution
371   // 2) the predecessor choice in that predecessor execution
372   private class Predecessor {
373     private int choice;           // Predecessor choice
374     private Execution execution;  // Predecessor execution
375
376     public Predecessor(int predChoice, Execution predExec) {
377       choice = predChoice;
378       execution = predExec;
379     }
380
381     public int getChoice() {
382       return choice;
383     }
384
385     public Execution getExecution() {
386       return execution;
387     }
388   }
389
390   // This class represents a R-Graph (in the paper it is a state transition graph R)
391   // This implementation stores reachable transitions from and connects with past executions
392   private class RGraph {
393     private int hiStateId;                                     // Maximum state Id
394     private HashMap<Integer, HashSet<TransitionEvent>> graph;  // Reachable transitions from past executions
395     // TODO: THIS IS THE ACCESS SUMMARY
396     private HashMap<Integer, HashMap<Integer, SummaryNode>> graphSummary;
397
398     public RGraph() {
399       hiStateId = 0;
400       graph = new HashMap<>();
401       graphSummary = new HashMap<>();
402     }
403
404     public void addReachableTransition(int stateId, TransitionEvent transition) {
405       // Record transition into graph
406       HashSet<TransitionEvent> transitionSet;
407       if (graph.containsKey(stateId)) {
408         transitionSet = graph.get(stateId);
409       } else {
410         transitionSet = new HashSet<>();
411         graph.put(stateId, transitionSet);
412       }
413       // Insert into the set if it does not contain it yet
414       if (!transitionSet.contains(transition)) {
415         transitionSet.add(transition);
416       }
417       // Update highest state ID
418       if (hiStateId < stateId) {
419         hiStateId = stateId;
420       }
421     }
422
423     public HashSet<TransitionEvent> getReachableTransitionsAtState(int stateId) {
424       if (!graph.containsKey(stateId)) {
425         // This is a loop from a transition to itself, so just return the current transition
426         HashSet<TransitionEvent> transitionSet = new HashSet<>();
427         transitionSet.add(currentExecution.getLastTransition());
428         return transitionSet;
429       }
430       return graph.get(stateId);
431     }
432
433     public HashSet<TransitionEvent> getReachableTransitions(int stateId) {
434       HashSet<TransitionEvent> reachableTransitions = new HashSet<>();
435       // All transitions from states higher than the given state ID (until the highest state ID) are reachable
436       for(int stId = stateId; stId <= hiStateId; stId++) {
437         // We might encounter state IDs from the first round of Boolean CG
438         // The second round of Boolean CG should consider these new states
439         if (graph.containsKey(stId)) {
440           reachableTransitions.addAll(graph.get(stId));
441         }
442       }
443       return reachableTransitions;
444     }
445
446     public HashMap<Integer, SummaryNode> getReachableTransitionsSummary(int stateId) {
447       // Just return an empty map if the state ID is not recorded yet
448       // This means that there is no reachable transition from this state
449       if (!graphSummary.containsKey(stateId)) {
450         return new HashMap<>();
451       }
452       return graphSummary.get(stateId);
453     }
454
455     private ReadWriteSet performUnion(ReadWriteSet recordedRWSet, ReadWriteSet rwSet) {
456       // Combine the same write accesses and record in the recordedRWSet
457       HashMap<String, Integer> recordedWriteMap = recordedRWSet.getWriteMap();
458       HashMap<String, Integer> writeMap = rwSet.getWriteMap();
459       for(Map.Entry<String, Integer> entry : recordedWriteMap.entrySet()) {
460         String writeField = entry.getKey();
461         // Remove the entry from rwSet if both field and object ID are the same
462         if (writeMap.containsKey(writeField) &&
463                 (writeMap.get(writeField) == recordedWriteMap.get(writeField))) {
464           writeMap.remove(writeField);
465         }
466       }
467       // Then add everything into the recorded map because these will be traversed
468       recordedWriteMap.putAll(writeMap);
469       // Combine the same read accesses and record in the recordedRWSet
470       HashMap<String, Integer> recordedReadMap = recordedRWSet.getReadMap();
471       HashMap<String, Integer> readMap = rwSet.getReadMap();
472       for(Map.Entry<String, Integer> entry : recordedReadMap.entrySet()) {
473         String readField = entry.getKey();
474         // Remove the entry from rwSet if both field and object ID are the same
475         if (readMap.containsKey(readField) &&
476                 (readMap.get(readField) == recordedReadMap.get(readField))) {
477           readMap.remove(readField);
478         }
479       }
480       // Then add everything into the recorded map because these will be traversed
481       recordedReadMap.putAll(readMap);
482
483       return rwSet;
484     }
485
486     public ReadWriteSet recordTransitionSummary(int stateId, TransitionEvent transition, ReadWriteSet rwSet) {
487       // Record transition into graphSummary
488       // TransitionMap maps event (choice) number to a R/W set
489       HashMap<Integer, SummaryNode> transitionSummary;
490       if (graphSummary.containsKey(stateId)) {
491         transitionSummary = graphSummary.get(stateId);
492       } else {
493         transitionSummary = new HashMap<>();
494         graphSummary.put(stateId, transitionSummary);
495       }
496       int choice = transition.getChoice();
497       SummaryNode summaryNode;
498       // Insert transition into the map if we haven't had this event number recorded
499       if (!transitionSummary.containsKey(choice)) {
500         summaryNode = new SummaryNode(transition, rwSet.getCopy());
501         transitionSummary.put(choice, summaryNode);
502       } else {
503         summaryNode = transitionSummary.get(choice);
504         // Perform union and subtraction between the recorded and the given R/W sets
505         rwSet = performUnion(summaryNode.getReadWriteSet(), rwSet);
506       }
507       return rwSet;
508     }
509   }
510
511   // This class compactly stores Read and Write field sets
512   // We store the field name and its object ID
513   // Sharing the same field means the same field name and object ID
514   private class ReadWriteSet {
515     private HashMap<String, Integer> readMap;
516     private HashMap<String, Integer> writeMap;
517
518     public ReadWriteSet() {
519       readMap = new HashMap<>();
520       writeMap = new HashMap<>();
521     }
522
523     public void addReadField(String field, int objectId) {
524       readMap.put(field, objectId);
525     }
526
527     public void addWriteField(String field, int objectId) {
528       writeMap.put(field, objectId);
529     }
530
531     public void removeReadField(String field) {
532       readMap.remove(field);
533     }
534
535     public void removeWriteField(String field) {
536       writeMap.remove(field);
537     }
538
539     public boolean isEmpty() {
540       return readMap.isEmpty() && writeMap.isEmpty();
541     }
542
543     public ReadWriteSet getCopy() {
544       ReadWriteSet copyRWSet = new ReadWriteSet();
545       // Copy the maps in the set into the new object copy
546       copyRWSet.setReadMap(new HashMap<>(this.getReadMap()));
547       copyRWSet.setWriteMap(new HashMap<>(this.getWriteMap()));
548       return copyRWSet;
549     }
550
551     public Set<String> getReadSet() {
552       return readMap.keySet();
553     }
554
555     public Set<String> getWriteSet() {
556       return writeMap.keySet();
557     }
558
559     public boolean readFieldExists(String field) {
560       return readMap.containsKey(field);
561     }
562
563     public boolean writeFieldExists(String field) {
564       return writeMap.containsKey(field);
565     }
566
567     public int readFieldObjectId(String field) {
568       return readMap.get(field);
569     }
570
571     public int writeFieldObjectId(String field) {
572       return writeMap.get(field);
573     }
574
575     private HashMap<String, Integer> getReadMap() {
576       return readMap;
577     }
578
579     private HashMap<String, Integer> getWriteMap() {
580       return writeMap;
581     }
582
583     private void setReadMap(HashMap<String, Integer> rMap) {
584       readMap = rMap;
585     }
586
587     private void setWriteMap(HashMap<String, Integer> wMap) {
588       writeMap = wMap;
589     }
590   }
591
592   // This class provides a data structure to store TransitionEvent and ReadWriteSet for a summary
593   private class SummaryNode {
594     private TransitionEvent transitionEvent;
595     private ReadWriteSet readWriteSet;
596
597     public SummaryNode(TransitionEvent transEvent, ReadWriteSet rwSet) {
598       transitionEvent = transEvent;
599       readWriteSet = rwSet;
600     }
601
602     public TransitionEvent getTransitionEvent() {
603       return transitionEvent;
604     }
605
606     public ReadWriteSet getReadWriteSet() {
607       return readWriteSet;
608     }
609   }
610
611   // This class compactly stores transitions:
612   // 1) CG,
613   // 2) state ID,
614   // 3) choice,
615   // 4) predecessors (for backward DFS).
616   private class TransitionEvent {
617     private int choice;                        // Choice chosen at this transition
618     private int choiceCounter;                 // Choice counter at this transition
619     private Execution execution;               // The execution where this transition belongs
620     private HashSet<Predecessor> predecessors; // Maps incoming events/transitions (execution and choice)
621     private int stateId;                       // State at this transition
622     private IntChoiceFromSet transitionCG;     // CG at this transition
623
624     public TransitionEvent() {
625       choice = 0;
626       choiceCounter = 0;
627       execution = null;
628       predecessors = new HashSet<>();
629       stateId = 0;
630       transitionCG = null;
631     }
632
633     public int getChoice() {
634       return choice;
635     }
636
637     public int getChoiceCounter() {
638       return choiceCounter;
639     }
640
641     public Execution getExecution() {
642       return execution;
643     }
644
645     public HashSet<Predecessor> getPredecessors() {
646       return predecessors;
647     }
648
649     public int getStateId() {
650       return stateId;
651     }
652
653     public IntChoiceFromSet getTransitionCG() { return transitionCG; }
654
655     public void recordPredecessor(Execution execution, int choice) {
656       predecessors.add(new Predecessor(choice, execution));
657     }
658
659     public void setChoice(int cho) {
660       choice = cho;
661     }
662
663     public void setChoiceCounter(int choCounter) {
664       choiceCounter = choCounter;
665     }
666
667     public void setExecution(Execution exec) {
668       execution = exec;
669     }
670
671     public void setPredecessors(HashSet<Predecessor> preds) {
672       predecessors = new HashSet<>(preds);
673     }
674
675     public void setStateId(int stId) {
676       stateId = stId;
677     }
678
679     public void setTransitionCG(IntChoiceFromSet cg) {
680       transitionCG = cg;
681     }
682   }
683
684   // -- CONSTANTS
685   private final static String DO_CALL_METHOD = "doCall";
686   // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
687   private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
688   private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
689           // Groovy library created fields
690           {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
691           // Infrastructure
692           "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
693           "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
694   private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
695           // Java and Groovy libraries
696           { "java", "org", "sun", "com", "gov", "groovy"};
697   private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
698   private final static String GET_PROPERTY_METHOD =
699           "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
700   private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
701   private final static String JAVA_INTEGER = "int";
702   private final static String JAVA_STRING_LIB = "java.lang.String";
703
704   // -- FUNCTIONS
705   private Integer[] copyChoices(Integer[] choicesToCopy) {
706
707     Integer[] copyOfChoices = new Integer[choicesToCopy.length];
708     System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
709     return copyOfChoices;
710   }
711
712   private void ensureFairSchedulingAndSetupTransition(IntChoiceFromSet icsCG, VM vm) {
713     // Check the next choice and if the value is not the same as the expected then force the expected value
714     int choiceIndex = choiceCounter % refChoices.length;
715     int nextChoice = icsCG.getNextChoice();
716     if (refChoices[choiceIndex] != nextChoice) {
717       int expectedChoice = refChoices[choiceIndex];
718       int currCGIndex = icsCG.getNextChoiceIndex();
719       if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
720         icsCG.setChoice(currCGIndex, expectedChoice);
721       }
722     }
723     // Get state ID and associate it with this transition
724     int stateId = vm.getStateId();
725     TransitionEvent transition = setupTransition(icsCG, stateId, choiceIndex);
726     // Add new transition to the current execution and map it in R-Graph
727     for (Integer stId : justVisitedStates) {  // Map this transition to all the previously passed states
728       rGraph.addReachableTransition(stId, transition);
729     }
730     currentExecution.mapCGToChoice(icsCG, choiceCounter);
731     // Store restorable state object for this state (always store the latest)
732     if (!restorableStateMap.containsKey(stateId)) {
733       RestorableVMState restorableState = vm.getRestorableState();
734       restorableStateMap.put(stateId, restorableState);
735     }
736   }
737
738   private TransitionEvent setupTransition(IntChoiceFromSet icsCG, int stateId, int choiceIndex) {
739     // Get a new transition
740     TransitionEvent transition;
741     if (currentExecution.isNew()) {
742       // We need to handle the first transition differently because this has a predecessor execution
743       transition = currentExecution.getFirstTransition();
744     } else {
745       transition = new TransitionEvent();
746       currentExecution.addTransition(transition);
747       transition.recordPredecessor(currentExecution, choiceCounter - 1);
748     }
749     transition.setExecution(currentExecution);
750     transition.setTransitionCG(icsCG);
751     transition.setStateId(stateId);
752     transition.setChoice(refChoices[choiceIndex]);
753     transition.setChoiceCounter(choiceCounter);
754
755     return transition;
756   }
757
758   // --- Functions related to cycle detection and reachability graph
759
760   // Detect cycles in the current execution/trace
761   // We terminate the execution iff:
762   // (1) the state has been visited in the current execution
763   // (2) the state has one or more cycles that involve all the events
764   // With simple approach we only need to check for a re-visited state.
765   // Basically, we have to check that we have executed all events between two occurrences of such state.
766   private boolean completeFullCycle(int stId) {
767     // False if the state ID hasn't been recorded
768     if (!stateToEventMap.containsKey(stId)) {
769       return false;
770     }
771     HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
772     // Check if this set contains all the event choices
773     // If not then this is not the terminating condition
774     for(int i=0; i<=maxEventChoice; i++) {
775       if (!visitedEvents.contains(i)) {
776         return false;
777       }
778     }
779     return true;
780   }
781
782   private void initializeStatesVariables() {
783     // DPOR-related
784     choices = null;
785     refChoices = null;
786     choiceCounter = 0;
787     maxEventChoice = 0;
788     // Cycle tracking
789     currVisitedStates = new HashSet<>();
790     justVisitedStates = new HashSet<>();
791     prevVisitedStates = new HashSet<>();
792     stateToEventMap = new HashMap<>();
793     // Backtracking
794     backtrackMap = new HashMap<>();
795     backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
796     currentExecution = new Execution();
797     currentExecution.addTransition(new TransitionEvent()); // Always start with 1 backtrack point
798     doneBacktrackMap = new HashMap<>();
799     rGraph = new RGraph();
800     // Booleans
801     isEndOfExecution = false;
802   }
803
804   private void mapStateToEvent(int nextChoiceValue) {
805     // Update all states with this event/choice
806     // This means that all past states now see this transition
807     Set<Integer> stateSet = stateToEventMap.keySet();
808     for(Integer stateId : stateSet) {
809       HashSet<Integer> eventSet = stateToEventMap.get(stateId);
810       eventSet.add(nextChoiceValue);
811     }
812   }
813
814   private boolean terminateCurrentExecution() {
815     // We need to check all the states that have just been visited
816     // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
817     for(Integer stateId : justVisitedStates) {
818       if (prevVisitedStates.contains(stateId) || completeFullCycle(stateId)) {
819         return true;
820       }
821     }
822     return false;
823   }
824
825   private void updateStateInfo(Search search) {
826     // Update the state variables
827     int stateId = search.getStateId();
828     // Insert state ID into the map if it is new
829     if (!stateToEventMap.containsKey(stateId)) {
830       HashSet<Integer> eventSet = new HashSet<>();
831       stateToEventMap.put(stateId, eventSet);
832     }
833     analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);
834     justVisitedStates.add(stateId);
835     if (!prevVisitedStates.contains(stateId)) {
836       // It is a currently visited states if the state has not been seen in previous executions
837       currVisitedStates.add(stateId);
838     }
839   }
840
841   // --- Functions related to Read/Write access analysis on shared fields
842
843   private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList, TransitionEvent conflictTransition) {
844     // Insert backtrack point to the right state ID
845     LinkedList<BacktrackExecution> backtrackExecList;
846     if (backtrackMap.containsKey(stateId)) {
847       backtrackExecList = backtrackMap.get(stateId);
848     } else {
849       backtrackExecList = new LinkedList<>();
850       backtrackMap.put(stateId, backtrackExecList);
851     }
852     // Add the new backtrack execution object
853     TransitionEvent backtrackTransition = new TransitionEvent();
854     backtrackTransition.setPredecessors(conflictTransition.getPredecessors());
855     backtrackExecList.addFirst(new BacktrackExecution(newChoiceList, backtrackTransition));
856     // Add to priority queue
857     if (!backtrackStateQ.contains(stateId)) {
858       backtrackStateQ.add(stateId);
859     }
860   }
861
862   // Analyze Read/Write accesses that are directly invoked on fields
863   private void analyzeReadWriteAccesses(Instruction executedInsn, int currentChoice) {
864     // Get the field info
865     FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
866     // Analyze only after being initialized
867     String fieldClass = fieldInfo.getFullName();
868     // Do the analysis to get Read and Write accesses to fields
869     ReadWriteSet rwSet = getReadWriteSet(currentChoice);
870     int objectId = fieldInfo.getClassInfo().getClassObjectRef();
871     // Record the field in the map
872     if (executedInsn instanceof WriteInstruction) {
873       // We first check the non-relevant fields set
874       if (!nonRelevantFields.contains(fieldInfo)) {
875         // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
876         for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
877           if (fieldClass.startsWith(str)) {
878             nonRelevantFields.add(fieldInfo);
879             return;
880           }
881         }
882       } else {
883         // If we have this field in the non-relevant fields set then we return right away
884         return;
885       }
886       rwSet.addWriteField(fieldClass, objectId);
887     } else if (executedInsn instanceof ReadInstruction) {
888       rwSet.addReadField(fieldClass, objectId);
889     }
890   }
891
892   // Analyze Read accesses that are indirect (performed through iterators)
893   // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
894   private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
895     // Get method name
896     INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
897     if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
898             insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
899       // Extract info from the stack frame
900       StackFrame frame = ti.getTopFrame();
901       int[] frameSlots = frame.getSlots();
902       // Get the Groovy callsite library at index 0
903       ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
904       if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
905         return;
906       }
907       // Get the iterated object whose property is accessed
908       ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
909       if (eiAccessObj == null) {
910         return;
911       }
912       // We exclude library classes (they start with java, org, etc.) and some more
913       ClassInfo classInfo = eiAccessObj.getClassInfo();
914       String objClassName = classInfo.getName();
915       // Check if this class info is part of the non-relevant classes set already
916       if (!nonRelevantClasses.contains(classInfo)) {
917         if (excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName) ||
918                 excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName)) {
919           nonRelevantClasses.add(classInfo);
920           return;
921         }
922       } else {
923         // If it is part of the non-relevant classes set then return immediately
924         return;
925       }
926       // Extract fields from this object and put them into the read write
927       int numOfFields = eiAccessObj.getNumberOfFields();
928       for(int i=0; i<numOfFields; i++) {
929         FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
930         if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
931           String fieldClass = fieldInfo.getFullName();
932           ReadWriteSet rwSet = getReadWriteSet(currentChoice);
933           int objectId = fieldInfo.getClassInfo().getClassObjectRef();
934           // Record the field in the map
935           rwSet.addReadField(fieldClass, objectId);
936         }
937       }
938     }
939   }
940
941   private int checkAndAdjustChoice(int currentChoice, VM vm) {
942     // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
943     // for certain method calls in the infrastructure, e.g., eventSince()
944     ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
945     // This is the main event CG
946     if (currentCG instanceof IntIntervalGenerator) {
947       // This is the interval CG used in device handlers
948       ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
949       // Iterate until we find the IntChoiceFromSet CG
950       while (!(parentCG instanceof IntChoiceFromSet)) {
951         parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
952       }
953       // Find the choice related to the IntIntervalGenerator CG from the map
954       currentChoice = currentExecution.getChoiceFromCG((IntChoiceFromSet) parentCG);
955     }
956     return currentChoice;
957   }
958
959   private void createBacktrackingPoint(Execution execution, int currentChoice,
960                                        Execution conflictExecution, int conflictChoice) {
961     // Create a new list of choices for backtrack based on the current choice and conflicting event number
962     // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
963     // for the original set {0, 1, 2, 3}
964     
965     // execution/currentChoice represent the event/transaction that will be put into the backtracking set of
966     // conflictExecution/conflictChoice
967     Integer[] newChoiceList = new Integer[refChoices.length];
968     ArrayList<TransitionEvent> currentTrace = execution.getExecutionTrace();
969     ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
970     int currChoice = currentTrace.get(currentChoice).getChoice();
971     int stateId = conflictTrace.get(conflictChoice).getStateId();
972     // Check if this trace has been done from this state
973     if (isTraceAlreadyConstructed(currChoice, stateId)) {
974       return;
975     }
976     // Put the conflicting event numbers first and reverse the order
977     newChoiceList[0] = currChoice;
978     // Put the rest of the event numbers into the array starting from the minimum to the upper bound
979     for (int i = 0, j = 1; i < refChoices.length; i++) {
980       if (refChoices[i] != newChoiceList[0]) {
981         newChoiceList[j] = refChoices[i];
982         j++;
983       }
984     }
985     // Predecessor of the new backtrack point is the same as the conflict point's
986     addNewBacktrackPoint(stateId, newChoiceList, conflictTrace.get(conflictChoice));
987   }
988
989   private boolean excludeThisForItContains(String[] excludedStrings, String className) {
990     for (String excludedField : excludedStrings) {
991       if (className.contains(excludedField)) {
992         return true;
993       }
994     }
995     return false;
996   }
997
998   private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
999     for (String excludedField : excludedStrings) {
1000       if (className.endsWith(excludedField)) {
1001         return true;
1002       }
1003     }
1004     return false;
1005   }
1006
1007   private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
1008     for (String excludedField : excludedStrings) {
1009       if (className.startsWith(excludedField)) {
1010         return true;
1011       }
1012     }
1013     return false;
1014   }
1015
1016   private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
1017                 // Check if we are reaching the end of our execution: no more backtracking points to explore
1018                 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
1019                 if (!backtrackStateQ.isEmpty()) {
1020                         // Set done all the other backtrack points
1021                         for (TransitionEvent backtrackTransition : currentExecution.getExecutionTrace()) {
1022         backtrackTransition.getTransitionCG().setDone();
1023                         }
1024                         // Reset the next backtrack point with the latest state
1025                         int hiStateId = backtrackStateQ.peek();
1026                         // Restore the state first if necessary
1027                         if (vm.getStateId() != hiStateId) {
1028                                 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
1029                                 vm.restoreState(restorableState);
1030                         }
1031                         // Set the backtrack CG
1032                         IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
1033                         setBacktrackCG(hiStateId, backtrackCG);
1034                 } else {
1035                         // Set done this last CG (we save a few rounds)
1036                         icsCG.setDone();
1037                 }
1038                 // Save all the visited states when starting a new execution of trace
1039                 prevVisitedStates.addAll(currVisitedStates);
1040                 // This marks a transitional period to the new CG
1041                 isEndOfExecution = true;
1042   }
1043
1044   private boolean isConflictFound(Execution execution, int reachableChoice, Execution conflictExecution, int conflictChoice,
1045                                   ReadWriteSet currRWSet) {
1046     // conflictExecution/conflictChoice represent a predecessor event/transaction that can potentially have a conflict
1047     ArrayList<TransitionEvent> executionTrace = execution.getExecutionTrace();
1048     ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
1049     HashMap<Integer, ReadWriteSet> confRWFieldsMap = conflictExecution.getReadWriteFieldsMap();
1050     // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
1051     if (!confRWFieldsMap.containsKey(conflictChoice) ||
1052             executionTrace.get(reachableChoice).getChoice() == conflictTrace.get(conflictChoice).getChoice()) {
1053       return false;
1054     }
1055     // R/W set of choice/event that may have a potential conflict
1056     ReadWriteSet confRWSet = confRWFieldsMap.get(conflictChoice);
1057     // Check for conflicts with Read and Write fields for Write instructions
1058     Set<String> currWriteSet = currRWSet.getWriteSet();
1059     for(String writeField : currWriteSet) {
1060       int currObjId = currRWSet.writeFieldObjectId(writeField);
1061       if ((confRWSet.readFieldExists(writeField) && confRWSet.readFieldObjectId(writeField) == currObjId) ||
1062           (confRWSet.writeFieldExists(writeField) && confRWSet.writeFieldObjectId(writeField) == currObjId)) {
1063         // Remove this from the write set as we are tracking per memory location
1064         currRWSet.removeWriteField(writeField);
1065         return true;
1066       }
1067     }
1068     // Check for conflicts with Write fields for Read instructions
1069     Set<String> currReadSet = currRWSet.getReadSet();
1070     for(String readField : currReadSet) {
1071       int currObjId = currRWSet.readFieldObjectId(readField);
1072       if (confRWSet.writeFieldExists(readField) && confRWSet.writeFieldObjectId(readField) == currObjId) {
1073         // Remove this from the read set as we are tracking per memory location
1074         currRWSet.removeReadField(readField);
1075         return true;
1076       }
1077     }
1078     // Return false if no conflict is found
1079     return false;
1080   }
1081
1082   private ReadWriteSet getReadWriteSet(int currentChoice) {
1083     // Do the analysis to get Read and Write accesses to fields
1084     ReadWriteSet rwSet;
1085     // We already have an entry
1086     HashMap<Integer, ReadWriteSet> currReadWriteFieldsMap = currentExecution.getReadWriteFieldsMap();
1087     if (currReadWriteFieldsMap.containsKey(currentChoice)) {
1088       rwSet = currReadWriteFieldsMap.get(currentChoice);
1089     } else { // We need to create a new entry
1090       rwSet = new ReadWriteSet();
1091       currReadWriteFieldsMap.put(currentChoice, rwSet);
1092     }
1093     return rwSet;
1094   }
1095
1096   private boolean isFieldExcluded(Instruction executedInsn) {
1097     // Get the field info
1098     FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
1099     // Check if the non-relevant fields set already has it
1100     if (nonRelevantFields.contains(fieldInfo)) {
1101       return true;
1102     }
1103     // Check if the relevant fields set already has it
1104     if (relevantFields.contains(fieldInfo)) {
1105       return false;
1106     }
1107     // Analyze only after being initialized
1108     String field = fieldInfo.getFullName();
1109     // Check against "starts-with", "ends-with", and "contains" list
1110     if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
1111             excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
1112             excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
1113       nonRelevantFields.add(fieldInfo);
1114       return true;
1115     }
1116     relevantFields.add(fieldInfo);
1117     return false;
1118   }
1119
1120   // Check if this trace is already constructed
1121   private boolean isTraceAlreadyConstructed(int firstChoice, int stateId) {
1122     // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
1123     // Check if the trace has been constructed as a backtrack point for this state
1124     // TODO: THIS IS AN OPTIMIZATION!
1125     HashSet<Integer> choiceSet;
1126     if (doneBacktrackMap.containsKey(stateId)) {
1127       choiceSet = doneBacktrackMap.get(stateId);
1128       if (choiceSet.contains(firstChoice)) {
1129         return true;
1130       }
1131     } else {
1132       choiceSet = new HashSet<>();
1133       doneBacktrackMap.put(stateId, choiceSet);
1134     }
1135     choiceSet.add(firstChoice);
1136
1137     return false;
1138   }
1139
1140   // Reset data structure for each new execution
1141   private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
1142     if (choices == null || choices != icsCG.getAllChoices()) {
1143       // Reset state variables
1144       choiceCounter = 0;
1145       choices = icsCG.getAllChoices();
1146       refChoices = copyChoices(choices);
1147       // Clear data structures
1148       currVisitedStates = new HashSet<>();
1149       stateToEventMap = new HashMap<>();
1150       isEndOfExecution = false;
1151     }
1152   }
1153
1154   // Set a backtrack point for a particular state
1155   private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
1156     // Set a backtrack CG based on a state ID
1157     LinkedList<BacktrackExecution> backtrackExecutions = backtrackMap.get(stateId);
1158     BacktrackExecution backtrackExecution = backtrackExecutions.removeLast();
1159     backtrackCG.setNewValues(backtrackExecution.getChoiceList());  // Get the last from the queue
1160     backtrackCG.setStateId(stateId);
1161     backtrackCG.reset();
1162     // Update current execution with this new execution
1163     Execution newExecution = new Execution();
1164     TransitionEvent firstTransition = backtrackExecution.getFirstTransition();
1165     newExecution.addTransition(firstTransition);
1166     // Try to free some memory since this map is only used for the current execution
1167     currentExecution.clearCGToChoiceMap();
1168     currentExecution = newExecution;
1169     // Remove from the queue if we don't have more backtrack points for that state
1170     if (backtrackExecutions.isEmpty()) {
1171       backtrackMap.remove(stateId);
1172       backtrackStateQ.remove(stateId);
1173     }
1174   }
1175
1176   // Update backtrack sets
1177   // 1) recursively, and
1178   // 2) track accesses per memory location (per shared variable/field)
1179   private void updateBacktrackSet(Execution execution, int currentChoice) {
1180     // Copy ReadWriteSet object
1181     HashMap<Integer, ReadWriteSet> currRWFieldsMap = execution.getReadWriteFieldsMap();
1182     ReadWriteSet currRWSet = currRWFieldsMap.get(currentChoice);
1183     if (currRWSet == null) {
1184       return;
1185     }
1186     currRWSet = currRWSet.getCopy();
1187     // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1188     HashSet<TransitionEvent> visited = new HashSet<>();
1189     // Update backtrack set recursively
1190     // TODO: The following is the call to the original version of the method
1191 //    updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, currRWSet, visited);
1192     // TODO: The following is the call to the version of the method with pushing up happens-before transitions
1193     updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, currRWSet, visited);
1194   }
1195
1196 //  TODO: This is the original version of the recursive method
1197 //  private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1198 //                                           Execution conflictExecution, int conflictChoice,
1199 //                                           ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1200 //    // Halt when we have found the first read/write conflicts for all memory locations
1201 //    if (currRWSet.isEmpty()) {
1202 //      return;
1203 //    }
1204 //    TransitionEvent confTrans = conflictExecution.getExecutionTrace().get(conflictChoice);
1205 //    // Halt when we have visited this transition (in a cycle)
1206 //    if (visited.contains(confTrans)) {
1207 //      return;
1208 //    }
1209 //    visited.add(confTrans);
1210 //    // Explore all predecessors
1211 //    for (Predecessor predecessor : confTrans.getPredecessors()) {
1212 //      // Get the predecessor (previous conflict choice)
1213 //      conflictChoice = predecessor.getChoice();
1214 //      conflictExecution = predecessor.getExecution();
1215 //      // Check if a conflict is found
1216 //      if (isConflictFound(execution, currentChoice, conflictExecution, conflictChoice, currRWSet)) {
1217 //        createBacktrackingPoint(execution, currentChoice, conflictExecution, conflictChoice);
1218 //      }
1219 //      // Continue performing DFS if conflict is not found
1220 //      updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice, currRWSet, visited);
1221 //    }
1222 //  }
1223
1224   // TODO: This is the version of the method with pushing up happens-before transitions
1225   private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1226                                            Execution conflictExecution, int conflictChoice,
1227                                            ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1228     // TODO: THIS IS THE ACCESS SUMMARY
1229     TransitionEvent confTrans = conflictExecution.getExecutionTrace().get(conflictChoice);
1230     // Record this transition into rGraph summary
1231     currRWSet = rGraph.recordTransitionSummary(confTrans.getStateId(), confTrans, currRWSet);
1232     // Halt when we have found the first read/write conflicts for all memory locations
1233     if (currRWSet.isEmpty()) {
1234       return;
1235     }
1236     TransitionEvent currTrans = execution.getExecutionTrace().get(currentChoice);
1237     if (visited.contains(currTrans)) {
1238       return;
1239     }
1240     visited.add(currTrans);
1241     // Explore all predecessors
1242     for (Predecessor predecessor : currTrans.getPredecessors()) {
1243       // Get the predecessor (previous conflict choice)
1244       int predecessorChoice = predecessor.getChoice();
1245       Execution predecessorExecution = predecessor.getExecution();
1246       // Push up one happens-before transition
1247       int newConflictChoice = conflictChoice;
1248       Execution newConflictExecution = conflictExecution;
1249       // Check if a conflict is found
1250       if (isConflictFound(conflictExecution, conflictChoice, predecessorExecution, predecessorChoice, currRWSet)) {
1251         createBacktrackingPoint(conflictExecution, conflictChoice, predecessorExecution, predecessorChoice);
1252         newConflictChoice = conflictChoice;
1253         newConflictExecution = conflictExecution;
1254       }
1255       // Continue performing DFS if conflict is not found
1256       updateBacktrackSetRecursive(predecessorExecution, predecessorChoice, newConflictExecution, newConflictChoice,
1257               currRWSet, visited);
1258     }
1259     // Remove the transition after being explored
1260     // TODO: Seems to cause a lot of loops---commented out for now
1261     //visited.remove(confTrans);
1262   }
1263
1264   // --- Functions related to the reachability analysis when there is a state match
1265
1266   /*private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
1267     // Perform this analysis only when:
1268     // 1) this is not during a switch to a new execution,
1269     // 2) at least 2 choices/events have been explored (choiceCounter > 1),
1270     // 3) state > 0 (state 0 is for boolean CG)
1271     if (!isEndOfExecution && choiceCounter > 1 && stateId > 0) {
1272       if (currVisitedStates.contains(stateId) || prevVisitedStates.contains(stateId)) {
1273         // Update reachable transitions in the graph with a predecessor
1274         HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitionsAtState(stateId);
1275         for(TransitionEvent transition : reachableTransitions) {
1276           transition.recordPredecessor(currentExecution, choiceCounter - 1);
1277         }
1278         updateBacktrackSetsFromPreviousExecution(stateId);
1279       }
1280     }
1281   }
1282
1283   // Update the backtrack sets from previous executions
1284   private void updateBacktrackSetsFromPreviousExecution(int stateId) {
1285     // Collect all the reachable transitions from R-Graph
1286     HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitions(stateId);
1287     for(TransitionEvent transition : reachableTransitions) {
1288       Execution execution = transition.getExecution();
1289       int currentChoice = transition.getChoiceCounter();
1290       updateBacktrackSet(execution, currentChoice);
1291     }
1292   }*/
1293
1294   // TODO: THIS IS THE ACCESS SUMMARY
1295   private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
1296     // Perform this analysis only when:
1297     // 1) this is not during a switch to a new execution,
1298     // 2) at least 2 choices/events have been explored (choiceCounter > 1),
1299     // 3) state > 0 (state 0 is for boolean CG)
1300     if (!isEndOfExecution && choiceCounter > 1 && stateId > 0) {
1301       if (currVisitedStates.contains(stateId) || prevVisitedStates.contains(stateId)) {
1302         // Update reachable transitions in the graph with a predecessor
1303         HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitionsAtState(stateId);
1304         for(TransitionEvent transition : reachableTransitions) {
1305           transition.recordPredecessor(currentExecution, choiceCounter - 1);
1306         }
1307         updateBacktrackSetsFromPreviousExecution(currentExecution, choiceCounter - 1, stateId);
1308       }
1309     }
1310   }
1311
1312   private void updateBacktrackSetsFromPreviousExecution(Execution execution, int currentChoice, int stateId) {
1313     // Collect all the reachable transitions from R-Graph
1314     HashMap<Integer, SummaryNode> reachableTransitions = rGraph.getReachableTransitionsSummary(stateId);
1315     for(Map.Entry<Integer, SummaryNode> transition : reachableTransitions.entrySet()) {
1316       SummaryNode summaryNode = transition.getValue();
1317       TransitionEvent reachableTransition = summaryNode.getTransitionEvent();
1318       Execution conflictExecution = reachableTransition.getExecution();
1319       int conflictChoice = reachableTransition.getChoiceCounter();
1320       // Copy ReadWriteSet object
1321       ReadWriteSet currRWSet = summaryNode.getReadWriteSet();
1322       currRWSet = currRWSet.getCopy();
1323       // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1324       HashSet<TransitionEvent> visited = new HashSet<>();
1325       updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice, currRWSet, visited);
1326     }
1327   }
1328 }