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