LLVM  10.0.0
MIRVRegNamerUtils.cpp
Go to the documentation of this file.
1 //===---------- MIRVRegNamerUtils.cpp - MIR VReg Renaming Utilities -------===//
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 #include "MIRVRegNamerUtils.h"
10 #include "llvm/Support/Debug.h"
11 
12 using namespace llvm;
13 
14 #define DEBUG_TYPE "mir-vregnamer-utils"
15 
16 using VRegRenameMap = std::map<unsigned, unsigned>;
17 
18 bool VRegRenamer::doVRegRenaming(const VRegRenameMap &VRM) {
19  bool Changed = false;
20 
21  for (const auto &E : VRM) {
22  Changed = Changed || !MRI.reg_empty(E.first);
23  MRI.replaceRegWith(E.first, E.second);
24  }
25 
26  return Changed;
27 }
28 
30 VRegRenamer::getVRegRenameMap(const std::vector<NamedVReg> &VRegs) {
31 
32  StringMap<unsigned> VRegNameCollisionMap;
33 
34  auto GetUniqueVRegName = [&VRegNameCollisionMap](const NamedVReg &Reg) {
35  if (VRegNameCollisionMap.find(Reg.getName()) == VRegNameCollisionMap.end())
36  VRegNameCollisionMap[Reg.getName()] = 0;
37  const unsigned Counter = ++VRegNameCollisionMap[Reg.getName()];
38  return Reg.getName() + "__" + std::to_string(Counter);
39  };
40 
41  VRegRenameMap VRM;
42  for (const auto &VReg : VRegs) {
43  const unsigned Reg = VReg.getReg();
44  VRM[Reg] = createVirtualRegisterWithLowerName(Reg, GetUniqueVRegName(VReg));
45  }
46  return VRM;
47 }
48 
49 std::string VRegRenamer::getInstructionOpcodeHash(MachineInstr &MI) {
50  std::string S;
51  raw_string_ostream OS(S);
52 
53  // Gets a hashable artifact from a given MachineOperand (ie an unsigned).
54  auto GetHashableMO = [this](const MachineOperand &MO) -> unsigned {
55  switch (MO.getType()) {
57  return hash_combine(MO.getType(), MO.getTargetFlags(),
58  MO.getCImm()->getZExtValue());
60  return hash_combine(
61  MO.getType(), MO.getTargetFlags(),
62  MO.getFPImm()->getValueAPF().bitcastToAPInt().getZExtValue());
64  if (Register::isVirtualRegister(MO.getReg()))
65  return MRI.getVRegDef(MO.getReg())->getOpcode();
66  return MO.getReg();
68  return MO.getImm();
70  return MO.getOffset() | (MO.getTargetFlags() << 16);
72  return llvm::hash_value(MO);
73 
74  // We could explicitly handle all the types of the MachineOperand,
75  // here but we can just return a common number until we find a
76  // compelling test case where this is bad. The only side effect here
77  // is contributing to a hash collision but there's enough information
78  // (Opcodes,other registers etc) that this will likely not be a problem.
79 
80  // TODO: Handle the following Index/ID/Predicate cases. They can
81  // be hashed on in a stable manner.
87 
88  // In the cases below we havn't found a way to produce an artifact that will
89  // result in a stable hash, in most cases because they are pointers. We want
90  // stable hashes because we want the hash to be the same run to run.
100  return 0;
101  }
102  llvm_unreachable("Unexpected MachineOperandType.");
103  };
104 
105  SmallVector<unsigned, 16> MIOperands = {MI.getOpcode(), MI.getFlags()};
106  llvm::transform(MI.uses(), std::back_inserter(MIOperands), GetHashableMO);
107 
108  for (const auto *Op : MI.memoperands()) {
109  MIOperands.push_back((unsigned)Op->getSize());
110  MIOperands.push_back((unsigned)Op->getFlags());
111  MIOperands.push_back((unsigned)Op->getOffset());
112  MIOperands.push_back((unsigned)Op->getOrdering());
113  MIOperands.push_back((unsigned)Op->getAddrSpace());
114  MIOperands.push_back((unsigned)Op->getSyncScopeID());
115  MIOperands.push_back((unsigned)Op->getBaseAlignment());
116  MIOperands.push_back((unsigned)Op->getFailureOrdering());
117  }
118 
119  auto HashMI = hash_combine_range(MIOperands.begin(), MIOperands.end());
120  return std::to_string(HashMI).substr(0, 5);
121 }
122 
123 unsigned VRegRenamer::createVirtualRegister(unsigned VReg) {
124  assert(Register::isVirtualRegister(VReg) && "Expected Virtual Registers");
125  std::string Name = getInstructionOpcodeHash(*MRI.getVRegDef(VReg));
126  return createVirtualRegisterWithLowerName(VReg, Name);
127 }
128 
129 bool VRegRenamer::renameInstsInMBB(MachineBasicBlock *MBB) {
130  std::vector<NamedVReg> VRegs;
131  std::string Prefix = "bb" + std::to_string(CurrentBBNumber) + "_";
132  for (MachineInstr &Candidate : *MBB) {
133  // Don't rename stores/branches.
134  if (Candidate.mayStore() || Candidate.isBranch())
135  continue;
136  if (!Candidate.getNumOperands())
137  continue;
138  // Look for instructions that define VRegs in operand 0.
139  MachineOperand &MO = Candidate.getOperand(0);
140  // Avoid non regs, instructions defining physical regs.
141  if (!MO.isReg() || !Register::isVirtualRegister(MO.getReg()))
142  continue;
143  VRegs.push_back(
144  NamedVReg(MO.getReg(), Prefix + getInstructionOpcodeHash(Candidate)));
145  }
146 
147  return VRegs.size() ? doVRegRenaming(getVRegRenameMap(VRegs)) : false;
148 }
149 
150 unsigned VRegRenamer::createVirtualRegisterWithLowerName(unsigned VReg,
151  StringRef Name) {
152  std::string LowerName = Name.lower();
153  const TargetRegisterClass *RC = MRI.getRegClassOrNull(VReg);
154  return RC ? MRI.createVirtualRegister(RC, LowerName)
155  : MRI.createGenericVirtualRegister(MRI.getType(VReg), LowerName);
156 }
This class represents lattice values for constants.
Definition: AllocatorList.h:23
iterator_range< mop_iterator > uses()
Returns a range that includes all operands that are register uses.
Definition: MachineInstr.h:525
Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
void push_back(const T &Elt)
Definition: SmallVector.h:211
Address of indexed Jump Table for switch.
unsigned Reg
iterator find(StringRef Key)
Definition: StringMap.h:355
LLT getType(unsigned Reg) const
Get the low-level type of Reg or LLT{} if Reg is not a generic (target independent) virtual register...
MachineBasicBlock reference.
Mask of live-out registers.
Mask of preserved registers.
MCCFIInstruction index.
Target-dependent index+offset operand.
static Optional< unsigned > getOpcode(ArrayRef< VPValue *> Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:196
Name of external global symbol.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:426
MachineInstr * getVRegDef(unsigned Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
Immediate >64bit operand.
std::map< unsigned, unsigned > VRegRenameMap
hash_code hash_value(const APFloat &Arg)
See friend declarations above.
Definition: APFloat.cpp:4510
Address of a global value.
ArrayRef< MachineMemOperand * > memoperands() const
Access to memory operands of the instruction.
Definition: MachineInstr.h:549
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Address of a basic block.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Generic predicate for ISel.
MachineOperand class - Representation of each machine instruction operand.
MCSymbol reference (for debug/eh info)
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition: Hashing.h:600
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition: Hashing.h:478
void replaceRegWith(unsigned FromReg, unsigned ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
Representation of each machine instruction.
Definition: MachineInstr.h:63
Abstract Stack Frame Index.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere...
Definition: STLExtras.h:1264
uint16_t getFlags() const
Return the MI flags bitvector.
Definition: MachineInstr.h:307
const std::string to_string(const T &Value)
Definition: ScopedPrinter.h:61
LLVM_NODISCARD std::string lower() const
Definition: StringRef.cpp:108
const TargetRegisterClass * getRegClassOrNull(unsigned Reg) const
Return the register class of Reg, or null if Reg has not been assigned a register class yet...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:516
Floating-point immediate operand.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:69
bool reg_empty(unsigned RegNo) const
reg_empty - Return true if there are no instructions using or defining the specified register (it may...
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
Address of indexed Constant in Constant Pool.
Register createGenericVirtualRegister(LLT Ty, StringRef Name="")
Create and return a new generic virtual register with low-level type Ty.
Register getReg() const
getReg - Returns the register number.
Other IR Constant for ISel (shuffle masks)
iterator end()
Definition: StringMap.h:340
Metadata reference (for debug info)