SnippetFile.cpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. //===-- SnippetFile.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. #include "SnippetFile.h"
  9. #include "Error.h"
  10. #include "llvm/MC/MCContext.h"
  11. #include "llvm/MC/MCInstPrinter.h"
  12. #include "llvm/MC/MCObjectFileInfo.h"
  13. #include "llvm/MC/MCParser/MCAsmParser.h"
  14. #include "llvm/MC/MCParser/MCTargetAsmParser.h"
  15. #include "llvm/MC/MCRegisterInfo.h"
  16. #include "llvm/MC/MCStreamer.h"
  17. #include "llvm/MC/TargetRegistry.h"
  18. #include "llvm/Support/Format.h"
  19. #include "llvm/Support/Path.h"
  20. #include "llvm/Support/SourceMgr.h"
  21. #include <string>
  22. namespace llvm {
  23. namespace exegesis {
  24. namespace {
  25. // An MCStreamer that reads a BenchmarkCode definition from a file.
  26. class BenchmarkCodeStreamer : public MCStreamer, public AsmCommentConsumer {
  27. public:
  28. explicit BenchmarkCodeStreamer(MCContext *Context,
  29. const MCRegisterInfo *TheRegInfo,
  30. BenchmarkCode *Result)
  31. : MCStreamer(*Context), RegInfo(TheRegInfo), Result(Result) {}
  32. // Implementation of the MCStreamer interface. We only care about
  33. // instructions.
  34. void emitInstruction(const MCInst &Instruction,
  35. const MCSubtargetInfo &STI) override {
  36. Result->Key.Instructions.push_back(Instruction);
  37. }
  38. // Implementation of the AsmCommentConsumer.
  39. void HandleComment(SMLoc Loc, StringRef CommentText) override {
  40. CommentText = CommentText.trim();
  41. if (!CommentText.consume_front("LLVM-EXEGESIS-"))
  42. return;
  43. if (CommentText.consume_front("DEFREG")) {
  44. // LLVM-EXEGESIS-DEFREF <reg> <hex_value>
  45. RegisterValue RegVal;
  46. SmallVector<StringRef, 2> Parts;
  47. CommentText.split(Parts, ' ', /*unlimited splits*/ -1,
  48. /*do not keep empty strings*/ false);
  49. if (Parts.size() != 2) {
  50. errs() << "invalid comment 'LLVM-EXEGESIS-DEFREG " << CommentText
  51. << "', expected two parameters <REG> <HEX_VALUE>\n";
  52. ++InvalidComments;
  53. return;
  54. }
  55. if (!(RegVal.Register = findRegisterByName(Parts[0].trim()))) {
  56. errs() << "unknown register '" << Parts[0]
  57. << "' in 'LLVM-EXEGESIS-DEFREG " << CommentText << "'\n";
  58. ++InvalidComments;
  59. return;
  60. }
  61. const StringRef HexValue = Parts[1].trim();
  62. RegVal.Value = APInt(
  63. /* each hex digit is 4 bits */ HexValue.size() * 4, HexValue, 16);
  64. Result->Key.RegisterInitialValues.push_back(std::move(RegVal));
  65. return;
  66. }
  67. if (CommentText.consume_front("LIVEIN")) {
  68. // LLVM-EXEGESIS-LIVEIN <reg>
  69. const auto RegName = CommentText.ltrim();
  70. if (unsigned Reg = findRegisterByName(RegName))
  71. Result->LiveIns.push_back(Reg);
  72. else {
  73. errs() << "unknown register '" << RegName
  74. << "' in 'LLVM-EXEGESIS-LIVEIN " << CommentText << "'\n";
  75. ++InvalidComments;
  76. }
  77. return;
  78. }
  79. }
  80. unsigned numInvalidComments() const { return InvalidComments; }
  81. private:
  82. // We only care about instructions, we don't implement this part of the API.
  83. void emitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
  84. unsigned ByteAlignment) override {}
  85. bool emitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override {
  86. return false;
  87. }
  88. void emitValueToAlignment(unsigned ByteAlignment, int64_t Value,
  89. unsigned ValueSize,
  90. unsigned MaxBytesToEmit) override {}
  91. void emitZerofill(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
  92. unsigned ByteAlignment, SMLoc Loc) override {}
  93. unsigned findRegisterByName(const StringRef RegName) const {
  94. // FIXME: Can we do better than this ?
  95. for (unsigned I = 0, E = RegInfo->getNumRegs(); I < E; ++I) {
  96. if (RegName == RegInfo->getName(I))
  97. return I;
  98. }
  99. errs() << "'" << RegName
  100. << "' is not a valid register name for the target\n";
  101. return 0;
  102. }
  103. const MCRegisterInfo *const RegInfo;
  104. BenchmarkCode *const Result;
  105. unsigned InvalidComments = 0;
  106. };
  107. } // namespace
  108. // Reads code snippets from file `Filename`.
  109. Expected<std::vector<BenchmarkCode>> readSnippets(const LLVMState &State,
  110. StringRef Filename) {
  111. ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
  112. MemoryBuffer::getFileOrSTDIN(Filename);
  113. if (std::error_code EC = BufferPtr.getError()) {
  114. return make_error<Failure>("cannot read snippet: " + Filename + ": " +
  115. EC.message());
  116. }
  117. SourceMgr SM;
  118. SM.AddNewSourceBuffer(std::move(BufferPtr.get()), SMLoc());
  119. BenchmarkCode Result;
  120. const TargetMachine &TM = State.getTargetMachine();
  121. MCContext Context(TM.getTargetTriple(), TM.getMCAsmInfo(),
  122. TM.getMCRegisterInfo(), TM.getMCSubtargetInfo());
  123. std::unique_ptr<MCObjectFileInfo> ObjectFileInfo(
  124. TM.getTarget().createMCObjectFileInfo(Context, /*PIC=*/false));
  125. Context.setObjectFileInfo(ObjectFileInfo.get());
  126. Context.initInlineSourceManager();
  127. BenchmarkCodeStreamer Streamer(&Context, TM.getMCRegisterInfo(), &Result);
  128. std::string Error;
  129. raw_string_ostream ErrorStream(Error);
  130. formatted_raw_ostream InstPrinterOStream(ErrorStream);
  131. const std::unique_ptr<MCInstPrinter> InstPrinter(
  132. TM.getTarget().createMCInstPrinter(
  133. TM.getTargetTriple(), TM.getMCAsmInfo()->getAssemblerDialect(),
  134. *TM.getMCAsmInfo(), *TM.getMCInstrInfo(), *TM.getMCRegisterInfo()));
  135. // The following call will take care of calling Streamer.setTargetStreamer.
  136. TM.getTarget().createAsmTargetStreamer(Streamer, InstPrinterOStream,
  137. InstPrinter.get(),
  138. TM.Options.MCOptions.AsmVerbose);
  139. if (!Streamer.getTargetStreamer())
  140. return make_error<Failure>("cannot create target asm streamer");
  141. const std::unique_ptr<MCAsmParser> AsmParser(
  142. createMCAsmParser(SM, Context, Streamer, *TM.getMCAsmInfo()));
  143. if (!AsmParser)
  144. return make_error<Failure>("cannot create asm parser");
  145. AsmParser->getLexer().setCommentConsumer(&Streamer);
  146. const std::unique_ptr<MCTargetAsmParser> TargetAsmParser(
  147. TM.getTarget().createMCAsmParser(*TM.getMCSubtargetInfo(), *AsmParser,
  148. *TM.getMCInstrInfo(),
  149. MCTargetOptions()));
  150. if (!TargetAsmParser)
  151. return make_error<Failure>("cannot create target asm parser");
  152. AsmParser->setTargetParser(*TargetAsmParser);
  153. if (AsmParser->Run(false))
  154. return make_error<Failure>("cannot parse asm file");
  155. if (Streamer.numInvalidComments())
  156. return make_error<Failure>(Twine("found ")
  157. .concat(Twine(Streamer.numInvalidComments()))
  158. .concat(" invalid LLVM-EXEGESIS comments"));
  159. return std::vector<BenchmarkCode>{std::move(Result)};
  160. }
  161. } // namespace exegesis
  162. } // namespace llvm