1//===----------------------- CodeRegionGenerator.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/// \file
9///
10/// This file defines classes responsible for generating llvm-mca
11/// CodeRegions from various types of input. llvm-mca only analyzes CodeRegions,
12/// so the classes here provide the input-to-CodeRegions translation.
13//
14//===----------------------------------------------------------------------===//
15
16#include "CodeRegionGenerator.h"
17#include "llvm/ADT/StringRef.h"
18#include "llvm/MC/MCParser/MCTargetAsmParser.h"
19#include "llvm/MC/MCTargetOptions.h"
20#include "llvm/Support/Error.h"
21#include "llvm/Support/SMLoc.h"
22#include <memory>
23
24namespace llvm {
25namespace mca {
26
27// This virtual dtor serves as the anchor for the CodeRegionGenerator class.
28CodeRegionGenerator::~CodeRegionGenerator() = default;
29
30Expected<const CodeRegions &> AsmCodeRegionGenerator::parseCodeRegions(
31 const std::unique_ptr<MCInstPrinter> &IP, bool SkipFailures) {
32 MCTargetOptions Opts;
33 Opts.PreserveAsmComments = false;
34 CodeRegions &Regions = getRegions();
35 MCStreamerWrapper *Str = getMCStreamer();
36
37 // Need to initialize an MCTargetStreamer otherwise
38 // certain asm directives will cause a segfault.
39 // Using nulls() so that anything emitted by the MCTargetStreamer
40 // doesn't show up in the llvm-mca output.
41 raw_ostream &OSRef = nulls();
42 formatted_raw_ostream FOSRef(OSRef);
43 TheTarget.createAsmTargetStreamer(S&: *Str, OS&: FOSRef, InstPrint: IP.get());
44
45 // Create a MCAsmParser and setup the lexer to recognize llvm-mca ASM
46 // comments.
47 std::unique_ptr<MCAsmParser> Parser(
48 createMCAsmParser(Regions.getSourceMgr(), Ctx, *Str, MAI));
49 AsmLexer &Lexer = Parser->getLexer();
50 MCACommentConsumer *CCP = getCommentConsumer();
51 Lexer.setCommentConsumer(CCP);
52 // Enable support for MASM literal numbers (example: 05h, 101b).
53 Lexer.setLexMasmIntegers(true);
54
55 std::unique_ptr<MCTargetAsmParser> TAP(
56 TheTarget.createMCAsmParser(STI, Parser&: *Parser, MII: MCII));
57 if (!TAP)
58 return make_error<StringError>(
59 Args: "This target does not support assembly parsing.",
60 Args: inconvertibleErrorCode());
61 Parser->setTargetParser(*TAP);
62 // Parser->Run() confusingly returns true on errors, in which case the errors
63 // were already shown to the user. SkipFailures implies continuing in the
64 // presence of any kind of failure within the parser, in which case failing
65 // input lines are not represented, but the rest of the input remains.
66 bool HadParseError = Parser->Run(NoInitialTextSection: false);
67 if (CCP->hadErr())
68 return make_error<StringError>(Args: "There was an error parsing comments.",
69 Args: inconvertibleErrorCode());
70
71 if (HadParseError && !SkipFailures) {
72 const char *Message = "Assembly input parsing had errors, use "
73 "-skip-unsupported-instructions=parse-failure "
74 "to drop failing lines from the input.";
75 return make_error<StringError>(Args&: Message, Args: inconvertibleErrorCode());
76 }
77
78 // Set the assembler dialect from the input. llvm-mca will use this as the
79 // default dialect when printing reports.
80 AssemblerDialect = Parser->getAssemblerDialect();
81 return Regions;
82}
83
84void AnalysisRegionCommentConsumer::HandleComment(SMLoc Loc,
85 StringRef CommentText) {
86 // Skip empty comments.
87 StringRef Comment(CommentText);
88 if (Comment.empty())
89 return;
90
91 // Skip spaces and tabs.
92 unsigned Position = Comment.find_first_not_of(Chars: " \t");
93 if (Position >= Comment.size())
94 // We reached the end of the comment. Bail out.
95 return;
96
97 Comment = Comment.drop_front(N: Position);
98 if (Comment.consume_front(Prefix: "LLVM-MCA-END")) {
99 // Skip spaces and tabs.
100 Position = Comment.find_first_not_of(Chars: " \t");
101 if (Position < Comment.size())
102 Comment = Comment.drop_front(N: Position);
103 Regions.endRegion(Description: Comment, Loc);
104 return;
105 }
106
107 // Try to parse the LLVM-MCA-BEGIN comment.
108 if (!Comment.consume_front(Prefix: "LLVM-MCA-BEGIN"))
109 return;
110
111 // Skip spaces and tabs.
112 Position = Comment.find_first_not_of(Chars: " \t");
113 if (Position < Comment.size())
114 Comment = Comment.drop_front(N: Position);
115 // Use the rest of the string as a descriptor for this code snippet.
116 Regions.beginRegion(Description: Comment, Loc);
117}
118
119void InstrumentRegionCommentConsumer::HandleComment(SMLoc Loc,
120 StringRef CommentText) {
121 // Skip empty comments.
122 StringRef Comment(CommentText);
123 if (Comment.empty())
124 return;
125
126 // Skip spaces and tabs.
127 unsigned Position = Comment.find_first_not_of(Chars: " \t");
128 if (Position >= Comment.size())
129 // We reached the end of the comment. Bail out.
130 return;
131 Comment = Comment.drop_front(N: Position);
132
133 // Bail out if not an MCA style comment
134 if (!Comment.consume_front(Prefix: "LLVM-MCA-"))
135 return;
136
137 // Skip AnalysisRegion comments
138 if (Comment.consume_front(Prefix: "BEGIN") || Comment.consume_front(Prefix: "END"))
139 return;
140
141 if (IM.shouldIgnoreInstruments())
142 return;
143
144 auto [InstrumentKind, Data] = Comment.split(Separator: " ");
145
146 // An error if not of the form LLVM-MCA-TARGET-KIND
147 if (!IM.supportsInstrumentType(Type: InstrumentKind)) {
148 if (InstrumentKind.empty())
149 SM.PrintMessage(
150 Loc, Kind: llvm::SourceMgr::DK_Error,
151 Msg: "No instrumentation kind was provided in LLVM-MCA comment");
152 else
153 SM.PrintMessage(Loc, Kind: llvm::SourceMgr::DK_Error,
154 Msg: "Unknown instrumentation type in LLVM-MCA comment: " +
155 InstrumentKind);
156 FoundError = true;
157 return;
158 }
159
160 UniqueInstrument I = IM.createInstrument(Desc: InstrumentKind, Data);
161 if (!I) {
162 if (Data.empty())
163 SM.PrintMessage(Loc, Kind: llvm::SourceMgr::DK_Error,
164 Msg: "Failed to create " + InstrumentKind +
165 " instrument with no data");
166 else
167 SM.PrintMessage(Loc, Kind: llvm::SourceMgr::DK_Error,
168 Msg: "Failed to create " + InstrumentKind +
169 " instrument with data: " + Data);
170 FoundError = true;
171 return;
172 }
173
174 // End InstrumentType region if one is open
175 if (Regions.isRegionActive(Description: InstrumentKind))
176 Regions.endRegion(Description: InstrumentKind, Loc);
177 // Start new instrumentation region
178 Regions.beginRegion(Description: InstrumentKind, Loc, Instrument: std::move(I));
179}
180
181} // namespace mca
182} // namespace llvm
183