• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- llvm/CodeGen/SelectionDAG.h - InstSelection DAG ----------*- 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 declares the SelectionDAG class, and transitively defines the
10 // SDNode class and subclasses.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CODEGEN_SELECTIONDAG_H
15 #define LLVM_CODEGEN_SELECTIONDAG_H
16 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/ilist.h"
24 #include "llvm/ADT/iterator.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/CodeGen/DAGCombine.h"
27 #include "llvm/CodeGen/ISDOpcodes.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineMemOperand.h"
30 #include "llvm/CodeGen/MachinePassManager.h"
31 #include "llvm/CodeGen/SelectionDAGNodes.h"
32 #include "llvm/CodeGen/ValueTypes.h"
33 #include "llvm/CodeGenTypes/MachineValueType.h"
34 #include "llvm/IR/ConstantRange.h"
35 #include "llvm/IR/DebugLoc.h"
36 #include "llvm/IR/Metadata.h"
37 #include "llvm/Support/Allocator.h"
38 #include "llvm/Support/ArrayRecycler.h"
39 #include "llvm/Support/CodeGen.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/RecyclingAllocator.h"
42 #include <cassert>
43 #include <cstdint>
44 #include <functional>
45 #include <map>
46 #include <string>
47 #include <tuple>
48 #include <utility>
49 #include <vector>
50 
51 namespace llvm {
52 
53 class DIExpression;
54 class DILabel;
55 class DIVariable;
56 class Function;
57 class Pass;
58 class Type;
59 template <class GraphType> struct GraphTraits;
60 template <typename T, unsigned int N> class SmallSetVector;
61 template <typename T, typename Enable> struct FoldingSetTrait;
62 class AAResults;
63 class BlockAddress;
64 class BlockFrequencyInfo;
65 class Constant;
66 class ConstantFP;
67 class ConstantInt;
68 class DataLayout;
69 struct fltSemantics;
70 class FunctionLoweringInfo;
71 class FunctionVarLocs;
72 class GlobalValue;
73 struct KnownBits;
74 class LLVMContext;
75 class MachineBasicBlock;
76 class MachineConstantPoolValue;
77 class MachineModuleInfo;
78 class MCSymbol;
79 class OptimizationRemarkEmitter;
80 class ProfileSummaryInfo;
81 class SDDbgValue;
82 class SDDbgOperand;
83 class SDDbgLabel;
84 class SelectionDAG;
85 class SelectionDAGTargetInfo;
86 class TargetLibraryInfo;
87 class TargetLowering;
88 class TargetMachine;
89 class TargetSubtargetInfo;
90 class Value;
91 
92 template <typename T> class GenericSSAContext;
93 using SSAContext = GenericSSAContext<Function>;
94 template <typename T> class GenericUniformityInfo;
95 using UniformityInfo = GenericUniformityInfo<SSAContext>;
96 
97 class SDVTListNode : public FoldingSetNode {
98   friend struct FoldingSetTrait<SDVTListNode>;
99 
100   /// A reference to an Interned FoldingSetNodeID for this node.
101   /// The Allocator in SelectionDAG holds the data.
102   /// SDVTList contains all types which are frequently accessed in SelectionDAG.
103   /// The size of this list is not expected to be big so it won't introduce
104   /// a memory penalty.
105   FoldingSetNodeIDRef FastID;
106   const EVT *VTs;
107   unsigned int NumVTs;
108   /// The hash value for SDVTList is fixed, so cache it to avoid
109   /// hash calculation.
110   unsigned HashValue;
111 
112 public:
113   SDVTListNode(const FoldingSetNodeIDRef ID, const EVT *VT, unsigned int Num) :
114       FastID(ID), VTs(VT), NumVTs(Num) {
115     HashValue = ID.ComputeHash();
116   }
117 
118   SDVTList getSDVTList() {
119     SDVTList result = {VTs, NumVTs};
120     return result;
121   }
122 };
123 
124 /// Specialize FoldingSetTrait for SDVTListNode
125 /// to avoid computing temp FoldingSetNodeID and hash value.
126 template<> struct FoldingSetTrait<SDVTListNode> : DefaultFoldingSetTrait<SDVTListNode> {
127   static void Profile(const SDVTListNode &X, FoldingSetNodeID& ID) {
128     ID = X.FastID;
129   }
130 
131   static bool Equals(const SDVTListNode &X, const FoldingSetNodeID &ID,
132                      unsigned IDHash, FoldingSetNodeID &TempID) {
133     if (X.HashValue != IDHash)
134       return false;
135     return ID == X.FastID;
136   }
137 
138   static unsigned ComputeHash(const SDVTListNode &X, FoldingSetNodeID &TempID) {
139     return X.HashValue;
140   }
141 };
142 
143 template <> struct ilist_alloc_traits<SDNode> {
144   static void deleteNode(SDNode *) {
145     llvm_unreachable("ilist_traits<SDNode> shouldn't see a deleteNode call!");
146   }
147 };
148 
149 /// Keeps track of dbg_value information through SDISel.  We do
150 /// not build SDNodes for these so as not to perturb the generated code;
151 /// instead the info is kept off to the side in this structure. Each SDNode may
152 /// have one or more associated dbg_value entries. This information is kept in
153 /// DbgValMap.
154 /// Byval parameters are handled separately because they don't use alloca's,
155 /// which busts the normal mechanism.  There is good reason for handling all
156 /// parameters separately:  they may not have code generated for them, they
157 /// should always go at the beginning of the function regardless of other code
158 /// motion, and debug info for them is potentially useful even if the parameter
159 /// is unused.  Right now only byval parameters are handled separately.
160 class SDDbgInfo {
161   BumpPtrAllocator Alloc;
162   SmallVector<SDDbgValue*, 32> DbgValues;
163   SmallVector<SDDbgValue*, 32> ByvalParmDbgValues;
164   SmallVector<SDDbgLabel*, 4> DbgLabels;
165   using DbgValMapType = DenseMap<const SDNode *, SmallVector<SDDbgValue *, 2>>;
166   DbgValMapType DbgValMap;
167 
168 public:
169   SDDbgInfo() = default;
170   SDDbgInfo(const SDDbgInfo &) = delete;
171   SDDbgInfo &operator=(const SDDbgInfo &) = delete;
172 
173   void add(SDDbgValue *V, bool isParameter);
174 
175   void add(SDDbgLabel *L) { DbgLabels.push_back(L); }
176 
177   /// Invalidate all DbgValues attached to the node and remove
178   /// it from the Node-to-DbgValues map.
179   void erase(const SDNode *Node);
180 
181   void clear() {
182     DbgValMap.clear();
183     DbgValues.clear();
184     ByvalParmDbgValues.clear();
185     DbgLabels.clear();
186     Alloc.Reset();
187   }
188 
189   BumpPtrAllocator &getAlloc() { return Alloc; }
190 
191   bool empty() const {
192     return DbgValues.empty() && ByvalParmDbgValues.empty() && DbgLabels.empty();
193   }
194 
195   ArrayRef<SDDbgValue*> getSDDbgValues(const SDNode *Node) const {
196     auto I = DbgValMap.find(Node);
197     if (I != DbgValMap.end())
198       return I->second;
199     return ArrayRef<SDDbgValue*>();
200   }
201 
202   using DbgIterator = SmallVectorImpl<SDDbgValue*>::iterator;
203   using DbgLabelIterator = SmallVectorImpl<SDDbgLabel*>::iterator;
204 
205   DbgIterator DbgBegin() { return DbgValues.begin(); }
206   DbgIterator DbgEnd()   { return DbgValues.end(); }
207   DbgIterator ByvalParmDbgBegin() { return ByvalParmDbgValues.begin(); }
208   DbgIterator ByvalParmDbgEnd()   { return ByvalParmDbgValues.end(); }
209   DbgLabelIterator DbgLabelBegin() { return DbgLabels.begin(); }
210   DbgLabelIterator DbgLabelEnd()   { return DbgLabels.end(); }
211 };
212 
213 void checkForCycles(const SelectionDAG *DAG, bool force = false);
214 
215 /// This is used to represent a portion of an LLVM function in a low-level
216 /// Data Dependence DAG representation suitable for instruction selection.
217 /// This DAG is constructed as the first step of instruction selection in order
218 /// to allow implementation of machine specific optimizations
219 /// and code simplifications.
220 ///
221 /// The representation used by the SelectionDAG is a target-independent
222 /// representation, which has some similarities to the GCC RTL representation,
223 /// but is significantly more simple, powerful, and is a graph form instead of a
224 /// linear form.
225 ///
226 class SelectionDAG {
227   const TargetMachine &TM;
228   const SelectionDAGTargetInfo *TSI = nullptr;
229   const TargetLowering *TLI = nullptr;
230   const TargetLibraryInfo *LibInfo = nullptr;
231   const FunctionVarLocs *FnVarLocs = nullptr;
232   MachineFunction *MF;
233   MachineFunctionAnalysisManager *MFAM = nullptr;
234   Pass *SDAGISelPass = nullptr;
235   LLVMContext *Context;
236   CodeGenOptLevel OptLevel;
237 
238   UniformityInfo *UA = nullptr;
239   FunctionLoweringInfo * FLI = nullptr;
240 
241   /// The function-level optimization remark emitter.  Used to emit remarks
242   /// whenever manipulating the DAG.
243   OptimizationRemarkEmitter *ORE;
244 
245   ProfileSummaryInfo *PSI = nullptr;
246   BlockFrequencyInfo *BFI = nullptr;
247   MachineModuleInfo *MMI = nullptr;
248 
249   /// List of non-single value types.
250   FoldingSet<SDVTListNode> VTListMap;
251 
252   /// Pool allocation for misc. objects that are created once per SelectionDAG.
253   BumpPtrAllocator Allocator;
254 
255   /// The starting token.
256   SDNode EntryNode;
257 
258   /// The root of the entire DAG.
259   SDValue Root;
260 
261   /// A linked list of nodes in the current DAG.
262   ilist<SDNode> AllNodes;
263 
264   /// The AllocatorType for allocating SDNodes. We use
265   /// pool allocation with recycling.
266   using NodeAllocatorType = RecyclingAllocator<BumpPtrAllocator, SDNode,
267                                                sizeof(LargestSDNode),
268                                                alignof(MostAlignedSDNode)>;
269 
270   /// Pool allocation for nodes.
271   NodeAllocatorType NodeAllocator;
272 
273   /// This structure is used to memoize nodes, automatically performing
274   /// CSE with existing nodes when a duplicate is requested.
275   FoldingSet<SDNode> CSEMap;
276 
277   /// Pool allocation for machine-opcode SDNode operands.
278   BumpPtrAllocator OperandAllocator;
279   ArrayRecycler<SDUse> OperandRecycler;
280 
281   /// Tracks dbg_value and dbg_label information through SDISel.
282   SDDbgInfo *DbgInfo;
283 
284   using CallSiteInfo = MachineFunction::CallSiteInfo;
285 
286   struct NodeExtraInfo {
287     CallSiteInfo CSInfo;
288     MDNode *HeapAllocSite = nullptr;
289     MDNode *PCSections = nullptr;
290     MDNode *MMRA = nullptr;
291     bool NoMerge = false;
292   };
293   /// Out-of-line extra information for SDNodes.
294   DenseMap<const SDNode *, NodeExtraInfo> SDEI;
295 
296   /// PersistentId counter to be used when inserting the next
297   /// SDNode to this SelectionDAG. We do not place that under
298   /// `#if LLVM_ENABLE_ABI_BREAKING_CHECKS` intentionally because
299   /// it adds unneeded complexity without noticeable
300   /// benefits (see discussion with @thakis in D120714).
301   uint16_t NextPersistentId = 0;
302 
303 public:
304   /// Clients of various APIs that cause global effects on
305   /// the DAG can optionally implement this interface.  This allows the clients
306   /// to handle the various sorts of updates that happen.
307   ///
308   /// A DAGUpdateListener automatically registers itself with DAG when it is
309   /// constructed, and removes itself when destroyed in RAII fashion.
310   struct DAGUpdateListener {
311     DAGUpdateListener *const Next;
312     SelectionDAG &DAG;
313 
314     explicit DAGUpdateListener(SelectionDAG &D)
315       : Next(D.UpdateListeners), DAG(D) {
316       DAG.UpdateListeners = this;
317     }
318 
319     virtual ~DAGUpdateListener() {
320       assert(DAG.UpdateListeners == this &&
321              "DAGUpdateListeners must be destroyed in LIFO order");
322       DAG.UpdateListeners = Next;
323     }
324 
325     /// The node N that was deleted and, if E is not null, an
326     /// equivalent node E that replaced it.
327     virtual void NodeDeleted(SDNode *N, SDNode *E);
328 
329     /// The node N that was updated.
330     virtual void NodeUpdated(SDNode *N);
331 
332     /// The node N that was inserted.
333     virtual void NodeInserted(SDNode *N);
334   };
335 
336   struct DAGNodeDeletedListener : public DAGUpdateListener {
337     std::function<void(SDNode *, SDNode *)> Callback;
338 
339     DAGNodeDeletedListener(SelectionDAG &DAG,
340                            std::function<void(SDNode *, SDNode *)> Callback)
341         : DAGUpdateListener(DAG), Callback(std::move(Callback)) {}
342 
343     void NodeDeleted(SDNode *N, SDNode *E) override { Callback(N, E); }
344 
345    private:
346     virtual void anchor();
347   };
348 
349   struct DAGNodeInsertedListener : public DAGUpdateListener {
350     std::function<void(SDNode *)> Callback;
351 
352     DAGNodeInsertedListener(SelectionDAG &DAG,
353                             std::function<void(SDNode *)> Callback)
354         : DAGUpdateListener(DAG), Callback(std::move(Callback)) {}
355 
356     void NodeInserted(SDNode *N) override { Callback(N); }
357 
358   private:
359     virtual void anchor();
360   };
361 
362   /// Help to insert SDNodeFlags automatically in transforming. Use
363   /// RAII to save and resume flags in current scope.
364   class FlagInserter {
365     SelectionDAG &DAG;
366     SDNodeFlags Flags;
367     FlagInserter *LastInserter;
368 
369   public:
370     FlagInserter(SelectionDAG &SDAG, SDNodeFlags Flags)
371         : DAG(SDAG), Flags(Flags),
372           LastInserter(SDAG.getFlagInserter()) {
373       SDAG.setFlagInserter(this);
374     }
375     FlagInserter(SelectionDAG &SDAG, SDNode *N)
376         : FlagInserter(SDAG, N->getFlags()) {}
377 
378     FlagInserter(const FlagInserter &) = delete;
379     FlagInserter &operator=(const FlagInserter &) = delete;
380     ~FlagInserter() { DAG.setFlagInserter(LastInserter); }
381 
382     SDNodeFlags getFlags() const { return Flags; }
383   };
384 
385   /// When true, additional steps are taken to
386   /// ensure that getConstant() and similar functions return DAG nodes that
387   /// have legal types. This is important after type legalization since
388   /// any illegally typed nodes generated after this point will not experience
389   /// type legalization.
390   bool NewNodesMustHaveLegalTypes = false;
391 
392 private:
393   /// DAGUpdateListener is a friend so it can manipulate the listener stack.
394   friend struct DAGUpdateListener;
395 
396   /// Linked list of registered DAGUpdateListener instances.
397   /// This stack is maintained by DAGUpdateListener RAII.
398   DAGUpdateListener *UpdateListeners = nullptr;
399 
400   /// Implementation of setSubgraphColor.
401   /// Return whether we had to truncate the search.
402   bool setSubgraphColorHelper(SDNode *N, const char *Color,
403                               DenseSet<SDNode *> &visited,
404                               int level, bool &printed);
405 
406   template <typename SDNodeT, typename... ArgTypes>
407   SDNodeT *newSDNode(ArgTypes &&... Args) {
408     return new (NodeAllocator.template Allocate<SDNodeT>())
409         SDNodeT(std::forward<ArgTypes>(Args)...);
410   }
411 
412   /// Build a synthetic SDNodeT with the given args and extract its subclass
413   /// data as an integer (e.g. for use in a folding set).
414   ///
415   /// The args to this function are the same as the args to SDNodeT's
416   /// constructor, except the second arg (assumed to be a const DebugLoc&) is
417   /// omitted.
418   template <typename SDNodeT, typename... ArgTypes>
419   static uint16_t getSyntheticNodeSubclassData(unsigned IROrder,
420                                                ArgTypes &&... Args) {
421     // The compiler can reduce this expression to a constant iff we pass an
422     // empty DebugLoc.  Thankfully, the debug location doesn't have any bearing
423     // on the subclass data.
424     return SDNodeT(IROrder, DebugLoc(), std::forward<ArgTypes>(Args)...)
425         .getRawSubclassData();
426   }
427 
428   template <typename SDNodeTy>
429   static uint16_t getSyntheticNodeSubclassData(unsigned Opc, unsigned Order,
430                                                 SDVTList VTs, EVT MemoryVT,
431                                                 MachineMemOperand *MMO) {
432     return SDNodeTy(Opc, Order, DebugLoc(), VTs, MemoryVT, MMO)
433          .getRawSubclassData();
434   }
435 
436   void createOperands(SDNode *Node, ArrayRef<SDValue> Vals);
437 
438   void removeOperands(SDNode *Node) {
439     if (!Node->OperandList)
440       return;
441     OperandRecycler.deallocate(
442         ArrayRecycler<SDUse>::Capacity::get(Node->NumOperands),
443         Node->OperandList);
444     Node->NumOperands = 0;
445     Node->OperandList = nullptr;
446   }
447   void CreateTopologicalOrder(std::vector<SDNode*>& Order);
448 
449 public:
450   // Maximum depth for recursive analysis such as computeKnownBits, etc.
451   static constexpr unsigned MaxRecursionDepth = 6;
452 
453   explicit SelectionDAG(const TargetMachine &TM, CodeGenOptLevel);
454   SelectionDAG(const SelectionDAG &) = delete;
455   SelectionDAG &operator=(const SelectionDAG &) = delete;
456   ~SelectionDAG();
457 
458   /// Prepare this SelectionDAG to process code in the given MachineFunction.
459   void init(MachineFunction &NewMF, OptimizationRemarkEmitter &NewORE,
460             Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
461             UniformityInfo *UA, ProfileSummaryInfo *PSIin,
462             BlockFrequencyInfo *BFIin, MachineModuleInfo &MMI,
463             FunctionVarLocs const *FnVarLocs);
464 
465   void init(MachineFunction &NewMF, OptimizationRemarkEmitter &NewORE,
466             MachineFunctionAnalysisManager &AM,
467             const TargetLibraryInfo *LibraryInfo, UniformityInfo *UA,
468             ProfileSummaryInfo *PSIin, BlockFrequencyInfo *BFIin,
469             MachineModuleInfo &MMI, FunctionVarLocs const *FnVarLocs) {
470     init(NewMF, NewORE, nullptr, LibraryInfo, UA, PSIin, BFIin, MMI, FnVarLocs);
471     MFAM = &AM;
472   }
473 
474   void setFunctionLoweringInfo(FunctionLoweringInfo * FuncInfo) {
475     FLI = FuncInfo;
476   }
477 
478   /// Clear state and free memory necessary to make this
479   /// SelectionDAG ready to process a new block.
480   void clear();
481 
482   MachineFunction &getMachineFunction() const { return *MF; }
483   const Pass *getPass() const { return SDAGISelPass; }
484   MachineFunctionAnalysisManager *getMFAM() { return MFAM; }
485 
486   CodeGenOptLevel getOptLevel() const { return OptLevel; }
487   const DataLayout &getDataLayout() const { return MF->getDataLayout(); }
488   const TargetMachine &getTarget() const { return TM; }
489   const TargetSubtargetInfo &getSubtarget() const { return MF->getSubtarget(); }
490   template <typename STC> const STC &getSubtarget() const {
491     return MF->getSubtarget<STC>();
492   }
493   const TargetLowering &getTargetLoweringInfo() const { return *TLI; }
494   const TargetLibraryInfo &getLibInfo() const { return *LibInfo; }
495   const SelectionDAGTargetInfo &getSelectionDAGInfo() const { return *TSI; }
496   const UniformityInfo *getUniformityInfo() const { return UA; }
497   /// Returns the result of the AssignmentTrackingAnalysis pass if it's
498   /// available, otherwise return nullptr.
499   const FunctionVarLocs *getFunctionVarLocs() const { return FnVarLocs; }
500   LLVMContext *getContext() const { return Context; }
501   OptimizationRemarkEmitter &getORE() const { return *ORE; }
502   ProfileSummaryInfo *getPSI() const { return PSI; }
503   BlockFrequencyInfo *getBFI() const { return BFI; }
504   MachineModuleInfo *getMMI() const { return MMI; }
505 
506   FlagInserter *getFlagInserter() { return Inserter; }
507   void setFlagInserter(FlagInserter *FI) { Inserter = FI; }
508 
509   /// Just dump dot graph to a user-provided path and title.
510   /// This doesn't open the dot viewer program and
511   /// helps visualization when outside debugging session.
512   /// FileName expects absolute path. If provided
513   /// without any path separators then the file
514   /// will be created in the current directory.
515   /// Error will be emitted if the path is insane.
516 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
517   LLVM_DUMP_METHOD void dumpDotGraph(const Twine &FileName, const Twine &Title);
518 #endif
519 
520   /// Pop up a GraphViz/gv window with the DAG rendered using 'dot'.
521   void viewGraph(const std::string &Title);
522   void viewGraph();
523 
524 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
525   std::map<const SDNode *, std::string> NodeGraphAttrs;
526 #endif
527 
528   /// Clear all previously defined node graph attributes.
529   /// Intended to be used from a debugging tool (eg. gdb).
530   void clearGraphAttrs();
531 
532   /// Set graph attributes for a node. (eg. "color=red".)
533   void setGraphAttrs(const SDNode *N, const char *Attrs);
534 
535   /// Get graph attributes for a node. (eg. "color=red".)
536   /// Used from getNodeAttributes.
537   std::string getGraphAttrs(const SDNode *N) const;
538 
539   /// Convenience for setting node color attribute.
540   void setGraphColor(const SDNode *N, const char *Color);
541 
542   /// Convenience for setting subgraph color attribute.
543   void setSubgraphColor(SDNode *N, const char *Color);
544 
545   using allnodes_const_iterator = ilist<SDNode>::const_iterator;
546 
547   allnodes_const_iterator allnodes_begin() const { return AllNodes.begin(); }
548   allnodes_const_iterator allnodes_end() const { return AllNodes.end(); }
549 
550   using allnodes_iterator = ilist<SDNode>::iterator;
551 
552   allnodes_iterator allnodes_begin() { return AllNodes.begin(); }
553   allnodes_iterator allnodes_end() { return AllNodes.end(); }
554 
555   ilist<SDNode>::size_type allnodes_size() const {
556     return AllNodes.size();
557   }
558 
559   iterator_range<allnodes_iterator> allnodes() {
560     return make_range(allnodes_begin(), allnodes_end());
561   }
562   iterator_range<allnodes_const_iterator> allnodes() const {
563     return make_range(allnodes_begin(), allnodes_end());
564   }
565 
566   /// Return the root tag of the SelectionDAG.
567   const SDValue &getRoot() const { return Root; }
568 
569   /// Return the token chain corresponding to the entry of the function.
570   SDValue getEntryNode() const {
571     return SDValue(const_cast<SDNode *>(&EntryNode), 0);
572   }
573 
574   /// Set the current root tag of the SelectionDAG.
575   ///
576   const SDValue &setRoot(SDValue N) {
577     assert((!N.getNode() || N.getValueType() == MVT::Other) &&
578            "DAG root value is not a chain!");
579     if (N.getNode())
580       checkForCycles(N.getNode(), this);
581     Root = N;
582     if (N.getNode())
583       checkForCycles(this);
584     return Root;
585   }
586 
587 #ifndef NDEBUG
588   void VerifyDAGDivergence();
589 #endif
590 
591   /// This iterates over the nodes in the SelectionDAG, folding
592   /// certain types of nodes together, or eliminating superfluous nodes.  The
593   /// Level argument controls whether Combine is allowed to produce nodes and
594   /// types that are illegal on the target.
595   void Combine(CombineLevel Level, AAResults *AA, CodeGenOptLevel OptLevel);
596 
597   /// This transforms the SelectionDAG into a SelectionDAG that
598   /// only uses types natively supported by the target.
599   /// Returns "true" if it made any changes.
600   ///
601   /// Note that this is an involved process that may invalidate pointers into
602   /// the graph.
603   bool LegalizeTypes();
604 
605   /// This transforms the SelectionDAG into a SelectionDAG that is
606   /// compatible with the target instruction selector, as indicated by the
607   /// TargetLowering object.
608   ///
609   /// Note that this is an involved process that may invalidate pointers into
610   /// the graph.
611   void Legalize();
612 
613   /// Transforms a SelectionDAG node and any operands to it into a node
614   /// that is compatible with the target instruction selector, as indicated by
615   /// the TargetLowering object.
616   ///
617   /// \returns true if \c N is a valid, legal node after calling this.
618   ///
619   /// This essentially runs a single recursive walk of the \c Legalize process
620   /// over the given node (and its operands). This can be used to incrementally
621   /// legalize the DAG. All of the nodes which are directly replaced,
622   /// potentially including N, are added to the output parameter \c
623   /// UpdatedNodes so that the delta to the DAG can be understood by the
624   /// caller.
625   ///
626   /// When this returns false, N has been legalized in a way that make the
627   /// pointer passed in no longer valid. It may have even been deleted from the
628   /// DAG, and so it shouldn't be used further. When this returns true, the
629   /// N passed in is a legal node, and can be immediately processed as such.
630   /// This may still have done some work on the DAG, and will still populate
631   /// UpdatedNodes with any new nodes replacing those originally in the DAG.
632   bool LegalizeOp(SDNode *N, SmallSetVector<SDNode *, 16> &UpdatedNodes);
633 
634   /// This transforms the SelectionDAG into a SelectionDAG
635   /// that only uses vector math operations supported by the target.  This is
636   /// necessary as a separate step from Legalize because unrolling a vector
637   /// operation can introduce illegal types, which requires running
638   /// LegalizeTypes again.
639   ///
640   /// This returns true if it made any changes; in that case, LegalizeTypes
641   /// is called again before Legalize.
642   ///
643   /// Note that this is an involved process that may invalidate pointers into
644   /// the graph.
645   bool LegalizeVectors();
646 
647   /// This method deletes all unreachable nodes in the SelectionDAG.
648   void RemoveDeadNodes();
649 
650   /// Remove the specified node from the system.  This node must
651   /// have no referrers.
652   void DeleteNode(SDNode *N);
653 
654   /// Return an SDVTList that represents the list of values specified.
655   SDVTList getVTList(EVT VT);
656   SDVTList getVTList(EVT VT1, EVT VT2);
657   SDVTList getVTList(EVT VT1, EVT VT2, EVT VT3);
658   SDVTList getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4);
659   SDVTList getVTList(ArrayRef<EVT> VTs);
660 
661   //===--------------------------------------------------------------------===//
662   // Node creation methods.
663 
664   /// Create a ConstantSDNode wrapping a constant value.
665   /// If VT is a vector type, the constant is splatted into a BUILD_VECTOR.
666   ///
667   /// If only legal types can be produced, this does the necessary
668   /// transformations (e.g., if the vector element type is illegal).
669   /// @{
670   SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
671                       bool isTarget = false, bool isOpaque = false);
672   SDValue getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
673                       bool isTarget = false, bool isOpaque = false);
674 
675   SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT,
676                             bool isTarget = false, bool isOpaque = false);
677 
678   SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget = false,
679                              bool IsOpaque = false);
680 
681   SDValue getConstant(const ConstantInt &Val, const SDLoc &DL, EVT VT,
682                       bool isTarget = false, bool isOpaque = false);
683   SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL,
684                             bool isTarget = false);
685   SDValue getShiftAmountConstant(uint64_t Val, EVT VT, const SDLoc &DL);
686   SDValue getShiftAmountConstant(const APInt &Val, EVT VT, const SDLoc &DL);
687   SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
688                                bool isTarget = false);
689 
690   SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT,
691                             bool isOpaque = false) {
692     return getConstant(Val, DL, VT, true, isOpaque);
693   }
694   SDValue getTargetConstant(const APInt &Val, const SDLoc &DL, EVT VT,
695                             bool isOpaque = false) {
696     return getConstant(Val, DL, VT, true, isOpaque);
697   }
698   SDValue getTargetConstant(const ConstantInt &Val, const SDLoc &DL, EVT VT,
699                             bool isOpaque = false) {
700     return getConstant(Val, DL, VT, true, isOpaque);
701   }
702 
703   /// Create a true or false constant of type \p VT using the target's
704   /// BooleanContent for type \p OpVT.
705   SDValue getBoolConstant(bool V, const SDLoc &DL, EVT VT, EVT OpVT);
706   /// @}
707 
708   /// Create a ConstantFPSDNode wrapping a constant value.
709   /// If VT is a vector type, the constant is splatted into a BUILD_VECTOR.
710   ///
711   /// If only legal types can be produced, this does the necessary
712   /// transformations (e.g., if the vector element type is illegal).
713   /// The forms that take a double should only be used for simple constants
714   /// that can be exactly represented in VT.  No checks are made.
715   /// @{
716   SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT,
717                         bool isTarget = false);
718   SDValue getConstantFP(const APFloat &Val, const SDLoc &DL, EVT VT,
719                         bool isTarget = false);
720   SDValue getConstantFP(const ConstantFP &V, const SDLoc &DL, EVT VT,
721                         bool isTarget = false);
722   SDValue getTargetConstantFP(double Val, const SDLoc &DL, EVT VT) {
723     return getConstantFP(Val, DL, VT, true);
724   }
725   SDValue getTargetConstantFP(const APFloat &Val, const SDLoc &DL, EVT VT) {
726     return getConstantFP(Val, DL, VT, true);
727   }
728   SDValue getTargetConstantFP(const ConstantFP &Val, const SDLoc &DL, EVT VT) {
729     return getConstantFP(Val, DL, VT, true);
730   }
731   /// @}
732 
733   SDValue getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT,
734                            int64_t offset = 0, bool isTargetGA = false,
735                            unsigned TargetFlags = 0);
736   SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT,
737                                  int64_t offset = 0, unsigned TargetFlags = 0) {
738     return getGlobalAddress(GV, DL, VT, offset, true, TargetFlags);
739   }
740   SDValue getFrameIndex(int FI, EVT VT, bool isTarget = false);
741   SDValue getTargetFrameIndex(int FI, EVT VT) {
742     return getFrameIndex(FI, VT, true);
743   }
744   SDValue getJumpTable(int JTI, EVT VT, bool isTarget = false,
745                        unsigned TargetFlags = 0);
746   SDValue getTargetJumpTable(int JTI, EVT VT, unsigned TargetFlags = 0) {
747     return getJumpTable(JTI, VT, true, TargetFlags);
748   }
749   SDValue getJumpTableDebugInfo(int JTI, SDValue Chain, const SDLoc &DL);
750   SDValue getConstantPool(const Constant *C, EVT VT,
751                           MaybeAlign Align = std::nullopt, int Offs = 0,
752                           bool isT = false, unsigned TargetFlags = 0);
753   SDValue getTargetConstantPool(const Constant *C, EVT VT,
754                                 MaybeAlign Align = std::nullopt, int Offset = 0,
755                                 unsigned TargetFlags = 0) {
756     return getConstantPool(C, VT, Align, Offset, true, TargetFlags);
757   }
758   SDValue getConstantPool(MachineConstantPoolValue *C, EVT VT,
759                           MaybeAlign Align = std::nullopt, int Offs = 0,
760                           bool isT = false, unsigned TargetFlags = 0);
761   SDValue getTargetConstantPool(MachineConstantPoolValue *C, EVT VT,
762                                 MaybeAlign Align = std::nullopt, int Offset = 0,
763                                 unsigned TargetFlags = 0) {
764     return getConstantPool(C, VT, Align, Offset, true, TargetFlags);
765   }
766   // When generating a branch to a BB, we don't in general know enough
767   // to provide debug info for the BB at that time, so keep this one around.
768   SDValue getBasicBlock(MachineBasicBlock *MBB);
769   SDValue getExternalSymbol(const char *Sym, EVT VT);
770   SDValue getTargetExternalSymbol(const char *Sym, EVT VT,
771                                   unsigned TargetFlags = 0);
772   SDValue getMCSymbol(MCSymbol *Sym, EVT VT);
773 
774   SDValue getValueType(EVT);
775   SDValue getRegister(unsigned Reg, EVT VT);
776   SDValue getRegisterMask(const uint32_t *RegMask);
777   SDValue getEHLabel(const SDLoc &dl, SDValue Root, MCSymbol *Label);
778   SDValue getLabelNode(unsigned Opcode, const SDLoc &dl, SDValue Root,
779                        MCSymbol *Label);
780   SDValue getBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset = 0,
781                           bool isTarget = false, unsigned TargetFlags = 0);
782   SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT,
783                                 int64_t Offset = 0, unsigned TargetFlags = 0) {
784     return getBlockAddress(BA, VT, Offset, true, TargetFlags);
785   }
786 
787   SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, unsigned Reg,
788                        SDValue N) {
789     return getNode(ISD::CopyToReg, dl, MVT::Other, Chain,
790                    getRegister(Reg, N.getValueType()), N);
791   }
792 
793   // This version of the getCopyToReg method takes an extra operand, which
794   // indicates that there is potentially an incoming glue value (if Glue is not
795   // null) and that there should be a glue result.
796   SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, unsigned Reg, SDValue N,
797                        SDValue Glue) {
798     SDVTList VTs = getVTList(MVT::Other, MVT::Glue);
799     SDValue Ops[] = { Chain, getRegister(Reg, N.getValueType()), N, Glue };
800     return getNode(ISD::CopyToReg, dl, VTs,
801                    ArrayRef(Ops, Glue.getNode() ? 4 : 3));
802   }
803 
804   // Similar to last getCopyToReg() except parameter Reg is a SDValue
805   SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, SDValue Reg, SDValue N,
806                        SDValue Glue) {
807     SDVTList VTs = getVTList(MVT::Other, MVT::Glue);
808     SDValue Ops[] = { Chain, Reg, N, Glue };
809     return getNode(ISD::CopyToReg, dl, VTs,
810                    ArrayRef(Ops, Glue.getNode() ? 4 : 3));
811   }
812 
813   SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, unsigned Reg, EVT VT) {
814     SDVTList VTs = getVTList(VT, MVT::Other);
815     SDValue Ops[] = { Chain, getRegister(Reg, VT) };
816     return getNode(ISD::CopyFromReg, dl, VTs, Ops);
817   }
818 
819   // This version of the getCopyFromReg method takes an extra operand, which
820   // indicates that there is potentially an incoming glue value (if Glue is not
821   // null) and that there should be a glue result.
822   SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, unsigned Reg, EVT VT,
823                          SDValue Glue) {
824     SDVTList VTs = getVTList(VT, MVT::Other, MVT::Glue);
825     SDValue Ops[] = { Chain, getRegister(Reg, VT), Glue };
826     return getNode(ISD::CopyFromReg, dl, VTs,
827                    ArrayRef(Ops, Glue.getNode() ? 3 : 2));
828   }
829 
830   SDValue getCondCode(ISD::CondCode Cond);
831 
832   /// Return an ISD::VECTOR_SHUFFLE node. The number of elements in VT,
833   /// which must be a vector type, must match the number of mask elements
834   /// NumElts. An integer mask element equal to -1 is treated as undefined.
835   SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2,
836                            ArrayRef<int> Mask);
837 
838   /// Return an ISD::BUILD_VECTOR node. The number of elements in VT,
839   /// which must be a vector type, must match the number of operands in Ops.
840   /// The operands must have the same type as (or, for integers, a type wider
841   /// than) VT's element type.
842   SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef<SDValue> Ops) {
843     // VerifySDNode (via InsertNode) checks BUILD_VECTOR later.
844     return getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
845   }
846 
847   /// Return an ISD::BUILD_VECTOR node. The number of elements in VT,
848   /// which must be a vector type, must match the number of operands in Ops.
849   /// The operands must have the same type as (or, for integers, a type wider
850   /// than) VT's element type.
851   SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef<SDUse> Ops) {
852     // VerifySDNode (via InsertNode) checks BUILD_VECTOR later.
853     return getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
854   }
855 
856   /// Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all
857   /// elements. VT must be a vector type. Op's type must be the same as (or,
858   /// for integers, a type wider than) VT's element type.
859   SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op) {
860     // VerifySDNode (via InsertNode) checks BUILD_VECTOR later.
861     if (Op.getOpcode() == ISD::UNDEF) {
862       assert((VT.getVectorElementType() == Op.getValueType() ||
863               (VT.isInteger() &&
864                VT.getVectorElementType().bitsLE(Op.getValueType()))) &&
865              "A splatted value must have a width equal or (for integers) "
866              "greater than the vector element type!");
867       return getNode(ISD::UNDEF, SDLoc(), VT);
868     }
869 
870     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Op);
871     return getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
872   }
873 
874   // Return a splat ISD::SPLAT_VECTOR node, consisting of Op splatted to all
875   // elements.
876   SDValue getSplatVector(EVT VT, const SDLoc &DL, SDValue Op) {
877     if (Op.getOpcode() == ISD::UNDEF) {
878       assert((VT.getVectorElementType() == Op.getValueType() ||
879               (VT.isInteger() &&
880                VT.getVectorElementType().bitsLE(Op.getValueType()))) &&
881              "A splatted value must have a width equal or (for integers) "
882              "greater than the vector element type!");
883       return getNode(ISD::UNDEF, SDLoc(), VT);
884     }
885     return getNode(ISD::SPLAT_VECTOR, DL, VT, Op);
886   }
887 
888   /// Returns a node representing a splat of one value into all lanes
889   /// of the provided vector type.  This is a utility which returns
890   /// either a BUILD_VECTOR or SPLAT_VECTOR depending on the
891   /// scalability of the desired vector type.
892   SDValue getSplat(EVT VT, const SDLoc &DL, SDValue Op) {
893     assert(VT.isVector() && "Can't splat to non-vector type");
894     return VT.isScalableVector() ?
895       getSplatVector(VT, DL, Op) : getSplatBuildVector(VT, DL, Op);
896   }
897 
898   /// Returns a vector of type ResVT whose elements contain the linear sequence
899   ///   <0, Step, Step * 2, Step * 3, ...>
900   SDValue getStepVector(const SDLoc &DL, EVT ResVT, const APInt &StepVal);
901 
902   /// Returns a vector of type ResVT whose elements contain the linear sequence
903   ///   <0, 1, 2, 3, ...>
904   SDValue getStepVector(const SDLoc &DL, EVT ResVT);
905 
906   /// Returns an ISD::VECTOR_SHUFFLE node semantically equivalent to
907   /// the shuffle node in input but with swapped operands.
908   ///
909   /// Example: shuffle A, B, <0,5,2,7> -> shuffle B, A, <4,1,6,3>
910   SDValue getCommutedVectorShuffle(const ShuffleVectorSDNode &SV);
911 
912   /// Convert Op, which must be of float type, to the
913   /// float type VT, by either extending or rounding (by truncation).
914   SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT);
915 
916   /// Convert Op, which must be a STRICT operation of float type, to the
917   /// float type VT, by either extending or rounding (by truncation).
918   std::pair<SDValue, SDValue>
919   getStrictFPExtendOrRound(SDValue Op, SDValue Chain, const SDLoc &DL, EVT VT);
920 
921   /// Convert *_EXTEND_VECTOR_INREG to *_EXTEND opcode.
922   static unsigned getOpcode_EXTEND(unsigned Opcode) {
923     switch (Opcode) {
924     case ISD::ANY_EXTEND:
925     case ISD::ANY_EXTEND_VECTOR_INREG:
926       return ISD::ANY_EXTEND;
927     case ISD::ZERO_EXTEND:
928     case ISD::ZERO_EXTEND_VECTOR_INREG:
929       return ISD::ZERO_EXTEND;
930     case ISD::SIGN_EXTEND:
931     case ISD::SIGN_EXTEND_VECTOR_INREG:
932       return ISD::SIGN_EXTEND;
933     }
934     llvm_unreachable("Unknown opcode");
935   }
936 
937   /// Convert *_EXTEND to *_EXTEND_VECTOR_INREG opcode.
938   static unsigned getOpcode_EXTEND_VECTOR_INREG(unsigned Opcode) {
939     switch (Opcode) {
940     case ISD::ANY_EXTEND:
941     case ISD::ANY_EXTEND_VECTOR_INREG:
942       return ISD::ANY_EXTEND_VECTOR_INREG;
943     case ISD::ZERO_EXTEND:
944     case ISD::ZERO_EXTEND_VECTOR_INREG:
945       return ISD::ZERO_EXTEND_VECTOR_INREG;
946     case ISD::SIGN_EXTEND:
947     case ISD::SIGN_EXTEND_VECTOR_INREG:
948       return ISD::SIGN_EXTEND_VECTOR_INREG;
949     }
950     llvm_unreachable("Unknown opcode");
951   }
952 
953   /// Convert Op, which must be of integer type, to the
954   /// integer type VT, by either any-extending or truncating it.
955   SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT);
956 
957   /// Convert Op, which must be of integer type, to the
958   /// integer type VT, by either sign-extending or truncating it.
959   SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT);
960 
961   /// Convert Op, which must be of integer type, to the
962   /// integer type VT, by either zero-extending or truncating it.
963   SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT);
964 
965   /// Convert Op, which must be of integer type, to the
966   /// integer type VT, by either any/sign/zero-extending (depending on IsAny /
967   /// IsSigned) or truncating it.
968   SDValue getExtOrTrunc(SDValue Op, const SDLoc &DL,
969                         EVT VT, unsigned Opcode) {
970     switch(Opcode) {
971       case ISD::ANY_EXTEND:
972         return getAnyExtOrTrunc(Op, DL, VT);
973       case ISD::ZERO_EXTEND:
974         return getZExtOrTrunc(Op, DL, VT);
975       case ISD::SIGN_EXTEND:
976         return getSExtOrTrunc(Op, DL, VT);
977     }
978     llvm_unreachable("Unsupported opcode");
979   }
980 
981   /// Convert Op, which must be of integer type, to the
982   /// integer type VT, by either sign/zero-extending (depending on IsSigned) or
983   /// truncating it.
984   SDValue getExtOrTrunc(bool IsSigned, SDValue Op, const SDLoc &DL, EVT VT) {
985     return IsSigned ? getSExtOrTrunc(Op, DL, VT) : getZExtOrTrunc(Op, DL, VT);
986   }
987 
988   /// Convert Op, which must be of integer type, to the
989   /// integer type VT, by first bitcasting (from potential vector) to
990   /// corresponding scalar type then either any-extending or truncating it.
991   SDValue getBitcastedAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT);
992 
993   /// Convert Op, which must be of integer type, to the
994   /// integer type VT, by first bitcasting (from potential vector) to
995   /// corresponding scalar type then either sign-extending or truncating it.
996   SDValue getBitcastedSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT);
997 
998   /// Convert Op, which must be of integer type, to the
999   /// integer type VT, by first bitcasting (from potential vector) to
1000   /// corresponding scalar type then either zero-extending or truncating it.
1001   SDValue getBitcastedZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT);
1002 
1003   /// Return the expression required to zero extend the Op
1004   /// value assuming it was the smaller SrcTy value.
1005   SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT);
1006 
1007   /// Return the expression required to zero extend the Op
1008   /// value assuming it was the smaller SrcTy value.
1009   SDValue getVPZeroExtendInReg(SDValue Op, SDValue Mask, SDValue EVL,
1010                                const SDLoc &DL, EVT VT);
1011 
1012   /// Convert Op, which must be of integer type, to the integer type VT, by
1013   /// either truncating it or performing either zero or sign extension as
1014   /// appropriate extension for the pointer's semantics.
1015   SDValue getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT);
1016 
1017   /// Return the expression required to extend the Op as a pointer value
1018   /// assuming it was the smaller SrcTy value. This may be either a zero extend
1019   /// or a sign extend.
1020   SDValue getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT);
1021 
1022   /// Convert Op, which must be of integer type, to the integer type VT,
1023   /// by using an extension appropriate for the target's
1024   /// BooleanContent for type OpVT or truncating it.
1025   SDValue getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, EVT OpVT);
1026 
1027   /// Create negative operation as (SUB 0, Val).
1028   SDValue getNegative(SDValue Val, const SDLoc &DL, EVT VT);
1029 
1030   /// Create a bitwise NOT operation as (XOR Val, -1).
1031   SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT);
1032 
1033   /// Create a logical NOT operation as (XOR Val, BooleanOne).
1034   SDValue getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT);
1035 
1036   /// Create a vector-predicated logical NOT operation as (VP_XOR Val,
1037   /// BooleanOne, Mask, EVL).
1038   SDValue getVPLogicalNOT(const SDLoc &DL, SDValue Val, SDValue Mask,
1039                           SDValue EVL, EVT VT);
1040 
1041   /// Convert a vector-predicated Op, which must be an integer vector, to the
1042   /// vector-type VT, by performing either vector-predicated zext or truncating
1043   /// it. The Op will be returned as-is if Op and VT are vectors containing
1044   /// integer with same width.
1045   SDValue getVPZExtOrTrunc(const SDLoc &DL, EVT VT, SDValue Op, SDValue Mask,
1046                            SDValue EVL);
1047 
1048   /// Convert a vector-predicated Op, which must be of integer type, to the
1049   /// vector-type integer type VT, by either truncating it or performing either
1050   /// vector-predicated zero or sign extension as appropriate extension for the
1051   /// pointer's semantics. This function just redirects to getVPZExtOrTrunc
1052   /// right now.
1053   SDValue getVPPtrExtOrTrunc(const SDLoc &DL, EVT VT, SDValue Op, SDValue Mask,
1054                              SDValue EVL);
1055 
1056   /// Returns sum of the base pointer and offset.
1057   /// Unlike getObjectPtrOffset this does not set NoUnsignedWrap by default.
1058   SDValue getMemBasePlusOffset(SDValue Base, TypeSize Offset, const SDLoc &DL,
1059                                const SDNodeFlags Flags = SDNodeFlags());
1060   SDValue getMemBasePlusOffset(SDValue Base, SDValue Offset, const SDLoc &DL,
1061                                const SDNodeFlags Flags = SDNodeFlags());
1062 
1063   /// Create an add instruction with appropriate flags when used for
1064   /// addressing some offset of an object. i.e. if a load is split into multiple
1065   /// components, create an add nuw from the base pointer to the offset.
1066   SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset) {
1067     SDNodeFlags Flags;
1068     Flags.setNoUnsignedWrap(true);
1069     return getMemBasePlusOffset(Ptr, Offset, SL, Flags);
1070   }
1071 
1072   SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, SDValue Offset) {
1073     // The object itself can't wrap around the address space, so it shouldn't be
1074     // possible for the adds of the offsets to the split parts to overflow.
1075     SDNodeFlags Flags;
1076     Flags.setNoUnsignedWrap(true);
1077     return getMemBasePlusOffset(Ptr, Offset, SL, Flags);
1078   }
1079 
1080   /// Return a new CALLSEQ_START node, that starts new call frame, in which
1081   /// InSize bytes are set up inside CALLSEQ_START..CALLSEQ_END sequence and
1082   /// OutSize specifies part of the frame set up prior to the sequence.
1083   SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize,
1084                            const SDLoc &DL) {
1085     SDVTList VTs = getVTList(MVT::Other, MVT::Glue);
1086     SDValue Ops[] = { Chain,
1087                       getIntPtrConstant(InSize, DL, true),
1088                       getIntPtrConstant(OutSize, DL, true) };
1089     return getNode(ISD::CALLSEQ_START, DL, VTs, Ops);
1090   }
1091 
1092   /// Return a new CALLSEQ_END node, which always must have a
1093   /// glue result (to ensure it's not CSE'd).
1094   /// CALLSEQ_END does not have a useful SDLoc.
1095   SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2,
1096                          SDValue InGlue, const SDLoc &DL) {
1097     SDVTList NodeTys = getVTList(MVT::Other, MVT::Glue);
1098     SmallVector<SDValue, 4> Ops;
1099     Ops.push_back(Chain);
1100     Ops.push_back(Op1);
1101     Ops.push_back(Op2);
1102     if (InGlue.getNode())
1103       Ops.push_back(InGlue);
1104     return getNode(ISD::CALLSEQ_END, DL, NodeTys, Ops);
1105   }
1106 
1107   SDValue getCALLSEQ_END(SDValue Chain, uint64_t Size1, uint64_t Size2,
1108                          SDValue Glue, const SDLoc &DL) {
1109     return getCALLSEQ_END(
1110         Chain, getIntPtrConstant(Size1, DL, /*isTarget=*/true),
1111         getIntPtrConstant(Size2, DL, /*isTarget=*/true), Glue, DL);
1112   }
1113 
1114   /// Return true if the result of this operation is always undefined.
1115   bool isUndef(unsigned Opcode, ArrayRef<SDValue> Ops);
1116 
1117   /// Return an UNDEF node. UNDEF does not have a useful SDLoc.
1118   SDValue getUNDEF(EVT VT) {
1119     return getNode(ISD::UNDEF, SDLoc(), VT);
1120   }
1121 
1122   /// Return a node that represents the runtime scaling 'MulImm * RuntimeVL'.
1123   SDValue getVScale(const SDLoc &DL, EVT VT, APInt MulImm,
1124                     bool ConstantFold = true);
1125 
1126   SDValue getElementCount(const SDLoc &DL, EVT VT, ElementCount EC,
1127                           bool ConstantFold = true);
1128 
1129   /// Return a GLOBAL_OFFSET_TABLE node. This does not have a useful SDLoc.
1130   SDValue getGLOBAL_OFFSET_TABLE(EVT VT) {
1131     return getNode(ISD::GLOBAL_OFFSET_TABLE, SDLoc(), VT);
1132   }
1133 
1134   /// Gets or creates the specified node.
1135   ///
1136   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
1137                   ArrayRef<SDUse> Ops);
1138   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
1139                   ArrayRef<SDValue> Ops, const SDNodeFlags Flags);
1140   SDValue getNode(unsigned Opcode, const SDLoc &DL, ArrayRef<EVT> ResultTys,
1141                   ArrayRef<SDValue> Ops);
1142   SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
1143                   ArrayRef<SDValue> Ops, const SDNodeFlags Flags);
1144 
1145   // Use flags from current flag inserter.
1146   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
1147                   ArrayRef<SDValue> Ops);
1148   SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
1149                   ArrayRef<SDValue> Ops);
1150   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue Operand);
1151   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
1152                   SDValue N2);
1153   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
1154                   SDValue N2, SDValue N3);
1155 
1156   // Specialize based on number of operands.
1157   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT);
1158   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue Operand,
1159                   const SDNodeFlags Flags);
1160   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
1161                   SDValue N2, const SDNodeFlags Flags);
1162   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
1163                   SDValue N2, SDValue N3, const SDNodeFlags Flags);
1164   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
1165                   SDValue N2, SDValue N3, SDValue N4);
1166   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
1167                   SDValue N2, SDValue N3, SDValue N4, const SDNodeFlags Flags);
1168   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
1169                   SDValue N2, SDValue N3, SDValue N4, SDValue N5);
1170   SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N1,
1171                   SDValue N2, SDValue N3, SDValue N4, SDValue N5,
1172                   const SDNodeFlags Flags);
1173 
1174   // Specialize again based on number of operands for nodes with a VTList
1175   // rather than a single VT.
1176   SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList);
1177   SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, SDValue N);
1178   SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, SDValue N1,
1179                   SDValue N2);
1180   SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, SDValue N1,
1181                   SDValue N2, SDValue N3);
1182   SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, SDValue N1,
1183                   SDValue N2, SDValue N3, SDValue N4);
1184   SDValue getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, SDValue N1,
1185                   SDValue N2, SDValue N3, SDValue N4, SDValue N5);
1186 
1187   /// Compute a TokenFactor to force all the incoming stack arguments to be
1188   /// loaded from the stack. This is used in tail call lowering to protect
1189   /// stack arguments from being clobbered.
1190   SDValue getStackArgumentTokenFactor(SDValue Chain);
1191 
1192   /* \p CI if not null is the memset call being lowered.
1193    * \p OverrideTailCall is an optional parameter that can be used to override
1194    * the tail call optimization decision. */
1195   SDValue
1196   getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src,
1197             SDValue Size, Align Alignment, bool isVol, bool AlwaysInline,
1198             const CallInst *CI, std::optional<bool> OverrideTailCall,
1199             MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo,
1200             const AAMDNodes &AAInfo = AAMDNodes(), AAResults *AA = nullptr);
1201 
1202   /* \p CI if not null is the memset call being lowered.
1203    * \p OverrideTailCall is an optional parameter that can be used to override
1204    * the tail call optimization decision. */
1205   SDValue getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src,
1206                      SDValue Size, Align Alignment, bool isVol,
1207                      const CallInst *CI, std::optional<bool> OverrideTailCall,
1208                      MachinePointerInfo DstPtrInfo,
1209                      MachinePointerInfo SrcPtrInfo,
1210                      const AAMDNodes &AAInfo = AAMDNodes(),
1211                      AAResults *AA = nullptr);
1212 
1213   SDValue getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src,
1214                     SDValue Size, Align Alignment, bool isVol,
1215                     bool AlwaysInline, const CallInst *CI,
1216                     MachinePointerInfo DstPtrInfo,
1217                     const AAMDNodes &AAInfo = AAMDNodes());
1218 
1219   SDValue getAtomicMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
1220                           SDValue Src, SDValue Size, Type *SizeTy,
1221                           unsigned ElemSz, bool isTailCall,
1222                           MachinePointerInfo DstPtrInfo,
1223                           MachinePointerInfo SrcPtrInfo);
1224 
1225   SDValue getAtomicMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
1226                            SDValue Src, SDValue Size, Type *SizeTy,
1227                            unsigned ElemSz, bool isTailCall,
1228                            MachinePointerInfo DstPtrInfo,
1229                            MachinePointerInfo SrcPtrInfo);
1230 
1231   SDValue getAtomicMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
1232                           SDValue Value, SDValue Size, Type *SizeTy,
1233                           unsigned ElemSz, bool isTailCall,
1234                           MachinePointerInfo DstPtrInfo);
1235 
1236   /// Helper function to make it easier to build SetCC's if you just have an
1237   /// ISD::CondCode instead of an SDValue.
1238   SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS,
1239                    ISD::CondCode Cond, SDValue Chain = SDValue(),
1240                    bool IsSignaling = false) {
1241     assert(LHS.getValueType().isVector() == RHS.getValueType().isVector() &&
1242            "Vector/scalar operand type mismatch for setcc");
1243     assert(LHS.getValueType().isVector() == VT.isVector() &&
1244            "Vector/scalar result type mismatch for setcc");
1245     assert(Cond != ISD::SETCC_INVALID &&
1246            "Cannot create a setCC of an invalid node.");
1247     if (Chain)
1248       return getNode(IsSignaling ? ISD::STRICT_FSETCCS : ISD::STRICT_FSETCC, DL,
1249                      {VT, MVT::Other}, {Chain, LHS, RHS, getCondCode(Cond)});
1250     return getNode(ISD::SETCC, DL, VT, LHS, RHS, getCondCode(Cond));
1251   }
1252 
1253   /// Helper function to make it easier to build VP_SETCCs if you just have an
1254   /// ISD::CondCode instead of an SDValue.
1255   SDValue getSetCCVP(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS,
1256                      ISD::CondCode Cond, SDValue Mask, SDValue EVL) {
1257     assert(LHS.getValueType().isVector() && RHS.getValueType().isVector() &&
1258            "Cannot compare scalars");
1259     assert(Cond != ISD::SETCC_INVALID &&
1260            "Cannot create a setCC of an invalid node.");
1261     return getNode(ISD::VP_SETCC, DL, VT, LHS, RHS, getCondCode(Cond), Mask,
1262                    EVL);
1263   }
1264 
1265   /// Helper function to make it easier to build Select's if you just have
1266   /// operands and don't want to check for vector.
1267   SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS,
1268                     SDValue RHS, SDNodeFlags Flags = SDNodeFlags()) {
1269     assert(LHS.getValueType() == VT && RHS.getValueType() == VT &&
1270            "Cannot use select on differing types");
1271     auto Opcode = Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
1272     return getNode(Opcode, DL, VT, Cond, LHS, RHS, Flags);
1273   }
1274 
1275   /// Helper function to make it easier to build SelectCC's if you just have an
1276   /// ISD::CondCode instead of an SDValue.
1277   SDValue getSelectCC(const SDLoc &DL, SDValue LHS, SDValue RHS, SDValue True,
1278                       SDValue False, ISD::CondCode Cond) {
1279     return getNode(ISD::SELECT_CC, DL, True.getValueType(), LHS, RHS, True,
1280                    False, getCondCode(Cond));
1281   }
1282 
1283   /// Try to simplify a select/vselect into 1 of its operands or a constant.
1284   SDValue simplifySelect(SDValue Cond, SDValue TVal, SDValue FVal);
1285 
1286   /// Try to simplify a shift into 1 of its operands or a constant.
1287   SDValue simplifyShift(SDValue X, SDValue Y);
1288 
1289   /// Try to simplify a floating-point binary operation into 1 of its operands
1290   /// or a constant.
1291   SDValue simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
1292                           SDNodeFlags Flags);
1293 
1294   /// VAArg produces a result and token chain, and takes a pointer
1295   /// and a source value as input.
1296   SDValue getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr,
1297                    SDValue SV, unsigned Align);
1298 
1299   /// Gets a node for an atomic cmpxchg op. There are two
1300   /// valid Opcodes. ISD::ATOMIC_CMO_SWAP produces the value loaded and a
1301   /// chain result. ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS produces the value loaded,
1302   /// a success flag (initially i1), and a chain.
1303   SDValue getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, EVT MemVT,
1304                            SDVTList VTs, SDValue Chain, SDValue Ptr,
1305                            SDValue Cmp, SDValue Swp, MachineMemOperand *MMO);
1306 
1307   /// Gets a node for an atomic op, produces result (if relevant)
1308   /// and chain and takes 2 operands.
1309   SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain,
1310                     SDValue Ptr, SDValue Val, MachineMemOperand *MMO);
1311 
1312   /// Gets a node for an atomic op, produces result and chain and
1313   /// takes 1 operand.
1314   SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, EVT VT,
1315                     SDValue Chain, SDValue Ptr, MachineMemOperand *MMO);
1316 
1317   /// Gets a node for an atomic op, produces result and chain and takes N
1318   /// operands.
1319   SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
1320                     SDVTList VTList, ArrayRef<SDValue> Ops,
1321                     MachineMemOperand *MMO);
1322 
1323   /// Creates a MemIntrinsicNode that may produce a
1324   /// result and takes a list of operands. Opcode may be INTRINSIC_VOID,
1325   /// INTRINSIC_W_CHAIN, or a target-specific opcode with a value not
1326   /// less than FIRST_TARGET_MEMORY_OPCODE.
1327   SDValue getMemIntrinsicNode(
1328       unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
1329       EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
1330       MachineMemOperand::Flags Flags = MachineMemOperand::MOLoad |
1331                                        MachineMemOperand::MOStore,
1332       LocationSize Size = 0, const AAMDNodes &AAInfo = AAMDNodes());
1333 
1334   inline SDValue getMemIntrinsicNode(
1335       unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
1336       EVT MemVT, MachinePointerInfo PtrInfo,
1337       MaybeAlign Alignment = std::nullopt,
1338       MachineMemOperand::Flags Flags = MachineMemOperand::MOLoad |
1339                                        MachineMemOperand::MOStore,
1340       LocationSize Size = 0, const AAMDNodes &AAInfo = AAMDNodes()) {
1341     // Ensure that codegen never sees alignment 0
1342     return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, PtrInfo,
1343                                Alignment.value_or(getEVTAlign(MemVT)), Flags,
1344                                Size, AAInfo);
1345   }
1346 
1347   SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList,
1348                               ArrayRef<SDValue> Ops, EVT MemVT,
1349                               MachineMemOperand *MMO);
1350 
1351   /// Creates a LifetimeSDNode that starts (`IsStart==true`) or ends
1352   /// (`IsStart==false`) the lifetime of the portion of `FrameIndex` between
1353   /// offsets `Offset` and `Offset + Size`.
1354   SDValue getLifetimeNode(bool IsStart, const SDLoc &dl, SDValue Chain,
1355                           int FrameIndex, int64_t Size, int64_t Offset = -1);
1356 
1357   /// Creates a PseudoProbeSDNode with function GUID `Guid` and
1358   /// the index of the block `Index` it is probing, as well as the attributes
1359   /// `attr` of the probe.
1360   SDValue getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, uint64_t Guid,
1361                              uint64_t Index, uint32_t Attr);
1362 
1363   /// Create a MERGE_VALUES node from the given operands.
1364   SDValue getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl);
1365 
1366   /// Loads are not normal binary operators: their result type is not
1367   /// determined by their operands, and they produce a value AND a token chain.
1368   ///
1369   /// This function will set the MOLoad flag on MMOFlags, but you can set it if
1370   /// you want.  The MOStore flag must not be set.
1371   SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr,
1372                   MachinePointerInfo PtrInfo,
1373                   MaybeAlign Alignment = MaybeAlign(),
1374                   MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1375                   const AAMDNodes &AAInfo = AAMDNodes(),
1376                   const MDNode *Ranges = nullptr);
1377   SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr,
1378                   MachineMemOperand *MMO);
1379   SDValue
1380   getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain,
1381              SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT,
1382              MaybeAlign Alignment = MaybeAlign(),
1383              MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1384              const AAMDNodes &AAInfo = AAMDNodes());
1385   SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT,
1386                      SDValue Chain, SDValue Ptr, EVT MemVT,
1387                      MachineMemOperand *MMO);
1388   SDValue getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, SDValue Base,
1389                          SDValue Offset, ISD::MemIndexedMode AM);
1390   SDValue getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT,
1391                   const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue Offset,
1392                   MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
1393                   MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1394                   const AAMDNodes &AAInfo = AAMDNodes(),
1395                   const MDNode *Ranges = nullptr);
1396   inline SDValue getLoad(
1397       ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
1398       SDValue Chain, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo,
1399       EVT MemVT, MaybeAlign Alignment = MaybeAlign(),
1400       MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1401       const AAMDNodes &AAInfo = AAMDNodes(), const MDNode *Ranges = nullptr) {
1402     // Ensures that codegen never sees a None Alignment.
1403     return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, PtrInfo, MemVT,
1404                    Alignment.value_or(getEVTAlign(MemVT)), MMOFlags, AAInfo,
1405                    Ranges);
1406   }
1407   SDValue getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT,
1408                   const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue Offset,
1409                   EVT MemVT, MachineMemOperand *MMO);
1410 
1411   /// Helper function to build ISD::STORE nodes.
1412   ///
1413   /// This function will set the MOStore flag on MMOFlags, but you can set it if
1414   /// you want.  The MOLoad and MOInvariant flags must not be set.
1415 
1416   SDValue
1417   getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr,
1418            MachinePointerInfo PtrInfo, Align Alignment,
1419            MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1420            const AAMDNodes &AAInfo = AAMDNodes());
1421   inline SDValue
1422   getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr,
1423            MachinePointerInfo PtrInfo, MaybeAlign Alignment = MaybeAlign(),
1424            MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1425            const AAMDNodes &AAInfo = AAMDNodes()) {
1426     return getStore(Chain, dl, Val, Ptr, PtrInfo,
1427                     Alignment.value_or(getEVTAlign(Val.getValueType())),
1428                     MMOFlags, AAInfo);
1429   }
1430   SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr,
1431                    MachineMemOperand *MMO);
1432   SDValue
1433   getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr,
1434                 MachinePointerInfo PtrInfo, EVT SVT, Align Alignment,
1435                 MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1436                 const AAMDNodes &AAInfo = AAMDNodes());
1437   inline SDValue
1438   getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr,
1439                 MachinePointerInfo PtrInfo, EVT SVT,
1440                 MaybeAlign Alignment = MaybeAlign(),
1441                 MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1442                 const AAMDNodes &AAInfo = AAMDNodes()) {
1443     return getTruncStore(Chain, dl, Val, Ptr, PtrInfo, SVT,
1444                          Alignment.value_or(getEVTAlign(SVT)), MMOFlags,
1445                          AAInfo);
1446   }
1447   SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
1448                         SDValue Ptr, EVT SVT, MachineMemOperand *MMO);
1449   SDValue getIndexedStore(SDValue OrigStore, const SDLoc &dl, SDValue Base,
1450                           SDValue Offset, ISD::MemIndexedMode AM);
1451 
1452   SDValue getLoadVP(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT,
1453                     const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue Offset,
1454                     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo,
1455                     EVT MemVT, Align Alignment,
1456                     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
1457                     const MDNode *Ranges = nullptr, bool IsExpanding = false);
1458   inline SDValue
1459   getLoadVP(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT,
1460             const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue Offset,
1461             SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT,
1462             MaybeAlign Alignment = MaybeAlign(),
1463             MachineMemOperand::Flags MMOFlags = MachineMemOperand::MONone,
1464             const AAMDNodes &AAInfo = AAMDNodes(),
1465             const MDNode *Ranges = nullptr, bool IsExpanding = false) {
1466     // Ensures that codegen never sees a None Alignment.
1467     return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL,
1468                      PtrInfo, MemVT, Alignment.value_or(getEVTAlign(MemVT)),
1469                      MMOFlags, AAInfo, Ranges, IsExpanding);
1470   }
1471   SDValue getLoadVP(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT,
1472                     const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue Offset,
1473                     SDValue Mask, SDValue EVL, EVT MemVT,
1474                     MachineMemOperand *MMO, bool IsExpanding = false);
1475   SDValue getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr,
1476                     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo,
1477                     MaybeAlign Alignment, MachineMemOperand::Flags MMOFlags,
1478                     const AAMDNodes &AAInfo, const MDNode *Ranges = nullptr,
1479                     bool IsExpanding = false);
1480   SDValue getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr,
1481                     SDValue Mask, SDValue EVL, MachineMemOperand *MMO,
1482                     bool IsExpanding = false);
1483   SDValue getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT,
1484                        SDValue Chain, SDValue Ptr, SDValue Mask, SDValue EVL,
1485                        MachinePointerInfo PtrInfo, EVT MemVT,
1486                        MaybeAlign Alignment, MachineMemOperand::Flags MMOFlags,
1487                        const AAMDNodes &AAInfo, bool IsExpanding = false);
1488   SDValue getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT,
1489                        SDValue Chain, SDValue Ptr, SDValue Mask, SDValue EVL,
1490                        EVT MemVT, MachineMemOperand *MMO,
1491                        bool IsExpanding = false);
1492   SDValue getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, SDValue Base,
1493                            SDValue Offset, ISD::MemIndexedMode AM);
1494   SDValue getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr,
1495                      SDValue Offset, SDValue Mask, SDValue EVL, EVT MemVT,
1496                      MachineMemOperand *MMO, ISD::MemIndexedMode AM,
1497                      bool IsTruncating = false, bool IsCompressing = false);
1498   SDValue getTruncStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
1499                           SDValue Ptr, SDValue Mask, SDValue EVL,
1500                           MachinePointerInfo PtrInfo, EVT SVT, Align Alignment,
1501                           MachineMemOperand::Flags MMOFlags,
1502                           const AAMDNodes &AAInfo, bool IsCompressing = false);
1503   SDValue getTruncStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
1504                           SDValue Ptr, SDValue Mask, SDValue EVL, EVT SVT,
1505                           MachineMemOperand *MMO, bool IsCompressing = false);
1506   SDValue getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, SDValue Base,
1507                             SDValue Offset, ISD::MemIndexedMode AM);
1508 
1509   SDValue getStridedLoadVP(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
1510                            EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr,
1511                            SDValue Offset, SDValue Stride, SDValue Mask,
1512                            SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
1513                            bool IsExpanding = false);
1514   SDValue getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr,
1515                            SDValue Stride, SDValue Mask, SDValue EVL,
1516                            MachineMemOperand *MMO, bool IsExpanding = false);
1517   SDValue getExtStridedLoadVP(ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT,
1518                               SDValue Chain, SDValue Ptr, SDValue Stride,
1519                               SDValue Mask, SDValue EVL, EVT MemVT,
1520                               MachineMemOperand *MMO, bool IsExpanding = false);
1521   SDValue getStridedStoreVP(SDValue Chain, const SDLoc &DL, SDValue Val,
1522                             SDValue Ptr, SDValue Offset, SDValue Stride,
1523                             SDValue Mask, SDValue EVL, EVT MemVT,
1524                             MachineMemOperand *MMO, ISD::MemIndexedMode AM,
1525                             bool IsTruncating = false,
1526                             bool IsCompressing = false);
1527   SDValue getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL, SDValue Val,
1528                                  SDValue Ptr, SDValue Stride, SDValue Mask,
1529                                  SDValue EVL, EVT SVT, MachineMemOperand *MMO,
1530                                  bool IsCompressing = false);
1531 
1532   SDValue getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
1533                       ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
1534                       ISD::MemIndexType IndexType);
1535   SDValue getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
1536                        ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
1537                        ISD::MemIndexType IndexType);
1538 
1539   SDValue getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Base,
1540                         SDValue Offset, SDValue Mask, SDValue Src0, EVT MemVT,
1541                         MachineMemOperand *MMO, ISD::MemIndexedMode AM,
1542                         ISD::LoadExtType, bool IsExpanding = false);
1543   SDValue getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, SDValue Base,
1544                                SDValue Offset, ISD::MemIndexedMode AM);
1545   SDValue getMaskedStore(SDValue Chain, const SDLoc &dl, SDValue Val,
1546                          SDValue Base, SDValue Offset, SDValue Mask, EVT MemVT,
1547                          MachineMemOperand *MMO, ISD::MemIndexedMode AM,
1548                          bool IsTruncating = false, bool IsCompressing = false);
1549   SDValue getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
1550                                 SDValue Base, SDValue Offset,
1551                                 ISD::MemIndexedMode AM);
1552   SDValue getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
1553                           ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
1554                           ISD::MemIndexType IndexType, ISD::LoadExtType ExtTy);
1555   SDValue getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
1556                            ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
1557                            ISD::MemIndexType IndexType,
1558                            bool IsTruncating = false);
1559   SDValue getMaskedHistogram(SDVTList VTs, EVT MemVT, const SDLoc &dl,
1560                              ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
1561                              ISD::MemIndexType IndexType);
1562 
1563   SDValue getGetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, EVT MemVT,
1564                       MachineMemOperand *MMO);
1565   SDValue getSetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, EVT MemVT,
1566                       MachineMemOperand *MMO);
1567 
1568   /// Construct a node to track a Value* through the backend.
1569   SDValue getSrcValue(const Value *v);
1570 
1571   /// Return an MDNodeSDNode which holds an MDNode.
1572   SDValue getMDNode(const MDNode *MD);
1573 
1574   /// Return a bitcast using the SDLoc of the value operand, and casting to the
1575   /// provided type. Use getNode to set a custom SDLoc.
1576   SDValue getBitcast(EVT VT, SDValue V);
1577 
1578   /// Return an AddrSpaceCastSDNode.
1579   SDValue getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, unsigned SrcAS,
1580                            unsigned DestAS);
1581 
1582   /// Return a freeze using the SDLoc of the value operand.
1583   SDValue getFreeze(SDValue V);
1584 
1585   /// Return an AssertAlignSDNode.
1586   SDValue getAssertAlign(const SDLoc &DL, SDValue V, Align A);
1587 
1588   /// Swap N1 and N2 if Opcode is a commutative binary opcode
1589   /// and the canonical form expects the opposite order.
1590   void canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1,
1591                                     SDValue &N2) const;
1592 
1593   /// Return the specified value casted to
1594   /// the target's desired shift amount type.
1595   SDValue getShiftAmountOperand(EVT LHSTy, SDValue Op);
1596 
1597   /// Expand the specified \c ISD::VAARG node as the Legalize pass would.
1598   SDValue expandVAArg(SDNode *Node);
1599 
1600   /// Expand the specified \c ISD::VACOPY node as the Legalize pass would.
1601   SDValue expandVACopy(SDNode *Node);
1602 
1603   /// Return a GlobalAddress of the function from the current module with
1604   /// name matching the given ExternalSymbol. Additionally can provide the
1605   /// matched function.
1606   /// Panic if the function doesn't exist.
1607   SDValue getSymbolFunctionGlobalAddress(SDValue Op,
1608                                          Function **TargetFunction = nullptr);
1609 
1610   /// *Mutate* the specified node in-place to have the
1611   /// specified operands.  If the resultant node already exists in the DAG,
1612   /// this does not modify the specified node, instead it returns the node that
1613   /// already exists.  If the resultant node does not exist in the DAG, the
1614   /// input node is returned.  As a degenerate case, if you specify the same
1615   /// input operands as the node already has, the input node is returned.
1616   SDNode *UpdateNodeOperands(SDNode *N, SDValue Op);
1617   SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2);
1618   SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
1619                                SDValue Op3);
1620   SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
1621                                SDValue Op3, SDValue Op4);
1622   SDNode *UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
1623                                SDValue Op3, SDValue Op4, SDValue Op5);
1624   SDNode *UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops);
1625 
1626   /// Creates a new TokenFactor containing \p Vals. If \p Vals contains 64k
1627   /// values or more, move values into new TokenFactors in 64k-1 blocks, until
1628   /// the final TokenFactor has less than 64k operands.
1629   SDValue getTokenFactor(const SDLoc &DL, SmallVectorImpl<SDValue> &Vals);
1630 
1631   /// *Mutate* the specified machine node's memory references to the provided
1632   /// list.
1633   void setNodeMemRefs(MachineSDNode *N,
1634                       ArrayRef<MachineMemOperand *> NewMemRefs);
1635 
1636   // Calculate divergence of node \p N based on its operands.
1637   bool calculateDivergence(SDNode *N);
1638 
1639   // Propagates the change in divergence to users
1640   void updateDivergence(SDNode * N);
1641 
1642   /// These are used for target selectors to *mutate* the
1643   /// specified node to have the specified return type, Target opcode, and
1644   /// operands.  Note that target opcodes are stored as
1645   /// ~TargetOpcode in the node opcode field.  The resultant node is returned.
1646   SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT);
1647   SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT, SDValue Op1);
1648   SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT,
1649                        SDValue Op1, SDValue Op2);
1650   SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT,
1651                        SDValue Op1, SDValue Op2, SDValue Op3);
1652   SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT,
1653                        ArrayRef<SDValue> Ops);
1654   SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT1, EVT VT2);
1655   SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT1,
1656                        EVT VT2, ArrayRef<SDValue> Ops);
1657   SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT1,
1658                        EVT VT2, EVT VT3, ArrayRef<SDValue> Ops);
1659   SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT1,
1660                        EVT VT2, SDValue Op1, SDValue Op2);
1661   SDNode *SelectNodeTo(SDNode *N, unsigned MachineOpc, SDVTList VTs,
1662                        ArrayRef<SDValue> Ops);
1663 
1664   /// This *mutates* the specified node to have the specified
1665   /// return type, opcode, and operands.
1666   SDNode *MorphNodeTo(SDNode *N, unsigned Opc, SDVTList VTs,
1667                       ArrayRef<SDValue> Ops);
1668 
1669   /// Mutate the specified strict FP node to its non-strict equivalent,
1670   /// unlinking the node from its chain and dropping the metadata arguments.
1671   /// The node must be a strict FP node.
1672   SDNode *mutateStrictFPToFP(SDNode *Node);
1673 
1674   /// These are used for target selectors to create a new node
1675   /// with specified return type(s), MachineInstr opcode, and operands.
1676   ///
1677   /// Note that getMachineNode returns the resultant node.  If there is already
1678   /// a node of the specified opcode and operands, it returns that node instead
1679   /// of the current one.
1680   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT);
1681   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT,
1682                                 SDValue Op1);
1683   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT,
1684                                 SDValue Op1, SDValue Op2);
1685   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT,
1686                                 SDValue Op1, SDValue Op2, SDValue Op3);
1687   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT,
1688                                 ArrayRef<SDValue> Ops);
1689   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT1,
1690                                 EVT VT2, SDValue Op1, SDValue Op2);
1691   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT1,
1692                                 EVT VT2, SDValue Op1, SDValue Op2, SDValue Op3);
1693   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT1,
1694                                 EVT VT2, ArrayRef<SDValue> Ops);
1695   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT1,
1696                                 EVT VT2, EVT VT3, SDValue Op1, SDValue Op2);
1697   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT1,
1698                                 EVT VT2, EVT VT3, SDValue Op1, SDValue Op2,
1699                                 SDValue Op3);
1700   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT1,
1701                                 EVT VT2, EVT VT3, ArrayRef<SDValue> Ops);
1702   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl,
1703                                 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops);
1704   MachineSDNode *getMachineNode(unsigned Opcode, const SDLoc &dl, SDVTList VTs,
1705                                 ArrayRef<SDValue> Ops);
1706 
1707   /// A convenience function for creating TargetInstrInfo::EXTRACT_SUBREG nodes.
1708   SDValue getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
1709                                  SDValue Operand);
1710 
1711   /// A convenience function for creating TargetInstrInfo::INSERT_SUBREG nodes.
1712   SDValue getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
1713                                 SDValue Operand, SDValue Subreg);
1714 
1715   /// Get the specified node if it's already available, or else return NULL.
1716   SDNode *getNodeIfExists(unsigned Opcode, SDVTList VTList,
1717                           ArrayRef<SDValue> Ops, const SDNodeFlags Flags);
1718   SDNode *getNodeIfExists(unsigned Opcode, SDVTList VTList,
1719                           ArrayRef<SDValue> Ops);
1720 
1721   /// Check if a node exists without modifying its flags.
1722   bool doesNodeExist(unsigned Opcode, SDVTList VTList, ArrayRef<SDValue> Ops);
1723 
1724   /// Creates a SDDbgValue node.
1725   SDDbgValue *getDbgValue(DIVariable *Var, DIExpression *Expr, SDNode *N,
1726                           unsigned R, bool IsIndirect, const DebugLoc &DL,
1727                           unsigned O);
1728 
1729   /// Creates a constant SDDbgValue node.
1730   SDDbgValue *getConstantDbgValue(DIVariable *Var, DIExpression *Expr,
1731                                   const Value *C, const DebugLoc &DL,
1732                                   unsigned O);
1733 
1734   /// Creates a FrameIndex SDDbgValue node.
1735   SDDbgValue *getFrameIndexDbgValue(DIVariable *Var, DIExpression *Expr,
1736                                     unsigned FI, bool IsIndirect,
1737                                     const DebugLoc &DL, unsigned O);
1738 
1739   /// Creates a FrameIndex SDDbgValue node.
1740   SDDbgValue *getFrameIndexDbgValue(DIVariable *Var, DIExpression *Expr,
1741                                     unsigned FI,
1742                                     ArrayRef<SDNode *> Dependencies,
1743                                     bool IsIndirect, const DebugLoc &DL,
1744                                     unsigned O);
1745 
1746   /// Creates a VReg SDDbgValue node.
1747   SDDbgValue *getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
1748                               unsigned VReg, bool IsIndirect,
1749                               const DebugLoc &DL, unsigned O);
1750 
1751   /// Creates a SDDbgValue node from a list of locations.
1752   SDDbgValue *getDbgValueList(DIVariable *Var, DIExpression *Expr,
1753                               ArrayRef<SDDbgOperand> Locs,
1754                               ArrayRef<SDNode *> Dependencies, bool IsIndirect,
1755                               const DebugLoc &DL, unsigned O, bool IsVariadic);
1756 
1757   /// Creates a SDDbgLabel node.
1758   SDDbgLabel *getDbgLabel(DILabel *Label, const DebugLoc &DL, unsigned O);
1759 
1760   /// Transfer debug values from one node to another, while optionally
1761   /// generating fragment expressions for split-up values. If \p InvalidateDbg
1762   /// is set, debug values are invalidated after they are transferred.
1763   void transferDbgValues(SDValue From, SDValue To, unsigned OffsetInBits = 0,
1764                          unsigned SizeInBits = 0, bool InvalidateDbg = true);
1765 
1766   /// Remove the specified node from the system. If any of its
1767   /// operands then becomes dead, remove them as well. Inform UpdateListener
1768   /// for each node deleted.
1769   void RemoveDeadNode(SDNode *N);
1770 
1771   /// This method deletes the unreachable nodes in the
1772   /// given list, and any nodes that become unreachable as a result.
1773   void RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes);
1774 
1775   /// Modify anything using 'From' to use 'To' instead.
1776   /// This can cause recursive merging of nodes in the DAG.  Use the first
1777   /// version if 'From' is known to have a single result, use the second
1778   /// if you have two nodes with identical results (or if 'To' has a superset
1779   /// of the results of 'From'), use the third otherwise.
1780   ///
1781   /// These methods all take an optional UpdateListener, which (if not null) is
1782   /// informed about nodes that are deleted and modified due to recursive
1783   /// changes in the dag.
1784   ///
1785   /// These functions only replace all existing uses. It's possible that as
1786   /// these replacements are being performed, CSE may cause the From node
1787   /// to be given new uses. These new uses of From are left in place, and
1788   /// not automatically transferred to To.
1789   ///
1790   void ReplaceAllUsesWith(SDValue From, SDValue To);
1791   void ReplaceAllUsesWith(SDNode *From, SDNode *To);
1792   void ReplaceAllUsesWith(SDNode *From, const SDValue *To);
1793 
1794   /// Replace any uses of From with To, leaving
1795   /// uses of other values produced by From.getNode() alone.
1796   void ReplaceAllUsesOfValueWith(SDValue From, SDValue To);
1797 
1798   /// Like ReplaceAllUsesOfValueWith, but for multiple values at once.
1799   /// This correctly handles the case where
1800   /// there is an overlap between the From values and the To values.
1801   void ReplaceAllUsesOfValuesWith(const SDValue *From, const SDValue *To,
1802                                   unsigned Num);
1803 
1804   /// If an existing load has uses of its chain, create a token factor node with
1805   /// that chain and the new memory node's chain and update users of the old
1806   /// chain to the token factor. This ensures that the new memory node will have
1807   /// the same relative memory dependency position as the old load. Returns the
1808   /// new merged load chain.
1809   SDValue makeEquivalentMemoryOrdering(SDValue OldChain, SDValue NewMemOpChain);
1810 
1811   /// If an existing load has uses of its chain, create a token factor node with
1812   /// that chain and the new memory node's chain and update users of the old
1813   /// chain to the token factor. This ensures that the new memory node will have
1814   /// the same relative memory dependency position as the old load. Returns the
1815   /// new merged load chain.
1816   SDValue makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, SDValue NewMemOp);
1817 
1818   /// Topological-sort the AllNodes list and a
1819   /// assign a unique node id for each node in the DAG based on their
1820   /// topological order. Returns the number of nodes.
1821   unsigned AssignTopologicalOrder();
1822 
1823   /// Move node N in the AllNodes list to be immediately
1824   /// before the given iterator Position. This may be used to update the
1825   /// topological ordering when the list of nodes is modified.
1826   void RepositionNode(allnodes_iterator Position, SDNode *N) {
1827     AllNodes.insert(Position, AllNodes.remove(N));
1828   }
1829 
1830   /// Add a dbg_value SDNode. If SD is non-null that means the
1831   /// value is produced by SD.
1832   void AddDbgValue(SDDbgValue *DB, bool isParameter);
1833 
1834   /// Add a dbg_label SDNode.
1835   void AddDbgLabel(SDDbgLabel *DB);
1836 
1837   /// Get the debug values which reference the given SDNode.
1838   ArrayRef<SDDbgValue*> GetDbgValues(const SDNode* SD) const {
1839     return DbgInfo->getSDDbgValues(SD);
1840   }
1841 
1842 public:
1843   /// Return true if there are any SDDbgValue nodes associated
1844   /// with this SelectionDAG.
1845   bool hasDebugValues() const { return !DbgInfo->empty(); }
1846 
1847   SDDbgInfo::DbgIterator DbgBegin() const { return DbgInfo->DbgBegin(); }
1848   SDDbgInfo::DbgIterator DbgEnd() const  { return DbgInfo->DbgEnd(); }
1849 
1850   SDDbgInfo::DbgIterator ByvalParmDbgBegin() const {
1851     return DbgInfo->ByvalParmDbgBegin();
1852   }
1853   SDDbgInfo::DbgIterator ByvalParmDbgEnd() const {
1854     return DbgInfo->ByvalParmDbgEnd();
1855   }
1856 
1857   SDDbgInfo::DbgLabelIterator DbgLabelBegin() const {
1858     return DbgInfo->DbgLabelBegin();
1859   }
1860   SDDbgInfo::DbgLabelIterator DbgLabelEnd() const {
1861     return DbgInfo->DbgLabelEnd();
1862   }
1863 
1864   /// To be invoked on an SDNode that is slated to be erased. This
1865   /// function mirrors \c llvm::salvageDebugInfo.
1866   void salvageDebugInfo(SDNode &N);
1867 
1868   void dump() const;
1869 
1870   /// In most cases this function returns the ABI alignment for a given type,
1871   /// except for illegal vector types where the alignment exceeds that of the
1872   /// stack. In such cases we attempt to break the vector down to a legal type
1873   /// and return the ABI alignment for that instead.
1874   Align getReducedAlign(EVT VT, bool UseABI);
1875 
1876   /// Create a stack temporary based on the size in bytes and the alignment
1877   SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment);
1878 
1879   /// Create a stack temporary, suitable for holding the specified value type.
1880   /// If minAlign is specified, the slot size will have at least that alignment.
1881   SDValue CreateStackTemporary(EVT VT, unsigned minAlign = 1);
1882 
1883   /// Create a stack temporary suitable for holding either of the specified
1884   /// value types.
1885   SDValue CreateStackTemporary(EVT VT1, EVT VT2);
1886 
1887   SDValue FoldSymbolOffset(unsigned Opcode, EVT VT,
1888                            const GlobalAddressSDNode *GA,
1889                            const SDNode *N2);
1890 
1891   SDValue FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT,
1892                                  ArrayRef<SDValue> Ops,
1893                                  SDNodeFlags Flags = SDNodeFlags());
1894 
1895   /// Fold floating-point operations when all operands are constants and/or
1896   /// undefined.
1897   SDValue foldConstantFPMath(unsigned Opcode, const SDLoc &DL, EVT VT,
1898                              ArrayRef<SDValue> Ops);
1899 
1900   /// Constant fold a setcc to true or false.
1901   SDValue FoldSetCC(EVT VT, SDValue N1, SDValue N2, ISD::CondCode Cond,
1902                     const SDLoc &dl);
1903 
1904   /// Return true if the sign bit of Op is known to be zero.
1905   /// We use this predicate to simplify operations downstream.
1906   bool SignBitIsZero(SDValue Op, unsigned Depth = 0) const;
1907 
1908   /// Return true if 'Op & Mask' is known to be zero.  We
1909   /// use this predicate to simplify operations downstream.  Op and Mask are
1910   /// known to be the same type.
1911   bool MaskedValueIsZero(SDValue Op, const APInt &Mask,
1912                          unsigned Depth = 0) const;
1913 
1914   /// Return true if 'Op & Mask' is known to be zero in DemandedElts.  We
1915   /// use this predicate to simplify operations downstream.  Op and Mask are
1916   /// known to be the same type.
1917   bool MaskedValueIsZero(SDValue Op, const APInt &Mask,
1918                          const APInt &DemandedElts, unsigned Depth = 0) const;
1919 
1920   /// Return true if 'Op' is known to be zero in DemandedElts.  We
1921   /// use this predicate to simplify operations downstream.
1922   bool MaskedVectorIsZero(SDValue Op, const APInt &DemandedElts,
1923                           unsigned Depth = 0) const;
1924 
1925   /// Return true if '(Op & Mask) == Mask'.
1926   /// Op and Mask are known to be the same type.
1927   bool MaskedValueIsAllOnes(SDValue Op, const APInt &Mask,
1928                             unsigned Depth = 0) const;
1929 
1930   /// For each demanded element of a vector, see if it is known to be zero.
1931   APInt computeVectorKnownZeroElements(SDValue Op, const APInt &DemandedElts,
1932                                        unsigned Depth = 0) const;
1933 
1934   /// Determine which bits of Op are known to be either zero or one and return
1935   /// them in Known. For vectors, the known bits are those that are shared by
1936   /// every vector element.
1937   /// Targets can implement the computeKnownBitsForTargetNode method in the
1938   /// TargetLowering class to allow target nodes to be understood.
1939   KnownBits computeKnownBits(SDValue Op, unsigned Depth = 0) const;
1940 
1941   /// Determine which bits of Op are known to be either zero or one and return
1942   /// them in Known. The DemandedElts argument allows us to only collect the
1943   /// known bits that are shared by the requested vector elements.
1944   /// Targets can implement the computeKnownBitsForTargetNode method in the
1945   /// TargetLowering class to allow target nodes to be understood.
1946   KnownBits computeKnownBits(SDValue Op, const APInt &DemandedElts,
1947                              unsigned Depth = 0) const;
1948 
1949   /// Used to represent the possible overflow behavior of an operation.
1950   /// Never: the operation cannot overflow.
1951   /// Always: the operation will always overflow.
1952   /// Sometime: the operation may or may not overflow.
1953   enum OverflowKind {
1954     OFK_Never,
1955     OFK_Sometime,
1956     OFK_Always,
1957   };
1958 
1959   /// Determine if the result of the signed addition of 2 nodes can overflow.
1960   OverflowKind computeOverflowForSignedAdd(SDValue N0, SDValue N1) const;
1961 
1962   /// Determine if the result of the unsigned addition of 2 nodes can overflow.
1963   OverflowKind computeOverflowForUnsignedAdd(SDValue N0, SDValue N1) const;
1964 
1965   /// Determine if the result of the addition of 2 nodes can overflow.
1966   OverflowKind computeOverflowForAdd(bool IsSigned, SDValue N0,
1967                                      SDValue N1) const {
1968     return IsSigned ? computeOverflowForSignedAdd(N0, N1)
1969                     : computeOverflowForUnsignedAdd(N0, N1);
1970   }
1971 
1972   /// Determine if the result of the addition of 2 nodes can never overflow.
1973   bool willNotOverflowAdd(bool IsSigned, SDValue N0, SDValue N1) const {
1974     return computeOverflowForAdd(IsSigned, N0, N1) == OFK_Never;
1975   }
1976 
1977   /// Determine if the result of the signed sub of 2 nodes can overflow.
1978   OverflowKind computeOverflowForSignedSub(SDValue N0, SDValue N1) const;
1979 
1980   /// Determine if the result of the unsigned sub of 2 nodes can overflow.
1981   OverflowKind computeOverflowForUnsignedSub(SDValue N0, SDValue N1) const;
1982 
1983   /// Determine if the result of the sub of 2 nodes can overflow.
1984   OverflowKind computeOverflowForSub(bool IsSigned, SDValue N0,
1985                                      SDValue N1) const {
1986     return IsSigned ? computeOverflowForSignedSub(N0, N1)
1987                     : computeOverflowForUnsignedSub(N0, N1);
1988   }
1989 
1990   /// Determine if the result of the sub of 2 nodes can never overflow.
1991   bool willNotOverflowSub(bool IsSigned, SDValue N0, SDValue N1) const {
1992     return computeOverflowForSub(IsSigned, N0, N1) == OFK_Never;
1993   }
1994 
1995   /// Determine if the result of the signed mul of 2 nodes can overflow.
1996   OverflowKind computeOverflowForSignedMul(SDValue N0, SDValue N1) const;
1997 
1998   /// Determine if the result of the unsigned mul of 2 nodes can overflow.
1999   OverflowKind computeOverflowForUnsignedMul(SDValue N0, SDValue N1) const;
2000 
2001   /// Determine if the result of the mul of 2 nodes can overflow.
2002   OverflowKind computeOverflowForMul(bool IsSigned, SDValue N0,
2003                                      SDValue N1) const {
2004     return IsSigned ? computeOverflowForSignedMul(N0, N1)
2005                     : computeOverflowForUnsignedMul(N0, N1);
2006   }
2007 
2008   /// Determine if the result of the mul of 2 nodes can never overflow.
2009   bool willNotOverflowMul(bool IsSigned, SDValue N0, SDValue N1) const {
2010     return computeOverflowForMul(IsSigned, N0, N1) == OFK_Never;
2011   }
2012 
2013   /// Test if the given value is known to have exactly one bit set. This differs
2014   /// from computeKnownBits in that it doesn't necessarily determine which bit
2015   /// is set.
2016   bool isKnownToBeAPowerOfTwo(SDValue Val, unsigned Depth = 0) const;
2017 
2018   /// Test if the given _fp_ value is known to be an integer power-of-2, either
2019   /// positive or negative.
2020   bool isKnownToBeAPowerOfTwoFP(SDValue Val, unsigned Depth = 0) const;
2021 
2022   /// Return the number of times the sign bit of the register is replicated into
2023   /// the other bits. We know that at least 1 bit is always equal to the sign
2024   /// bit (itself), but other cases can give us information. For example,
2025   /// immediately after an "SRA X, 2", we know that the top 3 bits are all equal
2026   /// to each other, so we return 3. Targets can implement the
2027   /// ComputeNumSignBitsForTarget method in the TargetLowering class to allow
2028   /// target nodes to be understood.
2029   unsigned ComputeNumSignBits(SDValue Op, unsigned Depth = 0) const;
2030 
2031   /// Return the number of times the sign bit of the register is replicated into
2032   /// the other bits. We know that at least 1 bit is always equal to the sign
2033   /// bit (itself), but other cases can give us information. For example,
2034   /// immediately after an "SRA X, 2", we know that the top 3 bits are all equal
2035   /// to each other, so we return 3. The DemandedElts argument allows
2036   /// us to only collect the minimum sign bits of the requested vector elements.
2037   /// Targets can implement the ComputeNumSignBitsForTarget method in the
2038   /// TargetLowering class to allow target nodes to be understood.
2039   unsigned ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
2040                               unsigned Depth = 0) const;
2041 
2042   /// Get the upper bound on bit size for this Value \p Op as a signed integer.
2043   /// i.e.  x == sext(trunc(x to MaxSignedBits) to bitwidth(x)).
2044   /// Similar to the APInt::getSignificantBits function.
2045   /// Helper wrapper to ComputeNumSignBits.
2046   unsigned ComputeMaxSignificantBits(SDValue Op, unsigned Depth = 0) const;
2047 
2048   /// Get the upper bound on bit size for this Value \p Op as a signed integer.
2049   /// i.e.  x == sext(trunc(x to MaxSignedBits) to bitwidth(x)).
2050   /// Similar to the APInt::getSignificantBits function.
2051   /// Helper wrapper to ComputeNumSignBits.
2052   unsigned ComputeMaxSignificantBits(SDValue Op, const APInt &DemandedElts,
2053                                      unsigned Depth = 0) const;
2054 
2055   /// Return true if this function can prove that \p Op is never poison
2056   /// and, if \p PoisonOnly is false, does not have undef bits.
2057   bool isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly = false,
2058                                         unsigned Depth = 0) const;
2059 
2060   /// Return true if this function can prove that \p Op is never poison
2061   /// and, if \p PoisonOnly is false, does not have undef bits. The DemandedElts
2062   /// argument limits the check to the requested vector elements.
2063   bool isGuaranteedNotToBeUndefOrPoison(SDValue Op, const APInt &DemandedElts,
2064                                         bool PoisonOnly = false,
2065                                         unsigned Depth = 0) const;
2066 
2067   /// Return true if this function can prove that \p Op is never poison.
2068   bool isGuaranteedNotToBePoison(SDValue Op, unsigned Depth = 0) const {
2069     return isGuaranteedNotToBeUndefOrPoison(Op, /*PoisonOnly*/ true, Depth);
2070   }
2071 
2072   /// Return true if this function can prove that \p Op is never poison. The
2073   /// DemandedElts argument limits the check to the requested vector elements.
2074   bool isGuaranteedNotToBePoison(SDValue Op, const APInt &DemandedElts,
2075                                  unsigned Depth = 0) const {
2076     return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts,
2077                                             /*PoisonOnly*/ true, Depth);
2078   }
2079 
2080   /// Return true if Op can create undef or poison from non-undef & non-poison
2081   /// operands. The DemandedElts argument limits the check to the requested
2082   /// vector elements.
2083   ///
2084   /// \p ConsiderFlags controls whether poison producing flags on the
2085   /// instruction are considered.  This can be used to see if the instruction
2086   /// could still introduce undef or poison even without poison generating flags
2087   /// which might be on the instruction.  (i.e. could the result of
2088   /// Op->dropPoisonGeneratingFlags() still create poison or undef)
2089   bool canCreateUndefOrPoison(SDValue Op, const APInt &DemandedElts,
2090                               bool PoisonOnly = false,
2091                               bool ConsiderFlags = true,
2092                               unsigned Depth = 0) const;
2093 
2094   /// Return true if Op can create undef or poison from non-undef & non-poison
2095   /// operands.
2096   ///
2097   /// \p ConsiderFlags controls whether poison producing flags on the
2098   /// instruction are considered.  This can be used to see if the instruction
2099   /// could still introduce undef or poison even without poison generating flags
2100   /// which might be on the instruction.  (i.e. could the result of
2101   /// Op->dropPoisonGeneratingFlags() still create poison or undef)
2102   bool canCreateUndefOrPoison(SDValue Op, bool PoisonOnly = false,
2103                               bool ConsiderFlags = true,
2104                               unsigned Depth = 0) const;
2105 
2106   /// Return true if the specified operand is an ISD::OR or ISD::XOR node
2107   /// that can be treated as an ISD::ADD node.
2108   /// or(x,y) == add(x,y) iff haveNoCommonBitsSet(x,y)
2109   /// xor(x,y) == add(x,y) iff isMinSignedConstant(y) && !NoWrap
2110   /// If \p NoWrap is true, this will not match ISD::XOR.
2111   bool isADDLike(SDValue Op, bool NoWrap = false) const;
2112 
2113   /// Return true if the specified operand is an ISD::ADD with a ConstantSDNode
2114   /// on the right-hand side, or if it is an ISD::OR with a ConstantSDNode that
2115   /// is guaranteed to have the same semantics as an ADD. This handles the
2116   /// equivalence:
2117   ///     X|Cst == X+Cst iff X&Cst = 0.
2118   bool isBaseWithConstantOffset(SDValue Op) const;
2119 
2120   /// Test whether the given SDValue (or all elements of it, if it is a
2121   /// vector) is known to never be NaN. If \p SNaN is true, returns if \p Op is
2122   /// known to never be a signaling NaN (it may still be a qNaN).
2123   bool isKnownNeverNaN(SDValue Op, bool SNaN = false, unsigned Depth = 0) const;
2124 
2125   /// \returns true if \p Op is known to never be a signaling NaN.
2126   bool isKnownNeverSNaN(SDValue Op, unsigned Depth = 0) const {
2127     return isKnownNeverNaN(Op, true, Depth);
2128   }
2129 
2130   /// Test whether the given floating point SDValue is known to never be
2131   /// positive or negative zero.
2132   bool isKnownNeverZeroFloat(SDValue Op) const;
2133 
2134   /// Test whether the given SDValue is known to contain non-zero value(s).
2135   bool isKnownNeverZero(SDValue Op, unsigned Depth = 0) const;
2136 
2137   /// Test whether the given float value is known to be positive. +0.0, +inf and
2138   /// +nan are considered positive, -0.0, -inf and -nan are not.
2139   bool cannotBeOrderedNegativeFP(SDValue Op) const;
2140 
2141   /// Test whether two SDValues are known to compare equal. This
2142   /// is true if they are the same value, or if one is negative zero and the
2143   /// other positive zero.
2144   bool isEqualTo(SDValue A, SDValue B) const;
2145 
2146   /// Return true if A and B have no common bits set. As an example, this can
2147   /// allow an 'add' to be transformed into an 'or'.
2148   bool haveNoCommonBitsSet(SDValue A, SDValue B) const;
2149 
2150   /// Test whether \p V has a splatted value for all the demanded elements.
2151   ///
2152   /// On success \p UndefElts will indicate the elements that have UNDEF
2153   /// values instead of the splat value, this is only guaranteed to be correct
2154   /// for \p DemandedElts.
2155   ///
2156   /// NOTE: The function will return true for a demanded splat of UNDEF values.
2157   bool isSplatValue(SDValue V, const APInt &DemandedElts, APInt &UndefElts,
2158                     unsigned Depth = 0) const;
2159 
2160   /// Test whether \p V has a splatted value.
2161   bool isSplatValue(SDValue V, bool AllowUndefs = false) const;
2162 
2163   /// If V is a splatted value, return the source vector and its splat index.
2164   SDValue getSplatSourceVector(SDValue V, int &SplatIndex);
2165 
2166   /// If V is a splat vector, return its scalar source operand by extracting
2167   /// that element from the source vector. If LegalTypes is true, this method
2168   /// may only return a legally-typed splat value. If it cannot legalize the
2169   /// splatted value it will return SDValue().
2170   SDValue getSplatValue(SDValue V, bool LegalTypes = false);
2171 
2172   /// If a SHL/SRA/SRL node \p V has shift amounts that are all less than the
2173   /// element bit-width of the shift node, return the valid constant range.
2174   std::optional<ConstantRange>
2175   getValidShiftAmountRange(SDValue V, const APInt &DemandedElts,
2176                            unsigned Depth) const;
2177 
2178   /// If a SHL/SRA/SRL node \p V has a uniform shift amount
2179   /// that is less than the element bit-width of the shift node, return it.
2180   std::optional<uint64_t> getValidShiftAmount(SDValue V,
2181                                               const APInt &DemandedElts,
2182                                               unsigned Depth = 0) const;
2183 
2184   /// If a SHL/SRA/SRL node \p V has a uniform shift amount
2185   /// that is less than the element bit-width of the shift node, return it.
2186   std::optional<uint64_t> getValidShiftAmount(SDValue V,
2187                                               unsigned Depth = 0) const;
2188 
2189   /// If a SHL/SRA/SRL node \p V has shift amounts that are all less than the
2190   /// element bit-width of the shift node, return the minimum possible value.
2191   std::optional<uint64_t> getValidMinimumShiftAmount(SDValue V,
2192                                                      const APInt &DemandedElts,
2193                                                      unsigned Depth = 0) const;
2194 
2195   /// If a SHL/SRA/SRL node \p V has shift amounts that are all less than the
2196   /// element bit-width of the shift node, return the minimum possible value.
2197   std::optional<uint64_t> getValidMinimumShiftAmount(SDValue V,
2198                                                      unsigned Depth = 0) const;
2199 
2200   /// If a SHL/SRA/SRL node \p V has shift amounts that are all less than the
2201   /// element bit-width of the shift node, return the maximum possible value.
2202   std::optional<uint64_t> getValidMaximumShiftAmount(SDValue V,
2203                                                      const APInt &DemandedElts,
2204                                                      unsigned Depth = 0) const;
2205 
2206   /// If a SHL/SRA/SRL node \p V has shift amounts that are all less than the
2207   /// element bit-width of the shift node, return the maximum possible value.
2208   std::optional<uint64_t> getValidMaximumShiftAmount(SDValue V,
2209                                                      unsigned Depth = 0) const;
2210 
2211   /// Match a binop + shuffle pyramid that represents a horizontal reduction
2212   /// over the elements of a vector starting from the EXTRACT_VECTOR_ELT node /p
2213   /// Extract. The reduction must use one of the opcodes listed in /p
2214   /// CandidateBinOps and on success /p BinOp will contain the matching opcode.
2215   /// Returns the vector that is being reduced on, or SDValue() if a reduction
2216   /// was not matched. If \p AllowPartials is set then in the case of a
2217   /// reduction pattern that only matches the first few stages, the extracted
2218   /// subvector of the start of the reduction is returned.
2219   SDValue matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
2220                               ArrayRef<ISD::NodeType> CandidateBinOps,
2221                               bool AllowPartials = false);
2222 
2223   /// Utility function used by legalize and lowering to
2224   /// "unroll" a vector operation by splitting out the scalars and operating
2225   /// on each element individually.  If the ResNE is 0, fully unroll the vector
2226   /// op. If ResNE is less than the width of the vector op, unroll up to ResNE.
2227   /// If the  ResNE is greater than the width of the vector op, unroll the
2228   /// vector op and fill the end of the resulting vector with UNDEFS.
2229   SDValue UnrollVectorOp(SDNode *N, unsigned ResNE = 0);
2230 
2231   /// Like UnrollVectorOp(), but for the [US](ADD|SUB|MUL)O family of opcodes.
2232   /// This is a separate function because those opcodes have two results.
2233   std::pair<SDValue, SDValue> UnrollVectorOverflowOp(SDNode *N,
2234                                                      unsigned ResNE = 0);
2235 
2236   /// Return true if loads are next to each other and can be
2237   /// merged. Check that both are nonvolatile and if LD is loading
2238   /// 'Bytes' bytes from a location that is 'Dist' units away from the
2239   /// location that the 'Base' load is loading from.
2240   bool areNonVolatileConsecutiveLoads(LoadSDNode *LD, LoadSDNode *Base,
2241                                       unsigned Bytes, int Dist) const;
2242 
2243   /// Infer alignment of a load / store address. Return std::nullopt if it
2244   /// cannot be inferred.
2245   MaybeAlign InferPtrAlign(SDValue Ptr) const;
2246 
2247   /// Split the scalar node with EXTRACT_ELEMENT using the provided VTs and
2248   /// return the low/high part.
2249   std::pair<SDValue, SDValue> SplitScalar(const SDValue &N, const SDLoc &DL,
2250                                           const EVT &LoVT, const EVT &HiVT);
2251 
2252   /// Compute the VTs needed for the low/hi parts of a type
2253   /// which is split (or expanded) into two not necessarily identical pieces.
2254   std::pair<EVT, EVT> GetSplitDestVTs(const EVT &VT) const;
2255 
2256   /// Compute the VTs needed for the low/hi parts of a type, dependent on an
2257   /// enveloping VT that has been split into two identical pieces. Sets the
2258   /// HisIsEmpty flag when hi type has zero storage size.
2259   std::pair<EVT, EVT> GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
2260                                                bool *HiIsEmpty) const;
2261 
2262   /// Split the vector with EXTRACT_SUBVECTOR using the provided
2263   /// VTs and return the low/high part.
2264   std::pair<SDValue, SDValue> SplitVector(const SDValue &N, const SDLoc &DL,
2265                                           const EVT &LoVT, const EVT &HiVT);
2266 
2267   /// Split the vector with EXTRACT_SUBVECTOR and return the low/high part.
2268   std::pair<SDValue, SDValue> SplitVector(const SDValue &N, const SDLoc &DL) {
2269     EVT LoVT, HiVT;
2270     std::tie(LoVT, HiVT) = GetSplitDestVTs(N.getValueType());
2271     return SplitVector(N, DL, LoVT, HiVT);
2272   }
2273 
2274   /// Split the explicit vector length parameter of a VP operation.
2275   std::pair<SDValue, SDValue> SplitEVL(SDValue N, EVT VecVT, const SDLoc &DL);
2276 
2277   /// Split the node's operand with EXTRACT_SUBVECTOR and
2278   /// return the low/high part.
2279   std::pair<SDValue, SDValue> SplitVectorOperand(const SDNode *N, unsigned OpNo)
2280   {
2281     return SplitVector(N->getOperand(OpNo), SDLoc(N));
2282   }
2283 
2284   /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
2285   SDValue WidenVector(const SDValue &N, const SDLoc &DL);
2286 
2287   /// Append the extracted elements from Start to Count out of the vector Op in
2288   /// Args. If Count is 0, all of the elements will be extracted. The extracted
2289   /// elements will have type EVT if it is provided, and otherwise their type
2290   /// will be Op's element type.
2291   void ExtractVectorElements(SDValue Op, SmallVectorImpl<SDValue> &Args,
2292                              unsigned Start = 0, unsigned Count = 0,
2293                              EVT EltVT = EVT());
2294 
2295   /// Compute the default alignment value for the given type.
2296   Align getEVTAlign(EVT MemoryVT) const;
2297 
2298   /// Test whether the given value is a constant int or similar node.
2299   SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) const;
2300 
2301   /// Test whether the given value is a constant FP or similar node.
2302   SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) const ;
2303 
2304   /// \returns true if \p N is any kind of constant or build_vector of
2305   /// constants, int or float. If a vector, it may not necessarily be a splat.
2306   inline bool isConstantValueOfAnyType(SDValue N) const {
2307     return isConstantIntBuildVectorOrConstantInt(N) ||
2308            isConstantFPBuildVectorOrConstantFP(N);
2309   }
2310 
2311   /// Check if a value \op N is a constant using the target's BooleanContent for
2312   /// its type.
2313   std::optional<bool> isBoolConstant(SDValue N,
2314                                      bool AllowTruncation = false) const;
2315 
2316   /// Set CallSiteInfo to be associated with Node.
2317   void addCallSiteInfo(const SDNode *Node, CallSiteInfo &&CallInfo) {
2318     SDEI[Node].CSInfo = std::move(CallInfo);
2319   }
2320   /// Return CallSiteInfo associated with Node, or a default if none exists.
2321   CallSiteInfo getCallSiteInfo(const SDNode *Node) {
2322     auto I = SDEI.find(Node);
2323     return I != SDEI.end() ? std::move(I->second).CSInfo : CallSiteInfo();
2324   }
2325   /// Set HeapAllocSite to be associated with Node.
2326   void addHeapAllocSite(const SDNode *Node, MDNode *MD) {
2327     SDEI[Node].HeapAllocSite = MD;
2328   }
2329   /// Return HeapAllocSite associated with Node, or nullptr if none exists.
2330   MDNode *getHeapAllocSite(const SDNode *Node) const {
2331     auto I = SDEI.find(Node);
2332     return I != SDEI.end() ? I->second.HeapAllocSite : nullptr;
2333   }
2334   /// Set PCSections to be associated with Node.
2335   void addPCSections(const SDNode *Node, MDNode *MD) {
2336     SDEI[Node].PCSections = MD;
2337   }
2338   /// Set MMRAMetadata to be associated with Node.
2339   void addMMRAMetadata(const SDNode *Node, MDNode *MMRA) {
2340     SDEI[Node].MMRA = MMRA;
2341   }
2342   /// Return PCSections associated with Node, or nullptr if none exists.
2343   MDNode *getPCSections(const SDNode *Node) const {
2344     auto It = SDEI.find(Node);
2345     return It != SDEI.end() ? It->second.PCSections : nullptr;
2346   }
2347   /// Return the MMRA MDNode associated with Node, or nullptr if none
2348   /// exists.
2349   MDNode *getMMRAMetadata(const SDNode *Node) const {
2350     auto It = SDEI.find(Node);
2351     return It != SDEI.end() ? It->second.MMRA : nullptr;
2352   }
2353   /// Set NoMergeSiteInfo to be associated with Node if NoMerge is true.
2354   void addNoMergeSiteInfo(const SDNode *Node, bool NoMerge) {
2355     if (NoMerge)
2356       SDEI[Node].NoMerge = NoMerge;
2357   }
2358   /// Return NoMerge info associated with Node.
2359   bool getNoMergeSiteInfo(const SDNode *Node) const {
2360     auto I = SDEI.find(Node);
2361     return I != SDEI.end() ? I->second.NoMerge : false;
2362   }
2363 
2364   /// Copy extra info associated with one node to another.
2365   void copyExtraInfo(SDNode *From, SDNode *To);
2366 
2367   /// Return the current function's default denormal handling kind for the given
2368   /// floating point type.
2369   DenormalMode getDenormalMode(EVT VT) const {
2370     return MF->getDenormalMode(VT.getFltSemantics());
2371   }
2372 
2373   bool shouldOptForSize() const;
2374 
2375   /// Get the (commutative) neutral element for the given opcode, if it exists.
2376   SDValue getNeutralElement(unsigned Opcode, const SDLoc &DL, EVT VT,
2377                             SDNodeFlags Flags);
2378 
2379   /// Some opcodes may create immediate undefined behavior when used with some
2380   /// values (integer division-by-zero for example). Therefore, these operations
2381   /// are not generally safe to move around or change.
2382   bool isSafeToSpeculativelyExecute(unsigned Opcode) const {
2383     switch (Opcode) {
2384     case ISD::SDIV:
2385     case ISD::SREM:
2386     case ISD::SDIVREM:
2387     case ISD::UDIV:
2388     case ISD::UREM:
2389     case ISD::UDIVREM:
2390       return false;
2391     default:
2392       return true;
2393     }
2394   }
2395 
2396   /// Check if the provided node is save to speculatively executed given its
2397   /// current arguments. So, while `udiv` the opcode is not safe to
2398   /// speculatively execute, a given `udiv` node may be if the denominator is
2399   /// known nonzero.
2400   bool isSafeToSpeculativelyExecuteNode(const SDNode *N) const {
2401     switch (N->getOpcode()) {
2402     case ISD::UDIV:
2403       return isKnownNeverZero(N->getOperand(1));
2404     default:
2405       return isSafeToSpeculativelyExecute(N->getOpcode());
2406     }
2407   }
2408 
2409   SDValue makeStateFunctionCall(unsigned LibFunc, SDValue Ptr, SDValue InChain,
2410                                 const SDLoc &DLoc);
2411 
2412 private:
2413   void InsertNode(SDNode *N);
2414   bool RemoveNodeFromCSEMaps(SDNode *N);
2415   void AddModifiedNodeToCSEMaps(SDNode *N);
2416   SDNode *FindModifiedNodeSlot(SDNode *N, SDValue Op, void *&InsertPos);
2417   SDNode *FindModifiedNodeSlot(SDNode *N, SDValue Op1, SDValue Op2,
2418                                void *&InsertPos);
2419   SDNode *FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
2420                                void *&InsertPos);
2421   SDNode *UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &loc);
2422 
2423   void DeleteNodeNotInCSEMaps(SDNode *N);
2424   void DeallocateNode(SDNode *N);
2425 
2426   void allnodes_clear();
2427 
2428   /// Look up the node specified by ID in CSEMap.  If it exists, return it.  If
2429   /// not, return the insertion token that will make insertion faster.  This
2430   /// overload is for nodes other than Constant or ConstantFP, use the other one
2431   /// for those.
2432   SDNode *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos);
2433 
2434   /// Look up the node specified by ID in CSEMap.  If it exists, return it.  If
2435   /// not, return the insertion token that will make insertion faster.  Performs
2436   /// additional processing for constant nodes.
2437   SDNode *FindNodeOrInsertPos(const FoldingSetNodeID &ID, const SDLoc &DL,
2438                               void *&InsertPos);
2439 
2440   /// Maps to auto-CSE operations.
2441   std::vector<CondCodeSDNode*> CondCodeNodes;
2442 
2443   std::vector<SDNode*> ValueTypeNodes;
2444   std::map<EVT, SDNode*, EVT::compareRawBits> ExtendedValueTypeNodes;
2445   StringMap<SDNode*> ExternalSymbols;
2446 
2447   std::map<std::pair<std::string, unsigned>, SDNode *> TargetExternalSymbols;
2448   DenseMap<MCSymbol *, SDNode *> MCSymbols;
2449 
2450   FlagInserter *Inserter = nullptr;
2451 };
2452 
2453 template <> struct GraphTraits<SelectionDAG*> : public GraphTraits<SDNode*> {
2454   using nodes_iterator = pointer_iterator<SelectionDAG::allnodes_iterator>;
2455 
2456   static nodes_iterator nodes_begin(SelectionDAG *G) {
2457     return nodes_iterator(G->allnodes_begin());
2458   }
2459 
2460   static nodes_iterator nodes_end(SelectionDAG *G) {
2461     return nodes_iterator(G->allnodes_end());
2462   }
2463 };
2464 
2465 } // end namespace llvm
2466 
2467 #endif // LLVM_CODEGEN_SELECTIONDAG_H
2468