[clang] [llvm] [Clang][Driver] Clear group bits from parseSanitizeArgs (PR #245495)

Vitaly Buka via cfe-commits cfe-commits at lists.llvm.org
Mon Nov 23 22:05:36 PST 2026


https://github.com/vitalybuka updated https://github.com/llvm/llvm-project/pull/245495

>From f0fa4c283108986e6bd066f8127cc3ded891a113 Mon Sep 17 00:00:00 2001
From: Vitaly Buka <vitalybuka at google.com>
Date: Mon, 23 Nov 2026 21:39:17 -0800
Subject: [PATCH 1/4] [spr] update

Created using spr 2.0.0-beta.2
---
 llvm/lib/Transforms/Instrumentation/KCFI.cpp | 107 ++++++++++---------
 1 file changed, 58 insertions(+), 49 deletions(-)

diff --git a/llvm/lib/Transforms/Instrumentation/KCFI.cpp b/llvm/lib/Transforms/Instrumentation/KCFI.cpp
index 61acbe0b9d3582..fa54849b163f39 100644
--- a/llvm/lib/Transforms/Instrumentation/KCFI.cpp
+++ b/llvm/lib/Transforms/Instrumentation/KCFI.cpp
@@ -23,7 +23,7 @@
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/MDBuilder.h"
 #include "llvm/IR/Module.h"
-#include "llvm/Target/TargetMachine.h"
+#include "llvm/TargetParser/Triple.h"
 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
 
 using namespace llvm;
@@ -44,22 +44,61 @@ class DiagnosticInfoKCFI : public DiagnosticInfo {
 };
 } // namespace
 
