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