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 "CodeGenOptions.h"
11#include "llvm/CodeGen/MachineRegisterInfo.h"
12#include "llvm/CodeGen/MachineStableHash.h"
13#include "llvm/IR/Constants.h"
14
15using namespace llvm;
16
17#define DEBUG_TYPE "mir-vregnamer-utils"
18
19using VRegRenameMap = std::map<Register, Register>;
20
21bool VRegRenamer::doVRegRenaming(const VRegRenameMap &VRM) {
22 bool Changed = false;
23
24 for (const auto &E : VRM) {
25 Changed = Changed || !MRI.reg_empty(RegNo: E.first);
26 MRI.replaceRegWith(FromReg: E.first, ToReg: E.second);
27 }
28
29 return Changed;
30}
31
32VRegRenameMap
33VRegRenamer::getVRegRenameMap(const std::vector<NamedVReg> &VRegs) {
34
35 StringMap<unsigned> VRegNameCollisionMap;
36
37 auto GetUniqueVRegName = [&VRegNameCollisionMap](const NamedVReg &Reg) {
38 const unsigned Counter = ++VRegNameCollisionMap[Reg.getName()];
39 return Reg.getName() + "__" + std::to_string(val: Counter);
40 };
41
42 VRegRenameMap VRM;
43 for (const auto &VReg : VRegs) {
44 const Register Reg = VReg.getReg();
45 VRM[Reg] = createVirtualRegisterWithLowerName(VReg: Reg, Name: GetUniqueVRegName(VReg));
46 }
47 return VRM;
48}
49
50std::string VRegRenamer::getInstructionOpcodeHash(MachineInstr &MI) {
51 std::string S;
52 raw_string_ostream OS(S);
53
54 if (Opts.mir_vreg_namer_use_stable_hash) {
55 auto Hash = stableHashValue(MI, /* HashVRegs */ true,
56 /* HashConstantPoolIndices */ true,
57 /* HashMemOperands */ true);
58 assert(Hash && "Expected non-zero Hash");
59 OS << format_hex_no_prefix(N: Hash, Width: 16, Upper: true);
60 return OS.str();
61 }
62
63 // Gets a hashable artifact from a given MachineOperand (ie an unsigned).
64 auto GetHashableMO = [this](const MachineOperand &MO) -> unsigned {
65 switch (MO.getType()) {
66 case MachineOperand::MO_CImmediate:
67 return hash_combine(args: MO.getType(), args: MO.getTargetFlags(),
68 args: MO.getCImm()->getZExtValue());
69 case MachineOperand::MO_FPImmediate:
70 return hash_combine(
71 args: MO.getType(), args: MO.getTargetFlags(),
72 args: MO.getFPImm()->getValueAPF().bitcastToAPInt().getZExtValue());
73 case MachineOperand::MO_Register:
74 if (MO.getReg().isVirtual())
75 return MRI.getVRegDef(Reg: MO.getReg())->getOpcode();
76 return MO.getReg().id();
77 case MachineOperand::MO_Immediate:
78 return MO.getImm();
79 case MachineOperand::MO_TargetIndex:
80 return MO.getOffset() | (MO.getTargetFlags() << 16);
81 case MachineOperand::MO_FrameIndex:
82 case MachineOperand::MO_ConstantPoolIndex:
83 case MachineOperand::MO_JumpTableIndex:
84 return llvm::hash_value(MO);
85
86 // We could explicitly handle all the types of the MachineOperand,
87 // here but we can just return a common number until we find a
88 // compelling test case where this is bad. The only side effect here
89 // is contributing to a hash collision but there's enough information
90 // (Opcodes,other registers etc) that this will likely not be a problem.
91
92 // TODO: Handle the following Index/ID/Predicate/LaneMask cases. They can
93 // be hashed on in a stable manner.
94 case MachineOperand::MO_CFIIndex:
95 case MachineOperand::MO_IntrinsicID:
96 case MachineOperand::MO_Predicate:
97 case MachineOperand::MO_LaneMask:
98
99 // In the cases below we havn't found a way to produce an artifact that will
100 // result in a stable hash, in most cases because they are pointers. We want
101 // stable hashes because we want the hash to be the same run to run.
102 case MachineOperand::MO_MachineBasicBlock:
103 case MachineOperand::MO_ExternalSymbol:
104 case MachineOperand::MO_GlobalAddress:
105 case MachineOperand::MO_BlockAddress:
106 case MachineOperand::MO_RegisterMask:
107 case MachineOperand::MO_RegisterLiveOut:
108 case MachineOperand::MO_Metadata:
109 case MachineOperand::MO_MCSymbol:
110 case MachineOperand::MO_ShuffleMask:
111 case MachineOperand::MO_DbgInstrRef:
112 return 0;
113 }
114 llvm_unreachable("Unexpected MachineOperandType.");
115 };
116
117 SmallVector<unsigned, 16> MIOperands = {MI.getOpcode(), MI.getFlags()};
118 llvm::transform(Range: MI.uses(), d_first: std::back_inserter(x&: MIOperands), F: GetHashableMO);
119
120 for (const auto *Op : MI.memoperands()) {
121 MIOperands.push_back(Elt: (unsigned)Op->getSize().getValue());
122 MIOperands.push_back(Elt: (unsigned)Op->getFlags());
123 MIOperands.push_back(Elt: (unsigned)Op->getOffset());
124 MIOperands.push_back(Elt: (unsigned)Op->getSuccessOrdering());
125 MIOperands.push_back(Elt: (unsigned)Op->getAddrSpace());
126 MIOperands.push_back(Elt: (unsigned)Op->getSyncScopeID());
127 MIOperands.push_back(Elt: (unsigned)Op->getBaseAlign().value());
128 MIOperands.push_back(Elt: (unsigned)Op->getFailureOrdering());
129 }
130
131 auto HashMI = hash_combine_range(R&: MIOperands);
132 OS << format_hex_no_prefix(N: HashMI, Width: 16, Upper: true);
133 return OS.str();
134}
135
136Register VRegRenamer::createVirtualRegister(Register VReg) {
137 assert(VReg.isVirtual() && "Expected Virtual Registers");
138 std::string Name = getInstructionOpcodeHash(MI&: *MRI.getVRegDef(Reg: VReg));
139 return createVirtualRegisterWithLowerName(VReg, Name);
140}
141
142bool VRegRenamer::renameInstsInMBB(MachineBasicBlock *MBB) {
143 std::vector<NamedVReg> VRegs;
144 std::string Prefix = "bb" + std::to_string(val: CurrentBBNumber) + "_";
145 for (MachineInstr &Candidate : *MBB) {
146 // Don't rename stores/branches.
147 if (Candidate.mayStore() || Candidate.isBranch())
148 continue;
149 if (!Candidate.getNumOperands())
150 continue;
151 // Look for instructions that define VRegs.
152 for (MachineOperand &MO : Candidate.all_defs()) {
153 // Avoid physical reg defs.
154 if (!MO.getReg().isVirtual())
155 continue;
156 VRegs.push_back(
157 x: NamedVReg(MO.getReg(), Prefix + getInstructionOpcodeHash(MI&: Candidate)));
158 }
159 }
160
161 return !VRegs.empty() ? doVRegRenaming(VRM: getVRegRenameMap(VRegs)) : false;
162}
163
164Register VRegRenamer::createVirtualRegisterWithLowerName(Register VReg,
165 StringRef Name) {
166 std::string LowerName = Name.lower();
167 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg: VReg);
168 return RC ? MRI.createVirtualRegister(RegClass: RC, Name: LowerName)
169 : MRI.createGenericVirtualRegister(Ty: MRI.getType(Reg: VReg), Name: LowerName);
170}
171