Question for llvm dyn_cast<type>() helper function in MLIR toy example

I was looking into the MLIR toy tutorial and found something I don’t understand.
According to the document, dyn_cast should return pointer type. However, in the MLIR toy source code,

// Ask the operation to infer its output shapes.
      LLVM_DEBUG(llvm::dbgs() << "Inferring shape for: " << *op << "\n");
      if (auto shapeOp = dyn_cast<ShapeInference>(op)) {
        shapeOp.inferShapes();

It seems like shapeOp is not pointer type, but ‘ShapeInference’ type. After this, it inferences shape and changes type of the result of the operation.

My question is

  1. How can dyn_cast return object that is not a pointer?
  2. How can changing output type of ShapeInference take effect if it doesn’t point to the object inside the current operation?

I must be misunderstanding something. Your help will be appreciated.
Best regards

I’d suggest taking a look at Casting.h - but the short answer is that dyn_cast simply invokes the static doCastIfPossible on the CastInfo<To, From> specialized for a given type. For mlir::Operation this means calling this here: llvm-project/Operation.h at main · llvm/llvm-project · GitHub

The basic way this works is by constructing one object from another. In the case of MLIR, most (all?) objects use the pImpl idiom and so constructing a ShapeInference from an Operation * is really simple, and it means that casting from a value to another value works just fine because they’re more or less just different views on the same underlying storage.

1 Like

Thanks for your help. I looked inside the source code and I could see how it works.