Skip to content

Improve codegen for "nullable boolean equals constant" #66431

@svick

Description

@svick

Currently, the IL generated for operations on a bool? nb; like nb == true and nb is true is suboptimal. And since the runtime does not seem to understand the semantics of Nullable<T>, this results in suboptimal machine code being executed.

Namely:

  1. The code nb == true generates branchless IL (see lifted comparison codegen can be improved #17261) equivalent to nb.GetValueOrDefault() == true & nb.HasValue, when it could be just nb.GetValueOrDefault().
  2. The code nb is true generates branched IL equivalent to nb.HasValue ? nb.GetValueOrDefault() : false, when it could also be just nb.GetValueOrDefault().
  3. The code nb is false generates branched IL equivalent to nb.HasValue ? !nb.GetValueOrDefault() : false when it could be the branchless !nb.GetValueOrDefault() & nb.HasValue.
  4. The code nb ?? true generates branched IL equivalent to nb.HasValue ? nb.GetValueOrDefault() : true, when it could be the branchless nb.GetValueOrDefault() | !nb.HasValue.

Note that nb ?? false already produces the optimal code of nb.GetValueOrDefault().

Also note that the suggested code does not contain comparisons with true, which also result in unnecessary IL and machine code.

SharpLab link.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area-CompilersCode Gen QualityRoom for improvement in the quality of the compiler's generated code

    Type

    No type
    No fields configured for issues without a type.

    Projects

    Status

    Misc

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions