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