1f785676fSDimitry Andric //===---------------------------- StackMaps.cpp ---------------------------===//
2f785676fSDimitry Andric //
3f785676fSDimitry Andric //                     The LLVM Compiler Infrastructure
4f785676fSDimitry Andric //
5f785676fSDimitry Andric // This file is distributed under the University of Illinois Open Source
6f785676fSDimitry Andric // License. See LICENSE.TXT for details.
7f785676fSDimitry Andric //
8f785676fSDimitry Andric //===----------------------------------------------------------------------===//
9f785676fSDimitry Andric 
10f785676fSDimitry Andric #include "llvm/CodeGen/StackMaps.h"
11f785676fSDimitry Andric #include "llvm/CodeGen/AsmPrinter.h"
1291bc56edSDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
1391bc56edSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
14f785676fSDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
1591bc56edSDimitry Andric #include "llvm/IR/DataLayout.h"
16f785676fSDimitry Andric #include "llvm/MC/MCContext.h"
17f785676fSDimitry Andric #include "llvm/MC/MCExpr.h"
18f785676fSDimitry Andric #include "llvm/MC/MCObjectFileInfo.h"
19f785676fSDimitry Andric #include "llvm/MC/MCSectionMachO.h"
20f785676fSDimitry Andric #include "llvm/MC/MCStreamer.h"
2191bc56edSDimitry Andric #include "llvm/Support/CommandLine.h"
22f785676fSDimitry Andric #include "llvm/Target/TargetMachine.h"
2391bc56edSDimitry Andric #include "llvm/Target/TargetOpcodes.h"
24f785676fSDimitry Andric #include "llvm/Target/TargetRegisterInfo.h"
2539d628a0SDimitry Andric #include "llvm/Target/TargetSubtargetInfo.h"
26f785676fSDimitry Andric #include <iterator>
27f785676fSDimitry Andric 
28f785676fSDimitry Andric using namespace llvm;
29f785676fSDimitry Andric 
3091bc56edSDimitry Andric #define DEBUG_TYPE "stackmaps"
3191bc56edSDimitry Andric 
32875ed548SDimitry Andric static cl::opt<int> StackMapVersion(
33875ed548SDimitry Andric     "stackmap-version", cl::init(1),
3491bc56edSDimitry Andric     cl::desc("Specify the stackmap encoding version (default = 1)"));
3591bc56edSDimitry Andric 
3691bc56edSDimitry Andric const char *StackMaps::WSMP = "Stack Maps: ";
3791bc56edSDimitry Andric 
3891bc56edSDimitry Andric PatchPointOpers::PatchPointOpers(const MachineInstr *MI)
39875ed548SDimitry Andric     : MI(MI), HasDef(MI->getOperand(0).isReg() && MI->getOperand(0).isDef() &&
40f785676fSDimitry Andric                      !MI->getOperand(0).isImplicit()),
41875ed548SDimitry Andric       IsAnyReg(MI->getOperand(getMetaIdx(CCPos)).getImm() ==
42875ed548SDimitry Andric                CallingConv::AnyReg) {
4391bc56edSDimitry Andric #ifndef NDEBUG
44f785676fSDimitry Andric   unsigned CheckStartIdx = 0, e = MI->getNumOperands();
45f785676fSDimitry Andric   while (CheckStartIdx < e && MI->getOperand(CheckStartIdx).isReg() &&
46f785676fSDimitry Andric          MI->getOperand(CheckStartIdx).isDef() &&
47f785676fSDimitry Andric          !MI->getOperand(CheckStartIdx).isImplicit())
48f785676fSDimitry Andric     ++CheckStartIdx;
49f785676fSDimitry Andric 
50f785676fSDimitry Andric   assert(getMetaIdx() == CheckStartIdx &&
5191bc56edSDimitry Andric          "Unexpected additional definition in Patchpoint intrinsic.");
52f785676fSDimitry Andric #endif
53f785676fSDimitry Andric }
54f785676fSDimitry Andric 
55f785676fSDimitry Andric unsigned PatchPointOpers::getNextScratchIdx(unsigned StartIdx) const {
56f785676fSDimitry Andric   if (!StartIdx)
57f785676fSDimitry Andric     StartIdx = getVarIdx();
58f785676fSDimitry Andric 
59f785676fSDimitry Andric   // Find the next scratch register (implicit def and early clobber)
60f785676fSDimitry Andric   unsigned ScratchIdx = StartIdx, e = MI->getNumOperands();
61f785676fSDimitry Andric   while (ScratchIdx < e &&
62f785676fSDimitry Andric          !(MI->getOperand(ScratchIdx).isReg() &&
63f785676fSDimitry Andric            MI->getOperand(ScratchIdx).isDef() &&
64f785676fSDimitry Andric            MI->getOperand(ScratchIdx).isImplicit() &&
65f785676fSDimitry Andric            MI->getOperand(ScratchIdx).isEarlyClobber()))
66f785676fSDimitry Andric     ++ScratchIdx;
67f785676fSDimitry Andric 
68f785676fSDimitry Andric   assert(ScratchIdx != e && "No scratch register available");
69f785676fSDimitry Andric   return ScratchIdx;
70f785676fSDimitry Andric }
71f785676fSDimitry Andric 
7291bc56edSDimitry Andric StackMaps::StackMaps(AsmPrinter &AP) : AP(AP) {
7391bc56edSDimitry Andric   if (StackMapVersion != 1)
7491bc56edSDimitry Andric     llvm_unreachable("Unsupported stackmap version!");
7591bc56edSDimitry Andric }
7691bc56edSDimitry Andric 
77ff0cc061SDimitry Andric /// Go up the super-register chain until we hit a valid dwarf register number.
78ff0cc061SDimitry Andric static unsigned getDwarfRegNum(unsigned Reg, const TargetRegisterInfo *TRI) {
79875ed548SDimitry Andric   int RegNum = TRI->getDwarfRegNum(Reg, false);
80875ed548SDimitry Andric   for (MCSuperRegIterator SR(Reg, TRI); SR.isValid() && RegNum < 0; ++SR)
81875ed548SDimitry Andric     RegNum = TRI->getDwarfRegNum(*SR, false);
82ff0cc061SDimitry Andric 
83875ed548SDimitry Andric   assert(RegNum >= 0 && "Invalid Dwarf register number.");
84875ed548SDimitry Andric   return (unsigned)RegNum;
85ff0cc061SDimitry Andric }
86ff0cc061SDimitry Andric 
8791bc56edSDimitry Andric MachineInstr::const_mop_iterator
8891bc56edSDimitry Andric StackMaps::parseOperand(MachineInstr::const_mop_iterator MOI,
89875ed548SDimitry Andric                         MachineInstr::const_mop_iterator MOE, LocationVec &Locs,
90875ed548SDimitry Andric                         LiveOutVec &LiveOuts) const {
91ff0cc061SDimitry Andric   const TargetRegisterInfo *TRI = AP.MF->getSubtarget().getRegisterInfo();
9291bc56edSDimitry Andric   if (MOI->isImm()) {
9391bc56edSDimitry Andric     switch (MOI->getImm()) {
94875ed548SDimitry Andric     default:
95875ed548SDimitry Andric       llvm_unreachable("Unrecognized operand type.");
9691bc56edSDimitry Andric     case StackMaps::DirectMemRefOp: {
97ff0cc061SDimitry Andric       unsigned Size = AP.TM.getDataLayout()->getPointerSizeInBits();
9891bc56edSDimitry Andric       assert((Size % 8) == 0 && "Need pointer size in bytes.");
9991bc56edSDimitry Andric       Size /= 8;
10091bc56edSDimitry Andric       unsigned Reg = (++MOI)->getReg();
10191bc56edSDimitry Andric       int64_t Imm = (++MOI)->getImm();
102875ed548SDimitry Andric       Locs.emplace_back(StackMaps::Location::Direct, Size,
103875ed548SDimitry Andric                         getDwarfRegNum(Reg, TRI), Imm);
10491bc56edSDimitry Andric       break;
10591bc56edSDimitry Andric     }
10691bc56edSDimitry Andric     case StackMaps::IndirectMemRefOp: {
10791bc56edSDimitry Andric       int64_t Size = (++MOI)->getImm();
10891bc56edSDimitry Andric       assert(Size > 0 && "Need a valid size for indirect memory locations.");
10991bc56edSDimitry Andric       unsigned Reg = (++MOI)->getReg();
11091bc56edSDimitry Andric       int64_t Imm = (++MOI)->getImm();
111875ed548SDimitry Andric       Locs.emplace_back(StackMaps::Location::Indirect, Size,
112875ed548SDimitry Andric                         getDwarfRegNum(Reg, TRI), Imm);
11391bc56edSDimitry Andric       break;
11491bc56edSDimitry Andric     }
11591bc56edSDimitry Andric     case StackMaps::ConstantOp: {
11691bc56edSDimitry Andric       ++MOI;
11791bc56edSDimitry Andric       assert(MOI->isImm() && "Expected constant operand.");
11891bc56edSDimitry Andric       int64_t Imm = MOI->getImm();
119875ed548SDimitry Andric       Locs.emplace_back(Location::Constant, sizeof(int64_t), 0, Imm);
12091bc56edSDimitry Andric       break;
12191bc56edSDimitry Andric     }
12291bc56edSDimitry Andric     }
12391bc56edSDimitry Andric     return ++MOI;
12491bc56edSDimitry Andric   }
12591bc56edSDimitry Andric 
12691bc56edSDimitry Andric   // The physical register number will ultimately be encoded as a DWARF regno.
12791bc56edSDimitry Andric   // The stack map also records the size of a spill slot that can hold the
12891bc56edSDimitry Andric   // register content. (The runtime can track the actual size of the data type
12991bc56edSDimitry Andric   // if it needs to.)
13091bc56edSDimitry Andric   if (MOI->isReg()) {
13191bc56edSDimitry Andric     // Skip implicit registers (this includes our scratch registers)
13291bc56edSDimitry Andric     if (MOI->isImplicit())
13391bc56edSDimitry Andric       return ++MOI;
13491bc56edSDimitry Andric 
13591bc56edSDimitry Andric     assert(TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) &&
13691bc56edSDimitry Andric            "Virtreg operands should have been rewritten before now.");
137ff0cc061SDimitry Andric     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(MOI->getReg());
13891bc56edSDimitry Andric     assert(!MOI->getSubReg() && "Physical subreg still around.");
139ff0cc061SDimitry Andric 
140ff0cc061SDimitry Andric     unsigned Offset = 0;
141875ed548SDimitry Andric     unsigned DwarfRegNum = getDwarfRegNum(MOI->getReg(), TRI);
142875ed548SDimitry Andric     unsigned LLVMRegNum = TRI->getLLVMRegNum(DwarfRegNum, false);
143875ed548SDimitry Andric     unsigned SubRegIdx = TRI->getSubRegIndex(LLVMRegNum, MOI->getReg());
144ff0cc061SDimitry Andric     if (SubRegIdx)
145ff0cc061SDimitry Andric       Offset = TRI->getSubRegIdxOffset(SubRegIdx);
146ff0cc061SDimitry Andric 
147875ed548SDimitry Andric     Locs.emplace_back(Location::Register, RC->getSize(), DwarfRegNum, Offset);
14891bc56edSDimitry Andric     return ++MOI;
14991bc56edSDimitry Andric   }
15091bc56edSDimitry Andric 
15191bc56edSDimitry Andric   if (MOI->isRegLiveOut())
15291bc56edSDimitry Andric     LiveOuts = parseRegisterLiveOutMask(MOI->getRegLiveOut());
15391bc56edSDimitry Andric 
15491bc56edSDimitry Andric   return ++MOI;
15591bc56edSDimitry Andric }
15691bc56edSDimitry Andric 
157ff0cc061SDimitry Andric void StackMaps::print(raw_ostream &OS) {
158ff0cc061SDimitry Andric   const TargetRegisterInfo *TRI =
159ff0cc061SDimitry Andric       AP.MF ? AP.MF->getSubtarget().getRegisterInfo() : nullptr;
160ff0cc061SDimitry Andric   OS << WSMP << "callsites:\n";
161ff0cc061SDimitry Andric   for (const auto &CSI : CSInfos) {
162ff0cc061SDimitry Andric     const LocationVec &CSLocs = CSI.Locations;
163ff0cc061SDimitry Andric     const LiveOutVec &LiveOuts = CSI.LiveOuts;
16491bc56edSDimitry Andric 
165ff0cc061SDimitry Andric     OS << WSMP << "callsite " << CSI.ID << "\n";
166ff0cc061SDimitry Andric     OS << WSMP << "  has " << CSLocs.size() << " locations\n";
167ff0cc061SDimitry Andric 
168875ed548SDimitry Andric     unsigned Idx = 0;
169ff0cc061SDimitry Andric     for (const auto &Loc : CSLocs) {
170875ed548SDimitry Andric       OS << WSMP << "\t\tLoc " << Idx << ": ";
171875ed548SDimitry Andric       switch (Loc.Type) {
172ff0cc061SDimitry Andric       case Location::Unprocessed:
173ff0cc061SDimitry Andric         OS << "<Unprocessed operand>";
174ff0cc061SDimitry Andric         break;
175ff0cc061SDimitry Andric       case Location::Register:
176ff0cc061SDimitry Andric         OS << "Register ";
177ff0cc061SDimitry Andric         if (TRI)
178ff0cc061SDimitry Andric           OS << TRI->getName(Loc.Reg);
179ff0cc061SDimitry Andric         else
180ff0cc061SDimitry Andric           OS << Loc.Reg;
181ff0cc061SDimitry Andric         break;
182ff0cc061SDimitry Andric       case Location::Direct:
183ff0cc061SDimitry Andric         OS << "Direct ";
184ff0cc061SDimitry Andric         if (TRI)
185ff0cc061SDimitry Andric           OS << TRI->getName(Loc.Reg);
186ff0cc061SDimitry Andric         else
187ff0cc061SDimitry Andric           OS << Loc.Reg;
188ff0cc061SDimitry Andric         if (Loc.Offset)
189ff0cc061SDimitry Andric           OS << " + " << Loc.Offset;
190ff0cc061SDimitry Andric         break;
191ff0cc061SDimitry Andric       case Location::Indirect:
192ff0cc061SDimitry Andric         OS << "Indirect ";
193ff0cc061SDimitry Andric         if (TRI)
194ff0cc061SDimitry Andric           OS << TRI->getName(Loc.Reg);
195ff0cc061SDimitry Andric         else
196ff0cc061SDimitry Andric           OS << Loc.Reg;
197ff0cc061SDimitry Andric         OS << "+" << Loc.Offset;
198ff0cc061SDimitry Andric         break;
199ff0cc061SDimitry Andric       case Location::Constant:
200ff0cc061SDimitry Andric         OS << "Constant " << Loc.Offset;
201ff0cc061SDimitry Andric         break;
202ff0cc061SDimitry Andric       case Location::ConstantIndex:
203ff0cc061SDimitry Andric         OS << "Constant Index " << Loc.Offset;
204ff0cc061SDimitry Andric         break;
205ff0cc061SDimitry Andric       }
206875ed548SDimitry Andric       OS << "\t[encoding: .byte " << Loc.Type << ", .byte " << Loc.Size
207ff0cc061SDimitry Andric          << ", .short " << Loc.Reg << ", .int " << Loc.Offset << "]\n";
208875ed548SDimitry Andric       Idx++;
209ff0cc061SDimitry Andric     }
210ff0cc061SDimitry Andric 
211875ed548SDimitry Andric     OS << WSMP << "\thas " << LiveOuts.size() << " live-out registers\n";
212ff0cc061SDimitry Andric 
213875ed548SDimitry Andric     Idx = 0;
214ff0cc061SDimitry Andric     for (const auto &LO : LiveOuts) {
215875ed548SDimitry Andric       OS << WSMP << "\t\tLO " << Idx << ": ";
216ff0cc061SDimitry Andric       if (TRI)
217ff0cc061SDimitry Andric         OS << TRI->getName(LO.Reg);
218ff0cc061SDimitry Andric       else
219ff0cc061SDimitry Andric         OS << LO.Reg;
220875ed548SDimitry Andric       OS << "\t[encoding: .short " << LO.DwarfRegNum << ", .byte 0, .byte "
221ff0cc061SDimitry Andric          << LO.Size << "]\n";
222875ed548SDimitry Andric       Idx++;
223ff0cc061SDimitry Andric     }
224ff0cc061SDimitry Andric   }
22591bc56edSDimitry Andric }
22691bc56edSDimitry Andric 
22791bc56edSDimitry Andric /// Create a live-out register record for the given register Reg.
22891bc56edSDimitry Andric StackMaps::LiveOutReg
22991bc56edSDimitry Andric StackMaps::createLiveOutReg(unsigned Reg, const TargetRegisterInfo *TRI) const {
230875ed548SDimitry Andric   unsigned DwarfRegNum = getDwarfRegNum(Reg, TRI);
23191bc56edSDimitry Andric   unsigned Size = TRI->getMinimalPhysRegClass(Reg)->getSize();
232875ed548SDimitry Andric   return LiveOutReg(Reg, DwarfRegNum, Size);
23391bc56edSDimitry Andric }
23491bc56edSDimitry Andric 
23591bc56edSDimitry Andric /// Parse the register live-out mask and return a vector of live-out registers
23691bc56edSDimitry Andric /// that need to be recorded in the stackmap.
23791bc56edSDimitry Andric StackMaps::LiveOutVec
23891bc56edSDimitry Andric StackMaps::parseRegisterLiveOutMask(const uint32_t *Mask) const {
23991bc56edSDimitry Andric   assert(Mask && "No register mask specified");
240ff0cc061SDimitry Andric   const TargetRegisterInfo *TRI = AP.MF->getSubtarget().getRegisterInfo();
24191bc56edSDimitry Andric   LiveOutVec LiveOuts;
24291bc56edSDimitry Andric 
24391bc56edSDimitry Andric   // Create a LiveOutReg for each bit that is set in the register mask.
24491bc56edSDimitry Andric   for (unsigned Reg = 0, NumRegs = TRI->getNumRegs(); Reg != NumRegs; ++Reg)
24591bc56edSDimitry Andric     if ((Mask[Reg / 32] >> Reg % 32) & 1)
24691bc56edSDimitry Andric       LiveOuts.push_back(createLiveOutReg(Reg, TRI));
24791bc56edSDimitry Andric 
24891bc56edSDimitry Andric   // We don't need to keep track of a register if its super-register is already
24991bc56edSDimitry Andric   // in the list. Merge entries that refer to the same dwarf register and use
25091bc56edSDimitry Andric   // the maximum size that needs to be spilled.
251875ed548SDimitry Andric 
252875ed548SDimitry Andric   std::sort(LiveOuts.begin(), LiveOuts.end(),
253875ed548SDimitry Andric             [](const LiveOutReg &LHS, const LiveOutReg &RHS) {
254875ed548SDimitry Andric               // Only sort by the dwarf register number.
255875ed548SDimitry Andric               return LHS.DwarfRegNum < RHS.DwarfRegNum;
256875ed548SDimitry Andric             });
257875ed548SDimitry Andric 
258875ed548SDimitry Andric   for (auto I = LiveOuts.begin(), E = LiveOuts.end(); I != E; ++I) {
259875ed548SDimitry Andric     for (auto II = std::next(I); II != E; ++II) {
260875ed548SDimitry Andric       if (I->DwarfRegNum != II->DwarfRegNum) {
26191bc56edSDimitry Andric         // Skip all the now invalid entries.
26291bc56edSDimitry Andric         I = --II;
26391bc56edSDimitry Andric         break;
26491bc56edSDimitry Andric       }
26591bc56edSDimitry Andric       I->Size = std::max(I->Size, II->Size);
26691bc56edSDimitry Andric       if (TRI->isSuperRegister(I->Reg, II->Reg))
26791bc56edSDimitry Andric         I->Reg = II->Reg;
268875ed548SDimitry Andric       II->Reg = 0; // mark for deletion.
26991bc56edSDimitry Andric     }
27091bc56edSDimitry Andric   }
271875ed548SDimitry Andric 
272875ed548SDimitry Andric   LiveOuts.erase(
273875ed548SDimitry Andric       std::remove_if(LiveOuts.begin(), LiveOuts.end(),
274875ed548SDimitry Andric                      [](const LiveOutReg &LO) { return LO.Reg == 0; }),
275875ed548SDimitry Andric       LiveOuts.end());
276875ed548SDimitry Andric 
27791bc56edSDimitry Andric   return LiveOuts;
27891bc56edSDimitry Andric }
27991bc56edSDimitry Andric 
28091bc56edSDimitry Andric void StackMaps::recordStackMapOpers(const MachineInstr &MI, uint64_t ID,
281f785676fSDimitry Andric                                     MachineInstr::const_mop_iterator MOI,
282f785676fSDimitry Andric                                     MachineInstr::const_mop_iterator MOE,
283f785676fSDimitry Andric                                     bool recordResult) {
284f785676fSDimitry Andric 
285ff0cc061SDimitry Andric   MCContext &OutContext = AP.OutStreamer->getContext();
286ff0cc061SDimitry Andric   MCSymbol *MILabel = OutContext.createTempSymbol();
287ff0cc061SDimitry Andric   AP.OutStreamer->EmitLabel(MILabel);
288f785676fSDimitry Andric 
28991bc56edSDimitry Andric   LocationVec Locations;
29091bc56edSDimitry Andric   LiveOutVec LiveOuts;
291f785676fSDimitry Andric 
292f785676fSDimitry Andric   if (recordResult) {
29391bc56edSDimitry Andric     assert(PatchPointOpers(&MI).hasDef() && "Stackmap has no return value.");
294875ed548SDimitry Andric     parseOperand(MI.operands_begin(), std::next(MI.operands_begin()), Locations,
295875ed548SDimitry Andric                  LiveOuts);
296f785676fSDimitry Andric   }
297f785676fSDimitry Andric 
29891bc56edSDimitry Andric   // Parse operands.
299f785676fSDimitry Andric   while (MOI != MOE) {
30091bc56edSDimitry Andric     MOI = parseOperand(MOI, MOE, Locations, LiveOuts);
30191bc56edSDimitry Andric   }
302f785676fSDimitry Andric 
303f785676fSDimitry Andric   // Move large constants into the constant pool.
304875ed548SDimitry Andric   for (auto &Loc : Locations) {
30591bc56edSDimitry Andric     // Constants are encoded as sign-extended integers.
30691bc56edSDimitry Andric     // -1 is directly encoded as .long 0xFFFFFFFF with no constant pool.
307875ed548SDimitry Andric     if (Loc.Type == Location::Constant && !isInt<32>(Loc.Offset)) {
308875ed548SDimitry Andric       Loc.Type = Location::ConstantIndex;
30939d628a0SDimitry Andric       // ConstPool is intentionally a MapVector of 'uint64_t's (as
31039d628a0SDimitry Andric       // opposed to 'int64_t's).  We should never be in a situation
31139d628a0SDimitry Andric       // where we have to insert either the tombstone or the empty
31239d628a0SDimitry Andric       // keys into a map, and for a DenseMap<uint64_t, T> these are
31339d628a0SDimitry Andric       // (uint64_t)0 and (uint64_t)-1.  They can be and are
31439d628a0SDimitry Andric       // represented using 32 bit integers.
315875ed548SDimitry Andric       assert((uint64_t)Loc.Offset != DenseMapInfo<uint64_t>::getEmptyKey() &&
316875ed548SDimitry Andric              (uint64_t)Loc.Offset !=
317875ed548SDimitry Andric                  DenseMapInfo<uint64_t>::getTombstoneKey() &&
31839d628a0SDimitry Andric              "empty and tombstone keys should fit in 32 bits!");
319875ed548SDimitry Andric       auto Result = ConstPool.insert(std::make_pair(Loc.Offset, Loc.Offset));
320875ed548SDimitry Andric       Loc.Offset = Result.first - ConstPool.begin();
32191bc56edSDimitry Andric     }
322f785676fSDimitry Andric   }
323f785676fSDimitry Andric 
32491bc56edSDimitry Andric   // Create an expression to calculate the offset of the callsite from function
32591bc56edSDimitry Andric   // entry.
32697bc6c73SDimitry Andric   const MCExpr *CSOffsetExpr = MCBinaryExpr::createSub(
32797bc6c73SDimitry Andric       MCSymbolRefExpr::create(MILabel, OutContext),
328875ed548SDimitry Andric       MCSymbolRefExpr::create(AP.CurrentFnSymForSize, OutContext), OutContext);
329f785676fSDimitry Andric 
33039d628a0SDimitry Andric   CSInfos.emplace_back(CSOffsetExpr, ID, std::move(Locations),
33139d628a0SDimitry Andric                        std::move(LiveOuts));
332f785676fSDimitry Andric 
33391bc56edSDimitry Andric   // Record the stack size of the current function.
33491bc56edSDimitry Andric   const MachineFrameInfo *MFI = AP.MF->getFrameInfo();
33539d628a0SDimitry Andric   const TargetRegisterInfo *RegInfo = AP.MF->getSubtarget().getRegisterInfo();
336875ed548SDimitry Andric   bool HasDynamicFrameSize =
337875ed548SDimitry Andric       MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(*(AP.MF));
33891bc56edSDimitry Andric   FnStackSize[AP.CurrentFnSym] =
339875ed548SDimitry Andric       HasDynamicFrameSize ? UINT64_MAX : MFI->getStackSize();
340f785676fSDimitry Andric }
341f785676fSDimitry Andric 
342f785676fSDimitry Andric void StackMaps::recordStackMap(const MachineInstr &MI) {
34391bc56edSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::STACKMAP && "expected stackmap");
344f785676fSDimitry Andric 
345f785676fSDimitry Andric   int64_t ID = MI.getOperand(0).getImm();
34691bc56edSDimitry Andric   recordStackMapOpers(MI, ID, std::next(MI.operands_begin(), 2),
34791bc56edSDimitry Andric                       MI.operands_end());
348f785676fSDimitry Andric }
349f785676fSDimitry Andric 
350f785676fSDimitry Andric void StackMaps::recordPatchPoint(const MachineInstr &MI) {
35191bc56edSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::PATCHPOINT && "expected patchpoint");
352f785676fSDimitry Andric 
353f785676fSDimitry Andric   PatchPointOpers opers(&MI);
354f785676fSDimitry Andric   int64_t ID = opers.getMetaOper(PatchPointOpers::IDPos).getImm();
35591bc56edSDimitry Andric 
356875ed548SDimitry Andric   auto MOI = std::next(MI.operands_begin(), opers.getStackMapStartIdx());
35791bc56edSDimitry Andric   recordStackMapOpers(MI, ID, MOI, MI.operands_end(),
358f785676fSDimitry Andric                       opers.isAnyReg() && opers.hasDef());
359f785676fSDimitry Andric 
360f785676fSDimitry Andric #ifndef NDEBUG
361f785676fSDimitry Andric   // verify anyregcc
362875ed548SDimitry Andric   auto &Locations = CSInfos.back().Locations;
363f785676fSDimitry Andric   if (opers.isAnyReg()) {
364f785676fSDimitry Andric     unsigned NArgs = opers.getMetaOper(PatchPointOpers::NArgPos).getImm();
365f785676fSDimitry Andric     for (unsigned i = 0, e = (opers.hasDef() ? NArgs + 1 : NArgs); i != e; ++i)
366875ed548SDimitry Andric       assert(Locations[i].Type == Location::Register &&
367f785676fSDimitry Andric              "anyreg arg must be in reg.");
368f785676fSDimitry Andric   }
369f785676fSDimitry Andric #endif
370f785676fSDimitry Andric }
37139d628a0SDimitry Andric void StackMaps::recordStatepoint(const MachineInstr &MI) {
372875ed548SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::STATEPOINT && "expected statepoint");
37339d628a0SDimitry Andric 
37439d628a0SDimitry Andric   StatepointOpers opers(&MI);
37539d628a0SDimitry Andric   // Record all the deopt and gc operands (they're contiguous and run from the
37639d628a0SDimitry Andric   // initial index to the end of the operand list)
37739d628a0SDimitry Andric   const unsigned StartIdx = opers.getVarIdx();
378ff0cc061SDimitry Andric   recordStackMapOpers(MI, opers.getID(), MI.operands_begin() + StartIdx,
379ff0cc061SDimitry Andric                       MI.operands_end(), false);
38039d628a0SDimitry Andric }
381f785676fSDimitry Andric 
38291bc56edSDimitry Andric /// Emit the stackmap header.
383f785676fSDimitry Andric ///
38491bc56edSDimitry Andric /// Header {
38591bc56edSDimitry Andric ///   uint8  : Stack Map Version (currently 1)
38691bc56edSDimitry Andric ///   uint8  : Reserved (expected to be 0)
38791bc56edSDimitry Andric ///   uint16 : Reserved (expected to be 0)
38891bc56edSDimitry Andric /// }
38991bc56edSDimitry Andric /// uint32 : NumFunctions
390f785676fSDimitry Andric /// uint32 : NumConstants
391f785676fSDimitry Andric /// uint32 : NumRecords
39291bc56edSDimitry Andric void StackMaps::emitStackmapHeader(MCStreamer &OS) {
39391bc56edSDimitry Andric   // Header.
39491bc56edSDimitry Andric   OS.EmitIntValue(StackMapVersion, 1); // Version.
39591bc56edSDimitry Andric   OS.EmitIntValue(0, 1);               // Reserved.
39691bc56edSDimitry Andric   OS.EmitIntValue(0, 2);               // Reserved.
39791bc56edSDimitry Andric 
39891bc56edSDimitry Andric   // Num functions.
39991bc56edSDimitry Andric   DEBUG(dbgs() << WSMP << "#functions = " << FnStackSize.size() << '\n');
40091bc56edSDimitry Andric   OS.EmitIntValue(FnStackSize.size(), 4);
40191bc56edSDimitry Andric   // Num constants.
40291bc56edSDimitry Andric   DEBUG(dbgs() << WSMP << "#constants = " << ConstPool.size() << '\n');
40391bc56edSDimitry Andric   OS.EmitIntValue(ConstPool.size(), 4);
40491bc56edSDimitry Andric   // Num callsites.
40591bc56edSDimitry Andric   DEBUG(dbgs() << WSMP << "#callsites = " << CSInfos.size() << '\n');
40691bc56edSDimitry Andric   OS.EmitIntValue(CSInfos.size(), 4);
40791bc56edSDimitry Andric }
40891bc56edSDimitry Andric 
40991bc56edSDimitry Andric /// Emit the function frame record for each function.
41091bc56edSDimitry Andric ///
41191bc56edSDimitry Andric /// StkSizeRecord[NumFunctions] {
41291bc56edSDimitry Andric ///   uint64 : Function Address
41391bc56edSDimitry Andric ///   uint64 : Stack Size
41491bc56edSDimitry Andric /// }
41591bc56edSDimitry Andric void StackMaps::emitFunctionFrameRecords(MCStreamer &OS) {
41691bc56edSDimitry Andric   // Function Frame records.
41791bc56edSDimitry Andric   DEBUG(dbgs() << WSMP << "functions:\n");
41891bc56edSDimitry Andric   for (auto const &FR : FnStackSize) {
41991bc56edSDimitry Andric     DEBUG(dbgs() << WSMP << "function addr: " << FR.first
42091bc56edSDimitry Andric                  << " frame size: " << FR.second);
42191bc56edSDimitry Andric     OS.EmitSymbolValue(FR.first, 8);
42291bc56edSDimitry Andric     OS.EmitIntValue(FR.second, 8);
42391bc56edSDimitry Andric   }
42491bc56edSDimitry Andric }
42591bc56edSDimitry Andric 
42691bc56edSDimitry Andric /// Emit the constant pool.
42791bc56edSDimitry Andric ///
42891bc56edSDimitry Andric /// int64  : Constants[NumConstants]
42991bc56edSDimitry Andric void StackMaps::emitConstantPoolEntries(MCStreamer &OS) {
43091bc56edSDimitry Andric   // Constant pool entries.
43191bc56edSDimitry Andric   DEBUG(dbgs() << WSMP << "constants:\n");
432875ed548SDimitry Andric   for (const auto &ConstEntry : ConstPool) {
43391bc56edSDimitry Andric     DEBUG(dbgs() << WSMP << ConstEntry.second << '\n');
43491bc56edSDimitry Andric     OS.EmitIntValue(ConstEntry.second, 8);
43591bc56edSDimitry Andric   }
43691bc56edSDimitry Andric }
43791bc56edSDimitry Andric 
43891bc56edSDimitry Andric /// Emit the callsite info for each callsite.
43991bc56edSDimitry Andric ///
440f785676fSDimitry Andric /// StkMapRecord[NumRecords] {
44191bc56edSDimitry Andric ///   uint64 : PatchPoint ID
442f785676fSDimitry Andric ///   uint32 : Instruction Offset
443f785676fSDimitry Andric ///   uint16 : Reserved (record flags)
444f785676fSDimitry Andric ///   uint16 : NumLocations
445f785676fSDimitry Andric ///   Location[NumLocations] {
446f785676fSDimitry Andric ///     uint8  : Register | Direct | Indirect | Constant | ConstantIndex
447f785676fSDimitry Andric ///     uint8  : Size in Bytes
448f785676fSDimitry Andric ///     uint16 : Dwarf RegNum
449f785676fSDimitry Andric ///     int32  : Offset
450f785676fSDimitry Andric ///   }
45191bc56edSDimitry Andric ///   uint16 : Padding
45291bc56edSDimitry Andric ///   uint16 : NumLiveOuts
45391bc56edSDimitry Andric ///   LiveOuts[NumLiveOuts] {
45491bc56edSDimitry Andric ///     uint16 : Dwarf RegNum
45591bc56edSDimitry Andric ///     uint8  : Reserved
45691bc56edSDimitry Andric ///     uint8  : Size in Bytes
45791bc56edSDimitry Andric ///   }
45891bc56edSDimitry Andric ///   uint32 : Padding (only if required to align to 8 byte)
459f785676fSDimitry Andric /// }
460f785676fSDimitry Andric ///
461f785676fSDimitry Andric /// Location Encoding, Type, Value:
462f785676fSDimitry Andric ///   0x1, Register, Reg                 (value in register)
463f785676fSDimitry Andric ///   0x2, Direct, Reg + Offset          (frame index)
464f785676fSDimitry Andric ///   0x3, Indirect, [Reg + Offset]      (spilled value)
465f785676fSDimitry Andric ///   0x4, Constant, Offset              (small constant)
466f785676fSDimitry Andric ///   0x5, ConstIndex, Constants[Offset] (large constant)
467ff0cc061SDimitry Andric void StackMaps::emitCallsiteEntries(MCStreamer &OS) {
468ff0cc061SDimitry Andric   DEBUG(print(dbgs()));
46991bc56edSDimitry Andric   // Callsite entries.
47091bc56edSDimitry Andric   for (const auto &CSI : CSInfos) {
47191bc56edSDimitry Andric     const LocationVec &CSLocs = CSI.Locations;
47291bc56edSDimitry Andric     const LiveOutVec &LiveOuts = CSI.LiveOuts;
473f785676fSDimitry Andric 
474f785676fSDimitry Andric     // Verify stack map entry. It's better to communicate a problem to the
475f785676fSDimitry Andric     // runtime than crash in case of in-process compilation. Currently, we do
476f785676fSDimitry Andric     // simple overflow checks, but we may eventually communicate other
477f785676fSDimitry Andric     // compilation errors this way.
47891bc56edSDimitry Andric     if (CSLocs.size() > UINT16_MAX || LiveOuts.size() > UINT16_MAX) {
47991bc56edSDimitry Andric       OS.EmitIntValue(UINT64_MAX, 8); // Invalid ID.
48091bc56edSDimitry Andric       OS.EmitValue(CSI.CSOffsetExpr, 4);
48191bc56edSDimitry Andric       OS.EmitIntValue(0, 2); // Reserved.
48291bc56edSDimitry Andric       OS.EmitIntValue(0, 2); // 0 locations.
48391bc56edSDimitry Andric       OS.EmitIntValue(0, 2); // padding.
48491bc56edSDimitry Andric       OS.EmitIntValue(0, 2); // 0 live-out registers.
48591bc56edSDimitry Andric       OS.EmitIntValue(0, 4); // padding.
486f785676fSDimitry Andric       continue;
487f785676fSDimitry Andric     }
488f785676fSDimitry Andric 
48991bc56edSDimitry Andric     OS.EmitIntValue(CSI.ID, 8);
49091bc56edSDimitry Andric     OS.EmitValue(CSI.CSOffsetExpr, 4);
491f785676fSDimitry Andric 
492f785676fSDimitry Andric     // Reserved for flags.
49391bc56edSDimitry Andric     OS.EmitIntValue(0, 2);
49491bc56edSDimitry Andric     OS.EmitIntValue(CSLocs.size(), 2);
495f785676fSDimitry Andric 
49691bc56edSDimitry Andric     for (const auto &Loc : CSLocs) {
497875ed548SDimitry Andric       OS.EmitIntValue(Loc.Type, 1);
49891bc56edSDimitry Andric       OS.EmitIntValue(Loc.Size, 1);
499ff0cc061SDimitry Andric       OS.EmitIntValue(Loc.Reg, 2);
500ff0cc061SDimitry Andric       OS.EmitIntValue(Loc.Offset, 4);
501f785676fSDimitry Andric     }
50291bc56edSDimitry Andric 
50391bc56edSDimitry Andric     // Num live-out registers and padding to align to 4 byte.
50491bc56edSDimitry Andric     OS.EmitIntValue(0, 2);
50591bc56edSDimitry Andric     OS.EmitIntValue(LiveOuts.size(), 2);
50691bc56edSDimitry Andric 
50791bc56edSDimitry Andric     for (const auto &LO : LiveOuts) {
508875ed548SDimitry Andric       OS.EmitIntValue(LO.DwarfRegNum, 2);
50991bc56edSDimitry Andric       OS.EmitIntValue(0, 1);
51091bc56edSDimitry Andric       OS.EmitIntValue(LO.Size, 1);
511f785676fSDimitry Andric     }
51291bc56edSDimitry Andric     // Emit alignment to 8 byte.
51391bc56edSDimitry Andric     OS.EmitValueToAlignment(8);
514f785676fSDimitry Andric   }
515f785676fSDimitry Andric }
516f785676fSDimitry Andric 
51791bc56edSDimitry Andric /// Serialize the stackmap data.
51891bc56edSDimitry Andric void StackMaps::serializeToStackMapSection() {
51991bc56edSDimitry Andric   (void)WSMP;
52091bc56edSDimitry Andric   // Bail out if there's no stack map data.
52191bc56edSDimitry Andric   assert((!CSInfos.empty() || (CSInfos.empty() && ConstPool.empty())) &&
52291bc56edSDimitry Andric          "Expected empty constant pool too!");
52391bc56edSDimitry Andric   assert((!CSInfos.empty() || (CSInfos.empty() && FnStackSize.empty())) &&
52491bc56edSDimitry Andric          "Expected empty function record too!");
52591bc56edSDimitry Andric   if (CSInfos.empty())
52691bc56edSDimitry Andric     return;
527f785676fSDimitry Andric 
528ff0cc061SDimitry Andric   MCContext &OutContext = AP.OutStreamer->getContext();
529ff0cc061SDimitry Andric   MCStreamer &OS = *AP.OutStreamer;
53091bc56edSDimitry Andric 
53191bc56edSDimitry Andric   // Create the section.
532ff0cc061SDimitry Andric   MCSection *StackMapSection =
53391bc56edSDimitry Andric       OutContext.getObjectFileInfo()->getStackMapSection();
53491bc56edSDimitry Andric   OS.SwitchSection(StackMapSection);
53591bc56edSDimitry Andric 
53691bc56edSDimitry Andric   // Emit a dummy symbol to force section inclusion.
537ff0cc061SDimitry Andric   OS.EmitLabel(OutContext.getOrCreateSymbol(Twine("__LLVM_StackMaps")));
53891bc56edSDimitry Andric 
53991bc56edSDimitry Andric   // Serialize data.
54091bc56edSDimitry Andric   DEBUG(dbgs() << "********** Stack Map Output **********\n");
54191bc56edSDimitry Andric   emitStackmapHeader(OS);
54291bc56edSDimitry Andric   emitFunctionFrameRecords(OS);
54391bc56edSDimitry Andric   emitConstantPoolEntries(OS);
544ff0cc061SDimitry Andric   emitCallsiteEntries(OS);
54591bc56edSDimitry Andric   OS.AddBlankLine();
54691bc56edSDimitry Andric 
54791bc56edSDimitry Andric   // Clean up.
548f785676fSDimitry Andric   CSInfos.clear();
54991bc56edSDimitry Andric   ConstPool.clear();
550f785676fSDimitry Andric }
551