[llvm] [llubi] Map tags into pointer components (PR #200236)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Thu May 28 11:04:12 PDT 2026


https://github.com/dtcxzyw created https://github.com/llvm/llvm-project/pull/200236

This patch adjusts https://github.com/llvm/llvm-project/pull/185977 to generate tags for pointer components (excluding addresses), instead of memory objects. This allows us to distinguish between `read_provenance` and `provenance`. See the original comment in https://github.com/llvm/llvm-project/pull/185977#discussion_r3310861793.

I don't know what a better name for `PointerComponents/Metadata` is. It is definitely larger than the scope of provenance (I mean, the ability to perform memory access), as I'd like to use this to track all attributes described as `based on another pointer` in LangRef (e.g., `captures(address)`, `nofree`).

Currently, tags are only generated for those pointer components associated with a known memory object. We may need some special tags for `capture(address)`-only pointers and the result of inttoptr (wildcard provenance) in the future.


>From a67a35a6936392bb654c96373a2e264d72fa2b46 Mon Sep 17 00:00:00 2001
From: Yingwei Zheng <dtcxzyw2333 at gmail.com>
Date: Fri, 29 May 2026 01:49:51 +0800
Subject: [PATCH] [llubi] Map tags into pointer components

---
 llvm/tools/llubi/lib/Context.cpp | 53 ++++++++++++++++----------------
 llvm/tools/llubi/lib/Context.h   | 29 ++++++-----------
 llvm/tools/llubi/lib/Value.cpp   | 11 +++++--
 llvm/tools/llubi/lib/Value.h     | 52 ++++++++++++++++++++++++++-----
 4 files changed, 90 insertions(+), 55 deletions(-)

diff --git a/llvm/tools/llubi/lib/Context.cpp b/llvm/tools/llubi/lib/Context.cpp
index d3a0ee5db167a..15d3ad2c71af3 100644
--- a/llvm/tools/llubi/lib/Context.cpp
+++ b/llvm/tools/llubi/lib/Context.cpp
@@ -110,20 +110,21 @@ const AnyValue &Context::getConstantValue(Constant *C) {
   return ConstCache.emplace(C, getConstantValueImpl(C)).first->second;
 }
 
-APInt Context::getTag(uint32_t BitWidth, MemoryObject *Obj) {
+APInt Context::getTag(uint32_t BitWidth, PointerComponents &Comp) {
   // Nullary provenance.
-  if (!Obj)
+  if (!Comp.getMemoryObject())
     return APInt::getZero(BitWidth);
   // The tag is already initialized.
-  if (!Obj->getTag().isZero())
-    return Obj->getTag();
+  if (!Comp.getTag().isZero())
+    return Comp.getTag();
 
   // FIXME: This doesn't work when the address space is too small.
   while (true) {
     APInt Tag = generateRandomAPInt(BitWidth);
-    if (Tag.isZero() || !TaggedMemoryObjects.try_emplace(Tag, Obj).second)
+    if (Tag.isZero() || !TaggedPointerComponents.try_emplace(Tag, &Comp).second)
       continue;
-    Obj->setTag(Tag);
+    Comp.setTag(Tag);
+    Comp.getMemoryObject()->AssociatedTags.push_back(Tag);
     return Tag;
   }
 }
@@ -215,7 +216,8 @@ AnyValue Context::fromBytes(ConstBytesView Bytes, Type *Ty,
   // Try to recover provenance from the tag.
   if (IsTagValid) {
     APInt Tag(NumBitsToExtract, RawTagBits);
-    return Pointer(TaggedMemoryObjects.lookup(Tag), Bits);
+    if (auto Comp = TaggedPointerComponents.lookup(Tag))
+      return Pointer(std::move(Comp), Bits);
   }
   return Pointer(Bits);
 }
@@ -349,18 +351,12 @@ void Context::toBytes(const AnyValue &Val, Type *Ty, uint32_t OffsetInBits,
               /*TagBits=*/nullptr);
   } else if (Ty->isPointerTy()) {
     auto &AddressBits = Val.asPointer().address();
-    if (auto *MO = Val.asPointer().getMemoryObject()) {
-      APInt Tag = getTag(AddressBits.getBitWidth(), MO);
-      if (NeedsPadding)
-        Tag = Tag.zext(NewOffsetInBits - OffsetInBits);
-      WriteBits(NeedsPadding ? AddressBits.zext(NewOffsetInBits - OffsetInBits)
-                             : AddressBits,
-                &Tag);
-    } else {
-      WriteBits(NeedsPadding ? AddressBits.zext(NewOffsetInBits - OffsetInBits)
-                             : AddressBits,
-                /*TagBits=*/nullptr);
-    }
+    APInt Tag = getTag(AddressBits.getBitWidth(), Val.asPointer().components());
+    if (NeedsPadding)
+      Tag = Tag.zext(NewOffsetInBits - OffsetInBits);
+    WriteBits(NeedsPadding ? AddressBits.zext(NewOffsetInBits - OffsetInBits)
+                           : AddressBits,
+              &Tag);
   } else {
     llvm_unreachable("Unsupported scalar type.");
   }
@@ -547,15 +543,23 @@ bool Context::free(const MemoryObject &Obj) {
     return false;
 
   UsedMem -= std::max(It->second->getSize(), static_cast<uint64_t>(1));
-  It->second->markAsFreed();
+
+  MemoryObject &MutableObj = *It->second;
+  MutableObj.State = MemoryObjectState::Freed;
+  MutableObj.Bytes.clear();
+  for (const APInt &Tag : MutableObj.AssociatedTags)
+    TaggedPointerComponents.erase(Tag);
+  MutableObj.AssociatedTags.clear();
+
   MemoryObjects.erase(It);
   return true;
 }
 
 Pointer Context::deriveFromMemoryObject(IntrusiveRefCntPtr<MemoryObject> Obj) {
   assert(Obj && "Cannot determine the address space of a null memory object");
-  return Pointer(Obj, APInt(DL.getPointerSizeInBits(Obj->getAddressSpace()),
-                            Obj->getAddress()));
+  return Pointer(makeIntrusiveRefCnt<PointerComponents>(Obj),
+                 APInt(DL.getPointerSizeInBits(Obj->getAddressSpace()),
+                       Obj->getAddress()));
 }
 
 Function *Context::getTargetFunction(const Pointer &Ptr) {
@@ -630,11 +634,6 @@ uint64_t Context::getRandomUInt64() {
   return 0;
 }
 
-void MemoryObject::markAsFreed() {
-  State = MemoryObjectState::Freed;
-  Bytes.clear();
-}
-
 bool MemoryObject::isGlobal() const {
   return AllocKind == MemAllocKind::Global;
 }
diff --git a/llvm/tools/llubi/lib/Context.h b/llvm/tools/llubi/lib/Context.h
index ad2d303b452a4..e0fe272a75019 100644
--- a/llvm/tools/llubi/lib/Context.h
+++ b/llvm/tools/llubi/lib/Context.h
@@ -108,16 +108,11 @@ class MemoryObject : public RefCountedBase<MemoryObject> {
   MemAllocKind AllocKind;
   bool IsConstant = false;
 
-  // A tag is a randomly generated unique identifier to recover the provenance
-  // of a pointer. The length of tag is equal to the store size of the pointer
-  // type, in bits. It may produce false negatives in some corner cases. But in
-  // real practice the false negative rate should be negligible.
-  // A zero tag is invalid.
-  // TODO: we need a tag->provenance mapping instead of assigning a tag to each
-  // memory object.
-  // TODO: we need a special tag encoding for wildcard provenance, which is
-  // introduced by inttoptr.
-  APInt Tag;
+  // Tagged pointer components related to this memory object.
+  // It is used to erasing the tags after the memory object is freed.
+  SmallVector<APInt> AssociatedTags;
+
+  friend class Context;
 
 public:
   MemoryObject(uint64_t Addr, uint64_t Size, StringRef Name, unsigned AS,
@@ -137,8 +132,6 @@ class MemoryObject : public RefCountedBase<MemoryObject> {
   MemAllocKind getAllocKind() const { return AllocKind; }
   bool isConstant() const { return IsConstant; }
   void setIsConstant(bool C) { IsConstant = C; }
-  const APInt &getTag() const { return Tag; }
-  void setTag(const APInt &T) { Tag = T; }
 
   bool inBounds(const APInt &NewAddr) const {
     return NewAddr.uge(Address) && NewAddr.ule(Address + Size);
@@ -151,8 +144,6 @@ class MemoryObject : public RefCountedBase<MemoryObject> {
   ArrayRef<Byte> getBytes() const { return Bytes; }
   MutableArrayRef<Byte> getBytes() { return Bytes; }
 
-  void markAsFreed();
-
   bool isGlobal() const;
   bool isStackAllocated() const;
   bool isHeapAllocated() const;
@@ -238,15 +229,15 @@ class Context {
   uint64_t AllocationBase = 8;
   // All live memory objects.
   DenseMap<uint64_t, IntrusiveRefCntPtr<MemoryObject>> MemoryObjects;
-  // Mapping from tags to memory objects. Tags are lazily generated when a
+  // Mapping from tags to pointer components. Tags are lazily generated when a
   // pointer is captured by memory.
-  DenseMap<APInt, IntrusiveRefCntPtr<MemoryObject>> TaggedMemoryObjects;
+  DenseMap<APInt, IntrusiveRefCntPtr<PointerComponents>>
+      TaggedPointerComponents;
   // TODO: Maintains a global list of 'exposed' provenances. This is used to
   // convert an address back to a pointer with a previously exposed provenance.
 
-  /// Get the tag for a pointer to the given memory object.
-  /// TODO: encode metadata bits into the tag.
-  APInt getTag(uint32_t BitWidth, MemoryObject *Obj);
+  /// Get the tag for the given pointer metadata.
+  APInt getTag(uint32_t BitWidth, PointerComponents &Comp);
   AnyValue fromBytes(ConstBytesView Bytes, Type *Ty, uint32_t OffsetInBits,
                      bool CheckPaddingBits, bool *ContainsUndefinedBits);
   void toBytes(const AnyValue &Val, Type *Ty, uint32_t OffsetInBits,
diff --git a/llvm/tools/llubi/lib/Value.cpp b/llvm/tools/llubi/lib/Value.cpp
index 1bc835b662b51..37d042c16690d 100644
--- a/llvm/tools/llubi/lib/Value.cpp
+++ b/llvm/tools/llubi/lib/Value.cpp
@@ -16,11 +16,17 @@
 
 namespace llvm::ubi {
 
+IntrusiveRefCntPtr<PointerComponents> PointerComponents::nullary() {
+  static IntrusiveRefCntPtr<PointerComponents> Instance =
+      makeIntrusiveRefCnt<PointerComponents>(nullptr);
+  return Instance;
+}
+
 void Pointer::print(raw_ostream &OS) const {
   SmallString<32> AddrStr;
   Address.toStringUnsigned(AddrStr, 16);
   OS << "ptr 0x" << AddrStr << " [";
-  if (Obj) {
+  if (MemoryObject *Obj = getMemoryObject()) {
     OS << Obj->getName();
     if (Address != Obj->getAddress())
       OS << " + " << (Address - Obj->getAddress());
@@ -34,7 +40,8 @@ void Pointer::print(raw_ostream &OS) const {
 }
 
 AnyValue Pointer::null(unsigned AS, const DataLayout &DL) {
-  return AnyValue(Pointer(nullptr, DL.getNullPtrValue(AS)));
+  return AnyValue(
+      Pointer(PointerComponents::nullary(), DL.getNullPtrValue(AS)));
 }
 
 bool Pointer::isNullPtr(unsigned AS, const DataLayout &DL) const {
diff --git a/llvm/tools/llubi/lib/Value.h b/llvm/tools/llubi/lib/Value.h
index 59d9a5c5f46fd..33ac5252b0b18 100644
--- a/llvm/tools/llubi/lib/Value.h
+++ b/llvm/tools/llubi/lib/Value.h
@@ -104,27 +104,65 @@ enum class StorageKind {
 /// Tri-state boolean value.
 enum class BooleanKind { False, True, Poison };
 
-class Pointer {
+/// Components of a pointer excluding address.
+/// Each node will be assigned a unique, pointer-sized tag, which is used to
+/// represent the pointer in the memory.
+class PointerComponents : public RefCountedBase<PointerComponents> {
+  // TODO: store reference to the components of the pointer it is derived from
+
   // The underlying memory object. It can be null for invalid or dangling
   // pointers.
   IntrusiveRefCntPtr<MemoryObject> Obj;
+
+  // A tag is a randomly generated unique identifier to recover the provenance
+  // of a pointer. The length of tag is equal to the store size of the pointer
+  // type, in bits. It may produce false negatives in some corner cases. But in
+  // real practice the false negative rate should be negligible.
+  // A zero tag is invalid.
+  // TODO: we need a special tag for wildcard provenance, which is introduced by
+  // inttoptr.
+  APInt Tag;
+
+  // TODO: modeling nofree
+  // TODO: modeling captures
+  // TODO: modeling inrange(Start, End) attribute
+
+  const APInt &getTag() const { return Tag; }
+  void setTag(const APInt &T) { Tag = T; }
+
+  friend class Context;
+
+public:
+  PointerComponents(IntrusiveRefCntPtr<MemoryObject> Obj)
+      : Obj(std::move(Obj)) {}
+  static IntrusiveRefCntPtr<PointerComponents> nullary();
+  MemoryObject *getMemoryObject() const { return Obj.get(); }
+};
+
+class Pointer {
+  // Components of a pointer excluding address.
+  IntrusiveRefCntPtr<PointerComponents> Metadata;
   // The address of the pointer. The bit width is determined by
   // DataLayout::getPointerSizeInBits.
   APInt Address;
-  // TODO: modeling inrange(Start, End) attribute
 
 public:
-  explicit Pointer(const APInt &Address) : Obj(nullptr), Address(Address) {}
-  explicit Pointer(IntrusiveRefCntPtr<MemoryObject> Obj, const APInt &Address)
-      : Obj(std::move(Obj)), Address(Address) {}
+  explicit Pointer(const APInt &Address)
+      : Metadata(PointerComponents::nullary()), Address(Address) {}
+  explicit Pointer(IntrusiveRefCntPtr<PointerComponents> Metadata,
+                   const APInt &Address)
+      : Metadata(std::move(Metadata)), Address(Address) {
+    assert(this->Metadata && "Invalid pointer components.");
+  }
   Pointer getWithNewAddr(const APInt &NewAddr) const {
-    return Pointer(Obj, NewAddr);
+    return Pointer(Metadata, NewAddr);
   }
   static AnyValue null(unsigned AS, const DataLayout &DL);
   bool isNullPtr(unsigned AS, const DataLayout &DL) const;
   void print(raw_ostream &OS) const;
   const APInt &address() const { return Address; }
-  MemoryObject *getMemoryObject() const { return Obj.get(); }
+  PointerComponents &components() const { return *Metadata; }
+  MemoryObject *getMemoryObject() const { return Metadata->getMemoryObject(); }
 };
 
 // Value representation for actual values of LLVM values.



More information about the llvm-commits mailing list