[DAGCombiner] Eliminate dead stores to stack.
[llvm-complete.git] / lib / CodeGen / SelectionDAG / SelectionDAG.cpp
blob05f733b5676ed900f4630042958af09eaa6582e5
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.
11 //===----------------------------------------------------------------------===//
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/ValueTracking.h"
28 #include "llvm/CodeGen/ISDOpcodes.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineConstantPool.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineMemOperand.h"
34 #include "llvm/CodeGen/RuntimeLibcalls.h"
35 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
36 #include "llvm/CodeGen/SelectionDAGNodes.h"
37 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
38 #include "llvm/CodeGen/TargetLowering.h"
39 #include "llvm/CodeGen/TargetRegisterInfo.h"
40 #include "llvm/CodeGen/TargetSubtargetInfo.h"
41 #include "llvm/CodeGen/ValueTypes.h"
42 #include "llvm/IR/Constant.h"
43 #include "llvm/IR/Constants.h"
44 #include "llvm/IR/DataLayout.h"
45 #include "llvm/IR/DebugInfoMetadata.h"
46 #include "llvm/IR/DebugLoc.h"
47 #include "llvm/IR/DerivedTypes.h"
48 #include "llvm/IR/Function.h"
49 #include "llvm/IR/GlobalValue.h"
50 #include "llvm/IR/Metadata.h"
51 #include "llvm/IR/Type.h"
52 #include "llvm/IR/Value.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/CodeGen.h"
55 #include "llvm/Support/Compiler.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/KnownBits.h"
59 #include "llvm/Support/MachineValueType.h"
60 #include "llvm/Support/ManagedStatic.h"
61 #include "llvm/Support/MathExtras.h"
62 #include "llvm/Support/Mutex.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "llvm/Target/TargetMachine.h"
65 #include "llvm/Target/TargetOptions.h"
66 #include <algorithm>
67 #include <cassert>
68 #include <cstdint>
69 #include <cstdlib>
70 #include <limits>
71 #include <set>
72 #include <string>
73 #include <utility>
74 #include <vector>
76 using namespace llvm;
78 /// makeVTList - Return an instance of the SDVTList struct initialized with the
79 /// specified members.
80 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
81 SDVTList Res = {VTs, NumVTs};
82 return Res;
85 // Default null implementations of the callbacks.
86 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
87 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
89 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
91 #define DEBUG_TYPE "selectiondag"
93 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
94 cl::Hidden, cl::init(true),
95 cl::desc("Gang up loads and stores generated by inlining of memcpy"));
97 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
98 cl::desc("Number limit for gluing ld/st of memcpy."),
99 cl::Hidden, cl::init(0));
101 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
102 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
105 //===----------------------------------------------------------------------===//
106 // ConstantFPSDNode Class
107 //===----------------------------------------------------------------------===//
109 /// isExactlyValue - We don't rely on operator== working on double values, as
110 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
111 /// As such, this method can be used to do an exact bit-for-bit comparison of
112 /// two floating point values.
113 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
114 return getValueAPF().bitwiseIsEqual(V);
117 bool ConstantFPSDNode::isValueValidForType(EVT VT,
118 const APFloat& Val) {
119 assert(VT.isFloatingPoint() && "Can only convert between FP types");
121 // convert modifies in place, so make a copy.
122 APFloat Val2 = APFloat(Val);
123 bool losesInfo;
124 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
125 APFloat::rmNearestTiesToEven,
126 &losesInfo);
127 return !losesInfo;
130 //===----------------------------------------------------------------------===//
131 // ISD Namespace
132 //===----------------------------------------------------------------------===//
134 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
135 auto *BV = dyn_cast<BuildVectorSDNode>(N);
136 if (!BV)
137 return false;
139 APInt SplatUndef;
140 unsigned SplatBitSize;
141 bool HasUndefs;
142 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
143 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
144 EltSize) &&
145 EltSize == SplatBitSize;
148 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
149 // specializations of the more general isConstantSplatVector()?
151 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
152 // Look through a bit convert.
153 while (N->getOpcode() == ISD::BITCAST)
154 N = N->getOperand(0).getNode();
156 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
158 unsigned i = 0, e = N->getNumOperands();
160 // Skip over all of the undef values.
161 while (i != e && N->getOperand(i).isUndef())
162 ++i;
164 // Do not accept an all-undef vector.
165 if (i == e) return false;
167 // Do not accept build_vectors that aren't all constants or which have non-~0
168 // elements. We have to be a bit careful here, as the type of the constant
169 // may not be the same as the type of the vector elements due to type
170 // legalization (the elements are promoted to a legal type for the target and
171 // a vector of a type may be legal when the base element type is not).
172 // We only want to check enough bits to cover the vector elements, because
173 // we care if the resultant vector is all ones, not whether the individual
174 // constants are.
175 SDValue NotZero = N->getOperand(i);
176 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
177 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
178 if (CN->getAPIntValue().countTrailingOnes() < EltSize)
179 return false;
180 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
181 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
182 return false;
183 } else
184 return false;
186 // Okay, we have at least one ~0 value, check to see if the rest match or are
187 // undefs. Even with the above element type twiddling, this should be OK, as
188 // the same type legalization should have applied to all the elements.
189 for (++i; i != e; ++i)
190 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
191 return false;
192 return true;
195 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
196 // Look through a bit convert.
197 while (N->getOpcode() == ISD::BITCAST)
198 N = N->getOperand(0).getNode();
200 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
202 bool IsAllUndef = true;
203 for (const SDValue &Op : N->op_values()) {
204 if (Op.isUndef())
205 continue;
206 IsAllUndef = false;
207 // Do not accept build_vectors that aren't all constants or which have non-0
208 // elements. We have to be a bit careful here, as the type of the constant
209 // may not be the same as the type of the vector elements due to type
210 // legalization (the elements are promoted to a legal type for the target
211 // and a vector of a type may be legal when the base element type is not).
212 // We only want to check enough bits to cover the vector elements, because
213 // we care if the resultant vector is all zeros, not whether the individual
214 // constants are.
215 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
216 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
217 if (CN->getAPIntValue().countTrailingZeros() < EltSize)
218 return false;
219 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
220 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
221 return false;
222 } else
223 return false;
226 // Do not accept an all-undef vector.
227 if (IsAllUndef)
228 return false;
229 return true;
232 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
233 if (N->getOpcode() != ISD::BUILD_VECTOR)
234 return false;
236 for (const SDValue &Op : N->op_values()) {
237 if (Op.isUndef())
238 continue;
239 if (!isa<ConstantSDNode>(Op))
240 return false;
242 return true;
245 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
246 if (N->getOpcode() != ISD::BUILD_VECTOR)
247 return false;
249 for (const SDValue &Op : N->op_values()) {
250 if (Op.isUndef())
251 continue;
252 if (!isa<ConstantFPSDNode>(Op))
253 return false;
255 return true;
258 bool ISD::allOperandsUndef(const SDNode *N) {
259 // Return false if the node has no operands.
260 // This is "logically inconsistent" with the definition of "all" but
261 // is probably the desired behavior.
262 if (N->getNumOperands() == 0)
263 return false;
265 for (const SDValue &Op : N->op_values())
266 if (!Op.isUndef())
267 return false;
269 return true;
272 bool ISD::matchUnaryPredicate(SDValue Op,
273 std::function<bool(ConstantSDNode *)> Match,
274 bool AllowUndefs) {
275 // FIXME: Add support for scalar UNDEF cases?
276 if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
277 return Match(Cst);
279 // FIXME: Add support for vector UNDEF cases?
280 if (ISD::BUILD_VECTOR != Op.getOpcode())
281 return false;
283 EVT SVT = Op.getValueType().getScalarType();
284 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
285 if (AllowUndefs && Op.getOperand(i).isUndef()) {
286 if (!Match(nullptr))
287 return false;
288 continue;
291 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
292 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
293 return false;
295 return true;
298 bool ISD::matchBinaryPredicate(
299 SDValue LHS, SDValue RHS,
300 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
301 bool AllowUndefs) {
302 if (LHS.getValueType() != RHS.getValueType())
303 return false;
305 // TODO: Add support for scalar UNDEF cases?
306 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
307 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
308 return Match(LHSCst, RHSCst);
310 // TODO: Add support for vector UNDEF cases?
311 if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
312 ISD::BUILD_VECTOR != RHS.getOpcode())
313 return false;
315 EVT SVT = LHS.getValueType().getScalarType();
316 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
317 SDValue LHSOp = LHS.getOperand(i);
318 SDValue RHSOp = RHS.getOperand(i);
319 bool LHSUndef = AllowUndefs && LHSOp.isUndef();
320 bool RHSUndef = AllowUndefs && RHSOp.isUndef();
321 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
322 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
323 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
324 return false;
325 if (LHSOp.getValueType() != SVT ||
326 LHSOp.getValueType() != RHSOp.getValueType())
327 return false;
328 if (!Match(LHSCst, RHSCst))
329 return false;
331 return true;
334 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
335 switch (ExtType) {
336 case ISD::EXTLOAD:
337 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
338 case ISD::SEXTLOAD:
339 return ISD::SIGN_EXTEND;
340 case ISD::ZEXTLOAD:
341 return ISD::ZERO_EXTEND;
342 default:
343 break;
346 llvm_unreachable("Invalid LoadExtType");
349 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
350 // To perform this operation, we just need to swap the L and G bits of the
351 // operation.
352 unsigned OldL = (Operation >> 2) & 1;
353 unsigned OldG = (Operation >> 1) & 1;
354 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
355 (OldL << 1) | // New G bit
356 (OldG << 2)); // New L bit.
359 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
360 unsigned Operation = Op;
361 if (isInteger)
362 Operation ^= 7; // Flip L, G, E bits, but not U.
363 else
364 Operation ^= 15; // Flip all of the condition bits.
366 if (Operation > ISD::SETTRUE2)
367 Operation &= ~8; // Don't let N and U bits get set.
369 return ISD::CondCode(Operation);
372 /// For an integer comparison, return 1 if the comparison is a signed operation
373 /// and 2 if the result is an unsigned comparison. Return zero if the operation
374 /// does not depend on the sign of the input (setne and seteq).
375 static int isSignedOp(ISD::CondCode Opcode) {
376 switch (Opcode) {
377 default: llvm_unreachable("Illegal integer setcc operation!");
378 case ISD::SETEQ:
379 case ISD::SETNE: return 0;
380 case ISD::SETLT:
381 case ISD::SETLE:
382 case ISD::SETGT:
383 case ISD::SETGE: return 1;
384 case ISD::SETULT:
385 case ISD::SETULE:
386 case ISD::SETUGT:
387 case ISD::SETUGE: return 2;
391 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
392 bool IsInteger) {
393 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
394 // Cannot fold a signed integer setcc with an unsigned integer setcc.
395 return ISD::SETCC_INVALID;
397 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
399 // If the N and U bits get set, then the resultant comparison DOES suddenly
400 // care about orderedness, and it is true when ordered.
401 if (Op > ISD::SETTRUE2)
402 Op &= ~16; // Clear the U bit if the N bit is set.
404 // Canonicalize illegal integer setcc's.
405 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
406 Op = ISD::SETNE;
408 return ISD::CondCode(Op);
411 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
412 bool IsInteger) {
413 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
414 // Cannot fold a signed setcc with an unsigned setcc.
415 return ISD::SETCC_INVALID;
417 // Combine all of the condition bits.
418 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
420 // Canonicalize illegal integer setcc's.
421 if (IsInteger) {
422 switch (Result) {
423 default: break;
424 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
425 case ISD::SETOEQ: // SETEQ & SETU[LG]E
426 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
427 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
428 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
432 return Result;
435 //===----------------------------------------------------------------------===//
436 // SDNode Profile Support
437 //===----------------------------------------------------------------------===//
439 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
440 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
441 ID.AddInteger(OpC);
444 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
445 /// solely with their pointer.
446 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
447 ID.AddPointer(VTList.VTs);
450 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
451 static void AddNodeIDOperands(FoldingSetNodeID &ID,
452 ArrayRef<SDValue> Ops) {
453 for (auto& Op : Ops) {
454 ID.AddPointer(Op.getNode());
455 ID.AddInteger(Op.getResNo());
459 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
460 static void AddNodeIDOperands(FoldingSetNodeID &ID,
461 ArrayRef<SDUse> Ops) {
462 for (auto& Op : Ops) {
463 ID.AddPointer(Op.getNode());
464 ID.AddInteger(Op.getResNo());
468 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
469 SDVTList VTList, ArrayRef<SDValue> OpList) {
470 AddNodeIDOpcode(ID, OpC);
471 AddNodeIDValueTypes(ID, VTList);
472 AddNodeIDOperands(ID, OpList);
475 /// If this is an SDNode with special info, add this info to the NodeID data.
476 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
477 switch (N->getOpcode()) {
478 case ISD::TargetExternalSymbol:
479 case ISD::ExternalSymbol:
480 case ISD::MCSymbol:
481 llvm_unreachable("Should only be used on nodes with operands");
482 default: break; // Normal nodes don't need extra info.
483 case ISD::TargetConstant:
484 case ISD::Constant: {
485 const ConstantSDNode *C = cast<ConstantSDNode>(N);
486 ID.AddPointer(C->getConstantIntValue());
487 ID.AddBoolean(C->isOpaque());
488 break;
490 case ISD::TargetConstantFP:
491 case ISD::ConstantFP:
492 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
493 break;
494 case ISD::TargetGlobalAddress:
495 case ISD::GlobalAddress:
496 case ISD::TargetGlobalTLSAddress:
497 case ISD::GlobalTLSAddress: {
498 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
499 ID.AddPointer(GA->getGlobal());
500 ID.AddInteger(GA->getOffset());
501 ID.AddInteger(GA->getTargetFlags());
502 break;
504 case ISD::BasicBlock:
505 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
506 break;
507 case ISD::Register:
508 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
509 break;
510 case ISD::RegisterMask:
511 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
512 break;
513 case ISD::SRCVALUE:
514 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
515 break;
516 case ISD::FrameIndex:
517 case ISD::TargetFrameIndex:
518 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
519 break;
520 case ISD::JumpTable:
521 case ISD::TargetJumpTable:
522 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
523 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
524 break;
525 case ISD::ConstantPool:
526 case ISD::TargetConstantPool: {
527 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
528 ID.AddInteger(CP->getAlignment());
529 ID.AddInteger(CP->getOffset());
530 if (CP->isMachineConstantPoolEntry())
531 CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
532 else
533 ID.AddPointer(CP->getConstVal());
534 ID.AddInteger(CP->getTargetFlags());
535 break;
537 case ISD::TargetIndex: {
538 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
539 ID.AddInteger(TI->getIndex());
540 ID.AddInteger(TI->getOffset());
541 ID.AddInteger(TI->getTargetFlags());
542 break;
544 case ISD::LOAD: {
545 const LoadSDNode *LD = cast<LoadSDNode>(N);
546 ID.AddInteger(LD->getMemoryVT().getRawBits());
547 ID.AddInteger(LD->getRawSubclassData());
548 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
549 break;
551 case ISD::STORE: {
552 const StoreSDNode *ST = cast<StoreSDNode>(N);
553 ID.AddInteger(ST->getMemoryVT().getRawBits());
554 ID.AddInteger(ST->getRawSubclassData());
555 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
556 break;
558 case ISD::MLOAD: {
559 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
560 ID.AddInteger(MLD->getMemoryVT().getRawBits());
561 ID.AddInteger(MLD->getRawSubclassData());
562 ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
563 break;
565 case ISD::MSTORE: {
566 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
567 ID.AddInteger(MST->getMemoryVT().getRawBits());
568 ID.AddInteger(MST->getRawSubclassData());
569 ID.AddInteger(MST->getPointerInfo().getAddrSpace());
570 break;
572 case ISD::MGATHER: {
573 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
574 ID.AddInteger(MG->getMemoryVT().getRawBits());
575 ID.AddInteger(MG->getRawSubclassData());
576 ID.AddInteger(MG->getPointerInfo().getAddrSpace());
577 break;
579 case ISD::MSCATTER: {
580 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
581 ID.AddInteger(MS->getMemoryVT().getRawBits());
582 ID.AddInteger(MS->getRawSubclassData());
583 ID.AddInteger(MS->getPointerInfo().getAddrSpace());
584 break;
586 case ISD::ATOMIC_CMP_SWAP:
587 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
588 case ISD::ATOMIC_SWAP:
589 case ISD::ATOMIC_LOAD_ADD:
590 case ISD::ATOMIC_LOAD_SUB:
591 case ISD::ATOMIC_LOAD_AND:
592 case ISD::ATOMIC_LOAD_CLR:
593 case ISD::ATOMIC_LOAD_OR:
594 case ISD::ATOMIC_LOAD_XOR:
595 case ISD::ATOMIC_LOAD_NAND:
596 case ISD::ATOMIC_LOAD_MIN:
597 case ISD::ATOMIC_LOAD_MAX:
598 case ISD::ATOMIC_LOAD_UMIN:
599 case ISD::ATOMIC_LOAD_UMAX:
600 case ISD::ATOMIC_LOAD:
601 case ISD::ATOMIC_STORE: {
602 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
603 ID.AddInteger(AT->getMemoryVT().getRawBits());
604 ID.AddInteger(AT->getRawSubclassData());
605 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
606 break;
608 case ISD::PREFETCH: {
609 const MemSDNode *PF = cast<MemSDNode>(N);
610 ID.AddInteger(PF->getPointerInfo().getAddrSpace());
611 break;
613 case ISD::VECTOR_SHUFFLE: {
614 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
615 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
616 i != e; ++i)
617 ID.AddInteger(SVN->getMaskElt(i));
618 break;
620 case ISD::TargetBlockAddress:
621 case ISD::BlockAddress: {
622 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
623 ID.AddPointer(BA->getBlockAddress());
624 ID.AddInteger(BA->getOffset());
625 ID.AddInteger(BA->getTargetFlags());
626 break;
628 } // end switch (N->getOpcode())
630 // Target specific memory nodes could also have address spaces to check.
631 if (N->isTargetMemoryOpcode())
632 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
635 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
636 /// data.
637 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
638 AddNodeIDOpcode(ID, N->getOpcode());
639 // Add the return value info.
640 AddNodeIDValueTypes(ID, N->getVTList());
641 // Add the operand info.
642 AddNodeIDOperands(ID, N->ops());
644 // Handle SDNode leafs with special info.
645 AddNodeIDCustom(ID, N);
648 //===----------------------------------------------------------------------===//
649 // SelectionDAG Class
650 //===----------------------------------------------------------------------===//
652 /// doNotCSE - Return true if CSE should not be performed for this node.
653 static bool doNotCSE(SDNode *N) {
654 if (N->getValueType(0) == MVT::Glue)
655 return true; // Never CSE anything that produces a flag.
657 switch (N->getOpcode()) {
658 default: break;
659 case ISD::HANDLENODE:
660 case ISD::EH_LABEL:
661 return true; // Never CSE these nodes.
664 // Check that remaining values produced are not flags.
665 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
666 if (N->getValueType(i) == MVT::Glue)
667 return true; // Never CSE anything that produces a flag.
669 return false;
672 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
673 /// SelectionDAG.
674 void SelectionDAG::RemoveDeadNodes() {
675 // Create a dummy node (which is not added to allnodes), that adds a reference
676 // to the root node, preventing it from being deleted.
677 HandleSDNode Dummy(getRoot());
679 SmallVector<SDNode*, 128> DeadNodes;
681 // Add all obviously-dead nodes to the DeadNodes worklist.
682 for (SDNode &Node : allnodes())
683 if (Node.use_empty())
684 DeadNodes.push_back(&Node);
686 RemoveDeadNodes(DeadNodes);
688 // If the root changed (e.g. it was a dead load, update the root).
689 setRoot(Dummy.getValue());
692 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
693 /// given list, and any nodes that become unreachable as a result.
694 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
696 // Process the worklist, deleting the nodes and adding their uses to the
697 // worklist.
698 while (!DeadNodes.empty()) {
699 SDNode *N = DeadNodes.pop_back_val();
700 // Skip to next node if we've already managed to delete the node. This could
701 // happen if replacing a node causes a node previously added to the node to
702 // be deleted.
703 if (N->getOpcode() == ISD::DELETED_NODE)
704 continue;
706 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
707 DUL->NodeDeleted(N, nullptr);
709 // Take the node out of the appropriate CSE map.
710 RemoveNodeFromCSEMaps(N);
712 // Next, brutally remove the operand list. This is safe to do, as there are
713 // no cycles in the graph.
714 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
715 SDUse &Use = *I++;
716 SDNode *Operand = Use.getNode();
717 Use.set(SDValue());
719 // Now that we removed this operand, see if there are no uses of it left.
720 if (Operand->use_empty())
721 DeadNodes.push_back(Operand);
724 DeallocateNode(N);
728 void SelectionDAG::RemoveDeadNode(SDNode *N){
729 SmallVector<SDNode*, 16> DeadNodes(1, N);
731 // Create a dummy node that adds a reference to the root node, preventing
732 // it from being deleted. (This matters if the root is an operand of the
733 // dead node.)
734 HandleSDNode Dummy(getRoot());
736 RemoveDeadNodes(DeadNodes);
739 void SelectionDAG::DeleteNode(SDNode *N) {
740 // First take this out of the appropriate CSE map.
741 RemoveNodeFromCSEMaps(N);
743 // Finally, remove uses due to operands of this node, remove from the
744 // AllNodes list, and delete the node.
745 DeleteNodeNotInCSEMaps(N);
748 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
749 assert(N->getIterator() != AllNodes.begin() &&
750 "Cannot delete the entry node!");
751 assert(N->use_empty() && "Cannot delete a node that is not dead!");
753 // Drop all of the operands and decrement used node's use counts.
754 N->DropOperands();
756 DeallocateNode(N);
759 void SDDbgInfo::erase(const SDNode *Node) {
760 DbgValMapType::iterator I = DbgValMap.find(Node);
761 if (I == DbgValMap.end())
762 return;
763 for (auto &Val: I->second)
764 Val->setIsInvalidated();
765 DbgValMap.erase(I);
768 void SelectionDAG::DeallocateNode(SDNode *N) {
769 // If we have operands, deallocate them.
770 removeOperands(N);
772 NodeAllocator.Deallocate(AllNodes.remove(N));
774 // Set the opcode to DELETED_NODE to help catch bugs when node
775 // memory is reallocated.
776 // FIXME: There are places in SDag that have grown a dependency on the opcode
777 // value in the released node.
778 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
779 N->NodeType = ISD::DELETED_NODE;
781 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
782 // them and forget about that node.
783 DbgInfo->erase(N);
786 #ifndef NDEBUG
787 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
788 static void VerifySDNode(SDNode *N) {
789 switch (N->getOpcode()) {
790 default:
791 break;
792 case ISD::BUILD_PAIR: {
793 EVT VT = N->getValueType(0);
794 assert(N->getNumValues() == 1 && "Too many results!");
795 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
796 "Wrong return type!");
797 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
798 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
799 "Mismatched operand types!");
800 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
801 "Wrong operand type!");
802 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
803 "Wrong return type size");
804 break;
806 case ISD::BUILD_VECTOR: {
807 assert(N->getNumValues() == 1 && "Too many results!");
808 assert(N->getValueType(0).isVector() && "Wrong return type!");
809 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
810 "Wrong number of operands!");
811 EVT EltVT = N->getValueType(0).getVectorElementType();
812 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
813 assert((I->getValueType() == EltVT ||
814 (EltVT.isInteger() && I->getValueType().isInteger() &&
815 EltVT.bitsLE(I->getValueType()))) &&
816 "Wrong operand type!");
817 assert(I->getValueType() == N->getOperand(0).getValueType() &&
818 "Operands must all have the same type");
820 break;
824 #endif // NDEBUG
826 /// Insert a newly allocated node into the DAG.
828 /// Handles insertion into the all nodes list and CSE map, as well as
829 /// verification and other common operations when a new node is allocated.
830 void SelectionDAG::InsertNode(SDNode *N) {
831 AllNodes.push_back(N);
832 #ifndef NDEBUG
833 N->PersistentId = NextPersistentId++;
834 VerifySDNode(N);
835 #endif
838 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
839 /// correspond to it. This is useful when we're about to delete or repurpose
840 /// the node. We don't want future request for structurally identical nodes
841 /// to return N anymore.
842 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
843 bool Erased = false;
844 switch (N->getOpcode()) {
845 case ISD::HANDLENODE: return false; // noop.
846 case ISD::CONDCODE:
847 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
848 "Cond code doesn't exist!");
849 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
850 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
851 break;
852 case ISD::ExternalSymbol:
853 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
854 break;
855 case ISD::TargetExternalSymbol: {
856 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
857 Erased = TargetExternalSymbols.erase(
858 std::pair<std::string,unsigned char>(ESN->getSymbol(),
859 ESN->getTargetFlags()));
860 break;
862 case ISD::MCSymbol: {
863 auto *MCSN = cast<MCSymbolSDNode>(N);
864 Erased = MCSymbols.erase(MCSN->getMCSymbol());
865 break;
867 case ISD::VALUETYPE: {
868 EVT VT = cast<VTSDNode>(N)->getVT();
869 if (VT.isExtended()) {
870 Erased = ExtendedValueTypeNodes.erase(VT);
871 } else {
872 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
873 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
875 break;
877 default:
878 // Remove it from the CSE Map.
879 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
880 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
881 Erased = CSEMap.RemoveNode(N);
882 break;
884 #ifndef NDEBUG
885 // Verify that the node was actually in one of the CSE maps, unless it has a
886 // flag result (which cannot be CSE'd) or is one of the special cases that are
887 // not subject to CSE.
888 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
889 !N->isMachineOpcode() && !doNotCSE(N)) {
890 N->dump(this);
891 dbgs() << "\n";
892 llvm_unreachable("Node is not in map!");
894 #endif
895 return Erased;
898 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
899 /// maps and modified in place. Add it back to the CSE maps, unless an identical
900 /// node already exists, in which case transfer all its users to the existing
901 /// node. This transfer can potentially trigger recursive merging.
902 void
903 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
904 // For node types that aren't CSE'd, just act as if no identical node
905 // already exists.
906 if (!doNotCSE(N)) {
907 SDNode *Existing = CSEMap.GetOrInsertNode(N);
908 if (Existing != N) {
909 // If there was already an existing matching node, use ReplaceAllUsesWith
910 // to replace the dead one with the existing one. This can cause
911 // recursive merging of other unrelated nodes down the line.
912 ReplaceAllUsesWith(N, Existing);
914 // N is now dead. Inform the listeners and delete it.
915 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
916 DUL->NodeDeleted(N, Existing);
917 DeleteNodeNotInCSEMaps(N);
918 return;
922 // If the node doesn't already exist, we updated it. Inform listeners.
923 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
924 DUL->NodeUpdated(N);
927 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
928 /// were replaced with those specified. If this node is never memoized,
929 /// return null, otherwise return a pointer to the slot it would take. If a
930 /// node already exists with these operands, the slot will be non-null.
931 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
932 void *&InsertPos) {
933 if (doNotCSE(N))
934 return nullptr;
936 SDValue Ops[] = { Op };
937 FoldingSetNodeID ID;
938 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
939 AddNodeIDCustom(ID, N);
940 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
941 if (Node)
942 Node->intersectFlagsWith(N->getFlags());
943 return Node;
946 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
947 /// were replaced with those specified. If this node is never memoized,
948 /// return null, otherwise return a pointer to the slot it would take. If a
949 /// node already exists with these operands, the slot will be non-null.
950 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
951 SDValue Op1, SDValue Op2,
952 void *&InsertPos) {
953 if (doNotCSE(N))
954 return nullptr;
956 SDValue Ops[] = { Op1, Op2 };
957 FoldingSetNodeID ID;
958 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
959 AddNodeIDCustom(ID, N);
960 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
961 if (Node)
962 Node->intersectFlagsWith(N->getFlags());
963 return Node;
966 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
967 /// were replaced with those specified. If this node is never memoized,
968 /// return null, otherwise return a pointer to the slot it would take. If a
969 /// node already exists with these operands, the slot will be non-null.
970 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
971 void *&InsertPos) {
972 if (doNotCSE(N))
973 return nullptr;
975 FoldingSetNodeID ID;
976 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
977 AddNodeIDCustom(ID, N);
978 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
979 if (Node)
980 Node->intersectFlagsWith(N->getFlags());
981 return Node;
984 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
985 Type *Ty = VT == MVT::iPTR ?
986 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
987 VT.getTypeForEVT(*getContext());
989 return getDataLayout().getABITypeAlignment(Ty);
992 // EntryNode could meaningfully have debug info if we can find it...
993 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
994 : TM(tm), OptLevel(OL),
995 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
996 Root(getEntryNode()) {
997 InsertNode(&EntryNode);
998 DbgInfo = new SDDbgInfo();
1001 void SelectionDAG::init(MachineFunction &NewMF,
1002 OptimizationRemarkEmitter &NewORE,
1003 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1004 LegacyDivergenceAnalysis * Divergence) {
1005 MF = &NewMF;
1006 SDAGISelPass = PassPtr;
1007 ORE = &NewORE;
1008 TLI = getSubtarget().getTargetLowering();
1009 TSI = getSubtarget().getSelectionDAGInfo();
1010 LibInfo = LibraryInfo;
1011 Context = &MF->getFunction().getContext();
1012 DA = Divergence;
1015 SelectionDAG::~SelectionDAG() {
1016 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1017 allnodes_clear();
1018 OperandRecycler.clear(OperandAllocator);
1019 delete DbgInfo;
1022 void SelectionDAG::allnodes_clear() {
1023 assert(&*AllNodes.begin() == &EntryNode);
1024 AllNodes.remove(AllNodes.begin());
1025 while (!AllNodes.empty())
1026 DeallocateNode(&AllNodes.front());
1027 #ifndef NDEBUG
1028 NextPersistentId = 0;
1029 #endif
1032 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1033 void *&InsertPos) {
1034 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1035 if (N) {
1036 switch (N->getOpcode()) {
1037 default: break;
1038 case ISD::Constant:
1039 case ISD::ConstantFP:
1040 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1041 "debug location. Use another overload.");
1044 return N;
1047 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1048 const SDLoc &DL, void *&InsertPos) {
1049 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1050 if (N) {
1051 switch (N->getOpcode()) {
1052 case ISD::Constant:
1053 case ISD::ConstantFP:
1054 // Erase debug location from the node if the node is used at several
1055 // different places. Do not propagate one location to all uses as it
1056 // will cause a worse single stepping debugging experience.
1057 if (N->getDebugLoc() != DL.getDebugLoc())
1058 N->setDebugLoc(DebugLoc());
1059 break;
1060 default:
1061 // When the node's point of use is located earlier in the instruction
1062 // sequence than its prior point of use, update its debug info to the
1063 // earlier location.
1064 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1065 N->setDebugLoc(DL.getDebugLoc());
1066 break;
1069 return N;
1072 void SelectionDAG::clear() {
1073 allnodes_clear();
1074 OperandRecycler.clear(OperandAllocator);
1075 OperandAllocator.Reset();
1076 CSEMap.clear();
1078 ExtendedValueTypeNodes.clear();
1079 ExternalSymbols.clear();
1080 TargetExternalSymbols.clear();
1081 MCSymbols.clear();
1082 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1083 static_cast<CondCodeSDNode*>(nullptr));
1084 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1085 static_cast<SDNode*>(nullptr));
1087 EntryNode.UseList = nullptr;
1088 InsertNode(&EntryNode);
1089 Root = getEntryNode();
1090 DbgInfo->clear();
1093 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1094 return VT.bitsGT(Op.getValueType())
1095 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1096 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1099 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1100 return VT.bitsGT(Op.getValueType()) ?
1101 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1102 getNode(ISD::TRUNCATE, DL, VT, Op);
1105 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1106 return VT.bitsGT(Op.getValueType()) ?
1107 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1108 getNode(ISD::TRUNCATE, DL, VT, Op);
1111 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1112 return VT.bitsGT(Op.getValueType()) ?
1113 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1114 getNode(ISD::TRUNCATE, DL, VT, Op);
1117 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1118 EVT OpVT) {
1119 if (VT.bitsLE(Op.getValueType()))
1120 return getNode(ISD::TRUNCATE, SL, VT, Op);
1122 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1123 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1126 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1127 assert(!VT.isVector() &&
1128 "getZeroExtendInReg should use the vector element type instead of "
1129 "the vector type!");
1130 if (Op.getValueType().getScalarType() == VT) return Op;
1131 unsigned BitWidth = Op.getScalarValueSizeInBits();
1132 APInt Imm = APInt::getLowBitsSet(BitWidth,
1133 VT.getSizeInBits());
1134 return getNode(ISD::AND, DL, Op.getValueType(), Op,
1135 getConstant(Imm, DL, Op.getValueType()));
1138 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1139 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1140 EVT EltVT = VT.getScalarType();
1141 SDValue NegOne =
1142 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1143 return getNode(ISD::XOR, DL, VT, Val, NegOne);
1146 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1147 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1148 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1151 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1152 EVT OpVT) {
1153 if (!V)
1154 return getConstant(0, DL, VT);
1156 switch (TLI->getBooleanContents(OpVT)) {
1157 case TargetLowering::ZeroOrOneBooleanContent:
1158 case TargetLowering::UndefinedBooleanContent:
1159 return getConstant(1, DL, VT);
1160 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1161 return getAllOnesConstant(DL, VT);
1163 llvm_unreachable("Unexpected boolean content enum!");
1166 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1167 bool isT, bool isO) {
1168 EVT EltVT = VT.getScalarType();
1169 assert((EltVT.getSizeInBits() >= 64 ||
1170 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1171 "getConstant with a uint64_t value that doesn't fit in the type!");
1172 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1175 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1176 bool isT, bool isO) {
1177 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1180 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1181 EVT VT, bool isT, bool isO) {
1182 assert(VT.isInteger() && "Cannot create FP integer constant!");
1184 EVT EltVT = VT.getScalarType();
1185 const ConstantInt *Elt = &Val;
1187 // In some cases the vector type is legal but the element type is illegal and
1188 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1189 // inserted value (the type does not need to match the vector element type).
1190 // Any extra bits introduced will be truncated away.
1191 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1192 TargetLowering::TypePromoteInteger) {
1193 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1194 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1195 Elt = ConstantInt::get(*getContext(), NewVal);
1197 // In other cases the element type is illegal and needs to be expanded, for
1198 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1199 // the value into n parts and use a vector type with n-times the elements.
1200 // Then bitcast to the type requested.
1201 // Legalizing constants too early makes the DAGCombiner's job harder so we
1202 // only legalize if the DAG tells us we must produce legal types.
1203 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1204 TLI->getTypeAction(*getContext(), EltVT) ==
1205 TargetLowering::TypeExpandInteger) {
1206 const APInt &NewVal = Elt->getValue();
1207 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1208 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1209 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1210 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1212 // Check the temporary vector is the correct size. If this fails then
1213 // getTypeToTransformTo() probably returned a type whose size (in bits)
1214 // isn't a power-of-2 factor of the requested type size.
1215 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1217 SmallVector<SDValue, 2> EltParts;
1218 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1219 EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
1220 .zextOrTrunc(ViaEltSizeInBits), DL,
1221 ViaEltVT, isT, isO));
1224 // EltParts is currently in little endian order. If we actually want
1225 // big-endian order then reverse it now.
1226 if (getDataLayout().isBigEndian())
1227 std::reverse(EltParts.begin(), EltParts.end());
1229 // The elements must be reversed when the element order is different
1230 // to the endianness of the elements (because the BITCAST is itself a
1231 // vector shuffle in this situation). However, we do not need any code to
1232 // perform this reversal because getConstant() is producing a vector
1233 // splat.
1234 // This situation occurs in MIPS MSA.
1236 SmallVector<SDValue, 8> Ops;
1237 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1238 Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
1240 SDValue V = getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1241 return V;
1244 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1245 "APInt size does not match type size!");
1246 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1247 FoldingSetNodeID ID;
1248 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1249 ID.AddPointer(Elt);
1250 ID.AddBoolean(isO);
1251 void *IP = nullptr;
1252 SDNode *N = nullptr;
1253 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1254 if (!VT.isVector())
1255 return SDValue(N, 0);
1257 if (!N) {
1258 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1259 CSEMap.InsertNode(N, IP);
1260 InsertNode(N);
1261 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1264 SDValue Result(N, 0);
1265 if (VT.isVector())
1266 Result = getSplatBuildVector(VT, DL, Result);
1268 return Result;
1271 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1272 bool isTarget) {
1273 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1276 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1277 bool isTarget) {
1278 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1281 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1282 EVT VT, bool isTarget) {
1283 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1285 EVT EltVT = VT.getScalarType();
1287 // Do the map lookup using the actual bit pattern for the floating point
1288 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1289 // we don't have issues with SNANs.
1290 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1291 FoldingSetNodeID ID;
1292 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1293 ID.AddPointer(&V);
1294 void *IP = nullptr;
1295 SDNode *N = nullptr;
1296 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1297 if (!VT.isVector())
1298 return SDValue(N, 0);
1300 if (!N) {
1301 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1302 CSEMap.InsertNode(N, IP);
1303 InsertNode(N);
1306 SDValue Result(N, 0);
1307 if (VT.isVector())
1308 Result = getSplatBuildVector(VT, DL, Result);
1309 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1310 return Result;
1313 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1314 bool isTarget) {
1315 EVT EltVT = VT.getScalarType();
1316 if (EltVT == MVT::f32)
1317 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1318 else if (EltVT == MVT::f64)
1319 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1320 else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1321 EltVT == MVT::f16) {
1322 bool Ignored;
1323 APFloat APF = APFloat(Val);
1324 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1325 &Ignored);
1326 return getConstantFP(APF, DL, VT, isTarget);
1327 } else
1328 llvm_unreachable("Unsupported type in getConstantFP");
1331 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1332 EVT VT, int64_t Offset, bool isTargetGA,
1333 unsigned char TargetFlags) {
1334 assert((TargetFlags == 0 || isTargetGA) &&
1335 "Cannot set target flags on target-independent globals");
1337 // Truncate (with sign-extension) the offset value to the pointer size.
1338 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1339 if (BitWidth < 64)
1340 Offset = SignExtend64(Offset, BitWidth);
1342 unsigned Opc;
1343 if (GV->isThreadLocal())
1344 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1345 else
1346 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1348 FoldingSetNodeID ID;
1349 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1350 ID.AddPointer(GV);
1351 ID.AddInteger(Offset);
1352 ID.AddInteger(TargetFlags);
1353 void *IP = nullptr;
1354 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1355 return SDValue(E, 0);
1357 auto *N = newSDNode<GlobalAddressSDNode>(
1358 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1359 CSEMap.InsertNode(N, IP);
1360 InsertNode(N);
1361 return SDValue(N, 0);
1364 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1365 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1366 FoldingSetNodeID ID;
1367 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1368 ID.AddInteger(FI);
1369 void *IP = nullptr;
1370 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1371 return SDValue(E, 0);
1373 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1374 CSEMap.InsertNode(N, IP);
1375 InsertNode(N);
1376 return SDValue(N, 0);
1379 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1380 unsigned char TargetFlags) {
1381 assert((TargetFlags == 0 || isTarget) &&
1382 "Cannot set target flags on target-independent jump tables");
1383 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1384 FoldingSetNodeID ID;
1385 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1386 ID.AddInteger(JTI);
1387 ID.AddInteger(TargetFlags);
1388 void *IP = nullptr;
1389 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1390 return SDValue(E, 0);
1392 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1393 CSEMap.InsertNode(N, IP);
1394 InsertNode(N);
1395 return SDValue(N, 0);
1398 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1399 unsigned Alignment, int Offset,
1400 bool isTarget,
1401 unsigned char TargetFlags) {
1402 assert((TargetFlags == 0 || isTarget) &&
1403 "Cannot set target flags on target-independent globals");
1404 if (Alignment == 0)
1405 Alignment = MF->getFunction().optForSize()
1406 ? getDataLayout().getABITypeAlignment(C->getType())
1407 : getDataLayout().getPrefTypeAlignment(C->getType());
1408 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1409 FoldingSetNodeID ID;
1410 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1411 ID.AddInteger(Alignment);
1412 ID.AddInteger(Offset);
1413 ID.AddPointer(C);
1414 ID.AddInteger(TargetFlags);
1415 void *IP = nullptr;
1416 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1417 return SDValue(E, 0);
1419 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1420 TargetFlags);
1421 CSEMap.InsertNode(N, IP);
1422 InsertNode(N);
1423 return SDValue(N, 0);
1426 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1427 unsigned Alignment, int Offset,
1428 bool isTarget,
1429 unsigned char TargetFlags) {
1430 assert((TargetFlags == 0 || isTarget) &&
1431 "Cannot set target flags on target-independent globals");
1432 if (Alignment == 0)
1433 Alignment = getDataLayout().getPrefTypeAlignment(C->getType());
1434 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1435 FoldingSetNodeID ID;
1436 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1437 ID.AddInteger(Alignment);
1438 ID.AddInteger(Offset);
1439 C->addSelectionDAGCSEId(ID);
1440 ID.AddInteger(TargetFlags);
1441 void *IP = nullptr;
1442 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1443 return SDValue(E, 0);
1445 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1446 TargetFlags);
1447 CSEMap.InsertNode(N, IP);
1448 InsertNode(N);
1449 return SDValue(N, 0);
1452 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1453 unsigned char TargetFlags) {
1454 FoldingSetNodeID ID;
1455 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1456 ID.AddInteger(Index);
1457 ID.AddInteger(Offset);
1458 ID.AddInteger(TargetFlags);
1459 void *IP = nullptr;
1460 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1461 return SDValue(E, 0);
1463 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1464 CSEMap.InsertNode(N, IP);
1465 InsertNode(N);
1466 return SDValue(N, 0);
1469 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1470 FoldingSetNodeID ID;
1471 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1472 ID.AddPointer(MBB);
1473 void *IP = nullptr;
1474 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1475 return SDValue(E, 0);
1477 auto *N = newSDNode<BasicBlockSDNode>(MBB);
1478 CSEMap.InsertNode(N, IP);
1479 InsertNode(N);
1480 return SDValue(N, 0);
1483 SDValue SelectionDAG::getValueType(EVT VT) {
1484 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1485 ValueTypeNodes.size())
1486 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1488 SDNode *&N = VT.isExtended() ?
1489 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1491 if (N) return SDValue(N, 0);
1492 N = newSDNode<VTSDNode>(VT);
1493 InsertNode(N);
1494 return SDValue(N, 0);
1497 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1498 SDNode *&N = ExternalSymbols[Sym];
1499 if (N) return SDValue(N, 0);
1500 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1501 InsertNode(N);
1502 return SDValue(N, 0);
1505 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1506 SDNode *&N = MCSymbols[Sym];
1507 if (N)
1508 return SDValue(N, 0);
1509 N = newSDNode<MCSymbolSDNode>(Sym, VT);
1510 InsertNode(N);
1511 return SDValue(N, 0);
1514 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1515 unsigned char TargetFlags) {
1516 SDNode *&N =
1517 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1518 TargetFlags)];
1519 if (N) return SDValue(N, 0);
1520 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1521 InsertNode(N);
1522 return SDValue(N, 0);
1525 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1526 if ((unsigned)Cond >= CondCodeNodes.size())
1527 CondCodeNodes.resize(Cond+1);
1529 if (!CondCodeNodes[Cond]) {
1530 auto *N = newSDNode<CondCodeSDNode>(Cond);
1531 CondCodeNodes[Cond] = N;
1532 InsertNode(N);
1535 return SDValue(CondCodeNodes[Cond], 0);
1538 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1539 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1540 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1541 std::swap(N1, N2);
1542 ShuffleVectorSDNode::commuteMask(M);
1545 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1546 SDValue N2, ArrayRef<int> Mask) {
1547 assert(VT.getVectorNumElements() == Mask.size() &&
1548 "Must have the same number of vector elements as mask elements!");
1549 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1550 "Invalid VECTOR_SHUFFLE");
1552 // Canonicalize shuffle undef, undef -> undef
1553 if (N1.isUndef() && N2.isUndef())
1554 return getUNDEF(VT);
1556 // Validate that all indices in Mask are within the range of the elements
1557 // input to the shuffle.
1558 int NElts = Mask.size();
1559 assert(llvm::all_of(Mask,
1560 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1561 "Index out of range");
1563 // Copy the mask so we can do any needed cleanup.
1564 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1566 // Canonicalize shuffle v, v -> v, undef
1567 if (N1 == N2) {
1568 N2 = getUNDEF(VT);
1569 for (int i = 0; i != NElts; ++i)
1570 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1573 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1574 if (N1.isUndef())
1575 commuteShuffle(N1, N2, MaskVec);
1577 if (TLI->hasVectorBlend()) {
1578 // If shuffling a splat, try to blend the splat instead. We do this here so
1579 // that even when this arises during lowering we don't have to re-handle it.
1580 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1581 BitVector UndefElements;
1582 SDValue Splat = BV->getSplatValue(&UndefElements);
1583 if (!Splat)
1584 return;
1586 for (int i = 0; i < NElts; ++i) {
1587 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1588 continue;
1590 // If this input comes from undef, mark it as such.
1591 if (UndefElements[MaskVec[i] - Offset]) {
1592 MaskVec[i] = -1;
1593 continue;
1596 // If we can blend a non-undef lane, use that instead.
1597 if (!UndefElements[i])
1598 MaskVec[i] = i + Offset;
1601 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1602 BlendSplat(N1BV, 0);
1603 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1604 BlendSplat(N2BV, NElts);
1607 // Canonicalize all index into lhs, -> shuffle lhs, undef
1608 // Canonicalize all index into rhs, -> shuffle rhs, undef
1609 bool AllLHS = true, AllRHS = true;
1610 bool N2Undef = N2.isUndef();
1611 for (int i = 0; i != NElts; ++i) {
1612 if (MaskVec[i] >= NElts) {
1613 if (N2Undef)
1614 MaskVec[i] = -1;
1615 else
1616 AllLHS = false;
1617 } else if (MaskVec[i] >= 0) {
1618 AllRHS = false;
1621 if (AllLHS && AllRHS)
1622 return getUNDEF(VT);
1623 if (AllLHS && !N2Undef)
1624 N2 = getUNDEF(VT);
1625 if (AllRHS) {
1626 N1 = getUNDEF(VT);
1627 commuteShuffle(N1, N2, MaskVec);
1629 // Reset our undef status after accounting for the mask.
1630 N2Undef = N2.isUndef();
1631 // Re-check whether both sides ended up undef.
1632 if (N1.isUndef() && N2Undef)
1633 return getUNDEF(VT);
1635 // If Identity shuffle return that node.
1636 bool Identity = true, AllSame = true;
1637 for (int i = 0; i != NElts; ++i) {
1638 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1639 if (MaskVec[i] != MaskVec[0]) AllSame = false;
1641 if (Identity && NElts)
1642 return N1;
1644 // Shuffling a constant splat doesn't change the result.
1645 if (N2Undef) {
1646 SDValue V = N1;
1648 // Look through any bitcasts. We check that these don't change the number
1649 // (and size) of elements and just changes their types.
1650 while (V.getOpcode() == ISD::BITCAST)
1651 V = V->getOperand(0);
1653 // A splat should always show up as a build vector node.
1654 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1655 BitVector UndefElements;
1656 SDValue Splat = BV->getSplatValue(&UndefElements);
1657 // If this is a splat of an undef, shuffling it is also undef.
1658 if (Splat && Splat.isUndef())
1659 return getUNDEF(VT);
1661 bool SameNumElts =
1662 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1664 // We only have a splat which can skip shuffles if there is a splatted
1665 // value and no undef lanes rearranged by the shuffle.
1666 if (Splat && UndefElements.none()) {
1667 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1668 // number of elements match or the value splatted is a zero constant.
1669 if (SameNumElts)
1670 return N1;
1671 if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1672 if (C->isNullValue())
1673 return N1;
1676 // If the shuffle itself creates a splat, build the vector directly.
1677 if (AllSame && SameNumElts) {
1678 EVT BuildVT = BV->getValueType(0);
1679 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1680 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1682 // We may have jumped through bitcasts, so the type of the
1683 // BUILD_VECTOR may not match the type of the shuffle.
1684 if (BuildVT != VT)
1685 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1686 return NewBV;
1691 FoldingSetNodeID ID;
1692 SDValue Ops[2] = { N1, N2 };
1693 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1694 for (int i = 0; i != NElts; ++i)
1695 ID.AddInteger(MaskVec[i]);
1697 void* IP = nullptr;
1698 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1699 return SDValue(E, 0);
1701 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1702 // SDNode doesn't have access to it. This memory will be "leaked" when
1703 // the node is deallocated, but recovered when the NodeAllocator is released.
1704 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1705 llvm::copy(MaskVec, MaskAlloc);
1707 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1708 dl.getDebugLoc(), MaskAlloc);
1709 createOperands(N, Ops);
1711 CSEMap.InsertNode(N, IP);
1712 InsertNode(N);
1713 SDValue V = SDValue(N, 0);
1714 NewSDValueDbgMsg(V, "Creating new node: ", this);
1715 return V;
1718 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1719 EVT VT = SV.getValueType(0);
1720 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1721 ShuffleVectorSDNode::commuteMask(MaskVec);
1723 SDValue Op0 = SV.getOperand(0);
1724 SDValue Op1 = SV.getOperand(1);
1725 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1728 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1729 FoldingSetNodeID ID;
1730 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1731 ID.AddInteger(RegNo);
1732 void *IP = nullptr;
1733 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1734 return SDValue(E, 0);
1736 auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1737 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
1738 CSEMap.InsertNode(N, IP);
1739 InsertNode(N);
1740 return SDValue(N, 0);
1743 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1744 FoldingSetNodeID ID;
1745 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1746 ID.AddPointer(RegMask);
1747 void *IP = nullptr;
1748 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1749 return SDValue(E, 0);
1751 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1752 CSEMap.InsertNode(N, IP);
1753 InsertNode(N);
1754 return SDValue(N, 0);
1757 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1758 MCSymbol *Label) {
1759 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
1762 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
1763 SDValue Root, MCSymbol *Label) {
1764 FoldingSetNodeID ID;
1765 SDValue Ops[] = { Root };
1766 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
1767 ID.AddPointer(Label);
1768 void *IP = nullptr;
1769 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1770 return SDValue(E, 0);
1772 auto *N = newSDNode<LabelSDNode>(dl.getIROrder(), dl.getDebugLoc(), Label);
1773 createOperands(N, Ops);
1775 CSEMap.InsertNode(N, IP);
1776 InsertNode(N);
1777 return SDValue(N, 0);
1780 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1781 int64_t Offset,
1782 bool isTarget,
1783 unsigned char TargetFlags) {
1784 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1786 FoldingSetNodeID ID;
1787 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1788 ID.AddPointer(BA);
1789 ID.AddInteger(Offset);
1790 ID.AddInteger(TargetFlags);
1791 void *IP = nullptr;
1792 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1793 return SDValue(E, 0);
1795 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
1796 CSEMap.InsertNode(N, IP);
1797 InsertNode(N);
1798 return SDValue(N, 0);
1801 SDValue SelectionDAG::getSrcValue(const Value *V) {
1802 assert((!V || V->getType()->isPointerTy()) &&
1803 "SrcValue is not a pointer?");
1805 FoldingSetNodeID ID;
1806 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
1807 ID.AddPointer(V);
1809 void *IP = nullptr;
1810 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1811 return SDValue(E, 0);
1813 auto *N = newSDNode<SrcValueSDNode>(V);
1814 CSEMap.InsertNode(N, IP);
1815 InsertNode(N);
1816 return SDValue(N, 0);
1819 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1820 FoldingSetNodeID ID;
1821 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
1822 ID.AddPointer(MD);
1824 void *IP = nullptr;
1825 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1826 return SDValue(E, 0);
1828 auto *N = newSDNode<MDNodeSDNode>(MD);
1829 CSEMap.InsertNode(N, IP);
1830 InsertNode(N);
1831 return SDValue(N, 0);
1834 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
1835 if (VT == V.getValueType())
1836 return V;
1838 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
1841 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
1842 unsigned SrcAS, unsigned DestAS) {
1843 SDValue Ops[] = {Ptr};
1844 FoldingSetNodeID ID;
1845 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
1846 ID.AddInteger(SrcAS);
1847 ID.AddInteger(DestAS);
1849 void *IP = nullptr;
1850 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1851 return SDValue(E, 0);
1853 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
1854 VT, SrcAS, DestAS);
1855 createOperands(N, Ops);
1857 CSEMap.InsertNode(N, IP);
1858 InsertNode(N);
1859 return SDValue(N, 0);
1862 /// getShiftAmountOperand - Return the specified value casted to
1863 /// the target's desired shift amount type.
1864 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1865 EVT OpTy = Op.getValueType();
1866 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
1867 if (OpTy == ShTy || OpTy.isVector()) return Op;
1869 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
1872 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
1873 SDLoc dl(Node);
1874 const TargetLowering &TLI = getTargetLoweringInfo();
1875 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1876 EVT VT = Node->getValueType(0);
1877 SDValue Tmp1 = Node->getOperand(0);
1878 SDValue Tmp2 = Node->getOperand(1);
1879 unsigned Align = Node->getConstantOperandVal(3);
1881 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
1882 Tmp2, MachinePointerInfo(V));
1883 SDValue VAList = VAListLoad;
1885 if (Align > TLI.getMinStackArgumentAlignment()) {
1886 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1888 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1889 getConstant(Align - 1, dl, VAList.getValueType()));
1891 VAList = getNode(ISD::AND, dl, VAList.getValueType(), VAList,
1892 getConstant(-(int64_t)Align, dl, VAList.getValueType()));
1895 // Increment the pointer, VAList, to the next vaarg
1896 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1897 getConstant(getDataLayout().getTypeAllocSize(
1898 VT.getTypeForEVT(*getContext())),
1899 dl, VAList.getValueType()));
1900 // Store the incremented VAList to the legalized pointer
1901 Tmp1 =
1902 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
1903 // Load the actual argument out of the pointer VAList
1904 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
1907 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
1908 SDLoc dl(Node);
1909 const TargetLowering &TLI = getTargetLoweringInfo();
1910 // This defaults to loading a pointer from the input and storing it to the
1911 // output, returning the chain.
1912 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
1913 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
1914 SDValue Tmp1 =
1915 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
1916 Node->getOperand(2), MachinePointerInfo(VS));
1917 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
1918 MachinePointerInfo(VD));
1921 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1922 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1923 unsigned ByteSize = VT.getStoreSize();
1924 Type *Ty = VT.getTypeForEVT(*getContext());
1925 unsigned StackAlign =
1926 std::max((unsigned)getDataLayout().getPrefTypeAlignment(Ty), minAlign);
1928 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
1929 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1932 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1933 unsigned Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize());
1934 Type *Ty1 = VT1.getTypeForEVT(*getContext());
1935 Type *Ty2 = VT2.getTypeForEVT(*getContext());
1936 const DataLayout &DL = getDataLayout();
1937 unsigned Align =
1938 std::max(DL.getPrefTypeAlignment(Ty1), DL.getPrefTypeAlignment(Ty2));
1940 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1941 int FrameIdx = MFI.CreateStackObject(Bytes, Align, false);
1942 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1945 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
1946 ISD::CondCode Cond, const SDLoc &dl) {
1947 EVT OpVT = N1.getValueType();
1949 // These setcc operations always fold.
1950 switch (Cond) {
1951 default: break;
1952 case ISD::SETFALSE:
1953 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
1954 case ISD::SETTRUE:
1955 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
1957 case ISD::SETOEQ:
1958 case ISD::SETOGT:
1959 case ISD::SETOGE:
1960 case ISD::SETOLT:
1961 case ISD::SETOLE:
1962 case ISD::SETONE:
1963 case ISD::SETO:
1964 case ISD::SETUO:
1965 case ISD::SETUEQ:
1966 case ISD::SETUNE:
1967 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1968 break;
1971 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
1972 const APInt &C2 = N2C->getAPIntValue();
1973 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
1974 const APInt &C1 = N1C->getAPIntValue();
1976 switch (Cond) {
1977 default: llvm_unreachable("Unknown integer setcc!");
1978 case ISD::SETEQ: return getBoolConstant(C1 == C2, dl, VT, OpVT);
1979 case ISD::SETNE: return getBoolConstant(C1 != C2, dl, VT, OpVT);
1980 case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
1981 case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
1982 case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
1983 case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
1984 case ISD::SETLT: return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
1985 case ISD::SETGT: return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
1986 case ISD::SETLE: return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
1987 case ISD::SETGE: return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
1991 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1)) {
1992 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2)) {
1993 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1994 switch (Cond) {
1995 default: break;
1996 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1997 return getUNDEF(VT);
1998 LLVM_FALLTHROUGH;
1999 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2000 OpVT);
2001 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2002 return getUNDEF(VT);
2003 LLVM_FALLTHROUGH;
2004 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2005 R==APFloat::cmpLessThan, dl, VT,
2006 OpVT);
2007 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2008 return getUNDEF(VT);
2009 LLVM_FALLTHROUGH;
2010 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2011 OpVT);
2012 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2013 return getUNDEF(VT);
2014 LLVM_FALLTHROUGH;
2015 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2016 VT, OpVT);
2017 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2018 return getUNDEF(VT);
2019 LLVM_FALLTHROUGH;
2020 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2021 R==APFloat::cmpEqual, dl, VT,
2022 OpVT);
2023 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2024 return getUNDEF(VT);
2025 LLVM_FALLTHROUGH;
2026 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2027 R==APFloat::cmpEqual, dl, VT, OpVT);
2028 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2029 OpVT);
2030 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2031 OpVT);
2032 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2033 R==APFloat::cmpEqual, dl, VT,
2034 OpVT);
2035 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2036 OpVT);
2037 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2038 R==APFloat::cmpLessThan, dl, VT,
2039 OpVT);
2040 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2041 R==APFloat::cmpUnordered, dl, VT,
2042 OpVT);
2043 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2044 VT, OpVT);
2045 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2046 OpVT);
2048 } else {
2049 // Ensure that the constant occurs on the RHS.
2050 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2051 MVT CompVT = N1.getValueType().getSimpleVT();
2052 if (!TLI->isCondCodeLegal(SwappedCond, CompVT))
2053 return SDValue();
2055 return getSetCC(dl, VT, N2, N1, SwappedCond);
2059 // Could not fold it.
2060 return SDValue();
2063 /// See if the specified operand can be simplified with the knowledge that only
2064 /// the bits specified by Mask are used.
2065 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &Mask) {
2066 switch (V.getOpcode()) {
2067 default:
2068 break;
2069 case ISD::Constant: {
2070 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
2071 assert(CV && "Const value should be ConstSDNode.");
2072 const APInt &CVal = CV->getAPIntValue();
2073 APInt NewVal = CVal & Mask;
2074 if (NewVal != CVal)
2075 return getConstant(NewVal, SDLoc(V), V.getValueType());
2076 break;
2078 case ISD::OR:
2079 case ISD::XOR:
2080 // If the LHS or RHS don't contribute bits to the or, drop them.
2081 if (MaskedValueIsZero(V.getOperand(0), Mask))
2082 return V.getOperand(1);
2083 if (MaskedValueIsZero(V.getOperand(1), Mask))
2084 return V.getOperand(0);
2085 break;
2086 case ISD::SRL:
2087 // Only look at single-use SRLs.
2088 if (!V.getNode()->hasOneUse())
2089 break;
2090 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2091 // See if we can recursively simplify the LHS.
2092 unsigned Amt = RHSC->getZExtValue();
2094 // Watch out for shift count overflow though.
2095 if (Amt >= Mask.getBitWidth())
2096 break;
2097 APInt NewMask = Mask << Amt;
2098 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
2099 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2100 V.getOperand(1));
2102 break;
2103 case ISD::AND: {
2104 // X & -1 -> X (ignoring bits which aren't demanded).
2105 ConstantSDNode *AndVal = isConstOrConstSplat(V.getOperand(1));
2106 if (AndVal && Mask.isSubsetOf(AndVal->getAPIntValue()))
2107 return V.getOperand(0);
2108 break;
2110 case ISD::ANY_EXTEND: {
2111 SDValue Src = V.getOperand(0);
2112 unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
2113 // Being conservative here - only peek through if we only demand bits in the
2114 // non-extended source (even though the extended bits are technically undef).
2115 if (Mask.getActiveBits() > SrcBitWidth)
2116 break;
2117 APInt SrcMask = Mask.trunc(SrcBitWidth);
2118 if (SDValue DemandedSrc = GetDemandedBits(Src, SrcMask))
2119 return getNode(ISD::ANY_EXTEND, SDLoc(V), V.getValueType(), DemandedSrc);
2120 break;
2122 case ISD::SIGN_EXTEND_INREG:
2123 EVT ExVT = cast<VTSDNode>(V.getOperand(1))->getVT();
2124 unsigned ExVTBits = ExVT.getScalarSizeInBits();
2126 // If none of the extended bits are demanded, eliminate the sextinreg.
2127 if (Mask.getActiveBits() <= ExVTBits)
2128 return V.getOperand(0);
2130 break;
2132 return SDValue();
2135 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2136 /// use this predicate to simplify operations downstream.
2137 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2138 unsigned BitWidth = Op.getScalarValueSizeInBits();
2139 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2142 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2143 /// this predicate to simplify operations downstream. Mask is known to be zero
2144 /// for bits that V cannot have.
2145 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
2146 unsigned Depth) const {
2147 return Mask.isSubsetOf(computeKnownBits(Op, Depth).Zero);
2150 /// isSplatValue - Return true if the vector V has the same value
2151 /// across all DemandedElts.
2152 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2153 APInt &UndefElts) {
2154 if (!DemandedElts)
2155 return false; // No demanded elts, better to assume we don't know anything.
2157 EVT VT = V.getValueType();
2158 assert(VT.isVector() && "Vector type expected");
2160 unsigned NumElts = VT.getVectorNumElements();
2161 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2162 UndefElts = APInt::getNullValue(NumElts);
2164 switch (V.getOpcode()) {
2165 case ISD::BUILD_VECTOR: {
2166 SDValue Scl;
2167 for (unsigned i = 0; i != NumElts; ++i) {
2168 SDValue Op = V.getOperand(i);
2169 if (Op.isUndef()) {
2170 UndefElts.setBit(i);
2171 continue;
2173 if (!DemandedElts[i])
2174 continue;
2175 if (Scl && Scl != Op)
2176 return false;
2177 Scl = Op;
2179 return true;
2181 case ISD::VECTOR_SHUFFLE: {
2182 // Check if this is a shuffle node doing a splat.
2183 // TODO: Do we need to handle shuffle(splat, undef, mask)?
2184 int SplatIndex = -1;
2185 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2186 for (int i = 0; i != (int)NumElts; ++i) {
2187 int M = Mask[i];
2188 if (M < 0) {
2189 UndefElts.setBit(i);
2190 continue;
2192 if (!DemandedElts[i])
2193 continue;
2194 if (0 <= SplatIndex && SplatIndex != M)
2195 return false;
2196 SplatIndex = M;
2198 return true;
2200 case ISD::EXTRACT_SUBVECTOR: {
2201 SDValue Src = V.getOperand(0);
2202 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(V.getOperand(1));
2203 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2204 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2205 // Offset the demanded elts by the subvector index.
2206 uint64_t Idx = SubIdx->getZExtValue();
2207 APInt UndefSrcElts;
2208 APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2209 if (isSplatValue(Src, DemandedSrc, UndefSrcElts)) {
2210 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2211 return true;
2214 break;
2216 case ISD::ADD:
2217 case ISD::SUB:
2218 case ISD::AND: {
2219 APInt UndefLHS, UndefRHS;
2220 SDValue LHS = V.getOperand(0);
2221 SDValue RHS = V.getOperand(1);
2222 if (isSplatValue(LHS, DemandedElts, UndefLHS) &&
2223 isSplatValue(RHS, DemandedElts, UndefRHS)) {
2224 UndefElts = UndefLHS | UndefRHS;
2225 return true;
2227 break;
2231 return false;
2234 /// Helper wrapper to main isSplatValue function.
2235 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2236 EVT VT = V.getValueType();
2237 assert(VT.isVector() && "Vector type expected");
2238 unsigned NumElts = VT.getVectorNumElements();
2240 APInt UndefElts;
2241 APInt DemandedElts = APInt::getAllOnesValue(NumElts);
2242 return isSplatValue(V, DemandedElts, UndefElts) &&
2243 (AllowUndefs || !UndefElts);
2246 /// Helper function that checks to see if a node is a constant or a
2247 /// build vector of splat constants at least within the demanded elts.
2248 static ConstantSDNode *isConstOrDemandedConstSplat(SDValue N,
2249 const APInt &DemandedElts) {
2250 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
2251 return CN;
2252 if (N.getOpcode() != ISD::BUILD_VECTOR)
2253 return nullptr;
2254 EVT VT = N.getValueType();
2255 ConstantSDNode *Cst = nullptr;
2256 unsigned NumElts = VT.getVectorNumElements();
2257 assert(DemandedElts.getBitWidth() == NumElts && "Unexpected vector size");
2258 for (unsigned i = 0; i != NumElts; ++i) {
2259 if (!DemandedElts[i])
2260 continue;
2261 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(i));
2262 if (!C || (Cst && Cst->getAPIntValue() != C->getAPIntValue()) ||
2263 C->getValueType(0) != VT.getScalarType())
2264 return nullptr;
2265 Cst = C;
2267 return Cst;
2270 /// If a SHL/SRA/SRL node has a constant or splat constant shift amount that
2271 /// is less than the element bit-width of the shift node, return it.
2272 static const APInt *getValidShiftAmountConstant(SDValue V) {
2273 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1))) {
2274 // Shifting more than the bitwidth is not valid.
2275 const APInt &ShAmt = SA->getAPIntValue();
2276 if (ShAmt.ult(V.getScalarValueSizeInBits()))
2277 return &ShAmt;
2279 return nullptr;
2282 /// Determine which bits of Op are known to be either zero or one and return
2283 /// them in Known. For vectors, the known bits are those that are shared by
2284 /// every vector element.
2285 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2286 EVT VT = Op.getValueType();
2287 APInt DemandedElts = VT.isVector()
2288 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2289 : APInt(1, 1);
2290 return computeKnownBits(Op, DemandedElts, Depth);
2293 /// Determine which bits of Op are known to be either zero or one and return
2294 /// them in Known. The DemandedElts argument allows us to only collect the known
2295 /// bits that are shared by the requested vector elements.
2296 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2297 unsigned Depth) const {
2298 unsigned BitWidth = Op.getScalarValueSizeInBits();
2300 KnownBits Known(BitWidth); // Don't know anything.
2302 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2303 // We know all of the bits for a constant!
2304 Known.One = C->getAPIntValue();
2305 Known.Zero = ~Known.One;
2306 return Known;
2308 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2309 // We know all of the bits for a constant fp!
2310 Known.One = C->getValueAPF().bitcastToAPInt();
2311 Known.Zero = ~Known.One;
2312 return Known;
2315 if (Depth == 6)
2316 return Known; // Limit search depth.
2318 KnownBits Known2;
2319 unsigned NumElts = DemandedElts.getBitWidth();
2320 assert((!Op.getValueType().isVector() ||
2321 NumElts == Op.getValueType().getVectorNumElements()) &&
2322 "Unexpected vector size");
2324 if (!DemandedElts)
2325 return Known; // No demanded elts, better to assume we don't know anything.
2327 unsigned Opcode = Op.getOpcode();
2328 switch (Opcode) {
2329 case ISD::BUILD_VECTOR:
2330 // Collect the known bits that are shared by every demanded vector element.
2331 Known.Zero.setAllBits(); Known.One.setAllBits();
2332 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2333 if (!DemandedElts[i])
2334 continue;
2336 SDValue SrcOp = Op.getOperand(i);
2337 Known2 = computeKnownBits(SrcOp, Depth + 1);
2339 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2340 if (SrcOp.getValueSizeInBits() != BitWidth) {
2341 assert(SrcOp.getValueSizeInBits() > BitWidth &&
2342 "Expected BUILD_VECTOR implicit truncation");
2343 Known2 = Known2.trunc(BitWidth);
2346 // Known bits are the values that are shared by every demanded element.
2347 Known.One &= Known2.One;
2348 Known.Zero &= Known2.Zero;
2350 // If we don't know any bits, early out.
2351 if (Known.isUnknown())
2352 break;
2354 break;
2355 case ISD::VECTOR_SHUFFLE: {
2356 // Collect the known bits that are shared by every vector element referenced
2357 // by the shuffle.
2358 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2359 Known.Zero.setAllBits(); Known.One.setAllBits();
2360 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2361 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2362 for (unsigned i = 0; i != NumElts; ++i) {
2363 if (!DemandedElts[i])
2364 continue;
2366 int M = SVN->getMaskElt(i);
2367 if (M < 0) {
2368 // For UNDEF elements, we don't know anything about the common state of
2369 // the shuffle result.
2370 Known.resetAll();
2371 DemandedLHS.clearAllBits();
2372 DemandedRHS.clearAllBits();
2373 break;
2376 if ((unsigned)M < NumElts)
2377 DemandedLHS.setBit((unsigned)M % NumElts);
2378 else
2379 DemandedRHS.setBit((unsigned)M % NumElts);
2381 // Known bits are the values that are shared by every demanded element.
2382 if (!!DemandedLHS) {
2383 SDValue LHS = Op.getOperand(0);
2384 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2385 Known.One &= Known2.One;
2386 Known.Zero &= Known2.Zero;
2388 // If we don't know any bits, early out.
2389 if (Known.isUnknown())
2390 break;
2391 if (!!DemandedRHS) {
2392 SDValue RHS = Op.getOperand(1);
2393 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2394 Known.One &= Known2.One;
2395 Known.Zero &= Known2.Zero;
2397 break;
2399 case ISD::CONCAT_VECTORS: {
2400 // Split DemandedElts and test each of the demanded subvectors.
2401 Known.Zero.setAllBits(); Known.One.setAllBits();
2402 EVT SubVectorVT = Op.getOperand(0).getValueType();
2403 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2404 unsigned NumSubVectors = Op.getNumOperands();
2405 for (unsigned i = 0; i != NumSubVectors; ++i) {
2406 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2407 DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2408 if (!!DemandedSub) {
2409 SDValue Sub = Op.getOperand(i);
2410 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2411 Known.One &= Known2.One;
2412 Known.Zero &= Known2.Zero;
2414 // If we don't know any bits, early out.
2415 if (Known.isUnknown())
2416 break;
2418 break;
2420 case ISD::INSERT_SUBVECTOR: {
2421 // If we know the element index, demand any elements from the subvector and
2422 // the remainder from the src its inserted into, otherwise demand them all.
2423 SDValue Src = Op.getOperand(0);
2424 SDValue Sub = Op.getOperand(1);
2425 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2426 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2427 if (SubIdx && SubIdx->getAPIntValue().ule(NumElts - NumSubElts)) {
2428 Known.One.setAllBits();
2429 Known.Zero.setAllBits();
2430 uint64_t Idx = SubIdx->getZExtValue();
2431 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2432 if (!!DemandedSubElts) {
2433 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2434 if (Known.isUnknown())
2435 break; // early-out.
2437 APInt SubMask = APInt::getBitsSet(NumElts, Idx, Idx + NumSubElts);
2438 APInt DemandedSrcElts = DemandedElts & ~SubMask;
2439 if (!!DemandedSrcElts) {
2440 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2441 Known.One &= Known2.One;
2442 Known.Zero &= Known2.Zero;
2444 } else {
2445 Known = computeKnownBits(Sub, Depth + 1);
2446 if (Known.isUnknown())
2447 break; // early-out.
2448 Known2 = computeKnownBits(Src, Depth + 1);
2449 Known.One &= Known2.One;
2450 Known.Zero &= Known2.Zero;
2452 break;
2454 case ISD::EXTRACT_SUBVECTOR: {
2455 // If we know the element index, just demand that subvector elements,
2456 // otherwise demand them all.
2457 SDValue Src = Op.getOperand(0);
2458 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2459 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2460 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2461 // Offset the demanded elts by the subvector index.
2462 uint64_t Idx = SubIdx->getZExtValue();
2463 APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2464 Known = computeKnownBits(Src, DemandedSrc, Depth + 1);
2465 } else {
2466 Known = computeKnownBits(Src, Depth + 1);
2468 break;
2470 case ISD::SCALAR_TO_VECTOR: {
2471 // We know about scalar_to_vector as much as we know about it source,
2472 // which becomes the first element of otherwise unknown vector.
2473 if (DemandedElts != 1)
2474 break;
2476 SDValue N0 = Op.getOperand(0);
2477 Known = computeKnownBits(N0, Depth + 1);
2478 if (N0.getValueSizeInBits() != BitWidth)
2479 Known = Known.trunc(BitWidth);
2481 break;
2483 case ISD::BITCAST: {
2484 SDValue N0 = Op.getOperand(0);
2485 EVT SubVT = N0.getValueType();
2486 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2488 // Ignore bitcasts from unsupported types.
2489 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2490 break;
2492 // Fast handling of 'identity' bitcasts.
2493 if (BitWidth == SubBitWidth) {
2494 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2495 break;
2498 bool IsLE = getDataLayout().isLittleEndian();
2500 // Bitcast 'small element' vector to 'large element' scalar/vector.
2501 if ((BitWidth % SubBitWidth) == 0) {
2502 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2504 // Collect known bits for the (larger) output by collecting the known
2505 // bits from each set of sub elements and shift these into place.
2506 // We need to separately call computeKnownBits for each set of
2507 // sub elements as the knownbits for each is likely to be different.
2508 unsigned SubScale = BitWidth / SubBitWidth;
2509 APInt SubDemandedElts(NumElts * SubScale, 0);
2510 for (unsigned i = 0; i != NumElts; ++i)
2511 if (DemandedElts[i])
2512 SubDemandedElts.setBit(i * SubScale);
2514 for (unsigned i = 0; i != SubScale; ++i) {
2515 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2516 Depth + 1);
2517 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2518 Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts);
2519 Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts);
2523 // Bitcast 'large element' scalar/vector to 'small element' vector.
2524 if ((SubBitWidth % BitWidth) == 0) {
2525 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2527 // Collect known bits for the (smaller) output by collecting the known
2528 // bits from the overlapping larger input elements and extracting the
2529 // sub sections we actually care about.
2530 unsigned SubScale = SubBitWidth / BitWidth;
2531 APInt SubDemandedElts(NumElts / SubScale, 0);
2532 for (unsigned i = 0; i != NumElts; ++i)
2533 if (DemandedElts[i])
2534 SubDemandedElts.setBit(i / SubScale);
2536 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
2538 Known.Zero.setAllBits(); Known.One.setAllBits();
2539 for (unsigned i = 0; i != NumElts; ++i)
2540 if (DemandedElts[i]) {
2541 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
2542 unsigned Offset = (Shifts % SubScale) * BitWidth;
2543 Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
2544 Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
2545 // If we don't know any bits, early out.
2546 if (Known.isUnknown())
2547 break;
2550 break;
2552 case ISD::AND:
2553 // If either the LHS or the RHS are Zero, the result is zero.
2554 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2555 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2557 // Output known-1 bits are only known if set in both the LHS & RHS.
2558 Known.One &= Known2.One;
2559 // Output known-0 are known to be clear if zero in either the LHS | RHS.
2560 Known.Zero |= Known2.Zero;
2561 break;
2562 case ISD::OR:
2563 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2564 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2566 // Output known-0 bits are only known if clear in both the LHS & RHS.
2567 Known.Zero &= Known2.Zero;
2568 // Output known-1 are known to be set if set in either the LHS | RHS.
2569 Known.One |= Known2.One;
2570 break;
2571 case ISD::XOR: {
2572 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2573 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2575 // Output known-0 bits are known if clear or set in both the LHS & RHS.
2576 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
2577 // Output known-1 are known to be set if set in only one of the LHS, RHS.
2578 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
2579 Known.Zero = KnownZeroOut;
2580 break;
2582 case ISD::MUL: {
2583 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2584 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2586 // If low bits are zero in either operand, output low known-0 bits.
2587 // Also compute a conservative estimate for high known-0 bits.
2588 // More trickiness is possible, but this is sufficient for the
2589 // interesting case of alignment computation.
2590 unsigned TrailZ = Known.countMinTrailingZeros() +
2591 Known2.countMinTrailingZeros();
2592 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
2593 Known2.countMinLeadingZeros(),
2594 BitWidth) - BitWidth;
2596 Known.resetAll();
2597 Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
2598 Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
2599 break;
2601 case ISD::UDIV: {
2602 // For the purposes of computing leading zeros we can conservatively
2603 // treat a udiv as a logical right shift by the power of 2 known to
2604 // be less than the denominator.
2605 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2606 unsigned LeadZ = Known2.countMinLeadingZeros();
2608 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2609 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
2610 if (RHSMaxLeadingZeros != BitWidth)
2611 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
2613 Known.Zero.setHighBits(LeadZ);
2614 break;
2616 case ISD::SELECT:
2617 case ISD::VSELECT:
2618 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
2619 // If we don't know any bits, early out.
2620 if (Known.isUnknown())
2621 break;
2622 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
2624 // Only known if known in both the LHS and RHS.
2625 Known.One &= Known2.One;
2626 Known.Zero &= Known2.Zero;
2627 break;
2628 case ISD::SELECT_CC:
2629 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
2630 // If we don't know any bits, early out.
2631 if (Known.isUnknown())
2632 break;
2633 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
2635 // Only known if known in both the LHS and RHS.
2636 Known.One &= Known2.One;
2637 Known.Zero &= Known2.Zero;
2638 break;
2639 case ISD::SMULO:
2640 case ISD::UMULO:
2641 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
2642 if (Op.getResNo() != 1)
2643 break;
2644 // The boolean result conforms to getBooleanContents.
2645 // If we know the result of a setcc has the top bits zero, use this info.
2646 // We know that we have an integer-based boolean since these operations
2647 // are only available for integer.
2648 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2649 TargetLowering::ZeroOrOneBooleanContent &&
2650 BitWidth > 1)
2651 Known.Zero.setBitsFrom(1);
2652 break;
2653 case ISD::SETCC:
2654 // If we know the result of a setcc has the top bits zero, use this info.
2655 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2656 TargetLowering::ZeroOrOneBooleanContent &&
2657 BitWidth > 1)
2658 Known.Zero.setBitsFrom(1);
2659 break;
2660 case ISD::SHL:
2661 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2662 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2663 unsigned Shift = ShAmt->getZExtValue();
2664 Known.Zero <<= Shift;
2665 Known.One <<= Shift;
2666 // Low bits are known zero.
2667 Known.Zero.setLowBits(Shift);
2669 break;
2670 case ISD::SRL:
2671 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2672 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2673 unsigned Shift = ShAmt->getZExtValue();
2674 Known.Zero.lshrInPlace(Shift);
2675 Known.One.lshrInPlace(Shift);
2676 // High bits are known zero.
2677 Known.Zero.setHighBits(Shift);
2678 } else if (auto *BV = dyn_cast<BuildVectorSDNode>(Op.getOperand(1))) {
2679 // If the shift amount is a vector of constants see if we can bound
2680 // the number of upper zero bits.
2681 unsigned ShiftAmountMin = BitWidth;
2682 for (unsigned i = 0; i != BV->getNumOperands(); ++i) {
2683 if (auto *C = dyn_cast<ConstantSDNode>(BV->getOperand(i))) {
2684 const APInt &ShAmt = C->getAPIntValue();
2685 if (ShAmt.ult(BitWidth)) {
2686 ShiftAmountMin = std::min<unsigned>(ShiftAmountMin,
2687 ShAmt.getZExtValue());
2688 continue;
2691 // Don't know anything.
2692 ShiftAmountMin = 0;
2693 break;
2696 Known.Zero.setHighBits(ShiftAmountMin);
2698 break;
2699 case ISD::SRA:
2700 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2701 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2702 unsigned Shift = ShAmt->getZExtValue();
2703 // Sign extend known zero/one bit (else is unknown).
2704 Known.Zero.ashrInPlace(Shift);
2705 Known.One.ashrInPlace(Shift);
2707 break;
2708 case ISD::FSHL:
2709 case ISD::FSHR:
2710 if (ConstantSDNode *C =
2711 isConstOrDemandedConstSplat(Op.getOperand(2), DemandedElts)) {
2712 unsigned Amt = C->getAPIntValue().urem(BitWidth);
2714 // For fshl, 0-shift returns the 1st arg.
2715 // For fshr, 0-shift returns the 2nd arg.
2716 if (Amt == 0) {
2717 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
2718 DemandedElts, Depth + 1);
2719 break;
2722 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
2723 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
2724 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2725 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2726 if (Opcode == ISD::FSHL) {
2727 Known.One <<= Amt;
2728 Known.Zero <<= Amt;
2729 Known2.One.lshrInPlace(BitWidth - Amt);
2730 Known2.Zero.lshrInPlace(BitWidth - Amt);
2731 } else {
2732 Known.One <<= BitWidth - Amt;
2733 Known.Zero <<= BitWidth - Amt;
2734 Known2.One.lshrInPlace(Amt);
2735 Known2.Zero.lshrInPlace(Amt);
2737 Known.One |= Known2.One;
2738 Known.Zero |= Known2.Zero;
2740 break;
2741 case ISD::SIGN_EXTEND_INREG: {
2742 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2743 unsigned EBits = EVT.getScalarSizeInBits();
2745 // Sign extension. Compute the demanded bits in the result that are not
2746 // present in the input.
2747 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
2749 APInt InSignMask = APInt::getSignMask(EBits);
2750 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
2752 // If the sign extended bits are demanded, we know that the sign
2753 // bit is demanded.
2754 InSignMask = InSignMask.zext(BitWidth);
2755 if (NewBits.getBoolValue())
2756 InputDemandedBits |= InSignMask;
2758 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2759 Known.One &= InputDemandedBits;
2760 Known.Zero &= InputDemandedBits;
2762 // If the sign bit of the input is known set or clear, then we know the
2763 // top bits of the result.
2764 if (Known.Zero.intersects(InSignMask)) { // Input sign bit known clear
2765 Known.Zero |= NewBits;
2766 Known.One &= ~NewBits;
2767 } else if (Known.One.intersects(InSignMask)) { // Input sign bit known set
2768 Known.One |= NewBits;
2769 Known.Zero &= ~NewBits;
2770 } else { // Input sign bit unknown
2771 Known.Zero &= ~NewBits;
2772 Known.One &= ~NewBits;
2774 break;
2776 case ISD::CTTZ:
2777 case ISD::CTTZ_ZERO_UNDEF: {
2778 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2779 // If we have a known 1, its position is our upper bound.
2780 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2781 unsigned LowBits = Log2_32(PossibleTZ) + 1;
2782 Known.Zero.setBitsFrom(LowBits);
2783 break;
2785 case ISD::CTLZ:
2786 case ISD::CTLZ_ZERO_UNDEF: {
2787 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2788 // If we have a known 1, its position is our upper bound.
2789 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2790 unsigned LowBits = Log2_32(PossibleLZ) + 1;
2791 Known.Zero.setBitsFrom(LowBits);
2792 break;
2794 case ISD::CTPOP: {
2795 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2796 // If we know some of the bits are zero, they can't be one.
2797 unsigned PossibleOnes = Known2.countMaxPopulation();
2798 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
2799 break;
2801 case ISD::LOAD: {
2802 LoadSDNode *LD = cast<LoadSDNode>(Op);
2803 // If this is a ZEXTLoad and we are looking at the loaded value.
2804 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
2805 EVT VT = LD->getMemoryVT();
2806 unsigned MemBits = VT.getScalarSizeInBits();
2807 Known.Zero.setBitsFrom(MemBits);
2808 } else if (const MDNode *Ranges = LD->getRanges()) {
2809 if (LD->getExtensionType() == ISD::NON_EXTLOAD)
2810 computeKnownBitsFromRangeMetadata(*Ranges, Known);
2812 break;
2814 case ISD::ZERO_EXTEND_VECTOR_INREG: {
2815 EVT InVT = Op.getOperand(0).getValueType();
2816 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
2817 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
2818 Known = Known.zext(BitWidth);
2819 Known.Zero.setBitsFrom(InVT.getScalarSizeInBits());
2820 break;
2822 case ISD::ZERO_EXTEND: {
2823 EVT InVT = Op.getOperand(0).getValueType();
2824 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2825 Known = Known.zext(BitWidth);
2826 Known.Zero.setBitsFrom(InVT.getScalarSizeInBits());
2827 break;
2829 case ISD::SIGN_EXTEND_VECTOR_INREG: {
2830 EVT InVT = Op.getOperand(0).getValueType();
2831 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
2832 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
2833 // If the sign bit is known to be zero or one, then sext will extend
2834 // it to the top bits, else it will just zext.
2835 Known = Known.sext(BitWidth);
2836 break;
2838 case ISD::SIGN_EXTEND: {
2839 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2840 // If the sign bit is known to be zero or one, then sext will extend
2841 // it to the top bits, else it will just zext.
2842 Known = Known.sext(BitWidth);
2843 break;
2845 case ISD::ANY_EXTEND: {
2846 Known = computeKnownBits(Op.getOperand(0), Depth+1);
2847 Known = Known.zext(BitWidth);
2848 break;
2850 case ISD::TRUNCATE: {
2851 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2852 Known = Known.trunc(BitWidth);
2853 break;
2855 case ISD::AssertZext: {
2856 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2857 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
2858 Known = computeKnownBits(Op.getOperand(0), Depth+1);
2859 Known.Zero |= (~InMask);
2860 Known.One &= (~Known.Zero);
2861 break;
2863 case ISD::FGETSIGN:
2864 // All bits are zero except the low bit.
2865 Known.Zero.setBitsFrom(1);
2866 break;
2867 case ISD::USUBO:
2868 case ISD::SSUBO:
2869 if (Op.getResNo() == 1) {
2870 // If we know the result of a setcc has the top bits zero, use this info.
2871 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2872 TargetLowering::ZeroOrOneBooleanContent &&
2873 BitWidth > 1)
2874 Known.Zero.setBitsFrom(1);
2875 break;
2877 LLVM_FALLTHROUGH;
2878 case ISD::SUB:
2879 case ISD::SUBC: {
2880 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0))) {
2881 // We know that the top bits of C-X are clear if X contains less bits
2882 // than C (i.e. no wrap-around can happen). For example, 20-X is
2883 // positive if we can prove that X is >= 0 and < 16.
2884 if (CLHS->getAPIntValue().isNonNegative()) {
2885 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
2886 // NLZ can't be BitWidth with no sign bit
2887 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
2888 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts,
2889 Depth + 1);
2891 // If all of the MaskV bits are known to be zero, then we know the
2892 // output top bits are zero, because we now know that the output is
2893 // from [0-C].
2894 if ((Known2.Zero & MaskV) == MaskV) {
2895 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
2896 // Top bits known zero.
2897 Known.Zero.setHighBits(NLZ2);
2902 // If low bits are know to be zero in both operands, then we know they are
2903 // going to be 0 in the result. Both addition and complement operations
2904 // preserve the low zero bits.
2905 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2906 unsigned KnownZeroLow = Known2.countMinTrailingZeros();
2907 if (KnownZeroLow == 0)
2908 break;
2910 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2911 KnownZeroLow = std::min(KnownZeroLow, Known2.countMinTrailingZeros());
2912 Known.Zero.setLowBits(KnownZeroLow);
2913 break;
2915 case ISD::UADDO:
2916 case ISD::SADDO:
2917 case ISD::ADDCARRY:
2918 if (Op.getResNo() == 1) {
2919 // If we know the result of a setcc has the top bits zero, use this info.
2920 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2921 TargetLowering::ZeroOrOneBooleanContent &&
2922 BitWidth > 1)
2923 Known.Zero.setBitsFrom(1);
2924 break;
2926 LLVM_FALLTHROUGH;
2927 case ISD::ADD:
2928 case ISD::ADDC:
2929 case ISD::ADDE: {
2930 // Output known-0 bits are known if clear or set in both the low clear bits
2931 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
2932 // low 3 bits clear.
2933 // Output known-0 bits are also known if the top bits of each input are
2934 // known to be clear. For example, if one input has the top 10 bits clear
2935 // and the other has the top 8 bits clear, we know the top 7 bits of the
2936 // output must be clear.
2937 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2938 unsigned KnownZeroHigh = Known2.countMinLeadingZeros();
2939 unsigned KnownZeroLow = Known2.countMinTrailingZeros();
2941 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2942 KnownZeroHigh = std::min(KnownZeroHigh, Known2.countMinLeadingZeros());
2943 KnownZeroLow = std::min(KnownZeroLow, Known2.countMinTrailingZeros());
2945 if (Opcode == ISD::ADDE || Opcode == ISD::ADDCARRY) {
2946 // With ADDE and ADDCARRY, a carry bit may be added in, so we can only
2947 // use this information if we know (at least) that the low two bits are
2948 // clear. We then return to the caller that the low bit is unknown but
2949 // that other bits are known zero.
2950 if (KnownZeroLow >= 2)
2951 Known.Zero.setBits(1, KnownZeroLow);
2952 break;
2955 Known.Zero.setLowBits(KnownZeroLow);
2956 if (KnownZeroHigh > 1)
2957 Known.Zero.setHighBits(KnownZeroHigh - 1);
2958 break;
2960 case ISD::SREM:
2961 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
2962 const APInt &RA = Rem->getAPIntValue().abs();
2963 if (RA.isPowerOf2()) {
2964 APInt LowBits = RA - 1;
2965 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2967 // The low bits of the first operand are unchanged by the srem.
2968 Known.Zero = Known2.Zero & LowBits;
2969 Known.One = Known2.One & LowBits;
2971 // If the first operand is non-negative or has all low bits zero, then
2972 // the upper bits are all zero.
2973 if (Known2.Zero[BitWidth-1] || ((Known2.Zero & LowBits) == LowBits))
2974 Known.Zero |= ~LowBits;
2976 // If the first operand is negative and not all low bits are zero, then
2977 // the upper bits are all one.
2978 if (Known2.One[BitWidth-1] && ((Known2.One & LowBits) != 0))
2979 Known.One |= ~LowBits;
2980 assert((Known.Zero & Known.One) == 0&&"Bits known to be one AND zero?");
2983 break;
2984 case ISD::UREM: {
2985 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
2986 const APInt &RA = Rem->getAPIntValue();
2987 if (RA.isPowerOf2()) {
2988 APInt LowBits = (RA - 1);
2989 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2991 // The upper bits are all zero, the lower ones are unchanged.
2992 Known.Zero = Known2.Zero | ~LowBits;
2993 Known.One = Known2.One & LowBits;
2994 break;
2998 // Since the result is less than or equal to either operand, any leading
2999 // zero bits in either operand must also exist in the result.
3000 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3001 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3003 uint32_t Leaders =
3004 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
3005 Known.resetAll();
3006 Known.Zero.setHighBits(Leaders);
3007 break;
3009 case ISD::EXTRACT_ELEMENT: {
3010 Known = computeKnownBits(Op.getOperand(0), Depth+1);
3011 const unsigned Index = Op.getConstantOperandVal(1);
3012 const unsigned BitWidth = Op.getValueSizeInBits();
3014 // Remove low part of known bits mask
3015 Known.Zero = Known.Zero.getHiBits(Known.Zero.getBitWidth() - Index * BitWidth);
3016 Known.One = Known.One.getHiBits(Known.One.getBitWidth() - Index * BitWidth);
3018 // Remove high part of known bit mask
3019 Known = Known.trunc(BitWidth);
3020 break;
3022 case ISD::EXTRACT_VECTOR_ELT: {
3023 SDValue InVec = Op.getOperand(0);
3024 SDValue EltNo = Op.getOperand(1);
3025 EVT VecVT = InVec.getValueType();
3026 const unsigned BitWidth = Op.getValueSizeInBits();
3027 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3028 const unsigned NumSrcElts = VecVT.getVectorNumElements();
3029 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3030 // anything about the extended bits.
3031 if (BitWidth > EltBitWidth)
3032 Known = Known.trunc(EltBitWidth);
3033 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3034 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) {
3035 // If we know the element index, just demand that vector element.
3036 unsigned Idx = ConstEltNo->getZExtValue();
3037 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
3038 Known = computeKnownBits(InVec, DemandedElt, Depth + 1);
3039 } else {
3040 // Unknown element index, so ignore DemandedElts and demand them all.
3041 Known = computeKnownBits(InVec, Depth + 1);
3043 if (BitWidth > EltBitWidth)
3044 Known = Known.zext(BitWidth);
3045 break;
3047 case ISD::INSERT_VECTOR_ELT: {
3048 SDValue InVec = Op.getOperand(0);
3049 SDValue InVal = Op.getOperand(1);
3050 SDValue EltNo = Op.getOperand(2);
3052 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3053 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3054 // If we know the element index, split the demand between the
3055 // source vector and the inserted element.
3056 Known.Zero = Known.One = APInt::getAllOnesValue(BitWidth);
3057 unsigned EltIdx = CEltNo->getZExtValue();
3059 // If we demand the inserted element then add its common known bits.
3060 if (DemandedElts[EltIdx]) {
3061 Known2 = computeKnownBits(InVal, Depth + 1);
3062 Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
3063 Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
3066 // If we demand the source vector then add its common known bits, ensuring
3067 // that we don't demand the inserted element.
3068 APInt VectorElts = DemandedElts & ~(APInt::getOneBitSet(NumElts, EltIdx));
3069 if (!!VectorElts) {
3070 Known2 = computeKnownBits(InVec, VectorElts, Depth + 1);
3071 Known.One &= Known2.One;
3072 Known.Zero &= Known2.Zero;
3074 } else {
3075 // Unknown element index, so ignore DemandedElts and demand them all.
3076 Known = computeKnownBits(InVec, Depth + 1);
3077 Known2 = computeKnownBits(InVal, Depth + 1);
3078 Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
3079 Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
3081 break;
3083 case ISD::BITREVERSE: {
3084 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3085 Known.Zero = Known2.Zero.reverseBits();
3086 Known.One = Known2.One.reverseBits();
3087 break;
3089 case ISD::BSWAP: {
3090 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3091 Known.Zero = Known2.Zero.byteSwap();
3092 Known.One = Known2.One.byteSwap();
3093 break;
3095 case ISD::ABS: {
3096 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3098 // If the source's MSB is zero then we know the rest of the bits already.
3099 if (Known2.isNonNegative()) {
3100 Known.Zero = Known2.Zero;
3101 Known.One = Known2.One;
3102 break;
3105 // We only know that the absolute values's MSB will be zero iff there is
3106 // a set bit that isn't the sign bit (otherwise it could be INT_MIN).
3107 Known2.One.clearSignBit();
3108 if (Known2.One.getBoolValue()) {
3109 Known.Zero = APInt::getSignMask(BitWidth);
3110 break;
3112 break;
3114 case ISD::UMIN: {
3115 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3116 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3118 // UMIN - we know that the result will have the maximum of the
3119 // known zero leading bits of the inputs.
3120 unsigned LeadZero = Known.countMinLeadingZeros();
3121 LeadZero = std::max(LeadZero, Known2.countMinLeadingZeros());
3123 Known.Zero &= Known2.Zero;
3124 Known.One &= Known2.One;
3125 Known.Zero.setHighBits(LeadZero);
3126 break;
3128 case ISD::UMAX: {
3129 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3130 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3132 // UMAX - we know that the result will have the maximum of the
3133 // known one leading bits of the inputs.
3134 unsigned LeadOne = Known.countMinLeadingOnes();
3135 LeadOne = std::max(LeadOne, Known2.countMinLeadingOnes());
3137 Known.Zero &= Known2.Zero;
3138 Known.One &= Known2.One;
3139 Known.One.setHighBits(LeadOne);
3140 break;
3142 case ISD::SMIN:
3143 case ISD::SMAX: {
3144 // If we have a clamp pattern, we know that the number of sign bits will be
3145 // the minimum of the clamp min/max range.
3146 bool IsMax = (Opcode == ISD::SMAX);
3147 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3148 if ((CstLow = isConstOrDemandedConstSplat(Op.getOperand(1), DemandedElts)))
3149 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3150 CstHigh = isConstOrDemandedConstSplat(Op.getOperand(0).getOperand(1),
3151 DemandedElts);
3152 if (CstLow && CstHigh) {
3153 if (!IsMax)
3154 std::swap(CstLow, CstHigh);
3156 const APInt &ValueLow = CstLow->getAPIntValue();
3157 const APInt &ValueHigh = CstHigh->getAPIntValue();
3158 if (ValueLow.sle(ValueHigh)) {
3159 unsigned LowSignBits = ValueLow.getNumSignBits();
3160 unsigned HighSignBits = ValueHigh.getNumSignBits();
3161 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3162 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3163 Known.One.setHighBits(MinSignBits);
3164 break;
3166 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3167 Known.Zero.setHighBits(MinSignBits);
3168 break;
3173 // Fallback - just get the shared known bits of the operands.
3174 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3175 if (Known.isUnknown()) break; // Early-out
3176 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3177 Known.Zero &= Known2.Zero;
3178 Known.One &= Known2.One;
3179 break;
3181 case ISD::FrameIndex:
3182 case ISD::TargetFrameIndex:
3183 TLI->computeKnownBitsForFrameIndex(Op, Known, DemandedElts, *this, Depth);
3184 break;
3186 default:
3187 if (Opcode < ISD::BUILTIN_OP_END)
3188 break;
3189 LLVM_FALLTHROUGH;
3190 case ISD::INTRINSIC_WO_CHAIN:
3191 case ISD::INTRINSIC_W_CHAIN:
3192 case ISD::INTRINSIC_VOID:
3193 // Allow the target to implement this method for its nodes.
3194 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3195 break;
3198 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3199 return Known;
3202 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3203 SDValue N1) const {
3204 // X + 0 never overflow
3205 if (isNullConstant(N1))
3206 return OFK_Never;
3208 KnownBits N1Known = computeKnownBits(N1);
3209 if (N1Known.Zero.getBoolValue()) {
3210 KnownBits N0Known = computeKnownBits(N0);
3212 bool overflow;
3213 (void)(~N0Known.Zero).uadd_ov(~N1Known.Zero, overflow);
3214 if (!overflow)
3215 return OFK_Never;
3218 // mulhi + 1 never overflow
3219 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3220 (~N1Known.Zero & 0x01) == ~N1Known.Zero)
3221 return OFK_Never;
3223 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3224 KnownBits N0Known = computeKnownBits(N0);
3226 if ((~N0Known.Zero & 0x01) == ~N0Known.Zero)
3227 return OFK_Never;
3230 return OFK_Sometime;
3233 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3234 EVT OpVT = Val.getValueType();
3235 unsigned BitWidth = OpVT.getScalarSizeInBits();
3237 // Is the constant a known power of 2?
3238 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3239 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3241 // A left-shift of a constant one will have exactly one bit set because
3242 // shifting the bit off the end is undefined.
3243 if (Val.getOpcode() == ISD::SHL) {
3244 auto *C = isConstOrConstSplat(Val.getOperand(0));
3245 if (C && C->getAPIntValue() == 1)
3246 return true;
3249 // Similarly, a logical right-shift of a constant sign-bit will have exactly
3250 // one bit set.
3251 if (Val.getOpcode() == ISD::SRL) {
3252 auto *C = isConstOrConstSplat(Val.getOperand(0));
3253 if (C && C->getAPIntValue().isSignMask())
3254 return true;
3257 // Are all operands of a build vector constant powers of two?
3258 if (Val.getOpcode() == ISD::BUILD_VECTOR)
3259 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3260 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3261 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3262 return false;
3264 return true;
3266 // More could be done here, though the above checks are enough
3267 // to handle some common cases.
3269 // Fall back to computeKnownBits to catch other known cases.
3270 KnownBits Known = computeKnownBits(Val);
3271 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3274 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3275 EVT VT = Op.getValueType();
3276 APInt DemandedElts = VT.isVector()
3277 ? APInt::getAllOnesValue(VT.getVectorNumElements())
3278 : APInt(1, 1);
3279 return ComputeNumSignBits(Op, DemandedElts, Depth);
3282 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3283 unsigned Depth) const {
3284 EVT VT = Op.getValueType();
3285 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3286 unsigned VTBits = VT.getScalarSizeInBits();
3287 unsigned NumElts = DemandedElts.getBitWidth();
3288 unsigned Tmp, Tmp2;
3289 unsigned FirstAnswer = 1;
3291 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3292 const APInt &Val = C->getAPIntValue();
3293 return Val.getNumSignBits();
3296 if (Depth == 6)
3297 return 1; // Limit search depth.
3299 if (!DemandedElts)
3300 return 1; // No demanded elts, better to assume we don't know anything.
3302 unsigned Opcode = Op.getOpcode();
3303 switch (Opcode) {
3304 default: break;
3305 case ISD::AssertSext:
3306 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3307 return VTBits-Tmp+1;
3308 case ISD::AssertZext:
3309 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3310 return VTBits-Tmp;
3312 case ISD::BUILD_VECTOR:
3313 Tmp = VTBits;
3314 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3315 if (!DemandedElts[i])
3316 continue;
3318 SDValue SrcOp = Op.getOperand(i);
3319 Tmp2 = ComputeNumSignBits(Op.getOperand(i), Depth + 1);
3321 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3322 if (SrcOp.getValueSizeInBits() != VTBits) {
3323 assert(SrcOp.getValueSizeInBits() > VTBits &&
3324 "Expected BUILD_VECTOR implicit truncation");
3325 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3326 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3328 Tmp = std::min(Tmp, Tmp2);
3330 return Tmp;
3332 case ISD::VECTOR_SHUFFLE: {
3333 // Collect the minimum number of sign bits that are shared by every vector
3334 // element referenced by the shuffle.
3335 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3336 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3337 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3338 for (unsigned i = 0; i != NumElts; ++i) {
3339 int M = SVN->getMaskElt(i);
3340 if (!DemandedElts[i])
3341 continue;
3342 // For UNDEF elements, we don't know anything about the common state of
3343 // the shuffle result.
3344 if (M < 0)
3345 return 1;
3346 if ((unsigned)M < NumElts)
3347 DemandedLHS.setBit((unsigned)M % NumElts);
3348 else
3349 DemandedRHS.setBit((unsigned)M % NumElts);
3351 Tmp = std::numeric_limits<unsigned>::max();
3352 if (!!DemandedLHS)
3353 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3354 if (!!DemandedRHS) {
3355 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3356 Tmp = std::min(Tmp, Tmp2);
3358 // If we don't know anything, early out and try computeKnownBits fall-back.
3359 if (Tmp == 1)
3360 break;
3361 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3362 return Tmp;
3365 case ISD::BITCAST: {
3366 SDValue N0 = Op.getOperand(0);
3367 EVT SrcVT = N0.getValueType();
3368 unsigned SrcBits = SrcVT.getScalarSizeInBits();
3370 // Ignore bitcasts from unsupported types..
3371 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3372 break;
3374 // Fast handling of 'identity' bitcasts.
3375 if (VTBits == SrcBits)
3376 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3378 bool IsLE = getDataLayout().isLittleEndian();
3380 // Bitcast 'large element' scalar/vector to 'small element' vector.
3381 if ((SrcBits % VTBits) == 0) {
3382 assert(VT.isVector() && "Expected bitcast to vector");
3384 unsigned Scale = SrcBits / VTBits;
3385 APInt SrcDemandedElts(NumElts / Scale, 0);
3386 for (unsigned i = 0; i != NumElts; ++i)
3387 if (DemandedElts[i])
3388 SrcDemandedElts.setBit(i / Scale);
3390 // Fast case - sign splat can be simply split across the small elements.
3391 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3392 if (Tmp == SrcBits)
3393 return VTBits;
3395 // Slow case - determine how far the sign extends into each sub-element.
3396 Tmp2 = VTBits;
3397 for (unsigned i = 0; i != NumElts; ++i)
3398 if (DemandedElts[i]) {
3399 unsigned SubOffset = i % Scale;
3400 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3401 SubOffset = SubOffset * VTBits;
3402 if (Tmp <= SubOffset)
3403 return 1;
3404 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3406 return Tmp2;
3408 break;
3411 case ISD::SIGN_EXTEND:
3412 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3413 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3414 case ISD::SIGN_EXTEND_INREG:
3415 // Max of the input and what this extends.
3416 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3417 Tmp = VTBits-Tmp+1;
3418 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3419 return std::max(Tmp, Tmp2);
3420 case ISD::SIGN_EXTEND_VECTOR_INREG: {
3421 SDValue Src = Op.getOperand(0);
3422 EVT SrcVT = Src.getValueType();
3423 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3424 Tmp = VTBits - SrcVT.getScalarSizeInBits();
3425 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3428 case ISD::SRA:
3429 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3430 // SRA X, C -> adds C sign bits.
3431 if (ConstantSDNode *C =
3432 isConstOrDemandedConstSplat(Op.getOperand(1), DemandedElts)) {
3433 APInt ShiftVal = C->getAPIntValue();
3434 ShiftVal += Tmp;
3435 Tmp = ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
3437 return Tmp;
3438 case ISD::SHL:
3439 if (ConstantSDNode *C =
3440 isConstOrDemandedConstSplat(Op.getOperand(1), DemandedElts)) {
3441 // shl destroys sign bits.
3442 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3443 if (C->getAPIntValue().uge(VTBits) || // Bad shift.
3444 C->getAPIntValue().uge(Tmp)) break; // Shifted all sign bits out.
3445 return Tmp - C->getZExtValue();
3447 break;
3448 case ISD::AND:
3449 case ISD::OR:
3450 case ISD::XOR: // NOT is handled here.
3451 // Logical binary ops preserve the number of sign bits at the worst.
3452 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3453 if (Tmp != 1) {
3454 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3455 FirstAnswer = std::min(Tmp, Tmp2);
3456 // We computed what we know about the sign bits as our first
3457 // answer. Now proceed to the generic code that uses
3458 // computeKnownBits, and pick whichever answer is better.
3460 break;
3462 case ISD::SELECT:
3463 case ISD::VSELECT:
3464 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3465 if (Tmp == 1) return 1; // Early out.
3466 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3467 return std::min(Tmp, Tmp2);
3468 case ISD::SELECT_CC:
3469 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3470 if (Tmp == 1) return 1; // Early out.
3471 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3472 return std::min(Tmp, Tmp2);
3474 case ISD::SMIN:
3475 case ISD::SMAX: {
3476 // If we have a clamp pattern, we know that the number of sign bits will be
3477 // the minimum of the clamp min/max range.
3478 bool IsMax = (Opcode == ISD::SMAX);
3479 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3480 if ((CstLow = isConstOrDemandedConstSplat(Op.getOperand(1), DemandedElts)))
3481 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3482 CstHigh = isConstOrDemandedConstSplat(Op.getOperand(0).getOperand(1),
3483 DemandedElts);
3484 if (CstLow && CstHigh) {
3485 if (!IsMax)
3486 std::swap(CstLow, CstHigh);
3487 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3488 Tmp = CstLow->getAPIntValue().getNumSignBits();
3489 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3490 return std::min(Tmp, Tmp2);
3494 // Fallback - just get the minimum number of sign bits of the operands.
3495 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3496 if (Tmp == 1)
3497 return 1; // Early out.
3498 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3499 return std::min(Tmp, Tmp2);
3501 case ISD::UMIN:
3502 case ISD::UMAX:
3503 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3504 if (Tmp == 1)
3505 return 1; // Early out.
3506 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3507 return std::min(Tmp, Tmp2);
3508 case ISD::SADDO:
3509 case ISD::UADDO:
3510 case ISD::SSUBO:
3511 case ISD::USUBO:
3512 case ISD::SMULO:
3513 case ISD::UMULO:
3514 if (Op.getResNo() != 1)
3515 break;
3516 // The boolean result conforms to getBooleanContents. Fall through.
3517 // If setcc returns 0/-1, all bits are sign bits.
3518 // We know that we have an integer-based boolean since these operations
3519 // are only available for integer.
3520 if (TLI->getBooleanContents(VT.isVector(), false) ==
3521 TargetLowering::ZeroOrNegativeOneBooleanContent)
3522 return VTBits;
3523 break;
3524 case ISD::SETCC:
3525 // If setcc returns 0/-1, all bits are sign bits.
3526 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3527 TargetLowering::ZeroOrNegativeOneBooleanContent)
3528 return VTBits;
3529 break;
3530 case ISD::ROTL:
3531 case ISD::ROTR:
3532 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3533 unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3535 // Handle rotate right by N like a rotate left by 32-N.
3536 if (Opcode == ISD::ROTR)
3537 RotAmt = (VTBits - RotAmt) % VTBits;
3539 // If we aren't rotating out all of the known-in sign bits, return the
3540 // number that are left. This handles rotl(sext(x), 1) for example.
3541 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3542 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3544 break;
3545 case ISD::ADD:
3546 case ISD::ADDC:
3547 // Add can have at most one carry bit. Thus we know that the output
3548 // is, at worst, one more bit than the inputs.
3549 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3550 if (Tmp == 1) return 1; // Early out.
3552 // Special case decrementing a value (ADD X, -1):
3553 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3554 if (CRHS->isAllOnesValue()) {
3555 KnownBits Known = computeKnownBits(Op.getOperand(0), Depth+1);
3557 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3558 // sign bits set.
3559 if ((Known.Zero | 1).isAllOnesValue())
3560 return VTBits;
3562 // If we are subtracting one from a positive number, there is no carry
3563 // out of the result.
3564 if (Known.isNonNegative())
3565 return Tmp;
3568 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3569 if (Tmp2 == 1) return 1;
3570 return std::min(Tmp, Tmp2)-1;
3572 case ISD::SUB:
3573 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3574 if (Tmp2 == 1) return 1;
3576 // Handle NEG.
3577 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0)))
3578 if (CLHS->isNullValue()) {
3579 KnownBits Known = computeKnownBits(Op.getOperand(1), Depth+1);
3580 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3581 // sign bits set.
3582 if ((Known.Zero | 1).isAllOnesValue())
3583 return VTBits;
3585 // If the input is known to be positive (the sign bit is known clear),
3586 // the output of the NEG has the same number of sign bits as the input.
3587 if (Known.isNonNegative())
3588 return Tmp2;
3590 // Otherwise, we treat this like a SUB.
3593 // Sub can have at most one carry bit. Thus we know that the output
3594 // is, at worst, one more bit than the inputs.
3595 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3596 if (Tmp == 1) return 1; // Early out.
3597 return std::min(Tmp, Tmp2)-1;
3598 case ISD::TRUNCATE: {
3599 // Check if the sign bits of source go down as far as the truncated value.
3600 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3601 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3602 if (NumSrcSignBits > (NumSrcBits - VTBits))
3603 return NumSrcSignBits - (NumSrcBits - VTBits);
3604 break;
3606 case ISD::EXTRACT_ELEMENT: {
3607 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3608 const int BitWidth = Op.getValueSizeInBits();
3609 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3611 // Get reverse index (starting from 1), Op1 value indexes elements from
3612 // little end. Sign starts at big end.
3613 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3615 // If the sign portion ends in our element the subtraction gives correct
3616 // result. Otherwise it gives either negative or > bitwidth result
3617 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3619 case ISD::INSERT_VECTOR_ELT: {
3620 SDValue InVec = Op.getOperand(0);
3621 SDValue InVal = Op.getOperand(1);
3622 SDValue EltNo = Op.getOperand(2);
3623 unsigned NumElts = InVec.getValueType().getVectorNumElements();
3625 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3626 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3627 // If we know the element index, split the demand between the
3628 // source vector and the inserted element.
3629 unsigned EltIdx = CEltNo->getZExtValue();
3631 // If we demand the inserted element then get its sign bits.
3632 Tmp = std::numeric_limits<unsigned>::max();
3633 if (DemandedElts[EltIdx]) {
3634 // TODO - handle implicit truncation of inserted elements.
3635 if (InVal.getScalarValueSizeInBits() != VTBits)
3636 break;
3637 Tmp = ComputeNumSignBits(InVal, Depth + 1);
3640 // If we demand the source vector then get its sign bits, and determine
3641 // the minimum.
3642 APInt VectorElts = DemandedElts;
3643 VectorElts.clearBit(EltIdx);
3644 if (!!VectorElts) {
3645 Tmp2 = ComputeNumSignBits(InVec, VectorElts, Depth + 1);
3646 Tmp = std::min(Tmp, Tmp2);
3648 } else {
3649 // Unknown element index, so ignore DemandedElts and demand them all.
3650 Tmp = ComputeNumSignBits(InVec, Depth + 1);
3651 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
3652 Tmp = std::min(Tmp, Tmp2);
3654 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3655 return Tmp;
3657 case ISD::EXTRACT_VECTOR_ELT: {
3658 SDValue InVec = Op.getOperand(0);
3659 SDValue EltNo = Op.getOperand(1);
3660 EVT VecVT = InVec.getValueType();
3661 const unsigned BitWidth = Op.getValueSizeInBits();
3662 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
3663 const unsigned NumSrcElts = VecVT.getVectorNumElements();
3665 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
3666 // anything about sign bits. But if the sizes match we can derive knowledge
3667 // about sign bits from the vector operand.
3668 if (BitWidth != EltBitWidth)
3669 break;
3671 // If we know the element index, just demand that vector element, else for
3672 // an unknown element index, ignore DemandedElts and demand them all.
3673 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3674 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3675 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3676 DemandedSrcElts =
3677 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3679 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
3681 case ISD::EXTRACT_SUBVECTOR: {
3682 // If we know the element index, just demand that subvector elements,
3683 // otherwise demand them all.
3684 SDValue Src = Op.getOperand(0);
3685 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
3686 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3687 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
3688 // Offset the demanded elts by the subvector index.
3689 uint64_t Idx = SubIdx->getZExtValue();
3690 APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
3691 return ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
3693 return ComputeNumSignBits(Src, Depth + 1);
3695 case ISD::CONCAT_VECTORS: {
3696 // Determine the minimum number of sign bits across all demanded
3697 // elts of the input vectors. Early out if the result is already 1.
3698 Tmp = std::numeric_limits<unsigned>::max();
3699 EVT SubVectorVT = Op.getOperand(0).getValueType();
3700 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3701 unsigned NumSubVectors = Op.getNumOperands();
3702 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
3703 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
3704 DemandedSub = DemandedSub.trunc(NumSubVectorElts);
3705 if (!DemandedSub)
3706 continue;
3707 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
3708 Tmp = std::min(Tmp, Tmp2);
3710 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3711 return Tmp;
3713 case ISD::INSERT_SUBVECTOR: {
3714 // If we know the element index, demand any elements from the subvector and
3715 // the remainder from the src its inserted into, otherwise demand them all.
3716 SDValue Src = Op.getOperand(0);
3717 SDValue Sub = Op.getOperand(1);
3718 auto *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3719 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3720 if (SubIdx && SubIdx->getAPIntValue().ule(NumElts - NumSubElts)) {
3721 Tmp = std::numeric_limits<unsigned>::max();
3722 uint64_t Idx = SubIdx->getZExtValue();
3723 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3724 if (!!DemandedSubElts) {
3725 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
3726 if (Tmp == 1) return 1; // early-out
3728 APInt SubMask = APInt::getBitsSet(NumElts, Idx, Idx + NumSubElts);
3729 APInt DemandedSrcElts = DemandedElts & ~SubMask;
3730 if (!!DemandedSrcElts) {
3731 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
3732 Tmp = std::min(Tmp, Tmp2);
3734 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3735 return Tmp;
3738 // Not able to determine the index so just assume worst case.
3739 Tmp = ComputeNumSignBits(Sub, Depth + 1);
3740 if (Tmp == 1) return 1; // early-out
3741 Tmp2 = ComputeNumSignBits(Src, Depth + 1);
3742 Tmp = std::min(Tmp, Tmp2);
3743 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3744 return Tmp;
3748 // If we are looking at the loaded value of the SDNode.
3749 if (Op.getResNo() == 0) {
3750 // Handle LOADX separately here. EXTLOAD case will fallthrough.
3751 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
3752 unsigned ExtType = LD->getExtensionType();
3753 switch (ExtType) {
3754 default: break;
3755 case ISD::SEXTLOAD: // '17' bits known
3756 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3757 return VTBits-Tmp+1;
3758 case ISD::ZEXTLOAD: // '16' bits known
3759 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3760 return VTBits-Tmp;
3765 // Allow the target to implement this method for its nodes.
3766 if (Opcode >= ISD::BUILTIN_OP_END ||
3767 Opcode == ISD::INTRINSIC_WO_CHAIN ||
3768 Opcode == ISD::INTRINSIC_W_CHAIN ||
3769 Opcode == ISD::INTRINSIC_VOID) {
3770 unsigned NumBits =
3771 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
3772 if (NumBits > 1)
3773 FirstAnswer = std::max(FirstAnswer, NumBits);
3776 // Finally, if we can prove that the top bits of the result are 0's or 1's,
3777 // use this information.
3778 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
3780 APInt Mask;
3781 if (Known.isNonNegative()) { // sign bit is 0
3782 Mask = Known.Zero;
3783 } else if (Known.isNegative()) { // sign bit is 1;
3784 Mask = Known.One;
3785 } else {
3786 // Nothing known.
3787 return FirstAnswer;
3790 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
3791 // the number of identical bits in the top of the input value.
3792 Mask = ~Mask;
3793 Mask <<= Mask.getBitWidth()-VTBits;
3794 // Return # leading zeros. We use 'min' here in case Val was zero before
3795 // shifting. We don't want to return '64' as for an i32 "0".
3796 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
3799 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
3800 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
3801 !isa<ConstantSDNode>(Op.getOperand(1)))
3802 return false;
3804 if (Op.getOpcode() == ISD::OR &&
3805 !MaskedValueIsZero(Op.getOperand(0),
3806 cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue()))
3807 return false;
3809 return true;
3812 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
3813 // If we're told that NaNs won't happen, assume they won't.
3814 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
3815 return true;
3817 if (Depth == 6)
3818 return false; // Limit search depth.
3820 // TODO: Handle vectors.
3821 // If the value is a constant, we can obviously see if it is a NaN or not.
3822 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
3823 return !C->getValueAPF().isNaN() ||
3824 (SNaN && !C->getValueAPF().isSignaling());
3827 unsigned Opcode = Op.getOpcode();
3828 switch (Opcode) {
3829 case ISD::FADD:
3830 case ISD::FSUB:
3831 case ISD::FMUL:
3832 case ISD::FDIV:
3833 case ISD::FREM:
3834 case ISD::FSIN:
3835 case ISD::FCOS: {
3836 if (SNaN)
3837 return true;
3838 // TODO: Need isKnownNeverInfinity
3839 return false;
3841 case ISD::FCANONICALIZE:
3842 case ISD::FEXP:
3843 case ISD::FEXP2:
3844 case ISD::FTRUNC:
3845 case ISD::FFLOOR:
3846 case ISD::FCEIL:
3847 case ISD::FROUND:
3848 case ISD::FRINT:
3849 case ISD::FNEARBYINT: {
3850 if (SNaN)
3851 return true;
3852 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
3854 case ISD::FABS:
3855 case ISD::FNEG:
3856 case ISD::FCOPYSIGN: {
3857 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
3859 case ISD::SELECT:
3860 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
3861 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
3862 case ISD::FP_EXTEND:
3863 case ISD::FP_ROUND: {
3864 if (SNaN)
3865 return true;
3866 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
3868 case ISD::SINT_TO_FP:
3869 case ISD::UINT_TO_FP:
3870 return true;
3871 case ISD::FMA:
3872 case ISD::FMAD: {
3873 if (SNaN)
3874 return true;
3875 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
3876 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
3877 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
3879 case ISD::FSQRT: // Need is known positive
3880 case ISD::FLOG:
3881 case ISD::FLOG2:
3882 case ISD::FLOG10:
3883 case ISD::FPOWI:
3884 case ISD::FPOW: {
3885 if (SNaN)
3886 return true;
3887 // TODO: Refine on operand
3888 return false;
3890 case ISD::FMINNUM:
3891 case ISD::FMAXNUM: {
3892 // Only one needs to be known not-nan, since it will be returned if the
3893 // other ends up being one.
3894 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
3895 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
3897 case ISD::FMINNUM_IEEE:
3898 case ISD::FMAXNUM_IEEE: {
3899 if (SNaN)
3900 return true;
3901 // This can return a NaN if either operand is an sNaN, or if both operands
3902 // are NaN.
3903 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
3904 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
3905 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
3906 isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
3908 case ISD::FMINIMUM:
3909 case ISD::FMAXIMUM: {
3910 // TODO: Does this quiet or return the origina NaN as-is?
3911 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
3912 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
3914 case ISD::EXTRACT_VECTOR_ELT: {
3915 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
3917 default:
3918 if (Opcode >= ISD::BUILTIN_OP_END ||
3919 Opcode == ISD::INTRINSIC_WO_CHAIN ||
3920 Opcode == ISD::INTRINSIC_W_CHAIN ||
3921 Opcode == ISD::INTRINSIC_VOID) {
3922 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
3925 return false;
3929 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
3930 assert(Op.getValueType().isFloatingPoint() &&
3931 "Floating point type expected");
3933 // If the value is a constant, we can obviously see if it is a zero or not.
3934 // TODO: Add BuildVector support.
3935 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
3936 return !C->isZero();
3937 return false;
3940 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
3941 assert(!Op.getValueType().isFloatingPoint() &&
3942 "Floating point types unsupported - use isKnownNeverZeroFloat");
3944 // If the value is a constant, we can obviously see if it is a zero or not.
3945 if (ISD::matchUnaryPredicate(
3946 Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
3947 return true;
3949 // TODO: Recognize more cases here.
3950 switch (Op.getOpcode()) {
3951 default: break;
3952 case ISD::OR:
3953 if (isKnownNeverZero(Op.getOperand(1)) ||
3954 isKnownNeverZero(Op.getOperand(0)))
3955 return true;
3956 break;
3959 return false;
3962 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
3963 // Check the obvious case.
3964 if (A == B) return true;
3966 // For for negative and positive zero.
3967 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
3968 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
3969 if (CA->isZero() && CB->isZero()) return true;
3971 // Otherwise they may not be equal.
3972 return false;
3975 // FIXME: unify with llvm::haveNoCommonBitsSet.
3976 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
3977 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
3978 assert(A.getValueType() == B.getValueType() &&
3979 "Values must have the same type");
3980 return (computeKnownBits(A).Zero | computeKnownBits(B).Zero).isAllOnesValue();
3983 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
3984 ArrayRef<SDValue> Ops,
3985 SelectionDAG &DAG) {
3986 int NumOps = Ops.size();
3987 assert(NumOps != 0 && "Can't build an empty vector!");
3988 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
3989 "Incorrect element count in BUILD_VECTOR!");
3991 // BUILD_VECTOR of UNDEFs is UNDEF.
3992 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
3993 return DAG.getUNDEF(VT);
3995 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
3996 SDValue IdentitySrc;
3997 bool IsIdentity = true;
3998 for (int i = 0; i != NumOps; ++i) {
3999 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4000 Ops[i].getOperand(0).getValueType() != VT ||
4001 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4002 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4003 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4004 IsIdentity = false;
4005 break;
4007 IdentitySrc = Ops[i].getOperand(0);
4009 if (IsIdentity)
4010 return IdentitySrc;
4012 return SDValue();
4015 static SDValue FoldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4016 ArrayRef<SDValue> Ops,
4017 SelectionDAG &DAG) {
4018 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4019 assert(llvm::all_of(Ops,
4020 [Ops](SDValue Op) {
4021 return Ops[0].getValueType() == Op.getValueType();
4022 }) &&
4023 "Concatenation of vectors with inconsistent value types!");
4024 assert((Ops.size() * Ops[0].getValueType().getVectorNumElements()) ==
4025 VT.getVectorNumElements() &&
4026 "Incorrect element count in vector concatenation!");
4028 if (Ops.size() == 1)
4029 return Ops[0];
4031 // Concat of UNDEFs is UNDEF.
4032 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4033 return DAG.getUNDEF(VT);
4035 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4036 // simplified to one big BUILD_VECTOR.
4037 // FIXME: Add support for SCALAR_TO_VECTOR as well.
4038 EVT SVT = VT.getScalarType();
4039 SmallVector<SDValue, 16> Elts;
4040 for (SDValue Op : Ops) {
4041 EVT OpVT = Op.getValueType();
4042 if (Op.isUndef())
4043 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4044 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4045 Elts.append(Op->op_begin(), Op->op_end());
4046 else
4047 return SDValue();
4050 // BUILD_VECTOR requires all inputs to be of the same type, find the
4051 // maximum type and extend them all.
4052 for (SDValue Op : Elts)
4053 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4055 if (SVT.bitsGT(VT.getScalarType()))
4056 for (SDValue &Op : Elts)
4057 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4058 ? DAG.getZExtOrTrunc(Op, DL, SVT)
4059 : DAG.getSExtOrTrunc(Op, DL, SVT);
4061 SDValue V = DAG.getBuildVector(VT, DL, Elts);
4062 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4063 return V;
4066 /// Gets or creates the specified node.
4067 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4068 FoldingSetNodeID ID;
4069 AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4070 void *IP = nullptr;
4071 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4072 return SDValue(E, 0);
4074 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4075 getVTList(VT));
4076 CSEMap.InsertNode(N, IP);
4078 InsertNode(N);
4079 SDValue V = SDValue(N, 0);
4080 NewSDValueDbgMsg(V, "Creating new node: ", this);
4081 return V;
4084 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4085 SDValue Operand, const SDNodeFlags Flags) {
4086 // Constant fold unary operations with an integer constant operand. Even
4087 // opaque constant will be folded, because the folding of unary operations
4088 // doesn't create new constants with different values. Nevertheless, the
4089 // opaque flag is preserved during folding to prevent future folding with
4090 // other constants.
4091 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4092 const APInt &Val = C->getAPIntValue();
4093 switch (Opcode) {
4094 default: break;
4095 case ISD::SIGN_EXTEND:
4096 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4097 C->isTargetOpcode(), C->isOpaque());
4098 case ISD::TRUNCATE:
4099 if (C->isOpaque())
4100 break;
4101 LLVM_FALLTHROUGH;
4102 case ISD::ANY_EXTEND:
4103 case ISD::ZERO_EXTEND:
4104 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4105 C->isTargetOpcode(), C->isOpaque());
4106 case ISD::UINT_TO_FP:
4107 case ISD::SINT_TO_FP: {
4108 APFloat apf(EVTToAPFloatSemantics(VT),
4109 APInt::getNullValue(VT.getSizeInBits()));
4110 (void)apf.convertFromAPInt(Val,
4111 Opcode==ISD::SINT_TO_FP,
4112 APFloat::rmNearestTiesToEven);
4113 return getConstantFP(apf, DL, VT);
4115 case ISD::BITCAST:
4116 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4117 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4118 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4119 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4120 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4121 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4122 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4123 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4124 break;
4125 case ISD::ABS:
4126 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4127 C->isOpaque());
4128 case ISD::BITREVERSE:
4129 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4130 C->isOpaque());
4131 case ISD::BSWAP:
4132 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4133 C->isOpaque());
4134 case ISD::CTPOP:
4135 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4136 C->isOpaque());
4137 case ISD::CTLZ:
4138 case ISD::CTLZ_ZERO_UNDEF:
4139 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4140 C->isOpaque());
4141 case ISD::CTTZ:
4142 case ISD::CTTZ_ZERO_UNDEF:
4143 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4144 C->isOpaque());
4145 case ISD::FP16_TO_FP: {
4146 bool Ignored;
4147 APFloat FPV(APFloat::IEEEhalf(),
4148 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4150 // This can return overflow, underflow, or inexact; we don't care.
4151 // FIXME need to be more flexible about rounding mode.
4152 (void)FPV.convert(EVTToAPFloatSemantics(VT),
4153 APFloat::rmNearestTiesToEven, &Ignored);
4154 return getConstantFP(FPV, DL, VT);
4159 // Constant fold unary operations with a floating point constant operand.
4160 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4161 APFloat V = C->getValueAPF(); // make copy
4162 switch (Opcode) {
4163 case ISD::FNEG:
4164 V.changeSign();
4165 return getConstantFP(V, DL, VT);
4166 case ISD::FABS:
4167 V.clearSign();
4168 return getConstantFP(V, DL, VT);
4169 case ISD::FCEIL: {
4170 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4171 if (fs == APFloat::opOK || fs == APFloat::opInexact)
4172 return getConstantFP(V, DL, VT);
4173 break;
4175 case ISD::FTRUNC: {
4176 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4177 if (fs == APFloat::opOK || fs == APFloat::opInexact)
4178 return getConstantFP(V, DL, VT);
4179 break;
4181 case ISD::FFLOOR: {
4182 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4183 if (fs == APFloat::opOK || fs == APFloat::opInexact)
4184 return getConstantFP(V, DL, VT);
4185 break;
4187 case ISD::FP_EXTEND: {
4188 bool ignored;
4189 // This can return overflow, underflow, or inexact; we don't care.
4190 // FIXME need to be more flexible about rounding mode.
4191 (void)V.convert(EVTToAPFloatSemantics(VT),
4192 APFloat::rmNearestTiesToEven, &ignored);
4193 return getConstantFP(V, DL, VT);
4195 case ISD::FP_TO_SINT:
4196 case ISD::FP_TO_UINT: {
4197 bool ignored;
4198 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4199 // FIXME need to be more flexible about rounding mode.
4200 APFloat::opStatus s =
4201 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4202 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4203 break;
4204 return getConstant(IntVal, DL, VT);
4206 case ISD::BITCAST:
4207 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4208 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4209 else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4210 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4211 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4212 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4213 break;
4214 case ISD::FP_TO_FP16: {
4215 bool Ignored;
4216 // This can return overflow, underflow, or inexact; we don't care.
4217 // FIXME need to be more flexible about rounding mode.
4218 (void)V.convert(APFloat::IEEEhalf(),
4219 APFloat::rmNearestTiesToEven, &Ignored);
4220 return getConstant(V.bitcastToAPInt(), DL, VT);
4225 // Constant fold unary operations with a vector integer or float operand.
4226 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
4227 if (BV->isConstant()) {
4228 switch (Opcode) {
4229 default:
4230 // FIXME: Entirely reasonable to perform folding of other unary
4231 // operations here as the need arises.
4232 break;
4233 case ISD::FNEG:
4234 case ISD::FABS:
4235 case ISD::FCEIL:
4236 case ISD::FTRUNC:
4237 case ISD::FFLOOR:
4238 case ISD::FP_EXTEND:
4239 case ISD::FP_TO_SINT:
4240 case ISD::FP_TO_UINT:
4241 case ISD::TRUNCATE:
4242 case ISD::ANY_EXTEND:
4243 case ISD::ZERO_EXTEND:
4244 case ISD::SIGN_EXTEND:
4245 case ISD::UINT_TO_FP:
4246 case ISD::SINT_TO_FP:
4247 case ISD::ABS:
4248 case ISD::BITREVERSE:
4249 case ISD::BSWAP:
4250 case ISD::CTLZ:
4251 case ISD::CTLZ_ZERO_UNDEF:
4252 case ISD::CTTZ:
4253 case ISD::CTTZ_ZERO_UNDEF:
4254 case ISD::CTPOP: {
4255 SDValue Ops = { Operand };
4256 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4257 return Fold;
4263 unsigned OpOpcode = Operand.getNode()->getOpcode();
4264 switch (Opcode) {
4265 case ISD::TokenFactor:
4266 case ISD::MERGE_VALUES:
4267 case ISD::CONCAT_VECTORS:
4268 return Operand; // Factor, merge or concat of one node? No need.
4269 case ISD::BUILD_VECTOR: {
4270 // Attempt to simplify BUILD_VECTOR.
4271 SDValue Ops[] = {Operand};
4272 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4273 return V;
4274 break;
4276 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4277 case ISD::FP_EXTEND:
4278 assert(VT.isFloatingPoint() &&
4279 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4280 if (Operand.getValueType() == VT) return Operand; // noop conversion.
4281 assert((!VT.isVector() ||
4282 VT.getVectorNumElements() ==
4283 Operand.getValueType().getVectorNumElements()) &&
4284 "Vector element count mismatch!");
4285 assert(Operand.getValueType().bitsLT(VT) &&
4286 "Invalid fpext node, dst < src!");
4287 if (Operand.isUndef())
4288 return getUNDEF(VT);
4289 break;
4290 case ISD::SIGN_EXTEND:
4291 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4292 "Invalid SIGN_EXTEND!");
4293 if (Operand.getValueType() == VT) return Operand; // noop extension
4294 assert((!VT.isVector() ||
4295 VT.getVectorNumElements() ==
4296 Operand.getValueType().getVectorNumElements()) &&
4297 "Vector element count mismatch!");
4298 assert(Operand.getValueType().bitsLT(VT) &&
4299 "Invalid sext node, dst < src!");
4300 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4301 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4302 else if (OpOpcode == ISD::UNDEF)
4303 // sext(undef) = 0, because the top bits will all be the same.
4304 return getConstant(0, DL, VT);
4305 break;
4306 case ISD::ZERO_EXTEND:
4307 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4308 "Invalid ZERO_EXTEND!");
4309 if (Operand.getValueType() == VT) return Operand; // noop extension
4310 assert((!VT.isVector() ||
4311 VT.getVectorNumElements() ==
4312 Operand.getValueType().getVectorNumElements()) &&
4313 "Vector element count mismatch!");
4314 assert(Operand.getValueType().bitsLT(VT) &&
4315 "Invalid zext node, dst < src!");
4316 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
4317 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4318 else if (OpOpcode == ISD::UNDEF)
4319 // zext(undef) = 0, because the top bits will be zero.
4320 return getConstant(0, DL, VT);
4321 break;
4322 case ISD::ANY_EXTEND:
4323 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4324 "Invalid ANY_EXTEND!");
4325 if (Operand.getValueType() == VT) return Operand; // noop extension
4326 assert((!VT.isVector() ||
4327 VT.getVectorNumElements() ==
4328 Operand.getValueType().getVectorNumElements()) &&
4329 "Vector element count mismatch!");
4330 assert(Operand.getValueType().bitsLT(VT) &&
4331 "Invalid anyext node, dst < src!");
4333 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4334 OpOpcode == ISD::ANY_EXTEND)
4335 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
4336 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4337 else if (OpOpcode == ISD::UNDEF)
4338 return getUNDEF(VT);
4340 // (ext (trunc x)) -> x
4341 if (OpOpcode == ISD::TRUNCATE) {
4342 SDValue OpOp = Operand.getOperand(0);
4343 if (OpOp.getValueType() == VT) {
4344 transferDbgValues(Operand, OpOp);
4345 return OpOp;
4348 break;
4349 case ISD::TRUNCATE:
4350 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4351 "Invalid TRUNCATE!");
4352 if (Operand.getValueType() == VT) return Operand; // noop truncate
4353 assert((!VT.isVector() ||
4354 VT.getVectorNumElements() ==
4355 Operand.getValueType().getVectorNumElements()) &&
4356 "Vector element count mismatch!");
4357 assert(Operand.getValueType().bitsGT(VT) &&
4358 "Invalid truncate node, src < dst!");
4359 if (OpOpcode == ISD::TRUNCATE)
4360 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4361 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4362 OpOpcode == ISD::ANY_EXTEND) {
4363 // If the source is smaller than the dest, we still need an extend.
4364 if (Operand.getOperand(0).getValueType().getScalarType()
4365 .bitsLT(VT.getScalarType()))
4366 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4367 if (Operand.getOperand(0).getValueType().bitsGT(VT))
4368 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4369 return Operand.getOperand(0);
4371 if (OpOpcode == ISD::UNDEF)
4372 return getUNDEF(VT);
4373 break;
4374 case ISD::ANY_EXTEND_VECTOR_INREG:
4375 case ISD::ZERO_EXTEND_VECTOR_INREG:
4376 case ISD::SIGN_EXTEND_VECTOR_INREG:
4377 assert(VT.isVector() && "This DAG node is restricted to vector types.");
4378 assert(Operand.getValueType().bitsLE(VT) &&
4379 "The input must be the same size or smaller than the result.");
4380 assert(VT.getVectorNumElements() <
4381 Operand.getValueType().getVectorNumElements() &&
4382 "The destination vector type must have fewer lanes than the input.");
4383 break;
4384 case ISD::ABS:
4385 assert(VT.isInteger() && VT == Operand.getValueType() &&
4386 "Invalid ABS!");
4387 if (OpOpcode == ISD::UNDEF)
4388 return getUNDEF(VT);
4389 break;
4390 case ISD::BSWAP:
4391 assert(VT.isInteger() && VT == Operand.getValueType() &&
4392 "Invalid BSWAP!");
4393 assert((VT.getScalarSizeInBits() % 16 == 0) &&
4394 "BSWAP types must be a multiple of 16 bits!");
4395 if (OpOpcode == ISD::UNDEF)
4396 return getUNDEF(VT);
4397 break;
4398 case ISD::BITREVERSE:
4399 assert(VT.isInteger() && VT == Operand.getValueType() &&
4400 "Invalid BITREVERSE!");
4401 if (OpOpcode == ISD::UNDEF)
4402 return getUNDEF(VT);
4403 break;
4404 case ISD::BITCAST:
4405 // Basic sanity checking.
4406 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
4407 "Cannot BITCAST between types of different sizes!");
4408 if (VT == Operand.getValueType()) return Operand; // noop conversion.
4409 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
4410 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
4411 if (OpOpcode == ISD::UNDEF)
4412 return getUNDEF(VT);
4413 break;
4414 case ISD::SCALAR_TO_VECTOR:
4415 assert(VT.isVector() && !Operand.getValueType().isVector() &&
4416 (VT.getVectorElementType() == Operand.getValueType() ||
4417 (VT.getVectorElementType().isInteger() &&
4418 Operand.getValueType().isInteger() &&
4419 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
4420 "Illegal SCALAR_TO_VECTOR node!");
4421 if (OpOpcode == ISD::UNDEF)
4422 return getUNDEF(VT);
4423 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
4424 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
4425 isa<ConstantSDNode>(Operand.getOperand(1)) &&
4426 Operand.getConstantOperandVal(1) == 0 &&
4427 Operand.getOperand(0).getValueType() == VT)
4428 return Operand.getOperand(0);
4429 break;
4430 case ISD::FNEG:
4431 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
4432 if ((getTarget().Options.UnsafeFPMath || Flags.hasNoSignedZeros()) &&
4433 OpOpcode == ISD::FSUB)
4434 return getNode(ISD::FSUB, DL, VT, Operand.getOperand(1),
4435 Operand.getOperand(0), Flags);
4436 if (OpOpcode == ISD::FNEG) // --X -> X
4437 return Operand.getOperand(0);
4438 break;
4439 case ISD::FABS:
4440 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
4441 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
4442 break;
4445 SDNode *N;
4446 SDVTList VTs = getVTList(VT);
4447 SDValue Ops[] = {Operand};
4448 if (VT != MVT::Glue) { // Don't CSE flag producing nodes
4449 FoldingSetNodeID ID;
4450 AddNodeIDNode(ID, Opcode, VTs, Ops);
4451 void *IP = nullptr;
4452 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4453 E->intersectFlagsWith(Flags);
4454 return SDValue(E, 0);
4457 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4458 N->setFlags(Flags);
4459 createOperands(N, Ops);
4460 CSEMap.InsertNode(N, IP);
4461 } else {
4462 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4463 createOperands(N, Ops);
4466 InsertNode(N);
4467 SDValue V = SDValue(N, 0);
4468 NewSDValueDbgMsg(V, "Creating new node: ", this);
4469 return V;
4472 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1,
4473 const APInt &C2) {
4474 switch (Opcode) {
4475 case ISD::ADD: return std::make_pair(C1 + C2, true);
4476 case ISD::SUB: return std::make_pair(C1 - C2, true);
4477 case ISD::MUL: return std::make_pair(C1 * C2, true);
4478 case ISD::AND: return std::make_pair(C1 & C2, true);
4479 case ISD::OR: return std::make_pair(C1 | C2, true);
4480 case ISD::XOR: return std::make_pair(C1 ^ C2, true);
4481 case ISD::SHL: return std::make_pair(C1 << C2, true);
4482 case ISD::SRL: return std::make_pair(C1.lshr(C2), true);
4483 case ISD::SRA: return std::make_pair(C1.ashr(C2), true);
4484 case ISD::ROTL: return std::make_pair(C1.rotl(C2), true);
4485 case ISD::ROTR: return std::make_pair(C1.rotr(C2), true);
4486 case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true);
4487 case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true);
4488 case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true);
4489 case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true);
4490 case ISD::SADDSAT: return std::make_pair(C1.sadd_sat(C2), true);
4491 case ISD::UADDSAT: return std::make_pair(C1.uadd_sat(C2), true);
4492 case ISD::SSUBSAT: return std::make_pair(C1.ssub_sat(C2), true);
4493 case ISD::USUBSAT: return std::make_pair(C1.usub_sat(C2), true);
4494 case ISD::UDIV:
4495 if (!C2.getBoolValue())
4496 break;
4497 return std::make_pair(C1.udiv(C2), true);
4498 case ISD::UREM:
4499 if (!C2.getBoolValue())
4500 break;
4501 return std::make_pair(C1.urem(C2), true);
4502 case ISD::SDIV:
4503 if (!C2.getBoolValue())
4504 break;
4505 return std::make_pair(C1.sdiv(C2), true);
4506 case ISD::SREM:
4507 if (!C2.getBoolValue())
4508 break;
4509 return std::make_pair(C1.srem(C2), true);
4511 return std::make_pair(APInt(1, 0), false);
4514 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
4515 EVT VT, const ConstantSDNode *C1,
4516 const ConstantSDNode *C2) {
4517 if (C1->isOpaque() || C2->isOpaque())
4518 return SDValue();
4520 std::pair<APInt, bool> Folded = FoldValue(Opcode, C1->getAPIntValue(),
4521 C2->getAPIntValue());
4522 if (!Folded.second)
4523 return SDValue();
4524 return getConstant(Folded.first, DL, VT);
4527 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
4528 const GlobalAddressSDNode *GA,
4529 const SDNode *N2) {
4530 if (GA->getOpcode() != ISD::GlobalAddress)
4531 return SDValue();
4532 if (!TLI->isOffsetFoldingLegal(GA))
4533 return SDValue();
4534 auto *C2 = dyn_cast<ConstantSDNode>(N2);
4535 if (!C2)
4536 return SDValue();
4537 int64_t Offset = C2->getSExtValue();
4538 switch (Opcode) {
4539 case ISD::ADD: break;
4540 case ISD::SUB: Offset = -uint64_t(Offset); break;
4541 default: return SDValue();
4543 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
4544 GA->getOffset() + uint64_t(Offset));
4547 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
4548 switch (Opcode) {
4549 case ISD::SDIV:
4550 case ISD::UDIV:
4551 case ISD::SREM:
4552 case ISD::UREM: {
4553 // If a divisor is zero/undef or any element of a divisor vector is
4554 // zero/undef, the whole op is undef.
4555 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
4556 SDValue Divisor = Ops[1];
4557 if (Divisor.isUndef() || isNullConstant(Divisor))
4558 return true;
4560 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
4561 llvm::any_of(Divisor->op_values(),
4562 [](SDValue V) { return V.isUndef() ||
4563 isNullConstant(V); });
4564 // TODO: Handle signed overflow.
4566 // TODO: Handle oversized shifts.
4567 default:
4568 return false;
4572 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
4573 EVT VT, SDNode *N1, SDNode *N2) {
4574 // If the opcode is a target-specific ISD node, there's nothing we can
4575 // do here and the operand rules may not line up with the below, so
4576 // bail early.
4577 if (Opcode >= ISD::BUILTIN_OP_END)
4578 return SDValue();
4580 if (isUndef(Opcode, {SDValue(N1, 0), SDValue(N2, 0)}))
4581 return getUNDEF(VT);
4583 // Handle the case of two scalars.
4584 if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
4585 if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) {
4586 SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, C1, C2);
4587 assert((!Folded || !VT.isVector()) &&
4588 "Can't fold vectors ops with scalar operands");
4589 return Folded;
4593 // fold (add Sym, c) -> Sym+c
4594 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1))
4595 return FoldSymbolOffset(Opcode, VT, GA, N2);
4596 if (TLI->isCommutativeBinOp(Opcode))
4597 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2))
4598 return FoldSymbolOffset(Opcode, VT, GA, N1);
4600 // For vectors, extract each constant element and fold them individually.
4601 // Either input may be an undef value.
4602 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
4603 if (!BV1 && !N1->isUndef())
4604 return SDValue();
4605 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
4606 if (!BV2 && !N2->isUndef())
4607 return SDValue();
4608 // If both operands are undef, that's handled the same way as scalars.
4609 if (!BV1 && !BV2)
4610 return SDValue();
4612 assert((!BV1 || !BV2 || BV1->getNumOperands() == BV2->getNumOperands()) &&
4613 "Vector binop with different number of elements in operands?");
4615 EVT SVT = VT.getScalarType();
4616 EVT LegalSVT = SVT;
4617 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
4618 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
4619 if (LegalSVT.bitsLT(SVT))
4620 return SDValue();
4622 SmallVector<SDValue, 4> Outputs;
4623 unsigned NumOps = BV1 ? BV1->getNumOperands() : BV2->getNumOperands();
4624 for (unsigned I = 0; I != NumOps; ++I) {
4625 SDValue V1 = BV1 ? BV1->getOperand(I) : getUNDEF(SVT);
4626 SDValue V2 = BV2 ? BV2->getOperand(I) : getUNDEF(SVT);
4627 if (SVT.isInteger()) {
4628 if (V1->getValueType(0).bitsGT(SVT))
4629 V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
4630 if (V2->getValueType(0).bitsGT(SVT))
4631 V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
4634 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
4635 return SDValue();
4637 // Fold one vector element.
4638 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
4639 if (LegalSVT != SVT)
4640 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
4642 // Scalar folding only succeeded if the result is a constant or UNDEF.
4643 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
4644 ScalarResult.getOpcode() != ISD::ConstantFP)
4645 return SDValue();
4646 Outputs.push_back(ScalarResult);
4649 assert(VT.getVectorNumElements() == Outputs.size() &&
4650 "Vector size mismatch!");
4652 // We may have a vector type but a scalar result. Create a splat.
4653 Outputs.resize(VT.getVectorNumElements(), Outputs.back());
4655 // Build a big vector out of the scalar elements we generated.
4656 return getBuildVector(VT, SDLoc(), Outputs);
4659 // TODO: Merge with FoldConstantArithmetic
4660 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
4661 const SDLoc &DL, EVT VT,
4662 ArrayRef<SDValue> Ops,
4663 const SDNodeFlags Flags) {
4664 // If the opcode is a target-specific ISD node, there's nothing we can
4665 // do here and the operand rules may not line up with the below, so
4666 // bail early.
4667 if (Opcode >= ISD::BUILTIN_OP_END)
4668 return SDValue();
4670 if (isUndef(Opcode, Ops))
4671 return getUNDEF(VT);
4673 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
4674 if (!VT.isVector())
4675 return SDValue();
4677 unsigned NumElts = VT.getVectorNumElements();
4679 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
4680 return !Op.getValueType().isVector() ||
4681 Op.getValueType().getVectorNumElements() == NumElts;
4684 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
4685 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
4686 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
4687 (BV && BV->isConstant());
4690 // All operands must be vector types with the same number of elements as
4691 // the result type and must be either UNDEF or a build vector of constant
4692 // or UNDEF scalars.
4693 if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
4694 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
4695 return SDValue();
4697 // If we are comparing vectors, then the result needs to be a i1 boolean
4698 // that is then sign-extended back to the legal result type.
4699 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
4701 // Find legal integer scalar type for constant promotion and
4702 // ensure that its scalar size is at least as large as source.
4703 EVT LegalSVT = VT.getScalarType();
4704 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
4705 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
4706 if (LegalSVT.bitsLT(VT.getScalarType()))
4707 return SDValue();
4710 // Constant fold each scalar lane separately.
4711 SmallVector<SDValue, 4> ScalarResults;
4712 for (unsigned i = 0; i != NumElts; i++) {
4713 SmallVector<SDValue, 4> ScalarOps;
4714 for (SDValue Op : Ops) {
4715 EVT InSVT = Op.getValueType().getScalarType();
4716 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
4717 if (!InBV) {
4718 // We've checked that this is UNDEF or a constant of some kind.
4719 if (Op.isUndef())
4720 ScalarOps.push_back(getUNDEF(InSVT));
4721 else
4722 ScalarOps.push_back(Op);
4723 continue;
4726 SDValue ScalarOp = InBV->getOperand(i);
4727 EVT ScalarVT = ScalarOp.getValueType();
4729 // Build vector (integer) scalar operands may need implicit
4730 // truncation - do this before constant folding.
4731 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
4732 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
4734 ScalarOps.push_back(ScalarOp);
4737 // Constant fold the scalar operands.
4738 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
4740 // Legalize the (integer) scalar constant if necessary.
4741 if (LegalSVT != SVT)
4742 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
4744 // Scalar folding only succeeded if the result is a constant or UNDEF.
4745 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
4746 ScalarResult.getOpcode() != ISD::ConstantFP)
4747 return SDValue();
4748 ScalarResults.push_back(ScalarResult);
4751 SDValue V = getBuildVector(VT, DL, ScalarResults);
4752 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
4753 return V;
4756 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4757 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
4758 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4759 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4760 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4761 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
4763 // Canonicalize constant to RHS if commutative.
4764 if (TLI->isCommutativeBinOp(Opcode)) {
4765 if (N1C && !N2C) {
4766 std::swap(N1C, N2C);
4767 std::swap(N1, N2);
4768 } else if (N1CFP && !N2CFP) {
4769 std::swap(N1CFP, N2CFP);
4770 std::swap(N1, N2);
4774 switch (Opcode) {
4775 default: break;
4776 case ISD::TokenFactor:
4777 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
4778 N2.getValueType() == MVT::Other && "Invalid token factor!");
4779 // Fold trivial token factors.
4780 if (N1.getOpcode() == ISD::EntryToken) return N2;
4781 if (N2.getOpcode() == ISD::EntryToken) return N1;
4782 if (N1 == N2) return N1;
4783 break;
4784 case ISD::BUILD_VECTOR: {
4785 // Attempt to simplify BUILD_VECTOR.
4786 SDValue Ops[] = {N1, N2};
4787 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4788 return V;
4789 break;
4791 case ISD::CONCAT_VECTORS: {
4792 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
4793 SDValue Ops[] = {N1, N2};
4794 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
4795 return V;
4796 break;
4798 case ISD::AND:
4799 assert(VT.isInteger() && "This operator does not apply to FP types!");
4800 assert(N1.getValueType() == N2.getValueType() &&
4801 N1.getValueType() == VT && "Binary operator types must match!");
4802 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
4803 // worth handling here.
4804 if (N2C && N2C->isNullValue())
4805 return N2;
4806 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
4807 return N1;
4808 break;
4809 case ISD::OR:
4810 case ISD::XOR:
4811 case ISD::ADD:
4812 case ISD::SUB:
4813 assert(VT.isInteger() && "This operator does not apply to FP types!");
4814 assert(N1.getValueType() == N2.getValueType() &&
4815 N1.getValueType() == VT && "Binary operator types must match!");
4816 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
4817 // it's worth handling here.
4818 if (N2C && N2C->isNullValue())
4819 return N1;
4820 break;
4821 case ISD::UDIV:
4822 case ISD::UREM:
4823 case ISD::MULHU:
4824 case ISD::MULHS:
4825 case ISD::MUL:
4826 case ISD::SDIV:
4827 case ISD::SREM:
4828 case ISD::SMIN:
4829 case ISD::SMAX:
4830 case ISD::UMIN:
4831 case ISD::UMAX:
4832 case ISD::SADDSAT:
4833 case ISD::SSUBSAT:
4834 case ISD::UADDSAT:
4835 case ISD::USUBSAT:
4836 assert(VT.isInteger() && "This operator does not apply to FP types!");
4837 assert(N1.getValueType() == N2.getValueType() &&
4838 N1.getValueType() == VT && "Binary operator types must match!");
4839 break;
4840 case ISD::FADD:
4841 case ISD::FSUB:
4842 case ISD::FMUL:
4843 case ISD::FDIV:
4844 case ISD::FREM:
4845 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
4846 assert(N1.getValueType() == N2.getValueType() &&
4847 N1.getValueType() == VT && "Binary operator types must match!");
4848 break;
4849 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
4850 assert(N1.getValueType() == VT &&
4851 N1.getValueType().isFloatingPoint() &&
4852 N2.getValueType().isFloatingPoint() &&
4853 "Invalid FCOPYSIGN!");
4854 break;
4855 case ISD::SHL:
4856 case ISD::SRA:
4857 case ISD::SRL:
4858 if (SDValue V = simplifyShift(N1, N2))
4859 return V;
4860 LLVM_FALLTHROUGH;
4861 case ISD::ROTL:
4862 case ISD::ROTR:
4863 assert(VT == N1.getValueType() &&
4864 "Shift operators return type must be the same as their first arg");
4865 assert(VT.isInteger() && N2.getValueType().isInteger() &&
4866 "Shifts only work on integers");
4867 assert((!VT.isVector() || VT == N2.getValueType()) &&
4868 "Vector shift amounts must be in the same as their first arg");
4869 // Verify that the shift amount VT is big enough to hold valid shift
4870 // amounts. This catches things like trying to shift an i1024 value by an
4871 // i8, which is easy to fall into in generic code that uses
4872 // TLI.getShiftAmount().
4873 assert(N2.getValueSizeInBits() >= Log2_32_Ceil(N1.getValueSizeInBits()) &&
4874 "Invalid use of small shift amount with oversized value!");
4876 // Always fold shifts of i1 values so the code generator doesn't need to
4877 // handle them. Since we know the size of the shift has to be less than the
4878 // size of the value, the shift/rotate count is guaranteed to be zero.
4879 if (VT == MVT::i1)
4880 return N1;
4881 if (N2C && N2C->isNullValue())
4882 return N1;
4883 break;
4884 case ISD::FP_ROUND_INREG: {
4885 EVT EVT = cast<VTSDNode>(N2)->getVT();
4886 assert(VT == N1.getValueType() && "Not an inreg round!");
4887 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
4888 "Cannot FP_ROUND_INREG integer types");
4889 assert(EVT.isVector() == VT.isVector() &&
4890 "FP_ROUND_INREG type should be vector iff the operand "
4891 "type is vector!");
4892 assert((!EVT.isVector() ||
4893 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4894 "Vector element counts must match in FP_ROUND_INREG");
4895 assert(EVT.bitsLE(VT) && "Not rounding down!");
4896 (void)EVT;
4897 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
4898 break;
4900 case ISD::FP_ROUND:
4901 assert(VT.isFloatingPoint() &&
4902 N1.getValueType().isFloatingPoint() &&
4903 VT.bitsLE(N1.getValueType()) &&
4904 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
4905 "Invalid FP_ROUND!");
4906 if (N1.getValueType() == VT) return N1; // noop conversion.
4907 break;
4908 case ISD::AssertSext:
4909 case ISD::AssertZext: {
4910 EVT EVT = cast<VTSDNode>(N2)->getVT();
4911 assert(VT == N1.getValueType() && "Not an inreg extend!");
4912 assert(VT.isInteger() && EVT.isInteger() &&
4913 "Cannot *_EXTEND_INREG FP types");
4914 assert(!EVT.isVector() &&
4915 "AssertSExt/AssertZExt type should be the vector element type "
4916 "rather than the vector type!");
4917 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
4918 if (VT.getScalarType() == EVT) return N1; // noop assertion.
4919 break;
4921 case ISD::SIGN_EXTEND_INREG: {
4922 EVT EVT = cast<VTSDNode>(N2)->getVT();
4923 assert(VT == N1.getValueType() && "Not an inreg extend!");
4924 assert(VT.isInteger() && EVT.isInteger() &&
4925 "Cannot *_EXTEND_INREG FP types");
4926 assert(EVT.isVector() == VT.isVector() &&
4927 "SIGN_EXTEND_INREG type should be vector iff the operand "
4928 "type is vector!");
4929 assert((!EVT.isVector() ||
4930 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4931 "Vector element counts must match in SIGN_EXTEND_INREG");
4932 assert(EVT.bitsLE(VT) && "Not extending!");
4933 if (EVT == VT) return N1; // Not actually extending
4935 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
4936 unsigned FromBits = EVT.getScalarSizeInBits();
4937 Val <<= Val.getBitWidth() - FromBits;
4938 Val.ashrInPlace(Val.getBitWidth() - FromBits);
4939 return getConstant(Val, DL, ConstantVT);
4942 if (N1C) {
4943 const APInt &Val = N1C->getAPIntValue();
4944 return SignExtendInReg(Val, VT);
4946 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
4947 SmallVector<SDValue, 8> Ops;
4948 llvm::EVT OpVT = N1.getOperand(0).getValueType();
4949 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
4950 SDValue Op = N1.getOperand(i);
4951 if (Op.isUndef()) {
4952 Ops.push_back(getUNDEF(OpVT));
4953 continue;
4955 ConstantSDNode *C = cast<ConstantSDNode>(Op);
4956 APInt Val = C->getAPIntValue();
4957 Ops.push_back(SignExtendInReg(Val, OpVT));
4959 return getBuildVector(VT, DL, Ops);
4961 break;
4963 case ISD::EXTRACT_VECTOR_ELT:
4964 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
4965 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
4966 element type of the vector.");
4968 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
4969 if (N1.isUndef())
4970 return getUNDEF(VT);
4972 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF
4973 if (N2C && N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
4974 return getUNDEF(VT);
4976 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
4977 // expanding copies of large vectors from registers.
4978 if (N2C &&
4979 N1.getOpcode() == ISD::CONCAT_VECTORS &&
4980 N1.getNumOperands() > 0) {
4981 unsigned Factor =
4982 N1.getOperand(0).getValueType().getVectorNumElements();
4983 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
4984 N1.getOperand(N2C->getZExtValue() / Factor),
4985 getConstant(N2C->getZExtValue() % Factor, DL,
4986 N2.getValueType()));
4989 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
4990 // expanding large vector constants.
4991 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
4992 SDValue Elt = N1.getOperand(N2C->getZExtValue());
4994 if (VT != Elt.getValueType())
4995 // If the vector element type is not legal, the BUILD_VECTOR operands
4996 // are promoted and implicitly truncated, and the result implicitly
4997 // extended. Make that explicit here.
4998 Elt = getAnyExtOrTrunc(Elt, DL, VT);
5000 return Elt;
5003 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5004 // operations are lowered to scalars.
5005 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5006 // If the indices are the same, return the inserted element else
5007 // if the indices are known different, extract the element from
5008 // the original vector.
5009 SDValue N1Op2 = N1.getOperand(2);
5010 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5012 if (N1Op2C && N2C) {
5013 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5014 if (VT == N1.getOperand(1).getValueType())
5015 return N1.getOperand(1);
5016 else
5017 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5020 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5024 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5025 // when vector types are scalarized and v1iX is legal.
5026 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx)
5027 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5028 N1.getValueType().getVectorNumElements() == 1) {
5029 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5030 N1.getOperand(1));
5032 break;
5033 case ISD::EXTRACT_ELEMENT:
5034 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5035 assert(!N1.getValueType().isVector() && !VT.isVector() &&
5036 (N1.getValueType().isInteger() == VT.isInteger()) &&
5037 N1.getValueType() != VT &&
5038 "Wrong types for EXTRACT_ELEMENT!");
5040 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5041 // 64-bit integers into 32-bit parts. Instead of building the extract of
5042 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5043 if (N1.getOpcode() == ISD::BUILD_PAIR)
5044 return N1.getOperand(N2C->getZExtValue());
5046 // EXTRACT_ELEMENT of a constant int is also very common.
5047 if (N1C) {
5048 unsigned ElementSize = VT.getSizeInBits();
5049 unsigned Shift = ElementSize * N2C->getZExtValue();
5050 APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
5051 return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
5053 break;
5054 case ISD::EXTRACT_SUBVECTOR:
5055 if (VT.isSimple() && N1.getValueType().isSimple()) {
5056 assert(VT.isVector() && N1.getValueType().isVector() &&
5057 "Extract subvector VTs must be a vectors!");
5058 assert(VT.getVectorElementType() ==
5059 N1.getValueType().getVectorElementType() &&
5060 "Extract subvector VTs must have the same element type!");
5061 assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
5062 "Extract subvector must be from larger vector to smaller vector!");
5064 if (N2C) {
5065 assert((VT.getVectorNumElements() + N2C->getZExtValue()
5066 <= N1.getValueType().getVectorNumElements())
5067 && "Extract subvector overflow!");
5070 // Trivial extraction.
5071 if (VT.getSimpleVT() == N1.getSimpleValueType())
5072 return N1;
5074 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5075 if (N1.isUndef())
5076 return getUNDEF(VT);
5078 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5079 // the concat have the same type as the extract.
5080 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
5081 N1.getNumOperands() > 0 &&
5082 VT == N1.getOperand(0).getValueType()) {
5083 unsigned Factor = VT.getVectorNumElements();
5084 return N1.getOperand(N2C->getZExtValue() / Factor);
5087 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5088 // during shuffle legalization.
5089 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5090 VT == N1.getOperand(1).getValueType())
5091 return N1.getOperand(1);
5093 break;
5096 // Perform trivial constant folding.
5097 if (SDValue SV =
5098 FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode()))
5099 return SV;
5101 // Constant fold FP operations.
5102 bool HasFPExceptions = TLI->hasFloatingPointExceptions();
5103 if (N1CFP) {
5104 if (N2CFP) {
5105 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
5106 APFloat::opStatus s;
5107 switch (Opcode) {
5108 case ISD::FADD:
5109 s = V1.add(V2, APFloat::rmNearestTiesToEven);
5110 if (!HasFPExceptions || s != APFloat::opInvalidOp)
5111 return getConstantFP(V1, DL, VT);
5112 break;
5113 case ISD::FSUB:
5114 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
5115 if (!HasFPExceptions || s!=APFloat::opInvalidOp)
5116 return getConstantFP(V1, DL, VT);
5117 break;
5118 case ISD::FMUL:
5119 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
5120 if (!HasFPExceptions || s!=APFloat::opInvalidOp)
5121 return getConstantFP(V1, DL, VT);
5122 break;
5123 case ISD::FDIV:
5124 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
5125 if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
5126 s!=APFloat::opDivByZero)) {
5127 return getConstantFP(V1, DL, VT);
5129 break;
5130 case ISD::FREM :
5131 s = V1.mod(V2);
5132 if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
5133 s!=APFloat::opDivByZero)) {
5134 return getConstantFP(V1, DL, VT);
5136 break;
5137 case ISD::FCOPYSIGN:
5138 V1.copySign(V2);
5139 return getConstantFP(V1, DL, VT);
5140 default: break;
5144 if (Opcode == ISD::FP_ROUND) {
5145 APFloat V = N1CFP->getValueAPF(); // make copy
5146 bool ignored;
5147 // This can return overflow, underflow, or inexact; we don't care.
5148 // FIXME need to be more flexible about rounding mode.
5149 (void)V.convert(EVTToAPFloatSemantics(VT),
5150 APFloat::rmNearestTiesToEven, &ignored);
5151 return getConstantFP(V, DL, VT);
5155 switch (Opcode) {
5156 case ISD::FADD:
5157 case ISD::FSUB:
5158 case ISD::FMUL:
5159 case ISD::FDIV:
5160 case ISD::FREM:
5161 // If both operands are undef, the result is undef. If 1 operand is undef,
5162 // the result is NaN. This should match the behavior of the IR optimizer.
5163 if (N1.isUndef() && N2.isUndef())
5164 return getUNDEF(VT);
5165 if (N1.isUndef() || N2.isUndef())
5166 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5169 // Canonicalize an UNDEF to the RHS, even over a constant.
5170 if (N1.isUndef()) {
5171 if (TLI->isCommutativeBinOp(Opcode)) {
5172 std::swap(N1, N2);
5173 } else {
5174 switch (Opcode) {
5175 case ISD::FP_ROUND_INREG:
5176 case ISD::SIGN_EXTEND_INREG:
5177 case ISD::SUB:
5178 return getUNDEF(VT); // fold op(undef, arg2) -> undef
5179 case ISD::UDIV:
5180 case ISD::SDIV:
5181 case ISD::UREM:
5182 case ISD::SREM:
5183 case ISD::SSUBSAT:
5184 case ISD::USUBSAT:
5185 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
5190 // Fold a bunch of operators when the RHS is undef.
5191 if (N2.isUndef()) {
5192 switch (Opcode) {
5193 case ISD::XOR:
5194 if (N1.isUndef())
5195 // Handle undef ^ undef -> 0 special case. This is a common
5196 // idiom (misuse).
5197 return getConstant(0, DL, VT);
5198 LLVM_FALLTHROUGH;
5199 case ISD::ADD:
5200 case ISD::SUB:
5201 case ISD::UDIV:
5202 case ISD::SDIV:
5203 case ISD::UREM:
5204 case ISD::SREM:
5205 return getUNDEF(VT); // fold op(arg1, undef) -> undef
5206 case ISD::MUL:
5207 case ISD::AND:
5208 case ISD::SSUBSAT:
5209 case ISD::USUBSAT:
5210 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
5211 case ISD::OR:
5212 case ISD::SADDSAT:
5213 case ISD::UADDSAT:
5214 return getAllOnesConstant(DL, VT);
5218 // Memoize this node if possible.
5219 SDNode *N;
5220 SDVTList VTs = getVTList(VT);
5221 SDValue Ops[] = {N1, N2};
5222 if (VT != MVT::Glue) {
5223 FoldingSetNodeID ID;
5224 AddNodeIDNode(ID, Opcode, VTs, Ops);
5225 void *IP = nullptr;
5226 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5227 E->intersectFlagsWith(Flags);
5228 return SDValue(E, 0);
5231 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5232 N->setFlags(Flags);
5233 createOperands(N, Ops);
5234 CSEMap.InsertNode(N, IP);
5235 } else {
5236 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5237 createOperands(N, Ops);
5240 InsertNode(N);
5241 SDValue V = SDValue(N, 0);
5242 NewSDValueDbgMsg(V, "Creating new node: ", this);
5243 return V;
5246 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5247 SDValue N1, SDValue N2, SDValue N3,
5248 const SDNodeFlags Flags) {
5249 // Perform various simplifications.
5250 switch (Opcode) {
5251 case ISD::FMA: {
5252 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5253 assert(N1.getValueType() == VT && N2.getValueType() == VT &&
5254 N3.getValueType() == VT && "FMA types must match!");
5255 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5256 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5257 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
5258 if (N1CFP && N2CFP && N3CFP) {
5259 APFloat V1 = N1CFP->getValueAPF();
5260 const APFloat &V2 = N2CFP->getValueAPF();
5261 const APFloat &V3 = N3CFP->getValueAPF();
5262 APFloat::opStatus s =
5263 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
5264 if (!TLI->hasFloatingPointExceptions() || s != APFloat::opInvalidOp)
5265 return getConstantFP(V1, DL, VT);
5267 break;
5269 case ISD::BUILD_VECTOR: {
5270 // Attempt to simplify BUILD_VECTOR.
5271 SDValue Ops[] = {N1, N2, N3};
5272 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5273 return V;
5274 break;
5276 case ISD::CONCAT_VECTORS: {
5277 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
5278 SDValue Ops[] = {N1, N2, N3};
5279 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
5280 return V;
5281 break;
5283 case ISD::SETCC: {
5284 assert(VT.isInteger() && "SETCC result type must be an integer!");
5285 assert(N1.getValueType() == N2.getValueType() &&
5286 "SETCC operands must have the same type!");
5287 assert(VT.isVector() == N1.getValueType().isVector() &&
5288 "SETCC type should be vector iff the operand type is vector!");
5289 assert((!VT.isVector() ||
5290 VT.getVectorNumElements() == N1.getValueType().getVectorNumElements()) &&
5291 "SETCC vector element counts must match!");
5292 // Use FoldSetCC to simplify SETCC's.
5293 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
5294 return V;
5295 // Vector constant folding.
5296 SDValue Ops[] = {N1, N2, N3};
5297 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
5298 NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
5299 return V;
5301 break;
5303 case ISD::SELECT:
5304 case ISD::VSELECT:
5305 if (SDValue V = simplifySelect(N1, N2, N3))
5306 return V;
5307 break;
5308 case ISD::VECTOR_SHUFFLE:
5309 llvm_unreachable("should use getVectorShuffle constructor!");
5310 case ISD::INSERT_VECTOR_ELT: {
5311 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
5312 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF
5313 if (N3C && N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
5314 return getUNDEF(VT);
5315 break;
5317 case ISD::INSERT_SUBVECTOR: {
5318 SDValue Index = N3;
5319 if (VT.isSimple() && N1.getValueType().isSimple()
5320 && N2.getValueType().isSimple()) {
5321 assert(VT.isVector() && N1.getValueType().isVector() &&
5322 N2.getValueType().isVector() &&
5323 "Insert subvector VTs must be a vectors");
5324 assert(VT == N1.getValueType() &&
5325 "Dest and insert subvector source types must match!");
5326 assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
5327 "Insert subvector must be from smaller vector to larger vector!");
5328 if (isa<ConstantSDNode>(Index)) {
5329 assert((N2.getValueType().getVectorNumElements() +
5330 cast<ConstantSDNode>(Index)->getZExtValue()
5331 <= VT.getVectorNumElements())
5332 && "Insert subvector overflow!");
5335 // Trivial insertion.
5336 if (VT.getSimpleVT() == N2.getSimpleValueType())
5337 return N2;
5339 break;
5341 case ISD::BITCAST:
5342 // Fold bit_convert nodes from a type to themselves.
5343 if (N1.getValueType() == VT)
5344 return N1;
5345 break;
5348 // Memoize node if it doesn't produce a flag.
5349 SDNode *N;
5350 SDVTList VTs = getVTList(VT);
5351 SDValue Ops[] = {N1, N2, N3};
5352 if (VT != MVT::Glue) {
5353 FoldingSetNodeID ID;
5354 AddNodeIDNode(ID, Opcode, VTs, Ops);
5355 void *IP = nullptr;
5356 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5357 E->intersectFlagsWith(Flags);
5358 return SDValue(E, 0);
5361 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5362 N->setFlags(Flags);
5363 createOperands(N, Ops);
5364 CSEMap.InsertNode(N, IP);
5365 } else {
5366 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5367 createOperands(N, Ops);
5370 InsertNode(N);
5371 SDValue V = SDValue(N, 0);
5372 NewSDValueDbgMsg(V, "Creating new node: ", this);
5373 return V;
5376 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5377 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
5378 SDValue Ops[] = { N1, N2, N3, N4 };
5379 return getNode(Opcode, DL, VT, Ops);
5382 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5383 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
5384 SDValue N5) {
5385 SDValue Ops[] = { N1, N2, N3, N4, N5 };
5386 return getNode(Opcode, DL, VT, Ops);
5389 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
5390 /// the incoming stack arguments to be loaded from the stack.
5391 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
5392 SmallVector<SDValue, 8> ArgChains;
5394 // Include the original chain at the beginning of the list. When this is
5395 // used by target LowerCall hooks, this helps legalize find the
5396 // CALLSEQ_BEGIN node.
5397 ArgChains.push_back(Chain);
5399 // Add a chain value for each stack argument.
5400 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
5401 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
5402 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
5403 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
5404 if (FI->getIndex() < 0)
5405 ArgChains.push_back(SDValue(L, 1));
5407 // Build a tokenfactor for all the chains.
5408 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
5411 /// getMemsetValue - Vectorized representation of the memset value
5412 /// operand.
5413 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
5414 const SDLoc &dl) {
5415 assert(!Value.isUndef());
5417 unsigned NumBits = VT.getScalarSizeInBits();
5418 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
5419 assert(C->getAPIntValue().getBitWidth() == 8);
5420 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
5421 if (VT.isInteger()) {
5422 bool IsOpaque = VT.getSizeInBits() > 64 ||
5423 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
5424 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
5426 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
5427 VT);
5430 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
5431 EVT IntVT = VT.getScalarType();
5432 if (!IntVT.isInteger())
5433 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
5435 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
5436 if (NumBits > 8) {
5437 // Use a multiplication with 0x010101... to extend the input to the
5438 // required length.
5439 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
5440 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
5441 DAG.getConstant(Magic, dl, IntVT));
5444 if (VT != Value.getValueType() && !VT.isInteger())
5445 Value = DAG.getBitcast(VT.getScalarType(), Value);
5446 if (VT != Value.getValueType())
5447 Value = DAG.getSplatBuildVector(VT, dl, Value);
5449 return Value;
5452 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
5453 /// used when a memcpy is turned into a memset when the source is a constant
5454 /// string ptr.
5455 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
5456 const TargetLowering &TLI,
5457 const ConstantDataArraySlice &Slice) {
5458 // Handle vector with all elements zero.
5459 if (Slice.Array == nullptr) {
5460 if (VT.isInteger())
5461 return DAG.getConstant(0, dl, VT);
5462 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
5463 return DAG.getConstantFP(0.0, dl, VT);
5464 else if (VT.isVector()) {
5465 unsigned NumElts = VT.getVectorNumElements();
5466 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5467 return DAG.getNode(ISD::BITCAST, dl, VT,
5468 DAG.getConstant(0, dl,
5469 EVT::getVectorVT(*DAG.getContext(),
5470 EltVT, NumElts)));
5471 } else
5472 llvm_unreachable("Expected type!");
5475 assert(!VT.isVector() && "Can't handle vector type here!");
5476 unsigned NumVTBits = VT.getSizeInBits();
5477 unsigned NumVTBytes = NumVTBits / 8;
5478 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
5480 APInt Val(NumVTBits, 0);
5481 if (DAG.getDataLayout().isLittleEndian()) {
5482 for (unsigned i = 0; i != NumBytes; ++i)
5483 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
5484 } else {
5485 for (unsigned i = 0; i != NumBytes; ++i)
5486 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
5489 // If the "cost" of materializing the integer immediate is less than the cost
5490 // of a load, then it is cost effective to turn the load into the immediate.
5491 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
5492 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
5493 return DAG.getConstant(Val, dl, VT);
5494 return SDValue(nullptr, 0);
5497 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset,
5498 const SDLoc &DL) {
5499 EVT VT = Base.getValueType();
5500 return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT));
5503 /// Returns true if memcpy source is constant data.
5504 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
5505 uint64_t SrcDelta = 0;
5506 GlobalAddressSDNode *G = nullptr;
5507 if (Src.getOpcode() == ISD::GlobalAddress)
5508 G = cast<GlobalAddressSDNode>(Src);
5509 else if (Src.getOpcode() == ISD::ADD &&
5510 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
5511 Src.getOperand(1).getOpcode() == ISD::Constant) {
5512 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
5513 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
5515 if (!G)
5516 return false;
5518 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
5519 SrcDelta + G->getOffset());
5522 /// Determines the optimal series of memory ops to replace the memset / memcpy.
5523 /// Return true if the number of memory ops is below the threshold (Limit).
5524 /// It returns the types of the sequence of memory ops to perform
5525 /// memset / memcpy by reference.
5526 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
5527 unsigned Limit, uint64_t Size,
5528 unsigned DstAlign, unsigned SrcAlign,
5529 bool IsMemset,
5530 bool ZeroMemset,
5531 bool MemcpyStrSrc,
5532 bool AllowOverlap,
5533 unsigned DstAS, unsigned SrcAS,
5534 SelectionDAG &DAG,
5535 const TargetLowering &TLI) {
5536 assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
5537 "Expecting memcpy / memset source to meet alignment requirement!");
5538 // If 'SrcAlign' is zero, that means the memory operation does not need to
5539 // load the value, i.e. memset or memcpy from constant string. Otherwise,
5540 // it's the inferred alignment of the source. 'DstAlign', on the other hand,
5541 // is the specified alignment of the memory operation. If it is zero, that
5542 // means it's possible to change the alignment of the destination.
5543 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
5544 // not need to be loaded.
5545 EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
5546 IsMemset, ZeroMemset, MemcpyStrSrc,
5547 DAG.getMachineFunction());
5549 if (VT == MVT::Other) {
5550 // Use the largest integer type whose alignment constraints are satisfied.
5551 // We only need to check DstAlign here as SrcAlign is always greater or
5552 // equal to DstAlign (or zero).
5553 VT = MVT::i64;
5554 while (DstAlign && DstAlign < VT.getSizeInBits() / 8 &&
5555 !TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign))
5556 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
5557 assert(VT.isInteger());
5559 // Find the largest legal integer type.
5560 MVT LVT = MVT::i64;
5561 while (!TLI.isTypeLegal(LVT))
5562 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
5563 assert(LVT.isInteger());
5565 // If the type we've chosen is larger than the largest legal integer type
5566 // then use that instead.
5567 if (VT.bitsGT(LVT))
5568 VT = LVT;
5571 unsigned NumMemOps = 0;
5572 while (Size != 0) {
5573 unsigned VTSize = VT.getSizeInBits() / 8;
5574 while (VTSize > Size) {
5575 // For now, only use non-vector load / store's for the left-over pieces.
5576 EVT NewVT = VT;
5577 unsigned NewVTSize;
5579 bool Found = false;
5580 if (VT.isVector() || VT.isFloatingPoint()) {
5581 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
5582 if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) &&
5583 TLI.isSafeMemOpType(NewVT.getSimpleVT()))
5584 Found = true;
5585 else if (NewVT == MVT::i64 &&
5586 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
5587 TLI.isSafeMemOpType(MVT::f64)) {
5588 // i64 is usually not legal on 32-bit targets, but f64 may be.
5589 NewVT = MVT::f64;
5590 Found = true;
5594 if (!Found) {
5595 do {
5596 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
5597 if (NewVT == MVT::i8)
5598 break;
5599 } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT()));
5601 NewVTSize = NewVT.getSizeInBits() / 8;
5603 // If the new VT cannot cover all of the remaining bits, then consider
5604 // issuing a (or a pair of) unaligned and overlapping load / store.
5605 bool Fast;
5606 if (NumMemOps && AllowOverlap && NewVTSize < Size &&
5607 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign, &Fast) &&
5608 Fast)
5609 VTSize = Size;
5610 else {
5611 VT = NewVT;
5612 VTSize = NewVTSize;
5616 if (++NumMemOps > Limit)
5617 return false;
5619 MemOps.push_back(VT);
5620 Size -= VTSize;
5623 return true;
5626 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) {
5627 // On Darwin, -Os means optimize for size without hurting performance, so
5628 // only really optimize for size when -Oz (MinSize) is used.
5629 if (MF.getTarget().getTargetTriple().isOSDarwin())
5630 return MF.getFunction().optForMinSize();
5631 return MF.getFunction().optForSize();
5634 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
5635 SmallVector<SDValue, 32> &OutChains, unsigned From,
5636 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
5637 SmallVector<SDValue, 16> &OutStoreChains) {
5638 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
5639 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
5640 SmallVector<SDValue, 16> GluedLoadChains;
5641 for (unsigned i = From; i < To; ++i) {
5642 OutChains.push_back(OutLoadChains[i]);
5643 GluedLoadChains.push_back(OutLoadChains[i]);
5646 // Chain for all loads.
5647 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5648 GluedLoadChains);
5650 for (unsigned i = From; i < To; ++i) {
5651 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
5652 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
5653 ST->getBasePtr(), ST->getMemoryVT(),
5654 ST->getMemOperand());
5655 OutChains.push_back(NewStore);
5659 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
5660 SDValue Chain, SDValue Dst, SDValue Src,
5661 uint64_t Size, unsigned Align,
5662 bool isVol, bool AlwaysInline,
5663 MachinePointerInfo DstPtrInfo,
5664 MachinePointerInfo SrcPtrInfo) {
5665 // Turn a memcpy of undef to nop.
5666 if (Src.isUndef())
5667 return Chain;
5669 // Expand memcpy to a series of load and store ops if the size operand falls
5670 // below a certain threshold.
5671 // TODO: In the AlwaysInline case, if the size is big then generate a loop
5672 // rather than maybe a humongous number of loads and stores.
5673 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5674 const DataLayout &DL = DAG.getDataLayout();
5675 LLVMContext &C = *DAG.getContext();
5676 std::vector<EVT> MemOps;
5677 bool DstAlignCanChange = false;
5678 MachineFunction &MF = DAG.getMachineFunction();
5679 MachineFrameInfo &MFI = MF.getFrameInfo();
5680 bool OptSize = shouldLowerMemFuncForSize(MF);
5681 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5682 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5683 DstAlignCanChange = true;
5684 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
5685 if (Align > SrcAlign)
5686 SrcAlign = Align;
5687 ConstantDataArraySlice Slice;
5688 bool CopyFromConstant = isMemSrcFromConstant(Src, Slice);
5689 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
5690 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
5692 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
5693 (DstAlignCanChange ? 0 : Align),
5694 (isZeroConstant ? 0 : SrcAlign),
5695 false, false, CopyFromConstant, true,
5696 DstPtrInfo.getAddrSpace(),
5697 SrcPtrInfo.getAddrSpace(),
5698 DAG, TLI))
5699 return SDValue();
5701 if (DstAlignCanChange) {
5702 Type *Ty = MemOps[0].getTypeForEVT(C);
5703 unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
5705 // Don't promote to an alignment that would require dynamic stack
5706 // realignment.
5707 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
5708 if (!TRI->needsStackRealignment(MF))
5709 while (NewAlign > Align &&
5710 DL.exceedsNaturalStackAlignment(NewAlign))
5711 NewAlign /= 2;
5713 if (NewAlign > Align) {
5714 // Give the stack frame object a larger alignment if needed.
5715 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5716 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5717 Align = NewAlign;
5721 MachineMemOperand::Flags MMOFlags =
5722 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
5723 SmallVector<SDValue, 16> OutLoadChains;
5724 SmallVector<SDValue, 16> OutStoreChains;
5725 SmallVector<SDValue, 32> OutChains;
5726 unsigned NumMemOps = MemOps.size();
5727 uint64_t SrcOff = 0, DstOff = 0;
5728 for (unsigned i = 0; i != NumMemOps; ++i) {
5729 EVT VT = MemOps[i];
5730 unsigned VTSize = VT.getSizeInBits() / 8;
5731 SDValue Value, Store;
5733 if (VTSize > Size) {
5734 // Issuing an unaligned load / store pair that overlaps with the previous
5735 // pair. Adjust the offset accordingly.
5736 assert(i == NumMemOps-1 && i != 0);
5737 SrcOff -= VTSize - Size;
5738 DstOff -= VTSize - Size;
5741 if (CopyFromConstant &&
5742 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
5743 // It's unlikely a store of a vector immediate can be done in a single
5744 // instruction. It would require a load from a constantpool first.
5745 // We only handle zero vectors here.
5746 // FIXME: Handle other cases where store of vector immediate is done in
5747 // a single instruction.
5748 ConstantDataArraySlice SubSlice;
5749 if (SrcOff < Slice.Length) {
5750 SubSlice = Slice;
5751 SubSlice.move(SrcOff);
5752 } else {
5753 // This is an out-of-bounds access and hence UB. Pretend we read zero.
5754 SubSlice.Array = nullptr;
5755 SubSlice.Offset = 0;
5756 SubSlice.Length = VTSize;
5758 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
5759 if (Value.getNode()) {
5760 Store = DAG.getStore(Chain, dl, Value,
5761 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5762 DstPtrInfo.getWithOffset(DstOff), Align,
5763 MMOFlags);
5764 OutChains.push_back(Store);
5768 if (!Store.getNode()) {
5769 // The type might not be legal for the target. This should only happen
5770 // if the type is smaller than a legal type, as on PPC, so the right
5771 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
5772 // to Load/Store if NVT==VT.
5773 // FIXME does the case above also need this?
5774 EVT NVT = TLI.getTypeToTransformTo(C, VT);
5775 assert(NVT.bitsGE(VT));
5777 bool isDereferenceable =
5778 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
5779 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
5780 if (isDereferenceable)
5781 SrcMMOFlags |= MachineMemOperand::MODereferenceable;
5783 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
5784 DAG.getMemBasePlusOffset(Src, SrcOff, dl),
5785 SrcPtrInfo.getWithOffset(SrcOff), VT,
5786 MinAlign(SrcAlign, SrcOff), SrcMMOFlags);
5787 OutLoadChains.push_back(Value.getValue(1));
5789 Store = DAG.getTruncStore(
5790 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5791 DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags);
5792 OutStoreChains.push_back(Store);
5794 SrcOff += VTSize;
5795 DstOff += VTSize;
5796 Size -= VTSize;
5799 unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
5800 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
5801 unsigned NumLdStInMemcpy = OutStoreChains.size();
5803 if (NumLdStInMemcpy) {
5804 // It may be that memcpy might be converted to memset if it's memcpy
5805 // of constants. In such a case, we won't have loads and stores, but
5806 // just stores. In the absence of loads, there is nothing to gang up.
5807 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
5808 // If target does not care, just leave as it.
5809 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
5810 OutChains.push_back(OutLoadChains[i]);
5811 OutChains.push_back(OutStoreChains[i]);
5813 } else {
5814 // Ld/St less than/equal limit set by target.
5815 if (NumLdStInMemcpy <= GluedLdStLimit) {
5816 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
5817 NumLdStInMemcpy, OutLoadChains,
5818 OutStoreChains);
5819 } else {
5820 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
5821 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
5822 unsigned GlueIter = 0;
5824 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
5825 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
5826 unsigned IndexTo = NumLdStInMemcpy - GlueIter;
5828 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
5829 OutLoadChains, OutStoreChains);
5830 GlueIter += GluedLdStLimit;
5833 // Residual ld/st.
5834 if (RemainingLdStInMemcpy) {
5835 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
5836 RemainingLdStInMemcpy, OutLoadChains,
5837 OutStoreChains);
5842 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5845 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
5846 SDValue Chain, SDValue Dst, SDValue Src,
5847 uint64_t Size, unsigned Align,
5848 bool isVol, bool AlwaysInline,
5849 MachinePointerInfo DstPtrInfo,
5850 MachinePointerInfo SrcPtrInfo) {
5851 // Turn a memmove of undef to nop.
5852 if (Src.isUndef())
5853 return Chain;
5855 // Expand memmove to a series of load and store ops if the size operand falls
5856 // below a certain threshold.
5857 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5858 const DataLayout &DL = DAG.getDataLayout();
5859 LLVMContext &C = *DAG.getContext();
5860 std::vector<EVT> MemOps;
5861 bool DstAlignCanChange = false;
5862 MachineFunction &MF = DAG.getMachineFunction();
5863 MachineFrameInfo &MFI = MF.getFrameInfo();
5864 bool OptSize = shouldLowerMemFuncForSize(MF);
5865 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5866 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5867 DstAlignCanChange = true;
5868 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
5869 if (Align > SrcAlign)
5870 SrcAlign = Align;
5871 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
5873 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
5874 (DstAlignCanChange ? 0 : Align), SrcAlign,
5875 false, false, false, false,
5876 DstPtrInfo.getAddrSpace(),
5877 SrcPtrInfo.getAddrSpace(),
5878 DAG, TLI))
5879 return SDValue();
5881 if (DstAlignCanChange) {
5882 Type *Ty = MemOps[0].getTypeForEVT(C);
5883 unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
5884 if (NewAlign > Align) {
5885 // Give the stack frame object a larger alignment if needed.
5886 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5887 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5888 Align = NewAlign;
5892 MachineMemOperand::Flags MMOFlags =
5893 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
5894 uint64_t SrcOff = 0, DstOff = 0;
5895 SmallVector<SDValue, 8> LoadValues;
5896 SmallVector<SDValue, 8> LoadChains;
5897 SmallVector<SDValue, 8> OutChains;
5898 unsigned NumMemOps = MemOps.size();
5899 for (unsigned i = 0; i < NumMemOps; i++) {
5900 EVT VT = MemOps[i];
5901 unsigned VTSize = VT.getSizeInBits() / 8;
5902 SDValue Value;
5904 bool isDereferenceable =
5905 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
5906 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
5907 if (isDereferenceable)
5908 SrcMMOFlags |= MachineMemOperand::MODereferenceable;
5910 Value =
5911 DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl),
5912 SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, SrcMMOFlags);
5913 LoadValues.push_back(Value);
5914 LoadChains.push_back(Value.getValue(1));
5915 SrcOff += VTSize;
5917 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
5918 OutChains.clear();
5919 for (unsigned i = 0; i < NumMemOps; i++) {
5920 EVT VT = MemOps[i];
5921 unsigned VTSize = VT.getSizeInBits() / 8;
5922 SDValue Store;
5924 Store = DAG.getStore(Chain, dl, LoadValues[i],
5925 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5926 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
5927 OutChains.push_back(Store);
5928 DstOff += VTSize;
5931 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5934 /// Lower the call to 'memset' intrinsic function into a series of store
5935 /// operations.
5937 /// \param DAG Selection DAG where lowered code is placed.
5938 /// \param dl Link to corresponding IR location.
5939 /// \param Chain Control flow dependency.
5940 /// \param Dst Pointer to destination memory location.
5941 /// \param Src Value of byte to write into the memory.
5942 /// \param Size Number of bytes to write.
5943 /// \param Align Alignment of the destination in bytes.
5944 /// \param isVol True if destination is volatile.
5945 /// \param DstPtrInfo IR information on the memory pointer.
5946 /// \returns New head in the control flow, if lowering was successful, empty
5947 /// SDValue otherwise.
5949 /// The function tries to replace 'llvm.memset' intrinsic with several store
5950 /// operations and value calculation code. This is usually profitable for small
5951 /// memory size.
5952 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
5953 SDValue Chain, SDValue Dst, SDValue Src,
5954 uint64_t Size, unsigned Align, bool isVol,
5955 MachinePointerInfo DstPtrInfo) {
5956 // Turn a memset of undef to nop.
5957 if (Src.isUndef())
5958 return Chain;
5960 // Expand memset to a series of load/store ops if the size operand
5961 // falls below a certain threshold.
5962 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5963 std::vector<EVT> MemOps;
5964 bool DstAlignCanChange = false;
5965 MachineFunction &MF = DAG.getMachineFunction();
5966 MachineFrameInfo &MFI = MF.getFrameInfo();
5967 bool OptSize = shouldLowerMemFuncForSize(MF);
5968 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5969 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5970 DstAlignCanChange = true;
5971 bool IsZeroVal =
5972 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
5973 if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
5974 Size, (DstAlignCanChange ? 0 : Align), 0,
5975 true, IsZeroVal, false, true,
5976 DstPtrInfo.getAddrSpace(), ~0u,
5977 DAG, TLI))
5978 return SDValue();
5980 if (DstAlignCanChange) {
5981 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
5982 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
5983 if (NewAlign > Align) {
5984 // Give the stack frame object a larger alignment if needed.
5985 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5986 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5987 Align = NewAlign;
5991 SmallVector<SDValue, 8> OutChains;
5992 uint64_t DstOff = 0;
5993 unsigned NumMemOps = MemOps.size();
5995 // Find the largest store and generate the bit pattern for it.
5996 EVT LargestVT = MemOps[0];
5997 for (unsigned i = 1; i < NumMemOps; i++)
5998 if (MemOps[i].bitsGT(LargestVT))
5999 LargestVT = MemOps[i];
6000 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6002 for (unsigned i = 0; i < NumMemOps; i++) {
6003 EVT VT = MemOps[i];
6004 unsigned VTSize = VT.getSizeInBits() / 8;
6005 if (VTSize > Size) {
6006 // Issuing an unaligned load / store pair that overlaps with the previous
6007 // pair. Adjust the offset accordingly.
6008 assert(i == NumMemOps-1 && i != 0);
6009 DstOff -= VTSize - Size;
6012 // If this store is smaller than the largest store see whether we can get
6013 // the smaller value for free with a truncate.
6014 SDValue Value = MemSetValue;
6015 if (VT.bitsLT(LargestVT)) {
6016 if (!LargestVT.isVector() && !VT.isVector() &&
6017 TLI.isTruncateFree(LargestVT, VT))
6018 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6019 else
6020 Value = getMemsetValue(Src, VT, DAG, dl);
6022 assert(Value.getValueType() == VT && "Value with wrong type.");
6023 SDValue Store = DAG.getStore(
6024 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
6025 DstPtrInfo.getWithOffset(DstOff), Align,
6026 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
6027 OutChains.push_back(Store);
6028 DstOff += VT.getSizeInBits() / 8;
6029 Size -= VTSize;
6032 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6035 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6036 unsigned AS) {
6037 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6038 // pointer operands can be losslessly bitcasted to pointers of address space 0
6039 if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) {
6040 report_fatal_error("cannot lower memory intrinsic in address space " +
6041 Twine(AS));
6045 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6046 SDValue Src, SDValue Size, unsigned Align,
6047 bool isVol, bool AlwaysInline, bool isTailCall,
6048 MachinePointerInfo DstPtrInfo,
6049 MachinePointerInfo SrcPtrInfo) {
6050 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
6052 // Check to see if we should lower the memcpy to loads and stores first.
6053 // For cases within the target-specified limits, this is the best choice.
6054 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6055 if (ConstantSize) {
6056 // Memcpy with size zero? Just return the original chain.
6057 if (ConstantSize->isNullValue())
6058 return Chain;
6060 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6061 ConstantSize->getZExtValue(),Align,
6062 isVol, false, DstPtrInfo, SrcPtrInfo);
6063 if (Result.getNode())
6064 return Result;
6067 // Then check to see if we should lower the memcpy with target-specific
6068 // code. If the target chooses to do this, this is the next best.
6069 if (TSI) {
6070 SDValue Result = TSI->EmitTargetCodeForMemcpy(
6071 *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline,
6072 DstPtrInfo, SrcPtrInfo);
6073 if (Result.getNode())
6074 return Result;
6077 // If we really need inline code and the target declined to provide it,
6078 // use a (potentially long) sequence of loads and stores.
6079 if (AlwaysInline) {
6080 assert(ConstantSize && "AlwaysInline requires a constant size!");
6081 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6082 ConstantSize->getZExtValue(), Align, isVol,
6083 true, DstPtrInfo, SrcPtrInfo);
6086 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6087 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6089 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6090 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6091 // respect volatile, so they may do things like read or write memory
6092 // beyond the given memory regions. But fixing this isn't easy, and most
6093 // people don't care.
6095 // Emit a library call.
6096 TargetLowering::ArgListTy Args;
6097 TargetLowering::ArgListEntry Entry;
6098 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6099 Entry.Node = Dst; Args.push_back(Entry);
6100 Entry.Node = Src; Args.push_back(Entry);
6101 Entry.Node = Size; Args.push_back(Entry);
6102 // FIXME: pass in SDLoc
6103 TargetLowering::CallLoweringInfo CLI(*this);
6104 CLI.setDebugLoc(dl)
6105 .setChain(Chain)
6106 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6107 Dst.getValueType().getTypeForEVT(*getContext()),
6108 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6109 TLI->getPointerTy(getDataLayout())),
6110 std::move(Args))
6111 .setDiscardResult()
6112 .setTailCall(isTailCall);
6114 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6115 return CallResult.second;
6118 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6119 SDValue Dst, unsigned DstAlign,
6120 SDValue Src, unsigned SrcAlign,
6121 SDValue Size, Type *SizeTy,
6122 unsigned ElemSz, bool isTailCall,
6123 MachinePointerInfo DstPtrInfo,
6124 MachinePointerInfo SrcPtrInfo) {
6125 // Emit a library call.
6126 TargetLowering::ArgListTy Args;
6127 TargetLowering::ArgListEntry Entry;
6128 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6129 Entry.Node = Dst;
6130 Args.push_back(Entry);
6132 Entry.Node = Src;
6133 Args.push_back(Entry);
6135 Entry.Ty = SizeTy;
6136 Entry.Node = Size;
6137 Args.push_back(Entry);
6139 RTLIB::Libcall LibraryCall =
6140 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6141 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6142 report_fatal_error("Unsupported element size");
6144 TargetLowering::CallLoweringInfo CLI(*this);
6145 CLI.setDebugLoc(dl)
6146 .setChain(Chain)
6147 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6148 Type::getVoidTy(*getContext()),
6149 getExternalSymbol(TLI->getLibcallName(LibraryCall),
6150 TLI->getPointerTy(getDataLayout())),
6151 std::move(Args))
6152 .setDiscardResult()
6153 .setTailCall(isTailCall);
6155 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6156 return CallResult.second;
6159 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6160 SDValue Src, SDValue Size, unsigned Align,
6161 bool isVol, bool isTailCall,
6162 MachinePointerInfo DstPtrInfo,
6163 MachinePointerInfo SrcPtrInfo) {
6164 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
6166 // Check to see if we should lower the memmove to loads and stores first.
6167 // For cases within the target-specified limits, this is the best choice.
6168 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6169 if (ConstantSize) {
6170 // Memmove with size zero? Just return the original chain.
6171 if (ConstantSize->isNullValue())
6172 return Chain;
6174 SDValue Result =
6175 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
6176 ConstantSize->getZExtValue(), Align, isVol,
6177 false, DstPtrInfo, SrcPtrInfo);
6178 if (Result.getNode())
6179 return Result;
6182 // Then check to see if we should lower the memmove with target-specific
6183 // code. If the target chooses to do this, this is the next best.
6184 if (TSI) {
6185 SDValue Result = TSI->EmitTargetCodeForMemmove(
6186 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
6187 if (Result.getNode())
6188 return Result;
6191 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6192 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6194 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6195 // not be safe. See memcpy above for more details.
6197 // Emit a library call.
6198 TargetLowering::ArgListTy Args;
6199 TargetLowering::ArgListEntry Entry;
6200 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6201 Entry.Node = Dst; Args.push_back(Entry);
6202 Entry.Node = Src; Args.push_back(Entry);
6203 Entry.Node = Size; Args.push_back(Entry);
6204 // FIXME: pass in SDLoc
6205 TargetLowering::CallLoweringInfo CLI(*this);
6206 CLI.setDebugLoc(dl)
6207 .setChain(Chain)
6208 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
6209 Dst.getValueType().getTypeForEVT(*getContext()),
6210 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
6211 TLI->getPointerTy(getDataLayout())),
6212 std::move(Args))
6213 .setDiscardResult()
6214 .setTailCall(isTailCall);
6216 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6217 return CallResult.second;
6220 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
6221 SDValue Dst, unsigned DstAlign,
6222 SDValue Src, unsigned SrcAlign,
6223 SDValue Size, Type *SizeTy,
6224 unsigned ElemSz, bool isTailCall,
6225 MachinePointerInfo DstPtrInfo,
6226 MachinePointerInfo SrcPtrInfo) {
6227 // Emit a library call.
6228 TargetLowering::ArgListTy Args;
6229 TargetLowering::ArgListEntry Entry;
6230 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6231 Entry.Node = Dst;
6232 Args.push_back(Entry);
6234 Entry.Node = Src;
6235 Args.push_back(Entry);
6237 Entry.Ty = SizeTy;
6238 Entry.Node = Size;
6239 Args.push_back(Entry);
6241 RTLIB::Libcall LibraryCall =
6242 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6243 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6244 report_fatal_error("Unsupported element size");
6246 TargetLowering::CallLoweringInfo CLI(*this);
6247 CLI.setDebugLoc(dl)
6248 .setChain(Chain)
6249 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6250 Type::getVoidTy(*getContext()),
6251 getExternalSymbol(TLI->getLibcallName(LibraryCall),
6252 TLI->getPointerTy(getDataLayout())),
6253 std::move(Args))
6254 .setDiscardResult()
6255 .setTailCall(isTailCall);
6257 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6258 return CallResult.second;
6261 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
6262 SDValue Src, SDValue Size, unsigned Align,
6263 bool isVol, bool isTailCall,
6264 MachinePointerInfo DstPtrInfo) {
6265 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
6267 // Check to see if we should lower the memset to stores first.
6268 // For cases within the target-specified limits, this is the best choice.
6269 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6270 if (ConstantSize) {
6271 // Memset with size zero? Just return the original chain.
6272 if (ConstantSize->isNullValue())
6273 return Chain;
6275 SDValue Result =
6276 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
6277 Align, isVol, DstPtrInfo);
6279 if (Result.getNode())
6280 return Result;
6283 // Then check to see if we should lower the memset with target-specific
6284 // code. If the target chooses to do this, this is the next best.
6285 if (TSI) {
6286 SDValue Result = TSI->EmitTargetCodeForMemset(
6287 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo);
6288 if (Result.getNode())
6289 return Result;
6292 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6294 // Emit a library call.
6295 Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext());
6296 TargetLowering::ArgListTy Args;
6297 TargetLowering::ArgListEntry Entry;
6298 Entry.Node = Dst; Entry.Ty = IntPtrTy;
6299 Args.push_back(Entry);
6300 Entry.Node = Src;
6301 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
6302 Args.push_back(Entry);
6303 Entry.Node = Size;
6304 Entry.Ty = IntPtrTy;
6305 Args.push_back(Entry);
6307 // FIXME: pass in SDLoc
6308 TargetLowering::CallLoweringInfo CLI(*this);
6309 CLI.setDebugLoc(dl)
6310 .setChain(Chain)
6311 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
6312 Dst.getValueType().getTypeForEVT(*getContext()),
6313 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
6314 TLI->getPointerTy(getDataLayout())),
6315 std::move(Args))
6316 .setDiscardResult()
6317 .setTailCall(isTailCall);
6319 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6320 return CallResult.second;
6323 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
6324 SDValue Dst, unsigned DstAlign,
6325 SDValue Value, SDValue Size, Type *SizeTy,
6326 unsigned ElemSz, bool isTailCall,
6327 MachinePointerInfo DstPtrInfo) {
6328 // Emit a library call.
6329 TargetLowering::ArgListTy Args;
6330 TargetLowering::ArgListEntry Entry;
6331 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6332 Entry.Node = Dst;
6333 Args.push_back(Entry);
6335 Entry.Ty = Type::getInt8Ty(*getContext());
6336 Entry.Node = Value;
6337 Args.push_back(Entry);
6339 Entry.Ty = SizeTy;
6340 Entry.Node = Size;
6341 Args.push_back(Entry);
6343 RTLIB::Libcall LibraryCall =
6344 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6345 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6346 report_fatal_error("Unsupported element size");
6348 TargetLowering::CallLoweringInfo CLI(*this);
6349 CLI.setDebugLoc(dl)
6350 .setChain(Chain)
6351 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6352 Type::getVoidTy(*getContext()),
6353 getExternalSymbol(TLI->getLibcallName(LibraryCall),
6354 TLI->getPointerTy(getDataLayout())),
6355 std::move(Args))
6356 .setDiscardResult()
6357 .setTailCall(isTailCall);
6359 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6360 return CallResult.second;
6363 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6364 SDVTList VTList, ArrayRef<SDValue> Ops,
6365 MachineMemOperand *MMO) {
6366 FoldingSetNodeID ID;
6367 ID.AddInteger(MemVT.getRawBits());
6368 AddNodeIDNode(ID, Opcode, VTList, Ops);
6369 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6370 void* IP = nullptr;
6371 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6372 cast<AtomicSDNode>(E)->refineAlignment(MMO);
6373 return SDValue(E, 0);
6376 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6377 VTList, MemVT, MMO);
6378 createOperands(N, Ops);
6380 CSEMap.InsertNode(N, IP);
6381 InsertNode(N);
6382 return SDValue(N, 0);
6385 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
6386 EVT MemVT, SDVTList VTs, SDValue Chain,
6387 SDValue Ptr, SDValue Cmp, SDValue Swp,
6388 MachineMemOperand *MMO) {
6389 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
6390 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
6391 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
6393 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
6394 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6397 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6398 SDValue Chain, SDValue Ptr, SDValue Val,
6399 MachineMemOperand *MMO) {
6400 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
6401 Opcode == ISD::ATOMIC_LOAD_SUB ||
6402 Opcode == ISD::ATOMIC_LOAD_AND ||
6403 Opcode == ISD::ATOMIC_LOAD_CLR ||
6404 Opcode == ISD::ATOMIC_LOAD_OR ||
6405 Opcode == ISD::ATOMIC_LOAD_XOR ||
6406 Opcode == ISD::ATOMIC_LOAD_NAND ||
6407 Opcode == ISD::ATOMIC_LOAD_MIN ||
6408 Opcode == ISD::ATOMIC_LOAD_MAX ||
6409 Opcode == ISD::ATOMIC_LOAD_UMIN ||
6410 Opcode == ISD::ATOMIC_LOAD_UMAX ||
6411 Opcode == ISD::ATOMIC_LOAD_FADD ||
6412 Opcode == ISD::ATOMIC_LOAD_FSUB ||
6413 Opcode == ISD::ATOMIC_SWAP ||
6414 Opcode == ISD::ATOMIC_STORE) &&
6415 "Invalid Atomic Op");
6417 EVT VT = Val.getValueType();
6419 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
6420 getVTList(VT, MVT::Other);
6421 SDValue Ops[] = {Chain, Ptr, Val};
6422 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6425 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6426 EVT VT, SDValue Chain, SDValue Ptr,
6427 MachineMemOperand *MMO) {
6428 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
6430 SDVTList VTs = getVTList(VT, MVT::Other);
6431 SDValue Ops[] = {Chain, Ptr};
6432 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6435 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
6436 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
6437 if (Ops.size() == 1)
6438 return Ops[0];
6440 SmallVector<EVT, 4> VTs;
6441 VTs.reserve(Ops.size());
6442 for (unsigned i = 0; i < Ops.size(); ++i)
6443 VTs.push_back(Ops[i].getValueType());
6444 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
6447 SDValue SelectionDAG::getMemIntrinsicNode(
6448 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
6449 EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align,
6450 MachineMemOperand::Flags Flags, unsigned Size) {
6451 if (Align == 0) // Ensure that codegen never sees alignment 0
6452 Align = getEVTAlignment(MemVT);
6454 if (!Size)
6455 Size = MemVT.getStoreSize();
6457 MachineFunction &MF = getMachineFunction();
6458 MachineMemOperand *MMO =
6459 MF.getMachineMemOperand(PtrInfo, Flags, Size, Align);
6461 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
6464 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
6465 SDVTList VTList,
6466 ArrayRef<SDValue> Ops, EVT MemVT,
6467 MachineMemOperand *MMO) {
6468 assert((Opcode == ISD::INTRINSIC_VOID ||
6469 Opcode == ISD::INTRINSIC_W_CHAIN ||
6470 Opcode == ISD::PREFETCH ||
6471 Opcode == ISD::LIFETIME_START ||
6472 Opcode == ISD::LIFETIME_END ||
6473 ((int)Opcode <= std::numeric_limits<int>::max() &&
6474 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
6475 "Opcode is not a memory-accessing opcode!");
6477 // Memoize the node unless it returns a flag.
6478 MemIntrinsicSDNode *N;
6479 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
6480 FoldingSetNodeID ID;
6481 AddNodeIDNode(ID, Opcode, VTList, Ops);
6482 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
6483 Opcode, dl.getIROrder(), VTList, MemVT, MMO));
6484 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6485 void *IP = nullptr;
6486 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6487 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
6488 return SDValue(E, 0);
6491 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6492 VTList, MemVT, MMO);
6493 createOperands(N, Ops);
6495 CSEMap.InsertNode(N, IP);
6496 } else {
6497 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6498 VTList, MemVT, MMO);
6499 createOperands(N, Ops);
6501 InsertNode(N);
6502 return SDValue(N, 0);
6505 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
6506 SDValue Chain, int FrameIndex,
6507 int64_t Size, int64_t Offset) {
6508 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
6509 const auto VTs = getVTList(MVT::Other);
6510 SDValue Ops[2] = {
6511 Chain,
6512 getFrameIndex(FrameIndex,
6513 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
6514 true)};
6516 FoldingSetNodeID ID;
6517 AddNodeIDNode(ID, Opcode, VTs, Ops);
6518 ID.AddInteger(FrameIndex);
6519 ID.AddInteger(Size);
6520 ID.AddInteger(Offset);
6521 void *IP = nullptr;
6522 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
6523 return SDValue(E, 0);
6525 LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
6526 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
6527 createOperands(N, Ops);
6528 CSEMap.InsertNode(N, IP);
6529 InsertNode(N);
6530 SDValue V(N, 0);
6531 NewSDValueDbgMsg(V, "Creating new node: ", this);
6532 return V;
6535 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
6536 /// MachinePointerInfo record from it. This is particularly useful because the
6537 /// code generator has many cases where it doesn't bother passing in a
6538 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
6539 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
6540 SelectionDAG &DAG, SDValue Ptr,
6541 int64_t Offset = 0) {
6542 // If this is FI+Offset, we can model it.
6543 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
6544 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
6545 FI->getIndex(), Offset);
6547 // If this is (FI+Offset1)+Offset2, we can model it.
6548 if (Ptr.getOpcode() != ISD::ADD ||
6549 !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
6550 !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
6551 return Info;
6553 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6554 return MachinePointerInfo::getFixedStack(
6555 DAG.getMachineFunction(), FI,
6556 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
6559 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
6560 /// MachinePointerInfo record from it. This is particularly useful because the
6561 /// code generator has many cases where it doesn't bother passing in a
6562 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
6563 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
6564 SelectionDAG &DAG, SDValue Ptr,
6565 SDValue OffsetOp) {
6566 // If the 'Offset' value isn't a constant, we can't handle this.
6567 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
6568 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
6569 if (OffsetOp.isUndef())
6570 return InferPointerInfo(Info, DAG, Ptr);
6571 return Info;
6574 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
6575 EVT VT, const SDLoc &dl, SDValue Chain,
6576 SDValue Ptr, SDValue Offset,
6577 MachinePointerInfo PtrInfo, EVT MemVT,
6578 unsigned Alignment,
6579 MachineMemOperand::Flags MMOFlags,
6580 const AAMDNodes &AAInfo, const MDNode *Ranges) {
6581 assert(Chain.getValueType() == MVT::Other &&
6582 "Invalid chain type");
6583 if (Alignment == 0) // Ensure that codegen never sees alignment 0
6584 Alignment = getEVTAlignment(MemVT);
6586 MMOFlags |= MachineMemOperand::MOLoad;
6587 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
6588 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
6589 // clients.
6590 if (PtrInfo.V.isNull())
6591 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
6593 MachineFunction &MF = getMachineFunction();
6594 MachineMemOperand *MMO = MF.getMachineMemOperand(
6595 PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges);
6596 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
6599 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
6600 EVT VT, const SDLoc &dl, SDValue Chain,
6601 SDValue Ptr, SDValue Offset, EVT MemVT,
6602 MachineMemOperand *MMO) {
6603 if (VT == MemVT) {
6604 ExtType = ISD::NON_EXTLOAD;
6605 } else if (ExtType == ISD::NON_EXTLOAD) {
6606 assert(VT == MemVT && "Non-extending load from different memory type!");
6607 } else {
6608 // Extending load.
6609 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
6610 "Should only be an extending load, not truncating!");
6611 assert(VT.isInteger() == MemVT.isInteger() &&
6612 "Cannot convert from FP to Int or Int -> FP!");
6613 assert(VT.isVector() == MemVT.isVector() &&
6614 "Cannot use an ext load to convert to or from a vector!");
6615 assert((!VT.isVector() ||
6616 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
6617 "Cannot use an ext load to change the number of vector elements!");
6620 bool Indexed = AM != ISD::UNINDEXED;
6621 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
6623 SDVTList VTs = Indexed ?
6624 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
6625 SDValue Ops[] = { Chain, Ptr, Offset };
6626 FoldingSetNodeID ID;
6627 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
6628 ID.AddInteger(MemVT.getRawBits());
6629 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
6630 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
6631 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6632 void *IP = nullptr;
6633 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6634 cast<LoadSDNode>(E)->refineAlignment(MMO);
6635 return SDValue(E, 0);
6637 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
6638 ExtType, MemVT, MMO);
6639 createOperands(N, Ops);
6641 CSEMap.InsertNode(N, IP);
6642 InsertNode(N);
6643 SDValue V(N, 0);
6644 NewSDValueDbgMsg(V, "Creating new node: ", this);
6645 return V;
6648 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
6649 SDValue Ptr, MachinePointerInfo PtrInfo,
6650 unsigned Alignment,
6651 MachineMemOperand::Flags MMOFlags,
6652 const AAMDNodes &AAInfo, const MDNode *Ranges) {
6653 SDValue Undef = getUNDEF(Ptr.getValueType());
6654 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
6655 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
6658 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
6659 SDValue Ptr, MachineMemOperand *MMO) {
6660 SDValue Undef = getUNDEF(Ptr.getValueType());
6661 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
6662 VT, MMO);
6665 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
6666 EVT VT, SDValue Chain, SDValue Ptr,
6667 MachinePointerInfo PtrInfo, EVT MemVT,
6668 unsigned Alignment,
6669 MachineMemOperand::Flags MMOFlags,
6670 const AAMDNodes &AAInfo) {
6671 SDValue Undef = getUNDEF(Ptr.getValueType());
6672 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
6673 MemVT, Alignment, MMOFlags, AAInfo);
6676 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
6677 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
6678 MachineMemOperand *MMO) {
6679 SDValue Undef = getUNDEF(Ptr.getValueType());
6680 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
6681 MemVT, MMO);
6684 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
6685 SDValue Base, SDValue Offset,
6686 ISD::MemIndexedMode AM) {
6687 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
6688 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
6689 // Don't propagate the invariant or dereferenceable flags.
6690 auto MMOFlags =
6691 LD->getMemOperand()->getFlags() &
6692 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
6693 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
6694 LD->getChain(), Base, Offset, LD->getPointerInfo(),
6695 LD->getMemoryVT(), LD->getAlignment(), MMOFlags,
6696 LD->getAAInfo());
6699 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6700 SDValue Ptr, MachinePointerInfo PtrInfo,
6701 unsigned Alignment,
6702 MachineMemOperand::Flags MMOFlags,
6703 const AAMDNodes &AAInfo) {
6704 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
6705 if (Alignment == 0) // Ensure that codegen never sees alignment 0
6706 Alignment = getEVTAlignment(Val.getValueType());
6708 MMOFlags |= MachineMemOperand::MOStore;
6709 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
6711 if (PtrInfo.V.isNull())
6712 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
6714 MachineFunction &MF = getMachineFunction();
6715 MachineMemOperand *MMO = MF.getMachineMemOperand(
6716 PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo);
6717 return getStore(Chain, dl, Val, Ptr, MMO);
6720 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6721 SDValue Ptr, MachineMemOperand *MMO) {
6722 assert(Chain.getValueType() == MVT::Other &&
6723 "Invalid chain type");
6724 EVT VT = Val.getValueType();
6725 SDVTList VTs = getVTList(MVT::Other);
6726 SDValue Undef = getUNDEF(Ptr.getValueType());
6727 SDValue Ops[] = { Chain, Val, Ptr, Undef };
6728 FoldingSetNodeID ID;
6729 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6730 ID.AddInteger(VT.getRawBits());
6731 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
6732 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
6733 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6734 void *IP = nullptr;
6735 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6736 cast<StoreSDNode>(E)->refineAlignment(MMO);
6737 return SDValue(E, 0);
6739 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6740 ISD::UNINDEXED, false, VT, MMO);
6741 createOperands(N, Ops);
6743 CSEMap.InsertNode(N, IP);
6744 InsertNode(N);
6745 SDValue V(N, 0);
6746 NewSDValueDbgMsg(V, "Creating new node: ", this);
6747 return V;
6750 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6751 SDValue Ptr, MachinePointerInfo PtrInfo,
6752 EVT SVT, unsigned Alignment,
6753 MachineMemOperand::Flags MMOFlags,
6754 const AAMDNodes &AAInfo) {
6755 assert(Chain.getValueType() == MVT::Other &&
6756 "Invalid chain type");
6757 if (Alignment == 0) // Ensure that codegen never sees alignment 0
6758 Alignment = getEVTAlignment(SVT);
6760 MMOFlags |= MachineMemOperand::MOStore;
6761 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
6763 if (PtrInfo.V.isNull())
6764 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
6766 MachineFunction &MF = getMachineFunction();
6767 MachineMemOperand *MMO = MF.getMachineMemOperand(
6768 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
6769 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
6772 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6773 SDValue Ptr, EVT SVT,
6774 MachineMemOperand *MMO) {
6775 EVT VT = Val.getValueType();
6777 assert(Chain.getValueType() == MVT::Other &&
6778 "Invalid chain type");
6779 if (VT == SVT)
6780 return getStore(Chain, dl, Val, Ptr, MMO);
6782 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
6783 "Should only be a truncating store, not extending!");
6784 assert(VT.isInteger() == SVT.isInteger() &&
6785 "Can't do FP-INT conversion!");
6786 assert(VT.isVector() == SVT.isVector() &&
6787 "Cannot use trunc store to convert to or from a vector!");
6788 assert((!VT.isVector() ||
6789 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
6790 "Cannot use trunc store to change the number of vector elements!");
6792 SDVTList VTs = getVTList(MVT::Other);
6793 SDValue Undef = getUNDEF(Ptr.getValueType());
6794 SDValue Ops[] = { Chain, Val, Ptr, Undef };
6795 FoldingSetNodeID ID;
6796 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6797 ID.AddInteger(SVT.getRawBits());
6798 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
6799 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
6800 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6801 void *IP = nullptr;
6802 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6803 cast<StoreSDNode>(E)->refineAlignment(MMO);
6804 return SDValue(E, 0);
6806 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6807 ISD::UNINDEXED, true, SVT, MMO);
6808 createOperands(N, Ops);
6810 CSEMap.InsertNode(N, IP);
6811 InsertNode(N);
6812 SDValue V(N, 0);
6813 NewSDValueDbgMsg(V, "Creating new node: ", this);
6814 return V;
6817 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
6818 SDValue Base, SDValue Offset,
6819 ISD::MemIndexedMode AM) {
6820 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
6821 assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
6822 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
6823 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
6824 FoldingSetNodeID ID;
6825 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6826 ID.AddInteger(ST->getMemoryVT().getRawBits());
6827 ID.AddInteger(ST->getRawSubclassData());
6828 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
6829 void *IP = nullptr;
6830 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
6831 return SDValue(E, 0);
6833 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
6834 ST->isTruncatingStore(), ST->getMemoryVT(),
6835 ST->getMemOperand());
6836 createOperands(N, Ops);
6838 CSEMap.InsertNode(N, IP);
6839 InsertNode(N);
6840 SDValue V(N, 0);
6841 NewSDValueDbgMsg(V, "Creating new node: ", this);
6842 return V;
6845 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
6846 SDValue Ptr, SDValue Mask, SDValue PassThru,
6847 EVT MemVT, MachineMemOperand *MMO,
6848 ISD::LoadExtType ExtTy, bool isExpanding) {
6849 SDVTList VTs = getVTList(VT, MVT::Other);
6850 SDValue Ops[] = { Chain, Ptr, Mask, PassThru };
6851 FoldingSetNodeID ID;
6852 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
6853 ID.AddInteger(VT.getRawBits());
6854 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
6855 dl.getIROrder(), VTs, ExtTy, isExpanding, MemVT, MMO));
6856 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6857 void *IP = nullptr;
6858 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6859 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
6860 return SDValue(E, 0);
6862 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6863 ExtTy, isExpanding, MemVT, MMO);
6864 createOperands(N, Ops);
6866 CSEMap.InsertNode(N, IP);
6867 InsertNode(N);
6868 SDValue V(N, 0);
6869 NewSDValueDbgMsg(V, "Creating new node: ", this);
6870 return V;
6873 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
6874 SDValue Val, SDValue Ptr, SDValue Mask,
6875 EVT MemVT, MachineMemOperand *MMO,
6876 bool IsTruncating, bool IsCompressing) {
6877 assert(Chain.getValueType() == MVT::Other &&
6878 "Invalid chain type");
6879 EVT VT = Val.getValueType();
6880 SDVTList VTs = getVTList(MVT::Other);
6881 SDValue Ops[] = { Chain, Val, Ptr, Mask };
6882 FoldingSetNodeID ID;
6883 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
6884 ID.AddInteger(VT.getRawBits());
6885 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
6886 dl.getIROrder(), VTs, IsTruncating, IsCompressing, MemVT, MMO));
6887 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6888 void *IP = nullptr;
6889 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6890 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
6891 return SDValue(E, 0);
6893 auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6894 IsTruncating, IsCompressing, MemVT, MMO);
6895 createOperands(N, Ops);
6897 CSEMap.InsertNode(N, IP);
6898 InsertNode(N);
6899 SDValue V(N, 0);
6900 NewSDValueDbgMsg(V, "Creating new node: ", this);
6901 return V;
6904 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
6905 ArrayRef<SDValue> Ops,
6906 MachineMemOperand *MMO) {
6907 assert(Ops.size() == 6 && "Incompatible number of operands");
6909 FoldingSetNodeID ID;
6910 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
6911 ID.AddInteger(VT.getRawBits());
6912 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
6913 dl.getIROrder(), VTs, VT, MMO));
6914 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6915 void *IP = nullptr;
6916 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6917 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
6918 return SDValue(E, 0);
6921 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
6922 VTs, VT, MMO);
6923 createOperands(N, Ops);
6925 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
6926 "Incompatible type of the PassThru value in MaskedGatherSDNode");
6927 assert(N->getMask().getValueType().getVectorNumElements() ==
6928 N->getValueType(0).getVectorNumElements() &&
6929 "Vector width mismatch between mask and data");
6930 assert(N->getIndex().getValueType().getVectorNumElements() >=
6931 N->getValueType(0).getVectorNumElements() &&
6932 "Vector width mismatch between index and data");
6933 assert(isa<ConstantSDNode>(N->getScale()) &&
6934 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
6935 "Scale should be a constant power of 2");
6937 CSEMap.InsertNode(N, IP);
6938 InsertNode(N);
6939 SDValue V(N, 0);
6940 NewSDValueDbgMsg(V, "Creating new node: ", this);
6941 return V;
6944 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
6945 ArrayRef<SDValue> Ops,
6946 MachineMemOperand *MMO) {
6947 assert(Ops.size() == 6 && "Incompatible number of operands");
6949 FoldingSetNodeID ID;
6950 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
6951 ID.AddInteger(VT.getRawBits());
6952 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
6953 dl.getIROrder(), VTs, VT, MMO));
6954 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6955 void *IP = nullptr;
6956 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6957 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
6958 return SDValue(E, 0);
6960 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
6961 VTs, VT, MMO);
6962 createOperands(N, Ops);
6964 assert(N->getMask().getValueType().getVectorNumElements() ==
6965 N->getValue().getValueType().getVectorNumElements() &&
6966 "Vector width mismatch between mask and data");
6967 assert(N->getIndex().getValueType().getVectorNumElements() >=
6968 N->getValue().getValueType().getVectorNumElements() &&
6969 "Vector width mismatch between index and data");
6970 assert(isa<ConstantSDNode>(N->getScale()) &&
6971 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
6972 "Scale should be a constant power of 2");
6974 CSEMap.InsertNode(N, IP);
6975 InsertNode(N);
6976 SDValue V(N, 0);
6977 NewSDValueDbgMsg(V, "Creating new node: ", this);
6978 return V;
6981 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
6982 // select undef, T, F --> T (if T is a constant), otherwise F
6983 // select, ?, undef, F --> F
6984 // select, ?, T, undef --> T
6985 if (Cond.isUndef())
6986 return isConstantValueOfAnyType(T) ? T : F;
6987 if (T.isUndef())
6988 return F;
6989 if (F.isUndef())
6990 return T;
6992 // select true, T, F --> T
6993 // select false, T, F --> F
6994 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
6995 return CondC->isNullValue() ? F : T;
6997 // TODO: This should simplify VSELECT with constant condition using something
6998 // like this (but check boolean contents to be complete?):
6999 // if (ISD::isBuildVectorAllOnes(Cond.getNode()))
7000 // return T;
7001 // if (ISD::isBuildVectorAllZeros(Cond.getNode()))
7002 // return F;
7004 // select ?, T, T --> T
7005 if (T == F)
7006 return T;
7008 return SDValue();
7011 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
7012 // shift undef, Y --> 0 (can always assume that the undef value is 0)
7013 if (X.isUndef())
7014 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
7015 // shift X, undef --> undef (because it may shift by the bitwidth)
7016 if (Y.isUndef())
7017 return getUNDEF(X.getValueType());
7019 // shift 0, Y --> 0
7020 // shift X, 0 --> X
7021 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
7022 return X;
7024 // shift X, C >= bitwidth(X) --> undef
7025 // All vector elements must be too big (or undef) to avoid partial undefs.
7026 auto isShiftTooBig = [X](ConstantSDNode *Val) {
7027 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
7029 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
7030 return getUNDEF(X.getValueType());
7032 return SDValue();
7035 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
7036 SDValue Ptr, SDValue SV, unsigned Align) {
7037 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
7038 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
7041 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7042 ArrayRef<SDUse> Ops) {
7043 switch (Ops.size()) {
7044 case 0: return getNode(Opcode, DL, VT);
7045 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
7046 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
7047 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
7048 default: break;
7051 // Copy from an SDUse array into an SDValue array for use with
7052 // the regular getNode logic.
7053 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
7054 return getNode(Opcode, DL, VT, NewOps);
7057 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7058 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7059 unsigned NumOps = Ops.size();
7060 switch (NumOps) {
7061 case 0: return getNode(Opcode, DL, VT);
7062 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
7063 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
7064 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
7065 default: break;
7068 switch (Opcode) {
7069 default: break;
7070 case ISD::BUILD_VECTOR:
7071 // Attempt to simplify BUILD_VECTOR.
7072 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7073 return V;
7074 break;
7075 case ISD::CONCAT_VECTORS:
7076 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
7077 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
7078 return V;
7079 break;
7080 case ISD::SELECT_CC:
7081 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
7082 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
7083 "LHS and RHS of condition must have same type!");
7084 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7085 "True and False arms of SelectCC must have same type!");
7086 assert(Ops[2].getValueType() == VT &&
7087 "select_cc node must be of same type as true and false value!");
7088 break;
7089 case ISD::BR_CC:
7090 assert(NumOps == 5 && "BR_CC takes 5 operands!");
7091 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7092 "LHS/RHS of comparison should match types!");
7093 break;
7096 // Memoize nodes.
7097 SDNode *N;
7098 SDVTList VTs = getVTList(VT);
7100 if (VT != MVT::Glue) {
7101 FoldingSetNodeID ID;
7102 AddNodeIDNode(ID, Opcode, VTs, Ops);
7103 void *IP = nullptr;
7105 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7106 return SDValue(E, 0);
7108 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7109 createOperands(N, Ops);
7111 CSEMap.InsertNode(N, IP);
7112 } else {
7113 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7114 createOperands(N, Ops);
7117 InsertNode(N);
7118 SDValue V(N, 0);
7119 NewSDValueDbgMsg(V, "Creating new node: ", this);
7120 return V;
7123 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7124 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
7125 return getNode(Opcode, DL, getVTList(ResultTys), Ops);
7128 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7129 ArrayRef<SDValue> Ops) {
7130 if (VTList.NumVTs == 1)
7131 return getNode(Opcode, DL, VTList.VTs[0], Ops);
7133 #if 0
7134 switch (Opcode) {
7135 // FIXME: figure out how to safely handle things like
7136 // int foo(int x) { return 1 << (x & 255); }
7137 // int bar() { return foo(256); }
7138 case ISD::SRA_PARTS:
7139 case ISD::SRL_PARTS:
7140 case ISD::SHL_PARTS:
7141 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7142 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
7143 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7144 else if (N3.getOpcode() == ISD::AND)
7145 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
7146 // If the and is only masking out bits that cannot effect the shift,
7147 // eliminate the and.
7148 unsigned NumBits = VT.getScalarSizeInBits()*2;
7149 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
7150 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7152 break;
7154 #endif
7156 // Memoize the node unless it returns a flag.
7157 SDNode *N;
7158 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7159 FoldingSetNodeID ID;
7160 AddNodeIDNode(ID, Opcode, VTList, Ops);
7161 void *IP = nullptr;
7162 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7163 return SDValue(E, 0);
7165 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7166 createOperands(N, Ops);
7167 CSEMap.InsertNode(N, IP);
7168 } else {
7169 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7170 createOperands(N, Ops);
7172 InsertNode(N);
7173 SDValue V(N, 0);
7174 NewSDValueDbgMsg(V, "Creating new node: ", this);
7175 return V;
7178 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7179 SDVTList VTList) {
7180 return getNode(Opcode, DL, VTList, None);
7183 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7184 SDValue N1) {
7185 SDValue Ops[] = { N1 };
7186 return getNode(Opcode, DL, VTList, Ops);
7189 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7190 SDValue N1, SDValue N2) {
7191 SDValue Ops[] = { N1, N2 };
7192 return getNode(Opcode, DL, VTList, Ops);
7195 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7196 SDValue N1, SDValue N2, SDValue N3) {
7197 SDValue Ops[] = { N1, N2, N3 };
7198 return getNode(Opcode, DL, VTList, Ops);
7201 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7202 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
7203 SDValue Ops[] = { N1, N2, N3, N4 };
7204 return getNode(Opcode, DL, VTList, Ops);
7207 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7208 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
7209 SDValue N5) {
7210 SDValue Ops[] = { N1, N2, N3, N4, N5 };
7211 return getNode(Opcode, DL, VTList, Ops);
7214 SDVTList SelectionDAG::getVTList(EVT VT) {
7215 return makeVTList(SDNode::getValueTypeList(VT), 1);
7218 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
7219 FoldingSetNodeID ID;
7220 ID.AddInteger(2U);
7221 ID.AddInteger(VT1.getRawBits());
7222 ID.AddInteger(VT2.getRawBits());
7224 void *IP = nullptr;
7225 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7226 if (!Result) {
7227 EVT *Array = Allocator.Allocate<EVT>(2);
7228 Array[0] = VT1;
7229 Array[1] = VT2;
7230 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
7231 VTListMap.InsertNode(Result, IP);
7233 return Result->getSDVTList();
7236 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
7237 FoldingSetNodeID ID;
7238 ID.AddInteger(3U);
7239 ID.AddInteger(VT1.getRawBits());
7240 ID.AddInteger(VT2.getRawBits());
7241 ID.AddInteger(VT3.getRawBits());
7243 void *IP = nullptr;
7244 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7245 if (!Result) {
7246 EVT *Array = Allocator.Allocate<EVT>(3);
7247 Array[0] = VT1;
7248 Array[1] = VT2;
7249 Array[2] = VT3;
7250 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
7251 VTListMap.InsertNode(Result, IP);
7253 return Result->getSDVTList();
7256 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
7257 FoldingSetNodeID ID;
7258 ID.AddInteger(4U);
7259 ID.AddInteger(VT1.getRawBits());
7260 ID.AddInteger(VT2.getRawBits());
7261 ID.AddInteger(VT3.getRawBits());
7262 ID.AddInteger(VT4.getRawBits());
7264 void *IP = nullptr;
7265 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7266 if (!Result) {
7267 EVT *Array = Allocator.Allocate<EVT>(4);
7268 Array[0] = VT1;
7269 Array[1] = VT2;
7270 Array[2] = VT3;
7271 Array[3] = VT4;
7272 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
7273 VTListMap.InsertNode(Result, IP);
7275 return Result->getSDVTList();
7278 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
7279 unsigned NumVTs = VTs.size();
7280 FoldingSetNodeID ID;
7281 ID.AddInteger(NumVTs);
7282 for (unsigned index = 0; index < NumVTs; index++) {
7283 ID.AddInteger(VTs[index].getRawBits());
7286 void *IP = nullptr;
7287 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7288 if (!Result) {
7289 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
7290 llvm::copy(VTs, Array);
7291 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
7292 VTListMap.InsertNode(Result, IP);
7294 return Result->getSDVTList();
7298 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
7299 /// specified operands. If the resultant node already exists in the DAG,
7300 /// this does not modify the specified node, instead it returns the node that
7301 /// already exists. If the resultant node does not exist in the DAG, the
7302 /// input node is returned. As a degenerate case, if you specify the same
7303 /// input operands as the node already has, the input node is returned.
7304 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
7305 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
7307 // Check to see if there is no change.
7308 if (Op == N->getOperand(0)) return N;
7310 // See if the modified node already exists.
7311 void *InsertPos = nullptr;
7312 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
7313 return Existing;
7315 // Nope it doesn't. Remove the node from its current place in the maps.
7316 if (InsertPos)
7317 if (!RemoveNodeFromCSEMaps(N))
7318 InsertPos = nullptr;
7320 // Now we update the operands.
7321 N->OperandList[0].set(Op);
7323 updateDivergence(N);
7324 // If this gets put into a CSE map, add it.
7325 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7326 return N;
7329 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
7330 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
7332 // Check to see if there is no change.
7333 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
7334 return N; // No operands changed, just return the input node.
7336 // See if the modified node already exists.
7337 void *InsertPos = nullptr;
7338 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
7339 return Existing;
7341 // Nope it doesn't. Remove the node from its current place in the maps.
7342 if (InsertPos)
7343 if (!RemoveNodeFromCSEMaps(N))
7344 InsertPos = nullptr;
7346 // Now we update the operands.
7347 if (N->OperandList[0] != Op1)
7348 N->OperandList[0].set(Op1);
7349 if (N->OperandList[1] != Op2)
7350 N->OperandList[1].set(Op2);
7352 updateDivergence(N);
7353 // If this gets put into a CSE map, add it.
7354 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7355 return N;
7358 SDNode *SelectionDAG::
7359 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
7360 SDValue Ops[] = { Op1, Op2, Op3 };
7361 return UpdateNodeOperands(N, Ops);
7364 SDNode *SelectionDAG::
7365 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
7366 SDValue Op3, SDValue Op4) {
7367 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
7368 return UpdateNodeOperands(N, Ops);
7371 SDNode *SelectionDAG::
7372 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
7373 SDValue Op3, SDValue Op4, SDValue Op5) {
7374 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
7375 return UpdateNodeOperands(N, Ops);
7378 SDNode *SelectionDAG::
7379 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
7380 unsigned NumOps = Ops.size();
7381 assert(N->getNumOperands() == NumOps &&
7382 "Update with wrong number of operands");
7384 // If no operands changed just return the input node.
7385 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
7386 return N;
7388 // See if the modified node already exists.
7389 void *InsertPos = nullptr;
7390 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
7391 return Existing;
7393 // Nope it doesn't. Remove the node from its current place in the maps.
7394 if (InsertPos)
7395 if (!RemoveNodeFromCSEMaps(N))
7396 InsertPos = nullptr;
7398 // Now we update the operands.
7399 for (unsigned i = 0; i != NumOps; ++i)
7400 if (N->OperandList[i] != Ops[i])
7401 N->OperandList[i].set(Ops[i]);
7403 updateDivergence(N);
7404 // If this gets put into a CSE map, add it.
7405 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7406 return N;
7409 /// DropOperands - Release the operands and set this node to have
7410 /// zero operands.
7411 void SDNode::DropOperands() {
7412 // Unlike the code in MorphNodeTo that does this, we don't need to
7413 // watch for dead nodes here.
7414 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
7415 SDUse &Use = *I++;
7416 Use.set(SDValue());
7420 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
7421 ArrayRef<MachineMemOperand *> NewMemRefs) {
7422 if (NewMemRefs.empty()) {
7423 N->clearMemRefs();
7424 return;
7427 // Check if we can avoid allocating by storing a single reference directly.
7428 if (NewMemRefs.size() == 1) {
7429 N->MemRefs = NewMemRefs[0];
7430 N->NumMemRefs = 1;
7431 return;
7434 MachineMemOperand **MemRefsBuffer =
7435 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
7436 llvm::copy(NewMemRefs, MemRefsBuffer);
7437 N->MemRefs = MemRefsBuffer;
7438 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
7441 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
7442 /// machine opcode.
7444 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7445 EVT VT) {
7446 SDVTList VTs = getVTList(VT);
7447 return SelectNodeTo(N, MachineOpc, VTs, None);
7450 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7451 EVT VT, SDValue Op1) {
7452 SDVTList VTs = getVTList(VT);
7453 SDValue Ops[] = { Op1 };
7454 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7457 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7458 EVT VT, SDValue Op1,
7459 SDValue Op2) {
7460 SDVTList VTs = getVTList(VT);
7461 SDValue Ops[] = { Op1, Op2 };
7462 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7465 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7466 EVT VT, SDValue Op1,
7467 SDValue Op2, SDValue Op3) {
7468 SDVTList VTs = getVTList(VT);
7469 SDValue Ops[] = { Op1, Op2, Op3 };
7470 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7473 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7474 EVT VT, ArrayRef<SDValue> Ops) {
7475 SDVTList VTs = getVTList(VT);
7476 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7479 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7480 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
7481 SDVTList VTs = getVTList(VT1, VT2);
7482 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7485 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7486 EVT VT1, EVT VT2) {
7487 SDVTList VTs = getVTList(VT1, VT2);
7488 return SelectNodeTo(N, MachineOpc, VTs, None);
7491 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7492 EVT VT1, EVT VT2, EVT VT3,
7493 ArrayRef<SDValue> Ops) {
7494 SDVTList VTs = getVTList(VT1, VT2, VT3);
7495 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7498 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7499 EVT VT1, EVT VT2,
7500 SDValue Op1, SDValue Op2) {
7501 SDVTList VTs = getVTList(VT1, VT2);
7502 SDValue Ops[] = { Op1, Op2 };
7503 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7506 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7507 SDVTList VTs,ArrayRef<SDValue> Ops) {
7508 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
7509 // Reset the NodeID to -1.
7510 New->setNodeId(-1);
7511 if (New != N) {
7512 ReplaceAllUsesWith(N, New);
7513 RemoveDeadNode(N);
7515 return New;
7518 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
7519 /// the line number information on the merged node since it is not possible to
7520 /// preserve the information that operation is associated with multiple lines.
7521 /// This will make the debugger working better at -O0, were there is a higher
7522 /// probability having other instructions associated with that line.
7524 /// For IROrder, we keep the smaller of the two
7525 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
7526 DebugLoc NLoc = N->getDebugLoc();
7527 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
7528 N->setDebugLoc(DebugLoc());
7530 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
7531 N->setIROrder(Order);
7532 return N;
7535 /// MorphNodeTo - This *mutates* the specified node to have the specified
7536 /// return type, opcode, and operands.
7538 /// Note that MorphNodeTo returns the resultant node. If there is already a
7539 /// node of the specified opcode and operands, it returns that node instead of
7540 /// the current one. Note that the SDLoc need not be the same.
7542 /// Using MorphNodeTo is faster than creating a new node and swapping it in
7543 /// with ReplaceAllUsesWith both because it often avoids allocating a new
7544 /// node, and because it doesn't require CSE recalculation for any of
7545 /// the node's users.
7547 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
7548 /// As a consequence it isn't appropriate to use from within the DAG combiner or
7549 /// the legalizer which maintain worklists that would need to be updated when
7550 /// deleting things.
7551 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
7552 SDVTList VTs, ArrayRef<SDValue> Ops) {
7553 // If an identical node already exists, use it.
7554 void *IP = nullptr;
7555 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
7556 FoldingSetNodeID ID;
7557 AddNodeIDNode(ID, Opc, VTs, Ops);
7558 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
7559 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
7562 if (!RemoveNodeFromCSEMaps(N))
7563 IP = nullptr;
7565 // Start the morphing.
7566 N->NodeType = Opc;
7567 N->ValueList = VTs.VTs;
7568 N->NumValues = VTs.NumVTs;
7570 // Clear the operands list, updating used nodes to remove this from their
7571 // use list. Keep track of any operands that become dead as a result.
7572 SmallPtrSet<SDNode*, 16> DeadNodeSet;
7573 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
7574 SDUse &Use = *I++;
7575 SDNode *Used = Use.getNode();
7576 Use.set(SDValue());
7577 if (Used->use_empty())
7578 DeadNodeSet.insert(Used);
7581 // For MachineNode, initialize the memory references information.
7582 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
7583 MN->clearMemRefs();
7585 // Swap for an appropriately sized array from the recycler.
7586 removeOperands(N);
7587 createOperands(N, Ops);
7589 // Delete any nodes that are still dead after adding the uses for the
7590 // new operands.
7591 if (!DeadNodeSet.empty()) {
7592 SmallVector<SDNode *, 16> DeadNodes;
7593 for (SDNode *N : DeadNodeSet)
7594 if (N->use_empty())
7595 DeadNodes.push_back(N);
7596 RemoveDeadNodes(DeadNodes);
7599 if (IP)
7600 CSEMap.InsertNode(N, IP); // Memoize the new node.
7601 return N;
7604 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
7605 unsigned OrigOpc = Node->getOpcode();
7606 unsigned NewOpc;
7607 bool IsUnary = false;
7608 bool IsTernary = false;
7609 switch (OrigOpc) {
7610 default:
7611 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
7612 case ISD::STRICT_FADD: NewOpc = ISD::FADD; break;
7613 case ISD::STRICT_FSUB: NewOpc = ISD::FSUB; break;
7614 case ISD::STRICT_FMUL: NewOpc = ISD::FMUL; break;
7615 case ISD::STRICT_FDIV: NewOpc = ISD::FDIV; break;
7616 case ISD::STRICT_FREM: NewOpc = ISD::FREM; break;
7617 case ISD::STRICT_FMA: NewOpc = ISD::FMA; IsTernary = true; break;
7618 case ISD::STRICT_FSQRT: NewOpc = ISD::FSQRT; IsUnary = true; break;
7619 case ISD::STRICT_FPOW: NewOpc = ISD::FPOW; break;
7620 case ISD::STRICT_FPOWI: NewOpc = ISD::FPOWI; break;
7621 case ISD::STRICT_FSIN: NewOpc = ISD::FSIN; IsUnary = true; break;
7622 case ISD::STRICT_FCOS: NewOpc = ISD::FCOS; IsUnary = true; break;
7623 case ISD::STRICT_FEXP: NewOpc = ISD::FEXP; IsUnary = true; break;
7624 case ISD::STRICT_FEXP2: NewOpc = ISD::FEXP2; IsUnary = true; break;
7625 case ISD::STRICT_FLOG: NewOpc = ISD::FLOG; IsUnary = true; break;
7626 case ISD::STRICT_FLOG10: NewOpc = ISD::FLOG10; IsUnary = true; break;
7627 case ISD::STRICT_FLOG2: NewOpc = ISD::FLOG2; IsUnary = true; break;
7628 case ISD::STRICT_FRINT: NewOpc = ISD::FRINT; IsUnary = true; break;
7629 case ISD::STRICT_FNEARBYINT:
7630 NewOpc = ISD::FNEARBYINT;
7631 IsUnary = true;
7632 break;
7633 case ISD::STRICT_FMAXNUM: NewOpc = ISD::FMAXNUM; break;
7634 case ISD::STRICT_FMINNUM: NewOpc = ISD::FMINNUM; break;
7635 case ISD::STRICT_FCEIL: NewOpc = ISD::FCEIL; IsUnary = true; break;
7636 case ISD::STRICT_FFLOOR: NewOpc = ISD::FFLOOR; IsUnary = true; break;
7637 case ISD::STRICT_FROUND: NewOpc = ISD::FROUND; IsUnary = true; break;
7638 case ISD::STRICT_FTRUNC: NewOpc = ISD::FTRUNC; IsUnary = true; break;
7641 // We're taking this node out of the chain, so we need to re-link things.
7642 SDValue InputChain = Node->getOperand(0);
7643 SDValue OutputChain = SDValue(Node, 1);
7644 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
7646 SDVTList VTs = getVTList(Node->getOperand(1).getValueType());
7647 SDNode *Res = nullptr;
7648 if (IsUnary)
7649 Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1) });
7650 else if (IsTernary)
7651 Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1),
7652 Node->getOperand(2),
7653 Node->getOperand(3)});
7654 else
7655 Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1),
7656 Node->getOperand(2) });
7658 // MorphNodeTo can operate in two ways: if an existing node with the
7659 // specified operands exists, it can just return it. Otherwise, it
7660 // updates the node in place to have the requested operands.
7661 if (Res == Node) {
7662 // If we updated the node in place, reset the node ID. To the isel,
7663 // this should be just like a newly allocated machine node.
7664 Res->setNodeId(-1);
7665 } else {
7666 ReplaceAllUsesWith(Node, Res);
7667 RemoveDeadNode(Node);
7670 return Res;
7673 /// getMachineNode - These are used for target selectors to create a new node
7674 /// with specified return type(s), MachineInstr opcode, and operands.
7676 /// Note that getMachineNode returns the resultant node. If there is already a
7677 /// node of the specified opcode and operands, it returns that node instead of
7678 /// the current one.
7679 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7680 EVT VT) {
7681 SDVTList VTs = getVTList(VT);
7682 return getMachineNode(Opcode, dl, VTs, None);
7685 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7686 EVT VT, SDValue Op1) {
7687 SDVTList VTs = getVTList(VT);
7688 SDValue Ops[] = { Op1 };
7689 return getMachineNode(Opcode, dl, VTs, Ops);
7692 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7693 EVT VT, SDValue Op1, SDValue Op2) {
7694 SDVTList VTs = getVTList(VT);
7695 SDValue Ops[] = { Op1, Op2 };
7696 return getMachineNode(Opcode, dl, VTs, Ops);
7699 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7700 EVT VT, SDValue Op1, SDValue Op2,
7701 SDValue Op3) {
7702 SDVTList VTs = getVTList(VT);
7703 SDValue Ops[] = { Op1, Op2, Op3 };
7704 return getMachineNode(Opcode, dl, VTs, Ops);
7707 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7708 EVT VT, ArrayRef<SDValue> Ops) {
7709 SDVTList VTs = getVTList(VT);
7710 return getMachineNode(Opcode, dl, VTs, Ops);
7713 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7714 EVT VT1, EVT VT2, SDValue Op1,
7715 SDValue Op2) {
7716 SDVTList VTs = getVTList(VT1, VT2);
7717 SDValue Ops[] = { Op1, Op2 };
7718 return getMachineNode(Opcode, dl, VTs, Ops);
7721 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7722 EVT VT1, EVT VT2, SDValue Op1,
7723 SDValue Op2, SDValue Op3) {
7724 SDVTList VTs = getVTList(VT1, VT2);
7725 SDValue Ops[] = { Op1, Op2, Op3 };
7726 return getMachineNode(Opcode, dl, VTs, Ops);
7729 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7730 EVT VT1, EVT VT2,
7731 ArrayRef<SDValue> Ops) {
7732 SDVTList VTs = getVTList(VT1, VT2);
7733 return getMachineNode(Opcode, dl, VTs, Ops);
7736 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7737 EVT VT1, EVT VT2, EVT VT3,
7738 SDValue Op1, SDValue Op2) {
7739 SDVTList VTs = getVTList(VT1, VT2, VT3);
7740 SDValue Ops[] = { Op1, Op2 };
7741 return getMachineNode(Opcode, dl, VTs, Ops);
7744 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7745 EVT VT1, EVT VT2, EVT VT3,
7746 SDValue Op1, SDValue Op2,
7747 SDValue Op3) {
7748 SDVTList VTs = getVTList(VT1, VT2, VT3);
7749 SDValue Ops[] = { Op1, Op2, Op3 };
7750 return getMachineNode(Opcode, dl, VTs, Ops);
7753 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7754 EVT VT1, EVT VT2, EVT VT3,
7755 ArrayRef<SDValue> Ops) {
7756 SDVTList VTs = getVTList(VT1, VT2, VT3);
7757 return getMachineNode(Opcode, dl, VTs, Ops);
7760 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7761 ArrayRef<EVT> ResultTys,
7762 ArrayRef<SDValue> Ops) {
7763 SDVTList VTs = getVTList(ResultTys);
7764 return getMachineNode(Opcode, dl, VTs, Ops);
7767 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
7768 SDVTList VTs,
7769 ArrayRef<SDValue> Ops) {
7770 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
7771 MachineSDNode *N;
7772 void *IP = nullptr;
7774 if (DoCSE) {
7775 FoldingSetNodeID ID;
7776 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
7777 IP = nullptr;
7778 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
7779 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
7783 // Allocate a new MachineSDNode.
7784 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7785 createOperands(N, Ops);
7787 if (DoCSE)
7788 CSEMap.InsertNode(N, IP);
7790 InsertNode(N);
7791 return N;
7794 /// getTargetExtractSubreg - A convenience function for creating
7795 /// TargetOpcode::EXTRACT_SUBREG nodes.
7796 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
7797 SDValue Operand) {
7798 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
7799 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
7800 VT, Operand, SRIdxVal);
7801 return SDValue(Subreg, 0);
7804 /// getTargetInsertSubreg - A convenience function for creating
7805 /// TargetOpcode::INSERT_SUBREG nodes.
7806 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
7807 SDValue Operand, SDValue Subreg) {
7808 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
7809 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
7810 VT, Operand, Subreg, SRIdxVal);
7811 return SDValue(Result, 0);
7814 /// getNodeIfExists - Get the specified node if it's already available, or
7815 /// else return NULL.
7816 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
7817 ArrayRef<SDValue> Ops,
7818 const SDNodeFlags Flags) {
7819 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
7820 FoldingSetNodeID ID;
7821 AddNodeIDNode(ID, Opcode, VTList, Ops);
7822 void *IP = nullptr;
7823 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
7824 E->intersectFlagsWith(Flags);
7825 return E;
7828 return nullptr;
7831 /// getDbgValue - Creates a SDDbgValue node.
7833 /// SDNode
7834 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
7835 SDNode *N, unsigned R, bool IsIndirect,
7836 const DebugLoc &DL, unsigned O) {
7837 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7838 "Expected inlined-at fields to agree");
7839 return new (DbgInfo->getAlloc())
7840 SDDbgValue(Var, Expr, N, R, IsIndirect, DL, O);
7843 /// Constant
7844 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
7845 DIExpression *Expr,
7846 const Value *C,
7847 const DebugLoc &DL, unsigned O) {
7848 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7849 "Expected inlined-at fields to agree");
7850 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, DL, O);
7853 /// FrameIndex
7854 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
7855 DIExpression *Expr, unsigned FI,
7856 bool IsIndirect,
7857 const DebugLoc &DL,
7858 unsigned O) {
7859 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7860 "Expected inlined-at fields to agree");
7861 return new (DbgInfo->getAlloc())
7862 SDDbgValue(Var, Expr, FI, IsIndirect, DL, O, SDDbgValue::FRAMEIX);
7865 /// VReg
7866 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var,
7867 DIExpression *Expr,
7868 unsigned VReg, bool IsIndirect,
7869 const DebugLoc &DL, unsigned O) {
7870 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7871 "Expected inlined-at fields to agree");
7872 return new (DbgInfo->getAlloc())
7873 SDDbgValue(Var, Expr, VReg, IsIndirect, DL, O, SDDbgValue::VREG);
7876 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
7877 unsigned OffsetInBits, unsigned SizeInBits,
7878 bool InvalidateDbg) {
7879 SDNode *FromNode = From.getNode();
7880 SDNode *ToNode = To.getNode();
7881 assert(FromNode && ToNode && "Can't modify dbg values");
7883 // PR35338
7884 // TODO: assert(From != To && "Redundant dbg value transfer");
7885 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
7886 if (From == To || FromNode == ToNode)
7887 return;
7889 if (!FromNode->getHasDebugValue())
7890 return;
7892 SmallVector<SDDbgValue *, 2> ClonedDVs;
7893 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
7894 if (Dbg->getKind() != SDDbgValue::SDNODE || Dbg->isInvalidated())
7895 continue;
7897 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
7899 // Just transfer the dbg value attached to From.
7900 if (Dbg->getResNo() != From.getResNo())
7901 continue;
7903 DIVariable *Var = Dbg->getVariable();
7904 auto *Expr = Dbg->getExpression();
7905 // If a fragment is requested, update the expression.
7906 if (SizeInBits) {
7907 // When splitting a larger (e.g., sign-extended) value whose
7908 // lower bits are described with an SDDbgValue, do not attempt
7909 // to transfer the SDDbgValue to the upper bits.
7910 if (auto FI = Expr->getFragmentInfo())
7911 if (OffsetInBits + SizeInBits > FI->SizeInBits)
7912 continue;
7913 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
7914 SizeInBits);
7915 if (!Fragment)
7916 continue;
7917 Expr = *Fragment;
7919 // Clone the SDDbgValue and move it to To.
7920 SDDbgValue *Clone =
7921 getDbgValue(Var, Expr, ToNode, To.getResNo(), Dbg->isIndirect(),
7922 Dbg->getDebugLoc(), Dbg->getOrder());
7923 ClonedDVs.push_back(Clone);
7925 if (InvalidateDbg) {
7926 // Invalidate value and indicate the SDDbgValue should not be emitted.
7927 Dbg->setIsInvalidated();
7928 Dbg->setIsEmitted();
7932 for (SDDbgValue *Dbg : ClonedDVs)
7933 AddDbgValue(Dbg, ToNode, false);
7936 void SelectionDAG::salvageDebugInfo(SDNode &N) {
7937 if (!N.getHasDebugValue())
7938 return;
7940 SmallVector<SDDbgValue *, 2> ClonedDVs;
7941 for (auto DV : GetDbgValues(&N)) {
7942 if (DV->isInvalidated())
7943 continue;
7944 switch (N.getOpcode()) {
7945 default:
7946 break;
7947 case ISD::ADD:
7948 SDValue N0 = N.getOperand(0);
7949 SDValue N1 = N.getOperand(1);
7950 if (!isConstantIntBuildVectorOrConstantInt(N0) &&
7951 isConstantIntBuildVectorOrConstantInt(N1)) {
7952 uint64_t Offset = N.getConstantOperandVal(1);
7953 // Rewrite an ADD constant node into a DIExpression. Since we are
7954 // performing arithmetic to compute the variable's *value* in the
7955 // DIExpression, we need to mark the expression with a
7956 // DW_OP_stack_value.
7957 auto *DIExpr = DV->getExpression();
7958 DIExpr = DIExpression::prepend(DIExpr, DIExpression::NoDeref, Offset,
7959 DIExpression::NoDeref,
7960 DIExpression::WithStackValue);
7961 SDDbgValue *Clone =
7962 getDbgValue(DV->getVariable(), DIExpr, N0.getNode(), N0.getResNo(),
7963 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder());
7964 ClonedDVs.push_back(Clone);
7965 DV->setIsInvalidated();
7966 DV->setIsEmitted();
7967 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
7968 N0.getNode()->dumprFull(this);
7969 dbgs() << " into " << *DIExpr << '\n');
7974 for (SDDbgValue *Dbg : ClonedDVs)
7975 AddDbgValue(Dbg, Dbg->getSDNode(), false);
7978 /// Creates a SDDbgLabel node.
7979 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
7980 const DebugLoc &DL, unsigned O) {
7981 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
7982 "Expected inlined-at fields to agree");
7983 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
7986 namespace {
7988 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
7989 /// pointed to by a use iterator is deleted, increment the use iterator
7990 /// so that it doesn't dangle.
7992 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
7993 SDNode::use_iterator &UI;
7994 SDNode::use_iterator &UE;
7996 void NodeDeleted(SDNode *N, SDNode *E) override {
7997 // Increment the iterator as needed.
7998 while (UI != UE && N == *UI)
7999 ++UI;
8002 public:
8003 RAUWUpdateListener(SelectionDAG &d,
8004 SDNode::use_iterator &ui,
8005 SDNode::use_iterator &ue)
8006 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
8009 } // end anonymous namespace
8011 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8012 /// This can cause recursive merging of nodes in the DAG.
8014 /// This version assumes From has a single result value.
8016 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
8017 SDNode *From = FromN.getNode();
8018 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
8019 "Cannot replace with this method!");
8020 assert(From != To.getNode() && "Cannot replace uses of with self");
8022 // Preserve Debug Values
8023 transferDbgValues(FromN, To);
8025 // Iterate over all the existing uses of From. New uses will be added
8026 // to the beginning of the use list, which we avoid visiting.
8027 // This specifically avoids visiting uses of From that arise while the
8028 // replacement is happening, because any such uses would be the result
8029 // of CSE: If an existing node looks like From after one of its operands
8030 // is replaced by To, we don't want to replace of all its users with To
8031 // too. See PR3018 for more info.
8032 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8033 RAUWUpdateListener Listener(*this, UI, UE);
8034 while (UI != UE) {
8035 SDNode *User = *UI;
8037 // This node is about to morph, remove its old self from the CSE maps.
8038 RemoveNodeFromCSEMaps(User);
8040 // A user can appear in a use list multiple times, and when this
8041 // happens the uses are usually next to each other in the list.
8042 // To help reduce the number of CSE recomputations, process all
8043 // the uses of this user that we can find this way.
8044 do {
8045 SDUse &Use = UI.getUse();
8046 ++UI;
8047 Use.set(To);
8048 if (To->isDivergent() != From->isDivergent())
8049 updateDivergence(User);
8050 } while (UI != UE && *UI == User);
8051 // Now that we have modified User, add it back to the CSE maps. If it
8052 // already exists there, recursively merge the results together.
8053 AddModifiedNodeToCSEMaps(User);
8056 // If we just RAUW'd the root, take note.
8057 if (FromN == getRoot())
8058 setRoot(To);
8061 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8062 /// This can cause recursive merging of nodes in the DAG.
8064 /// This version assumes that for each value of From, there is a
8065 /// corresponding value in To in the same position with the same type.
8067 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
8068 #ifndef NDEBUG
8069 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8070 assert((!From->hasAnyUseOfValue(i) ||
8071 From->getValueType(i) == To->getValueType(i)) &&
8072 "Cannot use this version of ReplaceAllUsesWith!");
8073 #endif
8075 // Handle the trivial case.
8076 if (From == To)
8077 return;
8079 // Preserve Debug Info. Only do this if there's a use.
8080 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8081 if (From->hasAnyUseOfValue(i)) {
8082 assert((i < To->getNumValues()) && "Invalid To location");
8083 transferDbgValues(SDValue(From, i), SDValue(To, i));
8086 // Iterate over just the existing users of From. See the comments in
8087 // the ReplaceAllUsesWith above.
8088 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8089 RAUWUpdateListener Listener(*this, UI, UE);
8090 while (UI != UE) {
8091 SDNode *User = *UI;
8093 // This node is about to morph, remove its old self from the CSE maps.
8094 RemoveNodeFromCSEMaps(User);
8096 // A user can appear in a use list multiple times, and when this
8097 // happens the uses are usually next to each other in the list.
8098 // To help reduce the number of CSE recomputations, process all
8099 // the uses of this user that we can find this way.
8100 do {
8101 SDUse &Use = UI.getUse();
8102 ++UI;
8103 Use.setNode(To);
8104 if (To->isDivergent() != From->isDivergent())
8105 updateDivergence(User);
8106 } while (UI != UE && *UI == User);
8108 // Now that we have modified User, add it back to the CSE maps. If it
8109 // already exists there, recursively merge the results together.
8110 AddModifiedNodeToCSEMaps(User);
8113 // If we just RAUW'd the root, take note.
8114 if (From == getRoot().getNode())
8115 setRoot(SDValue(To, getRoot().getResNo()));
8118 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8119 /// This can cause recursive merging of nodes in the DAG.
8121 /// This version can replace From with any result values. To must match the
8122 /// number and types of values returned by From.
8123 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
8124 if (From->getNumValues() == 1) // Handle the simple case efficiently.
8125 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
8127 // Preserve Debug Info.
8128 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8129 transferDbgValues(SDValue(From, i), To[i]);
8131 // Iterate over just the existing users of From. See the comments in
8132 // the ReplaceAllUsesWith above.
8133 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8134 RAUWUpdateListener Listener(*this, UI, UE);
8135 while (UI != UE) {
8136 SDNode *User = *UI;
8138 // This node is about to morph, remove its old self from the CSE maps.
8139 RemoveNodeFromCSEMaps(User);
8141 // A user can appear in a use list multiple times, and when this happens the
8142 // uses are usually next to each other in the list. To help reduce the
8143 // number of CSE and divergence recomputations, process all the uses of this
8144 // user that we can find this way.
8145 bool To_IsDivergent = false;
8146 do {
8147 SDUse &Use = UI.getUse();
8148 const SDValue &ToOp = To[Use.getResNo()];
8149 ++UI;
8150 Use.set(ToOp);
8151 To_IsDivergent |= ToOp->isDivergent();
8152 } while (UI != UE && *UI == User);
8154 if (To_IsDivergent != From->isDivergent())
8155 updateDivergence(User);
8157 // Now that we have modified User, add it back to the CSE maps. If it
8158 // already exists there, recursively merge the results together.
8159 AddModifiedNodeToCSEMaps(User);
8162 // If we just RAUW'd the root, take note.
8163 if (From == getRoot().getNode())
8164 setRoot(SDValue(To[getRoot().getResNo()]));
8167 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
8168 /// uses of other values produced by From.getNode() alone. The Deleted
8169 /// vector is handled the same way as for ReplaceAllUsesWith.
8170 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
8171 // Handle the really simple, really trivial case efficiently.
8172 if (From == To) return;
8174 // Handle the simple, trivial, case efficiently.
8175 if (From.getNode()->getNumValues() == 1) {
8176 ReplaceAllUsesWith(From, To);
8177 return;
8180 // Preserve Debug Info.
8181 transferDbgValues(From, To);
8183 // Iterate over just the existing users of From. See the comments in
8184 // the ReplaceAllUsesWith above.
8185 SDNode::use_iterator UI = From.getNode()->use_begin(),
8186 UE = From.getNode()->use_end();
8187 RAUWUpdateListener Listener(*this, UI, UE);
8188 while (UI != UE) {
8189 SDNode *User = *UI;
8190 bool UserRemovedFromCSEMaps = false;
8192 // A user can appear in a use list multiple times, and when this
8193 // happens the uses are usually next to each other in the list.
8194 // To help reduce the number of CSE recomputations, process all
8195 // the uses of this user that we can find this way.
8196 do {
8197 SDUse &Use = UI.getUse();
8199 // Skip uses of different values from the same node.
8200 if (Use.getResNo() != From.getResNo()) {
8201 ++UI;
8202 continue;
8205 // If this node hasn't been modified yet, it's still in the CSE maps,
8206 // so remove its old self from the CSE maps.
8207 if (!UserRemovedFromCSEMaps) {
8208 RemoveNodeFromCSEMaps(User);
8209 UserRemovedFromCSEMaps = true;
8212 ++UI;
8213 Use.set(To);
8214 if (To->isDivergent() != From->isDivergent())
8215 updateDivergence(User);
8216 } while (UI != UE && *UI == User);
8217 // We are iterating over all uses of the From node, so if a use
8218 // doesn't use the specific value, no changes are made.
8219 if (!UserRemovedFromCSEMaps)
8220 continue;
8222 // Now that we have modified User, add it back to the CSE maps. If it
8223 // already exists there, recursively merge the results together.
8224 AddModifiedNodeToCSEMaps(User);
8227 // If we just RAUW'd the root, take note.
8228 if (From == getRoot())
8229 setRoot(To);
8232 namespace {
8234 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
8235 /// to record information about a use.
8236 struct UseMemo {
8237 SDNode *User;
8238 unsigned Index;
8239 SDUse *Use;
8242 /// operator< - Sort Memos by User.
8243 bool operator<(const UseMemo &L, const UseMemo &R) {
8244 return (intptr_t)L.User < (intptr_t)R.User;
8247 } // end anonymous namespace
8249 void SelectionDAG::updateDivergence(SDNode * N)
8251 if (TLI->isSDNodeAlwaysUniform(N))
8252 return;
8253 bool IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
8254 for (auto &Op : N->ops()) {
8255 if (Op.Val.getValueType() != MVT::Other)
8256 IsDivergent |= Op.getNode()->isDivergent();
8258 if (N->SDNodeBits.IsDivergent != IsDivergent) {
8259 N->SDNodeBits.IsDivergent = IsDivergent;
8260 for (auto U : N->uses()) {
8261 updateDivergence(U);
8267 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode*>& Order) {
8268 DenseMap<SDNode *, unsigned> Degree;
8269 Order.reserve(AllNodes.size());
8270 for (auto & N : allnodes()) {
8271 unsigned NOps = N.getNumOperands();
8272 Degree[&N] = NOps;
8273 if (0 == NOps)
8274 Order.push_back(&N);
8276 for (std::vector<SDNode *>::iterator I = Order.begin();
8277 I!=Order.end();++I) {
8278 SDNode * N = *I;
8279 for (auto U : N->uses()) {
8280 unsigned &UnsortedOps = Degree[U];
8281 if (0 == --UnsortedOps)
8282 Order.push_back(U);
8287 #ifndef NDEBUG
8288 void SelectionDAG::VerifyDAGDiverence()
8290 std::vector<SDNode*> TopoOrder;
8291 CreateTopologicalOrder(TopoOrder);
8292 const TargetLowering &TLI = getTargetLoweringInfo();
8293 DenseMap<const SDNode *, bool> DivergenceMap;
8294 for (auto &N : allnodes()) {
8295 DivergenceMap[&N] = false;
8297 for (auto N : TopoOrder) {
8298 bool IsDivergent = DivergenceMap[N];
8299 bool IsSDNodeDivergent = TLI.isSDNodeSourceOfDivergence(N, FLI, DA);
8300 for (auto &Op : N->ops()) {
8301 if (Op.Val.getValueType() != MVT::Other)
8302 IsSDNodeDivergent |= DivergenceMap[Op.getNode()];
8304 if (!IsDivergent && IsSDNodeDivergent && !TLI.isSDNodeAlwaysUniform(N)) {
8305 DivergenceMap[N] = true;
8308 for (auto &N : allnodes()) {
8309 (void)N;
8310 assert(DivergenceMap[&N] == N.isDivergent() &&
8311 "Divergence bit inconsistency detected\n");
8314 #endif
8317 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
8318 /// uses of other values produced by From.getNode() alone. The same value
8319 /// may appear in both the From and To list. The Deleted vector is
8320 /// handled the same way as for ReplaceAllUsesWith.
8321 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
8322 const SDValue *To,
8323 unsigned Num){
8324 // Handle the simple, trivial case efficiently.
8325 if (Num == 1)
8326 return ReplaceAllUsesOfValueWith(*From, *To);
8328 transferDbgValues(*From, *To);
8330 // Read up all the uses and make records of them. This helps
8331 // processing new uses that are introduced during the
8332 // replacement process.
8333 SmallVector<UseMemo, 4> Uses;
8334 for (unsigned i = 0; i != Num; ++i) {
8335 unsigned FromResNo = From[i].getResNo();
8336 SDNode *FromNode = From[i].getNode();
8337 for (SDNode::use_iterator UI = FromNode->use_begin(),
8338 E = FromNode->use_end(); UI != E; ++UI) {
8339 SDUse &Use = UI.getUse();
8340 if (Use.getResNo() == FromResNo) {
8341 UseMemo Memo = { *UI, i, &Use };
8342 Uses.push_back(Memo);
8347 // Sort the uses, so that all the uses from a given User are together.
8348 llvm::sort(Uses);
8350 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
8351 UseIndex != UseIndexEnd; ) {
8352 // We know that this user uses some value of From. If it is the right
8353 // value, update it.
8354 SDNode *User = Uses[UseIndex].User;
8356 // This node is about to morph, remove its old self from the CSE maps.
8357 RemoveNodeFromCSEMaps(User);
8359 // The Uses array is sorted, so all the uses for a given User
8360 // are next to each other in the list.
8361 // To help reduce the number of CSE recomputations, process all
8362 // the uses of this user that we can find this way.
8363 do {
8364 unsigned i = Uses[UseIndex].Index;
8365 SDUse &Use = *Uses[UseIndex].Use;
8366 ++UseIndex;
8368 Use.set(To[i]);
8369 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
8371 // Now that we have modified User, add it back to the CSE maps. If it
8372 // already exists there, recursively merge the results together.
8373 AddModifiedNodeToCSEMaps(User);
8377 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
8378 /// based on their topological order. It returns the maximum id and a vector
8379 /// of the SDNodes* in assigned order by reference.
8380 unsigned SelectionDAG::AssignTopologicalOrder() {
8381 unsigned DAGSize = 0;
8383 // SortedPos tracks the progress of the algorithm. Nodes before it are
8384 // sorted, nodes after it are unsorted. When the algorithm completes
8385 // it is at the end of the list.
8386 allnodes_iterator SortedPos = allnodes_begin();
8388 // Visit all the nodes. Move nodes with no operands to the front of
8389 // the list immediately. Annotate nodes that do have operands with their
8390 // operand count. Before we do this, the Node Id fields of the nodes
8391 // may contain arbitrary values. After, the Node Id fields for nodes
8392 // before SortedPos will contain the topological sort index, and the
8393 // Node Id fields for nodes At SortedPos and after will contain the
8394 // count of outstanding operands.
8395 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
8396 SDNode *N = &*I++;
8397 checkForCycles(N, this);
8398 unsigned Degree = N->getNumOperands();
8399 if (Degree == 0) {
8400 // A node with no uses, add it to the result array immediately.
8401 N->setNodeId(DAGSize++);
8402 allnodes_iterator Q(N);
8403 if (Q != SortedPos)
8404 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
8405 assert(SortedPos != AllNodes.end() && "Overran node list");
8406 ++SortedPos;
8407 } else {
8408 // Temporarily use the Node Id as scratch space for the degree count.
8409 N->setNodeId(Degree);
8413 // Visit all the nodes. As we iterate, move nodes into sorted order,
8414 // such that by the time the end is reached all nodes will be sorted.
8415 for (SDNode &Node : allnodes()) {
8416 SDNode *N = &Node;
8417 checkForCycles(N, this);
8418 // N is in sorted position, so all its uses have one less operand
8419 // that needs to be sorted.
8420 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
8421 UI != UE; ++UI) {
8422 SDNode *P = *UI;
8423 unsigned Degree = P->getNodeId();
8424 assert(Degree != 0 && "Invalid node degree");
8425 --Degree;
8426 if (Degree == 0) {
8427 // All of P's operands are sorted, so P may sorted now.
8428 P->setNodeId(DAGSize++);
8429 if (P->getIterator() != SortedPos)
8430 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
8431 assert(SortedPos != AllNodes.end() && "Overran node list");
8432 ++SortedPos;
8433 } else {
8434 // Update P's outstanding operand count.
8435 P->setNodeId(Degree);
8438 if (Node.getIterator() == SortedPos) {
8439 #ifndef NDEBUG
8440 allnodes_iterator I(N);
8441 SDNode *S = &*++I;
8442 dbgs() << "Overran sorted position:\n";
8443 S->dumprFull(this); dbgs() << "\n";
8444 dbgs() << "Checking if this is due to cycles\n";
8445 checkForCycles(this, true);
8446 #endif
8447 llvm_unreachable(nullptr);
8451 assert(SortedPos == AllNodes.end() &&
8452 "Topological sort incomplete!");
8453 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
8454 "First node in topological sort is not the entry token!");
8455 assert(AllNodes.front().getNodeId() == 0 &&
8456 "First node in topological sort has non-zero id!");
8457 assert(AllNodes.front().getNumOperands() == 0 &&
8458 "First node in topological sort has operands!");
8459 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
8460 "Last node in topologic sort has unexpected id!");
8461 assert(AllNodes.back().use_empty() &&
8462 "Last node in topologic sort has users!");
8463 assert(DAGSize == allnodes_size() && "Node count mismatch!");
8464 return DAGSize;
8467 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
8468 /// value is produced by SD.
8469 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
8470 if (SD) {
8471 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
8472 SD->setHasDebugValue(true);
8474 DbgInfo->add(DB, SD, isParameter);
8477 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) {
8478 DbgInfo->add(DB);
8481 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
8482 SDValue NewMemOp) {
8483 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
8484 // The new memory operation must have the same position as the old load in
8485 // terms of memory dependency. Create a TokenFactor for the old load and new
8486 // memory operation and update uses of the old load's output chain to use that
8487 // TokenFactor.
8488 SDValue OldChain = SDValue(OldLoad, 1);
8489 SDValue NewChain = SDValue(NewMemOp.getNode(), 1);
8490 if (!OldLoad->hasAnyUseOfValue(1))
8491 return NewChain;
8493 SDValue TokenFactor =
8494 getNode(ISD::TokenFactor, SDLoc(OldLoad), MVT::Other, OldChain, NewChain);
8495 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
8496 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewChain);
8497 return TokenFactor;
8500 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
8501 Function **OutFunction) {
8502 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
8504 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8505 auto *Module = MF->getFunction().getParent();
8506 auto *Function = Module->getFunction(Symbol);
8508 if (OutFunction != nullptr)
8509 *OutFunction = Function;
8511 if (Function != nullptr) {
8512 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
8513 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
8516 std::string ErrorStr;
8517 raw_string_ostream ErrorFormatter(ErrorStr);
8519 ErrorFormatter << "Undefined external symbol ";
8520 ErrorFormatter << '"' << Symbol << '"';
8521 ErrorFormatter.flush();
8523 report_fatal_error(ErrorStr);
8526 //===----------------------------------------------------------------------===//
8527 // SDNode Class
8528 //===----------------------------------------------------------------------===//
8530 bool llvm::isNullConstant(SDValue V) {
8531 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
8532 return Const != nullptr && Const->isNullValue();
8535 bool llvm::isNullFPConstant(SDValue V) {
8536 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
8537 return Const != nullptr && Const->isZero() && !Const->isNegative();
8540 bool llvm::isAllOnesConstant(SDValue V) {
8541 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
8542 return Const != nullptr && Const->isAllOnesValue();
8545 bool llvm::isOneConstant(SDValue V) {
8546 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
8547 return Const != nullptr && Const->isOne();
8550 SDValue llvm::peekThroughBitcasts(SDValue V) {
8551 while (V.getOpcode() == ISD::BITCAST)
8552 V = V.getOperand(0);
8553 return V;
8556 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
8557 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
8558 V = V.getOperand(0);
8559 return V;
8562 bool llvm::isBitwiseNot(SDValue V) {
8563 if (V.getOpcode() != ISD::XOR)
8564 return false;
8565 ConstantSDNode *C = isConstOrConstSplat(peekThroughBitcasts(V.getOperand(1)));
8566 return C && C->isAllOnesValue();
8569 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs) {
8570 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
8571 return CN;
8573 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
8574 BitVector UndefElements;
8575 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
8577 // BuildVectors can truncate their operands. Ignore that case here.
8578 if (CN && (UndefElements.none() || AllowUndefs) &&
8579 CN->getValueType(0) == N.getValueType().getScalarType())
8580 return CN;
8583 return nullptr;
8586 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
8587 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
8588 return CN;
8590 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
8591 BitVector UndefElements;
8592 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
8593 if (CN && (UndefElements.none() || AllowUndefs))
8594 return CN;
8597 return nullptr;
8600 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
8601 // TODO: may want to use peekThroughBitcast() here.
8602 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
8603 return C && C->isNullValue();
8606 bool llvm::isOneOrOneSplat(SDValue N) {
8607 // TODO: may want to use peekThroughBitcast() here.
8608 unsigned BitWidth = N.getScalarValueSizeInBits();
8609 ConstantSDNode *C = isConstOrConstSplat(N);
8610 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
8613 bool llvm::isAllOnesOrAllOnesSplat(SDValue N) {
8614 N = peekThroughBitcasts(N);
8615 unsigned BitWidth = N.getScalarValueSizeInBits();
8616 ConstantSDNode *C = isConstOrConstSplat(N);
8617 return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth;
8620 HandleSDNode::~HandleSDNode() {
8621 DropOperands();
8624 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
8625 const DebugLoc &DL,
8626 const GlobalValue *GA, EVT VT,
8627 int64_t o, unsigned char TF)
8628 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
8629 TheGlobal = GA;
8632 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
8633 EVT VT, unsigned SrcAS,
8634 unsigned DestAS)
8635 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
8636 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
8638 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
8639 SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
8640 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
8641 MemSDNodeBits.IsVolatile = MMO->isVolatile();
8642 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
8643 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
8644 MemSDNodeBits.IsInvariant = MMO->isInvariant();
8646 // We check here that the size of the memory operand fits within the size of
8647 // the MMO. This is because the MMO might indicate only a possible address
8648 // range instead of specifying the affected memory addresses precisely.
8649 assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
8652 /// Profile - Gather unique data for the node.
8654 void SDNode::Profile(FoldingSetNodeID &ID) const {
8655 AddNodeIDNode(ID, this);
8658 namespace {
8660 struct EVTArray {
8661 std::vector<EVT> VTs;
8663 EVTArray() {
8664 VTs.reserve(MVT::LAST_VALUETYPE);
8665 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
8666 VTs.push_back(MVT((MVT::SimpleValueType)i));
8670 } // end anonymous namespace
8672 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
8673 static ManagedStatic<EVTArray> SimpleVTArray;
8674 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
8676 /// getValueTypeList - Return a pointer to the specified value type.
8678 const EVT *SDNode::getValueTypeList(EVT VT) {
8679 if (VT.isExtended()) {
8680 sys::SmartScopedLock<true> Lock(*VTMutex);
8681 return &(*EVTs->insert(VT).first);
8682 } else {
8683 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
8684 "Value type out of range!");
8685 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
8689 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
8690 /// indicated value. This method ignores uses of other values defined by this
8691 /// operation.
8692 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
8693 assert(Value < getNumValues() && "Bad value!");
8695 // TODO: Only iterate over uses of a given value of the node
8696 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
8697 if (UI.getUse().getResNo() == Value) {
8698 if (NUses == 0)
8699 return false;
8700 --NUses;
8704 // Found exactly the right number of uses?
8705 return NUses == 0;
8708 /// hasAnyUseOfValue - Return true if there are any use of the indicated
8709 /// value. This method ignores uses of other values defined by this operation.
8710 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
8711 assert(Value < getNumValues() && "Bad value!");
8713 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
8714 if (UI.getUse().getResNo() == Value)
8715 return true;
8717 return false;
8720 /// isOnlyUserOf - Return true if this node is the only use of N.
8721 bool SDNode::isOnlyUserOf(const SDNode *N) const {
8722 bool Seen = false;
8723 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
8724 SDNode *User = *I;
8725 if (User == this)
8726 Seen = true;
8727 else
8728 return false;
8731 return Seen;
8734 /// Return true if the only users of N are contained in Nodes.
8735 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
8736 bool Seen = false;
8737 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
8738 SDNode *User = *I;
8739 if (llvm::any_of(Nodes,
8740 [&User](const SDNode *Node) { return User == Node; }))
8741 Seen = true;
8742 else
8743 return false;
8746 return Seen;
8749 /// isOperand - Return true if this node is an operand of N.
8750 bool SDValue::isOperandOf(const SDNode *N) const {
8751 for (const SDValue &Op : N->op_values())
8752 if (*this == Op)
8753 return true;
8754 return false;
8757 bool SDNode::isOperandOf(const SDNode *N) const {
8758 for (const SDValue &Op : N->op_values())
8759 if (this == Op.getNode())
8760 return true;
8761 return false;
8764 /// reachesChainWithoutSideEffects - Return true if this operand (which must
8765 /// be a chain) reaches the specified operand without crossing any
8766 /// side-effecting instructions on any chain path. In practice, this looks
8767 /// through token factors and non-volatile loads. In order to remain efficient,
8768 /// this only looks a couple of nodes in, it does not do an exhaustive search.
8770 /// Note that we only need to examine chains when we're searching for
8771 /// side-effects; SelectionDAG requires that all side-effects are represented
8772 /// by chains, even if another operand would force a specific ordering. This
8773 /// constraint is necessary to allow transformations like splitting loads.
8774 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
8775 unsigned Depth) const {
8776 if (*this == Dest) return true;
8778 // Don't search too deeply, we just want to be able to see through
8779 // TokenFactor's etc.
8780 if (Depth == 0) return false;
8782 // If this is a token factor, all inputs to the TF happen in parallel.
8783 if (getOpcode() == ISD::TokenFactor) {
8784 // First, try a shallow search.
8785 if (is_contained((*this)->ops(), Dest)) {
8786 // We found the chain we want as an operand of this TokenFactor.
8787 // Essentially, we reach the chain without side-effects if we could
8788 // serialize the TokenFactor into a simple chain of operations with
8789 // Dest as the last operation. This is automatically true if the
8790 // chain has one use: there are no other ordering constraints.
8791 // If the chain has more than one use, we give up: some other
8792 // use of Dest might force a side-effect between Dest and the current
8793 // node.
8794 if (Dest.hasOneUse())
8795 return true;
8797 // Next, try a deep search: check whether every operand of the TokenFactor
8798 // reaches Dest.
8799 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
8800 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
8804 // Loads don't have side effects, look through them.
8805 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
8806 if (!Ld->isVolatile())
8807 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
8809 return false;
8812 bool SDNode::hasPredecessor(const SDNode *N) const {
8813 SmallPtrSet<const SDNode *, 32> Visited;
8814 SmallVector<const SDNode *, 16> Worklist;
8815 Worklist.push_back(this);
8816 return hasPredecessorHelper(N, Visited, Worklist);
8819 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
8820 this->Flags.intersectWith(Flags);
8823 SDValue
8824 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
8825 ArrayRef<ISD::NodeType> CandidateBinOps) {
8826 // The pattern must end in an extract from index 0.
8827 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8828 !isNullConstant(Extract->getOperand(1)))
8829 return SDValue();
8831 SDValue Op = Extract->getOperand(0);
8832 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
8834 // Match against one of the candidate binary ops.
8835 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
8836 return Op.getOpcode() == unsigned(BinOp);
8838 return SDValue();
8840 // At each stage, we're looking for something that looks like:
8841 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
8842 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
8843 // i32 undef, i32 undef, i32 undef, i32 undef>
8844 // %a = binop <8 x i32> %op, %s
8845 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
8846 // we expect something like:
8847 // <4,5,6,7,u,u,u,u>
8848 // <2,3,u,u,u,u,u,u>
8849 // <1,u,u,u,u,u,u,u>
8850 unsigned CandidateBinOp = Op.getOpcode();
8851 for (unsigned i = 0; i < Stages; ++i) {
8852 if (Op.getOpcode() != CandidateBinOp)
8853 return SDValue();
8855 SDValue Op0 = Op.getOperand(0);
8856 SDValue Op1 = Op.getOperand(1);
8858 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
8859 if (Shuffle) {
8860 Op = Op1;
8861 } else {
8862 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
8863 Op = Op0;
8866 // The first operand of the shuffle should be the same as the other operand
8867 // of the binop.
8868 if (!Shuffle || Shuffle->getOperand(0) != Op)
8869 return SDValue();
8871 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
8872 for (int Index = 0, MaskEnd = 1 << i; Index < MaskEnd; ++Index)
8873 if (Shuffle->getMaskElt(Index) != MaskEnd + Index)
8874 return SDValue();
8877 BinOp = (ISD::NodeType)CandidateBinOp;
8878 return Op;
8881 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
8882 assert(N->getNumValues() == 1 &&
8883 "Can't unroll a vector with multiple results!");
8885 EVT VT = N->getValueType(0);
8886 unsigned NE = VT.getVectorNumElements();
8887 EVT EltVT = VT.getVectorElementType();
8888 SDLoc dl(N);
8890 SmallVector<SDValue, 8> Scalars;
8891 SmallVector<SDValue, 4> Operands(N->getNumOperands());
8893 // If ResNE is 0, fully unroll the vector op.
8894 if (ResNE == 0)
8895 ResNE = NE;
8896 else if (NE > ResNE)
8897 NE = ResNE;
8899 unsigned i;
8900 for (i= 0; i != NE; ++i) {
8901 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
8902 SDValue Operand = N->getOperand(j);
8903 EVT OperandVT = Operand.getValueType();
8904 if (OperandVT.isVector()) {
8905 // A vector operand; extract a single element.
8906 EVT OperandEltVT = OperandVT.getVectorElementType();
8907 Operands[j] =
8908 getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand,
8909 getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout())));
8910 } else {
8911 // A scalar operand; just use it as is.
8912 Operands[j] = Operand;
8916 switch (N->getOpcode()) {
8917 default: {
8918 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
8919 N->getFlags()));
8920 break;
8922 case ISD::VSELECT:
8923 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
8924 break;
8925 case ISD::SHL:
8926 case ISD::SRA:
8927 case ISD::SRL:
8928 case ISD::ROTL:
8929 case ISD::ROTR:
8930 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
8931 getShiftAmountOperand(Operands[0].getValueType(),
8932 Operands[1])));
8933 break;
8934 case ISD::SIGN_EXTEND_INREG:
8935 case ISD::FP_ROUND_INREG: {
8936 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
8937 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
8938 Operands[0],
8939 getValueType(ExtVT)));
8944 for (; i < ResNE; ++i)
8945 Scalars.push_back(getUNDEF(EltVT));
8947 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
8948 return getBuildVector(VecVT, dl, Scalars);
8951 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
8952 LoadSDNode *Base,
8953 unsigned Bytes,
8954 int Dist) const {
8955 if (LD->isVolatile() || Base->isVolatile())
8956 return false;
8957 if (LD->isIndexed() || Base->isIndexed())
8958 return false;
8959 if (LD->getChain() != Base->getChain())
8960 return false;
8961 EVT VT = LD->getValueType(0);
8962 if (VT.getSizeInBits() / 8 != Bytes)
8963 return false;
8965 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
8966 auto LocDecomp = BaseIndexOffset::match(LD, *this);
8968 int64_t Offset = 0;
8969 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
8970 return (Dist * Bytes == Offset);
8971 return false;
8974 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
8975 /// it cannot be inferred.
8976 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
8977 // If this is a GlobalAddress + cst, return the alignment.
8978 const GlobalValue *GV;
8979 int64_t GVOffset = 0;
8980 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
8981 unsigned IdxWidth = getDataLayout().getIndexTypeSizeInBits(GV->getType());
8982 KnownBits Known(IdxWidth);
8983 llvm::computeKnownBits(GV, Known, getDataLayout());
8984 unsigned AlignBits = Known.countMinTrailingZeros();
8985 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
8986 if (Align)
8987 return MinAlign(Align, GVOffset);
8990 // If this is a direct reference to a stack slot, use information about the
8991 // stack slot's alignment.
8992 int FrameIdx = 1 << 31;
8993 int64_t FrameOffset = 0;
8994 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
8995 FrameIdx = FI->getIndex();
8996 } else if (isBaseWithConstantOffset(Ptr) &&
8997 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
8998 // Handle FI+Cst
8999 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
9000 FrameOffset = Ptr.getConstantOperandVal(1);
9003 if (FrameIdx != (1 << 31)) {
9004 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
9005 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
9006 FrameOffset);
9007 return FIInfoAlign;
9010 return 0;
9013 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
9014 /// which is split (or expanded) into two not necessarily identical pieces.
9015 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
9016 // Currently all types are split in half.
9017 EVT LoVT, HiVT;
9018 if (!VT.isVector())
9019 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
9020 else
9021 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
9023 return std::make_pair(LoVT, HiVT);
9026 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
9027 /// low/high part.
9028 std::pair<SDValue, SDValue>
9029 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
9030 const EVT &HiVT) {
9031 assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
9032 N.getValueType().getVectorNumElements() &&
9033 "More vector elements requested than available!");
9034 SDValue Lo, Hi;
9035 Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
9036 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
9037 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
9038 getConstant(LoVT.getVectorNumElements(), DL,
9039 TLI->getVectorIdxTy(getDataLayout())));
9040 return std::make_pair(Lo, Hi);
9043 void SelectionDAG::ExtractVectorElements(SDValue Op,
9044 SmallVectorImpl<SDValue> &Args,
9045 unsigned Start, unsigned Count) {
9046 EVT VT = Op.getValueType();
9047 if (Count == 0)
9048 Count = VT.getVectorNumElements();
9050 EVT EltVT = VT.getVectorElementType();
9051 EVT IdxTy = TLI->getVectorIdxTy(getDataLayout());
9052 SDLoc SL(Op);
9053 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
9054 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9055 Op, getConstant(i, SL, IdxTy)));
9059 // getAddressSpace - Return the address space this GlobalAddress belongs to.
9060 unsigned GlobalAddressSDNode::getAddressSpace() const {
9061 return getGlobal()->getType()->getAddressSpace();
9064 Type *ConstantPoolSDNode::getType() const {
9065 if (isMachineConstantPoolEntry())
9066 return Val.MachineCPVal->getType();
9067 return Val.ConstVal->getType();
9070 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
9071 unsigned &SplatBitSize,
9072 bool &HasAnyUndefs,
9073 unsigned MinSplatBits,
9074 bool IsBigEndian) const {
9075 EVT VT = getValueType(0);
9076 assert(VT.isVector() && "Expected a vector type");
9077 unsigned VecWidth = VT.getSizeInBits();
9078 if (MinSplatBits > VecWidth)
9079 return false;
9081 // FIXME: The widths are based on this node's type, but build vectors can
9082 // truncate their operands.
9083 SplatValue = APInt(VecWidth, 0);
9084 SplatUndef = APInt(VecWidth, 0);
9086 // Get the bits. Bits with undefined values (when the corresponding element
9087 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
9088 // in SplatValue. If any of the values are not constant, give up and return
9089 // false.
9090 unsigned int NumOps = getNumOperands();
9091 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
9092 unsigned EltWidth = VT.getScalarSizeInBits();
9094 for (unsigned j = 0; j < NumOps; ++j) {
9095 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
9096 SDValue OpVal = getOperand(i);
9097 unsigned BitPos = j * EltWidth;
9099 if (OpVal.isUndef())
9100 SplatUndef.setBits(BitPos, BitPos + EltWidth);
9101 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
9102 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
9103 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
9104 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
9105 else
9106 return false;
9109 // The build_vector is all constants or undefs. Find the smallest element
9110 // size that splats the vector.
9111 HasAnyUndefs = (SplatUndef != 0);
9113 // FIXME: This does not work for vectors with elements less than 8 bits.
9114 while (VecWidth > 8) {
9115 unsigned HalfSize = VecWidth / 2;
9116 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
9117 APInt LowValue = SplatValue.trunc(HalfSize);
9118 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
9119 APInt LowUndef = SplatUndef.trunc(HalfSize);
9121 // If the two halves do not match (ignoring undef bits), stop here.
9122 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
9123 MinSplatBits > HalfSize)
9124 break;
9126 SplatValue = HighValue | LowValue;
9127 SplatUndef = HighUndef & LowUndef;
9129 VecWidth = HalfSize;
9132 SplatBitSize = VecWidth;
9133 return true;
9136 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
9137 if (UndefElements) {
9138 UndefElements->clear();
9139 UndefElements->resize(getNumOperands());
9141 SDValue Splatted;
9142 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
9143 SDValue Op = getOperand(i);
9144 if (Op.isUndef()) {
9145 if (UndefElements)
9146 (*UndefElements)[i] = true;
9147 } else if (!Splatted) {
9148 Splatted = Op;
9149 } else if (Splatted != Op) {
9150 return SDValue();
9154 if (!Splatted) {
9155 assert(getOperand(0).isUndef() &&
9156 "Can only have a splat without a constant for all undefs.");
9157 return getOperand(0);
9160 return Splatted;
9163 ConstantSDNode *
9164 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
9165 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
9168 ConstantFPSDNode *
9169 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
9170 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
9173 int32_t
9174 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
9175 uint32_t BitWidth) const {
9176 if (ConstantFPSDNode *CN =
9177 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
9178 bool IsExact;
9179 APSInt IntVal(BitWidth);
9180 const APFloat &APF = CN->getValueAPF();
9181 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
9182 APFloat::opOK ||
9183 !IsExact)
9184 return -1;
9186 return IntVal.exactLogBase2();
9188 return -1;
9191 bool BuildVectorSDNode::isConstant() const {
9192 for (const SDValue &Op : op_values()) {
9193 unsigned Opc = Op.getOpcode();
9194 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
9195 return false;
9197 return true;
9200 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
9201 // Find the first non-undef value in the shuffle mask.
9202 unsigned i, e;
9203 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
9204 /* search */;
9206 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
9208 // Make sure all remaining elements are either undef or the same as the first
9209 // non-undef value.
9210 for (int Idx = Mask[i]; i != e; ++i)
9211 if (Mask[i] >= 0 && Mask[i] != Idx)
9212 return false;
9213 return true;
9216 // Returns the SDNode if it is a constant integer BuildVector
9217 // or constant integer.
9218 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
9219 if (isa<ConstantSDNode>(N))
9220 return N.getNode();
9221 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
9222 return N.getNode();
9223 // Treat a GlobalAddress supporting constant offset folding as a
9224 // constant integer.
9225 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
9226 if (GA->getOpcode() == ISD::GlobalAddress &&
9227 TLI->isOffsetFoldingLegal(GA))
9228 return GA;
9229 return nullptr;
9232 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) {
9233 if (isa<ConstantFPSDNode>(N))
9234 return N.getNode();
9236 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
9237 return N.getNode();
9239 return nullptr;
9242 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
9243 assert(!Node->OperandList && "Node already has operands");
9244 assert(SDNode::getMaxNumOperands() >= Vals.size() &&
9245 "too many operands to fit into SDNode");
9246 SDUse *Ops = OperandRecycler.allocate(
9247 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
9249 bool IsDivergent = false;
9250 for (unsigned I = 0; I != Vals.size(); ++I) {
9251 Ops[I].setUser(Node);
9252 Ops[I].setInitial(Vals[I]);
9253 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
9254 IsDivergent = IsDivergent || Ops[I].getNode()->isDivergent();
9256 Node->NumOperands = Vals.size();
9257 Node->OperandList = Ops;
9258 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
9259 if (!TLI->isSDNodeAlwaysUniform(Node))
9260 Node->SDNodeBits.IsDivergent = IsDivergent;
9261 checkForCycles(Node);
9264 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
9265 SmallVectorImpl<SDValue> &Vals) {
9266 size_t Limit = SDNode::getMaxNumOperands();
9267 while (Vals.size() > Limit) {
9268 unsigned SliceIdx = Vals.size() - Limit;
9269 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
9270 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
9271 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
9272 Vals.emplace_back(NewTF);
9274 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
9277 #ifndef NDEBUG
9278 static void checkForCyclesHelper(const SDNode *N,
9279 SmallPtrSetImpl<const SDNode*> &Visited,
9280 SmallPtrSetImpl<const SDNode*> &Checked,
9281 const llvm::SelectionDAG *DAG) {
9282 // If this node has already been checked, don't check it again.
9283 if (Checked.count(N))
9284 return;
9286 // If a node has already been visited on this depth-first walk, reject it as
9287 // a cycle.
9288 if (!Visited.insert(N).second) {
9289 errs() << "Detected cycle in SelectionDAG\n";
9290 dbgs() << "Offending node:\n";
9291 N->dumprFull(DAG); dbgs() << "\n";
9292 abort();
9295 for (const SDValue &Op : N->op_values())
9296 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
9298 Checked.insert(N);
9299 Visited.erase(N);
9301 #endif
9303 void llvm::checkForCycles(const llvm::SDNode *N,
9304 const llvm::SelectionDAG *DAG,
9305 bool force) {
9306 #ifndef NDEBUG
9307 bool check = force;
9308 #ifdef EXPENSIVE_CHECKS
9309 check = true;
9310 #endif // EXPENSIVE_CHECKS
9311 if (check) {
9312 assert(N && "Checking nonexistent SDNode");
9313 SmallPtrSet<const SDNode*, 32> visited;
9314 SmallPtrSet<const SDNode*, 32> checked;
9315 checkForCyclesHelper(N, visited, checked, DAG);
9317 #endif // !NDEBUG
9320 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
9321 checkForCycles(DAG->getRoot().getNode(), DAG, force);