]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/llvm/include/llvm/CodeGen/GlobalISel/RegisterBankInfo.h
MFC r355940:
[FreeBSD/FreeBSD.git] / contrib / llvm-project / llvm / include / llvm / CodeGen / GlobalISel / RegisterBankInfo.h
1 //===- llvm/CodeGen/GlobalISel/RegisterBankInfo.h ---------------*- 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 /// \file This file declares the API for the register bank info.
10 /// This API is responsible for handling the register banks.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_CODEGEN_GLOBALISEL_REGISTERBANKINFO_H
15 #define LLVM_CODEGEN_GLOBALISEL_REGISTERBANKINFO_H
16
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/Hashing.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/iterator_range.h"
21 #include "llvm/CodeGen/Register.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include <cassert>
24 #include <initializer_list>
25 #include <memory>
26
27 namespace llvm {
28
29 class MachineInstr;
30 class MachineRegisterInfo;
31 class raw_ostream;
32 class RegisterBank;
33 class TargetInstrInfo;
34 class TargetRegisterClass;
35 class TargetRegisterInfo;
36
37 /// Holds all the information related to register banks.
38 class RegisterBankInfo {
39 public:
40   /// Helper struct that represents how a value is partially mapped
41   /// into a register.
42   /// The StartIdx and Length represent what region of the orginal
43   /// value this partial mapping covers.
44   /// This can be represented as a Mask of contiguous bit starting
45   /// at StartIdx bit and spanning Length bits.
46   /// StartIdx is the number of bits from the less significant bits.
47   struct PartialMapping {
48     /// Number of bits at which this partial mapping starts in the
49     /// original value.  The bits are counted from less significant
50     /// bits to most significant bits.
51     unsigned StartIdx;
52
53     /// Length of this mapping in bits. This is how many bits this
54     /// partial mapping covers in the original value:
55     /// from StartIdx to StartIdx + Length -1.
56     unsigned Length;
57
58     /// Register bank where the partial value lives.
59     const RegisterBank *RegBank;
60
61     PartialMapping() = default;
62
63     /// Provide a shortcut for quickly building PartialMapping.
64     PartialMapping(unsigned StartIdx, unsigned Length,
65                    const RegisterBank &RegBank)
66         : StartIdx(StartIdx), Length(Length), RegBank(&RegBank) {}
67
68     /// \return the index of in the original value of the most
69     /// significant bit that this partial mapping covers.
70     unsigned getHighBitIdx() const { return StartIdx + Length - 1; }
71
72     /// Print this partial mapping on dbgs() stream.
73     void dump() const;
74
75     /// Print this partial mapping on \p OS;
76     void print(raw_ostream &OS) const;
77
78     /// Check that the Mask is compatible with the RegBank.
79     /// Indeed, if the RegBank cannot accomadate the "active bits" of the mask,
80     /// there is no way this mapping is valid.
81     ///
82     /// \note This method does not check anything when assertions are disabled.
83     ///
84     /// \return True is the check was successful.
85     bool verify() const;
86   };
87
88   /// Helper struct that represents how a value is mapped through
89   /// different register banks.
90   ///
91   /// \note: So far we do not have any users of the complex mappings
92   /// (mappings with more than one partial mapping), but when we do,
93   /// we would have needed to duplicate partial mappings.
94   /// The alternative could be to use an array of pointers of partial
95   /// mapping (i.e., PartialMapping **BreakDown) and duplicate the
96   /// pointers instead.
97   ///
98   /// E.g.,
99   /// Let say we have a 32-bit add and a <2 x 32-bit> vadd. We
100   /// can expand the
101   /// <2 x 32-bit> add into 2 x 32-bit add.
102   ///
103   /// Currently the TableGen-like file would look like:
104   /// \code
105   /// PartialMapping[] = {
106   /// /*32-bit add*/    {0, 32, GPR}, // Scalar entry repeated for first vec elt.
107   /// /*2x32-bit add*/  {0, 32, GPR}, {32, 32, GPR},
108   /// /*<2x32-bit> vadd {0, 64, VPR}
109   /// }; // PartialMapping duplicated.
110   ///
111   /// ValueMapping[] {
112   ///   /*plain 32-bit add*/ {&PartialMapping[0], 1},
113   ///   /*expanded vadd on 2xadd*/ {&PartialMapping[1], 2},
114   ///   /*plain <2x32-bit> vadd*/ {&PartialMapping[3], 1}
115   /// };
116   /// \endcode
117   ///
118   /// With the array of pointer, we would have:
119   /// \code
120   /// PartialMapping[] = {
121   /// /*32-bit add lower */ {0, 32, GPR},
122   /// /*32-bit add upper */ {32, 32, GPR},
123   /// /*<2x32-bit> vadd {0, 64, VPR}
124   /// }; // No more duplication.
125   ///
126   /// BreakDowns[] = {
127   /// /*AddBreakDown*/ &PartialMapping[0],
128   /// /*2xAddBreakDown*/ &PartialMapping[0], &PartialMapping[1],
129   /// /*VAddBreakDown*/ &PartialMapping[2]
130   /// }; // Addresses of PartialMapping duplicated (smaller).
131   ///
132   /// ValueMapping[] {
133   ///   /*plain 32-bit add*/ {&BreakDowns[0], 1},
134   ///   /*expanded vadd on 2xadd*/ {&BreakDowns[1], 2},
135   ///   /*plain <2x32-bit> vadd*/ {&BreakDowns[3], 1}
136   /// };
137   /// \endcode
138   ///
139   /// Given that a PartialMapping is actually small, the code size
140   /// impact is actually a degradation. Moreover the compile time will
141   /// be hit by the additional indirection.
142   /// If PartialMapping gets bigger we may reconsider.
143   struct ValueMapping {
144     /// How the value is broken down between the different register banks.
145     const PartialMapping *BreakDown;
146
147     /// Number of partial mapping to break down this value.
148     unsigned NumBreakDowns;
149
150     /// The default constructor creates an invalid (isValid() == false)
151     /// instance.
152     ValueMapping() : ValueMapping(nullptr, 0) {}
153
154     /// Initialize a ValueMapping with the given parameter.
155     /// \p BreakDown needs to have a life time at least as long
156     /// as this instance.
157     ValueMapping(const PartialMapping *BreakDown, unsigned NumBreakDowns)
158         : BreakDown(BreakDown), NumBreakDowns(NumBreakDowns) {}
159
160     /// Iterators through the PartialMappings.
161     const PartialMapping *begin() const { return BreakDown; }
162     const PartialMapping *end() const { return BreakDown + NumBreakDowns; }
163
164     /// \return true if all partial mappings are the same size and register
165     /// bank.
166     bool partsAllUniform() const;
167
168     /// Check if this ValueMapping is valid.
169     bool isValid() const { return BreakDown && NumBreakDowns; }
170
171     /// Verify that this mapping makes sense for a value of
172     /// \p MeaningfulBitWidth.
173     /// \note This method does not check anything when assertions are disabled.
174     ///
175     /// \return True is the check was successful.
176     bool verify(unsigned MeaningfulBitWidth) const;
177
178     /// Print this on dbgs() stream.
179     void dump() const;
180
181     /// Print this on \p OS;
182     void print(raw_ostream &OS) const;
183   };
184
185   /// Helper class that represents how the value of an instruction may be
186   /// mapped and what is the related cost of such mapping.
187   class InstructionMapping {
188     /// Identifier of the mapping.
189     /// This is used to communicate between the target and the optimizers
190     /// which mapping should be realized.
191     unsigned ID = InvalidMappingID;
192
193     /// Cost of this mapping.
194     unsigned Cost = 0;
195
196     /// Mapping of all the operands.
197     const ValueMapping *OperandsMapping = nullptr;
198
199     /// Number of operands.
200     unsigned NumOperands = 0;
201
202     const ValueMapping &getOperandMapping(unsigned i) {
203       assert(i < getNumOperands() && "Out of bound operand");
204       return OperandsMapping[i];
205     }
206
207   public:
208     /// Constructor for the mapping of an instruction.
209     /// \p NumOperands must be equal to number of all the operands of
210     /// the related instruction.
211     /// The rationale is that it is more efficient for the optimizers
212     /// to be able to assume that the mapping of the ith operand is
213     /// at the index i.
214     InstructionMapping(unsigned ID, unsigned Cost,
215                        const ValueMapping *OperandsMapping,
216                        unsigned NumOperands)
217         : ID(ID), Cost(Cost), OperandsMapping(OperandsMapping),
218           NumOperands(NumOperands) {
219     }
220
221     /// Default constructor.
222     /// Use this constructor to express that the mapping is invalid.
223     InstructionMapping() = default;
224
225     /// Get the cost.
226     unsigned getCost() const { return Cost; }
227
228     /// Get the ID.
229     unsigned getID() const { return ID; }
230
231     /// Get the number of operands.
232     unsigned getNumOperands() const { return NumOperands; }
233
234     /// Get the value mapping of the ith operand.
235     /// \pre The mapping for the ith operand has been set.
236     /// \pre The ith operand is a register.
237     const ValueMapping &getOperandMapping(unsigned i) const {
238       const ValueMapping &ValMapping =
239           const_cast<InstructionMapping *>(this)->getOperandMapping(i);
240       return ValMapping;
241     }
242
243     /// Set the mapping for all the operands.
244     /// In other words, OpdsMapping should hold at least getNumOperands
245     /// ValueMapping.
246     void setOperandsMapping(const ValueMapping *OpdsMapping) {
247       OperandsMapping = OpdsMapping;
248     }
249
250     /// Check whether this object is valid.
251     /// This is a lightweight check for obvious wrong instance.
252     bool isValid() const {
253       return getID() != InvalidMappingID && OperandsMapping;
254     }
255
256     /// Verifiy that this mapping makes sense for \p MI.
257     /// \pre \p MI must be connected to a MachineFunction.
258     ///
259     /// \note This method does not check anything when assertions are disabled.
260     ///
261     /// \return True is the check was successful.
262     bool verify(const MachineInstr &MI) const;
263
264     /// Print this on dbgs() stream.
265     void dump() const;
266
267     /// Print this on \p OS;
268     void print(raw_ostream &OS) const;
269   };
270
271   /// Convenient type to represent the alternatives for mapping an
272   /// instruction.
273   /// \todo When we move to TableGen this should be an array ref.
274   using InstructionMappings = SmallVector<const InstructionMapping *, 4>;
275
276   /// Helper class used to get/create the virtual registers that will be used
277   /// to replace the MachineOperand when applying a mapping.
278   class OperandsMapper {
279     /// The OpIdx-th cell contains the index in NewVRegs where the VRegs of the
280     /// OpIdx-th operand starts. -1 means we do not have such mapping yet.
281     /// Note: We use a SmallVector to avoid heap allocation for most cases.
282     SmallVector<int, 8> OpToNewVRegIdx;
283
284     /// Hold the registers that will be used to map MI with InstrMapping.
285     SmallVector<Register, 8> NewVRegs;
286
287     /// Current MachineRegisterInfo, used to create new virtual registers.
288     MachineRegisterInfo &MRI;
289
290     /// Instruction being remapped.
291     MachineInstr &MI;
292
293     /// New mapping of the instruction.
294     const InstructionMapping &InstrMapping;
295
296     /// Constant value identifying that the index in OpToNewVRegIdx
297     /// for an operand has not been set yet.
298     static const int DontKnowIdx;
299
300     /// Get the range in NewVRegs to store all the partial
301     /// values for the \p OpIdx-th operand.
302     ///
303     /// \return The iterator range for the space created.
304     //
305     /// \pre getMI().getOperand(OpIdx).isReg()
306     iterator_range<SmallVectorImpl<Register>::iterator>
307     getVRegsMem(unsigned OpIdx);
308
309     /// Get the end iterator for a range starting at \p StartIdx and
310     /// spannig \p NumVal in NewVRegs.
311     /// \pre StartIdx + NumVal <= NewVRegs.size()
312     SmallVectorImpl<Register>::const_iterator
313     getNewVRegsEnd(unsigned StartIdx, unsigned NumVal) const;
314     SmallVectorImpl<Register>::iterator getNewVRegsEnd(unsigned StartIdx,
315                                                        unsigned NumVal);
316
317   public:
318     /// Create an OperandsMapper that will hold the information to apply \p
319     /// InstrMapping to \p MI.
320     /// \pre InstrMapping.verify(MI)
321     OperandsMapper(MachineInstr &MI, const InstructionMapping &InstrMapping,
322                    MachineRegisterInfo &MRI);
323
324     /// \name Getters.
325     /// @{
326     /// The MachineInstr being remapped.
327     MachineInstr &getMI() const { return MI; }
328
329     /// The final mapping of the instruction.
330     const InstructionMapping &getInstrMapping() const { return InstrMapping; }
331
332     /// The MachineRegisterInfo we used to realize the mapping.
333     MachineRegisterInfo &getMRI() const { return MRI; }
334     /// @}
335
336     /// Create as many new virtual registers as needed for the mapping of the \p
337     /// OpIdx-th operand.
338     /// The number of registers is determined by the number of breakdown for the
339     /// related operand in the instruction mapping.
340     /// The type of the new registers is a plain scalar of the right size.
341     /// The proper type is expected to be set when the mapping is applied to
342     /// the instruction(s) that realizes the mapping.
343     ///
344     /// \pre getMI().getOperand(OpIdx).isReg()
345     ///
346     /// \post All the partial mapping of the \p OpIdx-th operand have been
347     /// assigned a new virtual register.
348     void createVRegs(unsigned OpIdx);
349
350     /// Set the virtual register of the \p PartialMapIdx-th partial mapping of
351     /// the OpIdx-th operand to \p NewVReg.
352     ///
353     /// \pre getMI().getOperand(OpIdx).isReg()
354     /// \pre getInstrMapping().getOperandMapping(OpIdx).BreakDown.size() >
355     /// PartialMapIdx
356     /// \pre NewReg != 0
357     ///
358     /// \post the \p PartialMapIdx-th register of the value mapping of the \p
359     /// OpIdx-th operand has been set.
360     void setVRegs(unsigned OpIdx, unsigned PartialMapIdx, Register NewVReg);
361
362     /// Get all the virtual registers required to map the \p OpIdx-th operand of
363     /// the instruction.
364     ///
365     /// This return an empty range when createVRegs or setVRegs has not been
366     /// called.
367     /// The iterator may be invalidated by a call to setVRegs or createVRegs.
368     ///
369     /// When \p ForDebug is true, we will not check that the list of new virtual
370     /// registers does not contain uninitialized values.
371     ///
372     /// \pre getMI().getOperand(OpIdx).isReg()
373     /// \pre ForDebug || All partial mappings have been set a register
374     iterator_range<SmallVectorImpl<Register>::const_iterator>
375     getVRegs(unsigned OpIdx, bool ForDebug = false) const;
376
377     /// Print this operands mapper on dbgs() stream.
378     void dump() const;
379
380     /// Print this operands mapper on \p OS stream.
381     void print(raw_ostream &OS, bool ForDebug = false) const;
382   };
383
384 protected:
385   /// Hold the set of supported register banks.
386   RegisterBank **RegBanks;
387
388   /// Total number of register banks.
389   unsigned NumRegBanks;
390
391   /// Keep dynamically allocated PartialMapping in a separate map.
392   /// This shouldn't be needed when everything gets TableGen'ed.
393   mutable DenseMap<unsigned, std::unique_ptr<const PartialMapping>>
394       MapOfPartialMappings;
395
396   /// Keep dynamically allocated ValueMapping in a separate map.
397   /// This shouldn't be needed when everything gets TableGen'ed.
398   mutable DenseMap<unsigned, std::unique_ptr<const ValueMapping>>
399       MapOfValueMappings;
400
401   /// Keep dynamically allocated array of ValueMapping in a separate map.
402   /// This shouldn't be needed when everything gets TableGen'ed.
403   mutable DenseMap<unsigned, std::unique_ptr<ValueMapping[]>>
404       MapOfOperandsMappings;
405
406   /// Keep dynamically allocated InstructionMapping in a separate map.
407   /// This shouldn't be needed when everything gets TableGen'ed.
408   mutable DenseMap<unsigned, std::unique_ptr<const InstructionMapping>>
409       MapOfInstructionMappings;
410
411   /// Getting the minimal register class of a physreg is expensive.
412   /// Cache this information as we get it.
413   mutable DenseMap<unsigned, const TargetRegisterClass *> PhysRegMinimalRCs;
414
415   /// Create a RegisterBankInfo that can accommodate up to \p NumRegBanks
416   /// RegisterBank instances.
417   RegisterBankInfo(RegisterBank **RegBanks, unsigned NumRegBanks);
418
419   /// This constructor is meaningless.
420   /// It just provides a default constructor that can be used at link time
421   /// when GlobalISel is not built.
422   /// That way, targets can still inherit from this class without doing
423   /// crazy gymnastic to avoid link time failures.
424   /// \note That works because the constructor is inlined.
425   RegisterBankInfo() {
426     llvm_unreachable("This constructor should not be executed");
427   }
428
429   /// Get the register bank identified by \p ID.
430   RegisterBank &getRegBank(unsigned ID) {
431     assert(ID < getNumRegBanks() && "Accessing an unknown register bank");
432     return *RegBanks[ID];
433   }
434
435   /// Get the MinimalPhysRegClass for Reg.
436   /// \pre Reg is a physical register.
437   const TargetRegisterClass &
438   getMinimalPhysRegClass(Register Reg, const TargetRegisterInfo &TRI) const;
439
440   /// Try to get the mapping of \p MI.
441   /// See getInstrMapping for more details on what a mapping represents.
442   ///
443   /// Unlike getInstrMapping the returned InstructionMapping may be invalid
444   /// (isValid() == false).
445   /// This means that the target independent code is not smart enough
446   /// to get the mapping of \p MI and thus, the target has to provide the
447   /// information for \p MI.
448   ///
449   /// This implementation is able to get the mapping of:
450   /// - Target specific instructions by looking at the encoding constraints.
451   /// - Any instruction if all the register operands have already been assigned
452   ///   a register, a register class, or a register bank.
453   /// - Copies and phis if at least one of the operands has been assigned a
454   ///   register, a register class, or a register bank.
455   /// In other words, this method will likely fail to find a mapping for
456   /// any generic opcode that has not been lowered by target specific code.
457   const InstructionMapping &getInstrMappingImpl(const MachineInstr &MI) const;
458
459   /// Get the uniquely generated PartialMapping for the
460   /// given arguments.
461   const PartialMapping &getPartialMapping(unsigned StartIdx, unsigned Length,
462                                           const RegisterBank &RegBank) const;
463
464   /// \name Methods to get a uniquely generated ValueMapping.
465   /// @{
466
467   /// The most common ValueMapping consists of a single PartialMapping.
468   /// Feature a method for that.
469   const ValueMapping &getValueMapping(unsigned StartIdx, unsigned Length,
470                                       const RegisterBank &RegBank) const;
471
472   /// Get the ValueMapping for the given arguments.
473   const ValueMapping &getValueMapping(const PartialMapping *BreakDown,
474                                       unsigned NumBreakDowns) const;
475   /// @}
476
477   /// \name Methods to get a uniquely generated array of ValueMapping.
478   /// @{
479
480   /// Get the uniquely generated array of ValueMapping for the
481   /// elements of between \p Begin and \p End.
482   ///
483   /// Elements that are nullptr will be replaced by
484   /// invalid ValueMapping (ValueMapping::isValid == false).
485   ///
486   /// \pre The pointers on ValueMapping between \p Begin and \p End
487   /// must uniquely identify a ValueMapping. Otherwise, there is no
488   /// guarantee that the return instance will be unique, i.e., another
489   /// OperandsMapping could have the same content.
490   template <typename Iterator>
491   const ValueMapping *getOperandsMapping(Iterator Begin, Iterator End) const;
492
493   /// Get the uniquely generated array of ValueMapping for the
494   /// elements of \p OpdsMapping.
495   ///
496   /// Elements of \p OpdsMapping that are nullptr will be replaced by
497   /// invalid ValueMapping (ValueMapping::isValid == false).
498   const ValueMapping *getOperandsMapping(
499       const SmallVectorImpl<const ValueMapping *> &OpdsMapping) const;
500
501   /// Get the uniquely generated array of ValueMapping for the
502   /// given arguments.
503   ///
504   /// Arguments that are nullptr will be replaced by invalid
505   /// ValueMapping (ValueMapping::isValid == false).
506   const ValueMapping *getOperandsMapping(
507       std::initializer_list<const ValueMapping *> OpdsMapping) const;
508   /// @}
509
510   /// \name Methods to get a uniquely generated InstructionMapping.
511   /// @{
512
513 private:
514   /// Method to get a uniquely generated InstructionMapping.
515   const InstructionMapping &
516   getInstructionMappingImpl(bool IsInvalid, unsigned ID = InvalidMappingID,
517                             unsigned Cost = 0,
518                             const ValueMapping *OperandsMapping = nullptr,
519                             unsigned NumOperands = 0) const;
520
521 public:
522   /// Method to get a uniquely generated InstructionMapping.
523   const InstructionMapping &
524   getInstructionMapping(unsigned ID, unsigned Cost,
525                         const ValueMapping *OperandsMapping,
526                         unsigned NumOperands) const {
527     return getInstructionMappingImpl(/*IsInvalid*/ false, ID, Cost,
528                                      OperandsMapping, NumOperands);
529   }
530
531   /// Method to get a uniquely generated invalid InstructionMapping.
532   const InstructionMapping &getInvalidInstructionMapping() const {
533     return getInstructionMappingImpl(/*IsInvalid*/ true);
534   }
535   /// @}
536
537   /// Get the register bank for the \p OpIdx-th operand of \p MI form
538   /// the encoding constraints, if any.
539   ///
540   /// \return A register bank that covers the register class of the
541   /// related encoding constraints or nullptr if \p MI did not provide
542   /// enough information to deduce it.
543   const RegisterBank *
544   getRegBankFromConstraints(const MachineInstr &MI, unsigned OpIdx,
545                             const TargetInstrInfo &TII,
546                             const TargetRegisterInfo &TRI) const;
547
548   /// Helper method to apply something that is like the default mapping.
549   /// Basically, that means that \p OpdMapper.getMI() is left untouched
550   /// aside from the reassignment of the register operand that have been
551   /// remapped.
552   ///
553   /// The type of all the new registers that have been created by the
554   /// mapper are properly remapped to the type of the original registers
555   /// they replace. In other words, the semantic of the instruction does
556   /// not change, only the register banks.
557   ///
558   /// If the mapping of one of the operand spans several registers, this
559   /// method will abort as this is not like a default mapping anymore.
560   ///
561   /// \pre For OpIdx in {0..\p OpdMapper.getMI().getNumOperands())
562   ///        the range OpdMapper.getVRegs(OpIdx) is empty or of size 1.
563   static void applyDefaultMapping(const OperandsMapper &OpdMapper);
564
565   /// See ::applyMapping.
566   virtual void applyMappingImpl(const OperandsMapper &OpdMapper) const {
567     llvm_unreachable("The target has to implement that part");
568   }
569
570 public:
571   virtual ~RegisterBankInfo() = default;
572
573   /// Get the register bank identified by \p ID.
574   const RegisterBank &getRegBank(unsigned ID) const {
575     return const_cast<RegisterBankInfo *>(this)->getRegBank(ID);
576   }
577
578   /// Get the register bank of \p Reg.
579   /// If Reg has not been assigned a register, a register class,
580   /// or a register bank, then this returns nullptr.
581   ///
582   /// \pre Reg != 0 (NoRegister)
583   const RegisterBank *getRegBank(Register Reg, const MachineRegisterInfo &MRI,
584                                  const TargetRegisterInfo &TRI) const;
585
586   /// Get the total number of register banks.
587   unsigned getNumRegBanks() const { return NumRegBanks; }
588
589   /// Get a register bank that covers \p RC.
590   ///
591   /// \pre \p RC is a user-defined register class (as opposed as one
592   /// generated by TableGen).
593   ///
594   /// \note The mapping RC -> RegBank could be built while adding the
595   /// coverage for the register banks. However, we do not do it, because,
596   /// at least for now, we only need this information for register classes
597   /// that are used in the description of instruction. In other words,
598   /// there are just a handful of them and we do not want to waste space.
599   ///
600   /// \todo This should be TableGen'ed.
601   virtual const RegisterBank &
602   getRegBankFromRegClass(const TargetRegisterClass &RC) const {
603     llvm_unreachable("The target must override this method");
604   }
605
606   /// Get the cost of a copy from \p B to \p A, or put differently,
607   /// get the cost of A = COPY B. Since register banks may cover
608   /// different size, \p Size specifies what will be the size in bits
609   /// that will be copied around.
610   ///
611   /// \note Since this is a copy, both registers have the same size.
612   virtual unsigned copyCost(const RegisterBank &A, const RegisterBank &B,
613                             unsigned Size) const {
614     // Optimistically assume that copies are coalesced. I.e., when
615     // they are on the same bank, they are free.
616     // Otherwise assume a non-zero cost of 1. The targets are supposed
617     // to override that properly anyway if they care.
618     return &A != &B;
619   }
620
621   /// \returns true if emitting a copy from \p Src to \p Dst is impossible.
622   bool cannotCopy(const RegisterBank &Dst, const RegisterBank &Src,
623                   unsigned Size) const {
624     return copyCost(Dst, Src, Size) == std::numeric_limits<unsigned>::max();
625   }
626
627   /// Get the cost of using \p ValMapping to decompose a register. This is
628   /// similar to ::copyCost, except for cases where multiple copy-like
629   /// operations need to be inserted. If the register is used as a source
630   /// operand and already has a bank assigned, \p CurBank is non-null.
631   virtual unsigned getBreakDownCost(const ValueMapping &ValMapping,
632                                     const RegisterBank *CurBank = nullptr) const {
633     return std::numeric_limits<unsigned>::max();
634   }
635
636   /// Constrain the (possibly generic) virtual register \p Reg to \p RC.
637   ///
638   /// \pre \p Reg is a virtual register that either has a bank or a class.
639   /// \returns The constrained register class, or nullptr if there is none.
640   /// \note This is a generic variant of MachineRegisterInfo::constrainRegClass
641   /// \note Use MachineRegisterInfo::constrainRegAttrs instead for any non-isel
642   /// purpose, including non-select passes of GlobalISel
643   static const TargetRegisterClass *
644   constrainGenericRegister(Register Reg, const TargetRegisterClass &RC,
645                            MachineRegisterInfo &MRI);
646
647   /// Identifier used when the related instruction mapping instance
648   /// is generated by target independent code.
649   /// Make sure not to use that identifier to avoid possible collision.
650   static const unsigned DefaultMappingID;
651
652   /// Identifier used when the related instruction mapping instance
653   /// is generated by the default constructor.
654   /// Make sure not to use that identifier.
655   static const unsigned InvalidMappingID;
656
657   /// Get the mapping of the different operands of \p MI
658   /// on the register bank.
659   /// This mapping should be the direct translation of \p MI.
660   /// In other words, when \p MI is mapped with the returned mapping,
661   /// only the register banks of the operands of \p MI need to be updated.
662   /// In particular, neither the opcode nor the type of \p MI needs to be
663   /// updated for this direct mapping.
664   ///
665   /// The target independent implementation gives a mapping based on
666   /// the register classes for the target specific opcode.
667   /// It uses the ID RegisterBankInfo::DefaultMappingID for that mapping.
668   /// Make sure you do not use that ID for the alternative mapping
669   /// for MI. See getInstrAlternativeMappings for the alternative
670   /// mappings.
671   ///
672   /// For instance, if \p MI is a vector add, the mapping should
673   /// not be a scalarization of the add.
674   ///
675   /// \post returnedVal.verify(MI).
676   ///
677   /// \note If returnedVal does not verify MI, this would probably mean
678   /// that the target does not support that instruction.
679   virtual const InstructionMapping &
680   getInstrMapping(const MachineInstr &MI) const;
681
682   /// Get the alternative mappings for \p MI.
683   /// Alternative in the sense different from getInstrMapping.
684   virtual InstructionMappings
685   getInstrAlternativeMappings(const MachineInstr &MI) const;
686
687   /// Get the possible mapping for \p MI.
688   /// A mapping defines where the different operands may live and at what cost.
689   /// For instance, let us consider:
690   /// v0(16) = G_ADD <2 x i8> v1, v2
691   /// The possible mapping could be:
692   ///
693   /// {/*ID*/VectorAdd, /*Cost*/1, /*v0*/{(0xFFFF, VPR)}, /*v1*/{(0xFFFF, VPR)},
694   ///                              /*v2*/{(0xFFFF, VPR)}}
695   /// {/*ID*/ScalarAddx2, /*Cost*/2, /*v0*/{(0x00FF, GPR),(0xFF00, GPR)},
696   ///                                /*v1*/{(0x00FF, GPR),(0xFF00, GPR)},
697   ///                                /*v2*/{(0x00FF, GPR),(0xFF00, GPR)}}
698   ///
699   /// \note The first alternative of the returned mapping should be the
700   /// direct translation of \p MI current form.
701   ///
702   /// \post !returnedVal.empty().
703   InstructionMappings getInstrPossibleMappings(const MachineInstr &MI) const;
704
705   /// Apply \p OpdMapper.getInstrMapping() to \p OpdMapper.getMI().
706   /// After this call \p OpdMapper.getMI() may not be valid anymore.
707   /// \p OpdMapper.getInstrMapping().getID() carries the information of
708   /// what has been chosen to map \p OpdMapper.getMI(). This ID is set
709   /// by the various getInstrXXXMapping method.
710   ///
711   /// Therefore, getting the mapping and applying it should be kept in
712   /// sync.
713   void applyMapping(const OperandsMapper &OpdMapper) const {
714     // The only mapping we know how to handle is the default mapping.
715     if (OpdMapper.getInstrMapping().getID() == DefaultMappingID)
716       return applyDefaultMapping(OpdMapper);
717     // For other mapping, the target needs to do the right thing.
718     // If that means calling applyDefaultMapping, fine, but this
719     // must be explicitly stated.
720     applyMappingImpl(OpdMapper);
721   }
722
723   /// Get the size in bits of \p Reg.
724   /// Utility method to get the size of any registers. Unlike
725   /// MachineRegisterInfo::getSize, the register does not need to be a
726   /// virtual register.
727   ///
728   /// \pre \p Reg != 0 (NoRegister).
729   unsigned getSizeInBits(Register Reg, const MachineRegisterInfo &MRI,
730                          const TargetRegisterInfo &TRI) const;
731
732   /// Check that information hold by this instance make sense for the
733   /// given \p TRI.
734   ///
735   /// \note This method does not check anything when assertions are disabled.
736   ///
737   /// \return True is the check was successful.
738   bool verify(const TargetRegisterInfo &TRI) const;
739 };
740
741 inline raw_ostream &
742 operator<<(raw_ostream &OS,
743            const RegisterBankInfo::PartialMapping &PartMapping) {
744   PartMapping.print(OS);
745   return OS;
746 }
747
748 inline raw_ostream &
749 operator<<(raw_ostream &OS, const RegisterBankInfo::ValueMapping &ValMapping) {
750   ValMapping.print(OS);
751   return OS;
752 }
753
754 inline raw_ostream &
755 operator<<(raw_ostream &OS,
756            const RegisterBankInfo::InstructionMapping &InstrMapping) {
757   InstrMapping.print(OS);
758   return OS;
759 }
760
761 inline raw_ostream &
762 operator<<(raw_ostream &OS, const RegisterBankInfo::OperandsMapper &OpdMapper) {
763   OpdMapper.print(OS, /*ForDebug*/ false);
764   return OS;
765 }
766
767 /// Hashing function for PartialMapping.
768 /// It is required for the hashing of ValueMapping.
769 hash_code hash_value(const RegisterBankInfo::PartialMapping &PartMapping);
770
771 } // end namespace llvm
772
773 #endif // LLVM_CODEGEN_GLOBALISEL_REGISTERBANKINFO_H