Bug Summary

File:llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp
Warning:line 6881, column 36
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 SelectionDAG.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 -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/lib/CodeGen/SelectionDAG -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/lib/CodeGen/SelectionDAG -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/lib/CodeGen/SelectionDAG -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -D NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/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-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/lib/CodeGen/SelectionDAG -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -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 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp

1//===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
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 implements the SelectionDAG class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/CodeGen/SelectionDAG.h"
14#include "SDNodeDbgValue.h"
15#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/APSInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/BitVector.h"
20#include "llvm/ADT/FoldingSet.h"
21#include "llvm/ADT/None.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/SmallPtrSet.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/Triple.h"
26#include "llvm/ADT/Twine.h"
27#include "llvm/Analysis/BlockFrequencyInfo.h"
28#include "llvm/Analysis/MemoryLocation.h"
29#include "llvm/Analysis/ProfileSummaryInfo.h"
30#include "llvm/Analysis/ValueTracking.h"
31#include "llvm/CodeGen/FunctionLoweringInfo.h"
32#include "llvm/CodeGen/ISDOpcodes.h"
33#include "llvm/CodeGen/MachineBasicBlock.h"
34#include "llvm/CodeGen/MachineConstantPool.h"
35#include "llvm/CodeGen/MachineFrameInfo.h"
36#include "llvm/CodeGen/MachineFunction.h"
37#include "llvm/CodeGen/MachineMemOperand.h"
38#include "llvm/CodeGen/RuntimeLibcalls.h"
39#include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
40#include "llvm/CodeGen/SelectionDAGNodes.h"
41#include "llvm/CodeGen/SelectionDAGTargetInfo.h"
42#include "llvm/CodeGen/TargetFrameLowering.h"
43#include "llvm/CodeGen/TargetLowering.h"
44#include "llvm/CodeGen/TargetRegisterInfo.h"
45#include "llvm/CodeGen/TargetSubtargetInfo.h"
46#include "llvm/CodeGen/ValueTypes.h"
47#include "llvm/IR/Constant.h"
48#include "llvm/IR/Constants.h"
49#include "llvm/IR/DataLayout.h"
50#include "llvm/IR/DebugInfoMetadata.h"
51#include "llvm/IR/DebugLoc.h"
52#include "llvm/IR/DerivedTypes.h"
53#include "llvm/IR/Function.h"
54#include "llvm/IR/GlobalValue.h"
55#include "llvm/IR/Metadata.h"
56#include "llvm/IR/Type.h"
57#include "llvm/IR/Value.h"
58#include "llvm/Support/Casting.h"
59#include "llvm/Support/CodeGen.h"
60#include "llvm/Support/Compiler.h"
61#include "llvm/Support/Debug.h"
62#include "llvm/Support/ErrorHandling.h"
63#include "llvm/Support/KnownBits.h"
64#include "llvm/Support/MachineValueType.h"
65#include "llvm/Support/ManagedStatic.h"
66#include "llvm/Support/MathExtras.h"
67#include "llvm/Support/Mutex.h"
68#include "llvm/Support/raw_ostream.h"
69#include "llvm/Target/TargetMachine.h"
70#include "llvm/Target/TargetOptions.h"
71#include "llvm/Transforms/Utils/SizeOpts.h"
72#include <algorithm>
73#include <cassert>
74#include <cstdint>
75#include <cstdlib>
76#include <limits>
77#include <set>
78#include <string>
79#include <utility>
80#include <vector>
81
82using namespace llvm;
83
84/// makeVTList - Return an instance of the SDVTList struct initialized with the
85/// specified members.
86static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
87 SDVTList Res = {VTs, NumVTs};
88 return Res;
89}
90
91// Default null implementations of the callbacks.
92void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
93void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
94void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
95
96void SelectionDAG::DAGNodeDeletedListener::anchor() {}
97
98#define DEBUG_TYPE"selectiondag" "selectiondag"
99
100static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
101 cl::Hidden, cl::init(true),
102 cl::desc("Gang up loads and stores generated by inlining of memcpy"));
103
104static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
105 cl::desc("Number limit for gluing ld/st of memcpy."),
106 cl::Hidden, cl::init(0));
107
108static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
109 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G);)do { } while (false);
110}
111
112//===----------------------------------------------------------------------===//
113// ConstantFPSDNode Class
114//===----------------------------------------------------------------------===//
115
116/// isExactlyValue - We don't rely on operator== working on double values, as
117/// it returns true for things that are clearly not equal, like -0.0 and 0.0.
118/// As such, this method can be used to do an exact bit-for-bit comparison of
119/// two floating point values.
120bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
121 return getValueAPF().bitwiseIsEqual(V);
122}
123
124bool ConstantFPSDNode::isValueValidForType(EVT VT,
125 const APFloat& Val) {
126 assert(VT.isFloatingPoint() && "Can only convert between FP types")(static_cast<void> (0));
127
128 // convert modifies in place, so make a copy.
129 APFloat Val2 = APFloat(Val);
130 bool losesInfo;
131 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
132 APFloat::rmNearestTiesToEven,
133 &losesInfo);
134 return !losesInfo;
135}
136
137//===----------------------------------------------------------------------===//
138// ISD Namespace
139//===----------------------------------------------------------------------===//
140
141bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
142 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
143 unsigned EltSize =
144 N->getValueType(0).getVectorElementType().getSizeInBits();
145 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
146 SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize);
147 return true;
148 }
149 if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
150 SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize);
151 return true;
152 }
153 }
154
155 auto *BV = dyn_cast<BuildVectorSDNode>(N);
156 if (!BV)
157 return false;
158
159 APInt SplatUndef;
160 unsigned SplatBitSize;
161 bool HasUndefs;
162 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
163 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
164 EltSize) &&
165 EltSize == SplatBitSize;
166}
167
168// FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
169// specializations of the more general isConstantSplatVector()?
170
171bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
172 // Look through a bit convert.
173 while (N->getOpcode() == ISD::BITCAST)
174 N = N->getOperand(0).getNode();
175
176 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
177 APInt SplatVal;
178 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnesValue();
179 }
180
181 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
182
183 unsigned i = 0, e = N->getNumOperands();
184
185 // Skip over all of the undef values.
186 while (i != e && N->getOperand(i).isUndef())
187 ++i;
188
189 // Do not accept an all-undef vector.
190 if (i == e) return false;
191
192 // Do not accept build_vectors that aren't all constants or which have non-~0
193 // elements. We have to be a bit careful here, as the type of the constant
194 // may not be the same as the type of the vector elements due to type
195 // legalization (the elements are promoted to a legal type for the target and
196 // a vector of a type may be legal when the base element type is not).
197 // We only want to check enough bits to cover the vector elements, because
198 // we care if the resultant vector is all ones, not whether the individual
199 // constants are.
200 SDValue NotZero = N->getOperand(i);
201 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
202 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
203 if (CN->getAPIntValue().countTrailingOnes() < EltSize)
204 return false;
205 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
206 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
207 return false;
208 } else
209 return false;
210
211 // Okay, we have at least one ~0 value, check to see if the rest match or are
212 // undefs. Even with the above element type twiddling, this should be OK, as
213 // the same type legalization should have applied to all the elements.
214 for (++i; i != e; ++i)
215 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
216 return false;
217 return true;
218}
219
220bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
221 // Look through a bit convert.
222 while (N->getOpcode() == ISD::BITCAST)
223 N = N->getOperand(0).getNode();
224
225 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
226 APInt SplatVal;
227 return isConstantSplatVector(N, SplatVal) && SplatVal.isNullValue();
228 }
229
230 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
231
232 bool IsAllUndef = true;
233 for (const SDValue &Op : N->op_values()) {
234 if (Op.isUndef())
235 continue;
236 IsAllUndef = false;
237 // Do not accept build_vectors that aren't all constants or which have non-0
238 // elements. We have to be a bit careful here, as the type of the constant
239 // may not be the same as the type of the vector elements due to type
240 // legalization (the elements are promoted to a legal type for the target
241 // and a vector of a type may be legal when the base element type is not).
242 // We only want to check enough bits to cover the vector elements, because
243 // we care if the resultant vector is all zeros, not whether the individual
244 // constants are.
245 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
246 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
247 if (CN->getAPIntValue().countTrailingZeros() < EltSize)
248 return false;
249 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
250 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
251 return false;
252 } else
253 return false;
254 }
255
256 // Do not accept an all-undef vector.
257 if (IsAllUndef)
258 return false;
259 return true;
260}
261
262bool ISD::isBuildVectorAllOnes(const SDNode *N) {
263 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
264}
265
266bool ISD::isBuildVectorAllZeros(const SDNode *N) {
267 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
268}
269
270bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
271 if (N->getOpcode() != ISD::BUILD_VECTOR)
272 return false;
273
274 for (const SDValue &Op : N->op_values()) {
275 if (Op.isUndef())
276 continue;
277 if (!isa<ConstantSDNode>(Op))
278 return false;
279 }
280 return true;
281}
282
283bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
284 if (N->getOpcode() != ISD::BUILD_VECTOR)
285 return false;
286
287 for (const SDValue &Op : N->op_values()) {
288 if (Op.isUndef())
289 continue;
290 if (!isa<ConstantFPSDNode>(Op))
291 return false;
292 }
293 return true;
294}
295
296bool ISD::allOperandsUndef(const SDNode *N) {
297 // Return false if the node has no operands.
298 // This is "logically inconsistent" with the definition of "all" but
299 // is probably the desired behavior.
300 if (N->getNumOperands() == 0)
301 return false;
302 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
303}
304
305bool ISD::matchUnaryPredicate(SDValue Op,
306 std::function<bool(ConstantSDNode *)> Match,
307 bool AllowUndefs) {
308 // FIXME: Add support for scalar UNDEF cases?
309 if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
310 return Match(Cst);
311
312 // FIXME: Add support for vector UNDEF cases?
313 if (ISD::BUILD_VECTOR != Op.getOpcode() &&
314 ISD::SPLAT_VECTOR != Op.getOpcode())
315 return false;
316
317 EVT SVT = Op.getValueType().getScalarType();
318 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
319 if (AllowUndefs && Op.getOperand(i).isUndef()) {
320 if (!Match(nullptr))
321 return false;
322 continue;
323 }
324
325 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
326 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
327 return false;
328 }
329 return true;
330}
331
332bool ISD::matchBinaryPredicate(
333 SDValue LHS, SDValue RHS,
334 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
335 bool AllowUndefs, bool AllowTypeMismatch) {
336 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
337 return false;
338
339 // TODO: Add support for scalar UNDEF cases?
340 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
341 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
342 return Match(LHSCst, RHSCst);
343
344 // TODO: Add support for vector UNDEF cases?
345 if (LHS.getOpcode() != RHS.getOpcode() ||
346 (LHS.getOpcode() != ISD::BUILD_VECTOR &&
347 LHS.getOpcode() != ISD::SPLAT_VECTOR))
348 return false;
349
350 EVT SVT = LHS.getValueType().getScalarType();
351 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
352 SDValue LHSOp = LHS.getOperand(i);
353 SDValue RHSOp = RHS.getOperand(i);
354 bool LHSUndef = AllowUndefs && LHSOp.isUndef();
355 bool RHSUndef = AllowUndefs && RHSOp.isUndef();
356 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
357 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
358 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
359 return false;
360 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
361 LHSOp.getValueType() != RHSOp.getValueType()))
362 return false;
363 if (!Match(LHSCst, RHSCst))
364 return false;
365 }
366 return true;
367}
368
369ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
370 switch (VecReduceOpcode) {
371 default:
372 llvm_unreachable("Expected VECREDUCE opcode")__builtin_unreachable();
373 case ISD::VECREDUCE_FADD:
374 case ISD::VECREDUCE_SEQ_FADD:
375 return ISD::FADD;
376 case ISD::VECREDUCE_FMUL:
377 case ISD::VECREDUCE_SEQ_FMUL:
378 return ISD::FMUL;
379 case ISD::VECREDUCE_ADD:
380 return ISD::ADD;
381 case ISD::VECREDUCE_MUL:
382 return ISD::MUL;
383 case ISD::VECREDUCE_AND:
384 return ISD::AND;
385 case ISD::VECREDUCE_OR:
386 return ISD::OR;
387 case ISD::VECREDUCE_XOR:
388 return ISD::XOR;
389 case ISD::VECREDUCE_SMAX:
390 return ISD::SMAX;
391 case ISD::VECREDUCE_SMIN:
392 return ISD::SMIN;
393 case ISD::VECREDUCE_UMAX:
394 return ISD::UMAX;
395 case ISD::VECREDUCE_UMIN:
396 return ISD::UMIN;
397 case ISD::VECREDUCE_FMAX:
398 return ISD::FMAXNUM;
399 case ISD::VECREDUCE_FMIN:
400 return ISD::FMINNUM;
401 }
402}
403
404bool ISD::isVPOpcode(unsigned Opcode) {
405 switch (Opcode) {
406 default:
407 return false;
408#define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...) \
409 case ISD::SDOPC: \
410 return true;
411#include "llvm/IR/VPIntrinsics.def"
412 }
413}
414
415/// The operand position of the vector mask.
416Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
417 switch (Opcode) {
418 default:
419 return None;
420#define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, ...) \
421 case ISD::SDOPC: \
422 return MASKPOS;
423#include "llvm/IR/VPIntrinsics.def"
424 }
425}
426
427/// The operand position of the explicit vector length parameter.
428Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
429 switch (Opcode) {
430 default:
431 return None;
432#define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \
433 case ISD::SDOPC: \
434 return EVLPOS;
435#include "llvm/IR/VPIntrinsics.def"
436 }
437}
438
439ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
440 switch (ExtType) {
441 case ISD::EXTLOAD:
442 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
443 case ISD::SEXTLOAD:
444 return ISD::SIGN_EXTEND;
445 case ISD::ZEXTLOAD:
446 return ISD::ZERO_EXTEND;
447 default:
448 break;
449 }
450
451 llvm_unreachable("Invalid LoadExtType")__builtin_unreachable();
452}
453
454ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
455 // To perform this operation, we just need to swap the L and G bits of the
456 // operation.
457 unsigned OldL = (Operation >> 2) & 1;
458 unsigned OldG = (Operation >> 1) & 1;
459 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
460 (OldL << 1) | // New G bit
461 (OldG << 2)); // New L bit.
462}
463
464static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
465 unsigned Operation = Op;
466 if (isIntegerLike)
467 Operation ^= 7; // Flip L, G, E bits, but not U.
468 else
469 Operation ^= 15; // Flip all of the condition bits.
470
471 if (Operation > ISD::SETTRUE2)
472 Operation &= ~8; // Don't let N and U bits get set.
473
474 return ISD::CondCode(Operation);
475}
476
477ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
478 return getSetCCInverseImpl(Op, Type.isInteger());
479}
480
481ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
482 bool isIntegerLike) {
483 return getSetCCInverseImpl(Op, isIntegerLike);
484}
485
486/// For an integer comparison, return 1 if the comparison is a signed operation
487/// and 2 if the result is an unsigned comparison. Return zero if the operation
488/// does not depend on the sign of the input (setne and seteq).
489static int isSignedOp(ISD::CondCode Opcode) {
490 switch (Opcode) {
491 default: llvm_unreachable("Illegal integer setcc operation!")__builtin_unreachable();
492 case ISD::SETEQ:
493 case ISD::SETNE: return 0;
494 case ISD::SETLT:
495 case ISD::SETLE:
496 case ISD::SETGT:
497 case ISD::SETGE: return 1;
498 case ISD::SETULT:
499 case ISD::SETULE:
500 case ISD::SETUGT:
501 case ISD::SETUGE: return 2;
502 }
503}
504
505ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
506 EVT Type) {
507 bool IsInteger = Type.isInteger();
508 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
509 // Cannot fold a signed integer setcc with an unsigned integer setcc.
510 return ISD::SETCC_INVALID;
511
512 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
513
514 // If the N and U bits get set, then the resultant comparison DOES suddenly
515 // care about orderedness, and it is true when ordered.
516 if (Op > ISD::SETTRUE2)
517 Op &= ~16; // Clear the U bit if the N bit is set.
518
519 // Canonicalize illegal integer setcc's.
520 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
521 Op = ISD::SETNE;
522
523 return ISD::CondCode(Op);
524}
525
526ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
527 EVT Type) {
528 bool IsInteger = Type.isInteger();
529 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
530 // Cannot fold a signed setcc with an unsigned setcc.
531 return ISD::SETCC_INVALID;
532
533 // Combine all of the condition bits.
534 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
535
536 // Canonicalize illegal integer setcc's.
537 if (IsInteger) {
538 switch (Result) {
539 default: break;
540 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
541 case ISD::SETOEQ: // SETEQ & SETU[LG]E
542 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
543 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
544 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
545 }
546 }
547
548 return Result;
549}
550
551//===----------------------------------------------------------------------===//
552// SDNode Profile Support
553//===----------------------------------------------------------------------===//
554
555/// AddNodeIDOpcode - Add the node opcode to the NodeID data.
556static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
557 ID.AddInteger(OpC);
558}
559
560/// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
561/// solely with their pointer.
562static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
563 ID.AddPointer(VTList.VTs);
564}
565
566/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
567static void AddNodeIDOperands(FoldingSetNodeID &ID,
568 ArrayRef<SDValue> Ops) {
569 for (auto& Op : Ops) {
570 ID.AddPointer(Op.getNode());
571 ID.AddInteger(Op.getResNo());
572 }
573}
574
575/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
576static void AddNodeIDOperands(FoldingSetNodeID &ID,
577 ArrayRef<SDUse> Ops) {
578 for (auto& Op : Ops) {
579 ID.AddPointer(Op.getNode());
580 ID.AddInteger(Op.getResNo());
581 }
582}
583
584static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
585 SDVTList VTList, ArrayRef<SDValue> OpList) {
586 AddNodeIDOpcode(ID, OpC);
587 AddNodeIDValueTypes(ID, VTList);
588 AddNodeIDOperands(ID, OpList);
589}
590
591/// If this is an SDNode with special info, add this info to the NodeID data.
592static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
593 switch (N->getOpcode()) {
594 case ISD::TargetExternalSymbol:
595 case ISD::ExternalSymbol:
596 case ISD::MCSymbol:
597 llvm_unreachable("Should only be used on nodes with operands")__builtin_unreachable();
598 default: break; // Normal nodes don't need extra info.
599 case ISD::TargetConstant:
600 case ISD::Constant: {
601 const ConstantSDNode *C = cast<ConstantSDNode>(N);
602 ID.AddPointer(C->getConstantIntValue());
603 ID.AddBoolean(C->isOpaque());
604 break;
605 }
606 case ISD::TargetConstantFP:
607 case ISD::ConstantFP:
608 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
609 break;
610 case ISD::TargetGlobalAddress:
611 case ISD::GlobalAddress:
612 case ISD::TargetGlobalTLSAddress:
613 case ISD::GlobalTLSAddress: {
614 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
615 ID.AddPointer(GA->getGlobal());
616 ID.AddInteger(GA->getOffset());
617 ID.AddInteger(GA->getTargetFlags());
618 break;
619 }
620 case ISD::BasicBlock:
621 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
622 break;
623 case ISD::Register:
624 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
625 break;
626 case ISD::RegisterMask:
627 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
628 break;
629 case ISD::SRCVALUE:
630 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
631 break;
632 case ISD::FrameIndex:
633 case ISD::TargetFrameIndex:
634 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
635 break;
636 case ISD::LIFETIME_START:
637 case ISD::LIFETIME_END:
638 if (cast<LifetimeSDNode>(N)->hasOffset()) {
639 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
640 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
641 }
642 break;
643 case ISD::PSEUDO_PROBE:
644 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
645 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
646 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
647 break;
648 case ISD::JumpTable:
649 case ISD::TargetJumpTable:
650 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
651 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
652 break;
653 case ISD::ConstantPool:
654 case ISD::TargetConstantPool: {
655 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
656 ID.AddInteger(CP->getAlign().value());
657 ID.AddInteger(CP->getOffset());
658 if (CP->isMachineConstantPoolEntry())
659 CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
660 else
661 ID.AddPointer(CP->getConstVal());
662 ID.AddInteger(CP->getTargetFlags());
663 break;
664 }
665 case ISD::TargetIndex: {
666 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
667 ID.AddInteger(TI->getIndex());
668 ID.AddInteger(TI->getOffset());
669 ID.AddInteger(TI->getTargetFlags());
670 break;
671 }
672 case ISD::LOAD: {
673 const LoadSDNode *LD = cast<LoadSDNode>(N);
674 ID.AddInteger(LD->getMemoryVT().getRawBits());
675 ID.AddInteger(LD->getRawSubclassData());
676 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
677 break;
678 }
679 case ISD::STORE: {
680 const StoreSDNode *ST = cast<StoreSDNode>(N);
681 ID.AddInteger(ST->getMemoryVT().getRawBits());
682 ID.AddInteger(ST->getRawSubclassData());
683 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
684 break;
685 }
686 case ISD::VP_LOAD: {
687 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
688 ID.AddInteger(ELD->getMemoryVT().getRawBits());
689 ID.AddInteger(ELD->getRawSubclassData());
690 ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
691 break;
692 }
693 case ISD::VP_STORE: {
694 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
695 ID.AddInteger(EST->getMemoryVT().getRawBits());
696 ID.AddInteger(EST->getRawSubclassData());
697 ID.AddInteger(EST->getPointerInfo().getAddrSpace());
698 break;
699 }
700 case ISD::VP_GATHER: {
701 const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
702 ID.AddInteger(EG->getMemoryVT().getRawBits());
703 ID.AddInteger(EG->getRawSubclassData());
704 ID.AddInteger(EG->getPointerInfo().getAddrSpace());
705 break;
706 }
707 case ISD::VP_SCATTER: {
708 const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
709 ID.AddInteger(ES->getMemoryVT().getRawBits());
710 ID.AddInteger(ES->getRawSubclassData());
711 ID.AddInteger(ES->getPointerInfo().getAddrSpace());
712 break;
713 }
714 case ISD::MLOAD: {
715 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
716 ID.AddInteger(MLD->getMemoryVT().getRawBits());
717 ID.AddInteger(MLD->getRawSubclassData());
718 ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
719 break;
720 }
721 case ISD::MSTORE: {
722 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
723 ID.AddInteger(MST->getMemoryVT().getRawBits());
724 ID.AddInteger(MST->getRawSubclassData());
725 ID.AddInteger(MST->getPointerInfo().getAddrSpace());
726 break;
727 }
728 case ISD::MGATHER: {
729 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
730 ID.AddInteger(MG->getMemoryVT().getRawBits());
731 ID.AddInteger(MG->getRawSubclassData());
732 ID.AddInteger(MG->getPointerInfo().getAddrSpace());
733 break;
734 }
735 case ISD::MSCATTER: {
736 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
737 ID.AddInteger(MS->getMemoryVT().getRawBits());
738 ID.AddInteger(MS->getRawSubclassData());
739 ID.AddInteger(MS->getPointerInfo().getAddrSpace());
740 break;
741 }
742 case ISD::ATOMIC_CMP_SWAP:
743 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
744 case ISD::ATOMIC_SWAP:
745 case ISD::ATOMIC_LOAD_ADD:
746 case ISD::ATOMIC_LOAD_SUB:
747 case ISD::ATOMIC_LOAD_AND:
748 case ISD::ATOMIC_LOAD_CLR:
749 case ISD::ATOMIC_LOAD_OR:
750 case ISD::ATOMIC_LOAD_XOR:
751 case ISD::ATOMIC_LOAD_NAND:
752 case ISD::ATOMIC_LOAD_MIN:
753 case ISD::ATOMIC_LOAD_MAX:
754 case ISD::ATOMIC_LOAD_UMIN:
755 case ISD::ATOMIC_LOAD_UMAX:
756 case ISD::ATOMIC_LOAD:
757 case ISD::ATOMIC_STORE: {
758 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
759 ID.AddInteger(AT->getMemoryVT().getRawBits());
760 ID.AddInteger(AT->getRawSubclassData());
761 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
762 break;
763 }
764 case ISD::PREFETCH: {
765 const MemSDNode *PF = cast<MemSDNode>(N);
766 ID.AddInteger(PF->getPointerInfo().getAddrSpace());
767 break;
768 }
769 case ISD::VECTOR_SHUFFLE: {
770 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
771 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
772 i != e; ++i)
773 ID.AddInteger(SVN->getMaskElt(i));
774 break;
775 }
776 case ISD::TargetBlockAddress:
777 case ISD::BlockAddress: {
778 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
779 ID.AddPointer(BA->getBlockAddress());
780 ID.AddInteger(BA->getOffset());
781 ID.AddInteger(BA->getTargetFlags());
782 break;
783 }
784 } // end switch (N->getOpcode())
785
786 // Target specific memory nodes could also have address spaces to check.
787 if (N->isTargetMemoryOpcode())
788 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
789}
790
791/// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
792/// data.
793static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
794 AddNodeIDOpcode(ID, N->getOpcode());
795 // Add the return value info.
796 AddNodeIDValueTypes(ID, N->getVTList());
797 // Add the operand info.
798 AddNodeIDOperands(ID, N->ops());
799
800 // Handle SDNode leafs with special info.
801 AddNodeIDCustom(ID, N);
802}
803
804//===----------------------------------------------------------------------===//
805// SelectionDAG Class
806//===----------------------------------------------------------------------===//
807
808/// doNotCSE - Return true if CSE should not be performed for this node.
809static bool doNotCSE(SDNode *N) {
810 if (N->getValueType(0) == MVT::Glue)
811 return true; // Never CSE anything that produces a flag.
812
813 switch (N->getOpcode()) {
814 default: break;
815 case ISD::HANDLENODE:
816 case ISD::EH_LABEL:
817 return true; // Never CSE these nodes.
818 }
819
820 // Check that remaining values produced are not flags.
821 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
822 if (N->getValueType(i) == MVT::Glue)
823 return true; // Never CSE anything that produces a flag.
824
825 return false;
826}
827
828/// RemoveDeadNodes - This method deletes all unreachable nodes in the
829/// SelectionDAG.
830void SelectionDAG::RemoveDeadNodes() {
831 // Create a dummy node (which is not added to allnodes), that adds a reference
832 // to the root node, preventing it from being deleted.
833 HandleSDNode Dummy(getRoot());
834
835 SmallVector<SDNode*, 128> DeadNodes;
836
837 // Add all obviously-dead nodes to the DeadNodes worklist.
838 for (SDNode &Node : allnodes())
839 if (Node.use_empty())
840 DeadNodes.push_back(&Node);
841
842 RemoveDeadNodes(DeadNodes);
843
844 // If the root changed (e.g. it was a dead load, update the root).
845 setRoot(Dummy.getValue());
846}
847
848/// RemoveDeadNodes - This method deletes the unreachable nodes in the
849/// given list, and any nodes that become unreachable as a result.
850void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
851
852 // Process the worklist, deleting the nodes and adding their uses to the
853 // worklist.
854 while (!DeadNodes.empty()) {
855 SDNode *N = DeadNodes.pop_back_val();
856 // Skip to next node if we've already managed to delete the node. This could
857 // happen if replacing a node causes a node previously added to the node to
858 // be deleted.
859 if (N->getOpcode() == ISD::DELETED_NODE)
860 continue;
861
862 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
863 DUL->NodeDeleted(N, nullptr);
864
865 // Take the node out of the appropriate CSE map.
866 RemoveNodeFromCSEMaps(N);
867
868 // Next, brutally remove the operand list. This is safe to do, as there are
869 // no cycles in the graph.
870 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
871 SDUse &Use = *I++;
872 SDNode *Operand = Use.getNode();
873 Use.set(SDValue());
874
875 // Now that we removed this operand, see if there are no uses of it left.
876 if (Operand->use_empty())
877 DeadNodes.push_back(Operand);
878 }
879
880 DeallocateNode(N);
881 }
882}
883
884void SelectionDAG::RemoveDeadNode(SDNode *N){
885 SmallVector<SDNode*, 16> DeadNodes(1, N);
886
887 // Create a dummy node that adds a reference to the root node, preventing
888 // it from being deleted. (This matters if the root is an operand of the
889 // dead node.)
890 HandleSDNode Dummy(getRoot());
891
892 RemoveDeadNodes(DeadNodes);
893}
894
895void SelectionDAG::DeleteNode(SDNode *N) {
896 // First take this out of the appropriate CSE map.
897 RemoveNodeFromCSEMaps(N);
898
899 // Finally, remove uses due to operands of this node, remove from the
900 // AllNodes list, and delete the node.
901 DeleteNodeNotInCSEMaps(N);
902}
903
904void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
905 assert(N->getIterator() != AllNodes.begin() &&(static_cast<void> (0))
906 "Cannot delete the entry node!")(static_cast<void> (0));
907 assert(N->use_empty() && "Cannot delete a node that is not dead!")(static_cast<void> (0));
908
909 // Drop all of the operands and decrement used node's use counts.
910 N->DropOperands();
911
912 DeallocateNode(N);
913}
914
915void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
916 assert(!(V->isVariadic() && isParameter))(static_cast<void> (0));
917 if (isParameter)
918 ByvalParmDbgValues.push_back(V);
919 else
920 DbgValues.push_back(V);
921 for (const SDNode *Node : V->getSDNodes())
922 if (Node)
923 DbgValMap[Node].push_back(V);
924}
925
926void SDDbgInfo::erase(const SDNode *Node) {
927 DbgValMapType::iterator I = DbgValMap.find(Node);
928 if (I == DbgValMap.end())
929 return;
930 for (auto &Val: I->second)
931 Val->setIsInvalidated();
932 DbgValMap.erase(I);
933}
934
935void SelectionDAG::DeallocateNode(SDNode *N) {
936 // If we have operands, deallocate them.
937 removeOperands(N);
938
939 NodeAllocator.Deallocate(AllNodes.remove(N));
940
941 // Set the opcode to DELETED_NODE to help catch bugs when node
942 // memory is reallocated.
943 // FIXME: There are places in SDag that have grown a dependency on the opcode
944 // value in the released node.
945 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
946 N->NodeType = ISD::DELETED_NODE;
947
948 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
949 // them and forget about that node.
950 DbgInfo->erase(N);
951}
952
953#ifndef NDEBUG1
954/// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
955static void VerifySDNode(SDNode *N) {
956 switch (N->getOpcode()) {
957 default:
958 break;
959 case ISD::BUILD_PAIR: {
960 EVT VT = N->getValueType(0);
961 assert(N->getNumValues() == 1 && "Too many results!")(static_cast<void> (0));
962 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&(static_cast<void> (0))
963 "Wrong return type!")(static_cast<void> (0));
964 assert(N->getNumOperands() == 2 && "Wrong number of operands!")(static_cast<void> (0));
965 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&(static_cast<void> (0))
966 "Mismatched operand types!")(static_cast<void> (0));
967 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&(static_cast<void> (0))
968 "Wrong operand type!")(static_cast<void> (0));
969 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&(static_cast<void> (0))
970 "Wrong return type size")(static_cast<void> (0));
971 break;
972 }
973 case ISD::BUILD_VECTOR: {
974 assert(N->getNumValues() == 1 && "Too many results!")(static_cast<void> (0));
975 assert(N->getValueType(0).isVector() && "Wrong return type!")(static_cast<void> (0));
976 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&(static_cast<void> (0))
977 "Wrong number of operands!")(static_cast<void> (0));
978 EVT EltVT = N->getValueType(0).getVectorElementType();
979 for (const SDUse &Op : N->ops()) {
980 assert((Op.getValueType() == EltVT ||(static_cast<void> (0))
981 (EltVT.isInteger() && Op.getValueType().isInteger() &&(static_cast<void> (0))
982 EltVT.bitsLE(Op.getValueType()))) &&(static_cast<void> (0))
983 "Wrong operand type!")(static_cast<void> (0));
984 assert(Op.getValueType() == N->getOperand(0).getValueType() &&(static_cast<void> (0))
985 "Operands must all have the same type")(static_cast<void> (0));
986 }
987 break;
988 }
989 }
990}
991#endif // NDEBUG
992
993/// Insert a newly allocated node into the DAG.
994///
995/// Handles insertion into the all nodes list and CSE map, as well as
996/// verification and other common operations when a new node is allocated.
997void SelectionDAG::InsertNode(SDNode *N) {
998 AllNodes.push_back(N);
999#ifndef NDEBUG1
1000 N->PersistentId = NextPersistentId++;
1001 VerifySDNode(N);
1002#endif
1003 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1004 DUL->NodeInserted(N);
1005}
1006
1007/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1008/// correspond to it. This is useful when we're about to delete or repurpose
1009/// the node. We don't want future request for structurally identical nodes
1010/// to return N anymore.
1011bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1012 bool Erased = false;
1013 switch (N->getOpcode()) {
1014 case ISD::HANDLENODE: return false; // noop.
1015 case ISD::CONDCODE:
1016 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&(static_cast<void> (0))
1017 "Cond code doesn't exist!")(static_cast<void> (0));
1018 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1019 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1020 break;
1021 case ISD::ExternalSymbol:
1022 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1023 break;
1024 case ISD::TargetExternalSymbol: {
1025 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1026 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1027 ESN->getSymbol(), ESN->getTargetFlags()));
1028 break;
1029 }
1030 case ISD::MCSymbol: {
1031 auto *MCSN = cast<MCSymbolSDNode>(N);
1032 Erased = MCSymbols.erase(MCSN->getMCSymbol());
1033 break;
1034 }
1035 case ISD::VALUETYPE: {
1036 EVT VT = cast<VTSDNode>(N)->getVT();
1037 if (VT.isExtended()) {
1038 Erased = ExtendedValueTypeNodes.erase(VT);
1039 } else {
1040 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1041 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1042 }
1043 break;
1044 }
1045 default:
1046 // Remove it from the CSE Map.
1047 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!")(static_cast<void> (0));
1048 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!")(static_cast<void> (0));
1049 Erased = CSEMap.RemoveNode(N);
1050 break;
1051 }
1052#ifndef NDEBUG1
1053 // Verify that the node was actually in one of the CSE maps, unless it has a
1054 // flag result (which cannot be CSE'd) or is one of the special cases that are
1055 // not subject to CSE.
1056 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1057 !N->isMachineOpcode() && !doNotCSE(N)) {
1058 N->dump(this);
1059 dbgs() << "\n";
1060 llvm_unreachable("Node is not in map!")__builtin_unreachable();
1061 }
1062#endif
1063 return Erased;
1064}
1065
1066/// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1067/// maps and modified in place. Add it back to the CSE maps, unless an identical
1068/// node already exists, in which case transfer all its users to the existing
1069/// node. This transfer can potentially trigger recursive merging.
1070void
1071SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1072 // For node types that aren't CSE'd, just act as if no identical node
1073 // already exists.
1074 if (!doNotCSE(N)) {
1075 SDNode *Existing = CSEMap.GetOrInsertNode(N);
1076 if (Existing != N) {
1077 // If there was already an existing matching node, use ReplaceAllUsesWith
1078 // to replace the dead one with the existing one. This can cause
1079 // recursive merging of other unrelated nodes down the line.
1080 ReplaceAllUsesWith(N, Existing);
1081
1082 // N is now dead. Inform the listeners and delete it.
1083 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1084 DUL->NodeDeleted(N, Existing);
1085 DeleteNodeNotInCSEMaps(N);
1086 return;
1087 }
1088 }
1089
1090 // If the node doesn't already exist, we updated it. Inform listeners.
1091 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1092 DUL->NodeUpdated(N);
1093}
1094
1095/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1096/// were replaced with those specified. If this node is never memoized,
1097/// return null, otherwise return a pointer to the slot it would take. If a
1098/// node already exists with these operands, the slot will be non-null.
1099SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1100 void *&InsertPos) {
1101 if (doNotCSE(N))
1102 return nullptr;
1103
1104 SDValue Ops[] = { Op };
1105 FoldingSetNodeID ID;
1106 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1107 AddNodeIDCustom(ID, N);
1108 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1109 if (Node)
1110 Node->intersectFlagsWith(N->getFlags());
1111 return Node;
1112}
1113
1114/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1115/// were replaced with those specified. If this node is never memoized,
1116/// return null, otherwise return a pointer to the slot it would take. If a
1117/// node already exists with these operands, the slot will be non-null.
1118SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1119 SDValue Op1, SDValue Op2,
1120 void *&InsertPos) {
1121 if (doNotCSE(N))
1122 return nullptr;
1123
1124 SDValue Ops[] = { Op1, Op2 };
1125 FoldingSetNodeID ID;
1126 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1127 AddNodeIDCustom(ID, N);
1128 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1129 if (Node)
1130 Node->intersectFlagsWith(N->getFlags());
1131 return Node;
1132}
1133
1134/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1135/// were replaced with those specified. If this node is never memoized,
1136/// return null, otherwise return a pointer to the slot it would take. If a
1137/// node already exists with these operands, the slot will be non-null.
1138SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1139 void *&InsertPos) {
1140 if (doNotCSE(N))
1141 return nullptr;
1142
1143 FoldingSetNodeID ID;
1144 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1145 AddNodeIDCustom(ID, N);
1146 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1147 if (Node)
1148 Node->intersectFlagsWith(N->getFlags());
1149 return Node;
1150}
1151
1152Align SelectionDAG::getEVTAlign(EVT VT) const {
1153 Type *Ty = VT == MVT::iPTR ?
1154 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1155 VT.getTypeForEVT(*getContext());
1156
1157 return getDataLayout().getABITypeAlign(Ty);
1158}
1159
1160// EntryNode could meaningfully have debug info if we can find it...
1161SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1162 : TM(tm), OptLevel(OL),
1163 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1164 Root(getEntryNode()) {
1165 InsertNode(&EntryNode);
1166 DbgInfo = new SDDbgInfo();
1167}
1168
1169void SelectionDAG::init(MachineFunction &NewMF,
1170 OptimizationRemarkEmitter &NewORE,
1171 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1172 LegacyDivergenceAnalysis * Divergence,
1173 ProfileSummaryInfo *PSIin,
1174 BlockFrequencyInfo *BFIin) {
1175 MF = &NewMF;
1176 SDAGISelPass = PassPtr;
1177 ORE = &NewORE;
1178 TLI = getSubtarget().getTargetLowering();
1179 TSI = getSubtarget().getSelectionDAGInfo();
1180 LibInfo = LibraryInfo;
1181 Context = &MF->getFunction().getContext();
1182 DA = Divergence;
1183 PSI = PSIin;
1184 BFI = BFIin;
1185}
1186
1187SelectionDAG::~SelectionDAG() {
1188 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners")(static_cast<void> (0));
1189 allnodes_clear();
1190 OperandRecycler.clear(OperandAllocator);
1191 delete DbgInfo;
1192}
1193
1194bool SelectionDAG::shouldOptForSize() const {
1195 return MF->getFunction().hasOptSize() ||
1196 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1197}
1198
1199void SelectionDAG::allnodes_clear() {
1200 assert(&*AllNodes.begin() == &EntryNode)(static_cast<void> (0));
1201 AllNodes.remove(AllNodes.begin());
1202 while (!AllNodes.empty())
1203 DeallocateNode(&AllNodes.front());
1204#ifndef NDEBUG1
1205 NextPersistentId = 0;
1206#endif
1207}
1208
1209SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1210 void *&InsertPos) {
1211 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1212 if (N) {
1213 switch (N->getOpcode()) {
1214 default: break;
1215 case ISD::Constant:
1216 case ISD::ConstantFP:
1217 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "__builtin_unreachable()
1218 "debug location. Use another overload.")__builtin_unreachable();
1219 }
1220 }
1221 return N;
1222}
1223
1224SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1225 const SDLoc &DL, void *&InsertPos) {
1226 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1227 if (N) {
1228 switch (N->getOpcode()) {
1229 case ISD::Constant:
1230 case ISD::ConstantFP:
1231 // Erase debug location from the node if the node is used at several
1232 // different places. Do not propagate one location to all uses as it
1233 // will cause a worse single stepping debugging experience.
1234 if (N->getDebugLoc() != DL.getDebugLoc())
1235 N->setDebugLoc(DebugLoc());
1236 break;
1237 default:
1238 // When the node's point of use is located earlier in the instruction
1239 // sequence than its prior point of use, update its debug info to the
1240 // earlier location.
1241 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1242 N->setDebugLoc(DL.getDebugLoc());
1243 break;
1244 }
1245 }
1246 return N;
1247}
1248
1249void SelectionDAG::clear() {
1250 allnodes_clear();
1251 OperandRecycler.clear(OperandAllocator);
1252 OperandAllocator.Reset();
1253 CSEMap.clear();
1254
1255 ExtendedValueTypeNodes.clear();
1256 ExternalSymbols.clear();
1257 TargetExternalSymbols.clear();
1258 MCSymbols.clear();
1259 SDCallSiteDbgInfo.clear();
1260 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1261 static_cast<CondCodeSDNode*>(nullptr));
1262 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1263 static_cast<SDNode*>(nullptr));
1264
1265 EntryNode.UseList = nullptr;
1266 InsertNode(&EntryNode);
1267 Root = getEntryNode();
1268 DbgInfo->clear();
1269}
1270
1271SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1272 return VT.bitsGT(Op.getValueType())
1273 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1274 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1275}
1276
1277std::pair<SDValue, SDValue>
1278SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1279 const SDLoc &DL, EVT VT) {
1280 assert(!VT.bitsEq(Op.getValueType()) &&(static_cast<void> (0))
1281 "Strict no-op FP extend/round not allowed.")(static_cast<void> (0));
1282 SDValue Res =
1283 VT.bitsGT(Op.getValueType())
1284 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1285 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1286 {Chain, Op, getIntPtrConstant(0, DL)});
1287
1288 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1289}
1290
1291SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1292 return VT.bitsGT(Op.getValueType()) ?
1293 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1294 getNode(ISD::TRUNCATE, DL, VT, Op);
1295}
1296
1297SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1298 return VT.bitsGT(Op.getValueType()) ?
1299 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1300 getNode(ISD::TRUNCATE, DL, VT, Op);
1301}
1302
1303SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1304 return VT.bitsGT(Op.getValueType()) ?
1305 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1306 getNode(ISD::TRUNCATE, DL, VT, Op);
1307}
1308
1309SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1310 EVT OpVT) {
1311 if (VT.bitsLE(Op.getValueType()))
1312 return getNode(ISD::TRUNCATE, SL, VT, Op);
1313
1314 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1315 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1316}
1317
1318SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1319 EVT OpVT = Op.getValueType();
1320 assert(VT.isInteger() && OpVT.isInteger() &&(static_cast<void> (0))
1321 "Cannot getZeroExtendInReg FP types")(static_cast<void> (0));
1322 assert(VT.isVector() == OpVT.isVector() &&(static_cast<void> (0))
1323 "getZeroExtendInReg type should be vector iff the operand "(static_cast<void> (0))
1324 "type is vector!")(static_cast<void> (0));
1325 assert((!VT.isVector() ||(static_cast<void> (0))
1326 VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&(static_cast<void> (0))
1327 "Vector element counts must match in getZeroExtendInReg")(static_cast<void> (0));
1328 assert(VT.bitsLE(OpVT) && "Not extending!")(static_cast<void> (0));
1329 if (OpVT == VT)
1330 return Op;
1331 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1332 VT.getScalarSizeInBits());
1333 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1334}
1335
1336SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1337 // Only unsigned pointer semantics are supported right now. In the future this
1338 // might delegate to TLI to check pointer signedness.
1339 return getZExtOrTrunc(Op, DL, VT);
1340}
1341
1342SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1343 // Only unsigned pointer semantics are supported right now. In the future this
1344 // might delegate to TLI to check pointer signedness.
1345 return getZeroExtendInReg(Op, DL, VT);
1346}
1347
1348/// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1349SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1350 EVT EltVT = VT.getScalarType();
1351 SDValue NegOne =
1352 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1353 return getNode(ISD::XOR, DL, VT, Val, NegOne);
1354}
1355
1356SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1357 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1358 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1359}
1360
1361SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1362 EVT OpVT) {
1363 if (!V)
1364 return getConstant(0, DL, VT);
1365
1366 switch (TLI->getBooleanContents(OpVT)) {
1367 case TargetLowering::ZeroOrOneBooleanContent:
1368 case TargetLowering::UndefinedBooleanContent:
1369 return getConstant(1, DL, VT);
1370 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1371 return getAllOnesConstant(DL, VT);
1372 }
1373 llvm_unreachable("Unexpected boolean content enum!")__builtin_unreachable();
1374}
1375
1376SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1377 bool isT, bool isO) {
1378 EVT EltVT = VT.getScalarType();
1379 assert((EltVT.getSizeInBits() >= 64 ||(static_cast<void> (0))
1380 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&(static_cast<void> (0))
1381 "getConstant with a uint64_t value that doesn't fit in the type!")(static_cast<void> (0));
1382 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1383}
1384
1385SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1386 bool isT, bool isO) {
1387 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1388}
1389
1390SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1391 EVT VT, bool isT, bool isO) {
1392 assert(VT.isInteger() && "Cannot create FP integer constant!")(static_cast<void> (0));
1393
1394 EVT EltVT = VT.getScalarType();
1395 const ConstantInt *Elt = &Val;
1396
1397 // In some cases the vector type is legal but the element type is illegal and
1398 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1399 // inserted value (the type does not need to match the vector element type).
1400 // Any extra bits introduced will be truncated away.
1401 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1402 TargetLowering::TypePromoteInteger) {
1403 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1404 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1405 Elt = ConstantInt::get(*getContext(), NewVal);
1406 }
1407 // In other cases the element type is illegal and needs to be expanded, for
1408 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1409 // the value into n parts and use a vector type with n-times the elements.
1410 // Then bitcast to the type requested.
1411 // Legalizing constants too early makes the DAGCombiner's job harder so we
1412 // only legalize if the DAG tells us we must produce legal types.
1413 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1414 TLI->getTypeAction(*getContext(), EltVT) ==
1415 TargetLowering::TypeExpandInteger) {
1416 const APInt &NewVal = Elt->getValue();
1417 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1418 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1419
1420 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1421 if (VT.isScalableVector()) {
1422 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&(static_cast<void> (0))
1423 "Can only handle an even split!")(static_cast<void> (0));
1424 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1425
1426 SmallVector<SDValue, 2> ScalarParts;
1427 for (unsigned i = 0; i != Parts; ++i)
1428 ScalarParts.push_back(getConstant(
1429 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1430 ViaEltVT, isT, isO));
1431
1432 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1433 }
1434
1435 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1436 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1437
1438 // Check the temporary vector is the correct size. If this fails then
1439 // getTypeToTransformTo() probably returned a type whose size (in bits)
1440 // isn't a power-of-2 factor of the requested type size.
1441 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits())(static_cast<void> (0));
1442
1443 SmallVector<SDValue, 2> EltParts;
1444 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1445 EltParts.push_back(getConstant(
1446 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1447 ViaEltVT, isT, isO));
1448
1449 // EltParts is currently in little endian order. If we actually want
1450 // big-endian order then reverse it now.
1451 if (getDataLayout().isBigEndian())
1452 std::reverse(EltParts.begin(), EltParts.end());
1453
1454 // The elements must be reversed when the element order is different
1455 // to the endianness of the elements (because the BITCAST is itself a
1456 // vector shuffle in this situation). However, we do not need any code to
1457 // perform this reversal because getConstant() is producing a vector
1458 // splat.
1459 // This situation occurs in MIPS MSA.
1460
1461 SmallVector<SDValue, 8> Ops;
1462 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1463 llvm::append_range(Ops, EltParts);
1464
1465 SDValue V =
1466 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1467 return V;
1468 }
1469
1470 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&(static_cast<void> (0))
1471 "APInt size does not match type size!")(static_cast<void> (0));
1472 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1473 FoldingSetNodeID ID;
1474 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1475 ID.AddPointer(Elt);
1476 ID.AddBoolean(isO);
1477 void *IP = nullptr;
1478 SDNode *N = nullptr;
1479 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1480 if (!VT.isVector())
1481 return SDValue(N, 0);
1482
1483 if (!N) {
1484 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1485 CSEMap.InsertNode(N, IP);
1486 InsertNode(N);
1487 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1488 }
1489
1490 SDValue Result(N, 0);
1491 if (VT.isScalableVector())
1492 Result = getSplatVector(VT, DL, Result);
1493 else if (VT.isVector())
1494 Result = getSplatBuildVector(VT, DL, Result);
1495
1496 return Result;
1497}
1498
1499SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1500 bool isTarget) {
1501 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1502}
1503
1504SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1505 const SDLoc &DL, bool LegalTypes) {
1506 assert(VT.isInteger() && "Shift amount is not an integer type!")(static_cast<void> (0));
1507 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1508 return getConstant(Val, DL, ShiftVT);
1509}
1510
1511SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1512 bool isTarget) {
1513 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1514}
1515
1516SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1517 bool isTarget) {
1518 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1519}
1520
1521SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1522 EVT VT, bool isTarget) {
1523 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!")(static_cast<void> (0));
1524
1525 EVT EltVT = VT.getScalarType();
1526
1527 // Do the map lookup using the actual bit pattern for the floating point
1528 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1529 // we don't have issues with SNANs.
1530 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1531 FoldingSetNodeID ID;
1532 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1533 ID.AddPointer(&V);
1534 void *IP = nullptr;
1535 SDNode *N = nullptr;
1536 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1537 if (!VT.isVector())
1538 return SDValue(N, 0);
1539
1540 if (!N) {
1541 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1542 CSEMap.InsertNode(N, IP);
1543 InsertNode(N);
1544 }
1545
1546 SDValue Result(N, 0);
1547 if (VT.isScalableVector())
1548 Result = getSplatVector(VT, DL, Result);
1549 else if (VT.isVector())
1550 Result = getSplatBuildVector(VT, DL, Result);
1551 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1552 return Result;
1553}
1554
1555SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1556 bool isTarget) {
1557 EVT EltVT = VT.getScalarType();
1558 if (EltVT == MVT::f32)
1559 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1560 if (EltVT == MVT::f64)
1561 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1562 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1563 EltVT == MVT::f16 || EltVT == MVT::bf16) {
1564 bool Ignored;
1565 APFloat APF = APFloat(Val);
1566 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1567 &Ignored);
1568 return getConstantFP(APF, DL, VT, isTarget);
1569 }
1570 llvm_unreachable("Unsupported type in getConstantFP")__builtin_unreachable();
1571}
1572
1573SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1574 EVT VT, int64_t Offset, bool isTargetGA,
1575 unsigned TargetFlags) {
1576 assert((TargetFlags == 0 || isTargetGA) &&(static_cast<void> (0))
1577 "Cannot set target flags on target-independent globals")(static_cast<void> (0));
1578
1579 // Truncate (with sign-extension) the offset value to the pointer size.
1580 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1581 if (BitWidth < 64)
1582 Offset = SignExtend64(Offset, BitWidth);
1583
1584 unsigned Opc;
1585 if (GV->isThreadLocal())
1586 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1587 else
1588 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1589
1590 FoldingSetNodeID ID;
1591 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1592 ID.AddPointer(GV);
1593 ID.AddInteger(Offset);
1594 ID.AddInteger(TargetFlags);
1595 void *IP = nullptr;
1596 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1597 return SDValue(E, 0);
1598
1599 auto *N = newSDNode<GlobalAddressSDNode>(
1600 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1601 CSEMap.InsertNode(N, IP);
1602 InsertNode(N);
1603 return SDValue(N, 0);
1604}
1605
1606SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1607 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1608 FoldingSetNodeID ID;
1609 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1610 ID.AddInteger(FI);
1611 void *IP = nullptr;
1612 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1613 return SDValue(E, 0);
1614
1615 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1616 CSEMap.InsertNode(N, IP);
1617 InsertNode(N);
1618 return SDValue(N, 0);
1619}
1620
1621SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1622 unsigned TargetFlags) {
1623 assert((TargetFlags == 0 || isTarget) &&(static_cast<void> (0))
1624 "Cannot set target flags on target-independent jump tables")(static_cast<void> (0));
1625 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1626 FoldingSetNodeID ID;
1627 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1628 ID.AddInteger(JTI);
1629 ID.AddInteger(TargetFlags);
1630 void *IP = nullptr;
1631 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1632 return SDValue(E, 0);
1633
1634 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1635 CSEMap.InsertNode(N, IP);
1636 InsertNode(N);
1637 return SDValue(N, 0);
1638}
1639
1640SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1641 MaybeAlign Alignment, int Offset,
1642 bool isTarget, unsigned TargetFlags) {
1643 assert((TargetFlags == 0 || isTarget) &&(static_cast<void> (0))
1644 "Cannot set target flags on target-independent globals")(static_cast<void> (0));
1645 if (!Alignment)
1646 Alignment = shouldOptForSize()
1647 ? getDataLayout().getABITypeAlign(C->getType())
1648 : getDataLayout().getPrefTypeAlign(C->getType());
1649 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1650 FoldingSetNodeID ID;
1651 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1652 ID.AddInteger(Alignment->value());
1653 ID.AddInteger(Offset);
1654 ID.AddPointer(C);
1655 ID.AddInteger(TargetFlags);
1656 void *IP = nullptr;
1657 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1658 return SDValue(E, 0);
1659
1660 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1661 TargetFlags);
1662 CSEMap.InsertNode(N, IP);
1663 InsertNode(N);
1664 SDValue V = SDValue(N, 0);
1665 NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1666 return V;
1667}
1668
1669SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1670 MaybeAlign Alignment, int Offset,
1671 bool isTarget, unsigned TargetFlags) {
1672 assert((TargetFlags == 0 || isTarget) &&(static_cast<void> (0))
1673 "Cannot set target flags on target-independent globals")(static_cast<void> (0));
1674 if (!Alignment)
1675 Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1676 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1677 FoldingSetNodeID ID;
1678 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1679 ID.AddInteger(Alignment->value());
1680 ID.AddInteger(Offset);
1681 C->addSelectionDAGCSEId(ID);
1682 ID.AddInteger(TargetFlags);
1683 void *IP = nullptr;
1684 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1685 return SDValue(E, 0);
1686
1687 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1688 TargetFlags);
1689 CSEMap.InsertNode(N, IP);
1690 InsertNode(N);
1691 return SDValue(N, 0);
1692}
1693
1694SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1695 unsigned TargetFlags) {
1696 FoldingSetNodeID ID;
1697 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1698 ID.AddInteger(Index);
1699 ID.AddInteger(Offset);
1700 ID.AddInteger(TargetFlags);
1701 void *IP = nullptr;
1702 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1703 return SDValue(E, 0);
1704
1705 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1706 CSEMap.InsertNode(N, IP);
1707 InsertNode(N);
1708 return SDValue(N, 0);
1709}
1710
1711SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1712 FoldingSetNodeID ID;
1713 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1714 ID.AddPointer(MBB);
1715 void *IP = nullptr;
1716 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1717 return SDValue(E, 0);
1718
1719 auto *N = newSDNode<BasicBlockSDNode>(MBB);
1720 CSEMap.InsertNode(N, IP);
1721 InsertNode(N);
1722 return SDValue(N, 0);
1723}
1724
1725SDValue SelectionDAG::getValueType(EVT VT) {
1726 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1727 ValueTypeNodes.size())
1728 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1729
1730 SDNode *&N = VT.isExtended() ?
1731 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1732
1733 if (N) return SDValue(N, 0);
1734 N = newSDNode<VTSDNode>(VT);
1735 InsertNode(N);
1736 return SDValue(N, 0);
1737}
1738
1739SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1740 SDNode *&N = ExternalSymbols[Sym];
1741 if (N) return SDValue(N, 0);
1742 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1743 InsertNode(N);
1744 return SDValue(N, 0);
1745}
1746
1747SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1748 SDNode *&N = MCSymbols[Sym];
1749 if (N)
1750 return SDValue(N, 0);
1751 N = newSDNode<MCSymbolSDNode>(Sym, VT);
1752 InsertNode(N);
1753 return SDValue(N, 0);
1754}
1755
1756SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1757 unsigned TargetFlags) {
1758 SDNode *&N =
1759 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1760 if (N) return SDValue(N, 0);
1761 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1762 InsertNode(N);
1763 return SDValue(N, 0);
1764}
1765
1766SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1767 if ((unsigned)Cond >= CondCodeNodes.size())
1768 CondCodeNodes.resize(Cond+1);
1769
1770 if (!CondCodeNodes[Cond]) {
1771 auto *N = newSDNode<CondCodeSDNode>(Cond);
1772 CondCodeNodes[Cond] = N;
1773 InsertNode(N);
1774 }
1775
1776 return SDValue(CondCodeNodes[Cond], 0);
1777}
1778
1779SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1780 APInt One(ResVT.getScalarSizeInBits(), 1);
1781 return getStepVector(DL, ResVT, One);
1782}
1783
1784SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1785 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth())(static_cast<void> (0));
1786 if (ResVT.isScalableVector())
1787 return getNode(
1788 ISD::STEP_VECTOR, DL, ResVT,
1789 getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1790
1791 SmallVector<SDValue, 16> OpsStepConstants;
1792 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1793 OpsStepConstants.push_back(
1794 getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1795 return getBuildVector(ResVT, DL, OpsStepConstants);
1796}
1797
1798/// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1799/// point at N1 to point at N2 and indices that point at N2 to point at N1.
1800static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1801 std::swap(N1, N2);
1802 ShuffleVectorSDNode::commuteMask(M);
1803}
1804
1805SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1806 SDValue N2, ArrayRef<int> Mask) {
1807 assert(VT.getVectorNumElements() == Mask.size() &&(static_cast<void> (0))
1808 "Must have the same number of vector elements as mask elements!")(static_cast<void> (0));
1809 assert(VT == N1.getValueType() && VT == N2.getValueType() &&(static_cast<void> (0))
1810 "Invalid VECTOR_SHUFFLE")(static_cast<void> (0));
1811
1812 // Canonicalize shuffle undef, undef -> undef
1813 if (N1.isUndef() && N2.isUndef())
1814 return getUNDEF(VT);
1815
1816 // Validate that all indices in Mask are within the range of the elements
1817 // input to the shuffle.
1818 int NElts = Mask.size();
1819 assert(llvm::all_of(Mask,(static_cast<void> (0))
1820 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&(static_cast<void> (0))
1821 "Index out of range")(static_cast<void> (0));
1822
1823 // Copy the mask so we can do any needed cleanup.
1824 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1825
1826 // Canonicalize shuffle v, v -> v, undef
1827 if (N1 == N2) {
1828 N2 = getUNDEF(VT);
1829 for (int i = 0; i != NElts; ++i)
1830 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1831 }
1832
1833 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1834 if (N1.isUndef())
1835 commuteShuffle(N1, N2, MaskVec);
1836
1837 if (TLI->hasVectorBlend()) {
1838 // If shuffling a splat, try to blend the splat instead. We do this here so
1839 // that even when this arises during lowering we don't have to re-handle it.
1840 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1841 BitVector UndefElements;
1842 SDValue Splat = BV->getSplatValue(&UndefElements);
1843 if (!Splat)
1844 return;
1845
1846 for (int i = 0; i < NElts; ++i) {
1847 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1848 continue;
1849
1850 // If this input comes from undef, mark it as such.
1851 if (UndefElements[MaskVec[i] - Offset]) {
1852 MaskVec[i] = -1;
1853 continue;
1854 }
1855
1856 // If we can blend a non-undef lane, use that instead.
1857 if (!UndefElements[i])
1858 MaskVec[i] = i + Offset;
1859 }
1860 };
1861 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1862 BlendSplat(N1BV, 0);
1863 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1864 BlendSplat(N2BV, NElts);
1865 }
1866
1867 // Canonicalize all index into lhs, -> shuffle lhs, undef
1868 // Canonicalize all index into rhs, -> shuffle rhs, undef
1869 bool AllLHS = true, AllRHS = true;
1870 bool N2Undef = N2.isUndef();
1871 for (int i = 0; i != NElts; ++i) {
1872 if (MaskVec[i] >= NElts) {
1873 if (N2Undef)
1874 MaskVec[i] = -1;
1875 else
1876 AllLHS = false;
1877 } else if (MaskVec[i] >= 0) {
1878 AllRHS = false;
1879 }
1880 }
1881 if (AllLHS && AllRHS)
1882 return getUNDEF(VT);
1883 if (AllLHS && !N2Undef)
1884 N2 = getUNDEF(VT);
1885 if (AllRHS) {
1886 N1 = getUNDEF(VT);
1887 commuteShuffle(N1, N2, MaskVec);
1888 }
1889 // Reset our undef status after accounting for the mask.
1890 N2Undef = N2.isUndef();
1891 // Re-check whether both sides ended up undef.
1892 if (N1.isUndef() && N2Undef)
1893 return getUNDEF(VT);
1894
1895 // If Identity shuffle return that node.
1896 bool Identity = true, AllSame = true;
1897 for (int i = 0; i != NElts; ++i) {
1898 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1899 if (MaskVec[i] != MaskVec[0]) AllSame = false;
1900 }
1901 if (Identity && NElts)
1902 return N1;
1903
1904 // Shuffling a constant splat doesn't change the result.
1905 if (N2Undef) {
1906 SDValue V = N1;
1907
1908 // Look through any bitcasts. We check that these don't change the number
1909 // (and size) of elements and just changes their types.
1910 while (V.getOpcode() == ISD::BITCAST)
1911 V = V->getOperand(0);
1912
1913 // A splat should always show up as a build vector node.
1914 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1915 BitVector UndefElements;
1916 SDValue Splat = BV->getSplatValue(&UndefElements);
1917 // If this is a splat of an undef, shuffling it is also undef.
1918 if (Splat && Splat.isUndef())
1919 return getUNDEF(VT);
1920
1921 bool SameNumElts =
1922 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1923
1924 // We only have a splat which can skip shuffles if there is a splatted
1925 // value and no undef lanes rearranged by the shuffle.
1926 if (Splat && UndefElements.none()) {
1927 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1928 // number of elements match or the value splatted is a zero constant.
1929 if (SameNumElts)
1930 return N1;
1931 if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1932 if (C->isNullValue())
1933 return N1;
1934 }
1935
1936 // If the shuffle itself creates a splat, build the vector directly.
1937 if (AllSame && SameNumElts) {
1938 EVT BuildVT = BV->getValueType(0);
1939 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1940 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1941
1942 // We may have jumped through bitcasts, so the type of the
1943 // BUILD_VECTOR may not match the type of the shuffle.
1944 if (BuildVT != VT)
1945 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1946 return NewBV;
1947 }
1948 }
1949 }
1950
1951 FoldingSetNodeID ID;
1952 SDValue Ops[2] = { N1, N2 };
1953 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1954 for (int i = 0; i != NElts; ++i)
1955 ID.AddInteger(MaskVec[i]);
1956
1957 void* IP = nullptr;
1958 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1959 return SDValue(E, 0);
1960
1961 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1962 // SDNode doesn't have access to it. This memory will be "leaked" when
1963 // the node is deallocated, but recovered when the NodeAllocator is released.
1964 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1965 llvm::copy(MaskVec, MaskAlloc);
1966
1967 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1968 dl.getDebugLoc(), MaskAlloc);
1969 createOperands(N, Ops);
1970
1971 CSEMap.InsertNode(N, IP);
1972 InsertNode(N);
1973 SDValue V = SDValue(N, 0);
1974 NewSDValueDbgMsg(V, "Creating new node: ", this);
1975 return V;
1976}
1977
1978SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1979 EVT VT = SV.getValueType(0);
1980 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1981 ShuffleVectorSDNode::commuteMask(MaskVec);
1982
1983 SDValue Op0 = SV.getOperand(0);
1984 SDValue Op1 = SV.getOperand(1);
1985 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1986}
1987
1988SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1989 FoldingSetNodeID ID;
1990 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1991 ID.AddInteger(RegNo);
1992 void *IP = nullptr;
1993 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1994 return SDValue(E, 0);
1995
1996 auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1997 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
1998 CSEMap.InsertNode(N, IP);
1999 InsertNode(N);
2000 return SDValue(N, 0);
2001}
2002
2003SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2004 FoldingSetNodeID ID;
2005 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2006 ID.AddPointer(RegMask);
2007 void *IP = nullptr;
2008 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2009 return SDValue(E, 0);
2010
2011 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2012 CSEMap.InsertNode(N, IP);
2013 InsertNode(N);
2014 return SDValue(N, 0);
2015}
2016
2017SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2018 MCSymbol *Label) {
2019 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2020}
2021
2022SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2023 SDValue Root, MCSymbol *Label) {
2024 FoldingSetNodeID ID;
2025 SDValue Ops[] = { Root };
2026 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2027 ID.AddPointer(Label);
2028 void *IP = nullptr;
2029 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2030 return SDValue(E, 0);
2031
2032 auto *N =
2033 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2034 createOperands(N, Ops);
2035
2036 CSEMap.InsertNode(N, IP);
2037 InsertNode(N);
2038 return SDValue(N, 0);
2039}
2040
2041SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2042 int64_t Offset, bool isTarget,
2043 unsigned TargetFlags) {
2044 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2045
2046 FoldingSetNodeID ID;
2047 AddNodeIDNode(ID, Opc, getVTList(VT), None);
2048 ID.AddPointer(BA);
2049 ID.AddInteger(Offset);
2050 ID.AddInteger(TargetFlags);
2051 void *IP = nullptr;
2052 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2053 return SDValue(E, 0);
2054
2055 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2056 CSEMap.InsertNode(N, IP);
2057 InsertNode(N);
2058 return SDValue(N, 0);
2059}
2060
2061SDValue SelectionDAG::getSrcValue(const Value *V) {
2062 FoldingSetNodeID ID;
2063 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2064 ID.AddPointer(V);
2065
2066 void *IP = nullptr;
2067 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2068 return SDValue(E, 0);
2069
2070 auto *N = newSDNode<SrcValueSDNode>(V);
2071 CSEMap.InsertNode(N, IP);
2072 InsertNode(N);
2073 return SDValue(N, 0);
2074}
2075
2076SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2077 FoldingSetNodeID ID;
2078 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2079 ID.AddPointer(MD);
2080
2081 void *IP = nullptr;
2082 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2083 return SDValue(E, 0);
2084
2085 auto *N = newSDNode<MDNodeSDNode>(MD);
2086 CSEMap.InsertNode(N, IP);
2087 InsertNode(N);
2088 return SDValue(N, 0);
2089}
2090
2091SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2092 if (VT == V.getValueType())
2093 return V;
2094
2095 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2096}
2097
2098SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2099 unsigned SrcAS, unsigned DestAS) {
2100 SDValue Ops[] = {Ptr};
2101 FoldingSetNodeID ID;
2102 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2103 ID.AddInteger(SrcAS);
2104 ID.AddInteger(DestAS);
2105
2106 void *IP = nullptr;
2107 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2108 return SDValue(E, 0);
2109
2110 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2111 VT, SrcAS, DestAS);
2112 createOperands(N, Ops);
2113
2114 CSEMap.InsertNode(N, IP);
2115 InsertNode(N);
2116 return SDValue(N, 0);
2117}
2118
2119SDValue SelectionDAG::getFreeze(SDValue V) {
2120 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2121}
2122
2123/// getShiftAmountOperand - Return the specified value casted to
2124/// the target's desired shift amount type.
2125SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2126 EVT OpTy = Op.getValueType();
2127 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2128 if (OpTy == ShTy || OpTy.isVector()) return Op;
2129
2130 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2131}
2132
2133SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2134 SDLoc dl(Node);
2135 const TargetLowering &TLI = getTargetLoweringInfo();
2136 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2137 EVT VT = Node->getValueType(0);
2138 SDValue Tmp1 = Node->getOperand(0);
2139 SDValue Tmp2 = Node->getOperand(1);
2140 const MaybeAlign MA(Node->getConstantOperandVal(3));
2141
2142 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2143 Tmp2, MachinePointerInfo(V));
2144 SDValue VAList = VAListLoad;
2145
2146 if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2147 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2148 getConstant(MA->value() - 1, dl, VAList.getValueType()));
2149
2150 VAList =
2151 getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2152 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2153 }
2154
2155 // Increment the pointer, VAList, to the next vaarg
2156 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2157 getConstant(getDataLayout().getTypeAllocSize(
2158 VT.getTypeForEVT(*getContext())),
2159 dl, VAList.getValueType()));
2160 // Store the incremented VAList to the legalized pointer
2161 Tmp1 =
2162 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2163 // Load the actual argument out of the pointer VAList
2164 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2165}
2166
2167SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2168 SDLoc dl(Node);
2169 const TargetLowering &TLI = getTargetLoweringInfo();
2170 // This defaults to loading a pointer from the input and storing it to the
2171 // output, returning the chain.
2172 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2173 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2174 SDValue Tmp1 =
2175 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2176 Node->getOperand(2), MachinePointerInfo(VS));
2177 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2178 MachinePointerInfo(VD));
2179}
2180
2181Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2182 const DataLayout &DL = getDataLayout();
2183 Type *Ty = VT.getTypeForEVT(*getContext());
2184 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2185
2186 if (TLI->isTypeLegal(VT) || !VT.isVector())
2187 return RedAlign;
2188
2189 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2190 const Align StackAlign = TFI->getStackAlign();
2191
2192 // See if we can choose a smaller ABI alignment in cases where it's an
2193 // illegal vector type that will get broken down.
2194 if (RedAlign > StackAlign) {
2195 EVT IntermediateVT;
2196 MVT RegisterVT;
2197 unsigned NumIntermediates;
2198 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2199 NumIntermediates, RegisterVT);
2200 Ty = IntermediateVT.getTypeForEVT(*getContext());
2201 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2202 if (RedAlign2 < RedAlign)
2203 RedAlign = RedAlign2;
2204 }
2205
2206 return RedAlign;
2207}
2208
2209SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2210 MachineFrameInfo &MFI = MF->getFrameInfo();
2211 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2212 int StackID = 0;
2213 if (Bytes.isScalable())
2214 StackID = TFI->getStackIDForScalableVectors();
2215 // The stack id gives an indication of whether the object is scalable or
2216 // not, so it's safe to pass in the minimum size here.
2217 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2218 false, nullptr, StackID);
2219 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2220}
2221
2222SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2223 Type *Ty = VT.getTypeForEVT(*getContext());
2224 Align StackAlign =
2225 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2226 return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2227}
2228
2229SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2230 TypeSize VT1Size = VT1.getStoreSize();
2231 TypeSize VT2Size = VT2.getStoreSize();
2232 assert(VT1Size.isScalable() == VT2Size.isScalable() &&(static_cast<void> (0))
2233 "Don't know how to choose the maximum size when creating a stack "(static_cast<void> (0))
2234 "temporary")(static_cast<void> (0));
2235 TypeSize Bytes =
2236 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2237
2238 Type *Ty1 = VT1.getTypeForEVT(*getContext());
2239 Type *Ty2 = VT2.getTypeForEVT(*getContext());
2240 const DataLayout &DL = getDataLayout();
2241 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2242 return CreateStackTemporary(Bytes, Align);
2243}
2244
2245SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2246 ISD::CondCode Cond, const SDLoc &dl) {
2247 EVT OpVT = N1.getValueType();
2248
2249 // These setcc operations always fold.
2250 switch (Cond) {
2251 default: break;
2252 case ISD::SETFALSE:
2253 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2254 case ISD::SETTRUE:
2255 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2256
2257 case ISD::SETOEQ:
2258 case ISD::SETOGT:
2259 case ISD::SETOGE:
2260 case ISD::SETOLT:
2261 case ISD::SETOLE:
2262 case ISD::SETONE:
2263 case ISD::SETO:
2264 case ISD::SETUO:
2265 case ISD::SETUEQ:
2266 case ISD::SETUNE:
2267 assert(!OpVT.isInteger() && "Illegal setcc for integer!")(static_cast<void> (0));
2268 break;
2269 }
2270
2271 if (OpVT.isInteger()) {
2272 // For EQ and NE, we can always pick a value for the undef to make the
2273 // predicate pass or fail, so we can return undef.
2274 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2275 // icmp eq/ne X, undef -> undef.
2276 if ((N1.isUndef() || N2.isUndef()) &&
2277 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2278 return getUNDEF(VT);
2279
2280 // If both operands are undef, we can return undef for int comparison.
2281 // icmp undef, undef -> undef.
2282 if (N1.isUndef() && N2.isUndef())
2283 return getUNDEF(VT);
2284
2285 // icmp X, X -> true/false
2286 // icmp X, undef -> true/false because undef could be X.
2287 if (N1 == N2)
2288 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2289 }
2290
2291 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2292 const APInt &C2 = N2C->getAPIntValue();
2293 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2294 const APInt &C1 = N1C->getAPIntValue();
2295
2296 switch (Cond) {
2297 default: llvm_unreachable("Unknown integer setcc!")__builtin_unreachable();
2298 case ISD::SETEQ: return getBoolConstant(C1 == C2, dl, VT, OpVT);
2299 case ISD::SETNE: return getBoolConstant(C1 != C2, dl, VT, OpVT);
2300 case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
2301 case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
2302 case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
2303 case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
2304 case ISD::SETLT: return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
2305 case ISD::SETGT: return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
2306 case ISD::SETLE: return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
2307 case ISD::SETGE: return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
2308 }
2309 }
2310 }
2311
2312 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2313 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2314
2315 if (N1CFP && N2CFP) {
2316 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2317 switch (Cond) {
2318 default: break;
2319 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2320 return getUNDEF(VT);
2321 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2322 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2323 OpVT);
2324 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2325 return getUNDEF(VT);
2326 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2327 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2328 R==APFloat::cmpLessThan, dl, VT,
2329 OpVT);
2330 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2331 return getUNDEF(VT);
2332 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2333 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2334 OpVT);
2335 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2336 return getUNDEF(VT);
2337 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2338 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2339 VT, OpVT);
2340 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2341 return getUNDEF(VT);
2342 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2343 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2344 R==APFloat::cmpEqual, dl, VT,
2345 OpVT);
2346 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2347 return getUNDEF(VT);
2348 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2349 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2350 R==APFloat::cmpEqual, dl, VT, OpVT);
2351 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2352 OpVT);
2353 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2354 OpVT);
2355 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2356 R==APFloat::cmpEqual, dl, VT,
2357 OpVT);
2358 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2359 OpVT);
2360 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2361 R==APFloat::cmpLessThan, dl, VT,
2362 OpVT);
2363 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2364 R==APFloat::cmpUnordered, dl, VT,
2365 OpVT);
2366 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2367 VT, OpVT);
2368 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2369 OpVT);
2370 }
2371 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2372 // Ensure that the constant occurs on the RHS.
2373 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2374 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2375 return SDValue();
2376 return getSetCC(dl, VT, N2, N1, SwappedCond);
2377 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2378 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2379 // If an operand is known to be a nan (or undef that could be a nan), we can
2380 // fold it.
2381 // Choosing NaN for the undef will always make unordered comparison succeed
2382 // and ordered comparison fails.
2383 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2384 switch (ISD::getUnorderedFlavor(Cond)) {
2385 default:
2386 llvm_unreachable("Unknown flavor!")__builtin_unreachable();
2387 case 0: // Known false.
2388 return getBoolConstant(false, dl, VT, OpVT);
2389 case 1: // Known true.
2390 return getBoolConstant(true, dl, VT, OpVT);
2391 case 2: // Undefined.
2392 return getUNDEF(VT);
2393 }
2394 }
2395
2396 // Could not fold it.
2397 return SDValue();
2398}
2399
2400/// See if the specified operand can be simplified with the knowledge that only
2401/// the bits specified by DemandedBits are used.
2402/// TODO: really we should be making this into the DAG equivalent of
2403/// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2404SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2405 EVT VT = V.getValueType();
2406
2407 if (VT.isScalableVector())
2408 return SDValue();
2409
2410 APInt DemandedElts = VT.isVector()
2411 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2412 : APInt(1, 1);
2413 return GetDemandedBits(V, DemandedBits, DemandedElts);
2414}
2415
2416/// See if the specified operand can be simplified with the knowledge that only
2417/// the bits specified by DemandedBits are used in the elements specified by
2418/// DemandedElts.
2419/// TODO: really we should be making this into the DAG equivalent of
2420/// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2421SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2422 const APInt &DemandedElts) {
2423 switch (V.getOpcode()) {
2424 default:
2425 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2426 *this, 0);
2427 case ISD::Constant: {
2428 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2429 APInt NewVal = CVal & DemandedBits;
2430 if (NewVal != CVal)
2431 return getConstant(NewVal, SDLoc(V), V.getValueType());
2432 break;
2433 }
2434 case ISD::SRL:
2435 // Only look at single-use SRLs.
2436 if (!V.getNode()->hasOneUse())
2437 break;
2438 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2439 // See if we can recursively simplify the LHS.
2440 unsigned Amt = RHSC->getZExtValue();
2441
2442 // Watch out for shift count overflow though.
2443 if (Amt >= DemandedBits.getBitWidth())
2444 break;
2445 APInt SrcDemandedBits = DemandedBits << Amt;
2446 if (SDValue SimplifyLHS =
2447 GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2448 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2449 V.getOperand(1));
2450 }
2451 break;
2452 }
2453 return SDValue();
2454}
2455
2456/// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2457/// use this predicate to simplify operations downstream.
2458bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2459 unsigned BitWidth = Op.getScalarValueSizeInBits();
2460 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2461}
2462
2463/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2464/// this predicate to simplify operations downstream. Mask is known to be zero
2465/// for bits that V cannot have.
2466bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2467 unsigned Depth) const {
2468 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2469}
2470
2471/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2472/// DemandedElts. We use this predicate to simplify operations downstream.
2473/// Mask is known to be zero for bits that V cannot have.
2474bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2475 const APInt &DemandedElts,
2476 unsigned Depth) const {
2477 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2478}
2479
2480/// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2481bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2482 unsigned Depth) const {
2483 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2484}
2485
2486/// isSplatValue - Return true if the vector V has the same value
2487/// across all DemandedElts. For scalable vectors it does not make
2488/// sense to specify which elements are demanded or undefined, therefore
2489/// they are simply ignored.
2490bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2491 APInt &UndefElts, unsigned Depth) {
2492 EVT VT = V.getValueType();
2493 assert(VT.isVector() && "Vector type expected")(static_cast<void> (0));
2494
2495 if (!VT.isScalableVector() && !DemandedElts)
2496 return false; // No demanded elts, better to assume we don't know anything.
2497
2498 if (Depth >= MaxRecursionDepth)
2499 return false; // Limit search depth.
2500
2501 // Deal with some common cases here that work for both fixed and scalable
2502 // vector types.
2503 switch (V.getOpcode()) {
2504 case ISD::SPLAT_VECTOR:
2505 UndefElts = V.getOperand(0).isUndef()
2506 ? APInt::getAllOnesValue(DemandedElts.getBitWidth())
2507 : APInt(DemandedElts.getBitWidth(), 0);
2508 return true;
2509 case ISD::ADD:
2510 case ISD::SUB:
2511 case ISD::AND:
2512 case ISD::XOR:
2513 case ISD::OR: {
2514 APInt UndefLHS, UndefRHS;
2515 SDValue LHS = V.getOperand(0);
2516 SDValue RHS = V.getOperand(1);
2517 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2518 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2519 UndefElts = UndefLHS | UndefRHS;
2520 return true;
2521 }
2522 return false;
2523 }
2524 case ISD::ABS:
2525 case ISD::TRUNCATE:
2526 case ISD::SIGN_EXTEND:
2527 case ISD::ZERO_EXTEND:
2528 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2529 }
2530
2531 // We don't support other cases than those above for scalable vectors at
2532 // the moment.
2533 if (VT.isScalableVector())
2534 return false;
2535
2536 unsigned NumElts = VT.getVectorNumElements();
2537 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch")(static_cast<void> (0));
2538 UndefElts = APInt::getNullValue(NumElts);
2539
2540 switch (V.getOpcode()) {
2541 case ISD::BUILD_VECTOR: {
2542 SDValue Scl;
2543 for (unsigned i = 0; i != NumElts; ++i) {
2544 SDValue Op = V.getOperand(i);
2545 if (Op.isUndef()) {
2546 UndefElts.setBit(i);
2547 continue;
2548 }
2549 if (!DemandedElts[i])
2550 continue;
2551 if (Scl && Scl != Op)
2552 return false;
2553 Scl = Op;
2554 }
2555 return true;
2556 }
2557 case ISD::VECTOR_SHUFFLE: {
2558 // Check if this is a shuffle node doing a splat.
2559 // TODO: Do we need to handle shuffle(splat, undef, mask)?
2560 int SplatIndex = -1;
2561 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2562 for (int i = 0; i != (int)NumElts; ++i) {
2563 int M = Mask[i];
2564 if (M < 0) {
2565 UndefElts.setBit(i);
2566 continue;
2567 }
2568 if (!DemandedElts[i])
2569 continue;
2570 if (0 <= SplatIndex && SplatIndex != M)
2571 return false;
2572 SplatIndex = M;
2573 }
2574 return true;
2575 }
2576 case ISD::EXTRACT_SUBVECTOR: {
2577 // Offset the demanded elts by the subvector index.
2578 SDValue Src = V.getOperand(0);
2579 // We don't support scalable vectors at the moment.
2580 if (Src.getValueType().isScalableVector())
2581 return false;
2582 uint64_t Idx = V.getConstantOperandVal(1);
2583 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2584 APInt UndefSrcElts;
2585 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2586 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2587 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2588 return true;
2589 }
2590 break;
2591 }
2592 }
2593
2594 return false;
2595}
2596
2597/// Helper wrapper to main isSplatValue function.
2598bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2599 EVT VT = V.getValueType();
2600 assert(VT.isVector() && "Vector type expected")(static_cast<void> (0));
2601
2602 APInt UndefElts;
2603 APInt DemandedElts;
2604
2605 // For now we don't support this with scalable vectors.
2606 if (!VT.isScalableVector())
2607 DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2608 return isSplatValue(V, DemandedElts, UndefElts) &&
2609 (AllowUndefs || !UndefElts);
2610}
2611
2612SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2613 V = peekThroughExtractSubvectors(V);
2614
2615 EVT VT = V.getValueType();
2616 unsigned Opcode = V.getOpcode();
2617 switch (Opcode) {
2618 default: {
2619 APInt UndefElts;
2620 APInt DemandedElts;
2621
2622 if (!VT.isScalableVector())
2623 DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2624
2625 if (isSplatValue(V, DemandedElts, UndefElts)) {
2626 if (VT.isScalableVector()) {
2627 // DemandedElts and UndefElts are ignored for scalable vectors, since
2628 // the only supported cases are SPLAT_VECTOR nodes.
2629 SplatIdx = 0;
2630 } else {
2631 // Handle case where all demanded elements are UNDEF.
2632 if (DemandedElts.isSubsetOf(UndefElts)) {
2633 SplatIdx = 0;
2634 return getUNDEF(VT);
2635 }
2636 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2637 }
2638 return V;
2639 }
2640 break;
2641 }
2642 case ISD::SPLAT_VECTOR:
2643 SplatIdx = 0;
2644 return V;
2645 case ISD::VECTOR_SHUFFLE: {
2646 if (VT.isScalableVector())
2647 return SDValue();
2648
2649 // Check if this is a shuffle node doing a splat.
2650 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2651 // getTargetVShiftNode currently struggles without the splat source.
2652 auto *SVN = cast<ShuffleVectorSDNode>(V);
2653 if (!SVN->isSplat())
2654 break;
2655 int Idx = SVN->getSplatIndex();
2656 int NumElts = V.getValueType().getVectorNumElements();
2657 SplatIdx = Idx % NumElts;
2658 return V.getOperand(Idx / NumElts);
2659 }
2660 }
2661
2662 return SDValue();
2663}
2664
2665SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2666 int SplatIdx;
2667 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2668 EVT SVT = SrcVector.getValueType().getScalarType();
2669 EVT LegalSVT = SVT;
2670 if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2671 if (!SVT.isInteger())
2672 return SDValue();
2673 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2674 if (LegalSVT.bitsLT(SVT))
2675 return SDValue();
2676 }
2677 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2678 getVectorIdxConstant(SplatIdx, SDLoc(V)));
2679 }
2680 return SDValue();
2681}
2682
2683const APInt *
2684SelectionDAG::getValidShiftAmountConstant(SDValue V,
2685 const APInt &DemandedElts) const {
2686 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||(static_cast<void> (0))
2687 V.getOpcode() == ISD::SRA) &&(static_cast<void> (0))
2688 "Unknown shift node")(static_cast<void> (0));
2689 unsigned BitWidth = V.getScalarValueSizeInBits();
2690 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2691 // Shifting more than the bitwidth is not valid.
2692 const APInt &ShAmt = SA->getAPIntValue();
2693 if (ShAmt.ult(BitWidth))
2694 return &ShAmt;
2695 }
2696 return nullptr;
2697}
2698
2699const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2700 SDValue V, const APInt &DemandedElts) const {
2701 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||(static_cast<void> (0))
2702 V.getOpcode() == ISD::SRA) &&(static_cast<void> (0))
2703 "Unknown shift node")(static_cast<void> (0));
2704 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2705 return ValidAmt;
2706 unsigned BitWidth = V.getScalarValueSizeInBits();
2707 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2708 if (!BV)
2709 return nullptr;
2710 const APInt *MinShAmt = nullptr;
2711 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2712 if (!DemandedElts[i])
2713 continue;
2714 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2715 if (!SA)
2716 return nullptr;
2717 // Shifting more than the bitwidth is not valid.
2718 const APInt &ShAmt = SA->getAPIntValue();
2719 if (ShAmt.uge(BitWidth))
2720 return nullptr;
2721 if (MinShAmt && MinShAmt->ule(ShAmt))
2722 continue;
2723 MinShAmt = &ShAmt;
2724 }
2725 return MinShAmt;
2726}
2727
2728const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2729 SDValue V, const APInt &DemandedElts) const {
2730 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||(static_cast<void> (0))
2731 V.getOpcode() == ISD::SRA) &&(static_cast<void> (0))
2732 "Unknown shift node")(static_cast<void> (0));
2733 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2734 return ValidAmt;
2735 unsigned BitWidth = V.getScalarValueSizeInBits();
2736 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2737 if (!BV)
2738 return nullptr;
2739 const APInt *MaxShAmt = nullptr;
2740 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2741 if (!DemandedElts[i])
2742 continue;
2743 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2744 if (!SA)
2745 return nullptr;
2746 // Shifting more than the bitwidth is not valid.
2747 const APInt &ShAmt = SA->getAPIntValue();
2748 if (ShAmt.uge(BitWidth))
2749 return nullptr;
2750 if (MaxShAmt && MaxShAmt->uge(ShAmt))
2751 continue;
2752 MaxShAmt = &ShAmt;
2753 }
2754 return MaxShAmt;
2755}
2756
2757/// Determine which bits of Op are known to be either zero or one and return
2758/// them in Known. For vectors, the known bits are those that are shared by
2759/// every vector element.
2760KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2761 EVT VT = Op.getValueType();
2762
2763 // TOOD: Until we have a plan for how to represent demanded elements for
2764 // scalable vectors, we can just bail out for now.
2765 if (Op.getValueType().isScalableVector()) {
2766 unsigned BitWidth = Op.getScalarValueSizeInBits();
2767 return KnownBits(BitWidth);
2768 }
2769
2770 APInt DemandedElts = VT.isVector()
2771 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2772 : APInt(1, 1);
2773 return computeKnownBits(Op, DemandedElts, Depth);
2774}
2775
2776/// Determine which bits of Op are known to be either zero or one and return
2777/// them in Known. The DemandedElts argument allows us to only collect the known
2778/// bits that are shared by the requested vector elements.
2779KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2780 unsigned Depth) const {
2781 unsigned BitWidth = Op.getScalarValueSizeInBits();
2782
2783 KnownBits Known(BitWidth); // Don't know anything.
2784
2785 // TOOD: Until we have a plan for how to represent demanded elements for
2786 // scalable vectors, we can just bail out for now.
2787 if (Op.getValueType().isScalableVector())
2788 return Known;
2789
2790 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2791 // We know all of the bits for a constant!
2792 return KnownBits::makeConstant(C->getAPIntValue());
2793 }
2794 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2795 // We know all of the bits for a constant fp!
2796 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2797 }
2798
2799 if (Depth >= MaxRecursionDepth)
2800 return Known; // Limit search depth.
2801
2802 KnownBits Known2;
2803 unsigned NumElts = DemandedElts.getBitWidth();
2804 assert((!Op.getValueType().isVector() ||(static_cast<void> (0))
2805 NumElts == Op.getValueType().getVectorNumElements()) &&(static_cast<void> (0))
2806 "Unexpected vector size")(static_cast<void> (0));
2807
2808 if (!DemandedElts)
2809 return Known; // No demanded elts, better to assume we don't know anything.
2810
2811 unsigned Opcode = Op.getOpcode();
2812 switch (Opcode) {
2813 case ISD::BUILD_VECTOR:
2814 // Collect the known bits that are shared by every demanded vector element.
2815 Known.Zero.setAllBits(); Known.One.setAllBits();
2816 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2817 if (!DemandedElts[i])
2818 continue;
2819
2820 SDValue SrcOp = Op.getOperand(i);
2821 Known2 = computeKnownBits(SrcOp, Depth + 1);
2822
2823 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2824 if (SrcOp.getValueSizeInBits() != BitWidth) {
2825 assert(SrcOp.getValueSizeInBits() > BitWidth &&(static_cast<void> (0))
2826 "Expected BUILD_VECTOR implicit truncation")(static_cast<void> (0));
2827 Known2 = Known2.trunc(BitWidth);
2828 }
2829
2830 // Known bits are the values that are shared by every demanded element.
2831 Known = KnownBits::commonBits(Known, Known2);
2832
2833 // If we don't know any bits, early out.
2834 if (Known.isUnknown())
2835 break;
2836 }
2837 break;
2838 case ISD::VECTOR_SHUFFLE: {
2839 // Collect the known bits that are shared by every vector element referenced
2840 // by the shuffle.
2841 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2842 Known.Zero.setAllBits(); Known.One.setAllBits();
2843 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2844 assert(NumElts == SVN->getMask().size() && "Unexpected vector size")(static_cast<void> (0));
2845 for (unsigned i = 0; i != NumElts; ++i) {
2846 if (!DemandedElts[i])
2847 continue;
2848
2849 int M = SVN->getMaskElt(i);
2850 if (M < 0) {
2851 // For UNDEF elements, we don't know anything about the common state of
2852 // the shuffle result.
2853 Known.resetAll();
2854 DemandedLHS.clearAllBits();
2855 DemandedRHS.clearAllBits();
2856 break;
2857 }
2858
2859 if ((unsigned)M < NumElts)
2860 DemandedLHS.setBit((unsigned)M % NumElts);
2861 else
2862 DemandedRHS.setBit((unsigned)M % NumElts);
2863 }
2864 // Known bits are the values that are shared by every demanded element.
2865 if (!!DemandedLHS) {
2866 SDValue LHS = Op.getOperand(0);
2867 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2868 Known = KnownBits::commonBits(Known, Known2);
2869 }
2870 // If we don't know any bits, early out.
2871 if (Known.isUnknown())
2872 break;
2873 if (!!DemandedRHS) {
2874 SDValue RHS = Op.getOperand(1);
2875 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2876 Known = KnownBits::commonBits(Known, Known2);
2877 }
2878 break;
2879 }
2880 case ISD::CONCAT_VECTORS: {
2881 // Split DemandedElts and test each of the demanded subvectors.
2882 Known.Zero.setAllBits(); Known.One.setAllBits();
2883 EVT SubVectorVT = Op.getOperand(0).getValueType();
2884 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2885 unsigned NumSubVectors = Op.getNumOperands();
2886 for (unsigned i = 0; i != NumSubVectors; ++i) {
2887 APInt DemandedSub =
2888 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
2889 if (!!DemandedSub) {
2890 SDValue Sub = Op.getOperand(i);
2891 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2892 Known = KnownBits::commonBits(Known, Known2);
2893 }
2894 // If we don't know any bits, early out.
2895 if (Known.isUnknown())
2896 break;
2897 }
2898 break;
2899 }
2900 case ISD::INSERT_SUBVECTOR: {
2901 // Demand any elements from the subvector and the remainder from the src its
2902 // inserted into.
2903 SDValue Src = Op.getOperand(0);
2904 SDValue Sub = Op.getOperand(1);
2905 uint64_t Idx = Op.getConstantOperandVal(2);
2906 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2907 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2908 APInt DemandedSrcElts = DemandedElts;
2909 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
2910
2911 Known.One.setAllBits();
2912 Known.Zero.setAllBits();
2913 if (!!DemandedSubElts) {
2914 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2915 if (Known.isUnknown())
2916 break; // early-out.
2917 }
2918 if (!!DemandedSrcElts) {
2919 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2920 Known = KnownBits::commonBits(Known, Known2);
2921 }
2922 break;
2923 }
2924 case ISD::EXTRACT_SUBVECTOR: {
2925 // Offset the demanded elts by the subvector index.
2926 SDValue Src = Op.getOperand(0);
2927 // Bail until we can represent demanded elements for scalable vectors.
2928 if (Src.getValueType().isScalableVector())
2929 break;
2930 uint64_t Idx = Op.getConstantOperandVal(1);
2931 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2932 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2933 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2934 break;
2935 }
2936 case ISD::SCALAR_TO_VECTOR: {
2937 // We know about scalar_to_vector as much as we know about it source,
2938 // which becomes the first element of otherwise unknown vector.
2939 if (DemandedElts != 1)
2940 break;
2941
2942 SDValue N0 = Op.getOperand(0);
2943 Known = computeKnownBits(N0, Depth + 1);
2944 if (N0.getValueSizeInBits() != BitWidth)
2945 Known = Known.trunc(BitWidth);
2946
2947 break;
2948 }
2949 case ISD::BITCAST: {
2950 SDValue N0 = Op.getOperand(0);
2951 EVT SubVT = N0.getValueType();
2952 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2953
2954 // Ignore bitcasts from unsupported types.
2955 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2956 break;
2957
2958 // Fast handling of 'identity' bitcasts.
2959 if (BitWidth == SubBitWidth) {
2960 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2961 break;
2962 }
2963
2964 bool IsLE = getDataLayout().isLittleEndian();
2965
2966 // Bitcast 'small element' vector to 'large element' scalar/vector.
2967 if ((BitWidth % SubBitWidth) == 0) {
2968 assert(N0.getValueType().isVector() && "Expected bitcast from vector")(static_cast<void> (0));
2969
2970 // Collect known bits for the (larger) output by collecting the known
2971 // bits from each set of sub elements and shift these into place.
2972 // We need to separately call computeKnownBits for each set of
2973 // sub elements as the knownbits for each is likely to be different.
2974 unsigned SubScale = BitWidth / SubBitWidth;
2975 APInt SubDemandedElts(NumElts * SubScale, 0);
2976 for (unsigned i = 0; i != NumElts; ++i)
2977 if (DemandedElts[i])
2978 SubDemandedElts.setBit(i * SubScale);
2979
2980 for (unsigned i = 0; i != SubScale; ++i) {
2981 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2982 Depth + 1);
2983 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2984 Known.insertBits(Known2, SubBitWidth * Shifts);
2985 }
2986 }
2987
2988 // Bitcast 'large element' scalar/vector to 'small element' vector.
2989 if ((SubBitWidth % BitWidth) == 0) {
2990 assert(Op.getValueType().isVector() && "Expected bitcast to vector")(static_cast<void> (0));
2991
2992 // Collect known bits for the (smaller) output by collecting the known
2993 // bits from the overlapping larger input elements and extracting the
2994 // sub sections we actually care about.
2995 unsigned SubScale = SubBitWidth / BitWidth;
2996 APInt SubDemandedElts(NumElts / SubScale, 0);
2997 for (unsigned i = 0; i != NumElts; ++i)
2998 if (DemandedElts[i])
2999 SubDemandedElts.setBit(i / SubScale);
3000
3001 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3002
3003 Known.Zero.setAllBits(); Known.One.setAllBits();
3004 for (unsigned i = 0; i != NumElts; ++i)
3005 if (DemandedElts[i]) {
3006 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3007 unsigned Offset = (Shifts % SubScale) * BitWidth;
3008 Known = KnownBits::commonBits(Known,
3009 Known2.extractBits(BitWidth, Offset));
3010 // If we don't know any bits, early out.
3011 if (Known.isUnknown())
3012 break;
3013 }
3014 }
3015 break;
3016 }
3017 case ISD::AND:
3018 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3019 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3020
3021 Known &= Known2;
3022 break;
3023 case ISD::OR:
3024 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3025 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3026
3027 Known |= Known2;
3028 break;
3029 case ISD::XOR:
3030 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3031 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3032
3033 Known ^= Known2;
3034 break;
3035 case ISD::MUL: {
3036 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3037 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3038 Known = KnownBits::mul(Known, Known2);
3039 break;
3040 }
3041 case ISD::MULHU: {
3042 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3043 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3044 Known = KnownBits::mulhu(Known, Known2);
3045 break;
3046 }
3047 case ISD::MULHS: {
3048 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3049 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3050 Known = KnownBits::mulhs(Known, Known2);
3051 break;
3052 }
3053 case ISD::UMUL_LOHI: {
3054 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result")(static_cast<void> (0));
3055 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3056 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3057 if (Op.getResNo() == 0)
3058 Known = KnownBits::mul(Known, Known2);
3059 else
3060 Known = KnownBits::mulhu(Known, Known2);
3061 break;
3062 }
3063 case ISD::SMUL_LOHI: {
3064 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result")(static_cast<void> (0));
3065 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3066 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3067 if (Op.getResNo() == 0)
3068 Known = KnownBits::mul(Known, Known2);
3069 else
3070 Known = KnownBits::mulhs(Known, Known2);
3071 break;
3072 }
3073 case ISD::UDIV: {
3074 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3075 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3076 Known = KnownBits::udiv(Known, Known2);
3077 break;
3078 }
3079 case ISD::SELECT:
3080 case ISD::VSELECT:
3081 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3082 // If we don't know any bits, early out.
3083 if (Known.isUnknown())
3084 break;
3085 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3086
3087 // Only known if known in both the LHS and RHS.
3088 Known = KnownBits::commonBits(Known, Known2);
3089 break;
3090 case ISD::SELECT_CC:
3091 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3092 // If we don't know any bits, early out.
3093 if (Known.isUnknown())
3094 break;
3095 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3096
3097 // Only known if known in both the LHS and RHS.
3098 Known = KnownBits::commonBits(Known, Known2);
3099 break;
3100 case ISD::SMULO:
3101 case ISD::UMULO:
3102 if (Op.getResNo() != 1)
3103 break;
3104 // The boolean result conforms to getBooleanContents.
3105 // If we know the result of a setcc has the top bits zero, use this info.
3106 // We know that we have an integer-based boolean since these operations
3107 // are only available for integer.
3108 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3109 TargetLowering::ZeroOrOneBooleanContent &&
3110 BitWidth > 1)
3111 Known.Zero.setBitsFrom(1);
3112 break;
3113 case ISD::SETCC:
3114 case ISD::STRICT_FSETCC:
3115 case ISD::STRICT_FSETCCS: {
3116 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3117 // If we know the result of a setcc has the top bits zero, use this info.
3118 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3119 TargetLowering::ZeroOrOneBooleanContent &&
3120 BitWidth > 1)
3121 Known.Zero.setBitsFrom(1);
3122 break;
3123 }
3124 case ISD::SHL:
3125 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3126 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3127 Known = KnownBits::shl(Known, Known2);
3128
3129 // Minimum shift low bits are known zero.
3130 if (const APInt *ShMinAmt =
3131 getValidMinimumShiftAmountConstant(Op, DemandedElts))
3132 Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3133 break;
3134 case ISD::SRL:
3135 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3136 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3137 Known = KnownBits::lshr(Known, Known2);
3138
3139 // Minimum shift high bits are known zero.
3140 if (const APInt *ShMinAmt =
3141 getValidMinimumShiftAmountConstant(Op, DemandedElts))
3142 Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3143 break;
3144 case ISD::SRA:
3145 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3146 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3147 Known = KnownBits::ashr(Known, Known2);
3148 // TODO: Add minimum shift high known sign bits.
3149 break;
3150 case ISD::FSHL:
3151 case ISD::FSHR:
3152 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3153 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3154
3155 // For fshl, 0-shift returns the 1st arg.
3156 // For fshr, 0-shift returns the 2nd arg.
3157 if (Amt == 0) {
3158 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3159 DemandedElts, Depth + 1);
3160 break;
3161 }
3162
3163 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3164 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3165 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3166 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3167 if (Opcode == ISD::FSHL) {
3168 Known.One <<= Amt;
3169 Known.Zero <<= Amt;
3170 Known2.One.lshrInPlace(BitWidth - Amt);
3171 Known2.Zero.lshrInPlace(BitWidth - Amt);
3172 } else {
3173 Known.One <<= BitWidth - Amt;
3174 Known.Zero <<= BitWidth - Amt;
3175 Known2.One.lshrInPlace(Amt);
3176 Known2.Zero.lshrInPlace(Amt);
3177 }
3178 Known.One |= Known2.One;
3179 Known.Zero |= Known2.Zero;
3180 }
3181 break;
3182 case ISD::SIGN_EXTEND_INREG: {
3183 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3184 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3185 Known = Known.sextInReg(EVT.getScalarSizeInBits());
3186 break;
3187 }
3188 case ISD::CTTZ:
3189 case ISD::CTTZ_ZERO_UNDEF: {
3190 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3191 // If we have a known 1, its position is our upper bound.
3192 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3193 unsigned LowBits = Log2_32(PossibleTZ) + 1;
3194 Known.Zero.setBitsFrom(LowBits);
3195 break;
3196 }
3197 case ISD::CTLZ:
3198 case ISD::CTLZ_ZERO_UNDEF: {
3199 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3200 // If we have a known 1, its position is our upper bound.
3201 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3202 unsigned LowBits = Log2_32(PossibleLZ) + 1;
3203 Known.Zero.setBitsFrom(LowBits);
3204 break;
3205 }
3206 case ISD::CTPOP: {
3207 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3208 // If we know some of the bits are zero, they can't be one.
3209 unsigned PossibleOnes = Known2.countMaxPopulation();
3210 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3211 break;
3212 }
3213 case ISD::PARITY: {
3214 // Parity returns 0 everywhere but the LSB.
3215 Known.Zero.setBitsFrom(1);
3216 break;
3217 }
3218 case ISD::LOAD: {
3219 LoadSDNode *LD = cast<LoadSDNode>(Op);
3220 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3221 if (ISD::isNON_EXTLoad(LD) && Cst) {
3222 // Determine any common known bits from the loaded constant pool value.
3223 Type *CstTy = Cst->getType();
3224 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3225 // If its a vector splat, then we can (quickly) reuse the scalar path.
3226 // NOTE: We assume all elements match and none are UNDEF.
3227 if (CstTy->isVectorTy()) {
3228 if (const Constant *Splat = Cst->getSplatValue()) {
3229 Cst = Splat;
3230 CstTy = Cst->getType();
3231 }
3232 }
3233 // TODO - do we need to handle different bitwidths?
3234 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3235 // Iterate across all vector elements finding common known bits.
3236 Known.One.setAllBits();
3237 Known.Zero.setAllBits();
3238 for (unsigned i = 0; i != NumElts; ++i) {
3239 if (!DemandedElts[i])
3240 continue;
3241 if (Constant *Elt = Cst->getAggregateElement(i)) {
3242 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3243 const APInt &Value = CInt->getValue();
3244 Known.One &= Value;
3245 Known.Zero &= ~Value;
3246 continue;
3247 }
3248 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3249 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3250 Known.One &= Value;
3251 Known.Zero &= ~Value;
3252 continue;
3253 }
3254 }
3255 Known.One.clearAllBits();
3256 Known.Zero.clearAllBits();
3257 break;
3258 }
3259 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3260 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3261 Known = KnownBits::makeConstant(CInt->getValue());
3262 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3263 Known =
3264 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3265 }
3266 }
3267 }
3268 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3269 // If this is a ZEXTLoad and we are looking at the loaded value.
3270 EVT VT = LD->getMemoryVT();
3271 unsigned MemBits = VT.getScalarSizeInBits();
3272 Known.Zero.setBitsFrom(MemBits);
3273 } else if (const MDNode *Ranges = LD->getRanges()) {
3274 if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3275 computeKnownBitsFromRangeMetadata(*Ranges, Known);
3276 }
3277 break;
3278 }
3279 case ISD::ZERO_EXTEND_VECTOR_INREG: {
3280 EVT InVT = Op.getOperand(0).getValueType();
3281 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3282 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3283 Known = Known.zext(BitWidth);
3284 break;
3285 }
3286 case ISD::ZERO_EXTEND: {
3287 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3288 Known = Known.zext(BitWidth);
3289 break;
3290 }
3291 case ISD::SIGN_EXTEND_VECTOR_INREG: {
3292 EVT InVT = Op.getOperand(0).getValueType();
3293 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3294 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3295 // If the sign bit is known to be zero or one, then sext will extend
3296 // it to the top bits, else it will just zext.
3297 Known = Known.sext(BitWidth);
3298 break;
3299 }
3300 case ISD::SIGN_EXTEND: {
3301 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3302 // If the sign bit is known to be zero or one, then sext will extend
3303 // it to the top bits, else it will just zext.
3304 Known = Known.sext(BitWidth);
3305 break;
3306 }
3307 case ISD::ANY_EXTEND_VECTOR_INREG: {
3308 EVT InVT = Op.getOperand(0).getValueType();
3309 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3310 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3311 Known = Known.anyext(BitWidth);
3312 break;
3313 }
3314 case ISD::ANY_EXTEND: {
3315 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3316 Known = Known.anyext(BitWidth);
3317 break;
3318 }
3319 case ISD::TRUNCATE: {
3320 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3321 Known = Known.trunc(BitWidth);
3322 break;
3323 }
3324 case ISD::AssertZext: {
3325 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3326 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3327 Known = computeKnownBits(Op.getOperand(0), Depth+1);
3328 Known.Zero |= (~InMask);
3329 Known.One &= (~Known.Zero);
3330 break;
3331 }
3332 case ISD::AssertAlign: {
3333 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3334 assert(LogOfAlign != 0)(static_cast<void> (0));
3335 // If a node is guaranteed to be aligned, set low zero bits accordingly as
3336 // well as clearing one bits.
3337 Known.Zero.setLowBits(LogOfAlign);
3338 Known.One.clearLowBits(LogOfAlign);
3339 break;
3340 }
3341 case ISD::FGETSIGN:
3342 // All bits are zero except the low bit.
3343 Known.Zero.setBitsFrom(1);
3344 break;
3345 case ISD::USUBO:
3346 case ISD::SSUBO:
3347 if (Op.getResNo() == 1) {
3348 // If we know the result of a setcc has the top bits zero, use this info.
3349 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3350 TargetLowering::ZeroOrOneBooleanContent &&
3351 BitWidth > 1)
3352 Known.Zero.setBitsFrom(1);
3353 break;
3354 }
3355 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3356 case ISD::SUB:
3357 case ISD::SUBC: {
3358 assert(Op.getResNo() == 0 &&(static_cast<void> (0))
3359 "We only compute knownbits for the difference here.")(static_cast<void> (0));
3360
3361 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3362 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3363 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3364 Known, Known2);
3365 break;
3366 }
3367 case ISD::UADDO:
3368 case ISD::SADDO:
3369 case ISD::ADDCARRY:
3370 if (Op.getResNo() == 1) {
3371 // If we know the result of a setcc has the top bits zero, use this info.
3372 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3373 TargetLowering::ZeroOrOneBooleanContent &&
3374 BitWidth > 1)
3375 Known.Zero.setBitsFrom(1);
3376 break;
3377 }
3378 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3379 case ISD::ADD:
3380 case ISD::ADDC:
3381 case ISD::ADDE: {
3382 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.")(static_cast<void> (0));
3383
3384 // With ADDE and ADDCARRY, a carry bit may be added in.
3385 KnownBits Carry(1);
3386 if (Opcode == ISD::ADDE)
3387 // Can't track carry from glue, set carry to unknown.
3388 Carry.resetAll();
3389 else if (Opcode == ISD::ADDCARRY)
3390 // TODO: Compute known bits for the carry operand. Not sure if it is worth
3391 // the trouble (how often will we find a known carry bit). And I haven't
3392 // tested this very much yet, but something like this might work:
3393 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3394 // Carry = Carry.zextOrTrunc(1, false);
3395 Carry.resetAll();
3396 else
3397 Carry.setAllZero();
3398
3399 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3400 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3401 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3402 break;
3403 }
3404 case ISD::SREM: {
3405 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3406 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3407 Known = KnownBits::srem(Known, Known2);
3408 break;
3409 }
3410 case ISD::UREM: {
3411 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3412 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3413 Known = KnownBits::urem(Known, Known2);
3414 break;
3415 }
3416 case ISD::EXTRACT_ELEMENT: {
3417 Known = computeKnownBits(Op.getOperand(0), Depth+1);
3418 const unsigned Index = Op.getConstantOperandVal(1);
3419 const unsigned EltBitWidth = Op.getValueSizeInBits();
3420
3421 // Remove low part of known bits mask
3422 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3423 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3424
3425 // Remove high part of known bit mask
3426 Known = Known.trunc(EltBitWidth);
3427 break;
3428 }
3429 case ISD::EXTRACT_VECTOR_ELT: {
3430 SDValue InVec = Op.getOperand(0);
3431 SDValue EltNo = Op.getOperand(1);
3432 EVT VecVT = InVec.getValueType();
3433 // computeKnownBits not yet implemented for scalable vectors.
3434 if (VecVT.isScalableVector())
3435 break;
3436 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3437 const unsigned NumSrcElts = VecVT.getVectorNumElements();
3438
3439 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3440 // anything about the extended bits.
3441 if (BitWidth > EltBitWidth)
3442 Known = Known.trunc(EltBitWidth);
3443
3444 // If we know the element index, just demand that vector element, else for
3445 // an unknown element index, ignore DemandedElts and demand them all.
3446 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3447 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3448 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3449 DemandedSrcElts =
3450 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3451
3452 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3453 if (BitWidth > EltBitWidth)
3454 Known = Known.anyext(BitWidth);
3455 break;
3456 }
3457 case ISD::INSERT_VECTOR_ELT: {
3458 // If we know the element index, split the demand between the
3459 // source vector and the inserted element, otherwise assume we need
3460 // the original demanded vector elements and the value.
3461 SDValue InVec = Op.getOperand(0);
3462 SDValue InVal = Op.getOperand(1);
3463 SDValue EltNo = Op.getOperand(2);
3464 bool DemandedVal = true;
3465 APInt DemandedVecElts = DemandedElts;
3466 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3467 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3468 unsigned EltIdx = CEltNo->getZExtValue();
3469 DemandedVal = !!DemandedElts[EltIdx];
3470 DemandedVecElts.clearBit(EltIdx);
3471 }
3472 Known.One.setAllBits();
3473 Known.Zero.setAllBits();
3474 if (DemandedVal) {
3475 Known2 = computeKnownBits(InVal, Depth + 1);
3476 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3477 }
3478 if (!!DemandedVecElts) {
3479 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3480 Known = KnownBits::commonBits(Known, Known2);
3481 }
3482 break;
3483 }
3484 case ISD::BITREVERSE: {
3485 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3486 Known = Known2.reverseBits();
3487 break;
3488 }
3489 case ISD::BSWAP: {
3490 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3491 Known = Known2.byteSwap();
3492 break;
3493 }
3494 case ISD::ABS: {
3495 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3496 Known = Known2.abs();
3497 break;
3498 }
3499 case ISD::USUBSAT: {
3500 // The result of usubsat will never be larger than the LHS.
3501 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3502 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3503 break;
3504 }
3505 case ISD::UMIN: {
3506 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3507 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3508 Known = KnownBits::umin(Known, Known2);
3509 break;
3510 }
3511 case ISD::UMAX: {
3512 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3513 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3514 Known = KnownBits::umax(Known, Known2);
3515 break;
3516 }
3517 case ISD::SMIN:
3518 case ISD::SMAX: {
3519 // If we have a clamp pattern, we know that the number of sign bits will be
3520 // the minimum of the clamp min/max range.
3521 bool IsMax = (Opcode == ISD::SMAX);
3522 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3523 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3524 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3525 CstHigh =
3526 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3527 if (CstLow && CstHigh) {
3528 if (!IsMax)
3529 std::swap(CstLow, CstHigh);
3530
3531 const APInt &ValueLow = CstLow->getAPIntValue();
3532 const APInt &ValueHigh = CstHigh->getAPIntValue();
3533 if (ValueLow.sle(ValueHigh)) {
3534 unsigned LowSignBits = ValueLow.getNumSignBits();
3535 unsigned HighSignBits = ValueHigh.getNumSignBits();
3536 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3537 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3538 Known.One.setHighBits(MinSignBits);
3539 break;
3540 }
3541 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3542 Known.Zero.setHighBits(MinSignBits);
3543 break;
3544 }
3545 }
3546 }
3547
3548 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3549 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3550 if (IsMax)
3551 Known = KnownBits::smax(Known, Known2);
3552 else
3553 Known = KnownBits::smin(Known, Known2);
3554 break;
3555 }
3556 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3557 if (Op.getResNo() == 1) {
3558 // The boolean result conforms to getBooleanContents.
3559 // If we know the result of a setcc has the top bits zero, use this info.
3560 // We know that we have an integer-based boolean since these operations
3561 // are only available for integer.
3562 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3563 TargetLowering::ZeroOrOneBooleanContent &&
3564 BitWidth > 1)
3565 Known.Zero.setBitsFrom(1);
3566 break;
3567 }
3568 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3569 case ISD::ATOMIC_CMP_SWAP:
3570 case ISD::ATOMIC_SWAP:
3571 case ISD::ATOMIC_LOAD_ADD:
3572 case ISD::ATOMIC_LOAD_SUB:
3573 case ISD::ATOMIC_LOAD_AND:
3574 case ISD::ATOMIC_LOAD_CLR:
3575 case ISD::ATOMIC_LOAD_OR:
3576 case ISD::ATOMIC_LOAD_XOR:
3577 case ISD::ATOMIC_LOAD_NAND:
3578 case ISD::ATOMIC_LOAD_MIN:
3579 case ISD::ATOMIC_LOAD_MAX:
3580 case ISD::ATOMIC_LOAD_UMIN:
3581 case ISD::ATOMIC_LOAD_UMAX:
3582 case ISD::ATOMIC_LOAD: {
3583 unsigned MemBits =
3584 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3585 // If we are looking at the loaded value.
3586 if (Op.getResNo() == 0) {
3587 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3588 Known.Zero.setBitsFrom(MemBits);
3589 }
3590 break;
3591 }
3592 case ISD::FrameIndex:
3593 case ISD::TargetFrameIndex:
3594 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3595 Known, getMachineFunction());
3596 break;
3597
3598 default:
3599 if (Opcode < ISD::BUILTIN_OP_END)
3600 break;
3601 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3602 case ISD::INTRINSIC_WO_CHAIN:
3603 case ISD::INTRINSIC_W_CHAIN:
3604 case ISD::INTRINSIC_VOID:
3605 // Allow the target to implement this method for its nodes.
3606 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3607 break;
3608 }
3609
3610 assert(!Known.hasConflict() && "Bits known to be one AND zero?")(static_cast<void> (0));
3611 return Known;
3612}
3613
3614SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3615 SDValue N1) const {
3616 // X + 0 never overflow
3617 if (isNullConstant(N1))
3618 return OFK_Never;
3619
3620 KnownBits N1Known = computeKnownBits(N1);
3621 if (N1Known.Zero.getBoolValue()) {
3622 KnownBits N0Known = computeKnownBits(N0);
3623
3624 bool overflow;
3625 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3626 if (!overflow)
3627 return OFK_Never;
3628 }
3629
3630 // mulhi + 1 never overflow
3631 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3632 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3633 return OFK_Never;
3634
3635 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3636 KnownBits N0Known = computeKnownBits(N0);
3637
3638 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3639 return OFK_Never;
3640 }
3641
3642 return OFK_Sometime;
3643}
3644
3645bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3646 EVT OpVT = Val.getValueType();
3647 unsigned BitWidth = OpVT.getScalarSizeInBits();
3648
3649 // Is the constant a known power of 2?
3650 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3651 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3652
3653 // A left-shift of a constant one will have exactly one bit set because
3654 // shifting the bit off the end is undefined.
3655 if (Val.getOpcode() == ISD::SHL) {
3656 auto *C = isConstOrConstSplat(Val.getOperand(0));
3657 if (C && C->getAPIntValue() == 1)
3658 return true;
3659 }
3660
3661 // Similarly, a logical right-shift of a constant sign-bit will have exactly
3662 // one bit set.
3663 if (Val.getOpcode() == ISD::SRL) {
3664 auto *C = isConstOrConstSplat(Val.getOperand(0));
3665 if (C && C->getAPIntValue().isSignMask())
3666 return true;
3667 }
3668
3669 // Are all operands of a build vector constant powers of two?
3670 if (Val.getOpcode() == ISD::BUILD_VECTOR)
3671 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3672 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3673 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3674 return false;
3675 }))
3676 return true;
3677
3678 // Is the operand of a splat vector a constant power of two?
3679 if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3680 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3681 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3682 return true;
3683
3684 // More could be done here, though the above checks are enough
3685 // to handle some common cases.
3686
3687 // Fall back to computeKnownBits to catch other known cases.
3688 KnownBits Known = computeKnownBits(Val);
3689 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3690}
3691
3692unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3693 EVT VT = Op.getValueType();
3694
3695 // TODO: Assume we don't know anything for now.
3696 if (VT.isScalableVector())
3697 return 1;
3698
3699 APInt DemandedElts = VT.isVector()
3700 ? APInt::getAllOnesValue(VT.getVectorNumElements())
3701 : APInt(1, 1);
3702 return ComputeNumSignBits(Op, DemandedElts, Depth);
3703}
3704
3705unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3706 unsigned Depth) const {
3707 EVT VT = Op.getValueType();
3708 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!")(static_cast<void> (0));
3709 unsigned VTBits = VT.getScalarSizeInBits();
3710 unsigned NumElts = DemandedElts.getBitWidth();
3711 unsigned Tmp, Tmp2;
3712 unsigned FirstAnswer = 1;
3713
3714 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3715 const APInt &Val = C->getAPIntValue();
3716 return Val.getNumSignBits();
3717 }
3718
3719 if (Depth >= MaxRecursionDepth)
3720 return 1; // Limit search depth.
3721
3722 if (!DemandedElts || VT.isScalableVector())
3723 return 1; // No demanded elts, better to assume we don't know anything.
3724
3725 unsigned Opcode = Op.getOpcode();
3726 switch (Opcode) {
3727 default: break;
3728 case ISD::AssertSext:
3729 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3730 return VTBits-Tmp+1;
3731 case ISD::AssertZext:
3732 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3733 return VTBits-Tmp;
3734
3735 case ISD::BUILD_VECTOR:
3736 Tmp = VTBits;
3737 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3738 if (!DemandedElts[i])
3739 continue;
3740
3741 SDValue SrcOp = Op.getOperand(i);
3742 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3743
3744 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3745 if (SrcOp.getValueSizeInBits() != VTBits) {
3746 assert(SrcOp.getValueSizeInBits() > VTBits &&(static_cast<void> (0))
3747 "Expected BUILD_VECTOR implicit truncation")(static_cast<void> (0));
3748 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3749 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3750 }
3751 Tmp = std::min(Tmp, Tmp2);
3752 }
3753 return Tmp;
3754
3755 case ISD::VECTOR_SHUFFLE: {
3756 // Collect the minimum number of sign bits that are shared by every vector
3757 // element referenced by the shuffle.
3758 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3759 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3760 assert(NumElts == SVN->getMask().size() && "Unexpected vector size")(static_cast<void> (0));
3761 for (unsigned i = 0; i != NumElts; ++i) {
3762 int M = SVN->getMaskElt(i);
3763 if (!DemandedElts[i])
3764 continue;
3765 // For UNDEF elements, we don't know anything about the common state of
3766 // the shuffle result.
3767 if (M < 0)
3768 return 1;
3769 if ((unsigned)M < NumElts)
3770 DemandedLHS.setBit((unsigned)M % NumElts);
3771 else
3772 DemandedRHS.setBit((unsigned)M % NumElts);
3773 }
3774 Tmp = std::numeric_limits<unsigned>::max();
3775 if (!!DemandedLHS)
3776 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3777 if (!!DemandedRHS) {
3778 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3779 Tmp = std::min(Tmp, Tmp2);
3780 }
3781 // If we don't know anything, early out and try computeKnownBits fall-back.
3782 if (Tmp == 1)
3783 break;
3784 assert(Tmp <= VTBits && "Failed to determine minimum sign bits")(static_cast<void> (0));
3785 return Tmp;
3786 }
3787
3788 case ISD::BITCAST: {
3789 SDValue N0 = Op.getOperand(0);
3790 EVT SrcVT = N0.getValueType();
3791 unsigned SrcBits = SrcVT.getScalarSizeInBits();
3792
3793 // Ignore bitcasts from unsupported types..
3794 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3795 break;
3796
3797 // Fast handling of 'identity' bitcasts.
3798 if (VTBits == SrcBits)
3799 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3800
3801 bool IsLE = getDataLayout().isLittleEndian();
3802
3803 // Bitcast 'large element' scalar/vector to 'small element' vector.
3804 if ((SrcBits % VTBits) == 0) {
3805 assert(VT.isVector() && "Expected bitcast to vector")(static_cast<void> (0));
3806
3807 unsigned Scale = SrcBits / VTBits;
3808 APInt SrcDemandedElts(NumElts / Scale, 0);
3809 for (unsigned i = 0; i != NumElts; ++i)
3810 if (DemandedElts[i])
3811 SrcDemandedElts.setBit(i / Scale);
3812
3813 // Fast case - sign splat can be simply split across the small elements.
3814 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3815 if (Tmp == SrcBits)
3816 return VTBits;
3817
3818 // Slow case - determine how far the sign extends into each sub-element.
3819 Tmp2 = VTBits;
3820 for (unsigned i = 0; i != NumElts; ++i)
3821 if (DemandedElts[i]) {
3822 unsigned SubOffset = i % Scale;
3823 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3824 SubOffset = SubOffset * VTBits;
3825 if (Tmp <= SubOffset)
3826 return 1;
3827 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3828 }
3829 return Tmp2;
3830 }
3831 break;
3832 }
3833
3834 case ISD::SIGN_EXTEND:
3835 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3836 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3837 case ISD::SIGN_EXTEND_INREG:
3838 // Max of the input and what this extends.
3839 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3840 Tmp = VTBits-Tmp+1;
3841 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3842 return std::max(Tmp, Tmp2);
3843 case ISD::SIGN_EXTEND_VECTOR_INREG: {
3844 SDValue Src = Op.getOperand(0);
3845 EVT SrcVT = Src.getValueType();
3846 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3847 Tmp = VTBits - SrcVT.getScalarSizeInBits();
3848 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3849 }
3850 case ISD::SRA:
3851 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3852 // SRA X, C -> adds C sign bits.
3853 if (const APInt *ShAmt =
3854 getValidMinimumShiftAmountConstant(Op, DemandedElts))
3855 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3856 return Tmp;
3857 case ISD::SHL:
3858 if (const APInt *ShAmt =
3859 getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3860 // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3861 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3862 if (ShAmt->ult(Tmp))
3863 return Tmp - ShAmt->getZExtValue();
3864 }
3865 break;
3866 case ISD::AND:
3867 case ISD::OR:
3868 case ISD::XOR: // NOT is handled here.
3869 // Logical binary ops preserve the number of sign bits at the worst.
3870 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3871 if (Tmp != 1) {
3872 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3873 FirstAnswer = std::min(Tmp, Tmp2);
3874 // We computed what we know about the sign bits as our first
3875 // answer. Now proceed to the generic code that uses
3876 // computeKnownBits, and pick whichever answer is better.
3877 }
3878 break;
3879
3880 case ISD::SELECT:
3881 case ISD::VSELECT:
3882 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3883 if (Tmp == 1) return 1; // Early out.
3884 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3885 return std::min(Tmp, Tmp2);
3886 case ISD::SELECT_CC:
3887 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3888 if (Tmp == 1) return 1; // Early out.
3889 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3890 return std::min(Tmp, Tmp2);
3891
3892 case ISD::SMIN:
3893 case ISD::SMAX: {
3894 // If we have a clamp pattern, we know that the number of sign bits will be
3895 // the minimum of the clamp min/max range.
3896 bool IsMax = (Opcode == ISD::SMAX);
3897 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3898 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3899 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3900 CstHigh =
3901 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3902 if (CstLow && CstHigh) {
3903 if (!IsMax)
3904 std::swap(CstLow, CstHigh);
3905 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3906 Tmp = CstLow->getAPIntValue().getNumSignBits();
3907 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3908 return std::min(Tmp, Tmp2);
3909 }
3910 }
3911
3912 // Fallback - just get the minimum number of sign bits of the operands.
3913 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3914 if (Tmp == 1)
3915 return 1; // Early out.
3916 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3917 return std::min(Tmp, Tmp2);
3918 }
3919 case ISD::UMIN:
3920 case ISD::UMAX:
3921 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3922 if (Tmp == 1)
3923 return 1; // Early out.
3924 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3925 return std::min(Tmp, Tmp2);
3926 case ISD::SADDO:
3927 case ISD::UADDO:
3928 case ISD::SSUBO:
3929 case ISD::USUBO:
3930 case ISD::SMULO:
3931 case ISD::UMULO:
3932 if (Op.getResNo() != 1)
3933 break;
3934 // The boolean result conforms to getBooleanContents. Fall through.
3935 // If setcc returns 0/-1, all bits are sign bits.
3936 // We know that we have an integer-based boolean since these operations
3937 // are only available for integer.
3938 if (TLI->getBooleanContents(VT.isVector(), false) ==
3939 TargetLowering::ZeroOrNegativeOneBooleanContent)
3940 return VTBits;
3941 break;
3942 case ISD::SETCC:
3943 case ISD::STRICT_FSETCC:
3944 case ISD::STRICT_FSETCCS: {
3945 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3946 // If setcc returns 0/-1, all bits are sign bits.
3947 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3948 TargetLowering::ZeroOrNegativeOneBooleanContent)
3949 return VTBits;
3950 break;
3951 }
3952 case ISD::ROTL:
3953 case ISD::ROTR:
3954 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3955
3956 // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
3957 if (Tmp == VTBits)
3958 return VTBits;
3959
3960 if (ConstantSDNode *C =
3961 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3962 unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3963
3964 // Handle rotate right by N like a rotate left by 32-N.
3965 if (Opcode == ISD::ROTR)
3966 RotAmt = (VTBits - RotAmt) % VTBits;
3967
3968 // If we aren't rotating out all of the known-in sign bits, return the
3969 // number that are left. This handles rotl(sext(x), 1) for example.
3970 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3971 }
3972 break;
3973 case ISD::ADD:
3974 case ISD::ADDC:
3975 // Add can have at most one carry bit. Thus we know that the output
3976 // is, at worst, one more bit than the inputs.
3977 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3978 if (Tmp == 1) return 1; // Early out.
3979
3980 // Special case decrementing a value (ADD X, -1):
3981 if (ConstantSDNode *CRHS =
3982 isConstOrConstSplat(Op.getOperand(1), DemandedElts))
3983 if (CRHS->isAllOnesValue()) {
3984 KnownBits Known =
3985 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3986
3987 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3988 // sign bits set.
3989 if ((Known.Zero | 1).isAllOnesValue())
3990 return VTBits;
3991
3992 // If we are subtracting one from a positive number, there is no carry
3993 // out of the result.
3994 if (Known.isNonNegative())
3995 return Tmp;
3996 }
3997
3998 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3999 if (Tmp2 == 1) return 1; // Early out.
4000 return std::min(Tmp, Tmp2) - 1;
4001 case ISD::SUB:
4002 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4003 if (Tmp2 == 1) return 1; // Early out.
4004
4005 // Handle NEG.
4006 if (ConstantSDNode *CLHS =
4007 isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4008 if (CLHS->isNullValue()) {
4009 KnownBits Known =
4010 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4011 // If the input is known to be 0 or 1, the output is 0/-1, which is all
4012 // sign bits set.
4013 if ((Known.Zero | 1).isAllOnesValue())
4014 return VTBits;
4015
4016 // If the input is known to be positive (the sign bit is known clear),
4017 // the output of the NEG has the same number of sign bits as the input.
4018 if (Known.isNonNegative())
4019 return Tmp2;
4020
4021 // Otherwise, we treat this like a SUB.
4022 }
4023
4024 // Sub can have at most one carry bit. Thus we know that the output
4025 // is, at worst, one more bit than the inputs.
4026 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4027 if (Tmp == 1) return 1; // Early out.
4028 return std::min(Tmp, Tmp2) - 1;
4029 case ISD::MUL: {
4030 // The output of the Mul can be at most twice the valid bits in the inputs.
4031 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4032 if (SignBitsOp0 == 1)
4033 break;
4034 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4035 if (SignBitsOp1 == 1)
4036 break;
4037 unsigned OutValidBits =
4038 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4039 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4040 }
4041 case ISD::SREM:
4042 // The sign bit is the LHS's sign bit, except when the result of the
4043 // remainder is zero. The magnitude of the result should be less than or
4044 // equal to the magnitude of the LHS. Therefore, the result should have
4045 // at least as many sign bits as the left hand side.
4046 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4047 case ISD::TRUNCATE: {
4048 // Check if the sign bits of source go down as far as the truncated value.
4049 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4050 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4051 if (NumSrcSignBits > (NumSrcBits - VTBits))
4052 return NumSrcSignBits - (NumSrcBits - VTBits);
4053 break;
4054 }
4055 case ISD::EXTRACT_ELEMENT: {
4056 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4057 const int BitWidth = Op.getValueSizeInBits();
4058 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4059
4060 // Get reverse index (starting from 1), Op1 value indexes elements from
4061 // little end. Sign starts at big end.
4062 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4063
4064 // If the sign portion ends in our element the subtraction gives correct
4065 // result. Otherwise it gives either negative or > bitwidth result
4066 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4067 }
4068 case ISD::INSERT_VECTOR_ELT: {
4069 // If we know the element index, split the demand between the
4070 // source vector and the inserted element, otherwise assume we need
4071 // the original demanded vector elements and the value.
4072 SDValue InVec = Op.getOperand(0);
4073 SDValue InVal = Op.getOperand(1);
4074 SDValue EltNo = Op.getOperand(2);
4075 bool DemandedVal = true;
4076 APInt DemandedVecElts = DemandedElts;
4077 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4078 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4079 unsigned EltIdx = CEltNo->getZExtValue();
4080 DemandedVal = !!DemandedElts[EltIdx];
4081 DemandedVecElts.clearBit(EltIdx);
4082 }
4083 Tmp = std::numeric_limits<unsigned>::max();
4084 if (DemandedVal) {
4085 // TODO - handle implicit truncation of inserted elements.
4086 if (InVal.getScalarValueSizeInBits() != VTBits)
4087 break;
4088 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4089 Tmp = std::min(Tmp, Tmp2);
4090 }
4091 if (!!DemandedVecElts) {
4092 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4093 Tmp = std::min(Tmp, Tmp2);
4094 }
4095 assert(Tmp <= VTBits && "Failed to determine minimum sign bits")(static_cast<void> (0));
4096 return Tmp;
4097 }
4098 case ISD::EXTRACT_VECTOR_ELT: {
4099 SDValue InVec = Op.getOperand(0);
4100 SDValue EltNo = Op.getOperand(1);
4101 EVT VecVT = InVec.getValueType();
4102 // ComputeNumSignBits not yet implemented for scalable vectors.
4103 if (VecVT.isScalableVector())
4104 break;
4105 const unsigned BitWidth = Op.getValueSizeInBits();
4106 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4107 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4108
4109 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4110 // anything about sign bits. But if the sizes match we can derive knowledge
4111 // about sign bits from the vector operand.
4112 if (BitWidth != EltBitWidth)
4113 break;
4114
4115 // If we know the element index, just demand that vector element, else for
4116 // an unknown element index, ignore DemandedElts and demand them all.
4117 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
4118 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4119 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4120 DemandedSrcElts =
4121 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4122
4123 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4124 }
4125 case ISD::EXTRACT_SUBVECTOR: {
4126 // Offset the demanded elts by the subvector index.
4127 SDValue Src = Op.getOperand(0);
4128 // Bail until we can represent demanded elements for scalable vectors.
4129 if (Src.getValueType().isScalableVector())
4130 break;
4131 uint64_t Idx = Op.getConstantOperandVal(1);
4132 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4133 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4134 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4135 }
4136 case ISD::CONCAT_VECTORS: {
4137 // Determine the minimum number of sign bits across all demanded
4138 // elts of the input vectors. Early out if the result is already 1.
4139 Tmp = std::numeric_limits<unsigned>::max();
4140 EVT SubVectorVT = Op.getOperand(0).getValueType();
4141 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4142 unsigned NumSubVectors = Op.getNumOperands();
4143 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4144 APInt DemandedSub =
4145 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4146 if (!DemandedSub)
4147 continue;
4148 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4149 Tmp = std::min(Tmp, Tmp2);
4150 }
4151 assert(Tmp <= VTBits && "Failed to determine minimum sign bits")(static_cast<void> (0));
4152 return Tmp;
4153 }
4154 case ISD::INSERT_SUBVECTOR: {
4155 // Demand any elements from the subvector and the remainder from the src its
4156 // inserted into.
4157 SDValue Src = Op.getOperand(0);
4158 SDValue Sub = Op.getOperand(1);
4159 uint64_t Idx = Op.getConstantOperandVal(2);
4160 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4161 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4162 APInt DemandedSrcElts = DemandedElts;
4163 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
4164
4165 Tmp = std::numeric_limits<unsigned>::max();
4166 if (!!DemandedSubElts) {
4167 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4168 if (Tmp == 1)
4169 return 1; // early-out
4170 }
4171 if (!!DemandedSrcElts) {
4172 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4173 Tmp = std::min(Tmp, Tmp2);
4174 }
4175 assert(Tmp <= VTBits && "Failed to determine minimum sign bits")(static_cast<void> (0));
4176 return Tmp;
4177 }
4178 case ISD::ATOMIC_CMP_SWAP:
4179 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4180 case ISD::ATOMIC_SWAP:
4181 case ISD::ATOMIC_LOAD_ADD:
4182 case ISD::ATOMIC_LOAD_SUB:
4183 case ISD::ATOMIC_LOAD_AND:
4184 case ISD::ATOMIC_LOAD_CLR:
4185 case ISD::ATOMIC_LOAD_OR:
4186 case ISD::ATOMIC_LOAD_XOR:
4187 case ISD::ATOMIC_LOAD_NAND:
4188 case ISD::ATOMIC_LOAD_MIN:
4189 case ISD::ATOMIC_LOAD_MAX:
4190 case ISD::ATOMIC_LOAD_UMIN:
4191 case ISD::ATOMIC_LOAD_UMAX:
4192 case ISD::ATOMIC_LOAD: {
4193 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4194 // If we are looking at the loaded value.
4195 if (Op.getResNo() == 0) {
4196 if (Tmp == VTBits)
4197 return 1; // early-out
4198 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4199 return VTBits - Tmp + 1;
4200 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4201 return VTBits - Tmp;
4202 }
4203 break;
4204 }
4205 }
4206
4207 // If we are looking at the loaded value of the SDNode.
4208 if (Op.getResNo() == 0) {
4209 // Handle LOADX separately here. EXTLOAD case will fallthrough.
4210 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4211 unsigned ExtType = LD->getExtensionType();
4212 switch (ExtType) {
4213 default: break;
4214 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4215 Tmp = LD->getMemoryVT().getScalarSizeInBits();
4216 return VTBits - Tmp + 1;
4217 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4218 Tmp = LD->getMemoryVT().getScalarSizeInBits();
4219 return VTBits - Tmp;
4220 case ISD::NON_EXTLOAD:
4221 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4222 // We only need to handle vectors - computeKnownBits should handle
4223 // scalar cases.
4224 Type *CstTy = Cst->getType();
4225 if (CstTy->isVectorTy() &&
4226 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4227 Tmp = VTBits;
4228 for (unsigned i = 0; i != NumElts; ++i) {
4229 if (!DemandedElts[i])
4230 continue;
4231 if (Constant *Elt = Cst->getAggregateElement(i)) {
4232 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4233 const APInt &Value = CInt->getValue();
4234 Tmp = std::min(Tmp, Value.getNumSignBits());
4235 continue;
4236 }
4237 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4238 APInt Value = CFP->getValueAPF().bitcastToAPInt();
4239 Tmp = std::min(Tmp, Value.getNumSignBits());
4240 continue;
4241 }
4242 }
4243 // Unknown type. Conservatively assume no bits match sign bit.
4244 return 1;
4245 }
4246 return Tmp;
4247 }
4248 }
4249 break;
4250 }
4251 }
4252 }
4253
4254 // Allow the target to implement this method for its nodes.
4255 if (Opcode >= ISD::BUILTIN_OP_END ||
4256 Opcode == ISD::INTRINSIC_WO_CHAIN ||
4257 Opcode == ISD::INTRINSIC_W_CHAIN ||
4258 Opcode == ISD::INTRINSIC_VOID) {
4259 unsigned NumBits =
4260 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4261 if (NumBits > 1)
4262 FirstAnswer = std::max(FirstAnswer, NumBits);
4263 }
4264
4265 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4266 // use this information.
4267 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4268
4269 APInt Mask;
4270 if (Known.isNonNegative()) { // sign bit is 0
4271 Mask = Known.Zero;
4272 } else if (Known.isNegative()) { // sign bit is 1;
4273 Mask = Known.One;
4274 } else {
4275 // Nothing known.
4276 return FirstAnswer;
4277 }
4278
4279 // Okay, we know that the sign bit in Mask is set. Use CLO to determine
4280 // the number of identical bits in the top of the input value.
4281 Mask <<= Mask.getBitWidth()-VTBits;
4282 return std::max(FirstAnswer, Mask.countLeadingOnes());
4283}
4284
4285bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4286 unsigned Depth) const {
4287 // Early out for FREEZE.
4288 if (Op.getOpcode() == ISD::FREEZE)
4289 return true;
4290
4291 // TODO: Assume we don't know anything for now.
4292 EVT VT = Op.getValueType();
4293 if (VT.isScalableVector())
4294 return false;
4295
4296 APInt DemandedElts = VT.isVector()
4297 ? APInt::getAllOnesValue(VT.getVectorNumElements())
4298 : APInt(1, 1);
4299 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4300}
4301
4302bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4303 const APInt &DemandedElts,
4304 bool PoisonOnly,
4305 unsigned Depth) const {
4306 unsigned Opcode = Op.getOpcode();
4307
4308 // Early out for FREEZE.
4309 if (Opcode == ISD::FREEZE)
4310 return true;
4311
4312 if (Depth >= MaxRecursionDepth)
4313 return false; // Limit search depth.
4314
4315 if (isIntOrFPConstant(Op))
4316 return true;
4317
4318 switch (Opcode) {
4319 case ISD::UNDEF:
4320 return PoisonOnly;
4321
4322 case ISD::BUILD_VECTOR:
4323 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4324 // this shouldn't affect the result.
4325 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4326 if (!DemandedElts[i])
4327 continue;
4328 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4329 Depth + 1))
4330 return false;
4331 }
4332 return true;
4333
4334 // TODO: Search for noundef attributes from library functions.
4335
4336 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4337
4338 default:
4339 // Allow the target to implement this method for its nodes.
4340 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4341 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4342 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4343 Op, DemandedElts, *this, PoisonOnly, Depth);
4344 break;
4345 }
4346
4347 return false;
4348}
4349
4350bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4351 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4352 !isa<ConstantSDNode>(Op.getOperand(1)))
4353 return false;
4354
4355 if (Op.getOpcode() == ISD::OR &&
4356 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4357 return false;
4358
4359 return true;
4360}
4361
4362bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4363 // If we're told that NaNs won't happen, assume they won't.
4364 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4365 return true;
4366
4367 if (Depth >= MaxRecursionDepth)
4368 return false; // Limit search depth.
4369
4370 // TODO: Handle vectors.
4371 // If the value is a constant, we can obviously see if it is a NaN or not.
4372 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4373 return !C->getValueAPF().isNaN() ||
4374 (SNaN && !C->getValueAPF().isSignaling());
4375 }
4376
4377 unsigned Opcode = Op.getOpcode();
4378 switch (Opcode) {
4379 case ISD::FADD:
4380 case ISD::FSUB:
4381 case ISD::FMUL:
4382 case ISD::FDIV:
4383 case ISD::FREM:
4384 case ISD::FSIN:
4385 case ISD::FCOS: {
4386 if (SNaN)
4387 return true;
4388 // TODO: Need isKnownNeverInfinity
4389 return false;
4390 }
4391 case ISD::FCANONICALIZE:
4392 case ISD::FEXP:
4393 case ISD::FEXP2:
4394 case ISD::FTRUNC:
4395 case ISD::FFLOOR:
4396 case ISD::FCEIL:
4397 case ISD::FROUND:
4398 case ISD::FROUNDEVEN:
4399 case ISD::FRINT:
4400 case ISD::FNEARBYINT: {
4401 if (SNaN)
4402 return true;
4403 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4404 }
4405 case ISD::FABS:
4406 case ISD::FNEG:
4407 case ISD::FCOPYSIGN: {
4408 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4409 }
4410 case ISD::SELECT:
4411 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4412 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4413 case ISD::FP_EXTEND:
4414 case ISD::FP_ROUND: {
4415 if (SNaN)
4416 return true;
4417 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4418 }
4419 case ISD::SINT_TO_FP:
4420 case ISD::UINT_TO_FP:
4421 return true;
4422 case ISD::FMA:
4423 case ISD::FMAD: {
4424 if (SNaN)
4425 return true;
4426 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4427 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4428 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4429 }
4430 case ISD::FSQRT: // Need is known positive
4431 case ISD::FLOG:
4432 case ISD::FLOG2:
4433 case ISD::FLOG10:
4434 case ISD::FPOWI:
4435 case ISD::FPOW: {
4436 if (SNaN)
4437 return true;
4438 // TODO: Refine on operand
4439 return false;
4440 }
4441 case ISD::FMINNUM:
4442 case ISD::FMAXNUM: {
4443 // Only one needs to be known not-nan, since it will be returned if the
4444 // other ends up being one.
4445 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4446 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4447 }
4448 case ISD::FMINNUM_IEEE:
4449 case ISD::FMAXNUM_IEEE: {
4450 if (SNaN)
4451 return true;
4452 // This can return a NaN if either operand is an sNaN, or if both operands
4453 // are NaN.
4454 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4455 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4456 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4457 isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4458 }
4459 case ISD::FMINIMUM:
4460 case ISD::FMAXIMUM: {
4461 // TODO: Does this quiet or return the origina NaN as-is?
4462 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4463 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4464 }
4465 case ISD::EXTRACT_VECTOR_ELT: {
4466 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4467 }
4468 default:
4469 if (Opcode >= ISD::BUILTIN_OP_END ||
4470 Opcode == ISD::INTRINSIC_WO_CHAIN ||
4471 Opcode == ISD::INTRINSIC_W_CHAIN ||
4472 Opcode == ISD::INTRINSIC_VOID) {
4473 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4474 }
4475
4476 return false;
4477 }
4478}
4479
4480bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4481 assert(Op.getValueType().isFloatingPoint() &&(static_cast<void> (0))
4482 "Floating point type expected")(static_cast<void> (0));
4483
4484 // If the value is a constant, we can obviously see if it is a zero or not.
4485 // TODO: Add BuildVector support.
4486 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4487 return !C->isZero();
4488 return false;
4489}
4490
4491bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4492 assert(!Op.getValueType().isFloatingPoint() &&(static_cast<void> (0))
4493 "Floating point types unsupported - use isKnownNeverZeroFloat")(static_cast<void> (0));
4494
4495 // If the value is a constant, we can obviously see if it is a zero or not.
4496 if (ISD::matchUnaryPredicate(
4497 Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
4498 return true;
4499
4500 // TODO: Recognize more cases here.
4501 switch (Op.getOpcode()) {
4502 default: break;
4503 case ISD::OR:
4504 if (isKnownNeverZero(Op.getOperand(1)) ||
4505 isKnownNeverZero(Op.getOperand(0)))
4506 return true;
4507 break;
4508 }
4509
4510 return false;
4511}
4512
4513bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4514 // Check the obvious case.
4515 if (A == B) return true;
4516
4517 // For for negative and positive zero.
4518 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4519 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4520 if (CA->isZero() && CB->isZero()) return true;
4521
4522 // Otherwise they may not be equal.
4523 return false;
4524}
4525
4526// FIXME: unify with llvm::haveNoCommonBitsSet.
4527// FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4528bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4529 assert(A.getValueType() == B.getValueType() &&(static_cast<void> (0))
4530 "Values must have the same type")(static_cast<void> (0));
4531 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4532 computeKnownBits(B));
4533}
4534
4535static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4536 SelectionDAG &DAG) {
4537 if (cast<ConstantSDNode>(Step)->isNullValue())
4538 return DAG.getConstant(0, DL, VT);
4539
4540 return SDValue();
4541}
4542
4543static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4544 ArrayRef<SDValue> Ops,
4545 SelectionDAG &DAG) {
4546 int NumOps = Ops.size();
4547 assert(NumOps != 0 && "Can't build an empty vector!")(static_cast<void> (0));
4548 assert(!VT.isScalableVector() &&(static_cast<void> (0))
4549 "BUILD_VECTOR cannot be used with scalable types")(static_cast<void> (0));
4550 assert(VT.getVectorNumElements() == (unsigned)NumOps &&(static_cast<void> (0))
4551 "Incorrect element count in BUILD_VECTOR!")(static_cast<void> (0));
4552
4553 // BUILD_VECTOR of UNDEFs is UNDEF.
4554 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4555 return DAG.getUNDEF(VT);
4556
4557 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4558 SDValue IdentitySrc;
4559 bool IsIdentity = true;
4560 for (int i = 0; i != NumOps; ++i) {
4561 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4562 Ops[i].getOperand(0).getValueType() != VT ||
4563 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4564 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4565 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4566 IsIdentity = false;
4567 break;
4568 }
4569 IdentitySrc = Ops[i].getOperand(0);
4570 }
4571 if (IsIdentity)
4572 return IdentitySrc;
4573
4574 return SDValue();
4575}
4576
4577/// Try to simplify vector concatenation to an input value, undef, or build
4578/// vector.
4579static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4580 ArrayRef<SDValue> Ops,
4581 SelectionDAG &DAG) {
4582 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!")(static_cast<void> (0));
4583 assert(llvm::all_of(Ops,(static_cast<void> (0))
4584 [Ops](SDValue Op) {(static_cast<void> (0))
4585 return Ops[0].getValueType() == Op.getValueType();(static_cast<void> (0))
4586 }) &&(static_cast<void> (0))
4587 "Concatenation of vectors with inconsistent value types!")(static_cast<void> (0));
4588 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==(static_cast<void> (0))
4589 VT.getVectorElementCount() &&(static_cast<void> (0))
4590 "Incorrect element count in vector concatenation!")(static_cast<void> (0));
4591
4592 if (Ops.size() == 1)
4593 return Ops[0];
4594
4595 // Concat of UNDEFs is UNDEF.
4596 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4597 return DAG.getUNDEF(VT);
4598
4599 // Scan the operands and look for extract operations from a single source
4600 // that correspond to insertion at the same location via this concatenation:
4601 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4602 SDValue IdentitySrc;
4603 bool IsIdentity = true;
4604 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4605 SDValue Op = Ops[i];
4606 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4607 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4608 Op.getOperand(0).getValueType() != VT ||
4609 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4610 Op.getConstantOperandVal(1) != IdentityIndex) {
4611 IsIdentity = false;
4612 break;
4613 }
4614 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&(static_cast<void> (0))
4615 "Unexpected identity source vector for concat of extracts")(static_cast<void> (0));
4616 IdentitySrc = Op.getOperand(0);
4617 }
4618 if (IsIdentity) {
4619 assert(IdentitySrc && "Failed to set source vector of extracts")(static_cast<void> (0));
4620 return IdentitySrc;
4621 }
4622
4623 // The code below this point is only designed to work for fixed width
4624 // vectors, so we bail out for now.
4625 if (VT.isScalableVector())
4626 return SDValue();
4627
4628 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4629 // simplified to one big BUILD_VECTOR.
4630 // FIXME: Add support for SCALAR_TO_VECTOR as well.
4631 EVT SVT = VT.getScalarType();
4632 SmallVector<SDValue, 16> Elts;
4633 for (SDValue Op : Ops) {
4634 EVT OpVT = Op.getValueType();
4635 if (Op.isUndef())
4636 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4637 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4638 Elts.append(Op->op_begin(), Op->op_end());
4639 else
4640 return SDValue();
4641 }
4642
4643 // BUILD_VECTOR requires all inputs to be of the same type, find the
4644 // maximum type and extend them all.
4645 for (SDValue Op : Elts)
4646 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4647
4648 if (SVT.bitsGT(VT.getScalarType())) {
4649 for (SDValue &Op : Elts) {
4650 if (Op.isUndef())
4651 Op = DAG.getUNDEF(SVT);
4652 else
4653 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4654 ? DAG.getZExtOrTrunc(Op, DL, SVT)
4655 : DAG.getSExtOrTrunc(Op, DL, SVT);
4656 }
4657 }
4658
4659 SDValue V = DAG.getBuildVector(VT, DL, Elts);
4660 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4661 return V;
4662}
4663
4664/// Gets or creates the specified node.
4665SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4666 FoldingSetNodeID ID;
4667 AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4668 void *IP = nullptr;
4669 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4670 return SDValue(E, 0);
4671
4672 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4673 getVTList(VT));
4674 CSEMap.InsertNode(N, IP);
4675
4676 InsertNode(N);
4677 SDValue V = SDValue(N, 0);
4678 NewSDValueDbgMsg(V, "Creating new node: ", this);
4679 return V;
4680}
4681
4682SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4683 SDValue Operand) {
4684 SDNodeFlags Flags;
4685 if (Inserter)
4686 Flags = Inserter->getFlags();
4687 return getNode(Opcode, DL, VT, Operand, Flags);
4688}
4689
4690SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4691 SDValue Operand, const SDNodeFlags Flags) {
4692 assert(Operand.getOpcode() != ISD::DELETED_NODE &&(static_cast<void> (0))
4693 "Operand is DELETED_NODE!")(static_cast<void> (0));
4694 // Constant fold unary operations with an integer constant operand. Even
4695 // opaque constant will be folded, because the folding of unary operations
4696 // doesn't create new constants with different values. Nevertheless, the
4697 // opaque flag is preserved during folding to prevent future folding with
4698 // other constants.
4699 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4700 const APInt &Val = C->getAPIntValue();
4701 switch (Opcode) {
4702 default: break;
4703 case ISD::SIGN_EXTEND:
4704 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4705 C->isTargetOpcode(), C->isOpaque());
4706 case ISD::TRUNCATE:
4707 if (C->isOpaque())
4708 break;
4709 LLVM_FALLTHROUGH[[gnu::fallthrough]];
4710 case ISD::ZERO_EXTEND:
4711 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4712 C->isTargetOpcode(), C->isOpaque());
4713 case ISD::ANY_EXTEND:
4714 // Some targets like RISCV prefer to sign extend some types.
4715 if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4716 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4717 C->isTargetOpcode(), C->isOpaque());
4718 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4719 C->isTargetOpcode(), C->isOpaque());
4720 case ISD::UINT_TO_FP:
4721 case ISD::SINT_TO_FP: {
4722 APFloat apf(EVTToAPFloatSemantics(VT),
4723 APInt::getNullValue(VT.getSizeInBits()));
4724 (void)apf.convertFromAPInt(Val,
4725 Opcode==ISD::SINT_TO_FP,
4726 APFloat::rmNearestTiesToEven);
4727 return getConstantFP(apf, DL, VT);
4728 }
4729 case ISD::BITCAST:
4730 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4731 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4732 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4733 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4734 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4735 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4736 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4737 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4738 break;
4739 case ISD::ABS:
4740 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4741 C->isOpaque());
4742 case ISD::BITREVERSE:
4743 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4744 C->isOpaque());
4745 case ISD::BSWAP:
4746 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4747 C->isOpaque());
4748 case ISD::CTPOP:
4749 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4750 C->isOpaque());
4751 case ISD::CTLZ:
4752 case ISD::CTLZ_ZERO_UNDEF:
4753 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4754 C->isOpaque());
4755 case ISD::CTTZ:
4756 case ISD::CTTZ_ZERO_UNDEF:
4757 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4758 C->isOpaque());
4759 case ISD::FP16_TO_FP: {
4760 bool Ignored;
4761 APFloat FPV(APFloat::IEEEhalf(),
4762 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4763
4764 // This can return overflow, underflow, or inexact; we don't care.
4765 // FIXME need to be more flexible about rounding mode.
4766 (void)FPV.convert(EVTToAPFloatSemantics(VT),
4767 APFloat::rmNearestTiesToEven, &Ignored);
4768 return getConstantFP(FPV, DL, VT);
4769 }
4770 case ISD::STEP_VECTOR: {
4771 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4772 return V;
4773 break;
4774 }
4775 }
4776 }
4777
4778 // Constant fold unary operations with a floating point constant operand.
4779 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4780 APFloat V = C->getValueAPF(); // make copy
4781 switch (Opcode) {
4782 case ISD::FNEG:
4783 V.changeSign();
4784 return getConstantFP(V, DL, VT);
4785 case ISD::FABS:
4786 V.clearSign();
4787 return getConstantFP(V, DL, VT);
4788 case ISD::FCEIL: {
4789 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4790 if (fs == APFloat::opOK || fs == APFloat::opInexact)
4791 return getConstantFP(V, DL, VT);
4792 break;
4793 }
4794 case ISD::FTRUNC: {
4795 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4796 if (fs == APFloat::opOK || fs == APFloat::opInexact)
4797 return getConstantFP(V, DL, VT);
4798 break;
4799 }
4800 case ISD::FFLOOR: {
4801 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4802 if (fs == APFloat::opOK || fs == APFloat::opInexact)
4803 return getConstantFP(V, DL, VT);
4804 break;
4805 }
4806 case ISD::FP_EXTEND: {
4807 bool ignored;
4808 // This can return overflow, underflow, or inexact; we don't care.
4809 // FIXME need to be more flexible about rounding mode.
4810 (void)V.convert(EVTToAPFloatSemantics(VT),
4811 APFloat::rmNearestTiesToEven, &ignored);
4812 return getConstantFP(V, DL, VT);
4813 }
4814 case ISD::FP_TO_SINT:
4815 case ISD::FP_TO_UINT: {
4816 bool ignored;
4817 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4818 // FIXME need to be more flexible about rounding mode.
4819 APFloat::opStatus s =
4820 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4821 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4822 break;
4823 return getConstant(IntVal, DL, VT);
4824 }
4825 case ISD::BITCAST:
4826 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4827 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4828 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
4829 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4830 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4831 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4832 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4833 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4834 break;
4835 case ISD::FP_TO_FP16: {
4836 bool Ignored;
4837 // This can return overflow, underflow, or inexact; we don't care.
4838 // FIXME need to be more flexible about rounding mode.
4839 (void)V.convert(APFloat::IEEEhalf(),
4840 APFloat::rmNearestTiesToEven, &Ignored);
4841 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4842 }
4843 }
4844 }
4845
4846 // Constant fold unary operations with a vector integer or float operand.
4847 switch (Opcode) {
4848 default:
4849 // FIXME: Entirely reasonable to perform folding of other unary
4850 // operations here as the need arises.
4851 break;
4852 case ISD::FNEG:
4853 case ISD::FABS:
4854 case ISD::FCEIL:
4855 case ISD::FTRUNC:
4856 case ISD::FFLOOR:
4857 case ISD::FP_EXTEND:
4858 case ISD::FP_TO_SINT:
4859 case ISD::FP_TO_UINT:
4860 case ISD::TRUNCATE:
4861 case ISD::ANY_EXTEND:
4862 case ISD::ZERO_EXTEND:
4863 case ISD::SIGN_EXTEND:
4864 case ISD::UINT_TO_FP:
4865 case ISD::SINT_TO_FP:
4866 case ISD::ABS:
4867 case ISD::BITREVERSE:
4868 case ISD::BSWAP:
4869 case ISD::CTLZ:
4870 case ISD::CTLZ_ZERO_UNDEF:
4871 case ISD::CTTZ:
4872 case ISD::CTTZ_ZERO_UNDEF:
4873 case ISD::CTPOP: {
4874 SDValue Ops = {Operand};
4875 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4876 return Fold;
4877 }
4878 }
4879
4880 unsigned OpOpcode = Operand.getNode()->getOpcode();
4881 switch (Opcode) {
4882 case ISD::STEP_VECTOR:
4883 assert(VT.isScalableVector() &&(static_cast<void> (0))
4884 "STEP_VECTOR can only be used with scalable types")(static_cast<void> (0));
4885 assert(OpOpcode == ISD::TargetConstant &&(static_cast<void> (0))
4886 VT.getVectorElementType() == Operand.getValueType() &&(static_cast<void> (0))
4887 "Unexpected step operand")(static_cast<void> (0));
4888 break;
4889 case ISD::FREEZE:
4890 assert(VT == Operand.getValueType() && "Unexpected VT!")(static_cast<void> (0));
4891 break;
4892 case ISD::TokenFactor:
4893 case ISD::MERGE_VALUES:
4894 case ISD::CONCAT_VECTORS:
4895 return Operand; // Factor, merge or concat of one node? No need.
4896 case ISD::BUILD_VECTOR: {
4897 // Attempt to simplify BUILD_VECTOR.
4898 SDValue Ops[] = {Operand};
4899 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4900 return V;
4901 break;
4902 }
4903 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node")__builtin_unreachable();
4904 case ISD::FP_EXTEND:
4905 assert(VT.isFloatingPoint() &&(static_cast<void> (0))
4906 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!")(static_cast<void> (0));
4907 if (Operand.getValueType() == VT) return Operand; // noop conversion.
4908 assert((!VT.isVector() ||(static_cast<void> (0))
4909 VT.getVectorElementCount() ==(static_cast<void> (0))
4910 Operand.getValueType().getVectorElementCount()) &&(static_cast<void> (0))
4911 "Vector element count mismatch!")(static_cast<void> (0));
4912 assert(Operand.getValueType().bitsLT(VT) &&(static_cast<void> (0))
4913 "Invalid fpext node, dst < src!")(static_cast<void> (0));
4914 if (Operand.isUndef())
4915 return getUNDEF(VT);
4916 break;
4917 case ISD::FP_TO_SINT:
4918 case ISD::FP_TO_UINT:
4919 if (Operand.isUndef())
4920 return getUNDEF(VT);
4921 break;
4922 case ISD::SINT_TO_FP:
4923 case ISD::UINT_TO_FP:
4924 // [us]itofp(undef) = 0, because the result value is bounded.
4925 if (Operand.isUndef())
4926 return getConstantFP(0.0, DL, VT);
4927 break;
4928 case ISD::SIGN_EXTEND:
4929 assert(VT.isInteger() && Operand.getValueType().isInteger() &&(static_cast<void> (0))
4930 "Invalid SIGN_EXTEND!")(static_cast<void> (0));
4931 assert(VT.isVector() == Operand.getValueType().isVector() &&(static_cast<void> (0))
4932 "SIGN_EXTEND result type type should be vector iff the operand "(static_cast<void> (0))
4933 "type is vector!")(static_cast<void> (0));
4934 if (Operand.getValueType() == VT) return Operand; // noop extension
4935 assert((!VT.isVector() ||(static_cast<void> (0))
4936 VT.getVectorElementCount() ==(static_cast<void> (0))
4937 Operand.getValueType().getVectorElementCount()) &&(static_cast<void> (0))
4938 "Vector element count mismatch!")(static_cast<void> (0));
4939 assert(Operand.getValueType().bitsLT(VT) &&(static_cast<void> (0))
4940 "Invalid sext node, dst < src!")(static_cast<void> (0));
4941 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4942 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4943 if (OpOpcode == ISD::UNDEF)
4944 // sext(undef) = 0, because the top bits will all be the same.
4945 return getConstant(0, DL, VT);
4946 break;
4947 case ISD::ZERO_EXTEND:
4948 assert(VT.isInteger() && Operand.getValueType().isInteger() &&(static_cast<void> (0))
4949 "Invalid ZERO_EXTEND!")(static_cast<void> (0));
4950 assert(VT.isVector() == Operand.getValueType().isVector() &&(static_cast<void> (0))
4951 "ZERO_EXTEND result type type should be vector iff the operand "(static_cast<void> (0))
4952 "type is vector!")(static_cast<void> (0));
4953 if (Operand.getValueType() == VT) return Operand; // noop extension
4954 assert((!VT.isVector() ||(static_cast<void> (0))
4955 VT.getVectorElementCount() ==(static_cast<void> (0))
4956 Operand.getValueType().getVectorElementCount()) &&(static_cast<void> (0))
4957 "Vector element count mismatch!")(static_cast<void> (0));
4958 assert(Operand.getValueType().bitsLT(VT) &&(static_cast<void> (0))
4959 "Invalid zext node, dst < src!")(static_cast<void> (0));
4960 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
4961 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4962 if (OpOpcode == ISD::UNDEF)
4963 // zext(undef) = 0, because the top bits will be zero.
4964 return getConstant(0, DL, VT);
4965 break;
4966 case ISD::ANY_EXTEND:
4967 assert(VT.isInteger() && Operand.getValueType().isInteger() &&(static_cast<void> (0))
4968 "Invalid ANY_EXTEND!")(static_cast<void> (0));
4969 assert(VT.isVector() == Operand.getValueType().isVector() &&(static_cast<void> (0))
4970 "ANY_EXTEND result type type should be vector iff the operand "(static_cast<void> (0))
4971 "type is vector!")(static_cast<void> (0));
4972 if (Operand.getValueType() == VT) return Operand; // noop extension
4973 assert((!VT.isVector() ||(static_cast<void> (0))
4974 VT.getVectorElementCount() ==(static_cast<void> (0))
4975 Operand.getValueType().getVectorElementCount()) &&(static_cast<void> (0))
4976 "Vector element count mismatch!")(static_cast<void> (0));
4977 assert(Operand.getValueType().bitsLT(VT) &&(static_cast<void> (0))
4978 "Invalid anyext node, dst < src!")(static_cast<void> (0));
4979
4980 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4981 OpOpcode == ISD::ANY_EXTEND)
4982 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
4983 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4984 if (OpOpcode == ISD::UNDEF)
4985 return getUNDEF(VT);
4986
4987 // (ext (trunc x)) -> x
4988 if (OpOpcode == ISD::TRUNCATE) {
4989 SDValue OpOp = Operand.getOperand(0);
4990 if (OpOp.getValueType() == VT) {
4991 transferDbgValues(Operand, OpOp);
4992 return OpOp;
4993 }
4994 }
4995 break;
4996 case ISD::TRUNCATE:
4997 assert(VT.isInteger() && Operand.getValueType().isInteger() &&(static_cast<void> (0))
4998 "Invalid TRUNCATE!")(static_cast<void> (0));
4999 assert(VT.isVector() == Operand.getValueType().isVector() &&(static_cast<void> (0))
5000 "TRUNCATE result type type should be vector iff the operand "(static_cast<void> (0))
5001 "type is vector!")(static_cast<void> (0));
5002 if (Operand.getValueType() == VT) return Operand; // noop truncate
5003 assert((!VT.isVector() ||(static_cast<void> (0))
5004 VT.getVectorElementCount() ==(static_cast<void> (0))
5005 Operand.getValueType().getVectorElementCount()) &&(static_cast<void> (0))
5006 "Vector element count mismatch!")(static_cast<void> (0));
5007 assert(Operand.getValueType().bitsGT(VT) &&(static_cast<void> (0))
5008 "Invalid truncate node, src < dst!")(static_cast<void> (0));
5009 if (OpOpcode == ISD::TRUNCATE)
5010 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5011 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5012 OpOpcode == ISD::ANY_EXTEND) {
5013 // If the source is smaller than the dest, we still need an extend.
5014 if (Operand.getOperand(0).getValueType().getScalarType()
5015 .bitsLT(VT.getScalarType()))
5016 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5017 if (Operand.getOperand(0).getValueType().bitsGT(VT))
5018 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5019 return Operand.getOperand(0);
5020 }
5021 if (OpOpcode == ISD::UNDEF)
5022 return getUNDEF(VT);
5023 break;
5024 case ISD::ANY_EXTEND_VECTOR_INREG:
5025 case ISD::ZERO_EXTEND_VECTOR_INREG:
5026 case ISD::SIGN_EXTEND_VECTOR_INREG:
5027 assert(VT.isVector() && "This DAG node is restricted to vector types.")(static_cast<void> (0));
5028 assert(Operand.getValueType().bitsLE(VT) &&(static_cast<void> (0))
5029 "The input must be the same size or smaller than the result.")(static_cast<void> (0));
5030 assert(VT.getVectorMinNumElements() <(static_cast<void> (0))
5031 Operand.getValueType().getVectorMinNumElements() &&(static_cast<void> (0))
5032 "The destination vector type must have fewer lanes than the input.")(static_cast<void> (0));
5033 break;
5034 case ISD::ABS:
5035 assert(VT.isInteger() && VT == Operand.getValueType() &&(static_cast<void> (0))
5036 "Invalid ABS!")(static_cast<void> (0));
5037 if (OpOpcode == ISD::UNDEF)
5038 return getUNDEF(VT);
5039 break;
5040 case ISD::BSWAP:
5041 assert(VT.isInteger() && VT == Operand.getValueType() &&(static_cast<void> (0))
5042 "Invalid BSWAP!")(static_cast<void> (0));
5043 assert((VT.getScalarSizeInBits() % 16 == 0) &&(static_cast<void> (0))
5044 "BSWAP types must be a multiple of 16 bits!")(static_cast<void> (0));
5045 if (OpOpcode == ISD::UNDEF)
5046 return getUNDEF(VT);
5047 break;
5048 case ISD::BITREVERSE:
5049 assert(VT.isInteger() && VT == Operand.getValueType() &&(static_cast<void> (0))
5050 "Invalid BITREVERSE!")(static_cast<void> (0));
5051 if (OpOpcode == ISD::UNDEF)
5052 return getUNDEF(VT);
5053 break;
5054 case ISD::BITCAST:
5055 // Basic sanity checking.
5056 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&(static_cast<void> (0))
5057 "Cannot BITCAST between types of different sizes!")(static_cast<void> (0));
5058 if (VT == Operand.getValueType()) return Operand; // noop conversion.
5059 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
5060 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5061 if (OpOpcode == ISD::UNDEF)
5062 return getUNDEF(VT);
5063 break;
5064 case ISD::SCALAR_TO_VECTOR:
5065 assert(VT.isVector() && !Operand.getValueType().isVector() &&(static_cast<void> (0))
5066 (VT.getVectorElementType() == Operand.getValueType() ||(static_cast<void> (0))
5067 (VT.getVectorElementType().isInteger() &&(static_cast<void> (0))
5068 Operand.getValueType().isInteger() &&(static_cast<void> (0))
5069 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&(static_cast<void> (0))
5070 "Illegal SCALAR_TO_VECTOR node!")(static_cast<void> (0));
5071 if (OpOpcode == ISD::UNDEF)
5072 return getUNDEF(VT);
5073 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5074 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5075 isa<ConstantSDNode>(Operand.getOperand(1)) &&
5076 Operand.getConstantOperandVal(1) == 0 &&
5077 Operand.getOperand(0).getValueType() == VT)
5078 return Operand.getOperand(0);
5079 break;
5080 case ISD::FNEG:
5081 // Negation of an unknown bag of bits is still completely undefined.
5082 if (OpOpcode == ISD::UNDEF)
5083 return getUNDEF(VT);
5084
5085 if (OpOpcode == ISD::FNEG) // --X -> X
5086 return Operand.getOperand(0);
5087 break;
5088 case ISD::FABS:
5089 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
5090 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5091 break;
5092 case ISD::VSCALE:
5093 assert(VT == Operand.getValueType() && "Unexpected VT!")(static_cast<void> (0));
5094 break;
5095 case ISD::CTPOP:
5096 if (Operand.getValueType().getScalarType() == MVT::i1)
5097 return Operand;
5098 break;
5099 case ISD::CTLZ:
5100 case ISD::CTTZ:
5101 if (Operand.getValueType().getScalarType() == MVT::i1)
5102 return getNOT(DL, Operand, Operand.getValueType());
5103 break;
5104 case ISD::VECREDUCE_SMIN:
5105 case ISD::VECREDUCE_UMAX:
5106 if (Operand.getValueType().getScalarType() == MVT::i1)
5107 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5108 break;
5109 case ISD::VECREDUCE_SMAX:
5110 case ISD::VECREDUCE_UMIN:
5111 if (Operand.getValueType().getScalarType() == MVT::i1)
5112 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5113 break;
5114 }
5115
5116 SDNode *N;
5117 SDVTList VTs = getVTList(VT);
5118 SDValue Ops[] = {Operand};
5119 if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5120 FoldingSetNodeID ID;
5121 AddNodeIDNode(ID, Opcode, VTs, Ops);
5122 void *IP = nullptr;
5123 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5124 E->intersectFlagsWith(Flags);
5125 return SDValue(E, 0);
5126 }
5127
5128 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5129 N->setFlags(Flags);
5130 createOperands(N, Ops);
5131 CSEMap.InsertNode(N, IP);
5132 } else {
5133 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5134 createOperands(N, Ops);
5135 }
5136
5137 InsertNode(N);
5138 SDValue V = SDValue(N, 0);
5139 NewSDValueDbgMsg(V, "Creating new node: ", this);
5140 return V;
5141}
5142
5143static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5144 const APInt &C2) {
5145 switch (Opcode) {
5146 case ISD::ADD: return C1 + C2;
5147 case ISD::SUB: return C1 - C2;
5148 case ISD::MUL: return C1 * C2;
5149 case ISD::AND: return C1 & C2;
5150 case ISD::OR: return C1 | C2;
5151 case ISD::XOR: return C1 ^ C2;
5152 case ISD::SHL: return C1 << C2;
5153 case ISD::SRL: return C1.lshr(C2);
5154 case ISD::SRA: return C1.ashr(C2);
5155 case ISD::ROTL: return C1.rotl(C2);
5156 case ISD::ROTR: return C1.rotr(C2);
5157 case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5158 case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5159 case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5160 case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5161 case ISD::SADDSAT: return C1.sadd_sat(C2);
5162 case ISD::UADDSAT: return C1.uadd_sat(C2);
5163 case ISD::SSUBSAT: return C1.ssub_sat(C2);
5164 case ISD::USUBSAT: return C1.usub_sat(C2);
5165 case ISD::UDIV:
5166 if (!C2.getBoolValue())
5167 break;
5168 return C1.udiv(C2);
5169 case ISD::UREM:
5170 if (!C2.getBoolValue())
5171 break;
5172 return C1.urem(C2);
5173 case ISD::SDIV:
5174 if (!C2.getBoolValue())
5175 break;
5176 return C1.sdiv(C2);
5177 case ISD::SREM:
5178 if (!C2.getBoolValue())
5179 break;
5180 return C1.srem(C2);
5181 case ISD::MULHS: {
5182 unsigned FullWidth = C1.getBitWidth() * 2;
5183 APInt C1Ext = C1.sext(FullWidth);
5184 APInt C2Ext = C2.sext(FullWidth);
5185 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5186 }
5187 case ISD::MULHU: {
5188 unsigned FullWidth = C1.getBitWidth() * 2;
5189 APInt C1Ext = C1.zext(FullWidth);
5190 APInt C2Ext = C2.zext(FullWidth);
5191 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5192 }
5193 }
5194 return llvm::None;
5195}
5196
5197SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5198 const GlobalAddressSDNode *GA,
5199 const SDNode *N2) {
5200 if (GA->getOpcode() != ISD::GlobalAddress)
5201 return SDValue();
5202 if (!TLI->isOffsetFoldingLegal(GA))
5203 return SDValue();
5204 auto *C2 = dyn_cast<ConstantSDNode>(N2);
5205 if (!C2)
5206 return SDValue();
5207 int64_t Offset = C2->getSExtValue();
5208 switch (Opcode) {
5209 case ISD::ADD: break;
5210 case ISD::SUB: Offset = -uint64_t(Offset); break;
5211 default: return SDValue();
5212 }
5213 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5214 GA->getOffset() + uint64_t(Offset));
5215}
5216
5217bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5218 switch (Opcode) {
5219 case ISD::SDIV:
5220 case ISD::UDIV:
5221 case ISD::SREM:
5222 case ISD::UREM: {
5223 // If a divisor is zero/undef or any element of a divisor vector is
5224 // zero/undef, the whole op is undef.
5225 assert(Ops.size() == 2 && "Div/rem should have 2 operands")(static_cast<void> (0));
5226 SDValue Divisor = Ops[1];
5227 if (Divisor.isUndef() || isNullConstant(Divisor))
5228 return true;
5229
5230 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5231 llvm::any_of(Divisor->op_values(),
5232 [](SDValue V) { return V.isUndef() ||
5233 isNullConstant(V); });
5234 // TODO: Handle signed overflow.
5235 }
5236 // TODO: Handle oversized shifts.
5237 default:
5238 return false;
5239 }
5240}
5241
5242SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5243 EVT VT, ArrayRef<SDValue> Ops) {
5244 // If the opcode is a target-specific ISD node, there's nothing we can
5245 // do here and the operand rules may not line up with the below, so
5246 // bail early.
5247 // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5248 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5249 // foldCONCAT_VECTORS in getNode before this is called.
5250 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5251 return SDValue();
5252
5253 // For now, the array Ops should only contain two values.
5254 // This enforcement will be removed once this function is merged with
5255 // FoldConstantVectorArithmetic
5256 if (Ops.size() != 2)
5257 return SDValue();
5258
5259 if (isUndef(Opcode, Ops))
5260 return getUNDEF(VT);
5261
5262 SDNode *N1 = Ops[0].getNode();
5263 SDNode *N2 = Ops[1].getNode();
5264
5265 // Handle the case of two scalars.
5266 if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
5267 if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) {
5268 if (C1->isOpaque() || C2->isOpaque())
5269 return SDValue();
5270
5271 Optional<APInt> FoldAttempt =
5272 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5273 if (!FoldAttempt)
5274 return SDValue();
5275
5276 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5277 assert((!Folded || !VT.isVector()) &&(static_cast<void> (0))
5278 "Can't fold vectors ops with scalar operands")(static_cast<void> (0));
5279 return Folded;
5280 }
5281 }
5282
5283 // fold (add Sym, c) -> Sym+c
5284 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1))
5285 return FoldSymbolOffset(Opcode, VT, GA, N2);
5286 if (TLI->isCommutativeBinOp(Opcode))
5287 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2))
5288 return FoldSymbolOffset(Opcode, VT, GA, N1);
5289
5290 // For fixed width vectors, extract each constant element and fold them
5291 // individually. Either input may be an undef value.
5292 bool IsBVOrSV1 = N1->getOpcode() == ISD::BUILD_VECTOR ||
5293 N1->getOpcode() == ISD::SPLAT_VECTOR;
5294 if (!IsBVOrSV1 && !N1->isUndef())
5295 return SDValue();
5296 bool IsBVOrSV2 = N2->getOpcode() == ISD::BUILD_VECTOR ||
5297 N2->getOpcode() == ISD::SPLAT_VECTOR;
5298 if (!IsBVOrSV2 && !N2->isUndef())
5299 return SDValue();
5300 // If both operands are undef, that's handled the same way as scalars.
5301 if (!IsBVOrSV1 && !IsBVOrSV2)
5302 return SDValue();
5303
5304 EVT SVT = VT.getScalarType();
5305 EVT LegalSVT = SVT;
5306 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5307 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5308 if (LegalSVT.bitsLT(SVT))
5309 return SDValue();
5310 }
5311
5312 SmallVector<SDValue, 4> Outputs;
5313 unsigned NumOps = 0;
5314 if (IsBVOrSV1)
5315 NumOps = std::max(NumOps, N1->getNumOperands());
5316 if (IsBVOrSV2)
5317 NumOps = std::max(NumOps, N2->getNumOperands());
5318 assert(NumOps != 0 && "Expected non-zero operands")(static_cast<void> (0));
5319 // Scalable vectors should only be SPLAT_VECTOR or UNDEF here. We only need
5320 // one iteration for that.
5321 assert((!VT.isScalableVector() || NumOps == 1) &&(static_cast<void> (0))
5322 "Scalable vector should only have one scalar")(static_cast<void> (0));
5323
5324 for (unsigned I = 0; I != NumOps; ++I) {
5325 // We can have a fixed length SPLAT_VECTOR and a BUILD_VECTOR so we need
5326 // to use operand 0 of the SPLAT_VECTOR for each fixed element.
5327 SDValue V1;
5328 if (N1->getOpcode() == ISD::BUILD_VECTOR)
5329 V1 = N1->getOperand(I);
5330 else if (N1->getOpcode() == ISD::SPLAT_VECTOR)
5331 V1 = N1->getOperand(0);
5332 else
5333 V1 = getUNDEF(SVT);
5334
5335 SDValue V2;
5336 if (N2->getOpcode() == ISD::BUILD_VECTOR)
5337 V2 = N2->getOperand(I);
5338 else if (N2->getOpcode() == ISD::SPLAT_VECTOR)
5339 V2 = N2->getOperand(0);
5340 else
5341 V2 = getUNDEF(SVT);
5342
5343 if (SVT.isInteger()) {
5344 if (V1.getValueType().bitsGT(SVT))
5345 V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
5346 if (V2.getValueType().bitsGT(SVT))
5347 V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
5348 }
5349
5350 if (V1.getValueType() != SVT || V2.getValueType() != SVT)
5351 return SDValue();
5352
5353 // Fold one vector element.
5354 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
5355 if (LegalSVT != SVT)
5356 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5357
5358 // Scalar folding only succeeded if the result is a constant or UNDEF.
5359 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5360 ScalarResult.getOpcode() != ISD::ConstantFP)
5361 return SDValue();
5362 Outputs.push_back(ScalarResult);
5363 }
5364
5365 if (N1->getOpcode() == ISD::BUILD_VECTOR ||
5366 N2->getOpcode() == ISD::BUILD_VECTOR) {
5367 assert(VT.getVectorNumElements() == Outputs.size() &&(static_cast<void> (0))
5368 "Vector size mismatch!")(static_cast<void> (0));
5369
5370 // Build a big vector out of the scalar elements we generated.
5371 return getBuildVector(VT, SDLoc(), Outputs);
5372 }
5373
5374 assert((N1->getOpcode() == ISD::SPLAT_VECTOR ||(static_cast<void> (0))
5375 N2->getOpcode() == ISD::SPLAT_VECTOR) &&(static_cast<void> (0))
5376 "One operand should be a splat vector")(static_cast<void> (0));
5377
5378 assert(Outputs.size() == 1 && "Vector size mismatch!")(static_cast<void> (0));
5379 return getSplatVector(VT, SDLoc(), Outputs[0]);
5380}
5381
5382// TODO: Merge with FoldConstantArithmetic
5383SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
5384 const SDLoc &DL, EVT VT,
5385 ArrayRef<SDValue> Ops,
5386 const SDNodeFlags Flags) {
5387 // If the opcode is a target-specific ISD node, there's nothing we can
5388 // do here and the operand rules may not line up with the below, so
5389 // bail early.
5390 if (Opcode >= ISD::BUILTIN_OP_END)
5391 return SDValue();
5392
5393 if (isUndef(Opcode, Ops))
5394 return getUNDEF(VT);
5395
5396 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
5397 if (!VT.isVector())
5398 return SDValue();
5399
5400 ElementCount NumElts = VT.getVectorElementCount();
5401
5402 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5403 return !Op.getValueType().isVector() ||
5404 Op.getValueType().getVectorElementCount() == NumElts;
5405 };
5406
5407 auto IsConstantBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5408 APInt SplatVal;
5409 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
5410 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5411 (BV && BV->isConstant()) ||
5412 (Op.getOpcode() == ISD::SPLAT_VECTOR &&
5413 ISD::isConstantSplatVector(Op.getNode(), SplatVal));
5414 };
5415
5416 // All operands must be vector types with the same number of elements as
5417 // the result type and must be either UNDEF or a build vector of constant
5418 // or UNDEF scalars.
5419 if (!llvm::all_of(Ops, IsConstantBuildVectorSplatVectorOrUndef) ||
5420 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5421 return SDValue();
5422
5423 // If we are comparing vectors, then the result needs to be a i1 boolean
5424 // that is then sign-extended back to the legal result type.
5425 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5426
5427 // Find legal integer scalar type for constant promotion and
5428 // ensure that its scalar size is at least as large as source.
5429 EVT LegalSVT = VT.getScalarType();
5430 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5431 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5432 if (LegalSVT.bitsLT(VT.getScalarType()))
5433 return SDValue();
5434 }
5435
5436 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5437 // only have one operand to check. For fixed-length vector types we may have
5438 // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5439 unsigned NumOperands = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5440
5441 // Constant fold each scalar lane separately.
5442 SmallVector<SDValue, 4> ScalarResults;
5443 for (unsigned I = 0; I != NumOperands; I++) {
5444 SmallVector<SDValue, 4> ScalarOps;
5445 for (SDValue Op : Ops) {
5446 EVT InSVT = Op.getValueType().getScalarType();
5447 if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5448 Op.getOpcode() != ISD::SPLAT_VECTOR) {
5449 // We've checked that this is UNDEF or a constant of some kind.
5450 if (Op.isUndef())
5451 ScalarOps.push_back(getUNDEF(InSVT));
5452 else
5453 ScalarOps.push_back(Op);
5454 continue;
5455 }
5456
5457 SDValue ScalarOp =
5458 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5459 EVT ScalarVT = ScalarOp.getValueType();
5460
5461 // Build vector (integer) scalar operands may need implicit
5462 // truncation - do this before constant folding.
5463 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5464 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5465
5466 ScalarOps.push_back(ScalarOp);
5467 }
5468
5469 // Constant fold the scalar operands.
5470 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
5471
5472 // Legalize the (integer) scalar constant if necessary.
5473 if (LegalSVT != SVT)
5474 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5475
5476 // Scalar folding only succeeded if the result is a constant or UNDEF.
5477 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5478 ScalarResult.getOpcode() != ISD::ConstantFP)
5479 return SDValue();
5480 ScalarResults.push_back(ScalarResult);
5481 }
5482
5483 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5484 : getBuildVector(VT, DL, ScalarResults);
5485 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5486 return V;
5487}
5488
5489SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5490 EVT VT, SDValue N1, SDValue N2) {
5491 // TODO: We don't do any constant folding for strict FP opcodes here, but we
5492 // should. That will require dealing with a potentially non-default
5493 // rounding mode, checking the "opStatus" return value from the APFloat
5494 // math calculations, and possibly other variations.
5495 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
5496 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
5497 if (N1CFP && N2CFP) {
5498 APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
5499 switch (Opcode) {
5500 case ISD::FADD:
5501 C1.add(C2, APFloat::rmNearestTiesToEven);
5502 return getConstantFP(C1, DL, VT);
5503 case ISD::FSUB:
5504 C1.subtract(C2, APFloat::rmNearestTiesToEven);
5505 return getConstantFP(C1, DL, VT);
5506 case ISD::FMUL:
5507 C1.multiply(C2, APFloat::rmNearestTiesToEven);
5508 return getConstantFP(C1, DL, VT);
5509 case ISD::FDIV:
5510 C1.divide(C2, APFloat::rmNearestTiesToEven);
5511 return getConstantFP(C1, DL, VT);
5512 case ISD::FREM:
5513 C1.mod(C2);
5514 return getConstantFP(C1, DL, VT);
5515 case ISD::FCOPYSIGN:
5516 C1.copySign(C2);
5517 return getConstantFP(C1, DL, VT);
5518 default: break;
5519 }
5520 }
5521 if (N1CFP && Opcode == ISD::FP_ROUND) {
5522 APFloat C1 = N1CFP->getValueAPF(); // make copy
5523 bool Unused;
5524 // This can return overflow, underflow, or inexact; we don't care.
5525 // FIXME need to be more flexible about rounding mode.
5526 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5527 &Unused);
5528 return getConstantFP(C1, DL, VT);
5529 }
5530
5531 switch (Opcode) {
5532 case ISD::FSUB:
5533 // -0.0 - undef --> undef (consistent with "fneg undef")
5534 if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef())
5535 return getUNDEF(VT);
5536 LLVM_FALLTHROUGH[[gnu::fallthrough]];
5537
5538 case ISD::FADD:
5539 case ISD::FMUL:
5540 case ISD::FDIV:
5541 case ISD::FREM:
5542 // If both operands are undef, the result is undef. If 1 operand is undef,
5543 // the result is NaN. This should match the behavior of the IR optimizer.
5544 if (N1.isUndef() && N2.isUndef())
5545 return getUNDEF(VT);
5546 if (N1.isUndef() || N2.isUndef())
5547 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5548 }
5549 return SDValue();
5550}
5551
5552SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5553 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!")(static_cast<void> (0));
5554
5555 // There's no need to assert on a byte-aligned pointer. All pointers are at
5556 // least byte aligned.
5557 if (A == Align(1))
5558 return Val;
5559
5560 FoldingSetNodeID ID;
5561 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5562 ID.AddInteger(A.value());
5563
5564 void *IP = nullptr;
5565 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5566 return SDValue(E, 0);
5567
5568 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5569 Val.getValueType(), A);
5570 createOperands(N, {Val});
5571
5572 CSEMap.InsertNode(N, IP);
5573 InsertNode(N);
5574
5575 SDValue V(N, 0);
5576 NewSDValueDbgMsg(V, "Creating new node: ", this);
5577 return V;
5578}
5579
5580SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5581 SDValue N1, SDValue N2) {
5582 SDNodeFlags Flags;
5583 if (Inserter)
5584 Flags = Inserter->getFlags();
5585 return getNode(Opcode, DL, VT, N1, N2, Flags);
5586}
5587
5588SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5589 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5590 assert(N1.getOpcode() != ISD::DELETED_NODE &&(static_cast<void> (0))
5591 N2.getOpcode() != ISD::DELETED_NODE &&(static_cast<void> (0))
5592 "Operand is DELETED_NODE!")(static_cast<void> (0));
5593 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5594 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5595 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5596 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5597
5598 // Canonicalize constant to RHS if commutative.
5599 if (TLI->isCommutativeBinOp(Opcode)) {
5600 if (N1C && !N2C) {
5601 std::swap(N1C, N2C);
5602 std::swap(N1, N2);
5603 } else if (N1CFP && !N2CFP) {
5604 std::swap(N1CFP, N2CFP);
5605 std::swap(N1, N2);
5606 }
5607 }
5608
5609 switch (Opcode) {
5610 default: break;
5611 case ISD::TokenFactor:
5612 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&(static_cast<void> (0))
5613 N2.getValueType() == MVT::Other && "Invalid token factor!")(static_cast<void> (0));
5614 // Fold trivial token factors.
5615 if (N1.getOpcode() == ISD::EntryToken) return N2;
5616 if (N2.getOpcode() == ISD::EntryToken) return N1;
5617 if (N1 == N2) return N1;
5618 break;
5619 case ISD::BUILD_VECTOR: {
5620 // Attempt to simplify BUILD_VECTOR.
5621 SDValue Ops[] = {N1, N2};
5622 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5623 return V;
5624 break;
5625 }
5626 case ISD::CONCAT_VECTORS: {
5627 SDValue Ops[] = {N1, N2};
5628 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5629 return V;
5630 break;
5631 }
5632 case ISD::AND:
5633 assert(VT.isInteger() && "This operator does not apply to FP types!")(static_cast<void> (0));
5634 assert(N1.getValueType() == N2.getValueType() &&(static_cast<void> (0))
5635 N1.getValueType() == VT && "Binary operator types must match!")(static_cast<void> (0));
5636 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
5637 // worth handling here.
5638 if (N2C && N2C->isNullValue())
5639 return N2;
5640 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
5641 return N1;
5642 break;
5643 case ISD::OR:
5644 case ISD::XOR:
5645 case ISD::ADD:
5646 case ISD::SUB:
5647 assert(VT.isInteger() && "This operator does not apply to FP types!")(static_cast<void> (0));
5648 assert(N1.getValueType() == N2.getValueType() &&(static_cast<void> (0))
5649 N1.getValueType() == VT && "Binary operator types must match!")(static_cast<void> (0));
5650 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
5651 // it's worth handling here.
5652 if (N2C && N2C->isNullValue())
5653 return N1;
5654 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5655 VT.getVectorElementType() == MVT::i1)
5656 return getNode(ISD::XOR, DL, VT, N1, N2);
5657 break;
5658 case ISD::MUL:
5659 assert(VT.isInteger() && "This operator does not apply to FP types!")(static_cast<void> (0));
5660 assert(N1.getValueType() == N2.getValueType() &&(static_cast<void> (0))
5661 N1.getValueType() == VT && "Binary operator types must match!")(static_cast<void> (0));
5662 if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5663 return getNode(ISD::AND, DL, VT, N1, N2);
5664 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5665 const APInt &MulImm = N1->getConstantOperandAPInt(0);
5666 const APInt &N2CImm = N2C->getAPIntValue();
5667 return getVScale(DL, VT, MulImm * N2CImm);
5668 }
5669 break;
5670 case ISD::UDIV:
5671 case ISD::UREM:
5672 case ISD::MULHU:
5673 case ISD::MULHS:
5674 case ISD::SDIV:
5675 case ISD::SREM:
5676 case ISD::SADDSAT:
5677 case ISD::SSUBSAT:
5678 case ISD::UADDSAT:
5679 case ISD::USUBSAT:
5680 assert(VT.isInteger() && "This operator does not apply to FP types!")(static_cast<void> (0));
5681 assert(N1.getValueType() == N2.getValueType() &&(static_cast<void> (0))
5682 N1.getValueType() == VT && "Binary operator types must match!")(static_cast<void> (0));
5683 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5684 // fold (add_sat x, y) -> (or x, y) for bool types.
5685 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5686 return getNode(ISD::OR, DL, VT, N1, N2);
5687 // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5688 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5689 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5690 }
5691 break;
5692 case ISD::SMIN:
5693 case ISD::UMAX:
5694 assert(VT.isInteger() && "This operator does not apply to FP types!")(static_cast<void> (0));
5695 assert(N1.getValueType() == N2.getValueType() &&(static_cast<void> (0))
5696 N1.getValueType() == VT && "Binary operator types must match!")(static_cast<void> (0));
5697 if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5698 return getNode(ISD::OR, DL, VT, N1, N2);
5699 break;
5700 case ISD::SMAX:
5701 case ISD::UMIN:
5702 assert(VT.isInteger() && "This operator does not apply to FP types!")(static_cast<void> (0));
5703 assert(N1.getValueType() == N2.getValueType() &&(static_cast<void> (0))
5704 N1.getValueType() == VT && "Binary operator types must match!")(static_cast<void> (0));
5705 if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5706 return getNode(ISD::AND, DL, VT, N1, N2);
5707 break;
5708 case ISD::FADD:
5709 case ISD::FSUB:
5710 case ISD::FMUL:
5711 case ISD::FDIV:
5712 case ISD::FREM:
5713 assert(VT.isFloatingPoint() && "This operator only applies to FP types!")(static_cast<void> (0));
5714 assert(N1.getValueType() == N2.getValueType() &&(static_cast<void> (0))
5715 N1.getValueType() == VT && "Binary operator types must match!")(static_cast<void> (0));
5716 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5717 return V;
5718 break;
5719 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
5720 assert(N1.getValueType() == VT &&(static_cast<void> (0))
5721 N1.getValueType().isFloatingPoint() &&(static_cast<void> (0))
5722 N2.getValueType().isFloatingPoint() &&(static_cast<void> (0))
5723 "Invalid FCOPYSIGN!")(static_cast<void> (0));
5724 break;
5725 case ISD::SHL:
5726 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5727 const APInt &MulImm = N1->getConstantOperandAPInt(0);
5728 const APInt &ShiftImm = N2C->getAPIntValue();
5729 return getVScale(DL, VT, MulImm << ShiftImm);
5730 }
5731 LLVM_FALLTHROUGH[[gnu::fallthrough]];
5732 case ISD::SRA:
5733 case ISD::SRL:
5734 if (SDValue V = simplifyShift(N1, N2))
5735 return V;
5736 LLVM_FALLTHROUGH[[gnu::fallthrough]];
5737 case ISD::ROTL:
5738 case ISD::ROTR:
5739 assert(VT == N1.getValueType() &&(static_cast<void> (0))
5740 "Shift operators return type must be the same as their first arg")(static_cast<void> (0));
5741 assert(VT.isInteger() && N2.getValueType().isInteger() &&(static_cast<void> (0))
5742 "Shifts only work on integers")(static_cast<void> (0));
5743 assert((!VT.isVector() || VT == N2.getValueType()) &&(static_cast<void> (0))
5744 "Vector shift amounts must be in the same as their first arg")(static_cast<void> (0));
5745 // Verify that the shift amount VT is big enough to hold valid shift
5746 // amounts. This catches things like trying to shift an i1024 value by an
5747 // i8, which is easy to fall into in generic code that uses
5748 // TLI.getShiftAmount().
5749 assert(N2.getValueType().getScalarSizeInBits() >=(static_cast<void> (0))
5750 Log2_32_Ceil(VT.getScalarSizeInBits()) &&(static_cast<void> (0))
5751 "Invalid use of small shift amount with oversized value!")(static_cast<void> (0));
5752
5753 // Always fold shifts of i1 values so the code generator doesn't need to
5754 // handle them. Since we know the size of the shift has to be less than the
5755 // size of the value, the shift/rotate count is guaranteed to be zero.
5756 if (VT == MVT::i1)
5757 return N1;
5758 if (N2C && N2C->isNullValue())
5759 return N1;
5760 break;
5761 case ISD::FP_ROUND:
5762 assert(VT.isFloatingPoint() &&(static_cast<void> (0))
5763 N1.getValueType().isFloatingPoint() &&(static_cast<void> (0))
5764 VT.bitsLE(N1.getValueType()) &&(static_cast<void> (0))
5765 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&(static_cast<void> (0))
5766 "Invalid FP_ROUND!")(static_cast<void> (0));
5767 if (N1.getValueType() == VT) return N1; // noop conversion.
5768 break;
5769 case ISD::AssertSext:
5770 case ISD::AssertZext: {
5771 EVT EVT = cast<VTSDNode>(N2)->getVT();
5772 assert(VT == N1.getValueType() && "Not an inreg extend!")(static_cast<void> (0));
5773 assert(VT.isInteger() && EVT.isInteger() &&(static_cast<void> (0))
5774 "Cannot *_EXTEND_INREG FP types")(static_cast<void> (0));
5775 assert(!EVT.isVector() &&(static_cast<void> (0))
5776 "AssertSExt/AssertZExt type should be the vector element type "(static_cast<void> (0))
5777 "rather than the vector type!")(static_cast<void> (0));
5778 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!")(static_cast<void> (0));
5779 if (VT.getScalarType() == EVT) return N1; // noop assertion.
5780 break;
5781 }
5782 case ISD::SIGN_EXTEND_INREG: {
5783 EVT EVT = cast<VTSDNode>(N2)->getVT();
5784 assert(VT == N1.getValueType() && "Not an inreg extend!")(static_cast<void> (0));
5785 assert(VT.isInteger() && EVT.isInteger() &&(static_cast<void> (0))
5786 "Cannot *_EXTEND_INREG FP types")(static_cast<void> (0));
5787 assert(EVT.isVector() == VT.isVector() &&(static_cast<void> (0))
5788 "SIGN_EXTEND_INREG type should be vector iff the operand "(static_cast<void> (0))
5789 "type is vector!")(static_cast<void> (0));
5790 assert((!EVT.isVector() ||(static_cast<void> (0))
5791 EVT.getVectorElementCount() == VT.getVectorElementCount()) &&(static_cast<void> (0))
5792 "Vector element counts must match in SIGN_EXTEND_INREG")(static_cast<void> (0));
5793 assert(EVT.bitsLE(VT) && "Not extending!")(static_cast<void> (0));
5794 if (EVT == VT) return N1; // Not actually extending
5795
5796 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5797 unsigned FromBits = EVT.getScalarSizeInBits();
5798 Val <<= Val.getBitWidth() - FromBits;
5799 Val.ashrInPlace(Val.getBitWidth() - FromBits);
5800 return getConstant(Val, DL, ConstantVT);
5801 };
5802
5803 if (N1C) {
5804 const APInt &Val = N1C->getAPIntValue();
5805 return SignExtendInReg(Val, VT);
5806 }
5807
5808 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5809 SmallVector<SDValue, 8> Ops;
5810 llvm::EVT OpVT = N1.getOperand(0).getValueType();
5811 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5812 SDValue Op = N1.getOperand(i);
5813 if (Op.isUndef()) {
5814 Ops.push_back(getUNDEF(OpVT));
5815 continue;
5816 }
5817 ConstantSDNode *C = cast<ConstantSDNode>(Op);
5818 APInt Val = C->getAPIntValue();
5819 Ops.push_back(SignExtendInReg(Val, OpVT));
5820 }
5821 return getBuildVector(VT, DL, Ops);
5822 }
5823 break;
5824 }
5825 case ISD::FP_TO_SINT_SAT:
5826 case ISD::FP_TO_UINT_SAT: {
5827 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&(static_cast<void> (0))
5828 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT")(static_cast<void> (0));
5829 assert(N1.getValueType().isVector() == VT.isVector() &&(static_cast<void> (0))
5830 "FP_TO_*INT_SAT type should be vector iff the operand type is "(static_cast<void> (0))
5831 "vector!")(static_cast<void> (0));
5832 assert((!VT.isVector() || VT.getVectorNumElements() ==(static_cast<void> (0))
5833 N1.getValueType().getVectorNumElements()) &&(static_cast<void> (0))
5834 "Vector element counts must match in FP_TO_*INT_SAT")(static_cast<void> (0));
5835 assert(!cast<VTSDNode>(N2)->getVT().isVector() &&(static_cast<void> (0))
5836 "Type to saturate to must be a scalar.")(static_cast<void> (0));
5837 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&(static_cast<void> (0))
5838 "Not extending!")(static_cast<void> (0));
5839 break;
5840 }
5841 case ISD::EXTRACT_VECTOR_ELT:
5842 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&(static_cast<void> (0))
5843 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \(static_cast<void> (0))
5844 element type of the vector.")(static_cast<void> (0));
5845
5846 // Extract from an undefined value or using an undefined index is undefined.
5847 if (N1.isUndef() || N2.isUndef())
5848 return getUNDEF(VT);
5849
5850 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5851 // vectors. For scalable vectors we will provide appropriate support for
5852 // dealing with arbitrary indices.
5853 if (N2C && N1.getValueType().isFixedLengthVector() &&
5854 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5855 return getUNDEF(VT);
5856
5857 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5858 // expanding copies of large vectors from registers. This only works for
5859 // fixed length vectors, since we need to know the exact number of
5860 // elements.
5861 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5862 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5863 unsigned Factor =
5864 N1.getOperand(0).getValueType().getVectorNumElements();
5865 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5866 N1.getOperand(N2C->getZExtValue() / Factor),
5867 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5868 }
5869
5870 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5871 // lowering is expanding large vector constants.
5872 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5873 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5874 assert((N1.getOpcode() != ISD::BUILD_VECTOR ||(static_cast<void> (0))
5875 N1.getValueType().isFixedLengthVector()) &&(static_cast<void> (0))
5876 "BUILD_VECTOR used for scalable vectors")(static_cast<void> (0));
5877 unsigned Index =
5878 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5879 SDValue Elt = N1.getOperand(Index);
5880
5881 if (VT != Elt.getValueType())
5882 // If the vector element type is not legal, the BUILD_VECTOR operands
5883 // are promoted and implicitly truncated, and the result implicitly
5884 // extended. Make that explicit here.
5885 Elt = getAnyExtOrTrunc(Elt, DL, VT);
5886
5887 return Elt;
5888 }
5889
5890 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5891 // operations are lowered to scalars.
5892 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5893 // If the indices are the same, return the inserted element else
5894 // if the indices are known different, extract the element from
5895 // the original vector.
5896 SDValue N1Op2 = N1.getOperand(2);
5897 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5898
5899 if (N1Op2C && N2C) {
5900 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5901 if (VT == N1.getOperand(1).getValueType())
5902 return N1.getOperand(1);
5903 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5904 }
5905 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5906 }
5907 }
5908
5909 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5910 // when vector types are scalarized and v1iX is legal.
5911 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5912 // Here we are completely ignoring the extract element index (N2),
5913 // which is fine for fixed width vectors, since any index other than 0
5914 // is undefined anyway. However, this cannot be ignored for scalable
5915 // vectors - in theory we could support this, but we don't want to do this
5916 // without a profitability check.
5917 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5918 N1.getValueType().isFixedLengthVector() &&
5919 N1.getValueType().getVectorNumElements() == 1) {
5920 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5921 N1.getOperand(1));
5922 }
5923 break;
5924 case ISD::EXTRACT_ELEMENT:
5925 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!")(static_cast<void> (0));
5926 assert(!N1.getValueType().isVector() && !VT.isVector() &&(static_cast<void> (0))
5927 (N1.getValueType().isInteger() == VT.isInteger()) &&(static_cast<void> (0))
5928 N1.getValueType() != VT &&(static_cast<void> (0))
5929 "Wrong types for EXTRACT_ELEMENT!")(static_cast<void> (0));
5930
5931 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5932 // 64-bit integers into 32-bit parts. Instead of building the extract of
5933 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5934 if (N1.getOpcode() == ISD::BUILD_PAIR)
5935 return N1.getOperand(N2C->getZExtValue());
5936
5937 // EXTRACT_ELEMENT of a constant int is also very common.
5938 if (N1C) {
5939 unsigned ElementSize = VT.getSizeInBits();
5940 unsigned Shift = ElementSize * N2C->getZExtValue();
5941 const APInt &Val = N1C->getAPIntValue();
5942 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
5943 }
5944 break;
5945 case ISD::EXTRACT_SUBVECTOR: {
5946 EVT N1VT = N1.getValueType();
5947 assert(VT.isVector() && N1VT.isVector() &&(static_cast<void> (0))
5948 "Extract subvector VTs must be vectors!")(static_cast<void> (0));
5949 assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&(static_cast<void> (0))
5950 "Extract subvector VTs must have the same element type!")(static_cast<void> (0));
5951 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&(static_cast<void> (0))
5952 "Cannot extract a scalable vector from a fixed length vector!")(static_cast<void> (0));
5953 assert((VT.isScalableVector() != N1VT.isScalableVector() ||(static_cast<void> (0))
5954 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&(static_cast<void> (0))
5955 "Extract subvector must be from larger vector to smaller vector!")(static_cast<void> (0));
5956 assert(N2C && "Extract subvector index must be a constant")(static_cast<void> (0));
5957 assert((VT.isScalableVector() != N1VT.isScalableVector() ||(static_cast<void> (0))
5958 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=(static_cast<void> (0))
5959 N1VT.getVectorMinNumElements()) &&(static_cast<void> (0))
5960 "Extract subvector overflow!")(static_cast<void> (0));
5961 assert(N2C->getAPIntValue().getBitWidth() ==(static_cast<void> (0))
5962 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&(static_cast<void> (0))
5963 "Constant index for EXTRACT_SUBVECTOR has an invalid size")(static_cast<void> (0));
5964
5965 // Trivial extraction.
5966 if (VT == N1VT)
5967 return N1;
5968
5969 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5970 if (N1.isUndef())
5971 return getUNDEF(VT);
5972
5973 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5974 // the concat have the same type as the extract.
5975 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
5976 VT == N1.getOperand(0).getValueType()) {
5977 unsigned Factor = VT.getVectorMinNumElements();
5978 return N1.getOperand(N2C->getZExtValue() / Factor);
5979 }
5980
5981 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5982 // during shuffle legalization.
5983 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5984 VT == N1.getOperand(1).getValueType())
5985 return N1.getOperand(1);
5986 break;
5987 }
5988 }
5989
5990 // Perform trivial constant folding.
5991 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
5992 return SV;
5993
5994 if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
5995 return V;
5996
5997 // Canonicalize an UNDEF to the RHS, even over a constant.
5998 if (N1.isUndef()) {
5999 if (TLI->isCommutativeBinOp(Opcode)) {
6000 std::swap(N1, N2);
6001 } else {
6002 switch (Opcode) {
6003 case ISD::SIGN_EXTEND_INREG:
6004 case ISD::SUB:
6005 return getUNDEF(VT); // fold op(undef, arg2) -> undef
6006 case ISD::UDIV:
6007 case ISD::SDIV:
6008 case ISD::UREM:
6009 case ISD::SREM:
6010 case ISD::SSUBSAT:
6011 case ISD::USUBSAT:
6012 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
6013 }
6014 }
6015 }
6016
6017 // Fold a bunch of operators when the RHS is undef.
6018 if (N2.isUndef()) {
6019 switch (Opcode) {
6020 case ISD::XOR:
6021 if (N1.isUndef())
6022 // Handle undef ^ undef -> 0 special case. This is a common
6023 // idiom (misuse).
6024 return getConstant(0, DL, VT);
6025 LLVM_FALLTHROUGH[[gnu::fallthrough]];
6026 case ISD::ADD:
6027 case ISD::SUB:
6028 case ISD::UDIV:
6029 case ISD::SDIV:
6030 case ISD::UREM:
6031 case ISD::SREM:
6032 return getUNDEF(VT); // fold op(arg1, undef) -> undef
6033 case ISD::MUL:
6034 case ISD::AND:
6035 case ISD::SSUBSAT:
6036 case ISD::USUBSAT:
6037 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
6038 case ISD::OR:
6039 case ISD::SADDSAT:
6040 case ISD::UADDSAT:
6041 return getAllOnesConstant(DL, VT);
6042 }
6043 }
6044
6045 // Memoize this node if possible.
6046 SDNode *N;
6047 SDVTList VTs = getVTList(VT);
6048 SDValue Ops[] = {N1, N2};
6049 if (VT != MVT::Glue) {
6050 FoldingSetNodeID ID;
6051 AddNodeIDNode(ID, Opcode, VTs, Ops);
6052 void *IP = nullptr;
6053 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6054 E->intersectFlagsWith(Flags);
6055 return SDValue(E, 0);
6056 }
6057
6058 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6059 N->setFlags(Flags);
6060 createOperands(N, Ops);
6061 CSEMap.InsertNode(N, IP);
6062 } else {
6063 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6064 createOperands(N, Ops);
6065 }
6066
6067 InsertNode(N);
6068 SDValue V = SDValue(N, 0);
6069 NewSDValueDbgMsg(V, "Creating new node: ", this);
6070 return V;
6071}
6072
6073SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6074 SDValue N1, SDValue N2, SDValue N3) {
6075 SDNodeFlags Flags;
6076 if (Inserter)
6077 Flags = Inserter->getFlags();
6078 return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6079}
6080
6081SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6082 SDValue N1, SDValue N2, SDValue N3,
6083 const SDNodeFlags Flags) {
6084 assert(N1.getOpcode() != ISD::DELETED_NODE &&(static_cast<void> (0))
6085 N2.getOpcode() != ISD::DELETED_NODE &&(static_cast<void> (0))
6086 N3.getOpcode() != ISD::DELETED_NODE &&(static_cast<void> (0))
6087 "Operand is DELETED_NODE!")(static_cast<void> (0));
6088 // Perform various simplifications.
6089 switch (Opcode) {
6090 case ISD::FMA: {
6091 assert(VT.isFloatingPoint() && "This operator only applies to FP types!")(static_cast<void> (0));
6092 assert(N1.getValueType() == VT && N2.getValueType() == VT &&(static_cast<void> (0))
6093 N3.getValueType() == VT && "FMA types must match!")(static_cast<void> (0));
6094 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6095 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6096 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6097 if (N1CFP && N2CFP && N3CFP) {
6098 APFloat V1 = N1CFP->getValueAPF();
6099 const APFloat &V2 = N2CFP->getValueAPF();
6100 const APFloat &V3 = N3CFP->getValueAPF();
6101 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6102 return getConstantFP(V1, DL, VT);
6103 }
6104 break;
6105 }
6106 case ISD::BUILD_VECTOR: {
6107 // Attempt to simplify BUILD_VECTOR.
6108 SDValue Ops[] = {N1, N2, N3};
6109 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6110 return V;
6111 break;
6112 }
6113 case ISD::CONCAT_VECTORS: {
6114 SDValue Ops[] = {N1, N2, N3};
6115 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6116 return V;
6117 break;
6118 }
6119 case ISD::SETCC: {
6120 assert(VT.isInteger() && "SETCC result type must be an integer!")(static_cast<void> (0));
6121 assert(N1.getValueType() == N2.getValueType() &&(static_cast<void> (0))
6122 "SETCC operands must have the same type!")(static_cast<void> (0));
6123 assert(VT.isVector() == N1.getValueType().isVector() &&(static_cast<void> (0))
6124 "SETCC type should be vector iff the operand type is vector!")(static_cast<void> (0));
6125 assert((!VT.isVector() || VT.getVectorElementCount() ==(static_cast<void> (0))
6126 N1.getValueType().getVectorElementCount()) &&(static_cast<void> (0))
6127 "SETCC vector element counts must match!")(static_cast<void> (0));
6128 // Use FoldSetCC to simplify SETCC's.
6129 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6130 return V;
6131 // Vector constant folding.
6132 SDValue Ops[] = {N1, N2, N3};
6133 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
6134 NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6135 return V;
6136 }
6137 break;
6138 }
6139 case ISD::SELECT:
6140 case ISD::VSELECT:
6141 if (SDValue V = simplifySelect(N1, N2, N3))
6142 return V;
6143 break;
6144 case ISD::VECTOR_SHUFFLE:
6145 llvm_unreachable("should use getVectorShuffle constructor!")__builtin_unreachable();
6146 case ISD::INSERT_VECTOR_ELT: {
6147 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6148 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6149 // for scalable vectors where we will generate appropriate code to
6150 // deal with out-of-bounds cases correctly.
6151 if (N3C && N1.getValueType().isFixedLengthVector() &&
6152 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6153 return getUNDEF(VT);
6154
6155 // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6156 if (N3.isUndef())
6157 return getUNDEF(VT);
6158
6159 // If the inserted element is an UNDEF, just use the input vector.
6160 if (N2.isUndef())
6161 return N1;
6162
6163 break;
6164 }
6165 case ISD::INSERT_SUBVECTOR: {
6166 // Inserting undef into undef is still undef.
6167 if (N1.isUndef() && N2.isUndef())
6168 return getUNDEF(VT);
6169
6170 EVT N2VT = N2.getValueType();
6171 assert(VT == N1.getValueType() &&(static_cast<void> (0))
6172 "Dest and insert subvector source types must match!")(static_cast<void> (0));
6173 assert(VT.isVector() && N2VT.isVector() &&(static_cast<void> (0))
6174 "Insert subvector VTs must be vectors!")(static_cast<void> (0));
6175 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&(static_cast<void> (0))
6176 "Cannot insert a scalable vector into a fixed length vector!")(static_cast<void> (0));
6177 assert((VT.isScalableVector() != N2VT.isScalableVector() ||(static_cast<void> (0))
6178 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&(static_cast<void> (0))
6179 "Insert subvector must be from smaller vector to larger vector!")(static_cast<void> (0));
6180 assert(isa<ConstantSDNode>(N3) &&(static_cast<void> (0))
6181 "Insert subvector index must be constant")(static_cast<void> (0));
6182 assert((VT.isScalableVector() != N2VT.isScalableVector() ||(static_cast<void> (0))
6183 (N2VT.getVectorMinNumElements() +(static_cast<void> (0))
6184 cast<ConstantSDNode>(N3)->getZExtValue()) <=(static_cast<void> (0))
6185 VT.getVectorMinNumElements()) &&(static_cast<void> (0))
6186 "Insert subvector overflow!")(static_cast<void> (0));
6187 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==(static_cast<void> (0))
6188 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&(static_cast<void> (0))
6189 "Constant index for INSERT_SUBVECTOR has an invalid size")(static_cast<void> (0));
6190
6191 // Trivial insertion.
6192 if (VT == N2VT)
6193 return N2;
6194
6195 // If this is an insert of an extracted vector into an undef vector, we
6196 // can just use the input to the extract.
6197 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6198 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6199 return N2.getOperand(0);
6200 break;
6201 }
6202 case ISD::BITCAST:
6203 // Fold bit_convert nodes from a type to themselves.
6204 if (N1.getValueType() == VT)
6205 return N1;
6206 break;
6207 }
6208
6209 // Memoize node if it doesn't produce a flag.
6210 SDNode *N;
6211 SDVTList VTs = getVTList(VT);
6212 SDValue Ops[] = {N1, N2, N3};
6213 if (VT != MVT::Glue) {
6214 FoldingSetNodeID ID;
6215 AddNodeIDNode(ID, Opcode, VTs, Ops);
6216 void *IP = nullptr;
6217 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6218 E->intersectFlagsWith(Flags);
6219 return SDValue(E, 0);
6220 }
6221
6222 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6223 N->setFlags(Flags);
6224 createOperands(N, Ops);
6225 CSEMap.InsertNode(N, IP);
6226 } else {
6227 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6228 createOperands(N, Ops);
6229 }
6230
6231 InsertNode(N);
6232 SDValue V = SDValue(N, 0);
6233 NewSDValueDbgMsg(V, "Creating new node: ", this);
6234 return V;
6235}
6236
6237SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6238 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6239 SDValue Ops[] = { N1, N2, N3, N4 };
6240 return getNode(Opcode, DL, VT, Ops);
6241}
6242
6243SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6244 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6245 SDValue N5) {
6246 SDValue Ops[] = { N1, N2, N3, N4, N5 };
6247 return getNode(Opcode, DL, VT, Ops);
6248}
6249
6250/// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6251/// the incoming stack arguments to be loaded from the stack.
6252SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6253 SmallVector<SDValue, 8> ArgChains;
6254
6255 // Include the original chain at the beginning of the list. When this is
6256 // used by target LowerCall hooks, this helps legalize find the
6257 // CALLSEQ_BEGIN node.
6258 ArgChains.push_back(Chain);
6259
6260 // Add a chain value for each stack argument.
6261 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
6262 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
6263 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
6264 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6265 if (FI->getIndex() < 0)
6266 ArgChains.push_back(SDValue(L, 1));
6267
6268 // Build a tokenfactor for all the chains.
6269 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6270}
6271
6272/// getMemsetValue - Vectorized representation of the memset value
6273/// operand.
6274static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6275 const SDLoc &dl) {
6276 assert(!Value.isUndef())(static_cast<void> (0));
6277
6278 unsigned NumBits = VT.getScalarSizeInBits();
6279 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6280 assert(C->getAPIntValue().getBitWidth() == 8)(static_cast<void> (0));
6281 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6282 if (VT.isInteger()) {
6283 bool IsOpaque = VT.getSizeInBits() > 64 ||
6284 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6285 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6286 }
6287 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6288 VT);
6289 }
6290
6291 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?")(static_cast<void> (0));
6292 EVT IntVT = VT.getScalarType();
6293 if (!IntVT.isInteger())
6294 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6295
6296 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6297 if (NumBits > 8) {
6298 // Use a multiplication with 0x010101... to extend the input to the
6299 // required length.
6300 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6301 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6302 DAG.getConstant(Magic, dl, IntVT));
6303 }
6304
6305 if (VT != Value.getValueType() && !VT.isInteger())
6306 Value = DAG.getBitcast(VT.getScalarType(), Value);
6307 if (VT != Value.getValueType())
6308 Value = DAG.getSplatBuildVector(VT, dl, Value);
6309
6310 return Value;
6311}
6312
6313/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6314/// used when a memcpy is turned into a memset when the source is a constant
6315/// string ptr.
6316static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6317 const TargetLowering &TLI,
6318 const ConstantDataArraySlice &Slice) {
6319 // Handle vector with all elements zero.
6320 if (Slice.Array == nullptr) {
6321 if (VT.isInteger())
6322 return DAG.getConstant(0, dl, VT);
6323 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6324 return DAG.getConstantFP(0.0, dl, VT);
6325 if (VT.isVector()) {
6326 unsigned NumElts = VT.getVectorNumElements();
6327 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6328 return DAG.getNode(ISD::BITCAST, dl, VT,
6329 DAG.getConstant(0, dl,
6330 EVT::getVectorVT(*DAG.getContext(),
6331 EltVT, NumElts)));
6332 }
6333 llvm_unreachable("Expected type!")__builtin_unreachable();
6334 }
6335
6336 assert(!VT.isVector() && "Can't handle vector type here!")(static_cast<void> (0));
6337 unsigned NumVTBits = VT.getSizeInBits();
6338 unsigned NumVTBytes = NumVTBits / 8;
6339 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6340
6341 APInt Val(NumVTBits, 0);
6342 if (DAG.getDataLayout().isLittleEndian()) {
6343 for (unsigned i = 0; i != NumBytes; ++i)
6344 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6345 } else {
6346 for (unsigned i = 0; i != NumBytes; ++i)
6347 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6348 }
6349
6350 // If the "cost" of materializing the integer immediate is less than the cost
6351 // of a load, then it is cost effective to turn the load into the immediate.
6352 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6353 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6354 return DAG.getConstant(Val, dl, VT);
6355 return SDValue(nullptr, 0);
6356}
6357
6358SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6359 const SDLoc &DL,
6360 const SDNodeFlags Flags) {
6361 EVT VT = Base.getValueType();
6362 SDValue Index;
6363
6364 if (Offset.isScalable())
6365 Index = getVScale(DL, Base.getValueType(),
6366 APInt(Base.getValueSizeInBits().getFixedSize(),
6367 Offset.getKnownMinSize()));
6368 else
6369 Index = getConstant(Offset.getFixedSize(), DL, VT);
6370
6371 return getMemBasePlusOffset(Base, Index, DL, Flags);
6372}
6373
6374SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6375 const SDLoc &DL,
6376 const SDNodeFlags Flags) {
6377 assert(Offset.getValueType().isInteger())(static_cast<void> (0));
6378 EVT BasePtrVT = Ptr.getValueType();
6379 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6380}
6381
6382/// Returns true if memcpy source is constant data.
6383static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6384 uint64_t SrcDelta = 0;
6385 GlobalAddressSDNode *G = nullptr;
6386 if (Src.getOpcode() == ISD::GlobalAddress)
6387 G = cast<GlobalAddressSDNode>(Src);
6388 else if (Src.getOpcode() == ISD::ADD &&
6389 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6390 Src.getOperand(1).getOpcode() == ISD::Constant) {
6391 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6392 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6393 }
6394 if (!G)
6395 return false;
6396
6397 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6398 SrcDelta + G->getOffset());
6399}
6400
6401static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6402 SelectionDAG &DAG) {
6403 // On Darwin, -Os means optimize for size without hurting performance, so
6404 // only really optimize for size when -Oz (MinSize) is used.
6405 if (MF.getTarget().getTargetTriple().isOSDarwin())
6406 return MF.getFunction().hasMinSize();
6407 return DAG.shouldOptForSize();
6408}
6409
6410static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6411 SmallVector<SDValue, 32> &OutChains, unsigned From,
6412 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6413 SmallVector<SDValue, 16> &OutStoreChains) {
6414 assert(OutLoadChains.size() && "Missing loads in memcpy inlining")(static_cast<void> (0));
6415 assert(OutStoreChains.size() && "Missing stores in memcpy inlining")(static_cast<void> (0));
6416 SmallVector<SDValue, 16> GluedLoadChains;
6417 for (unsigned i = From; i < To; ++i) {
6418 OutChains.push_back(OutLoadChains[i]);
6419 GluedLoadChains.push_back(OutLoadChains[i]);
6420 }
6421
6422 // Chain for all loads.
6423 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6424 GluedLoadChains);
6425
6426 for (unsigned i = From; i < To; ++i) {
6427 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6428 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6429 ST->getBasePtr(), ST->getMemoryVT(),
6430 ST->getMemOperand());
6431 OutChains.push_back(NewStore);
6432 }
6433}
6434
6435static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6436 SDValue Chain, SDValue Dst, SDValue Src,
6437 uint64_t Size, Align Alignment,
6438 bool isVol, bool AlwaysInline,
6439 MachinePointerInfo DstPtrInfo,
6440 MachinePointerInfo SrcPtrInfo,
6441 const AAMDNodes &AAInfo) {
6442 // Turn a memcpy of undef to nop.
6443 // FIXME: We need to honor volatile even is Src is undef.
6444 if (Src.isUndef())
6445 return Chain;
6446
6447 // Expand memcpy to a series of load and store ops if the size operand falls
6448 // below a certain threshold.
6449 // TODO: In the AlwaysInline case, if the size is big then generate a loop
6450 // rather than maybe a humongous number of loads and stores.
6451 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6452 const DataLayout &DL = DAG.getDataLayout();
6453 LLVMContext &C = *DAG.getContext();
6454 std::vector<EVT> MemOps;
6455 bool DstAlignCanChange = false;
6456 MachineFunction &MF = DAG.getMachineFunction();
6457 MachineFrameInfo &MFI = MF.getFrameInfo();
6458 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6459 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6460 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6461 DstAlignCanChange = true;
6462 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6463 if (!SrcAlign || Alignment > *SrcAlign)
6464 SrcAlign = Alignment;
6465 assert(SrcAlign && "SrcAlign must be set")(static_cast<void> (0));
6466 ConstantDataArraySlice Slice;
6467 // If marked as volatile, perform a copy even when marked as constant.
6468 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6469 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6470 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6471 const MemOp Op = isZeroConstant
6472 ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6473 /*IsZeroMemset*/ true, isVol)
6474 : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6475 *SrcAlign, isVol, CopyFromConstant);
6476 if (!TLI.findOptimalMemOpLowering(
6477 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6478 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6479 return SDValue();
6480
6481 if (DstAlignCanChange) {
6482 Type *Ty = MemOps[0].getTypeForEVT(C);
6483 Align NewAlign = DL.getABITypeAlign(Ty);
6484
6485 // Don't promote to an alignment that would require dynamic stack
6486 // realignment.
6487 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6488 if (!TRI->hasStackRealignment(MF))
6489 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6490 NewAlign = NewAlign / 2;
6491
6492 if (NewAlign > Alignment) {
6493 // Give the stack frame object a larger alignment if needed.
6494 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6495 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6496 Alignment = NewAlign;
6497 }
6498 }
6499
6500 // Prepare AAInfo for loads/stores after lowering this memcpy.
6501 AAMDNodes NewAAInfo = AAInfo;
6502 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6503
6504 MachineMemOperand::Flags MMOFlags =
6505 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6506 SmallVector<SDValue, 16> OutLoadChains;
6507 SmallVector<SDValue, 16> OutStoreChains;
6508 SmallVector<SDValue, 32> OutChains;
6509 unsigned NumMemOps = MemOps.size();
6510 uint64_t SrcOff = 0, DstOff = 0;
6511 for (unsigned i = 0; i != NumMemOps; ++i) {
6512 EVT VT = MemOps[i];
6513 unsigned VTSize = VT.getSizeInBits() / 8;
6514 SDValue Value, Store;
6515
6516 if (VTSize > Size) {
6517 // Issuing an unaligned load / store pair that overlaps with the previous
6518 // pair. Adjust the offset accordingly.
6519 assert(i == NumMemOps-1 && i != 0)(static_cast<void> (0));
6520 SrcOff -= VTSize - Size;
6521 DstOff -= VTSize - Size;
6522 }
6523
6524 if (CopyFromConstant &&
6525 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6526 // It's unlikely a store of a vector immediate can be done in a single
6527 // instruction. It would require a load from a constantpool first.
6528 // We only handle zero vectors here.
6529 // FIXME: Handle other cases where store of vector immediate is done in
6530 // a single instruction.
6531 ConstantDataArraySlice SubSlice;
6532 if (SrcOff < Slice.Length) {
6533 SubSlice = Slice;
6534 SubSlice.move(SrcOff);
6535 } else {
6536 // This is an out-of-bounds access and hence UB. Pretend we read zero.
6537 SubSlice.Array = nullptr;
6538 SubSlice.Offset = 0;
6539 SubSlice.Length = VTSize;
6540 }
6541 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6542 if (Value.getNode()) {
6543 Store = DAG.getStore(
6544 Chain, dl, Value,
6545 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6546 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6547 OutChains.push_back(Store);
6548 }
6549 }
6550
6551 if (!Store.getNode()) {
6552 // The type might not be legal for the target. This should only happen
6553 // if the type is smaller than a legal type, as on PPC, so the right
6554 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
6555 // to Load/Store if NVT==VT.
6556 // FIXME does the case above also need this?
6557 EVT NVT = TLI.getTypeToTransformTo(C, VT);
6558 assert(NVT.bitsGE(VT))(static_cast<void> (0));
6559
6560 bool isDereferenceable =
6561 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6562 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6563 if (isDereferenceable)
6564 SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6565
6566 Value = DAG.getExtLoad(
6567 ISD::EXTLOAD, dl, NVT, Chain,
6568 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6569 SrcPtrInfo.getWithOffset(SrcOff), VT,
6570 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6571 OutLoadChains.push_back(Value.getValue(1));
6572
6573 Store = DAG.getTruncStore(
6574 Chain, dl, Value,
6575 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6576 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6577 OutStoreChains.push_back(Store);
6578 }
6579 SrcOff += VTSize;
6580 DstOff += VTSize;
6581 Size -= VTSize;
6582 }
6583
6584 unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6585 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6586 unsigned NumLdStInMemcpy = OutStoreChains.size();
6587
6588 if (NumLdStInMemcpy) {
6589 // It may be that memcpy might be converted to memset if it's memcpy
6590 // of constants. In such a case, we won't have loads and stores, but
6591 // just stores. In the absence of loads, there is nothing to gang up.
6592 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6593 // If target does not care, just leave as it.
6594 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6595 OutChains.push_back(OutLoadChains[i]);
6596 OutChains.push_back(OutStoreChains[i]);
6597 }
6598 } else {
6599 // Ld/St less than/equal limit set by target.
6600 if (NumLdStInMemcpy <= GluedLdStLimit) {
6601 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6602 NumLdStInMemcpy, OutLoadChains,
6603 OutStoreChains);
6604 } else {
6605 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
6606 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6607 unsigned GlueIter = 0;
6608
6609 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6610 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6611 unsigned IndexTo = NumLdStInMemcpy - GlueIter;
6612
6613 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6614 OutLoadChains, OutStoreChains);
6615 GlueIter += GluedLdStLimit;
6616 }
6617
6618 // Residual ld/st.
6619 if (RemainingLdStInMemcpy) {
6620 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6621 RemainingLdStInMemcpy, OutLoadChains,
6622 OutStoreChains);
6623 }
6624 }
6625 }
6626 }
6627 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6628}
6629
6630static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6631 SDValue Chain, SDValue Dst, SDValue Src,
6632 uint64_t Size, Align Alignment,
6633 bool isVol, bool AlwaysInline,
6634 MachinePointerInfo DstPtrInfo,
6635 MachinePointerInfo SrcPtrInfo,
6636 const AAMDNodes &AAInfo) {
6637 // Turn a memmove of undef to nop.
6638 // FIXME: We need to honor volatile even is Src is undef.
6639 if (Src.isUndef())
6640 return Chain;
6641
6642 // Expand memmove to a series of load and store ops if the size operand falls
6643 // below a certain threshold.
6644 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6645 const DataLayout &DL = DAG.getDataLayout();
6646 LLVMContext &C = *DAG.getContext();
6647 std::vector<EVT> MemOps;
6648 bool DstAlignCanChange = false;
6649 MachineFunction &MF = DAG.getMachineFunction();
6650 MachineFrameInfo &MFI = MF.getFrameInfo();
6651 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6652 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6653 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6654 DstAlignCanChange = true;
6655 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6656 if (!SrcAlign || Alignment > *SrcAlign)
6657 SrcAlign = Alignment;
6658 assert(SrcAlign && "SrcAlign must be set")(static_cast<void> (0));
6659 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6660 if (!TLI.findOptimalMemOpLowering(
6661 MemOps, Limit,
6662 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6663 /*IsVolatile*/ true),
6664 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6665 MF.getFunction().getAttributes()))
6666 return SDValue();
6667
6668 if (DstAlignCanChange) {
6669 Type *Ty = MemOps[0].getTypeForEVT(C);
6670 Align NewAlign = DL.getABITypeAlign(Ty);
6671 if (NewAlign > Alignment) {
6672 // Give the stack frame object a larger alignment if needed.
6673 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6674 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6675 Alignment = NewAlign;
6676 }
6677 }
6678
6679 // Prepare AAInfo for loads/stores after lowering this memmove.
6680 AAMDNodes NewAAInfo = AAInfo;
6681 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6682
6683 MachineMemOperand::Flags MMOFlags =
6684 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6685 uint64_t SrcOff = 0, DstOff = 0;
6686 SmallVector<SDValue, 8> LoadValues;
6687 SmallVector<SDValue, 8> LoadChains;
6688 SmallVector<SDValue, 8> OutChains;
6689 unsigned NumMemOps = MemOps.size();
6690 for (unsigned i = 0; i < NumMemOps; i++) {
6691 EVT VT = MemOps[i];
6692 unsigned VTSize = VT.getSizeInBits() / 8;
6693 SDValue Value;
6694
6695 bool isDereferenceable =
6696 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6697 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6698 if (isDereferenceable)
6699 SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6700
6701 Value = DAG.getLoad(
6702 VT, dl, Chain,
6703 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6704 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6705 LoadValues.push_back(Value);
6706 LoadChains.push_back(Value.getValue(1));
6707 SrcOff += VTSize;
6708 }
6709 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6710 OutChains.clear();
6711 for (unsigned i = 0; i < NumMemOps; i++) {
6712 EVT VT = MemOps[i];
6713 unsigned VTSize = VT.getSizeInBits() / 8;
6714 SDValue Store;
6715
6716 Store = DAG.getStore(
6717 Chain, dl, LoadValues[i],
6718 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6719 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6720 OutChains.push_back(Store);
6721 DstOff += VTSize;
6722 }
6723
6724 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6725}
6726
6727/// Lower the call to 'memset' intrinsic function into a series of store
6728/// operations.
6729///
6730/// \param DAG Selection DAG where lowered code is placed.
6731/// \param dl Link to corresponding IR location.
6732/// \param Chain Control flow dependency.
6733/// \param Dst Pointer to destination memory location.
6734/// \param Src Value of byte to write into the memory.
6735/// \param Size Number of bytes to write.
6736/// \param Alignment Alignment of the destination in bytes.
6737/// \param isVol True if destination is volatile.
6738/// \param DstPtrInfo IR information on the memory pointer.
6739/// \returns New head in the control flow, if lowering was successful, empty
6740/// SDValue otherwise.
6741///
6742/// The function tries to replace 'llvm.memset' intrinsic with several store
6743/// operations and value calculation code. This is usually profitable for small
6744/// memory size.
6745static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6746 SDValue Chain, SDValue Dst, SDValue Src,
6747 uint64_t Size, Align Alignment, bool isVol,
6748 MachinePointerInfo DstPtrInfo,
6749 const AAMDNodes &AAInfo) {
6750 // Turn a memset of undef to nop.
6751 // FIXME: We need to honor volatile even is Src is undef.
6752 if (Src.isUndef())
6753 return Chain;
6754
6755 // Expand memset to a series of load/store ops if the size operand
6756 // falls below a certain threshold.
6757 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6758 std::vector<EVT> MemOps;
6759 bool DstAlignCanChange = false;
6760 MachineFunction &MF = DAG.getMachineFunction();
6761 MachineFrameInfo &MFI = MF.getFrameInfo();
6762 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6763 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6764 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6765 DstAlignCanChange = true;
6766 bool IsZeroVal =
6767 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
6768 if (!TLI.findOptimalMemOpLowering(
6769 MemOps, TLI.getMaxStoresPerMemset(OptSize),
6770 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6771 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6772 return SDValue();
6773
6774 if (DstAlignCanChange) {
6775 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6776 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6777 if (NewAlign > Alignment) {
6778 // Give the stack frame object a larger alignment if needed.
6779 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6780 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6781 Alignment = NewAlign;
6782 }
6783 }
6784
6785 SmallVector<SDValue, 8> OutChains;
6786 uint64_t DstOff = 0;
6787 unsigned NumMemOps = MemOps.size();
6788
6789 // Find the largest store and generate the bit pattern for it.
6790 EVT LargestVT = MemOps[0];
6791 for (unsigned i = 1; i < NumMemOps; i++)
6792 if (MemOps[i].bitsGT(LargestVT))
6793 LargestVT = MemOps[i];
6794 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6795
6796 // Prepare AAInfo for loads/stores after lowering this memset.
6797 AAMDNodes NewAAInfo = AAInfo;
6798 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6799
6800 for (unsigned i = 0; i < NumMemOps; i++) {
6801 EVT VT = MemOps[i];
6802 unsigned VTSize = VT.getSizeInBits() / 8;
6803 if (VTSize > Size) {
6804 // Issuing an unaligned load / store pair that overlaps with the previous
6805 // pair. Adjust the offset accordingly.
6806 assert(i == NumMemOps-1 && i != 0)(static_cast<void> (0));
6807 DstOff -= VTSize - Size;
6808 }
6809
6810 // If this store is smaller than the largest store see whether we can get
6811 // the smaller value for free with a truncate.
6812 SDValue Value = MemSetValue;
6813 if (VT.bitsLT(LargestVT)) {
6814 if (!LargestVT.isVector() && !VT.isVector() &&
6815 TLI.isTruncateFree(LargestVT, VT))
6816 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6817 else
6818 Value = getMemsetValue(Src, VT, DAG, dl);
6819 }
6820 assert(Value.getValueType() == VT && "Value with wrong type.")(static_cast<void> (0));
6821 SDValue Store = DAG.getStore(
6822 Chain, dl, Value,
6823 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6824 DstPtrInfo.getWithOffset(DstOff), Alignment,
6825 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
6826 NewAAInfo);
6827 OutChains.push_back(Store);
6828 DstOff += VT.getSizeInBits() / 8;
6829 Size -= VTSize;
6830 }
6831
6832 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6833}
6834
6835static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6836 unsigned AS) {
6837 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6838 // pointer operands can be losslessly bitcasted to pointers of address space 0
6839 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6840 report_fatal_error("cannot lower memory intrinsic in address space " +
6841 Twine(AS));
6842 }
6843}
6844
6845SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6846 SDValue Src, SDValue Size, Align Alignment,
6847 bool isVol, bool AlwaysInline, bool isTailCall,
6848 MachinePointerInfo DstPtrInfo,
6849 MachinePointerInfo SrcPtrInfo,
6850 const AAMDNodes &AAInfo) {
6851 // Check to see if we should lower the memcpy to loads and stores first.
6852 // For cases within the target-specified limits, this is the best choice.
6853 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
1
Calling 'dyn_cast<llvm::ConstantSDNode, llvm::SDValue>'
21
Returning from 'dyn_cast<llvm::ConstantSDNode, llvm::SDValue>'
22
'ConstantSize' initialized here
6854 if (ConstantSize) {
23
Assuming 'ConstantSize' is null
24
Taking false branch
6855 // Memcpy with size zero? Just return the original chain.
6856 if (ConstantSize->isNullValue())
6857 return Chain;
6858
6859 SDValue Result = getMemcpyLoadsAndStores(
6860 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6861 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6862 if (Result.getNode())
6863 return Result;
6864 }
6865
6866 // Then check to see if we should lower the memcpy with target-specific
6867 // code. If the target chooses to do this, this is the next best.
6868 if (TSI) {
25
Assuming field 'TSI' is null
26
Taking false branch
6869 SDValue Result = TSI->EmitTargetCodeForMemcpy(
6870 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6871 DstPtrInfo, SrcPtrInfo);
6872 if (Result.getNode())
6873 return Result;
6874 }
6875
6876 // If we really need inline code and the target declined to provide it,
6877 // use a (potentially long) sequence of loads and stores.
6878 if (AlwaysInline) {
27
Assuming 'AlwaysInline' is true
28
Taking true branch
6879 assert(ConstantSize && "AlwaysInline requires a constant size!")(static_cast<void> (0));
6880 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6881 ConstantSize->getZExtValue(), Alignment,
29
Called C++ object pointer is null
6882 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
6883 }
6884
6885 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6886 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6887
6888 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6889 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6890 // respect volatile, so they may do things like read or write memory
6891 // beyond the given memory regions. But fixing this isn't easy, and most
6892 // people don't care.
6893
6894 // Emit a library call.
6895 TargetLowering::ArgListTy Args;
6896 TargetLowering::ArgListEntry Entry;
6897 Entry.Ty = Type::getInt8PtrTy(*getContext());
6898 Entry.Node = Dst; Args.push_back(Entry);
6899 Entry.Node = Src; Args.push_back(Entry);
6900
6901 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6902 Entry.Node = Size; Args.push_back(Entry);
6903 // FIXME: pass in SDLoc
6904 TargetLowering::CallLoweringInfo CLI(*this);
6905 CLI.setDebugLoc(dl)
6906 .setChain(Chain)
6907 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6908 Dst.getValueType().getTypeForEVT(*getContext()),
6909 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6910 TLI->getPointerTy(getDataLayout())),
6911 std::move(Args))
6912 .setDiscardResult()
6913 .setTailCall(isTailCall);
6914
6915 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6916 return CallResult.second;
6917}
6918
6919SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6920 SDValue Dst, unsigned DstAlign,
6921 SDValue Src, unsigned SrcAlign,
6922 SDValue Size, Type *SizeTy,
6923 unsigned ElemSz, bool isTailCall,
6924 MachinePointerInfo DstPtrInfo,
6925 MachinePointerInfo SrcPtrInfo) {
6926 // Emit a library call.
6927 TargetLowering::ArgListTy Args;
6928 TargetLowering::ArgListEntry Entry;
6929 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6930 Entry.Node = Dst;
6931 Args.push_back(Entry);
6932
6933 Entry.Node = Src;
6934 Args.push_back(Entry);
6935
6936 Entry.Ty = SizeTy;
6937 Entry.Node = Size;
6938 Args.push_back(Entry);
6939
6940 RTLIB::Libcall LibraryCall =
6941 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6942 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6943 report_fatal_error("Unsupported element size");
6944
6945 TargetLowering::CallLoweringInfo CLI(*this);
6946 CLI.setDebugLoc(dl)
6947 .setChain(Chain)
6948 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6949 Type::getVoidTy(*getContext()),
6950 getExternalSymbol(TLI->getLibcallName(LibraryCall),
6951 TLI->getPointerTy(getDataLayout())),
6952 std::move(Args))
6953 .setDiscardResult()
6954 .setTailCall(isTailCall);
6955
6956 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6957 return CallResult.second;
6958}
6959
6960SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6961 SDValue Src, SDValue Size, Align Alignment,
6962 bool isVol, bool isTailCall,
6963 MachinePointerInfo DstPtrInfo,
6964 MachinePointerInfo SrcPtrInfo,
6965 const AAMDNodes &AAInfo) {
6966 // Check to see if we should lower the memmove to loads and stores first.
6967 // For cases within the target-specified limits, this is the best choice.
6968 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6969 if (ConstantSize) {
6970 // Memmove with size zero? Just return the original chain.
6971 if (ConstantSize->isNullValue())
6972 return Chain;
6973
6974 SDValue Result = getMemmoveLoadsAndStores(
6975 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6976 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6977 if (Result.getNode())
6978 return Result;
6979 }
6980
6981 // Then check to see if we should lower the memmove with target-specific
6982 // code. If the target chooses to do this, this is the next best.
6983 if (TSI) {
6984 SDValue Result =
6985 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
6986 Alignment, isVol, DstPtrInfo, SrcPtrInfo);
6987 if (Result.getNode())
6988 return Result;
6989 }
6990
6991 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6992 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6993
6994 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6995 // not be safe. See memcpy above for more details.
6996
6997 // Emit a library call.
6998 TargetLowering::ArgListTy Args;
6999 TargetLowering::ArgListEntry Entry;
7000 Entry.Ty = Type::getInt8PtrTy(*getContext());
7001 Entry.Node = Dst; Args.push_back(Entry);
7002 Entry.Node = Src; Args.push_back(Entry);
7003
7004 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7005 Entry.Node = Size; Args.push_back(Entry);
7006 // FIXME: pass in SDLoc
7007 TargetLowering::CallLoweringInfo CLI(*this);
7008 CLI.setDebugLoc(dl)
7009 .setChain(Chain)
7010 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7011 Dst.getValueType().getTypeForEVT(*getContext()),
7012 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7013 TLI->getPointerTy(getDataLayout())),
7014 std::move(Args))
7015 .setDiscardResult()
7016 .setTailCall(isTailCall);
7017
7018 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7019 return CallResult.second;
7020}
7021
7022SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7023 SDValue Dst, unsigned DstAlign,
7024 SDValue Src, unsigned SrcAlign,
7025 SDValue Size, Type *SizeTy,
7026 unsigned ElemSz, bool isTailCall,
7027 MachinePointerInfo DstPtrInfo,
7028 MachinePointerInfo SrcPtrInfo) {
7029 // Emit a library call.
7030 TargetLowering::ArgListTy Args;
7031 TargetLowering::ArgListEntry Entry;
7032 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7033 Entry.Node = Dst;
7034 Args.push_back(Entry);
7035
7036 Entry.Node = Src;
7037 Args.push_back(Entry);
7038
7039 Entry.Ty = SizeTy;
7040 Entry.Node = Size;
7041 Args.push_back(Entry);
7042
7043 RTLIB::Libcall LibraryCall =
7044 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7045 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7046 report_fatal_error("Unsupported element size");
7047
7048 TargetLowering::CallLoweringInfo CLI(*this);
7049 CLI.setDebugLoc(dl)
7050 .setChain(Chain)
7051 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7052 Type::getVoidTy(*getContext()),
7053 getExternalSymbol(TLI->getLibcallName(LibraryCall),
7054 TLI->getPointerTy(getDataLayout())),
7055 std::move(Args))
7056 .setDiscardResult()
7057 .setTailCall(isTailCall);
7058
7059 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7060 return CallResult.second;
7061}
7062
7063SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7064 SDValue Src, SDValue Size, Align Alignment,
7065 bool isVol, bool isTailCall,
7066 MachinePointerInfo DstPtrInfo,
7067 const AAMDNodes &AAInfo) {
7068 // Check to see if we should lower the memset to stores first.
7069 // For cases within the target-specified limits, this is the best choice.
7070 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7071 if (ConstantSize) {
7072 // Memset with size zero? Just return the original chain.
7073 if (ConstantSize->isNullValue())
7074 return Chain;
7075
7076 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7077 ConstantSize->getZExtValue(), Alignment,
7078 isVol, DstPtrInfo, AAInfo);
7079
7080 if (Result.getNode())
7081 return Result;
7082 }
7083
7084 // Then check to see if we should lower the memset with target-specific
7085 // code. If the target chooses to do this, this is the next best.
7086 if (TSI) {
7087 SDValue Result = TSI->EmitTargetCodeForMemset(
7088 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
7089 if (Result.getNode())
7090 return Result;
7091 }
7092
7093 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7094
7095 // Emit a library call.
7096 TargetLowering::ArgListTy Args;
7097 TargetLowering::ArgListEntry Entry;
7098 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
7099 Args.push_back(Entry);
7100 Entry.Node = Src;
7101 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7102 Args.push_back(Entry);
7103 Entry.Node = Size;
7104 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7105 Args.push_back(Entry);
7106
7107 // FIXME: pass in SDLoc
7108 TargetLowering::CallLoweringInfo CLI(*this);
7109 CLI.setDebugLoc(dl)
7110 .setChain(Chain)
7111 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7112 Dst.getValueType().getTypeForEVT(*getContext()),
7113 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7114 TLI->getPointerTy(getDataLayout())),
7115 std::move(Args))
7116 .setDiscardResult()
7117 .setTailCall(isTailCall);
7118
7119 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7120 return CallResult.second;
7121}
7122
7123SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7124 SDValue Dst, unsigned DstAlign,
7125 SDValue Value, SDValue Size, Type *SizeTy,
7126 unsigned ElemSz, bool isTailCall,
7127 MachinePointerInfo DstPtrInfo) {
7128 // Emit a library call.
7129 TargetLowering::ArgListTy Args;
7130 TargetLowering::ArgListEntry Entry;
7131 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7132 Entry.Node = Dst;
7133 Args.push_back(Entry);
7134
7135 Entry.Ty = Type::getInt8Ty(*getContext());
7136 Entry.Node = Value;
7137 Args.push_back(Entry);
7138
7139 Entry.Ty = SizeTy;
7140 Entry.Node = Size;
7141 Args.push_back(Entry);
7142
7143 RTLIB::Libcall LibraryCall =
7144 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7145 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7146 report_fatal_error("Unsupported element size");
7147
7148 TargetLowering::CallLoweringInfo CLI(*this);
7149 CLI.setDebugLoc(dl)
7150 .setChain(Chain)
7151 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7152 Type::getVoidTy(*getContext()),
7153 getExternalSymbol(TLI->getLibcallName(LibraryCall),
7154 TLI->getPointerTy(getDataLayout())),
7155 std::move(Args))
7156 .setDiscardResult()
7157 .setTailCall(isTailCall);
7158
7159 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7160 return CallResult.second;
7161}
7162
7163SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7164 SDVTList VTList, ArrayRef<SDValue> Ops,
7165 MachineMemOperand *MMO) {
7166 FoldingSetNodeID ID;
7167 ID.AddInteger(MemVT.getRawBits());
7168 AddNodeIDNode(ID, Opcode, VTList, Ops);
7169 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7170 void* IP = nullptr;
7171 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7172 cast<AtomicSDNode>(E)->refineAlignment(MMO);
7173 return SDValue(E, 0);
7174 }
7175
7176 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7177 VTList, MemVT, MMO);
7178 createOperands(N, Ops);
7179
7180 CSEMap.InsertNode(N, IP);
7181 InsertNode(N);
7182 return SDValue(N, 0);
7183}
7184
7185SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7186 EVT MemVT, SDVTList VTs, SDValue Chain,
7187 SDValue Ptr, SDValue Cmp, SDValue Swp,
7188 MachineMemOperand *MMO) {
7189 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||(static_cast<void> (0))
7190 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS)(static_cast<void> (0));
7191 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types")(static_cast<void> (0));
7192
7193 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7194 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7195}
7196
7197SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7198 SDValue Chain, SDValue Ptr, SDValue Val,
7199 MachineMemOperand *MMO) {
7200 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||(static_cast<void> (0))
7201 Opcode == ISD::ATOMIC_LOAD_SUB ||(static_cast<void> (0))
7202 Opcode == ISD::ATOMIC_LOAD_AND ||(static_cast<void> (0))
7203 Opcode == ISD::ATOMIC_LOAD_CLR ||(static_cast<void> (0))
7204 Opcode == ISD::ATOMIC_LOAD_OR ||(static_cast<void> (0))
7205 Opcode == ISD::ATOMIC_LOAD_XOR ||(static_cast<void> (0))
7206 Opcode == ISD::ATOMIC_LOAD_NAND ||(static_cast<void> (0))
7207 Opcode == ISD::ATOMIC_LOAD_MIN ||(static_cast<void> (0))
7208 Opcode == ISD::ATOMIC_LOAD_MAX ||(static_cast<void> (0))
7209 Opcode == ISD::ATOMIC_LOAD_UMIN ||(static_cast<void> (0))
7210 Opcode == ISD::ATOMIC_LOAD_UMAX ||(static_cast<void> (0))
7211 Opcode == ISD::ATOMIC_LOAD_FADD ||(static_cast<void> (0))
7212 Opcode == ISD::ATOMIC_LOAD_FSUB ||(static_cast<void> (0))
7213 Opcode == ISD::ATOMIC_SWAP ||(static_cast<void> (0))
7214 Opcode == ISD::ATOMIC_STORE) &&(static_cast<void> (0))
7215 "Invalid Atomic Op")(static_cast<void> (0));
7216
7217 EVT VT = Val.getValueType();
7218
7219 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7220 getVTList(VT, MVT::Other);
7221 SDValue Ops[] = {Chain, Ptr, Val};
7222 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7223}
7224
7225SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7226 EVT VT, SDValue Chain, SDValue Ptr,
7227 MachineMemOperand *MMO) {
7228 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op")(static_cast<void> (0));
7229
7230 SDVTList VTs = getVTList(VT, MVT::Other);
7231 SDValue Ops[] = {Chain, Ptr};
7232 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7233}
7234
7235/// getMergeValues - Create a MERGE_VALUES node from the given operands.
7236SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7237 if (Ops.size() == 1)
7238 return Ops[0];
7239
7240 SmallVector<EVT, 4> VTs;
7241 VTs.reserve(Ops.size());
7242 for (const SDValue &Op : Ops)
7243 VTs.push_back(Op.getValueType());
7244 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7245}
7246
7247SDValue SelectionDAG::getMemIntrinsicNode(
7248 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7249 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7250 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7251 if (!Size && MemVT.isScalableVector())
7252 Size = MemoryLocation::UnknownSize;
7253 else if (!Size)
7254 Size = MemVT.getStoreSize();
7255
7256 MachineFunction &MF = getMachineFunction();
7257 MachineMemOperand *MMO =
7258 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7259
7260 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7261}
7262
7263SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7264 SDVTList VTList,
7265 ArrayRef<SDValue> Ops, EVT MemVT,
7266 MachineMemOperand *MMO) {
7267 assert((Opcode == ISD::INTRINSIC_VOID ||(static_cast<void> (0))
7268 Opcode == ISD::INTRINSIC_W_CHAIN ||(static_cast<void> (0))
7269 Opcode == ISD::PREFETCH ||(static_cast<void> (0))
7270 ((int)Opcode <= std::numeric_limits<int>::max() &&(static_cast<void> (0))
7271 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&(static_cast<void> (0))
7272 "Opcode is not a memory-accessing opcode!")(static_cast<void> (0));
7273
7274 // Memoize the node unless it returns a flag.
7275 MemIntrinsicSDNode *N;
7276 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7277 FoldingSetNodeID ID;
7278 AddNodeIDNode(ID, Opcode, VTList, Ops);
7279 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7280 Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7281 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7282 void *IP = nullptr;
7283 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7284 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7285 return SDValue(E, 0);
7286 }
7287
7288 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7289 VTList, MemVT, MMO);
7290 createOperands(N, Ops);
7291
7292 CSEMap.InsertNode(N, IP);
7293 } else {
7294 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7295 VTList, MemVT, MMO);
7296 createOperands(N, Ops);
7297 }
7298 InsertNode(N);
7299 SDValue V(N, 0);
7300 NewSDValueDbgMsg(V, "Creating new node: ", this);
7301 return V;
7302}
7303
7304SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7305 SDValue Chain, int FrameIndex,
7306 int64_t Size, int64_t Offset) {
7307 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7308 const auto VTs = getVTList(MVT::Other);
7309 SDValue Ops[2] = {
7310 Chain,
7311 getFrameIndex(FrameIndex,
7312 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7313 true)};
7314
7315 FoldingSetNodeID ID;
7316 AddNodeIDNode(ID, Opcode, VTs, Ops);
7317 ID.AddInteger(FrameIndex);
7318 ID.AddInteger(Size);
7319 ID.AddInteger(Offset);
7320 void *IP = nullptr;
7321 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7322 return SDValue(E, 0);
7323
7324 LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7325 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7326 createOperands(N, Ops);
7327 CSEMap.InsertNode(N, IP);
7328 InsertNode(N);
7329 SDValue V(N, 0);
7330 NewSDValueDbgMsg(V, "Creating new node: ", this);
7331 return V;
7332}
7333
7334SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7335 uint64_t Guid, uint64_t Index,
7336 uint32_t Attr) {
7337 const unsigned Opcode = ISD::PSEUDO_PROBE;
7338 const auto VTs = getVTList(MVT::Other);
7339 SDValue Ops[] = {Chain};
7340 FoldingSetNodeID ID;
7341 AddNodeIDNode(ID, Opcode, VTs, Ops);
7342 ID.AddInteger(Guid);
7343 ID.AddInteger(Index);
7344 void *IP = nullptr;
7345 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7346 return SDValue(E, 0);
7347
7348 auto *N = newSDNode<PseudoProbeSDNode>(
7349 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7350 createOperands(N, Ops);
7351 CSEMap.InsertNode(N, IP);
7352 InsertNode(N);
7353 SDValue V(N, 0);
7354 NewSDValueDbgMsg(V, "Creating new node: ", this);
7355 return V;
7356}
7357
7358/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7359/// MachinePointerInfo record from it. This is particularly useful because the
7360/// code generator has many cases where it doesn't bother passing in a
7361/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7362static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7363 SelectionDAG &DAG, SDValue Ptr,
7364 int64_t Offset = 0) {
7365 // If this is FI+Offset, we can model it.
7366 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7367 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7368 FI->getIndex(), Offset);
7369
7370 // If this is (FI+Offset1)+Offset2, we can model it.
7371 if (Ptr.getOpcode() != ISD::ADD ||
7372 !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7373 !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7374 return Info;
7375
7376 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7377 return MachinePointerInfo::getFixedStack(
7378 DAG.getMachineFunction(), FI,
7379 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7380}
7381
7382/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7383/// MachinePointerInfo record from it. This is particularly useful because the
7384/// code generator has many cases where it doesn't bother passing in a
7385/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7386static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7387 SelectionDAG &DAG, SDValue Ptr,
7388 SDValue OffsetOp) {
7389 // If the 'Offset' value isn't a constant, we can't handle this.
7390 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7391 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7392 if (OffsetOp.isUndef())
7393 return InferPointerInfo(Info, DAG, Ptr);
7394 return Info;
7395}
7396
7397SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7398 EVT VT, const SDLoc &dl, SDValue Chain,
7399 SDValue Ptr, SDValue Offset,
7400 MachinePointerInfo PtrInfo, EVT MemVT,
7401 Align Alignment,
7402 MachineMemOperand::Flags MMOFlags,
7403 const AAMDNodes &AAInfo, const MDNode *Ranges) {
7404 assert(Chain.getValueType() == MVT::Other &&(static_cast<void> (0))
7405 "Invalid chain type")(static_cast<void> (0));
7406
7407 MMOFlags |= MachineMemOperand::MOLoad;
7408 assert((MMOFlags & MachineMemOperand::MOStore) == 0)(static_cast<void> (0));
7409 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7410 // clients.
7411 if (PtrInfo.V.isNull())
7412 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7413
7414 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7415 MachineFunction &MF = getMachineFunction();
7416 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7417 Alignment, AAInfo, Ranges);
7418 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7419}
7420
7421SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7422 EVT VT, const SDLoc &dl, SDValue Chain,
7423 SDValue Ptr, SDValue Offset, EVT MemVT,
7424 MachineMemOperand *MMO) {
7425 if (VT == MemVT) {
7426 ExtType = ISD::NON_EXTLOAD;
7427 } else if (ExtType == ISD::NON_EXTLOAD) {
7428 assert(VT == MemVT && "Non-extending load from different memory type!")(static_cast<void> (0));
7429 } else {
7430 // Extending load.
7431 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&(static_cast<void> (0))
7432 "Should only be an extending load, not truncating!")(static_cast<void> (0));
7433 assert(VT.isInteger() == MemVT.isInteger() &&(static_cast<void> (0))
7434 "Cannot convert from FP to Int or Int -> FP!")(static_cast<void> (0));
7435 assert(VT.isVector() == MemVT.isVector() &&(static_cast<void> (0))
7436 "Cannot use an ext load to convert to or from a vector!")(static_cast<void> (0));
7437 assert((!VT.isVector() ||(static_cast<void> (0))
7438 VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&(static_cast<void> (0))
7439 "Cannot use an ext load to change the number of vector elements!")(static_cast<void> (0));
7440 }
7441
7442 bool Indexed = AM != ISD::UNINDEXED;
7443 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!")(static_cast<void> (0));
7444
7445 SDVTList VTs = Indexed ?
7446 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7447 SDValue Ops[] = { Chain, Ptr, Offset };
7448 FoldingSetNodeID ID;
7449 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7450 ID.AddInteger(MemVT.getRawBits());
7451 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7452 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7453 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7454 void *IP = nullptr;
7455 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7456 cast<LoadSDNode>(E)->refineAlignment(MMO);
7457 return SDValue(E, 0);
7458 }
7459 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7460 ExtType, MemVT, MMO);
7461 createOperands(N, Ops);
7462
7463 CSEMap.InsertNode(N, IP);
7464 InsertNode(N);
7465 SDValue V(N, 0);
7466 NewSDValueDbgMsg(V, "Creating new node: ", this);
7467 return V;
7468}
7469
7470SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7471 SDValue Ptr, MachinePointerInfo PtrInfo,
7472 MaybeAlign Alignment,
7473 MachineMemOperand::Flags MMOFlags,
7474 const AAMDNodes &AAInfo, const MDNode *Ranges) {
7475 SDValue Undef = getUNDEF(Ptr.getValueType());
7476 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7477 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7478}
7479
7480SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7481 SDValue Ptr, MachineMemOperand *MMO) {
7482 SDValue Undef = getUNDEF(Ptr.getValueType());
7483 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7484 VT, MMO);
7485}
7486
7487SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7488 EVT VT, SDValue Chain, SDValue Ptr,
7489 MachinePointerInfo PtrInfo, EVT MemVT,
7490 MaybeAlign Alignment,
7491 MachineMemOperand::Flags MMOFlags,
7492 const AAMDNodes &AAInfo) {
7493 SDValue Undef = getUNDEF(Ptr.getValueType());
7494 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7495 MemVT, Alignment, MMOFlags, AAInfo);
7496}
7497
7498SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7499 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7500 MachineMemOperand *MMO) {
7501 SDValue Undef = getUNDEF(Ptr.getValueType());
7502 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7503 MemVT, MMO);
7504}
7505
7506SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7507 SDValue Base, SDValue Offset,
7508 ISD::MemIndexedMode AM) {
7509 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7510 assert(LD->getOffset().isUndef() && "Load is already a indexed load!")(static_cast<void> (0));
7511 // Don't propagate the invariant or dereferenceable flags.
7512 auto MMOFlags =
7513 LD->getMemOperand()->getFlags() &
7514 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7515 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7516 LD->getChain(), Base, Offset, LD->getPointerInfo(),
7517 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7518}
7519
7520SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7521 SDValue Ptr, MachinePointerInfo PtrInfo,
7522 Align Alignment,
7523 MachineMemOperand::Flags MMOFlags,
7524 const AAMDNodes &AAInfo) {
7525 assert(Chain.getValueType() == MVT::Other && "Invalid chain type")(static_cast<void> (0));
7526
7527 MMOFlags |= MachineMemOperand::MOStore;
7528 assert((MMOFlags & MachineMemOperand::MOLoad) == 0)(static_cast<void> (0));
7529
7530 if (PtrInfo.V.isNull())
7531 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7532
7533 MachineFunction &MF = getMachineFunction();
7534 uint64_t Size =
7535 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7536 MachineMemOperand *MMO =
7537 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7538 return getStore(Chain, dl, Val, Ptr, MMO);
7539}
7540
7541SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7542 SDValue Ptr, MachineMemOperand *MMO) {
7543 assert(Chain.getValueType() == MVT::Other &&(static_cast<void> (0))
7544 "Invalid chain type")(static_cast<void> (0));
7545 EVT VT = Val.getValueType();
7546 SDVTList VTs = getVTList(MVT::Other);
7547 SDValue Undef = getUNDEF(Ptr.getValueType());
7548 SDValue Ops[] = { Chain, Val, Ptr, Undef };
7549 FoldingSetNodeID ID;
7550 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7551 ID.AddInteger(VT.getRawBits());
7552 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7553 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7554 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7555 void *IP = nullptr;
7556 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7557 cast<StoreSDNode>(E)->refineAlignment(MMO);
7558 return SDValue(E, 0);
7559 }
7560 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7561 ISD::UNINDEXED, false, VT, MMO);
7562 createOperands(N, Ops);
7563
7564 CSEMap.InsertNode(N, IP);
7565 InsertNode(N);
7566 SDValue V(N, 0);
7567 NewSDValueDbgMsg(V, "Creating new node: ", this);
7568 return V;
7569}
7570
7571SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7572 SDValue Ptr, MachinePointerInfo PtrInfo,
7573 EVT SVT, Align Alignment,
7574 MachineMemOperand::Flags MMOFlags,
7575 const AAMDNodes &AAInfo) {
7576 assert(Chain.getValueType() == MVT::Other &&(static_cast<void> (0))
7577 "Invalid chain type")(static_cast<void> (0));
7578
7579 MMOFlags |= MachineMemOperand::MOStore;
7580 assert((MMOFlags & MachineMemOperand::MOLoad) == 0)(static_cast<void> (0));
7581
7582 if (PtrInfo.V.isNull())
7583 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7584
7585 MachineFunction &MF = getMachineFunction();
7586 MachineMemOperand *MMO = MF.getMachineMemOperand(
7587 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7588 Alignment, AAInfo);
7589 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7590}
7591
7592SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7593 SDValue Ptr, EVT SVT,
7594 MachineMemOperand *MMO) {
7595 EVT VT = Val.getValueType();
7596
7597 assert(Chain.getValueType() == MVT::Other &&(static_cast<void> (0))
7598 "Invalid chain type")(static_cast<void> (0));
7599 if (VT == SVT)
7600 return getStore(Chain, dl, Val, Ptr, MMO);
7601
7602 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&(static_cast<void> (0))
7603 "Should only be a truncating store, not extending!")(static_cast<void> (0));
7604 assert(VT.isInteger() == SVT.isInteger() &&(static_cast<void> (0))
7605 "Can't do FP-INT conversion!")(static_cast<void> (0));
7606 assert(VT.isVector() == SVT.isVector() &&(static_cast<void> (0))
7607 "Cannot use trunc store to convert to or from a vector!")(static_cast<void> (0));
7608 assert((!VT.isVector() ||(static_cast<void> (0))
7609 VT.getVectorElementCount() == SVT.getVectorElementCount()) &&(static_cast<void> (0))
7610 "Cannot use trunc store to change the number of vector elements!")(static_cast<void> (0));
7611
7612 SDVTList VTs = getVTList(MVT::Other);
7613 SDValue Undef = getUNDEF(Ptr.getValueType());
7614 SDValue Ops[] = { Chain, Val, Ptr, Undef };
7615 FoldingSetNodeID ID;
7616 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7617 ID.AddInteger(SVT.getRawBits());
7618 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7619 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7620 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7621 void *IP = nullptr;
7622 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7623 cast<StoreSDNode>(E)->refineAlignment(MMO);
7624 return SDValue(E, 0);
7625 }
7626 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7627 ISD::UNINDEXED, true, SVT, MMO);
7628 createOperands(N, Ops);
7629
7630 CSEMap.InsertNode(N, IP);
7631 InsertNode(N);
7632 SDValue V(N, 0);
7633 NewSDValueDbgMsg(V, "Creating new node: ", this);
7634 return V;
7635}
7636
7637SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7638 SDValue Base, SDValue Offset,
7639 ISD::MemIndexedMode AM) {
7640 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7641 assert(ST->getOffset().isUndef() && "Store is already a indexed store!")(static_cast<void> (0));
7642 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7643 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7644 FoldingSetNodeID ID;
7645 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7646 ID.AddInteger(ST->getMemoryVT().getRawBits());
7647 ID.AddInteger(ST->getRawSubclassData());
7648 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7649 void *IP = nullptr;
7650 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7651 return SDValue(E, 0);
7652
7653 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7654 ST->isTruncatingStore(), ST->getMemoryVT(),
7655 ST->getMemOperand());
7656 createOperands(N, Ops);
7657
7658 CSEMap.InsertNode(N, IP);
7659 InsertNode(N);
7660 SDValue V(N, 0);
7661 NewSDValueDbgMsg(V, "Creating new node: ", this);
7662 return V;
7663}
7664
7665SDValue SelectionDAG::getLoadVP(
7666 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7667 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7668 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7669 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7670 const MDNode *Ranges, bool IsExpanding) {
7671 assert(Chain.getValueType() == MVT::Other && "Invalid chain type")(static_cast<void> (0));
7672
7673 MMOFlags |= MachineMemOperand::MOLoad;
7674 assert((MMOFlags & MachineMemOperand::MOStore) == 0)(static_cast<void> (0));
7675 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7676 // clients.
7677 if (PtrInfo.V.isNull())
7678 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7679
7680 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7681 MachineFunction &MF = getMachineFunction();
7682 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7683 Alignment, AAInfo, Ranges);
7684 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7685 MMO, IsExpanding);
7686}
7687
7688SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7689 ISD::LoadExtType ExtType, EVT VT,
7690 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7691 SDValue Offset, SDValue Mask, SDValue EVL,
7692 EVT MemVT, MachineMemOperand *MMO,
7693 bool IsExpanding) {
7694 if (VT == MemVT) {
7695 ExtType = ISD::NON_EXTLOAD;
7696 } else if (ExtType == ISD::NON_EXTLOAD) {
7697 assert(VT == MemVT && "Non-extending load from different memory type!")(static_cast<void> (0));
7698 } else {
7699 // Extending load.
7700 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&(static_cast<void> (0))
7701 "Should only be an extending load, not truncating!")(static_cast<void> (0));
7702 assert(VT.isInteger() == MemVT.isInteger() &&(static_cast<void> (0))
7703 "Cannot convert from FP to Int or Int -> FP!")(static_cast<void> (0));
7704 assert(VT.isVector() == MemVT.isVector() &&(static_cast<void> (0))
7705 "Cannot use an ext load to convert to or from a vector!")(static_cast<void> (0));
7706 assert((!VT.isVector() ||(static_cast<void> (0))
7707 VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&(static_cast<void> (0))
7708 "Cannot use an ext load to change the number of vector elements!")(static_cast<void> (0));
7709 }
7710
7711 bool Indexed = AM != ISD::UNINDEXED;
7712 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!")(static_cast<void> (0));
7713
7714 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7715 : getVTList(VT, MVT::Other);
7716 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
7717 FoldingSetNodeID ID;
7718 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
7719 ID.AddInteger(VT.getRawBits());
7720 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
7721 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
7722 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7723 void *IP = nullptr;
7724 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7725 cast<VPLoadSDNode>(E)->refineAlignment(MMO);
7726 return SDValue(E, 0);
7727 }
7728 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7729 ExtType, IsExpanding, MemVT, MMO);
7730 createOperands(N, Ops);
7731
7732 CSEMap.InsertNode(N, IP);
7733 InsertNode(N);
7734 SDValue V(N, 0);
7735 NewSDValueDbgMsg(V, "Creating new node: ", this);
7736 return V;
7737}
7738
7739SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7740 SDValue Ptr, SDValue Mask, SDValue EVL,
7741 MachinePointerInfo PtrInfo,
7742 MaybeAlign Alignment,
7743 MachineMemOperand::Flags MMOFlags,
7744 const AAMDNodes &AAInfo, const MDNode *Ranges,
7745 bool IsExpanding) {
7746 SDValue Undef = getUNDEF(Ptr.getValueType());
7747 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7748 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
7749 IsExpanding);
7750}
7751
7752SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7753 SDValue Ptr, SDValue Mask, SDValue EVL,
7754 MachineMemOperand *MMO, bool IsExpanding) {
7755 SDValue Undef = getUNDEF(Ptr.getValueType());
7756 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7757 Mask, EVL, VT, MMO, IsExpanding);
7758}
7759
7760SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7761 EVT VT, SDValue Chain, SDValue Ptr,
7762 SDValue Mask, SDValue EVL,
7763 MachinePointerInfo PtrInfo, EVT MemVT,
7764 MaybeAlign Alignment,
7765 MachineMemOperand::Flags MMOFlags,
7766 const AAMDNodes &AAInfo, bool IsExpanding) {
7767 SDValue Undef = getUNDEF(Ptr.getValueType());
7768 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7769 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
7770 IsExpanding);
7771}
7772
7773SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7774 EVT VT, SDValue Chain, SDValue Ptr,
7775 SDValue Mask, SDValue EVL, EVT MemVT,
7776 MachineMemOperand *MMO, bool IsExpanding) {
7777 SDValue Undef = getUNDEF(Ptr.getValueType());
7778 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7779 EVL, MemVT, MMO, IsExpanding);
7780}
7781
7782SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
7783 SDValue Base, SDValue Offset,
7784 ISD::MemIndexedMode AM) {
7785 auto *LD = cast<VPLoadSDNode>(OrigLoad);
7786 assert(LD->getOffset().isUndef() && "Load is already a indexed load!")(static_cast<void> (0));
7787 // Don't propagate the invariant or dereferenceable flags.
7788 auto MMOFlags =
7789 LD->getMemOperand()->getFlags() &
7790 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7791 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7792 LD->getChain(), Base, Offset, LD->getMask(),
7793 LD->getVectorLength(), LD->getPointerInfo(),
7794 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
7795 nullptr, LD->isExpandingLoad());
7796}
7797
7798SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7799 SDValue Ptr, SDValue Mask, SDValue EVL,
7800 MachinePointerInfo PtrInfo, Align Alignment,
7801 MachineMemOperand::Flags MMOFlags,
7802 const AAMDNodes &AAInfo, bool IsCompressing) {
7803 assert(Chain.getValueType() == MVT::Other && "Invalid chain type")(static_cast<void> (0));
7804
7805 MMOFlags |= MachineMemOperand::MOStore;
7806 assert((MMOFlags & MachineMemOperand::MOLoad) == 0)(static_cast<void> (0));
7807
7808 if (PtrInfo.V.isNull())
7809 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7810
7811 MachineFunction &MF = getMachineFunction();
7812 uint64_t Size =
7813 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7814 MachineMemOperand *MMO =
7815 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7816 return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing);
7817}
7818
7819SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7820 SDValue Ptr, SDValue Mask, SDValue EVL,
7821 MachineMemOperand *MMO, bool IsCompressing) {
7822 assert(Chain.getValueType() == MVT::Other && "Invalid chain type")(static_cast<void> (0));
7823 EVT VT = Val.getValueType();
7824 SDVTList VTs = getVTList(MVT::Other);
7825 SDValue Undef = getUNDEF(Ptr.getValueType());
7826 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
7827 FoldingSetNodeID ID;
7828 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7829 ID.AddInteger(VT.getRawBits());
7830 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7831 dl.getIROrder(), VTs, ISD::UNINDEXED, false, IsCompressing, VT, MMO));
7832 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7833 void *IP = nullptr;
7834 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7835 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7836 return SDValue(E, 0);
7837 }
7838 auto *N =
7839 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7840 ISD::UNINDEXED, false, IsCompressing, VT, MMO);
7841 createOperands(N, Ops);
7842
7843 CSEMap.InsertNode(N, IP);
7844 InsertNode(N);
7845 SDValue V(N, 0);
7846 NewSDValueDbgMsg(V, "Creating new node: ", this);
7847 return V;
7848}
7849
7850SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7851 SDValue Val, SDValue Ptr, SDValue Mask,
7852 SDValue EVL, MachinePointerInfo PtrInfo,
7853 EVT SVT, Align Alignment,
7854 MachineMemOperand::Flags MMOFlags,
7855 const AAMDNodes &AAInfo,
7856 bool IsCompressing) {
7857 assert(Chain.getValueType() == MVT::Other && "Invalid chain type")(static_cast<void> (0));
7858
7859 MMOFlags |= MachineMemOperand::MOStore;
7860 assert((MMOFlags & MachineMemOperand::MOLoad) == 0)(static_cast<void> (0));
7861
7862 if (PtrInfo.V.isNull())
7863 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7864
7865 MachineFunction &MF = getMachineFunction();
7866 MachineMemOperand *MMO = MF.getMachineMemOperand(
7867 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7868 Alignment, AAInfo);
7869 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
7870 IsCompressing);
7871}
7872
7873SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7874 SDValue Val, SDValue Ptr, SDValue Mask,
7875 SDValue EVL, EVT SVT,
7876 MachineMemOperand *MMO,
7877 bool IsCompressing) {
7878 EVT VT = Val.getValueType();
7879
7880 assert(Chain.getValueType() == MVT::Other && "Invalid chain type")(static_cast<void> (0));
7881 if (VT == SVT)
7882 return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing);
7883
7884 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&(static_cast<void> (0))
7885 "Should only be a truncating store, not extending!")(static_cast<void> (0));
7886 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!")(static_cast<void> (0));
7887 assert(VT.isVector() == SVT.isVector() &&(static_cast<void> (0))
7888 "Cannot use trunc store to convert to or from a vector!")(static_cast<void> (0));
7889 assert((!VT.isVector() ||(static_cast<void> (0))
7890 VT.getVectorElementCount() == SVT.getVectorElementCount()) &&(static_cast<void> (0))
7891 "Cannot use trunc store to change the number of vector elements!")(static_cast<void> (0));
7892
7893 SDVTList VTs = getVTList(MVT::Other);
7894 SDValue Undef = getUNDEF(Ptr.getValueType());
7895 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
7896 FoldingSetNodeID ID;
7897 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7898 ID.AddInteger(SVT.getRawBits());
7899 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7900 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
7901 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7902 void *IP = nullptr;
7903 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7904 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7905 return SDValue(E, 0);
7906 }
7907 auto *N =
7908 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7909 ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
7910 createOperands(N, Ops);
7911
7912 CSEMap.InsertNode(N, IP);
7913 InsertNode(N);
7914 SDValue V(N, 0);
7915 NewSDValueDbgMsg(V, "Creating new node: ", this);
7916 return V;
7917}
7918
7919SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
7920 SDValue Base, SDValue Offset,
7921 ISD::MemIndexedMode AM) {
7922 auto *ST = cast<VPStoreSDNode>(OrigStore);
7923 assert(ST->getOffset().isUndef() && "Store is already an indexed store!")(static_cast<void> (0));
7924 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7925 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
7926 Offset, ST->getMask(), ST->getVectorLength()};
7927 FoldingSetNodeID ID;
7928 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7929 ID.AddInteger(ST->getMemoryVT().getRawBits());
7930 ID.AddInteger(ST->getRawSubclassData());
7931 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7932 void *IP = nullptr;
7933 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7934 return SDValue(E, 0);
7935
7936 auto *N = newSDNode<VPStoreSDNode>(
7937 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
7938 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
7939 createOperands(N, Ops);
7940
7941 CSEMap.InsertNode(N, IP);
7942 InsertNode(N);
7943 SDValue V(N, 0);
7944 NewSDValueDbgMsg(V, "Creating new node: ", this);
7945 return V;
7946}
7947
7948SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7949 ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
7950 ISD::MemIndexType IndexType) {
7951 assert(Ops.size() == 6 && "Incompatible number of operands")(static_cast<void> (0));
7952
7953 FoldingSetNodeID ID;
7954 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
7955 ID.AddInteger(VT.getRawBits());
7956 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
7957 dl.getIROrder(), VTs, VT, MMO, IndexType));
7958 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7959 void *IP = nullptr;
7960 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7961 cast<VPGatherSDNode>(E)->refineAlignment(MMO);
7962 return SDValue(E, 0);
7963 }
7964
7965 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7966 VT, MMO, IndexType);
7967 createOperands(N, Ops);
7968
7969 assert(N->getMask().getValueType().getVectorElementCount() ==(static_cast<void> (0))
7970 N->getValueType(0).getVectorElementCount() &&(static_cast<void> (0))
7971 "Vector width mismatch between mask and data")(static_cast<void> (0));
7972 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==(static_cast<void> (0))
7973 N->getValueType(0).getVectorElementCount().isScalable() &&(static_cast<void> (0))
7974 "Scalable flags of index and data do not match")(static_cast<void> (0));
7975 assert(ElementCount::isKnownGE((static_cast<void> (0))
7976 N->getIndex().getValueType().getVectorElementCount(),(static_cast<void> (0))
7977 N->getValueType(0).getVectorElementCount()) &&(static_cast<void> (0))
7978 "Vector width mismatch between index and data")(static_cast<void> (0));
7979 assert(isa<ConstantSDNode>(N->getScale()) &&(static_cast<void> (0))
7980 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&(static_cast<void> (0))
7981 "Scale should be a constant power of 2")(static_cast<void> (0));
7982
7983 CSEMap.InsertNode(N, IP);
7984 InsertNode(N);
7985 SDValue V(N, 0);
7986 NewSDValueDbgMsg(V, "Creating new node: ", this);
7987 return V;
7988}
7989
7990SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7991 ArrayRef<SDValue> Ops,
7992 MachineMemOperand *MMO,
7993 ISD::MemIndexType IndexType) {
7994 assert(Ops.size() == 7 && "Incompatible number of operands")(static_cast<void> (0));
7995
7996 FoldingSetNodeID ID;
7997 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
7998 ID.AddInteger(VT.getRawBits());
7999 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
8000 dl.getIROrder(), VTs, VT, MMO, IndexType));
8001 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8002 void *IP = nullptr;
8003 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8004 cast<VPScatterSDNode>(E)->refineAlignment(MMO);
8005 return SDValue(E, 0);
8006 }
8007 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8008 VT, MMO, IndexType);
8009 createOperands(N, Ops);
8010
8011 assert(N->getMask().getValueType().getVectorElementCount() ==(static_cast<void> (0))
8012 N->getValue().getValueType().getVectorElementCount() &&(static_cast<void> (0))
8013 "Vector width mismatch between mask and data")(static_cast<void> (0));
8014 assert((static_cast<void> (0))
8015 N->getIndex().getValueType().getVectorElementCount().isScalable() ==(static_cast<void> (0))
8016 N->getValue().getValueType().getVectorElementCount().isScalable() &&(static_cast<void> (0))
8017 "Scalable flags of index and data do not match")(static_cast<void> (0));
8018 assert(ElementCount::isKnownGE((static_cast<void> (0))
8019 N->getIndex().getValueType().getVectorElementCount(),(static_cast<void> (0))
8020 N->getValue().getValueType().getVectorElementCount()) &&(static_cast<void> (0))
8021 "Vector width mismatch between index and data")(static_cast<void> (0));
8022 assert(isa<ConstantSDNode>(N->getScale()) &&(static_cast<void> (0))
8023 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&(static_cast<void> (0))
8024 "Scale should be a constant power of 2")(static_cast<void> (0));
8025
8026 CSEMap.InsertNode(N, IP);
8027 InsertNode(N);
8028 SDValue V(N, 0);
8029 NewSDValueDbgMsg(V, "Creating new node: ", this);
8030 return V;
8031}
8032
8033SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8034 SDValue Base, SDValue Offset, SDValue Mask,
8035 SDValue PassThru, EVT MemVT,
8036 MachineMemOperand *MMO,
8037 ISD::MemIndexedMode AM,
8038 ISD::LoadExtType ExtTy, bool isExpanding) {
8039 bool Indexed = AM != ISD::UNINDEXED;
8040 assert((Indexed || Offset.isUndef()) &&(static_cast<void> (0))
8041 "Unindexed masked load with an offset!")(static_cast<void> (0));
8042 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8043 : getVTList(VT, MVT::Other);
8044 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8045 FoldingSetNodeID ID;
8046 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8047 ID.AddInteger(MemVT.getRawBits());
8048 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8049 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8050 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8051 void *IP = nullptr;
8052 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8053 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8054 return SDValue(E, 0);
8055 }
8056 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8057 AM, ExtTy, isExpanding, MemVT, MMO);
8058 createOperands(N, Ops);
8059
8060 CSEMap.InsertNode(N, IP);
8061 InsertNode(N);
8062 SDValue V(N, 0);
8063 NewSDValueDbgMsg(V, "Creating new node: ", this);
8064 return V;
8065}
8066
8067SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8068 SDValue Base, SDValue Offset,
8069 ISD::MemIndexedMode AM) {
8070 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8071 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!")(static_cast<void> (0));
8072 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8073 Offset, LD->getMask(), LD->getPassThru(),
8074 LD->getMemoryVT(), LD->getMemOperand(), AM,
8075 LD->getExtensionType(), LD->isExpandingLoad());
8076}
8077
8078SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8079 SDValue Val, SDValue Base, SDValue Offset,
8080 SDValue Mask, EVT MemVT,
8081 MachineMemOperand *MMO,
8082 ISD::MemIndexedMode AM, bool IsTruncating,
8083 bool IsCompressing) {
8084 assert(Chain.getValueType() == MVT::Other &&(static_cast<void> (0))
8085 "Invalid chain type")(static_cast<void> (0));
8086 bool Indexed = AM != ISD::UNINDEXED;
8087 assert((Indexed || Offset.isUndef()) &&(static_cast<void> (0))
8088 "Unindexed masked store with an offset!")(static_cast<void> (0));
8089 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8090 : getVTList(MVT::Other);
8091 SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8092 FoldingSetNodeID ID;
8093 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8094 ID.AddInteger(MemVT.getRawBits());
8095 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8096 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8097 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8098 void *IP = nullptr;
8099 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8100 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8101 return SDValue(E, 0);
8102 }
8103 auto *N =
8104 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8105 IsTruncating, IsCompressing, MemVT, MMO);
8106 createOperands(N, Ops);
8107
8108 CSEMap.InsertNode(N, IP);
8109 InsertNode(N);
8110 SDValue V(N, 0);
8111 NewSDValueDbgMsg(V, "Creating new node: ", this);
8112 return V;
8113}
8114
8115SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8116 SDValue Base, SDValue Offset,
8117 ISD::MemIndexedMode AM) {
8118 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8119 assert(ST->getOffset().isUndef() &&(static_cast<void> (0))
8120 "Masked store is already a indexed store!")(static_cast<void> (0));
8121 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8122 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8123 AM, ST->isTruncatingStore(), ST->isCompressingStore());
8124}
8125
8126SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8127 ArrayRef<SDValue> Ops,
8128 MachineMemOperand *MMO,
8129 ISD::MemIndexType IndexType,
8130 ISD::LoadExtType ExtTy) {
8131 assert(Ops.size() == 6 && "Incompatible number of operands")(static_cast<void> (0));
8132
8133 FoldingSetNodeID ID;
8134 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8135 ID.AddInteger(MemVT.getRawBits());
8136 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8137 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8138 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8139 void *IP = nullptr;
8140 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8141 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8142 return SDValue(E, 0);
8143 }
8144
8145 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8146 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8147 VTs, MemVT, MMO, IndexType, ExtTy);
8148 createOperands(N, Ops);
8149
8150 assert(N->getPassThru().getValueType() == N->getValueType(0) &&(static_cast<void> (0))
8151 "Incompatible type of the PassThru value in MaskedGatherSDNode")(static_cast<void> (0));
8152 assert(N->getMask().getValueType().getVectorElementCount() ==(static_cast<void> (0))
8153 N->getValueType(0).getVectorElementCount() &&(static_cast<void> (0))
8154 "Vector width mismatch between mask and data")(static_cast<void> (0));
8155 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==(static_cast<void> (0))
8156 N->getValueType(0).getVectorElementCount().isScalable() &&(static_cast<void> (0))
8157 "Scalable flags of index and data do not match")(static_cast<void> (0));
8158 assert(ElementCount::isKnownGE((static_cast<void> (0))
8159 N->getIndex().getValueType().getVectorElementCount(),(static_cast<void> (0))
8160 N->getValueType(0).getVectorElementCount()) &&(static_cast<void> (0))
8161 "Vector width mismatch between index and data")(static_cast<void> (0));
8162 assert(isa<ConstantSDNode>(N->getScale()) &&(static_cast<void> (0))
8163 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&(static_cast<void> (0))
8164 "Scale should be a constant power of 2")(static_cast<void> (0));
8165
8166 CSEMap.InsertNode(N, IP);
8167 InsertNode(N);
8168 SDValue V(N, 0);
8169 NewSDValueDbgMsg(V, "Creating new node: ", this);
8170 return V;
8171}
8172
8173SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8174 ArrayRef<SDValue> Ops,
8175 MachineMemOperand *MMO,
8176 ISD::MemIndexType IndexType,
8177 bool IsTrunc) {
8178 assert(Ops.size() == 6 && "Incompatible number of operands")(static_cast<void> (0));
8179
8180 FoldingSetNodeID ID;
8181 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8182 ID.AddInteger(MemVT.getRawBits());
8183 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8184 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8185 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8186 void *IP = nullptr;
8187 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8188 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8189 return SDValue(E, 0);
8190 }
8191
8192 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8193 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8194 VTs, MemVT, MMO, IndexType, IsTrunc);
8195 createOperands(N, Ops);
8196
8197 assert(N->getMask().getValueType().getVectorElementCount() ==(static_cast<void> (0))
8198 N->getValue().getValueType().getVectorElementCount() &&(static_cast<void> (0))
8199 "Vector width mismatch between mask and data")(static_cast<void> (0));
8200 assert((static_cast<void> (0))
8201 N->getIndex().getValueType().getVectorElementCount().isScalable() ==(static_cast<void> (0))
8202 N->getValue().getValueType().getVectorElementCount().isScalable() &&(static_cast<void> (0))
8203 "Scalable flags of index and data do not match")(static_cast<void> (0));
8204 assert(ElementCount::isKnownGE((static_cast<void> (0))
8205 N->getIndex().getValueType().getVectorElementCount(),(static_cast<void> (0))
8206 N->getValue().getValueType().getVectorElementCount()) &&(static_cast<void> (0))
8207 "Vector width mismatch between index and data")(static_cast<void> (0));
8208 assert(isa<ConstantSDNode>(N->getScale()) &&(static_cast<void> (0))
8209 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&(static_cast<void> (0))
8210 "Scale should be a constant power of 2")(static_cast<void> (0));
8211
8212 CSEMap.InsertNode(N, IP);
8213 InsertNode(N);
8214 SDValue V(N, 0);
8215 NewSDValueDbgMsg(V, "Creating new node: ", this);
8216 return V;
8217}
8218
8219SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8220 // select undef, T, F --> T (if T is a constant), otherwise F
8221 // select, ?, undef, F --> F
8222 // select, ?, T, undef --> T
8223 if (Cond.isUndef())
8224 return isConstantValueOfAnyType(T) ? T : F;
8225 if (T.isUndef())
8226 return F;
8227 if (F.isUndef())
8228 return T;
8229
8230 // select true, T, F --> T
8231 // select false, T, F --> F
8232 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8233 return CondC->isNullValue() ? F : T;
8234
8235 // TODO: This should simplify VSELECT with constant condition using something
8236 // like this (but check boolean contents to be complete?):
8237 // if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8238 // return T;
8239 // if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8240 // return F;
8241
8242 // select ?, T, T --> T
8243 if (T == F)
8244 return T;
8245
8246 return SDValue();
8247}
8248
8249SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8250 // shift undef, Y --> 0 (can always assume that the undef value is 0)
8251 if (X.isUndef())
8252 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8253 // shift X, undef --> undef (because it may shift by the bitwidth)
8254 if (Y.isUndef())
8255 return getUNDEF(X.getValueType());
8256
8257 // shift 0, Y --> 0
8258 // shift X, 0 --> X
8259 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8260 return X;
8261
8262 // shift X, C >= bitwidth(X) --> undef
8263 // All vector elements must be too big (or undef) to avoid partial undefs.
8264 auto isShiftTooBig = [X](ConstantSDNode *Val) {
8265 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8266 };
8267 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8268 return getUNDEF(X.getValueType());
8269
8270 return SDValue();
8271}
8272
8273SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8274 SDNodeFlags Flags) {
8275 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8276 // (an undef operand can be chosen to be Nan/Inf), then the result of this
8277 // operation is poison. That result can be relaxed to undef.
8278 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8279 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8280 bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8281 (YC && YC->getValueAPF().isNaN());
8282 bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8283 (YC && YC->getValueAPF().isInfinity());
8284
8285 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8286 return getUNDEF(X.getValueType());
8287
8288 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8289 return getUNDEF(X.getValueType());
8290
8291 if (!YC)
8292 return SDValue();
8293
8294 // X + -0.0 --> X
8295 if (Opcode == ISD::FADD)
8296 if (YC->getValueAPF().isNegZero())
8297 return X;
8298
8299 // X - +0.0 --> X
8300 if (Opcode == ISD::FSUB)
8301 if (YC->getValueAPF().isPosZero())
8302 return X;
8303
8304 // X * 1.0 --> X
8305 // X / 1.0 --> X
8306 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8307 if (YC->getValueAPF().isExactlyValue(1.0))
8308 return X;
8309
8310 // X * 0.0 --> 0.0
8311 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8312 if (YC->getValueAPF().isZero())
8313 return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8314
8315 return SDValue();
8316}
8317
8318SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8319 SDValue Ptr, SDValue SV, unsigned Align) {
8320 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8321 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8322}
8323
8324SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8325 ArrayRef<SDUse> Ops) {
8326 switch (Ops.size()) {
8327 case 0: return getNode(Opcode, DL, VT);
8328 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8329 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8330 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8331 default: break;
8332 }
8333
8334 // Copy from an SDUse array into an SDValue array for use with
8335 // the regular getNode logic.
8336 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8337 return getNode(Opcode, DL, VT, NewOps);
8338}
8339
8340SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8341 ArrayRef<SDValue> Ops) {
8342 SDNodeFlags Flags;
8343 if (Inserter)
8344 Flags = Inserter->getFlags();
8345 return getNode(Opcode, DL, VT, Ops, Flags);
8346}
8347
8348SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8349 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8350 unsigned NumOps = Ops.size();
8351 switch (NumOps) {
8352 case 0: return getNode(Opcode, DL, VT);
8353 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8354 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8355 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8356 default: break;
8357 }
8358
8359#ifndef NDEBUG1
8360 for (auto &Op : Ops)
8361 assert(Op.getOpcode() != ISD::DELETED_NODE &&(static_cast<void> (0))
8362 "Operand is DELETED_NODE!")(static_cast<void> (0));
8363#endif
8364
8365 switch (Opcode) {
8366 default: break;
8367 case ISD::BUILD_VECTOR:
8368 // Attempt to simplify BUILD_VECTOR.
8369 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8370 return V;
8371 break;
8372 case ISD::CONCAT_VECTORS:
8373 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8374 return V;
8375 break;
8376 case ISD::SELECT_CC:
8377 assert(NumOps == 5 && "SELECT_CC takes 5 operands!")(static_cast<void> (0));
8378 assert(Ops[0].getValueType() == Ops[1].getValueType() &&(static_cast<void> (0))
8379 "LHS and RHS of condition must have same type!")(static_cast<void> (0));
8380 assert(Ops[2].getValueType() == Ops[3].getValueType() &&(static_cast<void> (0))
8381 "True and False arms of SelectCC must have same type!")(static_cast<void> (0));
8382 assert(Ops[2].getValueType() == VT &&(static_cast<void> (0))
8383 "select_cc node must be of same type as true and false value!")(static_cast<void> (0));
8384 break;
8385 case ISD::BR_CC:
8386 assert(NumOps == 5 && "BR_CC takes 5 operands!")(static_cast<void> (0));
8387 assert(Ops[2].getValueType() == Ops[3].getValueType() &&(static_cast<void> (0))
8388 "LHS/RHS of comparison should match types!")(static_cast<void> (0));
8389 break;
8390 }
8391
8392 // Memoize nodes.
8393 SDNode *N;
8394 SDVTList VTs = getVTList(VT);
8395
8396 if (VT != MVT::Glue) {
8397 FoldingSetNodeID ID;
8398 AddNodeIDNode(ID, Opcode, VTs, Ops);
8399 void *IP = nullptr;
8400
8401 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8402 return SDValue(E, 0);
8403
8404 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8405 createOperands(N, Ops);
8406
8407 CSEMap.InsertNode(N, IP);
8408 } else {
8409 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8410 createOperands(N, Ops);
8411 }
8412
8413 N->setFlags(Flags);
8414 InsertNode(N);
8415 SDValue V(N, 0);
8416 NewSDValueDbgMsg(V, "Creating new node: ", this);
8417 return V;
8418}
8419
8420SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8421 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8422 return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8423}
8424
8425SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8426 ArrayRef<SDValue> Ops) {
8427 SDNodeFlags Flags;
8428 if (Inserter)
8429 Flags = Inserter->getFlags();
8430 return getNode(Opcode, DL, VTList, Ops, Flags);
8431}
8432
8433SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8434 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8435 if (VTList.NumVTs == 1)
8436 return getNode(Opcode, DL, VTList.VTs[0], Ops);
8437
8438#ifndef NDEBUG1
8439 for (auto &Op : Ops)
8440 assert(Op.getOpcode() != ISD::DELETED_NODE &&(static_cast<void> (0))
8441 "Operand is DELETED_NODE!")(static_cast<void> (0));
8442#endif
8443
8444 switch (Opcode) {
8445 case ISD::STRICT_FP_EXTEND:
8446 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&(static_cast<void> (0))
8447 "Invalid STRICT_FP_EXTEND!")(static_cast<void> (0));
8448 assert(VTList.VTs[0].isFloatingPoint() &&(static_cast<void> (0))
8449 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!")(static_cast<void> (0));
8450 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&(static_cast<void> (0))
8451 "STRICT_FP_EXTEND result type should be vector iff the operand "(static_cast<void> (0))
8452 "type is vector!")(static_cast<void> (0));
8453 assert((!VTList.VTs[0].isVector() ||(static_cast<void> (0))
8454 VTList.VTs[0].getVectorNumElements() ==(static_cast<void> (0))
8455 Ops[1].getValueType().getVectorNumElements()) &&(static_cast<void> (0))
8456 "Vector element count mismatch!")(static_cast<void> (0));
8457 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&(static_cast<void> (0))
8458 "Invalid fpext node, dst <= src!")(static_cast<void> (0));
8459 break;
8460 case ISD::STRICT_FP_ROUND:
8461 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!")(static_cast<void> (0));
8462 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&(static_cast<void> (0))
8463 "STRICT_FP_ROUND result type should be vector iff the operand "(static_cast<void> (0))
8464 "type is vector!")(static_cast<void> (0));
8465 assert((!VTList.VTs[0].isVector() ||(static_cast<void> (0))
8466 VTList.VTs[0].getVectorNumElements() ==(static_cast<void> (0))
8467 Ops[1].getValueType().getVectorNumElements()) &&(static_cast<void> (0))
8468 "Vector element count mismatch!")(static_cast<void> (0));
8469 assert(VTList.VTs[0].isFloatingPoint() &&(static_cast<void> (0))
8470 Ops[1].getValueType().isFloatingPoint() &&(static_cast<void> (0))
8471 VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&(static_cast<void> (0))
8472 isa<ConstantSDNode>(Ops[2]) &&(static_cast<void> (0))
8473 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||(static_cast<void> (0))
8474 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&(static_cast<void> (0))
8475 "Invalid STRICT_FP_ROUND!")(static_cast<void> (0));
8476 break;
8477#if 0
8478 // FIXME: figure out how to safely handle things like
8479 // int foo(int x) { return 1 << (x & 255); }
8480 // int bar() { return foo(256); }
8481 case ISD::SRA_PARTS:
8482 case ISD::SRL_PARTS:
8483 case ISD::SHL_PARTS:
8484 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8485 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8486 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8487 else if (N3.getOpcode() == ISD::AND)
8488 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
8489 // If the and is only masking out bits that cannot effect the shift,
8490 // eliminate the and.
8491 unsigned NumBits = VT.getScalarSizeInBits()*2;
8492 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
8493 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8494 }
8495 break;
8496#endif
8497 }
8498
8499 // Memoize the node unless it returns a flag.
8500 SDNode *N;
8501 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
8502 FoldingSetNodeID ID;
8503 AddNodeIDNode(ID, Opcode, VTList, Ops);
8504 void *IP = nullptr;
8505 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8506 return SDValue(E, 0);
8507
8508 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8509 createOperands(N, Ops);
8510 CSEMap.InsertNode(N, IP);
8511 } else {
8512 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8513 createOperands(N, Ops);
8514 }
8515
8516 N->setFlags(Flags);
8517 InsertNode(N);
8518 SDValue V(N, 0);
8519 NewSDValueDbgMsg(V, "Creating new node: ", this);
8520 return V;
8521}
8522
8523SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8524 SDVTList VTList) {
8525 return getNode(Opcode, DL, VTList, None);
8526}
8527
8528SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8529 SDValue N1) {
8530 SDValue Ops[] = { N1 };
8531 return getNode(Opcode, DL, VTList, Ops);
8532}
8533
8534SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8535 SDValue N1, SDValue N2) {
8536 SDValue Ops[] = { N1, N2 };
8537 return getNode(Opcode, DL, VTList, Ops);
8538}
8539
8540SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8541 SDValue N1, SDValue N2, SDValue N3) {
8542 SDValue Ops[] = { N1, N2, N3 };
8543 return getNode(Opcode, DL, VTList, Ops);
8544}
8545
8546SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8547 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
8548 SDValue Ops[] = { N1, N2, N3, N4 };
8549 return getNode(Opcode, DL, VTList, Ops);
8550}
8551
8552SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8553 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8554 SDValue N5) {
8555 SDValue Ops[] = { N1, N2, N3, N4, N5 };
8556 return getNode(Opcode, DL, VTList, Ops);
8557}
8558
8559SDVTList SelectionDAG::getVTList(EVT VT) {
8560 return makeVTList(SDNode::getValueTypeList(VT), 1);
8561}
8562
8563SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
8564 FoldingSetNodeID ID;
8565 ID.AddInteger(2U);
8566 ID.AddInteger(VT1.getRawBits());
8567 ID.AddInteger(VT2.getRawBits());
8568
8569 void *IP = nullptr;
8570 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8571 if (!Result) {
8572 EVT *Array = Allocator.Allocate<EVT>(2);
8573 Array[0] = VT1;
8574 Array[1] = VT2;
8575 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
8576 VTListMap.InsertNode(Result, IP);
8577 }
8578 return Result->getSDVTList();
8579}
8580
8581SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
8582 FoldingSetNodeID ID;
8583 ID.AddInteger(3U);
8584 ID.AddInteger(VT1.getRawBits());
8585 ID.AddInteger(VT2.getRawBits());
8586 ID.AddInteger(VT3.getRawBits());
8587
8588 void *IP = nullptr;
8589 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8590 if (!Result) {
8591 EVT *Array = Allocator.Allocate<EVT>(3);
8592 Array[0] = VT1;
8593 Array[1] = VT2;
8594 Array[2] = VT3;
8595 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
8596 VTListMap.InsertNode(Result, IP);
8597 }
8598 return Result->getSDVTList();
8599}
8600
8601SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
8602 FoldingSetNodeID ID;
8603 ID.AddInteger(4U);
8604 ID.AddInteger(VT1.getRawBits());
8605 ID.AddInteger(VT2.getRawBits());
8606 ID.AddInteger(VT3.getRawBits());
8607 ID.AddInteger(VT4.getRawBits());
8608
8609 void *IP = nullptr;
8610 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8611 if (!Result) {
8612 EVT *Array = Allocator.Allocate<EVT>(4);
8613 Array[0] = VT1;
8614 Array[1] = VT2;
8615 Array[2] = VT3;
8616 Array[3] = VT4;
8617 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
8618 VTListMap.InsertNode(Result, IP);
8619 }
8620 return Result->getSDVTList();
8621}
8622
8623SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
8624 unsigned NumVTs = VTs.size();
8625 FoldingSetNodeID ID;
8626 ID.AddInteger(NumVTs);
8627 for (unsigned index = 0; index < NumVTs; index++) {
8628 ID.AddInteger(VTs[index].getRawBits());
8629 }
8630
8631 void *IP = nullptr;
8632 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8633 if (!Result) {
8634 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
8635 llvm::copy(VTs, Array);
8636 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
8637 VTListMap.InsertNode(Result, IP);
8638 }
8639 return Result->getSDVTList();
8640}
8641
8642
8643/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
8644/// specified operands. If the resultant node already exists in the DAG,
8645/// this does not modify the specified node, instead it returns the node that
8646/// already exists. If the resultant node does not exist in the DAG, the
8647/// input node is returned. As a degenerate case, if you specify the same
8648/// input operands as the node already has, the input node is returned.
8649SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
8650 assert(N->getNumOperands() == 1 && "Update with wrong number of operands")(static_cast<void> (0));
8651
8652 // Check to see if there is no change.
8653 if (Op == N->getOperand(0)) return N;
8654
8655 // See if the modified node already exists.
8656 void *InsertPos = nullptr;
8657 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
8658 return Existing;
8659
8660 // Nope it doesn't. Remove the node from its current place in the maps.
8661 if (InsertPos)
8662 if (!RemoveNodeFromCSEMaps(N))
8663 InsertPos = nullptr;
8664
8665 // Now we update the operands.
8666 N->OperandList[0].set(Op);
8667
8668 updateDivergence(N);
8669 // If this gets put into a CSE map, add it.
8670 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8671 return N;
8672}
8673
8674SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8675 assert(N->getNumOperands() == 2 && "Update with wrong number of operands")(static_cast<void> (0));
8676
8677 // Check to see if there is no change.
8678 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8679 return N; // No operands changed, just return the input node.
8680
8681 // See if the modified node already exists.
8682 void *InsertPos = nullptr;
8683 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8684 return Existing;
8685
8686 // Nope it doesn't. Remove the node from its current place in the maps.
8687 if (InsertPos)
8688 if (!RemoveNodeFromCSEMaps(N))
8689 InsertPos = nullptr;
8690
8691 // Now we update the operands.
8692 if (N->OperandList[0] != Op1)
8693 N->OperandList[0].set(Op1);
8694 if (N->OperandList[1] != Op2)
8695 N->OperandList[1].set(Op2);
8696
8697 updateDivergence(N);
8698 // If this gets put into a CSE map, add it.
8699 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8700 return N;
8701}
8702
8703SDNode *SelectionDAG::
8704UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8705 SDValue Ops[] = { Op1, Op2, Op3 };
8706 return UpdateNodeOperands(N, Ops);
8707}
8708
8709SDNode *SelectionDAG::
8710UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8711 SDValue Op3, SDValue Op4) {
8712 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8713 return UpdateNodeOperands(N, Ops);
8714}
8715
8716SDNode *SelectionDAG::
8717UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8718 SDValue Op3, SDValue Op4, SDValue Op5) {
8719 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8720 return UpdateNodeOperands(N, Ops);
8721}
8722
8723SDNode *SelectionDAG::
8724UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8725 unsigned NumOps = Ops.size();
8726 assert(N->getNumOperands() == NumOps &&(static_cast<void> (0))
8727 "Update with wrong number of operands")(static_cast<void> (0));
8728
8729 // If no operands changed just return the input node.
8730 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8731 return N;
8732
8733 // See if the modified node already exists.
8734 void *InsertPos = nullptr;
8735 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8736 return Existing;
8737
8738 // Nope it doesn't. Remove the node from its current place in the maps.
8739 if (InsertPos)
8740 if (!RemoveNodeFromCSEMaps(N))
8741 InsertPos = nullptr;
8742
8743 // Now we update the operands.
8744 for (unsigned i = 0; i != NumOps; ++i)
8745 if (N->OperandList[i] != Ops[i])
8746 N->OperandList[i].set(Ops[i]);
8747
8748 updateDivergence(N);
8749 // If this gets put into a CSE map, add it.
8750 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8751 return N;
8752}
8753
8754/// DropOperands - Release the operands and set this node to have
8755/// zero operands.
8756void SDNode::DropOperands() {
8757 // Unlike the code in MorphNodeTo that does this, we don't need to
8758 // watch for dead nodes here.
8759 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8760 SDUse &Use = *I++;
8761 Use.set(SDValue());
8762 }
8763}
8764
8765void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8766 ArrayRef<MachineMemOperand *> NewMemRefs) {
8767 if (NewMemRefs.empty()) {
8768 N->clearMemRefs();
8769 return;
8770 }
8771
8772 // Check if we can avoid allocating by storing a single reference directly.
8773 if (NewMemRefs.size() == 1) {
8774 N->MemRefs = NewMemRefs[0];
8775 N->NumMemRefs = 1;
8776 return;
8777 }
8778
8779 MachineMemOperand **MemRefsBuffer =
8780 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8781 llvm::copy(NewMemRefs, MemRefsBuffer);
8782 N->MemRefs = MemRefsBuffer;
8783 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8784}
8785
8786/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8787/// machine opcode.
8788///
8789SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8790 EVT VT) {
8791 SDVTList VTs = getVTList(VT);
8792 return SelectNodeTo(N, MachineOpc, VTs, None);
8793}
8794
8795SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8796 EVT VT, SDValue Op1) {
8797 SDVTList VTs = getVTList(VT);
8798 SDValue Ops[] = { Op1 };
8799 return SelectNodeTo(N, MachineOpc, VTs, Ops);
8800}
8801
8802SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8803 EVT VT, SDValue Op1,
8804 SDValue Op2) {
8805 SDVTList VTs = getVTList(VT);
8806 SDValue Ops[] = { Op1, Op2 };
8807 return SelectNodeTo(N, MachineOpc, VTs, Ops);
8808}
8809
8810SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8811 EVT VT, SDValue Op1,
8812 SDValue Op2, SDValue Op3) {
8813 SDVTList VTs = getVTList(VT);
8814 SDValue Ops[] = { Op1, Op2, Op3 };
8815 return SelectNodeTo(N, MachineOpc, VTs, Ops);
8816}
8817
8818SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8819 EVT VT, ArrayRef<SDValue> Ops) {
8820 SDVTList VTs = getVTList(VT);
8821 return SelectNodeTo(N, MachineOpc, VTs, Ops);
8822}
8823
8824SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8825 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8826 SDVTList VTs = getVTList(VT1, VT2);
8827 return SelectNodeTo(N, MachineOpc, VTs, Ops);
8828}
8829
8830SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8831 EVT VT1, EVT VT2) {
8832 SDVTList VTs = getVTList(VT1, VT2);
8833 return SelectNodeTo(N, MachineOpc, VTs, None);
8834}
8835
8836SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8837 EVT VT1, EVT VT2, EVT VT3,
8838 ArrayRef<SDValue> Ops) {
8839 SDVTList VTs = getVTList(VT1, VT2, VT3);
8840 return SelectNodeTo(N, MachineOpc, VTs, Ops);
8841}
8842
8843SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8844 EVT VT1, EVT VT2,
8845 SDValue Op1, SDValue Op2) {
8846 SDVTList VTs = getVTList(VT1, VT2);
8847 SDValue Ops[] = { Op1, Op2 };
8848 return SelectNodeTo(N, MachineOpc, VTs, Ops);
8849}
8850
8851SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8852 SDVTList VTs,ArrayRef<SDValue> Ops) {
8853 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8854 // Reset the NodeID to -1.
8855 New->setNodeId(-1);
8856 if (New != N) {
8857 ReplaceAllUsesWith(N, New);
8858 RemoveDeadNode(N);
8859 }
8860 return New;
8861}
8862
8863/// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8864/// the line number information on the merged node since it is not possible to
8865/// preserve the information that operation is associated with multiple lines.
8866/// This will make the debugger working better at -O0, were there is a higher
8867/// probability having other instructions associated with that line.
8868///
8869/// For IROrder, we keep the smaller of the two
8870SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8871 DebugLoc NLoc = N->getDebugLoc();
8872 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8873 N->setDebugLoc(DebugLoc());
8874 }
8875 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8876 N->setIROrder(Order);
8877 return N;
8878}
8879
8880/// MorphNodeTo - This *mutates* the specified node to have the specified
8881/// return type, opcode, and operands.
8882///
8883/// Note that MorphNodeTo returns the resultant node. If there is already a
8884/// node of the specified opcode and operands, it returns that node instead of
8885/// the current one. Note that the SDLoc need not be the same.
8886///
8887/// Using MorphNodeTo is faster than creating a new node and swapping it in
8888/// with ReplaceAllUsesWith both because it often avoids allocating a new
8889/// node, and because it doesn't require CSE recalculation for any of
8890/// the node's users.
8891///
8892/// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8893/// As a consequence it isn't appropriate to use from within the DAG combiner or
8894/// the legalizer which maintain worklists that would need to be updated when
8895/// deleting things.
8896SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8897 SDVTList VTs, ArrayRef<SDValue> Ops) {
8898 // If an identical node already exists, use it.
8899 void *IP = nullptr;
8900 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8901 FoldingSetNodeID ID;
8902 AddNodeIDNode(ID, Opc, VTs, Ops);
8903 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8904 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8905 }
8906
8907 if (!RemoveNodeFromCSEMaps(N))
8908 IP = nullptr;
8909
8910 // Start the morphing.
8911 N->NodeType = Opc;
8912 N->ValueList = VTs.VTs;
8913 N->NumValues = VTs.NumVTs;
8914
8915 // Clear the operands list, updating used nodes to remove this from their
8916 // use list. Keep track of any operands that become dead as a result.
8917 SmallPtrSet<SDNode*, 16> DeadNodeSet;
8918 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8919 SDUse &Use = *I++;
8920 SDNode *Used = Use.getNode();
8921 Use.set(SDValue());
8922 if (Used->use_empty())
8923 DeadNodeSet.insert(Used);
8924 }
8925
8926 // For MachineNode, initialize the memory references information.
8927 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8928 MN->clearMemRefs();
8929
8930 // Swap for an appropriately sized array from the recycler.
8931 removeOperands(N);
8932 createOperands(N, Ops);
8933
8934 // Delete any nodes that are still dead after adding the uses for the
8935 // new operands.
8936 if (!DeadNodeSet.empty()) {
8937 SmallVector<SDNode *, 16> DeadNodes;
8938 for (SDNode *N : DeadNodeSet)
8939 if (N->use_empty())
8940 DeadNodes.push_back(N);
8941 RemoveDeadNodes(DeadNodes);
8942 }
8943
8944 if (IP)
8945 CSEMap.InsertNode(N, IP); // Memoize the new node.
8946 return N;
8947}
8948
8949SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8950 unsigned OrigOpc = Node->getOpcode();
8951 unsigned NewOpc;
8952 switch (OrigOpc) {
8953 default:
8954 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!")__builtin_unreachable();
8955#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
8956 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8957#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
8958 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8959#include "llvm/IR/ConstrainedOps.def"
8960 }
8961
8962 assert(Node->getNumValues() == 2 && "Unexpected number of results!")(static_cast<void> (0));
8963
8964 // We're taking this node out of the chain, so we need to re-link things.
8965 SDValue InputChain = Node->getOperand(0);
8966 SDValue OutputChain = SDValue(Node, 1);
8967 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8968
8969 SmallVector<SDValue, 3> Ops;
8970 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8971 Ops.push_back(Node->getOperand(i));
8972
8973 SDVTList VTs = getVTList(Node->getValueType(0));
8974 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8975
8976 // MorphNodeTo can operate in two ways: if an existing node with the
8977 // specified operands exists, it can just return it. Otherwise, it
8978 // updates the node in place to have the requested operands.
8979 if (Res == Node) {
8980 // If we updated the node in place, reset the node ID. To the isel,
8981 // this should be just like a newly allocated machine node.
8982 Res->setNodeId(-1);
8983 } else {
8984 ReplaceAllUsesWith(Node, Res);
8985 RemoveDeadNode(Node);
8986 }
8987
8988 return Res;
8989}
8990
8991/// getMachineNode - These are used for target selectors to create a new node
8992/// with specified return type(s), MachineInstr opcode, and operands.
8993///
8994/// Note that getMachineNode returns the resultant node. If there is already a
8995/// node of the specified opcode and operands, it returns that node instead of
8996/// the current one.
8997MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8998 EVT VT) {
8999 SDVTList VTs = getVTList(VT);
9000 return getMachineNode(Opcode, dl, VTs, None);
9001}
9002
9003MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9004 EVT VT, SDValue Op1) {
9005 SDVTList VTs = getVTList(VT);
9006 SDValue Ops[] = { Op1 };
9007 return getMachineNode(Opcode, dl, VTs, Ops);
9008}
9009
9010MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9011 EVT VT, SDValue Op1, SDValue Op2) {
9012 SDVTList VTs = getVTList(VT);
9013 SDValue Ops[] = { Op1, Op2 };
9014 return getMachineNode(Opcode, dl, VTs, Ops);
9015}
9016
9017MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9018 EVT VT, SDValue Op1, SDValue Op2,
9019 SDValue Op3) {
9020 SDVTList VTs = getVTList(VT);
9021 SDValue Ops[] = { Op1, Op2, Op3 };
9022 return getMachineNode(Opcode, dl, VTs, Ops);
9023}
9024
9025MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9026 EVT VT, ArrayRef<SDValue> Ops) {
9027 SDVTList VTs = getVTList(VT);
9028 return getMachineNode(Opcode, dl, VTs, Ops);
9029}
9030
9031MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9032 EVT VT1, EVT VT2, SDValue Op1,
9033 SDValue Op2) {
9034 SDVTList VTs = getVTList(VT1, VT2);
9035 SDValue Ops[] = { Op1, Op2 };
9036 return getMachineNode(Opcode, dl, VTs, Ops);
9037}
9038
9039MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9040 EVT VT1, EVT VT2, SDValue Op1,
9041 SDValue Op2, SDValue Op3) {
9042 SDVTList VTs = getVTList(VT1, VT2);
9043 SDValue Ops[] = { Op1, Op2, Op3 };
9044 return getMachineNode(Opcode, dl, VTs, Ops);
9045}
9046
9047MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9048 EVT VT1, EVT VT2,
9049 ArrayRef<SDValue> Ops) {
9050 SDVTList VTs = getVTList(VT1, VT2);
9051 return getMachineNode(Opcode, dl, VTs, Ops);
9052}
9053
9054MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9055 EVT VT1, EVT VT2, EVT VT3,
9056 SDValue Op1, SDValue Op2) {
9057 SDVTList VTs = getVTList(VT1, VT2, VT3);
9058 SDValue Ops[] = { Op1, Op2 };
9059 return getMachineNode(Opcode, dl, VTs, Ops);
9060}
9061
9062MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9063 EVT VT1, EVT VT2, EVT VT3,
9064 SDValue Op1, SDValue Op2,
9065 SDValue Op3) {
9066 SDVTList VTs = getVTList(VT1, VT2, VT3);
9067 SDValue Ops[] = { Op1, Op2, Op3 };
9068 return getMachineNode(Opcode, dl, VTs, Ops);
9069}
9070
9071MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9072 EVT VT1, EVT VT2, EVT VT3,
9073 ArrayRef<SDValue> Ops) {
9074 SDVTList VTs = getVTList(VT1, VT2, VT3);
9075 return getMachineNode(Opcode, dl, VTs, Ops);
9076}
9077
9078MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9079 ArrayRef<EVT> ResultTys,
9080 ArrayRef<SDValue> Ops) {
9081 SDVTList VTs = getVTList(ResultTys);
9082 return getMachineNode(Opcode, dl, VTs, Ops);
9083}
9084
9085MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9086 SDVTList VTs,
9087 ArrayRef<SDValue> Ops) {
9088 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9089 MachineSDNode *N;
9090 void *IP = nullptr;
9091
9092 if (DoCSE) {
9093 FoldingSetNodeID ID;
9094 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9095 IP = nullptr;
9096 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9097 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9098 }
9099 }
9100
9101 // Allocate a new MachineSDNode.
9102 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9103 createOperands(N, Ops);
9104
9105 if (DoCSE)
9106 CSEMap.InsertNode(N, IP);
9107
9108 InsertNode(N);
9109 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9110 return N;
9111}
9112
9113/// getTargetExtractSubreg - A convenience function for creating
9114/// TargetOpcode::EXTRACT_SUBREG nodes.
9115SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9116 SDValue Operand) {
9117 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9118 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9119 VT, Operand, SRIdxVal);
9120 return SDValue(Subreg, 0);
9121}
9122
9123/// getTargetInsertSubreg - A convenience function for creating
9124/// TargetOpcode::INSERT_SUBREG nodes.
9125SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9126 SDValue Operand, SDValue Subreg) {
9127 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9128 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9129 VT, Operand, Subreg, SRIdxVal);
9130 return SDValue(Result, 0);
9131}
9132
9133/// getNodeIfExists - Get the specified node if it's already available, or
9134/// else return NULL.
9135SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9136 ArrayRef<SDValue> Ops) {
9137 SDNodeFlags Flags;
9138 if (Inserter)
9139 Flags = Inserter->getFlags();
9140 return getNodeIfExists(Opcode, VTList, Ops, Flags);
9141}
9142
9143SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9144 ArrayRef<SDValue> Ops,
9145 const SDNodeFlags Flags) {
9146 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9147 FoldingSetNodeID ID;
9148 AddNodeIDNode(ID, Opcode, VTList, Ops);
9149 void *IP = nullptr;
9150 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9151 E->intersectFlagsWith(Flags);
9152 return E;
9153 }
9154 }
9155 return nullptr;
9156}
9157
9158/// doesNodeExist - Check if a node exists without modifying its flags.
9159bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9160 ArrayRef<SDValue> Ops) {
9161 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9162 FoldingSetNodeID ID;
9163 AddNodeIDNode(ID, Opcode, VTList, Ops);
9164 void *IP = nullptr;
9165 if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9166 return true;
9167 }
9168 return false;
9169}
9170
9171/// getDbgValue - Creates a SDDbgValue node.
9172///
9173/// SDNode
9174SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9175 SDNode *N, unsigned R, bool IsIndirect,
9176 const DebugLoc &DL, unsigned O) {
9177 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&(static_cast<void> (0))
9178 "Expected inlined-at fields to agree")(static_cast<void> (0));
9179 return new (DbgInfo->getAlloc())
9180 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9181 {}, IsIndirect, DL, O,
9182 /*IsVariadic=*/false);
9183}
9184
9185/// Constant
9186SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9187 DIExpression *Expr,
9188 const Value *C,
9189 const DebugLoc &DL, unsigned O) {
9190 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&(static_cast<void> (0))
9191 "Expected inlined-at fields to agree")(static_cast<void> (0));
9192 return new (DbgInfo->getAlloc())
9193 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9194 /*IsIndirect=*/false, DL, O,
9195 /*IsVariadic=*/false);
9196}
9197
9198/// FrameIndex
9199SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9200 DIExpression *Expr, unsigned FI,
9201 bool IsIndirect,
9202 const DebugLoc &DL,
9203 unsigned O) {
9204 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&(static_cast<void> (0))
9205 "Expected inlined-at fields to agree")(static_cast<void> (0));
9206 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9207}
9208
9209/// FrameIndex with dependencies
9210SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9211 DIExpression *Expr, unsigned FI,
9212 ArrayRef<SDNode *> Dependencies,
9213 bool IsIndirect,
9214 const DebugLoc &DL,
9215 unsigned O) {
9216 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&(static_cast<void> (0))
9217 "Expected inlined-at fields to agree")(static_cast<void> (0));
9218 return new (DbgInfo->getAlloc())
9219 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9220 Dependencies, IsIndirect, DL, O,
9221 /*IsVariadic=*/false);
9222}
9223
9224/// VReg
9225SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9226 unsigned VReg, bool IsIndirect,
9227 const DebugLoc &DL, unsigned O) {
9228 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&(static_cast<void> (0))
9229 "Expected inlined-at fields to agree")(static_cast<void> (0));
9230 return new (DbgInfo->getAlloc())
9231 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9232 {}, IsIndirect, DL, O,
9233 /*IsVariadic=*/false);
9234}
9235
9236SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9237 ArrayRef<SDDbgOperand> Locs,
9238 ArrayRef<SDNode *> Dependencies,
9239 bool IsIndirect, const DebugLoc &DL,
9240 unsigned O, bool IsVariadic) {
9241 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&(static_cast<void> (0))
9242 "Expected inlined-at fields to agree")(static_cast<void> (0));
9243 return new (DbgInfo->getAlloc())
9244 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9245 DL, O, IsVariadic);
9246}
9247
9248void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9249 unsigned OffsetInBits, unsigned SizeInBits,
9250 bool InvalidateDbg) {
9251 SDNode *FromNode = From.getNode();
9252 SDNode *ToNode = To.getNode();
9253 assert(FromNode && ToNode && "Can't modify dbg values")(static_cast<void> (0));
9254
9255 // PR35338
9256 // TODO: assert(From != To && "Redundant dbg value transfer");
9257 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9258 if (From == To || FromNode == ToNode)
9259 return;
9260
9261 if (!FromNode->getHasDebugValue())
9262 return;
9263
9264 SDDbgOperand FromLocOp =
9265 SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9266 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9267
9268 SmallVector<SDDbgValue *, 2> ClonedDVs;
9269 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9270 if (Dbg->isInvalidated())
9271 continue;
9272
9273 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9274
9275 // Create a new location ops vector that is equal to the old vector, but
9276 // with each instance of FromLocOp replaced with ToLocOp.
9277 bool Changed = false;
9278 auto NewLocOps = Dbg->copyLocationOps();
9279 std::replace_if(
9280 NewLocOps.begin(), NewLocOps.end(),
9281 [&Changed, FromLocOp](const SDDbgOperand &Op) {
9282 bool Match = Op == FromLocOp;
9283 Changed |= Match;
9284 return Match;
9285 },
9286 ToLocOp);
9287 // Ignore this SDDbgValue if we didn't find a matching location.
9288 if (!Changed)
9289 continue;
9290
9291 DIVariable *Var = Dbg->getVariable();
9292 auto *Expr = Dbg->getExpression();
9293 // If a fragment is requested, update the expression.
9294 if (SizeInBits) {
9295 // When splitting a larger (e.g., sign-extended) value whose
9296 // lower bits are described with an SDDbgValue, do not attempt
9297 // to transfer the SDDbgValue to the upper bits.
9298 if (auto FI = Expr->getFragmentInfo())
9299 if (OffsetInBits + SizeInBits > FI->SizeInBits)
9300 continue;
9301 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9302 SizeInBits);
9303 if (!Fragment)
9304 continue;
9305 Expr = *Fragment;
9306 }
9307
9308 auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9309 // Clone the SDDbgValue and move it to To.
9310 SDDbgValue *Clone = getDbgValueList(
9311 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9312 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9313 Dbg->isVariadic());
9314 ClonedDVs.push_back(Clone);
9315
9316 if (InvalidateDbg) {
9317 // Invalidate value and indicate the SDDbgValue should not be emitted.
9318 Dbg->setIsInvalidated();
9319 Dbg->setIsEmitted();
9320 }
9321 }
9322
9323 for (SDDbgValue *Dbg : ClonedDVs) {
9324 assert(is_contained(Dbg->getSDNodes(), ToNode) &&(static_cast<void> (0))
9325 "Transferred DbgValues should depend on the new SDNode")(static_cast<void> (0));
9326 AddDbgValue(Dbg, false);
9327 }
9328}
9329
9330void SelectionDAG::salvageDebugInfo(SDNode &N) {
9331 if (!N.getHasDebugValue())
9332 return;
9333
9334 SmallVector<SDDbgValue *, 2> ClonedDVs;
9335 for (auto DV : GetDbgValues(&N)) {
9336 if (DV->isInvalidated())
9337 continue;
9338 switch (N.getOpcode()) {
9339 default:
9340 break;
9341 case ISD::ADD:
9342 SDValue N0 = N.getOperand(0);
9343 SDValue N1 = N.getOperand(1);
9344 if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9345 isConstantIntBuildVectorOrConstantInt(N1)) {
9346 uint64_t Offset = N.getConstantOperandVal(1);
9347
9348 // Rewrite an ADD constant node into a DIExpression. Since we are
9349 // performing arithmetic to compute the variable's *value* in the
9350 // DIExpression, we need to mark the expression with a
9351 // DW_OP_stack_value.
9352 auto *DIExpr = DV->getExpression();
9353 auto NewLocOps = DV->copyLocationOps();
9354 bool Changed = false;
9355 for (size_t i = 0; i < NewLocOps.size(); ++i) {
9356 // We're not given a ResNo to compare against because the whole
9357 // node is going away. We know that any ISD::ADD only has one
9358 // result, so we can assume any node match is using the result.
9359 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9360 NewLocOps[i].getSDNode() != &N)
9361 continue;
9362 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9363 SmallVector<uint64_t, 3> ExprOps;
9364 DIExpression::appendOffset(ExprOps, Offset);
9365 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9366 Changed = true;
9367 }
9368 (void)Changed;
9369 assert(Changed && "Salvage target doesn't use N")(static_cast<void> (0));
9370
9371 auto AdditionalDependencies = DV->getAdditionalDependencies();
9372 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9373 NewLocOps, AdditionalDependencies,
9374 DV->isIndirect(), DV->getDebugLoc(),
9375 DV->getOrder(), DV->isVariadic());
9376 ClonedDVs.push_back(Clone);
9377 DV->setIsInvalidated();
9378 DV->setIsEmitted();
9379 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";do { } while (false)
9380 N0.getNode()->dumprFull(this);do { } while (false)
9381 dbgs() << " into " << *DIExpr << '\n')do { } while (false);
9382 }
9383 }
9384 }
9385
9386 for (SDDbgValue *Dbg : ClonedDVs) {
9387 assert(!Dbg->getSDNodes().empty() &&(static_cast<void> (0))
9388 "Salvaged DbgValue should depend on a new SDNode")(static_cast<void> (0));
9389 AddDbgValue(Dbg, false);
9390 }
9391}
9392
9393/// Creates a SDDbgLabel node.
9394SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9395 const DebugLoc &DL, unsigned O) {
9396 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&(static_cast<void> (0))
9397 "Expected inlined-at fields to agree")(static_cast<void> (0));
9398 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9399}
9400
9401namespace {
9402
9403/// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9404/// pointed to by a use iterator is deleted, increment the use iterator
9405/// so that it doesn't dangle.
9406///
9407class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9408 SDNode::use_iterator &UI;
9409 SDNode::use_iterator &UE;
9410
9411 void NodeDeleted(SDNode *N, SDNode *E) override {
9412 // Increment the iterator as needed.
9413 while (UI != UE && N == *UI)
9414 ++UI;
9415 }
9416
9417public:
9418 RAUWUpdateListener(SelectionDAG &d,
9419 SDNode::use_iterator &ui,
9420 SDNode::use_iterator &ue)
9421 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9422};
9423
9424} // end anonymous namespace
9425
9426/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9427/// This can cause recursive merging of nodes in the DAG.
9428///
9429/// This version assumes From has a single result value.
9430///
9431void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9432 SDNode *From = FromN.getNode();
9433 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&(static_cast<void> (0))
9434 "Cannot replace with this method!")(static_cast<void> (0));
9435 assert(From != To.getNode() && "Cannot replace uses of with self")(static_cast<void> (0));
9436
9437 // Preserve Debug Values
9438 transferDbgValues(FromN, To);
9439
9440 // Iterate over all the existing uses of From. New uses will be added
9441 // to the beginning of the use list, which we avoid visiting.
9442 // This specifically avoids visiting uses of From that arise while the
9443 // replacement is happening, because any such uses would be the result
9444 // of CSE: If an existing node looks like From after one of its operands
9445 // is replaced by To, we don't want to replace of all its users with To
9446 // too. See PR3018 for more info.
9447 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9448 RAUWUpdateListener Listener(*this, UI, UE);
9449 while (UI != UE) {
9450 SDNode *User = *UI;
9451
9452 // This node is about to morph, remove its old self from the CSE maps.
9453 RemoveNodeFromCSEMaps(User);
9454
9455 // A user can appear in a use list multiple times, and when this
9456 // happens the uses are usually next to each other in the list.
9457 // To help reduce the number of CSE recomputations, process all
9458 // the uses of this user that we can find this way.
9459 do {
9460 SDUse &Use = UI.getUse();
9461 ++UI;
9462 Use.set(To);
9463 if (To->isDivergent() != From->isDivergent())
9464 updateDivergence(User);
9465 } while (UI != UE && *UI == User);
9466 // Now that we have modified User, add it back to the CSE maps. If it
9467 // already exists there, recursively merge the results together.
9468 AddModifiedNodeToCSEMaps(User);
9469 }
9470
9471 // If we just RAUW'd the root, take note.
9472 if (FromN == getRoot())
9473 setRoot(To);
9474}
9475
9476/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9477/// This can cause recursive merging of nodes in the DAG.
9478///
9479/// This version assumes that for each value of From, there is a
9480/// corresponding value in To in the same position with the same type.
9481///
9482void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9483#ifndef NDEBUG1
9484 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9485 assert((!From->hasAnyUseOfValue(i) ||(static_cast<void> (0))
9486 From->getValueType(i) == To->getValueType(i)) &&(static_cast<void> (0))
9487 "Cannot use this version of ReplaceAllUsesWith!")(static_cast<void> (0));
9488#endif
9489
9490 // Handle the trivial case.
9491 if (From == To)
9492 return;
9493
9494 // Preserve Debug Info. Only do this if there's a use.
9495 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9496 if (From->hasAnyUseOfValue(i)) {
9497 assert((i < To->getNumValues()) && "Invalid To location")(static_cast<void> (0));
9498 transferDbgValues(SDValue(From, i), SDValue(To, i));
9499 }
9500
9501 // Iterate over just the existing users of From. See the comments in
9502 // the ReplaceAllUsesWith above.
9503 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9504 RAUWUpdateListener Listener(*this, UI, UE);
9505 while (UI != UE) {
9506 SDNode *User = *UI;
9507
9508 // This node is about to morph, remove its old self from the CSE maps.
9509 RemoveNodeFromCSEMaps(User);
9510
9511 // A user can appear in a use list multiple times, and when this
9512 // happens the uses are usually next to each other in the list.
9513 // To help reduce the number of CSE recomputations, process all
9514 // the uses of this user that we can find this way.
9515 do {
9516 SDUse &Use = UI.getUse();
9517 ++UI;
9518 Use.setNode(To);
9519 if (To->isDivergent() != From->isDivergent())
9520 updateDivergence(User);
9521 } while (UI != UE && *UI == User);
9522
9523 // Now that we have modified User, add it back to the CSE maps. If it
9524 // already exists there, recursively merge the results together.
9525 AddModifiedNodeToCSEMaps(User);
9526 }
9527
9528 // If we just RAUW'd the root, take note.
9529 if (From == getRoot().getNode())
9530 setRoot(SDValue(To, getRoot().getResNo()));
9531}
9532
9533/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9534/// This can cause recursive merging of nodes in the DAG.
9535///
9536/// This version can replace From with any result values. To must match the
9537/// number and types of values returned by From.
9538void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
9539 if (From->getNumValues() == 1) // Handle the simple case efficiently.
9540 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
9541
9542 // Preserve Debug Info.
9543 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9544 transferDbgValues(SDValue(From, i), To[i]);
9545
9546 // Iterate over just the existing users of From. See the comments in
9547 // the ReplaceAllUsesWith above.
9548 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9549 RAUWUpdateListener Listener(*this, UI, UE);
9550 while (UI != UE) {
9551 SDNode *User = *UI;
9552
9553 // This node is about to morph, remove its old self from the CSE maps.
9554 RemoveNodeFromCSEMaps(User);
9555
9556 // A user can appear in a use list multiple times, and when this happens the
9557 // uses are usually next to each other in the list. To help reduce the
9558 // number of CSE and divergence recomputations, process all the uses of this
9559 // user that we can find this way.
9560 bool To_IsDivergent = false;
9561 do {
9562 SDUse &Use = UI.getUse();
9563 const SDValue &ToOp = To[Use.getResNo()];
9564 ++UI;
9565 Use.set(ToOp);
9566 To_IsDivergent |= ToOp->isDivergent();
9567 } while (UI != UE && *UI == User);
9568
9569 if (To_IsDivergent != From->isDivergent())
9570 updateDivergence(User);
9571
9572 // Now that we have modified User, add it back to the CSE maps. If it
9573 // already exists there, recursively merge the results together.
9574 AddModifiedNodeToCSEMaps(User);
9575 }
9576
9577 // If we just RAUW'd the root, take note.
9578 if (From == getRoot().getNode())
9579 setRoot(SDValue(To[getRoot().getResNo()]));
9580}
9581
9582/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
9583/// uses of other values produced by From.getNode() alone. The Deleted
9584/// vector is handled the same way as for ReplaceAllUsesWith.
9585void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
9586 // Handle the really simple, really trivial case efficiently.
9587 if (From == To) return;
9588
9589 // Handle the simple, trivial, case efficiently.
9590 if (From.getNode()->getNumValues() == 1) {
9591 ReplaceAllUsesWith(From, To);
9592 return;
9593 }
9594
9595 // Preserve Debug Info.
9596 transferDbgValues(From, To);
9597
9598 // Iterate over just the existing users of From. See the comments in
9599 // the ReplaceAllUsesWith above.
9600 SDNode::use_iterator UI = From.getNode()->use_begin(),
9601 UE = From.getNode()->use_end();
9602 RAUWUpdateListener Listener(*this, UI, UE);
9603 while (UI != UE) {
9604 SDNode *User = *UI;
9605 bool UserRemovedFromCSEMaps = false;
9606
9607 // A user can appear in a use list multiple times, and when this
9608 // happens the uses are usually next to each other in the list.
9609 // To help reduce the number of CSE recomputations, process all
9610 // the uses of this user that we can find this way.
9611 do {
9612 SDUse &Use = UI.getUse();
9613
9614 // Skip uses of different values from the same node.
9615 if (Use.getResNo() != From.getResNo()) {
9616 ++UI;
9617 continue;
9618 }
9619
9620 // If this node hasn't been modified yet, it's still in the CSE maps,
9621 // so remove its old self from the CSE maps.
9622 if (!UserRemovedFromCSEMaps) {
9623 RemoveNodeFromCSEMaps(User);
9624 UserRemovedFromCSEMaps = true;
9625 }
9626
9627 ++UI;
9628 Use.set(To);
9629 if (To->isDivergent() != From->isDivergent())
9630 updateDivergence(User);
9631 } while (UI != UE && *UI == User);
9632 // We are iterating over all uses of the From node, so if a use
9633 // doesn't use the specific value, no changes are made.
9634 if (!UserRemovedFromCSEMaps)
9635 continue;
9636
9637 // Now that we have modified User, add it back to the CSE maps. If it
9638 // already exists there, recursively merge the results together.
9639 AddModifiedNodeToCSEMaps(User);
9640 }
9641
9642 // If we just RAUW'd the root, take note.
9643 if (From == getRoot())
9644 setRoot(To);
9645}
9646
9647namespace {
9648
9649 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
9650 /// to record information about a use.
9651 struct UseMemo {
9652 SDNode *User;
9653 unsigned Index;
9654 SDUse *Use;
9655 };
9656
9657 /// operator< - Sort Memos by User.
9658 bool operator<(const UseMemo &L, const UseMemo &R) {
9659 return (intptr_t)L.User < (intptr_t)R.User;
9660 }
9661
9662} // end anonymous namespace
9663
9664bool SelectionDAG::calculateDivergence(SDNode *N) {
9665 if (TLI->isSDNodeAlwaysUniform(N)) {
9666 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&(static_cast<void> (0))
9667 "Conflicting divergence information!")(static_cast<void> (0));
9668 return false;
9669 }
9670 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9671 return true;
9672 for (auto &Op : N->ops()) {
9673 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9674 return true;
9675 }
9676 return false;
9677}
9678
9679void SelectionDAG::updateDivergence(SDNode *N) {
9680 SmallVector<SDNode *, 16> Worklist(1, N);
9681 do {
9682 N = Worklist.pop_back_val();
9683 bool IsDivergent = calculateDivergence(N);
9684 if (N->SDNodeBits.IsDivergent != IsDivergent) {
9685 N->SDNodeBits.IsDivergent = IsDivergent;
9686 llvm::append_range(Worklist, N->uses());
9687 }
9688 } while (!Worklist.empty());
9689}
9690
9691void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9692 DenseMap<SDNode *, unsigned> Degree;
9693 Order.reserve(AllNodes.size());
9694 for (auto &N : allnodes()) {
9695 unsigned NOps = N.getNumOperands();
9696 Degree[&N] = NOps;
9697 if (0 == NOps)
9698 Order.push_back(&N);
9699 }
9700 for (size_t I = 0; I != Order.size(); ++I) {
9701 SDNode *N = Order[I];
9702 for (auto U : N->uses()) {
9703 unsigned &UnsortedOps = Degree[U];
9704 if (0 == --UnsortedOps)
9705 Order.push_back(U);
9706 }
9707 }
9708}
9709
9710#ifndef NDEBUG1
9711void SelectionDAG::VerifyDAGDiverence() {
9712 std::vector<SDNode *> TopoOrder;
9713 CreateTopologicalOrder(TopoOrder);
9714 for (auto *N : TopoOrder) {
9715 assert(calculateDivergence(N) == N->isDivergent() &&(static_cast<void> (0))
9716 "Divergence bit inconsistency detected")(static_cast<void> (0));
9717 }
9718}
9719#endif
9720
9721/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9722/// uses of other values produced by From.getNode() alone. The same value
9723/// may appear in both the From and To list. The Deleted vector is
9724/// handled the same way as for ReplaceAllUsesWith.
9725void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9726 const SDValue *To,
9727 unsigned Num){
9728 // Handle the simple, trivial case efficiently.
9729 if (Num == 1)
9730 return ReplaceAllUsesOfValueWith(*From, *To);
9731
9732 transferDbgValues(*From, *To);
9733
9734 // Read up all the uses and make records of them. This helps
9735 // processing new uses that are introduced during the
9736 // replacement process.
9737 SmallVector<UseMemo, 4> Uses;
9738 for (unsigned i = 0; i != Num; ++i) {
9739 unsigned FromResNo = From[i].getResNo();
9740 SDNode *FromNode = From[i].getNode();
9741 for (SDNode::use_iterator UI = FromNode->use_begin(),
9742 E = FromNode->use_end(); UI != E; ++UI) {
9743 SDUse &Use = UI.getUse();
9744 if (Use.getResNo() == FromResNo) {
9745 UseMemo Memo = { *UI, i, &Use };
9746 Uses.push_back(Memo);
9747 }
9748 }
9749 }
9750
9751 // Sort the uses, so that all the uses from a given User are together.
9752 llvm::sort(Uses);
9753
9754 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9755 UseIndex != UseIndexEnd; ) {
9756 // We know that this user uses some value of From. If it is the right
9757 // value, update it.
9758 SDNode *User = Uses[UseIndex].User;
9759
9760 // This node is about to morph, remove its old self from the CSE maps.
9761 RemoveNodeFromCSEMaps(User);
9762
9763 // The Uses array is sorted, so all the uses for a given User
9764 // are next to each other in the list.
9765 // To help reduce the number of CSE recomputations, process all
9766 // the uses of this user that we can find this way.
9767 do {
9768 unsigned i = Uses[UseIndex].Index;
9769 SDUse &Use = *Uses[UseIndex].Use;
9770 ++UseIndex;
9771
9772 Use.set(To[i]);
9773 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9774
9775 // Now that we have modified User, add it back to the CSE maps. If it
9776 // already exists there, recursively merge the results together.
9777 AddModifiedNodeToCSEMaps(User);
9778 }
9779}
9780
9781/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9782/// based on their topological order. It returns the maximum id and a vector
9783/// of the SDNodes* in assigned order by reference.
9784unsigned SelectionDAG::AssignTopologicalOrder() {
9785 unsigned DAGSize = 0;
9786
9787 // SortedPos tracks the progress of the algorithm. Nodes before it are
9788 // sorted, nodes after it are unsorted. When the algorithm completes
9789 // it is at the end of the list.
9790 allnodes_iterator SortedPos = allnodes_begin();
9791
9792 // Visit all the nodes. Move nodes with no operands to the front of
9793 // the list immediately. Annotate nodes that do have operands with their
9794 // operand count. Before we do this, the Node Id fields of the nodes
9795 // may contain arbitrary values. After, the Node Id fields for nodes
9796 // before SortedPos will contain the topological sort index, and the
9797 // Node Id fields for nodes At SortedPos and after will contain the
9798 // count of outstanding operands.
9799 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
9800 SDNode *N = &*I++;
9801 checkForCycles(N, this);
9802 unsigned Degree = N->getNumOperands();
9803 if (Degree == 0) {
9804 // A node with no uses, add it to the result array immediately.
9805 N->setNodeId(DAGSize++);
9806 allnodes_iterator Q(N);
9807 if (Q != SortedPos)
9808 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9809 assert(SortedPos != AllNodes.end() && "Overran node list")(static_cast<void> (0));
9810 ++SortedPos;
9811 } else {
9812 // Temporarily use the Node Id as scratch space for the degree count.
9813 N->setNodeId(Degree);
9814 }
9815 }
9816
9817 // Visit all the nodes. As we iterate, move nodes into sorted order,
9818 // such that by the time the end is reached all nodes will be sorted.
9819 for (SDNode &Node : allnodes()) {
9820 SDNode *N = &Node;
9821 checkForCycles(N, this);
9822 // N is in sorted position, so all its uses have one less operand
9823 // that needs to be sorted.
9824 for (SDNode *P : N->uses()) {
9825 unsigned Degree = P->getNodeId();
9826 assert(Degree != 0 && "Invalid node degree")(static_cast<void> (0));
9827 --Degree;
9828 if (Degree == 0) {
9829 // All of P's operands are sorted, so P may sorted now.
9830 P->setNodeId(DAGSize++);
9831 if (P->getIterator() != SortedPos)
9832 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9833 assert(SortedPos != AllNodes.end() && "Overran node list")(static_cast<void> (0));
9834 ++SortedPos;
9835 } else {
9836 // Update P's outstanding operand count.
9837 P->setNodeId(Degree);
9838 }
9839 }
9840 if (Node.getIterator() == SortedPos) {
9841#ifndef NDEBUG1
9842 allnodes_iterator I(N);
9843 SDNode *S = &*++I;
9844 dbgs() << "Overran sorted position:\n";
9845 S->dumprFull(this); dbgs() << "\n";
9846 dbgs() << "Checking if this is due to cycles\n";
9847 checkForCycles(this, true);
9848#endif
9849 llvm_unreachable(nullptr)__builtin_unreachable();
9850 }
9851 }
9852
9853 assert(SortedPos == AllNodes.end() &&(static_cast<void> (0))
9854 "Topological sort incomplete!")(static_cast<void> (0));
9855 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&(static_cast<void> (0))
9856 "First node in topological sort is not the entry token!")(static_cast<void> (0));
9857 assert(AllNodes.front().getNodeId() == 0 &&(static_cast<void> (0))
9858 "First node in topological sort has non-zero id!")(static_cast<void> (0));
9859 assert(AllNodes.front().getNumOperands() == 0 &&(static_cast<void> (0))
9860 "First node in topological sort has operands!")(static_cast<void> (0));
9861 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&(static_cast<void> (0))
9862 "Last node in topologic sort has unexpected id!")(static_cast<void> (0));
9863 assert(AllNodes.back().use_empty() &&(static_cast<void> (0))
9864 "Last node in topologic sort has users!")(static_cast<void> (0));
9865 assert(DAGSize == allnodes_size() && "Node count mismatch!")(static_cast<void> (0));
9866 return DAGSize;
9867}
9868
9869/// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9870/// value is produced by SD.
9871void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
9872 for (SDNode *SD : DB->getSDNodes()) {
9873 if (!SD)
9874 continue;
9875 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue())(static_cast<void> (0));
9876 SD->setHasDebugValue(true);
9877 }
9878 DbgInfo->add(DB, isParameter);
9879}
9880
9881void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
9882
9883SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9884 SDValue NewMemOpChain) {
9885 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node")(static_cast<void> (0));
9886 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT")(static_cast<void> (0));
9887 // The new memory operation must have the same position as the old load in
9888 // terms of memory dependency. Create a TokenFactor for the old load and new
9889 // memory operation and update uses of the old load's output chain to use that
9890 // TokenFactor.
9891 if (OldChain == NewMemOpChain || OldChain.use_empty())
9892 return NewMemOpChain;
9893
9894 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9895 OldChain, NewMemOpChain);
9896 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9897 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9898 return TokenFactor;
9899}
9900
9901SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9902 SDValue NewMemOp) {
9903 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node")(static_cast<void> (0));
9904 SDValue OldChain = SDValue(OldLoad, 1);
9905 SDValue NewMemOpChain = NewMemOp.getValue(1);
9906 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9907}
9908
9909SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9910 Function **OutFunction) {
9911 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol")(static_cast<void> (0));
9912
9913 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9914 auto *Module = MF->getFunction().getParent();
9915 auto *Function = Module->getFunction(Symbol);
9916
9917 if (OutFunction != nullptr)
9918 *OutFunction = Function;
9919
9920 if (Function != nullptr) {
9921 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9922 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9923 }
9924
9925 std::string ErrorStr;
9926 raw_string_ostream ErrorFormatter(ErrorStr);
9927
9928 ErrorFormatter << "Undefined external symbol ";
9929 ErrorFormatter << '"' << Symbol << '"';
9930 ErrorFormatter.flush();
9931
9932 report_fatal_error(ErrorStr);
9933}
9934
9935//===----------------------------------------------------------------------===//
9936// SDNode Class
9937//===----------------------------------------------------------------------===//
9938
9939bool llvm::isNullConstant(SDValue V) {
9940 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9941 return Const != nullptr && Const->isNullValue();
9942}
9943
9944bool llvm::isNullFPConstant(SDValue V) {
9945 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9946 return Const != nullptr && Const->isZero() && !Const->isNegative();
9947}
9948
9949bool llvm::isAllOnesConstant(SDValue V) {
9950 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9951 return Const != nullptr && Const->isAllOnesValue();
9952}
9953
9954bool llvm::isOneConstant(SDValue V) {
9955 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9956 return Const != nullptr && Const->isOne();
9957}
9958
9959SDValue llvm::peekThroughBitcasts(SDValue V) {
9960 while (V.getOpcode() == ISD::BITCAST)
9961 V = V.getOperand(0);
9962 return V;
9963}
9964
9965SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9966 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9967 V = V.getOperand(0);
9968 return V;
9969}
9970
9971SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9972 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9973 V = V.getOperand(0);
9974 return V;
9975}
9976
9977bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9978 if (V.getOpcode() != ISD::XOR)
9979 return false;
9980 V = peekThroughBitcasts(V.getOperand(1));
9981 unsigned NumBits = V.getScalarValueSizeInBits();
9982 ConstantSDNode *C =
9983 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9984 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9985}
9986
9987ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9988 bool AllowTruncation) {
9989 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9990 return CN;
9991
9992 // SplatVectors can truncate their operands. Ignore that case here unless
9993 // AllowTruncation is set.
9994 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
9995 EVT VecEltVT = N->getValueType(0).getVectorElementType();
9996 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9997 EVT CVT = CN->getValueType(0);
9998 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension")(static_cast<void> (0));
9999 if (AllowTruncation || CVT == VecEltVT)
10000 return CN;
10001 }
10002 }
10003
10004 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10005 BitVector UndefElements;
10006 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
10007
10008 // BuildVectors can truncate their operands. Ignore that case here unless
10009 // AllowTruncation is set.
10010 if (CN && (UndefElements.none() || AllowUndefs)) {
10011 EVT CVT = CN->getValueType(0);
10012 EVT NSVT = N.getValueType().getScalarType();
10013 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension")(static_cast<void> (0));
10014 if (AllowTruncation || (CVT == NSVT))
10015 return CN;
10016 }
10017 }
10018
10019 return nullptr;
10020}
10021
10022ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10023 bool AllowUndefs,
10024 bool AllowTruncation) {
10025 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10026 return CN;
10027
10028 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10029 BitVector UndefElements;
10030 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10031
10032 // BuildVectors can truncate their operands. Ignore that case here unless
10033 // AllowTruncation is set.
10034 if (CN && (UndefElements.none() || AllowUndefs)) {
10035 EVT CVT = CN->getValueType(0);
10036 EVT NSVT = N.getValueType().getScalarType();
10037 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension")(static_cast<void> (0));
10038 if (AllowTruncation || (CVT == NSVT))
10039 return CN;
10040 }
10041 }
10042
10043 return nullptr;
10044}
10045
10046ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10047 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10048 return CN;
10049
10050 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10051 BitVector UndefElements;
10052 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10053 if (CN && (UndefElements.none() || AllowUndefs))
10054 return CN;
10055 }
10056
10057 if (N.getOpcode() == ISD::SPLAT_VECTOR)
10058 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10059 return CN;
10060
10061 return nullptr;
10062}
10063
10064ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10065 const APInt &DemandedElts,
10066 bool AllowUndefs) {
10067 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10068 return CN;
10069
10070 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10071 BitVector UndefElements;
10072 ConstantFPSDNode *CN =
10073 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10074 if (CN && (UndefElements.none() || AllowUndefs))
10075 return CN;
10076 }
10077
10078 return nullptr;
10079}
10080
10081bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10082 // TODO: may want to use peekThroughBitcast() here.
10083 ConstantSDNode *C =
10084 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10085 return C && C->isNullValue();
10086}
10087
10088bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10089 // TODO: may want to use peekThroughBitcast() here.
10090 unsigned BitWidth = N.getScalarValueSizeInBits();
10091 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10092 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
10093}
10094
10095bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10096 N = peekThroughBitcasts(N);
10097 unsigned BitWidth = N.getScalarValueSizeInBits();
10098 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10099 return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth;
10100}
10101
10102HandleSDNode::~HandleSDNode() {
10103 DropOperands();
10104}
10105
10106GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10107 const DebugLoc &DL,
10108 const GlobalValue *GA, EVT VT,
10109 int64_t o, unsigned TF)
10110 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10111 TheGlobal = GA;
10112}
10113
10114AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10115 EVT VT, unsigned SrcAS,
10116 unsigned DestAS)
10117 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10118 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10119
10120MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10121 SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10122 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10123 MemSDNodeBits.IsVolatile = MMO->isVolatile();
10124 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10125 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10126 MemSDNodeBits.IsInvariant = MMO->isInvariant();
10127
10128 // We check here that the size of the memory operand fits within the size of
10129 // the MMO. This is because the MMO might indicate only a possible address
10130 // range instead of specifying the affected memory addresses precisely.
10131 // TODO: Make MachineMemOperands aware of scalable vectors.
10132 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&(static_cast<void> (0))
10133 "Size mismatch!")(static_cast<void> (0));
10134}
10135
10136/// Profile - Gather unique data for the node.
10137///
10138void SDNode::Profile(FoldingSetNodeID &ID) const {
10139 AddNodeIDNode(ID, this);
10140}
10141
10142namespace {
10143
10144 struct EVTArray {
10145 std::vector<EVT> VTs;
10146
10147 EVTArray() {
10148 VTs.reserve(MVT::VALUETYPE_SIZE);
10149 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10150 VTs.push_back(MVT((MVT::SimpleValueType)i));
10151 }
10152 };
10153
10154} // end anonymous namespace
10155
10156static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10157static ManagedStatic<EVTArray> SimpleVTArray;
10158static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10159
10160/// getValueTypeList - Return a pointer to the specified value type.
10161///
10162const EVT *SDNode::getValueTypeList(EVT VT) {
10163 if (VT.isExtended()) {
10164 sys::SmartScopedLock<true> Lock(*VTMutex);
10165 return &(*EVTs->insert(VT).first);
10166 }
10167 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!")(static_cast<void> (0));
10168 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10169}
10170
10171/// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10172/// indicated value. This method ignores uses of other values defined by this
10173/// operation.
10174bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10175 assert(Value < getNumValues() && "Bad value!")(static_cast<void> (0));
10176
10177 // TODO: Only iterate over uses of a given value of the node
10178 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10179 if (UI.getUse().getResNo() == Value) {
10180 if (NUses == 0)
10181 return false;
10182 --NUses;
10183 }
10184 }
10185
10186 // Found exactly the right number of uses?
10187 return NUses == 0;
10188}
10189
10190/// hasAnyUseOfValue - Return true if there are any use of the indicated
10191/// value. This method ignores uses of other values defined by this operation.
10192bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10193 assert(Value < getNumValues() && "Bad value!")(static_cast<void> (0));
10194
10195 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10196 if (UI.getUse().getResNo() == Value)
10197 return true;
10198
10199 return false;
10200}
10201
10202/// isOnlyUserOf - Return true if this node is the only use of N.
10203bool SDNode::isOnlyUserOf(const SDNode *N) const {
10204 bool Seen = false;
10205 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
10206 SDNode *User = *I;
10207 if (User == this)
10208 Seen = true;
10209 else
10210 return false;
10211 }
10212
10213 return Seen;
10214}
10215
10216/// Return true if the only users of N are contained in Nodes.
10217bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10218 bool Seen = false;
10219 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
10220 SDNode *User = *I;
10221 if (llvm::is_contained(Nodes, User))
10222 Seen = true;
10223 else
10224 return false;
10225 }
10226
10227 return Seen;
10228}
10229
10230/// isOperand - Return true if this node is an operand of N.
10231bool SDValue::isOperandOf(const SDNode *N) const {
10232 return is_contained(N->op_values(), *this);
10233}
10234
10235bool SDNode::isOperandOf(const SDNode *N) const {
10236 return any_of(N->op_values(),
10237 [this](SDValue Op) { return this == Op.getNode(); });
10238}
10239
10240/// reachesChainWithoutSideEffects - Return true if this operand (which must
10241/// be a chain) reaches the specified operand without crossing any
10242/// side-effecting instructions on any chain path. In practice, this looks
10243/// through token factors and non-volatile loads. In order to remain efficient,
10244/// this only looks a couple of nodes in, it does not do an exhaustive search.
10245///
10246/// Note that we only need to examine chains when we're searching for
10247/// side-effects; SelectionDAG requires that all side-effects are represented
10248/// by chains, even if another operand would force a specific ordering. This
10249/// constraint is necessary to allow transformations like splitting loads.
10250bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10251 unsigned Depth) const {
10252 if (*this == Dest) return true;
10253
10254 // Don't search too deeply, we just want to be able to see through
10255 // TokenFactor's etc.
10256 if (Depth == 0) return false;
10257
10258 // If this is a token factor, all inputs to the TF happen in parallel.
10259 if (getOpcode() == ISD::TokenFactor) {
10260 // First, try a shallow search.
10261 if (is_contained((*this)->ops(), Dest)) {
10262 // We found the chain we want as an operand of this TokenFactor.
10263 // Essentially, we reach the chain without side-effects if we could
10264 // serialize the TokenFactor into a simple chain of operations with
10265 // Dest as the last operation. This is automatically true if the
10266 // chain has one use: there are no other ordering constraints.
10267 // If the chain has more than one use, we give up: some other
10268 // use of Dest might force a side-effect between Dest and the current
10269 // node.
10270 if (Dest.hasOneUse())
10271 return true;
10272 }
10273 // Next, try a deep search: check whether every operand of the TokenFactor
10274 // reaches Dest.
10275 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10276 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10277 });
10278 }
10279
10280 // Loads don't have side effects, look through them.
10281 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10282 if (Ld->isUnordered())
10283 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10284 }
10285 return false;
10286}
10287
10288bool SDNode::hasPredecessor(const SDNode *N) const {
10289 SmallPtrSet<const SDNode *, 32> Visited;
10290 SmallVector<const SDNode *, 16> Worklist;
10291 Worklist.push_back(this);
10292 return hasPredecessorHelper(N, Visited, Worklist);
10293}
10294
10295void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10296 this->Flags.intersectWith(Flags);
10297}
10298
10299SDValue
10300SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10301 ArrayRef<ISD::NodeType> CandidateBinOps,
10302 bool AllowPartials) {
10303 // The pattern must end in an extract from index 0.
10304 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10305 !isNullConstant(Extract->getOperand(1)))
10306 return SDValue();
10307
10308 // Match against one of the candidate binary ops.
10309 SDValue Op = Extract->getOperand(0);
10310 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10311 return Op.getOpcode() == unsigned(BinOp);
10312 }))
10313 return SDValue();
10314
10315 // Floating-point reductions may require relaxed constraints on the final step
10316 // of the reduction because they may reorder intermediate operations.
10317 unsigned CandidateBinOp = Op.getOpcode();
10318 if (Op.getValueType().isFloatingPoint()) {
10319 SDNodeFlags Flags = Op->getFlags();
10320 switch (CandidateBinOp) {
10321 case ISD::FADD:
10322 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10323 return SDValue();
10324 break;
10325 default:
10326 llvm_unreachable("Unhandled FP opcode for binop reduction")__builtin_unreachable();
10327 }
10328 }
10329
10330 // Matching failed - attempt to see if we did enough stages that a partial
10331 // reduction from a subvector is possible.
10332 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10333 if (!AllowPartials || !Op)
10334 return SDValue();
10335 EVT OpVT = Op.getValueType();
10336 EVT OpSVT = OpVT.getScalarType();
10337 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10338 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10339 return SDValue();
10340 BinOp = (ISD::NodeType)CandidateBinOp;
10341 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10342 getVectorIdxConstant(0, SDLoc(Op)));
10343 };
10344
10345 // At each stage, we're looking for something that looks like:
10346 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10347 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10348 // i32 undef, i32 undef, i32 undef, i32 undef>
10349 // %a = binop <8 x i32> %op, %s
10350 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10351 // we expect something like:
10352 // <4,5,6,7,u,u,u,u>
10353 // <2,3,u,u,u,u,u,u>
10354 // <1,u,u,u,u,u,u,u>
10355 // While a partial reduction match would be:
10356 // <2,3,u,u,u,u,u,u>
10357 // <1,u,u,u,u,u,u,u>
10358 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10359 SDValue PrevOp;
10360 for (unsigned i = 0; i < Stages; ++i) {
10361 unsigned MaskEnd = (1 << i);
10362
10363 if (Op.getOpcode() != CandidateBinOp)
10364 return PartialReduction(PrevOp, MaskEnd);
10365
10366 SDValue Op0 = Op.getOperand(0);
10367 SDValue Op1 = Op.getOperand(1);
10368
10369 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10370 if (Shuffle) {
10371 Op = Op1;
10372 } else {
10373 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10374 Op = Op0;
10375 }
10376
10377 // The first operand of the shuffle should be the same as the other operand
10378 // of the binop.
10379 if (!Shuffle || Shuffle->getOperand(0) != Op)
10380 return PartialReduction(PrevOp, MaskEnd);
10381
10382 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10383 for (int Index = 0; Index < (int)MaskEnd; ++Index)
10384 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10385 return PartialReduction(PrevOp, MaskEnd);
10386
10387 PrevOp = Op;
10388 }
10389
10390 // Handle subvector reductions, which tend to appear after the shuffle
10391 // reduction stages.
10392 while (Op.getOpcode() == CandidateBinOp) {
10393 unsigned NumElts = Op.getValueType().getVectorNumElements();
10394 SDValue Op0 = Op.getOperand(0);
10395 SDValue Op1 = Op.getOperand(1);
10396 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10397 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10398 Op0.getOperand(0) != Op1.getOperand(0))
10399 break;
10400 SDValue Src = Op0.getOperand(0);
10401 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10402 if (NumSrcElts != (2 * NumElts))
10403 break;
10404 if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10405 Op1.getConstantOperandAPInt(1) == NumElts) &&
10406 !(Op1.getConstantOperandAPInt(1) == 0 &&
10407 Op0.getConstantOperandAPInt(1) == NumElts))
10408 break;
10409 Op = Src;
10410 }
10411
10412 BinOp = (ISD::NodeType)CandidateBinOp;
10413 return Op;
10414}
10415
10416SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
10417 assert(N->getNumValues() == 1 &&(static_cast<void> (0))
10418 "Can't unroll a vector with multiple results!")(static_cast<void> (0));
10419
10420 EVT VT = N->getValueType(0);
10421 unsigned NE = VT.getVectorNumElements();
10422 EVT EltVT = VT.getVectorElementType();
10423 SDLoc dl(N);
10424
10425 SmallVector<SDValue, 8> Scalars;
10426 SmallVector<SDValue, 4> Operands(N->getNumOperands());
10427
10428 // If ResNE is 0, fully unroll the vector op.
10429 if (ResNE == 0)
10430 ResNE = NE;
10431 else if (NE > ResNE)
10432 NE = ResNE;
10433
10434 unsigned i;
10435 for (i= 0; i != NE; ++i) {
10436 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
10437 SDValue Operand = N->getOperand(j);
10438 EVT OperandVT = Operand.getValueType();
10439 if (OperandVT.isVector()) {
10440 // A vector operand; extract a single element.
10441 EVT OperandEltVT = OperandVT.getVectorElementType();
10442 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
10443 Operand, getVectorIdxConstant(i, dl));
10444 } else {
10445 // A scalar operand; just use it as is.
10446 Operands[j] = Operand;
10447 }
10448 }
10449
10450 switch (N->getOpcode()) {
10451 default: {
10452 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
10453 N->getFlags()));
10454 break;
10455 }
10456 case ISD::VSELECT:
10457 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
10458 break;
10459 case ISD::SHL:
10460 case ISD::SRA:
10461 case ISD::SRL:
10462 case ISD::ROTL:
10463 case ISD::ROTR:
10464 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
10465 getShiftAmountOperand(Operands[0].getValueType(),
10466 Operands[1])));
10467 break;
10468 case ISD::SIGN_EXTEND_INREG: {
10469 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
10470 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
10471 Operands[0],
10472 getValueType(ExtVT)));
10473 }
10474 }
10475 }
10476
10477 for (; i < ResNE; ++i)
10478 Scalars.push_back(getUNDEF(EltVT));
10479
10480 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
10481 return getBuildVector(VecVT, dl, Scalars);
10482}
10483
10484std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
10485 SDNode *N, unsigned ResNE) {
10486 unsigned Opcode = N->getOpcode();
10487 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||(static_cast<void> (0))
10488 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||(static_cast<void> (0))
10489 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&(static_cast<void> (0))
10490 "Expected an overflow opcode")(static_cast<void> (0));
10491
10492 EVT ResVT = N->getValueType(0);
10493 EVT OvVT = N->getValueType(1);
10494 EVT ResEltVT = ResVT.getVectorElementType();
10495 EVT OvEltVT = OvVT.getVectorElementType();
10496 SDLoc dl(N);
10497
10498 // If ResNE is 0, fully unroll the vector op.
10499 unsigned NE = ResVT.getVectorNumElements();
10500 if (ResNE == 0)
10501 ResNE = NE;
10502 else if (NE > ResNE)
10503 NE = ResNE;
10504
10505 SmallVector<SDValue, 8> LHSScalars;
10506 SmallVector<SDValue, 8> RHSScalars;
10507 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
10508 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
10509
10510 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
10511 SDVTList VTs = getVTList(ResEltVT, SVT);
10512 SmallVector<SDValue, 8> ResScalars;
10513 SmallVector<SDValue, 8> OvScalars;
10514 for (unsigned i = 0; i < NE; ++i) {
10515 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
10516 SDValue Ov =
10517 getSelect(dl, OvEltVT, Res.getValue(1),
10518 getBoolConstant(true, dl, OvEltVT, ResVT),
10519 getConstant(0, dl, OvEltVT));
10520
10521 ResScalars.push_back(Res);
10522 OvScalars.push_back(Ov);
10523 }
10524
10525 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
10526 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
10527
10528 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
10529 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
10530 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
10531 getBuildVector(NewOvVT, dl, OvScalars));
10532}
10533
10534bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
10535 LoadSDNode *Base,
10536 unsigned Bytes,
10537 int Dist) const {
10538 if (LD->isVolatile() || Base->isVolatile())
10539 return false;
10540 // TODO: probably too restrictive for atomics, revisit
10541 if (!LD->isSimple())
10542 return false;
10543 if (LD->isIndexed() || Base->isIndexed())
10544 return false;
10545 if (LD->getChain() != Base->getChain())
10546 return false;
10547 EVT VT = LD->getValueType(0);
10548 if (VT.getSizeInBits() / 8 != Bytes)
10549 return false;
10550
10551 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
10552 auto LocDecomp = BaseIndexOffset::match(LD, *this);
10553
10554 int64_t Offset = 0;
10555 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
10556 return (Dist * Bytes == Offset);
10557 return false;
10558}
10559
10560/// InferPtrAlignment - Infer alignment of a load / store address. Return None
10561/// if it cannot be inferred.
10562MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
10563 // If this is a GlobalAddress + cst, return the alignment.
10564 const GlobalValue *GV = nullptr;
10565 int64_t GVOffset = 0;
10566 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
10567 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
10568 KnownBits Known(PtrWidth);
10569 llvm::computeKnownBits(GV, Known, getDataLayout());
10570 unsigned AlignBits = Known.countMinTrailingZeros();
10571 if (AlignBits)
10572 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
10573 }
10574
10575 // If this is a direct reference to a stack slot, use information about the
10576 // stack slot's alignment.
10577 int FrameIdx = INT_MIN(-2147483647 -1);
10578 int64_t FrameOffset = 0;
10579 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
10580 FrameIdx = FI->getIndex();
10581 } else if (isBaseWithConstantOffset(Ptr) &&
10582 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
10583 // Handle FI+Cst
10584 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10585 FrameOffset = Ptr.getConstantOperandVal(1);
10586 }
10587
10588 if (FrameIdx != INT_MIN(-2147483647 -1)) {
10589 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
10590 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
10591 }
10592
10593 return None;
10594}
10595
10596/// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
10597/// which is split (or expanded) into two not necessarily identical pieces.
10598std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
10599 // Currently all types are split in half.
10600 EVT LoVT, HiVT;
10601 if (!VT.isVector())
10602 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
10603 else
10604 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
10605
10606 return std::make_pair(LoVT, HiVT);
10607}
10608
10609/// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
10610/// type, dependent on an enveloping VT that has been split into two identical
10611/// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
10612std::pair<EVT, EVT>
10613SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
10614 bool *HiIsEmpty) const {
10615 EVT EltTp = VT.getVectorElementType();
10616 // Examples:
10617 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
10618 // custom VL=9 with enveloping VL=8/8 yields 8/1
10619 // custom VL=10 with enveloping VL=8/8 yields 8/2
10620 // etc.
10621 ElementCount VTNumElts = VT.getVectorElementCount();
10622 ElementCount EnvNumElts = EnvVT.getVectorElementCount();
10623 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&(static_cast<void> (0))
10624 "Mixing fixed width and scalable vectors when enveloping a type")(static_cast<void> (0));
10625 EVT LoVT, HiVT;
10626 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
10627 LoVT = EnvVT;
10628 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
10629 *HiIsEmpty = false;
10630 } else {
10631 // Flag that hi type has zero storage size, but return split envelop type
10632 // (this would be easier if vector types with zero elements were allowed).
10633 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
10634 HiVT = EnvVT;
10635 *HiIsEmpty = true;
10636 }
10637 return std::make_pair(LoVT, HiVT);
10638}
10639
10640/// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
10641/// low/high part.
10642std::pair<SDValue, SDValue>
10643SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
10644 const EVT &HiVT) {
10645 assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&(static_cast<void> (0))
10646 LoVT.isScalableVector() == N.getValueType().isScalableVector() &&(static_cast<void> (0))
10647 "Splitting vector with an invalid mixture of fixed and scalable "(static_cast<void> (0))
10648 "vector types")(static_cast<void> (0));
10649 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=(static_cast<void> (0))
10650 N.getValueType().getVectorMinNumElements() &&(static_cast<void> (0))
10651 "More vector elements requested than available!")(static_cast<void> (0));
10652 SDValue Lo, Hi;
10653 Lo =
10654 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
10655 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
10656 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
10657 // IDX with the runtime scaling factor of the result vector type. For
10658 // fixed-width result vectors, that runtime scaling factor is 1.
10659 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
10660 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
10661 return std::make_pair(Lo, Hi);
10662}
10663
10664/// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10665SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10666 EVT VT = N.getValueType();
10667 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10668 NextPowerOf2(VT.getVectorNumElements()));
10669 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10670 getVectorIdxConstant(0, DL));
10671}
10672
10673void SelectionDAG::ExtractVectorElements(SDValue Op,
10674 SmallVectorImpl<SDValue> &Args,
10675 unsigned Start, unsigned Count,
10676 EVT EltVT) {
10677 EVT VT = Op.getValueType();
10678 if (Count == 0)
10679 Count = VT.getVectorNumElements();
10680 if (EltVT == EVT())
10681 EltVT = VT.getVectorElementType();
10682 SDLoc SL(Op);
10683 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10684 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10685 getVectorIdxConstant(i, SL)));
10686 }
10687}
10688
10689// getAddressSpace - Return the address space this GlobalAddress belongs to.
10690unsigned GlobalAddressSDNode::getAddressSpace() const {
10691 return getGlobal()->getType()->getAddressSpace();
10692}
10693
10694Type *ConstantPoolSDNode::getType() const {
10695 if (isMachineConstantPoolEntry())
10696 return Val.MachineCPVal->getType();
10697 return Val.ConstVal->getType();
10698}
10699
10700bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10701 unsigned &SplatBitSize,
10702 bool &HasAnyUndefs,
10703 unsigned MinSplatBits,
10704 bool IsBigEndian) const {
10705 EVT VT = getValueType(0);
10706 assert(VT.isVector() && "Expected a vector type")(static_cast<void> (0));
10707 unsigned VecWidth = VT.getSizeInBits();
10708 if (MinSplatBits > VecWidth)
10709 return false;
10710
10711 // FIXME: The widths are based on this node's type, but build vectors can
10712 // truncate their operands.
10713 SplatValue = APInt(VecWidth, 0);
10714 SplatUndef = APInt(VecWidth, 0);
10715
10716 // Get the bits. Bits with undefined values (when the corresponding element
10717 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10718 // in SplatValue. If any of the values are not constant, give up and return
10719 // false.
10720 unsigned int NumOps = getNumOperands();
10721 assert(NumOps > 0 && "isConstantSplat has 0-size build vector")(static_cast<void> (0));
10722 unsigned EltWidth = VT.getScalarSizeInBits();
10723
10724 for (unsigned j = 0; j < NumOps; ++j) {
10725 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10726 SDValue OpVal = getOperand(i);
10727 unsigned BitPos = j * EltWidth;
10728
10729 if (OpVal.isUndef())
10730 SplatUndef.setBits(BitPos, BitPos + EltWidth);
10731 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10732 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10733 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10734 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10735 else
10736 return false;
10737 }
10738
10739 // The build_vector is all constants or undefs. Find the smallest element
10740 // size that splats the vector.
10741 HasAnyUndefs = (SplatUndef != 0);
10742
10743 // FIXME: This does not work for vectors with elements less than 8 bits.
10744 while (VecWidth > 8) {
10745 unsigned HalfSize = VecWidth / 2;
10746 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
10747 APInt LowValue = SplatValue.extractBits(HalfSize, 0);
10748 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
10749 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
10750
10751 // If the two halves do not match (ignoring undef bits), stop here.
10752 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10753 MinSplatBits > HalfSize)
10754 break;
10755
10756 SplatValue = HighValue | LowValue;
10757 SplatUndef = HighUndef & LowUndef;
10758
10759 VecWidth = HalfSize;
10760 }
10761
10762 SplatBitSize = VecWidth;
10763 return true;
10764}
10765
10766SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10767 BitVector *UndefElements) const {
10768 unsigned NumOps = getNumOperands();
10769 if (UndefElements) {
10770 UndefElements->clear();
10771 UndefElements->resize(NumOps);
10772 }
10773 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size")(static_cast<void> (0));
10774 if (!DemandedElts)
10775 return SDValue();
10776 SDValue Splatted;
10777 for (unsigned i = 0; i != NumOps; ++i) {
10778 if (!DemandedElts[i])
10779 continue;
10780 SDValue Op = getOperand(i);
10781 if (Op.isUndef()) {
10782 if (UndefElements)
10783 (*UndefElements)[i] = true;
10784 } else if (!Splatted) {
10785 Splatted = Op;
10786 } else if (Splatted != Op) {
10787 return SDValue();
10788 }
10789 }
10790
10791 if (!Splatted) {
10792 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10793 assert(getOperand(FirstDemandedIdx).isUndef() &&(static_cast<void> (0))
10794 "Can only have a splat without a constant for all undefs.")(static_cast<void> (0));
10795 return getOperand(FirstDemandedIdx);
10796 }
10797
10798 return Splatted;
10799}
10800
10801SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10802 APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
10803 return getSplatValue(DemandedElts, UndefElements);
10804}
10805
10806bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10807 SmallVectorImpl<SDValue> &Sequence,
10808 BitVector *UndefElements) const {
10809 unsigned NumOps = getNumOperands();
10810 Sequence.clear();
10811 if (UndefElements) {
10812 UndefElements->clear();
10813 UndefElements->resize(NumOps);
10814 }
10815 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size")(static_cast<void> (0));
10816 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10817 return false;
10818
10819 // Set the undefs even if we don't find a sequence (like getSplatValue).
10820 if (UndefElements)
10821 for (unsigned I = 0; I != NumOps; ++I)
10822 if (DemandedElts[I] && getOperand(I).isUndef())
10823 (*UndefElements)[I] = true;
10824
10825 // Iteratively widen the sequence length looking for repetitions.
10826 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10827 Sequence.append(SeqLen, SDValue());
10828 for (unsigned I = 0; I != NumOps; ++I) {
10829 if (!DemandedElts[I])
10830 continue;
10831 SDValue &SeqOp = Sequence[I % SeqLen];
10832 SDValue Op = getOperand(I);
10833 if (Op.isUndef()) {
10834 if (!SeqOp)
10835 SeqOp = Op;
10836 continue;
10837 }
10838 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10839 Sequence.clear();
10840 break;
10841 }
10842 SeqOp = Op;
10843 }
10844 if (!Sequence.empty())
10845 return true;
10846 }
10847
10848 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern")(static_cast<void> (0));
10849 return false;
10850}
10851
10852bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
10853 BitVector *UndefElements) const {
10854 APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
10855 return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
10856}
10857
10858ConstantSDNode *
10859BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10860 BitVector *UndefElements) const {
10861 return dyn_cast_or_null<ConstantSDNode>(
10862 getSplatValue(DemandedElts, UndefElements));
10863}
10864
10865ConstantSDNode *
10866BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10867 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10868}
10869
10870ConstantFPSDNode *
10871BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10872 BitVector *UndefElements) const {
10873 return dyn_cast_or_null<ConstantFPSDNode>(
10874 getSplatValue(DemandedElts, UndefElements));
10875}
10876
10877ConstantFPSDNode *
10878BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10879 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10880}
10881
10882int32_t
10883BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10884 uint32_t BitWidth) const {
10885 if (ConstantFPSDNode *CN =
10886 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10887 bool IsExact;
10888 APSInt IntVal(BitWidth);
10889 const APFloat &APF = CN->getValueAPF();
10890 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10891 APFloat::opOK ||
10892 !IsExact)
10893 return -1;
10894
10895 return IntVal.exactLogBase2();
10896 }
10897 return -1;
10898}
10899
10900bool BuildVectorSDNode::isConstant() const {
10901 for (const SDValue &Op : op_values()) {
10902 unsigned Opc = Op.getOpcode();
10903 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
10904 return false;
10905 }
10906 return true;
10907}
10908
10909bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
10910 // Find the first non-undef value in the shuffle mask.
10911 unsigned i, e;
10912 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
10913 /* search */;
10914
10915 // If all elements are undefined, this shuffle can be considered a splat
10916 // (although it should eventually get simplified away completely).
10917 if (i == e)
10918 return true;
10919
10920 // Make sure all remaining elements are either undef or the same as the first
10921 // non-undef value.
10922 for (int Idx = Mask[i]; i != e; ++i)
10923 if (Mask[i] >= 0 && Mask[i] != Idx)
10924 return false;
10925 return true;
10926}
10927
10928// Returns the SDNode if it is a constant integer BuildVector
10929// or constant integer.
10930SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
10931 if (isa<ConstantSDNode>(N))
10932 return N.getNode();
10933 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
10934 return N.getNode();
10935 // Treat a GlobalAddress supporting constant offset folding as a
10936 // constant integer.
10937 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
10938 if (GA->getOpcode() == ISD::GlobalAddress &&
10939 TLI->isOffsetFoldingLegal(GA))
10940 return GA;
10941 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
10942 isa<ConstantSDNode>(N.getOperand(0)))
10943 return N.getNode();
10944 return nullptr;
10945}
10946
10947// Returns the SDNode if it is a constant float BuildVector
10948// or constant float.
10949SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
10950 if (isa<ConstantFPSDNode>(N))
10951 return N.getNode();
10952
10953 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
10954 return N.getNode();
10955
10956 return nullptr;
10957}
10958
10959void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
10960 assert(!Node->OperandList && "Node already has operands")(static_cast<void> (0));
10961 assert(SDNode::getMaxNumOperands() >= Vals.size() &&(static_cast<void> (0))
10962 "too many operands to fit into SDNode")(static_cast<void> (0));
10963 SDUse *Ops = OperandRecycler.allocate(
10964 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
10965
10966 bool IsDivergent = false;
10967 for (unsigned I = 0; I != Vals.size(); ++I) {
10968 Ops[I].setUser(Node);
10969 Ops[I].setInitial(Vals[I]);
10970 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
10971 IsDivergent |= Ops[I].getNode()->isDivergent();
10972 }
10973 Node->NumOperands = Vals.size();
10974 Node->OperandList = Ops;
10975 if (!TLI->isSDNodeAlwaysUniform(Node)) {
10976 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
10977 Node->SDNodeBits.IsDivergent = IsDivergent;
10978 }
10979 checkForCycles(Node);
10980}
10981
10982SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
10983 SmallVectorImpl<SDValue> &Vals) {
10984 size_t Limit = SDNode::getMaxNumOperands();
10985 while (Vals.size() > Limit) {
10986 unsigned SliceIdx = Vals.size() - Limit;
10987 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
10988 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
10989 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
10990 Vals.emplace_back(NewTF);
10991 }
10992 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
10993}
10994
10995SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
10996 EVT VT, SDNodeFlags Flags) {
10997 switch (Opcode) {
10998 default:
10999 return SDValue();
11000 case ISD::ADD:
11001 case ISD::OR:
11002 case ISD::XOR:
11003 case ISD::UMAX:
11004 return getConstant(0, DL, VT);
11005 case ISD::MUL:
11006 return getConstant(1, DL, VT);
11007 case ISD::AND:
11008 case ISD::UMIN:
11009 return getAllOnesConstant(DL, VT);
11010 case ISD::SMAX:
11011 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11012 case ISD::SMIN:
11013 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11014 case ISD::FADD:
11015 return getConstantFP(-0.0, DL, VT);
11016 case ISD::FMUL:
11017 return getConstantFP(1.0, DL, VT);
11018 case ISD::FMINNUM:
11019 case ISD::FMAXNUM: {
11020 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11021 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11022 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11023 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11024 APFloat::getLargest(Semantics);
11025 if (Opcode == ISD::FMAXNUM)
11026 NeutralAF.changeSign();
11027
11028 return getConstantFP(NeutralAF, DL, VT);
11029 }
11030 }
11031}
11032
11033#ifndef NDEBUG1
11034static void checkForCyclesHelper(const SDNode *N,
11035 SmallPtrSetImpl<const SDNode*> &Visited,
11036 SmallPtrSetImpl<const SDNode*> &Checked,
11037 const llvm::SelectionDAG *DAG) {
11038 // If this node has already been checked, don't check it again.
11039 if (Checked.count(N))
11040 return;
11041
11042 // If a node has already been visited on this depth-first walk, reject it as
11043 // a cycle.
11044 if (!Visited.insert(N).second) {
11045 errs() << "Detected cycle in SelectionDAG\n";
11046 dbgs() << "Offending node:\n";
11047 N->dumprFull(DAG); dbgs() << "\n";
11048 abort();
11049 }
11050
11051 for (const SDValue &Op : N->op_values())
11052 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11053
11054 Checked.insert(N);
11055 Visited.erase(N);
11056}
11057#endif
11058
11059void llvm::checkForCycles(const llvm::SDNode *N,
11060 const llvm::SelectionDAG *DAG,
11061 bool force) {
11062#ifndef NDEBUG1
11063 bool check = force;
11064#ifdef EXPENSIVE_CHECKS
11065 check = true;
11066#endif // EXPENSIVE_CHECKS
11067 if (check) {
11068 assert(N && "Checking nonexistent SDNode")(static_cast<void> (0));
11069 SmallPtrSet<const SDNode*, 32> visited;
11070 SmallPtrSet<const SDNode*, 32> checked;
11071 checkForCyclesHelper(N, visited, checked, DAG);
11072 }
11073#endif // !NDEBUG
11074}
11075
11076void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11077 checkForCycles(DAG->getRoot().getNode(), DAG, force);
11078}

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/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")(static_cast<void> (0));
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")(static_cast<void> (0));
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")(static_cast<void> (0));
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")(static_cast<void> (0));
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")(static_cast<void> (0));
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,
8
Calling 'cast_convert_val::doit'
12
Returning from 'cast_convert_val::doit'
13
Returning pointer, which participates in a condition later
14
Returning pointer
225 typename simplify_type<SimpleFrom>::SimpleType>::doit(
226 simplify_type<From>::getSimplifiedValue(Val));
6
Assigning value
7
Passing value via 1st parameter 'Val'
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
9
'Res2' initialized here
234 = (typename cast_retty<To, FromTy>::ret_type)const_cast<FromTy&>(Val);
235 return Res2;
10
Returning pointer (loaded from 'Res2'), which participates in a condition later
11
Returning pointer (loaded from '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!")(static_cast<void> (0));
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!")(static_cast<void> (0));
263 return cast_convert_val<X, Y,
5
Calling 'cast_convert_val::doit'
15
Returning from 'cast_convert_val::doit'
16
Returning pointer, which participates in a condition later
17
Returning pointer
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!")(static_cast<void> (0));
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!")(static_cast<void> (0));
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!")(static_cast<void> (0));
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!")(static_cast<void> (0));
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!")(static_cast<void> (0));
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;
2
Assuming 'Val' is a 'ConstantSDNode'
3
'?' condition is true
4
Calling 'cast<llvm::ConstantSDNode, llvm::SDValue>'
18
Returning from 'cast<llvm::ConstantSDNode, llvm::SDValue>'
19
Returning pointer, which participates in a condition later
20
Returning pointer
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