Get Module from an IR instruction. Is it necessary to check nullptr in the chain of `getParent()` function call?

Hi,
The use case is to get the Module pointer from a given IR instruction, which is basically Instruction.getParent()->getParent()->getParent().

The question is, is it necessary to check nullptr in the chain of getParent() function call? Could an middle-end pass assume an IR instruction always has a BB, and this BB always has a Function, and this Function always has a Module?

Searching getParent()->getParent()->getParent() gives a bunch of use cases, like llvm-project/InlineAdvisor.cpp at 2f637fe730a7b65f4584ae636c50197ebaf5a4a7 · llvm/llvm-project · GitHub, so it seems to me checking nullptr is not necessary. If this is true, which pass guarantees that an IR instruction always resides in a Module?

IR is usually accessed in ‘top-down’ fashion with clearly defined module and function contexts. Unless it is corrupted, the parent link should point to the contexts which are valid.

got it, thanks!

You usually only need to check these for nullptr if your API is explicitly designed to work on instructions that have not been inserted into a function, or functions that have not been inserted into a module. For example, you’ll find checks like this in InstructionSimplify (which explicitly supports non-inserted instructions), but not most other places: llvm-project/InstructionSimplify.cpp at 0af19ef9ff5364f76f682259f9c7f5579aa95696 · llvm/llvm-project · GitHub

You usually only need to check these for nullptr if your API is explicitly designed to work on instructions that have not been inserted into a function, or functions that have not been inserted into a module.

Acknowledged,thanks for the example!