c++ - Branch Prediction and Division By Zero -
i writing code looked following...
if(denominator == 0){ return false; } int result = value / denominator;
... when thought branching behavior in cpu.
https://stackoverflow.com/a/11227902/620863 answer says cpu try correctly guess way branch go, , head down branch stop if discovers guessed branch incorrectly.
but if cpu predicts branch above incorrectly, divide 0 in following instructions. doesn't happen though, , wondering why? cpu execute division 0 , wait see if branch correct before doing anything, or can tell shouldn't continue in these situations? what's going on?
the cpu free whatever wants, when speculatively executing branch based on prediction. needs in way that's transparent user. may stage "division zero" fault, should invisible if branch prediction turns out wrong. same logic, may stage writes memory, may not commit them.
as cpu designer, wouldn't bother predicting past such fault. that's not worth it. fault means bad prediction, , resolve enough.
this freedom thing. consider simple std::accumulate
loop. branch predictor correctly predict lot of jumps (for (auto current = begin, current != end; ++current)
jumps begin of loop), , there lot of memory reads may potentially fault (sum += *current
). cpu refuse read memory value until previous branch has been resolved lot slower. , yet mispredicted jump @ end of loop might cause harmless memory fault, predicted branch tries read past buffer. needs resolved without visible fault.
Comments
Post a Comment