luau-lang / luau

A fast, small, safe, gradually typed embeddable scripting language derived from Lua
https://luau.org
MIT License
4.1k stars 385 forks source link

Add constant folding of vector math like exists for numbers #1553

Open dv-extrarius opened 20 hours ago

dv-extrarius commented 20 hours ago

For numbers, expressions that consist entirely of constants are evaluated at bytecode compilation time and the final result is used as a single constant.

For vectors, this does not happen, and operations between constants are evaluated at runtime.

For example, with a constant SIZE, vector.create(0.5*SIZE, 0.5*SIZE, 0.5*SIZE) will be turned into a single constant (loaded via the LoadK opcode). However, vector.create(0.5, 0.5, 0.5)*SIZE is not turned into a single constant and instead remains a multiplication (the vector loaded with LoadK then multiplied with MulK).

It looks like Compiler/src/ConstantFolding.cpp needs cases for vector constants and Compiler/src/BuiltinFolding.cpp needs cases for built-in vector functions.

dv-extrarius commented 20 hours ago

You might want to add other missing built-ins to built-in folding too. It looks like nothing past vector creation was considered, but the following could be: LBF_BIT32_COUNTLZ, LBF_BIT32_COUNTRZ, LBF_BIT32_EXTRACTK, LBF_TONUMBER, LBF_TOSTRING, LBF_BIT32_BYTESWAP