Move DataLayout back to the TargetMachine from TargetSubtargetInfo
[oota-llvm.git] / lib / CodeGen / StackMaps.cpp
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 #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"
28 #include <iterator>
29
30 using namespace llvm;
31
32 #define DEBUG_TYPE "stackmaps"
33
34 static cl::opt<int> StackMapVersion("stackmap-version", cl::init(1),
35   cl::desc("Specify the stackmap encoding version (default = 1)"));
36
37 const char *StackMaps::WSMP = "Stack Maps: ";
38
39 PatchPointOpers::PatchPointOpers(const MachineInstr *MI)
40   : MI(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)
44 {
45 #ifndef NDEBUG
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())
50     ++CheckStartIdx;
51
52   assert(getMetaIdx() == CheckStartIdx &&
53          "Unexpected additional definition in Patchpoint intrinsic.");
54 #endif
55 }
56
57 unsigned PatchPointOpers::getNextScratchIdx(unsigned StartIdx) const {
58   if (!StartIdx)
59     StartIdx = getVarIdx();
60
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()))
68     ++ScratchIdx;
69
70   assert(ScratchIdx != e && "No scratch register available");
71   return ScratchIdx;
72 }
73
74 StackMaps::StackMaps(AsmPrinter &AP) : AP(AP) {
75   if (StackMapVersion != 1)
76     llvm_unreachable("Unsupported stackmap version!");
77 }
78
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 {
83   if (MOI->isImm()) {
84     switch (MOI->getImm()) {
85     default: llvm_unreachable("Unrecognized operand type.");
86     case StackMaps::DirectMemRefOp: {
87       unsigned Size = AP.TM.getDataLayout()->getPointerSizeInBits();
88       assert((Size % 8) == 0 && "Need pointer size in bytes.");
89       Size /= 8;
90       unsigned Reg = (++MOI)->getReg();
91       int64_t Imm = (++MOI)->getImm();
92       Locs.push_back(Location(StackMaps::Location::Direct, Size, Reg, Imm));
93       break;
94     }
95     case StackMaps::IndirectMemRefOp: {
96       int64_t Size = (++MOI)->getImm();
97       assert(Size > 0 && "Need a valid size for indirect memory locations.");
98       unsigned Reg = (++MOI)->getReg();
99       int64_t Imm = (++MOI)->getImm();
100       Locs.push_back(Location(StackMaps::Location::Indirect, Size, Reg, Imm));
101       break;
102     }
103     case StackMaps::ConstantOp: {
104       ++MOI;
105       assert(MOI->isImm() && "Expected constant operand.");
106       int64_t Imm = MOI->getImm();
107       Locs.push_back(Location(Location::Constant, sizeof(int64_t), 0, Imm));
108       break;
109     }
110     }
111     return ++MOI;
112   }
113
114   // The physical register number will ultimately be encoded as a DWARF regno.
115   // The stack map also records the size of a spill slot that can hold the
116   // register content. (The runtime can track the actual size of the data type
117   // if it needs to.)
118   if (MOI->isReg()) {
119     // Skip implicit registers (this includes our scratch registers)
120     if (MOI->isImplicit())
121       return ++MOI;
122
123     assert(TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) &&
124            "Virtreg operands should have been rewritten before now.");
125     const TargetRegisterClass *RC =
126         AP.TM.getSubtargetImpl()->getRegisterInfo()->getMinimalPhysRegClass(
127             MOI->getReg());
128     assert(!MOI->getSubReg() && "Physical subreg still around.");
129     Locs.push_back(
130       Location(Location::Register, RC->getSize(), MOI->getReg(), 0));
131     return ++MOI;
132   }
133
134   if (MOI->isRegLiveOut())
135     LiveOuts = parseRegisterLiveOutMask(MOI->getRegLiveOut());
136
137   return ++MOI;
138 }
139
140 /// Go up the super-register chain until we hit a valid dwarf register number.
141 static unsigned getDwarfRegNum(unsigned Reg, const TargetRegisterInfo *TRI) {
142   int RegNo = TRI->getDwarfRegNum(Reg, false);
143   for (MCSuperRegIterator SR(Reg, TRI); SR.isValid() && RegNo < 0; ++SR)
144     RegNo = TRI->getDwarfRegNum(*SR, false);
145
146   assert(RegNo >= 0 && "Invalid Dwarf register number.");
147   return (unsigned) RegNo;
148 }
149
150 /// Create a live-out register record for the given register Reg.
151 StackMaps::LiveOutReg
152 StackMaps::createLiveOutReg(unsigned Reg, const TargetRegisterInfo *TRI) const {
153   unsigned RegNo = getDwarfRegNum(Reg, TRI);
154   unsigned Size = TRI->getMinimalPhysRegClass(Reg)->getSize();
155   return LiveOutReg(Reg, RegNo, Size);
156 }
157
158 /// Parse the register live-out mask and return a vector of live-out registers
159 /// that need to be recorded in the stackmap.
160 StackMaps::LiveOutVec
161 StackMaps::parseRegisterLiveOutMask(const uint32_t *Mask) const {
162   assert(Mask && "No register mask specified");
163   const TargetRegisterInfo *TRI = AP.TM.getSubtargetImpl()->getRegisterInfo();
164   LiveOutVec LiveOuts;
165
166   // Create a LiveOutReg for each bit that is set in the register mask.
167   for (unsigned Reg = 0, NumRegs = TRI->getNumRegs(); Reg != NumRegs; ++Reg)
168     if ((Mask[Reg / 32] >> Reg % 32) & 1)
169       LiveOuts.push_back(createLiveOutReg(Reg, TRI));
170
171   // We don't need to keep track of a register if its super-register is already
172   // in the list. Merge entries that refer to the same dwarf register and use
173   // the maximum size that needs to be spilled.
174   std::sort(LiveOuts.begin(), LiveOuts.end());
175   for (LiveOutVec::iterator I = LiveOuts.begin(), E = LiveOuts.end();
176        I != E; ++I) {
177     for (LiveOutVec::iterator II = std::next(I); II != E; ++II) {
178       if (I->RegNo != II->RegNo) {
179         // Skip all the now invalid entries.
180         I = --II;
181         break;
182       }
183       I->Size = std::max(I->Size, II->Size);
184       if (TRI->isSuperRegister(I->Reg, II->Reg))
185         I->Reg = II->Reg;
186       II->MarkInvalid();
187     }
188   }
189   LiveOuts.erase(std::remove_if(LiveOuts.begin(), LiveOuts.end(),
190                                 LiveOutReg::IsInvalid), LiveOuts.end());
191   return LiveOuts;
192 }
193
194 void StackMaps::recordStackMapOpers(const MachineInstr &MI, uint64_t ID,
195                                     MachineInstr::const_mop_iterator MOI,
196                                     MachineInstr::const_mop_iterator MOE,
197                                     bool recordResult) {
198
199   MCContext &OutContext = AP.OutStreamer.getContext();
200   MCSymbol *MILabel = OutContext.CreateTempSymbol();
201   AP.OutStreamer.EmitLabel(MILabel);
202
203   LocationVec Locations;
204   LiveOutVec LiveOuts;
205
206   if (recordResult) {
207     assert(PatchPointOpers(&MI).hasDef() && "Stackmap has no return value.");
208     parseOperand(MI.operands_begin(), std::next(MI.operands_begin()),
209                  Locations, LiveOuts);
210   }
211
212   // Parse operands.
213   while (MOI != MOE) {
214     MOI = parseOperand(MOI, MOE, Locations, LiveOuts);
215   }
216
217   // Move large constants into the constant pool.
218   for (LocationVec::iterator I = Locations.begin(), E = Locations.end();
219        I != E; ++I) {
220     // Constants are encoded as sign-extended integers.
221     // -1 is directly encoded as .long 0xFFFFFFFF with no constant pool.
222     if (I->LocType == Location::Constant && !isInt<32>(I->Offset)) {
223       I->LocType = Location::ConstantIndex;
224       // ConstPool is intentionally a MapVector of 'uint64_t's (as
225       // opposed to 'int64_t's).  We should never be in a situation
226       // where we have to insert either the tombstone or the empty
227       // keys into a map, and for a DenseMap<uint64_t, T> these are
228       // (uint64_t)0 and (uint64_t)-1.  They can be and are
229       // represented using 32 bit integers.
230
231       assert((uint64_t)I->Offset != DenseMapInfo<uint64_t>::getEmptyKey() &&
232              (uint64_t)I->Offset != DenseMapInfo<uint64_t>::getTombstoneKey() &&
233              "empty and tombstone keys should fit in 32 bits!");
234       auto Result = ConstPool.insert(std::make_pair(I->Offset, I->Offset));
235       I->Offset = Result.first - ConstPool.begin();
236     }
237   }
238
239   // Create an expression to calculate the offset of the callsite from function
240   // entry.
241   const MCExpr *CSOffsetExpr = MCBinaryExpr::CreateSub(
242     MCSymbolRefExpr::Create(MILabel, OutContext),
243     MCSymbolRefExpr::Create(AP.CurrentFnSymForSize, OutContext),
244     OutContext);
245
246   CSInfos.emplace_back(CSOffsetExpr, ID, std::move(Locations),
247                        std::move(LiveOuts));
248
249   // Record the stack size of the current function.
250   const MachineFrameInfo *MFI = AP.MF->getFrameInfo();
251   const TargetRegisterInfo *RegInfo = AP.MF->getSubtarget().getRegisterInfo();
252   const bool DynamicFrameSize = MFI->hasVarSizedObjects() ||
253     RegInfo->needsStackRealignment(*(AP.MF));
254   FnStackSize[AP.CurrentFnSym] =
255     DynamicFrameSize ? UINT64_MAX : MFI->getStackSize();
256 }
257
258 void StackMaps::recordStackMap(const MachineInstr &MI) {
259   assert(MI.getOpcode() == TargetOpcode::STACKMAP && "expected stackmap");
260
261   int64_t ID = MI.getOperand(0).getImm();
262   recordStackMapOpers(MI, ID, std::next(MI.operands_begin(), 2),
263                       MI.operands_end());
264 }
265
266 void StackMaps::recordPatchPoint(const MachineInstr &MI) {
267   assert(MI.getOpcode() == TargetOpcode::PATCHPOINT && "expected patchpoint");
268
269   PatchPointOpers opers(&MI);
270   int64_t ID = opers.getMetaOper(PatchPointOpers::IDPos).getImm();
271
272   MachineInstr::const_mop_iterator MOI =
273     std::next(MI.operands_begin(), opers.getStackMapStartIdx());
274   recordStackMapOpers(MI, ID, MOI, MI.operands_end(),
275                       opers.isAnyReg() && opers.hasDef());
276
277 #ifndef NDEBUG
278   // verify anyregcc
279   LocationVec &Locations = CSInfos.back().Locations;
280   if (opers.isAnyReg()) {
281     unsigned NArgs = opers.getMetaOper(PatchPointOpers::NArgPos).getImm();
282     for (unsigned i = 0, e = (opers.hasDef() ? NArgs+1 : NArgs); i != e; ++i)
283       assert(Locations[i].LocType == Location::Register &&
284              "anyreg arg must be in reg.");
285   }
286 #endif
287 }
288 void StackMaps::recordStatepoint(const MachineInstr &MI) {
289   assert(MI.getOpcode() == TargetOpcode::STATEPOINT &&
290          "expected statepoint");
291
292   StatepointOpers opers(&MI);
293   // Record all the deopt and gc operands (they're contiguous and run from the
294   // initial index to the end of the operand list)
295   const unsigned StartIdx = opers.getVarIdx();
296   recordStackMapOpers(MI, 0xABCDEF00,
297                       MI.operands_begin() + StartIdx, MI.operands_end(),
298                       false);
299 }
300
301 /// Emit the stackmap header.
302 ///
303 /// Header {
304 ///   uint8  : Stack Map Version (currently 1)
305 ///   uint8  : Reserved (expected to be 0)
306 ///   uint16 : Reserved (expected to be 0)
307 /// }
308 /// uint32 : NumFunctions
309 /// uint32 : NumConstants
310 /// uint32 : NumRecords
311 void StackMaps::emitStackmapHeader(MCStreamer &OS) {
312   // Header.
313   OS.EmitIntValue(StackMapVersion, 1); // Version.
314   OS.EmitIntValue(0, 1); // Reserved.
315   OS.EmitIntValue(0, 2); // Reserved.
316
317   // Num functions.
318   DEBUG(dbgs() << WSMP << "#functions = " << FnStackSize.size() << '\n');
319   OS.EmitIntValue(FnStackSize.size(), 4);
320   // Num constants.
321   DEBUG(dbgs() << WSMP << "#constants = " << ConstPool.size() << '\n');
322   OS.EmitIntValue(ConstPool.size(), 4);
323   // Num callsites.
324   DEBUG(dbgs() << WSMP << "#callsites = " << CSInfos.size() << '\n');
325   OS.EmitIntValue(CSInfos.size(), 4);
326 }
327
328 /// Emit the function frame record for each function.
329 ///
330 /// StkSizeRecord[NumFunctions] {
331 ///   uint64 : Function Address
332 ///   uint64 : Stack Size
333 /// }
334 void StackMaps::emitFunctionFrameRecords(MCStreamer &OS) {
335   // Function Frame records.
336   DEBUG(dbgs() << WSMP << "functions:\n");
337   for (auto const &FR : FnStackSize) {
338     DEBUG(dbgs() << WSMP << "function addr: " << FR.first
339                          << " frame size: " << FR.second);
340     OS.EmitSymbolValue(FR.first, 8);
341     OS.EmitIntValue(FR.second, 8);
342   }
343 }
344
345 /// Emit the constant pool.
346 ///
347 /// int64  : Constants[NumConstants]
348 void StackMaps::emitConstantPoolEntries(MCStreamer &OS) {
349   // Constant pool entries.
350   DEBUG(dbgs() << WSMP << "constants:\n");
351   for (auto ConstEntry : ConstPool) {
352     DEBUG(dbgs() << WSMP << ConstEntry.second << '\n');
353     OS.EmitIntValue(ConstEntry.second, 8);
354   }
355 }
356
357 /// Emit the callsite info for each callsite.
358 ///
359 /// StkMapRecord[NumRecords] {
360 ///   uint64 : PatchPoint ID
361 ///   uint32 : Instruction Offset
362 ///   uint16 : Reserved (record flags)
363 ///   uint16 : NumLocations
364 ///   Location[NumLocations] {
365 ///     uint8  : Register | Direct | Indirect | Constant | ConstantIndex
366 ///     uint8  : Size in Bytes
367 ///     uint16 : Dwarf RegNum
368 ///     int32  : Offset
369 ///   }
370 ///   uint16 : Padding
371 ///   uint16 : NumLiveOuts
372 ///   LiveOuts[NumLiveOuts] {
373 ///     uint16 : Dwarf RegNum
374 ///     uint8  : Reserved
375 ///     uint8  : Size in Bytes
376 ///   }
377 ///   uint32 : Padding (only if required to align to 8 byte)
378 /// }
379 ///
380 /// Location Encoding, Type, Value:
381 ///   0x1, Register, Reg                 (value in register)
382 ///   0x2, Direct, Reg + Offset          (frame index)
383 ///   0x3, Indirect, [Reg + Offset]      (spilled value)
384 ///   0x4, Constant, Offset              (small constant)
385 ///   0x5, ConstIndex, Constants[Offset] (large constant)
386 void StackMaps::emitCallsiteEntries(MCStreamer &OS,
387                                     const TargetRegisterInfo *TRI) {
388   // Callsite entries.
389   DEBUG(dbgs() << WSMP << "callsites:\n");
390   for (const auto &CSI : CSInfos) {
391     const LocationVec &CSLocs = CSI.Locations;
392     const LiveOutVec &LiveOuts = CSI.LiveOuts;
393
394     DEBUG(dbgs() << WSMP << "callsite " << CSI.ID << "\n");
395
396     // Verify stack map entry. It's better to communicate a problem to the
397     // runtime than crash in case of in-process compilation. Currently, we do
398     // simple overflow checks, but we may eventually communicate other
399     // compilation errors this way.
400     if (CSLocs.size() > UINT16_MAX || LiveOuts.size() > UINT16_MAX) {
401       OS.EmitIntValue(UINT64_MAX, 8); // Invalid ID.
402       OS.EmitValue(CSI.CSOffsetExpr, 4);
403       OS.EmitIntValue(0, 2); // Reserved.
404       OS.EmitIntValue(0, 2); // 0 locations.
405       OS.EmitIntValue(0, 2); // padding.
406       OS.EmitIntValue(0, 2); // 0 live-out registers.
407       OS.EmitIntValue(0, 4); // padding.
408       continue;
409     }
410
411     OS.EmitIntValue(CSI.ID, 8);
412     OS.EmitValue(CSI.CSOffsetExpr, 4);
413
414     // Reserved for flags.
415     OS.EmitIntValue(0, 2);
416
417     DEBUG(dbgs() << WSMP << "  has " << CSLocs.size() << " locations\n");
418
419     OS.EmitIntValue(CSLocs.size(), 2);
420
421     unsigned OperIdx = 0;
422     for (const auto &Loc : CSLocs) {
423       unsigned RegNo = 0;
424       int Offset = Loc.Offset;
425       if(Loc.Reg) {
426         RegNo = getDwarfRegNum(Loc.Reg, TRI);
427
428         // If this is a register location, put the subregister byte offset in
429         // the location offset.
430         if (Loc.LocType == Location::Register) {
431           assert(!Loc.Offset && "Register location should have zero offset");
432           unsigned LLVMRegNo = TRI->getLLVMRegNum(RegNo, false);
433           unsigned SubRegIdx = TRI->getSubRegIndex(LLVMRegNo, Loc.Reg);
434           if (SubRegIdx)
435             Offset = TRI->getSubRegIdxOffset(SubRegIdx);
436         }
437       }
438       else {
439         assert(Loc.LocType != Location::Register &&
440                "Missing location register");
441       }
442
443       DEBUG(dbgs() << WSMP << "  Loc " << OperIdx << ": ";
444             switch (Loc.LocType) {
445             case Location::Unprocessed:
446               dbgs() << "<Unprocessed operand>";
447               break;
448             case Location::Register:
449               dbgs() << "Register " << TRI->getName(Loc.Reg);
450               break;
451             case Location::Direct:
452               dbgs() << "Direct " << TRI->getName(Loc.Reg);
453               if (Loc.Offset)
454               dbgs() << " + " << Loc.Offset;
455               break;
456             case Location::Indirect:
457               dbgs() << "Indirect " << TRI->getName(Loc.Reg)
458               << " + " << Loc.Offset;
459               break;
460             case Location::Constant:
461               dbgs() << "Constant " << Loc.Offset;
462               break;
463             case Location::ConstantIndex:
464               dbgs() << "Constant Index " << Loc.Offset;
465               break;
466               }
467             dbgs() << "     [encoding: .byte " << Loc.LocType
468             << ", .byte " << Loc.Size
469             << ", .short " << RegNo
470             << ", .int " << Offset << "]\n";
471             );
472
473       OS.EmitIntValue(Loc.LocType, 1);
474       OS.EmitIntValue(Loc.Size, 1);
475       OS.EmitIntValue(RegNo, 2);
476       OS.EmitIntValue(Offset, 4);
477       OperIdx++;
478     }
479
480     DEBUG(dbgs() << WSMP << "  has " << LiveOuts.size()
481                          << " live-out registers\n");
482
483     // Num live-out registers and padding to align to 4 byte.
484     OS.EmitIntValue(0, 2);
485     OS.EmitIntValue(LiveOuts.size(), 2);
486
487     OperIdx = 0;
488     for (const auto &LO : LiveOuts) {
489       DEBUG(dbgs() << WSMP << "  LO " << OperIdx << ": "
490                            << TRI->getName(LO.Reg)
491                            << "     [encoding: .short " << LO.RegNo
492                            << ", .byte 0, .byte " << LO.Size << "]\n");
493       OS.EmitIntValue(LO.RegNo, 2);
494       OS.EmitIntValue(0, 1);
495       OS.EmitIntValue(LO.Size, 1);
496     }
497     // Emit alignment to 8 byte.
498     OS.EmitValueToAlignment(8);
499   }
500 }
501
502 /// Serialize the stackmap data.
503 void StackMaps::serializeToStackMapSection() {
504   (void) WSMP;
505   // Bail out if there's no stack map data.
506   assert((!CSInfos.empty() || (CSInfos.empty() && ConstPool.empty())) &&
507          "Expected empty constant pool too!");
508   assert((!CSInfos.empty() || (CSInfos.empty() && FnStackSize.empty())) &&
509          "Expected empty function record too!");
510   if (CSInfos.empty())
511     return;
512
513   MCContext &OutContext = AP.OutStreamer.getContext();
514   MCStreamer &OS = AP.OutStreamer;
515   const TargetRegisterInfo *TRI = AP.TM.getSubtargetImpl()->getRegisterInfo();
516
517   // Create the section.
518   const MCSection *StackMapSection =
519     OutContext.getObjectFileInfo()->getStackMapSection();
520   OS.SwitchSection(StackMapSection);
521
522   // Emit a dummy symbol to force section inclusion.
523   OS.EmitLabel(OutContext.GetOrCreateSymbol(Twine("__LLVM_StackMaps")));
524
525   // Serialize data.
526   DEBUG(dbgs() << "********** Stack Map Output **********\n");
527   emitStackmapHeader(OS);
528   emitFunctionFrameRecords(OS);
529   emitConstantPoolEntries(OS);
530   emitCallsiteEntries(OS, TRI);
531   OS.AddBlankLine();
532
533   // Clean up.
534   CSInfos.clear();
535   ConstPool.clear();
536 }