]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/CodeGen/MachineRegisterInfo.h
Import tzdata 2018d
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / CodeGen / MachineRegisterInfo.h
1 //===- llvm/CodeGen/MachineRegisterInfo.h -----------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the MachineRegisterInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_CODEGEN_MACHINEREGISTERINFO_H
15 #define LLVM_CODEGEN_MACHINEREGISTERINFO_H
16
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/IndexedMap.h"
21 #include "llvm/ADT/PointerUnion.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/iterator_range.h"
24 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
25 #include "llvm/CodeGen/LowLevelType.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBundle.h"
29 #include "llvm/CodeGen/MachineOperand.h"
30 #include "llvm/CodeGen/TargetRegisterInfo.h"
31 #include "llvm/CodeGen/TargetSubtargetInfo.h"
32 #include "llvm/MC/LaneBitmask.h"
33 #include <cassert>
34 #include <cstddef>
35 #include <cstdint>
36 #include <iterator>
37 #include <memory>
38 #include <utility>
39 #include <vector>
40
41 namespace llvm {
42
43 class PSetIterator;
44
45 /// Convenient type to represent either a register class or a register bank.
46 using RegClassOrRegBank =
47     PointerUnion<const TargetRegisterClass *, const RegisterBank *>;
48
49 /// MachineRegisterInfo - Keep track of information for virtual and physical
50 /// registers, including vreg register classes, use/def chains for registers,
51 /// etc.
52 class MachineRegisterInfo {
53 public:
54   class Delegate {
55     virtual void anchor();
56
57   public:
58     virtual ~Delegate() = default;
59
60     virtual void MRI_NoteNewVirtualRegister(unsigned Reg) = 0;
61   };
62
63 private:
64   MachineFunction *MF;
65   Delegate *TheDelegate = nullptr;
66
67   /// True if subregister liveness is tracked.
68   const bool TracksSubRegLiveness;
69
70   /// VRegInfo - Information we keep for each virtual register.
71   ///
72   /// Each element in this list contains the register class of the vreg and the
73   /// start of the use/def list for the register.
74   IndexedMap<std::pair<RegClassOrRegBank, MachineOperand *>,
75              VirtReg2IndexFunctor>
76       VRegInfo;
77
78   /// The flag is true upon \p UpdatedCSRs initialization
79   /// and false otherwise.
80   bool IsUpdatedCSRsInitialized;
81
82   /// Contains the updated callee saved register list.
83   /// As opposed to the static list defined in register info,
84   /// all registers that were disabled are removed from the list.
85   SmallVector<MCPhysReg, 16> UpdatedCSRs;
86
87   /// RegAllocHints - This vector records register allocation hints for
88   /// virtual registers. For each virtual register, it keeps a pair of hint
89   /// type and hints vector making up the allocation hints. Only the first
90   /// hint may be target specific, and in that case this is reflected by the
91   /// first member of the pair being non-zero. If the hinted register is
92   /// virtual, it means the allocator should prefer the physical register
93   /// allocated to it if any.
94   IndexedMap<std::pair<unsigned, SmallVector<unsigned, 4>>,
95              VirtReg2IndexFunctor> RegAllocHints;
96
97   /// PhysRegUseDefLists - This is an array of the head of the use/def list for
98   /// physical registers.
99   std::unique_ptr<MachineOperand *[]> PhysRegUseDefLists;
100
101   /// getRegUseDefListHead - Return the head pointer for the register use/def
102   /// list for the specified virtual or physical register.
103   MachineOperand *&getRegUseDefListHead(unsigned RegNo) {
104     if (TargetRegisterInfo::isVirtualRegister(RegNo))
105       return VRegInfo[RegNo].second;
106     return PhysRegUseDefLists[RegNo];
107   }
108
109   MachineOperand *getRegUseDefListHead(unsigned RegNo) const {
110     if (TargetRegisterInfo::isVirtualRegister(RegNo))
111       return VRegInfo[RegNo].second;
112     return PhysRegUseDefLists[RegNo];
113   }
114
115   /// Get the next element in the use-def chain.
116   static MachineOperand *getNextOperandForReg(const MachineOperand *MO) {
117     assert(MO && MO->isReg() && "This is not a register operand!");
118     return MO->Contents.Reg.Next;
119   }
120
121   /// UsedPhysRegMask - Additional used physregs including aliases.
122   /// This bit vector represents all the registers clobbered by function calls.
123   BitVector UsedPhysRegMask;
124
125   /// ReservedRegs - This is a bit vector of reserved registers.  The target
126   /// may change its mind about which registers should be reserved.  This
127   /// vector is the frozen set of reserved registers when register allocation
128   /// started.
129   BitVector ReservedRegs;
130
131   using VRegToTypeMap = DenseMap<unsigned, LLT>;
132   /// Map generic virtual registers to their actual size.
133   mutable std::unique_ptr<VRegToTypeMap> VRegToType;
134
135   /// Keep track of the physical registers that are live in to the function.
136   /// Live in values are typically arguments in registers.  LiveIn values are
137   /// allowed to have virtual registers associated with them, stored in the
138   /// second element.
139   std::vector<std::pair<unsigned, unsigned>> LiveIns;
140
141 public:
142   explicit MachineRegisterInfo(MachineFunction *MF);
143   MachineRegisterInfo(const MachineRegisterInfo &) = delete;
144   MachineRegisterInfo &operator=(const MachineRegisterInfo &) = delete;
145
146   const TargetRegisterInfo *getTargetRegisterInfo() const {
147     return MF->getSubtarget().getRegisterInfo();
148   }
149
150   void resetDelegate(Delegate *delegate) {
151     // Ensure another delegate does not take over unless the current
152     // delegate first unattaches itself. If we ever need to multicast
153     // notifications, we will need to change to using a list.
154     assert(TheDelegate == delegate &&
155            "Only the current delegate can perform reset!");
156     TheDelegate = nullptr;
157   }
158
159   void setDelegate(Delegate *delegate) {
160     assert(delegate && !TheDelegate &&
161            "Attempted to set delegate to null, or to change it without "
162            "first resetting it!");
163
164     TheDelegate = delegate;
165   }
166
167   //===--------------------------------------------------------------------===//
168   // Function State
169   //===--------------------------------------------------------------------===//
170
171   // isSSA - Returns true when the machine function is in SSA form. Early
172   // passes require the machine function to be in SSA form where every virtual
173   // register has a single defining instruction.
174   //
175   // The TwoAddressInstructionPass and PHIElimination passes take the machine
176   // function out of SSA form when they introduce multiple defs per virtual
177   // register.
178   bool isSSA() const {
179     return MF->getProperties().hasProperty(
180         MachineFunctionProperties::Property::IsSSA);
181   }
182
183   // leaveSSA - Indicates that the machine function is no longer in SSA form.
184   void leaveSSA() {
185     MF->getProperties().reset(MachineFunctionProperties::Property::IsSSA);
186   }
187
188   /// tracksLiveness - Returns true when tracking register liveness accurately.
189   /// (see MachineFUnctionProperties::Property description for details)
190   bool tracksLiveness() const {
191     return MF->getProperties().hasProperty(
192         MachineFunctionProperties::Property::TracksLiveness);
193   }
194
195   /// invalidateLiveness - Indicates that register liveness is no longer being
196   /// tracked accurately.
197   ///
198   /// This should be called by late passes that invalidate the liveness
199   /// information.
200   void invalidateLiveness() {
201     MF->getProperties().reset(
202         MachineFunctionProperties::Property::TracksLiveness);
203   }
204
205   /// Returns true if liveness for register class @p RC should be tracked at
206   /// the subregister level.
207   bool shouldTrackSubRegLiveness(const TargetRegisterClass &RC) const {
208     return subRegLivenessEnabled() && RC.HasDisjunctSubRegs;
209   }
210   bool shouldTrackSubRegLiveness(unsigned VReg) const {
211     assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Must pass a VReg");
212     return shouldTrackSubRegLiveness(*getRegClass(VReg));
213   }
214   bool subRegLivenessEnabled() const {
215     return TracksSubRegLiveness;
216   }
217
218   //===--------------------------------------------------------------------===//
219   // Register Info
220   //===--------------------------------------------------------------------===//
221
222   /// Returns true if the updated CSR list was initialized and false otherwise.
223   bool isUpdatedCSRsInitialized() const { return IsUpdatedCSRsInitialized; }
224
225   /// Disables the register from the list of CSRs.
226   /// I.e. the register will not appear as part of the CSR mask.
227   /// \see UpdatedCalleeSavedRegs.
228   void disableCalleeSavedRegister(unsigned Reg);
229
230   /// Returns list of callee saved registers.
231   /// The function returns the updated CSR list (after taking into account
232   /// registers that are disabled from the CSR list).
233   const MCPhysReg *getCalleeSavedRegs() const;
234
235   /// Sets the updated Callee Saved Registers list.
236   /// Notice that it will override ant previously disabled/saved CSRs.
237   void setCalleeSavedRegs(ArrayRef<MCPhysReg> CSRs);
238
239   // Strictly for use by MachineInstr.cpp.
240   void addRegOperandToUseList(MachineOperand *MO);
241
242   // Strictly for use by MachineInstr.cpp.
243   void removeRegOperandFromUseList(MachineOperand *MO);
244
245   // Strictly for use by MachineInstr.cpp.
246   void moveOperands(MachineOperand *Dst, MachineOperand *Src, unsigned NumOps);
247
248   /// Verify the sanity of the use list for Reg.
249   void verifyUseList(unsigned Reg) const;
250
251   /// Verify the use list of all registers.
252   void verifyUseLists() const;
253
254   /// reg_begin/reg_end - Provide iteration support to walk over all definitions
255   /// and uses of a register within the MachineFunction that corresponds to this
256   /// MachineRegisterInfo object.
257   template<bool Uses, bool Defs, bool SkipDebug,
258            bool ByOperand, bool ByInstr, bool ByBundle>
259   class defusechain_iterator;
260   template<bool Uses, bool Defs, bool SkipDebug,
261            bool ByOperand, bool ByInstr, bool ByBundle>
262   class defusechain_instr_iterator;
263
264   // Make it a friend so it can access getNextOperandForReg().
265   template<bool, bool, bool, bool, bool, bool>
266     friend class defusechain_iterator;
267   template<bool, bool, bool, bool, bool, bool>
268     friend class defusechain_instr_iterator;
269
270   /// reg_iterator/reg_begin/reg_end - Walk all defs and uses of the specified
271   /// register.
272   using reg_iterator =
273       defusechain_iterator<true, true, false, true, false, false>;
274   reg_iterator reg_begin(unsigned RegNo) const {
275     return reg_iterator(getRegUseDefListHead(RegNo));
276   }
277   static reg_iterator reg_end() { return reg_iterator(nullptr); }
278
279   inline iterator_range<reg_iterator>  reg_operands(unsigned Reg) const {
280     return make_range(reg_begin(Reg), reg_end());
281   }
282
283   /// reg_instr_iterator/reg_instr_begin/reg_instr_end - Walk all defs and uses
284   /// of the specified register, stepping by MachineInstr.
285   using reg_instr_iterator =
286       defusechain_instr_iterator<true, true, false, false, true, false>;
287   reg_instr_iterator reg_instr_begin(unsigned RegNo) const {
288     return reg_instr_iterator(getRegUseDefListHead(RegNo));
289   }
290   static reg_instr_iterator reg_instr_end() {
291     return reg_instr_iterator(nullptr);
292   }
293
294   inline iterator_range<reg_instr_iterator>
295   reg_instructions(unsigned Reg) const {
296     return make_range(reg_instr_begin(Reg), reg_instr_end());
297   }
298
299   /// reg_bundle_iterator/reg_bundle_begin/reg_bundle_end - Walk all defs and uses
300   /// of the specified register, stepping by bundle.
301   using reg_bundle_iterator =
302       defusechain_instr_iterator<true, true, false, false, false, true>;
303   reg_bundle_iterator reg_bundle_begin(unsigned RegNo) const {
304     return reg_bundle_iterator(getRegUseDefListHead(RegNo));
305   }
306   static reg_bundle_iterator reg_bundle_end() {
307     return reg_bundle_iterator(nullptr);
308   }
309
310   inline iterator_range<reg_bundle_iterator> reg_bundles(unsigned Reg) const {
311     return make_range(reg_bundle_begin(Reg), reg_bundle_end());
312   }
313
314   /// reg_empty - Return true if there are no instructions using or defining the
315   /// specified register (it may be live-in).
316   bool reg_empty(unsigned RegNo) const { return reg_begin(RegNo) == reg_end(); }
317
318   /// reg_nodbg_iterator/reg_nodbg_begin/reg_nodbg_end - Walk all defs and uses
319   /// of the specified register, skipping those marked as Debug.
320   using reg_nodbg_iterator =
321       defusechain_iterator<true, true, true, true, false, false>;
322   reg_nodbg_iterator reg_nodbg_begin(unsigned RegNo) const {
323     return reg_nodbg_iterator(getRegUseDefListHead(RegNo));
324   }
325   static reg_nodbg_iterator reg_nodbg_end() {
326     return reg_nodbg_iterator(nullptr);
327   }
328
329   inline iterator_range<reg_nodbg_iterator>
330   reg_nodbg_operands(unsigned Reg) const {
331     return make_range(reg_nodbg_begin(Reg), reg_nodbg_end());
332   }
333
334   /// reg_instr_nodbg_iterator/reg_instr_nodbg_begin/reg_instr_nodbg_end - Walk
335   /// all defs and uses of the specified register, stepping by MachineInstr,
336   /// skipping those marked as Debug.
337   using reg_instr_nodbg_iterator =
338       defusechain_instr_iterator<true, true, true, false, true, false>;
339   reg_instr_nodbg_iterator reg_instr_nodbg_begin(unsigned RegNo) const {
340     return reg_instr_nodbg_iterator(getRegUseDefListHead(RegNo));
341   }
342   static reg_instr_nodbg_iterator reg_instr_nodbg_end() {
343     return reg_instr_nodbg_iterator(nullptr);
344   }
345
346   inline iterator_range<reg_instr_nodbg_iterator>
347   reg_nodbg_instructions(unsigned Reg) const {
348     return make_range(reg_instr_nodbg_begin(Reg), reg_instr_nodbg_end());
349   }
350
351   /// reg_bundle_nodbg_iterator/reg_bundle_nodbg_begin/reg_bundle_nodbg_end - Walk
352   /// all defs and uses of the specified register, stepping by bundle,
353   /// skipping those marked as Debug.
354   using reg_bundle_nodbg_iterator =
355       defusechain_instr_iterator<true, true, true, false, false, true>;
356   reg_bundle_nodbg_iterator reg_bundle_nodbg_begin(unsigned RegNo) const {
357     return reg_bundle_nodbg_iterator(getRegUseDefListHead(RegNo));
358   }
359   static reg_bundle_nodbg_iterator reg_bundle_nodbg_end() {
360     return reg_bundle_nodbg_iterator(nullptr);
361   }
362
363   inline iterator_range<reg_bundle_nodbg_iterator>
364   reg_nodbg_bundles(unsigned Reg) const {
365     return make_range(reg_bundle_nodbg_begin(Reg), reg_bundle_nodbg_end());
366   }
367
368   /// reg_nodbg_empty - Return true if the only instructions using or defining
369   /// Reg are Debug instructions.
370   bool reg_nodbg_empty(unsigned RegNo) const {
371     return reg_nodbg_begin(RegNo) == reg_nodbg_end();
372   }
373
374   /// def_iterator/def_begin/def_end - Walk all defs of the specified register.
375   using def_iterator =
376       defusechain_iterator<false, true, false, true, false, false>;
377   def_iterator def_begin(unsigned RegNo) const {
378     return def_iterator(getRegUseDefListHead(RegNo));
379   }
380   static def_iterator def_end() { return def_iterator(nullptr); }
381
382   inline iterator_range<def_iterator> def_operands(unsigned Reg) const {
383     return make_range(def_begin(Reg), def_end());
384   }
385
386   /// def_instr_iterator/def_instr_begin/def_instr_end - Walk all defs of the
387   /// specified register, stepping by MachineInst.
388   using def_instr_iterator =
389       defusechain_instr_iterator<false, true, false, false, true, false>;
390   def_instr_iterator def_instr_begin(unsigned RegNo) const {
391     return def_instr_iterator(getRegUseDefListHead(RegNo));
392   }
393   static def_instr_iterator def_instr_end() {
394     return def_instr_iterator(nullptr);
395   }
396
397   inline iterator_range<def_instr_iterator>
398   def_instructions(unsigned Reg) const {
399     return make_range(def_instr_begin(Reg), def_instr_end());
400   }
401
402   /// def_bundle_iterator/def_bundle_begin/def_bundle_end - Walk all defs of the
403   /// specified register, stepping by bundle.
404   using def_bundle_iterator =
405       defusechain_instr_iterator<false, true, false, false, false, true>;
406   def_bundle_iterator def_bundle_begin(unsigned RegNo) const {
407     return def_bundle_iterator(getRegUseDefListHead(RegNo));
408   }
409   static def_bundle_iterator def_bundle_end() {
410     return def_bundle_iterator(nullptr);
411   }
412
413   inline iterator_range<def_bundle_iterator> def_bundles(unsigned Reg) const {
414     return make_range(def_bundle_begin(Reg), def_bundle_end());
415   }
416
417   /// def_empty - Return true if there are no instructions defining the
418   /// specified register (it may be live-in).
419   bool def_empty(unsigned RegNo) const { return def_begin(RegNo) == def_end(); }
420
421   /// Return true if there is exactly one operand defining the specified
422   /// register.
423   bool hasOneDef(unsigned RegNo) const {
424     def_iterator DI = def_begin(RegNo);
425     if (DI == def_end())
426       return false;
427     return ++DI == def_end();
428   }
429
430   /// use_iterator/use_begin/use_end - Walk all uses of the specified register.
431   using use_iterator =
432       defusechain_iterator<true, false, false, true, false, false>;
433   use_iterator use_begin(unsigned RegNo) const {
434     return use_iterator(getRegUseDefListHead(RegNo));
435   }
436   static use_iterator use_end() { return use_iterator(nullptr); }
437
438   inline iterator_range<use_iterator> use_operands(unsigned Reg) const {
439     return make_range(use_begin(Reg), use_end());
440   }
441
442   /// use_instr_iterator/use_instr_begin/use_instr_end - Walk all uses of the
443   /// specified register, stepping by MachineInstr.
444   using use_instr_iterator =
445       defusechain_instr_iterator<true, false, false, false, true, false>;
446   use_instr_iterator use_instr_begin(unsigned RegNo) const {
447     return use_instr_iterator(getRegUseDefListHead(RegNo));
448   }
449   static use_instr_iterator use_instr_end() {
450     return use_instr_iterator(nullptr);
451   }
452
453   inline iterator_range<use_instr_iterator>
454   use_instructions(unsigned Reg) const {
455     return make_range(use_instr_begin(Reg), use_instr_end());
456   }
457
458   /// use_bundle_iterator/use_bundle_begin/use_bundle_end - Walk all uses of the
459   /// specified register, stepping by bundle.
460   using use_bundle_iterator =
461       defusechain_instr_iterator<true, false, false, false, false, true>;
462   use_bundle_iterator use_bundle_begin(unsigned RegNo) const {
463     return use_bundle_iterator(getRegUseDefListHead(RegNo));
464   }
465   static use_bundle_iterator use_bundle_end() {
466     return use_bundle_iterator(nullptr);
467   }
468
469   inline iterator_range<use_bundle_iterator> use_bundles(unsigned Reg) const {
470     return make_range(use_bundle_begin(Reg), use_bundle_end());
471   }
472
473   /// use_empty - Return true if there are no instructions using the specified
474   /// register.
475   bool use_empty(unsigned RegNo) const { return use_begin(RegNo) == use_end(); }
476
477   /// hasOneUse - Return true if there is exactly one instruction using the
478   /// specified register.
479   bool hasOneUse(unsigned RegNo) const {
480     use_iterator UI = use_begin(RegNo);
481     if (UI == use_end())
482       return false;
483     return ++UI == use_end();
484   }
485
486   /// use_nodbg_iterator/use_nodbg_begin/use_nodbg_end - Walk all uses of the
487   /// specified register, skipping those marked as Debug.
488   using use_nodbg_iterator =
489       defusechain_iterator<true, false, true, true, false, false>;
490   use_nodbg_iterator use_nodbg_begin(unsigned RegNo) const {
491     return use_nodbg_iterator(getRegUseDefListHead(RegNo));
492   }
493   static use_nodbg_iterator use_nodbg_end() {
494     return use_nodbg_iterator(nullptr);
495   }
496
497   inline iterator_range<use_nodbg_iterator>
498   use_nodbg_operands(unsigned Reg) const {
499     return make_range(use_nodbg_begin(Reg), use_nodbg_end());
500   }
501
502   /// use_instr_nodbg_iterator/use_instr_nodbg_begin/use_instr_nodbg_end - Walk
503   /// all uses of the specified register, stepping by MachineInstr, skipping
504   /// those marked as Debug.
505   using use_instr_nodbg_iterator =
506       defusechain_instr_iterator<true, false, true, false, true, false>;
507   use_instr_nodbg_iterator use_instr_nodbg_begin(unsigned RegNo) const {
508     return use_instr_nodbg_iterator(getRegUseDefListHead(RegNo));
509   }
510   static use_instr_nodbg_iterator use_instr_nodbg_end() {
511     return use_instr_nodbg_iterator(nullptr);
512   }
513
514   inline iterator_range<use_instr_nodbg_iterator>
515   use_nodbg_instructions(unsigned Reg) const {
516     return make_range(use_instr_nodbg_begin(Reg), use_instr_nodbg_end());
517   }
518
519   /// use_bundle_nodbg_iterator/use_bundle_nodbg_begin/use_bundle_nodbg_end - Walk
520   /// all uses of the specified register, stepping by bundle, skipping
521   /// those marked as Debug.
522   using use_bundle_nodbg_iterator =
523       defusechain_instr_iterator<true, false, true, false, false, true>;
524   use_bundle_nodbg_iterator use_bundle_nodbg_begin(unsigned RegNo) const {
525     return use_bundle_nodbg_iterator(getRegUseDefListHead(RegNo));
526   }
527   static use_bundle_nodbg_iterator use_bundle_nodbg_end() {
528     return use_bundle_nodbg_iterator(nullptr);
529   }
530
531   inline iterator_range<use_bundle_nodbg_iterator>
532   use_nodbg_bundles(unsigned Reg) const {
533     return make_range(use_bundle_nodbg_begin(Reg), use_bundle_nodbg_end());
534   }
535
536   /// use_nodbg_empty - Return true if there are no non-Debug instructions
537   /// using the specified register.
538   bool use_nodbg_empty(unsigned RegNo) const {
539     return use_nodbg_begin(RegNo) == use_nodbg_end();
540   }
541
542   /// hasOneNonDBGUse - Return true if there is exactly one non-Debug
543   /// instruction using the specified register.
544   bool hasOneNonDBGUse(unsigned RegNo) const;
545
546   /// replaceRegWith - Replace all instances of FromReg with ToReg in the
547   /// machine function.  This is like llvm-level X->replaceAllUsesWith(Y),
548   /// except that it also changes any definitions of the register as well.
549   ///
550   /// Note that it is usually necessary to first constrain ToReg's register
551   /// class to match the FromReg constraints using:
552   ///
553   ///   constrainRegClass(ToReg, getRegClass(FromReg))
554   ///
555   /// That function will return NULL if the virtual registers have incompatible
556   /// constraints.
557   ///
558   /// Note that if ToReg is a physical register the function will replace and
559   /// apply sub registers to ToReg in order to obtain a final/proper physical
560   /// register.
561   void replaceRegWith(unsigned FromReg, unsigned ToReg);
562
563   /// getVRegDef - Return the machine instr that defines the specified virtual
564   /// register or null if none is found.  This assumes that the code is in SSA
565   /// form, so there should only be one definition.
566   MachineInstr *getVRegDef(unsigned Reg) const;
567
568   /// getUniqueVRegDef - Return the unique machine instr that defines the
569   /// specified virtual register or null if none is found.  If there are
570   /// multiple definitions or no definition, return null.
571   MachineInstr *getUniqueVRegDef(unsigned Reg) const;
572
573   /// clearKillFlags - Iterate over all the uses of the given register and
574   /// clear the kill flag from the MachineOperand. This function is used by
575   /// optimization passes which extend register lifetimes and need only
576   /// preserve conservative kill flag information.
577   void clearKillFlags(unsigned Reg) const;
578
579   void dumpUses(unsigned RegNo) const;
580
581   /// Returns true if PhysReg is unallocatable and constant throughout the
582   /// function. Writing to a constant register has no effect.
583   bool isConstantPhysReg(unsigned PhysReg) const;
584
585   /// Returns true if either isConstantPhysReg or TRI->isCallerPreservedPhysReg
586   /// returns true. This is a utility member function.
587   bool isCallerPreservedOrConstPhysReg(unsigned PhysReg) const;
588
589   /// Get an iterator over the pressure sets affected by the given physical or
590   /// virtual register. If RegUnit is physical, it must be a register unit (from
591   /// MCRegUnitIterator).
592   PSetIterator getPressureSets(unsigned RegUnit) const;
593
594   //===--------------------------------------------------------------------===//
595   // Virtual Register Info
596   //===--------------------------------------------------------------------===//
597
598   /// Return the register class of the specified virtual register.
599   /// This shouldn't be used directly unless \p Reg has a register class.
600   /// \see getRegClassOrNull when this might happen.
601   const TargetRegisterClass *getRegClass(unsigned Reg) const {
602     assert(VRegInfo[Reg].first.is<const TargetRegisterClass *>() &&
603            "Register class not set, wrong accessor");
604     return VRegInfo[Reg].first.get<const TargetRegisterClass *>();
605   }
606
607   /// Return the register class of \p Reg, or null if Reg has not been assigned
608   /// a register class yet.
609   ///
610   /// \note A null register class can only happen when these two
611   /// conditions are met:
612   /// 1. Generic virtual registers are created.
613   /// 2. The machine function has not completely been through the
614   ///    instruction selection process.
615   /// None of this condition is possible without GlobalISel for now.
616   /// In other words, if GlobalISel is not used or if the query happens after
617   /// the select pass, using getRegClass is safe.
618   const TargetRegisterClass *getRegClassOrNull(unsigned Reg) const {
619     const RegClassOrRegBank &Val = VRegInfo[Reg].first;
620     return Val.dyn_cast<const TargetRegisterClass *>();
621   }
622
623   /// Return the register bank of \p Reg, or null if Reg has not been assigned
624   /// a register bank or has been assigned a register class.
625   /// \note It is possible to get the register bank from the register class via
626   /// RegisterBankInfo::getRegBankFromRegClass.
627   const RegisterBank *getRegBankOrNull(unsigned Reg) const {
628     const RegClassOrRegBank &Val = VRegInfo[Reg].first;
629     return Val.dyn_cast<const RegisterBank *>();
630   }
631
632   /// Return the register bank or register class of \p Reg.
633   /// \note Before the register bank gets assigned (i.e., before the
634   /// RegBankSelect pass) \p Reg may not have either.
635   const RegClassOrRegBank &getRegClassOrRegBank(unsigned Reg) const {
636     return VRegInfo[Reg].first;
637   }
638
639   /// setRegClass - Set the register class of the specified virtual register.
640   void setRegClass(unsigned Reg, const TargetRegisterClass *RC);
641
642   /// Set the register bank to \p RegBank for \p Reg.
643   void setRegBank(unsigned Reg, const RegisterBank &RegBank);
644
645   void setRegClassOrRegBank(unsigned Reg,
646                             const RegClassOrRegBank &RCOrRB){
647     VRegInfo[Reg].first = RCOrRB;
648   }
649
650   /// constrainRegClass - Constrain the register class of the specified virtual
651   /// register to be a common subclass of RC and the current register class,
652   /// but only if the new class has at least MinNumRegs registers.  Return the
653   /// new register class, or NULL if no such class exists.
654   /// This should only be used when the constraint is known to be trivial, like
655   /// GR32 -> GR32_NOSP. Beware of increasing register pressure.
656   const TargetRegisterClass *constrainRegClass(unsigned Reg,
657                                                const TargetRegisterClass *RC,
658                                                unsigned MinNumRegs = 0);
659
660   /// recomputeRegClass - Try to find a legal super-class of Reg's register
661   /// class that still satisfies the constraints from the instructions using
662   /// Reg.  Returns true if Reg was upgraded.
663   ///
664   /// This method can be used after constraints have been removed from a
665   /// virtual register, for example after removing instructions or splitting
666   /// the live range.
667   bool recomputeRegClass(unsigned Reg);
668
669   /// createVirtualRegister - Create and return a new virtual register in the
670   /// function with the specified register class.
671   unsigned createVirtualRegister(const TargetRegisterClass *RegClass);
672
673   /// Accessor for VRegToType. This accessor should only be used
674   /// by global-isel related work.
675   VRegToTypeMap &getVRegToType() const {
676     if (!VRegToType)
677       VRegToType.reset(new VRegToTypeMap);
678     return *VRegToType.get();
679   }
680
681   /// Get the low-level type of \p VReg or LLT{} if VReg is not a generic
682   /// (target independent) virtual register.
683   LLT getType(unsigned VReg) const;
684
685   /// Set the low-level type of \p VReg to \p Ty.
686   void setType(unsigned VReg, LLT Ty);
687
688   /// Create and return a new generic virtual register with low-level
689   /// type \p Ty.
690   unsigned createGenericVirtualRegister(LLT Ty);
691
692   /// Remove all types associated to virtual registers (after instruction
693   /// selection and constraining of all generic virtual registers).
694   void clearVirtRegTypes();
695
696   /// Creates a new virtual register that has no register class, register bank
697   /// or size assigned yet. This is only allowed to be used
698   /// temporarily while constructing machine instructions. Most operations are
699   /// undefined on an incomplete register until one of setRegClass(),
700   /// setRegBank() or setSize() has been called on it.
701   unsigned createIncompleteVirtualRegister();
702
703   /// getNumVirtRegs - Return the number of virtual registers created.
704   unsigned getNumVirtRegs() const { return VRegInfo.size(); }
705
706   /// clearVirtRegs - Remove all virtual registers (after physreg assignment).
707   void clearVirtRegs();
708
709   /// setRegAllocationHint - Specify a register allocation hint for the
710   /// specified virtual register. This is typically used by target, and in case
711   /// of an earlier hint it will be overwritten.
712   void setRegAllocationHint(unsigned VReg, unsigned Type, unsigned PrefReg) {
713     assert(TargetRegisterInfo::isVirtualRegister(VReg));
714     RegAllocHints[VReg].first  = Type;
715     RegAllocHints[VReg].second.clear();
716     RegAllocHints[VReg].second.push_back(PrefReg);
717   }
718
719   /// addRegAllocationHint - Add a register allocation hint to the hints
720   /// vector for VReg.
721   void addRegAllocationHint(unsigned VReg, unsigned PrefReg) {
722     assert(TargetRegisterInfo::isVirtualRegister(VReg));
723     RegAllocHints[VReg].second.push_back(PrefReg);
724   }
725
726   /// Specify the preferred (target independent) register allocation hint for
727   /// the specified virtual register.
728   void setSimpleHint(unsigned VReg, unsigned PrefReg) {
729     setRegAllocationHint(VReg, /*Type=*/0, PrefReg);
730   }
731
732   void clearSimpleHint(unsigned VReg) {
733     assert (RegAllocHints[VReg].first == 0 &&
734             "Expected to clear a non-target hint!");
735     RegAllocHints[VReg].second.clear();
736   }
737
738   /// getRegAllocationHint - Return the register allocation hint for the
739   /// specified virtual register. If there are many hints, this returns the
740   /// one with the greatest weight.
741   std::pair<unsigned, unsigned>
742   getRegAllocationHint(unsigned VReg) const {
743     assert(TargetRegisterInfo::isVirtualRegister(VReg));
744     unsigned BestHint = (RegAllocHints[VReg].second.size() ?
745                          RegAllocHints[VReg].second[0] : 0);
746     return std::pair<unsigned, unsigned>(RegAllocHints[VReg].first, BestHint);
747   }
748
749   /// getSimpleHint - same as getRegAllocationHint except it will only return
750   /// a target independent hint.
751   unsigned getSimpleHint(unsigned VReg) const {
752     assert(TargetRegisterInfo::isVirtualRegister(VReg));
753     std::pair<unsigned, unsigned> Hint = getRegAllocationHint(VReg);
754     return Hint.first ? 0 : Hint.second;
755   }
756
757   /// getRegAllocationHints - Return a reference to the vector of all
758   /// register allocation hints for VReg.
759   const std::pair<unsigned, SmallVector<unsigned, 4>>
760   &getRegAllocationHints(unsigned VReg) const {
761     assert(TargetRegisterInfo::isVirtualRegister(VReg));
762     return RegAllocHints[VReg];
763   }
764
765   /// markUsesInDebugValueAsUndef - Mark every DBG_VALUE referencing the
766   /// specified register as undefined which causes the DBG_VALUE to be
767   /// deleted during LiveDebugVariables analysis.
768   void markUsesInDebugValueAsUndef(unsigned Reg) const;
769
770   /// Return true if the specified register is modified in this function.
771   /// This checks that no defining machine operands exist for the register or
772   /// any of its aliases. Definitions found on functions marked noreturn are
773   /// ignored, to consider them pass 'true' for optional parameter
774   /// SkipNoReturnDef. The register is also considered modified when it is set
775   /// in the UsedPhysRegMask.
776   bool isPhysRegModified(unsigned PhysReg, bool SkipNoReturnDef = false) const;
777
778   /// Return true if the specified register is modified or read in this
779   /// function. This checks that no machine operands exist for the register or
780   /// any of its aliases. The register is also considered used when it is set
781   /// in the UsedPhysRegMask.
782   bool isPhysRegUsed(unsigned PhysReg) const;
783
784   /// addPhysRegsUsedFromRegMask - Mark any registers not in RegMask as used.
785   /// This corresponds to the bit mask attached to register mask operands.
786   void addPhysRegsUsedFromRegMask(const uint32_t *RegMask) {
787     UsedPhysRegMask.setBitsNotInMask(RegMask);
788   }
789
790   const BitVector &getUsedPhysRegsMask() const { return UsedPhysRegMask; }
791
792   //===--------------------------------------------------------------------===//
793   // Reserved Register Info
794   //===--------------------------------------------------------------------===//
795   //
796   // The set of reserved registers must be invariant during register
797   // allocation.  For example, the target cannot suddenly decide it needs a
798   // frame pointer when the register allocator has already used the frame
799   // pointer register for something else.
800   //
801   // These methods can be used by target hooks like hasFP() to avoid changing
802   // the reserved register set during register allocation.
803
804   /// freezeReservedRegs - Called by the register allocator to freeze the set
805   /// of reserved registers before allocation begins.
806   void freezeReservedRegs(const MachineFunction&);
807
808   /// reservedRegsFrozen - Returns true after freezeReservedRegs() was called
809   /// to ensure the set of reserved registers stays constant.
810   bool reservedRegsFrozen() const {
811     return !ReservedRegs.empty();
812   }
813
814   /// canReserveReg - Returns true if PhysReg can be used as a reserved
815   /// register.  Any register can be reserved before freezeReservedRegs() is
816   /// called.
817   bool canReserveReg(unsigned PhysReg) const {
818     return !reservedRegsFrozen() || ReservedRegs.test(PhysReg);
819   }
820
821   /// getReservedRegs - Returns a reference to the frozen set of reserved
822   /// registers. This method should always be preferred to calling
823   /// TRI::getReservedRegs() when possible.
824   const BitVector &getReservedRegs() const {
825     assert(reservedRegsFrozen() &&
826            "Reserved registers haven't been frozen yet. "
827            "Use TRI::getReservedRegs().");
828     return ReservedRegs;
829   }
830
831   /// isReserved - Returns true when PhysReg is a reserved register.
832   ///
833   /// Reserved registers may belong to an allocatable register class, but the
834   /// target has explicitly requested that they are not used.
835   bool isReserved(unsigned PhysReg) const {
836     return getReservedRegs().test(PhysReg);
837   }
838
839   /// Returns true when the given register unit is considered reserved.
840   ///
841   /// Register units are considered reserved when for at least one of their
842   /// root registers, the root register and all super registers are reserved.
843   /// This currently iterates the register hierarchy and may be slower than
844   /// expected.
845   bool isReservedRegUnit(unsigned Unit) const;
846
847   /// isAllocatable - Returns true when PhysReg belongs to an allocatable
848   /// register class and it hasn't been reserved.
849   ///
850   /// Allocatable registers may show up in the allocation order of some virtual
851   /// register, so a register allocator needs to track its liveness and
852   /// availability.
853   bool isAllocatable(unsigned PhysReg) const {
854     return getTargetRegisterInfo()->isInAllocatableClass(PhysReg) &&
855       !isReserved(PhysReg);
856   }
857
858   //===--------------------------------------------------------------------===//
859   // LiveIn Management
860   //===--------------------------------------------------------------------===//
861
862   /// addLiveIn - Add the specified register as a live-in.  Note that it
863   /// is an error to add the same register to the same set more than once.
864   void addLiveIn(unsigned Reg, unsigned vreg = 0) {
865     LiveIns.push_back(std::make_pair(Reg, vreg));
866   }
867
868   // Iteration support for the live-ins set.  It's kept in sorted order
869   // by register number.
870   using livein_iterator =
871       std::vector<std::pair<unsigned,unsigned>>::const_iterator;
872   livein_iterator livein_begin() const { return LiveIns.begin(); }
873   livein_iterator livein_end()   const { return LiveIns.end(); }
874   bool            livein_empty() const { return LiveIns.empty(); }
875
876   ArrayRef<std::pair<unsigned, unsigned>> liveins() const {
877     return LiveIns;
878   }
879
880   bool isLiveIn(unsigned Reg) const;
881
882   /// getLiveInPhysReg - If VReg is a live-in virtual register, return the
883   /// corresponding live-in physical register.
884   unsigned getLiveInPhysReg(unsigned VReg) const;
885
886   /// getLiveInVirtReg - If PReg is a live-in physical register, return the
887   /// corresponding live-in physical register.
888   unsigned getLiveInVirtReg(unsigned PReg) const;
889
890   /// EmitLiveInCopies - Emit copies to initialize livein virtual registers
891   /// into the given entry block.
892   void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
893                         const TargetRegisterInfo &TRI,
894                         const TargetInstrInfo &TII);
895
896   /// Returns a mask covering all bits that can appear in lane masks of
897   /// subregisters of the virtual register @p Reg.
898   LaneBitmask getMaxLaneMaskForVReg(unsigned Reg) const;
899
900   /// defusechain_iterator - This class provides iterator support for machine
901   /// operands in the function that use or define a specific register.  If
902   /// ReturnUses is true it returns uses of registers, if ReturnDefs is true it
903   /// returns defs.  If neither are true then you are silly and it always
904   /// returns end().  If SkipDebug is true it skips uses marked Debug
905   /// when incrementing.
906   template<bool ReturnUses, bool ReturnDefs, bool SkipDebug,
907            bool ByOperand, bool ByInstr, bool ByBundle>
908   class defusechain_iterator
909     : public std::iterator<std::forward_iterator_tag, MachineInstr, ptrdiff_t> {
910     friend class MachineRegisterInfo;
911
912     MachineOperand *Op = nullptr;
913
914     explicit defusechain_iterator(MachineOperand *op) : Op(op) {
915       // If the first node isn't one we're interested in, advance to one that
916       // we are interested in.
917       if (op) {
918         if ((!ReturnUses && op->isUse()) ||
919             (!ReturnDefs && op->isDef()) ||
920             (SkipDebug && op->isDebug()))
921           advance();
922       }
923     }
924
925     void advance() {
926       assert(Op && "Cannot increment end iterator!");
927       Op = getNextOperandForReg(Op);
928
929       // All defs come before the uses, so stop def_iterator early.
930       if (!ReturnUses) {
931         if (Op) {
932           if (Op->isUse())
933             Op = nullptr;
934           else
935             assert(!Op->isDebug() && "Can't have debug defs");
936         }
937       } else {
938         // If this is an operand we don't care about, skip it.
939         while (Op && ((!ReturnDefs && Op->isDef()) ||
940                       (SkipDebug && Op->isDebug())))
941           Op = getNextOperandForReg(Op);
942       }
943     }
944
945   public:
946     using reference = std::iterator<std::forward_iterator_tag,
947                                     MachineInstr, ptrdiff_t>::reference;
948     using pointer = std::iterator<std::forward_iterator_tag,
949                                   MachineInstr, ptrdiff_t>::pointer;
950
951     defusechain_iterator() = default;
952
953     bool operator==(const defusechain_iterator &x) const {
954       return Op == x.Op;
955     }
956     bool operator!=(const defusechain_iterator &x) const {
957       return !operator==(x);
958     }
959
960     /// atEnd - return true if this iterator is equal to reg_end() on the value.
961     bool atEnd() const { return Op == nullptr; }
962
963     // Iterator traversal: forward iteration only
964     defusechain_iterator &operator++() {          // Preincrement
965       assert(Op && "Cannot increment end iterator!");
966       if (ByOperand)
967         advance();
968       else if (ByInstr) {
969         MachineInstr *P = Op->getParent();
970         do {
971           advance();
972         } while (Op && Op->getParent() == P);
973       } else if (ByBundle) {
974         MachineBasicBlock::instr_iterator P =
975             getBundleStart(Op->getParent()->getIterator());
976         do {
977           advance();
978         } while (Op && getBundleStart(Op->getParent()->getIterator()) == P);
979       }
980
981       return *this;
982     }
983     defusechain_iterator operator++(int) {        // Postincrement
984       defusechain_iterator tmp = *this; ++*this; return tmp;
985     }
986
987     /// getOperandNo - Return the operand # of this MachineOperand in its
988     /// MachineInstr.
989     unsigned getOperandNo() const {
990       assert(Op && "Cannot dereference end iterator!");
991       return Op - &Op->getParent()->getOperand(0);
992     }
993
994     // Retrieve a reference to the current operand.
995     MachineOperand &operator*() const {
996       assert(Op && "Cannot dereference end iterator!");
997       return *Op;
998     }
999
1000     MachineOperand *operator->() const {
1001       assert(Op && "Cannot dereference end iterator!");
1002       return Op;
1003     }
1004   };
1005
1006   /// defusechain_iterator - This class provides iterator support for machine
1007   /// operands in the function that use or define a specific register.  If
1008   /// ReturnUses is true it returns uses of registers, if ReturnDefs is true it
1009   /// returns defs.  If neither are true then you are silly and it always
1010   /// returns end().  If SkipDebug is true it skips uses marked Debug
1011   /// when incrementing.
1012   template<bool ReturnUses, bool ReturnDefs, bool SkipDebug,
1013            bool ByOperand, bool ByInstr, bool ByBundle>
1014   class defusechain_instr_iterator
1015     : public std::iterator<std::forward_iterator_tag, MachineInstr, ptrdiff_t> {
1016     friend class MachineRegisterInfo;
1017
1018     MachineOperand *Op = nullptr;
1019
1020     explicit defusechain_instr_iterator(MachineOperand *op) : Op(op) {
1021       // If the first node isn't one we're interested in, advance to one that
1022       // we are interested in.
1023       if (op) {
1024         if ((!ReturnUses && op->isUse()) ||
1025             (!ReturnDefs && op->isDef()) ||
1026             (SkipDebug && op->isDebug()))
1027           advance();
1028       }
1029     }
1030
1031     void advance() {
1032       assert(Op && "Cannot increment end iterator!");
1033       Op = getNextOperandForReg(Op);
1034
1035       // All defs come before the uses, so stop def_iterator early.
1036       if (!ReturnUses) {
1037         if (Op) {
1038           if (Op->isUse())
1039             Op = nullptr;
1040           else
1041             assert(!Op->isDebug() && "Can't have debug defs");
1042         }
1043       } else {
1044         // If this is an operand we don't care about, skip it.
1045         while (Op && ((!ReturnDefs && Op->isDef()) ||
1046                       (SkipDebug && Op->isDebug())))
1047           Op = getNextOperandForReg(Op);
1048       }
1049     }
1050
1051   public:
1052     using reference = std::iterator<std::forward_iterator_tag,
1053                                     MachineInstr, ptrdiff_t>::reference;
1054     using pointer = std::iterator<std::forward_iterator_tag,
1055                                   MachineInstr, ptrdiff_t>::pointer;
1056
1057     defusechain_instr_iterator() = default;
1058
1059     bool operator==(const defusechain_instr_iterator &x) const {
1060       return Op == x.Op;
1061     }
1062     bool operator!=(const defusechain_instr_iterator &x) const {
1063       return !operator==(x);
1064     }
1065
1066     /// atEnd - return true if this iterator is equal to reg_end() on the value.
1067     bool atEnd() const { return Op == nullptr; }
1068
1069     // Iterator traversal: forward iteration only
1070     defusechain_instr_iterator &operator++() {          // Preincrement
1071       assert(Op && "Cannot increment end iterator!");
1072       if (ByOperand)
1073         advance();
1074       else if (ByInstr) {
1075         MachineInstr *P = Op->getParent();
1076         do {
1077           advance();
1078         } while (Op && Op->getParent() == P);
1079       } else if (ByBundle) {
1080         MachineBasicBlock::instr_iterator P =
1081             getBundleStart(Op->getParent()->getIterator());
1082         do {
1083           advance();
1084         } while (Op && getBundleStart(Op->getParent()->getIterator()) == P);
1085       }
1086
1087       return *this;
1088     }
1089     defusechain_instr_iterator operator++(int) {        // Postincrement
1090       defusechain_instr_iterator tmp = *this; ++*this; return tmp;
1091     }
1092
1093     // Retrieve a reference to the current operand.
1094     MachineInstr &operator*() const {
1095       assert(Op && "Cannot dereference end iterator!");
1096       if (ByBundle)
1097         return *getBundleStart(Op->getParent()->getIterator());
1098       return *Op->getParent();
1099     }
1100
1101     MachineInstr *operator->() const { return &operator*(); }
1102   };
1103 };
1104
1105 /// Iterate over the pressure sets affected by the given physical or virtual
1106 /// register. If Reg is physical, it must be a register unit (from
1107 /// MCRegUnitIterator).
1108 class PSetIterator {
1109   const int *PSet = nullptr;
1110   unsigned Weight = 0;
1111
1112 public:
1113   PSetIterator() = default;
1114
1115   PSetIterator(unsigned RegUnit, const MachineRegisterInfo *MRI) {
1116     const TargetRegisterInfo *TRI = MRI->getTargetRegisterInfo();
1117     if (TargetRegisterInfo::isVirtualRegister(RegUnit)) {
1118       const TargetRegisterClass *RC = MRI->getRegClass(RegUnit);
1119       PSet = TRI->getRegClassPressureSets(RC);
1120       Weight = TRI->getRegClassWeight(RC).RegWeight;
1121     }
1122     else {
1123       PSet = TRI->getRegUnitPressureSets(RegUnit);
1124       Weight = TRI->getRegUnitWeight(RegUnit);
1125     }
1126     if (*PSet == -1)
1127       PSet = nullptr;
1128   }
1129
1130   bool isValid() const { return PSet; }
1131
1132   unsigned getWeight() const { return Weight; }
1133
1134   unsigned operator*() const { return *PSet; }
1135
1136   void operator++() {
1137     assert(isValid() && "Invalid PSetIterator.");
1138     ++PSet;
1139     if (*PSet == -1)
1140       PSet = nullptr;
1141   }
1142 };
1143
1144 inline PSetIterator MachineRegisterInfo::
1145 getPressureSets(unsigned RegUnit) const {
1146   return PSetIterator(RegUnit, this);
1147 }
1148
1149 } // end namespace llvm
1150
1151 #endif // LLVM_CODEGEN_MACHINEREGISTERINFO_H