[clang] [clang] Generate appropriate assume in presence of libc's memcpy (PR #119704)

via cfe-commits cfe-commits at lists.llvm.org
Thu Dec 12 06:15:48 PST 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-codegen

Author: None (serge-sans-paille)

<details>
<summary>Changes</summary>

It is an undefined behavior to pass null arguments as memcpy source or destination parameter, so generate the appropriate llvm.assume call to communicate this to the backend.

Don't do it for builtin memcpy as they don't suffer the same behavior in case of null size.

---
Full diff: https://github.com/llvm/llvm-project/pull/119704.diff


2 Files Affected:

- (modified) clang/lib/CodeGen/CGBuiltin.cpp (+6) 
- (modified) clang/test/CodeGen/catch-undef-behavior.c (+4) 


``````````diff
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 497a0b3952af8c..50cd8529120d36 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -4531,6 +4531,12 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
     Value *SizeVal = EmitScalarExpr(E->getArg(2));
     EmitArgCheck(TCK_Store, Dest, E->getArg(0), 0);
     EmitArgCheck(TCK_Load, Src, E->getArg(1), 1);
+    if (BuiltinID == Builtin::BImemcpy || BuiltinID == Builtin::BImempcpy) {
+      Builder.CreateAssumption(
+          Builder.CreateIsNotNull(Dest.emitRawPointer(*this)));
+      Builder.CreateAssumption(
+          Builder.CreateIsNotNull(Src.emitRawPointer(*this)));
+    }
     Builder.CreateMemCpy(Dest, Src, SizeVal, false);
     if (BuiltinID == Builtin::BImempcpy ||
         BuiltinID == Builtin::BI__builtin_mempcpy)
diff --git a/clang/test/CodeGen/catch-undef-behavior.c b/clang/test/CodeGen/catch-undef-behavior.c
index 7580290b0b0333..7ef7c78f1cebb7 100644
--- a/clang/test/CodeGen/catch-undef-behavior.c
+++ b/clang/test/CodeGen/catch-undef-behavior.c
@@ -371,6 +371,10 @@ void call_memcpy_nonnull(void *p, void *q, int sz) {
   // CHECK-TRAP: call void @llvm.ubsantrap(i8 16)
   // CHECK-COMMON-NOT: call
 
+  // CHECK-COMMON: %5 = icmp ne ptr %0, null
+  // CHECK-COMMON: call void @llvm.assume(i1 %5)
+  // CHECK-COMMON: %6 = icmp ne ptr %0, null
+  // CHECK-COMMON: call void @llvm.assume(i1 %6)
   // CHECK-COMMON: call void @llvm.memcpy.p0.p0.i64(ptr align 1 %0, ptr align 1 %1, i64 %conv, i1 false)
   memcpy(p, q, sz);
 }

``````````

</details>


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


More information about the cfe-commits mailing list