[ELF] Avoid make in elf::writeARMCmseImportLib
[llvm-project.git] / llvm / lib / CodeGen / MIRPrinter.cpp
blobc8f6341c1224d261629a3329799fa8076ef49f58
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.
12 //===----------------------------------------------------------------------===//
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/CodeGenTypes/LowLevelType.h"
37 #include "llvm/IR/DebugInfoMetadata.h"
38 #include "llvm/IR/DebugLoc.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/IRPrintingPasses.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/IR/ModuleSlotTracker.h"
44 #include "llvm/IR/Value.h"
45 #include "llvm/MC/LaneBitmask.h"
46 #include "llvm/Support/BranchProbability.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/Format.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>
63 using namespace llvm;
65 static cl::opt<bool> SimplifyMIR(
66 "simplify-mir", cl::Hidden,
67 cl::desc("Leave out unnecessary information when printing MIR"));
69 static cl::opt<bool> PrintLocations("mir-debug-loc", cl::Hidden, cl::init(true),
70 cl::desc("Print MIR debug-locations"));
72 extern cl::opt<bool> WriteNewDbgInfoFormat;
74 namespace {
76 /// This structure describes how to print out stack object references.
77 struct FrameIndexOperand {
78 std::string Name;
79 unsigned ID;
80 bool IsFixed;
82 FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
83 : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
85 /// Return an ordinary stack object reference.
86 static FrameIndexOperand create(StringRef Name, unsigned ID) {
87 return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
90 /// Return a fixed stack object reference.
91 static FrameIndexOperand createFixed(unsigned ID) {
92 return FrameIndexOperand("", ID, /*IsFixed=*/true);
96 } // end anonymous namespace
98 namespace llvm {
100 /// This class prints out the machine functions using the MIR serialization
101 /// format.
102 class MIRPrinter {
103 raw_ostream &OS;
104 const MachineModuleInfo &MMI;
105 DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
106 /// Maps from stack object indices to operand indices which will be used when
107 /// printing frame index machine operands.
108 DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
110 public:
111 MIRPrinter(raw_ostream &OS, const MachineModuleInfo &MMI)
112 : OS(OS), MMI(MMI) {}
114 void print(const MachineFunction &MF);
116 void convert(yaml::MachineFunction &YamlMF, const MachineFunction &MF,
117 const MachineRegisterInfo &RegInfo,
118 const TargetRegisterInfo *TRI);
119 void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
120 const MachineFrameInfo &MFI);
121 void convert(yaml::MachineFunction &MF,
122 const MachineConstantPool &ConstantPool);
123 void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
124 const MachineJumpTableInfo &JTI);
125 void convertStackObjects(yaml::MachineFunction &YMF,
126 const MachineFunction &MF, ModuleSlotTracker &MST);
127 void convertEntryValueObjects(yaml::MachineFunction &YMF,
128 const MachineFunction &MF,
129 ModuleSlotTracker &MST);
130 void convertCallSiteObjects(yaml::MachineFunction &YMF,
131 const MachineFunction &MF,
132 ModuleSlotTracker &MST);
133 void convertMachineMetadataNodes(yaml::MachineFunction &YMF,
134 const MachineFunction &MF,
135 MachineModuleSlotTracker &MST);
137 private:
138 void initRegisterMaskIds(const MachineFunction &MF);
141 /// This class prints out the machine instructions using the MIR serialization
142 /// format.
143 class MIPrinter {
144 raw_ostream &OS;
145 ModuleSlotTracker &MST;
146 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
147 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
148 /// Synchronization scope names registered with LLVMContext.
149 SmallVector<StringRef, 8> SSNs;
151 bool canPredictBranchProbabilities(const MachineBasicBlock &MBB) const;
152 bool canPredictSuccessors(const MachineBasicBlock &MBB) const;
154 public:
155 MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
156 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
157 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
158 : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
159 StackObjectOperandMapping(StackObjectOperandMapping) {}
161 void print(const MachineBasicBlock &MBB);
163 void print(const MachineInstr &MI);
164 void printStackObjectReference(int FrameIndex);
165 void print(const MachineInstr &MI, unsigned OpIdx,
166 const TargetRegisterInfo *TRI, const TargetInstrInfo *TII,
167 bool ShouldPrintRegisterTies, LLT TypeToPrint,
168 bool PrintDef = true);
171 } // end namespace llvm
173 namespace llvm {
174 namespace yaml {
176 /// This struct serializes the LLVM IR module.
177 template <> struct BlockScalarTraits<Module> {
178 static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
179 Mod.print(OS, nullptr);
182 static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
183 llvm_unreachable("LLVM Module is supposed to be parsed separately");
184 return "";
188 } // end namespace yaml
189 } // end namespace llvm
191 static void printRegMIR(unsigned Reg, yaml::StringValue &Dest,
192 const TargetRegisterInfo *TRI) {
193 raw_string_ostream OS(Dest.Value);
194 OS << printReg(Reg, TRI);
197 void MIRPrinter::print(const MachineFunction &MF) {
198 initRegisterMaskIds(MF);
200 yaml::MachineFunction YamlMF;
201 YamlMF.Name = MF.getName();
202 YamlMF.Alignment = MF.getAlignment();
203 YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
204 YamlMF.HasWinCFI = MF.hasWinCFI();
206 YamlMF.CallsEHReturn = MF.callsEHReturn();
207 YamlMF.CallsUnwindInit = MF.callsUnwindInit();
208 YamlMF.HasEHCatchret = MF.hasEHCatchret();
209 YamlMF.HasEHScopes = MF.hasEHScopes();
210 YamlMF.HasEHFunclets = MF.hasEHFunclets();
211 YamlMF.HasFakeUses = MF.hasFakeUses();
212 YamlMF.IsOutlined = MF.isOutlined();
213 YamlMF.UseDebugInstrRef = MF.useDebugInstrRef();
215 YamlMF.Legalized = MF.getProperties().hasProperty(
216 MachineFunctionProperties::Property::Legalized);
217 YamlMF.RegBankSelected = MF.getProperties().hasProperty(
218 MachineFunctionProperties::Property::RegBankSelected);
219 YamlMF.Selected = MF.getProperties().hasProperty(
220 MachineFunctionProperties::Property::Selected);
221 YamlMF.FailedISel = MF.getProperties().hasProperty(
222 MachineFunctionProperties::Property::FailedISel);
223 YamlMF.FailsVerification = MF.getProperties().hasProperty(
224 MachineFunctionProperties::Property::FailsVerification);
225 YamlMF.TracksDebugUserValues = MF.getProperties().hasProperty(
226 MachineFunctionProperties::Property::TracksDebugUserValues);
228 YamlMF.NoPHIs = MF.getProperties().hasProperty(
229 MachineFunctionProperties::Property::NoPHIs);
230 YamlMF.IsSSA = MF.getProperties().hasProperty(
231 MachineFunctionProperties::Property::IsSSA);
232 YamlMF.NoVRegs = MF.getProperties().hasProperty(
233 MachineFunctionProperties::Property::NoVRegs);
235 convert(YamlMF, MF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
236 MachineModuleSlotTracker MST(MMI, &MF);
237 MST.incorporateFunction(MF.getFunction());
238 convert(MST, YamlMF.FrameInfo, MF.getFrameInfo());
239 convertStackObjects(YamlMF, MF, MST);
240 convertEntryValueObjects(YamlMF, MF, MST);
241 convertCallSiteObjects(YamlMF, MF, MST);
242 for (const auto &Sub : MF.DebugValueSubstitutions) {
243 const auto &SubSrc = Sub.Src;
244 const auto &SubDest = Sub.Dest;
245 YamlMF.DebugValueSubstitutions.push_back({SubSrc.first, SubSrc.second,
246 SubDest.first,
247 SubDest.second,
248 Sub.Subreg});
250 if (const auto *ConstantPool = MF.getConstantPool())
251 convert(YamlMF, *ConstantPool);
252 if (const auto *JumpTableInfo = MF.getJumpTableInfo())
253 convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
255 const TargetMachine &TM = MF.getTarget();
256 YamlMF.MachineFuncInfo =
257 std::unique_ptr<yaml::MachineFunctionInfo>(TM.convertFuncInfoToYAML(MF));
259 raw_string_ostream StrOS(YamlMF.Body.Value.Value);
260 bool IsNewlineNeeded = false;
261 for (const auto &MBB : MF) {
262 if (IsNewlineNeeded)
263 StrOS << "\n";
264 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
265 .print(MBB);
266 IsNewlineNeeded = true;
268 // Convert machine metadata collected during the print of the machine
269 // function.
270 convertMachineMetadataNodes(YamlMF, MF, MST);
272 yaml::Output Out(OS);
273 if (!SimplifyMIR)
274 Out.setWriteDefaultValues(true);
275 Out << YamlMF;
278 static void printCustomRegMask(const uint32_t *RegMask, raw_ostream &OS,
279 const TargetRegisterInfo *TRI) {
280 assert(RegMask && "Can't print an empty register mask");
281 OS << StringRef("CustomRegMask(");
283 bool IsRegInRegMaskFound = false;
284 for (int I = 0, E = TRI->getNumRegs(); I < E; I++) {
285 // Check whether the register is asserted in regmask.
286 if (RegMask[I / 32] & (1u << (I % 32))) {
287 if (IsRegInRegMaskFound)
288 OS << ',';
289 OS << printReg(I, TRI);
290 IsRegInRegMaskFound = true;
294 OS << ')';
297 static void printRegClassOrBank(unsigned Reg, yaml::StringValue &Dest,
298 const MachineRegisterInfo &RegInfo,
299 const TargetRegisterInfo *TRI) {
300 raw_string_ostream OS(Dest.Value);
301 OS << printRegClassOrBank(Reg, RegInfo, TRI);
304 template <typename T>
305 static void
306 printStackObjectDbgInfo(const MachineFunction::VariableDbgInfo &DebugVar,
307 T &Object, ModuleSlotTracker &MST) {
308 std::array<std::string *, 3> Outputs{{&Object.DebugVar.Value,
309 &Object.DebugExpr.Value,
310 &Object.DebugLoc.Value}};
311 std::array<const Metadata *, 3> Metas{{DebugVar.Var,
312 DebugVar.Expr,
313 DebugVar.Loc}};
314 for (unsigned i = 0; i < 3; ++i) {
315 raw_string_ostream StrOS(*Outputs[i]);
316 Metas[i]->printAsOperand(StrOS, MST);
320 static void printRegFlags(Register Reg,
321 std::vector<yaml::FlowStringValue> &RegisterFlags,
322 const MachineFunction &MF,
323 const TargetRegisterInfo *TRI) {
324 auto FlagValues = TRI->getVRegFlagsOfReg(Reg, MF);
325 for (auto &Flag : FlagValues) {
326 RegisterFlags.push_back(yaml::FlowStringValue(Flag.str()));
330 void MIRPrinter::convert(yaml::MachineFunction &YamlMF,
331 const MachineFunction &MF,
332 const MachineRegisterInfo &RegInfo,
333 const TargetRegisterInfo *TRI) {
334 YamlMF.TracksRegLiveness = RegInfo.tracksLiveness();
336 // Print the virtual register definitions.
337 for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
338 Register Reg = Register::index2VirtReg(I);
339 yaml::VirtualRegisterDefinition VReg;
340 VReg.ID = I;
341 if (RegInfo.getVRegName(Reg) != "")
342 continue;
343 ::printRegClassOrBank(Reg, VReg.Class, RegInfo, TRI);
344 Register PreferredReg = RegInfo.getSimpleHint(Reg);
345 if (PreferredReg)
346 printRegMIR(PreferredReg, VReg.PreferredRegister, TRI);
347 printRegFlags(Reg, VReg.RegisterFlags, MF, TRI);
348 YamlMF.VirtualRegisters.push_back(std::move(VReg));
351 // Print the live ins.
352 for (std::pair<MCRegister, Register> LI : RegInfo.liveins()) {
353 yaml::MachineFunctionLiveIn LiveIn;
354 printRegMIR(LI.first, LiveIn.Register, TRI);
355 if (LI.second)
356 printRegMIR(LI.second, LiveIn.VirtualRegister, TRI);
357 YamlMF.LiveIns.push_back(std::move(LiveIn));
360 // Prints the callee saved registers.
361 if (RegInfo.isUpdatedCSRsInitialized()) {
362 const MCPhysReg *CalleeSavedRegs = RegInfo.getCalleeSavedRegs();
363 std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
364 for (const MCPhysReg *I = CalleeSavedRegs; *I; ++I) {
365 yaml::FlowStringValue Reg;
366 printRegMIR(*I, Reg, TRI);
367 CalleeSavedRegisters.push_back(std::move(Reg));
369 YamlMF.CalleeSavedRegisters = std::move(CalleeSavedRegisters);
373 void MIRPrinter::convert(ModuleSlotTracker &MST,
374 yaml::MachineFrameInfo &YamlMFI,
375 const MachineFrameInfo &MFI) {
376 YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
377 YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
378 YamlMFI.HasStackMap = MFI.hasStackMap();
379 YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
380 YamlMFI.StackSize = MFI.getStackSize();
381 YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
382 YamlMFI.MaxAlignment = MFI.getMaxAlign().value();
383 YamlMFI.AdjustsStack = MFI.adjustsStack();
384 YamlMFI.HasCalls = MFI.hasCalls();
385 YamlMFI.MaxCallFrameSize = MFI.isMaxCallFrameSizeComputed()
386 ? MFI.getMaxCallFrameSize() : ~0u;
387 YamlMFI.CVBytesOfCalleeSavedRegisters =
388 MFI.getCVBytesOfCalleeSavedRegisters();
389 YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
390 YamlMFI.HasVAStart = MFI.hasVAStart();
391 YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
392 YamlMFI.HasTailCall = MFI.hasTailCall();
393 YamlMFI.IsCalleeSavedInfoValid = MFI.isCalleeSavedInfoValid();
394 YamlMFI.LocalFrameSize = MFI.getLocalFrameSize();
395 if (MFI.getSavePoint()) {
396 raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
397 StrOS << printMBBReference(*MFI.getSavePoint());
399 if (MFI.getRestorePoint()) {
400 raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
401 StrOS << printMBBReference(*MFI.getRestorePoint());
405 void MIRPrinter::convertEntryValueObjects(yaml::MachineFunction &YMF,
406 const MachineFunction &MF,
407 ModuleSlotTracker &MST) {
408 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
409 for (const MachineFunction::VariableDbgInfo &DebugVar :
410 MF.getEntryValueVariableDbgInfo()) {
411 yaml::EntryValueObject &Obj = YMF.EntryValueObjects.emplace_back();
412 printStackObjectDbgInfo(DebugVar, Obj, MST);
413 MCRegister EntryValReg = DebugVar.getEntryValueRegister();
414 printRegMIR(EntryValReg, Obj.EntryValueRegister, TRI);
418 void MIRPrinter::convertStackObjects(yaml::MachineFunction &YMF,
419 const MachineFunction &MF,
420 ModuleSlotTracker &MST) {
421 const MachineFrameInfo &MFI = MF.getFrameInfo();
422 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
424 // Process fixed stack objects.
425 assert(YMF.FixedStackObjects.empty());
426 SmallVector<int, 32> FixedStackObjectsIdx;
427 const int BeginIdx = MFI.getObjectIndexBegin();
428 if (BeginIdx < 0)
429 FixedStackObjectsIdx.reserve(-BeginIdx);
431 unsigned ID = 0;
432 for (int I = BeginIdx; I < 0; ++I, ++ID) {
433 FixedStackObjectsIdx.push_back(-1); // Fill index for possible dead.
434 if (MFI.isDeadObjectIndex(I))
435 continue;
437 yaml::FixedMachineStackObject YamlObject;
438 YamlObject.ID = ID;
439 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
440 ? yaml::FixedMachineStackObject::SpillSlot
441 : yaml::FixedMachineStackObject::DefaultType;
442 YamlObject.Offset = MFI.getObjectOffset(I);
443 YamlObject.Size = MFI.getObjectSize(I);
444 YamlObject.Alignment = MFI.getObjectAlign(I);
445 YamlObject.StackID = (TargetStackID::Value)MFI.getStackID(I);
446 YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
447 YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
448 // Save the ID' position in FixedStackObjects storage vector.
449 FixedStackObjectsIdx[ID] = YMF.FixedStackObjects.size();
450 YMF.FixedStackObjects.push_back(YamlObject);
451 StackObjectOperandMapping.insert(
452 std::make_pair(I, FrameIndexOperand::createFixed(ID)));
455 // Process ordinary stack objects.
456 assert(YMF.StackObjects.empty());
457 SmallVector<unsigned, 32> StackObjectsIdx;
458 const int EndIdx = MFI.getObjectIndexEnd();
459 if (EndIdx > 0)
460 StackObjectsIdx.reserve(EndIdx);
461 ID = 0;
462 for (int I = 0; I < EndIdx; ++I, ++ID) {
463 StackObjectsIdx.push_back(-1); // Fill index for possible dead.
464 if (MFI.isDeadObjectIndex(I))
465 continue;
467 yaml::MachineStackObject YamlObject;
468 YamlObject.ID = ID;
469 if (const auto *Alloca = MFI.getObjectAllocation(I))
470 YamlObject.Name.Value = std::string(
471 Alloca->hasName() ? Alloca->getName() : "");
472 YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
473 ? yaml::MachineStackObject::SpillSlot
474 : MFI.isVariableSizedObjectIndex(I)
475 ? yaml::MachineStackObject::VariableSized
476 : yaml::MachineStackObject::DefaultType;
477 YamlObject.Offset = MFI.getObjectOffset(I);
478 YamlObject.Size = MFI.getObjectSize(I);
479 YamlObject.Alignment = MFI.getObjectAlign(I);
480 YamlObject.StackID = (TargetStackID::Value)MFI.getStackID(I);
482 // Save the ID' position in StackObjects storage vector.
483 StackObjectsIdx[ID] = YMF.StackObjects.size();
484 YMF.StackObjects.push_back(YamlObject);
485 StackObjectOperandMapping.insert(std::make_pair(
486 I, FrameIndexOperand::create(YamlObject.Name.Value, ID)));
489 for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
490 const int FrameIdx = CSInfo.getFrameIdx();
491 if (!CSInfo.isSpilledToReg() && MFI.isDeadObjectIndex(FrameIdx))
492 continue;
494 yaml::StringValue Reg;
495 printRegMIR(CSInfo.getReg(), Reg, TRI);
496 if (!CSInfo.isSpilledToReg()) {
497 assert(FrameIdx >= MFI.getObjectIndexBegin() &&
498 FrameIdx < MFI.getObjectIndexEnd() &&
499 "Invalid stack object index");
500 if (FrameIdx < 0) { // Negative index means fixed objects.
501 auto &Object =
502 YMF.FixedStackObjects
503 [FixedStackObjectsIdx[FrameIdx + MFI.getNumFixedObjects()]];
504 Object.CalleeSavedRegister = Reg;
505 Object.CalleeSavedRestored = CSInfo.isRestored();
506 } else {
507 auto &Object = YMF.StackObjects[StackObjectsIdx[FrameIdx]];
508 Object.CalleeSavedRegister = Reg;
509 Object.CalleeSavedRestored = CSInfo.isRestored();
513 for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) {
514 auto LocalObject = MFI.getLocalFrameObjectMap(I);
515 assert(LocalObject.first >= 0 && "Expected a locally mapped stack object");
516 YMF.StackObjects[StackObjectsIdx[LocalObject.first]].LocalOffset =
517 LocalObject.second;
520 // Print the stack object references in the frame information class after
521 // converting the stack objects.
522 if (MFI.hasStackProtectorIndex()) {
523 raw_string_ostream StrOS(YMF.FrameInfo.StackProtector.Value);
524 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
525 .printStackObjectReference(MFI.getStackProtectorIndex());
528 if (MFI.hasFunctionContextIndex()) {
529 raw_string_ostream StrOS(YMF.FrameInfo.FunctionContext.Value);
530 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
531 .printStackObjectReference(MFI.getFunctionContextIndex());
534 // Print the debug variable information.
535 for (const MachineFunction::VariableDbgInfo &DebugVar :
536 MF.getInStackSlotVariableDbgInfo()) {
537 int Idx = DebugVar.getStackSlot();
538 assert(Idx >= MFI.getObjectIndexBegin() && Idx < MFI.getObjectIndexEnd() &&
539 "Invalid stack object index");
540 if (Idx < 0) { // Negative index means fixed objects.
541 auto &Object =
542 YMF.FixedStackObjects[FixedStackObjectsIdx[Idx +
543 MFI.getNumFixedObjects()]];
544 printStackObjectDbgInfo(DebugVar, Object, MST);
545 } else {
546 auto &Object = YMF.StackObjects[StackObjectsIdx[Idx]];
547 printStackObjectDbgInfo(DebugVar, Object, MST);
552 void MIRPrinter::convertCallSiteObjects(yaml::MachineFunction &YMF,
553 const MachineFunction &MF,
554 ModuleSlotTracker &MST) {
555 const auto *TRI = MF.getSubtarget().getRegisterInfo();
556 for (auto CSInfo : MF.getCallSitesInfo()) {
557 yaml::CallSiteInfo YmlCS;
558 yaml::CallSiteInfo::MachineInstrLoc CallLocation;
560 // Prepare instruction position.
561 MachineBasicBlock::const_instr_iterator CallI = CSInfo.first->getIterator();
562 CallLocation.BlockNum = CallI->getParent()->getNumber();
563 // Get call instruction offset from the beginning of block.
564 CallLocation.Offset =
565 std::distance(CallI->getParent()->instr_begin(), CallI);
566 YmlCS.CallLocation = CallLocation;
567 // Construct call arguments and theirs forwarding register info.
568 for (auto ArgReg : CSInfo.second.ArgRegPairs) {
569 yaml::CallSiteInfo::ArgRegPair YmlArgReg;
570 YmlArgReg.ArgNo = ArgReg.ArgNo;
571 printRegMIR(ArgReg.Reg, YmlArgReg.Reg, TRI);
572 YmlCS.ArgForwardingRegs.emplace_back(YmlArgReg);
574 YMF.CallSitesInfo.push_back(YmlCS);
577 // Sort call info by position of call instructions.
578 llvm::sort(YMF.CallSitesInfo.begin(), YMF.CallSitesInfo.end(),
579 [](yaml::CallSiteInfo A, yaml::CallSiteInfo B) {
580 if (A.CallLocation.BlockNum == B.CallLocation.BlockNum)
581 return A.CallLocation.Offset < B.CallLocation.Offset;
582 return A.CallLocation.BlockNum < B.CallLocation.BlockNum;
586 void MIRPrinter::convertMachineMetadataNodes(yaml::MachineFunction &YMF,
587 const MachineFunction &MF,
588 MachineModuleSlotTracker &MST) {
589 MachineModuleSlotTracker::MachineMDNodeListType MDList;
590 MST.collectMachineMDNodes(MDList);
591 for (auto &MD : MDList) {
592 std::string NS;
593 raw_string_ostream StrOS(NS);
594 MD.second->print(StrOS, MST, MF.getFunction().getParent());
595 YMF.MachineMetadataNodes.push_back(NS);
599 void MIRPrinter::convert(yaml::MachineFunction &MF,
600 const MachineConstantPool &ConstantPool) {
601 unsigned ID = 0;
602 for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
603 std::string Str;
604 raw_string_ostream StrOS(Str);
605 if (Constant.isMachineConstantPoolEntry()) {
606 Constant.Val.MachineCPVal->print(StrOS);
607 } else {
608 Constant.Val.ConstVal->printAsOperand(StrOS);
611 yaml::MachineConstantPoolValue YamlConstant;
612 YamlConstant.ID = ID++;
613 YamlConstant.Value = Str;
614 YamlConstant.Alignment = Constant.getAlign();
615 YamlConstant.IsTargetSpecific = Constant.isMachineConstantPoolEntry();
617 MF.Constants.push_back(YamlConstant);
621 void MIRPrinter::convert(ModuleSlotTracker &MST,
622 yaml::MachineJumpTable &YamlJTI,
623 const MachineJumpTableInfo &JTI) {
624 YamlJTI.Kind = JTI.getEntryKind();
625 unsigned ID = 0;
626 for (const auto &Table : JTI.getJumpTables()) {
627 std::string Str;
628 yaml::MachineJumpTable::Entry Entry;
629 Entry.ID = ID++;
630 for (const auto *MBB : Table.MBBs) {
631 raw_string_ostream StrOS(Str);
632 StrOS << printMBBReference(*MBB);
633 Entry.Blocks.push_back(Str);
634 Str.clear();
636 YamlJTI.Entries.push_back(Entry);
640 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
641 const auto *TRI = MF.getSubtarget().getRegisterInfo();
642 unsigned I = 0;
643 for (const uint32_t *Mask : TRI->getRegMasks())
644 RegisterMaskIds.insert(std::make_pair(Mask, I++));
647 void llvm::guessSuccessors(const MachineBasicBlock &MBB,
648 SmallVectorImpl<MachineBasicBlock*> &Result,
649 bool &IsFallthrough) {
650 SmallPtrSet<MachineBasicBlock*,8> Seen;
652 for (const MachineInstr &MI : MBB) {
653 if (MI.isPHI())
654 continue;
655 for (const MachineOperand &MO : MI.operands()) {
656 if (!MO.isMBB())
657 continue;
658 MachineBasicBlock *Succ = MO.getMBB();
659 auto RP = Seen.insert(Succ);
660 if (RP.second)
661 Result.push_back(Succ);
664 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
665 IsFallthrough = I == MBB.end() || !I->isBarrier();
668 bool
669 MIPrinter::canPredictBranchProbabilities(const MachineBasicBlock &MBB) const {
670 if (MBB.succ_size() <= 1)
671 return true;
672 if (!MBB.hasSuccessorProbabilities())
673 return true;
675 SmallVector<BranchProbability,8> Normalized(MBB.Probs.begin(),
676 MBB.Probs.end());
677 BranchProbability::normalizeProbabilities(Normalized.begin(),
678 Normalized.end());
679 SmallVector<BranchProbability,8> Equal(Normalized.size());
680 BranchProbability::normalizeProbabilities(Equal.begin(), Equal.end());
682 return std::equal(Normalized.begin(), Normalized.end(), Equal.begin());
685 bool MIPrinter::canPredictSuccessors(const MachineBasicBlock &MBB) const {
686 SmallVector<MachineBasicBlock*,8> GuessedSuccs;
687 bool GuessedFallthrough;
688 guessSuccessors(MBB, GuessedSuccs, GuessedFallthrough);
689 if (GuessedFallthrough) {
690 const MachineFunction &MF = *MBB.getParent();
691 MachineFunction::const_iterator NextI = std::next(MBB.getIterator());
692 if (NextI != MF.end()) {
693 MachineBasicBlock *Next = const_cast<MachineBasicBlock*>(&*NextI);
694 if (!is_contained(GuessedSuccs, Next))
695 GuessedSuccs.push_back(Next);
698 if (GuessedSuccs.size() != MBB.succ_size())
699 return false;
700 return std::equal(MBB.succ_begin(), MBB.succ_end(), GuessedSuccs.begin());
703 void MIPrinter::print(const MachineBasicBlock &MBB) {
704 assert(MBB.getNumber() >= 0 && "Invalid MBB number");
705 MBB.printName(OS,
706 MachineBasicBlock::PrintNameIr |
707 MachineBasicBlock::PrintNameAttributes,
708 &MST);
709 OS << ":\n";
711 bool HasLineAttributes = false;
712 // Print the successors
713 bool canPredictProbs = canPredictBranchProbabilities(MBB);
714 // Even if the list of successors is empty, if we cannot guess it,
715 // we need to print it to tell the parser that the list is empty.
716 // This is needed, because MI model unreachable as empty blocks
717 // with an empty successor list. If the parser would see that
718 // without the successor list, it would guess the code would
719 // fallthrough.
720 if ((!MBB.succ_empty() && !SimplifyMIR) || !canPredictProbs ||
721 !canPredictSuccessors(MBB)) {
722 OS.indent(2) << "successors:";
723 if (!MBB.succ_empty())
724 OS << " ";
725 for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
726 if (I != MBB.succ_begin())
727 OS << ", ";
728 OS << printMBBReference(**I);
729 if (!SimplifyMIR || !canPredictProbs)
730 OS << '('
731 << format("0x%08" PRIx32, MBB.getSuccProbability(I).getNumerator())
732 << ')';
734 OS << "\n";
735 HasLineAttributes = true;
738 // Print the live in registers.
739 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
740 if (!MBB.livein_empty()) {
741 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
742 OS.indent(2) << "liveins: ";
743 bool First = true;
744 for (const auto &LI : MBB.liveins_dbg()) {
745 if (!First)
746 OS << ", ";
747 First = false;
748 OS << printReg(LI.PhysReg, &TRI);
749 if (!LI.LaneMask.all())
750 OS << ":0x" << PrintLaneMask(LI.LaneMask);
752 OS << "\n";
753 HasLineAttributes = true;
756 if (HasLineAttributes && !MBB.empty())
757 OS << "\n";
758 bool IsInBundle = false;
759 for (const MachineInstr &MI : MBB.instrs()) {
760 if (IsInBundle && !MI.isInsideBundle()) {
761 OS.indent(2) << "}\n";
762 IsInBundle = false;
764 OS.indent(IsInBundle ? 4 : 2);
765 print(MI);
766 if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
767 OS << " {";
768 IsInBundle = true;
770 OS << "\n";
772 if (IsInBundle)
773 OS.indent(2) << "}\n";
776 void MIPrinter::print(const MachineInstr &MI) {
777 const auto *MF = MI.getMF();
778 const auto &MRI = MF->getRegInfo();
779 const auto &SubTarget = MF->getSubtarget();
780 const auto *TRI = SubTarget.getRegisterInfo();
781 assert(TRI && "Expected target register info");
782 const auto *TII = SubTarget.getInstrInfo();
783 assert(TII && "Expected target instruction info");
784 if (MI.isCFIInstruction())
785 assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
787 SmallBitVector PrintedTypes(8);
788 bool ShouldPrintRegisterTies = MI.hasComplexRegisterTies();
789 unsigned I = 0, E = MI.getNumOperands();
790 for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
791 !MI.getOperand(I).isImplicit();
792 ++I) {
793 if (I)
794 OS << ", ";
795 print(MI, I, TRI, TII, ShouldPrintRegisterTies,
796 MI.getTypeToPrint(I, PrintedTypes, MRI),
797 /*PrintDef=*/false);
800 if (I)
801 OS << " = ";
802 if (MI.getFlag(MachineInstr::FrameSetup))
803 OS << "frame-setup ";
804 if (MI.getFlag(MachineInstr::FrameDestroy))
805 OS << "frame-destroy ";
806 if (MI.getFlag(MachineInstr::FmNoNans))
807 OS << "nnan ";
808 if (MI.getFlag(MachineInstr::FmNoInfs))
809 OS << "ninf ";
810 if (MI.getFlag(MachineInstr::FmNsz))
811 OS << "nsz ";
812 if (MI.getFlag(MachineInstr::FmArcp))
813 OS << "arcp ";
814 if (MI.getFlag(MachineInstr::FmContract))
815 OS << "contract ";
816 if (MI.getFlag(MachineInstr::FmAfn))
817 OS << "afn ";
818 if (MI.getFlag(MachineInstr::FmReassoc))
819 OS << "reassoc ";
820 if (MI.getFlag(MachineInstr::NoUWrap))
821 OS << "nuw ";
822 if (MI.getFlag(MachineInstr::NoSWrap))
823 OS << "nsw ";
824 if (MI.getFlag(MachineInstr::IsExact))
825 OS << "exact ";
826 if (MI.getFlag(MachineInstr::NoFPExcept))
827 OS << "nofpexcept ";
828 if (MI.getFlag(MachineInstr::NoMerge))
829 OS << "nomerge ";
830 if (MI.getFlag(MachineInstr::Unpredictable))
831 OS << "unpredictable ";
832 if (MI.getFlag(MachineInstr::NoConvergent))
833 OS << "noconvergent ";
834 if (MI.getFlag(MachineInstr::NonNeg))
835 OS << "nneg ";
836 if (MI.getFlag(MachineInstr::Disjoint))
837 OS << "disjoint ";
838 if (MI.getFlag(MachineInstr::NoUSWrap))
839 OS << "nusw ";
840 if (MI.getFlag(MachineInstr::SameSign))
841 OS << "samesign ";
843 OS << TII->getName(MI.getOpcode());
844 if (I < E)
845 OS << ' ';
847 bool NeedComma = false;
848 for (; I < E; ++I) {
849 if (NeedComma)
850 OS << ", ";
851 print(MI, I, TRI, TII, ShouldPrintRegisterTies,
852 MI.getTypeToPrint(I, PrintedTypes, MRI));
853 NeedComma = true;
856 // Print any optional symbols attached to this instruction as-if they were
857 // operands.
858 if (MCSymbol *PreInstrSymbol = MI.getPreInstrSymbol()) {
859 if (NeedComma)
860 OS << ',';
861 OS << " pre-instr-symbol ";
862 MachineOperand::printSymbol(OS, *PreInstrSymbol);
863 NeedComma = true;
865 if (MCSymbol *PostInstrSymbol = MI.getPostInstrSymbol()) {
866 if (NeedComma)
867 OS << ',';
868 OS << " post-instr-symbol ";
869 MachineOperand::printSymbol(OS, *PostInstrSymbol);
870 NeedComma = true;
872 if (MDNode *HeapAllocMarker = MI.getHeapAllocMarker()) {
873 if (NeedComma)
874 OS << ',';
875 OS << " heap-alloc-marker ";
876 HeapAllocMarker->printAsOperand(OS, MST);
877 NeedComma = true;
879 if (MDNode *PCSections = MI.getPCSections()) {
880 if (NeedComma)
881 OS << ',';
882 OS << " pcsections ";
883 PCSections->printAsOperand(OS, MST);
884 NeedComma = true;
886 if (MDNode *MMRA = MI.getMMRAMetadata()) {
887 if (NeedComma)
888 OS << ',';
889 OS << " mmra ";
890 MMRA->printAsOperand(OS, MST);
891 NeedComma = true;
893 if (uint32_t CFIType = MI.getCFIType()) {
894 if (NeedComma)
895 OS << ',';
896 OS << " cfi-type " << CFIType;
897 NeedComma = true;
900 if (auto Num = MI.peekDebugInstrNum()) {
901 if (NeedComma)
902 OS << ',';
903 OS << " debug-instr-number " << Num;
904 NeedComma = true;
907 if (PrintLocations) {
908 if (const DebugLoc &DL = MI.getDebugLoc()) {
909 if (NeedComma)
910 OS << ',';
911 OS << " debug-location ";
912 DL->printAsOperand(OS, MST);
916 if (!MI.memoperands_empty()) {
917 OS << " :: ";
918 const LLVMContext &Context = MF->getFunction().getContext();
919 const MachineFrameInfo &MFI = MF->getFrameInfo();
920 bool NeedComma = false;
921 for (const auto *Op : MI.memoperands()) {
922 if (NeedComma)
923 OS << ", ";
924 Op->print(OS, MST, SSNs, Context, &MFI, TII);
925 NeedComma = true;
930 void MIPrinter::printStackObjectReference(int FrameIndex) {
931 auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
932 assert(ObjectInfo != StackObjectOperandMapping.end() &&
933 "Invalid frame index");
934 const FrameIndexOperand &Operand = ObjectInfo->second;
935 MachineOperand::printStackObjectReference(OS, Operand.ID, Operand.IsFixed,
936 Operand.Name);
939 static std::string formatOperandComment(std::string Comment) {
940 if (Comment.empty())
941 return Comment;
942 return std::string(" /* " + Comment + " */");
945 void MIPrinter::print(const MachineInstr &MI, unsigned OpIdx,
946 const TargetRegisterInfo *TRI,
947 const TargetInstrInfo *TII,
948 bool ShouldPrintRegisterTies, LLT TypeToPrint,
949 bool PrintDef) {
950 const MachineOperand &Op = MI.getOperand(OpIdx);
951 std::string MOComment = TII->createMIROperandComment(MI, Op, OpIdx, TRI);
953 switch (Op.getType()) {
954 case MachineOperand::MO_Immediate:
955 if (MI.isOperandSubregIdx(OpIdx)) {
956 MachineOperand::printTargetFlags(OS, Op);
957 MachineOperand::printSubRegIdx(OS, Op.getImm(), TRI);
958 break;
960 [[fallthrough]];
961 case MachineOperand::MO_Register:
962 case MachineOperand::MO_CImmediate:
963 case MachineOperand::MO_FPImmediate:
964 case MachineOperand::MO_MachineBasicBlock:
965 case MachineOperand::MO_ConstantPoolIndex:
966 case MachineOperand::MO_TargetIndex:
967 case MachineOperand::MO_JumpTableIndex:
968 case MachineOperand::MO_ExternalSymbol:
969 case MachineOperand::MO_GlobalAddress:
970 case MachineOperand::MO_RegisterLiveOut:
971 case MachineOperand::MO_Metadata:
972 case MachineOperand::MO_MCSymbol:
973 case MachineOperand::MO_CFIIndex:
974 case MachineOperand::MO_IntrinsicID:
975 case MachineOperand::MO_Predicate:
976 case MachineOperand::MO_BlockAddress:
977 case MachineOperand::MO_DbgInstrRef:
978 case MachineOperand::MO_ShuffleMask: {
979 unsigned TiedOperandIdx = 0;
980 if (ShouldPrintRegisterTies && Op.isReg() && Op.isTied() && !Op.isDef())
981 TiedOperandIdx = Op.getParent()->findTiedOperandIdx(OpIdx);
982 const TargetIntrinsicInfo *TII = MI.getMF()->getTarget().getIntrinsicInfo();
983 Op.print(OS, MST, TypeToPrint, OpIdx, PrintDef, /*IsStandalone=*/false,
984 ShouldPrintRegisterTies, TiedOperandIdx, TRI, TII);
985 OS << formatOperandComment(MOComment);
986 break;
988 case MachineOperand::MO_FrameIndex:
989 printStackObjectReference(Op.getIndex());
990 break;
991 case MachineOperand::MO_RegisterMask: {
992 auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
993 if (RegMaskInfo != RegisterMaskIds.end())
994 OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
995 else
996 printCustomRegMask(Op.getRegMask(), OS, TRI);
997 break;
1002 void MIRFormatter::printIRValue(raw_ostream &OS, const Value &V,
1003 ModuleSlotTracker &MST) {
1004 if (isa<GlobalValue>(V)) {
1005 V.printAsOperand(OS, /*PrintType=*/false, MST);
1006 return;
1008 if (isa<Constant>(V)) {
1009 // Machine memory operands can load/store to/from constant value pointers.
1010 OS << '`';
1011 V.printAsOperand(OS, /*PrintType=*/true, MST);
1012 OS << '`';
1013 return;
1015 OS << "%ir.";
1016 if (V.hasName()) {
1017 printLLVMNameWithoutPrefix(OS, V.getName());
1018 return;
1020 int Slot = MST.getCurrentFunction() ? MST.getLocalSlot(&V) : -1;
1021 MachineOperand::printIRSlotNumber(OS, Slot);
1024 void llvm::printMIR(raw_ostream &OS, const Module &M) {
1025 ScopedDbgInfoFormatSetter FormatSetter(const_cast<Module &>(M),
1026 WriteNewDbgInfoFormat);
1028 yaml::Output Out(OS);
1029 Out << const_cast<Module &>(M);
1032 void llvm::printMIR(raw_ostream &OS, const MachineModuleInfo &MMI,
1033 const MachineFunction &MF) {
1034 // RemoveDIs: as there's no textual form for DbgRecords yet, print debug-info
1035 // in dbg.value format.
1036 ScopedDbgInfoFormatSetter FormatSetter(
1037 const_cast<Function &>(MF.getFunction()), WriteNewDbgInfoFormat);
1039 MIRPrinter Printer(OS, MMI);
1040 Printer.print(MF);