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