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