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 #define DEBUG_TYPE "stackmaps"
12 #include "llvm/CodeGen/StackMaps.h"
13 #include "llvm/CodeGen/AsmPrinter.h"
14 #include "llvm/CodeGen/MachineFunction.h"
15 #include "llvm/CodeGen/MachineFrameInfo.h"
16 #include "llvm/CodeGen/MachineInstr.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCObjectFileInfo.h"
21 #include "llvm/MC/MCSectionMachO.h"
22 #include "llvm/MC/MCStreamer.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetOpcodes.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
32 PatchPointOpers::PatchPointOpers(const MachineInstr *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)
39 unsigned CheckStartIdx = 0, e = MI->getNumOperands();
40 while (CheckStartIdx < e && MI->getOperand(CheckStartIdx).isReg() &&
41 MI->getOperand(CheckStartIdx).isDef() &&
42 !MI->getOperand(CheckStartIdx).isImplicit())
45 assert(getMetaIdx() == CheckStartIdx &&
46 "Unexpected additional definition in Patchpoint intrinsic.");
50 unsigned PatchPointOpers::getNextScratchIdx(unsigned StartIdx) const {
52 StartIdx = getVarIdx();
54 // Find the next scratch register (implicit def and early clobber)
55 unsigned ScratchIdx = StartIdx, e = MI->getNumOperands();
56 while (ScratchIdx < e &&
57 !(MI->getOperand(ScratchIdx).isReg() &&
58 MI->getOperand(ScratchIdx).isDef() &&
59 MI->getOperand(ScratchIdx).isImplicit() &&
60 MI->getOperand(ScratchIdx).isEarlyClobber()))
63 assert(ScratchIdx != e && "No scratch register available");
67 MachineInstr::const_mop_iterator
68 StackMaps::parseOperand(MachineInstr::const_mop_iterator MOI,
69 MachineInstr::const_mop_iterator MOE,
70 LocationVec &Locs, LiveOutVec &LiveOuts) const {
72 switch (MOI->getImm()) {
73 default: llvm_unreachable("Unrecognized operand type.");
74 case StackMaps::DirectMemRefOp: {
75 unsigned Size = AP.TM.getDataLayout()->getPointerSizeInBits();
76 assert((Size % 8) == 0 && "Need pointer size in bytes.");
78 unsigned Reg = (++MOI)->getReg();
79 int64_t Imm = (++MOI)->getImm();
80 Locs.push_back(Location(StackMaps::Location::Direct, Size, Reg, Imm));
83 case StackMaps::IndirectMemRefOp: {
84 int64_t Size = (++MOI)->getImm();
85 assert(Size > 0 && "Need a valid size for indirect memory locations.");
86 unsigned Reg = (++MOI)->getReg();
87 int64_t Imm = (++MOI)->getImm();
88 Locs.push_back(Location(StackMaps::Location::Indirect, Size, Reg, Imm));
91 case StackMaps::ConstantOp: {
93 assert(MOI->isImm() && "Expected constant operand.");
94 int64_t Imm = MOI->getImm();
95 Locs.push_back(Location(Location::Constant, sizeof(int64_t), 0, Imm));
102 // The physical register number will ultimately be encoded as a DWARF regno.
103 // The stack map also records the size of a spill slot that can hold the
104 // register content. (The runtime can track the actual size of the data type
107 // Skip implicit registers (this includes our scratch registers)
108 if (MOI->isImplicit())
111 assert(TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) &&
112 "Virtreg operands should have been rewritten before now.");
113 const TargetRegisterClass *RC =
114 AP.TM.getRegisterInfo()->getMinimalPhysRegClass(MOI->getReg());
115 assert(!MOI->getSubReg() && "Physical subreg still around.");
117 Location(Location::Register, RC->getSize(), MOI->getReg(), 0));
121 if (MOI->isRegLiveOut())
122 LiveOuts = parseRegisterLiveOutMask(MOI->getRegLiveOut());
127 /// Go up the super-register chain until we hit a valid dwarf register number.
128 static unsigned short getDwarfRegNum(unsigned Reg, const MCRegisterInfo &MCRI,
129 const TargetRegisterInfo *TRI) {
130 int RegNo = MCRI.getDwarfRegNum(Reg, false);
131 for (MCSuperRegIterator SR(Reg, TRI);
132 SR.isValid() && RegNo < 0; ++SR)
133 RegNo = TRI->getDwarfRegNum(*SR, false);
135 assert(RegNo >= 0 && "Invalid Dwarf register number.");
136 return (unsigned short) RegNo;
139 /// Create a live-out register record for the given register Reg.
140 StackMaps::LiveOutReg
141 StackMaps::createLiveOutReg(unsigned Reg, const MCRegisterInfo &MCRI,
142 const TargetRegisterInfo *TRI) const {
143 unsigned RegNo = getDwarfRegNum(Reg, MCRI, TRI);
144 unsigned Size = TRI->getMinimalPhysRegClass(Reg)->getSize();
145 return LiveOutReg(Reg, RegNo, Size);
148 /// Parse the register live-out mask and return a vector of live-out registers
149 /// that need to be recorded in the stackmap.
150 StackMaps::LiveOutVec
151 StackMaps::parseRegisterLiveOutMask(const uint32_t *Mask) const {
152 assert(Mask && "No register mask specified");
153 const TargetRegisterInfo *TRI = AP.TM.getRegisterInfo();
154 MCContext &OutContext = AP.OutStreamer.getContext();
155 const MCRegisterInfo &MCRI = *OutContext.getRegisterInfo();
158 // Create a LiveOutReg for each bit that is set in the register mask.
159 for (unsigned Reg = 0, NumRegs = TRI->getNumRegs(); Reg != NumRegs; ++Reg)
160 if ((Mask[Reg / 32] >> Reg % 32) & 1)
161 LiveOuts.push_back(createLiveOutReg(Reg, MCRI, TRI));
163 // We don't need to keep track of a register if its super-register is already
164 // in the list. Merge entries that refer to the same dwarf register and use
165 // the maximum size that needs to be spilled.
166 std::sort(LiveOuts.begin(), LiveOuts.end());
167 for (LiveOutVec::iterator I = LiveOuts.begin(), E = LiveOuts.end();
169 for (LiveOutVec::iterator II = next(I); II != E; ++II) {
170 if (I->RegNo != II->RegNo) {
171 // Skip all the now invalid entries.
175 I->Size = std::max(I->Size, II->Size);
176 if (TRI->isSuperRegister(I->Reg, II->Reg))
181 LiveOuts.erase(std::remove_if(LiveOuts.begin(), LiveOuts.end(),
182 LiveOutReg::IsInvalid), LiveOuts.end());
186 void StackMaps::recordStackMapOpers(const MachineInstr &MI, uint64_t ID,
187 MachineInstr::const_mop_iterator MOI,
188 MachineInstr::const_mop_iterator MOE,
191 MCContext &OutContext = AP.OutStreamer.getContext();
192 MCSymbol *MILabel = OutContext.CreateTempSymbol();
193 AP.OutStreamer.EmitLabel(MILabel);
195 LocationVec Locations;
199 assert(PatchPointOpers(&MI).hasDef() && "Stackmap has no return value.");
200 parseOperand(MI.operands_begin(), llvm::next(MI.operands_begin()),
201 Locations, LiveOuts);
206 MOI = parseOperand(MOI, MOE, Locations, LiveOuts);
209 // Move large constants into the constant pool.
210 for (LocationVec::iterator I = Locations.begin(), E = Locations.end();
212 // Constants are encoded as sign-extended integers.
213 // -1 is directly encoded as .long 0xFFFFFFFF with no constant pool.
214 if (I->LocType == Location::Constant &&
215 ((I->Offset + (int64_t(1)<<31)) >> 32) != 0) {
216 I->LocType = Location::ConstantIndex;
217 I->Offset = ConstPool.getConstantIndex(I->Offset);
221 // Create an expression to calculate the offset of the callsite from function
223 const MCExpr *CSOffsetExpr = MCBinaryExpr::CreateSub(
224 MCSymbolRefExpr::Create(MILabel, OutContext),
225 MCSymbolRefExpr::Create(AP.CurrentFnSym, OutContext),
228 CSInfos.push_back(CallsiteInfo(CSOffsetExpr, ID, Locations, LiveOuts));
230 // Record the stack size of the current function.
231 const MachineFrameInfo *MFI = AP.MF->getFrameInfo();
232 FnStackSize[AP.CurrentFnSym] =
233 MFI->hasVarSizedObjects() ? ~0U : MFI->getStackSize();
236 void StackMaps::recordStackMap(const MachineInstr &MI) {
237 assert(MI.getOpcode() == TargetOpcode::STACKMAP && "expected stackmap");
239 int64_t ID = MI.getOperand(0).getImm();
240 recordStackMapOpers(MI, ID, llvm::next(MI.operands_begin(), 2),
244 void StackMaps::recordPatchPoint(const MachineInstr &MI) {
245 assert(MI.getOpcode() == TargetOpcode::PATCHPOINT && "expected patchpoint");
247 PatchPointOpers opers(&MI);
248 int64_t ID = opers.getMetaOper(PatchPointOpers::IDPos).getImm();
250 MachineInstr::const_mop_iterator MOI =
251 llvm::next(MI.operands_begin(), opers.getStackMapStartIdx());
252 recordStackMapOpers(MI, ID, MOI, MI.operands_end(),
253 opers.isAnyReg() && opers.hasDef());
257 LocationVec &Locations = CSInfos.back().Locations;
258 if (opers.isAnyReg()) {
259 unsigned NArgs = opers.getMetaOper(PatchPointOpers::NArgPos).getImm();
260 for (unsigned i = 0, e = (opers.hasDef() ? NArgs+1 : NArgs); i != e; ++i)
261 assert(Locations[i].LocType == Location::Register &&
262 "anyreg arg must be in reg.");
267 /// serializeToStackMapSection conceptually populates the following fields:
269 /// uint32 : Reserved (header)
270 /// uint32 : NumFunctions
271 /// StkSizeRecord[NumFunctions] {
272 /// uint32 : Function Offset
273 /// uint32 : Stack Size
275 /// uint32 : NumConstants
276 /// int64 : Constants[NumConstants]
277 /// uint32 : NumRecords
278 /// StkMapRecord[NumRecords] {
279 /// uint64 : PatchPoint ID
280 /// uint32 : Instruction Offset
281 /// uint16 : Reserved (record flags)
282 /// uint16 : NumLocations
283 /// Location[NumLocations] {
284 /// uint8 : Register | Direct | Indirect | Constant | ConstantIndex
285 /// uint8 : Size in Bytes
286 /// uint16 : Dwarf RegNum
289 /// uint16 : NumLiveOuts
290 /// LiveOuts[NumLiveOuts]
291 /// uint16 : Dwarf RegNum
293 /// uint8 : Size in Bytes
296 /// Location Encoding, Type, Value:
297 /// 0x1, Register, Reg (value in register)
298 /// 0x2, Direct, Reg + Offset (frame index)
299 /// 0x3, Indirect, [Reg + Offset] (spilled value)
300 /// 0x4, Constant, Offset (small constant)
301 /// 0x5, ConstIndex, Constants[Offset] (large constant)
303 void StackMaps::serializeToStackMapSection() {
304 // Bail out if there's no stack map data.
308 MCContext &OutContext = AP.OutStreamer.getContext();
309 const TargetRegisterInfo *TRI = AP.TM.getRegisterInfo();
311 // Create the section.
312 const MCSection *StackMapSection =
313 OutContext.getObjectFileInfo()->getStackMapSection();
314 AP.OutStreamer.SwitchSection(StackMapSection);
316 // Emit a dummy symbol to force section inclusion.
317 AP.OutStreamer.EmitLabel(
318 OutContext.GetOrCreateSymbol(Twine("__LLVM_StackMaps")));
321 const char *WSMP = "Stack Maps: ";
323 const MCRegisterInfo &MCRI = *OutContext.getRegisterInfo();
325 DEBUG(dbgs() << "********** Stack Map Output **********\n");
328 AP.OutStreamer.EmitIntValue(0, 4);
331 AP.OutStreamer.EmitIntValue(FnStackSize.size(), 4);
333 // Stack size entries.
334 for (FnStackSizeMap::iterator I = FnStackSize.begin(), E = FnStackSize.end();
336 AP.OutStreamer.EmitSymbolValue(I->first, 4);
337 AP.OutStreamer.EmitIntValue(I->second, 4);
341 AP.OutStreamer.EmitIntValue(ConstPool.getNumConstants(), 4);
343 // Constant pool entries.
344 for (unsigned i = 0; i < ConstPool.getNumConstants(); ++i)
345 AP.OutStreamer.EmitIntValue(ConstPool.getConstant(i), 8);
347 DEBUG(dbgs() << WSMP << "#callsites = " << CSInfos.size() << "\n");
348 AP.OutStreamer.EmitIntValue(CSInfos.size(), 4);
350 for (CallsiteInfoList::const_iterator CSII = CSInfos.begin(),
351 CSIE = CSInfos.end();
352 CSII != CSIE; ++CSII) {
354 uint64_t CallsiteID = CSII->ID;
355 const LocationVec &CSLocs = CSII->Locations;
356 const LiveOutVec &LiveOuts = CSII->LiveOuts;
358 DEBUG(dbgs() << WSMP << "callsite " << CallsiteID << "\n");
360 // Verify stack map entry. It's better to communicate a problem to the
361 // runtime than crash in case of in-process compilation. Currently, we do
362 // simple overflow checks, but we may eventually communicate other
363 // compilation errors this way.
364 if (CSLocs.size() > UINT16_MAX || LiveOuts.size() > UINT16_MAX) {
365 AP.OutStreamer.EmitIntValue(UINT64_MAX, 8); // Invalid ID.
366 AP.OutStreamer.EmitValue(CSII->CSOffsetExpr, 4);
367 AP.OutStreamer.EmitIntValue(0, 2); // Reserved.
368 AP.OutStreamer.EmitIntValue(0, 2); // 0 locations.
369 AP.OutStreamer.EmitIntValue(0, 2); // 0 live-out registers.
373 AP.OutStreamer.EmitIntValue(CallsiteID, 8);
374 AP.OutStreamer.EmitValue(CSII->CSOffsetExpr, 4);
376 // Reserved for flags.
377 AP.OutStreamer.EmitIntValue(0, 2);
379 DEBUG(dbgs() << WSMP << " has " << CSLocs.size() << " locations\n");
381 AP.OutStreamer.EmitIntValue(CSLocs.size(), 2);
383 unsigned operIdx = 0;
384 for (LocationVec::const_iterator LocI = CSLocs.begin(), LocE = CSLocs.end();
385 LocI != LocE; ++LocI, ++operIdx) {
386 const Location &Loc = *LocI;
388 int Offset = Loc.Offset;
390 RegNo = MCRI.getDwarfRegNum(Loc.Reg, false);
391 for (MCSuperRegIterator SR(Loc.Reg, TRI);
392 SR.isValid() && (int)RegNo < 0; ++SR) {
393 RegNo = TRI->getDwarfRegNum(*SR, false);
395 // If this is a register location, put the subregister byte offset in
396 // the location offset.
397 if (Loc.LocType == Location::Register) {
398 assert(!Loc.Offset && "Register location should have zero offset");
399 unsigned LLVMRegNo = MCRI.getLLVMRegNum(RegNo, false);
400 unsigned SubRegIdx = MCRI.getSubRegIndex(LLVMRegNo, Loc.Reg);
402 Offset = MCRI.getSubRegIdxOffset(SubRegIdx);
406 assert(Loc.LocType != Location::Register &&
407 "Missing location register");
411 dbgs() << WSMP << " Loc " << operIdx << ": ";
412 switch (Loc.LocType) {
413 case Location::Unprocessed:
414 dbgs() << "<Unprocessed operand>";
416 case Location::Register:
417 dbgs() << "Register " << MCRI.getName(Loc.Reg);
419 case Location::Direct:
420 dbgs() << "Direct " << MCRI.getName(Loc.Reg);
422 dbgs() << " + " << Loc.Offset;
424 case Location::Indirect:
425 dbgs() << "Indirect " << MCRI.getName(Loc.Reg)
426 << " + " << Loc.Offset;
428 case Location::Constant:
429 dbgs() << "Constant " << Loc.Offset;
431 case Location::ConstantIndex:
432 dbgs() << "Constant Index " << Loc.Offset;
435 dbgs() << " [encoding: .byte " << Loc.LocType
436 << ", .byte " << Loc.Size
437 << ", .short " << RegNo
438 << ", .int " << Offset << "]\n";
441 AP.OutStreamer.EmitIntValue(Loc.LocType, 1);
442 AP.OutStreamer.EmitIntValue(Loc.Size, 1);
443 AP.OutStreamer.EmitIntValue(RegNo, 2);
444 AP.OutStreamer.EmitIntValue(Offset, 4);
447 DEBUG(dbgs() << WSMP << " has " << LiveOuts.size()
448 << " live-out registers\n");
450 AP.OutStreamer.EmitIntValue(LiveOuts.size(), 2);
453 for (LiveOutVec::const_iterator LI = LiveOuts.begin(), LE = LiveOuts.end();
454 LI != LE; ++LI, ++operIdx) {
455 DEBUG(dbgs() << WSMP << " LO " << operIdx << ": "
456 << MCRI.getName(LI->Reg)
457 << " [encoding: .short " << LI->RegNo
458 << ", .byte 0, .byte " << LI->Size << "]\n");
460 AP.OutStreamer.EmitIntValue(LI->RegNo, 2);
461 AP.OutStreamer.EmitIntValue(0, 1);
462 AP.OutStreamer.EmitIntValue(LI->Size, 1);
466 AP.OutStreamer.AddBlankLine();