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