1 //===- MIRPrinter.cpp - MIR serialization format printer ------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the class that prints out the LLVM IR and machine 10 // functions using the MIR serialization format. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/MIRPrinter.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/None.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SmallBitVector.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/CodeGen/GlobalISel/RegisterBank.h" 24 #include "llvm/CodeGen/MIRYamlMapping.h" 25 #include "llvm/CodeGen/MachineBasicBlock.h" 26 #include "llvm/CodeGen/MachineConstantPool.h" 27 #include "llvm/CodeGen/MachineFrameInfo.h" 28 #include "llvm/CodeGen/MachineFunction.h" 29 #include "llvm/CodeGen/MachineInstr.h" 30 #include "llvm/CodeGen/MachineJumpTableInfo.h" 31 #include "llvm/CodeGen/MachineMemOperand.h" 32 #include "llvm/CodeGen/MachineOperand.h" 33 #include "llvm/CodeGen/MachineRegisterInfo.h" 34 #include "llvm/CodeGen/PseudoSourceValue.h" 35 #include "llvm/CodeGen/TargetInstrInfo.h" 36 #include "llvm/CodeGen/TargetRegisterInfo.h" 37 #include "llvm/CodeGen/TargetSubtargetInfo.h" 38 #include "llvm/CodeGen/TargetFrameLowering.h" 39 #include "llvm/IR/BasicBlock.h" 40 #include "llvm/IR/Constants.h" 41 #include "llvm/IR/DebugInfo.h" 42 #include "llvm/IR/DebugLoc.h" 43 #include "llvm/IR/Function.h" 44 #include "llvm/IR/GlobalValue.h" 45 #include "llvm/IR/IRPrintingPasses.h" 46 #include "llvm/IR/InstrTypes.h" 47 #include "llvm/IR/Instructions.h" 48 #include "llvm/IR/Intrinsics.h" 49 #include "llvm/IR/Module.h" 50 #include "llvm/IR/ModuleSlotTracker.h" 51 #include "llvm/IR/Value.h" 52 #include "llvm/MC/LaneBitmask.h" 53 #include "llvm/MC/MCContext.h" 54 #include "llvm/MC/MCDwarf.h" 55 #include "llvm/MC/MCSymbol.h" 56 #include "llvm/Support/AtomicOrdering.h" 57 #include "llvm/Support/BranchProbability.h" 58 #include "llvm/Support/Casting.h" 59 #include "llvm/Support/CommandLine.h" 60 #include "llvm/Support/ErrorHandling.h" 61 #include "llvm/Support/Format.h" 62 #include "llvm/Support/LowLevelTypeImpl.h" 63 #include "llvm/Support/YAMLTraits.h" 64 #include "llvm/Support/raw_ostream.h" 65 #include "llvm/Target/TargetIntrinsicInfo.h" 66 #include "llvm/Target/TargetMachine.h" 67 #include <algorithm> 68 #include <cassert> 69 #include <cinttypes> 70 #include <cstdint> 71 #include <iterator> 72 #include <string> 73 #include <utility> 74 #include <vector> 75 76 using namespace llvm; 77 78 static cl::opt<bool> SimplifyMIR( 79 "simplify-mir", cl::Hidden, 80 cl::desc("Leave out unnecessary information when printing MIR")); 81 82 namespace { 83 84 /// This structure describes how to print out stack object references. 85 struct FrameIndexOperand { 86 std::string Name; 87 unsigned ID; 88 bool IsFixed; 89 90 FrameIndexOperand(StringRef Name, unsigned ID, bool IsFixed) 91 : Name(Name.str()), ID(ID), IsFixed(IsFixed) {} 92 93 /// Return an ordinary stack object reference. 94 static FrameIndexOperand create(StringRef Name, unsigned ID) { 95 return FrameIndexOperand(Name, ID, /*IsFixed=*/false); 96 } 97 98 /// Return a fixed stack object reference. 99 static FrameIndexOperand createFixed(unsigned ID) { 100 return FrameIndexOperand("", ID, /*IsFixed=*/true); 101 } 102 }; 103 104 } // end anonymous namespace 105 106 namespace llvm { 107 108 /// This class prints out the machine functions using the MIR serialization 109 /// format. 110 class MIRPrinter { 111 raw_ostream &OS; 112 DenseMap<const uint32_t *, unsigned> RegisterMaskIds; 113 /// Maps from stack object indices to operand indices which will be used when 114 /// printing frame index machine operands. 115 DenseMap<int, FrameIndexOperand> StackObjectOperandMapping; 116 117 public: 118 MIRPrinter(raw_ostream &OS) : OS(OS) {} 119 120 void print(const MachineFunction &MF); 121 122 void convert(yaml::MachineFunction &MF, const MachineRegisterInfo &RegInfo, 123 const TargetRegisterInfo *TRI); 124 void convert(ModuleSlotTracker &MST, yaml::MachineFrameInfo &YamlMFI, 125 const MachineFrameInfo &MFI); 126 void convert(yaml::MachineFunction &MF, 127 const MachineConstantPool &ConstantPool); 128 void convert(ModuleSlotTracker &MST, yaml::MachineJumpTable &YamlJTI, 129 const MachineJumpTableInfo &JTI); 130 void convertStackObjects(yaml::MachineFunction &YMF, 131 const MachineFunction &MF, ModuleSlotTracker &MST); 132 void convertCallSiteObjects(yaml::MachineFunction &YMF, 133 const MachineFunction &MF, 134 ModuleSlotTracker &MST); 135 136 private: 137 void initRegisterMaskIds(const MachineFunction &MF); 138 }; 139 140 /// This class prints out the machine instructions using the MIR serialization 141 /// format. 142 class MIPrinter { 143 raw_ostream &OS; 144 ModuleSlotTracker &MST; 145 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds; 146 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping; 147 /// Synchronization scope names registered with LLVMContext. 148 SmallVector<StringRef, 8> SSNs; 149 150 bool canPredictBranchProbabilities(const MachineBasicBlock &MBB) const; 151 bool canPredictSuccessors(const MachineBasicBlock &MBB) const; 152 153 public: 154 MIPrinter(raw_ostream &OS, ModuleSlotTracker &MST, 155 const DenseMap<const uint32_t *, unsigned> &RegisterMaskIds, 156 const DenseMap<int, FrameIndexOperand> &StackObjectOperandMapping) 157 : OS(OS), MST(MST), RegisterMaskIds(RegisterMaskIds), 158 StackObjectOperandMapping(StackObjectOperandMapping) {} 159 160 void print(const MachineBasicBlock &MBB); 161 162 void print(const MachineInstr &MI); 163 void printStackObjectReference(int FrameIndex); 164 void print(const MachineInstr &MI, unsigned OpIdx, 165 const TargetRegisterInfo *TRI, const TargetInstrInfo *TII, 166 bool ShouldPrintRegisterTies, LLT TypeToPrint, 167 bool PrintDef = true); 168 }; 169 170 } // end namespace llvm 171 172 namespace llvm { 173 namespace yaml { 174 175 /// This struct serializes the LLVM IR module. 176 template <> struct BlockScalarTraits<Module> { 177 static void output(const Module &Mod, void *Ctxt, raw_ostream &OS) { 178 Mod.print(OS, nullptr); 179 } 180 181 static StringRef input(StringRef Str, void *Ctxt, Module &Mod) { 182 llvm_unreachable("LLVM Module is supposed to be parsed separately"); 183 return ""; 184 } 185 }; 186 187 } // end namespace yaml 188 } // end namespace llvm 189 190 static void printRegMIR(unsigned Reg, yaml::StringValue &Dest, 191 const TargetRegisterInfo *TRI) { 192 raw_string_ostream OS(Dest.Value); 193 OS << printReg(Reg, TRI); 194 } 195 196 void MIRPrinter::print(const MachineFunction &MF) { 197 initRegisterMaskIds(MF); 198 199 yaml::MachineFunction YamlMF; 200 YamlMF.Name = MF.getName(); 201 YamlMF.Alignment = MF.getAlignment().value(); 202 YamlMF.ExposesReturnsTwice = MF.exposesReturnsTwice(); 203 YamlMF.HasWinCFI = MF.hasWinCFI(); 204 205 YamlMF.Legalized = MF.getProperties().hasProperty( 206 MachineFunctionProperties::Property::Legalized); 207 YamlMF.RegBankSelected = MF.getProperties().hasProperty( 208 MachineFunctionProperties::Property::RegBankSelected); 209 YamlMF.Selected = MF.getProperties().hasProperty( 210 MachineFunctionProperties::Property::Selected); 211 YamlMF.FailedISel = MF.getProperties().hasProperty( 212 MachineFunctionProperties::Property::FailedISel); 213 214 convert(YamlMF, MF.getRegInfo(), MF.getSubtarget().getRegisterInfo()); 215 ModuleSlotTracker MST(MF.getFunction().getParent()); 216 MST.incorporateFunction(MF.getFunction()); 217 convert(MST, YamlMF.FrameInfo, MF.getFrameInfo()); 218 convertStackObjects(YamlMF, MF, MST); 219 convertCallSiteObjects(YamlMF, MF, MST); 220 if (const auto *ConstantPool = MF.getConstantPool()) 221 convert(YamlMF, *ConstantPool); 222 if (const auto *JumpTableInfo = MF.getJumpTableInfo()) 223 convert(MST, YamlMF.JumpTableInfo, *JumpTableInfo); 224 225 const TargetMachine &TM = MF.getTarget(); 226 YamlMF.MachineFuncInfo = 227 std::unique_ptr<yaml::MachineFunctionInfo>(TM.convertFuncInfoToYAML(MF)); 228 229 raw_string_ostream StrOS(YamlMF.Body.Value.Value); 230 bool IsNewlineNeeded = false; 231 for (const auto &MBB : MF) { 232 if (IsNewlineNeeded) 233 StrOS << "\n"; 234 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping) 235 .print(MBB); 236 IsNewlineNeeded = true; 237 } 238 StrOS.flush(); 239 yaml::Output Out(OS); 240 if (!SimplifyMIR) 241 Out.setWriteDefaultValues(true); 242 Out << YamlMF; 243 } 244 245 static void printCustomRegMask(const uint32_t *RegMask, raw_ostream &OS, 246 const TargetRegisterInfo *TRI) { 247 assert(RegMask && "Can't print an empty register mask"); 248 OS << StringRef("CustomRegMask("); 249 250 bool IsRegInRegMaskFound = false; 251 for (int I = 0, E = TRI->getNumRegs(); I < E; I++) { 252 // Check whether the register is asserted in regmask. 253 if (RegMask[I / 32] & (1u << (I % 32))) { 254 if (IsRegInRegMaskFound) 255 OS << ','; 256 OS << printReg(I, TRI); 257 IsRegInRegMaskFound = true; 258 } 259 } 260 261 OS << ')'; 262 } 263 264 static void printRegClassOrBank(unsigned Reg, yaml::StringValue &Dest, 265 const MachineRegisterInfo &RegInfo, 266 const TargetRegisterInfo *TRI) { 267 raw_string_ostream OS(Dest.Value); 268 OS << printRegClassOrBank(Reg, RegInfo, TRI); 269 } 270 271 template <typename T> 272 static void 273 printStackObjectDbgInfo(const MachineFunction::VariableDbgInfo &DebugVar, 274 T &Object, ModuleSlotTracker &MST) { 275 std::array<std::string *, 3> Outputs{{&Object.DebugVar.Value, 276 &Object.DebugExpr.Value, 277 &Object.DebugLoc.Value}}; 278 std::array<const Metadata *, 3> Metas{{DebugVar.Var, 279 DebugVar.Expr, 280 DebugVar.Loc}}; 281 for (unsigned i = 0; i < 3; ++i) { 282 raw_string_ostream StrOS(*Outputs[i]); 283 Metas[i]->printAsOperand(StrOS, MST); 284 } 285 } 286 287 void MIRPrinter::convert(yaml::MachineFunction &MF, 288 const MachineRegisterInfo &RegInfo, 289 const TargetRegisterInfo *TRI) { 290 MF.TracksRegLiveness = RegInfo.tracksLiveness(); 291 292 // Print the virtual register definitions. 293 for (unsigned I = 0, E = RegInfo.getNumVirtRegs(); I < E; ++I) { 294 unsigned Reg = Register::index2VirtReg(I); 295 yaml::VirtualRegisterDefinition VReg; 296 VReg.ID = I; 297 if (RegInfo.getVRegName(Reg) != "") 298 continue; 299 ::printRegClassOrBank(Reg, VReg.Class, RegInfo, TRI); 300 unsigned PreferredReg = RegInfo.getSimpleHint(Reg); 301 if (PreferredReg) 302 printRegMIR(PreferredReg, VReg.PreferredRegister, TRI); 303 MF.VirtualRegisters.push_back(VReg); 304 } 305 306 // Print the live ins. 307 for (std::pair<unsigned, unsigned> LI : RegInfo.liveins()) { 308 yaml::MachineFunctionLiveIn LiveIn; 309 printRegMIR(LI.first, LiveIn.Register, TRI); 310 if (LI.second) 311 printRegMIR(LI.second, LiveIn.VirtualRegister, TRI); 312 MF.LiveIns.push_back(LiveIn); 313 } 314 315 // Prints the callee saved registers. 316 if (RegInfo.isUpdatedCSRsInitialized()) { 317 const MCPhysReg *CalleeSavedRegs = RegInfo.getCalleeSavedRegs(); 318 std::vector<yaml::FlowStringValue> CalleeSavedRegisters; 319 for (const MCPhysReg *I = CalleeSavedRegs; *I; ++I) { 320 yaml::FlowStringValue Reg; 321 printRegMIR(*I, Reg, TRI); 322 CalleeSavedRegisters.push_back(Reg); 323 } 324 MF.CalleeSavedRegisters = CalleeSavedRegisters; 325 } 326 } 327 328 void MIRPrinter::convert(ModuleSlotTracker &MST, 329 yaml::MachineFrameInfo &YamlMFI, 330 const MachineFrameInfo &MFI) { 331 YamlMFI.IsFrameAddressTaken = MFI.isFrameAddressTaken(); 332 YamlMFI.IsReturnAddressTaken = MFI.isReturnAddressTaken(); 333 YamlMFI.HasStackMap = MFI.hasStackMap(); 334 YamlMFI.HasPatchPoint = MFI.hasPatchPoint(); 335 YamlMFI.StackSize = MFI.getStackSize(); 336 YamlMFI.OffsetAdjustment = MFI.getOffsetAdjustment(); 337 YamlMFI.MaxAlignment = MFI.getMaxAlign().value(); 338 YamlMFI.AdjustsStack = MFI.adjustsStack(); 339 YamlMFI.HasCalls = MFI.hasCalls(); 340 YamlMFI.MaxCallFrameSize = MFI.isMaxCallFrameSizeComputed() 341 ? MFI.getMaxCallFrameSize() : ~0u; 342 YamlMFI.CVBytesOfCalleeSavedRegisters = 343 MFI.getCVBytesOfCalleeSavedRegisters(); 344 YamlMFI.HasOpaqueSPAdjustment = MFI.hasOpaqueSPAdjustment(); 345 YamlMFI.HasVAStart = MFI.hasVAStart(); 346 YamlMFI.HasMustTailInVarArgFunc = MFI.hasMustTailInVarArgFunc(); 347 YamlMFI.LocalFrameSize = MFI.getLocalFrameSize(); 348 if (MFI.getSavePoint()) { 349 raw_string_ostream StrOS(YamlMFI.SavePoint.Value); 350 StrOS << printMBBReference(*MFI.getSavePoint()); 351 } 352 if (MFI.getRestorePoint()) { 353 raw_string_ostream StrOS(YamlMFI.RestorePoint.Value); 354 StrOS << printMBBReference(*MFI.getRestorePoint()); 355 } 356 } 357 358 void MIRPrinter::convertStackObjects(yaml::MachineFunction &YMF, 359 const MachineFunction &MF, 360 ModuleSlotTracker &MST) { 361 const MachineFrameInfo &MFI = MF.getFrameInfo(); 362 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 363 // Process fixed stack objects. 364 unsigned ID = 0; 365 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I, ++ID) { 366 if (MFI.isDeadObjectIndex(I)) 367 continue; 368 369 yaml::FixedMachineStackObject YamlObject; 370 YamlObject.ID = ID; 371 YamlObject.Type = MFI.isSpillSlotObjectIndex(I) 372 ? yaml::FixedMachineStackObject::SpillSlot 373 : yaml::FixedMachineStackObject::DefaultType; 374 YamlObject.Offset = MFI.getObjectOffset(I); 375 YamlObject.Size = MFI.getObjectSize(I); 376 YamlObject.Alignment = MFI.getObjectAlignment(I); 377 YamlObject.StackID = (TargetStackID::Value)MFI.getStackID(I); 378 YamlObject.IsImmutable = MFI.isImmutableObjectIndex(I); 379 YamlObject.IsAliased = MFI.isAliasedObjectIndex(I); 380 YMF.FixedStackObjects.push_back(YamlObject); 381 StackObjectOperandMapping.insert( 382 std::make_pair(I, FrameIndexOperand::createFixed(ID))); 383 } 384 385 // Process ordinary stack objects. 386 ID = 0; 387 for (int I = 0, E = MFI.getObjectIndexEnd(); I < E; ++I, ++ID) { 388 if (MFI.isDeadObjectIndex(I)) 389 continue; 390 391 yaml::MachineStackObject YamlObject; 392 YamlObject.ID = ID; 393 if (const auto *Alloca = MFI.getObjectAllocation(I)) 394 YamlObject.Name.Value = std::string( 395 Alloca->hasName() ? Alloca->getName() : "<unnamed alloca>"); 396 YamlObject.Type = MFI.isSpillSlotObjectIndex(I) 397 ? yaml::MachineStackObject::SpillSlot 398 : MFI.isVariableSizedObjectIndex(I) 399 ? yaml::MachineStackObject::VariableSized 400 : yaml::MachineStackObject::DefaultType; 401 YamlObject.Offset = MFI.getObjectOffset(I); 402 YamlObject.Size = MFI.getObjectSize(I); 403 YamlObject.Alignment = MFI.getObjectAlignment(I); 404 YamlObject.StackID = (TargetStackID::Value)MFI.getStackID(I); 405 406 YMF.StackObjects.push_back(YamlObject); 407 StackObjectOperandMapping.insert(std::make_pair( 408 I, FrameIndexOperand::create(YamlObject.Name.Value, ID))); 409 } 410 411 for (const auto &CSInfo : MFI.getCalleeSavedInfo()) { 412 if (!CSInfo.isSpilledToReg() && MFI.isDeadObjectIndex(CSInfo.getFrameIdx())) 413 continue; 414 415 yaml::StringValue Reg; 416 printRegMIR(CSInfo.getReg(), Reg, TRI); 417 if (!CSInfo.isSpilledToReg()) { 418 auto StackObjectInfo = StackObjectOperandMapping.find(CSInfo.getFrameIdx()); 419 assert(StackObjectInfo != StackObjectOperandMapping.end() && 420 "Invalid stack object index"); 421 const FrameIndexOperand &StackObject = StackObjectInfo->second; 422 if (StackObject.IsFixed) { 423 YMF.FixedStackObjects[StackObject.ID].CalleeSavedRegister = Reg; 424 YMF.FixedStackObjects[StackObject.ID].CalleeSavedRestored = 425 CSInfo.isRestored(); 426 } else { 427 YMF.StackObjects[StackObject.ID].CalleeSavedRegister = Reg; 428 YMF.StackObjects[StackObject.ID].CalleeSavedRestored = 429 CSInfo.isRestored(); 430 } 431 } 432 } 433 for (unsigned I = 0, E = MFI.getLocalFrameObjectCount(); I < E; ++I) { 434 auto LocalObject = MFI.getLocalFrameObjectMap(I); 435 auto StackObjectInfo = StackObjectOperandMapping.find(LocalObject.first); 436 assert(StackObjectInfo != StackObjectOperandMapping.end() && 437 "Invalid stack object index"); 438 const FrameIndexOperand &StackObject = StackObjectInfo->second; 439 assert(!StackObject.IsFixed && "Expected a locally mapped stack object"); 440 YMF.StackObjects[StackObject.ID].LocalOffset = LocalObject.second; 441 } 442 443 // Print the stack object references in the frame information class after 444 // converting the stack objects. 445 if (MFI.hasStackProtectorIndex()) { 446 raw_string_ostream StrOS(YMF.FrameInfo.StackProtector.Value); 447 MIPrinter(StrOS, MST, RegisterMaskIds, StackObjectOperandMapping) 448 .printStackObjectReference(MFI.getStackProtectorIndex()); 449 } 450 451 // Print the debug variable information. 452 for (const MachineFunction::VariableDbgInfo &DebugVar : 453 MF.getVariableDbgInfo()) { 454 auto StackObjectInfo = StackObjectOperandMapping.find(DebugVar.Slot); 455 assert(StackObjectInfo != StackObjectOperandMapping.end() && 456 "Invalid stack object index"); 457 const FrameIndexOperand &StackObject = StackObjectInfo->second; 458 if (StackObject.IsFixed) { 459 auto &Object = YMF.FixedStackObjects[StackObject.ID]; 460 printStackObjectDbgInfo(DebugVar, Object, MST); 461 } else { 462 auto &Object = YMF.StackObjects[StackObject.ID]; 463 printStackObjectDbgInfo(DebugVar, Object, MST); 464 } 465 } 466 } 467 468 void MIRPrinter::convertCallSiteObjects(yaml::MachineFunction &YMF, 469 const MachineFunction &MF, 470 ModuleSlotTracker &MST) { 471 const auto *TRI = MF.getSubtarget().getRegisterInfo(); 472 for (auto CSInfo : MF.getCallSitesInfo()) { 473 yaml::CallSiteInfo YmlCS; 474 yaml::CallSiteInfo::MachineInstrLoc CallLocation; 475 476 // Prepare instruction position. 477 MachineBasicBlock::const_instr_iterator CallI = CSInfo.first->getIterator(); 478 CallLocation.BlockNum = CallI->getParent()->getNumber(); 479 // Get call instruction offset from the beginning of block. 480 CallLocation.Offset = 481 std::distance(CallI->getParent()->instr_begin(), CallI); 482 YmlCS.CallLocation = CallLocation; 483 // Construct call arguments and theirs forwarding register info. 484 for (auto ArgReg : CSInfo.second) { 485 yaml::CallSiteInfo::ArgRegPair YmlArgReg; 486 YmlArgReg.ArgNo = ArgReg.ArgNo; 487 printRegMIR(ArgReg.Reg, YmlArgReg.Reg, TRI); 488 YmlCS.ArgForwardingRegs.emplace_back(YmlArgReg); 489 } 490 YMF.CallSitesInfo.push_back(YmlCS); 491 } 492 493 // Sort call info by position of call instructions. 494 llvm::sort(YMF.CallSitesInfo.begin(), YMF.CallSitesInfo.end(), 495 [](yaml::CallSiteInfo A, yaml::CallSiteInfo B) { 496 if (A.CallLocation.BlockNum == B.CallLocation.BlockNum) 497 return A.CallLocation.Offset < B.CallLocation.Offset; 498 return A.CallLocation.BlockNum < B.CallLocation.BlockNum; 499 }); 500 } 501 502 void MIRPrinter::convert(yaml::MachineFunction &MF, 503 const MachineConstantPool &ConstantPool) { 504 unsigned ID = 0; 505 for (const MachineConstantPoolEntry &Constant : ConstantPool.getConstants()) { 506 std::string Str; 507 raw_string_ostream StrOS(Str); 508 if (Constant.isMachineConstantPoolEntry()) { 509 Constant.Val.MachineCPVal->print(StrOS); 510 } else { 511 Constant.Val.ConstVal->printAsOperand(StrOS); 512 } 513 514 yaml::MachineConstantPoolValue YamlConstant; 515 YamlConstant.ID = ID++; 516 YamlConstant.Value = StrOS.str(); 517 YamlConstant.Alignment = Constant.getAlignment(); 518 YamlConstant.IsTargetSpecific = Constant.isMachineConstantPoolEntry(); 519 520 MF.Constants.push_back(YamlConstant); 521 } 522 } 523 524 void MIRPrinter::convert(ModuleSlotTracker &MST, 525 yaml::MachineJumpTable &YamlJTI, 526 const MachineJumpTableInfo &JTI) { 527 YamlJTI.Kind = JTI.getEntryKind(); 528 unsigned ID = 0; 529 for (const auto &Table : JTI.getJumpTables()) { 530 std::string Str; 531 yaml::MachineJumpTable::Entry Entry; 532 Entry.ID = ID++; 533 for (const auto *MBB : Table.MBBs) { 534 raw_string_ostream StrOS(Str); 535 StrOS << printMBBReference(*MBB); 536 Entry.Blocks.push_back(StrOS.str()); 537 Str.clear(); 538 } 539 YamlJTI.Entries.push_back(Entry); 540 } 541 } 542 543 void MIRPrinter::initRegisterMaskIds(const MachineFunction &MF) { 544 const auto *TRI = MF.getSubtarget().getRegisterInfo(); 545 unsigned I = 0; 546 for (const uint32_t *Mask : TRI->getRegMasks()) 547 RegisterMaskIds.insert(std::make_pair(Mask, I++)); 548 } 549 550 void llvm::guessSuccessors(const MachineBasicBlock &MBB, 551 SmallVectorImpl<MachineBasicBlock*> &Result, 552 bool &IsFallthrough) { 553 SmallPtrSet<MachineBasicBlock*,8> Seen; 554 555 for (const MachineInstr &MI : MBB) { 556 if (MI.isPHI()) 557 continue; 558 for (const MachineOperand &MO : MI.operands()) { 559 if (!MO.isMBB()) 560 continue; 561 MachineBasicBlock *Succ = MO.getMBB(); 562 auto RP = Seen.insert(Succ); 563 if (RP.second) 564 Result.push_back(Succ); 565 } 566 } 567 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr(); 568 IsFallthrough = I == MBB.end() || !I->isBarrier(); 569 } 570 571 bool 572 MIPrinter::canPredictBranchProbabilities(const MachineBasicBlock &MBB) const { 573 if (MBB.succ_size() <= 1) 574 return true; 575 if (!MBB.hasSuccessorProbabilities()) 576 return true; 577 578 SmallVector<BranchProbability,8> Normalized(MBB.Probs.begin(), 579 MBB.Probs.end()); 580 BranchProbability::normalizeProbabilities(Normalized.begin(), 581 Normalized.end()); 582 SmallVector<BranchProbability,8> Equal(Normalized.size()); 583 BranchProbability::normalizeProbabilities(Equal.begin(), Equal.end()); 584 585 return std::equal(Normalized.begin(), Normalized.end(), Equal.begin()); 586 } 587 588 bool MIPrinter::canPredictSuccessors(const MachineBasicBlock &MBB) const { 589 SmallVector<MachineBasicBlock*,8> GuessedSuccs; 590 bool GuessedFallthrough; 591 guessSuccessors(MBB, GuessedSuccs, GuessedFallthrough); 592 if (GuessedFallthrough) { 593 const MachineFunction &MF = *MBB.getParent(); 594 MachineFunction::const_iterator NextI = std::next(MBB.getIterator()); 595 if (NextI != MF.end()) { 596 MachineBasicBlock *Next = const_cast<MachineBasicBlock*>(&*NextI); 597 if (!is_contained(GuessedSuccs, Next)) 598 GuessedSuccs.push_back(Next); 599 } 600 } 601 if (GuessedSuccs.size() != MBB.succ_size()) 602 return false; 603 return std::equal(MBB.succ_begin(), MBB.succ_end(), GuessedSuccs.begin()); 604 } 605 606 void MIPrinter::print(const MachineBasicBlock &MBB) { 607 assert(MBB.getNumber() >= 0 && "Invalid MBB number"); 608 OS << "bb." << MBB.getNumber(); 609 bool HasAttributes = false; 610 if (const auto *BB = MBB.getBasicBlock()) { 611 if (BB->hasName()) { 612 OS << "." << BB->getName(); 613 } else { 614 HasAttributes = true; 615 OS << " ("; 616 int Slot = MST.getLocalSlot(BB); 617 if (Slot == -1) 618 OS << "<ir-block badref>"; 619 else 620 OS << (Twine("%ir-block.") + Twine(Slot)).str(); 621 } 622 } 623 if (MBB.hasAddressTaken()) { 624 OS << (HasAttributes ? ", " : " ("); 625 OS << "address-taken"; 626 HasAttributes = true; 627 } 628 if (MBB.isEHPad()) { 629 OS << (HasAttributes ? ", " : " ("); 630 OS << "landing-pad"; 631 HasAttributes = true; 632 } 633 if (MBB.getAlignment() != Align(1)) { 634 OS << (HasAttributes ? ", " : " ("); 635 OS << "align " << MBB.getAlignment().value(); 636 HasAttributes = true; 637 } 638 if (MBB.getSectionType() != MBBS_None) { 639 OS << (HasAttributes ? ", " : " ("); 640 OS << "bbsections "; 641 switch (MBB.getSectionType()) { 642 case MBBS_Entry: 643 OS << "Entry"; 644 break; 645 case MBBS_Exception: 646 OS << "Exception"; 647 break; 648 case MBBS_Cold: 649 OS << "Cold"; 650 break; 651 case MBBS_Unique: 652 OS << "Unique"; 653 break; 654 default: 655 llvm_unreachable("No such section type"); 656 } 657 HasAttributes = true; 658 } 659 if (HasAttributes) 660 OS << ")"; 661 OS << ":\n"; 662 663 bool HasLineAttributes = false; 664 // Print the successors 665 bool canPredictProbs = canPredictBranchProbabilities(MBB); 666 // Even if the list of successors is empty, if we cannot guess it, 667 // we need to print it to tell the parser that the list is empty. 668 // This is needed, because MI model unreachable as empty blocks 669 // with an empty successor list. If the parser would see that 670 // without the successor list, it would guess the code would 671 // fallthrough. 672 if ((!MBB.succ_empty() && !SimplifyMIR) || !canPredictProbs || 673 !canPredictSuccessors(MBB)) { 674 OS.indent(2) << "successors: "; 675 for (auto I = MBB.succ_begin(), E = MBB.succ_end(); I != E; ++I) { 676 if (I != MBB.succ_begin()) 677 OS << ", "; 678 OS << printMBBReference(**I); 679 if (!SimplifyMIR || !canPredictProbs) 680 OS << '(' 681 << format("0x%08" PRIx32, MBB.getSuccProbability(I).getNumerator()) 682 << ')'; 683 } 684 OS << "\n"; 685 HasLineAttributes = true; 686 } 687 688 // Print the live in registers. 689 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo(); 690 if (MRI.tracksLiveness() && !MBB.livein_empty()) { 691 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo(); 692 OS.indent(2) << "liveins: "; 693 bool First = true; 694 for (const auto &LI : MBB.liveins()) { 695 if (!First) 696 OS << ", "; 697 First = false; 698 OS << printReg(LI.PhysReg, &TRI); 699 if (!LI.LaneMask.all()) 700 OS << ":0x" << PrintLaneMask(LI.LaneMask); 701 } 702 OS << "\n"; 703 HasLineAttributes = true; 704 } 705 706 if (HasLineAttributes) 707 OS << "\n"; 708 bool IsInBundle = false; 709 for (auto I = MBB.instr_begin(), E = MBB.instr_end(); I != E; ++I) { 710 const MachineInstr &MI = *I; 711 if (IsInBundle && !MI.isInsideBundle()) { 712 OS.indent(2) << "}\n"; 713 IsInBundle = false; 714 } 715 OS.indent(IsInBundle ? 4 : 2); 716 print(MI); 717 if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) { 718 OS << " {"; 719 IsInBundle = true; 720 } 721 OS << "\n"; 722 } 723 if (IsInBundle) 724 OS.indent(2) << "}\n"; 725 } 726 727 void MIPrinter::print(const MachineInstr &MI) { 728 const auto *MF = MI.getMF(); 729 const auto &MRI = MF->getRegInfo(); 730 const auto &SubTarget = MF->getSubtarget(); 731 const auto *TRI = SubTarget.getRegisterInfo(); 732 assert(TRI && "Expected target register info"); 733 const auto *TII = SubTarget.getInstrInfo(); 734 assert(TII && "Expected target instruction info"); 735 if (MI.isCFIInstruction()) 736 assert(MI.getNumOperands() == 1 && "Expected 1 operand in CFI instruction"); 737 738 SmallBitVector PrintedTypes(8); 739 bool ShouldPrintRegisterTies = MI.hasComplexRegisterTies(); 740 unsigned I = 0, E = MI.getNumOperands(); 741 for (; I < E && MI.getOperand(I).isReg() && MI.getOperand(I).isDef() && 742 !MI.getOperand(I).isImplicit(); 743 ++I) { 744 if (I) 745 OS << ", "; 746 print(MI, I, TRI, TII, ShouldPrintRegisterTies, 747 MI.getTypeToPrint(I, PrintedTypes, MRI), 748 /*PrintDef=*/false); 749 } 750 751 if (I) 752 OS << " = "; 753 if (MI.getFlag(MachineInstr::FrameSetup)) 754 OS << "frame-setup "; 755 if (MI.getFlag(MachineInstr::FrameDestroy)) 756 OS << "frame-destroy "; 757 if (MI.getFlag(MachineInstr::FmNoNans)) 758 OS << "nnan "; 759 if (MI.getFlag(MachineInstr::FmNoInfs)) 760 OS << "ninf "; 761 if (MI.getFlag(MachineInstr::FmNsz)) 762 OS << "nsz "; 763 if (MI.getFlag(MachineInstr::FmArcp)) 764 OS << "arcp "; 765 if (MI.getFlag(MachineInstr::FmContract)) 766 OS << "contract "; 767 if (MI.getFlag(MachineInstr::FmAfn)) 768 OS << "afn "; 769 if (MI.getFlag(MachineInstr::FmReassoc)) 770 OS << "reassoc "; 771 if (MI.getFlag(MachineInstr::NoUWrap)) 772 OS << "nuw "; 773 if (MI.getFlag(MachineInstr::NoSWrap)) 774 OS << "nsw "; 775 if (MI.getFlag(MachineInstr::IsExact)) 776 OS << "exact "; 777 if (MI.getFlag(MachineInstr::NoFPExcept)) 778 OS << "nofpexcept "; 779 780 OS << TII->getName(MI.getOpcode()); 781 if (I < E) 782 OS << ' '; 783 784 bool NeedComma = false; 785 for (; I < E; ++I) { 786 if (NeedComma) 787 OS << ", "; 788 print(MI, I, TRI, TII, ShouldPrintRegisterTies, 789 MI.getTypeToPrint(I, PrintedTypes, MRI)); 790 NeedComma = true; 791 } 792 793 // Print any optional symbols attached to this instruction as-if they were 794 // operands. 795 if (MCSymbol *PreInstrSymbol = MI.getPreInstrSymbol()) { 796 if (NeedComma) 797 OS << ','; 798 OS << " pre-instr-symbol "; 799 MachineOperand::printSymbol(OS, *PreInstrSymbol); 800 NeedComma = true; 801 } 802 if (MCSymbol *PostInstrSymbol = MI.getPostInstrSymbol()) { 803 if (NeedComma) 804 OS << ','; 805 OS << " post-instr-symbol "; 806 MachineOperand::printSymbol(OS, *PostInstrSymbol); 807 NeedComma = true; 808 } 809 if (MDNode *HeapAllocMarker = MI.getHeapAllocMarker()) { 810 if (NeedComma) 811 OS << ','; 812 OS << " heap-alloc-marker "; 813 HeapAllocMarker->printAsOperand(OS, MST); 814 NeedComma = true; 815 } 816 817 if (const DebugLoc &DL = MI.getDebugLoc()) { 818 if (NeedComma) 819 OS << ','; 820 OS << " debug-location "; 821 DL->printAsOperand(OS, MST); 822 } 823 824 if (!MI.memoperands_empty()) { 825 OS << " :: "; 826 const LLVMContext &Context = MF->getFunction().getContext(); 827 const MachineFrameInfo &MFI = MF->getFrameInfo(); 828 bool NeedComma = false; 829 for (const auto *Op : MI.memoperands()) { 830 if (NeedComma) 831 OS << ", "; 832 Op->print(OS, MST, SSNs, Context, &MFI, TII); 833 NeedComma = true; 834 } 835 } 836 } 837 838 void MIPrinter::printStackObjectReference(int FrameIndex) { 839 auto ObjectInfo = StackObjectOperandMapping.find(FrameIndex); 840 assert(ObjectInfo != StackObjectOperandMapping.end() && 841 "Invalid frame index"); 842 const FrameIndexOperand &Operand = ObjectInfo->second; 843 MachineOperand::printStackObjectReference(OS, Operand.ID, Operand.IsFixed, 844 Operand.Name); 845 } 846 847 static std::string formatOperandComment(std::string Comment) { 848 if (Comment.empty()) 849 return Comment; 850 return std::string(" /* " + Comment + " */"); 851 } 852 853 void MIPrinter::print(const MachineInstr &MI, unsigned OpIdx, 854 const TargetRegisterInfo *TRI, 855 const TargetInstrInfo *TII, 856 bool ShouldPrintRegisterTies, LLT TypeToPrint, 857 bool PrintDef) { 858 const MachineOperand &Op = MI.getOperand(OpIdx); 859 std::string MOComment = TII->createMIROperandComment(MI, Op, OpIdx); 860 861 switch (Op.getType()) { 862 case MachineOperand::MO_Immediate: 863 if (MI.isOperandSubregIdx(OpIdx)) { 864 MachineOperand::printTargetFlags(OS, Op); 865 MachineOperand::printSubRegIdx(OS, Op.getImm(), TRI); 866 break; 867 } 868 LLVM_FALLTHROUGH; 869 case MachineOperand::MO_Register: 870 case MachineOperand::MO_CImmediate: 871 case MachineOperand::MO_FPImmediate: 872 case MachineOperand::MO_MachineBasicBlock: 873 case MachineOperand::MO_ConstantPoolIndex: 874 case MachineOperand::MO_TargetIndex: 875 case MachineOperand::MO_JumpTableIndex: 876 case MachineOperand::MO_ExternalSymbol: 877 case MachineOperand::MO_GlobalAddress: 878 case MachineOperand::MO_RegisterLiveOut: 879 case MachineOperand::MO_Metadata: 880 case MachineOperand::MO_MCSymbol: 881 case MachineOperand::MO_CFIIndex: 882 case MachineOperand::MO_IntrinsicID: 883 case MachineOperand::MO_Predicate: 884 case MachineOperand::MO_BlockAddress: 885 case MachineOperand::MO_ShuffleMask: { 886 unsigned TiedOperandIdx = 0; 887 if (ShouldPrintRegisterTies && Op.isReg() && Op.isTied() && !Op.isDef()) 888 TiedOperandIdx = Op.getParent()->findTiedOperandIdx(OpIdx); 889 const TargetIntrinsicInfo *TII = MI.getMF()->getTarget().getIntrinsicInfo(); 890 Op.print(OS, MST, TypeToPrint, OpIdx, PrintDef, /*IsStandalone=*/false, 891 ShouldPrintRegisterTies, TiedOperandIdx, TRI, TII); 892 OS << formatOperandComment(MOComment); 893 break; 894 } 895 case MachineOperand::MO_FrameIndex: 896 printStackObjectReference(Op.getIndex()); 897 break; 898 case MachineOperand::MO_RegisterMask: { 899 auto RegMaskInfo = RegisterMaskIds.find(Op.getRegMask()); 900 if (RegMaskInfo != RegisterMaskIds.end()) 901 OS << StringRef(TRI->getRegMaskNames()[RegMaskInfo->second]).lower(); 902 else 903 printCustomRegMask(Op.getRegMask(), OS, TRI); 904 break; 905 } 906 } 907 } 908 909 void MIRFormatter::printIRValue(raw_ostream &OS, const Value &V, 910 ModuleSlotTracker &MST) { 911 if (isa<GlobalValue>(V)) { 912 V.printAsOperand(OS, /*PrintType=*/false, MST); 913 return; 914 } 915 if (isa<Constant>(V)) { 916 // Machine memory operands can load/store to/from constant value pointers. 917 OS << '`'; 918 V.printAsOperand(OS, /*PrintType=*/true, MST); 919 OS << '`'; 920 return; 921 } 922 OS << "%ir."; 923 if (V.hasName()) { 924 printLLVMNameWithoutPrefix(OS, V.getName()); 925 return; 926 } 927 int Slot = MST.getCurrentFunction() ? MST.getLocalSlot(&V) : -1; 928 MachineOperand::printIRSlotNumber(OS, Slot); 929 } 930 931 void llvm::printMIR(raw_ostream &OS, const Module &M) { 932 yaml::Output Out(OS); 933 Out << const_cast<Module &>(M); 934 } 935 936 void llvm::printMIR(raw_ostream &OS, const MachineFunction &MF) { 937 MIRPrinter Printer(OS); 938 Printer.print(MF); 939 } 940