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