1 //===- llvm/IR/LLVMRemarkStreamer.cpp - Remark Streamer -*- C++ ---------*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the implementation of the conversion between IR
10 // Diagnostics and serializable remarks::Remark objects.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/IR/LLVMRemarkStreamer.h"
15 #include "llvm/IR/DiagnosticInfo.h"
16 #include "llvm/IR/Function.h"
17 #include "llvm/IR/GlobalValue.h"
18 #include "llvm/Remarks/RemarkStreamer.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/ToolOutputFile.h"
21 
22 using namespace llvm;
23 
24 /// DiagnosticKind -> remarks::Type
25 static remarks::Type toRemarkType(enum DiagnosticKind Kind) {
26   switch (Kind) {
27   default:
28     return remarks::Type::Unknown;
29   case DK_OptimizationRemark:
30   case DK_MachineOptimizationRemark:
31     return remarks::Type::Passed;
32   case DK_OptimizationRemarkMissed:
33   case DK_MachineOptimizationRemarkMissed:
34     return remarks::Type::Missed;
35   case DK_OptimizationRemarkAnalysis:
36   case DK_MachineOptimizationRemarkAnalysis:
37     return remarks::Type::Analysis;
38   case DK_OptimizationRemarkAnalysisFPCommute:
39     return remarks::Type::AnalysisFPCommute;
40   case DK_OptimizationRemarkAnalysisAliasing:
41     return remarks::Type::AnalysisAliasing;
42   case DK_OptimizationFailure:
43     return remarks::Type::Failure;
44   }
45 }
46 
47 /// DiagnosticLocation -> remarks::RemarkLocation.
48 static Optional<remarks::RemarkLocation>
49 toRemarkLocation(const DiagnosticLocation &DL) {
50   if (!DL.isValid())
51     return None;
52   StringRef File = DL.getRelativePath();
53   unsigned Line = DL.getLine();
54   unsigned Col = DL.getColumn();
55   return remarks::RemarkLocation{File, Line, Col};
56 }
57 
58 /// LLVM Diagnostic -> Remark
59 remarks::Remark
60 LLVMRemarkStreamer::toRemark(const DiagnosticInfoOptimizationBase &Diag) const {
61   remarks::Remark R; // The result.
62   R.RemarkType = toRemarkType(static_cast<DiagnosticKind>(Diag.getKind()));
63   R.PassName = Diag.getPassName();
64   R.RemarkName = Diag.getRemarkName();
65   R.FunctionName =
66       GlobalValue::dropLLVMManglingEscape(Diag.getFunction().getName());
67   R.Loc = toRemarkLocation(Diag.getLocation());
68   R.Hotness = Diag.getHotness();
69 
70   for (const DiagnosticInfoOptimizationBase::Argument &Arg : Diag.getArgs()) {
71     R.Args.emplace_back();
72     R.Args.back().Key = Arg.Key;
73     R.Args.back().Val = Arg.Val;
74     R.Args.back().Loc = toRemarkLocation(Arg.Loc);
75   }
76 
77   return R;
78 }
79 
80 void LLVMRemarkStreamer::emit(const DiagnosticInfoOptimizationBase &Diag) {
81   if (!RS.matchesFilter(Diag.getPassName()))
82       return;
83 
84   // First, convert the diagnostic to a remark.
85   remarks::Remark R = toRemark(Diag);
86   // Then, emit the remark through the serializer.
87   RS.getSerializer().emit(R);
88 }
89 
90 char LLVMRemarkSetupFileError::ID = 0;
91 char LLVMRemarkSetupPatternError::ID = 0;
92 char LLVMRemarkSetupFormatError::ID = 0;
93 
94 Expected<std::unique_ptr<ToolOutputFile>> llvm::setupLLVMOptimizationRemarks(
95     LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses,
96     StringRef RemarksFormat, bool RemarksWithHotness,
97     Optional<uint64_t> RemarksHotnessThreshold) {
98   if (RemarksWithHotness)
99     Context.setDiagnosticsHotnessRequested(true);
100 
101   Context.setDiagnosticsHotnessThreshold(RemarksHotnessThreshold);
102 
103   if (RemarksFilename.empty())
104     return nullptr;
105 
106   Expected<remarks::Format> Format = remarks::parseFormat(RemarksFormat);
107   if (Error E = Format.takeError())
108     return make_error<LLVMRemarkSetupFormatError>(std::move(E));
109 
110   std::error_code EC;
111   auto Flags = *Format == remarks::Format::YAML ? sys::fs::OF_TextWithCRLF
112                                                 : sys::fs::OF_None;
113   auto RemarksFile =
114       std::make_unique<ToolOutputFile>(RemarksFilename, EC, Flags);
115   // We don't use llvm::FileError here because some diagnostics want the file
116   // name separately.
117   if (EC)
118     return make_error<LLVMRemarkSetupFileError>(errorCodeToError(EC));
119 
120   Expected<std::unique_ptr<remarks::RemarkSerializer>> RemarkSerializer =
121       remarks::createRemarkSerializer(
122           *Format, remarks::SerializerMode::Separate, RemarksFile->os());
123   if (Error E = RemarkSerializer.takeError())
124     return make_error<LLVMRemarkSetupFormatError>(std::move(E));
125 
126   // Create the main remark streamer.
127   Context.setMainRemarkStreamer(std::make_unique<remarks::RemarkStreamer>(
128       std::move(*RemarkSerializer), RemarksFilename));
129 
130   // Create LLVM's optimization remarks streamer.
131   Context.setLLVMRemarkStreamer(
132       std::make_unique<LLVMRemarkStreamer>(*Context.getMainRemarkStreamer()));
133 
134   if (!RemarksPasses.empty())
135     if (Error E = Context.getMainRemarkStreamer()->setFilter(RemarksPasses))
136       return make_error<LLVMRemarkSetupPatternError>(std::move(E));
137 
138   return std::move(RemarksFile);
139 }
140 
141 Error llvm::setupLLVMOptimizationRemarks(
142     LLVMContext &Context, raw_ostream &OS, StringRef RemarksPasses,
143     StringRef RemarksFormat, bool RemarksWithHotness,
144     Optional<uint64_t> RemarksHotnessThreshold) {
145   if (RemarksWithHotness)
146     Context.setDiagnosticsHotnessRequested(true);
147 
148   Context.setDiagnosticsHotnessThreshold(RemarksHotnessThreshold);
149 
150   Expected<remarks::Format> Format = remarks::parseFormat(RemarksFormat);
151   if (Error E = Format.takeError())
152     return make_error<LLVMRemarkSetupFormatError>(std::move(E));
153 
154   Expected<std::unique_ptr<remarks::RemarkSerializer>> RemarkSerializer =
155       remarks::createRemarkSerializer(*Format,
156                                       remarks::SerializerMode::Separate, OS);
157   if (Error E = RemarkSerializer.takeError())
158     return make_error<LLVMRemarkSetupFormatError>(std::move(E));
159 
160   // Create the main remark streamer.
161   Context.setMainRemarkStreamer(
162       std::make_unique<remarks::RemarkStreamer>(std::move(*RemarkSerializer)));
163 
164   // Create LLVM's optimization remarks streamer.
165   Context.setLLVMRemarkStreamer(
166       std::make_unique<LLVMRemarkStreamer>(*Context.getMainRemarkStreamer()));
167 
168   if (!RemarksPasses.empty())
169     if (Error E = Context.getMainRemarkStreamer()->setFilter(RemarksPasses))
170       return make_error<LLVMRemarkSetupPatternError>(std::move(E));
171 
172   return Error::success();
173 }
174