[llvm] [CodeGen] Use byte offsets and ptradd in ShadowStackGCLowering (PR #178436)

Jameson Nash via llvm-commits llvm-commits at lists.llvm.org
Wed Jan 28 06:29:04 PST 2026


https://github.com/vtjnash created https://github.com/llvm/llvm-project/pull/178436

Replace typed struct GEPs with byte array allocation and ptradd operations:

1. Track root offsets as byte offsets instead of building typed struct.
2. Use `ComputeFrameLayout` to compute byte offsets based on DataLayout, properly accounting for each root's size and alignment.
3. Allocate frame as `[FrameSize x i8]` byte array instead of typed struct.
4. Replace all CreateGEP operations with CreatePtrAdd using computed offsets.
5. Frame layout unchanged: `[Next ptr | Map ptr | Root 0 | Root 1 | ... | Root N]` where each root is placed at its computed aligned offset.
6. Zero out padding between roots with memset for deterministic frame contents for GC.

Benefits:
- Removes dependency on `getAllocatedType` for building frame struct
- Properly handles root alignment requirements (implements a TODO in code)

Apparently this is an upside (or downside) of leaving a TODO behind in the code, since AI goes and implements it when the refactoring happened to make it much more trivial to do.

>From 60e27d5aa8933cb671d983704b99cca7135f6515 Mon Sep 17 00:00:00 2001
From: Jameson Nash <vtjnash+github at gmail.com>
Date: Wed, 28 Jan 2026 03:25:23 +0000
Subject: [PATCH] [CodeGen] Use byte offsets and ptradd in
 ShadowStackGCLowering

Replace typed struct GEPs with byte array allocation and ptradd
operations:

1. Track root offsets as byte offsets instead of building typed struct.
2. Use `ComputeFrameLayout` to compute byte offsets based on DataLayout,
   properly accounting for each root's size and alignment.
3. Allocate frame as `[FrameSize x i8]` byte array instead of typed
   struct.
4. Replace all CreateGEP operations with CreatePtrAdd using computed
   offsets.
5. Frame layout unchanged:
   `[Next ptr | Map ptr | Root 0 | Root 1 | ... | Root N]`
   where each root is placed at its computed aligned offset.
6. Zero out padding between roots with memset for deterministic frame
   contents for GC.

Benefits:
- Removes dependency on `getAllocatedType` for building frame struct
- Properly handles root alignment requirements (fixes TODO in code)

Co-Authored-By: Claude Sonnet 4.5 <noreply at anthropic.com>
---
 llvm/lib/CodeGen/ShadowStackGCLowering.cpp | 187 +++++++++++----------
 1 file changed, 101 insertions(+), 86 deletions(-)

diff --git a/llvm/lib/CodeGen/ShadowStackGCLowering.cpp b/llvm/lib/CodeGen/ShadowStackGCLowering.cpp
index 6097468626e0a..38a4c2e64f3da 100644
--- a/llvm/lib/CodeGen/ShadowStackGCLowering.cpp
+++ b/llvm/lib/CodeGen/ShadowStackGCLowering.cpp
@@ -24,6 +24,7 @@
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/Constant.h"
 #include "llvm/IR/Constants.h"
+#include "llvm/IR/DataLayout.h"
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/Dominators.h"
 #include "llvm/IR/Function.h"
@@ -38,7 +39,9 @@
 #include "llvm/IR/Value.h"
 #include "llvm/InitializePasses.h"
 #include "llvm/Pass.h"
+#include "llvm/Support/Alignment.h"
 #include "llvm/Support/Casting.h"
+#include "llvm/Support/MathExtras.h"
 #include "llvm/Transforms/Utils/EscapeEnumerator.h"
 #include <cassert>
 #include <optional>
@@ -56,14 +59,16 @@ class ShadowStackGCLoweringImpl {
   /// roots.
   GlobalVariable *Head = nullptr;
 
-  /// StackEntryTy - Abstract type of a link in the shadow stack.
-  StructType *StackEntryTy = nullptr;
   StructType *FrameMapTy = nullptr;
 
   /// Roots - GC roots in the current function. Each is a pair of the
   /// intrinsic call and its corresponding alloca.
   std::vector<std::pair<CallInst *, AllocaInst *>> Roots;
 
+  /// RootOffsets - Byte offsets and sizes of each root within the frame.
+  /// Each element is a pair of (offset, size).
+  std::vector<std::pair<uint64_t, uint64_t>> RootOffsets;
+
 public:
   ShadowStackGCLoweringImpl() = default;
 
@@ -72,16 +77,9 @@ class ShadowStackGCLoweringImpl {
 
 private:
   bool IsNullValue(Value *V);
-  Constant *GetFrameMap(Function &F);
-  Type *GetConcreteStackEntryType(Function &F);
+  Constant *GetFrameMap(Function &F, uint64_t FrameSizeInPtrs);
+  std::pair<uint64_t, Align> ComputeFrameLayout(Function &F);
   void CollectRoots(Function &F);
-
-  static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
-                                      Type *Ty, Value *BasePtr, int Idx1,
-                                      const char *Name);
-  static GetElementPtrInst *CreateGEP(LLVMContext &Context, IRBuilder<> &B,
-                                      Type *Ty, Value *BasePtr, int Idx1, int Idx2,
-                                      const char *Name);
 };
 
 class ShadowStackGCLowering : public FunctionPass {
@@ -143,7 +141,8 @@ FunctionPass *llvm::createShadowStackGCLoweringPass() { return new ShadowStackGC
 
 ShadowStackGCLowering::ShadowStackGCLowering() : FunctionPass(ID) {}
 
-Constant *ShadowStackGCLoweringImpl::GetFrameMap(Function &F) {
+Constant *ShadowStackGCLoweringImpl::GetFrameMap(Function &F,
+                                                 uint64_t FrameSizeInPtrs) {
   // doInitialization creates the abstract type of this value.
   Type *VoidPtr = PointerType::getUnqual(F.getContext());
 
@@ -161,7 +160,7 @@ Constant *ShadowStackGCLoweringImpl::GetFrameMap(Function &F) {
   Type *Int32Ty = Type::getInt32Ty(F.getContext());
 
   Constant *BaseElts[] = {
-      ConstantInt::get(Int32Ty, Roots.size(), false),
+      ConstantInt::get(Int32Ty, FrameSizeInPtrs, false),
       ConstantInt::get(Int32Ty, NumMeta, false),
   };
 
@@ -197,14 +196,44 @@ Constant *ShadowStackGCLoweringImpl::GetFrameMap(Function &F) {
   return ConstantExpr::getGetElementPtr(FrameMap->getType(), GV, GEPIndices);
 }
 
-Type *ShadowStackGCLoweringImpl::GetConcreteStackEntryType(Function &F) {
-  // doInitialization creates the generic version of this type.
-  std::vector<Type *> EltTys;
-  EltTys.push_back(StackEntryTy);
-  for (const std::pair<CallInst *, AllocaInst *> &Root : Roots)
-    EltTys.push_back(Root.second->getAllocatedType());
+std::pair<uint64_t, Align>
+ShadowStackGCLoweringImpl::ComputeFrameLayout(Function &F) {
+  // Compute the layout of the shadow stack frame using byte offsets.
+  // Layout: [Next ptr | Map ptr | Root 0 | Root 1 | ... | Root N]
+
+  const DataLayout &DL = F.getParent()->getDataLayout();
+  uint64_t PtrSize = DL.getPointerSize(0);
+  Align PtrAlign = DL.getPointerABIAlignment(0);
+
+  RootOffsets.clear();
+  Align MaxAlign = PtrAlign;
+
+  // Offset 0: Next pointer
+  // Offset PtrSize: Map pointer
+  uint64_t Offset = 2 * PtrSize;
+
+  // Compute offsets and sizes for each root
+  for (const std::pair<CallInst *, AllocaInst *> &Root : Roots) {
+    AllocaInst *AI = Root.second;
+    std::optional<TypeSize> RootSize = AI->getAllocationSize(DL);
+    if (!RootSize || !RootSize->isFixed())
+      reportFatalUsageError(
+          "Intrinsic::gcroot requires a fixed size stack object");
+    uint64_t Size = RootSize->getFixedValue();
+    Align RootAlign = AI->getAlign();
+    MaxAlign = std::max(MaxAlign, RootAlign);
+
+    // Align the offset for this root
+    uint64_t AlignedOffset = alignTo(Offset, RootAlign);
+
+    // Store both offset and size as a pair
+    RootOffsets.push_back({AlignedOffset, Size});
+    Offset = AlignedOffset + Size;
+  }
 
-  return StructType::create(EltTys, ("gc_stackentry." + F.getName()).str());
+  // Final frame size, aligned to maximum alignment
+  uint64_t FrameSize = alignTo(Offset, MaxAlign);
+  return {FrameSize, MaxAlign};
 }
 
 /// doInitialization - If this module uses the GC intrinsics, find them now. If
@@ -231,21 +260,11 @@ bool ShadowStackGCLoweringImpl::doInitialization(Module &M) {
   // Specifies length of variable length array.
   EltTys.push_back(Type::getInt32Ty(M.getContext()));
   FrameMapTy = StructType::create(EltTys, "gc_map");
-  PointerType *FrameMapPtrTy = PointerType::getUnqual(M.getContext());
-
-  // struct StackEntry {
-  //   ShadowStackEntry *Next; // Caller's stack entry.
-  //   FrameMap *Map;          // Pointer to constant FrameMap.
-  //   void *Roots[];          // Stack roots (in-place array, so we pretend).
-  // };
 
+  // The shadow stack linked list uses opaque pointers.
+  // Each frame is a byte array with: [Next ptr | Map ptr | Roots...]
   PointerType *StackEntryPtrTy = PointerType::getUnqual(M.getContext());
 
-  EltTys.clear();
-  EltTys.push_back(StackEntryPtrTy);
-  EltTys.push_back(FrameMapPtrTy);
-  StackEntryTy = StructType::create(EltTys, "gc_stackentry");
-
   // Get the root chain if it already exists.
   Head = M.getGlobalVariable("llvm_gc_root_chain");
   if (!Head) {
@@ -269,10 +288,6 @@ bool ShadowStackGCLoweringImpl::IsNullValue(Value *V) {
 }
 
 void ShadowStackGCLoweringImpl::CollectRoots(Function &F) {
-  // FIXME: Account for original alignment. Could fragment the root array.
-  //   Approach 1: Null initialize empty slots at runtime. Yuck.
-  //   Approach 2: Emit a map of the array instead of just a count.
-
   assert(Roots.empty() && "Not cleaned up?");
 
   SmallVector<std::pair<CallInst *, AllocaInst *>, 16> MetaRoots;
@@ -296,34 +311,6 @@ void ShadowStackGCLoweringImpl::CollectRoots(Function &F) {
   Roots.insert(Roots.begin(), MetaRoots.begin(), MetaRoots.end());
 }
 
-GetElementPtrInst *
-ShadowStackGCLoweringImpl::CreateGEP(LLVMContext &Context, IRBuilder<> &B,
-                                     Type *Ty, Value *BasePtr, int Idx,
-                                     int Idx2, const char *Name) {
-  Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
-                      ConstantInt::get(Type::getInt32Ty(Context), Idx),
-                      ConstantInt::get(Type::getInt32Ty(Context), Idx2)};
-  Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name);
-
-  assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
-
-  return dyn_cast<GetElementPtrInst>(Val);
-}
-
-GetElementPtrInst *ShadowStackGCLoweringImpl::CreateGEP(LLVMContext &Context,
-                                                        IRBuilder<> &B,
-                                                        Type *Ty,
-                                                        Value *BasePtr, int Idx,
-                                                        const char *Name) {
-  Value *Indices[] = {ConstantInt::get(Type::getInt32Ty(Context), 0),
-                      ConstantInt::get(Type::getInt32Ty(Context), Idx)};
-  Value *Val = B.CreateGEP(Ty, BasePtr, Indices, Name);
-
-  assert(isa<GetElementPtrInst>(Val) && "Unexpected folded constant");
-
-  return dyn_cast<GetElementPtrInst>(Val);
-}
-
 /// runOnFunction - Insert code to maintain the shadow stack.
 bool ShadowStackGCLoweringImpl::runOnFunction(Function &F,
                                               DomTreeUpdater *DTU) {
@@ -332,6 +319,7 @@ bool ShadowStackGCLoweringImpl::runOnFunction(Function &F,
     return false;
 
   LLVMContext &Context = F.getContext();
+  const DataLayout &DL = F.getParent()->getDataLayout();
 
   // Find calls to llvm.gcroot.
   CollectRoots(F);
@@ -341,16 +329,20 @@ bool ShadowStackGCLoweringImpl::runOnFunction(Function &F,
   if (Roots.empty())
     return false;
 
-  // Build the constant map and figure the type of the shadow stack entry.
-  Value *FrameMap = GetFrameMap(F);
-  Type *ConcreteStackEntryTy = GetConcreteStackEntryType(F);
+  // Compute frame layout using byte offsets first.
+  auto [FrameSize, FrameAlign] = ComputeFrameLayout(F);
+
+  // Build the constant map with frame size in pointer-sized units.
+  uint64_t PtrSize = DL.getPointerSize();
+  Value *FrameMap = GetFrameMap(F, FrameSize / PtrSize);
 
   // Build the shadow stack entry at the very start of the function.
   BasicBlock::iterator IP = F.getEntryBlock().begin();
   IRBuilder<> AtEntry(IP->getParent(), IP);
-
-  Instruction *StackEntry =
-      AtEntry.CreateAlloca(ConcreteStackEntryTy, nullptr, "gc_frame");
+  Type *Int8Ty = Type::getInt8Ty(Context);
+  AllocaInst *StackEntry = AtEntry.CreateAlloca(
+      ArrayType::get(Int8Ty, FrameSize), nullptr, "gc_frame");
+  StackEntry->setAlignment(FrameAlign);
 
   AtEntry.SetInsertPointPastAllocas(&F);
   IP = AtEntry.GetInsertPoint();
@@ -358,20 +350,45 @@ bool ShadowStackGCLoweringImpl::runOnFunction(Function &F,
   // Initialize the map pointer and load the current head of the shadow stack.
   Instruction *CurrentHead =
       AtEntry.CreateLoad(AtEntry.getPtrTy(), Head, "gc_currhead");
-  Instruction *EntryMapPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
-                                       StackEntry, 0, 1, "gc_frame.map");
+
+  // Map pointer is at offset PtrSize (after the Next pointer)
+  Value *EntryMapPtr = AtEntry.CreatePtrAdd(
+      StackEntry, AtEntry.getInt64(PtrSize), "gc_frame.map");
   AtEntry.CreateStore(FrameMap, EntryMapPtr);
 
-  // After all the allocas...
+  // Zero out any padding between roots to ensure deterministic frame contents.
+  // This includes the region after the map pointer up to the first root.
+  uint64_t LastEnd = 2 * PtrSize; // End of Map pointer field
+  assert(RootOffsets.size() == Roots.size());
   for (unsigned I = 0, E = Roots.size(); I != E; ++I) {
-    // For each root, find the corresponding slot in the aggregate...
-    Value *SlotPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
-                               StackEntry, 1 + I, "gc_root");
+    auto [RootOffset, RootSize] = RootOffsets[I];
+
+    // Zero any padding before this root
+    if (RootOffset > LastEnd) {
+      Value *PaddingPtr =
+          AtEntry.CreatePtrAdd(StackEntry, AtEntry.getInt64(LastEnd));
+      AtEntry.CreateMemSet(PaddingPtr, AtEntry.getInt8(0),
+                           RootOffset - LastEnd, Align(1));
+    }
+
+    // For each root, compute pointer using precomputed offset
+    Value *SlotPtr =
+        AtEntry.CreatePtrAdd(StackEntry, AtEntry.getInt64(RootOffset), "gc_root");
 
     // And use it in lieu of the alloca.
     AllocaInst *OriginalAlloca = Roots[I].second;
     SlotPtr->takeName(OriginalAlloca);
     OriginalAlloca->replaceAllUsesWith(SlotPtr);
+
+    LastEnd = RootOffset + RootSize;
+  }
+
+  // Zero any padding at the end of the frame
+  if (FrameSize > LastEnd) {
+    Value *PaddingPtr =
+        AtEntry.CreatePtrAdd(StackEntry, AtEntry.getInt64(LastEnd));
+    AtEntry.CreateMemSet(PaddingPtr, AtEntry.getInt8(0), FrameSize - LastEnd,
+                         Align(1));
   }
 
   // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
@@ -383,23 +400,20 @@ bool ShadowStackGCLoweringImpl::runOnFunction(Function &F,
   AtEntry.SetInsertPoint(IP->getParent(), IP);
 
   // Push the entry onto the shadow stack.
-  Instruction *EntryNextPtr = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
-                                        StackEntry, 0, 0, "gc_frame.next");
-  Instruction *NewHeadVal = CreateGEP(Context, AtEntry, ConcreteStackEntryTy,
-                                      StackEntry, 0, "gc_newhead");
-  AtEntry.CreateStore(CurrentHead, EntryNextPtr);
-  AtEntry.CreateStore(NewHeadVal, Head);
+  // Next pointer is at offset 0, so it's just the frame pointer
+  AtEntry.CreateStore(CurrentHead, StackEntry);
+  // The new head value is also the frame pointer (the linked list links to
+  // frame base)
+  AtEntry.CreateStore(StackEntry, Head);
 
   // For each instruction that escapes...
   EscapeEnumerator EE(F, "gc_cleanup", /*HandleExceptions=*/true, DTU);
   while (IRBuilder<> *AtExit = EE.Next()) {
     // Pop the entry from the shadow stack. Don't reuse CurrentHead from
     // AtEntry, since that would make the value live for the entire function.
-    Instruction *EntryNextPtr2 =
-        CreateGEP(Context, *AtExit, ConcreteStackEntryTy, StackEntry, 0, 0,
-                  "gc_frame.next");
+    // Next pointer is at offset 0, so load from the frame base
     Value *SavedHead =
-        AtExit->CreateLoad(AtExit->getPtrTy(), EntryNextPtr2, "gc_savedhead");
+        AtExit->CreateLoad(AtExit->getPtrTy(), StackEntry, "gc_savedhead");
     AtExit->CreateStore(SavedHead, Head);
   }
 
@@ -412,5 +426,6 @@ bool ShadowStackGCLoweringImpl::runOnFunction(Function &F,
   }
 
   Roots.clear();
+  RootOffsets.clear();
   return true;
 }



More information about the llvm-commits mailing list