LLVM 23.0.0git
CSEInfo.cpp
Go to the documentation of this file.
1//===- CSEInfo.cpp ------------------------------===//
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//
10//===----------------------------------------------------------------------===//
14#include "llvm/Support/Error.h"
15
16#define DEBUG_TYPE "cseinfo"
17
18using namespace llvm;
23 "Analysis containing CSE Info", false, true)
24
25/// -------- UniqueMachineInstr -------------//
26
28 GISelInstProfileBuilder(ID, MI->getMF()->getRegInfo()).addNodeID(MI);
29}
30/// -----------------------------------------
31
32/// --------- CSEConfigFull ---------- ///
34 switch (Opc) {
35 default:
36 break;
37 case TargetOpcode::G_ADD:
38 case TargetOpcode::G_AND:
39 case TargetOpcode::G_ASHR:
40 case TargetOpcode::G_LSHR:
41 case TargetOpcode::G_MUL:
42 case TargetOpcode::G_OR:
43 case TargetOpcode::G_SHL:
44 case TargetOpcode::G_SUB:
45 case TargetOpcode::G_XOR:
46 case TargetOpcode::G_UDIV:
47 case TargetOpcode::G_SDIV:
48 case TargetOpcode::G_UREM:
49 case TargetOpcode::G_SREM:
50 case TargetOpcode::G_CONSTANT:
51 case TargetOpcode::G_FCONSTANT:
52 case TargetOpcode::G_IMPLICIT_DEF:
53 case TargetOpcode::G_ZEXT:
54 case TargetOpcode::G_SEXT:
55 case TargetOpcode::G_ANYEXT:
56 case TargetOpcode::G_UNMERGE_VALUES:
57 case TargetOpcode::G_TRUNC:
58 case TargetOpcode::G_PTR_ADD:
59 case TargetOpcode::G_EXTRACT:
60 case TargetOpcode::G_SELECT:
61 case TargetOpcode::G_BUILD_VECTOR:
62 case TargetOpcode::G_BUILD_VECTOR_TRUNC:
63 case TargetOpcode::G_SEXT_INREG:
64 case TargetOpcode::G_FADD:
65 case TargetOpcode::G_FSUB:
66 case TargetOpcode::G_FMUL:
67 case TargetOpcode::G_FDIV:
68 case TargetOpcode::G_FABS:
69 // TODO: support G_FNEG.
70 case TargetOpcode::G_FMAXNUM:
71 case TargetOpcode::G_FMINNUM:
72 case TargetOpcode::G_FMAXNUM_IEEE:
73 case TargetOpcode::G_FMINNUM_IEEE:
74 return true;
75 }
76 return false;
77}
78
80 return Opc == TargetOpcode::G_CONSTANT || Opc == TargetOpcode::G_FCONSTANT ||
81 Opc == TargetOpcode::G_IMPLICIT_DEF;
82}
83
84std::unique_ptr<CSEConfigBase>
86 std::unique_ptr<CSEConfigBase> Config;
87 if (Level == CodeGenOptLevel::None)
88 Config = std::make_unique<CSEConfigConstantOnly>();
89 else
90 Config = std::make_unique<CSEConfigFull>();
91 return Config;
92}
93
94/// -----------------------------------------
95
96/// -------- GISelCSEInfo -------------//
98 this->MF = &MF;
99 this->MRI = &MF.getRegInfo();
100}
101
103
104bool GISelCSEInfo::isUniqueMachineInstValid(
105 const UniqueMachineInstr &UMI) const {
106 // Should we check here and assert that the instruction has been fully
107 // constructed?
108 // FIXME: Any other checks required to be done here? Remove this method if
109 // none.
110 return true;
111}
112
113void GISelCSEInfo::invalidateUniqueMachineInstr(UniqueMachineInstr *UMI) {
114 bool Removed = CSEMap.RemoveNode(UMI);
115 (void)Removed;
116 assert(Removed && "Invalidation called on invalid UMI");
117 // FIXME: Should UMI be deallocated/destroyed?
118}
119
120UniqueMachineInstr *GISelCSEInfo::getNodeIfExists(FoldingSetNodeID &ID,
122 void *&InsertPos) {
123 auto *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
124 if (Node) {
125 if (!isUniqueMachineInstValid(*Node)) {
126 invalidateUniqueMachineInstr(Node);
127 return nullptr;
128 }
129
130 if (Node->MI->getParent() != MBB)
131 return nullptr;
132 }
133 return Node;
134}
135
136void GISelCSEInfo::insertNode(UniqueMachineInstr *UMI, void *InsertPos) {
138 assert(UMI);
139 UniqueMachineInstr *MaybeNewNode = UMI;
140 if (InsertPos)
141 CSEMap.InsertNode(UMI, InsertPos);
142 else
143 MaybeNewNode = CSEMap.GetOrInsertNode(UMI);
144 if (MaybeNewNode != UMI) {
145 // A similar node exists in the folding set. Let's ignore this one.
146 return;
147 }
148 assert(InstrMapping.count(UMI->MI) == 0 &&
149 "This instruction should not be in the map");
150 InstrMapping[UMI->MI] = MaybeNewNode;
151}
152
153UniqueMachineInstr *GISelCSEInfo::getUniqueInstrForMI(const MachineInstr *MI) {
154 assert(shouldCSE(MI->getOpcode()) && "Trying to CSE an unsupported Node");
155 auto *Node = new (UniqueInstrAllocator) UniqueMachineInstr(MI);
156 return Node;
157}
158
159void GISelCSEInfo::insertInstr(MachineInstr *MI, void *InsertPos) {
160 assert(MI);
161 // If it exists in temporary insts, remove it.
162 TemporaryInsts.remove(MI);
163 auto *Node = getUniqueInstrForMI(MI);
164 insertNode(Node, InsertPos);
165}
166
167MachineInstr *GISelCSEInfo::getMachineInstrIfExists(FoldingSetNodeID &ID,
169 void *&InsertPos) {
171 if (auto *Inst = getNodeIfExists(ID, MBB, InsertPos)) {
172 LLVM_DEBUG(dbgs() << "CSEInfo::Found Instr " << *Inst->MI);
173 return const_cast<MachineInstr *>(Inst->MI);
174 }
175 return nullptr;
176}
177
179#ifndef NDEBUG
180 ++OpcodeHitTable[Opc];
181#endif
182 // Else do nothing.
183}
184
186 if (shouldCSE(MI->getOpcode())) {
187 TemporaryInsts.insert(MI);
188 LLVM_DEBUG(dbgs() << "CSEInfo::Recording new MI " << *MI);
189 }
190}
191
193 assert(shouldCSE(MI->getOpcode()) && "Invalid instruction for CSE");
194 auto *UMI = InstrMapping.lookup(MI);
195 LLVM_DEBUG(dbgs() << "CSEInfo::Handling recorded MI " << *MI);
196 if (UMI) {
197 // Invalidate this MI.
198 invalidateUniqueMachineInstr(UMI);
199 InstrMapping.erase(MI);
200 }
201 /// Now insert the new instruction.
202 if (UMI) {
203 /// We'll reuse the same UniqueMachineInstr to avoid the new
204 /// allocation.
205 *UMI = UniqueMachineInstr(MI);
206 insertNode(UMI, nullptr);
207 } else {
208 /// This is a new instruction. Allocate a new UniqueMachineInstr and
209 /// Insert.
210 insertInstr(MI);
211 }
212}
213
215 if (auto *UMI = InstrMapping.lookup(MI)) {
216 invalidateUniqueMachineInstr(UMI);
217 InstrMapping.erase(MI);
218 }
219 TemporaryInsts.remove(MI);
220}
221
223 if (HandlingRecordedInstrs)
224 return;
225 HandlingRecordedInstrs = true;
226 while (!TemporaryInsts.empty()) {
227 auto *MI = TemporaryInsts.pop_back_val();
229 }
230 HandlingRecordedInstrs = false;
231}
232
233bool GISelCSEInfo::shouldCSE(unsigned Opc) const {
234 assert(CSEOpt.get() && "CSEConfig not set");
235 return CSEOpt->shouldCSEOpc(Opc);
236}
237
241 // For now, perform erase, followed by insert.
244}
246
248 setMF(MF);
249 for (auto &MBB : MF) {
250 for (MachineInstr &MI : MBB) {
251 if (!shouldCSE(MI.getOpcode()))
252 continue;
253 LLVM_DEBUG(dbgs() << "CSEInfo::Add MI: " << MI);
254 insertInstr(&MI);
255 }
256 }
257}
258
260 print();
261 CSEMap.clear();
262 InstrMapping.clear();
263 UniqueInstrAllocator.Reset();
264 TemporaryInsts.clear();
265 CSEOpt.reset();
266 MRI = nullptr;
267 MF = nullptr;
268#ifndef NDEBUG
269 OpcodeHitTable.clear();
270#endif
271}
272
273#ifndef NDEBUG
274static const char *stringify(const MachineInstr *MI, std::string &S) {
275 raw_string_ostream OS(S);
276 OS << *MI;
277 return OS.str().c_str();
278}
279#endif
280
282#ifndef NDEBUG
283 std::string S1, S2;
285 // For each instruction in map from MI -> UMI,
286 // Profile(MI) and make sure UMI is found for that profile.
287 for (auto &It : InstrMapping) {
288 FoldingSetNodeID TmpID;
289 GISelInstProfileBuilder(TmpID, *MRI).addNodeID(It.first);
290 void *InsertPos;
291 UniqueMachineInstr *FoundNode =
292 CSEMap.FindNodeOrInsertPos(TmpID, InsertPos);
293 if (FoundNode != It.second)
294 return createStringError(std::errc::not_supported,
295 "CSEMap mismatch, InstrMapping has MIs without "
296 "corresponding Nodes in CSEMap:\n%s",
297 stringify(It.second->MI, S1));
298 }
299
300 // For every node in the CSEMap, make sure that the InstrMapping
301 // points to it.
302 for (const UniqueMachineInstr &UMI : CSEMap) {
303 if (!InstrMapping.count(UMI.MI))
304 return createStringError(std::errc::not_supported,
305 "Node in CSE without InstrMapping:\n%s",
306 stringify(UMI.MI, S1));
307
308 if (InstrMapping[UMI.MI] != &UMI)
309 return createStringError(std::make_error_code(std::errc::not_supported),
310 "Mismatch in CSE mapping:\n%s\n%s",
311 stringify(InstrMapping[UMI.MI]->MI, S1),
312 stringify(UMI.MI, S2));
313 }
314#endif
315 return Error::success();
316}
317
319 LLVM_DEBUG({
320 for (auto &It : OpcodeHitTable)
321 dbgs() << "CSEInfo::CSE Hit for Opc " << It.first << " : " << It.second
322 << "\n";
323 });
324}
325/// -----------------------------------------
326// ---- Profiling methods for FoldingSetNode --- //
329 addNodeIDMBB(MI->getParent());
330 addNodeIDOpcode(MI->getOpcode());
331 for (const auto &Op : MI->operands())
333 addNodeIDFlag(MI->getFlags());
334 return *this;
335}
336
339 ID.AddInteger(Opc);
340 return *this;
341}
342
345 uint64_t Val = Ty.getUniqueRAWLLTData();
346 ID.AddInteger(Val);
347 return *this;
348}
349
352 ID.AddPointer(RC);
353 return *this;
354}
355
358 ID.AddPointer(RB);
359 return *this;
360}
361
363 MachineRegisterInfo::VRegAttrs Attrs) const {
364 addNodeIDRegType(Attrs.Ty);
365
366 const RegClassOrRegBank &RCOrRB = Attrs.RCOrRB;
367 if (RCOrRB) {
368 if (const auto *RB = dyn_cast_if_present<const RegisterBank *>(RCOrRB))
370 else
372 }
373 return *this;
374}
375
378 ID.AddInteger(Imm);
379 return *this;
380}
381
384 ID.AddInteger(Reg.id());
385 return *this;
386}
387
393
396 ID.AddPointer(MBB);
397 return *this;
398}
399
402 if (Flag)
403 ID.AddInteger(Flag);
404 return *this;
405}
406
409 addNodeIDRegType(MRI.getVRegAttrs(Reg));
410 return *this;
411}
412
414 const MachineOperand &MO) const {
415 if (MO.isReg()) {
416 Register Reg = MO.getReg();
417 if (!MO.isDef())
418 addNodeIDRegNum(Reg);
419
420 // Profile the register properties.
421 addNodeIDReg(Reg);
422 assert(!MO.isImplicit() && "Unhandled case");
423 } else if (MO.isImm())
424 ID.AddInteger(MO.getImm());
425 else if (MO.isCImm())
426 ID.AddPointer(MO.getCImm());
427 else if (MO.isFPImm())
428 ID.AddPointer(MO.getFPImm());
429 else if (MO.isPredicate())
430 ID.AddInteger(MO.getPredicate());
431 else
432 llvm_unreachable("Unhandled operand type");
433 // Handle other types
434 return *this;
435}
436
438GISelCSEAnalysisWrapper::get(std::unique_ptr<CSEConfigBase> CSEOpt,
439 bool Recompute) {
440 if (!AlreadyComputed || Recompute) {
441 Info.releaseMemory();
442 Info.setCSEConfig(std::move(CSEOpt));
443 Info.analyze(*MF);
444 AlreadyComputed = true;
445 }
446 return Info;
447}
452
455 Wrapper.setMF(MF);
456 return false;
457}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
constexpr LLT S1
MachineBasicBlock & MBB
static const char * stringify(const MachineInstr *MI, std::string &S)
Definition CSEInfo.cpp:274
Provides analysis for continuously CSEing during GISel passes.
#define DEBUG_TYPE
IRTranslator LLVM IR MI
Load MIR Sample Profile
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
#define LLVM_DEBUG(...)
Definition Debug.h:114
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
bool shouldCSEOpc(unsigned Opc) override
Definition CSEInfo.cpp:79
bool shouldCSEOpc(unsigned Opc) override
------— CSEConfigFull -------— ///
Definition CSEInfo.cpp:33
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
FoldingSetNodeID - This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:209
The actual analysis pass wrapper.
Definition CSEInfo.h:229
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
Definition CSEInfo.h:243
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition CSEInfo.cpp:448
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
Definition CSEInfo.cpp:453
LLVM_ABI GISelCSEInfo & get(std::unique_ptr< CSEConfigBase > CSEOpt, bool ReCompute=false)
Takes a CSEConfigBase object that defines what opcodes get CSEd.
Definition CSEInfo.cpp:438
The CSE Analysis object.
Definition CSEInfo.h:71
bool shouldCSE(unsigned Opc) const
Definition CSEInfo.cpp:233
~GISelCSEInfo() override
void changingInstr(MachineInstr &MI) override
This instruction is about to be mutated in some way.
Definition CSEInfo.cpp:240
void analyze(MachineFunction &MF)
Definition CSEInfo.cpp:247
void changedInstr(MachineInstr &MI) override
This instruction was mutated in some way.
Definition CSEInfo.cpp:245
void recordNewInstruction(MachineInstr *MI)
Records a newly created inst in a list and lazily insert it to the CSEMap.
Definition CSEInfo.cpp:185
void setMF(MachineFunction &MF)
-----— GISelCSEInfo ----------—//
Definition CSEInfo.cpp:97
void erasingInstr(MachineInstr &MI) override
An instruction is about to be erased.
Definition CSEInfo.cpp:238
void countOpcodeHit(unsigned Opc)
Definition CSEInfo.cpp:178
void handleRecordedInsts()
Use this callback to insert all the recorded instructions.
Definition CSEInfo.cpp:222
void handleRecordedInst(MachineInstr *MI)
Use this callback to inform CSE about a newly fully created instruction.
Definition CSEInfo.cpp:192
void handleRemoveInst(MachineInstr *MI)
Remove this inst from the CSE map.
Definition CSEInfo.cpp:214
void createdInstr(MachineInstr &MI) override
An instruction has been created and inserted into the function.
Definition CSEInfo.cpp:239
LLVM_ABI const GISelInstProfileBuilder & addNodeIDOpcode(unsigned Opc) const
Definition CSEInfo.cpp:338
LLVM_ABI const GISelInstProfileBuilder & addNodeIDRegNum(Register Reg) const
Definition CSEInfo.cpp:383
LLVM_ABI const GISelInstProfileBuilder & addNodeIDFlag(unsigned Flag) const
Definition CSEInfo.cpp:401
LLVM_ABI const GISelInstProfileBuilder & addNodeIDImmediate(int64_t Imm) const
Definition CSEInfo.cpp:377
LLVM_ABI const GISelInstProfileBuilder & addNodeIDReg(Register Reg) const
Definition CSEInfo.cpp:408
LLVM_ABI const GISelInstProfileBuilder & addNodeID(const MachineInstr *MI) const
Definition CSEInfo.cpp:328
LLVM_ABI const GISelInstProfileBuilder & addNodeIDMBB(const MachineBasicBlock *MBB) const
Definition CSEInfo.cpp:395
GISelInstProfileBuilder(FoldingSetNodeID &ID, const MachineRegisterInfo &MRI)
Definition CSEInfo.h:176
LLVM_ABI const GISelInstProfileBuilder & addNodeIDRegType(const LLT Ty) const
Definition CSEInfo.cpp:344
LLVM_ABI const GISelInstProfileBuilder & addNodeIDMachineOperand(const MachineOperand &MO) const
Definition CSEInfo.cpp:413
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
const ConstantInt * getCImm() const
bool isCImm() const
isCImm - Test if this is a MO_CImmediate operand.
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
Register getReg() const
getReg - Returns the register number.
const ConstantFP * getFPImm() const
unsigned getPredicate() const
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
bool isFPImm() const
isFPImm - Tests if this is a MO_FPImmediate operand.
This class implements the register bank concept.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
A class that wraps MachineInstrs and derives from FoldingSetNode in order to be uniqued in a CSEMap.
Definition CSEInfo.h:31
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
PointerUnion< const TargetRegisterClass *, const RegisterBank * > RegClassOrRegBank
Convenient type to represent either a register class or a register bank.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1305
LLVM_ABI std::unique_ptr< CSEConfigBase > getStandardCSEConfigForOpt(CodeGenOptLevel Level)
Definition CSEInfo.cpp:85
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:82
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
All attributes(register class or bank and low-level type) a virtual register can have.