Target.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  1. //===-- Target.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 "../Target.h"
  9. #include "../Error.h"
  10. #include "../ParallelSnippetGenerator.h"
  11. #include "../SerialSnippetGenerator.h"
  12. #include "../SnippetGenerator.h"
  13. #include "MCTargetDesc/X86BaseInfo.h"
  14. #include "MCTargetDesc/X86MCTargetDesc.h"
  15. #include "X86.h"
  16. #include "X86Counter.h"
  17. #include "X86RegisterInfo.h"
  18. #include "X86Subtarget.h"
  19. #include "llvm/ADT/Sequence.h"
  20. #include "llvm/MC/MCInstBuilder.h"
  21. #include "llvm/Support/Errc.h"
  22. #include "llvm/Support/Error.h"
  23. #include "llvm/Support/FormatVariadic.h"
  24. #include "llvm/Support/Host.h"
  25. #include <memory>
  26. #include <string>
  27. #include <vector>
  28. #if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))
  29. #include <immintrin.h>
  30. #include <intrin.h>
  31. #endif
  32. namespace llvm {
  33. namespace exegesis {
  34. static cl::OptionCategory
  35. BenchmarkOptions("llvm-exegesis benchmark x86-options");
  36. // If a positive value is specified, we are going to use the LBR in
  37. // latency-mode.
  38. //
  39. // Note:
  40. // - A small value is preferred, but too low a value could result in
  41. // throttling.
  42. // - A prime number is preferred to avoid always skipping certain blocks.
  43. //
  44. static cl::opt<unsigned> LbrSamplingPeriod(
  45. "x86-lbr-sample-period",
  46. cl::desc("The sample period (nbranches/sample), used for LBR sampling"),
  47. cl::cat(BenchmarkOptions), cl::init(0));
  48. // FIXME: Validates that repetition-mode is loop if LBR is requested.
  49. // Returns a non-null reason if we cannot handle the memory references in this
  50. // instruction.
  51. static const char *isInvalidMemoryInstr(const Instruction &Instr) {
  52. switch (Instr.Description.TSFlags & X86II::FormMask) {
  53. default:
  54. return "Unknown FormMask value";
  55. // These have no memory access.
  56. case X86II::Pseudo:
  57. case X86II::RawFrm:
  58. case X86II::AddCCFrm:
  59. case X86II::PrefixByte:
  60. case X86II::MRMDestReg:
  61. case X86II::MRMSrcReg:
  62. case X86II::MRMSrcReg4VOp3:
  63. case X86II::MRMSrcRegOp4:
  64. case X86II::MRMSrcRegCC:
  65. case X86II::MRMXrCC:
  66. case X86II::MRMr0:
  67. case X86II::MRMXr:
  68. case X86II::MRM0r:
  69. case X86II::MRM1r:
  70. case X86II::MRM2r:
  71. case X86II::MRM3r:
  72. case X86II::MRM4r:
  73. case X86II::MRM5r:
  74. case X86II::MRM6r:
  75. case X86II::MRM7r:
  76. case X86II::MRM0X:
  77. case X86II::MRM1X:
  78. case X86II::MRM2X:
  79. case X86II::MRM3X:
  80. case X86II::MRM4X:
  81. case X86II::MRM5X:
  82. case X86II::MRM6X:
  83. case X86II::MRM7X:
  84. case X86II::MRM_C0:
  85. case X86II::MRM_C1:
  86. case X86II::MRM_C2:
  87. case X86II::MRM_C3:
  88. case X86II::MRM_C4:
  89. case X86II::MRM_C5:
  90. case X86II::MRM_C6:
  91. case X86II::MRM_C7:
  92. case X86II::MRM_C8:
  93. case X86II::MRM_C9:
  94. case X86II::MRM_CA:
  95. case X86II::MRM_CB:
  96. case X86II::MRM_CC:
  97. case X86II::MRM_CD:
  98. case X86II::MRM_CE:
  99. case X86II::MRM_CF:
  100. case X86II::MRM_D0:
  101. case X86II::MRM_D1:
  102. case X86II::MRM_D2:
  103. case X86II::MRM_D3:
  104. case X86II::MRM_D4:
  105. case X86II::MRM_D5:
  106. case X86II::MRM_D6:
  107. case X86II::MRM_D7:
  108. case X86II::MRM_D8:
  109. case X86II::MRM_D9:
  110. case X86II::MRM_DA:
  111. case X86II::MRM_DB:
  112. case X86II::MRM_DC:
  113. case X86II::MRM_DD:
  114. case X86II::MRM_DE:
  115. case X86II::MRM_DF:
  116. case X86II::MRM_E0:
  117. case X86II::MRM_E1:
  118. case X86II::MRM_E2:
  119. case X86II::MRM_E3:
  120. case X86II::MRM_E4:
  121. case X86II::MRM_E5:
  122. case X86II::MRM_E6:
  123. case X86II::MRM_E7:
  124. case X86II::MRM_E8:
  125. case X86II::MRM_E9:
  126. case X86II::MRM_EA:
  127. case X86II::MRM_EB:
  128. case X86II::MRM_EC:
  129. case X86II::MRM_ED:
  130. case X86II::MRM_EE:
  131. case X86II::MRM_EF:
  132. case X86II::MRM_F0:
  133. case X86II::MRM_F1:
  134. case X86II::MRM_F2:
  135. case X86II::MRM_F3:
  136. case X86II::MRM_F4:
  137. case X86II::MRM_F5:
  138. case X86II::MRM_F6:
  139. case X86II::MRM_F7:
  140. case X86II::MRM_F8:
  141. case X86II::MRM_F9:
  142. case X86II::MRM_FA:
  143. case X86II::MRM_FB:
  144. case X86II::MRM_FC:
  145. case X86II::MRM_FD:
  146. case X86II::MRM_FE:
  147. case X86II::MRM_FF:
  148. case X86II::RawFrmImm8:
  149. return nullptr;
  150. case X86II::AddRegFrm:
  151. return (Instr.Description.Opcode == X86::POP16r ||
  152. Instr.Description.Opcode == X86::POP32r ||
  153. Instr.Description.Opcode == X86::PUSH16r ||
  154. Instr.Description.Opcode == X86::PUSH32r)
  155. ? "unsupported opcode: unsupported memory access"
  156. : nullptr;
  157. // These access memory and are handled.
  158. case X86II::MRMDestMem:
  159. case X86II::MRMSrcMem:
  160. case X86II::MRMSrcMem4VOp3:
  161. case X86II::MRMSrcMemOp4:
  162. case X86II::MRMSrcMemCC:
  163. case X86II::MRMXmCC:
  164. case X86II::MRMXm:
  165. case X86II::MRM0m:
  166. case X86II::MRM1m:
  167. case X86II::MRM2m:
  168. case X86II::MRM3m:
  169. case X86II::MRM4m:
  170. case X86II::MRM5m:
  171. case X86II::MRM6m:
  172. case X86II::MRM7m:
  173. return nullptr;
  174. // These access memory and are not handled yet.
  175. case X86II::RawFrmImm16:
  176. case X86II::RawFrmMemOffs:
  177. case X86II::RawFrmSrc:
  178. case X86II::RawFrmDst:
  179. case X86II::RawFrmDstSrc:
  180. return "unsupported opcode: non uniform memory access";
  181. }
  182. }
  183. // If the opcode is invalid, returns a pointer to a character literal indicating
  184. // the reason. nullptr indicates a valid opcode.
  185. static const char *isInvalidOpcode(const Instruction &Instr) {
  186. const auto OpcodeName = Instr.Name;
  187. if ((Instr.Description.TSFlags & X86II::FormMask) == X86II::Pseudo)
  188. return "unsupported opcode: pseudo instruction";
  189. if (OpcodeName.startswith("POP") || OpcodeName.startswith("PUSH") ||
  190. OpcodeName.startswith("ADJCALLSTACK") || OpcodeName.startswith("LEAVE"))
  191. return "unsupported opcode: Push/Pop/AdjCallStack/Leave";
  192. if (const auto reason = isInvalidMemoryInstr(Instr))
  193. return reason;
  194. // We do not handle instructions with OPERAND_PCREL.
  195. for (const Operand &Op : Instr.Operands)
  196. if (Op.isExplicit() &&
  197. Op.getExplicitOperandInfo().OperandType == MCOI::OPERAND_PCREL)
  198. return "unsupported opcode: PC relative operand";
  199. // We do not handle second-form X87 instructions. We only handle first-form
  200. // ones (_Fp), see comment in X86InstrFPStack.td.
  201. for (const Operand &Op : Instr.Operands)
  202. if (Op.isReg() && Op.isExplicit() &&
  203. Op.getExplicitOperandInfo().RegClass == X86::RSTRegClassID)
  204. return "unsupported second-form X87 instruction";
  205. return nullptr;
  206. }
  207. static unsigned getX86FPFlags(const Instruction &Instr) {
  208. return Instr.Description.TSFlags & X86II::FPTypeMask;
  209. }
  210. // Helper to fill a memory operand with a value.
  211. static void setMemOp(InstructionTemplate &IT, int OpIdx,
  212. const MCOperand &OpVal) {
  213. const auto Op = IT.getInstr().Operands[OpIdx];
  214. assert(Op.isExplicit() && "invalid memory pattern");
  215. IT.getValueFor(Op) = OpVal;
  216. }
  217. // Common (latency, uops) code for LEA templates. `GetDestReg` takes the
  218. // addressing base and index registers and returns the LEA destination register.
  219. static Expected<std::vector<CodeTemplate>> generateLEATemplatesCommon(
  220. const Instruction &Instr, const BitVector &ForbiddenRegisters,
  221. const LLVMState &State, const SnippetGenerator::Options &Opts,
  222. std::function<void(unsigned, unsigned, BitVector &CandidateDestRegs)>
  223. RestrictDestRegs) {
  224. assert(Instr.Operands.size() == 6 && "invalid LEA");
  225. assert(X86II::getMemoryOperandNo(Instr.Description.TSFlags) == 1 &&
  226. "invalid LEA");
  227. constexpr const int kDestOp = 0;
  228. constexpr const int kBaseOp = 1;
  229. constexpr const int kIndexOp = 3;
  230. auto PossibleDestRegs =
  231. Instr.Operands[kDestOp].getRegisterAliasing().sourceBits();
  232. remove(PossibleDestRegs, ForbiddenRegisters);
  233. auto PossibleBaseRegs =
  234. Instr.Operands[kBaseOp].getRegisterAliasing().sourceBits();
  235. remove(PossibleBaseRegs, ForbiddenRegisters);
  236. auto PossibleIndexRegs =
  237. Instr.Operands[kIndexOp].getRegisterAliasing().sourceBits();
  238. remove(PossibleIndexRegs, ForbiddenRegisters);
  239. const auto &RegInfo = State.getRegInfo();
  240. std::vector<CodeTemplate> Result;
  241. for (const unsigned BaseReg : PossibleBaseRegs.set_bits()) {
  242. for (const unsigned IndexReg : PossibleIndexRegs.set_bits()) {
  243. for (int LogScale = 0; LogScale <= 3; ++LogScale) {
  244. // FIXME: Add an option for controlling how we explore immediates.
  245. for (const int Disp : {0, 42}) {
  246. InstructionTemplate IT(&Instr);
  247. const int64_t Scale = 1ull << LogScale;
  248. setMemOp(IT, 1, MCOperand::createReg(BaseReg));
  249. setMemOp(IT, 2, MCOperand::createImm(Scale));
  250. setMemOp(IT, 3, MCOperand::createReg(IndexReg));
  251. setMemOp(IT, 4, MCOperand::createImm(Disp));
  252. // SegmentReg must be 0 for LEA.
  253. setMemOp(IT, 5, MCOperand::createReg(0));
  254. // Output reg candidates are selected by the caller.
  255. auto PossibleDestRegsNow = PossibleDestRegs;
  256. RestrictDestRegs(BaseReg, IndexReg, PossibleDestRegsNow);
  257. assert(PossibleDestRegsNow.set_bits().begin() !=
  258. PossibleDestRegsNow.set_bits().end() &&
  259. "no remaining registers");
  260. setMemOp(
  261. IT, 0,
  262. MCOperand::createReg(*PossibleDestRegsNow.set_bits().begin()));
  263. CodeTemplate CT;
  264. CT.Instructions.push_back(std::move(IT));
  265. CT.Config = formatv("{3}(%{0}, %{1}, {2})", RegInfo.getName(BaseReg),
  266. RegInfo.getName(IndexReg), Scale, Disp)
  267. .str();
  268. Result.push_back(std::move(CT));
  269. if (Result.size() >= Opts.MaxConfigsPerOpcode)
  270. return std::move(Result);
  271. }
  272. }
  273. }
  274. }
  275. return std::move(Result);
  276. }
  277. namespace {
  278. class X86SerialSnippetGenerator : public SerialSnippetGenerator {
  279. public:
  280. using SerialSnippetGenerator::SerialSnippetGenerator;
  281. Expected<std::vector<CodeTemplate>>
  282. generateCodeTemplates(InstructionTemplate Variant,
  283. const BitVector &ForbiddenRegisters) const override;
  284. };
  285. } // namespace
  286. Expected<std::vector<CodeTemplate>>
  287. X86SerialSnippetGenerator::generateCodeTemplates(
  288. InstructionTemplate Variant, const BitVector &ForbiddenRegisters) const {
  289. const Instruction &Instr = Variant.getInstr();
  290. if (const auto reason = isInvalidOpcode(Instr))
  291. return make_error<Failure>(reason);
  292. // LEA gets special attention.
  293. const auto Opcode = Instr.Description.getOpcode();
  294. if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r) {
  295. return generateLEATemplatesCommon(
  296. Instr, ForbiddenRegisters, State, Opts,
  297. [this](unsigned BaseReg, unsigned IndexReg,
  298. BitVector &CandidateDestRegs) {
  299. // We just select a destination register that aliases the base
  300. // register.
  301. CandidateDestRegs &=
  302. State.getRATC().getRegister(BaseReg).aliasedBits();
  303. });
  304. }
  305. if (Instr.hasMemoryOperands())
  306. return make_error<Failure>(
  307. "unsupported memory operand in latency measurements");
  308. switch (getX86FPFlags(Instr)) {
  309. case X86II::NotFP:
  310. return SerialSnippetGenerator::generateCodeTemplates(Variant,
  311. ForbiddenRegisters);
  312. case X86II::ZeroArgFP:
  313. case X86II::OneArgFP:
  314. case X86II::SpecialFP:
  315. case X86II::CompareFP:
  316. case X86II::CondMovFP:
  317. return make_error<Failure>("Unsupported x87 Instruction");
  318. case X86II::OneArgFPRW:
  319. case X86II::TwoArgFP:
  320. // These are instructions like
  321. // - `ST(0) = fsqrt(ST(0))` (OneArgFPRW)
  322. // - `ST(0) = ST(0) + ST(i)` (TwoArgFP)
  323. // They are intrinsically serial and do not modify the state of the stack.
  324. return generateSelfAliasingCodeTemplates(Variant);
  325. default:
  326. llvm_unreachable("Unknown FP Type!");
  327. }
  328. }
  329. namespace {
  330. class X86ParallelSnippetGenerator : public ParallelSnippetGenerator {
  331. public:
  332. using ParallelSnippetGenerator::ParallelSnippetGenerator;
  333. Expected<std::vector<CodeTemplate>>
  334. generateCodeTemplates(InstructionTemplate Variant,
  335. const BitVector &ForbiddenRegisters) const override;
  336. };
  337. } // namespace
  338. Expected<std::vector<CodeTemplate>>
  339. X86ParallelSnippetGenerator::generateCodeTemplates(
  340. InstructionTemplate Variant, const BitVector &ForbiddenRegisters) const {
  341. const Instruction &Instr = Variant.getInstr();
  342. if (const auto reason = isInvalidOpcode(Instr))
  343. return make_error<Failure>(reason);
  344. // LEA gets special attention.
  345. const auto Opcode = Instr.Description.getOpcode();
  346. if (Opcode == X86::LEA64r || Opcode == X86::LEA64_32r) {
  347. return generateLEATemplatesCommon(
  348. Instr, ForbiddenRegisters, State, Opts,
  349. [this](unsigned BaseReg, unsigned IndexReg,
  350. BitVector &CandidateDestRegs) {
  351. // Any destination register that is not used for addressing is fine.
  352. remove(CandidateDestRegs,
  353. State.getRATC().getRegister(BaseReg).aliasedBits());
  354. remove(CandidateDestRegs,
  355. State.getRATC().getRegister(IndexReg).aliasedBits());
  356. });
  357. }
  358. switch (getX86FPFlags(Instr)) {
  359. case X86II::NotFP:
  360. return ParallelSnippetGenerator::generateCodeTemplates(Variant,
  361. ForbiddenRegisters);
  362. case X86II::ZeroArgFP:
  363. case X86II::OneArgFP:
  364. case X86II::SpecialFP:
  365. return make_error<Failure>("Unsupported x87 Instruction");
  366. case X86II::OneArgFPRW:
  367. case X86II::TwoArgFP:
  368. // These are instructions like
  369. // - `ST(0) = fsqrt(ST(0))` (OneArgFPRW)
  370. // - `ST(0) = ST(0) + ST(i)` (TwoArgFP)
  371. // They are intrinsically serial and do not modify the state of the stack.
  372. // We generate the same code for latency and uops.
  373. return generateSelfAliasingCodeTemplates(Variant);
  374. case X86II::CompareFP:
  375. case X86II::CondMovFP:
  376. // We can compute uops for any FP instruction that does not grow or shrink
  377. // the stack (either do not touch the stack or push as much as they pop).
  378. return generateUnconstrainedCodeTemplates(
  379. Variant, "instruction does not grow/shrink the FP stack");
  380. default:
  381. llvm_unreachable("Unknown FP Type!");
  382. }
  383. }
  384. static unsigned getLoadImmediateOpcode(unsigned RegBitWidth) {
  385. switch (RegBitWidth) {
  386. case 8:
  387. return X86::MOV8ri;
  388. case 16:
  389. return X86::MOV16ri;
  390. case 32:
  391. return X86::MOV32ri;
  392. case 64:
  393. return X86::MOV64ri;
  394. }
  395. llvm_unreachable("Invalid Value Width");
  396. }
  397. // Generates instruction to load an immediate value into a register.
  398. static MCInst loadImmediate(unsigned Reg, unsigned RegBitWidth,
  399. const APInt &Value) {
  400. if (Value.getBitWidth() > RegBitWidth)
  401. llvm_unreachable("Value must fit in the Register");
  402. return MCInstBuilder(getLoadImmediateOpcode(RegBitWidth))
  403. .addReg(Reg)
  404. .addImm(Value.getZExtValue());
  405. }
  406. // Allocates scratch memory on the stack.
  407. static MCInst allocateStackSpace(unsigned Bytes) {
  408. return MCInstBuilder(X86::SUB64ri8)
  409. .addReg(X86::RSP)
  410. .addReg(X86::RSP)
  411. .addImm(Bytes);
  412. }
  413. // Fills scratch memory at offset `OffsetBytes` with value `Imm`.
  414. static MCInst fillStackSpace(unsigned MovOpcode, unsigned OffsetBytes,
  415. uint64_t Imm) {
  416. return MCInstBuilder(MovOpcode)
  417. // Address = ESP
  418. .addReg(X86::RSP) // BaseReg
  419. .addImm(1) // ScaleAmt
  420. .addReg(0) // IndexReg
  421. .addImm(OffsetBytes) // Disp
  422. .addReg(0) // Segment
  423. // Immediate.
  424. .addImm(Imm);
  425. }
  426. // Loads scratch memory into register `Reg` using opcode `RMOpcode`.
  427. static MCInst loadToReg(unsigned Reg, unsigned RMOpcode) {
  428. return MCInstBuilder(RMOpcode)
  429. .addReg(Reg)
  430. // Address = ESP
  431. .addReg(X86::RSP) // BaseReg
  432. .addImm(1) // ScaleAmt
  433. .addReg(0) // IndexReg
  434. .addImm(0) // Disp
  435. .addReg(0); // Segment
  436. }
  437. // Releases scratch memory.
  438. static MCInst releaseStackSpace(unsigned Bytes) {
  439. return MCInstBuilder(X86::ADD64ri8)
  440. .addReg(X86::RSP)
  441. .addReg(X86::RSP)
  442. .addImm(Bytes);
  443. }
  444. // Reserves some space on the stack, fills it with the content of the provided
  445. // constant and provide methods to load the stack value into a register.
  446. namespace {
  447. struct ConstantInliner {
  448. explicit ConstantInliner(const APInt &Constant) : Constant_(Constant) {}
  449. std::vector<MCInst> loadAndFinalize(unsigned Reg, unsigned RegBitWidth,
  450. unsigned Opcode);
  451. std::vector<MCInst> loadX87STAndFinalize(unsigned Reg);
  452. std::vector<MCInst> loadX87FPAndFinalize(unsigned Reg);
  453. std::vector<MCInst> popFlagAndFinalize();
  454. std::vector<MCInst> loadImplicitRegAndFinalize(unsigned Opcode,
  455. unsigned Value);
  456. private:
  457. ConstantInliner &add(const MCInst &Inst) {
  458. Instructions.push_back(Inst);
  459. return *this;
  460. }
  461. void initStack(unsigned Bytes);
  462. static constexpr const unsigned kF80Bytes = 10; // 80 bits.
  463. APInt Constant_;
  464. std::vector<MCInst> Instructions;
  465. };
  466. } // namespace
  467. std::vector<MCInst> ConstantInliner::loadAndFinalize(unsigned Reg,
  468. unsigned RegBitWidth,
  469. unsigned Opcode) {
  470. assert((RegBitWidth & 7) == 0 && "RegBitWidth must be a multiple of 8 bits");
  471. initStack(RegBitWidth / 8);
  472. add(loadToReg(Reg, Opcode));
  473. add(releaseStackSpace(RegBitWidth / 8));
  474. return std::move(Instructions);
  475. }
  476. std::vector<MCInst> ConstantInliner::loadX87STAndFinalize(unsigned Reg) {
  477. initStack(kF80Bytes);
  478. add(MCInstBuilder(X86::LD_F80m)
  479. // Address = ESP
  480. .addReg(X86::RSP) // BaseReg
  481. .addImm(1) // ScaleAmt
  482. .addReg(0) // IndexReg
  483. .addImm(0) // Disp
  484. .addReg(0)); // Segment
  485. if (Reg != X86::ST0)
  486. add(MCInstBuilder(X86::ST_Frr).addReg(Reg));
  487. add(releaseStackSpace(kF80Bytes));
  488. return std::move(Instructions);
  489. }
  490. std::vector<MCInst> ConstantInliner::loadX87FPAndFinalize(unsigned Reg) {
  491. initStack(kF80Bytes);
  492. add(MCInstBuilder(X86::LD_Fp80m)
  493. .addReg(Reg)
  494. // Address = ESP
  495. .addReg(X86::RSP) // BaseReg
  496. .addImm(1) // ScaleAmt
  497. .addReg(0) // IndexReg
  498. .addImm(0) // Disp
  499. .addReg(0)); // Segment
  500. add(releaseStackSpace(kF80Bytes));
  501. return std::move(Instructions);
  502. }
  503. std::vector<MCInst> ConstantInliner::popFlagAndFinalize() {
  504. initStack(8);
  505. add(MCInstBuilder(X86::POPF64));
  506. return std::move(Instructions);
  507. }
  508. std::vector<MCInst>
  509. ConstantInliner::loadImplicitRegAndFinalize(unsigned Opcode, unsigned Value) {
  510. add(allocateStackSpace(4));
  511. add(fillStackSpace(X86::MOV32mi, 0, Value)); // Mask all FP exceptions
  512. add(MCInstBuilder(Opcode)
  513. // Address = ESP
  514. .addReg(X86::RSP) // BaseReg
  515. .addImm(1) // ScaleAmt
  516. .addReg(0) // IndexReg
  517. .addImm(0) // Disp
  518. .addReg(0)); // Segment
  519. add(releaseStackSpace(4));
  520. return std::move(Instructions);
  521. }
  522. void ConstantInliner::initStack(unsigned Bytes) {
  523. assert(Constant_.getBitWidth() <= Bytes * 8 &&
  524. "Value does not have the correct size");
  525. const APInt WideConstant = Constant_.getBitWidth() < Bytes * 8
  526. ? Constant_.sext(Bytes * 8)
  527. : Constant_;
  528. add(allocateStackSpace(Bytes));
  529. size_t ByteOffset = 0;
  530. for (; Bytes - ByteOffset >= 4; ByteOffset += 4)
  531. add(fillStackSpace(
  532. X86::MOV32mi, ByteOffset,
  533. WideConstant.extractBits(32, ByteOffset * 8).getZExtValue()));
  534. if (Bytes - ByteOffset >= 2) {
  535. add(fillStackSpace(
  536. X86::MOV16mi, ByteOffset,
  537. WideConstant.extractBits(16, ByteOffset * 8).getZExtValue()));
  538. ByteOffset += 2;
  539. }
  540. if (Bytes - ByteOffset >= 1)
  541. add(fillStackSpace(
  542. X86::MOV8mi, ByteOffset,
  543. WideConstant.extractBits(8, ByteOffset * 8).getZExtValue()));
  544. }
  545. #include "X86GenExegesis.inc"
  546. namespace {
  547. class X86SavedState : public ExegesisTarget::SavedState {
  548. public:
  549. X86SavedState() {
  550. #ifdef __x86_64__
  551. # if defined(_MSC_VER)
  552. _fxsave64(FPState);
  553. Eflags = __readeflags();
  554. # elif defined(__GNUC__)
  555. __builtin_ia32_fxsave64(FPState);
  556. Eflags = __builtin_ia32_readeflags_u64();
  557. # endif
  558. #else
  559. llvm_unreachable("X86 exegesis running on non-X86 target");
  560. #endif
  561. }
  562. ~X86SavedState() {
  563. // Restoring the X87 state does not flush pending exceptions, make sure
  564. // these exceptions are flushed now.
  565. #ifdef __x86_64__
  566. # if defined(_MSC_VER)
  567. _clearfp();
  568. _fxrstor64(FPState);
  569. __writeeflags(Eflags);
  570. # elif defined(__GNUC__)
  571. asm volatile("fwait");
  572. __builtin_ia32_fxrstor64(FPState);
  573. __builtin_ia32_writeeflags_u64(Eflags);
  574. # endif
  575. #else
  576. llvm_unreachable("X86 exegesis running on non-X86 target");
  577. #endif
  578. }
  579. private:
  580. #ifdef __x86_64__
  581. alignas(16) char FPState[512];
  582. uint64_t Eflags;
  583. #endif
  584. };
  585. class ExegesisX86Target : public ExegesisTarget {
  586. public:
  587. ExegesisX86Target() : ExegesisTarget(X86CpuPfmCounters) {}
  588. Expected<std::unique_ptr<pfm::Counter>>
  589. createCounter(StringRef CounterName, const LLVMState &State) const override {
  590. // If LbrSamplingPeriod was provided, then ignore the
  591. // CounterName because we only have one for LBR.
  592. if (LbrSamplingPeriod > 0) {
  593. // Can't use LBR without HAVE_LIBPFM, LIBPFM_HAS_FIELD_CYCLES, or without
  594. // __linux__ (for now)
  595. #if defined(HAVE_LIBPFM) && defined(LIBPFM_HAS_FIELD_CYCLES) && \
  596. defined(__linux__)
  597. return std::make_unique<X86LbrCounter>(
  598. X86LbrPerfEvent(LbrSamplingPeriod));
  599. #else
  600. return llvm::make_error<llvm::StringError>(
  601. "LBR counter requested without HAVE_LIBPFM, LIBPFM_HAS_FIELD_CYCLES, "
  602. "or running on Linux.",
  603. llvm::errc::invalid_argument);
  604. #endif
  605. }
  606. return ExegesisTarget::createCounter(CounterName, State);
  607. }
  608. private:
  609. void addTargetSpecificPasses(PassManagerBase &PM) const override;
  610. unsigned getScratchMemoryRegister(const Triple &TT) const override;
  611. unsigned getLoopCounterRegister(const Triple &) const override;
  612. unsigned getMaxMemoryAccessSize() const override { return 64; }
  613. Error randomizeTargetMCOperand(const Instruction &Instr, const Variable &Var,
  614. MCOperand &AssignedValue,
  615. const BitVector &ForbiddenRegs) const override;
  616. void fillMemoryOperands(InstructionTemplate &IT, unsigned Reg,
  617. unsigned Offset) const override;
  618. void decrementLoopCounterAndJump(MachineBasicBlock &MBB,
  619. MachineBasicBlock &TargetMBB,
  620. const MCInstrInfo &MII) const override;
  621. std::vector<MCInst> setRegTo(const MCSubtargetInfo &STI, unsigned Reg,
  622. const APInt &Value) const override;
  623. ArrayRef<unsigned> getUnavailableRegisters() const override {
  624. return makeArrayRef(kUnavailableRegisters,
  625. sizeof(kUnavailableRegisters) /
  626. sizeof(kUnavailableRegisters[0]));
  627. }
  628. bool allowAsBackToBack(const Instruction &Instr) const override {
  629. const unsigned Opcode = Instr.Description.Opcode;
  630. return !isInvalidOpcode(Instr) && Opcode != X86::LEA64r &&
  631. Opcode != X86::LEA64_32r && Opcode != X86::LEA16r;
  632. }
  633. std::vector<InstructionTemplate>
  634. generateInstructionVariants(const Instruction &Instr,
  635. unsigned MaxConfigsPerOpcode) const override;
  636. std::unique_ptr<SnippetGenerator> createSerialSnippetGenerator(
  637. const LLVMState &State,
  638. const SnippetGenerator::Options &Opts) const override {
  639. return std::make_unique<X86SerialSnippetGenerator>(State, Opts);
  640. }
  641. std::unique_ptr<SnippetGenerator> createParallelSnippetGenerator(
  642. const LLVMState &State,
  643. const SnippetGenerator::Options &Opts) const override {
  644. return std::make_unique<X86ParallelSnippetGenerator>(State, Opts);
  645. }
  646. bool matchesArch(Triple::ArchType Arch) const override {
  647. return Arch == Triple::x86_64 || Arch == Triple::x86;
  648. }
  649. Error checkFeatureSupport() const override {
  650. // LBR is the only feature we conditionally support now.
  651. // So if LBR is not requested, then we should be able to run the benchmarks.
  652. if (LbrSamplingPeriod == 0)
  653. return Error::success();
  654. #if defined(__linux__) && defined(HAVE_LIBPFM) && \
  655. defined(LIBPFM_HAS_FIELD_CYCLES)
  656. // FIXME: Fix this.
  657. // https://bugs.llvm.org/show_bug.cgi?id=48918
  658. // For now, only do the check if we see an Intel machine because
  659. // the counter uses some intel-specific magic and it could
  660. // be confuse and think an AMD machine actually has LBR support.
  661. #if defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || \
  662. defined(_M_X64)
  663. using namespace sys::detail::x86;
  664. if (getVendorSignature() == VendorSignatures::GENUINE_INTEL)
  665. // If the kernel supports it, the hardware still may not have it.
  666. return X86LbrCounter::checkLbrSupport();
  667. #else
  668. llvm_unreachable("Running X86 exegesis on non-X86 target");
  669. #endif
  670. #endif
  671. return llvm::make_error<llvm::StringError>(
  672. "LBR not supported on this kernel and/or platform",
  673. llvm::errc::not_supported);
  674. }
  675. std::unique_ptr<SavedState> withSavedState() const override {
  676. return std::make_unique<X86SavedState>();
  677. }
  678. static const unsigned kUnavailableRegisters[4];
  679. };
  680. // We disable a few registers that cannot be encoded on instructions with a REX
  681. // prefix.
  682. const unsigned ExegesisX86Target::kUnavailableRegisters[4] = {X86::AH, X86::BH,
  683. X86::CH, X86::DH};
  684. // We're using one of R8-R15 because these registers are never hardcoded in
  685. // instructions (e.g. MOVS writes to EDI, ESI, EDX), so they have less
  686. // conflicts.
  687. constexpr const unsigned kLoopCounterReg = X86::R8;
  688. } // namespace
  689. void ExegesisX86Target::addTargetSpecificPasses(PassManagerBase &PM) const {
  690. // Lowers FP pseudo-instructions, e.g. ABS_Fp32 -> ABS_F.
  691. PM.add(createX86FloatingPointStackifierPass());
  692. }
  693. unsigned ExegesisX86Target::getScratchMemoryRegister(const Triple &TT) const {
  694. if (!TT.isArch64Bit()) {
  695. // FIXME: This would require popping from the stack, so we would have to
  696. // add some additional setup code.
  697. return 0;
  698. }
  699. return TT.isOSWindows() ? X86::RCX : X86::RDI;
  700. }
  701. unsigned ExegesisX86Target::getLoopCounterRegister(const Triple &TT) const {
  702. if (!TT.isArch64Bit()) {
  703. return 0;
  704. }
  705. return kLoopCounterReg;
  706. }
  707. Error ExegesisX86Target::randomizeTargetMCOperand(
  708. const Instruction &Instr, const Variable &Var, MCOperand &AssignedValue,
  709. const BitVector &ForbiddenRegs) const {
  710. const Operand &Op = Instr.getPrimaryOperand(Var);
  711. switch (Op.getExplicitOperandInfo().OperandType) {
  712. case X86::OperandType::OPERAND_ROUNDING_CONTROL:
  713. AssignedValue =
  714. MCOperand::createImm(randomIndex(X86::STATIC_ROUNDING::TO_ZERO));
  715. return Error::success();
  716. default:
  717. break;
  718. }
  719. return make_error<Failure>(
  720. Twine("unimplemented operand type ")
  721. .concat(Twine(Op.getExplicitOperandInfo().OperandType)));
  722. }
  723. void ExegesisX86Target::fillMemoryOperands(InstructionTemplate &IT,
  724. unsigned Reg,
  725. unsigned Offset) const {
  726. assert(!isInvalidMemoryInstr(IT.getInstr()) &&
  727. "fillMemoryOperands requires a valid memory instruction");
  728. int MemOpIdx = X86II::getMemoryOperandNo(IT.getInstr().Description.TSFlags);
  729. assert(MemOpIdx >= 0 && "invalid memory operand index");
  730. // getMemoryOperandNo() ignores tied operands, so we have to add them back.
  731. MemOpIdx += X86II::getOperandBias(IT.getInstr().Description);
  732. setMemOp(IT, MemOpIdx + 0, MCOperand::createReg(Reg)); // BaseReg
  733. setMemOp(IT, MemOpIdx + 1, MCOperand::createImm(1)); // ScaleAmt
  734. setMemOp(IT, MemOpIdx + 2, MCOperand::createReg(0)); // IndexReg
  735. setMemOp(IT, MemOpIdx + 3, MCOperand::createImm(Offset)); // Disp
  736. setMemOp(IT, MemOpIdx + 4, MCOperand::createReg(0)); // Segment
  737. }
  738. void ExegesisX86Target::decrementLoopCounterAndJump(
  739. MachineBasicBlock &MBB, MachineBasicBlock &TargetMBB,
  740. const MCInstrInfo &MII) const {
  741. BuildMI(&MBB, DebugLoc(), MII.get(X86::ADD64ri8))
  742. .addDef(kLoopCounterReg)
  743. .addUse(kLoopCounterReg)
  744. .addImm(-1);
  745. BuildMI(&MBB, DebugLoc(), MII.get(X86::JCC_1))
  746. .addMBB(&TargetMBB)
  747. .addImm(X86::COND_NE);
  748. }
  749. std::vector<MCInst> ExegesisX86Target::setRegTo(const MCSubtargetInfo &STI,
  750. unsigned Reg,
  751. const APInt &Value) const {
  752. if (X86::GR8RegClass.contains(Reg))
  753. return {loadImmediate(Reg, 8, Value)};
  754. if (X86::GR16RegClass.contains(Reg))
  755. return {loadImmediate(Reg, 16, Value)};
  756. if (X86::GR32RegClass.contains(Reg))
  757. return {loadImmediate(Reg, 32, Value)};
  758. if (X86::GR64RegClass.contains(Reg))
  759. return {loadImmediate(Reg, 64, Value)};
  760. ConstantInliner CI(Value);
  761. if (X86::VR64RegClass.contains(Reg))
  762. return CI.loadAndFinalize(Reg, 64, X86::MMX_MOVQ64rm);
  763. if (X86::VR128XRegClass.contains(Reg)) {
  764. if (STI.getFeatureBits()[X86::FeatureAVX512])
  765. return CI.loadAndFinalize(Reg, 128, X86::VMOVDQU32Z128rm);
  766. if (STI.getFeatureBits()[X86::FeatureAVX])
  767. return CI.loadAndFinalize(Reg, 128, X86::VMOVDQUrm);
  768. return CI.loadAndFinalize(Reg, 128, X86::MOVDQUrm);
  769. }
  770. if (X86::VR256XRegClass.contains(Reg)) {
  771. if (STI.getFeatureBits()[X86::FeatureAVX512])
  772. return CI.loadAndFinalize(Reg, 256, X86::VMOVDQU32Z256rm);
  773. if (STI.getFeatureBits()[X86::FeatureAVX])
  774. return CI.loadAndFinalize(Reg, 256, X86::VMOVDQUYrm);
  775. }
  776. if (X86::VR512RegClass.contains(Reg))
  777. if (STI.getFeatureBits()[X86::FeatureAVX512])
  778. return CI.loadAndFinalize(Reg, 512, X86::VMOVDQU32Zrm);
  779. if (X86::RSTRegClass.contains(Reg)) {
  780. return CI.loadX87STAndFinalize(Reg);
  781. }
  782. if (X86::RFP32RegClass.contains(Reg) || X86::RFP64RegClass.contains(Reg) ||
  783. X86::RFP80RegClass.contains(Reg)) {
  784. return CI.loadX87FPAndFinalize(Reg);
  785. }
  786. if (Reg == X86::EFLAGS)
  787. return CI.popFlagAndFinalize();
  788. if (Reg == X86::MXCSR)
  789. return CI.loadImplicitRegAndFinalize(
  790. STI.getFeatureBits()[X86::FeatureAVX] ? X86::VLDMXCSR : X86::LDMXCSR,
  791. 0x1f80);
  792. if (Reg == X86::FPCW)
  793. return CI.loadImplicitRegAndFinalize(X86::FLDCW16m, 0x37f);
  794. return {}; // Not yet implemented.
  795. }
  796. // Instruction can have some variable operands, and we may want to see how
  797. // different operands affect performance. So for each operand position,
  798. // precompute all the possible choices we might care about,
  799. // and greedily generate all the possible combinations of choices.
  800. std::vector<InstructionTemplate> ExegesisX86Target::generateInstructionVariants(
  801. const Instruction &Instr, unsigned MaxConfigsPerOpcode) const {
  802. bool Exploration = false;
  803. SmallVector<SmallVector<MCOperand, 1>, 4> VariableChoices;
  804. VariableChoices.resize(Instr.Variables.size());
  805. for (auto I : llvm::zip(Instr.Variables, VariableChoices)) {
  806. const Variable &Var = std::get<0>(I);
  807. SmallVectorImpl<MCOperand> &Choices = std::get<1>(I);
  808. switch (Instr.getPrimaryOperand(Var).getExplicitOperandInfo().OperandType) {
  809. default:
  810. // We don't wish to explicitly explore this variable.
  811. Choices.emplace_back(); // But add invalid MCOperand to simplify logic.
  812. continue;
  813. case X86::OperandType::OPERAND_COND_CODE: {
  814. Exploration = true;
  815. auto CondCodes = seq((int)X86::CondCode::COND_O,
  816. 1 + (int)X86::CondCode::LAST_VALID_COND);
  817. Choices.reserve(std::distance(CondCodes.begin(), CondCodes.end()));
  818. for (int CondCode : CondCodes)
  819. Choices.emplace_back(MCOperand::createImm(CondCode));
  820. break;
  821. }
  822. }
  823. }
  824. // If we don't wish to explore any variables, defer to the baseline method.
  825. if (!Exploration)
  826. return ExegesisTarget::generateInstructionVariants(Instr,
  827. MaxConfigsPerOpcode);
  828. std::vector<InstructionTemplate> Variants;
  829. size_t NumVariants;
  830. CombinationGenerator<MCOperand, decltype(VariableChoices)::value_type, 4> G(
  831. VariableChoices);
  832. // How many operand combinations can we produce, within the limit?
  833. NumVariants = std::min(G.numCombinations(), (size_t)MaxConfigsPerOpcode);
  834. // And actually produce all the wanted operand combinations.
  835. Variants.reserve(NumVariants);
  836. G.generate([&](ArrayRef<MCOperand> State) -> bool {
  837. Variants.emplace_back(&Instr);
  838. Variants.back().setVariableValues(State);
  839. // Did we run out of space for variants?
  840. return Variants.size() >= NumVariants;
  841. });
  842. assert(Variants.size() == NumVariants &&
  843. Variants.size() <= MaxConfigsPerOpcode &&
  844. "Should not produce too many variants");
  845. return Variants;
  846. }
  847. static ExegesisTarget *getTheExegesisX86Target() {
  848. static ExegesisX86Target Target;
  849. return &Target;
  850. }
  851. void InitializeX86ExegesisTarget() {
  852. ExegesisTarget::registerTarget(getTheExegesisX86Target());
  853. }
  854. } // namespace exegesis
  855. } // namespace llvm