diff --git a/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp b/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp --- a/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp +++ b/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp @@ -2821,6 +2821,16 @@ } Value *LibCallSimplifier::optimizeBCopy(CallInst *CI, IRBuilderBase &B) { + // Do not transform a bcopy call into llvm.memmove if it calls into another + // function. This ensures that the fortified implementation with + // __builtin___memmove_chk is not overriden. + Function *Callee = CI->getCalledFunction(); + if (!Callee->empty()) { + BasicBlock &BB = Callee->getEntryBlock(); + if (isa(BB.getFirstNonPHIOrDbgOrLifetime())) + return nullptr; + } + // bcopy(src, dst, n) -> llvm.memmove(dst, src, n) return B.CreateMemMove(CI->getArgOperand(1), Align(1), CI->getArgOperand(0), Align(1), CI->getArgOperand(2)); diff --git a/llvm/test/Transforms/InstCombine/bcopy-chk.ll b/llvm/test/Transforms/InstCombine/bcopy-chk.ll new file mode 100644 --- /dev/null +++ b/llvm/test/Transforms/InstCombine/bcopy-chk.ll @@ -0,0 +1,27 @@ +; NOTE: Assertions have been autogenerated by utils/update_test_checks.py +; RUN: opt < %s -O1 -S | FileCheck %s + +declare i8* @__memmove_chk(i8*, i8*, i64, i64) +declare i64 @llvm.objectsize.i64.p0i8(i8*, i1, i1, i1) + +define available_externally dso_local void @bcopy(i8* nocapture readonly %src, i8* nocapture %dst, i64 %len) #0 { + %size = call i64 @llvm.objectsize.i64.p0i8(i8* %dst, i1 false, i1 true, i1 false) + call i8* @__memmove_chk(i8* %dst, i8* %src, i64 %len, i64 %size) + ret void +} + +@buf = dso_local global [4 x i8] zeroinitializer, align 1 + +define dso_local void @fortified_bcopy(i64 %argc) { +; CHECK-LABEL: @fortified_bcopy( +; CHECK-NEXT: [[ADD:%.*]] = add i64 [[ARGC:%.*]], 1 +; CHECK-NEXT: [[TMP1:%.*]] = call i8* @__memmove_chk(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @buf, i64 0, i64 2), i8* getelementptr inbounds ([4 x i8], [4 x i8]* @buf, i64 0, i64 1), i64 [[ADD]], i64 2) +; CHECK-NEXT: ret void +; + %add = add i64 %argc, 1 + tail call void @bcopy(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @buf, i64 0, i64 1), i8* getelementptr inbounds ([4 x i8], [4 x i8]* @buf, i64 0, i64 2), i64 %add) #1 + ret void +} + +attributes #0 = { alwaysinline } +attributes #1 = { builtin }