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

    <tr>
        <th>Summary</th>
        <td>
            [DirectX] Running DXILFinalizeLinkage late causes DXILForwardHandleAccesses to fall over in dead code
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            new issue,
            backend:DirectX
      </td>
    </tr>

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

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

<pre>
    In #136244 we moved the DXILFinalizeLinkage pass later in order to take advantage of the fact that it deletes dead intrinsic declarations after we run DXILLegalize, which can remove all the uses of an intrinsic. However, this is causing problems, as now DXILForwardHandleAccess is running on (now dead) pre-inlined functions, and it isn't able to work out a mapping between globals and handles.

There are a few aspects to the problem here:
- Should DXILForwardHandleAccess be made to work on code that hasn't yet been inlined?
- Is DXILFinalizeLinkage in the right place in the pipeline?
- Should cleaning up dead intrinsic definitions be part of DXILFinalizeLinkage or separate?

I think the answers to these three questions are maybe, no, and separate. We put the intrinsic cleanup code into finalize linkage for two reasons: 1) convenience since the logic is similar, and 2) an assumption that later passes would clean up after themselves. I no longer think that was the right decision, for a couple of reasons:

1. Dead intrinsics have nothing to do with linkage. 
2. SPIR-V doesn't need to clean up dead intrinsics since it will go through an actual instruction selector, but it does care about linkage
3. The reason we need to clean up intrinsics is that we're going directly to DXIL from IR. LLVM IR allows these to be present and ignores them if they're unused, and it generally doesn't matter because it isn't the final product.

We should move the cleanup of dead intrinsics way later in the pipeline (likely DXILPrepare) and we should move finalize linkage back to the beginning of the backend pipeline.
</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJx0VcFu2zgQ_Rr5MoggUXacHHzwNjBqIAsUadH2SpEjiWuK1HIoC96vXwwl195NekiCiJyZN2_ePEoi0zrEXbb5I9u8rOQYOx92tW8dhlXt9WV3dJCJqqwexXoNE0Lvz6ghdggv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