-PreservedAnalyses KCFIPass::run(Function &F, FunctionAnalysisManager &AM) {
-  Module &M = *F.getParent();
-  if (!M.getModuleFlag("kcfi"))
-    return PreservedAnalyses::all();
+static void lowerTrapCheck(CallInst *CI, const Triple &T, IntegerType *Int32Ty,
+                           MDNode *VeryUnlikelyWeights) {
+  // Get the expected hash value.
+  const uint32_t ExpectedHash =
+      cast<ConstantInt>(CI->getOperandBundle(LLVMContext::OB_kcfi)->Inputs[0])
+          ->getZExtValue();
+
+  // Drop the KCFI operand bundle.
+  CallBase *Call = CallBase::removeOperandBundle(CI, LLVMContext::OB_kcfi,
+                                                 CI->getIterator());
+  assert(Call != CI);
+  Call->copyMetadata(*CI);
+  CI->replaceAllUsesWith(Call);
+  CI->eraseFromParent();
+
+  if (!Call->isIndirectCall())
+    return;
+
+  // Emit a check and trap if the target hash doesn't match.
+  IRBuilder<> Builder(Call);
+  Builder.disableGEPCanonicalization();
+  Value *FuncPtr = Call->getCalledOperand();
+  // ARM uses the least significant bit of the function pointer to select
+  // between ARM and Thumb modes for the callee. Instructions are always
+  // at least 16-bit aligned, so clear the LSB before we compute the hash
+  // location.
+  if (T.isARM() || T.isThumb()) {
+    FuncPtr = Builder.CreateIntToPtr(
+        Builder.CreateAnd(Builder.CreatePtrToInt(FuncPtr, Int32Ty),
+                          ConstantInt::getSigned(Int32Ty, -2)),
+        FuncPtr->getType());
+  }
+  Value *HashPtr = Builder.CreateConstInBoundsGEP1_32(Int32Ty, FuncPtr, -1);
+  Value *Test = Builder.CreateICmpNE(Builder.CreateLoad(Int32Ty, HashPtr),
+                                     ConstantInt::get(Int32Ty, ExpectedHash));
+  Instruction *ThenTerm =
+      SplitBlockAndInsertIfThen(Test, Call, false, VeryUnlikelyWeights);
+  Builder.SetInsertPoint(ThenTerm);
+  Builder.CreateIntrinsic(Intrinsic::debugtrap, {});
+  ++NumKCFIChecks;
+}
 
+static bool lowerTrapBundles(Function &F) {
   // Find call instructions with KCFI operand bundles.
-  SmallVector<CallInst *> KCFICalls;
+  SmallVector<CallInst *> TrapCalls;
   for (Instruction &I : instructions(F)) {
     if (auto *CI = dyn_cast<CallInst>(&I))
       if (CI->getOperandBundle(LLVMContext::OB_kcfi))
-        KCFICalls.push_back(CI);
+        TrapCalls.push_back(CI);
   }
 
-  if (KCFICalls.empty())
-    return PreservedAnalyses::all();
+  if (TrapCalls.empty())
+    return false;
 
+  Module &M = *F.getParent();
   LLVMContext &Ctx = M.getContext();
   // patchable-function-prefix emits nops between the KCFI type identifier
   // and the function start. As we don't know the size of the emitted nops,
@@ -73,46 +112,16 @@ PreservedAnalyses KCFIPass::run(Function &F, FunctionAnalysisManager &AM) {
   MDNode *VeryUnlikelyWeights = MDBuilder(Ctx).createUnlikelyBranchWeights();
   Triple T(M.getTargetTriple());
 
-  for (CallInst *CI : KCFICalls) {
-    // Get the expected hash value.
-    const uint32_t ExpectedHash =
-        cast<ConstantInt>(CI->getOperandBundle(LLVMContext::OB_kcfi)->Inputs[0])
-            ->getZExtValue();
-
-    // Drop the KCFI operand bundle.
-    CallBase *Call = CallBase::removeOperandBundle(CI, LLVMContext::OB_kcfi,
-                                                   CI->getIterator());
-    assert(Call != CI);
-    Call->copyMetadata(*CI);
-    CI->replaceAllUsesWith(Call);
-    CI->eraseFromParent();
-
-    if (!Call->isIndirectCall())
-      continue;
-
-    // Emit a check and trap if the target hash doesn't match.
-    IRBuilder<> Builder(Call);
-    Builder.disableGEPCanonicalization();
-    Value *FuncPtr = Call->getCalledOperand();
-    // ARM uses the least significant bit of the function pointer to select
-    // between ARM and Thumb modes for the callee. Instructions are always
-    // at least 16-bit aligned, so clear the LSB before we compute the hash
-    // location.
-    if (T.isARM() || T.isThumb()) {
-      FuncPtr = Builder.CreateIntToPtr(
-          Builder.CreateAnd(Builder.CreatePtrToInt(FuncPtr, Int32Ty),
-                            ConstantInt::getSigned(Int32Ty, -2)),
-          FuncPtr->getType());
-    }
-    Value *HashPtr = Builder.CreateConstInBoundsGEP1_32(Int32Ty, FuncPtr, -1);
-    Value *Test = Builder.CreateICmpNE(Builder.CreateLoad(Int32Ty, HashPtr),
-                                       ConstantInt::get(Int32Ty, ExpectedHash));
-    Instruction *ThenTerm =
-        SplitBlockAndInsertIfThen(Test, Call, false, VeryUnlikelyWeights);
-    Builder.SetInsertPoint(ThenTerm);
-    Builder.CreateIntrinsic(Intrinsic::debugtrap, {});
-    ++NumKCFIChecks;
-  }
+  for (CallInst *CI : TrapCalls)
+    lowerTrapCheck(CI, T, Int32Ty, VeryUnlikelyWeights);
+  return true;
+}
+
+PreservedAnalyses KCFIPass::run(Function &F, FunctionAnalysisManager &AM) {
+  if (!F.getParent()->getModuleFlag("kcfi"))
+    return PreservedAnalyses::all();
 
+  if (!lowerTrapBundles(F))
+    return PreservedAnalyses::all();
   return PreservedAnalyses::none();
 }

>From e0602ef4e03a07efb1f97e6e6989ac37687ec9ff Mon Sep 17 00:00:00 2001
From: Vitaly Buka <vitalybuka at google.com>
Date: Mon, 23 Nov 2026 21:39:24 -0800
Subject: [PATCH 2/4] [spr] update

Created using spr 2.0.0-beta.2
---
 clang/lib/Driver/SanitizerArgs.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Driver/SanitizerArgs.cpp b/clang/lib/Driver/SanitizerArgs.cpp
index 251338edd6cdb1..7880af4192549d 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -369,7 +369,8 @@ static SanitizerMask parseSanitizeTrapArgs(const Driver &D,
 
   return parseSanitizeArgs(D, Args, DiagnoseErrors, TrappingDefault, AlwaysTrap,
                            NeverTrap, options::OPT_fsanitize_trap_EQ,
-                           options::OPT_fno_sanitize_trap_EQ);
+                           options::OPT_fno_sanitize_trap_EQ) &
+         TrappingSupported;
 }
 
 static SanitizerMaskCutoffs

>From fe8345c1361b9ca467036000dd31a8e82cc099ae Mon Sep 17 00:00:00 2001
From: Vitaly Buka <vitalybuka at google.com>
Date: Mon, 23 Nov 2026 22:01:02 -0800
Subject: [PATCH 3/4] [spr] update

Created using spr 2.0.0-beta.2
---
 clang/lib/Driver/SanitizerArgs.cpp | 13 ++++++++++---
 clang/test/Driver/fsanitize-trap.c |  9 +++++++++
 2 files changed, 19 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Driver/SanitizerArgs.cpp b/clang/lib/Driver/SanitizerArgs.cpp
index 7880af4192549d..5df712cb9578d3 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -303,6 +303,14 @@ static SanitizerMask setGroupBits(SanitizerMask Kinds) {
   return Kinds;
 }
 
+/// Clears group bits from \p Kinds.
+static SanitizerMask clearGroupBits(SanitizerMask Kinds) {
+#define SANITIZER(NAME, ID)
+#define SANITIZER_GROUP(NAME, ID, ALIAS) Kinds &= ~SanitizerKind::ID##Group;
+#include "clang/Basic/Sanitizers.def"
+  return Kinds;
+}
+
 // Computes the sanitizer mask as:
 //     Default + Arguments (in or out) + AlwaysIn - AlwaysOut
 // with arguments parsed from left to right.
@@ -358,7 +366,7 @@ parseSanitizeArgs(const Driver &D, const llvm::opt::ArgList &Args,
   Output |= AlwaysIn;
   Output &= ~AlwaysOut;
 
-  return Output;
+  return clearGroupBits(Output);
 }
 
 static SanitizerMask parseSanitizeTrapArgs(const Driver &D,
@@ -369,8 +377,7 @@ static SanitizerMask parseSanitizeTrapArgs(const Driver &D,
 
   return parseSanitizeArgs(D, Args, DiagnoseErrors, TrappingDefault, AlwaysTrap,
                            NeverTrap, options::OPT_fsanitize_trap_EQ,
-                           options::OPT_fno_sanitize_trap_EQ) &
-         TrappingSupported;
+                           options::OPT_fno_sanitize_trap_EQ);
 }
 
 static SanitizerMaskCutoffs
diff --git a/clang/test/Driver/fsanitize-trap.c b/clang/test/Driver/fsanitize-trap.c
index be13edeffdda05..a93e774fce2bdc 100644
--- a/clang/test/Driver/fsanitize-trap.c
+++ b/clang/test/Driver/fsanitize-trap.c
@@ -8,3 +8,12 @@
 // CHECK-UNDEFINED-TRAP: "-fsanitize={{((signed-integer-overflow|integer-divide-by-zero|shift-base|shift-exponent|unreachable|return|vla-bound|alignment|null|pointer-overflow|float-cast-overflow|array-bounds|enum|bool|builtin|returns-nonnull-attribute|nonnull-attribute|function),?){18}"}}
 // CHECK-UNDEFINED-TRAP: "-fsanitize-trap=alignment,array-bounds,bool,builtin,enum,float-cast-overflow,function,integer-divide-by-zero,nonnull-attribute,null,pointer-overflow,return,returns-nonnull-attribute,shift-base,shift-exponent,signed-integer-overflow,unreachable,vla-bound"
 // CHECK-UNDEFINED-TRAP2: "-fsanitize-trap=alignment,array-bounds,bool,builtin,enum,float-cast-overflow,function,integer-divide-by-zero,nonnull-attribute,null,pointer-overflow,return,returns-nonnull-attribute,shift-base,shift-exponent,unreachable,vla-bound"
+
+// Disabling every member of an enabled group must not leave a stale group bit
+// that emits an empty flag to cc1.
+// RUN: %clang --target=x86_64-linux-gnu -fsanitize=bounds -fsanitize-trap=bounds -fno-sanitize-trap=array-bounds,local-bounds -fsanitize-recover=bounds -fno-sanitize-recover=array-bounds,local-bounds -fsanitize-merge=bounds -fno-sanitize-merge=array-bounds,local-bounds -fsanitize-annotate-debug-info=bounds -fno-sanitize-annotate-debug-info=array-bounds,local-bounds %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-EMPTY-FLAGS
+// CHECK-NO-EMPTY-FLAGS: "-fsanitize=array-bounds,local-bounds"
+// CHECK-NO-EMPTY-FLAGS-NOT: "-fsanitize-trap=
+// CHECK-NO-EMPTY-FLAGS-NOT: "-fsanitize-recover=
+// CHECK-NO-EMPTY-FLAGS-NOT: "-fsanitize-merge=
+// CHECK-NO-EMPTY-FLAGS-NOT: "-fsanitize-annotate-debug-info=

>From c366793bdf3921e28d9d92246033fc25e6e677cb Mon Sep 17 00:00:00 2001
From: Vitaly Buka <vitalybuka at google.com>
Date: Mon, 23 Nov 2026 22:05:23 -0800
Subject: [PATCH 4/4] [spr] update

Created using spr 2.0.0-beta.2
---
 llvm/lib/Transforms/Instrumentation/KCFI.cpp | 107 +++++++++----------
 1 file changed, 49 insertions(+), 58 deletions(-)

diff --git a/llvm/lib/Transforms/Instrumentation/KCFI.cpp b/llvm/lib/Transforms/Instrumentation/KCFI.cpp
index fa54849b163f39..61acbe0b9d3582 100644
--- a/llvm/lib/Transforms/Instrumentation/KCFI.cpp
+++ b/llvm/lib/Transforms/Instrumentation/KCFI.cpp
@@ -23,7 +23,7 @@
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/MDBuilder.h"
 #include "llvm/IR/Module.h"
-#include "llvm/TargetParser/Triple.h"
+#include "llvm/Target/TargetMachine.h"
 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
 
 using namespace llvm;
@@ -44,61 +44,22 @@ class DiagnosticInfoKCFI : public DiagnosticInfo {
 };
 } // namespace
 
