LLVM 22.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;
31class SDValue;
33class MachineFunction;
35class TargetLowering;
40class GCFunctionInfo;
42
43/// SelectionDAGISel - This is the common base class used for SelectionDAG-based
44/// pattern-matching instruction selectors.
46public:
50 std::unique_ptr<FunctionLoweringInfo> FuncInfo;
51 std::unique_ptr<SwiftErrorValueTracking> SwiftError;
56 std::unique_ptr<SelectionDAGBuilder> SDB;
57 mutable std::optional<BatchAAResults> BatchAA;
58 AssumptionCache *AC = nullptr;
59 GCFunctionInfo *GFI = nullptr;
60 SSPLayoutInfo *SP = nullptr;
61 const TargetTransformInfo *TTI = nullptr;
67
68 /// Current optimization remark emitter.
69 /// Used to report things like combines and FastISel failures.
70 std::unique_ptr<OptimizationRemarkEmitter> ORE;
71
72 /// True if the function currently processing is in the function printing list
73 /// (i.e. `-filter-print-funcs`).
74 /// This is primarily used by ISEL_DUMP, which spans in multiple member
75 /// functions. Storing the filter result here so that we only need to do the
76 /// filtering once.
77 bool MatchFilterFuncName = false;
79
82 virtual ~SelectionDAGISel();
83
84 /// Returns a (possibly null) pointer to the current BatchAAResults.
86 if (BatchAA.has_value())
87 return &BatchAA.value();
88 return nullptr;
89 }
90
91 const TargetLowering *getTargetLowering() const { return TLI; }
92
95
96 virtual bool runOnMachineFunction(MachineFunction &mf);
97
98 virtual void emitFunctionEntryCode() {}
99
100 /// PreprocessISelDAG - This hook allows targets to hack on the graph before
101 /// instruction selection starts.
102 virtual void PreprocessISelDAG() {}
103
104 /// PostprocessISelDAG() - This hook allows the target to hack on the graph
105 /// right after selection.
106 virtual void PostprocessISelDAG() {}
107
108 /// Main hook for targets to transform nodes into machine nodes.
109 virtual void Select(SDNode *N) = 0;
110
111 /// SelectInlineAsmMemoryOperand - Select the specified address as a target
112 /// addressing mode, according to the specified constraint. If this does
113 /// not match or is not implemented, return true. The resultant operands
114 /// (which will appear in the machine instruction) should be added to the
115 /// OutOps vector.
116 virtual bool
118 InlineAsm::ConstraintCode ConstraintID,
119 std::vector<SDValue> &OutOps) {
120 return true;
121 }
122
123 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
124 /// operand node N of U during instruction selection that starts at Root.
125 virtual bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const;
126
127 /// IsLegalToFold - Returns true if the specific operand node N of
128 /// U can be folded during instruction selection that starts at Root.
129 /// FIXME: This is a static member function because the MSP430/X86
130 /// targets, which uses it during isel. This could become a proper member.
131 static bool IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
133 bool IgnoreChains = false);
134
135 static void InvalidateNodeId(SDNode *N);
136 static int getUninvalidatedNodeId(SDNode *N);
137
138 static void EnforceNodeIdInvariant(SDNode *N);
139
140 // 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.
293 // Space-optimized forms that implicitly encode number of result VTs.
297 // Space-optimized forms that implicitly encode EmitNodeInfo.
305 // Space-optimized forms that implicitly encode number of result VTs.
309 // Space-optimized forms that implicitly encode EmitNodeInfo.
323 // Contains 32-bit offset in table for pattern being selected
325 };
326
327 enum {
328 OPFL_None = 0, // Node has no chain or glue input and isn't variadic.
329 OPFL_Chain = 1, // Node has a chain input.
330 OPFL_GlueInput = 2, // Node has a glue input.
331 OPFL_GlueOutput = 4, // Node has a glue output.
332 OPFL_MemRefs = 8, // Node gets accumulated MemRefs.
333 OPFL_Variadic0 = 1 << 4, // Node is variadic, root has 0 fixed inputs.
334 OPFL_Variadic1 = 2 << 4, // Node is variadic, root has 1 fixed inputs.
335 OPFL_Variadic2 = 3 << 4, // Node is variadic, root has 2 fixed inputs.
336 OPFL_Variadic3 = 4 << 4, // Node is variadic, root has 3 fixed inputs.
337 OPFL_Variadic4 = 5 << 4, // Node is variadic, root has 4 fixed inputs.
338 OPFL_Variadic5 = 6 << 4, // Node is variadic, root has 5 fixed inputs.
339 OPFL_Variadic6 = 7 << 4, // Node is variadic, root has 6 fixed inputs.
340 OPFL_Variadic7 = 8 << 4, // Node is variadic, root has 7 fixed inputs.
341
342 OPFL_VariadicInfo = 15 << 4 // Mask for extracting the OPFL_VariadicN bits.
343 };
344
345 /// getNumFixedFromVariadicInfo - Transform an EmitNode flags word into the
346 /// number of fixed arity values that should be skipped when copying from the
347 /// root.
348 static inline int getNumFixedFromVariadicInfo(unsigned Flags) {
349 return ((Flags&OPFL_VariadicInfo) >> 4)-1;
350 }
351
352
353protected:
354 /// DAGSize - Size of DAG being instruction selected.
355 ///
356 unsigned DAGSize = 0;
357
358 /// ReplaceUses - replace all uses of the old node F with the use
359 /// of the new node T.
361 CurDAG->ReplaceAllUsesOfValueWith(F, T);
362 EnforceNodeIdInvariant(T.getNode());
363 }
364
365 /// ReplaceUses - replace all uses of the old nodes F with the use
366 /// of the new nodes T.
367 void ReplaceUses(const SDValue *F, const SDValue *T, unsigned Num) {
368 CurDAG->ReplaceAllUsesOfValuesWith(F, T, Num);
369 for (unsigned i = 0; i < Num; ++i)
371 }
372
373 /// ReplaceUses - replace all uses of the old node F with the use
374 /// of the new node T.
376 CurDAG->ReplaceAllUsesWith(F, T);
378 }
379
380 /// Replace all uses of \c F with \c T, then remove \c F from the DAG.
382 CurDAG->ReplaceAllUsesWith(F, T);
384 CurDAG->RemoveDeadNode(F);
385 }
386
387 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
388 /// by tblgen. Others should not call it.
389 void SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops,
390 const SDLoc &DL);
391
392 /// getPatternForIndex - Patterns selected by tablegen during ISEL
393 virtual StringRef getPatternForIndex(unsigned index) {
394 llvm_unreachable("Tblgen should generate the implementation of this!");
395 }
396
397 /// getIncludePathForIndex - get the td source location of pattern instantiation
398 virtual StringRef getIncludePathForIndex(unsigned index) {
399 llvm_unreachable("Tblgen should generate the implementation of this!");
400 }
401
403 return CurDAG->shouldOptForSize();
404 }
405
406public:
407 // Calls to these predicates are generated by tblgen.
409 int64_t DesiredMaskS) const;
411 int64_t DesiredMaskS) const;
412
413
414 /// CheckPatternPredicate - This function is generated by tblgen in the
415 /// target. It runs the specified pattern predicate and returns true if it
416 /// succeeds or false if it fails. The number is a private implementation
417 /// detail to the code tblgen produces.
418 virtual bool CheckPatternPredicate(unsigned PredNo) const {
419 llvm_unreachable("Tblgen should generate the implementation of this!");
420 }
421
422 /// CheckNodePredicate - This function is generated by tblgen in the target.
423 /// It runs node predicate number PredNo and returns true if it succeeds or
424 /// false if it fails. The number is a private implementation
425 /// detail to the code tblgen produces.
426 virtual bool CheckNodePredicate(SDValue Op, unsigned PredNo) const {
427 llvm_unreachable("Tblgen should generate the implementation of this!");
428 }
429
430 /// CheckNodePredicateWithOperands - This function is generated by tblgen in
431 /// the target.
432 /// It runs node predicate number PredNo and returns true if it succeeds or
433 /// false if it fails. The number is a private implementation detail to the
434 /// code tblgen produces.
435 virtual bool
437 ArrayRef<SDValue> Operands) const {
438 llvm_unreachable("Tblgen should generate the implementation of this!");
439 }
440
441 virtual bool CheckComplexPattern(SDNode *Root, SDNode *Parent, SDValue N,
442 unsigned PatternNo,
443 SmallVectorImpl<std::pair<SDValue, SDNode*> > &Result) {
444 llvm_unreachable("Tblgen should generate the implementation of this!");
445 }
446
447 virtual SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {
448 llvm_unreachable("Tblgen should generate this!");
449 }
450
451 void SelectCodeCommon(SDNode *NodeToMatch, const uint8_t *MatcherTable,
452 unsigned TableSize);
453
454 /// Return true if complex patterns for this target can mutate the
455 /// DAG.
456 virtual bool ComplexPatternFuncMutatesDAG() const {
457 return false;
458 }
459
460 /// Return whether the node may raise an FP exception.
461 bool mayRaiseFPException(SDNode *Node) const;
462
463 bool isOrEquivalentToAdd(const SDNode *N) const;
464
465private:
466
467 // Calls to these functions are generated by tblgen.
468 void Select_INLINEASM(SDNode *N);
469 void Select_READ_REGISTER(SDNode *Op);
470 void Select_WRITE_REGISTER(SDNode *Op);
471 void Select_UNDEF(SDNode *N);
472 void Select_FAKE_USE(SDNode *N);
473 void Select_RELOC_NONE(SDNode *N);
474 void CannotYetSelect(SDNode *N);
475
476 void Select_FREEZE(SDNode *N);
477 void Select_ARITH_FENCE(SDNode *N);
478 void Select_MEMBARRIER(SDNode *N);
479
480 void Select_CONVERGENCECTRL_ANCHOR(SDNode *N);
481 void Select_CONVERGENCECTRL_ENTRY(SDNode *N);
482 void Select_CONVERGENCECTRL_LOOP(SDNode *N);
483
484 void pushStackMapLiveVariable(SmallVectorImpl<SDValue> &Ops, SDValue Operand,
485 SDLoc DL);
486 void Select_STACKMAP(SDNode *N);
487 void Select_PATCHPOINT(SDNode *N);
488
489 void Select_JUMP_TABLE_DEBUG_INFO(SDNode *N);
490
491private:
492 void DoInstructionSelection();
493 SDNode *MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
494 ArrayRef<SDValue> Ops, unsigned EmitNodeInfo);
495
496 /// Prepares the landing pad to take incoming values or do other EH
497 /// personality specific tasks. Returns true if the block should be
498 /// instruction selected, false if no code should be emitted for it.
499 bool PrepareEHLandingPad();
500
501 // Mark and Report IPToState for each Block under AsynchEH
502 void reportIPToStateForBlocks(MachineFunction *Fn);
503
504 /// Perform instruction selection on all basic blocks in the function.
505 void SelectAllBasicBlocks(const Function &Fn);
506
507 /// Perform instruction selection on a single basic block, for
508 /// instructions between \p Begin and \p End. \p HadTailCall will be set
509 /// to true if a call in the block was translated as a tail call.
510 void SelectBasicBlock(BasicBlock::const_iterator Begin,
512 bool &HadTailCall);
513 void FinishBasicBlock();
514
515 void CodeGenAndEmitDAG();
516
517 /// Generate instructions for lowering the incoming arguments of the
518 /// given function.
519 void LowerArguments(const Function &F);
520
521 void ComputeLiveOutVRegInfo();
522
523 /// Create the scheduler. If a specific scheduler was specified
524 /// via the SchedulerRegistry, use it, otherwise select the
525 /// one preferred by the target.
526 ///
527 ScheduleDAGSDNodes *CreateScheduler();
528
529 /// OpcodeOffset - This is a cache used to dispatch efficiently into isel
530 /// state machines that start with a OPC_SwitchOpcode node.
531 std::vector<unsigned> OpcodeOffset;
532
533 void UpdateChains(SDNode *NodeToMatch, SDValue InputChain,
534 SmallVectorImpl<SDNode *> &ChainNodesMatched,
535 bool isMorphNodeTo);
536};
537
539 std::unique_ptr<SelectionDAGISel> Selector;
540
541public:
542 SelectionDAGISelLegacy(char &ID, std::unique_ptr<SelectionDAGISel> S);
543
544 ~SelectionDAGISelLegacy() override = default;
545
546 void getAnalysisUsage(AnalysisUsage &AU) const override;
547
548 bool runOnMachineFunction(MachineFunction &MF) override;
549};
550
551class SelectionDAGISelPass : public PassInfoMixin<SelectionDAGISelPass> {
552 std::unique_ptr<SelectionDAGISel> Selector;
553
554protected:
555 SelectionDAGISelPass(std::unique_ptr<SelectionDAGISel> Selector)
556 : Selector(std::move(Selector)) {}
557
558public:
561 static bool isRequired() { return true; }
562};
563}
564
565#endif /* LLVM_CODEGEN_SELECTIONDAGISEL_H */
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define T
Value * RHS
Value * LHS
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:40
A cache of @llvm.assume calls within a function.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
Garbage collection metadata for a single function.
Definition GCMetadata.h:80
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,...
The optimization diagnostic interface.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
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.
SelectionDAGBuilder - This is the common target-independent lowering implementation that is parameter...
~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.
SelectionDAGISelLegacy(char &ID, std::unique_ptr< SelectionDAGISel > S)
SelectionDAGISelPass(std::unique_ptr< SelectionDAGISel > Selector)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
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).
void initializeAnalysisResults(MachineFunctionAnalysisManager &MFAM)
const TargetTransformInfo * TTI
virtual bool CheckNodePredicate(SDValue Op, unsigned PredNo) const
CheckNodePredicate - This function is generated by tblgen in the target.
MachineModuleInfo * MMI
virtual bool CheckNodePredicateWithOperands(SDValue Op, unsigned PredNo, ArrayRef< SDValue > Operands) const
CheckNodePredicateWithOperands - This function is generated by tblgen in the target.
const TargetLowering * TLI
virtual void PostprocessISelDAG()
PostprocessISelDAG() - This hook allows the target to hack on the graph right after selection.
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
std::unique_ptr< SwiftErrorValueTracking > SwiftError
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)
void SelectCodeCommon(SDNode *NodeToMatch, const uint8_t *MatcherTable, unsigned TableSize)
virtual void emitFunctionEntryCode()
const RTLIB::RuntimeLibcallsInfo * RuntimeLibCallInfo
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).
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.
SelectionDAGISel(TargetMachine &tm, CodeGenOptLevel OL=CodeGenOptLevel::Default)
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...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
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.
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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:82
@ Default
-O2, -Os, -Oz
Definition CodeGen.h:85
DWARFExpression::Operation Op
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:1915
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870
#define N
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition PassManager.h:70
A simple container for information about the supported runtime calls.
This represents a list of ValueType's that has been intern'd by a SelectionDAG.