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 15 #include "MIRPrinter.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/CodeGen/MachineConstantPool.h" 18 #include "llvm/CodeGen/MachineFunction.h" 19 #include "llvm/CodeGen/MachineFrameInfo.h" 20 #include "llvm/CodeGen/MachineMemOperand.h" 21 #include "llvm/CodeGen/MachineModuleInfo.h" 22 #include "llvm/CodeGen/MachineRegisterInfo.h" 23 #include "llvm/CodeGen/MIRYamlMapping.h" 24 #include "llvm/IR/BasicBlock.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/IR/Instructions.h" 27 #include "llvm/IR/IRPrintingPasses.h" 28 #include "llvm/IR/Module.h" 29 #include "llvm/IR/ModuleSlotTracker.h" 30 #include "llvm/MC/MCSymbol.h" 31 #include "llvm/Support/Format.h" 32 #include "llvm/Support/MemoryBuffer.h" 33 #include "llvm/Support/raw_ostream.h" 34 #include "llvm/Support/YAMLTraits.h" 35 #include "llvm/Target/TargetInstrInfo.h" 36 #include "llvm/Target/TargetSubtargetInfo.h" 37 38 using namespace llvm; 39 40 namespace { 41 42 /// This structure describes how to print out stack object references. 43 struct FrameIndexOperand { 44 std::string Name; 45 unsigned ID; 46 bool IsFixed; 47 48 FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed) 49 : Name(Name.str()), ID(ID), IsFixed(IsFixed) {} 50 51 /// Return an ordinary stack object reference. 52 static FrameIndexOperand create(StringRef Name, unsigned ID) { 53 return FrameIndexOperand(Name, ID, /*IsFixed=*/false); 54 } 55 56 /// Return a fixed stack object reference. 57 static FrameIndexOperand createFixed(unsigned ID) { 58 return FrameIndexOperand("", ID, /*IsFixed=*/true); 59 } 60 }; 61 62 } // end anonymous namespace 63 64 namespace llvm { 65 66 /// This class prints out the machine functions using the MIR serialization 67 /// format. 68 class MIRPrinter { 69 raw_ostream &OS; 70 DenseMap<const uint32_t *, unsigned> RegisterMaskIds; 71 /// Maps from stack object indices to operand indices which will be used when 72 /// printing frame index machine operands. 73 DenseMap<int, FrameIndexOperand> StackObjectOperandMapping; 74 75 public: 76 MIRPrinter(raw_ostream &OS) : OS(OS) {} 77 78 void print(const MachineFunction &MF); 79 80 void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo, 81 const TargetRegisterInfo *TRI); 82 void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI, 83 const MachineFrameInfo &MFI); 84 void convert(yaml::MachineFunction &MF, 85 const MachineConstantPool &ConstantPool); 86 void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI, 87 const MachineJumpTableInfo &JTI); 88 void convertStackObjects(yaml::MachineFunction &MF, 89 const MachineFrameInfo &MFI, MachineModuleInfo &MMI, 90 ModuleSlotTracker &MST, 91 const TargetRegisterInfo *TRI); 92 93 private: 94 void initRegisterMaskIds(const MachineFunction &MF); 95 }; 96 97 /// This class prints out the machine instructions using the MIR serialization 98 /// format. 99 class MIPrinter { 100 raw_ostream &OS; 101 ModuleSlotTracker &MST; 102 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds; 103 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping; 104 105 public: 106 MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST, 107 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds, 108 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping) 109 : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds), 110 StackObjectOperandMapping(StackObjectOperandMapping) {} 111 112 void print(const MachineBasicBlock &MBB); 113 114 void print(const MachineInstr &MI); 115 void printMBBReference(const MachineBasicBlock &MBB); 116 void printIRBlockReference(const BasicBlock &BB); 117 void printIRValueReference(const Value &V); 118 void printStackObjectReference(int FrameIndex); 119 void printOffset(int64_t Offset); 120 void printTargetFlags(const MachineOperand &Op); 121 void print(const MachineOperand &Op, const TargetRegisterInfo *TRI, 122 unsigned I, bool ShouldPrintRegisterTies, bool IsDef = false); 123 void print(const MachineMemOperand &Op); 124 125 void print(const MCCFIInstruction &CFI, const TargetRegisterInfo *TRI); 126 }; 127 128 } // end namespace llvm 129 130 namespace llvm { 131 namespace yaml { 132 133 /// This struct serializes the LLVM IR module. 134 template <> struct BlockScalarTraits<Module> { 135 static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) { 136 Mod.print(OS, nullptr); 137 } 138 static StringRef input(StringRef Str, void *Ctxt, Module &Mod) { 139 llvm_unreachable("LLVM Module is supposed to be parsed separately"); 140 return ""; 141 } 142 }; 143 144 } // end namespace yaml 145 } // end namespace llvm 146 147 static void printReg(unsigned Reg, raw_ostream &OS, 148 const TargetRegisterInfo *TRI) { 149 // TODO: Print Stack Slots. 150 if (!Reg) 151 OS << '_'; 152 else if (TargetRegisterInfo::isVirtualRegister(Reg)) 153 OS << '%' << TargetRegisterInfo::virtReg2Index(Reg); 154 else if (Reg < TRI->getNumRegs()) 155 OS << '%' << StringRef(TRI->getName(Reg)).lower(); 156 else 157 llvm_unreachable("Can't print this kind of register yet"); 158 } 159 160 static void printReg(unsigned Reg, yaml::StringValue &Dest, 161 const TargetRegisterInfo *TRI) { 162 raw_string_ostream OS(Dest.Value); 163 printReg(Reg, OS, TRI); 164 } 165 166 void MIRPrinter::print(const MachineFunction &MF) { 167 initRegisterMaskIds(MF); 168 169 yaml::MachineFunction YamlMF; 170 YamlMF.Name = MF.getName(); 171 YamlMF.Alignment = MF.getAlignment(); 172 YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice(); 173 YamlMF.HasInlineAsm = MF.hasInlineAsm(); 174 convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo()); 175 ModuleSlotTracker MST(MF.getFunction()->getParent()); 176 MST.incorporateFunction(*MF.getFunction()); 177 convert(MST, YamlMF.FrameInfo, *MF.getFrameInfo()); 178 convertStackObjects(YamlMF, *MF.getFrameInfo(), MF.getMMI(), MST, 179 MF.getSubtarget().getRegisterInfo()); 180 if (const auto *ConstantPool = MF.getConstantPool()) 181 convert(YamlMF, *ConstantPool); 182 if (const auto *JumpTableInfo = MF.getJumpTableInfo()) 183 convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo); 184 raw_string_ostream StrOS(YamlMF.Body.Value.Value); 185 bool IsNewlineNeeded = false; 186 for (const auto &MBB : MF) { 187 if (IsNewlineNeeded) 188 StrOS << "\n"; 189 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping) 190 .print(MBB); 191 IsNewlineNeeded = true; 192 } 193 StrOS.flush(); 194 yaml::Output Out(OS); 195 Out << YamlMF; 196 } 197 198 void MIRPrinter::convert(yaml::MachineFunction &MF, 199 const MachineRegisterInfo &RegInfo, 200 const TargetRegisterInfo *TRI) { 201 MF.IsSSA = RegInfo.isSSA(); 202 MF.TracksRegLiveness = RegInfo.tracksLiveness(); 203 MF.TracksSubRegLiveness = RegInfo.subRegLivenessEnabled(); 204 205 // Print the virtual register definitions. 206 for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) { 207 unsigned Reg = TargetRegisterInfo::index2VirtReg(I); 208 yaml::VirtualRegisterDefinition VReg; 209 VReg.ID = I; 210 VReg.Class = 211 StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower(); 212 unsigned PreferredReg = RegInfo.getSimpleHint(Reg); 213 if (PreferredReg) 214 printReg(PreferredReg, VReg.PreferredRegister, TRI); 215 MF.VirtualRegisters.push_back(VReg); 216 } 217 218 // Print the live ins. 219 for (auto I = RegInfo.livein_begin(), E = RegInfo.livein_end(); I != E; ++I) { 220 yaml::MachineFunctionLiveIn LiveIn; 221 printReg(I->first, LiveIn.Register, TRI); 222 if (I->second) 223 printReg(I->second, LiveIn.VirtualRegister, TRI); 224 MF.LiveIns.push_back(LiveIn); 225 } 226 // The used physical register mask is printed as an inverted callee saved 227 // register mask. 228 const BitVector &UsedPhysRegMask = RegInfo.getUsedPhysRegsMask(); 229 if (UsedPhysRegMask.none()) 230 return; 231 std::vector<yaml::FlowStringValue> CalleeSavedRegisters; 232 for (unsigned I = 0, E = UsedPhysRegMask.size(); I != E; ++I) { 233 if (!UsedPhysRegMask[I]) { 234 yaml::FlowStringValue Reg; 235 printReg(I, Reg, TRI); 236 CalleeSavedRegisters.push_back(Reg); 237 } 238 } 239 MF.CalleeSavedRegisters = CalleeSavedRegisters; 240 } 241 242 void MIRPrinter::convert(ModuleSlotTracker &MST, 243 yaml::MachineFrameInfo &YamlMFI, 244 const MachineFrameInfo &MFI) { 245 YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken(); 246 YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken(); 247 YamlMFI.HasStackMap = MFI.hasStackMap(); 248 YamlMFI.HasPatchPoint = MFI.hasPatchPoint(); 249 YamlMFI.StackSize = MFI.getStackSize(); 250 YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment(); 251 YamlMFI.MaxAlignment = MFI.getMaxAlignment(); 252 YamlMFI.AdjustsStack = MFI.adjustsStack(); 253 YamlMFI.HasCalls = MFI.hasCalls(); 254 YamlMFI.MaxCallFrameSize = MFI.getMaxCallFrameSize(); 255 YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment(); 256 YamlMFI.HasVAStart = MFI.hasVAStart(); 257 YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc(); 258 if (MFI.getSavePoint()) { 259 raw_string_ostream StrOS(YamlMFI.SavePoint.Value); 260 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping) 261 .printMBBReference(*MFI.getSavePoint()); 262 } 263 if (MFI.getRestorePoint()) { 264 raw_string_ostream StrOS(YamlMFI.RestorePoint.Value); 265 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping) 266 .printMBBReference(*MFI.getRestorePoint()); 267 } 268 } 269 270 void MIRPrinter::convertStackObjects(yaml::MachineFunction &MF, 271 const MachineFrameInfo &MFI, 272 MachineModuleInfo &MMI, 273 ModuleSlotTracker &MST, 274 const TargetRegisterInfo *TRI) { 275 // Process fixed stack objects. 276 unsigned ID = 0; 277 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) { 278 if (MFI.isDeadObjectIndex(I)) 279 continue; 280 281 yaml::FixedMachineStackObject YamlObject; 282 YamlObject.ID = ID; 283 YamlObject.Type = MFI.isSpillSlotObjectIndex(I) 284 ? yaml::FixedMachineStackObject::SpillSlot 285 : yaml::FixedMachineStackObject::DefaultType; 286 YamlObject.Offset = MFI.getObjectOffset(I); 287 YamlObject.Size = MFI.getObjectSize(I); 288 YamlObject.Alignment = MFI.getObjectAlignment(I); 289 YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I); 290 YamlObject.IsAliased = MFI.isAliasedObjectIndex(I); 291 MF.FixedStackObjects.push_back(YamlObject); 292 StackObjectOperandMapping.insert( 293 std::make_pair(I, FrameIndexOperand::createFixed(ID++))); 294 } 295 296 // Process ordinary stack objects. 297 ID = 0; 298 for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I) { 299 if (MFI.isDeadObjectIndex(I)) 300 continue; 301 302 yaml::MachineStackObject YamlObject; 303 YamlObject.ID = ID; 304 if (const auto *Alloca = MFI.getObjectAllocation(I)) 305 YamlObject.Name.Value = 306 Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>"; 307 YamlObject.Type = MFI.isSpillSlotObjectIndex(I) 308 ? yaml::MachineStackObject::SpillSlot 309 : MFI.isVariableSizedObjectIndex(I) 310 ? yaml::MachineStackObject::VariableSized 311 : yaml::MachineStackObject::DefaultType; 312 YamlObject.Offset = MFI.getObjectOffset(I); 313 YamlObject.Size = MFI.getObjectSize(I); 314 YamlObject.Alignment = MFI.getObjectAlignment(I); 315 316 MF.StackObjects.push_back(YamlObject); 317 StackObjectOperandMapping.insert(std::make_pair( 318 I, FrameIndexOperand::create(YamlObject.Name.Value, ID++))); 319 } 320 321 for (const auto &CSInfo : MFI.getCalleeSavedInfo()) { 322 yaml::StringValue Reg; 323 printReg(CSInfo.getReg(), Reg, TRI); 324 auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx()); 325 assert(StackObjectInfo != StackObjectOperandMapping.end() && 326 "Invalid stack object index"); 327 const FrameIndexOperand &StackObject = StackObjectInfo->second; 328 if (StackObject.IsFixed) 329 MF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg; 330 else 331 MF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg; 332 } 333 for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) { 334 auto LocalObject = MFI.getLocalFrameObjectMap(I); 335 auto StackObjectInfo = StackObjectOperandMapping.find(LocalObject.first); 336 assert(StackObjectInfo != StackObjectOperandMapping.end() && 337 "Invalid stack object index"); 338 const FrameIndexOperand &StackObject = StackObjectInfo->second; 339 assert(!StackObject.IsFixed && "Expected a locally mapped stack object"); 340 MF.StackObjects[StackObject.ID].LocalOffset = LocalObject.second; 341 } 342 343 // Print the stack object references in the frame information class after 344 // converting the stack objects. 345 if (MFI.hasStackProtectorIndex()) { 346 raw_string_ostream StrOS(MF.FrameInfo.StackProtector.Value); 347 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping) 348 .printStackObjectReference(MFI.getStackProtectorIndex()); 349 } 350 351 // Print the debug variable information. 352 for (MachineModuleInfo::VariableDbgInfo &DebugVar : 353 MMI.getVariableDbgInfo()) { 354 auto StackObjectInfo = StackObjectOperandMapping.find(DebugVar.Slot); 355 assert(StackObjectInfo != StackObjectOperandMapping.end() && 356 "Invalid stack object index"); 357 const FrameIndexOperand &StackObject = StackObjectInfo->second; 358 assert(!StackObject.IsFixed && "Expected a non-fixed stack object"); 359 auto &Object = MF.StackObjects[StackObject.ID]; 360 { 361 raw_string_ostream StrOS(Object.DebugVar.Value); 362 DebugVar.Var->printAsOperand(StrOS, MST); 363 } 364 { 365 raw_string_ostream StrOS(Object.DebugExpr.Value); 366 DebugVar.Expr->printAsOperand(StrOS, MST); 367 } 368 { 369 raw_string_ostream StrOS(Object.DebugLoc.Value); 370 DebugVar.Loc->printAsOperand(StrOS, MST); 371 } 372 } 373 } 374 375 void MIRPrinter::convert(yaml::MachineFunction &MF, 376 const MachineConstantPool &ConstantPool) { 377 unsigned ID = 0; 378 for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) { 379 // TODO: Serialize target specific constant pool entries. 380 if (Constant.isMachineConstantPoolEntry()) 381 llvm_unreachable("Can't print target specific constant pool entries yet"); 382 383 yaml::MachineConstantPoolValue YamlConstant; 384 std::string Str; 385 raw_string_ostream StrOS(Str); 386 Constant.Val.ConstVal->printAsOperand(StrOS); 387 YamlConstant.ID = ID++; 388 YamlConstant.Value = StrOS.str(); 389 YamlConstant.Alignment = Constant.getAlignment(); 390 MF.Constants.push_back(YamlConstant); 391 } 392 } 393 394 void MIRPrinter::convert(ModuleSlotTracker &MST, 395 yaml::MachineJumpTable &YamlJTI, 396 const MachineJumpTableInfo &JTI) { 397 YamlJTI.Kind = JTI.getEntryKind(); 398 unsigned ID = 0; 399 for (const auto &Table : JTI.getJumpTables()) { 400 std::string Str; 401 yaml::MachineJumpTable::Entry Entry; 402 Entry.ID = ID++; 403 for (const auto *MBB : Table.MBBs) { 404 raw_string_ostream StrOS(Str); 405 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping) 406 .printMBBReference(*MBB); 407 Entry.Blocks.push_back(StrOS.str()); 408 Str.clear(); 409 } 410 YamlJTI.Entries.push_back(Entry); 411 } 412 } 413 414 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) { 415 const auto *TRI = MF.getSubtarget().getRegisterInfo(); 416 unsigned I = 0; 417 for (const uint32_t *Mask : TRI->getRegMasks()) 418 RegisterMaskIds.insert(std::make_pair(Mask, I++)); 419 } 420 421 void MIPrinter::print(const MachineBasicBlock &MBB) { 422 assert(MBB.getNumber() >= 0 && "Invalid MBB number"); 423 OS << "bb." << MBB.getNumber(); 424 bool HasAttributes = false; 425 if (const auto *BB = MBB.getBasicBlock()) { 426 if (BB->hasName()) { 427 OS << "." << BB->getName(); 428 } else { 429 HasAttributes = true; 430 OS << " ("; 431 int Slot = MST.getLocalSlot(BB); 432 if (Slot == -1) 433 OS << "<ir-block badref>"; 434 else 435 OS << (Twine("%ir-block.") + Twine(Slot)).str(); 436 } 437 } 438 if (MBB.hasAddressTaken()) { 439 OS << (HasAttributes ? ", " : " ("); 440 OS << "address-taken"; 441 HasAttributes = true; 442 } 443 if (MBB.isEHPad()) { 444 OS << (HasAttributes ? ", " : " ("); 445 OS << "landing-pad"; 446 HasAttributes = true; 447 } 448 if (MBB.getAlignment()) { 449 OS << (HasAttributes ? ", " : " ("); 450 OS << "align " << MBB.getAlignment(); 451 HasAttributes = true; 452 } 453 if (HasAttributes) 454 OS << ")"; 455 OS << ":\n"; 456 457 bool HasLineAttributes = false; 458 // Print the successors 459 if (!MBB.succ_empty()) { 460 OS.indent(2) << "successors: "; 461 for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) { 462 if (I != MBB.succ_begin()) 463 OS << ", "; 464 printMBBReference(**I); 465 if (MBB.hasSuccessorWeights()) 466 OS << '(' << MBB.getSuccWeight(I) << ')'; 467 } 468 OS << "\n"; 469 HasLineAttributes = true; 470 } 471 472 // Print the live in registers. 473 const auto *TRI = MBB.getParent()->getSubtarget().getRegisterInfo(); 474 assert(TRI && "Expected target register info"); 475 if (!MBB.livein_empty()) { 476 OS.indent(2) << "liveins: "; 477 bool First = true; 478 for (const auto &LI : MBB.liveins()) { 479 if (!First) 480 OS << ", "; 481 First = false; 482 printReg(LI.PhysReg, OS, TRI); 483 if (LI.LaneMask != ~0u) 484 OS << format(":%08X", LI.LaneMask); 485 } 486 OS << "\n"; 487 HasLineAttributes = true; 488 } 489 490 if (HasLineAttributes) 491 OS << "\n"; 492 bool IsInBundle = false; 493 for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) { 494 const MachineInstr &MI = *I; 495 if (IsInBundle && !MI.isInsideBundle()) { 496 OS.indent(2) << "}\n"; 497 IsInBundle = false; 498 } 499 OS.indent(IsInBundle ? 4 : 2); 500 print(MI); 501 if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) { 502 OS << " {"; 503 IsInBundle = true; 504 } 505 OS << "\n"; 506 } 507 if (IsInBundle) 508 OS.indent(2) << "}\n"; 509 } 510 511 /// Return true when an instruction has tied register that can't be determined 512 /// by the instruction's descriptor. 513 static bool hasComplexRegisterTies(const MachineInstr &MI) { 514 const MCInstrDesc &MCID = MI.getDesc(); 515 for (unsigned I = 0, E = MI.getNumOperands(); I < E; ++I) { 516 const auto &Operand = MI.getOperand(I); 517 if (!Operand.isReg() || Operand.isDef()) 518 // Ignore the defined registers as MCID marks only the uses as tied. 519 continue; 520 int ExpectedTiedIdx = MCID.getOperandConstraint(I, MCOI::TIED_TO); 521 int TiedIdx = Operand.isTied() ? int(MI.findTiedOperandIdx(I)) : -1; 522 if (ExpectedTiedIdx != TiedIdx) 523 return true; 524 } 525 return false; 526 } 527 528 void MIPrinter::print(const MachineInstr &MI) { 529 const auto &SubTarget = MI.getParent()->getParent()->getSubtarget(); 530 const auto *TRI = SubTarget.getRegisterInfo(); 531 assert(TRI && "Expected target register info"); 532 const auto *TII = SubTarget.getInstrInfo(); 533 assert(TII && "Expected target instruction info"); 534 if (MI.isCFIInstruction()) 535 assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction"); 536 537 bool ShouldPrintRegisterTies = hasComplexRegisterTies(MI); 538 unsigned I = 0, E = MI.getNumOperands(); 539 for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() && 540 !MI.getOperand(I).isImplicit(); 541 ++I) { 542 if (I) 543 OS << ", "; 544 print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies, /*IsDef=*/true); 545 } 546 547 if (I) 548 OS << " = "; 549 if (MI.getFlag(MachineInstr::FrameSetup)) 550 OS << "frame-setup "; 551 OS << TII->getName(MI.getOpcode()); 552 if (I < E) 553 OS << ' '; 554 555 bool NeedComma = false; 556 for (; I < E; ++I) { 557 if (NeedComma) 558 OS << ", "; 559 print(MI.getOperand(I), TRI, I, ShouldPrintRegisterTies); 560 NeedComma = true; 561 } 562 563 if (MI.getDebugLoc()) { 564 if (NeedComma) 565 OS << ','; 566 OS << " debug-location "; 567 MI.getDebugLoc()->printAsOperand(OS, MST); 568 } 569 570 if (!MI.memoperands_empty()) { 571 OS << " :: "; 572 bool NeedComma = false; 573 for (const auto *Op : MI.memoperands()) { 574 if (NeedComma) 575 OS << ", "; 576 print(*Op); 577 NeedComma = true; 578 } 579 } 580 } 581 582 void MIPrinter::printMBBReference(const MachineBasicBlock &MBB) { 583 OS << "%bb." << MBB.getNumber(); 584 if (const auto *BB = MBB.getBasicBlock()) { 585 if (BB->hasName()) 586 OS << '.' << BB->getName(); 587 } 588 } 589 590 static void printIRSlotNumber(raw_ostream &OS, int Slot) { 591 if (Slot == -1) 592 OS << "<badref>"; 593 else 594 OS << Slot; 595 } 596 597 void MIPrinter::printIRBlockReference(const BasicBlock &BB) { 598 OS << "%ir-block."; 599 if (BB.hasName()) { 600 printLLVMNameWithoutPrefix(OS, BB.getName()); 601 return; 602 } 603 const Function *F = BB.getParent(); 604 int Slot; 605 if (F == MST.getCurrentFunction()) { 606 Slot = MST.getLocalSlot(&BB); 607 } else { 608 ModuleSlotTracker CustomMST(F->getParent(), 609 /*ShouldInitializeAllMetadata=*/false); 610 CustomMST.incorporateFunction(*F); 611 Slot = CustomMST.getLocalSlot(&BB); 612 } 613 printIRSlotNumber(OS, Slot); 614 } 615 616 void MIPrinter::printIRValueReference(const Value &V) { 617 if (isa<GlobalValue>(V)) { 618 V.printAsOperand(OS, /*PrintType=*/false, MST); 619 return; 620 } 621 if (isa<Constant>(V)) { 622 // Machine memory operands can load/store to/from constant value pointers. 623 OS << '`'; 624 V.printAsOperand(OS, /*PrintType=*/true, MST); 625 OS << '`'; 626 return; 627 } 628 OS << "%ir."; 629 if (V.hasName()) { 630 printLLVMNameWithoutPrefix(OS, V.getName()); 631 return; 632 } 633 printIRSlotNumber(OS, MST.getLocalSlot(&V)); 634 } 635 636 void MIPrinter::printStackObjectReference(int FrameIndex) { 637 auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex); 638 assert(ObjectInfo != StackObjectOperandMapping.end() && 639 "Invalid frame index"); 640 const FrameIndexOperand &Operand = ObjectInfo->second; 641 if (Operand.IsFixed) { 642 OS << "%fixed-stack." << Operand.ID; 643 return; 644 } 645 OS << "%stack." << Operand.ID; 646 if (!Operand.Name.empty()) 647 OS << '.' << Operand.Name; 648 } 649 650 void MIPrinter::printOffset(int64_t Offset) { 651 if (Offset == 0) 652 return; 653 if (Offset < 0) { 654 OS << " - " << -Offset; 655 return; 656 } 657 OS << " + " << Offset; 658 } 659 660 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) { 661 auto Flags = TII->getSerializableDirectMachineOperandTargetFlags(); 662 for (const auto &I : Flags) { 663 if (I.first == TF) { 664 return I.second; 665 } 666 } 667 return nullptr; 668 } 669 670 void MIPrinter::printTargetFlags(const MachineOperand &Op) { 671 if (!Op.getTargetFlags()) 672 return; 673 const auto *TII = 674 Op.getParent()->getParent()->getParent()->getSubtarget().getInstrInfo(); 675 assert(TII && "expected instruction info"); 676 auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags()); 677 OS << "target-flags("; 678 const bool HasDirectFlags = Flags.first; 679 const bool HasBitmaskFlags = Flags.second; 680 if (!HasDirectFlags && !HasBitmaskFlags) { 681 OS << "<unknown>) "; 682 return; 683 } 684 if (HasDirectFlags) { 685 if (const auto *Name = getTargetFlagName(TII, Flags.first)) 686 OS << Name; 687 else 688 OS << "<unknown target flag>"; 689 } 690 if (!HasBitmaskFlags) { 691 OS << ") "; 692 return; 693 } 694 bool IsCommaNeeded = HasDirectFlags; 695 unsigned BitMask = Flags.second; 696 auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags(); 697 for (const auto &Mask : BitMasks) { 698 // Check if the flag's bitmask has the bits of the current mask set. 699 if ((BitMask & Mask.first) == Mask.first) { 700 if (IsCommaNeeded) 701 OS << ", "; 702 IsCommaNeeded = true; 703 OS << Mask.second; 704 // Clear the bits which were serialized from the flag's bitmask. 705 BitMask &= ~(Mask.first); 706 } 707 } 708 if (BitMask) { 709 // When the resulting flag's bitmask isn't zero, we know that we didn't 710 // serialize all of the bit flags. 711 if (IsCommaNeeded) 712 OS << ", "; 713 OS << "<unknown bitmask target flag>"; 714 } 715 OS << ") "; 716 } 717 718 static const char *getTargetIndexName(const MachineFunction &MF, int Index) { 719 const auto *TII = MF.getSubtarget().getInstrInfo(); 720 assert(TII && "expected instruction info"); 721 auto Indices = TII->getSerializableTargetIndices(); 722 for (const auto &I : Indices) { 723 if (I.first == Index) { 724 return I.second; 725 } 726 } 727 return nullptr; 728 } 729 730 void MIPrinter::print(const MachineOperand &Op, const TargetRegisterInfo *TRI, 731 unsigned I, bool ShouldPrintRegisterTies, bool IsDef) { 732 printTargetFlags(Op); 733 switch (Op.getType()) { 734 case MachineOperand::MO_Register: 735 if (Op.isImplicit()) 736 OS << (Op.isDef() ? "implicit-def " : "implicit "); 737 else if (!IsDef && Op.isDef()) 738 // Print the 'def' flag only when the operand is defined after '='. 739 OS << "def "; 740 if (Op.isInternalRead()) 741 OS << "internal "; 742 if (Op.isDead()) 743 OS << "dead "; 744 if (Op.isKill()) 745 OS << "killed "; 746 if (Op.isUndef()) 747 OS << "undef "; 748 if (Op.isEarlyClobber()) 749 OS << "early-clobber "; 750 if (Op.isDebug()) 751 OS << "debug-use "; 752 printReg(Op.getReg(), OS, TRI); 753 // Print the sub register. 754 if (Op.getSubReg() != 0) 755 OS << ':' << TRI->getSubRegIndexName(Op.getSubReg()); 756 if (ShouldPrintRegisterTies && Op.isTied() && !Op.isDef()) 757 OS << "(tied-def " << Op.getParent()->findTiedOperandIdx(I) << ")"; 758 break; 759 case MachineOperand::MO_Immediate: 760 OS << Op.getImm(); 761 break; 762 case MachineOperand::MO_CImmediate: 763 Op.getCImm()->printAsOperand(OS, /*PrintType=*/true, MST); 764 break; 765 case MachineOperand::MO_FPImmediate: 766 Op.getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST); 767 break; 768 case MachineOperand::MO_MachineBasicBlock: 769 printMBBReference(*Op.getMBB()); 770 break; 771 case MachineOperand::MO_FrameIndex: 772 printStackObjectReference(Op.getIndex()); 773 break; 774 case MachineOperand::MO_ConstantPoolIndex: 775 OS << "%const." << Op.getIndex(); 776 printOffset(Op.getOffset()); 777 break; 778 case MachineOperand::MO_TargetIndex: { 779 OS << "target-index("; 780 if (const auto *Name = getTargetIndexName( 781 *Op.getParent()->getParent()->getParent(), Op.getIndex())) 782 OS << Name; 783 else 784 OS << "<unknown>"; 785 OS << ')'; 786 printOffset(Op.getOffset()); 787 break; 788 } 789 case MachineOperand::MO_JumpTableIndex: 790 OS << "%jump-table." << Op.getIndex(); 791 break; 792 case MachineOperand::MO_ExternalSymbol: 793 OS << '$'; 794 printLLVMNameWithoutPrefix(OS, Op.getSymbolName()); 795 printOffset(Op.getOffset()); 796 break; 797 case MachineOperand::MO_GlobalAddress: 798 Op.getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST); 799 printOffset(Op.getOffset()); 800 break; 801 case MachineOperand::MO_BlockAddress: 802 OS << "blockaddress("; 803 Op.getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false, 804 MST); 805 OS << ", "; 806 printIRBlockReference(*Op.getBlockAddress()->getBasicBlock()); 807 OS << ')'; 808 printOffset(Op.getOffset()); 809 break; 810 case MachineOperand::MO_RegisterMask: { 811 auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask()); 812 if (RegMaskInfo != RegisterMaskIds.end()) 813 OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower(); 814 else 815 llvm_unreachable("Can't print this machine register mask yet."); 816 break; 817 } 818 case MachineOperand::MO_RegisterLiveOut: { 819 const uint32_t *RegMask = Op.getRegLiveOut(); 820 OS << "liveout("; 821 bool IsCommaNeeded = false; 822 for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) { 823 if (RegMask[Reg / 32] & (1U << (Reg % 32))) { 824 if (IsCommaNeeded) 825 OS << ", "; 826 printReg(Reg, OS, TRI); 827 IsCommaNeeded = true; 828 } 829 } 830 OS << ")"; 831 break; 832 } 833 case MachineOperand::MO_Metadata: 834 Op.getMetadata()->printAsOperand(OS, MST); 835 break; 836 case MachineOperand::MO_MCSymbol: 837 OS << "<mcsymbol " << *Op.getMCSymbol() << ">"; 838 break; 839 case MachineOperand::MO_CFIIndex: { 840 const auto &MMI = Op.getParent()->getParent()->getParent()->getMMI(); 841 print(MMI.getFrameInstructions()[Op.getCFIIndex()], TRI); 842 break; 843 } 844 } 845 } 846 847 void MIPrinter::print(const MachineMemOperand &Op) { 848 OS << '('; 849 // TODO: Print operand's target specific flags. 850 if (Op.isVolatile()) 851 OS << "volatile "; 852 if (Op.isNonTemporal()) 853 OS << "non-temporal "; 854 if (Op.isInvariant()) 855 OS << "invariant "; 856 if (Op.isLoad()) 857 OS << "load "; 858 else { 859 assert(Op.isStore() && "Non load machine operand must be a store"); 860 OS << "store "; 861 } 862 OS << Op.getSize() << (Op.isLoad() ? " from " : " into "); 863 if (const Value *Val = Op.getValue()) { 864 printIRValueReference(*Val); 865 } else { 866 const PseudoSourceValue *PVal = Op.getPseudoValue(); 867 assert(PVal && "Expected a pseudo source value"); 868 switch (PVal->kind()) { 869 case PseudoSourceValue::Stack: 870 OS << "stack"; 871 break; 872 case PseudoSourceValue::GOT: 873 OS << "got"; 874 break; 875 case PseudoSourceValue::JumpTable: 876 OS << "jump-table"; 877 break; 878 case PseudoSourceValue::ConstantPool: 879 OS << "constant-pool"; 880 break; 881 case PseudoSourceValue::FixedStack: 882 printStackObjectReference( 883 cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex()); 884 break; 885 case PseudoSourceValue::GlobalValueCallEntry: 886 OS << "call-entry "; 887 cast<GlobalValuePseudoSourceValue>(PVal)->getValue()->printAsOperand( 888 OS, /*PrintType=*/false, MST); 889 break; 890 case PseudoSourceValue::ExternalSymbolCallEntry: 891 OS << "call-entry $"; 892 printLLVMNameWithoutPrefix( 893 OS, cast<ExternalSymbolPseudoSourceValue>(PVal)->getSymbol()); 894 break; 895 } 896 } 897 printOffset(Op.getOffset()); 898 if (Op.getBaseAlignment() != Op.getSize()) 899 OS << ", align " << Op.getBaseAlignment(); 900 auto AAInfo = Op.getAAInfo(); 901 if (AAInfo.TBAA) { 902 OS << ", !tbaa "; 903 AAInfo.TBAA->printAsOperand(OS, MST); 904 } 905 if (AAInfo.Scope) { 906 OS << ", !alias.scope "; 907 AAInfo.Scope->printAsOperand(OS, MST); 908 } 909 if (AAInfo.NoAlias) { 910 OS << ", !noalias "; 911 AAInfo.NoAlias->printAsOperand(OS, MST); 912 } 913 if (Op.getRanges()) { 914 OS << ", !range "; 915 Op.getRanges()->printAsOperand(OS, MST); 916 } 917 OS << ')'; 918 } 919 920 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS, 921 const TargetRegisterInfo *TRI) { 922 int Reg = TRI->getLLVMRegNum(DwarfReg, true); 923 if (Reg == -1) { 924 OS << "<badreg>"; 925 return; 926 } 927 printReg(Reg, OS, TRI); 928 } 929 930 void MIPrinter::print(const MCCFIInstruction &CFI, 931 const TargetRegisterInfo *TRI) { 932 switch (CFI.getOperation()) { 933 case MCCFIInstruction::OpSameValue: 934 OS << ".cfi_same_value "; 935 if (CFI.getLabel()) 936 OS << "<mcsymbol> "; 937 printCFIRegister(CFI.getRegister(), OS, TRI); 938 break; 939 case MCCFIInstruction::OpOffset: 940 OS << ".cfi_offset "; 941 if (CFI.getLabel()) 942 OS << "<mcsymbol> "; 943 printCFIRegister(CFI.getRegister(), OS, TRI); 944 OS << ", " << CFI.getOffset(); 945 break; 946 case MCCFIInstruction::OpDefCfaRegister: 947 OS << ".cfi_def_cfa_register "; 948 if (CFI.getLabel()) 949 OS << "<mcsymbol> "; 950 printCFIRegister(CFI.getRegister(), OS, TRI); 951 break; 952 case MCCFIInstruction::OpDefCfaOffset: 953 OS << ".cfi_def_cfa_offset "; 954 if (CFI.getLabel()) 955 OS << "<mcsymbol> "; 956 OS << CFI.getOffset(); 957 break; 958 case MCCFIInstruction::OpDefCfa: 959 OS << ".cfi_def_cfa "; 960 if (CFI.getLabel()) 961 OS << "<mcsymbol> "; 962 printCFIRegister(CFI.getRegister(), OS, TRI); 963 OS << ", " << CFI.getOffset(); 964 break; 965 default: 966 // TODO: Print the other CFI Operations. 967 OS << "<unserializable cfi operation>"; 968 break; 969 } 970 } 971 972 void llvm::printMIR(raw_ostream &OS, const Module &M) { 973 yaml::Output Out(OS); 974 Out << const_cast<Module &>(M); 975 } 976 977 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) { 978 MIRPrinter Printer(OS); 979 Printer.print(MF); 980 } 981