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