MIRPrinter.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  1. //===- MIRPrinter.cpp - MIR serialization format printer ------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the class that prints out the LLVM IR and machine
  11. // functions using the MIR serialization format.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/None.h"
  16. #include "llvm/ADT/SmallBitVector.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/ADT/Twine.h"
  23. #include "llvm/CodeGen/GlobalISel/RegisterBank.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/MIRPrinter.h"
  34. #include "llvm/CodeGen/MIRYamlMapping.h"
  35. #include "llvm/CodeGen/PseudoSourceValue.h"
  36. #include "llvm/IR/BasicBlock.h"
  37. #include "llvm/IR/Constants.h"
  38. #include "llvm/IR/DebugInfo.h"
  39. #include "llvm/IR/DebugLoc.h"
  40. #include "llvm/IR/Function.h"
  41. #include "llvm/IR/GlobalValue.h"
  42. #include "llvm/IR/InstrTypes.h"
  43. #include "llvm/IR/Instructions.h"
  44. #include "llvm/IR/Intrinsics.h"
  45. #include "llvm/IR/IRPrintingPasses.h"
  46. #include "llvm/IR/Module.h"
  47. #include "llvm/IR/ModuleSlotTracker.h"
  48. #include "llvm/IR/Value.h"
  49. #include "llvm/MC/LaneBitmask.h"
  50. #include "llvm/MC/MCDwarf.h"
  51. #include "llvm/MC/MCSymbol.h"
  52. #include "llvm/Support/AtomicOrdering.h"
  53. #include "llvm/Support/BranchProbability.h"
  54. #include "llvm/Support/Casting.h"
  55. #include "llvm/Support/CommandLine.h"
  56. #include "llvm/Support/ErrorHandling.h"
  57. #include "llvm/Support/Format.h"
  58. #include "llvm/Support/LowLevelTypeImpl.h"
  59. #include "llvm/Support/raw_ostream.h"
  60. #include "llvm/Support/YAMLTraits.h"
  61. #include "llvm/Target/TargetInstrInfo.h"
  62. #include "llvm/Target/TargetIntrinsicInfo.h"
  63. #include "llvm/Target/TargetMachine.h"
  64. #include "llvm/Target/TargetRegisterInfo.h"
  65. #include "llvm/Target/TargetSubtargetInfo.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("simplify-mir",
  76. cl::desc("Leave out unnecessary information when printing MIR"));
  77. namespace {
  78. /// This structure describes how to print out stack object references.
  79. struct FrameIndexOperand {
  80. std::string Name;
  81. unsigned ID;
  82. bool IsFixed;
  83. FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed)
  84. : Name(Name.str()), ID(ID), IsFixed(IsFixed) {}
  85. /// Return an ordinary stack object reference.
  86. static FrameIndexOperand create(StringRef Name, unsigned ID) {
  87. return FrameIndexOperand(Name, ID, /*IsFixed=*/false);
  88. }
  89. /// Return a fixed stack object reference.
  90. static FrameIndexOperand createFixed(unsigned ID) {
  91. return FrameIndexOperand("", ID, /*IsFixed=*/true);
  92. }
  93. };
  94. } // end anonymous namespace
  95. namespace llvm {
  96. /// This class prints out the machine functions using the MIR serialization
  97. /// format.
  98. class MIRPrinter {
  99. raw_ostream &OS;
  100. DenseMap<const uint32_t *, unsigned> RegisterMaskIds;
  101. /// Maps from stack object indices to operand indices which will be used when
  102. /// printing frame index machine operands.
  103. DenseMap<int, FrameIndexOperand> StackObjectOperandMapping;
  104. public:
  105. MIRPrinter(raw_ostream &OS) : OS(OS) {}
  106. void print(const MachineFunction &MF);
  107. void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo,
  108. const TargetRegisterInfo *TRI);
  109. void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI,
  110. const MachineFrameInfo &MFI);
  111. void convert(yaml::MachineFunction &MF,
  112. const MachineConstantPool &ConstantPool);
  113. void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI,
  114. const MachineJumpTableInfo &JTI);
  115. void convertStackObjects(yaml::MachineFunction &YMF,
  116. const MachineFunction &MF, ModuleSlotTracker &MST);
  117. private:
  118. void initRegisterMaskIds(const MachineFunction &MF);
  119. };
  120. /// This class prints out the machine instructions using the MIR serialization
  121. /// format.
  122. class MIPrinter {
  123. raw_ostream &OS;
  124. ModuleSlotTracker &MST;
  125. const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds;
  126. const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping;
  127. /// Synchronization scope names registered with LLVMContext.
  128. SmallVector<StringRef, 8> SSNs;
  129. bool canPredictBranchProbabilities(const MachineBasicBlock &MBB) const;
  130. bool canPredictSuccessors(const MachineBasicBlock &MBB) const;
  131. public:
  132. MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST,
  133. const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds,
  134. const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping)
  135. : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds),
  136. StackObjectOperandMapping(StackObjectOperandMapping) {}
  137. void print(const MachineBasicBlock &MBB);
  138. void print(const MachineInstr &MI);
  139. void printMBBReference(const MachineBasicBlock &MBB);
  140. void printIRBlockReference(const BasicBlock &BB);
  141. void printIRValueReference(const Value &V);
  142. void printStackObjectReference(int FrameIndex);
  143. void printOffset(int64_t Offset);
  144. void printTargetFlags(const MachineOperand &Op);
  145. void print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
  146. unsigned I, bool ShouldPrintRegisterTies,
  147. LLT TypeToPrint, bool IsDef = false);
  148. void print(const LLVMContext &Context, const TargetInstrInfo &TII,
  149. const MachineMemOperand &Op);
  150. void printSyncScope(const LLVMContext &Context, SyncScope::ID SSID);
  151. void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI);
  152. };
  153. } // end namespace llvm
  154. namespace llvm {
  155. namespace yaml {
  156. /// This struct serializes the LLVM IR module.
  157. template <> struct BlockScalarTraits<Module> {
  158. static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) {
  159. Mod.print(OS, nullptr);
  160. }
  161. static StringRef input(StringRef Str, void *Ctxt, Module &Mod) {
  162. llvm_unreachable("LLVM Module is supposed to be parsed separately");
  163. return "";
  164. }
  165. };
  166. } // end namespace yaml
  167. } // end namespace llvm
  168. static void printReg(unsigned Reg, raw_ostream &OS,
  169. const TargetRegisterInfo *TRI) {
  170. // TODO: Print Stack Slots.
  171. if (!Reg)
  172. OS << '_';
  173. else if (TargetRegisterInfo::isVirtualRegister(Reg))
  174. OS << '%' << TargetRegisterInfo::virtReg2Index(Reg);
  175. else if (Reg < TRI->getNumRegs())
  176. OS << '%' << StringRef(TRI->getName(Reg)).lower();
  177. else
  178. llvm_unreachable("Can't print this kind of register yet");
  179. }
  180. static void printReg(unsigned Reg, yaml::StringValue &Dest,
  181. const TargetRegisterInfo *TRI) {
  182. raw_string_ostream OS(Dest.Value);
  183. printReg(Reg, OS, TRI);
  184. }
  185. void MIRPrinter::print(const MachineFunction &MF) {
  186. initRegisterMaskIds(MF);
  187. yaml::MachineFunction YamlMF;
  188. YamlMF.Name = MF.getName();
  189. YamlMF.Alignment = MF.getAlignment();
  190. YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice();
  191. YamlMF.Legalized = MF.getProperties().hasProperty(
  192. MachineFunctionProperties::Property::Legalized);
  193. YamlMF.RegBankSelected = MF.getProperties().hasProperty(
  194. MachineFunctionProperties::Property::RegBankSelected);
  195. YamlMF.Selected = MF.getProperties().hasProperty(
  196. MachineFunctionProperties::Property::Selected);
  197. convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo());
  198. ModuleSlotTracker MST(MF.getFunction()->getParent());
  199. MST.incorporateFunction(*MF.getFunction());
  200. convert(MST, YamlMF.FrameInfo, MF.getFrameInfo());
  201. convertStackObjects(YamlMF, MF, MST);
  202. if (const auto *ConstantPool = MF.getConstantPool())
  203. convert(YamlMF, *ConstantPool);
  204. if (const auto *JumpTableInfo = MF.getJumpTableInfo())
  205. convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo);
  206. raw_string_ostream StrOS(YamlMF.Body.Value.Value);
  207. bool IsNewlineNeeded = false;
  208. for (const auto &MBB : MF) {
  209. if (IsNewlineNeeded)
  210. StrOS << "\n";
  211. MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
  212. .print(MBB);
  213. IsNewlineNeeded = true;
  214. }
  215. StrOS.flush();
  216. yaml::Output Out(OS);
  217. if (!SimplifyMIR)
  218. Out.setWriteDefaultValues(true);
  219. Out << YamlMF;
  220. }
  221. static void printCustomRegMask(const uint32_t *RegMask, raw_ostream &OS,
  222. const TargetRegisterInfo *TRI) {
  223. assert(RegMask && "Can't print an empty register mask");
  224. OS << StringRef("CustomRegMask(");
  225. bool IsRegInRegMaskFound = false;
  226. for (int I = 0, E = TRI->getNumRegs(); I < E; I++) {
  227. // Check whether the register is asserted in regmask.
  228. if (RegMask[I / 32] & (1u << (I % 32))) {
  229. if (IsRegInRegMaskFound)
  230. OS << ',';
  231. printReg(I, OS, TRI);
  232. IsRegInRegMaskFound = true;
  233. }
  234. }
  235. OS << ')';
  236. }
  237. void MIRPrinter::convert(yaml::MachineFunction &MF,
  238. const MachineRegisterInfo &RegInfo,
  239. const TargetRegisterInfo *TRI) {
  240. MF.TracksRegLiveness = RegInfo.tracksLiveness();
  241. // Print the virtual register definitions.
  242. for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) {
  243. unsigned Reg = TargetRegisterInfo::index2VirtReg(I);
  244. yaml::VirtualRegisterDefinition VReg;
  245. VReg.ID = I;
  246. if (RegInfo.getRegClassOrNull(Reg))
  247. VReg.Class =
  248. StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
  249. else if (RegInfo.getRegBankOrNull(Reg))
  250. VReg.Class = StringRef(RegInfo.getRegBankOrNull(Reg)->getName()).lower();
  251. else {
  252. VReg.Class = std::string("_");
  253. assert((RegInfo.def_empty(Reg) || RegInfo.getType(Reg).isValid()) &&
  254. "Generic registers must have a valid type");
  255. }
  256. unsigned PreferredReg = RegInfo.getSimpleHint(Reg);
  257. if (PreferredReg)
  258. printReg(PreferredReg, VReg.PreferredRegister, TRI);
  259. MF.VirtualRegisters.push_back(VReg);
  260. }
  261. // Print the live ins.
  262. for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) {
  263. yaml::MachineFunctionLiveIn LiveIn;
  264. printReg(I->first, LiveIn.Register, TRI);
  265. if (I->second)
  266. printReg(I->second, LiveIn.VirtualRegister, TRI);
  267. MF.LiveIns.push_back(LiveIn);
  268. }
  269. // Prints the callee saved registers.
  270. if (RegInfo.isUpdatedCSRsInitialized()) {
  271. const MCPhysReg *CalleeSavedRegs = RegInfo.getCalleeSavedRegs();
  272. std::vector<yaml::FlowStringValue> CalleeSavedRegisters;
  273. for (const MCPhysReg *I = CalleeSavedRegs; *I; ++I) {
  274. yaml::FlowStringValue Reg;
  275. printReg(*I, Reg, TRI);
  276. CalleeSavedRegisters.push_back(Reg);
  277. }
  278. MF.CalleeSavedRegisters = CalleeSavedRegisters;
  279. }
  280. }
  281. void MIRPrinter::convert(ModuleSlotTracker &MST,
  282. yaml::MachineFrameInfo &YamlMFI,
  283. const MachineFrameInfo &MFI) {
  284. YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken();
  285. YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken();
  286. YamlMFI.HasStackMap = MFI.hasStackMap();
  287. YamlMFI.HasPatchPoint = MFI.hasPatchPoint();
  288. YamlMFI.StackSize = MFI.getStackSize();
  289. YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment();
  290. YamlMFI.MaxAlignment = MFI.getMaxAlignment();
  291. YamlMFI.AdjustsStack = MFI.adjustsStack();
  292. YamlMFI.HasCalls = MFI.hasCalls();
  293. YamlMFI.MaxCallFrameSize = MFI.isMaxCallFrameSizeComputed()
  294. ? MFI.getMaxCallFrameSize() : ~0u;
  295. YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment();
  296. YamlMFI.HasVAStart = MFI.hasVAStart();
  297. YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc();
  298. if (MFI.getSavePoint()) {
  299. raw_string_ostream StrOS(YamlMFI.SavePoint.Value);
  300. MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
  301. .printMBBReference(*MFI.getSavePoint());
  302. }
  303. if (MFI.getRestorePoint()) {
  304. raw_string_ostream StrOS(YamlMFI.RestorePoint.Value);
  305. MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
  306. .printMBBReference(*MFI.getRestorePoint());
  307. }
  308. }
  309. void MIRPrinter::convertStackObjects(yaml::MachineFunction &YMF,
  310. const MachineFunction &MF,
  311. ModuleSlotTracker &MST) {
  312. const MachineFrameInfo &MFI = MF.getFrameInfo();
  313. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  314. // Process fixed stack objects.
  315. unsigned ID = 0;
  316. for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
  317. if (MFI.isDeadObjectIndex(I))
  318. continue;
  319. yaml::FixedMachineStackObject YamlObject;
  320. YamlObject.ID = ID;
  321. YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
  322. ? yaml::FixedMachineStackObject::SpillSlot
  323. : yaml::FixedMachineStackObject::DefaultType;
  324. YamlObject.Offset = MFI.getObjectOffset(I);
  325. YamlObject.Size = MFI.getObjectSize(I);
  326. YamlObject.Alignment = MFI.getObjectAlignment(I);
  327. YamlObject.StackID = MFI.getStackID(I);
  328. YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I);
  329. YamlObject.IsAliased = MFI.isAliasedObjectIndex(I);
  330. YMF.FixedStackObjects.push_back(YamlObject);
  331. StackObjectOperandMapping.insert(
  332. std::make_pair(I, FrameIndexOperand::createFixed(ID++)));
  333. }
  334. // Process ordinary stack objects.
  335. ID = 0;
  336. for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) {
  337. if (MFI.isDeadObjectIndex(I))
  338. continue;
  339. yaml::MachineStackObject YamlObject;
  340. YamlObject.ID = ID;
  341. if (const auto *Alloca = MFI.getObjectAllocation(I))
  342. YamlObject.Name.Value =
  343. Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>";
  344. YamlObject.Type = MFI.isSpillSlotObjectIndex(I)
  345. ? yaml::MachineStackObject::SpillSlot
  346. : MFI.isVariableSizedObjectIndex(I)
  347. ? yaml::MachineStackObject::VariableSized
  348. : yaml::MachineStackObject::DefaultType;
  349. YamlObject.Offset = MFI.getObjectOffset(I);
  350. YamlObject.Size = MFI.getObjectSize(I);
  351. YamlObject.Alignment = MFI.getObjectAlignment(I);
  352. YamlObject.StackID = MFI.getStackID(I);
  353. YMF.StackObjects.push_back(YamlObject);
  354. StackObjectOperandMapping.insert(std::make_pair(
  355. I, FrameIndexOperand::create(YamlObject.Name.Value, ID++)));
  356. }
  357. for (const auto &CSInfo : MFI.getCalleeSavedInfo()) {
  358. yaml::StringValue Reg;
  359. printReg(CSInfo.getReg(), Reg, TRI);
  360. auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx());
  361. assert(StackObjectInfo != StackObjectOperandMapping.end() &&
  362. "Invalid stack object index");
  363. const FrameIndexOperand &StackObject = StackObjectInfo->second;
  364. if (StackObject.IsFixed) {
  365. YMF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg;
  366. YMF.FixedStackObjects[StackObject.ID].CalleeSavedRestored =
  367. CSInfo.isRestored();
  368. } else {
  369. YMF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg;
  370. YMF.StackObjects[StackObject.ID].CalleeSavedRestored =
  371. CSInfo.isRestored();
  372. }
  373. }
  374. for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) {
  375. auto LocalObject = MFI.getLocalFrameObjectMap(I);
  376. auto StackObjectInfo = StackObjectOperandMapping.find(LocalObject.first);
  377. assert(StackObjectInfo != StackObjectOperandMapping.end() &&
  378. "Invalid stack object index");
  379. const FrameIndexOperand &StackObject = StackObjectInfo->second;
  380. assert(!StackObject.IsFixed && "Expected a locally mapped stack object");
  381. YMF.StackObjects[StackObject.ID].LocalOffset = LocalObject.second;
  382. }
  383. // Print the stack object references in the frame information class after
  384. // converting the stack objects.
  385. if (MFI.hasStackProtectorIndex()) {
  386. raw_string_ostream StrOS(YMF.FrameInfo.StackProtector.Value);
  387. MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
  388. .printStackObjectReference(MFI.getStackProtectorIndex());
  389. }
  390. // Print the debug variable information.
  391. for (const MachineFunction::VariableDbgInfo &DebugVar :
  392. MF.getVariableDbgInfo()) {
  393. auto StackObjectInfo = StackObjectOperandMapping.find(DebugVar.Slot);
  394. assert(StackObjectInfo != StackObjectOperandMapping.end() &&
  395. "Invalid stack object index");
  396. const FrameIndexOperand &StackObject = StackObjectInfo->second;
  397. assert(!StackObject.IsFixed && "Expected a non-fixed stack object");
  398. auto &Object = YMF.StackObjects[StackObject.ID];
  399. {
  400. raw_string_ostream StrOS(Object.DebugVar.Value);
  401. DebugVar.Var->printAsOperand(StrOS, MST);
  402. }
  403. {
  404. raw_string_ostream StrOS(Object.DebugExpr.Value);
  405. DebugVar.Expr->printAsOperand(StrOS, MST);
  406. }
  407. {
  408. raw_string_ostream StrOS(Object.DebugLoc.Value);
  409. DebugVar.Loc->printAsOperand(StrOS, MST);
  410. }
  411. }
  412. }
  413. void MIRPrinter::convert(yaml::MachineFunction &MF,
  414. const MachineConstantPool &ConstantPool) {
  415. unsigned ID = 0;
  416. for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) {
  417. std::string Str;
  418. raw_string_ostream StrOS(Str);
  419. if (Constant.isMachineConstantPoolEntry()) {
  420. Constant.Val.MachineCPVal->print(StrOS);
  421. } else {
  422. Constant.Val.ConstVal->printAsOperand(StrOS);
  423. }
  424. yaml::MachineConstantPoolValue YamlConstant;
  425. YamlConstant.ID = ID++;
  426. YamlConstant.Value = StrOS.str();
  427. YamlConstant.Alignment = Constant.getAlignment();
  428. YamlConstant.IsTargetSpecific = Constant.isMachineConstantPoolEntry();
  429. MF.Constants.push_back(YamlConstant);
  430. }
  431. }
  432. void MIRPrinter::convert(ModuleSlotTracker &MST,
  433. yaml::MachineJumpTable &YamlJTI,
  434. const MachineJumpTableInfo &JTI) {
  435. YamlJTI.Kind = JTI.getEntryKind();
  436. unsigned ID = 0;
  437. for (const auto &Table : JTI.getJumpTables()) {
  438. std::string Str;
  439. yaml::MachineJumpTable::Entry Entry;
  440. Entry.ID = ID++;
  441. for (const auto *MBB : Table.MBBs) {
  442. raw_string_ostream StrOS(Str);
  443. MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping)
  444. .printMBBReference(*MBB);
  445. Entry.Blocks.push_back(StrOS.str());
  446. Str.clear();
  447. }
  448. YamlJTI.Entries.push_back(Entry);
  449. }
  450. }
  451. void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) {
  452. const auto *TRI = MF.getSubtarget().getRegisterInfo();
  453. unsigned I = 0;
  454. for (const uint32_t *Mask : TRI->getRegMasks())
  455. RegisterMaskIds.insert(std::make_pair(Mask, I++));
  456. }
  457. void llvm::guessSuccessors(const MachineBasicBlock &MBB,
  458. SmallVectorImpl<MachineBasicBlock*> &Result,
  459. bool &IsFallthrough) {
  460. SmallPtrSet<MachineBasicBlock*,8> Seen;
  461. for (const MachineInstr &MI : MBB) {
  462. if (MI.isPHI())
  463. continue;
  464. for (const MachineOperand &MO : MI.operands()) {
  465. if (!MO.isMBB())
  466. continue;
  467. MachineBasicBlock *Succ = MO.getMBB();
  468. auto RP = Seen.insert(Succ);
  469. if (RP.second)
  470. Result.push_back(Succ);
  471. }
  472. }
  473. MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
  474. IsFallthrough = I == MBB.end() || !I->isBarrier();
  475. }
  476. bool
  477. MIPrinter::canPredictBranchProbabilities(const MachineBasicBlock &MBB) const {
  478. if (MBB.succ_size() <= 1)
  479. return true;
  480. if (!MBB.hasSuccessorProbabilities())
  481. return true;
  482. SmallVector<BranchProbability,8> Normalized(MBB.Probs.begin(),
  483. MBB.Probs.end());
  484. BranchProbability::normalizeProbabilities(Normalized.begin(),
  485. Normalized.end());
  486. SmallVector<BranchProbability,8> Equal(Normalized.size());
  487. BranchProbability::normalizeProbabilities(Equal.begin(), Equal.end());
  488. return std::equal(Normalized.begin(), Normalized.end(), Equal.begin());
  489. }
  490. bool MIPrinter::canPredictSuccessors(const MachineBasicBlock &MBB) const {
  491. SmallVector<MachineBasicBlock*,8> GuessedSuccs;
  492. bool GuessedFallthrough;
  493. guessSuccessors(MBB, GuessedSuccs, GuessedFallthrough);
  494. if (GuessedFallthrough) {
  495. const MachineFunction &MF = *MBB.getParent();
  496. MachineFunction::const_iterator NextI = std::next(MBB.getIterator());
  497. if (NextI != MF.end()) {
  498. MachineBasicBlock *Next = const_cast<MachineBasicBlock*>(&*NextI);
  499. if (!is_contained(GuessedSuccs, Next))
  500. GuessedSuccs.push_back(Next);
  501. }
  502. }
  503. if (GuessedSuccs.size() != MBB.succ_size())
  504. return false;
  505. return std::equal(MBB.succ_begin(), MBB.succ_end(), GuessedSuccs.begin());
  506. }
  507. void MIPrinter::print(const MachineBasicBlock &MBB) {
  508. assert(MBB.getNumber() >= 0 && "Invalid MBB number");
  509. OS << "bb." << MBB.getNumber();
  510. bool HasAttributes = false;
  511. if (const auto *BB = MBB.getBasicBlock()) {
  512. if (BB->hasName()) {
  513. OS << "." << BB->getName();
  514. } else {
  515. HasAttributes = true;
  516. OS << " (";
  517. int Slot = MST.getLocalSlot(BB);
  518. if (Slot == -1)
  519. OS << "<ir-block badref>";
  520. else
  521. OS << (Twine("%ir-block.") + Twine(Slot)).str();
  522. }
  523. }
  524. if (MBB.hasAddressTaken()) {
  525. OS << (HasAttributes ? ", " : " (");
  526. OS << "address-taken";
  527. HasAttributes = true;
  528. }
  529. if (MBB.isEHPad()) {
  530. OS << (HasAttributes ? ", " : " (");
  531. OS << "landing-pad";
  532. HasAttributes = true;
  533. }
  534. if (MBB.getAlignment()) {
  535. OS << (HasAttributes ? ", " : " (");
  536. OS << "align " << MBB.getAlignment();
  537. HasAttributes = true;
  538. }
  539. if (HasAttributes)
  540. OS << ")";
  541. OS << ":\n";
  542. bool HasLineAttributes = false;
  543. // Print the successors
  544. bool canPredictProbs = canPredictBranchProbabilities(MBB);
  545. // Even if the list of successors is empty, if we cannot guess it,
  546. // we need to print it to tell the parser that the list is empty.
  547. // This is needed, because MI model unreachable as empty blocks
  548. // with an empty successor list. If the parser would see that
  549. // without the successor list, it would guess the code would
  550. // fallthrough.
  551. if ((!MBB.succ_empty() && !SimplifyMIR) || !canPredictProbs ||
  552. !canPredictSuccessors(MBB)) {
  553. OS.indent(2) << "successors: ";
  554. for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) {
  555. if (I != MBB.succ_begin())
  556. OS << ", ";
  557. printMBBReference(**I);
  558. if (!SimplifyMIR || !canPredictProbs)
  559. OS << '('
  560. << format("0x%08" PRIx32, MBB.getSuccProbability(I).getNumerator())
  561. << ')';
  562. }
  563. OS << "\n";
  564. HasLineAttributes = true;
  565. }
  566. // Print the live in registers.
  567. const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
  568. if (MRI.tracksLiveness() && !MBB.livein_empty()) {
  569. const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
  570. OS.indent(2) << "liveins: ";
  571. bool First = true;
  572. for (const auto &LI : MBB.liveins()) {
  573. if (!First)
  574. OS << ", ";
  575. First = false;
  576. printReg(LI.PhysReg, OS, &TRI);
  577. if (!LI.LaneMask.all())
  578. OS << ":0x" << PrintLaneMask(LI.LaneMask);
  579. }
  580. OS << "\n";
  581. HasLineAttributes = true;
  582. }
  583. if (HasLineAttributes)
  584. OS << "\n";
  585. bool IsInBundle = false;
  586. for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) {
  587. const MachineInstr &MI = *I;
  588. if (IsInBundle && !MI.isInsideBundle()) {
  589. OS.indent(2) << "}\n";
  590. IsInBundle = false;
  591. }
  592. OS.indent(IsInBundle ? 4 : 2);
  593. print(MI);
  594. if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) {
  595. OS << " {";
  596. IsInBundle = true;
  597. }
  598. OS << "\n";
  599. }
  600. if (IsInBundle)
  601. OS.indent(2) << "}\n";
  602. }
  603. /// Return true when an instruction has tied register that can't be determined
  604. /// by the instruction's descriptor.
  605. static bool hasComplexRegisterTies(const MachineInstr &MI) {
  606. const MCInstrDesc &MCID = MI.getDesc();
  607. for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) {
  608. const auto &Operand = MI.getOperand(I);
  609. if (!Operand.isReg() || Operand.isDef())
  610. // Ignore the defined registers as MCID marks only the uses as tied.
  611. continue;
  612. int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO);
  613. int TiedIdx = Operand.isTied() ? int(MI.findTiedOperandIdx(I)) : -1;
  614. if (ExpectedTiedIdx != TiedIdx)
  615. return true;
  616. }
  617. return false;
  618. }
  619. static LLT getTypeToPrint(const MachineInstr &MI, unsigned OpIdx,
  620. SmallBitVector &PrintedTypes,
  621. const MachineRegisterInfo &MRI) {
  622. const MachineOperand &Op = MI.getOperand(OpIdx);
  623. if (!Op.isReg())
  624. return LLT{};
  625. if (MI.isVariadic() || OpIdx >= MI.getNumExplicitOperands())
  626. return MRI.getType(Op.getReg());
  627. auto &OpInfo = MI.getDesc().OpInfo[OpIdx];
  628. if (!OpInfo.isGenericType())
  629. return MRI.getType(Op.getReg());
  630. if (PrintedTypes[OpInfo.getGenericTypeIndex()])
  631. return LLT{};
  632. PrintedTypes.set(OpInfo.getGenericTypeIndex());
  633. return MRI.getType(Op.getReg());
  634. }
  635. void MIPrinter::print(const MachineInstr &MI) {
  636. const auto *MF = MI.getMF();
  637. const auto &MRI = MF->getRegInfo();
  638. const auto &SubTarget = MF->getSubtarget();
  639. const auto *TRI = SubTarget.getRegisterInfo();
  640. assert(TRI && "Expected target register info");
  641. const auto *TII = SubTarget.getInstrInfo();
  642. assert(TII && "Expected target instruction info");
  643. if (MI.isCFIInstruction())
  644. assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction");
  645. SmallBitVector PrintedTypes(8);
  646. bool ShouldPrintRegisterTies = hasComplexRegisterTies(MI);
  647. unsigned I = 0, E = MI.getNumOperands();
  648. for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() &&
  649. !MI.getOperand(I).isImplicit();
  650. ++I) {
  651. if (I)
  652. OS << ", ";
  653. print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies,
  654. getTypeToPrint(MI, I, PrintedTypes, MRI),
  655. /*IsDef=*/true);
  656. }
  657. if (I)
  658. OS << " = ";
  659. if (MI.getFlag(MachineInstr::FrameSetup))
  660. OS << "frame-setup ";
  661. OS << TII->getName(MI.getOpcode());
  662. if (I < E)
  663. OS << ' ';
  664. bool NeedComma = false;
  665. for (; I < E; ++I) {
  666. if (NeedComma)
  667. OS << ", ";
  668. print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies,
  669. getTypeToPrint(MI, I, PrintedTypes, MRI));
  670. NeedComma = true;
  671. }
  672. if (MI.getDebugLoc()) {
  673. if (NeedComma)
  674. OS << ',';
  675. OS << " debug-location ";
  676. MI.getDebugLoc()->printAsOperand(OS, MST);
  677. }
  678. if (!MI.memoperands_empty()) {
  679. OS << " :: ";
  680. const LLVMContext &Context = MF->getFunction()->getContext();
  681. bool NeedComma = false;
  682. for (const auto *Op : MI.memoperands()) {
  683. if (NeedComma)
  684. OS << ", ";
  685. print(Context, *TII, *Op);
  686. NeedComma = true;
  687. }
  688. }
  689. }
  690. void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) {
  691. OS << "%bb." << MBB.getNumber();
  692. if (const auto *BB = MBB.getBasicBlock()) {
  693. if (BB->hasName())
  694. OS << '.' << BB->getName();
  695. }
  696. }
  697. static void printIRSlotNumber(raw_ostream &OS, int Slot) {
  698. if (Slot == -1)
  699. OS << "<badref>";
  700. else
  701. OS << Slot;
  702. }
  703. void MIPrinter::printIRBlockReference(const BasicBlock &BB) {
  704. OS << "%ir-block.";
  705. if (BB.hasName()) {
  706. printLLVMNameWithoutPrefix(OS, BB.getName());
  707. return;
  708. }
  709. const Function *F = BB.getParent();
  710. int Slot;
  711. if (F == MST.getCurrentFunction()) {
  712. Slot = MST.getLocalSlot(&BB);
  713. } else {
  714. ModuleSlotTracker CustomMST(F->getParent(),
  715. /*ShouldInitializeAllMetadata=*/false);
  716. CustomMST.incorporateFunction(*F);
  717. Slot = CustomMST.getLocalSlot(&BB);
  718. }
  719. printIRSlotNumber(OS, Slot);
  720. }
  721. void MIPrinter::printIRValueReference(const Value &V) {
  722. if (isa<GlobalValue>(V)) {
  723. V.printAsOperand(OS, /*PrintType=*/false, MST);
  724. return;
  725. }
  726. if (isa<Constant>(V)) {
  727. // Machine memory operands can load/store to/from constant value pointers.
  728. OS << '`';
  729. V.printAsOperand(OS, /*PrintType=*/true, MST);
  730. OS << '`';
  731. return;
  732. }
  733. OS << "%ir.";
  734. if (V.hasName()) {
  735. printLLVMNameWithoutPrefix(OS, V.getName());
  736. return;
  737. }
  738. printIRSlotNumber(OS, MST.getLocalSlot(&V));
  739. }
  740. void MIPrinter::printStackObjectReference(int FrameIndex) {
  741. auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex);
  742. assert(ObjectInfo != StackObjectOperandMapping.end() &&
  743. "Invalid frame index");
  744. const FrameIndexOperand &Operand = ObjectInfo->second;
  745. if (Operand.IsFixed) {
  746. OS << "%fixed-stack." << Operand.ID;
  747. return;
  748. }
  749. OS << "%stack." << Operand.ID;
  750. if (!Operand.Name.empty())
  751. OS << '.' << Operand.Name;
  752. }
  753. void MIPrinter::printOffset(int64_t Offset) {
  754. if (Offset == 0)
  755. return;
  756. if (Offset < 0) {
  757. OS << " - " << -Offset;
  758. return;
  759. }
  760. OS << " + " << Offset;
  761. }
  762. static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
  763. auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
  764. for (const auto &I : Flags) {
  765. if (I.first == TF) {
  766. return I.second;
  767. }
  768. }
  769. return nullptr;
  770. }
  771. void MIPrinter::printTargetFlags(const MachineOperand &Op) {
  772. if (!Op.getTargetFlags())
  773. return;
  774. const auto *TII = Op.getParent()->getMF()->getSubtarget().getInstrInfo();
  775. assert(TII && "expected instruction info");
  776. auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
  777. OS << "target-flags(";
  778. const bool HasDirectFlags = Flags.first;
  779. const bool HasBitmaskFlags = Flags.second;
  780. if (!HasDirectFlags && !HasBitmaskFlags) {
  781. OS << "<unknown>) ";
  782. return;
  783. }
  784. if (HasDirectFlags) {
  785. if (const auto *Name = getTargetFlagName(TII, Flags.first))
  786. OS << Name;
  787. else
  788. OS << "<unknown target flag>";
  789. }
  790. if (!HasBitmaskFlags) {
  791. OS << ") ";
  792. return;
  793. }
  794. bool IsCommaNeeded = HasDirectFlags;
  795. unsigned BitMask = Flags.second;
  796. auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags();
  797. for (const auto &Mask : BitMasks) {
  798. // Check if the flag's bitmask has the bits of the current mask set.
  799. if ((BitMask & Mask.first) == Mask.first) {
  800. if (IsCommaNeeded)
  801. OS << ", ";
  802. IsCommaNeeded = true;
  803. OS << Mask.second;
  804. // Clear the bits which were serialized from the flag's bitmask.
  805. BitMask &= ~(Mask.first);
  806. }
  807. }
  808. if (BitMask) {
  809. // When the resulting flag's bitmask isn't zero, we know that we didn't
  810. // serialize all of the bit flags.
  811. if (IsCommaNeeded)
  812. OS << ", ";
  813. OS << "<unknown bitmask target flag>";
  814. }
  815. OS << ") ";
  816. }
  817. static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
  818. const auto *TII = MF.getSubtarget().getInstrInfo();
  819. assert(TII && "expected instruction info");
  820. auto Indices = TII->getSerializableTargetIndices();
  821. for (const auto &I : Indices) {
  822. if (I.first == Index) {
  823. return I.second;
  824. }
  825. }
  826. return nullptr;
  827. }
  828. void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI,
  829. unsigned I, bool ShouldPrintRegisterTies, LLT TypeToPrint,
  830. bool IsDef) {
  831. printTargetFlags(Op);
  832. switch (Op.getType()) {
  833. case MachineOperand::MO_Register:
  834. if (Op.isImplicit())
  835. OS << (Op.isDef() ? "implicit-def " : "implicit ");
  836. else if (!IsDef && Op.isDef())
  837. // Print the 'def' flag only when the operand is defined after '='.
  838. OS << "def ";
  839. if (Op.isInternalRead())
  840. OS << "internal ";
  841. if (Op.isDead())
  842. OS << "dead ";
  843. if (Op.isKill())
  844. OS << "killed ";
  845. if (Op.isUndef())
  846. OS << "undef ";
  847. if (Op.isEarlyClobber())
  848. OS << "early-clobber ";
  849. if (Op.isDebug())
  850. OS << "debug-use ";
  851. printReg(Op.getReg(), OS, TRI);
  852. // Print the sub register.
  853. if (Op.getSubReg() != 0)
  854. OS << '.' << TRI->getSubRegIndexName(Op.getSubReg());
  855. if (ShouldPrintRegisterTies && Op.isTied() && !Op.isDef())
  856. OS << "(tied-def " << Op.getParent()->findTiedOperandIdx(I) << ")";
  857. if (TypeToPrint.isValid())
  858. OS << '(' << TypeToPrint << ')';
  859. break;
  860. case MachineOperand::MO_Immediate:
  861. OS << Op.getImm();
  862. break;
  863. case MachineOperand::MO_CImmediate:
  864. Op.getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
  865. break;
  866. case MachineOperand::MO_FPImmediate:
  867. Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
  868. break;
  869. case MachineOperand::MO_MachineBasicBlock:
  870. printMBBReference(*Op.getMBB());
  871. break;
  872. case MachineOperand::MO_FrameIndex:
  873. printStackObjectReference(Op.getIndex());
  874. break;
  875. case MachineOperand::MO_ConstantPoolIndex:
  876. OS << "%const." << Op.getIndex();
  877. printOffset(Op.getOffset());
  878. break;
  879. case MachineOperand::MO_TargetIndex:
  880. OS << "target-index(";
  881. if (const auto *Name =
  882. getTargetIndexName(*Op.getParent()->getMF(), Op.getIndex()))
  883. OS << Name;
  884. else
  885. OS << "<unknown>";
  886. OS << ')';
  887. printOffset(Op.getOffset());
  888. break;
  889. case MachineOperand::MO_JumpTableIndex:
  890. OS << "%jump-table." << Op.getIndex();
  891. break;
  892. case MachineOperand::MO_ExternalSymbol: {
  893. StringRef Name = Op.getSymbolName();
  894. OS << '$';
  895. if (Name.empty()) {
  896. OS << "\"\"";
  897. } else {
  898. printLLVMNameWithoutPrefix(OS, Name);
  899. }
  900. printOffset(Op.getOffset());
  901. break;
  902. }
  903. case MachineOperand::MO_GlobalAddress:
  904. Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
  905. printOffset(Op.getOffset());
  906. break;
  907. case MachineOperand::MO_BlockAddress:
  908. OS << "blockaddress(";
  909. Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
  910. MST);
  911. OS << ", ";
  912. printIRBlockReference(*Op.getBlockAddress()->getBasicBlock());
  913. OS << ')';
  914. printOffset(Op.getOffset());
  915. break;
  916. case MachineOperand::MO_RegisterMask: {
  917. auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask());
  918. if (RegMaskInfo != RegisterMaskIds.end())
  919. OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower();
  920. else
  921. printCustomRegMask(Op.getRegMask(), OS, TRI);
  922. break;
  923. }
  924. case MachineOperand::MO_RegisterLiveOut: {
  925. const uint32_t *RegMask = Op.getRegLiveOut();
  926. OS << "liveout(";
  927. bool IsCommaNeeded = false;
  928. for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
  929. if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
  930. if (IsCommaNeeded)
  931. OS << ", ";
  932. printReg(Reg, OS, TRI);
  933. IsCommaNeeded = true;
  934. }
  935. }
  936. OS << ")";
  937. break;
  938. }
  939. case MachineOperand::MO_Metadata:
  940. Op.getMetadata()->printAsOperand(OS, MST);
  941. break;
  942. case MachineOperand::MO_MCSymbol:
  943. OS << "<mcsymbol " << *Op.getMCSymbol() << ">";
  944. break;
  945. case MachineOperand::MO_CFIIndex: {
  946. const MachineFunction &MF = *Op.getParent()->getMF();
  947. print(MF.getFrameInstructions()[Op.getCFIIndex()], TRI);
  948. break;
  949. }
  950. case MachineOperand::MO_IntrinsicID: {
  951. Intrinsic::ID ID = Op.getIntrinsicID();
  952. if (ID < Intrinsic::num_intrinsics)
  953. OS << "intrinsic(@" << Intrinsic::getName(ID, None) << ')';
  954. else {
  955. const MachineFunction &MF = *Op.getParent()->getMF();
  956. const TargetIntrinsicInfo *TII = MF.getTarget().getIntrinsicInfo();
  957. OS << "intrinsic(@" << TII->getName(ID) << ')';
  958. }
  959. break;
  960. }
  961. case MachineOperand::MO_Predicate: {
  962. auto Pred = static_cast<CmpInst::Predicate>(Op.getPredicate());
  963. OS << (CmpInst::isIntPredicate(Pred) ? "int" : "float") << "pred("
  964. << CmpInst::getPredicateName(Pred) << ')';
  965. break;
  966. }
  967. }
  968. }
  969. static const char *getTargetMMOFlagName(const TargetInstrInfo &TII,
  970. unsigned TMMOFlag) {
  971. auto Flags = TII.getSerializableMachineMemOperandTargetFlags();
  972. for (const auto &I : Flags) {
  973. if (I.first == TMMOFlag) {
  974. return I.second;
  975. }
  976. }
  977. return nullptr;
  978. }
  979. void MIPrinter::print(const LLVMContext &Context, const TargetInstrInfo &TII,
  980. const MachineMemOperand &Op) {
  981. OS << '(';
  982. if (Op.isVolatile())
  983. OS << "volatile ";
  984. if (Op.isNonTemporal())
  985. OS << "non-temporal ";
  986. if (Op.isDereferenceable())
  987. OS << "dereferenceable ";
  988. if (Op.isInvariant())
  989. OS << "invariant ";
  990. if (Op.getFlags() & MachineMemOperand::MOTargetFlag1)
  991. OS << '"' << getTargetMMOFlagName(TII, MachineMemOperand::MOTargetFlag1)
  992. << "\" ";
  993. if (Op.getFlags() & MachineMemOperand::MOTargetFlag2)
  994. OS << '"' << getTargetMMOFlagName(TII, MachineMemOperand::MOTargetFlag2)
  995. << "\" ";
  996. if (Op.getFlags() & MachineMemOperand::MOTargetFlag3)
  997. OS << '"' << getTargetMMOFlagName(TII, MachineMemOperand::MOTargetFlag3)
  998. << "\" ";
  999. if (Op.isLoad())
  1000. OS << "load ";
  1001. else {
  1002. assert(Op.isStore() && "Non load machine operand must be a store");
  1003. OS << "store ";
  1004. }
  1005. printSyncScope(Context, Op.getSyncScopeID());
  1006. if (Op.getOrdering() != AtomicOrdering::NotAtomic)
  1007. OS << toIRString(Op.getOrdering()) << ' ';
  1008. if (Op.getFailureOrdering() != AtomicOrdering::NotAtomic)
  1009. OS << toIRString(Op.getFailureOrdering()) << ' ';
  1010. OS << Op.getSize();
  1011. if (const Value *Val = Op.getValue()) {
  1012. OS << (Op.isLoad() ? " from " : " into ");
  1013. printIRValueReference(*Val);
  1014. } else if (const PseudoSourceValue *PVal = Op.getPseudoValue()) {
  1015. OS << (Op.isLoad() ? " from " : " into ");
  1016. assert(PVal && "Expected a pseudo source value");
  1017. switch (PVal->kind()) {
  1018. case PseudoSourceValue::Stack:
  1019. OS << "stack";
  1020. break;
  1021. case PseudoSourceValue::GOT:
  1022. OS << "got";
  1023. break;
  1024. case PseudoSourceValue::JumpTable:
  1025. OS << "jump-table";
  1026. break;
  1027. case PseudoSourceValue::ConstantPool:
  1028. OS << "constant-pool";
  1029. break;
  1030. case PseudoSourceValue::FixedStack:
  1031. printStackObjectReference(
  1032. cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex());
  1033. break;
  1034. case PseudoSourceValue::GlobalValueCallEntry:
  1035. OS << "call-entry ";
  1036. cast<GlobalValuePseudoSourceValue>(PVal)->getValue()->printAsOperand(
  1037. OS, /*PrintType=*/false, MST);
  1038. break;
  1039. case PseudoSourceValue::ExternalSymbolCallEntry:
  1040. OS << "call-entry $";
  1041. printLLVMNameWithoutPrefix(
  1042. OS, cast<ExternalSymbolPseudoSourceValue>(PVal)->getSymbol());
  1043. break;
  1044. case PseudoSourceValue::TargetCustom:
  1045. llvm_unreachable("TargetCustom pseudo source values are not supported");
  1046. break;
  1047. }
  1048. }
  1049. printOffset(Op.getOffset());
  1050. if (Op.getBaseAlignment() != Op.getSize())
  1051. OS << ", align " << Op.getBaseAlignment();
  1052. auto AAInfo = Op.getAAInfo();
  1053. if (AAInfo.TBAA) {
  1054. OS << ", !tbaa ";
  1055. AAInfo.TBAA->printAsOperand(OS, MST);
  1056. }
  1057. if (AAInfo.Scope) {
  1058. OS << ", !alias.scope ";
  1059. AAInfo.Scope->printAsOperand(OS, MST);
  1060. }
  1061. if (AAInfo.NoAlias) {
  1062. OS << ", !noalias ";
  1063. AAInfo.NoAlias->printAsOperand(OS, MST);
  1064. }
  1065. if (Op.getRanges()) {
  1066. OS << ", !range ";
  1067. Op.getRanges()->printAsOperand(OS, MST);
  1068. }
  1069. OS << ')';
  1070. }
  1071. void MIPrinter::printSyncScope(const LLVMContext &Context, SyncScope::ID SSID) {
  1072. switch (SSID) {
  1073. case SyncScope::System: {
  1074. break;
  1075. }
  1076. default: {
  1077. if (SSNs.empty())
  1078. Context.getSyncScopeNames(SSNs);
  1079. OS << "syncscope(\"";
  1080. PrintEscapedString(SSNs[SSID], OS);
  1081. OS << "\") ";
  1082. break;
  1083. }
  1084. }
  1085. }
  1086. static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
  1087. const TargetRegisterInfo *TRI) {
  1088. int Reg = TRI->getLLVMRegNum(DwarfReg, true);
  1089. if (Reg == -1) {
  1090. OS << "<badreg>";
  1091. return;
  1092. }
  1093. printReg(Reg, OS, TRI);
  1094. }
  1095. void MIPrinter::print(const MCCFIInstruction &CFI,
  1096. const TargetRegisterInfo *TRI) {
  1097. switch (CFI.getOperation()) {
  1098. case MCCFIInstruction::OpSameValue:
  1099. OS << "same_value ";
  1100. if (CFI.getLabel())
  1101. OS << "<mcsymbol> ";
  1102. printCFIRegister(CFI.getRegister(), OS, TRI);
  1103. break;
  1104. case MCCFIInstruction::OpOffset:
  1105. OS << "offset ";
  1106. if (CFI.getLabel())
  1107. OS << "<mcsymbol> ";
  1108. printCFIRegister(CFI.getRegister(), OS, TRI);
  1109. OS << ", " << CFI.getOffset();
  1110. break;
  1111. case MCCFIInstruction::OpDefCfaRegister:
  1112. OS << "def_cfa_register ";
  1113. if (CFI.getLabel())
  1114. OS << "<mcsymbol> ";
  1115. printCFIRegister(CFI.getRegister(), OS, TRI);
  1116. break;
  1117. case MCCFIInstruction::OpDefCfaOffset:
  1118. OS << "def_cfa_offset ";
  1119. if (CFI.getLabel())
  1120. OS << "<mcsymbol> ";
  1121. OS << CFI.getOffset();
  1122. break;
  1123. case MCCFIInstruction::OpDefCfa:
  1124. OS << "def_cfa ";
  1125. if (CFI.getLabel())
  1126. OS << "<mcsymbol> ";
  1127. printCFIRegister(CFI.getRegister(), OS, TRI);
  1128. OS << ", " << CFI.getOffset();
  1129. break;
  1130. default:
  1131. // TODO: Print the other CFI Operations.
  1132. OS << "<unserializable cfi operation>";
  1133. break;
  1134. }
  1135. }
  1136. void llvm::printMIR(raw_ostream &OS, const Module &M) {
  1137. yaml::Output Out(OS);
  1138. Out << const_cast<Module &>(M);
  1139. }
  1140. void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) {
  1141. MIRPrinter Printer(OS);
  1142. Printer.print(MF);
  1143. }