Fixing a bug: summary of conflict transition and ReadWriteSet need to be stored in...
[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(Execution predExec, int predChoice) {
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> getReachableTransitionSummary(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     public void recordTransitionSummaryAtState(int stateId, HashMap<Integer, SummaryNode> transitionSummary) {
511       // Record transition summary into graphSummary
512       graphSummary.put(stateId, transitionSummary);
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 provides a data structure to store TransitionEvent and ReadWriteSet for a summary
598   private class SummaryNode {
599     private TransitionEvent transitionEvent;
600     private ReadWriteSet readWriteSet;
601
602     public SummaryNode(TransitionEvent transEvent, ReadWriteSet rwSet) {
603       transitionEvent = transEvent;
604       readWriteSet = rwSet;
605     }
606
607     public TransitionEvent getTransitionEvent() {
608       return transitionEvent;
609     }
610
611     public ReadWriteSet getReadWriteSet() {
612       return readWriteSet;
613     }
614   }
615
616   // This class compactly stores transitions:
617   // 1) CG,
618   // 2) state ID,
619   // 3) choice,
620   // 4) predecessors (for backward DFS).
621   private class TransitionEvent {
622     private int choice;                        // Choice chosen at this transition
623     private int choiceCounter;                 // Choice counter at this transition
624     private Execution execution;               // The execution where this transition belongs
625     private HashSet<Predecessor> predecessors; // Maps incoming events/transitions (execution and choice)
626     // TODO: THIS IS THE ACCESS SUMMARY
627     private HashMap<Integer, SummaryNode> transitionSummary;
628                                                // Summary of pushed transitions at the current transition
629     private HashMap<Execution, HashSet<Integer>> recordedPredecessors;
630                                                // Memorize event and choice number to not record them twice
631     private int stateId;                       // State at this transition
632     private IntChoiceFromSet transitionCG;     // CG at this transition
633
634     public TransitionEvent() {
635       choice = 0;
636       choiceCounter = 0;
637       execution = null;
638       predecessors = new HashSet<>();
639       transitionSummary = new HashMap<>();
640       recordedPredecessors = new HashMap<>();
641       stateId = 0;
642       transitionCG = null;
643     }
644
645     public int getChoice() {
646       return choice;
647     }
648
649     public int getChoiceCounter() {
650       return choiceCounter;
651     }
652
653     public Execution getExecution() {
654       return execution;
655     }
656
657     public HashSet<Predecessor> getPredecessors() {
658       return predecessors;
659     }
660
661     public int getStateId() {
662       return stateId;
663     }
664
665     public HashMap<Integer, SummaryNode> getTransitionSummary() {
666       return transitionSummary;
667     }
668
669     public IntChoiceFromSet getTransitionCG() { return transitionCG; }
670
671     private boolean isRecordedPredecessor(Execution execution, int choice) {
672       // See if we have recorded this predecessor earlier
673       HashSet<Integer> recordedChoices;
674       if (recordedPredecessors.containsKey(execution)) {
675         recordedChoices = recordedPredecessors.get(execution);
676         if (recordedChoices.contains(choice)) {
677           return true;
678         }
679       } else {
680         recordedChoices = new HashSet<>();
681         recordedPredecessors.put(execution, recordedChoices);
682       }
683       // Record the choice if we haven't seen it
684       recordedChoices.add(choice);
685
686       return false;
687     }
688
689     private ReadWriteSet performUnion(ReadWriteSet recordedRWSet, ReadWriteSet rwSet) {
690       // Combine the same write accesses and record in the recordedRWSet
691       HashMap<String, Integer> recordedWriteMap = recordedRWSet.getWriteMap();
692       HashMap<String, Integer> writeMap = rwSet.getWriteMap();
693       for(Map.Entry<String, Integer> entry : recordedWriteMap.entrySet()) {
694         String writeField = entry.getKey();
695         // Remove the entry from rwSet if both field and object ID are the same
696         if (writeMap.containsKey(writeField) &&
697                 (writeMap.get(writeField) == recordedWriteMap.get(writeField))) {
698           writeMap.remove(writeField);
699         }
700       }
701       // Then add everything into the recorded map because these will be traversed
702       recordedWriteMap.putAll(writeMap);
703       // Combine the same read accesses and record in the recordedRWSet
704       HashMap<String, Integer> recordedReadMap = recordedRWSet.getReadMap();
705       HashMap<String, Integer> readMap = rwSet.getReadMap();
706       for(Map.Entry<String, Integer> entry : recordedReadMap.entrySet()) {
707         String readField = entry.getKey();
708         // Remove the entry from rwSet if both field and object ID are the same
709         if (readMap.containsKey(readField) &&
710                 (readMap.get(readField) == recordedReadMap.get(readField))) {
711           readMap.remove(readField);
712         }
713       }
714       // Then add everything into the recorded map because these will be traversed
715       recordedReadMap.putAll(readMap);
716
717       return rwSet;
718     }
719
720     public void recordPredecessor(Execution execution, int choice) {
721       if (!isRecordedPredecessor(execution, choice)) {
722         predecessors.add(new Predecessor(execution, choice));
723       }
724     }
725
726     public ReadWriteSet recordTransitionSummary(TransitionEvent transition, ReadWriteSet rwSet) {
727       // Record transition into reachability summary
728       // TransitionMap maps event (choice) number to a R/W set
729       int choice = transition.getChoice();
730       SummaryNode summaryNode;
731       // Insert transition into the map if we haven't had this event number recorded
732       if (!transitionSummary.containsKey(choice)) {
733         summaryNode = new SummaryNode(transition, rwSet.getCopy());
734         transitionSummary.put(choice, summaryNode);
735       } else {
736         summaryNode = transitionSummary.get(choice);
737         // Perform union and subtraction between the recorded and the given R/W sets
738         rwSet = performUnion(summaryNode.getReadWriteSet(), rwSet);
739       }
740       return rwSet;
741     }
742
743     public void setChoice(int cho) {
744       choice = cho;
745     }
746
747     public void setChoiceCounter(int choCounter) {
748       choiceCounter = choCounter;
749     }
750
751     public void setExecution(Execution exec) {
752       execution = exec;
753     }
754
755     public void setPredecessors(HashSet<Predecessor> preds) {
756       predecessors = new HashSet<>(preds);
757     }
758
759     public void setStateId(int stId) {
760       stateId = stId;
761     }
762
763     public void setTransitionCG(IntChoiceFromSet cg) {
764       transitionCG = cg;
765     }
766   }
767
768   // -- CONSTANTS
769   private final static String DO_CALL_METHOD = "doCall";
770   // We exclude fields that come from libraries (Java and Groovy), and also the infrastructure
771   private final static String[] EXCLUDED_FIELDS_CONTAINS_LIST = {"_closure"};
772   private final static String[] EXCLUDED_FIELDS_ENDS_WITH_LIST =
773           // Groovy library created fields
774           {"stMC", "callSiteArray", "metaClass", "staticClassInfo", "__constructor__",
775           // Infrastructure
776           "sendEvent", "Object", "reference", "location", "app", "state", "log", "functionList", "objectList",
777           "eventList", "valueList", "settings", "printToConsole", "app1", "app2"};
778   private final static String[] EXCLUDED_FIELDS_STARTS_WITH_LIST =
779           // Java and Groovy libraries
780           { "java", "org", "sun", "com", "gov", "groovy"};
781   private final static String[] EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST = {"Event"};
782   private final static String GET_PROPERTY_METHOD =
783           "invokeinterface org.codehaus.groovy.runtime.callsite.CallSite.callGetProperty";
784   private final static String GROOVY_CALLSITE_LIB = "org.codehaus.groovy.runtime.callsite";
785   private final static String JAVA_INTEGER = "int";
786   private final static String JAVA_STRING_LIB = "java.lang.String";
787
788   // -- FUNCTIONS
789   private Integer[] copyChoices(Integer[] choicesToCopy) {
790
791     Integer[] copyOfChoices = new Integer[choicesToCopy.length];
792     System.arraycopy(choicesToCopy, 0, copyOfChoices, 0, choicesToCopy.length);
793     return copyOfChoices;
794   }
795
796   private void ensureFairSchedulingAndSetupTransition(IntChoiceFromSet icsCG, VM vm) {
797     // Check the next choice and if the value is not the same as the expected then force the expected value
798     int choiceIndex = choiceCounter % refChoices.length;
799     int nextChoice = icsCG.getNextChoice();
800     if (refChoices[choiceIndex] != nextChoice) {
801       int expectedChoice = refChoices[choiceIndex];
802       int currCGIndex = icsCG.getNextChoiceIndex();
803       if ((currCGIndex >= 0) && (currCGIndex < refChoices.length)) {
804         icsCG.setChoice(currCGIndex, expectedChoice);
805       }
806     }
807     // Get state ID and associate it with this transition
808     int stateId = vm.getStateId();
809     TransitionEvent transition = setupTransition(icsCG, stateId, choiceIndex);
810     // Add new transition to the current execution and map it in R-Graph
811     for (Integer stId : justVisitedStates) {  // Map this transition to all the previously passed states
812       rGraph.addReachableTransition(stId, transition);
813     }
814     currentExecution.mapCGToChoice(icsCG, choiceCounter);
815     // Store restorable state object for this state (always store the latest)
816     if (!restorableStateMap.containsKey(stateId)) {
817       RestorableVMState restorableState = vm.getRestorableState();
818       restorableStateMap.put(stateId, restorableState);
819     }
820   }
821
822   private TransitionEvent setupTransition(IntChoiceFromSet icsCG, int stateId, int choiceIndex) {
823     // Get a new transition
824     TransitionEvent transition;
825     if (currentExecution.isNew()) {
826       // We need to handle the first transition differently because this has a predecessor execution
827       transition = currentExecution.getFirstTransition();
828     } else {
829       transition = new TransitionEvent();
830       currentExecution.addTransition(transition);
831       transition.recordPredecessor(currentExecution, choiceCounter - 1);
832     }
833     transition.setExecution(currentExecution);
834     transition.setTransitionCG(icsCG);
835     transition.setStateId(stateId);
836     transition.setChoice(refChoices[choiceIndex]);
837     transition.setChoiceCounter(choiceCounter);
838
839     return transition;
840   }
841
842   // --- Functions related to cycle detection and reachability graph
843
844   // Detect cycles in the current execution/trace
845   // We terminate the execution iff:
846   // (1) the state has been visited in the current execution
847   // (2) the state has one or more cycles that involve all the events
848   // With simple approach we only need to check for a re-visited state.
849   // Basically, we have to check that we have executed all events between two occurrences of such state.
850   private boolean completeFullCycle(int stId) {
851     // False if the state ID hasn't been recorded
852     if (!stateToEventMap.containsKey(stId)) {
853       return false;
854     }
855     HashSet<Integer> visitedEvents = stateToEventMap.get(stId);
856     // Check if this set contains all the event choices
857     // If not then this is not the terminating condition
858     for(int i=0; i<=maxEventChoice; i++) {
859       if (!visitedEvents.contains(i)) {
860         return false;
861       }
862     }
863     return true;
864   }
865
866   private void initializeStatesVariables() {
867     // DPOR-related
868     choices = null;
869     refChoices = null;
870     choiceCounter = 0;
871     maxEventChoice = 0;
872     // Cycle tracking
873     currVisitedStates = new HashSet<>();
874     justVisitedStates = new HashSet<>();
875     prevVisitedStates = new HashSet<>();
876     stateToEventMap = new HashMap<>();
877     // Backtracking
878     backtrackMap = new HashMap<>();
879     backtrackStateQ = new PriorityQueue<>(Collections.reverseOrder());
880     currentExecution = new Execution();
881     currentExecution.addTransition(new TransitionEvent()); // Always start with 1 backtrack point
882     doneBacktrackMap = new HashMap<>();
883     rGraph = new RGraph();
884     // Booleans
885     isEndOfExecution = false;
886   }
887
888   private void mapStateToEvent(int nextChoiceValue) {
889     // Update all states with this event/choice
890     // This means that all past states now see this transition
891     Set<Integer> stateSet = stateToEventMap.keySet();
892     for(Integer stateId : stateSet) {
893       HashSet<Integer> eventSet = stateToEventMap.get(stateId);
894       eventSet.add(nextChoiceValue);
895     }
896   }
897
898   private boolean terminateCurrentExecution() {
899     // We need to check all the states that have just been visited
900     // Often a transition (choice/event) can result into forwarding/backtracking to a number of states
901     for(Integer stateId : justVisitedStates) {
902       if (prevVisitedStates.contains(stateId) || completeFullCycle(stateId)) {
903         return true;
904       }
905     }
906     return false;
907   }
908
909   private void updateStateInfo(Search search) {
910     // Update the state variables
911     int stateId = search.getStateId();
912     // Insert state ID into the map if it is new
913     if (!stateToEventMap.containsKey(stateId)) {
914       HashSet<Integer> eventSet = new HashSet<>();
915       stateToEventMap.put(stateId, eventSet);
916     }
917     analyzeReachabilityAndCreateBacktrackPoints(search.getVM(), stateId);
918     justVisitedStates.add(stateId);
919     if (!prevVisitedStates.contains(stateId)) {
920       // It is a currently visited states if the state has not been seen in previous executions
921       currVisitedStates.add(stateId);
922     }
923   }
924
925   // --- Functions related to Read/Write access analysis on shared fields
926
927   private void addNewBacktrackPoint(int stateId, Integer[] newChoiceList, TransitionEvent conflictTransition) {
928     // Insert backtrack point to the right state ID
929     LinkedList<BacktrackExecution> backtrackExecList;
930     if (backtrackMap.containsKey(stateId)) {
931       backtrackExecList = backtrackMap.get(stateId);
932     } else {
933       backtrackExecList = new LinkedList<>();
934       backtrackMap.put(stateId, backtrackExecList);
935     }
936     // Add the new backtrack execution object
937     TransitionEvent backtrackTransition = new TransitionEvent();
938     backtrackTransition.setPredecessors(conflictTransition.getPredecessors());
939     backtrackExecList.addFirst(new BacktrackExecution(newChoiceList, backtrackTransition));
940     // Add to priority queue
941     if (!backtrackStateQ.contains(stateId)) {
942       backtrackStateQ.add(stateId);
943     }
944   }
945
946   // Analyze Read/Write accesses that are directly invoked on fields
947   private void analyzeReadWriteAccesses(Instruction executedInsn, int currentChoice) {
948     // Get the field info
949     FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
950     // Analyze only after being initialized
951     String fieldClass = fieldInfo.getFullName();
952     // Do the analysis to get Read and Write accesses to fields
953     ReadWriteSet rwSet = getReadWriteSet(currentChoice);
954     int objectId = fieldInfo.getClassInfo().getClassObjectRef();
955     // Record the field in the map
956     if (executedInsn instanceof WriteInstruction) {
957       // We first check the non-relevant fields set
958       if (!nonRelevantFields.contains(fieldInfo)) {
959         // Exclude certain field writes because of infrastructure needs, e.g., Event class field writes
960         for (String str : EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST) {
961           if (fieldClass.startsWith(str)) {
962             nonRelevantFields.add(fieldInfo);
963             return;
964           }
965         }
966       } else {
967         // If we have this field in the non-relevant fields set then we return right away
968         return;
969       }
970       rwSet.addWriteField(fieldClass, objectId);
971     } else if (executedInsn instanceof ReadInstruction) {
972       rwSet.addReadField(fieldClass, objectId);
973     }
974   }
975
976   // Analyze Read accesses that are indirect (performed through iterators)
977   // These accesses are marked by certain bytecode instructions, e.g., INVOKEINTERFACE
978   private void analyzeReadWriteAccesses(Instruction instruction, ThreadInfo ti, int currentChoice) {
979     // Get method name
980     INVOKEINTERFACE insn = (INVOKEINTERFACE) instruction;
981     if (insn.toString().startsWith(GET_PROPERTY_METHOD) &&
982             insn.getMethodInfo().getName().equals(DO_CALL_METHOD)) {
983       // Extract info from the stack frame
984       StackFrame frame = ti.getTopFrame();
985       int[] frameSlots = frame.getSlots();
986       // Get the Groovy callsite library at index 0
987       ElementInfo eiCallsite = VM.getVM().getHeap().get(frameSlots[0]);
988       if (!eiCallsite.getClassInfo().getName().startsWith(GROOVY_CALLSITE_LIB)) {
989         return;
990       }
991       // Get the iterated object whose property is accessed
992       ElementInfo eiAccessObj = VM.getVM().getHeap().get(frameSlots[1]);
993       if (eiAccessObj == null) {
994         return;
995       }
996       // We exclude library classes (they start with java, org, etc.) and some more
997       ClassInfo classInfo = eiAccessObj.getClassInfo();
998       String objClassName = classInfo.getName();
999       // Check if this class info is part of the non-relevant classes set already
1000       if (!nonRelevantClasses.contains(classInfo)) {
1001         if (excludeThisForItStartsWith(EXCLUDED_FIELDS_READ_WRITE_INSTRUCTIONS_STARTS_WITH_LIST, objClassName) ||
1002                 excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, objClassName)) {
1003           nonRelevantClasses.add(classInfo);
1004           return;
1005         }
1006       } else {
1007         // If it is part of the non-relevant classes set then return immediately
1008         return;
1009       }
1010       // Extract fields from this object and put them into the read write
1011       int numOfFields = eiAccessObj.getNumberOfFields();
1012       for(int i=0; i<numOfFields; i++) {
1013         FieldInfo fieldInfo = eiAccessObj.getFieldInfo(i);
1014         if (fieldInfo.getType().equals(JAVA_STRING_LIB) || fieldInfo.getType().equals(JAVA_INTEGER)) {
1015           String fieldClass = fieldInfo.getFullName();
1016           ReadWriteSet rwSet = getReadWriteSet(currentChoice);
1017           int objectId = fieldInfo.getClassInfo().getClassObjectRef();
1018           // Record the field in the map
1019           rwSet.addReadField(fieldClass, objectId);
1020         }
1021       }
1022     }
1023   }
1024
1025   private int checkAndAdjustChoice(int currentChoice, VM vm) {
1026     // If current choice is not the same, then this is caused by the firing of IntIntervalGenerator
1027     // for certain method calls in the infrastructure, e.g., eventSince()
1028     ChoiceGenerator<?> currentCG = vm.getChoiceGenerator();
1029     // This is the main event CG
1030     if (currentCG instanceof IntIntervalGenerator) {
1031       // This is the interval CG used in device handlers
1032       ChoiceGenerator<?> parentCG = ((IntIntervalGenerator) currentCG).getPreviousChoiceGenerator();
1033       // Iterate until we find the IntChoiceFromSet CG
1034       while (!(parentCG instanceof IntChoiceFromSet)) {
1035         parentCG = ((IntIntervalGenerator) parentCG).getPreviousChoiceGenerator();
1036       }
1037       // Find the choice related to the IntIntervalGenerator CG from the map
1038       currentChoice = currentExecution.getChoiceFromCG((IntChoiceFromSet) parentCG);
1039     }
1040     return currentChoice;
1041   }
1042
1043   private void createBacktrackingPoint(Execution execution, int currentChoice,
1044                                        Execution conflictExecution, int conflictChoice) {
1045     // Create a new list of choices for backtrack based on the current choice and conflicting event number
1046     // E.g. if we have a conflict between 1 and 3, then we create the list {3, 1, 0, 2}
1047     // for the original set {0, 1, 2, 3}
1048     
1049     // execution/currentChoice represent the event/transaction that will be put into the backtracking set of
1050     // conflictExecution/conflictChoice
1051     Integer[] newChoiceList = new Integer[refChoices.length];
1052     ArrayList<TransitionEvent> currentTrace = execution.getExecutionTrace();
1053     ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
1054     int currChoice = currentTrace.get(currentChoice).getChoice();
1055     int stateId = conflictTrace.get(conflictChoice).getStateId();
1056     // Check if this trace has been done from this state
1057     if (isTraceAlreadyConstructed(currChoice, stateId)) {
1058       return;
1059     }
1060     // Put the conflicting event numbers first and reverse the order
1061     newChoiceList[0] = currChoice;
1062     // Put the rest of the event numbers into the array starting from the minimum to the upper bound
1063     for (int i = 0, j = 1; i < refChoices.length; i++) {
1064       if (refChoices[i] != newChoiceList[0]) {
1065         newChoiceList[j] = refChoices[i];
1066         j++;
1067       }
1068     }
1069     // Predecessor of the new backtrack point is the same as the conflict point's
1070     addNewBacktrackPoint(stateId, newChoiceList, conflictTrace.get(conflictChoice));
1071   }
1072
1073   private boolean excludeThisForItContains(String[] excludedStrings, String className) {
1074     for (String excludedField : excludedStrings) {
1075       if (className.contains(excludedField)) {
1076         return true;
1077       }
1078     }
1079     return false;
1080   }
1081
1082   private boolean excludeThisForItEndsWith(String[] excludedStrings, String className) {
1083     for (String excludedField : excludedStrings) {
1084       if (className.endsWith(excludedField)) {
1085         return true;
1086       }
1087     }
1088     return false;
1089   }
1090
1091   private boolean excludeThisForItStartsWith(String[] excludedStrings, String className) {
1092     for (String excludedField : excludedStrings) {
1093       if (className.startsWith(excludedField)) {
1094         return true;
1095       }
1096     }
1097     return false;
1098   }
1099
1100   private void exploreNextBacktrackPoints(VM vm, IntChoiceFromSet icsCG) {
1101                 // Check if we are reaching the end of our execution: no more backtracking points to explore
1102                 // cgMap, backtrackMap, backtrackStateQ are updated simultaneously (checking backtrackStateQ is enough)
1103                 if (!backtrackStateQ.isEmpty()) {
1104                         // Set done all the other backtrack points
1105                         for (TransitionEvent backtrackTransition : currentExecution.getExecutionTrace()) {
1106         backtrackTransition.getTransitionCG().setDone();
1107                         }
1108                         // Reset the next backtrack point with the latest state
1109                         int hiStateId = backtrackStateQ.peek();
1110                         // Restore the state first if necessary
1111                         if (vm.getStateId() != hiStateId) {
1112                                 RestorableVMState restorableState = restorableStateMap.get(hiStateId);
1113                                 vm.restoreState(restorableState);
1114                         }
1115                         // Set the backtrack CG
1116                         IntChoiceFromSet backtrackCG = (IntChoiceFromSet) vm.getChoiceGenerator();
1117                         setBacktrackCG(hiStateId, backtrackCG);
1118                 } else {
1119                         // Set done this last CG (we save a few rounds)
1120                         icsCG.setDone();
1121                 }
1122                 // Save all the visited states when starting a new execution of trace
1123                 prevVisitedStates.addAll(currVisitedStates);
1124                 // This marks a transitional period to the new CG
1125                 isEndOfExecution = true;
1126   }
1127
1128   private boolean isConflictFound(Execution execution, int reachableChoice, Execution conflictExecution, int conflictChoice,
1129                                   ReadWriteSet currRWSet) {
1130     // conflictExecution/conflictChoice represent a predecessor event/transaction that can potentially have a conflict
1131     ArrayList<TransitionEvent> executionTrace = execution.getExecutionTrace();
1132     ArrayList<TransitionEvent> conflictTrace = conflictExecution.getExecutionTrace();
1133     HashMap<Integer, ReadWriteSet> confRWFieldsMap = conflictExecution.getReadWriteFieldsMap();
1134     // Skip if this event does not have any Read/Write set or the two events are basically the same event (number)
1135     if (!confRWFieldsMap.containsKey(conflictChoice) ||
1136             executionTrace.get(reachableChoice).getChoice() == conflictTrace.get(conflictChoice).getChoice()) {
1137       return false;
1138     }
1139     // R/W set of choice/event that may have a potential conflict
1140     ReadWriteSet confRWSet = confRWFieldsMap.get(conflictChoice);
1141     // Check for conflicts with Read and Write fields for Write instructions
1142     Set<String> currWriteSet = currRWSet.getWriteSet();
1143     for(String writeField : currWriteSet) {
1144       int currObjId = currRWSet.writeFieldObjectId(writeField);
1145       if ((confRWSet.readFieldExists(writeField) && confRWSet.readFieldObjectId(writeField) == currObjId) ||
1146           (confRWSet.writeFieldExists(writeField) && confRWSet.writeFieldObjectId(writeField) == currObjId)) {
1147         // Remove this from the write set as we are tracking per memory location
1148         currRWSet.removeWriteField(writeField);
1149         return true;
1150       }
1151     }
1152     // Check for conflicts with Write fields for Read instructions
1153     Set<String> currReadSet = currRWSet.getReadSet();
1154     for(String readField : currReadSet) {
1155       int currObjId = currRWSet.readFieldObjectId(readField);
1156       if (confRWSet.writeFieldExists(readField) && confRWSet.writeFieldObjectId(readField) == currObjId) {
1157         // Remove this from the read set as we are tracking per memory location
1158         currRWSet.removeReadField(readField);
1159         return true;
1160       }
1161     }
1162     // Return false if no conflict is found
1163     return false;
1164   }
1165
1166   private ReadWriteSet getReadWriteSet(int currentChoice) {
1167     // Do the analysis to get Read and Write accesses to fields
1168     ReadWriteSet rwSet;
1169     // We already have an entry
1170     HashMap<Integer, ReadWriteSet> currReadWriteFieldsMap = currentExecution.getReadWriteFieldsMap();
1171     if (currReadWriteFieldsMap.containsKey(currentChoice)) {
1172       rwSet = currReadWriteFieldsMap.get(currentChoice);
1173     } else { // We need to create a new entry
1174       rwSet = new ReadWriteSet();
1175       currReadWriteFieldsMap.put(currentChoice, rwSet);
1176     }
1177     return rwSet;
1178   }
1179
1180   private boolean isFieldExcluded(Instruction executedInsn) {
1181     // Get the field info
1182     FieldInfo fieldInfo = ((JVMFieldInstruction) executedInsn).getFieldInfo();
1183     // Check if the non-relevant fields set already has it
1184     if (nonRelevantFields.contains(fieldInfo)) {
1185       return true;
1186     }
1187     // Check if the relevant fields set already has it
1188     if (relevantFields.contains(fieldInfo)) {
1189       return false;
1190     }
1191     // Analyze only after being initialized
1192     String field = fieldInfo.getFullName();
1193     // Check against "starts-with", "ends-with", and "contains" list
1194     if (excludeThisForItStartsWith(EXCLUDED_FIELDS_STARTS_WITH_LIST, field) ||
1195             excludeThisForItEndsWith(EXCLUDED_FIELDS_ENDS_WITH_LIST, field) ||
1196             excludeThisForItContains(EXCLUDED_FIELDS_CONTAINS_LIST, field)) {
1197       nonRelevantFields.add(fieldInfo);
1198       return true;
1199     }
1200     relevantFields.add(fieldInfo);
1201     return false;
1202   }
1203
1204   // Check if this trace is already constructed
1205   private boolean isTraceAlreadyConstructed(int firstChoice, int stateId) {
1206     // Concatenate state ID and only the first event in the string, e.g., "1:1 for the trace 10234 at state 1"
1207     // Check if the trace has been constructed as a backtrack point for this state
1208     // TODO: THIS IS AN OPTIMIZATION!
1209     HashSet<Integer> choiceSet;
1210     if (doneBacktrackMap.containsKey(stateId)) {
1211       choiceSet = doneBacktrackMap.get(stateId);
1212       if (choiceSet.contains(firstChoice)) {
1213         return true;
1214       }
1215     } else {
1216       choiceSet = new HashSet<>();
1217       doneBacktrackMap.put(stateId, choiceSet);
1218     }
1219     choiceSet.add(firstChoice);
1220
1221     return false;
1222   }
1223
1224   // Reset data structure for each new execution
1225   private void resetStatesForNewExecution(IntChoiceFromSet icsCG, VM vm) {
1226     if (choices == null || choices != icsCG.getAllChoices()) {
1227       // Reset state variables
1228       choiceCounter = 0;
1229       choices = icsCG.getAllChoices();
1230       refChoices = copyChoices(choices);
1231       // Clear data structures
1232       currVisitedStates = new HashSet<>();
1233       stateToEventMap = new HashMap<>();
1234       isEndOfExecution = false;
1235     }
1236   }
1237
1238   // Set a backtrack point for a particular state
1239   private void setBacktrackCG(int stateId, IntChoiceFromSet backtrackCG) {
1240     // Set a backtrack CG based on a state ID
1241     LinkedList<BacktrackExecution> backtrackExecutions = backtrackMap.get(stateId);
1242     BacktrackExecution backtrackExecution = backtrackExecutions.removeLast();
1243     backtrackCG.setNewValues(backtrackExecution.getChoiceList());  // Get the last from the queue
1244     backtrackCG.setStateId(stateId);
1245     backtrackCG.reset();
1246     // Update current execution with this new execution
1247     Execution newExecution = new Execution();
1248     TransitionEvent firstTransition = backtrackExecution.getFirstTransition();
1249     newExecution.addTransition(firstTransition);
1250     // Try to free some memory since this map is only used for the current execution
1251     currentExecution.clearCGToChoiceMap();
1252     currentExecution = newExecution;
1253     // Remove from the queue if we don't have more backtrack points for that state
1254     if (backtrackExecutions.isEmpty()) {
1255       backtrackMap.remove(stateId);
1256       backtrackStateQ.remove(stateId);
1257     }
1258   }
1259
1260   // Update backtrack sets
1261   // 1) recursively, and
1262   // 2) track accesses per memory location (per shared variable/field)
1263   private void updateBacktrackSet(Execution execution, int currentChoice) {
1264     // Copy ReadWriteSet object
1265     HashMap<Integer, ReadWriteSet> currRWFieldsMap = execution.getReadWriteFieldsMap();
1266     ReadWriteSet currRWSet = currRWFieldsMap.get(currentChoice);
1267     if (currRWSet == null) {
1268       return;
1269     }
1270     currRWSet = currRWSet.getCopy();
1271     // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1272     HashSet<TransitionEvent> visited = new HashSet<>();
1273     // Update backtrack set recursively
1274     // TODO: The following is the call to the original version of the method
1275 //    updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, currRWSet, visited);
1276     // TODO: The following is the call to the version of the method with pushing up happens-before transitions
1277     updateBacktrackSetRecursive(execution, currentChoice, execution, currentChoice, currRWSet, visited);
1278   }
1279
1280 //  TODO: This is the original version of the recursive method
1281 //  private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1282 //                                           Execution conflictExecution, int conflictChoice,
1283 //                                           ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1284 //    // Halt when we have found the first read/write conflicts for all memory locations
1285 //    if (currRWSet.isEmpty()) {
1286 //      return;
1287 //    }
1288 //    TransitionEvent confTrans = conflictExecution.getExecutionTrace().get(conflictChoice);
1289 //    // Halt when we have visited this transition (in a cycle)
1290 //    if (visited.contains(confTrans)) {
1291 //      return;
1292 //    }
1293 //    visited.add(confTrans);
1294 //    // Explore all predecessors
1295 //    for (Predecessor predecessor : confTrans.getPredecessors()) {
1296 //      // Get the predecessor (previous conflict choice)
1297 //      conflictChoice = predecessor.getChoice();
1298 //      conflictExecution = predecessor.getExecution();
1299 //      // Check if a conflict is found
1300 //      if (isConflictFound(execution, currentChoice, conflictExecution, conflictChoice, currRWSet)) {
1301 //        createBacktrackingPoint(execution, currentChoice, conflictExecution, conflictChoice);
1302 //      }
1303 //      // Continue performing DFS if conflict is not found
1304 //      updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice, currRWSet, visited);
1305 //    }
1306 //  }
1307
1308   // TODO: This is the version of the method with pushing up happens-before transitions
1309   private void updateBacktrackSetRecursive(Execution execution, int currentChoice,
1310                                            Execution conflictExecution, int conflictChoice,
1311                                            ReadWriteSet currRWSet, HashSet<TransitionEvent> visited) {
1312     TransitionEvent currTrans = execution.getExecutionTrace().get(currentChoice);
1313     // TODO: THIS IS THE ACCESS SUMMARY
1314     TransitionEvent confTrans = conflictExecution.getExecutionTrace().get(conflictChoice);
1315     // Record this transition into rGraph summary
1316     //currRWSet = rGraph.recordTransitionSummary(currTrans.getStateId(), confTrans, currRWSet);
1317     currRWSet = currTrans.recordTransitionSummary(confTrans, currRWSet);
1318     rGraph.recordTransitionSummaryAtState(currTrans.getStateId(), currTrans.getTransitionSummary());
1319     // Halt when we have found the first read/write conflicts for all memory locations
1320     if (currRWSet.isEmpty()) {
1321       return;
1322     }
1323     if (visited.contains(currTrans)) {
1324       return;
1325     }
1326     visited.add(currTrans);
1327     // Explore all predecessors
1328     for (Predecessor predecessor : currTrans.getPredecessors()) {
1329       // Get the predecessor (previous conflict choice)
1330       int predecessorChoice = predecessor.getChoice();
1331       Execution predecessorExecution = predecessor.getExecution();
1332       // Push up one happens-before transition
1333       int newConflictChoice = conflictChoice;
1334       Execution newConflictExecution = conflictExecution;
1335       // Check if a conflict is found
1336       if (isConflictFound(conflictExecution, conflictChoice, predecessorExecution, predecessorChoice, currRWSet)) {
1337         createBacktrackingPoint(conflictExecution, conflictChoice, predecessorExecution, predecessorChoice);
1338         newConflictChoice = conflictChoice;
1339         newConflictExecution = conflictExecution;
1340       }
1341       // Continue performing DFS if conflict is not found
1342       updateBacktrackSetRecursive(predecessorExecution, predecessorChoice, newConflictExecution, newConflictChoice,
1343               currRWSet, visited);
1344     }
1345     // Remove the transition after being explored
1346     // TODO: Seems to cause a lot of loops---commented out for now
1347     //visited.remove(confTrans);
1348   }
1349
1350   // --- Functions related to the reachability analysis when there is a state match
1351
1352   /*private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
1353     // Perform this analysis only when:
1354     // 1) this is not during a switch to a new execution,
1355     // 2) at least 2 choices/events have been explored (choiceCounter > 1),
1356     // 3) state > 0 (state 0 is for boolean CG)
1357     if (!isEndOfExecution && choiceCounter > 1 && stateId > 0) {
1358       if (currVisitedStates.contains(stateId) || prevVisitedStates.contains(stateId)) {
1359         // Update reachable transitions in the graph with a predecessor
1360         HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitionsAtState(stateId);
1361         for(TransitionEvent transition : reachableTransitions) {
1362           transition.recordPredecessor(currentExecution, choiceCounter - 1);
1363         }
1364         updateBacktrackSetsFromPreviousExecution(stateId);
1365       }
1366     }
1367   }
1368
1369   // Update the backtrack sets from previous executions
1370   private void updateBacktrackSetsFromPreviousExecution(int stateId) {
1371     // Collect all the reachable transitions from R-Graph
1372     HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitions(stateId);
1373     for(TransitionEvent transition : reachableTransitions) {
1374       Execution execution = transition.getExecution();
1375       int currentChoice = transition.getChoiceCounter();
1376       updateBacktrackSet(execution, currentChoice);
1377     }
1378   }*/
1379
1380   // TODO: THIS IS THE ACCESS SUMMARY
1381   private void analyzeReachabilityAndCreateBacktrackPoints(VM vm, int stateId) {
1382     // Perform this analysis only when:
1383     // 1) this is not during a switch to a new execution,
1384     // 2) at least 2 choices/events have been explored (choiceCounter > 1),
1385     // 3) state > 0 (state 0 is for boolean CG)
1386     if (!isEndOfExecution && choiceCounter > 1 && stateId > 0) {
1387       if (currVisitedStates.contains(stateId) || prevVisitedStates.contains(stateId)) {
1388         // Update reachable transitions in the graph with a predecessor
1389         HashSet<TransitionEvent> reachableTransitions = rGraph.getReachableTransitionsAtState(stateId);
1390         for(TransitionEvent transition : reachableTransitions) {
1391           transition.recordPredecessor(currentExecution, choiceCounter - 1);
1392         }
1393         updateBacktrackSetsFromPreviousExecution(currentExecution, choiceCounter - 1, stateId);
1394       }
1395     }
1396   }
1397
1398   private void updateBacktrackSetsFromPreviousExecution(Execution execution, int currentChoice, int stateId) {
1399     // Collect all the reachable transitions from R-Graph
1400     HashMap<Integer, SummaryNode> reachableTransitions = rGraph.getReachableTransitionSummary(stateId);
1401     for(Map.Entry<Integer, SummaryNode> transition : reachableTransitions.entrySet()) {
1402       SummaryNode summaryNode = transition.getValue();
1403       TransitionEvent reachableTransition = summaryNode.getTransitionEvent();
1404       Execution conflictExecution = reachableTransition.getExecution();
1405       int conflictChoice = reachableTransition.getChoiceCounter();
1406       // Copy ReadWriteSet object
1407       ReadWriteSet currRWSet = summaryNode.getReadWriteSet();
1408       currRWSet = currRWSet.getCopy();
1409       // Memorize visited TransitionEvent object while performing backward DFS to avoid getting caught up in a cycle
1410       HashSet<TransitionEvent> visited = new HashSet<>();
1411       updateBacktrackSetRecursive(execution, currentChoice, conflictExecution, conflictChoice, currRWSet, visited);
1412     }
1413   }
1414 }