This patch relands https://reviews.llvm.org/D104799, but fixes the memory handling causing leak sanitizer failures. This reverts commit a56fe117e04f7d4b953a4226af412dad59425fb5.