Initial implementation of more efficient traversal with graph summary; pretty much...
[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, ReadWriteSet>> graphSummary;
397     private HashMap<Integer, HashMap<Integer, TransitionEvent>> eventSummary;
398
399     public RGraph() {
400       hiStateId = 0;
401       graph = new HashMap<>();
402       graphSummary = new HashMap<>();
403       eventSummary = new HashMap<>();
404     }
405
406     public void addReachableTransition(int stateId, TransitionEvent transition) {
407       // Record transition into graph
408       HashSet<TransitionEvent> transitionSet;
409       if (graph.containsKey(stateId)) {
410         transitionSet = graph.get(stateId);
411       } else {
412         transitionSet = new HashSet<>();
413         graph.put(stateId, transitionSet);
414       }
415       // Insert into the set if it does not contain it yet
416       if (!transitionSet.contains(transition)) {
417         transitionSet.add(transition);
418       }
419       // Update highest state ID
420       if (hiStateId < stateId) {
421         hiStateId = stateId;
422       }
423     }
424
425     public HashSet<TransitionEvent> getReachableTransitionsAtState(int stateId) {
426       if (!graph.containsKey(stateId)) {
427         // This is a loop from a transition to itself, so just return the current transition
428         HashSet<TransitionEvent> transitionSet = new HashSet<>();
429         transitionSet.add(currentExecution.getLastTransition());
430         return transitionSet;
431       }
432       return graph.get(stateId);
433     }
434
435     public HashSet<TransitionEvent> getReachableTransitions(int stateId) {
436       HashSet<TransitionEvent> reachableTransitions = new HashSet<>();
437       // All transitions from states higher than the given state ID (until the highest state ID) are reachable
438       for(int stId = stateId; stId <= hiStateId; stId++) {
439         // We might encounter state IDs from the first round of Boolean CG
440         // The second round of Boolean CG should consider these new states
441         if (graph.containsKey(stId)) {
442           reachableTransitions.addAll(graph.get(stId));
443         }
444       }
445       return reachableTransitions;
446     }
447
448     public HashMap<Integer, TransitionEvent> getReachableSummaryTransitions(int stateId) {
449       return eventSummary.get(stateId);
450     }
451
452     public HashMap<Integer, ReadWriteSet> getReachableSummaryRWSets(int stateId) {
453       return graphSummary.get(stateId);
454     }
455
456     private ReadWriteSet performUnion(ReadWriteSet recordedRWSet, ReadWriteSet rwSet) {
457       // Combine the same write accesses and record in the recordedRWSet
458       HashMap<String, Integer> recordedWriteMap = recordedRWSet.getWriteMap();
459       HashMap<String, Integer> writeMap = rwSet.getWriteMap();
460       for(Map.Entry<String, Integer> entry : recordedWriteMap.entrySet()) {
461         String writeField = entry.getKey();
462         // Remove the entry from rwSet if both field and object ID are the same
463         if (writeMap.containsKey(writeField) &&
464                 (writeMap.get(writeField) == recordedWriteMap.get(writeField))) {
465           writeMap.remove(writeField);
466         }
467       }
468       // Then add everything into the recorded map because these will be traversed
469       recordedWriteMap.putAll(writeMap);
470       // Combine the same read accesses and record in the recordedRWSet
471       HashMap<String, Integer> recordedReadMap = recordedRWSet.getReadMap();
472       HashMap<String, Integer> readMap = rwSet.getReadMap();
473       for(Map.Entry<String, Integer> entry : recordedReadMap.entrySet()) {
474         String readField = entry.getKey();
475         // Remove the entry from rwSet if both field and object ID are the same
476         if (readMap.containsKey(readField) &&
477                 (readMap.get(readField) == recordedReadMap.get(readField))) {
478           readMap.remove(readField);
479         }
480       }
481       // Then add everything into the recorded map because these will be traversed
482       recordedReadMap.putAll(readMap);
483
484       return rwSet;
485     }
486
487     public ReadWriteSet recordTransitionSummary(int stateId, TransitionEvent transition, ReadWriteSet rwSet) {
488       // Record transition into graphSummary
489       // TransitionMap maps event (choice) number to a R/W set
490       HashMap<Integer, ReadWriteSet> transitionMap;
491       if (graphSummary.containsKey(stateId)) {
492         transitionMap = graphSummary.get(stateId);
493       } else {
494         transitionMap = new HashMap<>();
495         graphSummary.put(stateId, transitionMap);
496       }
497       int choice = transition.getChoice();
498       ReadWriteSet recordedRWSet;
499       // Insert transition into the map if we haven't had this event number recorded
500       if (!transitionMap.containsKey(choice)) {
501         recordedRWSet = rwSet.getCopy();
502         transitionMap.put(choice, recordedRWSet);
503         // Insert the actual TransitionEvent object into the map
504         HashMap<Integer, TransitionEvent> eventMap = new HashMap<>();
505         eventMap.put(choice, transition);
506         eventSummary.put(stateId, eventMap);
507       } else {
508         recordedRWSet = transitionMap.get(choice);
509         // Perform union and subtraction between the recorded and the given R/W sets
510         rwSet = performUnion(recordedRWSet, rwSet);
511       }
512       return rwSet;
513     }
514   }
515
516   // This class compactly stores Read and Write field sets
517   // We store the field name and its object ID
518   // Sharing the same field means the same field name and object ID
519   private class ReadWriteSet {
520     private HashMap<String, Integer> readMap;
521     private HashMap<String, Integer> writeMap;
522
523     public ReadWriteSet() {
524       readMap = new HashMap<>();
525       writeMap = new HashMap<>();
526     }
527
528     public void addReadField(String field, int objectId) {
529       readMap.put(field, objectId);
530     }
531
532     public void addWriteField(String field, int objectId) {
533       writeMap.put(field, objectId);
534     }
535
536     public void removeReadField(String field) {
537       readMap.remove(field);
538     }
539
540     public void removeWriteField(String field) {
541       writeMap.remove(field);
542     }
543
544     public boolean isEmpty() {
545       return readMap.isEmpty() && writeMap.isEmpty();
546     }
547
548     public ReadWriteSet getCopy() {
549       ReadWriteSet copyRWSet = new ReadWriteSet();
550       // Copy the maps in the set into the new object copy
551       copyRWSet.setReadMap(new HashMap<>(this.getReadMap()));
552       copyRWSet.setWriteMap(new HashMap<>(this.getWriteMap()));
553       return copyRWSet;
554     }
555
556     public Set<String> getReadSet() {
557       return readMap.keySet();
558     }
559
560     public Set<String> getWriteSet() {
561       return writeMap.keySet();
562     }
563
564     public boolean readFieldExists(String field) {
565       return readMap.containsKey(field);
566     }
567
568     public boolean writeFieldExists(String field) {
569       return writeMap.containsKey(field);
570     }
571
572     public int readFieldObjectId(String field) {
573       return readMap.get(field);
574     }
575
576     public int writeFieldObjectId(String field) {
577       return writeMap.get(field);
578     }
579
580     private HashMap<String, Integer> getReadMap() {
581       return readMap;
582     }
583
584     private HashMap<String, Integer> getWriteMap() {
585       return writeMap;
586     }
587
588     private void setReadMap(HashMap<String, Integer> rMap) {
589       readMap = rMap;
590     }
591
592     private void setWriteMap(HashMap<String, Integer> wMap) {
593       writeMap = wMap;
594     }
595   }
596
597   // This class compactly stores transitions:
598   // 1) CG,
599   // 2) state ID,
600   // 3) choice,
601   // 4) predecessors (for backward DFS).
602   private class TransitionEvent {
603     private int choice;                        // Choice chosen at this transition
604     private int choiceCounter;                 // Choice counter at this transition
605     private Execution execution;               // The execution where this transition belongs
606     private HashSet<Predecessor> predecessors; // Maps incoming events/transitions (execution and choice)
607     private int stateId;                       // State at this transition
608     private IntChoiceFromSet transitionCG;     // CG at this transition
609
610     public TransitionEvent() {
611       choice = 0;
612       choiceCounter = 0;
613       execution = null;
614       predecessors = new HashSet<>();
615       stateId = 0;
616       transitionCG = null;
617     }
618
619     public int getChoice() {
620       return choice;
621     }
622
623     public int getChoiceCounter() {
624       return choiceCounter;
625     }
626
627     public Execution getExecution() {
628       return execution;
629     }
630
631     public HashSet<Predecessor> getPredecessors() {
632       return predecessors;
633     }
634
635     public int getStateId() {
636       return stateId;
637     }
638
639     public IntChoiceFromSet getTransitionCG() { return transitionCG; }
640
641     public void recordPredecessor(Execution execution, int choice) {
642       predecessors.add(new Predecessor(choice, execution));
643     }
644
645     public void setChoice(int cho) {
646       choice = cho;
647     }
648
649     public void setChoiceCounter(int choCounter) {
650       choiceCounter = choCounter;
651     }
652
653     public void setExecution(Execution exec) {
654       execution = exec;
655     }
656
657     public void setPredecessors(HashSet<Predecessor> preds) {
658       predecessors = new HashSet<>(preds);
659     }
660
661     public void setStateId(int stId) {
662       stateId = stId;
663     }
664
665     public void setTransitionCG(IntChoiceFromSet cg) {
666       transitionCG = cg;
667     }
668   }
669
670   // -- CONSTANTS
671   private final static String DO_CALL_METHOD = "doCall";
672   // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
673   private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
674   private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
675           // Groovy library created fields
676           {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
677           // Infrastructure
678           "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
679           "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
680   private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
681           // Java and Groovy libraries
682           { "java", "org", "sun", "com", "gov", "groovy"};
683   private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
684   private final static String GET_PROPERTY_METHOD =
685           "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
686   private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
687   private final static String JAVA_INTEGER = "int";
688   private final static String JAVA_STRING_LIB = "java.lang.String";
689
690   // -- FUNCTIONS
691   private Integer[] copyChoices(Integer[] choicesToCopy) {
692
693     Integer[] copyOfChoices = new Integer[choicesToCopy.length];
694     System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
695     return copyOfChoices;
696   }
697
698   private void ensureFairSchedulingAndSetupTransition(IntChoiceFromSet icsCG, VM vm) {
699     // Check the next choice and if the value is not the same as the expected then force the expected value
700     int choiceIndex = choiceCounter % refChoices.length;
701     int nextChoice = icsCG.getNextChoice();
702     if (refChoices[choiceIndex] != nextChoice) {
703       int expectedChoice = refChoices[choiceIndex];
704       int currCGIndex = icsCG.getNextChoiceIndex();
705       if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
706         icsCG.setChoice(currCGIndex, expectedChoice);
707       }
708     }
709     // Get state ID and associate it with this transition
710     int stateId = vm.getStateId();
711     TransitionEvent transition = setupTransition(icsCG, stateId, choiceIndex);
712     // Add new transition to the current execution and map it in R-Graph
713     for (Integer stId : justVisitedStates) {  // Map this transition to all the previously passed states
714       rGraph.addReachableTransition(stId, transition);
715     }
716     currentExecution.mapCGToChoice(icsCG, choiceCounter);
717     // Store restorable state object for this state (always store the latest)
718     if (!restorableStateMap.containsKey(stateId)) {
719       RestorableVMState restorableState = vm.getRestorableState();
720       restorableStateMap.put(stateId, restorableState);
721     }
722   }
723
724   private TransitionEvent setupTransition(IntChoiceFromSet icsCG, int stateId, int choiceIndex) {
725     // Get a new transition
726     TransitionEvent transition;
727     if (currentExecution.isNew()) {
728       // We need to handle the first transition differently because this has a predecessor execution
729       transition = currentExecution.getFirstTransition();
730     } else {
731       transition = new TransitionEvent();
732       currentExecution.addTransition(transition);
733       transition.recordPredecessor(currentExecution, choiceCounter - 1);
734     }
735     transition.setExecution(currentExecution);
736     transition.setTransitionCG(icsCG);
737     transition.setStateId(stateId);
738     transition.setChoice(refChoices[choiceIndex]);
739     transition.setChoiceCounter(choiceCounter);
740
741     return transition;
742   }
743
744   // --- Functions related to cycle detection and reachability graph
745
746   // Detect cycles in the current execution/trace
747   // We terminate the execution iff:
748   // (1) the state has been visited in the current execution
749   // (2) the state has one or more cycles that involve all the events
750   // With simple approach we only need to check for a re-visited state.
751   // Basically, we have to check that we have executed all events between two occurrences of such state.
752   private boolean completeFullCycle(int stId) {
753     // False if the state ID hasn't been recorded
754     if (!stateToEventMap.containsKey(stId)) {
755       return false;
756     }
757     HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
758     // Check if this set contains all the event choices
759     // If not then this is not the terminating condition
760     for(int i=0; i<=maxEventChoice; i++) {
761       if (!visitedEvents.contains(i)) {
762         return false;
763       }
764     }
765     return true;
766   }
767
768   private void initializeStatesVariables() {
769     // DPOR-related
770     choices = null;
771     refChoices = null;
772     choiceCounter = 0;
773     maxEventChoice = 0;
774     // Cycle tracking
775     currVisitedStates = new HashSet<>();
776     justVisitedStates = new HashSet<>();
777     prevVisitedStates = new HashSet<>();
778     stateToEventMap = new HashMap<>();
779     // Backtracking
780     backtrackMap = new HashMap<>();
781     backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
782     currentExecution = new Execution();
783     currentExecution.addTransition(new TransitionEvent()); // Always start with 1 backtrack point
784     doneBacktrackMap = new HashMap<>();
785     rGraph = new RGraph();
786     // Booleans
787     isEndOfExecution = false;
788   }
789
790   private void mapStateToEvent(int nextChoiceValue) {
791     // Update all states with this event/choice
792     // This means that all past states now see this transition
793     Set<Integer> stateSet = stateToEventMap.keySet();
794     for(Integer stateId : stateSet) {
795       HashSet<Integer> eventSet = stateToEventMap.get(stateId);
796       eventSet.add(nextChoiceValue);
797     }
798   }
799
800   private boolean terminateCurrentExecution() {
801     // We need to check all the states that have just been visited
802     // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
803     for(Integer stateId : justVisitedStates) {
804       if (prevVisitedStates.contains(stateId) || completeFullCycle(stateId)) {
805         return true;
806       }
807     }
808     return false;
809   }
810
811   private void updateStateInfo(Search search) {
812     // Update the state variables
813     int stateId = search.getStateId();
814     // Insert state ID into the map if it is new
815     if (!stateToEventMap.containsKey(stateId)) {
816       HashSet<Integer> eventSet = new HashSet<>();
817       stateToEventMap.put(stateId, eventSet);
818     }
819     analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);
820     justVisitedStates.add(stateId);
821     if (!prevVisitedStates.contains(stateId)) {
822       // It is a currently visited states if the state has not been seen in previous executions
823       currVisitedStates.add(stateId);
824     }
825   }
826
827   // --- Functions related to Read/Write access analysis on shared fields
828
829   private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList, TransitionEvent conflictTransition) {
830     // Insert backtrack point to the right state ID
831     LinkedList<BacktrackExecution> backtrackExecList;
832     if (backtrackMap.containsKey(stateId)) {
833       backtrackExecList = backtrackMap.get(stateId);
834     } else {
835       backtrackExecList = new LinkedList<>();
836       backtrackMap.put(stateId, backtrackExecList);
837     }
838     // Add the new backtrack execution object
839     TransitionEvent backtrackTransition = new TransitionEvent();
840     backtrackTransition.setPredecessors(conflictTransition.getPredecessors());
841     backtrackExecList.addFirst(new BacktrackExecution(newChoiceList, backtrackTransition));
842     // Add to priority queue
843     if (!backtrackStateQ.contains(stateId)) {
844       backtrackStateQ.add(stateId);
845     }
846   }
847
848   // Analyze Read/Write accesses that are directly invoked on fields
849   private void analyzeReadWriteAccesses(Instruction executedInsn, int currentChoice) {
850     // Get the field info
851     FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
852     // Analyze only after being initialized
853     String fieldClass = fieldInfo.getFullName();
854     // Do the analysis to get Read and Write accesses to fields
855     ReadWriteSet rwSet = getReadWriteSet(currentChoice);
856     int objectId = fieldInfo.getClassInfo().getClassObjectRef();
857     // Record the field in the map
858     if (executedInsn instanceof WriteInstruction) {
859       // We first check the non-relevant fields set
860       if (!nonRelevantFields.contains(fieldInfo)) {
861         // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
862         for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
863           if (fieldClass.startsWith(str)) {
864             nonRelevantFields.add(fieldInfo);
865             return;
866           }
867         }
868       } else {
869         // If we have this field in the non-relevant fields set then we return right away
870         return;
871       }
872       rwSet.addWriteField(fieldClass, objectId);
873     } else if (executedInsn instanceof ReadInstruction) {
874       rwSet.addReadField(fieldClass, objectId);
875     }
876   }
877
878   // Analyze Read accesses that are indirect (performed through iterators)
879   // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
880   private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
881     // Get method name
882     INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
883     if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
884             insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
885       // Extract info from the stack frame
886       StackFrame frame = ti.getTopFrame();
887       int[] frameSlots = frame.getSlots();
888       // Get the Groovy callsite library at index 0
889       ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
890       if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
891         return;
892       }
893       // Get the iterated object whose property is accessed
894       ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
895       if (eiAccessObj == null) {
896         return;
897       }
898       // We exclude library classes (they start with java, org, etc.) and some more
899       ClassInfo classInfo = eiAccessObj.getClassInfo();
900       String objClassName = classInfo.getName();
901       // Check if this class info is part of the non-relevant classes set already
902       if (!nonRelevantClasses.contains(classInfo)) {
903         if (excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName) ||
904                 excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName)) {
905           nonRelevantClasses.add(classInfo);
906           return;
907         }
908       } else {
909         // If it is part of the non-relevant classes set then return immediately
910         return;
911       }
912       // Extract fields from this object and put them into the read write
913       int numOfFields = eiAccessObj.getNumberOfFields();
914       for(int i=0; i<numOfFields; i++) {
915         FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
916         if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
917           String fieldClass = fieldInfo.getFullName();
918           ReadWriteSet rwSet = getReadWriteSet(currentChoice);
919           int objectId = fieldInfo.getClassInfo().getClassObjectRef();
920           // Record the field in the map
921           rwSet.addReadField(fieldClass, objectId);
922         }
923       }
924     }
925   }
926
927   private int checkAndAdjustChoice(int currentChoice, VM vm) {
928     // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
929     // for certain method calls in the infrastructure, e.g., eventSince()
930     ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
931     // This is the main event CG
932     if (currentCG instanceof IntIntervalGenerator) {
933       // This is the interval CG used in device handlers
934       ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
935       // Iterate until we find the IntChoiceFromSet CG
936       while (!(parentCG instanceof IntChoiceFromSet)) {
937         parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
938       }
939       // Find the choice related to the IntIntervalGenerator CG from the map
940       currentChoice = currentExecution.getChoiceFromCG((IntChoiceFromSet) parentCG);
941     }
942     return currentChoice;
943   }
944
945   private void createBacktrackingPoint(Execution execution, int currentChoice,
946                                        Execution conflictExecution, int conflictChoice) {
947     // Create a new list of choices for backtrack based on the current choice and conflicting event number
948     // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
949     // for the original set {0, 1, 2, 3}
950     
951     // execution/currentChoice represent the event/transaction that will be put into the backtracking set of
952     // conflictExecution/conflictChoice
953     Integer[] newChoiceList = new Integer[refChoices.length];
954     ArrayList<TransitionEvent> currentTrace = execution.getExecutionTrace();
955     ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
956     int currChoice = currentTrace.get(currentChoice).getChoice();
957     int stateId = conflictTrace.get(conflictChoice).getStateId();
958     // Check if this trace has been done from this state
959     if (isTraceAlreadyConstructed(currChoice, stateId)) {
960       return;
961     }
962     // Put the conflicting event numbers first and reverse the order
963     newChoiceList[0] = currChoice;
964     // Put the rest of the event numbers into the array starting from the minimum to the upper bound
965     for (int i = 0, j = 1; i < refChoices.length; i++) {
966       if (refChoices[i] != newChoiceList[0]) {
967         newChoiceList[j] = refChoices[i];
968         j++;
969       }
970     }
971     // Predecessor of the new backtrack point is the same as the conflict point's
972     addNewBacktrackPoint(stateId, newChoiceList, conflictTrace.get(conflictChoice));
973   }
974
975   private boolean excludeThisForItContains(String[] excludedStrings, String className) {
976     for (String excludedField : excludedStrings) {
977       if (className.contains(excludedField)) {
978         return true;
979       }
980     }
981     return false;
982   }
983
984   private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
985     for (String excludedField : excludedStrings) {
986       if (className.endsWith(excludedField)) {
987         return true;
988       }
989     }
990     return false;
991   }
992
993   private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
994     for (String excludedField : excludedStrings) {
995       if (className.startsWith(excludedField)) {
996         return true;
997       }
998     }
999     return false;
1000   }
1001
1002   private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
1003                 // Check if we are reaching the end of our execution: no more backtracking points to explore
1004                 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
1005                 if (!backtrackStateQ.isEmpty()) {
1006                         // Set done all the other backtrack points
1007                         for (TransitionEvent backtrackTransition : currentExecution.getExecutionTrace()) {
1008         backtrackTransition.getTransitionCG().setDone();
1009                         }
1010                         // Reset the next backtrack point with the latest state
1011                         int hiStateId = backtrackStateQ.peek();
1012                         // Restore the state first if necessary
1013                         if (vm.getStateId() != hiStateId) {
1014                                 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
1015                                 vm.restoreState(restorableState);
1016                         }
1017                         // Set the backtrack CG
1018                         IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
1019                         setBacktrackCG(hiStateId, backtrackCG);
1020                 } else {
1021                         // Set done this last CG (we save a few rounds)
1022                         icsCG.setDone();
1023                 }
1024                 // Save all the visited states when starting a new execution of trace
1025                 prevVisitedStates.addAll(currVisitedStates);
1026                 // This marks a transitional period to the new CG
1027                 isEndOfExecution = true;
1028   }
1029
1030   private boolean isConflictFound(Execution execution, int reachableChoice, Execution conflictExecution, int conflictChoice,
1031                                   ReadWriteSet currRWSet) {
1032     // conflictExecution/conflictChoice represent a predecessor event/transaction that can potentially have a conflict
1033     ArrayList<TransitionEvent> executionTrace = execution.getExecutionTrace();
1034     ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
1035     HashMap<Integer, ReadWriteSet> confRWFieldsMap = conflictExecution.getReadWriteFieldsMap();
1036     // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
1037     if (!confRWFieldsMap.containsKey(conflictChoice) ||
1038             executionTrace.get(reachableChoice).getChoice() == conflictTrace.get(conflictChoice).getChoice()) {
1039       return false;
1040     }
1041     // R/W set of choice/event that may have a potential conflict
1042     ReadWriteSet confRWSet = confRWFieldsMap.get(conflictChoice);
1043     // Check for conflicts with Read and Write fields for Write instructions
1044     Set<String> currWriteSet = currRWSet.getWriteSet();
1045     for(String writeField : currWriteSet) {
1046       int currObjId = currRWSet.writeFieldObjectId(writeField);
1047       if ((confRWSet.readFieldExists(writeField) && confRWSet.readFieldObjectId(writeField) == currObjId) ||
1048           (confRWSet.writeFieldExists(writeField) && confRWSet.writeFieldObjectId(writeField) == currObjId)) {
1049         // Remove this from the write set as we are tracking per memory location
1050         currRWSet.removeWriteField(writeField);
1051         return true;
1052       }
1053     }
1054     // Check for conflicts with Write fields for Read instructions
1055     Set<String> currReadSet = currRWSet.getReadSet();
1056     for(String readField : currReadSet) {
1057       int currObjId = currRWSet.readFieldObjectId(readField);
1058       if (confRWSet.writeFieldExists(readField) && confRWSet.writeFieldObjectId(readField) == currObjId) {
1059         // Remove this from the read set as we are tracking per memory location
1060         currRWSet.removeReadField(readField);
1061         return true;
1062       }
1063     }
1064     // Return false if no conflict is found
1065     return false;
1066   }
1067
1068   private ReadWriteSet getReadWriteSet(int currentChoice) {
1069     // Do the analysis to get Read and Write accesses to fields
1070     ReadWriteSet rwSet;
1071     // We already have an entry
1072     HashMap<Integer, ReadWriteSet> currReadWriteFieldsMap = currentExecution.getReadWriteFieldsMap();
1073     if (currReadWriteFieldsMap.containsKey(currentChoice)) {
1074       rwSet = currReadWriteFieldsMap.get(currentChoice);
1075     } else { // We need to create a new entry
1076       rwSet = new ReadWriteSet();
1077       currReadWriteFieldsMap.put(currentChoice, rwSet);
1078     }
1079     return rwSet;
1080   }
1081
1082   private boolean isFieldExcluded(Instruction executedInsn) {
1083     // Get the field info
1084     FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
1085     // Check if the non-relevant fields set already has it
1086     if (nonRelevantFields.contains(fieldInfo)) {
1087       return true;
1088     }
1089     // Check if the relevant fields set already has it
1090     if (relevantFields.contains(fieldInfo)) {
1091       return false;
1092     }
1093     // Analyze only after being initialized
1094     String field = fieldInfo.getFullName();
1095     // Check against "starts-with", "ends-with", and "contains" list
1096     if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
1097             excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
1098             excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
1099       nonRelevantFields.add(fieldInfo);
1100       return true;
1101     }
1102     relevantFields.add(fieldInfo);
1103     return false;
1104   }
1105
1106   // Check if this trace is already constructed
1107   private boolean isTraceAlreadyConstructed(int firstChoice, int stateId) {
1108     // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
1109     // Check if the trace has been constructed as a backtrack point for this state
1110     // TODO: THIS IS AN OPTIMIZATION!
1111     HashSet<Integer> choiceSet;
1112     if (doneBacktrackMap.containsKey(stateId)) {
1113       choiceSet = doneBacktrackMap.get(stateId);
1114       if (choiceSet.contains(firstChoice)) {
1115         return true;
1116       }
1117     } else {
1118       choiceSet = new HashSet<>();
1119       doneBacktrackMap.put(stateId, choiceSet);
1120     }
1121     choiceSet.add(firstChoice);
1122
1123     return false;
1124   }
1125
1126   // Reset data structure for each new execution
1127   private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
1128     if (choices == null || choices != icsCG.getAllChoices()) {
1129       // Reset state variables
1130       choiceCounter = 0;
1131       choices = icsCG.getAllChoices();
1132       refChoices = copyChoices(choices);
1133       // Clear data structures
1134       currVisitedStates = new HashSet<>();
1135       stateToEventMap = new HashMap<>();
1136       isEndOfExecution = false;
1137     }
1138   }
1139
1140   // Set a backtrack point for a particular state
1141   private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
1142     // Set a backtrack CG based on a state ID
1143     LinkedList<BacktrackExecution> backtrackExecutions = backtrackMap.get(stateId);
1144     BacktrackExecution backtrackExecution = backtrackExecutions.removeLast();
1145     backtrackCG.setNewValues(backtrackExecution.getChoiceList());  // Get the last from the queue
1146     backtrackCG.setStateId(stateId);
1147     backtrackCG.reset();
1148     // Update current execution with this new execution
1149     Execution newExecution = new Execution();
1150     TransitionEvent firstTransition = backtrackExecution.getFirstTransition();
1151     newExecution.addTransition(firstTransition);
1152     // Try to free some memory since this map is only used for the current execution
1153     currentExecution.clearCGToChoiceMap();
1154     currentExecution = newExecution;
1155     // Remove from the queue if we don't have more backtrack points for that state
1156     if (backtrackExecutions.isEmpty()) {
1157       backtrackMap.remove(stateId);
1158       backtrackStateQ.remove(stateId);
1159     }
1160   }
1161
1162   // Update backtrack sets
1163   // 1) recursively, and
1164   // 2) track accesses per memory location (per shared variable/field)
1165   private void updateBacktrackSet(Execution execution, int currentChoice) {
1166     // Copy ReadWriteSet object
1167     HashMap<Integer, ReadWriteSet> currRWFieldsMap = execution.getReadWriteFieldsMap();
1168     ReadWriteSet currRWSet = currRWFieldsMap.get(currentChoice);
1169     if (currRWSet == null) {
1170       return;
1171     }
1172     currRWSet = currRWSet.getCopy();
1173     // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1174     HashSet<TransitionEvent> visited = new HashSet<>();
1175     // Update backtrack set recursively
1176     // TODO: The following is the call to the original version of the method
1177 //    updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, currRWSet, visited);
1178     // TODO: The following is the call to the version of the method with pushing up happens-before transitions
1179     updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, currRWSet, visited);
1180   }
1181
1182 //  TODO: This is the original version of the recursive method
1183 //  private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1184 //                                           Execution conflictExecution, int conflictChoice,
1185 //                                           ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1186 //    // Halt when we have found the first read/write conflicts for all memory locations
1187 //    if (currRWSet.isEmpty()) {
1188 //      return;
1189 //    }
1190 //    TransitionEvent confTrans = conflictExecution.getExecutionTrace().get(conflictChoice);
1191 //    // Halt when we have visited this transition (in a cycle)
1192 //    if (visited.contains(confTrans)) {
1193 //      return;
1194 //    }
1195 //    visited.add(confTrans);
1196 //    // Explore all predecessors
1197 //    for (Predecessor predecessor : confTrans.getPredecessors()) {
1198 //      // Get the predecessor (previous conflict choice)
1199 //      conflictChoice = predecessor.getChoice();
1200 //      conflictExecution = predecessor.getExecution();
1201 //      // Check if a conflict is found
1202 //      if (isConflictFound(execution, currentChoice, conflictExecution, conflictChoice, currRWSet)) {
1203 //        createBacktrackingPoint(execution, currentChoice, conflictExecution, conflictChoice);
1204 //      }
1205 //      // Continue performing DFS if conflict is not found
1206 //      updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice, currRWSet, visited);
1207 //    }
1208 //  }
1209
1210   // TODO: This is the version of the method with pushing up happens-before transitions
1211   private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1212                                            Execution conflictExecution, int conflictChoice,
1213                                            ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1214     // Halt when we have found the first read/write conflicts for all memory locations
1215     if (currRWSet.isEmpty()) {
1216       return;
1217     }
1218     TransitionEvent currTrans = execution.getExecutionTrace().get(currentChoice);
1219     // Halt when we have visited this transition (in a cycle)
1220     if (visited.contains(currTrans)) {
1221       return;
1222     }
1223     visited.add(currTrans);
1224     // Explore all predecessors
1225     for (Predecessor predecessor : currTrans.getPredecessors()) {
1226       // Get the predecessor (previous conflict choice)
1227       int predecessorChoice = predecessor.getChoice();
1228       Execution predecessorExecution = predecessor.getExecution();
1229       // Push up one happens-before transition
1230       int newConflictChoice = conflictChoice;
1231       Execution newConflictExecution = conflictExecution;
1232       // Check if a conflict is found
1233       if (isConflictFound(conflictExecution, conflictChoice, predecessorExecution, predecessorChoice, currRWSet)) {
1234         createBacktrackingPoint(conflictExecution, conflictChoice, predecessorExecution, predecessorChoice);
1235         newConflictChoice = conflictChoice;
1236         newConflictExecution = conflictExecution;
1237       }
1238       // TODO: THIS IS THE ACCESS SUMMARY
1239       // Record this transition into rGraph summary
1240       int stateId = predecessor.getExecution().getExecutionTrace().get(predecessorChoice).getStateId();
1241       currRWSet = rGraph.recordTransitionSummary(stateId, currTrans, currRWSet);
1242       // Continue performing DFS if conflict is not found
1243       updateBacktrackSetRecursive(predecessorExecution, predecessorChoice, newConflictExecution, newConflictChoice,
1244               currRWSet, visited);
1245     }
1246     // Remove the transition after being explored
1247     // TODO: Seems to cause a lot of loops---commented out for now
1248     //visited.remove(confTrans);
1249   }
1250
1251   // --- Functions related to the reachability analysis when there is a state match
1252
1253   /*private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
1254     // Perform this analysis only when:
1255     // 1) this is not during a switch to a new execution,
1256     // 2) at least 2 choices/events have been explored (choiceCounter > 1),
1257     // 3) state > 0 (state 0 is for boolean CG)
1258     if (!isEndOfExecution && choiceCounter > 1 && stateId > 0) {
1259       if (currVisitedStates.contains(stateId) || prevVisitedStates.contains(stateId)) {
1260         // Update reachable transitions in the graph with a predecessor
1261         HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitionsAtState(stateId);
1262         for(TransitionEvent transition : reachableTransitions) {
1263           transition.recordPredecessor(currentExecution, choiceCounter - 1);
1264         }
1265         updateBacktrackSetsFromPreviousExecution(stateId);
1266       }
1267     }
1268   }
1269
1270   // Update the backtrack sets from previous executions
1271   private void updateBacktrackSetsFromPreviousExecution(int stateId) {
1272     // Collect all the reachable transitions from R-Graph
1273     HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitions(stateId);
1274     for(TransitionEvent transition : reachableTransitions) {
1275       Execution execution = transition.getExecution();
1276       int currentChoice = transition.getChoiceCounter();
1277       updateBacktrackSet(execution, currentChoice);
1278     }
1279   }*/
1280
1281   // TODO: THIS IS THE ACCESS SUMMARY
1282   private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
1283     // Perform this analysis only when:
1284     // 1) this is not during a switch to a new execution,
1285     // 2) at least 2 choices/events have been explored (choiceCounter > 1),
1286     // 3) state > 0 (state 0 is for boolean CG)
1287     if (!isEndOfExecution && choiceCounter > 1 && stateId > 0) {
1288       if (currVisitedStates.contains(stateId) || prevVisitedStates.contains(stateId)) {
1289         // Update reachable transitions in the graph with a predecessor
1290         HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitionsAtState(stateId);
1291         for(TransitionEvent transition : reachableTransitions) {
1292           transition.recordPredecessor(currentExecution, choiceCounter - 1);
1293         }
1294         updateBacktrackSetsFromPreviousExecution(currentExecution, choiceCounter - 1, stateId);
1295       }
1296     }
1297   }
1298
1299   private void updateBacktrackSetsFromPreviousExecution(Execution execution, int currentChoice, int stateId) {
1300     // Collect all the reachable transitions from R-Graph
1301     HashMap<Integer, TransitionEvent> reachableTransitions = rGraph.getReachableSummaryTransitions(stateId);
1302     HashMap<Integer, ReadWriteSet> reachableRWSets = rGraph.getReachableSummaryRWSets(stateId);
1303     for(Map.Entry<Integer, TransitionEvent> transition : reachableTransitions.entrySet()) {
1304       TransitionEvent reachableTransition = transition.getValue();
1305       Execution conflictExecution = reachableTransition.getExecution();
1306       int conflictChoice = reachableTransition.getChoiceCounter();
1307       // Copy ReadWriteSet object
1308       ReadWriteSet currRWSet = reachableRWSets.get(transition.getKey());
1309       currRWSet = currRWSet.getCopy();
1310       // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1311       HashSet<TransitionEvent> visited = new HashSet<>();
1312       updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice, currRWSet, visited);
1313     }
1314   }
1315 }