diff --git a/llvm/include/llvm/CodeGen/SlotIndexes.h b/llvm/include/llvm/CodeGen/SlotIndexes.h
--- a/llvm/include/llvm/CodeGen/SlotIndexes.h
+++ b/llvm/include/llvm/CodeGen/SlotIndexes.h
@@ -611,15 +611,18 @@
                          MachineInstr *InsertionPoint = nullptr) {
       MachineFunction::iterator nextMBB =
         std::next(MachineFunction::iterator(mbb));
+      bool IsLastMBB = nextMBB == mbb->getParent()->end();
 
       IndexListEntry *startEntry = nullptr;
       IndexListEntry *endEntry = nullptr;
       IndexList::iterator newItr;
       if (InsertionPoint) {
         startEntry = createEntry(nullptr, 0);
-        endEntry = getInstructionIndex(*InsertionPoint).listEntry();
-        newItr = indexList.insert(endEntry->getIterator(), startEntry);
-      } else if (nextMBB == mbb->getParent()->end()) {
+        endEntry = IsLastMBB ? &indexList.back()
+                             : getMBBStartIdx(&*nextMBB).listEntry();
+        auto *InsIdx = getInstructionIndex(*InsertionPoint).listEntry();
+        newItr = indexList.insert(InsIdx->getIterator(), startEntry);
+      } else if (IsLastMBB) {
         startEntry = &indexList.back();
         endEntry = createEntry(nullptr, 0);
         newItr = indexList.insertAfter(startEntry->getIterator(), endEntry);