[llvm] [RemoveDIs] Update DIBuilder to conditionally insert DbgRecords (PR #84739)

Orlando Cazalet-Hyams via llvm-commits llvm-commits at lists.llvm.org
Mon Mar 11 08:19:41 PDT 2024


https://github.com/OCHyams updated https://github.com/llvm/llvm-project/pull/84739

>From b25c5461627e919ee3a02657e7a734a2204e2d0e Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Mon, 4 Mar 2024 13:55:51 +0000
Subject: [PATCH 01/31] Add DbgInstPtr union, update labels

---
 llvm/include/llvm/IR/DIBuilder.h | 15 +++++++++------
 llvm/lib/IR/DIBuilder.cpp        | 14 +++++++-------
 2 files changed, 16 insertions(+), 13 deletions(-)

diff --git a/llvm/include/llvm/IR/DIBuilder.h b/llvm/include/llvm/IR/DIBuilder.h
index edec161b397155..644e35abf03aeb 100644
--- a/llvm/include/llvm/IR/DIBuilder.h
+++ b/llvm/include/llvm/IR/DIBuilder.h
@@ -38,6 +38,9 @@ namespace llvm {
   class Module;
   class Value;
   class DbgAssignIntrinsic;
+  class DbgRecord;
+
+  using DbgInstPtr = PointerUnion<Instruction *, DbgRecord *>;
 
   class DIBuilder {
     Module &M;
@@ -95,8 +98,8 @@ namespace llvm {
                                BasicBlock *InsertBB, Instruction *InsertBefore);
 
     /// Internal helper for insertLabel.
-    Instruction *insertLabel(DILabel *LabelInfo, const DILocation *DL,
-                             BasicBlock *InsertBB, Instruction *InsertBefore);
+    DbgInstPtr insertLabel(DILabel *LabelInfo, const DILocation *DL,
+                           BasicBlock *InsertBB, Instruction *InsertBefore);
 
     /// Internal helper with common code used by insertDbg{Value,Addr}Intrinsic.
     Instruction *insertDbgIntrinsic(llvm::Function *Intrinsic, llvm::Value *Val,
@@ -959,15 +962,15 @@ namespace llvm {
     /// \param LabelInfo    Label's debug info descriptor.
     /// \param DL           Debug info location.
     /// \param InsertBefore Location for the new intrinsic.
-    Instruction *insertLabel(DILabel *LabelInfo, const DILocation *DL,
-                             Instruction *InsertBefore);
+    DbgInstPtr insertLabel(DILabel *LabelInfo, const DILocation *DL,
+                           Instruction *InsertBefore);
 
     /// Insert a new llvm.dbg.label intrinsic call.
     /// \param LabelInfo    Label's debug info descriptor.
     /// \param DL           Debug info location.
     /// \param InsertAtEnd Location for the new intrinsic.
-    Instruction *insertLabel(DILabel *LabelInfo, const DILocation *DL,
-                             BasicBlock *InsertAtEnd);
+    DbgInstPtr insertLabel(DILabel *LabelInfo, const DILocation *DL,
+                           BasicBlock *InsertAtEnd);
 
     /// Insert a new llvm.dbg.value intrinsic call.
     /// \param Val          llvm::Value of the variable
diff --git a/llvm/lib/IR/DIBuilder.cpp b/llvm/lib/IR/DIBuilder.cpp
index 62efaba025344b..c816f14a1507b9 100644
--- a/llvm/lib/IR/DIBuilder.cpp
+++ b/llvm/lib/IR/DIBuilder.cpp
@@ -971,15 +971,15 @@ DIBuilder::insertDbgAssign(Instruction *LinkedInstr, Value *Val,
   return DVI;
 }
 
-Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
-                                    Instruction *InsertBefore) {
+DbgInstPtr DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
+                                  Instruction *InsertBefore) {
   return insertLabel(LabelInfo, DL,
                      InsertBefore ? InsertBefore->getParent() : nullptr,
                      InsertBefore);
 }
 
-Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
-                                    BasicBlock *InsertAtEnd) {
+DbgInstPtr DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
+                                  BasicBlock *InsertAtEnd) {
   return insertLabel(LabelInfo, DL, InsertAtEnd, nullptr);
 }
 
@@ -1081,9 +1081,9 @@ Instruction *DIBuilder::insertDbgIntrinsic(llvm::Function *IntrinsicFn,
   return B.CreateCall(IntrinsicFn, Args);
 }
 
-Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
-                                    BasicBlock *InsertBB,
-                                    Instruction *InsertBefore) {
+DbgInstPtr DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
+                                  BasicBlock *InsertBB,
+                                  Instruction *InsertBefore) {
   assert(LabelInfo && "empty or invalid DILabel* passed to dbg.label");
   assert(DL && "Expected debug loc");
   assert(DL->getScope()->getSubprogram() ==

>From b503e84f4a53c3b4e7100d11f8a6226bddbaa6b2 Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Mon, 4 Mar 2024 14:08:10 +0000
Subject: [PATCH 02/31] Add insertLabel body

---
 llvm/lib/IR/DIBuilder.cpp | 26 +++++++++++++++++---------
 1 file changed, 17 insertions(+), 9 deletions(-)

diff --git a/llvm/lib/IR/DIBuilder.cpp b/llvm/lib/IR/DIBuilder.cpp
index c816f14a1507b9..b1f2aa71535d49 100644
--- a/llvm/lib/IR/DIBuilder.cpp
+++ b/llvm/lib/IR/DIBuilder.cpp
@@ -1089,15 +1089,23 @@ DbgInstPtr DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
   assert(DL->getScope()->getSubprogram() ==
              LabelInfo->getScope()->getSubprogram() &&
          "Expected matching subprograms");
-  if (!LabelFn)
-    LabelFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_label);
-
-  trackIfUnresolved(LabelInfo);
-  Value *Args[] = {MetadataAsValue::get(VMContext, LabelInfo)};
-
-  IRBuilder<> B(DL->getContext());
-  initIRBuilder(B, DL, InsertBB, InsertBefore);
-  return B.CreateCall(LabelFn, Args);
+  if (M.IsNewDbgInfoFormat) {
+    DPLabel *DPL = new DPLabel(LabelInfo, DL);
+    if (InsertBefore)
+      InsertBB->insertDPValueBefore(DPL, InsertBefore->getIterator());
+    // FIXME: Use smart pointers for DbgRecord ownership management.
+    return DPL;
+  } else {
+    if (!LabelFn)
+      LabelFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_label);
+
+    trackIfUnresolved(LabelInfo);
+    Value *Args[] = {MetadataAsValue::get(VMContext, LabelInfo)};
+
+    IRBuilder<> B(DL->getContext());
+    initIRBuilder(B, DL, InsertBB, InsertBefore);
+    return B.CreateCall(LabelFn, Args);
+  }
 }
 
 void DIBuilder::replaceVTableHolder(DICompositeType *&T, DIType *VTableHolder) {

>From 3964cc50b3997c9bab78a7be3969f75497de8a1e Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Mon, 4 Mar 2024 15:52:48 +0000
Subject: [PATCH 03/31] labels test try#1

---
 llvm/lib/IR/DIBuilder.cpp           |  7 +++-
 llvm/unittests/IR/IRBuilderTest.cpp | 64 ++++++++++++++++++++---------
 2 files changed, 50 insertions(+), 21 deletions(-)

diff --git a/llvm/lib/IR/DIBuilder.cpp b/llvm/lib/IR/DIBuilder.cpp
index b1f2aa71535d49..ddff9bf4b1eeac 100644
--- a/llvm/lib/IR/DIBuilder.cpp
+++ b/llvm/lib/IR/DIBuilder.cpp
@@ -1089,17 +1089,20 @@ DbgInstPtr DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
   assert(DL->getScope()->getSubprogram() ==
              LabelInfo->getScope()->getSubprogram() &&
          "Expected matching subprograms");
+
+  trackIfUnresolved(LabelInfo);
   if (M.IsNewDbgInfoFormat) {
     DPLabel *DPL = new DPLabel(LabelInfo, DL);
-    if (InsertBefore)
+    if (InsertBB && InsertBefore)
       InsertBB->insertDPValueBefore(DPL, InsertBefore->getIterator());
+    else if (InsertBB)
+      InsertBB->insertDPValueBefore(DPL, std::prev(InsertBB->end())); // this  is awkward/wrong. What to do about insert-at-end shinanigans?
     // FIXME: Use smart pointers for DbgRecord ownership management.
     return DPL;
   } else {
     if (!LabelFn)
       LabelFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_label);
 
-    trackIfUnresolved(LabelInfo);
     Value *Args[] = {MetadataAsValue::get(VMContext, LabelInfo)};
 
     IRBuilder<> B(DL->getContext());
diff --git a/llvm/unittests/IR/IRBuilderTest.cpp b/llvm/unittests/IR/IRBuilderTest.cpp
index d15ff9dd51a4c4..0db1981969f658 100644
--- a/llvm/unittests/IR/IRBuilderTest.cpp
+++ b/llvm/unittests/IR/IRBuilderTest.cpp
@@ -871,25 +871,51 @@ TEST_F(IRBuilderTest, createFunction) {
 }
 
 TEST_F(IRBuilderTest, DIBuilder) {
-  IRBuilder<> Builder(BB);
-  DIBuilder DIB(*M);
-  auto File = DIB.createFile("F.CBL", "/");
-  auto CU = DIB.createCompileUnit(dwarf::DW_LANG_Cobol74,
-                                  DIB.createFile("F.CBL", "/"), "llvm-cobol74",
-                                  true, "", 0);
-  auto Type = DIB.createSubroutineType(DIB.getOrCreateTypeArray(std::nullopt));
-  auto SP = DIB.createFunction(
-      CU, "foo", "", File, 1, Type, 1, DINode::FlagZero,
-      DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
-  F->setSubprogram(SP);
-  AllocaInst *I = Builder.CreateAlloca(Builder.getInt8Ty());
-  auto BarSP = DIB.createFunction(
-      CU, "bar", "", File, 1, Type, 1, DINode::FlagZero,
-      DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
-  auto BadScope = DIB.createLexicalBlockFile(BarSP, File, 0);
-  I->setDebugLoc(DILocation::get(Ctx, 2, 0, BadScope));
-  DIB.finalize();
-  EXPECT_TRUE(verifyModule(*M));
+  bool NewDebugMode[] = {false, };
+
+  for (auto IsNewMode : NewDebugMode) {
+    if (!M)
+      SetUp();
+    if (IsNewMode)
+      M->convertToNewDbgValues();
+
+    IRBuilder<> Builder(BB);
+    DIBuilder DIB(*M);
+    auto File = DIB.createFile("F.CBL", "/");
+    auto CU = DIB.createCompileUnit(dwarf::DW_LANG_Cobol74,
+                                    DIB.createFile("F.CBL", "/"), "llvm-cobol74",
+                                    true, "", 0);
+    auto Type = DIB.createSubroutineType(DIB.getOrCreateTypeArray(std::nullopt));
+    auto SP = DIB.createFunction(
+        CU, "foo", "", File, 1, Type, 1, DINode::FlagZero,
+        DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
+    F->setSubprogram(SP);
+    AllocaInst *I = Builder.CreateAlloca(Builder.getInt8Ty());
+    auto BarSP = DIB.createFunction(
+        CU, "bar", "", File, 1, Type, 1, DINode::FlagZero,
+        DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
+    auto BarScope = DIB.createLexicalBlockFile(BarSP, File, 0);
+    I->setDebugLoc(DILocation::get(Ctx, 2, 0, BarScope));
+
+    // Label metadata and records.
+    DILocation *LabelLoc = DILocation::get(Ctx, 1, 0, BarScope);
+    DILabel *AlwaysPreserveLabel = DIB.createLabel(BarScope, "meles_meles", File, 1, /*AlwaysPreserve*/true);
+    DILabel *Label = DIB.createLabel(BarScope, "badger", File, 1, /*AlwaysPreserve*/false);
+    //DbgInstPtr LabelRecord = DIB.insertLabel(Label, Loc, BB); // FIXME., DIBuilder should track danglers?
+    // Insert before I.
+    DbgInstPtr LabelRecord = DIB.insertLabel(Label, LabelLoc, I);
+    EXPECT_FALSE(I->getDbgValueRange().empty());
+    //EXPECT_NE(find(LabelRecord.get<DbgRecord *>(), I->getDbgValueRange()), I->getDbgValueRange().end());
+
+    DIB.finalize();
+
+    // Check the labels are not/are added to Bar's retainedNodes array (AlwaysPreserve).
+    //EXPECT_EQ(Label, BarSP->getRetainedNodes(), BarSP->getRetainedNodes().end());
+    //EXPECT_NE(AlwaysPreserveLabel, BarSP->getRetainedNodes(), BarSP->getRetainedNodes().end());
+
+    EXPECT_TRUE(verifyModule(*M));
+    TearDown();
+  }
 }
 
 TEST_F(IRBuilderTest, createArtificialSubprogram) {

>From 36c7aa0416f0e79480d843efab7050f6b8f906ce Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Mon, 4 Mar 2024 17:14:35 +0000
Subject: [PATCH 04/31] continue to work on labeles test

---
 llvm/lib/IR/DIBuilder.cpp           |  5 ++-
 llvm/unittests/IR/IRBuilderTest.cpp | 58 ++++++++++++++++++++---------
 2 files changed, 44 insertions(+), 19 deletions(-)

diff --git a/llvm/lib/IR/DIBuilder.cpp b/llvm/lib/IR/DIBuilder.cpp
index ddff9bf4b1eeac..e2b68661440034 100644
--- a/llvm/lib/IR/DIBuilder.cpp
+++ b/llvm/lib/IR/DIBuilder.cpp
@@ -1096,7 +1096,10 @@ DbgInstPtr DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
     if (InsertBB && InsertBefore)
       InsertBB->insertDPValueBefore(DPL, InsertBefore->getIterator());
     else if (InsertBB)
-      InsertBB->insertDPValueBefore(DPL, std::prev(InsertBB->end())); // this  is awkward/wrong. What to do about insert-at-end shinanigans?
+      InsertBB->insertDPValueBefore(
+          DPL,
+          std::prev(InsertBB->end())); // this  is awkward/wrong. What to do
+                                       // about insert-at-end shinanigans?
     // FIXME: Use smart pointers for DbgRecord ownership management.
     return DPL;
   } else {
diff --git a/llvm/unittests/IR/IRBuilderTest.cpp b/llvm/unittests/IR/IRBuilderTest.cpp
index 0db1981969f658..2c6b2c980b75ea 100644
--- a/llvm/unittests/IR/IRBuilderTest.cpp
+++ b/llvm/unittests/IR/IRBuilderTest.cpp
@@ -871,21 +871,32 @@ TEST_F(IRBuilderTest, createFunction) {
 }
 
 TEST_F(IRBuilderTest, DIBuilder) {
-  bool NewDebugMode[] = {false, };
+  auto GetLastDbgRecord = [](const Instruction *I) -> DbgRecord * {
+    if (I->getDbgValueRange().empty())
+      return nullptr;
+    return &*std::prev(I->getDbgValueRange().end());
+  };
 
-  for (auto IsNewMode : NewDebugMode) {
-    if (!M)
-      SetUp();
-    if (IsNewMode)
-      M->convertToNewDbgValues();
+  auto ExpectOrder = [&](DbgInstPtr First, BasicBlock::iterator Second) {
+    if (M->IsNewDbgInfoFormat) {
+      EXPECT_TRUE(First.is<DbgRecord *>());
+      EXPECT_FALSE(Second->getDbgValueRange().empty());
+      EXPECT_EQ(GetLastDbgRecord(&*Second), First.get<DbgRecord *>());
+    } else {
+      EXPECT_TRUE(First.is<Instruction *>());
+      EXPECT_EQ(&*std::prev(Second), First.get<Instruction *>());
+    }
+  };
 
+  auto RunTest = [&]() {
     IRBuilder<> Builder(BB);
     DIBuilder DIB(*M);
     auto File = DIB.createFile("F.CBL", "/");
     auto CU = DIB.createCompileUnit(dwarf::DW_LANG_Cobol74,
-                                    DIB.createFile("F.CBL", "/"), "llvm-cobol74",
-                                    true, "", 0);
-    auto Type = DIB.createSubroutineType(DIB.getOrCreateTypeArray(std::nullopt));
+                                    DIB.createFile("F.CBL", "/"),
+                                    "llvm-cobol74", true, "", 0);
+    auto Type =
+        DIB.createSubroutineType(DIB.getOrCreateTypeArray(std::nullopt));
     auto SP = DIB.createFunction(
         CU, "foo", "", File, 1, Type, 1, DINode::FlagZero,
         DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
@@ -897,15 +908,22 @@ TEST_F(IRBuilderTest, DIBuilder) {
     auto BarScope = DIB.createLexicalBlockFile(BarSP, File, 0);
     I->setDebugLoc(DILocation::get(Ctx, 2, 0, BarScope));
 
+    // Create another instruction so that there's one before the alloca we're
+    // inserting debug intrinsics before, to make end-checking easier.
+    I = Builder.CreateAlloca(Builder.getInt1Ty());
+
     // Label metadata and records.
     DILocation *LabelLoc = DILocation::get(Ctx, 1, 0, BarScope);
-    DILabel *AlwaysPreserveLabel = DIB.createLabel(BarScope, "meles_meles", File, 1, /*AlwaysPreserve*/true);
-    DILabel *Label = DIB.createLabel(BarScope, "badger", File, 1, /*AlwaysPreserve*/false);
-    //DbgInstPtr LabelRecord = DIB.insertLabel(Label, Loc, BB); // FIXME., DIBuilder should track danglers?
-    // Insert before I.
-    DbgInstPtr LabelRecord = DIB.insertLabel(Label, LabelLoc, I);
-    EXPECT_FALSE(I->getDbgValueRange().empty());
-    //EXPECT_NE(find(LabelRecord.get<DbgRecord *>(), I->getDbgValueRange()), I->getDbgValueRange().end());
+    DILabel *AlwaysPreserveLabel = DIB.createLabel(
+        BarScope, "meles_meles", File, 1, /*AlwaysPreserve*/ true);
+    DILabel *Label =
+        DIB.createLabel(BarScope, "badger", File, 1, /*AlwaysPreserve*/ false);
+
+    // Insert before I and check order.
+    ExpectOrder(DIB.insertLabel(Label, LabelLoc, I), I->getIterator());
+    errs() << *BB << "\n";
+    // FIXME: We can't insert at the end of an incomplete block. Oops.
+    // DbgInstPtr LabelRecord = DIB.insertLabel(Label, Loc, BB); // FIXME.,
 
     DIB.finalize();
 
@@ -914,8 +932,12 @@ TEST_F(IRBuilderTest, DIBuilder) {
     //EXPECT_NE(AlwaysPreserveLabel, BarSP->getRetainedNodes(), BarSP->getRetainedNodes().end());
 
     EXPECT_TRUE(verifyModule(*M));
-    TearDown();
-  }
+  };
+  RunTest();
+  TearDown();
+  SetUp();
+  M->convertToNewDbgValues();
+  RunTest();
 }
 
 TEST_F(IRBuilderTest, createArtificialSubprogram) {

>From a706ca602d5a6f5088222417b3c3ce1596c07202 Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Mon, 4 Mar 2024 17:16:30 +0000
Subject: [PATCH 05/31] flushTerminators after every new instruction is
 inserted -- possibly also only want to do this if no terminator is present
 and the inst is at the end

---
 llvm/lib/IR/Instruction.cpp | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/llvm/lib/IR/Instruction.cpp b/llvm/lib/IR/Instruction.cpp
index e863ef3eb8d6d7..26b229ff65ec15 100644
--- a/llvm/lib/IR/Instruction.cpp
+++ b/llvm/lib/IR/Instruction.cpp
@@ -167,7 +167,10 @@ void Instruction::insertBefore(BasicBlock &BB,
 
   // If we're inserting a terminator, check if we need to flush out
   // TrailingDPValues.
-  if (isTerminator())
+  // if (isTerminator()) // @OCH -- what if we always attach danglers to the
+  // next inserted inst? This might be needed for the FE. Not very efficient
+  // though.
+  if (getParent()->getTrailingDPValues())
     getParent()->flushTerminatorDbgValues();
 }
 

>From c3cec699fb3faa03a31fe8733642fd53b3923cd2 Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Mon, 4 Mar 2024 17:18:35 +0000
Subject: [PATCH 06/31] do what that commit says

---
 llvm/lib/IR/Instruction.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/llvm/lib/IR/Instruction.cpp b/llvm/lib/IR/Instruction.cpp
index 26b229ff65ec15..7e5d38a1b2099f 100644
--- a/llvm/lib/IR/Instruction.cpp
+++ b/llvm/lib/IR/Instruction.cpp
@@ -170,7 +170,8 @@ void Instruction::insertBefore(BasicBlock &BB,
   // if (isTerminator()) // @OCH -- what if we always attach danglers to the
   // next inserted inst? This might be needed for the FE. Not very efficient
   // though.
-  if (getParent()->getTrailingDPValues())
+  if (isTerminator() ||
+      (getParent()->getTrailingDPValues() && InsertPos == BB.end()))
     getParent()->flushTerminatorDbgValues();
 }
 

>From f443a18d75ea3cbe4a211fd52cf81ce5621398b3 Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Mon, 4 Mar 2024 17:32:02 +0000
Subject: [PATCH 07/31] Allow insert-before at end() and test it in unittest --
 needed for clang

---
 llvm/lib/IR/BasicBlock.cpp          | 11 ++++++-----
 llvm/lib/IR/DIBuilder.cpp           |  5 +----
 llvm/unittests/IR/IRBuilderTest.cpp | 12 +++++++++---
 3 files changed, 16 insertions(+), 12 deletions(-)

diff --git a/llvm/lib/IR/BasicBlock.cpp b/llvm/lib/IR/BasicBlock.cpp
index 25aa3261164513..8b54e35dcd7ead 100644
--- a/llvm/lib/IR/BasicBlock.cpp
+++ b/llvm/lib/IR/BasicBlock.cpp
@@ -1040,13 +1040,14 @@ void BasicBlock::insertDPValueBefore(DbgRecord *DPV,
                                      InstListType::iterator Where) {
   // We should never directly insert at the end of the block, new DPValues
   // shouldn't be generated at times when there's no terminator.
-  assert(Where != end());
-  assert(Where->getParent() == this);
-  if (!Where->DbgMarker)
+  // assert(Where != end()); // ^ No longer true. Create seperate method if
+  // needed?
+  assert(Where == end() || Where->getParent() == this);
+  if (Where == end() || !Where->DbgMarker)
     createMarker(Where);
   bool InsertAtHead = Where.getHeadBit();
-  createMarker(&*Where);
-  Where->DbgMarker->insertDPValue(DPV, InsertAtHead);
+  DPMarker *M = createMarker(Where);
+  M->insertDPValue(DPV, InsertAtHead);
 }
 
 DPMarker *BasicBlock::getNextMarker(Instruction *I) {
diff --git a/llvm/lib/IR/DIBuilder.cpp b/llvm/lib/IR/DIBuilder.cpp
index e2b68661440034..ff3163213d71fd 100644
--- a/llvm/lib/IR/DIBuilder.cpp
+++ b/llvm/lib/IR/DIBuilder.cpp
@@ -1096,10 +1096,7 @@ DbgInstPtr DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
     if (InsertBB && InsertBefore)
       InsertBB->insertDPValueBefore(DPL, InsertBefore->getIterator());
     else if (InsertBB)
-      InsertBB->insertDPValueBefore(
-          DPL,
-          std::prev(InsertBB->end())); // this  is awkward/wrong. What to do
-                                       // about insert-at-end shinanigans?
+      InsertBB->insertDPValueBefore(DPL, InsertBB->end());
     // FIXME: Use smart pointers for DbgRecord ownership management.
     return DPL;
   } else {
diff --git a/llvm/unittests/IR/IRBuilderTest.cpp b/llvm/unittests/IR/IRBuilderTest.cpp
index 2c6b2c980b75ea..cedc880e6b079e 100644
--- a/llvm/unittests/IR/IRBuilderTest.cpp
+++ b/llvm/unittests/IR/IRBuilderTest.cpp
@@ -921,9 +921,15 @@ TEST_F(IRBuilderTest, DIBuilder) {
 
     // Insert before I and check order.
     ExpectOrder(DIB.insertLabel(Label, LabelLoc, I), I->getIterator());
-    errs() << *BB << "\n";
-    // FIXME: We can't insert at the end of an incomplete block. Oops.
-    // DbgInstPtr LabelRecord = DIB.insertLabel(Label, Loc, BB); // FIXME.,
+
+    // We should be able to insert at the end of the block, even if there's
+    // no terminator yet. Note that in RemoveDIs mode this record won't get
+    // inserted into the block untill another instruction is added.
+    DbgInstPtr LabelRecord = DIB.insertLabel(Label, LabelLoc, BB);
+    // Specifically do not insert a terminator, to check this works. `I` should
+    // have absorbed the DPLabel in the new debug info mode.
+    I = Builder.CreateAlloca(Builder.getInt1Ty());
+    ExpectOrder(LabelRecord, I->getIterator());
 
     DIB.finalize();
 

>From 88f6e211cfcc124833b0cce6b7ab1de4df515228 Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Mon, 4 Mar 2024 17:37:45 +0000
Subject: [PATCH 08/31] tidy up the label test

---
 llvm/unittests/IR/IRBuilderTest.cpp | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)

diff --git a/llvm/unittests/IR/IRBuilderTest.cpp b/llvm/unittests/IR/IRBuilderTest.cpp
index cedc880e6b079e..ed51c85fa7ffc7 100644
--- a/llvm/unittests/IR/IRBuilderTest.cpp
+++ b/llvm/unittests/IR/IRBuilderTest.cpp
@@ -934,15 +934,25 @@ TEST_F(IRBuilderTest, DIBuilder) {
     DIB.finalize();
 
     // Check the labels are not/are added to Bar's retainedNodes array (AlwaysPreserve).
-    //EXPECT_EQ(Label, BarSP->getRetainedNodes(), BarSP->getRetainedNodes().end());
-    //EXPECT_NE(AlwaysPreserveLabel, BarSP->getRetainedNodes(), BarSP->getRetainedNodes().end());
+    EXPECT_EQ(find(BarSP->getRetainedNodes(), Label),
+              BarSP->getRetainedNodes().end());
+    EXPECT_NE(find(BarSP->getRetainedNodes(), AlwaysPreserveLabel),
+              BarSP->getRetainedNodes().end());
 
     EXPECT_TRUE(verifyModule(*M));
   };
+
+  // Test in old-debug mode.
+  EXPECT_FALSE(M->IsNewDbgInfoFormat);
   RunTest();
+
+  // Test in new-debug mode.
+  // Reset the test then call convertToNewDbgValues to flip the flag
+  // on the test's Module, Funciton and BasicBlock.
   TearDown();
   SetUp();
   M->convertToNewDbgValues();
+  EXPECT_TRUE(M->IsNewDbgInfoFormat);
   RunTest();
 }
 

>From c6bbfe47a22b657596228819a4d12b67e337016e Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Mon, 4 Mar 2024 18:25:38 +0000
Subject: [PATCH 09/31] dbg.values WIP: mem2reg and C API need attendance

---
 llvm/include/llvm/IR/DIBuilder.h              | 27 +++++++++----------
 llvm/lib/IR/DIBuilder.cpp                     | 27 ++++++++++---------
 llvm/lib/IR/DebugInfo.cpp                     |  8 ++++++
 llvm/lib/Transforms/Utils/Local.cpp           | 12 ++++-----
 .../Utils/PromoteMemoryToRegister.cpp         | 25 +++++++++--------
 5 files changed, 53 insertions(+), 46 deletions(-)

diff --git a/llvm/include/llvm/IR/DIBuilder.h b/llvm/include/llvm/IR/DIBuilder.h
index 644e35abf03aeb..862fed0ced77d9 100644
--- a/llvm/include/llvm/IR/DIBuilder.h
+++ b/llvm/include/llvm/IR/DIBuilder.h
@@ -109,10 +109,11 @@ namespace llvm {
                                     Instruction *InsertBefore);
 
     /// Internal helper for insertDbgValueIntrinsic.
-    Instruction *
-    insertDbgValueIntrinsic(llvm::Value *Val, DILocalVariable *VarInfo,
-                            DIExpression *Expr, const DILocation *DL,
-                            BasicBlock *InsertBB, Instruction *InsertBefore);
+    DbgInstPtr insertDbgValueIntrinsic(llvm::Value *Val,
+                                       DILocalVariable *VarInfo,
+                                       DIExpression *Expr, const DILocation *DL,
+                                       BasicBlock *InsertBB,
+                                       Instruction *InsertBefore);
 
   public:
     /// Construct a builder for a module.
@@ -978,11 +979,10 @@ namespace llvm {
     /// \param Expr         A complex location expression.
     /// \param DL           Debug info location.
     /// \param InsertAtEnd Location for the new intrinsic.
-    Instruction *insertDbgValueIntrinsic(llvm::Value *Val,
-                                         DILocalVariable *VarInfo,
-                                         DIExpression *Expr,
-                                         const DILocation *DL,
-                                         BasicBlock *InsertAtEnd);
+    DbgInstPtr insertDbgValueIntrinsic(llvm::Value *Val,
+                                       DILocalVariable *VarInfo,
+                                       DIExpression *Expr, const DILocation *DL,
+                                       BasicBlock *InsertAtEnd);
 
     /// Insert a new llvm.dbg.value intrinsic call.
     /// \param Val          llvm::Value of the variable
@@ -990,11 +990,10 @@ namespace llvm {
     /// \param Expr         A complex location expression.
     /// \param DL           Debug info location.
     /// \param InsertBefore Location for the new intrinsic.
-    Instruction *insertDbgValueIntrinsic(llvm::Value *Val,
-                                         DILocalVariable *VarInfo,
-                                         DIExpression *Expr,
-                                         const DILocation *DL,
-                                         Instruction *InsertBefore);
+    DbgInstPtr insertDbgValueIntrinsic(llvm::Value *Val,
+                                       DILocalVariable *VarInfo,
+                                       DIExpression *Expr, const DILocation *DL,
+                                       Instruction *InsertBefore);
 
     /// Replace the vtable holder in the given type.
     ///
diff --git a/llvm/lib/IR/DIBuilder.cpp b/llvm/lib/IR/DIBuilder.cpp
index ff3163213d71fd..1611abd526f567 100644
--- a/llvm/lib/IR/DIBuilder.cpp
+++ b/llvm/lib/IR/DIBuilder.cpp
@@ -983,23 +983,24 @@ DbgInstPtr DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
   return insertLabel(LabelInfo, DL, InsertAtEnd, nullptr);
 }
 
-Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V,
-                                                DILocalVariable *VarInfo,
-                                                DIExpression *Expr,
-                                                const DILocation *DL,
-                                                Instruction *InsertBefore) {
-  Instruction *DVI = insertDbgValueIntrinsic(
+DbgInstPtr DIBuilder::insertDbgValueIntrinsic(Value *V,
+                                              DILocalVariable *VarInfo,
+                                              DIExpression *Expr,
+                                              const DILocation *DL,
+                                              Instruction *InsertBefore) {
+  DbgInstPtr DVI = insertDbgValueIntrinsic(
       V, VarInfo, Expr, DL, InsertBefore ? InsertBefore->getParent() : nullptr,
       InsertBefore);
-  cast<CallInst>(DVI)->setTailCall();
+  if (DVI.is<Instruction *>())
+    cast<CallInst>(DVI.get<Instruction *>())->setTailCall();
   return DVI;
 }
 
-Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V,
-                                                DILocalVariable *VarInfo,
-                                                DIExpression *Expr,
-                                                const DILocation *DL,
-                                                BasicBlock *InsertAtEnd) {
+DbgInstPtr DIBuilder::insertDbgValueIntrinsic(Value *V,
+                                              DILocalVariable *VarInfo,
+                                              DIExpression *Expr,
+                                              const DILocation *DL,
+                                              BasicBlock *InsertAtEnd) {
   return insertDbgValueIntrinsic(V, VarInfo, Expr, DL, InsertAtEnd, nullptr);
 }
 
@@ -1023,7 +1024,7 @@ static Function *getDeclareIntrin(Module &M) {
   return Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
 }
 
-Instruction *DIBuilder::insertDbgValueIntrinsic(
+DbgInstPtr DIBuilder::insertDbgValueIntrinsic(
     llvm::Value *Val, DILocalVariable *VarInfo, DIExpression *Expr,
     const DILocation *DL, BasicBlock *InsertBB, Instruction *InsertBefore) {
   if (!ValueFn)
diff --git a/llvm/lib/IR/DebugInfo.cpp b/llvm/lib/IR/DebugInfo.cpp
index 1f3ff2246a4453..298c36b7762d04 100644
--- a/llvm/lib/IR/DebugInfo.cpp
+++ b/llvm/lib/IR/DebugInfo.cpp
@@ -1684,10 +1684,14 @@ LLVMValueRef LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder,
                                                LLVMMetadataRef Expr,
                                                LLVMMetadataRef DebugLoc,
                                                LLVMValueRef Instr) {
+  return LLVMValueRef();
+  // FIXME: What to do here?
+  /*
   return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
                   unwrap(Val), unwrap<DILocalVariable>(VarInfo),
                   unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
                   unwrap<Instruction>(Instr)));
+   */
 }
 
 LLVMValueRef LLVMDIBuilderInsertDbgValueAtEnd(LLVMDIBuilderRef Builder,
@@ -1696,10 +1700,14 @@ LLVMValueRef LLVMDIBuilderInsertDbgValueAtEnd(LLVMDIBuilderRef Builder,
                                               LLVMMetadataRef Expr,
                                               LLVMMetadataRef DebugLoc,
                                               LLVMBasicBlockRef Block) {
+  return LLVMValueRef();
+  // FIXME: What to do here?
+  /*
   return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
                   unwrap(Val), unwrap<DILocalVariable>(VarInfo),
                   unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
                   unwrap(Block)));
+   */
 }
 
 LLVMMetadataRef LLVMDIBuilderCreateAutoVariable(
diff --git a/llvm/lib/Transforms/Utils/Local.cpp b/llvm/lib/Transforms/Utils/Local.cpp
index d3bb89075015e9..a44536e34c9225 100644
--- a/llvm/lib/Transforms/Utils/Local.cpp
+++ b/llvm/lib/Transforms/Utils/Local.cpp
@@ -1649,9 +1649,9 @@ static void insertDbgValueOrDPValue(DIBuilder &Builder, Value *DV,
                                     const DebugLoc &NewLoc,
                                     BasicBlock::iterator Instr) {
   if (!UseNewDbgInfoFormat) {
-    auto *DbgVal = Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc,
-                                                   (Instruction *)nullptr);
-    DbgVal->insertBefore(Instr);
+    auto DbgVal = Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc,
+                                                  (Instruction *)nullptr);
+    DbgVal.get<Instruction *>()->insertBefore(Instr);
   } else {
     // RemoveDIs: if we're using the new debug-info format, allocate a
     // DPValue directly instead of a dbg.value intrinsic.
@@ -1667,9 +1667,9 @@ static void insertDbgValueOrDPValueAfter(DIBuilder &Builder, Value *DV,
                                          const DebugLoc &NewLoc,
                                          BasicBlock::iterator Instr) {
   if (!UseNewDbgInfoFormat) {
-    auto *DbgVal = Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc,
-                                                   (Instruction *)nullptr);
-    DbgVal->insertAfter(&*Instr);
+    auto DbgVal = Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc,
+                                                  (Instruction *)nullptr);
+    DbgVal.get<Instruction *>()->insertAfter(&*Instr);
   } else {
     // RemoveDIs: if we're using the new debug-info format, allocate a
     // DPValue directly instead of a dbg.value intrinsic.
diff --git a/llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp b/llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp
index 88b05aab8db4df..b462803bad38c3 100644
--- a/llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp
+++ b/llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp
@@ -101,21 +101,20 @@ bool llvm::isAllocaPromotable(const AllocaInst *AI) {
 
 namespace {
 
-static DPValue *createDebugValue(DIBuilder &DIB, Value *NewValue,
-                                 DILocalVariable *Variable,
-                                 DIExpression *Expression, const DILocation *DI,
-                                 DPValue *InsertBefore) {
+static void createDebugValue(DIBuilder &DIB, Value *NewValue,
+                             DILocalVariable *Variable,
+                             DIExpression *Expression, const DILocation *DI,
+                             DPValue *InsertBefore) {
+  // FIXME: Merge these two functions now that DIBuilder supports DPValues.
+  // We neeed the API to accept DPValues as an insert point for that to work.
   (void)DIB;
-  return DPValue::createDPValue(NewValue, Variable, Expression, DI,
-                                *InsertBefore);
+  DPValue::createDPValue(NewValue, Variable, Expression, DI, *InsertBefore);
 }
-static DbgValueInst *createDebugValue(DIBuilder &DIB, Value *NewValue,
-                                      DILocalVariable *Variable,
-                                      DIExpression *Expression,
-                                      const DILocation *DI,
-                                      Instruction *InsertBefore) {
-  return static_cast<DbgValueInst *>(DIB.insertDbgValueIntrinsic(
-      NewValue, Variable, Expression, DI, InsertBefore));
+static void createDebugValue(DIBuilder &DIB, Value *NewValue,
+                             DILocalVariable *Variable,
+                             DIExpression *Expression, const DILocation *DI,
+                             Instruction *InsertBefore) {
+  DIB.insertDbgValueIntrinsic(NewValue, Variable, Expression, DI, InsertBefore);
 }
 
 /// Helper for updating assignment tracking debug info when promoting allocas.

>From 035630fc5adaca4b50946b2039e76245c255b4b0 Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Tue, 5 Mar 2024 10:54:36 +0000
Subject: [PATCH 10/31] add unittest for dbg.vals

---
 llvm/lib/IR/DIBuilder.cpp           | 17 +++++++++++++----
 llvm/unittests/IR/IRBuilderTest.cpp | 23 ++++++++++++++++++++---
 2 files changed, 33 insertions(+), 7 deletions(-)

diff --git a/llvm/lib/IR/DIBuilder.cpp b/llvm/lib/IR/DIBuilder.cpp
index 1611abd526f567..f94b72c24206e5 100644
--- a/llvm/lib/IR/DIBuilder.cpp
+++ b/llvm/lib/IR/DIBuilder.cpp
@@ -1027,10 +1027,19 @@ static Function *getDeclareIntrin(Module &M) {
 DbgInstPtr DIBuilder::insertDbgValueIntrinsic(
     llvm::Value *Val, DILocalVariable *VarInfo, DIExpression *Expr,
     const DILocation *DL, BasicBlock *InsertBB, Instruction *InsertBefore) {
-  if (!ValueFn)
-    ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
-  return insertDbgIntrinsic(ValueFn, Val, VarInfo, Expr, DL, InsertBB,
-                            InsertBefore);
+  if (M.IsNewDbgInfoFormat) {
+    DPValue *DPV = DPValue::createDPValue(Val, VarInfo, Expr, DL);
+    if (InsertBefore && InsertBB)
+      InsertBB->insertDPValueBefore(DPV, InsertBefore->getIterator());
+    else if (InsertBB)
+      InsertBB->insertDPValueBefore(DPV, InsertBB->end());
+    return DPV;
+  } else {
+    if (!ValueFn)
+      ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
+    return insertDbgIntrinsic(ValueFn, Val, VarInfo, Expr, DL, InsertBB,
+                              InsertBefore);
+  }
 }
 
 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
diff --git a/llvm/unittests/IR/IRBuilderTest.cpp b/llvm/unittests/IR/IRBuilderTest.cpp
index ed51c85fa7ffc7..1de1dec2efc168 100644
--- a/llvm/unittests/IR/IRBuilderTest.cpp
+++ b/llvm/unittests/IR/IRBuilderTest.cpp
@@ -912,7 +912,8 @@ TEST_F(IRBuilderTest, DIBuilder) {
     // inserting debug intrinsics before, to make end-checking easier.
     I = Builder.CreateAlloca(Builder.getInt1Ty());
 
-    // Label metadata and records.
+    // Label metadata and records
+    // --------------------------
     DILocation *LabelLoc = DILocation::get(Ctx, 1, 0, BarScope);
     DILabel *AlwaysPreserveLabel = DIB.createLabel(
         BarScope, "meles_meles", File, 1, /*AlwaysPreserve*/ true);
@@ -928,16 +929,32 @@ TEST_F(IRBuilderTest, DIBuilder) {
     DbgInstPtr LabelRecord = DIB.insertLabel(Label, LabelLoc, BB);
     // Specifically do not insert a terminator, to check this works. `I` should
     // have absorbed the DPLabel in the new debug info mode.
-    I = Builder.CreateAlloca(Builder.getInt1Ty());
+    I = Builder.CreateAlloca(Builder.getInt32Ty());
     ExpectOrder(LabelRecord, I->getIterator());
 
-    DIB.finalize();
+    // Variable metadata and records
+    // -----------------------------
+    DILocation *VarLoc = DILocation::get(Ctx, 2, 0, BarScope);
+    auto *IntType = DIB.createBasicType("int", 32, dwarf::DW_ATE_signed);
+    DILocalVariable *VarX =
+        DIB.createAutoVariable(BarSP, "X", File, 2, IntType, true);
+    ExpectOrder(
+        DIB.insertDbgValueIntrinsic(I, VarX, DIB.createExpression(), VarLoc, I),
+        I->getIterator());
+    // Check inserting at end of the block works as with labels.
+    DbgInstPtr VarXValue = DIB.insertDbgValueIntrinsic(
+        I, VarX, DIB.createExpression(), VarLoc, BB);
+    I = Builder.CreateAlloca(Builder.getInt32Ty());
+    ExpectOrder(VarXValue, I->getIterator());
 
+    DIB.finalize();
     // Check the labels are not/are added to Bar's retainedNodes array (AlwaysPreserve).
     EXPECT_EQ(find(BarSP->getRetainedNodes(), Label),
               BarSP->getRetainedNodes().end());
     EXPECT_NE(find(BarSP->getRetainedNodes(), AlwaysPreserveLabel),
               BarSP->getRetainedNodes().end());
+    EXPECT_NE(find(BarSP->getRetainedNodes(), VarX),
+              BarSP->getRetainedNodes().end());
 
     EXPECT_TRUE(verifyModule(*M));
   };

>From 1f95a01694c911d3a37f3dcc4a92006ffde385ce Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Tue, 5 Mar 2024 11:28:25 +0000
Subject: [PATCH 11/31] declare API. Sans C-API. Needs test and impl

---
 llvm/include/llvm/IR/DIBuilder.h | 18 +++++++++---------
 llvm/lib/IR/DIBuilder.cpp        | 20 ++++++++++----------
 llvm/lib/IR/DebugInfo.cpp        |  8 ++++++++
 3 files changed, 27 insertions(+), 19 deletions(-)

diff --git a/llvm/include/llvm/IR/DIBuilder.h b/llvm/include/llvm/IR/DIBuilder.h
index 862fed0ced77d9..c4c3c3ca52cd29 100644
--- a/llvm/include/llvm/IR/DIBuilder.h
+++ b/llvm/include/llvm/IR/DIBuilder.h
@@ -93,9 +93,9 @@ namespace llvm {
     void trackIfUnresolved(MDNode *N);
 
     /// Internal helper for insertDeclare.
-    Instruction *insertDeclare(llvm::Value *Storage, DILocalVariable *VarInfo,
-                               DIExpression *Expr, const DILocation *DL,
-                               BasicBlock *InsertBB, Instruction *InsertBefore);
+    DbgInstPtr insertDeclare(llvm::Value *Storage, DILocalVariable *VarInfo,
+                             DIExpression *Expr, const DILocation *DL,
+                             BasicBlock *InsertBB, Instruction *InsertBefore);
 
     /// Internal helper for insertLabel.
     DbgInstPtr insertLabel(DILabel *LabelInfo, const DILocation *DL,
@@ -925,9 +925,9 @@ namespace llvm {
     /// \param Expr        A complex location expression.
     /// \param DL          Debug info location.
     /// \param InsertAtEnd Location for the new intrinsic.
-    Instruction *insertDeclare(llvm::Value *Storage, DILocalVariable *VarInfo,
-                               DIExpression *Expr, const DILocation *DL,
-                               BasicBlock *InsertAtEnd);
+    DbgInstPtr insertDeclare(llvm::Value *Storage, DILocalVariable *VarInfo,
+                             DIExpression *Expr, const DILocation *DL,
+                             BasicBlock *InsertAtEnd);
 
     /// Insert a new llvm.dbg.assign intrinsic call.
     /// \param LinkedInstr   Instruction with a DIAssignID to link with the new
@@ -955,9 +955,9 @@ namespace llvm {
     /// \param Expr         A complex location expression.
     /// \param DL           Debug info location.
     /// \param InsertBefore Location for the new intrinsic.
-    Instruction *insertDeclare(llvm::Value *Storage, DILocalVariable *VarInfo,
-                               DIExpression *Expr, const DILocation *DL,
-                               Instruction *InsertBefore);
+    DbgInstPtr insertDeclare(llvm::Value *Storage, DILocalVariable *VarInfo,
+                             DIExpression *Expr, const DILocation *DL,
+                             Instruction *InsertBefore);
 
     /// Insert a new llvm.dbg.label intrinsic call.
     /// \param LabelInfo    Label's debug info descriptor.
diff --git a/llvm/lib/IR/DIBuilder.cpp b/llvm/lib/IR/DIBuilder.cpp
index f94b72c24206e5..e68a55fbe28299 100644
--- a/llvm/lib/IR/DIBuilder.cpp
+++ b/llvm/lib/IR/DIBuilder.cpp
@@ -925,16 +925,16 @@ DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
                                      File, Line, Col);
 }
 
-Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
-                                      DIExpression *Expr, const DILocation *DL,
-                                      Instruction *InsertBefore) {
+DbgInstPtr DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
+                                    DIExpression *Expr, const DILocation *DL,
+                                    Instruction *InsertBefore) {
   return insertDeclare(Storage, VarInfo, Expr, DL, InsertBefore->getParent(),
                        InsertBefore);
 }
 
-Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
-                                      DIExpression *Expr, const DILocation *DL,
-                                      BasicBlock *InsertAtEnd) {
+DbgInstPtr DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
+                                    DIExpression *Expr, const DILocation *DL,
+                                    BasicBlock *InsertAtEnd) {
   // If this block already has a terminator then insert this intrinsic before
   // the terminator. Otherwise, put it at the end of the block.
   Instruction *InsertBefore = InsertAtEnd->getTerminator();
@@ -1042,10 +1042,10 @@ DbgInstPtr DIBuilder::insertDbgValueIntrinsic(
   }
 }
 
-Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
-                                      DIExpression *Expr, const DILocation *DL,
-                                      BasicBlock *InsertBB,
-                                      Instruction *InsertBefore) {
+DbgInstPtr DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
+                                    DIExpression *Expr, const DILocation *DL,
+                                    BasicBlock *InsertBB,
+                                    Instruction *InsertBefore) {
   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
   assert(DL && "Expected debug loc");
   assert(DL->getScope()->getSubprogram() ==
diff --git a/llvm/lib/IR/DebugInfo.cpp b/llvm/lib/IR/DebugInfo.cpp
index 298c36b7762d04..e7b42c29918d3d 100644
--- a/llvm/lib/IR/DebugInfo.cpp
+++ b/llvm/lib/IR/DebugInfo.cpp
@@ -1663,19 +1663,27 @@ LLVMValueRef
 LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
                                  LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
                                  LLVMMetadataRef DL, LLVMValueRef Instr) {
+  return LLVMValueRef();
+  // FIXME: What to do here?
+  /*
   return wrap(unwrap(Builder)->insertDeclare(
                   unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
                   unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
                   unwrap<Instruction>(Instr)));
+  */
 }
 
 LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd(
     LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
     LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMBasicBlockRef Block) {
+  return LLVMValueRef();
+  // FIXME: What to do here?
+  /*
   return wrap(unwrap(Builder)->insertDeclare(
                   unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
                   unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
                   unwrap(Block)));
+  */
 }
 
 LLVMValueRef LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder,

>From eb428e63ffc07ae843c180a862d1fc253ec45fee Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Tue, 5 Mar 2024 11:39:50 +0000
Subject: [PATCH 12/31] add insertDPValue helper

---
 llvm/include/llvm/IR/DIBuilder.h |  4 ++++
 llvm/lib/IR/DIBuilder.cpp        | 18 ++++++++++++++----
 2 files changed, 18 insertions(+), 4 deletions(-)

diff --git a/llvm/include/llvm/IR/DIBuilder.h b/llvm/include/llvm/IR/DIBuilder.h
index c4c3c3ca52cd29..d0a807cad71d24 100644
--- a/llvm/include/llvm/IR/DIBuilder.h
+++ b/llvm/include/llvm/IR/DIBuilder.h
@@ -101,6 +101,10 @@ namespace llvm {
     DbgInstPtr insertLabel(DILabel *LabelInfo, const DILocation *DL,
                            BasicBlock *InsertBB, Instruction *InsertBefore);
 
+    /// Internal helper. Track metadata if untracked and insert \p DPV.
+    void insertDPValue(DPValue *DPV, BasicBlock *InsertBB,
+                       Instruction *InsertBefore);
+
     /// Internal helper with common code used by insertDbg{Value,Addr}Intrinsic.
     Instruction *insertDbgIntrinsic(llvm::Function *Intrinsic, llvm::Value *Val,
                                     DILocalVariable *VarInfo,
diff --git a/llvm/lib/IR/DIBuilder.cpp b/llvm/lib/IR/DIBuilder.cpp
index e68a55fbe28299..b9a78fa7d3700a 100644
--- a/llvm/lib/IR/DIBuilder.cpp
+++ b/llvm/lib/IR/DIBuilder.cpp
@@ -1029,10 +1029,7 @@ DbgInstPtr DIBuilder::insertDbgValueIntrinsic(
     const DILocation *DL, BasicBlock *InsertBB, Instruction *InsertBefore) {
   if (M.IsNewDbgInfoFormat) {
     DPValue *DPV = DPValue::createDPValue(Val, VarInfo, Expr, DL);
-    if (InsertBefore && InsertBB)
-      InsertBB->insertDPValueBefore(DPV, InsertBefore->getIterator());
-    else if (InsertBB)
-      InsertBB->insertDPValueBefore(DPV, InsertBB->end());
+    insertDPValue(DPV, InsertBB, InsertBefore);
     return DPV;
   } else {
     if (!ValueFn)
@@ -1065,6 +1062,19 @@ DbgInstPtr DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
   return B.CreateCall(DeclareFn, Args);
 }
 
+void DIBuilder::insertDPValue(DPValue *DPV, BasicBlock *InsertBB,
+                              Instruction *InsertBefore) {
+  trackIfUnresolved(DPV->getVariable());
+  trackIfUnresolved(DPV->getExpression());
+  if (DPV->isDbgAssign())
+    trackIfUnresolved(DPV->getAddressExpression());
+
+  if (InsertBB && InsertBefore)
+    InsertBB->insertDPValueBefore(DPV, InsertBefore->getIterator());
+  else if (InsertBB)
+    InsertBB->insertDPValueBefore(DPV, InsertBB->end());
+}
+
 Instruction *DIBuilder::insertDbgIntrinsic(llvm::Function *IntrinsicFn,
                                            Value *V, DILocalVariable *VarInfo,
                                            DIExpression *Expr,

>From 42f4e742818fa0443a326e689764724b6d35603b Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Tue, 5 Mar 2024 11:45:13 +0000
Subject: [PATCH 13/31] declare impl + tidy some others

---
 llvm/lib/IR/DIBuilder.cpp | 33 ++++++++++++++++++++-------------
 1 file changed, 20 insertions(+), 13 deletions(-)

diff --git a/llvm/lib/IR/DIBuilder.cpp b/llvm/lib/IR/DIBuilder.cpp
index b9a78fa7d3700a..c5ac298759a273 100644
--- a/llvm/lib/IR/DIBuilder.cpp
+++ b/llvm/lib/IR/DIBuilder.cpp
@@ -1031,12 +1031,12 @@ DbgInstPtr DIBuilder::insertDbgValueIntrinsic(
     DPValue *DPV = DPValue::createDPValue(Val, VarInfo, Expr, DL);
     insertDPValue(DPV, InsertBB, InsertBefore);
     return DPV;
-  } else {
-    if (!ValueFn)
-      ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
-    return insertDbgIntrinsic(ValueFn, Val, VarInfo, Expr, DL, InsertBB,
-                              InsertBefore);
   }
+
+  if (!ValueFn)
+    ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
+  return insertDbgIntrinsic(ValueFn, Val, VarInfo, Expr, DL, InsertBB,
+                            InsertBefore);
 }
 
 DbgInstPtr DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
@@ -1048,6 +1048,13 @@ DbgInstPtr DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
   assert(DL->getScope()->getSubprogram() ==
              VarInfo->getScope()->getSubprogram() &&
          "Expected matching subprograms");
+
+  if (M.IsNewDbgInfoFormat) {
+    DPValue *DPV = DPValue::createDPVDeclare(Storage, VarInfo, Expr, DL);
+    insertDPValue(DPV, InsertBB, InsertBefore);
+    return DPV;
+  }
+
   if (!DeclareFn)
     DeclareFn = getDeclareIntrin(M);
 
@@ -1119,16 +1126,16 @@ DbgInstPtr DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
       InsertBB->insertDPValueBefore(DPL, InsertBB->end());
     // FIXME: Use smart pointers for DbgRecord ownership management.
     return DPL;
-  } else {
-    if (!LabelFn)
-      LabelFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_label);
+  }
 
-    Value *Args[] = {MetadataAsValue::get(VMContext, LabelInfo)};
+  if (!LabelFn)
+    LabelFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_label);
 
-    IRBuilder<> B(DL->getContext());
-    initIRBuilder(B, DL, InsertBB, InsertBefore);
-    return B.CreateCall(LabelFn, Args);
-  }
+  Value *Args[] = {MetadataAsValue::get(VMContext, LabelInfo)};
+
+  IRBuilder<> B(DL->getContext());
+  initIRBuilder(B, DL, InsertBB, InsertBefore);
+  return B.CreateCall(LabelFn, Args);
 }
 
 void DIBuilder::replaceVTableHolder(DICompositeType *&T, DIType *VTableHolder) {

>From 063f9cda150cba3092c397838ebb8333ef1baaac Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Tue, 5 Mar 2024 11:51:41 +0000
Subject: [PATCH 14/31] dbg.declare unittest

---
 llvm/unittests/IR/IRBuilderTest.cpp | 56 ++++++++++++++++++-----------
 1 file changed, 36 insertions(+), 20 deletions(-)

diff --git a/llvm/unittests/IR/IRBuilderTest.cpp b/llvm/unittests/IR/IRBuilderTest.cpp
index 1de1dec2efc168..7d0b6ae6eaa835 100644
--- a/llvm/unittests/IR/IRBuilderTest.cpp
+++ b/llvm/unittests/IR/IRBuilderTest.cpp
@@ -920,17 +920,19 @@ TEST_F(IRBuilderTest, DIBuilder) {
     DILabel *Label =
         DIB.createLabel(BarScope, "badger", File, 1, /*AlwaysPreserve*/ false);
 
-    // Insert before I and check order.
-    ExpectOrder(DIB.insertLabel(Label, LabelLoc, I), I->getIterator());
-
-    // We should be able to insert at the end of the block, even if there's
-    // no terminator yet. Note that in RemoveDIs mode this record won't get
-    // inserted into the block untill another instruction is added.
-    DbgInstPtr LabelRecord = DIB.insertLabel(Label, LabelLoc, BB);
-    // Specifically do not insert a terminator, to check this works. `I` should
-    // have absorbed the DPLabel in the new debug info mode.
-    I = Builder.CreateAlloca(Builder.getInt32Ty());
-    ExpectOrder(LabelRecord, I->getIterator());
+    { /* dbg.label | DPLabel */
+      // Insert before I and check order.
+      ExpectOrder(DIB.insertLabel(Label, LabelLoc, I), I->getIterator());
+
+      // We should be able to insert at the end of the block, even if there's
+      // no terminator yet. Note that in RemoveDIs mode this record won't get
+      // inserted into the block untill another instruction is added.
+      DbgInstPtr LabelRecord = DIB.insertLabel(Label, LabelLoc, BB);
+      // Specifically do not insert a terminator, to check this works. `I`
+      // should have absorbed the DPLabel in the new debug info mode.
+      I = Builder.CreateAlloca(Builder.getInt32Ty());
+      ExpectOrder(LabelRecord, I->getIterator());
+    }
 
     // Variable metadata and records
     // -----------------------------
@@ -938,14 +940,27 @@ TEST_F(IRBuilderTest, DIBuilder) {
     auto *IntType = DIB.createBasicType("int", 32, dwarf::DW_ATE_signed);
     DILocalVariable *VarX =
         DIB.createAutoVariable(BarSP, "X", File, 2, IntType, true);
-    ExpectOrder(
-        DIB.insertDbgValueIntrinsic(I, VarX, DIB.createExpression(), VarLoc, I),
-        I->getIterator());
-    // Check inserting at end of the block works as with labels.
-    DbgInstPtr VarXValue = DIB.insertDbgValueIntrinsic(
-        I, VarX, DIB.createExpression(), VarLoc, BB);
-    I = Builder.CreateAlloca(Builder.getInt32Ty());
-    ExpectOrder(VarXValue, I->getIterator());
+    DILocalVariable *VarY =
+        DIB.createAutoVariable(BarSP, "Y", File, 2, IntType, true);
+    { /* dbg.value | DPValue::Value */
+      ExpectOrder(DIB.insertDbgValueIntrinsic(I, VarX, DIB.createExpression(),
+                                              VarLoc, I),
+                  I->getIterator());
+      // Check inserting at end of the block works as with labels.
+      DbgInstPtr VarXValue = DIB.insertDbgValueIntrinsic(
+          I, VarX, DIB.createExpression(), VarLoc, BB);
+      I = Builder.CreateAlloca(Builder.getInt32Ty());
+      ExpectOrder(VarXValue, I->getIterator());
+    }
+    { /* dbg.declare | DPValue::Declare */
+      ExpectOrder(DIB.insertDeclare(I, VarY, DIB.createExpression(), VarLoc, I),
+                  I->getIterator());
+      // Check inserting at end of the block works as with labels.
+      DbgInstPtr VarYDeclare =
+          DIB.insertDeclare(I, VarY, DIB.createExpression(), VarLoc, BB);
+      I = Builder.CreateAlloca(Builder.getInt32Ty());
+      ExpectOrder(VarYDeclare, I->getIterator());
+    }
 
     DIB.finalize();
     // Check the labels are not/are added to Bar's retainedNodes array (AlwaysPreserve).
@@ -955,7 +970,8 @@ TEST_F(IRBuilderTest, DIBuilder) {
               BarSP->getRetainedNodes().end());
     EXPECT_NE(find(BarSP->getRetainedNodes(), VarX),
               BarSP->getRetainedNodes().end());
-
+    EXPECT_NE(find(BarSP->getRetainedNodes(), VarY),
+              BarSP->getRetainedNodes().end());
     EXPECT_TRUE(verifyModule(*M));
   };
 

>From 60f9a2f0a55e6681dbd32313aefae669c9143113 Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Tue, 5 Mar 2024 12:37:23 +0000
Subject: [PATCH 15/31] dbg.assign api and impl

---
 llvm/include/llvm/IR/DIBuilder.h    |  9 +++---
 llvm/lib/IR/DIBuilder.cpp           | 26 +++++++++++------
 llvm/lib/IR/DebugInfo.cpp           | 11 ++++++--
 llvm/lib/Transforms/Scalar/SROA.cpp | 44 +++++++++++------------------
 4 files changed, 46 insertions(+), 44 deletions(-)

diff --git a/llvm/include/llvm/IR/DIBuilder.h b/llvm/include/llvm/IR/DIBuilder.h
index d0a807cad71d24..eac2f86635c48a 100644
--- a/llvm/include/llvm/IR/DIBuilder.h
+++ b/llvm/include/llvm/IR/DIBuilder.h
@@ -947,11 +947,10 @@ namespace llvm {
     /// \param DL            Debug info location, usually: (line: 0,
     ///                      column: 0, scope: var-decl-scope). See
     ///                      getDebugValueLoc.
-    DbgAssignIntrinsic *insertDbgAssign(Instruction *LinkedInstr, Value *Val,
-                                        DILocalVariable *SrcVar,
-                                        DIExpression *ValExpr, Value *Addr,
-                                        DIExpression *AddrExpr,
-                                        const DILocation *DL);
+    DbgInstPtr insertDbgAssign(Instruction *LinkedInstr, Value *Val,
+                               DILocalVariable *SrcVar, DIExpression *ValExpr,
+                               Value *Addr, DIExpression *AddrExpr,
+                               const DILocation *DL);
 
     /// Insert a new llvm.dbg.declare intrinsic call.
     /// \param Storage      llvm::Value of the variable
diff --git a/llvm/lib/IR/DIBuilder.cpp b/llvm/lib/IR/DIBuilder.cpp
index c5ac298759a273..57b3f5bd29b5d5 100644
--- a/llvm/lib/IR/DIBuilder.cpp
+++ b/llvm/lib/IR/DIBuilder.cpp
@@ -941,19 +941,29 @@ DbgInstPtr DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
   return insertDeclare(Storage, VarInfo, Expr, DL, InsertAtEnd, InsertBefore);
 }
 
-DbgAssignIntrinsic *
-DIBuilder::insertDbgAssign(Instruction *LinkedInstr, Value *Val,
-                           DILocalVariable *SrcVar, DIExpression *ValExpr,
-                           Value *Addr, DIExpression *AddrExpr,
-                           const DILocation *DL) {
+DbgInstPtr DIBuilder::insertDbgAssign(Instruction *LinkedInstr, Value *Val,
+                                      DILocalVariable *SrcVar,
+                                      DIExpression *ValExpr, Value *Addr,
+                                      DIExpression *AddrExpr,
+                                      const DILocation *DL) {
+  auto *Link = LinkedInstr->getMetadata(LLVMContext::MD_DIAssignID);
+  assert(Link && "Linked instruction must have DIAssign metadata attached");
+
+  if (M.IsNewDbgInfoFormat) {
+    DPValue *DPV = DPValue::createLinkedDPVAssign(LinkedInstr, Val, SrcVar,
+                                                  ValExpr, Addr, AddrExpr, DL);
+    BasicBlock *InsertBB = LinkedInstr->getParent();
+    BasicBlock::iterator NextIt = std::next(LinkedInstr->getIterator());
+    Instruction *InsertBefore = NextIt == InsertBB->end() ? nullptr : &*NextIt;
+    insertDPValue(DPV, InsertBB, InsertBefore);
+    return DPV;
+  }
+
   LLVMContext &Ctx = LinkedInstr->getContext();
   Module *M = LinkedInstr->getModule();
   if (!AssignFn)
     AssignFn = Intrinsic::getDeclaration(M, Intrinsic::dbg_assign);
 
-  auto *Link = LinkedInstr->getMetadata(LLVMContext::MD_DIAssignID);
-  assert(Link && "Linked instruction must have DIAssign metadata attached");
-
   std::array<Value *, 6> Args = {
       MetadataAsValue::get(Ctx, ValueAsMetadata::get(Val)),
       MetadataAsValue::get(Ctx, SrcVar),
diff --git a/llvm/lib/IR/DebugInfo.cpp b/llvm/lib/IR/DebugInfo.cpp
index e7b42c29918d3d..721b276ac06b43 100644
--- a/llvm/lib/IR/DebugInfo.cpp
+++ b/llvm/lib/IR/DebugInfo.cpp
@@ -2131,10 +2131,15 @@ static void emitDbgAssign(AssignmentInfo Info, Value *Val, Value *Dest,
     LLVM_DEBUG(if (Assign) errs() << " > INSERT: " << *Assign << "\n");
     return;
   }
-  auto *Assign = DIB.insertDbgAssign(&StoreLikeInst, Val, VarRec.Var, Expr,
-                                     Dest, AddrExpr, VarRec.DL);
+  auto Assign = DIB.insertDbgAssign(&StoreLikeInst, Val, VarRec.Var, Expr, Dest,
+                                    AddrExpr, VarRec.DL);
   (void)Assign;
-  LLVM_DEBUG(if (Assign) errs() << " > INSERT: " << *Assign << "\n");
+  LLVM_DEBUG(if (!Assign.isNull()) {
+    if (Assign.is<DbgRecord *>())
+      errs() << " > INSERT: " << *Assign.get<DbgRecord *>() << "\n";
+    else
+      errs() << " > INSERT: " << *Assign.get<Instruction *>() << "\n";
+  });
 }
 
 #undef DEBUG_TYPE // Silence redefinition warning (from ConstantsContext.h).
diff --git a/llvm/lib/Transforms/Scalar/SROA.cpp b/llvm/lib/Transforms/Scalar/SROA.cpp
index e11b984f13bbc4..8844b32738f98d 100644
--- a/llvm/lib/Transforms/Scalar/SROA.cpp
+++ b/llvm/lib/Transforms/Scalar/SROA.cpp
@@ -324,25 +324,6 @@ static DebugVariable getAggregateVariable(DPValue *DPV) {
                        DPV->getDebugLoc().getInlinedAt());
 }
 
-static DPValue *createLinkedAssign(DPValue *, DIBuilder &DIB,
-                                   Instruction *LinkedInstr, Value *NewValue,
-                                   DILocalVariable *Variable,
-                                   DIExpression *Expression, Value *Address,
-                                   DIExpression *AddressExpression,
-                                   const DILocation *DI) {
-  (void)DIB;
-  return DPValue::createLinkedDPVAssign(LinkedInstr, NewValue, Variable,
-                                        Expression, Address, AddressExpression,
-                                        DI);
-}
-static DbgAssignIntrinsic *createLinkedAssign(
-    DbgAssignIntrinsic *, DIBuilder &DIB, Instruction *LinkedInstr,
-    Value *NewValue, DILocalVariable *Variable, DIExpression *Expression,
-    Value *Address, DIExpression *AddressExpression, const DILocation *DI) {
-  return DIB.insertDbgAssign(LinkedInstr, NewValue, Variable, Expression,
-                             Address, AddressExpression, DI);
-}
-
 /// Find linked dbg.assign and generate a new one with the correct
 /// FragmentInfo. Link Inst to the new dbg.assign.  If Value is nullptr the
 /// value component is copied from the old dbg.assign to the new.
@@ -398,7 +379,7 @@ static void migrateDebugInfo(AllocaInst *OldAlloca, bool IsSplit,
   DIBuilder DIB(*OldInst->getModule(), /*AllowUnresolved*/ false);
   assert(OldAlloca->isStaticAlloca());
 
-  auto MigrateDbgAssign = [&](auto DbgAssign) {
+  auto MigrateDbgAssign = [&](auto *DbgAssign) {
     LLVM_DEBUG(dbgs() << "      existing dbg.assign is: " << *DbgAssign
                       << "\n");
     auto *Expr = DbgAssign->getExpression();
@@ -452,10 +433,15 @@ static void migrateDebugInfo(AllocaInst *OldAlloca, bool IsSplit,
     }
 
     ::Value *NewValue = Value ? Value : DbgAssign->getValue();
-    auto *NewAssign = createLinkedAssign(
-        DbgAssign, DIB, Inst, NewValue, DbgAssign->getVariable(), Expr, Dest,
-        DIExpression::get(Expr->getContext(), std::nullopt),
-        DbgAssign->getDebugLoc());
+    // insertDbgAssign returns a PointerUnion of {Instruction* | DbgRecord*}.
+    // If DbgAssign is a DPValue* it'll return a DbgRecord*, otherwise if
+    // DbgAssign is a DbgAssignIntrinsic* it'll return a Instruction*.
+    decltype(DbgAssign) NewAssign = reinterpret_cast<decltype(DbgAssign)>(
+        DIB.insertDbgAssign(Inst, NewValue, DbgAssign->getVariable(), Expr,
+                            Dest,
+                            DIExpression::get(Expr->getContext(), std::nullopt),
+                            DbgAssign->getDebugLoc())
+            .getOpaqueValue());
 
     // If we've updated the value but the original dbg.assign has an arglist
     // then kill it now - we can't use the requested new value.
@@ -5031,9 +5017,11 @@ static void insertNewDbgInst(DIBuilder &DIB, DbgAssignIntrinsic *Orig,
     NewAddr->setMetadata(LLVMContext::MD_DIAssignID,
                          DIAssignID::getDistinct(NewAddr->getContext()));
   }
-  auto *NewAssign = DIB.insertDbgAssign(
-      NewAddr, Orig->getValue(), Orig->getVariable(), NewFragmentExpr, NewAddr,
-      Orig->getAddressExpression(), Orig->getDebugLoc());
+  Instruction *NewAssign =
+      DIB.insertDbgAssign(NewAddr, Orig->getValue(), Orig->getVariable(),
+                          NewFragmentExpr, NewAddr,
+                          Orig->getAddressExpression(), Orig->getDebugLoc())
+          .get<Instruction *>();
   LLVM_DEBUG(dbgs() << "Created new assign intrinsic: " << *NewAssign << "\n");
   (void)NewAssign;
 }
@@ -5052,7 +5040,7 @@ static void insertNewDbgInst(DIBuilder &DIB, DPValue *Orig, AllocaInst *NewAddr,
     NewAddr->setMetadata(LLVMContext::MD_DIAssignID,
                          DIAssignID::getDistinct(NewAddr->getContext()));
   }
-  auto *NewAssign = DPValue::createLinkedDPVAssign(
+  DPValue *NewAssign = DPValue::createLinkedDPVAssign(
       NewAddr, Orig->getValue(), Orig->getVariable(), NewFragmentExpr, NewAddr,
       Orig->getAddressExpression(), Orig->getDebugLoc());
   LLVM_DEBUG(dbgs() << "Created new DPVAssign: " << *NewAssign << "\n");

>From 3a15cfadb7c45739f2a9e808ef043cbf5643f799 Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Tue, 5 Mar 2024 14:44:55 +0000
Subject: [PATCH 16/31] assign test -not working

---
 llvm/lib/IR/DIBuilder.cpp           |  1 +
 llvm/unittests/IR/IRBuilderTest.cpp | 14 ++++++++++++++
 2 files changed, 15 insertions(+)

diff --git a/llvm/lib/IR/DIBuilder.cpp b/llvm/lib/IR/DIBuilder.cpp
index 57b3f5bd29b5d5..7d6e2b6f94355a 100644
--- a/llvm/lib/IR/DIBuilder.cpp
+++ b/llvm/lib/IR/DIBuilder.cpp
@@ -1081,6 +1081,7 @@ DbgInstPtr DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
 
 void DIBuilder::insertDPValue(DPValue *DPV, BasicBlock *InsertBB,
                               Instruction *InsertBefore) {
+  assert(InsertBefore || InsertBB);
   trackIfUnresolved(DPV->getVariable());
   trackIfUnresolved(DPV->getExpression());
   if (DPV->isDbgAssign())
diff --git a/llvm/unittests/IR/IRBuilderTest.cpp b/llvm/unittests/IR/IRBuilderTest.cpp
index 7d0b6ae6eaa835..f83cb01a522e27 100644
--- a/llvm/unittests/IR/IRBuilderTest.cpp
+++ b/llvm/unittests/IR/IRBuilderTest.cpp
@@ -961,7 +961,21 @@ TEST_F(IRBuilderTest, DIBuilder) {
       I = Builder.CreateAlloca(Builder.getInt32Ty());
       ExpectOrder(VarYDeclare, I->getIterator());
     }
+    { /* dbg.assign | DPValue::Assign */
+      I = Builder.CreateAlloca(Builder.getInt32Ty());
+      I->setMetadata(LLVMContext::MD_DIAssignID, DIAssignID::getDistinct(Ctx));
+      Instruction *Before = I;
+      // DbgAssign interface is slightly different - it always inserts after the
+      // linked instr. The old debug mode doesn't support inserting these after
+      // the last instruction.
+      I = Builder.CreateAlloca(Builder.getInt32Ty());
+      DbgInstPtr VarXAssign =
+          DIB.insertDbgAssign(Before, Before, VarX, DIB.createExpression(), Before,
+                              DIB.createExpression(), VarLoc);
+      //ExpectOrder(VarXAssign, I->getIterator());
+    }
 
+    Builder.CreateRet(nullptr);
     DIB.finalize();
     // Check the labels are not/are added to Bar's retainedNodes array (AlwaysPreserve).
     EXPECT_EQ(find(BarSP->getRetainedNodes(), Label),

>From 7754eb963f05f62bafd12d5983648f2697c5cc8b Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Tue, 5 Mar 2024 15:16:25 +0000
Subject: [PATCH 17/31] fix dbg.assign test

---
 llvm/lib/IR/BasicBlock.cpp          |  2 --
 llvm/lib/IR/DIBuilder.cpp           |  7 ++++---
 llvm/unittests/IR/IRBuilderTest.cpp | 14 ++++++++------
 3 files changed, 12 insertions(+), 11 deletions(-)

diff --git a/llvm/lib/IR/BasicBlock.cpp b/llvm/lib/IR/BasicBlock.cpp
index 8b54e35dcd7ead..9c0e68b59f810e 100644
--- a/llvm/lib/IR/BasicBlock.cpp
+++ b/llvm/lib/IR/BasicBlock.cpp
@@ -1043,8 +1043,6 @@ void BasicBlock::insertDPValueBefore(DbgRecord *DPV,
   // assert(Where != end()); // ^ No longer true. Create seperate method if
   // needed?
   assert(Where == end() || Where->getParent() == this);
-  if (Where == end() || !Where->DbgMarker)
-    createMarker(Where);
   bool InsertAtHead = Where.getHeadBit();
   DPMarker *M = createMarker(Where);
   M->insertDPValue(DPV, InsertAtHead);
diff --git a/llvm/lib/IR/DIBuilder.cpp b/llvm/lib/IR/DIBuilder.cpp
index 7d6e2b6f94355a..2dce9213336ab7 100644
--- a/llvm/lib/IR/DIBuilder.cpp
+++ b/llvm/lib/IR/DIBuilder.cpp
@@ -946,12 +946,13 @@ DbgInstPtr DIBuilder::insertDbgAssign(Instruction *LinkedInstr, Value *Val,
                                       DIExpression *ValExpr, Value *Addr,
                                       DIExpression *AddrExpr,
                                       const DILocation *DL) {
-  auto *Link = LinkedInstr->getMetadata(LLVMContext::MD_DIAssignID);
+  auto *Link = cast_or_null<DIAssignID>(
+      LinkedInstr->getMetadata(LLVMContext::MD_DIAssignID));
   assert(Link && "Linked instruction must have DIAssign metadata attached");
 
   if (M.IsNewDbgInfoFormat) {
-    DPValue *DPV = DPValue::createLinkedDPVAssign(LinkedInstr, Val, SrcVar,
-                                                  ValExpr, Addr, AddrExpr, DL);
+    DPValue *DPV = DPValue::createDPVAssign(Val, SrcVar, ValExpr, Link, Addr,
+                                            AddrExpr, DL);
     BasicBlock *InsertBB = LinkedInstr->getParent();
     BasicBlock::iterator NextIt = std::next(LinkedInstr->getIterator());
     Instruction *InsertBefore = NextIt == InsertBB->end() ? nullptr : &*NextIt;
diff --git a/llvm/unittests/IR/IRBuilderTest.cpp b/llvm/unittests/IR/IRBuilderTest.cpp
index f83cb01a522e27..fcf7bf957f55df 100644
--- a/llvm/unittests/IR/IRBuilderTest.cpp
+++ b/llvm/unittests/IR/IRBuilderTest.cpp
@@ -951,6 +951,7 @@ TEST_F(IRBuilderTest, DIBuilder) {
           I, VarX, DIB.createExpression(), VarLoc, BB);
       I = Builder.CreateAlloca(Builder.getInt32Ty());
       ExpectOrder(VarXValue, I->getIterator());
+      EXPECT_EQ(BB->getTrailingDPValues(), nullptr);
     }
     { /* dbg.declare | DPValue::Declare */
       ExpectOrder(DIB.insertDeclare(I, VarY, DIB.createExpression(), VarLoc, I),
@@ -960,19 +961,20 @@ TEST_F(IRBuilderTest, DIBuilder) {
           DIB.insertDeclare(I, VarY, DIB.createExpression(), VarLoc, BB);
       I = Builder.CreateAlloca(Builder.getInt32Ty());
       ExpectOrder(VarYDeclare, I->getIterator());
+      EXPECT_EQ(BB->getTrailingDPValues(), nullptr);
     }
     { /* dbg.assign | DPValue::Assign */
       I = Builder.CreateAlloca(Builder.getInt32Ty());
       I->setMetadata(LLVMContext::MD_DIAssignID, DIAssignID::getDistinct(Ctx));
-      Instruction *Before = I;
       // DbgAssign interface is slightly different - it always inserts after the
-      // linked instr. The old debug mode doesn't support inserting these after
-      // the last instruction.
-      I = Builder.CreateAlloca(Builder.getInt32Ty());
+      // linked instr. Check we can do this with no instruction to insert
+      // before.
       DbgInstPtr VarXAssign =
-          DIB.insertDbgAssign(Before, Before, VarX, DIB.createExpression(), Before,
+          DIB.insertDbgAssign(I, I, VarX, DIB.createExpression(), I,
                               DIB.createExpression(), VarLoc);
-      //ExpectOrder(VarXAssign, I->getIterator());
+      I = Builder.CreateAlloca(Builder.getInt32Ty());
+      ExpectOrder(VarXAssign, I->getIterator());
+      EXPECT_EQ(BB->getTrailingDPValues(), nullptr);
     }
 
     Builder.CreateRet(nullptr);

>From 0a9625111c7d5ae722763978598badedb7f51290 Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Thu, 7 Mar 2024 15:54:43 +0000
Subject: [PATCH 18/31] insert dpassigns 'after' in DIBuilder

---
 llvm/include/llvm/IR/DIBuilder.h |  2 +-
 llvm/lib/IR/DIBuilder.cpp        | 12 ++++++++----
 2 files changed, 9 insertions(+), 5 deletions(-)

diff --git a/llvm/include/llvm/IR/DIBuilder.h b/llvm/include/llvm/IR/DIBuilder.h
index eac2f86635c48a..94af17af8160e9 100644
--- a/llvm/include/llvm/IR/DIBuilder.h
+++ b/llvm/include/llvm/IR/DIBuilder.h
@@ -103,7 +103,7 @@ namespace llvm {
 
     /// Internal helper. Track metadata if untracked and insert \p DPV.
     void insertDPValue(DPValue *DPV, BasicBlock *InsertBB,
-                       Instruction *InsertBefore);
+                       Instruction *InsertBefore, bool InsertAtHead = false);
 
     /// Internal helper with common code used by insertDbg{Value,Addr}Intrinsic.
     Instruction *insertDbgIntrinsic(llvm::Function *Intrinsic, llvm::Value *Val,
diff --git a/llvm/lib/IR/DIBuilder.cpp b/llvm/lib/IR/DIBuilder.cpp
index 2dce9213336ab7..71583b4c9768b0 100644
--- a/llvm/lib/IR/DIBuilder.cpp
+++ b/llvm/lib/IR/DIBuilder.cpp
@@ -954,9 +954,10 @@ DbgInstPtr DIBuilder::insertDbgAssign(Instruction *LinkedInstr, Value *Val,
     DPValue *DPV = DPValue::createDPVAssign(Val, SrcVar, ValExpr, Link, Addr,
                                             AddrExpr, DL);
     BasicBlock *InsertBB = LinkedInstr->getParent();
+    // Insert after LinkedInstr.
     BasicBlock::iterator NextIt = std::next(LinkedInstr->getIterator());
     Instruction *InsertBefore = NextIt == InsertBB->end() ? nullptr : &*NextIt;
-    insertDPValue(DPV, InsertBB, InsertBefore);
+    insertDPValue(DPV, InsertBB, InsertBefore, true);
     return DPV;
   }
 
@@ -1081,17 +1082,20 @@ DbgInstPtr DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
 }
 
 void DIBuilder::insertDPValue(DPValue *DPV, BasicBlock *InsertBB,
-                              Instruction *InsertBefore) {
+                              Instruction *InsertBefore, bool InsertAtHead) {
   assert(InsertBefore || InsertBB);
   trackIfUnresolved(DPV->getVariable());
   trackIfUnresolved(DPV->getExpression());
   if (DPV->isDbgAssign())
     trackIfUnresolved(DPV->getAddressExpression());
 
+  BasicBlock::iterator InsertPt;
   if (InsertBB && InsertBefore)
-    InsertBB->insertDPValueBefore(DPV, InsertBefore->getIterator());
+    InsertPt = InsertBefore->getIterator();
   else if (InsertBB)
-    InsertBB->insertDPValueBefore(DPV, InsertBB->end());
+    InsertPt = InsertBB->end();
+  InsertPt.setHeadBit(InsertAtHead);
+  InsertBB->insertDPValueBefore(DPV, InsertPt);
 }
 
 Instruction *DIBuilder::insertDbgIntrinsic(llvm::Function *IntrinsicFn,

>From 44008e286c3ce64619c57ff3cb3851e81b3f1571 Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Thu, 7 Mar 2024 17:38:40 +0000
Subject: [PATCH 19/31] gross C++

---
 llvm/lib/Transforms/Scalar/SROA.cpp | 18 +++++++++++++-----
 1 file changed, 13 insertions(+), 5 deletions(-)

diff --git a/llvm/lib/Transforms/Scalar/SROA.cpp b/llvm/lib/Transforms/Scalar/SROA.cpp
index 8844b32738f98d..bf06c8fbe4b343 100644
--- a/llvm/lib/Transforms/Scalar/SROA.cpp
+++ b/llvm/lib/Transforms/Scalar/SROA.cpp
@@ -379,7 +379,7 @@ static void migrateDebugInfo(AllocaInst *OldAlloca, bool IsSplit,
   DIBuilder DIB(*OldInst->getModule(), /*AllowUnresolved*/ false);
   assert(OldAlloca->isStaticAlloca());
 
-  auto MigrateDbgAssign = [&](auto *DbgAssign) {
+  auto MigrateDbgAssign = [&](auto *DbgAssign, auto *DbgInstType) {
     LLVM_DEBUG(dbgs() << "      existing dbg.assign is: " << *DbgAssign
                       << "\n");
     auto *Expr = DbgAssign->getExpression();
@@ -436,12 +436,16 @@ static void migrateDebugInfo(AllocaInst *OldAlloca, bool IsSplit,
     // insertDbgAssign returns a PointerUnion of {Instruction* | DbgRecord*}.
     // If DbgAssign is a DPValue* it'll return a DbgRecord*, otherwise if
     // DbgAssign is a DbgAssignIntrinsic* it'll return a Instruction*.
-    decltype(DbgAssign) NewAssign = reinterpret_cast<decltype(DbgAssign)>(
+    // The ugly code below creates a new debug marker, then gets the
+    // pointer type out of the union based on the type of DbgInstType
+    // (Instruction* or DbgRecord*), which is then cast to DbgAssignIntrinsic*
+    // or DPValue* so that the relevant member functions can be called.
+    auto *NewAssign = static_cast<decltype(DbgAssign)>(
         DIB.insertDbgAssign(Inst, NewValue, DbgAssign->getVariable(), Expr,
                             Dest,
                             DIExpression::get(Expr->getContext(), std::nullopt),
                             DbgAssign->getDebugLoc())
-            .getOpaqueValue());
+            .template get<decltype(DbgInstType)>());
 
     // If we've updated the value but the original dbg.assign has an arglist
     // then kill it now - we can't use the requested new value.
@@ -478,8 +482,12 @@ static void migrateDebugInfo(AllocaInst *OldAlloca, bool IsSplit,
     LLVM_DEBUG(dbgs() << "Created new assign: " << *NewAssign << "\n");
   };
 
-  for_each(MarkerRange, MigrateDbgAssign);
-  for_each(DPVAssignMarkerRange, MigrateDbgAssign);
+  for_each(MarkerRange, [&](DbgAssignIntrinsic *DAI) {
+    MigrateDbgAssign(DAI, static_cast<Instruction *>(nullptr));
+  });
+  for_each(DPVAssignMarkerRange, [&](DPValue *DPV) {
+    MigrateDbgAssign(DPV, static_cast<DbgRecord *>(nullptr));
+  });
 }
 
 namespace {

>From 2e69a991ffa5c6b230b5653a71c3f8cd93b0fc9f Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Fri, 8 Mar 2024 15:41:23 +0000
Subject: [PATCH 20/31] C-API approach #1 - return a union

---
 llvm/include/llvm-c/DebugInfo.h  | 28 +++++------
 llvm/include/llvm-c/Types.h      |  9 ++++
 llvm/include/llvm/IR/DIBuilder.h | 24 +++++++++
 llvm/lib/IR/DebugInfo.cpp        | 84 ++++++++++++--------------------
 4 files changed, 75 insertions(+), 70 deletions(-)

diff --git a/llvm/include/llvm-c/DebugInfo.h b/llvm/include/llvm-c/DebugInfo.h
index 5924294708cc35..501de88d72aa24 100644
--- a/llvm/include/llvm-c/DebugInfo.h
+++ b/llvm/include/llvm-c/DebugInfo.h
@@ -1257,9 +1257,10 @@ LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(
  * \param DebugLoc    Debug info location.
  * \param Instr       Instruction acting as a location for the new intrinsic.
  */
-LLVMValueRef LLVMDIBuilderInsertDeclareBefore(
-  LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
-  LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMValueRef Instr);
+LLVMDbgInstRef
+LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
+                                 LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
+                                 LLVMMetadataRef DebugLoc, LLVMValueRef Instr);
 
 /**
  * Insert a new llvm.dbg.declare intrinsic call at the end of the given basic
@@ -1272,7 +1273,7 @@ LLVMValueRef LLVMDIBuilderInsertDeclareBefore(
  * \param DebugLoc    Debug info location.
  * \param Block       Basic block acting as a location for the new intrinsic.
  */
-LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd(
+LLVMDbgInstRef LLVMDIBuilderInsertDeclareAtEnd(
     LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
     LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block);
 
@@ -1285,12 +1286,10 @@ LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd(
  * \param DebugLoc    Debug info location.
  * \param Instr       Instruction acting as a location for the new intrinsic.
  */
-LLVMValueRef LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder,
-                                               LLVMValueRef Val,
-                                               LLVMMetadataRef VarInfo,
-                                               LLVMMetadataRef Expr,
-                                               LLVMMetadataRef DebugLoc,
-                                               LLVMValueRef Instr);
+LLVMDbgInstRef
+LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder, LLVMValueRef Val,
+                                  LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
+                                  LLVMMetadataRef DebugLoc, LLVMValueRef Instr);
 
 /**
  * Insert a new llvm.dbg.value intrinsic call at the end of the given basic
@@ -1303,12 +1302,9 @@ LLVMValueRef LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder,
  * \param DebugLoc    Debug info location.
  * \param Block       Basic block acting as a location for the new intrinsic.
  */
-LLVMValueRef LLVMDIBuilderInsertDbgValueAtEnd(LLVMDIBuilderRef Builder,
-                                              LLVMValueRef Val,
-                                              LLVMMetadataRef VarInfo,
-                                              LLVMMetadataRef Expr,
-                                              LLVMMetadataRef DebugLoc,
-                                              LLVMBasicBlockRef Block);
+LLVMDbgInstRef LLVMDIBuilderInsertDbgValueAtEnd(
+    LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
+    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block);
 
 /**
  * Create a new descriptor for a local auto variable.
diff --git a/llvm/include/llvm-c/Types.h b/llvm/include/llvm-c/Types.h
index d5474d986309fa..09377e802ebb00 100644
--- a/llvm/include/llvm-c/Types.h
+++ b/llvm/include/llvm-c/Types.h
@@ -173,6 +173,15 @@ typedef struct LLVMOpaqueBinary *LLVMBinaryRef;
  * @}
  */
 
+typedef struct LLVMOpaqueDbgRecord *LLVMDbgRecord;
+typedef struct {
+  union {
+    LLVMValueRef Instr;
+    LLVMDbgRecord Record;
+  } Ptr;
+  int IsInstr;
+} LLVMDbgInstRef;
+
 LLVM_C_EXTERN_C_END
 
 #endif
diff --git a/llvm/include/llvm/IR/DIBuilder.h b/llvm/include/llvm/IR/DIBuilder.h
index 94af17af8160e9..34b0ed7afcb7e9 100644
--- a/llvm/include/llvm/IR/DIBuilder.h
+++ b/llvm/include/llvm/IR/DIBuilder.h
@@ -42,6 +42,30 @@ namespace llvm {
 
   using DbgInstPtr = PointerUnion<Instruction *, DbgRecord *>;
 
+  /* Specialized opaque type conversions.
+   */
+  inline DbgInstPtr unwrapDbgUnion(LLVMDbgInstRef Ref) {
+    DbgInstPtr Unwrapped;
+    if (Ref.IsInstr)
+      Unwrapped = unwrap<Instruction>(Ref.Ptr.Instr);
+    else
+      Unwrapped = reinterpret_cast<DbgRecord *>(Ref.Ptr.Record);
+    return Unwrapped;
+  }
+  inline LLVMDbgInstRef wrapDbgUnion(DbgInstPtr Ref) {
+    LLVMDbgInstRef Wrapped;
+    if (isa<Instruction *>(Ref)) {
+      Wrapped.Ptr.Instr =
+          wrap(reinterpret_cast<Value *>(Ref.get<Instruction *>()));
+      Wrapped.IsInstr = true;
+    } else {
+      Wrapped.Ptr.Record =
+          reinterpret_cast<LLVMDbgRecord>(Ref.get<DbgRecord *>());
+      Wrapped.IsInstr = false;
+    }
+    return Wrapped;
+  }
+
   class DIBuilder {
     Module &M;
     LLVMContext &VMContext;
diff --git a/llvm/lib/IR/DebugInfo.cpp b/llvm/lib/IR/DebugInfo.cpp
index 721b276ac06b43..0e4faa15bccaa5 100644
--- a/llvm/lib/IR/DebugInfo.cpp
+++ b/llvm/lib/IR/DebugInfo.cpp
@@ -1659,63 +1659,39 @@ LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(
       unwrapDI<MDNode>(Decl), nullptr, AlignInBits));
 }
 
-LLVMValueRef
+LLVMDbgInstRef
 LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
                                  LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
                                  LLVMMetadataRef DL, LLVMValueRef Instr) {
-  return LLVMValueRef();
-  // FIXME: What to do here?
-  /*
-  return wrap(unwrap(Builder)->insertDeclare(
-                  unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
-                  unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
-                  unwrap<Instruction>(Instr)));
-  */
-}
-
-LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd(
-    LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
-    LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMBasicBlockRef Block) {
-  return LLVMValueRef();
-  // FIXME: What to do here?
-  /*
-  return wrap(unwrap(Builder)->insertDeclare(
-                  unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
-                  unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
-                  unwrap(Block)));
-  */
-}
-
-LLVMValueRef LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder,
-                                               LLVMValueRef Val,
-                                               LLVMMetadataRef VarInfo,
-                                               LLVMMetadataRef Expr,
-                                               LLVMMetadataRef DebugLoc,
-                                               LLVMValueRef Instr) {
-  return LLVMValueRef();
-  // FIXME: What to do here?
-  /*
-  return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
-                  unwrap(Val), unwrap<DILocalVariable>(VarInfo),
-                  unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
-                  unwrap<Instruction>(Instr)));
-   */
-}
-
-LLVMValueRef LLVMDIBuilderInsertDbgValueAtEnd(LLVMDIBuilderRef Builder,
-                                              LLVMValueRef Val,
-                                              LLVMMetadataRef VarInfo,
-                                              LLVMMetadataRef Expr,
-                                              LLVMMetadataRef DebugLoc,
-                                              LLVMBasicBlockRef Block) {
-  return LLVMValueRef();
-  // FIXME: What to do here?
-  /*
-  return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
-                  unwrap(Val), unwrap<DILocalVariable>(VarInfo),
-                  unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
-                  unwrap(Block)));
-   */
+  return wrapDbgUnion(unwrap(Builder)->insertDeclare(
+      unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
+      unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
+      unwrap<Instruction>(Instr)));
+}
+
+LLVMDbgInstRef
+LLVMDIBuilderInsertDeclareAtEnd(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
+                                LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
+                                LLVMMetadataRef DL, LLVMBasicBlockRef Block) {
+  return wrapDbgUnion(unwrap(Builder)->insertDeclare(
+      unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
+      unwrap<DIExpression>(Expr), unwrap<DILocation>(DL), unwrap(Block)));
+}
+
+LLVMDbgInstRef LLVMDIBuilderInsertDbgValueBefore(
+    LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
+    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMValueRef Instr) {
+  return wrapDbgUnion(unwrap(Builder)->insertDbgValueIntrinsic(
+      unwrap(Val), unwrap<DILocalVariable>(VarInfo), unwrap<DIExpression>(Expr),
+      unwrap<DILocation>(DebugLoc), unwrap<Instruction>(Instr)));
+}
+
+LLVMDbgInstRef LLVMDIBuilderInsertDbgValueAtEnd(
+    LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
+    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block) {
+  return wrapDbgUnion(unwrap(Builder)->insertDbgValueIntrinsic(
+      unwrap(Val), unwrap<DILocalVariable>(VarInfo), unwrap<DIExpression>(Expr),
+      unwrap<DILocation>(DebugLoc), unwrap(Block)));
 }
 
 LLVMMetadataRef LLVMDIBuilderCreateAutoVariable(

>From 8b03c20d58a1812f127fcdcd2d6065d52c360b8b Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Fri, 8 Mar 2024 16:39:20 +0000
Subject: [PATCH 21/31] Revert "C-API approach #1 - return a union"

This reverts commit 8b8cddbd6af2777b3c44fbfb3550186f2b4a518c.
---
 llvm/include/llvm-c/DebugInfo.h  | 28 ++++++-----
 llvm/include/llvm-c/Types.h      |  9 ----
 llvm/include/llvm/IR/DIBuilder.h | 24 ---------
 llvm/lib/IR/DebugInfo.cpp        | 84 ++++++++++++++++++++------------
 4 files changed, 70 insertions(+), 75 deletions(-)

diff --git a/llvm/include/llvm-c/DebugInfo.h b/llvm/include/llvm-c/DebugInfo.h
index 501de88d72aa24..5924294708cc35 100644
--- a/llvm/include/llvm-c/DebugInfo.h
+++ b/llvm/include/llvm-c/DebugInfo.h
@@ -1257,10 +1257,9 @@ LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(
  * \param DebugLoc    Debug info location.
  * \param Instr       Instruction acting as a location for the new intrinsic.
  */
-LLVMDbgInstRef
-LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
-                                 LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
-                                 LLVMMetadataRef DebugLoc, LLVMValueRef Instr);
+LLVMValueRef LLVMDIBuilderInsertDeclareBefore(
+  LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
+  LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMValueRef Instr);
 
 /**
  * Insert a new llvm.dbg.declare intrinsic call at the end of the given basic
@@ -1273,7 +1272,7 @@ LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
  * \param DebugLoc    Debug info location.
  * \param Block       Basic block acting as a location for the new intrinsic.
  */
-LLVMDbgInstRef LLVMDIBuilderInsertDeclareAtEnd(
+LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd(
     LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
     LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block);
 
@@ -1286,10 +1285,12 @@ LLVMDbgInstRef LLVMDIBuilderInsertDeclareAtEnd(
  * \param DebugLoc    Debug info location.
  * \param Instr       Instruction acting as a location for the new intrinsic.
  */
-LLVMDbgInstRef
-LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder, LLVMValueRef Val,
-                                  LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
-                                  LLVMMetadataRef DebugLoc, LLVMValueRef Instr);
+LLVMValueRef LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder,
+                                               LLVMValueRef Val,
+                                               LLVMMetadataRef VarInfo,
+                                               LLVMMetadataRef Expr,
+                                               LLVMMetadataRef DebugLoc,
+                                               LLVMValueRef Instr);
 
 /**
  * Insert a new llvm.dbg.value intrinsic call at the end of the given basic
@@ -1302,9 +1303,12 @@ LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder, LLVMValueRef Val,
  * \param DebugLoc    Debug info location.
  * \param Block       Basic block acting as a location for the new intrinsic.
  */
-LLVMDbgInstRef LLVMDIBuilderInsertDbgValueAtEnd(
-    LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
-    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block);
+LLVMValueRef LLVMDIBuilderInsertDbgValueAtEnd(LLVMDIBuilderRef Builder,
+                                              LLVMValueRef Val,
+                                              LLVMMetadataRef VarInfo,
+                                              LLVMMetadataRef Expr,
+                                              LLVMMetadataRef DebugLoc,
+                                              LLVMBasicBlockRef Block);
 
 /**
  * Create a new descriptor for a local auto variable.
diff --git a/llvm/include/llvm-c/Types.h b/llvm/include/llvm-c/Types.h
index 09377e802ebb00..d5474d986309fa 100644
--- a/llvm/include/llvm-c/Types.h
+++ b/llvm/include/llvm-c/Types.h
@@ -173,15 +173,6 @@ typedef struct LLVMOpaqueBinary *LLVMBinaryRef;
  * @}
  */
 
-typedef struct LLVMOpaqueDbgRecord *LLVMDbgRecord;
-typedef struct {
-  union {
-    LLVMValueRef Instr;
-    LLVMDbgRecord Record;
-  } Ptr;
-  int IsInstr;
-} LLVMDbgInstRef;
-
 LLVM_C_EXTERN_C_END
 
 #endif
diff --git a/llvm/include/llvm/IR/DIBuilder.h b/llvm/include/llvm/IR/DIBuilder.h
index 34b0ed7afcb7e9..94af17af8160e9 100644
--- a/llvm/include/llvm/IR/DIBuilder.h
+++ b/llvm/include/llvm/IR/DIBuilder.h
@@ -42,30 +42,6 @@ namespace llvm {
 
   using DbgInstPtr = PointerUnion<Instruction *, DbgRecord *>;
 
-  /* Specialized opaque type conversions.
-   */
-  inline DbgInstPtr unwrapDbgUnion(LLVMDbgInstRef Ref) {
-    DbgInstPtr Unwrapped;
-    if (Ref.IsInstr)
-      Unwrapped = unwrap<Instruction>(Ref.Ptr.Instr);
-    else
-      Unwrapped = reinterpret_cast<DbgRecord *>(Ref.Ptr.Record);
-    return Unwrapped;
-  }
-  inline LLVMDbgInstRef wrapDbgUnion(DbgInstPtr Ref) {
-    LLVMDbgInstRef Wrapped;
-    if (isa<Instruction *>(Ref)) {
-      Wrapped.Ptr.Instr =
-          wrap(reinterpret_cast<Value *>(Ref.get<Instruction *>()));
-      Wrapped.IsInstr = true;
-    } else {
-      Wrapped.Ptr.Record =
-          reinterpret_cast<LLVMDbgRecord>(Ref.get<DbgRecord *>());
-      Wrapped.IsInstr = false;
-    }
-    return Wrapped;
-  }
-
   class DIBuilder {
     Module &M;
     LLVMContext &VMContext;
diff --git a/llvm/lib/IR/DebugInfo.cpp b/llvm/lib/IR/DebugInfo.cpp
index 0e4faa15bccaa5..721b276ac06b43 100644
--- a/llvm/lib/IR/DebugInfo.cpp
+++ b/llvm/lib/IR/DebugInfo.cpp
@@ -1659,39 +1659,63 @@ LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(
       unwrapDI<MDNode>(Decl), nullptr, AlignInBits));
 }
 
-LLVMDbgInstRef
+LLVMValueRef
 LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
                                  LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
                                  LLVMMetadataRef DL, LLVMValueRef Instr) {
-  return wrapDbgUnion(unwrap(Builder)->insertDeclare(
-      unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
-      unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
-      unwrap<Instruction>(Instr)));
-}
-
-LLVMDbgInstRef
-LLVMDIBuilderInsertDeclareAtEnd(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
-                                LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
-                                LLVMMetadataRef DL, LLVMBasicBlockRef Block) {
-  return wrapDbgUnion(unwrap(Builder)->insertDeclare(
-      unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
-      unwrap<DIExpression>(Expr), unwrap<DILocation>(DL), unwrap(Block)));
-}
-
-LLVMDbgInstRef LLVMDIBuilderInsertDbgValueBefore(
-    LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
-    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMValueRef Instr) {
-  return wrapDbgUnion(unwrap(Builder)->insertDbgValueIntrinsic(
-      unwrap(Val), unwrap<DILocalVariable>(VarInfo), unwrap<DIExpression>(Expr),
-      unwrap<DILocation>(DebugLoc), unwrap<Instruction>(Instr)));
-}
-
-LLVMDbgInstRef LLVMDIBuilderInsertDbgValueAtEnd(
-    LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
-    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block) {
-  return wrapDbgUnion(unwrap(Builder)->insertDbgValueIntrinsic(
-      unwrap(Val), unwrap<DILocalVariable>(VarInfo), unwrap<DIExpression>(Expr),
-      unwrap<DILocation>(DebugLoc), unwrap(Block)));
+  return LLVMValueRef();
+  // FIXME: What to do here?
+  /*
+  return wrap(unwrap(Builder)->insertDeclare(
+                  unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
+                  unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
+                  unwrap<Instruction>(Instr)));
+  */
+}
+
+LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd(
+    LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
+    LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMBasicBlockRef Block) {
+  return LLVMValueRef();
+  // FIXME: What to do here?
+  /*
+  return wrap(unwrap(Builder)->insertDeclare(
+                  unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
+                  unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
+                  unwrap(Block)));
+  */
+}
+
+LLVMValueRef LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder,
+                                               LLVMValueRef Val,
+                                               LLVMMetadataRef VarInfo,
+                                               LLVMMetadataRef Expr,
+                                               LLVMMetadataRef DebugLoc,
+                                               LLVMValueRef Instr) {
+  return LLVMValueRef();
+  // FIXME: What to do here?
+  /*
+  return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
+                  unwrap(Val), unwrap<DILocalVariable>(VarInfo),
+                  unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
+                  unwrap<Instruction>(Instr)));
+   */
+}
+
+LLVMValueRef LLVMDIBuilderInsertDbgValueAtEnd(LLVMDIBuilderRef Builder,
+                                              LLVMValueRef Val,
+                                              LLVMMetadataRef VarInfo,
+                                              LLVMMetadataRef Expr,
+                                              LLVMMetadataRef DebugLoc,
+                                              LLVMBasicBlockRef Block) {
+  return LLVMValueRef();
+  // FIXME: What to do here?
+  /*
+  return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
+                  unwrap(Val), unwrap<DILocalVariable>(VarInfo),
+                  unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
+                  unwrap(Block)));
+   */
 }
 
 LLVMMetadataRef LLVMDIBuilderCreateAutoVariable(

>From 63511e039249ca71ca24cf2bfa76459687e69668 Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Fri, 8 Mar 2024 17:40:54 +0000
Subject: [PATCH 22/31] other C-API tactic: use 2 function falvours

---
 llvm/include/llvm-c/Core.h                    |   8 ++
 llvm/include/llvm-c/DebugInfo.h               | 108 ++++++++++++---
 llvm/include/llvm-c/Types.h                   |   5 +
 .../include/llvm/IR/DebugProgramInstruction.h |   2 +
 llvm/lib/IR/Core.cpp                          |   4 +
 llvm/lib/IR/DebugInfo.cpp                     | 127 +++++++++++-------
 llvm/tools/llvm-c-test/debuginfo.c            |  44 ++++--
 7 files changed, 220 insertions(+), 78 deletions(-)

diff --git a/llvm/include/llvm-c/Core.h b/llvm/include/llvm-c/Core.h
index 7cfe4dc4f775fd..1ea4b59b857064 100644
--- a/llvm/include/llvm-c/Core.h
+++ b/llvm/include/llvm-c/Core.h
@@ -744,6 +744,14 @@ LLVMModuleRef LLVMCloneModule(LLVMModuleRef M);
  */
 void LLVMDisposeModule(LLVMModuleRef M);
 
+/**
+ * Returns true if the module is in the new debug info mode which uses
+ * non-instruction debug records instead of debug intrinsics for variable
+ * location tracking.
+ * See See https://llvm.org/docs/RemoveDIsDebugInfo.html.
+ */
+LLVMBool LLVMIsNewDbgInfoFormat(LLVMModuleRef M);
+
 /**
  * Obtain the identifier of a module.
  *
diff --git a/llvm/include/llvm-c/DebugInfo.h b/llvm/include/llvm-c/DebugInfo.h
index 5924294708cc35..6dd36f8dedec4d 100644
--- a/llvm/include/llvm-c/DebugInfo.h
+++ b/llvm/include/llvm-c/DebugInfo.h
@@ -1249,6 +1249,10 @@ LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(
     LLVMMetadataRef Decl, uint32_t AlignInBits);
 
 /**
+ * Soon to be deprecated.
+ * Only use in "old debug mode" (LLVMIsNewDbgFormat() is false).
+ * See https://llvm.org/docs/RemoveDIsDebugInfo.html
+ *
  * Insert a new llvm.dbg.declare intrinsic call before the given instruction.
  * \param Builder     The DIBuilder.
  * \param Storage     The storage of the variable to declare.
@@ -1257,11 +1261,31 @@ LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(
  * \param DebugLoc    Debug info location.
  * \param Instr       Instruction acting as a location for the new intrinsic.
  */
-LLVMValueRef LLVMDIBuilderInsertDeclareBefore(
-  LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
-  LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMValueRef Instr);
+LLVMValueRef LLVMDIBuilderInsertDeclareIntrinsicBefore(
+    LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
+    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMValueRef Instr);
+/**
+ * Only use in "new debug mode" (LLVMIsNewDbgFormat() is true).
+ * See https://llvm.org/docs/RemoveDIsDebugInfo.html
+ *
+ * Insert a Declare DbgRecord before the given instruction.
+ * \param Builder     The DIBuilder.
+ * \param Storage     The storage of the variable to declare.
+ * \param VarInfo     The variable's debug info descriptor.
+ * \param Expr        A complex location expression for the variable.
+ * \param DebugLoc    Debug info location.
+ * \param Instr       Instruction acting as a location for the new record.
+ */
+LLVMDbgRecordRef
+LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
+                                 LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
+                                 LLVMMetadataRef DebugLoc, LLVMValueRef Instr);
 
 /**
+ * Soon to be deprecated.
+ * Only use in "old debug mode" (LLVMIsNewDbgFormat() is false).
+ * See https://llvm.org/docs/RemoveDIsDebugInfo.html
+ *
  * Insert a new llvm.dbg.declare intrinsic call at the end of the given basic
  * block. If the basic block has a terminator instruction, the intrinsic is
  * inserted before that terminator instruction.
@@ -1272,11 +1296,32 @@ LLVMValueRef LLVMDIBuilderInsertDeclareBefore(
  * \param DebugLoc    Debug info location.
  * \param Block       Basic block acting as a location for the new intrinsic.
  */
-LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd(
+LLVMValueRef LLVMDIBuilderInsertDeclareIntrinsicAtEnd(
+    LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
+    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block);
+/**
+ * Only use in "new debug mode" (LLVMIsNewDbgFormat() is true).
+ * See https://llvm.org/docs/RemoveDIsDebugInfo.html
+ *
+ * Insert a Declare DbgRecord at the end of the given basic block. If the basic
+ * block has a terminator instruction, the record is inserted before that
+ * terminator instruction.
+ * \param Builder     The DIBuilder.
+ * \param Storage     The storage of the variable to declare.
+ * \param VarInfo     The variable's debug info descriptor.
+ * \param Expr        A complex location expression for the variable.
+ * \param DebugLoc    Debug info location.
+ * \param Block       Basic block acting as a location for the new record.
+ */
+LLVMDbgRecordRef LLVMDIBuilderInsertDeclareAtEnd(
     LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
     LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block);
 
 /**
+ * Soon to be deprecated.
+ * Only use in "old debug mode" (Module::IsNewDbgInfoFormat is false).
+ * See https://llvm.org/docs/RemoveDIsDebugInfo.html
+ *
  * Insert a new llvm.dbg.value intrinsic call before the given instruction.
  * \param Builder     The DIBuilder.
  * \param Val         The value of the variable.
@@ -1285,14 +1330,31 @@ LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd(
  * \param DebugLoc    Debug info location.
  * \param Instr       Instruction acting as a location for the new intrinsic.
  */
-LLVMValueRef LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder,
-                                               LLVMValueRef Val,
-                                               LLVMMetadataRef VarInfo,
-                                               LLVMMetadataRef Expr,
-                                               LLVMMetadataRef DebugLoc,
-                                               LLVMValueRef Instr);
+LLVMValueRef LLVMDIBuilderInsertDbgValueIntrinsicBefore(
+    LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
+    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMValueRef Instr);
+/**
+ * Only use in "new debug mode" (Module::IsNewDbgInfoFormat is true).
+ * See https://llvm.org/docs/RemoveDIsDebugInfo.html
+ *
+ * Insert a new llvm.dbg.value intrinsic call before the given instruction.
+ * \param Builder     The DIBuilder.
+ * \param Val         The value of the variable.
+ * \param VarInfo     The variable's debug info descriptor.
+ * \param Expr        A complex location expression for the variable.
+ * \param DebugLoc    Debug info location.
+ * \param Instr       Instruction acting as a location for the new intrinsic.
+ */
+LLVMDbgRecordRef
+LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder, LLVMValueRef Val,
+                                  LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
+                                  LLVMMetadataRef DebugLoc, LLVMValueRef Instr);
 
 /**
+ * Soon to be deprecated.
+ * Only use in "old debug mode" (Module::IsNewDbgInfoFormat is false).
+ * See https://llvm.org/docs/RemoveDIsDebugInfo.html
+ *
  * Insert a new llvm.dbg.value intrinsic call at the end of the given basic
  * block. If the basic block has a terminator instruction, the intrinsic is
  * inserted before that terminator instruction.
@@ -1303,12 +1365,26 @@ LLVMValueRef LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder,
  * \param DebugLoc    Debug info location.
  * \param Block       Basic block acting as a location for the new intrinsic.
  */
-LLVMValueRef LLVMDIBuilderInsertDbgValueAtEnd(LLVMDIBuilderRef Builder,
-                                              LLVMValueRef Val,
-                                              LLVMMetadataRef VarInfo,
-                                              LLVMMetadataRef Expr,
-                                              LLVMMetadataRef DebugLoc,
-                                              LLVMBasicBlockRef Block);
+LLVMValueRef LLVMDIBuilderInsertDbgValueIntrinsicAtEnd(
+    LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
+    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block);
+/**
+ * Only use in "new debug mode" (Module::IsNewDbgInfoFormat is true).
+ * See https://llvm.org/docs/RemoveDIsDebugInfo.html
+ *
+ * Insert a new llvm.dbg.value intrinsic call at the end of the given basic
+ * block. If the basic block has a terminator instruction, the intrinsic is
+ * inserted before that terminator instruction.
+ * \param Builder     The DIBuilder.
+ * \param Val         The value of the variable.
+ * \param VarInfo     The variable's debug info descriptor.
+ * \param Expr        A complex location expression for the variable.
+ * \param DebugLoc    Debug info location.
+ * \param Block       Basic block acting as a location for the new intrinsic.
+ */
+LLVMDbgRecordRef LLVMDIBuilderInsertDbgValueAtEnd(
+    LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
+    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block);
 
 /**
  * Create a new descriptor for a local auto variable.
diff --git a/llvm/include/llvm-c/Types.h b/llvm/include/llvm-c/Types.h
index d5474d986309fa..4681500ef9da3d 100644
--- a/llvm/include/llvm-c/Types.h
+++ b/llvm/include/llvm-c/Types.h
@@ -169,6 +169,11 @@ typedef struct LLVMOpaqueJITEventListener *LLVMJITEventListenerRef;
  */
 typedef struct LLVMOpaqueBinary *LLVMBinaryRef;
 
+/**
+ * @see llvm::DbgRecord
+ */
+typedef struct LLVMOpaqueDbgRecord *LLVMDbgRecordRef;
+
 /**
  * @}
  */
diff --git a/llvm/include/llvm/IR/DebugProgramInstruction.h b/llvm/include/llvm/IR/DebugProgramInstruction.h
index a8faf415a3ea87..960489dc52b12a 100644
--- a/llvm/include/llvm/IR/DebugProgramInstruction.h
+++ b/llvm/include/llvm/IR/DebugProgramInstruction.h
@@ -643,6 +643,8 @@ getDbgValueRange(DPMarker *DbgMarker) {
   return DbgMarker->getDbgValueRange();
 }
 
+DEFINE_ISA_CONVERSION_FUNCTIONS(DbgRecord, LLVMDbgRecordRef);
+
 } // namespace llvm
 
 #endif // LLVM_IR_DEBUGPROGRAMINSTRUCTION_H
diff --git a/llvm/lib/IR/Core.cpp b/llvm/lib/IR/Core.cpp
index 4b804a41a1676f..46aefc8f474fca 100644
--- a/llvm/lib/IR/Core.cpp
+++ b/llvm/lib/IR/Core.cpp
@@ -404,6 +404,10 @@ void LLVMAddModuleFlag(LLVMModuleRef M, LLVMModuleFlagBehavior Behavior,
                            {Key, KeyLen}, unwrap(Val));
 }
 
+LLVMBool LLVMIsNewDbgInfoFormat(LLVMModuleRef M) {
+  return unwrap(M)->IsNewDbgInfoFormat;
+}
+
 /*--.. Printing modules ....................................................--*/
 
 void LLVMDumpModule(LLVMModuleRef M) {
diff --git a/llvm/lib/IR/DebugInfo.cpp b/llvm/lib/IR/DebugInfo.cpp
index 721b276ac06b43..91c5499eac4e81 100644
--- a/llvm/lib/IR/DebugInfo.cpp
+++ b/llvm/lib/IR/DebugInfo.cpp
@@ -1659,63 +1659,90 @@ LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(
       unwrapDI<MDNode>(Decl), nullptr, AlignInBits));
 }
 
-LLVMValueRef
+LLVMValueRef LLVMDIBuilderInsertDeclareIntrinsicBefore(
+    LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
+    LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMValueRef Instr) {
+  return wrap(
+      unwrap(Builder)
+          ->insertDeclare(unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
+                          unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
+                          unwrap<Instruction>(Instr))
+          .get<Instruction *>());
+}
+LLVMDbgRecordRef
 LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
                                  LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
                                  LLVMMetadataRef DL, LLVMValueRef Instr) {
-  return LLVMValueRef();
-  // FIXME: What to do here?
-  /*
-  return wrap(unwrap(Builder)->insertDeclare(
-                  unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
-                  unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
-                  unwrap<Instruction>(Instr)));
-  */
+  return wrap(
+      unwrap(Builder)
+          ->insertDeclare(unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
+                          unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
+                          unwrap<Instruction>(Instr))
+          .get<DbgRecord *>());
 }
 
-LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd(
+LLVMValueRef LLVMDIBuilderInsertDeclareIntrinsicAtEnd(
     LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
     LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMBasicBlockRef Block) {
-  return LLVMValueRef();
-  // FIXME: What to do here?
-  /*
-  return wrap(unwrap(Builder)->insertDeclare(
-                  unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
-                  unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
-                  unwrap(Block)));
-  */
-}
-
-LLVMValueRef LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder,
-                                               LLVMValueRef Val,
-                                               LLVMMetadataRef VarInfo,
-                                               LLVMMetadataRef Expr,
-                                               LLVMMetadataRef DebugLoc,
-                                               LLVMValueRef Instr) {
-  return LLVMValueRef();
-  // FIXME: What to do here?
-  /*
-  return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
-                  unwrap(Val), unwrap<DILocalVariable>(VarInfo),
-                  unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
-                  unwrap<Instruction>(Instr)));
-   */
-}
-
-LLVMValueRef LLVMDIBuilderInsertDbgValueAtEnd(LLVMDIBuilderRef Builder,
-                                              LLVMValueRef Val,
-                                              LLVMMetadataRef VarInfo,
-                                              LLVMMetadataRef Expr,
-                                              LLVMMetadataRef DebugLoc,
-                                              LLVMBasicBlockRef Block) {
-  return LLVMValueRef();
-  // FIXME: What to do here?
-  /*
-  return wrap(unwrap(Builder)->insertDbgValueIntrinsic(
-                  unwrap(Val), unwrap<DILocalVariable>(VarInfo),
-                  unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
-                  unwrap(Block)));
-   */
+  return wrap(unwrap(Builder)
+                  ->insertDeclare(unwrap(Storage),
+                                  unwrap<DILocalVariable>(VarInfo),
+                                  unwrap<DIExpression>(Expr),
+                                  unwrap<DILocation>(DL), unwrap(Block))
+                  .get<Instruction *>());
+}
+LLVMDbgRecordRef
+LLVMDIBuilderInsertDeclareAtEnd(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
+                                LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
+                                LLVMMetadataRef DL, LLVMBasicBlockRef Block) {
+  return wrap(unwrap(Builder)
+                  ->insertDeclare(unwrap(Storage),
+                                  unwrap<DILocalVariable>(VarInfo),
+                                  unwrap<DIExpression>(Expr),
+                                  unwrap<DILocation>(DL), unwrap(Block))
+                  .get<DbgRecord *>());
+}
+
+LLVMValueRef LLVMDIBuilderInsertDbgValueIntrinsicBefore(
+    LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
+    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMValueRef Instr) {
+  return wrap(unwrap(Builder)
+                  ->insertDbgValueIntrinsic(
+                      unwrap(Val), unwrap<DILocalVariable>(VarInfo),
+                      unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
+                      unwrap<Instruction>(Instr))
+                  .get<Instruction *>());
+}
+LLVMDbgRecordRef LLVMDIBuilderInsertDbgValueBefore(
+    LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
+    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMValueRef Instr) {
+  return wrap(unwrap(Builder)
+                  ->insertDbgValueIntrinsic(
+                      unwrap(Val), unwrap<DILocalVariable>(VarInfo),
+                      unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
+                      unwrap<Instruction>(Instr))
+                  .get<DbgRecord *>());
+}
+
+LLVMValueRef LLVMDIBuilderInsertDbgValueIntrinsicAtEnd(
+    LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
+    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block) {
+  return wrap(unwrap(Builder)
+                  ->insertDbgValueIntrinsic(
+                      unwrap(Val), unwrap<DILocalVariable>(VarInfo),
+                      unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
+                      unwrap(Block))
+                  .get<Instruction *>());
+}
+LLVMDbgRecordRef LLVMDIBuilderInsertDbgValueAtEnd(
+    LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
+    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block) {
+  return wrap(unwrap(Builder)
+                  ->insertDbgValueIntrinsic(
+                      unwrap(Val), unwrap<DILocalVariable>(VarInfo),
+                      unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
+                      unwrap(Block))
+                  .get<DbgRecord *>());
 }
 
 LLVMMetadataRef LLVMDIBuilderCreateAutoVariable(
diff --git a/llvm/tools/llvm-c-test/debuginfo.c b/llvm/tools/llvm-c-test/debuginfo.c
index a3e41be12e95d4..4f4571d3292ff0 100644
--- a/llvm/tools/llvm-c-test/debuginfo.c
+++ b/llvm/tools/llvm-c-test/debuginfo.c
@@ -135,21 +135,38 @@ int llvm_test_dibuilder(void) {
   LLVMMetadataRef FooParamVar1 =
     LLVMDIBuilderCreateParameterVariable(DIB, FunctionMetadata, "a", 1, 1, File,
                                          42, Int64Ty, true, 0);
-  LLVMDIBuilderInsertDeclareAtEnd(DIB, LLVMConstInt(LLVMInt64Type(), 0, false),
-                                  FooParamVar1, FooParamExpression,
-                                  FooParamLocation, FooEntryBlock);
+  if (LLVMIsNewDbgInfoFormat(M))
+    LLVMDIBuilderInsertDeclareAtEnd(
+        DIB, LLVMConstInt(LLVMInt64Type(), 0, false), FooParamVar1,
+        FooParamExpression, FooParamLocation, FooEntryBlock);
+  else
+    LLVMDIBuilderInsertDeclareIntrinsicAtEnd(
+        DIB, LLVMConstInt(LLVMInt64Type(), 0, false), FooParamVar1,
+        FooParamExpression, FooParamLocation, FooEntryBlock);
   LLVMMetadataRef FooParamVar2 =
     LLVMDIBuilderCreateParameterVariable(DIB, FunctionMetadata, "b", 1, 2, File,
                                          42, Int64Ty, true, 0);
-  LLVMDIBuilderInsertDeclareAtEnd(DIB, LLVMConstInt(LLVMInt64Type(), 0, false),
-                                  FooParamVar2, FooParamExpression,
-                                  FooParamLocation, FooEntryBlock);
+
+  if (LLVMIsNewDbgInfoFormat(M))
+    LLVMDIBuilderInsertDeclareAtEnd(
+        DIB, LLVMConstInt(LLVMInt64Type(), 0, false), FooParamVar2,
+        FooParamExpression, FooParamLocation, FooEntryBlock);
+  else
+    LLVMDIBuilderInsertDeclareIntrinsicAtEnd(
+        DIB, LLVMConstInt(LLVMInt64Type(), 0, false), FooParamVar2,
+        FooParamExpression, FooParamLocation, FooEntryBlock);
+
   LLVMMetadataRef FooParamVar3 =
     LLVMDIBuilderCreateParameterVariable(DIB, FunctionMetadata, "c", 1, 3, File,
                                          42, VectorTy, true, 0);
-  LLVMDIBuilderInsertDeclareAtEnd(DIB, LLVMConstInt(LLVMInt64Type(), 0, false),
-                                  FooParamVar3, FooParamExpression,
-                                  FooParamLocation, FooEntryBlock);
+  if (LLVMIsNewDbgInfoFormat(M))
+    LLVMDIBuilderInsertDeclareAtEnd(
+        DIB, LLVMConstInt(LLVMInt64Type(), 0, false), FooParamVar3,
+        FooParamExpression, FooParamLocation, FooEntryBlock);
+  else
+    LLVMDIBuilderInsertDeclareIntrinsicAtEnd(
+        DIB, LLVMConstInt(LLVMInt64Type(), 0, false), FooParamVar3,
+        FooParamExpression, FooParamLocation, FooEntryBlock);
 
   LLVMSetSubprogram(FooFunction, FunctionMetadata);
 
@@ -166,9 +183,12 @@ int llvm_test_dibuilder(void) {
   LLVMValueRef FooVal1 = LLVMConstInt(LLVMInt64Type(), 0, false);
   LLVMMetadataRef FooVarValueExpr =
     LLVMDIBuilderCreateConstantValueExpression(DIB, 0);
-
-  LLVMDIBuilderInsertDbgValueAtEnd(DIB, FooVal1, FooVar1, FooVarValueExpr,
-                                   FooVarsLocation, FooVarBlock);
+  if (LLVMIsNewDbgInfoFormat(M))
+    LLVMDIBuilderInsertDbgValueAtEnd(DIB, FooVal1, FooVar1, FooVarValueExpr,
+                                     FooVarsLocation, FooVarBlock);
+  else
+    LLVMDIBuilderInsertDbgValueIntrinsicAtEnd(
+        DIB, FooVal1, FooVar1, FooVarValueExpr, FooVarsLocation, FooVarBlock);
 
   LLVMMetadataRef MacroFile =
       LLVMDIBuilderCreateTempMacroFile(DIB, NULL, 0, File);

>From 197ab575d5a0ebc2b25bed4ba7979e4ef717bd7f Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Fri, 8 Mar 2024 17:49:13 +0000
Subject: [PATCH 23/31] add C API info to the docs

---
 llvm/docs/RemoveDIsDebugInfo.md | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)

diff --git a/llvm/docs/RemoveDIsDebugInfo.md b/llvm/docs/RemoveDIsDebugInfo.md
index a0577678e20fcd..3755181f7a02e7 100644
--- a/llvm/docs/RemoveDIsDebugInfo.md
+++ b/llvm/docs/RemoveDIsDebugInfo.md
@@ -30,6 +30,22 @@ There are two significant changes to be aware of. Firstly, we're adding a single
 
 The second matter is that if you transfer sequences of instructions from one place to another manually, i.e. repeatedly using `moveBefore` where you might have used `splice`, then you should instead use the method `moveBeforePreserving`. `moveBeforePreserving` will transfer debug info records with the instruction they're attached to. This is something that happens automatically today -- if you use `moveBefore` on every element of an instruction sequence, then debug intrinsics will be moved in the normal course of your code, but we lose this behaviour with non-instruction debug info.
 
+# C-API changes
+
+```
+LLVMDIBuilderInsertDeclareBefore            # Changed - Inserts a non-instruction debug record.
+LLVMDIBuilderInsertDeclareAtEnd             # Changed - Inserts a non-instruction debug record.
+LLVMDIBuilderInsertDbgValueBefore           # Changed - Inserts a non-instruction debug record.
+LLVMDIBuilderInsertDbgValueAtEnd            # Changed - Inserts a non-instruction debug record.
+
+LLVMIsNewDbgInfoFormat                      # New - Returns true if the module is in the new non-instruction mode.  Will be deprecated in future.
+LLVMDIBuilderInsertDeclareIntrinsicBefore   # New - Old behaviour of the changed functions above, i.e., insert a dbg intrinsic call. Will be deprecated in future.
+LLVMDIBuilderInsertDeclareIntrinsicAtEnd    # New - Old behaviour of the changed functions above, i.e., insert a dbg intrinsic call. Will be deprecated in future.
+LLVMDIBuilderInsertDbgValueIntrinsicBefore  # New - Old behaviour of the changed functions above, i.e., insert a dbg intrinsic call. Will be deprecated in future.
+LLVMDIBuilderInsertDbgValueIntrinsicAtEnd   # New - Old behaviour of the changed functions above, i.e., insert a dbg intrinsic call. Will be deprecated in future.
+```
+
+
 # Anything else?
 
 Not really, but here's an "old vs new" comparison of how to do certain things and quickstart for how this "new" debug info is structured.

>From ef7ce1aa1732293aa768aa8e9fcdeafbea6ab64e Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Sat, 9 Mar 2024 13:27:55 +0000
Subject: [PATCH 24/31] allow empty to empty splice with trailing dpvalues,
 fixes OpenMP/cancel_codegen.cpp

---
 llvm/lib/IR/BasicBlock.cpp | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)

diff --git a/llvm/lib/IR/BasicBlock.cpp b/llvm/lib/IR/BasicBlock.cpp
index 9c0e68b59f810e..b51bd2fabb6b1e 100644
--- a/llvm/lib/IR/BasicBlock.cpp
+++ b/llvm/lib/IR/BasicBlock.cpp
@@ -752,14 +752,13 @@ void BasicBlock::spliceDebugInfoEmptyBlock(BasicBlock::iterator Dest,
   // occur when a block is optimised away and the terminator has been moved
   // somewhere else.
   if (Src->empty()) {
-    assert(Dest != end() &&
-           "Transferring trailing DPValues to another trailing position");
     DPMarker *SrcTrailingDPValues = Src->getTrailingDPValues();
     if (!SrcTrailingDPValues)
       return;
 
-    Dest->adoptDbgValues(Src, Src->end(), InsertAtHead);
-    // adoptDbgValues should have released the trailing DPValues.
+    DPMarker *DestMarker = getMarker(Dest);
+    DestMarker->absorbDebugValues(*SrcTrailingDPValues, InsertAtHead);
+    SrcTrailingDPValues->eraseFromParent();
     assert(!Src->getTrailingDPValues());
     return;
   }

>From 333bc9e325737c8df9d5b1a660e7ca8f11372093 Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Sun, 10 Mar 2024 15:32:38 +0000
Subject: [PATCH 25/31] Fix clang/test/Frontend/stack-layout-remark.c

---
 llvm/lib/IR/BasicBlock.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/llvm/lib/IR/BasicBlock.cpp b/llvm/lib/IR/BasicBlock.cpp
index b51bd2fabb6b1e..734d4f4539a78e 100644
--- a/llvm/lib/IR/BasicBlock.cpp
+++ b/llvm/lib/IR/BasicBlock.cpp
@@ -756,9 +756,9 @@ void BasicBlock::spliceDebugInfoEmptyBlock(BasicBlock::iterator Dest,
     if (!SrcTrailingDPValues)
       return;
 
-    DPMarker *DestMarker = getMarker(Dest);
-    DestMarker->absorbDebugValues(*SrcTrailingDPValues, InsertAtHead);
+    createMarker(Dest)->absorbDebugValues(*SrcTrailingDPValues, InsertAtHead);
     SrcTrailingDPValues->eraseFromParent();
+    Src->deleteTrailingDPValues();
     assert(!Src->getTrailingDPValues());
     return;
   }

>From 5cc4a3e2509340db1f868e0b94f1e77e51ed0187 Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Sun, 10 Mar 2024 16:07:14 +0000
Subject: [PATCH 26/31] format

---
 llvm/unittests/IR/IRBuilderTest.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/llvm/unittests/IR/IRBuilderTest.cpp b/llvm/unittests/IR/IRBuilderTest.cpp
index fcf7bf957f55df..9ee235e91d7b5a 100644
--- a/llvm/unittests/IR/IRBuilderTest.cpp
+++ b/llvm/unittests/IR/IRBuilderTest.cpp
@@ -979,7 +979,8 @@ TEST_F(IRBuilderTest, DIBuilder) {
 
     Builder.CreateRet(nullptr);
     DIB.finalize();
-    // Check the labels are not/are added to Bar's retainedNodes array (AlwaysPreserve).
+    // Check the labels are not/are added to Bar's retainedNodes array
+    // (AlwaysPreserve).
     EXPECT_EQ(find(BarSP->getRetainedNodes(), Label),
               BarSP->getRetainedNodes().end());
     EXPECT_NE(find(BarSP->getRetainedNodes(), AlwaysPreserveLabel),

>From 4e0bfff213d40bbf2715eed596706bf047481c10 Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Sun, 10 Mar 2024 16:10:56 +0000
Subject: [PATCH 27/31] tidy

---
 llvm/lib/IR/BasicBlock.cpp | 4 ----
 1 file changed, 4 deletions(-)

diff --git a/llvm/lib/IR/BasicBlock.cpp b/llvm/lib/IR/BasicBlock.cpp
index 734d4f4539a78e..7088a648f9778e 100644
--- a/llvm/lib/IR/BasicBlock.cpp
+++ b/llvm/lib/IR/BasicBlock.cpp
@@ -1037,10 +1037,6 @@ void BasicBlock::insertDPValueAfter(DbgRecord *DPV, Instruction *I) {
 
 void BasicBlock::insertDPValueBefore(DbgRecord *DPV,
                                      InstListType::iterator Where) {
-  // We should never directly insert at the end of the block, new DPValues
-  // shouldn't be generated at times when there's no terminator.
-  // assert(Where != end()); // ^ No longer true. Create seperate method if
-  // needed?
   assert(Where == end() || Where->getParent() == this);
   bool InsertAtHead = Where.getHeadBit();
   DPMarker *M = createMarker(Where);

>From 905a7946f9fda6b622d1899e070e50105e540ccf Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Sun, 10 Mar 2024 16:39:46 +0000
Subject: [PATCH 28/31] fix comment

---
 llvm/lib/IR/Instruction.cpp | 7 ++-----
 1 file changed, 2 insertions(+), 5 deletions(-)

diff --git a/llvm/lib/IR/Instruction.cpp b/llvm/lib/IR/Instruction.cpp
index 7e5d38a1b2099f..7436deb189650e 100644
--- a/llvm/lib/IR/Instruction.cpp
+++ b/llvm/lib/IR/Instruction.cpp
@@ -165,11 +165,8 @@ void Instruction::insertBefore(BasicBlock &BB,
     }
   }
 
-  // If we're inserting a terminator, check if we need to flush out
-  // TrailingDPValues.
-  // if (isTerminator()) // @OCH -- what if we always attach danglers to the
-  // next inserted inst? This might be needed for the FE. Not very efficient
-  // though.
+  // If we're inserting a new terminator or an instruction at end() check
+  // if we need to flush out TrailingDPValues.
   if (isTerminator() ||
       (getParent()->getTrailingDPValues() && InsertPos == BB.end()))
     getParent()->flushTerminatorDbgValues();

>From a7bbba305968df138e45ee6f7235084a02ae516b Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Sun, 10 Mar 2024 17:31:44 +0000
Subject: [PATCH 29/31] fix leftover dev comment/code

---
 llvm/lib/IR/Instruction.cpp | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/llvm/lib/IR/Instruction.cpp b/llvm/lib/IR/Instruction.cpp
index 7436deb189650e..6b8c6e0c85ed98 100644
--- a/llvm/lib/IR/Instruction.cpp
+++ b/llvm/lib/IR/Instruction.cpp
@@ -165,10 +165,10 @@ void Instruction::insertBefore(BasicBlock &BB,
     }
   }
 
-  // If we're inserting a new terminator or an instruction at end() check
-  // if we need to flush out TrailingDPValues.
-  if (isTerminator() ||
-      (getParent()->getTrailingDPValues() && InsertPos == BB.end()))
+  // If we're inserting a terminator, check if we need to flush out
+  // TrailingDPValues. Inserting instructions at the end of an incomplete
+  // block is handled by the code block above.
+  if (isTerminator())
     getParent()->flushTerminatorDbgValues();
 }
 

>From edecd145981cc4e716dc3aadfa2062e022ca9d1f Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Sun, 10 Mar 2024 19:19:36 +0000
Subject: [PATCH 30/31] undo uneeded change

---
 llvm/lib/IR/BasicBlock.cpp | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)

diff --git a/llvm/lib/IR/BasicBlock.cpp b/llvm/lib/IR/BasicBlock.cpp
index 7088a648f9778e..b37ca14925a6a2 100644
--- a/llvm/lib/IR/BasicBlock.cpp
+++ b/llvm/lib/IR/BasicBlock.cpp
@@ -756,9 +756,8 @@ void BasicBlock::spliceDebugInfoEmptyBlock(BasicBlock::iterator Dest,
     if (!SrcTrailingDPValues)
       return;
 
-    createMarker(Dest)->absorbDebugValues(*SrcTrailingDPValues, InsertAtHead);
-    SrcTrailingDPValues->eraseFromParent();
-    Src->deleteTrailingDPValues();
+    Dest->adoptDbgValues(Src, Src->end(), InsertAtHead);
+    // adoptDbgValues should have released the trailing DPValues.
     assert(!Src->getTrailingDPValues());
     return;
   }

>From 25c66b1ca09c3e9683a5fb8b419b21964a92db65 Mon Sep 17 00:00:00 2001
From: Orlando Cazalet-Hyams <orlando.hyams at sony.com>
Date: Sun, 10 Mar 2024 21:34:19 +0000
Subject: [PATCH 31/31] Remove C-API changes

---
 llvm/docs/RemoveDIsDebugInfo.md               |  16 ---
 llvm/include/llvm-c/Core.h                    |   8 --
 llvm/include/llvm-c/DebugInfo.h               |  88 +--------------
 llvm/include/llvm-c/Types.h                   |   5 -
 .../include/llvm/IR/DebugProgramInstruction.h |   2 -
 llvm/lib/IR/DebugInfo.cpp                     | 101 ++++++------------
 llvm/tools/llvm-c-test/debuginfo.c            |  44 +++-----
 7 files changed, 47 insertions(+), 217 deletions(-)

diff --git a/llvm/docs/RemoveDIsDebugInfo.md b/llvm/docs/RemoveDIsDebugInfo.md
index 3755181f7a02e7..a0577678e20fcd 100644
--- a/llvm/docs/RemoveDIsDebugInfo.md
+++ b/llvm/docs/RemoveDIsDebugInfo.md
@@ -30,22 +30,6 @@ There are two significant changes to be aware of. Firstly, we're adding a single
 
 The second matter is that if you transfer sequences of instructions from one place to another manually, i.e. repeatedly using `moveBefore` where you might have used `splice`, then you should instead use the method `moveBeforePreserving`. `moveBeforePreserving` will transfer debug info records with the instruction they're attached to. This is something that happens automatically today -- if you use `moveBefore` on every element of an instruction sequence, then debug intrinsics will be moved in the normal course of your code, but we lose this behaviour with non-instruction debug info.
 
-# C-API changes
-
-```
-LLVMDIBuilderInsertDeclareBefore            # Changed - Inserts a non-instruction debug record.
-LLVMDIBuilderInsertDeclareAtEnd             # Changed - Inserts a non-instruction debug record.
-LLVMDIBuilderInsertDbgValueBefore           # Changed - Inserts a non-instruction debug record.
-LLVMDIBuilderInsertDbgValueAtEnd            # Changed - Inserts a non-instruction debug record.
-
-LLVMIsNewDbgInfoFormat                      # New - Returns true if the module is in the new non-instruction mode.  Will be deprecated in future.
-LLVMDIBuilderInsertDeclareIntrinsicBefore   # New - Old behaviour of the changed functions above, i.e., insert a dbg intrinsic call. Will be deprecated in future.
-LLVMDIBuilderInsertDeclareIntrinsicAtEnd    # New - Old behaviour of the changed functions above, i.e., insert a dbg intrinsic call. Will be deprecated in future.
-LLVMDIBuilderInsertDbgValueIntrinsicBefore  # New - Old behaviour of the changed functions above, i.e., insert a dbg intrinsic call. Will be deprecated in future.
-LLVMDIBuilderInsertDbgValueIntrinsicAtEnd   # New - Old behaviour of the changed functions above, i.e., insert a dbg intrinsic call. Will be deprecated in future.
-```
-
-
 # Anything else?
 
 Not really, but here's an "old vs new" comparison of how to do certain things and quickstart for how this "new" debug info is structured.
diff --git a/llvm/include/llvm-c/Core.h b/llvm/include/llvm-c/Core.h
index 1ea4b59b857064..7cfe4dc4f775fd 100644
--- a/llvm/include/llvm-c/Core.h
+++ b/llvm/include/llvm-c/Core.h
@@ -744,14 +744,6 @@ LLVMModuleRef LLVMCloneModule(LLVMModuleRef M);
  */
 void LLVMDisposeModule(LLVMModuleRef M);
 
-/**
- * Returns true if the module is in the new debug info mode which uses
- * non-instruction debug records instead of debug intrinsics for variable
- * location tracking.
- * See See https://llvm.org/docs/RemoveDIsDebugInfo.html.
- */
-LLVMBool LLVMIsNewDbgInfoFormat(LLVMModuleRef M);
-
 /**
  * Obtain the identifier of a module.
  *
diff --git a/llvm/include/llvm-c/DebugInfo.h b/llvm/include/llvm-c/DebugInfo.h
index 6dd36f8dedec4d..ed863cff378fcd 100644
--- a/llvm/include/llvm-c/DebugInfo.h
+++ b/llvm/include/llvm-c/DebugInfo.h
@@ -1249,10 +1249,6 @@ LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(
     LLVMMetadataRef Decl, uint32_t AlignInBits);
 
 /**
- * Soon to be deprecated.
- * Only use in "old debug mode" (LLVMIsNewDbgFormat() is false).
- * See https://llvm.org/docs/RemoveDIsDebugInfo.html
- *
  * Insert a new llvm.dbg.declare intrinsic call before the given instruction.
  * \param Builder     The DIBuilder.
  * \param Storage     The storage of the variable to declare.
@@ -1261,31 +1257,12 @@ LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(
  * \param DebugLoc    Debug info location.
  * \param Instr       Instruction acting as a location for the new intrinsic.
  */
-LLVMValueRef LLVMDIBuilderInsertDeclareIntrinsicBefore(
-    LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
-    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMValueRef Instr);
-/**
- * Only use in "new debug mode" (LLVMIsNewDbgFormat() is true).
- * See https://llvm.org/docs/RemoveDIsDebugInfo.html
- *
- * Insert a Declare DbgRecord before the given instruction.
- * \param Builder     The DIBuilder.
- * \param Storage     The storage of the variable to declare.
- * \param VarInfo     The variable's debug info descriptor.
- * \param Expr        A complex location expression for the variable.
- * \param DebugLoc    Debug info location.
- * \param Instr       Instruction acting as a location for the new record.
- */
-LLVMDbgRecordRef
+LLVMValueRef
 LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
                                  LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
                                  LLVMMetadataRef DebugLoc, LLVMValueRef Instr);
 
 /**
- * Soon to be deprecated.
- * Only use in "old debug mode" (LLVMIsNewDbgFormat() is false).
- * See https://llvm.org/docs/RemoveDIsDebugInfo.html
- *
  * Insert a new llvm.dbg.declare intrinsic call at the end of the given basic
  * block. If the basic block has a terminator instruction, the intrinsic is
  * inserted before that terminator instruction.
@@ -1296,47 +1273,11 @@ LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
  * \param DebugLoc    Debug info location.
  * \param Block       Basic block acting as a location for the new intrinsic.
  */
-LLVMValueRef LLVMDIBuilderInsertDeclareIntrinsicAtEnd(
-    LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
-    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block);
-/**
- * Only use in "new debug mode" (LLVMIsNewDbgFormat() is true).
- * See https://llvm.org/docs/RemoveDIsDebugInfo.html
- *
- * Insert a Declare DbgRecord at the end of the given basic block. If the basic
- * block has a terminator instruction, the record is inserted before that
- * terminator instruction.
- * \param Builder     The DIBuilder.
- * \param Storage     The storage of the variable to declare.
- * \param VarInfo     The variable's debug info descriptor.
- * \param Expr        A complex location expression for the variable.
- * \param DebugLoc    Debug info location.
- * \param Block       Basic block acting as a location for the new record.
- */
-LLVMDbgRecordRef LLVMDIBuilderInsertDeclareAtEnd(
+LLVMValueRef LLVMDIBuilderInsertDeclareAtEnd(
     LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
     LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block);
 
 /**
- * Soon to be deprecated.
- * Only use in "old debug mode" (Module::IsNewDbgInfoFormat is false).
- * See https://llvm.org/docs/RemoveDIsDebugInfo.html
- *
- * Insert a new llvm.dbg.value intrinsic call before the given instruction.
- * \param Builder     The DIBuilder.
- * \param Val         The value of the variable.
- * \param VarInfo     The variable's debug info descriptor.
- * \param Expr        A complex location expression for the variable.
- * \param DebugLoc    Debug info location.
- * \param Instr       Instruction acting as a location for the new intrinsic.
- */
-LLVMValueRef LLVMDIBuilderInsertDbgValueIntrinsicBefore(
-    LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
-    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMValueRef Instr);
-/**
- * Only use in "new debug mode" (Module::IsNewDbgInfoFormat is true).
- * See https://llvm.org/docs/RemoveDIsDebugInfo.html
- *
  * Insert a new llvm.dbg.value intrinsic call before the given instruction.
  * \param Builder     The DIBuilder.
  * \param Val         The value of the variable.
@@ -1345,33 +1286,12 @@ LLVMValueRef LLVMDIBuilderInsertDbgValueIntrinsicBefore(
  * \param DebugLoc    Debug info location.
  * \param Instr       Instruction acting as a location for the new intrinsic.
  */
-LLVMDbgRecordRef
+LLVMValueRef
 LLVMDIBuilderInsertDbgValueBefore(LLVMDIBuilderRef Builder, LLVMValueRef Val,
                                   LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
                                   LLVMMetadataRef DebugLoc, LLVMValueRef Instr);
 
 /**
- * Soon to be deprecated.
- * Only use in "old debug mode" (Module::IsNewDbgInfoFormat is false).
- * See https://llvm.org/docs/RemoveDIsDebugInfo.html
- *
- * Insert a new llvm.dbg.value intrinsic call at the end of the given basic
- * block. If the basic block has a terminator instruction, the intrinsic is
- * inserted before that terminator instruction.
- * \param Builder     The DIBuilder.
- * \param Val         The value of the variable.
- * \param VarInfo     The variable's debug info descriptor.
- * \param Expr        A complex location expression for the variable.
- * \param DebugLoc    Debug info location.
- * \param Block       Basic block acting as a location for the new intrinsic.
- */
-LLVMValueRef LLVMDIBuilderInsertDbgValueIntrinsicAtEnd(
-    LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
-    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block);
-/**
- * Only use in "new debug mode" (Module::IsNewDbgInfoFormat is true).
- * See https://llvm.org/docs/RemoveDIsDebugInfo.html
- *
  * Insert a new llvm.dbg.value intrinsic call at the end of the given basic
  * block. If the basic block has a terminator instruction, the intrinsic is
  * inserted before that terminator instruction.
@@ -1382,7 +1302,7 @@ LLVMValueRef LLVMDIBuilderInsertDbgValueIntrinsicAtEnd(
  * \param DebugLoc    Debug info location.
  * \param Block       Basic block acting as a location for the new intrinsic.
  */
-LLVMDbgRecordRef LLVMDIBuilderInsertDbgValueAtEnd(
+LLVMValueRef LLVMDIBuilderInsertDbgValueAtEnd(
     LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
     LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block);
 
diff --git a/llvm/include/llvm-c/Types.h b/llvm/include/llvm-c/Types.h
index 4681500ef9da3d..d5474d986309fa 100644
--- a/llvm/include/llvm-c/Types.h
+++ b/llvm/include/llvm-c/Types.h
@@ -169,11 +169,6 @@ typedef struct LLVMOpaqueJITEventListener *LLVMJITEventListenerRef;
  */
 typedef struct LLVMOpaqueBinary *LLVMBinaryRef;
 
-/**
- * @see llvm::DbgRecord
- */
-typedef struct LLVMOpaqueDbgRecord *LLVMDbgRecordRef;
-
 /**
  * @}
  */
diff --git a/llvm/include/llvm/IR/DebugProgramInstruction.h b/llvm/include/llvm/IR/DebugProgramInstruction.h
index 960489dc52b12a..a8faf415a3ea87 100644
--- a/llvm/include/llvm/IR/DebugProgramInstruction.h
+++ b/llvm/include/llvm/IR/DebugProgramInstruction.h
@@ -643,8 +643,6 @@ getDbgValueRange(DPMarker *DbgMarker) {
   return DbgMarker->getDbgValueRange();
 }
 
-DEFINE_ISA_CONVERSION_FUNCTIONS(DbgRecord, LLVMDbgRecordRef);
-
 } // namespace llvm
 
 #endif // LLVM_IR_DEBUGPROGRAMINSTRUCTION_H
diff --git a/llvm/lib/IR/DebugInfo.cpp b/llvm/lib/IR/DebugInfo.cpp
index 91c5499eac4e81..68fd244e256974 100644
--- a/llvm/lib/IR/DebugInfo.cpp
+++ b/llvm/lib/IR/DebugInfo.cpp
@@ -1659,90 +1659,51 @@ LLVMMetadataRef LLVMDIBuilderCreateTempGlobalVariableFwdDecl(
       unwrapDI<MDNode>(Decl), nullptr, AlignInBits));
 }
 
-LLVMValueRef LLVMDIBuilderInsertDeclareIntrinsicBefore(
-    LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
-    LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMValueRef Instr) {
-  return wrap(
-      unwrap(Builder)
-          ->insertDeclare(unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
-                          unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
-                          unwrap<Instruction>(Instr))
-          .get<Instruction *>());
-}
-LLVMDbgRecordRef
+LLVMValueRef
 LLVMDIBuilderInsertDeclareBefore(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
                                  LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
                                  LLVMMetadataRef DL, LLVMValueRef Instr) {
-  return wrap(
-      unwrap(Builder)
-          ->insertDeclare(unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
-                          unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
-                          unwrap<Instruction>(Instr))
-          .get<DbgRecord *>());
-}
-
-LLVMValueRef LLVMDIBuilderInsertDeclareIntrinsicAtEnd(
-    LLVMDIBuilderRef Builder, LLVMValueRef Storage, LLVMMetadataRef VarInfo,
-    LLVMMetadataRef Expr, LLVMMetadataRef DL, LLVMBasicBlockRef Block) {
-  return wrap(unwrap(Builder)
-                  ->insertDeclare(unwrap(Storage),
-                                  unwrap<DILocalVariable>(VarInfo),
-                                  unwrap<DIExpression>(Expr),
-                                  unwrap<DILocation>(DL), unwrap(Block))
-                  .get<Instruction *>());
-}
-LLVMDbgRecordRef
+  DbgInstPtr DbgInst = unwrap(Builder)->insertDeclare(
+      unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
+      unwrap<DIExpression>(Expr), unwrap<DILocation>(DL),
+      unwrap<Instruction>(Instr));
+  assert(isa<Instruction *>(DbgInst) &&
+         "Inserted a DbgRecord into function using old debug info mode");
+  return wrap(cast<Instruction *>(DbgInst));
+}
+
+LLVMValueRef
 LLVMDIBuilderInsertDeclareAtEnd(LLVMDIBuilderRef Builder, LLVMValueRef Storage,
                                 LLVMMetadataRef VarInfo, LLVMMetadataRef Expr,
                                 LLVMMetadataRef DL, LLVMBasicBlockRef Block) {
-  return wrap(unwrap(Builder)
-                  ->insertDeclare(unwrap(Storage),
-                                  unwrap<DILocalVariable>(VarInfo),
-                                  unwrap<DIExpression>(Expr),
-                                  unwrap<DILocation>(DL), unwrap(Block))
-                  .get<DbgRecord *>());
+  DbgInstPtr DbgInst = unwrap(Builder)->insertDeclare(
+      unwrap(Storage), unwrap<DILocalVariable>(VarInfo),
+      unwrap<DIExpression>(Expr), unwrap<DILocation>(DL), unwrap(Block));
+  assert(isa<Instruction *>(DbgInst) &&
+         "Inserted a DbgRecord into function using old debug info mode");
+  return wrap(cast<Instruction *>(DbgInst));
 }
 
-LLVMValueRef LLVMDIBuilderInsertDbgValueIntrinsicBefore(
+LLVMValueRef LLVMDIBuilderInsertDbgValueBefore(
     LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
     LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMValueRef Instr) {
-  return wrap(unwrap(Builder)
-                  ->insertDbgValueIntrinsic(
-                      unwrap(Val), unwrap<DILocalVariable>(VarInfo),
-                      unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
-                      unwrap<Instruction>(Instr))
-                  .get<Instruction *>());
-}
-LLVMDbgRecordRef LLVMDIBuilderInsertDbgValueBefore(
-    LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
-    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMValueRef Instr) {
-  return wrap(unwrap(Builder)
-                  ->insertDbgValueIntrinsic(
-                      unwrap(Val), unwrap<DILocalVariable>(VarInfo),
-                      unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
-                      unwrap<Instruction>(Instr))
-                  .get<DbgRecord *>());
+  DbgInstPtr DbgInst = unwrap(Builder)->insertDbgValueIntrinsic(
+      unwrap(Val), unwrap<DILocalVariable>(VarInfo), unwrap<DIExpression>(Expr),
+      unwrap<DILocation>(DebugLoc), unwrap<Instruction>(Instr));
+  assert(isa<Instruction *>(DbgInst) &&
+         "Inserted a DbgRecord into function using old debug info mode");
+  return wrap(cast<Instruction *>(DbgInst));
 }
 
-LLVMValueRef LLVMDIBuilderInsertDbgValueIntrinsicAtEnd(
-    LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
-    LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block) {
-  return wrap(unwrap(Builder)
-                  ->insertDbgValueIntrinsic(
-                      unwrap(Val), unwrap<DILocalVariable>(VarInfo),
-                      unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
-                      unwrap(Block))
-                  .get<Instruction *>());
-}
-LLVMDbgRecordRef LLVMDIBuilderInsertDbgValueAtEnd(
+LLVMValueRef LLVMDIBuilderInsertDbgValueAtEnd(
     LLVMDIBuilderRef Builder, LLVMValueRef Val, LLVMMetadataRef VarInfo,
     LLVMMetadataRef Expr, LLVMMetadataRef DebugLoc, LLVMBasicBlockRef Block) {
-  return wrap(unwrap(Builder)
-                  ->insertDbgValueIntrinsic(
-                      unwrap(Val), unwrap<DILocalVariable>(VarInfo),
-                      unwrap<DIExpression>(Expr), unwrap<DILocation>(DebugLoc),
-                      unwrap(Block))
-                  .get<DbgRecord *>());
+  DbgInstPtr DbgInst = unwrap(Builder)->insertDbgValueIntrinsic(
+      unwrap(Val), unwrap<DILocalVariable>(VarInfo), unwrap<DIExpression>(Expr),
+      unwrap<DILocation>(DebugLoc), unwrap(Block));
+  assert(isa<Instruction *>(DbgInst) &&
+         "Inserted a DbgRecord into function using old debug info mode");
+  return wrap(cast<Instruction *>(DbgInst));
 }
 
 LLVMMetadataRef LLVMDIBuilderCreateAutoVariable(
diff --git a/llvm/tools/llvm-c-test/debuginfo.c b/llvm/tools/llvm-c-test/debuginfo.c
index 4f4571d3292ff0..a3e41be12e95d4 100644
--- a/llvm/tools/llvm-c-test/debuginfo.c
+++ b/llvm/tools/llvm-c-test/debuginfo.c
@@ -135,38 +135,21 @@ int llvm_test_dibuilder(void) {
   LLVMMetadataRef FooParamVar1 =
     LLVMDIBuilderCreateParameterVariable(DIB, FunctionMetadata, "a", 1, 1, File,
                                          42, Int64Ty, true, 0);
-  if (LLVMIsNewDbgInfoFormat(M))
-    LLVMDIBuilderInsertDeclareAtEnd(
-        DIB, LLVMConstInt(LLVMInt64Type(), 0, false), FooParamVar1,
-        FooParamExpression, FooParamLocation, FooEntryBlock);
-  else
-    LLVMDIBuilderInsertDeclareIntrinsicAtEnd(
-        DIB, LLVMConstInt(LLVMInt64Type(), 0, false), FooParamVar1,
-        FooParamExpression, FooParamLocation, FooEntryBlock);
+  LLVMDIBuilderInsertDeclareAtEnd(DIB, LLVMConstInt(LLVMInt64Type(), 0, false),
+                                  FooParamVar1, FooParamExpression,
+                                  FooParamLocation, FooEntryBlock);
   LLVMMetadataRef FooParamVar2 =
     LLVMDIBuilderCreateParameterVariable(DIB, FunctionMetadata, "b", 1, 2, File,
                                          42, Int64Ty, true, 0);
-
-  if (LLVMIsNewDbgInfoFormat(M))
-    LLVMDIBuilderInsertDeclareAtEnd(
-        DIB, LLVMConstInt(LLVMInt64Type(), 0, false), FooParamVar2,
-        FooParamExpression, FooParamLocation, FooEntryBlock);
-  else
-    LLVMDIBuilderInsertDeclareIntrinsicAtEnd(
-        DIB, LLVMConstInt(LLVMInt64Type(), 0, false), FooParamVar2,
-        FooParamExpression, FooParamLocation, FooEntryBlock);
-
+  LLVMDIBuilderInsertDeclareAtEnd(DIB, LLVMConstInt(LLVMInt64Type(), 0, false),
+                                  FooParamVar2, FooParamExpression,
+                                  FooParamLocation, FooEntryBlock);
   LLVMMetadataRef FooParamVar3 =
     LLVMDIBuilderCreateParameterVariable(DIB, FunctionMetadata, "c", 1, 3, File,
                                          42, VectorTy, true, 0);
-  if (LLVMIsNewDbgInfoFormat(M))
-    LLVMDIBuilderInsertDeclareAtEnd(
-        DIB, LLVMConstInt(LLVMInt64Type(), 0, false), FooParamVar3,
-        FooParamExpression, FooParamLocation, FooEntryBlock);
-  else
-    LLVMDIBuilderInsertDeclareIntrinsicAtEnd(
-        DIB, LLVMConstInt(LLVMInt64Type(), 0, false), FooParamVar3,
-        FooParamExpression, FooParamLocation, FooEntryBlock);
+  LLVMDIBuilderInsertDeclareAtEnd(DIB, LLVMConstInt(LLVMInt64Type(), 0, false),
+                                  FooParamVar3, FooParamExpression,
+                                  FooParamLocation, FooEntryBlock);
 
   LLVMSetSubprogram(FooFunction, FunctionMetadata);
 
@@ -183,12 +166,9 @@ int llvm_test_dibuilder(void) {
   LLVMValueRef FooVal1 = LLVMConstInt(LLVMInt64Type(), 0, false);
   LLVMMetadataRef FooVarValueExpr =
     LLVMDIBuilderCreateConstantValueExpression(DIB, 0);
-  if (LLVMIsNewDbgInfoFormat(M))
-    LLVMDIBuilderInsertDbgValueAtEnd(DIB, FooVal1, FooVar1, FooVarValueExpr,
-                                     FooVarsLocation, FooVarBlock);
-  else
-    LLVMDIBuilderInsertDbgValueIntrinsicAtEnd(
-        DIB, FooVal1, FooVar1, FooVarValueExpr, FooVarsLocation, FooVarBlock);
+
+  LLVMDIBuilderInsertDbgValueAtEnd(DIB, FooVal1, FooVar1, FooVarValueExpr,
+                                   FooVarsLocation, FooVarBlock);
 
   LLVMMetadataRef MacroFile =
       LLVMDIBuilderCreateTempMacroFile(DIB, NULL, 0, File);



More information about the llvm-commits mailing list