[InstCombine] Signed saturation tests. NFC
[llvm-core.git] / include / llvm / CodeGen / MachineFunction.h
blob3a3176e51c51f81c2def689b3b0b9811f71d2979
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.
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"
39 #include "llvm/Target/TargetMachine.h"
40 #include <cassert>
41 #include <cstdint>
42 #include <memory>
43 #include <utility>
44 #include <vector>
46 namespace llvm {
48 class BasicBlock;
49 class BlockAddress;
50 class DataLayout;
51 class DebugLoc;
52 class DIExpression;
53 class DILocalVariable;
54 class DILocation;
55 class Function;
56 class GlobalValue;
57 class LLVMTargetMachine;
58 class MachineConstantPool;
59 class MachineFrameInfo;
60 class MachineFunction;
61 class MachineJumpTableInfo;
62 class MachineModuleInfo;
63 class MachineRegisterInfo;
64 class MCContext;
65 class MCInstrDesc;
66 class MCSymbol;
67 class Pass;
68 class PseudoSourceValueManager;
69 class raw_ostream;
70 class SlotIndexes;
71 class TargetRegisterClass;
72 class TargetSubtargetInfo;
73 struct WasmEHFuncInfo;
74 struct WinEHFuncInfo;
76 template <> struct ilist_alloc_traits<MachineBasicBlock> {
77 void deleteNode(MachineBasicBlock *MBB);
80 template <> struct ilist_callback_traits<MachineBasicBlock> {
81 void addNodeToList(MachineBasicBlock* N);
82 void removeNodeFromList(MachineBasicBlock* N);
84 template <class Iterator>
85 void transferNodesFromList(ilist_callback_traits &OldList, Iterator, Iterator) {
86 assert(this == &OldList && "never transfer MBBs between functions");
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.
94 struct MachineFunctionInfo {
95 virtual ~MachineFunctionInfo();
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);
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.
110 class 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"
116 public:
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.
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,
158 bool hasProperty(Property P) const {
159 return Properties[static_cast<unsigned>(P)];
162 MachineFunctionProperties &set(Property P) {
163 Properties.set(static_cast<unsigned>(P));
164 return *this;
167 MachineFunctionProperties &reset(Property P) {
168 Properties.reset(static_cast<unsigned>(P));
169 return *this;
172 /// Reset all the properties.
173 MachineFunctionProperties &reset() {
174 Properties.reset();
175 return *this;
178 MachineFunctionProperties &set(const MachineFunctionProperties &MFP) {
179 Properties |= MFP.Properties;
180 return *this;
183 MachineFunctionProperties &reset(const MachineFunctionProperties &MFP) {
184 Properties.reset(MFP.Properties);
185 return *this;
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);
194 /// Print the MachineFunctionProperties in human-readable form.
195 void print(raw_ostream &OS) const;
197 private:
198 BitVector Properties =
199 BitVector(static_cast<unsigned>(Property::LastProperty)+1);
202 struct SEHHandler {
203 /// Filter or finally function. Null indicates a catch-all.
204 const Function *FilterOrFinally;
206 /// Address of block to recover at. Null for a finally handler.
207 const BlockAddress *RecoverBA;
210 /// This structure is used to retain landing pad info for the current function.
211 struct 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).
219 explicit LandingPadInfo(MachineBasicBlock *MBB)
220 : LandingPadBlock(MBB) {}
223 class MachineFunction {
224 const Function &F;
225 const LLVMTargetMachine &Target;
226 const TargetSubtargetInfo *STI;
227 MCContext &Ctx;
228 MachineModuleInfo &MMI;
230 // RegInfo - Information about each register in use in the function.
231 MachineRegisterInfo *RegInfo;
233 // Used to keep track of target-specific per-machine function information for
234 // the target implementation.
235 MachineFunctionInfo *MFInfo;
237 // Keep track of objects allocated on the stack.
238 MachineFrameInfo *FrameInfo;
240 // Keep track of constants which are spilled to memory
241 MachineConstantPool *ConstantPool;
243 // Keep track of jump tables for switch instructions
244 MachineJumpTableInfo *JumpTableInfo;
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;
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;
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;
259 // Pool-allocate MachineFunction-lifetime and IR objects.
260 BumpPtrAllocator Allocator;
262 // Allocation management for instructions in function.
263 Recycler<MachineInstr> InstructionRecycler;
265 // Allocation management for operand arrays on instructions.
266 ArrayRecycler<MachineOperand> OperandRecycler;
268 // Allocation management for basic blocks in function.
269 Recycler<MachineBasicBlock> BasicBlockRecycler;
271 // List of machine basic blocks in function
272 using BasicBlockListType = ilist<MachineBasicBlock>;
273 BasicBlockListType BasicBlocks;
275 /// FunctionNumber - This provides a unique ID for each function emitted in
276 /// this translation unit.
278 unsigned FunctionNumber;
280 /// Alignment - The alignment of the function.
281 Align Alignment;
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;
290 /// True if the function includes any inline assembly.
291 bool HasInlineAsm = false;
293 /// True if any WinCFI instruction have been emitted in this function.
294 bool HasWinCFI = false;
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;
300 // Allocation management for pseudo source values.
301 std::unique_ptr<PseudoSourceValueManager> PSVManager;
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;
307 /// \name Exception Handling
308 /// \{
310 /// List of LandingPadInfo describing the landing pad information.
311 std::vector<LandingPadInfo> LandingPads;
313 /// Map a landing pad's EH symbol to the call site indexes.
314 DenseMap<MCSymbol*, SmallVector<unsigned, 4>> LPadToCallSiteMap;
316 /// Map a landing pad to its index.
317 DenseMap<const MachineBasicBlock *, unsigned> WasmLPadToIndexMap;
319 /// Map of invoke call site index values to associated begin EH_LABEL.
320 DenseMap<MCSymbol*, unsigned> CallSiteMap;
322 /// CodeView label annotations.
323 std::vector<std::pair<MCSymbol *, MDNode *>> CodeViewAnnotations;
325 /// CodeView heapallocsites.
326 std::vector<std::tuple<MCSymbol *, MCSymbol *, const DIType *>>
327 CodeViewHeapAllocSites;
329 bool CallsEHReturn = false;
330 bool CallsUnwindInit = false;
331 bool HasEHScopes = false;
332 bool HasEHFunclets = false;
334 /// List of C++ TypeInfo used.
335 std::vector<const GlobalValue *> TypeInfos;
337 /// List of typeids encoding filters used.
338 std::vector<unsigned> FilterIds;
340 /// List of the indices in FilterIds corresponding to filter terminators.
341 std::vector<unsigned> FilterEnds;
343 EHPersonality PersonalityTypeCache = EHPersonality::Unknown;
345 /// \}
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();
358 public:
359 struct VariableDbgInfo {
360 const DILocalVariable *Var;
361 const DIExpression *Expr;
362 // The Slot can be negative for fixed stack objects.
363 int Slot;
364 const DILocation *Loc;
366 VariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr,
367 int Slot, const DILocation *Loc)
368 : Var(Var), Expr(Expr), Slot(Slot), Loc(Loc) {}
371 class Delegate {
372 virtual void anchor();
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;
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");
393 /// Vector of call argument and its forwarding register.
394 using CallSiteInfo = SmallVector<ArgRegPair, 1>;
395 using CallSiteInfoImpl = SmallVectorImpl<ArgRegPair>;
397 private:
398 Delegate *TheDelegate = nullptr;
400 using CallSiteInfoMap = DenseMap<const MachineInstr *, CallSiteInfo>;
401 /// Map a call instruction to call site arguments forwarding info.
402 CallSiteInfoMap CallSitesInfo;
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 assert(MI->isCall() &&
408 "Call site info refers only to call instructions!");
410 if (!Target.Options.EnableDebugEntryValues)
411 return CallSitesInfo.end();
412 return CallSitesInfo.find(MI);
415 // Callbacks for insertion and removal.
416 void handleInsertion(MachineInstr &MI);
417 void handleRemoval(MachineInstr &MI);
418 friend struct ilist_traits<MachineInstr>;
420 public:
421 using VariableDbgInfoMapTy = SmallVector<VariableDbgInfo, 4>;
422 VariableDbgInfoMapTy VariableDbgInfos;
424 MachineFunction(const Function &F, const LLVMTargetMachine &Target,
425 const TargetSubtargetInfo &STI, unsigned FunctionNum,
426 MachineModuleInfo &MMI);
427 MachineFunction(const MachineFunction &) = delete;
428 MachineFunction &operator=(const MachineFunction &) = delete;
429 ~MachineFunction();
431 /// Reset the instance as if it was just created.
432 void reset() {
433 clear();
434 init();
437 /// Reset the currently registered delegate - otherwise assert.
438 void resetDelegate(Delegate *delegate) {
439 assert(TheDelegate == delegate &&
440 "Only the current delegate can perform reset!");
441 TheDelegate = nullptr;
444 /// Set the delegate. resetDelegate must be called before attempting
445 /// to set.
446 void setDelegate(Delegate *delegate) {
447 assert(delegate && !TheDelegate &&
448 "Attempted to set delegate to null, or to change it without "
449 "first resetting it!");
451 TheDelegate = delegate;
454 MachineModuleInfo &getMMI() const { return MMI; }
455 MCContext &getContext() const { return Ctx; }
457 PseudoSourceValueManager &getPSVManager() const { return *PSVManager; }
459 /// Return the DataLayout attached to the Module associated to this MF.
460 const DataLayout &getDataLayout() const;
462 /// Return the LLVM function that this machine code represents
463 const Function &getFunction() const { return F; }
465 /// getName - Return the name of the corresponding LLVM function.
466 StringRef getName() const;
468 /// getFunctionNumber - Return a unique ID for the current function.
469 unsigned getFunctionNumber() const { return FunctionNumber; }
471 /// getTarget - Return the target machine this machine code is compiled with
472 const LLVMTargetMachine &getTarget() const { return Target; }
474 /// getSubtarget - Return the subtarget for which this machine code is being
475 /// compiled.
476 const TargetSubtargetInfo &getSubtarget() const { return *STI; }
478 /// getSubtarget - This method returns a pointer to the specified type of
479 /// TargetSubtargetInfo. In debug builds, it verifies that the object being
480 /// returned is of the correct type.
481 template<typename STC> const STC &getSubtarget() const {
482 return *static_cast<const STC *>(STI);
485 /// getRegInfo - Return information about the registers currently in use.
486 MachineRegisterInfo &getRegInfo() { return *RegInfo; }
487 const MachineRegisterInfo &getRegInfo() const { return *RegInfo; }
489 /// getFrameInfo - Return the frame info object for the current function.
490 /// This object contains information about objects allocated on the stack
491 /// frame of the current function in an abstract way.
492 MachineFrameInfo &getFrameInfo() { return *FrameInfo; }
493 const MachineFrameInfo &getFrameInfo() const { return *FrameInfo; }
495 /// getJumpTableInfo - Return the jump table info object for the current
496 /// function. This object contains information about jump tables in the
497 /// current function. If the current function has no jump tables, this will
498 /// return null.
499 const MachineJumpTableInfo *getJumpTableInfo() const { return JumpTableInfo; }
500 MachineJumpTableInfo *getJumpTableInfo() { return JumpTableInfo; }
502 /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
503 /// does already exist, allocate one.
504 MachineJumpTableInfo *getOrCreateJumpTableInfo(unsigned JTEntryKind);
506 /// getConstantPool - Return the constant pool object for the current
507 /// function.
508 MachineConstantPool *getConstantPool() { return ConstantPool; }
509 const MachineConstantPool *getConstantPool() const { return ConstantPool; }
511 /// getWasmEHFuncInfo - Return information about how the current function uses
512 /// Wasm exception handling. Returns null for functions that don't use wasm
513 /// exception handling.
514 const WasmEHFuncInfo *getWasmEHFuncInfo() const { return WasmEHInfo; }
515 WasmEHFuncInfo *getWasmEHFuncInfo() { return WasmEHInfo; }
517 /// getWinEHFuncInfo - Return information about how the current function uses
518 /// Windows exception handling. Returns null for functions that don't use
519 /// funclets for exception handling.
520 const WinEHFuncInfo *getWinEHFuncInfo() const { return WinEHInfo; }
521 WinEHFuncInfo *getWinEHFuncInfo() { return WinEHInfo; }
523 /// getAlignment - Return the alignment of the function.
524 Align getAlignment() const { return Alignment; }
526 /// setAlignment - Set the alignment of the function.
527 void setAlignment(Align A) { Alignment = A; }
529 /// ensureAlignment - Make sure the function is at least A bytes aligned.
530 void ensureAlignment(Align A) {
531 if (Alignment < A)
532 Alignment = A;
535 /// exposesReturnsTwice - Returns true if the function calls setjmp or
536 /// any other similar functions with attribute "returns twice" without
537 /// having the attribute itself.
538 bool exposesReturnsTwice() const {
539 return ExposesReturnsTwice;
542 /// setCallsSetJmp - Set a flag that indicates if there's a call to
543 /// a "returns twice" function.
544 void setExposesReturnsTwice(bool B) {
545 ExposesReturnsTwice = B;
548 /// Returns true if the function contains any inline assembly.
549 bool hasInlineAsm() const {
550 return HasInlineAsm;
553 /// Set a flag that indicates that the function contains inline assembly.
554 void setHasInlineAsm(bool B) {
555 HasInlineAsm = B;
558 bool hasWinCFI() const {
559 return HasWinCFI;
561 void setHasWinCFI(bool v) { HasWinCFI = v; }
563 /// Get the function properties
564 const MachineFunctionProperties &getProperties() const { return Properties; }
565 MachineFunctionProperties &getProperties() { return Properties; }
567 /// getInfo - Keep track of various per-function pieces of information for
568 /// backends that would like to do so.
570 template<typename Ty>
571 Ty *getInfo() {
572 if (!MFInfo)
573 MFInfo = Ty::template create<Ty>(Allocator, *this);
574 return static_cast<Ty*>(MFInfo);
577 template<typename Ty>
578 const Ty *getInfo() const {
579 return const_cast<MachineFunction*>(this)->getInfo<Ty>();
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];
592 /// Should we be emitting segmented stack stuff for the function
593 bool shouldSplitStack() const;
595 /// getNumBlockIDs - Return the number of MBB ID's allocated.
596 unsigned getNumBlockIDs() const { return (unsigned)MBBNumbering.size(); }
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);
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;
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;
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.
621 void viewCFGOnly() const;
623 /// dump - Print the current MachineFunction to cerr, useful for debugger use.
624 void dump() const;
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;
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;
638 /// Support for MachineBasicBlock::getNextNode().
639 static BasicBlockListType MachineFunction::*
640 getSublistAccess(MachineBasicBlock *) {
641 return &MachineFunction::BasicBlocks;
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);
648 //===--------------------------------------------------------------------===//
649 // BasicBlock accessor functions.
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(); }
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(); }
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(); }
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);
673 void splice(iterator InsertPt, iterator MBBI) {
674 BasicBlocks.splice(InsertPt, BasicBlocks, MBBI);
676 void splice(iterator InsertPt, MachineBasicBlock *MBB) {
677 BasicBlocks.splice(InsertPt, BasicBlocks, MBB);
679 void splice(iterator InsertPt, iterator MBBI, iterator MBBE) {
680 BasicBlocks.splice(InsertPt, BasicBlocks, MBBI, MBBE);
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); }
688 template <typename Comp>
689 void sort(Comp comp) {
690 BasicBlocks.sort(comp);
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;
701 //===--------------------------------------------------------------------===//
702 // Internal functions used to automatically number MachineBasicBlocks
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;
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;
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);
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.
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);
733 /// Clones instruction or the whole instruction bundle \p Orig and insert
734 /// into \p MBB before \p InsertBefore.
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);
741 /// DeleteMachineInstr - Delete the given MachineInstr.
742 void DeleteMachineInstr(MachineInstr *MI);
744 /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
745 /// instead of `new MachineBasicBlock'.
746 MachineBasicBlock *CreateMachineBasicBlock(const BasicBlock *bb = nullptr);
748 /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
749 void DeleteMachineBasicBlock(MachineBasicBlock *MBB);
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);
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);
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);
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);
781 using OperandCapacity = ArrayRecycler<MachineOperand>::Capacity;
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);
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);
796 /// Allocate and initialize a register mask with @p NumRegister bits.
797 uint32_t *allocateRegMask();
799 /// Allocate and construct an extra info structure for a `MachineInstr`.
801 /// This is allocated on the function's allocator and so lives the life of
802 /// the function.
803 MachineInstr::ExtraInfo *
804 createMIExtraInfo(ArrayRef<MachineMemOperand *> MMOs,
805 MCSymbol *PreInstrSymbol = nullptr,
806 MCSymbol *PostInstrSymbol = nullptr);
808 /// Allocate a string and populate it with the given external symbol name.
809 const char *createExternalSymbolName(StringRef Name);
811 //===--------------------------------------------------------------------===//
812 // Label Manipulation.
814 /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
815 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
816 /// normal 'L' label is returned.
817 MCSymbol *getJTISymbol(unsigned JTI, MCContext &Ctx,
818 bool isLinkerPrivate = false) const;
820 /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
821 /// base.
822 MCSymbol *getPICBaseSymbol() const;
824 /// Returns a reference to a list of cfi instructions in the function's
825 /// prologue. Used to construct frame maps for debug and exception handling
826 /// comsumers.
827 const std::vector<MCCFIInstruction> &getFrameInstructions() const {
828 return FrameInstructions;
831 LLVM_NODISCARD unsigned addFrameInst(const MCCFIInstruction &Inst);
833 /// \name Exception Handling
834 /// \{
836 bool callsEHReturn() const { return CallsEHReturn; }
837 void setCallsEHReturn(bool b) { CallsEHReturn = b; }
839 bool callsUnwindInit() const { return CallsUnwindInit; }
840 void setCallsUnwindInit(bool b) { CallsUnwindInit = b; }
842 bool hasEHScopes() const { return HasEHScopes; }
843 void setHasEHScopes(bool V) { HasEHScopes = V; }
845 bool hasEHFunclets() const { return HasEHFunclets; }
846 void setHasEHFunclets(bool V) { HasEHFunclets = V; }
848 /// Find or create an LandingPadInfo for the specified MachineBasicBlock.
849 LandingPadInfo &getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad);
851 /// Remap landing pad labels and remove any deleted landing pads.
852 void tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap = nullptr,
853 bool TidyIfNoBeginLabels = true);
855 /// Return a reference to the landing pad info for the current function.
856 const std::vector<LandingPadInfo> &getLandingPads() const {
857 return LandingPads;
860 /// Provide the begin and end labels of an invoke style call and associate it
861 /// with a try landing pad block.
862 void addInvoke(MachineBasicBlock *LandingPad,
863 MCSymbol *BeginLabel, MCSymbol *EndLabel);
865 /// Add a new panding pad, and extract the exception handling information from
866 /// the landingpad instruction. Returns the label ID for the landing pad
867 /// entry.
868 MCSymbol *addLandingPad(MachineBasicBlock *LandingPad);
870 /// Provide the catch typeinfo for a landing pad.
871 void addCatchTypeInfo(MachineBasicBlock *LandingPad,
872 ArrayRef<const GlobalValue *> TyInfo);
874 /// Provide the filter typeinfo for a landing pad.
875 void addFilterTypeInfo(MachineBasicBlock *LandingPad,
876 ArrayRef<const GlobalValue *> TyInfo);
878 /// Add a cleanup action for a landing pad.
879 void addCleanup(MachineBasicBlock *LandingPad);
881 void addSEHCatchHandler(MachineBasicBlock *LandingPad, const Function *Filter,
882 const BlockAddress *RecoverBA);
884 void addSEHCleanupHandler(MachineBasicBlock *LandingPad,
885 const Function *Cleanup);
887 /// Return the type id for the specified typeinfo. This is function wide.
888 unsigned getTypeIDFor(const GlobalValue *TI);
890 /// Return the id of the filter encoded by TyIds. This is function wide.
891 int getFilterIDFor(std::vector<unsigned> &TyIds);
893 /// Map the landing pad's EH symbol to the call site indexes.
894 void setCallSiteLandingPad(MCSymbol *Sym, ArrayRef<unsigned> Sites);
896 /// Map the landing pad to its index. Used for Wasm exception handling.
897 void setWasmLandingPadIndex(const MachineBasicBlock *LPad, unsigned Index) {
898 WasmLPadToIndexMap[LPad] = Index;
901 /// Returns true if the landing pad has an associate index in wasm EH.
902 bool hasWasmLandingPadIndex(const MachineBasicBlock *LPad) const {
903 return WasmLPadToIndexMap.count(LPad);
906 /// Get the index in wasm EH for a given landing pad.
907 unsigned getWasmLandingPadIndex(const MachineBasicBlock *LPad) const {
908 assert(hasWasmLandingPadIndex(LPad));
909 return WasmLPadToIndexMap.lookup(LPad);
912 /// Get the call site indexes for a landing pad EH symbol.
913 SmallVectorImpl<unsigned> &getCallSiteLandingPad(MCSymbol *Sym) {
914 assert(hasCallSiteLandingPad(Sym) &&
915 "missing call site number for landing pad!");
916 return LPadToCallSiteMap[Sym];
919 /// Return true if the landing pad Eh symbol has an associated call site.
920 bool hasCallSiteLandingPad(MCSymbol *Sym) {
921 return !LPadToCallSiteMap[Sym].empty();
924 /// Map the begin label for a call site.
925 void setCallSiteBeginLabel(MCSymbol *BeginLabel, unsigned Site) {
926 CallSiteMap[BeginLabel] = Site;
929 /// Get the call site number for a begin label.
930 unsigned getCallSiteBeginLabel(MCSymbol *BeginLabel) const {
931 assert(hasCallSiteBeginLabel(BeginLabel) &&
932 "Missing call site number for EH_LABEL!");
933 return CallSiteMap.lookup(BeginLabel);
936 /// Return true if the begin label has a call site number associated with it.
937 bool hasCallSiteBeginLabel(MCSymbol *BeginLabel) const {
938 return CallSiteMap.count(BeginLabel);
941 /// Record annotations associated with a particular label.
942 void addCodeViewAnnotation(MCSymbol *Label, MDNode *MD) {
943 CodeViewAnnotations.push_back({Label, MD});
946 ArrayRef<std::pair<MCSymbol *, MDNode *>> getCodeViewAnnotations() const {
947 return CodeViewAnnotations;
950 /// Record heapallocsites
951 void addCodeViewHeapAllocSite(MachineInstr *I, const MDNode *MD);
953 ArrayRef<std::tuple<MCSymbol *, MCSymbol *, const DIType *>>
954 getCodeViewHeapAllocSites() const {
955 return CodeViewHeapAllocSites;
958 /// Return a reference to the C++ typeinfo for the current function.
959 const std::vector<const GlobalValue *> &getTypeInfos() const {
960 return TypeInfos;
963 /// Return a reference to the typeids encoding filters used in the current
964 /// function.
965 const std::vector<unsigned> &getFilterIds() const {
966 return FilterIds;
969 /// \}
971 /// Collect information used to emit debugging information of a variable.
972 void setVariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr,
973 int Slot, const DILocation *Loc) {
974 VariableDbgInfos.emplace_back(Var, Expr, Slot, Loc);
977 VariableDbgInfoMapTy &getVariableDbgInfo() { return VariableDbgInfos; }
978 const VariableDbgInfoMapTy &getVariableDbgInfo() const {
979 return VariableDbgInfos;
982 void addCallArgsForwardingRegs(const MachineInstr *CallI,
983 CallSiteInfoImpl &&CallInfo) {
984 assert(CallI->isCall());
985 CallSitesInfo[CallI] = std::move(CallInfo);
988 const CallSiteInfoMap &getCallSitesInfo() const {
989 return CallSitesInfo;
992 /// Following functions update call site info. They should be called before
993 /// removing, replacing or copying call instruction.
995 /// Move the call site info from \p Old to \New call site info. This function
996 /// is used when we are replacing one call instruction with another one to
997 /// the same callee.
998 void moveCallSiteInfo(const MachineInstr *Old,
999 const MachineInstr *New);
1001 /// Erase the call site info for \p MI. It is used to remove a call
1002 /// instruction from the instruction stream.
1003 void eraseCallSiteInfo(const MachineInstr *MI);
1005 /// Copy the call site info from \p Old to \ New. Its usage is when we are
1006 /// making a copy of the instruction that will be inserted at different point
1007 /// of the instruction stream.
1008 void copyCallSiteInfo(const MachineInstr *Old,
1009 const MachineInstr *New);
1012 //===--------------------------------------------------------------------===//
1013 // GraphTraits specializations for function basic block graphs (CFGs)
1014 //===--------------------------------------------------------------------===//
1016 // Provide specializations of GraphTraits to be able to treat a
1017 // machine function as a graph of machine basic blocks... these are
1018 // the same as the machine basic block iterators, except that the root
1019 // node is implicitly the first node of the function.
1021 template <> struct GraphTraits<MachineFunction*> :
1022 public GraphTraits<MachineBasicBlock*> {
1023 static NodeRef getEntryNode(MachineFunction *F) { return &F->front(); }
1025 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
1026 using nodes_iterator = pointer_iterator<MachineFunction::iterator>;
1028 static nodes_iterator nodes_begin(MachineFunction *F) {
1029 return nodes_iterator(F->begin());
1032 static nodes_iterator nodes_end(MachineFunction *F) {
1033 return nodes_iterator(F->end());
1036 static unsigned size (MachineFunction *F) { return F->size(); }
1038 template <> struct GraphTraits<const MachineFunction*> :
1039 public GraphTraits<const MachineBasicBlock*> {
1040 static NodeRef getEntryNode(const MachineFunction *F) { return &F->front(); }
1042 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
1043 using nodes_iterator = pointer_iterator<MachineFunction::const_iterator>;
1045 static nodes_iterator nodes_begin(const MachineFunction *F) {
1046 return nodes_iterator(F->begin());
1049 static nodes_iterator nodes_end (const MachineFunction *F) {
1050 return nodes_iterator(F->end());
1053 static unsigned size (const MachineFunction *F) {
1054 return F->size();
1058 // Provide specializations of GraphTraits to be able to treat a function as a
1059 // graph of basic blocks... and to walk it in inverse order. Inverse order for
1060 // a function is considered to be when traversing the predecessor edges of a BB
1061 // instead of the successor edges.
1063 template <> struct GraphTraits<Inverse<MachineFunction*>> :
1064 public GraphTraits<Inverse<MachineBasicBlock*>> {
1065 static NodeRef getEntryNode(Inverse<MachineFunction *> G) {
1066 return &G.Graph->front();
1069 template <> struct GraphTraits<Inverse<const MachineFunction*>> :
1070 public GraphTraits<Inverse<const MachineBasicBlock*>> {
1071 static NodeRef getEntryNode(Inverse<const MachineFunction *> G) {
1072 return &G.Graph->front();
1076 } // end namespace llvm
1078 #endif // LLVM_CODEGEN_MACHINEFUNCTION_H