1 //===--------------------- CodeEmitter.h ------------------------*- 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 /// A utility class used to compute instruction encodings. It buffers encodings
11 /// for later usage. It exposes a simple API to compute and get the encodings as
12 /// StringRef.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #ifndef LLVM_MCA_CODEEMITTER_H
17 #define LLVM_MCA_CODEEMITTER_H
18 
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/MC/MCAsmBackend.h"
23 #include "llvm/MC/MCCodeEmitter.h"
24 #include "llvm/MC/MCInst.h"
25 #include "llvm/MC/MCSubtargetInfo.h"
26 
27 namespace llvm {
28 namespace mca {
29 
30 /// A utility class used to compute instruction encodings for a code region.
31 ///
32 /// It provides a simple API to compute and return instruction encodings as
33 /// strings. Encodings are cached internally for later usage.
34 class CodeEmitter {
35   const MCSubtargetInfo &STI;
36   const MCAsmBackend &MAB;
37   const MCCodeEmitter &MCE;
38 
39   SmallString<256> Code;
40   ArrayRef<MCInst> Sequence;
41 
42   // An EncodingInfo pair stores <base, length> information.  Base (i.e. first)
43   // is an index to the `Code`. Length (i.e. second) is the encoding size.
44   using EncodingInfo = std::pair<unsigned, unsigned>;
45 
46   // A cache of encodings.
47   SmallVector<EncodingInfo, 16> Encodings;
48 
49   EncodingInfo getOrCreateEncodingInfo(unsigned MCID);
50 
51 public:
52   CodeEmitter(const MCSubtargetInfo &ST, const MCAsmBackend &AB,
53               const MCCodeEmitter &CE, ArrayRef<MCInst> S)
54       : STI(ST), MAB(AB), MCE(CE), Sequence(S), Encodings(S.size()) {}
55 
56   StringRef getEncoding(unsigned MCID) {
57     EncodingInfo EI = getOrCreateEncodingInfo(MCID);
58     return StringRef(&Code[EI.first], EI.second);
59   }
60 };
61 
62 } // namespace mca
63 } // namespace llvm
64 
65 #endif // LLVM_MCA_CODEEMITTER_H
66