deleting a range of instructions


I am trying to delete a range of instructions ( specified as between [startIns , endIns) ) .
the endIns may not be in the same basic block as the start.

I keep getting the following error when trying to delete the last instruction in -

reference llvm::ilist_iterator<llvm::ilist_detail::node_options<llvm::Instruction, true, false, void>, false, false>::operator*() const [OptionsT = llvm::ilist_detail::node_options<llvm::Instruction, true, false, void>, IsReverse = false, IsConst = false]: Assertion `!NodePtr->isKnownSentinel()’ failed.

Following is my C++ code -

// delete all instructions between [start,end)
void deleteAllInstructionsInRange(Instruction* startInst,Instruction* endInst)
BasicBlock::iterator it(startInst);
BasicBlock::iterator it_end(endInst);

Instruction* currentInst ;
Instruction* lastInst ;

while(it != it_end)
currentInst = &*it;


if (!currentInst->use_empty())




Following is my IR -

define i32 @test2() {
%calltmp = call i32 @UInt()
%datasize = alloca i32
switch i32 %calltmp, label [
i32 1, label
i32 2, label
i32 3, label

; %res = alloca i8 ------> deleted this
; store i8 0, i8* %res ------> deleted this
;%datasize1 = load i32, i32* %datasize ------> deleted this
;ret i32 %datasize1 ------> deleted this

ret i32 undef ------> Unable to delete this ; preds = %entry
%resclone0 = alloca i10
store i10 0, i10* %resclone0
%datasize1clone0 = load i32, i32* %datasize
ret i32 %datasize1clone0

Any help will be appreciated.