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