From e5b9a43eaa4482eb668a4b8be7360ae95807cb75 Mon Sep 17 00:00:00 2001
From: Sanjay Patel <spatel@rotateright.com>
Date: Tue, 1 Oct 2019 21:25:36 +0000
Subject: [PATCH] [BypassSlowDivision][CodeGenPrepare] avoid crashing on unused
 code (PR43514)

https://bugs.llvm.org/show_bug.cgi?id=43514

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@373394 91177308-0d34-0410-b5e6-96231b3b80d8
---
 lib/Transforms/Utils/BypassSlowDivision.cpp |  8 ++++++--
 test/CodeGen/X86/bypass-slow-division-64.ll | 10 ++++++++++
 2 files changed, 16 insertions(+), 2 deletions(-)

diff --git a/lib/Transforms/Utils/BypassSlowDivision.cpp b/lib/Transforms/Utils/BypassSlowDivision.cpp
index df299f673f6..9a6761040bd 100644
--- a/lib/Transforms/Utils/BypassSlowDivision.cpp
+++ b/lib/Transforms/Utils/BypassSlowDivision.cpp
@@ -448,13 +448,17 @@ bool llvm::bypassSlowDivision(BasicBlock *BB,
   DivCacheTy PerBBDivCache;
 
   bool MadeChange = false;
-  Instruction* Next = &*BB->begin();
+  Instruction *Next = &*BB->begin();
   while (Next != nullptr) {
     // We may add instructions immediately after I, but we want to skip over
     // them.
-    Instruction* I = Next;
+    Instruction *I = Next;
     Next = Next->getNextNode();
 
+    // Ignore dead code to save time and avoid bugs.
+    if (I->hasNUses(0))
+      continue;
+
     FastDivInsertionTask Task(I, BypassWidths);
     if (Value *Replacement = Task.getReplacement(PerBBDivCache)) {
       I->replaceAllUsesWith(Replacement);
diff --git a/test/CodeGen/X86/bypass-slow-division-64.ll b/test/CodeGen/X86/bypass-slow-division-64.ll
index 11fc0df2443..14a71050e94 100644
--- a/test/CodeGen/X86/bypass-slow-division-64.ll
+++ b/test/CodeGen/X86/bypass-slow-division-64.ll
@@ -75,3 +75,13 @@ define i64 @Test_get_quotient_and_remainder(i64 %a, i64 %b) nounwind {
   %result = add i64 %resultdiv, %resultrem
   ret i64 %result
 }
+
+define void @PR43514(i32 %x, i32 %y) {
+; CHECK-LABEL: PR43514:
+; CHECK:       # %bb.0:
+; CHECK-NEXT:    retq
+  %z1 = zext i32 %x to i64
+  %z2 = zext i32 %y to i64
+  %s = srem i64 %z1, %z2
+  ret void
+}
-- 
2.40.0