vs2010 c ++尾调用优化

编程入门 行业动态 更新时间:2024-10-11 11:13:11
本文介绍了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 ++尾调用优化

本文发布于:2023-11-12 10:17:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581204.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!