Roger Federer produced one of his greatest comebacks to defeat Gael Monfils in five sets in the quarter-finals of the US Open.