Value::setNameImpl() is used both to set and reset name of the value.
In destructor of Function all arguments get reset their names (see Function::clearArguments()).
If the arguments had their names set (e.g. when the function was created with LLVMContex::DiscardValueNames == true) then their ValueName entries referred by the function's symbol table must be destructed. They are not destructed if LLVMContex::DiscardValueNames is set to false because of the fast path in Value::setNameImpl(). See the new test cases that demonstrate the problem. Without the fix they both crash in the function's destructor.
In Value::setNameImpl() this patch narrows down the fast path return for DiscardValueNames == true to allow destruction of ValueName entries if any.
I would guess it's important that we preserve the fast-path here (although I don't have numbers). Amending it to getContext().shouldDiscardValueNames() && !isa<GlobalValue>(this) && !hasName()) or something like that is probably trivial enough that it doesn't really matter, but the current patch runs a lot of code that doesn't do anything.