action: print '?' for unknown read-from-future
[model-checker.git] / model.cc
1 #include <stdio.h>
2
3 #include "model.h"
4 #include "action.h"
5 #include "nodestack.h"
6 #include "schedule.h"
7 #include "snapshot-interface.h"
8 #include "common.h"
9 #include "clockvector.h"
10 #include "cyclegraph.h"
11 #include "promise.h"
12
13 #define INITIAL_THREAD_ID       0
14
15 ModelChecker *model;
16
17 /** @brief Constructor */
18 ModelChecker::ModelChecker(struct model_params params) :
19         /* Initialize default scheduler */
20         scheduler(new Scheduler()),
21         /* First thread created will have id INITIAL_THREAD_ID */
22         next_thread_id(INITIAL_THREAD_ID),
23         used_sequence_numbers(0),
24         num_executions(0),
25         params(params),
26         current_action(NULL),
27         diverge(NULL),
28         nextThread(THREAD_ID_T_NONE),
29         action_trace(new action_list_t()),
30         thread_map(new HashTable<int, Thread *, int>()),
31         obj_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         lazy_sync_with_release(new HashTable<void *, std::list<ModelAction *>, uintptr_t, 4>()),
35         thrd_last_action(new std::vector<ModelAction *>(1)),
36         node_stack(new NodeStack()),
37         next_backtrack(NULL),
38         mo_graph(new CycleGraph()),
39         failed_promise(false)
40 {
41 }
42
43 /** @brief Destructor */
44 ModelChecker::~ModelChecker()
45 {
46         for (int i = 0; i < get_num_threads(); i++)
47                 delete thread_map->get(i);
48         delete thread_map;
49
50         delete obj_thrd_map;
51         delete obj_map;
52         delete action_trace;
53
54         for (unsigned int i = 0; i < promises->size(); i++)
55                 delete (*promises)[i];
56         delete promises;
57
58         delete lazy_sync_with_release;
59
60         delete thrd_last_action;
61         delete node_stack;
62         delete scheduler;
63         delete mo_graph;
64 }
65
66 /**
67  * Restores user program to initial state and resets all model-checker data
68  * structures.
69  */
70 void ModelChecker::reset_to_initial_state()
71 {
72         DEBUG("+++ Resetting to initial state +++\n");
73         node_stack->reset_execution();
74         current_action = NULL;
75         next_thread_id = INITIAL_THREAD_ID;
76         used_sequence_numbers = 0;
77         nextThread = 0;
78         next_backtrack = NULL;
79         failed_promise = false;
80         snapshotObject->backTrackBeforeStep(0);
81 }
82
83 /** @returns a thread ID for a new Thread */
84 thread_id_t ModelChecker::get_next_id()
85 {
86         return next_thread_id++;
87 }
88
89 /** @returns the number of user threads created during this execution */
90 int ModelChecker::get_num_threads()
91 {
92         return next_thread_id;
93 }
94
95 /** @returns a sequence number for a new ModelAction */
96 modelclock_t ModelChecker::get_next_seq_num()
97 {
98         return ++used_sequence_numbers;
99 }
100
101 /**
102  * Performs the "scheduling" for the model-checker. That is, it checks if the
103  * model-checker has selected a "next thread to run" and returns it, if
104  * available. This function should be called from the Scheduler routine, where
105  * the Scheduler falls back to a default scheduling routine if needed.
106  *
107  * @return The next thread chosen by the model-checker. If the model-checker
108  * makes no selection, retuns NULL.
109  */
110 Thread * ModelChecker::schedule_next_thread()
111 {
112         Thread *t;
113         if (nextThread == THREAD_ID_T_NONE)
114                 return NULL;
115         t = thread_map->get(id_to_int(nextThread));
116
117         ASSERT(t != NULL);
118
119         return t;
120 }
121
122 /**
123  * Choose the next thread in the replay sequence.
124  *
125  * If the replay sequence has reached the 'diverge' point, returns a thread
126  * from the backtracking set. Otherwise, simply returns the next thread in the
127  * sequence that is being replayed.
128  */
129 thread_id_t ModelChecker::get_next_replay_thread()
130 {
131         thread_id_t tid;
132
133         /* Have we completed exploring the preselected path? */
134         if (diverge == NULL)
135                 return THREAD_ID_T_NONE;
136
137         /* Else, we are trying to replay an execution */
138         ModelAction *next = node_stack->get_next()->get_action();
139
140         if (next == diverge) {
141                 Node *nextnode = next->get_node();
142                 /* Reached divergence point */
143                 if (nextnode->increment_promise()) {
144                         /* The next node will try to satisfy a different set of promises. */
145                         tid = next->get_tid();
146                         node_stack->pop_restofstack(2);
147                 } else if (nextnode->increment_read_from()) {
148                         /* The next node will read from a different value. */
149                         tid = next->get_tid();
150                         node_stack->pop_restofstack(2);
151                 } else if (nextnode->increment_future_value()) {
152                         /* The next node will try to read from a different future value. */
153                         tid = next->get_tid();
154                         node_stack->pop_restofstack(2);
155                 } else {
156                         /* Make a different thread execute for next step */
157                         Node *node = nextnode->get_parent();
158                         tid = node->get_next_backtrack();
159                         node_stack->pop_restofstack(1);
160                 }
161                 DEBUG("*** Divergence point ***\n");
162                 diverge = NULL;
163         } else {
164                 tid = next->get_tid();
165         }
166         DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
167         return tid;
168 }
169
170 /**
171  * Queries the model-checker for more executions to explore and, if one
172  * exists, resets the model-checker state to execute a new execution.
173  *
174  * @return If there are more executions to explore, return true. Otherwise,
175  * return false.
176  */
177 bool ModelChecker::next_execution()
178 {
179         DBG();
180
181         num_executions++;
182
183         if (isfinalfeasible() || DBG_ENABLED())
184                 print_summary();
185
186         if ((diverge = model->get_next_backtrack()) == NULL)
187                 return false;
188
189         if (DBG_ENABLED()) {
190                 printf("Next execution will diverge at:\n");
191                 diverge->print();
192         }
193
194         model->reset_to_initial_state();
195         return true;
196 }
197
198 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
199 {
200         action_type type = act->get_type();
201
202         switch (type) {
203                 case ATOMIC_READ:
204                 case ATOMIC_WRITE:
205                 case ATOMIC_RMW:
206                         break;
207                 default:
208                         return NULL;
209         }
210         /* linear search: from most recent to oldest */
211         action_list_t *list = obj_map->get_safe_ptr(act->get_location());
212         action_list_t::reverse_iterator rit;
213         for (rit = list->rbegin(); rit != list->rend(); rit++) {
214                 ModelAction *prev = *rit;
215                 if (act->is_synchronizing(prev))
216                         return prev;
217         }
218         return NULL;
219 }
220
221 void ModelChecker::set_backtracking(ModelAction *act)
222 {
223         ModelAction *prev;
224         Node *node;
225         Thread *t = get_thread(act->get_tid());
226
227         prev = get_last_conflict(act);
228         if (prev == NULL)
229                 return;
230
231         node = prev->get_node()->get_parent();
232
233         while (!node->is_enabled(t))
234                 t = t->get_parent();
235
236         /* Check if this has been explored already */
237         if (node->has_been_explored(t->get_id()))
238                 return;
239
240         /* Cache the latest backtracking point */
241         if (!next_backtrack || *prev > *next_backtrack)
242                 next_backtrack = prev;
243
244         /* If this is a new backtracking point, mark the tree */
245         if (!node->set_backtrack(t->get_id()))
246                 return;
247         DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
248                         prev->get_tid(), t->get_id());
249         if (DBG_ENABLED()) {
250                 prev->print();
251                 act->print();
252         }
253 }
254
255 /**
256  * Returns last backtracking point. The model checker will explore a different
257  * path for this point in the next execution.
258  * @return The ModelAction at which the next execution should diverge.
259  */
260 ModelAction * ModelChecker::get_next_backtrack()
261 {
262         ModelAction *next = next_backtrack;
263         next_backtrack = NULL;
264         return next;
265 }
266
267 void ModelChecker::check_current_action(void)
268 {
269         ModelAction *curr = this->current_action;
270         bool already_added = false;
271         this->current_action = NULL;
272         if (!curr) {
273                 DEBUG("trying to push NULL action...\n");
274                 return;
275         }
276
277         if (curr->is_rmwc() || curr->is_rmw()) {
278                 ModelAction *tmp = process_rmw(curr);
279                 already_added = true;
280                 delete curr;
281                 curr = tmp;
282         } else {
283                 ModelAction *tmp = node_stack->explore_action(curr);
284                 if (tmp) {
285                         /* Discard duplicate ModelAction; use action from NodeStack */
286                         /* First restore type and order in case of RMW operation */
287                         if (curr->is_rmwr())
288                                 tmp->copy_typeandorder(curr);
289
290                         /* If we have diverged, we need to reset the clock vector. */
291                         if (diverge == NULL)
292                                 tmp->create_cv(get_parent_action(tmp->get_tid()));
293
294                         delete curr;
295                         curr = tmp;
296                 } else {
297                         /*
298                          * Perform one-time actions when pushing new ModelAction onto
299                          * NodeStack
300                          */
301                         curr->create_cv(get_parent_action(curr->get_tid()));
302                         /* Build may_read_from set */
303                         if (curr->is_read())
304                                 build_reads_from_past(curr);
305                         if (curr->is_write())
306                                 compute_promises(curr);
307                 }
308         }
309
310         /* Assign 'creation' parent */
311         if (curr->get_type() == THREAD_CREATE) {
312                 Thread *th = (Thread *)curr->get_location();
313                 th->set_creation(curr);
314         }
315
316         /* Deal with new thread */
317         if (curr->get_type() == THREAD_START)
318                 check_promises(NULL, curr->get_cv());
319
320         /* Assign reads_from values */
321         Thread *th = get_thread(curr->get_tid());
322         uint64_t value = VALUE_NONE;
323         bool updated = false;
324         if (curr->is_read()) {
325                 const ModelAction *reads_from = curr->get_node()->get_read_from();
326                 if (reads_from != NULL) {
327                         value = reads_from->get_value();
328                         /* Assign reads_from, perform release/acquire synchronization */
329                         curr->read_from(reads_from);
330                         if (r_modification_order(curr,reads_from))
331                                 updated = true;
332                 } else {
333                         /* Read from future value */
334                         value = curr->get_node()->get_future_value();
335                         curr->read_from(NULL);
336                         Promise *valuepromise = new Promise(curr, value);
337                         promises->push_back(valuepromise);
338                 }
339         } else if (curr->is_write()) {
340                 if (w_modification_order(curr))
341                         updated = true;;
342                 if (resolve_promises(curr))
343                         updated = true;
344         }
345
346         if (updated)
347                 resolve_release_sequences(curr->get_location());
348
349         th->set_return_value(value);
350
351         /* Add action to list.  */
352         if (!already_added)
353                 add_action_to_lists(curr);
354
355         /** @todo Is there a better interface for setting the next thread rather
356                  than this field/convoluted approach?  Perhaps like just returning
357                  it or something? */
358
359         /* Do not split atomic actions. */
360         if (curr->is_rmwr())
361                 nextThread = thread_current()->get_id();
362         else
363                 nextThread = get_next_replay_thread();
364
365         Node *currnode = curr->get_node();
366         Node *parnode = currnode->get_parent();
367
368         if (!parnode->backtrack_empty() || !currnode->read_from_empty() ||
369                   !currnode->future_value_empty() || !currnode->promise_empty())
370                 if (!next_backtrack || *curr > *next_backtrack)
371                         next_backtrack = curr;
372
373         set_backtracking(curr);
374 }
375
376 /** @returns whether the current partial trace is feasible. */
377 bool ModelChecker::isfeasible() {
378         return !mo_graph->checkForCycles() && !failed_promise;
379 }
380
381 /** Returns whether the current completed trace is feasible. */
382 bool ModelChecker::isfinalfeasible() {
383         return isfeasible() && promises->size() == 0;
384 }
385
386 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
387 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
388         int tid = id_to_int(act->get_tid());
389         ModelAction *lastread = get_last_action(tid);
390         lastread->process_rmw(act);
391         if (act->is_rmw())
392                 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
393         return lastread;
394 }
395
396 /**
397  * Updates the mo_graph with the constraints imposed from the current read.
398  * @param curr The current action. Must be a read.
399  * @param rf The action that curr reads from. Must be a write.
400  * @return True if modification order edges were added; false otherwise
401  */
402 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
403 {
404         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
405         unsigned int i;
406         bool added = false;
407         ASSERT(curr->is_read());
408
409         /* Iterate over all threads */
410         for (i = 0; i < thrd_lists->size(); i++) {
411                 /* Iterate over actions in thread, starting from most recent */
412                 action_list_t *list = &(*thrd_lists)[i];
413                 action_list_t::reverse_iterator rit;
414                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
415                         ModelAction *act = *rit;
416
417                         /* Include at most one act per-thread that "happens before" curr */
418                         if (act->happens_before(curr)) {
419                                 if (act->is_read()) {
420                                         const ModelAction *prevreadfrom = act->get_reads_from();
421                                         if (prevreadfrom != NULL && rf != prevreadfrom) {
422                                                 mo_graph->addEdge(prevreadfrom, rf);
423                                                 added = true;
424                                         }
425                                 } else if (rf != act) {
426                                         mo_graph->addEdge(act, rf);
427                                         added = true;
428                                 }
429                                 break;
430                         }
431                 }
432         }
433
434         return added;
435 }
436
437 /** Updates the mo_graph with the constraints imposed from the current read. */
438 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
439 {
440         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
441         unsigned int i;
442         ASSERT(curr->is_read());
443
444         /* Iterate over all threads */
445         for (i = 0; i < thrd_lists->size(); i++) {
446                 /* Iterate over actions in thread, starting from most recent */
447                 action_list_t *list = &(*thrd_lists)[i];
448                 action_list_t::reverse_iterator rit;
449                 ModelAction *lastact = NULL;
450
451                 /* Find last action that happens after curr */
452                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
453                         ModelAction *act = *rit;
454                         if (curr->happens_before(act)) {
455                                 lastact = act;
456                         } else
457                                 break;
458                 }
459
460                         /* Include at most one act per-thread that "happens before" curr */
461                 if (lastact != NULL) {
462                         if (lastact->is_read()) {
463                                 const ModelAction *postreadfrom = lastact->get_reads_from();
464                                 if (postreadfrom != NULL&&rf != postreadfrom)
465                                         mo_graph->addEdge(rf, postreadfrom);
466                         } else if (rf != lastact) {
467                                 mo_graph->addEdge(rf, lastact);
468                         }
469                         break;
470                 }
471         }
472 }
473
474 /**
475  * Updates the mo_graph with the constraints imposed from the current write.
476  * @param curr The current action. Must be a write.
477  * @return True if modification order edges were added; false otherwise
478  */
479 bool ModelChecker::w_modification_order(ModelAction *curr)
480 {
481         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
482         unsigned int i;
483         bool added = false;
484         ASSERT(curr->is_write());
485
486         if (curr->is_seqcst()) {
487                 /* We have to at least see the last sequentially consistent write,
488                          so we are initialized. */
489                 ModelAction *last_seq_cst = get_last_seq_cst(curr->get_location());
490                 if (last_seq_cst != NULL) {
491                         mo_graph->addEdge(last_seq_cst, curr);
492                         added = true;
493                 }
494         }
495
496         /* Iterate over all threads */
497         for (i = 0; i < thrd_lists->size(); i++) {
498                 /* Iterate over actions in thread, starting from most recent */
499                 action_list_t *list = &(*thrd_lists)[i];
500                 action_list_t::reverse_iterator rit;
501                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
502                         ModelAction *act = *rit;
503
504                         /* Include at most one act per-thread that "happens before" curr */
505                         if (act->happens_before(curr)) {
506                                 if (act->is_read())
507                                         mo_graph->addEdge(act->get_reads_from(), curr);
508                                 else
509                                         mo_graph->addEdge(act, curr);
510                                 added = true;
511                                 break;
512                         } else if (act->is_read() && !act->is_synchronizing(curr) &&
513                                                      !act->same_thread(curr)) {
514                                 /* We have an action that:
515                                    (1) did not happen before us
516                                    (2) is a read and we are a write
517                                    (3) cannot synchronize with us
518                                    (4) is in a different thread
519                                    =>
520                                    that read could potentially read from our write.
521                                  */
522                                 if (act->get_node()->add_future_value(curr->get_value()) &&
523                                                 (!next_backtrack || *act > *next_backtrack))
524                                         next_backtrack = act;
525                         }
526                 }
527         }
528
529         return added;
530 }
531
532 /**
533  * Finds the head(s) of the release sequence(s) containing a given ModelAction.
534  * The ModelAction under consideration is expected to be taking part in
535  * release/acquire synchronization as an object of the "reads from" relation.
536  * Note that this can only provide release sequence support for RMW chains
537  * which do not read from the future, as those actions cannot be traced until
538  * their "promise" is fulfilled. Similarly, we may not even establish the
539  * presence of a release sequence with certainty, as some modification order
540  * constraints may be decided further in the future. Thus, this function
541  * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
542  * and a boolean representing certainty.
543  *
544  * @todo Finish lazy updating, when promises are fulfilled in the future
545  * @param rf The action that might be part of a release sequence. Must be a
546  * write.
547  * @param release_heads A pass-by-reference style return parameter.  After
548  * execution of this function, release_heads will contain the heads of all the
549  * relevant release sequences, if any exists
550  * @return true, if the ModelChecker is certain that release_heads is complete;
551  * false otherwise
552  */
553 bool ModelChecker::release_seq_head(const ModelAction *rf,
554                 std::vector<const ModelAction *> *release_heads) const
555 {
556         ASSERT(rf->is_write());
557         if (!rf) {
558                 /* read from future: need to settle this later */
559                 return false; /* incomplete */
560         }
561         if (rf->is_release())
562                 release_heads->push_back(rf);
563         if (rf->is_rmw()) {
564                 if (rf->is_acquire())
565                         return true; /* complete */
566                 return release_seq_head(rf->get_reads_from(), release_heads);
567         }
568         if (rf->is_release())
569                 return true; /* complete */
570
571         /* else relaxed write; check modification order for contiguous subsequence
572          * -> rf must be same thread as release */
573         int tid = id_to_int(rf->get_tid());
574         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
575         action_list_t *list = &(*thrd_lists)[tid];
576         action_list_t::const_reverse_iterator rit;
577
578         /* Find rf in the thread list */
579         for (rit = list->rbegin(); rit != list->rend(); rit++)
580                 if (*rit == rf)
581                         break;
582
583         /* Find the last write/release */
584         for (; rit != list->rend(); rit++)
585                 if ((*rit)->is_release())
586                         break;
587         if (rit == list->rend()) {
588                 /* No write-release in this thread */
589                 return true; /* complete */
590         }
591         ModelAction *release = *rit;
592
593         ASSERT(rf->same_thread(release));
594
595         bool certain = true;
596         for (unsigned int i = 0; i < thrd_lists->size(); i++) {
597                 if (id_to_int(rf->get_tid()) == (int)i)
598                         continue;
599                 list = &(*thrd_lists)[i];
600                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
601                         const ModelAction *act = *rit;
602                         if (!act->is_write())
603                                 continue;
604                         /* Reach synchronization -> this thread is complete */
605                         if (act->happens_before(release))
606                                 break;
607                         if (rf->happens_before(act))
608                                 continue;
609
610                         /* Check modification order */
611                         if (mo_graph->checkReachable(rf, act))
612                                 /* rf --mo--> act */
613                                 continue;
614                         if (mo_graph->checkReachable(act, release))
615                                 /* act --mo--> release */
616                                 break;
617                         if (mo_graph->checkReachable(release, act) &&
618                                       mo_graph->checkReachable(act, rf)) {
619                                 /* release --mo-> act --mo--> rf */
620                                 return true; /* complete */
621                         }
622                         certain = false;
623                 }
624         }
625
626         if (certain)
627                 release_heads->push_back(release);
628         return certain;
629 }
630
631 /**
632  * A public interface for getting the release sequence head(s) with which a
633  * given ModelAction must synchronize. This function only returns a non-empty
634  * result when it can locate a release sequence head with certainty. Otherwise,
635  * it may mark the internal state of the ModelChecker so that it will handle
636  * the release sequence at a later time, causing @a act to update its
637  * synchronization at some later point in execution.
638  * @param act The 'acquire' action that may read from a release sequence
639  * @param release_heads A pass-by-reference return parameter. Will be filled
640  * with the head(s) of the release sequence(s), if they exists with certainty.
641  * @see ModelChecker::release_seq_head
642  */
643 void ModelChecker::get_release_seq_heads(ModelAction *act,
644                 std::vector<const ModelAction *> *release_heads)
645 {
646         const ModelAction *rf = act->get_reads_from();
647         bool complete;
648         complete = release_seq_head(rf, release_heads);
649         if (!complete) {
650                 /* add act to 'lazy checking' list */
651                 std::list<ModelAction *> *list;
652                 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
653                 list->push_back(act);
654         }
655 }
656
657 /**
658  * Attempt to resolve all stashed operations that might synchronize with a
659  * release sequence for a given location. This implements the "lazy" portion of
660  * determining whether or not a release sequence was contiguous, since not all
661  * modification order information is present at the time an action occurs.
662  *
663  * @param location The location/object that should be checked for release
664  * sequence resolutions
665  * @return True if any updates occurred (new synchronization, new mo_graph edges)
666  */
667 bool ModelChecker::resolve_release_sequences(void *location)
668 {
669         std::list<ModelAction *> *list;
670         list = lazy_sync_with_release->getptr(location);
671         if (!list)
672                 return false;
673
674         bool updated = false;
675         std::list<ModelAction *>::iterator it = list->begin();
676         while (it != list->end()) {
677                 ModelAction *act = *it;
678                 const ModelAction *rf = act->get_reads_from();
679                 std::vector<const ModelAction *> release_heads;
680                 bool complete;
681                 complete = release_seq_head(rf, &release_heads);
682                 for (unsigned int i = 0; i < release_heads.size(); i++) {
683                         if (!act->has_synchronized_with(release_heads[i])) {
684                                 updated = true;
685                                 act->synchronize_with(release_heads[i]);
686                         }
687                 }
688
689                 if (updated) {
690                         /* propagate synchronization to later actions */
691                         action_list_t::reverse_iterator it = action_trace->rbegin();
692                         while ((*it) != act) {
693                                 ModelAction *propagate = *it;
694                                 if (act->happens_before(propagate))
695                                         /** @todo new mo_graph edges along with
696                                          * this synchronization? */
697                                         propagate->synchronize_with(act);
698                         }
699                 }
700                 if (complete)
701                         it = list->erase(it);
702                 else
703                         it++;
704         }
705
706         return updated;
707 }
708
709 /**
710  * Performs various bookkeeping operations for the current ModelAction. For
711  * instance, adds action to the per-object, per-thread action vector and to the
712  * action trace list of all thread actions.
713  *
714  * @param act is the ModelAction to add.
715  */
716 void ModelChecker::add_action_to_lists(ModelAction *act)
717 {
718         int tid = id_to_int(act->get_tid());
719         action_trace->push_back(act);
720
721         obj_map->get_safe_ptr(act->get_location())->push_back(act);
722
723         std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
724         if (tid >= (int)vec->size())
725                 vec->resize(next_thread_id);
726         (*vec)[tid].push_back(act);
727
728         if ((int)thrd_last_action->size() <= tid)
729                 thrd_last_action->resize(get_num_threads());
730         (*thrd_last_action)[tid] = act;
731 }
732
733 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
734 {
735         int nthreads = get_num_threads();
736         if ((int)thrd_last_action->size() < nthreads)
737                 thrd_last_action->resize(nthreads);
738         return (*thrd_last_action)[id_to_int(tid)];
739 }
740
741 /**
742  * Gets the last memory_order_seq_cst action (in the total global sequence)
743  * performed on a particular object (i.e., memory location).
744  * @param location The object location to check
745  * @return The last seq_cst action performed
746  */
747 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
748 {
749         action_list_t *list = obj_map->get_safe_ptr(location);
750         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
751         action_list_t::reverse_iterator rit;
752         for (rit = list->rbegin(); rit != list->rend(); rit++)
753                 if ((*rit)->is_write() && (*rit)->is_seqcst())
754                         return *rit;
755         return NULL;
756 }
757
758 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
759 {
760         ModelAction *parent = get_last_action(tid);
761         if (!parent)
762                 parent = get_thread(tid)->get_creation();
763         return parent;
764 }
765
766 /**
767  * Returns the clock vector for a given thread.
768  * @param tid The thread whose clock vector we want
769  * @return Desired clock vector
770  */
771 ClockVector * ModelChecker::get_cv(thread_id_t tid)
772 {
773         return get_parent_action(tid)->get_cv();
774 }
775
776 /**
777  * Resolve a set of Promises with a current write. The set is provided in the
778  * Node corresponding to @a write.
779  * @param write The ModelAction that is fulfilling Promises
780  * @return True if promises were resolved; false otherwise
781  */
782 bool ModelChecker::resolve_promises(ModelAction *write)
783 {
784         bool resolved = false;
785         for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
786                 Promise *promise = (*promises)[promise_index];
787                 if (write->get_node()->get_promise(i)) {
788                         ModelAction *read = promise->get_action();
789                         read->read_from(write);
790                         r_modification_order(read, write);
791                         post_r_modification_order(read, write);
792                         promises->erase(promises->begin() + promise_index);
793                         resolved = true;
794                 } else
795                         promise_index++;
796         }
797         return resolved;
798 }
799
800 /**
801  * Compute the set of promises that could potentially be satisfied by this
802  * action. Note that the set computation actually appears in the Node, not in
803  * ModelChecker.
804  * @param curr The ModelAction that may satisfy promises
805  */
806 void ModelChecker::compute_promises(ModelAction *curr)
807 {
808         for (unsigned int i = 0; i < promises->size(); i++) {
809                 Promise *promise = (*promises)[i];
810                 const ModelAction *act = promise->get_action();
811                 if (!act->happens_before(curr) &&
812                                 act->is_read() &&
813                                 !act->is_synchronizing(curr) &&
814                                 !act->same_thread(curr) &&
815                                 promise->get_value() == curr->get_value()) {
816                         curr->get_node()->set_promise(i);
817                 }
818         }
819 }
820
821 /** Checks promises in response to change in ClockVector Threads. */
822 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
823 {
824         for (unsigned int i = 0; i < promises->size(); i++) {
825                 Promise *promise = (*promises)[i];
826                 const ModelAction *act = promise->get_action();
827                 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
828                                 merge_cv->synchronized_since(act)) {
829                         //This thread is no longer able to send values back to satisfy the promise
830                         int num_synchronized_threads = promise->increment_threads();
831                         if (num_synchronized_threads == model->get_num_threads()) {
832                                 //Promise has failed
833                                 failed_promise = true;
834                                 return;
835                         }
836                 }
837         }
838 }
839
840 /**
841  * Build up an initial set of all past writes that this 'read' action may read
842  * from. This set is determined by the clock vector's "happens before"
843  * relationship.
844  * @param curr is the current ModelAction that we are exploring; it must be a
845  * 'read' operation.
846  */
847 void ModelChecker::build_reads_from_past(ModelAction *curr)
848 {
849         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
850         unsigned int i;
851         ASSERT(curr->is_read());
852
853         ModelAction *last_seq_cst = NULL;
854
855         /* Track whether this object has been initialized */
856         bool initialized = false;
857
858         if (curr->is_seqcst()) {
859                 last_seq_cst = get_last_seq_cst(curr->get_location());
860                 /* We have to at least see the last sequentially consistent write,
861                          so we are initialized. */
862                 if (last_seq_cst != NULL)
863                         initialized = true;
864         }
865
866         /* Iterate over all threads */
867         for (i = 0; i < thrd_lists->size(); i++) {
868                 /* Iterate over actions in thread, starting from most recent */
869                 action_list_t *list = &(*thrd_lists)[i];
870                 action_list_t::reverse_iterator rit;
871                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
872                         ModelAction *act = *rit;
873
874                         /* Only consider 'write' actions */
875                         if (!act->is_write())
876                                 continue;
877
878                         /* Don't consider more than one seq_cst write if we are a seq_cst read. */
879                         if (!act->is_seqcst() || !curr->is_seqcst() || act == last_seq_cst) {
880                                 DEBUG("Adding action to may_read_from:\n");
881                                 if (DBG_ENABLED()) {
882                                         act->print();
883                                         curr->print();
884                                 }
885                                 curr->get_node()->add_read_from(act);
886                         }
887
888                         /* Include at most one act per-thread that "happens before" curr */
889                         if (act->happens_before(curr)) {
890                                 initialized = true;
891                                 break;
892                         }
893                 }
894         }
895
896         if (!initialized) {
897                 /** @todo Need a more informative way of reporting errors. */
898                 printf("ERROR: may read from uninitialized atomic\n");
899         }
900
901         if (DBG_ENABLED() || !initialized) {
902                 printf("Reached read action:\n");
903                 curr->print();
904                 printf("Printing may_read_from\n");
905                 curr->get_node()->print_may_read_from();
906                 printf("End printing may_read_from\n");
907         }
908
909         ASSERT(initialized);
910 }
911
912 static void print_list(action_list_t *list)
913 {
914         action_list_t::iterator it;
915
916         printf("---------------------------------------------------------------------\n");
917         printf("Trace:\n");
918
919         for (it = list->begin(); it != list->end(); it++) {
920                 (*it)->print();
921         }
922         printf("---------------------------------------------------------------------\n");
923 }
924
925 void ModelChecker::print_summary()
926 {
927         printf("\n");
928         printf("Number of executions: %d\n", num_executions);
929         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
930
931         scheduler->print();
932
933         if (!isfinalfeasible())
934                 printf("INFEASIBLE EXECUTION!\n");
935         print_list(action_trace);
936         printf("\n");
937 }
938
939 /**
940  * Add a Thread to the system for the first time. Should only be called once
941  * per thread.
942  * @param t The Thread to add
943  */
944 void ModelChecker::add_thread(Thread *t)
945 {
946         thread_map->put(id_to_int(t->get_id()), t);
947         scheduler->add_thread(t);
948 }
949
950 void ModelChecker::remove_thread(Thread *t)
951 {
952         scheduler->remove_thread(t);
953 }
954
955 /**
956  * Switch from a user-context to the "master thread" context (a.k.a. system
957  * context). This switch is made with the intention of exploring a particular
958  * model-checking action (described by a ModelAction object). Must be called
959  * from a user-thread context.
960  * @param act The current action that will be explored. May be NULL, although
961  * there is little reason to switch to the model-checker without an action to
962  * explore (note: act == NULL is sometimes used as a hack to allow a thread to
963  * yield control without performing any progress; see thrd_join()).
964  * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
965  */
966 int ModelChecker::switch_to_master(ModelAction *act)
967 {
968         DBG();
969         Thread *old = thread_current();
970         set_current_action(act);
971         old->set_state(THREAD_READY);
972         return Thread::swap(old, &system_context);
973 }
974
975 /**
976  * Takes the next step in the execution, if possible.
977  * @return Returns true (success) if a step was taken and false otherwise.
978  */
979 bool ModelChecker::take_step() {
980         Thread *curr, *next;
981
982         curr = thread_current();
983         if (curr) {
984                 if (curr->get_state() == THREAD_READY) {
985                         check_current_action();
986                         scheduler->add_thread(curr);
987                 } else if (curr->get_state() == THREAD_RUNNING) {
988                         /* Stopped while running; i.e., completed */
989                         curr->complete();
990                 } else {
991                         ASSERT(false);
992                 }
993         }
994         next = scheduler->next_thread();
995
996         /* Infeasible -> don't take any more steps */
997         if (!isfeasible())
998                 return false;
999
1000         if (next)
1001                 next->set_state(THREAD_RUNNING);
1002         DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1003
1004         /* next == NULL -> don't take any more steps */
1005         if (!next)
1006                 return false;
1007         /* Return false only if swap fails with an error */
1008         return (Thread::swap(&system_context, next) == 0);
1009 }
1010
1011 /** Runs the current execution until threre are no more steps to take. */
1012 void ModelChecker::finish_execution() {
1013         DBG();
1014
1015         while (take_step());
1016 }