[llvm-branch-commits] [clang] [llvm] [msan] Add -msan-merge-checks to merge per-function warning blocks (PR #238707)

Vitaly Buka via llvm-branch-commits llvm-branch-commits at lists.llvm.org
Wed Nov 4 08:56:37 PST 2026


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

>From 99fccd37e8f51e306e6372e7e34167020bb786ab Mon Sep 17 00:00:00 2001
From: Vitaly Buka <vitalybuka at google.com>
Date: Tue, 3 Nov 2026 23:31:29 -0800
Subject: [PATCH] [spr] update

Created using spr 2.0.0-beta.2
---
 clang/lib/CodeGen/BackendUtil.cpp             |  6 ++-
 clang/test/CodeGen/sanitize-memory-merge.c    | 15 ++++---
 .../Instrumentation/MemorySanitizer.h         |  3 +-
 .../Instrumentation/InstrumentationOptions.td |  2 +
 .../Instrumentation/MemorySanitizer.cpp       | 44 ++++++++++++++-----
 .../MemorySanitizer/merge_checks.ll           | 17 ++++---
 6 files changed, 59 insertions(+), 28 deletions(-)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp b/clang/lib/CodeGen/BackendUtil.cpp
index e04934548176f8..9e8d44e24ce432 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -680,8 +680,10 @@ static void addSanitizers(const Triple &TargetTriple,
         int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
 
-        MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
-                                       CodeGenOpts.SanitizeMemoryParamRetval);
+        MemorySanitizerOptions options(
+            TrackOrigins, Recover, CompileKernel,
+            CodeGenOpts.SanitizeMemoryParamRetval,
+            CodeGenOpts.SanitizeMergeHandlers.has(Mask));
         MPM.addPass(MemorySanitizerPass(options));
         if (Level != OptimizationLevel::O0) {
           // MemorySanitizer inserts complex instrumentation that mostly follows
diff --git a/clang/test/CodeGen/sanitize-memory-merge.c b/clang/test/CodeGen/sanitize-memory-merge.c
index 4bb260e0b9657f..9019a1ee48d050 100644
--- a/clang/test/CodeGen/sanitize-memory-merge.c
+++ b/clang/test/CodeGen/sanitize-memory-merge.c
@@ -2,10 +2,14 @@
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -fsanitize=memory -O2 -emit-llvm -o - %s | FileCheck %s --implicit-check-not="call void @__msan_warning" --check-prefixes=CHECK,NOMERGE
 // RUN: %clang_cc1 -triple x86_64-linux-gnu -fsanitize=memory -fsanitize-merge=memory -O2 -emit-llvm -o - %s | FileCheck %s --implicit-check-not="call void @__msan_warning" --check-prefixes=CHECK,MERGE
 
-// CHECK-LABEL: define dso_local noundef range(i32 0, 3) i32 @two_checks(
-// CHECK-SAME: ptr nofree noundef readonly captures(none) [[P:%.*]], ptr nofree noundef readonly captures(none) [[Q:%.*]]) local_unnamed_addr #[[ATTR0:[0-9]+]] {
-// CHECK:    call void @__msan_warning_noreturn() #[[ATTR2:[0-9]+]]
-// CHECK:    call void @__msan_warning_noreturn() #[[ATTR2]]
+// NOMERGE-LABEL: define dso_local noundef range(i32 0, 3) i32 @two_checks(
+// NOMERGE-SAME: ptr nofree noundef readonly captures(none) [[P:%.*]], ptr nofree noundef readonly captures(none) [[Q:%.*]]) local_unnamed_addr #[[ATTR0:[0-9]+]] {
+// NOMERGE:    call void @__msan_warning_noreturn() #[[ATTR2:[0-9]+]]
+// NOMERGE:    call void @__msan_warning_noreturn() #[[ATTR2]]
+//
+// MERGE-LABEL: define dso_local noundef range(i32 0, 3) i32 @two_checks(
+// MERGE-SAME: ptr nofree noundef readonly captures(none) [[P:%.*]], ptr nofree noundef readonly captures(none) [[Q:%.*]]) local_unnamed_addr #[[ATTR0:[0-9]+]] {
+// MERGE:    call void @__msan_warning_noreturn() #[[ATTR2:[0-9]+]]
 //
 int two_checks(int *p, int *q) {
   if (*p)
@@ -15,5 +19,4 @@ int two_checks(int *p, int *q) {
   return 0;
 }
 //// NOTE: These prefixes are unused and the list is autogenerated. Do not add tests below this line:
-// MERGE: {{.*}}
-// NOMERGE: {{.*}}
+// CHECK: {{.*}}
diff --git a/llvm/include/llvm/Transforms/Instrumentation/MemorySanitizer.h b/llvm/include/llvm/Transforms/Instrumentation/MemorySanitizer.h
index b42f2e21aa52f4..81a6fb10f1a248 100644
--- a/llvm/include/llvm/Transforms/Instrumentation/MemorySanitizer.h
+++ b/llvm/include/llvm/Transforms/Instrumentation/MemorySanitizer.h
@@ -27,11 +27,12 @@ struct MemorySanitizerOptions {
   MemorySanitizerOptions(int TrackOrigins, bool Recover, bool Kernel)
       : MemorySanitizerOptions(TrackOrigins, Recover, Kernel, false) {}
   LLVM_ABI MemorySanitizerOptions(int TrackOrigins, bool Recover, bool Kernel,
-                                  bool EagerChecks);
+                                  bool EagerChecks, bool MergeChecks = false);
   bool Kernel;
   int TrackOrigins;
   bool Recover;
   bool EagerChecks;
+  bool MergeChecks;
 };
 
 /// A module pass for msan instrumentation.
diff --git a/llvm/lib/Transforms/Instrumentation/InstrumentationOptions.td b/llvm/lib/Transforms/Instrumentation/InstrumentationOptions.td
index 046d9d28041100..702c155a2dc241 100644
--- a/llvm/lib/Transforms/Instrumentation/InstrumentationOptions.td
+++ b/llvm/lib/Transforms/Instrumentation/InstrumentationOptions.td
@@ -479,6 +479,8 @@ defm : OptionalBoolField<"msan-keep-going",
   "Keep going after reporting a UMR">;
 defm : OptionalBoolField<"msan-kernel",
   "Enable KernelMemorySanitizer instrumentation">;
+defm : OptionalBoolField<"msan-merge-checks",
+  "Merge per-function MSan warning blocks">;
 defm : OptionalValueField<"msan-origin-base", "uint64_t",
   "Define custom MSan OriginBase">;
 defm : BoolField<"msan-poison-stack", "true",
diff --git a/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp b/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
index 3a7f3722b8afe2..b73f3d426cf71b 100644
--- a/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
@@ -434,7 +434,7 @@ class MemorySanitizer {
                   MemorySanitizerOptions Options)
       : Opts(Opts), CompileKernel(Options.Kernel),
         TrackOrigins(Options.TrackOrigins), Recover(Options.Recover),
-        EagerChecks(Options.EagerChecks) {
+        EagerChecks(Options.EagerChecks), MergeChecks(Options.MergeChecks) {
     initializeModule(M);
   }
 
@@ -473,6 +473,7 @@ class MemorySanitizer {
   int TrackOrigins;
   bool Recover;
   bool EagerChecks;
+  bool MergeChecks;
 
   Triple TargetTriple;
   LLVMContext *C;
@@ -592,8 +593,10 @@ void insertModuleCtor(const InstrumentationOptions &Opts, Module &M) {
 
 } // end anonymous namespace
 
-MemorySanitizerOptions::MemorySanitizerOptions(int TO, bool R, bool K, bool EC)
-    : Kernel(K), TrackOrigins(TO), Recover(R), EagerChecks(EC) {}
+MemorySanitizerOptions::MemorySanitizerOptions(int TO, bool R, bool K, bool EC,
+                                               bool MC)
+    : Kernel(K), TrackOrigins(TO), Recover(R), EagerChecks(EC),
+      MergeChecks(MC) {}
 
 static MemorySanitizerOptions resolveOptions(const InstrumentationOptions &Opts,
                                              MemorySanitizerOptions O) {
@@ -602,6 +605,7 @@ static MemorySanitizerOptions resolveOptions(const InstrumentationOptions &Opts,
       Opts.msan_track_origins.value_or(O.Kernel ? 2 : O.TrackOrigins);
   O.Recover = valueOr(Opts.msan_keep_going, O.Kernel || O.Recover);
   O.EagerChecks = valueOr(Opts.msan_eager_checks, O.EagerChecks);
+  O.MergeChecks = valueOr(Opts.msan_merge_checks, O.MergeChecks);
   return O;
 }
 
@@ -1047,6 +1051,7 @@ struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
   std::unique_ptr<VarArgHelper> VAHelper;
   const TargetLibraryInfo *TLI;
   Instruction *FnPrologueEnd;
+  BasicBlock *MergedWarningBB = nullptr;
   SmallVector<Instruction *, 16> Instructions;
 
   // The following flags disable parts of MSan instrumentation based on
@@ -1295,10 +1300,11 @@ struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
       }
     }
 
-    if (MS.CompileKernel || MS.TrackOrigins)
-      IRB.CreateCall(MS.WarningFn, Origin)->setCannotMerge();
-    else
-      IRB.CreateCall(MS.WarningFn)->setCannotMerge();
+    CallBase *CB = (MS.CompileKernel || MS.TrackOrigins)
+                       ? IRB.CreateCall(MS.WarningFn, Origin)
+                       : IRB.CreateCall(MS.WarningFn);
+    if (!MS.MergeChecks)
+      CB->setCannotMerge();
     // FIXME: Insert UnreachableInst if !MS.Recover?
     // This may invalidate some of the following checks and needs to be done
     // at the very end.
@@ -1337,12 +1343,26 @@ struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
       }
     } else {
       Value *Cmp = convertToBool(ConvertedShadow, IRB, "_mscmp");
-      Instruction *CheckTerm = SplitBlockAndInsertIfThen(
-          Cmp, &*IRB.GetInsertPoint(),
-          /* Unreachable */ !MS.Recover, MS.ColdCallWeights);
+      if (MS.MergeChecks && !MS.Recover && !MS.TrackOrigins &&
+          !MS.CompileKernel) {
+        bool NeedCall = (MergedWarningBB == nullptr);
+        Instruction *CheckTerm = SplitBlockAndInsertIfThen(
+            Cmp, &*IRB.GetInsertPoint(), /* Unreachable */ true,
+            MS.ColdCallWeights, /*DTU=*/nullptr, /*LI=*/nullptr,
+            MergedWarningBB);
+        if (NeedCall) {
+          MergedWarningBB = CheckTerm->getParent();
+          IRB.SetInsertPoint(CheckTerm);
+          insertWarningFn(IRB, Origin);
+        }
+      } else {
+        Instruction *CheckTerm = SplitBlockAndInsertIfThen(
+            Cmp, &*IRB.GetInsertPoint(),
+            /* Unreachable */ !MS.Recover, MS.ColdCallWeights);
 
-      IRB.SetInsertPoint(CheckTerm);
-      insertWarningFn(IRB, Origin);
+        IRB.SetInsertPoint(CheckTerm);
+        insertWarningFn(IRB, Origin);
+      }
       LLVM_DEBUG(dbgs() << "  CHECK: " << *Cmp << "\n");
     }
   }
