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