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