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