Skip to content

loop fails to increment counter #30594

Closed
Closed
@twistingedge

Description

@twistingedge

When running a simple for loop, the contents of a counter changes depending on the presence (and location) of a println() in the loop. If the println() is above the line modifying the counter, the line modifying the counter has no effect (optimized out?), and the counter's value does not change during the loop. If the println() is below the modification, the variable changes as expected. I have an earlier (and larger) example that passes the counter to a different (non-println()) function below the modification, and that also produces the error.

This behavior reproduces in 1.0.1, 0.7.0, and RC 1.1. This behavior does not reproduce in 0.6.2. (All versions checked were generic 64-bit binaries under Ubuntu 18.04.1 LTS.)

Note there are two fixes to the issue: add a println() after the variable increment inside the loop, or change the '+' method so it does not use copy().

import Base: +, copy

mutable struct DataWrap
    x::Float64
end # DataWrap
copy(x::DataWrap) = DataWrap(x.x)

function add!(p::DataWrap, off::DataWrap)
    p.x += off.x
    return p
end # add! DataWrap

+(a::DataWrap, b::DataWrap) = add!(copy(a), b) # resolve dispatch
# if you use the version below, the error clears up
# +(a::DataWrap, b::DataWrap) = DataWrap(a.x + b.x)

function put_colonnade(cnt::Int, dx::Int, dy::Int)
    step = DataWrap(dx)
    curr = step + DataWrap(1)
    for i in 1:cnt
        println(curr)
        curr = curr + step
# if you uncomment the line below, the variable increments as expected
#        println(curr)
    end
end

put_colonnade(4, -1,  0)

sample bad output:

julia> include("loopbug0.jl")
DataWrap(0.0)
DataWrap(0.0)
DataWrap(0.0)
DataWrap(0.0)

sample good output (with second println() uncommented):

julia> include("loopbug0.jl")
DataWrap(0.0)
DataWrap(-1.0)
DataWrap(-1.0)
DataWrap(-2.0)
DataWrap(-2.0)
DataWrap(-3.0)
DataWrap(-3.0)
DataWrap(-4.0)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugIndicates an unexpected problem or unintended behaviorcompiler:optimizerOptimization passes (mostly in base/compiler/ssair/)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions