← Back to Pull requests

Reboot TypeGeneralizing to use SubtypingDiscoverer #9263

Open
kripken opened this pull request with 2266 lines diff across 6 files
View on GitHub
kripken kripken commented on Oct 14, 2026 22:10 UTC
Author

Now that we have a "late opts" stage, we can do things like generalize
types. This initial PR rewrites the pass to use the SubtypingDiscoverer
logic that was added since, and which makes the pass a lot
simpler (about half the length).

More work is needed to get this fuzzed etc., but just this rewrite
already removes some TODOs and asserts that are no longer relevant.
The pass can now run on a large Kotlin testcase without erroring, and
it shrinks the size there by 0.25% (not much yet, but after adding cast
generalization, perhaps more..?)

All old tests pass like before. (One new test is added, to handle a
crash that happened during this porting process.)

This is basically NFC, except that removing the old asserts mean
that more things can run.

Diff: 2266 lines (+1348 / -918) across 6 files Reviewer: tlively Review duration: 10160m
All Vouch review confidence checks passed
Residual risk 0.05 = Change Risk (0.50) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.50 · 2266 lines diff across 6 files
0.50
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.87 · 5 substantive comment(s)
0.87
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
89%
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.400
Real PR Conversation Timeline
33 items
tlively tlively commented on code on Oct 15, 2026 00:52 UTC
Code Review
src/ir/subtype-exprs.h:1
@@ -285,7 +288,9 @@ struct SubtypingDiscoverer : public OverriddenVisitor<SubType> {
     }
   }
   void visitRethrow(Rethrow* curr) {}
