MIRPrinter.cpp 32 KB

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