1 //===- llvm/CodeGen/MachineFunction.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 // Collect native machine code for a function.  This class contains a list of
11 // MachineBasicBlock instances that make up the current compiled function.
12 //
13 // This class also contains pointers to various classes which hold
14 // target-specific information about the generated code.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #ifndef LLVM_CODEGEN_MACHINEFUNCTION_H
19 #define LLVM_CODEGEN_MACHINEFUNCTION_H
20 
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/BitVector.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/GraphTraits.h"
25 #include "llvm/ADT/Optional.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/ilist.h"
29 #include "llvm/ADT/iterator.h"
30 #include "llvm/Analysis/EHPersonalities.h"
31 #include "llvm/CodeGen/MachineBasicBlock.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineMemOperand.h"
34 #include "llvm/IR/DebugLoc.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Metadata.h"
37 #include "llvm/MC/MCDwarf.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Support/Allocator.h"
40 #include "llvm/Support/ArrayRecycler.h"
41 #include "llvm/Support/AtomicOrdering.h"
42 #include "llvm/Support/Compiler.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/Recycler.h"
45 #include <cassert>
46 #include <cstdint>
47 #include <memory>
48 #include <utility>
49 #include <vector>
50 
51 namespace llvm {
52 
53 class BasicBlock;
54 class BlockAddress;
55 class DataLayout;
56 class DIExpression;
57 class DILocalVariable;
58 class DILocation;
59 class Function;
60 class GlobalValue;
61 class LLVMTargetMachine;
62 class MachineConstantPool;
63 class MachineFrameInfo;
64 class MachineFunction;
65 class MachineJumpTableInfo;
66 class MachineModuleInfo;
67 class MachineRegisterInfo;
68 class MCContext;
69 class MCInstrDesc;
70 class Pass;
71 class PseudoSourceValueManager;
72 class raw_ostream;
73 class SlotIndexes;
74 class TargetRegisterClass;
75 class TargetSubtargetInfo;
76 struct WasmEHFuncInfo;
77 struct WinEHFuncInfo;
78 
79 template <> struct ilist_alloc_traits<MachineBasicBlock> {
80   void deleteNode(MachineBasicBlock *MBB);
81 };
82 
83 template <> struct ilist_callback_traits<MachineBasicBlock> {
84   void addNodeToList(MachineBasicBlock* N);
85   void removeNodeFromList(MachineBasicBlock* N);
86 
87   template <class Iterator>
88   void transferNodesFromList(ilist_callback_traits &OldList, Iterator, Iterator) {
89     llvm_unreachable("Never transfer between lists");
90   }
91 };
92 
93 /// MachineFunctionInfo - This class can be derived from and used by targets to
94 /// hold private target-specific information for each MachineFunction.  Objects
95 /// of type are accessed/created with MF::getInfo and destroyed when the
96 /// MachineFunction is destroyed.
97 struct MachineFunctionInfo {
98   virtual ~MachineFunctionInfo();
99 
100   /// Factory function: default behavior is to call new using the
101   /// supplied allocator.
102   ///
103   /// This function can be overridden in a derive class.
104   template<typename Ty>
105   static Ty *create(BumpPtrAllocator &Allocator, MachineFunction &MF) {
106     return new (Allocator.Allocate<Ty>()) Ty(MF);
107   }
108 };
109 
110 /// Properties which a MachineFunction may have at a given point in time.
111 /// Each of these has checking code in the MachineVerifier, and passes can
112 /// require that a property be set.
113 class MachineFunctionProperties {
114   // Possible TODO: Allow targets to extend this (perhaps by allowing the
115   // constructor to specify the size of the bit vector)
116   // Possible TODO: Allow requiring the negative (e.g. VRegsAllocated could be
117   // stated as the negative of "has vregs"
118 
119 public:
120   // The properties are stated in "positive" form; i.e. a pass could require
121   // that the property hold, but not that it does not hold.
122 
123   // Property descriptions:
124   // IsSSA: True when the machine function is in SSA form and virtual registers
125   //  have a single def.
126   // NoPHIs: The machine function does not contain any PHI instruction.
127   // TracksLiveness: True when tracking register liveness accurately.
128   //  While this property is set, register liveness information in basic block
129   //  live-in lists and machine instruction operands (e.g. kill flags, implicit
130   //  defs) is accurate. This means it can be used to change the code in ways
131   //  that affect the values in registers, for example by the register
132   //  scavenger.
133   //  When this property is clear, liveness is no longer reliable.
134   // NoVRegs: The machine function does not use any virtual registers.
135   // Legalized: In GlobalISel: the MachineLegalizer ran and all pre-isel generic
136   //  instructions have been legalized; i.e., all instructions are now one of:
137   //   - generic and always legal (e.g., COPY)
138   //   - target-specific
139   //   - legal pre-isel generic instructions.
140   // RegBankSelected: In GlobalISel: the RegBankSelect pass ran and all generic
141   //  virtual registers have been assigned to a register bank.
142   // Selected: In GlobalISel: the InstructionSelect pass ran and all pre-isel
143   //  generic instructions have been eliminated; i.e., all instructions are now
144   //  target-specific or non-pre-isel generic instructions (e.g., COPY).
145   //  Since only pre-isel generic instructions can have generic virtual register
146   //  operands, this also means that all generic virtual registers have been
147   //  constrained to virtual registers (assigned to register classes) and that
148   //  all sizes attached to them have been eliminated.
149   enum class Property : unsigned {
150     IsSSA,
151     NoPHIs,
152     TracksLiveness,
153     NoVRegs,
154     FailedISel,
155     Legalized,
156     RegBankSelected,
157     Selected,
158     LastProperty = Selected,
159   };
160 
161   bool hasProperty(Property P) const {
162     return Properties[static_cast<unsigned>(P)];
163   }
164 
165   MachineFunctionProperties &set(Property P) {
166     Properties.set(static_cast<unsigned>(P));
167     return *this;
168   }
169 
170   MachineFunctionProperties &reset(Property P) {
171     Properties.reset(static_cast<unsigned>(P));
172     return *this;
173   }
174 
175   /// Reset all the properties.
176   MachineFunctionProperties &reset() {
177     Properties.reset();
178     return *this;
179   }
180 
181   MachineFunctionProperties &set(const MachineFunctionProperties &MFP) {
182     Properties |= MFP.Properties;
183     return *this;
184   }
185 
186   MachineFunctionProperties &reset(const MachineFunctionProperties &MFP) {
187     Properties.reset(MFP.Properties);
188     return *this;
189   }
190 
191   // Returns true if all properties set in V (i.e. required by a pass) are set
192   // in this.
193   bool verifyRequiredProperties(const MachineFunctionProperties &V) const {
194     return !V.Properties.test(Properties);
195   }
196 
197   /// Print the MachineFunctionProperties in human-readable form.
198   void print(raw_ostream &OS) const;
199 
200 private:
201   BitVector Properties =
202       BitVector(static_cast<unsigned>(Property::LastProperty)+1);
203 };
204 
205 struct SEHHandler {
206   /// Filter or finally function. Null indicates a catch-all.
207   const Function *FilterOrFinally;
208 
209   /// Address of block to recover at. Null for a finally handler.
210   const BlockAddress *RecoverBA;
211 };
212 
213 /// This structure is used to retain landing pad info for the current function.
214 struct LandingPadInfo {
215   MachineBasicBlock *LandingPadBlock;      // Landing pad block.
216   SmallVector<MCSymbol *, 1> BeginLabels;  // Labels prior to invoke.
217   SmallVector<MCSymbol *, 1> EndLabels;    // Labels after invoke.
218   SmallVector<SEHHandler, 1> SEHHandlers;  // SEH handlers active at this lpad.
219   MCSymbol *LandingPadLabel = nullptr;     // Label at beginning of landing pad.
220   std::vector<int> TypeIds;                // List of type ids (filters negative).
221 
222   explicit LandingPadInfo(MachineBasicBlock *MBB)
223       : LandingPadBlock(MBB) {}
224 };
225 
226 class MachineFunction {
227   const Function &F;
228   const LLVMTargetMachine &Target;
229   const TargetSubtargetInfo *STI;
230   MCContext &Ctx;
231   MachineModuleInfo &MMI;
232 
233   // RegInfo - Information about each register in use in the function.
234   MachineRegisterInfo *RegInfo;
235 
236   // Used to keep track of target-specific per-machine function information for
237   // the target implementation.
238   MachineFunctionInfo *MFInfo;
239 
240   // Keep track of objects allocated on the stack.
241   MachineFrameInfo *FrameInfo;
242 
243   // Keep track of constants which are spilled to memory
244   MachineConstantPool *ConstantPool;
245 
246   // Keep track of jump tables for switch instructions
247   MachineJumpTableInfo *JumpTableInfo;
248 
249   // Keeps track of Wasm exception handling related data. This will be null for
250   // functions that aren't using a wasm EH personality.
251   WasmEHFuncInfo *WasmEHInfo = nullptr;
252 
253   // Keeps track of Windows exception handling related data. This will be null
254   // for functions that aren't using a funclet-based EH personality.
255   WinEHFuncInfo *WinEHInfo = nullptr;
256 
257   // Function-level unique numbering for MachineBasicBlocks.  When a
258   // MachineBasicBlock is inserted into a MachineFunction is it automatically
259   // numbered and this vector keeps track of the mapping from ID's to MBB's.
260   std::vector<MachineBasicBlock*> MBBNumbering;
261 
262   // Pool-allocate MachineFunction-lifetime and IR objects.
263   BumpPtrAllocator Allocator;
264 
265   // Allocation management for instructions in function.
266   Recycler<MachineInstr> InstructionRecycler;
267 
268   // Allocation management for operand arrays on instructions.
269   ArrayRecycler<MachineOperand> OperandRecycler;
270 
271   // Allocation management for basic blocks in function.
272   Recycler<MachineBasicBlock> BasicBlockRecycler;
273 
274   // List of machine basic blocks in function
275   using BasicBlockListType = ilist<MachineBasicBlock>;
276   BasicBlockListType BasicBlocks;
277 
278   /// FunctionNumber - This provides a unique ID for each function emitted in
279   /// this translation unit.
280   ///
281   unsigned FunctionNumber;
282 
283   /// Alignment - The alignment of the function.
284   unsigned Alignment;
285 
286   /// ExposesReturnsTwice - True if the function calls setjmp or related
287   /// functions with attribute "returns twice", but doesn't have
288   /// the attribute itself.
289   /// This is used to limit optimizations which cannot reason
290   /// about the control flow of such functions.
291   bool ExposesReturnsTwice = false;
292 
293   /// True if the function includes any inline assembly.
294   bool HasInlineAsm = false;
295 
296   /// True if any WinCFI instruction have been emitted in this function.
297   bool HasWinCFI = false;
298 
299   /// Current high-level properties of the IR of the function (e.g. is in SSA
300   /// form or whether registers have been allocated)
301   MachineFunctionProperties Properties;
302 
303   // Allocation management for pseudo source values.
304   std::unique_ptr<PseudoSourceValueManager> PSVManager;
305 
306   /// List of moves done by a function's prolog.  Used to construct frame maps
307   /// by debug and exception handling consumers.
308   std::vector<MCCFIInstruction> FrameInstructions;
309 
310   /// \name Exception Handling
311   /// \{
312 
313   /// List of LandingPadInfo describing the landing pad information.
314   std::vector<LandingPadInfo> LandingPads;
315 
316   /// Map a landing pad's EH symbol to the call site indexes.
317   DenseMap<MCSymbol*, SmallVector<unsigned, 4>> LPadToCallSiteMap;
318 
319   /// Map a landing pad to its index.
320   DenseMap<const MachineBasicBlock *, unsigned> WasmLPadToIndexMap;
321 
322   /// Map of invoke call site index values to associated begin EH_LABEL.
323   DenseMap<MCSymbol*, unsigned> CallSiteMap;
324 
325   /// CodeView label annotations.
326   std::vector<std::pair<MCSymbol *, MDNode *>> CodeViewAnnotations;
327 
328   bool CallsEHReturn = false;
329   bool CallsUnwindInit = false;
330   bool HasEHScopes = false;
331   bool HasEHFunclets = false;
332   bool HasLocalEscape = false;
333 
334   /// List of C++ TypeInfo used.
335   std::vector<const GlobalValue *> TypeInfos;
336 
337   /// List of typeids encoding filters used.
338   std::vector<unsigned> FilterIds;
339 
340   /// List of the indices in FilterIds corresponding to filter terminators.
341   std::vector<unsigned> FilterEnds;
342 
343   EHPersonality PersonalityTypeCache = EHPersonality::Unknown;
344 
345   /// \}
346 
347   /// Clear all the members of this MachineFunction, but the ones used
348   /// to initialize again the MachineFunction.
349   /// More specifically, this deallocates all the dynamically allocated
350   /// objects and get rid of all the XXXInfo data structure, but keep
351   /// unchanged the references to Fn, Target, MMI, and FunctionNumber.
352   void clear();
353   /// Allocate and initialize the different members.
354   /// In particular, the XXXInfo data structure.
355   /// \pre Fn, Target, MMI, and FunctionNumber are properly set.
356   void init();
357 
358 public:
359   struct VariableDbgInfo {
360     const DILocalVariable *Var;
361     const DIExpression *Expr;
362     // The Slot can be negative for fixed stack objects.
363     int Slot;
364     const DILocation *Loc;
365 
366     VariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr,
367                     int Slot, const DILocation *Loc)
368         : Var(Var), Expr(Expr), Slot(Slot), Loc(Loc) {}
369   };
370 
371   class Delegate {
372     virtual void anchor();
373 
374   public:
375     virtual ~Delegate() = default;
376     /// Callback after an insertion. This should not modify the MI directly.
377     virtual void MF_HandleInsertion(MachineInstr &MI) = 0;
378     /// Callback before a removal. This should not modify the MI directly.
379     virtual void MF_HandleRemoval(MachineInstr &MI) = 0;
380   };
381 
382 private:
383   Delegate *TheDelegate = nullptr;
384 
385   // Callbacks for insertion and removal.
386   void handleInsertion(MachineInstr &MI);
387   void handleRemoval(MachineInstr &MI);
388   friend struct ilist_traits<MachineInstr>;
389 
390 public:
391   using VariableDbgInfoMapTy = SmallVector<VariableDbgInfo, 4>;
392   VariableDbgInfoMapTy VariableDbgInfos;
393 
394   MachineFunction(const Function &F, const LLVMTargetMachine &Target,
395                   const TargetSubtargetInfo &STI, unsigned FunctionNum,
396                   MachineModuleInfo &MMI);
397   MachineFunction(const MachineFunction &) = delete;
398   MachineFunction &operator=(const MachineFunction &) = delete;
399   ~MachineFunction();
400 
401   /// Reset the instance as if it was just created.
402   void reset() {
403     clear();
404     init();
405   }
406 
407   /// Reset the currently registered delegate - otherwise assert.
408   void resetDelegate(Delegate *delegate) {
409     assert(TheDelegate == delegate &&
410            "Only the current delegate can perform reset!");
411     TheDelegate = nullptr;
412   }
413 
414   /// Set the delegate. resetDelegate must be called before attempting
415   /// to set.
416   void setDelegate(Delegate *delegate) {
417     assert(delegate && !TheDelegate &&
418            "Attempted to set delegate to null, or to change it without "
419            "first resetting it!");
420 
421     TheDelegate = delegate;
422   }
423 
424   MachineModuleInfo &getMMI() const { return MMI; }
425   MCContext &getContext() const { return Ctx; }
426 
427   PseudoSourceValueManager &getPSVManager() const { return *PSVManager; }
428 
429   /// Return the DataLayout attached to the Module associated to this MF.
430   const DataLayout &getDataLayout() const;
431 
432   /// Return the LLVM function that this machine code represents
433   const Function &getFunction() const { return F; }
434 
435   /// getName - Return the name of the corresponding LLVM function.
436   StringRef getName() const;
437 
438   /// getFunctionNumber - Return a unique ID for the current function.
439   unsigned getFunctionNumber() const { return FunctionNumber; }
440 
441   /// getTarget - Return the target machine this machine code is compiled with
442   const LLVMTargetMachine &getTarget() const { return Target; }
443 
444   /// getSubtarget - Return the subtarget for which this machine code is being
445   /// compiled.
446   const TargetSubtargetInfo &getSubtarget() const { return *STI; }
447   void setSubtarget(const TargetSubtargetInfo *ST) { STI = ST; }
448 
449   /// getSubtarget - This method returns a pointer to the specified type of
450   /// TargetSubtargetInfo.  In debug builds, it verifies that the object being
451   /// returned is of the correct type.
452   template<typename STC> const STC &getSubtarget() const {
453     return *static_cast<const STC *>(STI);
454   }
455 
456   /// getRegInfo - Return information about the registers currently in use.
457   MachineRegisterInfo &getRegInfo() { return *RegInfo; }
458   const MachineRegisterInfo &getRegInfo() const { return *RegInfo; }
459 
460   /// getFrameInfo - Return the frame info object for the current function.
461   /// This object contains information about objects allocated on the stack
462   /// frame of the current function in an abstract way.
463   MachineFrameInfo &getFrameInfo() { return *FrameInfo; }
464   const MachineFrameInfo &getFrameInfo() const { return *FrameInfo; }
465 
466   /// getJumpTableInfo - Return the jump table info object for the current
467   /// function.  This object contains information about jump tables in the
468   /// current function.  If the current function has no jump tables, this will
469   /// return null.
470   const MachineJumpTableInfo *getJumpTableInfo() const { return JumpTableInfo; }
471   MachineJumpTableInfo *getJumpTableInfo() { return JumpTableInfo; }
472 
473   /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
474   /// does already exist, allocate one.
475   MachineJumpTableInfo *getOrCreateJumpTableInfo(unsigned JTEntryKind);
476 
477   /// getConstantPool - Return the constant pool object for the current
478   /// function.
479   MachineConstantPool *getConstantPool() { return ConstantPool; }
480   const MachineConstantPool *getConstantPool() const { return ConstantPool; }
481 
482   /// getWasmEHFuncInfo - Return information about how the current function uses
483   /// Wasm exception handling. Returns null for functions that don't use wasm
484   /// exception handling.
485   const WasmEHFuncInfo *getWasmEHFuncInfo() const { return WasmEHInfo; }
486   WasmEHFuncInfo *getWasmEHFuncInfo() { return WasmEHInfo; }
487 
488   /// getWinEHFuncInfo - Return information about how the current function uses
489   /// Windows exception handling. Returns null for functions that don't use
490   /// funclets for exception handling.
491   const WinEHFuncInfo *getWinEHFuncInfo() const { return WinEHInfo; }
492   WinEHFuncInfo *getWinEHFuncInfo() { return WinEHInfo; }
493 
494   /// getAlignment - Return the alignment (log2, not bytes) of the function.
495   unsigned getAlignment() const { return Alignment; }
496 
497   /// setAlignment - Set the alignment (log2, not bytes) of the function.
498   void setAlignment(unsigned A) { Alignment = A; }
499 
500   /// ensureAlignment - Make sure the function is at least 1 << A bytes aligned.
501   void ensureAlignment(unsigned A) {
502     if (Alignment < A) Alignment = A;
503   }
504 
505   /// exposesReturnsTwice - Returns true if the function calls setjmp or
506   /// any other similar functions with attribute "returns twice" without
507   /// having the attribute itself.
508   bool exposesReturnsTwice() const {
509     return ExposesReturnsTwice;
510   }
511 
512   /// setCallsSetJmp - Set a flag that indicates if there's a call to
513   /// a "returns twice" function.
514   void setExposesReturnsTwice(bool B) {
515     ExposesReturnsTwice = B;
516   }
517 
518   /// Returns true if the function contains any inline assembly.
519   bool hasInlineAsm() const {
520     return HasInlineAsm;
521   }
522 
523   /// Set a flag that indicates that the function contains inline assembly.
524   void setHasInlineAsm(bool B) {
525     HasInlineAsm = B;
526   }
527 
528   bool hasWinCFI() const {
529     return HasWinCFI;
530   }
531   void setHasWinCFI(bool v) { HasWinCFI = v; }
532 
533   /// Get the function properties
534   const MachineFunctionProperties &getProperties() const { return Properties; }
535   MachineFunctionProperties &getProperties() { return Properties; }
536 
537   /// getInfo - Keep track of various per-function pieces of information for
538   /// backends that would like to do so.
539   ///
540   template<typename Ty>
541   Ty *getInfo() {
542     if (!MFInfo)
543       MFInfo = Ty::template create<Ty>(Allocator, *this);
544     return static_cast<Ty*>(MFInfo);
545   }
546 
547   template<typename Ty>
548   const Ty *getInfo() const {
549      return const_cast<MachineFunction*>(this)->getInfo<Ty>();
550   }
551 
552   /// getBlockNumbered - MachineBasicBlocks are automatically numbered when they
553   /// are inserted into the machine function.  The block number for a machine
554   /// basic block can be found by using the MBB::getNumber method, this method
555   /// provides the inverse mapping.
556   MachineBasicBlock *getBlockNumbered(unsigned N) const {
557     assert(N < MBBNumbering.size() && "Illegal block number");
558     assert(MBBNumbering[N] && "Block was removed from the machine function!");
559     return MBBNumbering[N];
560   }
561 
562   /// Should we be emitting segmented stack stuff for the function
563   bool shouldSplitStack() const;
564 
565   /// getNumBlockIDs - Return the number of MBB ID's allocated.
566   unsigned getNumBlockIDs() const { return (unsigned)MBBNumbering.size(); }
567 
568   /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
569   /// recomputes them.  This guarantees that the MBB numbers are sequential,
570   /// dense, and match the ordering of the blocks within the function.  If a
571   /// specific MachineBasicBlock is specified, only that block and those after
572   /// it are renumbered.
573   void RenumberBlocks(MachineBasicBlock *MBBFrom = nullptr);
574 
575   /// print - Print out the MachineFunction in a format suitable for debugging
576   /// to the specified stream.
577   void print(raw_ostream &OS, const SlotIndexes* = nullptr) const;
578 
579   /// viewCFG - This function is meant for use from the debugger.  You can just
580   /// say 'call F->viewCFG()' and a ghostview window should pop up from the
581   /// program, displaying the CFG of the current function with the code for each
582   /// basic block inside.  This depends on there being a 'dot' and 'gv' program
583   /// in your path.
584   void viewCFG() const;
585 
586   /// viewCFGOnly - This function is meant for use from the debugger.  It works
587   /// just like viewCFG, but it does not include the contents of basic blocks
588   /// into the nodes, just the label.  If you are only interested in the CFG
589   /// this can make the graph smaller.
590   ///
591   void viewCFGOnly() const;
592 
593   /// dump - Print the current MachineFunction to cerr, useful for debugger use.
594   void dump() const;
595 
596   /// Run the current MachineFunction through the machine code verifier, useful
597   /// for debugger use.
598   /// \returns true if no problems were found.
599   bool verify(Pass *p = nullptr, const char *Banner = nullptr,
600               bool AbortOnError = true) const;
601 
602   // Provide accessors for the MachineBasicBlock list...
603   using iterator = BasicBlockListType::iterator;
604   using const_iterator = BasicBlockListType::const_iterator;
605   using const_reverse_iterator = BasicBlockListType::const_reverse_iterator;
606   using reverse_iterator = BasicBlockListType::reverse_iterator;
607 
608   /// Support for MachineBasicBlock::getNextNode().
609   static BasicBlockListType MachineFunction::*
610   getSublistAccess(MachineBasicBlock *) {
611     return &MachineFunction::BasicBlocks;
612   }
613 
614   /// addLiveIn - Add the specified physical register as a live-in value and
615   /// create a corresponding virtual register for it.
616   unsigned addLiveIn(unsigned PReg, const TargetRegisterClass *RC);
617 
618   //===--------------------------------------------------------------------===//
619   // BasicBlock accessor functions.
620   //
621   iterator                 begin()       { return BasicBlocks.begin(); }
622   const_iterator           begin() const { return BasicBlocks.begin(); }
623   iterator                 end  ()       { return BasicBlocks.end();   }
624   const_iterator           end  () const { return BasicBlocks.end();   }
625 
626   reverse_iterator        rbegin()       { return BasicBlocks.rbegin(); }
627   const_reverse_iterator  rbegin() const { return BasicBlocks.rbegin(); }
628   reverse_iterator        rend  ()       { return BasicBlocks.rend();   }
629   const_reverse_iterator  rend  () const { return BasicBlocks.rend();   }
630 
631   unsigned                  size() const { return (unsigned)BasicBlocks.size();}
632   bool                     empty() const { return BasicBlocks.empty(); }
633   const MachineBasicBlock &front() const { return BasicBlocks.front(); }
634         MachineBasicBlock &front()       { return BasicBlocks.front(); }
635   const MachineBasicBlock & back() const { return BasicBlocks.back(); }
636         MachineBasicBlock & back()       { return BasicBlocks.back(); }
637 
638   void push_back (MachineBasicBlock *MBB) { BasicBlocks.push_back (MBB); }
639   void push_front(MachineBasicBlock *MBB) { BasicBlocks.push_front(MBB); }
640   void insert(iterator MBBI, MachineBasicBlock *MBB) {
641     BasicBlocks.insert(MBBI, MBB);
642   }
643   void splice(iterator InsertPt, iterator MBBI) {
644     BasicBlocks.splice(InsertPt, BasicBlocks, MBBI);
645   }
646   void splice(iterator InsertPt, MachineBasicBlock *MBB) {
647     BasicBlocks.splice(InsertPt, BasicBlocks, MBB);
648   }
649   void splice(iterator InsertPt, iterator MBBI, iterator MBBE) {
650     BasicBlocks.splice(InsertPt, BasicBlocks, MBBI, MBBE);
651   }
652 
653   void remove(iterator MBBI) { BasicBlocks.remove(MBBI); }
654   void remove(MachineBasicBlock *MBBI) { BasicBlocks.remove(MBBI); }
655   void erase(iterator MBBI) { BasicBlocks.erase(MBBI); }
656   void erase(MachineBasicBlock *MBBI) { BasicBlocks.erase(MBBI); }
657 
658   template <typename Comp>
659   void sort(Comp comp) {
660     BasicBlocks.sort(comp);
661   }
662 
663   /// Return the number of \p MachineInstrs in this \p MachineFunction.
664   unsigned getInstructionCount() const {
665     unsigned InstrCount = 0;
666     for (const MachineBasicBlock &MBB : BasicBlocks)
667       InstrCount += MBB.size();
668     return InstrCount;
669   }
670 
671   //===--------------------------------------------------------------------===//
672   // Internal functions used to automatically number MachineBasicBlocks
673 
674   /// Adds the MBB to the internal numbering. Returns the unique number
675   /// assigned to the MBB.
676   unsigned addToMBBNumbering(MachineBasicBlock *MBB) {
677     MBBNumbering.push_back(MBB);
678     return (unsigned)MBBNumbering.size()-1;
679   }
680 
681   /// removeFromMBBNumbering - Remove the specific machine basic block from our
682   /// tracker, this is only really to be used by the MachineBasicBlock
683   /// implementation.
684   void removeFromMBBNumbering(unsigned N) {
685     assert(N < MBBNumbering.size() && "Illegal basic block #");
686     MBBNumbering[N] = nullptr;
687   }
688 
689   /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
690   /// of `new MachineInstr'.
691   MachineInstr *CreateMachineInstr(const MCInstrDesc &MCID, const DebugLoc &DL,
692                                    bool NoImp = false);
693 
694   /// Create a new MachineInstr which is a copy of \p Orig, identical in all
695   /// ways except the instruction has no parent, prev, or next. Bundling flags
696   /// are reset.
697   ///
698   /// Note: Clones a single instruction, not whole instruction bundles.
699   /// Does not perform target specific adjustments; consider using
700   /// TargetInstrInfo::duplicate() instead.
701   MachineInstr *CloneMachineInstr(const MachineInstr *Orig);
702 
703   /// Clones instruction or the whole instruction bundle \p Orig and insert
704   /// into \p MBB before \p InsertBefore.
705   ///
706   /// Note: Does not perform target specific adjustments; consider using
707   /// TargetInstrInfo::duplicate() intead.
708   MachineInstr &CloneMachineInstrBundle(MachineBasicBlock &MBB,
709       MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig);
710 
711   /// DeleteMachineInstr - Delete the given MachineInstr.
712   void DeleteMachineInstr(MachineInstr *MI);
713 
714   /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
715   /// instead of `new MachineBasicBlock'.
716   MachineBasicBlock *CreateMachineBasicBlock(const BasicBlock *bb = nullptr);
717 
718   /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
719   void DeleteMachineBasicBlock(MachineBasicBlock *MBB);
720 
721   /// getMachineMemOperand - Allocate a new MachineMemOperand.
722   /// MachineMemOperands are owned by the MachineFunction and need not be
723   /// explicitly deallocated.
724   MachineMemOperand *getMachineMemOperand(
725       MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
726       unsigned base_alignment, const AAMDNodes &AAInfo = AAMDNodes(),
727       const MDNode *Ranges = nullptr,
728       SyncScope::ID SSID = SyncScope::System,
729       AtomicOrdering Ordering = AtomicOrdering::NotAtomic,
730       AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic);
731 
732   /// getMachineMemOperand - Allocate a new MachineMemOperand by copying
733   /// an existing one, adjusting by an offset and using the given size.
734   /// MachineMemOperands are owned by the MachineFunction and need not be
735   /// explicitly deallocated.
736   MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
737                                           int64_t Offset, uint64_t Size);
738 
739   /// Allocate a new MachineMemOperand by copying an existing one,
740   /// replacing only AliasAnalysis information. MachineMemOperands are owned
741   /// by the MachineFunction and need not be explicitly deallocated.
742   MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
743                                           const AAMDNodes &AAInfo);
744 
745   using OperandCapacity = ArrayRecycler<MachineOperand>::Capacity;
746 
747   /// Allocate an array of MachineOperands. This is only intended for use by
748   /// internal MachineInstr functions.
749   MachineOperand *allocateOperandArray(OperandCapacity Cap) {
750     return OperandRecycler.allocate(Cap, Allocator);
751   }
752 
753   /// Dellocate an array of MachineOperands and recycle the memory. This is
754   /// only intended for use by internal MachineInstr functions.
755   /// Cap must be the same capacity that was used to allocate the array.
756   void deallocateOperandArray(OperandCapacity Cap, MachineOperand *Array) {
757     OperandRecycler.deallocate(Cap, Array);
758   }
759 
760   /// Allocate and initialize a register mask with @p NumRegister bits.
761   uint32_t *allocateRegMask();
762 
763   /// Allocate and construct an extra info structure for a `MachineInstr`.
764   ///
765   /// This is allocated on the function's allocator and so lives the life of
766   /// the function.
767   MachineInstr::ExtraInfo *
768   createMIExtraInfo(ArrayRef<MachineMemOperand *> MMOs,
769                     MCSymbol *PreInstrSymbol = nullptr,
770                     MCSymbol *PostInstrSymbol = nullptr);
771 
772   /// Allocate a string and populate it with the given external symbol name.
773   const char *createExternalSymbolName(StringRef Name);
774 
775   //===--------------------------------------------------------------------===//
776   // Label Manipulation.
777 
778   /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
779   /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
780   /// normal 'L' label is returned.
781   MCSymbol *getJTISymbol(unsigned JTI, MCContext &Ctx,
782                          bool isLinkerPrivate = false) const;
783 
784   /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
785   /// base.
786   MCSymbol *getPICBaseSymbol() const;
787 
788   /// Returns a reference to a list of cfi instructions in the function's
789   /// prologue.  Used to construct frame maps for debug and exception handling
790   /// comsumers.
791   const std::vector<MCCFIInstruction> &getFrameInstructions() const {
792     return FrameInstructions;
793   }
794 
795   LLVM_NODISCARD unsigned addFrameInst(const MCCFIInstruction &Inst) {
796     FrameInstructions.push_back(Inst);
797     return FrameInstructions.size() - 1;
798   }
799 
800   /// \name Exception Handling
801   /// \{
802 
803   bool callsEHReturn() const { return CallsEHReturn; }
804   void setCallsEHReturn(bool b) { CallsEHReturn = b; }
805 
806   bool callsUnwindInit() const { return CallsUnwindInit; }
807   void setCallsUnwindInit(bool b) { CallsUnwindInit = b; }
808 
809   bool hasEHScopes() const { return HasEHScopes; }
810   void setHasEHScopes(bool V) { HasEHScopes = V; }
811 
812   bool hasEHFunclets() const { return HasEHFunclets; }
813   void setHasEHFunclets(bool V) { HasEHFunclets = V; }
814 
815   bool hasLocalEscape() const { return HasLocalEscape; }
816   void setHasLocalEscape(bool V) { HasLocalEscape = V; }
817 
818   /// Find or create an LandingPadInfo for the specified MachineBasicBlock.
819   LandingPadInfo &getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad);
820 
821   /// Remap landing pad labels and remove any deleted landing pads.
822   void tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap = nullptr,
823                        bool TidyIfNoBeginLabels = true);
824 
825   /// Return a reference to the landing pad info for the current function.
826   const std::vector<LandingPadInfo> &getLandingPads() const {
827     return LandingPads;
828   }
829 
830   /// Provide the begin and end labels of an invoke style call and associate it
831   /// with a try landing pad block.
832   void addInvoke(MachineBasicBlock *LandingPad,
833                  MCSymbol *BeginLabel, MCSymbol *EndLabel);
834 
835   /// Add a new panding pad, and extract the exception handling information from
836   /// the landingpad instruction. Returns the label ID for the landing pad
837   /// entry.
838   MCSymbol *addLandingPad(MachineBasicBlock *LandingPad);
839 
840   /// Provide the catch typeinfo for a landing pad.
841   void addCatchTypeInfo(MachineBasicBlock *LandingPad,
842                         ArrayRef<const GlobalValue *> TyInfo);
843 
844   /// Provide the filter typeinfo for a landing pad.
845   void addFilterTypeInfo(MachineBasicBlock *LandingPad,
846                          ArrayRef<const GlobalValue *> TyInfo);
847 
848   /// Add a cleanup action for a landing pad.
849   void addCleanup(MachineBasicBlock *LandingPad);
850 
851   void addSEHCatchHandler(MachineBasicBlock *LandingPad, const Function *Filter,
852                           const BlockAddress *RecoverBA);
853 
854   void addSEHCleanupHandler(MachineBasicBlock *LandingPad,
855                             const Function *Cleanup);
856 
857   /// Return the type id for the specified typeinfo.  This is function wide.
858   unsigned getTypeIDFor(const GlobalValue *TI);
859 
860   /// Return the id of the filter encoded by TyIds.  This is function wide.
861   int getFilterIDFor(std::vector<unsigned> &TyIds);
862 
863   /// Map the landing pad's EH symbol to the call site indexes.
864   void setCallSiteLandingPad(MCSymbol *Sym, ArrayRef<unsigned> Sites);
865 
866   /// Map the landing pad to its index. Used for Wasm exception handling.
867   void setWasmLandingPadIndex(const MachineBasicBlock *LPad, unsigned Index) {
868     WasmLPadToIndexMap[LPad] = Index;
869   }
870 
871   /// Returns true if the landing pad has an associate index in wasm EH.
872   bool hasWasmLandingPadIndex(const MachineBasicBlock *LPad) const {
873     return WasmLPadToIndexMap.count(LPad);
874   }
875 
876   /// Get the index in wasm EH for a given landing pad.
877   unsigned getWasmLandingPadIndex(const MachineBasicBlock *LPad) const {
878     assert(hasWasmLandingPadIndex(LPad));
879     return WasmLPadToIndexMap.lookup(LPad);
880   }
881 
882   /// Get the call site indexes for a landing pad EH symbol.
883   SmallVectorImpl<unsigned> &getCallSiteLandingPad(MCSymbol *Sym) {
884     assert(hasCallSiteLandingPad(Sym) &&
885            "missing call site number for landing pad!");
886     return LPadToCallSiteMap[Sym];
887   }
888 
889   /// Return true if the landing pad Eh symbol has an associated call site.
890   bool hasCallSiteLandingPad(MCSymbol *Sym) {
891     return !LPadToCallSiteMap[Sym].empty();
892   }
893 
894   /// Map the begin label for a call site.
895   void setCallSiteBeginLabel(MCSymbol *BeginLabel, unsigned Site) {
896     CallSiteMap[BeginLabel] = Site;
897   }
898 
899   /// Get the call site number for a begin label.
900   unsigned getCallSiteBeginLabel(MCSymbol *BeginLabel) const {
901     assert(hasCallSiteBeginLabel(BeginLabel) &&
902            "Missing call site number for EH_LABEL!");
903     return CallSiteMap.lookup(BeginLabel);
904   }
905 
906   /// Return true if the begin label has a call site number associated with it.
907   bool hasCallSiteBeginLabel(MCSymbol *BeginLabel) const {
908     return CallSiteMap.count(BeginLabel);
909   }
910 
911   /// Record annotations associated with a particular label.
912   void addCodeViewAnnotation(MCSymbol *Label, MDNode *MD) {
913     CodeViewAnnotations.push_back({Label, MD});
914   }
915 
916   ArrayRef<std::pair<MCSymbol *, MDNode *>> getCodeViewAnnotations() const {
917     return CodeViewAnnotations;
918   }
919 
920   /// Return a reference to the C++ typeinfo for the current function.
921   const std::vector<const GlobalValue *> &getTypeInfos() const {
922     return TypeInfos;
923   }
924 
925   /// Return a reference to the typeids encoding filters used in the current
926   /// function.
927   const std::vector<unsigned> &getFilterIds() const {
928     return FilterIds;
929   }
930 
931   /// \}
932 
933   /// Collect information used to emit debugging information of a variable.
934   void setVariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr,
935                           int Slot, const DILocation *Loc) {
936     VariableDbgInfos.emplace_back(Var, Expr, Slot, Loc);
937   }
938 
939   VariableDbgInfoMapTy &getVariableDbgInfo() { return VariableDbgInfos; }
940   const VariableDbgInfoMapTy &getVariableDbgInfo() const {
941     return VariableDbgInfos;
942   }
943 };
944 
945 //===--------------------------------------------------------------------===//
946 // GraphTraits specializations for function basic block graphs (CFGs)
947 //===--------------------------------------------------------------------===//
948 
949 // Provide specializations of GraphTraits to be able to treat a
950 // machine function as a graph of machine basic blocks... these are
951 // the same as the machine basic block iterators, except that the root
952 // node is implicitly the first node of the function.
953 //
954 template <> struct GraphTraits<MachineFunction*> :
955   public GraphTraits<MachineBasicBlock*> {
956   static NodeRef getEntryNode(MachineFunction *F) { return &F->front(); }
957 
958   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
959   using nodes_iterator = pointer_iterator<MachineFunction::iterator>;
960 
961   static nodes_iterator nodes_begin(MachineFunction *F) {
962     return nodes_iterator(F->begin());
963   }
964 
965   static nodes_iterator nodes_end(MachineFunction *F) {
966     return nodes_iterator(F->end());
967   }
968 
969   static unsigned       size       (MachineFunction *F) { return F->size(); }
970 };
971 template <> struct GraphTraits<const MachineFunction*> :
972   public GraphTraits<const MachineBasicBlock*> {
973   static NodeRef getEntryNode(const MachineFunction *F) { return &F->front(); }
974 
975   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
976   using nodes_iterator = pointer_iterator<MachineFunction::const_iterator>;
977 
978   static nodes_iterator nodes_begin(const MachineFunction *F) {
979     return nodes_iterator(F->begin());
980   }
981 
982   static nodes_iterator nodes_end  (const MachineFunction *F) {
983     return nodes_iterator(F->end());
984   }
985 
986   static unsigned       size       (const MachineFunction *F)  {
987     return F->size();
988   }
989 };
990 
991 // Provide specializations of GraphTraits to be able to treat a function as a
992 // graph of basic blocks... and to walk it in inverse order.  Inverse order for
993 // a function is considered to be when traversing the predecessor edges of a BB
994 // instead of the successor edges.
995 //
996 template <> struct GraphTraits<Inverse<MachineFunction*>> :
997   public GraphTraits<Inverse<MachineBasicBlock*>> {
998   static NodeRef getEntryNode(Inverse<MachineFunction *> G) {
999     return &G.Graph->front();
1000   }
1001 };
1002 template <> struct GraphTraits<Inverse<const MachineFunction*>> :
1003   public GraphTraits<Inverse<const MachineBasicBlock*>> {
1004   static NodeRef getEntryNode(Inverse<const MachineFunction *> G) {
1005     return &G.Graph->front();
1006   }
1007 };
1008 
1009 } // end namespace llvm
1010 
1011 #endif // LLVM_CODEGEN_MACHINEFUNCTION_H
1012