From d057fb26fb18a40e79d3ac620bf2182cd7de2a6d Mon Sep 17 00:00:00 2001 From: Augie Fackler Date: Fri, 15 Sep 2023 11:19:56 -0400 Subject: [PATCH] IRBuilder: avoid crash when seeking to start of a BasicBlock with only DebugInfo This fixes a crash in `rustc` that was triggered by https://reviews.llvm.org/D159485 (aka llvm/llvm-project@1ce1732f82aec29ec27d6de58153d516bca1d633). This was more or less pair-programmed with @krasimirgg - I can't claim full credit. --- llvm/lib/IR/Instruction.cpp | 3 ++- llvm/unittests/IR/DebugInfoTest.cpp | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/llvm/lib/IR/Instruction.cpp b/llvm/lib/IR/Instruction.cpp index 6b0348f8f691f..b497951a598cc 100644 --- a/llvm/lib/IR/Instruction.cpp +++ b/llvm/lib/IR/Instruction.cpp @@ -887,7 +887,8 @@ Instruction::getPrevNonDebugInstruction(bool SkipPseudoOp) const { const DebugLoc &Instruction::getStableDebugLoc() const { if (isa(this)) - return getNextNonDebugInstruction()->getDebugLoc(); + if (const Instruction *Next = getNextNonDebugInstruction()) + return Next->getDebugLoc(); return getDebugLoc(); } diff --git a/llvm/unittests/IR/DebugInfoTest.cpp b/llvm/unittests/IR/DebugInfoTest.cpp index a22c7be73f49f..84ed73333416c 100644 --- a/llvm/unittests/IR/DebugInfoTest.cpp +++ b/llvm/unittests/IR/DebugInfoTest.cpp @@ -566,6 +566,19 @@ TEST(AssignmentTrackingTest, Utils) { EXPECT_FALSE(at::getAssignmentMarkers(&Fun2Alloca).empty()); } +TEST(IRBuilder, GetSetInsertionPointWithEmptyBasicBlock) { + LLVMContext C; + std::unique_ptr BB(BasicBlock::Create(C, "start")); + Module *M = new Module("module", C); + IRBuilder<> Builder(BB.get()); + Function *DbgDeclare = Intrinsic::getDeclaration(M, Intrinsic::dbg_declare); + Value *DIV = MetadataAsValue::get(C, (Metadata *)nullptr); + SmallVector Args = {DIV, DIV, DIV}; + Builder.CreateCall(DbgDeclare, Args); + auto IP = BB->getFirstInsertionPt(); + Builder.SetInsertPoint(BB.get(), IP); +} + TEST(AssignmentTrackingTest, InstrMethods) { // Test the assignment tracking Instruction methods. // This includes: