LLVM 24.0.0git
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 "CodeGenOptions.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(E.first);
26 MRI.replaceRegWith(E.first, E.second);
27 }
28
29 return Changed;
30}
31
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(Counter);
40 };
41
42 VRegRenameMap VRM;
43 for (const auto &VReg : VRegs) {
44 const Register Reg = VReg.getReg();
45 VRM[Reg] = createVirtualRegisterWithLowerName(Reg, 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(Hash, 16, 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()) {
67 return hash_combine(MO.getType(), MO.getTargetFlags(),
68 MO.getCImm()->getZExtValue());
70 return hash_combine(
71 MO.getType(), MO.getTargetFlags(),
72 MO.getFPImm()->getValueAPF().bitcastToAPInt().getZExtValue());
74 if (MO.getReg().isVirtual())
75 return MRI.getVRegDef(MO.getReg())->getOpcode();
76 return MO.getReg().id();
78 return MO.getImm();
80 return MO.getOffset() | (MO.getTargetFlags() << 16);
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.
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.
112 return 0;
113 }
114 llvm_unreachable("Unexpected MachineOperandType.");
115 };
116
117 SmallVector<unsigned, 16> MIOperands = {MI.getOpcode(), MI.getFlags()};
118 llvm::transform(MI.uses(), std::back_inserter(MIOperands), GetHashableMO);
119
120 for (const auto *Op : MI.memoperands()) {
121 MIOperands.push_back((unsigned)Op->getSize().getValue());
122 MIOperands.push_back((unsigned)Op->getFlags());
123 MIOperands.push_back((unsigned)Op->getOffset());
124 MIOperands.push_back((unsigned)Op->getSuccessOrdering());
125 MIOperands.push_back((unsigned)Op->getAddrSpace());
126 MIOperands.push_back((unsigned)Op->getSyncScopeID());
127 MIOperands.push_back((unsigned)Op->getBaseAlign().value());
128 MIOperands.push_back((unsigned)Op->getFailureOrdering());
129 }
130
131 auto HashMI = hash_combine_range(MIOperands);
132 OS << format_hex_no_prefix(HashMI, 16, true);
133 return OS.str();
134}
135
136Register VRegRenamer::createVirtualRegister(Register VReg) {
137 assert(VReg.isVirtual() && "Expected Virtual Registers");
138 std::string Name = getInstructionOpcodeHash(*MRI.getVRegDef(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(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 NamedVReg(MO.getReg(), Prefix + getInstructionOpcodeHash(Candidate)));
158 }
159 }
160
161 return !VRegs.empty() ? doVRegRenaming(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(VReg);
168 return RC ? MRI.createVirtualRegister(RC, LowerName)
169 : MRI.createGenericVirtualRegister(MRI.getType(VReg), LowerName);
170}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
Function Alias Analysis false
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
IRTranslator LLVM IR MI
std::map< Register, Register > VRegRenameMap
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
MachineRegisterInfo & MRI
Representation of each machine instruction.
@ MO_CFIIndex
MCCFIInstruction index.
@ MO_Immediate
Immediate operand.
@ MO_ConstantPoolIndex
Address of indexed Constant in Constant Pool.
@ MO_MCSymbol
MCSymbol reference (for debug/eh info)
@ MO_Predicate
Generic predicate for ISel.
@ MO_GlobalAddress
Address of a global value.
@ MO_RegisterMask
Mask of preserved registers.
@ MO_ShuffleMask
Other IR Constant for ISel (shuffle masks)
@ MO_CImmediate
Immediate >64bit operand.
@ MO_BlockAddress
Address of a basic block.
@ MO_DbgInstrRef
Integer indices referring to an instruction+operand.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_LaneMask
Mask to represent active parts of registers.
@ MO_FrameIndex
Abstract Stack Frame Index.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
@ MO_IntrinsicID
Intrinsic ID for ISel.
@ MO_JumpTableIndex
Address of indexed Jump Table for switch.
@ MO_TargetIndex
Target-dependent index+offset operand.
@ MO_Metadata
Metadata reference (for debug info)
@ MO_FPImmediate
Floating-point immediate operand.
@ MO_RegisterLiveOut
Mask of live-out registers.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
hash_code hash_value(const FixedPointSemantics &Val)
LLVM_ABI stable_hash stableHashValue(const MachineOperand &MO, bool SourceQualifyLocalGlobals=false)
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:2042
FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width, bool Upper=false)
format_hex_no_prefix - Output N as a fixed width hexadecimal.
Definition Format.h:177
DWARFExpression::Operation Op
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:307
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:287
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58