promise: add Promise::get_index function
[cdsspec-compiler.git] / action.cc
1 #include <stdio.h>
2 #define __STDC_FORMAT_MACROS
3 #include <inttypes.h>
4
5 #include "model.h"
6 #include "action.h"
7 #include "clockvector.h"
8 #include "common.h"
9 #include "threads-model.h"
10 #include "nodestack.h"
11
12 #define ACTION_INITIAL_CLOCK 0
13
14 /** @brief A special value to represent a successful trylock */
15 #define VALUE_TRYSUCCESS 1
16
17 /** @brief A special value to represent a failed trylock */
18 #define VALUE_TRYFAILED 0
19
20 /**
21  * @brief Construct a new ModelAction
22  *
23  * @param type The type of action
24  * @param order The memory order of this action. A "don't care" for non-ATOMIC
25  * actions (e.g., THREAD_* or MODEL_* actions).
26  * @param loc The location that this action acts upon
27  * @param value (optional) A value associated with the action (e.g., the value
28  * read or written). Defaults to a given macro constant, for debugging purposes.
29  * @param thread (optional) The Thread in which this action occurred. If NULL
30  * (default), then a Thread is assigned according to the scheduler.
31  */
32 ModelAction::ModelAction(action_type_t type, memory_order order, void *loc,
33                 uint64_t value, Thread *thread) :
34         type(type),
35         order(order),
36         location(loc),
37         value(value),
38         reads_from(NULL),
39         reads_from_promise(NULL),
40         last_fence_release(NULL),
41         node(NULL),
42         seq_number(ACTION_INITIAL_CLOCK),
43         cv(NULL),
44         sleep_flag(false)
45 {
46         /* References to NULL atomic variables can end up here */
47         ASSERT(loc || type == ATOMIC_FENCE || type == MODEL_FIXUP_RELSEQ);
48
49         Thread *t = thread ? thread : thread_current();
50         this->tid = t->get_id();
51 }
52
53 /** @brief ModelAction destructor */
54 ModelAction::~ModelAction()
55 {
56         /**
57          * We can't free the clock vector:
58          * Clock vectors are snapshotting state. When we delete model actions,
59          * they are at the end of the node list and have invalid old clock
60          * vectors which have already been rolled back to an unallocated state.
61          */
62
63         /*
64          if (cv)
65                 delete cv; */
66 }
67
68 void ModelAction::copy_from_new(ModelAction *newaction)
69 {
70         seq_number = newaction->seq_number;
71 }
72
73 void ModelAction::set_seq_number(modelclock_t num)
74 {
75         /* ATOMIC_UNINIT actions should never have non-zero clock */
76         ASSERT(!is_uninitialized());
77         ASSERT(seq_number == ACTION_INITIAL_CLOCK);
78         seq_number = num;
79 }
80
81 bool ModelAction::is_thread_start() const
82 {
83         return type == THREAD_START;
84 }
85
86 bool ModelAction::is_thread_join() const
87 {
88         return type == THREAD_JOIN;
89 }
90
91 bool ModelAction::is_relseq_fixup() const
92 {
93         return type == MODEL_FIXUP_RELSEQ;
94 }
95
96 bool ModelAction::is_mutex_op() const
97 {
98         return type == ATOMIC_LOCK || type == ATOMIC_TRYLOCK || type == ATOMIC_UNLOCK || type == ATOMIC_WAIT || type == ATOMIC_NOTIFY_ONE || type == ATOMIC_NOTIFY_ALL;
99 }
100
101 bool ModelAction::is_lock() const
102 {
103         return type == ATOMIC_LOCK;
104 }
105
106 bool ModelAction::is_wait() const {
107         return type == ATOMIC_WAIT;
108 }
109
110 bool ModelAction::is_notify() const {
111         return type == ATOMIC_NOTIFY_ONE || type == ATOMIC_NOTIFY_ALL;
112 }
113
114 bool ModelAction::is_notify_one() const {
115         return type == ATOMIC_NOTIFY_ONE;
116 }
117
118 bool ModelAction::is_unlock() const
119 {
120         return type == ATOMIC_UNLOCK;
121 }
122
123 bool ModelAction::is_trylock() const
124 {
125         return type == ATOMIC_TRYLOCK;
126 }
127
128 bool ModelAction::is_success_lock() const
129 {
130         return type == ATOMIC_LOCK || (type == ATOMIC_TRYLOCK && value == VALUE_TRYSUCCESS);
131 }
132
133 bool ModelAction::is_failed_trylock() const
134 {
135         return (type == ATOMIC_TRYLOCK && value == VALUE_TRYFAILED);
136 }
137
138 /** @return True if this operation is performed on a C/C++ atomic variable */
139 bool ModelAction::is_atomic_var() const
140 {
141         return is_read() || could_be_write();
142 }
143
144 bool ModelAction::is_uninitialized() const
145 {
146         return type == ATOMIC_UNINIT;
147 }
148
149 bool ModelAction::is_read() const
150 {
151         return type == ATOMIC_READ || type == ATOMIC_RMWR || type == ATOMIC_RMW;
152 }
153
154 bool ModelAction::is_write() const
155 {
156         return type == ATOMIC_WRITE || type == ATOMIC_RMW || type == ATOMIC_INIT || type == ATOMIC_UNINIT;
157 }
158
159 bool ModelAction::could_be_write() const
160 {
161         return is_write() || is_rmwr();
162 }
163
164 bool ModelAction::is_yield() const
165 {
166         return type == THREAD_YIELD;
167 }
168
169 bool ModelAction::is_rmwr() const
170 {
171         return type == ATOMIC_RMWR;
172 }
173
174 bool ModelAction::is_rmw() const
175 {
176         return type == ATOMIC_RMW;
177 }
178
179 bool ModelAction::is_rmwc() const
180 {
181         return type == ATOMIC_RMWC;
182 }
183
184 bool ModelAction::is_fence() const
185 {
186         return type == ATOMIC_FENCE;
187 }
188
189 bool ModelAction::is_initialization() const
190 {
191         return type == ATOMIC_INIT;
192 }
193
194 bool ModelAction::is_relaxed() const
195 {
196         return order == std::memory_order_relaxed;
197 }
198
199 bool ModelAction::is_acquire() const
200 {
201         switch (order) {
202         case std::memory_order_acquire:
203         case std::memory_order_acq_rel:
204         case std::memory_order_seq_cst:
205                 return true;
206         default:
207                 return false;
208         }
209 }
210
211 bool ModelAction::is_release() const
212 {
213         switch (order) {
214         case std::memory_order_release:
215         case std::memory_order_acq_rel:
216         case std::memory_order_seq_cst:
217                 return true;
218         default:
219                 return false;
220         }
221 }
222
223 bool ModelAction::is_seqcst() const
224 {
225         return order == std::memory_order_seq_cst;
226 }
227
228 bool ModelAction::same_var(const ModelAction *act) const
229 {
230         if (act->is_wait() || is_wait()) {
231                 if (act->is_wait() && is_wait()) {
232                         if (((void *)value) == ((void *)act->value))
233                                 return true;
234                 } else if (is_wait()) {
235                         if (((void *)value) == act->location)
236                                 return true;
237                 } else if (act->is_wait()) {
238                         if (location == ((void *)act->value))
239                                 return true;
240                 }
241         }
242
243         return location == act->location;
244 }
245
246 bool ModelAction::same_thread(const ModelAction *act) const
247 {
248         return tid == act->tid;
249 }
250
251 void ModelAction::copy_typeandorder(ModelAction * act)
252 {
253         this->type = act->type;
254         this->order = act->order;
255 }
256
257 /**
258  * Get the Thread which is the operand of this action. This is only valid for
259  * THREAD_* operations (currently only for THREAD_CREATE and THREAD_JOIN). Note
260  * that this provides a central place for determining the conventions of Thread
261  * storage in ModelAction, where we generally aren't very type-safe (e.g., we
262  * store object references in a (void *) address.
263  *
264  * For THREAD_CREATE, this yields the Thread which is created.
265  * For THREAD_JOIN, this yields the Thread we are joining with.
266  *
267  * @return The Thread which this action acts on, if exists; otherwise NULL
268  */
269 Thread * ModelAction::get_thread_operand() const
270 {
271         if (type == THREAD_CREATE) {
272                 /* THREAD_CREATE stores its (Thread *) in a thrd_t::priv */
273                 thrd_t *thrd = (thrd_t *)get_location();
274                 return thrd->priv;
275         } else if (type == THREAD_JOIN)
276                 /* THREAD_JOIN uses (Thread *) for location */
277                 return (Thread *)get_location();
278         else
279                 return NULL;
280 }
281
282 /**
283  * @brief Convert the read portion of an RMW
284  *
285  * Changes an existing read part of an RMW action into either:
286  *  -# a full RMW action in case of the completed write or
287  *  -# a READ action in case a failed action.
288  *
289  * @todo  If the memory_order changes, we may potentially need to update our
290  * clock vector.
291  *
292  * @param act The second half of the RMW (either RMWC or RMW)
293  */
294 void ModelAction::process_rmw(ModelAction *act)
295 {
296         this->order = act->order;
297         if (act->is_rmwc())
298                 this->type = ATOMIC_READ;
299         else if (act->is_rmw()) {
300                 this->type = ATOMIC_RMW;
301                 this->value = act->value;
302         }
303 }
304
305 /**
306  * @brief Check if this action should be backtracked with another, due to
307  * potential synchronization
308  *
309  * The is_synchronizing method should only explore interleavings if:
310  *  -# the operations are seq_cst and don't commute or
311  *  -# the reordering may establish or break a synchronization relation.
312  *
313  * Other memory operations will be dealt with by using the reads_from relation.
314  *
315  * @param act The action to consider exploring a reordering
316  * @return True, if we have to explore a reordering; otherwise false
317  */
318 bool ModelAction::could_synchronize_with(const ModelAction *act) const
319 {
320         // Same thread can't be reordered
321         if (same_thread(act))
322                 return false;
323
324         // Different locations commute
325         if (!same_var(act))
326                 return false;
327
328         // Explore interleavings of seqcst writes/fences to guarantee total
329         // order of seq_cst operations that don't commute
330         if ((could_be_write() || act->could_be_write() || is_fence() || act->is_fence()) && is_seqcst() && act->is_seqcst())
331                 return true;
332
333         // Explore synchronizing read/write pairs
334         if (is_acquire() && act->is_release() && is_read() && act->could_be_write())
335                 return true;
336
337         // lock just released...we can grab lock
338         if ((is_lock() || is_trylock()) && (act->is_unlock() || act->is_wait()))
339                 return true;
340
341         // lock just acquired...we can fail to grab lock
342         if (is_trylock() && act->is_success_lock())
343                 return true;
344
345         // other thread stalling on lock...we can release lock
346         if (is_unlock() && (act->is_trylock() || act->is_lock()))
347                 return true;
348
349         if (is_trylock() && (act->is_unlock() || act->is_wait()))
350                 return true;
351
352         if (is_notify() && act->is_wait())
353                 return true;
354
355         if (is_wait() && act->is_notify())
356                 return true;
357
358         // Otherwise handle by reads_from relation
359         return false;
360 }
361
362 bool ModelAction::is_conflicting_lock(const ModelAction *act) const
363 {
364         // Must be different threads to reorder
365         if (same_thread(act))
366                 return false;
367
368         // Try to reorder a lock past a successful lock
369         if (act->is_success_lock())
370                 return true;
371
372         // Try to push a successful trylock past an unlock
373         if (act->is_unlock() && is_trylock() && value == VALUE_TRYSUCCESS)
374                 return true;
375
376         // Try to push a successful trylock past a wait
377         if (act->is_wait() && is_trylock() && value == VALUE_TRYSUCCESS)
378                 return true;
379
380         return false;
381 }
382
383 /**
384  * Create a new clock vector for this action. Note that this function allows a
385  * user to clobber (and leak) a ModelAction's existing clock vector. A user
386  * should ensure that the vector has already either been rolled back
387  * (effectively "freed") or freed.
388  *
389  * @param parent A ModelAction from which to inherit a ClockVector
390  */
391 void ModelAction::create_cv(const ModelAction *parent)
392 {
393         if (parent)
394                 cv = new ClockVector(parent->cv, this);
395         else
396                 cv = new ClockVector(NULL, this);
397 }
398
399 void ModelAction::set_try_lock(bool obtainedlock)
400 {
401         value = obtainedlock ? VALUE_TRYSUCCESS : VALUE_TRYFAILED;
402 }
403
404 /**
405  * @brief Get the value read by this load
406  *
407  * We differentiate this function from ModelAction::get_write_value and
408  * ModelAction::get_value for the purpose of RMW's, which may have both a
409  * 'read' and a 'write' value.
410  *
411  * Note: 'this' must be a load.
412  *
413  * @return The value read by this load
414  */
415 uint64_t ModelAction::get_reads_from_value() const
416 {
417         ASSERT(is_read());
418         if (reads_from)
419                 return reads_from->get_write_value();
420         else if (reads_from_promise)
421                 return reads_from_promise->get_value();
422         return VALUE_NONE; /* Only for new actions with no reads-from */
423 }
424
425 /**
426  * @brief Get the value written by this store
427  *
428  * We differentiate this function from ModelAction::get_reads_from_value and
429  * ModelAction::get_value for the purpose of RMW's, which may have both a
430  * 'read' and a 'write' value.
431  *
432  * Note: 'this' must be a store.
433  *
434  * @return The value written by this store
435  */
436 uint64_t ModelAction::get_write_value() const
437 {
438         ASSERT(is_write());
439         return value;
440 }
441
442 /**
443  * @brief Get the value returned by this action
444  *
445  * For atomic reads (including RMW), an operation returns the value it read.
446  * For atomic writes, an operation returns the value it wrote. For other
447  * operations, the return value varies (sometimes is a "don't care"), but the
448  * value is simply stored in the "value" field.
449  *
450  * @return This action's return value
451  */
452 uint64_t ModelAction::get_return_value() const
453 {
454         if (is_read())
455                 return get_reads_from_value();
456         else if (is_write())
457                 return get_write_value();
458         else
459                 return value;
460 }
461
462 /** @return The Node associated with this ModelAction */
463 Node * ModelAction::get_node() const
464 {
465         /* UNINIT actions do not have a Node */
466         ASSERT(!is_uninitialized());
467         return node;
468 }
469
470 /**
471  * Update the model action's read_from action
472  * @param act The action to read from; should be a write
473  */
474 void ModelAction::set_read_from(const ModelAction *act)
475 {
476         ASSERT(act);
477         reads_from = act;
478         reads_from_promise = NULL;
479         if (act->is_uninitialized())
480                 model->assert_bug("May read from uninitialized atomic\n");
481 }
482
483 /**
484  * Set this action's read-from promise
485  * @param promise The promise to read from
486  */
487 void ModelAction::set_read_from_promise(Promise *promise)
488 {
489         ASSERT(is_read());
490         reads_from_promise = promise;
491         reads_from = NULL;
492 }
493
494 /**
495  * Synchronize the current thread with the thread corresponding to the
496  * ModelAction parameter.
497  * @param act The ModelAction to synchronize with
498  * @return True if this is a valid synchronization; false otherwise
499  */
500 bool ModelAction::synchronize_with(const ModelAction *act)
501 {
502         if (*this < *act)
503                 return false;
504         model->check_promises(act->get_tid(), cv, act->cv);
505         cv->merge(act->cv);
506         return true;
507 }
508
509 bool ModelAction::has_synchronized_with(const ModelAction *act) const
510 {
511         return cv->synchronized_since(act);
512 }
513
514 /**
515  * Check whether 'this' happens before act, according to the memory-model's
516  * happens before relation. This is checked via the ClockVector constructs.
517  * @return true if this action's thread has synchronized with act's thread
518  * since the execution of act, false otherwise.
519  */
520 bool ModelAction::happens_before(const ModelAction *act) const
521 {
522         return act->cv->synchronized_since(this);
523 }
524
525 /** @brief Print nicely-formatted info about this ModelAction */
526 void ModelAction::print() const
527 {
528         const char *type_str, *mo_str;
529         switch (this->type) {
530         case MODEL_FIXUP_RELSEQ:
531                 type_str = "relseq fixup";
532                 break;
533         case THREAD_CREATE:
534                 type_str = "thread create";
535                 break;
536         case THREAD_START:
537                 type_str = "thread start";
538                 break;
539         case THREAD_YIELD:
540                 type_str = "thread yield";
541                 break;
542         case THREAD_JOIN:
543                 type_str = "thread join";
544                 break;
545         case THREAD_FINISH:
546                 type_str = "thread finish";
547                 break;
548         case ATOMIC_UNINIT:
549                 type_str = "uninitialized";
550                 break;
551         case ATOMIC_READ:
552                 type_str = "atomic read";
553                 break;
554         case ATOMIC_WRITE:
555                 type_str = "atomic write";
556                 break;
557         case ATOMIC_RMW:
558                 type_str = "atomic rmw";
559                 break;
560         case ATOMIC_FENCE:
561                 type_str = "fence";
562                 break;
563         case ATOMIC_RMWR:
564                 type_str = "atomic rmwr";
565                 break;
566         case ATOMIC_RMWC:
567                 type_str = "atomic rmwc";
568                 break;
569         case ATOMIC_INIT:
570                 type_str = "init atomic";
571                 break;
572         case ATOMIC_LOCK:
573                 type_str = "lock";
574                 break;
575         case ATOMIC_UNLOCK:
576                 type_str = "unlock";
577                 break;
578         case ATOMIC_TRYLOCK:
579                 type_str = "trylock";
580                 break;
581         case ATOMIC_WAIT:
582                 type_str = "wait";
583                 break;
584         case ATOMIC_NOTIFY_ONE:
585                 type_str = "notify one";
586                 break;
587         case ATOMIC_NOTIFY_ALL:
588                 type_str = "notify all";
589                 break;
590         default:
591                 type_str = "unknown type";
592         }
593
594         switch (this->order) {
595         case std::memory_order_relaxed:
596                 mo_str = "relaxed";
597                 break;
598         case std::memory_order_acquire:
599                 mo_str = "acquire";
600                 break;
601         case std::memory_order_release:
602                 mo_str = "release";
603                 break;
604         case std::memory_order_acq_rel:
605                 mo_str = "acq_rel";
606                 break;
607         case std::memory_order_seq_cst:
608                 mo_str = "seq_cst";
609                 break;
610         default:
611                 mo_str = "unknown";
612                 break;
613         }
614
615         model_print("(%4d) Thread: %-2d   Action: %-13s   MO: %7s  Loc: %14p   Value: %-#18" PRIx64,
616                         seq_number, id_to_int(tid), type_str, mo_str, location, get_return_value());
617         if (is_read()) {
618                 if (reads_from)
619                         model_print("  Rf: %-3d", reads_from->get_seq_number());
620                 else if (reads_from_promise) {
621                         int idx = reads_from_promise->get_index();
622                         if (idx >= 0)
623                                 model_print("  Rf: P%-2d", idx);
624                         else
625                                 model_print("  Rf: P? ");
626                 } else
627                         model_print("  Rf: ?  ");
628         }
629         if (cv) {
630                 if (is_read())
631                         model_print(" ");
632                 else
633                         model_print("          ");
634                 cv->print();
635         } else
636                 model_print("\n");
637 }
638
639 /** @brief Get a (likely) unique hash for this ModelAction */
640 unsigned int ModelAction::hash() const
641 {
642         unsigned int hash = (unsigned int)this->type;
643         hash ^= ((unsigned int)this->order) << 3;
644         hash ^= seq_number << 5;
645         hash ^= id_to_int(tid) << 6;
646
647         if (is_read()) {
648                if (reads_from)
649                        hash ^= reads_from->get_seq_number();
650                else if (reads_from_promise)
651                        hash ^= reads_from_promise->get_index();
652                hash ^= get_reads_from_value();
653         }
654         return hash;
655 }
656
657 /**
658  * @brief Checks the NodeStack to see if a ModelAction is in our may-read-from set
659  * @param write The ModelAction to check for
660  * @return True if the ModelAction is found; false otherwise
661  */
662 bool ModelAction::may_read_from(const ModelAction *write) const
663 {
664         for (int i = 0; i < node->get_read_from_past_size(); i++)
665                 if (node->get_read_from_past(i) == write)
666                         return true;
667         return false;
668 }
669
670 /**
671  * @brief Checks the NodeStack to see if a Promise is in our may-read-from set
672  * @param promise The Promise to check for
673  * @return True if the Promise is found; false otherwise
674  */
675 bool ModelAction::may_read_from(const Promise *promise) const
676 {
677         for (int i = 0; i < node->get_read_from_promise_size(); i++)
678                 if (node->get_read_from_promise(i) == promise)
679                         return true;
680         return false;
681 }
682
683 /**
684  * Only valid for LOCK, TRY_LOCK, UNLOCK, and WAIT operations.
685  * @return The mutex operated on by this action, if any; otherwise NULL
686  */
687 std::mutex * ModelAction::get_mutex() const
688 {
689         if (is_trylock() || is_lock() || is_unlock())
690                 return (std::mutex *)get_location();
691         else if (is_wait())
692                 return (std::mutex *)get_value();
693         else
694                 return NULL;
695 }