<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/59889>59889</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            clang assumes `this` is aligned, misoptimizes for tagged pointers
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            new issue
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          nbuwe
      </td>
    </tr>
</table>

<pre>
    clang 13 and later seem to assume that "this" in C++ is always suitably aligned and optimize aggressively based on that assumption.

The following example is distilled from the [Self](https://selflanguage.org/) VM code.  clang 13+ compiles `foo` to always return 666.  clang 12 emits the code to check the tag.
```
typedef unsigned long uintptr_t;

class T {
public:
    void *data;                 // need aligned data memeber to trigger

    int foo() const { return 42; }

    uintptr_t tag() const {
        // clang assumes "this" is aligned and so tag always returns 0
        return reinterpret_cast<uintptr_t>(this) & 0x3;
    }

    T *addr() const {
        return (T *)(reinterpret_cast<uintptr_t>(this) &~ 0x3);
    }
};

// This function is miscompiled to return 666
int
foo(T *t)
{
#if 1
    uintptr_t tag = t->tag();        // <- misoptimized
#else
    uintptr_t tag = reinterpret_cast<uintptr_t>(t) & 0x3; // ok
#endif

    int i;
    if (tag == 1)
        i = t->addr()->foo();
    else
        i = 666;

    return i;
}
```
Self VM uses lower bits in pointers as tags (for the garbage collector, etc) and uses inline methods like `tag` and `addr` above to manipulate such tagged pointers.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyUVU9v6zYM_zTKhWigyInjHHJ4aV5vO63Y9UG2aFurLBmi3L7usM8-UHaSpngdNsBIIkckf38oShPZziMexe4kdueVnlIf4tHX0xuu6mDej43TvoNNAdobcDphBEIcIAXQRNOAkHqdQCiVektCKbAeHoU6CXUCS6Ddm34noMkmXbt30I4LmpwujMkO9i8E3XURiewruneoNaGB4OfEuciYbPBrIc9Cfps_n3uENjgX3qzvAH_q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