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