Calculation of maxstack value in IL code

I have the following program to add values. When I comment on the Add Method method in the main method and look through ILDASM.EXE. The size of Maxstack is 2. And after the split, the size of maxstack becomes 4.

Why, in the case of the Main method, all the variables do not get on the stack, since the stack size remains only 2. If, in the case of the Add method, each variable is transferred to the stack? This is the case that, inside the main calculation of a method, it happens one after another, so that it only takes two variables at a time.

Please clear my confusion.

static void Main(string[] args) { int x = 2; int y = 3; int a = 4; int b = 5; int c = 6; Console.WriteLine(x + y + a + b + c); Console.WriteLine(Add(10, 20, 30, 40)); Console.ReadLine(); } static int Add(int x, int y, int z, int a) { return x + y + z + a; } 
+6
source share
1 answer

Each variable initialization:

 int x = 2; 

Requires the value to be on the stack: (stack size: 1 still required)

 .locals init ([0] int32 x, [1] int32 y, [2] int32 a, [3] int32 b, [4] int32 c) IL_0000: ldc.i4.2 // push 2 to the stack IL_0001: stloc.0 // load local variable 0 from stack ( x = 2 ) 

These operations are performed sequentially, so the maximum stack size is 1, during:

 int y = 3; int a = 4; int b = 5; int c = 6; 

And when it comes to this:

 Console.WriteLine(x + y + a + b + c); 

To add any two variables, stack size 2 is required:

 IL_000b: ldloc.0 // copy to stack x, max stack size required is still 1. IL_000c: ldloc.1 // copy to stack y, max stack size required is 2 now. IL_000d: add // execute add, will cause the sum x + y to be on stack IL_000e: ldloc.2 // copy to stack a IL_000f: add // execute add... (adds a to the result of x + y) .... 

Differential IL when you uncomment the Add method is below.

When calling the method, you need to push the link to the instance onto the stack (this means that if the Add method was non-stationary, the instance pointer to its declaring type should be pushed onto the stack)

Then, each argument that must be passed to the method must also be pushed onto the stack.

Therefore, this is the number of Add method parameters in your case, which determines the maximum stack size. Add a parameter to this Add method, and you will see that the maximum stack size increases to 5:

 // method is static so no need to push an instance pointer to the stack IL_001a: ldc.i4.s 10 // push to stack IL_001c: ldc.i4.s 20 // push to stack IL_001e: ldc.i4.s 30 // push to stack IL_0020: ldc.i4.s 40 // push to stack IL_0022: call int32 Program::Add(int32, int32, int32, int32) IL_0027: call void [mscorlib]System.Console::WriteLine(int32) 
+7
source

All Articles