diff --git a/compiler/dfa.nim b/compiler/dfa.nim index 2254cd0ff7..f3b358d72d 100644 --- a/compiler/dfa.nim +++ b/compiler/dfa.nim @@ -628,7 +628,7 @@ proc isAnalysableFieldAccess*(orig: PNode; owner: PSym): bool = # XXX Allow closure deref operations here if we know # the owner controlled the closure allocation? result = n.kind == nkSym and n.sym.owner == owner and - owner.kind != skModule and + sfGlobal notin n.sym.flags and (n.sym.kind != skParam or isSinkParam(n.sym)) # or n.sym.typ.kind == tyVar) # Note: There is a different move analyzer possible that checks for # consume(param.key); param.key = newValue for all paths. Then code like diff --git a/compiler/injectdestructors.nim b/compiler/injectdestructors.nim index da41b2d5c9..ff311f079c 100644 --- a/compiler/injectdestructors.nim +++ b/compiler/injectdestructors.nim @@ -37,18 +37,12 @@ type final: seq[PNode] # finally section needsTry: bool parent: ptr Scope - escapingSyms: IntSet # a construct like (block: let x = f(); x) - # means that 'x' escapes. We then destroy it - # in the parent's scope (and also allocate it there). - escapingExpr: PNode type Con = object owner: PSym g: ControlFlowGraph - jumpTargets: IntSet graph: ModuleGraph - emptyNode: PNode otherRead: PNode inLoop, inSpawn: int uninit: IntSet # set of uninit'ed vars @@ -72,12 +66,11 @@ proc getTemp(c: var Con; s: var Scope; typ: PType; info: TLineInfo): PNode = s.vars.add(sym) result = newSymNode(sym) +const sfSingleUsedTemp = sfExported # For temporaries that we know will only be used once + proc nestedScope(parent: var Scope): Scope = Scope(vars: @[], wasMoved: @[], final: @[], needsTry: false, parent: addr(parent)) -proc rememberParent(parent: var Scope; inner: Scope) {.inline.} = - parent.needsTry = parent.needsTry or inner.needsTry - proc optimize(s: var Scope) = # optimize away simple 'wasMoved(x); destroy(x)' pairs. #[ Unfortunately this optimization is only really safe when no exceptions @@ -124,68 +117,6 @@ proc optimize(s: var Scope) = filterNil(wasMoved) filterNil(final) -type - ToTreeFlag = enum - onlyCareAboutVars, - producesValue - -proc toTree(c: var Con; s: var Scope; ret: PNode; flags: set[ToTreeFlag]): PNode = - proc isComplexStmtListExpr(n: PNode): bool = - n.kind == nkStmtListExpr and (n.len == 0 or n[^1].kind != nkSym) - - #if not s.needsTry: optimize(s) - assert ret != nil - if s.vars.len == 0 and s.final.len == 0 and s.wasMoved.len == 0: - # trivial, nothing was done: - result = ret - else: - let isExpr = producesValue in flags and not isEmptyType(ret.typ) - var r = PNode(nil) - if isExpr: - result = newNodeIT(nkStmtListExpr, ret.info, ret.typ) - if ret.kind in nkCallKinds or isComplexStmtListExpr(ret): - r = c.getTemp(s, ret.typ, ret.info) - else: - result = newNodeI(nkStmtList, ret.info) - - if s.vars.len > 0: - let varSection = newNodeI(nkVarSection, ret.info) - for tmp in s.vars: - varSection.add newTree(nkIdentDefs, newSymNode(tmp), newNodeI(nkEmpty, ret.info), - newNodeI(nkEmpty, ret.info)) - result.add varSection - if onlyCareAboutVars in flags: - result.add ret - s.vars.setLen 0 - elif s.needsTry: - var finSection = newNodeI(nkStmtList, ret.info) - for m in s.wasMoved: finSection.add m - for i in countdown(s.final.high, 0): finSection.add s.final[i] - result.add newTryFinally(ret, finSection) - else: - if r != nil: - if ret.kind == nkStmtListExpr: - # simplify it a bit further by merging the nkStmtListExprs - let last = ret.len - 1 - for i in 0 ..< last: result.add ret[i] - result.add newTree(nkFastAsgn, r, ret[last]) - else: - result.add newTree(nkFastAsgn, r, ret) - for m in s.wasMoved: result.add m - for i in countdown(s.final.high, 0): result.add s.final[i] - result.add r - elif ret.kind == nkStmtListExpr: - # simplify it a bit further by merging the nkStmtListExprs - let last = ret.len - 1 - for i in 0 ..< last: result.add ret[i] - for m in s.wasMoved: result.add m - for i in countdown(s.final.high, 0): result.add s.final[i] - result.add ret[last] - else: - result.add ret - for m in s.wasMoved: result.add m - for i in countdown(s.final.high, 0): result.add s.final[i] - proc p(n: PNode; c: var Con; s: var Scope; mode: ProcessMode): PNode proc moveOrCopy(dest, ri: PNode; c: var Con; s: var Scope; isDecl = false): PNode @@ -228,6 +159,7 @@ proc isLastRead(n: PNode; c: var Con): bool = # first we need to search for the instruction that belongs to 'n': var instr = -1 let m = dfa.skipConvDfa(n) + if m.kind == nkSym and sfSingleUsedTemp in m.sym.flags: return true for i in 0.. 0: - it = it[^1] - s.escapingExpr = it - proc pVarTopLevel(v: PNode; c: var Con; s: var Scope; ri, res: PNode) = # move the variable declaration to the top of the frame: - let owningScope = c.addTopVar(s, v) + s.vars.add v.sym if isUnpackedTuple(v): if c.inLoop > 0: # unpacked tuple needs reset at every loop iteration res.add newTree(nkFastAsgn, v, genDefaultCall(v.typ, c, v.info)) elif sfThread notin v.sym.flags: # do not destroy thread vars for now at all for consistency. - if sfGlobal in v.sym.flags and s.parent == nil: - c.graph.globalDestructors.add c.genDestroy(v) #No need to genWasMoved here + if sfGlobal in v.sym.flags and s.parent == nil: #XXX: Rethink this logic (see tarcmisc.test2) + c.graph.globalDestructors.add c.genDestroy(v) else: - owningScope[].final.add c.genDestroy(v) + s.final.add c.genDestroy(v) if ri.kind == nkEmpty and c.inLoop > 0: res.add moveOrCopy(v, genDefaultCall(v.typ, c, v.info), c, s, isDecl = true) elif ri.kind != nkEmpty: res.add moveOrCopy(v, ri, c, s, isDecl = true) -template handleNestedTempl(n, processCall: untyped; alwaysStmt: bool) = +proc processScope(c: var Con; s: var Scope; ret: PNode): PNode = + result = newNodeI(nkStmtList, ret.info) + if s.vars.len > 0: + let varSection = newNodeI(nkVarSection, ret.info) + for tmp in s.vars: + varSection.add newTree(nkIdentDefs, newSymNode(tmp), newNodeI(nkEmpty, ret.info), + newNodeI(nkEmpty, ret.info)) + result.add varSection + if s.wasMoved.len > 0 or s.final.len > 0: + let finSection = newNodeI(nkStmtList, ret.info) + for m in s.wasMoved: finSection.add m + for i in countdown(s.final.high, 0): finSection.add s.final[i] + if s.needsTry: + result.add newTryFinally(ret, finSection) + else: + result.add ret + result.add finSection + else: + result.add ret + + if s.parent != nil: s.parent[].needsTry = s.parent[].needsTry or s.needsTry + +template processScopeExpr(c: var Con; s: var Scope; ret: PNode, processCall: untyped): PNode = + assert not ret.typ.isEmptyType + var result = newNodeI(nkStmtListExpr, ret.info) + # There is a possibility to do this check: s.wasMoved.len > 0 or s.final.len > 0 + # later and use it to eliminate the temporary when theres no need for it, but its + # tricky because you would have to intercept moveOrCopy at a certain point + let tmp = c.getTemp(s.parent[], ret.typ, ret.info) + tmp.sym.flags.incl sfSingleUsedTemp + let cpy = if ret.typ.hasDestructor: + moveOrCopy(tmp, ret, c, s, isDecl = true) + else: + newTree(nkFastAsgn, tmp, p(ret, c, s, normal)) + + if s.vars.len > 0: + let varSection = newNodeI(nkVarSection, ret.info) + for tmp in s.vars: + varSection.add newTree(nkIdentDefs, newSymNode(tmp), newNodeI(nkEmpty, ret.info), + newNodeI(nkEmpty, ret.info)) + result.add varSection + let finSection = newNodeI(nkStmtList, ret.info) + for m in s.wasMoved: finSection.add m + for i in countdown(s.final.high, 0): finSection.add s.final[i] + if s.needsTry: + result.add newTryFinally(newTree(nkStmtListExpr, cpy, processCall(tmp, s.parent[])), finSection) + else: + result.add cpy + result.add finSection + result.add processCall(tmp, s.parent[]) + + if s.parent != nil: s.parent[].needsTry = s.parent[].needsTry or s.needsTry + + result + +template handleNestedTempl(n, processCall: untyped, willProduceStmt = false) = template maybeVoid(child, s): untyped = if isEmptyType(child.typ): p(child, c, s, normal) else: processCall(child, s) - let treeFlags = if not isEmptyType(n.typ) and not alwaysStmt: {producesValue} else: {} case n.kind of nkStmtList, nkStmtListExpr: # a statement list does not open a new scope if n.len == 0: return n result = copyNode(n) - if alwaysStmt: result.typ = nil for i in 0..---------transformed-to--------->" echo renderTree(result, {renderIds}) diff --git a/tests/arc/tarcmisc.nim b/tests/arc/tarcmisc.nim index b6d9d781d8..2d7e6b455e 100644 --- a/tests/arc/tarcmisc.nim +++ b/tests/arc/tarcmisc.nim @@ -3,6 +3,11 @@ discard """ 123xyzabc destroyed: false destroyed: false +destroyed2: false +destroyed2: false +destroying variable: 2 +destroying variable: 1 +whiley ends :( 1 (x: "0") (x: "1") @@ -17,7 +22,8 @@ destroyed: false (x: "10") 0 closed -destroying variable +destroying variable: 20 +destroying variable: 10 ''' cmd: "nim c --gc:arc $file" """ @@ -40,11 +46,12 @@ type Variable = ref object value: int proc `=destroy`(self: var typeof(Variable()[])) = - echo "destroying variable" + echo "destroying variable: ",self.value proc newVariable(value: int): Variable = result = Variable() result.value = value + #echo "creating variable: ",result.value proc test(count: int) = var v {.global.} = newVariable(10) @@ -57,6 +64,28 @@ proc test(count: int) = test(3) +proc test2(count: int) = + #block: #XXX: Fails with block currently + var v {.global.} = newVariable(20) + + var count = count - 1 + if count == 0: return + + test2(count) + echo "destroyed2: ", v.isNil + +test2(3) + +proc whiley = + var a = newVariable(1) + while true: + var b = newVariable(2) + if true: raise newException(CatchableError, "test") + +try: + whiley() +except CatchableError: + echo "whiley ends :(" #------------------------------------------------------------------------------ # issue #13810 @@ -209,3 +238,8 @@ proc setParent(self: SimpleLoopB, parent: SimpleLoopB) = var l = SimpleLoopB() l.setParent(l) + + +# bug #14968 +import times +let currentTime = now().utc diff --git a/tests/arc/tcontrolflow.nim b/tests/arc/tcontrolflow.nim index 41f614cb20..80cc2b187e 100644 --- a/tests/arc/tcontrolflow.nim +++ b/tests/arc/tcontrolflow.nim @@ -1,12 +1,12 @@ discard """ output: '''begin A elif -destroyed end A +destroyed begin false if -destroyed end false +destroyed begin true if end true diff --git a/tests/arc/tmovebug.nim b/tests/arc/tmovebug.nim index ec0fce9a82..424785ed78 100644 --- a/tests/arc/tmovebug.nim +++ b/tests/arc/tmovebug.nim @@ -40,6 +40,33 @@ sink me (not sink) sinked and not optimized to a bitcopy sinked and not optimized to a bitcopy sinked and not optimized to a bitcopy +(data: @[0, 0]) +(data: @[0, 0]) +(data: @[0, 0]) +(data: @[0, 0]) +(data: @[0, 0]) +(data: @[0, 0]) +(data: @[0, 0]) +100 +hey +hey +(a: "a", b: 2) +ho +(a: "b", b: 3) +(b: "b", a: 2) +ho +(b: "a", a: 3) +hey +break +break +hey +ho +hey +ho +ho +king +live long; long live +king ''' """ @@ -325,3 +352,145 @@ proc update() = for i in 1..3: update() + + +# bug #14961 +type + Foo = object + data: seq[int] + +proc initFoo(len: int): Foo = + result = (let s = newSeq[int](len); Foo(data: s) ) + +var f = initFoo(2) +echo initFoo(2) + +proc initFoo2(len: int) = + echo if true: + let s = newSeq[int](len); Foo(data: s) + else: + let s = newSeq[int](len); Foo(data: s) + +initFoo2(2) + +proc initFoo3(len: int) = + echo (block: + let s = newSeq[int](len); Foo(data: s)) + +initFoo3(2) + +proc initFoo4(len: int) = + echo (let s = newSeq[int](len); Foo(data: s)) + +initFoo4(2) + +proc initFoo5(len: int) = + echo (case true + of true: + let s = newSeq[int](len); Foo(data: s) + of false: + let s = newSeq[int](len); Foo(data: s)) + +initFoo5(2) + +proc initFoo6(len: int) = + echo (block: + try: + let s = newSeq[int](len); Foo(data: s) + finally: discard) + +initFoo6(2) + +proc initFoo7(len: int) = + echo (block: + try: + raise newException(CatchableError, "sup") + let s = newSeq[int](len); Foo(data: s) + except CatchableError: + let s = newSeq[int](len); Foo(data: s) ) + +initFoo7(2) + + +# bug #14902 +iterator zip[T](s: openarray[T]): (T, T) = + var i = 0 + while i < 10: + yield (s[i mod 2], s[i mod 2 + 1]) + inc i + +var lastMem = int.high + +proc leak = + const len = 10 + var x = @[newString(len), newString(len), newString(len)] + + var c = 0 + for (a, b) in zip(x): + let newMem = getOccupiedMem() + assert newMem <= lastMem + lastMem = newMem + c += a.len + echo c + +leak() + + +proc consume(a: sink string) = echo a + +proc weirdScopes = + if (let a = "hey"; a.len > 0): + echo a + + while (let a = "hey"; a.len > 0): + echo a + break + + var a = block: (a: "a", b: 2) + echo a + (discard; a) = (echo "ho"; (a: "b", b: 3)) + echo a + + var b = try: (b: "b", a: 2) + except: raise + echo b + (discard; b) = (echo "ho"; (b: "a", a: 3)) + echo b + + var s = "break" + consume((echo "hey"; s)) + echo s + + echo (block: + var a = "hey" + (echo "hey"; "ho")) + + var b2 = "ho" + echo (block: + var a = "hey" + (echo "hey"; b2)) + echo b2 + + type status = enum + alive + + var king = "king" + echo (block: + var a = "a" + when true: + var b = "b" + case alive + of alive: + try: + var c = "c" + if true: + king + else: + "the abyss" + except: + echo "he ded" + "dead king") + echo "live long; long live" + echo king + +weirdScopes() diff --git a/tests/destructor/tmove_objconstr.nim b/tests/destructor/tmove_objconstr.nim index 0740bd46b7..16d0daa225 100644 --- a/tests/destructor/tmove_objconstr.nim +++ b/tests/destructor/tmove_objconstr.nim @@ -2,7 +2,6 @@ discard """ output: '''test created test destroyed 0 -Pony is dying! 1 2 3