StackMaps.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. //===---------------------------- StackMaps.cpp ---------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #define DEBUG_TYPE "stackmaps"
  10. #include "llvm/CodeGen/StackMaps.h"
  11. #include "llvm/CodeGen/AsmPrinter.h"
  12. #include "llvm/CodeGen/MachineInstr.h"
  13. #include "llvm/IR/DataLayout.h"
  14. #include "llvm/MC/MCContext.h"
  15. #include "llvm/MC/MCExpr.h"
  16. #include "llvm/MC/MCObjectFileInfo.h"
  17. #include "llvm/MC/MCSectionMachO.h"
  18. #include "llvm/MC/MCStreamer.h"
  19. #include "llvm/Support/Debug.h"
  20. #include "llvm/Support/raw_ostream.h"
  21. #include "llvm/Target/TargetOpcodes.h"
  22. #include "llvm/Target/TargetMachine.h"
  23. #include "llvm/Target/TargetRegisterInfo.h"
  24. #include <iterator>
  25. using namespace llvm;
  26. PatchPointOpers::PatchPointOpers(const MachineInstr *MI)
  27. : MI(MI),
  28. HasDef(MI->getOperand(0).isReg() && MI->getOperand(0).isDef() &&
  29. !MI->getOperand(0).isImplicit()),
  30. IsAnyReg(MI->getOperand(getMetaIdx(CCPos)).getImm() == CallingConv::AnyReg)
  31. {
  32. #ifndef NDEBUG
  33. unsigned CheckStartIdx = 0, e = MI->getNumOperands();
  34. while (CheckStartIdx < e && MI->getOperand(CheckStartIdx).isReg() &&
  35. MI->getOperand(CheckStartIdx).isDef() &&
  36. !MI->getOperand(CheckStartIdx).isImplicit())
  37. ++CheckStartIdx;
  38. assert(getMetaIdx() == CheckStartIdx &&
  39. "Unexpected additonal definition in Patchpoint intrinsic.");
  40. #endif
  41. }
  42. unsigned PatchPointOpers::getNextScratchIdx(unsigned StartIdx) const {
  43. if (!StartIdx)
  44. StartIdx = getVarIdx();
  45. // Find the next scratch register (implicit def and early clobber)
  46. unsigned ScratchIdx = StartIdx, e = MI->getNumOperands();
  47. while (ScratchIdx < e &&
  48. !(MI->getOperand(ScratchIdx).isReg() &&
  49. MI->getOperand(ScratchIdx).isDef() &&
  50. MI->getOperand(ScratchIdx).isImplicit() &&
  51. MI->getOperand(ScratchIdx).isEarlyClobber()))
  52. ++ScratchIdx;
  53. assert(ScratchIdx != e && "No scratch register available");
  54. return ScratchIdx;
  55. }
  56. MachineInstr::const_mop_iterator
  57. StackMaps::parseOperand(MachineInstr::const_mop_iterator MOI,
  58. MachineInstr::const_mop_iterator MOE,
  59. LocationVec &Locs, LiveOutVec &LiveOuts) const {
  60. if (MOI->isImm()) {
  61. switch (MOI->getImm()) {
  62. default: llvm_unreachable("Unrecognized operand type.");
  63. case StackMaps::DirectMemRefOp: {
  64. unsigned Size = AP.TM.getDataLayout()->getPointerSizeInBits();
  65. assert((Size % 8) == 0 && "Need pointer size in bytes.");
  66. Size /= 8;
  67. unsigned Reg = (++MOI)->getReg();
  68. int64_t Imm = (++MOI)->getImm();
  69. Locs.push_back(Location(StackMaps::Location::Direct, Size, Reg, Imm));
  70. break;
  71. }
  72. case StackMaps::IndirectMemRefOp: {
  73. int64_t Size = (++MOI)->getImm();
  74. assert(Size > 0 && "Need a valid size for indirect memory locations.");
  75. unsigned Reg = (++MOI)->getReg();
  76. int64_t Imm = (++MOI)->getImm();
  77. Locs.push_back(Location(StackMaps::Location::Indirect, Size, Reg, Imm));
  78. break;
  79. }
  80. case StackMaps::ConstantOp: {
  81. ++MOI;
  82. assert(MOI->isImm() && "Expected constant operand.");
  83. int64_t Imm = MOI->getImm();
  84. Locs.push_back(Location(Location::Constant, sizeof(int64_t), 0, Imm));
  85. break;
  86. }
  87. }
  88. return ++MOI;
  89. }
  90. // The physical register number will ultimately be encoded as a DWARF regno.
  91. // The stack map also records the size of a spill slot that can hold the
  92. // register content. (The runtime can track the actual size of the data type
  93. // if it needs to.)
  94. if (MOI->isReg()) {
  95. // Skip implicit registers (this includes our scratch registers)
  96. if (MOI->isImplicit())
  97. return ++MOI;
  98. assert(TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) &&
  99. "Virtreg operands should have been rewritten before now.");
  100. const TargetRegisterClass *RC =
  101. AP.TM.getRegisterInfo()->getMinimalPhysRegClass(MOI->getReg());
  102. assert(!MOI->getSubReg() && "Physical subreg still around.");
  103. Locs.push_back(
  104. Location(Location::Register, RC->getSize(), MOI->getReg(), 0));
  105. return ++MOI;
  106. }
  107. if (MOI->isRegLiveOut())
  108. LiveOuts = parseRegisterLiveOutMask(MOI->getRegLiveOut());
  109. return ++MOI;
  110. }
  111. /// Go up the super-register chain until we hit a valid dwarf register number.
  112. static unsigned short getDwarfRegNum(unsigned Reg, const MCRegisterInfo &MCRI,
  113. const TargetRegisterInfo *TRI) {
  114. int RegNo = MCRI.getDwarfRegNum(Reg, false);
  115. for (MCSuperRegIterator SR(Reg, TRI);
  116. SR.isValid() && RegNo < 0; ++SR)
  117. RegNo = TRI->getDwarfRegNum(*SR, false);
  118. assert(RegNo >= 0 && "Invalid Dwarf register number.");
  119. return (unsigned short) RegNo;
  120. }
  121. /// Create a live-out register record for the given register Reg.
  122. StackMaps::LiveOutReg
  123. StackMaps::createLiveOutReg(unsigned Reg, const MCRegisterInfo &MCRI,
  124. const TargetRegisterInfo *TRI) const {
  125. unsigned RegNo = getDwarfRegNum(Reg, MCRI, TRI);
  126. unsigned Size = TRI->getMinimalPhysRegClass(Reg)->getSize();
  127. return LiveOutReg(Reg, RegNo, Size);
  128. }
  129. /// Parse the register live-out mask and return a vector of live-out registers
  130. /// that need to be recorded in the stackmap.
  131. StackMaps::LiveOutVec
  132. StackMaps::parseRegisterLiveOutMask(const uint32_t *Mask) const {
  133. assert(Mask && "No register mask specified");
  134. const TargetRegisterInfo *TRI = AP.TM.getRegisterInfo();
  135. MCContext &OutContext = AP.OutStreamer.getContext();
  136. const MCRegisterInfo &MCRI = *OutContext.getRegisterInfo();
  137. LiveOutVec LiveOuts;
  138. // Create a LiveOutReg for each bit that is set in the register mask.
  139. for (unsigned Reg = 0, NumRegs = TRI->getNumRegs(); Reg != NumRegs; ++Reg)
  140. if ((Mask[Reg / 32] >> Reg % 32) & 1)
  141. LiveOuts.push_back(createLiveOutReg(Reg, MCRI, TRI));
  142. // We don't need to keep track of a register if its super-register is already
  143. // in the list. Merge entries that refer to the same dwarf register and use
  144. // the maximum size that needs to be spilled.
  145. std::sort(LiveOuts.begin(), LiveOuts.end());
  146. for (LiveOutVec::iterator I = LiveOuts.begin(), E = LiveOuts.end();
  147. I != E; ++I) {
  148. for (LiveOutVec::iterator II = next(I); II != E; ++II) {
  149. if (I->RegNo != II->RegNo) {
  150. // Skip all the now invalid entries.
  151. I = --II;
  152. break;
  153. }
  154. I->Size = std::max(I->Size, II->Size);
  155. if (TRI->isSuperRegister(I->Reg, II->Reg))
  156. I->Reg = II->Reg;
  157. II->MarkInvalid();
  158. }
  159. }
  160. LiveOuts.erase(std::remove_if(LiveOuts.begin(), LiveOuts.end(),
  161. LiveOutReg::IsInvalid), LiveOuts.end());
  162. return LiveOuts;
  163. }
  164. void StackMaps::recordStackMapOpers(const MachineInstr &MI, uint64_t ID,
  165. MachineInstr::const_mop_iterator MOI,
  166. MachineInstr::const_mop_iterator MOE,
  167. bool recordResult) {
  168. MCContext &OutContext = AP.OutStreamer.getContext();
  169. MCSymbol *MILabel = OutContext.CreateTempSymbol();
  170. AP.OutStreamer.EmitLabel(MILabel);
  171. LocationVec Locations;
  172. LiveOutVec LiveOuts;
  173. if (recordResult) {
  174. assert(PatchPointOpers(&MI).hasDef() && "Stackmap has no return value.");
  175. parseOperand(MI.operands_begin(), llvm::next(MI.operands_begin()),
  176. Locations, LiveOuts);
  177. }
  178. // Parse operands.
  179. while (MOI != MOE) {
  180. MOI = parseOperand(MOI, MOE, Locations, LiveOuts);
  181. }
  182. // Move large constants into the constant pool.
  183. for (LocationVec::iterator I = Locations.begin(), E = Locations.end();
  184. I != E; ++I) {
  185. if (I->LocType == Location::Constant && (I->Offset & ~0xFFFFFFFFULL)) {
  186. I->LocType = Location::ConstantIndex;
  187. I->Offset = ConstPool.getConstantIndex(I->Offset);
  188. }
  189. }
  190. const MCExpr *CSOffsetExpr = MCBinaryExpr::CreateSub(
  191. MCSymbolRefExpr::Create(MILabel, OutContext),
  192. MCSymbolRefExpr::Create(AP.CurrentFnSym, OutContext),
  193. OutContext);
  194. CSInfos.push_back(CallsiteInfo(CSOffsetExpr, ID, Locations, LiveOuts));
  195. }
  196. void StackMaps::recordStackMap(const MachineInstr &MI) {
  197. assert(MI.getOpcode() == TargetOpcode::STACKMAP && "expected stackmap");
  198. int64_t ID = MI.getOperand(0).getImm();
  199. recordStackMapOpers(MI, ID, llvm::next(MI.operands_begin(), 2),
  200. MI.operands_end());
  201. }
  202. void StackMaps::recordPatchPoint(const MachineInstr &MI) {
  203. assert(MI.getOpcode() == TargetOpcode::PATCHPOINT && "expected patchpoint");
  204. PatchPointOpers opers(&MI);
  205. int64_t ID = opers.getMetaOper(PatchPointOpers::IDPos).getImm();
  206. MachineInstr::const_mop_iterator MOI =
  207. llvm::next(MI.operands_begin(), opers.getStackMapStartIdx());
  208. recordStackMapOpers(MI, ID, MOI, MI.operands_end(),
  209. opers.isAnyReg() && opers.hasDef());
  210. #ifndef NDEBUG
  211. // verify anyregcc
  212. LocationVec &Locations = CSInfos.back().Locations;
  213. if (opers.isAnyReg()) {
  214. unsigned NArgs = opers.getMetaOper(PatchPointOpers::NArgPos).getImm();
  215. for (unsigned i = 0, e = (opers.hasDef() ? NArgs+1 : NArgs); i != e; ++i)
  216. assert(Locations[i].LocType == Location::Register &&
  217. "anyreg arg must be in reg.");
  218. }
  219. #endif
  220. }
  221. /// serializeToStackMapSection conceptually populates the following fields:
  222. ///
  223. /// uint32 : Reserved (header)
  224. /// uint32 : NumConstants
  225. /// int64 : Constants[NumConstants]
  226. /// uint32 : NumRecords
  227. /// StkMapRecord[NumRecords] {
  228. /// uint64 : PatchPoint ID
  229. /// uint32 : Instruction Offset
  230. /// uint16 : Reserved (record flags)
  231. /// uint16 : NumLocations
  232. /// Location[NumLocations] {
  233. /// uint8 : Register | Direct | Indirect | Constant | ConstantIndex
  234. /// uint8 : Size in Bytes
  235. /// uint16 : Dwarf RegNum
  236. /// int32 : Offset
  237. /// }
  238. /// uint16 : NumLiveOuts
  239. /// LiveOuts[NumLiveOuts]
  240. /// uint16 : Dwarf RegNum
  241. /// uint8 : Reserved
  242. /// uint8 : Size in Bytes
  243. /// }
  244. ///
  245. /// Location Encoding, Type, Value:
  246. /// 0x1, Register, Reg (value in register)
  247. /// 0x2, Direct, Reg + Offset (frame index)
  248. /// 0x3, Indirect, [Reg + Offset] (spilled value)
  249. /// 0x4, Constant, Offset (small constant)
  250. /// 0x5, ConstIndex, Constants[Offset] (large constant)
  251. ///
  252. void StackMaps::serializeToStackMapSection() {
  253. // Bail out if there's no stack map data.
  254. if (CSInfos.empty())
  255. return;
  256. MCContext &OutContext = AP.OutStreamer.getContext();
  257. const TargetRegisterInfo *TRI = AP.TM.getRegisterInfo();
  258. // Create the section.
  259. const MCSection *StackMapSection =
  260. OutContext.getObjectFileInfo()->getStackMapSection();
  261. AP.OutStreamer.SwitchSection(StackMapSection);
  262. // Emit a dummy symbol to force section inclusion.
  263. AP.OutStreamer.EmitLabel(
  264. OutContext.GetOrCreateSymbol(Twine("__LLVM_StackMaps")));
  265. // Serialize data.
  266. const char *WSMP = "Stack Maps: ";
  267. (void)WSMP;
  268. const MCRegisterInfo &MCRI = *OutContext.getRegisterInfo();
  269. DEBUG(dbgs() << "********** Stack Map Output **********\n");
  270. // Header.
  271. AP.OutStreamer.EmitIntValue(0, 4);
  272. // Num constants.
  273. AP.OutStreamer.EmitIntValue(ConstPool.getNumConstants(), 4);
  274. // Constant pool entries.
  275. for (unsigned i = 0; i < ConstPool.getNumConstants(); ++i)
  276. AP.OutStreamer.EmitIntValue(ConstPool.getConstant(i), 8);
  277. DEBUG(dbgs() << WSMP << "#callsites = " << CSInfos.size() << "\n");
  278. AP.OutStreamer.EmitIntValue(CSInfos.size(), 4);
  279. for (CallsiteInfoList::const_iterator CSII = CSInfos.begin(),
  280. CSIE = CSInfos.end();
  281. CSII != CSIE; ++CSII) {
  282. uint64_t CallsiteID = CSII->ID;
  283. const LocationVec &CSLocs = CSII->Locations;
  284. const LiveOutVec &LiveOuts = CSII->LiveOuts;
  285. DEBUG(dbgs() << WSMP << "callsite " << CallsiteID << "\n");
  286. // Verify stack map entry. It's better to communicate a problem to the
  287. // runtime than crash in case of in-process compilation. Currently, we do
  288. // simple overflow checks, but we may eventually communicate other
  289. // compilation errors this way.
  290. if (CSLocs.size() > UINT16_MAX || LiveOuts.size() > UINT16_MAX) {
  291. AP.OutStreamer.EmitIntValue(UINT64_MAX, 8); // Invalid ID.
  292. AP.OutStreamer.EmitValue(CSII->CSOffsetExpr, 4);
  293. AP.OutStreamer.EmitIntValue(0, 2); // Reserved.
  294. AP.OutStreamer.EmitIntValue(0, 2); // 0 locations.
  295. AP.OutStreamer.EmitIntValue(0, 2); // 0 live-out registers.
  296. continue;
  297. }
  298. AP.OutStreamer.EmitIntValue(CallsiteID, 8);
  299. AP.OutStreamer.EmitValue(CSII->CSOffsetExpr, 4);
  300. // Reserved for flags.
  301. AP.OutStreamer.EmitIntValue(0, 2);
  302. DEBUG(dbgs() << WSMP << " has " << CSLocs.size() << " locations\n");
  303. AP.OutStreamer.EmitIntValue(CSLocs.size(), 2);
  304. unsigned operIdx = 0;
  305. for (LocationVec::const_iterator LocI = CSLocs.begin(), LocE = CSLocs.end();
  306. LocI != LocE; ++LocI, ++operIdx) {
  307. const Location &Loc = *LocI;
  308. unsigned RegNo = 0;
  309. int Offset = Loc.Offset;
  310. if(Loc.Reg) {
  311. RegNo = MCRI.getDwarfRegNum(Loc.Reg, false);
  312. for (MCSuperRegIterator SR(Loc.Reg, TRI);
  313. SR.isValid() && (int)RegNo < 0; ++SR) {
  314. RegNo = TRI->getDwarfRegNum(*SR, false);
  315. }
  316. // If this is a register location, put the subregister byte offset in
  317. // the location offset.
  318. if (Loc.LocType == Location::Register) {
  319. assert(!Loc.Offset && "Register location should have zero offset");
  320. unsigned LLVMRegNo = MCRI.getLLVMRegNum(RegNo, false);
  321. unsigned SubRegIdx = MCRI.getSubRegIndex(LLVMRegNo, Loc.Reg);
  322. if (SubRegIdx)
  323. Offset = MCRI.getSubRegIdxOffset(SubRegIdx);
  324. }
  325. }
  326. else {
  327. assert(Loc.LocType != Location::Register &&
  328. "Missing location register");
  329. }
  330. DEBUG(
  331. dbgs() << WSMP << " Loc " << operIdx << ": ";
  332. switch (Loc.LocType) {
  333. case Location::Unprocessed:
  334. dbgs() << "<Unprocessed operand>";
  335. break;
  336. case Location::Register:
  337. dbgs() << "Register " << MCRI.getName(Loc.Reg);
  338. break;
  339. case Location::Direct:
  340. dbgs() << "Direct " << MCRI.getName(Loc.Reg);
  341. if (Loc.Offset)
  342. dbgs() << " + " << Loc.Offset;
  343. break;
  344. case Location::Indirect:
  345. dbgs() << "Indirect " << MCRI.getName(Loc.Reg)
  346. << " + " << Loc.Offset;
  347. break;
  348. case Location::Constant:
  349. dbgs() << "Constant " << Loc.Offset;
  350. break;
  351. case Location::ConstantIndex:
  352. dbgs() << "Constant Index " << Loc.Offset;
  353. break;
  354. }
  355. dbgs() << " [encoding: .byte " << Loc.LocType
  356. << ", .byte " << Loc.Size
  357. << ", .short " << RegNo
  358. << ", .int " << Offset << "]\n";
  359. );
  360. AP.OutStreamer.EmitIntValue(Loc.LocType, 1);
  361. AP.OutStreamer.EmitIntValue(Loc.Size, 1);
  362. AP.OutStreamer.EmitIntValue(RegNo, 2);
  363. AP.OutStreamer.EmitIntValue(Offset, 4);
  364. }
  365. DEBUG(dbgs() << WSMP << " has " << LiveOuts.size()
  366. << " live-out registers\n");
  367. AP.OutStreamer.EmitIntValue(LiveOuts.size(), 2);
  368. operIdx = 0;
  369. for (LiveOutVec::const_iterator LI = LiveOuts.begin(), LE = LiveOuts.end();
  370. LI != LE; ++LI, ++operIdx) {
  371. DEBUG(dbgs() << WSMP << " LO " << operIdx << ": "
  372. << MCRI.getName(LI->Reg)
  373. << " [encoding: .short " << LI->RegNo
  374. << ", .byte 0, .byte " << LI->Size << "]\n");
  375. AP.OutStreamer.EmitIntValue(LI->RegNo, 2);
  376. AP.OutStreamer.EmitIntValue(0, 1);
  377. AP.OutStreamer.EmitIntValue(LI->Size, 1);
  378. }
  379. }
  380. AP.OutStreamer.AddBlankLine();
  381. CSInfos.clear();
  382. }