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