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