gc.nim 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2016 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # Garbage Collector
  10. #
  11. # Refcounting + Mark&Sweep. Complex algorithms avoided.
  12. # Been there, done that, didn't work.
  13. {.push profiler:off.}
  14. const
  15. CycleIncrease = 2 # is a multiplicative increase
  16. InitialCycleThreshold = 4*1024*1024 # X MB because cycle checking is slow
  17. InitialZctThreshold = 500 # we collect garbage if the ZCT's size
  18. # reaches this threshold
  19. # this seems to be a good value
  20. withRealTime = defined(useRealtimeGC)
  21. when withRealTime and not declared(getTicks):
  22. include "system/timers"
  23. when defined(memProfiler):
  24. proc nimProfile(requestedSize: int) {.benign.}
  25. when hasThreadSupport:
  26. import sharedlist
  27. const
  28. rcIncrement = 0b1000 # so that lowest 3 bits are not touched
  29. rcBlack = 0b000 # cell is colored black; in use or free
  30. rcGray = 0b001 # possible member of a cycle
  31. rcWhite = 0b010 # member of a garbage cycle
  32. rcPurple = 0b011 # possible root of a cycle
  33. ZctFlag = 0b100 # in ZCT
  34. rcShift = 3 # shift by rcShift to get the reference counter
  35. colorMask = 0b011
  36. type
  37. WalkOp = enum
  38. waMarkGlobal, # part of the backup/debug mark&sweep
  39. waMarkPrecise, # part of the backup/debug mark&sweep
  40. waZctDecRef, waPush
  41. #, waDebug
  42. Finalizer {.compilerproc.} = proc (self: pointer) {.nimcall, benign.}
  43. # A ref type can have a finalizer that is called before the object's
  44. # storage is freed.
  45. GcStat {.final, pure.} = object
  46. stackScans: int # number of performed stack scans (for statistics)
  47. cycleCollections: int # number of performed full collections
  48. maxThreshold: int # max threshold that has been set
  49. maxStackSize: int # max stack size
  50. maxStackCells: int # max stack cells in ``decStack``
  51. cycleTableSize: int # max entries in cycle table
  52. maxPause: int64 # max measured GC pause in nanoseconds
  53. GcStack {.final, pure.} = object
  54. when nimCoroutines:
  55. prev: ptr GcStack
  56. next: ptr GcStack
  57. maxStackSize: int # Used to track statistics because we can not use
  58. # GcStat.maxStackSize when multiple stacks exist.
  59. bottom: pointer
  60. when withRealTime or nimCoroutines:
  61. pos: pointer # Used with `withRealTime` only for code clarity, see GC_Step().
  62. when withRealTime:
  63. bottomSaved: pointer
  64. GcHeap {.final, pure.} = object # this contains the zero count and
  65. # non-zero count table
  66. stack: GcStack
  67. when nimCoroutines:
  68. activeStack: ptr GcStack # current executing coroutine stack.
  69. cycleThreshold: int
  70. zctThreshold: int
  71. when useCellIds:
  72. idGenerator: int
  73. zct: CellSeq # the zero count table
  74. decStack: CellSeq # cells in the stack that are to decref again
  75. tempStack: CellSeq # temporary stack for recursion elimination
  76. recGcLock: int # prevent recursion via finalizers; no thread lock
  77. when withRealTime:
  78. maxPause: Nanos # max allowed pause in nanoseconds; active if > 0
  79. region: MemRegion # garbage collected region
  80. stat: GcStat
  81. marked: CellSet
  82. additionalRoots: CellSeq # dummy roots for GC_ref/unref
  83. when hasThreadSupport:
  84. toDispose: SharedList[pointer]
  85. gcThreadId: int
  86. var
  87. gch {.rtlThreadVar.}: GcHeap
  88. when not defined(useNimRtl):
  89. instantiateForRegion(gch.region)
  90. template gcAssert(cond: bool, msg: string) =
  91. when defined(useGcAssert):
  92. if not cond:
  93. echo "[GCASSERT] ", msg
  94. GC_disable()
  95. writeStackTrace()
  96. #var x: ptr int
  97. #echo x[]
  98. quit 1
  99. proc addZCT(s: var CellSeq, c: PCell) {.noinline.} =
  100. if (c.refcount and ZctFlag) == 0:
  101. c.refcount = c.refcount or ZctFlag
  102. add(s, c)
  103. proc cellToUsr(cell: PCell): pointer {.inline.} =
  104. # convert object (=pointer to refcount) to pointer to userdata
  105. result = cast[pointer](cast[ByteAddress](cell)+%ByteAddress(sizeof(Cell)))
  106. proc usrToCell(usr: pointer): PCell {.inline.} =
  107. # convert pointer to userdata to object (=pointer to refcount)
  108. result = cast[PCell](cast[ByteAddress](usr)-%ByteAddress(sizeof(Cell)))
  109. proc extGetCellType(c: pointer): PNimType {.compilerproc.} =
  110. # used for code generation concerning debugging
  111. result = usrToCell(c).typ
  112. proc internRefcount(p: pointer): int {.exportc: "getRefcount".} =
  113. result = int(usrToCell(p).refcount) shr rcShift
  114. # this that has to equals zero, otherwise we have to round up UnitsPerPage:
  115. when BitsPerPage mod (sizeof(int)*8) != 0:
  116. {.error: "(BitsPerPage mod BitsPerUnit) should be zero!".}
  117. template color(c): untyped = c.refCount and colorMask
  118. template setColor(c, col) =
  119. when col == rcBlack:
  120. c.refcount = c.refcount and not colorMask
  121. else:
  122. c.refcount = c.refcount and not colorMask or col
  123. when defined(logGC):
  124. proc writeCell(msg: cstring, c: PCell) =
  125. var kind = -1
  126. var typName: cstring = "nil"
  127. if c.typ != nil:
  128. kind = ord(c.typ.kind)
  129. when defined(nimTypeNames):
  130. if not c.typ.name.isNil:
  131. typName = c.typ.name
  132. when leakDetector:
  133. c_fprintf(stdout, "[GC] %s: %p %d %s rc=%ld from %s(%ld)\n",
  134. msg, c, kind, typName, c.refcount shr rcShift, c.filename, c.line)
  135. else:
  136. c_fprintf(stdout, "[GC] %s: %p %d %s rc=%ld; thread=%ld\n",
  137. msg, c, kind, typName, c.refcount shr rcShift, gch.gcThreadId)
  138. template gcTrace(cell, state: untyped) =
  139. when traceGC: traceCell(cell, state)
  140. # forward declarations:
  141. proc collectCT(gch: var GcHeap) {.benign.}
  142. proc isOnStack(p: pointer): bool {.noinline, benign.}
  143. proc forAllChildren(cell: PCell, op: WalkOp) {.benign.}
  144. proc doOperation(p: pointer, op: WalkOp) {.benign.}
  145. proc forAllChildrenAux(dest: pointer, mt: PNimType, op: WalkOp) {.benign.}
  146. # we need the prototype here for debugging purposes
  147. proc incRef(c: PCell) {.inline.} =
  148. gcAssert(isAllocatedPtr(gch.region, c), "incRef: interiorPtr")
  149. c.refcount = c.refcount +% rcIncrement
  150. # and not colorMask
  151. #writeCell("incRef", c)
  152. proc nimGCref(p: pointer) {.compilerProc.} =
  153. # we keep it from being collected by pretending it's not even allocated:
  154. let c = usrToCell(p)
  155. add(gch.additionalRoots, c)
  156. incRef(c)
  157. proc rtlAddZCT(c: PCell) {.rtl, inl.} =
  158. # we MUST access gch as a global here, because this crosses DLL boundaries!
  159. addZCT(gch.zct, c)
  160. proc decRef(c: PCell) {.inline.} =
  161. gcAssert(isAllocatedPtr(gch.region, c), "decRef: interiorPtr")
  162. gcAssert(c.refcount >=% rcIncrement, "decRef")
  163. c.refcount = c.refcount -% rcIncrement
  164. if c.refcount <% rcIncrement:
  165. rtlAddZCT(c)
  166. proc nimGCunref(p: pointer) {.compilerProc.} =
  167. let cell = usrToCell(p)
  168. var L = gch.additionalRoots.len-1
  169. var i = L
  170. let d = gch.additionalRoots.d
  171. while i >= 0:
  172. if d[i] == cell:
  173. d[i] = d[L]
  174. dec gch.additionalRoots.len
  175. break
  176. dec(i)
  177. decRef(usrToCell(p))
  178. include gc_common
  179. template beforeDealloc(gch: var GcHeap; c: PCell; msg: typed) =
  180. when false:
  181. for i in 0..gch.decStack.len-1:
  182. if gch.decStack.d[i] == c:
  183. sysAssert(false, msg)
  184. proc nimGCunrefNoCycle(p: pointer) {.compilerProc, inline.} =
  185. sysAssert(allocInv(gch.region), "begin nimGCunrefNoCycle")
  186. decRef(usrToCell(p))
  187. sysAssert(allocInv(gch.region), "end nimGCunrefNoCycle 5")
  188. proc nimGCunrefRC1(p: pointer) {.compilerProc, inline.} =
  189. decRef(usrToCell(p))
  190. proc asgnRef(dest: PPointer, src: pointer) {.compilerProc, inline.} =
  191. # the code generator calls this proc!
  192. gcAssert(not isOnStack(dest), "asgnRef")
  193. # BUGFIX: first incRef then decRef!
  194. if src != nil: incRef(usrToCell(src))
  195. if dest[] != nil: decRef(usrToCell(dest[]))
  196. dest[] = src
  197. proc asgnRefNoCycle(dest: PPointer, src: pointer) {.compilerproc, inline,
  198. deprecated: "old compiler compat".} = asgnRef(dest, src)
  199. proc unsureAsgnRef(dest: PPointer, src: pointer) {.compilerProc.} =
  200. # unsureAsgnRef updates the reference counters only if dest is not on the
  201. # stack. It is used by the code generator if it cannot decide wether a
  202. # reference is in the stack or not (this can happen for var parameters).
  203. if not isOnStack(dest):
  204. if src != nil: incRef(usrToCell(src))
  205. # XXX finally use assembler for the stack checking instead!
  206. # the test for '!= nil' is correct, but I got tired of the segfaults
  207. # resulting from the crappy stack checking:
  208. if cast[int](dest[]) >=% PageSize: decRef(usrToCell(dest[]))
  209. else:
  210. # can't be an interior pointer if it's a stack location!
  211. gcAssert(interiorAllocatedPtr(gch.region, dest) == nil,
  212. "stack loc AND interior pointer")
  213. dest[] = src
  214. proc initGC() =
  215. when not defined(useNimRtl):
  216. when traceGC:
  217. for i in low(CellState)..high(CellState): init(states[i])
  218. gch.cycleThreshold = InitialCycleThreshold
  219. gch.zctThreshold = InitialZctThreshold
  220. gch.stat.stackScans = 0
  221. gch.stat.cycleCollections = 0
  222. gch.stat.maxThreshold = 0
  223. gch.stat.maxStackSize = 0
  224. gch.stat.maxStackCells = 0
  225. gch.stat.cycleTableSize = 0
  226. # init the rt
  227. init(gch.zct)
  228. init(gch.tempStack)
  229. init(gch.decStack)
  230. init(gch.marked)
  231. init(gch.additionalRoots)
  232. when hasThreadSupport:
  233. init(gch.toDispose)
  234. gch.gcThreadId = atomicInc(gHeapidGenerator) - 1
  235. gcAssert(gch.gcThreadId >= 0, "invalid computed thread ID")
  236. proc cellsetReset(s: var CellSet) =
  237. deinit(s)
  238. init(s)
  239. {.push stacktrace:off.}
  240. proc forAllSlotsAux(dest: pointer, n: ptr TNimNode, op: WalkOp) {.benign.} =
  241. var d = cast[ByteAddress](dest)
  242. case n.kind
  243. of nkSlot: forAllChildrenAux(cast[pointer](d +% n.offset), n.typ, op)
  244. of nkList:
  245. for i in 0..n.len-1:
  246. # inlined for speed
  247. if n.sons[i].kind == nkSlot:
  248. if n.sons[i].typ.kind in {tyRef, tyOptAsRef, tyString, tySequence}:
  249. doOperation(cast[PPointer](d +% n.sons[i].offset)[], op)
  250. else:
  251. forAllChildrenAux(cast[pointer](d +% n.sons[i].offset),
  252. n.sons[i].typ, op)
  253. else:
  254. forAllSlotsAux(dest, n.sons[i], op)
  255. of nkCase:
  256. var m = selectBranch(dest, n)
  257. if m != nil: forAllSlotsAux(dest, m, op)
  258. of nkNone: sysAssert(false, "forAllSlotsAux")
  259. proc forAllChildrenAux(dest: pointer, mt: PNimType, op: WalkOp) =
  260. var d = cast[ByteAddress](dest)
  261. if dest == nil: return # nothing to do
  262. if ntfNoRefs notin mt.flags:
  263. case mt.kind
  264. of tyRef, tyOptAsRef, tyString, tySequence: # leaf:
  265. doOperation(cast[PPointer](d)[], op)
  266. of tyObject, tyTuple:
  267. forAllSlotsAux(dest, mt.node, op)
  268. of tyArray, tyArrayConstr, tyOpenArray:
  269. for i in 0..(mt.size div mt.base.size)-1:
  270. forAllChildrenAux(cast[pointer](d +% i *% mt.base.size), mt.base, op)
  271. else: discard
  272. proc forAllChildren(cell: PCell, op: WalkOp) =
  273. gcAssert(cell != nil, "forAllChildren: cell is nil")
  274. gcAssert(isAllocatedPtr(gch.region, cell), "forAllChildren: pointer not part of the heap")
  275. gcAssert(cell.typ != nil, "forAllChildren: cell.typ is nil")
  276. gcAssert cell.typ.kind in {tyRef, tyOptAsRef, tySequence, tyString}, "forAllChildren: unknown GC'ed type"
  277. let marker = cell.typ.marker
  278. if marker != nil:
  279. marker(cellToUsr(cell), op.int)
  280. else:
  281. case cell.typ.kind
  282. of tyRef, tyOptAsRef: # common case
  283. forAllChildrenAux(cellToUsr(cell), cell.typ.base, op)
  284. of tySequence:
  285. var d = cast[ByteAddress](cellToUsr(cell))
  286. var s = cast[PGenericSeq](d)
  287. if s != nil:
  288. for i in 0..s.len-1:
  289. forAllChildrenAux(cast[pointer](d +% i *% cell.typ.base.size +%
  290. GenericSeqSize), cell.typ.base, op)
  291. else: discard
  292. proc addNewObjToZCT(res: PCell, gch: var GcHeap) {.inline.} =
  293. # we check the last 8 entries (cache line) for a slot that could be reused.
  294. # In 63% of all cases we succeed here! But we have to optimize the heck
  295. # out of this small linear search so that ``newObj`` is not slowed down.
  296. #
  297. # Slots to try cache hit
  298. # 1 32%
  299. # 4 59%
  300. # 8 63%
  301. # 16 66%
  302. # all slots 68%
  303. var L = gch.zct.len
  304. var d = gch.zct.d
  305. when true:
  306. # loop unrolled for performance:
  307. template replaceZctEntry(i: untyped) =
  308. c = d[i]
  309. if c.refcount >=% rcIncrement:
  310. c.refcount = c.refcount and not ZctFlag
  311. d[i] = res
  312. return
  313. if L > 8:
  314. var c: PCell
  315. replaceZctEntry(L-1)
  316. replaceZctEntry(L-2)
  317. replaceZctEntry(L-3)
  318. replaceZctEntry(L-4)
  319. replaceZctEntry(L-5)
  320. replaceZctEntry(L-6)
  321. replaceZctEntry(L-7)
  322. replaceZctEntry(L-8)
  323. add(gch.zct, res)
  324. else:
  325. d[L] = res
  326. inc(gch.zct.len)
  327. else:
  328. for i in countdown(L-1, max(0, L-8)):
  329. var c = d[i]
  330. if c.refcount >=% rcIncrement:
  331. c.refcount = c.refcount and not ZctFlag
  332. d[i] = res
  333. return
  334. add(gch.zct, res)
  335. {.push stackTrace: off, profiler:off.}
  336. proc gcInvariant*() =
  337. sysAssert(allocInv(gch.region), "injected")
  338. when declared(markForDebug):
  339. markForDebug(gch)
  340. {.pop.}
  341. template setFrameInfo(c: PCell) =
  342. when leakDetector:
  343. if framePtr != nil and framePtr.prev != nil:
  344. c.filename = framePtr.prev.filename
  345. c.line = framePtr.prev.line
  346. else:
  347. c.filename = nil
  348. c.line = 0
  349. proc rawNewObj(typ: PNimType, size: int, gch: var GcHeap): pointer =
  350. # generates a new object and sets its reference counter to 0
  351. incTypeSize typ, size
  352. sysAssert(allocInv(gch.region), "rawNewObj begin")
  353. gcAssert(typ.kind in {tyRef, tyOptAsRef, tyString, tySequence}, "newObj: 1")
  354. collectCT(gch)
  355. var res = cast[PCell](rawAlloc(gch.region, size + sizeof(Cell)))
  356. #gcAssert typ.kind in {tyString, tySequence} or size >= typ.base.size, "size too small"
  357. gcAssert((cast[ByteAddress](res) and (MemAlign-1)) == 0, "newObj: 2")
  358. # now it is buffered in the ZCT
  359. res.typ = typ
  360. setFrameInfo(res)
  361. # refcount is zero, color is black, but mark it to be in the ZCT
  362. res.refcount = ZctFlag
  363. sysAssert(isAllocatedPtr(gch.region, res), "newObj: 3")
  364. # its refcount is zero, so add it to the ZCT:
  365. addNewObjToZCT(res, gch)
  366. when logGC: writeCell("new cell", res)
  367. track("rawNewObj", res, size)
  368. gcTrace(res, csAllocated)
  369. when useCellIds:
  370. inc gch.idGenerator
  371. res.id = gch.idGenerator * 1000_000 + gch.gcThreadId
  372. result = cellToUsr(res)
  373. sysAssert(allocInv(gch.region), "rawNewObj end")
  374. {.pop.} # .stackTrace off
  375. {.pop.} # .profiler off
  376. proc newObjNoInit(typ: PNimType, size: int): pointer {.compilerRtl.} =
  377. result = rawNewObj(typ, size, gch)
  378. when defined(memProfiler): nimProfile(size)
  379. proc newObj(typ: PNimType, size: int): pointer {.compilerRtl.} =
  380. result = rawNewObj(typ, size, gch)
  381. zeroMem(result, size)
  382. when defined(memProfiler): nimProfile(size)
  383. proc newSeq(typ: PNimType, len: int): pointer {.compilerRtl.} =
  384. # `newObj` already uses locks, so no need for them here.
  385. let size = addInt(mulInt(len, typ.base.size), GenericSeqSize)
  386. result = newObj(typ, size)
  387. cast[PGenericSeq](result).len = len
  388. cast[PGenericSeq](result).reserved = len
  389. when defined(memProfiler): nimProfile(size)
  390. proc newObjRC1(typ: PNimType, size: int): pointer {.compilerRtl.} =
  391. # generates a new object and sets its reference counter to 1
  392. incTypeSize typ, size
  393. sysAssert(allocInv(gch.region), "newObjRC1 begin")
  394. gcAssert(typ.kind in {tyRef, tyOptAsRef, tyString, tySequence}, "newObj: 1")
  395. collectCT(gch)
  396. sysAssert(allocInv(gch.region), "newObjRC1 after collectCT")
  397. var res = cast[PCell](rawAlloc(gch.region, size + sizeof(Cell)))
  398. sysAssert(allocInv(gch.region), "newObjRC1 after rawAlloc")
  399. sysAssert((cast[ByteAddress](res) and (MemAlign-1)) == 0, "newObj: 2")
  400. # now it is buffered in the ZCT
  401. res.typ = typ
  402. setFrameInfo(res)
  403. res.refcount = rcIncrement # refcount is 1
  404. sysAssert(isAllocatedPtr(gch.region, res), "newObj: 3")
  405. when logGC: writeCell("new cell", res)
  406. track("newObjRC1", res, size)
  407. gcTrace(res, csAllocated)
  408. when useCellIds:
  409. inc gch.idGenerator
  410. res.id = gch.idGenerator * 1000_000 + gch.gcThreadId
  411. result = cellToUsr(res)
  412. zeroMem(result, size)
  413. sysAssert(allocInv(gch.region), "newObjRC1 end")
  414. when defined(memProfiler): nimProfile(size)
  415. proc newSeqRC1(typ: PNimType, len: int): pointer {.compilerRtl.} =
  416. let size = addInt(mulInt(len, typ.base.size), GenericSeqSize)
  417. result = newObjRC1(typ, size)
  418. cast[PGenericSeq](result).len = len
  419. cast[PGenericSeq](result).reserved = len
  420. when defined(memProfiler): nimProfile(size)
  421. proc growObj(old: pointer, newsize: int, gch: var GcHeap): pointer =
  422. collectCT(gch)
  423. var ol = usrToCell(old)
  424. sysAssert(ol.typ != nil, "growObj: 1")
  425. gcAssert(ol.typ.kind in {tyString, tySequence}, "growObj: 2")
  426. sysAssert(allocInv(gch.region), "growObj begin")
  427. var res = cast[PCell](rawAlloc(gch.region, newsize + sizeof(Cell)))
  428. var elemSize = 1
  429. if ol.typ.kind != tyString: elemSize = ol.typ.base.size
  430. incTypeSize ol.typ, newsize
  431. var oldsize = cast[PGenericSeq](old).len*elemSize + GenericSeqSize
  432. copyMem(res, ol, oldsize + sizeof(Cell))
  433. zeroMem(cast[pointer](cast[ByteAddress](res) +% oldsize +% sizeof(Cell)),
  434. newsize-oldsize)
  435. sysAssert((cast[ByteAddress](res) and (MemAlign-1)) == 0, "growObj: 3")
  436. # This can be wrong for intermediate temps that are nevertheless on the
  437. # heap because of lambda lifting:
  438. #gcAssert(res.refcount shr rcShift <=% 1, "growObj: 4")
  439. when logGC:
  440. writeCell("growObj old cell", ol)
  441. writeCell("growObj new cell", res)
  442. gcTrace(ol, csZctFreed)
  443. gcTrace(res, csAllocated)
  444. track("growObj old", ol, 0)
  445. track("growObj new", res, newsize)
  446. when defined(nimIncrSeqV3):
  447. # since we steal the old seq's contents, we set the old length to 0.
  448. cast[PGenericSeq](old).len = 0
  449. elif reallyDealloc:
  450. sysAssert(allocInv(gch.region), "growObj before dealloc")
  451. if ol.refcount shr rcShift <=% 1:
  452. # free immediately to save space:
  453. if (ol.refcount and ZctFlag) != 0:
  454. var j = gch.zct.len-1
  455. var d = gch.zct.d
  456. while j >= 0:
  457. if d[j] == ol:
  458. d[j] = res
  459. break
  460. dec(j)
  461. beforeDealloc(gch, ol, "growObj stack trash")
  462. decTypeSize(ol, ol.typ)
  463. rawDealloc(gch.region, ol)
  464. else:
  465. # we split the old refcount in 2 parts. XXX This is still not entirely
  466. # correct if the pointer that receives growObj's result is on the stack.
  467. # A better fix would be to emit the location specific write barrier for
  468. # 'growObj', but this is lots of more work and who knows what new problems
  469. # this would create.
  470. res.refcount = rcIncrement
  471. decRef(ol)
  472. else:
  473. sysAssert(ol.typ != nil, "growObj: 5")
  474. zeroMem(ol, sizeof(Cell))
  475. when useCellIds:
  476. inc gch.idGenerator
  477. res.id = gch.idGenerator * 1000_000 + gch.gcThreadId
  478. result = cellToUsr(res)
  479. sysAssert(allocInv(gch.region), "growObj end")
  480. when defined(memProfiler): nimProfile(newsize-oldsize)
  481. proc growObj(old: pointer, newsize: int): pointer {.rtl.} =
  482. result = growObj(old, newsize, gch)
  483. {.push profiler:off, stackTrace:off.}
  484. # ---------------- cycle collector -------------------------------------------
  485. proc freeCyclicCell(gch: var GcHeap, c: PCell) =
  486. prepareDealloc(c)
  487. gcTrace(c, csCycFreed)
  488. track("cycle collector dealloc cell", c, 0)
  489. when logGC: writeCell("cycle collector dealloc cell", c)
  490. when reallyDealloc:
  491. sysAssert(allocInv(gch.region), "free cyclic cell")
  492. beforeDealloc(gch, c, "freeCyclicCell: stack trash")
  493. rawDealloc(gch.region, c)
  494. else:
  495. gcAssert(c.typ != nil, "freeCyclicCell")
  496. zeroMem(c, sizeof(Cell))
  497. proc sweep(gch: var GcHeap) =
  498. for x in allObjects(gch.region):
  499. if isCell(x):
  500. # cast to PCell is correct here:
  501. var c = cast[PCell](x)
  502. if c notin gch.marked: freeCyclicCell(gch, c)
  503. proc markS(gch: var GcHeap, c: PCell) =
  504. gcAssert isAllocatedPtr(gch.region, c), "markS: foreign heap root detected A!"
  505. incl(gch.marked, c)
  506. gcAssert gch.tempStack.len == 0, "stack not empty!"
  507. forAllChildren(c, waMarkPrecise)
  508. while gch.tempStack.len > 0:
  509. dec gch.tempStack.len
  510. var d = gch.tempStack.d[gch.tempStack.len]
  511. gcAssert isAllocatedPtr(gch.region, d), "markS: foreign heap root detected B!"
  512. if not containsOrIncl(gch.marked, d):
  513. forAllChildren(d, waMarkPrecise)
  514. proc markGlobals(gch: var GcHeap) =
  515. if gch.gcThreadId == 0:
  516. for i in 0 .. globalMarkersLen-1: globalMarkers[i]()
  517. for i in 0 .. threadLocalMarkersLen-1: threadLocalMarkers[i]()
  518. let d = gch.additionalRoots.d
  519. for i in 0 .. gch.additionalRoots.len-1: markS(gch, d[i])
  520. when logGC:
  521. var
  522. cycleCheckA: array[100, PCell]
  523. cycleCheckALen = 0
  524. proc alreadySeen(c: PCell): bool =
  525. for i in 0 .. cycleCheckALen-1:
  526. if cycleCheckA[i] == c: return true
  527. if cycleCheckALen == len(cycleCheckA):
  528. gcAssert(false, "cycle detection overflow")
  529. quit 1
  530. cycleCheckA[cycleCheckALen] = c
  531. inc cycleCheckALen
  532. proc debugGraph(s: PCell) =
  533. if alreadySeen(s):
  534. writeCell("child cell (already seen) ", s)
  535. else:
  536. writeCell("cell {", s)
  537. forAllChildren(s, waDebug)
  538. c_fprintf(stdout, "}\n")
  539. proc doOperation(p: pointer, op: WalkOp) =
  540. if p == nil: return
  541. var c: PCell = usrToCell(p)
  542. gcAssert(c != nil, "doOperation: 1")
  543. # the 'case' should be faster than function pointers because of easy
  544. # prediction:
  545. case op
  546. of waZctDecRef:
  547. #if not isAllocatedPtr(gch.region, c):
  548. # c_fprintf(stdout, "[GC] decref bug: %p", c)
  549. gcAssert(isAllocatedPtr(gch.region, c), "decRef: waZctDecRef")
  550. gcAssert(c.refcount >=% rcIncrement, "doOperation 2")
  551. when logGC: writeCell("decref (from doOperation)", c)
  552. track("waZctDecref", p, 0)
  553. decRef(c)
  554. of waPush:
  555. add(gch.tempStack, c)
  556. of waMarkGlobal:
  557. markS(gch, c)
  558. of waMarkPrecise:
  559. add(gch.tempStack, c)
  560. #of waDebug: debugGraph(c)
  561. proc nimGCvisit(d: pointer, op: int) {.compilerRtl.} =
  562. doOperation(d, WalkOp(op))
  563. proc collectZCT(gch: var GcHeap): bool {.benign.}
  564. proc collectCycles(gch: var GcHeap) =
  565. when hasThreadSupport:
  566. for c in gch.toDispose:
  567. nimGCunref(c)
  568. # ensure the ZCT 'color' is not used:
  569. while gch.zct.len > 0: discard collectZCT(gch)
  570. cellsetReset(gch.marked)
  571. var d = gch.decStack.d
  572. for i in 0..gch.decStack.len-1:
  573. sysAssert isAllocatedPtr(gch.region, d[i]), "collectCycles"
  574. markS(gch, d[i])
  575. markGlobals(gch)
  576. sweep(gch)
  577. proc gcMark(gch: var GcHeap, p: pointer) {.inline.} =
  578. # the addresses are not as cells on the stack, so turn them to cells:
  579. sysAssert(allocInv(gch.region), "gcMark begin")
  580. var cell = usrToCell(p)
  581. var c = cast[ByteAddress](cell)
  582. if c >% PageSize:
  583. # fast check: does it look like a cell?
  584. var objStart = cast[PCell](interiorAllocatedPtr(gch.region, cell))
  585. if objStart != nil:
  586. # mark the cell:
  587. incRef(objStart)
  588. add(gch.decStack, objStart)
  589. when false:
  590. if isAllocatedPtr(gch.region, cell):
  591. sysAssert false, "allocated pointer but not interior?"
  592. # mark the cell:
  593. incRef(cell)
  594. add(gch.decStack, cell)
  595. sysAssert(allocInv(gch.region), "gcMark end")
  596. #[
  597. This method is conditionally marked with an attribute so that it gets ignored by the LLVM ASAN
  598. (Address SANitizer) intrumentation as it will raise false errors due to the implementation of
  599. garbage collection that is used by Nim. For more information, please see the documentation of
  600. `CLANG_NO_SANITIZE_ADDRESS` in `lib/nimbase.h`.
  601. ]#
  602. proc markStackAndRegisters(gch: var GcHeap) {.noinline, cdecl, codegenDecl: "CLANG_NO_SANITIZE_ADDRESS $# $#$#".} =
  603. forEachStackSlot(gch, gcMark)
  604. proc collectZCT(gch: var GcHeap): bool =
  605. # Note: Freeing may add child objects to the ZCT! So essentially we do
  606. # deep freeing, which is bad for incremental operation. In order to
  607. # avoid a deep stack, we move objects to keep the ZCT small.
  608. # This is performance critical!
  609. const workPackage = 100
  610. var L = addr(gch.zct.len)
  611. when withRealTime:
  612. var steps = workPackage
  613. var t0: Ticks
  614. if gch.maxPause > 0: t0 = getticks()
  615. while L[] > 0:
  616. var c = gch.zct.d[0]
  617. sysAssert(isAllocatedPtr(gch.region, c), "CollectZCT: isAllocatedPtr")
  618. # remove from ZCT:
  619. gcAssert((c.refcount and ZctFlag) == ZctFlag, "collectZCT")
  620. c.refcount = c.refcount and not ZctFlag
  621. gch.zct.d[0] = gch.zct.d[L[] - 1]
  622. dec(L[])
  623. when withRealTime: dec steps
  624. if c.refcount <% rcIncrement:
  625. # It may have a RC > 0, if it is in the hardware stack or
  626. # it has not been removed yet from the ZCT. This is because
  627. # ``incref`` does not bother to remove the cell from the ZCT
  628. # as this might be too slow.
  629. # In any case, it should be removed from the ZCT. But not
  630. # freed. **KEEP THIS IN MIND WHEN MAKING THIS INCREMENTAL!**
  631. when logGC: writeCell("zct dealloc cell", c)
  632. track("zct dealloc cell", c, 0)
  633. gcTrace(c, csZctFreed)
  634. # We are about to free the object, call the finalizer BEFORE its
  635. # children are deleted as well, because otherwise the finalizer may
  636. # access invalid memory. This is done by prepareDealloc():
  637. prepareDealloc(c)
  638. forAllChildren(c, waZctDecRef)
  639. when reallyDealloc:
  640. sysAssert(allocInv(gch.region), "collectZCT: rawDealloc")
  641. beforeDealloc(gch, c, "collectZCT: stack trash")
  642. rawDealloc(gch.region, c)
  643. else:
  644. sysAssert(c.typ != nil, "collectZCT 2")
  645. zeroMem(c, sizeof(Cell))
  646. when withRealTime:
  647. if steps == 0:
  648. steps = workPackage
  649. if gch.maxPause > 0:
  650. let duration = getticks() - t0
  651. # the GC's measuring is not accurate and needs some cleanup actions
  652. # (stack unmarking), so subtract some short amount of time in
  653. # order to miss deadlines less often:
  654. if duration >= gch.maxPause - 50_000:
  655. return false
  656. result = true
  657. proc unmarkStackAndRegisters(gch: var GcHeap) =
  658. var d = gch.decStack.d
  659. for i in 0..gch.decStack.len-1:
  660. sysAssert isAllocatedPtr(gch.region, d[i]), "unmarkStackAndRegisters"
  661. decRef(d[i])
  662. gch.decStack.len = 0
  663. proc collectCTBody(gch: var GcHeap) =
  664. when withRealTime:
  665. let t0 = getticks()
  666. sysAssert(allocInv(gch.region), "collectCT: begin")
  667. when nimCoroutines:
  668. for stack in gch.stack.items():
  669. gch.stat.maxStackSize = max(gch.stat.maxStackSize, stack.stackSize())
  670. else:
  671. gch.stat.maxStackSize = max(gch.stat.maxStackSize, stackSize())
  672. sysAssert(gch.decStack.len == 0, "collectCT")
  673. prepareForInteriorPointerChecking(gch.region)
  674. markStackAndRegisters(gch)
  675. gch.stat.maxStackCells = max(gch.stat.maxStackCells, gch.decStack.len)
  676. inc(gch.stat.stackScans)
  677. if collectZCT(gch):
  678. when cycleGC:
  679. if getOccupiedMem(gch.region) >= gch.cycleThreshold or alwaysCycleGC:
  680. collectCycles(gch)
  681. #discard collectZCT(gch)
  682. inc(gch.stat.cycleCollections)
  683. gch.cycleThreshold = max(InitialCycleThreshold, getOccupiedMem() *
  684. CycleIncrease)
  685. gch.stat.maxThreshold = max(gch.stat.maxThreshold, gch.cycleThreshold)
  686. unmarkStackAndRegisters(gch)
  687. sysAssert(allocInv(gch.region), "collectCT: end")
  688. when withRealTime:
  689. let duration = getticks() - t0
  690. gch.stat.maxPause = max(gch.stat.maxPause, duration)
  691. when defined(reportMissedDeadlines):
  692. if gch.maxPause > 0 and duration > gch.maxPause:
  693. c_fprintf(stdout, "[GC] missed deadline: %ld\n", duration)
  694. proc collectCT(gch: var GcHeap) =
  695. if (gch.zct.len >= gch.zctThreshold or (cycleGC and
  696. getOccupiedMem(gch.region)>=gch.cycleThreshold) or alwaysGC) and
  697. gch.recGcLock == 0:
  698. when false:
  699. prepareForInteriorPointerChecking(gch.region)
  700. cellsetReset(gch.marked)
  701. markForDebug(gch)
  702. collectCTBody(gch)
  703. gch.zctThreshold = max(InitialZctThreshold, gch.zct.len * CycleIncrease)
  704. when withRealTime:
  705. proc toNano(x: int): Nanos {.inline.} =
  706. result = x * 1000
  707. proc GC_setMaxPause*(MaxPauseInUs: int) =
  708. gch.maxPause = MaxPauseInUs.toNano
  709. proc GC_step(gch: var GcHeap, us: int, strongAdvice: bool) =
  710. gch.maxPause = us.toNano
  711. if (gch.zct.len >= gch.zctThreshold or (cycleGC and
  712. getOccupiedMem(gch.region)>=gch.cycleThreshold) or alwaysGC) or
  713. strongAdvice:
  714. collectCTBody(gch)
  715. gch.zctThreshold = max(InitialZctThreshold, gch.zct.len * CycleIncrease)
  716. proc GC_step*(us: int, strongAdvice = false, stackSize = -1) {.noinline.} =
  717. if stackSize >= 0:
  718. var stackTop {.volatile.}: pointer
  719. gch.getActiveStack().pos = addr(stackTop)
  720. for stack in gch.stack.items():
  721. stack.bottomSaved = stack.bottom
  722. when stackIncreases:
  723. stack.bottom = cast[pointer](
  724. cast[ByteAddress](stack.pos) - sizeof(pointer) * 6 - stackSize)
  725. else:
  726. stack.bottom = cast[pointer](
  727. cast[ByteAddress](stack.pos) + sizeof(pointer) * 6 + stackSize)
  728. GC_step(gch, us, strongAdvice)
  729. if stackSize >= 0:
  730. for stack in gch.stack.items():
  731. stack.bottom = stack.bottomSaved
  732. when not defined(useNimRtl):
  733. proc GC_disable() =
  734. inc(gch.recGcLock)
  735. proc GC_enable() =
  736. if gch.recGcLock <= 0:
  737. raise newException(AssertionError,
  738. "API usage error: GC_enable called but GC is already enabled")
  739. dec(gch.recGcLock)
  740. proc GC_setStrategy(strategy: GC_Strategy) =
  741. discard
  742. proc GC_enableMarkAndSweep() =
  743. gch.cycleThreshold = InitialCycleThreshold
  744. proc GC_disableMarkAndSweep() =
  745. gch.cycleThreshold = high(gch.cycleThreshold)-1
  746. # set to the max value to suppress the cycle detector
  747. proc GC_fullCollect() =
  748. var oldThreshold = gch.cycleThreshold
  749. gch.cycleThreshold = 0 # forces cycle collection
  750. collectCT(gch)
  751. gch.cycleThreshold = oldThreshold
  752. proc GC_getStatistics(): string =
  753. result = "[GC] total memory: " & $(getTotalMem()) & "\n" &
  754. "[GC] occupied memory: " & $(getOccupiedMem()) & "\n" &
  755. "[GC] stack scans: " & $gch.stat.stackScans & "\n" &
  756. "[GC] stack cells: " & $gch.stat.maxStackCells & "\n" &
  757. "[GC] cycle collections: " & $gch.stat.cycleCollections & "\n" &
  758. "[GC] max threshold: " & $gch.stat.maxThreshold & "\n" &
  759. "[GC] zct capacity: " & $gch.zct.cap & "\n" &
  760. "[GC] max cycle table size: " & $gch.stat.cycleTableSize & "\n" &
  761. "[GC] max pause time [ms]: " & $(gch.stat.maxPause div 1000_000) & "\n"
  762. when nimCoroutines:
  763. result.add "[GC] number of stacks: " & $gch.stack.len & "\n"
  764. for stack in items(gch.stack):
  765. result.add "[GC] stack " & stack.bottom.repr & "[GC] max stack size " & cast[pointer](stack.maxStackSize).repr & "\n"
  766. else:
  767. result.add "[GC] max stack size: " & $gch.stat.maxStackSize & "\n"
  768. {.pop.} # profiler: off, stackTrace: off