1 //===- MIRPrinter.cpp - MIR serialization format printer ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the class that prints out the LLVM IR and machine
10 // functions using the MIR serialization format.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/MIRPrinter.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallBitVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/CodeGen/MIRYamlMapping.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineMemOperand.h"
29 #include "llvm/CodeGen/MachineModuleSlotTracker.h"
30 #include "llvm/CodeGen/MachineOperand.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/TargetFrameLowering.h"
33 #include "llvm/CodeGen/TargetInstrInfo.h"
34 #include "llvm/CodeGen/TargetRegisterInfo.h"
35 #include "llvm/CodeGen/TargetSubtargetInfo.h"
36 #include "llvm/IR/DebugInfoMetadata.h"
37 #include "llvm/IR/DebugLoc.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/IRPrintingPasses.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/IR/ModuleSlotTracker.h"
43 #include "llvm/IR/Value.h"
44 #include "llvm/MC/LaneBitmask.h"
45 #include "llvm/Support/BranchProbability.h"
46 #include "llvm/Support/Casting.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/Format.h"
50 #include "llvm/Support/LowLevelTypeImpl.h"
51 #include "llvm/Support/YAMLTraits.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetMachine.h"
54 #include <algorithm>
55 #include <cassert>
56 #include <cinttypes>
57 #include <cstdint>
58 #include <iterator>
59 #include <string>
60 #include <utility>
61 #include <vector>
62
63 using namespace llvm;
64
65 static cl::opt<bool> SimplifyMIR(
66 "simplify-mir", cl::Hidden,
67 cl::desc("Leave out unnecessary information when printing MIR"));
68
69 static cl::opt<bool> PrintLocations("mir-debug-loc", cl::Hidden, cl::init(true),
70 cl::desc("Print MIR debug-locations"));
71
72 namespace {
73
74 /// This structure describes how to print out stack object references.
75 struct FrameIndexOperand {
76 std::string Name;
77 unsigned ID;
78 bool IsFixed;
79
FrameIndexOperand__anonc22a66f00111::FrameIndexOperand80 FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
81 : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
82
83 /// Return an ordinary stack object reference.
create__anonc22a66f00111::FrameIndexOperand84 static FrameIndexOperand create(StringRef Name, unsigned ID) {
85 return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
86 }
87
88 /// Return a fixed stack object reference.
createFixed__anonc22a66f00111::FrameIndexOperand89 static FrameIndexOperand createFixed(unsigned ID) {
90 return FrameIndexOperand("", ID, /*IsFixed=*/true);
91 }
92 };
93
94 } // end anonymous namespace
95
96 namespace llvm {
97
98 /// This class prints out the machine functions using the MIR serialization
99 /// format.
100 class MIRPrinter {
101 raw_ostream &OS;
102 DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
103 /// Maps from stack object indices to operand indices which will be used when
104 /// printing frame index machine operands.
105 DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
106
107 public:
MIRPrinter(raw_ostream & OS)108 MIRPrinter(raw_ostream &OS) : OS(OS) {}
109
110 void print(const MachineFunction &MF);
111
112 void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
113 const TargetRegisterInfo *TRI);
114 void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
115 const MachineFrameInfo &MFI);
116 void convert(yaml::MachineFunction &MF,
117 const MachineConstantPool &ConstantPool);
118 void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
119 const MachineJumpTableInfo &JTI);
120 void convertStackObjects(yaml::MachineFunction &YMF,
121 const MachineFunction &MF, ModuleSlotTracker &MST);
122 void convertCallSiteObjects(yaml::MachineFunction &YMF,
123 const MachineFunction &MF,
124 ModuleSlotTracker &MST);
125 void convertMachineMetadataNodes(yaml::MachineFunction &YMF,
126 const MachineFunction &MF,
127 MachineModuleSlotTracker &MST);
128
129 private:
130 void initRegisterMaskIds(const MachineFunction &MF);
131 };
132
133 /// This class prints out the machine instructions using the MIR serialization
134 /// format.
135 class MIPrinter {
136 raw_ostream &OS;
137 ModuleSlotTracker &MST;
138 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
139 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
140 /// Synchronization scope names registered with LLVMContext.
141 SmallVector<StringRef, 8> SSNs;
142
143 bool canPredictBranchProbabilities(const MachineBasicBlock &MBB) const;
144 bool canPredictSuccessors(const MachineBasicBlock &MBB) const;
145
146 public:
MIPrinter(raw_ostream & OS,ModuleSlotTracker & MST,const DenseMap<const uint32_t *,unsigned> & RegisterMaskIds,const DenseMap<int,FrameIndexOperand> & StackObjectOperandMapping)147 MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
148 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
149 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
150 : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
151 StackObjectOperandMapping(StackObjectOperandMapping) {}
152
153 void print(const MachineBasicBlock &MBB);
154
155 void print(const MachineInstr &MI);
156 void printStackObjectReference(int FrameIndex);
157 void print(const MachineInstr &MI, unsigned OpIdx,
158 const TargetRegisterInfo *TRI, const TargetInstrInfo *TII,
159 bool ShouldPrintRegisterTies, LLT TypeToPrint,
160 bool PrintDef = true);
161 };
162
163 } // end namespace llvm
164
165 namespace llvm {
166 namespace yaml {
167
168 /// This struct serializes the LLVM IR module.
169 template <> struct BlockScalarTraits<Module> {
outputllvm::yaml::BlockScalarTraits170 static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
171 Mod.print(OS, nullptr);
172 }
173
inputllvm::yaml::BlockScalarTraits174 static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
175 llvm_unreachable("LLVM Module is supposed to be parsed separately");
176 return "";
177 }
178 };
179
180 } // end namespace yaml
181 } // end namespace llvm
182
printRegMIR(unsigned Reg,yaml::StringValue & Dest,const TargetRegisterInfo * TRI)183 static void printRegMIR(unsigned Reg, yaml::StringValue &Dest,
184 const TargetRegisterInfo *TRI) {
185 raw_string_ostream OS(Dest.Value);
186 OS << printReg(Reg, TRI);
187 }
188
print(const MachineFunction & MF)189 void MIRPrinter::print(const MachineFunction &MF) {
190 initRegisterMaskIds(MF);
191
192 yaml::MachineFunction YamlMF;
193 YamlMF.Name = MF.getName();
194 YamlMF.Alignment = MF.getAlignment();
195 YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
196 YamlMF.HasWinCFI = MF.hasWinCFI();
197
198 YamlMF.CallsEHReturn = MF.callsEHReturn();
199 YamlMF.CallsUnwindInit = MF.callsUnwindInit();
200 YamlMF.HasEHCatchret = MF.hasEHCatchret();
201 YamlMF.HasEHScopes = MF.hasEHScopes();
202 YamlMF.HasEHFunclets = MF.hasEHFunclets();
203
204 YamlMF.Legalized = MF.getProperties().hasProperty(
205 MachineFunctionProperties::Property::Legalized);
206 YamlMF.RegBankSelected = MF.getProperties().hasProperty(
207 MachineFunctionProperties::Property::RegBankSelected);
208 YamlMF.Selected = MF.getProperties().hasProperty(
209 MachineFunctionProperties::Property::Selected);
210 YamlMF.FailedISel = MF.getProperties().hasProperty(
211 MachineFunctionProperties::Property::FailedISel);
212 YamlMF.FailsVerification = MF.getProperties().hasProperty(
213 MachineFunctionProperties::Property::FailsVerification);
214 YamlMF.TracksDebugUserValues = MF.getProperties().hasProperty(
215 MachineFunctionProperties::Property::TracksDebugUserValues);
216
217 convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
218 MachineModuleSlotTracker MST(&MF);
219 MST.incorporateFunction(MF.getFunction());
220 convert(MST, YamlMF.FrameInfo, MF.getFrameInfo());
221 convertStackObjects(YamlMF, MF, MST);
222 convertCallSiteObjects(YamlMF, MF, MST);
223 for (const auto &Sub : MF.DebugValueSubstitutions) {
224 const auto &SubSrc = Sub.Src;
225 const auto &SubDest = Sub.Dest;
226 YamlMF.DebugValueSubstitutions.push_back({SubSrc.first, SubSrc.second,
227 SubDest.first,
228 SubDest.second,
229 Sub.Subreg});
230 }
231 if (const auto *ConstantPool = MF.getConstantPool())
232 convert(YamlMF, *ConstantPool);
233 if (const auto *JumpTableInfo = MF.getJumpTableInfo())
234 convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
235
236 const TargetMachine &TM = MF.getTarget();
237 YamlMF.MachineFuncInfo =
238 std::unique_ptr<yaml::MachineFunctionInfo>(TM.convertFuncInfoToYAML(MF));
239
240 raw_string_ostream StrOS(YamlMF.Body.Value.Value);
241 bool IsNewlineNeeded = false;
242 for (const auto &MBB : MF) {
243 if (IsNewlineNeeded)
244 StrOS << "\n";
245 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
246 .print(MBB);
247 IsNewlineNeeded = true;
248 }
249 StrOS.flush();
250 // Convert machine metadata collected during the print of the machine
251 // function.
252 convertMachineMetadataNodes(YamlMF, MF, MST);
253
254 yaml::Output Out(OS);
255 if (!SimplifyMIR)
256 Out.setWriteDefaultValues(true);
257 Out << YamlMF;
258 }
259
printCustomRegMask(const uint32_t * RegMask,raw_ostream & OS,const TargetRegisterInfo * TRI)260 static void printCustomRegMask(const uint32_t *RegMask, raw_ostream &OS,
261 const TargetRegisterInfo *TRI) {
262 assert(RegMask && "Can't print an empty register mask");
263 OS << StringRef("CustomRegMask(");
264
265 bool IsRegInRegMaskFound = false;
266 for (int I = 0, E = TRI->getNumRegs(); I < E; I++) {
267 // Check whether the register is asserted in regmask.
268 if (RegMask[I / 32] & (1u << (I % 32))) {
269 if (IsRegInRegMaskFound)
270 OS << ',';
271 OS << printReg(I, TRI);
272 IsRegInRegMaskFound = true;
273 }
274 }
275
276 OS << ')';
277 }
278
printRegClassOrBank(unsigned Reg,yaml::StringValue & Dest,const MachineRegisterInfo & RegInfo,const TargetRegisterInfo * TRI)279 static void printRegClassOrBank(unsigned Reg, yaml::StringValue &Dest,
280 const MachineRegisterInfo &RegInfo,
281 const TargetRegisterInfo *TRI) {
282 raw_string_ostream OS(Dest.Value);
283 OS << printRegClassOrBank(Reg, RegInfo, TRI);
284 }
285
286 template <typename T>
287 static void
printStackObjectDbgInfo(const MachineFunction::VariableDbgInfo & DebugVar,T & Object,ModuleSlotTracker & MST)288 printStackObjectDbgInfo(const MachineFunction::VariableDbgInfo &DebugVar,
289 T &Object, ModuleSlotTracker &MST) {
290 std::array<std::string *, 3> Outputs{{&Object.DebugVar.Value,
291 &Object.DebugExpr.Value,
292 &Object.DebugLoc.Value}};
293 std::array<const Metadata *, 3> Metas{{DebugVar.Var,
294 DebugVar.Expr,
295 DebugVar.Loc}};
296 for (unsigned i = 0; i < 3; ++i) {
297 raw_string_ostream StrOS(*Outputs[i]);
298 Metas[i]->printAsOperand(StrOS, MST);
299 }
300 }
301
convert(yaml::MachineFunction & MF,const MachineRegisterInfo & RegInfo,const TargetRegisterInfo * TRI)302 void MIRPrinter::convert(yaml::MachineFunction &MF,
303 const MachineRegisterInfo &RegInfo,
304 const TargetRegisterInfo *TRI) {
305 MF.TracksRegLiveness = RegInfo.tracksLiveness();
306
307 // Print the virtual register definitions.
308 for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
309 unsigned Reg = Register::index2VirtReg(I);
310 yaml::VirtualRegisterDefinition VReg;
311 VReg.ID = I;
312 if (RegInfo.getVRegName(Reg) != "")
313 continue;
314 ::printRegClassOrBank(Reg, VReg.Class, RegInfo, TRI);
315 unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
316 if (PreferredReg)
317 printRegMIR(PreferredReg, VReg.PreferredRegister, TRI);
318 MF.VirtualRegisters.push_back(VReg);
319 }
320
321 // Print the live ins.
322 for (std::pair<unsigned, unsigned> LI : RegInfo.liveins()) {
323 yaml::MachineFunctionLiveIn LiveIn;
324 printRegMIR(LI.first, LiveIn.Register, TRI);
325 if (LI.second)
326 printRegMIR(LI.second, LiveIn.VirtualRegister, TRI);
327 MF.LiveIns.push_back(LiveIn);
328 }
329
330 // Prints the callee saved registers.
331 if (RegInfo.isUpdatedCSRsInitialized()) {
332 const MCPhysReg *CalleeSavedRegs = RegInfo.getCalleeSavedRegs();
333 std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
334 for (const MCPhysReg *I = CalleeSavedRegs; *I; ++I) {
335 yaml::FlowStringValue Reg;
336 printRegMIR(*I, Reg, TRI);
337 CalleeSavedRegisters.push_back(Reg);
338 }
339 MF.CalleeSavedRegisters = CalleeSavedRegisters;
340 }
341 }
342
convert(ModuleSlotTracker & MST,yaml::MachineFrameInfo & YamlMFI,const MachineFrameInfo & MFI)343 void MIRPrinter::convert(ModuleSlotTracker &MST,
344 yaml::MachineFrameInfo &YamlMFI,
345 const MachineFrameInfo &MFI) {
346 YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
347 YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
348 YamlMFI.HasStackMap = MFI.hasStackMap();
349 YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
350 YamlMFI.StackSize = MFI.getStackSize();
351 YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
352 YamlMFI.MaxAlignment = MFI.getMaxAlign().value();
353 YamlMFI.AdjustsStack = MFI.adjustsStack();
354 YamlMFI.HasCalls = MFI.hasCalls();
355 YamlMFI.MaxCallFrameSize = MFI.isMaxCallFrameSizeComputed()
356 ? MFI.getMaxCallFrameSize() : ~0u;
357 YamlMFI.CVBytesOfCalleeSavedRegisters =
358 MFI.getCVBytesOfCalleeSavedRegisters();
359 YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
360 YamlMFI.HasVAStart = MFI.hasVAStart();
361 YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
362 YamlMFI.HasTailCall = MFI.hasTailCall();
363 YamlMFI.LocalFrameSize = MFI.getLocalFrameSize();
364 if (MFI.getSavePoint()) {
365 raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
366 StrOS << printMBBReference(*MFI.getSavePoint());
367 }
368 if (MFI.getRestorePoint()) {
369 raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
370 StrOS << printMBBReference(*MFI.getRestorePoint());
371 }
372 }
373
convertStackObjects(yaml::MachineFunction & YMF,const MachineFunction & MF,ModuleSlotTracker & MST)374 void MIRPrinter::convertStackObjects(yaml::MachineFunction &YMF,
375 const MachineFunction &MF,
376 ModuleSlotTracker &MST) {
377 const MachineFrameInfo &MFI = MF.getFrameInfo();
378 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
379
380 // Process fixed stack objects.
381 assert(YMF.FixedStackObjects.empty());
382 SmallVector<int, 32> FixedStackObjectsIdx;
383 const int BeginIdx = MFI.getObjectIndexBegin();
384 if (BeginIdx < 0)
385 FixedStackObjectsIdx.reserve(-BeginIdx);
386
387 unsigned ID = 0;
388 for (int I = BeginIdx; I < 0; ++I, ++ID) {
389 FixedStackObjectsIdx.push_back(-1); // Fill index for possible dead.
390 if (MFI.isDeadObjectIndex(I))
391 continue;
392
393 yaml::FixedMachineStackObject YamlObject;
394 YamlObject.ID = ID;
395 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
396 ? yaml::FixedMachineStackObject::SpillSlot
397 : yaml::FixedMachineStackObject::DefaultType;
398 YamlObject.Offset = MFI.getObjectOffset(I);
399 YamlObject.Size = MFI.getObjectSize(I);
400 YamlObject.Alignment = MFI.getObjectAlign(I);
401 YamlObject.StackID = (TargetStackID::Value)MFI.getStackID(I);
402 YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
403 YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
404 // Save the ID' position in FixedStackObjects storage vector.
405 FixedStackObjectsIdx[ID] = YMF.FixedStackObjects.size();
406 YMF.FixedStackObjects.push_back(YamlObject);
407 StackObjectOperandMapping.insert(
408 std::make_pair(I, FrameIndexOperand::createFixed(ID)));
409 }
410
411 // Process ordinary stack objects.
412 assert(YMF.StackObjects.empty());
413 SmallVector<unsigned, 32> StackObjectsIdx;
414 const int EndIdx = MFI.getObjectIndexEnd();
415 if (EndIdx > 0)
416 StackObjectsIdx.reserve(EndIdx);
417 ID = 0;
418 for (int I = 0; I < EndIdx; ++I, ++ID) {
419 StackObjectsIdx.push_back(-1); // Fill index for possible dead.
420 if (MFI.isDeadObjectIndex(I))
421 continue;
422
423 yaml::MachineStackObject YamlObject;
424 YamlObject.ID = ID;
425 if (const auto *Alloca = MFI.getObjectAllocation(I))
426 YamlObject.Name.Value = std::string(
427 Alloca->hasName() ? Alloca->getName() : "");
428 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
429 ? yaml::MachineStackObject::SpillSlot
430 : MFI.isVariableSizedObjectIndex(I)
431 ? yaml::MachineStackObject::VariableSized
432 : yaml::MachineStackObject::DefaultType;
433 YamlObject.Offset = MFI.getObjectOffset(I);
434 YamlObject.Size = MFI.getObjectSize(I);
435 YamlObject.Alignment = MFI.getObjectAlign(I);
436 YamlObject.StackID = (TargetStackID::Value)MFI.getStackID(I);
437
438 // Save the ID' position in StackObjects storage vector.
439 StackObjectsIdx[ID] = YMF.StackObjects.size();
440 YMF.StackObjects.push_back(YamlObject);
441 StackObjectOperandMapping.insert(std::make_pair(
442 I, FrameIndexOperand::create(YamlObject.Name.Value, ID)));
443 }
444
445 for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
446 const int FrameIdx = CSInfo.getFrameIdx();
447 if (!CSInfo.isSpilledToReg() && MFI.isDeadObjectIndex(FrameIdx))
448 continue;
449
450 yaml::StringValue Reg;
451 printRegMIR(CSInfo.getReg(), Reg, TRI);
452 if (!CSInfo.isSpilledToReg()) {
453 assert(FrameIdx >= MFI.getObjectIndexBegin() &&
454 FrameIdx < MFI.getObjectIndexEnd() &&
455 "Invalid stack object index");
456 if (FrameIdx < 0) { // Negative index means fixed objects.
457 auto &Object =
458 YMF.FixedStackObjects
459 [FixedStackObjectsIdx[FrameIdx + MFI.getNumFixedObjects()]];
460 Object.CalleeSavedRegister = Reg;
461 Object.CalleeSavedRestored = CSInfo.isRestored();
462 } else {
463 auto &Object = YMF.StackObjects[StackObjectsIdx[FrameIdx]];
464 Object.CalleeSavedRegister = Reg;
465 Object.CalleeSavedRestored = CSInfo.isRestored();
466 }
467 }
468 }
469 for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) {
470 auto LocalObject = MFI.getLocalFrameObjectMap(I);
471 assert(LocalObject.first >= 0 && "Expected a locally mapped stack object");
472 YMF.StackObjects[StackObjectsIdx[LocalObject.first]].LocalOffset =
473 LocalObject.second;
474 }
475
476 // Print the stack object references in the frame information class after
477 // converting the stack objects.
478 if (MFI.hasStackProtectorIndex()) {
479 raw_string_ostream StrOS(YMF.FrameInfo.StackProtector.Value);
480 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
481 .printStackObjectReference(MFI.getStackProtectorIndex());
482 }
483
484 if (MFI.hasFunctionContextIndex()) {
485 raw_string_ostream StrOS(YMF.FrameInfo.FunctionContext.Value);
486 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
487 .printStackObjectReference(MFI.getFunctionContextIndex());
488 }
489
490 // Print the debug variable information.
491 for (const MachineFunction::VariableDbgInfo &DebugVar :
492 MF.getVariableDbgInfo()) {
493 assert(DebugVar.Slot >= MFI.getObjectIndexBegin() &&
494 DebugVar.Slot < MFI.getObjectIndexEnd() &&
495 "Invalid stack object index");
496 if (DebugVar.Slot < 0) { // Negative index means fixed objects.
497 auto &Object =
498 YMF.FixedStackObjects[FixedStackObjectsIdx[DebugVar.Slot +
499 MFI.getNumFixedObjects()]];
500 printStackObjectDbgInfo(DebugVar, Object, MST);
501 } else {
502 auto &Object = YMF.StackObjects[StackObjectsIdx[DebugVar.Slot]];
503 printStackObjectDbgInfo(DebugVar, Object, MST);
504 }
505 }
506 }
507
convertCallSiteObjects(yaml::MachineFunction & YMF,const MachineFunction & MF,ModuleSlotTracker & MST)508 void MIRPrinter::convertCallSiteObjects(yaml::MachineFunction &YMF,
509 const MachineFunction &MF,
510 ModuleSlotTracker &MST) {
511 const auto *TRI = MF.getSubtarget().getRegisterInfo();
512 for (auto CSInfo : MF.getCallSitesInfo()) {
513 yaml::CallSiteInfo YmlCS;
514 yaml::CallSiteInfo::MachineInstrLoc CallLocation;
515
516 // Prepare instruction position.
517 MachineBasicBlock::const_instr_iterator CallI = CSInfo.first->getIterator();
518 CallLocation.BlockNum = CallI->getParent()->getNumber();
519 // Get call instruction offset from the beginning of block.
520 CallLocation.Offset =
521 std::distance(CallI->getParent()->instr_begin(), CallI);
522 YmlCS.CallLocation = CallLocation;
523 // Construct call arguments and theirs forwarding register info.
524 for (auto ArgReg : CSInfo.second) {
525 yaml::CallSiteInfo::ArgRegPair YmlArgReg;
526 YmlArgReg.ArgNo = ArgReg.ArgNo;
527 printRegMIR(ArgReg.Reg, YmlArgReg.Reg, TRI);
528 YmlCS.ArgForwardingRegs.emplace_back(YmlArgReg);
529 }
530 YMF.CallSitesInfo.push_back(YmlCS);
531 }
532
533 // Sort call info by position of call instructions.
534 llvm::sort(YMF.CallSitesInfo.begin(), YMF.CallSitesInfo.end(),
535 [](yaml::CallSiteInfo A, yaml::CallSiteInfo B) {
536 if (A.CallLocation.BlockNum == B.CallLocation.BlockNum)
537 return A.CallLocation.Offset < B.CallLocation.Offset;
538 return A.CallLocation.BlockNum < B.CallLocation.BlockNum;
539 });
540 }
541
convertMachineMetadataNodes(yaml::MachineFunction & YMF,const MachineFunction & MF,MachineModuleSlotTracker & MST)542 void MIRPrinter::convertMachineMetadataNodes(yaml::MachineFunction &YMF,
543 const MachineFunction &MF,
544 MachineModuleSlotTracker &MST) {
545 MachineModuleSlotTracker::MachineMDNodeListType MDList;
546 MST.collectMachineMDNodes(MDList);
547 for (auto &MD : MDList) {
548 std::string NS;
549 raw_string_ostream StrOS(NS);
550 MD.second->print(StrOS, MST, MF.getFunction().getParent());
551 YMF.MachineMetadataNodes.push_back(StrOS.str());
552 }
553 }
554
convert(yaml::MachineFunction & MF,const MachineConstantPool & ConstantPool)555 void MIRPrinter::convert(yaml::MachineFunction &MF,
556 const MachineConstantPool &ConstantPool) {
557 unsigned ID = 0;
558 for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
559 std::string Str;
560 raw_string_ostream StrOS(Str);
561 if (Constant.isMachineConstantPoolEntry()) {
562 Constant.Val.MachineCPVal->print(StrOS);
563 } else {
564 Constant.Val.ConstVal->printAsOperand(StrOS);
565 }
566
567 yaml::MachineConstantPoolValue YamlConstant;
568 YamlConstant.ID = ID++;
569 YamlConstant.Value = StrOS.str();
570 YamlConstant.Alignment = Constant.getAlign();
571 YamlConstant.IsTargetSpecific = Constant.isMachineConstantPoolEntry();
572
573 MF.Constants.push_back(YamlConstant);
574 }
575 }
576
convert(ModuleSlotTracker & MST,yaml::MachineJumpTable & YamlJTI,const MachineJumpTableInfo & JTI)577 void MIRPrinter::convert(ModuleSlotTracker &MST,
578 yaml::MachineJumpTable &YamlJTI,
579 const MachineJumpTableInfo &JTI) {
580 YamlJTI.Kind = JTI.getEntryKind();
581 unsigned ID = 0;
582 for (const auto &Table : JTI.getJumpTables()) {
583 std::string Str;
584 yaml::MachineJumpTable::Entry Entry;
585 Entry.ID = ID++;
586 for (const auto *MBB : Table.MBBs) {
587 raw_string_ostream StrOS(Str);
588 StrOS << printMBBReference(*MBB);
589 Entry.Blocks.push_back(StrOS.str());
590 Str.clear();
591 }
592 YamlJTI.Entries.push_back(Entry);
593 }
594 }
595
initRegisterMaskIds(const MachineFunction & MF)596 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
597 const auto *TRI = MF.getSubtarget().getRegisterInfo();
598 unsigned I = 0;
599 for (const uint32_t *Mask : TRI->getRegMasks())
600 RegisterMaskIds.insert(std::make_pair(Mask, I++));
601 }
602
guessSuccessors(const MachineBasicBlock & MBB,SmallVectorImpl<MachineBasicBlock * > & Result,bool & IsFallthrough)603 void llvm::guessSuccessors(const MachineBasicBlock &MBB,
604 SmallVectorImpl<MachineBasicBlock*> &Result,
605 bool &IsFallthrough) {
606 SmallPtrSet<MachineBasicBlock*,8> Seen;
607
608 for (const MachineInstr &MI : MBB) {
609 if (MI.isPHI())
610 continue;
611 for (const MachineOperand &MO : MI.operands()) {
612 if (!MO.isMBB())
613 continue;
614 MachineBasicBlock *Succ = MO.getMBB();
615 auto RP = Seen.insert(Succ);
616 if (RP.second)
617 Result.push_back(Succ);
618 }
619 }
620 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
621 IsFallthrough = I == MBB.end() || !I->isBarrier();
622 }
623
624 bool
canPredictBranchProbabilities(const MachineBasicBlock & MBB) const625 MIPrinter::canPredictBranchProbabilities(const MachineBasicBlock &MBB) const {
626 if (MBB.succ_size() <= 1)
627 return true;
628 if (!MBB.hasSuccessorProbabilities())
629 return true;
630
631 SmallVector<BranchProbability,8> Normalized(MBB.Probs.begin(),
632 MBB.Probs.end());
633 BranchProbability::normalizeProbabilities(Normalized.begin(),
634 Normalized.end());
635 SmallVector<BranchProbability,8> Equal(Normalized.size());
636 BranchProbability::normalizeProbabilities(Equal.begin(), Equal.end());
637
638 return std::equal(Normalized.begin(), Normalized.end(), Equal.begin());
639 }
640
canPredictSuccessors(const MachineBasicBlock & MBB) const641 bool MIPrinter::canPredictSuccessors(const MachineBasicBlock &MBB) const {
642 SmallVector<MachineBasicBlock*,8> GuessedSuccs;
643 bool GuessedFallthrough;
644 guessSuccessors(MBB, GuessedSuccs, GuessedFallthrough);
645 if (GuessedFallthrough) {
646 const MachineFunction &MF = *MBB.getParent();
647 MachineFunction::const_iterator NextI = std::next(MBB.getIterator());
648 if (NextI != MF.end()) {
649 MachineBasicBlock *Next = const_cast<MachineBasicBlock*>(&*NextI);
650 if (!is_contained(GuessedSuccs, Next))
651 GuessedSuccs.push_back(Next);
652 }
653 }
654 if (GuessedSuccs.size() != MBB.succ_size())
655 return false;
656 return std::equal(MBB.succ_begin(), MBB.succ_end(), GuessedSuccs.begin());
657 }
658
print(const MachineBasicBlock & MBB)659 void MIPrinter::print(const MachineBasicBlock &MBB) {
660 assert(MBB.getNumber() >= 0 && "Invalid MBB number");
661 MBB.printName(OS,
662 MachineBasicBlock::PrintNameIr |
663 MachineBasicBlock::PrintNameAttributes,
664 &MST);
665 OS << ":\n";
666
667 bool HasLineAttributes = false;
668 // Print the successors
669 bool canPredictProbs = canPredictBranchProbabilities(MBB);
670 // Even if the list of successors is empty, if we cannot guess it,
671 // we need to print it to tell the parser that the list is empty.
672 // This is needed, because MI model unreachable as empty blocks
673 // with an empty successor list. If the parser would see that
674 // without the successor list, it would guess the code would
675 // fallthrough.
676 if ((!MBB.succ_empty() && !SimplifyMIR) || !canPredictProbs ||
677 !canPredictSuccessors(MBB)) {
678 OS.indent(2) << "successors: ";
679 for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
680 if (I != MBB.succ_begin())
681 OS << ", ";
682 OS << printMBBReference(**I);
683 if (!SimplifyMIR || !canPredictProbs)
684 OS << '('
685 << format("0x%08" PRIx32, MBB.getSuccProbability(I).getNumerator())
686 << ')';
687 }
688 OS << "\n";
689 HasLineAttributes = true;
690 }
691
692 // Print the live in registers.
693 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
694 if (!MBB.livein_empty()) {
695 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
696 OS.indent(2) << "liveins: ";
697 bool First = true;
698 for (const auto &LI : MBB.liveins_dbg()) {
699 if (!First)
700 OS << ", ";
701 First = false;
702 OS << printReg(LI.PhysReg, &TRI);
703 if (!LI.LaneMask.all())
704 OS << ":0x" << PrintLaneMask(LI.LaneMask);
705 }
706 OS << "\n";
707 HasLineAttributes = true;
708 }
709
710 if (HasLineAttributes)
711 OS << "\n";
712 bool IsInBundle = false;
713 for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) {
714 const MachineInstr &MI = *I;
715 if (IsInBundle && !MI.isInsideBundle()) {
716 OS.indent(2) << "}\n";
717 IsInBundle = false;
718 }
719 OS.indent(IsInBundle ? 4 : 2);
720 print(MI);
721 if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
722 OS << " {";
723 IsInBundle = true;
724 }
725 OS << "\n";
726 }
727 if (IsInBundle)
728 OS.indent(2) << "}\n";
729 }
730
print(const MachineInstr & MI)731 void MIPrinter::print(const MachineInstr &MI) {
732 const auto *MF = MI.getMF();
733 const auto &MRI = MF->getRegInfo();
734 const auto &SubTarget = MF->getSubtarget();
735 const auto *TRI = SubTarget.getRegisterInfo();
736 assert(TRI && "Expected target register info");
737 const auto *TII = SubTarget.getInstrInfo();
738 assert(TII && "Expected target instruction info");
739 if (MI.isCFIInstruction())
740 assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
741
742 SmallBitVector PrintedTypes(8);
743 bool ShouldPrintRegisterTies = MI.hasComplexRegisterTies();
744 unsigned I = 0, E = MI.getNumOperands();
745 for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
746 !MI.getOperand(I).isImplicit();
747 ++I) {
748 if (I)
749 OS << ", ";
750 print(MI, I, TRI, TII, ShouldPrintRegisterTies,
751 MI.getTypeToPrint(I, PrintedTypes, MRI),
752 /*PrintDef=*/false);
753 }
754
755 if (I)
756 OS << " = ";
757 if (MI.getFlag(MachineInstr::FrameSetup))
758 OS << "frame-setup ";
759 if (MI.getFlag(MachineInstr::FrameDestroy))
760 OS << "frame-destroy ";
761 if (MI.getFlag(MachineInstr::FmNoNans))
762 OS << "nnan ";
763 if (MI.getFlag(MachineInstr::FmNoInfs))
764 OS << "ninf ";
765 if (MI.getFlag(MachineInstr::FmNsz))
766 OS << "nsz ";
767 if (MI.getFlag(MachineInstr::FmArcp))
768 OS << "arcp ";
769 if (MI.getFlag(MachineInstr::FmContract))
770 OS << "contract ";
771 if (MI.getFlag(MachineInstr::FmAfn))
772 OS << "afn ";
773 if (MI.getFlag(MachineInstr::FmReassoc))
774 OS << "reassoc ";
775 if (MI.getFlag(MachineInstr::NoUWrap))
776 OS << "nuw ";
777 if (MI.getFlag(MachineInstr::NoSWrap))
778 OS << "nsw ";
779 if (MI.getFlag(MachineInstr::IsExact))
780 OS << "exact ";
781 if (MI.getFlag(MachineInstr::NoFPExcept))
782 OS << "nofpexcept ";
783 if (MI.getFlag(MachineInstr::NoMerge))
784 OS << "nomerge ";
785
786 OS << TII->getName(MI.getOpcode());
787 if (I < E)
788 OS << ' ';
789
790 bool NeedComma = false;
791 for (; I < E; ++I) {
792 if (NeedComma)
793 OS << ", ";
794 print(MI, I, TRI, TII, ShouldPrintRegisterTies,
795 MI.getTypeToPrint(I, PrintedTypes, MRI));
796 NeedComma = true;
797 }
798
799 // Print any optional symbols attached to this instruction as-if they were
800 // operands.
801 if (MCSymbol *PreInstrSymbol = MI.getPreInstrSymbol()) {
802 if (NeedComma)
803 OS << ',';
804 OS << " pre-instr-symbol ";
805 MachineOperand::printSymbol(OS, *PreInstrSymbol);
806 NeedComma = true;
807 }
808 if (MCSymbol *PostInstrSymbol = MI.getPostInstrSymbol()) {
809 if (NeedComma)
810 OS << ',';
811 OS << " post-instr-symbol ";
812 MachineOperand::printSymbol(OS, *PostInstrSymbol);
813 NeedComma = true;
814 }
815 if (MDNode *HeapAllocMarker = MI.getHeapAllocMarker()) {
816 if (NeedComma)
817 OS << ',';
818 OS << " heap-alloc-marker ";
819 HeapAllocMarker->printAsOperand(OS, MST);
820 NeedComma = true;
821 }
822
823 if (auto Num = MI.peekDebugInstrNum()) {
824 if (NeedComma)
825 OS << ',';
826 OS << " debug-instr-number " << Num;
827 NeedComma = true;
828 }
829
830 if (PrintLocations) {
831 if (const DebugLoc &DL = MI.getDebugLoc()) {
832 if (NeedComma)
833 OS << ',';
834 OS << " debug-location ";
835 DL->printAsOperand(OS, MST);
836 }
837 }
838
839 if (!MI.memoperands_empty()) {
840 OS << " :: ";
841 const LLVMContext &Context = MF->getFunction().getContext();
842 const MachineFrameInfo &MFI = MF->getFrameInfo();
843 bool NeedComma = false;
844 for (const auto *Op : MI.memoperands()) {
845 if (NeedComma)
846 OS << ", ";
847 Op->print(OS, MST, SSNs, Context, &MFI, TII);
848 NeedComma = true;
849 }
850 }
851 }
852
printStackObjectReference(int FrameIndex)853 void MIPrinter::printStackObjectReference(int FrameIndex) {
854 auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
855 assert(ObjectInfo != StackObjectOperandMapping.end() &&
856 "Invalid frame index");
857 const FrameIndexOperand &Operand = ObjectInfo->second;
858 MachineOperand::printStackObjectReference(OS, Operand.ID, Operand.IsFixed,
859 Operand.Name);
860 }
861
formatOperandComment(std::string Comment)862 static std::string formatOperandComment(std::string Comment) {
863 if (Comment.empty())
864 return Comment;
865 return std::string(" /* " + Comment + " */");
866 }
867
print(const MachineInstr & MI,unsigned OpIdx,const TargetRegisterInfo * TRI,const TargetInstrInfo * TII,bool ShouldPrintRegisterTies,LLT TypeToPrint,bool PrintDef)868 void MIPrinter::print(const MachineInstr &MI, unsigned OpIdx,
869 const TargetRegisterInfo *TRI,
870 const TargetInstrInfo *TII,
871 bool ShouldPrintRegisterTies, LLT TypeToPrint,
872 bool PrintDef) {
873 const MachineOperand &Op = MI.getOperand(OpIdx);
874 std::string MOComment = TII->createMIROperandComment(MI, Op, OpIdx, TRI);
875
876 switch (Op.getType()) {
877 case MachineOperand::MO_Immediate:
878 if (MI.isOperandSubregIdx(OpIdx)) {
879 MachineOperand::printTargetFlags(OS, Op);
880 MachineOperand::printSubRegIdx(OS, Op.getImm(), TRI);
881 break;
882 }
883 LLVM_FALLTHROUGH;
884 case MachineOperand::MO_Register:
885 case MachineOperand::MO_CImmediate:
886 case MachineOperand::MO_FPImmediate:
887 case MachineOperand::MO_MachineBasicBlock:
888 case MachineOperand::MO_ConstantPoolIndex:
889 case MachineOperand::MO_TargetIndex:
890 case MachineOperand::MO_JumpTableIndex:
891 case MachineOperand::MO_ExternalSymbol:
892 case MachineOperand::MO_GlobalAddress:
893 case MachineOperand::MO_RegisterLiveOut:
894 case MachineOperand::MO_Metadata:
895 case MachineOperand::MO_MCSymbol:
896 case MachineOperand::MO_CFIIndex:
897 case MachineOperand::MO_IntrinsicID:
898 case MachineOperand::MO_Predicate:
899 case MachineOperand::MO_BlockAddress:
900 case MachineOperand::MO_ShuffleMask: {
901 unsigned TiedOperandIdx = 0;
902 if (ShouldPrintRegisterTies && Op.isReg() && Op.isTied() && !Op.isDef())
903 TiedOperandIdx = Op.getParent()->findTiedOperandIdx(OpIdx);
904 const TargetIntrinsicInfo *TII = MI.getMF()->getTarget().getIntrinsicInfo();
905 Op.print(OS, MST, TypeToPrint, OpIdx, PrintDef, /*IsStandalone=*/false,
906 ShouldPrintRegisterTies, TiedOperandIdx, TRI, TII);
907 OS << formatOperandComment(MOComment);
908 break;
909 }
910 case MachineOperand::MO_FrameIndex:
911 printStackObjectReference(Op.getIndex());
912 break;
913 case MachineOperand::MO_RegisterMask: {
914 auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
915 if (RegMaskInfo != RegisterMaskIds.end())
916 OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
917 else
918 printCustomRegMask(Op.getRegMask(), OS, TRI);
919 break;
920 }
921 }
922 }
923
printIRValue(raw_ostream & OS,const Value & V,ModuleSlotTracker & MST)924 void MIRFormatter::printIRValue(raw_ostream &OS, const Value &V,
925 ModuleSlotTracker &MST) {
926 if (isa<GlobalValue>(V)) {
927 V.printAsOperand(OS, /*PrintType=*/false, MST);
928 return;
929 }
930 if (isa<Constant>(V)) {
931 // Machine memory operands can load/store to/from constant value pointers.
932 OS << '`';
933 V.printAsOperand(OS, /*PrintType=*/true, MST);
934 OS << '`';
935 return;
936 }
937 OS << "%ir.";
938 if (V.hasName()) {
939 printLLVMNameWithoutPrefix(OS, V.getName());
940 return;
941 }
942 int Slot = MST.getCurrentFunction() ? MST.getLocalSlot(&V) : -1;
943 MachineOperand::printIRSlotNumber(OS, Slot);
944 }
945
printMIR(raw_ostream & OS,const Module & M)946 void llvm::printMIR(raw_ostream &OS, const Module &M) {
947 yaml::Output Out(OS);
948 Out << const_cast<Module &>(M);
949 }
950
printMIR(raw_ostream & OS,const MachineFunction & MF)951 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
952 MIRPrinter Printer(OS);
953 Printer.print(MF);
954 }
955