From 0482ca8ded8c112115c8a9c39a9668b69d3a4441 Mon Sep 17 00:00:00 2001 From: Hans Wennborg Date: Tue, 20 Aug 2019 09:45:09 +0000 Subject: [PATCH] Merging r369168: ------------------------------------------------------------------------ r369168 | spatel | 2019-08-17 01:10:34 +0200 (Sat, 17 Aug 2019) | 16 lines MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [CodeGenPrepare] Fix use-after-free If OptimizeExtractBits() encountered a shift instruction with no operands at all, it would erase the instruction, but still return false. This previously didn’t matter because its caller would always return after processing the instruction, but https://reviews.llvm.org/D63233 changed the function’s caller to fall through if it returned false, which would then cause a use-after-free detectable by ASAN. This change makes OptimizeExtractBits return true if it removes a shift instruction with no users, terminating processing of the instruction. Patch by: @brentdax (Brent Royal-Gordon) Differential Revision: https://reviews.llvm.org/D66330 ------------------------------------------------------------------------ llvm-svn: 369355 --- llvm/lib/CodeGen/CodeGenPrepare.cpp | 3 ++- .../CodeGenPrepare/sink-shift-and-trunc.ll | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp index 52b4bbea012bc..e6f2aa9ef9305 100644 --- a/llvm/lib/CodeGen/CodeGenPrepare.cpp +++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp @@ -1682,10 +1682,11 @@ static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, TheUse = InsertedShift; } - // If we removed all uses, nuke the shift. + // If we removed all uses, or there are none, nuke the shift. if (ShiftI->use_empty()) { salvageDebugInfo(*ShiftI); ShiftI->eraseFromParent(); + MadeChange = true; } return MadeChange; diff --git a/llvm/test/Transforms/CodeGenPrepare/sink-shift-and-trunc.ll b/llvm/test/Transforms/CodeGenPrepare/sink-shift-and-trunc.ll index 20a436edd105c..609b6bf679a25 100644 --- a/llvm/test/Transforms/CodeGenPrepare/sink-shift-and-trunc.ll +++ b/llvm/test/Transforms/CodeGenPrepare/sink-shift-and-trunc.ll @@ -58,6 +58,23 @@ return: ; preds = %if.then17, %if.end1 ret i32 %retval.0, !dbg !63 } +; CodeGenPrepare was erasing the unused lshr instruction, but then further +; processing the instruction after it was freed. If this bug is still present, +; this test will always crash in an LLVM built with ASAN enabled, and may +; crash even if ASAN is not enabled. + +define i32 @shift_unused(i32 %a) { +; CHECK-LABEL: @shift_unused( +; CHECK-NEXT: BB2: +; CHECK-NEXT: ret i32 [[A:%.*]] +; + %as = lshr i32 %a, 3 + br label %BB2 + +BB2: + ret i32 %a +} + ; CHECK: [[shift1_loc]] = !DILocation(line: 1 ; CHECK: [[trunc1_loc]] = !DILocation(line: 2 ; CHECK: [[shift2_loc]] = !DILocation(line: 3