[LLVMdev] Undefined behavior in Operator class?

Sean Silva silvas at purdue.edu
Sat Oct 6 20:43:44 PDT 2012

If I understand correctly, Operator is basically a trivial temporary
object that holds some common functionality for both Instruction and

It looks to me like Operator is doing something illegal though. For
example, in this member function of class Operator (in

  /// getOpcode - Return the opcode for this Instruction or ConstantExpr.
  unsigned getOpcode() const {
    if (const Instruction *I = dyn_cast<Instruction>(this))
      return I->getOpcode();
    return cast<ConstantExpr>(this)->getOpcode();

In this function, the `this` pointer is not pointing at an Operator
object. That's undefined behavior, right?

The problem that this Operator is trying to solve is similar to the
situation with DeclContext's inside Clang. The primary difference is
that while Operator isn't actualy a parent, DeclContext is a proper
parent (using multiple inheritance), and so these casts become legit
cross-casts for DeclContext. I'm not sure if multiple inheritance is
the right solution here, but we definitely don't want UB. Maybe it can
just store a User* to the Instruction/ConstantExpr?

Thoughts? Is this UB?

CC'ing Dan Gohman since it looks like he's the one that initially put
Operator in place.

-- Sean Silva

More information about the llvm-dev mailing list