1 //==- CodeGen/TargetRegisterInfo.h - Target Register Information -*- C++ -*-==// 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 describes an abstract interface used to get information about a 10 // target machines register file. This information is used for a variety of 11 // purposed, especially register allocation. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifndef LLVM_CODEGEN_TARGETREGISTERINFO_H 16 #define LLVM_CODEGEN_TARGETREGISTERINFO_H 17 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/ADT/StringRef.h" 21 #include "llvm/ADT/iterator_range.h" 22 #include "llvm/CodeGen/MachineBasicBlock.h" 23 #include "llvm/CodeGen/RegisterBank.h" 24 #include "llvm/IR/CallingConv.h" 25 #include "llvm/MC/LaneBitmask.h" 26 #include "llvm/MC/MCRegisterInfo.h" 27 #include "llvm/Support/ErrorHandling.h" 28 #include "llvm/Support/MathExtras.h" 29 #include "llvm/Support/Printable.h" 30 #include <cassert> 31 #include <cstdint> 32 33 namespace llvm { 34 35 class BitVector; 36 class DIExpression; 37 class LiveRegMatrix; 38 class MachineFunction; 39 class MachineInstr; 40 class RegScavenger; 41 class VirtRegMap; 42 class LiveIntervals; 43 class LiveInterval; 44 45 class TargetRegisterClass { 46 public: 47 using iterator = const MCPhysReg *; 48 using const_iterator = const MCPhysReg *; 49 using sc_iterator = const TargetRegisterClass* const *; 50 51 // Instance variables filled by tablegen, do not use! 52 const MCRegisterClass *MC; 53 const uint32_t *SubClassMask; 54 const uint16_t *SuperRegIndices; 55 const LaneBitmask LaneMask; 56 /// Classes with a higher priority value are assigned first by register 57 /// allocators using a greedy heuristic. The value is in the range [0,31]. 58 const uint8_t AllocationPriority; 59 60 // Change allocation priority heuristic used by greedy. 61 const bool GlobalPriority; 62 63 /// Configurable target specific flags. 64 const uint8_t TSFlags; 65 /// Whether the class supports two (or more) disjunct subregister indices. 66 const bool HasDisjunctSubRegs; 67 /// Whether a combination of subregisters can cover every register in the 68 /// class. See also the CoveredBySubRegs description in Target.td. 69 const bool CoveredBySubRegs; 70 const sc_iterator SuperClasses; 71 ArrayRef<MCPhysReg> (*OrderFunc)(const MachineFunction&); 72 73 /// Return the register class ID number. getID()74 unsigned getID() const { return MC->getID(); } 75 76 /// begin/end - Return all of the registers in this class. 77 /// begin()78 iterator begin() const { return MC->begin(); } end()79 iterator end() const { return MC->end(); } 80 81 /// Return the number of registers in this class. getNumRegs()82 unsigned getNumRegs() const { return MC->getNumRegs(); } 83 84 iterator_range<SmallVectorImpl<MCPhysReg>::const_iterator> getRegisters()85 getRegisters() const { 86 return make_range(MC->begin(), MC->end()); 87 } 88 89 /// Return the specified register in the class. getRegister(unsigned i)90 MCRegister getRegister(unsigned i) const { 91 return MC->getRegister(i); 92 } 93 94 /// Return true if the specified register is included in this register class. 95 /// This does not include virtual registers. contains(Register Reg)96 bool contains(Register Reg) const { 97 /// FIXME: Historically this function has returned false when given vregs 98 /// but it should probably only receive physical registers 99 if (!Reg.isPhysical()) 100 return false; 101 return MC->contains(Reg.asMCReg()); 102 } 103 104 /// Return true if both registers are in this class. contains(Register Reg1,Register Reg2)105 bool contains(Register Reg1, Register Reg2) const { 106 /// FIXME: Historically this function has returned false when given a vregs 107 /// but it should probably only receive physical registers 108 if (!Reg1.isPhysical() || !Reg2.isPhysical()) 109 return false; 110 return MC->contains(Reg1.asMCReg(), Reg2.asMCReg()); 111 } 112 113 /// Return the cost of copying a value between two registers in this class. 114 /// A negative number means the register class is very expensive 115 /// to copy e.g. status flag register classes. getCopyCost()116 int getCopyCost() const { return MC->getCopyCost(); } 117 118 /// Return true if this register class may be used to create virtual 119 /// registers. isAllocatable()120 bool isAllocatable() const { return MC->isAllocatable(); } 121 122 /// Return true if the specified TargetRegisterClass 123 /// is a proper sub-class of this TargetRegisterClass. hasSubClass(const TargetRegisterClass * RC)124 bool hasSubClass(const TargetRegisterClass *RC) const { 125 return RC != this && hasSubClassEq(RC); 126 } 127 128 /// Returns true if RC is a sub-class of or equal to this class. hasSubClassEq(const TargetRegisterClass * RC)129 bool hasSubClassEq(const TargetRegisterClass *RC) const { 130 unsigned ID = RC->getID(); 131 return (SubClassMask[ID / 32] >> (ID % 32)) & 1; 132 } 133 134 /// Return true if the specified TargetRegisterClass is a 135 /// proper super-class of this TargetRegisterClass. hasSuperClass(const TargetRegisterClass * RC)136 bool hasSuperClass(const TargetRegisterClass *RC) const { 137 return RC->hasSubClass(this); 138 } 139 140 /// Returns true if RC is a super-class of or equal to this class. hasSuperClassEq(const TargetRegisterClass * RC)141 bool hasSuperClassEq(const TargetRegisterClass *RC) const { 142 return RC->hasSubClassEq(this); 143 } 144 145 /// Returns a bit vector of subclasses, including this one. 146 /// The vector is indexed by class IDs. 147 /// 148 /// To use it, consider the returned array as a chunk of memory that 149 /// contains an array of bits of size NumRegClasses. Each 32-bit chunk 150 /// contains a bitset of the ID of the subclasses in big-endian style. 151 152 /// I.e., the representation of the memory from left to right at the 153 /// bit level looks like: 154 /// [31 30 ... 1 0] [ 63 62 ... 33 32] ... 155 /// [ XXX NumRegClasses NumRegClasses - 1 ... ] 156 /// Where the number represents the class ID and XXX bits that 157 /// should be ignored. 158 /// 159 /// See the implementation of hasSubClassEq for an example of how it 160 /// can be used. getSubClassMask()161 const uint32_t *getSubClassMask() const { 162 return SubClassMask; 163 } 164 165 /// Returns a 0-terminated list of sub-register indices that project some 166 /// super-register class into this register class. The list has an entry for 167 /// each Idx such that: 168 /// 169 /// There exists SuperRC where: 170 /// For all Reg in SuperRC: 171 /// this->contains(Reg:Idx) getSuperRegIndices()172 const uint16_t *getSuperRegIndices() const { 173 return SuperRegIndices; 174 } 175 176 /// Returns a NULL-terminated list of super-classes. The 177 /// classes are ordered by ID which is also a topological ordering from large 178 /// to small classes. The list does NOT include the current class. getSuperClasses()179 sc_iterator getSuperClasses() const { 180 return SuperClasses; 181 } 182 183 /// Return true if this TargetRegisterClass is a subset 184 /// class of at least one other TargetRegisterClass. isASubClass()185 bool isASubClass() const { 186 return SuperClasses[0] != nullptr; 187 } 188 189 /// Returns the preferred order for allocating registers from this register 190 /// class in MF. The raw order comes directly from the .td file and may 191 /// include reserved registers that are not allocatable. 192 /// Register allocators should also make sure to allocate 193 /// callee-saved registers only after all the volatiles are used. The 194 /// RegisterClassInfo class provides filtered allocation orders with 195 /// callee-saved registers moved to the end. 196 /// 197 /// The MachineFunction argument can be used to tune the allocatable 198 /// registers based on the characteristics of the function, subtarget, or 199 /// other criteria. 200 /// 201 /// By default, this method returns all registers in the class. getRawAllocationOrder(const MachineFunction & MF)202 ArrayRef<MCPhysReg> getRawAllocationOrder(const MachineFunction &MF) const { 203 return OrderFunc ? OrderFunc(MF) : ArrayRef(begin(), getNumRegs()); 204 } 205 206 /// Returns the combination of all lane masks of register in this class. 207 /// The lane masks of the registers are the combination of all lane masks 208 /// of their subregisters. Returns 1 if there are no subregisters. getLaneMask()209 LaneBitmask getLaneMask() const { 210 return LaneMask; 211 } 212 }; 213 214 /// Extra information, not in MCRegisterDesc, about registers. 215 /// These are used by codegen, not by MC. 216 struct TargetRegisterInfoDesc { 217 const uint8_t *CostPerUse; // Extra cost of instructions using register. 218 unsigned NumCosts; // Number of cost values associated with each register. 219 const bool 220 *InAllocatableClass; // Register belongs to an allocatable regclass. 221 }; 222 223 /// Each TargetRegisterClass has a per register weight, and weight 224 /// limit which must be less than the limits of its pressure sets. 225 struct RegClassWeight { 226 unsigned RegWeight; 227 unsigned WeightLimit; 228 }; 229 230 /// TargetRegisterInfo base class - We assume that the target defines a static 231 /// array of TargetRegisterDesc objects that represent all of the machine 232 /// registers that the target has. As such, we simply have to track a pointer 233 /// to this array so that we can turn register number into a register 234 /// descriptor. 235 /// 236 class TargetRegisterInfo : public MCRegisterInfo { 237 public: 238 using regclass_iterator = const TargetRegisterClass * const *; 239 using vt_iterator = const MVT::SimpleValueType *; 240 struct RegClassInfo { 241 unsigned RegSize, SpillSize, SpillAlignment; 242 unsigned VTListOffset; 243 }; 244 private: 245 const TargetRegisterInfoDesc *InfoDesc; // Extra desc array for codegen 246 const char *const *SubRegIndexNames; // Names of subreg indexes. 247 // Pointer to array of lane masks, one per sub-reg index. 248 const LaneBitmask *SubRegIndexLaneMasks; 249 250 regclass_iterator RegClassBegin, RegClassEnd; // List of regclasses 251 LaneBitmask CoveringLanes; 252 const RegClassInfo *const RCInfos; 253 const MVT::SimpleValueType *const RCVTLists; 254 unsigned HwMode; 255 256 protected: 257 TargetRegisterInfo(const TargetRegisterInfoDesc *ID, 258 regclass_iterator RCB, 259 regclass_iterator RCE, 260 const char *const *SRINames, 261 const LaneBitmask *SRILaneMasks, 262 LaneBitmask CoveringLanes, 263 const RegClassInfo *const RCIs, 264 const MVT::SimpleValueType *const RCVTLists, 265 unsigned Mode = 0); 266 virtual ~TargetRegisterInfo(); 267 268 public: 269 /// Return the number of registers for the function. (may overestimate) getNumSupportedRegs(const MachineFunction &)270 virtual unsigned getNumSupportedRegs(const MachineFunction &) const { 271 return getNumRegs(); 272 } 273 274 // Register numbers can represent physical registers, virtual registers, and 275 // sometimes stack slots. The unsigned values are divided into these ranges: 276 // 277 // 0 Not a register, can be used as a sentinel. 278 // [1;2^30) Physical registers assigned by TableGen. 279 // [2^30;2^31) Stack slots. (Rarely used.) 280 // [2^31;2^32) Virtual registers assigned by MachineRegisterInfo. 281 // 282 // Further sentinels can be allocated from the small negative integers. 283 // DenseMapInfo<unsigned> uses -1u and -2u. 284 285 /// Return the size in bits of a register from class RC. getRegSizeInBits(const TargetRegisterClass & RC)286 TypeSize getRegSizeInBits(const TargetRegisterClass &RC) const { 287 return TypeSize::getFixed(getRegClassInfo(RC).RegSize); 288 } 289 290 /// Return the size in bytes of the stack slot allocated to hold a spilled 291 /// copy of a register from class RC. getSpillSize(const TargetRegisterClass & RC)292 unsigned getSpillSize(const TargetRegisterClass &RC) const { 293 return getRegClassInfo(RC).SpillSize / 8; 294 } 295 296 /// Return the minimum required alignment in bytes for a spill slot for 297 /// a register of this class. getSpillAlign(const TargetRegisterClass & RC)298 Align getSpillAlign(const TargetRegisterClass &RC) const { 299 return Align(getRegClassInfo(RC).SpillAlignment / 8); 300 } 301 302 /// Return true if the given TargetRegisterClass has the ValueType T. isTypeLegalForClass(const TargetRegisterClass & RC,MVT T)303 bool isTypeLegalForClass(const TargetRegisterClass &RC, MVT T) const { 304 for (auto I = legalclasstypes_begin(RC); *I != MVT::Other; ++I) 305 if (MVT(*I) == T) 306 return true; 307 return false; 308 } 309 310 /// Return true if the given TargetRegisterClass is compatible with LLT T. isTypeLegalForClass(const TargetRegisterClass & RC,LLT T)311 bool isTypeLegalForClass(const TargetRegisterClass &RC, LLT T) const { 312 for (auto I = legalclasstypes_begin(RC); *I != MVT::Other; ++I) { 313 MVT VT(*I); 314 if (VT == MVT::Untyped) 315 return true; 316 317 if (LLT(VT) == T) 318 return true; 319 } 320 return false; 321 } 322 323 /// Loop over all of the value types that can be represented by values 324 /// in the given register class. legalclasstypes_begin(const TargetRegisterClass & RC)325 vt_iterator legalclasstypes_begin(const TargetRegisterClass &RC) const { 326 return &RCVTLists[getRegClassInfo(RC).VTListOffset]; 327 } 328 legalclasstypes_end(const TargetRegisterClass & RC)329 vt_iterator legalclasstypes_end(const TargetRegisterClass &RC) const { 330 vt_iterator I = legalclasstypes_begin(RC); 331 while (*I != MVT::Other) 332 ++I; 333 return I; 334 } 335 336 /// Returns the Register Class of a physical register of the given type, 337 /// picking the most sub register class of the right type that contains this 338 /// physreg. 339 const TargetRegisterClass *getMinimalPhysRegClass(MCRegister Reg, 340 MVT VT = MVT::Other) const; 341 342 /// Returns the Register Class of a physical register of the given type, 343 /// picking the most sub register class of the right type that contains this 344 /// physreg. If there is no register class compatible with the given type, 345 /// returns nullptr. 346 const TargetRegisterClass *getMinimalPhysRegClassLLT(MCRegister Reg, 347 LLT Ty = LLT()) const; 348 349 /// Return the maximal subclass of the given register class that is 350 /// allocatable or NULL. 351 const TargetRegisterClass * 352 getAllocatableClass(const TargetRegisterClass *RC) const; 353 354 /// Returns a bitset indexed by register number indicating if a register is 355 /// allocatable or not. If a register class is specified, returns the subset 356 /// for the class. 357 BitVector getAllocatableSet(const MachineFunction &MF, 358 const TargetRegisterClass *RC = nullptr) const; 359 360 /// Get a list of cost values for all registers that correspond to the index 361 /// returned by RegisterCostTableIndex. getRegisterCosts(const MachineFunction & MF)362 ArrayRef<uint8_t> getRegisterCosts(const MachineFunction &MF) const { 363 unsigned Idx = getRegisterCostTableIndex(MF); 364 unsigned NumRegs = getNumRegs(); 365 assert(Idx < InfoDesc->NumCosts && "CostPerUse index out of bounds"); 366 367 return ArrayRef(&InfoDesc->CostPerUse[Idx * NumRegs], NumRegs); 368 } 369 370 /// Return true if the register is in the allocation of any register class. isInAllocatableClass(MCRegister RegNo)371 bool isInAllocatableClass(MCRegister RegNo) const { 372 return InfoDesc->InAllocatableClass[RegNo]; 373 } 374 375 /// Return the human-readable symbolic target-specific 376 /// name for the specified SubRegIndex. getSubRegIndexName(unsigned SubIdx)377 const char *getSubRegIndexName(unsigned SubIdx) const { 378 assert(SubIdx && SubIdx < getNumSubRegIndices() && 379 "This is not a subregister index"); 380 return SubRegIndexNames[SubIdx-1]; 381 } 382 383 /// Return a bitmask representing the parts of a register that are covered by 384 /// SubIdx \see LaneBitmask. 385 /// 386 /// SubIdx == 0 is allowed, it has the lane mask ~0u. getSubRegIndexLaneMask(unsigned SubIdx)387 LaneBitmask getSubRegIndexLaneMask(unsigned SubIdx) const { 388 assert(SubIdx < getNumSubRegIndices() && "This is not a subregister index"); 389 return SubRegIndexLaneMasks[SubIdx]; 390 } 391 392 /// Try to find one or more subregister indexes to cover \p LaneMask. 393 /// 394 /// If this is possible, returns true and appends the best matching set of 395 /// indexes to \p Indexes. If this is not possible, returns false. 396 bool getCoveringSubRegIndexes(const MachineRegisterInfo &MRI, 397 const TargetRegisterClass *RC, 398 LaneBitmask LaneMask, 399 SmallVectorImpl<unsigned> &Indexes) const; 400 401 /// The lane masks returned by getSubRegIndexLaneMask() above can only be 402 /// used to determine if sub-registers overlap - they can't be used to 403 /// determine if a set of sub-registers completely cover another 404 /// sub-register. 405 /// 406 /// The X86 general purpose registers have two lanes corresponding to the 407 /// sub_8bit and sub_8bit_hi sub-registers. Both sub_32bit and sub_16bit have 408 /// lane masks '3', but the sub_16bit sub-register doesn't fully cover the 409 /// sub_32bit sub-register. 410 /// 411 /// On the other hand, the ARM NEON lanes fully cover their registers: The 412 /// dsub_0 sub-register is completely covered by the ssub_0 and ssub_1 lanes. 413 /// This is related to the CoveredBySubRegs property on register definitions. 414 /// 415 /// This function returns a bit mask of lanes that completely cover their 416 /// sub-registers. More precisely, given: 417 /// 418 /// Covering = getCoveringLanes(); 419 /// MaskA = getSubRegIndexLaneMask(SubA); 420 /// MaskB = getSubRegIndexLaneMask(SubB); 421 /// 422 /// If (MaskA & ~(MaskB & Covering)) == 0, then SubA is completely covered by 423 /// SubB. getCoveringLanes()424 LaneBitmask getCoveringLanes() const { return CoveringLanes; } 425 426 /// Returns true if the two registers are equal or alias each other. 427 /// The registers may be virtual registers. regsOverlap(Register RegA,Register RegB)428 bool regsOverlap(Register RegA, Register RegB) const { 429 if (RegA == RegB) 430 return true; 431 if (RegA.isPhysical() && RegB.isPhysical()) 432 return MCRegisterInfo::regsOverlap(RegA.asMCReg(), RegB.asMCReg()); 433 return false; 434 } 435 436 /// Returns true if Reg contains RegUnit. hasRegUnit(MCRegister Reg,Register RegUnit)437 bool hasRegUnit(MCRegister Reg, Register RegUnit) const { 438 for (MCRegUnit Unit : regunits(Reg)) 439 if (Register(Unit) == RegUnit) 440 return true; 441 return false; 442 } 443 444 /// Returns the original SrcReg unless it is the target of a copy-like 445 /// operation, in which case we chain backwards through all such operations 446 /// to the ultimate source register. If a physical register is encountered, 447 /// we stop the search. 448 virtual Register lookThruCopyLike(Register SrcReg, 449 const MachineRegisterInfo *MRI) const; 450 451 /// Find the original SrcReg unless it is the target of a copy-like operation, 452 /// in which case we chain backwards through all such operations to the 453 /// ultimate source register. If a physical register is encountered, we stop 454 /// the search. 455 /// Return the original SrcReg if all the definitions in the chain only have 456 /// one user and not a physical register. 457 virtual Register 458 lookThruSingleUseCopyChain(Register SrcReg, 459 const MachineRegisterInfo *MRI) const; 460 461 /// Return a null-terminated list of all of the callee-saved registers on 462 /// this target. The register should be in the order of desired callee-save 463 /// stack frame offset. The first register is closest to the incoming stack 464 /// pointer if stack grows down, and vice versa. 465 /// Notice: This function does not take into account disabled CSRs. 466 /// In most cases you will want to use instead the function 467 /// getCalleeSavedRegs that is implemented in MachineRegisterInfo. 468 virtual const MCPhysReg* 469 getCalleeSavedRegs(const MachineFunction *MF) const = 0; 470 471 /// Return a mask of call-preserved registers for the given calling convention 472 /// on the current function. The mask should include all call-preserved 473 /// aliases. This is used by the register allocator to determine which 474 /// registers can be live across a call. 475 /// 476 /// The mask is an array containing (TRI::getNumRegs()+31)/32 entries. 477 /// A set bit indicates that all bits of the corresponding register are 478 /// preserved across the function call. The bit mask is expected to be 479 /// sub-register complete, i.e. if A is preserved, so are all its 480 /// sub-registers. 481 /// 482 /// Bits are numbered from the LSB, so the bit for physical register Reg can 483 /// be found as (Mask[Reg / 32] >> Reg % 32) & 1. 484 /// 485 /// A NULL pointer means that no register mask will be used, and call 486 /// instructions should use implicit-def operands to indicate call clobbered 487 /// registers. 488 /// getCallPreservedMask(const MachineFunction & MF,CallingConv::ID)489 virtual const uint32_t *getCallPreservedMask(const MachineFunction &MF, 490 CallingConv::ID) const { 491 // The default mask clobbers everything. All targets should override. 492 return nullptr; 493 } 494 495 /// Return a register mask for the registers preserved by the unwinder, 496 /// or nullptr if no custom mask is needed. 497 virtual const uint32_t * getCustomEHPadPreservedMask(const MachineFunction & MF)498 getCustomEHPadPreservedMask(const MachineFunction &MF) const { 499 return nullptr; 500 } 501 502 /// Return a register mask that clobbers everything. getNoPreservedMask()503 virtual const uint32_t *getNoPreservedMask() const { 504 llvm_unreachable("target does not provide no preserved mask"); 505 } 506 507 /// Return a list of all of the registers which are clobbered "inside" a call 508 /// to the given function. For example, these might be needed for PLT 509 /// sequences of long-branch veneers. 510 virtual ArrayRef<MCPhysReg> getIntraCallClobberedRegs(const MachineFunction * MF)511 getIntraCallClobberedRegs(const MachineFunction *MF) const { 512 return {}; 513 } 514 515 /// Return true if all bits that are set in mask \p mask0 are also set in 516 /// \p mask1. 517 bool regmaskSubsetEqual(const uint32_t *mask0, const uint32_t *mask1) const; 518 519 /// Return all the call-preserved register masks defined for this target. 520 virtual ArrayRef<const uint32_t *> getRegMasks() const = 0; 521 virtual ArrayRef<const char *> getRegMaskNames() const = 0; 522 523 /// Returns a bitset indexed by physical register number indicating if a 524 /// register is a special register that has particular uses and should be 525 /// considered unavailable at all times, e.g. stack pointer, return address. 526 /// A reserved register: 527 /// - is not allocatable 528 /// - is considered always live 529 /// - is ignored by liveness tracking 530 /// It is often necessary to reserve the super registers of a reserved 531 /// register as well, to avoid them getting allocated indirectly. You may use 532 /// markSuperRegs() and checkAllSuperRegsMarked() in this case. 533 virtual BitVector getReservedRegs(const MachineFunction &MF) const = 0; 534 535 /// Returns either a string explaining why the given register is reserved for 536 /// this function, or an empty optional if no explanation has been written. 537 /// The absence of an explanation does not mean that the register is not 538 /// reserved (meaning, you should check that PhysReg is in fact reserved 539 /// before calling this). 540 virtual std::optional<std::string> explainReservedReg(const MachineFunction & MF,MCRegister PhysReg)541 explainReservedReg(const MachineFunction &MF, MCRegister PhysReg) const { 542 return {}; 543 } 544 545 /// Returns false if we can't guarantee that Physreg, specified as an IR asm 546 /// clobber constraint, will be preserved across the statement. isAsmClobberable(const MachineFunction & MF,MCRegister PhysReg)547 virtual bool isAsmClobberable(const MachineFunction &MF, 548 MCRegister PhysReg) const { 549 return true; 550 } 551 552 /// Returns true if PhysReg cannot be written to in inline asm statements. isInlineAsmReadOnlyReg(const MachineFunction & MF,unsigned PhysReg)553 virtual bool isInlineAsmReadOnlyReg(const MachineFunction &MF, 554 unsigned PhysReg) const { 555 return false; 556 } 557 558 /// Returns true if PhysReg is unallocatable and constant throughout the 559 /// function. Used by MachineRegisterInfo::isConstantPhysReg(). isConstantPhysReg(MCRegister PhysReg)560 virtual bool isConstantPhysReg(MCRegister PhysReg) const { return false; } 561 562 /// Returns true if the register class is considered divergent. isDivergentRegClass(const TargetRegisterClass * RC)563 virtual bool isDivergentRegClass(const TargetRegisterClass *RC) const { 564 return false; 565 } 566 567 /// Returns true if the register is considered uniform. isUniformReg(const MachineRegisterInfo & MRI,const RegisterBankInfo & RBI,Register Reg)568 virtual bool isUniformReg(const MachineRegisterInfo &MRI, 569 const RegisterBankInfo &RBI, Register Reg) const { 570 return false; 571 } 572 573 /// Physical registers that may be modified within a function but are 574 /// guaranteed to be restored before any uses. This is useful for targets that 575 /// have call sequences where a GOT register may be updated by the caller 576 /// prior to a call and is guaranteed to be restored (also by the caller) 577 /// after the call. isCallerPreservedPhysReg(MCRegister PhysReg,const MachineFunction & MF)578 virtual bool isCallerPreservedPhysReg(MCRegister PhysReg, 579 const MachineFunction &MF) const { 580 return false; 581 } 582 583 /// This is a wrapper around getCallPreservedMask(). 584 /// Return true if the register is preserved after the call. 585 virtual bool isCalleeSavedPhysReg(MCRegister PhysReg, 586 const MachineFunction &MF) const; 587 588 /// Returns true if PhysReg can be used as an argument to a function. isArgumentRegister(const MachineFunction & MF,MCRegister PhysReg)589 virtual bool isArgumentRegister(const MachineFunction &MF, 590 MCRegister PhysReg) const { 591 return false; 592 } 593 594 /// Returns true if PhysReg is a fixed register. isFixedRegister(const MachineFunction & MF,MCRegister PhysReg)595 virtual bool isFixedRegister(const MachineFunction &MF, 596 MCRegister PhysReg) const { 597 return false; 598 } 599 600 /// Returns true if PhysReg is a general purpose register. isGeneralPurposeRegister(const MachineFunction & MF,MCRegister PhysReg)601 virtual bool isGeneralPurposeRegister(const MachineFunction &MF, 602 MCRegister PhysReg) const { 603 return false; 604 } 605 606 /// Prior to adding the live-out mask to a stackmap or patchpoint 607 /// instruction, provide the target the opportunity to adjust it (mainly to 608 /// remove pseudo-registers that should be ignored). adjustStackMapLiveOutMask(uint32_t * Mask)609 virtual void adjustStackMapLiveOutMask(uint32_t *Mask) const {} 610 611 /// Return a super-register of the specified register 612 /// Reg so its sub-register of index SubIdx is Reg. getMatchingSuperReg(MCRegister Reg,unsigned SubIdx,const TargetRegisterClass * RC)613 MCRegister getMatchingSuperReg(MCRegister Reg, unsigned SubIdx, 614 const TargetRegisterClass *RC) const { 615 return MCRegisterInfo::getMatchingSuperReg(Reg, SubIdx, RC->MC); 616 } 617 618 /// Return a subclass of the specified register 619 /// class A so that each register in it has a sub-register of the 620 /// specified sub-register index which is in the specified register class B. 621 /// 622 /// TableGen will synthesize missing A sub-classes. 623 virtual const TargetRegisterClass * 624 getMatchingSuperRegClass(const TargetRegisterClass *A, 625 const TargetRegisterClass *B, unsigned Idx) const; 626 627 // For a copy-like instruction that defines a register of class DefRC with 628 // subreg index DefSubReg, reading from another source with class SrcRC and 629 // subregister SrcSubReg return true if this is a preferable copy 630 // instruction or an earlier use should be used. 631 virtual bool shouldRewriteCopySrc(const TargetRegisterClass *DefRC, 632 unsigned DefSubReg, 633 const TargetRegisterClass *SrcRC, 634 unsigned SrcSubReg) const; 635 636 /// Returns the largest legal sub-class of RC that 637 /// supports the sub-register index Idx. 638 /// If no such sub-class exists, return NULL. 639 /// If all registers in RC already have an Idx sub-register, return RC. 640 /// 641 /// TableGen generates a version of this function that is good enough in most 642 /// cases. Targets can override if they have constraints that TableGen 643 /// doesn't understand. For example, the x86 sub_8bit sub-register index is 644 /// supported by the full GR32 register class in 64-bit mode, but only by the 645 /// GR32_ABCD regiister class in 32-bit mode. 646 /// 647 /// TableGen will synthesize missing RC sub-classes. 648 virtual const TargetRegisterClass * getSubClassWithSubReg(const TargetRegisterClass * RC,unsigned Idx)649 getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx) const { 650 assert(Idx == 0 && "Target has no sub-registers"); 651 return RC; 652 } 653 654 /// Return a register class that can be used for a subregister copy from/into 655 /// \p SuperRC at \p SubRegIdx. 656 virtual const TargetRegisterClass * getSubRegisterClass(const TargetRegisterClass * SuperRC,unsigned SubRegIdx)657 getSubRegisterClass(const TargetRegisterClass *SuperRC, 658 unsigned SubRegIdx) const { 659 return nullptr; 660 } 661 662 /// Return the subregister index you get from composing 663 /// two subregister indices. 664 /// 665 /// The special null sub-register index composes as the identity. 666 /// 667 /// If R:a:b is the same register as R:c, then composeSubRegIndices(a, b) 668 /// returns c. Note that composeSubRegIndices does not tell you about illegal 669 /// compositions. If R does not have a subreg a, or R:a does not have a subreg 670 /// b, composeSubRegIndices doesn't tell you. 671 /// 672 /// The ARM register Q0 has two D subregs dsub_0:D0 and dsub_1:D1. It also has 673 /// ssub_0:S0 - ssub_3:S3 subregs. 674 /// If you compose subreg indices dsub_1, ssub_0 you get ssub_2. composeSubRegIndices(unsigned a,unsigned b)675 unsigned composeSubRegIndices(unsigned a, unsigned b) const { 676 if (!a) return b; 677 if (!b) return a; 678 return composeSubRegIndicesImpl(a, b); 679 } 680 681 /// Transforms a LaneMask computed for one subregister to the lanemask that 682 /// would have been computed when composing the subsubregisters with IdxA 683 /// first. @sa composeSubRegIndices() composeSubRegIndexLaneMask(unsigned IdxA,LaneBitmask Mask)684 LaneBitmask composeSubRegIndexLaneMask(unsigned IdxA, 685 LaneBitmask Mask) const { 686 if (!IdxA) 687 return Mask; 688 return composeSubRegIndexLaneMaskImpl(IdxA, Mask); 689 } 690 691 /// Transform a lanemask given for a virtual register to the corresponding 692 /// lanemask before using subregister with index \p IdxA. 693 /// This is the reverse of composeSubRegIndexLaneMask(), assuming Mask is a 694 /// valie lane mask (no invalid bits set) the following holds: 695 /// X0 = composeSubRegIndexLaneMask(Idx, Mask) 696 /// X1 = reverseComposeSubRegIndexLaneMask(Idx, X0) 697 /// => X1 == Mask reverseComposeSubRegIndexLaneMask(unsigned IdxA,LaneBitmask LaneMask)698 LaneBitmask reverseComposeSubRegIndexLaneMask(unsigned IdxA, 699 LaneBitmask LaneMask) const { 700 if (!IdxA) 701 return LaneMask; 702 return reverseComposeSubRegIndexLaneMaskImpl(IdxA, LaneMask); 703 } 704 705 /// Debugging helper: dump register in human readable form to dbgs() stream. 706 static void dumpReg(Register Reg, unsigned SubRegIndex = 0, 707 const TargetRegisterInfo *TRI = nullptr); 708 709 /// Return target defined base register class for a physical register. 710 /// This is the register class with the lowest BaseClassOrder containing the 711 /// register. 712 /// Will be nullptr if the register is not in any base register class. getPhysRegBaseClass(MCRegister Reg)713 virtual const TargetRegisterClass *getPhysRegBaseClass(MCRegister Reg) const { 714 return nullptr; 715 } 716 717 protected: 718 /// Overridden by TableGen in targets that have sub-registers. composeSubRegIndicesImpl(unsigned,unsigned)719 virtual unsigned composeSubRegIndicesImpl(unsigned, unsigned) const { 720 llvm_unreachable("Target has no sub-registers"); 721 } 722 723 /// Overridden by TableGen in targets that have sub-registers. 724 virtual LaneBitmask composeSubRegIndexLaneMaskImpl(unsigned,LaneBitmask)725 composeSubRegIndexLaneMaskImpl(unsigned, LaneBitmask) const { 726 llvm_unreachable("Target has no sub-registers"); 727 } 728 reverseComposeSubRegIndexLaneMaskImpl(unsigned,LaneBitmask)729 virtual LaneBitmask reverseComposeSubRegIndexLaneMaskImpl(unsigned, 730 LaneBitmask) const { 731 llvm_unreachable("Target has no sub-registers"); 732 } 733 734 /// Return the register cost table index. This implementation is sufficient 735 /// for most architectures and can be overriden by targets in case there are 736 /// multiple cost values associated with each register. getRegisterCostTableIndex(const MachineFunction & MF)737 virtual unsigned getRegisterCostTableIndex(const MachineFunction &MF) const { 738 return 0; 739 } 740 741 public: 742 /// Find a common super-register class if it exists. 743 /// 744 /// Find a register class, SuperRC and two sub-register indices, PreA and 745 /// PreB, such that: 746 /// 747 /// 1. PreA + SubA == PreB + SubB (using composeSubRegIndices()), and 748 /// 749 /// 2. For all Reg in SuperRC: Reg:PreA in RCA and Reg:PreB in RCB, and 750 /// 751 /// 3. SuperRC->getSize() >= max(RCA->getSize(), RCB->getSize()). 752 /// 753 /// SuperRC will be chosen such that no super-class of SuperRC satisfies the 754 /// requirements, and there is no register class with a smaller spill size 755 /// that satisfies the requirements. 756 /// 757 /// SubA and SubB must not be 0. Use getMatchingSuperRegClass() instead. 758 /// 759 /// Either of the PreA and PreB sub-register indices may be returned as 0. In 760 /// that case, the returned register class will be a sub-class of the 761 /// corresponding argument register class. 762 /// 763 /// The function returns NULL if no register class can be found. 764 const TargetRegisterClass* 765 getCommonSuperRegClass(const TargetRegisterClass *RCA, unsigned SubA, 766 const TargetRegisterClass *RCB, unsigned SubB, 767 unsigned &PreA, unsigned &PreB) const; 768 769 //===--------------------------------------------------------------------===// 770 // Register Class Information 771 // 772 protected: getRegClassInfo(const TargetRegisterClass & RC)773 const RegClassInfo &getRegClassInfo(const TargetRegisterClass &RC) const { 774 return RCInfos[getNumRegClasses() * HwMode + RC.getID()]; 775 } 776 777 public: 778 /// Register class iterators regclass_begin()779 regclass_iterator regclass_begin() const { return RegClassBegin; } regclass_end()780 regclass_iterator regclass_end() const { return RegClassEnd; } regclasses()781 iterator_range<regclass_iterator> regclasses() const { 782 return make_range(regclass_begin(), regclass_end()); 783 } 784 getNumRegClasses()785 unsigned getNumRegClasses() const { 786 return (unsigned)(regclass_end()-regclass_begin()); 787 } 788 789 /// Returns the register class associated with the enumeration value. 790 /// See class MCOperandInfo. getRegClass(unsigned i)791 const TargetRegisterClass *getRegClass(unsigned i) const { 792 assert(i < getNumRegClasses() && "Register Class ID out of range"); 793 return RegClassBegin[i]; 794 } 795 796 /// Returns the name of the register class. getRegClassName(const TargetRegisterClass * Class)797 const char *getRegClassName(const TargetRegisterClass *Class) const { 798 return MCRegisterInfo::getRegClassName(Class->MC); 799 } 800 801 /// Find the largest common subclass of A and B. 802 /// Return NULL if there is no common subclass. 803 const TargetRegisterClass * 804 getCommonSubClass(const TargetRegisterClass *A, 805 const TargetRegisterClass *B) const; 806 807 /// Returns a TargetRegisterClass used for pointer values. 808 /// If a target supports multiple different pointer register classes, 809 /// kind specifies which one is indicated. 810 virtual const TargetRegisterClass * 811 getPointerRegClass(const MachineFunction &MF, unsigned Kind=0) const { 812 llvm_unreachable("Target didn't implement getPointerRegClass!"); 813 } 814 815 /// Returns a legal register class to copy a register in the specified class 816 /// to or from. If it is possible to copy the register directly without using 817 /// a cross register class copy, return the specified RC. Returns NULL if it 818 /// is not possible to copy between two registers of the specified class. 819 virtual const TargetRegisterClass * getCrossCopyRegClass(const TargetRegisterClass * RC)820 getCrossCopyRegClass(const TargetRegisterClass *RC) const { 821 return RC; 822 } 823 824 /// Returns the largest super class of RC that is legal to use in the current 825 /// sub-target and has the same spill size. 826 /// The returned register class can be used to create virtual registers which 827 /// means that all its registers can be copied and spilled. 828 virtual const TargetRegisterClass * getLargestLegalSuperClass(const TargetRegisterClass * RC,const MachineFunction &)829 getLargestLegalSuperClass(const TargetRegisterClass *RC, 830 const MachineFunction &) const { 831 /// The default implementation is very conservative and doesn't allow the 832 /// register allocator to inflate register classes. 833 return RC; 834 } 835 836 /// Return the register pressure "high water mark" for the specific register 837 /// class. The scheduler is in high register pressure mode (for the specific 838 /// register class) if it goes over the limit. 839 /// 840 /// Note: this is the old register pressure model that relies on a manually 841 /// specified representative register class per value type. getRegPressureLimit(const TargetRegisterClass * RC,MachineFunction & MF)842 virtual unsigned getRegPressureLimit(const TargetRegisterClass *RC, 843 MachineFunction &MF) const { 844 return 0; 845 } 846 847 /// Return a heuristic for the machine scheduler to compare the profitability 848 /// of increasing one register pressure set versus another. The scheduler 849 /// will prefer increasing the register pressure of the set which returns 850 /// the largest value for this function. getRegPressureSetScore(const MachineFunction & MF,unsigned PSetID)851 virtual unsigned getRegPressureSetScore(const MachineFunction &MF, 852 unsigned PSetID) const { 853 return PSetID; 854 } 855 856 /// Get the weight in units of pressure for this register class. 857 virtual const RegClassWeight &getRegClassWeight( 858 const TargetRegisterClass *RC) const = 0; 859 860 /// Returns size in bits of a phys/virtual/generic register. 861 TypeSize getRegSizeInBits(Register Reg, const MachineRegisterInfo &MRI) const; 862 863 /// Get the weight in units of pressure for this register unit. 864 virtual unsigned getRegUnitWeight(unsigned RegUnit) const = 0; 865 866 /// Get the number of dimensions of register pressure. 867 virtual unsigned getNumRegPressureSets() const = 0; 868 869 /// Get the name of this register unit pressure set. 870 virtual const char *getRegPressureSetName(unsigned Idx) const = 0; 871 872 /// Get the register unit pressure limit for this dimension. 873 /// This limit must be adjusted dynamically for reserved registers. 874 virtual unsigned getRegPressureSetLimit(const MachineFunction &MF, 875 unsigned Idx) const = 0; 876 877 /// Get the dimensions of register pressure impacted by this register class. 878 /// Returns a -1 terminated array of pressure set IDs. 879 virtual const int *getRegClassPressureSets( 880 const TargetRegisterClass *RC) const = 0; 881 882 /// Get the dimensions of register pressure impacted by this register unit. 883 /// Returns a -1 terminated array of pressure set IDs. 884 virtual const int *getRegUnitPressureSets(unsigned RegUnit) const = 0; 885 886 /// Get a list of 'hint' registers that the register allocator should try 887 /// first when allocating a physical register for the virtual register 888 /// VirtReg. These registers are effectively moved to the front of the 889 /// allocation order. If true is returned, regalloc will try to only use 890 /// hints to the greatest extent possible even if it means spilling. 891 /// 892 /// The Order argument is the allocation order for VirtReg's register class 893 /// as returned from RegisterClassInfo::getOrder(). The hint registers must 894 /// come from Order, and they must not be reserved. 895 /// 896 /// The default implementation of this function will only add target 897 /// independent register allocation hints. Targets that override this 898 /// function should typically call this default implementation as well and 899 /// expect to see generic copy hints added. 900 virtual bool 901 getRegAllocationHints(Register VirtReg, ArrayRef<MCPhysReg> Order, 902 SmallVectorImpl<MCPhysReg> &Hints, 903 const MachineFunction &MF, 904 const VirtRegMap *VRM = nullptr, 905 const LiveRegMatrix *Matrix = nullptr) const; 906 907 /// A callback to allow target a chance to update register allocation hints 908 /// when a register is "changed" (e.g. coalesced) to another register. 909 /// e.g. On ARM, some virtual registers should target register pairs, 910 /// if one of pair is coalesced to another register, the allocation hint of 911 /// the other half of the pair should be changed to point to the new register. updateRegAllocHint(Register Reg,Register NewReg,MachineFunction & MF)912 virtual void updateRegAllocHint(Register Reg, Register NewReg, 913 MachineFunction &MF) const { 914 // Do nothing. 915 } 916 917 /// Allow the target to reverse allocation order of local live ranges. This 918 /// will generally allocate shorter local live ranges first. For targets with 919 /// many registers, this could reduce regalloc compile time by a large 920 /// factor. It is disabled by default for three reasons: 921 /// (1) Top-down allocation is simpler and easier to debug for targets that 922 /// don't benefit from reversing the order. 923 /// (2) Bottom-up allocation could result in poor evicition decisions on some 924 /// targets affecting the performance of compiled code. 925 /// (3) Bottom-up allocation is no longer guaranteed to optimally color. reverseLocalAssignment()926 virtual bool reverseLocalAssignment() const { return false; } 927 928 /// Allow the target to override the cost of using a callee-saved register for 929 /// the first time. Default value of 0 means we will use a callee-saved 930 /// register if it is available. getCSRFirstUseCost()931 virtual unsigned getCSRFirstUseCost() const { return 0; } 932 933 /// Returns true if the target requires (and can make use of) the register 934 /// scavenger. requiresRegisterScavenging(const MachineFunction & MF)935 virtual bool requiresRegisterScavenging(const MachineFunction &MF) const { 936 return false; 937 } 938 939 /// Returns true if the target wants to use frame pointer based accesses to 940 /// spill to the scavenger emergency spill slot. useFPForScavengingIndex(const MachineFunction & MF)941 virtual bool useFPForScavengingIndex(const MachineFunction &MF) const { 942 return true; 943 } 944 945 /// Returns true if the target requires post PEI scavenging of registers for 946 /// materializing frame index constants. requiresFrameIndexScavenging(const MachineFunction & MF)947 virtual bool requiresFrameIndexScavenging(const MachineFunction &MF) const { 948 return false; 949 } 950 951 /// Returns true if the target requires using the RegScavenger directly for 952 /// frame elimination despite using requiresFrameIndexScavenging. requiresFrameIndexReplacementScavenging(const MachineFunction & MF)953 virtual bool requiresFrameIndexReplacementScavenging( 954 const MachineFunction &MF) const { 955 return false; 956 } 957 958 /// Returns true if the target wants the LocalStackAllocation pass to be run 959 /// and virtual base registers used for more efficient stack access. requiresVirtualBaseRegisters(const MachineFunction & MF)960 virtual bool requiresVirtualBaseRegisters(const MachineFunction &MF) const { 961 return false; 962 } 963 964 /// Return true if target has reserved a spill slot in the stack frame of 965 /// the given function for the specified register. e.g. On x86, if the frame 966 /// register is required, the first fixed stack object is reserved as its 967 /// spill slot. This tells PEI not to create a new stack frame 968 /// object for the given register. It should be called only after 969 /// determineCalleeSaves(). hasReservedSpillSlot(const MachineFunction & MF,Register Reg,int & FrameIdx)970 virtual bool hasReservedSpillSlot(const MachineFunction &MF, Register Reg, 971 int &FrameIdx) const { 972 return false; 973 } 974 975 /// Returns true if the live-ins should be tracked after register allocation. trackLivenessAfterRegAlloc(const MachineFunction & MF)976 virtual bool trackLivenessAfterRegAlloc(const MachineFunction &MF) const { 977 return true; 978 } 979 980 /// True if the stack can be realigned for the target. 981 virtual bool canRealignStack(const MachineFunction &MF) const; 982 983 /// True if storage within the function requires the stack pointer to be 984 /// aligned more than the normal calling convention calls for. 985 virtual bool shouldRealignStack(const MachineFunction &MF) const; 986 987 /// True if stack realignment is required and still possible. hasStackRealignment(const MachineFunction & MF)988 bool hasStackRealignment(const MachineFunction &MF) const { 989 return shouldRealignStack(MF) && canRealignStack(MF); 990 } 991 992 /// Get the offset from the referenced frame index in the instruction, 993 /// if there is one. getFrameIndexInstrOffset(const MachineInstr * MI,int Idx)994 virtual int64_t getFrameIndexInstrOffset(const MachineInstr *MI, 995 int Idx) const { 996 return 0; 997 } 998 999 /// Returns true if the instruction's frame index reference would be better 1000 /// served by a base register other than FP or SP. 1001 /// Used by LocalStackFrameAllocation to determine which frame index 1002 /// references it should create new base registers for. needsFrameBaseReg(MachineInstr * MI,int64_t Offset)1003 virtual bool needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const { 1004 return false; 1005 } 1006 1007 /// Insert defining instruction(s) for a pointer to FrameIdx before 1008 /// insertion point I. Return materialized frame pointer. materializeFrameBaseRegister(MachineBasicBlock * MBB,int FrameIdx,int64_t Offset)1009 virtual Register materializeFrameBaseRegister(MachineBasicBlock *MBB, 1010 int FrameIdx, 1011 int64_t Offset) const { 1012 llvm_unreachable("materializeFrameBaseRegister does not exist on this " 1013 "target"); 1014 } 1015 1016 /// Resolve a frame index operand of an instruction 1017 /// to reference the indicated base register plus offset instead. resolveFrameIndex(MachineInstr & MI,Register BaseReg,int64_t Offset)1018 virtual void resolveFrameIndex(MachineInstr &MI, Register BaseReg, 1019 int64_t Offset) const { 1020 llvm_unreachable("resolveFrameIndex does not exist on this target"); 1021 } 1022 1023 /// Determine whether a given base register plus offset immediate is 1024 /// encodable to resolve a frame index. isFrameOffsetLegal(const MachineInstr * MI,Register BaseReg,int64_t Offset)1025 virtual bool isFrameOffsetLegal(const MachineInstr *MI, Register BaseReg, 1026 int64_t Offset) const { 1027 llvm_unreachable("isFrameOffsetLegal does not exist on this target"); 1028 } 1029 1030 /// Gets the DWARF expression opcodes for \p Offset. 1031 virtual void getOffsetOpcodes(const StackOffset &Offset, 1032 SmallVectorImpl<uint64_t> &Ops) const; 1033 1034 /// Prepends a DWARF expression for \p Offset to DIExpression \p Expr. 1035 DIExpression * 1036 prependOffsetExpression(const DIExpression *Expr, unsigned PrependFlags, 1037 const StackOffset &Offset) const; 1038 1039 /// Spill the register so it can be used by the register scavenger. 1040 /// Return true if the register was spilled, false otherwise. 1041 /// If this function does not spill the register, the scavenger 1042 /// will instead spill it to the emergency spill slot. saveScavengerRegister(MachineBasicBlock & MBB,MachineBasicBlock::iterator I,MachineBasicBlock::iterator & UseMI,const TargetRegisterClass * RC,Register Reg)1043 virtual bool saveScavengerRegister(MachineBasicBlock &MBB, 1044 MachineBasicBlock::iterator I, 1045 MachineBasicBlock::iterator &UseMI, 1046 const TargetRegisterClass *RC, 1047 Register Reg) const { 1048 return false; 1049 } 1050 1051 /// Process frame indices in reverse block order. This changes the behavior of 1052 /// the RegScavenger passed to eliminateFrameIndex. If this is true targets 1053 /// should scavengeRegisterBackwards in eliminateFrameIndex. New targets 1054 /// should prefer reverse scavenging behavior. 1055 /// TODO: Remove this when all targets return true. eliminateFrameIndicesBackwards()1056 virtual bool eliminateFrameIndicesBackwards() const { return true; } 1057 1058 /// This method must be overriden to eliminate abstract frame indices from 1059 /// instructions which may use them. The instruction referenced by the 1060 /// iterator contains an MO_FrameIndex operand which must be eliminated by 1061 /// this method. This method may modify or replace the specified instruction, 1062 /// as long as it keeps the iterator pointing at the finished product. 1063 /// SPAdj is the SP adjustment due to call frame setup instruction. 1064 /// FIOperandNum is the FI operand number. 1065 /// Returns true if the current instruction was removed and the iterator 1066 /// is not longer valid 1067 virtual bool eliminateFrameIndex(MachineBasicBlock::iterator MI, 1068 int SPAdj, unsigned FIOperandNum, 1069 RegScavenger *RS = nullptr) const = 0; 1070 1071 /// Return the assembly name for \p Reg. getRegAsmName(MCRegister Reg)1072 virtual StringRef getRegAsmName(MCRegister Reg) const { 1073 // FIXME: We are assuming that the assembly name is equal to the TableGen 1074 // name converted to lower case 1075 // 1076 // The TableGen name is the name of the definition for this register in the 1077 // target's tablegen files. For example, the TableGen name of 1078 // def EAX : Register <...>; is "EAX" 1079 return StringRef(getName(Reg)); 1080 } 1081 1082 //===--------------------------------------------------------------------===// 1083 /// Subtarget Hooks 1084 1085 /// SrcRC and DstRC will be morphed into NewRC if this returns true. shouldCoalesce(MachineInstr * MI,const TargetRegisterClass * SrcRC,unsigned SubReg,const TargetRegisterClass * DstRC,unsigned DstSubReg,const TargetRegisterClass * NewRC,LiveIntervals & LIS)1086 virtual bool shouldCoalesce(MachineInstr *MI, 1087 const TargetRegisterClass *SrcRC, 1088 unsigned SubReg, 1089 const TargetRegisterClass *DstRC, 1090 unsigned DstSubReg, 1091 const TargetRegisterClass *NewRC, 1092 LiveIntervals &LIS) const 1093 { return true; } 1094 1095 /// Region split has a high compile time cost especially for large live range. 1096 /// This method is used to decide whether or not \p VirtReg should 1097 /// go through this expensive splitting heuristic. 1098 virtual bool shouldRegionSplitForVirtReg(const MachineFunction &MF, 1099 const LiveInterval &VirtReg) const; 1100 1101 /// Last chance recoloring has a high compile time cost especially for 1102 /// targets with a lot of registers. 1103 /// This method is used to decide whether or not \p VirtReg should 1104 /// go through this expensive heuristic. 1105 /// When this target hook is hit, by returning false, there is a high 1106 /// chance that the register allocation will fail altogether (usually with 1107 /// "ran out of registers"). 1108 /// That said, this error usually points to another problem in the 1109 /// optimization pipeline. 1110 virtual bool shouldUseLastChanceRecoloringForVirtReg(const MachineFunction & MF,const LiveInterval & VirtReg)1111 shouldUseLastChanceRecoloringForVirtReg(const MachineFunction &MF, 1112 const LiveInterval &VirtReg) const { 1113 return true; 1114 } 1115 1116 /// Deferred spilling delays the spill insertion of a virtual register 1117 /// after every other allocation. By deferring the spilling, it is 1118 /// sometimes possible to eliminate that spilling altogether because 1119 /// something else could have been eliminated, thus leaving some space 1120 /// for the virtual register. 1121 /// However, this comes with a compile time impact because it adds one 1122 /// more stage to the greedy register allocator. 1123 /// This method is used to decide whether \p VirtReg should use the deferred 1124 /// spilling stage instead of being spilled right away. 1125 virtual bool shouldUseDeferredSpillingForVirtReg(const MachineFunction & MF,const LiveInterval & VirtReg)1126 shouldUseDeferredSpillingForVirtReg(const MachineFunction &MF, 1127 const LiveInterval &VirtReg) const { 1128 return false; 1129 } 1130 1131 /// When prioritizing live ranges in register allocation, if this hook returns 1132 /// true then the AllocationPriority of the register class will be treated as 1133 /// more important than whether the range is local to a basic block or global. 1134 virtual bool regClassPriorityTrumpsGlobalness(const MachineFunction & MF)1135 regClassPriorityTrumpsGlobalness(const MachineFunction &MF) const { 1136 return false; 1137 } 1138 1139 //===--------------------------------------------------------------------===// 1140 /// Debug information queries. 1141 1142 /// getFrameRegister - This method should return the register used as a base 1143 /// for values allocated in the current stack frame. 1144 virtual Register getFrameRegister(const MachineFunction &MF) const = 0; 1145 1146 /// Mark a register and all its aliases as reserved in the given set. 1147 void markSuperRegs(BitVector &RegisterSet, MCRegister Reg) const; 1148 1149 /// Returns true if for every register in the set all super registers are part 1150 /// of the set as well. 1151 bool checkAllSuperRegsMarked(const BitVector &RegisterSet, 1152 ArrayRef<MCPhysReg> Exceptions = ArrayRef<MCPhysReg>()) const; 1153 1154 virtual const TargetRegisterClass * getConstrainedRegClassForOperand(const MachineOperand & MO,const MachineRegisterInfo & MRI)1155 getConstrainedRegClassForOperand(const MachineOperand &MO, 1156 const MachineRegisterInfo &MRI) const { 1157 return nullptr; 1158 } 1159 1160 /// Returns the physical register number of sub-register "Index" 1161 /// for physical register RegNo. Return zero if the sub-register does not 1162 /// exist. getSubReg(MCRegister Reg,unsigned Idx)1163 inline MCRegister getSubReg(MCRegister Reg, unsigned Idx) const { 1164 return static_cast<const MCRegisterInfo *>(this)->getSubReg(Reg, Idx); 1165 } 1166 1167 /// Some targets have non-allocatable registers that aren't technically part 1168 /// of the explicit callee saved register list, but should be handled as such 1169 /// in certain cases. isNonallocatableRegisterCalleeSave(MCRegister Reg)1170 virtual bool isNonallocatableRegisterCalleeSave(MCRegister Reg) const { 1171 return false; 1172 } 1173 }; 1174 1175 //===----------------------------------------------------------------------===// 1176 // SuperRegClassIterator 1177 //===----------------------------------------------------------------------===// 1178 // 1179 // Iterate over the possible super-registers for a given register class. The 1180 // iterator will visit a list of pairs (Idx, Mask) corresponding to the 1181 // possible classes of super-registers. 1182 // 1183 // Each bit mask will have at least one set bit, and each set bit in Mask 1184 // corresponds to a SuperRC such that: 1185 // 1186 // For all Reg in SuperRC: Reg:Idx is in RC. 1187 // 1188 // The iterator can include (O, RC->getSubClassMask()) as the first entry which 1189 // also satisfies the above requirement, assuming Reg:0 == Reg. 1190 // 1191 class SuperRegClassIterator { 1192 const unsigned RCMaskWords; 1193 unsigned SubReg = 0; 1194 const uint16_t *Idx; 1195 const uint32_t *Mask; 1196 1197 public: 1198 /// Create a SuperRegClassIterator that visits all the super-register classes 1199 /// of RC. When IncludeSelf is set, also include the (0, sub-classes) entry. 1200 SuperRegClassIterator(const TargetRegisterClass *RC, 1201 const TargetRegisterInfo *TRI, 1202 bool IncludeSelf = false) 1203 : RCMaskWords((TRI->getNumRegClasses() + 31) / 32), 1204 Idx(RC->getSuperRegIndices()), Mask(RC->getSubClassMask()) { 1205 if (!IncludeSelf) 1206 ++*this; 1207 } 1208 1209 /// Returns true if this iterator is still pointing at a valid entry. isValid()1210 bool isValid() const { return Idx; } 1211 1212 /// Returns the current sub-register index. getSubReg()1213 unsigned getSubReg() const { return SubReg; } 1214 1215 /// Returns the bit mask of register classes that getSubReg() projects into 1216 /// RC. 1217 /// See TargetRegisterClass::getSubClassMask() for how to use it. getMask()1218 const uint32_t *getMask() const { return Mask; } 1219 1220 /// Advance iterator to the next entry. 1221 void operator++() { 1222 assert(isValid() && "Cannot move iterator past end."); 1223 Mask += RCMaskWords; 1224 SubReg = *Idx++; 1225 if (!SubReg) 1226 Idx = nullptr; 1227 } 1228 }; 1229 1230 //===----------------------------------------------------------------------===// 1231 // BitMaskClassIterator 1232 //===----------------------------------------------------------------------===// 1233 /// This class encapuslates the logic to iterate over bitmask returned by 1234 /// the various RegClass related APIs. 1235 /// E.g., this class can be used to iterate over the subclasses provided by 1236 /// TargetRegisterClass::getSubClassMask or SuperRegClassIterator::getMask. 1237 class BitMaskClassIterator { 1238 /// Total number of register classes. 1239 const unsigned NumRegClasses; 1240 /// Base index of CurrentChunk. 1241 /// In other words, the number of bit we read to get at the 1242 /// beginning of that chunck. 1243 unsigned Base = 0; 1244 /// Adjust base index of CurrentChunk. 1245 /// Base index + how many bit we read within CurrentChunk. 1246 unsigned Idx = 0; 1247 /// Current register class ID. 1248 unsigned ID = 0; 1249 /// Mask we are iterating over. 1250 const uint32_t *Mask; 1251 /// Current chunk of the Mask we are traversing. 1252 uint32_t CurrentChunk; 1253 1254 /// Move ID to the next set bit. moveToNextID()1255 void moveToNextID() { 1256 // If the current chunk of memory is empty, move to the next one, 1257 // while making sure we do not go pass the number of register 1258 // classes. 1259 while (!CurrentChunk) { 1260 // Move to the next chunk. 1261 Base += 32; 1262 if (Base >= NumRegClasses) { 1263 ID = NumRegClasses; 1264 return; 1265 } 1266 CurrentChunk = *++Mask; 1267 Idx = Base; 1268 } 1269 // Otherwise look for the first bit set from the right 1270 // (representation of the class ID is big endian). 1271 // See getSubClassMask for more details on the representation. 1272 unsigned Offset = llvm::countr_zero(CurrentChunk); 1273 // Add the Offset to the adjusted base number of this chunk: Idx. 1274 // This is the ID of the register class. 1275 ID = Idx + Offset; 1276 1277 // Consume the zeros, if any, and the bit we just read 1278 // so that we are at the right spot for the next call. 1279 // Do not do Offset + 1 because Offset may be 31 and 32 1280 // will be UB for the shift, though in that case we could 1281 // have make the chunk being equal to 0, but that would 1282 // have introduced a if statement. 1283 moveNBits(Offset); 1284 moveNBits(1); 1285 } 1286 1287 /// Move \p NumBits Bits forward in CurrentChunk. moveNBits(unsigned NumBits)1288 void moveNBits(unsigned NumBits) { 1289 assert(NumBits < 32 && "Undefined behavior spotted!"); 1290 // Consume the bit we read for the next call. 1291 CurrentChunk >>= NumBits; 1292 // Adjust the base for the chunk. 1293 Idx += NumBits; 1294 } 1295 1296 public: 1297 /// Create a BitMaskClassIterator that visits all the register classes 1298 /// represented by \p Mask. 1299 /// 1300 /// \pre \p Mask != nullptr BitMaskClassIterator(const uint32_t * Mask,const TargetRegisterInfo & TRI)1301 BitMaskClassIterator(const uint32_t *Mask, const TargetRegisterInfo &TRI) 1302 : NumRegClasses(TRI.getNumRegClasses()), Mask(Mask), CurrentChunk(*Mask) { 1303 // Move to the first ID. 1304 moveToNextID(); 1305 } 1306 1307 /// Returns true if this iterator is still pointing at a valid entry. isValid()1308 bool isValid() const { return getID() != NumRegClasses; } 1309 1310 /// Returns the current register class ID. getID()1311 unsigned getID() const { return ID; } 1312 1313 /// Advance iterator to the next entry. 1314 void operator++() { 1315 assert(isValid() && "Cannot move iterator past end."); 1316 moveToNextID(); 1317 } 1318 }; 1319 1320 // This is useful when building IndexedMaps keyed on virtual registers 1321 struct VirtReg2IndexFunctor { 1322 using argument_type = Register; operatorVirtReg2IndexFunctor1323 unsigned operator()(Register Reg) const { 1324 return Register::virtReg2Index(Reg); 1325 } 1326 }; 1327 1328 /// Prints virtual and physical registers with or without a TRI instance. 1329 /// 1330 /// The format is: 1331 /// %noreg - NoRegister 1332 /// %5 - a virtual register. 1333 /// %5:sub_8bit - a virtual register with sub-register index (with TRI). 1334 /// %eax - a physical register 1335 /// %physreg17 - a physical register when no TRI instance given. 1336 /// 1337 /// Usage: OS << printReg(Reg, TRI, SubRegIdx) << '\n'; 1338 Printable printReg(Register Reg, const TargetRegisterInfo *TRI = nullptr, 1339 unsigned SubIdx = 0, 1340 const MachineRegisterInfo *MRI = nullptr); 1341 1342 /// Create Printable object to print register units on a \ref raw_ostream. 1343 /// 1344 /// Register units are named after their root registers: 1345 /// 1346 /// al - Single root. 1347 /// fp0~st7 - Dual roots. 1348 /// 1349 /// Usage: OS << printRegUnit(Unit, TRI) << '\n'; 1350 Printable printRegUnit(unsigned Unit, const TargetRegisterInfo *TRI); 1351 1352 /// Create Printable object to print virtual registers and physical 1353 /// registers on a \ref raw_ostream. 1354 Printable printVRegOrUnit(unsigned VRegOrUnit, const TargetRegisterInfo *TRI); 1355 1356 /// Create Printable object to print register classes or register banks 1357 /// on a \ref raw_ostream. 1358 Printable printRegClassOrBank(Register Reg, const MachineRegisterInfo &RegInfo, 1359 const TargetRegisterInfo *TRI); 1360 1361 } // end namespace llvm 1362 1363 #endif // LLVM_CODEGEN_TARGETREGISTERINFO_H 1364