Search code examples
c#.netcilil

Are ldc.i4.x and ldc.i4 x instructions interchangeable and semantically identical?


There are some loading instructions in CIL such as ldc.i4.0, ldc.i4.1, ldc.i4.2, ldc.i4.3 …

I wonder, is it possible to use ldc.i4 1 instead of ldc.i4.1 or ldc.i4 5 instead of ldc.i4.5?


Solution

  • Yes, it is entirely legal to use ldc.i4 1 in place of ldc.i4.1. The single-byte op-codes are given for efficiency and brevity in the most common scenarios. In particular, all those ldarg.0 (1 byte) would quickly add up to significantly increase the size of your assembly if they were ldarg 0 (3 bytes), as would the ldc.i4.1 in things like i++; ldc.i4 1 is 5 bytes instead of 1.

    You are not obliged to use them. I would actually expect (untested) the JIT to spot the more verbose usage and treat it the same anyway, although it would not be required to do so.

    Personally, when I'm doing "emit" or similar, I just use a utility method that emits the most appropriate code(s) for any given value / local / argument / etc.