Bug Summary

File:llvm/include/llvm/CodeGen/SelectionDAGNodes.h
Warning:line 1102, column 10
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name StatepointLowering.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/lib/CodeGen/SelectionDAG -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/build-llvm/lib/CodeGen/SelectionDAG -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-11-29-190409-37574-1 -x c++ /build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp

/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp

1//===- StatepointLowering.cpp - SDAGBuilder's statepoint code -------------===//
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 includes support code use by SelectionDAGBuilder when lowering a
10// statepoint sequence in SelectionDAG IR.
11//
12//===----------------------------------------------------------------------===//
13
14#include "StatepointLowering.h"
15#include "SelectionDAGBuilder.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/None.h"
18#include "llvm/ADT/Optional.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallSet.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/CodeGen/FunctionLoweringInfo.h"
23#include "llvm/CodeGen/GCMetadata.h"
24#include "llvm/CodeGen/GCStrategy.h"
25#include "llvm/CodeGen/ISDOpcodes.h"
26#include "llvm/CodeGen/MachineFrameInfo.h"
27#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineMemOperand.h"
29#include "llvm/CodeGen/RuntimeLibcalls.h"
30#include "llvm/CodeGen/SelectionDAG.h"
31#include "llvm/CodeGen/StackMaps.h"
32#include "llvm/CodeGen/TargetLowering.h"
33#include "llvm/CodeGen/TargetOpcodes.h"
34#include "llvm/IR/CallingConv.h"
35#include "llvm/IR/DerivedTypes.h"
36#include "llvm/IR/Instruction.h"
37#include "llvm/IR/Instructions.h"
38#include "llvm/IR/LLVMContext.h"
39#include "llvm/IR/Statepoint.h"
40#include "llvm/IR/Type.h"
41#include "llvm/Support/Casting.h"
42#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/MachineValueType.h"
44#include "llvm/Target/TargetMachine.h"
45#include "llvm/Target/TargetOptions.h"
46#include <cassert>
47#include <cstddef>
48#include <cstdint>
49#include <iterator>
50#include <tuple>
51#include <utility>
52
53using namespace llvm;
54
55#define DEBUG_TYPE"statepoint-lowering" "statepoint-lowering"
56
57STATISTIC(NumSlotsAllocatedForStatepoints,static llvm::Statistic NumSlotsAllocatedForStatepoints = {"statepoint-lowering"
, "NumSlotsAllocatedForStatepoints", "Number of stack slots allocated for statepoints"
}
58 "Number of stack slots allocated for statepoints")static llvm::Statistic NumSlotsAllocatedForStatepoints = {"statepoint-lowering"
, "NumSlotsAllocatedForStatepoints", "Number of stack slots allocated for statepoints"
}
;
59STATISTIC(NumOfStatepoints, "Number of statepoint nodes encountered")static llvm::Statistic NumOfStatepoints = {"statepoint-lowering"
, "NumOfStatepoints", "Number of statepoint nodes encountered"
}
;
60STATISTIC(StatepointMaxSlotsRequired,static llvm::Statistic StatepointMaxSlotsRequired = {"statepoint-lowering"
, "StatepointMaxSlotsRequired", "Maximum number of stack slots required for a singe statepoint"
}
61 "Maximum number of stack slots required for a singe statepoint")static llvm::Statistic StatepointMaxSlotsRequired = {"statepoint-lowering"
, "StatepointMaxSlotsRequired", "Maximum number of stack slots required for a singe statepoint"
}
;
62
63cl::opt<bool> UseRegistersForDeoptValues(
64 "use-registers-for-deopt-values", cl::Hidden, cl::init(false),
65 cl::desc("Allow using registers for non pointer deopt args"));
66
67cl::opt<unsigned> MaxRegistersForGCPointers(
68 "max-registers-for-gc-values", cl::Hidden, cl::init(0),
69 cl::desc("Max number of VRegs allowed to pass GC pointer meta args in"));
70
71cl::opt<bool> AlwaysSpillBase("statepoint-always-spill-base", cl::Hidden,
72 cl::init(true),
73 cl::desc("Force spilling of base GC pointers"));
74
75typedef FunctionLoweringInfo::StatepointRelocationRecord RecordType;
76
77static void pushStackMapConstant(SmallVectorImpl<SDValue>& Ops,
78 SelectionDAGBuilder &Builder, uint64_t Value) {
79 SDLoc L = Builder.getCurSDLoc();
80 Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp, L,
81 MVT::i64));
82 Ops.push_back(Builder.DAG.getTargetConstant(Value, L, MVT::i64));
83}
84
85void StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
86 // Consistency check
87 assert(PendingGCRelocateCalls.empty() &&((PendingGCRelocateCalls.empty() && "Trying to visit statepoint before finished processing previous one"
) ? static_cast<void> (0) : __assert_fail ("PendingGCRelocateCalls.empty() && \"Trying to visit statepoint before finished processing previous one\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 88, __PRETTY_FUNCTION__))
88 "Trying to visit statepoint before finished processing previous one")((PendingGCRelocateCalls.empty() && "Trying to visit statepoint before finished processing previous one"
) ? static_cast<void> (0) : __assert_fail ("PendingGCRelocateCalls.empty() && \"Trying to visit statepoint before finished processing previous one\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 88, __PRETTY_FUNCTION__))
;
89 Locations.clear();
90 NextSlotToAllocate = 0;
91 // Need to resize this on each safepoint - we need the two to stay in sync and
92 // the clear patterns of a SelectionDAGBuilder have no relation to
93 // FunctionLoweringInfo. Also need to ensure used bits get cleared.
94 AllocatedStackSlots.clear();
95 AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
96}
97
98void StatepointLoweringState::clear() {
99 Locations.clear();
100 AllocatedStackSlots.clear();
101 assert(PendingGCRelocateCalls.empty() &&((PendingGCRelocateCalls.empty() && "cleared before statepoint sequence completed"
) ? static_cast<void> (0) : __assert_fail ("PendingGCRelocateCalls.empty() && \"cleared before statepoint sequence completed\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 102, __PRETTY_FUNCTION__))
102 "cleared before statepoint sequence completed")((PendingGCRelocateCalls.empty() && "cleared before statepoint sequence completed"
) ? static_cast<void> (0) : __assert_fail ("PendingGCRelocateCalls.empty() && \"cleared before statepoint sequence completed\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 102, __PRETTY_FUNCTION__))
;
103}
104
105SDValue
106StatepointLoweringState::allocateStackSlot(EVT ValueType,
107 SelectionDAGBuilder &Builder) {
108 NumSlotsAllocatedForStatepoints++;
109 MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
110
111 unsigned SpillSize = ValueType.getStoreSize();
112 assert((SpillSize * 8) == ValueType.getSizeInBits() && "Size not in bytes?")(((SpillSize * 8) == ValueType.getSizeInBits() && "Size not in bytes?"
) ? static_cast<void> (0) : __assert_fail ("(SpillSize * 8) == ValueType.getSizeInBits() && \"Size not in bytes?\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 112, __PRETTY_FUNCTION__))
;
113
114 // First look for a previously created stack slot which is not in
115 // use (accounting for the fact arbitrary slots may already be
116 // reserved), or to create a new stack slot and use it.
117
118 const size_t NumSlots = AllocatedStackSlots.size();
119 assert(NextSlotToAllocate <= NumSlots && "Broken invariant")((NextSlotToAllocate <= NumSlots && "Broken invariant"
) ? static_cast<void> (0) : __assert_fail ("NextSlotToAllocate <= NumSlots && \"Broken invariant\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 119, __PRETTY_FUNCTION__))
;
120
121 assert(AllocatedStackSlots.size() ==((AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots
.size() && "Broken invariant") ? static_cast<void>
(0) : __assert_fail ("AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots.size() && \"Broken invariant\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 123, __PRETTY_FUNCTION__))
122 Builder.FuncInfo.StatepointStackSlots.size() &&((AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots
.size() && "Broken invariant") ? static_cast<void>
(0) : __assert_fail ("AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots.size() && \"Broken invariant\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 123, __PRETTY_FUNCTION__))
123 "Broken invariant")((AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots
.size() && "Broken invariant") ? static_cast<void>
(0) : __assert_fail ("AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots.size() && \"Broken invariant\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 123, __PRETTY_FUNCTION__))
;
124
125 for (; NextSlotToAllocate < NumSlots; NextSlotToAllocate++) {
126 if (!AllocatedStackSlots.test(NextSlotToAllocate)) {
127 const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
128 if (MFI.getObjectSize(FI) == SpillSize) {
129 AllocatedStackSlots.set(NextSlotToAllocate);
130 // TODO: Is ValueType the right thing to use here?
131 return Builder.DAG.getFrameIndex(FI, ValueType);
132 }
133 }
134 }
135
136 // Couldn't find a free slot, so create a new one:
137
138 SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
139 const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
140 MFI.markAsStatepointSpillSlotObjectIndex(FI);
141
142 Builder.FuncInfo.StatepointStackSlots.push_back(FI);
143 AllocatedStackSlots.resize(AllocatedStackSlots.size()+1, true);
144 assert(AllocatedStackSlots.size() ==((AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots
.size() && "Broken invariant") ? static_cast<void>
(0) : __assert_fail ("AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots.size() && \"Broken invariant\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 146, __PRETTY_FUNCTION__))
145 Builder.FuncInfo.StatepointStackSlots.size() &&((AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots
.size() && "Broken invariant") ? static_cast<void>
(0) : __assert_fail ("AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots.size() && \"Broken invariant\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 146, __PRETTY_FUNCTION__))
146 "Broken invariant")((AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots
.size() && "Broken invariant") ? static_cast<void>
(0) : __assert_fail ("AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots.size() && \"Broken invariant\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 146, __PRETTY_FUNCTION__))
;
147
148 StatepointMaxSlotsRequired.updateMax(
149 Builder.FuncInfo.StatepointStackSlots.size());
150
151 return SpillSlot;
152}
153
154/// Utility function for reservePreviousStackSlotForValue. Tries to find
155/// stack slot index to which we have spilled value for previous statepoints.
156/// LookUpDepth specifies maximum DFS depth this function is allowed to look.
157static Optional<int> findPreviousSpillSlot(const Value *Val,
158 SelectionDAGBuilder &Builder,
159 int LookUpDepth) {
160 // Can not look any further - give up now
161 if (LookUpDepth <= 0)
162 return None;
163
164 // Spill location is known for gc relocates
165 if (const auto *Relocate = dyn_cast<GCRelocateInst>(Val)) {
166 const auto &RelocationMap =
167 Builder.FuncInfo.StatepointRelocationMaps[Relocate->getStatepoint()];
168
169 auto It = RelocationMap.find(Relocate->getDerivedPtr());
170 if (It == RelocationMap.end())
171 return None;
172
173 auto &Record = It->second;
174 if (Record.type != RecordType::Spill)
175 return None;
176
177 return Record.payload.FI;
178 }
179
180 // Look through bitcast instructions.
181 if (const BitCastInst *Cast = dyn_cast<BitCastInst>(Val))
182 return findPreviousSpillSlot(Cast->getOperand(0), Builder, LookUpDepth - 1);
183
184 // Look through phi nodes
185 // All incoming values should have same known stack slot, otherwise result
186 // is unknown.
187 if (const PHINode *Phi = dyn_cast<PHINode>(Val)) {
188 Optional<int> MergedResult = None;
189
190 for (auto &IncomingValue : Phi->incoming_values()) {
191 Optional<int> SpillSlot =
192 findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth - 1);
193 if (!SpillSlot.hasValue())
194 return None;
195
196 if (MergedResult.hasValue() && *MergedResult != *SpillSlot)
197 return None;
198
199 MergedResult = SpillSlot;
200 }
201 return MergedResult;
202 }
203
204 // TODO: We can do better for PHI nodes. In cases like this:
205 // ptr = phi(relocated_pointer, not_relocated_pointer)
206 // statepoint(ptr)
207 // We will return that stack slot for ptr is unknown. And later we might
208 // assign different stack slots for ptr and relocated_pointer. This limits
209 // llvm's ability to remove redundant stores.
210 // Unfortunately it's hard to accomplish in current infrastructure.
211 // We use this function to eliminate spill store completely, while
212 // in example we still need to emit store, but instead of any location
213 // we need to use special "preferred" location.
214
215 // TODO: handle simple updates. If a value is modified and the original
216 // value is no longer live, it would be nice to put the modified value in the
217 // same slot. This allows folding of the memory accesses for some
218 // instructions types (like an increment).
219 // statepoint (i)
220 // i1 = i+1
221 // statepoint (i1)
222 // However we need to be careful for cases like this:
223 // statepoint(i)
224 // i1 = i+1
225 // statepoint(i, i1)
226 // Here we want to reserve spill slot for 'i', but not for 'i+1'. If we just
227 // put handling of simple modifications in this function like it's done
228 // for bitcasts we might end up reserving i's slot for 'i+1' because order in
229 // which we visit values is unspecified.
230
231 // Don't know any information about this instruction
232 return None;
233}
234
235/// Return true if-and-only-if the given SDValue can be lowered as either a
236/// constant argument or a stack reference. The key point is that the value
237/// doesn't need to be spilled or tracked as a vreg use.
238static bool willLowerDirectly(SDValue Incoming) {
239 // We are making an unchecked assumption that the frame size <= 2^16 as that
240 // is the largest offset which can be encoded in the stackmap format.
241 if (isa<FrameIndexSDNode>(Incoming))
242 return true;
243
244 // The largest constant describeable in the StackMap format is 64 bits.
245 // Potential Optimization: Constants values are sign extended by consumer,
246 // and thus there are many constants of static type > 64 bits whose value
247 // happens to be sext(Con64) and could thus be lowered directly.
248 if (Incoming.getValueType().getSizeInBits() > 64)
249 return false;
250
251 return (isa<ConstantSDNode>(Incoming) || isa<ConstantFPSDNode>(Incoming) ||
252 Incoming.isUndef());
253}
254
255/// Try to find existing copies of the incoming values in stack slots used for
256/// statepoint spilling. If we can find a spill slot for the incoming value,
257/// mark that slot as allocated, and reuse the same slot for this safepoint.
258/// This helps to avoid series of loads and stores that only serve to reshuffle
259/// values on the stack between calls.
260static void reservePreviousStackSlotForValue(const Value *IncomingValue,
261 SelectionDAGBuilder &Builder) {
262 SDValue Incoming = Builder.getValue(IncomingValue);
263
264 // If we won't spill this, we don't need to check for previously allocated
265 // stack slots.
266 if (willLowerDirectly(Incoming))
267 return;
268
269 SDValue OldLocation = Builder.StatepointLowering.getLocation(Incoming);
270 if (OldLocation.getNode())
271 // Duplicates in input
272 return;
273
274 const int LookUpDepth = 6;
275 Optional<int> Index =
276 findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth);
277 if (!Index.hasValue())
278 return;
279
280 const auto &StatepointSlots = Builder.FuncInfo.StatepointStackSlots;
281
282 auto SlotIt = find(StatepointSlots, *Index);
283 assert(SlotIt != StatepointSlots.end() &&((SlotIt != StatepointSlots.end() && "Value spilled to the unknown stack slot"
) ? static_cast<void> (0) : __assert_fail ("SlotIt != StatepointSlots.end() && \"Value spilled to the unknown stack slot\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 284, __PRETTY_FUNCTION__))
284 "Value spilled to the unknown stack slot")((SlotIt != StatepointSlots.end() && "Value spilled to the unknown stack slot"
) ? static_cast<void> (0) : __assert_fail ("SlotIt != StatepointSlots.end() && \"Value spilled to the unknown stack slot\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 284, __PRETTY_FUNCTION__))
;
285
286 // This is one of our dedicated lowering slots
287 const int Offset = std::distance(StatepointSlots.begin(), SlotIt);
288 if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
289 // stack slot already assigned to someone else, can't use it!
290 // TODO: currently we reserve space for gc arguments after doing
291 // normal allocation for deopt arguments. We should reserve for
292 // _all_ deopt and gc arguments, then start allocating. This
293 // will prevent some moves being inserted when vm state changes,
294 // but gc state doesn't between two calls.
295 return;
296 }
297 // Reserve this stack slot
298 Builder.StatepointLowering.reserveStackSlot(Offset);
299
300 // Cache this slot so we find it when going through the normal
301 // assignment loop.
302 SDValue Loc =
303 Builder.DAG.getTargetFrameIndex(*Index, Builder.getFrameIndexTy());
304 Builder.StatepointLowering.setLocation(Incoming, Loc);
305}
306
307/// Extract call from statepoint, lower it and return pointer to the
308/// call node. Also update NodeMap so that getValue(statepoint) will
309/// reference lowered call result
310static std::pair<SDValue, SDNode *> lowerCallFromStatepointLoweringInfo(
311 SelectionDAGBuilder::StatepointLoweringInfo &SI,
312 SelectionDAGBuilder &Builder, SmallVectorImpl<SDValue> &PendingExports) {
313 SDValue ReturnValue, CallEndVal;
314 std::tie(ReturnValue, CallEndVal) =
315 Builder.lowerInvokable(SI.CLI, SI.EHPadBB);
316 SDNode *CallEnd = CallEndVal.getNode();
317
318 // Get a call instruction from the call sequence chain. Tail calls are not
319 // allowed. The following code is essentially reverse engineering X86's
320 // LowerCallTo.
321 //
322 // We are expecting DAG to have the following form:
323 //
324 // ch = eh_label (only in case of invoke statepoint)
325 // ch, glue = callseq_start ch
326 // ch, glue = X86::Call ch, glue
327 // ch, glue = callseq_end ch, glue
328 // get_return_value ch, glue
329 //
330 // get_return_value can either be a sequence of CopyFromReg instructions
331 // to grab the return value from the return register(s), or it can be a LOAD
332 // to load a value returned by reference via a stack slot.
333
334 bool HasDef = !SI.CLI.RetTy->isVoidTy();
335 if (HasDef) {
336 if (CallEnd->getOpcode() == ISD::LOAD)
337 CallEnd = CallEnd->getOperand(0).getNode();
338 else
339 while (CallEnd->getOpcode() == ISD::CopyFromReg)
340 CallEnd = CallEnd->getOperand(0).getNode();
341 }
342
343 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!")((CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!"
) ? static_cast<void> (0) : __assert_fail ("CallEnd->getOpcode() == ISD::CALLSEQ_END && \"expected!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 343, __PRETTY_FUNCTION__))
;
344 return std::make_pair(ReturnValue, CallEnd->getOperand(0).getNode());
345}
346
347static MachineMemOperand* getMachineMemOperand(MachineFunction &MF,
348 FrameIndexSDNode &FI) {
349 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FI.getIndex());
350 auto MMOFlags = MachineMemOperand::MOStore |
351 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
352 auto &MFI = MF.getFrameInfo();
353 return MF.getMachineMemOperand(PtrInfo, MMOFlags,
354 MFI.getObjectSize(FI.getIndex()),
355 MFI.getObjectAlign(FI.getIndex()));
356}
357
358/// Spill a value incoming to the statepoint. It might be either part of
359/// vmstate
360/// or gcstate. In both cases unconditionally spill it on the stack unless it
361/// is a null constant. Return pair with first element being frame index
362/// containing saved value and second element with outgoing chain from the
363/// emitted store
364static std::tuple<SDValue, SDValue, MachineMemOperand*>
365spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
366 SelectionDAGBuilder &Builder) {
367 SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
368 MachineMemOperand* MMO = nullptr;
369
370 // Emit new store if we didn't do it for this ptr before
371 if (!Loc.getNode()) {
372 Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
373 Builder);
374 int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
375 // We use TargetFrameIndex so that isel will not select it into LEA
376 Loc = Builder.DAG.getTargetFrameIndex(Index, Builder.getFrameIndexTy());
377
378 // Right now we always allocate spill slots that are of the same
379 // size as the value we're about to spill (the size of spillee can
380 // vary since we spill vectors of pointers too). At some point we
381 // can consider allowing spills of smaller values to larger slots
382 // (i.e. change the '==' in the assert below to a '>=').
383 MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
384 assert((MFI.getObjectSize(Index) * 8) ==(((MFI.getObjectSize(Index) * 8) == (int64_t)Incoming.getValueSizeInBits
() && "Bad spill: stack slot does not match!") ? static_cast
<void> (0) : __assert_fail ("(MFI.getObjectSize(Index) * 8) == (int64_t)Incoming.getValueSizeInBits() && \"Bad spill: stack slot does not match!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 386, __PRETTY_FUNCTION__))
385 (int64_t)Incoming.getValueSizeInBits() &&(((MFI.getObjectSize(Index) * 8) == (int64_t)Incoming.getValueSizeInBits
() && "Bad spill: stack slot does not match!") ? static_cast
<void> (0) : __assert_fail ("(MFI.getObjectSize(Index) * 8) == (int64_t)Incoming.getValueSizeInBits() && \"Bad spill: stack slot does not match!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 386, __PRETTY_FUNCTION__))
386 "Bad spill: stack slot does not match!")(((MFI.getObjectSize(Index) * 8) == (int64_t)Incoming.getValueSizeInBits
() && "Bad spill: stack slot does not match!") ? static_cast
<void> (0) : __assert_fail ("(MFI.getObjectSize(Index) * 8) == (int64_t)Incoming.getValueSizeInBits() && \"Bad spill: stack slot does not match!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 386, __PRETTY_FUNCTION__))
;
387
388 // Note: Using the alignment of the spill slot (rather than the abi or
389 // preferred alignment) is required for correctness when dealing with spill
390 // slots with preferred alignments larger than frame alignment..
391 auto &MF = Builder.DAG.getMachineFunction();
392 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, Index);
393 auto *StoreMMO = MF.getMachineMemOperand(
394 PtrInfo, MachineMemOperand::MOStore, MFI.getObjectSize(Index),
395 MFI.getObjectAlign(Index));
396 Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
397 StoreMMO);
398
399 MMO = getMachineMemOperand(MF, *cast<FrameIndexSDNode>(Loc));
400
401 Builder.StatepointLowering.setLocation(Incoming, Loc);
402 }
403
404 assert(Loc.getNode())((Loc.getNode()) ? static_cast<void> (0) : __assert_fail
("Loc.getNode()", "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 404, __PRETTY_FUNCTION__))
;
405 return std::make_tuple(Loc, Chain, MMO);
406}
407
408/// Lower a single value incoming to a statepoint node. This value can be
409/// either a deopt value or a gc value, the handling is the same. We special
410/// case constants and allocas, then fall back to spilling if required.
411static void
412lowerIncomingStatepointValue(SDValue Incoming, bool RequireSpillSlot,
413 SmallVectorImpl<SDValue> &Ops,
414 SmallVectorImpl<MachineMemOperand *> &MemRefs,
415 SelectionDAGBuilder &Builder) {
416
417 if (willLowerDirectly(Incoming)) {
24
Taking true branch
418 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
25
Calling 'dyn_cast<llvm::FrameIndexSDNode, llvm::SDValue>'
40
Returning from 'dyn_cast<llvm::FrameIndexSDNode, llvm::SDValue>'
41
Assuming 'FI' is null
42
Taking false branch
419 // This handles allocas as arguments to the statepoint (this is only
420 // really meaningful for a deopt value. For GC, we'd be trying to
421 // relocate the address of the alloca itself?)
422 assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&((Incoming.getValueType() == Builder.getFrameIndexTy() &&
"Incoming value is a frame index!") ? static_cast<void>
(0) : __assert_fail ("Incoming.getValueType() == Builder.getFrameIndexTy() && \"Incoming value is a frame index!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 423, __PRETTY_FUNCTION__))
423 "Incoming value is a frame index!")((Incoming.getValueType() == Builder.getFrameIndexTy() &&
"Incoming value is a frame index!") ? static_cast<void>
(0) : __assert_fail ("Incoming.getValueType() == Builder.getFrameIndexTy() && \"Incoming value is a frame index!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 423, __PRETTY_FUNCTION__))
;
424 Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
425 Builder.getFrameIndexTy()));
426
427 auto &MF = Builder.DAG.getMachineFunction();
428 auto *MMO = getMachineMemOperand(MF, *FI);
429 MemRefs.push_back(MMO);
430 return;
431 }
432
433 assert(Incoming.getValueType().getSizeInBits() <= 64)((Incoming.getValueType().getSizeInBits() <= 64) ? static_cast
<void> (0) : __assert_fail ("Incoming.getValueType().getSizeInBits() <= 64"
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 433, __PRETTY_FUNCTION__))
;
43
Calling 'SDValue::getValueType'
434
435 if (Incoming.isUndef()) {
436 // Put an easily recognized constant that's unlikely to be a valid
437 // value so that uses of undef by the consumer of the stackmap is
438 // easily recognized. This is legal since the compiler is always
439 // allowed to chose an arbitrary value for undef.
440 pushStackMapConstant(Ops, Builder, 0xFEFEFEFE);
441 return;
442 }
443
444 // If the original value was a constant, make sure it gets recorded as
445 // such in the stackmap. This is required so that the consumer can
446 // parse any internal format to the deopt state. It also handles null
447 // pointers and other constant pointers in GC states.
448 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
449 pushStackMapConstant(Ops, Builder, C->getSExtValue());
450 return;
451 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Incoming)) {
452 pushStackMapConstant(Ops, Builder,
453 C->getValueAPF().bitcastToAPInt().getZExtValue());
454 return;
455 }
456
457 llvm_unreachable("unhandled direct lowering case")::llvm::llvm_unreachable_internal("unhandled direct lowering case"
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 457)
;
458 }
459
460
461
462 if (!RequireSpillSlot) {
463 // If this value is live in (not live-on-return, or live-through), we can
464 // treat it the same way patchpoint treats it's "live in" values. We'll
465 // end up folding some of these into stack references, but they'll be
466 // handled by the register allocator. Note that we do not have the notion
467 // of a late use so these values might be placed in registers which are
468 // clobbered by the call. This is fine for live-in. For live-through
469 // fix-up pass should be executed to force spilling of such registers.
470 Ops.push_back(Incoming);
471 } else {
472 // Otherwise, locate a spill slot and explicitly spill it so it can be
473 // found by the runtime later. Note: We know all of these spills are
474 // independent, but don't bother to exploit that chain wise. DAGCombine
475 // will happily do so as needed, so doing it here would be a small compile
476 // time win at most.
477 SDValue Chain = Builder.getRoot();
478 auto Res = spillIncomingStatepointValue(Incoming, Chain, Builder);
479 Ops.push_back(std::get<0>(Res));
480 if (auto *MMO = std::get<2>(Res))
481 MemRefs.push_back(MMO);
482 Chain = std::get<1>(Res);;
483 Builder.DAG.setRoot(Chain);
484 }
485
486}
487
488/// Lower deopt state and gc pointer arguments of the statepoint. The actual
489/// lowering is described in lowerIncomingStatepointValue. This function is
490/// responsible for lowering everything in the right position and playing some
491/// tricks to avoid redundant stack manipulation where possible. On
492/// completion, 'Ops' will contain ready to use operands for machine code
493/// statepoint. The chain nodes will have already been created and the DAG root
494/// will be set to the last value spilled (if any were).
495static void
496lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
497 SmallVectorImpl<MachineMemOperand *> &MemRefs,
498 SmallVectorImpl<SDValue> &GCPtrs,
499 DenseMap<SDValue, int> &LowerAsVReg,
500 SelectionDAGBuilder::StatepointLoweringInfo &SI,
501 SelectionDAGBuilder &Builder) {
502 // Lower the deopt and gc arguments for this statepoint. Layout will be:
503 // deopt argument length, deopt arguments.., gc arguments...
504#ifndef NDEBUG
505 if (auto *GFI = Builder.GFI) {
1
Assuming 'GFI' is null
2
Taking false branch
506 // Check that each of the gc pointer and bases we've gotten out of the
507 // safepoint is something the strategy thinks might be a pointer (or vector
508 // of pointers) into the GC heap. This is basically just here to help catch
509 // errors during statepoint insertion. TODO: This should actually be in the
510 // Verifier, but we can't get to the GCStrategy from there (yet).
511 GCStrategy &S = GFI->getStrategy();
512 for (const Value *V : SI.Bases) {
513 auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
514 if (Opt.hasValue()) {
515 assert(Opt.getValue() &&((Opt.getValue() && "non gc managed base pointer found in statepoint"
) ? static_cast<void> (0) : __assert_fail ("Opt.getValue() && \"non gc managed base pointer found in statepoint\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 516, __PRETTY_FUNCTION__))
516 "non gc managed base pointer found in statepoint")((Opt.getValue() && "non gc managed base pointer found in statepoint"
) ? static_cast<void> (0) : __assert_fail ("Opt.getValue() && \"non gc managed base pointer found in statepoint\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 516, __PRETTY_FUNCTION__))
;
517 }
518 }
519 for (const Value *V : SI.Ptrs) {
520 auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
521 if (Opt.hasValue()) {
522 assert(Opt.getValue() &&((Opt.getValue() && "non gc managed derived pointer found in statepoint"
) ? static_cast<void> (0) : __assert_fail ("Opt.getValue() && \"non gc managed derived pointer found in statepoint\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 523, __PRETTY_FUNCTION__))
523 "non gc managed derived pointer found in statepoint")((Opt.getValue() && "non gc managed derived pointer found in statepoint"
) ? static_cast<void> (0) : __assert_fail ("Opt.getValue() && \"non gc managed derived pointer found in statepoint\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 523, __PRETTY_FUNCTION__))
;
524 }
525 }
526 assert(SI.Bases.size() == SI.Ptrs.size() && "Pointer without base!")((SI.Bases.size() == SI.Ptrs.size() && "Pointer without base!"
) ? static_cast<void> (0) : __assert_fail ("SI.Bases.size() == SI.Ptrs.size() && \"Pointer without base!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 526, __PRETTY_FUNCTION__))
;
527 } else {
528 assert(SI.Bases.empty() && "No gc specified, so cannot relocate pointers!")((SI.Bases.empty() && "No gc specified, so cannot relocate pointers!"
) ? static_cast<void> (0) : __assert_fail ("SI.Bases.empty() && \"No gc specified, so cannot relocate pointers!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 528, __PRETTY_FUNCTION__))
;
3
'?' condition is true
529 assert(SI.Ptrs.empty() && "No gc specified, so cannot relocate pointers!")((SI.Ptrs.empty() && "No gc specified, so cannot relocate pointers!"
) ? static_cast<void> (0) : __assert_fail ("SI.Ptrs.empty() && \"No gc specified, so cannot relocate pointers!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 529, __PRETTY_FUNCTION__))
;
4
'?' condition is true
530 }
531#endif
532
533 // Figure out what lowering strategy we're going to use for each part
534 // Note: Is is conservatively correct to lower both "live-in" and "live-out"
535 // as "live-through". A "live-through" variable is one which is "live-in",
536 // "live-out", and live throughout the lifetime of the call (i.e. we can find
537 // it from any PC within the transitive callee of the statepoint). In
538 // particular, if the callee spills callee preserved registers we may not
539 // be able to find a value placed in that register during the call. This is
540 // fine for live-out, but not for live-through. If we were willing to make
541 // assumptions about the code generator producing the callee, we could
542 // potentially allow live-through values in callee saved registers.
543 const bool LiveInDeopt =
544 SI.StatepointFlags & (uint64_t)StatepointFlags::DeoptLiveIn;
545
546 // Decide which deriver pointers will go on VRegs
547 unsigned MaxVRegPtrs = MaxRegistersForGCPointers.getValue();
548
549 LLVM_DEBUG(dbgs() << "Deciding how to lower GC Pointers:\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("statepoint-lowering")) { dbgs() << "Deciding how to lower GC Pointers:\n"
; } } while (false)
;
5
Assuming 'DebugFlag' is false
6
Loop condition is false. Exiting loop
550
551 // List of unique lowered GC Pointer values.
552 SmallSetVector<SDValue, 16> LoweredGCPtrs;
553 // Map lowered GC Pointer value to the index in above vector
554 DenseMap<SDValue, unsigned> GCPtrIndexMap;
555
556 unsigned CurNumVRegs = 0;
557
558 auto processGCPtr = [&](const Value *V) {
559 SDValue PtrSD = Builder.getValue(V);
560 if (!LoweredGCPtrs.insert(PtrSD))
561 return; // skip duplicates
562 GCPtrIndexMap[PtrSD] = LoweredGCPtrs.size() - 1;
563
564 assert(!LowerAsVReg.count(PtrSD) && "must not have been seen")((!LowerAsVReg.count(PtrSD) && "must not have been seen"
) ? static_cast<void> (0) : __assert_fail ("!LowerAsVReg.count(PtrSD) && \"must not have been seen\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 564, __PRETTY_FUNCTION__))
;
565 if (LowerAsVReg.size() == MaxVRegPtrs)
566 return;
567 if (willLowerDirectly(PtrSD) || V->getType()->isVectorTy()) {
568 LLVM_DEBUG(dbgs() << "direct/spill "; PtrSD.dump(&Builder.DAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("statepoint-lowering")) { dbgs() << "direct/spill "; PtrSD
.dump(&Builder.DAG); } } while (false)
;
569 return;
570 }
571 LLVM_DEBUG(dbgs() << "vreg "; PtrSD.dump(&Builder.DAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("statepoint-lowering")) { dbgs() << "vreg "; PtrSD.dump
(&Builder.DAG); } } while (false)
;
572 LowerAsVReg[PtrSD] = CurNumVRegs++;
573 };
574
575 // Process derived pointers first to give them more chance to go on VReg.
576 for (const Value *V : SI.Ptrs)
7
Assuming '__begin1' is equal to '__end1'
577 processGCPtr(V);
578 for (const Value *V : SI.Bases)
8
Assuming '__begin1' is equal to '__end1'
579 processGCPtr(V);
580
581 LLVM_DEBUG(dbgs() << LowerAsVReg.size() << " pointers will go in vregs\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("statepoint-lowering")) { dbgs() << LowerAsVReg.size()
<< " pointers will go in vregs\n"; } } while (false)
;
9
Assuming 'DebugFlag' is false
10
Loop condition is false. Exiting loop
582
583 auto isGCValue = [&](const Value *V) {
584 auto *Ty = V->getType();
585 if (!Ty->isPtrOrPtrVectorTy())
586 return false;
587 if (auto *GFI = Builder.GFI)
588 if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
589 return *IsManaged;
590 return true; // conservative
591 };
592
593 auto requireSpillSlot = [&](const Value *V) {
594 if (isGCValue(V))
595 return !LowerAsVReg.count(Builder.getValue(V));
596 return !(LiveInDeopt || UseRegistersForDeoptValues);
597 };
598
599 // Before we actually start lowering (and allocating spill slots for values),
600 // reserve any stack slots which we judge to be profitable to reuse for a
601 // particular value. This is purely an optimization over the code below and
602 // doesn't change semantics at all. It is important for performance that we
603 // reserve slots for both deopt and gc values before lowering either.
604 for (const Value *V : SI.DeoptState) {
11
Assuming '__begin1' is equal to '__end1'
605 if (requireSpillSlot(V))
606 reservePreviousStackSlotForValue(V, Builder);
607 }
608
609 for (const Value *V : SI.Ptrs) {
12
Assuming '__begin1' is equal to '__end1'
610 SDValue SDV = Builder.getValue(V);
611 if (!LowerAsVReg.count(SDV))
612 reservePreviousStackSlotForValue(V, Builder);
613 }
614
615 for (const Value *V : SI.Bases) {
13
Assuming '__begin1' is equal to '__end1'
616 SDValue SDV = Builder.getValue(V);
617 if (!LowerAsVReg.count(SDV))
618 reservePreviousStackSlotForValue(V, Builder);
619 }
620
621 // First, prefix the list with the number of unique values to be
622 // lowered. Note that this is the number of *Values* not the
623 // number of SDValues required to lower them.
624 const int NumVMSArgs = SI.DeoptState.size();
625 pushStackMapConstant(Ops, Builder, NumVMSArgs);
626
627 // The vm state arguments are lowered in an opaque manner. We do not know
628 // what type of values are contained within.
629 LLVM_DEBUG(dbgs() << "Lowering deopt state\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("statepoint-lowering")) { dbgs() << "Lowering deopt state\n"
; } } while (false)
;
14
Assuming 'DebugFlag' is false
15
Loop condition is false. Exiting loop
630 for (const Value *V : SI.DeoptState) {
16
Assuming '__begin1' is not equal to '__end1'
631 SDValue Incoming;
632 // If this is a function argument at a static frame index, generate it as
633 // the frame index.
634 if (const Argument *Arg
17.1
'Arg' is null
17.1
'Arg' is null
17.1
'Arg' is null
= dyn_cast<Argument>(V)) {
17
Assuming 'V' is not a 'Argument'
18
Taking false branch
635 int FI = Builder.FuncInfo.getArgumentFrameIndex(Arg);
636 if (FI != INT_MAX2147483647)
637 Incoming = Builder.DAG.getFrameIndex(FI, Builder.getFrameIndexTy());
638 }
639 if (!Incoming.getNode())
19
Taking true branch
640 Incoming = Builder.getValue(V);
641 LLVM_DEBUG(dbgs() << "Value " << *Vdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("statepoint-lowering")) { dbgs() << "Value " << *
V << " requireSpillSlot = " << requireSpillSlot(V
) << "\n"; } } while (false)
20
Assuming 'DebugFlag' is false
21
Loop condition is false. Exiting loop
642 << " requireSpillSlot = " << requireSpillSlot(V) << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("statepoint-lowering")) { dbgs() << "Value " << *
V << " requireSpillSlot = " << requireSpillSlot(V
) << "\n"; } } while (false)
;
643 lowerIncomingStatepointValue(Incoming, requireSpillSlot(V), Ops, MemRefs,
22
Value assigned to 'Incoming.Node'
23
Calling 'lowerIncomingStatepointValue'
644 Builder);
645 }
646
647 // Finally, go ahead and lower all the gc arguments.
648 pushStackMapConstant(Ops, Builder, LoweredGCPtrs.size());
649 for (SDValue SDV : LoweredGCPtrs)
650 lowerIncomingStatepointValue(SDV, !LowerAsVReg.count(SDV), Ops, MemRefs,
651 Builder);
652
653 // Copy to out vector. LoweredGCPtrs will be empty after this point.
654 GCPtrs = LoweredGCPtrs.takeVector();
655
656 // If there are any explicit spill slots passed to the statepoint, record
657 // them, but otherwise do not do anything special. These are user provided
658 // allocas and give control over placement to the consumer. In this case,
659 // it is the contents of the slot which may get updated, not the pointer to
660 // the alloca
661 SmallVector<SDValue, 4> Allocas;
662 for (Value *V : SI.GCArgs) {
663 SDValue Incoming = Builder.getValue(V);
664 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
665 // This handles allocas as arguments to the statepoint
666 assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&((Incoming.getValueType() == Builder.getFrameIndexTy() &&
"Incoming value is a frame index!") ? static_cast<void>
(0) : __assert_fail ("Incoming.getValueType() == Builder.getFrameIndexTy() && \"Incoming value is a frame index!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 667, __PRETTY_FUNCTION__))
667 "Incoming value is a frame index!")((Incoming.getValueType() == Builder.getFrameIndexTy() &&
"Incoming value is a frame index!") ? static_cast<void>
(0) : __assert_fail ("Incoming.getValueType() == Builder.getFrameIndexTy() && \"Incoming value is a frame index!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 667, __PRETTY_FUNCTION__))
;
668 Allocas.push_back(Builder.DAG.getTargetFrameIndex(
669 FI->getIndex(), Builder.getFrameIndexTy()));
670
671 auto &MF = Builder.DAG.getMachineFunction();
672 auto *MMO = getMachineMemOperand(MF, *FI);
673 MemRefs.push_back(MMO);
674 }
675 }
676 pushStackMapConstant(Ops, Builder, Allocas.size());
677 Ops.append(Allocas.begin(), Allocas.end());
678
679 // Now construct GC base/derived map;
680 pushStackMapConstant(Ops, Builder, SI.Ptrs.size());
681 SDLoc L = Builder.getCurSDLoc();
682 for (unsigned i = 0; i < SI.Ptrs.size(); ++i) {
683 SDValue Base = Builder.getValue(SI.Bases[i]);
684 assert(GCPtrIndexMap.count(Base) && "base not found in index map")((GCPtrIndexMap.count(Base) && "base not found in index map"
) ? static_cast<void> (0) : __assert_fail ("GCPtrIndexMap.count(Base) && \"base not found in index map\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 684, __PRETTY_FUNCTION__))
;
685 Ops.push_back(
686 Builder.DAG.getTargetConstant(GCPtrIndexMap[Base], L, MVT::i64));
687 SDValue Derived = Builder.getValue(SI.Ptrs[i]);
688 assert(GCPtrIndexMap.count(Derived) && "derived not found in index map")((GCPtrIndexMap.count(Derived) && "derived not found in index map"
) ? static_cast<void> (0) : __assert_fail ("GCPtrIndexMap.count(Derived) && \"derived not found in index map\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 688, __PRETTY_FUNCTION__))
;
689 Ops.push_back(
690 Builder.DAG.getTargetConstant(GCPtrIndexMap[Derived], L, MVT::i64));
691 }
692}
693
694SDValue SelectionDAGBuilder::LowerAsSTATEPOINT(
695 SelectionDAGBuilder::StatepointLoweringInfo &SI) {
696 // The basic scheme here is that information about both the original call and
697 // the safepoint is encoded in the CallInst. We create a temporary call and
698 // lower it, then reverse engineer the calling sequence.
699
700 NumOfStatepoints++;
701 // Clear state
702 StatepointLowering.startNewStatepoint(*this);
703 assert(SI.Bases.size() == SI.Ptrs.size() &&((SI.Bases.size() == SI.Ptrs.size() && SI.Ptrs.size()
<= SI.GCRelocates.size()) ? static_cast<void> (0) :
__assert_fail ("SI.Bases.size() == SI.Ptrs.size() && SI.Ptrs.size() <= SI.GCRelocates.size()"
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 704, __PRETTY_FUNCTION__))
704 SI.Ptrs.size() <= SI.GCRelocates.size())((SI.Bases.size() == SI.Ptrs.size() && SI.Ptrs.size()
<= SI.GCRelocates.size()) ? static_cast<void> (0) :
__assert_fail ("SI.Bases.size() == SI.Ptrs.size() && SI.Ptrs.size() <= SI.GCRelocates.size()"
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 704, __PRETTY_FUNCTION__))
;
705
706 LLVM_DEBUG(dbgs() << "Lowering statepoint " << *SI.StatepointInstr << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("statepoint-lowering")) { dbgs() << "Lowering statepoint "
<< *SI.StatepointInstr << "\n"; } } while (false
)
;
707#ifndef NDEBUG
708 for (auto *Reloc : SI.GCRelocates)
709 if (Reloc->getParent() == SI.StatepointInstr->getParent())
710 StatepointLowering.scheduleRelocCall(*Reloc);
711#endif
712
713 // Lower statepoint vmstate and gcstate arguments
714
715 // All lowered meta args.
716 SmallVector<SDValue, 10> LoweredMetaArgs;
717 // Lowered GC pointers (subset of above).
718 SmallVector<SDValue, 16> LoweredGCArgs;
719 SmallVector<MachineMemOperand*, 16> MemRefs;
720 // Maps derived pointer SDValue to statepoint result of relocated pointer.
721 DenseMap<SDValue, int> LowerAsVReg;
722 lowerStatepointMetaArgs(LoweredMetaArgs, MemRefs, LoweredGCArgs, LowerAsVReg,
723 SI, *this);
724
725 // Now that we've emitted the spills, we need to update the root so that the
726 // call sequence is ordered correctly.
727 SI.CLI.setChain(getRoot());
728
729 // Get call node, we will replace it later with statepoint
730 SDValue ReturnVal;
731 SDNode *CallNode;
732 std::tie(ReturnVal, CallNode) =
733 lowerCallFromStatepointLoweringInfo(SI, *this, PendingExports);
734
735 // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
736 // nodes with all the appropriate arguments and return values.
737
738 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
739 SDValue Chain = CallNode->getOperand(0);
740
741 SDValue Glue;
742 bool CallHasIncomingGlue = CallNode->getGluedNode();
743 if (CallHasIncomingGlue) {
744 // Glue is always last operand
745 Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
746 }
747
748 // Build the GC_TRANSITION_START node if necessary.
749 //
750 // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
751 // order in which they appear in the call to the statepoint intrinsic. If
752 // any of the operands is a pointer-typed, that operand is immediately
753 // followed by a SRCVALUE for the pointer that may be used during lowering
754 // (e.g. to form MachinePointerInfo values for loads/stores).
755 const bool IsGCTransition =
756 (SI.StatepointFlags & (uint64_t)StatepointFlags::GCTransition) ==
757 (uint64_t)StatepointFlags::GCTransition;
758 if (IsGCTransition) {
759 SmallVector<SDValue, 8> TSOps;
760
761 // Add chain
762 TSOps.push_back(Chain);
763
764 // Add GC transition arguments
765 for (const Value *V : SI.GCTransitionArgs) {
766 TSOps.push_back(getValue(V));
767 if (V->getType()->isPointerTy())
768 TSOps.push_back(DAG.getSrcValue(V));
769 }
770
771 // Add glue if necessary
772 if (CallHasIncomingGlue)
773 TSOps.push_back(Glue);
774
775 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
776
777 SDValue GCTransitionStart =
778 DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
779
780 Chain = GCTransitionStart.getValue(0);
781 Glue = GCTransitionStart.getValue(1);
782 }
783
784 // TODO: Currently, all of these operands are being marked as read/write in
785 // PrologEpilougeInserter.cpp, we should special case the VMState arguments
786 // and flags to be read-only.
787 SmallVector<SDValue, 40> Ops;
788
789 // Add the <id> and <numBytes> constants.
790 Ops.push_back(DAG.getTargetConstant(SI.ID, getCurSDLoc(), MVT::i64));
791 Ops.push_back(
792 DAG.getTargetConstant(SI.NumPatchBytes, getCurSDLoc(), MVT::i32));
793
794 // Calculate and push starting position of vmstate arguments
795 // Get number of arguments incoming directly into call node
796 unsigned NumCallRegArgs =
797 CallNode->getNumOperands() - (CallHasIncomingGlue ? 4 : 3);
798 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
799
800 // Add call target
801 SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
802 Ops.push_back(CallTarget);
803
804 // Add call arguments
805 // Get position of register mask in the call
806 SDNode::op_iterator RegMaskIt;
807 if (CallHasIncomingGlue)
808 RegMaskIt = CallNode->op_end() - 2;
809 else
810 RegMaskIt = CallNode->op_end() - 1;
811 Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
812
813 // Add a constant argument for the calling convention
814 pushStackMapConstant(Ops, *this, SI.CLI.CallConv);
815
816 // Add a constant argument for the flags
817 uint64_t Flags = SI.StatepointFlags;
818 assert(((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) &&((((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) &&
"Unknown flag used") ? static_cast<void> (0) : __assert_fail
("((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) && \"Unknown flag used\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 819, __PRETTY_FUNCTION__))
819 "Unknown flag used")((((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) &&
"Unknown flag used") ? static_cast<void> (0) : __assert_fail
("((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) && \"Unknown flag used\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 819, __PRETTY_FUNCTION__))
;
820 pushStackMapConstant(Ops, *this, Flags);
821
822 // Insert all vmstate and gcstate arguments
823 Ops.insert(Ops.end(), LoweredMetaArgs.begin(), LoweredMetaArgs.end());
824
825 // Add register mask from call node
826 Ops.push_back(*RegMaskIt);
827
828 // Add chain
829 Ops.push_back(Chain);
830
831 // Same for the glue, but we add it only if original call had it
832 if (Glue.getNode())
833 Ops.push_back(Glue);
834
835 // Compute return values. Provide a glue output since we consume one as
836 // input. This allows someone else to chain off us as needed.
837 SmallVector<EVT, 8> NodeTys;
838 for (auto SD : LoweredGCArgs) {
839 if (!LowerAsVReg.count(SD))
840 continue;
841 NodeTys.push_back(SD.getValueType());
842 }
843 LLVM_DEBUG(dbgs() << "Statepoint has " << NodeTys.size() << " results\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("statepoint-lowering")) { dbgs() << "Statepoint has " <<
NodeTys.size() << " results\n"; } } while (false)
;
844 assert(NodeTys.size() == LowerAsVReg.size() && "Inconsistent GC Ptr lowering")((NodeTys.size() == LowerAsVReg.size() && "Inconsistent GC Ptr lowering"
) ? static_cast<void> (0) : __assert_fail ("NodeTys.size() == LowerAsVReg.size() && \"Inconsistent GC Ptr lowering\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 844, __PRETTY_FUNCTION__))
;
845 NodeTys.push_back(MVT::Other);
846 NodeTys.push_back(MVT::Glue);
847
848 unsigned NumResults = NodeTys.size();
849 MachineSDNode *StatepointMCNode =
850 DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
851 DAG.setNodeMemRefs(StatepointMCNode, MemRefs);
852
853 // For values lowered to tied-defs, create the virtual registers. Note that
854 // for simplicity, we *always* create a vreg even within a single block.
855 DenseMap<SDValue, Register> VirtRegs;
856 for (const auto *Relocate : SI.GCRelocates) {
857 Value *Derived = Relocate->getDerivedPtr();
858 SDValue SD = getValue(Derived);
859 if (!LowerAsVReg.count(SD))
860 continue;
861
862 // Handle multiple gc.relocates of the same input efficiently.
863 if (VirtRegs.count(SD))
864 continue;
865
866 SDValue Relocated = SDValue(StatepointMCNode, LowerAsVReg[SD]);
867
868 auto *RetTy = Relocate->getType();
869 Register Reg = FuncInfo.CreateRegs(RetTy);
870 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
871 DAG.getDataLayout(), Reg, RetTy, None);
872 SDValue Chain = DAG.getRoot();
873 RFV.getCopyToRegs(Relocated, DAG, getCurSDLoc(), Chain, nullptr);
874 PendingExports.push_back(Chain);
875
876 VirtRegs[SD] = Reg;
877 }
878
879 // Record for later use how each relocation was lowered. This is needed to
880 // allow later gc.relocates to mirror the lowering chosen.
881 const Instruction *StatepointInstr = SI.StatepointInstr;
882 auto &RelocationMap = FuncInfo.StatepointRelocationMaps[StatepointInstr];
883 for (const GCRelocateInst *Relocate : SI.GCRelocates) {
884 const Value *V = Relocate->getDerivedPtr();
885 SDValue SDV = getValue(V);
886 SDValue Loc = StatepointLowering.getLocation(SDV);
887
888 RecordType Record;
889 if (LowerAsVReg.count(SDV)) {
890 Record.type = RecordType::VReg;
891 assert(VirtRegs.count(SDV))((VirtRegs.count(SDV)) ? static_cast<void> (0) : __assert_fail
("VirtRegs.count(SDV)", "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 891, __PRETTY_FUNCTION__))
;
892 Record.payload.Reg = VirtRegs[SDV];
893 } else if (Loc.getNode()) {
894 Record.type = RecordType::Spill;
895 Record.payload.FI = cast<FrameIndexSDNode>(Loc)->getIndex();
896 } else {
897 Record.type = RecordType::NoRelocate;
898 // If we didn't relocate a value, we'll essentialy end up inserting an
899 // additional use of the original value when lowering the gc.relocate.
900 // We need to make sure the value is available at the new use, which
901 // might be in another block.
902 if (Relocate->getParent() != StatepointInstr->getParent())
903 ExportFromCurrentBlock(V);
904 }
905 RelocationMap[V] = Record;
906 }
907
908
909
910 SDNode *SinkNode = StatepointMCNode;
911
912 // Build the GC_TRANSITION_END node if necessary.
913 //
914 // See the comment above regarding GC_TRANSITION_START for the layout of
915 // the operands to the GC_TRANSITION_END node.
916 if (IsGCTransition) {
917 SmallVector<SDValue, 8> TEOps;
918
919 // Add chain
920 TEOps.push_back(SDValue(StatepointMCNode, NumResults - 2));
921
922 // Add GC transition arguments
923 for (const Value *V : SI.GCTransitionArgs) {
924 TEOps.push_back(getValue(V));
925 if (V->getType()->isPointerTy())
926 TEOps.push_back(DAG.getSrcValue(V));
927 }
928
929 // Add glue
930 TEOps.push_back(SDValue(StatepointMCNode, NumResults - 1));
931
932 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
933
934 SDValue GCTransitionStart =
935 DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
936
937 SinkNode = GCTransitionStart.getNode();
938 }
939
940 // Replace original call
941 // Call: ch,glue = CALL ...
942 // Statepoint: [gc relocates],ch,glue = STATEPOINT ...
943 unsigned NumSinkValues = SinkNode->getNumValues();
944 SDValue StatepointValues[2] = {SDValue(SinkNode, NumSinkValues - 2),
945 SDValue(SinkNode, NumSinkValues - 1)};
946 DAG.ReplaceAllUsesWith(CallNode, StatepointValues);
947 // Remove original call node
948 DAG.DeleteNode(CallNode);
949
950 // Since we always emit CopyToRegs (even for local relocates), we must
951 // update root, so that they are emitted before any local uses.
952 (void)getControlRoot();
953
954 // TODO: A better future implementation would be to emit a single variable
955 // argument, variable return value STATEPOINT node here and then hookup the
956 // return value of each gc.relocate to the respective output of the
957 // previously emitted STATEPOINT value. Unfortunately, this doesn't appear
958 // to actually be possible today.
959
960 return ReturnVal;
961}
962
963void
964SelectionDAGBuilder::LowerStatepoint(const GCStatepointInst &I,
965 const BasicBlock *EHPadBB /*= nullptr*/) {
966 assert(I.getCallingConv() != CallingConv::AnyReg &&((I.getCallingConv() != CallingConv::AnyReg && "anyregcc is not supported on statepoints!"
) ? static_cast<void> (0) : __assert_fail ("I.getCallingConv() != CallingConv::AnyReg && \"anyregcc is not supported on statepoints!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 967, __PRETTY_FUNCTION__))
967 "anyregcc is not supported on statepoints!")((I.getCallingConv() != CallingConv::AnyReg && "anyregcc is not supported on statepoints!"
) ? static_cast<void> (0) : __assert_fail ("I.getCallingConv() != CallingConv::AnyReg && \"anyregcc is not supported on statepoints!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 967, __PRETTY_FUNCTION__))
;
968
969#ifndef NDEBUG
970 // Check that the associated GCStrategy expects to encounter statepoints.
971 assert(GFI->getStrategy().useStatepoints() &&((GFI->getStrategy().useStatepoints() && "GCStrategy does not expect to encounter statepoints"
) ? static_cast<void> (0) : __assert_fail ("GFI->getStrategy().useStatepoints() && \"GCStrategy does not expect to encounter statepoints\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 972, __PRETTY_FUNCTION__))
972 "GCStrategy does not expect to encounter statepoints")((GFI->getStrategy().useStatepoints() && "GCStrategy does not expect to encounter statepoints"
) ? static_cast<void> (0) : __assert_fail ("GFI->getStrategy().useStatepoints() && \"GCStrategy does not expect to encounter statepoints\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 972, __PRETTY_FUNCTION__))
;
973#endif
974
975 SDValue ActualCallee;
976 SDValue Callee = getValue(I.getActualCalledOperand());
977
978 if (I.getNumPatchBytes() > 0) {
979 // If we've been asked to emit a nop sequence instead of a call instruction
980 // for this statepoint then don't lower the call target, but use a constant
981 // `undef` instead. Not lowering the call target lets statepoint clients
982 // get away without providing a physical address for the symbolic call
983 // target at link time.
984 ActualCallee = DAG.getUNDEF(Callee.getValueType());
985 } else {
986 ActualCallee = Callee;
987 }
988
989 StatepointLoweringInfo SI(DAG);
990 populateCallLoweringInfo(SI.CLI, &I, GCStatepointInst::CallArgsBeginPos,
991 I.getNumCallArgs(), ActualCallee,
992 I.getActualReturnType(), false /* IsPatchPoint */);
993
994 // There may be duplication in the gc.relocate list; such as two copies of
995 // each relocation on normal and exceptional path for an invoke. We only
996 // need to spill once and record one copy in the stackmap, but we need to
997 // reload once per gc.relocate. (Dedupping gc.relocates is trickier and best
998 // handled as a CSE problem elsewhere.)
999 // TODO: There a couple of major stackmap size optimizations we could do
1000 // here if we wished.
1001 // 1) If we've encountered a derived pair {B, D}, we don't need to actually
1002 // record {B,B} if it's seen later.
1003 // 2) Due to rematerialization, actual derived pointers are somewhat rare;
1004 // given that, we could change the format to record base pointer relocations
1005 // separately with half the space. This would require a format rev and a
1006 // fairly major rework of the STATEPOINT node though.
1007 SmallSet<SDValue, 8> Seen;
1008 for (const GCRelocateInst *Relocate : I.getGCRelocates()) {
1009 SI.GCRelocates.push_back(Relocate);
1010
1011 SDValue DerivedSD = getValue(Relocate->getDerivedPtr());
1012 if (Seen.insert(DerivedSD).second) {
1013 SI.Bases.push_back(Relocate->getBasePtr());
1014 SI.Ptrs.push_back(Relocate->getDerivedPtr());
1015 }
1016 }
1017
1018 SI.GCArgs = ArrayRef<const Use>(I.gc_args_begin(), I.gc_args_end());
1019 SI.StatepointInstr = &I;
1020 SI.ID = I.getID();
1021
1022 SI.DeoptState = ArrayRef<const Use>(I.deopt_begin(), I.deopt_end());
1023 SI.GCTransitionArgs = ArrayRef<const Use>(I.gc_transition_args_begin(),
1024 I.gc_transition_args_end());
1025
1026 SI.StatepointFlags = I.getFlags();
1027 SI.NumPatchBytes = I.getNumPatchBytes();
1028 SI.EHPadBB = EHPadBB;
1029
1030 SDValue ReturnValue = LowerAsSTATEPOINT(SI);
1031
1032 // Export the result value if needed
1033 const GCResultInst *GCResult = I.getGCResult();
1034 Type *RetTy = I.getActualReturnType();
1035
1036 if (RetTy->isVoidTy() || !GCResult) {
1037 // The return value is not needed, just generate a poison value.
1038 setValue(&I, DAG.getIntPtrConstant(-1, getCurSDLoc()));
1039 return;
1040 }
1041
1042 if (GCResult->getParent() == I.getParent()) {
1043 // Result value will be used in a same basic block. Don't export it or
1044 // perform any explicit register copies. The gc_result will simply grab
1045 // this value.
1046 setValue(&I, ReturnValue);
1047 return;
1048 }
1049
1050 // Result value will be used in a different basic block so we need to export
1051 // it now. Default exporting mechanism will not work here because statepoint
1052 // call has a different type than the actual call. It means that by default
1053 // llvm will create export register of the wrong type (always i32 in our
1054 // case). So instead we need to create export register with correct type
1055 // manually.
1056 // TODO: To eliminate this problem we can remove gc.result intrinsics
1057 // completely and make statepoint call to return a tuple.
1058 unsigned Reg = FuncInfo.CreateRegs(RetTy);
1059 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1060 DAG.getDataLayout(), Reg, RetTy,
1061 I.getCallingConv());
1062 SDValue Chain = DAG.getEntryNode();
1063
1064 RFV.getCopyToRegs(ReturnValue, DAG, getCurSDLoc(), Chain, nullptr);
1065 PendingExports.push_back(Chain);
1066 FuncInfo.ValueMap[&I] = Reg;
1067}
1068
1069void SelectionDAGBuilder::LowerCallSiteWithDeoptBundleImpl(
1070 const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB,
1071 bool VarArgDisallowed, bool ForceVoidReturnTy) {
1072 StatepointLoweringInfo SI(DAG);
1073 unsigned ArgBeginIndex = Call->arg_begin() - Call->op_begin();
1074 populateCallLoweringInfo(
1075 SI.CLI, Call, ArgBeginIndex, Call->getNumArgOperands(), Callee,
1076 ForceVoidReturnTy ? Type::getVoidTy(*DAG.getContext()) : Call->getType(),
1077 false);
1078 if (!VarArgDisallowed)
1079 SI.CLI.IsVarArg = Call->getFunctionType()->isVarArg();
1080
1081 auto DeoptBundle = *Call->getOperandBundle(LLVMContext::OB_deopt);
1082
1083 unsigned DefaultID = StatepointDirectives::DeoptBundleStatepointID;
1084
1085 auto SD = parseStatepointDirectivesFromAttrs(Call->getAttributes());
1086 SI.ID = SD.StatepointID.getValueOr(DefaultID);
1087 SI.NumPatchBytes = SD.NumPatchBytes.getValueOr(0);
1088
1089 SI.DeoptState =
1090 ArrayRef<const Use>(DeoptBundle.Inputs.begin(), DeoptBundle.Inputs.end());
1091 SI.StatepointFlags = static_cast<uint64_t>(StatepointFlags::None);
1092 SI.EHPadBB = EHPadBB;
1093
1094 // NB! The GC arguments are deliberately left empty.
1095
1096 if (SDValue ReturnVal = LowerAsSTATEPOINT(SI)) {
1097 ReturnVal = lowerRangeToAssertZExt(DAG, *Call, ReturnVal);
1098 setValue(Call, ReturnVal);
1099 }
1100}
1101
1102void SelectionDAGBuilder::LowerCallSiteWithDeoptBundle(
1103 const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB) {
1104 LowerCallSiteWithDeoptBundleImpl(Call, Callee, EHPadBB,
1105 /* VarArgDisallowed = */ false,
1106 /* ForceVoidReturnTy = */ false);
1107}
1108
1109void SelectionDAGBuilder::visitGCResult(const GCResultInst &CI) {
1110 // The result value of the gc_result is simply the result of the actual
1111 // call. We've already emitted this, so just grab the value.
1112 const GCStatepointInst *SI = CI.getStatepoint();
1113
1114 if (SI->getParent() == CI.getParent()) {
1115 setValue(&CI, getValue(SI));
1116 return;
1117 }
1118 // Statepoint is in different basic block so we should have stored call
1119 // result in a virtual register.
1120 // We can not use default getValue() functionality to copy value from this
1121 // register because statepoint and actual call return types can be
1122 // different, and getValue() will use CopyFromReg of the wrong type,
1123 // which is always i32 in our case.
1124 Type *RetTy = SI->getActualReturnType();
1125 SDValue CopyFromReg = getCopyFromRegs(SI, RetTy);
1126
1127 assert(CopyFromReg.getNode())((CopyFromReg.getNode()) ? static_cast<void> (0) : __assert_fail
("CopyFromReg.getNode()", "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 1127, __PRETTY_FUNCTION__))
;
1128 setValue(&CI, CopyFromReg);
1129}
1130
1131void SelectionDAGBuilder::visitGCRelocate(const GCRelocateInst &Relocate) {
1132#ifndef NDEBUG
1133 // Consistency check
1134 // We skip this check for relocates not in the same basic block as their
1135 // statepoint. It would be too expensive to preserve validation info through
1136 // different basic blocks.
1137 if (Relocate.getStatepoint()->getParent() == Relocate.getParent())
1138 StatepointLowering.relocCallVisited(Relocate);
1139
1140 auto *Ty = Relocate.getType()->getScalarType();
1141 if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
1142 assert(*IsManaged && "Non gc managed pointer relocated!")((*IsManaged && "Non gc managed pointer relocated!") ?
static_cast<void> (0) : __assert_fail ("*IsManaged && \"Non gc managed pointer relocated!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 1142, __PRETTY_FUNCTION__))
;
1143#endif
1144
1145 const Value *DerivedPtr = Relocate.getDerivedPtr();
1146 auto &RelocationMap =
1147 FuncInfo.StatepointRelocationMaps[Relocate.getStatepoint()];
1148 auto SlotIt = RelocationMap.find(DerivedPtr);
1149 assert(SlotIt != RelocationMap.end() && "Relocating not lowered gc value")((SlotIt != RelocationMap.end() && "Relocating not lowered gc value"
) ? static_cast<void> (0) : __assert_fail ("SlotIt != RelocationMap.end() && \"Relocating not lowered gc value\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 1149, __PRETTY_FUNCTION__))
;
1150 const RecordType &Record = SlotIt->second;
1151
1152 // If relocation was done via virtual register..
1153 if (Record.type == RecordType::VReg) {
1154 Register InReg = Record.payload.Reg;
1155 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1156 DAG.getDataLayout(), InReg, Relocate.getType(),
1157 None); // This is not an ABI copy.
1158 // We generate copy to/from regs even for local uses, hence we must
1159 // chain with current root to ensure proper ordering of copies w.r.t.
1160 // statepoint.
1161 SDValue Chain = DAG.getRoot();
1162 SDValue Relocation = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
1163 Chain, nullptr, nullptr);
1164 setValue(&Relocate, Relocation);
1165 return;
1166 }
1167
1168 SDValue SD = getValue(DerivedPtr);
1169
1170 if (SD.isUndef() && SD.getValueType().getSizeInBits() <= 64) {
1171 // Lowering relocate(undef) as arbitrary constant. Current constant value
1172 // is chosen such that it's unlikely to be a valid pointer.
1173 setValue(&Relocate, DAG.getTargetConstant(0xFEFEFEFE, SDLoc(SD), MVT::i64));
1174 return;
1175 }
1176
1177
1178 // We didn't need to spill these special cases (constants and allocas).
1179 // See the handling in spillIncomingValueForStatepoint for detail.
1180 if (Record.type == RecordType::NoRelocate) {
1181 setValue(&Relocate, SD);
1182 return;
1183 }
1184
1185 assert(Record.type == RecordType::Spill)((Record.type == RecordType::Spill) ? static_cast<void>
(0) : __assert_fail ("Record.type == RecordType::Spill", "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 1185, __PRETTY_FUNCTION__))
;
1186
1187 unsigned Index = Record.payload.FI;;
1188 SDValue SpillSlot = DAG.getTargetFrameIndex(Index, getFrameIndexTy());
1189
1190 // All the reloads are independent and are reading memory only modified by
1191 // statepoints (i.e. no other aliasing stores); informing SelectionDAG of
1192 // this this let's CSE kick in for free and allows reordering of instructions
1193 // if possible. The lowering for statepoint sets the root, so this is
1194 // ordering all reloads with the either a) the statepoint node itself, or b)
1195 // the entry of the current block for an invoke statepoint.
1196 const SDValue Chain = DAG.getRoot(); // != Builder.getRoot()
1197
1198 auto &MF = DAG.getMachineFunction();
1199 auto &MFI = MF.getFrameInfo();
1200 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, Index);
1201 auto *LoadMMO = MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad,
1202 MFI.getObjectSize(Index),
1203 MFI.getObjectAlign(Index));
1204
1205 auto LoadVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
1206 Relocate.getType());
1207
1208 SDValue SpillLoad = DAG.getLoad(LoadVT, getCurSDLoc(), Chain,
1209 SpillSlot, LoadMMO);
1210 PendingLoads.push_back(SpillLoad.getValue(1));
1211
1212 assert(SpillLoad.getNode())((SpillLoad.getNode()) ? static_cast<void> (0) : __assert_fail
("SpillLoad.getNode()", "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 1212, __PRETTY_FUNCTION__))
;
1213 setValue(&Relocate, SpillLoad);
1214}
1215
1216void SelectionDAGBuilder::LowerDeoptimizeCall(const CallInst *CI) {
1217 const auto &TLI = DAG.getTargetLoweringInfo();
1218 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(RTLIB::DEOPTIMIZE),
1219 TLI.getPointerTy(DAG.getDataLayout()));
1220
1221 // We don't lower calls to __llvm_deoptimize as varargs, but as a regular
1222 // call. We also do not lower the return value to any virtual register, and
1223 // change the immediately following return to a trap instruction.
1224 LowerCallSiteWithDeoptBundleImpl(CI, Callee, /* EHPadBB = */ nullptr,
1225 /* VarArgDisallowed = */ true,
1226 /* ForceVoidReturnTy = */ true);
1227}
1228
1229void SelectionDAGBuilder::LowerDeoptimizingReturn() {
1230 // We do not lower the return value from llvm.deoptimize to any virtual
1231 // register, and change the immediately following return to a trap
1232 // instruction.
1233 if (DAG.getTarget().Options.TrapUnreachable)
1234 DAG.setRoot(
1235 DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
1236}

/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/Support/Casting.h

1//===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- 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 defines the isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(),
10// and dyn_cast_or_null<X>() templates.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_SUPPORT_CASTING_H
15#define LLVM_SUPPORT_CASTING_H
16
17#include "llvm/Support/Compiler.h"
18#include "llvm/Support/type_traits.h"
19#include <cassert>
20#include <memory>
21#include <type_traits>
22
23namespace llvm {
24
25//===----------------------------------------------------------------------===//
26// isa<x> Support Templates
27//===----------------------------------------------------------------------===//
28
29// Define a template that can be specialized by smart pointers to reflect the
30// fact that they are automatically dereferenced, and are not involved with the
31// template selection process... the default implementation is a noop.
32//
33template<typename From> struct simplify_type {
34 using SimpleType = From; // The real type this represents...
35
36 // An accessor to get the real value...
37 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
38};
39
40template<typename From> struct simplify_type<const From> {
41 using NonConstSimpleType = typename simplify_type<From>::SimpleType;
42 using SimpleType =
43 typename add_const_past_pointer<NonConstSimpleType>::type;
44 using RetType =
45 typename add_lvalue_reference_if_not_pointer<SimpleType>::type;
46
47 static RetType getSimplifiedValue(const From& Val) {
48 return simplify_type<From>::getSimplifiedValue(const_cast<From&>(Val));
49 }
50};
51
52// The core of the implementation of isa<X> is here; To and From should be
53// the names of classes. This template can be specialized to customize the
54// implementation of isa<> without rewriting it from scratch.
55template <typename To, typename From, typename Enabler = void>
56struct isa_impl {
57 static inline bool doit(const From &Val) {
58 return To::classof(&Val);
59 }
60};
61
62/// Always allow upcasts, and perform no dynamic check for them.
63template <typename To, typename From>
64struct isa_impl<To, From, std::enable_if_t<std::is_base_of<To, From>::value>> {
65 static inline bool doit(const From &) { return true; }
66};
67
68template <typename To, typename From> struct isa_impl_cl {
69 static inline bool doit(const From &Val) {
70 return isa_impl<To, From>::doit(Val);
71 }
72};
73
74template <typename To, typename From> struct isa_impl_cl<To, const From> {
75 static inline bool doit(const From &Val) {
76 return isa_impl<To, From>::doit(Val);
77 }
78};
79
80template <typename To, typename From>
81struct isa_impl_cl<To, const std::unique_ptr<From>> {
82 static inline bool doit(const std::unique_ptr<From> &Val) {
83 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/Support/Casting.h"
, 83, __PRETTY_FUNCTION__))
;
84 return isa_impl_cl<To, From>::doit(*Val);
85 }
86};
87
88template <typename To, typename From> struct isa_impl_cl<To, From*> {
89 static inline bool doit(const From *Val) {
90 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/Support/Casting.h"
, 90, __PRETTY_FUNCTION__))
;
91 return isa_impl<To, From>::doit(*Val);
92 }
93};
94
95template <typename To, typename From> struct isa_impl_cl<To, From*const> {
96 static inline bool doit(const From *Val) {
97 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/Support/Casting.h"
, 97, __PRETTY_FUNCTION__))
;
98 return isa_impl<To, From>::doit(*Val);
99 }
100};
101
102template <typename To, typename From> struct isa_impl_cl<To, const From*> {
103 static inline bool doit(const From *Val) {
104 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/Support/Casting.h"
, 104, __PRETTY_FUNCTION__))
;
105 return isa_impl<To, From>::doit(*Val);
106 }
107};
108
109template <typename To, typename From> struct isa_impl_cl<To, const From*const> {
110 static inline bool doit(const From *Val) {
111 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/Support/Casting.h"
, 111, __PRETTY_FUNCTION__))
;
112 return isa_impl<To, From>::doit(*Val);
113 }
114};
115
116template<typename To, typename From, typename SimpleFrom>
117struct isa_impl_wrap {
118 // When From != SimplifiedType, we can simplify the type some more by using
119 // the simplify_type template.
120 static bool doit(const From &Val) {
121 return isa_impl_wrap<To, SimpleFrom,
122 typename simplify_type<SimpleFrom>::SimpleType>::doit(
123 simplify_type<const From>::getSimplifiedValue(Val));
124 }
125};
126
127template<typename To, typename FromTy>
128struct isa_impl_wrap<To, FromTy, FromTy> {
129 // When From == SimpleType, we are as simple as we are going to get.
130 static bool doit(const FromTy &Val) {
131 return isa_impl_cl<To,FromTy>::doit(Val);
132 }
133};
134
135// isa<X> - Return true if the parameter to the template is an instance of one
136// of the template type arguments. Used like this:
137//
138// if (isa<Type>(myVal)) { ... }
139// if (isa<Type0, Type1, Type2>(myVal)) { ... }
140//
141template <class X, class Y> LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
142 return isa_impl_wrap<X, const Y,
143 typename simplify_type<const Y>::SimpleType>::doit(Val);
144}
145
146template <typename First, typename Second, typename... Rest, typename Y>
147LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
148 return isa<First>(Val) || isa<Second, Rest...>(Val);
149}
150
151// isa_and_nonnull<X> - Functionally identical to isa, except that a null value
152// is accepted.
153//
154template <typename... X, class Y>
155LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa_and_nonnull(const Y &Val) {
156 if (!Val)
157 return false;
158 return isa<X...>(Val);
159}
160
161//===----------------------------------------------------------------------===//
162// cast<x> Support Templates
163//===----------------------------------------------------------------------===//
164
165template<class To, class From> struct cast_retty;
166
167// Calculate what type the 'cast' function should return, based on a requested
168// type of To and a source type of From.
169template<class To, class From> struct cast_retty_impl {
170 using ret_type = To &; // Normal case, return Ty&
171};
172template<class To, class From> struct cast_retty_impl<To, const From> {
173 using ret_type = const To &; // Normal case, return Ty&
174};
175
176template<class To, class From> struct cast_retty_impl<To, From*> {
177 using ret_type = To *; // Pointer arg case, return Ty*
178};
179
180template<class To, class From> struct cast_retty_impl<To, const From*> {
181 using ret_type = const To *; // Constant pointer arg case, return const Ty*
182};
183
184template<class To, class From> struct cast_retty_impl<To, const From*const> {
185 using ret_type = const To *; // Constant pointer arg case, return const Ty*
186};
187
188template <class To, class From>
189struct cast_retty_impl<To, std::unique_ptr<From>> {
190private:
191 using PointerType = typename cast_retty_impl<To, From *>::ret_type;
192 using ResultType = std::remove_pointer_t<PointerType>;
193
194public:
195 using ret_type = std::unique_ptr<ResultType>;
196};
197
198template<class To, class From, class SimpleFrom>
199struct cast_retty_wrap {
200 // When the simplified type and the from type are not the same, use the type
201 // simplifier to reduce the type, then reuse cast_retty_impl to get the
202 // resultant type.
203 using ret_type = typename cast_retty<To, SimpleFrom>::ret_type;
204};
205
206template<class To, class FromTy>
207struct cast_retty_wrap<To, FromTy, FromTy> {
208 // When the simplified type is equal to the from type, use it directly.
209 using ret_type = typename cast_retty_impl<To,FromTy>::ret_type;
210};
211
212template<class To, class From>
213struct cast_retty {
214 using ret_type = typename cast_retty_wrap<
215 To, From, typename simplify_type<From>::SimpleType>::ret_type;
216};
217
218// Ensure the non-simple values are converted using the simplify_type template
219// that may be specialized by smart pointers...
220//
221template<class To, class From, class SimpleFrom> struct cast_convert_val {
222 // This is not a simple type, use the template to simplify it...
223 static typename cast_retty<To, From>::ret_type doit(From &Val) {
224 return cast_convert_val<To, SimpleFrom,
35
Returning without writing to 'Val.Node'
225 typename simplify_type<SimpleFrom>::SimpleType>::doit(
226 simplify_type<From>::getSimplifiedValue(Val));
32
Calling 'simplify_type::getSimplifiedValue'
34
Returning from 'simplify_type::getSimplifiedValue'
227 }
228};
229
230template<class To, class FromTy> struct cast_convert_val<To,FromTy,FromTy> {
231 // This _is_ a simple type, just cast it.
232 static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) {
233 typename cast_retty<To, FromTy>::ret_type Res2
234 = (typename cast_retty<To, FromTy>::ret_type)const_cast<FromTy&>(Val);
235 return Res2;
236 }
237};
238
239template <class X> struct is_simple_type {
240 static const bool value =
241 std::is_same<X, typename simplify_type<X>::SimpleType>::value;
242};
243
244// cast<X> - Return the argument parameter cast to the specified type. This
245// casting operator asserts that the type is correct, so it does not return null
246// on failure. It does not allow a null argument (use cast_or_null for that).
247// It is typically used like this:
248//
249// cast<Instruction>(myVal)->getParent()
250//
251template <class X, class Y>
252inline std::enable_if_t<!is_simple_type<Y>::value,
253 typename cast_retty<X, const Y>::ret_type>
254cast(const Y &Val) {
255 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/Support/Casting.h"
, 255, __PRETTY_FUNCTION__))
;
256 return cast_convert_val<
257 X, const Y, typename simplify_type<const Y>::SimpleType>::doit(Val);
258}
259
260template <class X, class Y>
261inline typename cast_retty<X, Y>::ret_type cast(Y &Val) {
262 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/Support/Casting.h"
, 262, __PRETTY_FUNCTION__))
;
29
Assuming 'Val' is a 'FrameIndexSDNode'
30
'?' condition is true
263 return cast_convert_val<X, Y,
31
Calling 'cast_convert_val::doit'
36
Returning from 'cast_convert_val::doit'
37
Returning without writing to 'Val.Node'
264 typename simplify_type<Y>::SimpleType>::doit(Val);
265}
266
267template <class X, class Y>
268inline typename cast_retty<X, Y *>::ret_type cast(Y *Val) {
269 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/Support/Casting.h"
, 269, __PRETTY_FUNCTION__))
;
270 return cast_convert_val<X, Y*,
271 typename simplify_type<Y*>::SimpleType>::doit(Val);
272}
273
274template <class X, class Y>
275inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
276cast(std::unique_ptr<Y> &&Val) {
277 assert(isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!")((isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val.get()) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/Support/Casting.h"
, 277, __PRETTY_FUNCTION__))
;
278 using ret_type = typename cast_retty<X, std::unique_ptr<Y>>::ret_type;
279 return ret_type(
280 cast_convert_val<X, Y *, typename simplify_type<Y *>::SimpleType>::doit(
281 Val.release()));
282}
283
284// cast_or_null<X> - Functionally identical to cast, except that a null value is
285// accepted.
286//
287template <class X, class Y>
288LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<
289 !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type>
290cast_or_null(const Y &Val) {
291 if (!Val)
292 return nullptr;
293 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/Support/Casting.h"
, 293, __PRETTY_FUNCTION__))
;
294 return cast<X>(Val);
295}
296
297template <class X, class Y>
298LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<!is_simple_type<Y>::value,
299 typename cast_retty<X, Y>::ret_type>
300cast_or_null(Y &Val) {
301 if (!Val)
302 return nullptr;
303 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/Support/Casting.h"
, 303, __PRETTY_FUNCTION__))
;
304 return cast<X>(Val);
305}
306
307template <class X, class Y>
308LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
309cast_or_null(Y *Val) {
310 if (!Val) return nullptr;
311 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/Support/Casting.h"
, 311, __PRETTY_FUNCTION__))
;
312 return cast<X>(Val);
313}
314
315template <class X, class Y>
316inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
317cast_or_null(std::unique_ptr<Y> &&Val) {
318 if (!Val)
319 return nullptr;
320 return cast<X>(std::move(Val));
321}
322
323// dyn_cast<X> - Return the argument parameter cast to the specified type. This
324// casting operator returns null if the argument is of the wrong type, so it can
325// be used to test for a type as well as cast if successful. This should be
326// used in the context of an if statement like this:
327//
328// if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... }
329//
330
331template <class X, class Y>
332LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<
333 !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type>
334dyn_cast(const Y &Val) {
335 return isa<X>(Val) ? cast<X>(Val) : nullptr;
336}
337
338template <class X, class Y>
339LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y>::ret_type dyn_cast(Y &Val) {
340 return isa<X>(Val) ? cast<X>(Val) : nullptr;
26
Assuming 'Val' is a 'FrameIndexSDNode'
27
'?' condition is true
28
Calling 'cast<llvm::FrameIndexSDNode, llvm::SDValue>'
38
Returning from 'cast<llvm::FrameIndexSDNode, llvm::SDValue>'
39
Returning without writing to 'Val.Node'
341}
342
343template <class X, class Y>
344LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type dyn_cast(Y *Val) {
345 return isa<X>(Val) ? cast<X>(Val) : nullptr;
346}
347
348// dyn_cast_or_null<X> - Functionally identical to dyn_cast, except that a null
349// value is accepted.
350//
351template <class X, class Y>
352LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<
353 !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type>
354dyn_cast_or_null(const Y &Val) {
355 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
356}
357
358template <class X, class Y>
359LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<!is_simple_type<Y>::value,
360 typename cast_retty<X, Y>::ret_type>
361dyn_cast_or_null(Y &Val) {
362 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
363}
364
365template <class X, class Y>
366LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
367dyn_cast_or_null(Y *Val) {
368 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
369}
370
371// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>,
372// taking ownership of the input pointer iff isa<X>(Val) is true. If the
373// cast is successful, From refers to nullptr on exit and the casted value
374// is returned. If the cast is unsuccessful, the function returns nullptr
375// and From is unchanged.
376template <class X, class Y>
377LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &Val)
378 -> decltype(cast<X>(Val)) {
379 if (!isa<X>(Val))
380 return nullptr;
381 return cast<X>(std::move(Val));
382}
383
384template <class X, class Y>
385LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val) {
386 return unique_dyn_cast<X, Y>(Val);
387}
388
389// dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast, except that
390// a null value is accepted.
391template <class X, class Y>
392LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &Val)
393 -> decltype(cast<X>(Val)) {
394 if (!Val)
395 return nullptr;
396 return unique_dyn_cast<X, Y>(Val);
397}
398
399template <class X, class Y>
400LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val) {
401 return unique_dyn_cast_or_null<X, Y>(Val);
402}
403
404} // end namespace llvm
405
406#endif // LLVM_SUPPORT_CASTING_H

/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h

1//===- llvm/CodeGen/SelectionDAGNodes.h - SelectionDAG Nodes ----*- 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 SDNode class and derived classes, which are used to
10// represent the nodes and operations present in a SelectionDAG. These nodes
11// and operations are machine code level operations, with some similarities to
12// the GCC RTL representation.
13//
14// Clients should include the SelectionDAG.h file instead of this file directly.
15//
16//===----------------------------------------------------------------------===//
17
18#ifndef LLVM_CODEGEN_SELECTIONDAGNODES_H
19#define LLVM_CODEGEN_SELECTIONDAGNODES_H
20
21#include "llvm/ADT/APFloat.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/BitVector.h"
24#include "llvm/ADT/FoldingSet.h"
25#include "llvm/ADT/GraphTraits.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/ilist_node.h"
29#include "llvm/ADT/iterator.h"
30#include "llvm/ADT/iterator_range.h"
31#include "llvm/CodeGen/ISDOpcodes.h"
32#include "llvm/CodeGen/MachineMemOperand.h"
33#include "llvm/CodeGen/Register.h"
34#include "llvm/CodeGen/ValueTypes.h"
35#include "llvm/IR/Constants.h"
36#include "llvm/IR/DebugLoc.h"
37#include "llvm/IR/Instruction.h"
38#include "llvm/IR/Instructions.h"
39#include "llvm/IR/Metadata.h"
40#include "llvm/IR/Operator.h"
41#include "llvm/Support/AlignOf.h"
42#include "llvm/Support/AtomicOrdering.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/MachineValueType.h"
46#include "llvm/Support/TypeSize.h"
47#include <algorithm>
48#include <cassert>
49#include <climits>
50#include <cstddef>
51#include <cstdint>
52#include <cstring>
53#include <iterator>
54#include <string>
55#include <tuple>
56
57namespace llvm {
58
59class APInt;
60class Constant;
61template <typename T> struct DenseMapInfo;
62class GlobalValue;
63class MachineBasicBlock;
64class MachineConstantPoolValue;
65class MCSymbol;
66class raw_ostream;
67class SDNode;
68class SelectionDAG;
69class Type;
70class Value;
71
72void checkForCycles(const SDNode *N, const SelectionDAG *DAG = nullptr,
73 bool force = false);
74
75/// This represents a list of ValueType's that has been intern'd by
76/// a SelectionDAG. Instances of this simple value class are returned by
77/// SelectionDAG::getVTList(...).
78///
79struct SDVTList {
80 const EVT *VTs;
81 unsigned int NumVTs;
82};
83
84namespace ISD {
85
86 /// Node predicates
87
88 /// If N is a BUILD_VECTOR node whose elements are all the same constant or
89 /// undefined, return true and return the constant value in \p SplatValue.
90 bool isConstantSplatVector(const SDNode *N, APInt &SplatValue);
91
92 /// Return true if the specified node is a BUILD_VECTOR where all of the
93 /// elements are ~0 or undef.
94 bool isBuildVectorAllOnes(const SDNode *N);
95
96 /// Return true if the specified node is a BUILD_VECTOR where all of the
97 /// elements are 0 or undef.
98 bool isBuildVectorAllZeros(const SDNode *N);
99
100 /// Return true if the specified node is a BUILD_VECTOR node of all
101 /// ConstantSDNode or undef.
102 bool isBuildVectorOfConstantSDNodes(const SDNode *N);
103
104 /// Return true if the specified node is a BUILD_VECTOR node of all
105 /// ConstantFPSDNode or undef.
106 bool isBuildVectorOfConstantFPSDNodes(const SDNode *N);
107
108 /// Return true if the node has at least one operand and all operands of the
109 /// specified node are ISD::UNDEF.
110 bool allOperandsUndef(const SDNode *N);
111
112} // end namespace ISD
113
114//===----------------------------------------------------------------------===//
115/// Unlike LLVM values, Selection DAG nodes may return multiple
116/// values as the result of a computation. Many nodes return multiple values,
117/// from loads (which define a token and a return value) to ADDC (which returns
118/// a result and a carry value), to calls (which may return an arbitrary number
119/// of values).
120///
121/// As such, each use of a SelectionDAG computation must indicate the node that
122/// computes it as well as which return value to use from that node. This pair
123/// of information is represented with the SDValue value type.
124///
125class SDValue {
126 friend struct DenseMapInfo<SDValue>;
127
128 SDNode *Node = nullptr; // The node defining the value we are using.
129 unsigned ResNo = 0; // Which return value of the node we are using.
130
131public:
132 SDValue() = default;
133 SDValue(SDNode *node, unsigned resno);
134
135 /// get the index which selects a specific result in the SDNode
136 unsigned getResNo() const { return ResNo; }
137
138 /// get the SDNode which holds the desired result
139 SDNode *getNode() const { return Node; }
140
141 /// set the SDNode
142 void setNode(SDNode *N) { Node = N; }
143
144 inline SDNode *operator->() const { return Node; }
145
146 bool operator==(const SDValue &O) const {
147 return Node == O.Node && ResNo == O.ResNo;
148 }
149 bool operator!=(const SDValue &O) const {
150 return !operator==(O);
151 }
152 bool operator<(const SDValue &O) const {
153 return std::tie(Node, ResNo) < std::tie(O.Node, O.ResNo);
154 }
155 explicit operator bool() const {
156 return Node != nullptr;
157 }
158
159 SDValue getValue(unsigned R) const {
160 return SDValue(Node, R);
161 }
162
163 /// Return true if this node is an operand of N.
164 bool isOperandOf(const SDNode *N) const;
165
166 /// Return the ValueType of the referenced return value.
167 inline EVT getValueType() const;
168
169 /// Return the simple ValueType of the referenced return value.
170 MVT getSimpleValueType() const {
171 return getValueType().getSimpleVT();
172 }
173
174 /// Returns the size of the value in bits.
175 ///
176 /// If the value type is a scalable vector type, the scalable property will
177 /// be set and the runtime size will be a positive integer multiple of the
178 /// base size.
179 TypeSize getValueSizeInBits() const {
180 return getValueType().getSizeInBits();
181 }
182
183 uint64_t getScalarValueSizeInBits() const {
184 return getValueType().getScalarType().getFixedSizeInBits();
185 }
186
187 // Forwarding methods - These forward to the corresponding methods in SDNode.
188 inline unsigned getOpcode() const;
189 inline unsigned getNumOperands() const;
190 inline const SDValue &getOperand(unsigned i) const;
191 inline uint64_t getConstantOperandVal(unsigned i) const;
192 inline const APInt &getConstantOperandAPInt(unsigned i) const;
193 inline bool isTargetMemoryOpcode() const;
194 inline bool isTargetOpcode() const;
195 inline bool isMachineOpcode() const;
196 inline bool isUndef() const;
197 inline unsigned getMachineOpcode() const;
198 inline const DebugLoc &getDebugLoc() const;
199 inline void dump() const;
200 inline void dump(const SelectionDAG *G) const;
201 inline void dumpr() const;
202 inline void dumpr(const SelectionDAG *G) const;
203
204 /// Return true if this operand (which must be a chain) reaches the
205 /// specified operand without crossing any side-effecting instructions.
206 /// In practice, this looks through token factors and non-volatile loads.
207 /// In order to remain efficient, this only
208 /// looks a couple of nodes in, it does not do an exhaustive search.
209 bool reachesChainWithoutSideEffects(SDValue Dest,
210 unsigned Depth = 2) const;
211
212 /// Return true if there are no nodes using value ResNo of Node.
213 inline bool use_empty() const;
214
215 /// Return true if there is exactly one node using value ResNo of Node.
216 inline bool hasOneUse() const;
217};
218
219template<> struct DenseMapInfo<SDValue> {
220 static inline SDValue getEmptyKey() {
221 SDValue V;
222 V.ResNo = -1U;
223 return V;
224 }
225
226 static inline SDValue getTombstoneKey() {
227 SDValue V;
228 V.ResNo = -2U;
229 return V;
230 }
231
232 static unsigned getHashValue(const SDValue &Val) {
233 return ((unsigned)((uintptr_t)Val.getNode() >> 4) ^
234 (unsigned)((uintptr_t)Val.getNode() >> 9)) + Val.getResNo();
235 }
236
237 static bool isEqual(const SDValue &LHS, const SDValue &RHS) {
238 return LHS == RHS;
239 }
240};
241
242/// Allow casting operators to work directly on
243/// SDValues as if they were SDNode*'s.
244template<> struct simplify_type<SDValue> {
245 using SimpleType = SDNode *;
246
247 static SimpleType getSimplifiedValue(SDValue &Val) {
248 return Val.getNode();
33
Returning without writing to 'Val.Node'
249 }
250};
251template<> struct simplify_type<const SDValue> {
252 using SimpleType = /*const*/ SDNode *;
253
254 static SimpleType getSimplifiedValue(const SDValue &Val) {
255 return Val.getNode();
256 }
257};
258
259/// Represents a use of a SDNode. This class holds an SDValue,
260/// which records the SDNode being used and the result number, a
261/// pointer to the SDNode using the value, and Next and Prev pointers,
262/// which link together all the uses of an SDNode.
263///
264class SDUse {
265 /// Val - The value being used.
266 SDValue Val;
267 /// User - The user of this value.
268 SDNode *User = nullptr;
269 /// Prev, Next - Pointers to the uses list of the SDNode referred by
270 /// this operand.
271 SDUse **Prev = nullptr;
272 SDUse *Next = nullptr;
273
274public:
275 SDUse() = default;
276 SDUse(const SDUse &U) = delete;
277 SDUse &operator=(const SDUse &) = delete;
278
279 /// Normally SDUse will just implicitly convert to an SDValue that it holds.
280 operator const SDValue&() const { return Val; }
281
282 /// If implicit conversion to SDValue doesn't work, the get() method returns
283 /// the SDValue.
284 const SDValue &get() const { return Val; }
285
286 /// This returns the SDNode that contains this Use.
287 SDNode *getUser() { return User; }
288
289 /// Get the next SDUse in the use list.
290 SDUse *getNext() const { return Next; }
291
292 /// Convenience function for get().getNode().
293 SDNode *getNode() const { return Val.getNode(); }
294 /// Convenience function for get().getResNo().
295 unsigned getResNo() const { return Val.getResNo(); }
296 /// Convenience function for get().getValueType().
297 EVT getValueType() const { return Val.getValueType(); }
298
299 /// Convenience function for get().operator==
300 bool operator==(const SDValue &V) const {
301 return Val == V;
302 }
303
304 /// Convenience function for get().operator!=
305 bool operator!=(const SDValue &V) const {
306 return Val != V;
307 }
308
309 /// Convenience function for get().operator<
310 bool operator<(const SDValue &V) const {
311 return Val < V;
312 }
313
314private:
315 friend class SelectionDAG;
316 friend class SDNode;
317 // TODO: unfriend HandleSDNode once we fix its operand handling.
318 friend class HandleSDNode;
319
320 void setUser(SDNode *p) { User = p; }
321
322 /// Remove this use from its existing use list, assign it the
323 /// given value, and add it to the new value's node's use list.
324 inline void set(const SDValue &V);
325 /// Like set, but only supports initializing a newly-allocated
326 /// SDUse with a non-null value.
327 inline void setInitial(const SDValue &V);
328 /// Like set, but only sets the Node portion of the value,
329 /// leaving the ResNo portion unmodified.
330 inline void setNode(SDNode *N);
331
332 void addToList(SDUse **List) {
333 Next = *List;
334 if (Next) Next->Prev = &Next;
335 Prev = List;
336 *List = this;
337 }
338
339 void removeFromList() {
340 *Prev = Next;
341 if (Next) Next->Prev = Prev;
342 }
343};
344
345/// simplify_type specializations - Allow casting operators to work directly on
346/// SDValues as if they were SDNode*'s.
347template<> struct simplify_type<SDUse> {
348 using SimpleType = SDNode *;
349
350 static SimpleType getSimplifiedValue(SDUse &Val) {
351 return Val.getNode();
352 }
353};
354
355/// These are IR-level optimization flags that may be propagated to SDNodes.
356/// TODO: This data structure should be shared by the IR optimizer and the
357/// the backend.
358struct SDNodeFlags {
359private:
360 bool NoUnsignedWrap : 1;
361 bool NoSignedWrap : 1;
362 bool Exact : 1;
363 bool NoNaNs : 1;
364 bool NoInfs : 1;
365 bool NoSignedZeros : 1;
366 bool AllowReciprocal : 1;
367 bool AllowContract : 1;
368 bool ApproximateFuncs : 1;
369 bool AllowReassociation : 1;
370
371 // We assume instructions do not raise floating-point exceptions by default,
372 // and only those marked explicitly may do so. We could choose to represent
373 // this via a positive "FPExcept" flags like on the MI level, but having a
374 // negative "NoFPExcept" flag here (that defaults to true) makes the flag
375 // intersection logic more straightforward.
376 bool NoFPExcept : 1;
377
378public:
379 /// Default constructor turns off all optimization flags.
380 SDNodeFlags()
381 : NoUnsignedWrap(false), NoSignedWrap(false), Exact(false), NoNaNs(false),
382 NoInfs(false), NoSignedZeros(false), AllowReciprocal(false),
383 AllowContract(false), ApproximateFuncs(false),
384 AllowReassociation(false), NoFPExcept(false) {}
385
386 /// Propagate the fast-math-flags from an IR FPMathOperator.
387 void copyFMF(const FPMathOperator &FPMO) {
388 setNoNaNs(FPMO.hasNoNaNs());
389 setNoInfs(FPMO.hasNoInfs());
390 setNoSignedZeros(FPMO.hasNoSignedZeros());
391 setAllowReciprocal(FPMO.hasAllowReciprocal());
392 setAllowContract(FPMO.hasAllowContract());
393 setApproximateFuncs(FPMO.hasApproxFunc());
394 setAllowReassociation(FPMO.hasAllowReassoc());
395 }
396
397 // These are mutators for each flag.
398 void setNoUnsignedWrap(bool b) { NoUnsignedWrap = b; }
399 void setNoSignedWrap(bool b) { NoSignedWrap = b; }
400 void setExact(bool b) { Exact = b; }
401 void setNoNaNs(bool b) { NoNaNs = b; }
402 void setNoInfs(bool b) { NoInfs = b; }
403 void setNoSignedZeros(bool b) { NoSignedZeros = b; }
404 void setAllowReciprocal(bool b) { AllowReciprocal = b; }
405 void setAllowContract(bool b) { AllowContract = b; }
406 void setApproximateFuncs(bool b) { ApproximateFuncs = b; }
407 void setAllowReassociation(bool b) { AllowReassociation = b; }
408 void setNoFPExcept(bool b) { NoFPExcept = b; }
409
410 // These are accessors for each flag.
411 bool hasNoUnsignedWrap() const { return NoUnsignedWrap; }
412 bool hasNoSignedWrap() const { return NoSignedWrap; }
413 bool hasExact() const { return Exact; }
414 bool hasNoNaNs() const { return NoNaNs; }
415 bool hasNoInfs() const { return NoInfs; }
416 bool hasNoSignedZeros() const { return NoSignedZeros; }
417 bool hasAllowReciprocal() const { return AllowReciprocal; }
418 bool hasAllowContract() const { return AllowContract; }
419 bool hasApproximateFuncs() const { return ApproximateFuncs; }
420 bool hasAllowReassociation() const { return AllowReassociation; }
421 bool hasNoFPExcept() const { return NoFPExcept; }
422
423 /// Clear any flags in this flag set that aren't also set in Flags. All
424 /// flags will be cleared if Flags are undefined.
425 void intersectWith(const SDNodeFlags Flags) {
426 NoUnsignedWrap &= Flags.NoUnsignedWrap;
427 NoSignedWrap &= Flags.NoSignedWrap;
428 Exact &= Flags.Exact;
429 NoNaNs &= Flags.NoNaNs;
430 NoInfs &= Flags.NoInfs;
431 NoSignedZeros &= Flags.NoSignedZeros;
432 AllowReciprocal &= Flags.AllowReciprocal;
433 AllowContract &= Flags.AllowContract;
434 ApproximateFuncs &= Flags.ApproximateFuncs;
435 AllowReassociation &= Flags.AllowReassociation;
436 NoFPExcept &= Flags.NoFPExcept;
437 }
438};
439
440/// Represents one node in the SelectionDAG.
441///
442class SDNode : public FoldingSetNode, public ilist_node<SDNode> {
443private:
444 /// The operation that this node performs.
445 int16_t NodeType;
446
447protected:
448 // We define a set of mini-helper classes to help us interpret the bits in our
449 // SubclassData. These are designed to fit within a uint16_t so they pack
450 // with NodeType.
451
452#if defined(_AIX) && (!defined(__GNUC__4) || defined(__ibmxl__))
453// Except for GCC; by default, AIX compilers store bit-fields in 4-byte words
454// and give the `pack` pragma push semantics.
455#define BEGIN_TWO_BYTE_PACK() _Pragma("pack(2)")pack(2)
456#define END_TWO_BYTE_PACK() _Pragma("pack(pop)")pack(pop)
457#else
458#define BEGIN_TWO_BYTE_PACK()
459#define END_TWO_BYTE_PACK()
460#endif
461
462BEGIN_TWO_BYTE_PACK()
463 class SDNodeBitfields {
464 friend class SDNode;
465 friend class MemIntrinsicSDNode;
466 friend class MemSDNode;
467 friend class SelectionDAG;
468
469 uint16_t HasDebugValue : 1;
470 uint16_t IsMemIntrinsic : 1;
471 uint16_t IsDivergent : 1;
472 };
473 enum { NumSDNodeBits = 3 };
474
475 class ConstantSDNodeBitfields {
476 friend class ConstantSDNode;
477
478 uint16_t : NumSDNodeBits;
479
480 uint16_t IsOpaque : 1;
481 };
482
483 class MemSDNodeBitfields {
484 friend class MemSDNode;
485 friend class MemIntrinsicSDNode;
486 friend class AtomicSDNode;
487
488 uint16_t : NumSDNodeBits;
489
490 uint16_t IsVolatile : 1;
491 uint16_t IsNonTemporal : 1;
492 uint16_t IsDereferenceable : 1;
493 uint16_t IsInvariant : 1;
494 };
495 enum { NumMemSDNodeBits = NumSDNodeBits + 4 };
496
497 class LSBaseSDNodeBitfields {
498 friend class LSBaseSDNode;
499 friend class MaskedLoadStoreSDNode;
500 friend class MaskedGatherScatterSDNode;
501
502 uint16_t : NumMemSDNodeBits;
503
504 // This storage is shared between disparate class hierarchies to hold an
505 // enumeration specific to the class hierarchy in use.
506 // LSBaseSDNode => enum ISD::MemIndexedMode
507 // MaskedLoadStoreBaseSDNode => enum ISD::MemIndexedMode
508 // MaskedGatherScatterSDNode => enum ISD::MemIndexType
509 uint16_t AddressingMode : 3;
510 };
511 enum { NumLSBaseSDNodeBits = NumMemSDNodeBits + 3 };
512
513 class LoadSDNodeBitfields {
514 friend class LoadSDNode;
515 friend class MaskedLoadSDNode;
516
517 uint16_t : NumLSBaseSDNodeBits;
518
519 uint16_t ExtTy : 2; // enum ISD::LoadExtType
520 uint16_t IsExpanding : 1;
521 };
522
523 class StoreSDNodeBitfields {
524 friend class StoreSDNode;
525 friend class MaskedStoreSDNode;
526 friend class MaskedScatterSDNode;
527
528 uint16_t : NumLSBaseSDNodeBits;
529
530 uint16_t IsTruncating : 1;
531 uint16_t IsCompressing : 1;
532 };
533
534 union {
535 char RawSDNodeBits[sizeof(uint16_t)];
536 SDNodeBitfields SDNodeBits;
537 ConstantSDNodeBitfields ConstantSDNodeBits;
538 MemSDNodeBitfields MemSDNodeBits;
539 LSBaseSDNodeBitfields LSBaseSDNodeBits;
540 LoadSDNodeBitfields LoadSDNodeBits;
541 StoreSDNodeBitfields StoreSDNodeBits;
542 };
543END_TWO_BYTE_PACK()
544#undef BEGIN_TWO_BYTE_PACK
545#undef END_TWO_BYTE_PACK
546
547 // RawSDNodeBits must cover the entirety of the union. This means that all of
548 // the union's members must have size <= RawSDNodeBits. We write the RHS as
549 // "2" instead of sizeof(RawSDNodeBits) because MSVC can't handle the latter.
550 static_assert(sizeof(SDNodeBitfields) <= 2, "field too wide");
551 static_assert(sizeof(ConstantSDNodeBitfields) <= 2, "field too wide");
552 static_assert(sizeof(MemSDNodeBitfields) <= 2, "field too wide");
553 static_assert(sizeof(LSBaseSDNodeBitfields) <= 2, "field too wide");
554 static_assert(sizeof(LoadSDNodeBitfields) <= 2, "field too wide");
555 static_assert(sizeof(StoreSDNodeBitfields) <= 2, "field too wide");
556
557private:
558 friend class SelectionDAG;
559 // TODO: unfriend HandleSDNode once we fix its operand handling.
560 friend class HandleSDNode;
561
562 /// Unique id per SDNode in the DAG.
563 int NodeId = -1;
564
565 /// The values that are used by this operation.
566 SDUse *OperandList = nullptr;
567
568 /// The types of the values this node defines. SDNode's may
569 /// define multiple values simultaneously.
570 const EVT *ValueList;
571
572 /// List of uses for this SDNode.
573 SDUse *UseList = nullptr;
574
575 /// The number of entries in the Operand/Value list.
576 unsigned short NumOperands = 0;
577 unsigned short NumValues;
578
579 // The ordering of the SDNodes. It roughly corresponds to the ordering of the
580 // original LLVM instructions.
581 // This is used for turning off scheduling, because we'll forgo
582 // the normal scheduling algorithms and output the instructions according to
583 // this ordering.
584 unsigned IROrder;
585
586 /// Source line information.
587 DebugLoc debugLoc;
588
589 /// Return a pointer to the specified value type.
590 static const EVT *getValueTypeList(EVT VT);
591
592 SDNodeFlags Flags;
593
594public:
595 /// Unique and persistent id per SDNode in the DAG.
596 /// Used for debug printing.
597 uint16_t PersistentId;
598
599 //===--------------------------------------------------------------------===//
600 // Accessors
601 //
602
603 /// Return the SelectionDAG opcode value for this node. For
604 /// pre-isel nodes (those for which isMachineOpcode returns false), these
605 /// are the opcode values in the ISD and <target>ISD namespaces. For
606 /// post-isel opcodes, see getMachineOpcode.
607 unsigned getOpcode() const { return (unsigned short)NodeType; }
608
609 /// Test if this node has a target-specific opcode (in the
610 /// \<target\>ISD namespace).
611 bool isTargetOpcode() const { return NodeType >= ISD::BUILTIN_OP_END; }
612
613 /// Test if this node has a target-specific opcode that may raise
614 /// FP exceptions (in the \<target\>ISD namespace and greater than
615 /// FIRST_TARGET_STRICTFP_OPCODE). Note that all target memory
616 /// opcode are currently automatically considered to possibly raise
617 /// FP exceptions as well.
618 bool isTargetStrictFPOpcode() const {
619 return NodeType >= ISD::FIRST_TARGET_STRICTFP_OPCODE;
620 }
621
622 /// Test if this node has a target-specific
623 /// memory-referencing opcode (in the \<target\>ISD namespace and
624 /// greater than FIRST_TARGET_MEMORY_OPCODE).
625 bool isTargetMemoryOpcode() const {
626 return NodeType >= ISD::FIRST_TARGET_MEMORY_OPCODE;
627 }
628
629 /// Return true if the type of the node type undefined.
630 bool isUndef() const { return NodeType == ISD::UNDEF; }
631
632 /// Test if this node is a memory intrinsic (with valid pointer information).
633 /// INTRINSIC_W_CHAIN and INTRINSIC_VOID nodes are sometimes created for
634 /// non-memory intrinsics (with chains) that are not really instances of
635 /// MemSDNode. For such nodes, we need some extra state to determine the
636 /// proper classof relationship.
637 bool isMemIntrinsic() const {
638 return (NodeType == ISD::INTRINSIC_W_CHAIN ||
639 NodeType == ISD::INTRINSIC_VOID) &&
640 SDNodeBits.IsMemIntrinsic;
641 }
642
643 /// Test if this node is a strict floating point pseudo-op.
644 bool isStrictFPOpcode() {
645 switch (NodeType) {
646 default:
647 return false;
648 case ISD::STRICT_FP16_TO_FP:
649 case ISD::STRICT_FP_TO_FP16:
650#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
651 case ISD::STRICT_##DAGN:
652#include "llvm/IR/ConstrainedOps.def"
653 return true;
654 }
655 }
656
657 /// Test if this node has a post-isel opcode, directly
658 /// corresponding to a MachineInstr opcode.
659 bool isMachineOpcode() const { return NodeType < 0; }
660
661 /// This may only be called if isMachineOpcode returns
662 /// true. It returns the MachineInstr opcode value that the node's opcode
663 /// corresponds to.
664 unsigned getMachineOpcode() const {
665 assert(isMachineOpcode() && "Not a MachineInstr opcode!")((isMachineOpcode() && "Not a MachineInstr opcode!") ?
static_cast<void> (0) : __assert_fail ("isMachineOpcode() && \"Not a MachineInstr opcode!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 665, __PRETTY_FUNCTION__))
;
666 return ~NodeType;
667 }
668
669 bool getHasDebugValue() const { return SDNodeBits.HasDebugValue; }
670 void setHasDebugValue(bool b) { SDNodeBits.HasDebugValue = b; }
671
672 bool isDivergent() const { return SDNodeBits.IsDivergent; }
673
674 /// Return true if there are no uses of this node.
675 bool use_empty() const { return UseList == nullptr; }
676
677 /// Return true if there is exactly one use of this node.
678 bool hasOneUse() const {
679 return !use_empty() && std::next(use_begin()) == use_end();
680 }
681
682 /// Return the number of uses of this node. This method takes
683 /// time proportional to the number of uses.
684 size_t use_size() const { return std::distance(use_begin(), use_end()); }
685
686 /// Return the unique node id.
687 int getNodeId() const { return NodeId; }
688
689 /// Set unique node id.
690 void setNodeId(int Id) { NodeId = Id; }
691
692 /// Return the node ordering.
693 unsigned getIROrder() const { return IROrder; }
694
695 /// Set the node ordering.
696 void setIROrder(unsigned Order) { IROrder = Order; }
697
698 /// Return the source location info.
699 const DebugLoc &getDebugLoc() const { return debugLoc; }
700
701 /// Set source location info. Try to avoid this, putting
702 /// it in the constructor is preferable.
703 void setDebugLoc(DebugLoc dl) { debugLoc = std::move(dl); }
704
705 /// This class provides iterator support for SDUse
706 /// operands that use a specific SDNode.
707 class use_iterator
708 : public std::iterator<std::forward_iterator_tag, SDUse, ptrdiff_t> {
709 friend class SDNode;
710
711 SDUse *Op = nullptr;
712
713 explicit use_iterator(SDUse *op) : Op(op) {}
714
715 public:
716 using reference = std::iterator<std::forward_iterator_tag,
717 SDUse, ptrdiff_t>::reference;
718 using pointer = std::iterator<std::forward_iterator_tag,
719 SDUse, ptrdiff_t>::pointer;
720
721 use_iterator() = default;
722 use_iterator(const use_iterator &I) : Op(I.Op) {}
723
724 bool operator==(const use_iterator &x) const {
725 return Op == x.Op;
726 }
727 bool operator!=(const use_iterator &x) const {
728 return !operator==(x);
729 }
730
731 /// Return true if this iterator is at the end of uses list.
732 bool atEnd() const { return Op == nullptr; }
733
734 // Iterator traversal: forward iteration only.
735 use_iterator &operator++() { // Preincrement
736 assert(Op && "Cannot increment end iterator!")((Op && "Cannot increment end iterator!") ? static_cast
<void> (0) : __assert_fail ("Op && \"Cannot increment end iterator!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 736, __PRETTY_FUNCTION__))
;
737 Op = Op->getNext();
738 return *this;
739 }
740
741 use_iterator operator++(int) { // Postincrement
742 use_iterator tmp = *this; ++*this; return tmp;
743 }
744
745 /// Retrieve a pointer to the current user node.
746 SDNode *operator*() const {
747 assert(Op && "Cannot dereference end iterator!")((Op && "Cannot dereference end iterator!") ? static_cast
<void> (0) : __assert_fail ("Op && \"Cannot dereference end iterator!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 747, __PRETTY_FUNCTION__))
;
748 return Op->getUser();
749 }
750
751 SDNode *operator->() const { return operator*(); }
752
753 SDUse &getUse() const { return *Op; }
754
755 /// Retrieve the operand # of this use in its user.
756 unsigned getOperandNo() const {
757 assert(Op && "Cannot dereference end iterator!")((Op && "Cannot dereference end iterator!") ? static_cast
<void> (0) : __assert_fail ("Op && \"Cannot dereference end iterator!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 757, __PRETTY_FUNCTION__))
;
758 return (unsigned)(Op - Op->getUser()->OperandList);
759 }
760 };
761
762 /// Provide iteration support to walk over all uses of an SDNode.
763 use_iterator use_begin() const {
764 return use_iterator(UseList);
765 }
766
767 static use_iterator use_end() { return use_iterator(nullptr); }
768
769 inline iterator_range<use_iterator> uses() {
770 return make_range(use_begin(), use_end());
771 }
772 inline iterator_range<use_iterator> uses() const {
773 return make_range(use_begin(), use_end());
774 }
775
776 /// Return true if there are exactly NUSES uses of the indicated value.
777 /// This method ignores uses of other values defined by this operation.
778 bool hasNUsesOfValue(unsigned NUses, unsigned Value) const;
779
780 /// Return true if there are any use of the indicated value.
781 /// This method ignores uses of other values defined by this operation.
782 bool hasAnyUseOfValue(unsigned Value) const;
783
784 /// Return true if this node is the only use of N.
785 bool isOnlyUserOf(const SDNode *N) const;
786
787 /// Return true if this node is an operand of N.
788 bool isOperandOf(const SDNode *N) const;
789
790 /// Return true if this node is a predecessor of N.
791 /// NOTE: Implemented on top of hasPredecessor and every bit as
792 /// expensive. Use carefully.
793 bool isPredecessorOf(const SDNode *N) const {
794 return N->hasPredecessor(this);
795 }
796
797 /// Return true if N is a predecessor of this node.
798 /// N is either an operand of this node, or can be reached by recursively
799 /// traversing up the operands.
800 /// NOTE: This is an expensive method. Use it carefully.
801 bool hasPredecessor(const SDNode *N) const;
802
803 /// Returns true if N is a predecessor of any node in Worklist. This
804 /// helper keeps Visited and Worklist sets externally to allow unions
805 /// searches to be performed in parallel, caching of results across
806 /// queries and incremental addition to Worklist. Stops early if N is
807 /// found but will resume. Remember to clear Visited and Worklists
808 /// if DAG changes. MaxSteps gives a maximum number of nodes to visit before
809 /// giving up. The TopologicalPrune flag signals that positive NodeIds are
810 /// topologically ordered (Operands have strictly smaller node id) and search
811 /// can be pruned leveraging this.
812 static bool hasPredecessorHelper(const SDNode *N,
813 SmallPtrSetImpl<const SDNode *> &Visited,
814 SmallVectorImpl<const SDNode *> &Worklist,
815 unsigned int MaxSteps = 0,
816 bool TopologicalPrune = false) {
817 SmallVector<const SDNode *, 8> DeferredNodes;
818 if (Visited.count(N))
819 return true;
820
821 // Node Id's are assigned in three places: As a topological
822 // ordering (> 0), during legalization (results in values set to
823 // 0), new nodes (set to -1). If N has a topolgical id then we
824 // know that all nodes with ids smaller than it cannot be
825 // successors and we need not check them. Filter out all node
826 // that can't be matches. We add them to the worklist before exit
827 // in case of multiple calls. Note that during selection the topological id
828 // may be violated if a node's predecessor is selected before it. We mark
829 // this at selection negating the id of unselected successors and
830 // restricting topological pruning to positive ids.
831
832 int NId = N->getNodeId();
833 // If we Invalidated the Id, reconstruct original NId.
834 if (NId < -1)
835 NId = -(NId + 1);
836
837 bool Found = false;
838 while (!Worklist.empty()) {
839 const SDNode *M = Worklist.pop_back_val();
840 int MId = M->getNodeId();
841 if (TopologicalPrune && M->getOpcode() != ISD::TokenFactor && (NId > 0) &&
842 (MId > 0) && (MId < NId)) {
843 DeferredNodes.push_back(M);
844 continue;
845 }
846 for (const SDValue &OpV : M->op_values()) {
847 SDNode *Op = OpV.getNode();
848 if (Visited.insert(Op).second)
849 Worklist.push_back(Op);
850 if (Op == N)
851 Found = true;
852 }
853 if (Found)
854 break;
855 if (MaxSteps != 0 && Visited.size() >= MaxSteps)
856 break;
857 }
858 // Push deferred nodes back on worklist.
859 Worklist.append(DeferredNodes.begin(), DeferredNodes.end());
860 // If we bailed early, conservatively return found.
861 if (MaxSteps != 0 && Visited.size() >= MaxSteps)
862 return true;
863 return Found;
864 }
865
866 /// Return true if all the users of N are contained in Nodes.
867 /// NOTE: Requires at least one match, but doesn't require them all.
868 static bool areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N);
869
870 /// Return the number of values used by this operation.
871 unsigned getNumOperands() const { return NumOperands; }
872
873 /// Return the maximum number of operands that a SDNode can hold.
874 static constexpr size_t getMaxNumOperands() {
875 return std::numeric_limits<decltype(SDNode::NumOperands)>::max();
876 }
877
878 /// Helper method returns the integer value of a ConstantSDNode operand.
879 inline uint64_t getConstantOperandVal(unsigned Num) const;
880
881 /// Helper method returns the APInt of a ConstantSDNode operand.
882 inline const APInt &getConstantOperandAPInt(unsigned Num) const;
883
884 const SDValue &getOperand(unsigned Num) const {
885 assert(Num < NumOperands && "Invalid child # of SDNode!")((Num < NumOperands && "Invalid child # of SDNode!"
) ? static_cast<void> (0) : __assert_fail ("Num < NumOperands && \"Invalid child # of SDNode!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 885, __PRETTY_FUNCTION__))
;
886 return OperandList[Num];
887 }
888
889 using op_iterator = SDUse *;
890
891 op_iterator op_begin() const { return OperandList; }
892 op_iterator op_end() const { return OperandList+NumOperands; }
893 ArrayRef<SDUse> ops() const { return makeArrayRef(op_begin(), op_end()); }
894
895 /// Iterator for directly iterating over the operand SDValue's.
896 struct value_op_iterator
897 : iterator_adaptor_base<value_op_iterator, op_iterator,
898 std::random_access_iterator_tag, SDValue,
899 ptrdiff_t, value_op_iterator *,
900 value_op_iterator *> {
901 explicit value_op_iterator(SDUse *U = nullptr)
902 : iterator_adaptor_base(U) {}
903
904 const SDValue &operator*() const { return I->get(); }
905 };
906
907 iterator_range<value_op_iterator> op_values() const {
908 return make_range(value_op_iterator(op_begin()),
909 value_op_iterator(op_end()));
910 }
911
912 SDVTList getVTList() const {
913 SDVTList X = { ValueList, NumValues };
914 return X;
915 }
916
917 /// If this node has a glue operand, return the node
918 /// to which the glue operand points. Otherwise return NULL.
919 SDNode *getGluedNode() const {
920 if (getNumOperands() != 0 &&
921 getOperand(getNumOperands()-1).getValueType() == MVT::Glue)
922 return getOperand(getNumOperands()-1).getNode();
923 return nullptr;
924 }
925
926 /// If this node has a glue value with a user, return
927 /// the user (there is at most one). Otherwise return NULL.
928 SDNode *getGluedUser() const {
929 for (use_iterator UI = use_begin(), UE = use_end(); UI != UE; ++UI)
930 if (UI.getUse().get().getValueType() == MVT::Glue)
931 return *UI;
932 return nullptr;
933 }
934
935 const SDNodeFlags getFlags() const { return Flags; }
936 void setFlags(SDNodeFlags NewFlags) { Flags = NewFlags; }
937
938 /// Clear any flags in this node that aren't also set in Flags.
939 /// If Flags is not in a defined state then this has no effect.
940 void intersectFlagsWith(const SDNodeFlags Flags);
941
942 /// Return the number of values defined/returned by this operator.
943 unsigned getNumValues() const { return NumValues; }
944
945 /// Return the type of a specified result.
946 EVT getValueType(unsigned ResNo) const {
947 assert(ResNo < NumValues && "Illegal result number!")((ResNo < NumValues && "Illegal result number!") ?
static_cast<void> (0) : __assert_fail ("ResNo < NumValues && \"Illegal result number!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 947, __PRETTY_FUNCTION__))
;
948 return ValueList[ResNo];
949 }
950
951 /// Return the type of a specified result as a simple type.
952 MVT getSimpleValueType(unsigned ResNo) const {
953 return getValueType(ResNo).getSimpleVT();
954 }
955
956 /// Returns MVT::getSizeInBits(getValueType(ResNo)).
957 ///
958 /// If the value type is a scalable vector type, the scalable property will
959 /// be set and the runtime size will be a positive integer multiple of the
960 /// base size.
961 TypeSize getValueSizeInBits(unsigned ResNo) const {
962 return getValueType(ResNo).getSizeInBits();
963 }
964
965 using value_iterator = const EVT *;
966
967 value_iterator value_begin() const { return ValueList; }
968 value_iterator value_end() const { return ValueList+NumValues; }
969 iterator_range<value_iterator> values() const {
970 return llvm::make_range(value_begin(), value_end());
971 }
972
973 /// Return the opcode of this operation for printing.
974 std::string getOperationName(const SelectionDAG *G = nullptr) const;
975 static const char* getIndexedModeName(ISD::MemIndexedMode AM);
976 void print_types(raw_ostream &OS, const SelectionDAG *G) const;
977 void print_details(raw_ostream &OS, const SelectionDAG *G) const;
978 void print(raw_ostream &OS, const SelectionDAG *G = nullptr) const;
979 void printr(raw_ostream &OS, const SelectionDAG *G = nullptr) const;
980
981 /// Print a SelectionDAG node and all children down to
982 /// the leaves. The given SelectionDAG allows target-specific nodes
983 /// to be printed in human-readable form. Unlike printr, this will
984 /// print the whole DAG, including children that appear multiple
985 /// times.
986 ///
987 void printrFull(raw_ostream &O, const SelectionDAG *G = nullptr) const;
988
989 /// Print a SelectionDAG node and children up to
990 /// depth "depth." The given SelectionDAG allows target-specific
991 /// nodes to be printed in human-readable form. Unlike printr, this
992 /// will print children that appear multiple times wherever they are
993 /// used.
994 ///
995 void printrWithDepth(raw_ostream &O, const SelectionDAG *G = nullptr,
996 unsigned depth = 100) const;
997
998 /// Dump this node, for debugging.
999 void dump() const;
1000
1001 /// Dump (recursively) this node and its use-def subgraph.
1002 void dumpr() const;
1003
1004 /// Dump this node, for debugging.
1005 /// The given SelectionDAG allows target-specific nodes to be printed
1006 /// in human-readable form.
1007 void dump(const SelectionDAG *G) const;
1008
1009 /// Dump (recursively) this node and its use-def subgraph.
1010 /// The given SelectionDAG allows target-specific nodes to be printed
1011 /// in human-readable form.
1012 void dumpr(const SelectionDAG *G) const;
1013
1014 /// printrFull to dbgs(). The given SelectionDAG allows
1015 /// target-specific nodes to be printed in human-readable form.
1016 /// Unlike dumpr, this will print the whole DAG, including children
1017 /// that appear multiple times.
1018 void dumprFull(const SelectionDAG *G = nullptr) const;
1019
1020 /// printrWithDepth to dbgs(). The given
1021 /// SelectionDAG allows target-specific nodes to be printed in
1022 /// human-readable form. Unlike dumpr, this will print children
1023 /// that appear multiple times wherever they are used.
1024 ///
1025 void dumprWithDepth(const SelectionDAG *G = nullptr,
1026 unsigned depth = 100) const;
1027
1028 /// Gather unique data for the node.
1029 void Profile(FoldingSetNodeID &ID) const;
1030
1031 /// This method should only be used by the SDUse class.
1032 void addUse(SDUse &U) { U.addToList(&UseList); }
1033
1034protected:
1035 static SDVTList getSDVTList(EVT VT) {
1036 SDVTList Ret = { getValueTypeList(VT), 1 };
1037 return Ret;
1038 }
1039
1040 /// Create an SDNode.
1041 ///
1042 /// SDNodes are created without any operands, and never own the operand
1043 /// storage. To add operands, see SelectionDAG::createOperands.
1044 SDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs)
1045 : NodeType(Opc), ValueList(VTs.VTs), NumValues(VTs.NumVTs),
1046 IROrder(Order), debugLoc(std::move(dl)) {
1047 memset(&RawSDNodeBits, 0, sizeof(RawSDNodeBits));
1048 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor")((debugLoc.hasTrivialDestructor() && "Expected trivial destructor"
) ? static_cast<void> (0) : __assert_fail ("debugLoc.hasTrivialDestructor() && \"Expected trivial destructor\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1048, __PRETTY_FUNCTION__))
;
1049 assert(NumValues == VTs.NumVTs &&((NumValues == VTs.NumVTs && "NumValues wasn't wide enough for its operands!"
) ? static_cast<void> (0) : __assert_fail ("NumValues == VTs.NumVTs && \"NumValues wasn't wide enough for its operands!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1050, __PRETTY_FUNCTION__))
1050 "NumValues wasn't wide enough for its operands!")((NumValues == VTs.NumVTs && "NumValues wasn't wide enough for its operands!"
) ? static_cast<void> (0) : __assert_fail ("NumValues == VTs.NumVTs && \"NumValues wasn't wide enough for its operands!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1050, __PRETTY_FUNCTION__))
;
1051 }
1052
1053 /// Release the operands and set this node to have zero operands.
1054 void DropOperands();
1055};
1056
1057/// Wrapper class for IR location info (IR ordering and DebugLoc) to be passed
1058/// into SDNode creation functions.
1059/// When an SDNode is created from the DAGBuilder, the DebugLoc is extracted
1060/// from the original Instruction, and IROrder is the ordinal position of
1061/// the instruction.
1062/// When an SDNode is created after the DAG is being built, both DebugLoc and
1063/// the IROrder are propagated from the original SDNode.
1064/// So SDLoc class provides two constructors besides the default one, one to
1065/// be used by the DAGBuilder, the other to be used by others.
1066class SDLoc {
1067private:
1068 DebugLoc DL;
1069 int IROrder = 0;
1070
1071public:
1072 SDLoc() = default;
1073 SDLoc(const SDNode *N) : DL(N->getDebugLoc()), IROrder(N->getIROrder()) {}
1074 SDLoc(const SDValue V) : SDLoc(V.getNode()) {}
1075 SDLoc(const Instruction *I, int Order) : IROrder(Order) {
1076 assert(Order >= 0 && "bad IROrder")((Order >= 0 && "bad IROrder") ? static_cast<void
> (0) : __assert_fail ("Order >= 0 && \"bad IROrder\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1076, __PRETTY_FUNCTION__))
;
1077 if (I)
1078 DL = I->getDebugLoc();
1079 }
1080
1081 unsigned getIROrder() const { return IROrder; }
1082 const DebugLoc &getDebugLoc() const { return DL; }
1083};
1084
1085// Define inline functions from the SDValue class.
1086
1087inline SDValue::SDValue(SDNode *node, unsigned resno)
1088 : Node(node), ResNo(resno) {
1089 // Explicitly check for !ResNo to avoid use-after-free, because there are
1090 // callers that use SDValue(N, 0) with a deleted N to indicate successful
1091 // combines.
1092 assert((!Node || !ResNo || ResNo < Node->getNumValues()) &&(((!Node || !ResNo || ResNo < Node->getNumValues()) &&
"Invalid result number for the given node!") ? static_cast<
void> (0) : __assert_fail ("(!Node || !ResNo || ResNo < Node->getNumValues()) && \"Invalid result number for the given node!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1093, __PRETTY_FUNCTION__))
1093 "Invalid result number for the given node!")(((!Node || !ResNo || ResNo < Node->getNumValues()) &&
"Invalid result number for the given node!") ? static_cast<
void> (0) : __assert_fail ("(!Node || !ResNo || ResNo < Node->getNumValues()) && \"Invalid result number for the given node!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1093, __PRETTY_FUNCTION__))
;
1094 assert(ResNo < -2U && "Cannot use result numbers reserved for DenseMaps.")((ResNo < -2U && "Cannot use result numbers reserved for DenseMaps."
) ? static_cast<void> (0) : __assert_fail ("ResNo < -2U && \"Cannot use result numbers reserved for DenseMaps.\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1094, __PRETTY_FUNCTION__))
;
1095}
1096
1097inline unsigned SDValue::getOpcode() const {
1098 return Node->getOpcode();
1099}
1100
1101inline EVT SDValue::getValueType() const {
1102 return Node->getValueType(ResNo);
44
Called C++ object pointer is null
1103}
1104
1105inline unsigned SDValue::getNumOperands() const {
1106 return Node->getNumOperands();
1107}
1108
1109inline const SDValue &SDValue::getOperand(unsigned i) const {
1110 return Node->getOperand(i);
1111}
1112
1113inline uint64_t SDValue::getConstantOperandVal(unsigned i) const {
1114 return Node->getConstantOperandVal(i);
1115}
1116
1117inline const APInt &SDValue::getConstantOperandAPInt(unsigned i) const {
1118 return Node->getConstantOperandAPInt(i);
1119}
1120
1121inline bool SDValue::isTargetOpcode() const {
1122 return Node->isTargetOpcode();
1123}
1124
1125inline bool SDValue::isTargetMemoryOpcode() const {
1126 return Node->isTargetMemoryOpcode();
1127}
1128
1129inline bool SDValue::isMachineOpcode() const {
1130 return Node->isMachineOpcode();
1131}
1132
1133inline unsigned SDValue::getMachineOpcode() const {
1134 return Node->getMachineOpcode();
1135}
1136
1137inline bool SDValue::isUndef() const {
1138 return Node->isUndef();
1139}
1140
1141inline bool SDValue::use_empty() const {
1142 return !Node->hasAnyUseOfValue(ResNo);
1143}
1144
1145inline bool SDValue::hasOneUse() const {
1146 return Node->hasNUsesOfValue(1, ResNo);
1147}
1148
1149inline const DebugLoc &SDValue::getDebugLoc() const {
1150 return Node->getDebugLoc();
1151}
1152
1153inline void SDValue::dump() const {
1154 return Node->dump();
1155}
1156
1157inline void SDValue::dump(const SelectionDAG *G) const {
1158 return Node->dump(G);
1159}
1160
1161inline void SDValue::dumpr() const {
1162 return Node->dumpr();
1163}
1164
1165inline void SDValue::dumpr(const SelectionDAG *G) const {
1166 return Node->dumpr(G);
1167}
1168
1169// Define inline functions from the SDUse class.
1170
1171inline void SDUse::set(const SDValue &V) {
1172 if (Val.getNode()) removeFromList();
1173 Val = V;
1174 if (V.getNode()) V.getNode()->addUse(*this);
1175}
1176
1177inline void SDUse::setInitial(const SDValue &V) {
1178 Val = V;
1179 V.getNode()->addUse(*this);
1180}
1181
1182inline void SDUse::setNode(SDNode *N) {
1183 if (Val.getNode()) removeFromList();
1184 Val.setNode(N);
1185 if (N) N->addUse(*this);
1186}
1187
1188/// This class is used to form a handle around another node that
1189/// is persistent and is updated across invocations of replaceAllUsesWith on its
1190/// operand. This node should be directly created by end-users and not added to
1191/// the AllNodes list.
1192class HandleSDNode : public SDNode {
1193 SDUse Op;
1194
1195public:
1196 explicit HandleSDNode(SDValue X)
1197 : SDNode(ISD::HANDLENODE, 0, DebugLoc(), getSDVTList(MVT::Other)) {
1198 // HandleSDNodes are never inserted into the DAG, so they won't be
1199 // auto-numbered. Use ID 65535 as a sentinel.
1200 PersistentId = 0xffff;
1201
1202 // Manually set up the operand list. This node type is special in that it's
1203 // always stack allocated and SelectionDAG does not manage its operands.
1204 // TODO: This should either (a) not be in the SDNode hierarchy, or (b) not
1205 // be so special.
1206 Op.setUser(this);
1207 Op.setInitial(X);
1208 NumOperands = 1;
1209 OperandList = &Op;
1210 }
1211 ~HandleSDNode();
1212
1213 const SDValue &getValue() const { return Op; }
1214};
1215
1216class AddrSpaceCastSDNode : public SDNode {
1217private:
1218 unsigned SrcAddrSpace;
1219 unsigned DestAddrSpace;
1220
1221public:
1222 AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, EVT VT,
1223 unsigned SrcAS, unsigned DestAS);
1224
1225 unsigned getSrcAddressSpace() const { return SrcAddrSpace; }
1226 unsigned getDestAddressSpace() const { return DestAddrSpace; }
1227
1228 static bool classof(const SDNode *N) {
1229 return N->getOpcode() == ISD::ADDRSPACECAST;
1230 }
1231};
1232
1233/// This is an abstract virtual class for memory operations.
1234class MemSDNode : public SDNode {
1235private:
1236 // VT of in-memory value.
1237 EVT MemoryVT;
1238
1239protected:
1240 /// Memory reference information.
1241 MachineMemOperand *MMO;
1242
1243public:
1244 MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs,
1245 EVT memvt, MachineMemOperand *MMO);
1246
1247 bool readMem() const { return MMO->isLoad(); }
1248 bool writeMem() const { return MMO->isStore(); }
1249
1250 /// Returns alignment and volatility of the memory access
1251 Align getOriginalAlign() const { return MMO->getBaseAlign(); }
1252 Align getAlign() const { return MMO->getAlign(); }
1253 LLVM_ATTRIBUTE_DEPRECATED(unsigned getOriginalAlignment() const,unsigned getOriginalAlignment() const __attribute__((deprecated
("Use getOriginalAlign() instead")))
1254 "Use getOriginalAlign() instead")unsigned getOriginalAlignment() const __attribute__((deprecated
("Use getOriginalAlign() instead")))
{
1255 return MMO->getBaseAlign().value();
1256 }
1257 // FIXME: Remove once transition to getAlign is over.
1258 unsigned getAlignment() const { return MMO->getAlign().value(); }
1259
1260 /// Return the SubclassData value, without HasDebugValue. This contains an
1261 /// encoding of the volatile flag, as well as bits used by subclasses. This
1262 /// function should only be used to compute a FoldingSetNodeID value.
1263 /// The HasDebugValue bit is masked out because CSE map needs to match
1264 /// nodes with debug info with nodes without debug info. Same is about
1265 /// isDivergent bit.
1266 unsigned getRawSubclassData() const {
1267 uint16_t Data;
1268 union {
1269 char RawSDNodeBits[sizeof(uint16_t)];
1270 SDNodeBitfields SDNodeBits;
1271 };
1272 memcpy(&RawSDNodeBits, &this->RawSDNodeBits, sizeof(this->RawSDNodeBits));
1273 SDNodeBits.HasDebugValue = 0;
1274 SDNodeBits.IsDivergent = false;
1275 memcpy(&Data, &RawSDNodeBits, sizeof(RawSDNodeBits));
1276 return Data;
1277 }
1278
1279 bool isVolatile() const { return MemSDNodeBits.IsVolatile; }
1280 bool isNonTemporal() const { return MemSDNodeBits.IsNonTemporal; }
1281 bool isDereferenceable() const { return MemSDNodeBits.IsDereferenceable; }
1282 bool isInvariant() const { return MemSDNodeBits.IsInvariant; }
1283
1284 // Returns the offset from the location of the access.
1285 int64_t getSrcValueOffset() const { return MMO->getOffset(); }
1286
1287 /// Returns the AA info that describes the dereference.
1288 AAMDNodes getAAInfo() const { return MMO->getAAInfo(); }
1289
1290 /// Returns the Ranges that describes the dereference.
1291 const MDNode *getRanges() const { return MMO->getRanges(); }
1292
1293 /// Returns the synchronization scope ID for this memory operation.
1294 SyncScope::ID getSyncScopeID() const { return MMO->getSyncScopeID(); }
1295
1296 /// Return the atomic ordering requirements for this memory operation. For
1297 /// cmpxchg atomic operations, return the atomic ordering requirements when
1298 /// store occurs.
1299 AtomicOrdering getOrdering() const { return MMO->getOrdering(); }
1300
1301 /// Return true if the memory operation ordering is Unordered or higher.
1302 bool isAtomic() const { return MMO->isAtomic(); }
1303
1304 /// Returns true if the memory operation doesn't imply any ordering
1305 /// constraints on surrounding memory operations beyond the normal memory
1306 /// aliasing rules.
1307 bool isUnordered() const { return MMO->isUnordered(); }
1308
1309 /// Returns true if the memory operation is neither atomic or volatile.
1310 bool isSimple() const { return !isAtomic() && !isVolatile(); }
1311
1312 /// Return the type of the in-memory value.
1313 EVT getMemoryVT() const { return MemoryVT; }
1314
1315 /// Return a MachineMemOperand object describing the memory
1316 /// reference performed by operation.
1317 MachineMemOperand *getMemOperand() const { return MMO; }
1318
1319 const MachinePointerInfo &getPointerInfo() const {
1320 return MMO->getPointerInfo();
1321 }
1322
1323 /// Return the address space for the associated pointer
1324 unsigned getAddressSpace() const {
1325 return getPointerInfo().getAddrSpace();
1326 }
1327
1328 /// Update this MemSDNode's MachineMemOperand information
1329 /// to reflect the alignment of NewMMO, if it has a greater alignment.
1330 /// This must only be used when the new alignment applies to all users of
1331 /// this MachineMemOperand.
1332 void refineAlignment(const MachineMemOperand *NewMMO) {
1333 MMO->refineAlignment(NewMMO);
1334 }
1335
1336 const SDValue &getChain() const { return getOperand(0); }
1337
1338 const SDValue &getBasePtr() const {
1339 switch (getOpcode()) {
1340 case ISD::STORE:
1341 case ISD::MSTORE:
1342 return getOperand(2);
1343 case ISD::MGATHER:
1344 case ISD::MSCATTER:
1345 return getOperand(3);
1346 default:
1347 return getOperand(1);
1348 }
1349 }
1350
1351 // Methods to support isa and dyn_cast
1352 static bool classof(const SDNode *N) {
1353 // For some targets, we lower some target intrinsics to a MemIntrinsicNode
1354 // with either an intrinsic or a target opcode.
1355 return N->getOpcode() == ISD::LOAD ||
1356 N->getOpcode() == ISD::STORE ||
1357 N->getOpcode() == ISD::PREFETCH ||
1358 N->getOpcode() == ISD::ATOMIC_CMP_SWAP ||
1359 N->getOpcode() == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS ||
1360 N->getOpcode() == ISD::ATOMIC_SWAP ||
1361 N->getOpcode() == ISD::ATOMIC_LOAD_ADD ||
1362 N->getOpcode() == ISD::ATOMIC_LOAD_SUB ||
1363 N->getOpcode() == ISD::ATOMIC_LOAD_AND ||
1364 N->getOpcode() == ISD::ATOMIC_LOAD_CLR ||
1365 N->getOpcode() == ISD::ATOMIC_LOAD_OR ||
1366 N->getOpcode() == ISD::ATOMIC_LOAD_XOR ||
1367 N->getOpcode() == ISD::ATOMIC_LOAD_NAND ||
1368 N->getOpcode() == ISD::ATOMIC_LOAD_MIN ||
1369 N->getOpcode() == ISD::ATOMIC_LOAD_MAX ||
1370 N->getOpcode() == ISD::ATOMIC_LOAD_UMIN ||
1371 N->getOpcode() == ISD::ATOMIC_LOAD_UMAX ||
1372 N->getOpcode() == ISD::ATOMIC_LOAD_FADD ||
1373 N->getOpcode() == ISD::ATOMIC_LOAD_FSUB ||
1374 N->getOpcode() == ISD::ATOMIC_LOAD ||
1375 N->getOpcode() == ISD::ATOMIC_STORE ||
1376 N->getOpcode() == ISD::MLOAD ||
1377 N->getOpcode() == ISD::MSTORE ||
1378 N->getOpcode() == ISD::MGATHER ||
1379 N->getOpcode() == ISD::MSCATTER ||
1380 N->isMemIntrinsic() ||
1381 N->isTargetMemoryOpcode();
1382 }
1383};
1384
1385/// This is an SDNode representing atomic operations.
1386class AtomicSDNode : public MemSDNode {
1387public:
1388 AtomicSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTL,
1389 EVT MemVT, MachineMemOperand *MMO)
1390 : MemSDNode(Opc, Order, dl, VTL, MemVT, MMO) {
1391 assert(((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE) ||((((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE
) || MMO->isAtomic()) && "then why are we using an AtomicSDNode?"
) ? static_cast<void> (0) : __assert_fail ("((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE) || MMO->isAtomic()) && \"then why are we using an AtomicSDNode?\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1392, __PRETTY_FUNCTION__))
1392 MMO->isAtomic()) && "then why are we using an AtomicSDNode?")((((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE
) || MMO->isAtomic()) && "then why are we using an AtomicSDNode?"
) ? static_cast<void> (0) : __assert_fail ("((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE) || MMO->isAtomic()) && \"then why are we using an AtomicSDNode?\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1392, __PRETTY_FUNCTION__))
;
1393 }
1394
1395 const SDValue &getBasePtr() const { return getOperand(1); }
1396 const SDValue &getVal() const { return getOperand(2); }
1397
1398 /// Returns true if this SDNode represents cmpxchg atomic operation, false
1399 /// otherwise.
1400 bool isCompareAndSwap() const {
1401 unsigned Op = getOpcode();
1402 return Op == ISD::ATOMIC_CMP_SWAP ||
1403 Op == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS;
1404 }
1405
1406 /// For cmpxchg atomic operations, return the atomic ordering requirements
1407 /// when store does not occur.
1408 AtomicOrdering getFailureOrdering() const {
1409 assert(isCompareAndSwap() && "Must be cmpxchg operation")((isCompareAndSwap() && "Must be cmpxchg operation") ?
static_cast<void> (0) : __assert_fail ("isCompareAndSwap() && \"Must be cmpxchg operation\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1409, __PRETTY_FUNCTION__))
;
1410 return MMO->getFailureOrdering();
1411 }
1412
1413 // Methods to support isa and dyn_cast
1414 static bool classof(const SDNode *N) {
1415 return N->getOpcode() == ISD::ATOMIC_CMP_SWAP ||
1416 N->getOpcode() == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS ||
1417 N->getOpcode() == ISD::ATOMIC_SWAP ||
1418 N->getOpcode() == ISD::ATOMIC_LOAD_ADD ||
1419 N->getOpcode() == ISD::ATOMIC_LOAD_SUB ||
1420 N->getOpcode() == ISD::ATOMIC_LOAD_AND ||
1421 N->getOpcode() == ISD::ATOMIC_LOAD_CLR ||
1422 N->getOpcode() == ISD::ATOMIC_LOAD_OR ||
1423 N->getOpcode() == ISD::ATOMIC_LOAD_XOR ||
1424 N->getOpcode() == ISD::ATOMIC_LOAD_NAND ||
1425 N->getOpcode() == ISD::ATOMIC_LOAD_MIN ||
1426 N->getOpcode() == ISD::ATOMIC_LOAD_MAX ||
1427 N->getOpcode() == ISD::ATOMIC_LOAD_UMIN ||
1428 N->getOpcode() == ISD::ATOMIC_LOAD_UMAX ||
1429 N->getOpcode() == ISD::ATOMIC_LOAD_FADD ||
1430 N->getOpcode() == ISD::ATOMIC_LOAD_FSUB ||
1431 N->getOpcode() == ISD::ATOMIC_LOAD ||
1432 N->getOpcode() == ISD::ATOMIC_STORE;
1433 }
1434};
1435
1436/// This SDNode is used for target intrinsics that touch
1437/// memory and need an associated MachineMemOperand. Its opcode may be
1438/// INTRINSIC_VOID, INTRINSIC_W_CHAIN, PREFETCH, or a target-specific opcode
1439/// with a value not less than FIRST_TARGET_MEMORY_OPCODE.
1440class MemIntrinsicSDNode : public MemSDNode {
1441public:
1442 MemIntrinsicSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
1443 SDVTList VTs, EVT MemoryVT, MachineMemOperand *MMO)
1444 : MemSDNode(Opc, Order, dl, VTs, MemoryVT, MMO) {
1445 SDNodeBits.IsMemIntrinsic = true;
1446 }
1447
1448 // Methods to support isa and dyn_cast
1449 static bool classof(const SDNode *N) {
1450 // We lower some target intrinsics to their target opcode
1451 // early a node with a target opcode can be of this class
1452 return N->isMemIntrinsic() ||
1453 N->getOpcode() == ISD::PREFETCH ||
1454 N->isTargetMemoryOpcode();
1455 }
1456};
1457
1458/// This SDNode is used to implement the code generator
1459/// support for the llvm IR shufflevector instruction. It combines elements
1460/// from two input vectors into a new input vector, with the selection and
1461/// ordering of elements determined by an array of integers, referred to as
1462/// the shuffle mask. For input vectors of width N, mask indices of 0..N-1
1463/// refer to elements from the LHS input, and indices from N to 2N-1 the RHS.
1464/// An index of -1 is treated as undef, such that the code generator may put
1465/// any value in the corresponding element of the result.
1466class ShuffleVectorSDNode : public SDNode {
1467 // The memory for Mask is owned by the SelectionDAG's OperandAllocator, and
1468 // is freed when the SelectionDAG object is destroyed.
1469 const int *Mask;
1470
1471protected:
1472 friend class SelectionDAG;
1473
1474 ShuffleVectorSDNode(EVT VT, unsigned Order, const DebugLoc &dl, const int *M)
1475 : SDNode(ISD::VECTOR_SHUFFLE, Order, dl, getSDVTList(VT)), Mask(M) {}
1476
1477public:
1478 ArrayRef<int> getMask() const {
1479 EVT VT = getValueType(0);
1480 return makeArrayRef(Mask, VT.getVectorNumElements());
1481 }
1482
1483 int getMaskElt(unsigned Idx) const {
1484 assert(Idx < getValueType(0).getVectorNumElements() && "Idx out of range!")((Idx < getValueType(0).getVectorNumElements() && "Idx out of range!"
) ? static_cast<void> (0) : __assert_fail ("Idx < getValueType(0).getVectorNumElements() && \"Idx out of range!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1484, __PRETTY_FUNCTION__))
;
1485 return Mask[Idx];
1486 }
1487
1488 bool isSplat() const { return isSplatMask(Mask, getValueType(0)); }
1489
1490 int getSplatIndex() const {
1491 assert(isSplat() && "Cannot get splat index for non-splat!")((isSplat() && "Cannot get splat index for non-splat!"
) ? static_cast<void> (0) : __assert_fail ("isSplat() && \"Cannot get splat index for non-splat!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1491, __PRETTY_FUNCTION__))
;
1492 EVT VT = getValueType(0);
1493 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1494 if (Mask[i] >= 0)
1495 return Mask[i];
1496
1497 // We can choose any index value here and be correct because all elements
1498 // are undefined. Return 0 for better potential for callers to simplify.
1499 return 0;
1500 }
1501
1502 static bool isSplatMask(const int *Mask, EVT VT);
1503
1504 /// Change values in a shuffle permute mask assuming
1505 /// the two vector operands have swapped position.
1506 static void commuteMask(MutableArrayRef<int> Mask) {
1507 unsigned NumElems = Mask.size();
1508 for (unsigned i = 0; i != NumElems; ++i) {
1509 int idx = Mask[i];
1510 if (idx < 0)
1511 continue;
1512 else if (idx < (int)NumElems)
1513 Mask[i] = idx + NumElems;
1514 else
1515 Mask[i] = idx - NumElems;
1516 }
1517 }
1518
1519 static bool classof(const SDNode *N) {
1520 return N->getOpcode() == ISD::VECTOR_SHUFFLE;
1521 }
1522};
1523
1524class ConstantSDNode : public SDNode {
1525 friend class SelectionDAG;
1526
1527 const ConstantInt *Value;
1528
1529 ConstantSDNode(bool isTarget, bool isOpaque, const ConstantInt *val, EVT VT)
1530 : SDNode(isTarget ? ISD::TargetConstant : ISD::Constant, 0, DebugLoc(),
1531 getSDVTList(VT)),
1532 Value(val) {
1533 ConstantSDNodeBits.IsOpaque = isOpaque;
1534 }
1535
1536public:
1537 const ConstantInt *getConstantIntValue() const { return Value; }
1538 const APInt &getAPIntValue() const { return Value->getValue(); }
1539 uint64_t getZExtValue() const { return Value->getZExtValue(); }
1540 int64_t getSExtValue() const { return Value->getSExtValue(); }
1541 uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX(18446744073709551615UL)) {
1542 return Value->getLimitedValue(Limit);
1543 }
1544 MaybeAlign getMaybeAlignValue() const { return Value->getMaybeAlignValue(); }
1545 Align getAlignValue() const { return Value->getAlignValue(); }
1546
1547 bool isOne() const { return Value->isOne(); }
1548 bool isNullValue() const { return Value->isZero(); }
1549 bool isAllOnesValue() const { return Value->isMinusOne(); }
1550
1551 bool isOpaque() const { return ConstantSDNodeBits.IsOpaque; }
1552
1553 static bool classof(const SDNode *N) {
1554 return N->getOpcode() == ISD::Constant ||
1555 N->getOpcode() == ISD::TargetConstant;
1556 }
1557};
1558
1559uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
1560 return cast<ConstantSDNode>(getOperand(Num))->getZExtValue();
1561}
1562
1563const APInt &SDNode::getConstantOperandAPInt(unsigned Num) const {
1564 return cast<ConstantSDNode>(getOperand(Num))->getAPIntValue();
1565}
1566
1567class ConstantFPSDNode : public SDNode {
1568 friend class SelectionDAG;
1569
1570 const ConstantFP *Value;
1571
1572 ConstantFPSDNode(bool isTarget, const ConstantFP *val, EVT VT)
1573 : SDNode(isTarget ? ISD::TargetConstantFP : ISD::ConstantFP, 0,
1574 DebugLoc(), getSDVTList(VT)),
1575 Value(val) {}
1576
1577public:
1578 const APFloat& getValueAPF() const { return Value->getValueAPF(); }
1579 const ConstantFP *getConstantFPValue() const { return Value; }
1580
1581 /// Return true if the value is positive or negative zero.
1582 bool isZero() const { return Value->isZero(); }
1583
1584 /// Return true if the value is a NaN.
1585 bool isNaN() const { return Value->isNaN(); }
1586
1587 /// Return true if the value is an infinity
1588 bool isInfinity() const { return Value->isInfinity(); }
1589
1590 /// Return true if the value is negative.
1591 bool isNegative() const { return Value->isNegative(); }
1592
1593 /// We don't rely on operator== working on double values, as
1594 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
1595 /// As such, this method can be used to do an exact bit-for-bit comparison of
1596 /// two floating point values.
1597
1598 /// We leave the version with the double argument here because it's just so
1599 /// convenient to write "2.0" and the like. Without this function we'd
1600 /// have to duplicate its logic everywhere it's called.
1601 bool isExactlyValue(double V) const {
1602 return Value->getValueAPF().isExactlyValue(V);
1603 }
1604 bool isExactlyValue(const APFloat& V) const;
1605
1606 static bool isValueValidForType(EVT VT, const APFloat& Val);
1607
1608 static bool classof(const SDNode *N) {
1609 return N->getOpcode() == ISD::ConstantFP ||
1610 N->getOpcode() == ISD::TargetConstantFP;
1611 }
1612};
1613
1614/// Returns true if \p V is a constant integer zero.
1615bool isNullConstant(SDValue V);
1616
1617/// Returns true if \p V is an FP constant with a value of positive zero.
1618bool isNullFPConstant(SDValue V);
1619
1620/// Returns true if \p V is an integer constant with all bits set.
1621bool isAllOnesConstant(SDValue V);
1622
1623/// Returns true if \p V is a constant integer one.
1624bool isOneConstant(SDValue V);
1625
1626/// Return the non-bitcasted source operand of \p V if it exists.
1627/// If \p V is not a bitcasted value, it is returned as-is.
1628SDValue peekThroughBitcasts(SDValue V);
1629
1630/// Return the non-bitcasted and one-use source operand of \p V if it exists.
1631/// If \p V is not a bitcasted one-use value, it is returned as-is.
1632SDValue peekThroughOneUseBitcasts(SDValue V);
1633
1634/// Return the non-extracted vector source operand of \p V if it exists.
1635/// If \p V is not an extracted subvector, it is returned as-is.
1636SDValue peekThroughExtractSubvectors(SDValue V);
1637
1638/// Returns true if \p V is a bitwise not operation. Assumes that an all ones
1639/// constant is canonicalized to be operand 1.
1640bool isBitwiseNot(SDValue V, bool AllowUndefs = false);
1641
1642/// Returns the SDNode if it is a constant splat BuildVector or constant int.
1643ConstantSDNode *isConstOrConstSplat(SDValue N, bool AllowUndefs = false,
1644 bool AllowTruncation = false);
1645
1646/// Returns the SDNode if it is a demanded constant splat BuildVector or
1647/// constant int.
1648ConstantSDNode *isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
1649 bool AllowUndefs = false,
1650 bool AllowTruncation = false);
1651
1652/// Returns the SDNode if it is a constant splat BuildVector or constant float.
1653ConstantFPSDNode *isConstOrConstSplatFP(SDValue N, bool AllowUndefs = false);
1654
1655/// Returns the SDNode if it is a demanded constant splat BuildVector or
1656/// constant float.
1657ConstantFPSDNode *isConstOrConstSplatFP(SDValue N, const APInt &DemandedElts,
1658 bool AllowUndefs = false);
1659
1660/// Return true if the value is a constant 0 integer or a splatted vector of
1661/// a constant 0 integer (with no undefs by default).
1662/// Build vector implicit truncation is not an issue for null values.
1663bool isNullOrNullSplat(SDValue V, bool AllowUndefs = false);
1664
1665/// Return true if the value is a constant 1 integer or a splatted vector of a
1666/// constant 1 integer (with no undefs).
1667/// Does not permit build vector implicit truncation.
1668bool isOneOrOneSplat(SDValue V);
1669
1670/// Return true if the value is a constant -1 integer or a splatted vector of a
1671/// constant -1 integer (with no undefs).
1672/// Does not permit build vector implicit truncation.
1673bool isAllOnesOrAllOnesSplat(SDValue V);
1674
1675class GlobalAddressSDNode : public SDNode {
1676 friend class SelectionDAG;
1677
1678 const GlobalValue *TheGlobal;
1679 int64_t Offset;
1680 unsigned TargetFlags;
1681
1682 GlobalAddressSDNode(unsigned Opc, unsigned Order, const DebugLoc &DL,
1683 const GlobalValue *GA, EVT VT, int64_t o,
1684 unsigned TF);
1685
1686public:
1687 const GlobalValue *getGlobal() const { return TheGlobal; }
1688 int64_t getOffset() const { return Offset; }
1689 unsigned getTargetFlags() const { return TargetFlags; }
1690 // Return the address space this GlobalAddress belongs to.
1691 unsigned getAddressSpace() const;
1692
1693 static bool classof(const SDNode *N) {
1694 return N->getOpcode() == ISD::GlobalAddress ||
1695 N->getOpcode() == ISD::TargetGlobalAddress ||
1696 N->getOpcode() == ISD::GlobalTLSAddress ||
1697 N->getOpcode() == ISD::TargetGlobalTLSAddress;
1698 }
1699};
1700
1701class FrameIndexSDNode : public SDNode {
1702 friend class SelectionDAG;
1703
1704 int FI;
1705
1706 FrameIndexSDNode(int fi, EVT VT, bool isTarg)
1707 : SDNode(isTarg ? ISD::TargetFrameIndex : ISD::FrameIndex,
1708 0, DebugLoc(), getSDVTList(VT)), FI(fi) {
1709 }
1710
1711public:
1712 int getIndex() const { return FI; }
1713
1714 static bool classof(const SDNode *N) {
1715 return N->getOpcode() == ISD::FrameIndex ||
1716 N->getOpcode() == ISD::TargetFrameIndex;
1717 }
1718};
1719
1720/// This SDNode is used for LIFETIME_START/LIFETIME_END values, which indicate
1721/// the offet and size that are started/ended in the underlying FrameIndex.
1722class LifetimeSDNode : public SDNode {
1723 friend class SelectionDAG;
1724 int64_t Size;
1725 int64_t Offset; // -1 if offset is unknown.
1726
1727 LifetimeSDNode(unsigned Opcode, unsigned Order, const DebugLoc &dl,
1728 SDVTList VTs, int64_t Size, int64_t Offset)
1729 : SDNode(Opcode, Order, dl, VTs), Size(Size), Offset(Offset) {}
1730public:
1731 int64_t getFrameIndex() const {
1732 return cast<FrameIndexSDNode>(getOperand(1))->getIndex();
1733 }
1734
1735 bool hasOffset() const { return Offset >= 0; }
1736 int64_t getOffset() const {
1737 assert(hasOffset() && "offset is unknown")((hasOffset() && "offset is unknown") ? static_cast<
void> (0) : __assert_fail ("hasOffset() && \"offset is unknown\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1737, __PRETTY_FUNCTION__))
;
1738 return Offset;
1739 }
1740 int64_t getSize() const {
1741 assert(hasOffset() && "offset is unknown")((hasOffset() && "offset is unknown") ? static_cast<
void> (0) : __assert_fail ("hasOffset() && \"offset is unknown\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1741, __PRETTY_FUNCTION__))
;
1742 return Size;
1743 }
1744
1745 // Methods to support isa and dyn_cast
1746 static bool classof(const SDNode *N) {
1747 return N->getOpcode() == ISD::LIFETIME_START ||
1748 N->getOpcode() == ISD::LIFETIME_END;
1749 }
1750};
1751
1752/// This SDNode is used for PSEUDO_PROBE values, which are the function guid and
1753/// the index of the basic block being probed. A pseudo probe serves as a place
1754/// holder and will be removed at the end of compilation. It does not have any
1755/// operand because we do not want the instruction selection to deal with any.
1756class PseudoProbeSDNode : public SDNode {
1757 friend class SelectionDAG;
1758 uint64_t Guid;
1759 uint64_t Index;
1760 uint32_t Attributes;
1761
1762 PseudoProbeSDNode(unsigned Opcode, unsigned Order, const DebugLoc &Dl,
1763 SDVTList VTs, uint64_t Guid, uint64_t Index, uint32_t Attr)
1764 : SDNode(Opcode, Order, Dl, VTs), Guid(Guid), Index(Index),
1765 Attributes(Attr) {}
1766
1767public:
1768 uint64_t getGuid() const { return Guid; }
1769 uint64_t getIndex() const { return Index; }
1770 uint32_t getAttributes() const { return Attributes; }
1771
1772 // Methods to support isa and dyn_cast
1773 static bool classof(const SDNode *N) {
1774 return N->getOpcode() == ISD::PSEUDO_PROBE;
1775 }
1776};
1777
1778class JumpTableSDNode : public SDNode {
1779 friend class SelectionDAG;
1780
1781 int JTI;
1782 unsigned TargetFlags;
1783
1784 JumpTableSDNode(int jti, EVT VT, bool isTarg, unsigned TF)
1785 : SDNode(isTarg ? ISD::TargetJumpTable : ISD::JumpTable,
1786 0, DebugLoc(), getSDVTList(VT)), JTI(jti), TargetFlags(TF) {
1787 }
1788
1789public:
1790 int getIndex() const { return JTI; }
1791 unsigned getTargetFlags() const { return TargetFlags; }
1792
1793 static bool classof(const SDNode *N) {
1794 return N->getOpcode() == ISD::JumpTable ||
1795 N->getOpcode() == ISD::TargetJumpTable;
1796 }
1797};
1798
1799class ConstantPoolSDNode : public SDNode {
1800 friend class SelectionDAG;
1801
1802 union {
1803 const Constant *ConstVal;
1804 MachineConstantPoolValue *MachineCPVal;
1805 } Val;
1806 int Offset; // It's a MachineConstantPoolValue if top bit is set.
1807 Align Alignment; // Minimum alignment requirement of CP.
1808 unsigned TargetFlags;
1809
1810 ConstantPoolSDNode(bool isTarget, const Constant *c, EVT VT, int o,
1811 Align Alignment, unsigned TF)
1812 : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, 0,
1813 DebugLoc(), getSDVTList(VT)),
1814 Offset(o), Alignment(Alignment), TargetFlags(TF) {
1815 assert(Offset >= 0 && "Offset is too large")((Offset >= 0 && "Offset is too large") ? static_cast
<void> (0) : __assert_fail ("Offset >= 0 && \"Offset is too large\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1815, __PRETTY_FUNCTION__))
;
1816 Val.ConstVal = c;
1817 }
1818
1819 ConstantPoolSDNode(bool isTarget, MachineConstantPoolValue *v, EVT VT, int o,
1820 Align Alignment, unsigned TF)
1821 : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, 0,
1822 DebugLoc(), getSDVTList(VT)),
1823 Offset(o), Alignment(Alignment), TargetFlags(TF) {
1824 assert(Offset >= 0 && "Offset is too large")((Offset >= 0 && "Offset is too large") ? static_cast
<void> (0) : __assert_fail ("Offset >= 0 && \"Offset is too large\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1824, __PRETTY_FUNCTION__))
;
1825 Val.MachineCPVal = v;
1826 Offset |= 1 << (sizeof(unsigned)*CHAR_BIT8-1);
1827 }
1828
1829public:
1830 bool isMachineConstantPoolEntry() const {
1831 return Offset < 0;
1832 }
1833
1834 const Constant *getConstVal() const {
1835 assert(!isMachineConstantPoolEntry() && "Wrong constantpool type")((!isMachineConstantPoolEntry() && "Wrong constantpool type"
) ? static_cast<void> (0) : __assert_fail ("!isMachineConstantPoolEntry() && \"Wrong constantpool type\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1835, __PRETTY_FUNCTION__))
;
1836 return Val.ConstVal;
1837 }
1838
1839 MachineConstantPoolValue *getMachineCPVal() const {
1840 assert(isMachineConstantPoolEntry() && "Wrong constantpool type")((isMachineConstantPoolEntry() && "Wrong constantpool type"
) ? static_cast<void> (0) : __assert_fail ("isMachineConstantPoolEntry() && \"Wrong constantpool type\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1840, __PRETTY_FUNCTION__))
;
1841 return Val.MachineCPVal;
1842 }
1843
1844 int getOffset() const {
1845 return Offset & ~(1 << (sizeof(unsigned)*CHAR_BIT8-1));
1846 }
1847
1848 // Return the alignment of this constant pool object, which is either 0 (for
1849 // default alignment) or the desired value.
1850 Align getAlign() const { return Alignment; }
1851 unsigned getTargetFlags() const { return TargetFlags; }
1852
1853 Type *getType() const;
1854
1855 static bool classof(const SDNode *N) {
1856 return N->getOpcode() == ISD::ConstantPool ||
1857 N->getOpcode() == ISD::TargetConstantPool;
1858 }
1859};
1860
1861/// Completely target-dependent object reference.
1862class TargetIndexSDNode : public SDNode {
1863 friend class SelectionDAG;
1864
1865 unsigned TargetFlags;
1866 int Index;
1867 int64_t Offset;
1868
1869public:
1870 TargetIndexSDNode(int Idx, EVT VT, int64_t Ofs, unsigned TF)
1871 : SDNode(ISD::TargetIndex, 0, DebugLoc(), getSDVTList(VT)),
1872 TargetFlags(TF), Index(Idx), Offset(Ofs) {}
1873
1874 unsigned getTargetFlags() const { return TargetFlags; }
1875 int getIndex() const { return Index; }
1876 int64_t getOffset() const { return Offset; }
1877
1878 static bool classof(const SDNode *N) {
1879 return N->getOpcode() == ISD::TargetIndex;
1880 }
1881};
1882
1883class BasicBlockSDNode : public SDNode {
1884 friend class SelectionDAG;
1885
1886 MachineBasicBlock *MBB;
1887
1888 /// Debug info is meaningful and potentially useful here, but we create
1889 /// blocks out of order when they're jumped to, which makes it a bit
1890 /// harder. Let's see if we need it first.
1891 explicit BasicBlockSDNode(MachineBasicBlock *mbb)
1892 : SDNode(ISD::BasicBlock, 0, DebugLoc(), getSDVTList(MVT::Other)), MBB(mbb)
1893 {}
1894
1895public:
1896 MachineBasicBlock *getBasicBlock() const { return MBB; }
1897
1898 static bool classof(const SDNode *N) {
1899 return N->getOpcode() == ISD::BasicBlock;
1900 }
1901};
1902
1903/// A "pseudo-class" with methods for operating on BUILD_VECTORs.
1904class BuildVectorSDNode : public SDNode {
1905public:
1906 // These are constructed as SDNodes and then cast to BuildVectorSDNodes.
1907 explicit BuildVectorSDNode() = delete;
1908
1909 /// Check if this is a constant splat, and if so, find the
1910 /// smallest element size that splats the vector. If MinSplatBits is
1911 /// nonzero, the element size must be at least that large. Note that the
1912 /// splat element may be the entire vector (i.e., a one element vector).
1913 /// Returns the splat element value in SplatValue. Any undefined bits in
1914 /// that value are zero, and the corresponding bits in the SplatUndef mask
1915 /// are set. The SplatBitSize value is set to the splat element size in
1916 /// bits. HasAnyUndefs is set to true if any bits in the vector are
1917 /// undefined. isBigEndian describes the endianness of the target.
1918 bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
1919 unsigned &SplatBitSize, bool &HasAnyUndefs,
1920 unsigned MinSplatBits = 0,
1921 bool isBigEndian = false) const;
1922
1923 /// Returns the demanded splatted value or a null value if this is not a
1924 /// splat.
1925 ///
1926 /// The DemandedElts mask indicates the elements that must be in the splat.
1927 /// If passed a non-null UndefElements bitvector, it will resize it to match
1928 /// the vector width and set the bits where elements are undef.
1929 SDValue getSplatValue(const APInt &DemandedElts,
1930 BitVector *UndefElements = nullptr) const;
1931
1932 /// Returns the splatted value or a null value if this is not a splat.
1933 ///
1934 /// If passed a non-null UndefElements bitvector, it will resize it to match
1935 /// the vector width and set the bits where elements are undef.
1936 SDValue getSplatValue(BitVector *UndefElements = nullptr) const;
1937
1938 /// Find the shortest repeating sequence of values in the build vector.
1939 ///
1940 /// e.g. { u, X, u, X, u, u, X, u } -> { X }
1941 /// { X, Y, u, Y, u, u, X, u } -> { X, Y }
1942 ///
1943 /// Currently this must be a power-of-2 build vector.
1944 /// The DemandedElts mask indicates the elements that must be present,
1945 /// undemanded elements in Sequence may be null (SDValue()). If passed a
1946 /// non-null UndefElements bitvector, it will resize it to match the original
1947 /// vector width and set the bits where elements are undef. If result is
1948 /// false, Sequence will be empty.
1949 bool getRepeatedSequence(const APInt &DemandedElts,
1950 SmallVectorImpl<SDValue> &Sequence,
1951 BitVector *UndefElements = nullptr) const;
1952
1953 /// Find the shortest repeating sequence of values in the build vector.
1954 ///
1955 /// e.g. { u, X, u, X, u, u, X, u } -> { X }
1956 /// { X, Y, u, Y, u, u, X, u } -> { X, Y }
1957 ///
1958 /// Currently this must be a power-of-2 build vector.
1959 /// If passed a non-null UndefElements bitvector, it will resize it to match
1960 /// the original vector width and set the bits where elements are undef.
1961 /// If result is false, Sequence will be empty.
1962 bool getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
1963 BitVector *UndefElements = nullptr) const;
1964
1965 /// Returns the demanded splatted constant or null if this is not a constant
1966 /// splat.
1967 ///
1968 /// The DemandedElts mask indicates the elements that must be in the splat.
1969 /// If passed a non-null UndefElements bitvector, it will resize it to match
1970 /// the vector width and set the bits where elements are undef.
1971 ConstantSDNode *
1972 getConstantSplatNode(const APInt &DemandedElts,
1973 BitVector *UndefElements = nullptr) const;
1974
1975 /// Returns the splatted constant or null if this is not a constant
1976 /// splat.
1977 ///
1978 /// If passed a non-null UndefElements bitvector, it will resize it to match
1979 /// the vector width and set the bits where elements are undef.
1980 ConstantSDNode *
1981 getConstantSplatNode(BitVector *UndefElements = nullptr) const;
1982
1983 /// Returns the demanded splatted constant FP or null if this is not a
1984 /// constant FP splat.
1985 ///
1986 /// The DemandedElts mask indicates the elements that must be in the splat.
1987 /// If passed a non-null UndefElements bitvector, it will resize it to match
1988 /// the vector width and set the bits where elements are undef.
1989 ConstantFPSDNode *
1990 getConstantFPSplatNode(const APInt &DemandedElts,
1991 BitVector *UndefElements = nullptr) const;
1992
1993 /// Returns the splatted constant FP or null if this is not a constant
1994 /// FP splat.
1995 ///
1996 /// If passed a non-null UndefElements bitvector, it will resize it to match
1997 /// the vector width and set the bits where elements are undef.
1998 ConstantFPSDNode *
1999 getConstantFPSplatNode(BitVector *UndefElements = nullptr) const;
2000
2001 /// If this is a constant FP splat and the splatted constant FP is an
2002 /// exact power or 2, return the log base 2 integer value. Otherwise,
2003 /// return -1.
2004 ///
2005 /// The BitWidth specifies the necessary bit precision.
2006 int32_t getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
2007 uint32_t BitWidth) const;
2008
2009 bool isConstant() const;
2010
2011 static bool classof(const SDNode *N) {
2012 return N->getOpcode() == ISD::BUILD_VECTOR;
2013 }
2014};
2015
2016/// An SDNode that holds an arbitrary LLVM IR Value. This is
2017/// used when the SelectionDAG needs to make a simple reference to something
2018/// in the LLVM IR representation.
2019///
2020class SrcValueSDNode : public SDNode {
2021 friend class SelectionDAG;
2022
2023 const Value *V;
2024
2025 /// Create a SrcValue for a general value.
2026 explicit SrcValueSDNode(const Value *v)
2027 : SDNode(ISD::SRCVALUE, 0, DebugLoc(), getSDVTList(MVT::Other)), V(v) {}
2028
2029public:
2030 /// Return the contained Value.
2031 const Value *getValue() const { return V; }
2032
2033 static bool classof(const SDNode *N) {
2034 return N->getOpcode() == ISD::SRCVALUE;
2035 }
2036};
2037
2038class MDNodeSDNode : public SDNode {
2039 friend class SelectionDAG;
2040
2041 const MDNode *MD;
2042
2043 explicit MDNodeSDNode(const MDNode *md)
2044 : SDNode(ISD::MDNODE_SDNODE, 0, DebugLoc(), getSDVTList(MVT::Other)), MD(md)
2045 {}
2046
2047public:
2048 const MDNode *getMD() const { return MD; }
2049
2050 static bool classof(const SDNode *N) {
2051 return N->getOpcode() == ISD::MDNODE_SDNODE;
2052 }
2053};
2054
2055class RegisterSDNode : public SDNode {
2056 friend class SelectionDAG;
2057
2058 Register Reg;
2059
2060 RegisterSDNode(Register reg, EVT VT)
2061 : SDNode(ISD::Register, 0, DebugLoc(), getSDVTList(VT)), Reg(reg) {}
2062
2063public:
2064 Register getReg() const { return Reg; }
2065
2066 static bool classof(const SDNode *N) {
2067 return N->getOpcode() == ISD::Register;
2068 }
2069};
2070
2071class RegisterMaskSDNode : public SDNode {
2072 friend class SelectionDAG;
2073
2074 // The memory for RegMask is not owned by the node.
2075 const uint32_t *RegMask;
2076
2077 RegisterMaskSDNode(const uint32_t *mask)
2078 : SDNode(ISD::RegisterMask, 0, DebugLoc(), getSDVTList(MVT::Untyped)),
2079 RegMask(mask) {}
2080
2081public:
2082 const uint32_t *getRegMask() const { return RegMask; }
2083
2084 static bool classof(const SDNode *N) {
2085 return N->getOpcode() == ISD::RegisterMask;
2086 }
2087};
2088
2089class BlockAddressSDNode : public SDNode {
2090 friend class SelectionDAG;
2091
2092 const BlockAddress *BA;
2093 int64_t Offset;
2094 unsigned TargetFlags;
2095
2096 BlockAddressSDNode(unsigned NodeTy, EVT VT, const BlockAddress *ba,
2097 int64_t o, unsigned Flags)
2098 : SDNode(NodeTy, 0, DebugLoc(), getSDVTList(VT)),
2099 BA(ba), Offset(o), TargetFlags(Flags) {}
2100
2101public:
2102 const BlockAddress *getBlockAddress() const { return BA; }
2103 int64_t getOffset() const { return Offset; }
2104 unsigned getTargetFlags() const { return TargetFlags; }
2105
2106 static bool classof(const SDNode *N) {
2107 return N->getOpcode() == ISD::BlockAddress ||
2108 N->getOpcode() == ISD::TargetBlockAddress;
2109 }
2110};
2111
2112class LabelSDNode : public SDNode {
2113 friend class SelectionDAG;
2114
2115 MCSymbol *Label;
2116
2117 LabelSDNode(unsigned Opcode, unsigned Order, const DebugLoc &dl, MCSymbol *L)
2118 : SDNode(Opcode, Order, dl, getSDVTList(MVT::Other)), Label(L) {
2119 assert(LabelSDNode::classof(this) && "not a label opcode")((LabelSDNode::classof(this) && "not a label opcode")
? static_cast<void> (0) : __assert_fail ("LabelSDNode::classof(this) && \"not a label opcode\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2119, __PRETTY_FUNCTION__))
;
2120 }
2121
2122public:
2123 MCSymbol *getLabel() const { return Label; }
2124
2125 static bool classof(const SDNode *N) {
2126 return N->getOpcode() == ISD::EH_LABEL ||
2127 N->getOpcode() == ISD::ANNOTATION_LABEL;
2128 }
2129};
2130
2131class ExternalSymbolSDNode : public SDNode {
2132 friend class SelectionDAG;
2133
2134 const char *Symbol;
2135 unsigned TargetFlags;
2136
2137 ExternalSymbolSDNode(bool isTarget, const char *Sym, unsigned TF, EVT VT)
2138 : SDNode(isTarget ? ISD::TargetExternalSymbol : ISD::ExternalSymbol, 0,
2139 DebugLoc(), getSDVTList(VT)),
2140 Symbol(Sym), TargetFlags(TF) {}
2141
2142public:
2143 const char *getSymbol() const { return Symbol; }
2144 unsigned getTargetFlags() const { return TargetFlags; }
2145
2146 static bool classof(const SDNode *N) {
2147 return N->getOpcode() == ISD::ExternalSymbol ||
2148 N->getOpcode() == ISD::TargetExternalSymbol;
2149 }
2150};
2151
2152class MCSymbolSDNode : public SDNode {
2153 friend class SelectionDAG;
2154
2155 MCSymbol *Symbol;
2156
2157 MCSymbolSDNode(MCSymbol *Symbol, EVT VT)
2158 : SDNode(ISD::MCSymbol, 0, DebugLoc(), getSDVTList(VT)), Symbol(Symbol) {}
2159
2160public:
2161 MCSymbol *getMCSymbol() const { return Symbol; }
2162
2163 static bool classof(const SDNode *N) {
2164 return N->getOpcode() == ISD::MCSymbol;
2165 }
2166};
2167
2168class CondCodeSDNode : public SDNode {
2169 friend class SelectionDAG;
2170
2171 ISD::CondCode Condition;
2172
2173 explicit CondCodeSDNode(ISD::CondCode Cond)
2174 : SDNode(ISD::CONDCODE, 0, DebugLoc(), getSDVTList(MVT::Other)),
2175 Condition(Cond) {}
2176
2177public:
2178 ISD::CondCode get() const { return Condition; }
2179
2180 static bool classof(const SDNode *N) {
2181 return N->getOpcode() == ISD::CONDCODE;
2182 }
2183};
2184
2185/// This class is used to represent EVT's, which are used
2186/// to parameterize some operations.
2187class VTSDNode : public SDNode {
2188 friend class SelectionDAG;
2189
2190 EVT ValueType;
2191
2192 explicit VTSDNode(EVT VT)
2193 : SDNode(ISD::VALUETYPE, 0, DebugLoc(), getSDVTList(MVT::Other)),
2194 ValueType(VT) {}
2195
2196public:
2197 EVT getVT() const { return ValueType; }
2198
2199 static bool classof(const SDNode *N) {
2200 return N->getOpcode() == ISD::VALUETYPE;
2201 }
2202};
2203
2204/// Base class for LoadSDNode and StoreSDNode
2205class LSBaseSDNode : public MemSDNode {
2206public:
2207 LSBaseSDNode(ISD::NodeType NodeTy, unsigned Order, const DebugLoc &dl,
2208 SDVTList VTs, ISD::MemIndexedMode AM, EVT MemVT,
2209 MachineMemOperand *MMO)
2210 : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2211 LSBaseSDNodeBits.AddressingMode = AM;
2212 assert(getAddressingMode() == AM && "Value truncated")((getAddressingMode() == AM && "Value truncated") ? static_cast
<void> (0) : __assert_fail ("getAddressingMode() == AM && \"Value truncated\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2212, __PRETTY_FUNCTION__))
;
2213 }
2214
2215 const SDValue &getOffset() const {
2216 return getOperand(getOpcode() == ISD::LOAD ? 2 : 3);
2217 }
2218
2219 /// Return the addressing mode for this load or store:
2220 /// unindexed, pre-inc, pre-dec, post-inc, or post-dec.
2221 ISD::MemIndexedMode getAddressingMode() const {
2222 return static_cast<ISD::MemIndexedMode>(LSBaseSDNodeBits.AddressingMode);
2223 }
2224
2225 /// Return true if this is a pre/post inc/dec load/store.
2226 bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; }
2227
2228 /// Return true if this is NOT a pre/post inc/dec load/store.
2229 bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; }
2230
2231 static bool classof(const SDNode *N) {
2232 return N->getOpcode() == ISD::LOAD ||
2233 N->getOpcode() == ISD::STORE;
2234 }
2235};
2236
2237/// This class is used to represent ISD::LOAD nodes.
2238class LoadSDNode : public LSBaseSDNode {
2239 friend class SelectionDAG;
2240
2241 LoadSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2242 ISD::MemIndexedMode AM, ISD::LoadExtType ETy, EVT MemVT,
2243 MachineMemOperand *MMO)
2244 : LSBaseSDNode(ISD::LOAD, Order, dl, VTs, AM, MemVT, MMO) {
2245 LoadSDNodeBits.ExtTy = ETy;
2246 assert(readMem() && "Load MachineMemOperand is not a load!")((readMem() && "Load MachineMemOperand is not a load!"
) ? static_cast<void> (0) : __assert_fail ("readMem() && \"Load MachineMemOperand is not a load!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2246, __PRETTY_FUNCTION__))
;
2247 assert(!writeMem() && "Load MachineMemOperand is a store!")((!writeMem() && "Load MachineMemOperand is a store!"
) ? static_cast<void> (0) : __assert_fail ("!writeMem() && \"Load MachineMemOperand is a store!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2247, __PRETTY_FUNCTION__))
;
2248 }
2249
2250public:
2251 /// Return whether this is a plain node,
2252 /// or one of the varieties of value-extending loads.
2253 ISD::LoadExtType getExtensionType() const {
2254 return static_cast<ISD::LoadExtType>(LoadSDNodeBits.ExtTy);
2255 }
2256
2257 const SDValue &getBasePtr() const { return getOperand(1); }
2258 const SDValue &getOffset() const { return getOperand(2); }
2259
2260 static bool classof(const SDNode *N) {
2261 return N->getOpcode() == ISD::LOAD;
2262 }
2263};
2264
2265/// This class is used to represent ISD::STORE nodes.
2266class StoreSDNode : public LSBaseSDNode {
2267 friend class SelectionDAG;
2268
2269 StoreSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2270 ISD::MemIndexedMode AM, bool isTrunc, EVT MemVT,
2271 MachineMemOperand *MMO)
2272 : LSBaseSDNode(ISD::STORE, Order, dl, VTs, AM, MemVT, MMO) {
2273 StoreSDNodeBits.IsTruncating = isTrunc;
2274 assert(!readMem() && "Store MachineMemOperand is a load!")((!readMem() && "Store MachineMemOperand is a load!")
? static_cast<void> (0) : __assert_fail ("!readMem() && \"Store MachineMemOperand is a load!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2274, __PRETTY_FUNCTION__))
;
2275 assert(writeMem() && "Store MachineMemOperand is not a store!")((writeMem() && "Store MachineMemOperand is not a store!"
) ? static_cast<void> (0) : __assert_fail ("writeMem() && \"Store MachineMemOperand is not a store!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2275, __PRETTY_FUNCTION__))
;
2276 }
2277
2278public:
2279 /// Return true if the op does a truncation before store.
2280 /// For integers this is the same as doing a TRUNCATE and storing the result.
2281 /// For floats, it is the same as doing an FP_ROUND and storing the result.
2282 bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2283 void setTruncatingStore(bool Truncating) {
2284 StoreSDNodeBits.IsTruncating = Truncating;
2285 }
2286
2287 const SDValue &getValue() const { return getOperand(1); }
2288 const SDValue &getBasePtr() const { return getOperand(2); }
2289 const SDValue &getOffset() const { return getOperand(3); }
2290
2291 static bool classof(const SDNode *N) {
2292 return N->getOpcode() == ISD::STORE;
2293 }
2294};
2295
2296/// This base class is used to represent MLOAD and MSTORE nodes
2297class MaskedLoadStoreSDNode : public MemSDNode {
2298public:
2299 friend class SelectionDAG;
2300
2301 MaskedLoadStoreSDNode(ISD::NodeType NodeTy, unsigned Order,
2302 const DebugLoc &dl, SDVTList VTs,
2303 ISD::MemIndexedMode AM, EVT MemVT,
2304 MachineMemOperand *MMO)
2305 : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2306 LSBaseSDNodeBits.AddressingMode = AM;
2307 assert(getAddressingMode() == AM && "Value truncated")((getAddressingMode() == AM && "Value truncated") ? static_cast
<void> (0) : __assert_fail ("getAddressingMode() == AM && \"Value truncated\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2307, __PRETTY_FUNCTION__))
;
2308 }
2309
2310 // MaskedLoadSDNode (Chain, ptr, offset, mask, passthru)
2311 // MaskedStoreSDNode (Chain, data, ptr, offset, mask)
2312 // Mask is a vector of i1 elements
2313 const SDValue &getOffset() const {
2314 return getOperand(getOpcode() == ISD::MLOAD ? 2 : 3);
2315 }
2316 const SDValue &getMask() const {
2317 return getOperand(getOpcode() == ISD::MLOAD ? 3 : 4);
2318 }
2319
2320 /// Return the addressing mode for this load or store:
2321 /// unindexed, pre-inc, pre-dec, post-inc, or post-dec.
2322 ISD::MemIndexedMode getAddressingMode() const {
2323 return static_cast<ISD::MemIndexedMode>(LSBaseSDNodeBits.AddressingMode);
2324 }
2325
2326 /// Return true if this is a pre/post inc/dec load/store.
2327 bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; }
2328
2329 /// Return true if this is NOT a pre/post inc/dec load/store.
2330 bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; }
2331
2332 static bool classof(const SDNode *N) {
2333 return N->getOpcode() == ISD::MLOAD ||
2334 N->getOpcode() == ISD::MSTORE;
2335 }
2336};
2337
2338/// This class is used to represent an MLOAD node
2339class MaskedLoadSDNode : public MaskedLoadStoreSDNode {
2340public:
2341 friend class SelectionDAG;
2342
2343 MaskedLoadSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2344 ISD::MemIndexedMode AM, ISD::LoadExtType ETy,
2345 bool IsExpanding, EVT MemVT, MachineMemOperand *MMO)
2346 : MaskedLoadStoreSDNode(ISD::MLOAD, Order, dl, VTs, AM, MemVT, MMO) {
2347 LoadSDNodeBits.ExtTy = ETy;
2348 LoadSDNodeBits.IsExpanding = IsExpanding;
2349 }
2350
2351 ISD::LoadExtType getExtensionType() const {
2352 return static_cast<ISD::LoadExtType>(LoadSDNodeBits.ExtTy);
2353 }
2354
2355 const SDValue &getBasePtr() const { return getOperand(1); }
2356 const SDValue &getOffset() const { return getOperand(2); }
2357 const SDValue &getMask() const { return getOperand(3); }
2358 const SDValue &getPassThru() const { return getOperand(4); }
2359
2360 static bool classof(const SDNode *N) {
2361 return N->getOpcode() == ISD::MLOAD;
2362 }
2363
2364 bool isExpandingLoad() const { return LoadSDNodeBits.IsExpanding; }
2365};
2366
2367/// This class is used to represent an MSTORE node
2368class MaskedStoreSDNode : public MaskedLoadStoreSDNode {
2369public:
2370 friend class SelectionDAG;
2371
2372 MaskedStoreSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2373 ISD::MemIndexedMode AM, bool isTrunc, bool isCompressing,
2374 EVT MemVT, MachineMemOperand *MMO)
2375 : MaskedLoadStoreSDNode(ISD::MSTORE, Order, dl, VTs, AM, MemVT, MMO) {
2376 StoreSDNodeBits.IsTruncating = isTrunc;
2377 StoreSDNodeBits.IsCompressing = isCompressing;
2378 }
2379
2380 /// Return true if the op does a truncation before store.
2381 /// For integers this is the same as doing a TRUNCATE and storing the result.
2382 /// For floats, it is the same as doing an FP_ROUND and storing the result.
2383 bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2384
2385 /// Returns true if the op does a compression to the vector before storing.
2386 /// The node contiguously stores the active elements (integers or floats)
2387 /// in src (those with their respective bit set in writemask k) to unaligned
2388 /// memory at base_addr.
2389 bool isCompressingStore() const { return StoreSDNodeBits.IsCompressing; }
2390
2391 const SDValue &getValue() const { return getOperand(1); }
2392 const SDValue &getBasePtr() const { return getOperand(2); }
2393 const SDValue &getOffset() const { return getOperand(3); }
2394 const SDValue &getMask() const { return getOperand(4); }
2395
2396 static bool classof(const SDNode *N) {
2397 return N->getOpcode() == ISD::MSTORE;
2398 }
2399};
2400
2401/// This is a base class used to represent
2402/// MGATHER and MSCATTER nodes
2403///
2404class MaskedGatherScatterSDNode : public MemSDNode {
2405public:
2406 friend class SelectionDAG;
2407
2408 MaskedGatherScatterSDNode(ISD::NodeType NodeTy, unsigned Order,
2409 const DebugLoc &dl, SDVTList VTs, EVT MemVT,
2410 MachineMemOperand *MMO, ISD::MemIndexType IndexType)
2411 : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2412 LSBaseSDNodeBits.AddressingMode = IndexType;
2413 assert(getIndexType() == IndexType && "Value truncated")((getIndexType() == IndexType && "Value truncated") ?
static_cast<void> (0) : __assert_fail ("getIndexType() == IndexType && \"Value truncated\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2413, __PRETTY_FUNCTION__))
;
2414 }
2415
2416 /// How is Index applied to BasePtr when computing addresses.
2417 ISD::MemIndexType getIndexType() const {
2418 return static_cast<ISD::MemIndexType>(LSBaseSDNodeBits.AddressingMode);
2419 }
2420 void setIndexType(ISD::MemIndexType IndexType) {
2421 LSBaseSDNodeBits.AddressingMode = IndexType;
2422 }
2423 bool isIndexScaled() const {
2424 return (getIndexType() == ISD::SIGNED_SCALED) ||
2425 (getIndexType() == ISD::UNSIGNED_SCALED);
2426 }
2427 bool isIndexSigned() const {
2428 return (getIndexType() == ISD::SIGNED_SCALED) ||
2429 (getIndexType() == ISD::SIGNED_UNSCALED);
2430 }
2431
2432 // In the both nodes address is Op1, mask is Op2:
2433 // MaskedGatherSDNode (Chain, passthru, mask, base, index, scale)
2434 // MaskedScatterSDNode (Chain, value, mask, base, index, scale)
2435 // Mask is a vector of i1 elements
2436 const SDValue &getBasePtr() const { return getOperand(3); }
2437 const SDValue &getIndex() const { return getOperand(4); }
2438 const SDValue &getMask() const { return getOperand(2); }
2439 const SDValue &getScale() const { return getOperand(5); }
2440
2441 static bool classof(const SDNode *N) {
2442 return N->getOpcode() == ISD::MGATHER ||
2443 N->getOpcode() == ISD::MSCATTER;
2444 }
2445};
2446
2447/// This class is used to represent an MGATHER node
2448///
2449class MaskedGatherSDNode : public MaskedGatherScatterSDNode {
2450public:
2451 friend class SelectionDAG;
2452
2453 MaskedGatherSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2454 EVT MemVT, MachineMemOperand *MMO,
2455 ISD::MemIndexType IndexType)
2456 : MaskedGatherScatterSDNode(ISD::MGATHER, Order, dl, VTs, MemVT, MMO,
2457 IndexType) {}
2458
2459 const SDValue &getPassThru() const { return getOperand(1); }
2460
2461 static bool classof(const SDNode *N) {
2462 return N->getOpcode() == ISD::MGATHER;
2463 }
2464};
2465
2466/// This class is used to represent an MSCATTER node
2467///
2468class MaskedScatterSDNode : public MaskedGatherScatterSDNode {
2469public:
2470 friend class SelectionDAG;
2471
2472 MaskedScatterSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2473 EVT MemVT, MachineMemOperand *MMO,
2474 ISD::MemIndexType IndexType, bool IsTrunc)
2475 : MaskedGatherScatterSDNode(ISD::MSCATTER, Order, dl, VTs, MemVT, MMO,
2476 IndexType) {
2477 StoreSDNodeBits.IsTruncating = IsTrunc;
2478 }
2479
2480 /// Return true if the op does a truncation before store.
2481 /// For integers this is the same as doing a TRUNCATE and storing the result.
2482 /// For floats, it is the same as doing an FP_ROUND and storing the result.
2483 bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2484
2485 const SDValue &getValue() const { return getOperand(1); }
2486
2487 static bool classof(const SDNode *N) {
2488 return N->getOpcode() == ISD::MSCATTER;
2489 }
2490};
2491
2492/// An SDNode that represents everything that will be needed
2493/// to construct a MachineInstr. These nodes are created during the
2494/// instruction selection proper phase.
2495///
2496/// Note that the only supported way to set the `memoperands` is by calling the
2497/// `SelectionDAG::setNodeMemRefs` function as the memory management happens
2498/// inside the DAG rather than in the node.
2499class MachineSDNode : public SDNode {
2500private:
2501 friend class SelectionDAG;
2502
2503 MachineSDNode(unsigned Opc, unsigned Order, const DebugLoc &DL, SDVTList VTs)
2504 : SDNode(Opc, Order, DL, VTs) {}
2505
2506 // We use a pointer union between a single `MachineMemOperand` pointer and
2507 // a pointer to an array of `MachineMemOperand` pointers. This is null when
2508 // the number of these is zero, the single pointer variant used when the
2509 // number is one, and the array is used for larger numbers.
2510 //
2511 // The array is allocated via the `SelectionDAG`'s allocator and so will
2512 // always live until the DAG is cleaned up and doesn't require ownership here.
2513 //
2514 // We can't use something simpler like `TinyPtrVector` here because `SDNode`
2515 // subclasses aren't managed in a conforming C++ manner. See the comments on
2516 // `SelectionDAG::MorphNodeTo` which details what all goes on, but the
2517 // constraint here is that these don't manage memory with their constructor or
2518 // destructor and can be initialized to a good state even if they start off
2519 // uninitialized.
2520 PointerUnion<MachineMemOperand *, MachineMemOperand **> MemRefs = {};
2521
2522 // Note that this could be folded into the above `MemRefs` member if doing so
2523 // is advantageous at some point. We don't need to store this in most cases.
2524 // However, at the moment this doesn't appear to make the allocation any
2525 // smaller and makes the code somewhat simpler to read.
2526 int NumMemRefs = 0;
2527
2528public:
2529 using mmo_iterator = ArrayRef<MachineMemOperand *>::const_iterator;
2530
2531 ArrayRef<MachineMemOperand *> memoperands() const {
2532 // Special case the common cases.
2533 if (NumMemRefs == 0)
2534 return {};
2535 if (NumMemRefs == 1)
2536 return makeArrayRef(MemRefs.getAddrOfPtr1(), 1);
2537
2538 // Otherwise we have an actual array.
2539 return makeArrayRef(MemRefs.get<MachineMemOperand **>(), NumMemRefs);
2540 }
2541 mmo_iterator memoperands_begin() const { return memoperands().begin(); }
2542 mmo_iterator memoperands_end() const { return memoperands().end(); }
2543 bool memoperands_empty() const { return memoperands().empty(); }
2544
2545 /// Clear out the memory reference descriptor list.
2546 void clearMemRefs() {
2547 MemRefs = nullptr;
2548 NumMemRefs = 0;
2549 }
2550
2551 static bool classof(const SDNode *N) {
2552 return N->isMachineOpcode();
2553 }
2554};
2555
2556/// An SDNode that records if a register contains a value that is guaranteed to
2557/// be aligned accordingly.
2558class AssertAlignSDNode : public SDNode {
2559 Align Alignment;
2560
2561public:
2562 AssertAlignSDNode(unsigned Order, const DebugLoc &DL, EVT VT, Align A)
2563 : SDNode(ISD::AssertAlign, Order, DL, getSDVTList(VT)), Alignment(A) {}
2564
2565 Align getAlign() const { return Alignment; }
2566
2567 static bool classof(const SDNode *N) {
2568 return N->getOpcode() == ISD::AssertAlign;
2569 }
2570};
2571
2572class SDNodeIterator : public std::iterator<std::forward_iterator_tag,
2573 SDNode, ptrdiff_t> {
2574 const SDNode *Node;
2575 unsigned Operand;
2576
2577 SDNodeIterator(const SDNode *N, unsigned Op) : Node(N), Operand(Op) {}
2578
2579public:
2580 bool operator==(const SDNodeIterator& x) const {
2581 return Operand == x.Operand;
2582 }
2583 bool operator!=(const SDNodeIterator& x) const { return !operator==(x); }
2584
2585 pointer operator*() const {
2586 return Node->getOperand(Operand).getNode();
2587 }
2588 pointer operator->() const { return operator*(); }
2589
2590 SDNodeIterator& operator++() { // Preincrement
2591 ++Operand;
2592 return *this;
2593 }
2594 SDNodeIterator operator++(int) { // Postincrement
2595 SDNodeIterator tmp = *this; ++*this; return tmp;
2596 }
2597 size_t operator-(SDNodeIterator Other) const {
2598 assert(Node == Other.Node &&((Node == Other.Node && "Cannot compare iterators of two different nodes!"
) ? static_cast<void> (0) : __assert_fail ("Node == Other.Node && \"Cannot compare iterators of two different nodes!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2599, __PRETTY_FUNCTION__))
2599 "Cannot compare iterators of two different nodes!")((Node == Other.Node && "Cannot compare iterators of two different nodes!"
) ? static_cast<void> (0) : __assert_fail ("Node == Other.Node && \"Cannot compare iterators of two different nodes!\""
, "/build/llvm-toolchain-snapshot-12~++20201129111111+e987fbdd85d/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2599, __PRETTY_FUNCTION__))
;
2600 return Operand - Other.Operand;
2601 }
2602
2603 static SDNodeIterator begin(const SDNode *N) { return SDNodeIterator(N, 0); }
2604 static SDNodeIterator end (const SDNode *N) {
2605 return SDNodeIterator(N, N->getNumOperands());
2606 }
2607
2608 unsigned getOperand() const { return Operand; }
2609 const SDNode *getNode() const { return Node; }
2610};
2611
2612template <> struct GraphTraits<SDNode*> {
2613 using NodeRef = SDNode *;
2614 using ChildIteratorType = SDNodeIterator;
2615
2616 static NodeRef getEntryNode(SDNode *N) { return N; }
2617
2618 static ChildIteratorType child_begin(NodeRef N) {
2619 return SDNodeIterator::begin(N);
2620 }
2621
2622 static ChildIteratorType child_end(NodeRef N) {
2623 return SDNodeIterator::end(N);
2624 }
2625};
2626
2627/// A representation of the largest SDNode, for use in sizeof().
2628///
2629/// This needs to be a union because the largest node differs on 32 bit systems
2630/// with 4 and 8 byte pointer alignment, respectively.
2631using LargestSDNode = AlignedCharArrayUnion<AtomicSDNode, TargetIndexSDNode,
2632 BlockAddressSDNode,
2633 GlobalAddressSDNode,
2634 PseudoProbeSDNode>;
2635
2636/// The SDNode class with the greatest alignment requirement.
2637using MostAlignedSDNode = GlobalAddressSDNode;
2638
2639namespace ISD {
2640
2641 /// Returns true if the specified node is a non-extending and unindexed load.
2642 inline bool isNormalLoad(const SDNode *N) {
2643 const LoadSDNode *Ld = dyn_cast<LoadSDNode>(N);
2644 return Ld && Ld->getExtensionType() == ISD::NON_EXTLOAD &&
2645 Ld->getAddressingMode() == ISD::UNINDEXED;
2646 }
2647
2648 /// Returns true if the specified node is a non-extending load.
2649 inline bool isNON_EXTLoad(const SDNode *N) {
2650 return isa<LoadSDNode>(N) &&
2651 cast<LoadSDNode>(N)->getExtensionType() == ISD::NON_EXTLOAD;
2652 }
2653
2654 /// Returns true if the specified node is a EXTLOAD.
2655 inline bool isEXTLoad(const SDNode *N) {
2656 return isa<LoadSDNode>(N) &&
2657 cast<LoadSDNode>(N)->getExtensionType() == ISD::EXTLOAD;
2658 }
2659
2660 /// Returns true if the specified node is a SEXTLOAD.
2661 inline bool isSEXTLoad(const SDNode *N) {
2662 return isa<LoadSDNode>(N) &&
2663 cast<LoadSDNode>(N)->getExtensionType() == ISD::SEXTLOAD;
2664 }
2665
2666 /// Returns true if the specified node is a ZEXTLOAD.
2667 inline bool isZEXTLoad(const SDNode *N) {
2668 return isa<LoadSDNode>(N) &&
2669 cast<LoadSDNode>(N)->getExtensionType() == ISD::ZEXTLOAD;
2670 }
2671
2672 /// Returns true if the specified node is an unindexed load.
2673 inline bool isUNINDEXEDLoad(const SDNode *N) {
2674 return isa<LoadSDNode>(N) &&
2675 cast<LoadSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
2676 }
2677
2678 /// Returns true if the specified node is a non-truncating
2679 /// and unindexed store.
2680 inline bool isNormalStore(const SDNode *N) {
2681 const StoreSDNode *St = dyn_cast<StoreSDNode>(N);
2682 return St && !St->isTruncatingStore() &&
2683 St->getAddressingMode() == ISD::UNINDEXED;
2684 }
2685
2686 /// Returns true if the specified node is a non-truncating store.
2687 inline bool isNON_TRUNCStore(const SDNode *N) {
2688 return isa<StoreSDNode>(N) && !cast<StoreSDNode>(N)->isTruncatingStore();
2689 }
2690
2691 /// Returns true if the specified node is a truncating store.
2692 inline bool isTRUNCStore(const SDNode *N) {
2693 return isa<StoreSDNode>(N) && cast<StoreSDNode>(N)->isTruncatingStore();
2694 }
2695
2696 /// Returns true if the specified node is an unindexed store.
2697 inline bool isUNINDEXEDStore(const SDNode *N) {
2698 return isa<StoreSDNode>(N) &&
2699 cast<StoreSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
2700 }
2701
2702 /// Attempt to match a unary predicate against a scalar/splat constant or
2703 /// every element of a constant BUILD_VECTOR.
2704 /// If AllowUndef is true, then UNDEF elements will pass nullptr to Match.
2705 bool matchUnaryPredicate(SDValue Op,
2706 std::function<bool(ConstantSDNode *)> Match,
2707 bool AllowUndefs = false);
2708
2709 /// Attempt to match a binary predicate against a pair of scalar/splat
2710 /// constants or every element of a pair of constant BUILD_VECTORs.
2711 /// If AllowUndef is true, then UNDEF elements will pass nullptr to Match.
2712 /// If AllowTypeMismatch is true then RetType + ArgTypes don't need to match.
2713 bool matchBinaryPredicate(
2714 SDValue LHS, SDValue RHS,
2715 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
2716 bool AllowUndefs = false, bool AllowTypeMismatch = false);
2717
2718 /// Returns true if the specified value is the overflow result from one
2719 /// of the overflow intrinsic nodes.
2720 inline bool isOverflowIntrOpRes(SDValue Op) {
2721 unsigned Opc = Op.getOpcode();
2722 return (Op.getResNo() == 1 &&
2723 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2724 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2725 }
2726
2727} // end namespace ISD
2728
2729} // end namespace llvm
2730
2731#endif // LLVM_CODEGEN_SELECTIONDAGNODES_H