Purpose of cmove instruction in x86 assembly? | cmove 指令如何避免错误的分支预测带来的开销?

x33g5p2x  于2022-01-04 转载在 其他  
字(1.3k)|赞(0)|评价(0)|浏览(254)

cmove 指令是用来做什么的?(Purpose of cmove instruction in x86 assembly?

The purpose of cmov is to allow software (in some cases) to avoid a branch.

For example, if you have this code:

cmp eax,ebx
    jne .l1
    mov eax,edx
.l1:

…then when a modern CPU sees the jne branch it will take a guess about whether the branch will be taken or not taken, and then start speculatively executing instructions based on the guess. If the guess is wrong there’s a performance penalty, because the CPU has to discard any speculatively executed work and then start fetching and executing the correct path.

For a conditional move (e.g. cmove eax,edx) the CPU doesn’t need to guess which code will be executed and the cost of a mispredicted branch is avoided. However, the CPU can’t know if the value in eax will change or not, which means that later instructions that depend on the results of the conditional move have to wait until the conditional move completes (instead of being speculatively executed with an assumed value and not stalling). 我的理解是,它只是通过不去预测这种方式,来避免预测错了重来。就像你只要不写代码,就不会有bug。

This means that if the branch can be easily predicted a branch can be faster; and if the branch can’t be easily predicted the condition move can be faster.

Note that a conditional move is never strictly needed (it can always be done with a branch instead) - it’s more like an optional optimization.

参考:条件数据传送(Conditional Data Transfer)

Reference: CSAPP Section 5.12 - Understanding Memory Performance

需要指出的是,不是所有的条件行为都能用条件数据传送来实现,所以无可避免地在某些情况中,程序员会写出导致条件分支的代码,而对于这些条件分支,处理器用分支预测可能会处理得很糟糕。

相关文章