Assertion `ResultPass && "getAnalysis*() called on an analysis that was not " "'required' by pass!"' failed.

Hello,

I have two passes, A and B. A is a function pass. B is a module
pass. Each uses their getAnalysisUsage() method to .addRequired()
several passes, and each .setPreserveAll()s. **Pass B requires pass
A**. But, when I call getAnalysis<A> from within B, it exclaims:

Assertion `ResultPass && "getAnalysis*() called on an analysis that
was not " "'required' by pass!"' failed.

Clearly, that is nonsense, because I require that pass.

Under what circumstances can this happen, and why?

I ran into this problem when B would call getAnalysis<A> on an
external function, ie. a declaration rather than a definition in LLVM
terms. If you're iterating over the functions within a module, try
skipping functions for which isDeclaration() returns true. From what I
can gather, the strange error message results from the fact that
function analysis called from modules are generated on the fly, but a
function analysis cannot be performed on an external function so the
analysis is unavailable and the assert triggers believing the pass was
never requested in the first place.