← Back to Pull requests

[SPIR-V] Rebuild pointer constant arms of an aggregate PHI or select #236370

Merged
gonsolo merged 8 files (402 lines) on Nov 23, 2026 15:08 UTC
View on GitHub
gonsolo gonsolo commented on Oct 28, 2026 10:42 UTC
Author

A constant arm's pointer members carry the pointee types deduced for them anywhere in the module (constant expressions are shared between functions), so the constant can be a different SPIR-V type than the PHI or select and its other arms: selectSelect asserts. Rebuild such an arm with insertvalue, which casts each member to the result's member type.

Assisted-by: Claude Opus 5.5

Diff: 402 lines (+353 / -49) across 8 files Reviewer: maarquitos14 Review duration: 37705m
All Vouch review confidence checks passed
Residual risk 0.14 = Change Risk (0.54) × (1 − Review Confidence (0.75)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.54 · 402 lines diff across 8 files
0.54
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.52 · 5 substantive comment(s)
0.52
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
74%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.359
Ai Authored ai_authored
0.050
Real PR Conversation Timeline
38 items
llvmorg-github-actions[bot] llvmorg-github-actions[bot] commented on Oct 28, 2026 10:43 UTC
Bot

<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-backend-spir-v

Author: Gonsolo (gonsolo)

<details>
<summary>Changes</summary>

A composite constant arm of an aggregate PHI or select gets its type from deduceNestedTypeHelper. Once the inttoptr constants in it have a deduced pointee type, which constant expressions carry across functions, that is a distinct struct with typed pointer members, i.e. a different SPIR-V type than the select and its other arms: selectSelect asserts. The test needs a second function that uses one of the constants first.

Every arm of a PHI or select has the result's type, so its constant arms now get that type.

Testing: the new test fails without the change; llvm/test/CodeGen/SPIRV passes (1375 tests) and the output passes spirv-val. Found while compiling Mojo GPU kernels (a path tracer, 117 modules) for an Intel Arc B580: with this and two related SPIR-V fixes, every module compiles to valid SPIR-V without frontend workarounds.

This change was prepared with AI assistance (Claude Code); I have reviewed it and will answer for it in review.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LqBCeZyWd3hVdxTTAumnrq

---
Full diff: https://github.com/llvm/llvm-project/pull/236370.diff

2 Files Affected:

  • (modified) llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp (+7)

  • (added) llvm/test/CodeGen/SPIRV/instructions/select-constant-arm-deduced-pointee.ll (+25)
  • ``````

    diff --git a/llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp b/llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp
    index 9b45b9ebc32cf..6f430314fc532 100644
    --- a/llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp
    +++ b/llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp
    @@ -3899,6 +3899,13 @@ bool SPIRVEmitIntrinsicsImpl::runOnFunction(Function &Func) {
           continue;
         // Give multi-register arms a value-id first, before the result is mutated.
         insertCompositeAggregateArms(&I, B);
    +    // Every arm has the result's type. A constant arm's deduced type can be a
    +    // distinct struct with typed pointer members (pointee types deduced in
    +    // another function), which would no longer match.
    +    for (Value *Op : I.operands())
    +      if (auto *OpI = dyn_cast<Instruction>(Op))
    +        if (auto It = AggrConstTypes.find(OpI); It != AggrConstTypes.end())
    +          It->second = I.getType();
         AggrConstTypes[&I] = I.getType();
         I.mutateType(I32Ty);
       }
    diff --git a/llvm/test/CodeGen/SPIRV/instructions/select-constant-arm-deduced-pointee.ll b/llvm/test/CodeGen/SPIRV/instructions/select-constant-arm-deduced-pointee.ll
    new file mode 100644
    index 0000000000000..e589fabd88e4b
    --- /dev/null
    +++ b/llvm/test/CodeGen/SPIRV/instructions/select-constant-arm-deduced-pointee.ll
    @@ -0,0 +1,25 @@
    +; Every arm of an aggregate select has the select's type. A constant arm's
    +; deduced type became a distinct struct with typed pointer members once the
    +; inttoptr constants it holds had a pointee type deduced (here in @a, since
    +; constant expressions are shared between functions), which no longer matched
    +; the select and its zeroinitializer arm.
    +
    +; RUN: llc -O0 -mtriple=spirv64-unknown-unknown %s -o - | FileCheck %s
    +; RUN: %if spirv-tools %{ llc -O0 -mtriple=spirv64-unknown-unknown %s -o - -filetype=obj | spirv-val %}
    +
    +; CHECK: %[[#Ptr:]] = OpTypePointer Generic
    +; CHECK: %[[#Q:]] = OpTypeStruct %[[#Ptr]] %[[#Ptr]]
    +; CHECK-NOT: OpTypeStruct %[[#Ptr]] %[[#Ptr]]
    +; CHECK: OpSelect %[[#Q]] %[[#]] %[[#]] %[[#]]
    +
    +%P = type { ptr addrspace(4), i32 }
    +%Q = type { ptr addrspace(4), ptr addrspace(4) }
    +
    +define %P @a() {
    +  ret %P { ptr addrspace(4) inttoptr (i64 4 to ptr addrspace(4)), i32 0 }
    +}
    +
    +define %Q @b(i1 %c) {
    +  %s = select i1 %c, %Q zeroinitializer, %Q { ptr addrspace(4) inttoptr (i64 8 to ptr addrspace(4)), ptr addrspace(4) inttoptr (i64 4 to ptr addrspace(4)) }
    +  ret %Q %s
    +}
    
    
    ``````

    </details>

    MrSidims MrSidims requested changes on Nov 01, 2026 19:53 UTC
    Changes Requested Reviewer

    The override is only correct when the deduced pointee happens to be i8, which is what the test in the PR exercises. With a typed member the deduced struct really differs and forcing the select's type without casting the members produces invalid SPIR-V instead of the current assert

    gonsolo gonsolo commented on Nov 02, 2026 11:29 UTC
    Author

    You're right, thanks. Forcing the type only covered an i8 pointee: with an i32 pointee deduced for the same constant in another function it still asserts. I've replaced the override with rebuilding such a constant arm as an insertvalue chain, so the member casts from #227599 apply. The test now covers both pointees and a PHI arm; it fails without the change, check-llvm-codegen-spirv passes and spirv-val accepts the output.

    Session: https://claude.ai/code/session_0141xq22BhyCNa4pRpmwvhAc

    MrSidims MrSidims commented on code on Nov 05, 2026 22:37 UTC
    Code Review
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp:1
    @@ -1808,6 +1809,33 @@ void SPIRVEmitIntrinsicsImpl::insertCompositeAggregateArms(Instruction *I,
       }
     }
     
    +// Rebuild each constant arm of an aggregate PHI/select/freeze that holds
    +// pointers as an insertvalue chain. A constant's pointer members carry the
    +// pointee types deduced for them anywhere in the module, so the constant can be
    +// a different SPIR-V type than the result; insertvalue casts each member to the
    +// result's member type.
    +void SPIRVEmitIntrinsicsImpl::insertPointerConstantArms(Function &Func) {

    I feel like this routine could be broken for a case with a switch, whose two cases lead into the same block. Could you add a test for this?

    gonsolo gonsolo commented on code on Nov 05, 2026 23:27 UTC
    Code Review
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp:1
    @@ -1808,6 +1809,33 @@ void SPIRVEmitIntrinsicsImpl::insertCompositeAggregateArms(Instruction *I,
       }
     }
     
    +// Rebuild each constant arm of an aggregate PHI/select/freeze that holds
    +// pointers as an insertvalue chain. A constant's pointer members carry the
    +// pointee types deduced for them anywhere in the module, so the constant can be
    +// a different SPIR-V type than the result; insertvalue casts each member to the
    +// result's member type.
    +void SPIRVEmitIntrinsicsImpl::insertPointerConstantArms(Function &Func) {

    You're right, a switch with two cases into the same block got two different insertvalue chains for one predecessor, which the verifier rejects. Fixed in ec6d19eada by building one chain per incoming block, with a switch test.

    maleadt maleadt commented on Nov 06, 2026 11:25 UTC
    Contributor

    Thanks, this also fixes a case Julia's GPU back-ends can hit. Julia's bits-union return values produce this pattern (phi { ptr, i8 } [ { ptr getelementptr (i8, ptr @box, i64 8), i8 -124 }, ... ] from a @noinline function returning a Union). On main that becomes an OpPhi spirv-val rejects. With this PR it validates, and our test suite still passes.

    Nested aggregates still assert though, since only top-level members are checked:

    @g = addrspace(1) global i32 0
    %Q = type { ptr addrspace(1), i32 }
    %R = type { %Q, i32 }
    define %R @nested(i1 %c) {
      %s = select i1 %c, %R zeroinitializer, %R { %Q { ptr addrspace(1) @g, i32 1 }, i32 2 }
      ret %R %s
    }
    

    Rebuilding nested ConstantAggregate members recursively, each as its own chain, probably fixes that.

    maleadt maleadt commented on code on Nov 06, 2026 11:26 UTC
    Code Review
    llvm/test/CodeGen/SPIRV/instructions/select-constant-arm-deduced-pointee.ll:1
    @@ -0,0 +1,65 @@
    +; A constant arm of an aggregate select or PHI holds pointer members whose
    +; pointee types were deduced elsewhere in the module (constant expressions are
    +; shared between functions): i8 for the one returned in @a, i32 for the one
    +; loaded through in @a2. The arm is rebuilt with insertvalue, which casts each
    +; member to the result's member type, so all arms have the result's type.
    +; A PHI arm is rebuilt in its incoming block, once even when a switch lists
    +; that block twice.

    I don't think this even needs a second function: any pointer member with a known pointee is enough, e.g. select i1 %c, %Q zeroinitializer, %Q { ptr addrspace(1) @g, i32 1 } asserts on its own. For a PHI there's no assert, just an OpPhi that spirv-val rejects.

    gonsolo gonsolo commented on Nov 06, 2026 12:06 UTC
    Author

    Thanks for testing it with Julia! Nested aggregates are handled in 5e6f553d9f: a nested struct or array member with pointers is rebuilt as its own insertvalue chain, with your reproducer as a test (select and PHI). And 91857e6d59 simplifies the test as you suggested: one global with a known pointee instead of the extra functions.

    aobolensk aobolensk commented on code on Nov 09, 2026 14:56 UTC
    Code Review
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp:1
    @@ -1808,6 +1809,64 @@ void SPIRVEmitIntrinsicsImpl::insertCompositeAggregateArms(Instruction *I,
       }
     }
     
    +static bool isStructOrArrayConstant(const Value *V) {
    +  return isa<ConstantStruct, ConstantArray>(V);

    hasPointerMember() misses pointers nested inside ConstantVector. I believe that handling could be added here as well

    aobolensk aobolensk commented on code on Nov 09, 2026 15:02 UTC
    Code Review
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp:1
    @@ -1808,6 +1809,64 @@ void SPIRVEmitIntrinsicsImpl::insertCompositeAggregateArms(Instruction *I,
       }
     }
     
    +static bool isStructOrArrayConstant(const Value *V) {
    +  return isa<ConstantStruct, ConstantArray>(V);
    +}
    +
    +static bool hasPointerMember(const Constant *C) {
    +  return any_of(C->operands(), [](const Use &E) {
    +    return E->getType()->isPointerTy() ||
    +           (isStructOrArrayConstant(E.get()) &&
    +            hasPointerMember(cast<Constant>(E.get())));
    +  });
    +}
    +
    +// A nested aggregate member with pointers gets its own chain.
    +static Value *buildInsertValueChain(Constant *C,
    +                                    BasicBlock::iterator InsertPt) {
    +  Value *Composite = PoisonValue::get(C->getType());
    +  for (unsigned Idx = 0, E = C->getNumOperands(); Idx != E; ++Idx) {
    +    Value *Member = C->getOperand(Idx);
    +    if (isStructOrArrayConstant(Member) &&
    +        hasPointerMember(cast<Constant>(Member)))
    +      Member = buildInsertValueChain(cast<Constant>(Member), InsertPt);
    +    Composite = InsertValueInst::Create(Composite, Member, Idx, "", InsertPt);
    +  }
    +  return Composite;
    +}
    +
    +// Rebuild each constant arm of an aggregate PHI/select/freeze that holds
    +// pointers as an insertvalue chain. A constant's pointer members carry the
    +// pointee types deduced for them anywhere in the module, so the constant can be
    +// a different SPIR-V type than the result; insertvalue casts each member to the
    +// result's member type.
    +void SPIRVEmitIntrinsicsImpl::insertPointerConstantArms(Function &Func) {
    +  for (Instruction &I : instructions(Func)) {
    +    if (!isAggregateValueIdInstr(I))
    +      continue;
    +    auto *Phi = dyn_cast<PHINode>(&I);
    +    // A switch can list an incoming block twice, and both entries need the
    +    // same value, so build one chain per block.
    +    SmallDenseMap<BasicBlock *, Value *> PhiArms;
    +    for (Use &U : I.operands()) {
    +      auto *C = dyn_cast<ConstantAggregate>(U.get());
    +      if (!C || !hasPointerMember(C))

    Could we rebuild only when the deduced spirv type actually differs from the result type? Otherwise we're spamming too much with insertvalue instruments

    gonsolo gonsolo commented on code on Nov 09, 2026 18:29 UTC
    Code Review
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp:1
    @@ -1808,6 +1809,64 @@ void SPIRVEmitIntrinsicsImpl::insertCompositeAggregateArms(Instruction *I,
       }
     }
     
    +static bool isStructOrArrayConstant(const Value *V) {
    +  return isa<ConstantStruct, ConstantArray>(V);
    +}
    +
    +static bool hasPointerMember(const Constant *C) {
    +  return any_of(C->operands(), [](const Use &E) {
    +    return E->getType()->isPointerTy() ||
    +           (isStructOrArrayConstant(E.get()) &&
    +            hasPointerMember(cast<Constant>(E.get())));
    +  });
    +}
    +
    +// A nested aggregate member with pointers gets its own chain.
    +static Value *buildInsertValueChain(Constant *C,
    +                                    BasicBlock::iterator InsertPt) {
    +  Value *Composite = PoisonValue::get(C->getType());
    +  for (unsigned Idx = 0, E = C->getNumOperands(); Idx != E; ++Idx) {
    +    Value *Member = C->getOperand(Idx);
    +    if (isStructOrArrayConstant(Member) &&
    +        hasPointerMember(cast<Constant>(Member)))
    +      Member = buildInsertValueChain(cast<Constant>(Member), InsertPt);
    +    Composite = InsertValueInst::Create(Composite, Member, Idx, "", InsertPt);
    +  }
    +  return Composite;
    +}
    +
    +// Rebuild each constant arm of an aggregate PHI/select/freeze that holds
    +// pointers as an insertvalue chain. A constant's pointer members carry the
    +// pointee types deduced for them anywhere in the module, so the constant can be
    +// a different SPIR-V type than the result; insertvalue casts each member to the
    +// result's member type.
    +void SPIRVEmitIntrinsicsImpl::insertPointerConstantArms(Function &Func) {
    +  for (Instruction &I : instructions(Func)) {
    +    if (!isAggregateValueIdInstr(I))
    +      continue;
    +    auto *Phi = dyn_cast<PHINode>(&I);
    +    // A switch can list an incoming block twice, and both entries need the
    +    // same value, so build one chain per block.
    +    SmallDenseMap<BasicBlock *, Value *> PhiArms;
    +    for (Use &U : I.operands()) {
    +      auto *C = dyn_cast<ConstantAggregate>(U.get());
    +      if (!C || !hasPointerMember(C))

    Done in a5e35f8c1bd9. An arm is now rebuilt only when deduceNestedTypeHelper gives it a different type than its LLVM type, which happens when a pointer member has a known pointee. preprocessCompositeConstants uses the same helper to type the constant. Nested members are rebuilt only under the same condition, and an arm with only null pointers is kept as it is (new CHECK-NOT case in select-constant-arm-deduced-pointee.ll).

    gonsolo gonsolo commented on code on Nov 09, 2026 18:29 UTC
    Code Review
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp:1
    @@ -1808,6 +1809,64 @@ void SPIRVEmitIntrinsicsImpl::insertCompositeAggregateArms(Instruction *I,
       }
     }
     
    +static bool isStructOrArrayConstant(const Value *V) {
    +  return isa<ConstantStruct, ConstantArray>(V);

    Right, a <2 x ptr addrspace(1)> member hit the same selectSelect assert. hasPointerMember is gone (see the other thread), and 34401a29edce rebuilds a vector member as an insertelement chain. That needed 55b64abc20f1 first: unlike insertvalue, insertelement did not cast an inserted pointer to the element type, so a plain insertelement of @g into a <2 x ptr addrspace(1)> already failed spirv-val. Tests: select-constant-arm-pointer-vector.ll and insertelement-typed-pointer.ll, both pass spirv-val.

    maarquitos14 maarquitos14 commented on code on Nov 11, 2026 21:44 UTC
    Code Review
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp:1
    @@ -1808,6 +1811,65 @@ void SPIRVEmitIntrinsicsImpl::insertCompositeAggregateArms(Instruction *I,
       }
     }
     
    +// True for a constant aggregate whose deduced type differs from its LLVM type,
    +// i.e. one with a pointer member of known pointee type.
    +bool SPIRVEmitIntrinsicsImpl::hasDeducedPointee(Value *V) {
    +  auto *C = dyn_cast<ConstantAggregate>(V);
    +  return C && deduceNestedTypeHelper(C, false) != C->getType();
    +}
    +
    +// A nested aggregate or vector member with such pointers gets its own chain,
    +// a vector one of insertelement.
    +Value *
    +SPIRVEmitIntrinsicsImpl::buildInsertValueChain(Constant *C,
    +                                               BasicBlock::iterator InsertPt) {
    +  Value *Composite = PoisonValue::get(C->getType());
    +  bool IsVector = C->getType()->isVectorTy();
    +  Type *I32Ty = Type::getInt32Ty(C->getContext());
    +  for (unsigned Idx = 0, E = C->getNumOperands(); Idx != E; ++Idx) {
    +    Value *Member = C->getOperand(Idx);
    +    if (hasDeducedPointee(Member))
    +      Member = buildInsertValueChain(cast<Constant>(Member), InsertPt);
    +    if (IsVector)
    +      Composite = InsertElementInst::Create(
    +          Composite, Member, ConstantInt::get(I32Ty, Idx), "", InsertPt);
    +    else
    +      Composite = InsertValueInst::Create(Composite, Member, Idx, "", InsertPt);
    +  }
    +  return Composite;
    +}
    +
    +// Rebuild each constant arm of an aggregate PHI/select/freeze whose pointer
    +// members have known pointee types as an insertvalue chain. Such a constant is
    +// a different SPIR-V type than the result; insertvalue casts each member to the
    +// result's member type.
    +void SPIRVEmitIntrinsicsImpl::insertPointerConstantArms(Function &Func) {
    +  for (Instruction &I : instructions(Func)) {
    +    if (!isAggregateValueIdInstr(I))

    This excludes vectors, so a vector-of-pointers select hits the same selectSelect assert you're fixing for other types. The PHI version below is currently stopped earlier at legalizer, but with #241166 it produces an invalid OpPhi instead. Reproducible with:

    @g = addrspace(1) global i32 0
    define <2 x ptr addrspace(1)> @s(i1 %c) {
      %s = select i1 %c, <2 x ptr addrspace(1)> zeroinitializer, <2 x ptr addrspace(1)> <ptr addrspace(1) @g, ptr addrspace(1) @g>
      ret <2 x ptr addrspace(1)> %s
    }
    define <2 x ptr addrspace(1)> @p(i1 %c) {
    entry:
      br i1 %c, label %then, label %join
    then:
      br label %join
    join:
      %p = phi <2 x ptr addrspace(1)> [ zeroinitializer, %entry ], [ <ptr addrspace(1) @g, ptr addrspace(1) @g>, %then ]
      ret <2 x ptr addrspace(1)> %p
    }
    

    I tried with the code below instead (and with #241166), and the reproducer above passes and all the LIT tests too. Note the reproducer above needs --spirv-ext=+SPV_INTEL_masked_gather_scatter.

       if (!isAggregateValueIdInstr(I) &&
        !(isa<PHINode, SelectInst>(I) && I.getType()->isVectorTy()))
      continue;
    

    maarquitos14 maarquitos14 commented on code on Nov 11, 2026 21:47 UTC
    Code Review
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp:1
    @@ -1808,6 +1811,65 @@ void SPIRVEmitIntrinsicsImpl::insertCompositeAggregateArms(Instruction *I,
       }
     }
     
    +// True for a constant aggregate whose deduced type differs from its LLVM type,
    +// i.e. one with a pointer member of known pointee type.
    +bool SPIRVEmitIntrinsicsImpl::hasDeducedPointee(Value *V) {
    +  auto *C = dyn_cast<ConstantAggregate>(V);
    +  return C && deduceNestedTypeHelper(C, false) != C->getType();
    +}
    +
    +// A nested aggregate or vector member with such pointers gets its own chain,
    +// a vector one of insertelement.
    +Value *
    +SPIRVEmitIntrinsicsImpl::buildInsertValueChain(Constant *C,
    +                                               BasicBlock::iterator InsertPt) {
    +  Value *Composite = PoisonValue::get(C->getType());
    +  bool IsVector = C->getType()->isVectorTy();
    +  Type *I32Ty = Type::getInt32Ty(C->getContext());
    +  for (unsigned Idx = 0, E = C->getNumOperands(); Idx != E; ++Idx) {
    +    Value *Member = C->getOperand(Idx);
    +    if (hasDeducedPointee(Member))
    +      Member = buildInsertValueChain(cast<Constant>(Member), InsertPt);
    +    if (IsVector)
    +      Composite = InsertElementInst::Create(
    +          Composite, Member, ConstantInt::get(I32Ty, Idx), "", InsertPt);
    +    else
    +      Composite = InsertValueInst::Create(Composite, Member, Idx, "", InsertPt);
    +  }
    +  return Composite;
    +}
    +
    +// Rebuild each constant arm of an aggregate PHI/select/freeze whose pointer
    +// members have known pointee types as an insertvalue chain. Such a constant is
    +// a different SPIR-V type than the result; insertvalue casts each member to the
    +// result's member type.
    +void SPIRVEmitIntrinsicsImpl::insertPointerConstantArms(Function &Func) {
    +  for (Instruction &I : instructions(Func)) {
    +    if (!isAggregateValueIdInstr(I))
    +      continue;
    +    auto *Phi = dyn_cast<PHINode>(&I);
    +    // A switch can list an incoming block twice, and both entries need the
    +    // same value, so build one chain per block.
    +    SmallDenseMap<BasicBlock *, Value *> PhiArms;

    Did I not see this before in other PRs you authored? I think #236369 has it too, or very similar. Could be factored out to a helper?

    maarquitos14 maarquitos14 commented on code on Nov 11, 2026 21:52 UTC
    Code Review
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp:1
    @@ -1808,6 +1811,65 @@ void SPIRVEmitIntrinsicsImpl::insertCompositeAggregateArms(Instruction *I,
       }
     }
     
    +// True for a constant aggregate whose deduced type differs from its LLVM type,
    +// i.e. one with a pointer member of known pointee type.
    +bool SPIRVEmitIntrinsicsImpl::hasDeducedPointee(Value *V) {
    +  auto *C = dyn_cast<ConstantAggregate>(V);
    +  return C && deduceNestedTypeHelper(C, false) != C->getType();
    +}
    +
    +// A nested aggregate or vector member with such pointers gets its own chain,
    +// a vector one of insertelement.

    // Rebuild C as an insertvalue (insertelement for a vector) chain before InsertPt.
    // Members with deduced pointee get their own chain.
    

    maarquitos14 maarquitos14 commented on code on Nov 11, 2026 21:59 UTC
    Code Review
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp:1
    @@ -2391,6 +2453,17 @@ void SPIRVEmitIntrinsicsImpl::insertPtrCastOrAssignTypeInstr(Instruction *I,
               InsertValueInst::getInsertedValueOperandIndex(), B);
         return;
       }
    +  // So must a pointer inserted into a vector.
    +  if (auto *IEI = dyn_cast<InsertElementInst>(I)) {
    +    Value *Op = IEI->getOperand(1);
    +    if (isPointerTy(Op->getType())) {
    +      Type *ElemTy = getPointeeType(IEI->getType()->getElementType());

    Isn't this always nullptr? Couldn't find an input that shows otherwise. As a result, the conditional below is always taking i8 branch. Is that intended?

    maarquitos14 maarquitos14 commented on code on Nov 11, 2026 22:00 UTC
    Code Review
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp:1
    @@ -1808,6 +1811,65 @@ void SPIRVEmitIntrinsicsImpl::insertCompositeAggregateArms(Instruction *I,
       }
     }
     
    +// True for a constant aggregate whose deduced type differs from its LLVM type,
    +// i.e. one with a pointer member of known pointee type.
    +bool SPIRVEmitIntrinsicsImpl::hasDeducedPointee(Value *V) {

    I think the name is misleading, it doesn't really reflect what it does. What about deducedTypeDiffers?

    maarquitos14 maarquitos14 commented on code on Nov 11, 2026 22:03 UTC
    Code Review
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp:1
    @@ -1808,6 +1811,65 @@ void SPIRVEmitIntrinsicsImpl::insertCompositeAggregateArms(Instruction *I,
       }
     }
     
    +// True for a constant aggregate whose deduced type differs from its LLVM type,
    +// i.e. one with a pointer member of known pointee type.
    +bool SPIRVEmitIntrinsicsImpl::hasDeducedPointee(Value *V) {
    +  auto *C = dyn_cast<ConstantAggregate>(V);
    +  return C && deduceNestedTypeHelper(C, false) != C->getType();

    deduceNestedTypeHelper only checks operand 0 for arrays and vectors. Something like [null, @g] is missed.

    maarquitos14 maarquitos14 commented on code on Nov 11, 2026 22:04 UTC
    Code Review
    llvm/test/CodeGen/SPIRV/instructions/select-constant-arm-deduced-pointee.ll:1
    @@ -0,0 +1,68 @@
    +; A constant arm of an aggregate select or PHI holds a pointer whose pointee
    +; type is known (i32 for @g), so the constant is a different SPIR-V type than
    +; the result. The arm is rebuilt with insertvalue, which casts each member to
    +; the result's member type, so all arms have the result's type.
    +; A PHI arm is rebuilt in its incoming block, once even when a switch lists
    +; that block twice. An arm with only null pointers is kept as it is.

    ; A constant select/PHI arm holding @g (i32 pointee) is rebuilt with
    ; OpCompositeInsert in the result type. A PHI arm is built once in its incoming
    ; block, even for duplicate switch edges; a null-only arm stays a constant.
    

    We like to read what the test expects.

    maarquitos14 maarquitos14 commented on code on Nov 11, 2026 22:05 UTC
    Code Review
    llvm/test/CodeGen/SPIRV/instructions/select-constant-arm-nested-aggregate.ll:1
    @@ -0,0 +1,42 @@
    +; A constant arm of an aggregate select or PHI whose pointer sits in a nested
    +; aggregate member: the nested member is rebuilt as its own insertvalue chain.

    ; A pointer in a nested struct of a constant arm: inner and outer structs are
    ; rebuilt with OpCompositeInsert in the result's types.
    

    maarquitos14 maarquitos14 commented on code on Nov 11, 2026 22:06 UTC
    Code Review
    llvm/test/CodeGen/SPIRV/instructions/select-constant-arm-pointer-vector.ll:1
    @@ -0,0 +1,43 @@
    +; A constant arm of an aggregate select or PHI whose pointer of known pointee
    +; type sits in a vector member: the vector is rebuilt as an insertelement chain,
    +; which casts each pointer to the result's element type.

    ; A pointer in a vector member of a constant arm is bitcast to the vector's
    ; element type; the vector and struct are rebuilt with OpCompositeInsert.
    

    maarquitos14 maarquitos14 commented on code on Nov 11, 2026 22:06 UTC
    Code Review
    llvm/test/CodeGen/SPIRV/instructions/insertelement-typed-pointer.ll:1
    @@ -0,0 +1,23 @@
    +; A pointer inserted into a vector of pointers is cast to the vector's element
    +; type, as one inserted into an aggregate is: @g points to i32, the vector
    +; elements to i8.

    ; @g (i32 pointee) inserted into a pointer vector is bitcast to
    ; the vector's element type (pointer to i8).
    

    maarquitos14 maarquitos14 requested changes on Nov 12, 2026 11:21 UTC
    Changes Requested Reviewer

    Thank you for the patch. It fixes the select/PHI cases shown in the tests you added. However, I think this is not directly addressing the root-cause, which IMO is in preprocessCompositeConstants. It gives every constant aggregate its deduced type no matter what the user is: https://github.com/llvm/llvm-project/blob/5ed1f2f3b3633b8a18377fdba569b5d8814786b9/llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp#L1900

    This PR addresses when the user is Select/PHI/freeze, but the mismatch happens also when the constant is returned, passed to a call, or inserted into another aggregate. For example, these are all invalid even with this PR:

    @g = addrspace(1) global i32 0
    %Q = type { ptr addrspace(1), i32 }
    %R = type { %Q, i32 }
    declare void @use(%Q)
    
    define %Q @ret() {
      ret %Q { ptr addrspace(1) @g, i32 1 }
    }
    define void @call() {
      call void @use(%Q { ptr addrspace(1) @g, i32 1 })
      ret void
    }
    define %R @ins(i32 %x) {
      %r = insertvalue %R poison, %Q { ptr addrspace(1) @g, i32 1 }, 0
      %r2 = insertvalue %R %r, i32 %x, 1
      ret %R %r2
    }
    

    Would it make sense to decide this in preprocessCompositeConstants instead? When it lowers a constant aggregate operand of I to spv_const_composite, it knows both the user and the deduced type, so if I isn't an intrinsic and the deduced type differs from the LLVM type, it could build the insertvalue chain there. As a quick check, I added ReturnInst, InsertValueInst and non-intrinsic CallInst to the filter in insertPointerConstantArms and all three cases became valid.

    gonsolo gonsolo commented on Nov 12, 2026 11:37 UTC
    Author

    Would it make sense to decide this in preprocessCompositeConstants instead?

    Yes, that's the better place, thanks. preprocessCompositeConstants now rebuilds such a constant as an insertvalue (insertelement for a vector) chain for every user except intrinsics and extractvalue. extractvalue reads the deduced type, and composite-ptr-member-bitcast.ll relies on that. insertPointerConstantArms is gone. Nested members need no recursion: the chain's insertvalues go back on the worklist, so a nested member with a known pointee gets its own chain. Your ret/call/insertvalue examples are in the new constant-deduced-pointee-users.ll and pass spirv-val.

    This excludes vectors, so a vector-of-pointers select hits the same selectSelect assert

    The same change covers it, and the vector select is in the new test. With #241166 applied, your PHI reproducer passes spirv-val as well.

    Did I not see this before in other PRs you authored? […] Could be factored out to a helper?

    The map is gone. A PHI's chain now goes into the entry block like its other constants, and replaceUsesOfWith gives duplicate switch edges the same value.

    Isn't this always nullptr?

    Yes. A vector's elements are untyped pointers, so it was always i8; it now casts to i8 directly.

    I think the name is misleading, it doesn't really reflect what it does.

    The function is gone; the check is inline now (DeducedTy != AggrConst->getType()).

    deduceNestedTypeHelper only checks operand 0 for arrays and vectors. Something like [null, @g] is missed.

    Fixed: it now deduces from every element. select-constant-arm-array-null-first.ll tests [null, @g]. It's a separate file because a null pointer is uniqued per module, so an earlier function in a shared file could already have given it a pointee.

    I applied the test comment suggestions, with the PHI sentence changed to say the arm is now built in the entry block.

    maarquitos14 maarquitos14 commented on code on Nov 12, 2026 16:59 UTC
    Code Review
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp:1
    @@ -1848,37 +1866,56 @@ void SPIRVEmitIntrinsicsImpl::preprocessCompositeConstants(IRBuilder<> &B) {
                     : B.SetInsertPoint(I);
               BPrepared = true;
             };
    +        PrepareInsert();
    +        Type *DeducedTy = deduceNestedTypeHelper(AggrConst, false);
    +        // A pointer member of known pointee makes the deduced type differ from
    +        // the type a user other than an intrinsic or extractvalue expects.
    +        // Rebuild such a constant as an insertvalue (insertelement for a
    +        // vector) chain, which casts each member to the LLVM type's member
    +        // type.
    +        if (DeducedTy != AggrConst->getType() &&

    I noticed in the existing composite-ptr-member-bitcast.ll test (its CHECK lines don't pin this, so we should probably update it) that ret_nested_aggr now returns a 4-instruction OpCompositeInsert chain instead of the OpConstantComposite it had before, although none of its members has a known pointee. If I read it right, ptr null is uniqued, so once an earlier function uses it (ret_aggr here, or even just ret ptr null) it carries a deduced element type, and every later aggregate constant holding ptr null takes this path. Two identical functions returning { ptr null, i8 1 } get a constant for the first and a chain for the second. The output is still valid, but should a null member count as a known pointee here?

    maarquitos14 maarquitos14 commented on code on Nov 12, 2026 17:02 UTC
    Code Review
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp:1
    @@ -1220,7 +1221,7 @@ Type *SPIRVEmitIntrinsicsImpl::deduceNestedTypeHelper(
           }
         }
       } else if (auto *VecTy = dyn_cast<VectorType>(OrigTy)) {
    -    if (Value *Op = U->getNumOperands() > 0 ? U->getOperand(0) : nullptr) {
    +    for (Value *Op : U->operands()) {

    Thanks for addressing this. Can we have a test for this? I didn't see any. Maybe a <null, @g> variant of @select in select-constant-arm-pointer-vector.ll?

    maarquitos14 maarquitos14 commented on code on Nov 12, 2026 17:04 UTC
    Code Review
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp:1
    @@ -1848,37 +1866,56 @@ void SPIRVEmitIntrinsicsImpl::preprocessCompositeConstants(IRBuilder<> &B) {
                     : B.SetInsertPoint(I);
               BPrepared = true;
             };
    +        PrepareInsert();
    +        Type *DeducedTy = deduceNestedTypeHelper(AggrConst, false);
    +        // A pointer member of known pointee makes the deduced type differ from
    +        // the type a user other than an intrinsic or extractvalue expects.
    +        // Rebuild such a constant as an insertvalue (insertelement for a
    +        // vector) chain, which casts each member to the LLVM type's member
    +        // type.

            // Users other than an intrinsic or extractvalue expect the LLVM type.
            // Rebuild the constant as an insert chain, which casts each member
            // to it.
    

    maarquitos14 maarquitos14 commented on code on Nov 12, 2026 17:07 UTC
    Code Review
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp:1
    @@ -1808,6 +1809,23 @@ void SPIRVEmitIntrinsicsImpl::insertCompositeAggregateArms(Instruction *I,
       }
     }
     
    +// A member of a constant aggregate as it is lowered. addrspacecast(null)
    +// becomes null in the target address space, so that it gets the correct pointer
    +// type. Undef or poison nested in a constant aggregate is not a direct
    +// instruction operand, so preprocessUndefsAndPoisons() misses it; an unlowered
    +// aggregate one would reach IRTranslator as an untranslatable operand.

    // Lower a constant aggregate member to null in the target address space
    // if it's `addrspacecast(null)`, and nested `undef/poison` because they're
    // missed in `preprocessUndefsAndPoisons()`.
    

    maarquitos14 maarquitos14 commented on code on Nov 12, 2026 17:08 UTC
    Code Review
    llvm/test/CodeGen/SPIRV/instructions/constant-deduced-pointee-users.ll:1
    @@ -0,0 +1,65 @@
    +; A constant holding @g (i32 pointee) is rebuilt with OpCompositeInsert in its
    +; LLVM type for any user but an intrinsic or extractvalue: a return, a call
    +; argument, an insertvalue or a vector select.

    ; A constant holding @g (i32 pointee) is rebuilt with OpCompositeInsert in its
    ; LLVM type for any user other than an intrinsic or extractvalue.
    

    gonsolo gonsolo commented on code on Nov 12, 2026 17:22 UTC
    Code Review
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp:1
    @@ -1848,37 +1866,56 @@ void SPIRVEmitIntrinsicsImpl::preprocessCompositeConstants(IRBuilder<> &B) {
                     : B.SetInsertPoint(I);
               BPrepared = true;
             };
    +        PrepareInsert();
    +        Type *DeducedTy = deduceNestedTypeHelper(AggrConst, false);
    +        // A pointer member of known pointee makes the deduced type differ from
    +        // the type a user other than an intrinsic or extractvalue expects.
    +        // Rebuild such a constant as an insertvalue (insertelement for a
    +        // vector) chain, which casts each member to the LLVM type's member
    +        // type.
    +        if (DeducedTy != AggrConst->getType() &&

    If I read it right, ptr null is uniqued, so once an earlier function uses it (ret_aggr here, or even just ret ptr null) it carries a deduced element type, and every later aggregate constant holding ptr null takes this path. [...] should a null member count as a known pointee here?

    You read it right, and no, it shouldn't. deduceNestedTypeHelper now skips a ConstantPointerNull member (88cafcded700), so ret_nested_aggr is an OpConstantComposite again regardless of what used the null before. I pinned that in composite-ptr-member-bitcast.ll; the check fails without the fix. While there, the struct, array and vector branches share one lambda for the member deduction.

    gonsolo gonsolo commented on code on Nov 12, 2026 17:22 UTC
    Code Review
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp:1
    @@ -1220,7 +1221,7 @@ Type *SPIRVEmitIntrinsicsImpl::deduceNestedTypeHelper(
           }
         }
       } else if (auto *VecTy = dyn_cast<VectorType>(OrigTy)) {
    -    if (Value *Op = U->getNumOperands() > 0 ? U->getOperand(0) : nullptr) {
    +    for (Value *Op : U->operands()) {

    Can we have a test for this? I didn't see any. Maybe a <null, @g> variant of @select in select-constant-arm-pointer-vector.ll?

    Added @select_null_first there (696daa0483c2): with the null first and nulls no longer contributing a pointee, only @g gives the element type, so it checks the deduction looks past element 0. The array case is in select-constant-arm-array-null-first.ll.

    gonsolo gonsolo commented on code on Nov 12, 2026 17:22 UTC
    Code Review
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp:1
    @@ -1848,37 +1866,56 @@ void SPIRVEmitIntrinsicsImpl::preprocessCompositeConstants(IRBuilder<> &B) {
                     : B.SetInsertPoint(I);
               BPrepared = true;
             };
    +        PrepareInsert();
    +        Type *DeducedTy = deduceNestedTypeHelper(AggrConst, false);
    +        // A pointer member of known pointee makes the deduced type differ from
    +        // the type a user other than an intrinsic or extractvalue expects.
    +        // Rebuild such a constant as an insertvalue (insertelement for a
    +        // vector) chain, which casts each member to the LLVM type's member
    +        // type.

    >         // Users other than an intrinsic or extractvalue expect the LLVM type.
    >         // Rebuild the constant as an insert chain, which casts each member
    >         // to it.
    > 

    Done.

    gonsolo gonsolo commented on code on Nov 12, 2026 17:22 UTC
    Code Review
    llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp:1
    @@ -1808,6 +1809,23 @@ void SPIRVEmitIntrinsicsImpl::insertCompositeAggregateArms(Instruction *I,
       }
     }
     
    +// A member of a constant aggregate as it is lowered. addrspacecast(null)
    +// becomes null in the target address space, so that it gets the correct pointer
    +// type. Undef or poison nested in a constant aggregate is not a direct
    +// instruction operand, so preprocessUndefsAndPoisons() misses it; an unlowered
    +// aggregate one would reach IRTranslator as an untranslatable operand.

    > // Lower a constant aggregate member to null in the target address space
    > // if it's `addrspacecast(null)`, and nested `undef/poison` because they're
    > // missed in `preprocessUndefsAndPoisons()`.
    > 

    Done.

    gonsolo gonsolo commented on code on Nov 12, 2026 17:22 UTC
    Code Review
    llvm/test/CodeGen/SPIRV/instructions/constant-deduced-pointee-users.ll:1
    @@ -0,0 +1,65 @@
    +; A constant holding @g (i32 pointee) is rebuilt with OpCompositeInsert in its
    +; LLVM type for any user but an intrinsic or extractvalue: a return, a call
    +; argument, an insertvalue or a vector select.

    > ; A constant holding @g (i32 pointee) is rebuilt with OpCompositeInsert in its
    > ; LLVM type for any user other than an intrinsic or extractvalue.
    > 

    Done.

    maarquitos14 maarquitos14 approved these changes on Nov 17, 2026 16:30 UTC
    Approved Reviewer

    Approved these changes.

    aobolensk aobolensk approved these changes on Nov 18, 2026 07:22 UTC
    Approved Reviewer

    Approved these changes.

    gonsolo gonsolo commented on Nov 23, 2026 09:30 UTC
    Author

    Thanks for the reviews! I don't have commit access; could one of you merge this?

    Reviewers
    Assignees
    gonsolo gonsolo
    Labels
    risk: low confidence: 75.0% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 54.1% (MEDIUM) · Higher = larger blast radius
    54.1%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 75.0% · Lower = rushed or shallow review
    75.0%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 13.6% · Safe to merge
    13.6%