cyclebreaker.nim 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2020 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. #[
  10. A Cycle breaker for Nim
  11. -----------------------
  12. Instead of "collecting" cycles with all of its pitfalls we will break cycles.
  13. We exploit that every 'ref' can be 'nil' for this and so get away without
  14. a distinction between weak and strong pointers. The required runtime
  15. mechanisms are the same though: We need to be able to traverse the graph.
  16. This design has the tremendous benefit that it doesn't require a dedicated
  17. 'rawDispose' operation and that it plays well with Nim's cost model.
  18. The cost of freeing a subgraph with cycles is 2 * N rather than N, that's all.
  19. Cycles do not have to be prepared via .acyclic, there are not multiple
  20. pointless traversals, only a single proc, `breakCycles` is exposed as a
  21. separate module.
  22. Algorithm
  23. ---------
  24. We traverse the graph and notice the nodes we've already traversed. If we
  25. marked the node already, we set the pointer that leads to this node to 'nil'
  26. and decrement the reference count of the cell we pointed at.
  27. We notice that multiple paths to the same object do not mean
  28. we found a cycle, it only means the node is shared.
  29. a -------> b <----- c
  30. | ^ ^
  31. +----------+ |
  32. | |
  33. +-------------------+
  34. If we simply remove all links to already processed nodes we end up with:
  35. a -------> b c
  36. | ^
  37. + |
  38. | |
  39. +-------------------+
  40. That seems acceptable, no leak is produced. This implies that the standard
  41. depth-first traversal suffices.
  42. ]#
  43. include cellseqs_v2
  44. const
  45. colGreen = 0b000
  46. colYellow = 0b001
  47. colRed = 0b010
  48. colorMask = 0b011
  49. type
  50. TraceProc = proc (p, env: pointer) {.nimcall, benign.}
  51. DisposeProc = proc (p: pointer) {.nimcall, benign.}
  52. template color(c): untyped = c.rc and colorMask
  53. template setColor(c, col) =
  54. c.rc = c.rc and not colorMask or col
  55. proc nimIncRefCyclic(p: pointer; cyclic: bool) {.compilerRtl, inl.} =
  56. let h = head(p)
  57. inc h.rc, rcIncrement
  58. proc nimMarkCyclic(p: pointer) {.compilerRtl, inl.} = discard
  59. type
  60. GcEnv = object
  61. traceStack: CellSeq[ptr pointer]
  62. proc trace(p: pointer; desc: PNimTypeV2; j: var GcEnv) {.inline.} =
  63. when false:
  64. cprintf("[Trace] desc: %p %p\n", desc, p)
  65. cprintf("[Trace] trace: %p\n", desc.traceImpl)
  66. if desc.traceImpl != nil:
  67. cast[TraceProc](desc.traceImpl)(p, addr(j))
  68. proc nimTraceRef(q: pointer; desc: PNimTypeV2; env: pointer) {.compilerRtl.} =
  69. let p = cast[ptr pointer](q)
  70. when traceCollector:
  71. cprintf("[Trace] raw: %p\n", p)
  72. cprintf("[Trace] deref: %p\n", p[])
  73. if p[] != nil:
  74. var j = cast[ptr GcEnv](env)
  75. j.traceStack.add(p, desc)
  76. proc nimTraceRefDyn(q: pointer; env: pointer) {.compilerRtl.} =
  77. let p = cast[ptr pointer](q)
  78. when traceCollector:
  79. cprintf("[TraceDyn] raw: %p\n", p)
  80. cprintf("[TraceDyn] deref: %p\n", p[])
  81. if p[] != nil:
  82. var j = cast[ptr GcEnv](env)
  83. j.traceStack.add(p, cast[ptr PNimTypeV2](p[])[])
  84. var markerGeneration: int
  85. proc breakCycles(s: Cell; desc: PNimTypeV2) =
  86. let markerColor = if (markerGeneration and 1) == 0: colRed
  87. else: colYellow
  88. atomicInc markerGeneration
  89. when traceCollector:
  90. cprintf("[BreakCycles] starting: %p %s RC %ld trace proc %p\n",
  91. s, desc.name, s.rc shr rcShift, desc.traceImpl)
  92. var j: GcEnv
  93. init j.traceStack
  94. s.setColor markerColor
  95. trace(s +! sizeof(RefHeader), desc, j)
  96. while j.traceStack.len > 0:
  97. let (u, desc) = j.traceStack.pop()
  98. let p = u[]
  99. let t = head(p)
  100. if t.color != markerColor:
  101. t.setColor markerColor
  102. trace(p, desc, j)
  103. when traceCollector:
  104. cprintf("[BreakCycles] followed: %p RC %ld\n", t, t.rc shr rcShift)
  105. else:
  106. if (t.rc shr rcShift) > 0:
  107. dec t.rc, rcIncrement
  108. # mark as a link that the produced destructor does not have to follow:
  109. u[] = nil
  110. when traceCollector:
  111. cprintf("[BreakCycles] niled out: %p RC %ld\n", t, t.rc shr rcShift)
  112. else:
  113. # anyhow as a link that the produced destructor does not have to follow:
  114. u[] = nil
  115. when traceCollector:
  116. cprintf("[Bug] %p %s RC %ld\n", t, desc.name, t.rc shr rcShift)
  117. deinit j.traceStack
  118. proc thinout*[T](x: ref T) {.inline.} =
  119. ## turn the subgraph starting with `x` into its spanning tree by
  120. ## `nil`'ing out any pointers that would harm the spanning tree
  121. ## structure. Any back pointers that introduced cycles
  122. ## and thus would keep the graph from being freed are `nil`'ed.
  123. ## This is a form of cycle collection that works well with Nim's ARC
  124. ## and its associated cost model.
  125. proc getDynamicTypeInfo[T](x: T): PNimTypeV2 {.magic: "GetTypeInfoV2", noSideEffect.}
  126. breakCycles(head(cast[pointer](x)), getDynamicTypeInfo(x[]))
  127. proc thinout*[T: proc](x: T) {.inline.} =
  128. proc rawEnv[T: proc](x: T): pointer {.noSideEffect, inline.} =
  129. {.emit: """
  130. `result` = `x`.ClE_0;
  131. """.}
  132. let p = rawEnv(x)
  133. breakCycles(head(p), cast[ptr PNimTypeV2](p)[])
  134. proc nimDecRefIsLastCyclicDyn(p: pointer): bool {.compilerRtl, inl.} =
  135. if p != nil:
  136. var cell = head(p)
  137. if (cell.rc and not rcMask) == 0:
  138. result = true
  139. #cprintf("[DESTROY] %p\n", p)
  140. else:
  141. dec cell.rc, rcIncrement
  142. # According to Lins it's correct to do nothing else here.
  143. #cprintf("[DeCREF] %p\n", p)
  144. proc nimDecRefIsLastCyclicStatic(p: pointer; desc: PNimTypeV2): bool {.compilerRtl, inl.} =
  145. if p != nil:
  146. var cell = head(p)
  147. if (cell.rc and not rcMask) == 0:
  148. result = true
  149. #cprintf("[DESTROY] %p %s\n", p, desc.name)
  150. else:
  151. dec cell.rc, rcIncrement
  152. #cprintf("[DeCREF] %p %s %ld\n", p, desc.name, cell.rc)