MIRPrinter.cpp 34 KB

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