diff --git a/llvm/test/Instrumentation/MemorySanitizer/merge_checks.ll b/llvm/test/Instrumentation/MemorySanitizer/merge_checks.ll
index dfc29536868fd9..1f72f7d8235127 100644
--- a/llvm/test/Instrumentation/MemorySanitizer/merge_checks.ll
+++ b/llvm/test/Instrumentation/MemorySanitizer/merge_checks.ll
@@ -1,15 +1,19 @@
 ; NOTE: Assertions have been autogenerated by utils/update_test_checks.py UTC_ARGS: --filter "call void @__msan_warning" --version 6
 ; RUN: opt < %s -S -passes=msan | FileCheck %s --implicit-check-not="call void @__msan_warning" --check-prefixes=CHECK,NOMERGE
-; RUN: opt < %s -S -passes=msan | FileCheck %s --implicit-check-not="call void @__msan_warning" --check-prefixes=CHECK,MERGE
+; RUN: opt < %s -S -passes=msan -msan-merge-checks | FileCheck %s --implicit-check-not="call void @__msan_warning" --check-prefixes=CHECK,MERGE
 
 target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64-S128"
 target triple = "x86_64-unknown-linux-gnu"
 
 define i32 @two_checks(ptr %p, ptr %q) sanitize_memory {
-; CHECK-LABEL: define i32 @two_checks(
-; CHECK-SAME: ptr [[P:%.*]], ptr [[Q:%.*]]) #[[ATTR0:[0-9]+]] {
-; CHECK:    call void @__msan_warning_noreturn() #[[ATTR3:[0-9]+]]
-; CHECK:    call void @__msan_warning_noreturn() #[[ATTR3]]
+; NOMERGE-LABEL: define i32 @two_checks(
+; NOMERGE-SAME: ptr [[P:%.*]], ptr [[Q:%.*]]) #[[ATTR0:[0-9]+]] {
+; NOMERGE:    call void @__msan_warning_noreturn() #[[ATTR3:[0-9]+]]
+; NOMERGE:    call void @__msan_warning_noreturn() #[[ATTR3]]
+;
+; MERGE-LABEL: define i32 @two_checks(
+; MERGE-SAME: ptr [[P:%.*]], ptr [[Q:%.*]]) #[[ATTR0:[0-9]+]] {
+; MERGE:    call void @__msan_warning_noreturn()
 ;
   %a = load i32, ptr %p, align 4
   %b = load i32, ptr %q, align 4
@@ -17,5 +21,4 @@ define i32 @two_checks(ptr %p, ptr %q) sanitize_memory {
   ret i32 %s
 }
 ;; NOTE: These prefixes are unused and the list is autogenerated. Do not add tests below this line:
-; MERGE: {{.*}}
-; NOMERGE: {{.*}}
+; CHECK: {{.*}}



More information about the llvm-branch-commits mailing list