1a94fa862Swlei //===-- ErrorHandling.h - Error handler -------------------------*- C++ -*-===//
2a94fa862Swlei //
3a94fa862Swlei // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4a94fa862Swlei // See https://llvm.org/LICENSE.txt for license information.
5a94fa862Swlei // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6a94fa862Swlei //
7a94fa862Swlei //===----------------------------------------------------------------------===//
8a94fa862Swlei
9a94fa862Swlei #ifndef LLVM_TOOLS_LLVM_PROFGEN_ERRORHANDLING_H
10a94fa862Swlei #define LLVM_TOOLS_LLVM_PROFGEN_ERRORHANDLING_H
11a94fa862Swlei
12a94fa862Swlei #include "llvm/ADT/Twine.h"
13a94fa862Swlei #include "llvm/Support/Errc.h"
14a94fa862Swlei #include "llvm/Support/Error.h"
15a94fa862Swlei #include "llvm/Support/ErrorOr.h"
16a94fa862Swlei #include "llvm/Support/WithColor.h"
17a94fa862Swlei #include <system_error>
18a94fa862Swlei
19a94fa862Swlei using namespace llvm;
20a94fa862Swlei
216da3d8b1SFangrui Song [[noreturn]] inline void exitWithError(const Twine &Message,
226da3d8b1SFangrui Song StringRef Whence = StringRef(),
23a94fa862Swlei StringRef Hint = StringRef()) {
24a94fa862Swlei WithColor::error(errs(), "llvm-profgen");
25a94fa862Swlei if (!Whence.empty())
26a94fa862Swlei errs() << Whence.str() << ": ";
27a94fa862Swlei errs() << Message << "\n";
28a94fa862Swlei if (!Hint.empty())
29a94fa862Swlei WithColor::note() << Hint.str() << "\n";
30a94fa862Swlei ::exit(EXIT_FAILURE);
31a94fa862Swlei }
32a94fa862Swlei
336da3d8b1SFangrui Song [[noreturn]] inline void exitWithError(std::error_code EC,
346da3d8b1SFangrui Song StringRef Whence = StringRef()) {
35a94fa862Swlei exitWithError(EC.message(), Whence);
36a94fa862Swlei }
37a94fa862Swlei
exitWithError(Error E,StringRef Whence)386da3d8b1SFangrui Song [[noreturn]] inline void exitWithError(Error E, StringRef Whence) {
39a94fa862Swlei exitWithError(errorToErrorCode(std::move(E)), Whence);
40a94fa862Swlei }
4132221694Swlei
4232221694Swlei template <typename T, typename... Ts>
unwrapOrError(Expected<T> EO,Ts &&...Args)4332221694Swlei T unwrapOrError(Expected<T> EO, Ts &&... Args) {
4432221694Swlei if (EO)
4532221694Swlei return std::move(*EO);
4632221694Swlei exitWithError(EO.takeError(), std::forward<Ts>(Args)...);
4732221694Swlei }
48*aab18100Swlei
emitWarningSummary(uint64_t Num,uint64_t Total,StringRef Msg)49*aab18100Swlei inline void emitWarningSummary(uint64_t Num, uint64_t Total, StringRef Msg) {
50*aab18100Swlei if (!Total || !Num)
51*aab18100Swlei return;
52*aab18100Swlei WithColor::warning() << format("%.2f", static_cast<double>(Num) * 100 / Total)
53*aab18100Swlei << "%(" << Num << "/" << Total << ") " << Msg << "\n";
54*aab18100Swlei }
55*aab18100Swlei
56a94fa862Swlei #endif
57