[x86] fix assert with horizontal math + broadcast of vector (PR43402)
[llvm-core.git] / lib / CodeGen / SelectionDAG / SelectionDAG.cpp
blob1dcac7a7e3be2daba1fd9ca2afd439d4d0b02b02
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*) {}
88 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
90 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
92 #define DEBUG_TYPE "selectiondag"
94 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
95 cl::Hidden, cl::init(true),
96 cl::desc("Gang up loads and stores generated by inlining of memcpy"));
98 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
99 cl::desc("Number limit for gluing ld/st of memcpy."),
100 cl::Hidden, cl::init(0));
102 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
103 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
106 //===----------------------------------------------------------------------===//
107 // ConstantFPSDNode Class
108 //===----------------------------------------------------------------------===//
110 /// isExactlyValue - We don't rely on operator== working on double values, as
111 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
112 /// As such, this method can be used to do an exact bit-for-bit comparison of
113 /// two floating point values.
114 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
115 return getValueAPF().bitwiseIsEqual(V);
118 bool ConstantFPSDNode::isValueValidForType(EVT VT,
119 const APFloat& Val) {
120 assert(VT.isFloatingPoint() && "Can only convert between FP types");
122 // convert modifies in place, so make a copy.
123 APFloat Val2 = APFloat(Val);
124 bool losesInfo;
125 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
126 APFloat::rmNearestTiesToEven,
127 &losesInfo);
128 return !losesInfo;
131 //===----------------------------------------------------------------------===//
132 // ISD Namespace
133 //===----------------------------------------------------------------------===//
135 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
136 auto *BV = dyn_cast<BuildVectorSDNode>(N);
137 if (!BV)
138 return false;
140 APInt SplatUndef;
141 unsigned SplatBitSize;
142 bool HasUndefs;
143 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
144 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
145 EltSize) &&
146 EltSize == SplatBitSize;
149 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
150 // specializations of the more general isConstantSplatVector()?
152 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
153 // Look through a bit convert.
154 while (N->getOpcode() == ISD::BITCAST)
155 N = N->getOperand(0).getNode();
157 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
159 unsigned i = 0, e = N->getNumOperands();
161 // Skip over all of the undef values.
162 while (i != e && N->getOperand(i).isUndef())
163 ++i;
165 // Do not accept an all-undef vector.
166 if (i == e) return false;
168 // Do not accept build_vectors that aren't all constants or which have non-~0
169 // elements. We have to be a bit careful here, as the type of the constant
170 // may not be the same as the type of the vector elements due to type
171 // legalization (the elements are promoted to a legal type for the target and
172 // a vector of a type may be legal when the base element type is not).
173 // We only want to check enough bits to cover the vector elements, because
174 // we care if the resultant vector is all ones, not whether the individual
175 // constants are.
176 SDValue NotZero = N->getOperand(i);
177 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
178 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
179 if (CN->getAPIntValue().countTrailingOnes() < EltSize)
180 return false;
181 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
182 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
183 return false;
184 } else
185 return false;
187 // Okay, we have at least one ~0 value, check to see if the rest match or are
188 // undefs. Even with the above element type twiddling, this should be OK, as
189 // the same type legalization should have applied to all the elements.
190 for (++i; i != e; ++i)
191 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
192 return false;
193 return true;
196 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
197 // Look through a bit convert.
198 while (N->getOpcode() == ISD::BITCAST)
199 N = N->getOperand(0).getNode();
201 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
203 bool IsAllUndef = true;
204 for (const SDValue &Op : N->op_values()) {
205 if (Op.isUndef())
206 continue;
207 IsAllUndef = false;
208 // Do not accept build_vectors that aren't all constants or which have non-0
209 // elements. We have to be a bit careful here, as the type of the constant
210 // may not be the same as the type of the vector elements due to type
211 // legalization (the elements are promoted to a legal type for the target
212 // and a vector of a type may be legal when the base element type is not).
213 // We only want to check enough bits to cover the vector elements, because
214 // we care if the resultant vector is all zeros, not whether the individual
215 // constants are.
216 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
217 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
218 if (CN->getAPIntValue().countTrailingZeros() < EltSize)
219 return false;
220 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
221 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
222 return false;
223 } else
224 return false;
227 // Do not accept an all-undef vector.
228 if (IsAllUndef)
229 return false;
230 return true;
233 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
234 if (N->getOpcode() != ISD::BUILD_VECTOR)
235 return false;
237 for (const SDValue &Op : N->op_values()) {
238 if (Op.isUndef())
239 continue;
240 if (!isa<ConstantSDNode>(Op))
241 return false;
243 return true;
246 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
247 if (N->getOpcode() != ISD::BUILD_VECTOR)
248 return false;
250 for (const SDValue &Op : N->op_values()) {
251 if (Op.isUndef())
252 continue;
253 if (!isa<ConstantFPSDNode>(Op))
254 return false;
256 return true;
259 bool ISD::allOperandsUndef(const SDNode *N) {
260 // Return false if the node has no operands.
261 // This is "logically inconsistent" with the definition of "all" but
262 // is probably the desired behavior.
263 if (N->getNumOperands() == 0)
264 return false;
265 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
268 bool ISD::matchUnaryPredicate(SDValue Op,
269 std::function<bool(ConstantSDNode *)> Match,
270 bool AllowUndefs) {
271 // FIXME: Add support for scalar UNDEF cases?
272 if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
273 return Match(Cst);
275 // FIXME: Add support for vector UNDEF cases?
276 if (ISD::BUILD_VECTOR != Op.getOpcode())
277 return false;
279 EVT SVT = Op.getValueType().getScalarType();
280 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
281 if (AllowUndefs && Op.getOperand(i).isUndef()) {
282 if (!Match(nullptr))
283 return false;
284 continue;
287 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
288 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
289 return false;
291 return true;
294 bool ISD::matchBinaryPredicate(
295 SDValue LHS, SDValue RHS,
296 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
297 bool AllowUndefs, bool AllowTypeMismatch) {
298 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
299 return false;
301 // TODO: Add support for scalar UNDEF cases?
302 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
303 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
304 return Match(LHSCst, RHSCst);
306 // TODO: Add support for vector UNDEF cases?
307 if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
308 ISD::BUILD_VECTOR != RHS.getOpcode())
309 return false;
311 EVT SVT = LHS.getValueType().getScalarType();
312 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
313 SDValue LHSOp = LHS.getOperand(i);
314 SDValue RHSOp = RHS.getOperand(i);
315 bool LHSUndef = AllowUndefs && LHSOp.isUndef();
316 bool RHSUndef = AllowUndefs && RHSOp.isUndef();
317 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
318 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
319 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
320 return false;
321 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
322 LHSOp.getValueType() != RHSOp.getValueType()))
323 return false;
324 if (!Match(LHSCst, RHSCst))
325 return false;
327 return true;
330 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
331 switch (ExtType) {
332 case ISD::EXTLOAD:
333 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
334 case ISD::SEXTLOAD:
335 return ISD::SIGN_EXTEND;
336 case ISD::ZEXTLOAD:
337 return ISD::ZERO_EXTEND;
338 default:
339 break;
342 llvm_unreachable("Invalid LoadExtType");
345 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
346 // To perform this operation, we just need to swap the L and G bits of the
347 // operation.
348 unsigned OldL = (Operation >> 2) & 1;
349 unsigned OldG = (Operation >> 1) & 1;
350 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
351 (OldL << 1) | // New G bit
352 (OldG << 2)); // New L bit.
355 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
356 unsigned Operation = Op;
357 if (isInteger)
358 Operation ^= 7; // Flip L, G, E bits, but not U.
359 else
360 Operation ^= 15; // Flip all of the condition bits.
362 if (Operation > ISD::SETTRUE2)
363 Operation &= ~8; // Don't let N and U bits get set.
365 return ISD::CondCode(Operation);
368 /// For an integer comparison, return 1 if the comparison is a signed operation
369 /// and 2 if the result is an unsigned comparison. Return zero if the operation
370 /// does not depend on the sign of the input (setne and seteq).
371 static int isSignedOp(ISD::CondCode Opcode) {
372 switch (Opcode) {
373 default: llvm_unreachable("Illegal integer setcc operation!");
374 case ISD::SETEQ:
375 case ISD::SETNE: return 0;
376 case ISD::SETLT:
377 case ISD::SETLE:
378 case ISD::SETGT:
379 case ISD::SETGE: return 1;
380 case ISD::SETULT:
381 case ISD::SETULE:
382 case ISD::SETUGT:
383 case ISD::SETUGE: return 2;
387 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
388 bool IsInteger) {
389 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
390 // Cannot fold a signed integer setcc with an unsigned integer setcc.
391 return ISD::SETCC_INVALID;
393 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
395 // If the N and U bits get set, then the resultant comparison DOES suddenly
396 // care about orderedness, and it is true when ordered.
397 if (Op > ISD::SETTRUE2)
398 Op &= ~16; // Clear the U bit if the N bit is set.
400 // Canonicalize illegal integer setcc's.
401 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
402 Op = ISD::SETNE;
404 return ISD::CondCode(Op);
407 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
408 bool IsInteger) {
409 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
410 // Cannot fold a signed setcc with an unsigned setcc.
411 return ISD::SETCC_INVALID;
413 // Combine all of the condition bits.
414 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
416 // Canonicalize illegal integer setcc's.
417 if (IsInteger) {
418 switch (Result) {
419 default: break;
420 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
421 case ISD::SETOEQ: // SETEQ & SETU[LG]E
422 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
423 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
424 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
428 return Result;
431 //===----------------------------------------------------------------------===//
432 // SDNode Profile Support
433 //===----------------------------------------------------------------------===//
435 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
436 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
437 ID.AddInteger(OpC);
440 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
441 /// solely with their pointer.
442 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
443 ID.AddPointer(VTList.VTs);
446 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
447 static void AddNodeIDOperands(FoldingSetNodeID &ID,
448 ArrayRef<SDValue> Ops) {
449 for (auto& Op : Ops) {
450 ID.AddPointer(Op.getNode());
451 ID.AddInteger(Op.getResNo());
455 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
456 static void AddNodeIDOperands(FoldingSetNodeID &ID,
457 ArrayRef<SDUse> Ops) {
458 for (auto& Op : Ops) {
459 ID.AddPointer(Op.getNode());
460 ID.AddInteger(Op.getResNo());
464 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
465 SDVTList VTList, ArrayRef<SDValue> OpList) {
466 AddNodeIDOpcode(ID, OpC);
467 AddNodeIDValueTypes(ID, VTList);
468 AddNodeIDOperands(ID, OpList);
471 /// If this is an SDNode with special info, add this info to the NodeID data.
472 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
473 switch (N->getOpcode()) {
474 case ISD::TargetExternalSymbol:
475 case ISD::ExternalSymbol:
476 case ISD::MCSymbol:
477 llvm_unreachable("Should only be used on nodes with operands");
478 default: break; // Normal nodes don't need extra info.
479 case ISD::TargetConstant:
480 case ISD::Constant: {
481 const ConstantSDNode *C = cast<ConstantSDNode>(N);
482 ID.AddPointer(C->getConstantIntValue());
483 ID.AddBoolean(C->isOpaque());
484 break;
486 case ISD::TargetConstantFP:
487 case ISD::ConstantFP:
488 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
489 break;
490 case ISD::TargetGlobalAddress:
491 case ISD::GlobalAddress:
492 case ISD::TargetGlobalTLSAddress:
493 case ISD::GlobalTLSAddress: {
494 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
495 ID.AddPointer(GA->getGlobal());
496 ID.AddInteger(GA->getOffset());
497 ID.AddInteger(GA->getTargetFlags());
498 break;
500 case ISD::BasicBlock:
501 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
502 break;
503 case ISD::Register:
504 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
505 break;
506 case ISD::RegisterMask:
507 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
508 break;
509 case ISD::SRCVALUE:
510 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
511 break;
512 case ISD::FrameIndex:
513 case ISD::TargetFrameIndex:
514 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
515 break;
516 case ISD::LIFETIME_START:
517 case ISD::LIFETIME_END:
518 if (cast<LifetimeSDNode>(N)->hasOffset()) {
519 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
520 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
522 break;
523 case ISD::JumpTable:
524 case ISD::TargetJumpTable:
525 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
526 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
527 break;
528 case ISD::ConstantPool:
529 case ISD::TargetConstantPool: {
530 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
531 ID.AddInteger(CP->getAlignment());
532 ID.AddInteger(CP->getOffset());
533 if (CP->isMachineConstantPoolEntry())
534 CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
535 else
536 ID.AddPointer(CP->getConstVal());
537 ID.AddInteger(CP->getTargetFlags());
538 break;
540 case ISD::TargetIndex: {
541 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
542 ID.AddInteger(TI->getIndex());
543 ID.AddInteger(TI->getOffset());
544 ID.AddInteger(TI->getTargetFlags());
545 break;
547 case ISD::LOAD: {
548 const LoadSDNode *LD = cast<LoadSDNode>(N);
549 ID.AddInteger(LD->getMemoryVT().getRawBits());
550 ID.AddInteger(LD->getRawSubclassData());
551 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
552 break;
554 case ISD::STORE: {
555 const StoreSDNode *ST = cast<StoreSDNode>(N);
556 ID.AddInteger(ST->getMemoryVT().getRawBits());
557 ID.AddInteger(ST->getRawSubclassData());
558 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
559 break;
561 case ISD::MLOAD: {
562 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
563 ID.AddInteger(MLD->getMemoryVT().getRawBits());
564 ID.AddInteger(MLD->getRawSubclassData());
565 ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
566 break;
568 case ISD::MSTORE: {
569 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
570 ID.AddInteger(MST->getMemoryVT().getRawBits());
571 ID.AddInteger(MST->getRawSubclassData());
572 ID.AddInteger(MST->getPointerInfo().getAddrSpace());
573 break;
575 case ISD::MGATHER: {
576 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
577 ID.AddInteger(MG->getMemoryVT().getRawBits());
578 ID.AddInteger(MG->getRawSubclassData());
579 ID.AddInteger(MG->getPointerInfo().getAddrSpace());
580 break;
582 case ISD::MSCATTER: {
583 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
584 ID.AddInteger(MS->getMemoryVT().getRawBits());
585 ID.AddInteger(MS->getRawSubclassData());
586 ID.AddInteger(MS->getPointerInfo().getAddrSpace());
587 break;
589 case ISD::ATOMIC_CMP_SWAP:
590 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
591 case ISD::ATOMIC_SWAP:
592 case ISD::ATOMIC_LOAD_ADD:
593 case ISD::ATOMIC_LOAD_SUB:
594 case ISD::ATOMIC_LOAD_AND:
595 case ISD::ATOMIC_LOAD_CLR:
596 case ISD::ATOMIC_LOAD_OR:
597 case ISD::ATOMIC_LOAD_XOR:
598 case ISD::ATOMIC_LOAD_NAND:
599 case ISD::ATOMIC_LOAD_MIN:
600 case ISD::ATOMIC_LOAD_MAX:
601 case ISD::ATOMIC_LOAD_UMIN:
602 case ISD::ATOMIC_LOAD_UMAX:
603 case ISD::ATOMIC_LOAD:
604 case ISD::ATOMIC_STORE: {
605 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
606 ID.AddInteger(AT->getMemoryVT().getRawBits());
607 ID.AddInteger(AT->getRawSubclassData());
608 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
609 break;
611 case ISD::PREFETCH: {
612 const MemSDNode *PF = cast<MemSDNode>(N);
613 ID.AddInteger(PF->getPointerInfo().getAddrSpace());
614 break;
616 case ISD::VECTOR_SHUFFLE: {
617 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
618 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
619 i != e; ++i)
620 ID.AddInteger(SVN->getMaskElt(i));
621 break;
623 case ISD::TargetBlockAddress:
624 case ISD::BlockAddress: {
625 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
626 ID.AddPointer(BA->getBlockAddress());
627 ID.AddInteger(BA->getOffset());
628 ID.AddInteger(BA->getTargetFlags());
629 break;
631 } // end switch (N->getOpcode())
633 // Target specific memory nodes could also have address spaces to check.
634 if (N->isTargetMemoryOpcode())
635 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
638 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
639 /// data.
640 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
641 AddNodeIDOpcode(ID, N->getOpcode());
642 // Add the return value info.
643 AddNodeIDValueTypes(ID, N->getVTList());
644 // Add the operand info.
645 AddNodeIDOperands(ID, N->ops());
647 // Handle SDNode leafs with special info.
648 AddNodeIDCustom(ID, N);
651 //===----------------------------------------------------------------------===//
652 // SelectionDAG Class
653 //===----------------------------------------------------------------------===//
655 /// doNotCSE - Return true if CSE should not be performed for this node.
656 static bool doNotCSE(SDNode *N) {
657 if (N->getValueType(0) == MVT::Glue)
658 return true; // Never CSE anything that produces a flag.
660 switch (N->getOpcode()) {
661 default: break;
662 case ISD::HANDLENODE:
663 case ISD::EH_LABEL:
664 return true; // Never CSE these nodes.
667 // Check that remaining values produced are not flags.
668 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
669 if (N->getValueType(i) == MVT::Glue)
670 return true; // Never CSE anything that produces a flag.
672 return false;
675 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
676 /// SelectionDAG.
677 void SelectionDAG::RemoveDeadNodes() {
678 // Create a dummy node (which is not added to allnodes), that adds a reference
679 // to the root node, preventing it from being deleted.
680 HandleSDNode Dummy(getRoot());
682 SmallVector<SDNode*, 128> DeadNodes;
684 // Add all obviously-dead nodes to the DeadNodes worklist.
685 for (SDNode &Node : allnodes())
686 if (Node.use_empty())
687 DeadNodes.push_back(&Node);
689 RemoveDeadNodes(DeadNodes);
691 // If the root changed (e.g. it was a dead load, update the root).
692 setRoot(Dummy.getValue());
695 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
696 /// given list, and any nodes that become unreachable as a result.
697 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
699 // Process the worklist, deleting the nodes and adding their uses to the
700 // worklist.
701 while (!DeadNodes.empty()) {
702 SDNode *N = DeadNodes.pop_back_val();
703 // Skip to next node if we've already managed to delete the node. This could
704 // happen if replacing a node causes a node previously added to the node to
705 // be deleted.
706 if (N->getOpcode() == ISD::DELETED_NODE)
707 continue;
709 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
710 DUL->NodeDeleted(N, nullptr);
712 // Take the node out of the appropriate CSE map.
713 RemoveNodeFromCSEMaps(N);
715 // Next, brutally remove the operand list. This is safe to do, as there are
716 // no cycles in the graph.
717 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
718 SDUse &Use = *I++;
719 SDNode *Operand = Use.getNode();
720 Use.set(SDValue());
722 // Now that we removed this operand, see if there are no uses of it left.
723 if (Operand->use_empty())
724 DeadNodes.push_back(Operand);
727 DeallocateNode(N);
731 void SelectionDAG::RemoveDeadNode(SDNode *N){
732 SmallVector<SDNode*, 16> DeadNodes(1, N);
734 // Create a dummy node that adds a reference to the root node, preventing
735 // it from being deleted. (This matters if the root is an operand of the
736 // dead node.)
737 HandleSDNode Dummy(getRoot());
739 RemoveDeadNodes(DeadNodes);
742 void SelectionDAG::DeleteNode(SDNode *N) {
743 // First take this out of the appropriate CSE map.
744 RemoveNodeFromCSEMaps(N);
746 // Finally, remove uses due to operands of this node, remove from the
747 // AllNodes list, and delete the node.
748 DeleteNodeNotInCSEMaps(N);
751 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
752 assert(N->getIterator() != AllNodes.begin() &&
753 "Cannot delete the entry node!");
754 assert(N->use_empty() && "Cannot delete a node that is not dead!");
756 // Drop all of the operands and decrement used node's use counts.
757 N->DropOperands();
759 DeallocateNode(N);
762 void SDDbgInfo::erase(const SDNode *Node) {
763 DbgValMapType::iterator I = DbgValMap.find(Node);
764 if (I == DbgValMap.end())
765 return;
766 for (auto &Val: I->second)
767 Val->setIsInvalidated();
768 DbgValMap.erase(I);
771 void SelectionDAG::DeallocateNode(SDNode *N) {
772 // If we have operands, deallocate them.
773 removeOperands(N);
775 NodeAllocator.Deallocate(AllNodes.remove(N));
777 // Set the opcode to DELETED_NODE to help catch bugs when node
778 // memory is reallocated.
779 // FIXME: There are places in SDag that have grown a dependency on the opcode
780 // value in the released node.
781 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
782 N->NodeType = ISD::DELETED_NODE;
784 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
785 // them and forget about that node.
786 DbgInfo->erase(N);
789 #ifndef NDEBUG
790 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
791 static void VerifySDNode(SDNode *N) {
792 switch (N->getOpcode()) {
793 default:
794 break;
795 case ISD::BUILD_PAIR: {
796 EVT VT = N->getValueType(0);
797 assert(N->getNumValues() == 1 && "Too many results!");
798 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
799 "Wrong return type!");
800 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
801 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
802 "Mismatched operand types!");
803 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
804 "Wrong operand type!");
805 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
806 "Wrong return type size");
807 break;
809 case ISD::BUILD_VECTOR: {
810 assert(N->getNumValues() == 1 && "Too many results!");
811 assert(N->getValueType(0).isVector() && "Wrong return type!");
812 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
813 "Wrong number of operands!");
814 EVT EltVT = N->getValueType(0).getVectorElementType();
815 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
816 assert((I->getValueType() == EltVT ||
817 (EltVT.isInteger() && I->getValueType().isInteger() &&
818 EltVT.bitsLE(I->getValueType()))) &&
819 "Wrong operand type!");
820 assert(I->getValueType() == N->getOperand(0).getValueType() &&
821 "Operands must all have the same type");
823 break;
827 #endif // NDEBUG
829 /// Insert a newly allocated node into the DAG.
831 /// Handles insertion into the all nodes list and CSE map, as well as
832 /// verification and other common operations when a new node is allocated.
833 void SelectionDAG::InsertNode(SDNode *N) {
834 AllNodes.push_back(N);
835 #ifndef NDEBUG
836 N->PersistentId = NextPersistentId++;
837 VerifySDNode(N);
838 #endif
839 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
840 DUL->NodeInserted(N);
843 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
844 /// correspond to it. This is useful when we're about to delete or repurpose
845 /// the node. We don't want future request for structurally identical nodes
846 /// to return N anymore.
847 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
848 bool Erased = false;
849 switch (N->getOpcode()) {
850 case ISD::HANDLENODE: return false; // noop.
851 case ISD::CONDCODE:
852 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
853 "Cond code doesn't exist!");
854 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
855 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
856 break;
857 case ISD::ExternalSymbol:
858 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
859 break;
860 case ISD::TargetExternalSymbol: {
861 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
862 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
863 ESN->getSymbol(), ESN->getTargetFlags()));
864 break;
866 case ISD::MCSymbol: {
867 auto *MCSN = cast<MCSymbolSDNode>(N);
868 Erased = MCSymbols.erase(MCSN->getMCSymbol());
869 break;
871 case ISD::VALUETYPE: {
872 EVT VT = cast<VTSDNode>(N)->getVT();
873 if (VT.isExtended()) {
874 Erased = ExtendedValueTypeNodes.erase(VT);
875 } else {
876 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
877 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
879 break;
881 default:
882 // Remove it from the CSE Map.
883 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
884 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
885 Erased = CSEMap.RemoveNode(N);
886 break;
888 #ifndef NDEBUG
889 // Verify that the node was actually in one of the CSE maps, unless it has a
890 // flag result (which cannot be CSE'd) or is one of the special cases that are
891 // not subject to CSE.
892 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
893 !N->isMachineOpcode() && !doNotCSE(N)) {
894 N->dump(this);
895 dbgs() << "\n";
896 llvm_unreachable("Node is not in map!");
898 #endif
899 return Erased;
902 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
903 /// maps and modified in place. Add it back to the CSE maps, unless an identical
904 /// node already exists, in which case transfer all its users to the existing
905 /// node. This transfer can potentially trigger recursive merging.
906 void
907 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
908 // For node types that aren't CSE'd, just act as if no identical node
909 // already exists.
910 if (!doNotCSE(N)) {
911 SDNode *Existing = CSEMap.GetOrInsertNode(N);
912 if (Existing != N) {
913 // If there was already an existing matching node, use ReplaceAllUsesWith
914 // to replace the dead one with the existing one. This can cause
915 // recursive merging of other unrelated nodes down the line.
916 ReplaceAllUsesWith(N, Existing);
918 // N is now dead. Inform the listeners and delete it.
919 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
920 DUL->NodeDeleted(N, Existing);
921 DeleteNodeNotInCSEMaps(N);
922 return;
926 // If the node doesn't already exist, we updated it. Inform listeners.
927 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
928 DUL->NodeUpdated(N);
931 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
932 /// were replaced with those specified. If this node is never memoized,
933 /// return null, otherwise return a pointer to the slot it would take. If a
934 /// node already exists with these operands, the slot will be non-null.
935 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
936 void *&InsertPos) {
937 if (doNotCSE(N))
938 return nullptr;
940 SDValue Ops[] = { Op };
941 FoldingSetNodeID ID;
942 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
943 AddNodeIDCustom(ID, N);
944 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
945 if (Node)
946 Node->intersectFlagsWith(N->getFlags());
947 return Node;
950 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
951 /// were replaced with those specified. If this node is never memoized,
952 /// return null, otherwise return a pointer to the slot it would take. If a
953 /// node already exists with these operands, the slot will be non-null.
954 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
955 SDValue Op1, SDValue Op2,
956 void *&InsertPos) {
957 if (doNotCSE(N))
958 return nullptr;
960 SDValue Ops[] = { Op1, Op2 };
961 FoldingSetNodeID ID;
962 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
963 AddNodeIDCustom(ID, N);
964 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
965 if (Node)
966 Node->intersectFlagsWith(N->getFlags());
967 return Node;
970 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
971 /// were replaced with those specified. If this node is never memoized,
972 /// return null, otherwise return a pointer to the slot it would take. If a
973 /// node already exists with these operands, the slot will be non-null.
974 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
975 void *&InsertPos) {
976 if (doNotCSE(N))
977 return nullptr;
979 FoldingSetNodeID ID;
980 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
981 AddNodeIDCustom(ID, N);
982 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
983 if (Node)
984 Node->intersectFlagsWith(N->getFlags());
985 return Node;
988 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
989 Type *Ty = VT == MVT::iPTR ?
990 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
991 VT.getTypeForEVT(*getContext());
993 return getDataLayout().getABITypeAlignment(Ty);
996 // EntryNode could meaningfully have debug info if we can find it...
997 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
998 : TM(tm), OptLevel(OL),
999 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1000 Root(getEntryNode()) {
1001 InsertNode(&EntryNode);
1002 DbgInfo = new SDDbgInfo();
1005 void SelectionDAG::init(MachineFunction &NewMF,
1006 OptimizationRemarkEmitter &NewORE,
1007 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1008 LegacyDivergenceAnalysis * Divergence) {
1009 MF = &NewMF;
1010 SDAGISelPass = PassPtr;
1011 ORE = &NewORE;
1012 TLI = getSubtarget().getTargetLowering();
1013 TSI = getSubtarget().getSelectionDAGInfo();
1014 LibInfo = LibraryInfo;
1015 Context = &MF->getFunction().getContext();
1016 DA = Divergence;
1019 SelectionDAG::~SelectionDAG() {
1020 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1021 allnodes_clear();
1022 OperandRecycler.clear(OperandAllocator);
1023 delete DbgInfo;
1026 void SelectionDAG::allnodes_clear() {
1027 assert(&*AllNodes.begin() == &EntryNode);
1028 AllNodes.remove(AllNodes.begin());
1029 while (!AllNodes.empty())
1030 DeallocateNode(&AllNodes.front());
1031 #ifndef NDEBUG
1032 NextPersistentId = 0;
1033 #endif
1036 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1037 void *&InsertPos) {
1038 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1039 if (N) {
1040 switch (N->getOpcode()) {
1041 default: break;
1042 case ISD::Constant:
1043 case ISD::ConstantFP:
1044 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1045 "debug location. Use another overload.");
1048 return N;
1051 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1052 const SDLoc &DL, void *&InsertPos) {
1053 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1054 if (N) {
1055 switch (N->getOpcode()) {
1056 case ISD::Constant:
1057 case ISD::ConstantFP:
1058 // Erase debug location from the node if the node is used at several
1059 // different places. Do not propagate one location to all uses as it
1060 // will cause a worse single stepping debugging experience.
1061 if (N->getDebugLoc() != DL.getDebugLoc())
1062 N->setDebugLoc(DebugLoc());
1063 break;
1064 default:
1065 // When the node's point of use is located earlier in the instruction
1066 // sequence than its prior point of use, update its debug info to the
1067 // earlier location.
1068 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1069 N->setDebugLoc(DL.getDebugLoc());
1070 break;
1073 return N;
1076 void SelectionDAG::clear() {
1077 allnodes_clear();
1078 OperandRecycler.clear(OperandAllocator);
1079 OperandAllocator.Reset();
1080 CSEMap.clear();
1082 ExtendedValueTypeNodes.clear();
1083 ExternalSymbols.clear();
1084 TargetExternalSymbols.clear();
1085 MCSymbols.clear();
1086 SDCallSiteDbgInfo.clear();
1087 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1088 static_cast<CondCodeSDNode*>(nullptr));
1089 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1090 static_cast<SDNode*>(nullptr));
1092 EntryNode.UseList = nullptr;
1093 InsertNode(&EntryNode);
1094 Root = getEntryNode();
1095 DbgInfo->clear();
1098 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1099 return VT.bitsGT(Op.getValueType())
1100 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1101 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1104 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1105 return VT.bitsGT(Op.getValueType()) ?
1106 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1107 getNode(ISD::TRUNCATE, DL, VT, Op);
1110 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1111 return VT.bitsGT(Op.getValueType()) ?
1112 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1113 getNode(ISD::TRUNCATE, DL, VT, Op);
1116 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1117 return VT.bitsGT(Op.getValueType()) ?
1118 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1119 getNode(ISD::TRUNCATE, DL, VT, Op);
1122 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1123 EVT OpVT) {
1124 if (VT.bitsLE(Op.getValueType()))
1125 return getNode(ISD::TRUNCATE, SL, VT, Op);
1127 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1128 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1131 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1132 assert(!VT.isVector() &&
1133 "getZeroExtendInReg should use the vector element type instead of "
1134 "the vector type!");
1135 if (Op.getValueType().getScalarType() == VT) return Op;
1136 unsigned BitWidth = Op.getScalarValueSizeInBits();
1137 APInt Imm = APInt::getLowBitsSet(BitWidth,
1138 VT.getSizeInBits());
1139 return getNode(ISD::AND, DL, Op.getValueType(), Op,
1140 getConstant(Imm, DL, Op.getValueType()));
1143 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1144 // Only unsigned pointer semantics are supported right now. In the future this
1145 // might delegate to TLI to check pointer signedness.
1146 return getZExtOrTrunc(Op, DL, VT);
1149 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1150 // Only unsigned pointer semantics are supported right now. In the future this
1151 // might delegate to TLI to check pointer signedness.
1152 return getZeroExtendInReg(Op, DL, VT);
1155 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1156 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1157 EVT EltVT = VT.getScalarType();
1158 SDValue NegOne =
1159 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1160 return getNode(ISD::XOR, DL, VT, Val, NegOne);
1163 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1164 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1165 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1168 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1169 EVT OpVT) {
1170 if (!V)
1171 return getConstant(0, DL, VT);
1173 switch (TLI->getBooleanContents(OpVT)) {
1174 case TargetLowering::ZeroOrOneBooleanContent:
1175 case TargetLowering::UndefinedBooleanContent:
1176 return getConstant(1, DL, VT);
1177 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1178 return getAllOnesConstant(DL, VT);
1180 llvm_unreachable("Unexpected boolean content enum!");
1183 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1184 bool isT, bool isO) {
1185 EVT EltVT = VT.getScalarType();
1186 assert((EltVT.getSizeInBits() >= 64 ||
1187 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1188 "getConstant with a uint64_t value that doesn't fit in the type!");
1189 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1192 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1193 bool isT, bool isO) {
1194 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1197 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1198 EVT VT, bool isT, bool isO) {
1199 assert(VT.isInteger() && "Cannot create FP integer constant!");
1201 EVT EltVT = VT.getScalarType();
1202 const ConstantInt *Elt = &Val;
1204 // In some cases the vector type is legal but the element type is illegal and
1205 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1206 // inserted value (the type does not need to match the vector element type).
1207 // Any extra bits introduced will be truncated away.
1208 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1209 TargetLowering::TypePromoteInteger) {
1210 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1211 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1212 Elt = ConstantInt::get(*getContext(), NewVal);
1214 // In other cases the element type is illegal and needs to be expanded, for
1215 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1216 // the value into n parts and use a vector type with n-times the elements.
1217 // Then bitcast to the type requested.
1218 // Legalizing constants too early makes the DAGCombiner's job harder so we
1219 // only legalize if the DAG tells us we must produce legal types.
1220 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1221 TLI->getTypeAction(*getContext(), EltVT) ==
1222 TargetLowering::TypeExpandInteger) {
1223 const APInt &NewVal = Elt->getValue();
1224 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1225 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1226 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1227 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1229 // Check the temporary vector is the correct size. If this fails then
1230 // getTypeToTransformTo() probably returned a type whose size (in bits)
1231 // isn't a power-of-2 factor of the requested type size.
1232 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1234 SmallVector<SDValue, 2> EltParts;
1235 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1236 EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
1237 .zextOrTrunc(ViaEltSizeInBits), DL,
1238 ViaEltVT, isT, isO));
1241 // EltParts is currently in little endian order. If we actually want
1242 // big-endian order then reverse it now.
1243 if (getDataLayout().isBigEndian())
1244 std::reverse(EltParts.begin(), EltParts.end());
1246 // The elements must be reversed when the element order is different
1247 // to the endianness of the elements (because the BITCAST is itself a
1248 // vector shuffle in this situation). However, we do not need any code to
1249 // perform this reversal because getConstant() is producing a vector
1250 // splat.
1251 // This situation occurs in MIPS MSA.
1253 SmallVector<SDValue, 8> Ops;
1254 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1255 Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
1257 SDValue V = getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1258 return V;
1261 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1262 "APInt size does not match type size!");
1263 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1264 FoldingSetNodeID ID;
1265 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1266 ID.AddPointer(Elt);
1267 ID.AddBoolean(isO);
1268 void *IP = nullptr;
1269 SDNode *N = nullptr;
1270 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1271 if (!VT.isVector())
1272 return SDValue(N, 0);
1274 if (!N) {
1275 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1276 CSEMap.InsertNode(N, IP);
1277 InsertNode(N);
1278 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1281 SDValue Result(N, 0);
1282 if (VT.isVector())
1283 Result = getSplatBuildVector(VT, DL, Result);
1285 return Result;
1288 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1289 bool isTarget) {
1290 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1293 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1294 const SDLoc &DL, bool LegalTypes) {
1295 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1296 return getConstant(Val, DL, ShiftVT);
1299 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1300 bool isTarget) {
1301 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1304 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1305 EVT VT, bool isTarget) {
1306 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1308 EVT EltVT = VT.getScalarType();
1310 // Do the map lookup using the actual bit pattern for the floating point
1311 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1312 // we don't have issues with SNANs.
1313 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1314 FoldingSetNodeID ID;
1315 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1316 ID.AddPointer(&V);
1317 void *IP = nullptr;
1318 SDNode *N = nullptr;
1319 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1320 if (!VT.isVector())
1321 return SDValue(N, 0);
1323 if (!N) {
1324 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1325 CSEMap.InsertNode(N, IP);
1326 InsertNode(N);
1329 SDValue Result(N, 0);
1330 if (VT.isVector())
1331 Result = getSplatBuildVector(VT, DL, Result);
1332 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1333 return Result;
1336 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1337 bool isTarget) {
1338 EVT EltVT = VT.getScalarType();
1339 if (EltVT == MVT::f32)
1340 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1341 else if (EltVT == MVT::f64)
1342 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1343 else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1344 EltVT == MVT::f16) {
1345 bool Ignored;
1346 APFloat APF = APFloat(Val);
1347 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1348 &Ignored);
1349 return getConstantFP(APF, DL, VT, isTarget);
1350 } else
1351 llvm_unreachable("Unsupported type in getConstantFP");
1354 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1355 EVT VT, int64_t Offset, bool isTargetGA,
1356 unsigned TargetFlags) {
1357 assert((TargetFlags == 0 || isTargetGA) &&
1358 "Cannot set target flags on target-independent globals");
1360 // Truncate (with sign-extension) the offset value to the pointer size.
1361 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1362 if (BitWidth < 64)
1363 Offset = SignExtend64(Offset, BitWidth);
1365 unsigned Opc;
1366 if (GV->isThreadLocal())
1367 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1368 else
1369 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1371 FoldingSetNodeID ID;
1372 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1373 ID.AddPointer(GV);
1374 ID.AddInteger(Offset);
1375 ID.AddInteger(TargetFlags);
1376 void *IP = nullptr;
1377 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1378 return SDValue(E, 0);
1380 auto *N = newSDNode<GlobalAddressSDNode>(
1381 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1382 CSEMap.InsertNode(N, IP);
1383 InsertNode(N);
1384 return SDValue(N, 0);
1387 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1388 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1389 FoldingSetNodeID ID;
1390 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1391 ID.AddInteger(FI);
1392 void *IP = nullptr;
1393 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1394 return SDValue(E, 0);
1396 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1397 CSEMap.InsertNode(N, IP);
1398 InsertNode(N);
1399 return SDValue(N, 0);
1402 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1403 unsigned TargetFlags) {
1404 assert((TargetFlags == 0 || isTarget) &&
1405 "Cannot set target flags on target-independent jump tables");
1406 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1407 FoldingSetNodeID ID;
1408 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1409 ID.AddInteger(JTI);
1410 ID.AddInteger(TargetFlags);
1411 void *IP = nullptr;
1412 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1413 return SDValue(E, 0);
1415 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1416 CSEMap.InsertNode(N, IP);
1417 InsertNode(N);
1418 return SDValue(N, 0);
1421 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1422 unsigned Alignment, int Offset,
1423 bool isTarget,
1424 unsigned TargetFlags) {
1425 assert((TargetFlags == 0 || isTarget) &&
1426 "Cannot set target flags on target-independent globals");
1427 if (Alignment == 0)
1428 Alignment = MF->getFunction().hasOptSize()
1429 ? getDataLayout().getABITypeAlignment(C->getType())
1430 : getDataLayout().getPrefTypeAlignment(C->getType());
1431 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1432 FoldingSetNodeID ID;
1433 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1434 ID.AddInteger(Alignment);
1435 ID.AddInteger(Offset);
1436 ID.AddPointer(C);
1437 ID.AddInteger(TargetFlags);
1438 void *IP = nullptr;
1439 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1440 return SDValue(E, 0);
1442 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1443 TargetFlags);
1444 CSEMap.InsertNode(N, IP);
1445 InsertNode(N);
1446 return SDValue(N, 0);
1449 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1450 unsigned Alignment, int Offset,
1451 bool isTarget,
1452 unsigned TargetFlags) {
1453 assert((TargetFlags == 0 || isTarget) &&
1454 "Cannot set target flags on target-independent globals");
1455 if (Alignment == 0)
1456 Alignment = getDataLayout().getPrefTypeAlignment(C->getType());
1457 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1458 FoldingSetNodeID ID;
1459 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1460 ID.AddInteger(Alignment);
1461 ID.AddInteger(Offset);
1462 C->addSelectionDAGCSEId(ID);
1463 ID.AddInteger(TargetFlags);
1464 void *IP = nullptr;
1465 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1466 return SDValue(E, 0);
1468 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1469 TargetFlags);
1470 CSEMap.InsertNode(N, IP);
1471 InsertNode(N);
1472 return SDValue(N, 0);
1475 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1476 unsigned TargetFlags) {
1477 FoldingSetNodeID ID;
1478 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1479 ID.AddInteger(Index);
1480 ID.AddInteger(Offset);
1481 ID.AddInteger(TargetFlags);
1482 void *IP = nullptr;
1483 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1484 return SDValue(E, 0);
1486 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1487 CSEMap.InsertNode(N, IP);
1488 InsertNode(N);
1489 return SDValue(N, 0);
1492 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1493 FoldingSetNodeID ID;
1494 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1495 ID.AddPointer(MBB);
1496 void *IP = nullptr;
1497 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1498 return SDValue(E, 0);
1500 auto *N = newSDNode<BasicBlockSDNode>(MBB);
1501 CSEMap.InsertNode(N, IP);
1502 InsertNode(N);
1503 return SDValue(N, 0);
1506 SDValue SelectionDAG::getValueType(EVT VT) {
1507 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1508 ValueTypeNodes.size())
1509 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1511 SDNode *&N = VT.isExtended() ?
1512 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1514 if (N) return SDValue(N, 0);
1515 N = newSDNode<VTSDNode>(VT);
1516 InsertNode(N);
1517 return SDValue(N, 0);
1520 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1521 SDNode *&N = ExternalSymbols[Sym];
1522 if (N) return SDValue(N, 0);
1523 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1524 InsertNode(N);
1525 return SDValue(N, 0);
1528 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1529 SDNode *&N = MCSymbols[Sym];
1530 if (N)
1531 return SDValue(N, 0);
1532 N = newSDNode<MCSymbolSDNode>(Sym, VT);
1533 InsertNode(N);
1534 return SDValue(N, 0);
1537 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1538 unsigned TargetFlags) {
1539 SDNode *&N =
1540 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1541 if (N) return SDValue(N, 0);
1542 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1543 InsertNode(N);
1544 return SDValue(N, 0);
1547 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1548 if ((unsigned)Cond >= CondCodeNodes.size())
1549 CondCodeNodes.resize(Cond+1);
1551 if (!CondCodeNodes[Cond]) {
1552 auto *N = newSDNode<CondCodeSDNode>(Cond);
1553 CondCodeNodes[Cond] = N;
1554 InsertNode(N);
1557 return SDValue(CondCodeNodes[Cond], 0);
1560 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1561 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1562 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1563 std::swap(N1, N2);
1564 ShuffleVectorSDNode::commuteMask(M);
1567 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1568 SDValue N2, ArrayRef<int> Mask) {
1569 assert(VT.getVectorNumElements() == Mask.size() &&
1570 "Must have the same number of vector elements as mask elements!");
1571 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1572 "Invalid VECTOR_SHUFFLE");
1574 // Canonicalize shuffle undef, undef -> undef
1575 if (N1.isUndef() && N2.isUndef())
1576 return getUNDEF(VT);
1578 // Validate that all indices in Mask are within the range of the elements
1579 // input to the shuffle.
1580 int NElts = Mask.size();
1581 assert(llvm::all_of(Mask,
1582 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1583 "Index out of range");
1585 // Copy the mask so we can do any needed cleanup.
1586 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1588 // Canonicalize shuffle v, v -> v, undef
1589 if (N1 == N2) {
1590 N2 = getUNDEF(VT);
1591 for (int i = 0; i != NElts; ++i)
1592 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1595 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1596 if (N1.isUndef())
1597 commuteShuffle(N1, N2, MaskVec);
1599 if (TLI->hasVectorBlend()) {
1600 // If shuffling a splat, try to blend the splat instead. We do this here so
1601 // that even when this arises during lowering we don't have to re-handle it.
1602 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1603 BitVector UndefElements;
1604 SDValue Splat = BV->getSplatValue(&UndefElements);
1605 if (!Splat)
1606 return;
1608 for (int i = 0; i < NElts; ++i) {
1609 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1610 continue;
1612 // If this input comes from undef, mark it as such.
1613 if (UndefElements[MaskVec[i] - Offset]) {
1614 MaskVec[i] = -1;
1615 continue;
1618 // If we can blend a non-undef lane, use that instead.
1619 if (!UndefElements[i])
1620 MaskVec[i] = i + Offset;
1623 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1624 BlendSplat(N1BV, 0);
1625 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1626 BlendSplat(N2BV, NElts);
1629 // Canonicalize all index into lhs, -> shuffle lhs, undef
1630 // Canonicalize all index into rhs, -> shuffle rhs, undef
1631 bool AllLHS = true, AllRHS = true;
1632 bool N2Undef = N2.isUndef();
1633 for (int i = 0; i != NElts; ++i) {
1634 if (MaskVec[i] >= NElts) {
1635 if (N2Undef)
1636 MaskVec[i] = -1;
1637 else
1638 AllLHS = false;
1639 } else if (MaskVec[i] >= 0) {
1640 AllRHS = false;
1643 if (AllLHS && AllRHS)
1644 return getUNDEF(VT);
1645 if (AllLHS && !N2Undef)
1646 N2 = getUNDEF(VT);
1647 if (AllRHS) {
1648 N1 = getUNDEF(VT);
1649 commuteShuffle(N1, N2, MaskVec);
1651 // Reset our undef status after accounting for the mask.
1652 N2Undef = N2.isUndef();
1653 // Re-check whether both sides ended up undef.
1654 if (N1.isUndef() && N2Undef)
1655 return getUNDEF(VT);
1657 // If Identity shuffle return that node.
1658 bool Identity = true, AllSame = true;
1659 for (int i = 0; i != NElts; ++i) {
1660 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1661 if (MaskVec[i] != MaskVec[0]) AllSame = false;
1663 if (Identity && NElts)
1664 return N1;
1666 // Shuffling a constant splat doesn't change the result.
1667 if (N2Undef) {
1668 SDValue V = N1;
1670 // Look through any bitcasts. We check that these don't change the number
1671 // (and size) of elements and just changes their types.
1672 while (V.getOpcode() == ISD::BITCAST)
1673 V = V->getOperand(0);
1675 // A splat should always show up as a build vector node.
1676 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1677 BitVector UndefElements;
1678 SDValue Splat = BV->getSplatValue(&UndefElements);
1679 // If this is a splat of an undef, shuffling it is also undef.
1680 if (Splat && Splat.isUndef())
1681 return getUNDEF(VT);
1683 bool SameNumElts =
1684 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1686 // We only have a splat which can skip shuffles if there is a splatted
1687 // value and no undef lanes rearranged by the shuffle.
1688 if (Splat && UndefElements.none()) {
1689 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1690 // number of elements match or the value splatted is a zero constant.
1691 if (SameNumElts)
1692 return N1;
1693 if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1694 if (C->isNullValue())
1695 return N1;
1698 // If the shuffle itself creates a splat, build the vector directly.
1699 if (AllSame && SameNumElts) {
1700 EVT BuildVT = BV->getValueType(0);
1701 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1702 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1704 // We may have jumped through bitcasts, so the type of the
1705 // BUILD_VECTOR may not match the type of the shuffle.
1706 if (BuildVT != VT)
1707 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1708 return NewBV;
1713 FoldingSetNodeID ID;
1714 SDValue Ops[2] = { N1, N2 };
1715 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1716 for (int i = 0; i != NElts; ++i)
1717 ID.AddInteger(MaskVec[i]);
1719 void* IP = nullptr;
1720 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1721 return SDValue(E, 0);
1723 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1724 // SDNode doesn't have access to it. This memory will be "leaked" when
1725 // the node is deallocated, but recovered when the NodeAllocator is released.
1726 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1727 llvm::copy(MaskVec, MaskAlloc);
1729 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1730 dl.getDebugLoc(), MaskAlloc);
1731 createOperands(N, Ops);
1733 CSEMap.InsertNode(N, IP);
1734 InsertNode(N);
1735 SDValue V = SDValue(N, 0);
1736 NewSDValueDbgMsg(V, "Creating new node: ", this);
1737 return V;
1740 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1741 EVT VT = SV.getValueType(0);
1742 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1743 ShuffleVectorSDNode::commuteMask(MaskVec);
1745 SDValue Op0 = SV.getOperand(0);
1746 SDValue Op1 = SV.getOperand(1);
1747 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1750 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1751 FoldingSetNodeID ID;
1752 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1753 ID.AddInteger(RegNo);
1754 void *IP = nullptr;
1755 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1756 return SDValue(E, 0);
1758 auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1759 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
1760 CSEMap.InsertNode(N, IP);
1761 InsertNode(N);
1762 return SDValue(N, 0);
1765 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1766 FoldingSetNodeID ID;
1767 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1768 ID.AddPointer(RegMask);
1769 void *IP = nullptr;
1770 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1771 return SDValue(E, 0);
1773 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1774 CSEMap.InsertNode(N, IP);
1775 InsertNode(N);
1776 return SDValue(N, 0);
1779 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1780 MCSymbol *Label) {
1781 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
1784 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
1785 SDValue Root, MCSymbol *Label) {
1786 FoldingSetNodeID ID;
1787 SDValue Ops[] = { Root };
1788 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
1789 ID.AddPointer(Label);
1790 void *IP = nullptr;
1791 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1792 return SDValue(E, 0);
1794 auto *N =
1795 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
1796 createOperands(N, Ops);
1798 CSEMap.InsertNode(N, IP);
1799 InsertNode(N);
1800 return SDValue(N, 0);
1803 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1804 int64_t Offset, bool isTarget,
1805 unsigned TargetFlags) {
1806 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1808 FoldingSetNodeID ID;
1809 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1810 ID.AddPointer(BA);
1811 ID.AddInteger(Offset);
1812 ID.AddInteger(TargetFlags);
1813 void *IP = nullptr;
1814 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1815 return SDValue(E, 0);
1817 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
1818 CSEMap.InsertNode(N, IP);
1819 InsertNode(N);
1820 return SDValue(N, 0);
1823 SDValue SelectionDAG::getSrcValue(const Value *V) {
1824 assert((!V || V->getType()->isPointerTy()) &&
1825 "SrcValue is not a pointer?");
1827 FoldingSetNodeID ID;
1828 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
1829 ID.AddPointer(V);
1831 void *IP = nullptr;
1832 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1833 return SDValue(E, 0);
1835 auto *N = newSDNode<SrcValueSDNode>(V);
1836 CSEMap.InsertNode(N, IP);
1837 InsertNode(N);
1838 return SDValue(N, 0);
1841 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1842 FoldingSetNodeID ID;
1843 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
1844 ID.AddPointer(MD);
1846 void *IP = nullptr;
1847 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1848 return SDValue(E, 0);
1850 auto *N = newSDNode<MDNodeSDNode>(MD);
1851 CSEMap.InsertNode(N, IP);
1852 InsertNode(N);
1853 return SDValue(N, 0);
1856 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
1857 if (VT == V.getValueType())
1858 return V;
1860 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
1863 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
1864 unsigned SrcAS, unsigned DestAS) {
1865 SDValue Ops[] = {Ptr};
1866 FoldingSetNodeID ID;
1867 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
1868 ID.AddInteger(SrcAS);
1869 ID.AddInteger(DestAS);
1871 void *IP = nullptr;
1872 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1873 return SDValue(E, 0);
1875 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
1876 VT, SrcAS, DestAS);
1877 createOperands(N, Ops);
1879 CSEMap.InsertNode(N, IP);
1880 InsertNode(N);
1881 return SDValue(N, 0);
1884 /// getShiftAmountOperand - Return the specified value casted to
1885 /// the target's desired shift amount type.
1886 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1887 EVT OpTy = Op.getValueType();
1888 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
1889 if (OpTy == ShTy || OpTy.isVector()) return Op;
1891 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
1894 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
1895 SDLoc dl(Node);
1896 const TargetLowering &TLI = getTargetLoweringInfo();
1897 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1898 EVT VT = Node->getValueType(0);
1899 SDValue Tmp1 = Node->getOperand(0);
1900 SDValue Tmp2 = Node->getOperand(1);
1901 const llvm::MaybeAlign MA(Node->getConstantOperandVal(3));
1903 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
1904 Tmp2, MachinePointerInfo(V));
1905 SDValue VAList = VAListLoad;
1907 if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
1908 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1909 getConstant(MA->value() - 1, dl, VAList.getValueType()));
1911 VAList =
1912 getNode(ISD::AND, dl, VAList.getValueType(), VAList,
1913 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
1916 // Increment the pointer, VAList, to the next vaarg
1917 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1918 getConstant(getDataLayout().getTypeAllocSize(
1919 VT.getTypeForEVT(*getContext())),
1920 dl, VAList.getValueType()));
1921 // Store the incremented VAList to the legalized pointer
1922 Tmp1 =
1923 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
1924 // Load the actual argument out of the pointer VAList
1925 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
1928 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
1929 SDLoc dl(Node);
1930 const TargetLowering &TLI = getTargetLoweringInfo();
1931 // This defaults to loading a pointer from the input and storing it to the
1932 // output, returning the chain.
1933 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
1934 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
1935 SDValue Tmp1 =
1936 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
1937 Node->getOperand(2), MachinePointerInfo(VS));
1938 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
1939 MachinePointerInfo(VD));
1942 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1943 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1944 unsigned ByteSize = VT.getStoreSize();
1945 Type *Ty = VT.getTypeForEVT(*getContext());
1946 unsigned StackAlign =
1947 std::max((unsigned)getDataLayout().getPrefTypeAlignment(Ty), minAlign);
1949 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
1950 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1953 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1954 unsigned Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize());
1955 Type *Ty1 = VT1.getTypeForEVT(*getContext());
1956 Type *Ty2 = VT2.getTypeForEVT(*getContext());
1957 const DataLayout &DL = getDataLayout();
1958 unsigned Align =
1959 std::max(DL.getPrefTypeAlignment(Ty1), DL.getPrefTypeAlignment(Ty2));
1961 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1962 int FrameIdx = MFI.CreateStackObject(Bytes, Align, false);
1963 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1966 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
1967 ISD::CondCode Cond, const SDLoc &dl) {
1968 EVT OpVT = N1.getValueType();
1970 // These setcc operations always fold.
1971 switch (Cond) {
1972 default: break;
1973 case ISD::SETFALSE:
1974 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
1975 case ISD::SETTRUE:
1976 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
1978 case ISD::SETOEQ:
1979 case ISD::SETOGT:
1980 case ISD::SETOGE:
1981 case ISD::SETOLT:
1982 case ISD::SETOLE:
1983 case ISD::SETONE:
1984 case ISD::SETO:
1985 case ISD::SETUO:
1986 case ISD::SETUEQ:
1987 case ISD::SETUNE:
1988 assert(!OpVT.isInteger() && "Illegal setcc for integer!");
1989 break;
1992 if (OpVT.isInteger()) {
1993 // For EQ and NE, we can always pick a value for the undef to make the
1994 // predicate pass or fail, so we can return undef.
1995 // Matches behavior in llvm::ConstantFoldCompareInstruction.
1996 // icmp eq/ne X, undef -> undef.
1997 if ((N1.isUndef() || N2.isUndef()) &&
1998 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
1999 return getUNDEF(VT);
2001 // If both operands are undef, we can return undef for int comparison.
2002 // icmp undef, undef -> undef.
2003 if (N1.isUndef() && N2.isUndef())
2004 return getUNDEF(VT);
2006 // icmp X, X -> true/false
2007 // icmp X, undef -> true/false because undef could be X.
2008 if (N1 == N2)
2009 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2012 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2013 const APInt &C2 = N2C->getAPIntValue();
2014 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2015 const APInt &C1 = N1C->getAPIntValue();
2017 switch (Cond) {
2018 default: llvm_unreachable("Unknown integer setcc!");
2019 case ISD::SETEQ: return getBoolConstant(C1 == C2, dl, VT, OpVT);
2020 case ISD::SETNE: return getBoolConstant(C1 != C2, dl, VT, OpVT);
2021 case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
2022 case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
2023 case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
2024 case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
2025 case ISD::SETLT: return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
2026 case ISD::SETGT: return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
2027 case ISD::SETLE: return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
2028 case ISD::SETGE: return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
2033 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2034 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2036 if (N1CFP && N2CFP) {
2037 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2038 switch (Cond) {
2039 default: break;
2040 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2041 return getUNDEF(VT);
2042 LLVM_FALLTHROUGH;
2043 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2044 OpVT);
2045 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2046 return getUNDEF(VT);
2047 LLVM_FALLTHROUGH;
2048 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2049 R==APFloat::cmpLessThan, dl, VT,
2050 OpVT);
2051 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2052 return getUNDEF(VT);
2053 LLVM_FALLTHROUGH;
2054 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2055 OpVT);
2056 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2057 return getUNDEF(VT);
2058 LLVM_FALLTHROUGH;
2059 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2060 VT, OpVT);
2061 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2062 return getUNDEF(VT);
2063 LLVM_FALLTHROUGH;
2064 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2065 R==APFloat::cmpEqual, dl, VT,
2066 OpVT);
2067 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2068 return getUNDEF(VT);
2069 LLVM_FALLTHROUGH;
2070 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2071 R==APFloat::cmpEqual, dl, VT, OpVT);
2072 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2073 OpVT);
2074 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2075 OpVT);
2076 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2077 R==APFloat::cmpEqual, dl, VT,
2078 OpVT);
2079 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2080 OpVT);
2081 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2082 R==APFloat::cmpLessThan, dl, VT,
2083 OpVT);
2084 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2085 R==APFloat::cmpUnordered, dl, VT,
2086 OpVT);
2087 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2088 VT, OpVT);
2089 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2090 OpVT);
2092 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2093 // Ensure that the constant occurs on the RHS.
2094 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2095 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2096 return SDValue();
2097 return getSetCC(dl, VT, N2, N1, SwappedCond);
2098 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2099 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2100 // If an operand is known to be a nan (or undef that could be a nan), we can
2101 // fold it.
2102 // Choosing NaN for the undef will always make unordered comparison succeed
2103 // and ordered comparison fails.
2104 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2105 switch (ISD::getUnorderedFlavor(Cond)) {
2106 default:
2107 llvm_unreachable("Unknown flavor!");
2108 case 0: // Known false.
2109 return getBoolConstant(false, dl, VT, OpVT);
2110 case 1: // Known true.
2111 return getBoolConstant(true, dl, VT, OpVT);
2112 case 2: // Undefined.
2113 return getUNDEF(VT);
2117 // Could not fold it.
2118 return SDValue();
2121 /// See if the specified operand can be simplified with the knowledge that only
2122 /// the bits specified by DemandedBits are used.
2123 /// TODO: really we should be making this into the DAG equivalent of
2124 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2125 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2126 EVT VT = V.getValueType();
2127 APInt DemandedElts = VT.isVector()
2128 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2129 : APInt(1, 1);
2130 return GetDemandedBits(V, DemandedBits, DemandedElts);
2133 /// See if the specified operand can be simplified with the knowledge that only
2134 /// the bits specified by DemandedBits are used in the elements specified by
2135 /// DemandedElts.
2136 /// TODO: really we should be making this into the DAG equivalent of
2137 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2138 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2139 const APInt &DemandedElts) {
2140 switch (V.getOpcode()) {
2141 default:
2142 break;
2143 case ISD::Constant: {
2144 auto *CV = cast<ConstantSDNode>(V.getNode());
2145 assert(CV && "Const value should be ConstSDNode.");
2146 const APInt &CVal = CV->getAPIntValue();
2147 APInt NewVal = CVal & DemandedBits;
2148 if (NewVal != CVal)
2149 return getConstant(NewVal, SDLoc(V), V.getValueType());
2150 break;
2152 case ISD::OR:
2153 case ISD::XOR:
2154 case ISD::SIGN_EXTEND_INREG:
2155 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2156 *this, 0);
2157 case ISD::SRL:
2158 // Only look at single-use SRLs.
2159 if (!V.getNode()->hasOneUse())
2160 break;
2161 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2162 // See if we can recursively simplify the LHS.
2163 unsigned Amt = RHSC->getZExtValue();
2165 // Watch out for shift count overflow though.
2166 if (Amt >= DemandedBits.getBitWidth())
2167 break;
2168 APInt SrcDemandedBits = DemandedBits << Amt;
2169 if (SDValue SimplifyLHS =
2170 GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2171 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2172 V.getOperand(1));
2174 break;
2175 case ISD::AND: {
2176 // X & -1 -> X (ignoring bits which aren't demanded).
2177 // Also handle the case where masked out bits in X are known to be zero.
2178 if (ConstantSDNode *RHSC = isConstOrConstSplat(V.getOperand(1))) {
2179 const APInt &AndVal = RHSC->getAPIntValue();
2180 if (DemandedBits.isSubsetOf(AndVal) ||
2181 DemandedBits.isSubsetOf(computeKnownBits(V.getOperand(0)).Zero |
2182 AndVal))
2183 return V.getOperand(0);
2185 break;
2187 case ISD::ANY_EXTEND: {
2188 SDValue Src = V.getOperand(0);
2189 unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
2190 // Being conservative here - only peek through if we only demand bits in the
2191 // non-extended source (even though the extended bits are technically
2192 // undef).
2193 if (DemandedBits.getActiveBits() > SrcBitWidth)
2194 break;
2195 APInt SrcDemandedBits = DemandedBits.trunc(SrcBitWidth);
2196 if (SDValue DemandedSrc = GetDemandedBits(Src, SrcDemandedBits))
2197 return getNode(ISD::ANY_EXTEND, SDLoc(V), V.getValueType(), DemandedSrc);
2198 break;
2201 return SDValue();
2204 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2205 /// use this predicate to simplify operations downstream.
2206 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2207 unsigned BitWidth = Op.getScalarValueSizeInBits();
2208 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2211 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2212 /// this predicate to simplify operations downstream. Mask is known to be zero
2213 /// for bits that V cannot have.
2214 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2215 unsigned Depth) const {
2216 EVT VT = V.getValueType();
2217 APInt DemandedElts = VT.isVector()
2218 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2219 : APInt(1, 1);
2220 return MaskedValueIsZero(V, Mask, DemandedElts, Depth);
2223 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2224 /// DemandedElts. We use this predicate to simplify operations downstream.
2225 /// Mask is known to be zero for bits that V cannot have.
2226 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2227 const APInt &DemandedElts,
2228 unsigned Depth) const {
2229 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2232 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2233 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2234 unsigned Depth) const {
2235 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2238 /// isSplatValue - Return true if the vector V has the same value
2239 /// across all DemandedElts.
2240 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2241 APInt &UndefElts) {
2242 if (!DemandedElts)
2243 return false; // No demanded elts, better to assume we don't know anything.
2245 EVT VT = V.getValueType();
2246 assert(VT.isVector() && "Vector type expected");
2248 unsigned NumElts = VT.getVectorNumElements();
2249 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2250 UndefElts = APInt::getNullValue(NumElts);
2252 switch (V.getOpcode()) {
2253 case ISD::BUILD_VECTOR: {
2254 SDValue Scl;
2255 for (unsigned i = 0; i != NumElts; ++i) {
2256 SDValue Op = V.getOperand(i);
2257 if (Op.isUndef()) {
2258 UndefElts.setBit(i);
2259 continue;
2261 if (!DemandedElts[i])
2262 continue;
2263 if (Scl && Scl != Op)
2264 return false;
2265 Scl = Op;
2267 return true;
2269 case ISD::VECTOR_SHUFFLE: {
2270 // Check if this is a shuffle node doing a splat.
2271 // TODO: Do we need to handle shuffle(splat, undef, mask)?
2272 int SplatIndex = -1;
2273 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2274 for (int i = 0; i != (int)NumElts; ++i) {
2275 int M = Mask[i];
2276 if (M < 0) {
2277 UndefElts.setBit(i);
2278 continue;
2280 if (!DemandedElts[i])
2281 continue;
2282 if (0 <= SplatIndex && SplatIndex != M)
2283 return false;
2284 SplatIndex = M;
2286 return true;
2288 case ISD::EXTRACT_SUBVECTOR: {
2289 SDValue Src = V.getOperand(0);
2290 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(V.getOperand(1));
2291 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2292 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2293 // Offset the demanded elts by the subvector index.
2294 uint64_t Idx = SubIdx->getZExtValue();
2295 APInt UndefSrcElts;
2296 APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2297 if (isSplatValue(Src, DemandedSrc, UndefSrcElts)) {
2298 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2299 return true;
2302 break;
2304 case ISD::ADD:
2305 case ISD::SUB:
2306 case ISD::AND: {
2307 APInt UndefLHS, UndefRHS;
2308 SDValue LHS = V.getOperand(0);
2309 SDValue RHS = V.getOperand(1);
2310 if (isSplatValue(LHS, DemandedElts, UndefLHS) &&
2311 isSplatValue(RHS, DemandedElts, UndefRHS)) {
2312 UndefElts = UndefLHS | UndefRHS;
2313 return true;
2315 break;
2319 return false;
2322 /// Helper wrapper to main isSplatValue function.
2323 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2324 EVT VT = V.getValueType();
2325 assert(VT.isVector() && "Vector type expected");
2326 unsigned NumElts = VT.getVectorNumElements();
2328 APInt UndefElts;
2329 APInt DemandedElts = APInt::getAllOnesValue(NumElts);
2330 return isSplatValue(V, DemandedElts, UndefElts) &&
2331 (AllowUndefs || !UndefElts);
2334 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2335 V = peekThroughExtractSubvectors(V);
2337 EVT VT = V.getValueType();
2338 unsigned Opcode = V.getOpcode();
2339 switch (Opcode) {
2340 default: {
2341 APInt UndefElts;
2342 APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2343 if (isSplatValue(V, DemandedElts, UndefElts)) {
2344 // Handle case where all demanded elements are UNDEF.
2345 if (DemandedElts.isSubsetOf(UndefElts)) {
2346 SplatIdx = 0;
2347 return getUNDEF(VT);
2349 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2350 return V;
2352 break;
2354 case ISD::VECTOR_SHUFFLE: {
2355 // Check if this is a shuffle node doing a splat.
2356 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2357 // getTargetVShiftNode currently struggles without the splat source.
2358 auto *SVN = cast<ShuffleVectorSDNode>(V);
2359 if (!SVN->isSplat())
2360 break;
2361 int Idx = SVN->getSplatIndex();
2362 int NumElts = V.getValueType().getVectorNumElements();
2363 SplatIdx = Idx % NumElts;
2364 return V.getOperand(Idx / NumElts);
2368 return SDValue();
2371 SDValue SelectionDAG::getSplatValue(SDValue V) {
2372 int SplatIdx;
2373 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx))
2374 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V),
2375 SrcVector.getValueType().getScalarType(), SrcVector,
2376 getIntPtrConstant(SplatIdx, SDLoc(V)));
2377 return SDValue();
2380 /// If a SHL/SRA/SRL node has a constant or splat constant shift amount that
2381 /// is less than the element bit-width of the shift node, return it.
2382 static const APInt *getValidShiftAmountConstant(SDValue V) {
2383 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1))) {
2384 // Shifting more than the bitwidth is not valid.
2385 const APInt &ShAmt = SA->getAPIntValue();
2386 if (ShAmt.ult(V.getScalarValueSizeInBits()))
2387 return &ShAmt;
2389 return nullptr;
2392 /// Determine which bits of Op are known to be either zero or one and return
2393 /// them in Known. For vectors, the known bits are those that are shared by
2394 /// every vector element.
2395 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2396 EVT VT = Op.getValueType();
2397 APInt DemandedElts = VT.isVector()
2398 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2399 : APInt(1, 1);
2400 return computeKnownBits(Op, DemandedElts, Depth);
2403 /// Determine which bits of Op are known to be either zero or one and return
2404 /// them in Known. The DemandedElts argument allows us to only collect the known
2405 /// bits that are shared by the requested vector elements.
2406 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2407 unsigned Depth) const {
2408 unsigned BitWidth = Op.getScalarValueSizeInBits();
2410 KnownBits Known(BitWidth); // Don't know anything.
2412 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2413 // We know all of the bits for a constant!
2414 Known.One = C->getAPIntValue();
2415 Known.Zero = ~Known.One;
2416 return Known;
2418 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2419 // We know all of the bits for a constant fp!
2420 Known.One = C->getValueAPF().bitcastToAPInt();
2421 Known.Zero = ~Known.One;
2422 return Known;
2425 if (Depth >= MaxRecursionDepth)
2426 return Known; // Limit search depth.
2428 KnownBits Known2;
2429 unsigned NumElts = DemandedElts.getBitWidth();
2430 assert((!Op.getValueType().isVector() ||
2431 NumElts == Op.getValueType().getVectorNumElements()) &&
2432 "Unexpected vector size");
2434 if (!DemandedElts)
2435 return Known; // No demanded elts, better to assume we don't know anything.
2437 unsigned Opcode = Op.getOpcode();
2438 switch (Opcode) {
2439 case ISD::BUILD_VECTOR:
2440 // Collect the known bits that are shared by every demanded vector element.
2441 Known.Zero.setAllBits(); Known.One.setAllBits();
2442 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2443 if (!DemandedElts[i])
2444 continue;
2446 SDValue SrcOp = Op.getOperand(i);
2447 Known2 = computeKnownBits(SrcOp, Depth + 1);
2449 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2450 if (SrcOp.getValueSizeInBits() != BitWidth) {
2451 assert(SrcOp.getValueSizeInBits() > BitWidth &&
2452 "Expected BUILD_VECTOR implicit truncation");
2453 Known2 = Known2.trunc(BitWidth);
2456 // Known bits are the values that are shared by every demanded element.
2457 Known.One &= Known2.One;
2458 Known.Zero &= Known2.Zero;
2460 // If we don't know any bits, early out.
2461 if (Known.isUnknown())
2462 break;
2464 break;
2465 case ISD::VECTOR_SHUFFLE: {
2466 // Collect the known bits that are shared by every vector element referenced
2467 // by the shuffle.
2468 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2469 Known.Zero.setAllBits(); Known.One.setAllBits();
2470 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2471 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2472 for (unsigned i = 0; i != NumElts; ++i) {
2473 if (!DemandedElts[i])
2474 continue;
2476 int M = SVN->getMaskElt(i);
2477 if (M < 0) {
2478 // For UNDEF elements, we don't know anything about the common state of
2479 // the shuffle result.
2480 Known.resetAll();
2481 DemandedLHS.clearAllBits();
2482 DemandedRHS.clearAllBits();
2483 break;
2486 if ((unsigned)M < NumElts)
2487 DemandedLHS.setBit((unsigned)M % NumElts);
2488 else
2489 DemandedRHS.setBit((unsigned)M % NumElts);
2491 // Known bits are the values that are shared by every demanded element.
2492 if (!!DemandedLHS) {
2493 SDValue LHS = Op.getOperand(0);
2494 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2495 Known.One &= Known2.One;
2496 Known.Zero &= Known2.Zero;
2498 // If we don't know any bits, early out.
2499 if (Known.isUnknown())
2500 break;
2501 if (!!DemandedRHS) {
2502 SDValue RHS = Op.getOperand(1);
2503 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2504 Known.One &= Known2.One;
2505 Known.Zero &= Known2.Zero;
2507 break;
2509 case ISD::CONCAT_VECTORS: {
2510 // Split DemandedElts and test each of the demanded subvectors.
2511 Known.Zero.setAllBits(); Known.One.setAllBits();
2512 EVT SubVectorVT = Op.getOperand(0).getValueType();
2513 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2514 unsigned NumSubVectors = Op.getNumOperands();
2515 for (unsigned i = 0; i != NumSubVectors; ++i) {
2516 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2517 DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2518 if (!!DemandedSub) {
2519 SDValue Sub = Op.getOperand(i);
2520 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2521 Known.One &= Known2.One;
2522 Known.Zero &= Known2.Zero;
2524 // If we don't know any bits, early out.
2525 if (Known.isUnknown())
2526 break;
2528 break;
2530 case ISD::INSERT_SUBVECTOR: {
2531 // If we know the element index, demand any elements from the subvector and
2532 // the remainder from the src its inserted into, otherwise demand them all.
2533 SDValue Src = Op.getOperand(0);
2534 SDValue Sub = Op.getOperand(1);
2535 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2536 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2537 if (SubIdx && SubIdx->getAPIntValue().ule(NumElts - NumSubElts)) {
2538 Known.One.setAllBits();
2539 Known.Zero.setAllBits();
2540 uint64_t Idx = SubIdx->getZExtValue();
2541 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2542 if (!!DemandedSubElts) {
2543 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2544 if (Known.isUnknown())
2545 break; // early-out.
2547 APInt SubMask = APInt::getBitsSet(NumElts, Idx, Idx + NumSubElts);
2548 APInt DemandedSrcElts = DemandedElts & ~SubMask;
2549 if (!!DemandedSrcElts) {
2550 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2551 Known.One &= Known2.One;
2552 Known.Zero &= Known2.Zero;
2554 } else {
2555 Known = computeKnownBits(Sub, Depth + 1);
2556 if (Known.isUnknown())
2557 break; // early-out.
2558 Known2 = computeKnownBits(Src, Depth + 1);
2559 Known.One &= Known2.One;
2560 Known.Zero &= Known2.Zero;
2562 break;
2564 case ISD::EXTRACT_SUBVECTOR: {
2565 // If we know the element index, just demand that subvector elements,
2566 // otherwise demand them all.
2567 SDValue Src = Op.getOperand(0);
2568 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2569 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2570 APInt DemandedSrc = APInt::getAllOnesValue(NumSrcElts);
2571 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2572 // Offset the demanded elts by the subvector index.
2573 uint64_t Idx = SubIdx->getZExtValue();
2574 DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2576 Known = computeKnownBits(Src, DemandedSrc, Depth + 1);
2577 break;
2579 case ISD::SCALAR_TO_VECTOR: {
2580 // We know about scalar_to_vector as much as we know about it source,
2581 // which becomes the first element of otherwise unknown vector.
2582 if (DemandedElts != 1)
2583 break;
2585 SDValue N0 = Op.getOperand(0);
2586 Known = computeKnownBits(N0, Depth + 1);
2587 if (N0.getValueSizeInBits() != BitWidth)
2588 Known = Known.trunc(BitWidth);
2590 break;
2592 case ISD::BITCAST: {
2593 SDValue N0 = Op.getOperand(0);
2594 EVT SubVT = N0.getValueType();
2595 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2597 // Ignore bitcasts from unsupported types.
2598 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2599 break;
2601 // Fast handling of 'identity' bitcasts.
2602 if (BitWidth == SubBitWidth) {
2603 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2604 break;
2607 bool IsLE = getDataLayout().isLittleEndian();
2609 // Bitcast 'small element' vector to 'large element' scalar/vector.
2610 if ((BitWidth % SubBitWidth) == 0) {
2611 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2613 // Collect known bits for the (larger) output by collecting the known
2614 // bits from each set of sub elements and shift these into place.
2615 // We need to separately call computeKnownBits for each set of
2616 // sub elements as the knownbits for each is likely to be different.
2617 unsigned SubScale = BitWidth / SubBitWidth;
2618 APInt SubDemandedElts(NumElts * SubScale, 0);
2619 for (unsigned i = 0; i != NumElts; ++i)
2620 if (DemandedElts[i])
2621 SubDemandedElts.setBit(i * SubScale);
2623 for (unsigned i = 0; i != SubScale; ++i) {
2624 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2625 Depth + 1);
2626 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2627 Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts);
2628 Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts);
2632 // Bitcast 'large element' scalar/vector to 'small element' vector.
2633 if ((SubBitWidth % BitWidth) == 0) {
2634 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2636 // Collect known bits for the (smaller) output by collecting the known
2637 // bits from the overlapping larger input elements and extracting the
2638 // sub sections we actually care about.
2639 unsigned SubScale = SubBitWidth / BitWidth;
2640 APInt SubDemandedElts(NumElts / SubScale, 0);
2641 for (unsigned i = 0; i != NumElts; ++i)
2642 if (DemandedElts[i])
2643 SubDemandedElts.setBit(i / SubScale);
2645 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
2647 Known.Zero.setAllBits(); Known.One.setAllBits();
2648 for (unsigned i = 0; i != NumElts; ++i)
2649 if (DemandedElts[i]) {
2650 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
2651 unsigned Offset = (Shifts % SubScale) * BitWidth;
2652 Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
2653 Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
2654 // If we don't know any bits, early out.
2655 if (Known.isUnknown())
2656 break;
2659 break;
2661 case ISD::AND:
2662 // If either the LHS or the RHS are Zero, the result is zero.
2663 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2664 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2666 // Output known-1 bits are only known if set in both the LHS & RHS.
2667 Known.One &= Known2.One;
2668 // Output known-0 are known to be clear if zero in either the LHS | RHS.
2669 Known.Zero |= Known2.Zero;
2670 break;
2671 case ISD::OR:
2672 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2673 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2675 // Output known-0 bits are only known if clear in both the LHS & RHS.
2676 Known.Zero &= Known2.Zero;
2677 // Output known-1 are known to be set if set in either the LHS | RHS.
2678 Known.One |= Known2.One;
2679 break;
2680 case ISD::XOR: {
2681 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2682 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2684 // Output known-0 bits are known if clear or set in both the LHS & RHS.
2685 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
2686 // Output known-1 are known to be set if set in only one of the LHS, RHS.
2687 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
2688 Known.Zero = KnownZeroOut;
2689 break;
2691 case ISD::MUL: {
2692 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2693 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2695 // If low bits are zero in either operand, output low known-0 bits.
2696 // Also compute a conservative estimate for high known-0 bits.
2697 // More trickiness is possible, but this is sufficient for the
2698 // interesting case of alignment computation.
2699 unsigned TrailZ = Known.countMinTrailingZeros() +
2700 Known2.countMinTrailingZeros();
2701 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
2702 Known2.countMinLeadingZeros(),
2703 BitWidth) - BitWidth;
2705 Known.resetAll();
2706 Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
2707 Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
2708 break;
2710 case ISD::UDIV: {
2711 // For the purposes of computing leading zeros we can conservatively
2712 // treat a udiv as a logical right shift by the power of 2 known to
2713 // be less than the denominator.
2714 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2715 unsigned LeadZ = Known2.countMinLeadingZeros();
2717 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2718 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
2719 if (RHSMaxLeadingZeros != BitWidth)
2720 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
2722 Known.Zero.setHighBits(LeadZ);
2723 break;
2725 case ISD::SELECT:
2726 case ISD::VSELECT:
2727 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
2728 // If we don't know any bits, early out.
2729 if (Known.isUnknown())
2730 break;
2731 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
2733 // Only known if known in both the LHS and RHS.
2734 Known.One &= Known2.One;
2735 Known.Zero &= Known2.Zero;
2736 break;
2737 case ISD::SELECT_CC:
2738 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
2739 // If we don't know any bits, early out.
2740 if (Known.isUnknown())
2741 break;
2742 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
2744 // Only known if known in both the LHS and RHS.
2745 Known.One &= Known2.One;
2746 Known.Zero &= Known2.Zero;
2747 break;
2748 case ISD::SMULO:
2749 case ISD::UMULO:
2750 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
2751 if (Op.getResNo() != 1)
2752 break;
2753 // The boolean result conforms to getBooleanContents.
2754 // If we know the result of a setcc has the top bits zero, use this info.
2755 // We know that we have an integer-based boolean since these operations
2756 // are only available for integer.
2757 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2758 TargetLowering::ZeroOrOneBooleanContent &&
2759 BitWidth > 1)
2760 Known.Zero.setBitsFrom(1);
2761 break;
2762 case ISD::SETCC:
2763 // If we know the result of a setcc has the top bits zero, use this info.
2764 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2765 TargetLowering::ZeroOrOneBooleanContent &&
2766 BitWidth > 1)
2767 Known.Zero.setBitsFrom(1);
2768 break;
2769 case ISD::SHL:
2770 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2771 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2772 unsigned Shift = ShAmt->getZExtValue();
2773 Known.Zero <<= Shift;
2774 Known.One <<= Shift;
2775 // Low bits are known zero.
2776 Known.Zero.setLowBits(Shift);
2778 break;
2779 case ISD::SRL:
2780 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2781 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2782 unsigned Shift = ShAmt->getZExtValue();
2783 Known.Zero.lshrInPlace(Shift);
2784 Known.One.lshrInPlace(Shift);
2785 // High bits are known zero.
2786 Known.Zero.setHighBits(Shift);
2787 } else if (auto *BV = dyn_cast<BuildVectorSDNode>(Op.getOperand(1))) {
2788 // If the shift amount is a vector of constants see if we can bound
2789 // the number of upper zero bits.
2790 unsigned ShiftAmountMin = BitWidth;
2791 for (unsigned i = 0; i != BV->getNumOperands(); ++i) {
2792 if (auto *C = dyn_cast<ConstantSDNode>(BV->getOperand(i))) {
2793 const APInt &ShAmt = C->getAPIntValue();
2794 if (ShAmt.ult(BitWidth)) {
2795 ShiftAmountMin = std::min<unsigned>(ShiftAmountMin,
2796 ShAmt.getZExtValue());
2797 continue;
2800 // Don't know anything.
2801 ShiftAmountMin = 0;
2802 break;
2805 Known.Zero.setHighBits(ShiftAmountMin);
2807 break;
2808 case ISD::SRA:
2809 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2810 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2811 unsigned Shift = ShAmt->getZExtValue();
2812 // Sign extend known zero/one bit (else is unknown).
2813 Known.Zero.ashrInPlace(Shift);
2814 Known.One.ashrInPlace(Shift);
2816 break;
2817 case ISD::FSHL:
2818 case ISD::FSHR:
2819 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
2820 unsigned Amt = C->getAPIntValue().urem(BitWidth);
2822 // For fshl, 0-shift returns the 1st arg.
2823 // For fshr, 0-shift returns the 2nd arg.
2824 if (Amt == 0) {
2825 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
2826 DemandedElts, Depth + 1);
2827 break;
2830 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
2831 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
2832 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2833 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2834 if (Opcode == ISD::FSHL) {
2835 Known.One <<= Amt;
2836 Known.Zero <<= Amt;
2837 Known2.One.lshrInPlace(BitWidth - Amt);
2838 Known2.Zero.lshrInPlace(BitWidth - Amt);
2839 } else {
2840 Known.One <<= BitWidth - Amt;
2841 Known.Zero <<= BitWidth - Amt;
2842 Known2.One.lshrInPlace(Amt);
2843 Known2.Zero.lshrInPlace(Amt);
2845 Known.One |= Known2.One;
2846 Known.Zero |= Known2.Zero;
2848 break;
2849 case ISD::SIGN_EXTEND_INREG: {
2850 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2851 unsigned EBits = EVT.getScalarSizeInBits();
2853 // Sign extension. Compute the demanded bits in the result that are not
2854 // present in the input.
2855 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
2857 APInt InSignMask = APInt::getSignMask(EBits);
2858 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
2860 // If the sign extended bits are demanded, we know that the sign
2861 // bit is demanded.
2862 InSignMask = InSignMask.zext(BitWidth);
2863 if (NewBits.getBoolValue())
2864 InputDemandedBits |= InSignMask;
2866 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2867 Known.One &= InputDemandedBits;
2868 Known.Zero &= InputDemandedBits;
2870 // If the sign bit of the input is known set or clear, then we know the
2871 // top bits of the result.
2872 if (Known.Zero.intersects(InSignMask)) { // Input sign bit known clear
2873 Known.Zero |= NewBits;
2874 Known.One &= ~NewBits;
2875 } else if (Known.One.intersects(InSignMask)) { // Input sign bit known set
2876 Known.One |= NewBits;
2877 Known.Zero &= ~NewBits;
2878 } else { // Input sign bit unknown
2879 Known.Zero &= ~NewBits;
2880 Known.One &= ~NewBits;
2882 break;
2884 case ISD::CTTZ:
2885 case ISD::CTTZ_ZERO_UNDEF: {
2886 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2887 // If we have a known 1, its position is our upper bound.
2888 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2889 unsigned LowBits = Log2_32(PossibleTZ) + 1;
2890 Known.Zero.setBitsFrom(LowBits);
2891 break;
2893 case ISD::CTLZ:
2894 case ISD::CTLZ_ZERO_UNDEF: {
2895 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2896 // If we have a known 1, its position is our upper bound.
2897 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2898 unsigned LowBits = Log2_32(PossibleLZ) + 1;
2899 Known.Zero.setBitsFrom(LowBits);
2900 break;
2902 case ISD::CTPOP: {
2903 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2904 // If we know some of the bits are zero, they can't be one.
2905 unsigned PossibleOnes = Known2.countMaxPopulation();
2906 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
2907 break;
2909 case ISD::LOAD: {
2910 LoadSDNode *LD = cast<LoadSDNode>(Op);
2911 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
2912 if (ISD::isNON_EXTLoad(LD) && Cst) {
2913 // Determine any common known bits from the loaded constant pool value.
2914 Type *CstTy = Cst->getType();
2915 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
2916 // If its a vector splat, then we can (quickly) reuse the scalar path.
2917 // NOTE: We assume all elements match and none are UNDEF.
2918 if (CstTy->isVectorTy()) {
2919 if (const Constant *Splat = Cst->getSplatValue()) {
2920 Cst = Splat;
2921 CstTy = Cst->getType();
2924 // TODO - do we need to handle different bitwidths?
2925 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
2926 // Iterate across all vector elements finding common known bits.
2927 Known.One.setAllBits();
2928 Known.Zero.setAllBits();
2929 for (unsigned i = 0; i != NumElts; ++i) {
2930 if (!DemandedElts[i])
2931 continue;
2932 if (Constant *Elt = Cst->getAggregateElement(i)) {
2933 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
2934 const APInt &Value = CInt->getValue();
2935 Known.One &= Value;
2936 Known.Zero &= ~Value;
2937 continue;
2939 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
2940 APInt Value = CFP->getValueAPF().bitcastToAPInt();
2941 Known.One &= Value;
2942 Known.Zero &= ~Value;
2943 continue;
2946 Known.One.clearAllBits();
2947 Known.Zero.clearAllBits();
2948 break;
2950 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
2951 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
2952 const APInt &Value = CInt->getValue();
2953 Known.One = Value;
2954 Known.Zero = ~Value;
2955 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
2956 APInt Value = CFP->getValueAPF().bitcastToAPInt();
2957 Known.One = Value;
2958 Known.Zero = ~Value;
2962 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
2963 // If this is a ZEXTLoad and we are looking at the loaded value.
2964 EVT VT = LD->getMemoryVT();
2965 unsigned MemBits = VT.getScalarSizeInBits();
2966 Known.Zero.setBitsFrom(MemBits);
2967 } else if (const MDNode *Ranges = LD->getRanges()) {
2968 if (LD->getExtensionType() == ISD::NON_EXTLOAD)
2969 computeKnownBitsFromRangeMetadata(*Ranges, Known);
2971 break;
2973 case ISD::ZERO_EXTEND_VECTOR_INREG: {
2974 EVT InVT = Op.getOperand(0).getValueType();
2975 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
2976 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
2977 Known = Known.zext(BitWidth, true /* ExtendedBitsAreKnownZero */);
2978 break;
2980 case ISD::ZERO_EXTEND: {
2981 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2982 Known = Known.zext(BitWidth, true /* ExtendedBitsAreKnownZero */);
2983 break;
2985 case ISD::SIGN_EXTEND_VECTOR_INREG: {
2986 EVT InVT = Op.getOperand(0).getValueType();
2987 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
2988 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
2989 // If the sign bit is known to be zero or one, then sext will extend
2990 // it to the top bits, else it will just zext.
2991 Known = Known.sext(BitWidth);
2992 break;
2994 case ISD::SIGN_EXTEND: {
2995 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2996 // If the sign bit is known to be zero or one, then sext will extend
2997 // it to the top bits, else it will just zext.
2998 Known = Known.sext(BitWidth);
2999 break;
3001 case ISD::ANY_EXTEND: {
3002 Known = computeKnownBits(Op.getOperand(0), Depth+1);
3003 Known = Known.zext(BitWidth, false /* ExtendedBitsAreKnownZero */);
3004 break;
3006 case ISD::TRUNCATE: {
3007 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3008 Known = Known.trunc(BitWidth);
3009 break;
3011 case ISD::AssertZext: {
3012 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3013 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3014 Known = computeKnownBits(Op.getOperand(0), Depth+1);
3015 Known.Zero |= (~InMask);
3016 Known.One &= (~Known.Zero);
3017 break;
3019 case ISD::FGETSIGN:
3020 // All bits are zero except the low bit.
3021 Known.Zero.setBitsFrom(1);
3022 break;
3023 case ISD::USUBO:
3024 case ISD::SSUBO:
3025 if (Op.getResNo() == 1) {
3026 // If we know the result of a setcc has the top bits zero, use this info.
3027 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3028 TargetLowering::ZeroOrOneBooleanContent &&
3029 BitWidth > 1)
3030 Known.Zero.setBitsFrom(1);
3031 break;
3033 LLVM_FALLTHROUGH;
3034 case ISD::SUB:
3035 case ISD::SUBC: {
3036 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3037 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3038 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3039 Known, Known2);
3040 break;
3042 case ISD::UADDO:
3043 case ISD::SADDO:
3044 case ISD::ADDCARRY:
3045 if (Op.getResNo() == 1) {
3046 // If we know the result of a setcc has the top bits zero, use this info.
3047 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3048 TargetLowering::ZeroOrOneBooleanContent &&
3049 BitWidth > 1)
3050 Known.Zero.setBitsFrom(1);
3051 break;
3053 LLVM_FALLTHROUGH;
3054 case ISD::ADD:
3055 case ISD::ADDC:
3056 case ISD::ADDE: {
3057 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3059 // With ADDE and ADDCARRY, a carry bit may be added in.
3060 KnownBits Carry(1);
3061 if (Opcode == ISD::ADDE)
3062 // Can't track carry from glue, set carry to unknown.
3063 Carry.resetAll();
3064 else if (Opcode == ISD::ADDCARRY)
3065 // TODO: Compute known bits for the carry operand. Not sure if it is worth
3066 // the trouble (how often will we find a known carry bit). And I haven't
3067 // tested this very much yet, but something like this might work:
3068 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3069 // Carry = Carry.zextOrTrunc(1, false);
3070 Carry.resetAll();
3071 else
3072 Carry.setAllZero();
3074 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3075 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3076 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3077 break;
3079 case ISD::SREM:
3080 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
3081 const APInt &RA = Rem->getAPIntValue().abs();
3082 if (RA.isPowerOf2()) {
3083 APInt LowBits = RA - 1;
3084 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3086 // The low bits of the first operand are unchanged by the srem.
3087 Known.Zero = Known2.Zero & LowBits;
3088 Known.One = Known2.One & LowBits;
3090 // If the first operand is non-negative or has all low bits zero, then
3091 // the upper bits are all zero.
3092 if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
3093 Known.Zero |= ~LowBits;
3095 // If the first operand is negative and not all low bits are zero, then
3096 // the upper bits are all one.
3097 if (Known2.isNegative() && LowBits.intersects(Known2.One))
3098 Known.One |= ~LowBits;
3099 assert((Known.Zero & Known.One) == 0&&"Bits known to be one AND zero?");
3102 break;
3103 case ISD::UREM: {
3104 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
3105 const APInt &RA = Rem->getAPIntValue();
3106 if (RA.isPowerOf2()) {
3107 APInt LowBits = (RA - 1);
3108 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3110 // The upper bits are all zero, the lower ones are unchanged.
3111 Known.Zero = Known2.Zero | ~LowBits;
3112 Known.One = Known2.One & LowBits;
3113 break;
3117 // Since the result is less than or equal to either operand, any leading
3118 // zero bits in either operand must also exist in the result.
3119 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3120 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3122 uint32_t Leaders =
3123 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
3124 Known.resetAll();
3125 Known.Zero.setHighBits(Leaders);
3126 break;
3128 case ISD::EXTRACT_ELEMENT: {
3129 Known = computeKnownBits(Op.getOperand(0), Depth+1);
3130 const unsigned Index = Op.getConstantOperandVal(1);
3131 const unsigned EltBitWidth = Op.getValueSizeInBits();
3133 // Remove low part of known bits mask
3134 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3135 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3137 // Remove high part of known bit mask
3138 Known = Known.trunc(EltBitWidth);
3139 break;
3141 case ISD::EXTRACT_VECTOR_ELT: {
3142 SDValue InVec = Op.getOperand(0);
3143 SDValue EltNo = Op.getOperand(1);
3144 EVT VecVT = InVec.getValueType();
3145 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3146 const unsigned NumSrcElts = VecVT.getVectorNumElements();
3147 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3148 // anything about the extended bits.
3149 if (BitWidth > EltBitWidth)
3150 Known = Known.trunc(EltBitWidth);
3151 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3152 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) {
3153 // If we know the element index, just demand that vector element.
3154 unsigned Idx = ConstEltNo->getZExtValue();
3155 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
3156 Known = computeKnownBits(InVec, DemandedElt, Depth + 1);
3157 } else {
3158 // Unknown element index, so ignore DemandedElts and demand them all.
3159 Known = computeKnownBits(InVec, Depth + 1);
3161 if (BitWidth > EltBitWidth)
3162 Known = Known.zext(BitWidth, false /* => any extend */);
3163 break;
3165 case ISD::INSERT_VECTOR_ELT: {
3166 SDValue InVec = Op.getOperand(0);
3167 SDValue InVal = Op.getOperand(1);
3168 SDValue EltNo = Op.getOperand(2);
3170 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3171 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3172 // If we know the element index, split the demand between the
3173 // source vector and the inserted element.
3174 Known.Zero = Known.One = APInt::getAllOnesValue(BitWidth);
3175 unsigned EltIdx = CEltNo->getZExtValue();
3177 // If we demand the inserted element then add its common known bits.
3178 if (DemandedElts[EltIdx]) {
3179 Known2 = computeKnownBits(InVal, Depth + 1);
3180 Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
3181 Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
3184 // If we demand the source vector then add its common known bits, ensuring
3185 // that we don't demand the inserted element.
3186 APInt VectorElts = DemandedElts & ~(APInt::getOneBitSet(NumElts, EltIdx));
3187 if (!!VectorElts) {
3188 Known2 = computeKnownBits(InVec, VectorElts, Depth + 1);
3189 Known.One &= Known2.One;
3190 Known.Zero &= Known2.Zero;
3192 } else {
3193 // Unknown element index, so ignore DemandedElts and demand them all.
3194 Known = computeKnownBits(InVec, Depth + 1);
3195 Known2 = computeKnownBits(InVal, Depth + 1);
3196 Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
3197 Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
3199 break;
3201 case ISD::BITREVERSE: {
3202 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3203 Known.Zero = Known2.Zero.reverseBits();
3204 Known.One = Known2.One.reverseBits();
3205 break;
3207 case ISD::BSWAP: {
3208 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3209 Known.Zero = Known2.Zero.byteSwap();
3210 Known.One = Known2.One.byteSwap();
3211 break;
3213 case ISD::ABS: {
3214 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3216 // If the source's MSB is zero then we know the rest of the bits already.
3217 if (Known2.isNonNegative()) {
3218 Known.Zero = Known2.Zero;
3219 Known.One = Known2.One;
3220 break;
3223 // We only know that the absolute values's MSB will be zero iff there is
3224 // a set bit that isn't the sign bit (otherwise it could be INT_MIN).
3225 Known2.One.clearSignBit();
3226 if (Known2.One.getBoolValue()) {
3227 Known.Zero = APInt::getSignMask(BitWidth);
3228 break;
3230 break;
3232 case ISD::UMIN: {
3233 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3234 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3236 // UMIN - we know that the result will have the maximum of the
3237 // known zero leading bits of the inputs.
3238 unsigned LeadZero = Known.countMinLeadingZeros();
3239 LeadZero = std::max(LeadZero, Known2.countMinLeadingZeros());
3241 Known.Zero &= Known2.Zero;
3242 Known.One &= Known2.One;
3243 Known.Zero.setHighBits(LeadZero);
3244 break;
3246 case ISD::UMAX: {
3247 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3248 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3250 // UMAX - we know that the result will have the maximum of the
3251 // known one leading bits of the inputs.
3252 unsigned LeadOne = Known.countMinLeadingOnes();
3253 LeadOne = std::max(LeadOne, Known2.countMinLeadingOnes());
3255 Known.Zero &= Known2.Zero;
3256 Known.One &= Known2.One;
3257 Known.One.setHighBits(LeadOne);
3258 break;
3260 case ISD::SMIN:
3261 case ISD::SMAX: {
3262 // If we have a clamp pattern, we know that the number of sign bits will be
3263 // the minimum of the clamp min/max range.
3264 bool IsMax = (Opcode == ISD::SMAX);
3265 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3266 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3267 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3268 CstHigh =
3269 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3270 if (CstLow && CstHigh) {
3271 if (!IsMax)
3272 std::swap(CstLow, CstHigh);
3274 const APInt &ValueLow = CstLow->getAPIntValue();
3275 const APInt &ValueHigh = CstHigh->getAPIntValue();
3276 if (ValueLow.sle(ValueHigh)) {
3277 unsigned LowSignBits = ValueLow.getNumSignBits();
3278 unsigned HighSignBits = ValueHigh.getNumSignBits();
3279 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3280 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3281 Known.One.setHighBits(MinSignBits);
3282 break;
3284 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3285 Known.Zero.setHighBits(MinSignBits);
3286 break;
3291 // Fallback - just get the shared known bits of the operands.
3292 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3293 if (Known.isUnknown()) break; // Early-out
3294 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3295 Known.Zero &= Known2.Zero;
3296 Known.One &= Known2.One;
3297 break;
3299 case ISD::FrameIndex:
3300 case ISD::TargetFrameIndex:
3301 TLI->computeKnownBitsForFrameIndex(Op, Known, DemandedElts, *this, Depth);
3302 break;
3304 default:
3305 if (Opcode < ISD::BUILTIN_OP_END)
3306 break;
3307 LLVM_FALLTHROUGH;
3308 case ISD::INTRINSIC_WO_CHAIN:
3309 case ISD::INTRINSIC_W_CHAIN:
3310 case ISD::INTRINSIC_VOID:
3311 // Allow the target to implement this method for its nodes.
3312 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3313 break;
3316 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3317 return Known;
3320 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3321 SDValue N1) const {
3322 // X + 0 never overflow
3323 if (isNullConstant(N1))
3324 return OFK_Never;
3326 KnownBits N1Known = computeKnownBits(N1);
3327 if (N1Known.Zero.getBoolValue()) {
3328 KnownBits N0Known = computeKnownBits(N0);
3330 bool overflow;
3331 (void)(~N0Known.Zero).uadd_ov(~N1Known.Zero, overflow);
3332 if (!overflow)
3333 return OFK_Never;
3336 // mulhi + 1 never overflow
3337 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3338 (~N1Known.Zero & 0x01) == ~N1Known.Zero)
3339 return OFK_Never;
3341 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3342 KnownBits N0Known = computeKnownBits(N0);
3344 if ((~N0Known.Zero & 0x01) == ~N0Known.Zero)
3345 return OFK_Never;
3348 return OFK_Sometime;
3351 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3352 EVT OpVT = Val.getValueType();
3353 unsigned BitWidth = OpVT.getScalarSizeInBits();
3355 // Is the constant a known power of 2?
3356 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3357 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3359 // A left-shift of a constant one will have exactly one bit set because
3360 // shifting the bit off the end is undefined.
3361 if (Val.getOpcode() == ISD::SHL) {
3362 auto *C = isConstOrConstSplat(Val.getOperand(0));
3363 if (C && C->getAPIntValue() == 1)
3364 return true;
3367 // Similarly, a logical right-shift of a constant sign-bit will have exactly
3368 // one bit set.
3369 if (Val.getOpcode() == ISD::SRL) {
3370 auto *C = isConstOrConstSplat(Val.getOperand(0));
3371 if (C && C->getAPIntValue().isSignMask())
3372 return true;
3375 // Are all operands of a build vector constant powers of two?
3376 if (Val.getOpcode() == ISD::BUILD_VECTOR)
3377 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3378 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3379 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3380 return false;
3382 return true;
3384 // More could be done here, though the above checks are enough
3385 // to handle some common cases.
3387 // Fall back to computeKnownBits to catch other known cases.
3388 KnownBits Known = computeKnownBits(Val);
3389 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3392 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3393 EVT VT = Op.getValueType();
3394 APInt DemandedElts = VT.isVector()
3395 ? APInt::getAllOnesValue(VT.getVectorNumElements())
3396 : APInt(1, 1);
3397 return ComputeNumSignBits(Op, DemandedElts, Depth);
3400 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3401 unsigned Depth) const {
3402 EVT VT = Op.getValueType();
3403 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3404 unsigned VTBits = VT.getScalarSizeInBits();
3405 unsigned NumElts = DemandedElts.getBitWidth();
3406 unsigned Tmp, Tmp2;
3407 unsigned FirstAnswer = 1;
3409 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3410 const APInt &Val = C->getAPIntValue();
3411 return Val.getNumSignBits();
3414 if (Depth >= MaxRecursionDepth)
3415 return 1; // Limit search depth.
3417 if (!DemandedElts)
3418 return 1; // No demanded elts, better to assume we don't know anything.
3420 unsigned Opcode = Op.getOpcode();
3421 switch (Opcode) {
3422 default: break;
3423 case ISD::AssertSext:
3424 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3425 return VTBits-Tmp+1;
3426 case ISD::AssertZext:
3427 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3428 return VTBits-Tmp;
3430 case ISD::BUILD_VECTOR:
3431 Tmp = VTBits;
3432 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3433 if (!DemandedElts[i])
3434 continue;
3436 SDValue SrcOp = Op.getOperand(i);
3437 Tmp2 = ComputeNumSignBits(Op.getOperand(i), Depth + 1);
3439 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3440 if (SrcOp.getValueSizeInBits() != VTBits) {
3441 assert(SrcOp.getValueSizeInBits() > VTBits &&
3442 "Expected BUILD_VECTOR implicit truncation");
3443 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3444 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3446 Tmp = std::min(Tmp, Tmp2);
3448 return Tmp;
3450 case ISD::VECTOR_SHUFFLE: {
3451 // Collect the minimum number of sign bits that are shared by every vector
3452 // element referenced by the shuffle.
3453 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3454 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3455 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3456 for (unsigned i = 0; i != NumElts; ++i) {
3457 int M = SVN->getMaskElt(i);
3458 if (!DemandedElts[i])
3459 continue;
3460 // For UNDEF elements, we don't know anything about the common state of
3461 // the shuffle result.
3462 if (M < 0)
3463 return 1;
3464 if ((unsigned)M < NumElts)
3465 DemandedLHS.setBit((unsigned)M % NumElts);
3466 else
3467 DemandedRHS.setBit((unsigned)M % NumElts);
3469 Tmp = std::numeric_limits<unsigned>::max();
3470 if (!!DemandedLHS)
3471 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3472 if (!!DemandedRHS) {
3473 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3474 Tmp = std::min(Tmp, Tmp2);
3476 // If we don't know anything, early out and try computeKnownBits fall-back.
3477 if (Tmp == 1)
3478 break;
3479 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3480 return Tmp;
3483 case ISD::BITCAST: {
3484 SDValue N0 = Op.getOperand(0);
3485 EVT SrcVT = N0.getValueType();
3486 unsigned SrcBits = SrcVT.getScalarSizeInBits();
3488 // Ignore bitcasts from unsupported types..
3489 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3490 break;
3492 // Fast handling of 'identity' bitcasts.
3493 if (VTBits == SrcBits)
3494 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3496 bool IsLE = getDataLayout().isLittleEndian();
3498 // Bitcast 'large element' scalar/vector to 'small element' vector.
3499 if ((SrcBits % VTBits) == 0) {
3500 assert(VT.isVector() && "Expected bitcast to vector");
3502 unsigned Scale = SrcBits / VTBits;
3503 APInt SrcDemandedElts(NumElts / Scale, 0);
3504 for (unsigned i = 0; i != NumElts; ++i)
3505 if (DemandedElts[i])
3506 SrcDemandedElts.setBit(i / Scale);
3508 // Fast case - sign splat can be simply split across the small elements.
3509 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3510 if (Tmp == SrcBits)
3511 return VTBits;
3513 // Slow case - determine how far the sign extends into each sub-element.
3514 Tmp2 = VTBits;
3515 for (unsigned i = 0; i != NumElts; ++i)
3516 if (DemandedElts[i]) {
3517 unsigned SubOffset = i % Scale;
3518 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3519 SubOffset = SubOffset * VTBits;
3520 if (Tmp <= SubOffset)
3521 return 1;
3522 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3524 return Tmp2;
3526 break;
3529 case ISD::SIGN_EXTEND:
3530 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3531 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3532 case ISD::SIGN_EXTEND_INREG:
3533 // Max of the input and what this extends.
3534 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3535 Tmp = VTBits-Tmp+1;
3536 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3537 return std::max(Tmp, Tmp2);
3538 case ISD::SIGN_EXTEND_VECTOR_INREG: {
3539 SDValue Src = Op.getOperand(0);
3540 EVT SrcVT = Src.getValueType();
3541 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3542 Tmp = VTBits - SrcVT.getScalarSizeInBits();
3543 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3546 case ISD::SRA:
3547 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3548 // SRA X, C -> adds C sign bits.
3549 if (ConstantSDNode *C =
3550 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3551 APInt ShiftVal = C->getAPIntValue();
3552 ShiftVal += Tmp;
3553 Tmp = ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
3555 return Tmp;
3556 case ISD::SHL:
3557 if (ConstantSDNode *C =
3558 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3559 // shl destroys sign bits.
3560 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3561 if (C->getAPIntValue().uge(VTBits) || // Bad shift.
3562 C->getAPIntValue().uge(Tmp)) break; // Shifted all sign bits out.
3563 return Tmp - C->getZExtValue();
3565 break;
3566 case ISD::AND:
3567 case ISD::OR:
3568 case ISD::XOR: // NOT is handled here.
3569 // Logical binary ops preserve the number of sign bits at the worst.
3570 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3571 if (Tmp != 1) {
3572 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3573 FirstAnswer = std::min(Tmp, Tmp2);
3574 // We computed what we know about the sign bits as our first
3575 // answer. Now proceed to the generic code that uses
3576 // computeKnownBits, and pick whichever answer is better.
3578 break;
3580 case ISD::SELECT:
3581 case ISD::VSELECT:
3582 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3583 if (Tmp == 1) return 1; // Early out.
3584 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3585 return std::min(Tmp, Tmp2);
3586 case ISD::SELECT_CC:
3587 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3588 if (Tmp == 1) return 1; // Early out.
3589 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3590 return std::min(Tmp, Tmp2);
3592 case ISD::SMIN:
3593 case ISD::SMAX: {
3594 // If we have a clamp pattern, we know that the number of sign bits will be
3595 // the minimum of the clamp min/max range.
3596 bool IsMax = (Opcode == ISD::SMAX);
3597 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3598 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3599 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3600 CstHigh =
3601 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3602 if (CstLow && CstHigh) {
3603 if (!IsMax)
3604 std::swap(CstLow, CstHigh);
3605 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3606 Tmp = CstLow->getAPIntValue().getNumSignBits();
3607 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3608 return std::min(Tmp, Tmp2);
3612 // Fallback - just get the minimum number of sign bits of the operands.
3613 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3614 if (Tmp == 1)
3615 return 1; // Early out.
3616 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3617 return std::min(Tmp, Tmp2);
3619 case ISD::UMIN:
3620 case ISD::UMAX:
3621 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3622 if (Tmp == 1)
3623 return 1; // Early out.
3624 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3625 return std::min(Tmp, Tmp2);
3626 case ISD::SADDO:
3627 case ISD::UADDO:
3628 case ISD::SSUBO:
3629 case ISD::USUBO:
3630 case ISD::SMULO:
3631 case ISD::UMULO:
3632 if (Op.getResNo() != 1)
3633 break;
3634 // The boolean result conforms to getBooleanContents. Fall through.
3635 // If setcc returns 0/-1, all bits are sign bits.
3636 // We know that we have an integer-based boolean since these operations
3637 // are only available for integer.
3638 if (TLI->getBooleanContents(VT.isVector(), false) ==
3639 TargetLowering::ZeroOrNegativeOneBooleanContent)
3640 return VTBits;
3641 break;
3642 case ISD::SETCC:
3643 // If setcc returns 0/-1, all bits are sign bits.
3644 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3645 TargetLowering::ZeroOrNegativeOneBooleanContent)
3646 return VTBits;
3647 break;
3648 case ISD::ROTL:
3649 case ISD::ROTR:
3650 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3651 unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3653 // Handle rotate right by N like a rotate left by 32-N.
3654 if (Opcode == ISD::ROTR)
3655 RotAmt = (VTBits - RotAmt) % VTBits;
3657 // If we aren't rotating out all of the known-in sign bits, return the
3658 // number that are left. This handles rotl(sext(x), 1) for example.
3659 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3660 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3662 break;
3663 case ISD::ADD:
3664 case ISD::ADDC:
3665 // Add can have at most one carry bit. Thus we know that the output
3666 // is, at worst, one more bit than the inputs.
3667 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3668 if (Tmp == 1) return 1; // Early out.
3670 // Special case decrementing a value (ADD X, -1):
3671 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3672 if (CRHS->isAllOnesValue()) {
3673 KnownBits Known = computeKnownBits(Op.getOperand(0), Depth+1);
3675 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3676 // sign bits set.
3677 if ((Known.Zero | 1).isAllOnesValue())
3678 return VTBits;
3680 // If we are subtracting one from a positive number, there is no carry
3681 // out of the result.
3682 if (Known.isNonNegative())
3683 return Tmp;
3686 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3687 if (Tmp2 == 1) return 1;
3688 return std::min(Tmp, Tmp2)-1;
3690 case ISD::SUB:
3691 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3692 if (Tmp2 == 1) return 1;
3694 // Handle NEG.
3695 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0)))
3696 if (CLHS->isNullValue()) {
3697 KnownBits Known = computeKnownBits(Op.getOperand(1), Depth+1);
3698 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3699 // sign bits set.
3700 if ((Known.Zero | 1).isAllOnesValue())
3701 return VTBits;
3703 // If the input is known to be positive (the sign bit is known clear),
3704 // the output of the NEG has the same number of sign bits as the input.
3705 if (Known.isNonNegative())
3706 return Tmp2;
3708 // Otherwise, we treat this like a SUB.
3711 // Sub can have at most one carry bit. Thus we know that the output
3712 // is, at worst, one more bit than the inputs.
3713 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3714 if (Tmp == 1) return 1; // Early out.
3715 return std::min(Tmp, Tmp2)-1;
3716 case ISD::MUL: {
3717 // The output of the Mul can be at most twice the valid bits in the inputs.
3718 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3719 if (SignBitsOp0 == 1)
3720 break;
3721 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3722 if (SignBitsOp1 == 1)
3723 break;
3724 unsigned OutValidBits =
3725 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
3726 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
3728 case ISD::TRUNCATE: {
3729 // Check if the sign bits of source go down as far as the truncated value.
3730 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3731 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3732 if (NumSrcSignBits > (NumSrcBits - VTBits))
3733 return NumSrcSignBits - (NumSrcBits - VTBits);
3734 break;
3736 case ISD::EXTRACT_ELEMENT: {
3737 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3738 const int BitWidth = Op.getValueSizeInBits();
3739 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3741 // Get reverse index (starting from 1), Op1 value indexes elements from
3742 // little end. Sign starts at big end.
3743 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3745 // If the sign portion ends in our element the subtraction gives correct
3746 // result. Otherwise it gives either negative or > bitwidth result
3747 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3749 case ISD::INSERT_VECTOR_ELT: {
3750 SDValue InVec = Op.getOperand(0);
3751 SDValue InVal = Op.getOperand(1);
3752 SDValue EltNo = Op.getOperand(2);
3754 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3755 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3756 // If we know the element index, split the demand between the
3757 // source vector and the inserted element.
3758 unsigned EltIdx = CEltNo->getZExtValue();
3760 // If we demand the inserted element then get its sign bits.
3761 Tmp = std::numeric_limits<unsigned>::max();
3762 if (DemandedElts[EltIdx]) {
3763 // TODO - handle implicit truncation of inserted elements.
3764 if (InVal.getScalarValueSizeInBits() != VTBits)
3765 break;
3766 Tmp = ComputeNumSignBits(InVal, Depth + 1);
3769 // If we demand the source vector then get its sign bits, and determine
3770 // the minimum.
3771 APInt VectorElts = DemandedElts;
3772 VectorElts.clearBit(EltIdx);
3773 if (!!VectorElts) {
3774 Tmp2 = ComputeNumSignBits(InVec, VectorElts, Depth + 1);
3775 Tmp = std::min(Tmp, Tmp2);
3777 } else {
3778 // Unknown element index, so ignore DemandedElts and demand them all.
3779 Tmp = ComputeNumSignBits(InVec, Depth + 1);
3780 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
3781 Tmp = std::min(Tmp, Tmp2);
3783 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3784 return Tmp;
3786 case ISD::EXTRACT_VECTOR_ELT: {
3787 SDValue InVec = Op.getOperand(0);
3788 SDValue EltNo = Op.getOperand(1);
3789 EVT VecVT = InVec.getValueType();
3790 const unsigned BitWidth = Op.getValueSizeInBits();
3791 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
3792 const unsigned NumSrcElts = VecVT.getVectorNumElements();
3794 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
3795 // anything about sign bits. But if the sizes match we can derive knowledge
3796 // about sign bits from the vector operand.
3797 if (BitWidth != EltBitWidth)
3798 break;
3800 // If we know the element index, just demand that vector element, else for
3801 // an unknown element index, ignore DemandedElts and demand them all.
3802 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3803 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3804 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3805 DemandedSrcElts =
3806 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3808 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
3810 case ISD::EXTRACT_SUBVECTOR: {
3811 // If we know the element index, just demand that subvector elements,
3812 // otherwise demand them all.
3813 SDValue Src = Op.getOperand(0);
3814 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
3815 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3816 APInt DemandedSrc = APInt::getAllOnesValue(NumSrcElts);
3817 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
3818 // Offset the demanded elts by the subvector index.
3819 uint64_t Idx = SubIdx->getZExtValue();
3820 DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
3822 return ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
3824 case ISD::CONCAT_VECTORS: {
3825 // Determine the minimum number of sign bits across all demanded
3826 // elts of the input vectors. Early out if the result is already 1.
3827 Tmp = std::numeric_limits<unsigned>::max();
3828 EVT SubVectorVT = Op.getOperand(0).getValueType();
3829 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3830 unsigned NumSubVectors = Op.getNumOperands();
3831 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
3832 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
3833 DemandedSub = DemandedSub.trunc(NumSubVectorElts);
3834 if (!DemandedSub)
3835 continue;
3836 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
3837 Tmp = std::min(Tmp, Tmp2);
3839 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3840 return Tmp;
3842 case ISD::INSERT_SUBVECTOR: {
3843 // If we know the element index, demand any elements from the subvector and
3844 // the remainder from the src its inserted into, otherwise demand them all.
3845 SDValue Src = Op.getOperand(0);
3846 SDValue Sub = Op.getOperand(1);
3847 auto *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3848 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3849 if (SubIdx && SubIdx->getAPIntValue().ule(NumElts - NumSubElts)) {
3850 Tmp = std::numeric_limits<unsigned>::max();
3851 uint64_t Idx = SubIdx->getZExtValue();
3852 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3853 if (!!DemandedSubElts) {
3854 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
3855 if (Tmp == 1) return 1; // early-out
3857 APInt SubMask = APInt::getBitsSet(NumElts, Idx, Idx + NumSubElts);
3858 APInt DemandedSrcElts = DemandedElts & ~SubMask;
3859 if (!!DemandedSrcElts) {
3860 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
3861 Tmp = std::min(Tmp, Tmp2);
3863 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3864 return Tmp;
3867 // Not able to determine the index so just assume worst case.
3868 Tmp = ComputeNumSignBits(Sub, Depth + 1);
3869 if (Tmp == 1) return 1; // early-out
3870 Tmp2 = ComputeNumSignBits(Src, Depth + 1);
3871 Tmp = std::min(Tmp, Tmp2);
3872 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3873 return Tmp;
3877 // If we are looking at the loaded value of the SDNode.
3878 if (Op.getResNo() == 0) {
3879 // Handle LOADX separately here. EXTLOAD case will fallthrough.
3880 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
3881 unsigned ExtType = LD->getExtensionType();
3882 switch (ExtType) {
3883 default: break;
3884 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
3885 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3886 return VTBits - Tmp + 1;
3887 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
3888 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3889 return VTBits - Tmp;
3890 case ISD::NON_EXTLOAD:
3891 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
3892 // We only need to handle vectors - computeKnownBits should handle
3893 // scalar cases.
3894 Type *CstTy = Cst->getType();
3895 if (CstTy->isVectorTy() &&
3896 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
3897 Tmp = VTBits;
3898 for (unsigned i = 0; i != NumElts; ++i) {
3899 if (!DemandedElts[i])
3900 continue;
3901 if (Constant *Elt = Cst->getAggregateElement(i)) {
3902 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3903 const APInt &Value = CInt->getValue();
3904 Tmp = std::min(Tmp, Value.getNumSignBits());
3905 continue;
3907 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3908 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3909 Tmp = std::min(Tmp, Value.getNumSignBits());
3910 continue;
3913 // Unknown type. Conservatively assume no bits match sign bit.
3914 return 1;
3916 return Tmp;
3919 break;
3924 // Allow the target to implement this method for its nodes.
3925 if (Opcode >= ISD::BUILTIN_OP_END ||
3926 Opcode == ISD::INTRINSIC_WO_CHAIN ||
3927 Opcode == ISD::INTRINSIC_W_CHAIN ||
3928 Opcode == ISD::INTRINSIC_VOID) {
3929 unsigned NumBits =
3930 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
3931 if (NumBits > 1)
3932 FirstAnswer = std::max(FirstAnswer, NumBits);
3935 // Finally, if we can prove that the top bits of the result are 0's or 1's,
3936 // use this information.
3937 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
3939 APInt Mask;
3940 if (Known.isNonNegative()) { // sign bit is 0
3941 Mask = Known.Zero;
3942 } else if (Known.isNegative()) { // sign bit is 1;
3943 Mask = Known.One;
3944 } else {
3945 // Nothing known.
3946 return FirstAnswer;
3949 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
3950 // the number of identical bits in the top of the input value.
3951 Mask = ~Mask;
3952 Mask <<= Mask.getBitWidth()-VTBits;
3953 // Return # leading zeros. We use 'min' here in case Val was zero before
3954 // shifting. We don't want to return '64' as for an i32 "0".
3955 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
3958 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
3959 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
3960 !isa<ConstantSDNode>(Op.getOperand(1)))
3961 return false;
3963 if (Op.getOpcode() == ISD::OR &&
3964 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
3965 return false;
3967 return true;
3970 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
3971 // If we're told that NaNs won't happen, assume they won't.
3972 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
3973 return true;
3975 if (Depth >= MaxRecursionDepth)
3976 return false; // Limit search depth.
3978 // TODO: Handle vectors.
3979 // If the value is a constant, we can obviously see if it is a NaN or not.
3980 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
3981 return !C->getValueAPF().isNaN() ||
3982 (SNaN && !C->getValueAPF().isSignaling());
3985 unsigned Opcode = Op.getOpcode();
3986 switch (Opcode) {
3987 case ISD::FADD:
3988 case ISD::FSUB:
3989 case ISD::FMUL:
3990 case ISD::FDIV:
3991 case ISD::FREM:
3992 case ISD::FSIN:
3993 case ISD::FCOS: {
3994 if (SNaN)
3995 return true;
3996 // TODO: Need isKnownNeverInfinity
3997 return false;
3999 case ISD::FCANONICALIZE:
4000 case ISD::FEXP:
4001 case ISD::FEXP2:
4002 case ISD::FTRUNC:
4003 case ISD::FFLOOR:
4004 case ISD::FCEIL:
4005 case ISD::FROUND:
4006 case ISD::FRINT:
4007 case ISD::FNEARBYINT: {
4008 if (SNaN)
4009 return true;
4010 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4012 case ISD::FABS:
4013 case ISD::FNEG:
4014 case ISD::FCOPYSIGN: {
4015 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4017 case ISD::SELECT:
4018 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4019 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4020 case ISD::FP_EXTEND:
4021 case ISD::FP_ROUND: {
4022 if (SNaN)
4023 return true;
4024 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4026 case ISD::SINT_TO_FP:
4027 case ISD::UINT_TO_FP:
4028 return true;
4029 case ISD::FMA:
4030 case ISD::FMAD: {
4031 if (SNaN)
4032 return true;
4033 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4034 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4035 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4037 case ISD::FSQRT: // Need is known positive
4038 case ISD::FLOG:
4039 case ISD::FLOG2:
4040 case ISD::FLOG10:
4041 case ISD::FPOWI:
4042 case ISD::FPOW: {
4043 if (SNaN)
4044 return true;
4045 // TODO: Refine on operand
4046 return false;
4048 case ISD::FMINNUM:
4049 case ISD::FMAXNUM: {
4050 // Only one needs to be known not-nan, since it will be returned if the
4051 // other ends up being one.
4052 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4053 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4055 case ISD::FMINNUM_IEEE:
4056 case ISD::FMAXNUM_IEEE: {
4057 if (SNaN)
4058 return true;
4059 // This can return a NaN if either operand is an sNaN, or if both operands
4060 // are NaN.
4061 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4062 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4063 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4064 isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4066 case ISD::FMINIMUM:
4067 case ISD::FMAXIMUM: {
4068 // TODO: Does this quiet or return the origina NaN as-is?
4069 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4070 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4072 case ISD::EXTRACT_VECTOR_ELT: {
4073 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4075 default:
4076 if (Opcode >= ISD::BUILTIN_OP_END ||
4077 Opcode == ISD::INTRINSIC_WO_CHAIN ||
4078 Opcode == ISD::INTRINSIC_W_CHAIN ||
4079 Opcode == ISD::INTRINSIC_VOID) {
4080 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4083 return false;
4087 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4088 assert(Op.getValueType().isFloatingPoint() &&
4089 "Floating point type expected");
4091 // If the value is a constant, we can obviously see if it is a zero or not.
4092 // TODO: Add BuildVector support.
4093 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4094 return !C->isZero();
4095 return false;
4098 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4099 assert(!Op.getValueType().isFloatingPoint() &&
4100 "Floating point types unsupported - use isKnownNeverZeroFloat");
4102 // If the value is a constant, we can obviously see if it is a zero or not.
4103 if (ISD::matchUnaryPredicate(
4104 Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
4105 return true;
4107 // TODO: Recognize more cases here.
4108 switch (Op.getOpcode()) {
4109 default: break;
4110 case ISD::OR:
4111 if (isKnownNeverZero(Op.getOperand(1)) ||
4112 isKnownNeverZero(Op.getOperand(0)))
4113 return true;
4114 break;
4117 return false;
4120 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4121 // Check the obvious case.
4122 if (A == B) return true;
4124 // For for negative and positive zero.
4125 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4126 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4127 if (CA->isZero() && CB->isZero()) return true;
4129 // Otherwise they may not be equal.
4130 return false;
4133 // FIXME: unify with llvm::haveNoCommonBitsSet.
4134 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4135 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4136 assert(A.getValueType() == B.getValueType() &&
4137 "Values must have the same type");
4138 return (computeKnownBits(A).Zero | computeKnownBits(B).Zero).isAllOnesValue();
4141 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4142 ArrayRef<SDValue> Ops,
4143 SelectionDAG &DAG) {
4144 int NumOps = Ops.size();
4145 assert(NumOps != 0 && "Can't build an empty vector!");
4146 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4147 "Incorrect element count in BUILD_VECTOR!");
4149 // BUILD_VECTOR of UNDEFs is UNDEF.
4150 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4151 return DAG.getUNDEF(VT);
4153 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4154 SDValue IdentitySrc;
4155 bool IsIdentity = true;
4156 for (int i = 0; i != NumOps; ++i) {
4157 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4158 Ops[i].getOperand(0).getValueType() != VT ||
4159 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4160 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4161 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4162 IsIdentity = false;
4163 break;
4165 IdentitySrc = Ops[i].getOperand(0);
4167 if (IsIdentity)
4168 return IdentitySrc;
4170 return SDValue();
4173 /// Try to simplify vector concatenation to an input value, undef, or build
4174 /// vector.
4175 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4176 ArrayRef<SDValue> Ops,
4177 SelectionDAG &DAG) {
4178 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4179 assert(llvm::all_of(Ops,
4180 [Ops](SDValue Op) {
4181 return Ops[0].getValueType() == Op.getValueType();
4182 }) &&
4183 "Concatenation of vectors with inconsistent value types!");
4184 assert((Ops.size() * Ops[0].getValueType().getVectorNumElements()) ==
4185 VT.getVectorNumElements() &&
4186 "Incorrect element count in vector concatenation!");
4188 if (Ops.size() == 1)
4189 return Ops[0];
4191 // Concat of UNDEFs is UNDEF.
4192 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4193 return DAG.getUNDEF(VT);
4195 // Scan the operands and look for extract operations from a single source
4196 // that correspond to insertion at the same location via this concatenation:
4197 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4198 SDValue IdentitySrc;
4199 bool IsIdentity = true;
4200 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4201 SDValue Op = Ops[i];
4202 unsigned IdentityIndex = i * Op.getValueType().getVectorNumElements();
4203 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4204 Op.getOperand(0).getValueType() != VT ||
4205 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4206 !isa<ConstantSDNode>(Op.getOperand(1)) ||
4207 Op.getConstantOperandVal(1) != IdentityIndex) {
4208 IsIdentity = false;
4209 break;
4211 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4212 "Unexpected identity source vector for concat of extracts");
4213 IdentitySrc = Op.getOperand(0);
4215 if (IsIdentity) {
4216 assert(IdentitySrc && "Failed to set source vector of extracts");
4217 return IdentitySrc;
4220 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4221 // simplified to one big BUILD_VECTOR.
4222 // FIXME: Add support for SCALAR_TO_VECTOR as well.
4223 EVT SVT = VT.getScalarType();
4224 SmallVector<SDValue, 16> Elts;
4225 for (SDValue Op : Ops) {
4226 EVT OpVT = Op.getValueType();
4227 if (Op.isUndef())
4228 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4229 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4230 Elts.append(Op->op_begin(), Op->op_end());
4231 else
4232 return SDValue();
4235 // BUILD_VECTOR requires all inputs to be of the same type, find the
4236 // maximum type and extend them all.
4237 for (SDValue Op : Elts)
4238 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4240 if (SVT.bitsGT(VT.getScalarType()))
4241 for (SDValue &Op : Elts)
4242 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4243 ? DAG.getZExtOrTrunc(Op, DL, SVT)
4244 : DAG.getSExtOrTrunc(Op, DL, SVT);
4246 SDValue V = DAG.getBuildVector(VT, DL, Elts);
4247 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4248 return V;
4251 /// Gets or creates the specified node.
4252 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4253 FoldingSetNodeID ID;
4254 AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4255 void *IP = nullptr;
4256 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4257 return SDValue(E, 0);
4259 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4260 getVTList(VT));
4261 CSEMap.InsertNode(N, IP);
4263 InsertNode(N);
4264 SDValue V = SDValue(N, 0);
4265 NewSDValueDbgMsg(V, "Creating new node: ", this);
4266 return V;
4269 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4270 SDValue Operand, const SDNodeFlags Flags) {
4271 // Constant fold unary operations with an integer constant operand. Even
4272 // opaque constant will be folded, because the folding of unary operations
4273 // doesn't create new constants with different values. Nevertheless, the
4274 // opaque flag is preserved during folding to prevent future folding with
4275 // other constants.
4276 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4277 const APInt &Val = C->getAPIntValue();
4278 switch (Opcode) {
4279 default: break;
4280 case ISD::SIGN_EXTEND:
4281 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4282 C->isTargetOpcode(), C->isOpaque());
4283 case ISD::TRUNCATE:
4284 if (C->isOpaque())
4285 break;
4286 LLVM_FALLTHROUGH;
4287 case ISD::ANY_EXTEND:
4288 case ISD::ZERO_EXTEND:
4289 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4290 C->isTargetOpcode(), C->isOpaque());
4291 case ISD::UINT_TO_FP:
4292 case ISD::SINT_TO_FP: {
4293 APFloat apf(EVTToAPFloatSemantics(VT),
4294 APInt::getNullValue(VT.getSizeInBits()));
4295 (void)apf.convertFromAPInt(Val,
4296 Opcode==ISD::SINT_TO_FP,
4297 APFloat::rmNearestTiesToEven);
4298 return getConstantFP(apf, DL, VT);
4300 case ISD::BITCAST:
4301 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4302 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4303 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4304 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4305 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4306 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4307 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4308 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4309 break;
4310 case ISD::ABS:
4311 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4312 C->isOpaque());
4313 case ISD::BITREVERSE:
4314 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4315 C->isOpaque());
4316 case ISD::BSWAP:
4317 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4318 C->isOpaque());
4319 case ISD::CTPOP:
4320 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4321 C->isOpaque());
4322 case ISD::CTLZ:
4323 case ISD::CTLZ_ZERO_UNDEF:
4324 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4325 C->isOpaque());
4326 case ISD::CTTZ:
4327 case ISD::CTTZ_ZERO_UNDEF:
4328 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4329 C->isOpaque());
4330 case ISD::FP16_TO_FP: {
4331 bool Ignored;
4332 APFloat FPV(APFloat::IEEEhalf(),
4333 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4335 // This can return overflow, underflow, or inexact; we don't care.
4336 // FIXME need to be more flexible about rounding mode.
4337 (void)FPV.convert(EVTToAPFloatSemantics(VT),
4338 APFloat::rmNearestTiesToEven, &Ignored);
4339 return getConstantFP(FPV, DL, VT);
4344 // Constant fold unary operations with a floating point constant operand.
4345 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4346 APFloat V = C->getValueAPF(); // make copy
4347 switch (Opcode) {
4348 case ISD::FNEG:
4349 V.changeSign();
4350 return getConstantFP(V, DL, VT);
4351 case ISD::FABS:
4352 V.clearSign();
4353 return getConstantFP(V, DL, VT);
4354 case ISD::FCEIL: {
4355 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4356 if (fs == APFloat::opOK || fs == APFloat::opInexact)
4357 return getConstantFP(V, DL, VT);
4358 break;
4360 case ISD::FTRUNC: {
4361 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4362 if (fs == APFloat::opOK || fs == APFloat::opInexact)
4363 return getConstantFP(V, DL, VT);
4364 break;
4366 case ISD::FFLOOR: {
4367 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4368 if (fs == APFloat::opOK || fs == APFloat::opInexact)
4369 return getConstantFP(V, DL, VT);
4370 break;
4372 case ISD::FP_EXTEND: {
4373 bool ignored;
4374 // This can return overflow, underflow, or inexact; we don't care.
4375 // FIXME need to be more flexible about rounding mode.
4376 (void)V.convert(EVTToAPFloatSemantics(VT),
4377 APFloat::rmNearestTiesToEven, &ignored);
4378 return getConstantFP(V, DL, VT);
4380 case ISD::FP_TO_SINT:
4381 case ISD::FP_TO_UINT: {
4382 bool ignored;
4383 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4384 // FIXME need to be more flexible about rounding mode.
4385 APFloat::opStatus s =
4386 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4387 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4388 break;
4389 return getConstant(IntVal, DL, VT);
4391 case ISD::BITCAST:
4392 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4393 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4394 else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4395 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4396 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4397 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4398 break;
4399 case ISD::FP_TO_FP16: {
4400 bool Ignored;
4401 // This can return overflow, underflow, or inexact; we don't care.
4402 // FIXME need to be more flexible about rounding mode.
4403 (void)V.convert(APFloat::IEEEhalf(),
4404 APFloat::rmNearestTiesToEven, &Ignored);
4405 return getConstant(V.bitcastToAPInt(), DL, VT);
4410 // Constant fold unary operations with a vector integer or float operand.
4411 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
4412 if (BV->isConstant()) {
4413 switch (Opcode) {
4414 default:
4415 // FIXME: Entirely reasonable to perform folding of other unary
4416 // operations here as the need arises.
4417 break;
4418 case ISD::FNEG:
4419 case ISD::FABS:
4420 case ISD::FCEIL:
4421 case ISD::FTRUNC:
4422 case ISD::FFLOOR:
4423 case ISD::FP_EXTEND:
4424 case ISD::FP_TO_SINT:
4425 case ISD::FP_TO_UINT:
4426 case ISD::TRUNCATE:
4427 case ISD::ANY_EXTEND:
4428 case ISD::ZERO_EXTEND:
4429 case ISD::SIGN_EXTEND:
4430 case ISD::UINT_TO_FP:
4431 case ISD::SINT_TO_FP:
4432 case ISD::ABS:
4433 case ISD::BITREVERSE:
4434 case ISD::BSWAP:
4435 case ISD::CTLZ:
4436 case ISD::CTLZ_ZERO_UNDEF:
4437 case ISD::CTTZ:
4438 case ISD::CTTZ_ZERO_UNDEF:
4439 case ISD::CTPOP: {
4440 SDValue Ops = { Operand };
4441 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4442 return Fold;
4448 unsigned OpOpcode = Operand.getNode()->getOpcode();
4449 switch (Opcode) {
4450 case ISD::TokenFactor:
4451 case ISD::MERGE_VALUES:
4452 case ISD::CONCAT_VECTORS:
4453 return Operand; // Factor, merge or concat of one node? No need.
4454 case ISD::BUILD_VECTOR: {
4455 // Attempt to simplify BUILD_VECTOR.
4456 SDValue Ops[] = {Operand};
4457 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4458 return V;
4459 break;
4461 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4462 case ISD::FP_EXTEND:
4463 assert(VT.isFloatingPoint() &&
4464 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4465 if (Operand.getValueType() == VT) return Operand; // noop conversion.
4466 assert((!VT.isVector() ||
4467 VT.getVectorNumElements() ==
4468 Operand.getValueType().getVectorNumElements()) &&
4469 "Vector element count mismatch!");
4470 assert(Operand.getValueType().bitsLT(VT) &&
4471 "Invalid fpext node, dst < src!");
4472 if (Operand.isUndef())
4473 return getUNDEF(VT);
4474 break;
4475 case ISD::FP_TO_SINT:
4476 case ISD::FP_TO_UINT:
4477 if (Operand.isUndef())
4478 return getUNDEF(VT);
4479 break;
4480 case ISD::SINT_TO_FP:
4481 case ISD::UINT_TO_FP:
4482 // [us]itofp(undef) = 0, because the result value is bounded.
4483 if (Operand.isUndef())
4484 return getConstantFP(0.0, DL, VT);
4485 break;
4486 case ISD::SIGN_EXTEND:
4487 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4488 "Invalid SIGN_EXTEND!");
4489 assert(VT.isVector() == Operand.getValueType().isVector() &&
4490 "SIGN_EXTEND result type type should be vector iff the operand "
4491 "type is vector!");
4492 if (Operand.getValueType() == VT) return Operand; // noop extension
4493 assert((!VT.isVector() ||
4494 VT.getVectorNumElements() ==
4495 Operand.getValueType().getVectorNumElements()) &&
4496 "Vector element count mismatch!");
4497 assert(Operand.getValueType().bitsLT(VT) &&
4498 "Invalid sext node, dst < src!");
4499 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4500 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4501 else if (OpOpcode == ISD::UNDEF)
4502 // sext(undef) = 0, because the top bits will all be the same.
4503 return getConstant(0, DL, VT);
4504 break;
4505 case ISD::ZERO_EXTEND:
4506 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4507 "Invalid ZERO_EXTEND!");
4508 assert(VT.isVector() == Operand.getValueType().isVector() &&
4509 "ZERO_EXTEND result type type should be vector iff the operand "
4510 "type is vector!");
4511 if (Operand.getValueType() == VT) return Operand; // noop extension
4512 assert((!VT.isVector() ||
4513 VT.getVectorNumElements() ==
4514 Operand.getValueType().getVectorNumElements()) &&
4515 "Vector element count mismatch!");
4516 assert(Operand.getValueType().bitsLT(VT) &&
4517 "Invalid zext node, dst < src!");
4518 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
4519 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4520 else if (OpOpcode == ISD::UNDEF)
4521 // zext(undef) = 0, because the top bits will be zero.
4522 return getConstant(0, DL, VT);
4523 break;
4524 case ISD::ANY_EXTEND:
4525 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4526 "Invalid ANY_EXTEND!");
4527 assert(VT.isVector() == Operand.getValueType().isVector() &&
4528 "ANY_EXTEND result type type should be vector iff the operand "
4529 "type is vector!");
4530 if (Operand.getValueType() == VT) return Operand; // noop extension
4531 assert((!VT.isVector() ||
4532 VT.getVectorNumElements() ==
4533 Operand.getValueType().getVectorNumElements()) &&
4534 "Vector element count mismatch!");
4535 assert(Operand.getValueType().bitsLT(VT) &&
4536 "Invalid anyext node, dst < src!");
4538 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4539 OpOpcode == ISD::ANY_EXTEND)
4540 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
4541 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4542 else if (OpOpcode == ISD::UNDEF)
4543 return getUNDEF(VT);
4545 // (ext (trunc x)) -> x
4546 if (OpOpcode == ISD::TRUNCATE) {
4547 SDValue OpOp = Operand.getOperand(0);
4548 if (OpOp.getValueType() == VT) {
4549 transferDbgValues(Operand, OpOp);
4550 return OpOp;
4553 break;
4554 case ISD::TRUNCATE:
4555 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4556 "Invalid TRUNCATE!");
4557 assert(VT.isVector() == Operand.getValueType().isVector() &&
4558 "TRUNCATE result type type should be vector iff the operand "
4559 "type is vector!");
4560 if (Operand.getValueType() == VT) return Operand; // noop truncate
4561 assert((!VT.isVector() ||
4562 VT.getVectorNumElements() ==
4563 Operand.getValueType().getVectorNumElements()) &&
4564 "Vector element count mismatch!");
4565 assert(Operand.getValueType().bitsGT(VT) &&
4566 "Invalid truncate node, src < dst!");
4567 if (OpOpcode == ISD::TRUNCATE)
4568 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4569 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4570 OpOpcode == ISD::ANY_EXTEND) {
4571 // If the source is smaller than the dest, we still need an extend.
4572 if (Operand.getOperand(0).getValueType().getScalarType()
4573 .bitsLT(VT.getScalarType()))
4574 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4575 if (Operand.getOperand(0).getValueType().bitsGT(VT))
4576 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4577 return Operand.getOperand(0);
4579 if (OpOpcode == ISD::UNDEF)
4580 return getUNDEF(VT);
4581 break;
4582 case ISD::ANY_EXTEND_VECTOR_INREG:
4583 case ISD::ZERO_EXTEND_VECTOR_INREG:
4584 case ISD::SIGN_EXTEND_VECTOR_INREG:
4585 assert(VT.isVector() && "This DAG node is restricted to vector types.");
4586 assert(Operand.getValueType().bitsLE(VT) &&
4587 "The input must be the same size or smaller than the result.");
4588 assert(VT.getVectorNumElements() <
4589 Operand.getValueType().getVectorNumElements() &&
4590 "The destination vector type must have fewer lanes than the input.");
4591 break;
4592 case ISD::ABS:
4593 assert(VT.isInteger() && VT == Operand.getValueType() &&
4594 "Invalid ABS!");
4595 if (OpOpcode == ISD::UNDEF)
4596 return getUNDEF(VT);
4597 break;
4598 case ISD::BSWAP:
4599 assert(VT.isInteger() && VT == Operand.getValueType() &&
4600 "Invalid BSWAP!");
4601 assert((VT.getScalarSizeInBits() % 16 == 0) &&
4602 "BSWAP types must be a multiple of 16 bits!");
4603 if (OpOpcode == ISD::UNDEF)
4604 return getUNDEF(VT);
4605 break;
4606 case ISD::BITREVERSE:
4607 assert(VT.isInteger() && VT == Operand.getValueType() &&
4608 "Invalid BITREVERSE!");
4609 if (OpOpcode == ISD::UNDEF)
4610 return getUNDEF(VT);
4611 break;
4612 case ISD::BITCAST:
4613 // Basic sanity checking.
4614 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
4615 "Cannot BITCAST between types of different sizes!");
4616 if (VT == Operand.getValueType()) return Operand; // noop conversion.
4617 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
4618 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
4619 if (OpOpcode == ISD::UNDEF)
4620 return getUNDEF(VT);
4621 break;
4622 case ISD::SCALAR_TO_VECTOR:
4623 assert(VT.isVector() && !Operand.getValueType().isVector() &&
4624 (VT.getVectorElementType() == Operand.getValueType() ||
4625 (VT.getVectorElementType().isInteger() &&
4626 Operand.getValueType().isInteger() &&
4627 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
4628 "Illegal SCALAR_TO_VECTOR node!");
4629 if (OpOpcode == ISD::UNDEF)
4630 return getUNDEF(VT);
4631 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
4632 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
4633 isa<ConstantSDNode>(Operand.getOperand(1)) &&
4634 Operand.getConstantOperandVal(1) == 0 &&
4635 Operand.getOperand(0).getValueType() == VT)
4636 return Operand.getOperand(0);
4637 break;
4638 case ISD::FNEG:
4639 // Negation of an unknown bag of bits is still completely undefined.
4640 if (OpOpcode == ISD::UNDEF)
4641 return getUNDEF(VT);
4643 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
4644 if ((getTarget().Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros()) &&
4645 OpOpcode == ISD::FSUB)
4646 return getNode(ISD::FSUB, DL, VT, Operand.getOperand(1),
4647 Operand.getOperand(0), Flags);
4648 if (OpOpcode == ISD::FNEG) // --X -> X
4649 return Operand.getOperand(0);
4650 break;
4651 case ISD::FABS:
4652 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
4653 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
4654 break;
4657 SDNode *N;
4658 SDVTList VTs = getVTList(VT);
4659 SDValue Ops[] = {Operand};
4660 if (VT != MVT::Glue) { // Don't CSE flag producing nodes
4661 FoldingSetNodeID ID;
4662 AddNodeIDNode(ID, Opcode, VTs, Ops);
4663 void *IP = nullptr;
4664 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4665 E->intersectFlagsWith(Flags);
4666 return SDValue(E, 0);
4669 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4670 N->setFlags(Flags);
4671 createOperands(N, Ops);
4672 CSEMap.InsertNode(N, IP);
4673 } else {
4674 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4675 createOperands(N, Ops);
4678 InsertNode(N);
4679 SDValue V = SDValue(N, 0);
4680 NewSDValueDbgMsg(V, "Creating new node: ", this);
4681 return V;
4684 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1,
4685 const APInt &C2) {
4686 switch (Opcode) {
4687 case ISD::ADD: return std::make_pair(C1 + C2, true);
4688 case ISD::SUB: return std::make_pair(C1 - C2, true);
4689 case ISD::MUL: return std::make_pair(C1 * C2, true);
4690 case ISD::AND: return std::make_pair(C1 & C2, true);
4691 case ISD::OR: return std::make_pair(C1 | C2, true);
4692 case ISD::XOR: return std::make_pair(C1 ^ C2, true);
4693 case ISD::SHL: return std::make_pair(C1 << C2, true);
4694 case ISD::SRL: return std::make_pair(C1.lshr(C2), true);
4695 case ISD::SRA: return std::make_pair(C1.ashr(C2), true);
4696 case ISD::ROTL: return std::make_pair(C1.rotl(C2), true);
4697 case ISD::ROTR: return std::make_pair(C1.rotr(C2), true);
4698 case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true);
4699 case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true);
4700 case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true);
4701 case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true);
4702 case ISD::SADDSAT: return std::make_pair(C1.sadd_sat(C2), true);
4703 case ISD::UADDSAT: return std::make_pair(C1.uadd_sat(C2), true);
4704 case ISD::SSUBSAT: return std::make_pair(C1.ssub_sat(C2), true);
4705 case ISD::USUBSAT: return std::make_pair(C1.usub_sat(C2), true);
4706 case ISD::UDIV:
4707 if (!C2.getBoolValue())
4708 break;
4709 return std::make_pair(C1.udiv(C2), true);
4710 case ISD::UREM:
4711 if (!C2.getBoolValue())
4712 break;
4713 return std::make_pair(C1.urem(C2), true);
4714 case ISD::SDIV:
4715 if (!C2.getBoolValue())
4716 break;
4717 return std::make_pair(C1.sdiv(C2), true);
4718 case ISD::SREM:
4719 if (!C2.getBoolValue())
4720 break;
4721 return std::make_pair(C1.srem(C2), true);
4723 return std::make_pair(APInt(1, 0), false);
4726 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
4727 EVT VT, const ConstantSDNode *C1,
4728 const ConstantSDNode *C2) {
4729 if (C1->isOpaque() || C2->isOpaque())
4730 return SDValue();
4732 std::pair<APInt, bool> Folded = FoldValue(Opcode, C1->getAPIntValue(),
4733 C2->getAPIntValue());
4734 if (!Folded.second)
4735 return SDValue();
4736 return getConstant(Folded.first, DL, VT);
4739 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
4740 const GlobalAddressSDNode *GA,
4741 const SDNode *N2) {
4742 if (GA->getOpcode() != ISD::GlobalAddress)
4743 return SDValue();
4744 if (!TLI->isOffsetFoldingLegal(GA))
4745 return SDValue();
4746 auto *C2 = dyn_cast<ConstantSDNode>(N2);
4747 if (!C2)
4748 return SDValue();
4749 int64_t Offset = C2->getSExtValue();
4750 switch (Opcode) {
4751 case ISD::ADD: break;
4752 case ISD::SUB: Offset = -uint64_t(Offset); break;
4753 default: return SDValue();
4755 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
4756 GA->getOffset() + uint64_t(Offset));
4759 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
4760 switch (Opcode) {
4761 case ISD::SDIV:
4762 case ISD::UDIV:
4763 case ISD::SREM:
4764 case ISD::UREM: {
4765 // If a divisor is zero/undef or any element of a divisor vector is
4766 // zero/undef, the whole op is undef.
4767 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
4768 SDValue Divisor = Ops[1];
4769 if (Divisor.isUndef() || isNullConstant(Divisor))
4770 return true;
4772 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
4773 llvm::any_of(Divisor->op_values(),
4774 [](SDValue V) { return V.isUndef() ||
4775 isNullConstant(V); });
4776 // TODO: Handle signed overflow.
4778 // TODO: Handle oversized shifts.
4779 default:
4780 return false;
4784 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
4785 EVT VT, SDNode *N1, SDNode *N2) {
4786 // If the opcode is a target-specific ISD node, there's nothing we can
4787 // do here and the operand rules may not line up with the below, so
4788 // bail early.
4789 if (Opcode >= ISD::BUILTIN_OP_END)
4790 return SDValue();
4792 if (isUndef(Opcode, {SDValue(N1, 0), SDValue(N2, 0)}))
4793 return getUNDEF(VT);
4795 // Handle the case of two scalars.
4796 if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
4797 if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) {
4798 SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, C1, C2);
4799 assert((!Folded || !VT.isVector()) &&
4800 "Can't fold vectors ops with scalar operands");
4801 return Folded;
4805 // fold (add Sym, c) -> Sym+c
4806 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1))
4807 return FoldSymbolOffset(Opcode, VT, GA, N2);
4808 if (TLI->isCommutativeBinOp(Opcode))
4809 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2))
4810 return FoldSymbolOffset(Opcode, VT, GA, N1);
4812 // For vectors, extract each constant element and fold them individually.
4813 // Either input may be an undef value.
4814 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
4815 if (!BV1 && !N1->isUndef())
4816 return SDValue();
4817 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
4818 if (!BV2 && !N2->isUndef())
4819 return SDValue();
4820 // If both operands are undef, that's handled the same way as scalars.
4821 if (!BV1 && !BV2)
4822 return SDValue();
4824 assert((!BV1 || !BV2 || BV1->getNumOperands() == BV2->getNumOperands()) &&
4825 "Vector binop with different number of elements in operands?");
4827 EVT SVT = VT.getScalarType();
4828 EVT LegalSVT = SVT;
4829 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
4830 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
4831 if (LegalSVT.bitsLT(SVT))
4832 return SDValue();
4834 SmallVector<SDValue, 4> Outputs;
4835 unsigned NumOps = BV1 ? BV1->getNumOperands() : BV2->getNumOperands();
4836 for (unsigned I = 0; I != NumOps; ++I) {
4837 SDValue V1 = BV1 ? BV1->getOperand(I) : getUNDEF(SVT);
4838 SDValue V2 = BV2 ? BV2->getOperand(I) : getUNDEF(SVT);
4839 if (SVT.isInteger()) {
4840 if (V1->getValueType(0).bitsGT(SVT))
4841 V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
4842 if (V2->getValueType(0).bitsGT(SVT))
4843 V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
4846 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
4847 return SDValue();
4849 // Fold one vector element.
4850 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
4851 if (LegalSVT != SVT)
4852 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
4854 // Scalar folding only succeeded if the result is a constant or UNDEF.
4855 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
4856 ScalarResult.getOpcode() != ISD::ConstantFP)
4857 return SDValue();
4858 Outputs.push_back(ScalarResult);
4861 assert(VT.getVectorNumElements() == Outputs.size() &&
4862 "Vector size mismatch!");
4864 // We may have a vector type but a scalar result. Create a splat.
4865 Outputs.resize(VT.getVectorNumElements(), Outputs.back());
4867 // Build a big vector out of the scalar elements we generated.
4868 return getBuildVector(VT, SDLoc(), Outputs);
4871 // TODO: Merge with FoldConstantArithmetic
4872 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
4873 const SDLoc &DL, EVT VT,
4874 ArrayRef<SDValue> Ops,
4875 const SDNodeFlags Flags) {
4876 // If the opcode is a target-specific ISD node, there's nothing we can
4877 // do here and the operand rules may not line up with the below, so
4878 // bail early.
4879 if (Opcode >= ISD::BUILTIN_OP_END)
4880 return SDValue();
4882 if (isUndef(Opcode, Ops))
4883 return getUNDEF(VT);
4885 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
4886 if (!VT.isVector())
4887 return SDValue();
4889 unsigned NumElts = VT.getVectorNumElements();
4891 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
4892 return !Op.getValueType().isVector() ||
4893 Op.getValueType().getVectorNumElements() == NumElts;
4896 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
4897 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
4898 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
4899 (BV && BV->isConstant());
4902 // All operands must be vector types with the same number of elements as
4903 // the result type and must be either UNDEF or a build vector of constant
4904 // or UNDEF scalars.
4905 if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
4906 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
4907 return SDValue();
4909 // If we are comparing vectors, then the result needs to be a i1 boolean
4910 // that is then sign-extended back to the legal result type.
4911 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
4913 // Find legal integer scalar type for constant promotion and
4914 // ensure that its scalar size is at least as large as source.
4915 EVT LegalSVT = VT.getScalarType();
4916 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
4917 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
4918 if (LegalSVT.bitsLT(VT.getScalarType()))
4919 return SDValue();
4922 // Constant fold each scalar lane separately.
4923 SmallVector<SDValue, 4> ScalarResults;
4924 for (unsigned i = 0; i != NumElts; i++) {
4925 SmallVector<SDValue, 4> ScalarOps;
4926 for (SDValue Op : Ops) {
4927 EVT InSVT = Op.getValueType().getScalarType();
4928 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
4929 if (!InBV) {
4930 // We've checked that this is UNDEF or a constant of some kind.
4931 if (Op.isUndef())
4932 ScalarOps.push_back(getUNDEF(InSVT));
4933 else
4934 ScalarOps.push_back(Op);
4935 continue;
4938 SDValue ScalarOp = InBV->getOperand(i);
4939 EVT ScalarVT = ScalarOp.getValueType();
4941 // Build vector (integer) scalar operands may need implicit
4942 // truncation - do this before constant folding.
4943 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
4944 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
4946 ScalarOps.push_back(ScalarOp);
4949 // Constant fold the scalar operands.
4950 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
4952 // Legalize the (integer) scalar constant if necessary.
4953 if (LegalSVT != SVT)
4954 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
4956 // Scalar folding only succeeded if the result is a constant or UNDEF.
4957 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
4958 ScalarResult.getOpcode() != ISD::ConstantFP)
4959 return SDValue();
4960 ScalarResults.push_back(ScalarResult);
4963 SDValue V = getBuildVector(VT, DL, ScalarResults);
4964 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
4965 return V;
4968 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
4969 EVT VT, SDValue N1, SDValue N2) {
4970 // TODO: We don't do any constant folding for strict FP opcodes here, but we
4971 // should. That will require dealing with a potentially non-default
4972 // rounding mode, checking the "opStatus" return value from the APFloat
4973 // math calculations, and possibly other variations.
4974 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
4975 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
4976 if (N1CFP && N2CFP) {
4977 APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
4978 switch (Opcode) {
4979 case ISD::FADD:
4980 C1.add(C2, APFloat::rmNearestTiesToEven);
4981 return getConstantFP(C1, DL, VT);
4982 case ISD::FSUB:
4983 C1.subtract(C2, APFloat::rmNearestTiesToEven);
4984 return getConstantFP(C1, DL, VT);
4985 case ISD::FMUL:
4986 C1.multiply(C2, APFloat::rmNearestTiesToEven);
4987 return getConstantFP(C1, DL, VT);
4988 case ISD::FDIV:
4989 C1.divide(C2, APFloat::rmNearestTiesToEven);
4990 return getConstantFP(C1, DL, VT);
4991 case ISD::FREM:
4992 C1.mod(C2);
4993 return getConstantFP(C1, DL, VT);
4994 case ISD::FCOPYSIGN:
4995 C1.copySign(C2);
4996 return getConstantFP(C1, DL, VT);
4997 default: break;
5000 if (N1CFP && Opcode == ISD::FP_ROUND) {
5001 APFloat C1 = N1CFP->getValueAPF(); // make copy
5002 bool Unused;
5003 // This can return overflow, underflow, or inexact; we don't care.
5004 // FIXME need to be more flexible about rounding mode.
5005 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5006 &Unused);
5007 return getConstantFP(C1, DL, VT);
5010 switch (Opcode) {
5011 case ISD::FADD:
5012 case ISD::FSUB:
5013 case ISD::FMUL:
5014 case ISD::FDIV:
5015 case ISD::FREM:
5016 // If both operands are undef, the result is undef. If 1 operand is undef,
5017 // the result is NaN. This should match the behavior of the IR optimizer.
5018 if (N1.isUndef() && N2.isUndef())
5019 return getUNDEF(VT);
5020 if (N1.isUndef() || N2.isUndef())
5021 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5023 return SDValue();
5026 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5027 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5028 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5029 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5030 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5031 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5033 // Canonicalize constant to RHS if commutative.
5034 if (TLI->isCommutativeBinOp(Opcode)) {
5035 if (N1C && !N2C) {
5036 std::swap(N1C, N2C);
5037 std::swap(N1, N2);
5038 } else if (N1CFP && !N2CFP) {
5039 std::swap(N1CFP, N2CFP);
5040 std::swap(N1, N2);
5044 switch (Opcode) {
5045 default: break;
5046 case ISD::TokenFactor:
5047 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5048 N2.getValueType() == MVT::Other && "Invalid token factor!");
5049 // Fold trivial token factors.
5050 if (N1.getOpcode() == ISD::EntryToken) return N2;
5051 if (N2.getOpcode() == ISD::EntryToken) return N1;
5052 if (N1 == N2) return N1;
5053 break;
5054 case ISD::BUILD_VECTOR: {
5055 // Attempt to simplify BUILD_VECTOR.
5056 SDValue Ops[] = {N1, N2};
5057 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5058 return V;
5059 break;
5061 case ISD::CONCAT_VECTORS: {
5062 SDValue Ops[] = {N1, N2};
5063 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5064 return V;
5065 break;
5067 case ISD::AND:
5068 assert(VT.isInteger() && "This operator does not apply to FP types!");
5069 assert(N1.getValueType() == N2.getValueType() &&
5070 N1.getValueType() == VT && "Binary operator types must match!");
5071 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
5072 // worth handling here.
5073 if (N2C && N2C->isNullValue())
5074 return N2;
5075 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
5076 return N1;
5077 break;
5078 case ISD::OR:
5079 case ISD::XOR:
5080 case ISD::ADD:
5081 case ISD::SUB:
5082 assert(VT.isInteger() && "This operator does not apply to FP types!");
5083 assert(N1.getValueType() == N2.getValueType() &&
5084 N1.getValueType() == VT && "Binary operator types must match!");
5085 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
5086 // it's worth handling here.
5087 if (N2C && N2C->isNullValue())
5088 return N1;
5089 break;
5090 case ISD::UDIV:
5091 case ISD::UREM:
5092 case ISD::MULHU:
5093 case ISD::MULHS:
5094 case ISD::MUL:
5095 case ISD::SDIV:
5096 case ISD::SREM:
5097 case ISD::SMIN:
5098 case ISD::SMAX:
5099 case ISD::UMIN:
5100 case ISD::UMAX:
5101 case ISD::SADDSAT:
5102 case ISD::SSUBSAT:
5103 case ISD::UADDSAT:
5104 case ISD::USUBSAT:
5105 assert(VT.isInteger() && "This operator does not apply to FP types!");
5106 assert(N1.getValueType() == N2.getValueType() &&
5107 N1.getValueType() == VT && "Binary operator types must match!");
5108 break;
5109 case ISD::FADD:
5110 case ISD::FSUB:
5111 case ISD::FMUL:
5112 case ISD::FDIV:
5113 case ISD::FREM:
5114 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5115 assert(N1.getValueType() == N2.getValueType() &&
5116 N1.getValueType() == VT && "Binary operator types must match!");
5117 if (SDValue V = simplifyFPBinop(Opcode, N1, N2))
5118 return V;
5119 break;
5120 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
5121 assert(N1.getValueType() == VT &&
5122 N1.getValueType().isFloatingPoint() &&
5123 N2.getValueType().isFloatingPoint() &&
5124 "Invalid FCOPYSIGN!");
5125 break;
5126 case ISD::SHL:
5127 case ISD::SRA:
5128 case ISD::SRL:
5129 if (SDValue V = simplifyShift(N1, N2))
5130 return V;
5131 LLVM_FALLTHROUGH;
5132 case ISD::ROTL:
5133 case ISD::ROTR:
5134 assert(VT == N1.getValueType() &&
5135 "Shift operators return type must be the same as their first arg");
5136 assert(VT.isInteger() && N2.getValueType().isInteger() &&
5137 "Shifts only work on integers");
5138 assert((!VT.isVector() || VT == N2.getValueType()) &&
5139 "Vector shift amounts must be in the same as their first arg");
5140 // Verify that the shift amount VT is big enough to hold valid shift
5141 // amounts. This catches things like trying to shift an i1024 value by an
5142 // i8, which is easy to fall into in generic code that uses
5143 // TLI.getShiftAmount().
5144 assert(N2.getValueSizeInBits() >= Log2_32_Ceil(N1.getValueSizeInBits()) &&
5145 "Invalid use of small shift amount with oversized value!");
5147 // Always fold shifts of i1 values so the code generator doesn't need to
5148 // handle them. Since we know the size of the shift has to be less than the
5149 // size of the value, the shift/rotate count is guaranteed to be zero.
5150 if (VT == MVT::i1)
5151 return N1;
5152 if (N2C && N2C->isNullValue())
5153 return N1;
5154 break;
5155 case ISD::FP_ROUND:
5156 assert(VT.isFloatingPoint() &&
5157 N1.getValueType().isFloatingPoint() &&
5158 VT.bitsLE(N1.getValueType()) &&
5159 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5160 "Invalid FP_ROUND!");
5161 if (N1.getValueType() == VT) return N1; // noop conversion.
5162 break;
5163 case ISD::AssertSext:
5164 case ISD::AssertZext: {
5165 EVT EVT = cast<VTSDNode>(N2)->getVT();
5166 assert(VT == N1.getValueType() && "Not an inreg extend!");
5167 assert(VT.isInteger() && EVT.isInteger() &&
5168 "Cannot *_EXTEND_INREG FP types");
5169 assert(!EVT.isVector() &&
5170 "AssertSExt/AssertZExt type should be the vector element type "
5171 "rather than the vector type!");
5172 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5173 if (VT.getScalarType() == EVT) return N1; // noop assertion.
5174 break;
5176 case ISD::SIGN_EXTEND_INREG: {
5177 EVT EVT = cast<VTSDNode>(N2)->getVT();
5178 assert(VT == N1.getValueType() && "Not an inreg extend!");
5179 assert(VT.isInteger() && EVT.isInteger() &&
5180 "Cannot *_EXTEND_INREG FP types");
5181 assert(EVT.isVector() == VT.isVector() &&
5182 "SIGN_EXTEND_INREG type should be vector iff the operand "
5183 "type is vector!");
5184 assert((!EVT.isVector() ||
5185 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
5186 "Vector element counts must match in SIGN_EXTEND_INREG");
5187 assert(EVT.bitsLE(VT) && "Not extending!");
5188 if (EVT == VT) return N1; // Not actually extending
5190 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5191 unsigned FromBits = EVT.getScalarSizeInBits();
5192 Val <<= Val.getBitWidth() - FromBits;
5193 Val.ashrInPlace(Val.getBitWidth() - FromBits);
5194 return getConstant(Val, DL, ConstantVT);
5197 if (N1C) {
5198 const APInt &Val = N1C->getAPIntValue();
5199 return SignExtendInReg(Val, VT);
5201 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5202 SmallVector<SDValue, 8> Ops;
5203 llvm::EVT OpVT = N1.getOperand(0).getValueType();
5204 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5205 SDValue Op = N1.getOperand(i);
5206 if (Op.isUndef()) {
5207 Ops.push_back(getUNDEF(OpVT));
5208 continue;
5210 ConstantSDNode *C = cast<ConstantSDNode>(Op);
5211 APInt Val = C->getAPIntValue();
5212 Ops.push_back(SignExtendInReg(Val, OpVT));
5214 return getBuildVector(VT, DL, Ops);
5216 break;
5218 case ISD::EXTRACT_VECTOR_ELT:
5219 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5220 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5221 element type of the vector.");
5223 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
5224 if (N1.isUndef())
5225 return getUNDEF(VT);
5227 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF
5228 if (N2C && N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5229 return getUNDEF(VT);
5231 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5232 // expanding copies of large vectors from registers.
5233 if (N2C &&
5234 N1.getOpcode() == ISD::CONCAT_VECTORS &&
5235 N1.getNumOperands() > 0) {
5236 unsigned Factor =
5237 N1.getOperand(0).getValueType().getVectorNumElements();
5238 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5239 N1.getOperand(N2C->getZExtValue() / Factor),
5240 getConstant(N2C->getZExtValue() % Factor, DL,
5241 N2.getValueType()));
5244 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
5245 // expanding large vector constants.
5246 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
5247 SDValue Elt = N1.getOperand(N2C->getZExtValue());
5249 if (VT != Elt.getValueType())
5250 // If the vector element type is not legal, the BUILD_VECTOR operands
5251 // are promoted and implicitly truncated, and the result implicitly
5252 // extended. Make that explicit here.
5253 Elt = getAnyExtOrTrunc(Elt, DL, VT);
5255 return Elt;
5258 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5259 // operations are lowered to scalars.
5260 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5261 // If the indices are the same, return the inserted element else
5262 // if the indices are known different, extract the element from
5263 // the original vector.
5264 SDValue N1Op2 = N1.getOperand(2);
5265 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5267 if (N1Op2C && N2C) {
5268 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5269 if (VT == N1.getOperand(1).getValueType())
5270 return N1.getOperand(1);
5271 else
5272 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5275 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5279 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5280 // when vector types are scalarized and v1iX is legal.
5281 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx)
5282 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5283 N1.getValueType().getVectorNumElements() == 1) {
5284 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5285 N1.getOperand(1));
5287 break;
5288 case ISD::EXTRACT_ELEMENT:
5289 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5290 assert(!N1.getValueType().isVector() && !VT.isVector() &&
5291 (N1.getValueType().isInteger() == VT.isInteger()) &&
5292 N1.getValueType() != VT &&
5293 "Wrong types for EXTRACT_ELEMENT!");
5295 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5296 // 64-bit integers into 32-bit parts. Instead of building the extract of
5297 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5298 if (N1.getOpcode() == ISD::BUILD_PAIR)
5299 return N1.getOperand(N2C->getZExtValue());
5301 // EXTRACT_ELEMENT of a constant int is also very common.
5302 if (N1C) {
5303 unsigned ElementSize = VT.getSizeInBits();
5304 unsigned Shift = ElementSize * N2C->getZExtValue();
5305 APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
5306 return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
5308 break;
5309 case ISD::EXTRACT_SUBVECTOR:
5310 if (VT.isSimple() && N1.getValueType().isSimple()) {
5311 assert(VT.isVector() && N1.getValueType().isVector() &&
5312 "Extract subvector VTs must be a vectors!");
5313 assert(VT.getVectorElementType() ==
5314 N1.getValueType().getVectorElementType() &&
5315 "Extract subvector VTs must have the same element type!");
5316 assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
5317 "Extract subvector must be from larger vector to smaller vector!");
5319 if (N2C) {
5320 assert((VT.getVectorNumElements() + N2C->getZExtValue()
5321 <= N1.getValueType().getVectorNumElements())
5322 && "Extract subvector overflow!");
5325 // Trivial extraction.
5326 if (VT.getSimpleVT() == N1.getSimpleValueType())
5327 return N1;
5329 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5330 if (N1.isUndef())
5331 return getUNDEF(VT);
5333 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5334 // the concat have the same type as the extract.
5335 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
5336 N1.getNumOperands() > 0 &&
5337 VT == N1.getOperand(0).getValueType()) {
5338 unsigned Factor = VT.getVectorNumElements();
5339 return N1.getOperand(N2C->getZExtValue() / Factor);
5342 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5343 // during shuffle legalization.
5344 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5345 VT == N1.getOperand(1).getValueType())
5346 return N1.getOperand(1);
5348 break;
5351 // Perform trivial constant folding.
5352 if (SDValue SV =
5353 FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode()))
5354 return SV;
5356 if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
5357 return V;
5359 // Canonicalize an UNDEF to the RHS, even over a constant.
5360 if (N1.isUndef()) {
5361 if (TLI->isCommutativeBinOp(Opcode)) {
5362 std::swap(N1, N2);
5363 } else {
5364 switch (Opcode) {
5365 case ISD::SIGN_EXTEND_INREG:
5366 case ISD::SUB:
5367 return getUNDEF(VT); // fold op(undef, arg2) -> undef
5368 case ISD::UDIV:
5369 case ISD::SDIV:
5370 case ISD::UREM:
5371 case ISD::SREM:
5372 case ISD::SSUBSAT:
5373 case ISD::USUBSAT:
5374 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
5379 // Fold a bunch of operators when the RHS is undef.
5380 if (N2.isUndef()) {
5381 switch (Opcode) {
5382 case ISD::XOR:
5383 if (N1.isUndef())
5384 // Handle undef ^ undef -> 0 special case. This is a common
5385 // idiom (misuse).
5386 return getConstant(0, DL, VT);
5387 LLVM_FALLTHROUGH;
5388 case ISD::ADD:
5389 case ISD::SUB:
5390 case ISD::UDIV:
5391 case ISD::SDIV:
5392 case ISD::UREM:
5393 case ISD::SREM:
5394 return getUNDEF(VT); // fold op(arg1, undef) -> undef
5395 case ISD::MUL:
5396 case ISD::AND:
5397 case ISD::SSUBSAT:
5398 case ISD::USUBSAT:
5399 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
5400 case ISD::OR:
5401 case ISD::SADDSAT:
5402 case ISD::UADDSAT:
5403 return getAllOnesConstant(DL, VT);
5407 // Memoize this node if possible.
5408 SDNode *N;
5409 SDVTList VTs = getVTList(VT);
5410 SDValue Ops[] = {N1, N2};
5411 if (VT != MVT::Glue) {
5412 FoldingSetNodeID ID;
5413 AddNodeIDNode(ID, Opcode, VTs, Ops);
5414 void *IP = nullptr;
5415 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5416 E->intersectFlagsWith(Flags);
5417 return SDValue(E, 0);
5420 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5421 N->setFlags(Flags);
5422 createOperands(N, Ops);
5423 CSEMap.InsertNode(N, IP);
5424 } else {
5425 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5426 createOperands(N, Ops);
5429 InsertNode(N);
5430 SDValue V = SDValue(N, 0);
5431 NewSDValueDbgMsg(V, "Creating new node: ", this);
5432 return V;
5435 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5436 SDValue N1, SDValue N2, SDValue N3,
5437 const SDNodeFlags Flags) {
5438 // Perform various simplifications.
5439 switch (Opcode) {
5440 case ISD::FMA: {
5441 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5442 assert(N1.getValueType() == VT && N2.getValueType() == VT &&
5443 N3.getValueType() == VT && "FMA types must match!");
5444 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5445 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5446 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
5447 if (N1CFP && N2CFP && N3CFP) {
5448 APFloat V1 = N1CFP->getValueAPF();
5449 const APFloat &V2 = N2CFP->getValueAPF();
5450 const APFloat &V3 = N3CFP->getValueAPF();
5451 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
5452 return getConstantFP(V1, DL, VT);
5454 break;
5456 case ISD::BUILD_VECTOR: {
5457 // Attempt to simplify BUILD_VECTOR.
5458 SDValue Ops[] = {N1, N2, N3};
5459 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5460 return V;
5461 break;
5463 case ISD::CONCAT_VECTORS: {
5464 SDValue Ops[] = {N1, N2, N3};
5465 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5466 return V;
5467 break;
5469 case ISD::SETCC: {
5470 assert(VT.isInteger() && "SETCC result type must be an integer!");
5471 assert(N1.getValueType() == N2.getValueType() &&
5472 "SETCC operands must have the same type!");
5473 assert(VT.isVector() == N1.getValueType().isVector() &&
5474 "SETCC type should be vector iff the operand type is vector!");
5475 assert((!VT.isVector() ||
5476 VT.getVectorNumElements() == N1.getValueType().getVectorNumElements()) &&
5477 "SETCC vector element counts must match!");
5478 // Use FoldSetCC to simplify SETCC's.
5479 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
5480 return V;
5481 // Vector constant folding.
5482 SDValue Ops[] = {N1, N2, N3};
5483 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
5484 NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
5485 return V;
5487 break;
5489 case ISD::SELECT:
5490 case ISD::VSELECT:
5491 if (SDValue V = simplifySelect(N1, N2, N3))
5492 return V;
5493 break;
5494 case ISD::VECTOR_SHUFFLE:
5495 llvm_unreachable("should use getVectorShuffle constructor!");
5496 case ISD::INSERT_VECTOR_ELT: {
5497 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
5498 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF
5499 if (N3C && N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
5500 return getUNDEF(VT);
5501 break;
5503 case ISD::INSERT_SUBVECTOR: {
5504 // Inserting undef into undef is still undef.
5505 if (N1.isUndef() && N2.isUndef())
5506 return getUNDEF(VT);
5507 SDValue Index = N3;
5508 if (VT.isSimple() && N1.getValueType().isSimple()
5509 && N2.getValueType().isSimple()) {
5510 assert(VT.isVector() && N1.getValueType().isVector() &&
5511 N2.getValueType().isVector() &&
5512 "Insert subvector VTs must be a vectors");
5513 assert(VT == N1.getValueType() &&
5514 "Dest and insert subvector source types must match!");
5515 assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
5516 "Insert subvector must be from smaller vector to larger vector!");
5517 if (isa<ConstantSDNode>(Index)) {
5518 assert((N2.getValueType().getVectorNumElements() +
5519 cast<ConstantSDNode>(Index)->getZExtValue()
5520 <= VT.getVectorNumElements())
5521 && "Insert subvector overflow!");
5524 // Trivial insertion.
5525 if (VT.getSimpleVT() == N2.getSimpleValueType())
5526 return N2;
5528 // If this is an insert of an extracted vector into an undef vector, we
5529 // can just use the input to the extract.
5530 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5531 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
5532 return N2.getOperand(0);
5534 break;
5536 case ISD::BITCAST:
5537 // Fold bit_convert nodes from a type to themselves.
5538 if (N1.getValueType() == VT)
5539 return N1;
5540 break;
5543 // Memoize node if it doesn't produce a flag.
5544 SDNode *N;
5545 SDVTList VTs = getVTList(VT);
5546 SDValue Ops[] = {N1, N2, N3};
5547 if (VT != MVT::Glue) {
5548 FoldingSetNodeID ID;
5549 AddNodeIDNode(ID, Opcode, VTs, Ops);
5550 void *IP = nullptr;
5551 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5552 E->intersectFlagsWith(Flags);
5553 return SDValue(E, 0);
5556 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5557 N->setFlags(Flags);
5558 createOperands(N, Ops);
5559 CSEMap.InsertNode(N, IP);
5560 } else {
5561 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5562 createOperands(N, Ops);
5565 InsertNode(N);
5566 SDValue V = SDValue(N, 0);
5567 NewSDValueDbgMsg(V, "Creating new node: ", this);
5568 return V;
5571 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5572 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
5573 SDValue Ops[] = { N1, N2, N3, N4 };
5574 return getNode(Opcode, DL, VT, Ops);
5577 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5578 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
5579 SDValue N5) {
5580 SDValue Ops[] = { N1, N2, N3, N4, N5 };
5581 return getNode(Opcode, DL, VT, Ops);
5584 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
5585 /// the incoming stack arguments to be loaded from the stack.
5586 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
5587 SmallVector<SDValue, 8> ArgChains;
5589 // Include the original chain at the beginning of the list. When this is
5590 // used by target LowerCall hooks, this helps legalize find the
5591 // CALLSEQ_BEGIN node.
5592 ArgChains.push_back(Chain);
5594 // Add a chain value for each stack argument.
5595 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
5596 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
5597 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
5598 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
5599 if (FI->getIndex() < 0)
5600 ArgChains.push_back(SDValue(L, 1));
5602 // Build a tokenfactor for all the chains.
5603 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
5606 /// getMemsetValue - Vectorized representation of the memset value
5607 /// operand.
5608 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
5609 const SDLoc &dl) {
5610 assert(!Value.isUndef());
5612 unsigned NumBits = VT.getScalarSizeInBits();
5613 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
5614 assert(C->getAPIntValue().getBitWidth() == 8);
5615 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
5616 if (VT.isInteger()) {
5617 bool IsOpaque = VT.getSizeInBits() > 64 ||
5618 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
5619 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
5621 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
5622 VT);
5625 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
5626 EVT IntVT = VT.getScalarType();
5627 if (!IntVT.isInteger())
5628 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
5630 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
5631 if (NumBits > 8) {
5632 // Use a multiplication with 0x010101... to extend the input to the
5633 // required length.
5634 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
5635 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
5636 DAG.getConstant(Magic, dl, IntVT));
5639 if (VT != Value.getValueType() && !VT.isInteger())
5640 Value = DAG.getBitcast(VT.getScalarType(), Value);
5641 if (VT != Value.getValueType())
5642 Value = DAG.getSplatBuildVector(VT, dl, Value);
5644 return Value;
5647 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
5648 /// used when a memcpy is turned into a memset when the source is a constant
5649 /// string ptr.
5650 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
5651 const TargetLowering &TLI,
5652 const ConstantDataArraySlice &Slice) {
5653 // Handle vector with all elements zero.
5654 if (Slice.Array == nullptr) {
5655 if (VT.isInteger())
5656 return DAG.getConstant(0, dl, VT);
5657 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
5658 return DAG.getConstantFP(0.0, dl, VT);
5659 else if (VT.isVector()) {
5660 unsigned NumElts = VT.getVectorNumElements();
5661 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5662 return DAG.getNode(ISD::BITCAST, dl, VT,
5663 DAG.getConstant(0, dl,
5664 EVT::getVectorVT(*DAG.getContext(),
5665 EltVT, NumElts)));
5666 } else
5667 llvm_unreachable("Expected type!");
5670 assert(!VT.isVector() && "Can't handle vector type here!");
5671 unsigned NumVTBits = VT.getSizeInBits();
5672 unsigned NumVTBytes = NumVTBits / 8;
5673 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
5675 APInt Val(NumVTBits, 0);
5676 if (DAG.getDataLayout().isLittleEndian()) {
5677 for (unsigned i = 0; i != NumBytes; ++i)
5678 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
5679 } else {
5680 for (unsigned i = 0; i != NumBytes; ++i)
5681 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
5684 // If the "cost" of materializing the integer immediate is less than the cost
5685 // of a load, then it is cost effective to turn the load into the immediate.
5686 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
5687 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
5688 return DAG.getConstant(Val, dl, VT);
5689 return SDValue(nullptr, 0);
5692 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset,
5693 const SDLoc &DL) {
5694 EVT VT = Base.getValueType();
5695 return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT));
5698 /// Returns true if memcpy source is constant data.
5699 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
5700 uint64_t SrcDelta = 0;
5701 GlobalAddressSDNode *G = nullptr;
5702 if (Src.getOpcode() == ISD::GlobalAddress)
5703 G = cast<GlobalAddressSDNode>(Src);
5704 else if (Src.getOpcode() == ISD::ADD &&
5705 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
5706 Src.getOperand(1).getOpcode() == ISD::Constant) {
5707 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
5708 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
5710 if (!G)
5711 return false;
5713 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
5714 SrcDelta + G->getOffset());
5717 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) {
5718 // On Darwin, -Os means optimize for size without hurting performance, so
5719 // only really optimize for size when -Oz (MinSize) is used.
5720 if (MF.getTarget().getTargetTriple().isOSDarwin())
5721 return MF.getFunction().hasMinSize();
5722 return MF.getFunction().hasOptSize();
5725 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
5726 SmallVector<SDValue, 32> &OutChains, unsigned From,
5727 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
5728 SmallVector<SDValue, 16> &OutStoreChains) {
5729 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
5730 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
5731 SmallVector<SDValue, 16> GluedLoadChains;
5732 for (unsigned i = From; i < To; ++i) {
5733 OutChains.push_back(OutLoadChains[i]);
5734 GluedLoadChains.push_back(OutLoadChains[i]);
5737 // Chain for all loads.
5738 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5739 GluedLoadChains);
5741 for (unsigned i = From; i < To; ++i) {
5742 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
5743 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
5744 ST->getBasePtr(), ST->getMemoryVT(),
5745 ST->getMemOperand());
5746 OutChains.push_back(NewStore);
5750 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
5751 SDValue Chain, SDValue Dst, SDValue Src,
5752 uint64_t Size, unsigned Align,
5753 bool isVol, bool AlwaysInline,
5754 MachinePointerInfo DstPtrInfo,
5755 MachinePointerInfo SrcPtrInfo) {
5756 // Turn a memcpy of undef to nop.
5757 // FIXME: We need to honor volatile even is Src is undef.
5758 if (Src.isUndef())
5759 return Chain;
5761 // Expand memcpy to a series of load and store ops if the size operand falls
5762 // below a certain threshold.
5763 // TODO: In the AlwaysInline case, if the size is big then generate a loop
5764 // rather than maybe a humongous number of loads and stores.
5765 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5766 const DataLayout &DL = DAG.getDataLayout();
5767 LLVMContext &C = *DAG.getContext();
5768 std::vector<EVT> MemOps;
5769 bool DstAlignCanChange = false;
5770 MachineFunction &MF = DAG.getMachineFunction();
5771 MachineFrameInfo &MFI = MF.getFrameInfo();
5772 bool OptSize = shouldLowerMemFuncForSize(MF);
5773 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5774 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5775 DstAlignCanChange = true;
5776 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
5777 if (Align > SrcAlign)
5778 SrcAlign = Align;
5779 ConstantDataArraySlice Slice;
5780 bool CopyFromConstant = isMemSrcFromConstant(Src, Slice);
5781 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
5782 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
5784 if (!TLI.findOptimalMemOpLowering(
5785 MemOps, Limit, Size, (DstAlignCanChange ? 0 : Align),
5786 (isZeroConstant ? 0 : SrcAlign), /*IsMemset=*/false,
5787 /*ZeroMemset=*/false, /*MemcpyStrSrc=*/CopyFromConstant,
5788 /*AllowOverlap=*/!isVol, DstPtrInfo.getAddrSpace(),
5789 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
5790 return SDValue();
5792 if (DstAlignCanChange) {
5793 Type *Ty = MemOps[0].getTypeForEVT(C);
5794 unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
5796 // Don't promote to an alignment that would require dynamic stack
5797 // realignment.
5798 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
5799 if (!TRI->needsStackRealignment(MF))
5800 while (NewAlign > Align &&
5801 DL.exceedsNaturalStackAlignment(llvm::Align(NewAlign)))
5802 NewAlign /= 2;
5804 if (NewAlign > Align) {
5805 // Give the stack frame object a larger alignment if needed.
5806 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5807 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5808 Align = NewAlign;
5812 MachineMemOperand::Flags MMOFlags =
5813 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
5814 SmallVector<SDValue, 16> OutLoadChains;
5815 SmallVector<SDValue, 16> OutStoreChains;
5816 SmallVector<SDValue, 32> OutChains;
5817 unsigned NumMemOps = MemOps.size();
5818 uint64_t SrcOff = 0, DstOff = 0;
5819 for (unsigned i = 0; i != NumMemOps; ++i) {
5820 EVT VT = MemOps[i];
5821 unsigned VTSize = VT.getSizeInBits() / 8;
5822 SDValue Value, Store;
5824 if (VTSize > Size) {
5825 // Issuing an unaligned load / store pair that overlaps with the previous
5826 // pair. Adjust the offset accordingly.
5827 assert(i == NumMemOps-1 && i != 0);
5828 SrcOff -= VTSize - Size;
5829 DstOff -= VTSize - Size;
5832 if (CopyFromConstant &&
5833 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
5834 // It's unlikely a store of a vector immediate can be done in a single
5835 // instruction. It would require a load from a constantpool first.
5836 // We only handle zero vectors here.
5837 // FIXME: Handle other cases where store of vector immediate is done in
5838 // a single instruction.
5839 ConstantDataArraySlice SubSlice;
5840 if (SrcOff < Slice.Length) {
5841 SubSlice = Slice;
5842 SubSlice.move(SrcOff);
5843 } else {
5844 // This is an out-of-bounds access and hence UB. Pretend we read zero.
5845 SubSlice.Array = nullptr;
5846 SubSlice.Offset = 0;
5847 SubSlice.Length = VTSize;
5849 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
5850 if (Value.getNode()) {
5851 Store = DAG.getStore(Chain, dl, Value,
5852 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5853 DstPtrInfo.getWithOffset(DstOff), Align,
5854 MMOFlags);
5855 OutChains.push_back(Store);
5859 if (!Store.getNode()) {
5860 // The type might not be legal for the target. This should only happen
5861 // if the type is smaller than a legal type, as on PPC, so the right
5862 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
5863 // to Load/Store if NVT==VT.
5864 // FIXME does the case above also need this?
5865 EVT NVT = TLI.getTypeToTransformTo(C, VT);
5866 assert(NVT.bitsGE(VT));
5868 bool isDereferenceable =
5869 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
5870 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
5871 if (isDereferenceable)
5872 SrcMMOFlags |= MachineMemOperand::MODereferenceable;
5874 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
5875 DAG.getMemBasePlusOffset(Src, SrcOff, dl),
5876 SrcPtrInfo.getWithOffset(SrcOff), VT,
5877 MinAlign(SrcAlign, SrcOff), SrcMMOFlags);
5878 OutLoadChains.push_back(Value.getValue(1));
5880 Store = DAG.getTruncStore(
5881 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5882 DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags);
5883 OutStoreChains.push_back(Store);
5885 SrcOff += VTSize;
5886 DstOff += VTSize;
5887 Size -= VTSize;
5890 unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
5891 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
5892 unsigned NumLdStInMemcpy = OutStoreChains.size();
5894 if (NumLdStInMemcpy) {
5895 // It may be that memcpy might be converted to memset if it's memcpy
5896 // of constants. In such a case, we won't have loads and stores, but
5897 // just stores. In the absence of loads, there is nothing to gang up.
5898 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
5899 // If target does not care, just leave as it.
5900 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
5901 OutChains.push_back(OutLoadChains[i]);
5902 OutChains.push_back(OutStoreChains[i]);
5904 } else {
5905 // Ld/St less than/equal limit set by target.
5906 if (NumLdStInMemcpy <= GluedLdStLimit) {
5907 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
5908 NumLdStInMemcpy, OutLoadChains,
5909 OutStoreChains);
5910 } else {
5911 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
5912 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
5913 unsigned GlueIter = 0;
5915 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
5916 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
5917 unsigned IndexTo = NumLdStInMemcpy - GlueIter;
5919 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
5920 OutLoadChains, OutStoreChains);
5921 GlueIter += GluedLdStLimit;
5924 // Residual ld/st.
5925 if (RemainingLdStInMemcpy) {
5926 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
5927 RemainingLdStInMemcpy, OutLoadChains,
5928 OutStoreChains);
5933 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5936 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
5937 SDValue Chain, SDValue Dst, SDValue Src,
5938 uint64_t Size, unsigned Align,
5939 bool isVol, bool AlwaysInline,
5940 MachinePointerInfo DstPtrInfo,
5941 MachinePointerInfo SrcPtrInfo) {
5942 // Turn a memmove of undef to nop.
5943 // FIXME: We need to honor volatile even is Src is undef.
5944 if (Src.isUndef())
5945 return Chain;
5947 // Expand memmove to a series of load and store ops if the size operand falls
5948 // below a certain threshold.
5949 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5950 const DataLayout &DL = DAG.getDataLayout();
5951 LLVMContext &C = *DAG.getContext();
5952 std::vector<EVT> MemOps;
5953 bool DstAlignCanChange = false;
5954 MachineFunction &MF = DAG.getMachineFunction();
5955 MachineFrameInfo &MFI = MF.getFrameInfo();
5956 bool OptSize = shouldLowerMemFuncForSize(MF);
5957 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5958 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5959 DstAlignCanChange = true;
5960 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
5961 if (Align > SrcAlign)
5962 SrcAlign = Align;
5963 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
5964 // FIXME: `AllowOverlap` should really be `!isVol` but there is a bug in
5965 // findOptimalMemOpLowering. Meanwhile, setting it to `false` produces the
5966 // correct code.
5967 bool AllowOverlap = false;
5968 if (!TLI.findOptimalMemOpLowering(
5969 MemOps, Limit, Size, (DstAlignCanChange ? 0 : Align), SrcAlign,
5970 /*IsMemset=*/false, /*ZeroMemset=*/false, /*MemcpyStrSrc=*/false,
5971 AllowOverlap, DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
5972 MF.getFunction().getAttributes()))
5973 return SDValue();
5975 if (DstAlignCanChange) {
5976 Type *Ty = MemOps[0].getTypeForEVT(C);
5977 unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
5978 if (NewAlign > Align) {
5979 // Give the stack frame object a larger alignment if needed.
5980 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5981 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5982 Align = NewAlign;
5986 MachineMemOperand::Flags MMOFlags =
5987 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
5988 uint64_t SrcOff = 0, DstOff = 0;
5989 SmallVector<SDValue, 8> LoadValues;
5990 SmallVector<SDValue, 8> LoadChains;
5991 SmallVector<SDValue, 8> OutChains;
5992 unsigned NumMemOps = MemOps.size();
5993 for (unsigned i = 0; i < NumMemOps; i++) {
5994 EVT VT = MemOps[i];
5995 unsigned VTSize = VT.getSizeInBits() / 8;
5996 SDValue Value;
5998 bool isDereferenceable =
5999 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6000 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6001 if (isDereferenceable)
6002 SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6004 Value =
6005 DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl),
6006 SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, SrcMMOFlags);
6007 LoadValues.push_back(Value);
6008 LoadChains.push_back(Value.getValue(1));
6009 SrcOff += VTSize;
6011 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6012 OutChains.clear();
6013 for (unsigned i = 0; i < NumMemOps; i++) {
6014 EVT VT = MemOps[i];
6015 unsigned VTSize = VT.getSizeInBits() / 8;
6016 SDValue Store;
6018 Store = DAG.getStore(Chain, dl, LoadValues[i],
6019 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
6020 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
6021 OutChains.push_back(Store);
6022 DstOff += VTSize;
6025 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6028 /// Lower the call to 'memset' intrinsic function into a series of store
6029 /// operations.
6031 /// \param DAG Selection DAG where lowered code is placed.
6032 /// \param dl Link to corresponding IR location.
6033 /// \param Chain Control flow dependency.
6034 /// \param Dst Pointer to destination memory location.
6035 /// \param Src Value of byte to write into the memory.
6036 /// \param Size Number of bytes to write.
6037 /// \param Align Alignment of the destination in bytes.
6038 /// \param isVol True if destination is volatile.
6039 /// \param DstPtrInfo IR information on the memory pointer.
6040 /// \returns New head in the control flow, if lowering was successful, empty
6041 /// SDValue otherwise.
6043 /// The function tries to replace 'llvm.memset' intrinsic with several store
6044 /// operations and value calculation code. This is usually profitable for small
6045 /// memory size.
6046 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6047 SDValue Chain, SDValue Dst, SDValue Src,
6048 uint64_t Size, unsigned Align, bool isVol,
6049 MachinePointerInfo DstPtrInfo) {
6050 // Turn a memset of undef to nop.
6051 // FIXME: We need to honor volatile even is Src is undef.
6052 if (Src.isUndef())
6053 return Chain;
6055 // Expand memset to a series of load/store ops if the size operand
6056 // falls below a certain threshold.
6057 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6058 std::vector<EVT> MemOps;
6059 bool DstAlignCanChange = false;
6060 MachineFunction &MF = DAG.getMachineFunction();
6061 MachineFrameInfo &MFI = MF.getFrameInfo();
6062 bool OptSize = shouldLowerMemFuncForSize(MF);
6063 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6064 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6065 DstAlignCanChange = true;
6066 bool IsZeroVal =
6067 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
6068 if (!TLI.findOptimalMemOpLowering(
6069 MemOps, TLI.getMaxStoresPerMemset(OptSize), Size,
6070 (DstAlignCanChange ? 0 : Align), 0, /*IsMemset=*/true,
6071 /*ZeroMemset=*/IsZeroVal, /*MemcpyStrSrc=*/false,
6072 /*AllowOverlap=*/!isVol, DstPtrInfo.getAddrSpace(), ~0u,
6073 MF.getFunction().getAttributes()))
6074 return SDValue();
6076 if (DstAlignCanChange) {
6077 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6078 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
6079 if (NewAlign > Align) {
6080 // Give the stack frame object a larger alignment if needed.
6081 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
6082 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6083 Align = NewAlign;
6087 SmallVector<SDValue, 8> OutChains;
6088 uint64_t DstOff = 0;
6089 unsigned NumMemOps = MemOps.size();
6091 // Find the largest store and generate the bit pattern for it.
6092 EVT LargestVT = MemOps[0];
6093 for (unsigned i = 1; i < NumMemOps; i++)
6094 if (MemOps[i].bitsGT(LargestVT))
6095 LargestVT = MemOps[i];
6096 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6098 for (unsigned i = 0; i < NumMemOps; i++) {
6099 EVT VT = MemOps[i];
6100 unsigned VTSize = VT.getSizeInBits() / 8;
6101 if (VTSize > Size) {
6102 // Issuing an unaligned load / store pair that overlaps with the previous
6103 // pair. Adjust the offset accordingly.
6104 assert(i == NumMemOps-1 && i != 0);
6105 DstOff -= VTSize - Size;
6108 // If this store is smaller than the largest store see whether we can get
6109 // the smaller value for free with a truncate.
6110 SDValue Value = MemSetValue;
6111 if (VT.bitsLT(LargestVT)) {
6112 if (!LargestVT.isVector() && !VT.isVector() &&
6113 TLI.isTruncateFree(LargestVT, VT))
6114 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6115 else
6116 Value = getMemsetValue(Src, VT, DAG, dl);
6118 assert(Value.getValueType() == VT && "Value with wrong type.");
6119 SDValue Store = DAG.getStore(
6120 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
6121 DstPtrInfo.getWithOffset(DstOff), Align,
6122 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
6123 OutChains.push_back(Store);
6124 DstOff += VT.getSizeInBits() / 8;
6125 Size -= VTSize;
6128 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6131 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6132 unsigned AS) {
6133 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6134 // pointer operands can be losslessly bitcasted to pointers of address space 0
6135 if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) {
6136 report_fatal_error("cannot lower memory intrinsic in address space " +
6137 Twine(AS));
6141 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6142 SDValue Src, SDValue Size, unsigned Align,
6143 bool isVol, bool AlwaysInline, bool isTailCall,
6144 MachinePointerInfo DstPtrInfo,
6145 MachinePointerInfo SrcPtrInfo) {
6146 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
6148 // Check to see if we should lower the memcpy to loads and stores first.
6149 // For cases within the target-specified limits, this is the best choice.
6150 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6151 if (ConstantSize) {
6152 // Memcpy with size zero? Just return the original chain.
6153 if (ConstantSize->isNullValue())
6154 return Chain;
6156 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6157 ConstantSize->getZExtValue(),Align,
6158 isVol, false, DstPtrInfo, SrcPtrInfo);
6159 if (Result.getNode())
6160 return Result;
6163 // Then check to see if we should lower the memcpy with target-specific
6164 // code. If the target chooses to do this, this is the next best.
6165 if (TSI) {
6166 SDValue Result = TSI->EmitTargetCodeForMemcpy(
6167 *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline,
6168 DstPtrInfo, SrcPtrInfo);
6169 if (Result.getNode())
6170 return Result;
6173 // If we really need inline code and the target declined to provide it,
6174 // use a (potentially long) sequence of loads and stores.
6175 if (AlwaysInline) {
6176 assert(ConstantSize && "AlwaysInline requires a constant size!");
6177 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6178 ConstantSize->getZExtValue(), Align, isVol,
6179 true, DstPtrInfo, SrcPtrInfo);
6182 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6183 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6185 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6186 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6187 // respect volatile, so they may do things like read or write memory
6188 // beyond the given memory regions. But fixing this isn't easy, and most
6189 // people don't care.
6191 // Emit a library call.
6192 TargetLowering::ArgListTy Args;
6193 TargetLowering::ArgListEntry Entry;
6194 Entry.Ty = Type::getInt8PtrTy(*getContext());
6195 Entry.Node = Dst; Args.push_back(Entry);
6196 Entry.Node = Src; Args.push_back(Entry);
6198 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6199 Entry.Node = Size; Args.push_back(Entry);
6200 // FIXME: pass in SDLoc
6201 TargetLowering::CallLoweringInfo CLI(*this);
6202 CLI.setDebugLoc(dl)
6203 .setChain(Chain)
6204 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6205 Dst.getValueType().getTypeForEVT(*getContext()),
6206 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6207 TLI->getPointerTy(getDataLayout())),
6208 std::move(Args))
6209 .setDiscardResult()
6210 .setTailCall(isTailCall);
6212 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6213 return CallResult.second;
6216 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6217 SDValue Dst, unsigned DstAlign,
6218 SDValue Src, unsigned SrcAlign,
6219 SDValue Size, Type *SizeTy,
6220 unsigned ElemSz, bool isTailCall,
6221 MachinePointerInfo DstPtrInfo,
6222 MachinePointerInfo SrcPtrInfo) {
6223 // Emit a library call.
6224 TargetLowering::ArgListTy Args;
6225 TargetLowering::ArgListEntry Entry;
6226 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6227 Entry.Node = Dst;
6228 Args.push_back(Entry);
6230 Entry.Node = Src;
6231 Args.push_back(Entry);
6233 Entry.Ty = SizeTy;
6234 Entry.Node = Size;
6235 Args.push_back(Entry);
6237 RTLIB::Libcall LibraryCall =
6238 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6239 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6240 report_fatal_error("Unsupported element size");
6242 TargetLowering::CallLoweringInfo CLI(*this);
6243 CLI.setDebugLoc(dl)
6244 .setChain(Chain)
6245 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6246 Type::getVoidTy(*getContext()),
6247 getExternalSymbol(TLI->getLibcallName(LibraryCall),
6248 TLI->getPointerTy(getDataLayout())),
6249 std::move(Args))
6250 .setDiscardResult()
6251 .setTailCall(isTailCall);
6253 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6254 return CallResult.second;
6257 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6258 SDValue Src, SDValue Size, unsigned Align,
6259 bool isVol, bool isTailCall,
6260 MachinePointerInfo DstPtrInfo,
6261 MachinePointerInfo SrcPtrInfo) {
6262 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
6264 // Check to see if we should lower the memmove to loads and stores first.
6265 // For cases within the target-specified limits, this is the best choice.
6266 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6267 if (ConstantSize) {
6268 // Memmove with size zero? Just return the original chain.
6269 if (ConstantSize->isNullValue())
6270 return Chain;
6272 SDValue Result =
6273 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
6274 ConstantSize->getZExtValue(), Align, isVol,
6275 false, DstPtrInfo, SrcPtrInfo);
6276 if (Result.getNode())
6277 return Result;
6280 // Then check to see if we should lower the memmove with target-specific
6281 // code. If the target chooses to do this, this is the next best.
6282 if (TSI) {
6283 SDValue Result = TSI->EmitTargetCodeForMemmove(
6284 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
6285 if (Result.getNode())
6286 return Result;
6289 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6290 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6292 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6293 // not be safe. See memcpy above for more details.
6295 // Emit a library call.
6296 TargetLowering::ArgListTy Args;
6297 TargetLowering::ArgListEntry Entry;
6298 Entry.Ty = Type::getInt8PtrTy(*getContext());
6299 Entry.Node = Dst; Args.push_back(Entry);
6300 Entry.Node = Src; Args.push_back(Entry);
6302 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6303 Entry.Node = Size; Args.push_back(Entry);
6304 // FIXME: pass in SDLoc
6305 TargetLowering::CallLoweringInfo CLI(*this);
6306 CLI.setDebugLoc(dl)
6307 .setChain(Chain)
6308 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
6309 Dst.getValueType().getTypeForEVT(*getContext()),
6310 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
6311 TLI->getPointerTy(getDataLayout())),
6312 std::move(Args))
6313 .setDiscardResult()
6314 .setTailCall(isTailCall);
6316 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6317 return CallResult.second;
6320 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
6321 SDValue Dst, unsigned DstAlign,
6322 SDValue Src, unsigned SrcAlign,
6323 SDValue Size, Type *SizeTy,
6324 unsigned ElemSz, bool isTailCall,
6325 MachinePointerInfo DstPtrInfo,
6326 MachinePointerInfo SrcPtrInfo) {
6327 // Emit a library call.
6328 TargetLowering::ArgListTy Args;
6329 TargetLowering::ArgListEntry Entry;
6330 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6331 Entry.Node = Dst;
6332 Args.push_back(Entry);
6334 Entry.Node = Src;
6335 Args.push_back(Entry);
6337 Entry.Ty = SizeTy;
6338 Entry.Node = Size;
6339 Args.push_back(Entry);
6341 RTLIB::Libcall LibraryCall =
6342 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6343 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6344 report_fatal_error("Unsupported element size");
6346 TargetLowering::CallLoweringInfo CLI(*this);
6347 CLI.setDebugLoc(dl)
6348 .setChain(Chain)
6349 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6350 Type::getVoidTy(*getContext()),
6351 getExternalSymbol(TLI->getLibcallName(LibraryCall),
6352 TLI->getPointerTy(getDataLayout())),
6353 std::move(Args))
6354 .setDiscardResult()
6355 .setTailCall(isTailCall);
6357 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6358 return CallResult.second;
6361 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
6362 SDValue Src, SDValue Size, unsigned Align,
6363 bool isVol, bool isTailCall,
6364 MachinePointerInfo DstPtrInfo) {
6365 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
6367 // Check to see if we should lower the memset to stores first.
6368 // For cases within the target-specified limits, this is the best choice.
6369 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6370 if (ConstantSize) {
6371 // Memset with size zero? Just return the original chain.
6372 if (ConstantSize->isNullValue())
6373 return Chain;
6375 SDValue Result =
6376 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
6377 Align, isVol, DstPtrInfo);
6379 if (Result.getNode())
6380 return Result;
6383 // Then check to see if we should lower the memset with target-specific
6384 // code. If the target chooses to do this, this is the next best.
6385 if (TSI) {
6386 SDValue Result = TSI->EmitTargetCodeForMemset(
6387 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo);
6388 if (Result.getNode())
6389 return Result;
6392 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6394 // Emit a library call.
6395 TargetLowering::ArgListTy Args;
6396 TargetLowering::ArgListEntry Entry;
6397 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
6398 Args.push_back(Entry);
6399 Entry.Node = Src;
6400 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
6401 Args.push_back(Entry);
6402 Entry.Node = Size;
6403 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6404 Args.push_back(Entry);
6406 // FIXME: pass in SDLoc
6407 TargetLowering::CallLoweringInfo CLI(*this);
6408 CLI.setDebugLoc(dl)
6409 .setChain(Chain)
6410 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
6411 Dst.getValueType().getTypeForEVT(*getContext()),
6412 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
6413 TLI->getPointerTy(getDataLayout())),
6414 std::move(Args))
6415 .setDiscardResult()
6416 .setTailCall(isTailCall);
6418 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6419 return CallResult.second;
6422 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
6423 SDValue Dst, unsigned DstAlign,
6424 SDValue Value, SDValue Size, Type *SizeTy,
6425 unsigned ElemSz, bool isTailCall,
6426 MachinePointerInfo DstPtrInfo) {
6427 // Emit a library call.
6428 TargetLowering::ArgListTy Args;
6429 TargetLowering::ArgListEntry Entry;
6430 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6431 Entry.Node = Dst;
6432 Args.push_back(Entry);
6434 Entry.Ty = Type::getInt8Ty(*getContext());
6435 Entry.Node = Value;
6436 Args.push_back(Entry);
6438 Entry.Ty = SizeTy;
6439 Entry.Node = Size;
6440 Args.push_back(Entry);
6442 RTLIB::Libcall LibraryCall =
6443 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6444 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6445 report_fatal_error("Unsupported element size");
6447 TargetLowering::CallLoweringInfo CLI(*this);
6448 CLI.setDebugLoc(dl)
6449 .setChain(Chain)
6450 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6451 Type::getVoidTy(*getContext()),
6452 getExternalSymbol(TLI->getLibcallName(LibraryCall),
6453 TLI->getPointerTy(getDataLayout())),
6454 std::move(Args))
6455 .setDiscardResult()
6456 .setTailCall(isTailCall);
6458 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6459 return CallResult.second;
6462 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6463 SDVTList VTList, ArrayRef<SDValue> Ops,
6464 MachineMemOperand *MMO) {
6465 FoldingSetNodeID ID;
6466 ID.AddInteger(MemVT.getRawBits());
6467 AddNodeIDNode(ID, Opcode, VTList, Ops);
6468 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6469 void* IP = nullptr;
6470 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6471 cast<AtomicSDNode>(E)->refineAlignment(MMO);
6472 return SDValue(E, 0);
6475 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6476 VTList, MemVT, MMO);
6477 createOperands(N, Ops);
6479 CSEMap.InsertNode(N, IP);
6480 InsertNode(N);
6481 return SDValue(N, 0);
6484 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
6485 EVT MemVT, SDVTList VTs, SDValue Chain,
6486 SDValue Ptr, SDValue Cmp, SDValue Swp,
6487 MachineMemOperand *MMO) {
6488 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
6489 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
6490 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
6492 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
6493 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6496 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6497 SDValue Chain, SDValue Ptr, SDValue Val,
6498 MachineMemOperand *MMO) {
6499 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
6500 Opcode == ISD::ATOMIC_LOAD_SUB ||
6501 Opcode == ISD::ATOMIC_LOAD_AND ||
6502 Opcode == ISD::ATOMIC_LOAD_CLR ||
6503 Opcode == ISD::ATOMIC_LOAD_OR ||
6504 Opcode == ISD::ATOMIC_LOAD_XOR ||
6505 Opcode == ISD::ATOMIC_LOAD_NAND ||
6506 Opcode == ISD::ATOMIC_LOAD_MIN ||
6507 Opcode == ISD::ATOMIC_LOAD_MAX ||
6508 Opcode == ISD::ATOMIC_LOAD_UMIN ||
6509 Opcode == ISD::ATOMIC_LOAD_UMAX ||
6510 Opcode == ISD::ATOMIC_LOAD_FADD ||
6511 Opcode == ISD::ATOMIC_LOAD_FSUB ||
6512 Opcode == ISD::ATOMIC_SWAP ||
6513 Opcode == ISD::ATOMIC_STORE) &&
6514 "Invalid Atomic Op");
6516 EVT VT = Val.getValueType();
6518 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
6519 getVTList(VT, MVT::Other);
6520 SDValue Ops[] = {Chain, Ptr, Val};
6521 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6524 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6525 EVT VT, SDValue Chain, SDValue Ptr,
6526 MachineMemOperand *MMO) {
6527 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
6529 SDVTList VTs = getVTList(VT, MVT::Other);
6530 SDValue Ops[] = {Chain, Ptr};
6531 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6534 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
6535 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
6536 if (Ops.size() == 1)
6537 return Ops[0];
6539 SmallVector<EVT, 4> VTs;
6540 VTs.reserve(Ops.size());
6541 for (unsigned i = 0; i < Ops.size(); ++i)
6542 VTs.push_back(Ops[i].getValueType());
6543 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
6546 SDValue SelectionDAG::getMemIntrinsicNode(
6547 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
6548 EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align,
6549 MachineMemOperand::Flags Flags, unsigned Size, const AAMDNodes &AAInfo) {
6550 if (Align == 0) // Ensure that codegen never sees alignment 0
6551 Align = getEVTAlignment(MemVT);
6553 if (!Size)
6554 Size = MemVT.getStoreSize();
6556 MachineFunction &MF = getMachineFunction();
6557 MachineMemOperand *MMO =
6558 MF.getMachineMemOperand(PtrInfo, Flags, Size, Align, AAInfo);
6560 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
6563 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
6564 SDVTList VTList,
6565 ArrayRef<SDValue> Ops, EVT MemVT,
6566 MachineMemOperand *MMO) {
6567 assert((Opcode == ISD::INTRINSIC_VOID ||
6568 Opcode == ISD::INTRINSIC_W_CHAIN ||
6569 Opcode == ISD::PREFETCH ||
6570 Opcode == ISD::LIFETIME_START ||
6571 Opcode == ISD::LIFETIME_END ||
6572 ((int)Opcode <= std::numeric_limits<int>::max() &&
6573 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
6574 "Opcode is not a memory-accessing opcode!");
6576 // Memoize the node unless it returns a flag.
6577 MemIntrinsicSDNode *N;
6578 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
6579 FoldingSetNodeID ID;
6580 AddNodeIDNode(ID, Opcode, VTList, Ops);
6581 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
6582 Opcode, dl.getIROrder(), VTList, MemVT, MMO));
6583 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6584 void *IP = nullptr;
6585 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6586 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
6587 return SDValue(E, 0);
6590 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6591 VTList, MemVT, MMO);
6592 createOperands(N, Ops);
6594 CSEMap.InsertNode(N, IP);
6595 } else {
6596 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6597 VTList, MemVT, MMO);
6598 createOperands(N, Ops);
6600 InsertNode(N);
6601 SDValue V(N, 0);
6602 NewSDValueDbgMsg(V, "Creating new node: ", this);
6603 return V;
6606 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
6607 SDValue Chain, int FrameIndex,
6608 int64_t Size, int64_t Offset) {
6609 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
6610 const auto VTs = getVTList(MVT::Other);
6611 SDValue Ops[2] = {
6612 Chain,
6613 getFrameIndex(FrameIndex,
6614 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
6615 true)};
6617 FoldingSetNodeID ID;
6618 AddNodeIDNode(ID, Opcode, VTs, Ops);
6619 ID.AddInteger(FrameIndex);
6620 ID.AddInteger(Size);
6621 ID.AddInteger(Offset);
6622 void *IP = nullptr;
6623 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
6624 return SDValue(E, 0);
6626 LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
6627 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
6628 createOperands(N, Ops);
6629 CSEMap.InsertNode(N, IP);
6630 InsertNode(N);
6631 SDValue V(N, 0);
6632 NewSDValueDbgMsg(V, "Creating new node: ", this);
6633 return V;
6636 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
6637 /// MachinePointerInfo record from it. This is particularly useful because the
6638 /// code generator has many cases where it doesn't bother passing in a
6639 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
6640 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
6641 SelectionDAG &DAG, SDValue Ptr,
6642 int64_t Offset = 0) {
6643 // If this is FI+Offset, we can model it.
6644 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
6645 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
6646 FI->getIndex(), Offset);
6648 // If this is (FI+Offset1)+Offset2, we can model it.
6649 if (Ptr.getOpcode() != ISD::ADD ||
6650 !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
6651 !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
6652 return Info;
6654 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6655 return MachinePointerInfo::getFixedStack(
6656 DAG.getMachineFunction(), FI,
6657 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
6660 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
6661 /// MachinePointerInfo record from it. This is particularly useful because the
6662 /// code generator has many cases where it doesn't bother passing in a
6663 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
6664 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
6665 SelectionDAG &DAG, SDValue Ptr,
6666 SDValue OffsetOp) {
6667 // If the 'Offset' value isn't a constant, we can't handle this.
6668 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
6669 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
6670 if (OffsetOp.isUndef())
6671 return InferPointerInfo(Info, DAG, Ptr);
6672 return Info;
6675 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
6676 EVT VT, const SDLoc &dl, SDValue Chain,
6677 SDValue Ptr, SDValue Offset,
6678 MachinePointerInfo PtrInfo, EVT MemVT,
6679 unsigned Alignment,
6680 MachineMemOperand::Flags MMOFlags,
6681 const AAMDNodes &AAInfo, const MDNode *Ranges) {
6682 assert(Chain.getValueType() == MVT::Other &&
6683 "Invalid chain type");
6684 if (Alignment == 0) // Ensure that codegen never sees alignment 0
6685 Alignment = getEVTAlignment(MemVT);
6687 MMOFlags |= MachineMemOperand::MOLoad;
6688 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
6689 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
6690 // clients.
6691 if (PtrInfo.V.isNull())
6692 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
6694 MachineFunction &MF = getMachineFunction();
6695 MachineMemOperand *MMO = MF.getMachineMemOperand(
6696 PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges);
6697 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
6700 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
6701 EVT VT, const SDLoc &dl, SDValue Chain,
6702 SDValue Ptr, SDValue Offset, EVT MemVT,
6703 MachineMemOperand *MMO) {
6704 if (VT == MemVT) {
6705 ExtType = ISD::NON_EXTLOAD;
6706 } else if (ExtType == ISD::NON_EXTLOAD) {
6707 assert(VT == MemVT && "Non-extending load from different memory type!");
6708 } else {
6709 // Extending load.
6710 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
6711 "Should only be an extending load, not truncating!");
6712 assert(VT.isInteger() == MemVT.isInteger() &&
6713 "Cannot convert from FP to Int or Int -> FP!");
6714 assert(VT.isVector() == MemVT.isVector() &&
6715 "Cannot use an ext load to convert to or from a vector!");
6716 assert((!VT.isVector() ||
6717 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
6718 "Cannot use an ext load to change the number of vector elements!");
6721 bool Indexed = AM != ISD::UNINDEXED;
6722 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
6724 SDVTList VTs = Indexed ?
6725 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
6726 SDValue Ops[] = { Chain, Ptr, Offset };
6727 FoldingSetNodeID ID;
6728 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
6729 ID.AddInteger(MemVT.getRawBits());
6730 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
6731 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
6732 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6733 void *IP = nullptr;
6734 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6735 cast<LoadSDNode>(E)->refineAlignment(MMO);
6736 return SDValue(E, 0);
6738 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
6739 ExtType, MemVT, MMO);
6740 createOperands(N, Ops);
6742 CSEMap.InsertNode(N, IP);
6743 InsertNode(N);
6744 SDValue V(N, 0);
6745 NewSDValueDbgMsg(V, "Creating new node: ", this);
6746 return V;
6749 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
6750 SDValue Ptr, MachinePointerInfo PtrInfo,
6751 unsigned Alignment,
6752 MachineMemOperand::Flags MMOFlags,
6753 const AAMDNodes &AAInfo, const MDNode *Ranges) {
6754 SDValue Undef = getUNDEF(Ptr.getValueType());
6755 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
6756 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
6759 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
6760 SDValue Ptr, MachineMemOperand *MMO) {
6761 SDValue Undef = getUNDEF(Ptr.getValueType());
6762 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
6763 VT, MMO);
6766 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
6767 EVT VT, SDValue Chain, SDValue Ptr,
6768 MachinePointerInfo PtrInfo, EVT MemVT,
6769 unsigned Alignment,
6770 MachineMemOperand::Flags MMOFlags,
6771 const AAMDNodes &AAInfo) {
6772 SDValue Undef = getUNDEF(Ptr.getValueType());
6773 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
6774 MemVT, Alignment, MMOFlags, AAInfo);
6777 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
6778 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
6779 MachineMemOperand *MMO) {
6780 SDValue Undef = getUNDEF(Ptr.getValueType());
6781 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
6782 MemVT, MMO);
6785 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
6786 SDValue Base, SDValue Offset,
6787 ISD::MemIndexedMode AM) {
6788 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
6789 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
6790 // Don't propagate the invariant or dereferenceable flags.
6791 auto MMOFlags =
6792 LD->getMemOperand()->getFlags() &
6793 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
6794 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
6795 LD->getChain(), Base, Offset, LD->getPointerInfo(),
6796 LD->getMemoryVT(), LD->getAlignment(), MMOFlags,
6797 LD->getAAInfo());
6800 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6801 SDValue Ptr, MachinePointerInfo PtrInfo,
6802 unsigned Alignment,
6803 MachineMemOperand::Flags MMOFlags,
6804 const AAMDNodes &AAInfo) {
6805 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
6806 if (Alignment == 0) // Ensure that codegen never sees alignment 0
6807 Alignment = getEVTAlignment(Val.getValueType());
6809 MMOFlags |= MachineMemOperand::MOStore;
6810 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
6812 if (PtrInfo.V.isNull())
6813 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
6815 MachineFunction &MF = getMachineFunction();
6816 MachineMemOperand *MMO = MF.getMachineMemOperand(
6817 PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo);
6818 return getStore(Chain, dl, Val, Ptr, MMO);
6821 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6822 SDValue Ptr, MachineMemOperand *MMO) {
6823 assert(Chain.getValueType() == MVT::Other &&
6824 "Invalid chain type");
6825 EVT VT = Val.getValueType();
6826 SDVTList VTs = getVTList(MVT::Other);
6827 SDValue Undef = getUNDEF(Ptr.getValueType());
6828 SDValue Ops[] = { Chain, Val, Ptr, Undef };
6829 FoldingSetNodeID ID;
6830 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6831 ID.AddInteger(VT.getRawBits());
6832 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
6833 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
6834 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6835 void *IP = nullptr;
6836 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6837 cast<StoreSDNode>(E)->refineAlignment(MMO);
6838 return SDValue(E, 0);
6840 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6841 ISD::UNINDEXED, false, VT, MMO);
6842 createOperands(N, Ops);
6844 CSEMap.InsertNode(N, IP);
6845 InsertNode(N);
6846 SDValue V(N, 0);
6847 NewSDValueDbgMsg(V, "Creating new node: ", this);
6848 return V;
6851 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6852 SDValue Ptr, MachinePointerInfo PtrInfo,
6853 EVT SVT, unsigned Alignment,
6854 MachineMemOperand::Flags MMOFlags,
6855 const AAMDNodes &AAInfo) {
6856 assert(Chain.getValueType() == MVT::Other &&
6857 "Invalid chain type");
6858 if (Alignment == 0) // Ensure that codegen never sees alignment 0
6859 Alignment = getEVTAlignment(SVT);
6861 MMOFlags |= MachineMemOperand::MOStore;
6862 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
6864 if (PtrInfo.V.isNull())
6865 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
6867 MachineFunction &MF = getMachineFunction();
6868 MachineMemOperand *MMO = MF.getMachineMemOperand(
6869 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
6870 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
6873 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6874 SDValue Ptr, EVT SVT,
6875 MachineMemOperand *MMO) {
6876 EVT VT = Val.getValueType();
6878 assert(Chain.getValueType() == MVT::Other &&
6879 "Invalid chain type");
6880 if (VT == SVT)
6881 return getStore(Chain, dl, Val, Ptr, MMO);
6883 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
6884 "Should only be a truncating store, not extending!");
6885 assert(VT.isInteger() == SVT.isInteger() &&
6886 "Can't do FP-INT conversion!");
6887 assert(VT.isVector() == SVT.isVector() &&
6888 "Cannot use trunc store to convert to or from a vector!");
6889 assert((!VT.isVector() ||
6890 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
6891 "Cannot use trunc store to change the number of vector elements!");
6893 SDVTList VTs = getVTList(MVT::Other);
6894 SDValue Undef = getUNDEF(Ptr.getValueType());
6895 SDValue Ops[] = { Chain, Val, Ptr, Undef };
6896 FoldingSetNodeID ID;
6897 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6898 ID.AddInteger(SVT.getRawBits());
6899 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
6900 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
6901 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6902 void *IP = nullptr;
6903 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6904 cast<StoreSDNode>(E)->refineAlignment(MMO);
6905 return SDValue(E, 0);
6907 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6908 ISD::UNINDEXED, true, SVT, MMO);
6909 createOperands(N, Ops);
6911 CSEMap.InsertNode(N, IP);
6912 InsertNode(N);
6913 SDValue V(N, 0);
6914 NewSDValueDbgMsg(V, "Creating new node: ", this);
6915 return V;
6918 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
6919 SDValue Base, SDValue Offset,
6920 ISD::MemIndexedMode AM) {
6921 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
6922 assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
6923 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
6924 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
6925 FoldingSetNodeID ID;
6926 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6927 ID.AddInteger(ST->getMemoryVT().getRawBits());
6928 ID.AddInteger(ST->getRawSubclassData());
6929 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
6930 void *IP = nullptr;
6931 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
6932 return SDValue(E, 0);
6934 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
6935 ST->isTruncatingStore(), ST->getMemoryVT(),
6936 ST->getMemOperand());
6937 createOperands(N, Ops);
6939 CSEMap.InsertNode(N, IP);
6940 InsertNode(N);
6941 SDValue V(N, 0);
6942 NewSDValueDbgMsg(V, "Creating new node: ", this);
6943 return V;
6946 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
6947 SDValue Ptr, SDValue Mask, SDValue PassThru,
6948 EVT MemVT, MachineMemOperand *MMO,
6949 ISD::LoadExtType ExtTy, bool isExpanding) {
6950 SDVTList VTs = getVTList(VT, MVT::Other);
6951 SDValue Ops[] = { Chain, Ptr, Mask, PassThru };
6952 FoldingSetNodeID ID;
6953 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
6954 ID.AddInteger(MemVT.getRawBits());
6955 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
6956 dl.getIROrder(), VTs, ExtTy, isExpanding, MemVT, MMO));
6957 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6958 void *IP = nullptr;
6959 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6960 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
6961 return SDValue(E, 0);
6963 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6964 ExtTy, isExpanding, MemVT, MMO);
6965 createOperands(N, Ops);
6967 CSEMap.InsertNode(N, IP);
6968 InsertNode(N);
6969 SDValue V(N, 0);
6970 NewSDValueDbgMsg(V, "Creating new node: ", this);
6971 return V;
6974 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
6975 SDValue Val, SDValue Ptr, SDValue Mask,
6976 EVT MemVT, MachineMemOperand *MMO,
6977 bool IsTruncating, bool IsCompressing) {
6978 assert(Chain.getValueType() == MVT::Other &&
6979 "Invalid chain type");
6980 SDVTList VTs = getVTList(MVT::Other);
6981 SDValue Ops[] = { Chain, Val, Ptr, Mask };
6982 FoldingSetNodeID ID;
6983 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
6984 ID.AddInteger(MemVT.getRawBits());
6985 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
6986 dl.getIROrder(), VTs, IsTruncating, IsCompressing, MemVT, MMO));
6987 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6988 void *IP = nullptr;
6989 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6990 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
6991 return SDValue(E, 0);
6993 auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6994 IsTruncating, IsCompressing, MemVT, MMO);
6995 createOperands(N, Ops);
6997 CSEMap.InsertNode(N, IP);
6998 InsertNode(N);
6999 SDValue V(N, 0);
7000 NewSDValueDbgMsg(V, "Creating new node: ", this);
7001 return V;
7004 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
7005 ArrayRef<SDValue> Ops,
7006 MachineMemOperand *MMO,
7007 ISD::MemIndexType IndexType) {
7008 assert(Ops.size() == 6 && "Incompatible number of operands");
7010 FoldingSetNodeID ID;
7011 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
7012 ID.AddInteger(VT.getRawBits());
7013 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
7014 dl.getIROrder(), VTs, VT, MMO, IndexType));
7015 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7016 void *IP = nullptr;
7017 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7018 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
7019 return SDValue(E, 0);
7022 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7023 VTs, VT, MMO, IndexType);
7024 createOperands(N, Ops);
7026 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
7027 "Incompatible type of the PassThru value in MaskedGatherSDNode");
7028 assert(N->getMask().getValueType().getVectorNumElements() ==
7029 N->getValueType(0).getVectorNumElements() &&
7030 "Vector width mismatch between mask and data");
7031 assert(N->getIndex().getValueType().getVectorNumElements() >=
7032 N->getValueType(0).getVectorNumElements() &&
7033 "Vector width mismatch between index and data");
7034 assert(isa<ConstantSDNode>(N->getScale()) &&
7035 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7036 "Scale should be a constant power of 2");
7038 CSEMap.InsertNode(N, IP);
7039 InsertNode(N);
7040 SDValue V(N, 0);
7041 NewSDValueDbgMsg(V, "Creating new node: ", this);
7042 return V;
7045 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
7046 ArrayRef<SDValue> Ops,
7047 MachineMemOperand *MMO,
7048 ISD::MemIndexType IndexType) {
7049 assert(Ops.size() == 6 && "Incompatible number of operands");
7051 FoldingSetNodeID ID;
7052 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
7053 ID.AddInteger(VT.getRawBits());
7054 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
7055 dl.getIROrder(), VTs, VT, MMO, IndexType));
7056 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7057 void *IP = nullptr;
7058 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7059 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
7060 return SDValue(E, 0);
7062 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7063 VTs, VT, MMO, IndexType);
7064 createOperands(N, Ops);
7066 assert(N->getMask().getValueType().getVectorNumElements() ==
7067 N->getValue().getValueType().getVectorNumElements() &&
7068 "Vector width mismatch between mask and data");
7069 assert(N->getIndex().getValueType().getVectorNumElements() >=
7070 N->getValue().getValueType().getVectorNumElements() &&
7071 "Vector width mismatch between index and data");
7072 assert(isa<ConstantSDNode>(N->getScale()) &&
7073 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7074 "Scale should be a constant power of 2");
7076 CSEMap.InsertNode(N, IP);
7077 InsertNode(N);
7078 SDValue V(N, 0);
7079 NewSDValueDbgMsg(V, "Creating new node: ", this);
7080 return V;
7083 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
7084 // select undef, T, F --> T (if T is a constant), otherwise F
7085 // select, ?, undef, F --> F
7086 // select, ?, T, undef --> T
7087 if (Cond.isUndef())
7088 return isConstantValueOfAnyType(T) ? T : F;
7089 if (T.isUndef())
7090 return F;
7091 if (F.isUndef())
7092 return T;
7094 // select true, T, F --> T
7095 // select false, T, F --> F
7096 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
7097 return CondC->isNullValue() ? F : T;
7099 // TODO: This should simplify VSELECT with constant condition using something
7100 // like this (but check boolean contents to be complete?):
7101 // if (ISD::isBuildVectorAllOnes(Cond.getNode()))
7102 // return T;
7103 // if (ISD::isBuildVectorAllZeros(Cond.getNode()))
7104 // return F;
7106 // select ?, T, T --> T
7107 if (T == F)
7108 return T;
7110 return SDValue();
7113 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
7114 // shift undef, Y --> 0 (can always assume that the undef value is 0)
7115 if (X.isUndef())
7116 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
7117 // shift X, undef --> undef (because it may shift by the bitwidth)
7118 if (Y.isUndef())
7119 return getUNDEF(X.getValueType());
7121 // shift 0, Y --> 0
7122 // shift X, 0 --> X
7123 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
7124 return X;
7126 // shift X, C >= bitwidth(X) --> undef
7127 // All vector elements must be too big (or undef) to avoid partial undefs.
7128 auto isShiftTooBig = [X](ConstantSDNode *Val) {
7129 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
7131 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
7132 return getUNDEF(X.getValueType());
7134 return SDValue();
7137 // TODO: Use fast-math-flags to enable more simplifications.
7138 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y) {
7139 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
7140 if (!YC)
7141 return SDValue();
7143 // X + -0.0 --> X
7144 if (Opcode == ISD::FADD)
7145 if (YC->getValueAPF().isNegZero())
7146 return X;
7148 // X - +0.0 --> X
7149 if (Opcode == ISD::FSUB)
7150 if (YC->getValueAPF().isPosZero())
7151 return X;
7153 // X * 1.0 --> X
7154 // X / 1.0 --> X
7155 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
7156 if (YC->getValueAPF().isExactlyValue(1.0))
7157 return X;
7159 return SDValue();
7162 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
7163 SDValue Ptr, SDValue SV, unsigned Align) {
7164 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
7165 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
7168 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7169 ArrayRef<SDUse> Ops) {
7170 switch (Ops.size()) {
7171 case 0: return getNode(Opcode, DL, VT);
7172 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
7173 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
7174 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
7175 default: break;
7178 // Copy from an SDUse array into an SDValue array for use with
7179 // the regular getNode logic.
7180 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
7181 return getNode(Opcode, DL, VT, NewOps);
7184 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7185 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7186 unsigned NumOps = Ops.size();
7187 switch (NumOps) {
7188 case 0: return getNode(Opcode, DL, VT);
7189 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
7190 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
7191 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
7192 default: break;
7195 switch (Opcode) {
7196 default: break;
7197 case ISD::BUILD_VECTOR:
7198 // Attempt to simplify BUILD_VECTOR.
7199 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7200 return V;
7201 break;
7202 case ISD::CONCAT_VECTORS:
7203 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
7204 return V;
7205 break;
7206 case ISD::SELECT_CC:
7207 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
7208 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
7209 "LHS and RHS of condition must have same type!");
7210 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7211 "True and False arms of SelectCC must have same type!");
7212 assert(Ops[2].getValueType() == VT &&
7213 "select_cc node must be of same type as true and false value!");
7214 break;
7215 case ISD::BR_CC:
7216 assert(NumOps == 5 && "BR_CC takes 5 operands!");
7217 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7218 "LHS/RHS of comparison should match types!");
7219 break;
7222 // Memoize nodes.
7223 SDNode *N;
7224 SDVTList VTs = getVTList(VT);
7226 if (VT != MVT::Glue) {
7227 FoldingSetNodeID ID;
7228 AddNodeIDNode(ID, Opcode, VTs, Ops);
7229 void *IP = nullptr;
7231 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7232 return SDValue(E, 0);
7234 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7235 createOperands(N, Ops);
7237 CSEMap.InsertNode(N, IP);
7238 } else {
7239 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7240 createOperands(N, Ops);
7243 InsertNode(N);
7244 SDValue V(N, 0);
7245 NewSDValueDbgMsg(V, "Creating new node: ", this);
7246 return V;
7249 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7250 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
7251 return getNode(Opcode, DL, getVTList(ResultTys), Ops);
7254 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7255 ArrayRef<SDValue> Ops) {
7256 if (VTList.NumVTs == 1)
7257 return getNode(Opcode, DL, VTList.VTs[0], Ops);
7259 #if 0
7260 switch (Opcode) {
7261 // FIXME: figure out how to safely handle things like
7262 // int foo(int x) { return 1 << (x & 255); }
7263 // int bar() { return foo(256); }
7264 case ISD::SRA_PARTS:
7265 case ISD::SRL_PARTS:
7266 case ISD::SHL_PARTS:
7267 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7268 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
7269 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7270 else if (N3.getOpcode() == ISD::AND)
7271 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
7272 // If the and is only masking out bits that cannot effect the shift,
7273 // eliminate the and.
7274 unsigned NumBits = VT.getScalarSizeInBits()*2;
7275 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
7276 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7278 break;
7280 #endif
7282 // Memoize the node unless it returns a flag.
7283 SDNode *N;
7284 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7285 FoldingSetNodeID ID;
7286 AddNodeIDNode(ID, Opcode, VTList, Ops);
7287 void *IP = nullptr;
7288 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7289 return SDValue(E, 0);
7291 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7292 createOperands(N, Ops);
7293 CSEMap.InsertNode(N, IP);
7294 } else {
7295 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7296 createOperands(N, Ops);
7298 InsertNode(N);
7299 SDValue V(N, 0);
7300 NewSDValueDbgMsg(V, "Creating new node: ", this);
7301 return V;
7304 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7305 SDVTList VTList) {
7306 return getNode(Opcode, DL, VTList, None);
7309 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7310 SDValue N1) {
7311 SDValue Ops[] = { N1 };
7312 return getNode(Opcode, DL, VTList, Ops);
7315 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7316 SDValue N1, SDValue N2) {
7317 SDValue Ops[] = { N1, N2 };
7318 return getNode(Opcode, DL, VTList, Ops);
7321 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7322 SDValue N1, SDValue N2, SDValue N3) {
7323 SDValue Ops[] = { N1, N2, N3 };
7324 return getNode(Opcode, DL, VTList, Ops);
7327 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7328 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
7329 SDValue Ops[] = { N1, N2, N3, N4 };
7330 return getNode(Opcode, DL, VTList, Ops);
7333 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7334 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
7335 SDValue N5) {
7336 SDValue Ops[] = { N1, N2, N3, N4, N5 };
7337 return getNode(Opcode, DL, VTList, Ops);
7340 SDVTList SelectionDAG::getVTList(EVT VT) {
7341 return makeVTList(SDNode::getValueTypeList(VT), 1);
7344 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
7345 FoldingSetNodeID ID;
7346 ID.AddInteger(2U);
7347 ID.AddInteger(VT1.getRawBits());
7348 ID.AddInteger(VT2.getRawBits());
7350 void *IP = nullptr;
7351 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7352 if (!Result) {
7353 EVT *Array = Allocator.Allocate<EVT>(2);
7354 Array[0] = VT1;
7355 Array[1] = VT2;
7356 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
7357 VTListMap.InsertNode(Result, IP);
7359 return Result->getSDVTList();
7362 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
7363 FoldingSetNodeID ID;
7364 ID.AddInteger(3U);
7365 ID.AddInteger(VT1.getRawBits());
7366 ID.AddInteger(VT2.getRawBits());
7367 ID.AddInteger(VT3.getRawBits());
7369 void *IP = nullptr;
7370 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7371 if (!Result) {
7372 EVT *Array = Allocator.Allocate<EVT>(3);
7373 Array[0] = VT1;
7374 Array[1] = VT2;
7375 Array[2] = VT3;
7376 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
7377 VTListMap.InsertNode(Result, IP);
7379 return Result->getSDVTList();
7382 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
7383 FoldingSetNodeID ID;
7384 ID.AddInteger(4U);
7385 ID.AddInteger(VT1.getRawBits());
7386 ID.AddInteger(VT2.getRawBits());
7387 ID.AddInteger(VT3.getRawBits());
7388 ID.AddInteger(VT4.getRawBits());
7390 void *IP = nullptr;
7391 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7392 if (!Result) {
7393 EVT *Array = Allocator.Allocate<EVT>(4);
7394 Array[0] = VT1;
7395 Array[1] = VT2;
7396 Array[2] = VT3;
7397 Array[3] = VT4;
7398 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
7399 VTListMap.InsertNode(Result, IP);
7401 return Result->getSDVTList();
7404 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
7405 unsigned NumVTs = VTs.size();
7406 FoldingSetNodeID ID;
7407 ID.AddInteger(NumVTs);
7408 for (unsigned index = 0; index < NumVTs; index++) {
7409 ID.AddInteger(VTs[index].getRawBits());
7412 void *IP = nullptr;
7413 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7414 if (!Result) {
7415 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
7416 llvm::copy(VTs, Array);
7417 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
7418 VTListMap.InsertNode(Result, IP);
7420 return Result->getSDVTList();
7424 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
7425 /// specified operands. If the resultant node already exists in the DAG,
7426 /// this does not modify the specified node, instead it returns the node that
7427 /// already exists. If the resultant node does not exist in the DAG, the
7428 /// input node is returned. As a degenerate case, if you specify the same
7429 /// input operands as the node already has, the input node is returned.
7430 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
7431 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
7433 // Check to see if there is no change.
7434 if (Op == N->getOperand(0)) return N;
7436 // See if the modified node already exists.
7437 void *InsertPos = nullptr;
7438 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
7439 return Existing;
7441 // Nope it doesn't. Remove the node from its current place in the maps.
7442 if (InsertPos)
7443 if (!RemoveNodeFromCSEMaps(N))
7444 InsertPos = nullptr;
7446 // Now we update the operands.
7447 N->OperandList[0].set(Op);
7449 updateDivergence(N);
7450 // If this gets put into a CSE map, add it.
7451 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7452 return N;
7455 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
7456 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
7458 // Check to see if there is no change.
7459 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
7460 return N; // No operands changed, just return the input node.
7462 // See if the modified node already exists.
7463 void *InsertPos = nullptr;
7464 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
7465 return Existing;
7467 // Nope it doesn't. Remove the node from its current place in the maps.
7468 if (InsertPos)
7469 if (!RemoveNodeFromCSEMaps(N))
7470 InsertPos = nullptr;
7472 // Now we update the operands.
7473 if (N->OperandList[0] != Op1)
7474 N->OperandList[0].set(Op1);
7475 if (N->OperandList[1] != Op2)
7476 N->OperandList[1].set(Op2);
7478 updateDivergence(N);
7479 // If this gets put into a CSE map, add it.
7480 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7481 return N;
7484 SDNode *SelectionDAG::
7485 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
7486 SDValue Ops[] = { Op1, Op2, Op3 };
7487 return UpdateNodeOperands(N, Ops);
7490 SDNode *SelectionDAG::
7491 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
7492 SDValue Op3, SDValue Op4) {
7493 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
7494 return UpdateNodeOperands(N, Ops);
7497 SDNode *SelectionDAG::
7498 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
7499 SDValue Op3, SDValue Op4, SDValue Op5) {
7500 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
7501 return UpdateNodeOperands(N, Ops);
7504 SDNode *SelectionDAG::
7505 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
7506 unsigned NumOps = Ops.size();
7507 assert(N->getNumOperands() == NumOps &&
7508 "Update with wrong number of operands");
7510 // If no operands changed just return the input node.
7511 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
7512 return N;
7514 // See if the modified node already exists.
7515 void *InsertPos = nullptr;
7516 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
7517 return Existing;
7519 // Nope it doesn't. Remove the node from its current place in the maps.
7520 if (InsertPos)
7521 if (!RemoveNodeFromCSEMaps(N))
7522 InsertPos = nullptr;
7524 // Now we update the operands.
7525 for (unsigned i = 0; i != NumOps; ++i)
7526 if (N->OperandList[i] != Ops[i])
7527 N->OperandList[i].set(Ops[i]);
7529 updateDivergence(N);
7530 // If this gets put into a CSE map, add it.
7531 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7532 return N;
7535 /// DropOperands - Release the operands and set this node to have
7536 /// zero operands.
7537 void SDNode::DropOperands() {
7538 // Unlike the code in MorphNodeTo that does this, we don't need to
7539 // watch for dead nodes here.
7540 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
7541 SDUse &Use = *I++;
7542 Use.set(SDValue());
7546 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
7547 ArrayRef<MachineMemOperand *> NewMemRefs) {
7548 if (NewMemRefs.empty()) {
7549 N->clearMemRefs();
7550 return;
7553 // Check if we can avoid allocating by storing a single reference directly.
7554 if (NewMemRefs.size() == 1) {
7555 N->MemRefs = NewMemRefs[0];
7556 N->NumMemRefs = 1;
7557 return;
7560 MachineMemOperand **MemRefsBuffer =
7561 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
7562 llvm::copy(NewMemRefs, MemRefsBuffer);
7563 N->MemRefs = MemRefsBuffer;
7564 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
7567 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
7568 /// machine opcode.
7570 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7571 EVT VT) {
7572 SDVTList VTs = getVTList(VT);
7573 return SelectNodeTo(N, MachineOpc, VTs, None);
7576 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7577 EVT VT, SDValue Op1) {
7578 SDVTList VTs = getVTList(VT);
7579 SDValue Ops[] = { Op1 };
7580 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7583 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7584 EVT VT, SDValue Op1,
7585 SDValue Op2) {
7586 SDVTList VTs = getVTList(VT);
7587 SDValue Ops[] = { Op1, Op2 };
7588 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7591 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7592 EVT VT, SDValue Op1,
7593 SDValue Op2, SDValue Op3) {
7594 SDVTList VTs = getVTList(VT);
7595 SDValue Ops[] = { Op1, Op2, Op3 };
7596 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7599 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7600 EVT VT, ArrayRef<SDValue> Ops) {
7601 SDVTList VTs = getVTList(VT);
7602 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7605 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7606 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
7607 SDVTList VTs = getVTList(VT1, VT2);
7608 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7611 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7612 EVT VT1, EVT VT2) {
7613 SDVTList VTs = getVTList(VT1, VT2);
7614 return SelectNodeTo(N, MachineOpc, VTs, None);
7617 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7618 EVT VT1, EVT VT2, EVT VT3,
7619 ArrayRef<SDValue> Ops) {
7620 SDVTList VTs = getVTList(VT1, VT2, VT3);
7621 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7624 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7625 EVT VT1, EVT VT2,
7626 SDValue Op1, SDValue Op2) {
7627 SDVTList VTs = getVTList(VT1, VT2);
7628 SDValue Ops[] = { Op1, Op2 };
7629 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7632 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7633 SDVTList VTs,ArrayRef<SDValue> Ops) {
7634 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
7635 // Reset the NodeID to -1.
7636 New->setNodeId(-1);
7637 if (New != N) {
7638 ReplaceAllUsesWith(N, New);
7639 RemoveDeadNode(N);
7641 return New;
7644 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
7645 /// the line number information on the merged node since it is not possible to
7646 /// preserve the information that operation is associated with multiple lines.
7647 /// This will make the debugger working better at -O0, were there is a higher
7648 /// probability having other instructions associated with that line.
7650 /// For IROrder, we keep the smaller of the two
7651 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
7652 DebugLoc NLoc = N->getDebugLoc();
7653 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
7654 N->setDebugLoc(DebugLoc());
7656 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
7657 N->setIROrder(Order);
7658 return N;
7661 /// MorphNodeTo - This *mutates* the specified node to have the specified
7662 /// return type, opcode, and operands.
7664 /// Note that MorphNodeTo returns the resultant node. If there is already a
7665 /// node of the specified opcode and operands, it returns that node instead of
7666 /// the current one. Note that the SDLoc need not be the same.
7668 /// Using MorphNodeTo is faster than creating a new node and swapping it in
7669 /// with ReplaceAllUsesWith both because it often avoids allocating a new
7670 /// node, and because it doesn't require CSE recalculation for any of
7671 /// the node's users.
7673 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
7674 /// As a consequence it isn't appropriate to use from within the DAG combiner or
7675 /// the legalizer which maintain worklists that would need to be updated when
7676 /// deleting things.
7677 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
7678 SDVTList VTs, ArrayRef<SDValue> Ops) {
7679 // If an identical node already exists, use it.
7680 void *IP = nullptr;
7681 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
7682 FoldingSetNodeID ID;
7683 AddNodeIDNode(ID, Opc, VTs, Ops);
7684 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
7685 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
7688 if (!RemoveNodeFromCSEMaps(N))
7689 IP = nullptr;
7691 // Start the morphing.
7692 N->NodeType = Opc;
7693 N->ValueList = VTs.VTs;
7694 N->NumValues = VTs.NumVTs;
7696 // Clear the operands list, updating used nodes to remove this from their
7697 // use list. Keep track of any operands that become dead as a result.
7698 SmallPtrSet<SDNode*, 16> DeadNodeSet;
7699 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
7700 SDUse &Use = *I++;
7701 SDNode *Used = Use.getNode();
7702 Use.set(SDValue());
7703 if (Used->use_empty())
7704 DeadNodeSet.insert(Used);
7707 // For MachineNode, initialize the memory references information.
7708 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
7709 MN->clearMemRefs();
7711 // Swap for an appropriately sized array from the recycler.
7712 removeOperands(N);
7713 createOperands(N, Ops);
7715 // Delete any nodes that are still dead after adding the uses for the
7716 // new operands.
7717 if (!DeadNodeSet.empty()) {
7718 SmallVector<SDNode *, 16> DeadNodes;
7719 for (SDNode *N : DeadNodeSet)
7720 if (N->use_empty())
7721 DeadNodes.push_back(N);
7722 RemoveDeadNodes(DeadNodes);
7725 if (IP)
7726 CSEMap.InsertNode(N, IP); // Memoize the new node.
7727 return N;
7730 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
7731 unsigned OrigOpc = Node->getOpcode();
7732 unsigned NewOpc;
7733 switch (OrigOpc) {
7734 default:
7735 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
7736 case ISD::STRICT_FADD: NewOpc = ISD::FADD; break;
7737 case ISD::STRICT_FSUB: NewOpc = ISD::FSUB; break;
7738 case ISD::STRICT_FMUL: NewOpc = ISD::FMUL; break;
7739 case ISD::STRICT_FDIV: NewOpc = ISD::FDIV; break;
7740 case ISD::STRICT_FREM: NewOpc = ISD::FREM; break;
7741 case ISD::STRICT_FMA: NewOpc = ISD::FMA; break;
7742 case ISD::STRICT_FSQRT: NewOpc = ISD::FSQRT; break;
7743 case ISD::STRICT_FPOW: NewOpc = ISD::FPOW; break;
7744 case ISD::STRICT_FPOWI: NewOpc = ISD::FPOWI; break;
7745 case ISD::STRICT_FSIN: NewOpc = ISD::FSIN; break;
7746 case ISD::STRICT_FCOS: NewOpc = ISD::FCOS; break;
7747 case ISD::STRICT_FEXP: NewOpc = ISD::FEXP; break;
7748 case ISD::STRICT_FEXP2: NewOpc = ISD::FEXP2; break;
7749 case ISD::STRICT_FLOG: NewOpc = ISD::FLOG; break;
7750 case ISD::STRICT_FLOG10: NewOpc = ISD::FLOG10; break;
7751 case ISD::STRICT_FLOG2: NewOpc = ISD::FLOG2; break;
7752 case ISD::STRICT_FRINT: NewOpc = ISD::FRINT; break;
7753 case ISD::STRICT_FNEARBYINT: NewOpc = ISD::FNEARBYINT; break;
7754 case ISD::STRICT_FMAXNUM: NewOpc = ISD::FMAXNUM; break;
7755 case ISD::STRICT_FMINNUM: NewOpc = ISD::FMINNUM; break;
7756 case ISD::STRICT_FCEIL: NewOpc = ISD::FCEIL; break;
7757 case ISD::STRICT_FFLOOR: NewOpc = ISD::FFLOOR; break;
7758 case ISD::STRICT_FROUND: NewOpc = ISD::FROUND; break;
7759 case ISD::STRICT_FTRUNC: NewOpc = ISD::FTRUNC; break;
7760 case ISD::STRICT_FP_ROUND: NewOpc = ISD::FP_ROUND; break;
7761 case ISD::STRICT_FP_EXTEND: NewOpc = ISD::FP_EXTEND; break;
7762 case ISD::STRICT_FP_TO_SINT: NewOpc = ISD::FP_TO_SINT; break;
7763 case ISD::STRICT_FP_TO_UINT: NewOpc = ISD::FP_TO_UINT; break;
7766 assert(Node->getNumValues() == 2 && "Unexpected number of results!");
7768 // We're taking this node out of the chain, so we need to re-link things.
7769 SDValue InputChain = Node->getOperand(0);
7770 SDValue OutputChain = SDValue(Node, 1);
7771 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
7773 SmallVector<SDValue, 3> Ops;
7774 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
7775 Ops.push_back(Node->getOperand(i));
7777 SDVTList VTs = getVTList(Node->getValueType(0));
7778 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
7780 // MorphNodeTo can operate in two ways: if an existing node with the
7781 // specified operands exists, it can just return it. Otherwise, it
7782 // updates the node in place to have the requested operands.
7783 if (Res == Node) {
7784 // If we updated the node in place, reset the node ID. To the isel,
7785 // this should be just like a newly allocated machine node.
7786 Res->setNodeId(-1);
7787 } else {
7788 ReplaceAllUsesWith(Node, Res);
7789 RemoveDeadNode(Node);
7792 return Res;
7795 /// getMachineNode - These are used for target selectors to create a new node
7796 /// with specified return type(s), MachineInstr opcode, and operands.
7798 /// Note that getMachineNode returns the resultant node. If there is already a
7799 /// node of the specified opcode and operands, it returns that node instead of
7800 /// the current one.
7801 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7802 EVT VT) {
7803 SDVTList VTs = getVTList(VT);
7804 return getMachineNode(Opcode, dl, VTs, None);
7807 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7808 EVT VT, SDValue Op1) {
7809 SDVTList VTs = getVTList(VT);
7810 SDValue Ops[] = { Op1 };
7811 return getMachineNode(Opcode, dl, VTs, Ops);
7814 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7815 EVT VT, SDValue Op1, SDValue Op2) {
7816 SDVTList VTs = getVTList(VT);
7817 SDValue Ops[] = { Op1, Op2 };
7818 return getMachineNode(Opcode, dl, VTs, Ops);
7821 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7822 EVT VT, SDValue Op1, SDValue Op2,
7823 SDValue Op3) {
7824 SDVTList VTs = getVTList(VT);
7825 SDValue Ops[] = { Op1, Op2, Op3 };
7826 return getMachineNode(Opcode, dl, VTs, Ops);
7829 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7830 EVT VT, ArrayRef<SDValue> Ops) {
7831 SDVTList VTs = getVTList(VT);
7832 return getMachineNode(Opcode, dl, VTs, Ops);
7835 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7836 EVT VT1, EVT VT2, SDValue Op1,
7837 SDValue Op2) {
7838 SDVTList VTs = getVTList(VT1, VT2);
7839 SDValue Ops[] = { Op1, Op2 };
7840 return getMachineNode(Opcode, dl, VTs, Ops);
7843 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7844 EVT VT1, EVT VT2, SDValue Op1,
7845 SDValue Op2, SDValue Op3) {
7846 SDVTList VTs = getVTList(VT1, VT2);
7847 SDValue Ops[] = { Op1, Op2, Op3 };
7848 return getMachineNode(Opcode, dl, VTs, Ops);
7851 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7852 EVT VT1, EVT VT2,
7853 ArrayRef<SDValue> Ops) {
7854 SDVTList VTs = getVTList(VT1, VT2);
7855 return getMachineNode(Opcode, dl, VTs, Ops);
7858 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7859 EVT VT1, EVT VT2, EVT VT3,
7860 SDValue Op1, SDValue Op2) {
7861 SDVTList VTs = getVTList(VT1, VT2, VT3);
7862 SDValue Ops[] = { Op1, Op2 };
7863 return getMachineNode(Opcode, dl, VTs, Ops);
7866 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7867 EVT VT1, EVT VT2, EVT VT3,
7868 SDValue Op1, SDValue Op2,
7869 SDValue Op3) {
7870 SDVTList VTs = getVTList(VT1, VT2, VT3);
7871 SDValue Ops[] = { Op1, Op2, Op3 };
7872 return getMachineNode(Opcode, dl, VTs, Ops);
7875 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7876 EVT VT1, EVT VT2, EVT VT3,
7877 ArrayRef<SDValue> Ops) {
7878 SDVTList VTs = getVTList(VT1, VT2, VT3);
7879 return getMachineNode(Opcode, dl, VTs, Ops);
7882 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7883 ArrayRef<EVT> ResultTys,
7884 ArrayRef<SDValue> Ops) {
7885 SDVTList VTs = getVTList(ResultTys);
7886 return getMachineNode(Opcode, dl, VTs, Ops);
7889 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
7890 SDVTList VTs,
7891 ArrayRef<SDValue> Ops) {
7892 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
7893 MachineSDNode *N;
7894 void *IP = nullptr;
7896 if (DoCSE) {
7897 FoldingSetNodeID ID;
7898 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
7899 IP = nullptr;
7900 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
7901 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
7905 // Allocate a new MachineSDNode.
7906 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7907 createOperands(N, Ops);
7909 if (DoCSE)
7910 CSEMap.InsertNode(N, IP);
7912 InsertNode(N);
7913 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
7914 return N;
7917 /// getTargetExtractSubreg - A convenience function for creating
7918 /// TargetOpcode::EXTRACT_SUBREG nodes.
7919 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
7920 SDValue Operand) {
7921 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
7922 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
7923 VT, Operand, SRIdxVal);
7924 return SDValue(Subreg, 0);
7927 /// getTargetInsertSubreg - A convenience function for creating
7928 /// TargetOpcode::INSERT_SUBREG nodes.
7929 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
7930 SDValue Operand, SDValue Subreg) {
7931 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
7932 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
7933 VT, Operand, Subreg, SRIdxVal);
7934 return SDValue(Result, 0);
7937 /// getNodeIfExists - Get the specified node if it's already available, or
7938 /// else return NULL.
7939 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
7940 ArrayRef<SDValue> Ops,
7941 const SDNodeFlags Flags) {
7942 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
7943 FoldingSetNodeID ID;
7944 AddNodeIDNode(ID, Opcode, VTList, Ops);
7945 void *IP = nullptr;
7946 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
7947 E->intersectFlagsWith(Flags);
7948 return E;
7951 return nullptr;
7954 /// getDbgValue - Creates a SDDbgValue node.
7956 /// SDNode
7957 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
7958 SDNode *N, unsigned R, bool IsIndirect,
7959 const DebugLoc &DL, unsigned O) {
7960 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7961 "Expected inlined-at fields to agree");
7962 return new (DbgInfo->getAlloc())
7963 SDDbgValue(Var, Expr, N, R, IsIndirect, DL, O);
7966 /// Constant
7967 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
7968 DIExpression *Expr,
7969 const Value *C,
7970 const DebugLoc &DL, unsigned O) {
7971 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7972 "Expected inlined-at fields to agree");
7973 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, DL, O);
7976 /// FrameIndex
7977 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
7978 DIExpression *Expr, unsigned FI,
7979 bool IsIndirect,
7980 const DebugLoc &DL,
7981 unsigned O) {
7982 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7983 "Expected inlined-at fields to agree");
7984 return new (DbgInfo->getAlloc())
7985 SDDbgValue(Var, Expr, FI, IsIndirect, DL, O, SDDbgValue::FRAMEIX);
7988 /// VReg
7989 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var,
7990 DIExpression *Expr,
7991 unsigned VReg, bool IsIndirect,
7992 const DebugLoc &DL, unsigned O) {
7993 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7994 "Expected inlined-at fields to agree");
7995 return new (DbgInfo->getAlloc())
7996 SDDbgValue(Var, Expr, VReg, IsIndirect, DL, O, SDDbgValue::VREG);
7999 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
8000 unsigned OffsetInBits, unsigned SizeInBits,
8001 bool InvalidateDbg) {
8002 SDNode *FromNode = From.getNode();
8003 SDNode *ToNode = To.getNode();
8004 assert(FromNode && ToNode && "Can't modify dbg values");
8006 // PR35338
8007 // TODO: assert(From != To && "Redundant dbg value transfer");
8008 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
8009 if (From == To || FromNode == ToNode)
8010 return;
8012 if (!FromNode->getHasDebugValue())
8013 return;
8015 SmallVector<SDDbgValue *, 2> ClonedDVs;
8016 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
8017 if (Dbg->getKind() != SDDbgValue::SDNODE || Dbg->isInvalidated())
8018 continue;
8020 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
8022 // Just transfer the dbg value attached to From.
8023 if (Dbg->getResNo() != From.getResNo())
8024 continue;
8026 DIVariable *Var = Dbg->getVariable();
8027 auto *Expr = Dbg->getExpression();
8028 // If a fragment is requested, update the expression.
8029 if (SizeInBits) {
8030 // When splitting a larger (e.g., sign-extended) value whose
8031 // lower bits are described with an SDDbgValue, do not attempt
8032 // to transfer the SDDbgValue to the upper bits.
8033 if (auto FI = Expr->getFragmentInfo())
8034 if (OffsetInBits + SizeInBits > FI->SizeInBits)
8035 continue;
8036 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
8037 SizeInBits);
8038 if (!Fragment)
8039 continue;
8040 Expr = *Fragment;
8042 // Clone the SDDbgValue and move it to To.
8043 SDDbgValue *Clone =
8044 getDbgValue(Var, Expr, ToNode, To.getResNo(), Dbg->isIndirect(),
8045 Dbg->getDebugLoc(), Dbg->getOrder());
8046 ClonedDVs.push_back(Clone);
8048 if (InvalidateDbg) {
8049 // Invalidate value and indicate the SDDbgValue should not be emitted.
8050 Dbg->setIsInvalidated();
8051 Dbg->setIsEmitted();
8055 for (SDDbgValue *Dbg : ClonedDVs)
8056 AddDbgValue(Dbg, ToNode, false);
8059 void SelectionDAG::salvageDebugInfo(SDNode &N) {
8060 if (!N.getHasDebugValue())
8061 return;
8063 SmallVector<SDDbgValue *, 2> ClonedDVs;
8064 for (auto DV : GetDbgValues(&N)) {
8065 if (DV->isInvalidated())
8066 continue;
8067 switch (N.getOpcode()) {
8068 default:
8069 break;
8070 case ISD::ADD:
8071 SDValue N0 = N.getOperand(0);
8072 SDValue N1 = N.getOperand(1);
8073 if (!isConstantIntBuildVectorOrConstantInt(N0) &&
8074 isConstantIntBuildVectorOrConstantInt(N1)) {
8075 uint64_t Offset = N.getConstantOperandVal(1);
8076 // Rewrite an ADD constant node into a DIExpression. Since we are
8077 // performing arithmetic to compute the variable's *value* in the
8078 // DIExpression, we need to mark the expression with a
8079 // DW_OP_stack_value.
8080 auto *DIExpr = DV->getExpression();
8081 DIExpr =
8082 DIExpression::prepend(DIExpr, DIExpression::StackValue, Offset);
8083 SDDbgValue *Clone =
8084 getDbgValue(DV->getVariable(), DIExpr, N0.getNode(), N0.getResNo(),
8085 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder());
8086 ClonedDVs.push_back(Clone);
8087 DV->setIsInvalidated();
8088 DV->setIsEmitted();
8089 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
8090 N0.getNode()->dumprFull(this);
8091 dbgs() << " into " << *DIExpr << '\n');
8096 for (SDDbgValue *Dbg : ClonedDVs)
8097 AddDbgValue(Dbg, Dbg->getSDNode(), false);
8100 /// Creates a SDDbgLabel node.
8101 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
8102 const DebugLoc &DL, unsigned O) {
8103 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
8104 "Expected inlined-at fields to agree");
8105 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
8108 namespace {
8110 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
8111 /// pointed to by a use iterator is deleted, increment the use iterator
8112 /// so that it doesn't dangle.
8114 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
8115 SDNode::use_iterator &UI;
8116 SDNode::use_iterator &UE;
8118 void NodeDeleted(SDNode *N, SDNode *E) override {
8119 // Increment the iterator as needed.
8120 while (UI != UE && N == *UI)
8121 ++UI;
8124 public:
8125 RAUWUpdateListener(SelectionDAG &d,
8126 SDNode::use_iterator &ui,
8127 SDNode::use_iterator &ue)
8128 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
8131 } // end anonymous namespace
8133 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8134 /// This can cause recursive merging of nodes in the DAG.
8136 /// This version assumes From has a single result value.
8138 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
8139 SDNode *From = FromN.getNode();
8140 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
8141 "Cannot replace with this method!");
8142 assert(From != To.getNode() && "Cannot replace uses of with self");
8144 // Preserve Debug Values
8145 transferDbgValues(FromN, To);
8147 // Iterate over all the existing uses of From. New uses will be added
8148 // to the beginning of the use list, which we avoid visiting.
8149 // This specifically avoids visiting uses of From that arise while the
8150 // replacement is happening, because any such uses would be the result
8151 // of CSE: If an existing node looks like From after one of its operands
8152 // is replaced by To, we don't want to replace of all its users with To
8153 // too. See PR3018 for more info.
8154 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8155 RAUWUpdateListener Listener(*this, UI, UE);
8156 while (UI != UE) {
8157 SDNode *User = *UI;
8159 // This node is about to morph, remove its old self from the CSE maps.
8160 RemoveNodeFromCSEMaps(User);
8162 // A user can appear in a use list multiple times, and when this
8163 // happens the uses are usually next to each other in the list.
8164 // To help reduce the number of CSE recomputations, process all
8165 // the uses of this user that we can find this way.
8166 do {
8167 SDUse &Use = UI.getUse();
8168 ++UI;
8169 Use.set(To);
8170 if (To->isDivergent() != From->isDivergent())
8171 updateDivergence(User);
8172 } while (UI != UE && *UI == User);
8173 // Now that we have modified User, add it back to the CSE maps. If it
8174 // already exists there, recursively merge the results together.
8175 AddModifiedNodeToCSEMaps(User);
8178 // If we just RAUW'd the root, take note.
8179 if (FromN == getRoot())
8180 setRoot(To);
8183 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8184 /// This can cause recursive merging of nodes in the DAG.
8186 /// This version assumes that for each value of From, there is a
8187 /// corresponding value in To in the same position with the same type.
8189 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
8190 #ifndef NDEBUG
8191 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8192 assert((!From->hasAnyUseOfValue(i) ||
8193 From->getValueType(i) == To->getValueType(i)) &&
8194 "Cannot use this version of ReplaceAllUsesWith!");
8195 #endif
8197 // Handle the trivial case.
8198 if (From == To)
8199 return;
8201 // Preserve Debug Info. Only do this if there's a use.
8202 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8203 if (From->hasAnyUseOfValue(i)) {
8204 assert((i < To->getNumValues()) && "Invalid To location");
8205 transferDbgValues(SDValue(From, i), SDValue(To, i));
8208 // Iterate over just the existing users of From. See the comments in
8209 // the ReplaceAllUsesWith above.
8210 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8211 RAUWUpdateListener Listener(*this, UI, UE);
8212 while (UI != UE) {
8213 SDNode *User = *UI;
8215 // This node is about to morph, remove its old self from the CSE maps.
8216 RemoveNodeFromCSEMaps(User);
8218 // A user can appear in a use list multiple times, and when this
8219 // happens the uses are usually next to each other in the list.
8220 // To help reduce the number of CSE recomputations, process all
8221 // the uses of this user that we can find this way.
8222 do {
8223 SDUse &Use = UI.getUse();
8224 ++UI;
8225 Use.setNode(To);
8226 if (To->isDivergent() != From->isDivergent())
8227 updateDivergence(User);
8228 } while (UI != UE && *UI == User);
8230 // Now that we have modified User, add it back to the CSE maps. If it
8231 // already exists there, recursively merge the results together.
8232 AddModifiedNodeToCSEMaps(User);
8235 // If we just RAUW'd the root, take note.
8236 if (From == getRoot().getNode())
8237 setRoot(SDValue(To, getRoot().getResNo()));
8240 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8241 /// This can cause recursive merging of nodes in the DAG.
8243 /// This version can replace From with any result values. To must match the
8244 /// number and types of values returned by From.
8245 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
8246 if (From->getNumValues() == 1) // Handle the simple case efficiently.
8247 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
8249 // Preserve Debug Info.
8250 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8251 transferDbgValues(SDValue(From, i), To[i]);
8253 // Iterate over just the existing users of From. See the comments in
8254 // the ReplaceAllUsesWith above.
8255 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8256 RAUWUpdateListener Listener(*this, UI, UE);
8257 while (UI != UE) {
8258 SDNode *User = *UI;
8260 // This node is about to morph, remove its old self from the CSE maps.
8261 RemoveNodeFromCSEMaps(User);
8263 // A user can appear in a use list multiple times, and when this happens the
8264 // uses are usually next to each other in the list. To help reduce the
8265 // number of CSE and divergence recomputations, process all the uses of this
8266 // user that we can find this way.
8267 bool To_IsDivergent = false;
8268 do {
8269 SDUse &Use = UI.getUse();
8270 const SDValue &ToOp = To[Use.getResNo()];
8271 ++UI;
8272 Use.set(ToOp);
8273 To_IsDivergent |= ToOp->isDivergent();
8274 } while (UI != UE && *UI == User);
8276 if (To_IsDivergent != From->isDivergent())
8277 updateDivergence(User);
8279 // Now that we have modified User, add it back to the CSE maps. If it
8280 // already exists there, recursively merge the results together.
8281 AddModifiedNodeToCSEMaps(User);
8284 // If we just RAUW'd the root, take note.
8285 if (From == getRoot().getNode())
8286 setRoot(SDValue(To[getRoot().getResNo()]));
8289 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
8290 /// uses of other values produced by From.getNode() alone. The Deleted
8291 /// vector is handled the same way as for ReplaceAllUsesWith.
8292 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
8293 // Handle the really simple, really trivial case efficiently.
8294 if (From == To) return;
8296 // Handle the simple, trivial, case efficiently.
8297 if (From.getNode()->getNumValues() == 1) {
8298 ReplaceAllUsesWith(From, To);
8299 return;
8302 // Preserve Debug Info.
8303 transferDbgValues(From, To);
8305 // Iterate over just the existing users of From. See the comments in
8306 // the ReplaceAllUsesWith above.
8307 SDNode::use_iterator UI = From.getNode()->use_begin(),
8308 UE = From.getNode()->use_end();
8309 RAUWUpdateListener Listener(*this, UI, UE);
8310 while (UI != UE) {
8311 SDNode *User = *UI;
8312 bool UserRemovedFromCSEMaps = false;
8314 // A user can appear in a use list multiple times, and when this
8315 // happens the uses are usually next to each other in the list.
8316 // To help reduce the number of CSE recomputations, process all
8317 // the uses of this user that we can find this way.
8318 do {
8319 SDUse &Use = UI.getUse();
8321 // Skip uses of different values from the same node.
8322 if (Use.getResNo() != From.getResNo()) {
8323 ++UI;
8324 continue;
8327 // If this node hasn't been modified yet, it's still in the CSE maps,
8328 // so remove its old self from the CSE maps.
8329 if (!UserRemovedFromCSEMaps) {
8330 RemoveNodeFromCSEMaps(User);
8331 UserRemovedFromCSEMaps = true;
8334 ++UI;
8335 Use.set(To);
8336 if (To->isDivergent() != From->isDivergent())
8337 updateDivergence(User);
8338 } while (UI != UE && *UI == User);
8339 // We are iterating over all uses of the From node, so if a use
8340 // doesn't use the specific value, no changes are made.
8341 if (!UserRemovedFromCSEMaps)
8342 continue;
8344 // Now that we have modified User, add it back to the CSE maps. If it
8345 // already exists there, recursively merge the results together.
8346 AddModifiedNodeToCSEMaps(User);
8349 // If we just RAUW'd the root, take note.
8350 if (From == getRoot())
8351 setRoot(To);
8354 namespace {
8356 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
8357 /// to record information about a use.
8358 struct UseMemo {
8359 SDNode *User;
8360 unsigned Index;
8361 SDUse *Use;
8364 /// operator< - Sort Memos by User.
8365 bool operator<(const UseMemo &L, const UseMemo &R) {
8366 return (intptr_t)L.User < (intptr_t)R.User;
8369 } // end anonymous namespace
8371 void SelectionDAG::updateDivergence(SDNode * N)
8373 if (TLI->isSDNodeAlwaysUniform(N))
8374 return;
8375 bool IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
8376 for (auto &Op : N->ops()) {
8377 if (Op.Val.getValueType() != MVT::Other)
8378 IsDivergent |= Op.getNode()->isDivergent();
8380 if (N->SDNodeBits.IsDivergent != IsDivergent) {
8381 N->SDNodeBits.IsDivergent = IsDivergent;
8382 for (auto U : N->uses()) {
8383 updateDivergence(U);
8388 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
8389 DenseMap<SDNode *, unsigned> Degree;
8390 Order.reserve(AllNodes.size());
8391 for (auto &N : allnodes()) {
8392 unsigned NOps = N.getNumOperands();
8393 Degree[&N] = NOps;
8394 if (0 == NOps)
8395 Order.push_back(&N);
8397 for (size_t I = 0; I != Order.size(); ++I) {
8398 SDNode *N = Order[I];
8399 for (auto U : N->uses()) {
8400 unsigned &UnsortedOps = Degree[U];
8401 if (0 == --UnsortedOps)
8402 Order.push_back(U);
8407 #ifndef NDEBUG
8408 void SelectionDAG::VerifyDAGDiverence() {
8409 std::vector<SDNode *> TopoOrder;
8410 CreateTopologicalOrder(TopoOrder);
8411 const TargetLowering &TLI = getTargetLoweringInfo();
8412 DenseMap<const SDNode *, bool> DivergenceMap;
8413 for (auto &N : allnodes()) {
8414 DivergenceMap[&N] = false;
8416 for (auto N : TopoOrder) {
8417 bool IsDivergent = DivergenceMap[N];
8418 bool IsSDNodeDivergent = TLI.isSDNodeSourceOfDivergence(N, FLI, DA);
8419 for (auto &Op : N->ops()) {
8420 if (Op.Val.getValueType() != MVT::Other)
8421 IsSDNodeDivergent |= DivergenceMap[Op.getNode()];
8423 if (!IsDivergent && IsSDNodeDivergent && !TLI.isSDNodeAlwaysUniform(N)) {
8424 DivergenceMap[N] = true;
8427 for (auto &N : allnodes()) {
8428 (void)N;
8429 assert(DivergenceMap[&N] == N.isDivergent() &&
8430 "Divergence bit inconsistency detected\n");
8433 #endif
8435 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
8436 /// uses of other values produced by From.getNode() alone. The same value
8437 /// may appear in both the From and To list. The Deleted vector is
8438 /// handled the same way as for ReplaceAllUsesWith.
8439 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
8440 const SDValue *To,
8441 unsigned Num){
8442 // Handle the simple, trivial case efficiently.
8443 if (Num == 1)
8444 return ReplaceAllUsesOfValueWith(*From, *To);
8446 transferDbgValues(*From, *To);
8448 // Read up all the uses and make records of them. This helps
8449 // processing new uses that are introduced during the
8450 // replacement process.
8451 SmallVector<UseMemo, 4> Uses;
8452 for (unsigned i = 0; i != Num; ++i) {
8453 unsigned FromResNo = From[i].getResNo();
8454 SDNode *FromNode = From[i].getNode();
8455 for (SDNode::use_iterator UI = FromNode->use_begin(),
8456 E = FromNode->use_end(); UI != E; ++UI) {
8457 SDUse &Use = UI.getUse();
8458 if (Use.getResNo() == FromResNo) {
8459 UseMemo Memo = { *UI, i, &Use };
8460 Uses.push_back(Memo);
8465 // Sort the uses, so that all the uses from a given User are together.
8466 llvm::sort(Uses);
8468 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
8469 UseIndex != UseIndexEnd; ) {
8470 // We know that this user uses some value of From. If it is the right
8471 // value, update it.
8472 SDNode *User = Uses[UseIndex].User;
8474 // This node is about to morph, remove its old self from the CSE maps.
8475 RemoveNodeFromCSEMaps(User);
8477 // The Uses array is sorted, so all the uses for a given User
8478 // are next to each other in the list.
8479 // To help reduce the number of CSE recomputations, process all
8480 // the uses of this user that we can find this way.
8481 do {
8482 unsigned i = Uses[UseIndex].Index;
8483 SDUse &Use = *Uses[UseIndex].Use;
8484 ++UseIndex;
8486 Use.set(To[i]);
8487 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
8489 // Now that we have modified User, add it back to the CSE maps. If it
8490 // already exists there, recursively merge the results together.
8491 AddModifiedNodeToCSEMaps(User);
8495 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
8496 /// based on their topological order. It returns the maximum id and a vector
8497 /// of the SDNodes* in assigned order by reference.
8498 unsigned SelectionDAG::AssignTopologicalOrder() {
8499 unsigned DAGSize = 0;
8501 // SortedPos tracks the progress of the algorithm. Nodes before it are
8502 // sorted, nodes after it are unsorted. When the algorithm completes
8503 // it is at the end of the list.
8504 allnodes_iterator SortedPos = allnodes_begin();
8506 // Visit all the nodes. Move nodes with no operands to the front of
8507 // the list immediately. Annotate nodes that do have operands with their
8508 // operand count. Before we do this, the Node Id fields of the nodes
8509 // may contain arbitrary values. After, the Node Id fields for nodes
8510 // before SortedPos will contain the topological sort index, and the
8511 // Node Id fields for nodes At SortedPos and after will contain the
8512 // count of outstanding operands.
8513 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
8514 SDNode *N = &*I++;
8515 checkForCycles(N, this);
8516 unsigned Degree = N->getNumOperands();
8517 if (Degree == 0) {
8518 // A node with no uses, add it to the result array immediately.
8519 N->setNodeId(DAGSize++);
8520 allnodes_iterator Q(N);
8521 if (Q != SortedPos)
8522 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
8523 assert(SortedPos != AllNodes.end() && "Overran node list");
8524 ++SortedPos;
8525 } else {
8526 // Temporarily use the Node Id as scratch space for the degree count.
8527 N->setNodeId(Degree);
8531 // Visit all the nodes. As we iterate, move nodes into sorted order,
8532 // such that by the time the end is reached all nodes will be sorted.
8533 for (SDNode &Node : allnodes()) {
8534 SDNode *N = &Node;
8535 checkForCycles(N, this);
8536 // N is in sorted position, so all its uses have one less operand
8537 // that needs to be sorted.
8538 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
8539 UI != UE; ++UI) {
8540 SDNode *P = *UI;
8541 unsigned Degree = P->getNodeId();
8542 assert(Degree != 0 && "Invalid node degree");
8543 --Degree;
8544 if (Degree == 0) {
8545 // All of P's operands are sorted, so P may sorted now.
8546 P->setNodeId(DAGSize++);
8547 if (P->getIterator() != SortedPos)
8548 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
8549 assert(SortedPos != AllNodes.end() && "Overran node list");
8550 ++SortedPos;
8551 } else {
8552 // Update P's outstanding operand count.
8553 P->setNodeId(Degree);
8556 if (Node.getIterator() == SortedPos) {
8557 #ifndef NDEBUG
8558 allnodes_iterator I(N);
8559 SDNode *S = &*++I;
8560 dbgs() << "Overran sorted position:\n";
8561 S->dumprFull(this); dbgs() << "\n";
8562 dbgs() << "Checking if this is due to cycles\n";
8563 checkForCycles(this, true);
8564 #endif
8565 llvm_unreachable(nullptr);
8569 assert(SortedPos == AllNodes.end() &&
8570 "Topological sort incomplete!");
8571 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
8572 "First node in topological sort is not the entry token!");
8573 assert(AllNodes.front().getNodeId() == 0 &&
8574 "First node in topological sort has non-zero id!");
8575 assert(AllNodes.front().getNumOperands() == 0 &&
8576 "First node in topological sort has operands!");
8577 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
8578 "Last node in topologic sort has unexpected id!");
8579 assert(AllNodes.back().use_empty() &&
8580 "Last node in topologic sort has users!");
8581 assert(DAGSize == allnodes_size() && "Node count mismatch!");
8582 return DAGSize;
8585 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
8586 /// value is produced by SD.
8587 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
8588 if (SD) {
8589 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
8590 SD->setHasDebugValue(true);
8592 DbgInfo->add(DB, SD, isParameter);
8595 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) {
8596 DbgInfo->add(DB);
8599 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
8600 SDValue NewMemOp) {
8601 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
8602 // The new memory operation must have the same position as the old load in
8603 // terms of memory dependency. Create a TokenFactor for the old load and new
8604 // memory operation and update uses of the old load's output chain to use that
8605 // TokenFactor.
8606 SDValue OldChain = SDValue(OldLoad, 1);
8607 SDValue NewChain = SDValue(NewMemOp.getNode(), 1);
8608 if (OldChain == NewChain || !OldLoad->hasAnyUseOfValue(1))
8609 return NewChain;
8611 SDValue TokenFactor =
8612 getNode(ISD::TokenFactor, SDLoc(OldLoad), MVT::Other, OldChain, NewChain);
8613 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
8614 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewChain);
8615 return TokenFactor;
8618 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
8619 Function **OutFunction) {
8620 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
8622 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8623 auto *Module = MF->getFunction().getParent();
8624 auto *Function = Module->getFunction(Symbol);
8626 if (OutFunction != nullptr)
8627 *OutFunction = Function;
8629 if (Function != nullptr) {
8630 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
8631 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
8634 std::string ErrorStr;
8635 raw_string_ostream ErrorFormatter(ErrorStr);
8637 ErrorFormatter << "Undefined external symbol ";
8638 ErrorFormatter << '"' << Symbol << '"';
8639 ErrorFormatter.flush();
8641 report_fatal_error(ErrorStr);
8644 //===----------------------------------------------------------------------===//
8645 // SDNode Class
8646 //===----------------------------------------------------------------------===//
8648 bool llvm::isNullConstant(SDValue V) {
8649 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
8650 return Const != nullptr && Const->isNullValue();
8653 bool llvm::isNullFPConstant(SDValue V) {
8654 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
8655 return Const != nullptr && Const->isZero() && !Const->isNegative();
8658 bool llvm::isAllOnesConstant(SDValue V) {
8659 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
8660 return Const != nullptr && Const->isAllOnesValue();
8663 bool llvm::isOneConstant(SDValue V) {
8664 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
8665 return Const != nullptr && Const->isOne();
8668 SDValue llvm::peekThroughBitcasts(SDValue V) {
8669 while (V.getOpcode() == ISD::BITCAST)
8670 V = V.getOperand(0);
8671 return V;
8674 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
8675 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
8676 V = V.getOperand(0);
8677 return V;
8680 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
8681 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8682 V = V.getOperand(0);
8683 return V;
8686 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
8687 if (V.getOpcode() != ISD::XOR)
8688 return false;
8689 V = peekThroughBitcasts(V.getOperand(1));
8690 unsigned NumBits = V.getScalarValueSizeInBits();
8691 ConstantSDNode *C =
8692 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
8693 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
8696 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
8697 bool AllowTruncation) {
8698 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
8699 return CN;
8701 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
8702 BitVector UndefElements;
8703 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
8705 // BuildVectors can truncate their operands. Ignore that case here unless
8706 // AllowTruncation is set.
8707 if (CN && (UndefElements.none() || AllowUndefs)) {
8708 EVT CVT = CN->getValueType(0);
8709 EVT NSVT = N.getValueType().getScalarType();
8710 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
8711 if (AllowTruncation || (CVT == NSVT))
8712 return CN;
8716 return nullptr;
8719 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
8720 bool AllowUndefs,
8721 bool AllowTruncation) {
8722 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
8723 return CN;
8725 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
8726 BitVector UndefElements;
8727 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
8729 // BuildVectors can truncate their operands. Ignore that case here unless
8730 // AllowTruncation is set.
8731 if (CN && (UndefElements.none() || AllowUndefs)) {
8732 EVT CVT = CN->getValueType(0);
8733 EVT NSVT = N.getValueType().getScalarType();
8734 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
8735 if (AllowTruncation || (CVT == NSVT))
8736 return CN;
8740 return nullptr;
8743 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
8744 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
8745 return CN;
8747 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
8748 BitVector UndefElements;
8749 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
8750 if (CN && (UndefElements.none() || AllowUndefs))
8751 return CN;
8754 return nullptr;
8757 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
8758 const APInt &DemandedElts,
8759 bool AllowUndefs) {
8760 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
8761 return CN;
8763 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
8764 BitVector UndefElements;
8765 ConstantFPSDNode *CN =
8766 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
8767 if (CN && (UndefElements.none() || AllowUndefs))
8768 return CN;
8771 return nullptr;
8774 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
8775 // TODO: may want to use peekThroughBitcast() here.
8776 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
8777 return C && C->isNullValue();
8780 bool llvm::isOneOrOneSplat(SDValue N) {
8781 // TODO: may want to use peekThroughBitcast() here.
8782 unsigned BitWidth = N.getScalarValueSizeInBits();
8783 ConstantSDNode *C = isConstOrConstSplat(N);
8784 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
8787 bool llvm::isAllOnesOrAllOnesSplat(SDValue N) {
8788 N = peekThroughBitcasts(N);
8789 unsigned BitWidth = N.getScalarValueSizeInBits();
8790 ConstantSDNode *C = isConstOrConstSplat(N);
8791 return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth;
8794 HandleSDNode::~HandleSDNode() {
8795 DropOperands();
8798 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
8799 const DebugLoc &DL,
8800 const GlobalValue *GA, EVT VT,
8801 int64_t o, unsigned TF)
8802 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
8803 TheGlobal = GA;
8806 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
8807 EVT VT, unsigned SrcAS,
8808 unsigned DestAS)
8809 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
8810 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
8812 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
8813 SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
8814 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
8815 MemSDNodeBits.IsVolatile = MMO->isVolatile();
8816 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
8817 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
8818 MemSDNodeBits.IsInvariant = MMO->isInvariant();
8820 // We check here that the size of the memory operand fits within the size of
8821 // the MMO. This is because the MMO might indicate only a possible address
8822 // range instead of specifying the affected memory addresses precisely.
8823 assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
8826 /// Profile - Gather unique data for the node.
8828 void SDNode::Profile(FoldingSetNodeID &ID) const {
8829 AddNodeIDNode(ID, this);
8832 namespace {
8834 struct EVTArray {
8835 std::vector<EVT> VTs;
8837 EVTArray() {
8838 VTs.reserve(MVT::LAST_VALUETYPE);
8839 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
8840 VTs.push_back(MVT((MVT::SimpleValueType)i));
8844 } // end anonymous namespace
8846 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
8847 static ManagedStatic<EVTArray> SimpleVTArray;
8848 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
8850 /// getValueTypeList - Return a pointer to the specified value type.
8852 const EVT *SDNode::getValueTypeList(EVT VT) {
8853 if (VT.isExtended()) {
8854 sys::SmartScopedLock<true> Lock(*VTMutex);
8855 return &(*EVTs->insert(VT).first);
8856 } else {
8857 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
8858 "Value type out of range!");
8859 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
8863 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
8864 /// indicated value. This method ignores uses of other values defined by this
8865 /// operation.
8866 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
8867 assert(Value < getNumValues() && "Bad value!");
8869 // TODO: Only iterate over uses of a given value of the node
8870 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
8871 if (UI.getUse().getResNo() == Value) {
8872 if (NUses == 0)
8873 return false;
8874 --NUses;
8878 // Found exactly the right number of uses?
8879 return NUses == 0;
8882 /// hasAnyUseOfValue - Return true if there are any use of the indicated
8883 /// value. This method ignores uses of other values defined by this operation.
8884 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
8885 assert(Value < getNumValues() && "Bad value!");
8887 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
8888 if (UI.getUse().getResNo() == Value)
8889 return true;
8891 return false;
8894 /// isOnlyUserOf - Return true if this node is the only use of N.
8895 bool SDNode::isOnlyUserOf(const SDNode *N) const {
8896 bool Seen = false;
8897 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
8898 SDNode *User = *I;
8899 if (User == this)
8900 Seen = true;
8901 else
8902 return false;
8905 return Seen;
8908 /// Return true if the only users of N are contained in Nodes.
8909 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
8910 bool Seen = false;
8911 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
8912 SDNode *User = *I;
8913 if (llvm::any_of(Nodes,
8914 [&User](const SDNode *Node) { return User == Node; }))
8915 Seen = true;
8916 else
8917 return false;
8920 return Seen;
8923 /// isOperand - Return true if this node is an operand of N.
8924 bool SDValue::isOperandOf(const SDNode *N) const {
8925 return any_of(N->op_values(), [this](SDValue Op) { return *this == Op; });
8928 bool SDNode::isOperandOf(const SDNode *N) const {
8929 return any_of(N->op_values(),
8930 [this](SDValue Op) { return this == Op.getNode(); });
8933 /// reachesChainWithoutSideEffects - Return true if this operand (which must
8934 /// be a chain) reaches the specified operand without crossing any
8935 /// side-effecting instructions on any chain path. In practice, this looks
8936 /// through token factors and non-volatile loads. In order to remain efficient,
8937 /// this only looks a couple of nodes in, it does not do an exhaustive search.
8939 /// Note that we only need to examine chains when we're searching for
8940 /// side-effects; SelectionDAG requires that all side-effects are represented
8941 /// by chains, even if another operand would force a specific ordering. This
8942 /// constraint is necessary to allow transformations like splitting loads.
8943 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
8944 unsigned Depth) const {
8945 if (*this == Dest) return true;
8947 // Don't search too deeply, we just want to be able to see through
8948 // TokenFactor's etc.
8949 if (Depth == 0) return false;
8951 // If this is a token factor, all inputs to the TF happen in parallel.
8952 if (getOpcode() == ISD::TokenFactor) {
8953 // First, try a shallow search.
8954 if (is_contained((*this)->ops(), Dest)) {
8955 // We found the chain we want as an operand of this TokenFactor.
8956 // Essentially, we reach the chain without side-effects if we could
8957 // serialize the TokenFactor into a simple chain of operations with
8958 // Dest as the last operation. This is automatically true if the
8959 // chain has one use: there are no other ordering constraints.
8960 // If the chain has more than one use, we give up: some other
8961 // use of Dest might force a side-effect between Dest and the current
8962 // node.
8963 if (Dest.hasOneUse())
8964 return true;
8966 // Next, try a deep search: check whether every operand of the TokenFactor
8967 // reaches Dest.
8968 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
8969 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
8973 // Loads don't have side effects, look through them.
8974 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
8975 if (Ld->isUnordered())
8976 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
8978 return false;
8981 bool SDNode::hasPredecessor(const SDNode *N) const {
8982 SmallPtrSet<const SDNode *, 32> Visited;
8983 SmallVector<const SDNode *, 16> Worklist;
8984 Worklist.push_back(this);
8985 return hasPredecessorHelper(N, Visited, Worklist);
8988 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
8989 this->Flags.intersectWith(Flags);
8992 SDValue
8993 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
8994 ArrayRef<ISD::NodeType> CandidateBinOps,
8995 bool AllowPartials) {
8996 // The pattern must end in an extract from index 0.
8997 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8998 !isNullConstant(Extract->getOperand(1)))
8999 return SDValue();
9001 // Match against one of the candidate binary ops.
9002 SDValue Op = Extract->getOperand(0);
9003 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
9004 return Op.getOpcode() == unsigned(BinOp);
9006 return SDValue();
9008 // Floating-point reductions may require relaxed constraints on the final step
9009 // of the reduction because they may reorder intermediate operations.
9010 unsigned CandidateBinOp = Op.getOpcode();
9011 if (Op.getValueType().isFloatingPoint()) {
9012 SDNodeFlags Flags = Op->getFlags();
9013 switch (CandidateBinOp) {
9014 case ISD::FADD:
9015 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
9016 return SDValue();
9017 break;
9018 default:
9019 llvm_unreachable("Unhandled FP opcode for binop reduction");
9023 // Matching failed - attempt to see if we did enough stages that a partial
9024 // reduction from a subvector is possible.
9025 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
9026 if (!AllowPartials || !Op)
9027 return SDValue();
9028 EVT OpVT = Op.getValueType();
9029 EVT OpSVT = OpVT.getScalarType();
9030 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
9031 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
9032 return SDValue();
9033 BinOp = (ISD::NodeType)CandidateBinOp;
9034 return getNode(
9035 ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
9036 getConstant(0, SDLoc(Op), TLI->getVectorIdxTy(getDataLayout())));
9039 // At each stage, we're looking for something that looks like:
9040 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
9041 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
9042 // i32 undef, i32 undef, i32 undef, i32 undef>
9043 // %a = binop <8 x i32> %op, %s
9044 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
9045 // we expect something like:
9046 // <4,5,6,7,u,u,u,u>
9047 // <2,3,u,u,u,u,u,u>
9048 // <1,u,u,u,u,u,u,u>
9049 // While a partial reduction match would be:
9050 // <2,3,u,u,u,u,u,u>
9051 // <1,u,u,u,u,u,u,u>
9052 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
9053 SDValue PrevOp;
9054 for (unsigned i = 0; i < Stages; ++i) {
9055 unsigned MaskEnd = (1 << i);
9057 if (Op.getOpcode() != CandidateBinOp)
9058 return PartialReduction(PrevOp, MaskEnd);
9060 SDValue Op0 = Op.getOperand(0);
9061 SDValue Op1 = Op.getOperand(1);
9063 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
9064 if (Shuffle) {
9065 Op = Op1;
9066 } else {
9067 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
9068 Op = Op0;
9071 // The first operand of the shuffle should be the same as the other operand
9072 // of the binop.
9073 if (!Shuffle || Shuffle->getOperand(0) != Op)
9074 return PartialReduction(PrevOp, MaskEnd);
9076 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
9077 for (int Index = 0; Index < (int)MaskEnd; ++Index)
9078 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
9079 return PartialReduction(PrevOp, MaskEnd);
9081 PrevOp = Op;
9084 BinOp = (ISD::NodeType)CandidateBinOp;
9085 return Op;
9088 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
9089 assert(N->getNumValues() == 1 &&
9090 "Can't unroll a vector with multiple results!");
9092 EVT VT = N->getValueType(0);
9093 unsigned NE = VT.getVectorNumElements();
9094 EVT EltVT = VT.getVectorElementType();
9095 SDLoc dl(N);
9097 SmallVector<SDValue, 8> Scalars;
9098 SmallVector<SDValue, 4> Operands(N->getNumOperands());
9100 // If ResNE is 0, fully unroll the vector op.
9101 if (ResNE == 0)
9102 ResNE = NE;
9103 else if (NE > ResNE)
9104 NE = ResNE;
9106 unsigned i;
9107 for (i= 0; i != NE; ++i) {
9108 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
9109 SDValue Operand = N->getOperand(j);
9110 EVT OperandVT = Operand.getValueType();
9111 if (OperandVT.isVector()) {
9112 // A vector operand; extract a single element.
9113 EVT OperandEltVT = OperandVT.getVectorElementType();
9114 Operands[j] =
9115 getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand,
9116 getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout())));
9117 } else {
9118 // A scalar operand; just use it as is.
9119 Operands[j] = Operand;
9123 switch (N->getOpcode()) {
9124 default: {
9125 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
9126 N->getFlags()));
9127 break;
9129 case ISD::VSELECT:
9130 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
9131 break;
9132 case ISD::SHL:
9133 case ISD::SRA:
9134 case ISD::SRL:
9135 case ISD::ROTL:
9136 case ISD::ROTR:
9137 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
9138 getShiftAmountOperand(Operands[0].getValueType(),
9139 Operands[1])));
9140 break;
9141 case ISD::SIGN_EXTEND_INREG: {
9142 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
9143 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
9144 Operands[0],
9145 getValueType(ExtVT)));
9150 for (; i < ResNE; ++i)
9151 Scalars.push_back(getUNDEF(EltVT));
9153 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
9154 return getBuildVector(VecVT, dl, Scalars);
9157 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
9158 SDNode *N, unsigned ResNE) {
9159 unsigned Opcode = N->getOpcode();
9160 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
9161 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
9162 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
9163 "Expected an overflow opcode");
9165 EVT ResVT = N->getValueType(0);
9166 EVT OvVT = N->getValueType(1);
9167 EVT ResEltVT = ResVT.getVectorElementType();
9168 EVT OvEltVT = OvVT.getVectorElementType();
9169 SDLoc dl(N);
9171 // If ResNE is 0, fully unroll the vector op.
9172 unsigned NE = ResVT.getVectorNumElements();
9173 if (ResNE == 0)
9174 ResNE = NE;
9175 else if (NE > ResNE)
9176 NE = ResNE;
9178 SmallVector<SDValue, 8> LHSScalars;
9179 SmallVector<SDValue, 8> RHSScalars;
9180 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
9181 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
9183 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
9184 SDVTList VTs = getVTList(ResEltVT, SVT);
9185 SmallVector<SDValue, 8> ResScalars;
9186 SmallVector<SDValue, 8> OvScalars;
9187 for (unsigned i = 0; i < NE; ++i) {
9188 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
9189 SDValue Ov =
9190 getSelect(dl, OvEltVT, Res.getValue(1),
9191 getBoolConstant(true, dl, OvEltVT, ResVT),
9192 getConstant(0, dl, OvEltVT));
9194 ResScalars.push_back(Res);
9195 OvScalars.push_back(Ov);
9198 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
9199 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
9201 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
9202 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
9203 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
9204 getBuildVector(NewOvVT, dl, OvScalars));
9207 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
9208 LoadSDNode *Base,
9209 unsigned Bytes,
9210 int Dist) const {
9211 if (LD->isVolatile() || Base->isVolatile())
9212 return false;
9213 // TODO: probably too restrictive for atomics, revisit
9214 if (!LD->isSimple())
9215 return false;
9216 if (LD->isIndexed() || Base->isIndexed())
9217 return false;
9218 if (LD->getChain() != Base->getChain())
9219 return false;
9220 EVT VT = LD->getValueType(0);
9221 if (VT.getSizeInBits() / 8 != Bytes)
9222 return false;
9224 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
9225 auto LocDecomp = BaseIndexOffset::match(LD, *this);
9227 int64_t Offset = 0;
9228 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
9229 return (Dist * Bytes == Offset);
9230 return false;
9233 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
9234 /// it cannot be inferred.
9235 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
9236 // If this is a GlobalAddress + cst, return the alignment.
9237 const GlobalValue *GV;
9238 int64_t GVOffset = 0;
9239 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
9240 unsigned IdxWidth = getDataLayout().getIndexTypeSizeInBits(GV->getType());
9241 KnownBits Known(IdxWidth);
9242 llvm::computeKnownBits(GV, Known, getDataLayout());
9243 unsigned AlignBits = Known.countMinTrailingZeros();
9244 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
9245 if (Align)
9246 return MinAlign(Align, GVOffset);
9249 // If this is a direct reference to a stack slot, use information about the
9250 // stack slot's alignment.
9251 int FrameIdx = INT_MIN;
9252 int64_t FrameOffset = 0;
9253 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
9254 FrameIdx = FI->getIndex();
9255 } else if (isBaseWithConstantOffset(Ptr) &&
9256 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
9257 // Handle FI+Cst
9258 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
9259 FrameOffset = Ptr.getConstantOperandVal(1);
9262 if (FrameIdx != INT_MIN) {
9263 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
9264 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
9265 FrameOffset);
9266 return FIInfoAlign;
9269 return 0;
9272 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
9273 /// which is split (or expanded) into two not necessarily identical pieces.
9274 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
9275 // Currently all types are split in half.
9276 EVT LoVT, HiVT;
9277 if (!VT.isVector())
9278 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
9279 else
9280 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
9282 return std::make_pair(LoVT, HiVT);
9285 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
9286 /// low/high part.
9287 std::pair<SDValue, SDValue>
9288 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
9289 const EVT &HiVT) {
9290 assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
9291 N.getValueType().getVectorNumElements() &&
9292 "More vector elements requested than available!");
9293 SDValue Lo, Hi;
9294 Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
9295 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
9296 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
9297 getConstant(LoVT.getVectorNumElements(), DL,
9298 TLI->getVectorIdxTy(getDataLayout())));
9299 return std::make_pair(Lo, Hi);
9302 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
9303 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
9304 EVT VT = N.getValueType();
9305 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
9306 NextPowerOf2(VT.getVectorNumElements()));
9307 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
9308 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
9311 void SelectionDAG::ExtractVectorElements(SDValue Op,
9312 SmallVectorImpl<SDValue> &Args,
9313 unsigned Start, unsigned Count) {
9314 EVT VT = Op.getValueType();
9315 if (Count == 0)
9316 Count = VT.getVectorNumElements();
9318 EVT EltVT = VT.getVectorElementType();
9319 EVT IdxTy = TLI->getVectorIdxTy(getDataLayout());
9320 SDLoc SL(Op);
9321 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
9322 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9323 Op, getConstant(i, SL, IdxTy)));
9327 // getAddressSpace - Return the address space this GlobalAddress belongs to.
9328 unsigned GlobalAddressSDNode::getAddressSpace() const {
9329 return getGlobal()->getType()->getAddressSpace();
9332 Type *ConstantPoolSDNode::getType() const {
9333 if (isMachineConstantPoolEntry())
9334 return Val.MachineCPVal->getType();
9335 return Val.ConstVal->getType();
9338 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
9339 unsigned &SplatBitSize,
9340 bool &HasAnyUndefs,
9341 unsigned MinSplatBits,
9342 bool IsBigEndian) const {
9343 EVT VT = getValueType(0);
9344 assert(VT.isVector() && "Expected a vector type");
9345 unsigned VecWidth = VT.getSizeInBits();
9346 if (MinSplatBits > VecWidth)
9347 return false;
9349 // FIXME: The widths are based on this node's type, but build vectors can
9350 // truncate their operands.
9351 SplatValue = APInt(VecWidth, 0);
9352 SplatUndef = APInt(VecWidth, 0);
9354 // Get the bits. Bits with undefined values (when the corresponding element
9355 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
9356 // in SplatValue. If any of the values are not constant, give up and return
9357 // false.
9358 unsigned int NumOps = getNumOperands();
9359 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
9360 unsigned EltWidth = VT.getScalarSizeInBits();
9362 for (unsigned j = 0; j < NumOps; ++j) {
9363 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
9364 SDValue OpVal = getOperand(i);
9365 unsigned BitPos = j * EltWidth;
9367 if (OpVal.isUndef())
9368 SplatUndef.setBits(BitPos, BitPos + EltWidth);
9369 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
9370 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
9371 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
9372 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
9373 else
9374 return false;
9377 // The build_vector is all constants or undefs. Find the smallest element
9378 // size that splats the vector.
9379 HasAnyUndefs = (SplatUndef != 0);
9381 // FIXME: This does not work for vectors with elements less than 8 bits.
9382 while (VecWidth > 8) {
9383 unsigned HalfSize = VecWidth / 2;
9384 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
9385 APInt LowValue = SplatValue.trunc(HalfSize);
9386 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
9387 APInt LowUndef = SplatUndef.trunc(HalfSize);
9389 // If the two halves do not match (ignoring undef bits), stop here.
9390 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
9391 MinSplatBits > HalfSize)
9392 break;
9394 SplatValue = HighValue | LowValue;
9395 SplatUndef = HighUndef & LowUndef;
9397 VecWidth = HalfSize;
9400 SplatBitSize = VecWidth;
9401 return true;
9404 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
9405 BitVector *UndefElements) const {
9406 if (UndefElements) {
9407 UndefElements->clear();
9408 UndefElements->resize(getNumOperands());
9410 assert(getNumOperands() == DemandedElts.getBitWidth() &&
9411 "Unexpected vector size");
9412 if (!DemandedElts)
9413 return SDValue();
9414 SDValue Splatted;
9415 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
9416 if (!DemandedElts[i])
9417 continue;
9418 SDValue Op = getOperand(i);
9419 if (Op.isUndef()) {
9420 if (UndefElements)
9421 (*UndefElements)[i] = true;
9422 } else if (!Splatted) {
9423 Splatted = Op;
9424 } else if (Splatted != Op) {
9425 return SDValue();
9429 if (!Splatted) {
9430 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
9431 assert(getOperand(FirstDemandedIdx).isUndef() &&
9432 "Can only have a splat without a constant for all undefs.");
9433 return getOperand(FirstDemandedIdx);
9436 return Splatted;
9439 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
9440 APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
9441 return getSplatValue(DemandedElts, UndefElements);
9444 ConstantSDNode *
9445 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
9446 BitVector *UndefElements) const {
9447 return dyn_cast_or_null<ConstantSDNode>(
9448 getSplatValue(DemandedElts, UndefElements));
9451 ConstantSDNode *
9452 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
9453 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
9456 ConstantFPSDNode *
9457 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
9458 BitVector *UndefElements) const {
9459 return dyn_cast_or_null<ConstantFPSDNode>(
9460 getSplatValue(DemandedElts, UndefElements));
9463 ConstantFPSDNode *
9464 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
9465 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
9468 int32_t
9469 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
9470 uint32_t BitWidth) const {
9471 if (ConstantFPSDNode *CN =
9472 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
9473 bool IsExact;
9474 APSInt IntVal(BitWidth);
9475 const APFloat &APF = CN->getValueAPF();
9476 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
9477 APFloat::opOK ||
9478 !IsExact)
9479 return -1;
9481 return IntVal.exactLogBase2();
9483 return -1;
9486 bool BuildVectorSDNode::isConstant() const {
9487 for (const SDValue &Op : op_values()) {
9488 unsigned Opc = Op.getOpcode();
9489 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
9490 return false;
9492 return true;
9495 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
9496 // Find the first non-undef value in the shuffle mask.
9497 unsigned i, e;
9498 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
9499 /* search */;
9501 // If all elements are undefined, this shuffle can be considered a splat
9502 // (although it should eventually get simplified away completely).
9503 if (i == e)
9504 return true;
9506 // Make sure all remaining elements are either undef or the same as the first
9507 // non-undef value.
9508 for (int Idx = Mask[i]; i != e; ++i)
9509 if (Mask[i] >= 0 && Mask[i] != Idx)
9510 return false;
9511 return true;
9514 // Returns the SDNode if it is a constant integer BuildVector
9515 // or constant integer.
9516 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
9517 if (isa<ConstantSDNode>(N))
9518 return N.getNode();
9519 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
9520 return N.getNode();
9521 // Treat a GlobalAddress supporting constant offset folding as a
9522 // constant integer.
9523 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
9524 if (GA->getOpcode() == ISD::GlobalAddress &&
9525 TLI->isOffsetFoldingLegal(GA))
9526 return GA;
9527 return nullptr;
9530 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) {
9531 if (isa<ConstantFPSDNode>(N))
9532 return N.getNode();
9534 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
9535 return N.getNode();
9537 return nullptr;
9540 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
9541 assert(!Node->OperandList && "Node already has operands");
9542 assert(SDNode::getMaxNumOperands() >= Vals.size() &&
9543 "too many operands to fit into SDNode");
9544 SDUse *Ops = OperandRecycler.allocate(
9545 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
9547 bool IsDivergent = false;
9548 for (unsigned I = 0; I != Vals.size(); ++I) {
9549 Ops[I].setUser(Node);
9550 Ops[I].setInitial(Vals[I]);
9551 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
9552 IsDivergent = IsDivergent || Ops[I].getNode()->isDivergent();
9554 Node->NumOperands = Vals.size();
9555 Node->OperandList = Ops;
9556 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
9557 if (!TLI->isSDNodeAlwaysUniform(Node))
9558 Node->SDNodeBits.IsDivergent = IsDivergent;
9559 checkForCycles(Node);
9562 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
9563 SmallVectorImpl<SDValue> &Vals) {
9564 size_t Limit = SDNode::getMaxNumOperands();
9565 while (Vals.size() > Limit) {
9566 unsigned SliceIdx = Vals.size() - Limit;
9567 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
9568 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
9569 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
9570 Vals.emplace_back(NewTF);
9572 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
9575 #ifndef NDEBUG
9576 static void checkForCyclesHelper(const SDNode *N,
9577 SmallPtrSetImpl<const SDNode*> &Visited,
9578 SmallPtrSetImpl<const SDNode*> &Checked,
9579 const llvm::SelectionDAG *DAG) {
9580 // If this node has already been checked, don't check it again.
9581 if (Checked.count(N))
9582 return;
9584 // If a node has already been visited on this depth-first walk, reject it as
9585 // a cycle.
9586 if (!Visited.insert(N).second) {
9587 errs() << "Detected cycle in SelectionDAG\n";
9588 dbgs() << "Offending node:\n";
9589 N->dumprFull(DAG); dbgs() << "\n";
9590 abort();
9593 for (const SDValue &Op : N->op_values())
9594 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
9596 Checked.insert(N);
9597 Visited.erase(N);
9599 #endif
9601 void llvm::checkForCycles(const llvm::SDNode *N,
9602 const llvm::SelectionDAG *DAG,
9603 bool force) {
9604 #ifndef NDEBUG
9605 bool check = force;
9606 #ifdef EXPENSIVE_CHECKS
9607 check = true;
9608 #endif // EXPENSIVE_CHECKS
9609 if (check) {
9610 assert(N && "Checking nonexistent SDNode");
9611 SmallPtrSet<const SDNode*, 32> visited;
9612 SmallPtrSet<const SDNode*, 32> checked;
9613 checkForCyclesHelper(N, visited, checked, DAG);
9615 #endif // !NDEBUG
9618 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
9619 checkForCycles(DAG->getRoot().getNode(), DAG, force);