LLVM 20.0.0git
SelectionDAGISel.h
Go to the documentation of this file.
1//===-- llvm/CodeGen/SelectionDAGISel.h - Common Base Class------*- 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// This file implements the SelectionDAGISel class, which is used as the common
10// base class for SelectionDAG-based instruction selectors.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CODEGEN_SELECTIONDAGISEL_H
15#define LLVM_CODEGEN_SELECTIONDAGISEL_H
16
21#include "llvm/IR/BasicBlock.h"
22#include <memory>
23
24namespace llvm {
25class AAResults;
26class AssumptionCache;
27class TargetInstrInfo;
28class TargetMachine;
29class SSPLayoutInfo;
30class SelectionDAGBuilder;
31class SDValue;
32class MachineRegisterInfo;
33class MachineFunction;
34class OptimizationRemarkEmitter;
35class TargetLowering;
36class TargetLibraryInfo;
37class TargetTransformInfo;
38class FunctionLoweringInfo;
39class SwiftErrorValueTracking;
40class GCFunctionInfo;
41class ScheduleDAGSDNodes;
42
43/// SelectionDAGISel - This is the common base class used for SelectionDAG-based
44/// pattern-matching instruction selectors.
46public:
49 std::unique_ptr<FunctionLoweringInfo> FuncInfo;
55 std::unique_ptr<SelectionDAGBuilder> SDB;
56 mutable std::optional<BatchAAResults> BatchAA;
57 AssumptionCache *AC = nullptr;
58 GCFunctionInfo *GFI = nullptr;
59 SSPLayoutInfo *SP = nullptr;
60#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
61 TargetTransformInfo *TTI = nullptr;
62#endif
68
69 /// Current optimization remark emitter.
70 /// Used to report things like combines and FastISel failures.
71 std::unique_ptr<OptimizationRemarkEmitter> ORE;
72
73 /// True if the function currently processing is in the function printing list
74 /// (i.e. `-filter-print-funcs`).
75 /// This is primarily used by ISEL_DUMP, which spans in multiple member
76 /// functions. Storing the filter result here so that we only need to do the
77 /// filtering once.
78 bool MatchFilterFuncName = false;
80
83 virtual ~SelectionDAGISel();
84
85 /// Returns a (possibly null) pointer to the current BatchAAResults.
87 if (BatchAA.has_value())
88 return &BatchAA.value();
89 return nullptr;
90 }
91
92 const TargetLowering *getTargetLowering() const { return TLI; }
93
96
97 virtual bool runOnMachineFunction(MachineFunction &mf);
98
99 virtual void emitFunctionEntryCode() {}
100
101 /// PreprocessISelDAG - This hook allows targets to hack on the graph before
102 /// instruction selection starts.
103 virtual void PreprocessISelDAG() {}
104
105 /// PostprocessISelDAG() - This hook allows the target to hack on the graph
106 /// right after selection.
107 virtual void PostprocessISelDAG() {}
108
109 /// Main hook for targets to transform nodes into machine nodes.
110 virtual void Select(SDNode *N) = 0;
111
112 /// SelectInlineAsmMemoryOperand - Select the specified address as a target
113 /// addressing mode, according to the specified constraint. If this does
114 /// not match or is not implemented, return true. The resultant operands
115 /// (which will appear in the machine instruction) should be added to the
116 /// OutOps vector.
117 virtual bool
119 InlineAsm::ConstraintCode ConstraintID,
120 std::vector<SDValue> &OutOps) {
121 return true;
122 }
123
124 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
125 /// operand node N of U during instruction selection that starts at Root.
126 virtual bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const;
127
128 /// IsLegalToFold - Returns true if the specific operand node N of
129 /// U can be folded during instruction selection that starts at Root.
130 /// FIXME: This is a static member function because the MSP430/X86
131 /// targets, which uses it during isel. This could become a proper member.
132 static bool IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
134 bool IgnoreChains = false);
135
136 static void InvalidateNodeId(SDNode *N);
137 static int getUninvalidatedNodeId(SDNode *N);
138
139 static void EnforceNodeIdInvariant(SDNode *N);
140
141 // Opcodes used by the DAG state machine:
202 // Space-optimized forms that implicitly encode VT.
215
224
233
257
259 // Space-optimized forms that implicitly encode integer VT.
265 // Space-optimized forms that implicitly encode integer VT.
296 // Space-optimized forms that implicitly encode number of result VTs.
300 // Space-optimized forms that implicitly encode EmitNodeInfo.
308 // Space-optimized forms that implicitly encode number of result VTs.
312 // Space-optimized forms that implicitly encode EmitNodeInfo.
326 // Contains 32-bit offset in table for pattern being selected
328 };
329
330 enum {
331 OPFL_None = 0, // Node has no chain or glue input and isn't variadic.
332 OPFL_Chain = 1, // Node has a chain input.
333 OPFL_GlueInput = 2, // Node has a glue input.
334 OPFL_GlueOutput = 4, // Node has a glue output.
335 OPFL_MemRefs = 8, // Node gets accumulated MemRefs.
336 OPFL_Variadic0 = 1<<4, // Node is variadic, root has 0 fixed inputs.
337 OPFL_Variadic1 = 2<<4, // Node is variadic, root has 1 fixed inputs.
338 OPFL_Variadic2 = 3<<4, // Node is variadic, root has 2 fixed inputs.
339 OPFL_Variadic3 = 4<<4, // Node is variadic, root has 3 fixed inputs.
340 OPFL_Variadic4 = 5<<4, // Node is variadic, root has 4 fixed inputs.
341 OPFL_Variadic5 = 6<<4, // Node is variadic, root has 5 fixed inputs.
342 OPFL_Variadic6 = 7<<4, // Node is variadic, root has 6 fixed inputs.
343
345 };
346
347 /// getNumFixedFromVariadicInfo - Transform an EmitNode flags word into the
348 /// number of fixed arity values that should be skipped when copying from the
349 /// root.
350 static inline int getNumFixedFromVariadicInfo(unsigned Flags) {
351 return ((Flags&OPFL_VariadicInfo) >> 4)-1;
352 }
353
354
355protected:
356 /// DAGSize - Size of DAG being instruction selected.
357 ///
358 unsigned DAGSize = 0;
359
360 /// ReplaceUses - replace all uses of the old node F with the use
361 /// of the new node T.
364 EnforceNodeIdInvariant(T.getNode());
365 }
366
367 /// ReplaceUses - replace all uses of the old nodes F with the use
368 /// of the new nodes T.
369 void ReplaceUses(const SDValue *F, const SDValue *T, unsigned Num) {
371 for (unsigned i = 0; i < Num; ++i)
373 }
374
375 /// ReplaceUses - replace all uses of the old node F with the use
376 /// of the new node T.
380 }
381
382 /// Replace all uses of \c F with \c T, then remove \c F from the DAG.
387 }
388
389 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
390 /// by tblgen. Others should not call it.
391 void SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops,
392 const SDLoc &DL);
393
394 /// getPatternForIndex - Patterns selected by tablegen during ISEL
395 virtual StringRef getPatternForIndex(unsigned index) {
396 llvm_unreachable("Tblgen should generate the implementation of this!");
397 }
398
399 /// getIncludePathForIndex - get the td source location of pattern instantiation
400 virtual StringRef getIncludePathForIndex(unsigned index) {
401 llvm_unreachable("Tblgen should generate the implementation of this!");
402 }
403
405 return CurDAG->shouldOptForSize();
406 }
407
408public:
409 // Calls to these predicates are generated by tblgen.
411 int64_t DesiredMaskS) const;
413 int64_t DesiredMaskS) const;
414
415
416 /// CheckPatternPredicate - This function is generated by tblgen in the
417 /// target. It runs the specified pattern predicate and returns true if it
418 /// succeeds or false if it fails. The number is a private implementation
419 /// detail to the code tblgen produces.
420 virtual bool CheckPatternPredicate(unsigned PredNo) const {
421 llvm_unreachable("Tblgen should generate the implementation of this!");
422 }
423
424 /// CheckNodePredicate - This function is generated by tblgen in the target.
425 /// It runs node predicate number PredNo and returns true if it succeeds or
426 /// false if it fails. The number is a private implementation
427 /// detail to the code tblgen produces.
428 virtual bool CheckNodePredicate(SDNode *N, unsigned PredNo) const {
429 llvm_unreachable("Tblgen should generate the implementation of this!");
430 }
431
432 /// CheckNodePredicateWithOperands - This function is generated by tblgen in
433 /// the target.
434 /// It runs node predicate number PredNo and returns true if it succeeds or
435 /// false if it fails. The number is a private implementation detail to the
436 /// code tblgen produces.
438 SDNode *N, unsigned PredNo,
439 const SmallVectorImpl<SDValue> &Operands) const {
440 llvm_unreachable("Tblgen should generate the implementation of this!");
441 }
442
443 virtual bool CheckComplexPattern(SDNode *Root, SDNode *Parent, SDValue N,
444 unsigned PatternNo,
445 SmallVectorImpl<std::pair<SDValue, SDNode*> > &Result) {
446 llvm_unreachable("Tblgen should generate the implementation of this!");
447 }
448
449 virtual SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {
450 llvm_unreachable("Tblgen should generate this!");
451 }
452
453 void SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
454 unsigned TableSize);
455
456 /// Return true if complex patterns for this target can mutate the
457 /// DAG.
458 virtual bool ComplexPatternFuncMutatesDAG() const {
459 return false;
460 }
461
462 /// Return whether the node may raise an FP exception.
463 bool mayRaiseFPException(SDNode *Node) const;
464
465 bool isOrEquivalentToAdd(const SDNode *N) const;
466
467private:
468
469 // Calls to these functions are generated by tblgen.
470 void Select_INLINEASM(SDNode *N);
471 void Select_READ_REGISTER(SDNode *Op);
472 void Select_WRITE_REGISTER(SDNode *Op);
473 void Select_UNDEF(SDNode *N);
474 void Select_FAKE_USE(SDNode *N);
475 void CannotYetSelect(SDNode *N);
476
477 void Select_FREEZE(SDNode *N);
478 void Select_ARITH_FENCE(SDNode *N);
479 void Select_MEMBARRIER(SDNode *N);
480
481 void Select_CONVERGENCECTRL_ANCHOR(SDNode *N);
482 void Select_CONVERGENCECTRL_ENTRY(SDNode *N);
483 void Select_CONVERGENCECTRL_LOOP(SDNode *N);
484
485 void pushStackMapLiveVariable(SmallVectorImpl<SDValue> &Ops, SDValue Operand,
486 SDLoc DL);
487 void Select_STACKMAP(SDNode *N);
488 void Select_PATCHPOINT(SDNode *N);
489
490 void Select_JUMP_TABLE_DEBUG_INFO(SDNode *N);
491
492private:
493 void DoInstructionSelection();
494 SDNode *MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
495 ArrayRef<SDValue> Ops, unsigned EmitNodeInfo);
496
497 /// Prepares the landing pad to take incoming values or do other EH
498 /// personality specific tasks. Returns true if the block should be
499 /// instruction selected, false if no code should be emitted for it.
500 bool PrepareEHLandingPad();
501
502 // Mark and Report IPToState for each Block under AsynchEH
503 void reportIPToStateForBlocks(MachineFunction *Fn);
504
505 /// Perform instruction selection on all basic blocks in the function.
506 void SelectAllBasicBlocks(const Function &Fn);
507
508 /// Perform instruction selection on a single basic block, for
509 /// instructions between \p Begin and \p End. \p HadTailCall will be set
510 /// to true if a call in the block was translated as a tail call.
511 void SelectBasicBlock(BasicBlock::const_iterator Begin,
513 bool &HadTailCall);
514 void FinishBasicBlock();
515
516 void CodeGenAndEmitDAG();
517
518 /// Generate instructions for lowering the incoming arguments of the
519 /// given function.
520 void LowerArguments(const Function &F);
521
522 void ComputeLiveOutVRegInfo();
523
524 /// Create the scheduler. If a specific scheduler was specified
525 /// via the SchedulerRegistry, use it, otherwise select the
526 /// one preferred by the target.
527 ///
528 ScheduleDAGSDNodes *CreateScheduler();
529
530 /// OpcodeOffset - This is a cache used to dispatch efficiently into isel
531 /// state machines that start with a OPC_SwitchOpcode node.
532 std::vector<unsigned> OpcodeOffset;
533
534 void UpdateChains(SDNode *NodeToMatch, SDValue InputChain,
535 SmallVectorImpl<SDNode *> &ChainNodesMatched,
536 bool isMorphNodeTo);
537};
538
540 std::unique_ptr<SelectionDAGISel> Selector;
541
542public:
543 SelectionDAGISelLegacy(char &ID, std::unique_ptr<SelectionDAGISel> S);
544
545 ~SelectionDAGISelLegacy() override = default;
546
547 void getAnalysisUsage(AnalysisUsage &AU) const override;
548
549 bool runOnMachineFunction(MachineFunction &MF) override;
550};
551
552class SelectionDAGISelPass : public PassInfoMixin<SelectionDAGISelPass> {
553 std::unique_ptr<SelectionDAGISel> Selector;
554
555protected:
556 SelectionDAGISelPass(std::unique_ptr<SelectionDAGISel> Selector)
557 : Selector(std::move(Selector)) {}
558
559public:
562 static bool isRequired() { return true; }
563};
564}
565
566#endif /* LLVM_CODEGEN_SELECTIONDAGISEL_H */
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
bool End
Definition: ELF_riscv.cpp:480
#define F(x, y, z)
Definition: MD5.cpp:55
mir Rename Register Operands
Value * RHS
Value * LHS
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
Represent the analysis usage information of a pass.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
A cache of @llvm.assume calls within a function.
InstListType::const_iterator const_iterator
Definition: BasicBlock.h:178
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
This class represents an Operation in the Expression.
Garbage collection metadata for a single function.
Definition: GCMetadata.h:78
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
This class contains meta information specific to a module.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
ScheduleDAGSDNodes - A ScheduleDAG for scheduling SDNode-based DAGs.
~SelectionDAGISelLegacy() override=default
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
SelectionDAGISelPass(std::unique_ptr< SelectionDAGISel > Selector)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
SelectionDAGISel - This is the common base class used for SelectionDAG-based pattern-matching instruc...
std::optional< BatchAAResults > BatchAA
std::unique_ptr< FunctionLoweringInfo > FuncInfo
SmallPtrSet< const Instruction *, 4 > ElidedArgCopyInstrs
virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op, InlineAsm::ConstraintCode ConstraintID, std::vector< SDValue > &OutOps)
SelectInlineAsmMemoryOperand - Select the specified address as a target addressing mode,...
bool CheckOrMask(SDValue LHS, ConstantSDNode *RHS, int64_t DesiredMaskS) const
CheckOrMask - The isel is trying to match something like (or X, 255).
AssumptionCache * AC
void initializeAnalysisResults(MachineFunctionAnalysisManager &MFAM)
MachineModuleInfo * MMI
const TargetLowering * TLI
virtual void PostprocessISelDAG()
PostprocessISelDAG() - This hook allows the target to hack on the graph right after selection.
MachineFunction * MF
virtual bool CheckNodePredicate(SDNode *N, unsigned PredNo) const
CheckNodePredicate - This function is generated by tblgen in the target.
std::unique_ptr< OptimizationRemarkEmitter > ORE
Current optimization remark emitter.
MachineRegisterInfo * RegInfo
unsigned DAGSize
DAGSize - Size of DAG being instruction selected.
bool isOrEquivalentToAdd(const SDNode *N) const
virtual bool CheckComplexPattern(SDNode *Root, SDNode *Parent, SDValue N, unsigned PatternNo, SmallVectorImpl< std::pair< SDValue, SDNode * > > &Result)
virtual bool CheckPatternPredicate(unsigned PredNo) const
CheckPatternPredicate - This function is generated by tblgen in the target.
static int getNumFixedFromVariadicInfo(unsigned Flags)
getNumFixedFromVariadicInfo - Transform an EmitNode flags word into the number of fixed arity values ...
const TargetLibraryInfo * LibInfo
static int getUninvalidatedNodeId(SDNode *N)
const TargetInstrInfo * TII
CodeGenOptLevel OptLevel
virtual bool CheckNodePredicateWithOperands(SDNode *N, unsigned PredNo, const SmallVectorImpl< SDValue > &Operands) const
CheckNodePredicateWithOperands - This function is generated by tblgen in the target.
GCFunctionInfo * GFI
void SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable, unsigned TableSize)
virtual void Select(SDNode *N)=0
Main hook for targets to transform nodes into machine nodes.
void ReplaceUses(const SDValue *F, const SDValue *T, unsigned Num)
ReplaceUses - replace all uses of the old nodes F with the use of the new nodes T.
static void EnforceNodeIdInvariant(SDNode *N)
virtual void emitFunctionEntryCode()
void ReplaceUses(SDValue F, SDValue T)
ReplaceUses - replace all uses of the old node F with the use of the new node T.
virtual bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const
IsProfitableToFold - Returns true if it's profitable to fold the specific operand node N of U during ...
virtual SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo)
bool MatchFilterFuncName
True if the function currently processing is in the function printing list (i.e.
void SelectInlineAsmMemoryOperands(std::vector< SDValue > &Ops, const SDLoc &DL)
SelectInlineAsmMemoryOperands - Calls to this are automatically generated by tblgen.
static bool IsLegalToFold(SDValue N, SDNode *U, SDNode *Root, CodeGenOptLevel OptLevel, bool IgnoreChains=false)
IsLegalToFold - Returns true if the specific operand node N of U can be folded during instruction sel...
virtual bool ComplexPatternFuncMutatesDAG() const
Return true if complex patterns for this target can mutate the DAG.
void ReplaceUses(SDNode *F, SDNode *T)
ReplaceUses - replace all uses of the old node F with the use of the new node T.
virtual void PreprocessISelDAG()
PreprocessISelDAG - This hook allows targets to hack on the graph before instruction selection starts...
BatchAAResults * getBatchAA() const
Returns a (possibly null) pointer to the current BatchAAResults.
bool CheckAndMask(SDValue LHS, ConstantSDNode *RHS, int64_t DesiredMaskS) const
CheckAndMask - The isel is trying to match something like (and X, 255).
SwiftErrorValueTracking * SwiftError
virtual StringRef getPatternForIndex(unsigned index)
getPatternForIndex - Patterns selected by tablegen during ISEL
bool mayRaiseFPException(SDNode *Node) const
Return whether the node may raise an FP exception.
std::unique_ptr< SelectionDAGBuilder > SDB
void ReplaceNode(SDNode *F, SDNode *T)
Replace all uses of F with T, then remove F from the DAG.
virtual bool runOnMachineFunction(MachineFunction &mf)
static void InvalidateNodeId(SDNode *N)
const TargetLowering * getTargetLowering() const
bool shouldOptForSize(const MachineFunction *MF) const
virtual StringRef getIncludePathForIndex(unsigned index)
getIncludePathForIndex - get the td source location of pattern instantiation
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
Definition: SelectionDAG.h:228
void ReplaceAllUsesOfValuesWith(const SDValue *From, const SDValue *To, unsigned Num)
Like ReplaceAllUsesOfValueWith, but for multiple values at once.
bool shouldOptForSize() const
void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using 'From' to use 'To' instead.
void RemoveDeadNode(SDNode *N)
Remove the specified node from the system.
void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:519
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
TargetInstrInfo - Interface to description of machine instruction set.
Provides information about what library functions are available for the current target.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:77
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
CodeGenOptLevel
Code generation optimization level.
Definition: CodeGen.h:54
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1873
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
#define N
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:69
This represents a list of ValueType's that has been intern'd by a SelectionDAG.