Can you intentionally write code in a specific way so that the branch predictor will choose the option that will be the case most of the times. For example error checks whether a resource was loaded. If this is possible how can you use this to your advantage?
Asked
Active
Viewed 327 times
4
-
1Why did you tag with so many languages? The answer for C is going to be different from the answer for Java. – Daniel Pryden Jul 04 '16 at 23:24
-
1Might an answer also be *hardware* dependent? – Scott Hunter Jul 04 '16 at 23:25
-
2How is this an exploit? Branch prediction isn't a bug... – Scott Hunter Jul 04 '16 at 23:26
-
A more interesting question is could you exploit the branch predictor to launch a timing attack on a crypto algorithm. Although I guess most of those avoid branching in the critical bits to keep them constant time to begin with. – Matti Virkkunen Jul 04 '16 at 23:26
-
Always relevant in this context: http://stackoverflow.com/questions/11227809/why-is-it-faster-to-process-a-sorted-array-than-an-unsorted-array – Hulk Jul 04 '16 at 23:26
-
Do you mean something like [_builtin_expect](http://blog.man7.org/2012/10/how-much-do-builtinexpect-likely-and.html)? – David Ranieri Jul 04 '16 at 23:28
-
1@ScottHunter "exploit" has a meaning outside of IT security, which is "use something to your advantage". – user253751 Jul 04 '16 at 23:40
-
1I [updated your title](http://stackoverflow.com/revisions/38193299/3) to be "aid" instead of "exploit" as I feel it fits the nature of what you are asking; however, if I'm wrong you may [edit] your question to clarify – Tas Jul 04 '16 at 23:45
-
2@immibis: I was referring to the "exploit" tag, which is not for the meaning you allude to. – Scott Hunter Jul 05 '16 at 01:31
-
1[Is there a compiler hint for GCC to force branch prediction to always go a certain way?](http://stackoverflow.com/q/30130930/1708801) has a lot of discussion about how useful this can/can not be. – Shafik Yaghmour Jul 05 '16 at 03:56
-
Avoid using branches would certainly help the predictor. – skypjack Jul 05 '16 at 05:42
2 Answers
8
If you are using GCC you can use the macros `likely()/unlikely()':
likely()/unlikely() macros in the Linux kernel - how do they work? What's their benefit?
Community
- 1
- 1
Sasha Pachev
- 4,884
- 3
- 19
- 19
1
Theoretically, yes. Effectively speaking NO. You won't really get any benefit, try it out yourself.
With the way modern hardware works your CPU will still grind out all of the branches no matter what you do. But it doesn't really matter because they will do it concurrently.
To attempt to do it yourself you would need to use assembly language. Compiler hints like shown above will not do much.
Yudrist
- 129
- 7
-
This reads a lot more like a comment than an answer. Can you explain HOW you can "theoretically" do it, instead of just saying yes. – Tas Jul 04 '16 at 23:45
-
1