Difference between “or eax,eax” and “test eax,eax” [duplicate]

南笙酒味 提交于 2019-11-29 10:06:22

In general, the only difference between test and and is that test <reg>, <reg> doesn't modify its operands. Essentially test applies an and operation, discarding the non-flags part of the result. If the operands are identical, the results will be the same (as will or).

test can be a superior instruction choice because of things like micro-op fusion. As a result, test is usually preferred unless the computation would have to be repeated. The same thing goes for cmp/sub.

Search Intel's doc for "fusion" and you should find the details.

Just to reiterate a little of, and add a little to, what @gsg indicated, the TEST instruction does a bitwise logical comparison (essentially ANDing them bitwise internally but not storing the result) of two operands and sets the processor flags according to the result of that operation. The OR instruction does a logical OR of the source with the destination, storing the result in the destination and sets the processor flags according to the result. They both affect the processor flags the same way. So when the operands are identical, the behavior is the same. There is no difference in flags. However, when the operands are different, their behavior is then quite different. You can also test for zero with and eax,eax which also affects the flags identically.

Pascal Cuoq

The circuitry to determine that the contents of eax after test eax, eax are the same as before the instruction is simpler than the circuitry required to arrive to that conclusion for or eax, eax. For this reason, test is better.

Some compilers may have generated or at a time when it did not make any difference (before out-of-order execution), but it will make a difference with some out-of-order processors nowadays (whereas yet other OOO processors will be so sophisticated that they will recognize or eax, eax as truly equivalent to test eax, eax).

I couldn't find a reference justifying that some modern processors are actually able to infer that or reg, reg does not modify reg, but here is an answer claiming it is the case for xchg reg, reg.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!