[llvm][ADT] Allow returning `std::nullopt` in TypeSwitch
authorMarkus Böck <markus.boeck02@gmail.com>
Sat, 17 Dec 2022 21:42:30 +0000 (22:42 +0100)
committerMarkus Böck <markus.boeck02@gmail.com>
Sat, 17 Dec 2022 23:02:03 +0000 (00:02 +0100)
commit1d43966bc33a55cad1db7758bf4d82526d125db7
tree79be234ffb40d8ac69833b4cc9c44cc70a1b8849
parent1792821c8308755593c114c3b7ae8ce33bdb08e9
[llvm][ADT] Allow returning `std::nullopt` in TypeSwitch

Returning `std::nullopt` from the case of a `TypeSwitch` yields broken results, by either falling through to another case, or falling of the switch entirely and hitting an assertion. This is simply due to the use of `operator=` of what is now `std::optional`, which has an overload specifically for `std::nullopt`, causing the internal optional, used for the `TypeSwitch` result to be reset, instead of a value being constructed from the `std::nullopt`.

The fix is to simply use the `emplace` method of `std::optional`, causing a value to always be constructed from the value returned by the case function.

Differential Revision: https://reviews.llvm.org/D140265
llvm/include/llvm/ADT/TypeSwitch.h
llvm/unittests/ADT/TypeSwitchTest.cpp