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/StringExtras.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/CodeGen/MIRFormatter.h"
23#include "llvm/CodeGen/MIRYamlMapping.h"
24#include "llvm/CodeGen/MachineBasicBlock.h"
25#include "llvm/CodeGen/MachineConstantPool.h"
26#include "llvm/CodeGen/MachineFrameInfo.h"
27#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFunctionAnalysis.h"
29#include "llvm/CodeGen/MachineInstr.h"
30#include "llvm/CodeGen/MachineJumpTableInfo.h"
31#include "llvm/CodeGen/MachineMemOperand.h"
32#include "llvm/CodeGen/MachineModuleInfo.h"
33#include "llvm/CodeGen/MachineModuleSlotTracker.h"
34#include "llvm/CodeGen/MachineOperand.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
36#include "llvm/CodeGen/TargetFrameLowering.h"
37#include "llvm/CodeGen/TargetInstrInfo.h"
38#include "llvm/CodeGen/TargetRegisterInfo.h"
39#include "llvm/CodeGen/TargetSubtargetInfo.h"
40#include "llvm/CodeGen/VirtRegMap.h"
41#include "llvm/CodeGenTypes/LowLevelType.h"
42#include "llvm/IR/DebugInfoMetadata.h"
43#include "llvm/IR/DebugLoc.h"
44#include "llvm/IR/Function.h"
45#include "llvm/IR/IRPrintingPasses.h"
46#include "llvm/IR/InlineAsm.h"
47#include "llvm/IR/Instructions.h"
48#include "llvm/IR/Module.h"
49#include "llvm/IR/ModuleSlotTracker.h"
50#include "llvm/IR/Value.h"
51#include "llvm/MC/LaneBitmask.h"
52#include "llvm/Support/BranchProbability.h"
53#include "llvm/Support/Casting.h"
54#include "llvm/Support/CommandLine.h"
55#include "llvm/Support/ErrorHandling.h"
56#include "llvm/Support/Format.h"
57#include "llvm/Support/YAMLTraits.h"
58#include "llvm/Support/raw_ostream.h"
59#include "llvm/Target/TargetMachine.h"
60#include <algorithm>
61#include <cassert>
62#include <cinttypes>
63#include <cstdint>
64#include <iterator>
65#include <string>
66#include <utility>
67#include <vector>
68
69using namespace llvm;
70
71static cl::opt<bool> SimplifyMIR(
72 "simplify-mir", cl::Hidden,
73 cl::desc("Leave out unnecessary information when printing MIR"));
74
75static cl::opt<bool> PrintLocations("mir-debug-loc", cl::Hidden, cl::init(Val: true),
76 cl::desc("Print MIR debug-locations"));
77
78namespace {
79
80/// This structure describes how to print out stack object references.
81struct FrameIndexOperand {
82 std::string Name;
83 unsigned ID;
84 bool IsFixed;
85
86 FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
87 : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
88
89 /// Return an ordinary stack object reference.
90 static FrameIndexOperand create(StringRef Name, unsigned ID) {
91 return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
92 }
93
94 /// Return a fixed stack object reference.
95 static FrameIndexOperand createFixed(unsigned ID) {
96 return FrameIndexOperand("", ID, /*IsFixed=*/true);
97 }
98};
99
100struct MFPrintState {
101 MachineModuleSlotTracker MST;
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 /// Synchronization scope names registered with LLVMContext.
107 SmallVector<StringRef, 8> SSNs;
108
109 MFPrintState(MFGetterFnT Fn, const MachineFunction &MF)
110 : MST(std::move(Fn), &MF) {}
111};
112
113} // end anonymous namespace
114
115/// This struct serializes the LLVM IR module.
116template <> struct yaml::BlockScalarTraits<Module> {
117 static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
118 Mod.print(OS, AAW: nullptr);
119 }
120
121 static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
122 llvm_unreachable("LLVM Module is supposed to be parsed separately");
123 return "";
124 }
125};
126
127static void printRegMIR(Register Reg, yaml::StringValue &Dest,
128 const TargetRegisterInfo *TRI) {
129 raw_string_ostream OS(Dest.Value);
130 OS << printReg(Reg, TRI);
131}
132
133static DenseMap<const uint32_t *, unsigned>
134initRegisterMaskIds(const MachineFunction &MF) {
135 DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
136 const auto *TRI = MF.getSubtarget().getRegisterInfo();
137 unsigned I = 0;
138 for (const uint32_t *Mask : TRI->getRegMasks())
139 RegisterMaskIds.insert(KV: std::make_pair(x&: Mask, y: I++));
140 return RegisterMaskIds;
141}
142
143static void printMBB(raw_ostream &OS, MFPrintState &State,
144 const MachineBasicBlock &MBB);
145static void convertMRI(yaml::MachineFunction &YamlMF, const MachineFunction &MF,
146 const MachineRegisterInfo &RegInfo,
147 const TargetRegisterInfo *TRI, const VirtRegMap *VRM);
148static void convertMCP(yaml::MachineFunction &MF,
149 const MachineConstantPool &ConstantPool);
150static void convertMJTI(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
151 const MachineJumpTableInfo &JTI);
152static void convertMFI(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
153 const MachineFrameInfo &MFI,
154 const TargetRegisterInfo *TRI);
155static void
156convertSRPoints(ModuleSlotTracker &MST,
157 std::vector<yaml::SaveRestorePointEntry> &YamlSRPoints,
158 const llvm::SaveRestorePoints &SRPoints,
159 const TargetRegisterInfo *TRI);
160static void convertStackObjects(yaml::MachineFunction &YMF,
161 const MachineFunction &MF,
162 ModuleSlotTracker &MST, MFPrintState &State);
163static void convertEntryValueObjects(yaml::MachineFunction &YMF,
164 const MachineFunction &MF,
165 ModuleSlotTracker &MST);
166static void convertCallSiteObjects(yaml::MachineFunction &YMF,
167 const MachineFunction &MF,
168 ModuleSlotTracker &MST);
169static void convertMachineMetadataNodes(yaml::MachineFunction &YMF,
170 const MachineFunction &MF,
171 MachineModuleSlotTracker &MST);
172static void convertCalledGlobals(yaml::MachineFunction &YMF,
173 const MachineFunction &MF,
174 MachineModuleSlotTracker &MST);
175static void convertPrefetchTargets(yaml::MachineFunction &YMF,
176 const MachineFunction &MF);
177
178static void printMF(raw_ostream &OS, MFGetterFnT Fn, const MachineFunction &MF,
179 const VirtRegMap *VRM) {
180 MFPrintState State(std::move(Fn), MF);
181
182 State.RegisterMaskIds = initRegisterMaskIds(MF);
183
184 yaml::MachineFunction YamlMF;
185 YamlMF.Name = MF.getName();
186 YamlMF.Alignment = MF.getAlignment();
187 YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
188 YamlMF.HasWinCFI = MF.hasWinCFI();
189
190 YamlMF.CallsEHReturn = MF.callsEHReturn();
191 YamlMF.CallsUnwindInit = MF.callsUnwindInit();
192 YamlMF.HasEHContTarget = MF.hasEHContTarget();
193 YamlMF.HasEHScopes = MF.hasEHScopes();
194 YamlMF.HasEHFunclets = MF.hasEHFunclets();
195 YamlMF.HasFakeUses = MF.hasFakeUses();
196 YamlMF.IsOutlined = MF.isOutlined();
197 YamlMF.UseDebugInstrRef = MF.useDebugInstrRef();
198
199 const MachineFunctionProperties &Props = MF.getProperties();
200 YamlMF.Legalized = Props.hasLegalized();
201 YamlMF.RegBankSelected = Props.hasRegBankSelected();
202 YamlMF.Selected = Props.hasSelected();
203 YamlMF.FailedISel = Props.hasFailedISel();
204 YamlMF.FailsVerification = Props.hasFailsVerification();
205 YamlMF.TracksDebugUserValues = Props.hasTracksDebugUserValues();
206 YamlMF.NoPHIs = Props.hasNoPHIs();
207 YamlMF.IsSSA = Props.hasIsSSA();
208 YamlMF.NoVRegs = Props.hasNoVRegs();
209
210 convertMRI(YamlMF, MF, RegInfo: MF.getRegInfo(), TRI: MF.getSubtarget().getRegisterInfo(),
211 VRM);
212 MachineModuleSlotTracker &MST = State.MST;
213 MST.incorporateFunction(F: MF.getFunction());
214 convertMFI(MST, YamlMFI&: YamlMF.FrameInfo, MFI: MF.getFrameInfo(),
215 TRI: MF.getSubtarget().getRegisterInfo());
216 convertStackObjects(YMF&: YamlMF, MF, MST, State);
217 convertEntryValueObjects(YMF&: YamlMF, MF, MST);
218 convertCallSiteObjects(YMF&: YamlMF, MF, MST);
219 for (const auto &Sub : MF.DebugValueSubstitutions) {
220 const auto &SubSrc = Sub.Src;
221 const auto &SubDest = Sub.Dest;
222 YamlMF.DebugValueSubstitutions.push_back(x: {.SrcInst: SubSrc.first, .SrcOp: SubSrc.second,
223 .DstInst: SubDest.first,
224 .DstOp: SubDest.second,
225 .Subreg: Sub.Subreg});
226 }
227 if (const auto *ConstantPool = MF.getConstantPool())
228 convertMCP(MF&: YamlMF, ConstantPool: *ConstantPool);
229 if (const auto *JumpTableInfo = MF.getJumpTableInfo())
230 convertMJTI(MST, YamlJTI&: YamlMF.JumpTableInfo, JTI: *JumpTableInfo);
231
232 const TargetMachine &TM = MF.getTarget();
233 YamlMF.MachineFuncInfo =
234 std::unique_ptr<yaml::MachineFunctionInfo>(TM.convertFuncInfoToYAML(MF));
235
236 raw_string_ostream StrOS(YamlMF.Body.Value.Value);
237 bool IsNewlineNeeded = false;
238 for (const auto &MBB : MF) {
239 if (IsNewlineNeeded)
240 StrOS << "\n";
241 printMBB(OS&: StrOS, State, MBB);
242 IsNewlineNeeded = true;
243 }
244 // Convert machine metadata collected during the print of the machine
245 // function.
246 convertMachineMetadataNodes(YMF&: YamlMF, MF, MST);
247
248 convertCalledGlobals(YMF&: YamlMF, MF, MST);
249
250 convertPrefetchTargets(YMF&: YamlMF, MF);
251
252 yaml::Output Out(OS);
253 if (!SimplifyMIR)
254 Out.setWriteDefaultValues(true);
255 Out << YamlMF;
256}
257
258static void printCustomRegMask(const uint32_t *RegMask, raw_ostream &OS,
259 const TargetRegisterInfo *TRI) {
260 assert(RegMask && "Can't print an empty register mask");
261 OS << StringRef("CustomRegMask(");
262
263 bool IsRegInRegMaskFound = false;
264 for (int I = 0, E = TRI->getNumRegs(); I < E; I++) {
265 // Check whether the register is asserted in regmask.
266 if (RegMask[I / 32] & (1u << (I % 32))) {
267 if (IsRegInRegMaskFound)
268 OS << ',';
269 OS << printReg(Reg: I, TRI);
270 IsRegInRegMaskFound = true;
271 }
272 }
273
274 OS << ')';
275}
276
277static void printRegClassOrBank(Register Reg, yaml::StringValue &Dest,
278 const MachineRegisterInfo &RegInfo,
279 const TargetRegisterInfo *TRI) {
280 raw_string_ostream OS(Dest.Value);
281 OS << printRegClassOrBank(Reg, RegInfo, TRI);
282}
283
284template <typename T>
285static void
286printStackObjectDbgInfo(const MachineFunction::VariableDbgInfo &DebugVar,
287 T &Object, ModuleSlotTracker &MST) {
288 std::array<std::string *, 3> Outputs{{&Object.DebugVar.Value,
289 &Object.DebugExpr.Value,
290 &Object.DebugLoc.Value}};
291 std::array<const Metadata *, 3> Metas{._M_elems: {DebugVar.Var,
292 DebugVar.Expr,
293 DebugVar.Loc}};
294 for (unsigned i = 0; i < 3; ++i) {
295 raw_string_ostream StrOS(*Outputs[i]);
296 Metas[i]->printAsOperand(OS&: StrOS, MST);
297 }
298}
299
300static void printRegFlags(Register Reg,
301 std::vector<yaml::FlowStringValue> &RegisterFlags,
302 const MachineFunction &MF,
303 const TargetRegisterInfo *TRI) {
304 auto FlagValues = TRI->getVRegFlagsOfReg(Reg, MF);
305 for (auto &Flag : FlagValues)
306 RegisterFlags.push_back(x: yaml::FlowStringValue(Flag.str()));
307}
308
309static void convertMRI(yaml::MachineFunction &YamlMF, const MachineFunction &MF,
310 const MachineRegisterInfo &RegInfo,
311 const TargetRegisterInfo *TRI, const VirtRegMap *VRM) {
312 YamlMF.TracksRegLiveness = RegInfo.tracksLiveness();
313
314 // Print the virtual register definitions.
315 for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
316 Register Reg = Register::index2VirtReg(Index: I);
317 yaml::VirtualRegisterDefinition VReg;
318 VReg.ID = I;
319 if (RegInfo.getVRegName(Reg) != "")
320 continue;
321 ::printRegClassOrBank(Reg, Dest&: VReg.Class, RegInfo, TRI);
322 Register PreferredReg = RegInfo.getSimpleHint(VReg: Reg);
323 if (PreferredReg)
324 printRegMIR(Reg: PreferredReg, Dest&: VReg.PreferredRegister, TRI);
325 printRegFlags(Reg, RegisterFlags&: VReg.RegisterFlags, MF, TRI);
326
327 // Print the anti-hints.
328 const auto &AntiHints = RegInfo.getRegAllocationAntiHints(VReg: Reg);
329 if (!AntiHints.empty()) {
330 std::vector<yaml::FlowStringValue> AntiHintStrings;
331 for (Register AntiHint : AntiHints) {
332 yaml::FlowStringValue AntiHintStr;
333 printRegMIR(Reg: AntiHint, Dest&: AntiHintStr, TRI);
334 AntiHintStrings.push_back(x: std::move(AntiHintStr));
335 }
336 VReg.AntiHints = std::move(AntiHintStrings);
337 }
338 if (VRM) {
339 Register Orig = VRM->getPreSplitReg(virtReg: Reg);
340 if (Orig && Orig != Reg) {
341 raw_string_ostream OS(VReg.SplitFrom.Value);
342 OS << printReg(Reg: Orig, TRI);
343 }
344 if (VRM->hasPhys(virtReg: Reg)) {
345 raw_string_ostream OS(VReg.AssignedPhys.Value);
346 OS << printReg(Reg: VRM->getPhys(virtReg: Reg), TRI);
347 }
348 }
349 YamlMF.VirtualRegisters.push_back(x: std::move(VReg));
350 }
351
352 // Print the live ins.
353 for (std::pair<MCRegister, Register> LI : RegInfo.liveins()) {
354 yaml::MachineFunctionLiveIn LiveIn;
355 printRegMIR(Reg: LI.first, Dest&: LiveIn.Register, TRI);
356 if (LI.second)
357 printRegMIR(Reg: LI.second, Dest&: LiveIn.VirtualRegister, TRI);
358 YamlMF.LiveIns.push_back(x: std::move(LiveIn));
359 }
360
361 // Prints the callee saved registers.
362 if (RegInfo.isUpdatedCSRsInitialized()) {
363 const MCPhysReg *CalleeSavedRegs = RegInfo.getCalleeSavedRegs();
364 std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
365 for (const MCPhysReg *I = CalleeSavedRegs; *I; ++I) {
366 yaml::FlowStringValue Reg;
367 printRegMIR(Reg: *I, Dest&: Reg, TRI);
368 CalleeSavedRegisters.push_back(x: std::move(Reg));
369 }
370 YamlMF.CalleeSavedRegisters = std::move(CalleeSavedRegisters);
371 }
372}
373
374static void convertMFI(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
375 const MachineFrameInfo &MFI,
376 const TargetRegisterInfo *TRI) {
377 YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
378 YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
379 YamlMFI.HasStackMap = MFI.hasStackMap();
380 YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
381 YamlMFI.StackSize = MFI.getStackSize();
382 YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
383 YamlMFI.MaxAlignment = MFI.getMaxAlign().value();
384 YamlMFI.AdjustsStack = MFI.adjustsStack();
385 YamlMFI.HasCalls = MFI.hasCalls();
386 YamlMFI.FramePointerPolicy = MFI.getFramePointerPolicy();
387 YamlMFI.MaxCallFrameSize = MFI.isMaxCallFrameSizeComputed()
388 ? MFI.getMaxCallFrameSize() : ~0u;
389 YamlMFI.CVBytesOfCalleeSavedRegisters =
390 MFI.getCVBytesOfCalleeSavedRegisters();
391 YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
392 YamlMFI.HasVAStart = MFI.hasVAStart();
393 YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
394 YamlMFI.HasTailCall = MFI.hasTailCall();
395 YamlMFI.IsCalleeSavedInfoValid = MFI.isCalleeSavedInfoValid();
396 YamlMFI.LocalFrameSize = MFI.getLocalFrameSize();
397 if (!MFI.getSavePoints().empty())
398 convertSRPoints(MST, YamlSRPoints&: YamlMFI.SavePoints, SRPoints: MFI.getSavePoints(), TRI);
399 if (!MFI.getRestorePoints().empty())
400 convertSRPoints(MST, YamlSRPoints&: YamlMFI.RestorePoints, SRPoints: MFI.getRestorePoints(), TRI);
401}
402
403static void convertEntryValueObjects(yaml::MachineFunction &YMF,
404 const MachineFunction &MF,
405 ModuleSlotTracker &MST) {
406 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
407 for (const MachineFunction::VariableDbgInfo &DebugVar :
408 MF.getEntryValueVariableDbgInfo()) {
409 yaml::EntryValueObject &Obj = YMF.EntryValueObjects.emplace_back();
410 printStackObjectDbgInfo(DebugVar, Object&: Obj, MST);
411 MCRegister EntryValReg = DebugVar.getEntryValueRegister();
412 printRegMIR(Reg: EntryValReg, Dest&: Obj.EntryValueRegister, TRI);
413 }
414}
415
416static void printStackObjectReference(raw_ostream &OS,
417 const MFPrintState &State,
418 int FrameIndex) {
419 auto ObjectInfo = State.StackObjectOperandMapping.find(Val: FrameIndex);
420 assert(ObjectInfo != State.StackObjectOperandMapping.end() &&
421 "Invalid frame index");
422 const FrameIndexOperand &Operand = ObjectInfo->second;
423 MachineOperand::printStackObjectReference(OS, FrameIndex: Operand.ID, IsFixed: Operand.IsFixed,
424 Name: Operand.Name);
425}
426
427static void convertStackObjects(yaml::MachineFunction &YMF,
428 const MachineFunction &MF,
429 ModuleSlotTracker &MST, MFPrintState &State) {
430 const MachineFrameInfo &MFI = MF.getFrameInfo();
431 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
432
433 // Process fixed stack objects.
434 assert(YMF.FixedStackObjects.empty());
435 SmallVector<int, 32> FixedStackObjectsIdx;
436 const int BeginIdx = MFI.getObjectIndexBegin();
437 if (BeginIdx < 0)
438 FixedStackObjectsIdx.reserve(N: -BeginIdx);
439
440 unsigned ID = 0;
441 for (int I = BeginIdx; I < 0; ++I, ++ID) {
442 FixedStackObjectsIdx.push_back(Elt: -1); // Fill index for possible dead.
443 if (MFI.isDeadObjectIndex(ObjectIdx: I))
444 continue;
445
446 yaml::FixedMachineStackObject YamlObject;
447 YamlObject.ID = ID;
448 YamlObject.Type = MFI.isSpillSlotObjectIndex(ObjectIdx: I)
449 ? yaml::FixedMachineStackObject::SpillSlot
450 : yaml::FixedMachineStackObject::DefaultType;
451 YamlObject.Offset = MFI.getObjectOffset(ObjectIdx: I);
452 YamlObject.Size = MFI.getObjectSize(ObjectIdx: I);
453 YamlObject.Alignment = MFI.getObjectAlign(ObjectIdx: I);
454 YamlObject.StackID = (TargetStackID::Value)MFI.getStackID(ObjectIdx: I);
455 YamlObject.IsImmutable = MFI.isImmutableObjectIndex(ObjectIdx: I);
456 YamlObject.IsAliased = MFI.isAliasedObjectIndex(ObjectIdx: I);
457 // Save the ID' position in FixedStackObjects storage vector.
458 FixedStackObjectsIdx[ID] = YMF.FixedStackObjects.size();
459 YMF.FixedStackObjects.push_back(x: std::move(YamlObject));
460 State.StackObjectOperandMapping.insert(
461 KV: std::make_pair(x&: I, y: FrameIndexOperand::createFixed(ID)));
462 }
463
464 // Process ordinary stack objects.
465 assert(YMF.StackObjects.empty());
466 SmallVector<unsigned, 32> StackObjectsIdx;
467 const int EndIdx = MFI.getObjectIndexEnd();
468 if (EndIdx > 0)
469 StackObjectsIdx.reserve(N: EndIdx);
470 ID = 0;
471 for (int I = 0; I < EndIdx; ++I, ++ID) {
472 StackObjectsIdx.push_back(Elt: -1); // Fill index for possible dead.
473 if (MFI.isDeadObjectIndex(ObjectIdx: I))
474 continue;
475
476 yaml::MachineStackObject YamlObject;
477 YamlObject.ID = ID;
478 if (const auto *Alloca = MFI.getObjectAllocation(ObjectIdx: I))
479 YamlObject.Name.Value = std::string(
480 Alloca->hasName() ? Alloca->getName() : "");
481 YamlObject.Type = MFI.isSpillSlotObjectIndex(ObjectIdx: I)
482 ? yaml::MachineStackObject::SpillSlot
483 : MFI.isVariableSizedObjectIndex(ObjectIdx: I)
484 ? yaml::MachineStackObject::VariableSized
485 : yaml::MachineStackObject::DefaultType;
486 YamlObject.Offset = MFI.getObjectOffset(ObjectIdx: I);
487 YamlObject.Size = MFI.getObjectSize(ObjectIdx: I);
488 YamlObject.Alignment = MFI.getObjectAlign(ObjectIdx: I);
489 YamlObject.StackID = (TargetStackID::Value)MFI.getStackID(ObjectIdx: I);
490
491 // Save the ID' position in StackObjects storage vector.
492 StackObjectsIdx[ID] = YMF.StackObjects.size();
493 YMF.StackObjects.push_back(x: YamlObject);
494 State.StackObjectOperandMapping.insert(KV: std::make_pair(
495 x&: I, y: FrameIndexOperand::create(Name: YamlObject.Name.Value, ID)));
496 }
497
498 for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
499 const int FrameIdx = CSInfo.getFrameIdx();
500 if (!CSInfo.isSpilledToReg() && MFI.isDeadObjectIndex(ObjectIdx: FrameIdx))
501 continue;
502
503 yaml::StringValue Reg;
504 printRegMIR(Reg: CSInfo.getReg(), Dest&: Reg, TRI);
505 if (!CSInfo.isSpilledToReg()) {
506 assert(FrameIdx >= MFI.getObjectIndexBegin() &&
507 FrameIdx < MFI.getObjectIndexEnd() &&
508 "Invalid stack object index");
509 if (FrameIdx < 0) { // Negative index means fixed objects.
510 auto &Object =
511 YMF.FixedStackObjects
512 [FixedStackObjectsIdx[FrameIdx + MFI.getNumFixedObjects()]];
513 Object.CalleeSavedRegister = std::move(Reg);
514 Object.CalleeSavedRestored = CSInfo.isRestored();
515 } else {
516 auto &Object = YMF.StackObjects[StackObjectsIdx[FrameIdx]];
517 Object.CalleeSavedRegister = std::move(Reg);
518 Object.CalleeSavedRestored = CSInfo.isRestored();
519 }
520 }
521 }
522 for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) {
523 auto LocalObject = MFI.getLocalFrameObjectMap(i: I);
524 assert(LocalObject.first >= 0 && "Expected a locally mapped stack object");
525 YMF.StackObjects[StackObjectsIdx[LocalObject.first]].LocalOffset =
526 LocalObject.second;
527 }
528
529 // Print the stack object references in the frame information class after
530 // converting the stack objects.
531 if (MFI.hasStackProtectorIndex()) {
532 raw_string_ostream StrOS(YMF.FrameInfo.StackProtector.Value);
533 printStackObjectReference(OS&: StrOS, State, FrameIndex: MFI.getStackProtectorIndex());
534 }
535
536 if (MFI.hasFunctionContextIndex()) {
537 raw_string_ostream StrOS(YMF.FrameInfo.FunctionContext.Value);
538 printStackObjectReference(OS&: StrOS, State, FrameIndex: MFI.getFunctionContextIndex());
539 }
540
541 // Print the debug variable information.
542 for (const MachineFunction::VariableDbgInfo &DebugVar :
543 MF.getInStackSlotVariableDbgInfo()) {
544 int Idx = DebugVar.getStackSlot();
545 assert(Idx >= MFI.getObjectIndexBegin() && Idx < MFI.getObjectIndexEnd() &&
546 "Invalid stack object index");
547 if (Idx < 0) { // Negative index means fixed objects.
548 auto &Object =
549 YMF.FixedStackObjects[FixedStackObjectsIdx[Idx +
550 MFI.getNumFixedObjects()]];
551 printStackObjectDbgInfo(DebugVar, Object, MST);
552 } else {
553 auto &Object = YMF.StackObjects[StackObjectsIdx[Idx]];
554 printStackObjectDbgInfo(DebugVar, Object, MST);
555 }
556 }
557}
558
559static void convertCallSiteObjects(yaml::MachineFunction &YMF,
560 const MachineFunction &MF,
561 ModuleSlotTracker &MST) {
562 const auto *TRI = MF.getSubtarget().getRegisterInfo();
563 // Each entry with the number of its block and its offset, for sorting.
564 SmallVector<std::pair<std::pair<int, unsigned>, yaml::CallSiteInfo>> Entries;
565 for (auto [MI, CallSiteInfo] : MF.getCallSitesInfo()) {
566 yaml::CallSiteInfo YmlCS;
567 yaml::MachineInstrLoc CallLocation;
568
569 // Prepare instruction position.
570 MachineBasicBlock::const_instr_iterator CallI = MI->getIterator();
571 const MachineBasicBlock &MBB = *CallI->getParent();
572 raw_string_ostream StrOS(CallLocation.Block.Value);
573 StrOS << printMBBReference(MBB);
574 // Get call instruction offset from the beginning of block.
575 CallLocation.Offset = std::distance(first: MBB.instr_begin(), last: CallI);
576 YmlCS.CallLocation = CallLocation;
577
578 auto [ArgRegPairs, CalleeTypeIds, _] = CallSiteInfo;
579 // Construct call arguments and theirs forwarding register info.
580 for (auto ArgReg : ArgRegPairs) {
581 yaml::CallSiteInfo::ArgRegPair YmlArgReg;
582 YmlArgReg.ArgNo = ArgReg.ArgNo;
583 printRegMIR(Reg: ArgReg.Reg, Dest&: YmlArgReg.Reg, TRI);
584 YmlCS.ArgForwardingRegs.emplace_back(args&: YmlArgReg);
585 }
586 // Get type ids.
587 for (auto *CalleeTypeId : CalleeTypeIds) {
588 YmlCS.CalleeTypeIds.push_back(x: CalleeTypeId->getZExtValue());
589 }
590 Entries.push_back(
591 Elt: {{MBB.getNumber(), CallLocation.Offset}, std::move(YmlCS)});
592 }
593
594 // Sort call info by position of call instructions.
595 llvm::sort(Start: Entries.begin(), End: Entries.end(), Comp: llvm::less_first());
596 for (auto &Entry : Entries)
597 YMF.CallSitesInfo.push_back(x: std::move(Entry.second));
598}
599
600static void convertMachineMetadataNodes(yaml::MachineFunction &YMF,
601 const MachineFunction &MF,
602 MachineModuleSlotTracker &MST) {
603 MachineModuleSlotTracker::MachineMDNodeListType MDList;
604 MST.collectMachineMDNodes(L&: MDList);
605 for (auto &MD : MDList) {
606 std::string NS;
607 raw_string_ostream StrOS(NS);
608 MD.second->print(OS&: StrOS, MST, M: MF.getFunction().getParent());
609 YMF.MachineMetadataNodes.push_back(x: std::move(NS));
610 }
611}
612
613static void convertCalledGlobals(yaml::MachineFunction &YMF,
614 const MachineFunction &MF,
615 MachineModuleSlotTracker &MST) {
616 // Each entry with the number of its block and its offset, for sorting.
617 SmallVector<std::pair<std::pair<int, unsigned>, yaml::CalledGlobal>> Entries;
618 for (const auto &[CallInst, CG] : MF.getCalledGlobals()) {
619 const MachineBasicBlock &MBB = *CallInst->getParent();
620 yaml::MachineInstrLoc CallSite;
621 raw_string_ostream StrOS(CallSite.Block.Value);
622 StrOS << printMBBReference(MBB);
623 CallSite.Offset = std::distance(first: MBB.instr_begin(), last: CallInst->getIterator());
624
625 yaml::CalledGlobal YamlCG{.CallSite: CallSite, .Callee: CG.Callee->getName().str(),
626 .Flags: CG.TargetFlags};
627 Entries.push_back(Elt: {{MBB.getNumber(), CallSite.Offset}, std::move(YamlCG)});
628 }
629
630 // Sort by position of call instructions.
631 llvm::sort(Start: Entries.begin(), End: Entries.end(), Comp: llvm::less_first());
632 for (auto &Entry : Entries)
633 YMF.CalledGlobals.push_back(x: std::move(Entry.second));
634}
635
636static void convertPrefetchTargets(yaml::MachineFunction &YMF,
637 const MachineFunction &MF) {
638 for (const auto &[BBID, CallsiteIndexes] : MF.getPrefetchTargets()) {
639 for (auto CallsiteIndex : CallsiteIndexes) {
640 std::string Str;
641 raw_string_ostream StrOS(Str);
642 StrOS << "bb_id " << BBID.BaseID << ", " << BBID.CloneID << ", "
643 << CallsiteIndex;
644 YMF.PrefetchTargets.push_back(x: yaml::FlowStringValue(Str));
645 }
646 }
647}
648
649static void convertMCP(yaml::MachineFunction &MF,
650 const MachineConstantPool &ConstantPool) {
651 unsigned ID = 0;
652 for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
653 std::string Str;
654 raw_string_ostream StrOS(Str);
655 if (Constant.isMachineConstantPoolEntry())
656 Constant.Val.MachineCPVal->print(O&: StrOS);
657 else
658 Constant.Val.ConstVal->printAsOperand(O&: StrOS);
659
660 yaml::MachineConstantPoolValue YamlConstant;
661 YamlConstant.ID = ID++;
662 YamlConstant.Value = std::move(Str);
663 YamlConstant.Alignment = Constant.getAlign();
664 YamlConstant.IsTargetSpecific = Constant.isMachineConstantPoolEntry();
665
666 MF.Constants.push_back(x: std::move(YamlConstant));
667 }
668}
669
670static void
671convertSRPoints(ModuleSlotTracker &MST,
672 std::vector<yaml::SaveRestorePointEntry> &YamlSRPoints,
673 const llvm::SaveRestorePoints &SRPoints,
674 const TargetRegisterInfo *TRI) {
675 for (const auto &[MBB, CSInfos] : SRPoints) {
676 SmallString<16> Str;
677 yaml::SaveRestorePointEntry Entry;
678 raw_svector_ostream StrOS(Str);
679 StrOS << printMBBReference(MBB: *MBB);
680 Entry.Point = StrOS.str().str();
681 Str.clear();
682 for (const CalleeSavedInfo &Info : CSInfos) {
683 if (Info.getReg()) {
684 StrOS << printReg(Reg: Info.getReg(), TRI);
685 Entry.Registers.push_back(x: StrOS.str().str());
686 Str.clear();
687 }
688 }
689 // Sort here needed for stable output for lit tests
690 std::sort(first: Entry.Registers.begin(), last: Entry.Registers.end(),
691 comp: [](const yaml::StringValue &Lhs, const yaml::StringValue &Rhs) {
692 return Lhs.Value < Rhs.Value;
693 });
694 YamlSRPoints.push_back(x: std::move(Entry));
695 }
696 // Sort here needed for stable output for lit tests
697 std::sort(first: YamlSRPoints.begin(), last: YamlSRPoints.end(),
698 comp: [](const yaml::SaveRestorePointEntry &Lhs,
699 const yaml::SaveRestorePointEntry &Rhs) {
700 return Lhs.Point.Value < Rhs.Point.Value;
701 });
702}
703
704static void convertMJTI(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
705 const MachineJumpTableInfo &JTI) {
706 YamlJTI.Kind = JTI.getEntryKind();
707 unsigned ID = 0;
708 for (const auto &Table : JTI.getJumpTables()) {
709 std::string Str;
710 yaml::MachineJumpTable::Entry Entry;
711 Entry.ID = ID++;
712 for (const auto *MBB : Table.MBBs) {
713 raw_string_ostream StrOS(Str);
714 StrOS << printMBBReference(MBB: *MBB);
715 Entry.Blocks.push_back(x: Str);
716 Str.clear();
717 }
718 YamlJTI.Entries.push_back(x: std::move(Entry));
719 }
720}
721
722void llvm::guessSuccessors(const MachineBasicBlock &MBB,
723 SmallVectorImpl<MachineBasicBlock*> &Result,
724 bool &IsFallthrough) {
725 SmallPtrSet<MachineBasicBlock*,8> Seen;
726
727 for (const MachineInstr &MI : MBB) {
728 if (MI.isPHI())
729 continue;
730 for (const MachineOperand &MO : MI.operands()) {
731 if (!MO.isMBB())
732 continue;
733 MachineBasicBlock *Succ = MO.getMBB();
734 auto RP = Seen.insert(Ptr: Succ);
735 if (RP.second)
736 Result.push_back(Elt: Succ);
737 }
738 }
739 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
740 IsFallthrough = I == MBB.end() || !I->isBarrier();
741}
742
743static bool canPredictSuccessors(const MachineBasicBlock &MBB) {
744 SmallVector<MachineBasicBlock*,8> GuessedSuccs;
745 bool GuessedFallthrough;
746 guessSuccessors(MBB, Result&: GuessedSuccs, IsFallthrough&: GuessedFallthrough);
747 if (GuessedFallthrough) {
748 const MachineFunction &MF = *MBB.getParent();
749 MachineFunction::const_iterator NextI = std::next(x: MBB.getIterator());
750 if (NextI != MF.end()) {
751 MachineBasicBlock *Next = const_cast<MachineBasicBlock*>(&*NextI);
752 if (!is_contained(Range&: GuessedSuccs, Element: Next))
753 GuessedSuccs.push_back(Elt: Next);
754 }
755 }
756 if (GuessedSuccs.size() != MBB.succ_size())
757 return false;
758 return std::equal(first1: MBB.succ_begin(), last1: MBB.succ_end(), first2: GuessedSuccs.begin());
759}
760
761static void printMI(raw_ostream &OS, MFPrintState &State,
762 const MachineInstr &MI);
763
764static void printMIOperand(raw_ostream &OS, MFPrintState &State,
765 const MachineInstr &MI, unsigned OpIdx,
766 const TargetRegisterInfo *TRI,
767 const TargetInstrInfo *TII,
768 bool ShouldPrintRegisterTies,
769 SmallBitVector &PrintedTypes,
770 const MachineRegisterInfo &MRI, bool PrintDef);
771
772void printMBB(raw_ostream &OS, MFPrintState &State,
773 const MachineBasicBlock &MBB) {
774 assert(MBB.getNumber() >= 0 && "Invalid MBB number");
775 MBB.printName(os&: OS,
776 printNameFlags: MachineBasicBlock::PrintNameIr |
777 MachineBasicBlock::PrintNameAttributes,
778 moduleSlotTracker: &State.MST);
779 OS << ":\n";
780
781 bool HasLineAttributes = false;
782 // Print the successors
783 bool canPredictProbs = MBB.canPredictBranchProbabilities();
784 // Even if the list of successors is empty, if we cannot guess it,
785 // we need to print it to tell the parser that the list is empty.
786 // This is needed, because MI model unreachable as empty blocks
787 // with an empty successor list. If the parser would see that
788 // without the successor list, it would guess the code would
789 // fallthrough.
790 if ((!MBB.succ_empty() && !SimplifyMIR) || !canPredictProbs ||
791 !canPredictSuccessors(MBB)) {
792 OS.indent(NumSpaces: 2) << "successors:";
793 if (!MBB.succ_empty())
794 OS << " ";
795 ListSeparator LS;
796 for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
797 OS << LS << printMBBReference(MBB: **I);
798 if (!SimplifyMIR || !canPredictProbs)
799 OS << format(Fmt: "(0x%08" PRIx32 ")",
800 Vals: MBB.getSuccProbability(Succ: I).getNumerator());
801 }
802 OS << "\n";
803 HasLineAttributes = true;
804 }
805
806 // Print the live in registers.
807 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
808 if (!MBB.livein_empty()) {
809 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
810 OS.indent(NumSpaces: 2) << "liveins: ";
811 ListSeparator LS;
812 for (const auto &LI : MBB.liveins_dbg()) {
813 OS << LS << printReg(Reg: LI.PhysReg, TRI: &TRI);
814 if (!LI.LaneMask.all())
815 OS << ":0x" << PrintLaneMask(LaneMask: LI.LaneMask);
816 }
817 OS << "\n";
818 HasLineAttributes = true;
819 }
820
821 if (HasLineAttributes && !MBB.empty())
822 OS << "\n";
823 bool IsInBundle = false;
824 for (const MachineInstr &MI : MBB.instrs()) {
825 if (IsInBundle && !MI.isInsideBundle()) {
826 OS.indent(NumSpaces: 2) << "}\n";
827 IsInBundle = false;
828 }
829 OS.indent(NumSpaces: IsInBundle ? 4 : 2);
830 printMI(OS, State, MI);
831 if (!IsInBundle && MI.getFlag(Flag: MachineInstr::BundledSucc)) {
832 OS << " {";
833 IsInBundle = true;
834 }
835 OS << "\n";
836 }
837 if (IsInBundle)
838 OS.indent(NumSpaces: 2) << "}\n";
839}
840
841static void printMI(raw_ostream &OS, MFPrintState &State,
842 const MachineInstr &MI) {
843 const auto *MF = MI.getMF();
844 const auto &MRI = MF->getRegInfo();
845 const auto &SubTarget = MF->getSubtarget();
846 const auto *TRI = SubTarget.getRegisterInfo();
847 assert(TRI && "Expected target register info");
848 const auto *TII = SubTarget.getInstrInfo();
849 assert(TII && "Expected target instruction info");
850 if (MI.isCFIInstruction())
851 assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
852
853 SmallBitVector PrintedTypes(8);
854 bool ShouldPrintRegisterTies = MI.hasComplexRegisterTies();
855 ListSeparator LS;
856 unsigned I = 0, E = MI.getNumOperands();
857 for (; I < E; ++I) {
858 const MachineOperand MO = MI.getOperand(i: I);
859 if (!MO.isReg() || !MO.isDef() || MO.isImplicit())
860 break;
861 OS << LS;
862 printMIOperand(OS, State, MI, OpIdx: I, TRI, TII, ShouldPrintRegisterTies,
863 PrintedTypes, MRI, /*PrintDef=*/false);
864 }
865
866 if (I)
867 OS << " = ";
868 if (MI.getFlag(Flag: MachineInstr::FrameSetup))
869 OS << "frame-setup ";
870 if (MI.getFlag(Flag: MachineInstr::FrameDestroy))
871 OS << "frame-destroy ";
872 if (MI.getFlag(Flag: MachineInstr::FmNoNans))
873 OS << "nnan ";
874 if (MI.getFlag(Flag: MachineInstr::FmNoInfs))
875 OS << "ninf ";
876 if (MI.getFlag(Flag: MachineInstr::FmNsz))
877 OS << "nsz ";
878 if (MI.getFlag(Flag: MachineInstr::FmArcp))
879 OS << "arcp ";
880 if (MI.getFlag(Flag: MachineInstr::FmContract))
881 OS << "contract ";
882 if (MI.getFlag(Flag: MachineInstr::FmAfn))
883 OS << "afn ";
884 if (MI.getFlag(Flag: MachineInstr::FmReassoc))
885 OS << "reassoc ";
886 if (MI.getFlag(Flag: MachineInstr::NoUWrap))
887 OS << "nuw ";
888 if (MI.getFlag(Flag: MachineInstr::NoSWrap))
889 OS << "nsw ";
890 if (MI.getFlag(Flag: MachineInstr::IsExact))
891 OS << "exact ";
892 if (MI.getFlag(Flag: MachineInstr::NoFPExcept))
893 OS << "nofpexcept ";
894 if (MI.getFlag(Flag: MachineInstr::NoMerge))
895 OS << "nomerge ";
896 if (MI.getFlag(Flag: MachineInstr::Unpredictable))
897 OS << "unpredictable ";
898 if (MI.getFlag(Flag: MachineInstr::NoConvergent))
899 OS << "noconvergent ";
900 if (MI.getFlag(Flag: MachineInstr::NonNeg))
901 OS << "nneg ";
902 if (MI.getFlag(Flag: MachineInstr::Disjoint))
903 OS << "disjoint ";
904 if (MI.getFlag(Flag: MachineInstr::NoUSWrap))
905 OS << "nusw ";
906 if (MI.getFlag(Flag: MachineInstr::SameSign))
907 OS << "samesign ";
908 if (MI.getFlag(Flag: MachineInstr::InBounds))
909 OS << "inbounds ";
910 if (MI.getFlag(Flag: MachineInstr::LRSplit))
911 OS << "lr-split ";
912 if (MI.getFlag(Flag: MachineInstr::NonNull))
913 OS << "nonnull ";
914
915 // NOTE: Please add new MIFlags also to the MI_FLAGS_STR in
916 // llvm/utils/UpdateTestChecks/mir.py.
917
918 OS << TII->getName(Opcode: MI.getOpcode());
919
920 // Print a space after the opcode if any additional tokens are printed.
921 LS = ListSeparator(", ", " ");
922
923 for (; I < E; ++I) {
924 OS << LS;
925 printMIOperand(OS, State, MI, OpIdx: I, TRI, TII, ShouldPrintRegisterTies,
926 PrintedTypes, MRI, /*PrintDef=*/true);
927 }
928
929 // Print any optional symbols attached to this instruction as-if they were
930 // operands.
931 if (MCSymbol *PreInstrSymbol = MI.getPreInstrSymbol()) {
932 OS << LS << "pre-instr-symbol ";
933 MachineOperand::printSymbol(OS, Sym&: *PreInstrSymbol);
934 }
935 if (MCSymbol *PostInstrSymbol = MI.getPostInstrSymbol()) {
936 OS << LS << "post-instr-symbol ";
937 MachineOperand::printSymbol(OS, Sym&: *PostInstrSymbol);
938 }
939 if (MDNode *HeapAllocMarker = MI.getHeapAllocMarker()) {
940 OS << LS << "heap-alloc-marker ";
941 HeapAllocMarker->printAsOperand(OS, MST&: State.MST);
942 }
943 if (MDNode *PCSections = MI.getPCSections()) {
944 OS << LS << "pcsections ";
945 PCSections->printAsOperand(OS, MST&: State.MST);
946 }
947 if (MDNode *MMRA = MI.getMMRAMetadata()) {
948 OS << LS << "mmra ";
949 MMRA->printAsOperand(OS, MST&: State.MST);
950 }
951 if (uint32_t CFIType = MI.getCFIType())
952 OS << LS << "cfi-type " << CFIType;
953 if (Value *DS = MI.getDeactivationSymbol()) {
954 OS << LS << "deactivation-symbol ";
955 MIRFormatter::printIRValue(OS, V: *DS, MST&: State.MST);
956 }
957
958 if (auto Num = MI.peekDebugInstrNum())
959 OS << LS << "debug-instr-number " << Num;
960
961 if (PrintLocations) {
962 if (const DebugLoc &DL = MI.getDebugLoc()) {
963 OS << LS << "debug-location ";
964 DL->printAsOperand(OS, MST&: State.MST);
965 }
966 }
967
968 if (!MI.memoperands_empty()) {
969 OS << " :: ";
970 const LLVMContext &Context = MF->getFunction().getContext();
971 const MachineFrameInfo &MFI = MF->getFrameInfo();
972 LS = ListSeparator();
973 for (const auto *Op : MI.memoperands()) {
974 OS << LS;
975 Op->print(OS, MST&: State.MST, SSNs&: State.SSNs, Context, MFI: &MFI, TII);
976 }
977 }
978}
979
980static std::string formatOperandComment(std::string Comment) {
981 if (Comment.empty())
982 return Comment;
983 return std::string(" /* " + Comment + " */");
984}
985
986static void printMIOperand(raw_ostream &OS, MFPrintState &State,
987 const MachineInstr &MI, unsigned OpIdx,
988 const TargetRegisterInfo *TRI,
989 const TargetInstrInfo *TII,
990 bool ShouldPrintRegisterTies,
991 SmallBitVector &PrintedTypes,
992 const MachineRegisterInfo &MRI, bool PrintDef) {
993 LLT TypeToPrint = MI.getTypeToPrint(OpIdx, PrintedTypes, MRI);
994 const MachineOperand &Op = MI.getOperand(i: OpIdx);
995 std::string MOComment = TII->createMIROperandComment(MI, Op, OpIdx);
996
997 switch (Op.getType()) {
998 case MachineOperand::MO_Immediate:
999 if (MI.isOperandSubregIdx(OpIdx)) {
1000 MachineOperand::printTargetFlags(OS, Op);
1001 MachineOperand::printSubRegIdx(OS, Index: Op.getImm(), TRI);
1002 break;
1003 }
1004 if (MI.isInlineAsm()) {
1005 if (OpIdx == InlineAsm::MIOp_ExtraInfo) {
1006 unsigned ExtraInfo = Op.getImm();
1007 interleave(c: InlineAsm::getExtraInfoNames(ExtraInfo), os&: OS, separator: " ");
1008 break;
1009 }
1010
1011 int FlagIdx = MI.findInlineAsmFlagIdx(OpIdx);
1012 if (FlagIdx >= 0 && (unsigned)FlagIdx == OpIdx) {
1013 InlineAsm::Flag F(Op.getImm());
1014 OS << F.getKindName();
1015
1016 bool IsReg = F.isRegDefKind() || F.isRegUseKind() ||
1017 F.isRegDefEarlyClobberKind();
1018 unsigned RCID;
1019 if (IsReg && F.hasRegClassConstraint(RC&: RCID))
1020 OS << ':' << TRI->getRegClassName(Class: TRI->getRegClass(i: RCID));
1021
1022 if (F.isMemKind()) {
1023 InlineAsm::ConstraintCode MCID = F.getMemoryConstraintID();
1024 OS << ':' << InlineAsm::getMemConstraintName(C: MCID);
1025 }
1026
1027 unsigned TiedTo;
1028 if (F.isUseOperandTiedToDef(Idx&: TiedTo))
1029 OS << " tiedto:$" << TiedTo;
1030 if (IsReg && F.getRegMayBeFolded())
1031 OS << " foldable";
1032
1033 break;
1034 }
1035 }
1036 [[fallthrough]];
1037 case MachineOperand::MO_Register:
1038 case MachineOperand::MO_CImmediate:
1039 case MachineOperand::MO_FPImmediate:
1040 case MachineOperand::MO_MachineBasicBlock:
1041 case MachineOperand::MO_ConstantPoolIndex:
1042 case MachineOperand::MO_TargetIndex:
1043 case MachineOperand::MO_JumpTableIndex:
1044 case MachineOperand::MO_ExternalSymbol:
1045 case MachineOperand::MO_GlobalAddress:
1046 case MachineOperand::MO_RegisterLiveOut:
1047 case MachineOperand::MO_Metadata:
1048 case MachineOperand::MO_MCSymbol:
1049 case MachineOperand::MO_CFIIndex:
1050 case MachineOperand::MO_IntrinsicID:
1051 case MachineOperand::MO_Predicate:
1052 case MachineOperand::MO_BlockAddress:
1053 case MachineOperand::MO_DbgInstrRef:
1054 case MachineOperand::MO_ShuffleMask:
1055 case MachineOperand::MO_LaneMask: {
1056 unsigned TiedOperandIdx = 0;
1057 if (ShouldPrintRegisterTies && Op.isReg() && Op.isTied() && !Op.isDef())
1058 TiedOperandIdx = Op.getParent()->findTiedOperandIdx(OpIdx);
1059 Op.print(os&: OS, MST&: State.MST, TypeToPrint, OpIdx, PrintDef,
1060 /*IsStandalone=*/false, ShouldPrintRegisterTies, TiedOperandIdx,
1061 TRI);
1062 OS << formatOperandComment(Comment: MOComment);
1063 break;
1064 }
1065 case MachineOperand::MO_FrameIndex:
1066 printStackObjectReference(OS, State, FrameIndex: Op.getIndex());
1067 break;
1068 case MachineOperand::MO_RegisterMask: {
1069 const auto &RegisterMaskIds = State.RegisterMaskIds;
1070 auto RegMaskInfo = RegisterMaskIds.find(Val: Op.getRegMask());
1071 if (RegMaskInfo != RegisterMaskIds.end())
1072 OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
1073 else
1074 printCustomRegMask(RegMask: Op.getRegMask(), OS, TRI);
1075 break;
1076 }
1077 }
1078}
1079
1080void MIRFormatter::printIRValue(raw_ostream &OS, const Value &V,
1081 ModuleSlotTracker &MST) {
1082 if (isa<GlobalValue>(Val: V)) {
1083 V.printAsOperand(O&: OS, /*PrintType=*/false, MST);
1084 return;
1085 }
1086 if (isa<Constant>(Val: V)) {
1087 // Machine memory operands can load/store to/from constant value pointers.
1088 OS << '`';
1089 V.printAsOperand(O&: OS, /*PrintType=*/true, MST);
1090 OS << '`';
1091 return;
1092 }
1093 OS << "%ir.";
1094 if (V.hasName()) {
1095 printLLVMNameWithoutPrefix(OS, Name: V.getName());
1096 return;
1097 }
1098 int Slot = MST.getCurrentFunction() ? MST.getLocalSlot(V: &V) : -1;
1099 MachineOperand::printIRSlotNumber(OS, Slot);
1100}
1101
1102void llvm::printMIR(raw_ostream &OS, const Module &M) {
1103 yaml::Output Out(OS);
1104 Out << const_cast<Module &>(M);
1105}
1106
1107void llvm::printMIR(raw_ostream &OS, const MachineModuleInfo &MMI,
1108 const MachineFunction &MF, const VirtRegMap *VRM) {
1109 printMF(
1110 OS, Fn: [&](const Function &F) { return MMI.getMachineFunction(F); }, MF,
1111 VRM);
1112}
1113
1114void llvm::printMIR(raw_ostream &OS, FunctionAnalysisManager &FAM,
1115 const MachineFunction &MF, const VirtRegMap *VRM) {
1116 printMF(
1117 OS,
1118 Fn: [&](const Function &F) {
1119 return &FAM.getResult<MachineFunctionAnalysis>(
1120 IR&: const_cast<Function &>(F))
1121 .getMF();
1122 },
1123 MF, VRM);
1124}
1125