From 540a73bdd3b4b7a43ed86dd9077fc2f3a15f8b65 Mon Sep 17 00:00:00 2001
From: Erik Pilkington <erik.pilkington@gmail.com>
Date: Thu, 21 Jul 2016 22:31:40 +0000
Subject: [PATCH] [CodeGen] Fix a crash when constant folding switch statement

Differential revision: https://reviews.llvm.org/D22542

git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@276350 91177308-0d34-0410-b5e6-96231b3b80d8
---
 lib/CodeGen/CGStmt.cpp                    | 8 ++++++++
 test/CodeGenCXX/switch-case-folding-2.cpp | 9 +++++++++
 2 files changed, 17 insertions(+)

diff --git a/lib/CodeGen/CGStmt.cpp b/lib/CodeGen/CGStmt.cpp
index a7fa60f73ad..31f19829d92 100644
--- a/lib/CodeGen/CGStmt.cpp
+++ b/lib/CodeGen/CGStmt.cpp
@@ -1264,6 +1264,14 @@ void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
 }
 
 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
+  // If there is no enclosing switch instance that we're aware of, then this
+  // default statement can be elided. This situation only happens when we've
+  // constant-folded the switch.
+  if (!SwitchInsn) {
+    EmitStmt(S.getSubStmt());
+    return;
+  }
+
   llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
   assert(DefaultBlock->empty() &&
          "EmitDefaultStmt: Default block already defined?");
diff --git a/test/CodeGenCXX/switch-case-folding-2.cpp b/test/CodeGenCXX/switch-case-folding-2.cpp
index b0bbf3282ac..558ca3c87d9 100644
--- a/test/CodeGenCXX/switch-case-folding-2.cpp
+++ b/test/CodeGenCXX/switch-case-folding-2.cpp
@@ -18,4 +18,13 @@ int main(void) {
  return test(5);
 }
 
+void other_test() {
+  switch(0) {
+  case 0:
+    do {
+    default:;
+    } while(0);
+  }
+}
+
 // CHECK: call i32 (i8*, ...) @_Z6printfPKcz
-- 
GitLab