[clang] [compiler-rt] [compiler-rt:ubsan] Add -fsanitize=unaligned-pointer-subtraction to detect undefined subtraction of two pointers (PR #210635)

Vitaly Buka via cfe-commits cfe-commits at lists.llvm.org
Sat Nov 28 14:27:05 PST 2026


================
@@ -5062,7 +5063,29 @@ Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
     divisor = CGF.CGM.getSize(elementSize);
   }
 
-  if (CGF.getLangOpts().StablePointerSubtraction)
+  // If the pointer-subtraction sanitizer is on, verify at runtime that the
+  // byte distance is an exact multiple of the element size. Zero-sized element
+  // types (a GNU extension) have no meaningful multiple, so don't emit a
+  // remainder by zero for them.
+  bool CheckSubtraction = CGF.SanOpts.has(SanitizerKind::PointerSubtraction);
+  auto *ConstDivisor = dyn_cast<llvm::ConstantInt>(divisor);
+  if (CheckSubtraction && !(ConstDivisor && ConstDivisor->isZero())) {
+    auto CheckOrdinal = SanitizerKind::SO_PointerSubtraction;
+    auto CheckHandler = SanitizerHandler::PointerSubtraction;
+    SanitizerDebugLocation SanScope(&CGF, {CheckOrdinal}, CheckHandler);
+
+    llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
+    llvm::Value *Rem = Builder.CreateSRem(diffInChars, divisor, "sub.ptr.rem");
+    llvm::Value *IsExact = Builder.CreateICmpEQ(Rem, Zero, "sub.ptr.exact");
+
+    llvm::Constant *StaticArgs[] = {
+        CGF.EmitCheckSourceLocation(op.E->getExprLoc())};
+    llvm::Value *DynamicArgs[] = {diffInChars, divisor};
+    CGF.EmitCheck({{IsExact, CheckOrdinal}}, CheckHandler, StaticArgs,
+                  DynamicArgs);
+  }
+
+  if (CGF.getLangOpts().StablePointerSubtraction || CheckSubtraction)
----------------
vitalybuka wrote:

Do we still want CheckSubtraction here to drop exact from sdiv in all modes (including abort and trap), or should we keep CreateExactSDiv unless StablePointerSubtraction is set?

https://github.com/llvm/llvm-project/pull/210635


More information about the cfe-commits mailing list