0

Given the following code:

func_pointer functions[] = { &func1, &func2, ..., &funcn }

void dispatch(int i) {
   functions[i]();
}

The address of the destination is not known in the compile time. Can the CPU speculate the destination of the call in case function dispatch() is called several times with the same value for parameter i?

Bogi
  • 2,274
  • 5
  • 26
  • 34
  • 1
    Yes, the branch predictors in modern CPUs will record the destination of the call each time it is executed and use that for future predictions. – prl Sep 02 '20 at 20:17
  • Yes, modern x86-64 CPUs have good indirect-branch pattern prediction, especially Haswell and later with IT-TAGE. https://hal.inria.fr/hal-01100647/document. See [How exactly R is affected by Branch Prediction?](https://stackoverflow.com/q/58399395) for discussion of a dispatch like this if used in a loop, such as an interpreter, keeping the details simple. – Peter Cordes Sep 03 '20 at 01:12
  • Found an exact duplicate: [branch prediction on a function pointer](https://stackoverflow.com/q/26239694) about repeated calls with the same `i`. – Peter Cordes Sep 03 '20 at 01:23

0 Answers0