Sure. A compiler can get predictive information if it knows:
- Statistical branch probabilities collected by instrumentation runs
- Statistical distribution of varible values collected by instrumentation runs; it can then predict the average outcome of a conditional and thus the branch
- Programmer-assertions as to frequency or bias of a conditional
- Estimates of loop bounds based on ranges (or defaults to "10" if unknown :)
- Knowledge that a branch is backwards to the top of loop (predict "taken"
利用这种信息,可以预测条件的可能结果,然后产生倾向于由硬件正确“预测”的分支指示。
一些汇编者进行的一套特别令人感兴趣的优化材料是:。 通过确定最大概率途径,汇编者可以在整个道路上进行优化,而只是在一个基本范围内这样做。
Sometimes compilers will generate branching code that indirectly uses the hardware s branch prediction capability. Compiled OO languages (static or JITted) have to compile method calls, and jump indirects are expensive. A cheap trick is to keep a small dynamic cache of most-recently invoked methods at each call site, and check the object type being dispatched. If the same type of object is frequently used for dispatch at a call site, the compare/branch sequence for the first (and somewhat less for the second) entry in the cache is highly probable, and the executed code thus avoids a mispredict. This is much better than a jump indirect.
最后一种标准trick计:如果你能够避免做一个分支,那么你就不必正确预测。 许多法典顺序类似:
if (exp1 relop exp2)
X = Y
endif
Modern CPUs have "predicated" instructions which are in effect "MOV_if_relop A to B",
for all relational conditions equal, not equal, less, etc.
So rather than generate a branch for the above construct, the compiler generates:
<compute exp1 and exp2>
CMP exp1,exp2 ; sets condition code
MOVif_relop X,Y