1 //==- TargetRegisterInfo.cpp - Target Register Information Implementation --==//
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 TargetRegisterInfo interface.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/TargetRegisterInfo.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/LiveInterval.h"
23 #include "llvm/CodeGen/TargetFrameLowering.h"
24 #include "llvm/CodeGen/TargetInstrInfo.h"
25 #include "llvm/CodeGen/TargetSubtargetInfo.h"
26 #include "llvm/CodeGen/VirtRegMap.h"
27 #include "llvm/Config/llvm-config.h"
28 #include "llvm/IR/Attributes.h"
29 #include "llvm/IR/DebugInfoMetadata.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/MachineValueType.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Printable.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <cassert>
40 #include <utility>
41 
42 #define DEBUG_TYPE "target-reg-info"
43 
44 using namespace llvm;
45 
46 static cl::opt<unsigned>
47     HugeSizeForSplit("huge-size-for-split", cl::Hidden,
48                      cl::desc("A threshold of live range size which may cause "
49                               "high compile time cost in global splitting."),
50                      cl::init(5000));
51 
52 TargetRegisterInfo::TargetRegisterInfo(const TargetRegisterInfoDesc *ID,
53                              regclass_iterator RCB, regclass_iterator RCE,
54                              const char *const *SRINames,
55                              const LaneBitmask *SRILaneMasks,
56                              LaneBitmask SRICoveringLanes,
57                              const RegClassInfo *const RCIs,
58                              unsigned Mode)
59   : InfoDesc(ID), SubRegIndexNames(SRINames),
60     SubRegIndexLaneMasks(SRILaneMasks),
61     RegClassBegin(RCB), RegClassEnd(RCE),
62     CoveringLanes(SRICoveringLanes),
63     RCInfos(RCIs), HwMode(Mode) {
64 }
65 
66 TargetRegisterInfo::~TargetRegisterInfo() = default;
67 
68 bool TargetRegisterInfo::shouldRegionSplitForVirtReg(
69     const MachineFunction &MF, const LiveInterval &VirtReg) const {
70   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
71   const MachineRegisterInfo &MRI = MF.getRegInfo();
72   MachineInstr *MI = MRI.getUniqueVRegDef(VirtReg.reg());
73   if (MI && TII->isTriviallyReMaterializable(*MI) &&
74       VirtReg.size() > HugeSizeForSplit)
75     return false;
76   return true;
77 }
78 
79 void TargetRegisterInfo::markSuperRegs(BitVector &RegisterSet,
80                                        MCRegister Reg) const {
81   for (MCSuperRegIterator AI(Reg, this, true); AI.isValid(); ++AI)
82     RegisterSet.set(*AI);
83 }
84 
85 bool TargetRegisterInfo::checkAllSuperRegsMarked(const BitVector &RegisterSet,
86     ArrayRef<MCPhysReg> Exceptions) const {
87   // Check that all super registers of reserved regs are reserved as well.
88   BitVector Checked(getNumRegs());
89   for (unsigned Reg : RegisterSet.set_bits()) {
90     if (Checked[Reg])
91       continue;
92     for (MCSuperRegIterator SR(Reg, this); SR.isValid(); ++SR) {
93       if (!RegisterSet[*SR] && !is_contained(Exceptions, Reg)) {
94         dbgs() << "Error: Super register " << printReg(*SR, this)
95                << " of reserved register " << printReg(Reg, this)
96                << " is not reserved.\n";
97         return false;
98       }
99 
100       // We transitively check superregs. So we can remember this for later
101       // to avoid compiletime explosion in deep register hierarchies.
102       Checked.set(*SR);
103     }
104   }
105   return true;
106 }
107 
108 namespace llvm {
109 
110 Printable printReg(Register Reg, const TargetRegisterInfo *TRI,
111                    unsigned SubIdx, const MachineRegisterInfo *MRI) {
112   return Printable([Reg, TRI, SubIdx, MRI](raw_ostream &OS) {
113     if (!Reg)
114       OS << "$noreg";
115     else if (Register::isStackSlot(Reg))
116       OS << "SS#" << Register::stackSlot2Index(Reg);
117     else if (Register::isVirtualRegister(Reg)) {
118       StringRef Name = MRI ? MRI->getVRegName(Reg) : "";
119       if (Name != "") {
120         OS << '%' << Name;
121       } else {
122         OS << '%' << Register::virtReg2Index(Reg);
123       }
124     } else if (!TRI)
125       OS << '$' << "physreg" << Reg;
126     else if (Reg < TRI->getNumRegs()) {
127       OS << '$';
128       printLowerCase(TRI->getName(Reg), OS);
129     } else
130       llvm_unreachable("Register kind is unsupported.");
131 
132     if (SubIdx) {
133       if (TRI)
134         OS << ':' << TRI->getSubRegIndexName(SubIdx);
135       else
136         OS << ":sub(" << SubIdx << ')';
137     }
138   });
139 }
140 
141 Printable printRegUnit(unsigned Unit, const TargetRegisterInfo *TRI) {
142   return Printable([Unit, TRI](raw_ostream &OS) {
143     // Generic printout when TRI is missing.
144     if (!TRI) {
145       OS << "Unit~" << Unit;
146       return;
147     }
148 
149     // Check for invalid register units.
150     if (Unit >= TRI->getNumRegUnits()) {
151       OS << "BadUnit~" << Unit;
152       return;
153     }
154 
155     // Normal units have at least one root.
156     MCRegUnitRootIterator Roots(Unit, TRI);
157     assert(Roots.isValid() && "Unit has no roots.");
158     OS << TRI->getName(*Roots);
159     for (++Roots; Roots.isValid(); ++Roots)
160       OS << '~' << TRI->getName(*Roots);
161   });
162 }
163 
164 Printable printVRegOrUnit(unsigned Unit, const TargetRegisterInfo *TRI) {
165   return Printable([Unit, TRI](raw_ostream &OS) {
166     if (Register::isVirtualRegister(Unit)) {
167       OS << '%' << Register::virtReg2Index(Unit);
168     } else {
169       OS << printRegUnit(Unit, TRI);
170     }
171   });
172 }
173 
174 Printable printRegClassOrBank(Register Reg, const MachineRegisterInfo &RegInfo,
175                               const TargetRegisterInfo *TRI) {
176   return Printable([Reg, &RegInfo, TRI](raw_ostream &OS) {
177     if (RegInfo.getRegClassOrNull(Reg))
178       OS << StringRef(TRI->getRegClassName(RegInfo.getRegClass(Reg))).lower();
179     else if (RegInfo.getRegBankOrNull(Reg))
180       OS << StringRef(RegInfo.getRegBankOrNull(Reg)->getName()).lower();
181     else {
182       OS << "_";
183       assert((RegInfo.def_empty(Reg) || RegInfo.getType(Reg).isValid()) &&
184              "Generic registers must have a valid type");
185     }
186   });
187 }
188 
189 } // end namespace llvm
190 
191 /// getAllocatableClass - Return the maximal subclass of the given register
192 /// class that is alloctable, or NULL.
193 const TargetRegisterClass *
194 TargetRegisterInfo::getAllocatableClass(const TargetRegisterClass *RC) const {
195   if (!RC || RC->isAllocatable())
196     return RC;
197 
198   for (BitMaskClassIterator It(RC->getSubClassMask(), *this); It.isValid();
199        ++It) {
200     const TargetRegisterClass *SubRC = getRegClass(It.getID());
201     if (SubRC->isAllocatable())
202       return SubRC;
203   }
204   return nullptr;
205 }
206 
207 /// getMinimalPhysRegClass - Returns the Register Class of a physical
208 /// register of the given type, picking the most sub register class of
209 /// the right type that contains this physreg.
210 const TargetRegisterClass *
211 TargetRegisterInfo::getMinimalPhysRegClass(MCRegister reg, MVT VT) const {
212   assert(Register::isPhysicalRegister(reg) &&
213          "reg must be a physical register");
214 
215   // Pick the most sub register class of the right type that contains
216   // this physreg.
217   const TargetRegisterClass* BestRC = nullptr;
218   for (const TargetRegisterClass* RC : regclasses()) {
219     if ((VT == MVT::Other || isTypeLegalForClass(*RC, VT)) &&
220         RC->contains(reg) && (!BestRC || BestRC->hasSubClass(RC)))
221       BestRC = RC;
222   }
223 
224   assert(BestRC && "Couldn't find the register class");
225   return BestRC;
226 }
227 
228 const TargetRegisterClass *
229 TargetRegisterInfo::getMinimalPhysRegClassLLT(MCRegister reg, LLT Ty) const {
230   assert(Register::isPhysicalRegister(reg) &&
231          "reg must be a physical register");
232 
233   // Pick the most sub register class of the right type that contains
234   // this physreg.
235   const TargetRegisterClass *BestRC = nullptr;
236   for (const TargetRegisterClass *RC : regclasses()) {
237     if ((!Ty.isValid() || isTypeLegalForClass(*RC, Ty)) && RC->contains(reg) &&
238         (!BestRC || BestRC->hasSubClass(RC)))
239       BestRC = RC;
240   }
241 
242   return BestRC;
243 }
244 
245 /// getAllocatableSetForRC - Toggle the bits that represent allocatable
246 /// registers for the specific register class.
247 static void getAllocatableSetForRC(const MachineFunction &MF,
248                                    const TargetRegisterClass *RC, BitVector &R){
249   assert(RC->isAllocatable() && "invalid for nonallocatable sets");
250   ArrayRef<MCPhysReg> Order = RC->getRawAllocationOrder(MF);
251   for (unsigned i = 0; i != Order.size(); ++i)
252     R.set(Order[i]);
253 }
254 
255 BitVector TargetRegisterInfo::getAllocatableSet(const MachineFunction &MF,
256                                           const TargetRegisterClass *RC) const {
257   BitVector Allocatable(getNumRegs());
258   if (RC) {
259     // A register class with no allocatable subclass returns an empty set.
260     const TargetRegisterClass *SubClass = getAllocatableClass(RC);
261     if (SubClass)
262       getAllocatableSetForRC(MF, SubClass, Allocatable);
263   } else {
264     for (const TargetRegisterClass *C : regclasses())
265       if (C->isAllocatable())
266         getAllocatableSetForRC(MF, C, Allocatable);
267   }
268 
269   // Mask out the reserved registers
270   BitVector Reserved = getReservedRegs(MF);
271   Allocatable &= Reserved.flip();
272 
273   return Allocatable;
274 }
275 
276 static inline
277 const TargetRegisterClass *firstCommonClass(const uint32_t *A,
278                                             const uint32_t *B,
279                                             const TargetRegisterInfo *TRI) {
280   for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; I += 32)
281     if (unsigned Common = *A++ & *B++)
282       return TRI->getRegClass(I + countTrailingZeros(Common));
283   return nullptr;
284 }
285 
286 const TargetRegisterClass *
287 TargetRegisterInfo::getCommonSubClass(const TargetRegisterClass *A,
288                                       const TargetRegisterClass *B) const {
289   // First take care of the trivial cases.
290   if (A == B)
291     return A;
292   if (!A || !B)
293     return nullptr;
294 
295   // Register classes are ordered topologically, so the largest common
296   // sub-class it the common sub-class with the smallest ID.
297   return firstCommonClass(A->getSubClassMask(), B->getSubClassMask(), this);
298 }
299 
300 const TargetRegisterClass *
301 TargetRegisterInfo::getMatchingSuperRegClass(const TargetRegisterClass *A,
302                                              const TargetRegisterClass *B,
303                                              unsigned Idx) const {
304   assert(A && B && "Missing register class");
305   assert(Idx && "Bad sub-register index");
306 
307   // Find Idx in the list of super-register indices.
308   for (SuperRegClassIterator RCI(B, this); RCI.isValid(); ++RCI)
309     if (RCI.getSubReg() == Idx)
310       // The bit mask contains all register classes that are projected into B
311       // by Idx. Find a class that is also a sub-class of A.
312       return firstCommonClass(RCI.getMask(), A->getSubClassMask(), this);
313   return nullptr;
314 }
315 
316 const TargetRegisterClass *TargetRegisterInfo::
317 getCommonSuperRegClass(const TargetRegisterClass *RCA, unsigned SubA,
318                        const TargetRegisterClass *RCB, unsigned SubB,
319                        unsigned &PreA, unsigned &PreB) const {
320   assert(RCA && SubA && RCB && SubB && "Invalid arguments");
321 
322   // Search all pairs of sub-register indices that project into RCA and RCB
323   // respectively. This is quadratic, but usually the sets are very small. On
324   // most targets like X86, there will only be a single sub-register index
325   // (e.g., sub_16bit projecting into GR16).
326   //
327   // The worst case is a register class like DPR on ARM.
328   // We have indices dsub_0..dsub_7 projecting into that class.
329   //
330   // It is very common that one register class is a sub-register of the other.
331   // Arrange for RCA to be the larger register so the answer will be found in
332   // the first iteration. This makes the search linear for the most common
333   // case.
334   const TargetRegisterClass *BestRC = nullptr;
335   unsigned *BestPreA = &PreA;
336   unsigned *BestPreB = &PreB;
337   if (getRegSizeInBits(*RCA) < getRegSizeInBits(*RCB)) {
338     std::swap(RCA, RCB);
339     std::swap(SubA, SubB);
340     std::swap(BestPreA, BestPreB);
341   }
342 
343   // Also terminate the search one we have found a register class as small as
344   // RCA.
345   unsigned MinSize = getRegSizeInBits(*RCA);
346 
347   for (SuperRegClassIterator IA(RCA, this, true); IA.isValid(); ++IA) {
348     unsigned FinalA = composeSubRegIndices(IA.getSubReg(), SubA);
349     for (SuperRegClassIterator IB(RCB, this, true); IB.isValid(); ++IB) {
350       // Check if a common super-register class exists for this index pair.
351       const TargetRegisterClass *RC =
352         firstCommonClass(IA.getMask(), IB.getMask(), this);
353       if (!RC || getRegSizeInBits(*RC) < MinSize)
354         continue;
355 
356       // The indexes must compose identically: PreA+SubA == PreB+SubB.
357       unsigned FinalB = composeSubRegIndices(IB.getSubReg(), SubB);
358       if (FinalA != FinalB)
359         continue;
360 
361       // Is RC a better candidate than BestRC?
362       if (BestRC && getRegSizeInBits(*RC) >= getRegSizeInBits(*BestRC))
363         continue;
364 
365       // Yes, RC is the smallest super-register seen so far.
366       BestRC = RC;
367       *BestPreA = IA.getSubReg();
368       *BestPreB = IB.getSubReg();
369 
370       // Bail early if we reached MinSize. We won't find a better candidate.
371       if (getRegSizeInBits(*BestRC) == MinSize)
372         return BestRC;
373     }
374   }
375   return BestRC;
376 }
377 
378 /// Check if the registers defined by the pair (RegisterClass, SubReg)
379 /// share the same register file.
380 static bool shareSameRegisterFile(const TargetRegisterInfo &TRI,
381                                   const TargetRegisterClass *DefRC,
382                                   unsigned DefSubReg,
383                                   const TargetRegisterClass *SrcRC,
384                                   unsigned SrcSubReg) {
385   // Same register class.
386   if (DefRC == SrcRC)
387     return true;
388 
389   // Both operands are sub registers. Check if they share a register class.
390   unsigned SrcIdx, DefIdx;
391   if (SrcSubReg && DefSubReg) {
392     return TRI.getCommonSuperRegClass(SrcRC, SrcSubReg, DefRC, DefSubReg,
393                                       SrcIdx, DefIdx) != nullptr;
394   }
395 
396   // At most one of the register is a sub register, make it Src to avoid
397   // duplicating the test.
398   if (!SrcSubReg) {
399     std::swap(DefSubReg, SrcSubReg);
400     std::swap(DefRC, SrcRC);
401   }
402 
403   // One of the register is a sub register, check if we can get a superclass.
404   if (SrcSubReg)
405     return TRI.getMatchingSuperRegClass(SrcRC, DefRC, SrcSubReg) != nullptr;
406 
407   // Plain copy.
408   return TRI.getCommonSubClass(DefRC, SrcRC) != nullptr;
409 }
410 
411 bool TargetRegisterInfo::shouldRewriteCopySrc(const TargetRegisterClass *DefRC,
412                                               unsigned DefSubReg,
413                                               const TargetRegisterClass *SrcRC,
414                                               unsigned SrcSubReg) const {
415   // If this source does not incur a cross register bank copy, use it.
416   return shareSameRegisterFile(*this, DefRC, DefSubReg, SrcRC, SrcSubReg);
417 }
418 
419 // Compute target-independent register allocator hints to help eliminate copies.
420 bool TargetRegisterInfo::getRegAllocationHints(
421     Register VirtReg, ArrayRef<MCPhysReg> Order,
422     SmallVectorImpl<MCPhysReg> &Hints, const MachineFunction &MF,
423     const VirtRegMap *VRM, const LiveRegMatrix *Matrix) const {
424   const MachineRegisterInfo &MRI = MF.getRegInfo();
425   const std::pair<Register, SmallVector<Register, 4>> &Hints_MRI =
426     MRI.getRegAllocationHints(VirtReg);
427 
428   SmallSet<Register, 32> HintedRegs;
429   // First hint may be a target hint.
430   bool Skip = (Hints_MRI.first != 0);
431   for (auto Reg : Hints_MRI.second) {
432     if (Skip) {
433       Skip = false;
434       continue;
435     }
436 
437     // Target-independent hints are either a physical or a virtual register.
438     Register Phys = Reg;
439     if (VRM && Phys.isVirtual())
440       Phys = VRM->getPhys(Phys);
441 
442     // Don't add the same reg twice (Hints_MRI may contain multiple virtual
443     // registers allocated to the same physreg).
444     if (!HintedRegs.insert(Phys).second)
445       continue;
446     // Check that Phys is a valid hint in VirtReg's register class.
447     if (!Phys.isPhysical())
448       continue;
449     if (MRI.isReserved(Phys))
450       continue;
451     // Check that Phys is in the allocation order. We shouldn't heed hints
452     // from VirtReg's register class if they aren't in the allocation order. The
453     // target probably has a reason for removing the register.
454     if (!is_contained(Order, Phys))
455       continue;
456 
457     // All clear, tell the register allocator to prefer this register.
458     Hints.push_back(Phys);
459   }
460   return false;
461 }
462 
463 bool TargetRegisterInfo::isCalleeSavedPhysReg(
464     MCRegister PhysReg, const MachineFunction &MF) const {
465   if (PhysReg == 0)
466     return false;
467   const uint32_t *callerPreservedRegs =
468       getCallPreservedMask(MF, MF.getFunction().getCallingConv());
469   if (callerPreservedRegs) {
470     assert(Register::isPhysicalRegister(PhysReg) &&
471            "Expected physical register");
472     return (callerPreservedRegs[PhysReg / 32] >> PhysReg % 32) & 1;
473   }
474   return false;
475 }
476 
477 bool TargetRegisterInfo::canRealignStack(const MachineFunction &MF) const {
478   return !MF.getFunction().hasFnAttribute("no-realign-stack");
479 }
480 
481 bool TargetRegisterInfo::shouldRealignStack(const MachineFunction &MF) const {
482   const MachineFrameInfo &MFI = MF.getFrameInfo();
483   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
484   const Function &F = MF.getFunction();
485   return F.hasFnAttribute("stackrealign") ||
486          (MFI.getMaxAlign() > TFI->getStackAlign()) ||
487          F.hasFnAttribute(Attribute::StackAlignment);
488 }
489 
490 bool TargetRegisterInfo::regmaskSubsetEqual(const uint32_t *mask0,
491                                             const uint32_t *mask1) const {
492   unsigned N = (getNumRegs()+31) / 32;
493   for (unsigned I = 0; I < N; ++I)
494     if ((mask0[I] & mask1[I]) != mask0[I])
495       return false;
496   return true;
497 }
498 
499 unsigned
500 TargetRegisterInfo::getRegSizeInBits(Register Reg,
501                                      const MachineRegisterInfo &MRI) const {
502   const TargetRegisterClass *RC{};
503   if (Reg.isPhysical()) {
504     // The size is not directly available for physical registers.
505     // Instead, we need to access a register class that contains Reg and
506     // get the size of that register class.
507     RC = getMinimalPhysRegClass(Reg);
508   } else {
509     LLT Ty = MRI.getType(Reg);
510     unsigned RegSize = Ty.isValid() ? Ty.getSizeInBits() : 0;
511     // If Reg is not a generic register, query the register class to
512     // get its size.
513     if (RegSize)
514       return RegSize;
515     // Since Reg is not a generic register, it must have a register class.
516     RC = MRI.getRegClass(Reg);
517   }
518   assert(RC && "Unable to deduce the register class");
519   return getRegSizeInBits(*RC);
520 }
521 
522 bool TargetRegisterInfo::getCoveringSubRegIndexes(
523     const MachineRegisterInfo &MRI, const TargetRegisterClass *RC,
524     LaneBitmask LaneMask, SmallVectorImpl<unsigned> &NeededIndexes) const {
525   SmallVector<unsigned, 8> PossibleIndexes;
526   unsigned BestIdx = 0;
527   unsigned BestCover = 0;
528 
529   for (unsigned Idx = 1, E = getNumSubRegIndices(); Idx < E; ++Idx) {
530     // Is this index even compatible with the given class?
531     if (getSubClassWithSubReg(RC, Idx) != RC)
532       continue;
533     LaneBitmask SubRegMask = getSubRegIndexLaneMask(Idx);
534     // Early exit if we found a perfect match.
535     if (SubRegMask == LaneMask) {
536       BestIdx = Idx;
537       break;
538     }
539 
540     // The index must not cover any lanes outside \p LaneMask.
541     if ((SubRegMask & ~LaneMask).any())
542       continue;
543 
544     unsigned PopCount = SubRegMask.getNumLanes();
545     PossibleIndexes.push_back(Idx);
546     if (PopCount > BestCover) {
547       BestCover = PopCount;
548       BestIdx = Idx;
549     }
550   }
551 
552   // Abort if we cannot possibly implement the COPY with the given indexes.
553   if (BestIdx == 0)
554     return 0;
555 
556   NeededIndexes.push_back(BestIdx);
557 
558   // Greedy heuristic: Keep iterating keeping the best covering subreg index
559   // each time.
560   LaneBitmask LanesLeft = LaneMask & ~getSubRegIndexLaneMask(BestIdx);
561   while (LanesLeft.any()) {
562     unsigned BestIdx = 0;
563     int BestCover = std::numeric_limits<int>::min();
564     for (unsigned Idx : PossibleIndexes) {
565       LaneBitmask SubRegMask = getSubRegIndexLaneMask(Idx);
566       // Early exit if we found a perfect match.
567       if (SubRegMask == LanesLeft) {
568         BestIdx = Idx;
569         break;
570       }
571 
572       // Try to cover as much of the remaining lanes as possible but
573       // as few of the already covered lanes as possible.
574       int Cover = (SubRegMask & LanesLeft).getNumLanes() -
575                   (SubRegMask & ~LanesLeft).getNumLanes();
576       if (Cover > BestCover) {
577         BestCover = Cover;
578         BestIdx = Idx;
579       }
580     }
581 
582     if (BestIdx == 0)
583       return 0; // Impossible to handle
584 
585     NeededIndexes.push_back(BestIdx);
586 
587     LanesLeft &= ~getSubRegIndexLaneMask(BestIdx);
588   }
589 
590   return BestIdx;
591 }
592 
593 Register
594 TargetRegisterInfo::lookThruCopyLike(Register SrcReg,
595                                      const MachineRegisterInfo *MRI) const {
596   while (true) {
597     const MachineInstr *MI = MRI->getVRegDef(SrcReg);
598     if (!MI->isCopyLike())
599       return SrcReg;
600 
601     Register CopySrcReg;
602     if (MI->isCopy())
603       CopySrcReg = MI->getOperand(1).getReg();
604     else {
605       assert(MI->isSubregToReg() && "Bad opcode for lookThruCopyLike");
606       CopySrcReg = MI->getOperand(2).getReg();
607     }
608 
609     if (!CopySrcReg.isVirtual())
610       return CopySrcReg;
611 
612     SrcReg = CopySrcReg;
613   }
614 }
615 
616 Register TargetRegisterInfo::lookThruSingleUseCopyChain(
617     Register SrcReg, const MachineRegisterInfo *MRI) const {
618   while (true) {
619     const MachineInstr *MI = MRI->getVRegDef(SrcReg);
620     // Found the real definition, return it if it has a single use.
621     if (!MI->isCopyLike())
622       return MRI->hasOneNonDBGUse(SrcReg) ? SrcReg : Register();
623 
624     Register CopySrcReg;
625     if (MI->isCopy())
626       CopySrcReg = MI->getOperand(1).getReg();
627     else {
628       assert(MI->isSubregToReg() && "Bad opcode for lookThruCopyLike");
629       CopySrcReg = MI->getOperand(2).getReg();
630     }
631 
632     // Continue only if the next definition in the chain is for a virtual
633     // register that has a single use.
634     if (!CopySrcReg.isVirtual() || !MRI->hasOneNonDBGUse(CopySrcReg))
635       return Register();
636 
637     SrcReg = CopySrcReg;
638   }
639 }
640 
641 void TargetRegisterInfo::getOffsetOpcodes(
642     const StackOffset &Offset, SmallVectorImpl<uint64_t> &Ops) const {
643   assert(!Offset.getScalable() && "Scalable offsets are not handled");
644   DIExpression::appendOffset(Ops, Offset.getFixed());
645 }
646 
647 DIExpression *
648 TargetRegisterInfo::prependOffsetExpression(const DIExpression *Expr,
649                                             unsigned PrependFlags,
650                                             const StackOffset &Offset) const {
651   assert((PrependFlags &
652           ~(DIExpression::DerefBefore | DIExpression::DerefAfter |
653             DIExpression::StackValue | DIExpression::EntryValue)) == 0 &&
654          "Unsupported prepend flag");
655   SmallVector<uint64_t, 16> OffsetExpr;
656   if (PrependFlags & DIExpression::DerefBefore)
657     OffsetExpr.push_back(dwarf::DW_OP_deref);
658   getOffsetOpcodes(Offset, OffsetExpr);
659   if (PrependFlags & DIExpression::DerefAfter)
660     OffsetExpr.push_back(dwarf::DW_OP_deref);
661   return DIExpression::prependOpcodes(Expr, OffsetExpr,
662                                       PrependFlags & DIExpression::StackValue,
663                                       PrependFlags & DIExpression::EntryValue);
664 }
665 
666 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
667 LLVM_DUMP_METHOD
668 void TargetRegisterInfo::dumpReg(Register Reg, unsigned SubRegIndex,
669                                  const TargetRegisterInfo *TRI) {
670   dbgs() << printReg(Reg, TRI, SubRegIndex) << "\n";
671 }
672 #endif
673