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