runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Get the inline stack on IP level

Open BrianBohe opened this issue 6 years ago • 8 comments

It would be great if we can get the virtual stack frame of inline functions.

Given the following code:

static int C(int a)
{
    Console.WriteLine(a);
    Random b = new Random();
    return a << b.Next();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static int B(int a)
{
    //Random b = new Random();
    //return C(b.Next() * a*3);
    return C(a);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static int A(int a)
{
    Random b = new Random();
    return B(b.Next() * a+1);
}

static void Main(string[] args)
{
    int res = A(42);
    Console.WriteLine(res);
}

If we put a breaking on the second line of function C, we expect the debugger to show a call stack like

  • C(int a)
  • B(int a)
  • A(int a)
  • Main(string[] args)

but we would get image

What is happening is that B is getting inlined in A and A in Main, and we are not reporting that to the debugger.

BrianBohe avatar Jan 30 '20 19:01 BrianBohe

There are quite a few things you will need to change to pull this off.

One is knowing which inlines are "active" at any given point in the code. Internally, the jit keeps a tree of inlines (largely accurate, but not guaranteed to be perfect) ; each statement in jit IR should point at a node in this tree indicating the method that the statement came from. You can dump this tree from a checked jit via COMPlus_JitPrintInlinedMethods=1, eg

Inlines into 06000001 BenchmarksGame.BinaryTrees_2:Main(System.String[]):int
  [1 IL=0009 TR=000025 06000FEF] [profitable inline] System.Int32:Parse(System.String):int
    [2 IL=0011 TR=000034 0600067F] [aggressive inline attribute] System.String:op_Implicit(System.String):System.ReadOnlySpan`1[Char]
      [3 IL=0014 TR=000055 06000688] [below ALWAYS_INLINE size] System.String:GetRawStringData():byref:this
      [4 IL=0025 TR=000064 06001281] [aggressive inline attribute] System.ReadOnlySpan`1[Char][System.Char]:.ctor(byref,int):this

The statement -> inline tree node mapping is produced during inlining and may get corrupted by later jit phases; only the inliner itself uses that data today. I don't know how pervasive this corruption is but I assume it is pretty bad. Any time a new statement is created after inlining something needs to figure out the right inline tree node for that statement.

You will also lose track of some things. for example a method that returns a constant or that just returns one of its arguments will likely just evaporate and leave no trace in the IR as the contribution of the inlinee was not a statement but just an IR node.

Once this IR->inline info has made it to the backend of the jit in good shape, it needs to be externalized into the debug information somehow. Then you would be able to go from some IP value to the set of frames you'd need to show in the debugger.

Along with this the jit would need to track the IL offsets properly in all statements, so that you could tell logically where you were in each inline frame (that is, synthesize the "Line N" part). Currently the jit does not do track IL offsets for statements from inlines, and the information likewise may get corrupted by subsequent phases. So corruption fixes would be needed here, along with some difficult cases where it is less obvious what is correct (eg if we CSE a node from two different statements, what inlinee/offset do we put on the CSE?).

Note for some method B the IL->native offset mapping for B itself will be quite different than for some inlined instance of B, and each inlined instance of B will have different offset info.

Getting all that correct and externalized and consumed by the debugger would give you inline function names and line offsets.

If you also want to describe locals and args for these frames then you need even more info. The jit does not keep track of args and locals introduced by inlining; they all look like jit temps. So there would have to be some extra bookkeeping in the local var table to map jit temps back to locals/args and to the relevant bit of the inline tree (and likely vice-versa -- from a node in the inline tree you'd want to find the temps that represent that inline's args and locals), and you'd need to emit debug information for these temps too like you do for the root method variables already.

All this data will end up being pretty large so there are complex challenges in finding an efficient way to represent it in the debug info. For a proof of concept you probably should defer this -- it is probably best only to tackle this once you have all the data you need...

So, I'd suggest the following outline:

  1. Investigate the statement -> inline tree node mapping in the jit. Fix cases where statements don't have associated tree nodes. Decide how to handle things like CSEs from two different inlinees. Assert at debug emission time that all statements refer to some inline tree node.
  2. Create debug records to externalize this info. This would be something like a map from native offset to inline record; each inline record would have a parent record and info needed to describe the method in the debugger (token/scope? not sure what suffices here).
  3. (possible demo) fix up some debugger to consult this data and fake up frames and show them. Could demo how this display changes as you step through the method.
  4. Update jit to track IL offsets for inlinee introduced statements. Initially, do this in such a way that it does not alter the debug emission. Add checking at end that all IL offsets for a statement are compatible with the associated inline tree node.
  5. Externalize native-> il offset for inlinee code, likely referring to the inline records in (2).
  6. (possible demo) Update debugger to use this to show line info for the inline frames, perhaps integrate this into the actual stack display and allow clicking on an inline frame to navigate to the right place in the source
  7. Update jit local var table to track inline introduced args and locals
  8. Update debug emission to emit inline args and locals plus location and live ranges
  9. (possible demo) update debugger to display inline args and locals
  10. Figure out how to do all of the above in a way that does not require enormous amounts of debug information.

AndyAyersMS avatar Jan 30 '20 20:01 AndyAyersMS

The JIT is giving this information for the debugging

struct boundariesDsc
{
    UNATIVE_OFFSET nativeIP;
    IL_OFFSET      ilOffset;
    unsigned       sourceReason;
} * eeBoundaries; 

on Compiler::eeSetLIinfo and Compiler::SetLIDone, as a way of mapping from IL to IP. The debugger assumes the ILOffsets are of the function being jitted.

BrianBohe avatar Jan 30 '20 22:01 BrianBohe

@AndyAyersMS, I have some questions:

  1. Can every statement map to an IL (or at least one IL)?

  2. I saw the inline context is tracked per statement and that only statements are candidates to get map to an IL. Could it be the case that one statement end up being inside another statement? And if we want to differentiate those two statements, Is it okay to discretize at a statement level? Should we assign to the GenTree* nodes their context?

  3. When Rationalizer::DoPhase happens, we stop seeing statements and continue with a list of GenTree* where some GenTreeILOffsetThe are added. Could this GenTree* nodes change their order?

BrianBohe avatar Jan 30 '20 22:01 BrianBohe

Some statements don't map to any IL offset (m_ILOffsetX will be BAD_IL_OFFSET). The rest should at least have a starting IL offset.

Statements are always top level, so one can't be inside another. I do not think we need to track things below this level.

When statements go away their semantic content is transferred to the GT_IL_OFFSET tree nodes. These new tree nodes should also capture the inline context from the statement.

Note we only make these GT_IL_OFFSET nodes for statements with valid offsets. In the current system, all statements coming from inlinees will have invalid offsets, so all their statement node info will be lost during rationalize. You may need to work around this if you follow my plan of first preserving the "what inlinee did I come from" data before you try and implement the "what IL offset in the inlinee did I come from" data.

AndyAyersMS avatar Jan 30 '20 23:01 AndyAyersMS

I think I will follow these steps:

On track steps

  1. Add to Statement a InlineFunction * to the function which it came from
  2. Add this to the GenTreeILOffset node and pass it to when rationalize happens
  3. Propose a communication interface to expose this information to the debugger. A map from native offset to inlined function sounds good to me and we can iterate this if it ends up been much information. If we choose that I think we can report all the native offset -> IL offset as the existing way, asserting they are sorted by native offset increasingly.
  4. Dump this information on JITDUMP (this is the minimum baseline to show in the presentation)
  5. Fix special cases of statements (like statements without tree nodes, and more if there more cases)
  6. Update IL offset for inlinee introduced statements. Add/Update existing asserts on IL considering each inline context.

Out of scope of my internship project are inline function's var/arg: 7. Update jit local var table to track inline introduced args and locals 8. Update debug emission to emit inline args and locals plus location and live ranges (possible demo) update debugger to display inline args and locals

BrianBohe avatar Jan 31 '20 00:01 BrianBohe

I made some progress. Using the ,cs example above, which has this IL

Main
IL to import:
IL_0000  1f 2a             ldc.i4.s     0x2A
IL_0002  28 03 00 00 06    call         0x6000003
IL_0007  28 0b 00 00 0a    call         0xA00000B
IL_000c  2a                ret

Invoking compiler for the inlinee method example1.Program:A(int):int :
IL to import:
IL_0000  73 0c 00 00 0a    newobj       0xA00000C
IL_0005  6f 0d 00 00 0a    callvirt     0xA00000D
IL_000a  02                ldarg.0
IL_000b  5a                mul
IL_000c  17                ldc.i4.1
IL_000d  58                add
IL_000e  28 02 00 00 06    call         0x6000002
IL_0013  2a                ret

Invoking compiler for the inlinee method example1.Program:B(int):int :
IL to import:
IL_0000  02                ldarg.0
IL_0001  28 01 00 00 06    call         0x6000001
IL_0006  2a                ret

We got 5 statements, which are

***** BB01
STMT00003 (IL 0x000...0x013) inlined from example1.Program:A(int):int
N005 ( 17, 16) [000008] -AC-----R---              *  ASG       ref    $180
N004 (  1,  1) [000007] D------N----              +--*  LCL_VAR   ref    V02 tmp1         d:1 $180
N003 ( 17, 16) [000006] --C---------              \--*  CALL help ref    HELPER.CORINFO_HELP_NEWSFAST $180
N002 (  3, 10) [000005] ------------ arg0 in rcx     \--*  CNS_INT(h) long   0x7ffe02fc1ba8 token $100

***** BB01
STMT00004 (IL   ???...  ???) inlined from example1.Program:A(int):int
N003 ( 15,  8) [000010] --CXG-------              *  CALL      void   System.Random..ctor $VN.Void
N002 (  1,  1) [000009] ------------ this in rcx  \--*  LCL_VAR   ref    V02 tmp1         u:1 $180

***** BB01
STMT00007 (IL 0x00E...  ???) inlined from example1.Program:A(int):int
N009 ( 22, 14) [000024] -ACXG---R---              *  ASG       int    $201
N008 (  1,  1) [000023] D------N----              +--*  LCL_VAR   int    V03 tmp2         d:1 $201
N007 ( 22, 14) [000016] --CXG-------              \--*  ADD       int    $201
N005 ( 20, 12) [000014] --CXG-------                 +--*  MUL       int    $200
N003 ( 15,  8) [000012] --CXG-------                 |  +--*  CALL      int    System.Random.Next $1c0
N002 (  1,  1) [000011] ------------ this in rcx     |  |  \--*  LCL_VAR   ref    V02 tmp1         u:1 (last use) $180
N004 (  1,  1) [000013] ------------                 |  \--*  CNS_INT   int    42 $41
N006 (  1,  1) [000015] ------------                 \--*  CNS_INT   int    1 $43

***** BB01
STMT00001 (IL 0x007...  ???) inlined from example1.Program:Main(System.String[])
N005 ( 29, 13) [000003] --CXG-------              *  CALL      void   System.Console.WriteLine $VN.Void
N004 ( 15,  7) [000021] --CXG------- arg0 in rcx  \--*  CALL      int    example1.Program.C $1c4
N003 (  1,  1) [000020] ------------ arg0 in rcx     \--*  LCL_VAR   int    V03 tmp2         u:1 (last use) $201

***** BB01
STMT00002 (IL 0x00C...  ???) inlined from example1.Program:Main(System.String[])
N001 (  0,  0) [000004] ------------              *  RETURN    void   $240

And dumping the IPMappingDsc* I get:

IP mapping count : 8
IL offs PROLOG : 0x00000000 ( STACK_EMPTY )
IL offs 0x0002 : 0x00000005 ( STACK_EMPTY )
IL offs 0x0000 : 0x00000005 ( STACK_EMPTY ) imported from example1.Program:A(int):int
IL offs 0x0002 : 0x0000001F ( STACK_EMPTY )
IL offs 0x000E : 0x0000001F imported from example1.Program:A(int):int
IL offs 0x0007 : 0x0000002D
IL offs 0x000C : 0x00000039 ( STACK_EMPTY )
IL offs EPILOG : 0x00000039 ( STACK_EMPTY )

I have added an extra IPMappingDsc* per each call that made us get that statement. In this example, Main inlined A and then inlined B. The two imported statements of A, has an IPMappingDsc before with the IL offset on Main from where the call has been done.

We can't find statements from B because the call was copied to the expected return value on STMT00001.

BrianBohe avatar Feb 06 '20 20:02 BrianBohe

I am moving forward with the interface changes needed to have something I could present at the end of my internship and then I will consider the cases in which I could lost debug info (like CSE).

BrianBohe avatar Feb 06 '20 20:02 BrianBohe

I have done some progress. I have opened a WIP PR to get reviews.

This is the updated list of tasks.

Done

  • [x] Add to Statement a InlineFunction * to the function which it came from.
  • [x] Add this to the GenTreeILOffset node and pass it to when rationalize happens.
  • [x] Update IL offset for inlinee introduced statements. Add/Update existing asserts on IL considering each inline context.
  • [x] Dump this information on JITDUMP (this is the minimum baseline to show in the presentation).
  • [x] Changes on the JIT Interface to store the new information.

On track steps

  1. Changes on interfaces to expose this information in order to be consumed.
  2. Fix special cases of statements (like statements without tree nodes, and more if there more cases)

Out of scope of my internship project are inline function's var/arg:

  1. Update jit local var table to track inline introduced args and locals
  2. Update debug emission to emit inline args and locals plus location and live ranges (possible demo) update debugger to display inline args and locals

BrianBohe avatar Feb 21 '20 00:02 BrianBohe