1 //===---------------------------- StackMaps.cpp ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/CodeGen/StackMaps.h"
11 #include "llvm/CodeGen/AsmPrinter.h"
12 #include "llvm/CodeGen/MachineFrameInfo.h"
13 #include "llvm/CodeGen/MachineFunction.h"
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/IR/DataLayout.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCObjectFileInfo.h"
19 #include "llvm/MC/MCSectionMachO.h"
20 #include "llvm/MC/MCStreamer.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetOpcodes.h"
26 #include "llvm/Target/TargetRegisterInfo.h"
27 #include "llvm/Target/TargetSubtargetInfo.h"
32 #define DEBUG_TYPE "stackmaps"
34 static cl::opt<int> StackMapVersion("stackmap-version", cl::init(1),
35 cl::desc("Specify the stackmap encoding version (default = 1)"));
37 const char *StackMaps::WSMP = "Stack Maps: ";
39 PatchPointOpers::PatchPointOpers(const MachineInstr *MI)
41 HasDef(MI->getOperand(0).isReg() && MI->getOperand(0).isDef() &&
42 !MI->getOperand(0).isImplicit()),
43 IsAnyReg(MI->getOperand(getMetaIdx(CCPos)).getImm() == CallingConv::AnyReg)
46 unsigned CheckStartIdx = 0, e = MI->getNumOperands();
47 while (CheckStartIdx < e && MI->getOperand(CheckStartIdx).isReg() &&
48 MI->getOperand(CheckStartIdx).isDef() &&
49 !MI->getOperand(CheckStartIdx).isImplicit())
52 assert(getMetaIdx() == CheckStartIdx &&
53 "Unexpected additional definition in Patchpoint intrinsic.");
57 unsigned PatchPointOpers::getNextScratchIdx(unsigned StartIdx) const {
59 StartIdx = getVarIdx();
61 // Find the next scratch register (implicit def and early clobber)
62 unsigned ScratchIdx = StartIdx, e = MI->getNumOperands();
63 while (ScratchIdx < e &&
64 !(MI->getOperand(ScratchIdx).isReg() &&
65 MI->getOperand(ScratchIdx).isDef() &&
66 MI->getOperand(ScratchIdx).isImplicit() &&
67 MI->getOperand(ScratchIdx).isEarlyClobber()))
70 assert(ScratchIdx != e && "No scratch register available");
74 StackMaps::StackMaps(AsmPrinter &AP) : AP(AP) {
75 if (StackMapVersion != 1)
76 llvm_unreachable("Unsupported stackmap version!");
79 MachineInstr::const_mop_iterator
80 StackMaps::parseOperand(MachineInstr::const_mop_iterator MOI,
81 MachineInstr::const_mop_iterator MOE,
82 LocationVec &Locs, LiveOutVec &LiveOuts) const {
84 switch (MOI->getImm()) {
85 default: llvm_unreachable("Unrecognized operand type.");
86 case StackMaps::DirectMemRefOp: {
88 AP.TM.getSubtargetImpl()->getDataLayout()->getPointerSizeInBits();
89 assert((Size % 8) == 0 && "Need pointer size in bytes.");
91 unsigned Reg = (++MOI)->getReg();
92 int64_t Imm = (++MOI)->getImm();
93 Locs.push_back(Location(StackMaps::Location::Direct, Size, Reg, Imm));
96 case StackMaps::IndirectMemRefOp: {
97 int64_t Size = (++MOI)->getImm();
98 assert(Size > 0 && "Need a valid size for indirect memory locations.");
99 unsigned Reg = (++MOI)->getReg();
100 int64_t Imm = (++MOI)->getImm();
101 Locs.push_back(Location(StackMaps::Location::Indirect, Size, Reg, Imm));
104 case StackMaps::ConstantOp: {
106 assert(MOI->isImm() && "Expected constant operand.");
107 int64_t Imm = MOI->getImm();
108 Locs.push_back(Location(Location::Constant, sizeof(int64_t), 0, Imm));
115 // The physical register number will ultimately be encoded as a DWARF regno.
116 // The stack map also records the size of a spill slot that can hold the
117 // register content. (The runtime can track the actual size of the data type
120 // Skip implicit registers (this includes our scratch registers)
121 if (MOI->isImplicit())
124 assert(TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) &&
125 "Virtreg operands should have been rewritten before now.");
126 const TargetRegisterClass *RC =
127 AP.TM.getSubtargetImpl()->getRegisterInfo()->getMinimalPhysRegClass(
129 assert(!MOI->getSubReg() && "Physical subreg still around.");
131 Location(Location::Register, RC->getSize(), MOI->getReg(), 0));
135 if (MOI->isRegLiveOut())
136 LiveOuts = parseRegisterLiveOutMask(MOI->getRegLiveOut());
141 /// Go up the super-register chain until we hit a valid dwarf register number.
142 static unsigned getDwarfRegNum(unsigned Reg, const TargetRegisterInfo *TRI) {
143 int RegNo = TRI->getDwarfRegNum(Reg, false);
144 for (MCSuperRegIterator SR(Reg, TRI); SR.isValid() && RegNo < 0; ++SR)
145 RegNo = TRI->getDwarfRegNum(*SR, false);
147 assert(RegNo >= 0 && "Invalid Dwarf register number.");
148 return (unsigned) RegNo;
151 /// Create a live-out register record for the given register Reg.
152 StackMaps::LiveOutReg
153 StackMaps::createLiveOutReg(unsigned Reg, const TargetRegisterInfo *TRI) const {
154 unsigned RegNo = getDwarfRegNum(Reg, TRI);
155 unsigned Size = TRI->getMinimalPhysRegClass(Reg)->getSize();
156 return LiveOutReg(Reg, RegNo, Size);
159 /// Parse the register live-out mask and return a vector of live-out registers
160 /// that need to be recorded in the stackmap.
161 StackMaps::LiveOutVec
162 StackMaps::parseRegisterLiveOutMask(const uint32_t *Mask) const {
163 assert(Mask && "No register mask specified");
164 const TargetRegisterInfo *TRI = AP.TM.getSubtargetImpl()->getRegisterInfo();
167 // Create a LiveOutReg for each bit that is set in the register mask.
168 for (unsigned Reg = 0, NumRegs = TRI->getNumRegs(); Reg != NumRegs; ++Reg)
169 if ((Mask[Reg / 32] >> Reg % 32) & 1)
170 LiveOuts.push_back(createLiveOutReg(Reg, TRI));
172 // We don't need to keep track of a register if its super-register is already
173 // in the list. Merge entries that refer to the same dwarf register and use
174 // the maximum size that needs to be spilled.
175 std::sort(LiveOuts.begin(), LiveOuts.end());
176 for (LiveOutVec::iterator I = LiveOuts.begin(), E = LiveOuts.end();
178 for (LiveOutVec::iterator II = std::next(I); II != E; ++II) {
179 if (I->RegNo != II->RegNo) {
180 // Skip all the now invalid entries.
184 I->Size = std::max(I->Size, II->Size);
185 if (TRI->isSuperRegister(I->Reg, II->Reg))
190 LiveOuts.erase(std::remove_if(LiveOuts.begin(), LiveOuts.end(),
191 LiveOutReg::IsInvalid), LiveOuts.end());
195 void StackMaps::recordStackMapOpers(const MachineInstr &MI, uint64_t ID,
196 MachineInstr::const_mop_iterator MOI,
197 MachineInstr::const_mop_iterator MOE,
200 MCContext &OutContext = AP.OutStreamer.getContext();
201 MCSymbol *MILabel = OutContext.CreateTempSymbol();
202 AP.OutStreamer.EmitLabel(MILabel);
204 LocationVec Locations;
208 assert(PatchPointOpers(&MI).hasDef() && "Stackmap has no return value.");
209 parseOperand(MI.operands_begin(), std::next(MI.operands_begin()),
210 Locations, LiveOuts);
215 MOI = parseOperand(MOI, MOE, Locations, LiveOuts);
218 // Move large constants into the constant pool.
219 for (LocationVec::iterator I = Locations.begin(), E = Locations.end();
221 // Constants are encoded as sign-extended integers.
222 // -1 is directly encoded as .long 0xFFFFFFFF with no constant pool.
223 if (I->LocType == Location::Constant &&
224 ((I->Offset + (int64_t(1)<<31)) >> 32) != 0) {
225 I->LocType = Location::ConstantIndex;
226 auto Result = ConstPool.insert(std::make_pair(I->Offset, I->Offset));
227 I->Offset = Result.first - ConstPool.begin();
231 // Create an expression to calculate the offset of the callsite from function
233 const MCExpr *CSOffsetExpr = MCBinaryExpr::CreateSub(
234 MCSymbolRefExpr::Create(MILabel, OutContext),
235 MCSymbolRefExpr::Create(AP.CurrentFnSym, OutContext),
238 CSInfos.emplace_back(CSOffsetExpr, ID, std::move(Locations),
239 std::move(LiveOuts));
241 // Record the stack size of the current function.
242 const MachineFrameInfo *MFI = AP.MF->getFrameInfo();
243 const TargetRegisterInfo *RegInfo = AP.MF->getSubtarget().getRegisterInfo();
244 const bool DynamicFrameSize = MFI->hasVarSizedObjects() ||
245 RegInfo->needsStackRealignment(*(AP.MF));
246 FnStackSize[AP.CurrentFnSym] =
247 DynamicFrameSize ? UINT64_MAX : MFI->getStackSize();
250 void StackMaps::recordStackMap(const MachineInstr &MI) {
251 assert(MI.getOpcode() == TargetOpcode::STACKMAP && "expected stackmap");
253 int64_t ID = MI.getOperand(0).getImm();
254 recordStackMapOpers(MI, ID, std::next(MI.operands_begin(), 2),
258 void StackMaps::recordPatchPoint(const MachineInstr &MI) {
259 assert(MI.getOpcode() == TargetOpcode::PATCHPOINT && "expected patchpoint");
261 PatchPointOpers opers(&MI);
262 int64_t ID = opers.getMetaOper(PatchPointOpers::IDPos).getImm();
264 MachineInstr::const_mop_iterator MOI =
265 std::next(MI.operands_begin(), opers.getStackMapStartIdx());
266 recordStackMapOpers(MI, ID, MOI, MI.operands_end(),
267 opers.isAnyReg() && opers.hasDef());
271 LocationVec &Locations = CSInfos.back().Locations;
272 if (opers.isAnyReg()) {
273 unsigned NArgs = opers.getMetaOper(PatchPointOpers::NArgPos).getImm();
274 for (unsigned i = 0, e = (opers.hasDef() ? NArgs+1 : NArgs); i != e; ++i)
275 assert(Locations[i].LocType == Location::Register &&
276 "anyreg arg must be in reg.");
281 /// Emit the stackmap header.
284 /// uint8 : Stack Map Version (currently 1)
285 /// uint8 : Reserved (expected to be 0)
286 /// uint16 : Reserved (expected to be 0)
288 /// uint32 : NumFunctions
289 /// uint32 : NumConstants
290 /// uint32 : NumRecords
291 void StackMaps::emitStackmapHeader(MCStreamer &OS) {
293 OS.EmitIntValue(StackMapVersion, 1); // Version.
294 OS.EmitIntValue(0, 1); // Reserved.
295 OS.EmitIntValue(0, 2); // Reserved.
298 DEBUG(dbgs() << WSMP << "#functions = " << FnStackSize.size() << '\n');
299 OS.EmitIntValue(FnStackSize.size(), 4);
301 DEBUG(dbgs() << WSMP << "#constants = " << ConstPool.size() << '\n');
302 OS.EmitIntValue(ConstPool.size(), 4);
304 DEBUG(dbgs() << WSMP << "#callsites = " << CSInfos.size() << '\n');
305 OS.EmitIntValue(CSInfos.size(), 4);
308 /// Emit the function frame record for each function.
310 /// StkSizeRecord[NumFunctions] {
311 /// uint64 : Function Address
312 /// uint64 : Stack Size
314 void StackMaps::emitFunctionFrameRecords(MCStreamer &OS) {
315 // Function Frame records.
316 DEBUG(dbgs() << WSMP << "functions:\n");
317 for (auto const &FR : FnStackSize) {
318 DEBUG(dbgs() << WSMP << "function addr: " << FR.first
319 << " frame size: " << FR.second);
320 OS.EmitSymbolValue(FR.first, 8);
321 OS.EmitIntValue(FR.second, 8);
325 /// Emit the constant pool.
327 /// int64 : Constants[NumConstants]
328 void StackMaps::emitConstantPoolEntries(MCStreamer &OS) {
329 // Constant pool entries.
330 DEBUG(dbgs() << WSMP << "constants:\n");
331 for (auto ConstEntry : ConstPool) {
332 DEBUG(dbgs() << WSMP << ConstEntry.second << '\n');
333 OS.EmitIntValue(ConstEntry.second, 8);
337 /// Emit the callsite info for each callsite.
339 /// StkMapRecord[NumRecords] {
340 /// uint64 : PatchPoint ID
341 /// uint32 : Instruction Offset
342 /// uint16 : Reserved (record flags)
343 /// uint16 : NumLocations
344 /// Location[NumLocations] {
345 /// uint8 : Register | Direct | Indirect | Constant | ConstantIndex
346 /// uint8 : Size in Bytes
347 /// uint16 : Dwarf RegNum
351 /// uint16 : NumLiveOuts
352 /// LiveOuts[NumLiveOuts] {
353 /// uint16 : Dwarf RegNum
355 /// uint8 : Size in Bytes
357 /// uint32 : Padding (only if required to align to 8 byte)
360 /// Location Encoding, Type, Value:
361 /// 0x1, Register, Reg (value in register)
362 /// 0x2, Direct, Reg + Offset (frame index)
363 /// 0x3, Indirect, [Reg + Offset] (spilled value)
364 /// 0x4, Constant, Offset (small constant)
365 /// 0x5, ConstIndex, Constants[Offset] (large constant)
366 void StackMaps::emitCallsiteEntries(MCStreamer &OS,
367 const TargetRegisterInfo *TRI) {
369 DEBUG(dbgs() << WSMP << "callsites:\n");
370 for (const auto &CSI : CSInfos) {
371 const LocationVec &CSLocs = CSI.Locations;
372 const LiveOutVec &LiveOuts = CSI.LiveOuts;
374 DEBUG(dbgs() << WSMP << "callsite " << CSI.ID << "\n");
376 // Verify stack map entry. It's better to communicate a problem to the
377 // runtime than crash in case of in-process compilation. Currently, we do
378 // simple overflow checks, but we may eventually communicate other
379 // compilation errors this way.
380 if (CSLocs.size() > UINT16_MAX || LiveOuts.size() > UINT16_MAX) {
381 OS.EmitIntValue(UINT64_MAX, 8); // Invalid ID.
382 OS.EmitValue(CSI.CSOffsetExpr, 4);
383 OS.EmitIntValue(0, 2); // Reserved.
384 OS.EmitIntValue(0, 2); // 0 locations.
385 OS.EmitIntValue(0, 2); // padding.
386 OS.EmitIntValue(0, 2); // 0 live-out registers.
387 OS.EmitIntValue(0, 4); // padding.
391 OS.EmitIntValue(CSI.ID, 8);
392 OS.EmitValue(CSI.CSOffsetExpr, 4);
394 // Reserved for flags.
395 OS.EmitIntValue(0, 2);
397 DEBUG(dbgs() << WSMP << " has " << CSLocs.size() << " locations\n");
399 OS.EmitIntValue(CSLocs.size(), 2);
401 unsigned OperIdx = 0;
402 for (const auto &Loc : CSLocs) {
404 int Offset = Loc.Offset;
406 RegNo = getDwarfRegNum(Loc.Reg, TRI);
408 // If this is a register location, put the subregister byte offset in
409 // the location offset.
410 if (Loc.LocType == Location::Register) {
411 assert(!Loc.Offset && "Register location should have zero offset");
412 unsigned LLVMRegNo = TRI->getLLVMRegNum(RegNo, false);
413 unsigned SubRegIdx = TRI->getSubRegIndex(LLVMRegNo, Loc.Reg);
415 Offset = TRI->getSubRegIdxOffset(SubRegIdx);
419 assert(Loc.LocType != Location::Register &&
420 "Missing location register");
423 DEBUG(dbgs() << WSMP << " Loc " << OperIdx << ": ";
424 switch (Loc.LocType) {
425 case Location::Unprocessed:
426 dbgs() << "<Unprocessed operand>";
428 case Location::Register:
429 dbgs() << "Register " << TRI->getName(Loc.Reg);
431 case Location::Direct:
432 dbgs() << "Direct " << TRI->getName(Loc.Reg);
434 dbgs() << " + " << Loc.Offset;
436 case Location::Indirect:
437 dbgs() << "Indirect " << TRI->getName(Loc.Reg)
438 << " + " << Loc.Offset;
440 case Location::Constant:
441 dbgs() << "Constant " << Loc.Offset;
443 case Location::ConstantIndex:
444 dbgs() << "Constant Index " << Loc.Offset;
447 dbgs() << " [encoding: .byte " << Loc.LocType
448 << ", .byte " << Loc.Size
449 << ", .short " << RegNo
450 << ", .int " << Offset << "]\n";
453 OS.EmitIntValue(Loc.LocType, 1);
454 OS.EmitIntValue(Loc.Size, 1);
455 OS.EmitIntValue(RegNo, 2);
456 OS.EmitIntValue(Offset, 4);
460 DEBUG(dbgs() << WSMP << " has " << LiveOuts.size()
461 << " live-out registers\n");
463 // Num live-out registers and padding to align to 4 byte.
464 OS.EmitIntValue(0, 2);
465 OS.EmitIntValue(LiveOuts.size(), 2);
468 for (const auto &LO : LiveOuts) {
469 DEBUG(dbgs() << WSMP << " LO " << OperIdx << ": "
470 << TRI->getName(LO.Reg)
471 << " [encoding: .short " << LO.RegNo
472 << ", .byte 0, .byte " << LO.Size << "]\n");
473 OS.EmitIntValue(LO.RegNo, 2);
474 OS.EmitIntValue(0, 1);
475 OS.EmitIntValue(LO.Size, 1);
477 // Emit alignment to 8 byte.
478 OS.EmitValueToAlignment(8);
482 /// Serialize the stackmap data.
483 void StackMaps::serializeToStackMapSection() {
485 // Bail out if there's no stack map data.
486 assert((!CSInfos.empty() || (CSInfos.empty() && ConstPool.empty())) &&
487 "Expected empty constant pool too!");
488 assert((!CSInfos.empty() || (CSInfos.empty() && FnStackSize.empty())) &&
489 "Expected empty function record too!");
493 MCContext &OutContext = AP.OutStreamer.getContext();
494 MCStreamer &OS = AP.OutStreamer;
495 const TargetRegisterInfo *TRI = AP.TM.getSubtargetImpl()->getRegisterInfo();
497 // Create the section.
498 const MCSection *StackMapSection =
499 OutContext.getObjectFileInfo()->getStackMapSection();
500 OS.SwitchSection(StackMapSection);
502 // Emit a dummy symbol to force section inclusion.
503 OS.EmitLabel(OutContext.GetOrCreateSymbol(Twine("__LLVM_StackMaps")));
506 DEBUG(dbgs() << "********** Stack Map Output **********\n");
507 emitStackmapHeader(OS);
508 emitFunctionFrameRecords(OS);
509 emitConstantPoolEntries(OS);
510 emitCallsiteEntries(OS, TRI);