Missing info in macro expansion chain

In the source below I need to be able to detect that the token 4 has
been expanded by body of macro z, but I'm unable to do that.

Asking for immediate expansion range of expanded location I get a
MacroArgExpansion loc for argument x whose immediate expansion range is
macro p.

It seems that use of macro z is not tracked in expansion chain, I'm
missing something?

#define p(x) x
#define z 4

void foo() {

Can you clarify exactly what it is you’re doing? This information is there to be dug out. You can see that it is preserved and that we use it in the caret diagnostics, check out the very first test in test/Misc/caret-diags-macro.c which should be exactly the same as your case.

You’ll likely need to combine getting the immediate expansion w/ getting the immediate spelling location and then getting its expansion in order to alternate between tracing the argument down and the text the user wrote.

The code that does this in diagnostics is DiagnosticRenderer::emitMacroExpansionsAndCarets (and its associated helper routines).

Also check out Lexer::getImmediateMacroName().