LLVM 17.0.0git
SystemZElimCompare.cpp
Go to the documentation of this file.
1//===-- SystemZElimCompare.cpp - Eliminate comparison instructions --------===//
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 pass:
10// (1) tries to remove compares if CC already contains the required information
11// (2) fuses compares and branches into COMPARE AND BRANCH instructions
12//
13//===----------------------------------------------------------------------===//
14
15#include "SystemZ.h"
16#include "SystemZInstrInfo.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/ADT/StringRef.h"
30#include "llvm/MC/MCInstrDesc.h"
31#include <cassert>
32#include <cstdint>
33
34using namespace llvm;
35
36#define DEBUG_TYPE "systemz-elim-compare"
37
38STATISTIC(BranchOnCounts, "Number of branch-on-count instructions");
39STATISTIC(LoadAndTraps, "Number of load-and-trap instructions");
40STATISTIC(EliminatedComparisons, "Number of eliminated comparisons");
41STATISTIC(FusedComparisons, "Number of fused compare-and-branch instructions");
42
43namespace {
44
45// Represents the references to a particular register in one or more
46// instructions.
47struct Reference {
48 Reference() = default;
49
50 Reference &operator|=(const Reference &Other) {
51 Def |= Other.Def;
52 Use |= Other.Use;
53 return *this;
54 }
55
56 explicit operator bool() const { return Def || Use; }
57
58 // True if the register is defined or used in some form, either directly or
59 // via a sub- or super-register.
60 bool Def = false;
61 bool Use = false;
62};
63
64class SystemZElimCompare : public MachineFunctionPass {
65public:
66 static char ID;
67
68 SystemZElimCompare() : MachineFunctionPass(ID) {
70 }
71
72 bool processBlock(MachineBasicBlock &MBB);
74
77 MachineFunctionProperties::Property::NoVRegs);
78 }
79
80private:
81 Reference getRegReferences(MachineInstr &MI, unsigned Reg);
82 bool convertToBRCT(MachineInstr &MI, MachineInstr &Compare,
84 bool convertToLoadAndTrap(MachineInstr &MI, MachineInstr &Compare,
86 bool convertToLoadAndTest(MachineInstr &MI, MachineInstr &Compare,
88 bool convertToLogical(MachineInstr &MI, MachineInstr &Compare,
90 bool adjustCCMasksForInstr(MachineInstr &MI, MachineInstr &Compare,
92 unsigned ConvOpc = 0);
93 bool optimizeCompareZero(MachineInstr &Compare,
95 bool fuseCompareOperations(MachineInstr &Compare,
97
98 const SystemZInstrInfo *TII = nullptr;
99 const TargetRegisterInfo *TRI = nullptr;
100};
101
102char SystemZElimCompare::ID = 0;
103
104} // end anonymous namespace
105
106INITIALIZE_PASS(SystemZElimCompare, DEBUG_TYPE,
107 "SystemZ Comparison Elimination", false, false)
108
109// Returns true if MI is an instruction whose output equals the value in Reg.
110static bool preservesValueOf(MachineInstr &MI, unsigned Reg) {
111 switch (MI.getOpcode()) {
112 case SystemZ::LR:
113 case SystemZ::LGR:
114 case SystemZ::LGFR:
115 case SystemZ::LTR:
116 case SystemZ::LTGR:
117 case SystemZ::LTGFR:
118 case SystemZ::LER:
119 case SystemZ::LDR:
120 case SystemZ::LXR:
121 case SystemZ::LTEBR:
122 case SystemZ::LTDBR:
123 case SystemZ::LTXBR:
124 if (MI.getOperand(1).getReg() == Reg)
125 return true;
126 }
127
128 return false;
129}
130
131// Return true if any CC result of MI would (perhaps after conversion)
132// reflect the value of Reg.
133static bool resultTests(MachineInstr &MI, unsigned Reg) {
134 if (MI.getNumOperands() > 0 && MI.getOperand(0).isReg() &&
135 MI.getOperand(0).isDef() && MI.getOperand(0).getReg() == Reg)
136 return true;
137
138 return (preservesValueOf(MI, Reg));
139}
140
141// Describe the references to Reg or any of its aliases in MI.
142Reference SystemZElimCompare::getRegReferences(MachineInstr &MI, unsigned Reg) {
144 if (MI.isDebugInstr())
145 return Ref;
146
147 for (const MachineOperand &MO : MI.operands()) {
148 if (MO.isReg()) {
149 if (Register MOReg = MO.getReg()) {
150 if (TRI->regsOverlap(MOReg, Reg)) {
151 if (MO.isUse())
152 Ref.Use = true;
153 else if (MO.isDef())
154 Ref.Def = true;
155 }
156 }
157 }
158 }
159 return Ref;
160}
161
162// Return true if this is a load and test which can be optimized the
163// same way as compare instruction.
165 // If we during isel used a load-and-test as a compare with 0, the
166 // def operand is dead.
167 return (MI.getOpcode() == SystemZ::LTEBR ||
168 MI.getOpcode() == SystemZ::LTDBR ||
169 MI.getOpcode() == SystemZ::LTXBR) &&
170 MI.getOperand(0).isDead();
171}
172
173// Return the source register of Compare, which is the unknown value
174// being tested.
175static unsigned getCompareSourceReg(MachineInstr &Compare) {
176 unsigned reg = 0;
177 if (Compare.isCompare())
178 reg = Compare.getOperand(0).getReg();
179 else if (isLoadAndTestAsCmp(Compare))
180 reg = Compare.getOperand(1).getReg();
181 assert(reg);
182
183 return reg;
184}
185
186// Compare compares the result of MI against zero. If MI is an addition
187// of -1 and if CCUsers is a single branch on nonzero, eliminate the addition
188// and convert the branch to a BRCT(G) or BRCTH. Return true on success.
189bool SystemZElimCompare::convertToBRCT(
190 MachineInstr &MI, MachineInstr &Compare,
192 // Check whether we have an addition of -1.
193 unsigned Opcode = MI.getOpcode();
194 unsigned BRCT;
195 if (Opcode == SystemZ::AHI)
196 BRCT = SystemZ::BRCT;
197 else if (Opcode == SystemZ::AGHI)
198 BRCT = SystemZ::BRCTG;
199 else if (Opcode == SystemZ::AIH)
200 BRCT = SystemZ::BRCTH;
201 else
202 return false;
203 if (MI.getOperand(2).getImm() != -1)
204 return false;
205
206 // Check whether we have a single JLH.
207 if (CCUsers.size() != 1)
208 return false;
209 MachineInstr *Branch = CCUsers[0];
210 if (Branch->getOpcode() != SystemZ::BRC ||
211 Branch->getOperand(0).getImm() != SystemZ::CCMASK_ICMP ||
212 Branch->getOperand(1).getImm() != SystemZ::CCMASK_CMP_NE)
213 return false;
214
215 // We already know that there are no references to the register between
216 // MI and Compare. Make sure that there are also no references between
217 // Compare and Branch.
218 unsigned SrcReg = getCompareSourceReg(Compare);
220 for (++MBBI; MBBI != MBBE; ++MBBI)
221 if (getRegReferences(*MBBI, SrcReg))
222 return false;
223
224 // The transformation is OK. Rebuild Branch as a BRCT(G) or BRCTH.
225 MachineOperand Target(Branch->getOperand(2));
226 while (Branch->getNumOperands())
227 Branch->removeOperand(0);
228 Branch->setDesc(TII->get(BRCT));
229 MachineInstrBuilder MIB(*Branch->getParent()->getParent(), Branch);
230 MIB.add(MI.getOperand(0)).add(MI.getOperand(1)).add(Target);
231 // Add a CC def to BRCT(G), since we may have to split them again if the
232 // branch displacement overflows. BRCTH has a 32-bit displacement, so
233 // this is not necessary there.
234 if (BRCT != SystemZ::BRCTH)
235 MIB.addReg(SystemZ::CC, RegState::ImplicitDefine | RegState::Dead);
236 MI.eraseFromParent();
237 return true;
238}
239
240// Compare compares the result of MI against zero. If MI is a suitable load
241// instruction and if CCUsers is a single conditional trap on zero, eliminate
242// the load and convert the branch to a load-and-trap. Return true on success.
243bool SystemZElimCompare::convertToLoadAndTrap(
244 MachineInstr &MI, MachineInstr &Compare,
246 unsigned LATOpcode = TII->getLoadAndTrap(MI.getOpcode());
247 if (!LATOpcode)
248 return false;
249
250 // Check whether we have a single CondTrap that traps on zero.
251 if (CCUsers.size() != 1)
252 return false;
253 MachineInstr *Branch = CCUsers[0];
254 if (Branch->getOpcode() != SystemZ::CondTrap ||
255 Branch->getOperand(0).getImm() != SystemZ::CCMASK_ICMP ||
256 Branch->getOperand(1).getImm() != SystemZ::CCMASK_CMP_EQ)
257 return false;
258
259 // We already know that there are no references to the register between
260 // MI and Compare. Make sure that there are also no references between
261 // Compare and Branch.
262 unsigned SrcReg = getCompareSourceReg(Compare);
264 for (++MBBI; MBBI != MBBE; ++MBBI)
265 if (getRegReferences(*MBBI, SrcReg))
266 return false;
267
268 // The transformation is OK. Rebuild Branch as a load-and-trap.
269 while (Branch->getNumOperands())
270 Branch->removeOperand(0);
271 Branch->setDesc(TII->get(LATOpcode));
272 MachineInstrBuilder(*Branch->getParent()->getParent(), Branch)
273 .add(MI.getOperand(0))
274 .add(MI.getOperand(1))
275 .add(MI.getOperand(2))
276 .add(MI.getOperand(3));
277 MI.eraseFromParent();
278 return true;
279}
280
281// If MI is a load instruction, try to convert it into a LOAD AND TEST.
282// Return true on success.
283bool SystemZElimCompare::convertToLoadAndTest(
284 MachineInstr &MI, MachineInstr &Compare,
286
287 // Try to adjust CC masks for the LOAD AND TEST opcode that could replace MI.
288 unsigned Opcode = TII->getLoadAndTest(MI.getOpcode());
289 if (!Opcode || !adjustCCMasksForInstr(MI, Compare, CCUsers, Opcode))
290 return false;
291
292 // Rebuild to get the CC operand in the right place.
293 auto MIB = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII->get(Opcode));
294 for (const auto &MO : MI.operands())
295 MIB.add(MO);
296 MIB.setMemRefs(MI.memoperands());
297 MI.eraseFromParent();
298
299 // Mark instruction as not raising an FP exception if applicable. We already
300 // verified earlier that this move is valid.
301 if (!Compare.mayRaiseFPException())
302 MIB.setMIFlag(MachineInstr::MIFlag::NoFPExcept);
303
304 return true;
305}
306
307// See if MI is an instruction with an equivalent "logical" opcode that can
308// be used and replace MI. This is useful for EQ/NE comparisons where the
309// "nsw" flag is missing since the "logical" opcode always sets CC to reflect
310// the result being zero or non-zero.
311bool SystemZElimCompare::convertToLogical(
312 MachineInstr &MI, MachineInstr &Compare,
314
315 unsigned ConvOpc = 0;
316 switch (MI.getOpcode()) {
317 case SystemZ::AR: ConvOpc = SystemZ::ALR; break;
318 case SystemZ::ARK: ConvOpc = SystemZ::ALRK; break;
319 case SystemZ::AGR: ConvOpc = SystemZ::ALGR; break;
320 case SystemZ::AGRK: ConvOpc = SystemZ::ALGRK; break;
321 case SystemZ::A: ConvOpc = SystemZ::AL; break;
322 case SystemZ::AY: ConvOpc = SystemZ::ALY; break;
323 case SystemZ::AG: ConvOpc = SystemZ::ALG; break;
324 default: break;
325 }
326 if (!ConvOpc || !adjustCCMasksForInstr(MI, Compare, CCUsers, ConvOpc))
327 return false;
328
329 // Operands should be identical, so just change the opcode and remove the
330 // dead flag on CC.
331 MI.setDesc(TII->get(ConvOpc));
332 MI.clearRegisterDeads(SystemZ::CC);
333 return true;
334}
335
336#ifndef NDEBUG
337static bool isAddWithImmediate(unsigned Opcode) {
338 switch(Opcode) {
339 case SystemZ::AHI:
340 case SystemZ::AHIK:
341 case SystemZ::AGHI:
342 case SystemZ::AGHIK:
343 case SystemZ::AFI:
344 case SystemZ::AIH:
345 case SystemZ::AGFI:
346 return true;
347 default: break;
348 }
349 return false;
350}
351#endif
352
353// The CC users in CCUsers are testing the result of a comparison of some
354// value X against zero and we know that any CC value produced by MI would
355// also reflect the value of X. ConvOpc may be used to pass the transfomed
356// opcode MI will have if this succeeds. Try to adjust CCUsers so that they
357// test the result of MI directly, returning true on success. Leave
358// everything unchanged on failure.
359bool SystemZElimCompare::adjustCCMasksForInstr(
360 MachineInstr &MI, MachineInstr &Compare,
362 unsigned ConvOpc) {
363 unsigned CompareFlags = Compare.getDesc().TSFlags;
364 unsigned CompareCCValues = SystemZII::getCCValues(CompareFlags);
365 int Opcode = (ConvOpc ? ConvOpc : MI.getOpcode());
366 const MCInstrDesc &Desc = TII->get(Opcode);
367 unsigned MIFlags = Desc.TSFlags;
368
369 // If Compare may raise an FP exception, we can only eliminate it
370 // if MI itself would have already raised the exception.
371 if (Compare.mayRaiseFPException()) {
372 // If the caller will change MI to use ConvOpc, only test whether
373 // ConvOpc is suitable; it is on the caller to set the MI flag.
374 if (ConvOpc && !Desc.mayRaiseFPException())
375 return false;
376 // If the caller will not change MI, we test the MI flag here.
377 if (!ConvOpc && !MI.mayRaiseFPException())
378 return false;
379 }
380
381 // See which compare-style condition codes are available.
382 unsigned CCValues = SystemZII::getCCValues(MIFlags);
383 unsigned ReusableCCMask = CCValues;
384 // For unsigned comparisons with zero, only equality makes sense.
385 if (CompareFlags & SystemZII::IsLogical)
386 ReusableCCMask &= SystemZ::CCMASK_CMP_EQ;
387 unsigned OFImplies = 0;
388 bool LogicalMI = false;
389 bool MIEquivalentToCmp = false;
390 if (MI.getFlag(MachineInstr::NoSWrap) &&
391 (MIFlags & SystemZII::CCIfNoSignedWrap)) {
392 // If MI has the NSW flag set in combination with the
393 // SystemZII::CCIfNoSignedWrap flag, all CCValues are valid.
394 }
395 else if ((MIFlags & SystemZII::CCIfNoSignedWrap) &&
396 MI.getOperand(2).isImm()) {
397 // Signed addition of immediate. If adding a positive immediate
398 // overflows, the result must be less than zero. If adding a negative
399 // immediate overflows, the result must be larger than zero (except in
400 // the special case of adding the minimum value of the result range, in
401 // which case we cannot predict whether the result is larger than or
402 // equal to zero).
403 assert(isAddWithImmediate(Opcode) && "Expected an add with immediate.");
404 assert(!MI.mayLoadOrStore() && "Expected an immediate term.");
405 int64_t RHS = MI.getOperand(2).getImm();
406 if (SystemZ::GRX32BitRegClass.contains(MI.getOperand(0).getReg()) &&
407 RHS == INT32_MIN)
408 return false;
410 }
411 else if ((MIFlags & SystemZII::IsLogical) && CCValues) {
412 // Use CCMASK_CMP_EQ to match with CCUsers. On success CCMask:s will be
413 // converted to CCMASK_LOGICAL_ZERO or CCMASK_LOGICAL_NONZERO.
414 LogicalMI = true;
415 ReusableCCMask = SystemZ::CCMASK_CMP_EQ;
416 }
417 else {
418 ReusableCCMask &= SystemZII::getCompareZeroCCMask(MIFlags);
419 assert((ReusableCCMask & ~CCValues) == 0 && "Invalid CCValues");
420 MIEquivalentToCmp =
421 ReusableCCMask == CCValues && CCValues == CompareCCValues;
422 }
423 if (ReusableCCMask == 0)
424 return false;
425
426 if (!MIEquivalentToCmp) {
427 // Now check whether these flags are enough for all users.
429 for (unsigned int I = 0, E = CCUsers.size(); I != E; ++I) {
430 MachineInstr *CCUserMI = CCUsers[I];
431
432 // Fail if this isn't a use of CC that we understand.
433 unsigned Flags = CCUserMI->getDesc().TSFlags;
434 unsigned FirstOpNum;
435 if (Flags & SystemZII::CCMaskFirst)
436 FirstOpNum = 0;
437 else if (Flags & SystemZII::CCMaskLast)
438 FirstOpNum = CCUserMI->getNumExplicitOperands() - 2;
439 else
440 return false;
441
442 // Check whether the instruction predicate treats all CC values
443 // outside of ReusableCCMask in the same way. In that case it
444 // doesn't matter what those CC values mean.
445 unsigned CCValid = CCUserMI->getOperand(FirstOpNum).getImm();
446 unsigned CCMask = CCUserMI->getOperand(FirstOpNum + 1).getImm();
447 assert(CCValid == CompareCCValues && (CCMask & ~CCValid) == 0 &&
448 "Corrupt CC operands of CCUser.");
449 unsigned OutValid = ~ReusableCCMask & CCValid;
450 unsigned OutMask = ~ReusableCCMask & CCMask;
451 if (OutMask != 0 && OutMask != OutValid)
452 return false;
453
454 AlterMasks.push_back(&CCUserMI->getOperand(FirstOpNum));
455 AlterMasks.push_back(&CCUserMI->getOperand(FirstOpNum + 1));
456 }
457
458 // All users are OK. Adjust the masks for MI.
459 for (unsigned I = 0, E = AlterMasks.size(); I != E; I += 2) {
460 AlterMasks[I]->setImm(CCValues);
461 unsigned CCMask = AlterMasks[I + 1]->getImm();
462 if (LogicalMI) {
463 // Translate the CCMask into its "logical" value.
464 CCMask = (CCMask == SystemZ::CCMASK_CMP_EQ ?
466 CCMask &= CCValues; // Logical subtracts never set CC=0.
467 } else {
468 if (CCMask & ~ReusableCCMask)
469 CCMask = (CCMask & ReusableCCMask) | (CCValues & ~ReusableCCMask);
470 CCMask |= (CCMask & OFImplies) ? SystemZ::CCMASK_ARITH_OVERFLOW : 0;
471 }
472 AlterMasks[I + 1]->setImm(CCMask);
473 }
474 }
475
476 // CC is now live after MI.
477 if (!ConvOpc)
478 MI.clearRegisterDeads(SystemZ::CC);
479
480 // Check if MI lies before Compare.
481 bool BeforeCmp = false;
482 MachineBasicBlock::iterator MBBI = MI, MBBE = MI.getParent()->end();
483 for (++MBBI; MBBI != MBBE; ++MBBI)
484 if (MBBI == Compare) {
485 BeforeCmp = true;
486 break;
487 }
488
489 // Clear any intervening kills of CC.
490 if (BeforeCmp) {
492 for (++MBBI; MBBI != MBBE; ++MBBI)
493 MBBI->clearRegisterKills(SystemZ::CC, TRI);
494 }
495
496 return true;
497}
498
499// Return true if Compare is a comparison against zero.
500static bool isCompareZero(MachineInstr &Compare) {
501 switch (Compare.getOpcode()) {
502 case SystemZ::LTEBRCompare:
503 case SystemZ::LTDBRCompare:
504 case SystemZ::LTXBRCompare:
505 return true;
506
507 default:
508 if (isLoadAndTestAsCmp(Compare))
509 return true;
510 return Compare.getNumExplicitOperands() == 2 &&
511 Compare.getOperand(1).isImm() && Compare.getOperand(1).getImm() == 0;
512 }
513}
514
515// Try to optimize cases where comparison instruction Compare is testing
516// a value against zero. Return true on success and if Compare should be
517// deleted as dead. CCUsers is the list of instructions that use the CC
518// value produced by Compare.
519bool SystemZElimCompare::optimizeCompareZero(
521 if (!isCompareZero(Compare))
522 return false;
523
524 // Search back for CC results that are based on the first operand.
525 unsigned SrcReg = getCompareSourceReg(Compare);
526 MachineBasicBlock &MBB = *Compare.getParent();
527 Reference CCRefs;
528 Reference SrcRefs;
530 std::next(MachineBasicBlock::reverse_iterator(&Compare)),
531 MBBE = MBB.rend(); MBBI != MBBE;) {
532 MachineInstr &MI = *MBBI++;
533 if (resultTests(MI, SrcReg)) {
534 // Try to remove both MI and Compare by converting a branch to BRCT(G).
535 // or a load-and-trap instruction. We don't care in this case whether
536 // CC is modified between MI and Compare.
537 if (!CCRefs.Use && !SrcRefs) {
538 if (convertToBRCT(MI, Compare, CCUsers)) {
539 BranchOnCounts += 1;
540 return true;
541 }
542 if (convertToLoadAndTrap(MI, Compare, CCUsers)) {
543 LoadAndTraps += 1;
544 return true;
545 }
546 }
547 // Try to eliminate Compare by reusing a CC result from MI.
548 if ((!CCRefs && convertToLoadAndTest(MI, Compare, CCUsers)) ||
549 (!CCRefs.Def &&
550 (adjustCCMasksForInstr(MI, Compare, CCUsers) ||
551 convertToLogical(MI, Compare, CCUsers)))) {
552 EliminatedComparisons += 1;
553 return true;
554 }
555 }
556 SrcRefs |= getRegReferences(MI, SrcReg);
557 if (SrcRefs.Def)
558 break;
559 CCRefs |= getRegReferences(MI, SystemZ::CC);
560 if (CCRefs.Use && CCRefs.Def)
561 break;
562 // Eliminating a Compare that may raise an FP exception will move
563 // raising the exception to some earlier MI. We cannot do this if
564 // there is anything in between that might change exception flags.
565 if (Compare.mayRaiseFPException() &&
566 (MI.isCall() || MI.hasUnmodeledSideEffects()))
567 break;
568 }
569
570 // Also do a forward search to handle cases where an instruction after the
571 // compare can be converted, like
572 // LTEBRCompare %f0s, %f0s; %f2s = LER %f0s => LTEBRCompare %f2s, %f0s
573 auto MIRange = llvm::make_range(
574 std::next(MachineBasicBlock::iterator(&Compare)), MBB.end());
575 for (MachineInstr &MI : llvm::make_early_inc_range(MIRange)) {
576 if (preservesValueOf(MI, SrcReg)) {
577 // Try to eliminate Compare by reusing a CC result from MI.
578 if (convertToLoadAndTest(MI, Compare, CCUsers)) {
579 EliminatedComparisons += 1;
580 return true;
581 }
582 }
583 if (getRegReferences(MI, SrcReg).Def)
584 return false;
585 if (getRegReferences(MI, SystemZ::CC))
586 return false;
587 }
588
589 return false;
590}
591
592// Try to fuse comparison instruction Compare into a later branch.
593// Return true on success and if Compare is therefore redundant.
594bool SystemZElimCompare::fuseCompareOperations(
596 // See whether we have a single branch with which to fuse.
597 if (CCUsers.size() != 1)
598 return false;
599 MachineInstr *Branch = CCUsers[0];
601 switch (Branch->getOpcode()) {
602 case SystemZ::BRC:
604 break;
605 case SystemZ::CondReturn:
607 break;
608 case SystemZ::CallBCR:
610 break;
611 case SystemZ::CondTrap:
613 break;
614 default:
615 return false;
616 }
617
618 // See whether we have a comparison that can be fused.
619 unsigned FusedOpcode =
620 TII->getFusedCompare(Compare.getOpcode(), Type, &Compare);
621 if (!FusedOpcode)
622 return false;
623
624 // Make sure that the operands are available at the branch.
625 // SrcReg2 is the register if the source operand is a register,
626 // 0 if the source operand is immediate, and the base register
627 // if the source operand is memory (index is not supported).
628 Register SrcReg = Compare.getOperand(0).getReg();
629 Register SrcReg2 =
630 Compare.getOperand(1).isReg() ? Compare.getOperand(1).getReg() : Register();
632 for (++MBBI; MBBI != MBBE; ++MBBI)
633 if (MBBI->modifiesRegister(SrcReg, TRI) ||
634 (SrcReg2 && MBBI->modifiesRegister(SrcReg2, TRI)))
635 return false;
636
637 // Read the branch mask, target (if applicable), regmask (if applicable).
638 MachineOperand CCMask(MBBI->getOperand(1));
639 assert((CCMask.getImm() & ~SystemZ::CCMASK_ICMP) == 0 &&
640 "Invalid condition-code mask for integer comparison");
641 // This is only valid for CompareAndBranch and CompareAndSibcall.
642 MachineOperand Target(MBBI->getOperand(
645 const uint32_t *RegMask;
647 RegMask = MBBI->getOperand(3).getRegMask();
648
649 // Clear out all current operands.
650 int CCUse = MBBI->findRegisterUseOperandIdx(SystemZ::CC, false, TRI);
651 assert(CCUse >= 0 && "BRC/BCR must use CC");
652 Branch->removeOperand(CCUse);
653 // Remove regmask (sibcall).
655 Branch->removeOperand(3);
656 // Remove target (branch or sibcall).
659 Branch->removeOperand(2);
660 Branch->removeOperand(1);
661 Branch->removeOperand(0);
662
663 // Rebuild Branch as a fused compare and branch.
664 // SrcNOps is the number of MI operands of the compare instruction
665 // that we need to copy over.
666 unsigned SrcNOps = 2;
667 if (FusedOpcode == SystemZ::CLT || FusedOpcode == SystemZ::CLGT)
668 SrcNOps = 3;
669 Branch->setDesc(TII->get(FusedOpcode));
670 MachineInstrBuilder MIB(*Branch->getParent()->getParent(), Branch);
671 for (unsigned I = 0; I < SrcNOps; I++)
672 MIB.add(Compare.getOperand(I));
673 MIB.add(CCMask);
674
676 // Only conditional branches define CC, as they may be converted back
677 // to a non-fused branch because of a long displacement. Conditional
678 // returns don't have that problem.
679 MIB.add(Target).addReg(SystemZ::CC,
681 }
682
684 MIB.add(Target);
685 MIB.addRegMask(RegMask);
686 }
687
688 // Clear any intervening kills of SrcReg and SrcReg2.
689 MBBI = Compare;
690 for (++MBBI; MBBI != MBBE; ++MBBI) {
691 MBBI->clearRegisterKills(SrcReg, TRI);
692 if (SrcReg2)
693 MBBI->clearRegisterKills(SrcReg2, TRI);
694 }
695 FusedComparisons += 1;
696 return true;
697}
698
699// Process all comparison instructions in MBB. Return true if something
700// changed.
701bool SystemZElimCompare::processBlock(MachineBasicBlock &MBB) {
702 bool Changed = false;
703
704 // Walk backwards through the block looking for comparisons, recording
705 // all CC users as we go. The subroutines can delete Compare and
706 // instructions before it.
707 LivePhysRegs LiveRegs(*TRI);
708 LiveRegs.addLiveOuts(MBB);
709 bool CompleteCCUsers = !LiveRegs.contains(SystemZ::CC);
712 while (MBBI != MBB.begin()) {
713 MachineInstr &MI = *--MBBI;
714 if (CompleteCCUsers && (MI.isCompare() || isLoadAndTestAsCmp(MI)) &&
715 (optimizeCompareZero(MI, CCUsers) ||
716 fuseCompareOperations(MI, CCUsers))) {
717 ++MBBI;
718 MI.eraseFromParent();
719 Changed = true;
720 CCUsers.clear();
721 continue;
722 }
723
724 if (MI.definesRegister(SystemZ::CC)) {
725 CCUsers.clear();
726 CompleteCCUsers = true;
727 }
728 if (MI.readsRegister(SystemZ::CC) && CompleteCCUsers)
729 CCUsers.push_back(&MI);
730 }
731 return Changed;
732}
733
734bool SystemZElimCompare::runOnMachineFunction(MachineFunction &F) {
735 if (skipFunction(F.getFunction()))
736 return false;
737
738 TII = F.getSubtarget<SystemZSubtarget>().getInstrInfo();
739 TRI = &TII->getRegisterInfo();
740
741 bool Changed = false;
742 for (auto &MBB : F)
743 Changed |= processBlock(MBB);
744
745 return Changed;
746}
747
749 return new SystemZElimCompare();
750}
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1260
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
const char LLVMTargetMachineRef TM
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
static bool resultTests(MachineInstr &MI, unsigned Reg)
unsigned Reg
static unsigned getCompareSourceReg(MachineInstr &Compare)
static bool isLoadAndTestAsCmp(MachineInstr &MI)
#define DEBUG_TYPE
static bool isCompareZero(MachineInstr &Compare)
static bool isAddWithImmediate(unsigned Opcode)
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition: Value.cpp:467
Value * RHS
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:308
A set of physical registers with utility functions to track liveness when walking backward/forward th...
Definition: LivePhysRegs.h:50
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:198
bool mayRaiseFPException() const
Return true if this instruction may raise a floating-point exception.
Definition: MCInstrDesc.h:446
reverse_iterator rend()
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
virtual MachineFunctionProperties getRequiredProperties() const
Properties which a MachineFunction may have at a given point in time.
MachineFunctionProperties & set(Property P)
const MachineInstrBuilder & add(const MachineOperand &MO) const
Representation of each machine instruction.
Definition: MachineInstr.h:68
unsigned getNumExplicitOperands() const
Returns the number of non-implicit operands.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:513
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:526
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:577
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Target - Wrapper for Target specific information.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ Dead
Unused definition.
static unsigned getCCValues(unsigned int Flags)
static unsigned getCompareZeroCCMask(unsigned int Flags)
const unsigned CCMASK_LOGICAL_ZERO
Definition: SystemZ.h:58
const unsigned CCMASK_CMP_GT
Definition: SystemZ.h:37
const unsigned CCMASK_CMP_EQ
Definition: SystemZ.h:35
const unsigned CCMASK_ICMP
Definition: SystemZ.h:47
const unsigned CCMASK_ARITH_OVERFLOW
Definition: SystemZ.h:54
const unsigned CCMASK_CMP_LT
Definition: SystemZ.h:36
const unsigned CCMASK_CMP_NE
Definition: SystemZ.h:38
const unsigned CCMASK_LOGICAL_NONZERO
Definition: SystemZ.h:59
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void initializeSystemZElimComparePass(PassRegistry &)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:721
FunctionPass * createSystemZElimComparePass(SystemZTargetMachine &TM)
@ Ref
The access may reference the value stored in memory.
bool operator|=(SparseBitVector< ElementSize > &LHS, const SparseBitVector< ElementSize > *RHS)