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