1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements the SelectionDAG class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/SelectionDAG.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/APSInt.h" 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/BitVector.h" 20 #include "llvm/ADT/DenseSet.h" 21 #include "llvm/ADT/FoldingSet.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/Twine.h" 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/ValueTracking.h" 29 #include "llvm/Analysis/VectorUtils.h" 30 #include "llvm/BinaryFormat/Dwarf.h" 31 #include "llvm/CodeGen/Analysis.h" 32 #include "llvm/CodeGen/FunctionLoweringInfo.h" 33 #include "llvm/CodeGen/ISDOpcodes.h" 34 #include "llvm/CodeGen/MachineBasicBlock.h" 35 #include "llvm/CodeGen/MachineConstantPool.h" 36 #include "llvm/CodeGen/MachineFrameInfo.h" 37 #include "llvm/CodeGen/MachineFunction.h" 38 #include "llvm/CodeGen/MachineMemOperand.h" 39 #include "llvm/CodeGen/MachineValueType.h" 40 #include "llvm/CodeGen/RuntimeLibcalls.h" 41 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 42 #include "llvm/CodeGen/SelectionDAGNodes.h" 43 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 44 #include "llvm/CodeGen/TargetFrameLowering.h" 45 #include "llvm/CodeGen/TargetLowering.h" 46 #include "llvm/CodeGen/TargetRegisterInfo.h" 47 #include "llvm/CodeGen/TargetSubtargetInfo.h" 48 #include "llvm/CodeGen/ValueTypes.h" 49 #include "llvm/IR/Constant.h" 50 #include "llvm/IR/ConstantRange.h" 51 #include "llvm/IR/Constants.h" 52 #include "llvm/IR/DataLayout.h" 53 #include "llvm/IR/DebugInfoMetadata.h" 54 #include "llvm/IR/DebugLoc.h" 55 #include "llvm/IR/DerivedTypes.h" 56 #include "llvm/IR/Function.h" 57 #include "llvm/IR/GlobalValue.h" 58 #include "llvm/IR/Metadata.h" 59 #include "llvm/IR/Type.h" 60 #include "llvm/Support/Casting.h" 61 #include "llvm/Support/CodeGen.h" 62 #include "llvm/Support/Compiler.h" 63 #include "llvm/Support/Debug.h" 64 #include "llvm/Support/ErrorHandling.h" 65 #include "llvm/Support/KnownBits.h" 66 #include "llvm/Support/MathExtras.h" 67 #include "llvm/Support/Mutex.h" 68 #include "llvm/Support/raw_ostream.h" 69 #include "llvm/Target/TargetMachine.h" 70 #include "llvm/Target/TargetOptions.h" 71 #include "llvm/TargetParser/Triple.h" 72 #include "llvm/Transforms/Utils/SizeOpts.h" 73 #include <algorithm> 74 #include <cassert> 75 #include <cstdint> 76 #include <cstdlib> 77 #include <limits> 78 #include <set> 79 #include <string> 80 #include <utility> 81 #include <vector> 82 83 using namespace llvm; 84 85 /// makeVTList - Return an instance of the SDVTList struct initialized with the 86 /// specified members. 87 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) { 88 SDVTList Res = {VTs, NumVTs}; 89 return Res; 90 } 91 92 // Default null implementations of the callbacks. 93 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {} 94 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {} 95 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {} 96 97 void SelectionDAG::DAGNodeDeletedListener::anchor() {} 98 void SelectionDAG::DAGNodeInsertedListener::anchor() {} 99 100 #define DEBUG_TYPE "selectiondag" 101 102 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt", 103 cl::Hidden, cl::init(true), 104 cl::desc("Gang up loads and stores generated by inlining of memcpy")); 105 106 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max", 107 cl::desc("Number limit for gluing ld/st of memcpy."), 108 cl::Hidden, cl::init(0)); 109 110 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) { 111 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G);); 112 } 113 114 //===----------------------------------------------------------------------===// 115 // ConstantFPSDNode Class 116 //===----------------------------------------------------------------------===// 117 118 /// isExactlyValue - We don't rely on operator== working on double values, as 119 /// it returns true for things that are clearly not equal, like -0.0 and 0.0. 120 /// As such, this method can be used to do an exact bit-for-bit comparison of 121 /// two floating point values. 122 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const { 123 return getValueAPF().bitwiseIsEqual(V); 124 } 125 126 bool ConstantFPSDNode::isValueValidForType(EVT VT, 127 const APFloat& Val) { 128 assert(VT.isFloatingPoint() && "Can only convert between FP types"); 129 130 // convert modifies in place, so make a copy. 131 APFloat Val2 = APFloat(Val); 132 bool losesInfo; 133 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT), 134 APFloat::rmNearestTiesToEven, 135 &losesInfo); 136 return !losesInfo; 137 } 138 139 //===----------------------------------------------------------------------===// 140 // ISD Namespace 141 //===----------------------------------------------------------------------===// 142 143 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) { 144 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 145 unsigned EltSize = 146 N->getValueType(0).getVectorElementType().getSizeInBits(); 147 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 148 SplatVal = Op0->getAPIntValue().trunc(EltSize); 149 return true; 150 } 151 if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) { 152 SplatVal = Op0->getValueAPF().bitcastToAPInt().trunc(EltSize); 153 return true; 154 } 155 } 156 157 auto *BV = dyn_cast<BuildVectorSDNode>(N); 158 if (!BV) 159 return false; 160 161 APInt SplatUndef; 162 unsigned SplatBitSize; 163 bool HasUndefs; 164 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 165 // Endianness does not matter here. We are checking for a splat given the 166 // element size of the vector, and if we find such a splat for little endian 167 // layout, then that should be valid also for big endian (as the full vector 168 // size is known to be a multiple of the element size). 169 const bool IsBigEndian = false; 170 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs, 171 EltSize, IsBigEndian) && 172 EltSize == SplatBitSize; 173 } 174 175 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be 176 // specializations of the more general isConstantSplatVector()? 177 178 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) { 179 // Look through a bit convert. 180 while (N->getOpcode() == ISD::BITCAST) 181 N = N->getOperand(0).getNode(); 182 183 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 184 APInt SplatVal; 185 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes(); 186 } 187 188 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 189 190 unsigned i = 0, e = N->getNumOperands(); 191 192 // Skip over all of the undef values. 193 while (i != e && N->getOperand(i).isUndef()) 194 ++i; 195 196 // Do not accept an all-undef vector. 197 if (i == e) return false; 198 199 // Do not accept build_vectors that aren't all constants or which have non-~0 200 // elements. We have to be a bit careful here, as the type of the constant 201 // may not be the same as the type of the vector elements due to type 202 // legalization (the elements are promoted to a legal type for the target and 203 // a vector of a type may be legal when the base element type is not). 204 // We only want to check enough bits to cover the vector elements, because 205 // we care if the resultant vector is all ones, not whether the individual 206 // constants are. 207 SDValue NotZero = N->getOperand(i); 208 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 209 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 210 if (CN->getAPIntValue().countr_one() < EltSize) 211 return false; 212 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 213 if (CFPN->getValueAPF().bitcastToAPInt().countr_one() < EltSize) 214 return false; 215 } else 216 return false; 217 218 // Okay, we have at least one ~0 value, check to see if the rest match or are 219 // undefs. Even with the above element type twiddling, this should be OK, as 220 // the same type legalization should have applied to all the elements. 221 for (++i; i != e; ++i) 222 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef()) 223 return false; 224 return true; 225 } 226 227 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) { 228 // Look through a bit convert. 229 while (N->getOpcode() == ISD::BITCAST) 230 N = N->getOperand(0).getNode(); 231 232 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 233 APInt SplatVal; 234 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero(); 235 } 236 237 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 238 239 bool IsAllUndef = true; 240 for (const SDValue &Op : N->op_values()) { 241 if (Op.isUndef()) 242 continue; 243 IsAllUndef = false; 244 // Do not accept build_vectors that aren't all constants or which have non-0 245 // elements. We have to be a bit careful here, as the type of the constant 246 // may not be the same as the type of the vector elements due to type 247 // legalization (the elements are promoted to a legal type for the target 248 // and a vector of a type may be legal when the base element type is not). 249 // We only want to check enough bits to cover the vector elements, because 250 // we care if the resultant vector is all zeros, not whether the individual 251 // constants are. 252 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 253 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) { 254 if (CN->getAPIntValue().countr_zero() < EltSize) 255 return false; 256 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) { 257 if (CFPN->getValueAPF().bitcastToAPInt().countr_zero() < EltSize) 258 return false; 259 } else 260 return false; 261 } 262 263 // Do not accept an all-undef vector. 264 if (IsAllUndef) 265 return false; 266 return true; 267 } 268 269 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 270 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true); 271 } 272 273 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 274 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true); 275 } 276 277 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 278 if (N->getOpcode() != ISD::BUILD_VECTOR) 279 return false; 280 281 for (const SDValue &Op : N->op_values()) { 282 if (Op.isUndef()) 283 continue; 284 if (!isa<ConstantSDNode>(Op)) 285 return false; 286 } 287 return true; 288 } 289 290 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) { 291 if (N->getOpcode() != ISD::BUILD_VECTOR) 292 return false; 293 294 for (const SDValue &Op : N->op_values()) { 295 if (Op.isUndef()) 296 continue; 297 if (!isa<ConstantFPSDNode>(Op)) 298 return false; 299 } 300 return true; 301 } 302 303 bool ISD::isVectorShrinkable(const SDNode *N, unsigned NewEltSize, 304 bool Signed) { 305 assert(N->getValueType(0).isVector() && "Expected a vector!"); 306 307 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 308 if (EltSize <= NewEltSize) 309 return false; 310 311 if (N->getOpcode() == ISD::ZERO_EXTEND) { 312 return (N->getOperand(0).getValueType().getScalarSizeInBits() <= 313 NewEltSize) && 314 !Signed; 315 } 316 if (N->getOpcode() == ISD::SIGN_EXTEND) { 317 return (N->getOperand(0).getValueType().getScalarSizeInBits() <= 318 NewEltSize) && 319 Signed; 320 } 321 if (N->getOpcode() != ISD::BUILD_VECTOR) 322 return false; 323 324 for (const SDValue &Op : N->op_values()) { 325 if (Op.isUndef()) 326 continue; 327 if (!isa<ConstantSDNode>(Op)) 328 return false; 329 330 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().trunc(EltSize); 331 if (Signed && C.trunc(NewEltSize).sext(EltSize) != C) 332 return false; 333 if (!Signed && C.trunc(NewEltSize).zext(EltSize) != C) 334 return false; 335 } 336 337 return true; 338 } 339 340 bool ISD::allOperandsUndef(const SDNode *N) { 341 // Return false if the node has no operands. 342 // This is "logically inconsistent" with the definition of "all" but 343 // is probably the desired behavior. 344 if (N->getNumOperands() == 0) 345 return false; 346 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); }); 347 } 348 349 bool ISD::isFreezeUndef(const SDNode *N) { 350 return N->getOpcode() == ISD::FREEZE && N->getOperand(0).isUndef(); 351 } 352 353 template <typename ConstNodeType> 354 bool ISD::matchUnaryPredicateImpl(SDValue Op, 355 std::function<bool(ConstNodeType *)> Match, 356 bool AllowUndefs) { 357 // FIXME: Add support for scalar UNDEF cases? 358 if (auto *C = dyn_cast<ConstNodeType>(Op)) 359 return Match(C); 360 361 // FIXME: Add support for vector UNDEF cases? 362 if (ISD::BUILD_VECTOR != Op.getOpcode() && 363 ISD::SPLAT_VECTOR != Op.getOpcode()) 364 return false; 365 366 EVT SVT = Op.getValueType().getScalarType(); 367 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 368 if (AllowUndefs && Op.getOperand(i).isUndef()) { 369 if (!Match(nullptr)) 370 return false; 371 continue; 372 } 373 374 auto *Cst = dyn_cast<ConstNodeType>(Op.getOperand(i)); 375 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 376 return false; 377 } 378 return true; 379 } 380 // Build used template types. 381 template bool ISD::matchUnaryPredicateImpl<ConstantSDNode>( 382 SDValue, std::function<bool(ConstantSDNode *)>, bool); 383 template bool ISD::matchUnaryPredicateImpl<ConstantFPSDNode>( 384 SDValue, std::function<bool(ConstantFPSDNode *)>, bool); 385 386 bool ISD::matchBinaryPredicate( 387 SDValue LHS, SDValue RHS, 388 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match, 389 bool AllowUndefs, bool AllowTypeMismatch) { 390 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType()) 391 return false; 392 393 // TODO: Add support for scalar UNDEF cases? 394 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 395 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 396 return Match(LHSCst, RHSCst); 397 398 // TODO: Add support for vector UNDEF cases? 399 if (LHS.getOpcode() != RHS.getOpcode() || 400 (LHS.getOpcode() != ISD::BUILD_VECTOR && 401 LHS.getOpcode() != ISD::SPLAT_VECTOR)) 402 return false; 403 404 EVT SVT = LHS.getValueType().getScalarType(); 405 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 406 SDValue LHSOp = LHS.getOperand(i); 407 SDValue RHSOp = RHS.getOperand(i); 408 bool LHSUndef = AllowUndefs && LHSOp.isUndef(); 409 bool RHSUndef = AllowUndefs && RHSOp.isUndef(); 410 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp); 411 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp); 412 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef)) 413 return false; 414 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT || 415 LHSOp.getValueType() != RHSOp.getValueType())) 416 return false; 417 if (!Match(LHSCst, RHSCst)) 418 return false; 419 } 420 return true; 421 } 422 423 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) { 424 switch (VecReduceOpcode) { 425 default: 426 llvm_unreachable("Expected VECREDUCE opcode"); 427 case ISD::VECREDUCE_FADD: 428 case ISD::VECREDUCE_SEQ_FADD: 429 case ISD::VP_REDUCE_FADD: 430 case ISD::VP_REDUCE_SEQ_FADD: 431 return ISD::FADD; 432 case ISD::VECREDUCE_FMUL: 433 case ISD::VECREDUCE_SEQ_FMUL: 434 case ISD::VP_REDUCE_FMUL: 435 case ISD::VP_REDUCE_SEQ_FMUL: 436 return ISD::FMUL; 437 case ISD::VECREDUCE_ADD: 438 case ISD::VP_REDUCE_ADD: 439 return ISD::ADD; 440 case ISD::VECREDUCE_MUL: 441 case ISD::VP_REDUCE_MUL: 442 return ISD::MUL; 443 case ISD::VECREDUCE_AND: 444 case ISD::VP_REDUCE_AND: 445 return ISD::AND; 446 case ISD::VECREDUCE_OR: 447 case ISD::VP_REDUCE_OR: 448 return ISD::OR; 449 case ISD::VECREDUCE_XOR: 450 case ISD::VP_REDUCE_XOR: 451 return ISD::XOR; 452 case ISD::VECREDUCE_SMAX: 453 case ISD::VP_REDUCE_SMAX: 454 return ISD::SMAX; 455 case ISD::VECREDUCE_SMIN: 456 case ISD::VP_REDUCE_SMIN: 457 return ISD::SMIN; 458 case ISD::VECREDUCE_UMAX: 459 case ISD::VP_REDUCE_UMAX: 460 return ISD::UMAX; 461 case ISD::VECREDUCE_UMIN: 462 case ISD::VP_REDUCE_UMIN: 463 return ISD::UMIN; 464 case ISD::VECREDUCE_FMAX: 465 case ISD::VP_REDUCE_FMAX: 466 return ISD::FMAXNUM; 467 case ISD::VECREDUCE_FMIN: 468 case ISD::VP_REDUCE_FMIN: 469 return ISD::FMINNUM; 470 case ISD::VECREDUCE_FMAXIMUM: 471 return ISD::FMAXIMUM; 472 case ISD::VECREDUCE_FMINIMUM: 473 return ISD::FMINIMUM; 474 } 475 } 476 477 bool ISD::isVPOpcode(unsigned Opcode) { 478 switch (Opcode) { 479 default: 480 return false; 481 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \ 482 case ISD::VPSD: \ 483 return true; 484 #include "llvm/IR/VPIntrinsics.def" 485 } 486 } 487 488 bool ISD::isVPBinaryOp(unsigned Opcode) { 489 switch (Opcode) { 490 default: 491 break; 492 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 493 #define VP_PROPERTY_BINARYOP return true; 494 #define END_REGISTER_VP_SDNODE(VPSD) break; 495 #include "llvm/IR/VPIntrinsics.def" 496 } 497 return false; 498 } 499 500 bool ISD::isVPReduction(unsigned Opcode) { 501 switch (Opcode) { 502 default: 503 break; 504 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 505 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true; 506 #define END_REGISTER_VP_SDNODE(VPSD) break; 507 #include "llvm/IR/VPIntrinsics.def" 508 } 509 return false; 510 } 511 512 /// The operand position of the vector mask. 513 std::optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) { 514 switch (Opcode) { 515 default: 516 return std::nullopt; 517 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \ 518 case ISD::VPSD: \ 519 return MASKPOS; 520 #include "llvm/IR/VPIntrinsics.def" 521 } 522 } 523 524 /// The operand position of the explicit vector length parameter. 525 std::optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) { 526 switch (Opcode) { 527 default: 528 return std::nullopt; 529 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \ 530 case ISD::VPSD: \ 531 return EVLPOS; 532 #include "llvm/IR/VPIntrinsics.def" 533 } 534 } 535 536 std::optional<unsigned> ISD::getBaseOpcodeForVP(unsigned VPOpcode, 537 bool hasFPExcept) { 538 // FIXME: Return strict opcodes in case of fp exceptions. 539 switch (VPOpcode) { 540 default: 541 return std::nullopt; 542 #define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) case ISD::VPOPC: 543 #define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) return ISD::SDOPC; 544 #define END_REGISTER_VP_SDNODE(VPOPC) break; 545 #include "llvm/IR/VPIntrinsics.def" 546 } 547 return std::nullopt; 548 } 549 550 unsigned ISD::getVPForBaseOpcode(unsigned Opcode) { 551 switch (Opcode) { 552 default: 553 llvm_unreachable("can not translate this Opcode to VP."); 554 #define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) break; 555 #define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) case ISD::SDOPC: 556 #define END_REGISTER_VP_SDNODE(VPOPC) return ISD::VPOPC; 557 #include "llvm/IR/VPIntrinsics.def" 558 } 559 } 560 561 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 562 switch (ExtType) { 563 case ISD::EXTLOAD: 564 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 565 case ISD::SEXTLOAD: 566 return ISD::SIGN_EXTEND; 567 case ISD::ZEXTLOAD: 568 return ISD::ZERO_EXTEND; 569 default: 570 break; 571 } 572 573 llvm_unreachable("Invalid LoadExtType"); 574 } 575 576 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 577 // To perform this operation, we just need to swap the L and G bits of the 578 // operation. 579 unsigned OldL = (Operation >> 2) & 1; 580 unsigned OldG = (Operation >> 1) & 1; 581 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 582 (OldL << 1) | // New G bit 583 (OldG << 2)); // New L bit. 584 } 585 586 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) { 587 unsigned Operation = Op; 588 if (isIntegerLike) 589 Operation ^= 7; // Flip L, G, E bits, but not U. 590 else 591 Operation ^= 15; // Flip all of the condition bits. 592 593 if (Operation > ISD::SETTRUE2) 594 Operation &= ~8; // Don't let N and U bits get set. 595 596 return ISD::CondCode(Operation); 597 } 598 599 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) { 600 return getSetCCInverseImpl(Op, Type.isInteger()); 601 } 602 603 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op, 604 bool isIntegerLike) { 605 return getSetCCInverseImpl(Op, isIntegerLike); 606 } 607 608 /// For an integer comparison, return 1 if the comparison is a signed operation 609 /// and 2 if the result is an unsigned comparison. Return zero if the operation 610 /// does not depend on the sign of the input (setne and seteq). 611 static int isSignedOp(ISD::CondCode Opcode) { 612 switch (Opcode) { 613 default: llvm_unreachable("Illegal integer setcc operation!"); 614 case ISD::SETEQ: 615 case ISD::SETNE: return 0; 616 case ISD::SETLT: 617 case ISD::SETLE: 618 case ISD::SETGT: 619 case ISD::SETGE: return 1; 620 case ISD::SETULT: 621 case ISD::SETULE: 622 case ISD::SETUGT: 623 case ISD::SETUGE: return 2; 624 } 625 } 626 627 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 628 EVT Type) { 629 bool IsInteger = Type.isInteger(); 630 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 631 // Cannot fold a signed integer setcc with an unsigned integer setcc. 632 return ISD::SETCC_INVALID; 633 634 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 635 636 // If the N and U bits get set, then the resultant comparison DOES suddenly 637 // care about orderedness, and it is true when ordered. 638 if (Op > ISD::SETTRUE2) 639 Op &= ~16; // Clear the U bit if the N bit is set. 640 641 // Canonicalize illegal integer setcc's. 642 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 643 Op = ISD::SETNE; 644 645 return ISD::CondCode(Op); 646 } 647 648 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 649 EVT Type) { 650 bool IsInteger = Type.isInteger(); 651 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 652 // Cannot fold a signed setcc with an unsigned setcc. 653 return ISD::SETCC_INVALID; 654 655 // Combine all of the condition bits. 656 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 657 658 // Canonicalize illegal integer setcc's. 659 if (IsInteger) { 660 switch (Result) { 661 default: break; 662 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 663 case ISD::SETOEQ: // SETEQ & SETU[LG]E 664 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 665 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 666 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 667 } 668 } 669 670 return Result; 671 } 672 673 //===----------------------------------------------------------------------===// 674 // SDNode Profile Support 675 //===----------------------------------------------------------------------===// 676 677 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 678 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 679 ID.AddInteger(OpC); 680 } 681 682 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 683 /// solely with their pointer. 684 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 685 ID.AddPointer(VTList.VTs); 686 } 687 688 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 689 static void AddNodeIDOperands(FoldingSetNodeID &ID, 690 ArrayRef<SDValue> Ops) { 691 for (const auto &Op : Ops) { 692 ID.AddPointer(Op.getNode()); 693 ID.AddInteger(Op.getResNo()); 694 } 695 } 696 697 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 698 static void AddNodeIDOperands(FoldingSetNodeID &ID, 699 ArrayRef<SDUse> Ops) { 700 for (const auto &Op : Ops) { 701 ID.AddPointer(Op.getNode()); 702 ID.AddInteger(Op.getResNo()); 703 } 704 } 705 706 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned OpC, 707 SDVTList VTList, ArrayRef<SDValue> OpList) { 708 AddNodeIDOpcode(ID, OpC); 709 AddNodeIDValueTypes(ID, VTList); 710 AddNodeIDOperands(ID, OpList); 711 } 712 713 /// If this is an SDNode with special info, add this info to the NodeID data. 714 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 715 switch (N->getOpcode()) { 716 case ISD::TargetExternalSymbol: 717 case ISD::ExternalSymbol: 718 case ISD::MCSymbol: 719 llvm_unreachable("Should only be used on nodes with operands"); 720 default: break; // Normal nodes don't need extra info. 721 case ISD::TargetConstant: 722 case ISD::Constant: { 723 const ConstantSDNode *C = cast<ConstantSDNode>(N); 724 ID.AddPointer(C->getConstantIntValue()); 725 ID.AddBoolean(C->isOpaque()); 726 break; 727 } 728 case ISD::TargetConstantFP: 729 case ISD::ConstantFP: 730 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 731 break; 732 case ISD::TargetGlobalAddress: 733 case ISD::GlobalAddress: 734 case ISD::TargetGlobalTLSAddress: 735 case ISD::GlobalTLSAddress: { 736 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 737 ID.AddPointer(GA->getGlobal()); 738 ID.AddInteger(GA->getOffset()); 739 ID.AddInteger(GA->getTargetFlags()); 740 break; 741 } 742 case ISD::BasicBlock: 743 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 744 break; 745 case ISD::Register: 746 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 747 break; 748 case ISD::RegisterMask: 749 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 750 break; 751 case ISD::SRCVALUE: 752 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 753 break; 754 case ISD::FrameIndex: 755 case ISD::TargetFrameIndex: 756 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 757 break; 758 case ISD::LIFETIME_START: 759 case ISD::LIFETIME_END: 760 if (cast<LifetimeSDNode>(N)->hasOffset()) { 761 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize()); 762 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset()); 763 } 764 break; 765 case ISD::PSEUDO_PROBE: 766 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid()); 767 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex()); 768 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes()); 769 break; 770 case ISD::JumpTable: 771 case ISD::TargetJumpTable: 772 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 773 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 774 break; 775 case ISD::ConstantPool: 776 case ISD::TargetConstantPool: { 777 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 778 ID.AddInteger(CP->getAlign().value()); 779 ID.AddInteger(CP->getOffset()); 780 if (CP->isMachineConstantPoolEntry()) 781 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 782 else 783 ID.AddPointer(CP->getConstVal()); 784 ID.AddInteger(CP->getTargetFlags()); 785 break; 786 } 787 case ISD::TargetIndex: { 788 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 789 ID.AddInteger(TI->getIndex()); 790 ID.AddInteger(TI->getOffset()); 791 ID.AddInteger(TI->getTargetFlags()); 792 break; 793 } 794 case ISD::LOAD: { 795 const LoadSDNode *LD = cast<LoadSDNode>(N); 796 ID.AddInteger(LD->getMemoryVT().getRawBits()); 797 ID.AddInteger(LD->getRawSubclassData()); 798 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 799 ID.AddInteger(LD->getMemOperand()->getFlags()); 800 break; 801 } 802 case ISD::STORE: { 803 const StoreSDNode *ST = cast<StoreSDNode>(N); 804 ID.AddInteger(ST->getMemoryVT().getRawBits()); 805 ID.AddInteger(ST->getRawSubclassData()); 806 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 807 ID.AddInteger(ST->getMemOperand()->getFlags()); 808 break; 809 } 810 case ISD::VP_LOAD: { 811 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N); 812 ID.AddInteger(ELD->getMemoryVT().getRawBits()); 813 ID.AddInteger(ELD->getRawSubclassData()); 814 ID.AddInteger(ELD->getPointerInfo().getAddrSpace()); 815 ID.AddInteger(ELD->getMemOperand()->getFlags()); 816 break; 817 } 818 case ISD::VP_STORE: { 819 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N); 820 ID.AddInteger(EST->getMemoryVT().getRawBits()); 821 ID.AddInteger(EST->getRawSubclassData()); 822 ID.AddInteger(EST->getPointerInfo().getAddrSpace()); 823 ID.AddInteger(EST->getMemOperand()->getFlags()); 824 break; 825 } 826 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: { 827 const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N); 828 ID.AddInteger(SLD->getMemoryVT().getRawBits()); 829 ID.AddInteger(SLD->getRawSubclassData()); 830 ID.AddInteger(SLD->getPointerInfo().getAddrSpace()); 831 break; 832 } 833 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: { 834 const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N); 835 ID.AddInteger(SST->getMemoryVT().getRawBits()); 836 ID.AddInteger(SST->getRawSubclassData()); 837 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 838 break; 839 } 840 case ISD::VP_GATHER: { 841 const VPGatherSDNode *EG = cast<VPGatherSDNode>(N); 842 ID.AddInteger(EG->getMemoryVT().getRawBits()); 843 ID.AddInteger(EG->getRawSubclassData()); 844 ID.AddInteger(EG->getPointerInfo().getAddrSpace()); 845 ID.AddInteger(EG->getMemOperand()->getFlags()); 846 break; 847 } 848 case ISD::VP_SCATTER: { 849 const VPScatterSDNode *ES = cast<VPScatterSDNode>(N); 850 ID.AddInteger(ES->getMemoryVT().getRawBits()); 851 ID.AddInteger(ES->getRawSubclassData()); 852 ID.AddInteger(ES->getPointerInfo().getAddrSpace()); 853 ID.AddInteger(ES->getMemOperand()->getFlags()); 854 break; 855 } 856 case ISD::MLOAD: { 857 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 858 ID.AddInteger(MLD->getMemoryVT().getRawBits()); 859 ID.AddInteger(MLD->getRawSubclassData()); 860 ID.AddInteger(MLD->getPointerInfo().getAddrSpace()); 861 ID.AddInteger(MLD->getMemOperand()->getFlags()); 862 break; 863 } 864 case ISD::MSTORE: { 865 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 866 ID.AddInteger(MST->getMemoryVT().getRawBits()); 867 ID.AddInteger(MST->getRawSubclassData()); 868 ID.AddInteger(MST->getPointerInfo().getAddrSpace()); 869 ID.AddInteger(MST->getMemOperand()->getFlags()); 870 break; 871 } 872 case ISD::MGATHER: { 873 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N); 874 ID.AddInteger(MG->getMemoryVT().getRawBits()); 875 ID.AddInteger(MG->getRawSubclassData()); 876 ID.AddInteger(MG->getPointerInfo().getAddrSpace()); 877 ID.AddInteger(MG->getMemOperand()->getFlags()); 878 break; 879 } 880 case ISD::MSCATTER: { 881 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N); 882 ID.AddInteger(MS->getMemoryVT().getRawBits()); 883 ID.AddInteger(MS->getRawSubclassData()); 884 ID.AddInteger(MS->getPointerInfo().getAddrSpace()); 885 ID.AddInteger(MS->getMemOperand()->getFlags()); 886 break; 887 } 888 case ISD::ATOMIC_CMP_SWAP: 889 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 890 case ISD::ATOMIC_SWAP: 891 case ISD::ATOMIC_LOAD_ADD: 892 case ISD::ATOMIC_LOAD_SUB: 893 case ISD::ATOMIC_LOAD_AND: 894 case ISD::ATOMIC_LOAD_CLR: 895 case ISD::ATOMIC_LOAD_OR: 896 case ISD::ATOMIC_LOAD_XOR: 897 case ISD::ATOMIC_LOAD_NAND: 898 case ISD::ATOMIC_LOAD_MIN: 899 case ISD::ATOMIC_LOAD_MAX: 900 case ISD::ATOMIC_LOAD_UMIN: 901 case ISD::ATOMIC_LOAD_UMAX: 902 case ISD::ATOMIC_LOAD: 903 case ISD::ATOMIC_STORE: { 904 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 905 ID.AddInteger(AT->getMemoryVT().getRawBits()); 906 ID.AddInteger(AT->getRawSubclassData()); 907 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 908 ID.AddInteger(AT->getMemOperand()->getFlags()); 909 break; 910 } 911 case ISD::VECTOR_SHUFFLE: { 912 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 913 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 914 i != e; ++i) 915 ID.AddInteger(SVN->getMaskElt(i)); 916 break; 917 } 918 case ISD::TargetBlockAddress: 919 case ISD::BlockAddress: { 920 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 921 ID.AddPointer(BA->getBlockAddress()); 922 ID.AddInteger(BA->getOffset()); 923 ID.AddInteger(BA->getTargetFlags()); 924 break; 925 } 926 case ISD::AssertAlign: 927 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value()); 928 break; 929 case ISD::PREFETCH: 930 case ISD::INTRINSIC_VOID: 931 case ISD::INTRINSIC_W_CHAIN: 932 // Handled by MemIntrinsicSDNode check after the switch. 933 break; 934 } // end switch (N->getOpcode()) 935 936 // MemIntrinsic nodes could also have subclass data, address spaces, and flags 937 // to check. 938 if (auto *MN = dyn_cast<MemIntrinsicSDNode>(N)) { 939 ID.AddInteger(MN->getRawSubclassData()); 940 ID.AddInteger(MN->getPointerInfo().getAddrSpace()); 941 ID.AddInteger(MN->getMemOperand()->getFlags()); 942 ID.AddInteger(MN->getMemoryVT().getRawBits()); 943 } 944 } 945 946 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 947 /// data. 948 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 949 AddNodeIDOpcode(ID, N->getOpcode()); 950 // Add the return value info. 951 AddNodeIDValueTypes(ID, N->getVTList()); 952 // Add the operand info. 953 AddNodeIDOperands(ID, N->ops()); 954 955 // Handle SDNode leafs with special info. 956 AddNodeIDCustom(ID, N); 957 } 958 959 //===----------------------------------------------------------------------===// 960 // SelectionDAG Class 961 //===----------------------------------------------------------------------===// 962 963 /// doNotCSE - Return true if CSE should not be performed for this node. 964 static bool doNotCSE(SDNode *N) { 965 if (N->getValueType(0) == MVT::Glue) 966 return true; // Never CSE anything that produces a glue result. 967 968 switch (N->getOpcode()) { 969 default: break; 970 case ISD::HANDLENODE: 971 case ISD::EH_LABEL: 972 return true; // Never CSE these nodes. 973 } 974 975 // Check that remaining values produced are not flags. 976 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 977 if (N->getValueType(i) == MVT::Glue) 978 return true; // Never CSE anything that produces a glue result. 979 980 return false; 981 } 982 983 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 984 /// SelectionDAG. 985 void SelectionDAG::RemoveDeadNodes() { 986 // Create a dummy node (which is not added to allnodes), that adds a reference 987 // to the root node, preventing it from being deleted. 988 HandleSDNode Dummy(getRoot()); 989 990 SmallVector<SDNode*, 128> DeadNodes; 991 992 // Add all obviously-dead nodes to the DeadNodes worklist. 993 for (SDNode &Node : allnodes()) 994 if (Node.use_empty()) 995 DeadNodes.push_back(&Node); 996 997 RemoveDeadNodes(DeadNodes); 998 999 // If the root changed (e.g. it was a dead load, update the root). 1000 setRoot(Dummy.getValue()); 1001 } 1002 1003 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 1004 /// given list, and any nodes that become unreachable as a result. 1005 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 1006 1007 // Process the worklist, deleting the nodes and adding their uses to the 1008 // worklist. 1009 while (!DeadNodes.empty()) { 1010 SDNode *N = DeadNodes.pop_back_val(); 1011 // Skip to next node if we've already managed to delete the node. This could 1012 // happen if replacing a node causes a node previously added to the node to 1013 // be deleted. 1014 if (N->getOpcode() == ISD::DELETED_NODE) 1015 continue; 1016 1017 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1018 DUL->NodeDeleted(N, nullptr); 1019 1020 // Take the node out of the appropriate CSE map. 1021 RemoveNodeFromCSEMaps(N); 1022 1023 // Next, brutally remove the operand list. This is safe to do, as there are 1024 // no cycles in the graph. 1025 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 1026 SDUse &Use = *I++; 1027 SDNode *Operand = Use.getNode(); 1028 Use.set(SDValue()); 1029 1030 // Now that we removed this operand, see if there are no uses of it left. 1031 if (Operand->use_empty()) 1032 DeadNodes.push_back(Operand); 1033 } 1034 1035 DeallocateNode(N); 1036 } 1037 } 1038 1039 void SelectionDAG::RemoveDeadNode(SDNode *N){ 1040 SmallVector<SDNode*, 16> DeadNodes(1, N); 1041 1042 // Create a dummy node that adds a reference to the root node, preventing 1043 // it from being deleted. (This matters if the root is an operand of the 1044 // dead node.) 1045 HandleSDNode Dummy(getRoot()); 1046 1047 RemoveDeadNodes(DeadNodes); 1048 } 1049 1050 void SelectionDAG::DeleteNode(SDNode *N) { 1051 // First take this out of the appropriate CSE map. 1052 RemoveNodeFromCSEMaps(N); 1053 1054 // Finally, remove uses due to operands of this node, remove from the 1055 // AllNodes list, and delete the node. 1056 DeleteNodeNotInCSEMaps(N); 1057 } 1058 1059 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 1060 assert(N->getIterator() != AllNodes.begin() && 1061 "Cannot delete the entry node!"); 1062 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 1063 1064 // Drop all of the operands and decrement used node's use counts. 1065 N->DropOperands(); 1066 1067 DeallocateNode(N); 1068 } 1069 1070 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) { 1071 assert(!(V->isVariadic() && isParameter)); 1072 if (isParameter) 1073 ByvalParmDbgValues.push_back(V); 1074 else 1075 DbgValues.push_back(V); 1076 for (const SDNode *Node : V->getSDNodes()) 1077 if (Node) 1078 DbgValMap[Node].push_back(V); 1079 } 1080 1081 void SDDbgInfo::erase(const SDNode *Node) { 1082 DbgValMapType::iterator I = DbgValMap.find(Node); 1083 if (I == DbgValMap.end()) 1084 return; 1085 for (auto &Val: I->second) 1086 Val->setIsInvalidated(); 1087 DbgValMap.erase(I); 1088 } 1089 1090 void SelectionDAG::DeallocateNode(SDNode *N) { 1091 // If we have operands, deallocate them. 1092 removeOperands(N); 1093 1094 NodeAllocator.Deallocate(AllNodes.remove(N)); 1095 1096 // Set the opcode to DELETED_NODE to help catch bugs when node 1097 // memory is reallocated. 1098 // FIXME: There are places in SDag that have grown a dependency on the opcode 1099 // value in the released node. 1100 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 1101 N->NodeType = ISD::DELETED_NODE; 1102 1103 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 1104 // them and forget about that node. 1105 DbgInfo->erase(N); 1106 1107 // Invalidate extra info. 1108 SDEI.erase(N); 1109 } 1110 1111 #ifndef NDEBUG 1112 /// VerifySDNode - Check the given SDNode. Aborts if it is invalid. 1113 static void VerifySDNode(SDNode *N) { 1114 switch (N->getOpcode()) { 1115 default: 1116 break; 1117 case ISD::BUILD_PAIR: { 1118 EVT VT = N->getValueType(0); 1119 assert(N->getNumValues() == 1 && "Too many results!"); 1120 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 1121 "Wrong return type!"); 1122 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 1123 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 1124 "Mismatched operand types!"); 1125 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 1126 "Wrong operand type!"); 1127 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 1128 "Wrong return type size"); 1129 break; 1130 } 1131 case ISD::BUILD_VECTOR: { 1132 assert(N->getNumValues() == 1 && "Too many results!"); 1133 assert(N->getValueType(0).isVector() && "Wrong return type!"); 1134 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 1135 "Wrong number of operands!"); 1136 EVT EltVT = N->getValueType(0).getVectorElementType(); 1137 for (const SDUse &Op : N->ops()) { 1138 assert((Op.getValueType() == EltVT || 1139 (EltVT.isInteger() && Op.getValueType().isInteger() && 1140 EltVT.bitsLE(Op.getValueType()))) && 1141 "Wrong operand type!"); 1142 assert(Op.getValueType() == N->getOperand(0).getValueType() && 1143 "Operands must all have the same type"); 1144 } 1145 break; 1146 } 1147 } 1148 } 1149 #endif // NDEBUG 1150 1151 /// Insert a newly allocated node into the DAG. 1152 /// 1153 /// Handles insertion into the all nodes list and CSE map, as well as 1154 /// verification and other common operations when a new node is allocated. 1155 void SelectionDAG::InsertNode(SDNode *N) { 1156 AllNodes.push_back(N); 1157 #ifndef NDEBUG 1158 N->PersistentId = NextPersistentId++; 1159 VerifySDNode(N); 1160 #endif 1161 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1162 DUL->NodeInserted(N); 1163 } 1164 1165 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 1166 /// correspond to it. This is useful when we're about to delete or repurpose 1167 /// the node. We don't want future request for structurally identical nodes 1168 /// to return N anymore. 1169 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 1170 bool Erased = false; 1171 switch (N->getOpcode()) { 1172 case ISD::HANDLENODE: return false; // noop. 1173 case ISD::CONDCODE: 1174 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 1175 "Cond code doesn't exist!"); 1176 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 1177 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 1178 break; 1179 case ISD::ExternalSymbol: 1180 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 1181 break; 1182 case ISD::TargetExternalSymbol: { 1183 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 1184 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 1185 ESN->getSymbol(), ESN->getTargetFlags())); 1186 break; 1187 } 1188 case ISD::MCSymbol: { 1189 auto *MCSN = cast<MCSymbolSDNode>(N); 1190 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 1191 break; 1192 } 1193 case ISD::VALUETYPE: { 1194 EVT VT = cast<VTSDNode>(N)->getVT(); 1195 if (VT.isExtended()) { 1196 Erased = ExtendedValueTypeNodes.erase(VT); 1197 } else { 1198 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 1199 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 1200 } 1201 break; 1202 } 1203 default: 1204 // Remove it from the CSE Map. 1205 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 1206 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 1207 Erased = CSEMap.RemoveNode(N); 1208 break; 1209 } 1210 #ifndef NDEBUG 1211 // Verify that the node was actually in one of the CSE maps, unless it has a 1212 // glue result (which cannot be CSE'd) or is one of the special cases that are 1213 // not subject to CSE. 1214 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 1215 !N->isMachineOpcode() && !doNotCSE(N)) { 1216 N->dump(this); 1217 dbgs() << "\n"; 1218 llvm_unreachable("Node is not in map!"); 1219 } 1220 #endif 1221 return Erased; 1222 } 1223 1224 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 1225 /// maps and modified in place. Add it back to the CSE maps, unless an identical 1226 /// node already exists, in which case transfer all its users to the existing 1227 /// node. This transfer can potentially trigger recursive merging. 1228 void 1229 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 1230 // For node types that aren't CSE'd, just act as if no identical node 1231 // already exists. 1232 if (!doNotCSE(N)) { 1233 SDNode *Existing = CSEMap.GetOrInsertNode(N); 1234 if (Existing != N) { 1235 // If there was already an existing matching node, use ReplaceAllUsesWith 1236 // to replace the dead one with the existing one. This can cause 1237 // recursive merging of other unrelated nodes down the line. 1238 ReplaceAllUsesWith(N, Existing); 1239 1240 // N is now dead. Inform the listeners and delete it. 1241 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1242 DUL->NodeDeleted(N, Existing); 1243 DeleteNodeNotInCSEMaps(N); 1244 return; 1245 } 1246 } 1247 1248 // If the node doesn't already exist, we updated it. Inform listeners. 1249 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1250 DUL->NodeUpdated(N); 1251 } 1252 1253 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1254 /// were replaced with those specified. If this node is never memoized, 1255 /// return null, otherwise return a pointer to the slot it would take. If a 1256 /// node already exists with these operands, the slot will be non-null. 1257 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1258 void *&InsertPos) { 1259 if (doNotCSE(N)) 1260 return nullptr; 1261 1262 SDValue Ops[] = { Op }; 1263 FoldingSetNodeID ID; 1264 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1265 AddNodeIDCustom(ID, N); 1266 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1267 if (Node) 1268 Node->intersectFlagsWith(N->getFlags()); 1269 return Node; 1270 } 1271 1272 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1273 /// were replaced with those specified. If this node is never memoized, 1274 /// return null, otherwise return a pointer to the slot it would take. If a 1275 /// node already exists with these operands, the slot will be non-null. 1276 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1277 SDValue Op1, SDValue Op2, 1278 void *&InsertPos) { 1279 if (doNotCSE(N)) 1280 return nullptr; 1281 1282 SDValue Ops[] = { Op1, Op2 }; 1283 FoldingSetNodeID ID; 1284 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1285 AddNodeIDCustom(ID, N); 1286 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1287 if (Node) 1288 Node->intersectFlagsWith(N->getFlags()); 1289 return Node; 1290 } 1291 1292 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1293 /// were replaced with those specified. If this node is never memoized, 1294 /// return null, otherwise return a pointer to the slot it would take. If a 1295 /// node already exists with these operands, the slot will be non-null. 1296 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1297 void *&InsertPos) { 1298 if (doNotCSE(N)) 1299 return nullptr; 1300 1301 FoldingSetNodeID ID; 1302 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1303 AddNodeIDCustom(ID, N); 1304 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1305 if (Node) 1306 Node->intersectFlagsWith(N->getFlags()); 1307 return Node; 1308 } 1309 1310 Align SelectionDAG::getEVTAlign(EVT VT) const { 1311 Type *Ty = VT == MVT::iPTR ? PointerType::get(*getContext(), 0) 1312 : VT.getTypeForEVT(*getContext()); 1313 1314 return getDataLayout().getABITypeAlign(Ty); 1315 } 1316 1317 // EntryNode could meaningfully have debug info if we can find it... 1318 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOptLevel OL) 1319 : TM(tm), OptLevel(OL), EntryNode(ISD::EntryToken, 0, DebugLoc(), 1320 getVTList(MVT::Other, MVT::Glue)), 1321 Root(getEntryNode()) { 1322 InsertNode(&EntryNode); 1323 DbgInfo = new SDDbgInfo(); 1324 } 1325 1326 void SelectionDAG::init(MachineFunction &NewMF, 1327 OptimizationRemarkEmitter &NewORE, Pass *PassPtr, 1328 const TargetLibraryInfo *LibraryInfo, 1329 UniformityInfo *NewUA, ProfileSummaryInfo *PSIin, 1330 BlockFrequencyInfo *BFIin, 1331 FunctionVarLocs const *VarLocs) { 1332 MF = &NewMF; 1333 SDAGISelPass = PassPtr; 1334 ORE = &NewORE; 1335 TLI = getSubtarget().getTargetLowering(); 1336 TSI = getSubtarget().getSelectionDAGInfo(); 1337 LibInfo = LibraryInfo; 1338 Context = &MF->getFunction().getContext(); 1339 UA = NewUA; 1340 PSI = PSIin; 1341 BFI = BFIin; 1342 FnVarLocs = VarLocs; 1343 } 1344 1345 SelectionDAG::~SelectionDAG() { 1346 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1347 allnodes_clear(); 1348 OperandRecycler.clear(OperandAllocator); 1349 delete DbgInfo; 1350 } 1351 1352 bool SelectionDAG::shouldOptForSize() const { 1353 return MF->getFunction().hasOptSize() || 1354 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1355 } 1356 1357 void SelectionDAG::allnodes_clear() { 1358 assert(&*AllNodes.begin() == &EntryNode); 1359 AllNodes.remove(AllNodes.begin()); 1360 while (!AllNodes.empty()) 1361 DeallocateNode(&AllNodes.front()); 1362 #ifndef NDEBUG 1363 NextPersistentId = 0; 1364 #endif 1365 } 1366 1367 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1368 void *&InsertPos) { 1369 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1370 if (N) { 1371 switch (N->getOpcode()) { 1372 default: break; 1373 case ISD::Constant: 1374 case ISD::ConstantFP: 1375 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1376 "debug location. Use another overload."); 1377 } 1378 } 1379 return N; 1380 } 1381 1382 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1383 const SDLoc &DL, void *&InsertPos) { 1384 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1385 if (N) { 1386 switch (N->getOpcode()) { 1387 case ISD::Constant: 1388 case ISD::ConstantFP: 1389 // Erase debug location from the node if the node is used at several 1390 // different places. Do not propagate one location to all uses as it 1391 // will cause a worse single stepping debugging experience. 1392 if (N->getDebugLoc() != DL.getDebugLoc()) 1393 N->setDebugLoc(DebugLoc()); 1394 break; 1395 default: 1396 // When the node's point of use is located earlier in the instruction 1397 // sequence than its prior point of use, update its debug info to the 1398 // earlier location. 1399 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1400 N->setDebugLoc(DL.getDebugLoc()); 1401 break; 1402 } 1403 } 1404 return N; 1405 } 1406 1407 void SelectionDAG::clear() { 1408 allnodes_clear(); 1409 OperandRecycler.clear(OperandAllocator); 1410 OperandAllocator.Reset(); 1411 CSEMap.clear(); 1412 1413 ExtendedValueTypeNodes.clear(); 1414 ExternalSymbols.clear(); 1415 TargetExternalSymbols.clear(); 1416 MCSymbols.clear(); 1417 SDEI.clear(); 1418 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1419 static_cast<CondCodeSDNode*>(nullptr)); 1420 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1421 static_cast<SDNode*>(nullptr)); 1422 1423 EntryNode.UseList = nullptr; 1424 InsertNode(&EntryNode); 1425 Root = getEntryNode(); 1426 DbgInfo->clear(); 1427 } 1428 1429 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1430 return VT.bitsGT(Op.getValueType()) 1431 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1432 : getNode(ISD::FP_ROUND, DL, VT, Op, 1433 getIntPtrConstant(0, DL, /*isTarget=*/true)); 1434 } 1435 1436 std::pair<SDValue, SDValue> 1437 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1438 const SDLoc &DL, EVT VT) { 1439 assert(!VT.bitsEq(Op.getValueType()) && 1440 "Strict no-op FP extend/round not allowed."); 1441 SDValue Res = 1442 VT.bitsGT(Op.getValueType()) 1443 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1444 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1445 {Chain, Op, getIntPtrConstant(0, DL)}); 1446 1447 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1448 } 1449 1450 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1451 return VT.bitsGT(Op.getValueType()) ? 1452 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1453 getNode(ISD::TRUNCATE, DL, VT, Op); 1454 } 1455 1456 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1457 return VT.bitsGT(Op.getValueType()) ? 1458 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1459 getNode(ISD::TRUNCATE, DL, VT, Op); 1460 } 1461 1462 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1463 return VT.bitsGT(Op.getValueType()) ? 1464 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1465 getNode(ISD::TRUNCATE, DL, VT, Op); 1466 } 1467 1468 SDValue SelectionDAG::getBitcastedAnyExtOrTrunc(SDValue Op, const SDLoc &DL, 1469 EVT VT) { 1470 assert(!VT.isVector()); 1471 auto Type = Op.getValueType(); 1472 SDValue DestOp; 1473 if (Type == VT) 1474 return Op; 1475 auto Size = Op.getValueSizeInBits(); 1476 DestOp = getBitcast(MVT::getIntegerVT(Size), Op); 1477 if (DestOp.getValueType() == VT) 1478 return DestOp; 1479 1480 return getAnyExtOrTrunc(DestOp, DL, VT); 1481 } 1482 1483 SDValue SelectionDAG::getBitcastedSExtOrTrunc(SDValue Op, const SDLoc &DL, 1484 EVT VT) { 1485 assert(!VT.isVector()); 1486 auto Type = Op.getValueType(); 1487 SDValue DestOp; 1488 if (Type == VT) 1489 return Op; 1490 auto Size = Op.getValueSizeInBits(); 1491 DestOp = getBitcast(MVT::getIntegerVT(Size), Op); 1492 if (DestOp.getValueType() == VT) 1493 return DestOp; 1494 1495 return getSExtOrTrunc(DestOp, DL, VT); 1496 } 1497 1498 SDValue SelectionDAG::getBitcastedZExtOrTrunc(SDValue Op, const SDLoc &DL, 1499 EVT VT) { 1500 assert(!VT.isVector()); 1501 auto Type = Op.getValueType(); 1502 SDValue DestOp; 1503 if (Type == VT) 1504 return Op; 1505 auto Size = Op.getValueSizeInBits(); 1506 DestOp = getBitcast(MVT::getIntegerVT(Size), Op); 1507 if (DestOp.getValueType() == VT) 1508 return DestOp; 1509 1510 return getZExtOrTrunc(DestOp, DL, VT); 1511 } 1512 1513 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1514 EVT OpVT) { 1515 if (VT.bitsLE(Op.getValueType())) 1516 return getNode(ISD::TRUNCATE, SL, VT, Op); 1517 1518 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1519 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1520 } 1521 1522 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1523 EVT OpVT = Op.getValueType(); 1524 assert(VT.isInteger() && OpVT.isInteger() && 1525 "Cannot getZeroExtendInReg FP types"); 1526 assert(VT.isVector() == OpVT.isVector() && 1527 "getZeroExtendInReg type should be vector iff the operand " 1528 "type is vector!"); 1529 assert((!VT.isVector() || 1530 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1531 "Vector element counts must match in getZeroExtendInReg"); 1532 assert(VT.bitsLE(OpVT) && "Not extending!"); 1533 if (OpVT == VT) 1534 return Op; 1535 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1536 VT.getScalarSizeInBits()); 1537 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1538 } 1539 1540 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1541 // Only unsigned pointer semantics are supported right now. In the future this 1542 // might delegate to TLI to check pointer signedness. 1543 return getZExtOrTrunc(Op, DL, VT); 1544 } 1545 1546 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1547 // Only unsigned pointer semantics are supported right now. In the future this 1548 // might delegate to TLI to check pointer signedness. 1549 return getZeroExtendInReg(Op, DL, VT); 1550 } 1551 1552 SDValue SelectionDAG::getNegative(SDValue Val, const SDLoc &DL, EVT VT) { 1553 return getNode(ISD::SUB, DL, VT, getConstant(0, DL, VT), Val); 1554 } 1555 1556 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1557 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1558 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT)); 1559 } 1560 1561 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1562 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1563 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1564 } 1565 1566 SDValue SelectionDAG::getVPLogicalNOT(const SDLoc &DL, SDValue Val, 1567 SDValue Mask, SDValue EVL, EVT VT) { 1568 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1569 return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL); 1570 } 1571 1572 SDValue SelectionDAG::getVPPtrExtOrTrunc(const SDLoc &DL, EVT VT, SDValue Op, 1573 SDValue Mask, SDValue EVL) { 1574 return getVPZExtOrTrunc(DL, VT, Op, Mask, EVL); 1575 } 1576 1577 SDValue SelectionDAG::getVPZExtOrTrunc(const SDLoc &DL, EVT VT, SDValue Op, 1578 SDValue Mask, SDValue EVL) { 1579 if (VT.bitsGT(Op.getValueType())) 1580 return getNode(ISD::VP_ZERO_EXTEND, DL, VT, Op, Mask, EVL); 1581 if (VT.bitsLT(Op.getValueType())) 1582 return getNode(ISD::VP_TRUNCATE, DL, VT, Op, Mask, EVL); 1583 return Op; 1584 } 1585 1586 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1587 EVT OpVT) { 1588 if (!V) 1589 return getConstant(0, DL, VT); 1590 1591 switch (TLI->getBooleanContents(OpVT)) { 1592 case TargetLowering::ZeroOrOneBooleanContent: 1593 case TargetLowering::UndefinedBooleanContent: 1594 return getConstant(1, DL, VT); 1595 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1596 return getAllOnesConstant(DL, VT); 1597 } 1598 llvm_unreachable("Unexpected boolean content enum!"); 1599 } 1600 1601 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1602 bool isT, bool isO) { 1603 EVT EltVT = VT.getScalarType(); 1604 assert((EltVT.getSizeInBits() >= 64 || 1605 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1606 "getConstant with a uint64_t value that doesn't fit in the type!"); 1607 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1608 } 1609 1610 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1611 bool isT, bool isO) { 1612 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1613 } 1614 1615 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1616 EVT VT, bool isT, bool isO) { 1617 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1618 1619 EVT EltVT = VT.getScalarType(); 1620 const ConstantInt *Elt = &Val; 1621 1622 // In some cases the vector type is legal but the element type is illegal and 1623 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1624 // inserted value (the type does not need to match the vector element type). 1625 // Any extra bits introduced will be truncated away. 1626 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1627 TargetLowering::TypePromoteInteger) { 1628 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1629 APInt NewVal; 1630 if (TLI->isSExtCheaperThanZExt(VT.getScalarType(), EltVT)) 1631 NewVal = Elt->getValue().sextOrTrunc(EltVT.getSizeInBits()); 1632 else 1633 NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1634 Elt = ConstantInt::get(*getContext(), NewVal); 1635 } 1636 // In other cases the element type is illegal and needs to be expanded, for 1637 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1638 // the value into n parts and use a vector type with n-times the elements. 1639 // Then bitcast to the type requested. 1640 // Legalizing constants too early makes the DAGCombiner's job harder so we 1641 // only legalize if the DAG tells us we must produce legal types. 1642 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1643 TLI->getTypeAction(*getContext(), EltVT) == 1644 TargetLowering::TypeExpandInteger) { 1645 const APInt &NewVal = Elt->getValue(); 1646 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1647 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1648 1649 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node. 1650 if (VT.isScalableVector() || 1651 TLI->isOperationLegal(ISD::SPLAT_VECTOR, VT)) { 1652 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 && 1653 "Can only handle an even split!"); 1654 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits; 1655 1656 SmallVector<SDValue, 2> ScalarParts; 1657 for (unsigned i = 0; i != Parts; ++i) 1658 ScalarParts.push_back(getConstant( 1659 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1660 ViaEltVT, isT, isO)); 1661 1662 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts); 1663 } 1664 1665 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1666 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1667 1668 // Check the temporary vector is the correct size. If this fails then 1669 // getTypeToTransformTo() probably returned a type whose size (in bits) 1670 // isn't a power-of-2 factor of the requested type size. 1671 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1672 1673 SmallVector<SDValue, 2> EltParts; 1674 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) 1675 EltParts.push_back(getConstant( 1676 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1677 ViaEltVT, isT, isO)); 1678 1679 // EltParts is currently in little endian order. If we actually want 1680 // big-endian order then reverse it now. 1681 if (getDataLayout().isBigEndian()) 1682 std::reverse(EltParts.begin(), EltParts.end()); 1683 1684 // The elements must be reversed when the element order is different 1685 // to the endianness of the elements (because the BITCAST is itself a 1686 // vector shuffle in this situation). However, we do not need any code to 1687 // perform this reversal because getConstant() is producing a vector 1688 // splat. 1689 // This situation occurs in MIPS MSA. 1690 1691 SmallVector<SDValue, 8> Ops; 1692 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1693 llvm::append_range(Ops, EltParts); 1694 1695 SDValue V = 1696 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1697 return V; 1698 } 1699 1700 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1701 "APInt size does not match type size!"); 1702 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1703 FoldingSetNodeID ID; 1704 AddNodeIDNode(ID, Opc, getVTList(EltVT), std::nullopt); 1705 ID.AddPointer(Elt); 1706 ID.AddBoolean(isO); 1707 void *IP = nullptr; 1708 SDNode *N = nullptr; 1709 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1710 if (!VT.isVector()) 1711 return SDValue(N, 0); 1712 1713 if (!N) { 1714 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1715 CSEMap.InsertNode(N, IP); 1716 InsertNode(N); 1717 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1718 } 1719 1720 SDValue Result(N, 0); 1721 if (VT.isVector()) 1722 Result = getSplat(VT, DL, Result); 1723 return Result; 1724 } 1725 1726 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1727 bool isTarget) { 1728 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1729 } 1730 1731 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1732 const SDLoc &DL, bool LegalTypes) { 1733 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1734 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1735 return getConstant(Val, DL, ShiftVT); 1736 } 1737 1738 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1739 bool isTarget) { 1740 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1741 } 1742 1743 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1744 bool isTarget) { 1745 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1746 } 1747 1748 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1749 EVT VT, bool isTarget) { 1750 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1751 1752 EVT EltVT = VT.getScalarType(); 1753 1754 // Do the map lookup using the actual bit pattern for the floating point 1755 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1756 // we don't have issues with SNANs. 1757 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1758 FoldingSetNodeID ID; 1759 AddNodeIDNode(ID, Opc, getVTList(EltVT), std::nullopt); 1760 ID.AddPointer(&V); 1761 void *IP = nullptr; 1762 SDNode *N = nullptr; 1763 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1764 if (!VT.isVector()) 1765 return SDValue(N, 0); 1766 1767 if (!N) { 1768 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1769 CSEMap.InsertNode(N, IP); 1770 InsertNode(N); 1771 } 1772 1773 SDValue Result(N, 0); 1774 if (VT.isVector()) 1775 Result = getSplat(VT, DL, Result); 1776 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1777 return Result; 1778 } 1779 1780 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1781 bool isTarget) { 1782 EVT EltVT = VT.getScalarType(); 1783 if (EltVT == MVT::f32) 1784 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1785 if (EltVT == MVT::f64) 1786 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1787 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1788 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1789 bool Ignored; 1790 APFloat APF = APFloat(Val); 1791 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1792 &Ignored); 1793 return getConstantFP(APF, DL, VT, isTarget); 1794 } 1795 llvm_unreachable("Unsupported type in getConstantFP"); 1796 } 1797 1798 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1799 EVT VT, int64_t Offset, bool isTargetGA, 1800 unsigned TargetFlags) { 1801 assert((TargetFlags == 0 || isTargetGA) && 1802 "Cannot set target flags on target-independent globals"); 1803 1804 // Truncate (with sign-extension) the offset value to the pointer size. 1805 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1806 if (BitWidth < 64) 1807 Offset = SignExtend64(Offset, BitWidth); 1808 1809 unsigned Opc; 1810 if (GV->isThreadLocal()) 1811 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1812 else 1813 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1814 1815 FoldingSetNodeID ID; 1816 AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt); 1817 ID.AddPointer(GV); 1818 ID.AddInteger(Offset); 1819 ID.AddInteger(TargetFlags); 1820 void *IP = nullptr; 1821 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1822 return SDValue(E, 0); 1823 1824 auto *N = newSDNode<GlobalAddressSDNode>( 1825 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1826 CSEMap.InsertNode(N, IP); 1827 InsertNode(N); 1828 return SDValue(N, 0); 1829 } 1830 1831 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1832 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1833 FoldingSetNodeID ID; 1834 AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt); 1835 ID.AddInteger(FI); 1836 void *IP = nullptr; 1837 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1838 return SDValue(E, 0); 1839 1840 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1841 CSEMap.InsertNode(N, IP); 1842 InsertNode(N); 1843 return SDValue(N, 0); 1844 } 1845 1846 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1847 unsigned TargetFlags) { 1848 assert((TargetFlags == 0 || isTarget) && 1849 "Cannot set target flags on target-independent jump tables"); 1850 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1851 FoldingSetNodeID ID; 1852 AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt); 1853 ID.AddInteger(JTI); 1854 ID.AddInteger(TargetFlags); 1855 void *IP = nullptr; 1856 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1857 return SDValue(E, 0); 1858 1859 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1860 CSEMap.InsertNode(N, IP); 1861 InsertNode(N); 1862 return SDValue(N, 0); 1863 } 1864 1865 SDValue SelectionDAG::getJumpTableDebugInfo(int JTI, SDValue Chain, 1866 const SDLoc &DL) { 1867 EVT PTy = getTargetLoweringInfo().getPointerTy(getDataLayout()); 1868 return getNode(ISD::JUMP_TABLE_DEBUG_INFO, DL, MVT::Glue, Chain, 1869 getTargetConstant(static_cast<uint64_t>(JTI), DL, PTy, true)); 1870 } 1871 1872 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1873 MaybeAlign Alignment, int Offset, 1874 bool isTarget, unsigned TargetFlags) { 1875 assert((TargetFlags == 0 || isTarget) && 1876 "Cannot set target flags on target-independent globals"); 1877 if (!Alignment) 1878 Alignment = shouldOptForSize() 1879 ? getDataLayout().getABITypeAlign(C->getType()) 1880 : getDataLayout().getPrefTypeAlign(C->getType()); 1881 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1882 FoldingSetNodeID ID; 1883 AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt); 1884 ID.AddInteger(Alignment->value()); 1885 ID.AddInteger(Offset); 1886 ID.AddPointer(C); 1887 ID.AddInteger(TargetFlags); 1888 void *IP = nullptr; 1889 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1890 return SDValue(E, 0); 1891 1892 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1893 TargetFlags); 1894 CSEMap.InsertNode(N, IP); 1895 InsertNode(N); 1896 SDValue V = SDValue(N, 0); 1897 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1898 return V; 1899 } 1900 1901 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1902 MaybeAlign Alignment, int Offset, 1903 bool isTarget, unsigned TargetFlags) { 1904 assert((TargetFlags == 0 || isTarget) && 1905 "Cannot set target flags on target-independent globals"); 1906 if (!Alignment) 1907 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1908 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1909 FoldingSetNodeID ID; 1910 AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt); 1911 ID.AddInteger(Alignment->value()); 1912 ID.AddInteger(Offset); 1913 C->addSelectionDAGCSEId(ID); 1914 ID.AddInteger(TargetFlags); 1915 void *IP = nullptr; 1916 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1917 return SDValue(E, 0); 1918 1919 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1920 TargetFlags); 1921 CSEMap.InsertNode(N, IP); 1922 InsertNode(N); 1923 return SDValue(N, 0); 1924 } 1925 1926 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1927 FoldingSetNodeID ID; 1928 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), std::nullopt); 1929 ID.AddPointer(MBB); 1930 void *IP = nullptr; 1931 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1932 return SDValue(E, 0); 1933 1934 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1935 CSEMap.InsertNode(N, IP); 1936 InsertNode(N); 1937 return SDValue(N, 0); 1938 } 1939 1940 SDValue SelectionDAG::getValueType(EVT VT) { 1941 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1942 ValueTypeNodes.size()) 1943 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1944 1945 SDNode *&N = VT.isExtended() ? 1946 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1947 1948 if (N) return SDValue(N, 0); 1949 N = newSDNode<VTSDNode>(VT); 1950 InsertNode(N); 1951 return SDValue(N, 0); 1952 } 1953 1954 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1955 SDNode *&N = ExternalSymbols[Sym]; 1956 if (N) return SDValue(N, 0); 1957 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1958 InsertNode(N); 1959 return SDValue(N, 0); 1960 } 1961 1962 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1963 SDNode *&N = MCSymbols[Sym]; 1964 if (N) 1965 return SDValue(N, 0); 1966 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1967 InsertNode(N); 1968 return SDValue(N, 0); 1969 } 1970 1971 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1972 unsigned TargetFlags) { 1973 SDNode *&N = 1974 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1975 if (N) return SDValue(N, 0); 1976 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1977 InsertNode(N); 1978 return SDValue(N, 0); 1979 } 1980 1981 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1982 if ((unsigned)Cond >= CondCodeNodes.size()) 1983 CondCodeNodes.resize(Cond+1); 1984 1985 if (!CondCodeNodes[Cond]) { 1986 auto *N = newSDNode<CondCodeSDNode>(Cond); 1987 CondCodeNodes[Cond] = N; 1988 InsertNode(N); 1989 } 1990 1991 return SDValue(CondCodeNodes[Cond], 0); 1992 } 1993 1994 SDValue SelectionDAG::getVScale(const SDLoc &DL, EVT VT, APInt MulImm, 1995 bool ConstantFold) { 1996 assert(MulImm.getBitWidth() == VT.getSizeInBits() && 1997 "APInt size does not match type size!"); 1998 1999 if (MulImm == 0) 2000 return getConstant(0, DL, VT); 2001 2002 if (ConstantFold) { 2003 const MachineFunction &MF = getMachineFunction(); 2004 const Function &F = MF.getFunction(); 2005 ConstantRange CR = getVScaleRange(&F, 64); 2006 if (const APInt *C = CR.getSingleElement()) 2007 return getConstant(MulImm * C->getZExtValue(), DL, VT); 2008 } 2009 2010 return getNode(ISD::VSCALE, DL, VT, getConstant(MulImm, DL, VT)); 2011 } 2012 2013 SDValue SelectionDAG::getElementCount(const SDLoc &DL, EVT VT, ElementCount EC, 2014 bool ConstantFold) { 2015 if (EC.isScalable()) 2016 return getVScale(DL, VT, 2017 APInt(VT.getSizeInBits(), EC.getKnownMinValue())); 2018 2019 return getConstant(EC.getKnownMinValue(), DL, VT); 2020 } 2021 2022 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) { 2023 APInt One(ResVT.getScalarSizeInBits(), 1); 2024 return getStepVector(DL, ResVT, One); 2025 } 2026 2027 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) { 2028 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth()); 2029 if (ResVT.isScalableVector()) 2030 return getNode( 2031 ISD::STEP_VECTOR, DL, ResVT, 2032 getTargetConstant(StepVal, DL, ResVT.getVectorElementType())); 2033 2034 SmallVector<SDValue, 16> OpsStepConstants; 2035 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++) 2036 OpsStepConstants.push_back( 2037 getConstant(StepVal * i, DL, ResVT.getVectorElementType())); 2038 return getBuildVector(ResVT, DL, OpsStepConstants); 2039 } 2040 2041 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 2042 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 2043 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 2044 std::swap(N1, N2); 2045 ShuffleVectorSDNode::commuteMask(M); 2046 } 2047 2048 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 2049 SDValue N2, ArrayRef<int> Mask) { 2050 assert(VT.getVectorNumElements() == Mask.size() && 2051 "Must have the same number of vector elements as mask elements!"); 2052 assert(VT == N1.getValueType() && VT == N2.getValueType() && 2053 "Invalid VECTOR_SHUFFLE"); 2054 2055 // Canonicalize shuffle undef, undef -> undef 2056 if (N1.isUndef() && N2.isUndef()) 2057 return getUNDEF(VT); 2058 2059 // Validate that all indices in Mask are within the range of the elements 2060 // input to the shuffle. 2061 int NElts = Mask.size(); 2062 assert(llvm::all_of(Mask, 2063 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 2064 "Index out of range"); 2065 2066 // Copy the mask so we can do any needed cleanup. 2067 SmallVector<int, 8> MaskVec(Mask); 2068 2069 // Canonicalize shuffle v, v -> v, undef 2070 if (N1 == N2) { 2071 N2 = getUNDEF(VT); 2072 for (int i = 0; i != NElts; ++i) 2073 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 2074 } 2075 2076 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 2077 if (N1.isUndef()) 2078 commuteShuffle(N1, N2, MaskVec); 2079 2080 if (TLI->hasVectorBlend()) { 2081 // If shuffling a splat, try to blend the splat instead. We do this here so 2082 // that even when this arises during lowering we don't have to re-handle it. 2083 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 2084 BitVector UndefElements; 2085 SDValue Splat = BV->getSplatValue(&UndefElements); 2086 if (!Splat) 2087 return; 2088 2089 for (int i = 0; i < NElts; ++i) { 2090 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 2091 continue; 2092 2093 // If this input comes from undef, mark it as such. 2094 if (UndefElements[MaskVec[i] - Offset]) { 2095 MaskVec[i] = -1; 2096 continue; 2097 } 2098 2099 // If we can blend a non-undef lane, use that instead. 2100 if (!UndefElements[i]) 2101 MaskVec[i] = i + Offset; 2102 } 2103 }; 2104 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 2105 BlendSplat(N1BV, 0); 2106 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 2107 BlendSplat(N2BV, NElts); 2108 } 2109 2110 // Canonicalize all index into lhs, -> shuffle lhs, undef 2111 // Canonicalize all index into rhs, -> shuffle rhs, undef 2112 bool AllLHS = true, AllRHS = true; 2113 bool N2Undef = N2.isUndef(); 2114 for (int i = 0; i != NElts; ++i) { 2115 if (MaskVec[i] >= NElts) { 2116 if (N2Undef) 2117 MaskVec[i] = -1; 2118 else 2119 AllLHS = false; 2120 } else if (MaskVec[i] >= 0) { 2121 AllRHS = false; 2122 } 2123 } 2124 if (AllLHS && AllRHS) 2125 return getUNDEF(VT); 2126 if (AllLHS && !N2Undef) 2127 N2 = getUNDEF(VT); 2128 if (AllRHS) { 2129 N1 = getUNDEF(VT); 2130 commuteShuffle(N1, N2, MaskVec); 2131 } 2132 // Reset our undef status after accounting for the mask. 2133 N2Undef = N2.isUndef(); 2134 // Re-check whether both sides ended up undef. 2135 if (N1.isUndef() && N2Undef) 2136 return getUNDEF(VT); 2137 2138 // If Identity shuffle return that node. 2139 bool Identity = true, AllSame = true; 2140 for (int i = 0; i != NElts; ++i) { 2141 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 2142 if (MaskVec[i] != MaskVec[0]) AllSame = false; 2143 } 2144 if (Identity && NElts) 2145 return N1; 2146 2147 // Shuffling a constant splat doesn't change the result. 2148 if (N2Undef) { 2149 SDValue V = N1; 2150 2151 // Look through any bitcasts. We check that these don't change the number 2152 // (and size) of elements and just changes their types. 2153 while (V.getOpcode() == ISD::BITCAST) 2154 V = V->getOperand(0); 2155 2156 // A splat should always show up as a build vector node. 2157 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 2158 BitVector UndefElements; 2159 SDValue Splat = BV->getSplatValue(&UndefElements); 2160 // If this is a splat of an undef, shuffling it is also undef. 2161 if (Splat && Splat.isUndef()) 2162 return getUNDEF(VT); 2163 2164 bool SameNumElts = 2165 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 2166 2167 // We only have a splat which can skip shuffles if there is a splatted 2168 // value and no undef lanes rearranged by the shuffle. 2169 if (Splat && UndefElements.none()) { 2170 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 2171 // number of elements match or the value splatted is a zero constant. 2172 if (SameNumElts || isNullConstant(Splat)) 2173 return N1; 2174 } 2175 2176 // If the shuffle itself creates a splat, build the vector directly. 2177 if (AllSame && SameNumElts) { 2178 EVT BuildVT = BV->getValueType(0); 2179 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 2180 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 2181 2182 // We may have jumped through bitcasts, so the type of the 2183 // BUILD_VECTOR may not match the type of the shuffle. 2184 if (BuildVT != VT) 2185 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 2186 return NewBV; 2187 } 2188 } 2189 } 2190 2191 FoldingSetNodeID ID; 2192 SDValue Ops[2] = { N1, N2 }; 2193 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 2194 for (int i = 0; i != NElts; ++i) 2195 ID.AddInteger(MaskVec[i]); 2196 2197 void* IP = nullptr; 2198 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2199 return SDValue(E, 0); 2200 2201 // Allocate the mask array for the node out of the BumpPtrAllocator, since 2202 // SDNode doesn't have access to it. This memory will be "leaked" when 2203 // the node is deallocated, but recovered when the NodeAllocator is released. 2204 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 2205 llvm::copy(MaskVec, MaskAlloc); 2206 2207 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 2208 dl.getDebugLoc(), MaskAlloc); 2209 createOperands(N, Ops); 2210 2211 CSEMap.InsertNode(N, IP); 2212 InsertNode(N); 2213 SDValue V = SDValue(N, 0); 2214 NewSDValueDbgMsg(V, "Creating new node: ", this); 2215 return V; 2216 } 2217 2218 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 2219 EVT VT = SV.getValueType(0); 2220 SmallVector<int, 8> MaskVec(SV.getMask()); 2221 ShuffleVectorSDNode::commuteMask(MaskVec); 2222 2223 SDValue Op0 = SV.getOperand(0); 2224 SDValue Op1 = SV.getOperand(1); 2225 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 2226 } 2227 2228 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 2229 FoldingSetNodeID ID; 2230 AddNodeIDNode(ID, ISD::Register, getVTList(VT), std::nullopt); 2231 ID.AddInteger(RegNo); 2232 void *IP = nullptr; 2233 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2234 return SDValue(E, 0); 2235 2236 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 2237 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, UA); 2238 CSEMap.InsertNode(N, IP); 2239 InsertNode(N); 2240 return SDValue(N, 0); 2241 } 2242 2243 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 2244 FoldingSetNodeID ID; 2245 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), std::nullopt); 2246 ID.AddPointer(RegMask); 2247 void *IP = nullptr; 2248 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2249 return SDValue(E, 0); 2250 2251 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 2252 CSEMap.InsertNode(N, IP); 2253 InsertNode(N); 2254 return SDValue(N, 0); 2255 } 2256 2257 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 2258 MCSymbol *Label) { 2259 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 2260 } 2261 2262 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 2263 SDValue Root, MCSymbol *Label) { 2264 FoldingSetNodeID ID; 2265 SDValue Ops[] = { Root }; 2266 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 2267 ID.AddPointer(Label); 2268 void *IP = nullptr; 2269 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2270 return SDValue(E, 0); 2271 2272 auto *N = 2273 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 2274 createOperands(N, Ops); 2275 2276 CSEMap.InsertNode(N, IP); 2277 InsertNode(N); 2278 return SDValue(N, 0); 2279 } 2280 2281 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 2282 int64_t Offset, bool isTarget, 2283 unsigned TargetFlags) { 2284 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 2285 2286 FoldingSetNodeID ID; 2287 AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt); 2288 ID.AddPointer(BA); 2289 ID.AddInteger(Offset); 2290 ID.AddInteger(TargetFlags); 2291 void *IP = nullptr; 2292 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2293 return SDValue(E, 0); 2294 2295 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 2296 CSEMap.InsertNode(N, IP); 2297 InsertNode(N); 2298 return SDValue(N, 0); 2299 } 2300 2301 SDValue SelectionDAG::getSrcValue(const Value *V) { 2302 FoldingSetNodeID ID; 2303 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), std::nullopt); 2304 ID.AddPointer(V); 2305 2306 void *IP = nullptr; 2307 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2308 return SDValue(E, 0); 2309 2310 auto *N = newSDNode<SrcValueSDNode>(V); 2311 CSEMap.InsertNode(N, IP); 2312 InsertNode(N); 2313 return SDValue(N, 0); 2314 } 2315 2316 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 2317 FoldingSetNodeID ID; 2318 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), std::nullopt); 2319 ID.AddPointer(MD); 2320 2321 void *IP = nullptr; 2322 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2323 return SDValue(E, 0); 2324 2325 auto *N = newSDNode<MDNodeSDNode>(MD); 2326 CSEMap.InsertNode(N, IP); 2327 InsertNode(N); 2328 return SDValue(N, 0); 2329 } 2330 2331 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2332 if (VT == V.getValueType()) 2333 return V; 2334 2335 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2336 } 2337 2338 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2339 unsigned SrcAS, unsigned DestAS) { 2340 SDValue Ops[] = {Ptr}; 2341 FoldingSetNodeID ID; 2342 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2343 ID.AddInteger(SrcAS); 2344 ID.AddInteger(DestAS); 2345 2346 void *IP = nullptr; 2347 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2348 return SDValue(E, 0); 2349 2350 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2351 VT, SrcAS, DestAS); 2352 createOperands(N, Ops); 2353 2354 CSEMap.InsertNode(N, IP); 2355 InsertNode(N); 2356 return SDValue(N, 0); 2357 } 2358 2359 SDValue SelectionDAG::getFreeze(SDValue V) { 2360 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2361 } 2362 2363 /// getShiftAmountOperand - Return the specified value casted to 2364 /// the target's desired shift amount type. 2365 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2366 EVT OpTy = Op.getValueType(); 2367 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2368 if (OpTy == ShTy || OpTy.isVector()) return Op; 2369 2370 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2371 } 2372 2373 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2374 SDLoc dl(Node); 2375 const TargetLowering &TLI = getTargetLoweringInfo(); 2376 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2377 EVT VT = Node->getValueType(0); 2378 SDValue Tmp1 = Node->getOperand(0); 2379 SDValue Tmp2 = Node->getOperand(1); 2380 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2381 2382 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2383 Tmp2, MachinePointerInfo(V)); 2384 SDValue VAList = VAListLoad; 2385 2386 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2387 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2388 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2389 2390 VAList = 2391 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2392 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2393 } 2394 2395 // Increment the pointer, VAList, to the next vaarg 2396 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2397 getConstant(getDataLayout().getTypeAllocSize( 2398 VT.getTypeForEVT(*getContext())), 2399 dl, VAList.getValueType())); 2400 // Store the incremented VAList to the legalized pointer 2401 Tmp1 = 2402 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2403 // Load the actual argument out of the pointer VAList 2404 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2405 } 2406 2407 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2408 SDLoc dl(Node); 2409 const TargetLowering &TLI = getTargetLoweringInfo(); 2410 // This defaults to loading a pointer from the input and storing it to the 2411 // output, returning the chain. 2412 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2413 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2414 SDValue Tmp1 = 2415 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2416 Node->getOperand(2), MachinePointerInfo(VS)); 2417 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2418 MachinePointerInfo(VD)); 2419 } 2420 2421 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2422 const DataLayout &DL = getDataLayout(); 2423 Type *Ty = VT.getTypeForEVT(*getContext()); 2424 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2425 2426 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2427 return RedAlign; 2428 2429 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2430 const Align StackAlign = TFI->getStackAlign(); 2431 2432 // See if we can choose a smaller ABI alignment in cases where it's an 2433 // illegal vector type that will get broken down. 2434 if (RedAlign > StackAlign) { 2435 EVT IntermediateVT; 2436 MVT RegisterVT; 2437 unsigned NumIntermediates; 2438 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2439 NumIntermediates, RegisterVT); 2440 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2441 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2442 if (RedAlign2 < RedAlign) 2443 RedAlign = RedAlign2; 2444 } 2445 2446 return RedAlign; 2447 } 2448 2449 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2450 MachineFrameInfo &MFI = MF->getFrameInfo(); 2451 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2452 int StackID = 0; 2453 if (Bytes.isScalable()) 2454 StackID = TFI->getStackIDForScalableVectors(); 2455 // The stack id gives an indication of whether the object is scalable or 2456 // not, so it's safe to pass in the minimum size here. 2457 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinValue(), Alignment, 2458 false, nullptr, StackID); 2459 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2460 } 2461 2462 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2463 Type *Ty = VT.getTypeForEVT(*getContext()); 2464 Align StackAlign = 2465 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2466 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2467 } 2468 2469 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2470 TypeSize VT1Size = VT1.getStoreSize(); 2471 TypeSize VT2Size = VT2.getStoreSize(); 2472 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2473 "Don't know how to choose the maximum size when creating a stack " 2474 "temporary"); 2475 TypeSize Bytes = VT1Size.getKnownMinValue() > VT2Size.getKnownMinValue() 2476 ? VT1Size 2477 : VT2Size; 2478 2479 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2480 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2481 const DataLayout &DL = getDataLayout(); 2482 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2483 return CreateStackTemporary(Bytes, Align); 2484 } 2485 2486 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2487 ISD::CondCode Cond, const SDLoc &dl) { 2488 EVT OpVT = N1.getValueType(); 2489 2490 auto GetUndefBooleanConstant = [&]() { 2491 if (VT.getScalarType() == MVT::i1 || 2492 TLI->getBooleanContents(OpVT) == 2493 TargetLowering::UndefinedBooleanContent) 2494 return getUNDEF(VT); 2495 // ZeroOrOne / ZeroOrNegative require specific values for the high bits, 2496 // so we cannot use getUNDEF(). Return zero instead. 2497 return getConstant(0, dl, VT); 2498 }; 2499 2500 // These setcc operations always fold. 2501 switch (Cond) { 2502 default: break; 2503 case ISD::SETFALSE: 2504 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2505 case ISD::SETTRUE: 2506 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2507 2508 case ISD::SETOEQ: 2509 case ISD::SETOGT: 2510 case ISD::SETOGE: 2511 case ISD::SETOLT: 2512 case ISD::SETOLE: 2513 case ISD::SETONE: 2514 case ISD::SETO: 2515 case ISD::SETUO: 2516 case ISD::SETUEQ: 2517 case ISD::SETUNE: 2518 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2519 break; 2520 } 2521 2522 if (OpVT.isInteger()) { 2523 // For EQ and NE, we can always pick a value for the undef to make the 2524 // predicate pass or fail, so we can return undef. 2525 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2526 // icmp eq/ne X, undef -> undef. 2527 if ((N1.isUndef() || N2.isUndef()) && 2528 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2529 return GetUndefBooleanConstant(); 2530 2531 // If both operands are undef, we can return undef for int comparison. 2532 // icmp undef, undef -> undef. 2533 if (N1.isUndef() && N2.isUndef()) 2534 return GetUndefBooleanConstant(); 2535 2536 // icmp X, X -> true/false 2537 // icmp X, undef -> true/false because undef could be X. 2538 if (N1.isUndef() || N2.isUndef() || N1 == N2) 2539 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2540 } 2541 2542 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2543 const APInt &C2 = N2C->getAPIntValue(); 2544 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2545 const APInt &C1 = N1C->getAPIntValue(); 2546 2547 return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)), 2548 dl, VT, OpVT); 2549 } 2550 } 2551 2552 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2553 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2554 2555 if (N1CFP && N2CFP) { 2556 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2557 switch (Cond) { 2558 default: break; 2559 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2560 return GetUndefBooleanConstant(); 2561 [[fallthrough]]; 2562 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2563 OpVT); 2564 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2565 return GetUndefBooleanConstant(); 2566 [[fallthrough]]; 2567 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2568 R==APFloat::cmpLessThan, dl, VT, 2569 OpVT); 2570 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2571 return GetUndefBooleanConstant(); 2572 [[fallthrough]]; 2573 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2574 OpVT); 2575 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2576 return GetUndefBooleanConstant(); 2577 [[fallthrough]]; 2578 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2579 VT, OpVT); 2580 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2581 return GetUndefBooleanConstant(); 2582 [[fallthrough]]; 2583 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2584 R==APFloat::cmpEqual, dl, VT, 2585 OpVT); 2586 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2587 return GetUndefBooleanConstant(); 2588 [[fallthrough]]; 2589 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2590 R==APFloat::cmpEqual, dl, VT, OpVT); 2591 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2592 OpVT); 2593 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2594 OpVT); 2595 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2596 R==APFloat::cmpEqual, dl, VT, 2597 OpVT); 2598 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2599 OpVT); 2600 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2601 R==APFloat::cmpLessThan, dl, VT, 2602 OpVT); 2603 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2604 R==APFloat::cmpUnordered, dl, VT, 2605 OpVT); 2606 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2607 VT, OpVT); 2608 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2609 OpVT); 2610 } 2611 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2612 // Ensure that the constant occurs on the RHS. 2613 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2614 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2615 return SDValue(); 2616 return getSetCC(dl, VT, N2, N1, SwappedCond); 2617 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2618 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2619 // If an operand is known to be a nan (or undef that could be a nan), we can 2620 // fold it. 2621 // Choosing NaN for the undef will always make unordered comparison succeed 2622 // and ordered comparison fails. 2623 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2624 switch (ISD::getUnorderedFlavor(Cond)) { 2625 default: 2626 llvm_unreachable("Unknown flavor!"); 2627 case 0: // Known false. 2628 return getBoolConstant(false, dl, VT, OpVT); 2629 case 1: // Known true. 2630 return getBoolConstant(true, dl, VT, OpVT); 2631 case 2: // Undefined. 2632 return GetUndefBooleanConstant(); 2633 } 2634 } 2635 2636 // Could not fold it. 2637 return SDValue(); 2638 } 2639 2640 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2641 /// use this predicate to simplify operations downstream. 2642 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2643 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2644 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2645 } 2646 2647 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2648 /// this predicate to simplify operations downstream. Mask is known to be zero 2649 /// for bits that V cannot have. 2650 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2651 unsigned Depth) const { 2652 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2653 } 2654 2655 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2656 /// DemandedElts. We use this predicate to simplify operations downstream. 2657 /// Mask is known to be zero for bits that V cannot have. 2658 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2659 const APInt &DemandedElts, 2660 unsigned Depth) const { 2661 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2662 } 2663 2664 /// MaskedVectorIsZero - Return true if 'Op' is known to be zero in 2665 /// DemandedElts. We use this predicate to simplify operations downstream. 2666 bool SelectionDAG::MaskedVectorIsZero(SDValue V, const APInt &DemandedElts, 2667 unsigned Depth /* = 0 */) const { 2668 return computeKnownBits(V, DemandedElts, Depth).isZero(); 2669 } 2670 2671 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2672 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2673 unsigned Depth) const { 2674 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2675 } 2676 2677 APInt SelectionDAG::computeVectorKnownZeroElements(SDValue Op, 2678 const APInt &DemandedElts, 2679 unsigned Depth) const { 2680 EVT VT = Op.getValueType(); 2681 assert(VT.isVector() && !VT.isScalableVector() && "Only for fixed vectors!"); 2682 2683 unsigned NumElts = VT.getVectorNumElements(); 2684 assert(DemandedElts.getBitWidth() == NumElts && "Unexpected demanded mask."); 2685 2686 APInt KnownZeroElements = APInt::getZero(NumElts); 2687 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) { 2688 if (!DemandedElts[EltIdx]) 2689 continue; // Don't query elements that are not demanded. 2690 APInt Mask = APInt::getOneBitSet(NumElts, EltIdx); 2691 if (MaskedVectorIsZero(Op, Mask, Depth)) 2692 KnownZeroElements.setBit(EltIdx); 2693 } 2694 return KnownZeroElements; 2695 } 2696 2697 /// isSplatValue - Return true if the vector V has the same value 2698 /// across all DemandedElts. For scalable vectors, we don't know the 2699 /// number of lanes at compile time. Instead, we use a 1 bit APInt 2700 /// to represent a conservative value for all lanes; that is, that 2701 /// one bit value is implicitly splatted across all lanes. 2702 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2703 APInt &UndefElts, unsigned Depth) const { 2704 unsigned Opcode = V.getOpcode(); 2705 EVT VT = V.getValueType(); 2706 assert(VT.isVector() && "Vector type expected"); 2707 assert((!VT.isScalableVector() || DemandedElts.getBitWidth() == 1) && 2708 "scalable demanded bits are ignored"); 2709 2710 if (!DemandedElts) 2711 return false; // No demanded elts, better to assume we don't know anything. 2712 2713 if (Depth >= MaxRecursionDepth) 2714 return false; // Limit search depth. 2715 2716 // Deal with some common cases here that work for both fixed and scalable 2717 // vector types. 2718 switch (Opcode) { 2719 case ISD::SPLAT_VECTOR: 2720 UndefElts = V.getOperand(0).isUndef() 2721 ? APInt::getAllOnes(DemandedElts.getBitWidth()) 2722 : APInt(DemandedElts.getBitWidth(), 0); 2723 return true; 2724 case ISD::ADD: 2725 case ISD::SUB: 2726 case ISD::AND: 2727 case ISD::XOR: 2728 case ISD::OR: { 2729 APInt UndefLHS, UndefRHS; 2730 SDValue LHS = V.getOperand(0); 2731 SDValue RHS = V.getOperand(1); 2732 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2733 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2734 UndefElts = UndefLHS | UndefRHS; 2735 return true; 2736 } 2737 return false; 2738 } 2739 case ISD::ABS: 2740 case ISD::TRUNCATE: 2741 case ISD::SIGN_EXTEND: 2742 case ISD::ZERO_EXTEND: 2743 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2744 default: 2745 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 2746 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 2747 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, *this, 2748 Depth); 2749 break; 2750 } 2751 2752 // We don't support other cases than those above for scalable vectors at 2753 // the moment. 2754 if (VT.isScalableVector()) 2755 return false; 2756 2757 unsigned NumElts = VT.getVectorNumElements(); 2758 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2759 UndefElts = APInt::getZero(NumElts); 2760 2761 switch (Opcode) { 2762 case ISD::BUILD_VECTOR: { 2763 SDValue Scl; 2764 for (unsigned i = 0; i != NumElts; ++i) { 2765 SDValue Op = V.getOperand(i); 2766 if (Op.isUndef()) { 2767 UndefElts.setBit(i); 2768 continue; 2769 } 2770 if (!DemandedElts[i]) 2771 continue; 2772 if (Scl && Scl != Op) 2773 return false; 2774 Scl = Op; 2775 } 2776 return true; 2777 } 2778 case ISD::VECTOR_SHUFFLE: { 2779 // Check if this is a shuffle node doing a splat or a shuffle of a splat. 2780 APInt DemandedLHS = APInt::getZero(NumElts); 2781 APInt DemandedRHS = APInt::getZero(NumElts); 2782 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2783 for (int i = 0; i != (int)NumElts; ++i) { 2784 int M = Mask[i]; 2785 if (M < 0) { 2786 UndefElts.setBit(i); 2787 continue; 2788 } 2789 if (!DemandedElts[i]) 2790 continue; 2791 if (M < (int)NumElts) 2792 DemandedLHS.setBit(M); 2793 else 2794 DemandedRHS.setBit(M - NumElts); 2795 } 2796 2797 // If we aren't demanding either op, assume there's no splat. 2798 // If we are demanding both ops, assume there's no splat. 2799 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) || 2800 (!DemandedLHS.isZero() && !DemandedRHS.isZero())) 2801 return false; 2802 2803 // See if the demanded elts of the source op is a splat or we only demand 2804 // one element, which should always be a splat. 2805 // TODO: Handle source ops splats with undefs. 2806 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) { 2807 APInt SrcUndefs; 2808 return (SrcElts.popcount() == 1) || 2809 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) && 2810 (SrcElts & SrcUndefs).isZero()); 2811 }; 2812 if (!DemandedLHS.isZero()) 2813 return CheckSplatSrc(V.getOperand(0), DemandedLHS); 2814 return CheckSplatSrc(V.getOperand(1), DemandedRHS); 2815 } 2816 case ISD::EXTRACT_SUBVECTOR: { 2817 // Offset the demanded elts by the subvector index. 2818 SDValue Src = V.getOperand(0); 2819 // We don't support scalable vectors at the moment. 2820 if (Src.getValueType().isScalableVector()) 2821 return false; 2822 uint64_t Idx = V.getConstantOperandVal(1); 2823 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2824 APInt UndefSrcElts; 2825 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 2826 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2827 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2828 return true; 2829 } 2830 break; 2831 } 2832 case ISD::ANY_EXTEND_VECTOR_INREG: 2833 case ISD::SIGN_EXTEND_VECTOR_INREG: 2834 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2835 // Widen the demanded elts by the src element count. 2836 SDValue Src = V.getOperand(0); 2837 // We don't support scalable vectors at the moment. 2838 if (Src.getValueType().isScalableVector()) 2839 return false; 2840 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2841 APInt UndefSrcElts; 2842 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts); 2843 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2844 UndefElts = UndefSrcElts.trunc(NumElts); 2845 return true; 2846 } 2847 break; 2848 } 2849 case ISD::BITCAST: { 2850 SDValue Src = V.getOperand(0); 2851 EVT SrcVT = Src.getValueType(); 2852 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits(); 2853 unsigned BitWidth = VT.getScalarSizeInBits(); 2854 2855 // Ignore bitcasts from unsupported types. 2856 // TODO: Add fp support? 2857 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger()) 2858 break; 2859 2860 // Bitcast 'small element' vector to 'large element' vector. 2861 if ((BitWidth % SrcBitWidth) == 0) { 2862 // See if each sub element is a splat. 2863 unsigned Scale = BitWidth / SrcBitWidth; 2864 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2865 APInt ScaledDemandedElts = 2866 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2867 for (unsigned I = 0; I != Scale; ++I) { 2868 APInt SubUndefElts; 2869 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I); 2870 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt); 2871 SubDemandedElts &= ScaledDemandedElts; 2872 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1)) 2873 return false; 2874 // TODO: Add support for merging sub undef elements. 2875 if (!SubUndefElts.isZero()) 2876 return false; 2877 } 2878 return true; 2879 } 2880 break; 2881 } 2882 } 2883 2884 // Fallback - this is a splat if all demanded elts are the same constant. 2885 if (computeKnownBits(V, DemandedElts, Depth).isConstant()) { 2886 UndefElts = ~DemandedElts; 2887 return true; 2888 } 2889 2890 return false; 2891 } 2892 2893 /// Helper wrapper to main isSplatValue function. 2894 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const { 2895 EVT VT = V.getValueType(); 2896 assert(VT.isVector() && "Vector type expected"); 2897 2898 APInt UndefElts; 2899 // Since the number of lanes in a scalable vector is unknown at compile time, 2900 // we track one bit which is implicitly broadcast to all lanes. This means 2901 // that all lanes in a scalable vector are considered demanded. 2902 APInt DemandedElts 2903 = APInt::getAllOnes(VT.isScalableVector() ? 1 : VT.getVectorNumElements()); 2904 return isSplatValue(V, DemandedElts, UndefElts) && 2905 (AllowUndefs || !UndefElts); 2906 } 2907 2908 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2909 V = peekThroughExtractSubvectors(V); 2910 2911 EVT VT = V.getValueType(); 2912 unsigned Opcode = V.getOpcode(); 2913 switch (Opcode) { 2914 default: { 2915 APInt UndefElts; 2916 // Since the number of lanes in a scalable vector is unknown at compile time, 2917 // we track one bit which is implicitly broadcast to all lanes. This means 2918 // that all lanes in a scalable vector are considered demanded. 2919 APInt DemandedElts 2920 = APInt::getAllOnes(VT.isScalableVector() ? 1 : VT.getVectorNumElements()); 2921 2922 if (isSplatValue(V, DemandedElts, UndefElts)) { 2923 if (VT.isScalableVector()) { 2924 // DemandedElts and UndefElts are ignored for scalable vectors, since 2925 // the only supported cases are SPLAT_VECTOR nodes. 2926 SplatIdx = 0; 2927 } else { 2928 // Handle case where all demanded elements are UNDEF. 2929 if (DemandedElts.isSubsetOf(UndefElts)) { 2930 SplatIdx = 0; 2931 return getUNDEF(VT); 2932 } 2933 SplatIdx = (UndefElts & DemandedElts).countr_one(); 2934 } 2935 return V; 2936 } 2937 break; 2938 } 2939 case ISD::SPLAT_VECTOR: 2940 SplatIdx = 0; 2941 return V; 2942 case ISD::VECTOR_SHUFFLE: { 2943 assert(!VT.isScalableVector()); 2944 // Check if this is a shuffle node doing a splat. 2945 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2946 // getTargetVShiftNode currently struggles without the splat source. 2947 auto *SVN = cast<ShuffleVectorSDNode>(V); 2948 if (!SVN->isSplat()) 2949 break; 2950 int Idx = SVN->getSplatIndex(); 2951 int NumElts = V.getValueType().getVectorNumElements(); 2952 SplatIdx = Idx % NumElts; 2953 return V.getOperand(Idx / NumElts); 2954 } 2955 } 2956 2957 return SDValue(); 2958 } 2959 2960 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) { 2961 int SplatIdx; 2962 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) { 2963 EVT SVT = SrcVector.getValueType().getScalarType(); 2964 EVT LegalSVT = SVT; 2965 if (LegalTypes && !TLI->isTypeLegal(SVT)) { 2966 if (!SVT.isInteger()) 2967 return SDValue(); 2968 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 2969 if (LegalSVT.bitsLT(SVT)) 2970 return SDValue(); 2971 } 2972 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector, 2973 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2974 } 2975 return SDValue(); 2976 } 2977 2978 const APInt * 2979 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2980 const APInt &DemandedElts) const { 2981 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2982 V.getOpcode() == ISD::SRA) && 2983 "Unknown shift node"); 2984 unsigned BitWidth = V.getScalarValueSizeInBits(); 2985 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2986 // Shifting more than the bitwidth is not valid. 2987 const APInt &ShAmt = SA->getAPIntValue(); 2988 if (ShAmt.ult(BitWidth)) 2989 return &ShAmt; 2990 } 2991 return nullptr; 2992 } 2993 2994 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2995 SDValue V, const APInt &DemandedElts) const { 2996 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2997 V.getOpcode() == ISD::SRA) && 2998 "Unknown shift node"); 2999 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 3000 return ValidAmt; 3001 unsigned BitWidth = V.getScalarValueSizeInBits(); 3002 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 3003 if (!BV) 3004 return nullptr; 3005 const APInt *MinShAmt = nullptr; 3006 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 3007 if (!DemandedElts[i]) 3008 continue; 3009 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 3010 if (!SA) 3011 return nullptr; 3012 // Shifting more than the bitwidth is not valid. 3013 const APInt &ShAmt = SA->getAPIntValue(); 3014 if (ShAmt.uge(BitWidth)) 3015 return nullptr; 3016 if (MinShAmt && MinShAmt->ule(ShAmt)) 3017 continue; 3018 MinShAmt = &ShAmt; 3019 } 3020 return MinShAmt; 3021 } 3022 3023 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 3024 SDValue V, const APInt &DemandedElts) const { 3025 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 3026 V.getOpcode() == ISD::SRA) && 3027 "Unknown shift node"); 3028 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 3029 return ValidAmt; 3030 unsigned BitWidth = V.getScalarValueSizeInBits(); 3031 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 3032 if (!BV) 3033 return nullptr; 3034 const APInt *MaxShAmt = nullptr; 3035 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 3036 if (!DemandedElts[i]) 3037 continue; 3038 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 3039 if (!SA) 3040 return nullptr; 3041 // Shifting more than the bitwidth is not valid. 3042 const APInt &ShAmt = SA->getAPIntValue(); 3043 if (ShAmt.uge(BitWidth)) 3044 return nullptr; 3045 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 3046 continue; 3047 MaxShAmt = &ShAmt; 3048 } 3049 return MaxShAmt; 3050 } 3051 3052 /// Determine which bits of Op are known to be either zero or one and return 3053 /// them in Known. For vectors, the known bits are those that are shared by 3054 /// every vector element. 3055 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 3056 EVT VT = Op.getValueType(); 3057 3058 // Since the number of lanes in a scalable vector is unknown at compile time, 3059 // we track one bit which is implicitly broadcast to all lanes. This means 3060 // that all lanes in a scalable vector are considered demanded. 3061 APInt DemandedElts = VT.isFixedLengthVector() 3062 ? APInt::getAllOnes(VT.getVectorNumElements()) 3063 : APInt(1, 1); 3064 return computeKnownBits(Op, DemandedElts, Depth); 3065 } 3066 3067 /// Determine which bits of Op are known to be either zero or one and return 3068 /// them in Known. The DemandedElts argument allows us to only collect the known 3069 /// bits that are shared by the requested vector elements. 3070 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 3071 unsigned Depth) const { 3072 unsigned BitWidth = Op.getScalarValueSizeInBits(); 3073 3074 KnownBits Known(BitWidth); // Don't know anything. 3075 3076 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3077 // We know all of the bits for a constant! 3078 return KnownBits::makeConstant(C->getAPIntValue()); 3079 } 3080 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 3081 // We know all of the bits for a constant fp! 3082 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 3083 } 3084 3085 if (Depth >= MaxRecursionDepth) 3086 return Known; // Limit search depth. 3087 3088 KnownBits Known2; 3089 unsigned NumElts = DemandedElts.getBitWidth(); 3090 assert((!Op.getValueType().isFixedLengthVector() || 3091 NumElts == Op.getValueType().getVectorNumElements()) && 3092 "Unexpected vector size"); 3093 3094 if (!DemandedElts) 3095 return Known; // No demanded elts, better to assume we don't know anything. 3096 3097 unsigned Opcode = Op.getOpcode(); 3098 switch (Opcode) { 3099 case ISD::MERGE_VALUES: 3100 return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts, 3101 Depth + 1); 3102 case ISD::SPLAT_VECTOR: { 3103 SDValue SrcOp = Op.getOperand(0); 3104 assert(SrcOp.getValueSizeInBits() >= BitWidth && 3105 "Expected SPLAT_VECTOR implicit truncation"); 3106 // Implicitly truncate the bits to match the official semantics of 3107 // SPLAT_VECTOR. 3108 Known = computeKnownBits(SrcOp, Depth + 1).trunc(BitWidth); 3109 break; 3110 } 3111 case ISD::SPLAT_VECTOR_PARTS: { 3112 unsigned ScalarSize = Op.getOperand(0).getScalarValueSizeInBits(); 3113 assert(ScalarSize * Op.getNumOperands() == BitWidth && 3114 "Expected SPLAT_VECTOR_PARTS scalars to cover element width"); 3115 for (auto [I, SrcOp] : enumerate(Op->ops())) { 3116 Known.insertBits(computeKnownBits(SrcOp, Depth + 1), ScalarSize * I); 3117 } 3118 break; 3119 } 3120 case ISD::BUILD_VECTOR: 3121 assert(!Op.getValueType().isScalableVector()); 3122 // Collect the known bits that are shared by every demanded vector element. 3123 Known.Zero.setAllBits(); Known.One.setAllBits(); 3124 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 3125 if (!DemandedElts[i]) 3126 continue; 3127 3128 SDValue SrcOp = Op.getOperand(i); 3129 Known2 = computeKnownBits(SrcOp, Depth + 1); 3130 3131 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3132 if (SrcOp.getValueSizeInBits() != BitWidth) { 3133 assert(SrcOp.getValueSizeInBits() > BitWidth && 3134 "Expected BUILD_VECTOR implicit truncation"); 3135 Known2 = Known2.trunc(BitWidth); 3136 } 3137 3138 // Known bits are the values that are shared by every demanded element. 3139 Known = Known.intersectWith(Known2); 3140 3141 // If we don't know any bits, early out. 3142 if (Known.isUnknown()) 3143 break; 3144 } 3145 break; 3146 case ISD::VECTOR_SHUFFLE: { 3147 assert(!Op.getValueType().isScalableVector()); 3148 // Collect the known bits that are shared by every vector element referenced 3149 // by the shuffle. 3150 APInt DemandedLHS, DemandedRHS; 3151 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3152 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3153 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts, 3154 DemandedLHS, DemandedRHS)) 3155 break; 3156 3157 // Known bits are the values that are shared by every demanded element. 3158 Known.Zero.setAllBits(); Known.One.setAllBits(); 3159 if (!!DemandedLHS) { 3160 SDValue LHS = Op.getOperand(0); 3161 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 3162 Known = Known.intersectWith(Known2); 3163 } 3164 // If we don't know any bits, early out. 3165 if (Known.isUnknown()) 3166 break; 3167 if (!!DemandedRHS) { 3168 SDValue RHS = Op.getOperand(1); 3169 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 3170 Known = Known.intersectWith(Known2); 3171 } 3172 break; 3173 } 3174 case ISD::VSCALE: { 3175 const Function &F = getMachineFunction().getFunction(); 3176 const APInt &Multiplier = Op.getConstantOperandAPInt(0); 3177 Known = getVScaleRange(&F, BitWidth).multiply(Multiplier).toKnownBits(); 3178 break; 3179 } 3180 case ISD::CONCAT_VECTORS: { 3181 if (Op.getValueType().isScalableVector()) 3182 break; 3183 // Split DemandedElts and test each of the demanded subvectors. 3184 Known.Zero.setAllBits(); Known.One.setAllBits(); 3185 EVT SubVectorVT = Op.getOperand(0).getValueType(); 3186 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 3187 unsigned NumSubVectors = Op.getNumOperands(); 3188 for (unsigned i = 0; i != NumSubVectors; ++i) { 3189 APInt DemandedSub = 3190 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 3191 if (!!DemandedSub) { 3192 SDValue Sub = Op.getOperand(i); 3193 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 3194 Known = Known.intersectWith(Known2); 3195 } 3196 // If we don't know any bits, early out. 3197 if (Known.isUnknown()) 3198 break; 3199 } 3200 break; 3201 } 3202 case ISD::INSERT_SUBVECTOR: { 3203 if (Op.getValueType().isScalableVector()) 3204 break; 3205 // Demand any elements from the subvector and the remainder from the src its 3206 // inserted into. 3207 SDValue Src = Op.getOperand(0); 3208 SDValue Sub = Op.getOperand(1); 3209 uint64_t Idx = Op.getConstantOperandVal(2); 3210 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 3211 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 3212 APInt DemandedSrcElts = DemandedElts; 3213 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 3214 3215 Known.One.setAllBits(); 3216 Known.Zero.setAllBits(); 3217 if (!!DemandedSubElts) { 3218 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 3219 if (Known.isUnknown()) 3220 break; // early-out. 3221 } 3222 if (!!DemandedSrcElts) { 3223 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3224 Known = Known.intersectWith(Known2); 3225 } 3226 break; 3227 } 3228 case ISD::EXTRACT_SUBVECTOR: { 3229 // Offset the demanded elts by the subvector index. 3230 SDValue Src = Op.getOperand(0); 3231 // Bail until we can represent demanded elements for scalable vectors. 3232 if (Op.getValueType().isScalableVector() || Src.getValueType().isScalableVector()) 3233 break; 3234 uint64_t Idx = Op.getConstantOperandVal(1); 3235 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3236 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 3237 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3238 break; 3239 } 3240 case ISD::SCALAR_TO_VECTOR: { 3241 if (Op.getValueType().isScalableVector()) 3242 break; 3243 // We know about scalar_to_vector as much as we know about it source, 3244 // which becomes the first element of otherwise unknown vector. 3245 if (DemandedElts != 1) 3246 break; 3247 3248 SDValue N0 = Op.getOperand(0); 3249 Known = computeKnownBits(N0, Depth + 1); 3250 if (N0.getValueSizeInBits() != BitWidth) 3251 Known = Known.trunc(BitWidth); 3252 3253 break; 3254 } 3255 case ISD::BITCAST: { 3256 if (Op.getValueType().isScalableVector()) 3257 break; 3258 3259 SDValue N0 = Op.getOperand(0); 3260 EVT SubVT = N0.getValueType(); 3261 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 3262 3263 // Ignore bitcasts from unsupported types. 3264 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 3265 break; 3266 3267 // Fast handling of 'identity' bitcasts. 3268 if (BitWidth == SubBitWidth) { 3269 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 3270 break; 3271 } 3272 3273 bool IsLE = getDataLayout().isLittleEndian(); 3274 3275 // Bitcast 'small element' vector to 'large element' scalar/vector. 3276 if ((BitWidth % SubBitWidth) == 0) { 3277 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 3278 3279 // Collect known bits for the (larger) output by collecting the known 3280 // bits from each set of sub elements and shift these into place. 3281 // We need to separately call computeKnownBits for each set of 3282 // sub elements as the knownbits for each is likely to be different. 3283 unsigned SubScale = BitWidth / SubBitWidth; 3284 APInt SubDemandedElts(NumElts * SubScale, 0); 3285 for (unsigned i = 0; i != NumElts; ++i) 3286 if (DemandedElts[i]) 3287 SubDemandedElts.setBit(i * SubScale); 3288 3289 for (unsigned i = 0; i != SubScale; ++i) { 3290 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 3291 Depth + 1); 3292 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 3293 Known.insertBits(Known2, SubBitWidth * Shifts); 3294 } 3295 } 3296 3297 // Bitcast 'large element' scalar/vector to 'small element' vector. 3298 if ((SubBitWidth % BitWidth) == 0) { 3299 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 3300 3301 // Collect known bits for the (smaller) output by collecting the known 3302 // bits from the overlapping larger input elements and extracting the 3303 // sub sections we actually care about. 3304 unsigned SubScale = SubBitWidth / BitWidth; 3305 APInt SubDemandedElts = 3306 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale); 3307 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 3308 3309 Known.Zero.setAllBits(); Known.One.setAllBits(); 3310 for (unsigned i = 0; i != NumElts; ++i) 3311 if (DemandedElts[i]) { 3312 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 3313 unsigned Offset = (Shifts % SubScale) * BitWidth; 3314 Known = Known.intersectWith(Known2.extractBits(BitWidth, Offset)); 3315 // If we don't know any bits, early out. 3316 if (Known.isUnknown()) 3317 break; 3318 } 3319 } 3320 break; 3321 } 3322 case ISD::AND: 3323 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3324 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3325 3326 Known &= Known2; 3327 break; 3328 case ISD::OR: 3329 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3330 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3331 3332 Known |= Known2; 3333 break; 3334 case ISD::XOR: 3335 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3336 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3337 3338 Known ^= Known2; 3339 break; 3340 case ISD::MUL: { 3341 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3342 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3343 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3344 // TODO: SelfMultiply can be poison, but not undef. 3345 if (SelfMultiply) 3346 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison( 3347 Op.getOperand(0), DemandedElts, false, Depth + 1); 3348 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3349 3350 // If the multiplication is known not to overflow, the product of a number 3351 // with itself is non-negative. Only do this if we didn't already computed 3352 // the opposite value for the sign bit. 3353 if (Op->getFlags().hasNoSignedWrap() && 3354 Op.getOperand(0) == Op.getOperand(1) && 3355 !Known.isNegative()) 3356 Known.makeNonNegative(); 3357 break; 3358 } 3359 case ISD::MULHU: { 3360 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3361 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3362 Known = KnownBits::mulhu(Known, Known2); 3363 break; 3364 } 3365 case ISD::MULHS: { 3366 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3367 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3368 Known = KnownBits::mulhs(Known, Known2); 3369 break; 3370 } 3371 case ISD::UMUL_LOHI: { 3372 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3373 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3374 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3375 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3376 if (Op.getResNo() == 0) 3377 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3378 else 3379 Known = KnownBits::mulhu(Known, Known2); 3380 break; 3381 } 3382 case ISD::SMUL_LOHI: { 3383 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3384 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3385 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3386 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3387 if (Op.getResNo() == 0) 3388 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3389 else 3390 Known = KnownBits::mulhs(Known, Known2); 3391 break; 3392 } 3393 case ISD::AVGCEILU: { 3394 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3395 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3396 Known = Known.zext(BitWidth + 1); 3397 Known2 = Known2.zext(BitWidth + 1); 3398 KnownBits One = KnownBits::makeConstant(APInt(1, 1)); 3399 Known = KnownBits::computeForAddCarry(Known, Known2, One); 3400 Known = Known.extractBits(BitWidth, 1); 3401 break; 3402 } 3403 case ISD::SELECT: 3404 case ISD::VSELECT: 3405 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3406 // If we don't know any bits, early out. 3407 if (Known.isUnknown()) 3408 break; 3409 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3410 3411 // Only known if known in both the LHS and RHS. 3412 Known = Known.intersectWith(Known2); 3413 break; 3414 case ISD::SELECT_CC: 3415 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3416 // If we don't know any bits, early out. 3417 if (Known.isUnknown()) 3418 break; 3419 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3420 3421 // Only known if known in both the LHS and RHS. 3422 Known = Known.intersectWith(Known2); 3423 break; 3424 case ISD::SMULO: 3425 case ISD::UMULO: 3426 if (Op.getResNo() != 1) 3427 break; 3428 // The boolean result conforms to getBooleanContents. 3429 // If we know the result of a setcc has the top bits zero, use this info. 3430 // We know that we have an integer-based boolean since these operations 3431 // are only available for integer. 3432 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3433 TargetLowering::ZeroOrOneBooleanContent && 3434 BitWidth > 1) 3435 Known.Zero.setBitsFrom(1); 3436 break; 3437 case ISD::SETCC: 3438 case ISD::SETCCCARRY: 3439 case ISD::STRICT_FSETCC: 3440 case ISD::STRICT_FSETCCS: { 3441 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3442 // If we know the result of a setcc has the top bits zero, use this info. 3443 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3444 TargetLowering::ZeroOrOneBooleanContent && 3445 BitWidth > 1) 3446 Known.Zero.setBitsFrom(1); 3447 break; 3448 } 3449 case ISD::SHL: 3450 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3451 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3452 Known = KnownBits::shl(Known, Known2); 3453 3454 // Minimum shift low bits are known zero. 3455 if (const APInt *ShMinAmt = 3456 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3457 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3458 break; 3459 case ISD::SRL: 3460 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3461 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3462 Known = KnownBits::lshr(Known, Known2); 3463 3464 // Minimum shift high bits are known zero. 3465 if (const APInt *ShMinAmt = 3466 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3467 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3468 break; 3469 case ISD::SRA: 3470 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3471 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3472 Known = KnownBits::ashr(Known, Known2); 3473 break; 3474 case ISD::FSHL: 3475 case ISD::FSHR: 3476 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3477 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3478 3479 // For fshl, 0-shift returns the 1st arg. 3480 // For fshr, 0-shift returns the 2nd arg. 3481 if (Amt == 0) { 3482 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3483 DemandedElts, Depth + 1); 3484 break; 3485 } 3486 3487 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3488 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3489 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3490 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3491 if (Opcode == ISD::FSHL) { 3492 Known.One <<= Amt; 3493 Known.Zero <<= Amt; 3494 Known2.One.lshrInPlace(BitWidth - Amt); 3495 Known2.Zero.lshrInPlace(BitWidth - Amt); 3496 } else { 3497 Known.One <<= BitWidth - Amt; 3498 Known.Zero <<= BitWidth - Amt; 3499 Known2.One.lshrInPlace(Amt); 3500 Known2.Zero.lshrInPlace(Amt); 3501 } 3502 Known = Known.unionWith(Known2); 3503 } 3504 break; 3505 case ISD::SHL_PARTS: 3506 case ISD::SRA_PARTS: 3507 case ISD::SRL_PARTS: { 3508 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3509 3510 // Collect lo/hi source values and concatenate. 3511 unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits(); 3512 unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits(); 3513 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3514 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3515 Known = Known2.concat(Known); 3516 3517 // Collect shift amount. 3518 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3519 3520 if (Opcode == ISD::SHL_PARTS) 3521 Known = KnownBits::shl(Known, Known2); 3522 else if (Opcode == ISD::SRA_PARTS) 3523 Known = KnownBits::ashr(Known, Known2); 3524 else // if (Opcode == ISD::SRL_PARTS) 3525 Known = KnownBits::lshr(Known, Known2); 3526 3527 // TODO: Minimum shift low/high bits are known zero. 3528 3529 if (Op.getResNo() == 0) 3530 Known = Known.extractBits(LoBits, 0); 3531 else 3532 Known = Known.extractBits(HiBits, LoBits); 3533 break; 3534 } 3535 case ISD::SIGN_EXTEND_INREG: { 3536 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3537 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3538 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3539 break; 3540 } 3541 case ISD::CTTZ: 3542 case ISD::CTTZ_ZERO_UNDEF: { 3543 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3544 // If we have a known 1, its position is our upper bound. 3545 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3546 unsigned LowBits = llvm::bit_width(PossibleTZ); 3547 Known.Zero.setBitsFrom(LowBits); 3548 break; 3549 } 3550 case ISD::CTLZ: 3551 case ISD::CTLZ_ZERO_UNDEF: { 3552 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3553 // If we have a known 1, its position is our upper bound. 3554 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3555 unsigned LowBits = llvm::bit_width(PossibleLZ); 3556 Known.Zero.setBitsFrom(LowBits); 3557 break; 3558 } 3559 case ISD::CTPOP: { 3560 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3561 // If we know some of the bits are zero, they can't be one. 3562 unsigned PossibleOnes = Known2.countMaxPopulation(); 3563 Known.Zero.setBitsFrom(llvm::bit_width(PossibleOnes)); 3564 break; 3565 } 3566 case ISD::PARITY: { 3567 // Parity returns 0 everywhere but the LSB. 3568 Known.Zero.setBitsFrom(1); 3569 break; 3570 } 3571 case ISD::LOAD: { 3572 LoadSDNode *LD = cast<LoadSDNode>(Op); 3573 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3574 if (ISD::isNON_EXTLoad(LD) && Cst) { 3575 // Determine any common known bits from the loaded constant pool value. 3576 Type *CstTy = Cst->getType(); 3577 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits() && 3578 !Op.getValueType().isScalableVector()) { 3579 // If its a vector splat, then we can (quickly) reuse the scalar path. 3580 // NOTE: We assume all elements match and none are UNDEF. 3581 if (CstTy->isVectorTy()) { 3582 if (const Constant *Splat = Cst->getSplatValue()) { 3583 Cst = Splat; 3584 CstTy = Cst->getType(); 3585 } 3586 } 3587 // TODO - do we need to handle different bitwidths? 3588 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3589 // Iterate across all vector elements finding common known bits. 3590 Known.One.setAllBits(); 3591 Known.Zero.setAllBits(); 3592 for (unsigned i = 0; i != NumElts; ++i) { 3593 if (!DemandedElts[i]) 3594 continue; 3595 if (Constant *Elt = Cst->getAggregateElement(i)) { 3596 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3597 const APInt &Value = CInt->getValue(); 3598 Known.One &= Value; 3599 Known.Zero &= ~Value; 3600 continue; 3601 } 3602 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3603 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3604 Known.One &= Value; 3605 Known.Zero &= ~Value; 3606 continue; 3607 } 3608 } 3609 Known.One.clearAllBits(); 3610 Known.Zero.clearAllBits(); 3611 break; 3612 } 3613 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3614 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3615 Known = KnownBits::makeConstant(CInt->getValue()); 3616 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3617 Known = 3618 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3619 } 3620 } 3621 } 3622 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3623 // If this is a ZEXTLoad and we are looking at the loaded value. 3624 EVT VT = LD->getMemoryVT(); 3625 unsigned MemBits = VT.getScalarSizeInBits(); 3626 Known.Zero.setBitsFrom(MemBits); 3627 } else if (const MDNode *Ranges = LD->getRanges()) { 3628 EVT VT = LD->getValueType(0); 3629 3630 // TODO: Handle for extending loads 3631 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 3632 if (VT.isVector()) { 3633 // Handle truncation to the first demanded element. 3634 // TODO: Figure out which demanded elements are covered 3635 if (DemandedElts != 1 || !getDataLayout().isLittleEndian()) 3636 break; 3637 3638 // Handle the case where a load has a vector type, but scalar memory 3639 // with an attached range. 3640 EVT MemVT = LD->getMemoryVT(); 3641 KnownBits KnownFull(MemVT.getSizeInBits()); 3642 3643 computeKnownBitsFromRangeMetadata(*Ranges, KnownFull); 3644 Known = KnownFull.trunc(BitWidth); 3645 } else 3646 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3647 } 3648 } 3649 break; 3650 } 3651 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3652 if (Op.getValueType().isScalableVector()) 3653 break; 3654 EVT InVT = Op.getOperand(0).getValueType(); 3655 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3656 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3657 Known = Known.zext(BitWidth); 3658 break; 3659 } 3660 case ISD::ZERO_EXTEND: { 3661 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3662 Known = Known.zext(BitWidth); 3663 break; 3664 } 3665 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3666 if (Op.getValueType().isScalableVector()) 3667 break; 3668 EVT InVT = Op.getOperand(0).getValueType(); 3669 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3670 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3671 // If the sign bit is known to be zero or one, then sext will extend 3672 // it to the top bits, else it will just zext. 3673 Known = Known.sext(BitWidth); 3674 break; 3675 } 3676 case ISD::SIGN_EXTEND: { 3677 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3678 // If the sign bit is known to be zero or one, then sext will extend 3679 // it to the top bits, else it will just zext. 3680 Known = Known.sext(BitWidth); 3681 break; 3682 } 3683 case ISD::ANY_EXTEND_VECTOR_INREG: { 3684 if (Op.getValueType().isScalableVector()) 3685 break; 3686 EVT InVT = Op.getOperand(0).getValueType(); 3687 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3688 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3689 Known = Known.anyext(BitWidth); 3690 break; 3691 } 3692 case ISD::ANY_EXTEND: { 3693 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3694 Known = Known.anyext(BitWidth); 3695 break; 3696 } 3697 case ISD::TRUNCATE: { 3698 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3699 Known = Known.trunc(BitWidth); 3700 break; 3701 } 3702 case ISD::AssertZext: { 3703 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3704 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3705 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3706 Known.Zero |= (~InMask); 3707 Known.One &= (~Known.Zero); 3708 break; 3709 } 3710 case ISD::AssertAlign: { 3711 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3712 assert(LogOfAlign != 0); 3713 3714 // TODO: Should use maximum with source 3715 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3716 // well as clearing one bits. 3717 Known.Zero.setLowBits(LogOfAlign); 3718 Known.One.clearLowBits(LogOfAlign); 3719 break; 3720 } 3721 case ISD::FGETSIGN: 3722 // All bits are zero except the low bit. 3723 Known.Zero.setBitsFrom(1); 3724 break; 3725 case ISD::ADD: 3726 case ISD::SUB: { 3727 SDNodeFlags Flags = Op.getNode()->getFlags(); 3728 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3729 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3730 Known = KnownBits::computeForAddSub(Op.getOpcode() == ISD::ADD, 3731 Flags.hasNoSignedWrap(), Known, Known2); 3732 break; 3733 } 3734 case ISD::USUBO: 3735 case ISD::SSUBO: 3736 case ISD::USUBO_CARRY: 3737 case ISD::SSUBO_CARRY: 3738 if (Op.getResNo() == 1) { 3739 // If we know the result of a setcc has the top bits zero, use this info. 3740 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3741 TargetLowering::ZeroOrOneBooleanContent && 3742 BitWidth > 1) 3743 Known.Zero.setBitsFrom(1); 3744 break; 3745 } 3746 [[fallthrough]]; 3747 case ISD::SUBC: { 3748 assert(Op.getResNo() == 0 && 3749 "We only compute knownbits for the difference here."); 3750 3751 // With USUBO_CARRY and SSUBO_CARRY a borrow bit may be added in. 3752 KnownBits Borrow(1); 3753 if (Opcode == ISD::USUBO_CARRY || Opcode == ISD::SSUBO_CARRY) { 3754 Borrow = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3755 // Borrow has bit width 1 3756 Borrow = Borrow.trunc(1); 3757 } else { 3758 Borrow.setAllZero(); 3759 } 3760 3761 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3762 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3763 Known = KnownBits::computeForSubBorrow(Known, Known2, Borrow); 3764 break; 3765 } 3766 case ISD::UADDO: 3767 case ISD::SADDO: 3768 case ISD::UADDO_CARRY: 3769 case ISD::SADDO_CARRY: 3770 if (Op.getResNo() == 1) { 3771 // If we know the result of a setcc has the top bits zero, use this info. 3772 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3773 TargetLowering::ZeroOrOneBooleanContent && 3774 BitWidth > 1) 3775 Known.Zero.setBitsFrom(1); 3776 break; 3777 } 3778 [[fallthrough]]; 3779 case ISD::ADDC: 3780 case ISD::ADDE: { 3781 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3782 3783 // With ADDE and UADDO_CARRY, a carry bit may be added in. 3784 KnownBits Carry(1); 3785 if (Opcode == ISD::ADDE) 3786 // Can't track carry from glue, set carry to unknown. 3787 Carry.resetAll(); 3788 else if (Opcode == ISD::UADDO_CARRY || Opcode == ISD::SADDO_CARRY) { 3789 Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3790 // Carry has bit width 1 3791 Carry = Carry.trunc(1); 3792 } else { 3793 Carry.setAllZero(); 3794 } 3795 3796 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3797 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3798 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3799 break; 3800 } 3801 case ISD::UDIV: { 3802 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3803 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3804 Known = KnownBits::udiv(Known, Known2, Op->getFlags().hasExact()); 3805 break; 3806 } 3807 case ISD::SDIV: { 3808 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3809 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3810 Known = KnownBits::sdiv(Known, Known2, Op->getFlags().hasExact()); 3811 break; 3812 } 3813 case ISD::SREM: { 3814 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3815 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3816 Known = KnownBits::srem(Known, Known2); 3817 break; 3818 } 3819 case ISD::UREM: { 3820 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3821 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3822 Known = KnownBits::urem(Known, Known2); 3823 break; 3824 } 3825 case ISD::EXTRACT_ELEMENT: { 3826 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3827 const unsigned Index = Op.getConstantOperandVal(1); 3828 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3829 3830 // Remove low part of known bits mask 3831 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3832 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3833 3834 // Remove high part of known bit mask 3835 Known = Known.trunc(EltBitWidth); 3836 break; 3837 } 3838 case ISD::EXTRACT_VECTOR_ELT: { 3839 SDValue InVec = Op.getOperand(0); 3840 SDValue EltNo = Op.getOperand(1); 3841 EVT VecVT = InVec.getValueType(); 3842 // computeKnownBits not yet implemented for scalable vectors. 3843 if (VecVT.isScalableVector()) 3844 break; 3845 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3846 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3847 3848 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3849 // anything about the extended bits. 3850 if (BitWidth > EltBitWidth) 3851 Known = Known.trunc(EltBitWidth); 3852 3853 // If we know the element index, just demand that vector element, else for 3854 // an unknown element index, ignore DemandedElts and demand them all. 3855 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 3856 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3857 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3858 DemandedSrcElts = 3859 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3860 3861 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3862 if (BitWidth > EltBitWidth) 3863 Known = Known.anyext(BitWidth); 3864 break; 3865 } 3866 case ISD::INSERT_VECTOR_ELT: { 3867 if (Op.getValueType().isScalableVector()) 3868 break; 3869 3870 // If we know the element index, split the demand between the 3871 // source vector and the inserted element, otherwise assume we need 3872 // the original demanded vector elements and the value. 3873 SDValue InVec = Op.getOperand(0); 3874 SDValue InVal = Op.getOperand(1); 3875 SDValue EltNo = Op.getOperand(2); 3876 bool DemandedVal = true; 3877 APInt DemandedVecElts = DemandedElts; 3878 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3879 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3880 unsigned EltIdx = CEltNo->getZExtValue(); 3881 DemandedVal = !!DemandedElts[EltIdx]; 3882 DemandedVecElts.clearBit(EltIdx); 3883 } 3884 Known.One.setAllBits(); 3885 Known.Zero.setAllBits(); 3886 if (DemandedVal) { 3887 Known2 = computeKnownBits(InVal, Depth + 1); 3888 Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth)); 3889 } 3890 if (!!DemandedVecElts) { 3891 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3892 Known = Known.intersectWith(Known2); 3893 } 3894 break; 3895 } 3896 case ISD::BITREVERSE: { 3897 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3898 Known = Known2.reverseBits(); 3899 break; 3900 } 3901 case ISD::BSWAP: { 3902 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3903 Known = Known2.byteSwap(); 3904 break; 3905 } 3906 case ISD::ABS: { 3907 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3908 Known = Known2.abs(); 3909 break; 3910 } 3911 case ISD::USUBSAT: { 3912 // The result of usubsat will never be larger than the LHS. 3913 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3914 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3915 break; 3916 } 3917 case ISD::UMIN: { 3918 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3919 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3920 Known = KnownBits::umin(Known, Known2); 3921 break; 3922 } 3923 case ISD::UMAX: { 3924 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3925 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3926 Known = KnownBits::umax(Known, Known2); 3927 break; 3928 } 3929 case ISD::SMIN: 3930 case ISD::SMAX: { 3931 // If we have a clamp pattern, we know that the number of sign bits will be 3932 // the minimum of the clamp min/max range. 3933 bool IsMax = (Opcode == ISD::SMAX); 3934 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3935 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3936 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3937 CstHigh = 3938 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3939 if (CstLow && CstHigh) { 3940 if (!IsMax) 3941 std::swap(CstLow, CstHigh); 3942 3943 const APInt &ValueLow = CstLow->getAPIntValue(); 3944 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3945 if (ValueLow.sle(ValueHigh)) { 3946 unsigned LowSignBits = ValueLow.getNumSignBits(); 3947 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3948 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3949 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3950 Known.One.setHighBits(MinSignBits); 3951 break; 3952 } 3953 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3954 Known.Zero.setHighBits(MinSignBits); 3955 break; 3956 } 3957 } 3958 } 3959 3960 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3961 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3962 if (IsMax) 3963 Known = KnownBits::smax(Known, Known2); 3964 else 3965 Known = KnownBits::smin(Known, Known2); 3966 3967 // For SMAX, if CstLow is non-negative we know the result will be 3968 // non-negative and thus all sign bits are 0. 3969 // TODO: There's an equivalent of this for smin with negative constant for 3970 // known ones. 3971 if (IsMax && CstLow) { 3972 const APInt &ValueLow = CstLow->getAPIntValue(); 3973 if (ValueLow.isNonNegative()) { 3974 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 3975 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits())); 3976 } 3977 } 3978 3979 break; 3980 } 3981 case ISD::FP_TO_UINT_SAT: { 3982 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT. 3983 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3984 Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits()); 3985 break; 3986 } 3987 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3988 if (Op.getResNo() == 1) { 3989 // The boolean result conforms to getBooleanContents. 3990 // If we know the result of a setcc has the top bits zero, use this info. 3991 // We know that we have an integer-based boolean since these operations 3992 // are only available for integer. 3993 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3994 TargetLowering::ZeroOrOneBooleanContent && 3995 BitWidth > 1) 3996 Known.Zero.setBitsFrom(1); 3997 break; 3998 } 3999 [[fallthrough]]; 4000 case ISD::ATOMIC_CMP_SWAP: 4001 case ISD::ATOMIC_SWAP: 4002 case ISD::ATOMIC_LOAD_ADD: 4003 case ISD::ATOMIC_LOAD_SUB: 4004 case ISD::ATOMIC_LOAD_AND: 4005 case ISD::ATOMIC_LOAD_CLR: 4006 case ISD::ATOMIC_LOAD_OR: 4007 case ISD::ATOMIC_LOAD_XOR: 4008 case ISD::ATOMIC_LOAD_NAND: 4009 case ISD::ATOMIC_LOAD_MIN: 4010 case ISD::ATOMIC_LOAD_MAX: 4011 case ISD::ATOMIC_LOAD_UMIN: 4012 case ISD::ATOMIC_LOAD_UMAX: 4013 case ISD::ATOMIC_LOAD: { 4014 unsigned MemBits = 4015 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4016 // If we are looking at the loaded value. 4017 if (Op.getResNo() == 0) { 4018 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4019 Known.Zero.setBitsFrom(MemBits); 4020 } 4021 break; 4022 } 4023 case ISD::FrameIndex: 4024 case ISD::TargetFrameIndex: 4025 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 4026 Known, getMachineFunction()); 4027 break; 4028 4029 default: 4030 if (Opcode < ISD::BUILTIN_OP_END) 4031 break; 4032 [[fallthrough]]; 4033 case ISD::INTRINSIC_WO_CHAIN: 4034 case ISD::INTRINSIC_W_CHAIN: 4035 case ISD::INTRINSIC_VOID: 4036 // TODO: Probably okay to remove after audit; here to reduce change size 4037 // in initial enablement patch for scalable vectors 4038 if (Op.getValueType().isScalableVector()) 4039 break; 4040 4041 // Allow the target to implement this method for its nodes. 4042 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 4043 break; 4044 } 4045 4046 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 4047 return Known; 4048 } 4049 4050 /// Convert ConstantRange OverflowResult into SelectionDAG::OverflowKind. 4051 static SelectionDAG::OverflowKind mapOverflowResult(ConstantRange::OverflowResult OR) { 4052 switch (OR) { 4053 case ConstantRange::OverflowResult::MayOverflow: 4054 return SelectionDAG::OFK_Sometime; 4055 case ConstantRange::OverflowResult::AlwaysOverflowsLow: 4056 case ConstantRange::OverflowResult::AlwaysOverflowsHigh: 4057 return SelectionDAG::OFK_Always; 4058 case ConstantRange::OverflowResult::NeverOverflows: 4059 return SelectionDAG::OFK_Never; 4060 } 4061 llvm_unreachable("Unknown OverflowResult"); 4062 } 4063 4064 SelectionDAG::OverflowKind 4065 SelectionDAG::computeOverflowForSignedAdd(SDValue N0, SDValue N1) const { 4066 // X + 0 never overflow 4067 if (isNullConstant(N1)) 4068 return OFK_Never; 4069 4070 // If both operands each have at least two sign bits, the addition 4071 // cannot overflow. 4072 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1) 4073 return OFK_Never; 4074 4075 // TODO: Add ConstantRange::signedAddMayOverflow handling. 4076 return OFK_Sometime; 4077 } 4078 4079 SelectionDAG::OverflowKind 4080 SelectionDAG::computeOverflowForUnsignedAdd(SDValue N0, SDValue N1) const { 4081 // X + 0 never overflow 4082 if (isNullConstant(N1)) 4083 return OFK_Never; 4084 4085 // mulhi + 1 never overflow 4086 KnownBits N1Known = computeKnownBits(N1); 4087 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 4088 N1Known.getMaxValue().ult(2)) 4089 return OFK_Never; 4090 4091 KnownBits N0Known = computeKnownBits(N0); 4092 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1 && 4093 N0Known.getMaxValue().ult(2)) 4094 return OFK_Never; 4095 4096 // Fallback to ConstantRange::unsignedAddMayOverflow handling. 4097 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false); 4098 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false); 4099 return mapOverflowResult(N0Range.unsignedAddMayOverflow(N1Range)); 4100 } 4101 4102 SelectionDAG::OverflowKind 4103 SelectionDAG::computeOverflowForSignedSub(SDValue N0, SDValue N1) const { 4104 // X - 0 never overflow 4105 if (isNullConstant(N1)) 4106 return OFK_Never; 4107 4108 // If both operands each have at least two sign bits, the subtraction 4109 // cannot overflow. 4110 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1) 4111 return OFK_Never; 4112 4113 KnownBits N0Known = computeKnownBits(N0); 4114 KnownBits N1Known = computeKnownBits(N1); 4115 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, true); 4116 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, true); 4117 return mapOverflowResult(N0Range.signedSubMayOverflow(N1Range)); 4118 } 4119 4120 SelectionDAG::OverflowKind 4121 SelectionDAG::computeOverflowForUnsignedSub(SDValue N0, SDValue N1) const { 4122 // X - 0 never overflow 4123 if (isNullConstant(N1)) 4124 return OFK_Never; 4125 4126 KnownBits N0Known = computeKnownBits(N0); 4127 KnownBits N1Known = computeKnownBits(N1); 4128 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false); 4129 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false); 4130 return mapOverflowResult(N0Range.unsignedSubMayOverflow(N1Range)); 4131 } 4132 4133 SelectionDAG::OverflowKind 4134 SelectionDAG::computeOverflowForUnsignedMul(SDValue N0, SDValue N1) const { 4135 // X * 0 and X * 1 never overflow. 4136 if (isNullConstant(N1) || isOneConstant(N1)) 4137 return OFK_Never; 4138 4139 KnownBits N0Known = computeKnownBits(N0); 4140 KnownBits N1Known = computeKnownBits(N1); 4141 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false); 4142 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false); 4143 return mapOverflowResult(N0Range.unsignedMulMayOverflow(N1Range)); 4144 } 4145 4146 SelectionDAG::OverflowKind 4147 SelectionDAG::computeOverflowForSignedMul(SDValue N0, SDValue N1) const { 4148 // X * 0 and X * 1 never overflow. 4149 if (isNullConstant(N1) || isOneConstant(N1)) 4150 return OFK_Never; 4151 4152 // Get the size of the result. 4153 unsigned BitWidth = N0.getScalarValueSizeInBits(); 4154 4155 // Sum of the sign bits. 4156 unsigned SignBits = ComputeNumSignBits(N0) + ComputeNumSignBits(N1); 4157 4158 // If we have enough sign bits, then there's no overflow. 4159 if (SignBits > BitWidth + 1) 4160 return OFK_Never; 4161 4162 if (SignBits == BitWidth + 1) { 4163 // The overflow occurs when the true multiplication of the 4164 // the operands is the minimum negative number. 4165 KnownBits N0Known = computeKnownBits(N0); 4166 KnownBits N1Known = computeKnownBits(N1); 4167 // If one of the operands is non-negative, then there's no 4168 // overflow. 4169 if (N0Known.isNonNegative() || N1Known.isNonNegative()) 4170 return OFK_Never; 4171 } 4172 4173 return OFK_Sometime; 4174 } 4175 4176 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val, unsigned Depth) const { 4177 if (Depth >= MaxRecursionDepth) 4178 return false; // Limit search depth. 4179 4180 EVT OpVT = Val.getValueType(); 4181 unsigned BitWidth = OpVT.getScalarSizeInBits(); 4182 4183 // Is the constant a known power of 2? 4184 if (ISD::matchUnaryPredicate(Val, [BitWidth](ConstantSDNode *C) { 4185 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 4186 })) 4187 return true; 4188 4189 // A left-shift of a constant one will have exactly one bit set because 4190 // shifting the bit off the end is undefined. 4191 if (Val.getOpcode() == ISD::SHL) { 4192 auto *C = isConstOrConstSplat(Val.getOperand(0)); 4193 if (C && C->getAPIntValue() == 1) 4194 return true; 4195 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1) && 4196 isKnownNeverZero(Val, Depth); 4197 } 4198 4199 // Similarly, a logical right-shift of a constant sign-bit will have exactly 4200 // one bit set. 4201 if (Val.getOpcode() == ISD::SRL) { 4202 auto *C = isConstOrConstSplat(Val.getOperand(0)); 4203 if (C && C->getAPIntValue().isSignMask()) 4204 return true; 4205 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1) && 4206 isKnownNeverZero(Val, Depth); 4207 } 4208 4209 if (Val.getOpcode() == ISD::ROTL || Val.getOpcode() == ISD::ROTR) 4210 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1); 4211 4212 // Are all operands of a build vector constant powers of two? 4213 if (Val.getOpcode() == ISD::BUILD_VECTOR) 4214 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 4215 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 4216 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 4217 return false; 4218 })) 4219 return true; 4220 4221 // Is the operand of a splat vector a constant power of two? 4222 if (Val.getOpcode() == ISD::SPLAT_VECTOR) 4223 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0))) 4224 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2()) 4225 return true; 4226 4227 // vscale(power-of-two) is a power-of-two for some targets 4228 if (Val.getOpcode() == ISD::VSCALE && 4229 getTargetLoweringInfo().isVScaleKnownToBeAPowerOfTwo() && 4230 isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1)) 4231 return true; 4232 4233 if (Val.getOpcode() == ISD::SMIN || Val.getOpcode() == ISD::SMAX || 4234 Val.getOpcode() == ISD::UMIN || Val.getOpcode() == ISD::UMAX) 4235 return isKnownToBeAPowerOfTwo(Val.getOperand(1), Depth + 1) && 4236 isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1); 4237 4238 if (Val.getOpcode() == ISD::SELECT || Val.getOpcode() == ISD::VSELECT) 4239 return isKnownToBeAPowerOfTwo(Val.getOperand(2), Depth + 1) && 4240 isKnownToBeAPowerOfTwo(Val.getOperand(1), Depth + 1); 4241 4242 if (Val.getOpcode() == ISD::AND) { 4243 // Looking for `x & -x` pattern: 4244 // If x == 0: 4245 // x & -x -> 0 4246 // If x != 0: 4247 // x & -x -> non-zero pow2 4248 // so if we find the pattern return whether we know `x` is non-zero. 4249 for (unsigned OpIdx = 0; OpIdx < 2; ++OpIdx) { 4250 SDValue NegOp = Val.getOperand(OpIdx); 4251 if (NegOp.getOpcode() == ISD::SUB && 4252 NegOp.getOperand(1) == Val.getOperand(1 - OpIdx) && 4253 isNullOrNullSplat(NegOp.getOperand(0))) 4254 return isKnownNeverZero(Val.getOperand(1 - OpIdx), Depth); 4255 } 4256 } 4257 4258 if (Val.getOpcode() == ISD::ZERO_EXTEND) 4259 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1); 4260 4261 // More could be done here, though the above checks are enough 4262 // to handle some common cases. 4263 return false; 4264 } 4265 4266 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 4267 EVT VT = Op.getValueType(); 4268 4269 // Since the number of lanes in a scalable vector is unknown at compile time, 4270 // we track one bit which is implicitly broadcast to all lanes. This means 4271 // that all lanes in a scalable vector are considered demanded. 4272 APInt DemandedElts = VT.isFixedLengthVector() 4273 ? APInt::getAllOnes(VT.getVectorNumElements()) 4274 : APInt(1, 1); 4275 return ComputeNumSignBits(Op, DemandedElts, Depth); 4276 } 4277 4278 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 4279 unsigned Depth) const { 4280 EVT VT = Op.getValueType(); 4281 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 4282 unsigned VTBits = VT.getScalarSizeInBits(); 4283 unsigned NumElts = DemandedElts.getBitWidth(); 4284 unsigned Tmp, Tmp2; 4285 unsigned FirstAnswer = 1; 4286 4287 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 4288 const APInt &Val = C->getAPIntValue(); 4289 return Val.getNumSignBits(); 4290 } 4291 4292 if (Depth >= MaxRecursionDepth) 4293 return 1; // Limit search depth. 4294 4295 if (!DemandedElts) 4296 return 1; // No demanded elts, better to assume we don't know anything. 4297 4298 unsigned Opcode = Op.getOpcode(); 4299 switch (Opcode) { 4300 default: break; 4301 case ISD::AssertSext: 4302 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 4303 return VTBits-Tmp+1; 4304 case ISD::AssertZext: 4305 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 4306 return VTBits-Tmp; 4307 case ISD::MERGE_VALUES: 4308 return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts, 4309 Depth + 1); 4310 case ISD::SPLAT_VECTOR: { 4311 // Check if the sign bits of source go down as far as the truncated value. 4312 unsigned NumSrcBits = Op.getOperand(0).getValueSizeInBits(); 4313 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4314 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4315 return NumSrcSignBits - (NumSrcBits - VTBits); 4316 break; 4317 } 4318 case ISD::BUILD_VECTOR: 4319 assert(!VT.isScalableVector()); 4320 Tmp = VTBits; 4321 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 4322 if (!DemandedElts[i]) 4323 continue; 4324 4325 SDValue SrcOp = Op.getOperand(i); 4326 // BUILD_VECTOR can implicitly truncate sources, we handle this specially 4327 // for constant nodes to ensure we only look at the sign bits. 4328 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SrcOp)) { 4329 APInt T = C->getAPIntValue().trunc(VTBits); 4330 Tmp2 = T.getNumSignBits(); 4331 } else { 4332 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 4333 4334 if (SrcOp.getValueSizeInBits() != VTBits) { 4335 assert(SrcOp.getValueSizeInBits() > VTBits && 4336 "Expected BUILD_VECTOR implicit truncation"); 4337 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 4338 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 4339 } 4340 } 4341 Tmp = std::min(Tmp, Tmp2); 4342 } 4343 return Tmp; 4344 4345 case ISD::VECTOR_SHUFFLE: { 4346 // Collect the minimum number of sign bits that are shared by every vector 4347 // element referenced by the shuffle. 4348 APInt DemandedLHS, DemandedRHS; 4349 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 4350 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 4351 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts, 4352 DemandedLHS, DemandedRHS)) 4353 return 1; 4354 4355 Tmp = std::numeric_limits<unsigned>::max(); 4356 if (!!DemandedLHS) 4357 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 4358 if (!!DemandedRHS) { 4359 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 4360 Tmp = std::min(Tmp, Tmp2); 4361 } 4362 // If we don't know anything, early out and try computeKnownBits fall-back. 4363 if (Tmp == 1) 4364 break; 4365 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4366 return Tmp; 4367 } 4368 4369 case ISD::BITCAST: { 4370 if (VT.isScalableVector()) 4371 break; 4372 SDValue N0 = Op.getOperand(0); 4373 EVT SrcVT = N0.getValueType(); 4374 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 4375 4376 // Ignore bitcasts from unsupported types.. 4377 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 4378 break; 4379 4380 // Fast handling of 'identity' bitcasts. 4381 if (VTBits == SrcBits) 4382 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 4383 4384 bool IsLE = getDataLayout().isLittleEndian(); 4385 4386 // Bitcast 'large element' scalar/vector to 'small element' vector. 4387 if ((SrcBits % VTBits) == 0) { 4388 assert(VT.isVector() && "Expected bitcast to vector"); 4389 4390 unsigned Scale = SrcBits / VTBits; 4391 APInt SrcDemandedElts = 4392 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale); 4393 4394 // Fast case - sign splat can be simply split across the small elements. 4395 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 4396 if (Tmp == SrcBits) 4397 return VTBits; 4398 4399 // Slow case - determine how far the sign extends into each sub-element. 4400 Tmp2 = VTBits; 4401 for (unsigned i = 0; i != NumElts; ++i) 4402 if (DemandedElts[i]) { 4403 unsigned SubOffset = i % Scale; 4404 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 4405 SubOffset = SubOffset * VTBits; 4406 if (Tmp <= SubOffset) 4407 return 1; 4408 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 4409 } 4410 return Tmp2; 4411 } 4412 break; 4413 } 4414 4415 case ISD::FP_TO_SINT_SAT: 4416 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT. 4417 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 4418 return VTBits - Tmp + 1; 4419 case ISD::SIGN_EXTEND: 4420 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 4421 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 4422 case ISD::SIGN_EXTEND_INREG: 4423 // Max of the input and what this extends. 4424 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 4425 Tmp = VTBits-Tmp+1; 4426 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4427 return std::max(Tmp, Tmp2); 4428 case ISD::SIGN_EXTEND_VECTOR_INREG: { 4429 if (VT.isScalableVector()) 4430 break; 4431 SDValue Src = Op.getOperand(0); 4432 EVT SrcVT = Src.getValueType(); 4433 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements()); 4434 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 4435 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 4436 } 4437 case ISD::SRA: 4438 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4439 // SRA X, C -> adds C sign bits. 4440 if (const APInt *ShAmt = 4441 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 4442 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 4443 return Tmp; 4444 case ISD::SHL: 4445 if (const APInt *ShAmt = 4446 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 4447 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 4448 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4449 if (ShAmt->ult(Tmp)) 4450 return Tmp - ShAmt->getZExtValue(); 4451 } 4452 break; 4453 case ISD::AND: 4454 case ISD::OR: 4455 case ISD::XOR: // NOT is handled here. 4456 // Logical binary ops preserve the number of sign bits at the worst. 4457 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4458 if (Tmp != 1) { 4459 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4460 FirstAnswer = std::min(Tmp, Tmp2); 4461 // We computed what we know about the sign bits as our first 4462 // answer. Now proceed to the generic code that uses 4463 // computeKnownBits, and pick whichever answer is better. 4464 } 4465 break; 4466 4467 case ISD::SELECT: 4468 case ISD::VSELECT: 4469 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4470 if (Tmp == 1) return 1; // Early out. 4471 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4472 return std::min(Tmp, Tmp2); 4473 case ISD::SELECT_CC: 4474 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4475 if (Tmp == 1) return 1; // Early out. 4476 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 4477 return std::min(Tmp, Tmp2); 4478 4479 case ISD::SMIN: 4480 case ISD::SMAX: { 4481 // If we have a clamp pattern, we know that the number of sign bits will be 4482 // the minimum of the clamp min/max range. 4483 bool IsMax = (Opcode == ISD::SMAX); 4484 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 4485 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 4486 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 4487 CstHigh = 4488 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 4489 if (CstLow && CstHigh) { 4490 if (!IsMax) 4491 std::swap(CstLow, CstHigh); 4492 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 4493 Tmp = CstLow->getAPIntValue().getNumSignBits(); 4494 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 4495 return std::min(Tmp, Tmp2); 4496 } 4497 } 4498 4499 // Fallback - just get the minimum number of sign bits of the operands. 4500 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4501 if (Tmp == 1) 4502 return 1; // Early out. 4503 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4504 return std::min(Tmp, Tmp2); 4505 } 4506 case ISD::UMIN: 4507 case ISD::UMAX: 4508 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4509 if (Tmp == 1) 4510 return 1; // Early out. 4511 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4512 return std::min(Tmp, Tmp2); 4513 case ISD::SADDO: 4514 case ISD::UADDO: 4515 case ISD::SADDO_CARRY: 4516 case ISD::UADDO_CARRY: 4517 case ISD::SSUBO: 4518 case ISD::USUBO: 4519 case ISD::SSUBO_CARRY: 4520 case ISD::USUBO_CARRY: 4521 case ISD::SMULO: 4522 case ISD::UMULO: 4523 if (Op.getResNo() != 1) 4524 break; 4525 // The boolean result conforms to getBooleanContents. Fall through. 4526 // If setcc returns 0/-1, all bits are sign bits. 4527 // We know that we have an integer-based boolean since these operations 4528 // are only available for integer. 4529 if (TLI->getBooleanContents(VT.isVector(), false) == 4530 TargetLowering::ZeroOrNegativeOneBooleanContent) 4531 return VTBits; 4532 break; 4533 case ISD::SETCC: 4534 case ISD::SETCCCARRY: 4535 case ISD::STRICT_FSETCC: 4536 case ISD::STRICT_FSETCCS: { 4537 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 4538 // If setcc returns 0/-1, all bits are sign bits. 4539 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 4540 TargetLowering::ZeroOrNegativeOneBooleanContent) 4541 return VTBits; 4542 break; 4543 } 4544 case ISD::ROTL: 4545 case ISD::ROTR: 4546 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4547 4548 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 4549 if (Tmp == VTBits) 4550 return VTBits; 4551 4552 if (ConstantSDNode *C = 4553 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 4554 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 4555 4556 // Handle rotate right by N like a rotate left by 32-N. 4557 if (Opcode == ISD::ROTR) 4558 RotAmt = (VTBits - RotAmt) % VTBits; 4559 4560 // If we aren't rotating out all of the known-in sign bits, return the 4561 // number that are left. This handles rotl(sext(x), 1) for example. 4562 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 4563 } 4564 break; 4565 case ISD::ADD: 4566 case ISD::ADDC: 4567 // Add can have at most one carry bit. Thus we know that the output 4568 // is, at worst, one more bit than the inputs. 4569 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4570 if (Tmp == 1) return 1; // Early out. 4571 4572 // Special case decrementing a value (ADD X, -1): 4573 if (ConstantSDNode *CRHS = 4574 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 4575 if (CRHS->isAllOnes()) { 4576 KnownBits Known = 4577 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 4578 4579 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4580 // sign bits set. 4581 if ((Known.Zero | 1).isAllOnes()) 4582 return VTBits; 4583 4584 // If we are subtracting one from a positive number, there is no carry 4585 // out of the result. 4586 if (Known.isNonNegative()) 4587 return Tmp; 4588 } 4589 4590 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4591 if (Tmp2 == 1) return 1; // Early out. 4592 return std::min(Tmp, Tmp2) - 1; 4593 case ISD::SUB: 4594 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4595 if (Tmp2 == 1) return 1; // Early out. 4596 4597 // Handle NEG. 4598 if (ConstantSDNode *CLHS = 4599 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 4600 if (CLHS->isZero()) { 4601 KnownBits Known = 4602 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 4603 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4604 // sign bits set. 4605 if ((Known.Zero | 1).isAllOnes()) 4606 return VTBits; 4607 4608 // If the input is known to be positive (the sign bit is known clear), 4609 // the output of the NEG has the same number of sign bits as the input. 4610 if (Known.isNonNegative()) 4611 return Tmp2; 4612 4613 // Otherwise, we treat this like a SUB. 4614 } 4615 4616 // Sub can have at most one carry bit. Thus we know that the output 4617 // is, at worst, one more bit than the inputs. 4618 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4619 if (Tmp == 1) return 1; // Early out. 4620 return std::min(Tmp, Tmp2) - 1; 4621 case ISD::MUL: { 4622 // The output of the Mul can be at most twice the valid bits in the inputs. 4623 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4624 if (SignBitsOp0 == 1) 4625 break; 4626 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 4627 if (SignBitsOp1 == 1) 4628 break; 4629 unsigned OutValidBits = 4630 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 4631 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 4632 } 4633 case ISD::SREM: 4634 // The sign bit is the LHS's sign bit, except when the result of the 4635 // remainder is zero. The magnitude of the result should be less than or 4636 // equal to the magnitude of the LHS. Therefore, the result should have 4637 // at least as many sign bits as the left hand side. 4638 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4639 case ISD::TRUNCATE: { 4640 // Check if the sign bits of source go down as far as the truncated value. 4641 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 4642 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4643 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4644 return NumSrcSignBits - (NumSrcBits - VTBits); 4645 break; 4646 } 4647 case ISD::EXTRACT_ELEMENT: { 4648 if (VT.isScalableVector()) 4649 break; 4650 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 4651 const int BitWidth = Op.getValueSizeInBits(); 4652 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 4653 4654 // Get reverse index (starting from 1), Op1 value indexes elements from 4655 // little end. Sign starts at big end. 4656 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 4657 4658 // If the sign portion ends in our element the subtraction gives correct 4659 // result. Otherwise it gives either negative or > bitwidth result 4660 return std::clamp(KnownSign - rIndex * BitWidth, 0, BitWidth); 4661 } 4662 case ISD::INSERT_VECTOR_ELT: { 4663 if (VT.isScalableVector()) 4664 break; 4665 // If we know the element index, split the demand between the 4666 // source vector and the inserted element, otherwise assume we need 4667 // the original demanded vector elements and the value. 4668 SDValue InVec = Op.getOperand(0); 4669 SDValue InVal = Op.getOperand(1); 4670 SDValue EltNo = Op.getOperand(2); 4671 bool DemandedVal = true; 4672 APInt DemandedVecElts = DemandedElts; 4673 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 4674 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 4675 unsigned EltIdx = CEltNo->getZExtValue(); 4676 DemandedVal = !!DemandedElts[EltIdx]; 4677 DemandedVecElts.clearBit(EltIdx); 4678 } 4679 Tmp = std::numeric_limits<unsigned>::max(); 4680 if (DemandedVal) { 4681 // TODO - handle implicit truncation of inserted elements. 4682 if (InVal.getScalarValueSizeInBits() != VTBits) 4683 break; 4684 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4685 Tmp = std::min(Tmp, Tmp2); 4686 } 4687 if (!!DemandedVecElts) { 4688 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 4689 Tmp = std::min(Tmp, Tmp2); 4690 } 4691 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4692 return Tmp; 4693 } 4694 case ISD::EXTRACT_VECTOR_ELT: { 4695 assert(!VT.isScalableVector()); 4696 SDValue InVec = Op.getOperand(0); 4697 SDValue EltNo = Op.getOperand(1); 4698 EVT VecVT = InVec.getValueType(); 4699 // ComputeNumSignBits not yet implemented for scalable vectors. 4700 if (VecVT.isScalableVector()) 4701 break; 4702 const unsigned BitWidth = Op.getValueSizeInBits(); 4703 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4704 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4705 4706 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4707 // anything about sign bits. But if the sizes match we can derive knowledge 4708 // about sign bits from the vector operand. 4709 if (BitWidth != EltBitWidth) 4710 break; 4711 4712 // If we know the element index, just demand that vector element, else for 4713 // an unknown element index, ignore DemandedElts and demand them all. 4714 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 4715 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4716 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4717 DemandedSrcElts = 4718 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4719 4720 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4721 } 4722 case ISD::EXTRACT_SUBVECTOR: { 4723 // Offset the demanded elts by the subvector index. 4724 SDValue Src = Op.getOperand(0); 4725 // Bail until we can represent demanded elements for scalable vectors. 4726 if (Src.getValueType().isScalableVector()) 4727 break; 4728 uint64_t Idx = Op.getConstantOperandVal(1); 4729 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4730 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 4731 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4732 } 4733 case ISD::CONCAT_VECTORS: { 4734 if (VT.isScalableVector()) 4735 break; 4736 // Determine the minimum number of sign bits across all demanded 4737 // elts of the input vectors. Early out if the result is already 1. 4738 Tmp = std::numeric_limits<unsigned>::max(); 4739 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4740 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4741 unsigned NumSubVectors = Op.getNumOperands(); 4742 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4743 APInt DemandedSub = 4744 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 4745 if (!DemandedSub) 4746 continue; 4747 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4748 Tmp = std::min(Tmp, Tmp2); 4749 } 4750 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4751 return Tmp; 4752 } 4753 case ISD::INSERT_SUBVECTOR: { 4754 if (VT.isScalableVector()) 4755 break; 4756 // Demand any elements from the subvector and the remainder from the src its 4757 // inserted into. 4758 SDValue Src = Op.getOperand(0); 4759 SDValue Sub = Op.getOperand(1); 4760 uint64_t Idx = Op.getConstantOperandVal(2); 4761 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4762 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4763 APInt DemandedSrcElts = DemandedElts; 4764 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 4765 4766 Tmp = std::numeric_limits<unsigned>::max(); 4767 if (!!DemandedSubElts) { 4768 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4769 if (Tmp == 1) 4770 return 1; // early-out 4771 } 4772 if (!!DemandedSrcElts) { 4773 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4774 Tmp = std::min(Tmp, Tmp2); 4775 } 4776 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4777 return Tmp; 4778 } 4779 case ISD::LOAD: { 4780 LoadSDNode *LD = cast<LoadSDNode>(Op); 4781 if (const MDNode *Ranges = LD->getRanges()) { 4782 if (DemandedElts != 1) 4783 break; 4784 4785 ConstantRange CR = getConstantRangeFromMetadata(*Ranges); 4786 if (VTBits > CR.getBitWidth()) { 4787 switch (LD->getExtensionType()) { 4788 case ISD::SEXTLOAD: 4789 CR = CR.signExtend(VTBits); 4790 break; 4791 case ISD::ZEXTLOAD: 4792 CR = CR.zeroExtend(VTBits); 4793 break; 4794 default: 4795 break; 4796 } 4797 } 4798 4799 if (VTBits != CR.getBitWidth()) 4800 break; 4801 return std::min(CR.getSignedMin().getNumSignBits(), 4802 CR.getSignedMax().getNumSignBits()); 4803 } 4804 4805 break; 4806 } 4807 case ISD::ATOMIC_CMP_SWAP: 4808 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4809 case ISD::ATOMIC_SWAP: 4810 case ISD::ATOMIC_LOAD_ADD: 4811 case ISD::ATOMIC_LOAD_SUB: 4812 case ISD::ATOMIC_LOAD_AND: 4813 case ISD::ATOMIC_LOAD_CLR: 4814 case ISD::ATOMIC_LOAD_OR: 4815 case ISD::ATOMIC_LOAD_XOR: 4816 case ISD::ATOMIC_LOAD_NAND: 4817 case ISD::ATOMIC_LOAD_MIN: 4818 case ISD::ATOMIC_LOAD_MAX: 4819 case ISD::ATOMIC_LOAD_UMIN: 4820 case ISD::ATOMIC_LOAD_UMAX: 4821 case ISD::ATOMIC_LOAD: { 4822 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4823 // If we are looking at the loaded value. 4824 if (Op.getResNo() == 0) { 4825 if (Tmp == VTBits) 4826 return 1; // early-out 4827 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND) 4828 return VTBits - Tmp + 1; 4829 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4830 return VTBits - Tmp; 4831 } 4832 break; 4833 } 4834 } 4835 4836 // If we are looking at the loaded value of the SDNode. 4837 if (Op.getResNo() == 0) { 4838 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4839 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4840 unsigned ExtType = LD->getExtensionType(); 4841 switch (ExtType) { 4842 default: break; 4843 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4844 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4845 return VTBits - Tmp + 1; 4846 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4847 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4848 return VTBits - Tmp; 4849 case ISD::NON_EXTLOAD: 4850 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4851 // We only need to handle vectors - computeKnownBits should handle 4852 // scalar cases. 4853 Type *CstTy = Cst->getType(); 4854 if (CstTy->isVectorTy() && !VT.isScalableVector() && 4855 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() && 4856 VTBits == CstTy->getScalarSizeInBits()) { 4857 Tmp = VTBits; 4858 for (unsigned i = 0; i != NumElts; ++i) { 4859 if (!DemandedElts[i]) 4860 continue; 4861 if (Constant *Elt = Cst->getAggregateElement(i)) { 4862 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4863 const APInt &Value = CInt->getValue(); 4864 Tmp = std::min(Tmp, Value.getNumSignBits()); 4865 continue; 4866 } 4867 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4868 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4869 Tmp = std::min(Tmp, Value.getNumSignBits()); 4870 continue; 4871 } 4872 } 4873 // Unknown type. Conservatively assume no bits match sign bit. 4874 return 1; 4875 } 4876 return Tmp; 4877 } 4878 } 4879 break; 4880 } 4881 } 4882 } 4883 4884 // Allow the target to implement this method for its nodes. 4885 if (Opcode >= ISD::BUILTIN_OP_END || 4886 Opcode == ISD::INTRINSIC_WO_CHAIN || 4887 Opcode == ISD::INTRINSIC_W_CHAIN || 4888 Opcode == ISD::INTRINSIC_VOID) { 4889 // TODO: This can probably be removed once target code is audited. This 4890 // is here purely to reduce patch size and review complexity. 4891 if (!VT.isScalableVector()) { 4892 unsigned NumBits = 4893 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4894 if (NumBits > 1) 4895 FirstAnswer = std::max(FirstAnswer, NumBits); 4896 } 4897 } 4898 4899 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4900 // use this information. 4901 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4902 return std::max(FirstAnswer, Known.countMinSignBits()); 4903 } 4904 4905 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4906 unsigned Depth) const { 4907 unsigned SignBits = ComputeNumSignBits(Op, Depth); 4908 return Op.getScalarValueSizeInBits() - SignBits + 1; 4909 } 4910 4911 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4912 const APInt &DemandedElts, 4913 unsigned Depth) const { 4914 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth); 4915 return Op.getScalarValueSizeInBits() - SignBits + 1; 4916 } 4917 4918 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly, 4919 unsigned Depth) const { 4920 // Early out for FREEZE. 4921 if (Op.getOpcode() == ISD::FREEZE) 4922 return true; 4923 4924 // TODO: Assume we don't know anything for now. 4925 EVT VT = Op.getValueType(); 4926 if (VT.isScalableVector()) 4927 return false; 4928 4929 APInt DemandedElts = VT.isVector() 4930 ? APInt::getAllOnes(VT.getVectorNumElements()) 4931 : APInt(1, 1); 4932 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth); 4933 } 4934 4935 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, 4936 const APInt &DemandedElts, 4937 bool PoisonOnly, 4938 unsigned Depth) const { 4939 unsigned Opcode = Op.getOpcode(); 4940 4941 // Early out for FREEZE. 4942 if (Opcode == ISD::FREEZE) 4943 return true; 4944 4945 if (Depth >= MaxRecursionDepth) 4946 return false; // Limit search depth. 4947 4948 if (isIntOrFPConstant(Op)) 4949 return true; 4950 4951 switch (Opcode) { 4952 case ISD::VALUETYPE: 4953 case ISD::FrameIndex: 4954 case ISD::TargetFrameIndex: 4955 return true; 4956 4957 case ISD::UNDEF: 4958 return PoisonOnly; 4959 4960 case ISD::BUILD_VECTOR: 4961 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements - 4962 // this shouldn't affect the result. 4963 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) { 4964 if (!DemandedElts[i]) 4965 continue; 4966 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly, 4967 Depth + 1)) 4968 return false; 4969 } 4970 return true; 4971 4972 // TODO: Search for noundef attributes from library functions. 4973 4974 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef. 4975 4976 default: 4977 // Allow the target to implement this method for its nodes. 4978 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 4979 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 4980 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode( 4981 Op, DemandedElts, *this, PoisonOnly, Depth); 4982 break; 4983 } 4984 4985 // If Op can't create undef/poison and none of its operands are undef/poison 4986 // then Op is never undef/poison. 4987 // NOTE: TargetNodes should handle this in themselves in 4988 // isGuaranteedNotToBeUndefOrPoisonForTargetNode. 4989 return !canCreateUndefOrPoison(Op, PoisonOnly, /*ConsiderFlags*/ true, 4990 Depth) && 4991 all_of(Op->ops(), [&](SDValue V) { 4992 return isGuaranteedNotToBeUndefOrPoison(V, PoisonOnly, Depth + 1); 4993 }); 4994 } 4995 4996 bool SelectionDAG::canCreateUndefOrPoison(SDValue Op, bool PoisonOnly, 4997 bool ConsiderFlags, 4998 unsigned Depth) const { 4999 // TODO: Assume we don't know anything for now. 5000 EVT VT = Op.getValueType(); 5001 if (VT.isScalableVector()) 5002 return true; 5003 5004 APInt DemandedElts = VT.isVector() 5005 ? APInt::getAllOnes(VT.getVectorNumElements()) 5006 : APInt(1, 1); 5007 return canCreateUndefOrPoison(Op, DemandedElts, PoisonOnly, ConsiderFlags, 5008 Depth); 5009 } 5010 5011 bool SelectionDAG::canCreateUndefOrPoison(SDValue Op, const APInt &DemandedElts, 5012 bool PoisonOnly, bool ConsiderFlags, 5013 unsigned Depth) const { 5014 // TODO: Assume we don't know anything for now. 5015 EVT VT = Op.getValueType(); 5016 if (VT.isScalableVector()) 5017 return true; 5018 5019 unsigned Opcode = Op.getOpcode(); 5020 switch (Opcode) { 5021 case ISD::FREEZE: 5022 case ISD::CONCAT_VECTORS: 5023 case ISD::INSERT_SUBVECTOR: 5024 case ISD::AND: 5025 case ISD::OR: 5026 case ISD::XOR: 5027 case ISD::ROTL: 5028 case ISD::ROTR: 5029 case ISD::FSHL: 5030 case ISD::FSHR: 5031 case ISD::BSWAP: 5032 case ISD::CTPOP: 5033 case ISD::BITREVERSE: 5034 case ISD::PARITY: 5035 case ISD::SIGN_EXTEND: 5036 case ISD::TRUNCATE: 5037 case ISD::SIGN_EXTEND_INREG: 5038 case ISD::SIGN_EXTEND_VECTOR_INREG: 5039 case ISD::ZERO_EXTEND_VECTOR_INREG: 5040 case ISD::BITCAST: 5041 case ISD::BUILD_VECTOR: 5042 case ISD::BUILD_PAIR: 5043 return false; 5044 5045 // Matches hasPoisonGeneratingFlags(). 5046 case ISD::ZERO_EXTEND: 5047 return ConsiderFlags && Op->getFlags().hasNonNeg(); 5048 5049 case ISD::ADD: 5050 case ISD::SUB: 5051 case ISD::MUL: 5052 // Matches hasPoisonGeneratingFlags(). 5053 return ConsiderFlags && (Op->getFlags().hasNoSignedWrap() || 5054 Op->getFlags().hasNoUnsignedWrap()); 5055 5056 case ISD::SHL: 5057 // If the max shift amount isn't in range, then the shift can create poison. 5058 if (!getValidMaximumShiftAmountConstant(Op, DemandedElts)) 5059 return true; 5060 5061 // Matches hasPoisonGeneratingFlags(). 5062 return ConsiderFlags && (Op->getFlags().hasNoSignedWrap() || 5063 Op->getFlags().hasNoUnsignedWrap()); 5064 5065 case ISD::INSERT_VECTOR_ELT:{ 5066 // Ensure that the element index is in bounds. 5067 EVT VecVT = Op.getOperand(0).getValueType(); 5068 KnownBits KnownIdx = computeKnownBits(Op.getOperand(2), Depth + 1); 5069 return KnownIdx.getMaxValue().uge(VecVT.getVectorMinNumElements()); 5070 } 5071 5072 default: 5073 // Allow the target to implement this method for its nodes. 5074 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 5075 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 5076 return TLI->canCreateUndefOrPoisonForTargetNode( 5077 Op, DemandedElts, *this, PoisonOnly, ConsiderFlags, Depth); 5078 break; 5079 } 5080 5081 // Be conservative and return true. 5082 return true; 5083 } 5084 5085 bool SelectionDAG::isADDLike(SDValue Op) const { 5086 unsigned Opcode = Op.getOpcode(); 5087 if (Opcode == ISD::OR) 5088 return haveNoCommonBitsSet(Op.getOperand(0), Op.getOperand(1)); 5089 if (Opcode == ISD::XOR) 5090 return isMinSignedConstant(Op.getOperand(1)); 5091 return false; 5092 } 5093 5094 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 5095 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 5096 !isa<ConstantSDNode>(Op.getOperand(1))) 5097 return false; 5098 5099 if (Op.getOpcode() == ISD::OR && 5100 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 5101 return false; 5102 5103 return true; 5104 } 5105 5106 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 5107 // If we're told that NaNs won't happen, assume they won't. 5108 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 5109 return true; 5110 5111 if (Depth >= MaxRecursionDepth) 5112 return false; // Limit search depth. 5113 5114 // If the value is a constant, we can obviously see if it is a NaN or not. 5115 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 5116 return !C->getValueAPF().isNaN() || 5117 (SNaN && !C->getValueAPF().isSignaling()); 5118 } 5119 5120 unsigned Opcode = Op.getOpcode(); 5121 switch (Opcode) { 5122 case ISD::FADD: 5123 case ISD::FSUB: 5124 case ISD::FMUL: 5125 case ISD::FDIV: 5126 case ISD::FREM: 5127 case ISD::FSIN: 5128 case ISD::FCOS: 5129 case ISD::FMA: 5130 case ISD::FMAD: { 5131 if (SNaN) 5132 return true; 5133 // TODO: Need isKnownNeverInfinity 5134 return false; 5135 } 5136 case ISD::FCANONICALIZE: 5137 case ISD::FEXP: 5138 case ISD::FEXP2: 5139 case ISD::FEXP10: 5140 case ISD::FTRUNC: 5141 case ISD::FFLOOR: 5142 case ISD::FCEIL: 5143 case ISD::FROUND: 5144 case ISD::FROUNDEVEN: 5145 case ISD::FRINT: 5146 case ISD::LRINT: 5147 case ISD::LLRINT: 5148 case ISD::FNEARBYINT: 5149 case ISD::FLDEXP: { 5150 if (SNaN) 5151 return true; 5152 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 5153 } 5154 case ISD::FABS: 5155 case ISD::FNEG: 5156 case ISD::FCOPYSIGN: { 5157 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 5158 } 5159 case ISD::SELECT: 5160 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 5161 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 5162 case ISD::FP_EXTEND: 5163 case ISD::FP_ROUND: { 5164 if (SNaN) 5165 return true; 5166 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 5167 } 5168 case ISD::SINT_TO_FP: 5169 case ISD::UINT_TO_FP: 5170 return true; 5171 case ISD::FSQRT: // Need is known positive 5172 case ISD::FLOG: 5173 case ISD::FLOG2: 5174 case ISD::FLOG10: 5175 case ISD::FPOWI: 5176 case ISD::FPOW: { 5177 if (SNaN) 5178 return true; 5179 // TODO: Refine on operand 5180 return false; 5181 } 5182 case ISD::FMINNUM: 5183 case ISD::FMAXNUM: { 5184 // Only one needs to be known not-nan, since it will be returned if the 5185 // other ends up being one. 5186 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 5187 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 5188 } 5189 case ISD::FMINNUM_IEEE: 5190 case ISD::FMAXNUM_IEEE: { 5191 if (SNaN) 5192 return true; 5193 // This can return a NaN if either operand is an sNaN, or if both operands 5194 // are NaN. 5195 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 5196 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 5197 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 5198 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 5199 } 5200 case ISD::FMINIMUM: 5201 case ISD::FMAXIMUM: { 5202 // TODO: Does this quiet or return the origina NaN as-is? 5203 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 5204 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 5205 } 5206 case ISD::EXTRACT_VECTOR_ELT: { 5207 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 5208 } 5209 case ISD::BUILD_VECTOR: { 5210 for (const SDValue &Opnd : Op->ops()) 5211 if (!isKnownNeverNaN(Opnd, SNaN, Depth + 1)) 5212 return false; 5213 return true; 5214 } 5215 default: 5216 if (Opcode >= ISD::BUILTIN_OP_END || 5217 Opcode == ISD::INTRINSIC_WO_CHAIN || 5218 Opcode == ISD::INTRINSIC_W_CHAIN || 5219 Opcode == ISD::INTRINSIC_VOID) { 5220 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 5221 } 5222 5223 return false; 5224 } 5225 } 5226 5227 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 5228 assert(Op.getValueType().isFloatingPoint() && 5229 "Floating point type expected"); 5230 5231 // If the value is a constant, we can obviously see if it is a zero or not. 5232 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 5233 return !C->isZero(); 5234 5235 // Return false if we find any zero in a vector. 5236 if (Op->getOpcode() == ISD::BUILD_VECTOR || 5237 Op->getOpcode() == ISD::SPLAT_VECTOR) { 5238 for (const SDValue &OpVal : Op->op_values()) { 5239 if (OpVal.isUndef()) 5240 return false; 5241 if (auto *C = dyn_cast<ConstantFPSDNode>(OpVal)) 5242 if (C->isZero()) 5243 return false; 5244 } 5245 return true; 5246 } 5247 return false; 5248 } 5249 5250 bool SelectionDAG::isKnownNeverZero(SDValue Op, unsigned Depth) const { 5251 if (Depth >= MaxRecursionDepth) 5252 return false; // Limit search depth. 5253 5254 assert(!Op.getValueType().isFloatingPoint() && 5255 "Floating point types unsupported - use isKnownNeverZeroFloat"); 5256 5257 // If the value is a constant, we can obviously see if it is a zero or not. 5258 if (ISD::matchUnaryPredicate(Op, 5259 [](ConstantSDNode *C) { return !C->isZero(); })) 5260 return true; 5261 5262 // TODO: Recognize more cases here. Most of the cases are also incomplete to 5263 // some degree. 5264 switch (Op.getOpcode()) { 5265 default: 5266 break; 5267 5268 case ISD::OR: 5269 return isKnownNeverZero(Op.getOperand(1), Depth + 1) || 5270 isKnownNeverZero(Op.getOperand(0), Depth + 1); 5271 5272 case ISD::VSELECT: 5273 case ISD::SELECT: 5274 return isKnownNeverZero(Op.getOperand(1), Depth + 1) && 5275 isKnownNeverZero(Op.getOperand(2), Depth + 1); 5276 5277 case ISD::SHL: { 5278 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap()) 5279 return isKnownNeverZero(Op.getOperand(0), Depth + 1); 5280 KnownBits ValKnown = computeKnownBits(Op.getOperand(0), Depth + 1); 5281 // 1 << X is never zero. 5282 if (ValKnown.One[0]) 5283 return true; 5284 // If max shift cnt of known ones is non-zero, result is non-zero. 5285 APInt MaxCnt = computeKnownBits(Op.getOperand(1), Depth + 1).getMaxValue(); 5286 if (MaxCnt.ult(ValKnown.getBitWidth()) && 5287 !ValKnown.One.shl(MaxCnt).isZero()) 5288 return true; 5289 break; 5290 } 5291 case ISD::UADDSAT: 5292 case ISD::UMAX: 5293 return isKnownNeverZero(Op.getOperand(1), Depth + 1) || 5294 isKnownNeverZero(Op.getOperand(0), Depth + 1); 5295 5296 // TODO for smin/smax: If either operand is known negative/positive 5297 // respectively we don't need the other to be known at all. 5298 case ISD::SMAX: 5299 case ISD::SMIN: 5300 case ISD::UMIN: 5301 return isKnownNeverZero(Op.getOperand(1), Depth + 1) && 5302 isKnownNeverZero(Op.getOperand(0), Depth + 1); 5303 5304 case ISD::ROTL: 5305 case ISD::ROTR: 5306 case ISD::BITREVERSE: 5307 case ISD::BSWAP: 5308 case ISD::CTPOP: 5309 case ISD::ABS: 5310 return isKnownNeverZero(Op.getOperand(0), Depth + 1); 5311 5312 case ISD::SRA: 5313 case ISD::SRL: { 5314 if (Op->getFlags().hasExact()) 5315 return isKnownNeverZero(Op.getOperand(0), Depth + 1); 5316 KnownBits ValKnown = computeKnownBits(Op.getOperand(0), Depth + 1); 5317 if (ValKnown.isNegative()) 5318 return true; 5319 // If max shift cnt of known ones is non-zero, result is non-zero. 5320 APInt MaxCnt = computeKnownBits(Op.getOperand(1), Depth + 1).getMaxValue(); 5321 if (MaxCnt.ult(ValKnown.getBitWidth()) && 5322 !ValKnown.One.lshr(MaxCnt).isZero()) 5323 return true; 5324 break; 5325 } 5326 case ISD::UDIV: 5327 case ISD::SDIV: 5328 // div exact can only produce a zero if the dividend is zero. 5329 // TODO: For udiv this is also true if Op1 u<= Op0 5330 if (Op->getFlags().hasExact()) 5331 return isKnownNeverZero(Op.getOperand(0), Depth + 1); 5332 break; 5333 5334 case ISD::ADD: 5335 if (Op->getFlags().hasNoUnsignedWrap()) 5336 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) || 5337 isKnownNeverZero(Op.getOperand(0), Depth + 1)) 5338 return true; 5339 // TODO: There are a lot more cases we can prove for add. 5340 break; 5341 5342 case ISD::SUB: { 5343 if (isNullConstant(Op.getOperand(0))) 5344 return isKnownNeverZero(Op.getOperand(1), Depth + 1); 5345 5346 std::optional<bool> ne = 5347 KnownBits::ne(computeKnownBits(Op.getOperand(0), Depth + 1), 5348 computeKnownBits(Op.getOperand(1), Depth + 1)); 5349 return ne && *ne; 5350 } 5351 5352 case ISD::MUL: 5353 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap()) 5354 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) && 5355 isKnownNeverZero(Op.getOperand(0), Depth + 1)) 5356 return true; 5357 break; 5358 5359 case ISD::ZERO_EXTEND: 5360 case ISD::SIGN_EXTEND: 5361 return isKnownNeverZero(Op.getOperand(0), Depth + 1); 5362 } 5363 5364 return computeKnownBits(Op, Depth).isNonZero(); 5365 } 5366 5367 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 5368 // Check the obvious case. 5369 if (A == B) return true; 5370 5371 // For negative and positive zero. 5372 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 5373 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 5374 if (CA->isZero() && CB->isZero()) return true; 5375 5376 // Otherwise they may not be equal. 5377 return false; 5378 } 5379 5380 // Only bits set in Mask must be negated, other bits may be arbitrary. 5381 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) { 5382 if (isBitwiseNot(V, AllowUndefs)) 5383 return V.getOperand(0); 5384 5385 // Handle any_extend (not (truncate X)) pattern, where Mask only sets 5386 // bits in the non-extended part. 5387 ConstantSDNode *MaskC = isConstOrConstSplat(Mask); 5388 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND) 5389 return SDValue(); 5390 SDValue ExtArg = V.getOperand(0); 5391 if (ExtArg.getScalarValueSizeInBits() >= 5392 MaskC->getAPIntValue().getActiveBits() && 5393 isBitwiseNot(ExtArg, AllowUndefs) && 5394 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE && 5395 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType()) 5396 return ExtArg.getOperand(0).getOperand(0); 5397 return SDValue(); 5398 } 5399 5400 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) { 5401 // Match masked merge pattern (X & ~M) op (Y & M) 5402 // Including degenerate case (X & ~M) op M 5403 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask, 5404 SDValue Other) { 5405 if (SDValue NotOperand = 5406 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) { 5407 if (NotOperand->getOpcode() == ISD::ZERO_EXTEND || 5408 NotOperand->getOpcode() == ISD::TRUNCATE) 5409 NotOperand = NotOperand->getOperand(0); 5410 5411 if (Other == NotOperand) 5412 return true; 5413 if (Other->getOpcode() == ISD::AND) 5414 return NotOperand == Other->getOperand(0) || 5415 NotOperand == Other->getOperand(1); 5416 } 5417 return false; 5418 }; 5419 5420 if (A->getOpcode() == ISD::ZERO_EXTEND || A->getOpcode() == ISD::TRUNCATE) 5421 A = A->getOperand(0); 5422 5423 if (B->getOpcode() == ISD::ZERO_EXTEND || B->getOpcode() == ISD::TRUNCATE) 5424 B = B->getOperand(0); 5425 5426 if (A->getOpcode() == ISD::AND) 5427 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) || 5428 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B); 5429 return false; 5430 } 5431 5432 // FIXME: unify with llvm::haveNoCommonBitsSet. 5433 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 5434 assert(A.getValueType() == B.getValueType() && 5435 "Values must have the same type"); 5436 if (haveNoCommonBitsSetCommutative(A, B) || 5437 haveNoCommonBitsSetCommutative(B, A)) 5438 return true; 5439 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A), 5440 computeKnownBits(B)); 5441 } 5442 5443 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 5444 SelectionDAG &DAG) { 5445 if (cast<ConstantSDNode>(Step)->isZero()) 5446 return DAG.getConstant(0, DL, VT); 5447 5448 return SDValue(); 5449 } 5450 5451 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 5452 ArrayRef<SDValue> Ops, 5453 SelectionDAG &DAG) { 5454 int NumOps = Ops.size(); 5455 assert(NumOps != 0 && "Can't build an empty vector!"); 5456 assert(!VT.isScalableVector() && 5457 "BUILD_VECTOR cannot be used with scalable types"); 5458 assert(VT.getVectorNumElements() == (unsigned)NumOps && 5459 "Incorrect element count in BUILD_VECTOR!"); 5460 5461 // BUILD_VECTOR of UNDEFs is UNDEF. 5462 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 5463 return DAG.getUNDEF(VT); 5464 5465 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 5466 SDValue IdentitySrc; 5467 bool IsIdentity = true; 5468 for (int i = 0; i != NumOps; ++i) { 5469 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5470 Ops[i].getOperand(0).getValueType() != VT || 5471 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 5472 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 5473 Ops[i].getConstantOperandAPInt(1) != i) { 5474 IsIdentity = false; 5475 break; 5476 } 5477 IdentitySrc = Ops[i].getOperand(0); 5478 } 5479 if (IsIdentity) 5480 return IdentitySrc; 5481 5482 return SDValue(); 5483 } 5484 5485 /// Try to simplify vector concatenation to an input value, undef, or build 5486 /// vector. 5487 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 5488 ArrayRef<SDValue> Ops, 5489 SelectionDAG &DAG) { 5490 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 5491 assert(llvm::all_of(Ops, 5492 [Ops](SDValue Op) { 5493 return Ops[0].getValueType() == Op.getValueType(); 5494 }) && 5495 "Concatenation of vectors with inconsistent value types!"); 5496 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 5497 VT.getVectorElementCount() && 5498 "Incorrect element count in vector concatenation!"); 5499 5500 if (Ops.size() == 1) 5501 return Ops[0]; 5502 5503 // Concat of UNDEFs is UNDEF. 5504 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 5505 return DAG.getUNDEF(VT); 5506 5507 // Scan the operands and look for extract operations from a single source 5508 // that correspond to insertion at the same location via this concatenation: 5509 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 5510 SDValue IdentitySrc; 5511 bool IsIdentity = true; 5512 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 5513 SDValue Op = Ops[i]; 5514 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 5515 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 5516 Op.getOperand(0).getValueType() != VT || 5517 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 5518 Op.getConstantOperandVal(1) != IdentityIndex) { 5519 IsIdentity = false; 5520 break; 5521 } 5522 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 5523 "Unexpected identity source vector for concat of extracts"); 5524 IdentitySrc = Op.getOperand(0); 5525 } 5526 if (IsIdentity) { 5527 assert(IdentitySrc && "Failed to set source vector of extracts"); 5528 return IdentitySrc; 5529 } 5530 5531 // The code below this point is only designed to work for fixed width 5532 // vectors, so we bail out for now. 5533 if (VT.isScalableVector()) 5534 return SDValue(); 5535 5536 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 5537 // simplified to one big BUILD_VECTOR. 5538 // FIXME: Add support for SCALAR_TO_VECTOR as well. 5539 EVT SVT = VT.getScalarType(); 5540 SmallVector<SDValue, 16> Elts; 5541 for (SDValue Op : Ops) { 5542 EVT OpVT = Op.getValueType(); 5543 if (Op.isUndef()) 5544 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 5545 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 5546 Elts.append(Op->op_begin(), Op->op_end()); 5547 else 5548 return SDValue(); 5549 } 5550 5551 // BUILD_VECTOR requires all inputs to be of the same type, find the 5552 // maximum type and extend them all. 5553 for (SDValue Op : Elts) 5554 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 5555 5556 if (SVT.bitsGT(VT.getScalarType())) { 5557 for (SDValue &Op : Elts) { 5558 if (Op.isUndef()) 5559 Op = DAG.getUNDEF(SVT); 5560 else 5561 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 5562 ? DAG.getZExtOrTrunc(Op, DL, SVT) 5563 : DAG.getSExtOrTrunc(Op, DL, SVT); 5564 } 5565 } 5566 5567 SDValue V = DAG.getBuildVector(VT, DL, Elts); 5568 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 5569 return V; 5570 } 5571 5572 /// Gets or creates the specified node. 5573 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 5574 FoldingSetNodeID ID; 5575 AddNodeIDNode(ID, Opcode, getVTList(VT), std::nullopt); 5576 void *IP = nullptr; 5577 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5578 return SDValue(E, 0); 5579 5580 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 5581 getVTList(VT)); 5582 CSEMap.InsertNode(N, IP); 5583 5584 InsertNode(N); 5585 SDValue V = SDValue(N, 0); 5586 NewSDValueDbgMsg(V, "Creating new node: ", this); 5587 return V; 5588 } 5589 5590 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5591 SDValue N1) { 5592 SDNodeFlags Flags; 5593 if (Inserter) 5594 Flags = Inserter->getFlags(); 5595 return getNode(Opcode, DL, VT, N1, Flags); 5596 } 5597 5598 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5599 SDValue N1, const SDNodeFlags Flags) { 5600 assert(N1.getOpcode() != ISD::DELETED_NODE && "Operand is DELETED_NODE!"); 5601 5602 // Constant fold unary operations with a vector integer or float operand. 5603 switch (Opcode) { 5604 default: 5605 // FIXME: Entirely reasonable to perform folding of other unary 5606 // operations here as the need arises. 5607 break; 5608 case ISD::FNEG: 5609 case ISD::FABS: 5610 case ISD::FCEIL: 5611 case ISD::FTRUNC: 5612 case ISD::FFLOOR: 5613 case ISD::FP_EXTEND: 5614 case ISD::FP_TO_SINT: 5615 case ISD::FP_TO_UINT: 5616 case ISD::FP_TO_FP16: 5617 case ISD::FP_TO_BF16: 5618 case ISD::TRUNCATE: 5619 case ISD::ANY_EXTEND: 5620 case ISD::ZERO_EXTEND: 5621 case ISD::SIGN_EXTEND: 5622 case ISD::UINT_TO_FP: 5623 case ISD::SINT_TO_FP: 5624 case ISD::FP16_TO_FP: 5625 case ISD::BF16_TO_FP: 5626 case ISD::BITCAST: 5627 case ISD::ABS: 5628 case ISD::BITREVERSE: 5629 case ISD::BSWAP: 5630 case ISD::CTLZ: 5631 case ISD::CTLZ_ZERO_UNDEF: 5632 case ISD::CTTZ: 5633 case ISD::CTTZ_ZERO_UNDEF: 5634 case ISD::CTPOP: 5635 case ISD::STEP_VECTOR: { 5636 SDValue Ops = {N1}; 5637 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops)) 5638 return Fold; 5639 } 5640 } 5641 5642 unsigned OpOpcode = N1.getNode()->getOpcode(); 5643 switch (Opcode) { 5644 case ISD::STEP_VECTOR: 5645 assert(VT.isScalableVector() && 5646 "STEP_VECTOR can only be used with scalable types"); 5647 assert(OpOpcode == ISD::TargetConstant && 5648 VT.getVectorElementType() == N1.getValueType() && 5649 "Unexpected step operand"); 5650 break; 5651 case ISD::FREEZE: 5652 assert(VT == N1.getValueType() && "Unexpected VT!"); 5653 if (isGuaranteedNotToBeUndefOrPoison(N1, /*PoisonOnly*/ false, 5654 /*Depth*/ 1)) 5655 return N1; 5656 break; 5657 case ISD::TokenFactor: 5658 case ISD::MERGE_VALUES: 5659 case ISD::CONCAT_VECTORS: 5660 return N1; // Factor, merge or concat of one node? No need. 5661 case ISD::BUILD_VECTOR: { 5662 // Attempt to simplify BUILD_VECTOR. 5663 SDValue Ops[] = {N1}; 5664 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5665 return V; 5666 break; 5667 } 5668 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 5669 case ISD::FP_EXTEND: 5670 assert(VT.isFloatingPoint() && N1.getValueType().isFloatingPoint() && 5671 "Invalid FP cast!"); 5672 if (N1.getValueType() == VT) return N1; // noop conversion. 5673 assert((!VT.isVector() || VT.getVectorElementCount() == 5674 N1.getValueType().getVectorElementCount()) && 5675 "Vector element count mismatch!"); 5676 assert(N1.getValueType().bitsLT(VT) && "Invalid fpext node, dst < src!"); 5677 if (N1.isUndef()) 5678 return getUNDEF(VT); 5679 break; 5680 case ISD::FP_TO_SINT: 5681 case ISD::FP_TO_UINT: 5682 if (N1.isUndef()) 5683 return getUNDEF(VT); 5684 break; 5685 case ISD::SINT_TO_FP: 5686 case ISD::UINT_TO_FP: 5687 // [us]itofp(undef) = 0, because the result value is bounded. 5688 if (N1.isUndef()) 5689 return getConstantFP(0.0, DL, VT); 5690 break; 5691 case ISD::SIGN_EXTEND: 5692 assert(VT.isInteger() && N1.getValueType().isInteger() && 5693 "Invalid SIGN_EXTEND!"); 5694 assert(VT.isVector() == N1.getValueType().isVector() && 5695 "SIGN_EXTEND result type type should be vector iff the operand " 5696 "type is vector!"); 5697 if (N1.getValueType() == VT) return N1; // noop extension 5698 assert((!VT.isVector() || VT.getVectorElementCount() == 5699 N1.getValueType().getVectorElementCount()) && 5700 "Vector element count mismatch!"); 5701 assert(N1.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!"); 5702 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 5703 return getNode(OpOpcode, DL, VT, N1.getOperand(0)); 5704 if (OpOpcode == ISD::UNDEF) 5705 // sext(undef) = 0, because the top bits will all be the same. 5706 return getConstant(0, DL, VT); 5707 break; 5708 case ISD::ZERO_EXTEND: 5709 assert(VT.isInteger() && N1.getValueType().isInteger() && 5710 "Invalid ZERO_EXTEND!"); 5711 assert(VT.isVector() == N1.getValueType().isVector() && 5712 "ZERO_EXTEND result type type should be vector iff the operand " 5713 "type is vector!"); 5714 if (N1.getValueType() == VT) return N1; // noop extension 5715 assert((!VT.isVector() || VT.getVectorElementCount() == 5716 N1.getValueType().getVectorElementCount()) && 5717 "Vector element count mismatch!"); 5718 assert(N1.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!"); 5719 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 5720 return getNode(ISD::ZERO_EXTEND, DL, VT, N1.getOperand(0)); 5721 if (OpOpcode == ISD::UNDEF) 5722 // zext(undef) = 0, because the top bits will be zero. 5723 return getConstant(0, DL, VT); 5724 5725 // Skip unnecessary zext_inreg pattern: 5726 // (zext (trunc x)) -> x iff the upper bits are known zero. 5727 // TODO: Remove (zext (trunc (and x, c))) exception which some targets 5728 // use to recognise zext_inreg patterns. 5729 if (OpOpcode == ISD::TRUNCATE) { 5730 SDValue OpOp = N1.getOperand(0); 5731 if (OpOp.getValueType() == VT) { 5732 if (OpOp.getOpcode() != ISD::AND) { 5733 APInt HiBits = APInt::getBitsSetFrom(VT.getScalarSizeInBits(), 5734 N1.getScalarValueSizeInBits()); 5735 if (MaskedValueIsZero(OpOp, HiBits)) { 5736 transferDbgValues(N1, OpOp); 5737 return OpOp; 5738 } 5739 } 5740 } 5741 } 5742 break; 5743 case ISD::ANY_EXTEND: 5744 assert(VT.isInteger() && N1.getValueType().isInteger() && 5745 "Invalid ANY_EXTEND!"); 5746 assert(VT.isVector() == N1.getValueType().isVector() && 5747 "ANY_EXTEND result type type should be vector iff the operand " 5748 "type is vector!"); 5749 if (N1.getValueType() == VT) return N1; // noop extension 5750 assert((!VT.isVector() || VT.getVectorElementCount() == 5751 N1.getValueType().getVectorElementCount()) && 5752 "Vector element count mismatch!"); 5753 assert(N1.getValueType().bitsLT(VT) && "Invalid anyext node, dst < src!"); 5754 5755 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5756 OpOpcode == ISD::ANY_EXTEND) 5757 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 5758 return getNode(OpOpcode, DL, VT, N1.getOperand(0)); 5759 if (OpOpcode == ISD::UNDEF) 5760 return getUNDEF(VT); 5761 5762 // (ext (trunc x)) -> x 5763 if (OpOpcode == ISD::TRUNCATE) { 5764 SDValue OpOp = N1.getOperand(0); 5765 if (OpOp.getValueType() == VT) { 5766 transferDbgValues(N1, OpOp); 5767 return OpOp; 5768 } 5769 } 5770 break; 5771 case ISD::TRUNCATE: 5772 assert(VT.isInteger() && N1.getValueType().isInteger() && 5773 "Invalid TRUNCATE!"); 5774 assert(VT.isVector() == N1.getValueType().isVector() && 5775 "TRUNCATE result type type should be vector iff the operand " 5776 "type is vector!"); 5777 if (N1.getValueType() == VT) return N1; // noop truncate 5778 assert((!VT.isVector() || VT.getVectorElementCount() == 5779 N1.getValueType().getVectorElementCount()) && 5780 "Vector element count mismatch!"); 5781 assert(N1.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!"); 5782 if (OpOpcode == ISD::TRUNCATE) 5783 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0)); 5784 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5785 OpOpcode == ISD::ANY_EXTEND) { 5786 // If the source is smaller than the dest, we still need an extend. 5787 if (N1.getOperand(0).getValueType().getScalarType().bitsLT( 5788 VT.getScalarType())) 5789 return getNode(OpOpcode, DL, VT, N1.getOperand(0)); 5790 if (N1.getOperand(0).getValueType().bitsGT(VT)) 5791 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0)); 5792 return N1.getOperand(0); 5793 } 5794 if (OpOpcode == ISD::UNDEF) 5795 return getUNDEF(VT); 5796 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes) 5797 return getVScale(DL, VT, 5798 N1.getConstantOperandAPInt(0).trunc(VT.getSizeInBits())); 5799 break; 5800 case ISD::ANY_EXTEND_VECTOR_INREG: 5801 case ISD::ZERO_EXTEND_VECTOR_INREG: 5802 case ISD::SIGN_EXTEND_VECTOR_INREG: 5803 assert(VT.isVector() && "This DAG node is restricted to vector types."); 5804 assert(N1.getValueType().bitsLE(VT) && 5805 "The input must be the same size or smaller than the result."); 5806 assert(VT.getVectorMinNumElements() < 5807 N1.getValueType().getVectorMinNumElements() && 5808 "The destination vector type must have fewer lanes than the input."); 5809 break; 5810 case ISD::ABS: 5811 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid ABS!"); 5812 if (OpOpcode == ISD::UNDEF) 5813 return getConstant(0, DL, VT); 5814 break; 5815 case ISD::BSWAP: 5816 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BSWAP!"); 5817 assert((VT.getScalarSizeInBits() % 16 == 0) && 5818 "BSWAP types must be a multiple of 16 bits!"); 5819 if (OpOpcode == ISD::UNDEF) 5820 return getUNDEF(VT); 5821 // bswap(bswap(X)) -> X. 5822 if (OpOpcode == ISD::BSWAP) 5823 return N1.getOperand(0); 5824 break; 5825 case ISD::BITREVERSE: 5826 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BITREVERSE!"); 5827 if (OpOpcode == ISD::UNDEF) 5828 return getUNDEF(VT); 5829 break; 5830 case ISD::BITCAST: 5831 assert(VT.getSizeInBits() == N1.getValueSizeInBits() && 5832 "Cannot BITCAST between types of different sizes!"); 5833 if (VT == N1.getValueType()) return N1; // noop conversion. 5834 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 5835 return getNode(ISD::BITCAST, DL, VT, N1.getOperand(0)); 5836 if (OpOpcode == ISD::UNDEF) 5837 return getUNDEF(VT); 5838 break; 5839 case ISD::SCALAR_TO_VECTOR: 5840 assert(VT.isVector() && !N1.getValueType().isVector() && 5841 (VT.getVectorElementType() == N1.getValueType() || 5842 (VT.getVectorElementType().isInteger() && 5843 N1.getValueType().isInteger() && 5844 VT.getVectorElementType().bitsLE(N1.getValueType()))) && 5845 "Illegal SCALAR_TO_VECTOR node!"); 5846 if (OpOpcode == ISD::UNDEF) 5847 return getUNDEF(VT); 5848 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 5849 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 5850 isa<ConstantSDNode>(N1.getOperand(1)) && 5851 N1.getConstantOperandVal(1) == 0 && 5852 N1.getOperand(0).getValueType() == VT) 5853 return N1.getOperand(0); 5854 break; 5855 case ISD::FNEG: 5856 // Negation of an unknown bag of bits is still completely undefined. 5857 if (OpOpcode == ISD::UNDEF) 5858 return getUNDEF(VT); 5859 5860 if (OpOpcode == ISD::FNEG) // --X -> X 5861 return N1.getOperand(0); 5862 break; 5863 case ISD::FABS: 5864 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 5865 return getNode(ISD::FABS, DL, VT, N1.getOperand(0)); 5866 break; 5867 case ISD::VSCALE: 5868 assert(VT == N1.getValueType() && "Unexpected VT!"); 5869 break; 5870 case ISD::CTPOP: 5871 if (N1.getValueType().getScalarType() == MVT::i1) 5872 return N1; 5873 break; 5874 case ISD::CTLZ: 5875 case ISD::CTTZ: 5876 if (N1.getValueType().getScalarType() == MVT::i1) 5877 return getNOT(DL, N1, N1.getValueType()); 5878 break; 5879 case ISD::VECREDUCE_ADD: 5880 if (N1.getValueType().getScalarType() == MVT::i1) 5881 return getNode(ISD::VECREDUCE_XOR, DL, VT, N1); 5882 break; 5883 case ISD::VECREDUCE_SMIN: 5884 case ISD::VECREDUCE_UMAX: 5885 if (N1.getValueType().getScalarType() == MVT::i1) 5886 return getNode(ISD::VECREDUCE_OR, DL, VT, N1); 5887 break; 5888 case ISD::VECREDUCE_SMAX: 5889 case ISD::VECREDUCE_UMIN: 5890 if (N1.getValueType().getScalarType() == MVT::i1) 5891 return getNode(ISD::VECREDUCE_AND, DL, VT, N1); 5892 break; 5893 } 5894 5895 SDNode *N; 5896 SDVTList VTs = getVTList(VT); 5897 SDValue Ops[] = {N1}; 5898 if (VT != MVT::Glue) { // Don't CSE glue producing nodes 5899 FoldingSetNodeID ID; 5900 AddNodeIDNode(ID, Opcode, VTs, Ops); 5901 void *IP = nullptr; 5902 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5903 E->intersectFlagsWith(Flags); 5904 return SDValue(E, 0); 5905 } 5906 5907 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5908 N->setFlags(Flags); 5909 createOperands(N, Ops); 5910 CSEMap.InsertNode(N, IP); 5911 } else { 5912 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5913 createOperands(N, Ops); 5914 } 5915 5916 InsertNode(N); 5917 SDValue V = SDValue(N, 0); 5918 NewSDValueDbgMsg(V, "Creating new node: ", this); 5919 return V; 5920 } 5921 5922 static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5923 const APInt &C2) { 5924 switch (Opcode) { 5925 case ISD::ADD: return C1 + C2; 5926 case ISD::SUB: return C1 - C2; 5927 case ISD::MUL: return C1 * C2; 5928 case ISD::AND: return C1 & C2; 5929 case ISD::OR: return C1 | C2; 5930 case ISD::XOR: return C1 ^ C2; 5931 case ISD::SHL: return C1 << C2; 5932 case ISD::SRL: return C1.lshr(C2); 5933 case ISD::SRA: return C1.ashr(C2); 5934 case ISD::ROTL: return C1.rotl(C2); 5935 case ISD::ROTR: return C1.rotr(C2); 5936 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5937 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5938 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5939 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5940 case ISD::SADDSAT: return C1.sadd_sat(C2); 5941 case ISD::UADDSAT: return C1.uadd_sat(C2); 5942 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5943 case ISD::USUBSAT: return C1.usub_sat(C2); 5944 case ISD::SSHLSAT: return C1.sshl_sat(C2); 5945 case ISD::USHLSAT: return C1.ushl_sat(C2); 5946 case ISD::UDIV: 5947 if (!C2.getBoolValue()) 5948 break; 5949 return C1.udiv(C2); 5950 case ISD::UREM: 5951 if (!C2.getBoolValue()) 5952 break; 5953 return C1.urem(C2); 5954 case ISD::SDIV: 5955 if (!C2.getBoolValue()) 5956 break; 5957 return C1.sdiv(C2); 5958 case ISD::SREM: 5959 if (!C2.getBoolValue()) 5960 break; 5961 return C1.srem(C2); 5962 case ISD::MULHS: { 5963 unsigned FullWidth = C1.getBitWidth() * 2; 5964 APInt C1Ext = C1.sext(FullWidth); 5965 APInt C2Ext = C2.sext(FullWidth); 5966 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5967 } 5968 case ISD::MULHU: { 5969 unsigned FullWidth = C1.getBitWidth() * 2; 5970 APInt C1Ext = C1.zext(FullWidth); 5971 APInt C2Ext = C2.zext(FullWidth); 5972 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5973 } 5974 case ISD::AVGFLOORS: { 5975 unsigned FullWidth = C1.getBitWidth() + 1; 5976 APInt C1Ext = C1.sext(FullWidth); 5977 APInt C2Ext = C2.sext(FullWidth); 5978 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5979 } 5980 case ISD::AVGFLOORU: { 5981 unsigned FullWidth = C1.getBitWidth() + 1; 5982 APInt C1Ext = C1.zext(FullWidth); 5983 APInt C2Ext = C2.zext(FullWidth); 5984 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5985 } 5986 case ISD::AVGCEILS: { 5987 unsigned FullWidth = C1.getBitWidth() + 1; 5988 APInt C1Ext = C1.sext(FullWidth); 5989 APInt C2Ext = C2.sext(FullWidth); 5990 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5991 } 5992 case ISD::AVGCEILU: { 5993 unsigned FullWidth = C1.getBitWidth() + 1; 5994 APInt C1Ext = C1.zext(FullWidth); 5995 APInt C2Ext = C2.zext(FullWidth); 5996 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5997 } 5998 case ISD::ABDS: 5999 return APIntOps::smax(C1, C2) - APIntOps::smin(C1, C2); 6000 case ISD::ABDU: 6001 return APIntOps::umax(C1, C2) - APIntOps::umin(C1, C2); 6002 } 6003 return std::nullopt; 6004 } 6005 6006 // Handle constant folding with UNDEF. 6007 // TODO: Handle more cases. 6008 static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1, 6009 bool IsUndef1, const APInt &C2, 6010 bool IsUndef2) { 6011 if (!(IsUndef1 || IsUndef2)) 6012 return FoldValue(Opcode, C1, C2); 6013 6014 // Fold and(x, undef) -> 0 6015 // Fold mul(x, undef) -> 0 6016 if (Opcode == ISD::AND || Opcode == ISD::MUL) 6017 return APInt::getZero(C1.getBitWidth()); 6018 6019 return std::nullopt; 6020 } 6021 6022 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 6023 const GlobalAddressSDNode *GA, 6024 const SDNode *N2) { 6025 if (GA->getOpcode() != ISD::GlobalAddress) 6026 return SDValue(); 6027 if (!TLI->isOffsetFoldingLegal(GA)) 6028 return SDValue(); 6029 auto *C2 = dyn_cast<ConstantSDNode>(N2); 6030 if (!C2) 6031 return SDValue(); 6032 int64_t Offset = C2->getSExtValue(); 6033 switch (Opcode) { 6034 case ISD::ADD: break; 6035 case ISD::SUB: Offset = -uint64_t(Offset); break; 6036 default: return SDValue(); 6037 } 6038 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 6039 GA->getOffset() + uint64_t(Offset)); 6040 } 6041 6042 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 6043 switch (Opcode) { 6044 case ISD::SDIV: 6045 case ISD::UDIV: 6046 case ISD::SREM: 6047 case ISD::UREM: { 6048 // If a divisor is zero/undef or any element of a divisor vector is 6049 // zero/undef, the whole op is undef. 6050 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 6051 SDValue Divisor = Ops[1]; 6052 if (Divisor.isUndef() || isNullConstant(Divisor)) 6053 return true; 6054 6055 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 6056 llvm::any_of(Divisor->op_values(), 6057 [](SDValue V) { return V.isUndef() || 6058 isNullConstant(V); }); 6059 // TODO: Handle signed overflow. 6060 } 6061 // TODO: Handle oversized shifts. 6062 default: 6063 return false; 6064 } 6065 } 6066 6067 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 6068 EVT VT, ArrayRef<SDValue> Ops) { 6069 // If the opcode is a target-specific ISD node, there's nothing we can 6070 // do here and the operand rules may not line up with the below, so 6071 // bail early. 6072 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 6073 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 6074 // foldCONCAT_VECTORS in getNode before this is called. 6075 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 6076 return SDValue(); 6077 6078 unsigned NumOps = Ops.size(); 6079 if (NumOps == 0) 6080 return SDValue(); 6081 6082 if (isUndef(Opcode, Ops)) 6083 return getUNDEF(VT); 6084 6085 // Handle unary special cases. 6086 if (NumOps == 1) { 6087 SDValue N1 = Ops[0]; 6088 6089 // Constant fold unary operations with an integer constant operand. Even 6090 // opaque constant will be folded, because the folding of unary operations 6091 // doesn't create new constants with different values. Nevertheless, the 6092 // opaque flag is preserved during folding to prevent future folding with 6093 // other constants. 6094 if (auto *C = dyn_cast<ConstantSDNode>(N1)) { 6095 const APInt &Val = C->getAPIntValue(); 6096 switch (Opcode) { 6097 case ISD::SIGN_EXTEND: 6098 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 6099 C->isTargetOpcode(), C->isOpaque()); 6100 case ISD::TRUNCATE: 6101 if (C->isOpaque()) 6102 break; 6103 [[fallthrough]]; 6104 case ISD::ZERO_EXTEND: 6105 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 6106 C->isTargetOpcode(), C->isOpaque()); 6107 case ISD::ANY_EXTEND: 6108 // Some targets like RISCV prefer to sign extend some types. 6109 if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT)) 6110 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 6111 C->isTargetOpcode(), C->isOpaque()); 6112 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 6113 C->isTargetOpcode(), C->isOpaque()); 6114 case ISD::ABS: 6115 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 6116 C->isOpaque()); 6117 case ISD::BITREVERSE: 6118 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 6119 C->isOpaque()); 6120 case ISD::BSWAP: 6121 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 6122 C->isOpaque()); 6123 case ISD::CTPOP: 6124 return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(), 6125 C->isOpaque()); 6126 case ISD::CTLZ: 6127 case ISD::CTLZ_ZERO_UNDEF: 6128 return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(), 6129 C->isOpaque()); 6130 case ISD::CTTZ: 6131 case ISD::CTTZ_ZERO_UNDEF: 6132 return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(), 6133 C->isOpaque()); 6134 case ISD::UINT_TO_FP: 6135 case ISD::SINT_TO_FP: { 6136 APFloat apf(EVTToAPFloatSemantics(VT), 6137 APInt::getZero(VT.getSizeInBits())); 6138 (void)apf.convertFromAPInt(Val, Opcode == ISD::SINT_TO_FP, 6139 APFloat::rmNearestTiesToEven); 6140 return getConstantFP(apf, DL, VT); 6141 } 6142 case ISD::FP16_TO_FP: 6143 case ISD::BF16_TO_FP: { 6144 bool Ignored; 6145 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf() 6146 : APFloat::BFloat(), 6147 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 6148 6149 // This can return overflow, underflow, or inexact; we don't care. 6150 // FIXME need to be more flexible about rounding mode. 6151 (void)FPV.convert(EVTToAPFloatSemantics(VT), 6152 APFloat::rmNearestTiesToEven, &Ignored); 6153 return getConstantFP(FPV, DL, VT); 6154 } 6155 case ISD::STEP_VECTOR: 6156 if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this)) 6157 return V; 6158 break; 6159 case ISD::BITCAST: 6160 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 6161 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 6162 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 6163 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 6164 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 6165 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 6166 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 6167 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 6168 break; 6169 } 6170 } 6171 6172 // Constant fold unary operations with a floating point constant operand. 6173 if (auto *C = dyn_cast<ConstantFPSDNode>(N1)) { 6174 APFloat V = C->getValueAPF(); // make copy 6175 switch (Opcode) { 6176 case ISD::FNEG: 6177 V.changeSign(); 6178 return getConstantFP(V, DL, VT); 6179 case ISD::FABS: 6180 V.clearSign(); 6181 return getConstantFP(V, DL, VT); 6182 case ISD::FCEIL: { 6183 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 6184 if (fs == APFloat::opOK || fs == APFloat::opInexact) 6185 return getConstantFP(V, DL, VT); 6186 return SDValue(); 6187 } 6188 case ISD::FTRUNC: { 6189 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 6190 if (fs == APFloat::opOK || fs == APFloat::opInexact) 6191 return getConstantFP(V, DL, VT); 6192 return SDValue(); 6193 } 6194 case ISD::FFLOOR: { 6195 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 6196 if (fs == APFloat::opOK || fs == APFloat::opInexact) 6197 return getConstantFP(V, DL, VT); 6198 return SDValue(); 6199 } 6200 case ISD::FP_EXTEND: { 6201 bool ignored; 6202 // This can return overflow, underflow, or inexact; we don't care. 6203 // FIXME need to be more flexible about rounding mode. 6204 (void)V.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 6205 &ignored); 6206 return getConstantFP(V, DL, VT); 6207 } 6208 case ISD::FP_TO_SINT: 6209 case ISD::FP_TO_UINT: { 6210 bool ignored; 6211 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 6212 // FIXME need to be more flexible about rounding mode. 6213 APFloat::opStatus s = 6214 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 6215 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 6216 break; 6217 return getConstant(IntVal, DL, VT); 6218 } 6219 case ISD::FP_TO_FP16: 6220 case ISD::FP_TO_BF16: { 6221 bool Ignored; 6222 // This can return overflow, underflow, or inexact; we don't care. 6223 // FIXME need to be more flexible about rounding mode. 6224 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf() 6225 : APFloat::BFloat(), 6226 APFloat::rmNearestTiesToEven, &Ignored); 6227 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 6228 } 6229 case ISD::BITCAST: 6230 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 6231 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, 6232 VT); 6233 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16) 6234 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, 6235 VT); 6236 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 6237 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, 6238 VT); 6239 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 6240 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 6241 break; 6242 } 6243 } 6244 6245 // Early-out if we failed to constant fold a bitcast. 6246 if (Opcode == ISD::BITCAST) 6247 return SDValue(); 6248 } 6249 6250 // Handle binops special cases. 6251 if (NumOps == 2) { 6252 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops)) 6253 return CFP; 6254 6255 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) { 6256 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) { 6257 if (C1->isOpaque() || C2->isOpaque()) 6258 return SDValue(); 6259 6260 std::optional<APInt> FoldAttempt = 6261 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 6262 if (!FoldAttempt) 6263 return SDValue(); 6264 6265 SDValue Folded = getConstant(*FoldAttempt, DL, VT); 6266 assert((!Folded || !VT.isVector()) && 6267 "Can't fold vectors ops with scalar operands"); 6268 return Folded; 6269 } 6270 } 6271 6272 // fold (add Sym, c) -> Sym+c 6273 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0])) 6274 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode()); 6275 if (TLI->isCommutativeBinOp(Opcode)) 6276 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1])) 6277 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode()); 6278 } 6279 6280 // This is for vector folding only from here on. 6281 if (!VT.isVector()) 6282 return SDValue(); 6283 6284 ElementCount NumElts = VT.getVectorElementCount(); 6285 6286 // See if we can fold through bitcasted integer ops. 6287 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() && 6288 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT && 6289 Ops[0].getOpcode() == ISD::BITCAST && 6290 Ops[1].getOpcode() == ISD::BITCAST) { 6291 SDValue N1 = peekThroughBitcasts(Ops[0]); 6292 SDValue N2 = peekThroughBitcasts(Ops[1]); 6293 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 6294 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 6295 EVT BVVT = N1.getValueType(); 6296 if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) { 6297 bool IsLE = getDataLayout().isLittleEndian(); 6298 unsigned EltBits = VT.getScalarSizeInBits(); 6299 SmallVector<APInt> RawBits1, RawBits2; 6300 BitVector UndefElts1, UndefElts2; 6301 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) && 6302 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) { 6303 SmallVector<APInt> RawBits; 6304 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) { 6305 std::optional<APInt> Fold = FoldValueWithUndef( 6306 Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]); 6307 if (!Fold) 6308 break; 6309 RawBits.push_back(*Fold); 6310 } 6311 if (RawBits.size() == NumElts.getFixedValue()) { 6312 // We have constant folded, but we need to cast this again back to 6313 // the original (possibly legalized) type. 6314 SmallVector<APInt> DstBits; 6315 BitVector DstUndefs; 6316 BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(), 6317 DstBits, RawBits, DstUndefs, 6318 BitVector(RawBits.size(), false)); 6319 EVT BVEltVT = BV1->getOperand(0).getValueType(); 6320 unsigned BVEltBits = BVEltVT.getSizeInBits(); 6321 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT)); 6322 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) { 6323 if (DstUndefs[I]) 6324 continue; 6325 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT); 6326 } 6327 return getBitcast(VT, getBuildVector(BVVT, DL, Ops)); 6328 } 6329 } 6330 } 6331 } 6332 6333 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)). 6334 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1)) 6335 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) && 6336 Ops[0].getOpcode() == ISD::STEP_VECTOR) { 6337 APInt RHSVal; 6338 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) { 6339 APInt NewStep = Opcode == ISD::MUL 6340 ? Ops[0].getConstantOperandAPInt(0) * RHSVal 6341 : Ops[0].getConstantOperandAPInt(0) << RHSVal; 6342 return getStepVector(DL, VT, NewStep); 6343 } 6344 } 6345 6346 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) { 6347 return !Op.getValueType().isVector() || 6348 Op.getValueType().getVectorElementCount() == NumElts; 6349 }; 6350 6351 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) { 6352 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE || 6353 Op.getOpcode() == ISD::BUILD_VECTOR || 6354 Op.getOpcode() == ISD::SPLAT_VECTOR; 6355 }; 6356 6357 // All operands must be vector types with the same number of elements as 6358 // the result type and must be either UNDEF or a build/splat vector 6359 // or UNDEF scalars. 6360 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) || 6361 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 6362 return SDValue(); 6363 6364 // If we are comparing vectors, then the result needs to be a i1 boolean that 6365 // is then extended back to the legal result type depending on how booleans 6366 // are represented. 6367 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 6368 ISD::NodeType ExtendCode = 6369 (Opcode == ISD::SETCC && SVT != VT.getScalarType()) 6370 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT)) 6371 : ISD::SIGN_EXTEND; 6372 6373 // Find legal integer scalar type for constant promotion and 6374 // ensure that its scalar size is at least as large as source. 6375 EVT LegalSVT = VT.getScalarType(); 6376 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 6377 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 6378 if (LegalSVT.bitsLT(VT.getScalarType())) 6379 return SDValue(); 6380 } 6381 6382 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We 6383 // only have one operand to check. For fixed-length vector types we may have 6384 // a combination of BUILD_VECTOR and SPLAT_VECTOR. 6385 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue(); 6386 6387 // Constant fold each scalar lane separately. 6388 SmallVector<SDValue, 4> ScalarResults; 6389 for (unsigned I = 0; I != NumVectorElts; I++) { 6390 SmallVector<SDValue, 4> ScalarOps; 6391 for (SDValue Op : Ops) { 6392 EVT InSVT = Op.getValueType().getScalarType(); 6393 if (Op.getOpcode() != ISD::BUILD_VECTOR && 6394 Op.getOpcode() != ISD::SPLAT_VECTOR) { 6395 if (Op.isUndef()) 6396 ScalarOps.push_back(getUNDEF(InSVT)); 6397 else 6398 ScalarOps.push_back(Op); 6399 continue; 6400 } 6401 6402 SDValue ScalarOp = 6403 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I); 6404 EVT ScalarVT = ScalarOp.getValueType(); 6405 6406 // Build vector (integer) scalar operands may need implicit 6407 // truncation - do this before constant folding. 6408 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) { 6409 // Don't create illegally-typed nodes unless they're constants or undef 6410 // - if we fail to constant fold we can't guarantee the (dead) nodes 6411 // we're creating will be cleaned up before being visited for 6412 // legalization. 6413 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() && 6414 !isa<ConstantSDNode>(ScalarOp) && 6415 TLI->getTypeAction(*getContext(), InSVT) != 6416 TargetLowering::TypeLegal) 6417 return SDValue(); 6418 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 6419 } 6420 6421 ScalarOps.push_back(ScalarOp); 6422 } 6423 6424 // Constant fold the scalar operands. 6425 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps); 6426 6427 // Legalize the (integer) scalar constant if necessary. 6428 if (LegalSVT != SVT) 6429 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult); 6430 6431 // Scalar folding only succeeded if the result is a constant or UNDEF. 6432 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 6433 ScalarResult.getOpcode() != ISD::ConstantFP) 6434 return SDValue(); 6435 ScalarResults.push_back(ScalarResult); 6436 } 6437 6438 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0]) 6439 : getBuildVector(VT, DL, ScalarResults); 6440 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 6441 return V; 6442 } 6443 6444 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 6445 EVT VT, ArrayRef<SDValue> Ops) { 6446 // TODO: Add support for unary/ternary fp opcodes. 6447 if (Ops.size() != 2) 6448 return SDValue(); 6449 6450 // TODO: We don't do any constant folding for strict FP opcodes here, but we 6451 // should. That will require dealing with a potentially non-default 6452 // rounding mode, checking the "opStatus" return value from the APFloat 6453 // math calculations, and possibly other variations. 6454 SDValue N1 = Ops[0]; 6455 SDValue N2 = Ops[1]; 6456 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false); 6457 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false); 6458 if (N1CFP && N2CFP) { 6459 APFloat C1 = N1CFP->getValueAPF(); // make copy 6460 const APFloat &C2 = N2CFP->getValueAPF(); 6461 switch (Opcode) { 6462 case ISD::FADD: 6463 C1.add(C2, APFloat::rmNearestTiesToEven); 6464 return getConstantFP(C1, DL, VT); 6465 case ISD::FSUB: 6466 C1.subtract(C2, APFloat::rmNearestTiesToEven); 6467 return getConstantFP(C1, DL, VT); 6468 case ISD::FMUL: 6469 C1.multiply(C2, APFloat::rmNearestTiesToEven); 6470 return getConstantFP(C1, DL, VT); 6471 case ISD::FDIV: 6472 C1.divide(C2, APFloat::rmNearestTiesToEven); 6473 return getConstantFP(C1, DL, VT); 6474 case ISD::FREM: 6475 C1.mod(C2); 6476 return getConstantFP(C1, DL, VT); 6477 case ISD::FCOPYSIGN: 6478 C1.copySign(C2); 6479 return getConstantFP(C1, DL, VT); 6480 case ISD::FMINNUM: 6481 return getConstantFP(minnum(C1, C2), DL, VT); 6482 case ISD::FMAXNUM: 6483 return getConstantFP(maxnum(C1, C2), DL, VT); 6484 case ISD::FMINIMUM: 6485 return getConstantFP(minimum(C1, C2), DL, VT); 6486 case ISD::FMAXIMUM: 6487 return getConstantFP(maximum(C1, C2), DL, VT); 6488 default: break; 6489 } 6490 } 6491 if (N1CFP && Opcode == ISD::FP_ROUND) { 6492 APFloat C1 = N1CFP->getValueAPF(); // make copy 6493 bool Unused; 6494 // This can return overflow, underflow, or inexact; we don't care. 6495 // FIXME need to be more flexible about rounding mode. 6496 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 6497 &Unused); 6498 return getConstantFP(C1, DL, VT); 6499 } 6500 6501 switch (Opcode) { 6502 case ISD::FSUB: 6503 // -0.0 - undef --> undef (consistent with "fneg undef") 6504 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true)) 6505 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef()) 6506 return getUNDEF(VT); 6507 [[fallthrough]]; 6508 6509 case ISD::FADD: 6510 case ISD::FMUL: 6511 case ISD::FDIV: 6512 case ISD::FREM: 6513 // If both operands are undef, the result is undef. If 1 operand is undef, 6514 // the result is NaN. This should match the behavior of the IR optimizer. 6515 if (N1.isUndef() && N2.isUndef()) 6516 return getUNDEF(VT); 6517 if (N1.isUndef() || N2.isUndef()) 6518 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 6519 } 6520 return SDValue(); 6521 } 6522 6523 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 6524 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 6525 6526 // There's no need to assert on a byte-aligned pointer. All pointers are at 6527 // least byte aligned. 6528 if (A == Align(1)) 6529 return Val; 6530 6531 FoldingSetNodeID ID; 6532 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 6533 ID.AddInteger(A.value()); 6534 6535 void *IP = nullptr; 6536 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 6537 return SDValue(E, 0); 6538 6539 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 6540 Val.getValueType(), A); 6541 createOperands(N, {Val}); 6542 6543 CSEMap.InsertNode(N, IP); 6544 InsertNode(N); 6545 6546 SDValue V(N, 0); 6547 NewSDValueDbgMsg(V, "Creating new node: ", this); 6548 return V; 6549 } 6550 6551 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6552 SDValue N1, SDValue N2) { 6553 SDNodeFlags Flags; 6554 if (Inserter) 6555 Flags = Inserter->getFlags(); 6556 return getNode(Opcode, DL, VT, N1, N2, Flags); 6557 } 6558 6559 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1, 6560 SDValue &N2) const { 6561 if (!TLI->isCommutativeBinOp(Opcode)) 6562 return; 6563 6564 // Canonicalize: 6565 // binop(const, nonconst) -> binop(nonconst, const) 6566 SDNode *N1C = isConstantIntBuildVectorOrConstantInt(N1); 6567 SDNode *N2C = isConstantIntBuildVectorOrConstantInt(N2); 6568 SDNode *N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 6569 SDNode *N2CFP = isConstantFPBuildVectorOrConstantFP(N2); 6570 if ((N1C && !N2C) || (N1CFP && !N2CFP)) 6571 std::swap(N1, N2); 6572 6573 // Canonicalize: 6574 // binop(splat(x), step_vector) -> binop(step_vector, splat(x)) 6575 else if (N1.getOpcode() == ISD::SPLAT_VECTOR && 6576 N2.getOpcode() == ISD::STEP_VECTOR) 6577 std::swap(N1, N2); 6578 } 6579 6580 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6581 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 6582 assert(N1.getOpcode() != ISD::DELETED_NODE && 6583 N2.getOpcode() != ISD::DELETED_NODE && 6584 "Operand is DELETED_NODE!"); 6585 6586 canonicalizeCommutativeBinop(Opcode, N1, N2); 6587 6588 auto *N1C = dyn_cast<ConstantSDNode>(N1); 6589 auto *N2C = dyn_cast<ConstantSDNode>(N2); 6590 6591 // Don't allow undefs in vector splats - we might be returning N2 when folding 6592 // to zero etc. 6593 ConstantSDNode *N2CV = 6594 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true); 6595 6596 switch (Opcode) { 6597 default: break; 6598 case ISD::TokenFactor: 6599 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 6600 N2.getValueType() == MVT::Other && "Invalid token factor!"); 6601 // Fold trivial token factors. 6602 if (N1.getOpcode() == ISD::EntryToken) return N2; 6603 if (N2.getOpcode() == ISD::EntryToken) return N1; 6604 if (N1 == N2) return N1; 6605 break; 6606 case ISD::BUILD_VECTOR: { 6607 // Attempt to simplify BUILD_VECTOR. 6608 SDValue Ops[] = {N1, N2}; 6609 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6610 return V; 6611 break; 6612 } 6613 case ISD::CONCAT_VECTORS: { 6614 SDValue Ops[] = {N1, N2}; 6615 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6616 return V; 6617 break; 6618 } 6619 case ISD::AND: 6620 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6621 assert(N1.getValueType() == N2.getValueType() && 6622 N1.getValueType() == VT && "Binary operator types must match!"); 6623 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 6624 // worth handling here. 6625 if (N2CV && N2CV->isZero()) 6626 return N2; 6627 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X 6628 return N1; 6629 break; 6630 case ISD::OR: 6631 case ISD::XOR: 6632 case ISD::ADD: 6633 case ISD::SUB: 6634 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6635 assert(N1.getValueType() == N2.getValueType() && 6636 N1.getValueType() == VT && "Binary operator types must match!"); 6637 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 6638 // it's worth handling here. 6639 if (N2CV && N2CV->isZero()) 6640 return N1; 6641 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 6642 VT.getVectorElementType() == MVT::i1) 6643 return getNode(ISD::XOR, DL, VT, N1, N2); 6644 break; 6645 case ISD::MUL: 6646 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6647 assert(N1.getValueType() == N2.getValueType() && 6648 N1.getValueType() == VT && "Binary operator types must match!"); 6649 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 6650 return getNode(ISD::AND, DL, VT, N1, N2); 6651 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 6652 const APInt &MulImm = N1->getConstantOperandAPInt(0); 6653 const APInt &N2CImm = N2C->getAPIntValue(); 6654 return getVScale(DL, VT, MulImm * N2CImm); 6655 } 6656 break; 6657 case ISD::UDIV: 6658 case ISD::UREM: 6659 case ISD::MULHU: 6660 case ISD::MULHS: 6661 case ISD::SDIV: 6662 case ISD::SREM: 6663 case ISD::SADDSAT: 6664 case ISD::SSUBSAT: 6665 case ISD::UADDSAT: 6666 case ISD::USUBSAT: 6667 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6668 assert(N1.getValueType() == N2.getValueType() && 6669 N1.getValueType() == VT && "Binary operator types must match!"); 6670 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 6671 // fold (add_sat x, y) -> (or x, y) for bool types. 6672 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 6673 return getNode(ISD::OR, DL, VT, N1, N2); 6674 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 6675 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 6676 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 6677 } 6678 break; 6679 case ISD::ABDS: 6680 case ISD::ABDU: 6681 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6682 assert(N1.getValueType() == N2.getValueType() && 6683 N1.getValueType() == VT && "Binary operator types must match!"); 6684 break; 6685 case ISD::SMIN: 6686 case ISD::UMAX: 6687 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6688 assert(N1.getValueType() == N2.getValueType() && 6689 N1.getValueType() == VT && "Binary operator types must match!"); 6690 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 6691 return getNode(ISD::OR, DL, VT, N1, N2); 6692 break; 6693 case ISD::SMAX: 6694 case ISD::UMIN: 6695 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6696 assert(N1.getValueType() == N2.getValueType() && 6697 N1.getValueType() == VT && "Binary operator types must match!"); 6698 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 6699 return getNode(ISD::AND, DL, VT, N1, N2); 6700 break; 6701 case ISD::FADD: 6702 case ISD::FSUB: 6703 case ISD::FMUL: 6704 case ISD::FDIV: 6705 case ISD::FREM: 6706 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6707 assert(N1.getValueType() == N2.getValueType() && 6708 N1.getValueType() == VT && "Binary operator types must match!"); 6709 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 6710 return V; 6711 break; 6712 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 6713 assert(N1.getValueType() == VT && 6714 N1.getValueType().isFloatingPoint() && 6715 N2.getValueType().isFloatingPoint() && 6716 "Invalid FCOPYSIGN!"); 6717 break; 6718 case ISD::SHL: 6719 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 6720 const APInt &MulImm = N1->getConstantOperandAPInt(0); 6721 const APInt &ShiftImm = N2C->getAPIntValue(); 6722 return getVScale(DL, VT, MulImm << ShiftImm); 6723 } 6724 [[fallthrough]]; 6725 case ISD::SRA: 6726 case ISD::SRL: 6727 if (SDValue V = simplifyShift(N1, N2)) 6728 return V; 6729 [[fallthrough]]; 6730 case ISD::ROTL: 6731 case ISD::ROTR: 6732 assert(VT == N1.getValueType() && 6733 "Shift operators return type must be the same as their first arg"); 6734 assert(VT.isInteger() && N2.getValueType().isInteger() && 6735 "Shifts only work on integers"); 6736 assert((!VT.isVector() || VT == N2.getValueType()) && 6737 "Vector shift amounts must be in the same as their first arg"); 6738 // Verify that the shift amount VT is big enough to hold valid shift 6739 // amounts. This catches things like trying to shift an i1024 value by an 6740 // i8, which is easy to fall into in generic code that uses 6741 // TLI.getShiftAmount(). 6742 assert(N2.getValueType().getScalarSizeInBits() >= 6743 Log2_32_Ceil(VT.getScalarSizeInBits()) && 6744 "Invalid use of small shift amount with oversized value!"); 6745 6746 // Always fold shifts of i1 values so the code generator doesn't need to 6747 // handle them. Since we know the size of the shift has to be less than the 6748 // size of the value, the shift/rotate count is guaranteed to be zero. 6749 if (VT == MVT::i1) 6750 return N1; 6751 if (N2CV && N2CV->isZero()) 6752 return N1; 6753 break; 6754 case ISD::FP_ROUND: 6755 assert(VT.isFloatingPoint() && 6756 N1.getValueType().isFloatingPoint() && 6757 VT.bitsLE(N1.getValueType()) && 6758 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 6759 "Invalid FP_ROUND!"); 6760 if (N1.getValueType() == VT) return N1; // noop conversion. 6761 break; 6762 case ISD::AssertSext: 6763 case ISD::AssertZext: { 6764 EVT EVT = cast<VTSDNode>(N2)->getVT(); 6765 assert(VT == N1.getValueType() && "Not an inreg extend!"); 6766 assert(VT.isInteger() && EVT.isInteger() && 6767 "Cannot *_EXTEND_INREG FP types"); 6768 assert(!EVT.isVector() && 6769 "AssertSExt/AssertZExt type should be the vector element type " 6770 "rather than the vector type!"); 6771 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 6772 if (VT.getScalarType() == EVT) return N1; // noop assertion. 6773 break; 6774 } 6775 case ISD::SIGN_EXTEND_INREG: { 6776 EVT EVT = cast<VTSDNode>(N2)->getVT(); 6777 assert(VT == N1.getValueType() && "Not an inreg extend!"); 6778 assert(VT.isInteger() && EVT.isInteger() && 6779 "Cannot *_EXTEND_INREG FP types"); 6780 assert(EVT.isVector() == VT.isVector() && 6781 "SIGN_EXTEND_INREG type should be vector iff the operand " 6782 "type is vector!"); 6783 assert((!EVT.isVector() || 6784 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 6785 "Vector element counts must match in SIGN_EXTEND_INREG"); 6786 assert(EVT.bitsLE(VT) && "Not extending!"); 6787 if (EVT == VT) return N1; // Not actually extending 6788 6789 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 6790 unsigned FromBits = EVT.getScalarSizeInBits(); 6791 Val <<= Val.getBitWidth() - FromBits; 6792 Val.ashrInPlace(Val.getBitWidth() - FromBits); 6793 return getConstant(Val, DL, ConstantVT); 6794 }; 6795 6796 if (N1C) { 6797 const APInt &Val = N1C->getAPIntValue(); 6798 return SignExtendInReg(Val, VT); 6799 } 6800 6801 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 6802 SmallVector<SDValue, 8> Ops; 6803 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 6804 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 6805 SDValue Op = N1.getOperand(i); 6806 if (Op.isUndef()) { 6807 Ops.push_back(getUNDEF(OpVT)); 6808 continue; 6809 } 6810 ConstantSDNode *C = cast<ConstantSDNode>(Op); 6811 APInt Val = C->getAPIntValue(); 6812 Ops.push_back(SignExtendInReg(Val, OpVT)); 6813 } 6814 return getBuildVector(VT, DL, Ops); 6815 } 6816 6817 if (N1.getOpcode() == ISD::SPLAT_VECTOR && 6818 isa<ConstantSDNode>(N1.getOperand(0))) 6819 return getNode( 6820 ISD::SPLAT_VECTOR, DL, VT, 6821 SignExtendInReg(N1.getConstantOperandAPInt(0), 6822 N1.getOperand(0).getValueType())); 6823 break; 6824 } 6825 case ISD::FP_TO_SINT_SAT: 6826 case ISD::FP_TO_UINT_SAT: { 6827 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 6828 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 6829 assert(N1.getValueType().isVector() == VT.isVector() && 6830 "FP_TO_*INT_SAT type should be vector iff the operand type is " 6831 "vector!"); 6832 assert((!VT.isVector() || VT.getVectorElementCount() == 6833 N1.getValueType().getVectorElementCount()) && 6834 "Vector element counts must match in FP_TO_*INT_SAT"); 6835 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 6836 "Type to saturate to must be a scalar."); 6837 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 6838 "Not extending!"); 6839 break; 6840 } 6841 case ISD::EXTRACT_VECTOR_ELT: 6842 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 6843 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 6844 element type of the vector."); 6845 6846 // Extract from an undefined value or using an undefined index is undefined. 6847 if (N1.isUndef() || N2.isUndef()) 6848 return getUNDEF(VT); 6849 6850 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 6851 // vectors. For scalable vectors we will provide appropriate support for 6852 // dealing with arbitrary indices. 6853 if (N2C && N1.getValueType().isFixedLengthVector() && 6854 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 6855 return getUNDEF(VT); 6856 6857 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 6858 // expanding copies of large vectors from registers. This only works for 6859 // fixed length vectors, since we need to know the exact number of 6860 // elements. 6861 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS && 6862 N1.getOperand(0).getValueType().isFixedLengthVector()) { 6863 unsigned Factor = 6864 N1.getOperand(0).getValueType().getVectorNumElements(); 6865 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 6866 N1.getOperand(N2C->getZExtValue() / Factor), 6867 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 6868 } 6869 6870 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 6871 // lowering is expanding large vector constants. 6872 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 6873 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 6874 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 6875 N1.getValueType().isFixedLengthVector()) && 6876 "BUILD_VECTOR used for scalable vectors"); 6877 unsigned Index = 6878 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 6879 SDValue Elt = N1.getOperand(Index); 6880 6881 if (VT != Elt.getValueType()) 6882 // If the vector element type is not legal, the BUILD_VECTOR operands 6883 // are promoted and implicitly truncated, and the result implicitly 6884 // extended. Make that explicit here. 6885 Elt = getAnyExtOrTrunc(Elt, DL, VT); 6886 6887 return Elt; 6888 } 6889 6890 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 6891 // operations are lowered to scalars. 6892 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 6893 // If the indices are the same, return the inserted element else 6894 // if the indices are known different, extract the element from 6895 // the original vector. 6896 SDValue N1Op2 = N1.getOperand(2); 6897 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 6898 6899 if (N1Op2C && N2C) { 6900 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 6901 if (VT == N1.getOperand(1).getValueType()) 6902 return N1.getOperand(1); 6903 if (VT.isFloatingPoint()) { 6904 assert(VT.getSizeInBits() > N1.getOperand(1).getValueType().getSizeInBits()); 6905 return getFPExtendOrRound(N1.getOperand(1), DL, VT); 6906 } 6907 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 6908 } 6909 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 6910 } 6911 } 6912 6913 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 6914 // when vector types are scalarized and v1iX is legal. 6915 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 6916 // Here we are completely ignoring the extract element index (N2), 6917 // which is fine for fixed width vectors, since any index other than 0 6918 // is undefined anyway. However, this cannot be ignored for scalable 6919 // vectors - in theory we could support this, but we don't want to do this 6920 // without a profitability check. 6921 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6922 N1.getValueType().isFixedLengthVector() && 6923 N1.getValueType().getVectorNumElements() == 1) { 6924 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 6925 N1.getOperand(1)); 6926 } 6927 break; 6928 case ISD::EXTRACT_ELEMENT: 6929 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 6930 assert(!N1.getValueType().isVector() && !VT.isVector() && 6931 (N1.getValueType().isInteger() == VT.isInteger()) && 6932 N1.getValueType() != VT && 6933 "Wrong types for EXTRACT_ELEMENT!"); 6934 6935 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 6936 // 64-bit integers into 32-bit parts. Instead of building the extract of 6937 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 6938 if (N1.getOpcode() == ISD::BUILD_PAIR) 6939 return N1.getOperand(N2C->getZExtValue()); 6940 6941 // EXTRACT_ELEMENT of a constant int is also very common. 6942 if (N1C) { 6943 unsigned ElementSize = VT.getSizeInBits(); 6944 unsigned Shift = ElementSize * N2C->getZExtValue(); 6945 const APInt &Val = N1C->getAPIntValue(); 6946 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 6947 } 6948 break; 6949 case ISD::EXTRACT_SUBVECTOR: { 6950 EVT N1VT = N1.getValueType(); 6951 assert(VT.isVector() && N1VT.isVector() && 6952 "Extract subvector VTs must be vectors!"); 6953 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 6954 "Extract subvector VTs must have the same element type!"); 6955 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 6956 "Cannot extract a scalable vector from a fixed length vector!"); 6957 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6958 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 6959 "Extract subvector must be from larger vector to smaller vector!"); 6960 assert(N2C && "Extract subvector index must be a constant"); 6961 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6962 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 6963 N1VT.getVectorMinNumElements()) && 6964 "Extract subvector overflow!"); 6965 assert(N2C->getAPIntValue().getBitWidth() == 6966 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6967 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 6968 6969 // Trivial extraction. 6970 if (VT == N1VT) 6971 return N1; 6972 6973 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 6974 if (N1.isUndef()) 6975 return getUNDEF(VT); 6976 6977 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 6978 // the concat have the same type as the extract. 6979 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 6980 VT == N1.getOperand(0).getValueType()) { 6981 unsigned Factor = VT.getVectorMinNumElements(); 6982 return N1.getOperand(N2C->getZExtValue() / Factor); 6983 } 6984 6985 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 6986 // during shuffle legalization. 6987 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 6988 VT == N1.getOperand(1).getValueType()) 6989 return N1.getOperand(1); 6990 break; 6991 } 6992 } 6993 6994 // Perform trivial constant folding. 6995 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 6996 return SV; 6997 6998 // Canonicalize an UNDEF to the RHS, even over a constant. 6999 if (N1.isUndef()) { 7000 if (TLI->isCommutativeBinOp(Opcode)) { 7001 std::swap(N1, N2); 7002 } else { 7003 switch (Opcode) { 7004 case ISD::SUB: 7005 return getUNDEF(VT); // fold op(undef, arg2) -> undef 7006 case ISD::SIGN_EXTEND_INREG: 7007 case ISD::UDIV: 7008 case ISD::SDIV: 7009 case ISD::UREM: 7010 case ISD::SREM: 7011 case ISD::SSUBSAT: 7012 case ISD::USUBSAT: 7013 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 7014 } 7015 } 7016 } 7017 7018 // Fold a bunch of operators when the RHS is undef. 7019 if (N2.isUndef()) { 7020 switch (Opcode) { 7021 case ISD::XOR: 7022 if (N1.isUndef()) 7023 // Handle undef ^ undef -> 0 special case. This is a common 7024 // idiom (misuse). 7025 return getConstant(0, DL, VT); 7026 [[fallthrough]]; 7027 case ISD::ADD: 7028 case ISD::SUB: 7029 case ISD::UDIV: 7030 case ISD::SDIV: 7031 case ISD::UREM: 7032 case ISD::SREM: 7033 return getUNDEF(VT); // fold op(arg1, undef) -> undef 7034 case ISD::MUL: 7035 case ISD::AND: 7036 case ISD::SSUBSAT: 7037 case ISD::USUBSAT: 7038 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 7039 case ISD::OR: 7040 case ISD::SADDSAT: 7041 case ISD::UADDSAT: 7042 return getAllOnesConstant(DL, VT); 7043 } 7044 } 7045 7046 // Memoize this node if possible. 7047 SDNode *N; 7048 SDVTList VTs = getVTList(VT); 7049 SDValue Ops[] = {N1, N2}; 7050 if (VT != MVT::Glue) { 7051 FoldingSetNodeID ID; 7052 AddNodeIDNode(ID, Opcode, VTs, Ops); 7053 void *IP = nullptr; 7054 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 7055 E->intersectFlagsWith(Flags); 7056 return SDValue(E, 0); 7057 } 7058 7059 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7060 N->setFlags(Flags); 7061 createOperands(N, Ops); 7062 CSEMap.InsertNode(N, IP); 7063 } else { 7064 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7065 createOperands(N, Ops); 7066 } 7067 7068 InsertNode(N); 7069 SDValue V = SDValue(N, 0); 7070 NewSDValueDbgMsg(V, "Creating new node: ", this); 7071 return V; 7072 } 7073 7074 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7075 SDValue N1, SDValue N2, SDValue N3) { 7076 SDNodeFlags Flags; 7077 if (Inserter) 7078 Flags = Inserter->getFlags(); 7079 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 7080 } 7081 7082 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7083 SDValue N1, SDValue N2, SDValue N3, 7084 const SDNodeFlags Flags) { 7085 assert(N1.getOpcode() != ISD::DELETED_NODE && 7086 N2.getOpcode() != ISD::DELETED_NODE && 7087 N3.getOpcode() != ISD::DELETED_NODE && 7088 "Operand is DELETED_NODE!"); 7089 // Perform various simplifications. 7090 switch (Opcode) { 7091 case ISD::FMA: 7092 case ISD::FMAD: { 7093 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 7094 assert(N1.getValueType() == VT && N2.getValueType() == VT && 7095 N3.getValueType() == VT && "FMA types must match!"); 7096 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7097 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 7098 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 7099 if (N1CFP && N2CFP && N3CFP) { 7100 APFloat V1 = N1CFP->getValueAPF(); 7101 const APFloat &V2 = N2CFP->getValueAPF(); 7102 const APFloat &V3 = N3CFP->getValueAPF(); 7103 if (Opcode == ISD::FMAD) { 7104 V1.multiply(V2, APFloat::rmNearestTiesToEven); 7105 V1.add(V3, APFloat::rmNearestTiesToEven); 7106 } else 7107 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 7108 return getConstantFP(V1, DL, VT); 7109 } 7110 break; 7111 } 7112 case ISD::BUILD_VECTOR: { 7113 // Attempt to simplify BUILD_VECTOR. 7114 SDValue Ops[] = {N1, N2, N3}; 7115 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 7116 return V; 7117 break; 7118 } 7119 case ISD::CONCAT_VECTORS: { 7120 SDValue Ops[] = {N1, N2, N3}; 7121 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 7122 return V; 7123 break; 7124 } 7125 case ISD::SETCC: { 7126 assert(VT.isInteger() && "SETCC result type must be an integer!"); 7127 assert(N1.getValueType() == N2.getValueType() && 7128 "SETCC operands must have the same type!"); 7129 assert(VT.isVector() == N1.getValueType().isVector() && 7130 "SETCC type should be vector iff the operand type is vector!"); 7131 assert((!VT.isVector() || VT.getVectorElementCount() == 7132 N1.getValueType().getVectorElementCount()) && 7133 "SETCC vector element counts must match!"); 7134 // Use FoldSetCC to simplify SETCC's. 7135 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 7136 return V; 7137 // Vector constant folding. 7138 SDValue Ops[] = {N1, N2, N3}; 7139 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) { 7140 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 7141 return V; 7142 } 7143 break; 7144 } 7145 case ISD::SELECT: 7146 case ISD::VSELECT: 7147 if (SDValue V = simplifySelect(N1, N2, N3)) 7148 return V; 7149 break; 7150 case ISD::VECTOR_SHUFFLE: 7151 llvm_unreachable("should use getVectorShuffle constructor!"); 7152 case ISD::VECTOR_SPLICE: { 7153 if (cast<ConstantSDNode>(N3)->isZero()) 7154 return N1; 7155 break; 7156 } 7157 case ISD::INSERT_VECTOR_ELT: { 7158 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 7159 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 7160 // for scalable vectors where we will generate appropriate code to 7161 // deal with out-of-bounds cases correctly. 7162 if (N3C && N1.getValueType().isFixedLengthVector() && 7163 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 7164 return getUNDEF(VT); 7165 7166 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 7167 if (N3.isUndef()) 7168 return getUNDEF(VT); 7169 7170 // If the inserted element is an UNDEF, just use the input vector. 7171 if (N2.isUndef()) 7172 return N1; 7173 7174 break; 7175 } 7176 case ISD::INSERT_SUBVECTOR: { 7177 // Inserting undef into undef is still undef. 7178 if (N1.isUndef() && N2.isUndef()) 7179 return getUNDEF(VT); 7180 7181 EVT N2VT = N2.getValueType(); 7182 assert(VT == N1.getValueType() && 7183 "Dest and insert subvector source types must match!"); 7184 assert(VT.isVector() && N2VT.isVector() && 7185 "Insert subvector VTs must be vectors!"); 7186 assert(VT.getVectorElementType() == N2VT.getVectorElementType() && 7187 "Insert subvector VTs must have the same element type!"); 7188 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 7189 "Cannot insert a scalable vector into a fixed length vector!"); 7190 assert((VT.isScalableVector() != N2VT.isScalableVector() || 7191 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 7192 "Insert subvector must be from smaller vector to larger vector!"); 7193 assert(isa<ConstantSDNode>(N3) && 7194 "Insert subvector index must be constant"); 7195 assert((VT.isScalableVector() != N2VT.isScalableVector() || 7196 (N2VT.getVectorMinNumElements() + 7197 cast<ConstantSDNode>(N3)->getZExtValue()) <= 7198 VT.getVectorMinNumElements()) && 7199 "Insert subvector overflow!"); 7200 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 7201 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 7202 "Constant index for INSERT_SUBVECTOR has an invalid size"); 7203 7204 // Trivial insertion. 7205 if (VT == N2VT) 7206 return N2; 7207 7208 // If this is an insert of an extracted vector into an undef vector, we 7209 // can just use the input to the extract. 7210 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 7211 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 7212 return N2.getOperand(0); 7213 break; 7214 } 7215 case ISD::BITCAST: 7216 // Fold bit_convert nodes from a type to themselves. 7217 if (N1.getValueType() == VT) 7218 return N1; 7219 break; 7220 case ISD::VP_TRUNCATE: 7221 case ISD::VP_SIGN_EXTEND: 7222 case ISD::VP_ZERO_EXTEND: 7223 // Don't create noop casts. 7224 if (N1.getValueType() == VT) 7225 return N1; 7226 break; 7227 } 7228 7229 // Memoize node if it doesn't produce a glue result. 7230 SDNode *N; 7231 SDVTList VTs = getVTList(VT); 7232 SDValue Ops[] = {N1, N2, N3}; 7233 if (VT != MVT::Glue) { 7234 FoldingSetNodeID ID; 7235 AddNodeIDNode(ID, Opcode, VTs, Ops); 7236 void *IP = nullptr; 7237 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 7238 E->intersectFlagsWith(Flags); 7239 return SDValue(E, 0); 7240 } 7241 7242 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7243 N->setFlags(Flags); 7244 createOperands(N, Ops); 7245 CSEMap.InsertNode(N, IP); 7246 } else { 7247 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7248 createOperands(N, Ops); 7249 } 7250 7251 InsertNode(N); 7252 SDValue V = SDValue(N, 0); 7253 NewSDValueDbgMsg(V, "Creating new node: ", this); 7254 return V; 7255 } 7256 7257 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7258 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 7259 SDValue Ops[] = { N1, N2, N3, N4 }; 7260 return getNode(Opcode, DL, VT, Ops); 7261 } 7262 7263 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7264 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 7265 SDValue N5) { 7266 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 7267 return getNode(Opcode, DL, VT, Ops); 7268 } 7269 7270 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 7271 /// the incoming stack arguments to be loaded from the stack. 7272 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 7273 SmallVector<SDValue, 8> ArgChains; 7274 7275 // Include the original chain at the beginning of the list. When this is 7276 // used by target LowerCall hooks, this helps legalize find the 7277 // CALLSEQ_BEGIN node. 7278 ArgChains.push_back(Chain); 7279 7280 // Add a chain value for each stack argument. 7281 for (SDNode *U : getEntryNode().getNode()->uses()) 7282 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U)) 7283 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 7284 if (FI->getIndex() < 0) 7285 ArgChains.push_back(SDValue(L, 1)); 7286 7287 // Build a tokenfactor for all the chains. 7288 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 7289 } 7290 7291 /// getMemsetValue - Vectorized representation of the memset value 7292 /// operand. 7293 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 7294 const SDLoc &dl) { 7295 assert(!Value.isUndef()); 7296 7297 unsigned NumBits = VT.getScalarSizeInBits(); 7298 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 7299 assert(C->getAPIntValue().getBitWidth() == 8); 7300 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 7301 if (VT.isInteger()) { 7302 bool IsOpaque = VT.getSizeInBits() > 64 || 7303 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 7304 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 7305 } 7306 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 7307 VT); 7308 } 7309 7310 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 7311 EVT IntVT = VT.getScalarType(); 7312 if (!IntVT.isInteger()) 7313 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 7314 7315 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 7316 if (NumBits > 8) { 7317 // Use a multiplication with 0x010101... to extend the input to the 7318 // required length. 7319 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 7320 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 7321 DAG.getConstant(Magic, dl, IntVT)); 7322 } 7323 7324 if (VT != Value.getValueType() && !VT.isInteger()) 7325 Value = DAG.getBitcast(VT.getScalarType(), Value); 7326 if (VT != Value.getValueType()) 7327 Value = DAG.getSplatBuildVector(VT, dl, Value); 7328 7329 return Value; 7330 } 7331 7332 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 7333 /// used when a memcpy is turned into a memset when the source is a constant 7334 /// string ptr. 7335 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 7336 const TargetLowering &TLI, 7337 const ConstantDataArraySlice &Slice) { 7338 // Handle vector with all elements zero. 7339 if (Slice.Array == nullptr) { 7340 if (VT.isInteger()) 7341 return DAG.getConstant(0, dl, VT); 7342 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 7343 return DAG.getConstantFP(0.0, dl, VT); 7344 if (VT.isVector()) { 7345 unsigned NumElts = VT.getVectorNumElements(); 7346 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 7347 return DAG.getNode(ISD::BITCAST, dl, VT, 7348 DAG.getConstant(0, dl, 7349 EVT::getVectorVT(*DAG.getContext(), 7350 EltVT, NumElts))); 7351 } 7352 llvm_unreachable("Expected type!"); 7353 } 7354 7355 assert(!VT.isVector() && "Can't handle vector type here!"); 7356 unsigned NumVTBits = VT.getSizeInBits(); 7357 unsigned NumVTBytes = NumVTBits / 8; 7358 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 7359 7360 APInt Val(NumVTBits, 0); 7361 if (DAG.getDataLayout().isLittleEndian()) { 7362 for (unsigned i = 0; i != NumBytes; ++i) 7363 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 7364 } else { 7365 for (unsigned i = 0; i != NumBytes; ++i) 7366 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 7367 } 7368 7369 // If the "cost" of materializing the integer immediate is less than the cost 7370 // of a load, then it is cost effective to turn the load into the immediate. 7371 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 7372 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 7373 return DAG.getConstant(Val, dl, VT); 7374 return SDValue(); 7375 } 7376 7377 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 7378 const SDLoc &DL, 7379 const SDNodeFlags Flags) { 7380 EVT VT = Base.getValueType(); 7381 SDValue Index; 7382 7383 if (Offset.isScalable()) 7384 Index = getVScale(DL, Base.getValueType(), 7385 APInt(Base.getValueSizeInBits().getFixedValue(), 7386 Offset.getKnownMinValue())); 7387 else 7388 Index = getConstant(Offset.getFixedValue(), DL, VT); 7389 7390 return getMemBasePlusOffset(Base, Index, DL, Flags); 7391 } 7392 7393 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 7394 const SDLoc &DL, 7395 const SDNodeFlags Flags) { 7396 assert(Offset.getValueType().isInteger()); 7397 EVT BasePtrVT = Ptr.getValueType(); 7398 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 7399 } 7400 7401 /// Returns true if memcpy source is constant data. 7402 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 7403 uint64_t SrcDelta = 0; 7404 GlobalAddressSDNode *G = nullptr; 7405 if (Src.getOpcode() == ISD::GlobalAddress) 7406 G = cast<GlobalAddressSDNode>(Src); 7407 else if (Src.getOpcode() == ISD::ADD && 7408 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 7409 Src.getOperand(1).getOpcode() == ISD::Constant) { 7410 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 7411 SrcDelta = Src.getConstantOperandVal(1); 7412 } 7413 if (!G) 7414 return false; 7415 7416 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 7417 SrcDelta + G->getOffset()); 7418 } 7419 7420 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 7421 SelectionDAG &DAG) { 7422 // On Darwin, -Os means optimize for size without hurting performance, so 7423 // only really optimize for size when -Oz (MinSize) is used. 7424 if (MF.getTarget().getTargetTriple().isOSDarwin()) 7425 return MF.getFunction().hasMinSize(); 7426 return DAG.shouldOptForSize(); 7427 } 7428 7429 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 7430 SmallVector<SDValue, 32> &OutChains, unsigned From, 7431 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 7432 SmallVector<SDValue, 16> &OutStoreChains) { 7433 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 7434 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 7435 SmallVector<SDValue, 16> GluedLoadChains; 7436 for (unsigned i = From; i < To; ++i) { 7437 OutChains.push_back(OutLoadChains[i]); 7438 GluedLoadChains.push_back(OutLoadChains[i]); 7439 } 7440 7441 // Chain for all loads. 7442 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7443 GluedLoadChains); 7444 7445 for (unsigned i = From; i < To; ++i) { 7446 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 7447 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 7448 ST->getBasePtr(), ST->getMemoryVT(), 7449 ST->getMemOperand()); 7450 OutChains.push_back(NewStore); 7451 } 7452 } 7453 7454 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 7455 SDValue Chain, SDValue Dst, SDValue Src, 7456 uint64_t Size, Align Alignment, 7457 bool isVol, bool AlwaysInline, 7458 MachinePointerInfo DstPtrInfo, 7459 MachinePointerInfo SrcPtrInfo, 7460 const AAMDNodes &AAInfo, AAResults *AA) { 7461 // Turn a memcpy of undef to nop. 7462 // FIXME: We need to honor volatile even is Src is undef. 7463 if (Src.isUndef()) 7464 return Chain; 7465 7466 // Expand memcpy to a series of load and store ops if the size operand falls 7467 // below a certain threshold. 7468 // TODO: In the AlwaysInline case, if the size is big then generate a loop 7469 // rather than maybe a humongous number of loads and stores. 7470 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7471 const DataLayout &DL = DAG.getDataLayout(); 7472 LLVMContext &C = *DAG.getContext(); 7473 std::vector<EVT> MemOps; 7474 bool DstAlignCanChange = false; 7475 MachineFunction &MF = DAG.getMachineFunction(); 7476 MachineFrameInfo &MFI = MF.getFrameInfo(); 7477 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 7478 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 7479 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 7480 DstAlignCanChange = true; 7481 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 7482 if (!SrcAlign || Alignment > *SrcAlign) 7483 SrcAlign = Alignment; 7484 assert(SrcAlign && "SrcAlign must be set"); 7485 ConstantDataArraySlice Slice; 7486 // If marked as volatile, perform a copy even when marked as constant. 7487 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 7488 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 7489 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 7490 const MemOp Op = isZeroConstant 7491 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 7492 /*IsZeroMemset*/ true, isVol) 7493 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 7494 *SrcAlign, isVol, CopyFromConstant); 7495 if (!TLI.findOptimalMemOpLowering( 7496 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 7497 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 7498 return SDValue(); 7499 7500 if (DstAlignCanChange) { 7501 Type *Ty = MemOps[0].getTypeForEVT(C); 7502 Align NewAlign = DL.getABITypeAlign(Ty); 7503 7504 // Don't promote to an alignment that would require dynamic stack 7505 // realignment which may conflict with optimizations such as tail call 7506 // optimization. 7507 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 7508 if (!TRI->hasStackRealignment(MF)) 7509 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 7510 NewAlign = NewAlign.previous(); 7511 7512 if (NewAlign > Alignment) { 7513 // Give the stack frame object a larger alignment if needed. 7514 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 7515 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 7516 Alignment = NewAlign; 7517 } 7518 } 7519 7520 // Prepare AAInfo for loads/stores after lowering this memcpy. 7521 AAMDNodes NewAAInfo = AAInfo; 7522 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 7523 7524 const Value *SrcVal = dyn_cast_if_present<const Value *>(SrcPtrInfo.V); 7525 bool isConstant = 7526 AA && SrcVal && 7527 AA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo)); 7528 7529 MachineMemOperand::Flags MMOFlags = 7530 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 7531 SmallVector<SDValue, 16> OutLoadChains; 7532 SmallVector<SDValue, 16> OutStoreChains; 7533 SmallVector<SDValue, 32> OutChains; 7534 unsigned NumMemOps = MemOps.size(); 7535 uint64_t SrcOff = 0, DstOff = 0; 7536 for (unsigned i = 0; i != NumMemOps; ++i) { 7537 EVT VT = MemOps[i]; 7538 unsigned VTSize = VT.getSizeInBits() / 8; 7539 SDValue Value, Store; 7540 7541 if (VTSize > Size) { 7542 // Issuing an unaligned load / store pair that overlaps with the previous 7543 // pair. Adjust the offset accordingly. 7544 assert(i == NumMemOps-1 && i != 0); 7545 SrcOff -= VTSize - Size; 7546 DstOff -= VTSize - Size; 7547 } 7548 7549 if (CopyFromConstant && 7550 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 7551 // It's unlikely a store of a vector immediate can be done in a single 7552 // instruction. It would require a load from a constantpool first. 7553 // We only handle zero vectors here. 7554 // FIXME: Handle other cases where store of vector immediate is done in 7555 // a single instruction. 7556 ConstantDataArraySlice SubSlice; 7557 if (SrcOff < Slice.Length) { 7558 SubSlice = Slice; 7559 SubSlice.move(SrcOff); 7560 } else { 7561 // This is an out-of-bounds access and hence UB. Pretend we read zero. 7562 SubSlice.Array = nullptr; 7563 SubSlice.Offset = 0; 7564 SubSlice.Length = VTSize; 7565 } 7566 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 7567 if (Value.getNode()) { 7568 Store = DAG.getStore( 7569 Chain, dl, Value, 7570 DAG.getMemBasePlusOffset(Dst, TypeSize::getFixed(DstOff), dl), 7571 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 7572 OutChains.push_back(Store); 7573 } 7574 } 7575 7576 if (!Store.getNode()) { 7577 // The type might not be legal for the target. This should only happen 7578 // if the type is smaller than a legal type, as on PPC, so the right 7579 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 7580 // to Load/Store if NVT==VT. 7581 // FIXME does the case above also need this? 7582 EVT NVT = TLI.getTypeToTransformTo(C, VT); 7583 assert(NVT.bitsGE(VT)); 7584 7585 bool isDereferenceable = 7586 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 7587 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 7588 if (isDereferenceable) 7589 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 7590 if (isConstant) 7591 SrcMMOFlags |= MachineMemOperand::MOInvariant; 7592 7593 Value = DAG.getExtLoad( 7594 ISD::EXTLOAD, dl, NVT, Chain, 7595 DAG.getMemBasePlusOffset(Src, TypeSize::getFixed(SrcOff), dl), 7596 SrcPtrInfo.getWithOffset(SrcOff), VT, 7597 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo); 7598 OutLoadChains.push_back(Value.getValue(1)); 7599 7600 Store = DAG.getTruncStore( 7601 Chain, dl, Value, 7602 DAG.getMemBasePlusOffset(Dst, TypeSize::getFixed(DstOff), dl), 7603 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo); 7604 OutStoreChains.push_back(Store); 7605 } 7606 SrcOff += VTSize; 7607 DstOff += VTSize; 7608 Size -= VTSize; 7609 } 7610 7611 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 7612 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 7613 unsigned NumLdStInMemcpy = OutStoreChains.size(); 7614 7615 if (NumLdStInMemcpy) { 7616 // It may be that memcpy might be converted to memset if it's memcpy 7617 // of constants. In such a case, we won't have loads and stores, but 7618 // just stores. In the absence of loads, there is nothing to gang up. 7619 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 7620 // If target does not care, just leave as it. 7621 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 7622 OutChains.push_back(OutLoadChains[i]); 7623 OutChains.push_back(OutStoreChains[i]); 7624 } 7625 } else { 7626 // Ld/St less than/equal limit set by target. 7627 if (NumLdStInMemcpy <= GluedLdStLimit) { 7628 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 7629 NumLdStInMemcpy, OutLoadChains, 7630 OutStoreChains); 7631 } else { 7632 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 7633 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 7634 unsigned GlueIter = 0; 7635 7636 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 7637 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 7638 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 7639 7640 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 7641 OutLoadChains, OutStoreChains); 7642 GlueIter += GluedLdStLimit; 7643 } 7644 7645 // Residual ld/st. 7646 if (RemainingLdStInMemcpy) { 7647 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 7648 RemainingLdStInMemcpy, OutLoadChains, 7649 OutStoreChains); 7650 } 7651 } 7652 } 7653 } 7654 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 7655 } 7656 7657 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 7658 SDValue Chain, SDValue Dst, SDValue Src, 7659 uint64_t Size, Align Alignment, 7660 bool isVol, bool AlwaysInline, 7661 MachinePointerInfo DstPtrInfo, 7662 MachinePointerInfo SrcPtrInfo, 7663 const AAMDNodes &AAInfo) { 7664 // Turn a memmove of undef to nop. 7665 // FIXME: We need to honor volatile even is Src is undef. 7666 if (Src.isUndef()) 7667 return Chain; 7668 7669 // Expand memmove to a series of load and store ops if the size operand falls 7670 // below a certain threshold. 7671 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7672 const DataLayout &DL = DAG.getDataLayout(); 7673 LLVMContext &C = *DAG.getContext(); 7674 std::vector<EVT> MemOps; 7675 bool DstAlignCanChange = false; 7676 MachineFunction &MF = DAG.getMachineFunction(); 7677 MachineFrameInfo &MFI = MF.getFrameInfo(); 7678 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 7679 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 7680 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 7681 DstAlignCanChange = true; 7682 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 7683 if (!SrcAlign || Alignment > *SrcAlign) 7684 SrcAlign = Alignment; 7685 assert(SrcAlign && "SrcAlign must be set"); 7686 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 7687 if (!TLI.findOptimalMemOpLowering( 7688 MemOps, Limit, 7689 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 7690 /*IsVolatile*/ true), 7691 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 7692 MF.getFunction().getAttributes())) 7693 return SDValue(); 7694 7695 if (DstAlignCanChange) { 7696 Type *Ty = MemOps[0].getTypeForEVT(C); 7697 Align NewAlign = DL.getABITypeAlign(Ty); 7698 7699 // Don't promote to an alignment that would require dynamic stack 7700 // realignment which may conflict with optimizations such as tail call 7701 // optimization. 7702 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 7703 if (!TRI->hasStackRealignment(MF)) 7704 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 7705 NewAlign = NewAlign.previous(); 7706 7707 if (NewAlign > Alignment) { 7708 // Give the stack frame object a larger alignment if needed. 7709 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 7710 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 7711 Alignment = NewAlign; 7712 } 7713 } 7714 7715 // Prepare AAInfo for loads/stores after lowering this memmove. 7716 AAMDNodes NewAAInfo = AAInfo; 7717 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 7718 7719 MachineMemOperand::Flags MMOFlags = 7720 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 7721 uint64_t SrcOff = 0, DstOff = 0; 7722 SmallVector<SDValue, 8> LoadValues; 7723 SmallVector<SDValue, 8> LoadChains; 7724 SmallVector<SDValue, 8> OutChains; 7725 unsigned NumMemOps = MemOps.size(); 7726 for (unsigned i = 0; i < NumMemOps; i++) { 7727 EVT VT = MemOps[i]; 7728 unsigned VTSize = VT.getSizeInBits() / 8; 7729 SDValue Value; 7730 7731 bool isDereferenceable = 7732 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 7733 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 7734 if (isDereferenceable) 7735 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 7736 7737 Value = DAG.getLoad( 7738 VT, dl, Chain, 7739 DAG.getMemBasePlusOffset(Src, TypeSize::getFixed(SrcOff), dl), 7740 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo); 7741 LoadValues.push_back(Value); 7742 LoadChains.push_back(Value.getValue(1)); 7743 SrcOff += VTSize; 7744 } 7745 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 7746 OutChains.clear(); 7747 for (unsigned i = 0; i < NumMemOps; i++) { 7748 EVT VT = MemOps[i]; 7749 unsigned VTSize = VT.getSizeInBits() / 8; 7750 SDValue Store; 7751 7752 Store = DAG.getStore( 7753 Chain, dl, LoadValues[i], 7754 DAG.getMemBasePlusOffset(Dst, TypeSize::getFixed(DstOff), dl), 7755 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 7756 OutChains.push_back(Store); 7757 DstOff += VTSize; 7758 } 7759 7760 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 7761 } 7762 7763 /// Lower the call to 'memset' intrinsic function into a series of store 7764 /// operations. 7765 /// 7766 /// \param DAG Selection DAG where lowered code is placed. 7767 /// \param dl Link to corresponding IR location. 7768 /// \param Chain Control flow dependency. 7769 /// \param Dst Pointer to destination memory location. 7770 /// \param Src Value of byte to write into the memory. 7771 /// \param Size Number of bytes to write. 7772 /// \param Alignment Alignment of the destination in bytes. 7773 /// \param isVol True if destination is volatile. 7774 /// \param AlwaysInline Makes sure no function call is generated. 7775 /// \param DstPtrInfo IR information on the memory pointer. 7776 /// \returns New head in the control flow, if lowering was successful, empty 7777 /// SDValue otherwise. 7778 /// 7779 /// The function tries to replace 'llvm.memset' intrinsic with several store 7780 /// operations and value calculation code. This is usually profitable for small 7781 /// memory size or when the semantic requires inlining. 7782 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 7783 SDValue Chain, SDValue Dst, SDValue Src, 7784 uint64_t Size, Align Alignment, bool isVol, 7785 bool AlwaysInline, MachinePointerInfo DstPtrInfo, 7786 const AAMDNodes &AAInfo) { 7787 // Turn a memset of undef to nop. 7788 // FIXME: We need to honor volatile even is Src is undef. 7789 if (Src.isUndef()) 7790 return Chain; 7791 7792 // Expand memset to a series of load/store ops if the size operand 7793 // falls below a certain threshold. 7794 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7795 std::vector<EVT> MemOps; 7796 bool DstAlignCanChange = false; 7797 MachineFunction &MF = DAG.getMachineFunction(); 7798 MachineFrameInfo &MFI = MF.getFrameInfo(); 7799 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 7800 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 7801 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 7802 DstAlignCanChange = true; 7803 bool IsZeroVal = isNullConstant(Src); 7804 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize); 7805 7806 if (!TLI.findOptimalMemOpLowering( 7807 MemOps, Limit, 7808 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 7809 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 7810 return SDValue(); 7811 7812 if (DstAlignCanChange) { 7813 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 7814 const DataLayout &DL = DAG.getDataLayout(); 7815 Align NewAlign = DL.getABITypeAlign(Ty); 7816 7817 // Don't promote to an alignment that would require dynamic stack 7818 // realignment which may conflict with optimizations such as tail call 7819 // optimization. 7820 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 7821 if (!TRI->hasStackRealignment(MF)) 7822 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 7823 NewAlign = NewAlign.previous(); 7824 7825 if (NewAlign > Alignment) { 7826 // Give the stack frame object a larger alignment if needed. 7827 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 7828 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 7829 Alignment = NewAlign; 7830 } 7831 } 7832 7833 SmallVector<SDValue, 8> OutChains; 7834 uint64_t DstOff = 0; 7835 unsigned NumMemOps = MemOps.size(); 7836 7837 // Find the largest store and generate the bit pattern for it. 7838 EVT LargestVT = MemOps[0]; 7839 for (unsigned i = 1; i < NumMemOps; i++) 7840 if (MemOps[i].bitsGT(LargestVT)) 7841 LargestVT = MemOps[i]; 7842 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 7843 7844 // Prepare AAInfo for loads/stores after lowering this memset. 7845 AAMDNodes NewAAInfo = AAInfo; 7846 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 7847 7848 for (unsigned i = 0; i < NumMemOps; i++) { 7849 EVT VT = MemOps[i]; 7850 unsigned VTSize = VT.getSizeInBits() / 8; 7851 if (VTSize > Size) { 7852 // Issuing an unaligned load / store pair that overlaps with the previous 7853 // pair. Adjust the offset accordingly. 7854 assert(i == NumMemOps-1 && i != 0); 7855 DstOff -= VTSize - Size; 7856 } 7857 7858 // If this store is smaller than the largest store see whether we can get 7859 // the smaller value for free with a truncate or extract vector element and 7860 // then store. 7861 SDValue Value = MemSetValue; 7862 if (VT.bitsLT(LargestVT)) { 7863 unsigned Index; 7864 unsigned NElts = LargestVT.getSizeInBits() / VT.getSizeInBits(); 7865 EVT SVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), NElts); 7866 if (!LargestVT.isVector() && !VT.isVector() && 7867 TLI.isTruncateFree(LargestVT, VT)) 7868 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 7869 else if (LargestVT.isVector() && !VT.isVector() && 7870 TLI.shallExtractConstSplatVectorElementToStore( 7871 LargestVT.getTypeForEVT(*DAG.getContext()), 7872 VT.getSizeInBits(), Index) && 7873 TLI.isTypeLegal(SVT) && 7874 LargestVT.getSizeInBits() == SVT.getSizeInBits()) { 7875 // Target which can combine store(extractelement VectorTy, Idx) can get 7876 // the smaller value for free. 7877 SDValue TailValue = DAG.getNode(ISD::BITCAST, dl, SVT, MemSetValue); 7878 Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, TailValue, 7879 DAG.getVectorIdxConstant(Index, dl)); 7880 } else 7881 Value = getMemsetValue(Src, VT, DAG, dl); 7882 } 7883 assert(Value.getValueType() == VT && "Value with wrong type."); 7884 SDValue Store = DAG.getStore( 7885 Chain, dl, Value, 7886 DAG.getMemBasePlusOffset(Dst, TypeSize::getFixed(DstOff), dl), 7887 DstPtrInfo.getWithOffset(DstOff), Alignment, 7888 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone, 7889 NewAAInfo); 7890 OutChains.push_back(Store); 7891 DstOff += VT.getSizeInBits() / 8; 7892 Size -= VTSize; 7893 } 7894 7895 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 7896 } 7897 7898 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 7899 unsigned AS) { 7900 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 7901 // pointer operands can be losslessly bitcasted to pointers of address space 0 7902 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 7903 report_fatal_error("cannot lower memory intrinsic in address space " + 7904 Twine(AS)); 7905 } 7906 } 7907 7908 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 7909 SDValue Src, SDValue Size, Align Alignment, 7910 bool isVol, bool AlwaysInline, bool isTailCall, 7911 MachinePointerInfo DstPtrInfo, 7912 MachinePointerInfo SrcPtrInfo, 7913 const AAMDNodes &AAInfo, AAResults *AA) { 7914 // Check to see if we should lower the memcpy to loads and stores first. 7915 // For cases within the target-specified limits, this is the best choice. 7916 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7917 if (ConstantSize) { 7918 // Memcpy with size zero? Just return the original chain. 7919 if (ConstantSize->isZero()) 7920 return Chain; 7921 7922 SDValue Result = getMemcpyLoadsAndStores( 7923 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7924 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, AA); 7925 if (Result.getNode()) 7926 return Result; 7927 } 7928 7929 // Then check to see if we should lower the memcpy with target-specific 7930 // code. If the target chooses to do this, this is the next best. 7931 if (TSI) { 7932 SDValue Result = TSI->EmitTargetCodeForMemcpy( 7933 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 7934 DstPtrInfo, SrcPtrInfo); 7935 if (Result.getNode()) 7936 return Result; 7937 } 7938 7939 // If we really need inline code and the target declined to provide it, 7940 // use a (potentially long) sequence of loads and stores. 7941 if (AlwaysInline) { 7942 assert(ConstantSize && "AlwaysInline requires a constant size!"); 7943 return getMemcpyLoadsAndStores( 7944 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7945 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, AA); 7946 } 7947 7948 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7949 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7950 7951 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 7952 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 7953 // respect volatile, so they may do things like read or write memory 7954 // beyond the given memory regions. But fixing this isn't easy, and most 7955 // people don't care. 7956 7957 // Emit a library call. 7958 TargetLowering::ArgListTy Args; 7959 TargetLowering::ArgListEntry Entry; 7960 Entry.Ty = PointerType::getUnqual(*getContext()); 7961 Entry.Node = Dst; Args.push_back(Entry); 7962 Entry.Node = Src; Args.push_back(Entry); 7963 7964 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7965 Entry.Node = Size; Args.push_back(Entry); 7966 // FIXME: pass in SDLoc 7967 TargetLowering::CallLoweringInfo CLI(*this); 7968 CLI.setDebugLoc(dl) 7969 .setChain(Chain) 7970 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 7971 Dst.getValueType().getTypeForEVT(*getContext()), 7972 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 7973 TLI->getPointerTy(getDataLayout())), 7974 std::move(Args)) 7975 .setDiscardResult() 7976 .setTailCall(isTailCall); 7977 7978 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7979 return CallResult.second; 7980 } 7981 7982 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 7983 SDValue Dst, SDValue Src, SDValue Size, 7984 Type *SizeTy, unsigned ElemSz, 7985 bool isTailCall, 7986 MachinePointerInfo DstPtrInfo, 7987 MachinePointerInfo SrcPtrInfo) { 7988 // Emit a library call. 7989 TargetLowering::ArgListTy Args; 7990 TargetLowering::ArgListEntry Entry; 7991 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7992 Entry.Node = Dst; 7993 Args.push_back(Entry); 7994 7995 Entry.Node = Src; 7996 Args.push_back(Entry); 7997 7998 Entry.Ty = SizeTy; 7999 Entry.Node = Size; 8000 Args.push_back(Entry); 8001 8002 RTLIB::Libcall LibraryCall = 8003 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 8004 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 8005 report_fatal_error("Unsupported element size"); 8006 8007 TargetLowering::CallLoweringInfo CLI(*this); 8008 CLI.setDebugLoc(dl) 8009 .setChain(Chain) 8010 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 8011 Type::getVoidTy(*getContext()), 8012 getExternalSymbol(TLI->getLibcallName(LibraryCall), 8013 TLI->getPointerTy(getDataLayout())), 8014 std::move(Args)) 8015 .setDiscardResult() 8016 .setTailCall(isTailCall); 8017 8018 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 8019 return CallResult.second; 8020 } 8021 8022 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 8023 SDValue Src, SDValue Size, Align Alignment, 8024 bool isVol, bool isTailCall, 8025 MachinePointerInfo DstPtrInfo, 8026 MachinePointerInfo SrcPtrInfo, 8027 const AAMDNodes &AAInfo, AAResults *AA) { 8028 // Check to see if we should lower the memmove to loads and stores first. 8029 // For cases within the target-specified limits, this is the best choice. 8030 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 8031 if (ConstantSize) { 8032 // Memmove with size zero? Just return the original chain. 8033 if (ConstantSize->isZero()) 8034 return Chain; 8035 8036 SDValue Result = getMemmoveLoadsAndStores( 8037 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 8038 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 8039 if (Result.getNode()) 8040 return Result; 8041 } 8042 8043 // Then check to see if we should lower the memmove with target-specific 8044 // code. If the target chooses to do this, this is the next best. 8045 if (TSI) { 8046 SDValue Result = 8047 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 8048 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 8049 if (Result.getNode()) 8050 return Result; 8051 } 8052 8053 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 8054 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 8055 8056 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 8057 // not be safe. See memcpy above for more details. 8058 8059 // Emit a library call. 8060 TargetLowering::ArgListTy Args; 8061 TargetLowering::ArgListEntry Entry; 8062 Entry.Ty = PointerType::getUnqual(*getContext()); 8063 Entry.Node = Dst; Args.push_back(Entry); 8064 Entry.Node = Src; Args.push_back(Entry); 8065 8066 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 8067 Entry.Node = Size; Args.push_back(Entry); 8068 // FIXME: pass in SDLoc 8069 TargetLowering::CallLoweringInfo CLI(*this); 8070 CLI.setDebugLoc(dl) 8071 .setChain(Chain) 8072 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 8073 Dst.getValueType().getTypeForEVT(*getContext()), 8074 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 8075 TLI->getPointerTy(getDataLayout())), 8076 std::move(Args)) 8077 .setDiscardResult() 8078 .setTailCall(isTailCall); 8079 8080 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 8081 return CallResult.second; 8082 } 8083 8084 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 8085 SDValue Dst, SDValue Src, SDValue Size, 8086 Type *SizeTy, unsigned ElemSz, 8087 bool isTailCall, 8088 MachinePointerInfo DstPtrInfo, 8089 MachinePointerInfo SrcPtrInfo) { 8090 // Emit a library call. 8091 TargetLowering::ArgListTy Args; 8092 TargetLowering::ArgListEntry Entry; 8093 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 8094 Entry.Node = Dst; 8095 Args.push_back(Entry); 8096 8097 Entry.Node = Src; 8098 Args.push_back(Entry); 8099 8100 Entry.Ty = SizeTy; 8101 Entry.Node = Size; 8102 Args.push_back(Entry); 8103 8104 RTLIB::Libcall LibraryCall = 8105 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 8106 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 8107 report_fatal_error("Unsupported element size"); 8108 8109 TargetLowering::CallLoweringInfo CLI(*this); 8110 CLI.setDebugLoc(dl) 8111 .setChain(Chain) 8112 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 8113 Type::getVoidTy(*getContext()), 8114 getExternalSymbol(TLI->getLibcallName(LibraryCall), 8115 TLI->getPointerTy(getDataLayout())), 8116 std::move(Args)) 8117 .setDiscardResult() 8118 .setTailCall(isTailCall); 8119 8120 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 8121 return CallResult.second; 8122 } 8123 8124 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 8125 SDValue Src, SDValue Size, Align Alignment, 8126 bool isVol, bool AlwaysInline, bool isTailCall, 8127 MachinePointerInfo DstPtrInfo, 8128 const AAMDNodes &AAInfo) { 8129 // Check to see if we should lower the memset to stores first. 8130 // For cases within the target-specified limits, this is the best choice. 8131 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 8132 if (ConstantSize) { 8133 // Memset with size zero? Just return the original chain. 8134 if (ConstantSize->isZero()) 8135 return Chain; 8136 8137 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 8138 ConstantSize->getZExtValue(), Alignment, 8139 isVol, false, DstPtrInfo, AAInfo); 8140 8141 if (Result.getNode()) 8142 return Result; 8143 } 8144 8145 // Then check to see if we should lower the memset with target-specific 8146 // code. If the target chooses to do this, this is the next best. 8147 if (TSI) { 8148 SDValue Result = TSI->EmitTargetCodeForMemset( 8149 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo); 8150 if (Result.getNode()) 8151 return Result; 8152 } 8153 8154 // If we really need inline code and the target declined to provide it, 8155 // use a (potentially long) sequence of loads and stores. 8156 if (AlwaysInline) { 8157 assert(ConstantSize && "AlwaysInline requires a constant size!"); 8158 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 8159 ConstantSize->getZExtValue(), Alignment, 8160 isVol, true, DstPtrInfo, AAInfo); 8161 assert(Result && 8162 "getMemsetStores must return a valid sequence when AlwaysInline"); 8163 return Result; 8164 } 8165 8166 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 8167 8168 // Emit a library call. 8169 auto &Ctx = *getContext(); 8170 const auto& DL = getDataLayout(); 8171 8172 TargetLowering::CallLoweringInfo CLI(*this); 8173 // FIXME: pass in SDLoc 8174 CLI.setDebugLoc(dl).setChain(Chain); 8175 8176 const char *BzeroName = getTargetLoweringInfo().getLibcallName(RTLIB::BZERO); 8177 8178 // Helper function to create an Entry from Node and Type. 8179 const auto CreateEntry = [](SDValue Node, Type *Ty) { 8180 TargetLowering::ArgListEntry Entry; 8181 Entry.Node = Node; 8182 Entry.Ty = Ty; 8183 return Entry; 8184 }; 8185 8186 // If zeroing out and bzero is present, use it. 8187 if (isNullConstant(Src) && BzeroName) { 8188 TargetLowering::ArgListTy Args; 8189 Args.push_back(CreateEntry(Dst, PointerType::getUnqual(Ctx))); 8190 Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx))); 8191 CLI.setLibCallee( 8192 TLI->getLibcallCallingConv(RTLIB::BZERO), Type::getVoidTy(Ctx), 8193 getExternalSymbol(BzeroName, TLI->getPointerTy(DL)), std::move(Args)); 8194 } else { 8195 TargetLowering::ArgListTy Args; 8196 Args.push_back(CreateEntry(Dst, PointerType::getUnqual(Ctx))); 8197 Args.push_back(CreateEntry(Src, Src.getValueType().getTypeForEVT(Ctx))); 8198 Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx))); 8199 CLI.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 8200 Dst.getValueType().getTypeForEVT(Ctx), 8201 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 8202 TLI->getPointerTy(DL)), 8203 std::move(Args)); 8204 } 8205 8206 CLI.setDiscardResult().setTailCall(isTailCall); 8207 8208 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 8209 return CallResult.second; 8210 } 8211 8212 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 8213 SDValue Dst, SDValue Value, SDValue Size, 8214 Type *SizeTy, unsigned ElemSz, 8215 bool isTailCall, 8216 MachinePointerInfo DstPtrInfo) { 8217 // Emit a library call. 8218 TargetLowering::ArgListTy Args; 8219 TargetLowering::ArgListEntry Entry; 8220 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 8221 Entry.Node = Dst; 8222 Args.push_back(Entry); 8223 8224 Entry.Ty = Type::getInt8Ty(*getContext()); 8225 Entry.Node = Value; 8226 Args.push_back(Entry); 8227 8228 Entry.Ty = SizeTy; 8229 Entry.Node = Size; 8230 Args.push_back(Entry); 8231 8232 RTLIB::Libcall LibraryCall = 8233 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 8234 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 8235 report_fatal_error("Unsupported element size"); 8236 8237 TargetLowering::CallLoweringInfo CLI(*this); 8238 CLI.setDebugLoc(dl) 8239 .setChain(Chain) 8240 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 8241 Type::getVoidTy(*getContext()), 8242 getExternalSymbol(TLI->getLibcallName(LibraryCall), 8243 TLI->getPointerTy(getDataLayout())), 8244 std::move(Args)) 8245 .setDiscardResult() 8246 .setTailCall(isTailCall); 8247 8248 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 8249 return CallResult.second; 8250 } 8251 8252 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 8253 SDVTList VTList, ArrayRef<SDValue> Ops, 8254 MachineMemOperand *MMO) { 8255 FoldingSetNodeID ID; 8256 ID.AddInteger(MemVT.getRawBits()); 8257 AddNodeIDNode(ID, Opcode, VTList, Ops); 8258 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8259 ID.AddInteger(MMO->getFlags()); 8260 void* IP = nullptr; 8261 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8262 cast<AtomicSDNode>(E)->refineAlignment(MMO); 8263 return SDValue(E, 0); 8264 } 8265 8266 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 8267 VTList, MemVT, MMO); 8268 createOperands(N, Ops); 8269 8270 CSEMap.InsertNode(N, IP); 8271 InsertNode(N); 8272 return SDValue(N, 0); 8273 } 8274 8275 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 8276 EVT MemVT, SDVTList VTs, SDValue Chain, 8277 SDValue Ptr, SDValue Cmp, SDValue Swp, 8278 MachineMemOperand *MMO) { 8279 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 8280 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 8281 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 8282 8283 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 8284 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 8285 } 8286 8287 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 8288 SDValue Chain, SDValue Ptr, SDValue Val, 8289 MachineMemOperand *MMO) { 8290 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 8291 Opcode == ISD::ATOMIC_LOAD_SUB || 8292 Opcode == ISD::ATOMIC_LOAD_AND || 8293 Opcode == ISD::ATOMIC_LOAD_CLR || 8294 Opcode == ISD::ATOMIC_LOAD_OR || 8295 Opcode == ISD::ATOMIC_LOAD_XOR || 8296 Opcode == ISD::ATOMIC_LOAD_NAND || 8297 Opcode == ISD::ATOMIC_LOAD_MIN || 8298 Opcode == ISD::ATOMIC_LOAD_MAX || 8299 Opcode == ISD::ATOMIC_LOAD_UMIN || 8300 Opcode == ISD::ATOMIC_LOAD_UMAX || 8301 Opcode == ISD::ATOMIC_LOAD_FADD || 8302 Opcode == ISD::ATOMIC_LOAD_FSUB || 8303 Opcode == ISD::ATOMIC_LOAD_FMAX || 8304 Opcode == ISD::ATOMIC_LOAD_FMIN || 8305 Opcode == ISD::ATOMIC_LOAD_UINC_WRAP || 8306 Opcode == ISD::ATOMIC_LOAD_UDEC_WRAP || 8307 Opcode == ISD::ATOMIC_SWAP || 8308 Opcode == ISD::ATOMIC_STORE) && 8309 "Invalid Atomic Op"); 8310 8311 EVT VT = Val.getValueType(); 8312 8313 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 8314 getVTList(VT, MVT::Other); 8315 SDValue Ops[] = {Chain, Ptr, Val}; 8316 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 8317 } 8318 8319 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 8320 EVT VT, SDValue Chain, SDValue Ptr, 8321 MachineMemOperand *MMO) { 8322 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 8323 8324 SDVTList VTs = getVTList(VT, MVT::Other); 8325 SDValue Ops[] = {Chain, Ptr}; 8326 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 8327 } 8328 8329 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 8330 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 8331 if (Ops.size() == 1) 8332 return Ops[0]; 8333 8334 SmallVector<EVT, 4> VTs; 8335 VTs.reserve(Ops.size()); 8336 for (const SDValue &Op : Ops) 8337 VTs.push_back(Op.getValueType()); 8338 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 8339 } 8340 8341 SDValue SelectionDAG::getMemIntrinsicNode( 8342 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 8343 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 8344 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 8345 if (!Size && MemVT.isScalableVector()) 8346 Size = MemoryLocation::UnknownSize; 8347 else if (!Size) 8348 Size = MemVT.getStoreSize(); 8349 8350 MachineFunction &MF = getMachineFunction(); 8351 MachineMemOperand *MMO = 8352 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 8353 8354 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 8355 } 8356 8357 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 8358 SDVTList VTList, 8359 ArrayRef<SDValue> Ops, EVT MemVT, 8360 MachineMemOperand *MMO) { 8361 assert((Opcode == ISD::INTRINSIC_VOID || 8362 Opcode == ISD::INTRINSIC_W_CHAIN || 8363 Opcode == ISD::PREFETCH || 8364 (Opcode <= (unsigned)std::numeric_limits<int>::max() && 8365 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 8366 "Opcode is not a memory-accessing opcode!"); 8367 8368 // Memoize the node unless it returns a glue result. 8369 MemIntrinsicSDNode *N; 8370 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 8371 FoldingSetNodeID ID; 8372 AddNodeIDNode(ID, Opcode, VTList, Ops); 8373 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 8374 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 8375 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8376 ID.AddInteger(MMO->getFlags()); 8377 ID.AddInteger(MemVT.getRawBits()); 8378 void *IP = nullptr; 8379 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8380 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 8381 return SDValue(E, 0); 8382 } 8383 8384 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 8385 VTList, MemVT, MMO); 8386 createOperands(N, Ops); 8387 8388 CSEMap.InsertNode(N, IP); 8389 } else { 8390 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 8391 VTList, MemVT, MMO); 8392 createOperands(N, Ops); 8393 } 8394 InsertNode(N); 8395 SDValue V(N, 0); 8396 NewSDValueDbgMsg(V, "Creating new node: ", this); 8397 return V; 8398 } 8399 8400 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 8401 SDValue Chain, int FrameIndex, 8402 int64_t Size, int64_t Offset) { 8403 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 8404 const auto VTs = getVTList(MVT::Other); 8405 SDValue Ops[2] = { 8406 Chain, 8407 getFrameIndex(FrameIndex, 8408 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 8409 true)}; 8410 8411 FoldingSetNodeID ID; 8412 AddNodeIDNode(ID, Opcode, VTs, Ops); 8413 ID.AddInteger(FrameIndex); 8414 ID.AddInteger(Size); 8415 ID.AddInteger(Offset); 8416 void *IP = nullptr; 8417 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 8418 return SDValue(E, 0); 8419 8420 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 8421 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 8422 createOperands(N, Ops); 8423 CSEMap.InsertNode(N, IP); 8424 InsertNode(N); 8425 SDValue V(N, 0); 8426 NewSDValueDbgMsg(V, "Creating new node: ", this); 8427 return V; 8428 } 8429 8430 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 8431 uint64_t Guid, uint64_t Index, 8432 uint32_t Attr) { 8433 const unsigned Opcode = ISD::PSEUDO_PROBE; 8434 const auto VTs = getVTList(MVT::Other); 8435 SDValue Ops[] = {Chain}; 8436 FoldingSetNodeID ID; 8437 AddNodeIDNode(ID, Opcode, VTs, Ops); 8438 ID.AddInteger(Guid); 8439 ID.AddInteger(Index); 8440 void *IP = nullptr; 8441 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 8442 return SDValue(E, 0); 8443 8444 auto *N = newSDNode<PseudoProbeSDNode>( 8445 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 8446 createOperands(N, Ops); 8447 CSEMap.InsertNode(N, IP); 8448 InsertNode(N); 8449 SDValue V(N, 0); 8450 NewSDValueDbgMsg(V, "Creating new node: ", this); 8451 return V; 8452 } 8453 8454 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 8455 /// MachinePointerInfo record from it. This is particularly useful because the 8456 /// code generator has many cases where it doesn't bother passing in a 8457 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 8458 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 8459 SelectionDAG &DAG, SDValue Ptr, 8460 int64_t Offset = 0) { 8461 // If this is FI+Offset, we can model it. 8462 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 8463 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 8464 FI->getIndex(), Offset); 8465 8466 // If this is (FI+Offset1)+Offset2, we can model it. 8467 if (Ptr.getOpcode() != ISD::ADD || 8468 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 8469 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 8470 return Info; 8471 8472 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 8473 return MachinePointerInfo::getFixedStack( 8474 DAG.getMachineFunction(), FI, 8475 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 8476 } 8477 8478 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 8479 /// MachinePointerInfo record from it. This is particularly useful because the 8480 /// code generator has many cases where it doesn't bother passing in a 8481 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 8482 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 8483 SelectionDAG &DAG, SDValue Ptr, 8484 SDValue OffsetOp) { 8485 // If the 'Offset' value isn't a constant, we can't handle this. 8486 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 8487 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 8488 if (OffsetOp.isUndef()) 8489 return InferPointerInfo(Info, DAG, Ptr); 8490 return Info; 8491 } 8492 8493 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 8494 EVT VT, const SDLoc &dl, SDValue Chain, 8495 SDValue Ptr, SDValue Offset, 8496 MachinePointerInfo PtrInfo, EVT MemVT, 8497 Align Alignment, 8498 MachineMemOperand::Flags MMOFlags, 8499 const AAMDNodes &AAInfo, const MDNode *Ranges) { 8500 assert(Chain.getValueType() == MVT::Other && 8501 "Invalid chain type"); 8502 8503 MMOFlags |= MachineMemOperand::MOLoad; 8504 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 8505 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 8506 // clients. 8507 if (PtrInfo.V.isNull()) 8508 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 8509 8510 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 8511 MachineFunction &MF = getMachineFunction(); 8512 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 8513 Alignment, AAInfo, Ranges); 8514 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 8515 } 8516 8517 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 8518 EVT VT, const SDLoc &dl, SDValue Chain, 8519 SDValue Ptr, SDValue Offset, EVT MemVT, 8520 MachineMemOperand *MMO) { 8521 if (VT == MemVT) { 8522 ExtType = ISD::NON_EXTLOAD; 8523 } else if (ExtType == ISD::NON_EXTLOAD) { 8524 assert(VT == MemVT && "Non-extending load from different memory type!"); 8525 } else { 8526 // Extending load. 8527 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 8528 "Should only be an extending load, not truncating!"); 8529 assert(VT.isInteger() == MemVT.isInteger() && 8530 "Cannot convert from FP to Int or Int -> FP!"); 8531 assert(VT.isVector() == MemVT.isVector() && 8532 "Cannot use an ext load to convert to or from a vector!"); 8533 assert((!VT.isVector() || 8534 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 8535 "Cannot use an ext load to change the number of vector elements!"); 8536 } 8537 8538 bool Indexed = AM != ISD::UNINDEXED; 8539 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 8540 8541 SDVTList VTs = Indexed ? 8542 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 8543 SDValue Ops[] = { Chain, Ptr, Offset }; 8544 FoldingSetNodeID ID; 8545 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 8546 ID.AddInteger(MemVT.getRawBits()); 8547 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 8548 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 8549 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8550 ID.AddInteger(MMO->getFlags()); 8551 void *IP = nullptr; 8552 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8553 cast<LoadSDNode>(E)->refineAlignment(MMO); 8554 return SDValue(E, 0); 8555 } 8556 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8557 ExtType, MemVT, MMO); 8558 createOperands(N, Ops); 8559 8560 CSEMap.InsertNode(N, IP); 8561 InsertNode(N); 8562 SDValue V(N, 0); 8563 NewSDValueDbgMsg(V, "Creating new node: ", this); 8564 return V; 8565 } 8566 8567 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8568 SDValue Ptr, MachinePointerInfo PtrInfo, 8569 MaybeAlign Alignment, 8570 MachineMemOperand::Flags MMOFlags, 8571 const AAMDNodes &AAInfo, const MDNode *Ranges) { 8572 SDValue Undef = getUNDEF(Ptr.getValueType()); 8573 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 8574 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 8575 } 8576 8577 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8578 SDValue Ptr, MachineMemOperand *MMO) { 8579 SDValue Undef = getUNDEF(Ptr.getValueType()); 8580 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 8581 VT, MMO); 8582 } 8583 8584 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 8585 EVT VT, SDValue Chain, SDValue Ptr, 8586 MachinePointerInfo PtrInfo, EVT MemVT, 8587 MaybeAlign Alignment, 8588 MachineMemOperand::Flags MMOFlags, 8589 const AAMDNodes &AAInfo) { 8590 SDValue Undef = getUNDEF(Ptr.getValueType()); 8591 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 8592 MemVT, Alignment, MMOFlags, AAInfo); 8593 } 8594 8595 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 8596 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 8597 MachineMemOperand *MMO) { 8598 SDValue Undef = getUNDEF(Ptr.getValueType()); 8599 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 8600 MemVT, MMO); 8601 } 8602 8603 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 8604 SDValue Base, SDValue Offset, 8605 ISD::MemIndexedMode AM) { 8606 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 8607 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 8608 // Don't propagate the invariant or dereferenceable flags. 8609 auto MMOFlags = 8610 LD->getMemOperand()->getFlags() & 8611 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8612 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 8613 LD->getChain(), Base, Offset, LD->getPointerInfo(), 8614 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 8615 } 8616 8617 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 8618 SDValue Ptr, MachinePointerInfo PtrInfo, 8619 Align Alignment, 8620 MachineMemOperand::Flags MMOFlags, 8621 const AAMDNodes &AAInfo) { 8622 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8623 8624 MMOFlags |= MachineMemOperand::MOStore; 8625 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8626 8627 if (PtrInfo.V.isNull()) 8628 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8629 8630 MachineFunction &MF = getMachineFunction(); 8631 uint64_t Size = 8632 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 8633 MachineMemOperand *MMO = 8634 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 8635 return getStore(Chain, dl, Val, Ptr, MMO); 8636 } 8637 8638 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 8639 SDValue Ptr, MachineMemOperand *MMO) { 8640 assert(Chain.getValueType() == MVT::Other && 8641 "Invalid chain type"); 8642 EVT VT = Val.getValueType(); 8643 SDVTList VTs = getVTList(MVT::Other); 8644 SDValue Undef = getUNDEF(Ptr.getValueType()); 8645 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 8646 FoldingSetNodeID ID; 8647 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 8648 ID.AddInteger(VT.getRawBits()); 8649 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 8650 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 8651 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8652 ID.AddInteger(MMO->getFlags()); 8653 void *IP = nullptr; 8654 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8655 cast<StoreSDNode>(E)->refineAlignment(MMO); 8656 return SDValue(E, 0); 8657 } 8658 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8659 ISD::UNINDEXED, false, VT, MMO); 8660 createOperands(N, Ops); 8661 8662 CSEMap.InsertNode(N, IP); 8663 InsertNode(N); 8664 SDValue V(N, 0); 8665 NewSDValueDbgMsg(V, "Creating new node: ", this); 8666 return V; 8667 } 8668 8669 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 8670 SDValue Ptr, MachinePointerInfo PtrInfo, 8671 EVT SVT, Align Alignment, 8672 MachineMemOperand::Flags MMOFlags, 8673 const AAMDNodes &AAInfo) { 8674 assert(Chain.getValueType() == MVT::Other && 8675 "Invalid chain type"); 8676 8677 MMOFlags |= MachineMemOperand::MOStore; 8678 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8679 8680 if (PtrInfo.V.isNull()) 8681 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8682 8683 MachineFunction &MF = getMachineFunction(); 8684 MachineMemOperand *MMO = MF.getMachineMemOperand( 8685 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 8686 Alignment, AAInfo); 8687 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 8688 } 8689 8690 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 8691 SDValue Ptr, EVT SVT, 8692 MachineMemOperand *MMO) { 8693 EVT VT = Val.getValueType(); 8694 8695 assert(Chain.getValueType() == MVT::Other && 8696 "Invalid chain type"); 8697 if (VT == SVT) 8698 return getStore(Chain, dl, Val, Ptr, MMO); 8699 8700 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8701 "Should only be a truncating store, not extending!"); 8702 assert(VT.isInteger() == SVT.isInteger() && 8703 "Can't do FP-INT conversion!"); 8704 assert(VT.isVector() == SVT.isVector() && 8705 "Cannot use trunc store to convert to or from a vector!"); 8706 assert((!VT.isVector() || 8707 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8708 "Cannot use trunc store to change the number of vector elements!"); 8709 8710 SDVTList VTs = getVTList(MVT::Other); 8711 SDValue Undef = getUNDEF(Ptr.getValueType()); 8712 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 8713 FoldingSetNodeID ID; 8714 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 8715 ID.AddInteger(SVT.getRawBits()); 8716 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 8717 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 8718 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8719 ID.AddInteger(MMO->getFlags()); 8720 void *IP = nullptr; 8721 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8722 cast<StoreSDNode>(E)->refineAlignment(MMO); 8723 return SDValue(E, 0); 8724 } 8725 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8726 ISD::UNINDEXED, true, SVT, MMO); 8727 createOperands(N, Ops); 8728 8729 CSEMap.InsertNode(N, IP); 8730 InsertNode(N); 8731 SDValue V(N, 0); 8732 NewSDValueDbgMsg(V, "Creating new node: ", this); 8733 return V; 8734 } 8735 8736 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 8737 SDValue Base, SDValue Offset, 8738 ISD::MemIndexedMode AM) { 8739 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 8740 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 8741 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8742 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 8743 FoldingSetNodeID ID; 8744 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 8745 ID.AddInteger(ST->getMemoryVT().getRawBits()); 8746 ID.AddInteger(ST->getRawSubclassData()); 8747 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 8748 ID.AddInteger(ST->getMemOperand()->getFlags()); 8749 void *IP = nullptr; 8750 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 8751 return SDValue(E, 0); 8752 8753 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8754 ST->isTruncatingStore(), ST->getMemoryVT(), 8755 ST->getMemOperand()); 8756 createOperands(N, Ops); 8757 8758 CSEMap.InsertNode(N, IP); 8759 InsertNode(N); 8760 SDValue V(N, 0); 8761 NewSDValueDbgMsg(V, "Creating new node: ", this); 8762 return V; 8763 } 8764 8765 SDValue SelectionDAG::getLoadVP( 8766 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, 8767 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, 8768 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 8769 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8770 const MDNode *Ranges, bool IsExpanding) { 8771 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8772 8773 MMOFlags |= MachineMemOperand::MOLoad; 8774 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 8775 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 8776 // clients. 8777 if (PtrInfo.V.isNull()) 8778 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 8779 8780 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 8781 MachineFunction &MF = getMachineFunction(); 8782 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 8783 Alignment, AAInfo, Ranges); 8784 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT, 8785 MMO, IsExpanding); 8786 } 8787 8788 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM, 8789 ISD::LoadExtType ExtType, EVT VT, 8790 const SDLoc &dl, SDValue Chain, SDValue Ptr, 8791 SDValue Offset, SDValue Mask, SDValue EVL, 8792 EVT MemVT, MachineMemOperand *MMO, 8793 bool IsExpanding) { 8794 bool Indexed = AM != ISD::UNINDEXED; 8795 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 8796 8797 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 8798 : getVTList(VT, MVT::Other); 8799 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL}; 8800 FoldingSetNodeID ID; 8801 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops); 8802 ID.AddInteger(MemVT.getRawBits()); 8803 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>( 8804 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 8805 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8806 ID.AddInteger(MMO->getFlags()); 8807 void *IP = nullptr; 8808 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8809 cast<VPLoadSDNode>(E)->refineAlignment(MMO); 8810 return SDValue(E, 0); 8811 } 8812 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8813 ExtType, IsExpanding, MemVT, MMO); 8814 createOperands(N, Ops); 8815 8816 CSEMap.InsertNode(N, IP); 8817 InsertNode(N); 8818 SDValue V(N, 0); 8819 NewSDValueDbgMsg(V, "Creating new node: ", this); 8820 return V; 8821 } 8822 8823 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 8824 SDValue Ptr, SDValue Mask, SDValue EVL, 8825 MachinePointerInfo PtrInfo, 8826 MaybeAlign Alignment, 8827 MachineMemOperand::Flags MMOFlags, 8828 const AAMDNodes &AAInfo, const MDNode *Ranges, 8829 bool IsExpanding) { 8830 SDValue Undef = getUNDEF(Ptr.getValueType()); 8831 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 8832 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges, 8833 IsExpanding); 8834 } 8835 8836 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 8837 SDValue Ptr, SDValue Mask, SDValue EVL, 8838 MachineMemOperand *MMO, bool IsExpanding) { 8839 SDValue Undef = getUNDEF(Ptr.getValueType()); 8840 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 8841 Mask, EVL, VT, MMO, IsExpanding); 8842 } 8843 8844 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 8845 EVT VT, SDValue Chain, SDValue Ptr, 8846 SDValue Mask, SDValue EVL, 8847 MachinePointerInfo PtrInfo, EVT MemVT, 8848 MaybeAlign Alignment, 8849 MachineMemOperand::Flags MMOFlags, 8850 const AAMDNodes &AAInfo, bool IsExpanding) { 8851 SDValue Undef = getUNDEF(Ptr.getValueType()); 8852 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 8853 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr, 8854 IsExpanding); 8855 } 8856 8857 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 8858 EVT VT, SDValue Chain, SDValue Ptr, 8859 SDValue Mask, SDValue EVL, EVT MemVT, 8860 MachineMemOperand *MMO, bool IsExpanding) { 8861 SDValue Undef = getUNDEF(Ptr.getValueType()); 8862 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 8863 EVL, MemVT, MMO, IsExpanding); 8864 } 8865 8866 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, 8867 SDValue Base, SDValue Offset, 8868 ISD::MemIndexedMode AM) { 8869 auto *LD = cast<VPLoadSDNode>(OrigLoad); 8870 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 8871 // Don't propagate the invariant or dereferenceable flags. 8872 auto MMOFlags = 8873 LD->getMemOperand()->getFlags() & 8874 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8875 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 8876 LD->getChain(), Base, Offset, LD->getMask(), 8877 LD->getVectorLength(), LD->getPointerInfo(), 8878 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(), 8879 nullptr, LD->isExpandingLoad()); 8880 } 8881 8882 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 8883 SDValue Ptr, SDValue Offset, SDValue Mask, 8884 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, 8885 ISD::MemIndexedMode AM, bool IsTruncating, 8886 bool IsCompressing) { 8887 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8888 bool Indexed = AM != ISD::UNINDEXED; 8889 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 8890 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 8891 : getVTList(MVT::Other); 8892 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL}; 8893 FoldingSetNodeID ID; 8894 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8895 ID.AddInteger(MemVT.getRawBits()); 8896 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8897 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8898 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8899 ID.AddInteger(MMO->getFlags()); 8900 void *IP = nullptr; 8901 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8902 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8903 return SDValue(E, 0); 8904 } 8905 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8906 IsTruncating, IsCompressing, MemVT, MMO); 8907 createOperands(N, Ops); 8908 8909 CSEMap.InsertNode(N, IP); 8910 InsertNode(N); 8911 SDValue V(N, 0); 8912 NewSDValueDbgMsg(V, "Creating new node: ", this); 8913 return V; 8914 } 8915 8916 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8917 SDValue Val, SDValue Ptr, SDValue Mask, 8918 SDValue EVL, MachinePointerInfo PtrInfo, 8919 EVT SVT, Align Alignment, 8920 MachineMemOperand::Flags MMOFlags, 8921 const AAMDNodes &AAInfo, 8922 bool IsCompressing) { 8923 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8924 8925 MMOFlags |= MachineMemOperand::MOStore; 8926 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8927 8928 if (PtrInfo.V.isNull()) 8929 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8930 8931 MachineFunction &MF = getMachineFunction(); 8932 MachineMemOperand *MMO = MF.getMachineMemOperand( 8933 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 8934 Alignment, AAInfo); 8935 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO, 8936 IsCompressing); 8937 } 8938 8939 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8940 SDValue Val, SDValue Ptr, SDValue Mask, 8941 SDValue EVL, EVT SVT, 8942 MachineMemOperand *MMO, 8943 bool IsCompressing) { 8944 EVT VT = Val.getValueType(); 8945 8946 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8947 if (VT == SVT) 8948 return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask, 8949 EVL, VT, MMO, ISD::UNINDEXED, 8950 /*IsTruncating*/ false, IsCompressing); 8951 8952 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8953 "Should only be a truncating store, not extending!"); 8954 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8955 assert(VT.isVector() == SVT.isVector() && 8956 "Cannot use trunc store to convert to or from a vector!"); 8957 assert((!VT.isVector() || 8958 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8959 "Cannot use trunc store to change the number of vector elements!"); 8960 8961 SDVTList VTs = getVTList(MVT::Other); 8962 SDValue Undef = getUNDEF(Ptr.getValueType()); 8963 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 8964 FoldingSetNodeID ID; 8965 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8966 ID.AddInteger(SVT.getRawBits()); 8967 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8968 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8969 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8970 ID.AddInteger(MMO->getFlags()); 8971 void *IP = nullptr; 8972 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8973 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8974 return SDValue(E, 0); 8975 } 8976 auto *N = 8977 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8978 ISD::UNINDEXED, true, IsCompressing, SVT, MMO); 8979 createOperands(N, Ops); 8980 8981 CSEMap.InsertNode(N, IP); 8982 InsertNode(N); 8983 SDValue V(N, 0); 8984 NewSDValueDbgMsg(V, "Creating new node: ", this); 8985 return V; 8986 } 8987 8988 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, 8989 SDValue Base, SDValue Offset, 8990 ISD::MemIndexedMode AM) { 8991 auto *ST = cast<VPStoreSDNode>(OrigStore); 8992 assert(ST->getOffset().isUndef() && "Store is already an indexed store!"); 8993 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8994 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base, 8995 Offset, ST->getMask(), ST->getVectorLength()}; 8996 FoldingSetNodeID ID; 8997 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8998 ID.AddInteger(ST->getMemoryVT().getRawBits()); 8999 ID.AddInteger(ST->getRawSubclassData()); 9000 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 9001 ID.AddInteger(ST->getMemOperand()->getFlags()); 9002 void *IP = nullptr; 9003 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 9004 return SDValue(E, 0); 9005 9006 auto *N = newSDNode<VPStoreSDNode>( 9007 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(), 9008 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand()); 9009 createOperands(N, Ops); 9010 9011 CSEMap.InsertNode(N, IP); 9012 InsertNode(N); 9013 SDValue V(N, 0); 9014 NewSDValueDbgMsg(V, "Creating new node: ", this); 9015 return V; 9016 } 9017 9018 SDValue SelectionDAG::getStridedLoadVP( 9019 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 9020 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 9021 SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 9022 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 9023 const MDNode *Ranges, bool IsExpanding) { 9024 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 9025 9026 MMOFlags |= MachineMemOperand::MOLoad; 9027 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 9028 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 9029 // clients. 9030 if (PtrInfo.V.isNull()) 9031 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 9032 9033 uint64_t Size = MemoryLocation::UnknownSize; 9034 MachineFunction &MF = getMachineFunction(); 9035 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 9036 Alignment, AAInfo, Ranges); 9037 return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask, 9038 EVL, MemVT, MMO, IsExpanding); 9039 } 9040 9041 SDValue SelectionDAG::getStridedLoadVP( 9042 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 9043 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 9044 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) { 9045 bool Indexed = AM != ISD::UNINDEXED; 9046 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 9047 9048 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL}; 9049 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 9050 : getVTList(VT, MVT::Other); 9051 FoldingSetNodeID ID; 9052 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops); 9053 ID.AddInteger(VT.getRawBits()); 9054 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>( 9055 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 9056 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9057 9058 void *IP = nullptr; 9059 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9060 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO); 9061 return SDValue(E, 0); 9062 } 9063 9064 auto *N = 9065 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM, 9066 ExtType, IsExpanding, MemVT, MMO); 9067 createOperands(N, Ops); 9068 CSEMap.InsertNode(N, IP); 9069 InsertNode(N); 9070 SDValue V(N, 0); 9071 NewSDValueDbgMsg(V, "Creating new node: ", this); 9072 return V; 9073 } 9074 9075 SDValue SelectionDAG::getStridedLoadVP( 9076 EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride, 9077 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment, 9078 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 9079 const MDNode *Ranges, bool IsExpanding) { 9080 SDValue Undef = getUNDEF(Ptr.getValueType()); 9081 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 9082 Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment, 9083 MMOFlags, AAInfo, Ranges, IsExpanding); 9084 } 9085 9086 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain, 9087 SDValue Ptr, SDValue Stride, 9088 SDValue Mask, SDValue EVL, 9089 MachineMemOperand *MMO, 9090 bool IsExpanding) { 9091 SDValue Undef = getUNDEF(Ptr.getValueType()); 9092 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 9093 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding); 9094 } 9095 9096 SDValue SelectionDAG::getExtStridedLoadVP( 9097 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 9098 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, 9099 MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment, 9100 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 9101 bool IsExpanding) { 9102 SDValue Undef = getUNDEF(Ptr.getValueType()); 9103 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 9104 Stride, Mask, EVL, PtrInfo, MemVT, Alignment, 9105 MMOFlags, AAInfo, nullptr, IsExpanding); 9106 } 9107 9108 SDValue SelectionDAG::getExtStridedLoadVP( 9109 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 9110 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, 9111 MachineMemOperand *MMO, bool IsExpanding) { 9112 SDValue Undef = getUNDEF(Ptr.getValueType()); 9113 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 9114 Stride, Mask, EVL, MemVT, MMO, IsExpanding); 9115 } 9116 9117 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL, 9118 SDValue Base, SDValue Offset, 9119 ISD::MemIndexedMode AM) { 9120 auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad); 9121 assert(SLD->getOffset().isUndef() && 9122 "Strided load is already a indexed load!"); 9123 // Don't propagate the invariant or dereferenceable flags. 9124 auto MMOFlags = 9125 SLD->getMemOperand()->getFlags() & 9126 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 9127 return getStridedLoadVP( 9128 AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(), 9129 Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(), 9130 SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags, 9131 SLD->getAAInfo(), nullptr, SLD->isExpandingLoad()); 9132 } 9133 9134 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL, 9135 SDValue Val, SDValue Ptr, 9136 SDValue Offset, SDValue Stride, 9137 SDValue Mask, SDValue EVL, EVT MemVT, 9138 MachineMemOperand *MMO, 9139 ISD::MemIndexedMode AM, 9140 bool IsTruncating, bool IsCompressing) { 9141 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 9142 bool Indexed = AM != ISD::UNINDEXED; 9143 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 9144 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 9145 : getVTList(MVT::Other); 9146 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL}; 9147 FoldingSetNodeID ID; 9148 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 9149 ID.AddInteger(MemVT.getRawBits()); 9150 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 9151 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 9152 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9153 void *IP = nullptr; 9154 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9155 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 9156 return SDValue(E, 0); 9157 } 9158 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 9159 VTs, AM, IsTruncating, 9160 IsCompressing, MemVT, MMO); 9161 createOperands(N, Ops); 9162 9163 CSEMap.InsertNode(N, IP); 9164 InsertNode(N); 9165 SDValue V(N, 0); 9166 NewSDValueDbgMsg(V, "Creating new node: ", this); 9167 return V; 9168 } 9169 9170 SDValue SelectionDAG::getTruncStridedStoreVP( 9171 SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride, 9172 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT, 9173 Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 9174 bool IsCompressing) { 9175 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 9176 9177 MMOFlags |= MachineMemOperand::MOStore; 9178 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 9179 9180 if (PtrInfo.V.isNull()) 9181 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 9182 9183 MachineFunction &MF = getMachineFunction(); 9184 MachineMemOperand *MMO = MF.getMachineMemOperand( 9185 PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo); 9186 return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT, 9187 MMO, IsCompressing); 9188 } 9189 9190 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL, 9191 SDValue Val, SDValue Ptr, 9192 SDValue Stride, SDValue Mask, 9193 SDValue EVL, EVT SVT, 9194 MachineMemOperand *MMO, 9195 bool IsCompressing) { 9196 EVT VT = Val.getValueType(); 9197 9198 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 9199 if (VT == SVT) 9200 return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()), 9201 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED, 9202 /*IsTruncating*/ false, IsCompressing); 9203 9204 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 9205 "Should only be a truncating store, not extending!"); 9206 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 9207 assert(VT.isVector() == SVT.isVector() && 9208 "Cannot use trunc store to convert to or from a vector!"); 9209 assert((!VT.isVector() || 9210 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 9211 "Cannot use trunc store to change the number of vector elements!"); 9212 9213 SDVTList VTs = getVTList(MVT::Other); 9214 SDValue Undef = getUNDEF(Ptr.getValueType()); 9215 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL}; 9216 FoldingSetNodeID ID; 9217 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 9218 ID.AddInteger(SVT.getRawBits()); 9219 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 9220 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 9221 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9222 void *IP = nullptr; 9223 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9224 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 9225 return SDValue(E, 0); 9226 } 9227 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 9228 VTs, ISD::UNINDEXED, true, 9229 IsCompressing, SVT, MMO); 9230 createOperands(N, Ops); 9231 9232 CSEMap.InsertNode(N, IP); 9233 InsertNode(N); 9234 SDValue V(N, 0); 9235 NewSDValueDbgMsg(V, "Creating new node: ", this); 9236 return V; 9237 } 9238 9239 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore, 9240 const SDLoc &DL, SDValue Base, 9241 SDValue Offset, 9242 ISD::MemIndexedMode AM) { 9243 auto *SST = cast<VPStridedStoreSDNode>(OrigStore); 9244 assert(SST->getOffset().isUndef() && 9245 "Strided store is already an indexed store!"); 9246 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 9247 SDValue Ops[] = { 9248 SST->getChain(), SST->getValue(), Base, Offset, SST->getStride(), 9249 SST->getMask(), SST->getVectorLength()}; 9250 FoldingSetNodeID ID; 9251 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 9252 ID.AddInteger(SST->getMemoryVT().getRawBits()); 9253 ID.AddInteger(SST->getRawSubclassData()); 9254 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 9255 void *IP = nullptr; 9256 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 9257 return SDValue(E, 0); 9258 9259 auto *N = newSDNode<VPStridedStoreSDNode>( 9260 DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(), 9261 SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand()); 9262 createOperands(N, Ops); 9263 9264 CSEMap.InsertNode(N, IP); 9265 InsertNode(N); 9266 SDValue V(N, 0); 9267 NewSDValueDbgMsg(V, "Creating new node: ", this); 9268 return V; 9269 } 9270 9271 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, 9272 ArrayRef<SDValue> Ops, MachineMemOperand *MMO, 9273 ISD::MemIndexType IndexType) { 9274 assert(Ops.size() == 6 && "Incompatible number of operands"); 9275 9276 FoldingSetNodeID ID; 9277 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops); 9278 ID.AddInteger(VT.getRawBits()); 9279 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>( 9280 dl.getIROrder(), VTs, VT, MMO, IndexType)); 9281 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9282 ID.AddInteger(MMO->getFlags()); 9283 void *IP = nullptr; 9284 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 9285 cast<VPGatherSDNode>(E)->refineAlignment(MMO); 9286 return SDValue(E, 0); 9287 } 9288 9289 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 9290 VT, MMO, IndexType); 9291 createOperands(N, Ops); 9292 9293 assert(N->getMask().getValueType().getVectorElementCount() == 9294 N->getValueType(0).getVectorElementCount() && 9295 "Vector width mismatch between mask and data"); 9296 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 9297 N->getValueType(0).getVectorElementCount().isScalable() && 9298 "Scalable flags of index and data do not match"); 9299 assert(ElementCount::isKnownGE( 9300 N->getIndex().getValueType().getVectorElementCount(), 9301 N->getValueType(0).getVectorElementCount()) && 9302 "Vector width mismatch between index and data"); 9303 assert(isa<ConstantSDNode>(N->getScale()) && 9304 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 9305 "Scale should be a constant power of 2"); 9306 9307 CSEMap.InsertNode(N, IP); 9308 InsertNode(N); 9309 SDValue V(N, 0); 9310 NewSDValueDbgMsg(V, "Creating new node: ", this); 9311 return V; 9312 } 9313 9314 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, 9315 ArrayRef<SDValue> Ops, 9316 MachineMemOperand *MMO, 9317 ISD::MemIndexType IndexType) { 9318 assert(Ops.size() == 7 && "Incompatible number of operands"); 9319 9320 FoldingSetNodeID ID; 9321 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops); 9322 ID.AddInteger(VT.getRawBits()); 9323 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>( 9324 dl.getIROrder(), VTs, VT, MMO, IndexType)); 9325 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9326 ID.AddInteger(MMO->getFlags()); 9327 void *IP = nullptr; 9328 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 9329 cast<VPScatterSDNode>(E)->refineAlignment(MMO); 9330 return SDValue(E, 0); 9331 } 9332 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 9333 VT, MMO, IndexType); 9334 createOperands(N, Ops); 9335 9336 assert(N->getMask().getValueType().getVectorElementCount() == 9337 N->getValue().getValueType().getVectorElementCount() && 9338 "Vector width mismatch between mask and data"); 9339 assert( 9340 N->getIndex().getValueType().getVectorElementCount().isScalable() == 9341 N->getValue().getValueType().getVectorElementCount().isScalable() && 9342 "Scalable flags of index and data do not match"); 9343 assert(ElementCount::isKnownGE( 9344 N->getIndex().getValueType().getVectorElementCount(), 9345 N->getValue().getValueType().getVectorElementCount()) && 9346 "Vector width mismatch between index and data"); 9347 assert(isa<ConstantSDNode>(N->getScale()) && 9348 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 9349 "Scale should be a constant power of 2"); 9350 9351 CSEMap.InsertNode(N, IP); 9352 InsertNode(N); 9353 SDValue V(N, 0); 9354 NewSDValueDbgMsg(V, "Creating new node: ", this); 9355 return V; 9356 } 9357 9358 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 9359 SDValue Base, SDValue Offset, SDValue Mask, 9360 SDValue PassThru, EVT MemVT, 9361 MachineMemOperand *MMO, 9362 ISD::MemIndexedMode AM, 9363 ISD::LoadExtType ExtTy, bool isExpanding) { 9364 bool Indexed = AM != ISD::UNINDEXED; 9365 assert((Indexed || Offset.isUndef()) && 9366 "Unindexed masked load with an offset!"); 9367 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 9368 : getVTList(VT, MVT::Other); 9369 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 9370 FoldingSetNodeID ID; 9371 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 9372 ID.AddInteger(MemVT.getRawBits()); 9373 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 9374 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 9375 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9376 ID.AddInteger(MMO->getFlags()); 9377 void *IP = nullptr; 9378 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 9379 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 9380 return SDValue(E, 0); 9381 } 9382 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 9383 AM, ExtTy, isExpanding, MemVT, MMO); 9384 createOperands(N, Ops); 9385 9386 CSEMap.InsertNode(N, IP); 9387 InsertNode(N); 9388 SDValue V(N, 0); 9389 NewSDValueDbgMsg(V, "Creating new node: ", this); 9390 return V; 9391 } 9392 9393 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 9394 SDValue Base, SDValue Offset, 9395 ISD::MemIndexedMode AM) { 9396 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 9397 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 9398 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 9399 Offset, LD->getMask(), LD->getPassThru(), 9400 LD->getMemoryVT(), LD->getMemOperand(), AM, 9401 LD->getExtensionType(), LD->isExpandingLoad()); 9402 } 9403 9404 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 9405 SDValue Val, SDValue Base, SDValue Offset, 9406 SDValue Mask, EVT MemVT, 9407 MachineMemOperand *MMO, 9408 ISD::MemIndexedMode AM, bool IsTruncating, 9409 bool IsCompressing) { 9410 assert(Chain.getValueType() == MVT::Other && 9411 "Invalid chain type"); 9412 bool Indexed = AM != ISD::UNINDEXED; 9413 assert((Indexed || Offset.isUndef()) && 9414 "Unindexed masked store with an offset!"); 9415 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 9416 : getVTList(MVT::Other); 9417 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 9418 FoldingSetNodeID ID; 9419 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 9420 ID.AddInteger(MemVT.getRawBits()); 9421 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 9422 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 9423 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9424 ID.AddInteger(MMO->getFlags()); 9425 void *IP = nullptr; 9426 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 9427 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 9428 return SDValue(E, 0); 9429 } 9430 auto *N = 9431 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 9432 IsTruncating, IsCompressing, MemVT, MMO); 9433 createOperands(N, Ops); 9434 9435 CSEMap.InsertNode(N, IP); 9436 InsertNode(N); 9437 SDValue V(N, 0); 9438 NewSDValueDbgMsg(V, "Creating new node: ", this); 9439 return V; 9440 } 9441 9442 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 9443 SDValue Base, SDValue Offset, 9444 ISD::MemIndexedMode AM) { 9445 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 9446 assert(ST->getOffset().isUndef() && 9447 "Masked store is already a indexed store!"); 9448 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 9449 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 9450 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 9451 } 9452 9453 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, 9454 ArrayRef<SDValue> Ops, 9455 MachineMemOperand *MMO, 9456 ISD::MemIndexType IndexType, 9457 ISD::LoadExtType ExtTy) { 9458 assert(Ops.size() == 6 && "Incompatible number of operands"); 9459 9460 FoldingSetNodeID ID; 9461 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 9462 ID.AddInteger(MemVT.getRawBits()); 9463 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 9464 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy)); 9465 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9466 ID.AddInteger(MMO->getFlags()); 9467 void *IP = nullptr; 9468 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 9469 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 9470 return SDValue(E, 0); 9471 } 9472 9473 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 9474 VTs, MemVT, MMO, IndexType, ExtTy); 9475 createOperands(N, Ops); 9476 9477 assert(N->getPassThru().getValueType() == N->getValueType(0) && 9478 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 9479 assert(N->getMask().getValueType().getVectorElementCount() == 9480 N->getValueType(0).getVectorElementCount() && 9481 "Vector width mismatch between mask and data"); 9482 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 9483 N->getValueType(0).getVectorElementCount().isScalable() && 9484 "Scalable flags of index and data do not match"); 9485 assert(ElementCount::isKnownGE( 9486 N->getIndex().getValueType().getVectorElementCount(), 9487 N->getValueType(0).getVectorElementCount()) && 9488 "Vector width mismatch between index and data"); 9489 assert(isa<ConstantSDNode>(N->getScale()) && 9490 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 9491 "Scale should be a constant power of 2"); 9492 9493 CSEMap.InsertNode(N, IP); 9494 InsertNode(N); 9495 SDValue V(N, 0); 9496 NewSDValueDbgMsg(V, "Creating new node: ", this); 9497 return V; 9498 } 9499 9500 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, 9501 ArrayRef<SDValue> Ops, 9502 MachineMemOperand *MMO, 9503 ISD::MemIndexType IndexType, 9504 bool IsTrunc) { 9505 assert(Ops.size() == 6 && "Incompatible number of operands"); 9506 9507 FoldingSetNodeID ID; 9508 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 9509 ID.AddInteger(MemVT.getRawBits()); 9510 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 9511 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc)); 9512 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9513 ID.AddInteger(MMO->getFlags()); 9514 void *IP = nullptr; 9515 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 9516 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 9517 return SDValue(E, 0); 9518 } 9519 9520 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 9521 VTs, MemVT, MMO, IndexType, IsTrunc); 9522 createOperands(N, Ops); 9523 9524 assert(N->getMask().getValueType().getVectorElementCount() == 9525 N->getValue().getValueType().getVectorElementCount() && 9526 "Vector width mismatch between mask and data"); 9527 assert( 9528 N->getIndex().getValueType().getVectorElementCount().isScalable() == 9529 N->getValue().getValueType().getVectorElementCount().isScalable() && 9530 "Scalable flags of index and data do not match"); 9531 assert(ElementCount::isKnownGE( 9532 N->getIndex().getValueType().getVectorElementCount(), 9533 N->getValue().getValueType().getVectorElementCount()) && 9534 "Vector width mismatch between index and data"); 9535 assert(isa<ConstantSDNode>(N->getScale()) && 9536 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 9537 "Scale should be a constant power of 2"); 9538 9539 CSEMap.InsertNode(N, IP); 9540 InsertNode(N); 9541 SDValue V(N, 0); 9542 NewSDValueDbgMsg(V, "Creating new node: ", this); 9543 return V; 9544 } 9545 9546 SDValue SelectionDAG::getGetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, 9547 EVT MemVT, MachineMemOperand *MMO) { 9548 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 9549 SDVTList VTs = getVTList(MVT::Other); 9550 SDValue Ops[] = {Chain, Ptr}; 9551 FoldingSetNodeID ID; 9552 AddNodeIDNode(ID, ISD::GET_FPENV_MEM, VTs, Ops); 9553 ID.AddInteger(MemVT.getRawBits()); 9554 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>( 9555 ISD::GET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO)); 9556 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9557 ID.AddInteger(MMO->getFlags()); 9558 void *IP = nullptr; 9559 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 9560 return SDValue(E, 0); 9561 9562 auto *N = newSDNode<FPStateAccessSDNode>(ISD::GET_FPENV_MEM, dl.getIROrder(), 9563 dl.getDebugLoc(), VTs, MemVT, MMO); 9564 createOperands(N, Ops); 9565 9566 CSEMap.InsertNode(N, IP); 9567 InsertNode(N); 9568 SDValue V(N, 0); 9569 NewSDValueDbgMsg(V, "Creating new node: ", this); 9570 return V; 9571 } 9572 9573 SDValue SelectionDAG::getSetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, 9574 EVT MemVT, MachineMemOperand *MMO) { 9575 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 9576 SDVTList VTs = getVTList(MVT::Other); 9577 SDValue Ops[] = {Chain, Ptr}; 9578 FoldingSetNodeID ID; 9579 AddNodeIDNode(ID, ISD::SET_FPENV_MEM, VTs, Ops); 9580 ID.AddInteger(MemVT.getRawBits()); 9581 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>( 9582 ISD::SET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO)); 9583 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9584 ID.AddInteger(MMO->getFlags()); 9585 void *IP = nullptr; 9586 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 9587 return SDValue(E, 0); 9588 9589 auto *N = newSDNode<FPStateAccessSDNode>(ISD::SET_FPENV_MEM, dl.getIROrder(), 9590 dl.getDebugLoc(), VTs, MemVT, MMO); 9591 createOperands(N, Ops); 9592 9593 CSEMap.InsertNode(N, IP); 9594 InsertNode(N); 9595 SDValue V(N, 0); 9596 NewSDValueDbgMsg(V, "Creating new node: ", this); 9597 return V; 9598 } 9599 9600 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 9601 // select undef, T, F --> T (if T is a constant), otherwise F 9602 // select, ?, undef, F --> F 9603 // select, ?, T, undef --> T 9604 if (Cond.isUndef()) 9605 return isConstantValueOfAnyType(T) ? T : F; 9606 if (T.isUndef()) 9607 return F; 9608 if (F.isUndef()) 9609 return T; 9610 9611 // select true, T, F --> T 9612 // select false, T, F --> F 9613 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 9614 return CondC->isZero() ? F : T; 9615 9616 // TODO: This should simplify VSELECT with non-zero constant condition using 9617 // something like this (but check boolean contents to be complete?): 9618 if (ConstantSDNode *CondC = isConstOrConstSplat(Cond, /*AllowUndefs*/ false, 9619 /*AllowTruncation*/ true)) 9620 if (CondC->isZero()) 9621 return F; 9622 9623 // select ?, T, T --> T 9624 if (T == F) 9625 return T; 9626 9627 return SDValue(); 9628 } 9629 9630 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 9631 // shift undef, Y --> 0 (can always assume that the undef value is 0) 9632 if (X.isUndef()) 9633 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 9634 // shift X, undef --> undef (because it may shift by the bitwidth) 9635 if (Y.isUndef()) 9636 return getUNDEF(X.getValueType()); 9637 9638 // shift 0, Y --> 0 9639 // shift X, 0 --> X 9640 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 9641 return X; 9642 9643 // shift X, C >= bitwidth(X) --> undef 9644 // All vector elements must be too big (or undef) to avoid partial undefs. 9645 auto isShiftTooBig = [X](ConstantSDNode *Val) { 9646 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 9647 }; 9648 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 9649 return getUNDEF(X.getValueType()); 9650 9651 return SDValue(); 9652 } 9653 9654 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 9655 SDNodeFlags Flags) { 9656 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 9657 // (an undef operand can be chosen to be Nan/Inf), then the result of this 9658 // operation is poison. That result can be relaxed to undef. 9659 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 9660 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 9661 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 9662 (YC && YC->getValueAPF().isNaN()); 9663 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 9664 (YC && YC->getValueAPF().isInfinity()); 9665 9666 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 9667 return getUNDEF(X.getValueType()); 9668 9669 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 9670 return getUNDEF(X.getValueType()); 9671 9672 if (!YC) 9673 return SDValue(); 9674 9675 // X + -0.0 --> X 9676 if (Opcode == ISD::FADD) 9677 if (YC->getValueAPF().isNegZero()) 9678 return X; 9679 9680 // X - +0.0 --> X 9681 if (Opcode == ISD::FSUB) 9682 if (YC->getValueAPF().isPosZero()) 9683 return X; 9684 9685 // X * 1.0 --> X 9686 // X / 1.0 --> X 9687 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 9688 if (YC->getValueAPF().isExactlyValue(1.0)) 9689 return X; 9690 9691 // X * 0.0 --> 0.0 9692 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 9693 if (YC->getValueAPF().isZero()) 9694 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 9695 9696 return SDValue(); 9697 } 9698 9699 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 9700 SDValue Ptr, SDValue SV, unsigned Align) { 9701 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 9702 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 9703 } 9704 9705 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 9706 ArrayRef<SDUse> Ops) { 9707 switch (Ops.size()) { 9708 case 0: return getNode(Opcode, DL, VT); 9709 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 9710 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 9711 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 9712 default: break; 9713 } 9714 9715 // Copy from an SDUse array into an SDValue array for use with 9716 // the regular getNode logic. 9717 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 9718 return getNode(Opcode, DL, VT, NewOps); 9719 } 9720 9721 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 9722 ArrayRef<SDValue> Ops) { 9723 SDNodeFlags Flags; 9724 if (Inserter) 9725 Flags = Inserter->getFlags(); 9726 return getNode(Opcode, DL, VT, Ops, Flags); 9727 } 9728 9729 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 9730 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 9731 unsigned NumOps = Ops.size(); 9732 switch (NumOps) { 9733 case 0: return getNode(Opcode, DL, VT); 9734 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 9735 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 9736 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 9737 default: break; 9738 } 9739 9740 #ifndef NDEBUG 9741 for (const auto &Op : Ops) 9742 assert(Op.getOpcode() != ISD::DELETED_NODE && 9743 "Operand is DELETED_NODE!"); 9744 #endif 9745 9746 switch (Opcode) { 9747 default: break; 9748 case ISD::BUILD_VECTOR: 9749 // Attempt to simplify BUILD_VECTOR. 9750 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 9751 return V; 9752 break; 9753 case ISD::CONCAT_VECTORS: 9754 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 9755 return V; 9756 break; 9757 case ISD::SELECT_CC: 9758 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 9759 assert(Ops[0].getValueType() == Ops[1].getValueType() && 9760 "LHS and RHS of condition must have same type!"); 9761 assert(Ops[2].getValueType() == Ops[3].getValueType() && 9762 "True and False arms of SelectCC must have same type!"); 9763 assert(Ops[2].getValueType() == VT && 9764 "select_cc node must be of same type as true and false value!"); 9765 assert((!Ops[0].getValueType().isVector() || 9766 Ops[0].getValueType().getVectorElementCount() == 9767 VT.getVectorElementCount()) && 9768 "Expected select_cc with vector result to have the same sized " 9769 "comparison type!"); 9770 break; 9771 case ISD::BR_CC: 9772 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 9773 assert(Ops[2].getValueType() == Ops[3].getValueType() && 9774 "LHS/RHS of comparison should match types!"); 9775 break; 9776 case ISD::VP_ADD: 9777 case ISD::VP_SUB: 9778 // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR 9779 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 9780 Opcode = ISD::VP_XOR; 9781 break; 9782 case ISD::VP_MUL: 9783 // If it is VP_MUL mask operation then turn it to VP_AND 9784 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 9785 Opcode = ISD::VP_AND; 9786 break; 9787 case ISD::VP_REDUCE_MUL: 9788 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND 9789 if (VT == MVT::i1) 9790 Opcode = ISD::VP_REDUCE_AND; 9791 break; 9792 case ISD::VP_REDUCE_ADD: 9793 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR 9794 if (VT == MVT::i1) 9795 Opcode = ISD::VP_REDUCE_XOR; 9796 break; 9797 case ISD::VP_REDUCE_SMAX: 9798 case ISD::VP_REDUCE_UMIN: 9799 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to 9800 // VP_REDUCE_AND. 9801 if (VT == MVT::i1) 9802 Opcode = ISD::VP_REDUCE_AND; 9803 break; 9804 case ISD::VP_REDUCE_SMIN: 9805 case ISD::VP_REDUCE_UMAX: 9806 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to 9807 // VP_REDUCE_OR. 9808 if (VT == MVT::i1) 9809 Opcode = ISD::VP_REDUCE_OR; 9810 break; 9811 } 9812 9813 // Memoize nodes. 9814 SDNode *N; 9815 SDVTList VTs = getVTList(VT); 9816 9817 if (VT != MVT::Glue) { 9818 FoldingSetNodeID ID; 9819 AddNodeIDNode(ID, Opcode, VTs, Ops); 9820 void *IP = nullptr; 9821 9822 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 9823 return SDValue(E, 0); 9824 9825 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9826 createOperands(N, Ops); 9827 9828 CSEMap.InsertNode(N, IP); 9829 } else { 9830 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9831 createOperands(N, Ops); 9832 } 9833 9834 N->setFlags(Flags); 9835 InsertNode(N); 9836 SDValue V(N, 0); 9837 NewSDValueDbgMsg(V, "Creating new node: ", this); 9838 return V; 9839 } 9840 9841 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 9842 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 9843 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 9844 } 9845 9846 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9847 ArrayRef<SDValue> Ops) { 9848 SDNodeFlags Flags; 9849 if (Inserter) 9850 Flags = Inserter->getFlags(); 9851 return getNode(Opcode, DL, VTList, Ops, Flags); 9852 } 9853 9854 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9855 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 9856 if (VTList.NumVTs == 1) 9857 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags); 9858 9859 #ifndef NDEBUG 9860 for (const auto &Op : Ops) 9861 assert(Op.getOpcode() != ISD::DELETED_NODE && 9862 "Operand is DELETED_NODE!"); 9863 #endif 9864 9865 switch (Opcode) { 9866 case ISD::SADDO: 9867 case ISD::UADDO: 9868 case ISD::SSUBO: 9869 case ISD::USUBO: { 9870 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 9871 "Invalid add/sub overflow op!"); 9872 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() && 9873 Ops[0].getValueType() == Ops[1].getValueType() && 9874 Ops[0].getValueType() == VTList.VTs[0] && 9875 "Binary operator types must match!"); 9876 SDValue N1 = Ops[0], N2 = Ops[1]; 9877 canonicalizeCommutativeBinop(Opcode, N1, N2); 9878 9879 // (X +- 0) -> X with zero-overflow. 9880 ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false, 9881 /*AllowTruncation*/ true); 9882 if (N2CV && N2CV->isZero()) { 9883 SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]); 9884 return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags); 9885 } 9886 9887 if (VTList.VTs[0].isVector() && 9888 VTList.VTs[0].getVectorElementType() == MVT::i1 && 9889 VTList.VTs[1].getVectorElementType() == MVT::i1) { 9890 SDValue F1 = getFreeze(N1); 9891 SDValue F2 = getFreeze(N2); 9892 // {vXi1,vXi1} (u/s)addo(vXi1 x, vXi1y) -> {xor(x,y),and(x,y)} 9893 if (Opcode == ISD::UADDO || Opcode == ISD::SADDO) 9894 return getNode(ISD::MERGE_VALUES, DL, VTList, 9895 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2), 9896 getNode(ISD::AND, DL, VTList.VTs[1], F1, F2)}, 9897 Flags); 9898 // {vXi1,vXi1} (u/s)subo(vXi1 x, vXi1y) -> {xor(x,y),and(~x,y)} 9899 if (Opcode == ISD::USUBO || Opcode == ISD::SSUBO) { 9900 SDValue NotF1 = getNOT(DL, F1, VTList.VTs[0]); 9901 return getNode(ISD::MERGE_VALUES, DL, VTList, 9902 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2), 9903 getNode(ISD::AND, DL, VTList.VTs[1], NotF1, F2)}, 9904 Flags); 9905 } 9906 } 9907 break; 9908 } 9909 case ISD::SMUL_LOHI: 9910 case ISD::UMUL_LOHI: { 9911 assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!"); 9912 assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] && 9913 VTList.VTs[0] == Ops[0].getValueType() && 9914 VTList.VTs[0] == Ops[1].getValueType() && 9915 "Binary operator types must match!"); 9916 // Constant fold. 9917 ConstantSDNode *LHS = dyn_cast<ConstantSDNode>(Ops[0]); 9918 ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ops[1]); 9919 if (LHS && RHS) { 9920 unsigned Width = VTList.VTs[0].getScalarSizeInBits(); 9921 unsigned OutWidth = Width * 2; 9922 APInt Val = LHS->getAPIntValue(); 9923 APInt Mul = RHS->getAPIntValue(); 9924 if (Opcode == ISD::SMUL_LOHI) { 9925 Val = Val.sext(OutWidth); 9926 Mul = Mul.sext(OutWidth); 9927 } else { 9928 Val = Val.zext(OutWidth); 9929 Mul = Mul.zext(OutWidth); 9930 } 9931 Val *= Mul; 9932 9933 SDValue Hi = 9934 getConstant(Val.extractBits(Width, Width), DL, VTList.VTs[0]); 9935 SDValue Lo = getConstant(Val.trunc(Width), DL, VTList.VTs[0]); 9936 return getNode(ISD::MERGE_VALUES, DL, VTList, {Lo, Hi}, Flags); 9937 } 9938 break; 9939 } 9940 case ISD::FFREXP: { 9941 assert(VTList.NumVTs == 2 && Ops.size() == 1 && "Invalid ffrexp op!"); 9942 assert(VTList.VTs[0].isFloatingPoint() && VTList.VTs[1].isInteger() && 9943 VTList.VTs[0] == Ops[0].getValueType() && "frexp type mismatch"); 9944 9945 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Ops[0])) { 9946 int FrexpExp; 9947 APFloat FrexpMant = 9948 frexp(C->getValueAPF(), FrexpExp, APFloat::rmNearestTiesToEven); 9949 SDValue Result0 = getConstantFP(FrexpMant, DL, VTList.VTs[0]); 9950 SDValue Result1 = 9951 getConstant(FrexpMant.isFinite() ? FrexpExp : 0, DL, VTList.VTs[1]); 9952 return getNode(ISD::MERGE_VALUES, DL, VTList, {Result0, Result1}, Flags); 9953 } 9954 9955 break; 9956 } 9957 case ISD::STRICT_FP_EXTEND: 9958 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 9959 "Invalid STRICT_FP_EXTEND!"); 9960 assert(VTList.VTs[0].isFloatingPoint() && 9961 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 9962 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 9963 "STRICT_FP_EXTEND result type should be vector iff the operand " 9964 "type is vector!"); 9965 assert((!VTList.VTs[0].isVector() || 9966 VTList.VTs[0].getVectorElementCount() == 9967 Ops[1].getValueType().getVectorElementCount()) && 9968 "Vector element count mismatch!"); 9969 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 9970 "Invalid fpext node, dst <= src!"); 9971 break; 9972 case ISD::STRICT_FP_ROUND: 9973 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 9974 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 9975 "STRICT_FP_ROUND result type should be vector iff the operand " 9976 "type is vector!"); 9977 assert((!VTList.VTs[0].isVector() || 9978 VTList.VTs[0].getVectorElementCount() == 9979 Ops[1].getValueType().getVectorElementCount()) && 9980 "Vector element count mismatch!"); 9981 assert(VTList.VTs[0].isFloatingPoint() && 9982 Ops[1].getValueType().isFloatingPoint() && 9983 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 9984 isa<ConstantSDNode>(Ops[2]) && 9985 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 9986 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 9987 "Invalid STRICT_FP_ROUND!"); 9988 break; 9989 #if 0 9990 // FIXME: figure out how to safely handle things like 9991 // int foo(int x) { return 1 << (x & 255); } 9992 // int bar() { return foo(256); } 9993 case ISD::SRA_PARTS: 9994 case ISD::SRL_PARTS: 9995 case ISD::SHL_PARTS: 9996 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 9997 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 9998 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 9999 else if (N3.getOpcode() == ISD::AND) 10000 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 10001 // If the and is only masking out bits that cannot effect the shift, 10002 // eliminate the and. 10003 unsigned NumBits = VT.getScalarSizeInBits()*2; 10004 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 10005 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 10006 } 10007 break; 10008 #endif 10009 } 10010 10011 // Memoize the node unless it returns a glue result. 10012 SDNode *N; 10013 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 10014 FoldingSetNodeID ID; 10015 AddNodeIDNode(ID, Opcode, VTList, Ops); 10016 void *IP = nullptr; 10017 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 10018 return SDValue(E, 0); 10019 10020 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 10021 createOperands(N, Ops); 10022 CSEMap.InsertNode(N, IP); 10023 } else { 10024 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 10025 createOperands(N, Ops); 10026 } 10027 10028 N->setFlags(Flags); 10029 InsertNode(N); 10030 SDValue V(N, 0); 10031 NewSDValueDbgMsg(V, "Creating new node: ", this); 10032 return V; 10033 } 10034 10035 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 10036 SDVTList VTList) { 10037 return getNode(Opcode, DL, VTList, std::nullopt); 10038 } 10039 10040 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 10041 SDValue N1) { 10042 SDValue Ops[] = { N1 }; 10043 return getNode(Opcode, DL, VTList, Ops); 10044 } 10045 10046 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 10047 SDValue N1, SDValue N2) { 10048 SDValue Ops[] = { N1, N2 }; 10049 return getNode(Opcode, DL, VTList, Ops); 10050 } 10051 10052 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 10053 SDValue N1, SDValue N2, SDValue N3) { 10054 SDValue Ops[] = { N1, N2, N3 }; 10055 return getNode(Opcode, DL, VTList, Ops); 10056 } 10057 10058 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 10059 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 10060 SDValue Ops[] = { N1, N2, N3, N4 }; 10061 return getNode(Opcode, DL, VTList, Ops); 10062 } 10063 10064 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 10065 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 10066 SDValue N5) { 10067 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 10068 return getNode(Opcode, DL, VTList, Ops); 10069 } 10070 10071 SDVTList SelectionDAG::getVTList(EVT VT) { 10072 return makeVTList(SDNode::getValueTypeList(VT), 1); 10073 } 10074 10075 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 10076 FoldingSetNodeID ID; 10077 ID.AddInteger(2U); 10078 ID.AddInteger(VT1.getRawBits()); 10079 ID.AddInteger(VT2.getRawBits()); 10080 10081 void *IP = nullptr; 10082 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 10083 if (!Result) { 10084 EVT *Array = Allocator.Allocate<EVT>(2); 10085 Array[0] = VT1; 10086 Array[1] = VT2; 10087 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 10088 VTListMap.InsertNode(Result, IP); 10089 } 10090 return Result->getSDVTList(); 10091 } 10092 10093 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 10094 FoldingSetNodeID ID; 10095 ID.AddInteger(3U); 10096 ID.AddInteger(VT1.getRawBits()); 10097 ID.AddInteger(VT2.getRawBits()); 10098 ID.AddInteger(VT3.getRawBits()); 10099 10100 void *IP = nullptr; 10101 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 10102 if (!Result) { 10103 EVT *Array = Allocator.Allocate<EVT>(3); 10104 Array[0] = VT1; 10105 Array[1] = VT2; 10106 Array[2] = VT3; 10107 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 10108 VTListMap.InsertNode(Result, IP); 10109 } 10110 return Result->getSDVTList(); 10111 } 10112 10113 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 10114 FoldingSetNodeID ID; 10115 ID.AddInteger(4U); 10116 ID.AddInteger(VT1.getRawBits()); 10117 ID.AddInteger(VT2.getRawBits()); 10118 ID.AddInteger(VT3.getRawBits()); 10119 ID.AddInteger(VT4.getRawBits()); 10120 10121 void *IP = nullptr; 10122 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 10123 if (!Result) { 10124 EVT *Array = Allocator.Allocate<EVT>(4); 10125 Array[0] = VT1; 10126 Array[1] = VT2; 10127 Array[2] = VT3; 10128 Array[3] = VT4; 10129 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 10130 VTListMap.InsertNode(Result, IP); 10131 } 10132 return Result->getSDVTList(); 10133 } 10134 10135 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 10136 unsigned NumVTs = VTs.size(); 10137 FoldingSetNodeID ID; 10138 ID.AddInteger(NumVTs); 10139 for (unsigned index = 0; index < NumVTs; index++) { 10140 ID.AddInteger(VTs[index].getRawBits()); 10141 } 10142 10143 void *IP = nullptr; 10144 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 10145 if (!Result) { 10146 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 10147 llvm::copy(VTs, Array); 10148 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 10149 VTListMap.InsertNode(Result, IP); 10150 } 10151 return Result->getSDVTList(); 10152 } 10153 10154 10155 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 10156 /// specified operands. If the resultant node already exists in the DAG, 10157 /// this does not modify the specified node, instead it returns the node that 10158 /// already exists. If the resultant node does not exist in the DAG, the 10159 /// input node is returned. As a degenerate case, if you specify the same 10160 /// input operands as the node already has, the input node is returned. 10161 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 10162 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 10163 10164 // Check to see if there is no change. 10165 if (Op == N->getOperand(0)) return N; 10166 10167 // See if the modified node already exists. 10168 void *InsertPos = nullptr; 10169 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 10170 return Existing; 10171 10172 // Nope it doesn't. Remove the node from its current place in the maps. 10173 if (InsertPos) 10174 if (!RemoveNodeFromCSEMaps(N)) 10175 InsertPos = nullptr; 10176 10177 // Now we update the operands. 10178 N->OperandList[0].set(Op); 10179 10180 updateDivergence(N); 10181 // If this gets put into a CSE map, add it. 10182 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 10183 return N; 10184 } 10185 10186 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 10187 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 10188 10189 // Check to see if there is no change. 10190 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 10191 return N; // No operands changed, just return the input node. 10192 10193 // See if the modified node already exists. 10194 void *InsertPos = nullptr; 10195 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 10196 return Existing; 10197 10198 // Nope it doesn't. Remove the node from its current place in the maps. 10199 if (InsertPos) 10200 if (!RemoveNodeFromCSEMaps(N)) 10201 InsertPos = nullptr; 10202 10203 // Now we update the operands. 10204 if (N->OperandList[0] != Op1) 10205 N->OperandList[0].set(Op1); 10206 if (N->OperandList[1] != Op2) 10207 N->OperandList[1].set(Op2); 10208 10209 updateDivergence(N); 10210 // If this gets put into a CSE map, add it. 10211 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 10212 return N; 10213 } 10214 10215 SDNode *SelectionDAG:: 10216 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 10217 SDValue Ops[] = { Op1, Op2, Op3 }; 10218 return UpdateNodeOperands(N, Ops); 10219 } 10220 10221 SDNode *SelectionDAG:: 10222 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 10223 SDValue Op3, SDValue Op4) { 10224 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 10225 return UpdateNodeOperands(N, Ops); 10226 } 10227 10228 SDNode *SelectionDAG:: 10229 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 10230 SDValue Op3, SDValue Op4, SDValue Op5) { 10231 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 10232 return UpdateNodeOperands(N, Ops); 10233 } 10234 10235 SDNode *SelectionDAG:: 10236 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 10237 unsigned NumOps = Ops.size(); 10238 assert(N->getNumOperands() == NumOps && 10239 "Update with wrong number of operands"); 10240 10241 // If no operands changed just return the input node. 10242 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 10243 return N; 10244 10245 // See if the modified node already exists. 10246 void *InsertPos = nullptr; 10247 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 10248 return Existing; 10249 10250 // Nope it doesn't. Remove the node from its current place in the maps. 10251 if (InsertPos) 10252 if (!RemoveNodeFromCSEMaps(N)) 10253 InsertPos = nullptr; 10254 10255 // Now we update the operands. 10256 for (unsigned i = 0; i != NumOps; ++i) 10257 if (N->OperandList[i] != Ops[i]) 10258 N->OperandList[i].set(Ops[i]); 10259 10260 updateDivergence(N); 10261 // If this gets put into a CSE map, add it. 10262 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 10263 return N; 10264 } 10265 10266 /// DropOperands - Release the operands and set this node to have 10267 /// zero operands. 10268 void SDNode::DropOperands() { 10269 // Unlike the code in MorphNodeTo that does this, we don't need to 10270 // watch for dead nodes here. 10271 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 10272 SDUse &Use = *I++; 10273 Use.set(SDValue()); 10274 } 10275 } 10276 10277 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 10278 ArrayRef<MachineMemOperand *> NewMemRefs) { 10279 if (NewMemRefs.empty()) { 10280 N->clearMemRefs(); 10281 return; 10282 } 10283 10284 // Check if we can avoid allocating by storing a single reference directly. 10285 if (NewMemRefs.size() == 1) { 10286 N->MemRefs = NewMemRefs[0]; 10287 N->NumMemRefs = 1; 10288 return; 10289 } 10290 10291 MachineMemOperand **MemRefsBuffer = 10292 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 10293 llvm::copy(NewMemRefs, MemRefsBuffer); 10294 N->MemRefs = MemRefsBuffer; 10295 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 10296 } 10297 10298 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 10299 /// machine opcode. 10300 /// 10301 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10302 EVT VT) { 10303 SDVTList VTs = getVTList(VT); 10304 return SelectNodeTo(N, MachineOpc, VTs, std::nullopt); 10305 } 10306 10307 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10308 EVT VT, SDValue Op1) { 10309 SDVTList VTs = getVTList(VT); 10310 SDValue Ops[] = { Op1 }; 10311 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10312 } 10313 10314 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10315 EVT VT, SDValue Op1, 10316 SDValue Op2) { 10317 SDVTList VTs = getVTList(VT); 10318 SDValue Ops[] = { Op1, Op2 }; 10319 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10320 } 10321 10322 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10323 EVT VT, SDValue Op1, 10324 SDValue Op2, SDValue Op3) { 10325 SDVTList VTs = getVTList(VT); 10326 SDValue Ops[] = { Op1, Op2, Op3 }; 10327 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10328 } 10329 10330 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10331 EVT VT, ArrayRef<SDValue> Ops) { 10332 SDVTList VTs = getVTList(VT); 10333 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10334 } 10335 10336 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10337 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 10338 SDVTList VTs = getVTList(VT1, VT2); 10339 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10340 } 10341 10342 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10343 EVT VT1, EVT VT2) { 10344 SDVTList VTs = getVTList(VT1, VT2); 10345 return SelectNodeTo(N, MachineOpc, VTs, std::nullopt); 10346 } 10347 10348 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10349 EVT VT1, EVT VT2, EVT VT3, 10350 ArrayRef<SDValue> Ops) { 10351 SDVTList VTs = getVTList(VT1, VT2, VT3); 10352 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10353 } 10354 10355 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10356 EVT VT1, EVT VT2, 10357 SDValue Op1, SDValue Op2) { 10358 SDVTList VTs = getVTList(VT1, VT2); 10359 SDValue Ops[] = { Op1, Op2 }; 10360 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10361 } 10362 10363 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10364 SDVTList VTs,ArrayRef<SDValue> Ops) { 10365 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 10366 // Reset the NodeID to -1. 10367 New->setNodeId(-1); 10368 if (New != N) { 10369 ReplaceAllUsesWith(N, New); 10370 RemoveDeadNode(N); 10371 } 10372 return New; 10373 } 10374 10375 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 10376 /// the line number information on the merged node since it is not possible to 10377 /// preserve the information that operation is associated with multiple lines. 10378 /// This will make the debugger working better at -O0, were there is a higher 10379 /// probability having other instructions associated with that line. 10380 /// 10381 /// For IROrder, we keep the smaller of the two 10382 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 10383 DebugLoc NLoc = N->getDebugLoc(); 10384 if (NLoc && OptLevel == CodeGenOptLevel::None && OLoc.getDebugLoc() != NLoc) { 10385 N->setDebugLoc(DebugLoc()); 10386 } 10387 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 10388 N->setIROrder(Order); 10389 return N; 10390 } 10391 10392 /// MorphNodeTo - This *mutates* the specified node to have the specified 10393 /// return type, opcode, and operands. 10394 /// 10395 /// Note that MorphNodeTo returns the resultant node. If there is already a 10396 /// node of the specified opcode and operands, it returns that node instead of 10397 /// the current one. Note that the SDLoc need not be the same. 10398 /// 10399 /// Using MorphNodeTo is faster than creating a new node and swapping it in 10400 /// with ReplaceAllUsesWith both because it often avoids allocating a new 10401 /// node, and because it doesn't require CSE recalculation for any of 10402 /// the node's users. 10403 /// 10404 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 10405 /// As a consequence it isn't appropriate to use from within the DAG combiner or 10406 /// the legalizer which maintain worklists that would need to be updated when 10407 /// deleting things. 10408 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 10409 SDVTList VTs, ArrayRef<SDValue> Ops) { 10410 // If an identical node already exists, use it. 10411 void *IP = nullptr; 10412 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 10413 FoldingSetNodeID ID; 10414 AddNodeIDNode(ID, Opc, VTs, Ops); 10415 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 10416 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 10417 } 10418 10419 if (!RemoveNodeFromCSEMaps(N)) 10420 IP = nullptr; 10421 10422 // Start the morphing. 10423 N->NodeType = Opc; 10424 N->ValueList = VTs.VTs; 10425 N->NumValues = VTs.NumVTs; 10426 10427 // Clear the operands list, updating used nodes to remove this from their 10428 // use list. Keep track of any operands that become dead as a result. 10429 SmallPtrSet<SDNode*, 16> DeadNodeSet; 10430 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 10431 SDUse &Use = *I++; 10432 SDNode *Used = Use.getNode(); 10433 Use.set(SDValue()); 10434 if (Used->use_empty()) 10435 DeadNodeSet.insert(Used); 10436 } 10437 10438 // For MachineNode, initialize the memory references information. 10439 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 10440 MN->clearMemRefs(); 10441 10442 // Swap for an appropriately sized array from the recycler. 10443 removeOperands(N); 10444 createOperands(N, Ops); 10445 10446 // Delete any nodes that are still dead after adding the uses for the 10447 // new operands. 10448 if (!DeadNodeSet.empty()) { 10449 SmallVector<SDNode *, 16> DeadNodes; 10450 for (SDNode *N : DeadNodeSet) 10451 if (N->use_empty()) 10452 DeadNodes.push_back(N); 10453 RemoveDeadNodes(DeadNodes); 10454 } 10455 10456 if (IP) 10457 CSEMap.InsertNode(N, IP); // Memoize the new node. 10458 return N; 10459 } 10460 10461 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 10462 unsigned OrigOpc = Node->getOpcode(); 10463 unsigned NewOpc; 10464 switch (OrigOpc) { 10465 default: 10466 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 10467 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 10468 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 10469 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 10470 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 10471 #include "llvm/IR/ConstrainedOps.def" 10472 } 10473 10474 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 10475 10476 // We're taking this node out of the chain, so we need to re-link things. 10477 SDValue InputChain = Node->getOperand(0); 10478 SDValue OutputChain = SDValue(Node, 1); 10479 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 10480 10481 SmallVector<SDValue, 3> Ops; 10482 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 10483 Ops.push_back(Node->getOperand(i)); 10484 10485 SDVTList VTs = getVTList(Node->getValueType(0)); 10486 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 10487 10488 // MorphNodeTo can operate in two ways: if an existing node with the 10489 // specified operands exists, it can just return it. Otherwise, it 10490 // updates the node in place to have the requested operands. 10491 if (Res == Node) { 10492 // If we updated the node in place, reset the node ID. To the isel, 10493 // this should be just like a newly allocated machine node. 10494 Res->setNodeId(-1); 10495 } else { 10496 ReplaceAllUsesWith(Node, Res); 10497 RemoveDeadNode(Node); 10498 } 10499 10500 return Res; 10501 } 10502 10503 /// getMachineNode - These are used for target selectors to create a new node 10504 /// with specified return type(s), MachineInstr opcode, and operands. 10505 /// 10506 /// Note that getMachineNode returns the resultant node. If there is already a 10507 /// node of the specified opcode and operands, it returns that node instead of 10508 /// the current one. 10509 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10510 EVT VT) { 10511 SDVTList VTs = getVTList(VT); 10512 return getMachineNode(Opcode, dl, VTs, std::nullopt); 10513 } 10514 10515 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10516 EVT VT, SDValue Op1) { 10517 SDVTList VTs = getVTList(VT); 10518 SDValue Ops[] = { Op1 }; 10519 return getMachineNode(Opcode, dl, VTs, Ops); 10520 } 10521 10522 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10523 EVT VT, SDValue Op1, SDValue Op2) { 10524 SDVTList VTs = getVTList(VT); 10525 SDValue Ops[] = { Op1, Op2 }; 10526 return getMachineNode(Opcode, dl, VTs, Ops); 10527 } 10528 10529 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10530 EVT VT, SDValue Op1, SDValue Op2, 10531 SDValue Op3) { 10532 SDVTList VTs = getVTList(VT); 10533 SDValue Ops[] = { Op1, Op2, Op3 }; 10534 return getMachineNode(Opcode, dl, VTs, Ops); 10535 } 10536 10537 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10538 EVT VT, ArrayRef<SDValue> Ops) { 10539 SDVTList VTs = getVTList(VT); 10540 return getMachineNode(Opcode, dl, VTs, Ops); 10541 } 10542 10543 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10544 EVT VT1, EVT VT2, SDValue Op1, 10545 SDValue Op2) { 10546 SDVTList VTs = getVTList(VT1, VT2); 10547 SDValue Ops[] = { Op1, Op2 }; 10548 return getMachineNode(Opcode, dl, VTs, Ops); 10549 } 10550 10551 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10552 EVT VT1, EVT VT2, SDValue Op1, 10553 SDValue Op2, SDValue Op3) { 10554 SDVTList VTs = getVTList(VT1, VT2); 10555 SDValue Ops[] = { Op1, Op2, Op3 }; 10556 return getMachineNode(Opcode, dl, VTs, Ops); 10557 } 10558 10559 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10560 EVT VT1, EVT VT2, 10561 ArrayRef<SDValue> Ops) { 10562 SDVTList VTs = getVTList(VT1, VT2); 10563 return getMachineNode(Opcode, dl, VTs, Ops); 10564 } 10565 10566 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10567 EVT VT1, EVT VT2, EVT VT3, 10568 SDValue Op1, SDValue Op2) { 10569 SDVTList VTs = getVTList(VT1, VT2, VT3); 10570 SDValue Ops[] = { Op1, Op2 }; 10571 return getMachineNode(Opcode, dl, VTs, Ops); 10572 } 10573 10574 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10575 EVT VT1, EVT VT2, EVT VT3, 10576 SDValue Op1, SDValue Op2, 10577 SDValue Op3) { 10578 SDVTList VTs = getVTList(VT1, VT2, VT3); 10579 SDValue Ops[] = { Op1, Op2, Op3 }; 10580 return getMachineNode(Opcode, dl, VTs, Ops); 10581 } 10582 10583 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10584 EVT VT1, EVT VT2, EVT VT3, 10585 ArrayRef<SDValue> Ops) { 10586 SDVTList VTs = getVTList(VT1, VT2, VT3); 10587 return getMachineNode(Opcode, dl, VTs, Ops); 10588 } 10589 10590 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10591 ArrayRef<EVT> ResultTys, 10592 ArrayRef<SDValue> Ops) { 10593 SDVTList VTs = getVTList(ResultTys); 10594 return getMachineNode(Opcode, dl, VTs, Ops); 10595 } 10596 10597 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 10598 SDVTList VTs, 10599 ArrayRef<SDValue> Ops) { 10600 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 10601 MachineSDNode *N; 10602 void *IP = nullptr; 10603 10604 if (DoCSE) { 10605 FoldingSetNodeID ID; 10606 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 10607 IP = nullptr; 10608 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 10609 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 10610 } 10611 } 10612 10613 // Allocate a new MachineSDNode. 10614 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 10615 createOperands(N, Ops); 10616 10617 if (DoCSE) 10618 CSEMap.InsertNode(N, IP); 10619 10620 InsertNode(N); 10621 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 10622 return N; 10623 } 10624 10625 /// getTargetExtractSubreg - A convenience function for creating 10626 /// TargetOpcode::EXTRACT_SUBREG nodes. 10627 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 10628 SDValue Operand) { 10629 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 10630 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 10631 VT, Operand, SRIdxVal); 10632 return SDValue(Subreg, 0); 10633 } 10634 10635 /// getTargetInsertSubreg - A convenience function for creating 10636 /// TargetOpcode::INSERT_SUBREG nodes. 10637 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 10638 SDValue Operand, SDValue Subreg) { 10639 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 10640 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 10641 VT, Operand, Subreg, SRIdxVal); 10642 return SDValue(Result, 0); 10643 } 10644 10645 /// getNodeIfExists - Get the specified node if it's already available, or 10646 /// else return NULL. 10647 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 10648 ArrayRef<SDValue> Ops) { 10649 SDNodeFlags Flags; 10650 if (Inserter) 10651 Flags = Inserter->getFlags(); 10652 return getNodeIfExists(Opcode, VTList, Ops, Flags); 10653 } 10654 10655 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 10656 ArrayRef<SDValue> Ops, 10657 const SDNodeFlags Flags) { 10658 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 10659 FoldingSetNodeID ID; 10660 AddNodeIDNode(ID, Opcode, VTList, Ops); 10661 void *IP = nullptr; 10662 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 10663 E->intersectFlagsWith(Flags); 10664 return E; 10665 } 10666 } 10667 return nullptr; 10668 } 10669 10670 /// doesNodeExist - Check if a node exists without modifying its flags. 10671 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 10672 ArrayRef<SDValue> Ops) { 10673 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 10674 FoldingSetNodeID ID; 10675 AddNodeIDNode(ID, Opcode, VTList, Ops); 10676 void *IP = nullptr; 10677 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 10678 return true; 10679 } 10680 return false; 10681 } 10682 10683 /// getDbgValue - Creates a SDDbgValue node. 10684 /// 10685 /// SDNode 10686 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 10687 SDNode *N, unsigned R, bool IsIndirect, 10688 const DebugLoc &DL, unsigned O) { 10689 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 10690 "Expected inlined-at fields to agree"); 10691 return new (DbgInfo->getAlloc()) 10692 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 10693 {}, IsIndirect, DL, O, 10694 /*IsVariadic=*/false); 10695 } 10696 10697 /// Constant 10698 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 10699 DIExpression *Expr, 10700 const Value *C, 10701 const DebugLoc &DL, unsigned O) { 10702 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 10703 "Expected inlined-at fields to agree"); 10704 return new (DbgInfo->getAlloc()) 10705 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 10706 /*IsIndirect=*/false, DL, O, 10707 /*IsVariadic=*/false); 10708 } 10709 10710 /// FrameIndex 10711 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 10712 DIExpression *Expr, unsigned FI, 10713 bool IsIndirect, 10714 const DebugLoc &DL, 10715 unsigned O) { 10716 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 10717 "Expected inlined-at fields to agree"); 10718 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 10719 } 10720 10721 /// FrameIndex with dependencies 10722 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 10723 DIExpression *Expr, unsigned FI, 10724 ArrayRef<SDNode *> Dependencies, 10725 bool IsIndirect, 10726 const DebugLoc &DL, 10727 unsigned O) { 10728 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 10729 "Expected inlined-at fields to agree"); 10730 return new (DbgInfo->getAlloc()) 10731 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 10732 Dependencies, IsIndirect, DL, O, 10733 /*IsVariadic=*/false); 10734 } 10735 10736 /// VReg 10737 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 10738 unsigned VReg, bool IsIndirect, 10739 const DebugLoc &DL, unsigned O) { 10740 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 10741 "Expected inlined-at fields to agree"); 10742 return new (DbgInfo->getAlloc()) 10743 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 10744 {}, IsIndirect, DL, O, 10745 /*IsVariadic=*/false); 10746 } 10747 10748 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 10749 ArrayRef<SDDbgOperand> Locs, 10750 ArrayRef<SDNode *> Dependencies, 10751 bool IsIndirect, const DebugLoc &DL, 10752 unsigned O, bool IsVariadic) { 10753 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 10754 "Expected inlined-at fields to agree"); 10755 return new (DbgInfo->getAlloc()) 10756 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 10757 DL, O, IsVariadic); 10758 } 10759 10760 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 10761 unsigned OffsetInBits, unsigned SizeInBits, 10762 bool InvalidateDbg) { 10763 SDNode *FromNode = From.getNode(); 10764 SDNode *ToNode = To.getNode(); 10765 assert(FromNode && ToNode && "Can't modify dbg values"); 10766 10767 // PR35338 10768 // TODO: assert(From != To && "Redundant dbg value transfer"); 10769 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 10770 if (From == To || FromNode == ToNode) 10771 return; 10772 10773 if (!FromNode->getHasDebugValue()) 10774 return; 10775 10776 SDDbgOperand FromLocOp = 10777 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 10778 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 10779 10780 SmallVector<SDDbgValue *, 2> ClonedDVs; 10781 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 10782 if (Dbg->isInvalidated()) 10783 continue; 10784 10785 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 10786 10787 // Create a new location ops vector that is equal to the old vector, but 10788 // with each instance of FromLocOp replaced with ToLocOp. 10789 bool Changed = false; 10790 auto NewLocOps = Dbg->copyLocationOps(); 10791 std::replace_if( 10792 NewLocOps.begin(), NewLocOps.end(), 10793 [&Changed, FromLocOp](const SDDbgOperand &Op) { 10794 bool Match = Op == FromLocOp; 10795 Changed |= Match; 10796 return Match; 10797 }, 10798 ToLocOp); 10799 // Ignore this SDDbgValue if we didn't find a matching location. 10800 if (!Changed) 10801 continue; 10802 10803 DIVariable *Var = Dbg->getVariable(); 10804 auto *Expr = Dbg->getExpression(); 10805 // If a fragment is requested, update the expression. 10806 if (SizeInBits) { 10807 // When splitting a larger (e.g., sign-extended) value whose 10808 // lower bits are described with an SDDbgValue, do not attempt 10809 // to transfer the SDDbgValue to the upper bits. 10810 if (auto FI = Expr->getFragmentInfo()) 10811 if (OffsetInBits + SizeInBits > FI->SizeInBits) 10812 continue; 10813 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 10814 SizeInBits); 10815 if (!Fragment) 10816 continue; 10817 Expr = *Fragment; 10818 } 10819 10820 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 10821 // Clone the SDDbgValue and move it to To. 10822 SDDbgValue *Clone = getDbgValueList( 10823 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 10824 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 10825 Dbg->isVariadic()); 10826 ClonedDVs.push_back(Clone); 10827 10828 if (InvalidateDbg) { 10829 // Invalidate value and indicate the SDDbgValue should not be emitted. 10830 Dbg->setIsInvalidated(); 10831 Dbg->setIsEmitted(); 10832 } 10833 } 10834 10835 for (SDDbgValue *Dbg : ClonedDVs) { 10836 assert(is_contained(Dbg->getSDNodes(), ToNode) && 10837 "Transferred DbgValues should depend on the new SDNode"); 10838 AddDbgValue(Dbg, false); 10839 } 10840 } 10841 10842 void SelectionDAG::salvageDebugInfo(SDNode &N) { 10843 if (!N.getHasDebugValue()) 10844 return; 10845 10846 SmallVector<SDDbgValue *, 2> ClonedDVs; 10847 for (auto *DV : GetDbgValues(&N)) { 10848 if (DV->isInvalidated()) 10849 continue; 10850 switch (N.getOpcode()) { 10851 default: 10852 break; 10853 case ISD::ADD: { 10854 SDValue N0 = N.getOperand(0); 10855 SDValue N1 = N.getOperand(1); 10856 if (!isa<ConstantSDNode>(N0)) { 10857 bool RHSConstant = isa<ConstantSDNode>(N1); 10858 uint64_t Offset; 10859 if (RHSConstant) 10860 Offset = N.getConstantOperandVal(1); 10861 // We are not allowed to turn indirect debug values variadic, so 10862 // don't salvage those. 10863 if (!RHSConstant && DV->isIndirect()) 10864 continue; 10865 10866 // Rewrite an ADD constant node into a DIExpression. Since we are 10867 // performing arithmetic to compute the variable's *value* in the 10868 // DIExpression, we need to mark the expression with a 10869 // DW_OP_stack_value. 10870 auto *DIExpr = DV->getExpression(); 10871 auto NewLocOps = DV->copyLocationOps(); 10872 bool Changed = false; 10873 size_t OrigLocOpsSize = NewLocOps.size(); 10874 for (size_t i = 0; i < OrigLocOpsSize; ++i) { 10875 // We're not given a ResNo to compare against because the whole 10876 // node is going away. We know that any ISD::ADD only has one 10877 // result, so we can assume any node match is using the result. 10878 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 10879 NewLocOps[i].getSDNode() != &N) 10880 continue; 10881 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 10882 if (RHSConstant) { 10883 SmallVector<uint64_t, 3> ExprOps; 10884 DIExpression::appendOffset(ExprOps, Offset); 10885 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 10886 } else { 10887 // Convert to a variadic expression (if not already). 10888 // convertToVariadicExpression() returns a const pointer, so we use 10889 // a temporary const variable here. 10890 const auto *TmpDIExpr = 10891 DIExpression::convertToVariadicExpression(DIExpr); 10892 SmallVector<uint64_t, 3> ExprOps; 10893 ExprOps.push_back(dwarf::DW_OP_LLVM_arg); 10894 ExprOps.push_back(NewLocOps.size()); 10895 ExprOps.push_back(dwarf::DW_OP_plus); 10896 SDDbgOperand RHS = 10897 SDDbgOperand::fromNode(N1.getNode(), N1.getResNo()); 10898 NewLocOps.push_back(RHS); 10899 DIExpr = DIExpression::appendOpsToArg(TmpDIExpr, ExprOps, i, true); 10900 } 10901 Changed = true; 10902 } 10903 (void)Changed; 10904 assert(Changed && "Salvage target doesn't use N"); 10905 10906 bool IsVariadic = 10907 DV->isVariadic() || OrigLocOpsSize != NewLocOps.size(); 10908 10909 auto AdditionalDependencies = DV->getAdditionalDependencies(); 10910 SDDbgValue *Clone = getDbgValueList( 10911 DV->getVariable(), DIExpr, NewLocOps, AdditionalDependencies, 10912 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder(), IsVariadic); 10913 ClonedDVs.push_back(Clone); 10914 DV->setIsInvalidated(); 10915 DV->setIsEmitted(); 10916 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 10917 N0.getNode()->dumprFull(this); 10918 dbgs() << " into " << *DIExpr << '\n'); 10919 } 10920 break; 10921 } 10922 case ISD::TRUNCATE: { 10923 SDValue N0 = N.getOperand(0); 10924 TypeSize FromSize = N0.getValueSizeInBits(); 10925 TypeSize ToSize = N.getValueSizeInBits(0); 10926 10927 DIExpression *DbgExpression = DV->getExpression(); 10928 auto ExtOps = DIExpression::getExtOps(FromSize, ToSize, false); 10929 auto NewLocOps = DV->copyLocationOps(); 10930 bool Changed = false; 10931 for (size_t i = 0; i < NewLocOps.size(); ++i) { 10932 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 10933 NewLocOps[i].getSDNode() != &N) 10934 continue; 10935 10936 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 10937 DbgExpression = DIExpression::appendOpsToArg(DbgExpression, ExtOps, i); 10938 Changed = true; 10939 } 10940 assert(Changed && "Salvage target doesn't use N"); 10941 (void)Changed; 10942 10943 SDDbgValue *Clone = 10944 getDbgValueList(DV->getVariable(), DbgExpression, NewLocOps, 10945 DV->getAdditionalDependencies(), DV->isIndirect(), 10946 DV->getDebugLoc(), DV->getOrder(), DV->isVariadic()); 10947 10948 ClonedDVs.push_back(Clone); 10949 DV->setIsInvalidated(); 10950 DV->setIsEmitted(); 10951 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; N0.getNode()->dumprFull(this); 10952 dbgs() << " into " << *DbgExpression << '\n'); 10953 break; 10954 } 10955 } 10956 } 10957 10958 for (SDDbgValue *Dbg : ClonedDVs) { 10959 assert(!Dbg->getSDNodes().empty() && 10960 "Salvaged DbgValue should depend on a new SDNode"); 10961 AddDbgValue(Dbg, false); 10962 } 10963 } 10964 10965 /// Creates a SDDbgLabel node. 10966 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 10967 const DebugLoc &DL, unsigned O) { 10968 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 10969 "Expected inlined-at fields to agree"); 10970 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 10971 } 10972 10973 namespace { 10974 10975 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 10976 /// pointed to by a use iterator is deleted, increment the use iterator 10977 /// so that it doesn't dangle. 10978 /// 10979 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 10980 SDNode::use_iterator &UI; 10981 SDNode::use_iterator &UE; 10982 10983 void NodeDeleted(SDNode *N, SDNode *E) override { 10984 // Increment the iterator as needed. 10985 while (UI != UE && N == *UI) 10986 ++UI; 10987 } 10988 10989 public: 10990 RAUWUpdateListener(SelectionDAG &d, 10991 SDNode::use_iterator &ui, 10992 SDNode::use_iterator &ue) 10993 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 10994 }; 10995 10996 } // end anonymous namespace 10997 10998 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 10999 /// This can cause recursive merging of nodes in the DAG. 11000 /// 11001 /// This version assumes From has a single result value. 11002 /// 11003 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 11004 SDNode *From = FromN.getNode(); 11005 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 11006 "Cannot replace with this method!"); 11007 assert(From != To.getNode() && "Cannot replace uses of with self"); 11008 11009 // Preserve Debug Values 11010 transferDbgValues(FromN, To); 11011 // Preserve extra info. 11012 copyExtraInfo(From, To.getNode()); 11013 11014 // Iterate over all the existing uses of From. New uses will be added 11015 // to the beginning of the use list, which we avoid visiting. 11016 // This specifically avoids visiting uses of From that arise while the 11017 // replacement is happening, because any such uses would be the result 11018 // of CSE: If an existing node looks like From after one of its operands 11019 // is replaced by To, we don't want to replace of all its users with To 11020 // too. See PR3018 for more info. 11021 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 11022 RAUWUpdateListener Listener(*this, UI, UE); 11023 while (UI != UE) { 11024 SDNode *User = *UI; 11025 11026 // This node is about to morph, remove its old self from the CSE maps. 11027 RemoveNodeFromCSEMaps(User); 11028 11029 // A user can appear in a use list multiple times, and when this 11030 // happens the uses are usually next to each other in the list. 11031 // To help reduce the number of CSE recomputations, process all 11032 // the uses of this user that we can find this way. 11033 do { 11034 SDUse &Use = UI.getUse(); 11035 ++UI; 11036 Use.set(To); 11037 if (To->isDivergent() != From->isDivergent()) 11038 updateDivergence(User); 11039 } while (UI != UE && *UI == User); 11040 // Now that we have modified User, add it back to the CSE maps. If it 11041 // already exists there, recursively merge the results together. 11042 AddModifiedNodeToCSEMaps(User); 11043 } 11044 11045 // If we just RAUW'd the root, take note. 11046 if (FromN == getRoot()) 11047 setRoot(To); 11048 } 11049 11050 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 11051 /// This can cause recursive merging of nodes in the DAG. 11052 /// 11053 /// This version assumes that for each value of From, there is a 11054 /// corresponding value in To in the same position with the same type. 11055 /// 11056 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 11057 #ifndef NDEBUG 11058 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 11059 assert((!From->hasAnyUseOfValue(i) || 11060 From->getValueType(i) == To->getValueType(i)) && 11061 "Cannot use this version of ReplaceAllUsesWith!"); 11062 #endif 11063 11064 // Handle the trivial case. 11065 if (From == To) 11066 return; 11067 11068 // Preserve Debug Info. Only do this if there's a use. 11069 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 11070 if (From->hasAnyUseOfValue(i)) { 11071 assert((i < To->getNumValues()) && "Invalid To location"); 11072 transferDbgValues(SDValue(From, i), SDValue(To, i)); 11073 } 11074 // Preserve extra info. 11075 copyExtraInfo(From, To); 11076 11077 // Iterate over just the existing users of From. See the comments in 11078 // the ReplaceAllUsesWith above. 11079 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 11080 RAUWUpdateListener Listener(*this, UI, UE); 11081 while (UI != UE) { 11082 SDNode *User = *UI; 11083 11084 // This node is about to morph, remove its old self from the CSE maps. 11085 RemoveNodeFromCSEMaps(User); 11086 11087 // A user can appear in a use list multiple times, and when this 11088 // happens the uses are usually next to each other in the list. 11089 // To help reduce the number of CSE recomputations, process all 11090 // the uses of this user that we can find this way. 11091 do { 11092 SDUse &Use = UI.getUse(); 11093 ++UI; 11094 Use.setNode(To); 11095 if (To->isDivergent() != From->isDivergent()) 11096 updateDivergence(User); 11097 } while (UI != UE && *UI == User); 11098 11099 // Now that we have modified User, add it back to the CSE maps. If it 11100 // already exists there, recursively merge the results together. 11101 AddModifiedNodeToCSEMaps(User); 11102 } 11103 11104 // If we just RAUW'd the root, take note. 11105 if (From == getRoot().getNode()) 11106 setRoot(SDValue(To, getRoot().getResNo())); 11107 } 11108 11109 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 11110 /// This can cause recursive merging of nodes in the DAG. 11111 /// 11112 /// This version can replace From with any result values. To must match the 11113 /// number and types of values returned by From. 11114 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 11115 if (From->getNumValues() == 1) // Handle the simple case efficiently. 11116 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 11117 11118 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) { 11119 // Preserve Debug Info. 11120 transferDbgValues(SDValue(From, i), To[i]); 11121 // Preserve extra info. 11122 copyExtraInfo(From, To[i].getNode()); 11123 } 11124 11125 // Iterate over just the existing users of From. See the comments in 11126 // the ReplaceAllUsesWith above. 11127 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 11128 RAUWUpdateListener Listener(*this, UI, UE); 11129 while (UI != UE) { 11130 SDNode *User = *UI; 11131 11132 // This node is about to morph, remove its old self from the CSE maps. 11133 RemoveNodeFromCSEMaps(User); 11134 11135 // A user can appear in a use list multiple times, and when this happens the 11136 // uses are usually next to each other in the list. To help reduce the 11137 // number of CSE and divergence recomputations, process all the uses of this 11138 // user that we can find this way. 11139 bool To_IsDivergent = false; 11140 do { 11141 SDUse &Use = UI.getUse(); 11142 const SDValue &ToOp = To[Use.getResNo()]; 11143 ++UI; 11144 Use.set(ToOp); 11145 To_IsDivergent |= ToOp->isDivergent(); 11146 } while (UI != UE && *UI == User); 11147 11148 if (To_IsDivergent != From->isDivergent()) 11149 updateDivergence(User); 11150 11151 // Now that we have modified User, add it back to the CSE maps. If it 11152 // already exists there, recursively merge the results together. 11153 AddModifiedNodeToCSEMaps(User); 11154 } 11155 11156 // If we just RAUW'd the root, take note. 11157 if (From == getRoot().getNode()) 11158 setRoot(SDValue(To[getRoot().getResNo()])); 11159 } 11160 11161 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 11162 /// uses of other values produced by From.getNode() alone. The Deleted 11163 /// vector is handled the same way as for ReplaceAllUsesWith. 11164 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 11165 // Handle the really simple, really trivial case efficiently. 11166 if (From == To) return; 11167 11168 // Handle the simple, trivial, case efficiently. 11169 if (From.getNode()->getNumValues() == 1) { 11170 ReplaceAllUsesWith(From, To); 11171 return; 11172 } 11173 11174 // Preserve Debug Info. 11175 transferDbgValues(From, To); 11176 copyExtraInfo(From.getNode(), To.getNode()); 11177 11178 // Iterate over just the existing users of From. See the comments in 11179 // the ReplaceAllUsesWith above. 11180 SDNode::use_iterator UI = From.getNode()->use_begin(), 11181 UE = From.getNode()->use_end(); 11182 RAUWUpdateListener Listener(*this, UI, UE); 11183 while (UI != UE) { 11184 SDNode *User = *UI; 11185 bool UserRemovedFromCSEMaps = false; 11186 11187 // A user can appear in a use list multiple times, and when this 11188 // happens the uses are usually next to each other in the list. 11189 // To help reduce the number of CSE recomputations, process all 11190 // the uses of this user that we can find this way. 11191 do { 11192 SDUse &Use = UI.getUse(); 11193 11194 // Skip uses of different values from the same node. 11195 if (Use.getResNo() != From.getResNo()) { 11196 ++UI; 11197 continue; 11198 } 11199 11200 // If this node hasn't been modified yet, it's still in the CSE maps, 11201 // so remove its old self from the CSE maps. 11202 if (!UserRemovedFromCSEMaps) { 11203 RemoveNodeFromCSEMaps(User); 11204 UserRemovedFromCSEMaps = true; 11205 } 11206 11207 ++UI; 11208 Use.set(To); 11209 if (To->isDivergent() != From->isDivergent()) 11210 updateDivergence(User); 11211 } while (UI != UE && *UI == User); 11212 // We are iterating over all uses of the From node, so if a use 11213 // doesn't use the specific value, no changes are made. 11214 if (!UserRemovedFromCSEMaps) 11215 continue; 11216 11217 // Now that we have modified User, add it back to the CSE maps. If it 11218 // already exists there, recursively merge the results together. 11219 AddModifiedNodeToCSEMaps(User); 11220 } 11221 11222 // If we just RAUW'd the root, take note. 11223 if (From == getRoot()) 11224 setRoot(To); 11225 } 11226 11227 namespace { 11228 11229 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 11230 /// to record information about a use. 11231 struct UseMemo { 11232 SDNode *User; 11233 unsigned Index; 11234 SDUse *Use; 11235 }; 11236 11237 /// operator< - Sort Memos by User. 11238 bool operator<(const UseMemo &L, const UseMemo &R) { 11239 return (intptr_t)L.User < (intptr_t)R.User; 11240 } 11241 11242 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node 11243 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that 11244 /// the node already has been taken care of recursively. 11245 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener { 11246 SmallVector<UseMemo, 4> &Uses; 11247 11248 void NodeDeleted(SDNode *N, SDNode *E) override { 11249 for (UseMemo &Memo : Uses) 11250 if (Memo.User == N) 11251 Memo.User = nullptr; 11252 } 11253 11254 public: 11255 RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses) 11256 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {} 11257 }; 11258 11259 } // end anonymous namespace 11260 11261 bool SelectionDAG::calculateDivergence(SDNode *N) { 11262 if (TLI->isSDNodeAlwaysUniform(N)) { 11263 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, UA) && 11264 "Conflicting divergence information!"); 11265 return false; 11266 } 11267 if (TLI->isSDNodeSourceOfDivergence(N, FLI, UA)) 11268 return true; 11269 for (const auto &Op : N->ops()) { 11270 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 11271 return true; 11272 } 11273 return false; 11274 } 11275 11276 void SelectionDAG::updateDivergence(SDNode *N) { 11277 SmallVector<SDNode *, 16> Worklist(1, N); 11278 do { 11279 N = Worklist.pop_back_val(); 11280 bool IsDivergent = calculateDivergence(N); 11281 if (N->SDNodeBits.IsDivergent != IsDivergent) { 11282 N->SDNodeBits.IsDivergent = IsDivergent; 11283 llvm::append_range(Worklist, N->uses()); 11284 } 11285 } while (!Worklist.empty()); 11286 } 11287 11288 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 11289 DenseMap<SDNode *, unsigned> Degree; 11290 Order.reserve(AllNodes.size()); 11291 for (auto &N : allnodes()) { 11292 unsigned NOps = N.getNumOperands(); 11293 Degree[&N] = NOps; 11294 if (0 == NOps) 11295 Order.push_back(&N); 11296 } 11297 for (size_t I = 0; I != Order.size(); ++I) { 11298 SDNode *N = Order[I]; 11299 for (auto *U : N->uses()) { 11300 unsigned &UnsortedOps = Degree[U]; 11301 if (0 == --UnsortedOps) 11302 Order.push_back(U); 11303 } 11304 } 11305 } 11306 11307 #ifndef NDEBUG 11308 void SelectionDAG::VerifyDAGDivergence() { 11309 std::vector<SDNode *> TopoOrder; 11310 CreateTopologicalOrder(TopoOrder); 11311 for (auto *N : TopoOrder) { 11312 assert(calculateDivergence(N) == N->isDivergent() && 11313 "Divergence bit inconsistency detected"); 11314 } 11315 } 11316 #endif 11317 11318 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 11319 /// uses of other values produced by From.getNode() alone. The same value 11320 /// may appear in both the From and To list. The Deleted vector is 11321 /// handled the same way as for ReplaceAllUsesWith. 11322 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 11323 const SDValue *To, 11324 unsigned Num){ 11325 // Handle the simple, trivial case efficiently. 11326 if (Num == 1) 11327 return ReplaceAllUsesOfValueWith(*From, *To); 11328 11329 transferDbgValues(*From, *To); 11330 copyExtraInfo(From->getNode(), To->getNode()); 11331 11332 // Read up all the uses and make records of them. This helps 11333 // processing new uses that are introduced during the 11334 // replacement process. 11335 SmallVector<UseMemo, 4> Uses; 11336 for (unsigned i = 0; i != Num; ++i) { 11337 unsigned FromResNo = From[i].getResNo(); 11338 SDNode *FromNode = From[i].getNode(); 11339 for (SDNode::use_iterator UI = FromNode->use_begin(), 11340 E = FromNode->use_end(); UI != E; ++UI) { 11341 SDUse &Use = UI.getUse(); 11342 if (Use.getResNo() == FromResNo) { 11343 UseMemo Memo = { *UI, i, &Use }; 11344 Uses.push_back(Memo); 11345 } 11346 } 11347 } 11348 11349 // Sort the uses, so that all the uses from a given User are together. 11350 llvm::sort(Uses); 11351 RAUOVWUpdateListener Listener(*this, Uses); 11352 11353 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 11354 UseIndex != UseIndexEnd; ) { 11355 // We know that this user uses some value of From. If it is the right 11356 // value, update it. 11357 SDNode *User = Uses[UseIndex].User; 11358 // If the node has been deleted by recursive CSE updates when updating 11359 // another node, then just skip this entry. 11360 if (User == nullptr) { 11361 ++UseIndex; 11362 continue; 11363 } 11364 11365 // This node is about to morph, remove its old self from the CSE maps. 11366 RemoveNodeFromCSEMaps(User); 11367 11368 // The Uses array is sorted, so all the uses for a given User 11369 // are next to each other in the list. 11370 // To help reduce the number of CSE recomputations, process all 11371 // the uses of this user that we can find this way. 11372 do { 11373 unsigned i = Uses[UseIndex].Index; 11374 SDUse &Use = *Uses[UseIndex].Use; 11375 ++UseIndex; 11376 11377 Use.set(To[i]); 11378 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 11379 11380 // Now that we have modified User, add it back to the CSE maps. If it 11381 // already exists there, recursively merge the results together. 11382 AddModifiedNodeToCSEMaps(User); 11383 } 11384 } 11385 11386 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 11387 /// based on their topological order. It returns the maximum id and a vector 11388 /// of the SDNodes* in assigned order by reference. 11389 unsigned SelectionDAG::AssignTopologicalOrder() { 11390 unsigned DAGSize = 0; 11391 11392 // SortedPos tracks the progress of the algorithm. Nodes before it are 11393 // sorted, nodes after it are unsorted. When the algorithm completes 11394 // it is at the end of the list. 11395 allnodes_iterator SortedPos = allnodes_begin(); 11396 11397 // Visit all the nodes. Move nodes with no operands to the front of 11398 // the list immediately. Annotate nodes that do have operands with their 11399 // operand count. Before we do this, the Node Id fields of the nodes 11400 // may contain arbitrary values. After, the Node Id fields for nodes 11401 // before SortedPos will contain the topological sort index, and the 11402 // Node Id fields for nodes At SortedPos and after will contain the 11403 // count of outstanding operands. 11404 for (SDNode &N : llvm::make_early_inc_range(allnodes())) { 11405 checkForCycles(&N, this); 11406 unsigned Degree = N.getNumOperands(); 11407 if (Degree == 0) { 11408 // A node with no uses, add it to the result array immediately. 11409 N.setNodeId(DAGSize++); 11410 allnodes_iterator Q(&N); 11411 if (Q != SortedPos) 11412 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 11413 assert(SortedPos != AllNodes.end() && "Overran node list"); 11414 ++SortedPos; 11415 } else { 11416 // Temporarily use the Node Id as scratch space for the degree count. 11417 N.setNodeId(Degree); 11418 } 11419 } 11420 11421 // Visit all the nodes. As we iterate, move nodes into sorted order, 11422 // such that by the time the end is reached all nodes will be sorted. 11423 for (SDNode &Node : allnodes()) { 11424 SDNode *N = &Node; 11425 checkForCycles(N, this); 11426 // N is in sorted position, so all its uses have one less operand 11427 // that needs to be sorted. 11428 for (SDNode *P : N->uses()) { 11429 unsigned Degree = P->getNodeId(); 11430 assert(Degree != 0 && "Invalid node degree"); 11431 --Degree; 11432 if (Degree == 0) { 11433 // All of P's operands are sorted, so P may sorted now. 11434 P->setNodeId(DAGSize++); 11435 if (P->getIterator() != SortedPos) 11436 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 11437 assert(SortedPos != AllNodes.end() && "Overran node list"); 11438 ++SortedPos; 11439 } else { 11440 // Update P's outstanding operand count. 11441 P->setNodeId(Degree); 11442 } 11443 } 11444 if (Node.getIterator() == SortedPos) { 11445 #ifndef NDEBUG 11446 allnodes_iterator I(N); 11447 SDNode *S = &*++I; 11448 dbgs() << "Overran sorted position:\n"; 11449 S->dumprFull(this); dbgs() << "\n"; 11450 dbgs() << "Checking if this is due to cycles\n"; 11451 checkForCycles(this, true); 11452 #endif 11453 llvm_unreachable(nullptr); 11454 } 11455 } 11456 11457 assert(SortedPos == AllNodes.end() && 11458 "Topological sort incomplete!"); 11459 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 11460 "First node in topological sort is not the entry token!"); 11461 assert(AllNodes.front().getNodeId() == 0 && 11462 "First node in topological sort has non-zero id!"); 11463 assert(AllNodes.front().getNumOperands() == 0 && 11464 "First node in topological sort has operands!"); 11465 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 11466 "Last node in topologic sort has unexpected id!"); 11467 assert(AllNodes.back().use_empty() && 11468 "Last node in topologic sort has users!"); 11469 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 11470 return DAGSize; 11471 } 11472 11473 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 11474 /// value is produced by SD. 11475 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 11476 for (SDNode *SD : DB->getSDNodes()) { 11477 if (!SD) 11478 continue; 11479 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 11480 SD->setHasDebugValue(true); 11481 } 11482 DbgInfo->add(DB, isParameter); 11483 } 11484 11485 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 11486 11487 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 11488 SDValue NewMemOpChain) { 11489 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 11490 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 11491 // The new memory operation must have the same position as the old load in 11492 // terms of memory dependency. Create a TokenFactor for the old load and new 11493 // memory operation and update uses of the old load's output chain to use that 11494 // TokenFactor. 11495 if (OldChain == NewMemOpChain || OldChain.use_empty()) 11496 return NewMemOpChain; 11497 11498 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 11499 OldChain, NewMemOpChain); 11500 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 11501 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 11502 return TokenFactor; 11503 } 11504 11505 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 11506 SDValue NewMemOp) { 11507 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 11508 SDValue OldChain = SDValue(OldLoad, 1); 11509 SDValue NewMemOpChain = NewMemOp.getValue(1); 11510 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 11511 } 11512 11513 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 11514 Function **OutFunction) { 11515 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 11516 11517 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 11518 auto *Module = MF->getFunction().getParent(); 11519 auto *Function = Module->getFunction(Symbol); 11520 11521 if (OutFunction != nullptr) 11522 *OutFunction = Function; 11523 11524 if (Function != nullptr) { 11525 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 11526 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 11527 } 11528 11529 std::string ErrorStr; 11530 raw_string_ostream ErrorFormatter(ErrorStr); 11531 ErrorFormatter << "Undefined external symbol "; 11532 ErrorFormatter << '"' << Symbol << '"'; 11533 report_fatal_error(Twine(ErrorFormatter.str())); 11534 } 11535 11536 //===----------------------------------------------------------------------===// 11537 // SDNode Class 11538 //===----------------------------------------------------------------------===// 11539 11540 bool llvm::isNullConstant(SDValue V) { 11541 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 11542 return Const != nullptr && Const->isZero(); 11543 } 11544 11545 bool llvm::isNullFPConstant(SDValue V) { 11546 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 11547 return Const != nullptr && Const->isZero() && !Const->isNegative(); 11548 } 11549 11550 bool llvm::isAllOnesConstant(SDValue V) { 11551 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 11552 return Const != nullptr && Const->isAllOnes(); 11553 } 11554 11555 bool llvm::isOneConstant(SDValue V) { 11556 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 11557 return Const != nullptr && Const->isOne(); 11558 } 11559 11560 bool llvm::isMinSignedConstant(SDValue V) { 11561 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 11562 return Const != nullptr && Const->isMinSignedValue(); 11563 } 11564 11565 bool llvm::isNeutralConstant(unsigned Opcode, SDNodeFlags Flags, SDValue V, 11566 unsigned OperandNo) { 11567 // NOTE: The cases should match with IR's ConstantExpr::getBinOpIdentity(). 11568 // TODO: Target-specific opcodes could be added. 11569 if (auto *Const = isConstOrConstSplat(V)) { 11570 switch (Opcode) { 11571 case ISD::ADD: 11572 case ISD::OR: 11573 case ISD::XOR: 11574 case ISD::UMAX: 11575 return Const->isZero(); 11576 case ISD::MUL: 11577 return Const->isOne(); 11578 case ISD::AND: 11579 case ISD::UMIN: 11580 return Const->isAllOnes(); 11581 case ISD::SMAX: 11582 return Const->isMinSignedValue(); 11583 case ISD::SMIN: 11584 return Const->isMaxSignedValue(); 11585 case ISD::SUB: 11586 case ISD::SHL: 11587 case ISD::SRA: 11588 case ISD::SRL: 11589 return OperandNo == 1 && Const->isZero(); 11590 case ISD::UDIV: 11591 case ISD::SDIV: 11592 return OperandNo == 1 && Const->isOne(); 11593 } 11594 } else if (auto *ConstFP = isConstOrConstSplatFP(V)) { 11595 switch (Opcode) { 11596 case ISD::FADD: 11597 return ConstFP->isZero() && 11598 (Flags.hasNoSignedZeros() || ConstFP->isNegative()); 11599 case ISD::FSUB: 11600 return OperandNo == 1 && ConstFP->isZero() && 11601 (Flags.hasNoSignedZeros() || !ConstFP->isNegative()); 11602 case ISD::FMUL: 11603 return ConstFP->isExactlyValue(1.0); 11604 case ISD::FDIV: 11605 return OperandNo == 1 && ConstFP->isExactlyValue(1.0); 11606 case ISD::FMINNUM: 11607 case ISD::FMAXNUM: { 11608 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 11609 EVT VT = V.getValueType(); 11610 const fltSemantics &Semantics = SelectionDAG::EVTToAPFloatSemantics(VT); 11611 APFloat NeutralAF = !Flags.hasNoNaNs() 11612 ? APFloat::getQNaN(Semantics) 11613 : !Flags.hasNoInfs() 11614 ? APFloat::getInf(Semantics) 11615 : APFloat::getLargest(Semantics); 11616 if (Opcode == ISD::FMAXNUM) 11617 NeutralAF.changeSign(); 11618 11619 return ConstFP->isExactlyValue(NeutralAF); 11620 } 11621 } 11622 } 11623 return false; 11624 } 11625 11626 SDValue llvm::peekThroughBitcasts(SDValue V) { 11627 while (V.getOpcode() == ISD::BITCAST) 11628 V = V.getOperand(0); 11629 return V; 11630 } 11631 11632 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 11633 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 11634 V = V.getOperand(0); 11635 return V; 11636 } 11637 11638 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 11639 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 11640 V = V.getOperand(0); 11641 return V; 11642 } 11643 11644 SDValue llvm::peekThroughTruncates(SDValue V) { 11645 while (V.getOpcode() == ISD::TRUNCATE) 11646 V = V.getOperand(0); 11647 return V; 11648 } 11649 11650 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 11651 if (V.getOpcode() != ISD::XOR) 11652 return false; 11653 V = peekThroughBitcasts(V.getOperand(1)); 11654 unsigned NumBits = V.getScalarValueSizeInBits(); 11655 ConstantSDNode *C = 11656 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 11657 return C && (C->getAPIntValue().countr_one() >= NumBits); 11658 } 11659 11660 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 11661 bool AllowTruncation) { 11662 EVT VT = N.getValueType(); 11663 APInt DemandedElts = VT.isFixedLengthVector() 11664 ? APInt::getAllOnes(VT.getVectorMinNumElements()) 11665 : APInt(1, 1); 11666 return isConstOrConstSplat(N, DemandedElts, AllowUndefs, AllowTruncation); 11667 } 11668 11669 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 11670 bool AllowUndefs, 11671 bool AllowTruncation) { 11672 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 11673 return CN; 11674 11675 // SplatVectors can truncate their operands. Ignore that case here unless 11676 // AllowTruncation is set. 11677 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 11678 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 11679 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 11680 EVT CVT = CN->getValueType(0); 11681 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 11682 if (AllowTruncation || CVT == VecEltVT) 11683 return CN; 11684 } 11685 } 11686 11687 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 11688 BitVector UndefElements; 11689 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 11690 11691 // BuildVectors can truncate their operands. Ignore that case here unless 11692 // AllowTruncation is set. 11693 // TODO: Look into whether we should allow UndefElements in non-DemandedElts 11694 if (CN && (UndefElements.none() || AllowUndefs)) { 11695 EVT CVT = CN->getValueType(0); 11696 EVT NSVT = N.getValueType().getScalarType(); 11697 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 11698 if (AllowTruncation || (CVT == NSVT)) 11699 return CN; 11700 } 11701 } 11702 11703 return nullptr; 11704 } 11705 11706 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 11707 EVT VT = N.getValueType(); 11708 APInt DemandedElts = VT.isFixedLengthVector() 11709 ? APInt::getAllOnes(VT.getVectorMinNumElements()) 11710 : APInt(1, 1); 11711 return isConstOrConstSplatFP(N, DemandedElts, AllowUndefs); 11712 } 11713 11714 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 11715 const APInt &DemandedElts, 11716 bool AllowUndefs) { 11717 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 11718 return CN; 11719 11720 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 11721 BitVector UndefElements; 11722 ConstantFPSDNode *CN = 11723 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 11724 // TODO: Look into whether we should allow UndefElements in non-DemandedElts 11725 if (CN && (UndefElements.none() || AllowUndefs)) 11726 return CN; 11727 } 11728 11729 if (N.getOpcode() == ISD::SPLAT_VECTOR) 11730 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 11731 return CN; 11732 11733 return nullptr; 11734 } 11735 11736 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 11737 // TODO: may want to use peekThroughBitcast() here. 11738 ConstantSDNode *C = 11739 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true); 11740 return C && C->isZero(); 11741 } 11742 11743 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 11744 ConstantSDNode *C = 11745 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true); 11746 return C && C->isOne(); 11747 } 11748 11749 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 11750 N = peekThroughBitcasts(N); 11751 unsigned BitWidth = N.getScalarValueSizeInBits(); 11752 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 11753 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth; 11754 } 11755 11756 HandleSDNode::~HandleSDNode() { 11757 DropOperands(); 11758 } 11759 11760 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 11761 const DebugLoc &DL, 11762 const GlobalValue *GA, EVT VT, 11763 int64_t o, unsigned TF) 11764 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 11765 TheGlobal = GA; 11766 } 11767 11768 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 11769 EVT VT, unsigned SrcAS, 11770 unsigned DestAS) 11771 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 11772 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 11773 11774 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 11775 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 11776 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 11777 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 11778 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 11779 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 11780 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 11781 11782 // We check here that the size of the memory operand fits within the size of 11783 // the MMO. This is because the MMO might indicate only a possible address 11784 // range instead of specifying the affected memory addresses precisely. 11785 // TODO: Make MachineMemOperands aware of scalable vectors. 11786 assert(memvt.getStoreSize().getKnownMinValue() <= MMO->getSize() && 11787 "Size mismatch!"); 11788 } 11789 11790 /// Profile - Gather unique data for the node. 11791 /// 11792 void SDNode::Profile(FoldingSetNodeID &ID) const { 11793 AddNodeIDNode(ID, this); 11794 } 11795 11796 namespace { 11797 11798 struct EVTArray { 11799 std::vector<EVT> VTs; 11800 11801 EVTArray() { 11802 VTs.reserve(MVT::VALUETYPE_SIZE); 11803 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i) 11804 VTs.push_back(MVT((MVT::SimpleValueType)i)); 11805 } 11806 }; 11807 11808 } // end anonymous namespace 11809 11810 /// getValueTypeList - Return a pointer to the specified value type. 11811 /// 11812 const EVT *SDNode::getValueTypeList(EVT VT) { 11813 static std::set<EVT, EVT::compareRawBits> EVTs; 11814 static EVTArray SimpleVTArray; 11815 static sys::SmartMutex<true> VTMutex; 11816 11817 if (VT.isExtended()) { 11818 sys::SmartScopedLock<true> Lock(VTMutex); 11819 return &(*EVTs.insert(VT).first); 11820 } 11821 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!"); 11822 return &SimpleVTArray.VTs[VT.getSimpleVT().SimpleTy]; 11823 } 11824 11825 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 11826 /// indicated value. This method ignores uses of other values defined by this 11827 /// operation. 11828 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 11829 assert(Value < getNumValues() && "Bad value!"); 11830 11831 // TODO: Only iterate over uses of a given value of the node 11832 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 11833 if (UI.getUse().getResNo() == Value) { 11834 if (NUses == 0) 11835 return false; 11836 --NUses; 11837 } 11838 } 11839 11840 // Found exactly the right number of uses? 11841 return NUses == 0; 11842 } 11843 11844 /// hasAnyUseOfValue - Return true if there are any use of the indicated 11845 /// value. This method ignores uses of other values defined by this operation. 11846 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 11847 assert(Value < getNumValues() && "Bad value!"); 11848 11849 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 11850 if (UI.getUse().getResNo() == Value) 11851 return true; 11852 11853 return false; 11854 } 11855 11856 /// isOnlyUserOf - Return true if this node is the only use of N. 11857 bool SDNode::isOnlyUserOf(const SDNode *N) const { 11858 bool Seen = false; 11859 for (const SDNode *User : N->uses()) { 11860 if (User == this) 11861 Seen = true; 11862 else 11863 return false; 11864 } 11865 11866 return Seen; 11867 } 11868 11869 /// Return true if the only users of N are contained in Nodes. 11870 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 11871 bool Seen = false; 11872 for (const SDNode *User : N->uses()) { 11873 if (llvm::is_contained(Nodes, User)) 11874 Seen = true; 11875 else 11876 return false; 11877 } 11878 11879 return Seen; 11880 } 11881 11882 /// isOperand - Return true if this node is an operand of N. 11883 bool SDValue::isOperandOf(const SDNode *N) const { 11884 return is_contained(N->op_values(), *this); 11885 } 11886 11887 bool SDNode::isOperandOf(const SDNode *N) const { 11888 return any_of(N->op_values(), 11889 [this](SDValue Op) { return this == Op.getNode(); }); 11890 } 11891 11892 /// reachesChainWithoutSideEffects - Return true if this operand (which must 11893 /// be a chain) reaches the specified operand without crossing any 11894 /// side-effecting instructions on any chain path. In practice, this looks 11895 /// through token factors and non-volatile loads. In order to remain efficient, 11896 /// this only looks a couple of nodes in, it does not do an exhaustive search. 11897 /// 11898 /// Note that we only need to examine chains when we're searching for 11899 /// side-effects; SelectionDAG requires that all side-effects are represented 11900 /// by chains, even if another operand would force a specific ordering. This 11901 /// constraint is necessary to allow transformations like splitting loads. 11902 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 11903 unsigned Depth) const { 11904 if (*this == Dest) return true; 11905 11906 // Don't search too deeply, we just want to be able to see through 11907 // TokenFactor's etc. 11908 if (Depth == 0) return false; 11909 11910 // If this is a token factor, all inputs to the TF happen in parallel. 11911 if (getOpcode() == ISD::TokenFactor) { 11912 // First, try a shallow search. 11913 if (is_contained((*this)->ops(), Dest)) { 11914 // We found the chain we want as an operand of this TokenFactor. 11915 // Essentially, we reach the chain without side-effects if we could 11916 // serialize the TokenFactor into a simple chain of operations with 11917 // Dest as the last operation. This is automatically true if the 11918 // chain has one use: there are no other ordering constraints. 11919 // If the chain has more than one use, we give up: some other 11920 // use of Dest might force a side-effect between Dest and the current 11921 // node. 11922 if (Dest.hasOneUse()) 11923 return true; 11924 } 11925 // Next, try a deep search: check whether every operand of the TokenFactor 11926 // reaches Dest. 11927 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 11928 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 11929 }); 11930 } 11931 11932 // Loads don't have side effects, look through them. 11933 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 11934 if (Ld->isUnordered()) 11935 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 11936 } 11937 return false; 11938 } 11939 11940 bool SDNode::hasPredecessor(const SDNode *N) const { 11941 SmallPtrSet<const SDNode *, 32> Visited; 11942 SmallVector<const SDNode *, 16> Worklist; 11943 Worklist.push_back(this); 11944 return hasPredecessorHelper(N, Visited, Worklist); 11945 } 11946 11947 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 11948 this->Flags.intersectWith(Flags); 11949 } 11950 11951 SDValue 11952 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 11953 ArrayRef<ISD::NodeType> CandidateBinOps, 11954 bool AllowPartials) { 11955 // The pattern must end in an extract from index 0. 11956 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11957 !isNullConstant(Extract->getOperand(1))) 11958 return SDValue(); 11959 11960 // Match against one of the candidate binary ops. 11961 SDValue Op = Extract->getOperand(0); 11962 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 11963 return Op.getOpcode() == unsigned(BinOp); 11964 })) 11965 return SDValue(); 11966 11967 // Floating-point reductions may require relaxed constraints on the final step 11968 // of the reduction because they may reorder intermediate operations. 11969 unsigned CandidateBinOp = Op.getOpcode(); 11970 if (Op.getValueType().isFloatingPoint()) { 11971 SDNodeFlags Flags = Op->getFlags(); 11972 switch (CandidateBinOp) { 11973 case ISD::FADD: 11974 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 11975 return SDValue(); 11976 break; 11977 default: 11978 llvm_unreachable("Unhandled FP opcode for binop reduction"); 11979 } 11980 } 11981 11982 // Matching failed - attempt to see if we did enough stages that a partial 11983 // reduction from a subvector is possible. 11984 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 11985 if (!AllowPartials || !Op) 11986 return SDValue(); 11987 EVT OpVT = Op.getValueType(); 11988 EVT OpSVT = OpVT.getScalarType(); 11989 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 11990 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 11991 return SDValue(); 11992 BinOp = (ISD::NodeType)CandidateBinOp; 11993 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 11994 getVectorIdxConstant(0, SDLoc(Op))); 11995 }; 11996 11997 // At each stage, we're looking for something that looks like: 11998 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 11999 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 12000 // i32 undef, i32 undef, i32 undef, i32 undef> 12001 // %a = binop <8 x i32> %op, %s 12002 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 12003 // we expect something like: 12004 // <4,5,6,7,u,u,u,u> 12005 // <2,3,u,u,u,u,u,u> 12006 // <1,u,u,u,u,u,u,u> 12007 // While a partial reduction match would be: 12008 // <2,3,u,u,u,u,u,u> 12009 // <1,u,u,u,u,u,u,u> 12010 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 12011 SDValue PrevOp; 12012 for (unsigned i = 0; i < Stages; ++i) { 12013 unsigned MaskEnd = (1 << i); 12014 12015 if (Op.getOpcode() != CandidateBinOp) 12016 return PartialReduction(PrevOp, MaskEnd); 12017 12018 SDValue Op0 = Op.getOperand(0); 12019 SDValue Op1 = Op.getOperand(1); 12020 12021 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 12022 if (Shuffle) { 12023 Op = Op1; 12024 } else { 12025 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 12026 Op = Op0; 12027 } 12028 12029 // The first operand of the shuffle should be the same as the other operand 12030 // of the binop. 12031 if (!Shuffle || Shuffle->getOperand(0) != Op) 12032 return PartialReduction(PrevOp, MaskEnd); 12033 12034 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 12035 for (int Index = 0; Index < (int)MaskEnd; ++Index) 12036 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 12037 return PartialReduction(PrevOp, MaskEnd); 12038 12039 PrevOp = Op; 12040 } 12041 12042 // Handle subvector reductions, which tend to appear after the shuffle 12043 // reduction stages. 12044 while (Op.getOpcode() == CandidateBinOp) { 12045 unsigned NumElts = Op.getValueType().getVectorNumElements(); 12046 SDValue Op0 = Op.getOperand(0); 12047 SDValue Op1 = Op.getOperand(1); 12048 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 12049 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 12050 Op0.getOperand(0) != Op1.getOperand(0)) 12051 break; 12052 SDValue Src = Op0.getOperand(0); 12053 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 12054 if (NumSrcElts != (2 * NumElts)) 12055 break; 12056 if (!(Op0.getConstantOperandAPInt(1) == 0 && 12057 Op1.getConstantOperandAPInt(1) == NumElts) && 12058 !(Op1.getConstantOperandAPInt(1) == 0 && 12059 Op0.getConstantOperandAPInt(1) == NumElts)) 12060 break; 12061 Op = Src; 12062 } 12063 12064 BinOp = (ISD::NodeType)CandidateBinOp; 12065 return Op; 12066 } 12067 12068 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 12069 EVT VT = N->getValueType(0); 12070 EVT EltVT = VT.getVectorElementType(); 12071 unsigned NE = VT.getVectorNumElements(); 12072 12073 SDLoc dl(N); 12074 12075 // If ResNE is 0, fully unroll the vector op. 12076 if (ResNE == 0) 12077 ResNE = NE; 12078 else if (NE > ResNE) 12079 NE = ResNE; 12080 12081 if (N->getNumValues() == 2) { 12082 SmallVector<SDValue, 8> Scalars0, Scalars1; 12083 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 12084 EVT VT1 = N->getValueType(1); 12085 EVT EltVT1 = VT1.getVectorElementType(); 12086 12087 unsigned i; 12088 for (i = 0; i != NE; ++i) { 12089 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 12090 SDValue Operand = N->getOperand(j); 12091 EVT OperandVT = Operand.getValueType(); 12092 12093 // A vector operand; extract a single element. 12094 EVT OperandEltVT = OperandVT.getVectorElementType(); 12095 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 12096 Operand, getVectorIdxConstant(i, dl)); 12097 } 12098 12099 SDValue EltOp = getNode(N->getOpcode(), dl, {EltVT, EltVT1}, Operands); 12100 Scalars0.push_back(EltOp); 12101 Scalars1.push_back(EltOp.getValue(1)); 12102 } 12103 12104 SDValue Vec0 = getBuildVector(VT, dl, Scalars0); 12105 SDValue Vec1 = getBuildVector(VT1, dl, Scalars1); 12106 return getMergeValues({Vec0, Vec1}, dl); 12107 } 12108 12109 assert(N->getNumValues() == 1 && 12110 "Can't unroll a vector with multiple results!"); 12111 12112 SmallVector<SDValue, 8> Scalars; 12113 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 12114 12115 unsigned i; 12116 for (i= 0; i != NE; ++i) { 12117 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 12118 SDValue Operand = N->getOperand(j); 12119 EVT OperandVT = Operand.getValueType(); 12120 if (OperandVT.isVector()) { 12121 // A vector operand; extract a single element. 12122 EVT OperandEltVT = OperandVT.getVectorElementType(); 12123 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 12124 Operand, getVectorIdxConstant(i, dl)); 12125 } else { 12126 // A scalar operand; just use it as is. 12127 Operands[j] = Operand; 12128 } 12129 } 12130 12131 switch (N->getOpcode()) { 12132 default: { 12133 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 12134 N->getFlags())); 12135 break; 12136 } 12137 case ISD::VSELECT: 12138 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 12139 break; 12140 case ISD::SHL: 12141 case ISD::SRA: 12142 case ISD::SRL: 12143 case ISD::ROTL: 12144 case ISD::ROTR: 12145 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 12146 getShiftAmountOperand(Operands[0].getValueType(), 12147 Operands[1]))); 12148 break; 12149 case ISD::SIGN_EXTEND_INREG: { 12150 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 12151 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 12152 Operands[0], 12153 getValueType(ExtVT))); 12154 } 12155 } 12156 } 12157 12158 for (; i < ResNE; ++i) 12159 Scalars.push_back(getUNDEF(EltVT)); 12160 12161 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 12162 return getBuildVector(VecVT, dl, Scalars); 12163 } 12164 12165 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 12166 SDNode *N, unsigned ResNE) { 12167 unsigned Opcode = N->getOpcode(); 12168 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 12169 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 12170 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 12171 "Expected an overflow opcode"); 12172 12173 EVT ResVT = N->getValueType(0); 12174 EVT OvVT = N->getValueType(1); 12175 EVT ResEltVT = ResVT.getVectorElementType(); 12176 EVT OvEltVT = OvVT.getVectorElementType(); 12177 SDLoc dl(N); 12178 12179 // If ResNE is 0, fully unroll the vector op. 12180 unsigned NE = ResVT.getVectorNumElements(); 12181 if (ResNE == 0) 12182 ResNE = NE; 12183 else if (NE > ResNE) 12184 NE = ResNE; 12185 12186 SmallVector<SDValue, 8> LHSScalars; 12187 SmallVector<SDValue, 8> RHSScalars; 12188 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 12189 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 12190 12191 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 12192 SDVTList VTs = getVTList(ResEltVT, SVT); 12193 SmallVector<SDValue, 8> ResScalars; 12194 SmallVector<SDValue, 8> OvScalars; 12195 for (unsigned i = 0; i < NE; ++i) { 12196 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 12197 SDValue Ov = 12198 getSelect(dl, OvEltVT, Res.getValue(1), 12199 getBoolConstant(true, dl, OvEltVT, ResVT), 12200 getConstant(0, dl, OvEltVT)); 12201 12202 ResScalars.push_back(Res); 12203 OvScalars.push_back(Ov); 12204 } 12205 12206 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 12207 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 12208 12209 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 12210 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 12211 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 12212 getBuildVector(NewOvVT, dl, OvScalars)); 12213 } 12214 12215 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 12216 LoadSDNode *Base, 12217 unsigned Bytes, 12218 int Dist) const { 12219 if (LD->isVolatile() || Base->isVolatile()) 12220 return false; 12221 // TODO: probably too restrictive for atomics, revisit 12222 if (!LD->isSimple()) 12223 return false; 12224 if (LD->isIndexed() || Base->isIndexed()) 12225 return false; 12226 if (LD->getChain() != Base->getChain()) 12227 return false; 12228 EVT VT = LD->getMemoryVT(); 12229 if (VT.getSizeInBits() / 8 != Bytes) 12230 return false; 12231 12232 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 12233 auto LocDecomp = BaseIndexOffset::match(LD, *this); 12234 12235 int64_t Offset = 0; 12236 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 12237 return (Dist * (int64_t)Bytes == Offset); 12238 return false; 12239 } 12240 12241 /// InferPtrAlignment - Infer alignment of a load / store address. Return 12242 /// std::nullopt if it cannot be inferred. 12243 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 12244 // If this is a GlobalAddress + cst, return the alignment. 12245 const GlobalValue *GV = nullptr; 12246 int64_t GVOffset = 0; 12247 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 12248 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 12249 KnownBits Known(PtrWidth); 12250 llvm::computeKnownBits(GV, Known, getDataLayout()); 12251 unsigned AlignBits = Known.countMinTrailingZeros(); 12252 if (AlignBits) 12253 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 12254 } 12255 12256 // If this is a direct reference to a stack slot, use information about the 12257 // stack slot's alignment. 12258 int FrameIdx = INT_MIN; 12259 int64_t FrameOffset = 0; 12260 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 12261 FrameIdx = FI->getIndex(); 12262 } else if (isBaseWithConstantOffset(Ptr) && 12263 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 12264 // Handle FI+Cst 12265 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 12266 FrameOffset = Ptr.getConstantOperandVal(1); 12267 } 12268 12269 if (FrameIdx != INT_MIN) { 12270 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 12271 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 12272 } 12273 12274 return std::nullopt; 12275 } 12276 12277 /// Split the scalar node with EXTRACT_ELEMENT using the provided 12278 /// VTs and return the low/high part. 12279 std::pair<SDValue, SDValue> SelectionDAG::SplitScalar(const SDValue &N, 12280 const SDLoc &DL, 12281 const EVT &LoVT, 12282 const EVT &HiVT) { 12283 assert(!LoVT.isVector() && !HiVT.isVector() && !N.getValueType().isVector() && 12284 "Split node must be a scalar type"); 12285 SDValue Lo = 12286 getNode(ISD::EXTRACT_ELEMENT, DL, LoVT, N, getIntPtrConstant(0, DL)); 12287 SDValue Hi = 12288 getNode(ISD::EXTRACT_ELEMENT, DL, HiVT, N, getIntPtrConstant(1, DL)); 12289 return std::make_pair(Lo, Hi); 12290 } 12291 12292 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 12293 /// which is split (or expanded) into two not necessarily identical pieces. 12294 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 12295 // Currently all types are split in half. 12296 EVT LoVT, HiVT; 12297 if (!VT.isVector()) 12298 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 12299 else 12300 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 12301 12302 return std::make_pair(LoVT, HiVT); 12303 } 12304 12305 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 12306 /// type, dependent on an enveloping VT that has been split into two identical 12307 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 12308 std::pair<EVT, EVT> 12309 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 12310 bool *HiIsEmpty) const { 12311 EVT EltTp = VT.getVectorElementType(); 12312 // Examples: 12313 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 12314 // custom VL=9 with enveloping VL=8/8 yields 8/1 12315 // custom VL=10 with enveloping VL=8/8 yields 8/2 12316 // etc. 12317 ElementCount VTNumElts = VT.getVectorElementCount(); 12318 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 12319 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 12320 "Mixing fixed width and scalable vectors when enveloping a type"); 12321 EVT LoVT, HiVT; 12322 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 12323 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 12324 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 12325 *HiIsEmpty = false; 12326 } else { 12327 // Flag that hi type has zero storage size, but return split envelop type 12328 // (this would be easier if vector types with zero elements were allowed). 12329 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 12330 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 12331 *HiIsEmpty = true; 12332 } 12333 return std::make_pair(LoVT, HiVT); 12334 } 12335 12336 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 12337 /// low/high part. 12338 std::pair<SDValue, SDValue> 12339 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 12340 const EVT &HiVT) { 12341 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 12342 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 12343 "Splitting vector with an invalid mixture of fixed and scalable " 12344 "vector types"); 12345 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 12346 N.getValueType().getVectorMinNumElements() && 12347 "More vector elements requested than available!"); 12348 SDValue Lo, Hi; 12349 Lo = 12350 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 12351 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 12352 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 12353 // IDX with the runtime scaling factor of the result vector type. For 12354 // fixed-width result vectors, that runtime scaling factor is 1. 12355 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 12356 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 12357 return std::make_pair(Lo, Hi); 12358 } 12359 12360 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT, 12361 const SDLoc &DL) { 12362 // Split the vector length parameter. 12363 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts). 12364 EVT VT = N.getValueType(); 12365 assert(VecVT.getVectorElementCount().isKnownEven() && 12366 "Expecting the mask to be an evenly-sized vector"); 12367 unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2; 12368 SDValue HalfNumElts = 12369 VecVT.isFixedLengthVector() 12370 ? getConstant(HalfMinNumElts, DL, VT) 12371 : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts)); 12372 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts); 12373 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts); 12374 return std::make_pair(Lo, Hi); 12375 } 12376 12377 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 12378 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 12379 EVT VT = N.getValueType(); 12380 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 12381 NextPowerOf2(VT.getVectorNumElements())); 12382 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 12383 getVectorIdxConstant(0, DL)); 12384 } 12385 12386 void SelectionDAG::ExtractVectorElements(SDValue Op, 12387 SmallVectorImpl<SDValue> &Args, 12388 unsigned Start, unsigned Count, 12389 EVT EltVT) { 12390 EVT VT = Op.getValueType(); 12391 if (Count == 0) 12392 Count = VT.getVectorNumElements(); 12393 if (EltVT == EVT()) 12394 EltVT = VT.getVectorElementType(); 12395 SDLoc SL(Op); 12396 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 12397 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 12398 getVectorIdxConstant(i, SL))); 12399 } 12400 } 12401 12402 // getAddressSpace - Return the address space this GlobalAddress belongs to. 12403 unsigned GlobalAddressSDNode::getAddressSpace() const { 12404 return getGlobal()->getType()->getAddressSpace(); 12405 } 12406 12407 Type *ConstantPoolSDNode::getType() const { 12408 if (isMachineConstantPoolEntry()) 12409 return Val.MachineCPVal->getType(); 12410 return Val.ConstVal->getType(); 12411 } 12412 12413 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 12414 unsigned &SplatBitSize, 12415 bool &HasAnyUndefs, 12416 unsigned MinSplatBits, 12417 bool IsBigEndian) const { 12418 EVT VT = getValueType(0); 12419 assert(VT.isVector() && "Expected a vector type"); 12420 unsigned VecWidth = VT.getSizeInBits(); 12421 if (MinSplatBits > VecWidth) 12422 return false; 12423 12424 // FIXME: The widths are based on this node's type, but build vectors can 12425 // truncate their operands. 12426 SplatValue = APInt(VecWidth, 0); 12427 SplatUndef = APInt(VecWidth, 0); 12428 12429 // Get the bits. Bits with undefined values (when the corresponding element 12430 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 12431 // in SplatValue. If any of the values are not constant, give up and return 12432 // false. 12433 unsigned int NumOps = getNumOperands(); 12434 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 12435 unsigned EltWidth = VT.getScalarSizeInBits(); 12436 12437 for (unsigned j = 0; j < NumOps; ++j) { 12438 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 12439 SDValue OpVal = getOperand(i); 12440 unsigned BitPos = j * EltWidth; 12441 12442 if (OpVal.isUndef()) 12443 SplatUndef.setBits(BitPos, BitPos + EltWidth); 12444 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 12445 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 12446 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 12447 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 12448 else 12449 return false; 12450 } 12451 12452 // The build_vector is all constants or undefs. Find the smallest element 12453 // size that splats the vector. 12454 HasAnyUndefs = (SplatUndef != 0); 12455 12456 // FIXME: This does not work for vectors with elements less than 8 bits. 12457 while (VecWidth > 8) { 12458 // If we can't split in half, stop here. 12459 if (VecWidth & 1) 12460 break; 12461 12462 unsigned HalfSize = VecWidth / 2; 12463 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize); 12464 APInt LowValue = SplatValue.extractBits(HalfSize, 0); 12465 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize); 12466 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0); 12467 12468 // If the two halves do not match (ignoring undef bits), stop here. 12469 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 12470 MinSplatBits > HalfSize) 12471 break; 12472 12473 SplatValue = HighValue | LowValue; 12474 SplatUndef = HighUndef & LowUndef; 12475 12476 VecWidth = HalfSize; 12477 } 12478 12479 // FIXME: The loop above only tries to split in halves. But if the input 12480 // vector for example is <3 x i16> it wouldn't be able to detect a 12481 // SplatBitSize of 16. No idea if that is a design flaw currently limiting 12482 // optimizations. I guess that back in the days when this helper was created 12483 // vectors normally was power-of-2 sized. 12484 12485 SplatBitSize = VecWidth; 12486 return true; 12487 } 12488 12489 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 12490 BitVector *UndefElements) const { 12491 unsigned NumOps = getNumOperands(); 12492 if (UndefElements) { 12493 UndefElements->clear(); 12494 UndefElements->resize(NumOps); 12495 } 12496 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 12497 if (!DemandedElts) 12498 return SDValue(); 12499 SDValue Splatted; 12500 for (unsigned i = 0; i != NumOps; ++i) { 12501 if (!DemandedElts[i]) 12502 continue; 12503 SDValue Op = getOperand(i); 12504 if (Op.isUndef()) { 12505 if (UndefElements) 12506 (*UndefElements)[i] = true; 12507 } else if (!Splatted) { 12508 Splatted = Op; 12509 } else if (Splatted != Op) { 12510 return SDValue(); 12511 } 12512 } 12513 12514 if (!Splatted) { 12515 unsigned FirstDemandedIdx = DemandedElts.countr_zero(); 12516 assert(getOperand(FirstDemandedIdx).isUndef() && 12517 "Can only have a splat without a constant for all undefs."); 12518 return getOperand(FirstDemandedIdx); 12519 } 12520 12521 return Splatted; 12522 } 12523 12524 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 12525 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 12526 return getSplatValue(DemandedElts, UndefElements); 12527 } 12528 12529 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 12530 SmallVectorImpl<SDValue> &Sequence, 12531 BitVector *UndefElements) const { 12532 unsigned NumOps = getNumOperands(); 12533 Sequence.clear(); 12534 if (UndefElements) { 12535 UndefElements->clear(); 12536 UndefElements->resize(NumOps); 12537 } 12538 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 12539 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 12540 return false; 12541 12542 // Set the undefs even if we don't find a sequence (like getSplatValue). 12543 if (UndefElements) 12544 for (unsigned I = 0; I != NumOps; ++I) 12545 if (DemandedElts[I] && getOperand(I).isUndef()) 12546 (*UndefElements)[I] = true; 12547 12548 // Iteratively widen the sequence length looking for repetitions. 12549 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 12550 Sequence.append(SeqLen, SDValue()); 12551 for (unsigned I = 0; I != NumOps; ++I) { 12552 if (!DemandedElts[I]) 12553 continue; 12554 SDValue &SeqOp = Sequence[I % SeqLen]; 12555 SDValue Op = getOperand(I); 12556 if (Op.isUndef()) { 12557 if (!SeqOp) 12558 SeqOp = Op; 12559 continue; 12560 } 12561 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 12562 Sequence.clear(); 12563 break; 12564 } 12565 SeqOp = Op; 12566 } 12567 if (!Sequence.empty()) 12568 return true; 12569 } 12570 12571 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 12572 return false; 12573 } 12574 12575 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 12576 BitVector *UndefElements) const { 12577 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 12578 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 12579 } 12580 12581 ConstantSDNode * 12582 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 12583 BitVector *UndefElements) const { 12584 return dyn_cast_or_null<ConstantSDNode>( 12585 getSplatValue(DemandedElts, UndefElements)); 12586 } 12587 12588 ConstantSDNode * 12589 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 12590 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 12591 } 12592 12593 ConstantFPSDNode * 12594 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 12595 BitVector *UndefElements) const { 12596 return dyn_cast_or_null<ConstantFPSDNode>( 12597 getSplatValue(DemandedElts, UndefElements)); 12598 } 12599 12600 ConstantFPSDNode * 12601 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 12602 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 12603 } 12604 12605 int32_t 12606 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 12607 uint32_t BitWidth) const { 12608 if (ConstantFPSDNode *CN = 12609 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 12610 bool IsExact; 12611 APSInt IntVal(BitWidth); 12612 const APFloat &APF = CN->getValueAPF(); 12613 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 12614 APFloat::opOK || 12615 !IsExact) 12616 return -1; 12617 12618 return IntVal.exactLogBase2(); 12619 } 12620 return -1; 12621 } 12622 12623 bool BuildVectorSDNode::getConstantRawBits( 12624 bool IsLittleEndian, unsigned DstEltSizeInBits, 12625 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const { 12626 // Early-out if this contains anything but Undef/Constant/ConstantFP. 12627 if (!isConstant()) 12628 return false; 12629 12630 unsigned NumSrcOps = getNumOperands(); 12631 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits(); 12632 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 12633 "Invalid bitcast scale"); 12634 12635 // Extract raw src bits. 12636 SmallVector<APInt> SrcBitElements(NumSrcOps, 12637 APInt::getZero(SrcEltSizeInBits)); 12638 BitVector SrcUndeElements(NumSrcOps, false); 12639 12640 for (unsigned I = 0; I != NumSrcOps; ++I) { 12641 SDValue Op = getOperand(I); 12642 if (Op.isUndef()) { 12643 SrcUndeElements.set(I); 12644 continue; 12645 } 12646 auto *CInt = dyn_cast<ConstantSDNode>(Op); 12647 auto *CFP = dyn_cast<ConstantFPSDNode>(Op); 12648 assert((CInt || CFP) && "Unknown constant"); 12649 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits) 12650 : CFP->getValueAPF().bitcastToAPInt(); 12651 } 12652 12653 // Recast to dst width. 12654 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements, 12655 SrcBitElements, UndefElements, SrcUndeElements); 12656 return true; 12657 } 12658 12659 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian, 12660 unsigned DstEltSizeInBits, 12661 SmallVectorImpl<APInt> &DstBitElements, 12662 ArrayRef<APInt> SrcBitElements, 12663 BitVector &DstUndefElements, 12664 const BitVector &SrcUndefElements) { 12665 unsigned NumSrcOps = SrcBitElements.size(); 12666 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth(); 12667 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 12668 "Invalid bitcast scale"); 12669 assert(NumSrcOps == SrcUndefElements.size() && 12670 "Vector size mismatch"); 12671 12672 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits; 12673 DstUndefElements.clear(); 12674 DstUndefElements.resize(NumDstOps, false); 12675 DstBitElements.assign(NumDstOps, APInt::getZero(DstEltSizeInBits)); 12676 12677 // Concatenate src elements constant bits together into dst element. 12678 if (SrcEltSizeInBits <= DstEltSizeInBits) { 12679 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits; 12680 for (unsigned I = 0; I != NumDstOps; ++I) { 12681 DstUndefElements.set(I); 12682 APInt &DstBits = DstBitElements[I]; 12683 for (unsigned J = 0; J != Scale; ++J) { 12684 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 12685 if (SrcUndefElements[Idx]) 12686 continue; 12687 DstUndefElements.reset(I); 12688 const APInt &SrcBits = SrcBitElements[Idx]; 12689 assert(SrcBits.getBitWidth() == SrcEltSizeInBits && 12690 "Illegal constant bitwidths"); 12691 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits); 12692 } 12693 } 12694 return; 12695 } 12696 12697 // Split src element constant bits into dst elements. 12698 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits; 12699 for (unsigned I = 0; I != NumSrcOps; ++I) { 12700 if (SrcUndefElements[I]) { 12701 DstUndefElements.set(I * Scale, (I + 1) * Scale); 12702 continue; 12703 } 12704 const APInt &SrcBits = SrcBitElements[I]; 12705 for (unsigned J = 0; J != Scale; ++J) { 12706 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 12707 APInt &DstBits = DstBitElements[Idx]; 12708 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits); 12709 } 12710 } 12711 } 12712 12713 bool BuildVectorSDNode::isConstant() const { 12714 for (const SDValue &Op : op_values()) { 12715 unsigned Opc = Op.getOpcode(); 12716 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 12717 return false; 12718 } 12719 return true; 12720 } 12721 12722 std::optional<std::pair<APInt, APInt>> 12723 BuildVectorSDNode::isConstantSequence() const { 12724 unsigned NumOps = getNumOperands(); 12725 if (NumOps < 2) 12726 return std::nullopt; 12727 12728 if (!isa<ConstantSDNode>(getOperand(0)) || 12729 !isa<ConstantSDNode>(getOperand(1))) 12730 return std::nullopt; 12731 12732 unsigned EltSize = getValueType(0).getScalarSizeInBits(); 12733 APInt Start = getConstantOperandAPInt(0).trunc(EltSize); 12734 APInt Stride = getConstantOperandAPInt(1).trunc(EltSize) - Start; 12735 12736 if (Stride.isZero()) 12737 return std::nullopt; 12738 12739 for (unsigned i = 2; i < NumOps; ++i) { 12740 if (!isa<ConstantSDNode>(getOperand(i))) 12741 return std::nullopt; 12742 12743 APInt Val = getConstantOperandAPInt(i).trunc(EltSize); 12744 if (Val != (Start + (Stride * i))) 12745 return std::nullopt; 12746 } 12747 12748 return std::make_pair(Start, Stride); 12749 } 12750 12751 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 12752 // Find the first non-undef value in the shuffle mask. 12753 unsigned i, e; 12754 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 12755 /* search */; 12756 12757 // If all elements are undefined, this shuffle can be considered a splat 12758 // (although it should eventually get simplified away completely). 12759 if (i == e) 12760 return true; 12761 12762 // Make sure all remaining elements are either undef or the same as the first 12763 // non-undef value. 12764 for (int Idx = Mask[i]; i != e; ++i) 12765 if (Mask[i] >= 0 && Mask[i] != Idx) 12766 return false; 12767 return true; 12768 } 12769 12770 // Returns the SDNode if it is a constant integer BuildVector 12771 // or constant integer. 12772 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 12773 if (isa<ConstantSDNode>(N)) 12774 return N.getNode(); 12775 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 12776 return N.getNode(); 12777 // Treat a GlobalAddress supporting constant offset folding as a 12778 // constant integer. 12779 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 12780 if (GA->getOpcode() == ISD::GlobalAddress && 12781 TLI->isOffsetFoldingLegal(GA)) 12782 return GA; 12783 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 12784 isa<ConstantSDNode>(N.getOperand(0))) 12785 return N.getNode(); 12786 return nullptr; 12787 } 12788 12789 // Returns the SDNode if it is a constant float BuildVector 12790 // or constant float. 12791 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 12792 if (isa<ConstantFPSDNode>(N)) 12793 return N.getNode(); 12794 12795 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 12796 return N.getNode(); 12797 12798 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 12799 isa<ConstantFPSDNode>(N.getOperand(0))) 12800 return N.getNode(); 12801 12802 return nullptr; 12803 } 12804 12805 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 12806 assert(!Node->OperandList && "Node already has operands"); 12807 assert(SDNode::getMaxNumOperands() >= Vals.size() && 12808 "too many operands to fit into SDNode"); 12809 SDUse *Ops = OperandRecycler.allocate( 12810 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 12811 12812 bool IsDivergent = false; 12813 for (unsigned I = 0; I != Vals.size(); ++I) { 12814 Ops[I].setUser(Node); 12815 Ops[I].setInitial(Vals[I]); 12816 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 12817 IsDivergent |= Ops[I].getNode()->isDivergent(); 12818 } 12819 Node->NumOperands = Vals.size(); 12820 Node->OperandList = Ops; 12821 if (!TLI->isSDNodeAlwaysUniform(Node)) { 12822 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, UA); 12823 Node->SDNodeBits.IsDivergent = IsDivergent; 12824 } 12825 checkForCycles(Node); 12826 } 12827 12828 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 12829 SmallVectorImpl<SDValue> &Vals) { 12830 size_t Limit = SDNode::getMaxNumOperands(); 12831 while (Vals.size() > Limit) { 12832 unsigned SliceIdx = Vals.size() - Limit; 12833 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 12834 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 12835 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 12836 Vals.emplace_back(NewTF); 12837 } 12838 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 12839 } 12840 12841 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 12842 EVT VT, SDNodeFlags Flags) { 12843 switch (Opcode) { 12844 default: 12845 return SDValue(); 12846 case ISD::ADD: 12847 case ISD::OR: 12848 case ISD::XOR: 12849 case ISD::UMAX: 12850 return getConstant(0, DL, VT); 12851 case ISD::MUL: 12852 return getConstant(1, DL, VT); 12853 case ISD::AND: 12854 case ISD::UMIN: 12855 return getAllOnesConstant(DL, VT); 12856 case ISD::SMAX: 12857 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 12858 case ISD::SMIN: 12859 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 12860 case ISD::FADD: 12861 return getConstantFP(-0.0, DL, VT); 12862 case ISD::FMUL: 12863 return getConstantFP(1.0, DL, VT); 12864 case ISD::FMINNUM: 12865 case ISD::FMAXNUM: { 12866 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 12867 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 12868 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 12869 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 12870 APFloat::getLargest(Semantics); 12871 if (Opcode == ISD::FMAXNUM) 12872 NeutralAF.changeSign(); 12873 12874 return getConstantFP(NeutralAF, DL, VT); 12875 } 12876 case ISD::FMINIMUM: 12877 case ISD::FMAXIMUM: { 12878 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF. 12879 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 12880 APFloat NeutralAF = !Flags.hasNoInfs() ? APFloat::getInf(Semantics) 12881 : APFloat::getLargest(Semantics); 12882 if (Opcode == ISD::FMAXIMUM) 12883 NeutralAF.changeSign(); 12884 12885 return getConstantFP(NeutralAF, DL, VT); 12886 } 12887 12888 } 12889 } 12890 12891 /// Helper used to make a call to a library function that has one argument of 12892 /// pointer type. 12893 /// 12894 /// Such functions include 'fegetmode', 'fesetenv' and some others, which are 12895 /// used to get or set floating-point state. They have one argument of pointer 12896 /// type, which points to the memory region containing bits of the 12897 /// floating-point state. The value returned by such function is ignored in the 12898 /// created call. 12899 /// 12900 /// \param LibFunc Reference to library function (value of RTLIB::Libcall). 12901 /// \param Ptr Pointer used to save/load state. 12902 /// \param InChain Ingoing token chain. 12903 /// \returns Outgoing chain token. 12904 SDValue SelectionDAG::makeStateFunctionCall(unsigned LibFunc, SDValue Ptr, 12905 SDValue InChain, 12906 const SDLoc &DLoc) { 12907 assert(InChain.getValueType() == MVT::Other && "Expected token chain"); 12908 TargetLowering::ArgListTy Args; 12909 TargetLowering::ArgListEntry Entry; 12910 Entry.Node = Ptr; 12911 Entry.Ty = Ptr.getValueType().getTypeForEVT(*getContext()); 12912 Args.push_back(Entry); 12913 RTLIB::Libcall LC = static_cast<RTLIB::Libcall>(LibFunc); 12914 SDValue Callee = getExternalSymbol(TLI->getLibcallName(LC), 12915 TLI->getPointerTy(getDataLayout())); 12916 TargetLowering::CallLoweringInfo CLI(*this); 12917 CLI.setDebugLoc(DLoc).setChain(InChain).setLibCallee( 12918 TLI->getLibcallCallingConv(LC), Type::getVoidTy(*getContext()), Callee, 12919 std::move(Args)); 12920 return TLI->LowerCallTo(CLI).second; 12921 } 12922 12923 void SelectionDAG::copyExtraInfo(SDNode *From, SDNode *To) { 12924 assert(From && To && "Invalid SDNode; empty source SDValue?"); 12925 auto I = SDEI.find(From); 12926 if (I == SDEI.end()) 12927 return; 12928 12929 // Use of operator[] on the DenseMap may cause an insertion, which invalidates 12930 // the iterator, hence the need to make a copy to prevent a use-after-free. 12931 NodeExtraInfo NEI = I->second; 12932 if (LLVM_LIKELY(!NEI.PCSections)) { 12933 // No deep copy required for the types of extra info set. 12934 // 12935 // FIXME: Investigate if other types of extra info also need deep copy. This 12936 // depends on the types of nodes they can be attached to: if some extra info 12937 // is only ever attached to nodes where a replacement To node is always the 12938 // node where later use and propagation of the extra info has the intended 12939 // semantics, no deep copy is required. 12940 SDEI[To] = std::move(NEI); 12941 return; 12942 } 12943 12944 // We need to copy NodeExtraInfo to all _new_ nodes that are being introduced 12945 // through the replacement of From with To. Otherwise, replacements of a node 12946 // (From) with more complex nodes (To and its operands) may result in lost 12947 // extra info where the root node (To) is insignificant in further propagating 12948 // and using extra info when further lowering to MIR. 12949 // 12950 // In the first step pre-populate the visited set with the nodes reachable 12951 // from the old From node. This avoids copying NodeExtraInfo to parts of the 12952 // DAG that is not new and should be left untouched. 12953 SmallVector<const SDNode *> Leafs{From}; // Leafs reachable with VisitFrom. 12954 DenseSet<const SDNode *> FromReach; // The set of nodes reachable from From. 12955 auto VisitFrom = [&](auto &&Self, const SDNode *N, int MaxDepth) { 12956 if (MaxDepth == 0) { 12957 // Remember this node in case we need to increase MaxDepth and continue 12958 // populating FromReach from this node. 12959 Leafs.emplace_back(N); 12960 return; 12961 } 12962 if (!FromReach.insert(N).second) 12963 return; 12964 for (const SDValue &Op : N->op_values()) 12965 Self(Self, Op.getNode(), MaxDepth - 1); 12966 }; 12967 12968 // Copy extra info to To and all its transitive operands (that are new). 12969 SmallPtrSet<const SDNode *, 8> Visited; 12970 auto DeepCopyTo = [&](auto &&Self, const SDNode *N) { 12971 if (FromReach.contains(N)) 12972 return true; 12973 if (!Visited.insert(N).second) 12974 return true; 12975 if (getEntryNode().getNode() == N) 12976 return false; 12977 for (const SDValue &Op : N->op_values()) { 12978 if (!Self(Self, Op.getNode())) 12979 return false; 12980 } 12981 // Copy only if entry node was not reached. 12982 SDEI[N] = NEI; 12983 return true; 12984 }; 12985 12986 // We first try with a lower MaxDepth, assuming that the path to common 12987 // operands between From and To is relatively short. This significantly 12988 // improves performance in the common case. The initial MaxDepth is big 12989 // enough to avoid retry in the common case; the last MaxDepth is large 12990 // enough to avoid having to use the fallback below (and protects from 12991 // potential stack exhaustion from recursion). 12992 for (int PrevDepth = 0, MaxDepth = 16; MaxDepth <= 1024; 12993 PrevDepth = MaxDepth, MaxDepth *= 2, Visited.clear()) { 12994 // StartFrom is the previous (or initial) set of leafs reachable at the 12995 // previous maximum depth. 12996 SmallVector<const SDNode *> StartFrom; 12997 std::swap(StartFrom, Leafs); 12998 for (const SDNode *N : StartFrom) 12999 VisitFrom(VisitFrom, N, MaxDepth - PrevDepth); 13000 if (LLVM_LIKELY(DeepCopyTo(DeepCopyTo, To))) 13001 return; 13002 // This should happen very rarely (reached the entry node). 13003 LLVM_DEBUG(dbgs() << __func__ << ": MaxDepth=" << MaxDepth << " too low\n"); 13004 assert(!Leafs.empty()); 13005 } 13006 13007 // This should not happen - but if it did, that means the subgraph reachable 13008 // from From has depth greater or equal to maximum MaxDepth, and VisitFrom() 13009 // could not visit all reachable common operands. Consequently, we were able 13010 // to reach the entry node. 13011 errs() << "warning: incomplete propagation of SelectionDAG::NodeExtraInfo\n"; 13012 assert(false && "From subgraph too complex - increase max. MaxDepth?"); 13013 // Best-effort fallback if assertions disabled. 13014 SDEI[To] = std::move(NEI); 13015 } 13016 13017 #ifndef NDEBUG 13018 static void checkForCyclesHelper(const SDNode *N, 13019 SmallPtrSetImpl<const SDNode*> &Visited, 13020 SmallPtrSetImpl<const SDNode*> &Checked, 13021 const llvm::SelectionDAG *DAG) { 13022 // If this node has already been checked, don't check it again. 13023 if (Checked.count(N)) 13024 return; 13025 13026 // If a node has already been visited on this depth-first walk, reject it as 13027 // a cycle. 13028 if (!Visited.insert(N).second) { 13029 errs() << "Detected cycle in SelectionDAG\n"; 13030 dbgs() << "Offending node:\n"; 13031 N->dumprFull(DAG); dbgs() << "\n"; 13032 abort(); 13033 } 13034 13035 for (const SDValue &Op : N->op_values()) 13036 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 13037 13038 Checked.insert(N); 13039 Visited.erase(N); 13040 } 13041 #endif 13042 13043 void llvm::checkForCycles(const llvm::SDNode *N, 13044 const llvm::SelectionDAG *DAG, 13045 bool force) { 13046 #ifndef NDEBUG 13047 bool check = force; 13048 #ifdef EXPENSIVE_CHECKS 13049 check = true; 13050 #endif // EXPENSIVE_CHECKS 13051 if (check) { 13052 assert(N && "Checking nonexistent SDNode"); 13053 SmallPtrSet<const SDNode*, 32> visited; 13054 SmallPtrSet<const SDNode*, 32> checked; 13055 checkForCyclesHelper(N, visited, checked, DAG); 13056 } 13057 #endif // !NDEBUG 13058 } 13059 13060 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 13061 checkForCycles(DAG->getRoot().getNode(), DAG, force); 13062 } 13063