refactor DBG_ENABLED() vs. verbose
[c11tester.git] / cyclegraph.cc
1 #include "cyclegraph.h"
2 #include "action.h"
3 #include "common.h"
4 #include "promise.h"
5 #include "model.h"
6 #include "threads-model.h"
7
8 /** Initializes a CycleGraph object. */
9 CycleGraph::CycleGraph() :
10         discovered(new HashTable<const CycleNode *, const CycleNode *, uintptr_t, 4, model_malloc, model_calloc, model_free>(16)),
11         hasCycles(false),
12         oldCycles(false)
13 {
14 }
15
16 /** CycleGraph destructor */
17 CycleGraph::~CycleGraph()
18 {
19         delete discovered;
20 }
21
22 /**
23  * Add a CycleNode to the graph, corresponding to a store ModelAction
24  * @param act The write action that should be added
25  * @param node The CycleNode that corresponds to the store
26  */
27 void CycleGraph::putNode(const ModelAction *act, CycleNode *node)
28 {
29         actionToNode.put(act, node);
30 #if SUPPORT_MOD_ORDER_DUMP
31         nodeList.push_back(node);
32 #endif
33 }
34
35 /**
36  * Add a CycleNode to the graph, corresponding to a Promise
37  * @param promise The Promise that should be added
38  * @param node The CycleNode that corresponds to the Promise
39  */
40 void CycleGraph::putNode(const Promise *promise, CycleNode *node)
41 {
42         promiseToNode.put(promise, node);
43 #if SUPPORT_MOD_ORDER_DUMP
44         nodeList.push_back(node);
45 #endif
46 }
47
48 /**
49  * @brief Remove the Promise node from the graph
50  * @param promise The promise to remove from the graph
51  */
52 void CycleGraph::erasePromiseNode(const Promise *promise)
53 {
54         promiseToNode.put(promise, NULL);
55 #if SUPPORT_MOD_ORDER_DUMP
56         /* Remove the promise node from nodeList */
57         CycleNode *node = getNode_noCreate(promise);
58         for (unsigned int i = 0; i < nodeList.size(); )
59                 if (nodeList[i] == node)
60                         nodeList.erase(nodeList.begin() + i);
61                 else
62                         i++;
63 #endif
64 }
65
66 /** @return The corresponding CycleNode, if exists; otherwise NULL */
67 CycleNode * CycleGraph::getNode_noCreate(const ModelAction *act) const
68 {
69         return actionToNode.get(act);
70 }
71
72 /** @return The corresponding CycleNode, if exists; otherwise NULL */
73 CycleNode * CycleGraph::getNode_noCreate(const Promise *promise) const
74 {
75         return promiseToNode.get(promise);
76 }
77
78 /**
79  * @brief Returns the CycleNode corresponding to a given ModelAction
80  *
81  * Gets (or creates, if none exist) a CycleNode corresponding to a ModelAction
82  *
83  * @param action The ModelAction to find a node for
84  * @return The CycleNode paired with this action
85  */
86 CycleNode * CycleGraph::getNode(const ModelAction *action)
87 {
88         CycleNode *node = getNode_noCreate(action);
89         if (node == NULL) {
90                 node = new CycleNode(action);
91                 putNode(action, node);
92         }
93         return node;
94 }
95
96 /**
97  * @brief Returns a CycleNode corresponding to a promise
98  *
99  * Gets (or creates, if none exist) a CycleNode corresponding to a promised
100  * value.
101  *
102  * @param promise The Promise generated by a reader
103  * @return The CycleNode corresponding to the Promise
104  */
105 CycleNode * CycleGraph::getNode(const Promise *promise)
106 {
107         CycleNode *node = getNode_noCreate(promise);
108         if (node == NULL) {
109                 node = new CycleNode(promise);
110                 putNode(promise, node);
111         }
112         return node;
113 }
114
115 /**
116  * Resolve/satisfy a Promise with a particular store ModelAction, taking care
117  * of the CycleGraph cleanups, including merging any necessary CycleNodes.
118  *
119  * @param promise The Promise to resolve
120  * @param writer The store that will resolve this Promise
121  * @return false if the resolution results in a cycle (or fails in some other
122  * way); true otherwise
123  */
124 bool CycleGraph::resolvePromise(const Promise *promise, ModelAction *writer)
125 {
126         CycleNode *promise_node = promiseToNode.get(promise);
127         CycleNode *w_node = actionToNode.get(writer);
128         ASSERT(promise_node);
129
130         if (w_node)
131                 return mergeNodes(w_node, promise_node);
132         /* No existing write-node; just convert the promise-node */
133         promise_node->resolvePromise(writer);
134         erasePromiseNode(promise_node->getPromise());
135         putNode(writer, promise_node);
136         return true;
137 }
138
139 /**
140  * @brief Merge two CycleNodes that represent the same write
141  *
142  * Note that this operation cannot be rolled back.
143  *
144  * @param w_node The write ModelAction node with which to merge
145  * @param p_node The Promise node to merge. Will be destroyed after this
146  * function.
147  *
148  * @return false if the merge cannot succeed; true otherwise
149  */
150 bool CycleGraph::mergeNodes(CycleNode *w_node, CycleNode *p_node)
151 {
152         ASSERT(!w_node->is_promise());
153         ASSERT(p_node->is_promise());
154
155         const Promise *promise = p_node->getPromise();
156         if (!promise->is_compatible(w_node->getAction()) ||
157                         !promise->same_value(w_node->getAction()))
158                 return false;
159
160         /* Transfer the RMW */
161         CycleNode *promise_rmw = p_node->getRMW();
162         if (promise_rmw && promise_rmw != w_node->getRMW() && w_node->setRMW(promise_rmw))
163                 return false;
164
165         /* Transfer back edges to w_node */
166         while (p_node->getNumBackEdges() > 0) {
167                 CycleNode *back = p_node->removeBackEdge();
168                 if (back == w_node)
169                         continue;
170                 addNodeEdge(back, w_node);
171                 if (hasCycles)
172                         return false;
173         }
174
175         /* Transfer forward edges to w_node */
176         while (p_node->getNumEdges() > 0) {
177                 CycleNode *forward = p_node->removeEdge();
178                 if (forward == w_node)
179                         continue;
180                 addNodeEdge(w_node, forward);
181                 if (hasCycles)
182                         return false;
183         }
184
185         erasePromiseNode(promise);
186         /* Not deleting p_node, to maintain consistency if mergeNodes() fails */
187
188         return !hasCycles;
189 }
190
191 /**
192  * Adds an edge between two CycleNodes.
193  * @param fromnode The edge comes from this CycleNode
194  * @param tonode The edge points to this CycleNode
195  * @return True, if new edge(s) are added; otherwise false
196  */
197 bool CycleGraph::addNodeEdge(CycleNode *fromnode, CycleNode *tonode)
198 {
199         bool added;
200
201         if (!hasCycles)
202                 hasCycles = checkReachable(tonode, fromnode);
203
204         if ((added = fromnode->addEdge(tonode)))
205                 rollbackvector.push_back(fromnode);
206
207         /*
208          * If the fromnode has a rmwnode that is not the tonode, we should add
209          * an edge between its rmwnode and the tonode
210          */
211         CycleNode *rmwnode = fromnode->getRMW();
212         if (rmwnode && rmwnode != tonode) {
213                 if (!hasCycles)
214                         hasCycles = checkReachable(tonode, rmwnode);
215
216                 if (rmwnode->addEdge(tonode)) {
217                         rollbackvector.push_back(rmwnode);
218                         added = true;
219                 }
220         }
221         return added;
222 }
223
224 /**
225  * @brief Add an edge between a write and the RMW which reads from it
226  *
227  * Handles special case of a RMW action, where the ModelAction rmw reads from
228  * the ModelAction/Promise from. The key differences are:
229  * (1) no write can occur in between the rmw and the from action.
230  * (2) Only one RMW action can read from a given write.
231  *
232  * @param from The edge comes from this ModelAction/Promise
233  * @param rmw The edge points to this ModelAction; this action must read from
234  * the ModelAction/Promise from
235  */
236 template <typename T>
237 void CycleGraph::addRMWEdge(const T *from, const ModelAction *rmw)
238 {
239         ASSERT(from);
240         ASSERT(rmw);
241
242         CycleNode *fromnode = getNode(from);
243         CycleNode *rmwnode = getNode(rmw);
244
245         /* Two RMW actions cannot read from the same write. */
246         if (fromnode->setRMW(rmwnode))
247                 hasCycles = true;
248         else
249                 rmwrollbackvector.push_back(fromnode);
250
251         /* Transfer all outgoing edges from the from node to the rmw node */
252         /* This process should not add a cycle because either:
253          * (1) The rmw should not have any incoming edges yet if it is the
254          * new node or
255          * (2) the fromnode is the new node and therefore it should not
256          * have any outgoing edges.
257          */
258         for (unsigned int i = 0; i < fromnode->getNumEdges(); i++) {
259                 CycleNode *tonode = fromnode->getEdge(i);
260                 if (tonode != rmwnode) {
261                         if (rmwnode->addEdge(tonode))
262                                 rollbackvector.push_back(rmwnode);
263                 }
264         }
265
266         addNodeEdge(fromnode, rmwnode);
267 }
268 /* Instantiate two forms of CycleGraph::addRMWEdge */
269 template void CycleGraph::addRMWEdge(const ModelAction *from, const ModelAction *rmw);
270 template void CycleGraph::addRMWEdge(const Promise *from, const ModelAction *rmw);
271
272 /**
273  * @brief Adds an edge between objects
274  *
275  * This function will add an edge between any two objects which can be
276  * associated with a CycleNode. That is, if they have a CycleGraph::getNode
277  * implementation.
278  *
279  * The object to is ordered after the object from.
280  *
281  * @param to The edge points to this object, of type T
282  * @param from The edge comes from this object, of type U
283  * @return True, if new edge(s) are added; otherwise false
284  */
285 template <typename T, typename U>
286 bool CycleGraph::addEdge(const T *from, const U *to)
287 {
288         ASSERT(from);
289         ASSERT(to);
290
291         CycleNode *fromnode = getNode(from);
292         CycleNode *tonode = getNode(to);
293
294         return addNodeEdge(fromnode, tonode);
295 }
296 /* Instantiate four forms of CycleGraph::addEdge */
297 template bool CycleGraph::addEdge(const ModelAction *from, const ModelAction *to);
298 template bool CycleGraph::addEdge(const ModelAction *from, const Promise *to);
299 template bool CycleGraph::addEdge(const Promise *from, const ModelAction *to);
300 template bool CycleGraph::addEdge(const Promise *from, const Promise *to);
301
302 #if SUPPORT_MOD_ORDER_DUMP
303
304 static void print_node(FILE *file, const CycleNode *node, int label)
305 {
306         if (node->is_promise()) {
307                 const Promise *promise = node->getPromise();
308                 int idx = model->get_promise_number(promise);
309                 fprintf(file, "P%u", idx);
310                 if (label) {
311                         int first = 1;
312                         fprintf(file, " [label=\"P%d, T", idx);
313                         for (unsigned int i = 0 ; i < model->get_num_threads(); i++)
314                                 if (promise->thread_is_available(int_to_id(i))) {
315                                         fprintf(file, "%s%u", first ? "": ",", i);
316                                         first = 0;
317                                 }
318                         fprintf(file, "\"]");
319                 }
320         } else {
321                 const ModelAction *act = node->getAction();
322                 modelclock_t idx = act->get_seq_number();
323                 fprintf(file, "N%u", idx);
324                 if (label)
325                         fprintf(file, " [label=\"N%u, T%u\"]", idx, act->get_tid());
326         }
327 }
328
329 static void print_edge(FILE *file, const CycleNode *from, const CycleNode *to, const char *prop)
330 {
331         print_node(file, from, 0);
332         fprintf(file, " -> ");
333         print_node(file, to, 0);
334         if (prop && strlen(prop))
335                 fprintf(file, " [%s]", prop);
336         fprintf(file, ";\n");
337 }
338
339 void CycleGraph::dot_print_node(FILE *file, const ModelAction *act)
340 {
341         print_node(file, getNode(act), 1);
342 }
343
344 template <typename T, typename U>
345 void CycleGraph::dot_print_edge(FILE *file, const T *from, const U *to, const char *prop)
346 {
347         CycleNode *fromnode = getNode(from);
348         CycleNode *tonode = getNode(to);
349
350         print_edge(file, fromnode, tonode, prop);
351 }
352 /* Instantiate two forms of CycleGraph::dot_print_edge */
353 template void CycleGraph::dot_print_edge(FILE *file, const Promise *from, const ModelAction *to, const char *prop);
354 template void CycleGraph::dot_print_edge(FILE *file, const ModelAction *from, const ModelAction *to, const char *prop);
355
356 void CycleGraph::dumpNodes(FILE *file) const
357 {
358         for (unsigned int i = 0; i < nodeList.size(); i++) {
359                 CycleNode *n = nodeList[i];
360                 print_node(file, n, 1);
361                 fprintf(file, ";\n");
362                 if (n->getRMW())
363                         print_edge(file, n, n->getRMW(), "style=dotted");
364                 for (unsigned int j = 0; j < n->getNumEdges(); j++)
365                         print_edge(file, n, n->getEdge(j), NULL);
366         }
367 }
368
369 void CycleGraph::dumpGraphToFile(const char *filename) const
370 {
371         char buffer[200];
372         sprintf(buffer, "%s.dot", filename);
373         FILE *file = fopen(buffer, "w");
374         fprintf(file, "digraph %s {\n", filename);
375         dumpNodes(file);
376         fprintf(file, "}\n");
377         fclose(file);
378 }
379 #endif
380
381 /**
382  * Checks whether one CycleNode can reach another.
383  * @param from The CycleNode from which to begin exploration
384  * @param to The CycleNode to reach
385  * @return True, @a from can reach @a to; otherwise, false
386  */
387 bool CycleGraph::checkReachable(const CycleNode *from, const CycleNode *to) const
388 {
389         std::vector< const CycleNode *, ModelAlloc<const CycleNode *> > queue;
390         discovered->reset();
391
392         queue.push_back(from);
393         discovered->put(from, from);
394         while (!queue.empty()) {
395                 const CycleNode *node = queue.back();
396                 queue.pop_back();
397                 if (node == to)
398                         return true;
399
400                 for (unsigned int i = 0; i < node->getNumEdges(); i++) {
401                         CycleNode *next = node->getEdge(i);
402                         if (!discovered->contains(next)) {
403                                 discovered->put(next, next);
404                                 queue.push_back(next);
405                         }
406                 }
407         }
408         return false;
409 }
410
411 /**
412  * Checks whether one ModelAction/Promise can reach another ModelAction/Promise
413  * @param from The ModelAction or Promise from which to begin exploration
414  * @param to The ModelAction or Promise to reach
415  * @return True, @a from can reach @a to; otherwise, false
416  */
417 template <typename T, typename U>
418 bool CycleGraph::checkReachable(const T *from, const U *to) const
419 {
420         CycleNode *fromnode = getNode_noCreate(from);
421         CycleNode *tonode = getNode_noCreate(to);
422
423         if (!fromnode || !tonode)
424                 return false;
425
426         return checkReachable(fromnode, tonode);
427 }
428 /* Instantiate four forms of CycleGraph::checkReachable */
429 template bool CycleGraph::checkReachable(const ModelAction *from,
430                 const ModelAction *to) const;
431 template bool CycleGraph::checkReachable(const ModelAction *from,
432                 const Promise *to) const;
433 template bool CycleGraph::checkReachable(const Promise *from,
434                 const ModelAction *to) const;
435 template bool CycleGraph::checkReachable(const Promise *from,
436                 const Promise *to) const;
437
438 /** @return True, if the promise has failed; false otherwise */
439 bool CycleGraph::checkPromise(const ModelAction *fromact, Promise *promise) const
440 {
441         std::vector< CycleNode *, ModelAlloc<CycleNode *> > queue;
442         discovered->reset();
443         CycleNode *from = actionToNode.get(fromact);
444
445         queue.push_back(from);
446         discovered->put(from, from);
447         while (!queue.empty()) {
448                 CycleNode *node = queue.back();
449                 queue.pop_back();
450
451                 if (node->getPromise() == promise)
452                         return true;
453                 if (!node->is_promise() &&
454                                 promise->eliminate_thread(node->getAction()->get_tid()))
455                         return true;
456
457                 for (unsigned int i = 0; i < node->getNumEdges(); i++) {
458                         CycleNode *next = node->getEdge(i);
459                         if (!discovered->contains(next)) {
460                                 discovered->put(next, next);
461                                 queue.push_back(next);
462                         }
463                 }
464         }
465         return false;
466 }
467
468 void CycleGraph::startChanges()
469 {
470         ASSERT(rollbackvector.empty());
471         ASSERT(rmwrollbackvector.empty());
472         ASSERT(oldCycles == hasCycles);
473 }
474
475 /** Commit changes to the cyclegraph. */
476 void CycleGraph::commitChanges()
477 {
478         rollbackvector.clear();
479         rmwrollbackvector.clear();
480         oldCycles = hasCycles;
481 }
482
483 /** Rollback changes to the previous commit. */
484 void CycleGraph::rollbackChanges()
485 {
486         for (unsigned int i = 0; i < rollbackvector.size(); i++)
487                 rollbackvector[i]->removeEdge();
488
489         for (unsigned int i = 0; i < rmwrollbackvector.size(); i++)
490                 rmwrollbackvector[i]->clearRMW();
491
492         hasCycles = oldCycles;
493         rollbackvector.clear();
494         rmwrollbackvector.clear();
495 }
496
497 /** @returns whether a CycleGraph contains cycles. */
498 bool CycleGraph::checkForCycles() const
499 {
500         return hasCycles;
501 }
502
503 /**
504  * @brief Constructor for a CycleNode
505  * @param act The ModelAction for this node
506  */
507 CycleNode::CycleNode(const ModelAction *act) :
508         action(act),
509         promise(NULL),
510         hasRMW(NULL)
511 {
512 }
513
514 /**
515  * @brief Constructor for a Promise CycleNode
516  * @param promise The Promise which was generated
517  */
518 CycleNode::CycleNode(const Promise *promise) :
519         action(NULL),
520         promise(promise),
521         hasRMW(NULL)
522 {
523 }
524
525 /**
526  * @param i The index of the edge to return
527  * @returns The a CycleNode edge indexed by i
528  */
529 CycleNode * CycleNode::getEdge(unsigned int i) const
530 {
531         return edges[i];
532 }
533
534 /** @returns The number of edges leaving this CycleNode */
535 unsigned int CycleNode::getNumEdges() const
536 {
537         return edges.size();
538 }
539
540 CycleNode * CycleNode::getBackEdge(unsigned int i) const
541 {
542         return back_edges[i];
543 }
544
545 unsigned int CycleNode::getNumBackEdges() const
546 {
547         return back_edges.size();
548 }
549
550 /**
551  * @brief Remove an element from a vector
552  * @param v The vector
553  * @param n The element to remove
554  * @return True if the element was found; false otherwise
555  */
556 template <typename T>
557 static bool vector_remove_node(std::vector<T, SnapshotAlloc<T> >& v, const T n)
558 {
559         for (unsigned int i = 0; i < v.size(); i++) {
560                 if (v[i] == n) {
561                         v.erase(v.begin() + i);
562                         return true;
563                 }
564         }
565         return false;
566 }
567
568 /**
569  * @brief Remove a (forward) edge from this CycleNode
570  * @return The CycleNode which was popped, if one exists; otherwise NULL
571  */
572 CycleNode * CycleNode::removeEdge()
573 {
574         if (edges.empty())
575                 return NULL;
576
577         CycleNode *ret = edges.back();
578         edges.pop_back();
579         vector_remove_node(ret->back_edges, this);
580         return ret;
581 }
582
583 /**
584  * @brief Remove a (back) edge from this CycleNode
585  * @return The CycleNode which was popped, if one exists; otherwise NULL
586  */
587 CycleNode * CycleNode::removeBackEdge()
588 {
589         if (back_edges.empty())
590                 return NULL;
591
592         CycleNode *ret = back_edges.back();
593         back_edges.pop_back();
594         vector_remove_node(ret->edges, this);
595         return ret;
596 }
597
598 /**
599  * Adds an edge from this CycleNode to another CycleNode.
600  * @param node The node to which we add a directed edge
601  * @return True if this edge is a new edge; false otherwise
602  */
603 bool CycleNode::addEdge(CycleNode *node)
604 {
605         for (unsigned int i = 0; i < edges.size(); i++)
606                 if (edges[i] == node)
607                         return false;
608         edges.push_back(node);
609         node->back_edges.push_back(this);
610         return true;
611 }
612
613 /** @returns the RMW CycleNode that reads from the current CycleNode */
614 CycleNode * CycleNode::getRMW() const
615 {
616         return hasRMW;
617 }
618
619 /**
620  * Set a RMW action node that reads from the current CycleNode.
621  * @param node The RMW that reads from the current node
622  * @return True, if this node already was read by another RMW; false otherwise
623  * @see CycleGraph::addRMWEdge
624  */
625 bool CycleNode::setRMW(CycleNode *node)
626 {
627         if (hasRMW != NULL)
628                 return true;
629         hasRMW = node;
630         return false;
631 }
632
633 /**
634  * Convert a Promise CycleNode into a concrete-valued CycleNode. Should only be
635  * used when there's no existing ModelAction CycleNode for this write.
636  *
637  * @param writer The ModelAction which wrote the future value represented by
638  * this CycleNode
639  */
640 void CycleNode::resolvePromise(const ModelAction *writer)
641 {
642         ASSERT(is_promise());
643         ASSERT(promise->is_compatible(writer));
644         action = writer;
645         promise = NULL;
646         ASSERT(!is_promise());
647 }