haxe icon indicating copy to clipboard operation
haxe copied to clipboard

Inline nullable basic types without allocations

Open Speedphoenix opened this issue 11 months ago • 6 comments

At the moment Null<Int> and Null<Float> used exclusively in one scope create unnecessary allocations on static platforms.

The compiler could inline those away like it does for anonymous structures:

var a: Null<Int> = 5;
var b: Null<Int> = null;
if (a != null)
	trace(a);

This is functionally the same as:

var a_null: Bool = false;
var a_val: Int = 5;
var b_null: Bool = true;
var b_val: Int;
if (!a_null)
	trace(a_val);

Speedphoenix avatar Dec 06 '24 10:12 Speedphoenix

This is similar to #11332, but for nullables rather than parameter enums

Speedphoenix avatar Dec 06 '24 10:12 Speedphoenix

@basro Do you think this is something we could add to the inline constructor code somewhat easily?

Simn avatar Dec 06 '24 10:12 Simn

I don't have much knowledge of what goes on with null on static targets so I don't have any idea of what would need to change.

@Simn could you get me a snapshot of the syntax tree before and after the inline constructor for a code sample that showcases the problem? I'd be able to reason about what is going on with that. I'd prefer to avoid setting up the environment needed to compile haxe if possible.

basro avatar Dec 06 '24 19:12 basro

Looking at this again, I wonder in which case this could even come up without being const-propagated away. If we statically know the null-ness and value of a local variable, then we likely end up optimizing it anyway. There could be artificial cases like this:

function main() {
	var a:Null<Int> = Math.random() > 0.5 ? 0 : 1;
	if (a != null) {
		trace(a);
	}
}

Here we don't know the value, but we do know the null-ness, which would allow us to optimize the branch away. However, this would require careful dataflow analysis in order to not break down immediately, e.g. on reassignment.

On balance, I don't know if this is worth the effort. Do we have a real-life example of some code which suffers from this and isn't already optimized properly with -D analyzer-optimize?

Simn avatar Dec 09 '24 16:12 Simn

-D analyzer-optimize is currently not an option for us because it breaks hl.I64 operations. See #12031

Speedphoenix avatar Mar 18 '25 09:03 Speedphoenix

#12031 has been closed again since your message, so it should be an option

kLabz avatar Mar 18 '25 12:03 kLabz