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 
19 using namespace llvm;
20 
21 /// DiagnosticKind -> remarks::Type
22 static remarks::Type toRemarkType(enum DiagnosticKind Kind) {
23   switch (Kind) {
24   default:
25     return remarks::Type::Unknown;
26   case DK_OptimizationRemark:
27   case DK_MachineOptimizationRemark:
28     return remarks::Type::Passed;
29   case DK_OptimizationRemarkMissed:
30   case DK_MachineOptimizationRemarkMissed:
31     return remarks::Type::Missed;
32   case DK_OptimizationRemarkAnalysis:
33   case DK_MachineOptimizationRemarkAnalysis:
34     return remarks::Type::Analysis;
35   case DK_OptimizationRemarkAnalysisFPCommute:
36     return remarks::Type::AnalysisFPCommute;
37   case DK_OptimizationRemarkAnalysisAliasing:
38     return remarks::Type::AnalysisAliasing;
39   case DK_OptimizationFailure:
40     return remarks::Type::Failure;
41   }
42 }
43 
44 /// DiagnosticLocation -> remarks::RemarkLocation.
45 static Optional<remarks::RemarkLocation>
46 toRemarkLocation(const DiagnosticLocation &DL) {
47   if (!DL.isValid())
48     return None;
49   StringRef File = DL.getRelativePath();
50   unsigned Line = DL.getLine();
51   unsigned Col = DL.getColumn();
52   return remarks::RemarkLocation{File, Line, Col};
53 }
54 
55 /// LLVM Diagnostic -> Remark
56 remarks::Remark
57 LLVMRemarkStreamer::toRemark(const DiagnosticInfoOptimizationBase &Diag) const {
58   remarks::Remark R; // The result.
59   R.RemarkType = toRemarkType(static_cast<DiagnosticKind>(Diag.getKind()));
60   R.PassName = Diag.getPassName();
61   R.RemarkName = Diag.getRemarkName();
62   R.FunctionName =
63       GlobalValue::dropLLVMManglingEscape(Diag.getFunction().getName());
64   R.Loc = toRemarkLocation(Diag.getLocation());
65   R.Hotness = Diag.getHotness();
66 
67   for (const DiagnosticInfoOptimizationBase::Argument &Arg : Diag.getArgs()) {
68     R.Args.emplace_back();
69     R.Args.back().Key = Arg.Key;
70     R.Args.back().Val = Arg.Val;
71     R.Args.back().Loc = toRemarkLocation(Arg.Loc);
72   }
73 
74   return R;
75 }
76 
77 void LLVMRemarkStreamer::emit(const DiagnosticInfoOptimizationBase &Diag) {
78   if (!RS.matchesFilter(Diag.getPassName()))
79       return;
80 
81   // First, convert the diagnostic to a remark.
82   remarks::Remark R = toRemark(Diag);
83   // Then, emit the remark through the serializer.
84   RS.getSerializer().emit(R);
85 }
86 
87 char LLVMRemarkSetupFileError::ID = 0;
88 char LLVMRemarkSetupPatternError::ID = 0;
89 char LLVMRemarkSetupFormatError::ID = 0;
90 
91 Expected<std::unique_ptr<ToolOutputFile>> llvm::setupLLVMOptimizationRemarks(
92     LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses,
93     StringRef RemarksFormat, bool RemarksWithHotness,
94     unsigned RemarksHotnessThreshold) {
95   if (RemarksWithHotness)
96     Context.setDiagnosticsHotnessRequested(true);
97 
98   if (RemarksHotnessThreshold)
99     Context.setDiagnosticsHotnessThreshold(RemarksHotnessThreshold);
100 
101   if (RemarksFilename.empty())
102     return nullptr;
103 
104   Expected<remarks::Format> Format = remarks::parseFormat(RemarksFormat);
105   if (Error E = Format.takeError())
106     return make_error<LLVMRemarkSetupFormatError>(std::move(E));
107 
108   std::error_code EC;
109   auto Flags = *Format == remarks::Format::YAML ? sys::fs::OF_Text
110                                                 : sys::fs::OF_None;
111   auto RemarksFile =
112       std::make_unique<ToolOutputFile>(RemarksFilename, EC, Flags);
113   // We don't use llvm::FileError here because some diagnostics want the file
114   // name separately.
115   if (EC)
116     return make_error<LLVMRemarkSetupFileError>(errorCodeToError(EC));
117 
118   Expected<std::unique_ptr<remarks::RemarkSerializer>> RemarkSerializer =
119       remarks::createRemarkSerializer(
120           *Format, remarks::SerializerMode::Separate, RemarksFile->os());
121   if (Error E = RemarkSerializer.takeError())
122     return make_error<LLVMRemarkSetupFormatError>(std::move(E));
123 
124   // Create the main remark streamer.
125   Context.setMainRemarkStreamer(std::make_unique<remarks::RemarkStreamer>(
126       std::move(*RemarkSerializer), RemarksFilename));
127 
128   // Create LLVM's optimization remarks streamer.
129   Context.setLLVMRemarkStreamer(
130       std::make_unique<LLVMRemarkStreamer>(*Context.getMainRemarkStreamer()));
131 
132   if (!RemarksPasses.empty())
133     if (Error E = Context.getMainRemarkStreamer()->setFilter(RemarksPasses))
134       return make_error<LLVMRemarkSetupPatternError>(std::move(E));
135 
136   return std::move(RemarksFile);
137 }
138 
139 Error llvm::setupLLVMOptimizationRemarks(LLVMContext &Context, raw_ostream &OS,
140                                          StringRef RemarksPasses,
141                                          StringRef RemarksFormat,
142                                          bool RemarksWithHotness,
143                                          unsigned RemarksHotnessThreshold) {
144   if (RemarksWithHotness)
145     Context.setDiagnosticsHotnessRequested(true);
146 
147   if (RemarksHotnessThreshold)
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