-  void visitThrowRef(ThrowRef* curr) {}
+  void visitThrowRef(ThrowRef* curr) {
+    self()->noteNonFlowSubtype(curr->exnref, Type(HeapType::exn, Nullable));

Why "non-flow" here? The ref does flow into the throw and out of a later catch.

tlively tlively commented on code on Oct 15, 2026 00:55 UTC
Code Review
src/ir/subtype-exprs.h:1
@@ -438,7 +451,14 @@ struct SubtypingDiscoverer : public OverriddenVisitor<SubType> {
   }
   void visitArrayLoad(ArrayLoad* curr) {}
   void visitArrayStore(ArrayStore* curr) {}
-  void visitArrayLen(ArrayLen* curr) {}
+  void visitArrayLen(ArrayLen* curr) {
+    auto share = Unshared;
+    if (curr->ref->type.isRef() && curr->ref->type.getHeapType().isShared()) {
+      share = Shared;
+    }
+    self()->noteNonFlowSubtype(

Again, why non-flow? Previously the only use of noteNonFlowSubtype was for ref.eq. If all these new uses of noteNonFlowSubtype are correct, then I suspect there are many more places that should be using it.

tlively tlively commented on code on Oct 15, 2026 01:11 UTC
Code Review
src/ir/subtype-exprs.h:1
@@ -345,7 +350,15 @@ struct SubtypingDiscoverer : public OverriddenVisitor<SubType> {
                         self()->findBreakTarget(curr->name));
   }
   void visitStructNew(StructNew* curr) {
-    if (!curr->type.isStruct() || curr->isWithDefault()) {
+    if (!curr->type.isStruct()) {
+      return;
+    }
+    if (curr->desc) {
+      auto descType = curr->type.getHeapType().getDescriptorType();
+      assert(descType);
+      self()->noteSubtype(curr->desc, Type(*descType, Nullable, Exact));
+    }

If visitation order matters, this should come after visiting the fields. (And even if visitation order doesn't matter now, it would probably be better to be consistent about it.)

tlively tlively commented on code on Oct 15, 2026 01:19 UTC
Code Review
test/lit/passes/type-generalizing.wast:1
@@ -1639,3 +1639,36 @@
   )
  )
 )
+
+(module
+ ;; CHECK:      (type $inner-super (sub (struct)))
+ (type $inner-super (sub (struct)))
+ ;; CHECK:      (type $inner-sub (sub $inner-super (struct (field i32))))
+ (type $inner-sub (sub $inner-super (struct (field i32))))
+ ;; CHECK:      (type $outer-super (sub (struct (field (ref $inner-super)))))
+ (type $outer-super (sub (struct (field (ref $inner-super)))))
+ ;; CHECK:      (type $outer-sub (sub $outer-super (struct (field (ref $inner-sub)))))
+ (type $outer-sub (sub $outer-super (struct (field (ref $inner-sub)))))
+
+ ;; CHECK:      (type $4 (func (result i32)))
+
+ ;; CHECK:      (func $struct-get-non-null-field (type $4) (result i32)
+ ;; CHECK-NEXT:  (local $var (ref null $outer-sub))
+ ;; CHECK-NEXT:  (struct.get $inner-sub 0
+ ;; CHECK-NEXT:   (struct.get $outer-sub 0
+ ;; CHECK-NEXT:    (local.get $var)
+ ;; CHECK-NEXT:   )
+ ;; CHECK-NEXT:  )
+ ;; CHECK-NEXT: )
+ (func $struct-get-non-null-field (result i32)
+  (local $var (ref null $outer-sub))
+  ;; The outer struct.get requires (ref null $inner-sub), which is nullable.
+  ;; $outer-super's field 0 has non-nullable type (ref $inner-super), which is
+  ;; incomparable with (ref null $inner-sub); we must still stop at $outer-sub.

  ;; incomparable with the i32 field of $inner-sub; we must still stop at $outer-sub.

Also the naming could be clearer here; "outer" and "inner" have opposing meanings when applied to the struct layout and IR layout.

tlively tlively commented on code on Oct 15, 2026 01:20 UTC
Code Review
test/passes/translate-to-fuzz_all-features_metrics_noprint.txt:1

Is this change related?

tlively tlively commented on code on Oct 15, 2026 01:24 UTC
Code Review
src/passes/TypeGeneralizing.cpp:1

It's probably worth a TODO about additional things that are not handled optimally by SubtypeDiscoverer because it assumes the result types cannot be generalized: specifically ref.as_non_null, br_on_null, publish, br_if, and maybe a couple others.

tlively tlively commented on Oct 15, 2026 01:25 UTC
Reviewer

Some initial comments before I get into the meat of the new implementation.

Test coverage doesn't look great, especially for the new changes in type-generalizing.

  Metric       Covered / Total        Details
  ------------ ---------------------- ----------------------------------
  Lines        243 / 326 (74.5%)      Executable lines in diff
  Regions      195 / 232 (84.1%)      Sub-line / block AST regions in diff
  Branches     131 / 170 (77.1%)      True/False branch outcomes in diff
  MC/DC        6 / 21 (28.6%)         Condition independence pairs in diff
  Functions    28 / 103 (27.2%)       Modified functions called >= 1x

tlively tlively commented on code on Oct 15, 2026 01:30 UTC
Code Review
src/ir/subtype-exprs.h:1
@@ -345,7 +350,15 @@ struct SubtypingDiscoverer : public OverriddenVisitor<SubType> {
                         self()->findBreakTarget(curr->name));
   }
   void visitStructNew(StructNew* curr) {
-    if (!curr->type.isStruct() || curr->isWithDefault()) {
+    if (!curr->type.isStruct()) {
+      return;
+    }
+    if (curr->desc) {
+      auto descType = curr->type.getHeapType().getDescriptorType();
+      assert(descType);
+      self()->noteSubtype(curr->desc, Type(*descType, Nullable, Exact));
+    }

BrOn and RefCast are also missing descriptor handling.

tlively tlively commented on Oct 15, 2026 01:33 UTC
Contributor

ChildTyper would probably be a better utility to use here because it does not assume the parent expression's type cannot be generalized.

(In fact, ChildTyper is a better fit for all current users of SubtypingDiscoverer except for Unsubtyping, which is where SubtypingDiscoverer originally came from.)

tlively tlively commented on Oct 15, 2026 03:53 UTC
Contributor

Actually, ChildTyper is not enough because it does not know about the required upper bounds on the parent expression's type, which means it cannot reflect those bounds in the constraints it reports for child types. We would need to build a full principal types utility (built on top of ChildTyper) to let us propagate type contraints from parents to children. I'll consider that as a follow-on project rather than holding up this PR.

kripken kripken commented on code on Oct 15, 2026 16:18 UTC
Code Review
src/ir/subtype-exprs.h:1
@@ -285,7 +288,9 @@ struct SubtypingDiscoverer : public OverriddenVisitor<SubType> {
     }
   }
   void visitRethrow(Rethrow* curr) {}
-  void visitThrowRef(ThrowRef* curr) {}
+  void visitThrowRef(ThrowRef* curr) {
+    self()->noteNonFlowSubtype(curr->exnref, Type(HeapType::exn, Nullable));

Yes, but it doesn't flow out of this expression. Reading the docs on top, I guess this can be ambiguous. I can reword that?

kripken kripken commented on code on Oct 15, 2026 16:19 UTC
Code Review
test/passes/translate-to-fuzz_all-features_metrics_noprint.txt:1

Yes. The fuzzer uses SubtypingDiscoverer internally (to find mutations, of the proper types). So improvements here lead to fuzzer improvements.

kripken kripken commented on code on Oct 15, 2026 16:22 UTC
Code Review
src/ir/subtype-exprs.h:1
@@ -438,7 +451,14 @@ struct SubtypingDiscoverer : public OverriddenVisitor<SubType> {
   }
   void visitArrayLoad(ArrayLoad* curr) {}
   void visitArrayStore(ArrayStore* curr) {}
-  void visitArrayLen(ArrayLen* curr) {}
+  void visitArrayLen(ArrayLen* curr) {
+    auto share = Unshared;
+    if (curr->ref->type.isRef() && curr->ref->type.getHeapType().isShared()) {
+      share = Shared;
+    }
+    self()->noteNonFlowSubtype(

I think this is correct (for the reasons I mentioned above) but yes, there might be more places it makes sense to use. I didn't try to find them all in this PR - would make more sense in a place where we can cover them more easily with tests, though I don't know that we have a better pass, actually...

kripken kripken commented on code on Oct 15, 2026 16:45 UTC
Code Review
src/ir/subtype-exprs.h:1
@@ -438,7 +451,14 @@ struct SubtypingDiscoverer : public OverriddenVisitor<SubType> {
   }
   void visitArrayLoad(ArrayLoad* curr) {}
   void visitArrayStore(ArrayStore* curr) {}
-  void visitArrayLen(ArrayLen* curr) {}
+  void visitArrayLen(ArrayLen* curr) {
+    auto share = Unshared;
+    if (curr->ref->type.isRef() && curr->ref->type.getHeapType().isShared()) {
+      share = Shared;
+    }
+    self()->noteNonFlowSubtype(

I can remove the ones not directly needed for tests in this PR if you prefer, though e.g. the String ones seem obvious?

kripken kripken commented on code on Oct 15, 2026 16:47 UTC
Code Review
src/ir/subtype-exprs.h:1
@@ -438,7 +451,14 @@ struct SubtypingDiscoverer : public OverriddenVisitor<SubType> {
   }
   void visitArrayLoad(ArrayLoad* curr) {}
   void visitArrayStore(ArrayStore* curr) {}
-  void visitArrayLen(ArrayLen* curr) {}
+  void visitArrayLen(ArrayLen* curr) {
+    auto share = Unshared;
+    if (curr->ref->type.isRef() && curr->ref->type.getHeapType().isShared()) {
+      share = Shared;
+    }
+    self()->noteNonFlowSubtype(

(Aside from them, the ThrowRef one can also be removed from this PR, it looks like.)

kripken kripken commented on code on Oct 15, 2026 16:48 UTC
Code Review
src/ir/subtype-exprs.h:1
@@ -345,7 +350,15 @@ struct SubtypingDiscoverer : public OverriddenVisitor<SubType> {
                         self()->findBreakTarget(curr->name));
   }
   void visitStructNew(StructNew* curr) {
-    if (!curr->type.isStruct() || curr->isWithDefault()) {
+    if (!curr->type.isStruct()) {
+      return;
+    }
+    if (curr->desc) {
+      auto descType = curr->type.getHeapType().getDescriptorType();
+      assert(descType);
+      self()->noteSubtype(curr->desc, Type(*descType, Nullable, Exact));
+    }

The order doesn't matter, but I agree it is nice to follow. Fixed.

kripken kripken commented on code on Oct 15, 2026 16:51 UTC
Code Review
src/ir/subtype-exprs.h:1
@@ -345,7 +350,15 @@ struct SubtypingDiscoverer : public OverriddenVisitor<SubType> {
                         self()->findBreakTarget(curr->name));
   }
   void visitStructNew(StructNew* curr) {
-    if (!curr->type.isStruct() || curr->isWithDefault()) {
+    if (!curr->type.isStruct()) {
+      return;
+    }
+    if (curr->desc) {
+      auto descType = curr->type.getHeapType().getDescriptorType();
+      assert(descType);
+      self()->noteSubtype(curr->desc, Type(*descType, Nullable, Exact));
+    }

BrOn and RefCast are also missing descriptor handling.

How about leaving those for later + tests? This PR is mainly focused on the reboot, but not adding new functionality.

kripken kripken commented on code on Oct 15, 2026 16:57 UTC
Code Review
test/lit/passes/type-generalizing.wast:1
@@ -1639,3 +1639,36 @@
   )
  )
 )
+
+(module
+ ;; CHECK:      (type $inner-super (sub (struct)))
+ (type $inner-super (sub (struct)))
+ ;; CHECK:      (type $inner-sub (sub $inner-super (struct (field i32))))
+ (type $inner-sub (sub $inner-super (struct (field i32))))
+ ;; CHECK:      (type $outer-super (sub (struct (field (ref $inner-super)))))
+ (type $outer-super (sub (struct (field (ref $inner-super)))))
+ ;; CHECK:      (type $outer-sub (sub $outer-super (struct (field (ref $inner-sub)))))
+ (type $outer-sub (sub $outer-super (struct (field (ref $inner-sub)))))
+
+ ;; CHECK:      (type $4 (func (result i32)))
+
+ ;; CHECK:      (func $struct-get-non-null-field (type $4) (result i32)
+ ;; CHECK-NEXT:  (local $var (ref null $outer-sub))
+ ;; CHECK-NEXT:  (struct.get $inner-sub 0
+ ;; CHECK-NEXT:   (struct.get $outer-sub 0
+ ;; CHECK-NEXT:    (local.get $var)
+ ;; CHECK-NEXT:   )
+ ;; CHECK-NEXT:  )
+ ;; CHECK-NEXT: )
+ (func $struct-get-non-null-field (result i32)
+  (local $var (ref null $outer-sub))
+  ;; The outer struct.get requires (ref null $inner-sub), which is nullable.
+  ;; $outer-super's field 0 has non-nullable type (ref $inner-super), which is
+  ;; incomparable with (ref null $inner-sub); we must still stop at $outer-sub.

Ok, renamed the vars, and completely rewrote the comment.

kripken kripken commented on code on Oct 15, 2026 17:02 UTC
Code Review
src/passes/TypeGeneralizing.cpp:1

Added a TODO

kripken kripken commented on Oct 15, 2026 18:29 UTC
Author

Commit pushed with comprehensive tests for new functionality in this PR.

The one thing I did not do here is verify they are new and not previously covered (as I didn't write the old ones originally, so I'd need to do a lot of work to match things up). But I had Gemini check that. In the worst case, if it got it wrong, we might be adding some small amount of overlap.

tlively tlively commented on Oct 16, 2026 20:56 UTC
Contributor

Thanks, that sounds like the right trade off to me.

tlively tlively commented on code on Oct 16, 2026 20:57 UTC
Code Review
src/ir/subtype-exprs.h:1
@@ -285,7 +288,9 @@ struct SubtypingDiscoverer : public OverriddenVisitor<SubType> {
     }
   }
   void visitRethrow(Rethrow* curr) {}
-  void visitThrowRef(ThrowRef* curr) {}
+  void visitThrowRef(ThrowRef* curr) {
+    self()->noteNonFlowSubtype(curr->exnref, Type(HeapType::exn, Nullable));

No need. It's probably worth going through later and using noteNonFlowSubtype in most other places.

tlively tlively commented on code on Oct 16, 2026 22:01 UTC
Code Review
src/passes/TypeGeneralizing.cpp:1
@@ -14,905 +14,381 @@
  * limitations under the License.
  */
 
-#include "analysis/cfg.h"
-#include "analysis/lattices/inverted.h"
-#include "analysis/lattices/shared.h"
-#include "analysis/lattices/stack.h"
-#include "analysis/lattices/tuple.h"
-#include "analysis/lattices/valtype.h"
-#include "analysis/lattices/vector.h"
-#include "analysis/monotone-analyzer.h"
+//
+// Generalize the types of locals as much as possible, both to eliminate
+// unnecessarily refined types from the type section and (TODO) to weaken casts
+// that cast to unnecessarily refined types. If the casts are weakened enough,
+// they will be able to be removed by OptimizeInstructions.
+//
+
+#include <optional>
+#include <unordered_map>
+#include <variant>
+#include <vector>
+
+#include "ir/glbs.h"
+#include "ir/subtype-exprs.h"
 #include "ir/utils.h"
 #include "pass.h"
 #include "wasm-traversal.h"
 #include "wasm.h"
 
-#ifndef TYPE_GENERALIZING_DEBUG
-#define TYPE_GENERALIZING_DEBUG 0
-#endif
-
-#if TYPE_GENERALIZING_DEBUG
-#define DBG(statement) statement
-#else
-#define DBG(statement)
-#endif
-
-// Generalize the types of program locations as much as possible, both to
-// eliminate unnecessarily refined types from the type section and (TODO) to
-// weaken casts that cast to unnecessarily refined types. If the casts are
-// weakened enough, they will be able to be removed by OptimizeInstructions.
-//
-// Perform a backward analysis tracking requirements on the types of program
-// locations (currently just locals and stack values) to discover how much the
-// type of each location can be generalized without breaking validation or
-// changing program behavior.
-
 namespace wasm {
 
 namespace {
 
-using namespace analysis;
-
-// We will learn stricter and stricter requirements as we perform the analysis,
-// so more specific types need to be higher up the lattice.
-using TypeRequirement = Inverted<ValType>;
-
-// Record a type requirement for each local variable. Shared the requirements
-// across basic blocks.
-using LocalTypeRequirements = SharedPath<Vector<TypeRequirement>>;
-
-// The type requirements for each reference-typed value on the stack at a
-// particular location.
-using ValueStackTypeRequirements = Stack<TypeRequirement>;
-
-// The full lattice used for the analysis.
-using StateLattice =
-  analysis::Tuple<LocalTypeRequirements, ValueStackTypeRequirements>;
-
-// Equip the state lattice with helpful accessors.
-struct State : StateLattice {
-  using Element = StateLattice::Element;
-
-  static constexpr int LocalsIndex = 0;
-  static constexpr int StackIndex = 1;
-
-  State(Function* func)
-    : StateLattice{SharedPath{initLocals(func)}, initStack()} {}
-
-  void push(Element& elem, Type type) const noexcept {
-    stackLattice().push(stack(elem), std::move(type));
-  }
-
-  Type pop(Element& elem) const noexcept {
-    return stackLattice().pop(stack(elem));
-  }
-
-  void clearStack(Element& elem) const noexcept {
-    stack(elem) = stackLattice().getBottom();
-  }
-
-  const std::vector<Type>& getLocals(Element& elem) const noexcept {
-    return *locals(elem);
-  }
-
-  const std::vector<Type>& getLocals() const noexcept {
-    return *locals(getBottom());
-  }
-
-  Type getLocal(Element& elem, Index i) const noexcept {
-    return getLocals(elem)[i];
-  }
-
-  bool updateLocal(Element& elem, Index i, Type type) const noexcept {
-    return localsLattice().join(
-      locals(elem),
-      Vector<TypeRequirement>::SingletonElement(i, std::move(type)));
-  }
-
-private:
-  static LocalTypeRequirements initLocals(Function* func) noexcept {
-    return SharedPath{Vector{Inverted{ValType{}}, func->getNumLocals()}};
-  }
-
-  static ValueStackTypeRequirements initStack() noexcept {
-    return Stack{Inverted{ValType{}}};
-  }
-
-  const LocalTypeRequirements& localsLattice() const noexcept {
-    return std::get<LocalsIndex>(lattices);
-  }
-
-  const ValueStackTypeRequirements& stackLattice() const noexcept {
-    return std::get<StackIndex>(lattices);
-  }
-
-  typename LocalTypeRequirements::Element&
-  locals(Element& elem) const noexcept {
-    return std::get<LocalsIndex>(elem);
-  }
-
-  const typename LocalTypeRequirements::Element&
-  locals(const Element& elem) const noexcept {
-    return std::get<LocalsIndex>(elem);
-  }
-
-  typename ValueStackTypeRequirements::Element&
-  stack(Element& elem) const noexcept {
-    return std::get<StackIndex>(elem);
-  }
-
-  const typename ValueStackTypeRequirements::Element&
-  stack(const Element& elem) const noexcept {
-    return std::get<StackIndex>(elem);
-  }
-};
-
-struct TransferFn : OverriddenVisitor<TransferFn> {
-  Module& wasm;
-  Function* func;
-  State lattice;
-  typename State::Element* state = nullptr;
-
-  // For each local, the set of blocks we may need to re-analyze when we update
-  // the constraint on the local.
-  std::vector<std::vector<const BasicBlock*>> localDependents;
-
-  // The set of basic blocks that may depend on the result of the current
-  // transfer.
-  std::unordered_set<const BasicBlock*> currDependents;
-
-  TransferFn(Module& wasm, Function* func, CFG& cfg)
-    : wasm(wasm), func(func), lattice(func),
-      localDependents(func->getNumLocals()) {
-    // Initialize `localDependents`. Any block containing a `local.set l` may
-    // need to be re-analyzed whenever the constraint on `l` is updated.
-    auto numLocals = func->getNumLocals();
-    std::vector<std::unordered_set<const BasicBlock*>> dependentSets(numLocals);
-    for (const auto& bb : cfg) {
-      for (const auto* inst : bb) {
-        if (auto set = inst->dynCast<LocalSet>()) {
-          dependentSets[set->index].insert(&bb);
-        }
+// Find the most general supertype of a signature type that does not change
+// parameter types (which are contravariant and would restrict argument
+// generalization) and whose result type satisfies `resultReq`, if any.
+HeapType generalizeCallRefTarget(HeapType sigType,
+                                 std::optional<Type> resultReq = std::nullopt) {
+  auto sig = sigType.getSignature();
+  auto numParams = sig.params.size();
+  auto targetReq = sigType;
+  while (true) {
+    auto candidateReq = targetReq.getDeclaredSuperType();
+    if (!candidateReq) {
+      break;
+    }
+    auto candidateSig = candidateReq->getSignature();
+    if (resultReq && !Type::isSubType(candidateSig.results, *resultReq)) {
+      break;
+    }
+    for (size_t i = 0; i < numParams; ++i) {
+      if (candidateSig.params[i] != sig.params[i]) {
+        return targetReq;
       }
     }
-    for (size_t i = 0, n = dependentSets.size(); i < n; ++i) {
-      localDependents[i] = std::vector<const BasicBlock*>(
-        dependentSets[i].begin(), dependentSets[i].end());
-    }
+    targetReq = *candidateReq;
   }
+  return targetReq;
+}
 
-  Type pop() noexcept { return lattice.pop(*state); }
-  void push(Type type) noexcept { lattice.push(*state, type); }
-  void clearStack() noexcept { lattice.clearStack(*state); }
-  Type getLocal(Index i) noexcept { return lattice.getLocal(*state, i); }
-  void updateLocal(Index i, Type type) noexcept {
-    if (lattice.updateLocal(*state, i, type)) {
-      currDependents.insert(localDependents[i].begin(),
-                            localDependents[i].end());
+// Find the most general supertype of a struct type that still has a field at
+// `index` whose type satisfies `reqFieldType`, if any.
+HeapType generalizeStructType(HeapType type,
+                              Index index,
+                              std::optional<Type> reqFieldType = std::nullopt) {
+  while (true) {
+    auto candidateType = type.getDeclaredSuperType();
+    if (!candidateType) {
+      break;
     }
-  }
-
-  void dumpState() {
-#if TYPE_GENERALIZING_DEBUG
-    std::cerr << "locals: ";
-    for (size_t i = 0, n = lattice.getLocals(*state).size(); i < n; ++i) {
-      if (i != 0) {
-        std::cerr << ", ";
-      }
-      std::cerr << getLocal(i);
+    const auto& candidateFields = candidateType->getStruct().fields;
+    if (candidateFields.size() <= index) {
+      break;
     }
-    std::cerr << "\nstack: ";
-    auto& stack = std::get<1>(*state);
-    for (size_t i = 0, n = stack.size(); i < n; ++i) {
-      if (i != 0) {
-        std::cerr << ", ";
+    if (reqFieldType) {
+      auto candidateFieldType = candidateFields[index].type;
+      if (!Type::isSubType(candidateFieldType, *reqFieldType)) {
+        break;
       }
-      std::cerr << stack[i];
     }
-    std::cerr << "\n";
-#endif // TYPE_GENERALIZING_DEBUG
+    type = *candidateType;
   }
+  return type;
+}
 
-  std::unordered_set<const BasicBlock*>
-  transfer(const BasicBlock& bb, typename State::Element& elem) noexcept {
-    DBG(std::cerr << "transferring bb " << bb.getIndex() << "\n");
-    state = &elem;
-
-    // This is a backward analysis: The constraints on a type depend on how it
-    // will be used in the future. Traverse the basic block in reverse and
-    // return the predecessors as the dependent blocks.
-    assert(currDependents.empty());
-    const auto& preds = bb.preds();
-    currDependents.insert(preds.begin(), preds.end());
-
-    dumpState();
-    if (bb.isExit()) {
-      DBG(std::cerr << "visiting exit\n");
-      visitFunctionExit();
-      dumpState();
-    }
-    for (auto it = bb.rbegin(); it != bb.rend(); ++it) {
-      DBG(std::cerr << "visiting " << ShallowExpression{*it} << "\n");
-      visit(*it);
-      dumpState();
-    }
-    if (bb.isEntry()) {
-      DBG(std::cerr << "visiting entry\n");
-      visitFunctionEntry();
-      dumpState();
-    }
-    DBG(std::cerr << "\n");
-
-    state = nullptr;
-
-    // Return the blocks that may need to be re-analyzed.
-    return std::move(currDependents);
-  }
-
-  void visitFunctionExit() {
-    // We cannot change the types of results. Push a requirement that the stack
-    // end up with the correct type.
-    auto result = func->getResults();
-    if (result.isRef()) {
-      push(result);
+// Find the most general supertype of an array type whose element type satisfies
+// `reqElemType`, if any.
+HeapType generalizeArrayType(HeapType type,
+                             std::optional<Type> reqElemType = std::nullopt) {
+  while (true) {
+    auto candidateType = type.getDeclaredSuperType();
+    if (!candidateType) {
+      break;
     }
-  }
-
-  void visitFunctionEntry() {
-    // We cannot change the types of parameters, so require that they have their
-    // original types.
-    Index i = 0;
-    Index numParams = func->getNumParams();
-    Index numLocals = func->getNumLocals();
-    for (; i < numParams; ++i) {
-      updateLocal(i, func->getLocalType(i));
-    }
-    // We also cannot change the types of any other non-ref locals. For
-    // reference-typed locals, we cannot generalize beyond their top type.
-    for (Index i = numParams; i < numLocals; ++i) {
-      auto type = func->getLocalType(i);
-      // TODO: Support optimizing tuple locals.
-      if (type.isRef()) {
-        updateLocal(i, Type(type.getHeapType().getTop(), Nullable));
-      } else {
-        updateLocal(i, type);
+    if (reqElemType) {
+      auto candidateElemType = candidateType->getArray().element.type;
+      if (!Type::isSubType(candidateElemType, *reqElemType)) {
+        break;
       }
     }
+    type = *candidateType;
   }
+  return type;
+}
 
-  void visitNop(Nop* curr) {}
-  void visitBlock(Block* curr) {}
-  void visitIf(If* curr) {}
-  void visitLoop(Loop* curr) {}
-
-  void visitBreak(Break* curr) {
-    if (curr->condition) {
-      // `br_if` pops everything but the sent value off the stack if the branch
-      // is taken, but if the branch is not taken, it only pops the condition.
-      // We must therefore propagate all requirements from the fallthrough
-      // successor but only the requirements for the sent value, if any, from
-      // the branch successor. We don't have any way to differentiate between
-      // requirements received from the two successors, however, so we cannot
-      // yet do anything correct here!
-      //
-      // Here is a sample program that would break if we tried to conservatively
-      // preserve the join of the requirements from both successors:
-      //
-      // (module
-      //  (func $func_any (param funcref anyref)
-      //   (unreachable)
-      //  )
-      //
-      //  (func $extern_any-any (param externref anyref) (result anyref)
-      //   (unreachable)
-      //  )
-      //
-      //  (func $br-if-bad
-      //   (local $bang externref)
-      //   (call $func_any ;; 2. Requires [func, any]
-      //    (ref.null nofunc)
-      //    (block $l (result anyref)
-      //     (call $extern_any-any ;; 1. Requires [extern, any]
-      //      (local.get $bang)
-      //      (br_if $l ;; 3. After join, requires [unreachable, any]
-      //       (ref.null none)
-      //       (i32.const 0)
-      //      )
-      //     )
-      //    )
-      //   )
-      //  )
-      // )
-      //
-      // To fix this, we need to insert an extra basic block encompassing the
-      // liminal space between where the br_if determines it should take the
-      // branch and when control arrives at the branch target. This is when the
-      // extra values are popped off the stack.
-      WASM_UNREACHABLE("TODO");
-    } else {
-      // `br` pops everything but the sent value off the stack, so do not
-      // require anything of values on the stack except for that sent value, if
-      // it exists.
-      if (curr->value && curr->value->type.isRef()) {
-        auto type = pop();
-        clearStack();
-        push(type);
-      } else {
-        // No sent value. Do not require anything.
-        clearStack();
-      }
-    }
-  }
+// Use SubtypingDiscoverer to find all subtyping constraints on expressions and
+// locals, and computes the greatest lower bound (GLB) of the required
+// supertypes for each local so that each local is given the least-refined valid
+// type.
+//
+// TODO: handle ref.as_non_null, br_on_null, publish, br_if, etc. better: we do
+//       not need to consider their results fixed.
+struct Generalizer
+  : public ControlFlowWalker<Generalizer, SubtypingDiscoverer<Generalizer>> {
+  Function* func;
 
-  void visitSwitch(Switch* curr) {
-    // Just like `br`, do not require anything of the values on the stack except
-    // for the sent value, if it exists.
-    if (curr->value && curr->value->type.isRef()) {
-      auto type = pop();
-      clearStack();
-      push(type);
-    } else {
-      clearStack();
-    }
-  }
+  // For each expression and local, track the GLB of all types it is required to
+  // be a subtype of.
+  std::unordered_map<Expression*, GLBFinder> exprGLBs;
+  std::vector<GLBFinder> localGLBs;
 
-  template<typename T> void handleCall(T* curr, Type params) {
-    if (curr->type.isRef()) {
-      pop();
-    }
-    for (auto param : params) {
-      // Cannot generalize beyond param types without interprocedural analysis.
-      if (param.isRef()) {
-        push(param);
-      }
-    }
-  }
+  // Map from an expression to the sub-expressions whose types flow out of it
+  // (or depend on its required output type, as in RefAs).
+  std::unordered_map<Expression*, std::vector<Expression*>> exprSubs;
 
-  void visitCall(Call* curr) {
-    handleCall(curr, wasm.getFunction(curr->target)->getParams());
-  }
+  // For each local, the values assigned to it via local.set / local.tee.
+  std::vector<std::vector<Expression*>> localSetValues;
 
-  void visitCallIndirect(CallIndirect* curr) {
-    handleCall(curr, curr->heapType.getSignature().params);
-  }
+  using WorkItem = std::variant<Expression*, Index>;

It would be good to say what these represent. I assume the Index is a local.

tlively tlively commented on code on Oct 16, 2026 22:02 UTC
Code Review
src/passes/TypeGeneralizing.cpp:1
@@ -14,905 +14,381 @@
  * limitations under the License.
  */
 
-#include "analysis/cfg.h"
-#include "analysis/lattices/inverted.h"
-#include "analysis/lattices/shared.h"
-#include "analysis/lattices/stack.h"
-#include "analysis/lattices/tuple.h"
-#include "analysis/lattices/valtype.h"
-#include "analysis/lattices/vector.h"
-#include "analysis/monotone-analyzer.h"
+//
+// Generalize the types of locals as much as possible, both to eliminate
+// unnecessarily refined types from the type section and (TODO) to weaken casts
+// that cast to unnecessarily refined types. If the casts are weakened enough,
+// they will be able to be removed by OptimizeInstructions.
+//
+
+#include <optional>
+#include <unordered_map>
+#include <variant>
+#include <vector>
+
+#include "ir/glbs.h"
+#include "ir/subtype-exprs.h"
 #include "ir/utils.h"
 #include "pass.h"
 #include "wasm-traversal.h"
 #include "wasm.h"
 
-#ifndef TYPE_GENERALIZING_DEBUG
-#define TYPE_GENERALIZING_DEBUG 0
-#endif
-
-#if TYPE_GENERALIZING_DEBUG
-#define DBG(statement) statement
-#else
-#define DBG(statement)
-#endif
-
-// Generalize the types of program locations as much as possible, both to
-// eliminate unnecessarily refined types from the type section and (TODO) to
-// weaken casts that cast to unnecessarily refined types. If the casts are
-// weakened enough, they will be able to be removed by OptimizeInstructions.
-//
-// Perform a backward analysis tracking requirements on the types of program
-// locations (currently just locals and stack values) to discover how much the
-// type of each location can be generalized without breaking validation or
-// changing program behavior.
-
 namespace wasm {
 
 namespace {
 
-using namespace analysis;
-
-// We will learn stricter and stricter requirements as we perform the analysis,
-// so more specific types need to be higher up the lattice.
-using TypeRequirement = Inverted<ValType>;
-
-// Record a type requirement for each local variable. Shared the requirements
-// across basic blocks.
-using LocalTypeRequirements = SharedPath<Vector<TypeRequirement>>;
-
-// The type requirements for each reference-typed value on the stack at a
-// particular location.
-using ValueStackTypeRequirements = Stack<TypeRequirement>;
-
-// The full lattice used for the analysis.
-using StateLattice =
-  analysis::Tuple<LocalTypeRequirements, ValueStackTypeRequirements>;
-
-// Equip the state lattice with helpful accessors.
-struct State : StateLattice {
-  using Element = StateLattice::Element;
-
-  static constexpr int LocalsIndex = 0;
-  static constexpr int StackIndex = 1;
-
-  State(Function* func)
-    : StateLattice{SharedPath{initLocals(func)}, initStack()} {}
-
-  void push(Element& elem, Type type) const noexcept {
-    stackLattice().push(stack(elem), std::move(type));
-  }
-
-  Type pop(Element& elem) const noexcept {
-    return stackLattice().pop(stack(elem));
-  }
-
-  void clearStack(Element& elem) const noexcept {
-    stack(elem) = stackLattice().getBottom();
-  }
-
-  const std::vector<Type>& getLocals(Element& elem) const noexcept {
-    return *locals(elem);
-  }
-
-  const std::vector<Type>& getLocals() const noexcept {
-    return *locals(getBottom());
-  }
-
-  Type getLocal(Element& elem, Index i) const noexcept {
-    return getLocals(elem)[i];
-  }
-
-  bool updateLocal(Element& elem, Index i, Type type) const noexcept {
-    return localsLattice().join(
-      locals(elem),
-      Vector<TypeRequirement>::SingletonElement(i, std::move(type)));
-  }
-
-private:
-  static LocalTypeRequirements initLocals(Function* func) noexcept {
-    return SharedPath{Vector{Inverted{ValType{}}, func->getNumLocals()}};
-  }
-
-  static ValueStackTypeRequirements initStack() noexcept {
-    return Stack{Inverted{ValType{}}};
-  }
-
-  const LocalTypeRequirements& localsLattice() const noexcept {
-    return std::get<LocalsIndex>(lattices);
-  }
-
-  const ValueStackTypeRequirements& stackLattice() const noexcept {
-    return std::get<StackIndex>(lattices);
-  }
-
-  typename LocalTypeRequirements::Element&
-  locals(Element& elem) const noexcept {
-    return std::get<LocalsIndex>(elem);
-  }
-
-  const typename LocalTypeRequirements::Element&
-  locals(const Element& elem) const noexcept {
-    return std::get<LocalsIndex>(elem);
-  }
-
-  typename ValueStackTypeRequirements::Element&
-  stack(Element& elem) const noexcept {
-    return std::get<StackIndex>(elem);
-  }
-
-  const typename ValueStackTypeRequirements::Element&
-  stack(const Element& elem) const noexcept {
-    return std::get<StackIndex>(elem);
-  }
-};
-
-struct TransferFn : OverriddenVisitor<TransferFn> {
-  Module& wasm;
-  Function* func;
-  State lattice;
-  typename State::Element* state = nullptr;
-
-  // For each local, the set of blocks we may need to re-analyze when we update
-  // the constraint on the local.
-  std::vector<std::vector<const BasicBlock*>> localDependents;
-
-  // The set of basic blocks that may depend on the result of the current
-  // transfer.
-  std::unordered_set<const BasicBlock*> currDependents;
-
-  TransferFn(Module& wasm, Function* func, CFG& cfg)
-    : wasm(wasm), func(func), lattice(func),
-      localDependents(func->getNumLocals()) {
-    // Initialize `localDependents`. Any block containing a `local.set l` may
-    // need to be re-analyzed whenever the constraint on `l` is updated.
-    auto numLocals = func->getNumLocals();
-    std::vector<std::unordered_set<const BasicBlock*>> dependentSets(numLocals);
-    for (const auto& bb : cfg) {
-      for (const auto* inst : bb) {
-        if (auto set = inst->dynCast<LocalSet>()) {
-          dependentSets[set->index].insert(&bb);
-        }
+// Find the most general supertype of a signature type that does not change
+// parameter types (which are contravariant and would restrict argument
+// generalization) and whose result type satisfies `resultReq`, if any.
+HeapType generalizeCallRefTarget(HeapType sigType,
+                                 std::optional<Type> resultReq = std::nullopt) {
+  auto sig = sigType.getSignature();
+  auto numParams = sig.params.size();
+  auto targetReq = sigType;
+  while (true) {
+    auto candidateReq = targetReq.getDeclaredSuperType();
+    if (!candidateReq) {
+      break;
+    }
+    auto candidateSig = candidateReq->getSignature();
+    if (resultReq && !Type::isSubType(candidateSig.results, *resultReq)) {
+      break;
+    }
+    for (size_t i = 0; i < numParams; ++i) {
+      if (candidateSig.params[i] != sig.params[i]) {
+        return targetReq;
       }
     }
-    for (size_t i = 0, n = dependentSets.size(); i < n; ++i) {
-      localDependents[i] = std::vector<const BasicBlock*>(
-        dependentSets[i].begin(), dependentSets[i].end());
-    }
+    targetReq = *candidateReq;
   }
+  return targetReq;
+}
 
-  Type pop() noexcept { return lattice.pop(*state); }
-  void push(Type type) noexcept { lattice.push(*state, type); }
-  void clearStack() noexcept { lattice.clearStack(*state); }
-  Type getLocal(Index i) noexcept { return lattice.getLocal(*state, i); }
-  void updateLocal(Index i, Type type) noexcept {
-    if (lattice.updateLocal(*state, i, type)) {
-      currDependents.insert(localDependents[i].begin(),
-                            localDependents[i].end());
+// Find the most general supertype of a struct type that still has a field at
+// `index` whose type satisfies `reqFieldType`, if any.
+HeapType generalizeStructType(HeapType type,
+                              Index index,
+                              std::optional<Type> reqFieldType = std::nullopt) {
+  while (true) {
+    auto candidateType = type.getDeclaredSuperType();
+    if (!candidateType) {
+      break;
     }
-  }
-
-  void dumpState() {
-#if TYPE_GENERALIZING_DEBUG
-    std::cerr << "locals: ";
-    for (size_t i = 0, n = lattice.getLocals(*state).size(); i < n; ++i) {
-      if (i != 0) {
-        std::cerr << ", ";
-      }
-      std::cerr << getLocal(i);
+    const auto& candidateFields = candidateType->getStruct().fields;
+    if (candidateFields.size() <= index) {
+      break;
     }
-    std::cerr << "\nstack: ";
-    auto& stack = std::get<1>(*state);
-    for (size_t i = 0, n = stack.size(); i < n; ++i) {
-      if (i != 0) {
-        std::cerr << ", ";
+    if (reqFieldType) {
+      auto candidateFieldType = candidateFields[index].type;
+      if (!Type::isSubType(candidateFieldType, *reqFieldType)) {
+        break;
       }
-      std::cerr << stack[i];
     }
-    std::cerr << "\n";
-#endif // TYPE_GENERALIZING_DEBUG
+    type = *candidateType;
   }
+  return type;
+}
 
-  std::unordered_set<const BasicBlock*>
-  transfer(const BasicBlock& bb, typename State::Element& elem) noexcept {
-    DBG(std::cerr << "transferring bb " << bb.getIndex() << "\n");
-    state = &elem;
-
-    // This is a backward analysis: The constraints on a type depend on how it
-    // will be used in the future. Traverse the basic block in reverse and
-    // return the predecessors as the dependent blocks.
-    assert(currDependents.empty());
-    const auto& preds = bb.preds();
-    currDependents.insert(preds.begin(), preds.end());
-
-    dumpState();
-    if (bb.isExit()) {
-      DBG(std::cerr << "visiting exit\n");
-      visitFunctionExit();
-      dumpState();
-    }
-    for (auto it = bb.rbegin(); it != bb.rend(); ++it) {
-      DBG(std::cerr << "visiting " << ShallowExpression{*it} << "\n");
-      visit(*it);
-      dumpState();
-    }
-    if (bb.isEntry()) {
-      DBG(std::cerr << "visiting entry\n");
-      visitFunctionEntry();
-      dumpState();
-    }
-    DBG(std::cerr << "\n");
-
-    state = nullptr;
-
-    // Return the blocks that may need to be re-analyzed.
-    return std::move(currDependents);
-  }
-
-  void visitFunctionExit() {
-    // We cannot change the types of results. Push a requirement that the stack
-    // end up with the correct type.
-    auto result = func->getResults();
-    if (result.isRef()) {
-      push(result);
+// Find the most general supertype of an array type whose element type satisfies
+// `reqElemType`, if any.
+HeapType generalizeArrayType(HeapType type,
+                             std::optional<Type> reqElemType = std::nullopt) {
+  while (true) {
+    auto candidateType = type.getDeclaredSuperType();
+    if (!candidateType) {
+      break;
     }
-  }
-
-  void visitFunctionEntry() {
-    // We cannot change the types of parameters, so require that they have their
-    // original types.
-    Index i = 0;
-    Index numParams = func->getNumParams();
-    Index numLocals = func->getNumLocals();
-    for (; i < numParams; ++i) {
-      updateLocal(i, func->getLocalType(i));
-    }
-    // We also cannot change the types of any other non-ref locals. For
-    // reference-typed locals, we cannot generalize beyond their top type.
-    for (Index i = numParams; i < numLocals; ++i) {
-      auto type = func->getLocalType(i);
-      // TODO: Support optimizing tuple locals.
-      if (type.isRef()) {
-        updateLocal(i, Type(type.getHeapType().getTop(), Nullable));
-      } else {
-        updateLocal(i, type);
+    if (reqElemType) {
+      auto candidateElemType = candidateType->getArray().element.type;
+      if (!Type::isSubType(candidateElemType, *reqElemType)) {
+        break;
       }
     }
+    type = *candidateType;
   }
+  return type;
+}
 
-  void visitNop(Nop* curr) {}
-  void visitBlock(Block* curr) {}
-  void visitIf(If* curr) {}
-  void visitLoop(Loop* curr) {}
-
-  void visitBreak(Break* curr) {
-    if (curr->condition) {
-      // `br_if` pops everything but the sent value off the stack if the branch
-      // is taken, but if the branch is not taken, it only pops the condition.
-      // We must therefore propagate all requirements from the fallthrough
-      // successor but only the requirements for the sent value, if any, from
-      // the branch successor. We don't have any way to differentiate between
-      // requirements received from the two successors, however, so we cannot
-      // yet do anything correct here!
-      //
-      // Here is a sample program that would break if we tried to conservatively
-      // preserve the join of the requirements from both successors:
-      //
-      // (module
-      //  (func $func_any (param funcref anyref)
-      //   (unreachable)
-      //  )
-      //
-      //  (func $extern_any-any (param externref anyref) (result anyref)
-      //   (unreachable)
-      //  )
-      //
-      //  (func $br-if-bad
-      //   (local $bang externref)
-      //   (call $func_any ;; 2. Requires [func, any]
-      //    (ref.null nofunc)
-      //    (block $l (result anyref)
-      //     (call $extern_any-any ;; 1. Requires [extern, any]
-      //      (local.get $bang)
-      //      (br_if $l ;; 3. After join, requires [unreachable, any]
-      //       (ref.null none)
-      //       (i32.const 0)
-      //      )
-      //     )
-      //    )
-      //   )
-      //  )
-      // )
-      //
-      // To fix this, we need to insert an extra basic block encompassing the
-      // liminal space between where the br_if determines it should take the
-      // branch and when control arrives at the branch target. This is when the
-      // extra values are popped off the stack.
-      WASM_UNREACHABLE("TODO");
-    } else {
-      // `br` pops everything but the sent value off the stack, so do not
-      // require anything of values on the stack except for that sent value, if
-      // it exists.
-      if (curr->value && curr->value->type.isRef()) {
-        auto type = pop();
-        clearStack();
-        push(type);
-      } else {
-        // No sent value. Do not require anything.
-        clearStack();
-      }
-    }
-  }
+// Use SubtypingDiscoverer to find all subtyping constraints on expressions and
+// locals, and computes the greatest lower bound (GLB) of the required
+// supertypes for each local so that each local is given the least-refined valid
+// type.
+//
+// TODO: handle ref.as_non_null, br_on_null, publish, br_if, etc. better: we do
+//       not need to consider their results fixed.
+struct Generalizer
+  : public ControlFlowWalker<Generalizer, SubtypingDiscoverer<Generalizer>> {
+  Function* func;
 
-  void visitSwitch(Switch* curr) {
-    // Just like `br`, do not require anything of the values on the stack except
-    // for the sent value, if it exists.
-    if (curr->value && curr->value->type.isRef()) {
-      auto type = pop();
-      clearStack();
-      push(type);
-    } else {
-      clearStack();
-    }
-  }
+  // For each expression and local, track the GLB of all types it is required to
+  // be a subtype of.
+  std::unordered_map<Expression*, GLBFinder> exprGLBs;
+  std::vector<GLBFinder> localGLBs;
 
-  template<typename T> void handleCall(T* curr, Type params) {
-    if (curr->type.isRef()) {
-      pop();
-    }
-    for (auto param : params) {
-      // Cannot generalize beyond param types without interprocedural analysis.
-      if (param.isRef()) {
-        push(param);
-      }
-    }
-  }
+  // Map from an expression to the sub-expressions whose types flow out of it
+  // (or depend on its required output type, as in RefAs).
+  std::unordered_map<Expression*, std::vector<Expression*>> exprSubs;
 
-  void visitCall(Call* curr) {
-    handleCall(curr, wasm.getFunction(curr->target)->getParams());
-  }
+  // For each local, the values assigned to it via local.set / local.tee.
+  std::vector<std::vector<Expression*>> localSetValues;
 
-  void visitCallIndirect(CallIndirect* curr) {
-    handleCall(curr, curr->heapType.getSignature().params);
-  }
+  using WorkItem = std::variant<Expression*, Index>;
+  std::vector<WorkItem> worklist;
 
-  void visitLocalGet(LocalGet* curr) {
-    if (!curr->type.isRef()) {
-      return;
-    }
-    // Propagate the requirement on the local.get output to the local.
-    updateLocal(curr->index, pop());
-  }
+  Generalizer(Function* func)
+    : func(func), localGLBs(func->getNumLocals()),
+      localSetValues(func->getNumLocals()) {}
 
-  void visitLocalSet(LocalSet* curr) {
-    if (!curr->value->type.isRef()) {
+  void addConstraint(Expression* expr, Type type) {
+    if (!expr->type.isRef() || !type.isRef()) {
       return;
     }
-    if (curr->isTee()) {
-      // Same as the local.get.
-      updateLocal(curr->index, pop());
+    auto& glb = exprGLBs[expr];
+    auto old = glb.getGLB();
+    glb.note(type);

Can we just have note return a bool saying whether anything changed?

tlively tlively commented on Oct 19, 2026 23:05 UTC
Reviewer

Gemini suggests I leave this comment:

LGTM! Thanks for adding the comprehensive test coverage and addressing the earlier feedback.

As a minor follow-up (not blocking this PR), we can update the doc comment at the top of `src/ir/subtype-exprs.h` to mention that `noteNonFlowSubtype` is also used for instructions that consume references without propagating them (such as `array.len`, string operations, etc.).

But I have more comments!

tlively tlively commented on Oct 21, 2026 00:00 UTC
Contributor

The one thing I did not do here is verify they are new and not previously covered (as I didn't write the old ones originally, so I'd need to do a lot of work to match things up). But I had Gemini check that. In the worst case, if it got it wrong, we might be adding some small amount of overlap.

I asked Gemini to use a coverage build to find the minimal set of tests. These can apparently be deleted without regressing coverage:

1. $struct-get-non-null-field (struct.get subtyping constraints were already fully exercised by module 0).
2. :$br_if (br_if flow constraints were already covered by baseline control-flow tests).
3. $return (return constraints were already covered by existing return tests).
4. $any-convert-extern-shared-nullable
5. $any-convert-extern-shared-non-nullable
6. $extern-convert-any-shared-nullable
7. $extern-convert-any-shared-non-nullable (The shared variants of any.convert_extern and extern.convert_any execute identical visitor and propagation paths as the unshared variants already tested in baseline).
8. $call-ref-non-null-result (generalizeCallRefTarget and non-null result propagation were already fully covered by module 0).
9. $throw (visitThrow was already covered by existing tag/exception tests).

kripken kripken commented on Oct 21, 2026 20:21 UTC
Author

Ok, just the very first item of that AI-generated list of tests is wrong, because I added it after we had a crash in the fuzzer that did not happen on the test suite. I went back in the history to verify that, and yes, that new testcase crashes while the old tests all pass.

kripken kripken commented on code on Oct 21, 2026 20:21 UTC
Code Review
src/passes/TypeGeneralizing.cpp:1
@@ -14,905 +14,381 @@
  * limitations under the License.
  */
 
-#include "analysis/cfg.h"
-#include "analysis/lattices/inverted.h"
-#include "analysis/lattices/shared.h"
-#include "analysis/lattices/stack.h"
-#include "analysis/lattices/tuple.h"
-#include "analysis/lattices/valtype.h"
-#include "analysis/lattices/vector.h"
-#include "analysis/monotone-analyzer.h"
+//
+// Generalize the types of locals as much as possible, both to eliminate
+// unnecessarily refined types from the type section and (TODO) to weaken casts
+// that cast to unnecessarily refined types. If the casts are weakened enough,
+// they will be able to be removed by OptimizeInstructions.
+//
+
+#include <optional>
+#include <unordered_map>
+#include <variant>
+#include <vector>
+
+#include "ir/glbs.h"
+#include "ir/subtype-exprs.h"
 #include "ir/utils.h"
 #include "pass.h"
 #include "wasm-traversal.h"
 #include "wasm.h"
 
-#ifndef TYPE_GENERALIZING_DEBUG
-#define TYPE_GENERALIZING_DEBUG 0
-#endif
-
-#if TYPE_GENERALIZING_DEBUG
-#define DBG(statement) statement
-#else
-#define DBG(statement)
-#endif
-
-// Generalize the types of program locations as much as possible, both to
-// eliminate unnecessarily refined types from the type section and (TODO) to
-// weaken casts that cast to unnecessarily refined types. If the casts are
-// weakened enough, they will be able to be removed by OptimizeInstructions.
-//
-// Perform a backward analysis tracking requirements on the types of program
-// locations (currently just locals and stack values) to discover how much the
-// type of each location can be generalized without breaking validation or
-// changing program behavior.
-
 namespace wasm {
 
 namespace {
 
-using namespace analysis;
-
-// We will learn stricter and stricter requirements as we perform the analysis,
-// so more specific types need to be higher up the lattice.
-using TypeRequirement = Inverted<ValType>;
-
-// Record a type requirement for each local variable. Shared the requirements
-// across basic blocks.
-using LocalTypeRequirements = SharedPath<Vector<TypeRequirement>>;
-
-// The type requirements for each reference-typed value on the stack at a
-// particular location.
-using ValueStackTypeRequirements = Stack<TypeRequirement>;
-
-// The full lattice used for the analysis.
-using StateLattice =
-  analysis::Tuple<LocalTypeRequirements, ValueStackTypeRequirements>;
-
-// Equip the state lattice with helpful accessors.
-struct State : StateLattice {
-  using Element = StateLattice::Element;
-
-  static constexpr int LocalsIndex = 0;
-  static constexpr int StackIndex = 1;
-
-  State(Function* func)
-    : StateLattice{SharedPath{initLocals(func)}, initStack()} {}
-
-  void push(Element& elem, Type type) const noexcept {
-    stackLattice().push(stack(elem), std::move(type));
-  }
-
-  Type pop(Element& elem) const noexcept {
-    return stackLattice().pop(stack(elem));
-  }
-
-  void clearStack(Element& elem) const noexcept {
-    stack(elem) = stackLattice().getBottom();
-  }
-
-  const std::vector<Type>& getLocals(Element& elem) const noexcept {
-    return *locals(elem);
-  }
-
-  const std::vector<Type>& getLocals() const noexcept {
-    return *locals(getBottom());
-  }
-
-  Type getLocal(Element& elem, Index i) const noexcept {
-    return getLocals(elem)[i];
-  }
-
-  bool updateLocal(Element& elem, Index i, Type type) const noexcept {
-    return localsLattice().join(
-      locals(elem),
-      Vector<TypeRequirement>::SingletonElement(i, std::move(type)));
-  }
-
-private:
-  static LocalTypeRequirements initLocals(Function* func) noexcept {
-    return SharedPath{Vector{Inverted{ValType{}}, func->getNumLocals()}};
-  }
-
-  static ValueStackTypeRequirements initStack() noexcept {
-    return Stack{Inverted{ValType{}}};
-  }
-
-  const LocalTypeRequirements& localsLattice() const noexcept {
-    return std::get<LocalsIndex>(lattices);
-  }
-
-  const ValueStackTypeRequirements& stackLattice() const noexcept {
-    return std::get<StackIndex>(lattices);
-  }
-
-  typename LocalTypeRequirements::Element&
-  locals(Element& elem) const noexcept {
-    return std::get<LocalsIndex>(elem);
-  }
-
-  const typename LocalTypeRequirements::Element&
-  locals(const Element& elem) const noexcept {
-    return std::get<LocalsIndex>(elem);
-  }
-
-  typename ValueStackTypeRequirements::Element&
-  stack(Element& elem) const noexcept {
-    return std::get<StackIndex>(elem);
-  }
-
-  const typename ValueStackTypeRequirements::Element&
-  stack(const Element& elem) const noexcept {
-    return std::get<StackIndex>(elem);
-  }
-};
-
-struct TransferFn : OverriddenVisitor<TransferFn> {
-  Module& wasm;
-  Function* func;
-  State lattice;
-  typename State::Element* state = nullptr;
-
-  // For each local, the set of blocks we may need to re-analyze when we update
-  // the constraint on the local.
-  std::vector<std::vector<const BasicBlock*>> localDependents;
-
-  // The set of basic blocks that may depend on the result of the current
-  // transfer.
-  std::unordered_set<const BasicBlock*> currDependents;
-
-  TransferFn(Module& wasm, Function* func, CFG& cfg)
-    : wasm(wasm), func(func), lattice(func),
-      localDependents(func->getNumLocals()) {
-    // Initialize `localDependents`. Any block containing a `local.set l` may
-    // need to be re-analyzed whenever the constraint on `l` is updated.
-    auto numLocals = func->getNumLocals();
-    std::vector<std::unordered_set<const BasicBlock*>> dependentSets(numLocals);
-    for (const auto& bb : cfg) {
-      for (const auto* inst : bb) {
-        if (auto set = inst->dynCast<LocalSet>()) {
-          dependentSets[set->index].insert(&bb);
-        }
+// Find the most general supertype of a signature type that does not change
+// parameter types (which are contravariant and would restrict argument
+// generalization) and whose result type satisfies `resultReq`, if any.
+HeapType generalizeCallRefTarget(HeapType sigType,
+                                 std::optional<Type> resultReq = std::nullopt) {
+  auto sig = sigType.getSignature();
+  auto numParams = sig.params.size();
+  auto targetReq = sigType;
+  while (true) {
+    auto candidateReq = targetReq.getDeclaredSuperType();
+    if (!candidateReq) {
+      break;
+    }
+    auto candidateSig = candidateReq->getSignature();
+    if (resultReq && !Type::isSubType(candidateSig.results, *resultReq)) {
+      break;
+    }
+    for (size_t i = 0; i < numParams; ++i) {
+      if (candidateSig.params[i] != sig.params[i]) {
+        return targetReq;
       }
     }
-    for (size_t i = 0, n = dependentSets.size(); i < n; ++i) {
-      localDependents[i] = std::vector<const BasicBlock*>(
-        dependentSets[i].begin(), dependentSets[i].end());
-    }
+    targetReq = *candidateReq;
   }
+  return targetReq;
+}
 
-  Type pop() noexcept { return lattice.pop(*state); }
-  void push(Type type) noexcept { lattice.push(*state, type); }
-  void clearStack() noexcept { lattice.clearStack(*state); }
-  Type getLocal(Index i) noexcept { return lattice.getLocal(*state, i); }
-  void updateLocal(Index i, Type type) noexcept {
-    if (lattice.updateLocal(*state, i, type)) {
-      currDependents.insert(localDependents[i].begin(),
-                            localDependents[i].end());
+// Find the most general supertype of a struct type that still has a field at
+// `index` whose type satisfies `reqFieldType`, if any.
+HeapType generalizeStructType(HeapType type,
+                              Index index,
+                              std::optional<Type> reqFieldType = std::nullopt) {
+  while (true) {
+    auto candidateType = type.getDeclaredSuperType();
+    if (!candidateType) {
+      break;
     }
-  }
-
-  void dumpState() {
-#if TYPE_GENERALIZING_DEBUG
-    std::cerr << "locals: ";
-    for (size_t i = 0, n = lattice.getLocals(*state).size(); i < n; ++i) {
-      if (i != 0) {
-        std::cerr << ", ";
-      }
-      std::cerr << getLocal(i);
+    const auto& candidateFields = candidateType->getStruct().fields;
+    if (candidateFields.size() <= index) {
+      break;
     }
-    std::cerr << "\nstack: ";
-    auto& stack = std::get<1>(*state);
-    for (size_t i = 0, n = stack.size(); i < n; ++i) {
-      if (i != 0) {
-        std::cerr << ", ";
+    if (reqFieldType) {
+      auto candidateFieldType = candidateFields[index].type;
+      if (!Type::isSubType(candidateFieldType, *reqFieldType)) {
+        break;
       }
-      std::cerr << stack[i];
     }
-    std::cerr << "\n";
-#endif // TYPE_GENERALIZING_DEBUG
+    type = *candidateType;
   }
+  return type;
+}
 
-  std::unordered_set<const BasicBlock*>
-  transfer(const BasicBlock& bb, typename State::Element& elem) noexcept {
-    DBG(std::cerr << "transferring bb " << bb.getIndex() << "\n");
-    state = &elem;
-
-    // This is a backward analysis: The constraints on a type depend on how it
-    // will be used in the future. Traverse the basic block in reverse and
-    // return the predecessors as the dependent blocks.
-    assert(currDependents.empty());
-    const auto& preds = bb.preds();
-    currDependents.insert(preds.begin(), preds.end());
-
-    dumpState();
-    if (bb.isExit()) {
-      DBG(std::cerr << "visiting exit\n");
-      visitFunctionExit();
-      dumpState();
-    }
-    for (auto it = bb.rbegin(); it != bb.rend(); ++it) {
-      DBG(std::cerr << "visiting " << ShallowExpression{*it} << "\n");
-      visit(*it);
-      dumpState();
-    }
-    if (bb.isEntry()) {
-      DBG(std::cerr << "visiting entry\n");
-      visitFunctionEntry();
-      dumpState();
-    }
-    DBG(std::cerr << "\n");
-
-    state = nullptr;
-
-    // Return the blocks that may need to be re-analyzed.
-    return std::move(currDependents);
-  }
-
-  void visitFunctionExit() {
-    // We cannot change the types of results. Push a requirement that the stack
-    // end up with the correct type.
-    auto result = func->getResults();
-    if (result.isRef()) {
-      push(result);
+// Find the most general supertype of an array type whose element type satisfies
+// `reqElemType`, if any.
+HeapType generalizeArrayType(HeapType type,
+                             std::optional<Type> reqElemType = std::nullopt) {
+  while (true) {
+    auto candidateType = type.getDeclaredSuperType();
+    if (!candidateType) {
+      break;
     }
-  }
-
-  void visitFunctionEntry() {
-    // We cannot change the types of parameters, so require that they have their
-    // original types.
-    Index i = 0;
-    Index numParams = func->getNumParams();
-    Index numLocals = func->getNumLocals();
-    for (; i < numParams; ++i) {
-      updateLocal(i, func->getLocalType(i));
-    }
-    // We also cannot change the types of any other non-ref locals. For
-    // reference-typed locals, we cannot generalize beyond their top type.
-    for (Index i = numParams; i < numLocals; ++i) {
-      auto type = func->getLocalType(i);
-      // TODO: Support optimizing tuple locals.
-      if (type.isRef()) {
-        updateLocal(i, Type(type.getHeapType().getTop(), Nullable));
-      } else {
-        updateLocal(i, type);
+    if (reqElemType) {
+      auto candidateElemType = candidateType->getArray().element.type;
+      if (!Type::isSubType(candidateElemType, *reqElemType)) {
+        break;
       }
     }
+    type = *candidateType;
   }
+  return type;
+}
 
-  void visitNop(Nop* curr) {}
-  void visitBlock(Block* curr) {}
-  void visitIf(If* curr) {}
-  void visitLoop(Loop* curr) {}
-
-  void visitBreak(Break* curr) {
-    if (curr->condition) {
-      // `br_if` pops everything but the sent value off the stack if the branch
-      // is taken, but if the branch is not taken, it only pops the condition.
-      // We must therefore propagate all requirements from the fallthrough
-      // successor but only the requirements for the sent value, if any, from
-      // the branch successor. We don't have any way to differentiate between
-      // requirements received from the two successors, however, so we cannot
-      // yet do anything correct here!
-      //
-      // Here is a sample program that would break if we tried to conservatively
-      // preserve the join of the requirements from both successors:
-      //
-      // (module
-      //  (func $func_any (param funcref anyref)
-      //   (unreachable)
-      //  )
-      //
-      //  (func $extern_any-any (param externref anyref) (result anyref)
-      //   (unreachable)
-      //  )
-      //
-      //  (func $br-if-bad
-      //   (local $bang externref)
-      //   (call $func_any ;; 2. Requires [func, any]
-      //    (ref.null nofunc)
-      //    (block $l (result anyref)
-      //     (call $extern_any-any ;; 1. Requires [extern, any]
-      //      (local.get $bang)
-      //      (br_if $l ;; 3. After join, requires [unreachable, any]
-      //       (ref.null none)
-      //       (i32.const 0)
-      //      )
-      //     )
-      //    )
-      //   )
-      //  )
-      // )
-      //
-      // To fix this, we need to insert an extra basic block encompassing the
-      // liminal space between where the br_if determines it should take the
-      // branch and when control arrives at the branch target. This is when the
-      // extra values are popped off the stack.
-      WASM_UNREACHABLE("TODO");
-    } else {
-      // `br` pops everything but the sent value off the stack, so do not
-      // require anything of values on the stack except for that sent value, if
-      // it exists.
-      if (curr->value && curr->value->type.isRef()) {
-        auto type = pop();
-        clearStack();
-        push(type);
-      } else {
-        // No sent value. Do not require anything.
-        clearStack();
-      }
-    }
-  }
+// Use SubtypingDiscoverer to find all subtyping constraints on expressions and
+// locals, and computes the greatest lower bound (GLB) of the required
+// supertypes for each local so that each local is given the least-refined valid
+// type.
+//
+// TODO: handle ref.as_non_null, br_on_null, publish, br_if, etc. better: we do
+//       not need to consider their results fixed.
+struct Generalizer
+  : public ControlFlowWalker<Generalizer, SubtypingDiscoverer<Generalizer>> {
+  Function* func;
 
-  void visitSwitch(Switch* curr) {
-    // Just like `br`, do not require anything of the values on the stack except
-    // for the sent value, if it exists.
-    if (curr->value && curr->value->type.isRef()) {
-      auto type = pop();
-      clearStack();
-      push(type);
-    } else {
-      clearStack();
-    }
-  }
+  // For each expression and local, track the GLB of all types it is required to
+  // be a subtype of.
+  std::unordered_map<Expression*, GLBFinder> exprGLBs;
+  std::vector<GLBFinder> localGLBs;
 
-  template<typename T> void handleCall(T* curr, Type params) {
-    if (curr->type.isRef()) {
-      pop();
-    }
-    for (auto param : params) {
-      // Cannot generalize beyond param types without interprocedural analysis.
-      if (param.isRef()) {
-        push(param);
-      }
-    }
-  }
+  // Map from an expression to the sub-expressions whose types flow out of it
+  // (or depend on its required output type, as in RefAs).
+  std::unordered_map<Expression*, std::vector<Expression*>> exprSubs;
 
-  void visitCall(Call* curr) {
-    handleCall(curr, wasm.getFunction(curr->target)->getParams());
-  }
+  // For each local, the values assigned to it via local.set / local.tee.
+  std::vector<std::vector<Expression*>> localSetValues;
 
-  void visitCallIndirect(CallIndirect* curr) {
-    handleCall(curr, curr->heapType.getSignature().params);
-  }
+  using WorkItem = std::variant<Expression*, Index>;
+  std::vector<WorkItem> worklist;
 
-  void visitLocalGet(LocalGet* curr) {
-    if (!curr->type.isRef()) {
-      return;
-    }
-    // Propagate the requirement on the local.get output to the local.
-    updateLocal(curr->index, pop());
-  }
+  Generalizer(Function* func)
+    : func(func), localGLBs(func->getNumLocals()),
+      localSetValues(func->getNumLocals()) {}
 
-  void visitLocalSet(LocalSet* curr) {
-    if (!curr->value->type.isRef()) {
+  void addConstraint(Expression* expr, Type type) {
+    if (!expr->type.isRef() || !type.isRef()) {
       return;
     }
-    if (curr->isTee()) {
-      // Same as the local.get.
-      updateLocal(curr->index, pop());
+    auto& glb = exprGLBs[expr];
+    auto old = glb.getGLB();
+    glb.note(type);

Perhaps, but it would break the current symmetry between LUBFinder::note and GLBFinder::note - ?

kripken kripken commented on code on Oct 21, 2026 20:21 UTC
Code Review
src/passes/TypeGeneralizing.cpp:1
@@ -14,905 +14,381 @@
  * limitations under the License.
  */
 
-#include "analysis/cfg.h"
-#include "analysis/lattices/inverted.h"
-#include "analysis/lattices/shared.h"
-#include "analysis/lattices/stack.h"
-#include "analysis/lattices/tuple.h"
-#include "analysis/lattices/valtype.h"
-#include "analysis/lattices/vector.h"
-#include "analysis/monotone-analyzer.h"
+//
+// Generalize the types of locals as much as possible, both to eliminate
+// unnecessarily refined types from the type section and (TODO) to weaken casts
+// that cast to unnecessarily refined types. If the casts are weakened enough,
+// they will be able to be removed by OptimizeInstructions.
+//
+
+#include <optional>
+#include <unordered_map>
+#include <variant>
+#include <vector>
+
+#include "ir/glbs.h"
+#include "ir/subtype-exprs.h"
 #include "ir/utils.h"
 #include "pass.h"
 #include "wasm-traversal.h"
 #include "wasm.h"
 
-#ifndef TYPE_GENERALIZING_DEBUG
-#define TYPE_GENERALIZING_DEBUG 0
-#endif
-
-#if TYPE_GENERALIZING_DEBUG
-#define DBG(statement) statement
-#else
-#define DBG(statement)
-#endif
-
-// Generalize the types of program locations as much as possible, both to
-// eliminate unnecessarily refined types from the type section and (TODO) to
-// weaken casts that cast to unnecessarily refined types. If the casts are
-// weakened enough, they will be able to be removed by OptimizeInstructions.
-//
-// Perform a backward analysis tracking requirements on the types of program
-// locations (currently just locals and stack values) to discover how much the
-// type of each location can be generalized without breaking validation or
-// changing program behavior.
-
 namespace wasm {
 
 namespace {
 
-using namespace analysis;
-
-// We will learn stricter and stricter requirements as we perform the analysis,
-// so more specific types need to be higher up the lattice.
-using TypeRequirement = Inverted<ValType>;
-
-// Record a type requirement for each local variable. Shared the requirements
-// across basic blocks.
-using LocalTypeRequirements = SharedPath<Vector<TypeRequirement>>;
-
-// The type requirements for each reference-typed value on the stack at a
-// particular location.
-using ValueStackTypeRequirements = Stack<TypeRequirement>;
-
-// The full lattice used for the analysis.
-using StateLattice =
-  analysis::Tuple<LocalTypeRequirements, ValueStackTypeRequirements>;
-
-// Equip the state lattice with helpful accessors.
-struct State : StateLattice {
-  using Element = StateLattice::Element;
-
-  static constexpr int LocalsIndex = 0;
-  static constexpr int StackIndex = 1;
-
-  State(Function* func)
-    : StateLattice{SharedPath{initLocals(func)}, initStack()} {}
-
-  void push(Element& elem, Type type) const noexcept {
-    stackLattice().push(stack(elem), std::move(type));
-  }
-
-  Type pop(Element& elem) const noexcept {
-    return stackLattice().pop(stack(elem));
-  }
-
-  void clearStack(Element& elem) const noexcept {
-    stack(elem) = stackLattice().getBottom();
-  }
-
-  const std::vector<Type>& getLocals(Element& elem) const noexcept {
-    return *locals(elem);
-  }
-
-  const std::vector<Type>& getLocals() const noexcept {
-    return *locals(getBottom());
-  }
-
-  Type getLocal(Element& elem, Index i) const noexcept {
-    return getLocals(elem)[i];
-  }
-
-  bool updateLocal(Element& elem, Index i, Type type) const noexcept {
-    return localsLattice().join(
-      locals(elem),
-      Vector<TypeRequirement>::SingletonElement(i, std::move(type)));
-  }
-
-private:
-  static LocalTypeRequirements initLocals(Function* func) noexcept {
-    return SharedPath{Vector{Inverted{ValType{}}, func->getNumLocals()}};
-  }
-
-  static ValueStackTypeRequirements initStack() noexcept {
-    return Stack{Inverted{ValType{}}};
-  }
-
-  const LocalTypeRequirements& localsLattice() const noexcept {
-    return std::get<LocalsIndex>(lattices);
-  }
-
-  const ValueStackTypeRequirements& stackLattice() const noexcept {
-    return std::get<StackIndex>(lattices);
-  }
-
-  typename LocalTypeRequirements::Element&
-  locals(Element& elem) const noexcept {
-    return std::get<LocalsIndex>(elem);
-  }
-
-  const typename LocalTypeRequirements::Element&
-  locals(const Element& elem) const noexcept {
-    return std::get<LocalsIndex>(elem);
-  }
-
-  typename ValueStackTypeRequirements::Element&
-  stack(Element& elem) const noexcept {
-    return std::get<StackIndex>(elem);
-  }
-
-  const typename ValueStackTypeRequirements::Element&
-  stack(const Element& elem) const noexcept {
-    return std::get<StackIndex>(elem);
-  }
-};
-
-struct TransferFn : OverriddenVisitor<TransferFn> {
-  Module& wasm;
-  Function* func;
-  State lattice;
-  typename State::Element* state = nullptr;
-
-  // For each local, the set of blocks we may need to re-analyze when we update
-  // the constraint on the local.
-  std::vector<std::vector<const BasicBlock*>> localDependents;
-
-  // The set of basic blocks that may depend on the result of the current
-  // transfer.
-  std::unordered_set<const BasicBlock*> currDependents;
-
-  TransferFn(Module& wasm, Function* func, CFG& cfg)
-    : wasm(wasm), func(func), lattice(func),
-      localDependents(func->getNumLocals()) {
-    // Initialize `localDependents`. Any block containing a `local.set l` may
-    // need to be re-analyzed whenever the constraint on `l` is updated.
-    auto numLocals = func->getNumLocals();
-    std::vector<std::unordered_set<const BasicBlock*>> dependentSets(numLocals);
-    for (const auto& bb : cfg) {
-      for (const auto* inst : bb) {
-        if (auto set = inst->dynCast<LocalSet>()) {
-          dependentSets[set->index].insert(&bb);
-        }
+// Find the most general supertype of a signature type that does not change
+// parameter types (which are contravariant and would restrict argument
+// generalization) and whose result type satisfies `resultReq`, if any.
+HeapType generalizeCallRefTarget(HeapType sigType,
+                                 std::optional<Type> resultReq = std::nullopt) {
+  auto sig = sigType.getSignature();
+  auto numParams = sig.params.size();
+  auto targetReq = sigType;
+  while (true) {
+    auto candidateReq = targetReq.getDeclaredSuperType();
+    if (!candidateReq) {
+      break;
+    }
+    auto candidateSig = candidateReq->getSignature();
+    if (resultReq && !Type::isSubType(candidateSig.results, *resultReq)) {
+      break;
+    }
+    for (size_t i = 0; i < numParams; ++i) {
+      if (candidateSig.params[i] != sig.params[i]) {
+        return targetReq;
       }
     }
-    for (size_t i = 0, n = dependentSets.size(); i < n; ++i) {
-      localDependents[i] = std::vector<const BasicBlock*>(
-        dependentSets[i].begin(), dependentSets[i].end());
-    }
+    targetReq = *candidateReq;
   }
+  return targetReq;
+}
 
-  Type pop() noexcept { return lattice.pop(*state); }
-  void push(Type type) noexcept { lattice.push(*state, type); }
-  void clearStack() noexcept { lattice.clearStack(*state); }
-  Type getLocal(Index i) noexcept { return lattice.getLocal(*state, i); }
-  void updateLocal(Index i, Type type) noexcept {
-    if (lattice.updateLocal(*state, i, type)) {
-      currDependents.insert(localDependents[i].begin(),
-                            localDependents[i].end());
+// Find the most general supertype of a struct type that still has a field at
+// `index` whose type satisfies `reqFieldType`, if any.
+HeapType generalizeStructType(HeapType type,
+                              Index index,
+                              std::optional<Type> reqFieldType = std::nullopt) {
+  while (true) {
+    auto candidateType = type.getDeclaredSuperType();
+    if (!candidateType) {
+      break;
     }
-  }
-
-  void dumpState() {
-#if TYPE_GENERALIZING_DEBUG
-    std::cerr << "locals: ";
-    for (size_t i = 0, n = lattice.getLocals(*state).size(); i < n; ++i) {
-      if (i != 0) {
-        std::cerr << ", ";
-      }
-      std::cerr << getLocal(i);
+    const auto& candidateFields = candidateType->getStruct().fields;
+    if (candidateFields.size() <= index) {
+      break;
     }
-    std::cerr << "\nstack: ";
-    auto& stack = std::get<1>(*state);
-    for (size_t i = 0, n = stack.size(); i < n; ++i) {
-      if (i != 0) {
-        std::cerr << ", ";
+    if (reqFieldType) {
+      auto candidateFieldType = candidateFields[index].type;
+      if (!Type::isSubType(candidateFieldType, *reqFieldType)) {
+        break;
       }
-      std::cerr << stack[i];
     }
-    std::cerr << "\n";
-#endif // TYPE_GENERALIZING_DEBUG
+    type = *candidateType;
   }
+  return type;
+}
 
-  std::unordered_set<const BasicBlock*>
-  transfer(const BasicBlock& bb, typename State::Element& elem) noexcept {
-    DBG(std::cerr << "transferring bb " << bb.getIndex() << "\n");
-    state = &elem;
-
-    // This is a backward analysis: The constraints on a type depend on how it
-    // will be used in the future. Traverse the basic block in reverse and
-    // return the predecessors as the dependent blocks.
-    assert(currDependents.empty());
-    const auto& preds = bb.preds();
-    currDependents.insert(preds.begin(), preds.end());
-
-    dumpState();
-    if (bb.isExit()) {
-      DBG(std::cerr << "visiting exit\n");
-      visitFunctionExit();
-      dumpState();
-    }
-    for (auto it = bb.rbegin(); it != bb.rend(); ++it) {
-      DBG(std::cerr << "visiting " << ShallowExpression{*it} << "\n");
-      visit(*it);
-      dumpState();
-    }
-    if (bb.isEntry()) {
-      DBG(std::cerr << "visiting entry\n");
-      visitFunctionEntry();
-      dumpState();
-    }
-    DBG(std::cerr << "\n");
-
-    state = nullptr;
-
-    // Return the blocks that may need to be re-analyzed.
-    return std::move(currDependents);
-  }
-
-  void visitFunctionExit() {
-    // We cannot change the types of results. Push a requirement that the stack
-    // end up with the correct type.
-    auto result = func->getResults();
-    if (result.isRef()) {
-      push(result);
+// Find the most general supertype of an array type whose element type satisfies
+// `reqElemType`, if any.
+HeapType generalizeArrayType(HeapType type,
+                             std::optional<Type> reqElemType = std::nullopt) {
+  while (true) {
+    auto candidateType = type.getDeclaredSuperType();
+    if (!candidateType) {
+      break;
     }
-  }
-
-  void visitFunctionEntry() {
-    // We cannot change the types of parameters, so require that they have their
-    // original types.
-    Index i = 0;
-    Index numParams = func->getNumParams();
-    Index numLocals = func->getNumLocals();
-    for (; i < numParams; ++i) {
-      updateLocal(i, func->getLocalType(i));
-    }
-    // We also cannot change the types of any other non-ref locals. For
-    // reference-typed locals, we cannot generalize beyond their top type.
-    for (Index i = numParams; i < numLocals; ++i) {
-      auto type = func->getLocalType(i);
-      // TODO: Support optimizing tuple locals.
-      if (type.isRef()) {
-        updateLocal(i, Type(type.getHeapType().getTop(), Nullable));
-      } else {
-        updateLocal(i, type);
+    if (reqElemType) {
+      auto candidateElemType = candidateType->getArray().element.type;
+      if (!Type::isSubType(candidateElemType, *reqElemType)) {
+        break;
       }
     }
+    type = *candidateType;
   }
+  return type;
+}
 
-  void visitNop(Nop* curr) {}
-  void visitBlock(Block* curr) {}
-  void visitIf(If* curr) {}
-  void visitLoop(Loop* curr) {}
-
-  void visitBreak(Break* curr) {
-    if (curr->condition) {
-      // `br_if` pops everything but the sent value off the stack if the branch
-      // is taken, but if the branch is not taken, it only pops the condition.
-      // We must therefore propagate all requirements from the fallthrough
-      // successor but only the requirements for the sent value, if any, from
-      // the branch successor. We don't have any way to differentiate between
-      // requirements received from the two successors, however, so we cannot
-      // yet do anything correct here!
-      //
-      // Here is a sample program that would break if we tried to conservatively
-      // preserve the join of the requirements from both successors:
-      //
-      // (module
-      //  (func $func_any (param funcref anyref)
-      //   (unreachable)
-      //  )
-      //
-      //  (func $extern_any-any (param externref anyref) (result anyref)
-      //   (unreachable)
-      //  )
-      //
-      //  (func $br-if-bad
-      //   (local $bang externref)
-      //   (call $func_any ;; 2. Requires [func, any]
-      //    (ref.null nofunc)
-      //    (block $l (result anyref)
-      //     (call $extern_any-any ;; 1. Requires [extern, any]
-      //      (local.get $bang)
-      //      (br_if $l ;; 3. After join, requires [unreachable, any]
-      //       (ref.null none)
-      //       (i32.const 0)
-      //      )
-      //     )
-      //    )
-      //   )
-      //  )
-      // )
-      //
-      // To fix this, we need to insert an extra basic block encompassing the
-      // liminal space between where the br_if determines it should take the
-      // branch and when control arrives at the branch target. This is when the
-      // extra values are popped off the stack.
-      WASM_UNREACHABLE("TODO");
-    } else {
-      // `br` pops everything but the sent value off the stack, so do not
-      // require anything of values on the stack except for that sent value, if
-      // it exists.
-      if (curr->value && curr->value->type.isRef()) {
-        auto type = pop();
-        clearStack();
-        push(type);
-      } else {
-        // No sent value. Do not require anything.
-        clearStack();
-      }
-    }
-  }
+// Use SubtypingDiscoverer to find all subtyping constraints on expressions and
+// locals, and computes the greatest lower bound (GLB) of the required
+// supertypes for each local so that each local is given the least-refined valid
+// type.
+//
+// TODO: handle ref.as_non_null, br_on_null, publish, br_if, etc. better: we do
+//       not need to consider their results fixed.
+struct Generalizer
+  : public ControlFlowWalker<Generalizer, SubtypingDiscoverer<Generalizer>> {
+  Function* func;
 
-  void visitSwitch(Switch* curr) {
-    // Just like `br`, do not require anything of the values on the stack except
-    // for the sent value, if it exists.
-    if (curr->value && curr->value->type.isRef()) {
-      auto type = pop();
-      clearStack();
-      push(type);
-    } else {
-      clearStack();
-    }
-  }
+  // For each expression and local, track the GLB of all types it is required to
+  // be a subtype of.
+  std::unordered_map<Expression*, GLBFinder> exprGLBs;
+  std::vector<GLBFinder> localGLBs;
 
-  template<typename T> void handleCall(T* curr, Type params) {
-    if (curr->type.isRef()) {
-      pop();
-    }
-    for (auto param : params) {
-      // Cannot generalize beyond param types without interprocedural analysis.
-      if (param.isRef()) {
-        push(param);
-      }
-    }
-  }
+  // Map from an expression to the sub-expressions whose types flow out of it
+  // (or depend on its required output type, as in RefAs).
+  std::unordered_map<Expression*, std::vector<Expression*>> exprSubs;
 
-  void visitCall(Call* curr) {
-    handleCall(curr, wasm.getFunction(curr->target)->getParams());
-  }
+  // For each local, the values assigned to it via local.set / local.tee.
+  std::vector<std::vector<Expression*>> localSetValues;
 
-  void visitCallIndirect(CallIndirect* curr) {
-    handleCall(curr, curr->heapType.getSignature().params);
-  }
+  using WorkItem = std::variant<Expression*, Index>;

comment added.

tlively tlively commented on Oct 21, 2026 22:24 UTC
Contributor

Ok, maybe the AI was lying to me or maybe line coverage wouldn't regress, but it's still useful as a regression test. That's fine. If any of those listed tests aren't useful for some other reason not captured by line coverage, though, it seems fine to delete them.

tlively tlively commented on code on Oct 21, 2026 22:24 UTC
Code Review
src/passes/TypeGeneralizing.cpp:1
@@ -14,905 +14,381 @@
  * limitations under the License.
  */
 
-#include "analysis/cfg.h"
-#include "analysis/lattices/inverted.h"
-#include "analysis/lattices/shared.h"
-#include "analysis/lattices/stack.h"
-#include "analysis/lattices/tuple.h"
-#include "analysis/lattices/valtype.h"
-#include "analysis/lattices/vector.h"
-#include "analysis/monotone-analyzer.h"
+//
+// Generalize the types of locals as much as possible, both to eliminate
+// unnecessarily refined types from the type section and (TODO) to weaken casts
+// that cast to unnecessarily refined types. If the casts are weakened enough,
+// they will be able to be removed by OptimizeInstructions.
+//
+
+#include <optional>
+#include <unordered_map>
+#include <variant>
+#include <vector>
+
+#include "ir/glbs.h"
+#include "ir/subtype-exprs.h"
 #include "ir/utils.h"
 #include "pass.h"
 #include "wasm-traversal.h"
 #include "wasm.h"
 
-#ifndef TYPE_GENERALIZING_DEBUG
-#define TYPE_GENERALIZING_DEBUG 0
-#endif
-
-#if TYPE_GENERALIZING_DEBUG
-#define DBG(statement) statement
-#else
-#define DBG(statement)
-#endif
-
-// Generalize the types of program locations as much as possible, both to
-// eliminate unnecessarily refined types from the type section and (TODO) to
-// weaken casts that cast to unnecessarily refined types. If the casts are
-// weakened enough, they will be able to be removed by OptimizeInstructions.
-//
-// Perform a backward analysis tracking requirements on the types of program
-// locations (currently just locals and stack values) to discover how much the
-// type of each location can be generalized without breaking validation or
-// changing program behavior.
-
 namespace wasm {
 
 namespace {
 
-using namespace analysis;
-
-// We will learn stricter and stricter requirements as we perform the analysis,
-// so more specific types need to be higher up the lattice.
-using TypeRequirement = Inverted<ValType>;
-
-// Record a type requirement for each local variable. Shared the requirements
-// across basic blocks.
-using LocalTypeRequirements = SharedPath<Vector<TypeRequirement>>;
-
-// The type requirements for each reference-typed value on the stack at a
-// particular location.
-using ValueStackTypeRequirements = Stack<TypeRequirement>;
-
-// The full lattice used for the analysis.
-using StateLattice =
-  analysis::Tuple<LocalTypeRequirements, ValueStackTypeRequirements>;
-
-// Equip the state lattice with helpful accessors.
-struct State : StateLattice {
-  using Element = StateLattice::Element;
-
-  static constexpr int LocalsIndex = 0;
-  static constexpr int StackIndex = 1;
-
-  State(Function* func)
-    : StateLattice{SharedPath{initLocals(func)}, initStack()} {}
-
-  void push(Element& elem, Type type) const noexcept {
-    stackLattice().push(stack(elem), std::move(type));
-  }
-
-  Type pop(Element& elem) const noexcept {
-    return stackLattice().pop(stack(elem));
-  }
-
-  void clearStack(Element& elem) const noexcept {
-    stack(elem) = stackLattice().getBottom();
-  }
-
-  const std::vector<Type>& getLocals(Element& elem) const noexcept {
-    return *locals(elem);
-  }
-
-  const std::vector<Type>& getLocals() const noexcept {
-    return *locals(getBottom());
-  }
-
-  Type getLocal(Element& elem, Index i) const noexcept {
-    return getLocals(elem)[i];
-  }
-
-  bool updateLocal(Element& elem, Index i, Type type) const noexcept {
-    return localsLattice().join(
-      locals(elem),
-      Vector<TypeRequirement>::SingletonElement(i, std::move(type)));
-  }
-
-private:
-  static LocalTypeRequirements initLocals(Function* func) noexcept {
-    return SharedPath{Vector{Inverted{ValType{}}, func->getNumLocals()}};
-  }
-
-  static ValueStackTypeRequirements initStack() noexcept {
-    return Stack{Inverted{ValType{}}};
-  }
-
-  const LocalTypeRequirements& localsLattice() const noexcept {
-    return std::get<LocalsIndex>(lattices);
-  }
-
-  const ValueStackTypeRequirements& stackLattice() const noexcept {
-    return std::get<StackIndex>(lattices);
-  }
-
-  typename LocalTypeRequirements::Element&
-  locals(Element& elem) const noexcept {
-    return std::get<LocalsIndex>(elem);
-  }
-
-  const typename LocalTypeRequirements::Element&
-  locals(const Element& elem) const noexcept {
-    return std::get<LocalsIndex>(elem);
-  }
-
-  typename ValueStackTypeRequirements::Element&
-  stack(Element& elem) const noexcept {
-    return std::get<StackIndex>(elem);
-  }
-
-  const typename ValueStackTypeRequirements::Element&
-  stack(const Element& elem) const noexcept {
-    return std::get<StackIndex>(elem);
-  }
-};
-
-struct TransferFn : OverriddenVisitor<TransferFn> {
-  Module& wasm;
-  Function* func;
-  State lattice;
-  typename State::Element* state = nullptr;
-
-  // For each local, the set of blocks we may need to re-analyze when we update
-  // the constraint on the local.
-  std::vector<std::vector<const BasicBlock*>> localDependents;
-
-  // The set of basic blocks that may depend on the result of the current
-  // transfer.
-  std::unordered_set<const BasicBlock*> currDependents;
-
-  TransferFn(Module& wasm, Function* func, CFG& cfg)
-    : wasm(wasm), func(func), lattice(func),
-      localDependents(func->getNumLocals()) {
-    // Initialize `localDependents`. Any block containing a `local.set l` may
-    // need to be re-analyzed whenever the constraint on `l` is updated.
-    auto numLocals = func->getNumLocals();
-    std::vector<std::unordered_set<const BasicBlock*>> dependentSets(numLocals);
-    for (const auto& bb : cfg) {
-      for (const auto* inst : bb) {
-        if (auto set = inst->dynCast<LocalSet>()) {
-          dependentSets[set->index].insert(&bb);
-        }
+// Find the most general supertype of a signature type that does not change
+// parameter types (which are contravariant and would restrict argument
+// generalization) and whose result type satisfies `resultReq`, if any.
+HeapType generalizeCallRefTarget(HeapType sigType,
+                                 std::optional<Type> resultReq = std::nullopt) {
+  auto sig = sigType.getSignature();
+  auto numParams = sig.params.size();
+  auto targetReq = sigType;
+  while (true) {
+    auto candidateReq = targetReq.getDeclaredSuperType();
+    if (!candidateReq) {
+      break;
+    }
+    auto candidateSig = candidateReq->getSignature();
+    if (resultReq && !Type::isSubType(candidateSig.results, *resultReq)) {
+      break;
+    }
+    for (size_t i = 0; i < numParams; ++i) {
+      if (candidateSig.params[i] != sig.params[i]) {
+        return targetReq;
       }
     }
-    for (size_t i = 0, n = dependentSets.size(); i < n; ++i) {
-      localDependents[i] = std::vector<const BasicBlock*>(
-        dependentSets[i].begin(), dependentSets[i].end());
-    }
+    targetReq = *candidateReq;
   }
+  return targetReq;
+}
 
-  Type pop() noexcept { return lattice.pop(*state); }
-  void push(Type type) noexcept { lattice.push(*state, type); }
-  void clearStack() noexcept { lattice.clearStack(*state); }
-  Type getLocal(Index i) noexcept { return lattice.getLocal(*state, i); }
-  void updateLocal(Index i, Type type) noexcept {
-    if (lattice.updateLocal(*state, i, type)) {
-      currDependents.insert(localDependents[i].begin(),
-                            localDependents[i].end());
+// Find the most general supertype of a struct type that still has a field at
+// `index` whose type satisfies `reqFieldType`, if any.
+HeapType generalizeStructType(HeapType type,
+                              Index index,
+                              std::optional<Type> reqFieldType = std::nullopt) {
+  while (true) {
+    auto candidateType = type.getDeclaredSuperType();
+    if (!candidateType) {
+      break;
     }
-  }
-
-  void dumpState() {
-#if TYPE_GENERALIZING_DEBUG
-    std::cerr << "locals: ";
-    for (size_t i = 0, n = lattice.getLocals(*state).size(); i < n; ++i) {
-      if (i != 0) {
-        std::cerr << ", ";
-      }
-      std::cerr << getLocal(i);
+    const auto& candidateFields = candidateType->getStruct().fields;
+    if (candidateFields.size() <= index) {
+      break;
     }
-    std::cerr << "\nstack: ";
-    auto& stack = std::get<1>(*state);
-    for (size_t i = 0, n = stack.size(); i < n; ++i) {
-      if (i != 0) {
-        std::cerr << ", ";
+    if (reqFieldType) {
+      auto candidateFieldType = candidateFields[index].type;
+      if (!Type::isSubType(candidateFieldType, *reqFieldType)) {
+        break;
       }
-      std::cerr << stack[i];
     }
-    std::cerr << "\n";
-#endif // TYPE_GENERALIZING_DEBUG
+    type = *candidateType;
   }
+  return type;
+}
 
-  std::unordered_set<const BasicBlock*>
-  transfer(const BasicBlock& bb, typename State::Element& elem) noexcept {
-    DBG(std::cerr << "transferring bb " << bb.getIndex() << "\n");
-    state = &elem;
-
-    // This is a backward analysis: The constraints on a type depend on how it
-    // will be used in the future. Traverse the basic block in reverse and
-    // return the predecessors as the dependent blocks.
-    assert(currDependents.empty());
-    const auto& preds = bb.preds();
-    currDependents.insert(preds.begin(), preds.end());
-
-    dumpState();
-    if (bb.isExit()) {
-      DBG(std::cerr << "visiting exit\n");
-      visitFunctionExit();
-      dumpState();
-    }
-    for (auto it = bb.rbegin(); it != bb.rend(); ++it) {
-      DBG(std::cerr << "visiting " << ShallowExpression{*it} << "\n");
-      visit(*it);
-      dumpState();
-    }
-    if (bb.isEntry()) {
-      DBG(std::cerr << "visiting entry\n");
-      visitFunctionEntry();
-      dumpState();
-    }
-    DBG(std::cerr << "\n");
-
-    state = nullptr;
-
-    // Return the blocks that may need to be re-analyzed.
-    return std::move(currDependents);
-  }
-
-  void visitFunctionExit() {
-    // We cannot change the types of results. Push a requirement that the stack
-    // end up with the correct type.
-    auto result = func->getResults();
-    if (result.isRef()) {
-      push(result);
+// Find the most general supertype of an array type whose element type satisfies
+// `reqElemType`, if any.
+HeapType generalizeArrayType(HeapType type,
+                             std::optional<Type> reqElemType = std::nullopt) {
+  while (true) {
+    auto candidateType = type.getDeclaredSuperType();
+    if (!candidateType) {
+      break;
     }
-  }
-
-  void visitFunctionEntry() {
-    // We cannot change the types of parameters, so require that they have their
-    // original types.
-    Index i = 0;
-    Index numParams = func->getNumParams();
-    Index numLocals = func->getNumLocals();
-    for (; i < numParams; ++i) {
-      updateLocal(i, func->getLocalType(i));
-    }
-    // We also cannot change the types of any other non-ref locals. For
-    // reference-typed locals, we cannot generalize beyond their top type.
-    for (Index i = numParams; i < numLocals; ++i) {
-      auto type = func->getLocalType(i);
-      // TODO: Support optimizing tuple locals.
-      if (type.isRef()) {
-        updateLocal(i, Type(type.getHeapType().getTop(), Nullable));
-      } else {
-        updateLocal(i, type);
+    if (reqElemType) {
+      auto candidateElemType = candidateType->getArray().element.type;
+      if (!Type::isSubType(candidateElemType, *reqElemType)) {
+        break;
       }
     }
+    type = *candidateType;
   }
+  return type;
+}
 
-  void visitNop(Nop* curr) {}
-  void visitBlock(Block* curr) {}
-  void visitIf(If* curr) {}
-  void visitLoop(Loop* curr) {}
-
-  void visitBreak(Break* curr) {
-    if (curr->condition) {
-      // `br_if` pops everything but the sent value off the stack if the branch
-      // is taken, but if the branch is not taken, it only pops the condition.
-      // We must therefore propagate all requirements from the fallthrough
-      // successor but only the requirements for the sent value, if any, from
-      // the branch successor. We don't have any way to differentiate between
-      // requirements received from the two successors, however, so we cannot
-      // yet do anything correct here!
-      //
-      // Here is a sample program that would break if we tried to conservatively
-      // preserve the join of the requirements from both successors:
-      //
-      // (module
-      //  (func $func_any (param funcref anyref)
-      //   (unreachable)
-      //  )
-      //
-      //  (func $extern_any-any (param externref anyref) (result anyref)
-      //   (unreachable)
-      //  )
-      //
-      //  (func $br-if-bad
-      //   (local $bang externref)
-      //   (call $func_any ;; 2. Requires [func, any]
-      //    (ref.null nofunc)
-      //    (block $l (result anyref)
-      //     (call $extern_any-any ;; 1. Requires [extern, any]
-      //      (local.get $bang)
-      //      (br_if $l ;; 3. After join, requires [unreachable, any]
-      //       (ref.null none)
-      //       (i32.const 0)
-      //      )
-      //     )
-      //    )
-      //   )
-      //  )
-      // )
-      //
-      // To fix this, we need to insert an extra basic block encompassing the
-      // liminal space between where the br_if determines it should take the
-      // branch and when control arrives at the branch target. This is when the
-      // extra values are popped off the stack.
-      WASM_UNREACHABLE("TODO");
-    } else {
-      // `br` pops everything but the sent value off the stack, so do not
-      // require anything of values on the stack except for that sent value, if
-      // it exists.
-      if (curr->value && curr->value->type.isRef()) {
-        auto type = pop();
-        clearStack();
-        push(type);
-      } else {
-        // No sent value. Do not require anything.
-        clearStack();
-      }
-    }
-  }
+// Use SubtypingDiscoverer to find all subtyping constraints on expressions and
+// locals, and computes the greatest lower bound (GLB) of the required
+// supertypes for each local so that each local is given the least-refined valid
+// type.
+//
+// TODO: handle ref.as_non_null, br_on_null, publish, br_if, etc. better: we do
+//       not need to consider their results fixed.
+struct Generalizer
+  : public ControlFlowWalker<Generalizer, SubtypingDiscoverer<Generalizer>> {
+  Function* func;
 
-  void visitSwitch(Switch* curr) {
-    // Just like `br`, do not require anything of the values on the stack except
-    // for the sent value, if it exists.
-    if (curr->value && curr->value->type.isRef()) {
-      auto type = pop();
-      clearStack();
-      push(type);
-    } else {
-      clearStack();
-    }
-  }
+  // For each expression and local, track the GLB of all types it is required to
+  // be a subtype of.
+  std::unordered_map<Expression*, GLBFinder> exprGLBs;
+  std::vector<GLBFinder> localGLBs;
 
-  template<typename T> void handleCall(T* curr, Type params) {
-    if (curr->type.isRef()) {
-      pop();
-    }
-    for (auto param : params) {
-      // Cannot generalize beyond param types without interprocedural analysis.
-      if (param.isRef()) {
-        push(param);
-      }
-    }
-  }
+  // Map from an expression to the sub-expressions whose types flow out of it
+  // (or depend on its required output type, as in RefAs).
+  std::unordered_map<Expression*, std::vector<Expression*>> exprSubs;
 
-  void visitCall(Call* curr) {
-    handleCall(curr, wasm.getFunction(curr->target)->getParams());
-  }
+  // For each local, the values assigned to it via local.set / local.tee.
+  std::vector<std::vector<Expression*>> localSetValues;
 
-  void visitCallIndirect(CallIndirect* curr) {
-    handleCall(curr, curr->heapType.getSignature().params);
-  }
+  using WorkItem = std::variant<Expression*, Index>;
+  std::vector<WorkItem> worklist;
 
-  void visitLocalGet(LocalGet* curr) {
-    if (!curr->type.isRef()) {
-      return;
-    }
-    // Propagate the requirement on the local.get output to the local.
-    updateLocal(curr->index, pop());
-  }
+  Generalizer(Function* func)
+    : func(func), localGLBs(func->getNumLocals()),
+      localSetValues(func->getNumLocals()) {}
 
-  void visitLocalSet(LocalSet* curr) {
-    if (!curr->value->type.isRef()) {
+  void addConstraint(Expression* expr, Type type) {
+    if (!expr->type.isRef() || !type.isRef()) {
       return;
     }
-    if (curr->isTee()) {
-      // Same as the local.get.
-      updateLocal(curr->index, pop());
+    auto& glb = exprGLBs[expr];
+    auto old = glb.getGLB();
+    glb.note(type);

Well LUBFinder::note would probably benefit from the same change :) But that's fine, we can leave that out of this PR.

tlively tlively approved these changes on Oct 21, 2026 22:49 UTC
Approved Reviewer

Approved these changes.

Reviewers
Assignees
kripken kripken
Labels
risk: low confidence: 89.5% 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: 50.3% (MEDIUM) · Higher = larger blast radius
50.3%
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: 89.5% · Lower = rushed or shallow review
89.5%
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: 5.3% · Safe to merge
5.3%