Skip to content

Problem when comparing boolean values after IL conv.i1 #12872

Closed

Description

@arlm

I am working on some tests for an DynamicMehtod IL generator called Sigil and I hit some interesting behavior on comparing booleans:

The dynamic method (Func<int, bool>) looks like:

   ldarg.0
   conv.i1
   ret   

When I invoke this function using 1 everything goes as expected for true. Although, when I invoke this function using 2 and start testing the results it happens that Visual Studio debugger and variable dumps (using Console.Write) states that it is true and ==comparisons succeed, but true.Equals() returns false. I have tried casting, making a boolean AND & operation with true, all with the same result.

Is this the expected behavior for this IL operation? It seems that Boolean.Equals(bool) behaves differently from Boolean.Equals(object?).

https://github.com/dotnet/corefx/blob/f5399d9d24536697a3bc36339e13ba085fc28938/src/Common/src/CoreLib/System/Boolean.cs#L143-L146

https://github.com/dotnet/corefx/blob/f5399d9d24536697a3bc36339e13ba085fc28938/src/Common/src/CoreLib/System/Boolean.cs#L130-L140

Also it seems that the second one is using the base Object == operator which is not defined as an operator on this object, so I infer it calls Object.Equals(objec) internally:

https://github.com/dotnet/corefx/blob/f5399d9d24536697a3bc36339e13ba085fc28938/src/Common/src/CoreLib/System/Object.cs#L47-L50

Although I found no code counterpart of this RuntimeHelpers.Equals(this, object), I guess it comes from the runtime and my guess would be that it calls the ObjectNative::Equals(Object, Object)

https://github.com/dotnet/coreclr/blob/fd2287c5e833439e0ea7c27ad14350bcccf371a0/src/classlibnative/bcltype/objectnative.cpp#L140-L179

Which compares the memory content of both objects.

Well that is as far as I could go with this odd behavior.

Activity

  1. arlm commented on Jun 12, 2019

    @arlm
    Author

    I have some test cases here:

    https://dotnetfiddle.net/ulqU8N

    and here

    https://gist.github.com/arlm/da7cb15b22dcbd231852c55b38038ca5

    with the output:

    [bool] bool actual parameter = True
    [bool] var value = System.Convert.ToBoolean(actual)
    [bool] var @true = true;
    [bool] true.Equals(true) = True
    [bool] true.Equals(@true) = True
    [bool] true.Equals(value) = False
    [bool] true.Equals((object)value) = False
    [bool] true.Equals(value && true) = False
    [bool] true ==  value = True
    [bool] (object)true ==  (object)value = False
    [bool] true ==  value && true = True
    [bool] value == true = True
    [bool] value && true == true = True
    
    [<TActual>] bool actual parameter = True
    [<TActual>] var value = System.Convert.ToBoolean(actual)
    [<TActual>] var @true = true;
    [<TActual>] true.Equals(true)= True
    [<TActual>] true.Equals((object)value) = False
    [<TActual>] true.Equals(@true) = True
    [<TActual>] true.Equals(value) = False
    [<TActual>] true.Equals(value && true) = False
    
  2. transferred this issue fromdotnet/corefxon Jun 12, 2019
  3. mikedn commented on Jun 12, 2019

    @mikedn
    Contributor

    Although, when I invoke this function using 2

    Do you have a particular need to support Boolean values other than 0 or 1? Neither the C# compiler nor the JIT compiler acknowledge the existence of such values and optimize as if only 0 and 1 are possible.

  4. arlm commented on Jun 12, 2019

    @arlm
    Author

    No, no actual need to support that. The thing is that during tests I have hit this odd behavior. I would say that it should be at least consistent:

    true == value = True
    and
    true.Equals(value) = False

    I would expect both to return false or both to return true.

    The question actually was:

    Is this the expected behavior for this IL operation?

    The rest was only my findings which were not conclusive on the expected behavior from the source-code analysis.

    I would say that the question still holds: Is that an expected behavior? (== and true. Equals to behave differently)

  5. mikedn commented on Jun 12, 2019

    @mikedn
    Contributor

    The question actually was: Is this the expected behavior for this IL operation?

    Yes. Neither conv.i1 nor the IL evaluation stack do not know anything about bool values. conv.i1 simply pops an i4 value from the stack, sign extends the lower byte of it to i4 and pushes the resulting value back to the IL stack. There is no such thing as a bool value on the evaluation stack. Basically it's almost the same as an enum:

    enum Boolean : byte 
    { 
        False = 0,
        True = 1
    }

    I would say that it should be at least consistent:

    Being consistent comes at a cost. Basically the C# compiler would need to normalize every bool value to ensure that it's either 0 or 1. It would also prevent some optimizations, such as the one that's responsible for true == value = True.

    For code like if (value == true) the C# compiler naturally generates a brtrue/brfalse instruction - these instructions check for a 0/non-0 value (again, IL operates with integers, not bools). On the other hand, Equals generates a ceq instruction to compare the bool values - of course that true.Equals(value) is false because 1 != 2.

  6. arlm commented on Jun 12, 2019

    @arlm
    Author

    Very enlightening. I was aware about the non-existence of a bool type underneath C#, on the IL level. But I had no idea how C# does the conversion of the comparison expressions to IL. That should be on the Roslyn code, right? Maybe I should take a look there first next time.

    So, from your answer that is very clear that this should be the expected behavior. Thank you for taking your time to explain me this. I guess the tests should reflect that on the kevin-montrose/Sigil project I am trying to update and add some fixes.

    https://github.com/arlm/Sigil-vNext/blob/5f0ac692f05ad9c23a351cf484a7611cff61a050/SigilTests/Converts.cs#L156-L165

                    var e1 = Emit<Func<int, bool>>.NewDynamicMethod();
                    e1.LoadArgument(0);
                    e1.Convert<bool>();
                    e1.Return();
    
                    var d1 = e1.CreateDelegate();
    
                    Assert.IsTrue(d1(1));
                    Assert.IsTrue(d1(2));
                    Assert.IsFalse(d1(0));
    
  7. tannergooding commented on Jun 12, 2019

    @tannergooding
    Member
  8. Joe4evr commented on Jun 13, 2019

    @Joe4evr
    Contributor
  9. mikedn commented on Jun 13, 2019

    @mikedn
    Contributor

    But I had no idea how C# does the conversion of the comparison expressions to IL. That should be on the Roslyn code, right? Maybe I should take a look there first next time.

    Yes, note that most (likely all) operators on primitive types are translated directly into IL instructions, there are no actual operator overloads on the types themselves. In the case of == and != you'd typically get ceq, beq, bne (which for bools only work "correctly" if the values are 0/1) but also brtrue or brfalse (which work with 0/non-zero bools). As the document linked to by @tannergooding above describes, this is choice specifically made by the C# compiler.

    I guess the tests should reflect that on the kevin-montrose/Sigil project I am trying to update and add some fixes.

    I'm inclined to remove any test that relies on non 0/1 bools. The behavior of these is basically undefined. It's not only equality that is affected, both thee C# compiler and the JIT compiler also make other optimizations that assume 0/1 bools - for example transforming a && b into a & b. The later works correctly only with 0/1 bools.

  10. transferred this issue fromdotnet/coreclron Jan 31, 2020
  11. ghost locked as resolved and limited conversation to collaborators on Dec 12, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions