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