add comments
[c11tester.git] / model.cc
1 #include <stdio.h>
2 #include <algorithm>
3
4 #include "model.h"
5 #include "action.h"
6 #include "nodestack.h"
7 #include "schedule.h"
8 #include "snapshot-interface.h"
9 #include "common.h"
10 #include "clockvector.h"
11 #include "cyclegraph.h"
12 #include "promise.h"
13 #include "datarace.h"
14 #include "mutex.h"
15
16 #define INITIAL_THREAD_ID       0
17
18 ModelChecker *model;
19
20 /** @brief Constructor */
21 ModelChecker::ModelChecker(struct model_params params) :
22         /* Initialize default scheduler */
23         params(params),
24         scheduler(new Scheduler()),
25         num_executions(0),
26         num_feasible_executions(0),
27         diverge(NULL),
28         action_trace(new action_list_t()),
29         thread_map(new HashTable<int, Thread *, int>()),
30         obj_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
31         lock_waiters_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
32         obj_thrd_map(new HashTable<void *, std::vector<action_list_t>, uintptr_t, 4 >()),
33         promises(new std::vector<Promise *>()),
34         futurevalues(new std::vector<struct PendingFutureValue>()),
35         lazy_sync_with_release(new HashTable<void *, action_list_t, uintptr_t, 4>()),
36         thrd_last_action(new std::vector<ModelAction *>(1)),
37         node_stack(new NodeStack()),
38         mo_graph(new CycleGraph()),
39         failed_promise(false),
40         too_many_reads(false),
41         asserted(false)
42 {
43         /* Allocate this "size" on the snapshotting heap */
44         priv = (struct model_snapshot_members *)calloc(1, sizeof(*priv));
45         /* First thread created will have id INITIAL_THREAD_ID */
46         priv->next_thread_id = INITIAL_THREAD_ID;
47
48         lazy_sync_size = &priv->lazy_sync_size;
49 }
50
51 /** @brief Destructor */
52 ModelChecker::~ModelChecker()
53 {
54         for (int i = 0; i < get_num_threads(); i++)
55                 delete thread_map->get(i);
56         delete thread_map;
57
58         delete obj_thrd_map;
59         delete obj_map;
60         delete lock_waiters_map;
61         delete action_trace;
62
63         for (unsigned int i = 0; i < promises->size(); i++)
64                 delete (*promises)[i];
65         delete promises;
66
67         delete lazy_sync_with_release;
68
69         delete thrd_last_action;
70         delete node_stack;
71         delete scheduler;
72         delete mo_graph;
73 }
74
75 /**
76  * Restores user program to initial state and resets all model-checker data
77  * structures.
78  */
79 void ModelChecker::reset_to_initial_state()
80 {
81         DEBUG("+++ Resetting to initial state +++\n");
82         node_stack->reset_execution();
83         failed_promise = false;
84         too_many_reads = false;
85         reset_asserted();
86         snapshotObject->backTrackBeforeStep(0);
87 }
88
89 /** @return a thread ID for a new Thread */
90 thread_id_t ModelChecker::get_next_id()
91 {
92         return priv->next_thread_id++;
93 }
94
95 /** @return the number of user threads created during this execution */
96 int ModelChecker::get_num_threads()
97 {
98         return priv->next_thread_id;
99 }
100
101 /** @return a sequence number for a new ModelAction */
102 modelclock_t ModelChecker::get_next_seq_num()
103 {
104         return ++priv->used_sequence_numbers;
105 }
106
107 /**
108  * @brief Choose the next thread to execute.
109  *
110  * This function chooses the next thread that should execute. It can force the
111  * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
112  * followed by a THREAD_START, or it can enforce execution replay/backtracking.
113  * The model-checker may have no preference regarding the next thread (i.e.,
114  * when exploring a new execution ordering), in which case this will return
115  * NULL.
116  * @param curr The current ModelAction. This action might guide the choice of
117  * next thread.
118  * @return The next thread to run. If the model-checker has no preference, NULL.
119  */
120 Thread * ModelChecker::get_next_thread(ModelAction *curr)
121 {
122         thread_id_t tid;
123
124         if (curr!=NULL) {
125                 /* Do not split atomic actions. */
126                 if (curr->is_rmwr())
127                         return thread_current();
128                 /* The THREAD_CREATE action points to the created Thread */
129                 else if (curr->get_type() == THREAD_CREATE)
130                         return (Thread *)curr->get_location();
131         }
132
133         /* Have we completed exploring the preselected path? */
134         if (diverge == NULL)
135                 return NULL;
136
137         /* Else, we are trying to replay an execution */
138         ModelAction *next = node_stack->get_next()->get_action();
139
140         if (next == diverge) {
141                 Node *nextnode = next->get_node();
142                 /* Reached divergence point */
143                 if (nextnode->increment_promise()) {
144                         /* The next node will try to satisfy a different set of promises. */
145                         tid = next->get_tid();
146                         node_stack->pop_restofstack(2);
147                 } else if (nextnode->increment_read_from()) {
148                         /* The next node will read from a different value. */
149                         tid = next->get_tid();
150                         node_stack->pop_restofstack(2);
151                 } else if (nextnode->increment_future_value()) {
152                         /* The next node will try to read from a different future value. */
153                         tid = next->get_tid();
154                         node_stack->pop_restofstack(2);
155                 } else {
156                         /* Make a different thread execute for next step */
157                         Node *node = nextnode->get_parent();
158                         tid = node->get_next_backtrack();
159                         node_stack->pop_restofstack(1);
160                 }
161                 DEBUG("*** Divergence point ***\n");
162                 diverge = NULL;
163         } else {
164                 tid = next->get_tid();
165         }
166         DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
167         ASSERT(tid != THREAD_ID_T_NONE);
168         return thread_map->get(id_to_int(tid));
169 }
170
171 /**
172  * Queries the model-checker for more executions to explore and, if one
173  * exists, resets the model-checker state to execute a new execution.
174  *
175  * @return If there are more executions to explore, return true. Otherwise,
176  * return false.
177  */
178 bool ModelChecker::next_execution()
179 {
180         DBG();
181
182         num_executions++;
183         if (isfinalfeasible())
184                 num_feasible_executions++;
185
186         if (isfinalfeasible() || DBG_ENABLED())
187                 print_summary();
188
189         if ((diverge = get_next_backtrack()) == NULL)
190                 return false;
191
192         if (DBG_ENABLED()) {
193                 printf("Next execution will diverge at:\n");
194                 diverge->print();
195         }
196
197         reset_to_initial_state();
198         return true;
199 }
200
201 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
202 {
203         switch (act->get_type()) {
204         case ATOMIC_READ:
205         case ATOMIC_WRITE:
206         case ATOMIC_RMW: {
207                 /* linear search: from most recent to oldest */
208                 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
209                 action_list_t::reverse_iterator rit;
210                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
211                         ModelAction *prev = *rit;
212                         if (act->is_synchronizing(prev))
213                                 return prev;
214                 }
215                 break;
216         }
217         case ATOMIC_LOCK:
218         case ATOMIC_TRYLOCK: {
219                 /* linear search: from most recent to oldest */
220                 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
221                 action_list_t::reverse_iterator rit;
222                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
223                         ModelAction *prev = *rit;
224                         if (act->is_conflicting_lock(prev))
225                                 return prev;
226                 }
227                 break;
228         }
229         case ATOMIC_UNLOCK: {
230                 /* linear search: from most recent to oldest */
231                 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
232                 action_list_t::reverse_iterator rit;
233                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
234                         ModelAction *prev = *rit;
235                         if (!act->same_thread(prev)&&prev->is_failed_trylock())
236                                 return prev;
237                 }
238                 break;
239         }
240         default:
241                 break;
242         }
243         return NULL;
244 }
245
246 /** This method find backtracking points where we should try to
247  * reorder the parameter ModelAction against.
248  *
249  * @param the ModelAction to find backtracking points for.
250  */
251
252
253 void ModelChecker::set_backtracking(ModelAction *act)
254 {
255         Thread *t = get_thread(act);
256         ModelAction * prev = get_last_conflict(act);
257         if (prev == NULL)
258                 return;
259
260         Node * node = prev->get_node()->get_parent();
261
262         int low_tid, high_tid;
263         if (node->is_enabled(t)) {
264                 low_tid = id_to_int(act->get_tid());
265                 high_tid = low_tid+1;
266         } else {
267                 low_tid = 0;
268                 high_tid = get_num_threads();
269         }
270
271         for(int i = low_tid; i < high_tid; i++) {
272                 thread_id_t tid = int_to_id(i);
273                 if (!node->is_enabled(tid))
274                         continue;
275
276                 /* Check if this has been explored already */
277                 if (node->has_been_explored(tid))
278                         continue;
279
280                 /* See if fairness allows */
281                 if (model->params.fairwindow != 0 && !node->has_priority(tid)) {
282                         bool unfair=false;
283                         for(int t=0;t<node->get_num_threads();t++) {
284                                 thread_id_t tother=int_to_id(t);
285                                 if (node->is_enabled(tother) && node->has_priority(tother)) {
286                                         unfair=true;
287                                         break;
288                                 }
289                         }
290                         if (unfair)
291                                 continue;
292                 }
293
294                 /* Cache the latest backtracking point */
295                 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
296                         priv->next_backtrack = prev;
297
298                 /* If this is a new backtracking point, mark the tree */
299                 if (!node->set_backtrack(tid))
300                         continue;
301                 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
302                                         prev->get_tid(), t->get_id());
303                 if (DBG_ENABLED()) {
304                         prev->print();
305                         act->print();
306                 }
307         }
308 }
309
310 /**
311  * Returns last backtracking point. The model checker will explore a different
312  * path for this point in the next execution.
313  * @return The ModelAction at which the next execution should diverge.
314  */
315 ModelAction * ModelChecker::get_next_backtrack()
316 {
317         ModelAction *next = priv->next_backtrack;
318         priv->next_backtrack = NULL;
319         return next;
320 }
321
322 /**
323  * Processes a read or rmw model action.
324  * @param curr is the read model action to process.
325  * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
326  * @return True if processing this read updates the mo_graph.
327  */
328 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
329 {
330         uint64_t value;
331         bool updated = false;
332         while (true) {
333                 const ModelAction *reads_from = curr->get_node()->get_read_from();
334                 if (reads_from != NULL) {
335                         mo_graph->startChanges();
336
337                         value = reads_from->get_value();
338                         bool r_status = false;
339
340                         if (!second_part_of_rmw) {
341                                 check_recency(curr);
342                                 r_status = r_modification_order(curr, reads_from);
343                         }
344
345
346                         if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
347                                 mo_graph->rollbackChanges();
348                                 too_many_reads = false;
349                                 continue;
350                         }
351
352                         curr->read_from(reads_from);
353                         mo_graph->commitChanges();
354                         updated |= r_status;
355                 } else if (!second_part_of_rmw) {
356                         /* Read from future value */
357                         value = curr->get_node()->get_future_value();
358                         modelclock_t expiration = curr->get_node()->get_future_value_expiration();
359                         curr->read_from(NULL);
360                         Promise *valuepromise = new Promise(curr, value, expiration);
361                         promises->push_back(valuepromise);
362                 }
363                 get_thread(curr)->set_return_value(value);
364                 return updated;
365         }
366 }
367
368 /**
369  * Processes a lock, trylock, or unlock model action.  @param curr is
370  * the read model action to process.
371  *
372  * The try lock operation checks whether the lock is taken.  If not,
373  * it falls to the normal lock operation case.  If so, it returns
374  * fail.
375  *
376  * The lock operation has already been checked that it is enabled, so
377  * it just grabs the lock and synchronizes with the previous unlock.
378  *
379  * The unlock operation has to re-enable all of the threads that are
380  * waiting on the lock.
381  */
382 void ModelChecker::process_mutex(ModelAction *curr) {
383         std::mutex *mutex = (std::mutex *)curr->get_location();
384         struct std::mutex_state *state = mutex->get_state();
385         switch (curr->get_type()) {
386         case ATOMIC_TRYLOCK: {
387                 bool success = !state->islocked;
388                 curr->set_try_lock(success);
389                 if (!success) {
390                         get_thread(curr)->set_return_value(0);
391                         break;
392                 }
393                 get_thread(curr)->set_return_value(1);
394         }
395                 //otherwise fall into the lock case
396         case ATOMIC_LOCK: {
397                 if (curr->get_cv()->getClock(state->alloc_tid) <= state->alloc_clock) {
398                         printf("Lock access before initialization\n");
399                         set_assert();
400                 }
401                 state->islocked = true;
402                 ModelAction *unlock = get_last_unlock(curr);
403                 //synchronize with the previous unlock statement
404                 if (unlock != NULL)
405                         curr->synchronize_with(unlock);
406                 break;
407         }
408         case ATOMIC_UNLOCK: {
409                 //unlock the lock
410                 state->islocked = false;
411                 //wake up the other threads
412                 action_list_t *waiters = lock_waiters_map->get_safe_ptr(curr->get_location());
413                 //activate all the waiting threads
414                 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
415                         scheduler->add_thread(get_thread((*rit)->get_tid()));
416                 }
417                 waiters->clear();
418                 break;
419         }
420         default:
421                 ASSERT(0);
422         }
423 }
424
425 /**
426  * Process a write ModelAction
427  * @param curr The ModelAction to process
428  * @return True if the mo_graph was updated or promises were resolved
429  */
430 bool ModelChecker::process_write(ModelAction *curr)
431 {
432         bool updated_mod_order = w_modification_order(curr);
433         bool updated_promises = resolve_promises(curr);
434
435         if (promises->size() == 0) {
436                 for (unsigned int i = 0; i < futurevalues->size(); i++) {
437                         struct PendingFutureValue pfv = (*futurevalues)[i];
438                         if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
439                                         (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
440                                 priv->next_backtrack = pfv.act;
441                 }
442                 futurevalues->resize(0);
443         }
444
445         mo_graph->commitChanges();
446         get_thread(curr)->set_return_value(VALUE_NONE);
447         return updated_mod_order || updated_promises;
448 }
449
450 /**
451  * Initialize the current action by performing one or more of the following
452  * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
453  * in the NodeStack, manipulating backtracking sets, allocating and
454  * initializing clock vectors, and computing the promises to fulfill.
455  *
456  * @param curr The current action, as passed from the user context; may be
457  * freed/invalidated after the execution of this function
458  * @return The current action, as processed by the ModelChecker. Is only the
459  * same as the parameter @a curr if this is a newly-explored action.
460  */
461 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
462 {
463         ModelAction *newcurr;
464
465         if (curr->is_rmwc() || curr->is_rmw()) {
466                 newcurr = process_rmw(curr);
467                 delete curr;
468                 compute_promises(newcurr);
469                 return newcurr;
470         }
471
472         newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
473         if (newcurr) {
474                 /* First restore type and order in case of RMW operation */
475                 if (curr->is_rmwr())
476                         newcurr->copy_typeandorder(curr);
477
478                 ASSERT(curr->get_location() == newcurr->get_location());
479                 newcurr->copy_from_new(curr);
480
481                 /* Discard duplicate ModelAction; use action from NodeStack */
482                 delete curr;
483
484                 /* If we have diverged, we need to reset the clock vector. */
485                 if (diverge == NULL)
486                         newcurr->create_cv(get_parent_action(newcurr->get_tid()));
487         } else {
488                 newcurr = curr;
489                 /*
490                  * Perform one-time actions when pushing new ModelAction onto
491                  * NodeStack
492                  */
493                 curr->create_cv(get_parent_action(curr->get_tid()));
494                 if (curr->is_write())
495                         compute_promises(curr);
496         }
497         return newcurr;
498 }
499
500 /**
501  * This method checks whether a model action is enabled at the given point.
502  * At this point, it checks whether a lock operation would be successful at this point.
503  * If not, it puts the thread in a waiter list.
504  * @param curr is the ModelAction to check whether it is enabled.
505  * @return a bool that indicates whether the action is enabled.
506  */
507
508 bool ModelChecker::check_action_enabled(ModelAction *curr) {
509         if (curr->is_lock()) {
510                 std::mutex * lock = (std::mutex *)curr->get_location();
511                 struct std::mutex_state * state = lock->get_state();
512                 if (state->islocked) {
513                         //Stick the action in the appropriate waiting queue
514                         lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
515                         return false;
516                 }
517         }
518
519         return true;
520 }
521
522 /**
523  * This is the heart of the model checker routine. It performs model-checking
524  * actions corresponding to a given "current action." Among other processes, it
525  * calculates reads-from relationships, updates synchronization clock vectors,
526  * forms a memory_order constraints graph, and handles replay/backtrack
527  * execution when running permutations of previously-observed executions.
528  *
529  * @param curr The current action to process
530  * @return The next Thread that must be executed. May be NULL if ModelChecker
531  * makes no choice (e.g., according to replay execution, combining RMW actions,
532  * etc.)
533  */
534 Thread * ModelChecker::check_current_action(ModelAction *curr)
535 {
536         ASSERT(curr);
537
538         bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
539
540         if (!check_action_enabled(curr)) {
541                 //we'll make the execution look like we chose to run this action
542                 //much later...when a lock is actually available to relese
543                 get_current_thread()->set_pending(curr);
544                 remove_thread(get_current_thread());
545                 return get_next_thread(NULL);
546         }
547
548         ModelAction *newcurr = initialize_curr_action(curr);
549
550         /* Add the action to lists before any other model-checking tasks */
551         if (!second_part_of_rmw)
552                 add_action_to_lists(newcurr);
553
554         /* Build may_read_from set for newly-created actions */
555         if (curr == newcurr && curr->is_read())
556                 build_reads_from_past(curr);
557         curr = newcurr;
558
559         /* Thread specific actions */
560         switch (curr->get_type()) {
561         case THREAD_CREATE: {
562                 Thread *th = (Thread *)curr->get_location();
563                 th->set_creation(curr);
564                 break;
565         }
566         case THREAD_JOIN: {
567                 Thread *waiting, *blocking;
568                 waiting = get_thread(curr);
569                 blocking = (Thread *)curr->get_location();
570                 if (!blocking->is_complete()) {
571                         blocking->push_wait_list(curr);
572                         scheduler->sleep(waiting);
573                 } else {
574                         do_complete_join(curr);
575                 }
576                 break;
577         }
578         case THREAD_FINISH: {
579                 Thread *th = get_thread(curr);
580                 while (!th->wait_list_empty()) {
581                         ModelAction *act = th->pop_wait_list();
582                         Thread *wake = get_thread(act);
583                         scheduler->wake(wake);
584                         do_complete_join(act);
585                 }
586                 th->complete();
587                 break;
588         }
589         case THREAD_START: {
590                 check_promises(NULL, curr->get_cv());
591                 break;
592         }
593         default:
594                 break;
595         }
596
597         work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
598
599         while (!work_queue.empty()) {
600                 WorkQueueEntry work = work_queue.front();
601                 work_queue.pop_front();
602
603                 switch (work.type) {
604                 case WORK_CHECK_CURR_ACTION: {
605                         ModelAction *act = work.action;
606                         bool updated = false;
607                         if (act->is_read() && process_read(act, second_part_of_rmw))
608                                 updated = true;
609
610                         if (act->is_write() && process_write(act))
611                                 updated = true;
612
613                         if (act->is_mutex_op())
614                                 process_mutex(act);
615
616                         if (updated)
617                                 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
618                         break;
619                 }
620                 case WORK_CHECK_RELEASE_SEQ:
621                         resolve_release_sequences(work.location, &work_queue);
622                         break;
623                 case WORK_CHECK_MO_EDGES: {
624                         /** @todo Complete verification of work_queue */
625                         ModelAction *act = work.action;
626                         bool updated = false;
627
628                         if (act->is_read()) {
629                                 if (r_modification_order(act, act->get_reads_from()))
630                                         updated = true;
631                         }
632                         if (act->is_write()) {
633                                 if (w_modification_order(act))
634                                         updated = true;
635                         }
636
637                         if (updated)
638                                 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
639                         break;
640                 }
641                 default:
642                         ASSERT(false);
643                         break;
644                 }
645         }
646
647         check_curr_backtracking(curr);
648
649         set_backtracking(curr);
650
651         return get_next_thread(curr);
652 }
653
654 /**
655  * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
656  * operation from the Thread it is joining with. Must be called after the
657  * completion of the Thread in question.
658  * @param join The THREAD_JOIN action
659  */
660 void ModelChecker::do_complete_join(ModelAction *join)
661 {
662         Thread *blocking = (Thread *)join->get_location();
663         ModelAction *act = get_last_action(blocking->get_id());
664         join->synchronize_with(act);
665 }
666
667 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
668         Node *currnode = curr->get_node();
669         Node *parnode = currnode->get_parent();
670
671         if ((!parnode->backtrack_empty() ||
672                          !currnode->read_from_empty() ||
673                          !currnode->future_value_empty() ||
674                          !currnode->promise_empty())
675                         && (!priv->next_backtrack ||
676                                         *curr > *priv->next_backtrack)) {
677                 priv->next_backtrack = curr;
678         }
679 }
680
681 bool ModelChecker::promises_expired() {
682         for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
683                 Promise *promise = (*promises)[promise_index];
684                 if (promise->get_expiration()<priv->used_sequence_numbers) {
685                         return true;
686                 }
687         }
688         return false;
689 }
690
691 /** @return whether the current partial trace must be a prefix of a
692  * feasible trace. */
693 bool ModelChecker::isfeasibleprefix() {
694         return promises->size() == 0 && *lazy_sync_size == 0;
695 }
696
697 /** @return whether the current partial trace is feasible. */
698 bool ModelChecker::isfeasible() {
699         return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
700 }
701
702 /** @return whether the current partial trace is feasible other than
703  * multiple RMW reading from the same store. */
704 bool ModelChecker::isfeasibleotherthanRMW() {
705         if (DBG_ENABLED()) {
706                 if (mo_graph->checkForCycles())
707                         DEBUG("Infeasible: modification order cycles\n");
708                 if (failed_promise)
709                         DEBUG("Infeasible: failed promise\n");
710                 if (too_many_reads)
711                         DEBUG("Infeasible: too many reads\n");
712                 if (promises_expired())
713                         DEBUG("Infeasible: promises expired\n");
714         }
715         return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !promises_expired();
716 }
717
718 /** Returns whether the current completed trace is feasible. */
719 bool ModelChecker::isfinalfeasible() {
720         if (DBG_ENABLED() && promises->size() != 0)
721                 DEBUG("Infeasible: unrevolved promises\n");
722
723         return isfeasible() && promises->size() == 0;
724 }
725
726 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
727 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
728         int tid = id_to_int(act->get_tid());
729         ModelAction *lastread = get_last_action(tid);
730         lastread->process_rmw(act);
731         if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
732                 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
733                 mo_graph->commitChanges();
734         }
735         return lastread;
736 }
737
738 /**
739  * Checks whether a thread has read from the same write for too many times
740  * without seeing the effects of a later write.
741  *
742  * Basic idea:
743  * 1) there must a different write that we could read from that would satisfy the modification order,
744  * 2) we must have read from the same value in excess of maxreads times, and
745  * 3) that other write must have been in the reads_from set for maxreads times.
746  *
747  * If so, we decide that the execution is no longer feasible.
748  */
749 void ModelChecker::check_recency(ModelAction *curr) {
750         if (params.maxreads != 0) {
751                 if (curr->get_node()->get_read_from_size() <= 1)
752                         return;
753
754                 //Must make sure that execution is currently feasible...  We could
755                 //accidentally clear by rolling back
756                 if (!isfeasible())
757                         return;
758
759                 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
760                 int tid = id_to_int(curr->get_tid());
761
762                 /* Skip checks */
763                 if ((int)thrd_lists->size() <= tid)
764                         return;
765
766                 action_list_t *list = &(*thrd_lists)[tid];
767
768                 action_list_t::reverse_iterator rit = list->rbegin();
769                 /* Skip past curr */
770                 for (; (*rit) != curr; rit++)
771                         ;
772                 /* go past curr now */
773                 rit++;
774
775                 action_list_t::reverse_iterator ritcopy = rit;
776                 //See if we have enough reads from the same value
777                 int count = 0;
778                 for (; count < params.maxreads; rit++,count++) {
779                         if (rit==list->rend())
780                                 return;
781                         ModelAction *act = *rit;
782                         if (!act->is_read())
783                                 return;
784                         if (act->get_reads_from() != curr->get_reads_from())
785                                 return;
786                         if (act->get_node()->get_read_from_size() <= 1)
787                                 return;
788                 }
789
790                 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
791                         //Get write
792                         const ModelAction * write = curr->get_node()->get_read_from_at(i);
793                         //Need a different write
794                         if (write==curr->get_reads_from())
795                                 continue;
796
797                         /* Test to see whether this is a feasible write to read from*/
798                         mo_graph->startChanges();
799                         r_modification_order(curr, write);
800                         bool feasiblereadfrom = isfeasible();
801                         mo_graph->rollbackChanges();
802
803                         if (!feasiblereadfrom)
804                                 continue;
805                         rit = ritcopy;
806
807                         bool feasiblewrite = true;
808                         //new we need to see if this write works for everyone
809
810                         for (int loop = count; loop>0; loop--,rit++) {
811                                 ModelAction *act=*rit;
812                                 bool foundvalue = false;
813                                 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
814                                         if (act->get_node()->get_read_from_at(i)==write) {
815                                                 foundvalue = true;
816                                                 break;
817                                         }
818                                 }
819                                 if (!foundvalue) {
820                                         feasiblewrite = false;
821                                         break;
822                                 }
823                         }
824                         if (feasiblewrite) {
825                                 too_many_reads = true;
826                                 return;
827                         }
828                 }
829         }
830 }
831
832 /**
833  * Updates the mo_graph with the constraints imposed from the current
834  * read.
835  *
836  * Basic idea is the following: Go through each other thread and find
837  * the lastest action that happened before our read.  Two cases:
838  *
839  * (1) The action is a write => that write must either occur before
840  * the write we read from or be the write we read from.
841  *
842  * (2) The action is a read => the write that that action read from
843  * must occur before the write we read from or be the same write.
844  *
845  * @param curr The current action. Must be a read.
846  * @param rf The action that curr reads from. Must be a write.
847  * @return True if modification order edges were added; false otherwise
848  */
849 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
850 {
851         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
852         unsigned int i;
853         bool added = false;
854         ASSERT(curr->is_read());
855
856         /* Iterate over all threads */
857         for (i = 0; i < thrd_lists->size(); i++) {
858                 /* Iterate over actions in thread, starting from most recent */
859                 action_list_t *list = &(*thrd_lists)[i];
860                 action_list_t::reverse_iterator rit;
861                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
862                         ModelAction *act = *rit;
863
864                         /*
865                          * Include at most one act per-thread that "happens
866                          * before" curr. Don't consider reflexively.
867                          */
868                         if (act->happens_before(curr) && act != curr) {
869                                 if (act->is_write()) {
870                                         if (rf != act) {
871                                                 mo_graph->addEdge(act, rf);
872                                                 added = true;
873                                         }
874                                 } else {
875                                         const ModelAction *prevreadfrom = act->get_reads_from();
876                                         if (prevreadfrom != NULL && rf != prevreadfrom) {
877                                                 mo_graph->addEdge(prevreadfrom, rf);
878                                                 added = true;
879                                         }
880                                 }
881                                 break;
882                         }
883                 }
884         }
885
886         return added;
887 }
888
889 /** This method fixes up the modification order when we resolve a
890  *  promises.  The basic problem is that actions that occur after the
891  *  read curr could not property add items to the modification order
892  *  for our read.
893  *
894  *  So for each thread, we find the earliest item that happens after
895  *  the read curr.  This is the item we have to fix up with additional
896  *  constraints.  If that action is write, we add a MO edge between
897  *  the Action rf and that action.  If the action is a read, we add a
898  *  MO edge between the Action rf, and whatever the read accessed.
899  *
900  * @param curr is the read ModelAction that we are fixing up MO edges for.
901  * @param rf is the write ModelAction that curr reads from.
902  *
903  */
904
905 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
906 {
907         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
908         unsigned int i;
909         ASSERT(curr->is_read());
910
911         /* Iterate over all threads */
912         for (i = 0; i < thrd_lists->size(); i++) {
913                 /* Iterate over actions in thread, starting from most recent */
914                 action_list_t *list = &(*thrd_lists)[i];
915                 action_list_t::reverse_iterator rit;
916                 ModelAction *lastact = NULL;
917
918                 /* Find last action that happens after curr */
919                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
920                         ModelAction *act = *rit;
921                         if (curr->happens_before(act)) {
922                                 lastact = act;
923                         } else
924                                 break;
925                 }
926
927                         /* Include at most one act per-thread that "happens before" curr */
928                 if (lastact != NULL) {
929                         if (lastact->is_read()) {
930                                 const ModelAction *postreadfrom = lastact->get_reads_from();
931                                 if (postreadfrom != NULL&&rf != postreadfrom)
932                                         mo_graph->addEdge(rf, postreadfrom);
933                         } else if (rf != lastact) {
934                                 mo_graph->addEdge(rf, lastact);
935                         }
936                         break;
937                 }
938         }
939 }
940
941 /**
942  * Updates the mo_graph with the constraints imposed from the current write.
943  *
944  * Basic idea is the following: Go through each other thread and find
945  * the lastest action that happened before our write.  Two cases:
946  *
947  * (1) The action is a write => that write must occur before
948  * the current write
949  *
950  * (2) The action is a read => the write that that action read from
951  * must occur before the current write.
952  *
953  * This method also handles two other issues:
954  *
955  * (I) Sequential Consistency: Making sure that if the current write is
956  * seq_cst, that it occurs after the previous seq_cst write.
957  *
958  * (II) Sending the write back to non-synchronizing reads.
959  *
960  * @param curr The current action. Must be a write.
961  * @return True if modification order edges were added; false otherwise
962  */
963 bool ModelChecker::w_modification_order(ModelAction *curr)
964 {
965         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
966         unsigned int i;
967         bool added = false;
968         ASSERT(curr->is_write());
969
970         if (curr->is_seqcst()) {
971                 /* We have to at least see the last sequentially consistent write,
972                          so we are initialized. */
973                 ModelAction *last_seq_cst = get_last_seq_cst(curr);
974                 if (last_seq_cst != NULL) {
975                         mo_graph->addEdge(last_seq_cst, curr);
976                         added = true;
977                 }
978         }
979
980         /* Iterate over all threads */
981         for (i = 0; i < thrd_lists->size(); i++) {
982                 /* Iterate over actions in thread, starting from most recent */
983                 action_list_t *list = &(*thrd_lists)[i];
984                 action_list_t::reverse_iterator rit;
985                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
986                         ModelAction *act = *rit;
987                         if (act == curr) {
988                                 /*
989                                  * If RMW, we already have all relevant edges,
990                                  * so just skip to next thread.
991                                  * If normal write, we need to look at earlier
992                                  * actions, so continue processing list.
993                                  */
994                                 if (curr->is_rmw())
995                                         break;
996                                 else
997                                         continue;
998                         }
999
1000                         /*
1001                          * Include at most one act per-thread that "happens
1002                          * before" curr
1003                          */
1004                         if (act->happens_before(curr)) {
1005                                 /*
1006                                  * Note: if act is RMW, just add edge:
1007                                  *   act --mo--> curr
1008                                  * The following edge should be handled elsewhere:
1009                                  *   readfrom(act) --mo--> act
1010                                  */
1011                                 if (act->is_write())
1012                                         mo_graph->addEdge(act, curr);
1013                                 else if (act->is_read() && act->get_reads_from() != NULL)
1014                                         mo_graph->addEdge(act->get_reads_from(), curr);
1015                                 added = true;
1016                                 break;
1017                         } else if (act->is_read() && !act->is_synchronizing(curr) &&
1018                                                      !act->same_thread(curr)) {
1019                                 /* We have an action that:
1020                                    (1) did not happen before us
1021                                    (2) is a read and we are a write
1022                                    (3) cannot synchronize with us
1023                                    (4) is in a different thread
1024                                    =>
1025                                    that read could potentially read from our write.
1026                                  */
1027                                 if (thin_air_constraint_may_allow(curr, act)) {
1028                                         if (isfeasible() ||
1029                                                         (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() == act->get_reads_from() && isfeasibleotherthanRMW())) {
1030                                                 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
1031                                                 futurevalues->push_back(pfv);
1032                                         }
1033                                 }
1034                         }
1035                 }
1036         }
1037
1038         return added;
1039 }
1040
1041 /** Arbitrary reads from the future are not allowed.  Section 29.3
1042  * part 9 places some constraints.  This method checks one result of constraint
1043  * constraint.  Others require compiler support. */
1044
1045 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
1046         if (!writer->is_rmw())
1047                 return true;
1048
1049         if (!reader->is_rmw())
1050                 return true;
1051
1052         for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1053                 if (search == reader)
1054                         return false;
1055                 if (search->get_tid() == reader->get_tid() &&
1056                                 search->happens_before(reader))
1057                         break;
1058         }
1059
1060         return true;
1061 }
1062
1063 /**
1064  * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1065  * The ModelAction under consideration is expected to be taking part in
1066  * release/acquire synchronization as an object of the "reads from" relation.
1067  * Note that this can only provide release sequence support for RMW chains
1068  * which do not read from the future, as those actions cannot be traced until
1069  * their "promise" is fulfilled. Similarly, we may not even establish the
1070  * presence of a release sequence with certainty, as some modification order
1071  * constraints may be decided further in the future. Thus, this function
1072  * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1073  * and a boolean representing certainty.
1074  *
1075  * @todo Finish lazy updating, when promises are fulfilled in the future
1076  * @param rf The action that might be part of a release sequence. Must be a
1077  * write.
1078  * @param release_heads A pass-by-reference style return parameter.  After
1079  * execution of this function, release_heads will contain the heads of all the
1080  * relevant release sequences, if any exists
1081  * @return true, if the ModelChecker is certain that release_heads is complete;
1082  * false otherwise
1083  */
1084 bool ModelChecker::release_seq_head(const ModelAction *rf, rel_heads_list_t *release_heads) const
1085 {
1086         if (!rf) {
1087                 /* read from future: need to settle this later */
1088                 return false; /* incomplete */
1089         }
1090
1091         ASSERT(rf->is_write());
1092
1093         if (rf->is_release())
1094                 release_heads->push_back(rf);
1095         if (rf->is_rmw()) {
1096                 /* We need a RMW action that is both an acquire and release to stop */
1097                 /** @todo Need to be smarter here...  In the linux lock
1098                  * example, this will run to the beginning of the program for
1099                  * every acquire. */
1100                 /** @todo The way to be smarter here is to keep going until 1
1101                  * thread has a release preceded by an acquire and you've seen
1102                  *       both. */
1103
1104                 if (rf->is_acquire() && rf->is_release())
1105                         return true; /* complete */
1106
1107                 /** @todo Might it be better to make this into a loop... */
1108
1109                 return release_seq_head(rf->get_reads_from(), release_heads);
1110         }
1111         if (rf->is_release())
1112                 return true; /* complete */
1113
1114         /* else relaxed write; check modification order for contiguous subsequence
1115          * -> rf must be same thread as release */
1116         int tid = id_to_int(rf->get_tid());
1117         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1118         action_list_t *list = &(*thrd_lists)[tid];
1119         action_list_t::const_reverse_iterator rit;
1120
1121         /* Find rf in the thread list */
1122         rit = std::find(list->rbegin(), list->rend(), rf);
1123         ASSERT(rit != list->rend());
1124
1125         /* Find the last write/release */
1126         for (; rit != list->rend(); rit++)
1127                 if ((*rit)->is_release())
1128                         break;
1129         if (rit == list->rend()) {
1130                 /* No write-release in this thread */
1131                 return true; /* complete */
1132         }
1133         ModelAction *release = *rit;
1134
1135         ASSERT(rf->same_thread(release));
1136
1137         bool certain = true;
1138         for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1139                 if (id_to_int(rf->get_tid()) == (int)i)
1140                         continue;
1141                 list = &(*thrd_lists)[i];
1142
1143                 /* Can we ensure no future writes from this thread may break
1144                  * the release seq? */
1145                 bool future_ordered = false;
1146
1147                 ModelAction *last = get_last_action(int_to_id(i));
1148                 if (last && rf->happens_before(last))
1149                         future_ordered = true;
1150
1151                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1152                         const ModelAction *act = *rit;
1153                         /* Reach synchronization -> this thread is complete */
1154                         if (act->happens_before(release))
1155                                 break;
1156                         if (rf->happens_before(act)) {
1157                                 future_ordered = true;
1158                                 continue;
1159                         }
1160
1161                         /* Only writes can break release sequences */
1162                         if (!act->is_write())
1163                                 continue;
1164
1165                         /* Check modification order */
1166                         if (mo_graph->checkReachable(rf, act)) {
1167                                 /* rf --mo--> act */
1168                                 future_ordered = true;
1169                                 continue;
1170                         }
1171                         if (mo_graph->checkReachable(act, release))
1172                                 /* act --mo--> release */
1173                                 break;
1174                         if (mo_graph->checkReachable(release, act) &&
1175                                       mo_graph->checkReachable(act, rf)) {
1176                                 /* release --mo-> act --mo--> rf */
1177                                 return true; /* complete */
1178                         }
1179                         certain = false;
1180                 }
1181                 if (!future_ordered)
1182                         return false; /* This thread is uncertain */
1183         }
1184
1185         if (certain)
1186                 release_heads->push_back(release);
1187         return certain;
1188 }
1189
1190 /**
1191  * A public interface for getting the release sequence head(s) with which a
1192  * given ModelAction must synchronize. This function only returns a non-empty
1193  * result when it can locate a release sequence head with certainty. Otherwise,
1194  * it may mark the internal state of the ModelChecker so that it will handle
1195  * the release sequence at a later time, causing @a act to update its
1196  * synchronization at some later point in execution.
1197  * @param act The 'acquire' action that may read from a release sequence
1198  * @param release_heads A pass-by-reference return parameter. Will be filled
1199  * with the head(s) of the release sequence(s), if they exists with certainty.
1200  * @see ModelChecker::release_seq_head
1201  */
1202 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1203 {
1204         const ModelAction *rf = act->get_reads_from();
1205         bool complete;
1206         complete = release_seq_head(rf, release_heads);
1207         if (!complete) {
1208                 /* add act to 'lazy checking' list */
1209                 action_list_t *list;
1210                 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
1211                 list->push_back(act);
1212                 (*lazy_sync_size)++;
1213         }
1214 }
1215
1216 /**
1217  * Attempt to resolve all stashed operations that might synchronize with a
1218  * release sequence for a given location. This implements the "lazy" portion of
1219  * determining whether or not a release sequence was contiguous, since not all
1220  * modification order information is present at the time an action occurs.
1221  *
1222  * @param location The location/object that should be checked for release
1223  * sequence resolutions
1224  * @param work_queue The work queue to which to add work items as they are
1225  * generated
1226  * @return True if any updates occurred (new synchronization, new mo_graph
1227  * edges)
1228  */
1229 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1230 {
1231         action_list_t *list;
1232         list = lazy_sync_with_release->getptr(location);
1233         if (!list)
1234                 return false;
1235
1236         bool updated = false;
1237         action_list_t::iterator it = list->begin();
1238         while (it != list->end()) {
1239                 ModelAction *act = *it;
1240                 const ModelAction *rf = act->get_reads_from();
1241                 rel_heads_list_t release_heads;
1242                 bool complete;
1243                 complete = release_seq_head(rf, &release_heads);
1244                 for (unsigned int i = 0; i < release_heads.size(); i++) {
1245                         if (!act->has_synchronized_with(release_heads[i])) {
1246                                 updated = true;
1247                                 act->synchronize_with(release_heads[i]);
1248                         }
1249                 }
1250
1251                 if (updated) {
1252                         /* Re-check act for mo_graph edges */
1253                         work_queue->push_back(MOEdgeWorkEntry(act));
1254
1255                         /* propagate synchronization to later actions */
1256                         action_list_t::reverse_iterator it = action_trace->rbegin();
1257                         for (; (*it) != act; it++) {
1258                                 ModelAction *propagate = *it;
1259                                 if (act->happens_before(propagate)) {
1260                                         propagate->synchronize_with(act);
1261                                         /* Re-check 'propagate' for mo_graph edges */
1262                                         work_queue->push_back(MOEdgeWorkEntry(propagate));
1263                                 }
1264                         }
1265                 }
1266                 if (complete) {
1267                         it = list->erase(it);
1268                         (*lazy_sync_size)--;
1269                 } else
1270                         it++;
1271         }
1272
1273         // If we resolved promises or data races, see if we have realized a data race.
1274         if (checkDataRaces()) {
1275                 set_assert();
1276         }
1277
1278         return updated;
1279 }
1280
1281 /**
1282  * Performs various bookkeeping operations for the current ModelAction. For
1283  * instance, adds action to the per-object, per-thread action vector and to the
1284  * action trace list of all thread actions.
1285  *
1286  * @param act is the ModelAction to add.
1287  */
1288 void ModelChecker::add_action_to_lists(ModelAction *act)
1289 {
1290         int tid = id_to_int(act->get_tid());
1291         action_trace->push_back(act);
1292
1293         obj_map->get_safe_ptr(act->get_location())->push_back(act);
1294
1295         std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1296         if (tid >= (int)vec->size())
1297                 vec->resize(priv->next_thread_id);
1298         (*vec)[tid].push_back(act);
1299
1300         if ((int)thrd_last_action->size() <= tid)
1301                 thrd_last_action->resize(get_num_threads());
1302         (*thrd_last_action)[tid] = act;
1303 }
1304
1305 /**
1306  * @brief Get the last action performed by a particular Thread
1307  * @param tid The thread ID of the Thread in question
1308  * @return The last action in the thread
1309  */
1310 ModelAction * ModelChecker::get_last_action(thread_id_t tid) const
1311 {
1312         int threadid = id_to_int(tid);
1313         if (threadid < (int)thrd_last_action->size())
1314                 return (*thrd_last_action)[id_to_int(tid)];
1315         else
1316                 return NULL;
1317 }
1318
1319 /**
1320  * Gets the last memory_order_seq_cst write (in the total global sequence)
1321  * performed on a particular object (i.e., memory location), not including the
1322  * current action.
1323  * @param curr The current ModelAction; also denotes the object location to
1324  * check
1325  * @return The last seq_cst write
1326  */
1327 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr) const
1328 {
1329         void *location = curr->get_location();
1330         action_list_t *list = obj_map->get_safe_ptr(location);
1331         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1332         action_list_t::reverse_iterator rit;
1333         for (rit = list->rbegin(); rit != list->rend(); rit++)
1334                 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1335                         return *rit;
1336         return NULL;
1337 }
1338
1339 /**
1340  * Gets the last unlock operation performed on a particular mutex (i.e., memory
1341  * location). This function identifies the mutex according to the current
1342  * action, which is presumed to perform on the same mutex.
1343  * @param curr The current ModelAction; also denotes the object location to
1344  * check
1345  * @return The last unlock operation
1346  */
1347 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr) const
1348 {
1349         void *location = curr->get_location();
1350         action_list_t *list = obj_map->get_safe_ptr(location);
1351         /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
1352         action_list_t::reverse_iterator rit;
1353         for (rit = list->rbegin(); rit != list->rend(); rit++)
1354                 if ((*rit)->is_unlock())
1355                         return *rit;
1356         return NULL;
1357 }
1358
1359 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1360 {
1361         ModelAction *parent = get_last_action(tid);
1362         if (!parent)
1363                 parent = get_thread(tid)->get_creation();
1364         return parent;
1365 }
1366
1367 /**
1368  * Returns the clock vector for a given thread.
1369  * @param tid The thread whose clock vector we want
1370  * @return Desired clock vector
1371  */
1372 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1373 {
1374         return get_parent_action(tid)->get_cv();
1375 }
1376
1377 /**
1378  * Resolve a set of Promises with a current write. The set is provided in the
1379  * Node corresponding to @a write.
1380  * @param write The ModelAction that is fulfilling Promises
1381  * @return True if promises were resolved; false otherwise
1382  */
1383 bool ModelChecker::resolve_promises(ModelAction *write)
1384 {
1385         bool resolved = false;
1386
1387         for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1388                 Promise *promise = (*promises)[promise_index];
1389                 if (write->get_node()->get_promise(i)) {
1390                         ModelAction *read = promise->get_action();
1391                         read->read_from(write);
1392                         if (read->is_rmw()) {
1393                                 mo_graph->addRMWEdge(write, read);
1394                         }
1395                         //First fix up the modification order for actions that happened
1396                         //before the read
1397                         r_modification_order(read, write);
1398                         //Next fix up the modification order for actions that happened
1399                         //after the read.
1400                         post_r_modification_order(read, write);
1401                         promises->erase(promises->begin() + promise_index);
1402                         resolved = true;
1403                 } else
1404                         promise_index++;
1405         }
1406         return resolved;
1407 }
1408
1409 /**
1410  * Compute the set of promises that could potentially be satisfied by this
1411  * action. Note that the set computation actually appears in the Node, not in
1412  * ModelChecker.
1413  * @param curr The ModelAction that may satisfy promises
1414  */
1415 void ModelChecker::compute_promises(ModelAction *curr)
1416 {
1417         for (unsigned int i = 0; i < promises->size(); i++) {
1418                 Promise *promise = (*promises)[i];
1419                 const ModelAction *act = promise->get_action();
1420                 if (!act->happens_before(curr) &&
1421                                 act->is_read() &&
1422                                 !act->is_synchronizing(curr) &&
1423                                 !act->same_thread(curr) &&
1424                                 promise->get_value() == curr->get_value()) {
1425                         curr->get_node()->set_promise(i);
1426                 }
1427         }
1428 }
1429
1430 /** Checks promises in response to change in ClockVector Threads. */
1431 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1432 {
1433         for (unsigned int i = 0; i < promises->size(); i++) {
1434                 Promise *promise = (*promises)[i];
1435                 const ModelAction *act = promise->get_action();
1436                 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1437                                 merge_cv->synchronized_since(act)) {
1438                         //This thread is no longer able to send values back to satisfy the promise
1439                         int num_synchronized_threads = promise->increment_threads();
1440                         if (num_synchronized_threads == get_num_threads()) {
1441                                 //Promise has failed
1442                                 failed_promise = true;
1443                                 return;
1444                         }
1445                 }
1446         }
1447 }
1448
1449 /**
1450  * Build up an initial set of all past writes that this 'read' action may read
1451  * from. This set is determined by the clock vector's "happens before"
1452  * relationship.
1453  * @param curr is the current ModelAction that we are exploring; it must be a
1454  * 'read' operation.
1455  */
1456 void ModelChecker::build_reads_from_past(ModelAction *curr)
1457 {
1458         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1459         unsigned int i;
1460         ASSERT(curr->is_read());
1461
1462         ModelAction *last_seq_cst = NULL;
1463
1464         /* Track whether this object has been initialized */
1465         bool initialized = false;
1466
1467         if (curr->is_seqcst()) {
1468                 last_seq_cst = get_last_seq_cst(curr);
1469                 /* We have to at least see the last sequentially consistent write,
1470                          so we are initialized. */
1471                 if (last_seq_cst != NULL)
1472                         initialized = true;
1473         }
1474
1475         /* Iterate over all threads */
1476         for (i = 0; i < thrd_lists->size(); i++) {
1477                 /* Iterate over actions in thread, starting from most recent */
1478                 action_list_t *list = &(*thrd_lists)[i];
1479                 action_list_t::reverse_iterator rit;
1480                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1481                         ModelAction *act = *rit;
1482
1483                         /* Only consider 'write' actions */
1484                         if (!act->is_write() || act == curr)
1485                                 continue;
1486
1487                         /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1488                         if (!curr->is_seqcst() || (!act->is_seqcst() && (last_seq_cst == NULL || !act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1489                                 DEBUG("Adding action to may_read_from:\n");
1490                                 if (DBG_ENABLED()) {
1491                                         act->print();
1492                                         curr->print();
1493                                 }
1494                                 curr->get_node()->add_read_from(act);
1495                         }
1496
1497                         /* Include at most one act per-thread that "happens before" curr */
1498                         if (act->happens_before(curr)) {
1499                                 initialized = true;
1500                                 break;
1501                         }
1502                 }
1503         }
1504
1505         if (!initialized) {
1506                 /** @todo Need a more informative way of reporting errors. */
1507                 printf("ERROR: may read from uninitialized atomic\n");
1508         }
1509
1510         if (DBG_ENABLED() || !initialized) {
1511                 printf("Reached read action:\n");
1512                 curr->print();
1513                 printf("Printing may_read_from\n");
1514                 curr->get_node()->print_may_read_from();
1515                 printf("End printing may_read_from\n");
1516         }
1517
1518         ASSERT(initialized);
1519 }
1520
1521 static void print_list(action_list_t *list)
1522 {
1523         action_list_t::iterator it;
1524
1525         printf("---------------------------------------------------------------------\n");
1526         printf("Trace:\n");
1527
1528         for (it = list->begin(); it != list->end(); it++) {
1529                 (*it)->print();
1530         }
1531         printf("---------------------------------------------------------------------\n");
1532 }
1533
1534 void ModelChecker::print_summary()
1535 {
1536         printf("\n");
1537         printf("Number of executions: %d\n", num_executions);
1538         printf("Number of feasible executions: %d\n", num_feasible_executions);
1539         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1540
1541 #if SUPPORT_MOD_ORDER_DUMP
1542         scheduler->print();
1543         char buffername[100];
1544         sprintf(buffername, "exec%04u", num_executions);
1545         mo_graph->dumpGraphToFile(buffername);
1546 #endif
1547
1548         if (!isfinalfeasible())
1549                 printf("INFEASIBLE EXECUTION!\n");
1550         print_list(action_trace);
1551         printf("\n");
1552 }
1553
1554 /**
1555  * Add a Thread to the system for the first time. Should only be called once
1556  * per thread.
1557  * @param t The Thread to add
1558  */
1559 void ModelChecker::add_thread(Thread *t)
1560 {
1561         thread_map->put(id_to_int(t->get_id()), t);
1562         scheduler->add_thread(t);
1563 }
1564
1565 /**
1566  * Removes a thread from the scheduler. 
1567  * @param the thread to remove.
1568  */
1569
1570 void ModelChecker::remove_thread(Thread *t)
1571 {
1572         scheduler->remove_thread(t);
1573 }
1574
1575 /**
1576  * Switch from a user-context to the "master thread" context (a.k.a. system
1577  * context). This switch is made with the intention of exploring a particular
1578  * model-checking action (described by a ModelAction object). Must be called
1579  * from a user-thread context.
1580  * @param act The current action that will be explored. Must not be NULL.
1581  * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1582  */
1583 int ModelChecker::switch_to_master(ModelAction *act)
1584 {
1585         DBG();
1586         Thread *old = thread_current();
1587         set_current_action(act);
1588         old->set_state(THREAD_READY);
1589         return Thread::swap(old, &system_context);
1590 }
1591
1592 /**
1593  * Takes the next step in the execution, if possible.
1594  * @return Returns true (success) if a step was taken and false otherwise.
1595  */
1596 bool ModelChecker::take_step() {
1597         if (has_asserted())
1598                 return false;
1599
1600         Thread * curr = thread_current();
1601         if (curr) {
1602                 if (curr->get_state() == THREAD_READY) {
1603                         ASSERT(priv->current_action);
1604
1605                         priv->nextThread = check_current_action(priv->current_action);
1606                         priv->current_action = NULL;
1607                         if (curr->is_blocked() || curr->is_complete())
1608                                 scheduler->remove_thread(curr);
1609                 } else {
1610                         ASSERT(false);
1611                 }
1612         }
1613         Thread * next = scheduler->next_thread(priv->nextThread);
1614
1615         /* Infeasible -> don't take any more steps */
1616         if (!isfeasible())
1617                 return false;
1618
1619         if (next)
1620                 next->set_state(THREAD_RUNNING);
1621         DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1622
1623         /* next == NULL -> don't take any more steps */
1624         if (!next)
1625                 return false;
1626
1627         if ( next->get_pending() != NULL ) {
1628                 //restart a pending action
1629                 set_current_action(next->get_pending());
1630                 next->set_pending(NULL);
1631                 next->set_state(THREAD_READY);
1632                 return true;
1633         }
1634
1635         /* Return false only if swap fails with an error */
1636         return (Thread::swap(&system_context, next) == 0);
1637 }
1638
1639 /** Runs the current execution until threre are no more steps to take. */
1640 void ModelChecker::finish_execution() {
1641         DBG();
1642
1643         while (take_step());
1644 }