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