StackMaps.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. //===- StackMaps.cpp ------------------------------------------------------===//
  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 "llvm/CodeGen/StackMaps.h"
  9. #include "llvm/ADT/DenseMapInfo.h"
  10. #include "llvm/ADT/STLExtras.h"
  11. #include "llvm/ADT/Twine.h"
  12. #include "llvm/CodeGen/AsmPrinter.h"
  13. #include "llvm/CodeGen/MachineFrameInfo.h"
  14. #include "llvm/CodeGen/MachineFunction.h"
  15. #include "llvm/CodeGen/MachineInstr.h"
  16. #include "llvm/CodeGen/MachineOperand.h"
  17. #include "llvm/CodeGen/TargetOpcodes.h"
  18. #include "llvm/CodeGen/TargetRegisterInfo.h"
  19. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  20. #include "llvm/IR/DataLayout.h"
  21. #include "llvm/MC/MCContext.h"
  22. #include "llvm/MC/MCExpr.h"
  23. #include "llvm/MC/MCObjectFileInfo.h"
  24. #include "llvm/MC/MCRegisterInfo.h"
  25. #include "llvm/MC/MCStreamer.h"
  26. #include "llvm/Support/CommandLine.h"
  27. #include "llvm/Support/Debug.h"
  28. #include "llvm/Support/ErrorHandling.h"
  29. #include "llvm/Support/MathExtras.h"
  30. #include "llvm/Support/raw_ostream.h"
  31. #include <algorithm>
  32. #include <cassert>
  33. #include <cstdint>
  34. #include <iterator>
  35. #include <utility>
  36. using namespace llvm;
  37. #define DEBUG_TYPE "stackmaps"
  38. static cl::opt<int> StackMapVersion(
  39. "stackmap-version", cl::init(3), cl::Hidden,
  40. cl::desc("Specify the stackmap encoding version (default = 3)"));
  41. const char *StackMaps::WSMP = "Stack Maps: ";
  42. static uint64_t getConstMetaVal(const MachineInstr &MI, unsigned Idx) {
  43. assert(MI.getOperand(Idx).isImm() &&
  44. MI.getOperand(Idx).getImm() == StackMaps::ConstantOp);
  45. const auto &MO = MI.getOperand(Idx + 1);
  46. assert(MO.isImm());
  47. return MO.getImm();
  48. }
  49. StackMapOpers::StackMapOpers(const MachineInstr *MI)
  50. : MI(MI) {
  51. assert(getVarIdx() <= MI->getNumOperands() &&
  52. "invalid stackmap definition");
  53. }
  54. PatchPointOpers::PatchPointOpers(const MachineInstr *MI)
  55. : MI(MI), HasDef(MI->getOperand(0).isReg() && MI->getOperand(0).isDef() &&
  56. !MI->getOperand(0).isImplicit()) {
  57. #ifndef NDEBUG
  58. unsigned CheckStartIdx = 0, e = MI->getNumOperands();
  59. while (CheckStartIdx < e && MI->getOperand(CheckStartIdx).isReg() &&
  60. MI->getOperand(CheckStartIdx).isDef() &&
  61. !MI->getOperand(CheckStartIdx).isImplicit())
  62. ++CheckStartIdx;
  63. assert(getMetaIdx() == CheckStartIdx &&
  64. "Unexpected additional definition in Patchpoint intrinsic.");
  65. #endif
  66. }
  67. unsigned PatchPointOpers::getNextScratchIdx(unsigned StartIdx) const {
  68. if (!StartIdx)
  69. StartIdx = getVarIdx();
  70. // Find the next scratch register (implicit def and early clobber)
  71. unsigned ScratchIdx = StartIdx, e = MI->getNumOperands();
  72. while (ScratchIdx < e &&
  73. !(MI->getOperand(ScratchIdx).isReg() &&
  74. MI->getOperand(ScratchIdx).isDef() &&
  75. MI->getOperand(ScratchIdx).isImplicit() &&
  76. MI->getOperand(ScratchIdx).isEarlyClobber()))
  77. ++ScratchIdx;
  78. assert(ScratchIdx != e && "No scratch register available");
  79. return ScratchIdx;
  80. }
  81. unsigned StatepointOpers::getNumGcMapEntriesIdx() {
  82. // Take index of num of allocas and skip all allocas records.
  83. unsigned CurIdx = getNumAllocaIdx();
  84. unsigned NumAllocas = getConstMetaVal(*MI, CurIdx - 1);
  85. CurIdx++;
  86. while (NumAllocas--)
  87. CurIdx = StackMaps::getNextMetaArgIdx(MI, CurIdx);
  88. return CurIdx + 1; // skip <StackMaps::ConstantOp>
  89. }
  90. unsigned StatepointOpers::getNumAllocaIdx() {
  91. // Take index of num of gc ptrs and skip all gc ptr records.
  92. unsigned CurIdx = getNumGCPtrIdx();
  93. unsigned NumGCPtrs = getConstMetaVal(*MI, CurIdx - 1);
  94. CurIdx++;
  95. while (NumGCPtrs--)
  96. CurIdx = StackMaps::getNextMetaArgIdx(MI, CurIdx);
  97. return CurIdx + 1; // skip <StackMaps::ConstantOp>
  98. }
  99. unsigned StatepointOpers::getNumGCPtrIdx() {
  100. // Take index of num of deopt args and skip all deopt records.
  101. unsigned CurIdx = getNumDeoptArgsIdx();
  102. unsigned NumDeoptArgs = getConstMetaVal(*MI, CurIdx - 1);
  103. CurIdx++;
  104. while (NumDeoptArgs--) {
  105. CurIdx = StackMaps::getNextMetaArgIdx(MI, CurIdx);
  106. }
  107. return CurIdx + 1; // skip <StackMaps::ConstantOp>
  108. }
  109. int StatepointOpers::getFirstGCPtrIdx() {
  110. unsigned NumGCPtrsIdx = getNumGCPtrIdx();
  111. unsigned NumGCPtrs = getConstMetaVal(*MI, NumGCPtrsIdx - 1);
  112. if (NumGCPtrs == 0)
  113. return -1;
  114. ++NumGCPtrsIdx; // skip <num gc ptrs>
  115. assert(NumGCPtrsIdx < MI->getNumOperands());
  116. return (int)NumGCPtrsIdx;
  117. }
  118. unsigned StatepointOpers::getGCPointerMap(
  119. SmallVectorImpl<std::pair<unsigned, unsigned>> &GCMap) {
  120. unsigned CurIdx = getNumGcMapEntriesIdx();
  121. unsigned GCMapSize = getConstMetaVal(*MI, CurIdx - 1);
  122. CurIdx++;
  123. for (unsigned N = 0; N < GCMapSize; ++N) {
  124. unsigned B = MI->getOperand(CurIdx++).getImm();
  125. unsigned D = MI->getOperand(CurIdx++).getImm();
  126. GCMap.push_back(std::make_pair(B, D));
  127. }
  128. return GCMapSize;
  129. }
  130. StackMaps::StackMaps(AsmPrinter &AP) : AP(AP) {
  131. if (StackMapVersion != 3)
  132. llvm_unreachable("Unsupported stackmap version!");
  133. }
  134. unsigned StackMaps::getNextMetaArgIdx(const MachineInstr *MI, unsigned CurIdx) {
  135. assert(CurIdx < MI->getNumOperands() && "Bad meta arg index");
  136. const auto &MO = MI->getOperand(CurIdx);
  137. if (MO.isImm()) {
  138. switch (MO.getImm()) {
  139. default:
  140. llvm_unreachable("Unrecognized operand type.");
  141. case StackMaps::DirectMemRefOp:
  142. CurIdx += 2;
  143. break;
  144. case StackMaps::IndirectMemRefOp:
  145. CurIdx += 3;
  146. break;
  147. case StackMaps::ConstantOp:
  148. ++CurIdx;
  149. break;
  150. }
  151. }
  152. ++CurIdx;
  153. assert(CurIdx < MI->getNumOperands() && "points past operand list");
  154. return CurIdx;
  155. }
  156. /// Go up the super-register chain until we hit a valid dwarf register number.
  157. static unsigned getDwarfRegNum(unsigned Reg, const TargetRegisterInfo *TRI) {
  158. int RegNum = TRI->getDwarfRegNum(Reg, false);
  159. for (MCSuperRegIterator SR(Reg, TRI); SR.isValid() && RegNum < 0; ++SR)
  160. RegNum = TRI->getDwarfRegNum(*SR, false);
  161. assert(RegNum >= 0 && "Invalid Dwarf register number.");
  162. return (unsigned)RegNum;
  163. }
  164. MachineInstr::const_mop_iterator
  165. StackMaps::parseOperand(MachineInstr::const_mop_iterator MOI,
  166. MachineInstr::const_mop_iterator MOE, LocationVec &Locs,
  167. LiveOutVec &LiveOuts) const {
  168. const TargetRegisterInfo *TRI = AP.MF->getSubtarget().getRegisterInfo();
  169. if (MOI->isImm()) {
  170. switch (MOI->getImm()) {
  171. default:
  172. llvm_unreachable("Unrecognized operand type.");
  173. case StackMaps::DirectMemRefOp: {
  174. auto &DL = AP.MF->getDataLayout();
  175. unsigned Size = DL.getPointerSizeInBits();
  176. assert((Size % 8) == 0 && "Need pointer size in bytes.");
  177. Size /= 8;
  178. Register Reg = (++MOI)->getReg();
  179. int64_t Imm = (++MOI)->getImm();
  180. Locs.emplace_back(StackMaps::Location::Direct, Size,
  181. getDwarfRegNum(Reg, TRI), Imm);
  182. break;
  183. }
  184. case StackMaps::IndirectMemRefOp: {
  185. int64_t Size = (++MOI)->getImm();
  186. assert(Size > 0 && "Need a valid size for indirect memory locations.");
  187. Register Reg = (++MOI)->getReg();
  188. int64_t Imm = (++MOI)->getImm();
  189. Locs.emplace_back(StackMaps::Location::Indirect, Size,
  190. getDwarfRegNum(Reg, TRI), Imm);
  191. break;
  192. }
  193. case StackMaps::ConstantOp: {
  194. ++MOI;
  195. assert(MOI->isImm() && "Expected constant operand.");
  196. int64_t Imm = MOI->getImm();
  197. Locs.emplace_back(Location::Constant, sizeof(int64_t), 0, Imm);
  198. break;
  199. }
  200. }
  201. return ++MOI;
  202. }
  203. // The physical register number will ultimately be encoded as a DWARF regno.
  204. // The stack map also records the size of a spill slot that can hold the
  205. // register content. (The runtime can track the actual size of the data type
  206. // if it needs to.)
  207. if (MOI->isReg()) {
  208. // Skip implicit registers (this includes our scratch registers)
  209. if (MOI->isImplicit())
  210. return ++MOI;
  211. if (MOI->isUndef()) {
  212. // Record `undef` register as constant. Use same value as ISel uses.
  213. Locs.emplace_back(Location::Constant, sizeof(int64_t), 0, 0xFEFEFEFE);
  214. return ++MOI;
  215. }
  216. assert(Register::isPhysicalRegister(MOI->getReg()) &&
  217. "Virtreg operands should have been rewritten before now.");
  218. const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(MOI->getReg());
  219. assert(!MOI->getSubReg() && "Physical subreg still around.");
  220. unsigned Offset = 0;
  221. unsigned DwarfRegNum = getDwarfRegNum(MOI->getReg(), TRI);
  222. unsigned LLVMRegNum = *TRI->getLLVMRegNum(DwarfRegNum, false);
  223. unsigned SubRegIdx = TRI->getSubRegIndex(LLVMRegNum, MOI->getReg());
  224. if (SubRegIdx)
  225. Offset = TRI->getSubRegIdxOffset(SubRegIdx);
  226. Locs.emplace_back(Location::Register, TRI->getSpillSize(*RC),
  227. DwarfRegNum, Offset);
  228. return ++MOI;
  229. }
  230. if (MOI->isRegLiveOut())
  231. LiveOuts = parseRegisterLiveOutMask(MOI->getRegLiveOut());
  232. return ++MOI;
  233. }
  234. void StackMaps::print(raw_ostream &OS) {
  235. const TargetRegisterInfo *TRI =
  236. AP.MF ? AP.MF->getSubtarget().getRegisterInfo() : nullptr;
  237. OS << WSMP << "callsites:\n";
  238. for (const auto &CSI : CSInfos) {
  239. const LocationVec &CSLocs = CSI.Locations;
  240. const LiveOutVec &LiveOuts = CSI.LiveOuts;
  241. OS << WSMP << "callsite " << CSI.ID << "\n";
  242. OS << WSMP << " has " << CSLocs.size() << " locations\n";
  243. unsigned Idx = 0;
  244. for (const auto &Loc : CSLocs) {
  245. OS << WSMP << "\t\tLoc " << Idx << ": ";
  246. switch (Loc.Type) {
  247. case Location::Unprocessed:
  248. OS << "<Unprocessed operand>";
  249. break;
  250. case Location::Register:
  251. OS << "Register ";
  252. if (TRI)
  253. OS << printReg(Loc.Reg, TRI);
  254. else
  255. OS << Loc.Reg;
  256. break;
  257. case Location::Direct:
  258. OS << "Direct ";
  259. if (TRI)
  260. OS << printReg(Loc.Reg, TRI);
  261. else
  262. OS << Loc.Reg;
  263. if (Loc.Offset)
  264. OS << " + " << Loc.Offset;
  265. break;
  266. case Location::Indirect:
  267. OS << "Indirect ";
  268. if (TRI)
  269. OS << printReg(Loc.Reg, TRI);
  270. else
  271. OS << Loc.Reg;
  272. OS << "+" << Loc.Offset;
  273. break;
  274. case Location::Constant:
  275. OS << "Constant " << Loc.Offset;
  276. break;
  277. case Location::ConstantIndex:
  278. OS << "Constant Index " << Loc.Offset;
  279. break;
  280. }
  281. OS << "\t[encoding: .byte " << Loc.Type << ", .byte 0"
  282. << ", .short " << Loc.Size << ", .short " << Loc.Reg << ", .short 0"
  283. << ", .int " << Loc.Offset << "]\n";
  284. Idx++;
  285. }
  286. OS << WSMP << "\thas " << LiveOuts.size() << " live-out registers\n";
  287. Idx = 0;
  288. for (const auto &LO : LiveOuts) {
  289. OS << WSMP << "\t\tLO " << Idx << ": ";
  290. if (TRI)
  291. OS << printReg(LO.Reg, TRI);
  292. else
  293. OS << LO.Reg;
  294. OS << "\t[encoding: .short " << LO.DwarfRegNum << ", .byte 0, .byte "
  295. << LO.Size << "]\n";
  296. Idx++;
  297. }
  298. }
  299. }
  300. /// Create a live-out register record for the given register Reg.
  301. StackMaps::LiveOutReg
  302. StackMaps::createLiveOutReg(unsigned Reg, const TargetRegisterInfo *TRI) const {
  303. unsigned DwarfRegNum = getDwarfRegNum(Reg, TRI);
  304. unsigned Size = TRI->getSpillSize(*TRI->getMinimalPhysRegClass(Reg));
  305. return LiveOutReg(Reg, DwarfRegNum, Size);
  306. }
  307. /// Parse the register live-out mask and return a vector of live-out registers
  308. /// that need to be recorded in the stackmap.
  309. StackMaps::LiveOutVec
  310. StackMaps::parseRegisterLiveOutMask(const uint32_t *Mask) const {
  311. assert(Mask && "No register mask specified");
  312. const TargetRegisterInfo *TRI = AP.MF->getSubtarget().getRegisterInfo();
  313. LiveOutVec LiveOuts;
  314. // Create a LiveOutReg for each bit that is set in the register mask.
  315. for (unsigned Reg = 0, NumRegs = TRI->getNumRegs(); Reg != NumRegs; ++Reg)
  316. if ((Mask[Reg / 32] >> (Reg % 32)) & 1)
  317. LiveOuts.push_back(createLiveOutReg(Reg, TRI));
  318. // We don't need to keep track of a register if its super-register is already
  319. // in the list. Merge entries that refer to the same dwarf register and use
  320. // the maximum size that needs to be spilled.
  321. llvm::sort(LiveOuts, [](const LiveOutReg &LHS, const LiveOutReg &RHS) {
  322. // Only sort by the dwarf register number.
  323. return LHS.DwarfRegNum < RHS.DwarfRegNum;
  324. });
  325. for (auto I = LiveOuts.begin(), E = LiveOuts.end(); I != E; ++I) {
  326. for (auto II = std::next(I); II != E; ++II) {
  327. if (I->DwarfRegNum != II->DwarfRegNum) {
  328. // Skip all the now invalid entries.
  329. I = --II;
  330. break;
  331. }
  332. I->Size = std::max(I->Size, II->Size);
  333. if (TRI->isSuperRegister(I->Reg, II->Reg))
  334. I->Reg = II->Reg;
  335. II->Reg = 0; // mark for deletion.
  336. }
  337. }
  338. llvm::erase_if(LiveOuts, [](const LiveOutReg &LO) { return LO.Reg == 0; });
  339. return LiveOuts;
  340. }
  341. // See statepoint MI format description in StatepointOpers' class comment
  342. // in include/llvm/CodeGen/StackMaps.h
  343. void StackMaps::parseStatepointOpers(const MachineInstr &MI,
  344. MachineInstr::const_mop_iterator MOI,
  345. MachineInstr::const_mop_iterator MOE,
  346. LocationVec &Locations,
  347. LiveOutVec &LiveOuts) {
  348. LLVM_DEBUG(dbgs() << "record statepoint : " << MI << "\n");
  349. StatepointOpers SO(&MI);
  350. MOI = parseOperand(MOI, MOE, Locations, LiveOuts); // CC
  351. MOI = parseOperand(MOI, MOE, Locations, LiveOuts); // Flags
  352. MOI = parseOperand(MOI, MOE, Locations, LiveOuts); // Num Deopts
  353. // Record Deopt Args.
  354. unsigned NumDeoptArgs = Locations.back().Offset;
  355. assert(Locations.back().Type == Location::Constant);
  356. assert(NumDeoptArgs == SO.getNumDeoptArgs());
  357. while (NumDeoptArgs--)
  358. MOI = parseOperand(MOI, MOE, Locations, LiveOuts);
  359. // Record gc base/derived pairs
  360. assert(MOI->isImm() && MOI->getImm() == StackMaps::ConstantOp);
  361. ++MOI;
  362. assert(MOI->isImm());
  363. unsigned NumGCPointers = MOI->getImm();
  364. ++MOI;
  365. if (NumGCPointers) {
  366. // Map logical index of GC ptr to MI operand index.
  367. SmallVector<unsigned, 8> GCPtrIndices;
  368. unsigned GCPtrIdx = (unsigned)SO.getFirstGCPtrIdx();
  369. assert((int)GCPtrIdx != -1);
  370. assert(MOI - MI.operands_begin() == GCPtrIdx + 0LL);
  371. while (NumGCPointers--) {
  372. GCPtrIndices.push_back(GCPtrIdx);
  373. GCPtrIdx = StackMaps::getNextMetaArgIdx(&MI, GCPtrIdx);
  374. }
  375. SmallVector<std::pair<unsigned, unsigned>, 8> GCPairs;
  376. unsigned NumGCPairs = SO.getGCPointerMap(GCPairs);
  377. (void)NumGCPairs;
  378. LLVM_DEBUG(dbgs() << "NumGCPairs = " << NumGCPairs << "\n");
  379. auto MOB = MI.operands_begin();
  380. for (auto &P : GCPairs) {
  381. assert(P.first < GCPtrIndices.size() && "base pointer index not found");
  382. assert(P.second < GCPtrIndices.size() &&
  383. "derived pointer index not found");
  384. unsigned BaseIdx = GCPtrIndices[P.first];
  385. unsigned DerivedIdx = GCPtrIndices[P.second];
  386. LLVM_DEBUG(dbgs() << "Base : " << BaseIdx << " Derived : " << DerivedIdx
  387. << "\n");
  388. (void)parseOperand(MOB + BaseIdx, MOE, Locations, LiveOuts);
  389. (void)parseOperand(MOB + DerivedIdx, MOE, Locations, LiveOuts);
  390. }
  391. MOI = MOB + GCPtrIdx;
  392. }
  393. // Record gc allocas
  394. assert(MOI < MOE);
  395. assert(MOI->isImm() && MOI->getImm() == StackMaps::ConstantOp);
  396. ++MOI;
  397. unsigned NumAllocas = MOI->getImm();
  398. ++MOI;
  399. while (NumAllocas--) {
  400. MOI = parseOperand(MOI, MOE, Locations, LiveOuts);
  401. assert(MOI < MOE);
  402. }
  403. }
  404. void StackMaps::recordStackMapOpers(const MCSymbol &MILabel,
  405. const MachineInstr &MI, uint64_t ID,
  406. MachineInstr::const_mop_iterator MOI,
  407. MachineInstr::const_mop_iterator MOE,
  408. bool recordResult) {
  409. MCContext &OutContext = AP.OutStreamer->getContext();
  410. LocationVec Locations;
  411. LiveOutVec LiveOuts;
  412. if (recordResult) {
  413. assert(PatchPointOpers(&MI).hasDef() && "Stackmap has no return value.");
  414. parseOperand(MI.operands_begin(), std::next(MI.operands_begin()), Locations,
  415. LiveOuts);
  416. }
  417. // Parse operands.
  418. if (MI.getOpcode() == TargetOpcode::STATEPOINT)
  419. parseStatepointOpers(MI, MOI, MOE, Locations, LiveOuts);
  420. else
  421. while (MOI != MOE)
  422. MOI = parseOperand(MOI, MOE, Locations, LiveOuts);
  423. // Move large constants into the constant pool.
  424. for (auto &Loc : Locations) {
  425. // Constants are encoded as sign-extended integers.
  426. // -1 is directly encoded as .long 0xFFFFFFFF with no constant pool.
  427. if (Loc.Type == Location::Constant && !isInt<32>(Loc.Offset)) {
  428. Loc.Type = Location::ConstantIndex;
  429. // ConstPool is intentionally a MapVector of 'uint64_t's (as
  430. // opposed to 'int64_t's). We should never be in a situation
  431. // where we have to insert either the tombstone or the empty
  432. // keys into a map, and for a DenseMap<uint64_t, T> these are
  433. // (uint64_t)0 and (uint64_t)-1. They can be and are
  434. // represented using 32 bit integers.
  435. assert((uint64_t)Loc.Offset != DenseMapInfo<uint64_t>::getEmptyKey() &&
  436. (uint64_t)Loc.Offset !=
  437. DenseMapInfo<uint64_t>::getTombstoneKey() &&
  438. "empty and tombstone keys should fit in 32 bits!");
  439. auto Result = ConstPool.insert(std::make_pair(Loc.Offset, Loc.Offset));
  440. Loc.Offset = Result.first - ConstPool.begin();
  441. }
  442. }
  443. // Create an expression to calculate the offset of the callsite from function
  444. // entry.
  445. const MCExpr *CSOffsetExpr = MCBinaryExpr::createSub(
  446. MCSymbolRefExpr::create(&MILabel, OutContext),
  447. MCSymbolRefExpr::create(AP.CurrentFnSymForSize, OutContext), OutContext);
  448. CSInfos.emplace_back(CSOffsetExpr, ID, std::move(Locations),
  449. std::move(LiveOuts));
  450. // Record the stack size of the current function and update callsite count.
  451. const MachineFrameInfo &MFI = AP.MF->getFrameInfo();
  452. const TargetRegisterInfo *RegInfo = AP.MF->getSubtarget().getRegisterInfo();
  453. bool HasDynamicFrameSize =
  454. MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(*(AP.MF));
  455. uint64_t FrameSize = HasDynamicFrameSize ? UINT64_MAX : MFI.getStackSize();
  456. auto CurrentIt = FnInfos.find(AP.CurrentFnSym);
  457. if (CurrentIt != FnInfos.end())
  458. CurrentIt->second.RecordCount++;
  459. else
  460. FnInfos.insert(std::make_pair(AP.CurrentFnSym, FunctionInfo(FrameSize)));
  461. }
  462. void StackMaps::recordStackMap(const MCSymbol &L, const MachineInstr &MI) {
  463. assert(MI.getOpcode() == TargetOpcode::STACKMAP && "expected stackmap");
  464. StackMapOpers opers(&MI);
  465. const int64_t ID = MI.getOperand(PatchPointOpers::IDPos).getImm();
  466. recordStackMapOpers(L, MI, ID, std::next(MI.operands_begin(),
  467. opers.getVarIdx()),
  468. MI.operands_end());
  469. }
  470. void StackMaps::recordPatchPoint(const MCSymbol &L, const MachineInstr &MI) {
  471. assert(MI.getOpcode() == TargetOpcode::PATCHPOINT && "expected patchpoint");
  472. PatchPointOpers opers(&MI);
  473. const int64_t ID = opers.getID();
  474. auto MOI = std::next(MI.operands_begin(), opers.getStackMapStartIdx());
  475. recordStackMapOpers(L, MI, ID, MOI, MI.operands_end(),
  476. opers.isAnyReg() && opers.hasDef());
  477. #ifndef NDEBUG
  478. // verify anyregcc
  479. auto &Locations = CSInfos.back().Locations;
  480. if (opers.isAnyReg()) {
  481. unsigned NArgs = opers.getNumCallArgs();
  482. for (unsigned i = 0, e = (opers.hasDef() ? NArgs + 1 : NArgs); i != e; ++i)
  483. assert(Locations[i].Type == Location::Register &&
  484. "anyreg arg must be in reg.");
  485. }
  486. #endif
  487. }
  488. void StackMaps::recordStatepoint(const MCSymbol &L, const MachineInstr &MI) {
  489. assert(MI.getOpcode() == TargetOpcode::STATEPOINT && "expected statepoint");
  490. StatepointOpers opers(&MI);
  491. const unsigned StartIdx = opers.getVarIdx();
  492. recordStackMapOpers(L, MI, opers.getID(), MI.operands_begin() + StartIdx,
  493. MI.operands_end(), false);
  494. }
  495. /// Emit the stackmap header.
  496. ///
  497. /// Header {
  498. /// uint8 : Stack Map Version (currently 3)
  499. /// uint8 : Reserved (expected to be 0)
  500. /// uint16 : Reserved (expected to be 0)
  501. /// }
  502. /// uint32 : NumFunctions
  503. /// uint32 : NumConstants
  504. /// uint32 : NumRecords
  505. void StackMaps::emitStackmapHeader(MCStreamer &OS) {
  506. // Header.
  507. OS.emitIntValue(StackMapVersion, 1); // Version.
  508. OS.emitIntValue(0, 1); // Reserved.
  509. OS.emitInt16(0); // Reserved.
  510. // Num functions.
  511. LLVM_DEBUG(dbgs() << WSMP << "#functions = " << FnInfos.size() << '\n');
  512. OS.emitInt32(FnInfos.size());
  513. // Num constants.
  514. LLVM_DEBUG(dbgs() << WSMP << "#constants = " << ConstPool.size() << '\n');
  515. OS.emitInt32(ConstPool.size());
  516. // Num callsites.
  517. LLVM_DEBUG(dbgs() << WSMP << "#callsites = " << CSInfos.size() << '\n');
  518. OS.emitInt32(CSInfos.size());
  519. }
  520. /// Emit the function frame record for each function.
  521. ///
  522. /// StkSizeRecord[NumFunctions] {
  523. /// uint64 : Function Address
  524. /// uint64 : Stack Size
  525. /// uint64 : Record Count
  526. /// }
  527. void StackMaps::emitFunctionFrameRecords(MCStreamer &OS) {
  528. // Function Frame records.
  529. LLVM_DEBUG(dbgs() << WSMP << "functions:\n");
  530. for (auto const &FR : FnInfos) {
  531. LLVM_DEBUG(dbgs() << WSMP << "function addr: " << FR.first
  532. << " frame size: " << FR.second.StackSize
  533. << " callsite count: " << FR.second.RecordCount << '\n');
  534. OS.emitSymbolValue(FR.first, 8);
  535. OS.emitIntValue(FR.second.StackSize, 8);
  536. OS.emitIntValue(FR.second.RecordCount, 8);
  537. }
  538. }
  539. /// Emit the constant pool.
  540. ///
  541. /// int64 : Constants[NumConstants]
  542. void StackMaps::emitConstantPoolEntries(MCStreamer &OS) {
  543. // Constant pool entries.
  544. LLVM_DEBUG(dbgs() << WSMP << "constants:\n");
  545. for (const auto &ConstEntry : ConstPool) {
  546. LLVM_DEBUG(dbgs() << WSMP << ConstEntry.second << '\n');
  547. OS.emitIntValue(ConstEntry.second, 8);
  548. }
  549. }
  550. /// Emit the callsite info for each callsite.
  551. ///
  552. /// StkMapRecord[NumRecords] {
  553. /// uint64 : PatchPoint ID
  554. /// uint32 : Instruction Offset
  555. /// uint16 : Reserved (record flags)
  556. /// uint16 : NumLocations
  557. /// Location[NumLocations] {
  558. /// uint8 : Register | Direct | Indirect | Constant | ConstantIndex
  559. /// uint8 : Size in Bytes
  560. /// uint16 : Dwarf RegNum
  561. /// int32 : Offset
  562. /// }
  563. /// uint16 : Padding
  564. /// uint16 : NumLiveOuts
  565. /// LiveOuts[NumLiveOuts] {
  566. /// uint16 : Dwarf RegNum
  567. /// uint8 : Reserved
  568. /// uint8 : Size in Bytes
  569. /// }
  570. /// uint32 : Padding (only if required to align to 8 byte)
  571. /// }
  572. ///
  573. /// Location Encoding, Type, Value:
  574. /// 0x1, Register, Reg (value in register)
  575. /// 0x2, Direct, Reg + Offset (frame index)
  576. /// 0x3, Indirect, [Reg + Offset] (spilled value)
  577. /// 0x4, Constant, Offset (small constant)
  578. /// 0x5, ConstIndex, Constants[Offset] (large constant)
  579. void StackMaps::emitCallsiteEntries(MCStreamer &OS) {
  580. LLVM_DEBUG(print(dbgs()));
  581. // Callsite entries.
  582. for (const auto &CSI : CSInfos) {
  583. const LocationVec &CSLocs = CSI.Locations;
  584. const LiveOutVec &LiveOuts = CSI.LiveOuts;
  585. // Verify stack map entry. It's better to communicate a problem to the
  586. // runtime than crash in case of in-process compilation. Currently, we do
  587. // simple overflow checks, but we may eventually communicate other
  588. // compilation errors this way.
  589. if (CSLocs.size() > UINT16_MAX || LiveOuts.size() > UINT16_MAX) {
  590. OS.emitIntValue(UINT64_MAX, 8); // Invalid ID.
  591. OS.emitValue(CSI.CSOffsetExpr, 4);
  592. OS.emitInt16(0); // Reserved.
  593. OS.emitInt16(0); // 0 locations.
  594. OS.emitInt16(0); // padding.
  595. OS.emitInt16(0); // 0 live-out registers.
  596. OS.emitInt32(0); // padding.
  597. continue;
  598. }
  599. OS.emitIntValue(CSI.ID, 8);
  600. OS.emitValue(CSI.CSOffsetExpr, 4);
  601. // Reserved for flags.
  602. OS.emitInt16(0);
  603. OS.emitInt16(CSLocs.size());
  604. for (const auto &Loc : CSLocs) {
  605. OS.emitIntValue(Loc.Type, 1);
  606. OS.emitIntValue(0, 1); // Reserved
  607. OS.emitInt16(Loc.Size);
  608. OS.emitInt16(Loc.Reg);
  609. OS.emitInt16(0); // Reserved
  610. OS.emitInt32(Loc.Offset);
  611. }
  612. // Emit alignment to 8 byte.
  613. OS.emitValueToAlignment(8);
  614. // Num live-out registers and padding to align to 4 byte.
  615. OS.emitInt16(0);
  616. OS.emitInt16(LiveOuts.size());
  617. for (const auto &LO : LiveOuts) {
  618. OS.emitInt16(LO.DwarfRegNum);
  619. OS.emitIntValue(0, 1);
  620. OS.emitIntValue(LO.Size, 1);
  621. }
  622. // Emit alignment to 8 byte.
  623. OS.emitValueToAlignment(8);
  624. }
  625. }
  626. /// Serialize the stackmap data.
  627. void StackMaps::serializeToStackMapSection() {
  628. (void)WSMP;
  629. // Bail out if there's no stack map data.
  630. assert((!CSInfos.empty() || ConstPool.empty()) &&
  631. "Expected empty constant pool too!");
  632. assert((!CSInfos.empty() || FnInfos.empty()) &&
  633. "Expected empty function record too!");
  634. if (CSInfos.empty())
  635. return;
  636. MCContext &OutContext = AP.OutStreamer->getContext();
  637. MCStreamer &OS = *AP.OutStreamer;
  638. // Create the section.
  639. MCSection *StackMapSection =
  640. OutContext.getObjectFileInfo()->getStackMapSection();
  641. OS.SwitchSection(StackMapSection);
  642. // Emit a dummy symbol to force section inclusion.
  643. OS.emitLabel(OutContext.getOrCreateSymbol(Twine("__LLVM_StackMaps")));
  644. // Serialize data.
  645. LLVM_DEBUG(dbgs() << "********** Stack Map Output **********\n");
  646. emitStackmapHeader(OS);
  647. emitFunctionFrameRecords(OS);
  648. emitConstantPoolEntries(OS);
  649. emitCallsiteEntries(OS);
  650. OS.AddBlankLine();
  651. // Clean up.
  652. CSInfos.clear();
  653. ConstPool.clear();
  654. }