StackMaps.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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/TargetMachine.h"
  22. #include "llvm/Target/TargetOpcodes.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. // Constants are encoded as sign-extended integers.
  186. // -1 is directly encoded as .long 0xFFFFFFFF with no constant pool.
  187. if (I->LocType == Location::Constant &&
  188. ((I->Offset + (int64_t(1)<<31)) >> 32) != 0) {
  189. I->LocType = Location::ConstantIndex;
  190. I->Offset = ConstPool.getConstantIndex(I->Offset);
  191. }
  192. }
  193. const MCExpr *CSOffsetExpr = MCBinaryExpr::CreateSub(
  194. MCSymbolRefExpr::Create(MILabel, OutContext),
  195. MCSymbolRefExpr::Create(AP.CurrentFnSym, OutContext),
  196. OutContext);
  197. CSInfos.push_back(CallsiteInfo(CSOffsetExpr, ID, Locations, LiveOuts));
  198. }
  199. void StackMaps::recordStackMap(const MachineInstr &MI) {
  200. assert(MI.getOpcode() == TargetOpcode::STACKMAP && "expected stackmap");
  201. int64_t ID = MI.getOperand(0).getImm();
  202. recordStackMapOpers(MI, ID, llvm::next(MI.operands_begin(), 2),
  203. MI.operands_end());
  204. }
  205. void StackMaps::recordPatchPoint(const MachineInstr &MI) {
  206. assert(MI.getOpcode() == TargetOpcode::PATCHPOINT && "expected patchpoint");
  207. PatchPointOpers opers(&MI);
  208. int64_t ID = opers.getMetaOper(PatchPointOpers::IDPos).getImm();
  209. MachineInstr::const_mop_iterator MOI =
  210. llvm::next(MI.operands_begin(), opers.getStackMapStartIdx());
  211. recordStackMapOpers(MI, ID, MOI, MI.operands_end(),
  212. opers.isAnyReg() && opers.hasDef());
  213. #ifndef NDEBUG
  214. // verify anyregcc
  215. LocationVec &Locations = CSInfos.back().Locations;
  216. if (opers.isAnyReg()) {
  217. unsigned NArgs = opers.getMetaOper(PatchPointOpers::NArgPos).getImm();
  218. for (unsigned i = 0, e = (opers.hasDef() ? NArgs+1 : NArgs); i != e; ++i)
  219. assert(Locations[i].LocType == Location::Register &&
  220. "anyreg arg must be in reg.");
  221. }
  222. #endif
  223. }
  224. /// serializeToStackMapSection conceptually populates the following fields:
  225. ///
  226. /// uint32 : Reserved (header)
  227. /// uint32 : NumConstants
  228. /// int64 : Constants[NumConstants]
  229. /// uint32 : NumRecords
  230. /// StkMapRecord[NumRecords] {
  231. /// uint64 : PatchPoint ID
  232. /// uint32 : Instruction Offset
  233. /// uint16 : Reserved (record flags)
  234. /// uint16 : NumLocations
  235. /// Location[NumLocations] {
  236. /// uint8 : Register | Direct | Indirect | Constant | ConstantIndex
  237. /// uint8 : Size in Bytes
  238. /// uint16 : Dwarf RegNum
  239. /// int32 : Offset
  240. /// }
  241. /// uint16 : NumLiveOuts
  242. /// LiveOuts[NumLiveOuts]
  243. /// uint16 : Dwarf RegNum
  244. /// uint8 : Reserved
  245. /// uint8 : Size in Bytes
  246. /// }
  247. ///
  248. /// Location Encoding, Type, Value:
  249. /// 0x1, Register, Reg (value in register)
  250. /// 0x2, Direct, Reg + Offset (frame index)
  251. /// 0x3, Indirect, [Reg + Offset] (spilled value)
  252. /// 0x4, Constant, Offset (small constant)
  253. /// 0x5, ConstIndex, Constants[Offset] (large constant)
  254. ///
  255. void StackMaps::serializeToStackMapSection() {
  256. // Bail out if there's no stack map data.
  257. if (CSInfos.empty())
  258. return;
  259. MCContext &OutContext = AP.OutStreamer.getContext();
  260. const TargetRegisterInfo *TRI = AP.TM.getRegisterInfo();
  261. // Create the section.
  262. const MCSection *StackMapSection =
  263. OutContext.getObjectFileInfo()->getStackMapSection();
  264. AP.OutStreamer.SwitchSection(StackMapSection);
  265. // Emit a dummy symbol to force section inclusion.
  266. AP.OutStreamer.EmitLabel(
  267. OutContext.GetOrCreateSymbol(Twine("__LLVM_StackMaps")));
  268. // Serialize data.
  269. const char *WSMP = "Stack Maps: ";
  270. (void)WSMP;
  271. const MCRegisterInfo &MCRI = *OutContext.getRegisterInfo();
  272. DEBUG(dbgs() << "********** Stack Map Output **********\n");
  273. // Header.
  274. AP.OutStreamer.EmitIntValue(0, 4);
  275. // Num constants.
  276. AP.OutStreamer.EmitIntValue(ConstPool.getNumConstants(), 4);
  277. // Constant pool entries.
  278. for (unsigned i = 0; i < ConstPool.getNumConstants(); ++i)
  279. AP.OutStreamer.EmitIntValue(ConstPool.getConstant(i), 8);
  280. DEBUG(dbgs() << WSMP << "#callsites = " << CSInfos.size() << "\n");
  281. AP.OutStreamer.EmitIntValue(CSInfos.size(), 4);
  282. for (CallsiteInfoList::const_iterator CSII = CSInfos.begin(),
  283. CSIE = CSInfos.end();
  284. CSII != CSIE; ++CSII) {
  285. uint64_t CallsiteID = CSII->ID;
  286. const LocationVec &CSLocs = CSII->Locations;
  287. const LiveOutVec &LiveOuts = CSII->LiveOuts;
  288. DEBUG(dbgs() << WSMP << "callsite " << CallsiteID << "\n");
  289. // Verify stack map entry. It's better to communicate a problem to the
  290. // runtime than crash in case of in-process compilation. Currently, we do
  291. // simple overflow checks, but we may eventually communicate other
  292. // compilation errors this way.
  293. if (CSLocs.size() > UINT16_MAX || LiveOuts.size() > UINT16_MAX) {
  294. AP.OutStreamer.EmitIntValue(UINT64_MAX, 8); // Invalid ID.
  295. AP.OutStreamer.EmitValue(CSII->CSOffsetExpr, 4);
  296. AP.OutStreamer.EmitIntValue(0, 2); // Reserved.
  297. AP.OutStreamer.EmitIntValue(0, 2); // 0 locations.
  298. AP.OutStreamer.EmitIntValue(0, 2); // 0 live-out registers.
  299. continue;
  300. }
  301. AP.OutStreamer.EmitIntValue(CallsiteID, 8);
  302. AP.OutStreamer.EmitValue(CSII->CSOffsetExpr, 4);
  303. // Reserved for flags.
  304. AP.OutStreamer.EmitIntValue(0, 2);
  305. DEBUG(dbgs() << WSMP << " has " << CSLocs.size() << " locations\n");
  306. AP.OutStreamer.EmitIntValue(CSLocs.size(), 2);
  307. unsigned operIdx = 0;
  308. for (LocationVec::const_iterator LocI = CSLocs.begin(), LocE = CSLocs.end();
  309. LocI != LocE; ++LocI, ++operIdx) {
  310. const Location &Loc = *LocI;
  311. unsigned RegNo = 0;
  312. int Offset = Loc.Offset;
  313. if(Loc.Reg) {
  314. RegNo = MCRI.getDwarfRegNum(Loc.Reg, false);
  315. for (MCSuperRegIterator SR(Loc.Reg, TRI);
  316. SR.isValid() && (int)RegNo < 0; ++SR) {
  317. RegNo = TRI->getDwarfRegNum(*SR, false);
  318. }
  319. // If this is a register location, put the subregister byte offset in
  320. // the location offset.
  321. if (Loc.LocType == Location::Register) {
  322. assert(!Loc.Offset && "Register location should have zero offset");
  323. unsigned LLVMRegNo = MCRI.getLLVMRegNum(RegNo, false);
  324. unsigned SubRegIdx = MCRI.getSubRegIndex(LLVMRegNo, Loc.Reg);
  325. if (SubRegIdx)
  326. Offset = MCRI.getSubRegIdxOffset(SubRegIdx);
  327. }
  328. }
  329. else {
  330. assert(Loc.LocType != Location::Register &&
  331. "Missing location register");
  332. }
  333. DEBUG(
  334. dbgs() << WSMP << " Loc " << operIdx << ": ";
  335. switch (Loc.LocType) {
  336. case Location::Unprocessed:
  337. dbgs() << "<Unprocessed operand>";
  338. break;
  339. case Location::Register:
  340. dbgs() << "Register " << MCRI.getName(Loc.Reg);
  341. break;
  342. case Location::Direct:
  343. dbgs() << "Direct " << MCRI.getName(Loc.Reg);
  344. if (Loc.Offset)
  345. dbgs() << " + " << Loc.Offset;
  346. break;
  347. case Location::Indirect:
  348. dbgs() << "Indirect " << MCRI.getName(Loc.Reg)
  349. << " + " << Loc.Offset;
  350. break;
  351. case Location::Constant:
  352. dbgs() << "Constant " << Loc.Offset;
  353. break;
  354. case Location::ConstantIndex:
  355. dbgs() << "Constant Index " << Loc.Offset;
  356. break;
  357. }
  358. dbgs() << " [encoding: .byte " << Loc.LocType
  359. << ", .byte " << Loc.Size
  360. << ", .short " << RegNo
  361. << ", .int " << Offset << "]\n";
  362. );
  363. AP.OutStreamer.EmitIntValue(Loc.LocType, 1);
  364. AP.OutStreamer.EmitIntValue(Loc.Size, 1);
  365. AP.OutStreamer.EmitIntValue(RegNo, 2);
  366. AP.OutStreamer.EmitIntValue(Offset, 4);
  367. }
  368. DEBUG(dbgs() << WSMP << " has " << LiveOuts.size()
  369. << " live-out registers\n");
  370. AP.OutStreamer.EmitIntValue(LiveOuts.size(), 2);
  371. operIdx = 0;
  372. for (LiveOutVec::const_iterator LI = LiveOuts.begin(), LE = LiveOuts.end();
  373. LI != LE; ++LI, ++operIdx) {
  374. DEBUG(dbgs() << WSMP << " LO " << operIdx << ": "
  375. << MCRI.getName(LI->Reg)
  376. << " [encoding: .short " << LI->RegNo
  377. << ", .byte 0, .byte " << LI->Size << "]\n");
  378. AP.OutStreamer.EmitIntValue(LI->RegNo, 2);
  379. AP.OutStreamer.EmitIntValue(0, 1);
  380. AP.OutStreamer.EmitIntValue(LI->Size, 1);
  381. }
  382. }
  383. AP.OutStreamer.AddBlankLine();
  384. CSInfos.clear();
  385. }