vs2010 c ++尾调用优化 [英] vs2010 c++ tail call optimization

查看:415
本文介绍了vs2010 c ++尾调用优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

  int fac_aux(int x,int res){
if(x = = 1)return res;
else return fac_aux(x - 1,res * x);
}

int fac(int x){
return fac_aux(x,1);
}

int main(){
int x = fac(50);

std :: cout<< X;
return 0;
}

根据生成的asm文件,一切正常,尾调用优化。 p>

尝试替换

  int x = fac 

  int x = fac_aux(50,1); 

很奇怪,但是尾调用优化消失了。据我记得在VS2008中没有这样一个奇怪的编译器行为。任何想法为什么这些事情发生和如何确保尾调用优化是否完成?



;函数编译标志:/ Ogtp



尝试了/ O2和/ Ox优化标志。是否有任何其他编译器选项很重要?



编辑:VS2012管理进行优化

解决方案

当原始代码编译时,调用点的程序集具有部分内联 fac_aux ,特别是 x - 1 部分,这是尾递归所必需的,但是使用 fac_aux 可以防止部分内联并因此阻止尾递归优化: / p>

  TestThin.fac_aux 013B1000 CMP ECX,1 
013B1003 JE SHORT TestThin.013B100E
013B1005 IMUL EAX,ECX
013B1008 DEC ECX
013B1009 CMP ECX,1
013B100C JNZ SHORT TestThin.013B1005
013B100E RETN
013B100F INT3
TestThin.main 013B1010 MOV EAX,32
013B1015 LEA ECX,DWORD PTR DS:[EAX-1];注意部分内联x - 1
013B1018 CALL TestThin.fac_aux


Consider the following code:

int fac_aux( int x, int res ) {
    if( x == 1 ) return res;
    else return fac_aux( x - 1, res * x );
}

int fac( int x ) {
    return fac_aux( x, 1 );
}

int main() {
    int x = fac( 50 );

    std::cout << x;
    return 0;
}

According to generated asm file everything is ok, tail call is optimized.

Try to replace

int x = fac( 50 );

with

int x = fac_aux( 50, 1 );

Strange enough, but tail call optimization is disappeared. As far as I remember there was no such a strange compiler behaviour in VS2008. Any ideas why these things happen and how to be sure of tail call optimization is done?

; Function compile flags: /Ogtp

Tried both /O2 and /Ox optimization flags. Are there any other compiler options that matter?

Edit: VS2012 manages to do the optimization

解决方案

when the original is compiled, the assembly at the callsite has partial inlining of fac_aux, specifically the x - 1 part, which is required for the tail recursion, but using fac_aux prevents the partial inlining and thus the tail recursion optimization:

TestThin.fac_aux 013B1000   CMP ECX,1
013B1003                    JE SHORT TestThin.013B100E
013B1005                    IMUL EAX,ECX
013B1008                    DEC ECX
013B1009                    CMP ECX,1
013B100C                    JNZ SHORT TestThin.013B1005
013B100E                    RETN
013B100F                    INT3
TestThin.main 013B1010      MOV EAX,32
013B1015                    LEA ECX,DWORD PTR DS:[EAX-1] ;notice the partial inlining of x - 1
013B1018                    CALL TestThin.fac_aux

这篇关于vs2010 c ++尾调用优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