LLVM 24.0.0git
TwoAddressInstructionPass.cpp
Go to the documentation of this file.
1//===- TwoAddressInstructionPass.cpp - Two-Address instruction pass -------===//
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 file implements the TwoAddress instruction pass which is used
10// by most register allocators. Two-Address instructions are rewritten
11// from:
12//
13// A = B op C
14//
15// to:
16//
17// A = B
18// A op= C
19//
20// Note that if a register allocator chooses to use this pass, that it
21// has to be capable of handling the non-SSA nature of these rewritten
22// virtual registers.
23//
24// It is also worth noting that the duplicate operand of the two
25// address instruction is removed.
26//
27//===----------------------------------------------------------------------===//
28
30#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/Statistic.h"
46#include "llvm/CodeGen/Passes.h"
53#include "llvm/MC/MCInstrDesc.h"
54#include "llvm/Pass.h"
57#include "llvm/Support/Debug.h"
61#include <cassert>
62#include <iterator>
63#include <utility>
64
65using namespace llvm;
66
67#define DEBUG_TYPE "twoaddressinstruction"
68
69STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
70STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
71STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
72STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
73STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up");
74STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down");
75
76// Temporary flag to disable rescheduling.
77static cl::opt<bool>
78EnableRescheduling("twoaddr-reschedule",
79 cl::desc("Coalesce copies by rescheduling (default=true)"),
80 cl::init(true), cl::Hidden);
81
83 "twoaddr-analyze-revcopy-tied",
84 cl::desc("Analyze tied operands when looking for reversed copy chain"),
85 cl::init(true), cl::Hidden);
86
87// Limit the number of dataflow edges to traverse when evaluating the benefit
88// of commuting operands.
90 "dataflow-edge-limit", cl::Hidden, cl::init(10),
91 cl::desc("Maximum number of dataflow edges to traverse when evaluating "
92 "the benefit of commuting operands"));
93
94namespace {
95
96class TwoAddressInstructionImpl {
97 MachineFunction *MF = nullptr;
98 const TargetInstrInfo *TII = nullptr;
99 const TargetRegisterInfo *TRI = nullptr;
100 const InstrItineraryData *InstrItins = nullptr;
101 MachineRegisterInfo *MRI = nullptr;
102 LiveVariables *LV = nullptr;
103 LiveIntervals *LIS = nullptr;
105
106 // The current basic block being processed.
107 MachineBasicBlock *MBB = nullptr;
108
109 // Keep track the distance of a MI from the start of the current basic block.
111
112 // Set of already processed instructions in the current block.
114
115 // A map from virtual registers to physical registers which are likely targets
116 // to be coalesced to due to copies from physical registers to virtual
117 // registers. e.g. v1024 = move r0.
119
120 // A map from virtual registers to physical registers which are likely targets
121 // to be coalesced to due to copies to physical registers from virtual
122 // registers. e.g. r1 = move v1024.
124
125 MachineInstr *getSingleDef(Register Reg, MachineBasicBlock *BB) const;
126
127 bool isRevCopyChain(Register FromReg, Register ToReg, int Maxlen);
128
129 bool noUseAfterLastDef(Register Reg, unsigned Dist, unsigned &LastDef);
130
131 bool isCopyToReg(MachineInstr &MI, Register &SrcReg, Register &DstReg,
132 bool &IsSrcPhys, bool &IsDstPhys) const;
133
134 bool isPlainlyKilled(const MachineInstr *MI, LiveRange &LR) const;
135 bool isPlainlyKilled(const MachineInstr *MI, Register Reg) const;
136 bool isPlainlyKilled(const MachineOperand &MO) const;
137
138 bool isKilled(MachineInstr &MI, Register Reg, bool allowFalsePositives) const;
139
140 MachineInstr *findOnlyInterestingUse(Register Reg, MachineBasicBlock *MBB,
141 bool &IsCopy, Register &DstReg,
142 bool &IsDstPhys) const;
143
144 bool regsAreCompatible(Register RegA, Register RegB) const;
145
146 void removeMapRegEntry(const MachineOperand &MO,
147 DenseMap<Register, Register> &RegMap) const;
148
149 void removeClobberedSrcRegMap(MachineInstr *MI);
150
151 bool regOverlapsSet(const SmallVectorImpl<Register> &Set, Register Reg) const;
152
153 bool isProfitableToCommute(Register RegA, Register RegB, Register RegC,
154 MachineInstr *MI, unsigned Dist);
155
156 bool commuteInstruction(MachineInstr *MI, unsigned DstIdx,
157 unsigned RegBIdx, unsigned RegCIdx, unsigned Dist);
158
159 bool isProfitableToConv3Addr(Register RegA, Register RegB);
160
161 bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
163 Register RegB, unsigned &Dist);
164
165 bool isDefTooClose(Register Reg, unsigned Dist, MachineInstr *MI);
166
167 bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
169 bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
171
172 bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
174 unsigned SrcIdx, unsigned DstIdx,
175 unsigned &Dist, bool shouldOnlyCommute);
176
177 bool tryInstructionCommute(MachineInstr *MI,
178 unsigned DstOpIdx,
179 unsigned BaseOpIdx,
180 bool BaseOpKilled,
181 unsigned Dist);
182 void scanUses(Register DstReg);
183
184 void processCopy(MachineInstr *MI);
185
186 using TiedPairList = SmallVector<std::pair<unsigned, unsigned>, 4>;
187 using TiedOperandMap = SmallDenseMap<Register, TiedPairList>;
188
189 bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
190 void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
191 void eliminateRegSequence(MachineBasicBlock::iterator&);
192 bool processStatepoint(MachineInstr *MI, TiedOperandMap &TiedOperands);
193
194public:
195 TwoAddressInstructionImpl(MachineFunction &MF, MachineFunctionPass *P);
196 TwoAddressInstructionImpl(MachineFunction &MF,
198 LiveIntervals *LIS);
199 void setOptLevel(CodeGenOptLevel Level) { OptLevel = Level; }
200 bool run();
201};
202
203class TwoAddressInstructionLegacyPass : public MachineFunctionPass {
204public:
205 static char ID; // Pass identification, replacement for typeid
206
207 TwoAddressInstructionLegacyPass() : MachineFunctionPass(ID) {}
208
209 /// Pass entry point.
210 bool runOnMachineFunction(MachineFunction &MF) override {
211 TwoAddressInstructionImpl Impl(MF, this);
212 // Disable optimizations if requested. We cannot skip the whole pass as some
213 // fixups are necessary for correctness.
214 if (skipFunction(MF.getFunction()))
215 Impl.setOptLevel(CodeGenOptLevel::None);
216 return Impl.run();
217 }
218
219 void getAnalysisUsage(AnalysisUsage &AU) const override {
220 AU.setPreservesCFG();
221 AU.addUsedIfAvailable<LiveVariablesWrapperPass>();
222 AU.addPreserved<LiveVariablesWrapperPass>();
223 AU.addPreserved<SlotIndexesWrapperPass>();
224 AU.addPreserved<LiveIntervalsWrapperPass>();
226 }
227};
228
229} // end anonymous namespace
230
234 // Disable optimizations if requested. We cannot skip the whole pass as some
235 // fixups are necessary for correctness.
237
238 TwoAddressInstructionImpl Impl(MF, MFAM, LIS);
239 if (MF.getFunction().hasOptNone() ||
241 Impl.setOptLevel(CodeGenOptLevel::None);
242
243 MFPropsModifier _(*this, MF);
244 bool Changed = Impl.run();
245 if (!Changed)
246 return PreservedAnalyses::all();
248
249 // SlotIndexes are only maintained when LiveIntervals is available. Only
250 // preserve SlotIndexes if we had LiveIntervals available and updated them.
251 if (LIS)
252 PA.preserve<SlotIndexesAnalysis>();
253
254 PA.preserve<LiveVariablesAnalysis>();
255 PA.preserve<LiveIntervalsAnalysis>();
256 PA.preserveSet<CFGAnalyses>();
257 return PA;
258}
259
260char TwoAddressInstructionLegacyPass::ID = 0;
261
262char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionLegacyPass::ID;
263
264INITIALIZE_PASS(TwoAddressInstructionLegacyPass, DEBUG_TYPE,
265 "Two-Address instruction pass", false, false)
266
267TwoAddressInstructionImpl::TwoAddressInstructionImpl(
269 LiveIntervals *LIS)
270 : MF(&Func), TII(Func.getSubtarget().getInstrInfo()),
271 TRI(Func.getSubtarget().getRegisterInfo()),
272 InstrItins(Func.getSubtarget().getInstrItineraryData()),
273 MRI(&Func.getRegInfo()),
274 LV(MFAM.getCachedResult<LiveVariablesAnalysis>(Func)), LIS(LIS),
275 OptLevel(Func.getTarget().getOptLevel()) {}
276
277TwoAddressInstructionImpl::TwoAddressInstructionImpl(MachineFunction &Func,
279 : MF(&Func), TII(Func.getSubtarget().getInstrInfo()),
280 TRI(Func.getSubtarget().getRegisterInfo()),
281 InstrItins(Func.getSubtarget().getInstrItineraryData()),
282 MRI(&Func.getRegInfo()), OptLevel(Func.getTarget().getOptLevel()) {
283 auto *LVWrapper = P->getAnalysisIfAvailable<LiveVariablesWrapperPass>();
284 LV = LVWrapper ? &LVWrapper->getLV() : nullptr;
285 auto *LISWrapper = P->getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
286 LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr;
287}
288
289/// Return the MachineInstr* if it is the single def of the Reg in current BB.
291TwoAddressInstructionImpl::getSingleDef(Register Reg,
292 MachineBasicBlock *BB) const {
293 MachineInstr *Ret = nullptr;
294 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
295 if (DefMI.getParent() != BB || DefMI.isDebugValue())
296 continue;
297 if (!Ret)
298 Ret = &DefMI;
299 else if (Ret != &DefMI)
300 return nullptr;
301 }
302 return Ret;
303}
304
305static bool getTiedUse(Register DefReg, MachineInstr *MI,
306 const TargetRegisterInfo *TRI, unsigned &TiedOpIdx) {
307 int DefRegIdx = MI->findRegisterDefOperandIdx(DefReg, TRI);
308 if (DefRegIdx < 0)
309 return false;
310 return MI->isRegTiedToUseOperand(DefRegIdx, &TiedOpIdx);
311}
312
313/// Check if there is a reversed copy chain from FromReg to ToReg:
314/// %Tmp1 = copy %Tmp2;
315/// %FromReg = copy %Tmp1;
316/// %ToReg = add %FromReg ...
317/// %Tmp2 = copy %ToReg;
318/// MaxLen specifies the maximum length of the copy chain the func
319/// can walk through.
320bool TwoAddressInstructionImpl::isRevCopyChain(Register FromReg, Register ToReg,
321 int Maxlen) {
322 Register TmpReg = FromReg;
323 for (int i = 0; i < Maxlen; i++) {
324 MachineInstr *Def = getSingleDef(TmpReg, MBB);
325 if (!Def)
326 return false;
327
328 if (Def->isCopy())
329 TmpReg = Def->getOperand(1).getReg();
330 else if (unsigned TiedOpIdx;
331 AnalyzeRevCopyTied && getTiedUse(TmpReg, Def, TRI, TiedOpIdx)) {
332 Register TiedUseReg = Def->getOperand(TiedOpIdx).getReg();
333 // Tied use reg matches def reg. It's not a copy chain. We won't make any
334 // forward progress anymore, stop the traversal here.
335 if (TiedUseReg == TmpReg)
336 return false;
337 TmpReg = TiedUseReg;
338 } else
339 return false;
340
341 if (TmpReg == ToReg)
342 return true;
343 }
344 return false;
345}
346
347/// Return true if there are no intervening uses between the last instruction
348/// in the MBB that defines the specified register and the two-address
349/// instruction which is being processed. It also returns the last def location
350/// by reference.
351bool TwoAddressInstructionImpl::noUseAfterLastDef(Register Reg, unsigned Dist,
352 unsigned &LastDef) {
353 LastDef = 0;
354 unsigned LastUse = Dist;
355 for (MachineOperand &MO : MRI->reg_operands(Reg)) {
356 MachineInstr *MI = MO.getParent();
357 if (MI->getParent() != MBB || MI->isDebugValue())
358 continue;
359 auto DI = DistanceMap.find(MI);
360 if (DI == DistanceMap.end())
361 continue;
362 if (MO.isUse() && DI->second < LastUse)
363 LastUse = DI->second;
364 if (MO.isDef() && DI->second > LastDef)
365 LastDef = DI->second;
366 }
367
368 return !(LastUse > LastDef && LastUse < Dist);
369}
370
371/// Return true if the specified MI is a copy instruction or an extract_subreg
372/// instruction. It also returns the source and destination registers and
373/// whether they are physical registers by reference.
374bool TwoAddressInstructionImpl::isCopyToReg(MachineInstr &MI, Register &SrcReg,
375 Register &DstReg, bool &IsSrcPhys,
376 bool &IsDstPhys) const {
377 SrcReg = 0;
378 DstReg = 0;
379 if (MI.isCopy() || MI.isSubregToReg()) {
380 DstReg = MI.getOperand(0).getReg();
381 SrcReg = MI.getOperand(1).getReg();
382 } else if (MI.isInsertSubreg()) {
383 DstReg = MI.getOperand(0).getReg();
384 SrcReg = MI.getOperand(2).getReg();
385 } else {
386 return false;
387 }
388
389 IsSrcPhys = SrcReg.isPhysical();
390 IsDstPhys = DstReg.isPhysical();
391 return true;
392}
393
394bool TwoAddressInstructionImpl::isPlainlyKilled(const MachineInstr *MI,
395 LiveRange &LR) const {
396 // This is to match the kill flag version where undefs don't have kill flags.
397 if (!LR.hasAtLeastOneValue())
398 return false;
399
400 SlotIndex useIdx = LIS->getInstructionIndex(*MI);
401 LiveInterval::const_iterator I = LR.find(useIdx);
402 assert(I != LR.end() && "Reg must be live-in to use.");
403 return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
404}
405
406/// Test if the given register value, which is used by the
407/// given instruction, is killed by the given instruction.
408bool TwoAddressInstructionImpl::isPlainlyKilled(const MachineInstr *MI,
409 Register Reg) const {
410 // FIXME: Sometimes tryInstructionTransform() will add instructions and
411 // test whether they can be folded before keeping them. In this case it
412 // sets a kill before recursively calling tryInstructionTransform() again.
413 // If there is no interval available, we assume that this instruction is
414 // one of those. A kill flag is manually inserted on the operand so the
415 // check below will handle it.
416 if (LIS && !LIS->isNotInMIMap(*MI)) {
417 if (Reg.isVirtual())
418 return isPlainlyKilled(MI, LIS->getInterval(Reg));
419 // Reserved registers are considered always live.
420 if (MRI->isReserved(Reg))
421 return false;
422 return all_of(TRI->regunits(Reg), [&](MCRegUnit U) {
423 return isPlainlyKilled(MI, LIS->getRegUnit(U));
424 });
425 }
426
427 return MI->killsRegister(Reg, /*TRI=*/nullptr);
428}
429
430/// Test if the register used by the given operand is killed by the operand's
431/// instruction.
432bool TwoAddressInstructionImpl::isPlainlyKilled(
433 const MachineOperand &MO) const {
434 return MO.isKill() || isPlainlyKilled(MO.getParent(), MO.getReg());
435}
436
437/// Test if the given register value, which is used by the given
438/// instruction, is killed by the given instruction. This looks through
439/// coalescable copies to see if the original value is potentially not killed.
440///
441/// For example, in this code:
442///
443/// %reg1034 = copy %reg1024
444/// %reg1035 = copy killed %reg1025
445/// %reg1036 = add killed %reg1034, killed %reg1035
446///
447/// %reg1034 is not considered to be killed, since it is copied from a
448/// register which is not killed. Treating it as not killed lets the
449/// normal heuristics commute the (two-address) add, which lets
450/// coalescing eliminate the extra copy.
451///
452/// If allowFalsePositives is true then likely kills are treated as kills even
453/// if it can't be proven that they are kills.
454bool TwoAddressInstructionImpl::isKilled(MachineInstr &MI, Register Reg,
455 bool allowFalsePositives) const {
456 MachineInstr *DefMI = &MI;
457 while (true) {
458 // All uses of physical registers are likely to be kills.
459 if (Reg.isPhysical() && (allowFalsePositives || MRI->hasOneUse(Reg)))
460 return true;
461 if (!isPlainlyKilled(DefMI, Reg))
462 return false;
463 if (Reg.isPhysical())
464 return true;
466 // If there are multiple defs, we can't do a simple analysis, so just
467 // go with what the kill flag says.
468 if (std::next(Begin) != MRI->def_end())
469 return true;
470 DefMI = Begin->getParent();
471 bool IsSrcPhys, IsDstPhys;
472 Register SrcReg, DstReg;
473 // If the def is something other than a copy, then it isn't going to
474 // be coalesced, so follow the kill flag.
475 if (!isCopyToReg(*DefMI, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
476 return true;
477 Reg = SrcReg;
478 }
479}
480
481/// Return true if the specified MI uses the specified register as a two-address
482/// use. If so, return the destination register by reference.
484 for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) {
485 const MachineOperand &MO = MI.getOperand(i);
486 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
487 continue;
488 unsigned ti;
489 if (MI.isRegTiedToDefOperand(i, &ti)) {
490 DstReg = MI.getOperand(ti).getReg();
491 return true;
492 }
493 }
494 return false;
495}
496
497/// Given a register, if all its uses are in the same basic block, return the
498/// last use instruction if it's a copy or a two-address use.
499MachineInstr *TwoAddressInstructionImpl::findOnlyInterestingUse(
500 Register Reg, MachineBasicBlock *MBB, bool &IsCopy, Register &DstReg,
501 bool &IsDstPhys) const {
502 MachineOperand *UseOp = nullptr;
503 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
504 if (MO.isUndef())
505 continue;
506
507 MachineInstr *MI = MO.getParent();
508 if (MI->getParent() != MBB)
509 return nullptr;
510 if (isPlainlyKilled(MI, Reg))
511 UseOp = &MO;
512 }
513 if (!UseOp)
514 return nullptr;
515 MachineInstr &UseMI = *UseOp->getParent();
516
517 Register SrcReg;
518 bool IsSrcPhys;
519 if (isCopyToReg(UseMI, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
520 IsCopy = true;
521 return &UseMI;
522 }
523 IsDstPhys = false;
524 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
525 IsDstPhys = DstReg.isPhysical();
526 return &UseMI;
527 }
528 if (UseMI.isCommutable()) {
530 unsigned Src2 = UseOp->getOperandNo();
531 if (TII->findCommutedOpIndices(UseMI, Src1, Src2)) {
532 MachineOperand &MO = UseMI.getOperand(Src1);
533 if (MO.isReg() && MO.isUse() &&
534 isTwoAddrUse(UseMI, MO.getReg(), DstReg)) {
535 IsDstPhys = DstReg.isPhysical();
536 return &UseMI;
537 }
538 }
539 }
540 return nullptr;
541}
542
543/// Return the physical register the specified virtual register might be mapped
544/// to.
547 while (Reg.isVirtual()) {
548 auto SI = RegMap.find(Reg);
549 if (SI == RegMap.end())
550 return 0;
551 Reg = SI->second;
552 }
553 if (Reg.isPhysical())
554 return Reg;
555 return 0;
556}
557
558/// Return true if the two registers are equal or aliased.
559bool TwoAddressInstructionImpl::regsAreCompatible(Register RegA,
560 Register RegB) const {
561 if (RegA == RegB)
562 return true;
563 if (!RegA || !RegB)
564 return false;
565 return TRI->regsOverlap(RegA, RegB);
566}
567
568/// From RegMap remove entries mapped to a physical register which overlaps MO.
569void TwoAddressInstructionImpl::removeMapRegEntry(
570 const MachineOperand &MO, DenseMap<Register, Register> &RegMap) const {
571 assert(
572 (MO.isReg() || MO.isRegMask()) &&
573 "removeMapRegEntry must be called with a register or regmask operand.");
574
576 for (auto SI : RegMap) {
577 Register ToReg = SI.second;
578 if (ToReg.isVirtual())
579 continue;
580
581 if (MO.isReg()) {
582 Register Reg = MO.getReg();
583 if (TRI->regsOverlap(ToReg, Reg))
584 Srcs.push_back(SI.first);
585 } else if (MO.clobbersPhysReg(ToReg))
586 Srcs.push_back(SI.first);
587 }
588
589 for (auto SrcReg : Srcs)
590 RegMap.erase(SrcReg);
591}
592
593/// If a physical register is clobbered, old entries mapped to it should be
594/// deleted. For example
595///
596/// %2:gr64 = COPY killed $rdx
597/// MUL64r %3:gr64, implicit-def $rax, implicit-def $rdx
598///
599/// After the MUL instruction, $rdx contains different value than in the COPY
600/// instruction. So %2 should not map to $rdx after MUL.
601void TwoAddressInstructionImpl::removeClobberedSrcRegMap(MachineInstr *MI) {
602 if (MI->isCopy()) {
603 // If a virtual register is copied to its mapped physical register, it
604 // doesn't change the potential coalescing between them, so we don't remove
605 // entries mapped to the physical register. For example
606 //
607 // %100 = COPY $r8
608 // ...
609 // $r8 = COPY %100
610 //
611 // The first copy constructs SrcRegMap[%100] = $r8, the second copy doesn't
612 // destroy the content of $r8, and should not impact SrcRegMap.
613 Register Dst = MI->getOperand(0).getReg();
614 if (!Dst || Dst.isVirtual())
615 return;
616
617 Register Src = MI->getOperand(1).getReg();
618 if (regsAreCompatible(Dst, getMappedReg(Src, SrcRegMap)))
619 return;
620 }
621
622 for (const MachineOperand &MO : MI->operands()) {
623 if (MO.isRegMask()) {
624 removeMapRegEntry(MO, SrcRegMap);
625 continue;
626 }
627 if (!MO.isReg() || !MO.isDef())
628 continue;
629 Register Reg = MO.getReg();
630 if (!Reg || Reg.isVirtual())
631 continue;
632 removeMapRegEntry(MO, SrcRegMap);
633 }
634}
635
636// Returns true if Reg is equal or aliased to at least one register in Set.
637bool TwoAddressInstructionImpl::regOverlapsSet(
638 const SmallVectorImpl<Register> &Set, Register Reg) const {
639 for (Register R : Set)
640 if (TRI->regsOverlap(R, Reg))
641 return true;
642
643 return false;
644}
645
646/// Return true if it's potentially profitable to commute the two-address
647/// instruction that's being processed.
648bool TwoAddressInstructionImpl::isProfitableToCommute(Register RegA,
649 Register RegB,
650 Register RegC,
651 MachineInstr *MI,
652 unsigned Dist) {
653 if (OptLevel == CodeGenOptLevel::None)
654 return false;
655
656 // Determine if it's profitable to commute this two address instruction. In
657 // general, we want no uses between this instruction and the definition of
658 // the two-address register.
659 // e.g.
660 // %reg1028 = EXTRACT_SUBREG killed %reg1027, 1
661 // %reg1029 = COPY %reg1028
662 // %reg1029 = SHR8ri %reg1029, 7, implicit dead %eflags
663 // insert => %reg1030 = COPY %reg1028
664 // %reg1030 = ADD8rr killed %reg1028, killed %reg1029, implicit dead %eflags
665 // In this case, it might not be possible to coalesce the second COPY
666 // instruction if the first one is coalesced. So it would be profitable to
667 // commute it:
668 // %reg1028 = EXTRACT_SUBREG killed %reg1027, 1
669 // %reg1029 = COPY %reg1028
670 // %reg1029 = SHR8ri %reg1029, 7, implicit dead %eflags
671 // insert => %reg1030 = COPY %reg1029
672 // %reg1030 = ADD8rr killed %reg1029, killed %reg1028, implicit dead %eflags
673
674 if (!isPlainlyKilled(MI, RegC))
675 return false;
676
677 // Ok, we have something like:
678 // %reg1030 = ADD8rr killed %reg1028, killed %reg1029, implicit dead %eflags
679 // let's see if it's worth commuting it.
680
681 // Look for situations like this:
682 // %reg1024 = MOV r1
683 // %reg1025 = MOV r0
684 // %reg1026 = ADD %reg1024, %reg1025
685 // r0 = MOV %reg1026
686 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
687 MCRegister ToRegA = getMappedReg(RegA, DstRegMap);
688 if (ToRegA) {
689 MCRegister FromRegB = getMappedReg(RegB, SrcRegMap);
690 MCRegister FromRegC = getMappedReg(RegC, SrcRegMap);
691 bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA);
692 bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA);
693
694 // Compute if any of the following are true:
695 // -RegB is not tied to a register and RegC is compatible with RegA.
696 // -RegB is tied to the wrong physical register, but RegC is.
697 // -RegB is tied to the wrong physical register, and RegC isn't tied.
698 if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC)))
699 return true;
700 // Don't compute if any of the following are true:
701 // -RegC is not tied to a register and RegB is compatible with RegA.
702 // -RegC is tied to the wrong physical register, but RegB is.
703 // -RegC is tied to the wrong physical register, and RegB isn't tied.
704 if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB)))
705 return false;
706 }
707
708 // If there is a use of RegC between its last def (could be livein) and this
709 // instruction, then bail.
710 unsigned LastDefC = 0;
711 if (!noUseAfterLastDef(RegC, Dist, LastDefC))
712 return false;
713
714 // If there is a use of RegB between its last def (could be livein) and this
715 // instruction, then go ahead and make this transformation.
716 unsigned LastDefB = 0;
717 if (!noUseAfterLastDef(RegB, Dist, LastDefB))
718 return true;
719
720 // Look for situation like this:
721 // %reg101 = MOV %reg100
722 // %reg102 = ...
723 // %reg103 = ADD %reg102, %reg101
724 // ... = %reg103 ...
725 // %reg100 = MOV %reg103
726 // If there is a reversed copy chain from reg101 to reg103, commute the ADD
727 // to eliminate an otherwise unavoidable copy.
728 // FIXME:
729 // We can extend the logic further: If an pair of operands in an insn has
730 // been merged, the insn could be regarded as a virtual copy, and the virtual
731 // copy could also be used to construct a copy chain.
732 // To more generally minimize register copies, ideally the logic of two addr
733 // instruction pass should be integrated with register allocation pass where
734 // interference graph is available.
735 if (isRevCopyChain(RegC, RegA, MaxDataFlowEdge))
736 return true;
737
738 if (isRevCopyChain(RegB, RegA, MaxDataFlowEdge))
739 return false;
740
741 // Look for other target specific commute preference.
742 bool Commute;
743 if (TII->hasCommutePreference(*MI, Commute))
744 return Commute;
745
746 // Since there are no intervening uses for both registers, then commute
747 // if the def of RegC is closer. Its live interval is shorter.
748 return LastDefB && LastDefC && LastDefC > LastDefB;
749}
750
751/// Commute a two-address instruction and update the basic block, distance map,
752/// and live variables if needed. Return true if it is successful.
753bool TwoAddressInstructionImpl::commuteInstruction(MachineInstr *MI,
754 unsigned DstIdx,
755 unsigned RegBIdx,
756 unsigned RegCIdx,
757 unsigned Dist) {
758 Register RegC = MI->getOperand(RegCIdx).getReg();
759 LLVM_DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
760 MachineInstr *NewMI = TII->commuteInstruction(*MI, false, RegBIdx, RegCIdx);
761
762 if (NewMI == nullptr) {
763 LLVM_DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
764 return false;
765 }
766
767 LLVM_DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
768 assert(NewMI == MI &&
769 "TargetInstrInfo::commuteInstruction() should not return a new "
770 "instruction unless it was requested.");
771
772 // Update source register map.
773 MCRegister FromRegC = getMappedReg(RegC, SrcRegMap);
774 if (FromRegC) {
775 Register RegA = MI->getOperand(DstIdx).getReg();
776 SrcRegMap[RegA] = FromRegC;
777 }
778
779 return true;
780}
781
782/// Return true if it is profitable to convert the given 2-address instruction
783/// to a 3-address one.
784bool TwoAddressInstructionImpl::isProfitableToConv3Addr(Register RegA,
785 Register RegB) {
786 // Look for situations like this:
787 // %reg1024 = MOV r1
788 // %reg1025 = MOV r0
789 // %reg1026 = ADD %reg1024, %reg1025
790 // r2 = MOV %reg1026
791 // Turn ADD into a 3-address instruction to avoid a copy.
792 MCRegister FromRegB = getMappedReg(RegB, SrcRegMap);
793 if (!FromRegB)
794 return false;
795 MCRegister ToRegA = getMappedReg(RegA, DstRegMap);
796 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA));
797}
798
799/// Convert the specified two-address instruction into a three address one.
800/// Return true if this transformation was successful.
801bool TwoAddressInstructionImpl::convertInstTo3Addr(
803 Register RegA, Register RegB, unsigned &Dist) {
804 MachineInstrSpan MIS(mi, MBB);
805 MachineInstr *NewMI = TII->convertToThreeAddress(*mi, LV, LIS);
806 if (!NewMI)
807 return false;
808
809 for (MachineInstr &MI : MIS)
810 DistanceMap.insert(std::make_pair(&MI, Dist++));
811
812 if (&*mi == NewMI) {
813 LLVM_DEBUG(dbgs() << "2addr: CONVERTED IN-PLACE TO 3-ADDR: " << *mi);
814 } else {
815 LLVM_DEBUG({
816 dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi;
817 dbgs() << "2addr: TO 3-ADDR: " << *NewMI;
818 });
819
820 // If the old instruction is debug value tracked, an update is required.
821 if (auto OldInstrNum = mi->peekDebugInstrNum()) {
822 assert(mi->getNumExplicitDefs() == 1);
823 assert(NewMI->getNumExplicitDefs() == 1);
824
825 // Find the old and new def location.
826 unsigned OldIdx = mi->defs().begin()->getOperandNo();
827 unsigned NewIdx = NewMI->defs().begin()->getOperandNo();
828
829 // Record that one def has been replaced by the other.
830 unsigned NewInstrNum = NewMI->getDebugInstrNum();
831 MF->makeDebugValueSubstitution(std::make_pair(OldInstrNum, OldIdx),
832 std::make_pair(NewInstrNum, NewIdx));
833 }
834
835 MBB->erase(mi); // Nuke the old inst.
836 Dist--;
837 }
838
839 mi = NewMI;
840 nmi = std::next(mi);
841
842 // Update source and destination register maps.
843 SrcRegMap.erase(RegA);
844 DstRegMap.erase(RegB);
845 return true;
846}
847
848/// Scan forward recursively for only uses, update maps if the use is a copy or
849/// a two-address instruction.
850void TwoAddressInstructionImpl::scanUses(Register DstReg) {
851 SmallVector<Register, 4> VirtRegPairs;
852 bool IsDstPhys;
853 bool IsCopy = false;
854 Register NewReg;
855 Register Reg = DstReg;
856 while (MachineInstr *UseMI =
857 findOnlyInterestingUse(Reg, MBB, IsCopy, NewReg, IsDstPhys)) {
858 if (IsCopy && !Processed.insert(UseMI).second)
859 break;
860
861 auto DI = DistanceMap.find(UseMI);
862 if (DI != DistanceMap.end())
863 // Earlier in the same MBB.Reached via a back edge.
864 break;
865
866 if (IsDstPhys) {
867 VirtRegPairs.push_back(NewReg);
868 break;
869 }
870 SrcRegMap[NewReg] = Reg;
871 VirtRegPairs.push_back(NewReg);
872 Reg = NewReg;
873 }
874
875 if (!VirtRegPairs.empty()) {
876 Register ToReg = VirtRegPairs.pop_back_val();
877 while (!VirtRegPairs.empty()) {
878 Register FromReg = VirtRegPairs.pop_back_val();
879 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
880 if (!isNew)
881 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
882 ToReg = FromReg;
883 }
884 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
885 if (!isNew)
886 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
887 }
888}
889
890/// If the specified instruction is not yet processed, process it if it's a
891/// copy. For a copy instruction, we find the physical registers the
892/// source and destination registers might be mapped to. These are kept in
893/// point-to maps used to determine future optimizations. e.g.
894/// v1024 = mov r0
895/// v1025 = mov r1
896/// v1026 = add v1024, v1025
897/// r1 = mov r1026
898/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
899/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
900/// potentially joined with r1 on the output side. It's worthwhile to commute
901/// 'add' to eliminate a copy.
902void TwoAddressInstructionImpl::processCopy(MachineInstr *MI) {
903 if (Processed.count(MI))
904 return;
905
906 bool IsSrcPhys, IsDstPhys;
907 Register SrcReg, DstReg;
908 if (!isCopyToReg(*MI, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
909 return;
910
911 if (IsDstPhys && !IsSrcPhys) {
912 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
913 } else if (!IsDstPhys && IsSrcPhys) {
914 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
915 if (!isNew)
916 assert(SrcRegMap[DstReg] == SrcReg &&
917 "Can't map to two src physical registers!");
918
919 scanUses(DstReg);
920 }
921
922 Processed.insert(MI);
923}
924
925/// If there is one more local instruction that reads 'Reg' and it kills 'Reg,
926/// consider moving the instruction below the kill instruction in order to
927/// eliminate the need for the copy.
928bool TwoAddressInstructionImpl::rescheduleMIBelowKill(
930 Register Reg) {
931 // Bail immediately if we don't have LV or LIS available. We use them to find
932 // kills efficiently.
933 if (!LV && !LIS)
934 return false;
935
936 MachineInstr *MI = &*mi;
937 auto DI = DistanceMap.find(MI);
938 if (DI == DistanceMap.end())
939 // Must be created from unfolded load. Don't waste time trying this.
940 return false;
941
942 MachineInstr *KillMI = nullptr;
943 if (LIS) {
944 LiveInterval &LI = LIS->getInterval(Reg);
945 assert(LI.end() != LI.begin() &&
946 "Reg should not have empty live interval.");
947
948 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
949 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
950 if (I != LI.end() && I->start < MBBEndIdx)
951 return false;
952
953 --I;
954 KillMI = LIS->getInstructionFromIndex(I->end);
955 } else {
956 KillMI = LV->getVarInfo(Reg).findKill(MBB);
957 }
958 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
959 // Don't mess with copies, they may be coalesced later.
960 return false;
961
962 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
963 KillMI->isBranch() || KillMI->isTerminator())
964 // Don't move pass calls, etc.
965 return false;
966
967 Register DstReg;
968 if (isTwoAddrUse(*KillMI, Reg, DstReg))
969 return false;
970
971 bool SeenStore = true;
972 if (!MI->isSafeToMove(SeenStore))
973 return false;
974
975 if (TII->getInstrLatency(InstrItins, *MI) > 1)
976 // FIXME: Needs more sophisticated heuristics.
977 return false;
978
982 for (const MachineOperand &MO : MI->operands()) {
983 if (!MO.isReg())
984 continue;
985 Register MOReg = MO.getReg();
986 if (!MOReg)
987 continue;
988 if (MO.isDef())
989 Defs.push_back(MOReg);
990 else {
991 Uses.push_back(MOReg);
992 if (MOReg != Reg && isPlainlyKilled(MO))
993 Kills.push_back(MOReg);
994 }
995 }
996
997 // Move the copies connected to MI down as well.
999 MachineBasicBlock::iterator AfterMI = std::next(Begin);
1000 MachineBasicBlock::iterator End = AfterMI;
1001 while (End != MBB->end()) {
1002 End = skipDebugInstructionsForward(End, MBB->end());
1003 if (End->isCopy() && regOverlapsSet(Defs, End->getOperand(1).getReg()))
1004 Defs.push_back(End->getOperand(0).getReg());
1005 else
1006 break;
1007 ++End;
1008 }
1009
1010 // Check if the reschedule will not break dependencies.
1011 unsigned NumVisited = 0;
1012 MachineBasicBlock::iterator KillPos = KillMI;
1013 ++KillPos;
1014 for (MachineInstr &OtherMI : make_range(End, KillPos)) {
1015 // Debug or pseudo instructions cannot be counted against the limit.
1016 if (OtherMI.isDebugOrPseudoInstr())
1017 continue;
1018 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1019 return false;
1020 ++NumVisited;
1021 if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
1022 OtherMI.isBranch() || OtherMI.isTerminator())
1023 // Don't move pass calls, etc.
1024 return false;
1025 for (const MachineOperand &MO : OtherMI.operands()) {
1026 if (!MO.isReg())
1027 continue;
1028 Register MOReg = MO.getReg();
1029 if (!MOReg)
1030 continue;
1031 if (MO.isDef()) {
1032 if (regOverlapsSet(Uses, MOReg))
1033 // Physical register use would be clobbered.
1034 return false;
1035 if (!MO.isDead() && regOverlapsSet(Defs, MOReg))
1036 // May clobber a physical register def.
1037 // FIXME: This may be too conservative. It's ok if the instruction
1038 // is sunken completely below the use.
1039 return false;
1040 } else {
1041 if (regOverlapsSet(Defs, MOReg))
1042 return false;
1043 bool isKill = isPlainlyKilled(MO);
1044 if (MOReg != Reg && ((isKill && regOverlapsSet(Uses, MOReg)) ||
1045 regOverlapsSet(Kills, MOReg)))
1046 // Don't want to extend other live ranges and update kills.
1047 return false;
1048 if (MOReg == Reg && !isKill)
1049 // We can't schedule across a use of the register in question.
1050 return false;
1051 // Ensure that if this is register in question, its the kill we expect.
1052 assert((MOReg != Reg || &OtherMI == KillMI) &&
1053 "Found multiple kills of a register in a basic block");
1054 }
1055 }
1056 }
1057
1058 // Move debug info as well.
1059 while (Begin != MBB->begin() && std::prev(Begin)->isDebugInstr())
1060 --Begin;
1061
1062 nmi = End;
1063 MachineBasicBlock::iterator InsertPos = KillPos;
1064 if (LIS) {
1065 // We have to move the copies (and any interleaved debug instructions)
1066 // first so that the MBB is still well-formed when calling handleMove().
1067 for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
1068 auto CopyMI = MBBI++;
1069 MBB->splice(InsertPos, MBB, CopyMI);
1070 if (!CopyMI->isDebugOrPseudoInstr())
1071 LIS->handleMove(*CopyMI);
1072 InsertPos = CopyMI;
1073 }
1074 End = std::next(MachineBasicBlock::iterator(MI));
1075 }
1076
1077 // Copies following MI may have been moved as well.
1078 MBB->splice(InsertPos, MBB, Begin, End);
1079 DistanceMap.erase(DI);
1080
1081 // Update live variables
1082 if (LIS) {
1083 LIS->handleMove(*MI);
1084 } else {
1085 LV->removeVirtualRegisterKilled(Reg, *KillMI);
1087 }
1088
1089 LLVM_DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
1090 return true;
1091}
1092
1093/// Return true if the re-scheduling will put the given instruction too close
1094/// to the defs of its register dependencies.
1095bool TwoAddressInstructionImpl::isDefTooClose(Register Reg, unsigned Dist,
1096 MachineInstr *MI) {
1097 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
1098 if (DefMI.getParent() != MBB || DefMI.isCopy() || DefMI.isCopyLike())
1099 continue;
1100 if (&DefMI == MI)
1101 return true; // MI is defining something KillMI uses
1102 auto DDI = DistanceMap.find(&DefMI);
1103 if (DDI == DistanceMap.end())
1104 return true; // Below MI
1105 unsigned DefDist = DDI->second;
1106 assert(Dist > DefDist && "Visited def already?");
1107 if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
1108 return true;
1109 }
1110 return false;
1111}
1112
1113/// If there is one more local instruction that reads 'Reg' and it kills 'Reg,
1114/// consider moving the kill instruction above the current two-address
1115/// instruction in order to eliminate the need for the copy.
1116bool TwoAddressInstructionImpl::rescheduleKillAboveMI(
1118 Register Reg) {
1119 // Bail immediately if we don't have LV or LIS available. We use them to find
1120 // kills efficiently.
1121 if (!LV && !LIS)
1122 return false;
1123
1124 MachineInstr *MI = &*mi;
1125 auto DI = DistanceMap.find(MI);
1126 if (DI == DistanceMap.end())
1127 // Must be created from unfolded load. Don't waste time trying this.
1128 return false;
1129
1130 MachineInstr *KillMI = nullptr;
1131 if (LIS) {
1132 LiveInterval &LI = LIS->getInterval(Reg);
1133 assert(LI.end() != LI.begin() &&
1134 "Reg should not have empty live interval.");
1135
1136 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
1137 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
1138 if (I != LI.end() && I->start < MBBEndIdx)
1139 return false;
1140
1141 --I;
1142 KillMI = LIS->getInstructionFromIndex(I->end);
1143 } else {
1144 KillMI = LV->getVarInfo(Reg).findKill(MBB);
1145 }
1146 if (!KillMI || MI == KillMI)
1147 return false;
1148
1149 if (KillMI->isCopyLike()) {
1150 if (!MI->mayLoad())
1151 return false;
1152
1153 Register CopySrcReg, CopyDstReg;
1154 bool IsCopySrcPhys, IsCopyDstPhys;
1155 // Most copies are better left for coalescing. Allow moving only the
1156 // case of a kill-copy from a source virtual register into a
1157 // physical register when the current two-address instruction has a folded
1158 // load; that preserves the memory form and avoids introducing a load+copy.
1159 if (!isCopyToReg(*KillMI, CopySrcReg, CopyDstReg, IsCopySrcPhys,
1160 IsCopyDstPhys))
1161 return false;
1162
1163 if (CopySrcReg != Reg || IsCopySrcPhys || !IsCopyDstPhys)
1164 return false;
1165 }
1166
1167 Register DstReg;
1168 if (isTwoAddrUse(*KillMI, Reg, DstReg))
1169 return false;
1170
1171 bool SeenStore = true;
1172 if (!KillMI->isSafeToMove(SeenStore))
1173 return false;
1174
1178 SmallVector<Register, 2> LiveDefs;
1179 for (const MachineOperand &MO : KillMI->operands()) {
1180 if (!MO.isReg())
1181 continue;
1182 Register MOReg = MO.getReg();
1183 if (MO.isUse()) {
1184 if (!MOReg)
1185 continue;
1186 if (isDefTooClose(MOReg, DI->second, MI))
1187 return false;
1188 bool isKill = isPlainlyKilled(MO);
1189 if (MOReg == Reg && !isKill)
1190 return false;
1191 Uses.push_back(MOReg);
1192 if (isKill && MOReg != Reg)
1193 Kills.push_back(MOReg);
1194 } else if (MOReg.isPhysical()) {
1195 Defs.push_back(MOReg);
1196 if (!MO.isDead())
1197 LiveDefs.push_back(MOReg);
1198 }
1199 }
1200
1201 // Check if the reschedule will not break dependencies.
1202 unsigned NumVisited = 0;
1203 for (MachineInstr &OtherMI :
1205 // Debug or pseudo instructions cannot be counted against the limit.
1206 if (OtherMI.isDebugOrPseudoInstr())
1207 continue;
1208 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1209 return false;
1210 ++NumVisited;
1211 if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
1212 OtherMI.isBranch() || OtherMI.isTerminator())
1213 // Don't move pass calls, etc.
1214 return false;
1215 SmallVector<Register, 2> OtherDefs;
1216 for (const MachineOperand &MO : OtherMI.operands()) {
1217 if (!MO.isReg())
1218 continue;
1219 Register MOReg = MO.getReg();
1220 if (!MOReg)
1221 continue;
1222 if (MO.isUse()) {
1223 if (regOverlapsSet(Defs, MOReg))
1224 // Moving KillMI can clobber the physical register if the def has
1225 // not been seen.
1226 return false;
1227 if (regOverlapsSet(Kills, MOReg))
1228 // Don't want to extend other live ranges and update kills.
1229 return false;
1230 if (&OtherMI != MI && MOReg == Reg && !isPlainlyKilled(MO))
1231 // We can't schedule across a use of the register in question.
1232 return false;
1233 } else {
1234 OtherDefs.push_back(MOReg);
1235 }
1236 }
1237
1238 for (Register MOReg : OtherDefs) {
1239 if (regOverlapsSet(Uses, MOReg))
1240 return false;
1241 if (MOReg.isPhysical() && regOverlapsSet(LiveDefs, MOReg))
1242 return false;
1243 // Physical register def is seen.
1244 llvm::erase(Defs, MOReg);
1245 }
1246 }
1247
1248 // Move the old kill above MI, don't forget to move debug info as well.
1249 MachineBasicBlock::iterator InsertPos = mi;
1250 while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugInstr())
1251 --InsertPos;
1252 MachineBasicBlock::iterator From = KillMI;
1253 MachineBasicBlock::iterator To = std::next(From);
1254 while (std::prev(From)->isDebugInstr())
1255 --From;
1256 MBB->splice(InsertPos, MBB, From, To);
1257
1258 nmi = std::prev(InsertPos); // Backtrack so we process the moved instr.
1259 DistanceMap.erase(DI);
1260
1261 // Update live variables
1262 if (LIS) {
1263 LIS->handleMove(*KillMI);
1264 } else {
1265 LV->removeVirtualRegisterKilled(Reg, *KillMI);
1267 }
1268
1269 LLVM_DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
1270 return true;
1271}
1272
1273/// Tries to commute the operand 'BaseOpIdx' and some other operand in the
1274/// given machine instruction to improve opportunities for coalescing and
1275/// elimination of a register to register copy.
1276///
1277/// 'DstOpIdx' specifies the index of MI def operand.
1278/// 'BaseOpKilled' specifies if the register associated with 'BaseOpIdx'
1279/// operand is killed by the given instruction.
1280/// The 'Dist' arguments provides the distance of MI from the start of the
1281/// current basic block and it is used to determine if it is profitable
1282/// to commute operands in the instruction.
1283///
1284/// Returns true if the transformation happened. Otherwise, returns false.
1285bool TwoAddressInstructionImpl::tryInstructionCommute(MachineInstr *MI,
1286 unsigned DstOpIdx,
1287 unsigned BaseOpIdx,
1288 bool BaseOpKilled,
1289 unsigned Dist) {
1290 if (!MI->isCommutable())
1291 return false;
1292
1293 bool MadeChange = false;
1294 Register DstOpReg = MI->getOperand(DstOpIdx).getReg();
1295 Register BaseOpReg = MI->getOperand(BaseOpIdx).getReg();
1296 unsigned OpsNum = MI->getDesc().getNumOperands();
1297 unsigned OtherOpIdx = MI->getDesc().getNumDefs();
1298 for (; OtherOpIdx < OpsNum; OtherOpIdx++) {
1299 // The call of findCommutedOpIndices below only checks if BaseOpIdx
1300 // and OtherOpIdx are commutable, it does not really search for
1301 // other commutable operands and does not change the values of passed
1302 // variables.
1303 if (OtherOpIdx == BaseOpIdx || !MI->getOperand(OtherOpIdx).isReg() ||
1304 !TII->findCommutedOpIndices(*MI, BaseOpIdx, OtherOpIdx))
1305 continue;
1306
1307 Register OtherOpReg = MI->getOperand(OtherOpIdx).getReg();
1308 bool AggressiveCommute = false;
1309
1310 // If OtherOp dies but BaseOp does not, swap the OtherOp and BaseOp
1311 // operands. This makes the live ranges of DstOp and OtherOp joinable.
1312 bool OtherOpKilled = isKilled(*MI, OtherOpReg, false);
1313 bool DoCommute = !BaseOpKilled && OtherOpKilled;
1314
1315 if (!DoCommute &&
1316 isProfitableToCommute(DstOpReg, BaseOpReg, OtherOpReg, MI, Dist)) {
1317 DoCommute = true;
1318 AggressiveCommute = true;
1319 }
1320
1321 // If it's profitable to commute, try to do so.
1322 if (DoCommute && commuteInstruction(MI, DstOpIdx, BaseOpIdx, OtherOpIdx,
1323 Dist)) {
1324 MadeChange = true;
1325 ++NumCommuted;
1326 if (AggressiveCommute)
1327 ++NumAggrCommuted;
1328
1329 // There might be more than two commutable operands, update BaseOp and
1330 // continue scanning.
1331 // FIXME: This assumes that the new instruction's operands are in the
1332 // same positions and were simply swapped.
1333 BaseOpReg = OtherOpReg;
1334 BaseOpKilled = OtherOpKilled;
1335 // Resamples OpsNum in case the number of operands was reduced. This
1336 // happens with X86.
1337 OpsNum = MI->getDesc().getNumOperands();
1338 }
1339 }
1340 return MadeChange;
1341}
1342
1343/// For the case where an instruction has a single pair of tied register
1344/// operands, attempt some transformations that may either eliminate the tied
1345/// operands or improve the opportunities for coalescing away the register copy.
1346/// Returns true if no copy needs to be inserted to untie mi's operands
1347/// (either because they were untied, or because mi was rescheduled, and will
1348/// be visited again later). If the shouldOnlyCommute flag is true, only
1349/// instruction commutation is attempted.
1350bool TwoAddressInstructionImpl::tryInstructionTransform(
1352 unsigned SrcIdx, unsigned DstIdx, unsigned &Dist, bool shouldOnlyCommute) {
1353 if (OptLevel == CodeGenOptLevel::None)
1354 return false;
1355
1356 MachineInstr &MI = *mi;
1357 Register regA = MI.getOperand(DstIdx).getReg();
1358 Register regB = MI.getOperand(SrcIdx).getReg();
1359
1360 assert(regB.isVirtual() && "cannot make instruction into two-address form");
1361 bool regBKilled = isKilled(MI, regB, true);
1362
1363 if (regA.isVirtual())
1364 scanUses(regA);
1365
1366 bool Commuted = tryInstructionCommute(&MI, DstIdx, SrcIdx, regBKilled, Dist);
1367
1368 // Give targets a chance to convert bundled instructions.
1369 bool ConvertibleTo3Addr = MI.isConvertibleTo3Addr(MachineInstr::AnyInBundle);
1370
1371 // If the instruction is convertible to 3 Addr, instead
1372 // of returning try 3 Addr transformation aggressively and
1373 // use this variable to check later. Because it might be better.
1374 // For example, we can just use `leal (%rsi,%rdi), %eax` and `ret`
1375 // instead of the following code.
1376 // addl %esi, %edi
1377 // movl %edi, %eax
1378 // ret
1379 if (Commuted && !ConvertibleTo3Addr)
1380 return false;
1381
1382 if (shouldOnlyCommute)
1383 return false;
1384
1385 // If there is one more use of regB later in the same MBB, consider
1386 // re-schedule this MI below it.
1387 if (!Commuted && EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) {
1388 ++NumReSchedDowns;
1389 return true;
1390 }
1391
1392 // If we commuted, regB may have changed so we should re-sample it to avoid
1393 // confusing the three address conversion below.
1394 if (Commuted) {
1395 regB = MI.getOperand(SrcIdx).getReg();
1396 regBKilled = isKilled(MI, regB, true);
1397 }
1398
1399 if (ConvertibleTo3Addr) {
1400 // This instruction is potentially convertible to a true
1401 // three-address instruction. Check if it is profitable.
1402 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
1403 // Try to convert it.
1404 if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
1405 ++NumConvertedTo3Addr;
1406 return true; // Done with this instruction.
1407 }
1408 }
1409 }
1410
1411 // Return if it is commuted but 3 addr conversion is failed.
1412 if (Commuted)
1413 return false;
1414
1415 // If there is one more use of regB later in the same MBB, consider
1416 // re-schedule it before this MI if it's legal.
1417 if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) {
1418 ++NumReSchedUps;
1419 return true;
1420 }
1421
1422 // If this is an instruction with a load folded into it, try unfolding
1423 // the load, e.g. avoid this:
1424 // movq %rdx, %rcx
1425 // addq (%rax), %rcx
1426 // in favor of this:
1427 // movq (%rax), %rcx
1428 // addq %rdx, %rcx
1429 // because it's preferable to schedule a load than a register copy.
1430 if (MI.mayLoad() && !regBKilled) {
1431 // Determine if a load can be unfolded.
1432 unsigned LoadRegIndex;
1433 unsigned NewOpc =
1434 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1435 /*UnfoldLoad=*/true,
1436 /*UnfoldStore=*/false,
1437 &LoadRegIndex);
1438 if (NewOpc != 0) {
1439 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1440 if (UnfoldMCID.getNumDefs() == 1) {
1441 // Unfold the load.
1442 LLVM_DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
1443 const TargetRegisterClass *RC = TRI->getAllocatableClass(
1444 TII->getRegClass(UnfoldMCID, LoadRegIndex));
1446 SmallVector<MachineInstr *, 2> NewMIs;
1447 if (!TII->unfoldMemoryOperand(*MF, MI, Reg,
1448 /*UnfoldLoad=*/true,
1449 /*UnfoldStore=*/false, NewMIs)) {
1450 LLVM_DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1451 return false;
1452 }
1453 assert(NewMIs.size() == 2 &&
1454 "Unfolded a load into multiple instructions!");
1455 // The load was previously folded, so this is the only use.
1456 NewMIs[1]->addRegisterKilled(Reg, TRI);
1457
1458 // Tentatively insert the instructions into the block so that they
1459 // look "normal" to the transformation logic.
1460 MBB->insert(mi, NewMIs[0]);
1461 MBB->insert(mi, NewMIs[1]);
1462 DistanceMap.insert(std::make_pair(NewMIs[0], Dist++));
1463 DistanceMap.insert(std::make_pair(NewMIs[1], Dist));
1464
1465 LLVM_DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1466 << "2addr: NEW INST: " << *NewMIs[1]);
1467
1468 // Transform the instruction, now that it no longer has a load.
1469 unsigned NewDstIdx =
1470 NewMIs[1]->findRegisterDefOperandIdx(regA, /*TRI=*/nullptr);
1471 unsigned NewSrcIdx =
1472 NewMIs[1]->findRegisterUseOperandIdx(regB, /*TRI=*/nullptr);
1473 MachineBasicBlock::iterator NewMI = NewMIs[1];
1474 bool TransformResult =
1475 tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
1476 (void)TransformResult;
1477 assert(!TransformResult &&
1478 "tryInstructionTransform() should return false.");
1479 if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1480 // Success, or at least we made an improvement. Keep the unfolded
1481 // instructions and discard the original.
1482 if (LV) {
1483 for (const MachineOperand &MO : MI.operands()) {
1484 if (MO.isReg() && MO.getReg().isVirtual()) {
1485 if (MO.isUse()) {
1486 if (MO.isKill()) {
1487 if (NewMIs[0]->killsRegister(MO.getReg(), /*TRI=*/nullptr))
1488 LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[0]);
1489 else {
1490 assert(NewMIs[1]->killsRegister(MO.getReg(),
1491 /*TRI=*/nullptr) &&
1492 "Kill missing after load unfold!");
1493 LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[1]);
1494 }
1495 }
1496 } else if (LV->removeVirtualRegisterDead(MO.getReg(), MI)) {
1497 if (NewMIs[1]->registerDefIsDead(MO.getReg(),
1498 /*TRI=*/nullptr))
1499 LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[1]);
1500 else {
1501 assert(NewMIs[0]->registerDefIsDead(MO.getReg(),
1502 /*TRI=*/nullptr) &&
1503 "Dead flag missing after load unfold!");
1504 LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[0]);
1505 }
1506 }
1507 }
1508 }
1509 LV->addVirtualRegisterKilled(Reg, *NewMIs[1]);
1510 }
1511
1512 SmallVector<Register, 4> OrigRegs;
1513 if (LIS) {
1514 for (const MachineOperand &MO : MI.operands()) {
1515 if (MO.isReg())
1516 OrigRegs.push_back(MO.getReg());
1517 }
1518
1520 }
1521
1522 MI.eraseFromParent();
1523 DistanceMap.erase(&MI);
1524
1525 // Update LiveIntervals.
1526 if (LIS) {
1527 MachineBasicBlock::iterator Begin(NewMIs[0]);
1528 MachineBasicBlock::iterator End(NewMIs[1]);
1529 LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
1530 }
1531
1532 mi = NewMIs[1];
1533 } else {
1534 // Transforming didn't eliminate the tie and didn't lead to an
1535 // improvement. Clean up the unfolded instructions and keep the
1536 // original.
1537 LLVM_DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1538 NewMIs[0]->eraseFromParent();
1539 NewMIs[1]->eraseFromParent();
1540 DistanceMap.erase(NewMIs[0]);
1541 DistanceMap.erase(NewMIs[1]);
1542 Dist--;
1543 }
1544 }
1545 }
1546 }
1547
1548 return false;
1549}
1550
1551// Collect tied operands of MI that need to be handled.
1552// Rewrite trivial cases immediately.
1553// Return true if any tied operands where found, including the trivial ones.
1554bool TwoAddressInstructionImpl::collectTiedOperands(
1555 MachineInstr *MI, TiedOperandMap &TiedOperands) {
1556 bool AnyOps = false;
1557 unsigned NumOps = MI->getNumOperands();
1558
1559 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1560 unsigned DstIdx = 0;
1561 if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1562 continue;
1563 AnyOps = true;
1564 MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1565 MachineOperand &DstMO = MI->getOperand(DstIdx);
1566 Register SrcReg = SrcMO.getReg();
1567 Register DstReg = DstMO.getReg();
1568 // Tied constraint already satisfied?
1569 if (SrcReg == DstReg)
1570 continue;
1571
1572 assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
1573
1574 // Deal with undef uses immediately - simply rewrite the src operand.
1575 if (SrcMO.isUndef() && !DstMO.getSubReg()) {
1576 // Constrain the DstReg register class if required.
1577 if (DstReg.isVirtual()) {
1578 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
1579 MRI->constrainRegClass(DstReg, RC);
1580 }
1581 SrcMO.setReg(DstReg);
1582 SrcMO.setSubReg(0);
1583 LLVM_DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1584 continue;
1585 }
1586 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
1587 }
1588 return AnyOps;
1589}
1590
1591// Process a list of tied MI operands that all use the same source register.
1592// The tied pairs are of the form (SrcIdx, DstIdx).
1593void TwoAddressInstructionImpl::processTiedPairs(MachineInstr *MI,
1594 TiedPairList &TiedPairs,
1595 unsigned &Dist) {
1596 bool IsEarlyClobber = llvm::any_of(TiedPairs, [MI](auto const &TP) {
1597 return MI->getOperand(TP.second).isEarlyClobber();
1598 });
1599
1600 bool RemovedKillFlag = false;
1601 bool AllUsesCopied = true;
1602 Register LastCopiedReg;
1603 SlotIndex LastCopyIdx;
1604 Register RegB = 0;
1605 unsigned SubRegB = 0;
1606 for (auto &TP : TiedPairs) {
1607 unsigned SrcIdx = TP.first;
1608 unsigned DstIdx = TP.second;
1609
1610 const MachineOperand &DstMO = MI->getOperand(DstIdx);
1611 Register RegA = DstMO.getReg();
1612
1613 // Grab RegB from the instruction because it may have changed if the
1614 // instruction was commuted.
1615 RegB = MI->getOperand(SrcIdx).getReg();
1616 SubRegB = MI->getOperand(SrcIdx).getSubReg();
1617
1618 if (RegA == RegB) {
1619 // The register is tied to multiple destinations (or else we would
1620 // not have continued this far), but this use of the register
1621 // already matches the tied destination. Leave it.
1622 AllUsesCopied = false;
1623 continue;
1624 }
1625 LastCopiedReg = RegA;
1626
1627 assert(RegB.isVirtual() && "cannot make instruction into two-address form");
1628
1629#ifndef NDEBUG
1630 // First, verify that we don't have a use of "a" in the instruction
1631 // (a = b + a for example) because our transformation will not
1632 // work. This should never occur because we are in SSA form.
1633 for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1634 assert(i == DstIdx ||
1635 !MI->getOperand(i).isReg() ||
1636 MI->getOperand(i).getReg() != RegA);
1637#endif
1638
1639 // Emit a copy.
1640 MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1641 TII->get(TargetOpcode::COPY), RegA);
1642 // If this operand is folding a truncation, the truncation now moves to the
1643 // copy so that the register classes remain valid for the operands.
1644 MIB.addReg(RegB, {}, SubRegB);
1645 const TargetRegisterClass *RC = MRI->getRegClass(RegB);
1646 if (SubRegB) {
1647 if (RegA.isVirtual()) {
1648 assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA),
1649 SubRegB) &&
1650 "tied subregister must be a truncation");
1651 // The superreg class will not be used to constrain the subreg class.
1652 RC = nullptr;
1653 } else {
1654 assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB))
1655 && "tied subregister must be a truncation");
1656 }
1657 }
1658
1659 // Update DistanceMap.
1661 --PrevMI;
1662 DistanceMap.insert(std::make_pair(&*PrevMI, Dist));
1663 DistanceMap[MI] = ++Dist;
1664
1665 if (LIS) {
1666 LastCopyIdx = LIS->InsertMachineInstrInMaps(*PrevMI).getRegSlot();
1667
1668 SlotIndex endIdx =
1669 LIS->getInstructionIndex(*MI).getRegSlot(IsEarlyClobber);
1670 if (RegA.isVirtual()) {
1671 LiveInterval &LI = LIS->getInterval(RegA);
1672 VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1673 LI.addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1674 for (auto &S : LI.subranges()) {
1675 VNI = S.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1676 S.addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1677 }
1678 } else {
1679 for (MCRegUnit Unit : TRI->regunits(RegA)) {
1680 if (LiveRange *LR = LIS->getCachedRegUnit(Unit)) {
1681 VNInfo *VNI =
1682 LR->getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1683 LR->addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1684 }
1685 }
1686 }
1687 }
1688
1689 LLVM_DEBUG(dbgs() << "\t\tprepend:\t" << *MIB);
1690
1691 MachineOperand &MO = MI->getOperand(SrcIdx);
1692 assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1693 "inconsistent operand info for 2-reg pass");
1694 if (isPlainlyKilled(MO)) {
1695 MO.setIsKill(false);
1696 RemovedKillFlag = true;
1697 }
1698
1699 // Make sure regA is a legal regclass for the SrcIdx operand.
1700 if (RegA.isVirtual() && RegB.isVirtual())
1701 MRI->constrainRegClass(RegA, RC);
1702 MO.setReg(RegA);
1703 // The getMatchingSuper asserts guarantee that the register class projected
1704 // by SubRegB is compatible with RegA with no subregister. So regardless of
1705 // whether the dest oper writes a subreg, the source oper should not.
1706 MO.setSubReg(0);
1707
1708 // Update uses of RegB to uses of RegA inside the bundle.
1709 if (MI->isBundle()) {
1710 for (MachineOperand &MO : mi_bundle_ops(*MI)) {
1711 if (MO.isReg() && MO.getReg() == RegB) {
1712 assert(MO.getSubReg() == 0 && SubRegB == 0 &&
1713 "tied subregister uses in bundled instructions not supported");
1714 MO.setReg(RegA);
1715 }
1716 }
1717 }
1718 }
1719
1720 if (AllUsesCopied) {
1721 LaneBitmask RemainingUses = LaneBitmask::getNone();
1722 // Replace other (un-tied) uses of regB with LastCopiedReg.
1723 for (MachineOperand &MO : MI->all_uses()) {
1724 if (MO.getReg() == RegB) {
1725 if (MO.getSubReg() == SubRegB && !IsEarlyClobber) {
1726 if (isPlainlyKilled(MO)) {
1727 MO.setIsKill(false);
1728 RemovedKillFlag = true;
1729 }
1730 MO.setReg(LastCopiedReg);
1731 MO.setSubReg(0);
1732 } else {
1733 RemainingUses |= TRI->getSubRegIndexLaneMask(MO.getSubReg());
1734 }
1735 }
1736 }
1737
1738 // Update live variables for regB.
1739 if (RemovedKillFlag && RemainingUses.none() && LV &&
1740 LV->getVarInfo(RegB).removeKill(*MI)) {
1742 --PrevMI;
1743 LV->addVirtualRegisterKilled(RegB, *PrevMI);
1744 }
1745
1746 if (RemovedKillFlag && RemainingUses.none())
1747 SrcRegMap[LastCopiedReg] = RegB;
1748
1749 // Update LiveIntervals.
1750 if (LIS) {
1751 SlotIndex UseIdx = LIS->getInstructionIndex(*MI);
1752 auto Shrink = [=](LiveRange &LR, LaneBitmask LaneMask) {
1753 LiveRange::Segment *S = LR.getSegmentContaining(LastCopyIdx);
1754 if (!S)
1755 return true;
1756 if ((LaneMask & RemainingUses).any())
1757 return false;
1758 if (S->end.getBaseIndex() != UseIdx)
1759 return false;
1760 S->end = LastCopyIdx;
1761 return true;
1762 };
1763
1764 LiveInterval &LI = LIS->getInterval(RegB);
1765 bool ShrinkLI = true;
1766 for (auto &S : LI.subranges())
1767 ShrinkLI &= Shrink(S, S.LaneMask);
1768 if (ShrinkLI)
1769 Shrink(LI, LaneBitmask::getAll());
1770 }
1771 } else if (RemovedKillFlag) {
1772 // Some tied uses of regB matched their destination registers, so
1773 // regB is still used in this instruction, but a kill flag was
1774 // removed from a different tied use of regB, so now we need to add
1775 // a kill flag to one of the remaining uses of regB.
1776 for (MachineOperand &MO : MI->all_uses()) {
1777 if (MO.getReg() == RegB) {
1778 MO.setIsKill(true);
1779 break;
1780 }
1781 }
1782 }
1783}
1784
1785// For every tied operand pair this function transforms statepoint from
1786// RegA = STATEPOINT ... RegB(tied-def N)
1787// to
1788// RegB = STATEPOINT ... RegB(tied-def N)
1789// and replaces all uses of RegA with RegB.
1790// No extra COPY instruction is necessary because tied use is killed at
1791// STATEPOINT.
1792bool TwoAddressInstructionImpl::processStatepoint(
1793 MachineInstr *MI, TiedOperandMap &TiedOperands) {
1794
1795 bool NeedCopy = false;
1796 for (auto &TO : TiedOperands) {
1797 Register RegB = TO.first;
1798 if (TO.second.size() != 1) {
1799 NeedCopy = true;
1800 continue;
1801 }
1802
1803 unsigned SrcIdx = TO.second[0].first;
1804 unsigned DstIdx = TO.second[0].second;
1805
1806 MachineOperand &DstMO = MI->getOperand(DstIdx);
1807 Register RegA = DstMO.getReg();
1808
1809 assert(RegB == MI->getOperand(SrcIdx).getReg());
1810
1811 if (RegA == RegB)
1812 continue;
1813
1814 // CodeGenPrepare can sink pointer compare past statepoint, which
1815 // breaks assumption that statepoint kills tied-use register when
1816 // in SSA form (see note in IR/SafepointIRVerifier.cpp). Fall back
1817 // to generic tied register handling to avoid assertion failures.
1818 // TODO: Recompute LIS/LV information for new range here.
1819 if (LIS) {
1820 const auto &UseLI = LIS->getInterval(RegB);
1821 const auto &DefLI = LIS->getInterval(RegA);
1822 if (DefLI.overlaps(UseLI)) {
1823 LLVM_DEBUG(dbgs() << "LIS: " << printReg(RegB, TRI, 0)
1824 << " UseLI overlaps with DefLI\n");
1825 NeedCopy = true;
1826 continue;
1827 }
1828 } else if (LV && LV->getVarInfo(RegB).findKill(MI->getParent()) != MI) {
1829 // Note that MachineOperand::isKill does not work here, because it
1830 // is set only on first register use in instruction and for statepoint
1831 // tied-use register will usually be found in preceeding deopt bundle.
1832 LLVM_DEBUG(dbgs() << "LV: " << printReg(RegB, TRI, 0)
1833 << " not killed by statepoint\n");
1834 NeedCopy = true;
1835 continue;
1836 }
1837
1838 if (!MRI->constrainRegClass(RegB, MRI->getRegClass(RegA))) {
1839 LLVM_DEBUG(dbgs() << "MRI: couldn't constrain" << printReg(RegB, TRI, 0)
1840 << " to register class of " << printReg(RegA, TRI, 0)
1841 << '\n');
1842 NeedCopy = true;
1843 continue;
1844 }
1845 MRI->replaceRegWith(RegA, RegB);
1846
1847 if (LIS) {
1849 LiveInterval &LI = LIS->getInterval(RegB);
1850 LiveInterval &Other = LIS->getInterval(RegA);
1851 SmallVector<VNInfo *> NewVNIs;
1852 for (const VNInfo *VNI : Other.valnos) {
1853 assert(VNI->id == NewVNIs.size() && "assumed");
1854 NewVNIs.push_back(LI.createValueCopy(VNI, A));
1855 }
1856 for (auto &S : Other) {
1857 VNInfo *VNI = NewVNIs[S.valno->id];
1858 LiveRange::Segment NewSeg(S.start, S.end, VNI);
1859 LI.addSegment(NewSeg);
1860 }
1861 LIS->removeInterval(RegA);
1862 }
1863
1864 if (LV) {
1865 if (MI->getOperand(SrcIdx).isKill())
1866 LV->removeVirtualRegisterKilled(RegB, *MI);
1867 LiveVariables::VarInfo &SrcInfo = LV->getVarInfo(RegB);
1868 LiveVariables::VarInfo &DstInfo = LV->getVarInfo(RegA);
1869 SrcInfo.AliveBlocks |= DstInfo.AliveBlocks;
1870 DstInfo.AliveBlocks.clear();
1871 for (auto *KillMI : DstInfo.Kills)
1872 LV->addVirtualRegisterKilled(RegB, *KillMI, false);
1873 }
1874 }
1875 return !NeedCopy;
1876}
1877
1878/// Reduce two-address instructions to two operands.
1879bool TwoAddressInstructionImpl::run() {
1880 bool MadeChange = false;
1881
1882 LLVM_DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1883 LLVM_DEBUG(dbgs() << "********** Function: " << MF->getName() << '\n');
1884
1885 // This pass takes the function out of SSA form.
1886 MRI->leaveSSA();
1887
1888 // This pass will rewrite the tied-def to meet the RegConstraint.
1889 MF->getProperties().setTiedOpsRewritten();
1890
1891 TiedOperandMap TiedOperands;
1892 for (MachineBasicBlock &MBBI : *MF) {
1893 MBB = &MBBI;
1894 unsigned Dist = 0;
1895 DistanceMap.clear();
1896 SrcRegMap.clear();
1897 DstRegMap.clear();
1898 Processed.clear();
1899 for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
1900 mi != me; ) {
1901 MachineBasicBlock::iterator nmi = std::next(mi);
1902 // Skip debug instructions.
1903 if (mi->isDebugInstr()) {
1904 mi = nmi;
1905 continue;
1906 }
1907
1908 // Expand REG_SEQUENCE instructions. This will position mi at the first
1909 // expanded instruction.
1910 if (mi->isRegSequence()) {
1911 eliminateRegSequence(mi);
1912 MadeChange = true;
1913 }
1914
1915 DistanceMap.insert(std::make_pair(&*mi, ++Dist));
1916
1917 processCopy(&*mi);
1918
1919 // First scan through all the tied register uses in this instruction
1920 // and record a list of pairs of tied operands for each register.
1921 if (!collectTiedOperands(&*mi, TiedOperands)) {
1922 removeClobberedSrcRegMap(&*mi);
1923 mi = nmi;
1924 continue;
1925 }
1926
1927 ++NumTwoAddressInstrs;
1928 MadeChange = true;
1929 LLVM_DEBUG(dbgs() << '\t' << *mi);
1930
1931 // If the instruction has a single pair of tied operands, try some
1932 // transformations that may either eliminate the tied operands or
1933 // improve the opportunities for coalescing away the register copy.
1934 if (TiedOperands.size() == 1) {
1935 SmallVectorImpl<std::pair<unsigned, unsigned>> &TiedPairs
1936 = TiedOperands.begin()->second;
1937 if (TiedPairs.size() == 1) {
1938 unsigned SrcIdx = TiedPairs[0].first;
1939 unsigned DstIdx = TiedPairs[0].second;
1940 Register SrcReg = mi->getOperand(SrcIdx).getReg();
1941 Register DstReg = mi->getOperand(DstIdx).getReg();
1942 if (SrcReg != DstReg &&
1943 tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
1944 // The tied operands have been eliminated or shifted further down
1945 // the block to ease elimination. Continue processing with 'nmi'.
1946 TiedOperands.clear();
1947 removeClobberedSrcRegMap(&*mi);
1948 mi = nmi;
1949 continue;
1950 }
1951 }
1952 }
1953
1954 if (mi->getOpcode() == TargetOpcode::STATEPOINT &&
1955 processStatepoint(&*mi, TiedOperands)) {
1956 TiedOperands.clear();
1957 LLVM_DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1958 mi = nmi;
1959 continue;
1960 }
1961
1962 // Now iterate over the information collected above.
1963 for (auto &TO : TiedOperands) {
1964 processTiedPairs(&*mi, TO.second, Dist);
1965 LLVM_DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1966 }
1967
1968 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1969 if (mi->isInsertSubreg()) {
1970 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1971 // To %reg:subidx = COPY %subreg
1972 unsigned SubIdx = mi->getOperand(3).getImm();
1973 mi->removeOperand(3);
1974 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1975 mi->getOperand(0).setSubReg(SubIdx);
1976 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1977 mi->removeOperand(1);
1978 mi->setDesc(TII->get(TargetOpcode::COPY));
1979 LLVM_DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1980
1981 // Update LiveIntervals.
1982 if (LIS) {
1983 Register Reg = mi->getOperand(0).getReg();
1984 LiveInterval &LI = LIS->getInterval(Reg);
1985 if (LI.hasSubRanges()) {
1986 // The COPY no longer defines subregs of %reg except for
1987 // %reg.subidx.
1988 LaneBitmask LaneMask =
1989 TRI->getSubRegIndexLaneMask(mi->getOperand(0).getSubReg());
1990 SlotIndex Idx = LIS->getInstructionIndex(*mi).getRegSlot();
1991 for (auto &S : LI.subranges()) {
1992 if ((S.LaneMask & LaneMask).none()) {
1993 LiveRange::iterator DefSeg = S.FindSegmentContaining(Idx);
1994 if (mi->getOperand(0).isUndef()) {
1995 S.removeValNo(DefSeg->valno);
1996 } else {
1997 LiveRange::iterator UseSeg = std::prev(DefSeg);
1998 S.MergeValueNumberInto(DefSeg->valno, UseSeg->valno);
1999 }
2000 }
2001 }
2002
2003 // The COPY no longer has a use of %reg.
2004 LIS->shrinkToUses(&LI);
2005 } else {
2006 // The live interval for Reg did not have subranges but now it needs
2007 // them because we have introduced a subreg def. Recompute it.
2008 LIS->removeInterval(Reg);
2010 }
2011 }
2012 }
2013
2014 // Clear TiedOperands here instead of at the top of the loop
2015 // since most instructions do not have tied operands.
2016 TiedOperands.clear();
2017 removeClobberedSrcRegMap(&*mi);
2018 mi = nmi;
2019 }
2020 }
2021
2022 return MadeChange;
2023}
2024
2025/// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
2026///
2027/// The instruction is turned into a sequence of sub-register copies:
2028///
2029/// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
2030///
2031/// Becomes:
2032///
2033/// undef %dst:ssub0 = COPY %v1
2034/// %dst:ssub1 = COPY %v2
2035void TwoAddressInstructionImpl::eliminateRegSequence(
2037 MachineInstr &MI = *MBBI;
2038 Register DstReg = MI.getOperand(0).getReg();
2039
2040 SmallVector<Register, 4> OrigRegs;
2041 VNInfo *DefVN = nullptr;
2042 if (LIS) {
2043 OrigRegs.push_back(MI.getOperand(0).getReg());
2044 for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2)
2045 OrigRegs.push_back(MI.getOperand(i).getReg());
2046 if (LIS->hasInterval(DstReg)) {
2047 DefVN = LIS->getInterval(DstReg)
2049 .valueOut();
2050 }
2051 }
2052
2053 // Undef lanes still need a COPY when a later read may not be marked undef;
2054 // without live intervals that is every later read.
2055 LaneBitmask KeepLanes = LaneBitmask::getNone();
2056 for (const MachineOperand &Use : MRI->use_nodbg_operands(DstReg)) {
2057 unsigned SubReg = Use.getSubReg();
2058 if (SubReg &&
2059 (!LIS || Use.getParent()->hasTiedAndOtherReadOf(DstReg, SubReg)))
2060 KeepLanes |= TRI->getSubRegIndexLaneMask(SubReg);
2061 }
2062
2063 LaneBitmask UndefLanes = LaneBitmask::getNone();
2064 bool DefEmitted = false;
2065 for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2) {
2066 MachineOperand &UseMO = MI.getOperand(i);
2067 Register SrcReg = UseMO.getReg();
2068 unsigned SubIdx = MI.getOperand(i+1).getImm();
2069 // Nothing needs to be inserted for undef operands.
2070 if (UseMO.isUndef()) {
2071 LaneBitmask LaneMask = TRI->getSubRegIndexLaneMask(SubIdx);
2072 if ((KeepLanes & LaneMask).none()) {
2073 UndefLanes |= LaneMask;
2074 continue;
2075 }
2076 }
2077
2078 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
2079 // might insert a COPY that uses SrcReg after is was killed.
2080 bool isKill = UseMO.isKill();
2081 if (isKill)
2082 for (unsigned j = i + 2; j < e; j += 2)
2083 if (MI.getOperand(j).getReg() == SrcReg) {
2084 MI.getOperand(j).setIsKill();
2085 UseMO.setIsKill(false);
2086 isKill = false;
2087 break;
2088 }
2089
2090 // Insert the sub-register copy.
2091 MachineInstr *CopyMI = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
2092 TII->get(TargetOpcode::COPY))
2093 .addReg(DstReg, RegState::Define, SubIdx)
2094 .add(UseMO);
2095
2096 // The first def needs an undef flag because there is no live register
2097 // before it.
2098 if (!DefEmitted) {
2099 CopyMI->getOperand(0).setIsUndef(true);
2100 // Return an iterator pointing to the first inserted instr.
2101 MBBI = CopyMI;
2102 }
2103 DefEmitted = true;
2104
2105 // Update LiveVariables' kill info.
2106 if (LV && isKill && !SrcReg.isPhysical())
2107 LV->replaceKillInstruction(SrcReg, MI, *CopyMI);
2108
2109 LLVM_DEBUG(dbgs() << "Inserted: " << *CopyMI);
2110 }
2111
2113 std::next(MachineBasicBlock::iterator(MI));
2114
2115 if (!DefEmitted) {
2116 LLVM_DEBUG(dbgs() << "Turned: " << MI << " into an IMPLICIT_DEF");
2117 MI.setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
2118 for (int j = MI.getNumOperands() - 1, ee = 0; j > ee; --j)
2119 MI.removeOperand(j);
2120 // The dead def of DstReg is left in place, so its live range is still
2121 // correct. Drop it from the repaired set.
2122 if (LIS)
2123 llvm::erase(OrigRegs, DstReg);
2124 } else {
2125 if (LIS) {
2126 // Force live interval recomputation if we moved to a partial definition
2127 // of the register. Undef flags must be propagate to uses of undefined
2128 // subregister for accurate interval computation.
2129 if (UndefLanes.any() && DefVN && MRI->shouldTrackSubRegLiveness(DstReg)) {
2130 auto &LI = LIS->getInterval(DstReg);
2131 for (MachineOperand &UseOp : MRI->use_operands(DstReg)) {
2132 unsigned SubReg = UseOp.getSubReg();
2133 if (UseOp.isUndef() || !SubReg)
2134 continue;
2135 auto *VN =
2136 LI.getVNInfoAt(LIS->getInstructionIndex(*UseOp.getParent()));
2137 if (DefVN != VN)
2138 continue;
2139 LaneBitmask LaneMask = TRI->getSubRegIndexLaneMask(SubReg);
2140 if ((UndefLanes & LaneMask).any())
2141 UseOp.setIsUndef(true);
2142 }
2143 LIS->removeInterval(DstReg);
2144 }
2146 }
2147
2148 LLVM_DEBUG(dbgs() << "Eliminated: " << MI);
2149 MI.eraseFromParent();
2150 }
2151
2152 // Udpate LiveIntervals.
2153 if (LIS)
2154 LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);
2155}
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file defines the DenseMap class.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
Remove Loads Into Fake Uses
SI Optimize VGPR LiveRange
This file defines the SmallPtrSet class.
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:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static bool isTwoAddrUse(MachineInstr &MI, Register Reg, Register &DstReg)
Return true if the specified MI uses the specified register as a two-address use.
static bool getTiedUse(Register DefReg, MachineInstr *MI, const TargetRegisterInfo *TRI, unsigned &TiedOpIdx)
static MCRegister getMappedReg(Register Reg, DenseMap< Register, Register > &RegMap)
Return the physical register the specified virtual register might be mapped to.
static cl::opt< bool > EnableRescheduling("twoaddr-reschedule", cl::desc("Coalesce copies by rescheduling (default=true)"), cl::init(true), cl::Hidden)
static cl::opt< bool > AnalyzeRevCopyTied("twoaddr-analyze-revcopy-tied", cl::desc("Analyze tied operands when looking for reversed copy chain"), cl::init(true), cl::Hidden)
static cl::opt< unsigned > MaxDataFlowEdge("dataflow-edge-limit", cl::Hidden, cl::init(10), cl::desc("Maximum number of dataflow edges to traverse when evaluating " "the benefit of commuting operands"))
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:278
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:258
bool erase(const KeyT &Val)
Definition DenseMap.h:426
iterator end()
Definition DenseMap.h:176
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:319
bool hasOptNone() const
Do not optimize this function (-O0).
Definition Function.h:686
unsigned getInstrLatency(const InstrItineraryData *ItinData, const MachineInstr &MI, unsigned *PredCost=nullptr) const override
Compute the instruction latency of a given instruction.
Itinerary data supplied by a subtarget to be used by a target.
bool hasSubRanges() const
Returns true if subregister liveness information is available.
iterator_range< subrange_iterator > subranges()
LLVM_ABI void repairIntervalsInRange(MachineBasicBlock *MBB, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, ArrayRef< Register > OrigRegs)
Update live intervals for instructions in a range of iterators.
bool hasInterval(Register Reg) const
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
LLVM_ABI void handleMove(MachineInstr &MI, bool UpdateFlags=false)
Call this method to notify LiveIntervals that instruction MI has been moved within a basic block.
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
void RemoveMachineInstrFromMaps(MachineInstr &MI)
VNInfo::Allocator & getVNInfoAllocator()
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
LiveInterval & getInterval(Register Reg)
void removeInterval(Register Reg)
Interval removal.
bool isNotInMIMap(const MachineInstr &Instr) const
Returns true if the specified machine instr has been removed or was never entered in the map.
LiveRange * getCachedRegUnit(MCRegUnit Unit)
Return the live range for register unit Unit if it has already been computed, or nullptr if it hasn't...
LLVM_ABI bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=nullptr)
After removing some uses of a register, shrink its live range to just the remaining uses.
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
VNInfo * valueOut() const
Return the value leaving the instruction, if any.
This class represents the liveness of a register, stack slot, etc.
LLVM_ABI iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
const Segment * getSegmentContaining(SlotIndex Idx) const
Return the segment that contains the specified index, or null if there is none.
VNInfo * createValueCopy(const VNInfo *orig, VNInfo::Allocator &VNInfoAllocator)
Create a copy of the given value.
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
iterator begin()
bool hasAtLeastOneValue() const
VNInfo * getNextValue(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator)
getNextValue - Create a new value number and return it.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
LLVM_ABI iterator find(SlotIndex Pos)
find - Return an iterator pointing to the first segment that ends after Pos, or end().
LLVM_ABI void replaceKillInstruction(Register Reg, MachineInstr &OldMI, MachineInstr &NewMI)
replaceKillInstruction - Update register kill info by replacing a kill instruction with a new one.
bool removeVirtualRegisterDead(Register Reg, MachineInstr &MI)
removeVirtualRegisterDead - Remove the specified kill of the virtual register from the live variable ...
bool removeVirtualRegisterKilled(Register Reg, MachineInstr &MI)
removeVirtualRegisterKilled - Remove the specified kill of the virtual register from the live variabl...
void addVirtualRegisterDead(Register IncomingReg, MachineInstr &MI, bool AddIfNotFound=false)
addVirtualRegisterDead - Add information about the fact that the specified register is dead after bei...
void addVirtualRegisterKilled(Register IncomingReg, MachineInstr &MI, bool AddIfNotFound=false)
addVirtualRegisterKilled - Add information about the fact that the specified register is killed after...
LLVM_ABI VarInfo & getVarInfo(Register Reg)
getVarInfo - Return the VarInfo structure for the specified VIRTUAL register.
unsigned getNumDefs() const
Return the number of MachineOperands that are register definitions.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
An RAII based helper class to modify MachineFunctionProperties when running pass.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
void makeDebugValueSubstitution(DebugInstrOperandPair, DebugInstrOperandPair, unsigned SubReg=0)
Create a substitution between one <instr,operand> value to a different, new value.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineFunctionProperties & getProperties() const
Get the function properties.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
Representation of each machine instruction.
mop_range defs()
Returns all explicit operands that are register definitions.
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
bool isCopy() const
bool isCopyLike() const
Return true if the instruction behaves like a copy.
bool isCall(QueryType Type=AnyInBundle) const
LLVM_ABI bool isSafeToMove(bool &SawStore) const
Return true if it is safe to move this instruction.
bool isBranch(QueryType Type=AnyInBundle) const
Returns true if this is a conditional, unconditional, or indirect branch.
mop_range operands()
LLVM_ABI bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore,...
LLVM_ABI unsigned getNumExplicitDefs() const
Returns the number of non-implicit definitions.
LLVM_ABI unsigned getDebugInstrNum()
Fetch the instruction number of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
LLVM_ABI unsigned getOperandNo() const
Returns the index of this operand in the instruction that it belongs to.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsKill(bool Val=true)
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
iterator_range< reg_iterator > reg_operands(Register Reg) const
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
iterator_range< def_instr_iterator > def_instructions(Register Reg) const
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
def_iterator def_begin(Register RegNo) const
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
bool hasOneUse(Register RegNo) const
hasOneUse - Return true if there is exactly one instruction using the specified register.
bool shouldTrackSubRegLiveness(const TargetRegisterClass &RC) const
Returns true if liveness for register class RC should be tracked at the subregister level.
defusechain_iterator< false, true, false, true, false > def_iterator
def_iterator/def_begin/def_end - Walk all defs of the specified register.
static def_iterator def_end()
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
iterator_range< use_iterator > use_operands(Register Reg) const
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
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
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
static const unsigned CommuteAnyOperandIndex
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
BumpPtrAllocator Allocator
unsigned id
The ID number of this value.
IteratorT begin() const
Changed
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
constexpr bool any(E Val)
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
constexpr double e
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
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.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2216
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:227
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ Other
Any other memory.
Definition ModRef.h:68
iterator_range< MIBundleOperands > mi_bundle_ops(MachineInstr &MI)
LLVM_ABI char & TwoAddressInstructionPassID
TwoAddressInstruction - This pass reduces two-address instructions to use two operands.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
static constexpr LaneBitmask getAll()
Definition LaneBitmask.h:82
constexpr bool none() const
Definition LaneBitmask.h:52
constexpr bool any() const
Definition LaneBitmask.h:53
static constexpr LaneBitmask getNone()
Definition LaneBitmask.h:81
bool removeKill(MachineInstr &MI)
removeKill - Delete a kill corresponding to the specified machine instruction.
std::vector< MachineInstr * > Kills
Kills - List of MachineInstruction's which are the last use of this virtual register (kill it) in the...
SparseBitVector AliveBlocks
AliveBlocks - Set of blocks in which this value is alive completely through.
LLVM_ABI MachineInstr * findKill(const MachineBasicBlock *MBB) const
findKill - Find a kill instruction in MBB. Return NULL if none is found.