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