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