What does an if look like in IL?

感情迁移 提交于 2019-12-06 07:41:50

问题


What does an if statement look like when it's compiled into IL?

It's a very simple construct in C#. Can sombody give me a more abstract definition of what it really is?


回答1:


Here are a few if statements and how they translate to IL:

ldc.i4.s 0x2f                      var i = 47;
stloc.0 

ldloc.0                            if (i == 47)
ldc.i4.s 0x2f
bne.un.s L_0012

ldstr "forty-seven!"                   Console.WriteLine("forty-seven!");
call Console::WriteLine

L_0012:
ldloc.0                            if (i > 0)
ldc.i4.0 
ble.s L_0020

ldstr "greater than zero!"             Console.WriteLine("greater than zero!");
call Console::WriteLine

L_0020:
ldloc.0                            bool b = (i != 0);
ldc.i4.0 
ceq 
ldc.i4.0 
ceq 
stloc.1 

ldloc.1                            if (b)
brfalse.s L_0035

ldstr "boolean true!"                  Console.WriteLine("boolean true!");
call Console::WriteLine

L_0035:
ret

One thing to note here: The IL instructions are always the “opposite”. if (i > 0) translates to something that effectively means “if i <= 0, then jump over the body of the if block”.




回答2:


A branch instruction is used that will jump to a target instruction depending on the value(s) on top of the stack.

brfalse Branch to target if value is zero (false)
brtrue  Branch to target if value is non-zero (true)
beq     Branch to target if equal
bge     Branch to target if greater than or equal to
bgt     Branch to target if greater than
ble     Branch to target if less than or equal to
blt     Branch to target if less than
bne.un  Branch to target if unequal or unordered



回答3:


It depends on the condition of the if. For example if you are checking a reference against null the compiler will emit a brfalse instruction (or a brtrue depending on what you wrote).

The actual if condition will differ based on the condition itself but a dissasembler like ILDASM or Reflector would be a better tool for learning more.




回答4:


A simple example:

ldloc.1                    // loads first local variable to stack
ldc.i4.0                   // loads constant 0 to stack
beq                        // branch if equal

This would be equal to

if(i == 0) //if i is the first local variable

Other ifs would differ, including conditional branches. This really is too much to explain in one post, you are better of looking for an introduction to IL-Code.

There is a nice article on codeproject concerning this.



来源:https://stackoverflow.com/questions/3663438/what-does-an-if-look-like-in-il

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!