0

This question may be silly but i will ask it anyway.
I've heard about branch prediction from this Mysticial's answer
and i want to know if it is possible for the following to happen

Lets say i have this piece of C++ code

while(memoryAddress = getNextAddress()){

  if(haveAccess(memoryAddress))
    // change the value of *memoryAdrress
  else 
    // do something else

}

So if the branch predictor predicts wrongly in some case that the if statement is true and then the program change the value of *memoryAddress can bad happen out of that? Can things like segmentation fault happen?

Community
  • 1
  • 1
Lan Pac
  • 365
  • 4
  • 14

1 Answers1

5

The branch predictor inside a processor is designed to have no functionally observable effects.

The branch predictor is not sophisticated enough to get it right every time, regardless of attempts to trick it such as yours. If it was right everytime, it would just be how branches are always executed, it wouldn't be a “predictor”.

The condition of the branch is still computed while execution continues, and if the condition turns out not have the predicted value, nothing is committed to memory. Execution goes back to the correct branch.

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
  • I understand that the branch predictor cant get it right always and the general idea of how a branch predictor works. I want to know about the part which as you described " is designed to have no functionally observable effects " – Lan Pac Oct 02 '13 at 18:57
  • 1
    @LanPac With respect, I don't think you want to know how branch speculation work. It is extremely pedestrian and it does not change the discussion if the predictor is a simple 1-bit affair. You seem to want to know how speculative execution works (it is also rather pedestrian if you don't go into the details). As I more or less said, “If it turns out the work was not needed after all, any changes made by the work are reverted and the results are ignored.” http://en.wikipedia.org/wiki/Speculative_execution – Pascal Cuoq Oct 02 '13 at 19:03