1 //===-- Analysis.cpp --------------------------------------------*- 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 #include "Analysis.h" 10 #include "BenchmarkResult.h" 11 #include "llvm/ADT/STLExtras.h" 12 #include "llvm/MC/MCAsmInfo.h" 13 #include "llvm/Support/FormatVariadic.h" 14 #include <limits> 15 #include <unordered_set> 16 #include <vector> 17 18 namespace llvm { 19 namespace exegesis { 20 21 static const char kCsvSep = ','; 22 23 static unsigned resolveSchedClassId(const llvm::MCSubtargetInfo &STI, 24 unsigned SchedClassId, 25 const llvm::MCInst &MCI) { 26 const auto &SM = STI.getSchedModel(); 27 while (SchedClassId && SM.getSchedClassDesc(SchedClassId)->isVariant()) 28 SchedClassId = 29 STI.resolveVariantSchedClass(SchedClassId, &MCI, SM.getProcessorID()); 30 return SchedClassId; 31 } 32 33 namespace { 34 35 enum EscapeTag { kEscapeCsv, kEscapeHtml, kEscapeHtmlString }; 36 37 template <EscapeTag Tag> 38 void writeEscaped(llvm::raw_ostream &OS, const llvm::StringRef S); 39 40 template <> 41 void writeEscaped<kEscapeCsv>(llvm::raw_ostream &OS, const llvm::StringRef S) { 42 if (std::find(S.begin(), S.end(), kCsvSep) == S.end()) { 43 OS << S; 44 } else { 45 // Needs escaping. 46 OS << '"'; 47 for (const char C : S) { 48 if (C == '"') 49 OS << "\"\""; 50 else 51 OS << C; 52 } 53 OS << '"'; 54 } 55 } 56 57 template <> 58 void writeEscaped<kEscapeHtml>(llvm::raw_ostream &OS, const llvm::StringRef S) { 59 for (const char C : S) { 60 if (C == '<') 61 OS << "<"; 62 else if (C == '>') 63 OS << ">"; 64 else if (C == '&') 65 OS << "&"; 66 else 67 OS << C; 68 } 69 } 70 71 template <> 72 void writeEscaped<kEscapeHtmlString>(llvm::raw_ostream &OS, 73 const llvm::StringRef S) { 74 for (const char C : S) { 75 if (C == '"') 76 OS << "\\\""; 77 else 78 OS << C; 79 } 80 } 81 82 } // namespace 83 84 template <EscapeTag Tag> 85 static void 86 writeClusterId(llvm::raw_ostream &OS, 87 const InstructionBenchmarkClustering::ClusterId &CID) { 88 if (CID.isNoise()) 89 writeEscaped<Tag>(OS, "[noise]"); 90 else if (CID.isError()) 91 writeEscaped<Tag>(OS, "[error]"); 92 else 93 OS << CID.getId(); 94 } 95 96 template <EscapeTag Tag> 97 static void writeMeasurementValue(llvm::raw_ostream &OS, const double Value) { 98 // Given Value, if we wanted to serialize it to a string, 99 // how many base-10 digits will we need to store, max? 100 static constexpr auto MaxDigitCount = 101 std::numeric_limits<decltype(Value)>::max_digits10; 102 // Also, we will need a decimal separator. 103 static constexpr auto DecimalSeparatorLen = 1; // '.' e.g. 104 // So how long of a string will the serialization produce, max? 105 static constexpr auto SerializationLen = MaxDigitCount + DecimalSeparatorLen; 106 107 // WARNING: when changing the format, also adjust the small-size estimate ^. 108 static constexpr StringLiteral SimpleFloatFormat = StringLiteral("{0:F}"); 109 110 writeEscaped<Tag>( 111 OS, 112 llvm::formatv(SimpleFloatFormat.data(), Value).sstr<SerializationLen>()); 113 } 114 115 template <typename EscapeTag, EscapeTag Tag> 116 void Analysis::writeSnippet(llvm::raw_ostream &OS, 117 llvm::ArrayRef<uint8_t> Bytes, 118 const char *Separator) const { 119 llvm::SmallVector<std::string, 3> Lines; 120 // Parse the asm snippet and print it. 121 while (!Bytes.empty()) { 122 llvm::MCInst MI; 123 uint64_t MISize = 0; 124 if (!Disasm_->getInstruction(MI, MISize, Bytes, 0, llvm::nulls(), 125 llvm::nulls())) { 126 writeEscaped<Tag>(OS, llvm::join(Lines, Separator)); 127 writeEscaped<Tag>(OS, Separator); 128 writeEscaped<Tag>(OS, "[error decoding asm snippet]"); 129 return; 130 } 131 llvm::SmallString<128> InstPrinterStr; // FIXME: magic number. 132 llvm::raw_svector_ostream OSS(InstPrinterStr); 133 InstPrinter_->printInst(&MI, OSS, "", *SubtargetInfo_); 134 Bytes = Bytes.drop_front(MISize); 135 Lines.emplace_back(llvm::StringRef(InstPrinterStr).trim()); 136 } 137 writeEscaped<Tag>(OS, llvm::join(Lines, Separator)); 138 } 139 140 // Prints a row representing an instruction, along with scheduling info and 141 // point coordinates (measurements). 142 void Analysis::printInstructionRowCsv(const size_t PointId, 143 llvm::raw_ostream &OS) const { 144 const InstructionBenchmark &Point = Clustering_.getPoints()[PointId]; 145 writeClusterId<kEscapeCsv>(OS, Clustering_.getClusterIdForPoint(PointId)); 146 OS << kCsvSep; 147 writeSnippet<EscapeTag, kEscapeCsv>(OS, Point.AssembledSnippet, "; "); 148 OS << kCsvSep; 149 writeEscaped<kEscapeCsv>(OS, Point.Key.Config); 150 OS << kCsvSep; 151 assert(!Point.Key.Instructions.empty()); 152 const llvm::MCInst &MCI = Point.keyInstruction(); 153 const unsigned SchedClassId = resolveSchedClassId( 154 *SubtargetInfo_, InstrInfo_->get(MCI.getOpcode()).getSchedClass(), MCI); 155 156 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 157 const llvm::MCSchedClassDesc *const SCDesc = 158 SubtargetInfo_->getSchedModel().getSchedClassDesc(SchedClassId); 159 writeEscaped<kEscapeCsv>(OS, SCDesc->Name); 160 #else 161 OS << SchedClassId; 162 #endif 163 for (const auto &Measurement : Point.Measurements) { 164 OS << kCsvSep; 165 writeMeasurementValue<kEscapeCsv>(OS, Measurement.PerInstructionValue); 166 } 167 OS << "\n"; 168 } 169 170 Analysis::Analysis(const llvm::Target &Target, 171 std::unique_ptr<llvm::MCInstrInfo> InstrInfo, 172 const InstructionBenchmarkClustering &Clustering, 173 double AnalysisInconsistencyEpsilon, 174 bool AnalysisDisplayUnstableOpcodes) 175 : Clustering_(Clustering), InstrInfo_(std::move(InstrInfo)), 176 AnalysisInconsistencyEpsilonSquared_(AnalysisInconsistencyEpsilon * 177 AnalysisInconsistencyEpsilon), 178 AnalysisDisplayUnstableOpcodes_(AnalysisDisplayUnstableOpcodes) { 179 if (Clustering.getPoints().empty()) 180 return; 181 182 const InstructionBenchmark &FirstPoint = Clustering.getPoints().front(); 183 RegInfo_.reset(Target.createMCRegInfo(FirstPoint.LLVMTriple)); 184 AsmInfo_.reset(Target.createMCAsmInfo(*RegInfo_, FirstPoint.LLVMTriple)); 185 SubtargetInfo_.reset(Target.createMCSubtargetInfo(FirstPoint.LLVMTriple, 186 FirstPoint.CpuName, "")); 187 InstPrinter_.reset(Target.createMCInstPrinter( 188 llvm::Triple(FirstPoint.LLVMTriple), 0 /*default variant*/, *AsmInfo_, 189 *InstrInfo_, *RegInfo_)); 190 191 Context_ = llvm::make_unique<llvm::MCContext>(AsmInfo_.get(), RegInfo_.get(), 192 &ObjectFileInfo_); 193 Disasm_.reset(Target.createMCDisassembler(*SubtargetInfo_, *Context_)); 194 assert(Disasm_ && "cannot create MCDisassembler. missing call to " 195 "InitializeXXXTargetDisassembler ?"); 196 } 197 198 template <> 199 llvm::Error 200 Analysis::run<Analysis::PrintClusters>(llvm::raw_ostream &OS) const { 201 if (Clustering_.getPoints().empty()) 202 return llvm::Error::success(); 203 204 // Write the header. 205 OS << "cluster_id" << kCsvSep << "opcode_name" << kCsvSep << "config" 206 << kCsvSep << "sched_class"; 207 for (const auto &Measurement : Clustering_.getPoints().front().Measurements) { 208 OS << kCsvSep; 209 writeEscaped<kEscapeCsv>(OS, Measurement.Key); 210 } 211 OS << "\n"; 212 213 // Write the points. 214 const auto &Clusters = Clustering_.getValidClusters(); 215 for (size_t I = 0, E = Clusters.size(); I < E; ++I) { 216 for (const size_t PointId : Clusters[I].PointIndices) { 217 printInstructionRowCsv(PointId, OS); 218 } 219 OS << "\n\n"; 220 } 221 return llvm::Error::success(); 222 } 223 224 Analysis::ResolvedSchedClassAndPoints::ResolvedSchedClassAndPoints( 225 ResolvedSchedClass &&RSC) 226 : RSC(std::move(RSC)) {} 227 228 std::vector<Analysis::ResolvedSchedClassAndPoints> 229 Analysis::makePointsPerSchedClass() const { 230 std::vector<ResolvedSchedClassAndPoints> Entries; 231 // Maps SchedClassIds to index in result. 232 std::unordered_map<unsigned, size_t> SchedClassIdToIndex; 233 const auto &Points = Clustering_.getPoints(); 234 for (size_t PointId = 0, E = Points.size(); PointId < E; ++PointId) { 235 const InstructionBenchmark &Point = Points[PointId]; 236 if (!Point.Error.empty()) 237 continue; 238 assert(!Point.Key.Instructions.empty()); 239 // FIXME: we should be using the tuple of classes for instructions in the 240 // snippet as key. 241 const llvm::MCInst &MCI = Point.keyInstruction(); 242 unsigned SchedClassId = InstrInfo_->get(MCI.getOpcode()).getSchedClass(); 243 const bool WasVariant = SchedClassId && SubtargetInfo_->getSchedModel() 244 .getSchedClassDesc(SchedClassId) 245 ->isVariant(); 246 SchedClassId = resolveSchedClassId(*SubtargetInfo_, SchedClassId, MCI); 247 const auto IndexIt = SchedClassIdToIndex.find(SchedClassId); 248 if (IndexIt == SchedClassIdToIndex.end()) { 249 // Create a new entry. 250 SchedClassIdToIndex.emplace(SchedClassId, Entries.size()); 251 ResolvedSchedClassAndPoints Entry( 252 ResolvedSchedClass(*SubtargetInfo_, SchedClassId, WasVariant)); 253 Entry.PointIds.push_back(PointId); 254 Entries.push_back(std::move(Entry)); 255 } else { 256 // Append to the existing entry. 257 Entries[IndexIt->second].PointIds.push_back(PointId); 258 } 259 } 260 return Entries; 261 } 262 263 // Uops repeat the same opcode over again. Just show this opcode and show the 264 // whole snippet only on hover. 265 static void writeUopsSnippetHtml(llvm::raw_ostream &OS, 266 const std::vector<llvm::MCInst> &Instructions, 267 const llvm::MCInstrInfo &InstrInfo) { 268 if (Instructions.empty()) 269 return; 270 writeEscaped<kEscapeHtml>(OS, InstrInfo.getName(Instructions[0].getOpcode())); 271 if (Instructions.size() > 1) 272 OS << " (x" << Instructions.size() << ")"; 273 } 274 275 // Latency tries to find a serial path. Just show the opcode path and show the 276 // whole snippet only on hover. 277 static void 278 writeLatencySnippetHtml(llvm::raw_ostream &OS, 279 const std::vector<llvm::MCInst> &Instructions, 280 const llvm::MCInstrInfo &InstrInfo) { 281 bool First = true; 282 for (const llvm::MCInst &Instr : Instructions) { 283 if (First) 284 First = false; 285 else 286 OS << " → "; 287 writeEscaped<kEscapeHtml>(OS, InstrInfo.getName(Instr.getOpcode())); 288 } 289 } 290 291 void Analysis::printSchedClassClustersHtml( 292 const std::vector<SchedClassCluster> &Clusters, 293 const ResolvedSchedClass &RSC, llvm::raw_ostream &OS) const { 294 const auto &Points = Clustering_.getPoints(); 295 OS << "<table class=\"sched-class-clusters\">"; 296 OS << "<tr><th>ClusterId</th><th>Opcode/Config</th>"; 297 assert(!Clusters.empty()); 298 for (const auto &Measurement : 299 Points[Clusters[0].getPointIds()[0]].Measurements) { 300 OS << "<th>"; 301 writeEscaped<kEscapeHtml>(OS, Measurement.Key); 302 OS << "</th>"; 303 } 304 OS << "</tr>"; 305 for (const SchedClassCluster &Cluster : Clusters) { 306 OS << "<tr class=\"" 307 << (Cluster.measurementsMatch(*SubtargetInfo_, RSC, Clustering_, 308 AnalysisInconsistencyEpsilonSquared_) 309 ? "good-cluster" 310 : "bad-cluster") 311 << "\"><td>"; 312 writeClusterId<kEscapeHtml>(OS, Cluster.id()); 313 OS << "</td><td><ul>"; 314 for (const size_t PointId : Cluster.getPointIds()) { 315 const auto &Point = Points[PointId]; 316 OS << "<li><span class=\"mono\" title=\""; 317 writeSnippet<EscapeTag, kEscapeHtmlString>(OS, Point.AssembledSnippet, 318 "\n"); 319 OS << "\">"; 320 switch (Point.Mode) { 321 case InstructionBenchmark::Latency: 322 writeLatencySnippetHtml(OS, Point.Key.Instructions, *InstrInfo_); 323 break; 324 case InstructionBenchmark::Uops: 325 case InstructionBenchmark::InverseThroughput: 326 writeUopsSnippetHtml(OS, Point.Key.Instructions, *InstrInfo_); 327 break; 328 default: 329 llvm_unreachable("invalid mode"); 330 } 331 OS << "</span> <span class=\"mono\">"; 332 writeEscaped<kEscapeHtml>(OS, Point.Key.Config); 333 OS << "</span></li>"; 334 } 335 OS << "</ul></td>"; 336 for (const auto &Stats : Cluster.getRepresentative()) { 337 OS << "<td class=\"measurement\">"; 338 writeMeasurementValue<kEscapeHtml>(OS, Stats.avg()); 339 OS << "<br><span class=\"minmax\">["; 340 writeMeasurementValue<kEscapeHtml>(OS, Stats.min()); 341 OS << ";"; 342 writeMeasurementValue<kEscapeHtml>(OS, Stats.max()); 343 OS << "]</span></td>"; 344 } 345 OS << "</tr>"; 346 } 347 OS << "</table>"; 348 } 349 350 // Return the non-redundant list of WriteProcRes used by the given sched class. 351 // The scheduling model for LLVM is such that each instruction has a certain 352 // number of uops which consume resources which are described by WriteProcRes 353 // entries. Each entry describe how many cycles are spent on a specific ProcRes 354 // kind. 355 // For example, an instruction might have 3 uOps, one dispatching on P0 356 // (ProcResIdx=1) and two on P06 (ProcResIdx = 7). 357 // Note that LLVM additionally denormalizes resource consumption to include 358 // usage of super resources by subresources. So in practice if there exists a 359 // P016 (ProcResIdx=10), then the cycles consumed by P0 are also consumed by 360 // P06 (ProcResIdx = 7) and P016 (ProcResIdx = 10), and the resources consumed 361 // by P06 are also consumed by P016. In the figure below, parenthesized cycles 362 // denote implied usage of superresources by subresources: 363 // P0 P06 P016 364 // uOp1 1 (1) (1) 365 // uOp2 1 (1) 366 // uOp3 1 (1) 367 // ============================= 368 // 1 3 3 369 // Eventually we end up with three entries for the WriteProcRes of the 370 // instruction: 371 // {ProcResIdx=1, Cycles=1} // P0 372 // {ProcResIdx=7, Cycles=3} // P06 373 // {ProcResIdx=10, Cycles=3} // P016 374 // 375 // Note that in this case, P016 does not contribute any cycles, so it would 376 // be removed by this function. 377 // FIXME: Move this to MCSubtargetInfo and use it in llvm-mca. 378 static llvm::SmallVector<llvm::MCWriteProcResEntry, 8> 379 getNonRedundantWriteProcRes(const llvm::MCSchedClassDesc &SCDesc, 380 const llvm::MCSubtargetInfo &STI) { 381 llvm::SmallVector<llvm::MCWriteProcResEntry, 8> Result; 382 const auto &SM = STI.getSchedModel(); 383 const unsigned NumProcRes = SM.getNumProcResourceKinds(); 384 385 // This assumes that the ProcResDescs are sorted in topological order, which 386 // is guaranteed by the tablegen backend. 387 llvm::SmallVector<float, 32> ProcResUnitUsage(NumProcRes); 388 for (const auto *WPR = STI.getWriteProcResBegin(&SCDesc), 389 *const WPREnd = STI.getWriteProcResEnd(&SCDesc); 390 WPR != WPREnd; ++WPR) { 391 const llvm::MCProcResourceDesc *const ProcResDesc = 392 SM.getProcResource(WPR->ProcResourceIdx); 393 if (ProcResDesc->SubUnitsIdxBegin == nullptr) { 394 // This is a ProcResUnit. 395 Result.push_back({WPR->ProcResourceIdx, WPR->Cycles}); 396 ProcResUnitUsage[WPR->ProcResourceIdx] += WPR->Cycles; 397 } else { 398 // This is a ProcResGroup. First see if it contributes any cycles or if 399 // it has cycles just from subunits. 400 float RemainingCycles = WPR->Cycles; 401 for (const auto *SubResIdx = ProcResDesc->SubUnitsIdxBegin; 402 SubResIdx != ProcResDesc->SubUnitsIdxBegin + ProcResDesc->NumUnits; 403 ++SubResIdx) { 404 RemainingCycles -= ProcResUnitUsage[*SubResIdx]; 405 } 406 if (RemainingCycles < 0.01f) { 407 // The ProcResGroup contributes no cycles of its own. 408 continue; 409 } 410 // The ProcResGroup contributes `RemainingCycles` cycles of its own. 411 Result.push_back({WPR->ProcResourceIdx, 412 static_cast<uint16_t>(std::round(RemainingCycles))}); 413 // Spread the remaining cycles over all subunits. 414 for (const auto *SubResIdx = ProcResDesc->SubUnitsIdxBegin; 415 SubResIdx != ProcResDesc->SubUnitsIdxBegin + ProcResDesc->NumUnits; 416 ++SubResIdx) { 417 ProcResUnitUsage[*SubResIdx] += RemainingCycles / ProcResDesc->NumUnits; 418 } 419 } 420 } 421 return Result; 422 } 423 424 Analysis::ResolvedSchedClass::ResolvedSchedClass( 425 const llvm::MCSubtargetInfo &STI, unsigned ResolvedSchedClassId, 426 bool WasVariant) 427 : SchedClassId(ResolvedSchedClassId), SCDesc(STI.getSchedModel().getSchedClassDesc(ResolvedSchedClassId)), 428 WasVariant(WasVariant), 429 NonRedundantWriteProcRes(getNonRedundantWriteProcRes(*SCDesc, STI)), 430 IdealizedProcResPressure(computeIdealizedProcResPressure( 431 STI.getSchedModel(), NonRedundantWriteProcRes)) { 432 assert((SCDesc == nullptr || !SCDesc->isVariant()) && 433 "ResolvedSchedClass should never be variant"); 434 } 435 436 void Analysis::SchedClassCluster::addPoint( 437 size_t PointId, const InstructionBenchmarkClustering &Clustering) { 438 PointIds.push_back(PointId); 439 const auto &Point = Clustering.getPoints()[PointId]; 440 if (ClusterId.isUndef()) { 441 ClusterId = Clustering.getClusterIdForPoint(PointId); 442 Representative.resize(Point.Measurements.size()); 443 } 444 for (size_t I = 0, E = Point.Measurements.size(); I < E; ++I) { 445 Representative[I].push(Point.Measurements[I]); 446 } 447 assert(ClusterId == Clustering.getClusterIdForPoint(PointId)); 448 } 449 450 // Returns a ProxResIdx by id or name. 451 static unsigned findProcResIdx(const llvm::MCSubtargetInfo &STI, 452 const llvm::StringRef NameOrId) { 453 // Interpret the key as an ProcResIdx. 454 unsigned ProcResIdx = 0; 455 if (llvm::to_integer(NameOrId, ProcResIdx, 10)) 456 return ProcResIdx; 457 // Interpret the key as a ProcRes name. 458 const auto &SchedModel = STI.getSchedModel(); 459 for (int I = 0, E = SchedModel.getNumProcResourceKinds(); I < E; ++I) { 460 if (NameOrId == SchedModel.getProcResource(I)->Name) 461 return I; 462 } 463 return 0; 464 } 465 466 bool Analysis::SchedClassCluster::measurementsMatch( 467 const llvm::MCSubtargetInfo &STI, const ResolvedSchedClass &RSC, 468 const InstructionBenchmarkClustering &Clustering, 469 const double AnalysisInconsistencyEpsilonSquared_) const { 470 const size_t NumMeasurements = Representative.size(); 471 std::vector<BenchmarkMeasure> ClusterCenterPoint(NumMeasurements); 472 std::vector<BenchmarkMeasure> SchedClassPoint(NumMeasurements); 473 // Latency case. 474 assert(!Clustering.getPoints().empty()); 475 const InstructionBenchmark::ModeE Mode = Clustering.getPoints()[0].Mode; 476 if (Mode == InstructionBenchmark::Latency) { 477 if (NumMeasurements != 1) { 478 llvm::errs() 479 << "invalid number of measurements in latency mode: expected 1, got " 480 << NumMeasurements << "\n"; 481 return false; 482 } 483 // Find the latency. 484 SchedClassPoint[0].PerInstructionValue = 0.0; 485 for (unsigned I = 0; I < RSC.SCDesc->NumWriteLatencyEntries; ++I) { 486 const llvm::MCWriteLatencyEntry *const WLE = 487 STI.getWriteLatencyEntry(RSC.SCDesc, I); 488 SchedClassPoint[0].PerInstructionValue = 489 std::max<double>(SchedClassPoint[0].PerInstructionValue, WLE->Cycles); 490 } 491 ClusterCenterPoint[0].PerInstructionValue = Representative[0].avg(); 492 } else if (Mode == InstructionBenchmark::Uops) { 493 for (int I = 0, E = Representative.size(); I < E; ++I) { 494 const auto Key = Representative[I].key(); 495 uint16_t ProcResIdx = findProcResIdx(STI, Key); 496 if (ProcResIdx > 0) { 497 // Find the pressure on ProcResIdx `Key`. 498 const auto ProcResPressureIt = 499 std::find_if(RSC.IdealizedProcResPressure.begin(), 500 RSC.IdealizedProcResPressure.end(), 501 [ProcResIdx](const std::pair<uint16_t, float> &WPR) { 502 return WPR.first == ProcResIdx; 503 }); 504 SchedClassPoint[I].PerInstructionValue = 505 ProcResPressureIt == RSC.IdealizedProcResPressure.end() 506 ? 0.0 507 : ProcResPressureIt->second; 508 } else if (Key == "NumMicroOps") { 509 SchedClassPoint[I].PerInstructionValue = RSC.SCDesc->NumMicroOps; 510 } else { 511 llvm::errs() << "expected `key` to be either a ProcResIdx or a ProcRes " 512 "name, got " 513 << Key << "\n"; 514 return false; 515 } 516 ClusterCenterPoint[I].PerInstructionValue = Representative[I].avg(); 517 } 518 } else if (Mode == InstructionBenchmark::InverseThroughput) { 519 for (int I = 0, E = Representative.size(); I < E; ++I) { 520 SchedClassPoint[I].PerInstructionValue = 521 MCSchedModel::getReciprocalThroughput(STI, *RSC.SCDesc); 522 ClusterCenterPoint[I].PerInstructionValue = Representative[I].min(); 523 } 524 } else { 525 llvm_unreachable("unimplemented measurement matching mode"); 526 return false; 527 } 528 return Clustering.isNeighbour(ClusterCenterPoint, SchedClassPoint, 529 AnalysisInconsistencyEpsilonSquared_); 530 } 531 532 void Analysis::printSchedClassDescHtml(const ResolvedSchedClass &RSC, 533 llvm::raw_ostream &OS) const { 534 OS << "<table class=\"sched-class-desc\">"; 535 OS << "<tr><th>Valid</th><th>Variant</th><th>NumMicroOps</th><th>Latency</" 536 "th><th>RThroughput</th><th>WriteProcRes</th><th title=\"This is the " 537 "idealized unit resource (port) pressure assuming ideal " 538 "distribution\">Idealized Resource Pressure</th></tr>"; 539 if (RSC.SCDesc->isValid()) { 540 const auto &SM = SubtargetInfo_->getSchedModel(); 541 OS << "<tr><td>✔</td>"; 542 OS << "<td>" << (RSC.WasVariant ? "✔" : "✕") << "</td>"; 543 OS << "<td>" << RSC.SCDesc->NumMicroOps << "</td>"; 544 // Latencies. 545 OS << "<td><ul>"; 546 for (int I = 0, E = RSC.SCDesc->NumWriteLatencyEntries; I < E; ++I) { 547 const auto *const Entry = 548 SubtargetInfo_->getWriteLatencyEntry(RSC.SCDesc, I); 549 OS << "<li>" << Entry->Cycles; 550 if (RSC.SCDesc->NumWriteLatencyEntries > 1) { 551 // Dismabiguate if more than 1 latency. 552 OS << " (WriteResourceID " << Entry->WriteResourceID << ")"; 553 } 554 OS << "</li>"; 555 } 556 OS << "</ul></td>"; 557 // inverse throughput. 558 OS << "<td>"; 559 writeMeasurementValue<kEscapeHtml>( 560 OS, 561 MCSchedModel::getReciprocalThroughput(*SubtargetInfo_, *RSC.SCDesc)); 562 OS << "</td>"; 563 // WriteProcRes. 564 OS << "<td><ul>"; 565 for (const auto &WPR : RSC.NonRedundantWriteProcRes) { 566 OS << "<li><span class=\"mono\">"; 567 writeEscaped<kEscapeHtml>(OS, 568 SM.getProcResource(WPR.ProcResourceIdx)->Name); 569 OS << "</span>: " << WPR.Cycles << "</li>"; 570 } 571 OS << "</ul></td>"; 572 // Idealized port pressure. 573 OS << "<td><ul>"; 574 for (const auto &Pressure : RSC.IdealizedProcResPressure) { 575 OS << "<li><span class=\"mono\">"; 576 writeEscaped<kEscapeHtml>(OS, SubtargetInfo_->getSchedModel() 577 .getProcResource(Pressure.first) 578 ->Name); 579 OS << "</span>: "; 580 writeMeasurementValue<kEscapeHtml>(OS, Pressure.second); 581 OS << "</li>"; 582 } 583 OS << "</ul></td>"; 584 OS << "</tr>"; 585 } else { 586 OS << "<tr><td>✕</td><td></td><td></td></tr>"; 587 } 588 OS << "</table>"; 589 } 590 591 static constexpr const char kHtmlHead[] = R"( 592 <head> 593 <title>llvm-exegesis Analysis Results</title> 594 <style> 595 body { 596 font-family: sans-serif 597 } 598 span.sched-class-name { 599 font-weight: bold; 600 font-family: monospace; 601 } 602 span.opcode { 603 font-family: monospace; 604 } 605 span.config { 606 font-family: monospace; 607 } 608 div.inconsistency { 609 margin-top: 50px; 610 } 611 table { 612 margin-left: 50px; 613 border-collapse: collapse; 614 } 615 table, table tr,td,th { 616 border: 1px solid #444; 617 } 618 table ul { 619 padding-left: 0px; 620 margin: 0px; 621 list-style-type: none; 622 } 623 table.sched-class-clusters td { 624 padding-left: 10px; 625 padding-right: 10px; 626 padding-top: 10px; 627 padding-bottom: 10px; 628 } 629 table.sched-class-desc td { 630 padding-left: 10px; 631 padding-right: 10px; 632 padding-top: 2px; 633 padding-bottom: 2px; 634 } 635 span.mono { 636 font-family: monospace; 637 } 638 td.measurement { 639 text-align: center; 640 } 641 tr.good-cluster td.measurement { 642 color: #292 643 } 644 tr.bad-cluster td.measurement { 645 color: #922 646 } 647 tr.good-cluster td.measurement span.minmax { 648 color: #888; 649 } 650 tr.bad-cluster td.measurement span.minmax { 651 color: #888; 652 } 653 </style> 654 </head> 655 )"; 656 657 template <> 658 llvm::Error Analysis::run<Analysis::PrintSchedClassInconsistencies>( 659 llvm::raw_ostream &OS) const { 660 const auto &FirstPoint = Clustering_.getPoints()[0]; 661 // Print the header. 662 OS << "<!DOCTYPE html><html>" << kHtmlHead << "<body>"; 663 OS << "<h1><span class=\"mono\">llvm-exegesis</span> Analysis Results</h1>"; 664 OS << "<h3>Triple: <span class=\"mono\">"; 665 writeEscaped<kEscapeHtml>(OS, FirstPoint.LLVMTriple); 666 OS << "</span></h3><h3>Cpu: <span class=\"mono\">"; 667 writeEscaped<kEscapeHtml>(OS, FirstPoint.CpuName); 668 OS << "</span></h3>"; 669 670 for (const auto &RSCAndPoints : makePointsPerSchedClass()) { 671 if (!RSCAndPoints.RSC.SCDesc) 672 continue; 673 // Bucket sched class points into sched class clusters. 674 std::vector<SchedClassCluster> SchedClassClusters; 675 for (const size_t PointId : RSCAndPoints.PointIds) { 676 const auto &ClusterId = Clustering_.getClusterIdForPoint(PointId); 677 if (!ClusterId.isValid()) 678 continue; // Ignore noise and errors. FIXME: take noise into account ? 679 if (ClusterId.isUnstable() ^ AnalysisDisplayUnstableOpcodes_) 680 continue; // Either display stable or unstable clusters only. 681 auto SchedClassClusterIt = 682 std::find_if(SchedClassClusters.begin(), SchedClassClusters.end(), 683 [ClusterId](const SchedClassCluster &C) { 684 return C.id() == ClusterId; 685 }); 686 if (SchedClassClusterIt == SchedClassClusters.end()) { 687 SchedClassClusters.emplace_back(); 688 SchedClassClusterIt = std::prev(SchedClassClusters.end()); 689 } 690 SchedClassClusterIt->addPoint(PointId, Clustering_); 691 } 692 693 // Print any scheduling class that has at least one cluster that does not 694 // match the checked-in data. 695 if (llvm::all_of(SchedClassClusters, 696 [this, &RSCAndPoints](const SchedClassCluster &C) { 697 return C.measurementsMatch( 698 *SubtargetInfo_, RSCAndPoints.RSC, Clustering_, 699 AnalysisInconsistencyEpsilonSquared_); 700 })) 701 continue; // Nothing weird. 702 703 OS << "<div class=\"inconsistency\"><p>Sched Class <span " 704 "class=\"sched-class-name\">"; 705 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 706 writeEscaped<kEscapeHtml>(OS, RSCAndPoints.RSC.SCDesc->Name); 707 #else 708 OS << RSCAndPoints.RSC.SchedClassId; 709 #endif 710 OS << "</span> contains instructions whose performance characteristics do" 711 " not match that of LLVM:</p>"; 712 printSchedClassClustersHtml(SchedClassClusters, RSCAndPoints.RSC, OS); 713 OS << "<p>llvm SchedModel data:</p>"; 714 printSchedClassDescHtml(RSCAndPoints.RSC, OS); 715 OS << "</div>"; 716 } 717 718 OS << "</body></html>"; 719 return llvm::Error::success(); 720 } 721 722 // Distributes a pressure budget as evenly as possible on the provided subunits 723 // given the already existing port pressure distribution. 724 // 725 // The algorithm is as follows: while there is remaining pressure to 726 // distribute, find the subunits with minimal pressure, and distribute 727 // remaining pressure equally up to the pressure of the unit with 728 // second-to-minimal pressure. 729 // For example, let's assume we want to distribute 2*P1256 730 // (Subunits = [P1,P2,P5,P6]), and the starting DensePressure is: 731 // DensePressure = P0 P1 P2 P3 P4 P5 P6 P7 732 // 0.1 0.3 0.2 0.0 0.0 0.5 0.5 0.5 733 // RemainingPressure = 2.0 734 // We sort the subunits by pressure: 735 // Subunits = [(P2,p=0.2), (P1,p=0.3), (P5,p=0.5), (P6, p=0.5)] 736 // We'll first start by the subunits with minimal pressure, which are at 737 // the beginning of the sorted array. In this example there is one (P2). 738 // The subunit with second-to-minimal pressure is the next one in the 739 // array (P1). So we distribute 0.1 pressure to P2, and remove 0.1 cycles 740 // from the budget. 741 // Subunits = [(P2,p=0.3), (P1,p=0.3), (P5,p=0.5), (P5,p=0.5)] 742 // RemainingPressure = 1.9 743 // We repeat this process: distribute 0.2 pressure on each of the minimal 744 // P2 and P1, decrease budget by 2*0.2: 745 // Subunits = [(P2,p=0.5), (P1,p=0.5), (P5,p=0.5), (P5,p=0.5)] 746 // RemainingPressure = 1.5 747 // There are no second-to-minimal subunits so we just share the remaining 748 // budget (1.5 cycles) equally: 749 // Subunits = [(P2,p=0.875), (P1,p=0.875), (P5,p=0.875), (P5,p=0.875)] 750 // RemainingPressure = 0.0 751 // We stop as there is no remaining budget to distribute. 752 void distributePressure(float RemainingPressure, 753 llvm::SmallVector<uint16_t, 32> Subunits, 754 llvm::SmallVector<float, 32> &DensePressure) { 755 // Find the number of subunits with minimal pressure (they are at the 756 // front). 757 llvm::sort(Subunits, [&DensePressure](const uint16_t A, const uint16_t B) { 758 return DensePressure[A] < DensePressure[B]; 759 }); 760 const auto getPressureForSubunit = [&DensePressure, 761 &Subunits](size_t I) -> float & { 762 return DensePressure[Subunits[I]]; 763 }; 764 size_t NumMinimalSU = 1; 765 while (NumMinimalSU < Subunits.size() && 766 getPressureForSubunit(NumMinimalSU) == getPressureForSubunit(0)) { 767 ++NumMinimalSU; 768 } 769 while (RemainingPressure > 0.0f) { 770 if (NumMinimalSU == Subunits.size()) { 771 // All units are minimal, just distribute evenly and be done. 772 for (size_t I = 0; I < NumMinimalSU; ++I) { 773 getPressureForSubunit(I) += RemainingPressure / NumMinimalSU; 774 } 775 return; 776 } 777 // Distribute the remaining pressure equally. 778 const float MinimalPressure = getPressureForSubunit(NumMinimalSU - 1); 779 const float SecondToMinimalPressure = getPressureForSubunit(NumMinimalSU); 780 assert(MinimalPressure < SecondToMinimalPressure); 781 const float Increment = SecondToMinimalPressure - MinimalPressure; 782 if (RemainingPressure <= NumMinimalSU * Increment) { 783 // There is not enough remaining pressure. 784 for (size_t I = 0; I < NumMinimalSU; ++I) { 785 getPressureForSubunit(I) += RemainingPressure / NumMinimalSU; 786 } 787 return; 788 } 789 // Bump all minimal pressure subunits to `SecondToMinimalPressure`. 790 for (size_t I = 0; I < NumMinimalSU; ++I) { 791 getPressureForSubunit(I) = SecondToMinimalPressure; 792 RemainingPressure -= SecondToMinimalPressure; 793 } 794 while (NumMinimalSU < Subunits.size() && 795 getPressureForSubunit(NumMinimalSU) == SecondToMinimalPressure) { 796 ++NumMinimalSU; 797 } 798 } 799 } 800 801 std::vector<std::pair<uint16_t, float>> computeIdealizedProcResPressure( 802 const llvm::MCSchedModel &SM, 803 llvm::SmallVector<llvm::MCWriteProcResEntry, 8> WPRS) { 804 // DensePressure[I] is the port pressure for Proc Resource I. 805 llvm::SmallVector<float, 32> DensePressure(SM.getNumProcResourceKinds()); 806 llvm::sort(WPRS, [](const llvm::MCWriteProcResEntry &A, 807 const llvm::MCWriteProcResEntry &B) { 808 return A.ProcResourceIdx < B.ProcResourceIdx; 809 }); 810 for (const llvm::MCWriteProcResEntry &WPR : WPRS) { 811 // Get units for the entry. 812 const llvm::MCProcResourceDesc *const ProcResDesc = 813 SM.getProcResource(WPR.ProcResourceIdx); 814 if (ProcResDesc->SubUnitsIdxBegin == nullptr) { 815 // This is a ProcResUnit. 816 DensePressure[WPR.ProcResourceIdx] += WPR.Cycles; 817 } else { 818 // This is a ProcResGroup. 819 llvm::SmallVector<uint16_t, 32> Subunits(ProcResDesc->SubUnitsIdxBegin, 820 ProcResDesc->SubUnitsIdxBegin + 821 ProcResDesc->NumUnits); 822 distributePressure(WPR.Cycles, Subunits, DensePressure); 823 } 824 } 825 // Turn dense pressure into sparse pressure by removing zero entries. 826 std::vector<std::pair<uint16_t, float>> Pressure; 827 for (unsigned I = 0, E = SM.getNumProcResourceKinds(); I < E; ++I) { 828 if (DensePressure[I] > 0.0f) 829 Pressure.emplace_back(I, DensePressure[I]); 830 } 831 return Pressure; 832 } 833 834 } // namespace exegesis 835 } // namespace llvm 836