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