Coverage Report

Created: 2023-09-25 06:27

/src/abseil-cpp/absl/synchronization/internal/graphcycles.cc
Line
Count
Source (jump to first uncovered line)
1
// Copyright 2017 The Abseil Authors.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//      https://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
// GraphCycles provides incremental cycle detection on a dynamic
16
// graph using the following algorithm:
17
//
18
// A dynamic topological sort algorithm for directed acyclic graphs
19
// David J. Pearce, Paul H. J. Kelly
20
// Journal of Experimental Algorithmics (JEA) JEA Homepage archive
21
// Volume 11, 2006, Article No. 1.7
22
//
23
// Brief summary of the algorithm:
24
//
25
// (1) Maintain a rank for each node that is consistent
26
//     with the topological sort of the graph. I.e., path from x to y
27
//     implies rank[x] < rank[y].
28
// (2) When a new edge (x->y) is inserted, do nothing if rank[x] < rank[y].
29
// (3) Otherwise: adjust ranks in the neighborhood of x and y.
30
31
#include "absl/base/attributes.h"
32
// This file is a no-op if the required LowLevelAlloc support is missing.
33
#include "absl/base/internal/low_level_alloc.h"
34
#ifndef ABSL_LOW_LEVEL_ALLOC_MISSING
35
36
#include "absl/synchronization/internal/graphcycles.h"
37
38
#include <algorithm>
39
#include <array>
40
#include <cinttypes>
41
#include <limits>
42
#include "absl/base/internal/hide_ptr.h"
43
#include "absl/base/internal/raw_logging.h"
44
#include "absl/base/internal/spinlock.h"
45
46
// Do not use STL.   This module does not use standard memory allocation.
47
48
namespace absl {
49
ABSL_NAMESPACE_BEGIN
50
namespace synchronization_internal {
51
52
namespace {
53
54
// Avoid LowLevelAlloc's default arena since it calls malloc hooks in
55
// which people are doing things like acquiring Mutexes.
56
ABSL_CONST_INIT static absl::base_internal::SpinLock arena_mu(
57
    absl::kConstInit, base_internal::SCHEDULE_KERNEL_ONLY);
58
ABSL_CONST_INIT static base_internal::LowLevelAlloc::Arena* arena;
59
60
2
static void InitArenaIfNecessary() {
61
2
  arena_mu.Lock();
62
2
  if (arena == nullptr) {
63
2
    arena = base_internal::LowLevelAlloc::NewArena(0);
64
2
  }
65
2
  arena_mu.Unlock();
66
2
}
67
68
// Number of inlined elements in Vec.  Hash table implementation
69
// relies on this being a power of two.
70
static const uint32_t kInline = 8;
71
72
// A simple LowLevelAlloc based resizable vector with inlined storage
73
// for a few elements.  T must be a plain type since constructor
74
// and destructor are not run on elements of type T managed by Vec.
75
template <typename T>
76
class Vec {
77
 public:
78
24
  Vec() { Init(); }
graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<absl::synchronization_internal::(anonymous namespace)::Node*>::Vec()
Line
Count
Source
78
2
  Vec() { Init(); }
graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<int>::Vec()
Line
Count
Source
78
22
  Vec() { Init(); }
79
0
  ~Vec() { Discard(); }
Unexecuted instantiation: graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<int>::~Vec()
Unexecuted instantiation: graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<absl::synchronization_internal::(anonymous namespace)::Node*>::~Vec()
80
81
10
  void clear() {
82
10
    Discard();
83
10
    Init();
84
10
  }
85
86
5
  bool empty() const { return size_ == 0; }
87
95
  uint32_t size() const { return size_; }
graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<int>::size() const
Line
Count
Source
87
90
  uint32_t size() const { return size_; }
graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<absl::synchronization_internal::(anonymous namespace)::Node*>::size() const
Line
Count
Source
87
5
  uint32_t size() const { return size_; }
88
0
  T* begin() { return ptr_; }
Unexecuted instantiation: graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<int>::begin()
Unexecuted instantiation: graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<absl::synchronization_internal::(anonymous namespace)::Node*>::begin()
89
0
  T* end() { return ptr_ + size_; }
Unexecuted instantiation: graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<int>::end()
Unexecuted instantiation: graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<absl::synchronization_internal::(anonymous namespace)::Node*>::end()
90
6.48M
  const T& operator[](uint32_t i) const { return ptr_[i]; }
graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<absl::synchronization_internal::(anonymous namespace)::Node*>::operator[](unsigned int) const
Line
Count
Source
90
6.48M
  const T& operator[](uint32_t i) const { return ptr_[i]; }
Unexecuted instantiation: graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<int>::operator[](unsigned int) const
91
6.48M
  T& operator[](uint32_t i) { return ptr_[i]; }
Unexecuted instantiation: graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<int>::operator[](unsigned int)
graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<absl::synchronization_internal::(anonymous namespace)::Node*>::operator[](unsigned int)
Line
Count
Source
91
6.48M
  T& operator[](uint32_t i) { return ptr_[i]; }
92
0
  const T& back() const { return ptr_[size_-1]; }
93
0
  void pop_back() { size_--; }
94
95
5
  void push_back(const T& v) {
96
5
    if (size_ == capacity_) Grow(size_ + 1);
97
5
    ptr_[size_] = v;
98
5
    size_++;
99
5
  }
graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<absl::synchronization_internal::(anonymous namespace)::Node*>::push_back(absl::synchronization_internal::(anonymous namespace)::Node* const&)
Line
Count
Source
95
5
  void push_back(const T& v) {
96
5
    if (size_ == capacity_) Grow(size_ + 1);
97
5
    ptr_[size_] = v;
98
5
    size_++;
99
5
  }
Unexecuted instantiation: graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<int>::push_back(int const&)
100
101
10
  void resize(uint32_t n) {
102
10
    if (n > capacity_) Grow(n);
103
10
    size_ = n;
104
10
  }
105
106
10
  void fill(const T& val) {
107
90
    for (uint32_t i = 0; i < size(); i++) {
108
80
      ptr_[i] = val;
109
80
    }
110
10
  }
111
112
  // Guarantees src is empty at end.
113
  // Provided for the hash table resizing code below.
114
0
  void MoveFrom(Vec<T>* src) {
115
0
    if (src->ptr_ == src->space_) {
116
      // Need to actually copy
117
0
      resize(src->size_);
118
0
      std::copy_n(src->ptr_, src->size_, ptr_);
119
0
      src->size_ = 0;
120
0
    } else {
121
0
      Discard();
122
0
      ptr_ = src->ptr_;
123
0
      size_ = src->size_;
124
0
      capacity_ = src->capacity_;
125
0
      src->Init();
126
0
    }
127
0
  }
128
129
 private:
130
  T* ptr_;
131
  T space_[kInline];
132
  uint32_t size_;
133
  uint32_t capacity_;
134
135
34
  void Init() {
136
34
    ptr_ = space_;
137
34
    size_ = 0;
138
34
    capacity_ = kInline;
139
34
  }
graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<absl::synchronization_internal::(anonymous namespace)::Node*>::Init()
Line
Count
Source
135
2
  void Init() {
136
2
    ptr_ = space_;
137
2
    size_ = 0;
138
2
    capacity_ = kInline;
139
2
  }
graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<int>::Init()
Line
Count
Source
135
32
  void Init() {
136
32
    ptr_ = space_;
137
32
    size_ = 0;
138
32
    capacity_ = kInline;
139
32
  }
140
141
10
  void Discard() {
142
10
    if (ptr_ != space_) base_internal::LowLevelAlloc::Free(ptr_);
143
10
  }
graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<int>::Discard()
Line
Count
Source
141
10
  void Discard() {
142
10
    if (ptr_ != space_) base_internal::LowLevelAlloc::Free(ptr_);
143
10
  }
Unexecuted instantiation: graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<absl::synchronization_internal::(anonymous namespace)::Node*>::Discard()
144
145
0
  void Grow(uint32_t n) {
146
0
    while (capacity_ < n) {
147
0
      capacity_ *= 2;
148
0
    }
149
0
    size_t request = static_cast<size_t>(capacity_) * sizeof(T);
150
0
    T* copy = static_cast<T*>(
151
0
        base_internal::LowLevelAlloc::AllocWithArena(request, arena));
152
0
    std::copy_n(ptr_, size_, copy);
153
0
    Discard();
154
0
    ptr_ = copy;
155
0
  }
Unexecuted instantiation: graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<int>::Grow(unsigned int)
Unexecuted instantiation: graphcycles.cc:absl::synchronization_internal::(anonymous namespace)::Vec<absl::synchronization_internal::(anonymous namespace)::Node*>::Grow(unsigned int)
156
157
  Vec(const Vec&) = delete;
158
  Vec& operator=(const Vec&) = delete;
159
};
160
161
// A hash set of non-negative int32_t that uses Vec for its underlying storage.
162
class NodeSet {
163
 public:
164
10
  NodeSet() { Init(); }
165
166
0
  void clear() { Init(); }
167
0
  bool contains(int32_t v) const { return table_[FindIndex(v)] == v; }
168
169
0
  bool insert(int32_t v) {
170
0
    uint32_t i = FindIndex(v);
171
0
    if (table_[i] == v) {
172
0
      return false;
173
0
    }
174
0
    if (table_[i] == kEmpty) {
175
      // Only inserting over an empty cell increases the number of occupied
176
      // slots.
177
0
      occupied_++;
178
0
    }
179
0
    table_[i] = v;
180
    // Double when 75% full.
181
0
    if (occupied_ >= table_.size() - table_.size()/4) Grow();
182
0
    return true;
183
0
  }
184
185
0
  void erase(int32_t v) {
186
0
    uint32_t i = FindIndex(v);
187
0
    if (table_[i] == v) {
188
0
      table_[i] = kDel;
189
0
    }
190
0
  }
191
192
  // Iteration: is done via HASH_FOR_EACH
193
  // Example:
194
  //    HASH_FOR_EACH(elem, node->out) { ... }
195
#define HASH_FOR_EACH(elem, eset) \
196
0
  for (int32_t elem, _cursor = 0; (eset).Next(&_cursor, &elem); )
197
0
  bool Next(int32_t* cursor, int32_t* elem) {
198
0
    while (static_cast<uint32_t>(*cursor) < table_.size()) {
199
0
      int32_t v = table_[static_cast<uint32_t>(*cursor)];
200
0
      (*cursor)++;
201
0
      if (v >= 0) {
202
0
        *elem = v;
203
0
        return true;
204
0
      }
205
0
    }
206
0
    return false;
207
0
  }
208
209
 private:
210
  enum : int32_t { kEmpty = -1, kDel = -2 };
211
  Vec<int32_t> table_;
212
  uint32_t occupied_;     // Count of non-empty slots (includes deleted slots)
213
214
0
  static uint32_t Hash(int32_t a) { return static_cast<uint32_t>(a * 41); }
215
216
  // Return index for storing v.  May return an empty index or deleted index
217
0
  uint32_t FindIndex(int32_t v) const {
218
    // Search starting at hash index.
219
0
    const uint32_t mask = table_.size() - 1;
220
0
    uint32_t i = Hash(v) & mask;
221
0
    uint32_t deleted_index = 0;  // index of first deleted element we see
222
0
    bool seen_deleted_element = false;
223
0
    while (true) {
224
0
      int32_t e = table_[i];
225
0
      if (v == e) {
226
0
        return i;
227
0
      } else if (e == kEmpty) {
228
        // Return any previously encountered deleted slot.
229
0
        return seen_deleted_element ? deleted_index : i;
230
0
      } else if (e == kDel && !seen_deleted_element) {
231
        // Keep searching since v might be present later.
232
0
        deleted_index = i;
233
0
        seen_deleted_element = true;
234
0
      }
235
0
      i = (i + 1) & mask;  // Linear probing; quadratic is slightly slower.
236
0
    }
237
0
  }
238
239
10
  void Init() {
240
10
    table_.clear();
241
10
    table_.resize(kInline);
242
10
    table_.fill(kEmpty);
243
10
    occupied_ = 0;
244
10
  }
245
246
0
  void Grow() {
247
0
    Vec<int32_t> copy;
248
0
    copy.MoveFrom(&table_);
249
0
    occupied_ = 0;
250
0
    table_.resize(copy.size() * 2);
251
0
    table_.fill(kEmpty);
252
253
0
    for (const auto& e : copy) {
254
0
      if (e >= 0) insert(e);
255
0
    }
256
0
  }
257
258
  NodeSet(const NodeSet&) = delete;
259
  NodeSet& operator=(const NodeSet&) = delete;
260
};
261
262
// We encode a node index and a node version in GraphId.  The version
263
// number is incremented when the GraphId is freed which automatically
264
// invalidates all copies of the GraphId.
265
266
6.48M
inline GraphId MakeId(int32_t index, uint32_t version) {
267
6.48M
  GraphId g;
268
6.48M
  g.handle =
269
6.48M
      (static_cast<uint64_t>(version) << 32) | static_cast<uint32_t>(index);
270
6.48M
  return g;
271
6.48M
}
272
273
0
inline int32_t NodeIndex(GraphId id) {
274
0
  return static_cast<int32_t>(id.handle);
275
0
}
276
277
0
inline uint32_t NodeVersion(GraphId id) {
278
0
  return static_cast<uint32_t>(id.handle >> 32);
279
0
}
280
281
struct Node {
282
  int32_t rank;               // rank number assigned by Pearce-Kelly algorithm
283
  uint32_t version;           // Current version number
284
  int32_t next_hash;          // Next entry in hash table
285
  bool visited;               // Temporary marker used by depth-first-search
286
  uintptr_t masked_ptr;       // User-supplied pointer
287
  NodeSet in;                 // List of immediate predecessor nodes in graph
288
  NodeSet out;                // List of immediate successor nodes in graph
289
  int priority;               // Priority of recorded stack trace.
290
  int nstack;                 // Depth of recorded stack trace.
291
  void* stack[40];            // stack[0,nstack-1] holds stack trace for node.
292
};
293
294
// Hash table for pointer to node index lookups.
295
class PointerMap {
296
 public:
297
2
  explicit PointerMap(const Vec<Node*>* nodes) : nodes_(nodes) {
298
2
    table_.fill(-1);
299
2
  }
300
301
6.48M
  int32_t Find(void* ptr) {
302
6.48M
    auto masked = base_internal::HidePtr(ptr);
303
6.48M
    for (int32_t i = table_[Hash(ptr)]; i != -1;) {
304
6.48M
      Node* n = (*nodes_)[static_cast<uint32_t>(i)];
305
6.48M
      if (n->masked_ptr == masked) return i;
306
0
      i = n->next_hash;
307
0
    }
308
5
    return -1;
309
6.48M
  }
310
311
5
  void Add(void* ptr, int32_t i) {
312
5
    int32_t* head = &table_[Hash(ptr)];
313
5
    (*nodes_)[static_cast<uint32_t>(i)]->next_hash = *head;
314
5
    *head = i;
315
5
  }
316
317
0
  int32_t Remove(void* ptr) {
318
    // Advance through linked list while keeping track of the
319
    // predecessor slot that points to the current entry.
320
0
    auto masked = base_internal::HidePtr(ptr);
321
0
    for (int32_t* slot = &table_[Hash(ptr)]; *slot != -1; ) {
322
0
      int32_t index = *slot;
323
0
      Node* n = (*nodes_)[static_cast<uint32_t>(index)];
324
0
      if (n->masked_ptr == masked) {
325
0
        *slot = n->next_hash;  // Remove n from linked list
326
0
        n->next_hash = -1;
327
0
        return index;
328
0
      }
329
0
      slot = &n->next_hash;
330
0
    }
331
0
    return -1;
332
0
  }
333
334
 private:
335
  // Number of buckets in hash table for pointer lookups.
336
  static constexpr uint32_t kHashTableSize = 8171;  // should be prime
337
338
  const Vec<Node*>* nodes_;
339
  std::array<int32_t, kHashTableSize> table_;
340
341
6.48M
  static uint32_t Hash(void* ptr) {
342
6.48M
    return reinterpret_cast<uintptr_t>(ptr) % kHashTableSize;
343
6.48M
  }
344
};
345
346
}  // namespace
347
348
struct GraphCycles::Rep {
349
  Vec<Node*> nodes_;
350
  Vec<int32_t> free_nodes_;  // Indices for unused entries in nodes_
351
  PointerMap ptrmap_;
352
353
  // Temporary state.
354
  Vec<int32_t> deltaf_;  // Results of forward DFS
355
  Vec<int32_t> deltab_;  // Results of backward DFS
356
  Vec<int32_t> list_;    // All nodes to reprocess
357
  Vec<int32_t> merged_;  // Rank values to assign to list_ entries
358
  Vec<int32_t> stack_;   // Emulates recursion stack for depth-first searches
359
360
2
  Rep() : ptrmap_(&nodes_) {}
361
};
362
363
0
static Node* FindNode(GraphCycles::Rep* rep, GraphId id) {
364
0
  Node* n = rep->nodes_[static_cast<uint32_t>(NodeIndex(id))];
365
0
  return (n->version == NodeVersion(id)) ? n : nullptr;
366
0
}
367
368
2
GraphCycles::GraphCycles() {
369
2
  InitArenaIfNecessary();
370
2
  rep_ = new (base_internal::LowLevelAlloc::AllocWithArena(sizeof(Rep), arena))
371
2
      Rep;
372
2
}
373
374
0
GraphCycles::~GraphCycles() {
375
0
  for (auto* node : rep_->nodes_) {
376
0
    node->Node::~Node();
377
0
    base_internal::LowLevelAlloc::Free(node);
378
0
  }
379
0
  rep_->Rep::~Rep();
380
0
  base_internal::LowLevelAlloc::Free(rep_);
381
0
}
382
383
0
bool GraphCycles::CheckInvariants() const {
384
0
  Rep* r = rep_;
385
0
  NodeSet ranks;  // Set of ranks seen so far.
386
0
  for (uint32_t x = 0; x < r->nodes_.size(); x++) {
387
0
    Node* nx = r->nodes_[x];
388
0
    void* ptr = base_internal::UnhidePtr<void>(nx->masked_ptr);
389
0
    if (ptr != nullptr && static_cast<uint32_t>(r->ptrmap_.Find(ptr)) != x) {
390
0
      ABSL_RAW_LOG(FATAL, "Did not find live node in hash table %" PRIu32 " %p",
391
0
                   x, ptr);
392
0
    }
393
0
    if (nx->visited) {
394
0
      ABSL_RAW_LOG(FATAL, "Did not clear visited marker on node %" PRIu32, x);
395
0
    }
396
0
    if (!ranks.insert(nx->rank)) {
397
0
      ABSL_RAW_LOG(FATAL, "Duplicate occurrence of rank %" PRId32, nx->rank);
398
0
    }
399
0
    HASH_FOR_EACH(y, nx->out) {
400
0
      Node* ny = r->nodes_[static_cast<uint32_t>(y)];
401
0
      if (nx->rank >= ny->rank) {
402
0
        ABSL_RAW_LOG(FATAL,
403
0
                     "Edge %" PRIu32 " ->%" PRId32
404
0
                     " has bad rank assignment %" PRId32 "->%" PRId32,
405
0
                     x, y, nx->rank, ny->rank);
406
0
      }
407
0
    }
408
0
  }
409
0
  return true;
410
0
}
411
412
6.48M
GraphId GraphCycles::GetId(void* ptr) {
413
6.48M
  int32_t i = rep_->ptrmap_.Find(ptr);
414
6.48M
  if (i != -1) {
415
6.48M
    return MakeId(i, rep_->nodes_[static_cast<uint32_t>(i)]->version);
416
6.48M
  } else if (rep_->free_nodes_.empty()) {
417
5
    Node* n =
418
5
        new (base_internal::LowLevelAlloc::AllocWithArena(sizeof(Node), arena))
419
5
            Node;
420
5
    n->version = 1;  // Avoid 0 since it is used by InvalidGraphId()
421
5
    n->visited = false;
422
5
    n->rank = static_cast<int32_t>(rep_->nodes_.size());
423
5
    n->masked_ptr = base_internal::HidePtr(ptr);
424
5
    n->nstack = 0;
425
5
    n->priority = 0;
426
5
    rep_->nodes_.push_back(n);
427
5
    rep_->ptrmap_.Add(ptr, n->rank);
428
5
    return MakeId(n->rank, n->version);
429
5
  } else {
430
    // Preserve preceding rank since the set of ranks in use must be
431
    // a permutation of [0,rep_->nodes_.size()-1].
432
0
    int32_t r = rep_->free_nodes_.back();
433
0
    rep_->free_nodes_.pop_back();
434
0
    Node* n = rep_->nodes_[static_cast<uint32_t>(r)];
435
0
    n->masked_ptr = base_internal::HidePtr(ptr);
436
0
    n->nstack = 0;
437
0
    n->priority = 0;
438
0
    rep_->ptrmap_.Add(ptr, r);
439
0
    return MakeId(r, n->version);
440
0
  }
441
6.48M
}
442
443
0
void GraphCycles::RemoveNode(void* ptr) {
444
0
  int32_t i = rep_->ptrmap_.Remove(ptr);
445
0
  if (i == -1) {
446
0
    return;
447
0
  }
448
0
  Node* x = rep_->nodes_[static_cast<uint32_t>(i)];
449
0
  HASH_FOR_EACH(y, x->out) {
450
0
    rep_->nodes_[static_cast<uint32_t>(y)]->in.erase(i);
451
0
  }
452
0
  HASH_FOR_EACH(y, x->in) {
453
0
    rep_->nodes_[static_cast<uint32_t>(y)]->out.erase(i);
454
0
  }
455
0
  x->in.clear();
456
0
  x->out.clear();
457
0
  x->masked_ptr = base_internal::HidePtr<void>(nullptr);
458
0
  if (x->version == std::numeric_limits<uint32_t>::max()) {
459
    // Cannot use x any more
460
0
  } else {
461
0
    x->version++;  // Invalidates all copies of node.
462
0
    rep_->free_nodes_.push_back(i);
463
0
  }
464
0
}
465
466
0
void* GraphCycles::Ptr(GraphId id) {
467
0
  Node* n = FindNode(rep_, id);
468
0
  return n == nullptr ? nullptr
469
0
                      : base_internal::UnhidePtr<void>(n->masked_ptr);
470
0
}
471
472
0
bool GraphCycles::HasNode(GraphId node) {
473
0
  return FindNode(rep_, node) != nullptr;
474
0
}
475
476
0
bool GraphCycles::HasEdge(GraphId x, GraphId y) const {
477
0
  Node* xn = FindNode(rep_, x);
478
0
  return xn && FindNode(rep_, y) && xn->out.contains(NodeIndex(y));
479
0
}
480
481
0
void GraphCycles::RemoveEdge(GraphId x, GraphId y) {
482
0
  Node* xn = FindNode(rep_, x);
483
0
  Node* yn = FindNode(rep_, y);
484
0
  if (xn && yn) {
485
0
    xn->out.erase(NodeIndex(y));
486
0
    yn->in.erase(NodeIndex(x));
487
    // No need to update the rank assignment since a previous valid
488
    // rank assignment remains valid after an edge deletion.
489
0
  }
490
0
}
491
492
static bool ForwardDFS(GraphCycles::Rep* r, int32_t n, int32_t upper_bound);
493
static void BackwardDFS(GraphCycles::Rep* r, int32_t n, int32_t lower_bound);
494
static void Reorder(GraphCycles::Rep* r);
495
static void Sort(const Vec<Node*>&, Vec<int32_t>* delta);
496
static void MoveToList(
497
    GraphCycles::Rep* r, Vec<int32_t>* src, Vec<int32_t>* dst);
498
499
0
bool GraphCycles::InsertEdge(GraphId idx, GraphId idy) {
500
0
  Rep* r = rep_;
501
0
  const int32_t x = NodeIndex(idx);
502
0
  const int32_t y = NodeIndex(idy);
503
0
  Node* nx = FindNode(r, idx);
504
0
  Node* ny = FindNode(r, idy);
505
0
  if (nx == nullptr || ny == nullptr) return true;  // Expired ids
506
507
0
  if (nx == ny) return false;  // Self edge
508
0
  if (!nx->out.insert(y)) {
509
    // Edge already exists.
510
0
    return true;
511
0
  }
512
513
0
  ny->in.insert(x);
514
515
0
  if (nx->rank <= ny->rank) {
516
    // New edge is consistent with existing rank assignment.
517
0
    return true;
518
0
  }
519
520
  // Current rank assignments are incompatible with the new edge.  Recompute.
521
  // We only need to consider nodes that fall in the range [ny->rank,nx->rank].
522
0
  if (!ForwardDFS(r, y, nx->rank)) {
523
    // Found a cycle.  Undo the insertion and tell caller.
524
0
    nx->out.erase(y);
525
0
    ny->in.erase(x);
526
    // Since we do not call Reorder() on this path, clear any visited
527
    // markers left by ForwardDFS.
528
0
    for (const auto& d : r->deltaf_) {
529
0
      r->nodes_[static_cast<uint32_t>(d)]->visited = false;
530
0
    }
531
0
    return false;
532
0
  }
533
0
  BackwardDFS(r, x, ny->rank);
534
0
  Reorder(r);
535
0
  return true;
536
0
}
537
538
0
static bool ForwardDFS(GraphCycles::Rep* r, int32_t n, int32_t upper_bound) {
539
  // Avoid recursion since stack space might be limited.
540
  // We instead keep a stack of nodes to visit.
541
0
  r->deltaf_.clear();
542
0
  r->stack_.clear();
543
0
  r->stack_.push_back(n);
544
0
  while (!r->stack_.empty()) {
545
0
    n = r->stack_.back();
546
0
    r->stack_.pop_back();
547
0
    Node* nn = r->nodes_[static_cast<uint32_t>(n)];
548
0
    if (nn->visited) continue;
549
550
0
    nn->visited = true;
551
0
    r->deltaf_.push_back(n);
552
553
0
    HASH_FOR_EACH(w, nn->out) {
554
0
      Node* nw = r->nodes_[static_cast<uint32_t>(w)];
555
0
      if (nw->rank == upper_bound) {
556
0
        return false;  // Cycle
557
0
      }
558
0
      if (!nw->visited && nw->rank < upper_bound) {
559
0
        r->stack_.push_back(w);
560
0
      }
561
0
    }
562
0
  }
563
0
  return true;
564
0
}
565
566
0
static void BackwardDFS(GraphCycles::Rep* r, int32_t n, int32_t lower_bound) {
567
0
  r->deltab_.clear();
568
0
  r->stack_.clear();
569
0
  r->stack_.push_back(n);
570
0
  while (!r->stack_.empty()) {
571
0
    n = r->stack_.back();
572
0
    r->stack_.pop_back();
573
0
    Node* nn = r->nodes_[static_cast<uint32_t>(n)];
574
0
    if (nn->visited) continue;
575
576
0
    nn->visited = true;
577
0
    r->deltab_.push_back(n);
578
579
0
    HASH_FOR_EACH(w, nn->in) {
580
0
      Node* nw = r->nodes_[static_cast<uint32_t>(w)];
581
0
      if (!nw->visited && lower_bound < nw->rank) {
582
0
        r->stack_.push_back(w);
583
0
      }
584
0
    }
585
0
  }
586
0
}
587
588
0
static void Reorder(GraphCycles::Rep* r) {
589
0
  Sort(r->nodes_, &r->deltab_);
590
0
  Sort(r->nodes_, &r->deltaf_);
591
592
  // Adds contents of delta lists to list_ (backwards deltas first).
593
0
  r->list_.clear();
594
0
  MoveToList(r, &r->deltab_, &r->list_);
595
0
  MoveToList(r, &r->deltaf_, &r->list_);
596
597
  // Produce sorted list of all ranks that will be reassigned.
598
0
  r->merged_.resize(r->deltab_.size() + r->deltaf_.size());
599
0
  std::merge(r->deltab_.begin(), r->deltab_.end(),
600
0
             r->deltaf_.begin(), r->deltaf_.end(),
601
0
             r->merged_.begin());
602
603
  // Assign the ranks in order to the collected list.
604
0
  for (uint32_t i = 0; i < r->list_.size(); i++) {
605
0
    r->nodes_[static_cast<uint32_t>(r->list_[i])]->rank = r->merged_[i];
606
0
  }
607
0
}
608
609
0
static void Sort(const Vec<Node*>& nodes, Vec<int32_t>* delta) {
610
0
  struct ByRank {
611
0
    const Vec<Node*>* nodes;
612
0
    bool operator()(int32_t a, int32_t b) const {
613
0
      return (*nodes)[static_cast<uint32_t>(a)]->rank <
614
0
             (*nodes)[static_cast<uint32_t>(b)]->rank;
615
0
    }
616
0
  };
617
0
  ByRank cmp;
618
0
  cmp.nodes = &nodes;
619
0
  std::sort(delta->begin(), delta->end(), cmp);
620
0
}
621
622
static void MoveToList(
623
0
    GraphCycles::Rep* r, Vec<int32_t>* src, Vec<int32_t>* dst) {
624
0
  for (auto& v : *src) {
625
0
    int32_t w = v;
626
    // Replace v entry with its rank
627
0
    v = r->nodes_[static_cast<uint32_t>(w)]->rank;
628
    // Prepare for future DFS calls
629
0
    r->nodes_[static_cast<uint32_t>(w)]->visited = false;
630
0
    dst->push_back(w);
631
0
  }
632
0
}
633
634
int GraphCycles::FindPath(GraphId idx, GraphId idy, int max_path_len,
635
0
                          GraphId path[]) const {
636
0
  Rep* r = rep_;
637
0
  if (FindNode(r, idx) == nullptr || FindNode(r, idy) == nullptr) return 0;
638
0
  const int32_t x = NodeIndex(idx);
639
0
  const int32_t y = NodeIndex(idy);
640
641
  // Forward depth first search starting at x until we hit y.
642
  // As we descend into a node, we push it onto the path.
643
  // As we leave a node, we remove it from the path.
644
0
  int path_len = 0;
645
646
0
  NodeSet seen;
647
0
  r->stack_.clear();
648
0
  r->stack_.push_back(x);
649
0
  while (!r->stack_.empty()) {
650
0
    int32_t n = r->stack_.back();
651
0
    r->stack_.pop_back();
652
0
    if (n < 0) {
653
      // Marker to indicate that we are leaving a node
654
0
      path_len--;
655
0
      continue;
656
0
    }
657
658
0
    if (path_len < max_path_len) {
659
0
      path[path_len] =
660
0
          MakeId(n, rep_->nodes_[static_cast<uint32_t>(n)]->version);
661
0
    }
662
0
    path_len++;
663
0
    r->stack_.push_back(-1);  // Will remove tentative path entry
664
665
0
    if (n == y) {
666
0
      return path_len;
667
0
    }
668
669
0
    HASH_FOR_EACH(w, r->nodes_[static_cast<uint32_t>(n)]->out) {
670
0
      if (seen.insert(w)) {
671
0
        r->stack_.push_back(w);
672
0
      }
673
0
    }
674
0
  }
675
676
0
  return 0;
677
0
}
678
679
0
bool GraphCycles::IsReachable(GraphId x, GraphId y) const {
680
0
  return FindPath(x, y, 0, nullptr) > 0;
681
0
}
682
683
void GraphCycles::UpdateStackTrace(GraphId id, int priority,
684
0
                                   int (*get_stack_trace)(void** stack, int)) {
685
0
  Node* n = FindNode(rep_, id);
686
0
  if (n == nullptr || n->priority >= priority) {
687
0
    return;
688
0
  }
689
0
  n->nstack = (*get_stack_trace)(n->stack, ABSL_ARRAYSIZE(n->stack));
690
0
  n->priority = priority;
691
0
}
692
693
0
int GraphCycles::GetStackTrace(GraphId id, void*** ptr) {
694
0
  Node* n = FindNode(rep_, id);
695
0
  if (n == nullptr) {
696
0
    *ptr = nullptr;
697
0
    return 0;
698
0
  } else {
699
0
    *ptr = n->stack;
700
0
    return n->nstack;
701
0
  }
702
0
}
703
704
}  // namespace synchronization_internal
705
ABSL_NAMESPACE_END
706
}  // namespace absl
707
708
#endif  // ABSL_LOW_LEVEL_ALLOC_MISSING