optimizer.nim 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. #
  2. #
  3. # The Nim Compiler
  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. ## Optimizer:
  10. ## - elide 'wasMoved(x); destroy(x)' pairs
  11. ## - recognize "all paths lead to 'wasMoved(x)'"
  12. import
  13. ast, renderer, idents, intsets
  14. from trees import exprStructuralEquivalent
  15. const
  16. nfMarkForDeletion = nfNone # faster than a lookup table
  17. type
  18. BasicBlock = object
  19. wasMovedLocs: seq[PNode]
  20. kind: TNodeKind
  21. hasReturn, hasBreak: bool
  22. label: PSym # can be nil
  23. parent: ptr BasicBlock
  24. Con = object
  25. somethingTodo: bool
  26. inFinally: int
  27. proc nestedBlock(parent: var BasicBlock; kind: TNodeKind): BasicBlock =
  28. BasicBlock(wasMovedLocs: @[], kind: kind, hasReturn: false, hasBreak: false,
  29. label: nil, parent: addr(parent))
  30. proc breakStmt(b: var BasicBlock; n: PNode) =
  31. var it = addr(b)
  32. while it != nil:
  33. it.wasMovedLocs.setLen 0
  34. it.hasBreak = true
  35. if n.kind == nkSym:
  36. if it.label == n.sym: break
  37. else:
  38. # unnamed break leaves the block is nkWhileStmt or the like:
  39. if it.kind in {nkWhileStmt, nkBlockStmt, nkBlockExpr}: break
  40. it = it.parent
  41. proc returnStmt(b: var BasicBlock) =
  42. b.hasReturn = true
  43. var it = addr(b)
  44. while it != nil:
  45. it.wasMovedLocs.setLen 0
  46. it = it.parent
  47. proc mergeBasicBlockInfo(parent: var BasicBlock; this: BasicBlock) {.inline.} =
  48. if this.hasReturn:
  49. parent.wasMovedLocs.setLen 0
  50. parent.hasReturn = true
  51. proc wasMovedTarget(matches: var IntSet; branch: seq[PNode]; moveTarget: PNode): bool =
  52. result = false
  53. for i in 0..<branch.len:
  54. if exprStructuralEquivalent(branch[i][1].skipAddr, moveTarget,
  55. strictSymEquality = true):
  56. result = true
  57. matches.incl i
  58. proc intersect(summary: var seq[PNode]; branch: seq[PNode]) =
  59. # keep all 'wasMoved(x)' calls in summary that are also in 'branch':
  60. var i = 0
  61. var matches = initIntSet()
  62. while i < summary.len:
  63. if wasMovedTarget(matches, branch, summary[i][1].skipAddr):
  64. inc i
  65. else:
  66. summary.del i
  67. for m in matches:
  68. summary.add branch[m]
  69. proc invalidateWasMoved(c: var BasicBlock; x: PNode) =
  70. var i = 0
  71. while i < c.wasMovedLocs.len:
  72. if exprStructuralEquivalent(c.wasMovedLocs[i][1].skipAddr, x,
  73. strictSymEquality = true):
  74. c.wasMovedLocs.del i
  75. else:
  76. inc i
  77. proc wasMovedDestroyPair(c: var Con; b: var BasicBlock; d: PNode) =
  78. var i = 0
  79. while i < b.wasMovedLocs.len:
  80. if exprStructuralEquivalent(b.wasMovedLocs[i][1].skipAddr, d[1].skipAddr,
  81. strictSymEquality = true):
  82. b.wasMovedLocs[i].flags.incl nfMarkForDeletion
  83. c.somethingTodo = true
  84. d.flags.incl nfMarkForDeletion
  85. b.wasMovedLocs.del i
  86. else:
  87. inc i
  88. proc analyse(c: var Con; b: var BasicBlock; n: PNode) =
  89. case n.kind
  90. of nkCallKinds:
  91. var special = false
  92. var reverse = false
  93. if n[0].kind == nkSym:
  94. let s = n[0].sym
  95. if s.magic == mWasMoved:
  96. b.wasMovedLocs.add n
  97. special = true
  98. elif s.name.s == "=destroy":
  99. if c.inFinally > 0 and (b.hasReturn or b.hasBreak):
  100. discard "cannot optimize away the destructor"
  101. else:
  102. c.wasMovedDestroyPair b, n
  103. special = true
  104. elif s.name.s == "=sink":
  105. reverse = true
  106. if not special:
  107. if not reverse:
  108. for i in 0 ..< n.len:
  109. analyse(c, b, n[i])
  110. else:
  111. #[ Test tmatrix.test3:
  112. Prevent this from being elided. We should probably
  113. find a better solution...
  114. `=sink`(b, - (
  115. let blitTmp = b;
  116. wasMoved(b);
  117. blitTmp + a)
  118. `=destroy`(b)
  119. ]#
  120. for i in countdown(n.len-1, 0):
  121. analyse(c, b, n[i])
  122. if canRaise(n[0]): returnStmt(b)
  123. of nkSym:
  124. # any usage of the location before destruction implies we
  125. # cannot elide the 'wasMoved(x)':
  126. b.invalidateWasMoved n
  127. of nkNone..pred(nkSym), succ(nkSym)..nkNilLit, nkTypeSection, nkProcDef, nkConverterDef,
  128. nkMethodDef, nkIteratorDef, nkMacroDef, nkTemplateDef, nkLambda, nkDo,
  129. nkFuncDef, nkConstSection, nkConstDef, nkIncludeStmt, nkImportStmt,
  130. nkExportStmt, nkPragma, nkCommentStmt, nkBreakState, nkTypeOfExpr:
  131. discard "do not follow the construct"
  132. of nkAsgn, nkFastAsgn:
  133. # reverse order, see remark for `=sink`:
  134. analyse(c, b, n[1])
  135. analyse(c, b, n[0])
  136. of nkIfStmt, nkIfExpr:
  137. let isExhaustive = n[^1].kind in {nkElse, nkElseExpr}
  138. var wasMovedSet: seq[PNode] = @[]
  139. for i in 0 ..< n.len:
  140. var branch = nestedBlock(b, n[i].kind)
  141. analyse(c, branch, n[i])
  142. mergeBasicBlockInfo(b, branch)
  143. if isExhaustive:
  144. if i == 0:
  145. wasMovedSet = move(branch.wasMovedLocs)
  146. else:
  147. wasMovedSet.intersect(branch.wasMovedLocs)
  148. for i in 0..<wasMovedSet.len:
  149. b.wasMovedLocs.add wasMovedSet[i]
  150. of nkCaseStmt:
  151. let isExhaustive = skipTypes(n[0].typ,
  152. abstractVarRange-{tyTypeDesc}).kind notin {tyFloat..tyFloat128, tyString} or
  153. n[^1].kind == nkElse
  154. analyse(c, b, n[0])
  155. var wasMovedSet: seq[PNode] = @[]
  156. for i in 1 ..< n.len:
  157. var branch = nestedBlock(b, n[i].kind)
  158. analyse(c, branch, n[i])
  159. mergeBasicBlockInfo(b, branch)
  160. if isExhaustive:
  161. if i == 1:
  162. wasMovedSet = move(branch.wasMovedLocs)
  163. else:
  164. wasMovedSet.intersect(branch.wasMovedLocs)
  165. for i in 0..<wasMovedSet.len:
  166. b.wasMovedLocs.add wasMovedSet[i]
  167. of nkTryStmt:
  168. for i in 0 ..< n.len:
  169. var tryBody = nestedBlock(b, nkTryStmt)
  170. analyse(c, tryBody, n[i])
  171. mergeBasicBlockInfo(b, tryBody)
  172. of nkWhileStmt:
  173. analyse(c, b, n[0])
  174. var loopBody = nestedBlock(b, nkWhileStmt)
  175. analyse(c, loopBody, n[1])
  176. mergeBasicBlockInfo(b, loopBody)
  177. of nkBlockStmt, nkBlockExpr:
  178. var blockBody = nestedBlock(b, n.kind)
  179. if n[0].kind == nkSym:
  180. blockBody.label = n[0].sym
  181. analyse(c, blockBody, n[1])
  182. mergeBasicBlockInfo(b, blockBody)
  183. of nkBreakStmt:
  184. breakStmt(b, n[0])
  185. of nkReturnStmt, nkRaiseStmt:
  186. for child in n: analyse(c, b, child)
  187. returnStmt(b)
  188. of nkFinally:
  189. inc c.inFinally
  190. for child in n: analyse(c, b, child)
  191. dec c.inFinally
  192. else:
  193. for child in n: analyse(c, b, child)
  194. proc opt(c: Con; n, parent: PNode; parentPos: int) =
  195. template recurse() =
  196. let x = shallowCopy(n)
  197. for i in 0 ..< n.len:
  198. opt(c, n[i], x, i)
  199. parent[parentPos] = x
  200. case n.kind
  201. of nkCallKinds:
  202. if nfMarkForDeletion in n.flags:
  203. parent[parentPos] = newNodeI(nkEmpty, n.info)
  204. else:
  205. recurse()
  206. of nkNone..nkNilLit, nkTypeSection, nkProcDef, nkConverterDef,
  207. nkMethodDef, nkIteratorDef, nkMacroDef, nkTemplateDef, nkLambda, nkDo,
  208. nkFuncDef, nkConstSection, nkConstDef, nkIncludeStmt, nkImportStmt,
  209. nkExportStmt, nkPragma, nkCommentStmt, nkBreakState, nkTypeOfExpr:
  210. parent[parentPos] = n
  211. else:
  212. recurse()
  213. proc optimize*(n: PNode): PNode =
  214. # optimize away simple 'wasMoved(x); destroy(x)' pairs.
  215. #[ Unfortunately this optimization is only really safe when no exceptions
  216. are possible, see for example:
  217. proc main(inp: string; cond: bool) =
  218. if cond:
  219. try:
  220. var s = ["hi", inp & "more"]
  221. for i in 0..4:
  222. use s
  223. consume(s)
  224. wasMoved(s)
  225. finally:
  226. destroy(s)
  227. Now assume 'use' raises, then we shouldn't do the 'wasMoved(s)'
  228. ]#
  229. var c: Con
  230. var b: BasicBlock
  231. analyse(c, b, n)
  232. if c.somethingTodo:
  233. result = shallowCopy(n)
  234. for i in 0 ..< n.safeLen:
  235. opt(c, n[i], result, i)
  236. else:
  237. result = n