1 //===- MIRPrinter.cpp - MIR serialization format printer ------------------===//
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
7 //===----------------------------------------------------------------------===//
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/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallBitVector.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
24 #include "llvm/CodeGen/MIRYamlMapping.h"
25 #include "llvm/CodeGen/MachineBasicBlock.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineMemOperand.h"
32 #include "llvm/CodeGen/MachineModuleSlotTracker.h"
33 #include "llvm/CodeGen/MachineOperand.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.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/IR/BasicBlock.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/DebugInfo.h"
43 #include "llvm/IR/DebugLoc.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/GlobalValue.h"
46 #include "llvm/IR/IRPrintingPasses.h"
47 #include "llvm/IR/InstrTypes.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/Intrinsics.h"
50 #include "llvm/IR/Module.h"
51 #include "llvm/IR/ModuleSlotTracker.h"
52 #include "llvm/IR/Value.h"
53 #include "llvm/MC/LaneBitmask.h"
54 #include "llvm/MC/MCContext.h"
55 #include "llvm/MC/MCDwarf.h"
56 #include "llvm/MC/MCSymbol.h"
57 #include "llvm/Support/AtomicOrdering.h"
58 #include "llvm/Support/BranchProbability.h"
59 #include "llvm/Support/Casting.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Support/ErrorHandling.h"
62 #include "llvm/Support/Format.h"
63 #include "llvm/Support/LowLevelTypeImpl.h"
64 #include "llvm/Support/YAMLTraits.h"
65 #include "llvm/Support/raw_ostream.h"
66 #include "llvm/Target/TargetIntrinsicInfo.h"
67 #include "llvm/Target/TargetMachine.h"
79 static cl::opt
<bool> SimplifyMIR(
80 "simplify-mir", cl::Hidden
,
81 cl::desc("Leave out unnecessary information when printing MIR"));
83 static cl::opt
<bool> PrintLocations("mir-debug-loc", cl::Hidden
, cl::init(true),
84 cl::desc("Print MIR debug-locations"));
88 /// This structure describes how to print out stack object references.
89 struct FrameIndexOperand
{
94 FrameIndexOperand(StringRef Name
, unsigned ID
, bool IsFixed
)
95 : Name(Name
.str()), ID(ID
), IsFixed(IsFixed
) {}
97 /// Return an ordinary stack object reference.
98 static FrameIndexOperand
create(StringRef Name
, unsigned ID
) {
99 return FrameIndexOperand(Name
, ID
, /*IsFixed=*/false);
102 /// Return a fixed stack object reference.
103 static FrameIndexOperand
createFixed(unsigned ID
) {
104 return FrameIndexOperand("", ID
, /*IsFixed=*/true);
108 } // end anonymous namespace
112 /// This class prints out the machine functions using the MIR serialization
116 DenseMap
<const uint32_t *, unsigned> RegisterMaskIds
;
117 /// Maps from stack object indices to operand indices which will be used when
118 /// printing frame index machine operands.
119 DenseMap
<int, FrameIndexOperand
> StackObjectOperandMapping
;
122 MIRPrinter(raw_ostream
&OS
) : OS(OS
) {}
124 void print(const MachineFunction
&MF
);
126 void convert(yaml::MachineFunction
&MF
, const MachineRegisterInfo
&RegInfo
,
127 const TargetRegisterInfo
*TRI
);
128 void convert(ModuleSlotTracker
&MST
, yaml::MachineFrameInfo
&YamlMFI
,
129 const MachineFrameInfo
&MFI
);
130 void convert(yaml::MachineFunction
&MF
,
131 const MachineConstantPool
&ConstantPool
);
132 void convert(ModuleSlotTracker
&MST
, yaml::MachineJumpTable
&YamlJTI
,
133 const MachineJumpTableInfo
&JTI
);
134 void convertStackObjects(yaml::MachineFunction
&YMF
,
135 const MachineFunction
&MF
, ModuleSlotTracker
&MST
);
136 void convertCallSiteObjects(yaml::MachineFunction
&YMF
,
137 const MachineFunction
&MF
,
138 ModuleSlotTracker
&MST
);
139 void convertMachineMetadataNodes(yaml::MachineFunction
&YMF
,
140 const MachineFunction
&MF
,
141 MachineModuleSlotTracker
&MST
);
144 void initRegisterMaskIds(const MachineFunction
&MF
);
147 /// This class prints out the machine instructions using the MIR serialization
151 ModuleSlotTracker
&MST
;
152 const DenseMap
<const uint32_t *, unsigned> &RegisterMaskIds
;
153 const DenseMap
<int, FrameIndexOperand
> &StackObjectOperandMapping
;
154 /// Synchronization scope names registered with LLVMContext.
155 SmallVector
<StringRef
, 8> SSNs
;
157 bool canPredictBranchProbabilities(const MachineBasicBlock
&MBB
) const;
158 bool canPredictSuccessors(const MachineBasicBlock
&MBB
) const;
161 MIPrinter(raw_ostream
&OS
, ModuleSlotTracker
&MST
,
162 const DenseMap
<const uint32_t *, unsigned> &RegisterMaskIds
,
163 const DenseMap
<int, FrameIndexOperand
> &StackObjectOperandMapping
)
164 : OS(OS
), MST(MST
), RegisterMaskIds(RegisterMaskIds
),
165 StackObjectOperandMapping(StackObjectOperandMapping
) {}
167 void print(const MachineBasicBlock
&MBB
);
169 void print(const MachineInstr
&MI
);
170 void printStackObjectReference(int FrameIndex
);
171 void print(const MachineInstr
&MI
, unsigned OpIdx
,
172 const TargetRegisterInfo
*TRI
, const TargetInstrInfo
*TII
,
173 bool ShouldPrintRegisterTies
, LLT TypeToPrint
,
174 bool PrintDef
= true);
177 } // end namespace llvm
182 /// This struct serializes the LLVM IR module.
183 template <> struct BlockScalarTraits
<Module
> {
184 static void output(const Module
&Mod
, void *Ctxt
, raw_ostream
&OS
) {
185 Mod
.print(OS
, nullptr);
188 static StringRef
input(StringRef Str
, void *Ctxt
, Module
&Mod
) {
189 llvm_unreachable("LLVM Module is supposed to be parsed separately");
194 } // end namespace yaml
195 } // end namespace llvm
197 static void printRegMIR(unsigned Reg
, yaml::StringValue
&Dest
,
198 const TargetRegisterInfo
*TRI
) {
199 raw_string_ostream
OS(Dest
.Value
);
200 OS
<< printReg(Reg
, TRI
);
203 void MIRPrinter::print(const MachineFunction
&MF
) {
204 initRegisterMaskIds(MF
);
206 yaml::MachineFunction YamlMF
;
207 YamlMF
.Name
= MF
.getName();
208 YamlMF
.Alignment
= MF
.getAlignment();
209 YamlMF
.ExposesReturnsTwice
= MF
.exposesReturnsTwice();
210 YamlMF
.HasWinCFI
= MF
.hasWinCFI();
212 YamlMF
.Legalized
= MF
.getProperties().hasProperty(
213 MachineFunctionProperties::Property::Legalized
);
214 YamlMF
.RegBankSelected
= MF
.getProperties().hasProperty(
215 MachineFunctionProperties::Property::RegBankSelected
);
216 YamlMF
.Selected
= MF
.getProperties().hasProperty(
217 MachineFunctionProperties::Property::Selected
);
218 YamlMF
.FailedISel
= MF
.getProperties().hasProperty(
219 MachineFunctionProperties::Property::FailedISel
);
221 convert(YamlMF
, MF
.getRegInfo(), MF
.getSubtarget().getRegisterInfo());
222 MachineModuleSlotTracker
MST(&MF
);
223 MST
.incorporateFunction(MF
.getFunction());
224 convert(MST
, YamlMF
.FrameInfo
, MF
.getFrameInfo());
225 convertStackObjects(YamlMF
, MF
, MST
);
226 convertCallSiteObjects(YamlMF
, MF
, MST
);
227 for (const auto &Sub
: MF
.DebugValueSubstitutions
) {
228 const auto &SubSrc
= Sub
.Src
;
229 const auto &SubDest
= Sub
.Dest
;
230 YamlMF
.DebugValueSubstitutions
.push_back({SubSrc
.first
, SubSrc
.second
,
235 if (const auto *ConstantPool
= MF
.getConstantPool())
236 convert(YamlMF
, *ConstantPool
);
237 if (const auto *JumpTableInfo
= MF
.getJumpTableInfo())
238 convert(MST
, YamlMF
.JumpTableInfo
, *JumpTableInfo
);
240 const TargetMachine
&TM
= MF
.getTarget();
241 YamlMF
.MachineFuncInfo
=
242 std::unique_ptr
<yaml::MachineFunctionInfo
>(TM
.convertFuncInfoToYAML(MF
));
244 raw_string_ostream
StrOS(YamlMF
.Body
.Value
.Value
);
245 bool IsNewlineNeeded
= false;
246 for (const auto &MBB
: MF
) {
249 MIPrinter(StrOS
, MST
, RegisterMaskIds
, StackObjectOperandMapping
)
251 IsNewlineNeeded
= true;
254 // Convert machine metadata collected during the print of the machine
256 convertMachineMetadataNodes(YamlMF
, MF
, MST
);
258 yaml::Output
Out(OS
);
260 Out
.setWriteDefaultValues(true);
264 static void printCustomRegMask(const uint32_t *RegMask
, raw_ostream
&OS
,
265 const TargetRegisterInfo
*TRI
) {
266 assert(RegMask
&& "Can't print an empty register mask");
267 OS
<< StringRef("CustomRegMask(");
269 bool IsRegInRegMaskFound
= false;
270 for (int I
= 0, E
= TRI
->getNumRegs(); I
< E
; I
++) {
271 // Check whether the register is asserted in regmask.
272 if (RegMask
[I
/ 32] & (1u << (I
% 32))) {
273 if (IsRegInRegMaskFound
)
275 OS
<< printReg(I
, TRI
);
276 IsRegInRegMaskFound
= true;
283 static void printRegClassOrBank(unsigned Reg
, yaml::StringValue
&Dest
,
284 const MachineRegisterInfo
&RegInfo
,
285 const TargetRegisterInfo
*TRI
) {
286 raw_string_ostream
OS(Dest
.Value
);
287 OS
<< printRegClassOrBank(Reg
, RegInfo
, TRI
);
290 template <typename T
>
292 printStackObjectDbgInfo(const MachineFunction::VariableDbgInfo
&DebugVar
,
293 T
&Object
, ModuleSlotTracker
&MST
) {
294 std::array
<std::string
*, 3> Outputs
{{&Object
.DebugVar
.Value
,
295 &Object
.DebugExpr
.Value
,
296 &Object
.DebugLoc
.Value
}};
297 std::array
<const Metadata
*, 3> Metas
{{DebugVar
.Var
,
300 for (unsigned i
= 0; i
< 3; ++i
) {
301 raw_string_ostream
StrOS(*Outputs
[i
]);
302 Metas
[i
]->printAsOperand(StrOS
, MST
);
306 void MIRPrinter::convert(yaml::MachineFunction
&MF
,
307 const MachineRegisterInfo
&RegInfo
,
308 const TargetRegisterInfo
*TRI
) {
309 MF
.TracksRegLiveness
= RegInfo
.tracksLiveness();
311 // Print the virtual register definitions.
312 for (unsigned I
= 0, E
= RegInfo
.getNumVirtRegs(); I
< E
; ++I
) {
313 unsigned Reg
= Register::index2VirtReg(I
);
314 yaml::VirtualRegisterDefinition VReg
;
316 if (RegInfo
.getVRegName(Reg
) != "")
318 ::printRegClassOrBank(Reg
, VReg
.Class
, RegInfo
, TRI
);
319 unsigned PreferredReg
= RegInfo
.getSimpleHint(Reg
);
321 printRegMIR(PreferredReg
, VReg
.PreferredRegister
, TRI
);
322 MF
.VirtualRegisters
.push_back(VReg
);
325 // Print the live ins.
326 for (std::pair
<unsigned, unsigned> LI
: RegInfo
.liveins()) {
327 yaml::MachineFunctionLiveIn LiveIn
;
328 printRegMIR(LI
.first
, LiveIn
.Register
, TRI
);
330 printRegMIR(LI
.second
, LiveIn
.VirtualRegister
, TRI
);
331 MF
.LiveIns
.push_back(LiveIn
);
334 // Prints the callee saved registers.
335 if (RegInfo
.isUpdatedCSRsInitialized()) {
336 const MCPhysReg
*CalleeSavedRegs
= RegInfo
.getCalleeSavedRegs();
337 std::vector
<yaml::FlowStringValue
> CalleeSavedRegisters
;
338 for (const MCPhysReg
*I
= CalleeSavedRegs
; *I
; ++I
) {
339 yaml::FlowStringValue Reg
;
340 printRegMIR(*I
, Reg
, TRI
);
341 CalleeSavedRegisters
.push_back(Reg
);
343 MF
.CalleeSavedRegisters
= CalleeSavedRegisters
;
347 void MIRPrinter::convert(ModuleSlotTracker
&MST
,
348 yaml::MachineFrameInfo
&YamlMFI
,
349 const MachineFrameInfo
&MFI
) {
350 YamlMFI
.IsFrameAddressTaken
= MFI
.isFrameAddressTaken();
351 YamlMFI
.IsReturnAddressTaken
= MFI
.isReturnAddressTaken();
352 YamlMFI
.HasStackMap
= MFI
.hasStackMap();
353 YamlMFI
.HasPatchPoint
= MFI
.hasPatchPoint();
354 YamlMFI
.StackSize
= MFI
.getStackSize();
355 YamlMFI
.OffsetAdjustment
= MFI
.getOffsetAdjustment();
356 YamlMFI
.MaxAlignment
= MFI
.getMaxAlign().value();
357 YamlMFI
.AdjustsStack
= MFI
.adjustsStack();
358 YamlMFI
.HasCalls
= MFI
.hasCalls();
359 YamlMFI
.MaxCallFrameSize
= MFI
.isMaxCallFrameSizeComputed()
360 ? MFI
.getMaxCallFrameSize() : ~0u;
361 YamlMFI
.CVBytesOfCalleeSavedRegisters
=
362 MFI
.getCVBytesOfCalleeSavedRegisters();
363 YamlMFI
.HasOpaqueSPAdjustment
= MFI
.hasOpaqueSPAdjustment();
364 YamlMFI
.HasVAStart
= MFI
.hasVAStart();
365 YamlMFI
.HasMustTailInVarArgFunc
= MFI
.hasMustTailInVarArgFunc();
366 YamlMFI
.HasTailCall
= MFI
.hasTailCall();
367 YamlMFI
.LocalFrameSize
= MFI
.getLocalFrameSize();
368 if (MFI
.getSavePoint()) {
369 raw_string_ostream
StrOS(YamlMFI
.SavePoint
.Value
);
370 StrOS
<< printMBBReference(*MFI
.getSavePoint());
372 if (MFI
.getRestorePoint()) {
373 raw_string_ostream
StrOS(YamlMFI
.RestorePoint
.Value
);
374 StrOS
<< printMBBReference(*MFI
.getRestorePoint());
378 void MIRPrinter::convertStackObjects(yaml::MachineFunction
&YMF
,
379 const MachineFunction
&MF
,
380 ModuleSlotTracker
&MST
) {
381 const MachineFrameInfo
&MFI
= MF
.getFrameInfo();
382 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
384 // Process fixed stack objects.
385 assert(YMF
.FixedStackObjects
.empty());
386 SmallVector
<int, 32> FixedStackObjectsIdx
;
387 const int BeginIdx
= MFI
.getObjectIndexBegin();
389 FixedStackObjectsIdx
.reserve(-BeginIdx
);
392 for (int I
= BeginIdx
; I
< 0; ++I
, ++ID
) {
393 FixedStackObjectsIdx
.push_back(-1); // Fill index for possible dead.
394 if (MFI
.isDeadObjectIndex(I
))
397 yaml::FixedMachineStackObject YamlObject
;
399 YamlObject
.Type
= MFI
.isSpillSlotObjectIndex(I
)
400 ? yaml::FixedMachineStackObject::SpillSlot
401 : yaml::FixedMachineStackObject::DefaultType
;
402 YamlObject
.Offset
= MFI
.getObjectOffset(I
);
403 YamlObject
.Size
= MFI
.getObjectSize(I
);
404 YamlObject
.Alignment
= MFI
.getObjectAlign(I
);
405 YamlObject
.StackID
= (TargetStackID::Value
)MFI
.getStackID(I
);
406 YamlObject
.IsImmutable
= MFI
.isImmutableObjectIndex(I
);
407 YamlObject
.IsAliased
= MFI
.isAliasedObjectIndex(I
);
408 // Save the ID' position in FixedStackObjects storage vector.
409 FixedStackObjectsIdx
[ID
] = YMF
.FixedStackObjects
.size();
410 YMF
.FixedStackObjects
.push_back(YamlObject
);
411 StackObjectOperandMapping
.insert(
412 std::make_pair(I
, FrameIndexOperand::createFixed(ID
)));
415 // Process ordinary stack objects.
416 assert(YMF
.StackObjects
.empty());
417 SmallVector
<unsigned, 32> StackObjectsIdx
;
418 const int EndIdx
= MFI
.getObjectIndexEnd();
420 StackObjectsIdx
.reserve(EndIdx
);
422 for (int I
= 0; I
< EndIdx
; ++I
, ++ID
) {
423 StackObjectsIdx
.push_back(-1); // Fill index for possible dead.
424 if (MFI
.isDeadObjectIndex(I
))
427 yaml::MachineStackObject YamlObject
;
429 if (const auto *Alloca
= MFI
.getObjectAllocation(I
))
430 YamlObject
.Name
.Value
= std::string(
431 Alloca
->hasName() ? Alloca
->getName() : "");
432 YamlObject
.Type
= MFI
.isSpillSlotObjectIndex(I
)
433 ? yaml::MachineStackObject::SpillSlot
434 : MFI
.isVariableSizedObjectIndex(I
)
435 ? yaml::MachineStackObject::VariableSized
436 : yaml::MachineStackObject::DefaultType
;
437 YamlObject
.Offset
= MFI
.getObjectOffset(I
);
438 YamlObject
.Size
= MFI
.getObjectSize(I
);
439 YamlObject
.Alignment
= MFI
.getObjectAlign(I
);
440 YamlObject
.StackID
= (TargetStackID::Value
)MFI
.getStackID(I
);
442 // Save the ID' position in StackObjects storage vector.
443 StackObjectsIdx
[ID
] = YMF
.StackObjects
.size();
444 YMF
.StackObjects
.push_back(YamlObject
);
445 StackObjectOperandMapping
.insert(std::make_pair(
446 I
, FrameIndexOperand::create(YamlObject
.Name
.Value
, ID
)));
449 for (const auto &CSInfo
: MFI
.getCalleeSavedInfo()) {
450 const int FrameIdx
= CSInfo
.getFrameIdx();
451 if (!CSInfo
.isSpilledToReg() && MFI
.isDeadObjectIndex(FrameIdx
))
454 yaml::StringValue Reg
;
455 printRegMIR(CSInfo
.getReg(), Reg
, TRI
);
456 if (!CSInfo
.isSpilledToReg()) {
457 assert(FrameIdx
>= MFI
.getObjectIndexBegin() &&
458 FrameIdx
< MFI
.getObjectIndexEnd() &&
459 "Invalid stack object index");
460 if (FrameIdx
< 0) { // Negative index means fixed objects.
462 YMF
.FixedStackObjects
463 [FixedStackObjectsIdx
[FrameIdx
+ MFI
.getNumFixedObjects()]];
464 Object
.CalleeSavedRegister
= Reg
;
465 Object
.CalleeSavedRestored
= CSInfo
.isRestored();
467 auto &Object
= YMF
.StackObjects
[StackObjectsIdx
[FrameIdx
]];
468 Object
.CalleeSavedRegister
= Reg
;
469 Object
.CalleeSavedRestored
= CSInfo
.isRestored();
473 for (unsigned I
= 0, E
= MFI
.getLocalFrameObjectCount(); I
< E
; ++I
) {
474 auto LocalObject
= MFI
.getLocalFrameObjectMap(I
);
475 assert(LocalObject
.first
>= 0 && "Expected a locally mapped stack object");
476 YMF
.StackObjects
[StackObjectsIdx
[LocalObject
.first
]].LocalOffset
=
480 // Print the stack object references in the frame information class after
481 // converting the stack objects.
482 if (MFI
.hasStackProtectorIndex()) {
483 raw_string_ostream
StrOS(YMF
.FrameInfo
.StackProtector
.Value
);
484 MIPrinter(StrOS
, MST
, RegisterMaskIds
, StackObjectOperandMapping
)
485 .printStackObjectReference(MFI
.getStackProtectorIndex());
488 // Print the debug variable information.
489 for (const MachineFunction::VariableDbgInfo
&DebugVar
:
490 MF
.getVariableDbgInfo()) {
491 assert(DebugVar
.Slot
>= MFI
.getObjectIndexBegin() &&
492 DebugVar
.Slot
< MFI
.getObjectIndexEnd() &&
493 "Invalid stack object index");
494 if (DebugVar
.Slot
< 0) { // Negative index means fixed objects.
496 YMF
.FixedStackObjects
[FixedStackObjectsIdx
[DebugVar
.Slot
+
497 MFI
.getNumFixedObjects()]];
498 printStackObjectDbgInfo(DebugVar
, Object
, MST
);
500 auto &Object
= YMF
.StackObjects
[StackObjectsIdx
[DebugVar
.Slot
]];
501 printStackObjectDbgInfo(DebugVar
, Object
, MST
);
506 void MIRPrinter::convertCallSiteObjects(yaml::MachineFunction
&YMF
,
507 const MachineFunction
&MF
,
508 ModuleSlotTracker
&MST
) {
509 const auto *TRI
= MF
.getSubtarget().getRegisterInfo();
510 for (auto CSInfo
: MF
.getCallSitesInfo()) {
511 yaml::CallSiteInfo YmlCS
;
512 yaml::CallSiteInfo::MachineInstrLoc CallLocation
;
514 // Prepare instruction position.
515 MachineBasicBlock::const_instr_iterator CallI
= CSInfo
.first
->getIterator();
516 CallLocation
.BlockNum
= CallI
->getParent()->getNumber();
517 // Get call instruction offset from the beginning of block.
518 CallLocation
.Offset
=
519 std::distance(CallI
->getParent()->instr_begin(), CallI
);
520 YmlCS
.CallLocation
= CallLocation
;
521 // Construct call arguments and theirs forwarding register info.
522 for (auto ArgReg
: CSInfo
.second
) {
523 yaml::CallSiteInfo::ArgRegPair YmlArgReg
;
524 YmlArgReg
.ArgNo
= ArgReg
.ArgNo
;
525 printRegMIR(ArgReg
.Reg
, YmlArgReg
.Reg
, TRI
);
526 YmlCS
.ArgForwardingRegs
.emplace_back(YmlArgReg
);
528 YMF
.CallSitesInfo
.push_back(YmlCS
);
531 // Sort call info by position of call instructions.
532 llvm::sort(YMF
.CallSitesInfo
.begin(), YMF
.CallSitesInfo
.end(),
533 [](yaml::CallSiteInfo A
, yaml::CallSiteInfo B
) {
534 if (A
.CallLocation
.BlockNum
== B
.CallLocation
.BlockNum
)
535 return A
.CallLocation
.Offset
< B
.CallLocation
.Offset
;
536 return A
.CallLocation
.BlockNum
< B
.CallLocation
.BlockNum
;
540 void MIRPrinter::convertMachineMetadataNodes(yaml::MachineFunction
&YMF
,
541 const MachineFunction
&MF
,
542 MachineModuleSlotTracker
&MST
) {
543 MachineModuleSlotTracker::MachineMDNodeListType MDList
;
544 MST
.collectMachineMDNodes(MDList
);
545 for (auto &MD
: MDList
) {
547 raw_string_ostream
StrOS(NS
);
548 MD
.second
->print(StrOS
, MST
, MF
.getFunction().getParent());
549 YMF
.MachineMetadataNodes
.push_back(StrOS
.str());
553 void MIRPrinter::convert(yaml::MachineFunction
&MF
,
554 const MachineConstantPool
&ConstantPool
) {
556 for (const MachineConstantPoolEntry
&Constant
: ConstantPool
.getConstants()) {
558 raw_string_ostream
StrOS(Str
);
559 if (Constant
.isMachineConstantPoolEntry()) {
560 Constant
.Val
.MachineCPVal
->print(StrOS
);
562 Constant
.Val
.ConstVal
->printAsOperand(StrOS
);
565 yaml::MachineConstantPoolValue YamlConstant
;
566 YamlConstant
.ID
= ID
++;
567 YamlConstant
.Value
= StrOS
.str();
568 YamlConstant
.Alignment
= Constant
.getAlign();
569 YamlConstant
.IsTargetSpecific
= Constant
.isMachineConstantPoolEntry();
571 MF
.Constants
.push_back(YamlConstant
);
575 void MIRPrinter::convert(ModuleSlotTracker
&MST
,
576 yaml::MachineJumpTable
&YamlJTI
,
577 const MachineJumpTableInfo
&JTI
) {
578 YamlJTI
.Kind
= JTI
.getEntryKind();
580 for (const auto &Table
: JTI
.getJumpTables()) {
582 yaml::MachineJumpTable::Entry Entry
;
584 for (const auto *MBB
: Table
.MBBs
) {
585 raw_string_ostream
StrOS(Str
);
586 StrOS
<< printMBBReference(*MBB
);
587 Entry
.Blocks
.push_back(StrOS
.str());
590 YamlJTI
.Entries
.push_back(Entry
);
594 void MIRPrinter::initRegisterMaskIds(const MachineFunction
&MF
) {
595 const auto *TRI
= MF
.getSubtarget().getRegisterInfo();
597 for (const uint32_t *Mask
: TRI
->getRegMasks())
598 RegisterMaskIds
.insert(std::make_pair(Mask
, I
++));
601 void llvm::guessSuccessors(const MachineBasicBlock
&MBB
,
602 SmallVectorImpl
<MachineBasicBlock
*> &Result
,
603 bool &IsFallthrough
) {
604 SmallPtrSet
<MachineBasicBlock
*,8> Seen
;
606 for (const MachineInstr
&MI
: MBB
) {
609 for (const MachineOperand
&MO
: MI
.operands()) {
612 MachineBasicBlock
*Succ
= MO
.getMBB();
613 auto RP
= Seen
.insert(Succ
);
615 Result
.push_back(Succ
);
618 MachineBasicBlock::const_iterator I
= MBB
.getLastNonDebugInstr();
619 IsFallthrough
= I
== MBB
.end() || !I
->isBarrier();
623 MIPrinter::canPredictBranchProbabilities(const MachineBasicBlock
&MBB
) const {
624 if (MBB
.succ_size() <= 1)
626 if (!MBB
.hasSuccessorProbabilities())
629 SmallVector
<BranchProbability
,8> Normalized(MBB
.Probs
.begin(),
631 BranchProbability::normalizeProbabilities(Normalized
.begin(),
633 SmallVector
<BranchProbability
,8> Equal(Normalized
.size());
634 BranchProbability::normalizeProbabilities(Equal
.begin(), Equal
.end());
636 return std::equal(Normalized
.begin(), Normalized
.end(), Equal
.begin());
639 bool MIPrinter::canPredictSuccessors(const MachineBasicBlock
&MBB
) const {
640 SmallVector
<MachineBasicBlock
*,8> GuessedSuccs
;
641 bool GuessedFallthrough
;
642 guessSuccessors(MBB
, GuessedSuccs
, GuessedFallthrough
);
643 if (GuessedFallthrough
) {
644 const MachineFunction
&MF
= *MBB
.getParent();
645 MachineFunction::const_iterator NextI
= std::next(MBB
.getIterator());
646 if (NextI
!= MF
.end()) {
647 MachineBasicBlock
*Next
= const_cast<MachineBasicBlock
*>(&*NextI
);
648 if (!is_contained(GuessedSuccs
, Next
))
649 GuessedSuccs
.push_back(Next
);
652 if (GuessedSuccs
.size() != MBB
.succ_size())
654 return std::equal(MBB
.succ_begin(), MBB
.succ_end(), GuessedSuccs
.begin());
657 void MIPrinter::print(const MachineBasicBlock
&MBB
) {
658 assert(MBB
.getNumber() >= 0 && "Invalid MBB number");
660 MachineBasicBlock::PrintNameIr
|
661 MachineBasicBlock::PrintNameAttributes
,
665 bool HasLineAttributes
= false;
666 // Print the successors
667 bool canPredictProbs
= canPredictBranchProbabilities(MBB
);
668 // Even if the list of successors is empty, if we cannot guess it,
669 // we need to print it to tell the parser that the list is empty.
670 // This is needed, because MI model unreachable as empty blocks
671 // with an empty successor list. If the parser would see that
672 // without the successor list, it would guess the code would
674 if ((!MBB
.succ_empty() && !SimplifyMIR
) || !canPredictProbs
||
675 !canPredictSuccessors(MBB
)) {
676 OS
.indent(2) << "successors: ";
677 for (auto I
= MBB
.succ_begin(), E
= MBB
.succ_end(); I
!= E
; ++I
) {
678 if (I
!= MBB
.succ_begin())
680 OS
<< printMBBReference(**I
);
681 if (!SimplifyMIR
|| !canPredictProbs
)
683 << format("0x%08" PRIx32
, MBB
.getSuccProbability(I
).getNumerator())
687 HasLineAttributes
= true;
690 // Print the live in registers.
691 const MachineRegisterInfo
&MRI
= MBB
.getParent()->getRegInfo();
692 if (MRI
.tracksLiveness() && !MBB
.livein_empty()) {
693 const TargetRegisterInfo
&TRI
= *MRI
.getTargetRegisterInfo();
694 OS
.indent(2) << "liveins: ";
696 for (const auto &LI
: MBB
.liveins()) {
700 OS
<< printReg(LI
.PhysReg
, &TRI
);
701 if (!LI
.LaneMask
.all())
702 OS
<< ":0x" << PrintLaneMask(LI
.LaneMask
);
705 HasLineAttributes
= true;
708 if (HasLineAttributes
)
710 bool IsInBundle
= false;
711 for (auto I
= MBB
.instr_begin(), E
= MBB
.instr_end(); I
!= E
; ++I
) {
712 const MachineInstr
&MI
= *I
;
713 if (IsInBundle
&& !MI
.isInsideBundle()) {
714 OS
.indent(2) << "}\n";
717 OS
.indent(IsInBundle
? 4 : 2);
719 if (!IsInBundle
&& MI
.getFlag(MachineInstr::BundledSucc
)) {
726 OS
.indent(2) << "}\n";
729 void MIPrinter::print(const MachineInstr
&MI
) {
730 const auto *MF
= MI
.getMF();
731 const auto &MRI
= MF
->getRegInfo();
732 const auto &SubTarget
= MF
->getSubtarget();
733 const auto *TRI
= SubTarget
.getRegisterInfo();
734 assert(TRI
&& "Expected target register info");
735 const auto *TII
= SubTarget
.getInstrInfo();
736 assert(TII
&& "Expected target instruction info");
737 if (MI
.isCFIInstruction())
738 assert(MI
.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
740 SmallBitVector
PrintedTypes(8);
741 bool ShouldPrintRegisterTies
= MI
.hasComplexRegisterTies();
742 unsigned I
= 0, E
= MI
.getNumOperands();
743 for (; I
< E
&& MI
.getOperand(I
).isReg() && MI
.getOperand(I
).isDef() &&
744 !MI
.getOperand(I
).isImplicit();
748 print(MI
, I
, TRI
, TII
, ShouldPrintRegisterTies
,
749 MI
.getTypeToPrint(I
, PrintedTypes
, MRI
),
755 if (MI
.getFlag(MachineInstr::FrameSetup
))
756 OS
<< "frame-setup ";
757 if (MI
.getFlag(MachineInstr::FrameDestroy
))
758 OS
<< "frame-destroy ";
759 if (MI
.getFlag(MachineInstr::FmNoNans
))
761 if (MI
.getFlag(MachineInstr::FmNoInfs
))
763 if (MI
.getFlag(MachineInstr::FmNsz
))
765 if (MI
.getFlag(MachineInstr::FmArcp
))
767 if (MI
.getFlag(MachineInstr::FmContract
))
769 if (MI
.getFlag(MachineInstr::FmAfn
))
771 if (MI
.getFlag(MachineInstr::FmReassoc
))
773 if (MI
.getFlag(MachineInstr::NoUWrap
))
775 if (MI
.getFlag(MachineInstr::NoSWrap
))
777 if (MI
.getFlag(MachineInstr::IsExact
))
779 if (MI
.getFlag(MachineInstr::NoFPExcept
))
781 if (MI
.getFlag(MachineInstr::NoMerge
))
784 OS
<< TII
->getName(MI
.getOpcode());
788 bool NeedComma
= false;
792 print(MI
, I
, TRI
, TII
, ShouldPrintRegisterTies
,
793 MI
.getTypeToPrint(I
, PrintedTypes
, MRI
));
797 // Print any optional symbols attached to this instruction as-if they were
799 if (MCSymbol
*PreInstrSymbol
= MI
.getPreInstrSymbol()) {
802 OS
<< " pre-instr-symbol ";
803 MachineOperand::printSymbol(OS
, *PreInstrSymbol
);
806 if (MCSymbol
*PostInstrSymbol
= MI
.getPostInstrSymbol()) {
809 OS
<< " post-instr-symbol ";
810 MachineOperand::printSymbol(OS
, *PostInstrSymbol
);
813 if (MDNode
*HeapAllocMarker
= MI
.getHeapAllocMarker()) {
816 OS
<< " heap-alloc-marker ";
817 HeapAllocMarker
->printAsOperand(OS
, MST
);
821 if (auto Num
= MI
.peekDebugInstrNum()) {
824 OS
<< " debug-instr-number " << Num
;
828 if (PrintLocations
) {
829 if (const DebugLoc
&DL
= MI
.getDebugLoc()) {
832 OS
<< " debug-location ";
833 DL
->printAsOperand(OS
, MST
);
837 if (!MI
.memoperands_empty()) {
839 const LLVMContext
&Context
= MF
->getFunction().getContext();
840 const MachineFrameInfo
&MFI
= MF
->getFrameInfo();
841 bool NeedComma
= false;
842 for (const auto *Op
: MI
.memoperands()) {
845 Op
->print(OS
, MST
, SSNs
, Context
, &MFI
, TII
);
851 void MIPrinter::printStackObjectReference(int FrameIndex
) {
852 auto ObjectInfo
= StackObjectOperandMapping
.find(FrameIndex
);
853 assert(ObjectInfo
!= StackObjectOperandMapping
.end() &&
854 "Invalid frame index");
855 const FrameIndexOperand
&Operand
= ObjectInfo
->second
;
856 MachineOperand::printStackObjectReference(OS
, Operand
.ID
, Operand
.IsFixed
,
860 static std::string
formatOperandComment(std::string Comment
) {
863 return std::string(" /* " + Comment
+ " */");
866 void MIPrinter::print(const MachineInstr
&MI
, unsigned OpIdx
,
867 const TargetRegisterInfo
*TRI
,
868 const TargetInstrInfo
*TII
,
869 bool ShouldPrintRegisterTies
, LLT TypeToPrint
,
871 const MachineOperand
&Op
= MI
.getOperand(OpIdx
);
872 std::string MOComment
= TII
->createMIROperandComment(MI
, Op
, OpIdx
, TRI
);
874 switch (Op
.getType()) {
875 case MachineOperand::MO_Immediate
:
876 if (MI
.isOperandSubregIdx(OpIdx
)) {
877 MachineOperand::printTargetFlags(OS
, Op
);
878 MachineOperand::printSubRegIdx(OS
, Op
.getImm(), TRI
);
882 case MachineOperand::MO_Register
:
883 case MachineOperand::MO_CImmediate
:
884 case MachineOperand::MO_FPImmediate
:
885 case MachineOperand::MO_MachineBasicBlock
:
886 case MachineOperand::MO_ConstantPoolIndex
:
887 case MachineOperand::MO_TargetIndex
:
888 case MachineOperand::MO_JumpTableIndex
:
889 case MachineOperand::MO_ExternalSymbol
:
890 case MachineOperand::MO_GlobalAddress
:
891 case MachineOperand::MO_RegisterLiveOut
:
892 case MachineOperand::MO_Metadata
:
893 case MachineOperand::MO_MCSymbol
:
894 case MachineOperand::MO_CFIIndex
:
895 case MachineOperand::MO_IntrinsicID
:
896 case MachineOperand::MO_Predicate
:
897 case MachineOperand::MO_BlockAddress
:
898 case MachineOperand::MO_ShuffleMask
: {
899 unsigned TiedOperandIdx
= 0;
900 if (ShouldPrintRegisterTies
&& Op
.isReg() && Op
.isTied() && !Op
.isDef())
901 TiedOperandIdx
= Op
.getParent()->findTiedOperandIdx(OpIdx
);
902 const TargetIntrinsicInfo
*TII
= MI
.getMF()->getTarget().getIntrinsicInfo();
903 Op
.print(OS
, MST
, TypeToPrint
, OpIdx
, PrintDef
, /*IsStandalone=*/false,
904 ShouldPrintRegisterTies
, TiedOperandIdx
, TRI
, TII
);
905 OS
<< formatOperandComment(MOComment
);
908 case MachineOperand::MO_FrameIndex
:
909 printStackObjectReference(Op
.getIndex());
911 case MachineOperand::MO_RegisterMask
: {
912 auto RegMaskInfo
= RegisterMaskIds
.find(Op
.getRegMask());
913 if (RegMaskInfo
!= RegisterMaskIds
.end())
914 OS
<< StringRef(TRI
->getRegMaskNames()[RegMaskInfo
->second
]).lower();
916 printCustomRegMask(Op
.getRegMask(), OS
, TRI
);
922 void MIRFormatter::printIRValue(raw_ostream
&OS
, const Value
&V
,
923 ModuleSlotTracker
&MST
) {
924 if (isa
<GlobalValue
>(V
)) {
925 V
.printAsOperand(OS
, /*PrintType=*/false, MST
);
928 if (isa
<Constant
>(V
)) {
929 // Machine memory operands can load/store to/from constant value pointers.
931 V
.printAsOperand(OS
, /*PrintType=*/true, MST
);
937 printLLVMNameWithoutPrefix(OS
, V
.getName());
940 int Slot
= MST
.getCurrentFunction() ? MST
.getLocalSlot(&V
) : -1;
941 MachineOperand::printIRSlotNumber(OS
, Slot
);
944 void llvm::printMIR(raw_ostream
&OS
, const Module
&M
) {
945 yaml::Output
Out(OS
);
946 Out
<< const_cast<Module
&>(M
);
949 void llvm::printMIR(raw_ostream
&OS
, const MachineFunction
&MF
) {
950 MIRPrinter
Printer(OS
);