1 //===- llvm/CodeGen/MachineFunction.h ---------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // Collect native machine code for a function. This class contains a list of
10 // MachineBasicBlock instances that make up the current compiled function.
12 // This class also contains pointers to various classes which hold
13 // target-specific information about the generated code.
15 //===----------------------------------------------------------------------===//
17 #ifndef LLVM_CODEGEN_MACHINEFUNCTION_H
18 #define LLVM_CODEGEN_MACHINEFUNCTION_H
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/GraphTraits.h"
24 #include "llvm/ADT/Optional.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/ilist.h"
28 #include "llvm/ADT/iterator.h"
29 #include "llvm/Analysis/EHPersonalities.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/CodeGen/MachineMemOperand.h"
33 #include "llvm/Support/Allocator.h"
34 #include "llvm/Support/ArrayRecycler.h"
35 #include "llvm/Support/AtomicOrdering.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/Recycler.h"
52 class DILocalVariable
;
56 class LLVMTargetMachine
;
57 class MachineConstantPool
;
58 class MachineFrameInfo
;
59 class MachineFunction
;
60 class MachineJumpTableInfo
;
61 class MachineModuleInfo
;
62 class MachineRegisterInfo
;
67 class PseudoSourceValueManager
;
70 class TargetRegisterClass
;
71 class TargetSubtargetInfo
;
72 struct WasmEHFuncInfo
;
75 template <> struct ilist_alloc_traits
<MachineBasicBlock
> {
76 void deleteNode(MachineBasicBlock
*MBB
);
79 template <> struct ilist_callback_traits
<MachineBasicBlock
> {
80 void addNodeToList(MachineBasicBlock
* N
);
81 void removeNodeFromList(MachineBasicBlock
* N
);
83 template <class Iterator
>
84 void transferNodesFromList(ilist_callback_traits
&OldList
, Iterator
, Iterator
) {
85 assert(this == &OldList
&& "never transfer MBBs between functions");
89 /// MachineFunctionInfo - This class can be derived from and used by targets to
90 /// hold private target-specific information for each MachineFunction. Objects
91 /// of type are accessed/created with MF::getInfo and destroyed when the
92 /// MachineFunction is destroyed.
93 struct MachineFunctionInfo
{
94 virtual ~MachineFunctionInfo();
96 /// Factory function: default behavior is to call new using the
97 /// supplied allocator.
99 /// This function can be overridden in a derive class.
100 template<typename Ty
>
101 static Ty
*create(BumpPtrAllocator
&Allocator
, MachineFunction
&MF
) {
102 return new (Allocator
.Allocate
<Ty
>()) Ty(MF
);
106 /// Properties which a MachineFunction may have at a given point in time.
107 /// Each of these has checking code in the MachineVerifier, and passes can
108 /// require that a property be set.
109 class MachineFunctionProperties
{
110 // Possible TODO: Allow targets to extend this (perhaps by allowing the
111 // constructor to specify the size of the bit vector)
112 // Possible TODO: Allow requiring the negative (e.g. VRegsAllocated could be
113 // stated as the negative of "has vregs"
116 // The properties are stated in "positive" form; i.e. a pass could require
117 // that the property hold, but not that it does not hold.
119 // Property descriptions:
120 // IsSSA: True when the machine function is in SSA form and virtual registers
121 // have a single def.
122 // NoPHIs: The machine function does not contain any PHI instruction.
123 // TracksLiveness: True when tracking register liveness accurately.
124 // While this property is set, register liveness information in basic block
125 // live-in lists and machine instruction operands (e.g. kill flags, implicit
126 // defs) is accurate. This means it can be used to change the code in ways
127 // that affect the values in registers, for example by the register
129 // When this property is clear, liveness is no longer reliable.
130 // NoVRegs: The machine function does not use any virtual registers.
131 // Legalized: In GlobalISel: the MachineLegalizer ran and all pre-isel generic
132 // instructions have been legalized; i.e., all instructions are now one of:
133 // - generic and always legal (e.g., COPY)
135 // - legal pre-isel generic instructions.
136 // RegBankSelected: In GlobalISel: the RegBankSelect pass ran and all generic
137 // virtual registers have been assigned to a register bank.
138 // Selected: In GlobalISel: the InstructionSelect pass ran and all pre-isel
139 // generic instructions have been eliminated; i.e., all instructions are now
140 // target-specific or non-pre-isel generic instructions (e.g., COPY).
141 // Since only pre-isel generic instructions can have generic virtual register
142 // operands, this also means that all generic virtual registers have been
143 // constrained to virtual registers (assigned to register classes) and that
144 // all sizes attached to them have been eliminated.
145 enum class Property
: unsigned {
154 LastProperty
= Selected
,
157 bool hasProperty(Property P
) const {
158 return Properties
[static_cast<unsigned>(P
)];
161 MachineFunctionProperties
&set(Property P
) {
162 Properties
.set(static_cast<unsigned>(P
));
166 MachineFunctionProperties
&reset(Property P
) {
167 Properties
.reset(static_cast<unsigned>(P
));
171 /// Reset all the properties.
172 MachineFunctionProperties
&reset() {
177 MachineFunctionProperties
&set(const MachineFunctionProperties
&MFP
) {
178 Properties
|= MFP
.Properties
;
182 MachineFunctionProperties
&reset(const MachineFunctionProperties
&MFP
) {
183 Properties
.reset(MFP
.Properties
);
187 // Returns true if all properties set in V (i.e. required by a pass) are set
189 bool verifyRequiredProperties(const MachineFunctionProperties
&V
) const {
190 return !V
.Properties
.test(Properties
);
193 /// Print the MachineFunctionProperties in human-readable form.
194 void print(raw_ostream
&OS
) const;
197 BitVector Properties
=
198 BitVector(static_cast<unsigned>(Property::LastProperty
)+1);
202 /// Filter or finally function. Null indicates a catch-all.
203 const Function
*FilterOrFinally
;
205 /// Address of block to recover at. Null for a finally handler.
206 const BlockAddress
*RecoverBA
;
209 /// This structure is used to retain landing pad info for the current function.
210 struct LandingPadInfo
{
211 MachineBasicBlock
*LandingPadBlock
; // Landing pad block.
212 SmallVector
<MCSymbol
*, 1> BeginLabels
; // Labels prior to invoke.
213 SmallVector
<MCSymbol
*, 1> EndLabels
; // Labels after invoke.
214 SmallVector
<SEHHandler
, 1> SEHHandlers
; // SEH handlers active at this lpad.
215 MCSymbol
*LandingPadLabel
= nullptr; // Label at beginning of landing pad.
216 std::vector
<int> TypeIds
; // List of type ids (filters negative).
218 explicit LandingPadInfo(MachineBasicBlock
*MBB
)
219 : LandingPadBlock(MBB
) {}
222 class MachineFunction
{
224 const LLVMTargetMachine
&Target
;
225 const TargetSubtargetInfo
*STI
;
227 MachineModuleInfo
&MMI
;
229 // RegInfo - Information about each register in use in the function.
230 MachineRegisterInfo
*RegInfo
;
232 // Used to keep track of target-specific per-machine function information for
233 // the target implementation.
234 MachineFunctionInfo
*MFInfo
;
236 // Keep track of objects allocated on the stack.
237 MachineFrameInfo
*FrameInfo
;
239 // Keep track of constants which are spilled to memory
240 MachineConstantPool
*ConstantPool
;
242 // Keep track of jump tables for switch instructions
243 MachineJumpTableInfo
*JumpTableInfo
;
245 // Keeps track of Wasm exception handling related data. This will be null for
246 // functions that aren't using a wasm EH personality.
247 WasmEHFuncInfo
*WasmEHInfo
= nullptr;
249 // Keeps track of Windows exception handling related data. This will be null
250 // for functions that aren't using a funclet-based EH personality.
251 WinEHFuncInfo
*WinEHInfo
= nullptr;
253 // Function-level unique numbering for MachineBasicBlocks. When a
254 // MachineBasicBlock is inserted into a MachineFunction is it automatically
255 // numbered and this vector keeps track of the mapping from ID's to MBB's.
256 std::vector
<MachineBasicBlock
*> MBBNumbering
;
258 // Pool-allocate MachineFunction-lifetime and IR objects.
259 BumpPtrAllocator Allocator
;
261 // Allocation management for instructions in function.
262 Recycler
<MachineInstr
> InstructionRecycler
;
264 // Allocation management for operand arrays on instructions.
265 ArrayRecycler
<MachineOperand
> OperandRecycler
;
267 // Allocation management for basic blocks in function.
268 Recycler
<MachineBasicBlock
> BasicBlockRecycler
;
270 // List of machine basic blocks in function
271 using BasicBlockListType
= ilist
<MachineBasicBlock
>;
272 BasicBlockListType BasicBlocks
;
274 /// FunctionNumber - This provides a unique ID for each function emitted in
275 /// this translation unit.
277 unsigned FunctionNumber
;
279 /// Alignment - The alignment of the function.
280 unsigned LogAlignment
;
282 /// ExposesReturnsTwice - True if the function calls setjmp or related
283 /// functions with attribute "returns twice", but doesn't have
284 /// the attribute itself.
285 /// This is used to limit optimizations which cannot reason
286 /// about the control flow of such functions.
287 bool ExposesReturnsTwice
= false;
289 /// True if the function includes any inline assembly.
290 bool HasInlineAsm
= false;
292 /// True if any WinCFI instruction have been emitted in this function.
293 bool HasWinCFI
= false;
295 /// Current high-level properties of the IR of the function (e.g. is in SSA
296 /// form or whether registers have been allocated)
297 MachineFunctionProperties Properties
;
299 // Allocation management for pseudo source values.
300 std::unique_ptr
<PseudoSourceValueManager
> PSVManager
;
302 /// List of moves done by a function's prolog. Used to construct frame maps
303 /// by debug and exception handling consumers.
304 std::vector
<MCCFIInstruction
> FrameInstructions
;
306 /// \name Exception Handling
309 /// List of LandingPadInfo describing the landing pad information.
310 std::vector
<LandingPadInfo
> LandingPads
;
312 /// Map a landing pad's EH symbol to the call site indexes.
313 DenseMap
<MCSymbol
*, SmallVector
<unsigned, 4>> LPadToCallSiteMap
;
315 /// Map a landing pad to its index.
316 DenseMap
<const MachineBasicBlock
*, unsigned> WasmLPadToIndexMap
;
318 /// Map of invoke call site index values to associated begin EH_LABEL.
319 DenseMap
<MCSymbol
*, unsigned> CallSiteMap
;
321 /// CodeView label annotations.
322 std::vector
<std::pair
<MCSymbol
*, MDNode
*>> CodeViewAnnotations
;
324 /// CodeView heapallocsites.
325 std::vector
<std::tuple
<MCSymbol
*, MCSymbol
*, const DIType
*>>
326 CodeViewHeapAllocSites
;
328 bool CallsEHReturn
= false;
329 bool CallsUnwindInit
= false;
330 bool HasEHScopes
= false;
331 bool HasEHFunclets
= false;
333 /// List of C++ TypeInfo used.
334 std::vector
<const GlobalValue
*> TypeInfos
;
336 /// List of typeids encoding filters used.
337 std::vector
<unsigned> FilterIds
;
339 /// List of the indices in FilterIds corresponding to filter terminators.
340 std::vector
<unsigned> FilterEnds
;
342 EHPersonality PersonalityTypeCache
= EHPersonality::Unknown
;
346 /// Clear all the members of this MachineFunction, but the ones used
347 /// to initialize again the MachineFunction.
348 /// More specifically, this deallocates all the dynamically allocated
349 /// objects and get rid of all the XXXInfo data structure, but keep
350 /// unchanged the references to Fn, Target, MMI, and FunctionNumber.
352 /// Allocate and initialize the different members.
353 /// In particular, the XXXInfo data structure.
354 /// \pre Fn, Target, MMI, and FunctionNumber are properly set.
358 struct VariableDbgInfo
{
359 const DILocalVariable
*Var
;
360 const DIExpression
*Expr
;
361 // The Slot can be negative for fixed stack objects.
363 const DILocation
*Loc
;
365 VariableDbgInfo(const DILocalVariable
*Var
, const DIExpression
*Expr
,
366 int Slot
, const DILocation
*Loc
)
367 : Var(Var
), Expr(Expr
), Slot(Slot
), Loc(Loc
) {}
371 virtual void anchor();
374 virtual ~Delegate() = default;
375 /// Callback after an insertion. This should not modify the MI directly.
376 virtual void MF_HandleInsertion(MachineInstr
&MI
) = 0;
377 /// Callback before a removal. This should not modify the MI directly.
378 virtual void MF_HandleRemoval(MachineInstr
&MI
) = 0;
381 /// Structure used to represent pair of argument number after call lowering
382 /// and register used to transfer that argument.
383 /// For now we support only cases when argument is transferred through one
388 ArgRegPair(unsigned R
, unsigned Arg
) : Reg(R
), ArgNo(Arg
) {
389 assert(Arg
< (1 << 16) && "Arg out of range");
392 /// Vector of call argument and its forwarding register.
393 using CallSiteInfo
= SmallVector
<ArgRegPair
, 1>;
394 using CallSiteInfoImpl
= SmallVectorImpl
<ArgRegPair
>;
397 Delegate
*TheDelegate
= nullptr;
399 using CallSiteInfoMap
= DenseMap
<const MachineInstr
*, CallSiteInfo
>;
400 /// Map a call instruction to call site arguments forwarding info.
401 CallSiteInfoMap CallSitesInfo
;
403 // Callbacks for insertion and removal.
404 void handleInsertion(MachineInstr
&MI
);
405 void handleRemoval(MachineInstr
&MI
);
406 friend struct ilist_traits
<MachineInstr
>;
409 using VariableDbgInfoMapTy
= SmallVector
<VariableDbgInfo
, 4>;
410 VariableDbgInfoMapTy VariableDbgInfos
;
412 MachineFunction(const Function
&F
, const LLVMTargetMachine
&Target
,
413 const TargetSubtargetInfo
&STI
, unsigned FunctionNum
,
414 MachineModuleInfo
&MMI
);
415 MachineFunction(const MachineFunction
&) = delete;
416 MachineFunction
&operator=(const MachineFunction
&) = delete;
419 /// Reset the instance as if it was just created.
425 /// Reset the currently registered delegate - otherwise assert.
426 void resetDelegate(Delegate
*delegate
) {
427 assert(TheDelegate
== delegate
&&
428 "Only the current delegate can perform reset!");
429 TheDelegate
= nullptr;
432 /// Set the delegate. resetDelegate must be called before attempting
434 void setDelegate(Delegate
*delegate
) {
435 assert(delegate
&& !TheDelegate
&&
436 "Attempted to set delegate to null, or to change it without "
437 "first resetting it!");
439 TheDelegate
= delegate
;
442 MachineModuleInfo
&getMMI() const { return MMI
; }
443 MCContext
&getContext() const { return Ctx
; }
445 PseudoSourceValueManager
&getPSVManager() const { return *PSVManager
; }
447 /// Return the DataLayout attached to the Module associated to this MF.
448 const DataLayout
&getDataLayout() const;
450 /// Return the LLVM function that this machine code represents
451 const Function
&getFunction() const { return F
; }
453 /// getName - Return the name of the corresponding LLVM function.
454 StringRef
getName() const;
456 /// getFunctionNumber - Return a unique ID for the current function.
457 unsigned getFunctionNumber() const { return FunctionNumber
; }
459 /// getTarget - Return the target machine this machine code is compiled with
460 const LLVMTargetMachine
&getTarget() const { return Target
; }
462 /// getSubtarget - Return the subtarget for which this machine code is being
464 const TargetSubtargetInfo
&getSubtarget() const { return *STI
; }
466 /// getSubtarget - This method returns a pointer to the specified type of
467 /// TargetSubtargetInfo. In debug builds, it verifies that the object being
468 /// returned is of the correct type.
469 template<typename STC
> const STC
&getSubtarget() const {
470 return *static_cast<const STC
*>(STI
);
473 /// getRegInfo - Return information about the registers currently in use.
474 MachineRegisterInfo
&getRegInfo() { return *RegInfo
; }
475 const MachineRegisterInfo
&getRegInfo() const { return *RegInfo
; }
477 /// getFrameInfo - Return the frame info object for the current function.
478 /// This object contains information about objects allocated on the stack
479 /// frame of the current function in an abstract way.
480 MachineFrameInfo
&getFrameInfo() { return *FrameInfo
; }
481 const MachineFrameInfo
&getFrameInfo() const { return *FrameInfo
; }
483 /// getJumpTableInfo - Return the jump table info object for the current
484 /// function. This object contains information about jump tables in the
485 /// current function. If the current function has no jump tables, this will
487 const MachineJumpTableInfo
*getJumpTableInfo() const { return JumpTableInfo
; }
488 MachineJumpTableInfo
*getJumpTableInfo() { return JumpTableInfo
; }
490 /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
491 /// does already exist, allocate one.
492 MachineJumpTableInfo
*getOrCreateJumpTableInfo(unsigned JTEntryKind
);
494 /// getConstantPool - Return the constant pool object for the current
496 MachineConstantPool
*getConstantPool() { return ConstantPool
; }
497 const MachineConstantPool
*getConstantPool() const { return ConstantPool
; }
499 /// getWasmEHFuncInfo - Return information about how the current function uses
500 /// Wasm exception handling. Returns null for functions that don't use wasm
501 /// exception handling.
502 const WasmEHFuncInfo
*getWasmEHFuncInfo() const { return WasmEHInfo
; }
503 WasmEHFuncInfo
*getWasmEHFuncInfo() { return WasmEHInfo
; }
505 /// getWinEHFuncInfo - Return information about how the current function uses
506 /// Windows exception handling. Returns null for functions that don't use
507 /// funclets for exception handling.
508 const WinEHFuncInfo
*getWinEHFuncInfo() const { return WinEHInfo
; }
509 WinEHFuncInfo
*getWinEHFuncInfo() { return WinEHInfo
; }
511 /// getLogAlignment - Return the alignment of the function.
512 unsigned getLogAlignment() const { return LogAlignment
; }
514 /// setLogAlignment - Set the alignment of the function.
515 void setLogAlignment(unsigned A
) { LogAlignment
= A
; }
517 /// ensureAlignment - Make sure the function is at least 1 << A bytes aligned.
518 void ensureLogAlignment(unsigned A
) {
519 if (LogAlignment
< A
)
523 /// exposesReturnsTwice - Returns true if the function calls setjmp or
524 /// any other similar functions with attribute "returns twice" without
525 /// having the attribute itself.
526 bool exposesReturnsTwice() const {
527 return ExposesReturnsTwice
;
530 /// setCallsSetJmp - Set a flag that indicates if there's a call to
531 /// a "returns twice" function.
532 void setExposesReturnsTwice(bool B
) {
533 ExposesReturnsTwice
= B
;
536 /// Returns true if the function contains any inline assembly.
537 bool hasInlineAsm() const {
541 /// Set a flag that indicates that the function contains inline assembly.
542 void setHasInlineAsm(bool B
) {
546 bool hasWinCFI() const {
549 void setHasWinCFI(bool v
) { HasWinCFI
= v
; }
551 /// Get the function properties
552 const MachineFunctionProperties
&getProperties() const { return Properties
; }
553 MachineFunctionProperties
&getProperties() { return Properties
; }
555 /// getInfo - Keep track of various per-function pieces of information for
556 /// backends that would like to do so.
558 template<typename Ty
>
561 MFInfo
= Ty::template create
<Ty
>(Allocator
, *this);
562 return static_cast<Ty
*>(MFInfo
);
565 template<typename Ty
>
566 const Ty
*getInfo() const {
567 return const_cast<MachineFunction
*>(this)->getInfo
<Ty
>();
570 /// getBlockNumbered - MachineBasicBlocks are automatically numbered when they
571 /// are inserted into the machine function. The block number for a machine
572 /// basic block can be found by using the MBB::getNumber method, this method
573 /// provides the inverse mapping.
574 MachineBasicBlock
*getBlockNumbered(unsigned N
) const {
575 assert(N
< MBBNumbering
.size() && "Illegal block number");
576 assert(MBBNumbering
[N
] && "Block was removed from the machine function!");
577 return MBBNumbering
[N
];
580 /// Should we be emitting segmented stack stuff for the function
581 bool shouldSplitStack() const;
583 /// getNumBlockIDs - Return the number of MBB ID's allocated.
584 unsigned getNumBlockIDs() const { return (unsigned)MBBNumbering
.size(); }
586 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
587 /// recomputes them. This guarantees that the MBB numbers are sequential,
588 /// dense, and match the ordering of the blocks within the function. If a
589 /// specific MachineBasicBlock is specified, only that block and those after
590 /// it are renumbered.
591 void RenumberBlocks(MachineBasicBlock
*MBBFrom
= nullptr);
593 /// print - Print out the MachineFunction in a format suitable for debugging
594 /// to the specified stream.
595 void print(raw_ostream
&OS
, const SlotIndexes
* = nullptr) const;
597 /// viewCFG - This function is meant for use from the debugger. You can just
598 /// say 'call F->viewCFG()' and a ghostview window should pop up from the
599 /// program, displaying the CFG of the current function with the code for each
600 /// basic block inside. This depends on there being a 'dot' and 'gv' program
602 void viewCFG() const;
604 /// viewCFGOnly - This function is meant for use from the debugger. It works
605 /// just like viewCFG, but it does not include the contents of basic blocks
606 /// into the nodes, just the label. If you are only interested in the CFG
607 /// this can make the graph smaller.
609 void viewCFGOnly() const;
611 /// dump - Print the current MachineFunction to cerr, useful for debugger use.
614 /// Run the current MachineFunction through the machine code verifier, useful
615 /// for debugger use.
616 /// \returns true if no problems were found.
617 bool verify(Pass
*p
= nullptr, const char *Banner
= nullptr,
618 bool AbortOnError
= true) const;
620 // Provide accessors for the MachineBasicBlock list...
621 using iterator
= BasicBlockListType::iterator
;
622 using const_iterator
= BasicBlockListType::const_iterator
;
623 using const_reverse_iterator
= BasicBlockListType::const_reverse_iterator
;
624 using reverse_iterator
= BasicBlockListType::reverse_iterator
;
626 /// Support for MachineBasicBlock::getNextNode().
627 static BasicBlockListType
MachineFunction::*
628 getSublistAccess(MachineBasicBlock
*) {
629 return &MachineFunction::BasicBlocks
;
632 /// addLiveIn - Add the specified physical register as a live-in value and
633 /// create a corresponding virtual register for it.
634 unsigned addLiveIn(unsigned PReg
, const TargetRegisterClass
*RC
);
636 //===--------------------------------------------------------------------===//
637 // BasicBlock accessor functions.
639 iterator
begin() { return BasicBlocks
.begin(); }
640 const_iterator
begin() const { return BasicBlocks
.begin(); }
641 iterator
end () { return BasicBlocks
.end(); }
642 const_iterator
end () const { return BasicBlocks
.end(); }
644 reverse_iterator
rbegin() { return BasicBlocks
.rbegin(); }
645 const_reverse_iterator
rbegin() const { return BasicBlocks
.rbegin(); }
646 reverse_iterator
rend () { return BasicBlocks
.rend(); }
647 const_reverse_iterator
rend () const { return BasicBlocks
.rend(); }
649 unsigned size() const { return (unsigned)BasicBlocks
.size();}
650 bool empty() const { return BasicBlocks
.empty(); }
651 const MachineBasicBlock
&front() const { return BasicBlocks
.front(); }
652 MachineBasicBlock
&front() { return BasicBlocks
.front(); }
653 const MachineBasicBlock
& back() const { return BasicBlocks
.back(); }
654 MachineBasicBlock
& back() { return BasicBlocks
.back(); }
656 void push_back (MachineBasicBlock
*MBB
) { BasicBlocks
.push_back (MBB
); }
657 void push_front(MachineBasicBlock
*MBB
) { BasicBlocks
.push_front(MBB
); }
658 void insert(iterator MBBI
, MachineBasicBlock
*MBB
) {
659 BasicBlocks
.insert(MBBI
, MBB
);
661 void splice(iterator InsertPt
, iterator MBBI
) {
662 BasicBlocks
.splice(InsertPt
, BasicBlocks
, MBBI
);
664 void splice(iterator InsertPt
, MachineBasicBlock
*MBB
) {
665 BasicBlocks
.splice(InsertPt
, BasicBlocks
, MBB
);
667 void splice(iterator InsertPt
, iterator MBBI
, iterator MBBE
) {
668 BasicBlocks
.splice(InsertPt
, BasicBlocks
, MBBI
, MBBE
);
671 void remove(iterator MBBI
) { BasicBlocks
.remove(MBBI
); }
672 void remove(MachineBasicBlock
*MBBI
) { BasicBlocks
.remove(MBBI
); }
673 void erase(iterator MBBI
) { BasicBlocks
.erase(MBBI
); }
674 void erase(MachineBasicBlock
*MBBI
) { BasicBlocks
.erase(MBBI
); }
676 template <typename Comp
>
677 void sort(Comp comp
) {
678 BasicBlocks
.sort(comp
);
681 /// Return the number of \p MachineInstrs in this \p MachineFunction.
682 unsigned getInstructionCount() const {
683 unsigned InstrCount
= 0;
684 for (const MachineBasicBlock
&MBB
: BasicBlocks
)
685 InstrCount
+= MBB
.size();
689 //===--------------------------------------------------------------------===//
690 // Internal functions used to automatically number MachineBasicBlocks
692 /// Adds the MBB to the internal numbering. Returns the unique number
693 /// assigned to the MBB.
694 unsigned addToMBBNumbering(MachineBasicBlock
*MBB
) {
695 MBBNumbering
.push_back(MBB
);
696 return (unsigned)MBBNumbering
.size()-1;
699 /// removeFromMBBNumbering - Remove the specific machine basic block from our
700 /// tracker, this is only really to be used by the MachineBasicBlock
702 void removeFromMBBNumbering(unsigned N
) {
703 assert(N
< MBBNumbering
.size() && "Illegal basic block #");
704 MBBNumbering
[N
] = nullptr;
707 /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
708 /// of `new MachineInstr'.
709 MachineInstr
*CreateMachineInstr(const MCInstrDesc
&MCID
, const DebugLoc
&DL
,
712 /// Create a new MachineInstr which is a copy of \p Orig, identical in all
713 /// ways except the instruction has no parent, prev, or next. Bundling flags
716 /// Note: Clones a single instruction, not whole instruction bundles.
717 /// Does not perform target specific adjustments; consider using
718 /// TargetInstrInfo::duplicate() instead.
719 MachineInstr
*CloneMachineInstr(const MachineInstr
*Orig
);
721 /// Clones instruction or the whole instruction bundle \p Orig and insert
722 /// into \p MBB before \p InsertBefore.
724 /// Note: Does not perform target specific adjustments; consider using
725 /// TargetInstrInfo::duplicate() intead.
726 MachineInstr
&CloneMachineInstrBundle(MachineBasicBlock
&MBB
,
727 MachineBasicBlock::iterator InsertBefore
, const MachineInstr
&Orig
);
729 /// DeleteMachineInstr - Delete the given MachineInstr.
730 void DeleteMachineInstr(MachineInstr
*MI
);
732 /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
733 /// instead of `new MachineBasicBlock'.
734 MachineBasicBlock
*CreateMachineBasicBlock(const BasicBlock
*bb
= nullptr);
736 /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
737 void DeleteMachineBasicBlock(MachineBasicBlock
*MBB
);
739 /// getMachineMemOperand - Allocate a new MachineMemOperand.
740 /// MachineMemOperands are owned by the MachineFunction and need not be
741 /// explicitly deallocated.
742 MachineMemOperand
*getMachineMemOperand(
743 MachinePointerInfo PtrInfo
, MachineMemOperand::Flags f
, uint64_t s
,
744 unsigned base_alignment
, const AAMDNodes
&AAInfo
= AAMDNodes(),
745 const MDNode
*Ranges
= nullptr,
746 SyncScope::ID SSID
= SyncScope::System
,
747 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
,
748 AtomicOrdering FailureOrdering
= AtomicOrdering::NotAtomic
);
750 /// getMachineMemOperand - Allocate a new MachineMemOperand by copying
751 /// an existing one, adjusting by an offset and using the given size.
752 /// MachineMemOperands are owned by the MachineFunction and need not be
753 /// explicitly deallocated.
754 MachineMemOperand
*getMachineMemOperand(const MachineMemOperand
*MMO
,
755 int64_t Offset
, uint64_t Size
);
757 /// Allocate a new MachineMemOperand by copying an existing one,
758 /// replacing only AliasAnalysis information. MachineMemOperands are owned
759 /// by the MachineFunction and need not be explicitly deallocated.
760 MachineMemOperand
*getMachineMemOperand(const MachineMemOperand
*MMO
,
761 const AAMDNodes
&AAInfo
);
763 /// Allocate a new MachineMemOperand by copying an existing one,
764 /// replacing the flags. MachineMemOperands are owned
765 /// by the MachineFunction and need not be explicitly deallocated.
766 MachineMemOperand
*getMachineMemOperand(const MachineMemOperand
*MMO
,
767 MachineMemOperand::Flags Flags
);
769 using OperandCapacity
= ArrayRecycler
<MachineOperand
>::Capacity
;
771 /// Allocate an array of MachineOperands. This is only intended for use by
772 /// internal MachineInstr functions.
773 MachineOperand
*allocateOperandArray(OperandCapacity Cap
) {
774 return OperandRecycler
.allocate(Cap
, Allocator
);
777 /// Dellocate an array of MachineOperands and recycle the memory. This is
778 /// only intended for use by internal MachineInstr functions.
779 /// Cap must be the same capacity that was used to allocate the array.
780 void deallocateOperandArray(OperandCapacity Cap
, MachineOperand
*Array
) {
781 OperandRecycler
.deallocate(Cap
, Array
);
784 /// Allocate and initialize a register mask with @p NumRegister bits.
785 uint32_t *allocateRegMask();
787 /// Allocate and construct an extra info structure for a `MachineInstr`.
789 /// This is allocated on the function's allocator and so lives the life of
791 MachineInstr::ExtraInfo
*
792 createMIExtraInfo(ArrayRef
<MachineMemOperand
*> MMOs
,
793 MCSymbol
*PreInstrSymbol
= nullptr,
794 MCSymbol
*PostInstrSymbol
= nullptr);
796 /// Allocate a string and populate it with the given external symbol name.
797 const char *createExternalSymbolName(StringRef Name
);
799 //===--------------------------------------------------------------------===//
800 // Label Manipulation.
802 /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
803 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
804 /// normal 'L' label is returned.
805 MCSymbol
*getJTISymbol(unsigned JTI
, MCContext
&Ctx
,
806 bool isLinkerPrivate
= false) const;
808 /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
810 MCSymbol
*getPICBaseSymbol() const;
812 /// Returns a reference to a list of cfi instructions in the function's
813 /// prologue. Used to construct frame maps for debug and exception handling
815 const std::vector
<MCCFIInstruction
> &getFrameInstructions() const {
816 return FrameInstructions
;
819 LLVM_NODISCARD
unsigned addFrameInst(const MCCFIInstruction
&Inst
);
821 /// \name Exception Handling
824 bool callsEHReturn() const { return CallsEHReturn
; }
825 void setCallsEHReturn(bool b
) { CallsEHReturn
= b
; }
827 bool callsUnwindInit() const { return CallsUnwindInit
; }
828 void setCallsUnwindInit(bool b
) { CallsUnwindInit
= b
; }
830 bool hasEHScopes() const { return HasEHScopes
; }
831 void setHasEHScopes(bool V
) { HasEHScopes
= V
; }
833 bool hasEHFunclets() const { return HasEHFunclets
; }
834 void setHasEHFunclets(bool V
) { HasEHFunclets
= V
; }
836 /// Find or create an LandingPadInfo for the specified MachineBasicBlock.
837 LandingPadInfo
&getOrCreateLandingPadInfo(MachineBasicBlock
*LandingPad
);
839 /// Remap landing pad labels and remove any deleted landing pads.
840 void tidyLandingPads(DenseMap
<MCSymbol
*, uintptr_t> *LPMap
= nullptr,
841 bool TidyIfNoBeginLabels
= true);
843 /// Return a reference to the landing pad info for the current function.
844 const std::vector
<LandingPadInfo
> &getLandingPads() const {
848 /// Provide the begin and end labels of an invoke style call and associate it
849 /// with a try landing pad block.
850 void addInvoke(MachineBasicBlock
*LandingPad
,
851 MCSymbol
*BeginLabel
, MCSymbol
*EndLabel
);
853 /// Add a new panding pad, and extract the exception handling information from
854 /// the landingpad instruction. Returns the label ID for the landing pad
856 MCSymbol
*addLandingPad(MachineBasicBlock
*LandingPad
);
858 /// Provide the catch typeinfo for a landing pad.
859 void addCatchTypeInfo(MachineBasicBlock
*LandingPad
,
860 ArrayRef
<const GlobalValue
*> TyInfo
);
862 /// Provide the filter typeinfo for a landing pad.
863 void addFilterTypeInfo(MachineBasicBlock
*LandingPad
,
864 ArrayRef
<const GlobalValue
*> TyInfo
);
866 /// Add a cleanup action for a landing pad.
867 void addCleanup(MachineBasicBlock
*LandingPad
);
869 void addSEHCatchHandler(MachineBasicBlock
*LandingPad
, const Function
*Filter
,
870 const BlockAddress
*RecoverBA
);
872 void addSEHCleanupHandler(MachineBasicBlock
*LandingPad
,
873 const Function
*Cleanup
);
875 /// Return the type id for the specified typeinfo. This is function wide.
876 unsigned getTypeIDFor(const GlobalValue
*TI
);
878 /// Return the id of the filter encoded by TyIds. This is function wide.
879 int getFilterIDFor(std::vector
<unsigned> &TyIds
);
881 /// Map the landing pad's EH symbol to the call site indexes.
882 void setCallSiteLandingPad(MCSymbol
*Sym
, ArrayRef
<unsigned> Sites
);
884 /// Map the landing pad to its index. Used for Wasm exception handling.
885 void setWasmLandingPadIndex(const MachineBasicBlock
*LPad
, unsigned Index
) {
886 WasmLPadToIndexMap
[LPad
] = Index
;
889 /// Returns true if the landing pad has an associate index in wasm EH.
890 bool hasWasmLandingPadIndex(const MachineBasicBlock
*LPad
) const {
891 return WasmLPadToIndexMap
.count(LPad
);
894 /// Get the index in wasm EH for a given landing pad.
895 unsigned getWasmLandingPadIndex(const MachineBasicBlock
*LPad
) const {
896 assert(hasWasmLandingPadIndex(LPad
));
897 return WasmLPadToIndexMap
.lookup(LPad
);
900 /// Get the call site indexes for a landing pad EH symbol.
901 SmallVectorImpl
<unsigned> &getCallSiteLandingPad(MCSymbol
*Sym
) {
902 assert(hasCallSiteLandingPad(Sym
) &&
903 "missing call site number for landing pad!");
904 return LPadToCallSiteMap
[Sym
];
907 /// Return true if the landing pad Eh symbol has an associated call site.
908 bool hasCallSiteLandingPad(MCSymbol
*Sym
) {
909 return !LPadToCallSiteMap
[Sym
].empty();
912 /// Map the begin label for a call site.
913 void setCallSiteBeginLabel(MCSymbol
*BeginLabel
, unsigned Site
) {
914 CallSiteMap
[BeginLabel
] = Site
;
917 /// Get the call site number for a begin label.
918 unsigned getCallSiteBeginLabel(MCSymbol
*BeginLabel
) const {
919 assert(hasCallSiteBeginLabel(BeginLabel
) &&
920 "Missing call site number for EH_LABEL!");
921 return CallSiteMap
.lookup(BeginLabel
);
924 /// Return true if the begin label has a call site number associated with it.
925 bool hasCallSiteBeginLabel(MCSymbol
*BeginLabel
) const {
926 return CallSiteMap
.count(BeginLabel
);
929 /// Record annotations associated with a particular label.
930 void addCodeViewAnnotation(MCSymbol
*Label
, MDNode
*MD
) {
931 CodeViewAnnotations
.push_back({Label
, MD
});
934 ArrayRef
<std::pair
<MCSymbol
*, MDNode
*>> getCodeViewAnnotations() const {
935 return CodeViewAnnotations
;
938 /// Record heapallocsites
939 void addCodeViewHeapAllocSite(MachineInstr
*I
, const MDNode
*MD
);
941 ArrayRef
<std::tuple
<MCSymbol
*, MCSymbol
*, const DIType
*>>
942 getCodeViewHeapAllocSites() const {
943 return CodeViewHeapAllocSites
;
946 /// Return a reference to the C++ typeinfo for the current function.
947 const std::vector
<const GlobalValue
*> &getTypeInfos() const {
951 /// Return a reference to the typeids encoding filters used in the current
953 const std::vector
<unsigned> &getFilterIds() const {
959 /// Collect information used to emit debugging information of a variable.
960 void setVariableDbgInfo(const DILocalVariable
*Var
, const DIExpression
*Expr
,
961 int Slot
, const DILocation
*Loc
) {
962 VariableDbgInfos
.emplace_back(Var
, Expr
, Slot
, Loc
);
965 VariableDbgInfoMapTy
&getVariableDbgInfo() { return VariableDbgInfos
; }
966 const VariableDbgInfoMapTy
&getVariableDbgInfo() const {
967 return VariableDbgInfos
;
970 void addCallArgsForwardingRegs(const MachineInstr
*CallI
,
971 CallSiteInfoImpl
&&CallInfo
) {
972 assert(CallI
->isCall());
973 CallSitesInfo
[CallI
] = std::move(CallInfo
);
976 const CallSiteInfoMap
&getCallSitesInfo() const {
977 return CallSitesInfo
;
980 /// Update call sites info by deleting entry for \p Old call instruction.
981 /// If \p New is present then transfer \p Old call info to it. This function
982 /// should be called before removing call instruction or before replacing
983 /// call instruction with new one.
984 void updateCallSiteInfo(const MachineInstr
*Old
,
985 const MachineInstr
*New
= nullptr);
988 //===--------------------------------------------------------------------===//
989 // GraphTraits specializations for function basic block graphs (CFGs)
990 //===--------------------------------------------------------------------===//
992 // Provide specializations of GraphTraits to be able to treat a
993 // machine function as a graph of machine basic blocks... these are
994 // the same as the machine basic block iterators, except that the root
995 // node is implicitly the first node of the function.
997 template <> struct GraphTraits
<MachineFunction
*> :
998 public GraphTraits
<MachineBasicBlock
*> {
999 static NodeRef
getEntryNode(MachineFunction
*F
) { return &F
->front(); }
1001 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
1002 using nodes_iterator
= pointer_iterator
<MachineFunction::iterator
>;
1004 static nodes_iterator
nodes_begin(MachineFunction
*F
) {
1005 return nodes_iterator(F
->begin());
1008 static nodes_iterator
nodes_end(MachineFunction
*F
) {
1009 return nodes_iterator(F
->end());
1012 static unsigned size (MachineFunction
*F
) { return F
->size(); }
1014 template <> struct GraphTraits
<const MachineFunction
*> :
1015 public GraphTraits
<const MachineBasicBlock
*> {
1016 static NodeRef
getEntryNode(const MachineFunction
*F
) { return &F
->front(); }
1018 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
1019 using nodes_iterator
= pointer_iterator
<MachineFunction::const_iterator
>;
1021 static nodes_iterator
nodes_begin(const MachineFunction
*F
) {
1022 return nodes_iterator(F
->begin());
1025 static nodes_iterator
nodes_end (const MachineFunction
*F
) {
1026 return nodes_iterator(F
->end());
1029 static unsigned size (const MachineFunction
*F
) {
1034 // Provide specializations of GraphTraits to be able to treat a function as a
1035 // graph of basic blocks... and to walk it in inverse order. Inverse order for
1036 // a function is considered to be when traversing the predecessor edges of a BB
1037 // instead of the successor edges.
1039 template <> struct GraphTraits
<Inverse
<MachineFunction
*>> :
1040 public GraphTraits
<Inverse
<MachineBasicBlock
*>> {
1041 static NodeRef
getEntryNode(Inverse
<MachineFunction
*> G
) {
1042 return &G
.Graph
->front();
1045 template <> struct GraphTraits
<Inverse
<const MachineFunction
*>> :
1046 public GraphTraits
<Inverse
<const MachineBasicBlock
*>> {
1047 static NodeRef
getEntryNode(Inverse
<const MachineFunction
*> G
) {
1048 return &G
.Graph
->front();
1052 } // end namespace llvm
1054 #endif // LLVM_CODEGEN_MACHINEFUNCTION_H