-static void lowerTrapCheck(CallInst *CI, const Triple &T, IntegerType *Int32Ty,
-                           MDNode *VeryUnlikelyWeights) {
-  // Get the expected hash value.
-  const uint32_t ExpectedHash =
-      cast<ConstantInt>(CI->getOperandBundle(LLVMContext::OB_kcfi)->Inputs[0])
-          ->getZExtValue();
-
-  // Drop the KCFI operand bundle.
-  CallBase *Call = CallBase::removeOperandBundle(CI, LLVMContext::OB_kcfi,
-                                                 CI->getIterator());
-  assert(Call != CI);
-  Call->copyMetadata(*CI);
-  CI->replaceAllUsesWith(Call);
-  CI->eraseFromParent();
-
-  if (!Call->isIndirectCall())
-    return;
-
-  // Emit a check and trap if the target hash doesn't match.
-  IRBuilder<> Builder(Call);
-  Builder.disableGEPCanonicalization();
-  Value *FuncPtr = Call->getCalledOperand();
-  // ARM uses the least significant bit of the function pointer to select
-  // between ARM and Thumb modes for the callee. Instructions are always
-  // at least 16-bit aligned, so clear the LSB before we compute the hash
-  // location.
-  if (T.isARM() || T.isThumb()) {
-    FuncPtr = Builder.CreateIntToPtr(
-        Builder.CreateAnd(Builder.CreatePtrToInt(FuncPtr, Int32Ty),
-                          ConstantInt::getSigned(Int32Ty, -2)),
-        FuncPtr->getType());
-  }
-  Value *HashPtr = Builder.CreateConstInBoundsGEP1_32(Int32Ty, FuncPtr, -1);
-  Value *Test = Builder.CreateICmpNE(Builder.CreateLoad(Int32Ty, HashPtr),
-                                     ConstantInt::get(Int32Ty, ExpectedHash));
-  Instruction *ThenTerm =
-      SplitBlockAndInsertIfThen(Test, Call, false, VeryUnlikelyWeights);
-  Builder.SetInsertPoint(ThenTerm);
-  Builder.CreateIntrinsic(Intrinsic::debugtrap, {});
-  ++NumKCFIChecks;
-}
+PreservedAnalyses KCFIPass::run(Function &F, FunctionAnalysisManager &AM) {
+  Module &M = *F.getParent();
+  if (!M.getModuleFlag("kcfi"))
+    return PreservedAnalyses::all();
 
-static bool lowerTrapBundles(Function &F) {
   // Find call instructions with KCFI operand bundles.
-  SmallVector<CallInst *> TrapCalls;
+  SmallVector<CallInst *> KCFICalls;
   for (Instruction &I : instructions(F)) {
     if (auto *CI = dyn_cast<CallInst>(&I))
       if (CI->getOperandBundle(LLVMContext::OB_kcfi))
-        TrapCalls.push_back(CI);
+        KCFICalls.push_back(CI);
   }
 
-  if (TrapCalls.empty())
-    return false;
+  if (KCFICalls.empty())
+    return PreservedAnalyses::all();
 
-  Module &M = *F.getParent();
   LLVMContext &Ctx = M.getContext();
   // patchable-function-prefix emits nops between the KCFI type identifier
   // and the function start. As we don't know the size of the emitted nops,
@@ -112,16 +73,46 @@ static bool lowerTrapBundles(Function &F) {
   MDNode *VeryUnlikelyWeights = MDBuilder(Ctx).createUnlikelyBranchWeights();
   Triple T(M.getTargetTriple());
 
-  for (CallInst *CI : TrapCalls)
-    lowerTrapCheck(CI, T, Int32Ty, VeryUnlikelyWeights);
-  return true;
-}
-
-PreservedAnalyses KCFIPass::run(Function &F, FunctionAnalysisManager &AM) {
-  if (!F.getParent()->getModuleFlag("kcfi"))
-    return PreservedAnalyses::all();
+  for (CallInst *CI : KCFICalls) {
+    // Get the expected hash value.
+    const uint32_t ExpectedHash =
+        cast<ConstantInt>(CI->getOperandBundle(LLVMContext::OB_kcfi)->Inputs[0])
+            ->getZExtValue();
+
+    // Drop the KCFI operand bundle.
+    CallBase *Call = CallBase::removeOperandBundle(CI, LLVMContext::OB_kcfi,
+                                                   CI->getIterator());
+    assert(Call != CI);
+    Call->copyMetadata(*CI);
+    CI->replaceAllUsesWith(Call);
+    CI->eraseFromParent();
+
+    if (!Call->isIndirectCall())
+      continue;
+
+    // Emit a check and trap if the target hash doesn't match.
+    IRBuilder<> Builder(Call);
+    Builder.disableGEPCanonicalization();
+    Value *FuncPtr = Call->getCalledOperand();
+    // ARM uses the least significant bit of the function pointer to select
+    // between ARM and Thumb modes for the callee. Instructions are always
+    // at least 16-bit aligned, so clear the LSB before we compute the hash
+    // location.
+    if (T.isARM() || T.isThumb()) {
+      FuncPtr = Builder.CreateIntToPtr(
+          Builder.CreateAnd(Builder.CreatePtrToInt(FuncPtr, Int32Ty),
+                            ConstantInt::getSigned(Int32Ty, -2)),
+          FuncPtr->getType());
+    }
+    Value *HashPtr = Builder.CreateConstInBoundsGEP1_32(Int32Ty, FuncPtr, -1);
+    Value *Test = Builder.CreateICmpNE(Builder.CreateLoad(Int32Ty, HashPtr),
+                                       ConstantInt::get(Int32Ty, ExpectedHash));
+    Instruction *ThenTerm =
+        SplitBlockAndInsertIfThen(Test, Call, false, VeryUnlikelyWeights);
+    Builder.SetInsertPoint(ThenTerm);
+    Builder.CreateIntrinsic(Intrinsic::debugtrap, {});
+    ++NumKCFIChecks;
+  }
 
-  if (!lowerTrapBundles(F))
-    return PreservedAnalyses::all();
   return PreservedAnalyses::none();
 }



More information about the cfe-commits mailing list