1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements the SelectionDAG class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/SelectionDAG.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/APSInt.h" 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/BitVector.h" 20 #include "llvm/ADT/FoldingSet.h" 21 #include "llvm/ADT/None.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/Triple.h" 26 #include "llvm/ADT/Twine.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/ValueTracking.h" 29 #include "llvm/CodeGen/Analysis.h" 30 #include "llvm/CodeGen/FunctionLoweringInfo.h" 31 #include "llvm/CodeGen/ISDOpcodes.h" 32 #include "llvm/CodeGen/MachineBasicBlock.h" 33 #include "llvm/CodeGen/MachineConstantPool.h" 34 #include "llvm/CodeGen/MachineFrameInfo.h" 35 #include "llvm/CodeGen/MachineFunction.h" 36 #include "llvm/CodeGen/MachineMemOperand.h" 37 #include "llvm/CodeGen/RuntimeLibcalls.h" 38 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 39 #include "llvm/CodeGen/SelectionDAGNodes.h" 40 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 41 #include "llvm/CodeGen/TargetFrameLowering.h" 42 #include "llvm/CodeGen/TargetLowering.h" 43 #include "llvm/CodeGen/TargetRegisterInfo.h" 44 #include "llvm/CodeGen/TargetSubtargetInfo.h" 45 #include "llvm/CodeGen/ValueTypes.h" 46 #include "llvm/IR/Constant.h" 47 #include "llvm/IR/Constants.h" 48 #include "llvm/IR/DataLayout.h" 49 #include "llvm/IR/DebugInfoMetadata.h" 50 #include "llvm/IR/DebugLoc.h" 51 #include "llvm/IR/DerivedTypes.h" 52 #include "llvm/IR/Function.h" 53 #include "llvm/IR/GlobalValue.h" 54 #include "llvm/IR/Metadata.h" 55 #include "llvm/IR/Type.h" 56 #include "llvm/Support/Casting.h" 57 #include "llvm/Support/CodeGen.h" 58 #include "llvm/Support/Compiler.h" 59 #include "llvm/Support/Debug.h" 60 #include "llvm/Support/ErrorHandling.h" 61 #include "llvm/Support/KnownBits.h" 62 #include "llvm/Support/MachineValueType.h" 63 #include "llvm/Support/ManagedStatic.h" 64 #include "llvm/Support/MathExtras.h" 65 #include "llvm/Support/Mutex.h" 66 #include "llvm/Support/raw_ostream.h" 67 #include "llvm/Target/TargetMachine.h" 68 #include "llvm/Target/TargetOptions.h" 69 #include "llvm/Transforms/Utils/SizeOpts.h" 70 #include <algorithm> 71 #include <cassert> 72 #include <cstdint> 73 #include <cstdlib> 74 #include <limits> 75 #include <set> 76 #include <string> 77 #include <utility> 78 #include <vector> 79 80 using namespace llvm; 81 82 /// makeVTList - Return an instance of the SDVTList struct initialized with the 83 /// specified members. 84 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) { 85 SDVTList Res = {VTs, NumVTs}; 86 return Res; 87 } 88 89 // Default null implementations of the callbacks. 90 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {} 91 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {} 92 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {} 93 94 void SelectionDAG::DAGNodeDeletedListener::anchor() {} 95 96 #define DEBUG_TYPE "selectiondag" 97 98 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt", 99 cl::Hidden, cl::init(true), 100 cl::desc("Gang up loads and stores generated by inlining of memcpy")); 101 102 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max", 103 cl::desc("Number limit for gluing ld/st of memcpy."), 104 cl::Hidden, cl::init(0)); 105 106 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) { 107 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G);); 108 } 109 110 //===----------------------------------------------------------------------===// 111 // ConstantFPSDNode Class 112 //===----------------------------------------------------------------------===// 113 114 /// isExactlyValue - We don't rely on operator== working on double values, as 115 /// it returns true for things that are clearly not equal, like -0.0 and 0.0. 116 /// As such, this method can be used to do an exact bit-for-bit comparison of 117 /// two floating point values. 118 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const { 119 return getValueAPF().bitwiseIsEqual(V); 120 } 121 122 bool ConstantFPSDNode::isValueValidForType(EVT VT, 123 const APFloat& Val) { 124 assert(VT.isFloatingPoint() && "Can only convert between FP types"); 125 126 // convert modifies in place, so make a copy. 127 APFloat Val2 = APFloat(Val); 128 bool losesInfo; 129 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT), 130 APFloat::rmNearestTiesToEven, 131 &losesInfo); 132 return !losesInfo; 133 } 134 135 //===----------------------------------------------------------------------===// 136 // ISD Namespace 137 //===----------------------------------------------------------------------===// 138 139 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) { 140 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 141 unsigned EltSize = 142 N->getValueType(0).getVectorElementType().getSizeInBits(); 143 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 144 SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize); 145 return true; 146 } 147 if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) { 148 SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize); 149 return true; 150 } 151 } 152 153 auto *BV = dyn_cast<BuildVectorSDNode>(N); 154 if (!BV) 155 return false; 156 157 APInt SplatUndef; 158 unsigned SplatBitSize; 159 bool HasUndefs; 160 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 161 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs, 162 EltSize) && 163 EltSize == SplatBitSize; 164 } 165 166 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be 167 // specializations of the more general isConstantSplatVector()? 168 169 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) { 170 // Look through a bit convert. 171 while (N->getOpcode() == ISD::BITCAST) 172 N = N->getOperand(0).getNode(); 173 174 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 175 APInt SplatVal; 176 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes(); 177 } 178 179 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 180 181 unsigned i = 0, e = N->getNumOperands(); 182 183 // Skip over all of the undef values. 184 while (i != e && N->getOperand(i).isUndef()) 185 ++i; 186 187 // Do not accept an all-undef vector. 188 if (i == e) return false; 189 190 // Do not accept build_vectors that aren't all constants or which have non-~0 191 // elements. We have to be a bit careful here, as the type of the constant 192 // may not be the same as the type of the vector elements due to type 193 // legalization (the elements are promoted to a legal type for the target and 194 // a vector of a type may be legal when the base element type is not). 195 // We only want to check enough bits to cover the vector elements, because 196 // we care if the resultant vector is all ones, not whether the individual 197 // constants are. 198 SDValue NotZero = N->getOperand(i); 199 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 200 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 201 if (CN->getAPIntValue().countTrailingOnes() < EltSize) 202 return false; 203 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 204 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize) 205 return false; 206 } else 207 return false; 208 209 // Okay, we have at least one ~0 value, check to see if the rest match or are 210 // undefs. Even with the above element type twiddling, this should be OK, as 211 // the same type legalization should have applied to all the elements. 212 for (++i; i != e; ++i) 213 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef()) 214 return false; 215 return true; 216 } 217 218 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) { 219 // Look through a bit convert. 220 while (N->getOpcode() == ISD::BITCAST) 221 N = N->getOperand(0).getNode(); 222 223 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 224 APInt SplatVal; 225 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero(); 226 } 227 228 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 229 230 bool IsAllUndef = true; 231 for (const SDValue &Op : N->op_values()) { 232 if (Op.isUndef()) 233 continue; 234 IsAllUndef = false; 235 // Do not accept build_vectors that aren't all constants or which have non-0 236 // elements. We have to be a bit careful here, as the type of the constant 237 // may not be the same as the type of the vector elements due to type 238 // legalization (the elements are promoted to a legal type for the target 239 // and a vector of a type may be legal when the base element type is not). 240 // We only want to check enough bits to cover the vector elements, because 241 // we care if the resultant vector is all zeros, not whether the individual 242 // constants are. 243 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 244 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) { 245 if (CN->getAPIntValue().countTrailingZeros() < EltSize) 246 return false; 247 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) { 248 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize) 249 return false; 250 } else 251 return false; 252 } 253 254 // Do not accept an all-undef vector. 255 if (IsAllUndef) 256 return false; 257 return true; 258 } 259 260 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 261 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true); 262 } 263 264 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 265 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true); 266 } 267 268 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 269 if (N->getOpcode() != ISD::BUILD_VECTOR) 270 return false; 271 272 for (const SDValue &Op : N->op_values()) { 273 if (Op.isUndef()) 274 continue; 275 if (!isa<ConstantSDNode>(Op)) 276 return false; 277 } 278 return true; 279 } 280 281 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) { 282 if (N->getOpcode() != ISD::BUILD_VECTOR) 283 return false; 284 285 for (const SDValue &Op : N->op_values()) { 286 if (Op.isUndef()) 287 continue; 288 if (!isa<ConstantFPSDNode>(Op)) 289 return false; 290 } 291 return true; 292 } 293 294 bool ISD::allOperandsUndef(const SDNode *N) { 295 // Return false if the node has no operands. 296 // This is "logically inconsistent" with the definition of "all" but 297 // is probably the desired behavior. 298 if (N->getNumOperands() == 0) 299 return false; 300 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); }); 301 } 302 303 bool ISD::matchUnaryPredicate(SDValue Op, 304 std::function<bool(ConstantSDNode *)> Match, 305 bool AllowUndefs) { 306 // FIXME: Add support for scalar UNDEF cases? 307 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) 308 return Match(Cst); 309 310 // FIXME: Add support for vector UNDEF cases? 311 if (ISD::BUILD_VECTOR != Op.getOpcode() && 312 ISD::SPLAT_VECTOR != Op.getOpcode()) 313 return false; 314 315 EVT SVT = Op.getValueType().getScalarType(); 316 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 317 if (AllowUndefs && Op.getOperand(i).isUndef()) { 318 if (!Match(nullptr)) 319 return false; 320 continue; 321 } 322 323 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i)); 324 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 325 return false; 326 } 327 return true; 328 } 329 330 bool ISD::matchBinaryPredicate( 331 SDValue LHS, SDValue RHS, 332 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match, 333 bool AllowUndefs, bool AllowTypeMismatch) { 334 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType()) 335 return false; 336 337 // TODO: Add support for scalar UNDEF cases? 338 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 339 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 340 return Match(LHSCst, RHSCst); 341 342 // TODO: Add support for vector UNDEF cases? 343 if (LHS.getOpcode() != RHS.getOpcode() || 344 (LHS.getOpcode() != ISD::BUILD_VECTOR && 345 LHS.getOpcode() != ISD::SPLAT_VECTOR)) 346 return false; 347 348 EVT SVT = LHS.getValueType().getScalarType(); 349 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 350 SDValue LHSOp = LHS.getOperand(i); 351 SDValue RHSOp = RHS.getOperand(i); 352 bool LHSUndef = AllowUndefs && LHSOp.isUndef(); 353 bool RHSUndef = AllowUndefs && RHSOp.isUndef(); 354 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp); 355 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp); 356 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef)) 357 return false; 358 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT || 359 LHSOp.getValueType() != RHSOp.getValueType())) 360 return false; 361 if (!Match(LHSCst, RHSCst)) 362 return false; 363 } 364 return true; 365 } 366 367 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) { 368 switch (VecReduceOpcode) { 369 default: 370 llvm_unreachable("Expected VECREDUCE opcode"); 371 case ISD::VECREDUCE_FADD: 372 case ISD::VECREDUCE_SEQ_FADD: 373 case ISD::VP_REDUCE_FADD: 374 case ISD::VP_REDUCE_SEQ_FADD: 375 return ISD::FADD; 376 case ISD::VECREDUCE_FMUL: 377 case ISD::VECREDUCE_SEQ_FMUL: 378 case ISD::VP_REDUCE_FMUL: 379 case ISD::VP_REDUCE_SEQ_FMUL: 380 return ISD::FMUL; 381 case ISD::VECREDUCE_ADD: 382 case ISD::VP_REDUCE_ADD: 383 return ISD::ADD; 384 case ISD::VECREDUCE_MUL: 385 case ISD::VP_REDUCE_MUL: 386 return ISD::MUL; 387 case ISD::VECREDUCE_AND: 388 case ISD::VP_REDUCE_AND: 389 return ISD::AND; 390 case ISD::VECREDUCE_OR: 391 case ISD::VP_REDUCE_OR: 392 return ISD::OR; 393 case ISD::VECREDUCE_XOR: 394 case ISD::VP_REDUCE_XOR: 395 return ISD::XOR; 396 case ISD::VECREDUCE_SMAX: 397 case ISD::VP_REDUCE_SMAX: 398 return ISD::SMAX; 399 case ISD::VECREDUCE_SMIN: 400 case ISD::VP_REDUCE_SMIN: 401 return ISD::SMIN; 402 case ISD::VECREDUCE_UMAX: 403 case ISD::VP_REDUCE_UMAX: 404 return ISD::UMAX; 405 case ISD::VECREDUCE_UMIN: 406 case ISD::VP_REDUCE_UMIN: 407 return ISD::UMIN; 408 case ISD::VECREDUCE_FMAX: 409 case ISD::VP_REDUCE_FMAX: 410 return ISD::FMAXNUM; 411 case ISD::VECREDUCE_FMIN: 412 case ISD::VP_REDUCE_FMIN: 413 return ISD::FMINNUM; 414 } 415 } 416 417 bool ISD::isVPOpcode(unsigned Opcode) { 418 switch (Opcode) { 419 default: 420 return false; 421 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \ 422 case ISD::VPSD: \ 423 return true; 424 #include "llvm/IR/VPIntrinsics.def" 425 } 426 } 427 428 bool ISD::isVPBinaryOp(unsigned Opcode) { 429 switch (Opcode) { 430 default: 431 break; 432 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 433 #define VP_PROPERTY_BINARYOP return true; 434 #define END_REGISTER_VP_SDNODE(VPSD) break; 435 #include "llvm/IR/VPIntrinsics.def" 436 } 437 return false; 438 } 439 440 bool ISD::isVPReduction(unsigned Opcode) { 441 switch (Opcode) { 442 default: 443 break; 444 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 445 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true; 446 #define END_REGISTER_VP_SDNODE(VPSD) break; 447 #include "llvm/IR/VPIntrinsics.def" 448 } 449 return false; 450 } 451 452 /// The operand position of the vector mask. 453 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) { 454 switch (Opcode) { 455 default: 456 return None; 457 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \ 458 case ISD::VPSD: \ 459 return MASKPOS; 460 #include "llvm/IR/VPIntrinsics.def" 461 } 462 } 463 464 /// The operand position of the explicit vector length parameter. 465 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) { 466 switch (Opcode) { 467 default: 468 return None; 469 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \ 470 case ISD::VPSD: \ 471 return EVLPOS; 472 #include "llvm/IR/VPIntrinsics.def" 473 } 474 } 475 476 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 477 switch (ExtType) { 478 case ISD::EXTLOAD: 479 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 480 case ISD::SEXTLOAD: 481 return ISD::SIGN_EXTEND; 482 case ISD::ZEXTLOAD: 483 return ISD::ZERO_EXTEND; 484 default: 485 break; 486 } 487 488 llvm_unreachable("Invalid LoadExtType"); 489 } 490 491 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 492 // To perform this operation, we just need to swap the L and G bits of the 493 // operation. 494 unsigned OldL = (Operation >> 2) & 1; 495 unsigned OldG = (Operation >> 1) & 1; 496 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 497 (OldL << 1) | // New G bit 498 (OldG << 2)); // New L bit. 499 } 500 501 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) { 502 unsigned Operation = Op; 503 if (isIntegerLike) 504 Operation ^= 7; // Flip L, G, E bits, but not U. 505 else 506 Operation ^= 15; // Flip all of the condition bits. 507 508 if (Operation > ISD::SETTRUE2) 509 Operation &= ~8; // Don't let N and U bits get set. 510 511 return ISD::CondCode(Operation); 512 } 513 514 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) { 515 return getSetCCInverseImpl(Op, Type.isInteger()); 516 } 517 518 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op, 519 bool isIntegerLike) { 520 return getSetCCInverseImpl(Op, isIntegerLike); 521 } 522 523 /// For an integer comparison, return 1 if the comparison is a signed operation 524 /// and 2 if the result is an unsigned comparison. Return zero if the operation 525 /// does not depend on the sign of the input (setne and seteq). 526 static int isSignedOp(ISD::CondCode Opcode) { 527 switch (Opcode) { 528 default: llvm_unreachable("Illegal integer setcc operation!"); 529 case ISD::SETEQ: 530 case ISD::SETNE: return 0; 531 case ISD::SETLT: 532 case ISD::SETLE: 533 case ISD::SETGT: 534 case ISD::SETGE: return 1; 535 case ISD::SETULT: 536 case ISD::SETULE: 537 case ISD::SETUGT: 538 case ISD::SETUGE: return 2; 539 } 540 } 541 542 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 543 EVT Type) { 544 bool IsInteger = Type.isInteger(); 545 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 546 // Cannot fold a signed integer setcc with an unsigned integer setcc. 547 return ISD::SETCC_INVALID; 548 549 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 550 551 // If the N and U bits get set, then the resultant comparison DOES suddenly 552 // care about orderedness, and it is true when ordered. 553 if (Op > ISD::SETTRUE2) 554 Op &= ~16; // Clear the U bit if the N bit is set. 555 556 // Canonicalize illegal integer setcc's. 557 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 558 Op = ISD::SETNE; 559 560 return ISD::CondCode(Op); 561 } 562 563 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 564 EVT Type) { 565 bool IsInteger = Type.isInteger(); 566 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 567 // Cannot fold a signed setcc with an unsigned setcc. 568 return ISD::SETCC_INVALID; 569 570 // Combine all of the condition bits. 571 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 572 573 // Canonicalize illegal integer setcc's. 574 if (IsInteger) { 575 switch (Result) { 576 default: break; 577 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 578 case ISD::SETOEQ: // SETEQ & SETU[LG]E 579 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 580 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 581 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 582 } 583 } 584 585 return Result; 586 } 587 588 //===----------------------------------------------------------------------===// 589 // SDNode Profile Support 590 //===----------------------------------------------------------------------===// 591 592 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 593 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 594 ID.AddInteger(OpC); 595 } 596 597 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 598 /// solely with their pointer. 599 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 600 ID.AddPointer(VTList.VTs); 601 } 602 603 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 604 static void AddNodeIDOperands(FoldingSetNodeID &ID, 605 ArrayRef<SDValue> Ops) { 606 for (auto& Op : Ops) { 607 ID.AddPointer(Op.getNode()); 608 ID.AddInteger(Op.getResNo()); 609 } 610 } 611 612 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 613 static void AddNodeIDOperands(FoldingSetNodeID &ID, 614 ArrayRef<SDUse> Ops) { 615 for (auto& Op : Ops) { 616 ID.AddPointer(Op.getNode()); 617 ID.AddInteger(Op.getResNo()); 618 } 619 } 620 621 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC, 622 SDVTList VTList, ArrayRef<SDValue> OpList) { 623 AddNodeIDOpcode(ID, OpC); 624 AddNodeIDValueTypes(ID, VTList); 625 AddNodeIDOperands(ID, OpList); 626 } 627 628 /// If this is an SDNode with special info, add this info to the NodeID data. 629 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 630 switch (N->getOpcode()) { 631 case ISD::TargetExternalSymbol: 632 case ISD::ExternalSymbol: 633 case ISD::MCSymbol: 634 llvm_unreachable("Should only be used on nodes with operands"); 635 default: break; // Normal nodes don't need extra info. 636 case ISD::TargetConstant: 637 case ISD::Constant: { 638 const ConstantSDNode *C = cast<ConstantSDNode>(N); 639 ID.AddPointer(C->getConstantIntValue()); 640 ID.AddBoolean(C->isOpaque()); 641 break; 642 } 643 case ISD::TargetConstantFP: 644 case ISD::ConstantFP: 645 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 646 break; 647 case ISD::TargetGlobalAddress: 648 case ISD::GlobalAddress: 649 case ISD::TargetGlobalTLSAddress: 650 case ISD::GlobalTLSAddress: { 651 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 652 ID.AddPointer(GA->getGlobal()); 653 ID.AddInteger(GA->getOffset()); 654 ID.AddInteger(GA->getTargetFlags()); 655 break; 656 } 657 case ISD::BasicBlock: 658 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 659 break; 660 case ISD::Register: 661 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 662 break; 663 case ISD::RegisterMask: 664 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 665 break; 666 case ISD::SRCVALUE: 667 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 668 break; 669 case ISD::FrameIndex: 670 case ISD::TargetFrameIndex: 671 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 672 break; 673 case ISD::LIFETIME_START: 674 case ISD::LIFETIME_END: 675 if (cast<LifetimeSDNode>(N)->hasOffset()) { 676 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize()); 677 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset()); 678 } 679 break; 680 case ISD::PSEUDO_PROBE: 681 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid()); 682 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex()); 683 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes()); 684 break; 685 case ISD::JumpTable: 686 case ISD::TargetJumpTable: 687 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 688 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 689 break; 690 case ISD::ConstantPool: 691 case ISD::TargetConstantPool: { 692 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 693 ID.AddInteger(CP->getAlign().value()); 694 ID.AddInteger(CP->getOffset()); 695 if (CP->isMachineConstantPoolEntry()) 696 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 697 else 698 ID.AddPointer(CP->getConstVal()); 699 ID.AddInteger(CP->getTargetFlags()); 700 break; 701 } 702 case ISD::TargetIndex: { 703 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 704 ID.AddInteger(TI->getIndex()); 705 ID.AddInteger(TI->getOffset()); 706 ID.AddInteger(TI->getTargetFlags()); 707 break; 708 } 709 case ISD::LOAD: { 710 const LoadSDNode *LD = cast<LoadSDNode>(N); 711 ID.AddInteger(LD->getMemoryVT().getRawBits()); 712 ID.AddInteger(LD->getRawSubclassData()); 713 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 714 ID.AddInteger(LD->getMemOperand()->getFlags()); 715 break; 716 } 717 case ISD::STORE: { 718 const StoreSDNode *ST = cast<StoreSDNode>(N); 719 ID.AddInteger(ST->getMemoryVT().getRawBits()); 720 ID.AddInteger(ST->getRawSubclassData()); 721 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 722 ID.AddInteger(ST->getMemOperand()->getFlags()); 723 break; 724 } 725 case ISD::VP_LOAD: { 726 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N); 727 ID.AddInteger(ELD->getMemoryVT().getRawBits()); 728 ID.AddInteger(ELD->getRawSubclassData()); 729 ID.AddInteger(ELD->getPointerInfo().getAddrSpace()); 730 ID.AddInteger(ELD->getMemOperand()->getFlags()); 731 break; 732 } 733 case ISD::VP_STORE: { 734 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N); 735 ID.AddInteger(EST->getMemoryVT().getRawBits()); 736 ID.AddInteger(EST->getRawSubclassData()); 737 ID.AddInteger(EST->getPointerInfo().getAddrSpace()); 738 ID.AddInteger(EST->getMemOperand()->getFlags()); 739 break; 740 } 741 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: { 742 const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N); 743 ID.AddInteger(SLD->getMemoryVT().getRawBits()); 744 ID.AddInteger(SLD->getRawSubclassData()); 745 ID.AddInteger(SLD->getPointerInfo().getAddrSpace()); 746 break; 747 } 748 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: { 749 const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N); 750 ID.AddInteger(SST->getMemoryVT().getRawBits()); 751 ID.AddInteger(SST->getRawSubclassData()); 752 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 753 break; 754 } 755 case ISD::VP_GATHER: { 756 const VPGatherSDNode *EG = cast<VPGatherSDNode>(N); 757 ID.AddInteger(EG->getMemoryVT().getRawBits()); 758 ID.AddInteger(EG->getRawSubclassData()); 759 ID.AddInteger(EG->getPointerInfo().getAddrSpace()); 760 ID.AddInteger(EG->getMemOperand()->getFlags()); 761 break; 762 } 763 case ISD::VP_SCATTER: { 764 const VPScatterSDNode *ES = cast<VPScatterSDNode>(N); 765 ID.AddInteger(ES->getMemoryVT().getRawBits()); 766 ID.AddInteger(ES->getRawSubclassData()); 767 ID.AddInteger(ES->getPointerInfo().getAddrSpace()); 768 ID.AddInteger(ES->getMemOperand()->getFlags()); 769 break; 770 } 771 case ISD::MLOAD: { 772 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 773 ID.AddInteger(MLD->getMemoryVT().getRawBits()); 774 ID.AddInteger(MLD->getRawSubclassData()); 775 ID.AddInteger(MLD->getPointerInfo().getAddrSpace()); 776 ID.AddInteger(MLD->getMemOperand()->getFlags()); 777 break; 778 } 779 case ISD::MSTORE: { 780 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 781 ID.AddInteger(MST->getMemoryVT().getRawBits()); 782 ID.AddInteger(MST->getRawSubclassData()); 783 ID.AddInteger(MST->getPointerInfo().getAddrSpace()); 784 ID.AddInteger(MST->getMemOperand()->getFlags()); 785 break; 786 } 787 case ISD::MGATHER: { 788 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N); 789 ID.AddInteger(MG->getMemoryVT().getRawBits()); 790 ID.AddInteger(MG->getRawSubclassData()); 791 ID.AddInteger(MG->getPointerInfo().getAddrSpace()); 792 ID.AddInteger(MG->getMemOperand()->getFlags()); 793 break; 794 } 795 case ISD::MSCATTER: { 796 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N); 797 ID.AddInteger(MS->getMemoryVT().getRawBits()); 798 ID.AddInteger(MS->getRawSubclassData()); 799 ID.AddInteger(MS->getPointerInfo().getAddrSpace()); 800 ID.AddInteger(MS->getMemOperand()->getFlags()); 801 break; 802 } 803 case ISD::ATOMIC_CMP_SWAP: 804 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 805 case ISD::ATOMIC_SWAP: 806 case ISD::ATOMIC_LOAD_ADD: 807 case ISD::ATOMIC_LOAD_SUB: 808 case ISD::ATOMIC_LOAD_AND: 809 case ISD::ATOMIC_LOAD_CLR: 810 case ISD::ATOMIC_LOAD_OR: 811 case ISD::ATOMIC_LOAD_XOR: 812 case ISD::ATOMIC_LOAD_NAND: 813 case ISD::ATOMIC_LOAD_MIN: 814 case ISD::ATOMIC_LOAD_MAX: 815 case ISD::ATOMIC_LOAD_UMIN: 816 case ISD::ATOMIC_LOAD_UMAX: 817 case ISD::ATOMIC_LOAD: 818 case ISD::ATOMIC_STORE: { 819 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 820 ID.AddInteger(AT->getMemoryVT().getRawBits()); 821 ID.AddInteger(AT->getRawSubclassData()); 822 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 823 ID.AddInteger(AT->getMemOperand()->getFlags()); 824 break; 825 } 826 case ISD::PREFETCH: { 827 const MemSDNode *PF = cast<MemSDNode>(N); 828 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 829 ID.AddInteger(PF->getMemOperand()->getFlags()); 830 break; 831 } 832 case ISD::VECTOR_SHUFFLE: { 833 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 834 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 835 i != e; ++i) 836 ID.AddInteger(SVN->getMaskElt(i)); 837 break; 838 } 839 case ISD::TargetBlockAddress: 840 case ISD::BlockAddress: { 841 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 842 ID.AddPointer(BA->getBlockAddress()); 843 ID.AddInteger(BA->getOffset()); 844 ID.AddInteger(BA->getTargetFlags()); 845 break; 846 } 847 case ISD::AssertAlign: 848 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value()); 849 break; 850 } // end switch (N->getOpcode()) 851 852 // Target specific memory nodes could also have address spaces and flags 853 // to check. 854 if (N->isTargetMemoryOpcode()) { 855 const MemSDNode *MN = cast<MemSDNode>(N); 856 ID.AddInteger(MN->getPointerInfo().getAddrSpace()); 857 ID.AddInteger(MN->getMemOperand()->getFlags()); 858 } 859 } 860 861 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 862 /// data. 863 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 864 AddNodeIDOpcode(ID, N->getOpcode()); 865 // Add the return value info. 866 AddNodeIDValueTypes(ID, N->getVTList()); 867 // Add the operand info. 868 AddNodeIDOperands(ID, N->ops()); 869 870 // Handle SDNode leafs with special info. 871 AddNodeIDCustom(ID, N); 872 } 873 874 //===----------------------------------------------------------------------===// 875 // SelectionDAG Class 876 //===----------------------------------------------------------------------===// 877 878 /// doNotCSE - Return true if CSE should not be performed for this node. 879 static bool doNotCSE(SDNode *N) { 880 if (N->getValueType(0) == MVT::Glue) 881 return true; // Never CSE anything that produces a flag. 882 883 switch (N->getOpcode()) { 884 default: break; 885 case ISD::HANDLENODE: 886 case ISD::EH_LABEL: 887 return true; // Never CSE these nodes. 888 } 889 890 // Check that remaining values produced are not flags. 891 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 892 if (N->getValueType(i) == MVT::Glue) 893 return true; // Never CSE anything that produces a flag. 894 895 return false; 896 } 897 898 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 899 /// SelectionDAG. 900 void SelectionDAG::RemoveDeadNodes() { 901 // Create a dummy node (which is not added to allnodes), that adds a reference 902 // to the root node, preventing it from being deleted. 903 HandleSDNode Dummy(getRoot()); 904 905 SmallVector<SDNode*, 128> DeadNodes; 906 907 // Add all obviously-dead nodes to the DeadNodes worklist. 908 for (SDNode &Node : allnodes()) 909 if (Node.use_empty()) 910 DeadNodes.push_back(&Node); 911 912 RemoveDeadNodes(DeadNodes); 913 914 // If the root changed (e.g. it was a dead load, update the root). 915 setRoot(Dummy.getValue()); 916 } 917 918 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 919 /// given list, and any nodes that become unreachable as a result. 920 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 921 922 // Process the worklist, deleting the nodes and adding their uses to the 923 // worklist. 924 while (!DeadNodes.empty()) { 925 SDNode *N = DeadNodes.pop_back_val(); 926 // Skip to next node if we've already managed to delete the node. This could 927 // happen if replacing a node causes a node previously added to the node to 928 // be deleted. 929 if (N->getOpcode() == ISD::DELETED_NODE) 930 continue; 931 932 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 933 DUL->NodeDeleted(N, nullptr); 934 935 // Take the node out of the appropriate CSE map. 936 RemoveNodeFromCSEMaps(N); 937 938 // Next, brutally remove the operand list. This is safe to do, as there are 939 // no cycles in the graph. 940 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 941 SDUse &Use = *I++; 942 SDNode *Operand = Use.getNode(); 943 Use.set(SDValue()); 944 945 // Now that we removed this operand, see if there are no uses of it left. 946 if (Operand->use_empty()) 947 DeadNodes.push_back(Operand); 948 } 949 950 DeallocateNode(N); 951 } 952 } 953 954 void SelectionDAG::RemoveDeadNode(SDNode *N){ 955 SmallVector<SDNode*, 16> DeadNodes(1, N); 956 957 // Create a dummy node that adds a reference to the root node, preventing 958 // it from being deleted. (This matters if the root is an operand of the 959 // dead node.) 960 HandleSDNode Dummy(getRoot()); 961 962 RemoveDeadNodes(DeadNodes); 963 } 964 965 void SelectionDAG::DeleteNode(SDNode *N) { 966 // First take this out of the appropriate CSE map. 967 RemoveNodeFromCSEMaps(N); 968 969 // Finally, remove uses due to operands of this node, remove from the 970 // AllNodes list, and delete the node. 971 DeleteNodeNotInCSEMaps(N); 972 } 973 974 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 975 assert(N->getIterator() != AllNodes.begin() && 976 "Cannot delete the entry node!"); 977 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 978 979 // Drop all of the operands and decrement used node's use counts. 980 N->DropOperands(); 981 982 DeallocateNode(N); 983 } 984 985 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) { 986 assert(!(V->isVariadic() && isParameter)); 987 if (isParameter) 988 ByvalParmDbgValues.push_back(V); 989 else 990 DbgValues.push_back(V); 991 for (const SDNode *Node : V->getSDNodes()) 992 if (Node) 993 DbgValMap[Node].push_back(V); 994 } 995 996 void SDDbgInfo::erase(const SDNode *Node) { 997 DbgValMapType::iterator I = DbgValMap.find(Node); 998 if (I == DbgValMap.end()) 999 return; 1000 for (auto &Val: I->second) 1001 Val->setIsInvalidated(); 1002 DbgValMap.erase(I); 1003 } 1004 1005 void SelectionDAG::DeallocateNode(SDNode *N) { 1006 // If we have operands, deallocate them. 1007 removeOperands(N); 1008 1009 NodeAllocator.Deallocate(AllNodes.remove(N)); 1010 1011 // Set the opcode to DELETED_NODE to help catch bugs when node 1012 // memory is reallocated. 1013 // FIXME: There are places in SDag that have grown a dependency on the opcode 1014 // value in the released node. 1015 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 1016 N->NodeType = ISD::DELETED_NODE; 1017 1018 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 1019 // them and forget about that node. 1020 DbgInfo->erase(N); 1021 } 1022 1023 #ifndef NDEBUG 1024 /// VerifySDNode - Check the given SDNode. Aborts if it is invalid. 1025 static void VerifySDNode(SDNode *N) { 1026 switch (N->getOpcode()) { 1027 default: 1028 break; 1029 case ISD::BUILD_PAIR: { 1030 EVT VT = N->getValueType(0); 1031 assert(N->getNumValues() == 1 && "Too many results!"); 1032 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 1033 "Wrong return type!"); 1034 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 1035 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 1036 "Mismatched operand types!"); 1037 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 1038 "Wrong operand type!"); 1039 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 1040 "Wrong return type size"); 1041 break; 1042 } 1043 case ISD::BUILD_VECTOR: { 1044 assert(N->getNumValues() == 1 && "Too many results!"); 1045 assert(N->getValueType(0).isVector() && "Wrong return type!"); 1046 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 1047 "Wrong number of operands!"); 1048 EVT EltVT = N->getValueType(0).getVectorElementType(); 1049 for (const SDUse &Op : N->ops()) { 1050 assert((Op.getValueType() == EltVT || 1051 (EltVT.isInteger() && Op.getValueType().isInteger() && 1052 EltVT.bitsLE(Op.getValueType()))) && 1053 "Wrong operand type!"); 1054 assert(Op.getValueType() == N->getOperand(0).getValueType() && 1055 "Operands must all have the same type"); 1056 } 1057 break; 1058 } 1059 } 1060 } 1061 #endif // NDEBUG 1062 1063 /// Insert a newly allocated node into the DAG. 1064 /// 1065 /// Handles insertion into the all nodes list and CSE map, as well as 1066 /// verification and other common operations when a new node is allocated. 1067 void SelectionDAG::InsertNode(SDNode *N) { 1068 AllNodes.push_back(N); 1069 #ifndef NDEBUG 1070 N->PersistentId = NextPersistentId++; 1071 VerifySDNode(N); 1072 #endif 1073 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1074 DUL->NodeInserted(N); 1075 } 1076 1077 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 1078 /// correspond to it. This is useful when we're about to delete or repurpose 1079 /// the node. We don't want future request for structurally identical nodes 1080 /// to return N anymore. 1081 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 1082 bool Erased = false; 1083 switch (N->getOpcode()) { 1084 case ISD::HANDLENODE: return false; // noop. 1085 case ISD::CONDCODE: 1086 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 1087 "Cond code doesn't exist!"); 1088 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 1089 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 1090 break; 1091 case ISD::ExternalSymbol: 1092 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 1093 break; 1094 case ISD::TargetExternalSymbol: { 1095 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 1096 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 1097 ESN->getSymbol(), ESN->getTargetFlags())); 1098 break; 1099 } 1100 case ISD::MCSymbol: { 1101 auto *MCSN = cast<MCSymbolSDNode>(N); 1102 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 1103 break; 1104 } 1105 case ISD::VALUETYPE: { 1106 EVT VT = cast<VTSDNode>(N)->getVT(); 1107 if (VT.isExtended()) { 1108 Erased = ExtendedValueTypeNodes.erase(VT); 1109 } else { 1110 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 1111 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 1112 } 1113 break; 1114 } 1115 default: 1116 // Remove it from the CSE Map. 1117 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 1118 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 1119 Erased = CSEMap.RemoveNode(N); 1120 break; 1121 } 1122 #ifndef NDEBUG 1123 // Verify that the node was actually in one of the CSE maps, unless it has a 1124 // flag result (which cannot be CSE'd) or is one of the special cases that are 1125 // not subject to CSE. 1126 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 1127 !N->isMachineOpcode() && !doNotCSE(N)) { 1128 N->dump(this); 1129 dbgs() << "\n"; 1130 llvm_unreachable("Node is not in map!"); 1131 } 1132 #endif 1133 return Erased; 1134 } 1135 1136 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 1137 /// maps and modified in place. Add it back to the CSE maps, unless an identical 1138 /// node already exists, in which case transfer all its users to the existing 1139 /// node. This transfer can potentially trigger recursive merging. 1140 void 1141 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 1142 // For node types that aren't CSE'd, just act as if no identical node 1143 // already exists. 1144 if (!doNotCSE(N)) { 1145 SDNode *Existing = CSEMap.GetOrInsertNode(N); 1146 if (Existing != N) { 1147 // If there was already an existing matching node, use ReplaceAllUsesWith 1148 // to replace the dead one with the existing one. This can cause 1149 // recursive merging of other unrelated nodes down the line. 1150 ReplaceAllUsesWith(N, Existing); 1151 1152 // N is now dead. Inform the listeners and delete it. 1153 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1154 DUL->NodeDeleted(N, Existing); 1155 DeleteNodeNotInCSEMaps(N); 1156 return; 1157 } 1158 } 1159 1160 // If the node doesn't already exist, we updated it. Inform listeners. 1161 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1162 DUL->NodeUpdated(N); 1163 } 1164 1165 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1166 /// were replaced with those specified. If this node is never memoized, 1167 /// return null, otherwise return a pointer to the slot it would take. If a 1168 /// node already exists with these operands, the slot will be non-null. 1169 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1170 void *&InsertPos) { 1171 if (doNotCSE(N)) 1172 return nullptr; 1173 1174 SDValue Ops[] = { Op }; 1175 FoldingSetNodeID ID; 1176 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1177 AddNodeIDCustom(ID, N); 1178 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1179 if (Node) 1180 Node->intersectFlagsWith(N->getFlags()); 1181 return Node; 1182 } 1183 1184 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1185 /// were replaced with those specified. If this node is never memoized, 1186 /// return null, otherwise return a pointer to the slot it would take. If a 1187 /// node already exists with these operands, the slot will be non-null. 1188 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1189 SDValue Op1, SDValue Op2, 1190 void *&InsertPos) { 1191 if (doNotCSE(N)) 1192 return nullptr; 1193 1194 SDValue Ops[] = { Op1, Op2 }; 1195 FoldingSetNodeID ID; 1196 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1197 AddNodeIDCustom(ID, N); 1198 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1199 if (Node) 1200 Node->intersectFlagsWith(N->getFlags()); 1201 return Node; 1202 } 1203 1204 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1205 /// were replaced with those specified. If this node is never memoized, 1206 /// return null, otherwise return a pointer to the slot it would take. If a 1207 /// node already exists with these operands, the slot will be non-null. 1208 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1209 void *&InsertPos) { 1210 if (doNotCSE(N)) 1211 return nullptr; 1212 1213 FoldingSetNodeID ID; 1214 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1215 AddNodeIDCustom(ID, N); 1216 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1217 if (Node) 1218 Node->intersectFlagsWith(N->getFlags()); 1219 return Node; 1220 } 1221 1222 Align SelectionDAG::getEVTAlign(EVT VT) const { 1223 Type *Ty = VT == MVT::iPTR ? 1224 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 1225 VT.getTypeForEVT(*getContext()); 1226 1227 return getDataLayout().getABITypeAlign(Ty); 1228 } 1229 1230 // EntryNode could meaningfully have debug info if we can find it... 1231 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 1232 : TM(tm), OptLevel(OL), 1233 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 1234 Root(getEntryNode()) { 1235 InsertNode(&EntryNode); 1236 DbgInfo = new SDDbgInfo(); 1237 } 1238 1239 void SelectionDAG::init(MachineFunction &NewMF, 1240 OptimizationRemarkEmitter &NewORE, 1241 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, 1242 LegacyDivergenceAnalysis * Divergence, 1243 ProfileSummaryInfo *PSIin, 1244 BlockFrequencyInfo *BFIin) { 1245 MF = &NewMF; 1246 SDAGISelPass = PassPtr; 1247 ORE = &NewORE; 1248 TLI = getSubtarget().getTargetLowering(); 1249 TSI = getSubtarget().getSelectionDAGInfo(); 1250 LibInfo = LibraryInfo; 1251 Context = &MF->getFunction().getContext(); 1252 DA = Divergence; 1253 PSI = PSIin; 1254 BFI = BFIin; 1255 } 1256 1257 SelectionDAG::~SelectionDAG() { 1258 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1259 allnodes_clear(); 1260 OperandRecycler.clear(OperandAllocator); 1261 delete DbgInfo; 1262 } 1263 1264 bool SelectionDAG::shouldOptForSize() const { 1265 return MF->getFunction().hasOptSize() || 1266 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1267 } 1268 1269 void SelectionDAG::allnodes_clear() { 1270 assert(&*AllNodes.begin() == &EntryNode); 1271 AllNodes.remove(AllNodes.begin()); 1272 while (!AllNodes.empty()) 1273 DeallocateNode(&AllNodes.front()); 1274 #ifndef NDEBUG 1275 NextPersistentId = 0; 1276 #endif 1277 } 1278 1279 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1280 void *&InsertPos) { 1281 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1282 if (N) { 1283 switch (N->getOpcode()) { 1284 default: break; 1285 case ISD::Constant: 1286 case ISD::ConstantFP: 1287 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1288 "debug location. Use another overload."); 1289 } 1290 } 1291 return N; 1292 } 1293 1294 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1295 const SDLoc &DL, void *&InsertPos) { 1296 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1297 if (N) { 1298 switch (N->getOpcode()) { 1299 case ISD::Constant: 1300 case ISD::ConstantFP: 1301 // Erase debug location from the node if the node is used at several 1302 // different places. Do not propagate one location to all uses as it 1303 // will cause a worse single stepping debugging experience. 1304 if (N->getDebugLoc() != DL.getDebugLoc()) 1305 N->setDebugLoc(DebugLoc()); 1306 break; 1307 default: 1308 // When the node's point of use is located earlier in the instruction 1309 // sequence than its prior point of use, update its debug info to the 1310 // earlier location. 1311 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1312 N->setDebugLoc(DL.getDebugLoc()); 1313 break; 1314 } 1315 } 1316 return N; 1317 } 1318 1319 void SelectionDAG::clear() { 1320 allnodes_clear(); 1321 OperandRecycler.clear(OperandAllocator); 1322 OperandAllocator.Reset(); 1323 CSEMap.clear(); 1324 1325 ExtendedValueTypeNodes.clear(); 1326 ExternalSymbols.clear(); 1327 TargetExternalSymbols.clear(); 1328 MCSymbols.clear(); 1329 SDCallSiteDbgInfo.clear(); 1330 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1331 static_cast<CondCodeSDNode*>(nullptr)); 1332 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1333 static_cast<SDNode*>(nullptr)); 1334 1335 EntryNode.UseList = nullptr; 1336 InsertNode(&EntryNode); 1337 Root = getEntryNode(); 1338 DbgInfo->clear(); 1339 } 1340 1341 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1342 return VT.bitsGT(Op.getValueType()) 1343 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1344 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL)); 1345 } 1346 1347 std::pair<SDValue, SDValue> 1348 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1349 const SDLoc &DL, EVT VT) { 1350 assert(!VT.bitsEq(Op.getValueType()) && 1351 "Strict no-op FP extend/round not allowed."); 1352 SDValue Res = 1353 VT.bitsGT(Op.getValueType()) 1354 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1355 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1356 {Chain, Op, getIntPtrConstant(0, DL)}); 1357 1358 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1359 } 1360 1361 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1362 return VT.bitsGT(Op.getValueType()) ? 1363 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1364 getNode(ISD::TRUNCATE, DL, VT, Op); 1365 } 1366 1367 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1368 return VT.bitsGT(Op.getValueType()) ? 1369 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1370 getNode(ISD::TRUNCATE, DL, VT, Op); 1371 } 1372 1373 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1374 return VT.bitsGT(Op.getValueType()) ? 1375 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1376 getNode(ISD::TRUNCATE, DL, VT, Op); 1377 } 1378 1379 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1380 EVT OpVT) { 1381 if (VT.bitsLE(Op.getValueType())) 1382 return getNode(ISD::TRUNCATE, SL, VT, Op); 1383 1384 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1385 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1386 } 1387 1388 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1389 EVT OpVT = Op.getValueType(); 1390 assert(VT.isInteger() && OpVT.isInteger() && 1391 "Cannot getZeroExtendInReg FP types"); 1392 assert(VT.isVector() == OpVT.isVector() && 1393 "getZeroExtendInReg type should be vector iff the operand " 1394 "type is vector!"); 1395 assert((!VT.isVector() || 1396 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1397 "Vector element counts must match in getZeroExtendInReg"); 1398 assert(VT.bitsLE(OpVT) && "Not extending!"); 1399 if (OpVT == VT) 1400 return Op; 1401 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1402 VT.getScalarSizeInBits()); 1403 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1404 } 1405 1406 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1407 // Only unsigned pointer semantics are supported right now. In the future this 1408 // might delegate to TLI to check pointer signedness. 1409 return getZExtOrTrunc(Op, DL, VT); 1410 } 1411 1412 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1413 // Only unsigned pointer semantics are supported right now. In the future this 1414 // might delegate to TLI to check pointer signedness. 1415 return getZeroExtendInReg(Op, DL, VT); 1416 } 1417 1418 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1419 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1420 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT)); 1421 } 1422 1423 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1424 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1425 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1426 } 1427 1428 SDValue SelectionDAG::getVPLogicalNOT(const SDLoc &DL, SDValue Val, 1429 SDValue Mask, SDValue EVL, EVT VT) { 1430 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1431 return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL); 1432 } 1433 1434 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1435 EVT OpVT) { 1436 if (!V) 1437 return getConstant(0, DL, VT); 1438 1439 switch (TLI->getBooleanContents(OpVT)) { 1440 case TargetLowering::ZeroOrOneBooleanContent: 1441 case TargetLowering::UndefinedBooleanContent: 1442 return getConstant(1, DL, VT); 1443 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1444 return getAllOnesConstant(DL, VT); 1445 } 1446 llvm_unreachable("Unexpected boolean content enum!"); 1447 } 1448 1449 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1450 bool isT, bool isO) { 1451 EVT EltVT = VT.getScalarType(); 1452 assert((EltVT.getSizeInBits() >= 64 || 1453 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1454 "getConstant with a uint64_t value that doesn't fit in the type!"); 1455 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1456 } 1457 1458 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1459 bool isT, bool isO) { 1460 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1461 } 1462 1463 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1464 EVT VT, bool isT, bool isO) { 1465 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1466 1467 EVT EltVT = VT.getScalarType(); 1468 const ConstantInt *Elt = &Val; 1469 1470 // In some cases the vector type is legal but the element type is illegal and 1471 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1472 // inserted value (the type does not need to match the vector element type). 1473 // Any extra bits introduced will be truncated away. 1474 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1475 TargetLowering::TypePromoteInteger) { 1476 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1477 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1478 Elt = ConstantInt::get(*getContext(), NewVal); 1479 } 1480 // In other cases the element type is illegal and needs to be expanded, for 1481 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1482 // the value into n parts and use a vector type with n-times the elements. 1483 // Then bitcast to the type requested. 1484 // Legalizing constants too early makes the DAGCombiner's job harder so we 1485 // only legalize if the DAG tells us we must produce legal types. 1486 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1487 TLI->getTypeAction(*getContext(), EltVT) == 1488 TargetLowering::TypeExpandInteger) { 1489 const APInt &NewVal = Elt->getValue(); 1490 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1491 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1492 1493 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node. 1494 if (VT.isScalableVector()) { 1495 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 && 1496 "Can only handle an even split!"); 1497 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits; 1498 1499 SmallVector<SDValue, 2> ScalarParts; 1500 for (unsigned i = 0; i != Parts; ++i) 1501 ScalarParts.push_back(getConstant( 1502 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1503 ViaEltVT, isT, isO)); 1504 1505 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts); 1506 } 1507 1508 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1509 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1510 1511 // Check the temporary vector is the correct size. If this fails then 1512 // getTypeToTransformTo() probably returned a type whose size (in bits) 1513 // isn't a power-of-2 factor of the requested type size. 1514 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1515 1516 SmallVector<SDValue, 2> EltParts; 1517 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) 1518 EltParts.push_back(getConstant( 1519 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1520 ViaEltVT, isT, isO)); 1521 1522 // EltParts is currently in little endian order. If we actually want 1523 // big-endian order then reverse it now. 1524 if (getDataLayout().isBigEndian()) 1525 std::reverse(EltParts.begin(), EltParts.end()); 1526 1527 // The elements must be reversed when the element order is different 1528 // to the endianness of the elements (because the BITCAST is itself a 1529 // vector shuffle in this situation). However, we do not need any code to 1530 // perform this reversal because getConstant() is producing a vector 1531 // splat. 1532 // This situation occurs in MIPS MSA. 1533 1534 SmallVector<SDValue, 8> Ops; 1535 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1536 llvm::append_range(Ops, EltParts); 1537 1538 SDValue V = 1539 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1540 return V; 1541 } 1542 1543 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1544 "APInt size does not match type size!"); 1545 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1546 FoldingSetNodeID ID; 1547 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1548 ID.AddPointer(Elt); 1549 ID.AddBoolean(isO); 1550 void *IP = nullptr; 1551 SDNode *N = nullptr; 1552 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1553 if (!VT.isVector()) 1554 return SDValue(N, 0); 1555 1556 if (!N) { 1557 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1558 CSEMap.InsertNode(N, IP); 1559 InsertNode(N); 1560 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1561 } 1562 1563 SDValue Result(N, 0); 1564 if (VT.isScalableVector()) 1565 Result = getSplatVector(VT, DL, Result); 1566 else if (VT.isVector()) 1567 Result = getSplatBuildVector(VT, DL, Result); 1568 1569 return Result; 1570 } 1571 1572 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1573 bool isTarget) { 1574 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1575 } 1576 1577 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1578 const SDLoc &DL, bool LegalTypes) { 1579 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1580 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1581 return getConstant(Val, DL, ShiftVT); 1582 } 1583 1584 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1585 bool isTarget) { 1586 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1587 } 1588 1589 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1590 bool isTarget) { 1591 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1592 } 1593 1594 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1595 EVT VT, bool isTarget) { 1596 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1597 1598 EVT EltVT = VT.getScalarType(); 1599 1600 // Do the map lookup using the actual bit pattern for the floating point 1601 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1602 // we don't have issues with SNANs. 1603 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1604 FoldingSetNodeID ID; 1605 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1606 ID.AddPointer(&V); 1607 void *IP = nullptr; 1608 SDNode *N = nullptr; 1609 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1610 if (!VT.isVector()) 1611 return SDValue(N, 0); 1612 1613 if (!N) { 1614 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1615 CSEMap.InsertNode(N, IP); 1616 InsertNode(N); 1617 } 1618 1619 SDValue Result(N, 0); 1620 if (VT.isScalableVector()) 1621 Result = getSplatVector(VT, DL, Result); 1622 else if (VT.isVector()) 1623 Result = getSplatBuildVector(VT, DL, Result); 1624 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1625 return Result; 1626 } 1627 1628 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1629 bool isTarget) { 1630 EVT EltVT = VT.getScalarType(); 1631 if (EltVT == MVT::f32) 1632 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1633 if (EltVT == MVT::f64) 1634 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1635 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1636 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1637 bool Ignored; 1638 APFloat APF = APFloat(Val); 1639 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1640 &Ignored); 1641 return getConstantFP(APF, DL, VT, isTarget); 1642 } 1643 llvm_unreachable("Unsupported type in getConstantFP"); 1644 } 1645 1646 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1647 EVT VT, int64_t Offset, bool isTargetGA, 1648 unsigned TargetFlags) { 1649 assert((TargetFlags == 0 || isTargetGA) && 1650 "Cannot set target flags on target-independent globals"); 1651 1652 // Truncate (with sign-extension) the offset value to the pointer size. 1653 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1654 if (BitWidth < 64) 1655 Offset = SignExtend64(Offset, BitWidth); 1656 1657 unsigned Opc; 1658 if (GV->isThreadLocal()) 1659 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1660 else 1661 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1662 1663 FoldingSetNodeID ID; 1664 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1665 ID.AddPointer(GV); 1666 ID.AddInteger(Offset); 1667 ID.AddInteger(TargetFlags); 1668 void *IP = nullptr; 1669 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1670 return SDValue(E, 0); 1671 1672 auto *N = newSDNode<GlobalAddressSDNode>( 1673 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1674 CSEMap.InsertNode(N, IP); 1675 InsertNode(N); 1676 return SDValue(N, 0); 1677 } 1678 1679 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1680 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1681 FoldingSetNodeID ID; 1682 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1683 ID.AddInteger(FI); 1684 void *IP = nullptr; 1685 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1686 return SDValue(E, 0); 1687 1688 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1689 CSEMap.InsertNode(N, IP); 1690 InsertNode(N); 1691 return SDValue(N, 0); 1692 } 1693 1694 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1695 unsigned TargetFlags) { 1696 assert((TargetFlags == 0 || isTarget) && 1697 "Cannot set target flags on target-independent jump tables"); 1698 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1699 FoldingSetNodeID ID; 1700 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1701 ID.AddInteger(JTI); 1702 ID.AddInteger(TargetFlags); 1703 void *IP = nullptr; 1704 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1705 return SDValue(E, 0); 1706 1707 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1708 CSEMap.InsertNode(N, IP); 1709 InsertNode(N); 1710 return SDValue(N, 0); 1711 } 1712 1713 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1714 MaybeAlign Alignment, int Offset, 1715 bool isTarget, unsigned TargetFlags) { 1716 assert((TargetFlags == 0 || isTarget) && 1717 "Cannot set target flags on target-independent globals"); 1718 if (!Alignment) 1719 Alignment = shouldOptForSize() 1720 ? getDataLayout().getABITypeAlign(C->getType()) 1721 : getDataLayout().getPrefTypeAlign(C->getType()); 1722 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1723 FoldingSetNodeID ID; 1724 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1725 ID.AddInteger(Alignment->value()); 1726 ID.AddInteger(Offset); 1727 ID.AddPointer(C); 1728 ID.AddInteger(TargetFlags); 1729 void *IP = nullptr; 1730 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1731 return SDValue(E, 0); 1732 1733 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1734 TargetFlags); 1735 CSEMap.InsertNode(N, IP); 1736 InsertNode(N); 1737 SDValue V = SDValue(N, 0); 1738 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1739 return V; 1740 } 1741 1742 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1743 MaybeAlign Alignment, int Offset, 1744 bool isTarget, unsigned TargetFlags) { 1745 assert((TargetFlags == 0 || isTarget) && 1746 "Cannot set target flags on target-independent globals"); 1747 if (!Alignment) 1748 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1749 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1750 FoldingSetNodeID ID; 1751 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1752 ID.AddInteger(Alignment->value()); 1753 ID.AddInteger(Offset); 1754 C->addSelectionDAGCSEId(ID); 1755 ID.AddInteger(TargetFlags); 1756 void *IP = nullptr; 1757 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1758 return SDValue(E, 0); 1759 1760 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1761 TargetFlags); 1762 CSEMap.InsertNode(N, IP); 1763 InsertNode(N); 1764 return SDValue(N, 0); 1765 } 1766 1767 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1768 unsigned TargetFlags) { 1769 FoldingSetNodeID ID; 1770 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1771 ID.AddInteger(Index); 1772 ID.AddInteger(Offset); 1773 ID.AddInteger(TargetFlags); 1774 void *IP = nullptr; 1775 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1776 return SDValue(E, 0); 1777 1778 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1779 CSEMap.InsertNode(N, IP); 1780 InsertNode(N); 1781 return SDValue(N, 0); 1782 } 1783 1784 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1785 FoldingSetNodeID ID; 1786 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1787 ID.AddPointer(MBB); 1788 void *IP = nullptr; 1789 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1790 return SDValue(E, 0); 1791 1792 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1793 CSEMap.InsertNode(N, IP); 1794 InsertNode(N); 1795 return SDValue(N, 0); 1796 } 1797 1798 SDValue SelectionDAG::getValueType(EVT VT) { 1799 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1800 ValueTypeNodes.size()) 1801 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1802 1803 SDNode *&N = VT.isExtended() ? 1804 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1805 1806 if (N) return SDValue(N, 0); 1807 N = newSDNode<VTSDNode>(VT); 1808 InsertNode(N); 1809 return SDValue(N, 0); 1810 } 1811 1812 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1813 SDNode *&N = ExternalSymbols[Sym]; 1814 if (N) return SDValue(N, 0); 1815 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1816 InsertNode(N); 1817 return SDValue(N, 0); 1818 } 1819 1820 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1821 SDNode *&N = MCSymbols[Sym]; 1822 if (N) 1823 return SDValue(N, 0); 1824 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1825 InsertNode(N); 1826 return SDValue(N, 0); 1827 } 1828 1829 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1830 unsigned TargetFlags) { 1831 SDNode *&N = 1832 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1833 if (N) return SDValue(N, 0); 1834 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1835 InsertNode(N); 1836 return SDValue(N, 0); 1837 } 1838 1839 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1840 if ((unsigned)Cond >= CondCodeNodes.size()) 1841 CondCodeNodes.resize(Cond+1); 1842 1843 if (!CondCodeNodes[Cond]) { 1844 auto *N = newSDNode<CondCodeSDNode>(Cond); 1845 CondCodeNodes[Cond] = N; 1846 InsertNode(N); 1847 } 1848 1849 return SDValue(CondCodeNodes[Cond], 0); 1850 } 1851 1852 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) { 1853 APInt One(ResVT.getScalarSizeInBits(), 1); 1854 return getStepVector(DL, ResVT, One); 1855 } 1856 1857 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) { 1858 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth()); 1859 if (ResVT.isScalableVector()) 1860 return getNode( 1861 ISD::STEP_VECTOR, DL, ResVT, 1862 getTargetConstant(StepVal, DL, ResVT.getVectorElementType())); 1863 1864 SmallVector<SDValue, 16> OpsStepConstants; 1865 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++) 1866 OpsStepConstants.push_back( 1867 getConstant(StepVal * i, DL, ResVT.getVectorElementType())); 1868 return getBuildVector(ResVT, DL, OpsStepConstants); 1869 } 1870 1871 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1872 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1873 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1874 std::swap(N1, N2); 1875 ShuffleVectorSDNode::commuteMask(M); 1876 } 1877 1878 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 1879 SDValue N2, ArrayRef<int> Mask) { 1880 assert(VT.getVectorNumElements() == Mask.size() && 1881 "Must have the same number of vector elements as mask elements!"); 1882 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1883 "Invalid VECTOR_SHUFFLE"); 1884 1885 // Canonicalize shuffle undef, undef -> undef 1886 if (N1.isUndef() && N2.isUndef()) 1887 return getUNDEF(VT); 1888 1889 // Validate that all indices in Mask are within the range of the elements 1890 // input to the shuffle. 1891 int NElts = Mask.size(); 1892 assert(llvm::all_of(Mask, 1893 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 1894 "Index out of range"); 1895 1896 // Copy the mask so we can do any needed cleanup. 1897 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end()); 1898 1899 // Canonicalize shuffle v, v -> v, undef 1900 if (N1 == N2) { 1901 N2 = getUNDEF(VT); 1902 for (int i = 0; i != NElts; ++i) 1903 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 1904 } 1905 1906 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1907 if (N1.isUndef()) 1908 commuteShuffle(N1, N2, MaskVec); 1909 1910 if (TLI->hasVectorBlend()) { 1911 // If shuffling a splat, try to blend the splat instead. We do this here so 1912 // that even when this arises during lowering we don't have to re-handle it. 1913 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1914 BitVector UndefElements; 1915 SDValue Splat = BV->getSplatValue(&UndefElements); 1916 if (!Splat) 1917 return; 1918 1919 for (int i = 0; i < NElts; ++i) { 1920 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 1921 continue; 1922 1923 // If this input comes from undef, mark it as such. 1924 if (UndefElements[MaskVec[i] - Offset]) { 1925 MaskVec[i] = -1; 1926 continue; 1927 } 1928 1929 // If we can blend a non-undef lane, use that instead. 1930 if (!UndefElements[i]) 1931 MaskVec[i] = i + Offset; 1932 } 1933 }; 1934 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1935 BlendSplat(N1BV, 0); 1936 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1937 BlendSplat(N2BV, NElts); 1938 } 1939 1940 // Canonicalize all index into lhs, -> shuffle lhs, undef 1941 // Canonicalize all index into rhs, -> shuffle rhs, undef 1942 bool AllLHS = true, AllRHS = true; 1943 bool N2Undef = N2.isUndef(); 1944 for (int i = 0; i != NElts; ++i) { 1945 if (MaskVec[i] >= NElts) { 1946 if (N2Undef) 1947 MaskVec[i] = -1; 1948 else 1949 AllLHS = false; 1950 } else if (MaskVec[i] >= 0) { 1951 AllRHS = false; 1952 } 1953 } 1954 if (AllLHS && AllRHS) 1955 return getUNDEF(VT); 1956 if (AllLHS && !N2Undef) 1957 N2 = getUNDEF(VT); 1958 if (AllRHS) { 1959 N1 = getUNDEF(VT); 1960 commuteShuffle(N1, N2, MaskVec); 1961 } 1962 // Reset our undef status after accounting for the mask. 1963 N2Undef = N2.isUndef(); 1964 // Re-check whether both sides ended up undef. 1965 if (N1.isUndef() && N2Undef) 1966 return getUNDEF(VT); 1967 1968 // If Identity shuffle return that node. 1969 bool Identity = true, AllSame = true; 1970 for (int i = 0; i != NElts; ++i) { 1971 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 1972 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1973 } 1974 if (Identity && NElts) 1975 return N1; 1976 1977 // Shuffling a constant splat doesn't change the result. 1978 if (N2Undef) { 1979 SDValue V = N1; 1980 1981 // Look through any bitcasts. We check that these don't change the number 1982 // (and size) of elements and just changes their types. 1983 while (V.getOpcode() == ISD::BITCAST) 1984 V = V->getOperand(0); 1985 1986 // A splat should always show up as a build vector node. 1987 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1988 BitVector UndefElements; 1989 SDValue Splat = BV->getSplatValue(&UndefElements); 1990 // If this is a splat of an undef, shuffling it is also undef. 1991 if (Splat && Splat.isUndef()) 1992 return getUNDEF(VT); 1993 1994 bool SameNumElts = 1995 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1996 1997 // We only have a splat which can skip shuffles if there is a splatted 1998 // value and no undef lanes rearranged by the shuffle. 1999 if (Splat && UndefElements.none()) { 2000 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 2001 // number of elements match or the value splatted is a zero constant. 2002 if (SameNumElts) 2003 return N1; 2004 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 2005 if (C->isZero()) 2006 return N1; 2007 } 2008 2009 // If the shuffle itself creates a splat, build the vector directly. 2010 if (AllSame && SameNumElts) { 2011 EVT BuildVT = BV->getValueType(0); 2012 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 2013 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 2014 2015 // We may have jumped through bitcasts, so the type of the 2016 // BUILD_VECTOR may not match the type of the shuffle. 2017 if (BuildVT != VT) 2018 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 2019 return NewBV; 2020 } 2021 } 2022 } 2023 2024 FoldingSetNodeID ID; 2025 SDValue Ops[2] = { N1, N2 }; 2026 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 2027 for (int i = 0; i != NElts; ++i) 2028 ID.AddInteger(MaskVec[i]); 2029 2030 void* IP = nullptr; 2031 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2032 return SDValue(E, 0); 2033 2034 // Allocate the mask array for the node out of the BumpPtrAllocator, since 2035 // SDNode doesn't have access to it. This memory will be "leaked" when 2036 // the node is deallocated, but recovered when the NodeAllocator is released. 2037 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 2038 llvm::copy(MaskVec, MaskAlloc); 2039 2040 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 2041 dl.getDebugLoc(), MaskAlloc); 2042 createOperands(N, Ops); 2043 2044 CSEMap.InsertNode(N, IP); 2045 InsertNode(N); 2046 SDValue V = SDValue(N, 0); 2047 NewSDValueDbgMsg(V, "Creating new node: ", this); 2048 return V; 2049 } 2050 2051 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 2052 EVT VT = SV.getValueType(0); 2053 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 2054 ShuffleVectorSDNode::commuteMask(MaskVec); 2055 2056 SDValue Op0 = SV.getOperand(0); 2057 SDValue Op1 = SV.getOperand(1); 2058 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 2059 } 2060 2061 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 2062 FoldingSetNodeID ID; 2063 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 2064 ID.AddInteger(RegNo); 2065 void *IP = nullptr; 2066 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2067 return SDValue(E, 0); 2068 2069 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 2070 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 2071 CSEMap.InsertNode(N, IP); 2072 InsertNode(N); 2073 return SDValue(N, 0); 2074 } 2075 2076 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 2077 FoldingSetNodeID ID; 2078 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 2079 ID.AddPointer(RegMask); 2080 void *IP = nullptr; 2081 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2082 return SDValue(E, 0); 2083 2084 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 2085 CSEMap.InsertNode(N, IP); 2086 InsertNode(N); 2087 return SDValue(N, 0); 2088 } 2089 2090 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 2091 MCSymbol *Label) { 2092 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 2093 } 2094 2095 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 2096 SDValue Root, MCSymbol *Label) { 2097 FoldingSetNodeID ID; 2098 SDValue Ops[] = { Root }; 2099 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 2100 ID.AddPointer(Label); 2101 void *IP = nullptr; 2102 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2103 return SDValue(E, 0); 2104 2105 auto *N = 2106 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 2107 createOperands(N, Ops); 2108 2109 CSEMap.InsertNode(N, IP); 2110 InsertNode(N); 2111 return SDValue(N, 0); 2112 } 2113 2114 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 2115 int64_t Offset, bool isTarget, 2116 unsigned TargetFlags) { 2117 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 2118 2119 FoldingSetNodeID ID; 2120 AddNodeIDNode(ID, Opc, getVTList(VT), None); 2121 ID.AddPointer(BA); 2122 ID.AddInteger(Offset); 2123 ID.AddInteger(TargetFlags); 2124 void *IP = nullptr; 2125 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2126 return SDValue(E, 0); 2127 2128 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 2129 CSEMap.InsertNode(N, IP); 2130 InsertNode(N); 2131 return SDValue(N, 0); 2132 } 2133 2134 SDValue SelectionDAG::getSrcValue(const Value *V) { 2135 FoldingSetNodeID ID; 2136 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 2137 ID.AddPointer(V); 2138 2139 void *IP = nullptr; 2140 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2141 return SDValue(E, 0); 2142 2143 auto *N = newSDNode<SrcValueSDNode>(V); 2144 CSEMap.InsertNode(N, IP); 2145 InsertNode(N); 2146 return SDValue(N, 0); 2147 } 2148 2149 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 2150 FoldingSetNodeID ID; 2151 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 2152 ID.AddPointer(MD); 2153 2154 void *IP = nullptr; 2155 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2156 return SDValue(E, 0); 2157 2158 auto *N = newSDNode<MDNodeSDNode>(MD); 2159 CSEMap.InsertNode(N, IP); 2160 InsertNode(N); 2161 return SDValue(N, 0); 2162 } 2163 2164 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2165 if (VT == V.getValueType()) 2166 return V; 2167 2168 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2169 } 2170 2171 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2172 unsigned SrcAS, unsigned DestAS) { 2173 SDValue Ops[] = {Ptr}; 2174 FoldingSetNodeID ID; 2175 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2176 ID.AddInteger(SrcAS); 2177 ID.AddInteger(DestAS); 2178 2179 void *IP = nullptr; 2180 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2181 return SDValue(E, 0); 2182 2183 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2184 VT, SrcAS, DestAS); 2185 createOperands(N, Ops); 2186 2187 CSEMap.InsertNode(N, IP); 2188 InsertNode(N); 2189 return SDValue(N, 0); 2190 } 2191 2192 SDValue SelectionDAG::getFreeze(SDValue V) { 2193 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2194 } 2195 2196 /// getShiftAmountOperand - Return the specified value casted to 2197 /// the target's desired shift amount type. 2198 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2199 EVT OpTy = Op.getValueType(); 2200 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2201 if (OpTy == ShTy || OpTy.isVector()) return Op; 2202 2203 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2204 } 2205 2206 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2207 SDLoc dl(Node); 2208 const TargetLowering &TLI = getTargetLoweringInfo(); 2209 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2210 EVT VT = Node->getValueType(0); 2211 SDValue Tmp1 = Node->getOperand(0); 2212 SDValue Tmp2 = Node->getOperand(1); 2213 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2214 2215 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2216 Tmp2, MachinePointerInfo(V)); 2217 SDValue VAList = VAListLoad; 2218 2219 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2220 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2221 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2222 2223 VAList = 2224 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2225 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2226 } 2227 2228 // Increment the pointer, VAList, to the next vaarg 2229 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2230 getConstant(getDataLayout().getTypeAllocSize( 2231 VT.getTypeForEVT(*getContext())), 2232 dl, VAList.getValueType())); 2233 // Store the incremented VAList to the legalized pointer 2234 Tmp1 = 2235 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2236 // Load the actual argument out of the pointer VAList 2237 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2238 } 2239 2240 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2241 SDLoc dl(Node); 2242 const TargetLowering &TLI = getTargetLoweringInfo(); 2243 // This defaults to loading a pointer from the input and storing it to the 2244 // output, returning the chain. 2245 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2246 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2247 SDValue Tmp1 = 2248 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2249 Node->getOperand(2), MachinePointerInfo(VS)); 2250 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2251 MachinePointerInfo(VD)); 2252 } 2253 2254 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2255 const DataLayout &DL = getDataLayout(); 2256 Type *Ty = VT.getTypeForEVT(*getContext()); 2257 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2258 2259 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2260 return RedAlign; 2261 2262 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2263 const Align StackAlign = TFI->getStackAlign(); 2264 2265 // See if we can choose a smaller ABI alignment in cases where it's an 2266 // illegal vector type that will get broken down. 2267 if (RedAlign > StackAlign) { 2268 EVT IntermediateVT; 2269 MVT RegisterVT; 2270 unsigned NumIntermediates; 2271 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2272 NumIntermediates, RegisterVT); 2273 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2274 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2275 if (RedAlign2 < RedAlign) 2276 RedAlign = RedAlign2; 2277 } 2278 2279 return RedAlign; 2280 } 2281 2282 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2283 MachineFrameInfo &MFI = MF->getFrameInfo(); 2284 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2285 int StackID = 0; 2286 if (Bytes.isScalable()) 2287 StackID = TFI->getStackIDForScalableVectors(); 2288 // The stack id gives an indication of whether the object is scalable or 2289 // not, so it's safe to pass in the minimum size here. 2290 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment, 2291 false, nullptr, StackID); 2292 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2293 } 2294 2295 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2296 Type *Ty = VT.getTypeForEVT(*getContext()); 2297 Align StackAlign = 2298 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2299 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2300 } 2301 2302 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2303 TypeSize VT1Size = VT1.getStoreSize(); 2304 TypeSize VT2Size = VT2.getStoreSize(); 2305 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2306 "Don't know how to choose the maximum size when creating a stack " 2307 "temporary"); 2308 TypeSize Bytes = 2309 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size; 2310 2311 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2312 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2313 const DataLayout &DL = getDataLayout(); 2314 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2315 return CreateStackTemporary(Bytes, Align); 2316 } 2317 2318 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2319 ISD::CondCode Cond, const SDLoc &dl) { 2320 EVT OpVT = N1.getValueType(); 2321 2322 // These setcc operations always fold. 2323 switch (Cond) { 2324 default: break; 2325 case ISD::SETFALSE: 2326 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2327 case ISD::SETTRUE: 2328 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2329 2330 case ISD::SETOEQ: 2331 case ISD::SETOGT: 2332 case ISD::SETOGE: 2333 case ISD::SETOLT: 2334 case ISD::SETOLE: 2335 case ISD::SETONE: 2336 case ISD::SETO: 2337 case ISD::SETUO: 2338 case ISD::SETUEQ: 2339 case ISD::SETUNE: 2340 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2341 break; 2342 } 2343 2344 if (OpVT.isInteger()) { 2345 // For EQ and NE, we can always pick a value for the undef to make the 2346 // predicate pass or fail, so we can return undef. 2347 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2348 // icmp eq/ne X, undef -> undef. 2349 if ((N1.isUndef() || N2.isUndef()) && 2350 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2351 return getUNDEF(VT); 2352 2353 // If both operands are undef, we can return undef for int comparison. 2354 // icmp undef, undef -> undef. 2355 if (N1.isUndef() && N2.isUndef()) 2356 return getUNDEF(VT); 2357 2358 // icmp X, X -> true/false 2359 // icmp X, undef -> true/false because undef could be X. 2360 if (N1 == N2) 2361 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2362 } 2363 2364 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2365 const APInt &C2 = N2C->getAPIntValue(); 2366 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2367 const APInt &C1 = N1C->getAPIntValue(); 2368 2369 return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)), 2370 dl, VT, OpVT); 2371 } 2372 } 2373 2374 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2375 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2376 2377 if (N1CFP && N2CFP) { 2378 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2379 switch (Cond) { 2380 default: break; 2381 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2382 return getUNDEF(VT); 2383 LLVM_FALLTHROUGH; 2384 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2385 OpVT); 2386 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2387 return getUNDEF(VT); 2388 LLVM_FALLTHROUGH; 2389 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2390 R==APFloat::cmpLessThan, dl, VT, 2391 OpVT); 2392 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2393 return getUNDEF(VT); 2394 LLVM_FALLTHROUGH; 2395 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2396 OpVT); 2397 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2398 return getUNDEF(VT); 2399 LLVM_FALLTHROUGH; 2400 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2401 VT, OpVT); 2402 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2403 return getUNDEF(VT); 2404 LLVM_FALLTHROUGH; 2405 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2406 R==APFloat::cmpEqual, dl, VT, 2407 OpVT); 2408 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2409 return getUNDEF(VT); 2410 LLVM_FALLTHROUGH; 2411 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2412 R==APFloat::cmpEqual, dl, VT, OpVT); 2413 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2414 OpVT); 2415 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2416 OpVT); 2417 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2418 R==APFloat::cmpEqual, dl, VT, 2419 OpVT); 2420 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2421 OpVT); 2422 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2423 R==APFloat::cmpLessThan, dl, VT, 2424 OpVT); 2425 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2426 R==APFloat::cmpUnordered, dl, VT, 2427 OpVT); 2428 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2429 VT, OpVT); 2430 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2431 OpVT); 2432 } 2433 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2434 // Ensure that the constant occurs on the RHS. 2435 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2436 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2437 return SDValue(); 2438 return getSetCC(dl, VT, N2, N1, SwappedCond); 2439 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2440 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2441 // If an operand is known to be a nan (or undef that could be a nan), we can 2442 // fold it. 2443 // Choosing NaN for the undef will always make unordered comparison succeed 2444 // and ordered comparison fails. 2445 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2446 switch (ISD::getUnorderedFlavor(Cond)) { 2447 default: 2448 llvm_unreachable("Unknown flavor!"); 2449 case 0: // Known false. 2450 return getBoolConstant(false, dl, VT, OpVT); 2451 case 1: // Known true. 2452 return getBoolConstant(true, dl, VT, OpVT); 2453 case 2: // Undefined. 2454 return getUNDEF(VT); 2455 } 2456 } 2457 2458 // Could not fold it. 2459 return SDValue(); 2460 } 2461 2462 /// See if the specified operand can be simplified with the knowledge that only 2463 /// the bits specified by DemandedBits are used. 2464 /// TODO: really we should be making this into the DAG equivalent of 2465 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2466 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) { 2467 EVT VT = V.getValueType(); 2468 2469 if (VT.isScalableVector()) 2470 return SDValue(); 2471 2472 APInt DemandedElts = VT.isVector() 2473 ? APInt::getAllOnes(VT.getVectorNumElements()) 2474 : APInt(1, 1); 2475 return GetDemandedBits(V, DemandedBits, DemandedElts); 2476 } 2477 2478 /// See if the specified operand can be simplified with the knowledge that only 2479 /// the bits specified by DemandedBits are used in the elements specified by 2480 /// DemandedElts. 2481 /// TODO: really we should be making this into the DAG equivalent of 2482 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2483 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits, 2484 const APInt &DemandedElts) { 2485 switch (V.getOpcode()) { 2486 default: 2487 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts, 2488 *this); 2489 case ISD::Constant: { 2490 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue(); 2491 APInt NewVal = CVal & DemandedBits; 2492 if (NewVal != CVal) 2493 return getConstant(NewVal, SDLoc(V), V.getValueType()); 2494 break; 2495 } 2496 case ISD::SRL: 2497 // Only look at single-use SRLs. 2498 if (!V.getNode()->hasOneUse()) 2499 break; 2500 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2501 // See if we can recursively simplify the LHS. 2502 unsigned Amt = RHSC->getZExtValue(); 2503 2504 // Watch out for shift count overflow though. 2505 if (Amt >= DemandedBits.getBitWidth()) 2506 break; 2507 APInt SrcDemandedBits = DemandedBits << Amt; 2508 if (SDValue SimplifyLHS = 2509 GetDemandedBits(V.getOperand(0), SrcDemandedBits)) 2510 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS, 2511 V.getOperand(1)); 2512 } 2513 break; 2514 } 2515 return SDValue(); 2516 } 2517 2518 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2519 /// use this predicate to simplify operations downstream. 2520 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2521 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2522 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2523 } 2524 2525 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2526 /// this predicate to simplify operations downstream. Mask is known to be zero 2527 /// for bits that V cannot have. 2528 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2529 unsigned Depth) const { 2530 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2531 } 2532 2533 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2534 /// DemandedElts. We use this predicate to simplify operations downstream. 2535 /// Mask is known to be zero for bits that V cannot have. 2536 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2537 const APInt &DemandedElts, 2538 unsigned Depth) const { 2539 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2540 } 2541 2542 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2543 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2544 unsigned Depth) const { 2545 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2546 } 2547 2548 /// isSplatValue - Return true if the vector V has the same value 2549 /// across all DemandedElts. For scalable vectors it does not make 2550 /// sense to specify which elements are demanded or undefined, therefore 2551 /// they are simply ignored. 2552 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2553 APInt &UndefElts, unsigned Depth) const { 2554 unsigned Opcode = V.getOpcode(); 2555 EVT VT = V.getValueType(); 2556 assert(VT.isVector() && "Vector type expected"); 2557 2558 if (!VT.isScalableVector() && !DemandedElts) 2559 return false; // No demanded elts, better to assume we don't know anything. 2560 2561 if (Depth >= MaxRecursionDepth) 2562 return false; // Limit search depth. 2563 2564 // Deal with some common cases here that work for both fixed and scalable 2565 // vector types. 2566 switch (Opcode) { 2567 case ISD::SPLAT_VECTOR: 2568 UndefElts = V.getOperand(0).isUndef() 2569 ? APInt::getAllOnes(DemandedElts.getBitWidth()) 2570 : APInt(DemandedElts.getBitWidth(), 0); 2571 return true; 2572 case ISD::ADD: 2573 case ISD::SUB: 2574 case ISD::AND: 2575 case ISD::XOR: 2576 case ISD::OR: { 2577 APInt UndefLHS, UndefRHS; 2578 SDValue LHS = V.getOperand(0); 2579 SDValue RHS = V.getOperand(1); 2580 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2581 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2582 UndefElts = UndefLHS | UndefRHS; 2583 return true; 2584 } 2585 return false; 2586 } 2587 case ISD::ABS: 2588 case ISD::TRUNCATE: 2589 case ISD::SIGN_EXTEND: 2590 case ISD::ZERO_EXTEND: 2591 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2592 default: 2593 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 2594 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 2595 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth); 2596 break; 2597 } 2598 2599 // We don't support other cases than those above for scalable vectors at 2600 // the moment. 2601 if (VT.isScalableVector()) 2602 return false; 2603 2604 unsigned NumElts = VT.getVectorNumElements(); 2605 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2606 UndefElts = APInt::getZero(NumElts); 2607 2608 switch (Opcode) { 2609 case ISD::BUILD_VECTOR: { 2610 SDValue Scl; 2611 for (unsigned i = 0; i != NumElts; ++i) { 2612 SDValue Op = V.getOperand(i); 2613 if (Op.isUndef()) { 2614 UndefElts.setBit(i); 2615 continue; 2616 } 2617 if (!DemandedElts[i]) 2618 continue; 2619 if (Scl && Scl != Op) 2620 return false; 2621 Scl = Op; 2622 } 2623 return true; 2624 } 2625 case ISD::VECTOR_SHUFFLE: { 2626 // Check if this is a shuffle node doing a splat or a shuffle of a splat. 2627 APInt DemandedLHS = APInt::getNullValue(NumElts); 2628 APInt DemandedRHS = APInt::getNullValue(NumElts); 2629 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2630 for (int i = 0; i != (int)NumElts; ++i) { 2631 int M = Mask[i]; 2632 if (M < 0) { 2633 UndefElts.setBit(i); 2634 continue; 2635 } 2636 if (!DemandedElts[i]) 2637 continue; 2638 if (M < (int)NumElts) 2639 DemandedLHS.setBit(M); 2640 else 2641 DemandedRHS.setBit(M - NumElts); 2642 } 2643 2644 // If we aren't demanding either op, assume there's no splat. 2645 // If we are demanding both ops, assume there's no splat. 2646 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) || 2647 (!DemandedLHS.isZero() && !DemandedRHS.isZero())) 2648 return false; 2649 2650 // See if the demanded elts of the source op is a splat or we only demand 2651 // one element, which should always be a splat. 2652 // TODO: Handle source ops splats with undefs. 2653 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) { 2654 APInt SrcUndefs; 2655 return (SrcElts.countPopulation() == 1) || 2656 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) && 2657 (SrcElts & SrcUndefs).isZero()); 2658 }; 2659 if (!DemandedLHS.isZero()) 2660 return CheckSplatSrc(V.getOperand(0), DemandedLHS); 2661 return CheckSplatSrc(V.getOperand(1), DemandedRHS); 2662 } 2663 case ISD::EXTRACT_SUBVECTOR: { 2664 // Offset the demanded elts by the subvector index. 2665 SDValue Src = V.getOperand(0); 2666 // We don't support scalable vectors at the moment. 2667 if (Src.getValueType().isScalableVector()) 2668 return false; 2669 uint64_t Idx = V.getConstantOperandVal(1); 2670 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2671 APInt UndefSrcElts; 2672 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2673 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2674 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2675 return true; 2676 } 2677 break; 2678 } 2679 case ISD::ANY_EXTEND_VECTOR_INREG: 2680 case ISD::SIGN_EXTEND_VECTOR_INREG: 2681 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2682 // Widen the demanded elts by the src element count. 2683 SDValue Src = V.getOperand(0); 2684 // We don't support scalable vectors at the moment. 2685 if (Src.getValueType().isScalableVector()) 2686 return false; 2687 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2688 APInt UndefSrcElts; 2689 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts); 2690 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2691 UndefElts = UndefSrcElts.truncOrSelf(NumElts); 2692 return true; 2693 } 2694 break; 2695 } 2696 case ISD::BITCAST: { 2697 SDValue Src = V.getOperand(0); 2698 EVT SrcVT = Src.getValueType(); 2699 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits(); 2700 unsigned BitWidth = VT.getScalarSizeInBits(); 2701 2702 // Ignore bitcasts from unsupported types. 2703 // TODO: Add fp support? 2704 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger()) 2705 break; 2706 2707 // Bitcast 'small element' vector to 'large element' vector. 2708 if ((BitWidth % SrcBitWidth) == 0) { 2709 // See if each sub element is a splat. 2710 unsigned Scale = BitWidth / SrcBitWidth; 2711 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2712 APInt ScaledDemandedElts = 2713 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2714 for (unsigned I = 0; I != Scale; ++I) { 2715 APInt SubUndefElts; 2716 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I); 2717 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt); 2718 SubDemandedElts &= ScaledDemandedElts; 2719 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1)) 2720 return false; 2721 // TODO: Add support for merging sub undef elements. 2722 if (SubDemandedElts.isSubsetOf(SubUndefElts)) 2723 return false; 2724 } 2725 return true; 2726 } 2727 break; 2728 } 2729 } 2730 2731 return false; 2732 } 2733 2734 /// Helper wrapper to main isSplatValue function. 2735 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const { 2736 EVT VT = V.getValueType(); 2737 assert(VT.isVector() && "Vector type expected"); 2738 2739 APInt UndefElts; 2740 APInt DemandedElts; 2741 2742 // For now we don't support this with scalable vectors. 2743 if (!VT.isScalableVector()) 2744 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2745 return isSplatValue(V, DemandedElts, UndefElts) && 2746 (AllowUndefs || !UndefElts); 2747 } 2748 2749 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2750 V = peekThroughExtractSubvectors(V); 2751 2752 EVT VT = V.getValueType(); 2753 unsigned Opcode = V.getOpcode(); 2754 switch (Opcode) { 2755 default: { 2756 APInt UndefElts; 2757 APInt DemandedElts; 2758 2759 if (!VT.isScalableVector()) 2760 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2761 2762 if (isSplatValue(V, DemandedElts, UndefElts)) { 2763 if (VT.isScalableVector()) { 2764 // DemandedElts and UndefElts are ignored for scalable vectors, since 2765 // the only supported cases are SPLAT_VECTOR nodes. 2766 SplatIdx = 0; 2767 } else { 2768 // Handle case where all demanded elements are UNDEF. 2769 if (DemandedElts.isSubsetOf(UndefElts)) { 2770 SplatIdx = 0; 2771 return getUNDEF(VT); 2772 } 2773 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes(); 2774 } 2775 return V; 2776 } 2777 break; 2778 } 2779 case ISD::SPLAT_VECTOR: 2780 SplatIdx = 0; 2781 return V; 2782 case ISD::VECTOR_SHUFFLE: { 2783 if (VT.isScalableVector()) 2784 return SDValue(); 2785 2786 // Check if this is a shuffle node doing a splat. 2787 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2788 // getTargetVShiftNode currently struggles without the splat source. 2789 auto *SVN = cast<ShuffleVectorSDNode>(V); 2790 if (!SVN->isSplat()) 2791 break; 2792 int Idx = SVN->getSplatIndex(); 2793 int NumElts = V.getValueType().getVectorNumElements(); 2794 SplatIdx = Idx % NumElts; 2795 return V.getOperand(Idx / NumElts); 2796 } 2797 } 2798 2799 return SDValue(); 2800 } 2801 2802 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) { 2803 int SplatIdx; 2804 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) { 2805 EVT SVT = SrcVector.getValueType().getScalarType(); 2806 EVT LegalSVT = SVT; 2807 if (LegalTypes && !TLI->isTypeLegal(SVT)) { 2808 if (!SVT.isInteger()) 2809 return SDValue(); 2810 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 2811 if (LegalSVT.bitsLT(SVT)) 2812 return SDValue(); 2813 } 2814 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector, 2815 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2816 } 2817 return SDValue(); 2818 } 2819 2820 const APInt * 2821 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2822 const APInt &DemandedElts) const { 2823 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2824 V.getOpcode() == ISD::SRA) && 2825 "Unknown shift node"); 2826 unsigned BitWidth = V.getScalarValueSizeInBits(); 2827 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2828 // Shifting more than the bitwidth is not valid. 2829 const APInt &ShAmt = SA->getAPIntValue(); 2830 if (ShAmt.ult(BitWidth)) 2831 return &ShAmt; 2832 } 2833 return nullptr; 2834 } 2835 2836 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2837 SDValue V, const APInt &DemandedElts) const { 2838 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2839 V.getOpcode() == ISD::SRA) && 2840 "Unknown shift node"); 2841 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2842 return ValidAmt; 2843 unsigned BitWidth = V.getScalarValueSizeInBits(); 2844 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2845 if (!BV) 2846 return nullptr; 2847 const APInt *MinShAmt = nullptr; 2848 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2849 if (!DemandedElts[i]) 2850 continue; 2851 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2852 if (!SA) 2853 return nullptr; 2854 // Shifting more than the bitwidth is not valid. 2855 const APInt &ShAmt = SA->getAPIntValue(); 2856 if (ShAmt.uge(BitWidth)) 2857 return nullptr; 2858 if (MinShAmt && MinShAmt->ule(ShAmt)) 2859 continue; 2860 MinShAmt = &ShAmt; 2861 } 2862 return MinShAmt; 2863 } 2864 2865 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2866 SDValue V, const APInt &DemandedElts) const { 2867 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2868 V.getOpcode() == ISD::SRA) && 2869 "Unknown shift node"); 2870 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2871 return ValidAmt; 2872 unsigned BitWidth = V.getScalarValueSizeInBits(); 2873 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2874 if (!BV) 2875 return nullptr; 2876 const APInt *MaxShAmt = nullptr; 2877 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2878 if (!DemandedElts[i]) 2879 continue; 2880 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2881 if (!SA) 2882 return nullptr; 2883 // Shifting more than the bitwidth is not valid. 2884 const APInt &ShAmt = SA->getAPIntValue(); 2885 if (ShAmt.uge(BitWidth)) 2886 return nullptr; 2887 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2888 continue; 2889 MaxShAmt = &ShAmt; 2890 } 2891 return MaxShAmt; 2892 } 2893 2894 /// Determine which bits of Op are known to be either zero or one and return 2895 /// them in Known. For vectors, the known bits are those that are shared by 2896 /// every vector element. 2897 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 2898 EVT VT = Op.getValueType(); 2899 2900 // TOOD: Until we have a plan for how to represent demanded elements for 2901 // scalable vectors, we can just bail out for now. 2902 if (Op.getValueType().isScalableVector()) { 2903 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2904 return KnownBits(BitWidth); 2905 } 2906 2907 APInt DemandedElts = VT.isVector() 2908 ? APInt::getAllOnes(VT.getVectorNumElements()) 2909 : APInt(1, 1); 2910 return computeKnownBits(Op, DemandedElts, Depth); 2911 } 2912 2913 /// Determine which bits of Op are known to be either zero or one and return 2914 /// them in Known. The DemandedElts argument allows us to only collect the known 2915 /// bits that are shared by the requested vector elements. 2916 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 2917 unsigned Depth) const { 2918 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2919 2920 KnownBits Known(BitWidth); // Don't know anything. 2921 2922 // TOOD: Until we have a plan for how to represent demanded elements for 2923 // scalable vectors, we can just bail out for now. 2924 if (Op.getValueType().isScalableVector()) 2925 return Known; 2926 2927 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2928 // We know all of the bits for a constant! 2929 return KnownBits::makeConstant(C->getAPIntValue()); 2930 } 2931 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 2932 // We know all of the bits for a constant fp! 2933 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 2934 } 2935 2936 if (Depth >= MaxRecursionDepth) 2937 return Known; // Limit search depth. 2938 2939 KnownBits Known2; 2940 unsigned NumElts = DemandedElts.getBitWidth(); 2941 assert((!Op.getValueType().isVector() || 2942 NumElts == Op.getValueType().getVectorNumElements()) && 2943 "Unexpected vector size"); 2944 2945 if (!DemandedElts) 2946 return Known; // No demanded elts, better to assume we don't know anything. 2947 2948 unsigned Opcode = Op.getOpcode(); 2949 switch (Opcode) { 2950 case ISD::BUILD_VECTOR: 2951 // Collect the known bits that are shared by every demanded vector element. 2952 Known.Zero.setAllBits(); Known.One.setAllBits(); 2953 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 2954 if (!DemandedElts[i]) 2955 continue; 2956 2957 SDValue SrcOp = Op.getOperand(i); 2958 Known2 = computeKnownBits(SrcOp, Depth + 1); 2959 2960 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2961 if (SrcOp.getValueSizeInBits() != BitWidth) { 2962 assert(SrcOp.getValueSizeInBits() > BitWidth && 2963 "Expected BUILD_VECTOR implicit truncation"); 2964 Known2 = Known2.trunc(BitWidth); 2965 } 2966 2967 // Known bits are the values that are shared by every demanded element. 2968 Known = KnownBits::commonBits(Known, Known2); 2969 2970 // If we don't know any bits, early out. 2971 if (Known.isUnknown()) 2972 break; 2973 } 2974 break; 2975 case ISD::VECTOR_SHUFFLE: { 2976 // Collect the known bits that are shared by every vector element referenced 2977 // by the shuffle. 2978 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 2979 Known.Zero.setAllBits(); Known.One.setAllBits(); 2980 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 2981 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 2982 for (unsigned i = 0; i != NumElts; ++i) { 2983 if (!DemandedElts[i]) 2984 continue; 2985 2986 int M = SVN->getMaskElt(i); 2987 if (M < 0) { 2988 // For UNDEF elements, we don't know anything about the common state of 2989 // the shuffle result. 2990 Known.resetAll(); 2991 DemandedLHS.clearAllBits(); 2992 DemandedRHS.clearAllBits(); 2993 break; 2994 } 2995 2996 if ((unsigned)M < NumElts) 2997 DemandedLHS.setBit((unsigned)M % NumElts); 2998 else 2999 DemandedRHS.setBit((unsigned)M % NumElts); 3000 } 3001 // Known bits are the values that are shared by every demanded element. 3002 if (!!DemandedLHS) { 3003 SDValue LHS = Op.getOperand(0); 3004 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 3005 Known = KnownBits::commonBits(Known, Known2); 3006 } 3007 // If we don't know any bits, early out. 3008 if (Known.isUnknown()) 3009 break; 3010 if (!!DemandedRHS) { 3011 SDValue RHS = Op.getOperand(1); 3012 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 3013 Known = KnownBits::commonBits(Known, Known2); 3014 } 3015 break; 3016 } 3017 case ISD::CONCAT_VECTORS: { 3018 // Split DemandedElts and test each of the demanded subvectors. 3019 Known.Zero.setAllBits(); Known.One.setAllBits(); 3020 EVT SubVectorVT = Op.getOperand(0).getValueType(); 3021 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 3022 unsigned NumSubVectors = Op.getNumOperands(); 3023 for (unsigned i = 0; i != NumSubVectors; ++i) { 3024 APInt DemandedSub = 3025 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 3026 if (!!DemandedSub) { 3027 SDValue Sub = Op.getOperand(i); 3028 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 3029 Known = KnownBits::commonBits(Known, Known2); 3030 } 3031 // If we don't know any bits, early out. 3032 if (Known.isUnknown()) 3033 break; 3034 } 3035 break; 3036 } 3037 case ISD::INSERT_SUBVECTOR: { 3038 // Demand any elements from the subvector and the remainder from the src its 3039 // inserted into. 3040 SDValue Src = Op.getOperand(0); 3041 SDValue Sub = Op.getOperand(1); 3042 uint64_t Idx = Op.getConstantOperandVal(2); 3043 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 3044 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 3045 APInt DemandedSrcElts = DemandedElts; 3046 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 3047 3048 Known.One.setAllBits(); 3049 Known.Zero.setAllBits(); 3050 if (!!DemandedSubElts) { 3051 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 3052 if (Known.isUnknown()) 3053 break; // early-out. 3054 } 3055 if (!!DemandedSrcElts) { 3056 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3057 Known = KnownBits::commonBits(Known, Known2); 3058 } 3059 break; 3060 } 3061 case ISD::EXTRACT_SUBVECTOR: { 3062 // Offset the demanded elts by the subvector index. 3063 SDValue Src = Op.getOperand(0); 3064 // Bail until we can represent demanded elements for scalable vectors. 3065 if (Src.getValueType().isScalableVector()) 3066 break; 3067 uint64_t Idx = Op.getConstantOperandVal(1); 3068 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3069 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 3070 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3071 break; 3072 } 3073 case ISD::SCALAR_TO_VECTOR: { 3074 // We know about scalar_to_vector as much as we know about it source, 3075 // which becomes the first element of otherwise unknown vector. 3076 if (DemandedElts != 1) 3077 break; 3078 3079 SDValue N0 = Op.getOperand(0); 3080 Known = computeKnownBits(N0, Depth + 1); 3081 if (N0.getValueSizeInBits() != BitWidth) 3082 Known = Known.trunc(BitWidth); 3083 3084 break; 3085 } 3086 case ISD::BITCAST: { 3087 SDValue N0 = Op.getOperand(0); 3088 EVT SubVT = N0.getValueType(); 3089 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 3090 3091 // Ignore bitcasts from unsupported types. 3092 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 3093 break; 3094 3095 // Fast handling of 'identity' bitcasts. 3096 if (BitWidth == SubBitWidth) { 3097 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 3098 break; 3099 } 3100 3101 bool IsLE = getDataLayout().isLittleEndian(); 3102 3103 // Bitcast 'small element' vector to 'large element' scalar/vector. 3104 if ((BitWidth % SubBitWidth) == 0) { 3105 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 3106 3107 // Collect known bits for the (larger) output by collecting the known 3108 // bits from each set of sub elements and shift these into place. 3109 // We need to separately call computeKnownBits for each set of 3110 // sub elements as the knownbits for each is likely to be different. 3111 unsigned SubScale = BitWidth / SubBitWidth; 3112 APInt SubDemandedElts(NumElts * SubScale, 0); 3113 for (unsigned i = 0; i != NumElts; ++i) 3114 if (DemandedElts[i]) 3115 SubDemandedElts.setBit(i * SubScale); 3116 3117 for (unsigned i = 0; i != SubScale; ++i) { 3118 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 3119 Depth + 1); 3120 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 3121 Known.insertBits(Known2, SubBitWidth * Shifts); 3122 } 3123 } 3124 3125 // Bitcast 'large element' scalar/vector to 'small element' vector. 3126 if ((SubBitWidth % BitWidth) == 0) { 3127 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 3128 3129 // Collect known bits for the (smaller) output by collecting the known 3130 // bits from the overlapping larger input elements and extracting the 3131 // sub sections we actually care about. 3132 unsigned SubScale = SubBitWidth / BitWidth; 3133 APInt SubDemandedElts = 3134 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale); 3135 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 3136 3137 Known.Zero.setAllBits(); Known.One.setAllBits(); 3138 for (unsigned i = 0; i != NumElts; ++i) 3139 if (DemandedElts[i]) { 3140 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 3141 unsigned Offset = (Shifts % SubScale) * BitWidth; 3142 Known = KnownBits::commonBits(Known, 3143 Known2.extractBits(BitWidth, Offset)); 3144 // If we don't know any bits, early out. 3145 if (Known.isUnknown()) 3146 break; 3147 } 3148 } 3149 break; 3150 } 3151 case ISD::AND: 3152 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3153 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3154 3155 Known &= Known2; 3156 break; 3157 case ISD::OR: 3158 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3159 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3160 3161 Known |= Known2; 3162 break; 3163 case ISD::XOR: 3164 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3165 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3166 3167 Known ^= Known2; 3168 break; 3169 case ISD::MUL: { 3170 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3171 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3172 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3173 // TODO: SelfMultiply can be poison, but not undef. 3174 if (SelfMultiply) 3175 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison( 3176 Op.getOperand(0), DemandedElts, false, Depth + 1); 3177 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3178 break; 3179 } 3180 case ISD::MULHU: { 3181 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3182 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3183 Known = KnownBits::mulhu(Known, Known2); 3184 break; 3185 } 3186 case ISD::MULHS: { 3187 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3188 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3189 Known = KnownBits::mulhs(Known, Known2); 3190 break; 3191 } 3192 case ISD::UMUL_LOHI: { 3193 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3194 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3195 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3196 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3197 if (Op.getResNo() == 0) 3198 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3199 else 3200 Known = KnownBits::mulhu(Known, Known2); 3201 break; 3202 } 3203 case ISD::SMUL_LOHI: { 3204 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3205 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3206 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3207 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3208 if (Op.getResNo() == 0) 3209 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3210 else 3211 Known = KnownBits::mulhs(Known, Known2); 3212 break; 3213 } 3214 case ISD::UDIV: { 3215 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3216 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3217 Known = KnownBits::udiv(Known, Known2); 3218 break; 3219 } 3220 case ISD::AVGCEILU: { 3221 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3222 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3223 Known = Known.zext(BitWidth + 1); 3224 Known2 = Known2.zext(BitWidth + 1); 3225 KnownBits One = KnownBits::makeConstant(APInt(1, 1)); 3226 Known = KnownBits::computeForAddCarry(Known, Known2, One); 3227 Known = Known.extractBits(BitWidth, 1); 3228 break; 3229 } 3230 case ISD::SELECT: 3231 case ISD::VSELECT: 3232 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3233 // If we don't know any bits, early out. 3234 if (Known.isUnknown()) 3235 break; 3236 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3237 3238 // Only known if known in both the LHS and RHS. 3239 Known = KnownBits::commonBits(Known, Known2); 3240 break; 3241 case ISD::SELECT_CC: 3242 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3243 // If we don't know any bits, early out. 3244 if (Known.isUnknown()) 3245 break; 3246 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3247 3248 // Only known if known in both the LHS and RHS. 3249 Known = KnownBits::commonBits(Known, Known2); 3250 break; 3251 case ISD::SMULO: 3252 case ISD::UMULO: 3253 if (Op.getResNo() != 1) 3254 break; 3255 // The boolean result conforms to getBooleanContents. 3256 // If we know the result of a setcc has the top bits zero, use this info. 3257 // We know that we have an integer-based boolean since these operations 3258 // are only available for integer. 3259 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3260 TargetLowering::ZeroOrOneBooleanContent && 3261 BitWidth > 1) 3262 Known.Zero.setBitsFrom(1); 3263 break; 3264 case ISD::SETCC: 3265 case ISD::STRICT_FSETCC: 3266 case ISD::STRICT_FSETCCS: { 3267 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3268 // If we know the result of a setcc has the top bits zero, use this info. 3269 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3270 TargetLowering::ZeroOrOneBooleanContent && 3271 BitWidth > 1) 3272 Known.Zero.setBitsFrom(1); 3273 break; 3274 } 3275 case ISD::SHL: 3276 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3277 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3278 Known = KnownBits::shl(Known, Known2); 3279 3280 // Minimum shift low bits are known zero. 3281 if (const APInt *ShMinAmt = 3282 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3283 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3284 break; 3285 case ISD::SRL: 3286 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3287 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3288 Known = KnownBits::lshr(Known, Known2); 3289 3290 // Minimum shift high bits are known zero. 3291 if (const APInt *ShMinAmt = 3292 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3293 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3294 break; 3295 case ISD::SRA: 3296 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3297 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3298 Known = KnownBits::ashr(Known, Known2); 3299 // TODO: Add minimum shift high known sign bits. 3300 break; 3301 case ISD::FSHL: 3302 case ISD::FSHR: 3303 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3304 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3305 3306 // For fshl, 0-shift returns the 1st arg. 3307 // For fshr, 0-shift returns the 2nd arg. 3308 if (Amt == 0) { 3309 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3310 DemandedElts, Depth + 1); 3311 break; 3312 } 3313 3314 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3315 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3316 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3317 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3318 if (Opcode == ISD::FSHL) { 3319 Known.One <<= Amt; 3320 Known.Zero <<= Amt; 3321 Known2.One.lshrInPlace(BitWidth - Amt); 3322 Known2.Zero.lshrInPlace(BitWidth - Amt); 3323 } else { 3324 Known.One <<= BitWidth - Amt; 3325 Known.Zero <<= BitWidth - Amt; 3326 Known2.One.lshrInPlace(Amt); 3327 Known2.Zero.lshrInPlace(Amt); 3328 } 3329 Known.One |= Known2.One; 3330 Known.Zero |= Known2.Zero; 3331 } 3332 break; 3333 case ISD::SIGN_EXTEND_INREG: { 3334 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3335 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3336 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3337 break; 3338 } 3339 case ISD::CTTZ: 3340 case ISD::CTTZ_ZERO_UNDEF: { 3341 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3342 // If we have a known 1, its position is our upper bound. 3343 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3344 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3345 Known.Zero.setBitsFrom(LowBits); 3346 break; 3347 } 3348 case ISD::CTLZ: 3349 case ISD::CTLZ_ZERO_UNDEF: { 3350 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3351 // If we have a known 1, its position is our upper bound. 3352 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3353 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3354 Known.Zero.setBitsFrom(LowBits); 3355 break; 3356 } 3357 case ISD::CTPOP: { 3358 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3359 // If we know some of the bits are zero, they can't be one. 3360 unsigned PossibleOnes = Known2.countMaxPopulation(); 3361 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3362 break; 3363 } 3364 case ISD::PARITY: { 3365 // Parity returns 0 everywhere but the LSB. 3366 Known.Zero.setBitsFrom(1); 3367 break; 3368 } 3369 case ISD::LOAD: { 3370 LoadSDNode *LD = cast<LoadSDNode>(Op); 3371 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3372 if (ISD::isNON_EXTLoad(LD) && Cst) { 3373 // Determine any common known bits from the loaded constant pool value. 3374 Type *CstTy = Cst->getType(); 3375 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3376 // If its a vector splat, then we can (quickly) reuse the scalar path. 3377 // NOTE: We assume all elements match and none are UNDEF. 3378 if (CstTy->isVectorTy()) { 3379 if (const Constant *Splat = Cst->getSplatValue()) { 3380 Cst = Splat; 3381 CstTy = Cst->getType(); 3382 } 3383 } 3384 // TODO - do we need to handle different bitwidths? 3385 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3386 // Iterate across all vector elements finding common known bits. 3387 Known.One.setAllBits(); 3388 Known.Zero.setAllBits(); 3389 for (unsigned i = 0; i != NumElts; ++i) { 3390 if (!DemandedElts[i]) 3391 continue; 3392 if (Constant *Elt = Cst->getAggregateElement(i)) { 3393 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3394 const APInt &Value = CInt->getValue(); 3395 Known.One &= Value; 3396 Known.Zero &= ~Value; 3397 continue; 3398 } 3399 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3400 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3401 Known.One &= Value; 3402 Known.Zero &= ~Value; 3403 continue; 3404 } 3405 } 3406 Known.One.clearAllBits(); 3407 Known.Zero.clearAllBits(); 3408 break; 3409 } 3410 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3411 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3412 Known = KnownBits::makeConstant(CInt->getValue()); 3413 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3414 Known = 3415 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3416 } 3417 } 3418 } 3419 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3420 // If this is a ZEXTLoad and we are looking at the loaded value. 3421 EVT VT = LD->getMemoryVT(); 3422 unsigned MemBits = VT.getScalarSizeInBits(); 3423 Known.Zero.setBitsFrom(MemBits); 3424 } else if (const MDNode *Ranges = LD->getRanges()) { 3425 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3426 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3427 } 3428 break; 3429 } 3430 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3431 EVT InVT = Op.getOperand(0).getValueType(); 3432 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3433 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3434 Known = Known.zext(BitWidth); 3435 break; 3436 } 3437 case ISD::ZERO_EXTEND: { 3438 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3439 Known = Known.zext(BitWidth); 3440 break; 3441 } 3442 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3443 EVT InVT = Op.getOperand(0).getValueType(); 3444 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3445 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3446 // If the sign bit is known to be zero or one, then sext will extend 3447 // it to the top bits, else it will just zext. 3448 Known = Known.sext(BitWidth); 3449 break; 3450 } 3451 case ISD::SIGN_EXTEND: { 3452 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3453 // If the sign bit is known to be zero or one, then sext will extend 3454 // it to the top bits, else it will just zext. 3455 Known = Known.sext(BitWidth); 3456 break; 3457 } 3458 case ISD::ANY_EXTEND_VECTOR_INREG: { 3459 EVT InVT = Op.getOperand(0).getValueType(); 3460 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3461 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3462 Known = Known.anyext(BitWidth); 3463 break; 3464 } 3465 case ISD::ANY_EXTEND: { 3466 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3467 Known = Known.anyext(BitWidth); 3468 break; 3469 } 3470 case ISD::TRUNCATE: { 3471 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3472 Known = Known.trunc(BitWidth); 3473 break; 3474 } 3475 case ISD::AssertZext: { 3476 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3477 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3478 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3479 Known.Zero |= (~InMask); 3480 Known.One &= (~Known.Zero); 3481 break; 3482 } 3483 case ISD::AssertAlign: { 3484 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3485 assert(LogOfAlign != 0); 3486 3487 // TODO: Should use maximum with source 3488 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3489 // well as clearing one bits. 3490 Known.Zero.setLowBits(LogOfAlign); 3491 Known.One.clearLowBits(LogOfAlign); 3492 break; 3493 } 3494 case ISD::FGETSIGN: 3495 // All bits are zero except the low bit. 3496 Known.Zero.setBitsFrom(1); 3497 break; 3498 case ISD::USUBO: 3499 case ISD::SSUBO: 3500 if (Op.getResNo() == 1) { 3501 // If we know the result of a setcc has the top bits zero, use this info. 3502 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3503 TargetLowering::ZeroOrOneBooleanContent && 3504 BitWidth > 1) 3505 Known.Zero.setBitsFrom(1); 3506 break; 3507 } 3508 LLVM_FALLTHROUGH; 3509 case ISD::SUB: 3510 case ISD::SUBC: { 3511 assert(Op.getResNo() == 0 && 3512 "We only compute knownbits for the difference here."); 3513 3514 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3515 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3516 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3517 Known, Known2); 3518 break; 3519 } 3520 case ISD::UADDO: 3521 case ISD::SADDO: 3522 case ISD::ADDCARRY: 3523 if (Op.getResNo() == 1) { 3524 // If we know the result of a setcc has the top bits zero, use this info. 3525 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3526 TargetLowering::ZeroOrOneBooleanContent && 3527 BitWidth > 1) 3528 Known.Zero.setBitsFrom(1); 3529 break; 3530 } 3531 LLVM_FALLTHROUGH; 3532 case ISD::ADD: 3533 case ISD::ADDC: 3534 case ISD::ADDE: { 3535 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3536 3537 // With ADDE and ADDCARRY, a carry bit may be added in. 3538 KnownBits Carry(1); 3539 if (Opcode == ISD::ADDE) 3540 // Can't track carry from glue, set carry to unknown. 3541 Carry.resetAll(); 3542 else if (Opcode == ISD::ADDCARRY) 3543 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3544 // the trouble (how often will we find a known carry bit). And I haven't 3545 // tested this very much yet, but something like this might work: 3546 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3547 // Carry = Carry.zextOrTrunc(1, false); 3548 Carry.resetAll(); 3549 else 3550 Carry.setAllZero(); 3551 3552 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3553 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3554 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3555 break; 3556 } 3557 case ISD::SREM: { 3558 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3559 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3560 Known = KnownBits::srem(Known, Known2); 3561 break; 3562 } 3563 case ISD::UREM: { 3564 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3565 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3566 Known = KnownBits::urem(Known, Known2); 3567 break; 3568 } 3569 case ISD::EXTRACT_ELEMENT: { 3570 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3571 const unsigned Index = Op.getConstantOperandVal(1); 3572 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3573 3574 // Remove low part of known bits mask 3575 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3576 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3577 3578 // Remove high part of known bit mask 3579 Known = Known.trunc(EltBitWidth); 3580 break; 3581 } 3582 case ISD::EXTRACT_VECTOR_ELT: { 3583 SDValue InVec = Op.getOperand(0); 3584 SDValue EltNo = Op.getOperand(1); 3585 EVT VecVT = InVec.getValueType(); 3586 // computeKnownBits not yet implemented for scalable vectors. 3587 if (VecVT.isScalableVector()) 3588 break; 3589 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3590 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3591 3592 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3593 // anything about the extended bits. 3594 if (BitWidth > EltBitWidth) 3595 Known = Known.trunc(EltBitWidth); 3596 3597 // If we know the element index, just demand that vector element, else for 3598 // an unknown element index, ignore DemandedElts and demand them all. 3599 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 3600 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3601 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3602 DemandedSrcElts = 3603 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3604 3605 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3606 if (BitWidth > EltBitWidth) 3607 Known = Known.anyext(BitWidth); 3608 break; 3609 } 3610 case ISD::INSERT_VECTOR_ELT: { 3611 // If we know the element index, split the demand between the 3612 // source vector and the inserted element, otherwise assume we need 3613 // the original demanded vector elements and the value. 3614 SDValue InVec = Op.getOperand(0); 3615 SDValue InVal = Op.getOperand(1); 3616 SDValue EltNo = Op.getOperand(2); 3617 bool DemandedVal = true; 3618 APInt DemandedVecElts = DemandedElts; 3619 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3620 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3621 unsigned EltIdx = CEltNo->getZExtValue(); 3622 DemandedVal = !!DemandedElts[EltIdx]; 3623 DemandedVecElts.clearBit(EltIdx); 3624 } 3625 Known.One.setAllBits(); 3626 Known.Zero.setAllBits(); 3627 if (DemandedVal) { 3628 Known2 = computeKnownBits(InVal, Depth + 1); 3629 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3630 } 3631 if (!!DemandedVecElts) { 3632 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3633 Known = KnownBits::commonBits(Known, Known2); 3634 } 3635 break; 3636 } 3637 case ISD::BITREVERSE: { 3638 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3639 Known = Known2.reverseBits(); 3640 break; 3641 } 3642 case ISD::BSWAP: { 3643 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3644 Known = Known2.byteSwap(); 3645 break; 3646 } 3647 case ISD::ABS: { 3648 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3649 Known = Known2.abs(); 3650 break; 3651 } 3652 case ISD::USUBSAT: { 3653 // The result of usubsat will never be larger than the LHS. 3654 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3655 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3656 break; 3657 } 3658 case ISD::UMIN: { 3659 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3660 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3661 Known = KnownBits::umin(Known, Known2); 3662 break; 3663 } 3664 case ISD::UMAX: { 3665 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3666 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3667 Known = KnownBits::umax(Known, Known2); 3668 break; 3669 } 3670 case ISD::SMIN: 3671 case ISD::SMAX: { 3672 // If we have a clamp pattern, we know that the number of sign bits will be 3673 // the minimum of the clamp min/max range. 3674 bool IsMax = (Opcode == ISD::SMAX); 3675 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3676 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3677 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3678 CstHigh = 3679 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3680 if (CstLow && CstHigh) { 3681 if (!IsMax) 3682 std::swap(CstLow, CstHigh); 3683 3684 const APInt &ValueLow = CstLow->getAPIntValue(); 3685 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3686 if (ValueLow.sle(ValueHigh)) { 3687 unsigned LowSignBits = ValueLow.getNumSignBits(); 3688 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3689 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3690 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3691 Known.One.setHighBits(MinSignBits); 3692 break; 3693 } 3694 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3695 Known.Zero.setHighBits(MinSignBits); 3696 break; 3697 } 3698 } 3699 } 3700 3701 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3702 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3703 if (IsMax) 3704 Known = KnownBits::smax(Known, Known2); 3705 else 3706 Known = KnownBits::smin(Known, Known2); 3707 break; 3708 } 3709 case ISD::FP_TO_UINT_SAT: { 3710 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT. 3711 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3712 Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits()); 3713 break; 3714 } 3715 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3716 if (Op.getResNo() == 1) { 3717 // The boolean result conforms to getBooleanContents. 3718 // If we know the result of a setcc has the top bits zero, use this info. 3719 // We know that we have an integer-based boolean since these operations 3720 // are only available for integer. 3721 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3722 TargetLowering::ZeroOrOneBooleanContent && 3723 BitWidth > 1) 3724 Known.Zero.setBitsFrom(1); 3725 break; 3726 } 3727 LLVM_FALLTHROUGH; 3728 case ISD::ATOMIC_CMP_SWAP: 3729 case ISD::ATOMIC_SWAP: 3730 case ISD::ATOMIC_LOAD_ADD: 3731 case ISD::ATOMIC_LOAD_SUB: 3732 case ISD::ATOMIC_LOAD_AND: 3733 case ISD::ATOMIC_LOAD_CLR: 3734 case ISD::ATOMIC_LOAD_OR: 3735 case ISD::ATOMIC_LOAD_XOR: 3736 case ISD::ATOMIC_LOAD_NAND: 3737 case ISD::ATOMIC_LOAD_MIN: 3738 case ISD::ATOMIC_LOAD_MAX: 3739 case ISD::ATOMIC_LOAD_UMIN: 3740 case ISD::ATOMIC_LOAD_UMAX: 3741 case ISD::ATOMIC_LOAD: { 3742 unsigned MemBits = 3743 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 3744 // If we are looking at the loaded value. 3745 if (Op.getResNo() == 0) { 3746 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 3747 Known.Zero.setBitsFrom(MemBits); 3748 } 3749 break; 3750 } 3751 case ISD::FrameIndex: 3752 case ISD::TargetFrameIndex: 3753 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3754 Known, getMachineFunction()); 3755 break; 3756 3757 default: 3758 if (Opcode < ISD::BUILTIN_OP_END) 3759 break; 3760 LLVM_FALLTHROUGH; 3761 case ISD::INTRINSIC_WO_CHAIN: 3762 case ISD::INTRINSIC_W_CHAIN: 3763 case ISD::INTRINSIC_VOID: 3764 // Allow the target to implement this method for its nodes. 3765 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3766 break; 3767 } 3768 3769 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3770 return Known; 3771 } 3772 3773 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3774 SDValue N1) const { 3775 // X + 0 never overflow 3776 if (isNullConstant(N1)) 3777 return OFK_Never; 3778 3779 KnownBits N1Known = computeKnownBits(N1); 3780 if (N1Known.Zero.getBoolValue()) { 3781 KnownBits N0Known = computeKnownBits(N0); 3782 3783 bool overflow; 3784 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3785 if (!overflow) 3786 return OFK_Never; 3787 } 3788 3789 // mulhi + 1 never overflow 3790 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3791 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3792 return OFK_Never; 3793 3794 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3795 KnownBits N0Known = computeKnownBits(N0); 3796 3797 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3798 return OFK_Never; 3799 } 3800 3801 return OFK_Sometime; 3802 } 3803 3804 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3805 EVT OpVT = Val.getValueType(); 3806 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3807 3808 // Is the constant a known power of 2? 3809 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3810 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3811 3812 // A left-shift of a constant one will have exactly one bit set because 3813 // shifting the bit off the end is undefined. 3814 if (Val.getOpcode() == ISD::SHL) { 3815 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3816 if (C && C->getAPIntValue() == 1) 3817 return true; 3818 } 3819 3820 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3821 // one bit set. 3822 if (Val.getOpcode() == ISD::SRL) { 3823 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3824 if (C && C->getAPIntValue().isSignMask()) 3825 return true; 3826 } 3827 3828 // Are all operands of a build vector constant powers of two? 3829 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3830 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3831 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3832 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3833 return false; 3834 })) 3835 return true; 3836 3837 // Is the operand of a splat vector a constant power of two? 3838 if (Val.getOpcode() == ISD::SPLAT_VECTOR) 3839 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0))) 3840 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2()) 3841 return true; 3842 3843 // More could be done here, though the above checks are enough 3844 // to handle some common cases. 3845 3846 // Fall back to computeKnownBits to catch other known cases. 3847 KnownBits Known = computeKnownBits(Val); 3848 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3849 } 3850 3851 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3852 EVT VT = Op.getValueType(); 3853 3854 // TODO: Assume we don't know anything for now. 3855 if (VT.isScalableVector()) 3856 return 1; 3857 3858 APInt DemandedElts = VT.isVector() 3859 ? APInt::getAllOnes(VT.getVectorNumElements()) 3860 : APInt(1, 1); 3861 return ComputeNumSignBits(Op, DemandedElts, Depth); 3862 } 3863 3864 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3865 unsigned Depth) const { 3866 EVT VT = Op.getValueType(); 3867 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3868 unsigned VTBits = VT.getScalarSizeInBits(); 3869 unsigned NumElts = DemandedElts.getBitWidth(); 3870 unsigned Tmp, Tmp2; 3871 unsigned FirstAnswer = 1; 3872 3873 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3874 const APInt &Val = C->getAPIntValue(); 3875 return Val.getNumSignBits(); 3876 } 3877 3878 if (Depth >= MaxRecursionDepth) 3879 return 1; // Limit search depth. 3880 3881 if (!DemandedElts || VT.isScalableVector()) 3882 return 1; // No demanded elts, better to assume we don't know anything. 3883 3884 unsigned Opcode = Op.getOpcode(); 3885 switch (Opcode) { 3886 default: break; 3887 case ISD::AssertSext: 3888 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3889 return VTBits-Tmp+1; 3890 case ISD::AssertZext: 3891 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3892 return VTBits-Tmp; 3893 3894 case ISD::BUILD_VECTOR: 3895 Tmp = VTBits; 3896 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3897 if (!DemandedElts[i]) 3898 continue; 3899 3900 SDValue SrcOp = Op.getOperand(i); 3901 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3902 3903 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3904 if (SrcOp.getValueSizeInBits() != VTBits) { 3905 assert(SrcOp.getValueSizeInBits() > VTBits && 3906 "Expected BUILD_VECTOR implicit truncation"); 3907 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3908 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3909 } 3910 Tmp = std::min(Tmp, Tmp2); 3911 } 3912 return Tmp; 3913 3914 case ISD::VECTOR_SHUFFLE: { 3915 // Collect the minimum number of sign bits that are shared by every vector 3916 // element referenced by the shuffle. 3917 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3918 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3919 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3920 for (unsigned i = 0; i != NumElts; ++i) { 3921 int M = SVN->getMaskElt(i); 3922 if (!DemandedElts[i]) 3923 continue; 3924 // For UNDEF elements, we don't know anything about the common state of 3925 // the shuffle result. 3926 if (M < 0) 3927 return 1; 3928 if ((unsigned)M < NumElts) 3929 DemandedLHS.setBit((unsigned)M % NumElts); 3930 else 3931 DemandedRHS.setBit((unsigned)M % NumElts); 3932 } 3933 Tmp = std::numeric_limits<unsigned>::max(); 3934 if (!!DemandedLHS) 3935 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 3936 if (!!DemandedRHS) { 3937 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 3938 Tmp = std::min(Tmp, Tmp2); 3939 } 3940 // If we don't know anything, early out and try computeKnownBits fall-back. 3941 if (Tmp == 1) 3942 break; 3943 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3944 return Tmp; 3945 } 3946 3947 case ISD::BITCAST: { 3948 SDValue N0 = Op.getOperand(0); 3949 EVT SrcVT = N0.getValueType(); 3950 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 3951 3952 // Ignore bitcasts from unsupported types.. 3953 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 3954 break; 3955 3956 // Fast handling of 'identity' bitcasts. 3957 if (VTBits == SrcBits) 3958 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 3959 3960 bool IsLE = getDataLayout().isLittleEndian(); 3961 3962 // Bitcast 'large element' scalar/vector to 'small element' vector. 3963 if ((SrcBits % VTBits) == 0) { 3964 assert(VT.isVector() && "Expected bitcast to vector"); 3965 3966 unsigned Scale = SrcBits / VTBits; 3967 APInt SrcDemandedElts = 3968 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale); 3969 3970 // Fast case - sign splat can be simply split across the small elements. 3971 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 3972 if (Tmp == SrcBits) 3973 return VTBits; 3974 3975 // Slow case - determine how far the sign extends into each sub-element. 3976 Tmp2 = VTBits; 3977 for (unsigned i = 0; i != NumElts; ++i) 3978 if (DemandedElts[i]) { 3979 unsigned SubOffset = i % Scale; 3980 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 3981 SubOffset = SubOffset * VTBits; 3982 if (Tmp <= SubOffset) 3983 return 1; 3984 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 3985 } 3986 return Tmp2; 3987 } 3988 break; 3989 } 3990 3991 case ISD::FP_TO_SINT_SAT: 3992 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT. 3993 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3994 return VTBits - Tmp + 1; 3995 case ISD::SIGN_EXTEND: 3996 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 3997 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 3998 case ISD::SIGN_EXTEND_INREG: 3999 // Max of the input and what this extends. 4000 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 4001 Tmp = VTBits-Tmp+1; 4002 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4003 return std::max(Tmp, Tmp2); 4004 case ISD::SIGN_EXTEND_VECTOR_INREG: { 4005 SDValue Src = Op.getOperand(0); 4006 EVT SrcVT = Src.getValueType(); 4007 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements()); 4008 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 4009 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 4010 } 4011 case ISD::SRA: 4012 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4013 // SRA X, C -> adds C sign bits. 4014 if (const APInt *ShAmt = 4015 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 4016 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 4017 return Tmp; 4018 case ISD::SHL: 4019 if (const APInt *ShAmt = 4020 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 4021 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 4022 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4023 if (ShAmt->ult(Tmp)) 4024 return Tmp - ShAmt->getZExtValue(); 4025 } 4026 break; 4027 case ISD::AND: 4028 case ISD::OR: 4029 case ISD::XOR: // NOT is handled here. 4030 // Logical binary ops preserve the number of sign bits at the worst. 4031 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4032 if (Tmp != 1) { 4033 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4034 FirstAnswer = std::min(Tmp, Tmp2); 4035 // We computed what we know about the sign bits as our first 4036 // answer. Now proceed to the generic code that uses 4037 // computeKnownBits, and pick whichever answer is better. 4038 } 4039 break; 4040 4041 case ISD::SELECT: 4042 case ISD::VSELECT: 4043 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4044 if (Tmp == 1) return 1; // Early out. 4045 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4046 return std::min(Tmp, Tmp2); 4047 case ISD::SELECT_CC: 4048 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4049 if (Tmp == 1) return 1; // Early out. 4050 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 4051 return std::min(Tmp, Tmp2); 4052 4053 case ISD::SMIN: 4054 case ISD::SMAX: { 4055 // If we have a clamp pattern, we know that the number of sign bits will be 4056 // the minimum of the clamp min/max range. 4057 bool IsMax = (Opcode == ISD::SMAX); 4058 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 4059 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 4060 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 4061 CstHigh = 4062 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 4063 if (CstLow && CstHigh) { 4064 if (!IsMax) 4065 std::swap(CstLow, CstHigh); 4066 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 4067 Tmp = CstLow->getAPIntValue().getNumSignBits(); 4068 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 4069 return std::min(Tmp, Tmp2); 4070 } 4071 } 4072 4073 // Fallback - just get the minimum number of sign bits of the operands. 4074 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4075 if (Tmp == 1) 4076 return 1; // Early out. 4077 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4078 return std::min(Tmp, Tmp2); 4079 } 4080 case ISD::UMIN: 4081 case ISD::UMAX: 4082 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4083 if (Tmp == 1) 4084 return 1; // Early out. 4085 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4086 return std::min(Tmp, Tmp2); 4087 case ISD::SADDO: 4088 case ISD::UADDO: 4089 case ISD::SSUBO: 4090 case ISD::USUBO: 4091 case ISD::SMULO: 4092 case ISD::UMULO: 4093 if (Op.getResNo() != 1) 4094 break; 4095 // The boolean result conforms to getBooleanContents. Fall through. 4096 // If setcc returns 0/-1, all bits are sign bits. 4097 // We know that we have an integer-based boolean since these operations 4098 // are only available for integer. 4099 if (TLI->getBooleanContents(VT.isVector(), false) == 4100 TargetLowering::ZeroOrNegativeOneBooleanContent) 4101 return VTBits; 4102 break; 4103 case ISD::SETCC: 4104 case ISD::STRICT_FSETCC: 4105 case ISD::STRICT_FSETCCS: { 4106 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 4107 // If setcc returns 0/-1, all bits are sign bits. 4108 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 4109 TargetLowering::ZeroOrNegativeOneBooleanContent) 4110 return VTBits; 4111 break; 4112 } 4113 case ISD::ROTL: 4114 case ISD::ROTR: 4115 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4116 4117 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 4118 if (Tmp == VTBits) 4119 return VTBits; 4120 4121 if (ConstantSDNode *C = 4122 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 4123 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 4124 4125 // Handle rotate right by N like a rotate left by 32-N. 4126 if (Opcode == ISD::ROTR) 4127 RotAmt = (VTBits - RotAmt) % VTBits; 4128 4129 // If we aren't rotating out all of the known-in sign bits, return the 4130 // number that are left. This handles rotl(sext(x), 1) for example. 4131 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 4132 } 4133 break; 4134 case ISD::ADD: 4135 case ISD::ADDC: 4136 // Add can have at most one carry bit. Thus we know that the output 4137 // is, at worst, one more bit than the inputs. 4138 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4139 if (Tmp == 1) return 1; // Early out. 4140 4141 // Special case decrementing a value (ADD X, -1): 4142 if (ConstantSDNode *CRHS = 4143 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 4144 if (CRHS->isAllOnes()) { 4145 KnownBits Known = 4146 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 4147 4148 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4149 // sign bits set. 4150 if ((Known.Zero | 1).isAllOnes()) 4151 return VTBits; 4152 4153 // If we are subtracting one from a positive number, there is no carry 4154 // out of the result. 4155 if (Known.isNonNegative()) 4156 return Tmp; 4157 } 4158 4159 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4160 if (Tmp2 == 1) return 1; // Early out. 4161 return std::min(Tmp, Tmp2) - 1; 4162 case ISD::SUB: 4163 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4164 if (Tmp2 == 1) return 1; // Early out. 4165 4166 // Handle NEG. 4167 if (ConstantSDNode *CLHS = 4168 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 4169 if (CLHS->isZero()) { 4170 KnownBits Known = 4171 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 4172 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4173 // sign bits set. 4174 if ((Known.Zero | 1).isAllOnes()) 4175 return VTBits; 4176 4177 // If the input is known to be positive (the sign bit is known clear), 4178 // the output of the NEG has the same number of sign bits as the input. 4179 if (Known.isNonNegative()) 4180 return Tmp2; 4181 4182 // Otherwise, we treat this like a SUB. 4183 } 4184 4185 // Sub can have at most one carry bit. Thus we know that the output 4186 // is, at worst, one more bit than the inputs. 4187 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4188 if (Tmp == 1) return 1; // Early out. 4189 return std::min(Tmp, Tmp2) - 1; 4190 case ISD::MUL: { 4191 // The output of the Mul can be at most twice the valid bits in the inputs. 4192 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4193 if (SignBitsOp0 == 1) 4194 break; 4195 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 4196 if (SignBitsOp1 == 1) 4197 break; 4198 unsigned OutValidBits = 4199 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 4200 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 4201 } 4202 case ISD::SREM: 4203 // The sign bit is the LHS's sign bit, except when the result of the 4204 // remainder is zero. The magnitude of the result should be less than or 4205 // equal to the magnitude of the LHS. Therefore, the result should have 4206 // at least as many sign bits as the left hand side. 4207 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4208 case ISD::TRUNCATE: { 4209 // Check if the sign bits of source go down as far as the truncated value. 4210 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 4211 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4212 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4213 return NumSrcSignBits - (NumSrcBits - VTBits); 4214 break; 4215 } 4216 case ISD::EXTRACT_ELEMENT: { 4217 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 4218 const int BitWidth = Op.getValueSizeInBits(); 4219 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 4220 4221 // Get reverse index (starting from 1), Op1 value indexes elements from 4222 // little end. Sign starts at big end. 4223 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 4224 4225 // If the sign portion ends in our element the subtraction gives correct 4226 // result. Otherwise it gives either negative or > bitwidth result 4227 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 4228 } 4229 case ISD::INSERT_VECTOR_ELT: { 4230 // If we know the element index, split the demand between the 4231 // source vector and the inserted element, otherwise assume we need 4232 // the original demanded vector elements and the value. 4233 SDValue InVec = Op.getOperand(0); 4234 SDValue InVal = Op.getOperand(1); 4235 SDValue EltNo = Op.getOperand(2); 4236 bool DemandedVal = true; 4237 APInt DemandedVecElts = DemandedElts; 4238 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 4239 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 4240 unsigned EltIdx = CEltNo->getZExtValue(); 4241 DemandedVal = !!DemandedElts[EltIdx]; 4242 DemandedVecElts.clearBit(EltIdx); 4243 } 4244 Tmp = std::numeric_limits<unsigned>::max(); 4245 if (DemandedVal) { 4246 // TODO - handle implicit truncation of inserted elements. 4247 if (InVal.getScalarValueSizeInBits() != VTBits) 4248 break; 4249 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4250 Tmp = std::min(Tmp, Tmp2); 4251 } 4252 if (!!DemandedVecElts) { 4253 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 4254 Tmp = std::min(Tmp, Tmp2); 4255 } 4256 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4257 return Tmp; 4258 } 4259 case ISD::EXTRACT_VECTOR_ELT: { 4260 SDValue InVec = Op.getOperand(0); 4261 SDValue EltNo = Op.getOperand(1); 4262 EVT VecVT = InVec.getValueType(); 4263 // ComputeNumSignBits not yet implemented for scalable vectors. 4264 if (VecVT.isScalableVector()) 4265 break; 4266 const unsigned BitWidth = Op.getValueSizeInBits(); 4267 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4268 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4269 4270 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4271 // anything about sign bits. But if the sizes match we can derive knowledge 4272 // about sign bits from the vector operand. 4273 if (BitWidth != EltBitWidth) 4274 break; 4275 4276 // If we know the element index, just demand that vector element, else for 4277 // an unknown element index, ignore DemandedElts and demand them all. 4278 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 4279 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4280 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4281 DemandedSrcElts = 4282 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4283 4284 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4285 } 4286 case ISD::EXTRACT_SUBVECTOR: { 4287 // Offset the demanded elts by the subvector index. 4288 SDValue Src = Op.getOperand(0); 4289 // Bail until we can represent demanded elements for scalable vectors. 4290 if (Src.getValueType().isScalableVector()) 4291 break; 4292 uint64_t Idx = Op.getConstantOperandVal(1); 4293 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4294 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 4295 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4296 } 4297 case ISD::CONCAT_VECTORS: { 4298 // Determine the minimum number of sign bits across all demanded 4299 // elts of the input vectors. Early out if the result is already 1. 4300 Tmp = std::numeric_limits<unsigned>::max(); 4301 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4302 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4303 unsigned NumSubVectors = Op.getNumOperands(); 4304 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4305 APInt DemandedSub = 4306 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 4307 if (!DemandedSub) 4308 continue; 4309 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4310 Tmp = std::min(Tmp, Tmp2); 4311 } 4312 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4313 return Tmp; 4314 } 4315 case ISD::INSERT_SUBVECTOR: { 4316 // Demand any elements from the subvector and the remainder from the src its 4317 // inserted into. 4318 SDValue Src = Op.getOperand(0); 4319 SDValue Sub = Op.getOperand(1); 4320 uint64_t Idx = Op.getConstantOperandVal(2); 4321 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4322 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4323 APInt DemandedSrcElts = DemandedElts; 4324 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 4325 4326 Tmp = std::numeric_limits<unsigned>::max(); 4327 if (!!DemandedSubElts) { 4328 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4329 if (Tmp == 1) 4330 return 1; // early-out 4331 } 4332 if (!!DemandedSrcElts) { 4333 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4334 Tmp = std::min(Tmp, Tmp2); 4335 } 4336 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4337 return Tmp; 4338 } 4339 case ISD::ATOMIC_CMP_SWAP: 4340 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4341 case ISD::ATOMIC_SWAP: 4342 case ISD::ATOMIC_LOAD_ADD: 4343 case ISD::ATOMIC_LOAD_SUB: 4344 case ISD::ATOMIC_LOAD_AND: 4345 case ISD::ATOMIC_LOAD_CLR: 4346 case ISD::ATOMIC_LOAD_OR: 4347 case ISD::ATOMIC_LOAD_XOR: 4348 case ISD::ATOMIC_LOAD_NAND: 4349 case ISD::ATOMIC_LOAD_MIN: 4350 case ISD::ATOMIC_LOAD_MAX: 4351 case ISD::ATOMIC_LOAD_UMIN: 4352 case ISD::ATOMIC_LOAD_UMAX: 4353 case ISD::ATOMIC_LOAD: { 4354 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4355 // If we are looking at the loaded value. 4356 if (Op.getResNo() == 0) { 4357 if (Tmp == VTBits) 4358 return 1; // early-out 4359 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND) 4360 return VTBits - Tmp + 1; 4361 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4362 return VTBits - Tmp; 4363 } 4364 break; 4365 } 4366 } 4367 4368 // If we are looking at the loaded value of the SDNode. 4369 if (Op.getResNo() == 0) { 4370 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4371 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4372 unsigned ExtType = LD->getExtensionType(); 4373 switch (ExtType) { 4374 default: break; 4375 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4376 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4377 return VTBits - Tmp + 1; 4378 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4379 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4380 return VTBits - Tmp; 4381 case ISD::NON_EXTLOAD: 4382 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4383 // We only need to handle vectors - computeKnownBits should handle 4384 // scalar cases. 4385 Type *CstTy = Cst->getType(); 4386 if (CstTy->isVectorTy() && 4387 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() && 4388 VTBits == CstTy->getScalarSizeInBits()) { 4389 Tmp = VTBits; 4390 for (unsigned i = 0; i != NumElts; ++i) { 4391 if (!DemandedElts[i]) 4392 continue; 4393 if (Constant *Elt = Cst->getAggregateElement(i)) { 4394 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4395 const APInt &Value = CInt->getValue(); 4396 Tmp = std::min(Tmp, Value.getNumSignBits()); 4397 continue; 4398 } 4399 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4400 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4401 Tmp = std::min(Tmp, Value.getNumSignBits()); 4402 continue; 4403 } 4404 } 4405 // Unknown type. Conservatively assume no bits match sign bit. 4406 return 1; 4407 } 4408 return Tmp; 4409 } 4410 } 4411 break; 4412 } 4413 } 4414 } 4415 4416 // Allow the target to implement this method for its nodes. 4417 if (Opcode >= ISD::BUILTIN_OP_END || 4418 Opcode == ISD::INTRINSIC_WO_CHAIN || 4419 Opcode == ISD::INTRINSIC_W_CHAIN || 4420 Opcode == ISD::INTRINSIC_VOID) { 4421 unsigned NumBits = 4422 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4423 if (NumBits > 1) 4424 FirstAnswer = std::max(FirstAnswer, NumBits); 4425 } 4426 4427 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4428 // use this information. 4429 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4430 return std::max(FirstAnswer, Known.countMinSignBits()); 4431 } 4432 4433 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4434 unsigned Depth) const { 4435 unsigned SignBits = ComputeNumSignBits(Op, Depth); 4436 return Op.getScalarValueSizeInBits() - SignBits + 1; 4437 } 4438 4439 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4440 const APInt &DemandedElts, 4441 unsigned Depth) const { 4442 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth); 4443 return Op.getScalarValueSizeInBits() - SignBits + 1; 4444 } 4445 4446 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly, 4447 unsigned Depth) const { 4448 // Early out for FREEZE. 4449 if (Op.getOpcode() == ISD::FREEZE) 4450 return true; 4451 4452 // TODO: Assume we don't know anything for now. 4453 EVT VT = Op.getValueType(); 4454 if (VT.isScalableVector()) 4455 return false; 4456 4457 APInt DemandedElts = VT.isVector() 4458 ? APInt::getAllOnes(VT.getVectorNumElements()) 4459 : APInt(1, 1); 4460 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth); 4461 } 4462 4463 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, 4464 const APInt &DemandedElts, 4465 bool PoisonOnly, 4466 unsigned Depth) const { 4467 unsigned Opcode = Op.getOpcode(); 4468 4469 // Early out for FREEZE. 4470 if (Opcode == ISD::FREEZE) 4471 return true; 4472 4473 if (Depth >= MaxRecursionDepth) 4474 return false; // Limit search depth. 4475 4476 if (isIntOrFPConstant(Op)) 4477 return true; 4478 4479 switch (Opcode) { 4480 case ISD::UNDEF: 4481 return PoisonOnly; 4482 4483 case ISD::BUILD_VECTOR: 4484 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements - 4485 // this shouldn't affect the result. 4486 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) { 4487 if (!DemandedElts[i]) 4488 continue; 4489 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly, 4490 Depth + 1)) 4491 return false; 4492 } 4493 return true; 4494 4495 // TODO: Search for noundef attributes from library functions. 4496 4497 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef. 4498 4499 default: 4500 // Allow the target to implement this method for its nodes. 4501 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 4502 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 4503 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode( 4504 Op, DemandedElts, *this, PoisonOnly, Depth); 4505 break; 4506 } 4507 4508 return false; 4509 } 4510 4511 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4512 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4513 !isa<ConstantSDNode>(Op.getOperand(1))) 4514 return false; 4515 4516 if (Op.getOpcode() == ISD::OR && 4517 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4518 return false; 4519 4520 return true; 4521 } 4522 4523 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4524 // If we're told that NaNs won't happen, assume they won't. 4525 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4526 return true; 4527 4528 if (Depth >= MaxRecursionDepth) 4529 return false; // Limit search depth. 4530 4531 // TODO: Handle vectors. 4532 // If the value is a constant, we can obviously see if it is a NaN or not. 4533 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4534 return !C->getValueAPF().isNaN() || 4535 (SNaN && !C->getValueAPF().isSignaling()); 4536 } 4537 4538 unsigned Opcode = Op.getOpcode(); 4539 switch (Opcode) { 4540 case ISD::FADD: 4541 case ISD::FSUB: 4542 case ISD::FMUL: 4543 case ISD::FDIV: 4544 case ISD::FREM: 4545 case ISD::FSIN: 4546 case ISD::FCOS: { 4547 if (SNaN) 4548 return true; 4549 // TODO: Need isKnownNeverInfinity 4550 return false; 4551 } 4552 case ISD::FCANONICALIZE: 4553 case ISD::FEXP: 4554 case ISD::FEXP2: 4555 case ISD::FTRUNC: 4556 case ISD::FFLOOR: 4557 case ISD::FCEIL: 4558 case ISD::FROUND: 4559 case ISD::FROUNDEVEN: 4560 case ISD::FRINT: 4561 case ISD::FNEARBYINT: { 4562 if (SNaN) 4563 return true; 4564 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4565 } 4566 case ISD::FABS: 4567 case ISD::FNEG: 4568 case ISD::FCOPYSIGN: { 4569 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4570 } 4571 case ISD::SELECT: 4572 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4573 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4574 case ISD::FP_EXTEND: 4575 case ISD::FP_ROUND: { 4576 if (SNaN) 4577 return true; 4578 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4579 } 4580 case ISD::SINT_TO_FP: 4581 case ISD::UINT_TO_FP: 4582 return true; 4583 case ISD::FMA: 4584 case ISD::FMAD: { 4585 if (SNaN) 4586 return true; 4587 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4588 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4589 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4590 } 4591 case ISD::FSQRT: // Need is known positive 4592 case ISD::FLOG: 4593 case ISD::FLOG2: 4594 case ISD::FLOG10: 4595 case ISD::FPOWI: 4596 case ISD::FPOW: { 4597 if (SNaN) 4598 return true; 4599 // TODO: Refine on operand 4600 return false; 4601 } 4602 case ISD::FMINNUM: 4603 case ISD::FMAXNUM: { 4604 // Only one needs to be known not-nan, since it will be returned if the 4605 // other ends up being one. 4606 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4607 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4608 } 4609 case ISD::FMINNUM_IEEE: 4610 case ISD::FMAXNUM_IEEE: { 4611 if (SNaN) 4612 return true; 4613 // This can return a NaN if either operand is an sNaN, or if both operands 4614 // are NaN. 4615 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4616 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4617 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4618 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4619 } 4620 case ISD::FMINIMUM: 4621 case ISD::FMAXIMUM: { 4622 // TODO: Does this quiet or return the origina NaN as-is? 4623 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4624 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4625 } 4626 case ISD::EXTRACT_VECTOR_ELT: { 4627 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4628 } 4629 default: 4630 if (Opcode >= ISD::BUILTIN_OP_END || 4631 Opcode == ISD::INTRINSIC_WO_CHAIN || 4632 Opcode == ISD::INTRINSIC_W_CHAIN || 4633 Opcode == ISD::INTRINSIC_VOID) { 4634 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4635 } 4636 4637 return false; 4638 } 4639 } 4640 4641 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4642 assert(Op.getValueType().isFloatingPoint() && 4643 "Floating point type expected"); 4644 4645 // If the value is a constant, we can obviously see if it is a zero or not. 4646 // TODO: Add BuildVector support. 4647 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4648 return !C->isZero(); 4649 return false; 4650 } 4651 4652 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4653 assert(!Op.getValueType().isFloatingPoint() && 4654 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4655 4656 // If the value is a constant, we can obviously see if it is a zero or not. 4657 if (ISD::matchUnaryPredicate(Op, 4658 [](ConstantSDNode *C) { return !C->isZero(); })) 4659 return true; 4660 4661 // TODO: Recognize more cases here. 4662 switch (Op.getOpcode()) { 4663 default: break; 4664 case ISD::OR: 4665 if (isKnownNeverZero(Op.getOperand(1)) || 4666 isKnownNeverZero(Op.getOperand(0))) 4667 return true; 4668 break; 4669 } 4670 4671 return false; 4672 } 4673 4674 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4675 // Check the obvious case. 4676 if (A == B) return true; 4677 4678 // For for negative and positive zero. 4679 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4680 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4681 if (CA->isZero() && CB->isZero()) return true; 4682 4683 // Otherwise they may not be equal. 4684 return false; 4685 } 4686 4687 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) { 4688 // Match masked merge pattern (X & ~M) op (Y & M) 4689 // Including degenerate case (X & ~M) op M 4690 auto MatchNoCommonBitsPattern = [&](SDValue NotM, SDValue Other) { 4691 if (isBitwiseNot(NotM, true)) { 4692 SDValue NotOperand = NotM->getOperand(0); 4693 if (Other == NotOperand) 4694 return true; 4695 if (Other->getOpcode() == ISD::AND) 4696 return NotOperand == Other->getOperand(0) || 4697 NotOperand == Other->getOperand(1); 4698 } 4699 return false; 4700 }; 4701 if (A->getOpcode() == ISD::AND) 4702 return MatchNoCommonBitsPattern(A->getOperand(0), B) || 4703 MatchNoCommonBitsPattern(A->getOperand(1), B); 4704 return false; 4705 } 4706 4707 // FIXME: unify with llvm::haveNoCommonBitsSet. 4708 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4709 assert(A.getValueType() == B.getValueType() && 4710 "Values must have the same type"); 4711 if (haveNoCommonBitsSetCommutative(A, B) || 4712 haveNoCommonBitsSetCommutative(B, A)) 4713 return true; 4714 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A), 4715 computeKnownBits(B)); 4716 } 4717 4718 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 4719 SelectionDAG &DAG) { 4720 if (cast<ConstantSDNode>(Step)->isZero()) 4721 return DAG.getConstant(0, DL, VT); 4722 4723 return SDValue(); 4724 } 4725 4726 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4727 ArrayRef<SDValue> Ops, 4728 SelectionDAG &DAG) { 4729 int NumOps = Ops.size(); 4730 assert(NumOps != 0 && "Can't build an empty vector!"); 4731 assert(!VT.isScalableVector() && 4732 "BUILD_VECTOR cannot be used with scalable types"); 4733 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4734 "Incorrect element count in BUILD_VECTOR!"); 4735 4736 // BUILD_VECTOR of UNDEFs is UNDEF. 4737 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4738 return DAG.getUNDEF(VT); 4739 4740 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4741 SDValue IdentitySrc; 4742 bool IsIdentity = true; 4743 for (int i = 0; i != NumOps; ++i) { 4744 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4745 Ops[i].getOperand(0).getValueType() != VT || 4746 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4747 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4748 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4749 IsIdentity = false; 4750 break; 4751 } 4752 IdentitySrc = Ops[i].getOperand(0); 4753 } 4754 if (IsIdentity) 4755 return IdentitySrc; 4756 4757 return SDValue(); 4758 } 4759 4760 /// Try to simplify vector concatenation to an input value, undef, or build 4761 /// vector. 4762 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4763 ArrayRef<SDValue> Ops, 4764 SelectionDAG &DAG) { 4765 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4766 assert(llvm::all_of(Ops, 4767 [Ops](SDValue Op) { 4768 return Ops[0].getValueType() == Op.getValueType(); 4769 }) && 4770 "Concatenation of vectors with inconsistent value types!"); 4771 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4772 VT.getVectorElementCount() && 4773 "Incorrect element count in vector concatenation!"); 4774 4775 if (Ops.size() == 1) 4776 return Ops[0]; 4777 4778 // Concat of UNDEFs is UNDEF. 4779 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4780 return DAG.getUNDEF(VT); 4781 4782 // Scan the operands and look for extract operations from a single source 4783 // that correspond to insertion at the same location via this concatenation: 4784 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4785 SDValue IdentitySrc; 4786 bool IsIdentity = true; 4787 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4788 SDValue Op = Ops[i]; 4789 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4790 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4791 Op.getOperand(0).getValueType() != VT || 4792 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4793 Op.getConstantOperandVal(1) != IdentityIndex) { 4794 IsIdentity = false; 4795 break; 4796 } 4797 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4798 "Unexpected identity source vector for concat of extracts"); 4799 IdentitySrc = Op.getOperand(0); 4800 } 4801 if (IsIdentity) { 4802 assert(IdentitySrc && "Failed to set source vector of extracts"); 4803 return IdentitySrc; 4804 } 4805 4806 // The code below this point is only designed to work for fixed width 4807 // vectors, so we bail out for now. 4808 if (VT.isScalableVector()) 4809 return SDValue(); 4810 4811 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4812 // simplified to one big BUILD_VECTOR. 4813 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4814 EVT SVT = VT.getScalarType(); 4815 SmallVector<SDValue, 16> Elts; 4816 for (SDValue Op : Ops) { 4817 EVT OpVT = Op.getValueType(); 4818 if (Op.isUndef()) 4819 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4820 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4821 Elts.append(Op->op_begin(), Op->op_end()); 4822 else 4823 return SDValue(); 4824 } 4825 4826 // BUILD_VECTOR requires all inputs to be of the same type, find the 4827 // maximum type and extend them all. 4828 for (SDValue Op : Elts) 4829 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4830 4831 if (SVT.bitsGT(VT.getScalarType())) { 4832 for (SDValue &Op : Elts) { 4833 if (Op.isUndef()) 4834 Op = DAG.getUNDEF(SVT); 4835 else 4836 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4837 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4838 : DAG.getSExtOrTrunc(Op, DL, SVT); 4839 } 4840 } 4841 4842 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4843 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4844 return V; 4845 } 4846 4847 /// Gets or creates the specified node. 4848 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4849 FoldingSetNodeID ID; 4850 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4851 void *IP = nullptr; 4852 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4853 return SDValue(E, 0); 4854 4855 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4856 getVTList(VT)); 4857 CSEMap.InsertNode(N, IP); 4858 4859 InsertNode(N); 4860 SDValue V = SDValue(N, 0); 4861 NewSDValueDbgMsg(V, "Creating new node: ", this); 4862 return V; 4863 } 4864 4865 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4866 SDValue Operand) { 4867 SDNodeFlags Flags; 4868 if (Inserter) 4869 Flags = Inserter->getFlags(); 4870 return getNode(Opcode, DL, VT, Operand, Flags); 4871 } 4872 4873 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4874 SDValue Operand, const SDNodeFlags Flags) { 4875 assert(Operand.getOpcode() != ISD::DELETED_NODE && 4876 "Operand is DELETED_NODE!"); 4877 // Constant fold unary operations with an integer constant operand. Even 4878 // opaque constant will be folded, because the folding of unary operations 4879 // doesn't create new constants with different values. Nevertheless, the 4880 // opaque flag is preserved during folding to prevent future folding with 4881 // other constants. 4882 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4883 const APInt &Val = C->getAPIntValue(); 4884 switch (Opcode) { 4885 default: break; 4886 case ISD::SIGN_EXTEND: 4887 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4888 C->isTargetOpcode(), C->isOpaque()); 4889 case ISD::TRUNCATE: 4890 if (C->isOpaque()) 4891 break; 4892 LLVM_FALLTHROUGH; 4893 case ISD::ZERO_EXTEND: 4894 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4895 C->isTargetOpcode(), C->isOpaque()); 4896 case ISD::ANY_EXTEND: 4897 // Some targets like RISCV prefer to sign extend some types. 4898 if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT)) 4899 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4900 C->isTargetOpcode(), C->isOpaque()); 4901 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4902 C->isTargetOpcode(), C->isOpaque()); 4903 case ISD::UINT_TO_FP: 4904 case ISD::SINT_TO_FP: { 4905 APFloat apf(EVTToAPFloatSemantics(VT), 4906 APInt::getZero(VT.getSizeInBits())); 4907 (void)apf.convertFromAPInt(Val, 4908 Opcode==ISD::SINT_TO_FP, 4909 APFloat::rmNearestTiesToEven); 4910 return getConstantFP(apf, DL, VT); 4911 } 4912 case ISD::BITCAST: 4913 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 4914 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 4915 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 4916 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 4917 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 4918 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 4919 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 4920 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 4921 break; 4922 case ISD::ABS: 4923 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 4924 C->isOpaque()); 4925 case ISD::BITREVERSE: 4926 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 4927 C->isOpaque()); 4928 case ISD::BSWAP: 4929 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 4930 C->isOpaque()); 4931 case ISD::CTPOP: 4932 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 4933 C->isOpaque()); 4934 case ISD::CTLZ: 4935 case ISD::CTLZ_ZERO_UNDEF: 4936 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 4937 C->isOpaque()); 4938 case ISD::CTTZ: 4939 case ISD::CTTZ_ZERO_UNDEF: 4940 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 4941 C->isOpaque()); 4942 case ISD::FP16_TO_FP: { 4943 bool Ignored; 4944 APFloat FPV(APFloat::IEEEhalf(), 4945 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 4946 4947 // This can return overflow, underflow, or inexact; we don't care. 4948 // FIXME need to be more flexible about rounding mode. 4949 (void)FPV.convert(EVTToAPFloatSemantics(VT), 4950 APFloat::rmNearestTiesToEven, &Ignored); 4951 return getConstantFP(FPV, DL, VT); 4952 } 4953 case ISD::STEP_VECTOR: { 4954 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this)) 4955 return V; 4956 break; 4957 } 4958 } 4959 } 4960 4961 // Constant fold unary operations with a floating point constant operand. 4962 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 4963 APFloat V = C->getValueAPF(); // make copy 4964 switch (Opcode) { 4965 case ISD::FNEG: 4966 V.changeSign(); 4967 return getConstantFP(V, DL, VT); 4968 case ISD::FABS: 4969 V.clearSign(); 4970 return getConstantFP(V, DL, VT); 4971 case ISD::FCEIL: { 4972 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 4973 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4974 return getConstantFP(V, DL, VT); 4975 break; 4976 } 4977 case ISD::FTRUNC: { 4978 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 4979 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4980 return getConstantFP(V, DL, VT); 4981 break; 4982 } 4983 case ISD::FFLOOR: { 4984 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 4985 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4986 return getConstantFP(V, DL, VT); 4987 break; 4988 } 4989 case ISD::FP_EXTEND: { 4990 bool ignored; 4991 // This can return overflow, underflow, or inexact; we don't care. 4992 // FIXME need to be more flexible about rounding mode. 4993 (void)V.convert(EVTToAPFloatSemantics(VT), 4994 APFloat::rmNearestTiesToEven, &ignored); 4995 return getConstantFP(V, DL, VT); 4996 } 4997 case ISD::FP_TO_SINT: 4998 case ISD::FP_TO_UINT: { 4999 bool ignored; 5000 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 5001 // FIXME need to be more flexible about rounding mode. 5002 APFloat::opStatus s = 5003 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 5004 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 5005 break; 5006 return getConstant(IntVal, DL, VT); 5007 } 5008 case ISD::BITCAST: 5009 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 5010 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5011 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16) 5012 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5013 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 5014 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5015 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 5016 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 5017 break; 5018 case ISD::FP_TO_FP16: { 5019 bool Ignored; 5020 // This can return overflow, underflow, or inexact; we don't care. 5021 // FIXME need to be more flexible about rounding mode. 5022 (void)V.convert(APFloat::IEEEhalf(), 5023 APFloat::rmNearestTiesToEven, &Ignored); 5024 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 5025 } 5026 } 5027 } 5028 5029 // Constant fold unary operations with a vector integer or float operand. 5030 switch (Opcode) { 5031 default: 5032 // FIXME: Entirely reasonable to perform folding of other unary 5033 // operations here as the need arises. 5034 break; 5035 case ISD::FNEG: 5036 case ISD::FABS: 5037 case ISD::FCEIL: 5038 case ISD::FTRUNC: 5039 case ISD::FFLOOR: 5040 case ISD::FP_EXTEND: 5041 case ISD::FP_TO_SINT: 5042 case ISD::FP_TO_UINT: 5043 case ISD::TRUNCATE: 5044 case ISD::ANY_EXTEND: 5045 case ISD::ZERO_EXTEND: 5046 case ISD::SIGN_EXTEND: 5047 case ISD::UINT_TO_FP: 5048 case ISD::SINT_TO_FP: 5049 case ISD::ABS: 5050 case ISD::BITREVERSE: 5051 case ISD::BSWAP: 5052 case ISD::CTLZ: 5053 case ISD::CTLZ_ZERO_UNDEF: 5054 case ISD::CTTZ: 5055 case ISD::CTTZ_ZERO_UNDEF: 5056 case ISD::CTPOP: { 5057 SDValue Ops = {Operand}; 5058 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops)) 5059 return Fold; 5060 } 5061 } 5062 5063 unsigned OpOpcode = Operand.getNode()->getOpcode(); 5064 switch (Opcode) { 5065 case ISD::STEP_VECTOR: 5066 assert(VT.isScalableVector() && 5067 "STEP_VECTOR can only be used with scalable types"); 5068 assert(OpOpcode == ISD::TargetConstant && 5069 VT.getVectorElementType() == Operand.getValueType() && 5070 "Unexpected step operand"); 5071 break; 5072 case ISD::FREEZE: 5073 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5074 if (isGuaranteedNotToBeUndefOrPoison(Operand)) 5075 return Operand; 5076 break; 5077 case ISD::TokenFactor: 5078 case ISD::MERGE_VALUES: 5079 case ISD::CONCAT_VECTORS: 5080 return Operand; // Factor, merge or concat of one node? No need. 5081 case ISD::BUILD_VECTOR: { 5082 // Attempt to simplify BUILD_VECTOR. 5083 SDValue Ops[] = {Operand}; 5084 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5085 return V; 5086 break; 5087 } 5088 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 5089 case ISD::FP_EXTEND: 5090 assert(VT.isFloatingPoint() && 5091 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 5092 if (Operand.getValueType() == VT) return Operand; // noop conversion. 5093 assert((!VT.isVector() || 5094 VT.getVectorElementCount() == 5095 Operand.getValueType().getVectorElementCount()) && 5096 "Vector element count mismatch!"); 5097 assert(Operand.getValueType().bitsLT(VT) && 5098 "Invalid fpext node, dst < src!"); 5099 if (Operand.isUndef()) 5100 return getUNDEF(VT); 5101 break; 5102 case ISD::FP_TO_SINT: 5103 case ISD::FP_TO_UINT: 5104 if (Operand.isUndef()) 5105 return getUNDEF(VT); 5106 break; 5107 case ISD::SINT_TO_FP: 5108 case ISD::UINT_TO_FP: 5109 // [us]itofp(undef) = 0, because the result value is bounded. 5110 if (Operand.isUndef()) 5111 return getConstantFP(0.0, DL, VT); 5112 break; 5113 case ISD::SIGN_EXTEND: 5114 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5115 "Invalid SIGN_EXTEND!"); 5116 assert(VT.isVector() == Operand.getValueType().isVector() && 5117 "SIGN_EXTEND result type type should be vector iff the operand " 5118 "type is vector!"); 5119 if (Operand.getValueType() == VT) return Operand; // noop extension 5120 assert((!VT.isVector() || 5121 VT.getVectorElementCount() == 5122 Operand.getValueType().getVectorElementCount()) && 5123 "Vector element count mismatch!"); 5124 assert(Operand.getValueType().bitsLT(VT) && 5125 "Invalid sext node, dst < src!"); 5126 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 5127 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5128 if (OpOpcode == ISD::UNDEF) 5129 // sext(undef) = 0, because the top bits will all be the same. 5130 return getConstant(0, DL, VT); 5131 break; 5132 case ISD::ZERO_EXTEND: 5133 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5134 "Invalid ZERO_EXTEND!"); 5135 assert(VT.isVector() == Operand.getValueType().isVector() && 5136 "ZERO_EXTEND result type type should be vector iff the operand " 5137 "type is vector!"); 5138 if (Operand.getValueType() == VT) return Operand; // noop extension 5139 assert((!VT.isVector() || 5140 VT.getVectorElementCount() == 5141 Operand.getValueType().getVectorElementCount()) && 5142 "Vector element count mismatch!"); 5143 assert(Operand.getValueType().bitsLT(VT) && 5144 "Invalid zext node, dst < src!"); 5145 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 5146 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 5147 if (OpOpcode == ISD::UNDEF) 5148 // zext(undef) = 0, because the top bits will be zero. 5149 return getConstant(0, DL, VT); 5150 break; 5151 case ISD::ANY_EXTEND: 5152 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5153 "Invalid ANY_EXTEND!"); 5154 assert(VT.isVector() == Operand.getValueType().isVector() && 5155 "ANY_EXTEND result type type should be vector iff the operand " 5156 "type is vector!"); 5157 if (Operand.getValueType() == VT) return Operand; // noop extension 5158 assert((!VT.isVector() || 5159 VT.getVectorElementCount() == 5160 Operand.getValueType().getVectorElementCount()) && 5161 "Vector element count mismatch!"); 5162 assert(Operand.getValueType().bitsLT(VT) && 5163 "Invalid anyext node, dst < src!"); 5164 5165 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5166 OpOpcode == ISD::ANY_EXTEND) 5167 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 5168 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5169 if (OpOpcode == ISD::UNDEF) 5170 return getUNDEF(VT); 5171 5172 // (ext (trunc x)) -> x 5173 if (OpOpcode == ISD::TRUNCATE) { 5174 SDValue OpOp = Operand.getOperand(0); 5175 if (OpOp.getValueType() == VT) { 5176 transferDbgValues(Operand, OpOp); 5177 return OpOp; 5178 } 5179 } 5180 break; 5181 case ISD::TRUNCATE: 5182 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5183 "Invalid TRUNCATE!"); 5184 assert(VT.isVector() == Operand.getValueType().isVector() && 5185 "TRUNCATE result type type should be vector iff the operand " 5186 "type is vector!"); 5187 if (Operand.getValueType() == VT) return Operand; // noop truncate 5188 assert((!VT.isVector() || 5189 VT.getVectorElementCount() == 5190 Operand.getValueType().getVectorElementCount()) && 5191 "Vector element count mismatch!"); 5192 assert(Operand.getValueType().bitsGT(VT) && 5193 "Invalid truncate node, src < dst!"); 5194 if (OpOpcode == ISD::TRUNCATE) 5195 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5196 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5197 OpOpcode == ISD::ANY_EXTEND) { 5198 // If the source is smaller than the dest, we still need an extend. 5199 if (Operand.getOperand(0).getValueType().getScalarType() 5200 .bitsLT(VT.getScalarType())) 5201 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5202 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 5203 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5204 return Operand.getOperand(0); 5205 } 5206 if (OpOpcode == ISD::UNDEF) 5207 return getUNDEF(VT); 5208 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes) 5209 return getVScale(DL, VT, Operand.getConstantOperandAPInt(0)); 5210 break; 5211 case ISD::ANY_EXTEND_VECTOR_INREG: 5212 case ISD::ZERO_EXTEND_VECTOR_INREG: 5213 case ISD::SIGN_EXTEND_VECTOR_INREG: 5214 assert(VT.isVector() && "This DAG node is restricted to vector types."); 5215 assert(Operand.getValueType().bitsLE(VT) && 5216 "The input must be the same size or smaller than the result."); 5217 assert(VT.getVectorMinNumElements() < 5218 Operand.getValueType().getVectorMinNumElements() && 5219 "The destination vector type must have fewer lanes than the input."); 5220 break; 5221 case ISD::ABS: 5222 assert(VT.isInteger() && VT == Operand.getValueType() && 5223 "Invalid ABS!"); 5224 if (OpOpcode == ISD::UNDEF) 5225 return getUNDEF(VT); 5226 break; 5227 case ISD::BSWAP: 5228 assert(VT.isInteger() && VT == Operand.getValueType() && 5229 "Invalid BSWAP!"); 5230 assert((VT.getScalarSizeInBits() % 16 == 0) && 5231 "BSWAP types must be a multiple of 16 bits!"); 5232 if (OpOpcode == ISD::UNDEF) 5233 return getUNDEF(VT); 5234 // bswap(bswap(X)) -> X. 5235 if (OpOpcode == ISD::BSWAP) 5236 return Operand.getOperand(0); 5237 break; 5238 case ISD::BITREVERSE: 5239 assert(VT.isInteger() && VT == Operand.getValueType() && 5240 "Invalid BITREVERSE!"); 5241 if (OpOpcode == ISD::UNDEF) 5242 return getUNDEF(VT); 5243 break; 5244 case ISD::BITCAST: 5245 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 5246 "Cannot BITCAST between types of different sizes!"); 5247 if (VT == Operand.getValueType()) return Operand; // noop conversion. 5248 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 5249 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 5250 if (OpOpcode == ISD::UNDEF) 5251 return getUNDEF(VT); 5252 break; 5253 case ISD::SCALAR_TO_VECTOR: 5254 assert(VT.isVector() && !Operand.getValueType().isVector() && 5255 (VT.getVectorElementType() == Operand.getValueType() || 5256 (VT.getVectorElementType().isInteger() && 5257 Operand.getValueType().isInteger() && 5258 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 5259 "Illegal SCALAR_TO_VECTOR node!"); 5260 if (OpOpcode == ISD::UNDEF) 5261 return getUNDEF(VT); 5262 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 5263 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 5264 isa<ConstantSDNode>(Operand.getOperand(1)) && 5265 Operand.getConstantOperandVal(1) == 0 && 5266 Operand.getOperand(0).getValueType() == VT) 5267 return Operand.getOperand(0); 5268 break; 5269 case ISD::FNEG: 5270 // Negation of an unknown bag of bits is still completely undefined. 5271 if (OpOpcode == ISD::UNDEF) 5272 return getUNDEF(VT); 5273 5274 if (OpOpcode == ISD::FNEG) // --X -> X 5275 return Operand.getOperand(0); 5276 break; 5277 case ISD::FABS: 5278 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 5279 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 5280 break; 5281 case ISD::VSCALE: 5282 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5283 break; 5284 case ISD::CTPOP: 5285 if (Operand.getValueType().getScalarType() == MVT::i1) 5286 return Operand; 5287 break; 5288 case ISD::CTLZ: 5289 case ISD::CTTZ: 5290 if (Operand.getValueType().getScalarType() == MVT::i1) 5291 return getNOT(DL, Operand, Operand.getValueType()); 5292 break; 5293 case ISD::VECREDUCE_SMIN: 5294 case ISD::VECREDUCE_UMAX: 5295 if (Operand.getValueType().getScalarType() == MVT::i1) 5296 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 5297 break; 5298 case ISD::VECREDUCE_SMAX: 5299 case ISD::VECREDUCE_UMIN: 5300 if (Operand.getValueType().getScalarType() == MVT::i1) 5301 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 5302 break; 5303 } 5304 5305 SDNode *N; 5306 SDVTList VTs = getVTList(VT); 5307 SDValue Ops[] = {Operand}; 5308 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 5309 FoldingSetNodeID ID; 5310 AddNodeIDNode(ID, Opcode, VTs, Ops); 5311 void *IP = nullptr; 5312 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5313 E->intersectFlagsWith(Flags); 5314 return SDValue(E, 0); 5315 } 5316 5317 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5318 N->setFlags(Flags); 5319 createOperands(N, Ops); 5320 CSEMap.InsertNode(N, IP); 5321 } else { 5322 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5323 createOperands(N, Ops); 5324 } 5325 5326 InsertNode(N); 5327 SDValue V = SDValue(N, 0); 5328 NewSDValueDbgMsg(V, "Creating new node: ", this); 5329 return V; 5330 } 5331 5332 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5333 const APInt &C2) { 5334 switch (Opcode) { 5335 case ISD::ADD: return C1 + C2; 5336 case ISD::SUB: return C1 - C2; 5337 case ISD::MUL: return C1 * C2; 5338 case ISD::AND: return C1 & C2; 5339 case ISD::OR: return C1 | C2; 5340 case ISD::XOR: return C1 ^ C2; 5341 case ISD::SHL: return C1 << C2; 5342 case ISD::SRL: return C1.lshr(C2); 5343 case ISD::SRA: return C1.ashr(C2); 5344 case ISD::ROTL: return C1.rotl(C2); 5345 case ISD::ROTR: return C1.rotr(C2); 5346 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5347 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5348 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5349 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5350 case ISD::SADDSAT: return C1.sadd_sat(C2); 5351 case ISD::UADDSAT: return C1.uadd_sat(C2); 5352 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5353 case ISD::USUBSAT: return C1.usub_sat(C2); 5354 case ISD::SSHLSAT: return C1.sshl_sat(C2); 5355 case ISD::USHLSAT: return C1.ushl_sat(C2); 5356 case ISD::UDIV: 5357 if (!C2.getBoolValue()) 5358 break; 5359 return C1.udiv(C2); 5360 case ISD::UREM: 5361 if (!C2.getBoolValue()) 5362 break; 5363 return C1.urem(C2); 5364 case ISD::SDIV: 5365 if (!C2.getBoolValue()) 5366 break; 5367 return C1.sdiv(C2); 5368 case ISD::SREM: 5369 if (!C2.getBoolValue()) 5370 break; 5371 return C1.srem(C2); 5372 case ISD::MULHS: { 5373 unsigned FullWidth = C1.getBitWidth() * 2; 5374 APInt C1Ext = C1.sext(FullWidth); 5375 APInt C2Ext = C2.sext(FullWidth); 5376 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5377 } 5378 case ISD::MULHU: { 5379 unsigned FullWidth = C1.getBitWidth() * 2; 5380 APInt C1Ext = C1.zext(FullWidth); 5381 APInt C2Ext = C2.zext(FullWidth); 5382 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5383 } 5384 case ISD::AVGFLOORS: { 5385 unsigned FullWidth = C1.getBitWidth() + 1; 5386 APInt C1Ext = C1.sext(FullWidth); 5387 APInt C2Ext = C2.sext(FullWidth); 5388 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5389 } 5390 case ISD::AVGFLOORU: { 5391 unsigned FullWidth = C1.getBitWidth() + 1; 5392 APInt C1Ext = C1.zext(FullWidth); 5393 APInt C2Ext = C2.zext(FullWidth); 5394 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5395 } 5396 case ISD::AVGCEILS: { 5397 unsigned FullWidth = C1.getBitWidth() + 1; 5398 APInt C1Ext = C1.sext(FullWidth); 5399 APInt C2Ext = C2.sext(FullWidth); 5400 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5401 } 5402 case ISD::AVGCEILU: { 5403 unsigned FullWidth = C1.getBitWidth() + 1; 5404 APInt C1Ext = C1.zext(FullWidth); 5405 APInt C2Ext = C2.zext(FullWidth); 5406 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5407 } 5408 } 5409 return llvm::None; 5410 } 5411 5412 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 5413 const GlobalAddressSDNode *GA, 5414 const SDNode *N2) { 5415 if (GA->getOpcode() != ISD::GlobalAddress) 5416 return SDValue(); 5417 if (!TLI->isOffsetFoldingLegal(GA)) 5418 return SDValue(); 5419 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5420 if (!C2) 5421 return SDValue(); 5422 int64_t Offset = C2->getSExtValue(); 5423 switch (Opcode) { 5424 case ISD::ADD: break; 5425 case ISD::SUB: Offset = -uint64_t(Offset); break; 5426 default: return SDValue(); 5427 } 5428 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 5429 GA->getOffset() + uint64_t(Offset)); 5430 } 5431 5432 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 5433 switch (Opcode) { 5434 case ISD::SDIV: 5435 case ISD::UDIV: 5436 case ISD::SREM: 5437 case ISD::UREM: { 5438 // If a divisor is zero/undef or any element of a divisor vector is 5439 // zero/undef, the whole op is undef. 5440 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 5441 SDValue Divisor = Ops[1]; 5442 if (Divisor.isUndef() || isNullConstant(Divisor)) 5443 return true; 5444 5445 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 5446 llvm::any_of(Divisor->op_values(), 5447 [](SDValue V) { return V.isUndef() || 5448 isNullConstant(V); }); 5449 // TODO: Handle signed overflow. 5450 } 5451 // TODO: Handle oversized shifts. 5452 default: 5453 return false; 5454 } 5455 } 5456 5457 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 5458 EVT VT, ArrayRef<SDValue> Ops) { 5459 // If the opcode is a target-specific ISD node, there's nothing we can 5460 // do here and the operand rules may not line up with the below, so 5461 // bail early. 5462 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 5463 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 5464 // foldCONCAT_VECTORS in getNode before this is called. 5465 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 5466 return SDValue(); 5467 5468 unsigned NumOps = Ops.size(); 5469 if (NumOps == 0) 5470 return SDValue(); 5471 5472 if (isUndef(Opcode, Ops)) 5473 return getUNDEF(VT); 5474 5475 // Handle binops special cases. 5476 if (NumOps == 2) { 5477 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1])) 5478 return CFP; 5479 5480 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) { 5481 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) { 5482 if (C1->isOpaque() || C2->isOpaque()) 5483 return SDValue(); 5484 5485 Optional<APInt> FoldAttempt = 5486 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 5487 if (!FoldAttempt) 5488 return SDValue(); 5489 5490 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT); 5491 assert((!Folded || !VT.isVector()) && 5492 "Can't fold vectors ops with scalar operands"); 5493 return Folded; 5494 } 5495 } 5496 5497 // fold (add Sym, c) -> Sym+c 5498 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0])) 5499 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode()); 5500 if (TLI->isCommutativeBinOp(Opcode)) 5501 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1])) 5502 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode()); 5503 } 5504 5505 // This is for vector folding only from here on. 5506 if (!VT.isVector()) 5507 return SDValue(); 5508 5509 ElementCount NumElts = VT.getVectorElementCount(); 5510 5511 // See if we can fold through bitcasted integer ops. 5512 // TODO: Can we handle undef elements? 5513 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() && 5514 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT && 5515 Ops[0].getOpcode() == ISD::BITCAST && 5516 Ops[1].getOpcode() == ISD::BITCAST) { 5517 SDValue N1 = peekThroughBitcasts(Ops[0]); 5518 SDValue N2 = peekThroughBitcasts(Ops[1]); 5519 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 5520 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 5521 EVT BVVT = N1.getValueType(); 5522 if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) { 5523 bool IsLE = getDataLayout().isLittleEndian(); 5524 unsigned EltBits = VT.getScalarSizeInBits(); 5525 SmallVector<APInt> RawBits1, RawBits2; 5526 BitVector UndefElts1, UndefElts2; 5527 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) && 5528 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) && 5529 UndefElts1.none() && UndefElts2.none()) { 5530 SmallVector<APInt> RawBits; 5531 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) { 5532 Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]); 5533 if (!Fold) 5534 break; 5535 RawBits.push_back(Fold.getValue()); 5536 } 5537 if (RawBits.size() == NumElts.getFixedValue()) { 5538 // We have constant folded, but we need to cast this again back to 5539 // the original (possibly legalized) type. 5540 SmallVector<APInt> DstBits; 5541 BitVector DstUndefs; 5542 BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(), 5543 DstBits, RawBits, DstUndefs, 5544 BitVector(RawBits.size(), false)); 5545 EVT BVEltVT = BV1->getOperand(0).getValueType(); 5546 unsigned BVEltBits = BVEltVT.getSizeInBits(); 5547 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT)); 5548 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) { 5549 if (DstUndefs[I]) 5550 continue; 5551 Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT); 5552 } 5553 return getBitcast(VT, getBuildVector(BVVT, DL, Ops)); 5554 } 5555 } 5556 } 5557 } 5558 5559 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)). 5560 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1)) 5561 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) && 5562 Ops[0].getOpcode() == ISD::STEP_VECTOR) { 5563 APInt RHSVal; 5564 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) { 5565 APInt NewStep = Opcode == ISD::MUL 5566 ? Ops[0].getConstantOperandAPInt(0) * RHSVal 5567 : Ops[0].getConstantOperandAPInt(0) << RHSVal; 5568 return getStepVector(DL, VT, NewStep); 5569 } 5570 } 5571 5572 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) { 5573 return !Op.getValueType().isVector() || 5574 Op.getValueType().getVectorElementCount() == NumElts; 5575 }; 5576 5577 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) { 5578 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE || 5579 Op.getOpcode() == ISD::BUILD_VECTOR || 5580 Op.getOpcode() == ISD::SPLAT_VECTOR; 5581 }; 5582 5583 // All operands must be vector types with the same number of elements as 5584 // the result type and must be either UNDEF or a build/splat vector 5585 // or UNDEF scalars. 5586 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) || 5587 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5588 return SDValue(); 5589 5590 // If we are comparing vectors, then the result needs to be a i1 boolean that 5591 // is then extended back to the legal result type depending on how booleans 5592 // are represented. 5593 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5594 ISD::NodeType ExtendCode = 5595 (Opcode == ISD::SETCC && SVT != VT.getScalarType()) 5596 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT)) 5597 : ISD::SIGN_EXTEND; 5598 5599 // Find legal integer scalar type for constant promotion and 5600 // ensure that its scalar size is at least as large as source. 5601 EVT LegalSVT = VT.getScalarType(); 5602 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5603 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5604 if (LegalSVT.bitsLT(VT.getScalarType())) 5605 return SDValue(); 5606 } 5607 5608 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We 5609 // only have one operand to check. For fixed-length vector types we may have 5610 // a combination of BUILD_VECTOR and SPLAT_VECTOR. 5611 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue(); 5612 5613 // Constant fold each scalar lane separately. 5614 SmallVector<SDValue, 4> ScalarResults; 5615 for (unsigned I = 0; I != NumVectorElts; I++) { 5616 SmallVector<SDValue, 4> ScalarOps; 5617 for (SDValue Op : Ops) { 5618 EVT InSVT = Op.getValueType().getScalarType(); 5619 if (Op.getOpcode() != ISD::BUILD_VECTOR && 5620 Op.getOpcode() != ISD::SPLAT_VECTOR) { 5621 if (Op.isUndef()) 5622 ScalarOps.push_back(getUNDEF(InSVT)); 5623 else 5624 ScalarOps.push_back(Op); 5625 continue; 5626 } 5627 5628 SDValue ScalarOp = 5629 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I); 5630 EVT ScalarVT = ScalarOp.getValueType(); 5631 5632 // Build vector (integer) scalar operands may need implicit 5633 // truncation - do this before constant folding. 5634 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) { 5635 // Don't create illegally-typed nodes unless they're constants or undef 5636 // - if we fail to constant fold we can't guarantee the (dead) nodes 5637 // we're creating will be cleaned up before being visited for 5638 // legalization. 5639 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() && 5640 !isa<ConstantSDNode>(ScalarOp) && 5641 TLI->getTypeAction(*getContext(), InSVT) != 5642 TargetLowering::TypeLegal) 5643 return SDValue(); 5644 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5645 } 5646 5647 ScalarOps.push_back(ScalarOp); 5648 } 5649 5650 // Constant fold the scalar operands. 5651 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps); 5652 5653 // Legalize the (integer) scalar constant if necessary. 5654 if (LegalSVT != SVT) 5655 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult); 5656 5657 // Scalar folding only succeeded if the result is a constant or UNDEF. 5658 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5659 ScalarResult.getOpcode() != ISD::ConstantFP) 5660 return SDValue(); 5661 ScalarResults.push_back(ScalarResult); 5662 } 5663 5664 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0]) 5665 : getBuildVector(VT, DL, ScalarResults); 5666 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5667 return V; 5668 } 5669 5670 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5671 EVT VT, SDValue N1, SDValue N2) { 5672 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5673 // should. That will require dealing with a potentially non-default 5674 // rounding mode, checking the "opStatus" return value from the APFloat 5675 // math calculations, and possibly other variations. 5676 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false); 5677 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false); 5678 if (N1CFP && N2CFP) { 5679 APFloat C1 = N1CFP->getValueAPF(); // make copy 5680 const APFloat &C2 = N2CFP->getValueAPF(); 5681 switch (Opcode) { 5682 case ISD::FADD: 5683 C1.add(C2, APFloat::rmNearestTiesToEven); 5684 return getConstantFP(C1, DL, VT); 5685 case ISD::FSUB: 5686 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5687 return getConstantFP(C1, DL, VT); 5688 case ISD::FMUL: 5689 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5690 return getConstantFP(C1, DL, VT); 5691 case ISD::FDIV: 5692 C1.divide(C2, APFloat::rmNearestTiesToEven); 5693 return getConstantFP(C1, DL, VT); 5694 case ISD::FREM: 5695 C1.mod(C2); 5696 return getConstantFP(C1, DL, VT); 5697 case ISD::FCOPYSIGN: 5698 C1.copySign(C2); 5699 return getConstantFP(C1, DL, VT); 5700 case ISD::FMINNUM: 5701 return getConstantFP(minnum(C1, C2), DL, VT); 5702 case ISD::FMAXNUM: 5703 return getConstantFP(maxnum(C1, C2), DL, VT); 5704 case ISD::FMINIMUM: 5705 return getConstantFP(minimum(C1, C2), DL, VT); 5706 case ISD::FMAXIMUM: 5707 return getConstantFP(maximum(C1, C2), DL, VT); 5708 default: break; 5709 } 5710 } 5711 if (N1CFP && Opcode == ISD::FP_ROUND) { 5712 APFloat C1 = N1CFP->getValueAPF(); // make copy 5713 bool Unused; 5714 // This can return overflow, underflow, or inexact; we don't care. 5715 // FIXME need to be more flexible about rounding mode. 5716 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5717 &Unused); 5718 return getConstantFP(C1, DL, VT); 5719 } 5720 5721 switch (Opcode) { 5722 case ISD::FSUB: 5723 // -0.0 - undef --> undef (consistent with "fneg undef") 5724 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true)) 5725 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef()) 5726 return getUNDEF(VT); 5727 LLVM_FALLTHROUGH; 5728 5729 case ISD::FADD: 5730 case ISD::FMUL: 5731 case ISD::FDIV: 5732 case ISD::FREM: 5733 // If both operands are undef, the result is undef. If 1 operand is undef, 5734 // the result is NaN. This should match the behavior of the IR optimizer. 5735 if (N1.isUndef() && N2.isUndef()) 5736 return getUNDEF(VT); 5737 if (N1.isUndef() || N2.isUndef()) 5738 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5739 } 5740 return SDValue(); 5741 } 5742 5743 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5744 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5745 5746 // There's no need to assert on a byte-aligned pointer. All pointers are at 5747 // least byte aligned. 5748 if (A == Align(1)) 5749 return Val; 5750 5751 FoldingSetNodeID ID; 5752 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5753 ID.AddInteger(A.value()); 5754 5755 void *IP = nullptr; 5756 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5757 return SDValue(E, 0); 5758 5759 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5760 Val.getValueType(), A); 5761 createOperands(N, {Val}); 5762 5763 CSEMap.InsertNode(N, IP); 5764 InsertNode(N); 5765 5766 SDValue V(N, 0); 5767 NewSDValueDbgMsg(V, "Creating new node: ", this); 5768 return V; 5769 } 5770 5771 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5772 SDValue N1, SDValue N2) { 5773 SDNodeFlags Flags; 5774 if (Inserter) 5775 Flags = Inserter->getFlags(); 5776 return getNode(Opcode, DL, VT, N1, N2, Flags); 5777 } 5778 5779 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1, 5780 SDValue &N2) const { 5781 if (!TLI->isCommutativeBinOp(Opcode)) 5782 return; 5783 5784 // Canonicalize: 5785 // binop(const, nonconst) -> binop(nonconst, const) 5786 bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1); 5787 bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2); 5788 bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1); 5789 bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2); 5790 if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP)) 5791 std::swap(N1, N2); 5792 5793 // Canonicalize: 5794 // binop(splat(x), step_vector) -> binop(step_vector, splat(x)) 5795 else if (N1.getOpcode() == ISD::SPLAT_VECTOR && 5796 N2.getOpcode() == ISD::STEP_VECTOR) 5797 std::swap(N1, N2); 5798 } 5799 5800 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5801 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5802 assert(N1.getOpcode() != ISD::DELETED_NODE && 5803 N2.getOpcode() != ISD::DELETED_NODE && 5804 "Operand is DELETED_NODE!"); 5805 5806 canonicalizeCommutativeBinop(Opcode, N1, N2); 5807 5808 auto *N1C = dyn_cast<ConstantSDNode>(N1); 5809 auto *N2C = dyn_cast<ConstantSDNode>(N2); 5810 5811 // Don't allow undefs in vector splats - we might be returning N2 when folding 5812 // to zero etc. 5813 ConstantSDNode *N2CV = 5814 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true); 5815 5816 switch (Opcode) { 5817 default: break; 5818 case ISD::TokenFactor: 5819 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5820 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5821 // Fold trivial token factors. 5822 if (N1.getOpcode() == ISD::EntryToken) return N2; 5823 if (N2.getOpcode() == ISD::EntryToken) return N1; 5824 if (N1 == N2) return N1; 5825 break; 5826 case ISD::BUILD_VECTOR: { 5827 // Attempt to simplify BUILD_VECTOR. 5828 SDValue Ops[] = {N1, N2}; 5829 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5830 return V; 5831 break; 5832 } 5833 case ISD::CONCAT_VECTORS: { 5834 SDValue Ops[] = {N1, N2}; 5835 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5836 return V; 5837 break; 5838 } 5839 case ISD::AND: 5840 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5841 assert(N1.getValueType() == N2.getValueType() && 5842 N1.getValueType() == VT && "Binary operator types must match!"); 5843 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5844 // worth handling here. 5845 if (N2CV && N2CV->isZero()) 5846 return N2; 5847 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X 5848 return N1; 5849 break; 5850 case ISD::OR: 5851 case ISD::XOR: 5852 case ISD::ADD: 5853 case ISD::SUB: 5854 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5855 assert(N1.getValueType() == N2.getValueType() && 5856 N1.getValueType() == VT && "Binary operator types must match!"); 5857 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5858 // it's worth handling here. 5859 if (N2CV && N2CV->isZero()) 5860 return N1; 5861 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5862 VT.getVectorElementType() == MVT::i1) 5863 return getNode(ISD::XOR, DL, VT, N1, N2); 5864 break; 5865 case ISD::MUL: 5866 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5867 assert(N1.getValueType() == N2.getValueType() && 5868 N1.getValueType() == VT && "Binary operator types must match!"); 5869 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5870 return getNode(ISD::AND, DL, VT, N1, N2); 5871 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5872 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5873 const APInt &N2CImm = N2C->getAPIntValue(); 5874 return getVScale(DL, VT, MulImm * N2CImm); 5875 } 5876 break; 5877 case ISD::UDIV: 5878 case ISD::UREM: 5879 case ISD::MULHU: 5880 case ISD::MULHS: 5881 case ISD::SDIV: 5882 case ISD::SREM: 5883 case ISD::SADDSAT: 5884 case ISD::SSUBSAT: 5885 case ISD::UADDSAT: 5886 case ISD::USUBSAT: 5887 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5888 assert(N1.getValueType() == N2.getValueType() && 5889 N1.getValueType() == VT && "Binary operator types must match!"); 5890 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5891 // fold (add_sat x, y) -> (or x, y) for bool types. 5892 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5893 return getNode(ISD::OR, DL, VT, N1, N2); 5894 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5895 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5896 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5897 } 5898 break; 5899 case ISD::SMIN: 5900 case ISD::UMAX: 5901 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5902 assert(N1.getValueType() == N2.getValueType() && 5903 N1.getValueType() == VT && "Binary operator types must match!"); 5904 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5905 return getNode(ISD::OR, DL, VT, N1, N2); 5906 break; 5907 case ISD::SMAX: 5908 case ISD::UMIN: 5909 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5910 assert(N1.getValueType() == N2.getValueType() && 5911 N1.getValueType() == VT && "Binary operator types must match!"); 5912 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5913 return getNode(ISD::AND, DL, VT, N1, N2); 5914 break; 5915 case ISD::FADD: 5916 case ISD::FSUB: 5917 case ISD::FMUL: 5918 case ISD::FDIV: 5919 case ISD::FREM: 5920 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5921 assert(N1.getValueType() == N2.getValueType() && 5922 N1.getValueType() == VT && "Binary operator types must match!"); 5923 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5924 return V; 5925 break; 5926 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5927 assert(N1.getValueType() == VT && 5928 N1.getValueType().isFloatingPoint() && 5929 N2.getValueType().isFloatingPoint() && 5930 "Invalid FCOPYSIGN!"); 5931 break; 5932 case ISD::SHL: 5933 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5934 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5935 const APInt &ShiftImm = N2C->getAPIntValue(); 5936 return getVScale(DL, VT, MulImm << ShiftImm); 5937 } 5938 LLVM_FALLTHROUGH; 5939 case ISD::SRA: 5940 case ISD::SRL: 5941 if (SDValue V = simplifyShift(N1, N2)) 5942 return V; 5943 LLVM_FALLTHROUGH; 5944 case ISD::ROTL: 5945 case ISD::ROTR: 5946 assert(VT == N1.getValueType() && 5947 "Shift operators return type must be the same as their first arg"); 5948 assert(VT.isInteger() && N2.getValueType().isInteger() && 5949 "Shifts only work on integers"); 5950 assert((!VT.isVector() || VT == N2.getValueType()) && 5951 "Vector shift amounts must be in the same as their first arg"); 5952 // Verify that the shift amount VT is big enough to hold valid shift 5953 // amounts. This catches things like trying to shift an i1024 value by an 5954 // i8, which is easy to fall into in generic code that uses 5955 // TLI.getShiftAmount(). 5956 assert(N2.getValueType().getScalarSizeInBits() >= 5957 Log2_32_Ceil(VT.getScalarSizeInBits()) && 5958 "Invalid use of small shift amount with oversized value!"); 5959 5960 // Always fold shifts of i1 values so the code generator doesn't need to 5961 // handle them. Since we know the size of the shift has to be less than the 5962 // size of the value, the shift/rotate count is guaranteed to be zero. 5963 if (VT == MVT::i1) 5964 return N1; 5965 if (N2CV && N2CV->isZero()) 5966 return N1; 5967 break; 5968 case ISD::FP_ROUND: 5969 assert(VT.isFloatingPoint() && 5970 N1.getValueType().isFloatingPoint() && 5971 VT.bitsLE(N1.getValueType()) && 5972 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 5973 "Invalid FP_ROUND!"); 5974 if (N1.getValueType() == VT) return N1; // noop conversion. 5975 break; 5976 case ISD::AssertSext: 5977 case ISD::AssertZext: { 5978 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5979 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5980 assert(VT.isInteger() && EVT.isInteger() && 5981 "Cannot *_EXTEND_INREG FP types"); 5982 assert(!EVT.isVector() && 5983 "AssertSExt/AssertZExt type should be the vector element type " 5984 "rather than the vector type!"); 5985 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 5986 if (VT.getScalarType() == EVT) return N1; // noop assertion. 5987 break; 5988 } 5989 case ISD::SIGN_EXTEND_INREG: { 5990 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5991 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5992 assert(VT.isInteger() && EVT.isInteger() && 5993 "Cannot *_EXTEND_INREG FP types"); 5994 assert(EVT.isVector() == VT.isVector() && 5995 "SIGN_EXTEND_INREG type should be vector iff the operand " 5996 "type is vector!"); 5997 assert((!EVT.isVector() || 5998 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 5999 "Vector element counts must match in SIGN_EXTEND_INREG"); 6000 assert(EVT.bitsLE(VT) && "Not extending!"); 6001 if (EVT == VT) return N1; // Not actually extending 6002 6003 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 6004 unsigned FromBits = EVT.getScalarSizeInBits(); 6005 Val <<= Val.getBitWidth() - FromBits; 6006 Val.ashrInPlace(Val.getBitWidth() - FromBits); 6007 return getConstant(Val, DL, ConstantVT); 6008 }; 6009 6010 if (N1C) { 6011 const APInt &Val = N1C->getAPIntValue(); 6012 return SignExtendInReg(Val, VT); 6013 } 6014 6015 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 6016 SmallVector<SDValue, 8> Ops; 6017 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 6018 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 6019 SDValue Op = N1.getOperand(i); 6020 if (Op.isUndef()) { 6021 Ops.push_back(getUNDEF(OpVT)); 6022 continue; 6023 } 6024 ConstantSDNode *C = cast<ConstantSDNode>(Op); 6025 APInt Val = C->getAPIntValue(); 6026 Ops.push_back(SignExtendInReg(Val, OpVT)); 6027 } 6028 return getBuildVector(VT, DL, Ops); 6029 } 6030 break; 6031 } 6032 case ISD::FP_TO_SINT_SAT: 6033 case ISD::FP_TO_UINT_SAT: { 6034 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 6035 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 6036 assert(N1.getValueType().isVector() == VT.isVector() && 6037 "FP_TO_*INT_SAT type should be vector iff the operand type is " 6038 "vector!"); 6039 assert((!VT.isVector() || VT.getVectorNumElements() == 6040 N1.getValueType().getVectorNumElements()) && 6041 "Vector element counts must match in FP_TO_*INT_SAT"); 6042 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 6043 "Type to saturate to must be a scalar."); 6044 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 6045 "Not extending!"); 6046 break; 6047 } 6048 case ISD::EXTRACT_VECTOR_ELT: 6049 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 6050 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 6051 element type of the vector."); 6052 6053 // Extract from an undefined value or using an undefined index is undefined. 6054 if (N1.isUndef() || N2.isUndef()) 6055 return getUNDEF(VT); 6056 6057 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 6058 // vectors. For scalable vectors we will provide appropriate support for 6059 // dealing with arbitrary indices. 6060 if (N2C && N1.getValueType().isFixedLengthVector() && 6061 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 6062 return getUNDEF(VT); 6063 6064 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 6065 // expanding copies of large vectors from registers. This only works for 6066 // fixed length vectors, since we need to know the exact number of 6067 // elements. 6068 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 6069 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 6070 unsigned Factor = 6071 N1.getOperand(0).getValueType().getVectorNumElements(); 6072 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 6073 N1.getOperand(N2C->getZExtValue() / Factor), 6074 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 6075 } 6076 6077 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 6078 // lowering is expanding large vector constants. 6079 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 6080 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 6081 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 6082 N1.getValueType().isFixedLengthVector()) && 6083 "BUILD_VECTOR used for scalable vectors"); 6084 unsigned Index = 6085 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 6086 SDValue Elt = N1.getOperand(Index); 6087 6088 if (VT != Elt.getValueType()) 6089 // If the vector element type is not legal, the BUILD_VECTOR operands 6090 // are promoted and implicitly truncated, and the result implicitly 6091 // extended. Make that explicit here. 6092 Elt = getAnyExtOrTrunc(Elt, DL, VT); 6093 6094 return Elt; 6095 } 6096 6097 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 6098 // operations are lowered to scalars. 6099 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 6100 // If the indices are the same, return the inserted element else 6101 // if the indices are known different, extract the element from 6102 // the original vector. 6103 SDValue N1Op2 = N1.getOperand(2); 6104 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 6105 6106 if (N1Op2C && N2C) { 6107 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 6108 if (VT == N1.getOperand(1).getValueType()) 6109 return N1.getOperand(1); 6110 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 6111 } 6112 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 6113 } 6114 } 6115 6116 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 6117 // when vector types are scalarized and v1iX is legal. 6118 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 6119 // Here we are completely ignoring the extract element index (N2), 6120 // which is fine for fixed width vectors, since any index other than 0 6121 // is undefined anyway. However, this cannot be ignored for scalable 6122 // vectors - in theory we could support this, but we don't want to do this 6123 // without a profitability check. 6124 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6125 N1.getValueType().isFixedLengthVector() && 6126 N1.getValueType().getVectorNumElements() == 1) { 6127 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 6128 N1.getOperand(1)); 6129 } 6130 break; 6131 case ISD::EXTRACT_ELEMENT: 6132 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 6133 assert(!N1.getValueType().isVector() && !VT.isVector() && 6134 (N1.getValueType().isInteger() == VT.isInteger()) && 6135 N1.getValueType() != VT && 6136 "Wrong types for EXTRACT_ELEMENT!"); 6137 6138 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 6139 // 64-bit integers into 32-bit parts. Instead of building the extract of 6140 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 6141 if (N1.getOpcode() == ISD::BUILD_PAIR) 6142 return N1.getOperand(N2C->getZExtValue()); 6143 6144 // EXTRACT_ELEMENT of a constant int is also very common. 6145 if (N1C) { 6146 unsigned ElementSize = VT.getSizeInBits(); 6147 unsigned Shift = ElementSize * N2C->getZExtValue(); 6148 const APInt &Val = N1C->getAPIntValue(); 6149 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 6150 } 6151 break; 6152 case ISD::EXTRACT_SUBVECTOR: { 6153 EVT N1VT = N1.getValueType(); 6154 assert(VT.isVector() && N1VT.isVector() && 6155 "Extract subvector VTs must be vectors!"); 6156 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 6157 "Extract subvector VTs must have the same element type!"); 6158 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 6159 "Cannot extract a scalable vector from a fixed length vector!"); 6160 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6161 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 6162 "Extract subvector must be from larger vector to smaller vector!"); 6163 assert(N2C && "Extract subvector index must be a constant"); 6164 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6165 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 6166 N1VT.getVectorMinNumElements()) && 6167 "Extract subvector overflow!"); 6168 assert(N2C->getAPIntValue().getBitWidth() == 6169 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6170 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 6171 6172 // Trivial extraction. 6173 if (VT == N1VT) 6174 return N1; 6175 6176 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 6177 if (N1.isUndef()) 6178 return getUNDEF(VT); 6179 6180 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 6181 // the concat have the same type as the extract. 6182 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 6183 VT == N1.getOperand(0).getValueType()) { 6184 unsigned Factor = VT.getVectorMinNumElements(); 6185 return N1.getOperand(N2C->getZExtValue() / Factor); 6186 } 6187 6188 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 6189 // during shuffle legalization. 6190 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 6191 VT == N1.getOperand(1).getValueType()) 6192 return N1.getOperand(1); 6193 break; 6194 } 6195 } 6196 6197 // Perform trivial constant folding. 6198 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 6199 return SV; 6200 6201 // Canonicalize an UNDEF to the RHS, even over a constant. 6202 if (N1.isUndef()) { 6203 if (TLI->isCommutativeBinOp(Opcode)) { 6204 std::swap(N1, N2); 6205 } else { 6206 switch (Opcode) { 6207 case ISD::SIGN_EXTEND_INREG: 6208 case ISD::SUB: 6209 return getUNDEF(VT); // fold op(undef, arg2) -> undef 6210 case ISD::UDIV: 6211 case ISD::SDIV: 6212 case ISD::UREM: 6213 case ISD::SREM: 6214 case ISD::SSUBSAT: 6215 case ISD::USUBSAT: 6216 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 6217 } 6218 } 6219 } 6220 6221 // Fold a bunch of operators when the RHS is undef. 6222 if (N2.isUndef()) { 6223 switch (Opcode) { 6224 case ISD::XOR: 6225 if (N1.isUndef()) 6226 // Handle undef ^ undef -> 0 special case. This is a common 6227 // idiom (misuse). 6228 return getConstant(0, DL, VT); 6229 LLVM_FALLTHROUGH; 6230 case ISD::ADD: 6231 case ISD::SUB: 6232 case ISD::UDIV: 6233 case ISD::SDIV: 6234 case ISD::UREM: 6235 case ISD::SREM: 6236 return getUNDEF(VT); // fold op(arg1, undef) -> undef 6237 case ISD::MUL: 6238 case ISD::AND: 6239 case ISD::SSUBSAT: 6240 case ISD::USUBSAT: 6241 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 6242 case ISD::OR: 6243 case ISD::SADDSAT: 6244 case ISD::UADDSAT: 6245 return getAllOnesConstant(DL, VT); 6246 } 6247 } 6248 6249 // Memoize this node if possible. 6250 SDNode *N; 6251 SDVTList VTs = getVTList(VT); 6252 SDValue Ops[] = {N1, N2}; 6253 if (VT != MVT::Glue) { 6254 FoldingSetNodeID ID; 6255 AddNodeIDNode(ID, Opcode, VTs, Ops); 6256 void *IP = nullptr; 6257 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6258 E->intersectFlagsWith(Flags); 6259 return SDValue(E, 0); 6260 } 6261 6262 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6263 N->setFlags(Flags); 6264 createOperands(N, Ops); 6265 CSEMap.InsertNode(N, IP); 6266 } else { 6267 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6268 createOperands(N, Ops); 6269 } 6270 6271 InsertNode(N); 6272 SDValue V = SDValue(N, 0); 6273 NewSDValueDbgMsg(V, "Creating new node: ", this); 6274 return V; 6275 } 6276 6277 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6278 SDValue N1, SDValue N2, SDValue N3) { 6279 SDNodeFlags Flags; 6280 if (Inserter) 6281 Flags = Inserter->getFlags(); 6282 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 6283 } 6284 6285 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6286 SDValue N1, SDValue N2, SDValue N3, 6287 const SDNodeFlags Flags) { 6288 assert(N1.getOpcode() != ISD::DELETED_NODE && 6289 N2.getOpcode() != ISD::DELETED_NODE && 6290 N3.getOpcode() != ISD::DELETED_NODE && 6291 "Operand is DELETED_NODE!"); 6292 // Perform various simplifications. 6293 switch (Opcode) { 6294 case ISD::FMA: { 6295 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6296 assert(N1.getValueType() == VT && N2.getValueType() == VT && 6297 N3.getValueType() == VT && "FMA types must match!"); 6298 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6299 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 6300 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 6301 if (N1CFP && N2CFP && N3CFP) { 6302 APFloat V1 = N1CFP->getValueAPF(); 6303 const APFloat &V2 = N2CFP->getValueAPF(); 6304 const APFloat &V3 = N3CFP->getValueAPF(); 6305 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 6306 return getConstantFP(V1, DL, VT); 6307 } 6308 break; 6309 } 6310 case ISD::BUILD_VECTOR: { 6311 // Attempt to simplify BUILD_VECTOR. 6312 SDValue Ops[] = {N1, N2, N3}; 6313 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6314 return V; 6315 break; 6316 } 6317 case ISD::CONCAT_VECTORS: { 6318 SDValue Ops[] = {N1, N2, N3}; 6319 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6320 return V; 6321 break; 6322 } 6323 case ISD::SETCC: { 6324 assert(VT.isInteger() && "SETCC result type must be an integer!"); 6325 assert(N1.getValueType() == N2.getValueType() && 6326 "SETCC operands must have the same type!"); 6327 assert(VT.isVector() == N1.getValueType().isVector() && 6328 "SETCC type should be vector iff the operand type is vector!"); 6329 assert((!VT.isVector() || VT.getVectorElementCount() == 6330 N1.getValueType().getVectorElementCount()) && 6331 "SETCC vector element counts must match!"); 6332 // Use FoldSetCC to simplify SETCC's. 6333 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 6334 return V; 6335 // Vector constant folding. 6336 SDValue Ops[] = {N1, N2, N3}; 6337 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) { 6338 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 6339 return V; 6340 } 6341 break; 6342 } 6343 case ISD::SELECT: 6344 case ISD::VSELECT: 6345 if (SDValue V = simplifySelect(N1, N2, N3)) 6346 return V; 6347 break; 6348 case ISD::VECTOR_SHUFFLE: 6349 llvm_unreachable("should use getVectorShuffle constructor!"); 6350 case ISD::VECTOR_SPLICE: { 6351 if (cast<ConstantSDNode>(N3)->isNullValue()) 6352 return N1; 6353 break; 6354 } 6355 case ISD::INSERT_VECTOR_ELT: { 6356 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 6357 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 6358 // for scalable vectors where we will generate appropriate code to 6359 // deal with out-of-bounds cases correctly. 6360 if (N3C && N1.getValueType().isFixedLengthVector() && 6361 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 6362 return getUNDEF(VT); 6363 6364 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 6365 if (N3.isUndef()) 6366 return getUNDEF(VT); 6367 6368 // If the inserted element is an UNDEF, just use the input vector. 6369 if (N2.isUndef()) 6370 return N1; 6371 6372 break; 6373 } 6374 case ISD::INSERT_SUBVECTOR: { 6375 // Inserting undef into undef is still undef. 6376 if (N1.isUndef() && N2.isUndef()) 6377 return getUNDEF(VT); 6378 6379 EVT N2VT = N2.getValueType(); 6380 assert(VT == N1.getValueType() && 6381 "Dest and insert subvector source types must match!"); 6382 assert(VT.isVector() && N2VT.isVector() && 6383 "Insert subvector VTs must be vectors!"); 6384 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 6385 "Cannot insert a scalable vector into a fixed length vector!"); 6386 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6387 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 6388 "Insert subvector must be from smaller vector to larger vector!"); 6389 assert(isa<ConstantSDNode>(N3) && 6390 "Insert subvector index must be constant"); 6391 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6392 (N2VT.getVectorMinNumElements() + 6393 cast<ConstantSDNode>(N3)->getZExtValue()) <= 6394 VT.getVectorMinNumElements()) && 6395 "Insert subvector overflow!"); 6396 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 6397 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6398 "Constant index for INSERT_SUBVECTOR has an invalid size"); 6399 6400 // Trivial insertion. 6401 if (VT == N2VT) 6402 return N2; 6403 6404 // If this is an insert of an extracted vector into an undef vector, we 6405 // can just use the input to the extract. 6406 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6407 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 6408 return N2.getOperand(0); 6409 break; 6410 } 6411 case ISD::BITCAST: 6412 // Fold bit_convert nodes from a type to themselves. 6413 if (N1.getValueType() == VT) 6414 return N1; 6415 break; 6416 } 6417 6418 // Memoize node if it doesn't produce a flag. 6419 SDNode *N; 6420 SDVTList VTs = getVTList(VT); 6421 SDValue Ops[] = {N1, N2, N3}; 6422 if (VT != MVT::Glue) { 6423 FoldingSetNodeID ID; 6424 AddNodeIDNode(ID, Opcode, VTs, Ops); 6425 void *IP = nullptr; 6426 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6427 E->intersectFlagsWith(Flags); 6428 return SDValue(E, 0); 6429 } 6430 6431 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6432 N->setFlags(Flags); 6433 createOperands(N, Ops); 6434 CSEMap.InsertNode(N, IP); 6435 } else { 6436 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6437 createOperands(N, Ops); 6438 } 6439 6440 InsertNode(N); 6441 SDValue V = SDValue(N, 0); 6442 NewSDValueDbgMsg(V, "Creating new node: ", this); 6443 return V; 6444 } 6445 6446 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6447 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 6448 SDValue Ops[] = { N1, N2, N3, N4 }; 6449 return getNode(Opcode, DL, VT, Ops); 6450 } 6451 6452 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6453 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6454 SDValue N5) { 6455 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6456 return getNode(Opcode, DL, VT, Ops); 6457 } 6458 6459 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 6460 /// the incoming stack arguments to be loaded from the stack. 6461 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 6462 SmallVector<SDValue, 8> ArgChains; 6463 6464 // Include the original chain at the beginning of the list. When this is 6465 // used by target LowerCall hooks, this helps legalize find the 6466 // CALLSEQ_BEGIN node. 6467 ArgChains.push_back(Chain); 6468 6469 // Add a chain value for each stack argument. 6470 for (SDNode *U : getEntryNode().getNode()->uses()) 6471 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U)) 6472 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 6473 if (FI->getIndex() < 0) 6474 ArgChains.push_back(SDValue(L, 1)); 6475 6476 // Build a tokenfactor for all the chains. 6477 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 6478 } 6479 6480 /// getMemsetValue - Vectorized representation of the memset value 6481 /// operand. 6482 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 6483 const SDLoc &dl) { 6484 assert(!Value.isUndef()); 6485 6486 unsigned NumBits = VT.getScalarSizeInBits(); 6487 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 6488 assert(C->getAPIntValue().getBitWidth() == 8); 6489 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 6490 if (VT.isInteger()) { 6491 bool IsOpaque = VT.getSizeInBits() > 64 || 6492 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 6493 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 6494 } 6495 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 6496 VT); 6497 } 6498 6499 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 6500 EVT IntVT = VT.getScalarType(); 6501 if (!IntVT.isInteger()) 6502 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 6503 6504 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 6505 if (NumBits > 8) { 6506 // Use a multiplication with 0x010101... to extend the input to the 6507 // required length. 6508 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 6509 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 6510 DAG.getConstant(Magic, dl, IntVT)); 6511 } 6512 6513 if (VT != Value.getValueType() && !VT.isInteger()) 6514 Value = DAG.getBitcast(VT.getScalarType(), Value); 6515 if (VT != Value.getValueType()) 6516 Value = DAG.getSplatBuildVector(VT, dl, Value); 6517 6518 return Value; 6519 } 6520 6521 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 6522 /// used when a memcpy is turned into a memset when the source is a constant 6523 /// string ptr. 6524 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 6525 const TargetLowering &TLI, 6526 const ConstantDataArraySlice &Slice) { 6527 // Handle vector with all elements zero. 6528 if (Slice.Array == nullptr) { 6529 if (VT.isInteger()) 6530 return DAG.getConstant(0, dl, VT); 6531 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 6532 return DAG.getConstantFP(0.0, dl, VT); 6533 if (VT.isVector()) { 6534 unsigned NumElts = VT.getVectorNumElements(); 6535 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 6536 return DAG.getNode(ISD::BITCAST, dl, VT, 6537 DAG.getConstant(0, dl, 6538 EVT::getVectorVT(*DAG.getContext(), 6539 EltVT, NumElts))); 6540 } 6541 llvm_unreachable("Expected type!"); 6542 } 6543 6544 assert(!VT.isVector() && "Can't handle vector type here!"); 6545 unsigned NumVTBits = VT.getSizeInBits(); 6546 unsigned NumVTBytes = NumVTBits / 8; 6547 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 6548 6549 APInt Val(NumVTBits, 0); 6550 if (DAG.getDataLayout().isLittleEndian()) { 6551 for (unsigned i = 0; i != NumBytes; ++i) 6552 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 6553 } else { 6554 for (unsigned i = 0; i != NumBytes; ++i) 6555 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6556 } 6557 6558 // If the "cost" of materializing the integer immediate is less than the cost 6559 // of a load, then it is cost effective to turn the load into the immediate. 6560 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6561 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6562 return DAG.getConstant(Val, dl, VT); 6563 return SDValue(); 6564 } 6565 6566 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6567 const SDLoc &DL, 6568 const SDNodeFlags Flags) { 6569 EVT VT = Base.getValueType(); 6570 SDValue Index; 6571 6572 if (Offset.isScalable()) 6573 Index = getVScale(DL, Base.getValueType(), 6574 APInt(Base.getValueSizeInBits().getFixedSize(), 6575 Offset.getKnownMinSize())); 6576 else 6577 Index = getConstant(Offset.getFixedSize(), DL, VT); 6578 6579 return getMemBasePlusOffset(Base, Index, DL, Flags); 6580 } 6581 6582 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6583 const SDLoc &DL, 6584 const SDNodeFlags Flags) { 6585 assert(Offset.getValueType().isInteger()); 6586 EVT BasePtrVT = Ptr.getValueType(); 6587 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6588 } 6589 6590 /// Returns true if memcpy source is constant data. 6591 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6592 uint64_t SrcDelta = 0; 6593 GlobalAddressSDNode *G = nullptr; 6594 if (Src.getOpcode() == ISD::GlobalAddress) 6595 G = cast<GlobalAddressSDNode>(Src); 6596 else if (Src.getOpcode() == ISD::ADD && 6597 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6598 Src.getOperand(1).getOpcode() == ISD::Constant) { 6599 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6600 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6601 } 6602 if (!G) 6603 return false; 6604 6605 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6606 SrcDelta + G->getOffset()); 6607 } 6608 6609 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6610 SelectionDAG &DAG) { 6611 // On Darwin, -Os means optimize for size without hurting performance, so 6612 // only really optimize for size when -Oz (MinSize) is used. 6613 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6614 return MF.getFunction().hasMinSize(); 6615 return DAG.shouldOptForSize(); 6616 } 6617 6618 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6619 SmallVector<SDValue, 32> &OutChains, unsigned From, 6620 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6621 SmallVector<SDValue, 16> &OutStoreChains) { 6622 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6623 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6624 SmallVector<SDValue, 16> GluedLoadChains; 6625 for (unsigned i = From; i < To; ++i) { 6626 OutChains.push_back(OutLoadChains[i]); 6627 GluedLoadChains.push_back(OutLoadChains[i]); 6628 } 6629 6630 // Chain for all loads. 6631 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6632 GluedLoadChains); 6633 6634 for (unsigned i = From; i < To; ++i) { 6635 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6636 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6637 ST->getBasePtr(), ST->getMemoryVT(), 6638 ST->getMemOperand()); 6639 OutChains.push_back(NewStore); 6640 } 6641 } 6642 6643 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6644 SDValue Chain, SDValue Dst, SDValue Src, 6645 uint64_t Size, Align Alignment, 6646 bool isVol, bool AlwaysInline, 6647 MachinePointerInfo DstPtrInfo, 6648 MachinePointerInfo SrcPtrInfo, 6649 const AAMDNodes &AAInfo) { 6650 // Turn a memcpy of undef to nop. 6651 // FIXME: We need to honor volatile even is Src is undef. 6652 if (Src.isUndef()) 6653 return Chain; 6654 6655 // Expand memcpy to a series of load and store ops if the size operand falls 6656 // below a certain threshold. 6657 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6658 // rather than maybe a humongous number of loads and stores. 6659 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6660 const DataLayout &DL = DAG.getDataLayout(); 6661 LLVMContext &C = *DAG.getContext(); 6662 std::vector<EVT> MemOps; 6663 bool DstAlignCanChange = false; 6664 MachineFunction &MF = DAG.getMachineFunction(); 6665 MachineFrameInfo &MFI = MF.getFrameInfo(); 6666 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6667 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6668 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6669 DstAlignCanChange = true; 6670 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6671 if (!SrcAlign || Alignment > *SrcAlign) 6672 SrcAlign = Alignment; 6673 assert(SrcAlign && "SrcAlign must be set"); 6674 ConstantDataArraySlice Slice; 6675 // If marked as volatile, perform a copy even when marked as constant. 6676 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6677 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6678 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6679 const MemOp Op = isZeroConstant 6680 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6681 /*IsZeroMemset*/ true, isVol) 6682 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6683 *SrcAlign, isVol, CopyFromConstant); 6684 if (!TLI.findOptimalMemOpLowering( 6685 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6686 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6687 return SDValue(); 6688 6689 if (DstAlignCanChange) { 6690 Type *Ty = MemOps[0].getTypeForEVT(C); 6691 Align NewAlign = DL.getABITypeAlign(Ty); 6692 6693 // Don't promote to an alignment that would require dynamic stack 6694 // realignment. 6695 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6696 if (!TRI->hasStackRealignment(MF)) 6697 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6698 NewAlign = NewAlign / 2; 6699 6700 if (NewAlign > Alignment) { 6701 // Give the stack frame object a larger alignment if needed. 6702 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6703 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6704 Alignment = NewAlign; 6705 } 6706 } 6707 6708 // Prepare AAInfo for loads/stores after lowering this memcpy. 6709 AAMDNodes NewAAInfo = AAInfo; 6710 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6711 6712 MachineMemOperand::Flags MMOFlags = 6713 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6714 SmallVector<SDValue, 16> OutLoadChains; 6715 SmallVector<SDValue, 16> OutStoreChains; 6716 SmallVector<SDValue, 32> OutChains; 6717 unsigned NumMemOps = MemOps.size(); 6718 uint64_t SrcOff = 0, DstOff = 0; 6719 for (unsigned i = 0; i != NumMemOps; ++i) { 6720 EVT VT = MemOps[i]; 6721 unsigned VTSize = VT.getSizeInBits() / 8; 6722 SDValue Value, Store; 6723 6724 if (VTSize > Size) { 6725 // Issuing an unaligned load / store pair that overlaps with the previous 6726 // pair. Adjust the offset accordingly. 6727 assert(i == NumMemOps-1 && i != 0); 6728 SrcOff -= VTSize - Size; 6729 DstOff -= VTSize - Size; 6730 } 6731 6732 if (CopyFromConstant && 6733 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6734 // It's unlikely a store of a vector immediate can be done in a single 6735 // instruction. It would require a load from a constantpool first. 6736 // We only handle zero vectors here. 6737 // FIXME: Handle other cases where store of vector immediate is done in 6738 // a single instruction. 6739 ConstantDataArraySlice SubSlice; 6740 if (SrcOff < Slice.Length) { 6741 SubSlice = Slice; 6742 SubSlice.move(SrcOff); 6743 } else { 6744 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6745 SubSlice.Array = nullptr; 6746 SubSlice.Offset = 0; 6747 SubSlice.Length = VTSize; 6748 } 6749 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6750 if (Value.getNode()) { 6751 Store = DAG.getStore( 6752 Chain, dl, Value, 6753 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6754 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6755 OutChains.push_back(Store); 6756 } 6757 } 6758 6759 if (!Store.getNode()) { 6760 // The type might not be legal for the target. This should only happen 6761 // if the type is smaller than a legal type, as on PPC, so the right 6762 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6763 // to Load/Store if NVT==VT. 6764 // FIXME does the case above also need this? 6765 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6766 assert(NVT.bitsGE(VT)); 6767 6768 bool isDereferenceable = 6769 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6770 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6771 if (isDereferenceable) 6772 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6773 6774 Value = DAG.getExtLoad( 6775 ISD::EXTLOAD, dl, NVT, Chain, 6776 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6777 SrcPtrInfo.getWithOffset(SrcOff), VT, 6778 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo); 6779 OutLoadChains.push_back(Value.getValue(1)); 6780 6781 Store = DAG.getTruncStore( 6782 Chain, dl, Value, 6783 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6784 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo); 6785 OutStoreChains.push_back(Store); 6786 } 6787 SrcOff += VTSize; 6788 DstOff += VTSize; 6789 Size -= VTSize; 6790 } 6791 6792 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6793 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6794 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6795 6796 if (NumLdStInMemcpy) { 6797 // It may be that memcpy might be converted to memset if it's memcpy 6798 // of constants. In such a case, we won't have loads and stores, but 6799 // just stores. In the absence of loads, there is nothing to gang up. 6800 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6801 // If target does not care, just leave as it. 6802 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6803 OutChains.push_back(OutLoadChains[i]); 6804 OutChains.push_back(OutStoreChains[i]); 6805 } 6806 } else { 6807 // Ld/St less than/equal limit set by target. 6808 if (NumLdStInMemcpy <= GluedLdStLimit) { 6809 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6810 NumLdStInMemcpy, OutLoadChains, 6811 OutStoreChains); 6812 } else { 6813 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6814 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6815 unsigned GlueIter = 0; 6816 6817 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6818 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6819 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6820 6821 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6822 OutLoadChains, OutStoreChains); 6823 GlueIter += GluedLdStLimit; 6824 } 6825 6826 // Residual ld/st. 6827 if (RemainingLdStInMemcpy) { 6828 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6829 RemainingLdStInMemcpy, OutLoadChains, 6830 OutStoreChains); 6831 } 6832 } 6833 } 6834 } 6835 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6836 } 6837 6838 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6839 SDValue Chain, SDValue Dst, SDValue Src, 6840 uint64_t Size, Align Alignment, 6841 bool isVol, bool AlwaysInline, 6842 MachinePointerInfo DstPtrInfo, 6843 MachinePointerInfo SrcPtrInfo, 6844 const AAMDNodes &AAInfo) { 6845 // Turn a memmove of undef to nop. 6846 // FIXME: We need to honor volatile even is Src is undef. 6847 if (Src.isUndef()) 6848 return Chain; 6849 6850 // Expand memmove to a series of load and store ops if the size operand falls 6851 // below a certain threshold. 6852 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6853 const DataLayout &DL = DAG.getDataLayout(); 6854 LLVMContext &C = *DAG.getContext(); 6855 std::vector<EVT> MemOps; 6856 bool DstAlignCanChange = false; 6857 MachineFunction &MF = DAG.getMachineFunction(); 6858 MachineFrameInfo &MFI = MF.getFrameInfo(); 6859 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6860 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6861 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6862 DstAlignCanChange = true; 6863 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6864 if (!SrcAlign || Alignment > *SrcAlign) 6865 SrcAlign = Alignment; 6866 assert(SrcAlign && "SrcAlign must be set"); 6867 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6868 if (!TLI.findOptimalMemOpLowering( 6869 MemOps, Limit, 6870 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6871 /*IsVolatile*/ true), 6872 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6873 MF.getFunction().getAttributes())) 6874 return SDValue(); 6875 6876 if (DstAlignCanChange) { 6877 Type *Ty = MemOps[0].getTypeForEVT(C); 6878 Align NewAlign = DL.getABITypeAlign(Ty); 6879 if (NewAlign > Alignment) { 6880 // Give the stack frame object a larger alignment if needed. 6881 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6882 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6883 Alignment = NewAlign; 6884 } 6885 } 6886 6887 // Prepare AAInfo for loads/stores after lowering this memmove. 6888 AAMDNodes NewAAInfo = AAInfo; 6889 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6890 6891 MachineMemOperand::Flags MMOFlags = 6892 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6893 uint64_t SrcOff = 0, DstOff = 0; 6894 SmallVector<SDValue, 8> LoadValues; 6895 SmallVector<SDValue, 8> LoadChains; 6896 SmallVector<SDValue, 8> OutChains; 6897 unsigned NumMemOps = MemOps.size(); 6898 for (unsigned i = 0; i < NumMemOps; i++) { 6899 EVT VT = MemOps[i]; 6900 unsigned VTSize = VT.getSizeInBits() / 8; 6901 SDValue Value; 6902 6903 bool isDereferenceable = 6904 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6905 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6906 if (isDereferenceable) 6907 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6908 6909 Value = DAG.getLoad( 6910 VT, dl, Chain, 6911 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6912 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo); 6913 LoadValues.push_back(Value); 6914 LoadChains.push_back(Value.getValue(1)); 6915 SrcOff += VTSize; 6916 } 6917 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6918 OutChains.clear(); 6919 for (unsigned i = 0; i < NumMemOps; i++) { 6920 EVT VT = MemOps[i]; 6921 unsigned VTSize = VT.getSizeInBits() / 8; 6922 SDValue Store; 6923 6924 Store = DAG.getStore( 6925 Chain, dl, LoadValues[i], 6926 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6927 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6928 OutChains.push_back(Store); 6929 DstOff += VTSize; 6930 } 6931 6932 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6933 } 6934 6935 /// Lower the call to 'memset' intrinsic function into a series of store 6936 /// operations. 6937 /// 6938 /// \param DAG Selection DAG where lowered code is placed. 6939 /// \param dl Link to corresponding IR location. 6940 /// \param Chain Control flow dependency. 6941 /// \param Dst Pointer to destination memory location. 6942 /// \param Src Value of byte to write into the memory. 6943 /// \param Size Number of bytes to write. 6944 /// \param Alignment Alignment of the destination in bytes. 6945 /// \param isVol True if destination is volatile. 6946 /// \param DstPtrInfo IR information on the memory pointer. 6947 /// \returns New head in the control flow, if lowering was successful, empty 6948 /// SDValue otherwise. 6949 /// 6950 /// The function tries to replace 'llvm.memset' intrinsic with several store 6951 /// operations and value calculation code. This is usually profitable for small 6952 /// memory size. 6953 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 6954 SDValue Chain, SDValue Dst, SDValue Src, 6955 uint64_t Size, Align Alignment, bool isVol, 6956 MachinePointerInfo DstPtrInfo, 6957 const AAMDNodes &AAInfo) { 6958 // Turn a memset of undef to nop. 6959 // FIXME: We need to honor volatile even is Src is undef. 6960 if (Src.isUndef()) 6961 return Chain; 6962 6963 // Expand memset to a series of load/store ops if the size operand 6964 // falls below a certain threshold. 6965 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6966 std::vector<EVT> MemOps; 6967 bool DstAlignCanChange = false; 6968 MachineFunction &MF = DAG.getMachineFunction(); 6969 MachineFrameInfo &MFI = MF.getFrameInfo(); 6970 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6971 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6972 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6973 DstAlignCanChange = true; 6974 bool IsZeroVal = 6975 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero(); 6976 if (!TLI.findOptimalMemOpLowering( 6977 MemOps, TLI.getMaxStoresPerMemset(OptSize), 6978 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 6979 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 6980 return SDValue(); 6981 6982 if (DstAlignCanChange) { 6983 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 6984 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 6985 if (NewAlign > Alignment) { 6986 // Give the stack frame object a larger alignment if needed. 6987 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6988 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6989 Alignment = NewAlign; 6990 } 6991 } 6992 6993 SmallVector<SDValue, 8> OutChains; 6994 uint64_t DstOff = 0; 6995 unsigned NumMemOps = MemOps.size(); 6996 6997 // Find the largest store and generate the bit pattern for it. 6998 EVT LargestVT = MemOps[0]; 6999 for (unsigned i = 1; i < NumMemOps; i++) 7000 if (MemOps[i].bitsGT(LargestVT)) 7001 LargestVT = MemOps[i]; 7002 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 7003 7004 // Prepare AAInfo for loads/stores after lowering this memset. 7005 AAMDNodes NewAAInfo = AAInfo; 7006 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 7007 7008 for (unsigned i = 0; i < NumMemOps; i++) { 7009 EVT VT = MemOps[i]; 7010 unsigned VTSize = VT.getSizeInBits() / 8; 7011 if (VTSize > Size) { 7012 // Issuing an unaligned load / store pair that overlaps with the previous 7013 // pair. Adjust the offset accordingly. 7014 assert(i == NumMemOps-1 && i != 0); 7015 DstOff -= VTSize - Size; 7016 } 7017 7018 // If this store is smaller than the largest store see whether we can get 7019 // the smaller value for free with a truncate. 7020 SDValue Value = MemSetValue; 7021 if (VT.bitsLT(LargestVT)) { 7022 if (!LargestVT.isVector() && !VT.isVector() && 7023 TLI.isTruncateFree(LargestVT, VT)) 7024 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 7025 else 7026 Value = getMemsetValue(Src, VT, DAG, dl); 7027 } 7028 assert(Value.getValueType() == VT && "Value with wrong type."); 7029 SDValue Store = DAG.getStore( 7030 Chain, dl, Value, 7031 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 7032 DstPtrInfo.getWithOffset(DstOff), Alignment, 7033 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone, 7034 NewAAInfo); 7035 OutChains.push_back(Store); 7036 DstOff += VT.getSizeInBits() / 8; 7037 Size -= VTSize; 7038 } 7039 7040 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 7041 } 7042 7043 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 7044 unsigned AS) { 7045 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 7046 // pointer operands can be losslessly bitcasted to pointers of address space 0 7047 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 7048 report_fatal_error("cannot lower memory intrinsic in address space " + 7049 Twine(AS)); 7050 } 7051 } 7052 7053 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 7054 SDValue Src, SDValue Size, Align Alignment, 7055 bool isVol, bool AlwaysInline, bool isTailCall, 7056 MachinePointerInfo DstPtrInfo, 7057 MachinePointerInfo SrcPtrInfo, 7058 const AAMDNodes &AAInfo) { 7059 // Check to see if we should lower the memcpy to loads and stores first. 7060 // For cases within the target-specified limits, this is the best choice. 7061 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7062 if (ConstantSize) { 7063 // Memcpy with size zero? Just return the original chain. 7064 if (ConstantSize->isZero()) 7065 return Chain; 7066 7067 SDValue Result = getMemcpyLoadsAndStores( 7068 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7069 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7070 if (Result.getNode()) 7071 return Result; 7072 } 7073 7074 // Then check to see if we should lower the memcpy with target-specific 7075 // code. If the target chooses to do this, this is the next best. 7076 if (TSI) { 7077 SDValue Result = TSI->EmitTargetCodeForMemcpy( 7078 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 7079 DstPtrInfo, SrcPtrInfo); 7080 if (Result.getNode()) 7081 return Result; 7082 } 7083 7084 // If we really need inline code and the target declined to provide it, 7085 // use a (potentially long) sequence of loads and stores. 7086 if (AlwaysInline) { 7087 assert(ConstantSize && "AlwaysInline requires a constant size!"); 7088 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 7089 ConstantSize->getZExtValue(), Alignment, 7090 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo); 7091 } 7092 7093 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7094 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7095 7096 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 7097 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 7098 // respect volatile, so they may do things like read or write memory 7099 // beyond the given memory regions. But fixing this isn't easy, and most 7100 // people don't care. 7101 7102 // Emit a library call. 7103 TargetLowering::ArgListTy Args; 7104 TargetLowering::ArgListEntry Entry; 7105 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7106 Entry.Node = Dst; Args.push_back(Entry); 7107 Entry.Node = Src; Args.push_back(Entry); 7108 7109 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7110 Entry.Node = Size; Args.push_back(Entry); 7111 // FIXME: pass in SDLoc 7112 TargetLowering::CallLoweringInfo CLI(*this); 7113 CLI.setDebugLoc(dl) 7114 .setChain(Chain) 7115 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 7116 Dst.getValueType().getTypeForEVT(*getContext()), 7117 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 7118 TLI->getPointerTy(getDataLayout())), 7119 std::move(Args)) 7120 .setDiscardResult() 7121 .setTailCall(isTailCall); 7122 7123 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7124 return CallResult.second; 7125 } 7126 7127 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 7128 SDValue Dst, unsigned DstAlign, 7129 SDValue Src, unsigned SrcAlign, 7130 SDValue Size, Type *SizeTy, 7131 unsigned ElemSz, bool isTailCall, 7132 MachinePointerInfo DstPtrInfo, 7133 MachinePointerInfo SrcPtrInfo) { 7134 // Emit a library call. 7135 TargetLowering::ArgListTy Args; 7136 TargetLowering::ArgListEntry Entry; 7137 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7138 Entry.Node = Dst; 7139 Args.push_back(Entry); 7140 7141 Entry.Node = Src; 7142 Args.push_back(Entry); 7143 7144 Entry.Ty = SizeTy; 7145 Entry.Node = Size; 7146 Args.push_back(Entry); 7147 7148 RTLIB::Libcall LibraryCall = 7149 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7150 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7151 report_fatal_error("Unsupported element size"); 7152 7153 TargetLowering::CallLoweringInfo CLI(*this); 7154 CLI.setDebugLoc(dl) 7155 .setChain(Chain) 7156 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7157 Type::getVoidTy(*getContext()), 7158 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7159 TLI->getPointerTy(getDataLayout())), 7160 std::move(Args)) 7161 .setDiscardResult() 7162 .setTailCall(isTailCall); 7163 7164 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7165 return CallResult.second; 7166 } 7167 7168 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 7169 SDValue Src, SDValue Size, Align Alignment, 7170 bool isVol, bool isTailCall, 7171 MachinePointerInfo DstPtrInfo, 7172 MachinePointerInfo SrcPtrInfo, 7173 const AAMDNodes &AAInfo) { 7174 // Check to see if we should lower the memmove to loads and stores first. 7175 // For cases within the target-specified limits, this is the best choice. 7176 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7177 if (ConstantSize) { 7178 // Memmove with size zero? Just return the original chain. 7179 if (ConstantSize->isZero()) 7180 return Chain; 7181 7182 SDValue Result = getMemmoveLoadsAndStores( 7183 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7184 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7185 if (Result.getNode()) 7186 return Result; 7187 } 7188 7189 // Then check to see if we should lower the memmove with target-specific 7190 // code. If the target chooses to do this, this is the next best. 7191 if (TSI) { 7192 SDValue Result = 7193 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 7194 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 7195 if (Result.getNode()) 7196 return Result; 7197 } 7198 7199 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7200 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7201 7202 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 7203 // not be safe. See memcpy above for more details. 7204 7205 // Emit a library call. 7206 TargetLowering::ArgListTy Args; 7207 TargetLowering::ArgListEntry Entry; 7208 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7209 Entry.Node = Dst; Args.push_back(Entry); 7210 Entry.Node = Src; Args.push_back(Entry); 7211 7212 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7213 Entry.Node = Size; Args.push_back(Entry); 7214 // FIXME: pass in SDLoc 7215 TargetLowering::CallLoweringInfo CLI(*this); 7216 CLI.setDebugLoc(dl) 7217 .setChain(Chain) 7218 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 7219 Dst.getValueType().getTypeForEVT(*getContext()), 7220 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 7221 TLI->getPointerTy(getDataLayout())), 7222 std::move(Args)) 7223 .setDiscardResult() 7224 .setTailCall(isTailCall); 7225 7226 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7227 return CallResult.second; 7228 } 7229 7230 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 7231 SDValue Dst, unsigned DstAlign, 7232 SDValue Src, unsigned SrcAlign, 7233 SDValue Size, Type *SizeTy, 7234 unsigned ElemSz, bool isTailCall, 7235 MachinePointerInfo DstPtrInfo, 7236 MachinePointerInfo SrcPtrInfo) { 7237 // Emit a library call. 7238 TargetLowering::ArgListTy Args; 7239 TargetLowering::ArgListEntry Entry; 7240 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7241 Entry.Node = Dst; 7242 Args.push_back(Entry); 7243 7244 Entry.Node = Src; 7245 Args.push_back(Entry); 7246 7247 Entry.Ty = SizeTy; 7248 Entry.Node = Size; 7249 Args.push_back(Entry); 7250 7251 RTLIB::Libcall LibraryCall = 7252 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7253 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7254 report_fatal_error("Unsupported element size"); 7255 7256 TargetLowering::CallLoweringInfo CLI(*this); 7257 CLI.setDebugLoc(dl) 7258 .setChain(Chain) 7259 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7260 Type::getVoidTy(*getContext()), 7261 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7262 TLI->getPointerTy(getDataLayout())), 7263 std::move(Args)) 7264 .setDiscardResult() 7265 .setTailCall(isTailCall); 7266 7267 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7268 return CallResult.second; 7269 } 7270 7271 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 7272 SDValue Src, SDValue Size, Align Alignment, 7273 bool isVol, bool isTailCall, 7274 MachinePointerInfo DstPtrInfo, 7275 const AAMDNodes &AAInfo) { 7276 // Check to see if we should lower the memset to stores first. 7277 // For cases within the target-specified limits, this is the best choice. 7278 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7279 if (ConstantSize) { 7280 // Memset with size zero? Just return the original chain. 7281 if (ConstantSize->isZero()) 7282 return Chain; 7283 7284 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7285 ConstantSize->getZExtValue(), Alignment, 7286 isVol, DstPtrInfo, AAInfo); 7287 7288 if (Result.getNode()) 7289 return Result; 7290 } 7291 7292 // Then check to see if we should lower the memset with target-specific 7293 // code. If the target chooses to do this, this is the next best. 7294 if (TSI) { 7295 SDValue Result = TSI->EmitTargetCodeForMemset( 7296 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo); 7297 if (Result.getNode()) 7298 return Result; 7299 } 7300 7301 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7302 7303 // Emit a library call. 7304 TargetLowering::ArgListTy Args; 7305 TargetLowering::ArgListEntry Entry; 7306 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext()); 7307 Args.push_back(Entry); 7308 Entry.Node = Src; 7309 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 7310 Args.push_back(Entry); 7311 Entry.Node = Size; 7312 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7313 Args.push_back(Entry); 7314 7315 // FIXME: pass in SDLoc 7316 TargetLowering::CallLoweringInfo CLI(*this); 7317 CLI.setDebugLoc(dl) 7318 .setChain(Chain) 7319 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 7320 Dst.getValueType().getTypeForEVT(*getContext()), 7321 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 7322 TLI->getPointerTy(getDataLayout())), 7323 std::move(Args)) 7324 .setDiscardResult() 7325 .setTailCall(isTailCall); 7326 7327 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7328 return CallResult.second; 7329 } 7330 7331 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 7332 SDValue Dst, unsigned DstAlign, 7333 SDValue Value, SDValue Size, Type *SizeTy, 7334 unsigned ElemSz, bool isTailCall, 7335 MachinePointerInfo DstPtrInfo) { 7336 // Emit a library call. 7337 TargetLowering::ArgListTy Args; 7338 TargetLowering::ArgListEntry Entry; 7339 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7340 Entry.Node = Dst; 7341 Args.push_back(Entry); 7342 7343 Entry.Ty = Type::getInt8Ty(*getContext()); 7344 Entry.Node = Value; 7345 Args.push_back(Entry); 7346 7347 Entry.Ty = SizeTy; 7348 Entry.Node = Size; 7349 Args.push_back(Entry); 7350 7351 RTLIB::Libcall LibraryCall = 7352 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7353 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7354 report_fatal_error("Unsupported element size"); 7355 7356 TargetLowering::CallLoweringInfo CLI(*this); 7357 CLI.setDebugLoc(dl) 7358 .setChain(Chain) 7359 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7360 Type::getVoidTy(*getContext()), 7361 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7362 TLI->getPointerTy(getDataLayout())), 7363 std::move(Args)) 7364 .setDiscardResult() 7365 .setTailCall(isTailCall); 7366 7367 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7368 return CallResult.second; 7369 } 7370 7371 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7372 SDVTList VTList, ArrayRef<SDValue> Ops, 7373 MachineMemOperand *MMO) { 7374 FoldingSetNodeID ID; 7375 ID.AddInteger(MemVT.getRawBits()); 7376 AddNodeIDNode(ID, Opcode, VTList, Ops); 7377 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7378 ID.AddInteger(MMO->getFlags()); 7379 void* IP = nullptr; 7380 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7381 cast<AtomicSDNode>(E)->refineAlignment(MMO); 7382 return SDValue(E, 0); 7383 } 7384 7385 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7386 VTList, MemVT, MMO); 7387 createOperands(N, Ops); 7388 7389 CSEMap.InsertNode(N, IP); 7390 InsertNode(N); 7391 return SDValue(N, 0); 7392 } 7393 7394 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 7395 EVT MemVT, SDVTList VTs, SDValue Chain, 7396 SDValue Ptr, SDValue Cmp, SDValue Swp, 7397 MachineMemOperand *MMO) { 7398 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 7399 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 7400 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 7401 7402 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 7403 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7404 } 7405 7406 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7407 SDValue Chain, SDValue Ptr, SDValue Val, 7408 MachineMemOperand *MMO) { 7409 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 7410 Opcode == ISD::ATOMIC_LOAD_SUB || 7411 Opcode == ISD::ATOMIC_LOAD_AND || 7412 Opcode == ISD::ATOMIC_LOAD_CLR || 7413 Opcode == ISD::ATOMIC_LOAD_OR || 7414 Opcode == ISD::ATOMIC_LOAD_XOR || 7415 Opcode == ISD::ATOMIC_LOAD_NAND || 7416 Opcode == ISD::ATOMIC_LOAD_MIN || 7417 Opcode == ISD::ATOMIC_LOAD_MAX || 7418 Opcode == ISD::ATOMIC_LOAD_UMIN || 7419 Opcode == ISD::ATOMIC_LOAD_UMAX || 7420 Opcode == ISD::ATOMIC_LOAD_FADD || 7421 Opcode == ISD::ATOMIC_LOAD_FSUB || 7422 Opcode == ISD::ATOMIC_SWAP || 7423 Opcode == ISD::ATOMIC_STORE) && 7424 "Invalid Atomic Op"); 7425 7426 EVT VT = Val.getValueType(); 7427 7428 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 7429 getVTList(VT, MVT::Other); 7430 SDValue Ops[] = {Chain, Ptr, Val}; 7431 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7432 } 7433 7434 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7435 EVT VT, SDValue Chain, SDValue Ptr, 7436 MachineMemOperand *MMO) { 7437 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 7438 7439 SDVTList VTs = getVTList(VT, MVT::Other); 7440 SDValue Ops[] = {Chain, Ptr}; 7441 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7442 } 7443 7444 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 7445 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 7446 if (Ops.size() == 1) 7447 return Ops[0]; 7448 7449 SmallVector<EVT, 4> VTs; 7450 VTs.reserve(Ops.size()); 7451 for (const SDValue &Op : Ops) 7452 VTs.push_back(Op.getValueType()); 7453 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 7454 } 7455 7456 SDValue SelectionDAG::getMemIntrinsicNode( 7457 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 7458 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 7459 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 7460 if (!Size && MemVT.isScalableVector()) 7461 Size = MemoryLocation::UnknownSize; 7462 else if (!Size) 7463 Size = MemVT.getStoreSize(); 7464 7465 MachineFunction &MF = getMachineFunction(); 7466 MachineMemOperand *MMO = 7467 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 7468 7469 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 7470 } 7471 7472 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 7473 SDVTList VTList, 7474 ArrayRef<SDValue> Ops, EVT MemVT, 7475 MachineMemOperand *MMO) { 7476 assert((Opcode == ISD::INTRINSIC_VOID || 7477 Opcode == ISD::INTRINSIC_W_CHAIN || 7478 Opcode == ISD::PREFETCH || 7479 ((int)Opcode <= std::numeric_limits<int>::max() && 7480 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 7481 "Opcode is not a memory-accessing opcode!"); 7482 7483 // Memoize the node unless it returns a flag. 7484 MemIntrinsicSDNode *N; 7485 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7486 FoldingSetNodeID ID; 7487 AddNodeIDNode(ID, Opcode, VTList, Ops); 7488 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 7489 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 7490 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7491 ID.AddInteger(MMO->getFlags()); 7492 void *IP = nullptr; 7493 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7494 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 7495 return SDValue(E, 0); 7496 } 7497 7498 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7499 VTList, MemVT, MMO); 7500 createOperands(N, Ops); 7501 7502 CSEMap.InsertNode(N, IP); 7503 } else { 7504 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7505 VTList, MemVT, MMO); 7506 createOperands(N, Ops); 7507 } 7508 InsertNode(N); 7509 SDValue V(N, 0); 7510 NewSDValueDbgMsg(V, "Creating new node: ", this); 7511 return V; 7512 } 7513 7514 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 7515 SDValue Chain, int FrameIndex, 7516 int64_t Size, int64_t Offset) { 7517 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 7518 const auto VTs = getVTList(MVT::Other); 7519 SDValue Ops[2] = { 7520 Chain, 7521 getFrameIndex(FrameIndex, 7522 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 7523 true)}; 7524 7525 FoldingSetNodeID ID; 7526 AddNodeIDNode(ID, Opcode, VTs, Ops); 7527 ID.AddInteger(FrameIndex); 7528 ID.AddInteger(Size); 7529 ID.AddInteger(Offset); 7530 void *IP = nullptr; 7531 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7532 return SDValue(E, 0); 7533 7534 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 7535 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 7536 createOperands(N, Ops); 7537 CSEMap.InsertNode(N, IP); 7538 InsertNode(N); 7539 SDValue V(N, 0); 7540 NewSDValueDbgMsg(V, "Creating new node: ", this); 7541 return V; 7542 } 7543 7544 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 7545 uint64_t Guid, uint64_t Index, 7546 uint32_t Attr) { 7547 const unsigned Opcode = ISD::PSEUDO_PROBE; 7548 const auto VTs = getVTList(MVT::Other); 7549 SDValue Ops[] = {Chain}; 7550 FoldingSetNodeID ID; 7551 AddNodeIDNode(ID, Opcode, VTs, Ops); 7552 ID.AddInteger(Guid); 7553 ID.AddInteger(Index); 7554 void *IP = nullptr; 7555 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 7556 return SDValue(E, 0); 7557 7558 auto *N = newSDNode<PseudoProbeSDNode>( 7559 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 7560 createOperands(N, Ops); 7561 CSEMap.InsertNode(N, IP); 7562 InsertNode(N); 7563 SDValue V(N, 0); 7564 NewSDValueDbgMsg(V, "Creating new node: ", this); 7565 return V; 7566 } 7567 7568 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7569 /// MachinePointerInfo record from it. This is particularly useful because the 7570 /// code generator has many cases where it doesn't bother passing in a 7571 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7572 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7573 SelectionDAG &DAG, SDValue Ptr, 7574 int64_t Offset = 0) { 7575 // If this is FI+Offset, we can model it. 7576 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7577 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7578 FI->getIndex(), Offset); 7579 7580 // If this is (FI+Offset1)+Offset2, we can model it. 7581 if (Ptr.getOpcode() != ISD::ADD || 7582 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7583 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7584 return Info; 7585 7586 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7587 return MachinePointerInfo::getFixedStack( 7588 DAG.getMachineFunction(), FI, 7589 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7590 } 7591 7592 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7593 /// MachinePointerInfo record from it. This is particularly useful because the 7594 /// code generator has many cases where it doesn't bother passing in a 7595 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7596 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7597 SelectionDAG &DAG, SDValue Ptr, 7598 SDValue OffsetOp) { 7599 // If the 'Offset' value isn't a constant, we can't handle this. 7600 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7601 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7602 if (OffsetOp.isUndef()) 7603 return InferPointerInfo(Info, DAG, Ptr); 7604 return Info; 7605 } 7606 7607 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7608 EVT VT, const SDLoc &dl, SDValue Chain, 7609 SDValue Ptr, SDValue Offset, 7610 MachinePointerInfo PtrInfo, EVT MemVT, 7611 Align Alignment, 7612 MachineMemOperand::Flags MMOFlags, 7613 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7614 assert(Chain.getValueType() == MVT::Other && 7615 "Invalid chain type"); 7616 7617 MMOFlags |= MachineMemOperand::MOLoad; 7618 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7619 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7620 // clients. 7621 if (PtrInfo.V.isNull()) 7622 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7623 7624 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7625 MachineFunction &MF = getMachineFunction(); 7626 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7627 Alignment, AAInfo, Ranges); 7628 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7629 } 7630 7631 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7632 EVT VT, const SDLoc &dl, SDValue Chain, 7633 SDValue Ptr, SDValue Offset, EVT MemVT, 7634 MachineMemOperand *MMO) { 7635 if (VT == MemVT) { 7636 ExtType = ISD::NON_EXTLOAD; 7637 } else if (ExtType == ISD::NON_EXTLOAD) { 7638 assert(VT == MemVT && "Non-extending load from different memory type!"); 7639 } else { 7640 // Extending load. 7641 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7642 "Should only be an extending load, not truncating!"); 7643 assert(VT.isInteger() == MemVT.isInteger() && 7644 "Cannot convert from FP to Int or Int -> FP!"); 7645 assert(VT.isVector() == MemVT.isVector() && 7646 "Cannot use an ext load to convert to or from a vector!"); 7647 assert((!VT.isVector() || 7648 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7649 "Cannot use an ext load to change the number of vector elements!"); 7650 } 7651 7652 bool Indexed = AM != ISD::UNINDEXED; 7653 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7654 7655 SDVTList VTs = Indexed ? 7656 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7657 SDValue Ops[] = { Chain, Ptr, Offset }; 7658 FoldingSetNodeID ID; 7659 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7660 ID.AddInteger(MemVT.getRawBits()); 7661 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7662 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7663 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7664 ID.AddInteger(MMO->getFlags()); 7665 void *IP = nullptr; 7666 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7667 cast<LoadSDNode>(E)->refineAlignment(MMO); 7668 return SDValue(E, 0); 7669 } 7670 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7671 ExtType, MemVT, MMO); 7672 createOperands(N, Ops); 7673 7674 CSEMap.InsertNode(N, IP); 7675 InsertNode(N); 7676 SDValue V(N, 0); 7677 NewSDValueDbgMsg(V, "Creating new node: ", this); 7678 return V; 7679 } 7680 7681 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7682 SDValue Ptr, MachinePointerInfo PtrInfo, 7683 MaybeAlign Alignment, 7684 MachineMemOperand::Flags MMOFlags, 7685 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7686 SDValue Undef = getUNDEF(Ptr.getValueType()); 7687 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7688 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7689 } 7690 7691 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7692 SDValue Ptr, MachineMemOperand *MMO) { 7693 SDValue Undef = getUNDEF(Ptr.getValueType()); 7694 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7695 VT, MMO); 7696 } 7697 7698 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7699 EVT VT, SDValue Chain, SDValue Ptr, 7700 MachinePointerInfo PtrInfo, EVT MemVT, 7701 MaybeAlign Alignment, 7702 MachineMemOperand::Flags MMOFlags, 7703 const AAMDNodes &AAInfo) { 7704 SDValue Undef = getUNDEF(Ptr.getValueType()); 7705 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7706 MemVT, Alignment, MMOFlags, AAInfo); 7707 } 7708 7709 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7710 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7711 MachineMemOperand *MMO) { 7712 SDValue Undef = getUNDEF(Ptr.getValueType()); 7713 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7714 MemVT, MMO); 7715 } 7716 7717 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7718 SDValue Base, SDValue Offset, 7719 ISD::MemIndexedMode AM) { 7720 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7721 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7722 // Don't propagate the invariant or dereferenceable flags. 7723 auto MMOFlags = 7724 LD->getMemOperand()->getFlags() & 7725 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7726 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7727 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7728 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7729 } 7730 7731 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7732 SDValue Ptr, MachinePointerInfo PtrInfo, 7733 Align Alignment, 7734 MachineMemOperand::Flags MMOFlags, 7735 const AAMDNodes &AAInfo) { 7736 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7737 7738 MMOFlags |= MachineMemOperand::MOStore; 7739 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7740 7741 if (PtrInfo.V.isNull()) 7742 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7743 7744 MachineFunction &MF = getMachineFunction(); 7745 uint64_t Size = 7746 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7747 MachineMemOperand *MMO = 7748 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7749 return getStore(Chain, dl, Val, Ptr, MMO); 7750 } 7751 7752 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7753 SDValue Ptr, MachineMemOperand *MMO) { 7754 assert(Chain.getValueType() == MVT::Other && 7755 "Invalid chain type"); 7756 EVT VT = Val.getValueType(); 7757 SDVTList VTs = getVTList(MVT::Other); 7758 SDValue Undef = getUNDEF(Ptr.getValueType()); 7759 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7760 FoldingSetNodeID ID; 7761 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7762 ID.AddInteger(VT.getRawBits()); 7763 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7764 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7765 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7766 ID.AddInteger(MMO->getFlags()); 7767 void *IP = nullptr; 7768 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7769 cast<StoreSDNode>(E)->refineAlignment(MMO); 7770 return SDValue(E, 0); 7771 } 7772 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7773 ISD::UNINDEXED, false, VT, MMO); 7774 createOperands(N, Ops); 7775 7776 CSEMap.InsertNode(N, IP); 7777 InsertNode(N); 7778 SDValue V(N, 0); 7779 NewSDValueDbgMsg(V, "Creating new node: ", this); 7780 return V; 7781 } 7782 7783 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7784 SDValue Ptr, MachinePointerInfo PtrInfo, 7785 EVT SVT, Align Alignment, 7786 MachineMemOperand::Flags MMOFlags, 7787 const AAMDNodes &AAInfo) { 7788 assert(Chain.getValueType() == MVT::Other && 7789 "Invalid chain type"); 7790 7791 MMOFlags |= MachineMemOperand::MOStore; 7792 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7793 7794 if (PtrInfo.V.isNull()) 7795 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7796 7797 MachineFunction &MF = getMachineFunction(); 7798 MachineMemOperand *MMO = MF.getMachineMemOperand( 7799 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7800 Alignment, AAInfo); 7801 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7802 } 7803 7804 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7805 SDValue Ptr, EVT SVT, 7806 MachineMemOperand *MMO) { 7807 EVT VT = Val.getValueType(); 7808 7809 assert(Chain.getValueType() == MVT::Other && 7810 "Invalid chain type"); 7811 if (VT == SVT) 7812 return getStore(Chain, dl, Val, Ptr, MMO); 7813 7814 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7815 "Should only be a truncating store, not extending!"); 7816 assert(VT.isInteger() == SVT.isInteger() && 7817 "Can't do FP-INT conversion!"); 7818 assert(VT.isVector() == SVT.isVector() && 7819 "Cannot use trunc store to convert to or from a vector!"); 7820 assert((!VT.isVector() || 7821 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7822 "Cannot use trunc store to change the number of vector elements!"); 7823 7824 SDVTList VTs = getVTList(MVT::Other); 7825 SDValue Undef = getUNDEF(Ptr.getValueType()); 7826 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7827 FoldingSetNodeID ID; 7828 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7829 ID.AddInteger(SVT.getRawBits()); 7830 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7831 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7832 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7833 ID.AddInteger(MMO->getFlags()); 7834 void *IP = nullptr; 7835 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7836 cast<StoreSDNode>(E)->refineAlignment(MMO); 7837 return SDValue(E, 0); 7838 } 7839 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7840 ISD::UNINDEXED, true, SVT, MMO); 7841 createOperands(N, Ops); 7842 7843 CSEMap.InsertNode(N, IP); 7844 InsertNode(N); 7845 SDValue V(N, 0); 7846 NewSDValueDbgMsg(V, "Creating new node: ", this); 7847 return V; 7848 } 7849 7850 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7851 SDValue Base, SDValue Offset, 7852 ISD::MemIndexedMode AM) { 7853 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7854 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7855 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7856 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7857 FoldingSetNodeID ID; 7858 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7859 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7860 ID.AddInteger(ST->getRawSubclassData()); 7861 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7862 ID.AddInteger(ST->getMemOperand()->getFlags()); 7863 void *IP = nullptr; 7864 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7865 return SDValue(E, 0); 7866 7867 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7868 ST->isTruncatingStore(), ST->getMemoryVT(), 7869 ST->getMemOperand()); 7870 createOperands(N, Ops); 7871 7872 CSEMap.InsertNode(N, IP); 7873 InsertNode(N); 7874 SDValue V(N, 0); 7875 NewSDValueDbgMsg(V, "Creating new node: ", this); 7876 return V; 7877 } 7878 7879 SDValue SelectionDAG::getLoadVP( 7880 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, 7881 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, 7882 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 7883 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 7884 const MDNode *Ranges, bool IsExpanding) { 7885 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7886 7887 MMOFlags |= MachineMemOperand::MOLoad; 7888 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7889 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7890 // clients. 7891 if (PtrInfo.V.isNull()) 7892 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7893 7894 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7895 MachineFunction &MF = getMachineFunction(); 7896 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7897 Alignment, AAInfo, Ranges); 7898 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT, 7899 MMO, IsExpanding); 7900 } 7901 7902 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM, 7903 ISD::LoadExtType ExtType, EVT VT, 7904 const SDLoc &dl, SDValue Chain, SDValue Ptr, 7905 SDValue Offset, SDValue Mask, SDValue EVL, 7906 EVT MemVT, MachineMemOperand *MMO, 7907 bool IsExpanding) { 7908 bool Indexed = AM != ISD::UNINDEXED; 7909 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7910 7911 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 7912 : getVTList(VT, MVT::Other); 7913 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL}; 7914 FoldingSetNodeID ID; 7915 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops); 7916 ID.AddInteger(VT.getRawBits()); 7917 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>( 7918 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 7919 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7920 ID.AddInteger(MMO->getFlags()); 7921 void *IP = nullptr; 7922 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7923 cast<VPLoadSDNode>(E)->refineAlignment(MMO); 7924 return SDValue(E, 0); 7925 } 7926 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7927 ExtType, IsExpanding, MemVT, MMO); 7928 createOperands(N, Ops); 7929 7930 CSEMap.InsertNode(N, IP); 7931 InsertNode(N); 7932 SDValue V(N, 0); 7933 NewSDValueDbgMsg(V, "Creating new node: ", this); 7934 return V; 7935 } 7936 7937 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7938 SDValue Ptr, SDValue Mask, SDValue EVL, 7939 MachinePointerInfo PtrInfo, 7940 MaybeAlign Alignment, 7941 MachineMemOperand::Flags MMOFlags, 7942 const AAMDNodes &AAInfo, const MDNode *Ranges, 7943 bool IsExpanding) { 7944 SDValue Undef = getUNDEF(Ptr.getValueType()); 7945 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7946 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges, 7947 IsExpanding); 7948 } 7949 7950 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7951 SDValue Ptr, SDValue Mask, SDValue EVL, 7952 MachineMemOperand *MMO, bool IsExpanding) { 7953 SDValue Undef = getUNDEF(Ptr.getValueType()); 7954 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7955 Mask, EVL, VT, MMO, IsExpanding); 7956 } 7957 7958 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7959 EVT VT, SDValue Chain, SDValue Ptr, 7960 SDValue Mask, SDValue EVL, 7961 MachinePointerInfo PtrInfo, EVT MemVT, 7962 MaybeAlign Alignment, 7963 MachineMemOperand::Flags MMOFlags, 7964 const AAMDNodes &AAInfo, bool IsExpanding) { 7965 SDValue Undef = getUNDEF(Ptr.getValueType()); 7966 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7967 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr, 7968 IsExpanding); 7969 } 7970 7971 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7972 EVT VT, SDValue Chain, SDValue Ptr, 7973 SDValue Mask, SDValue EVL, EVT MemVT, 7974 MachineMemOperand *MMO, bool IsExpanding) { 7975 SDValue Undef = getUNDEF(Ptr.getValueType()); 7976 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7977 EVL, MemVT, MMO, IsExpanding); 7978 } 7979 7980 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, 7981 SDValue Base, SDValue Offset, 7982 ISD::MemIndexedMode AM) { 7983 auto *LD = cast<VPLoadSDNode>(OrigLoad); 7984 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7985 // Don't propagate the invariant or dereferenceable flags. 7986 auto MMOFlags = 7987 LD->getMemOperand()->getFlags() & 7988 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7989 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7990 LD->getChain(), Base, Offset, LD->getMask(), 7991 LD->getVectorLength(), LD->getPointerInfo(), 7992 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(), 7993 nullptr, LD->isExpandingLoad()); 7994 } 7995 7996 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 7997 SDValue Ptr, SDValue Offset, SDValue Mask, 7998 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, 7999 ISD::MemIndexedMode AM, bool IsTruncating, 8000 bool IsCompressing) { 8001 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8002 bool Indexed = AM != ISD::UNINDEXED; 8003 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 8004 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 8005 : getVTList(MVT::Other); 8006 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL}; 8007 FoldingSetNodeID ID; 8008 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8009 ID.AddInteger(MemVT.getRawBits()); 8010 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8011 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8012 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8013 ID.AddInteger(MMO->getFlags()); 8014 void *IP = nullptr; 8015 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8016 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8017 return SDValue(E, 0); 8018 } 8019 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8020 IsTruncating, IsCompressing, MemVT, MMO); 8021 createOperands(N, Ops); 8022 8023 CSEMap.InsertNode(N, IP); 8024 InsertNode(N); 8025 SDValue V(N, 0); 8026 NewSDValueDbgMsg(V, "Creating new node: ", this); 8027 return V; 8028 } 8029 8030 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8031 SDValue Val, SDValue Ptr, SDValue Mask, 8032 SDValue EVL, MachinePointerInfo PtrInfo, 8033 EVT SVT, Align Alignment, 8034 MachineMemOperand::Flags MMOFlags, 8035 const AAMDNodes &AAInfo, 8036 bool IsCompressing) { 8037 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8038 8039 MMOFlags |= MachineMemOperand::MOStore; 8040 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8041 8042 if (PtrInfo.V.isNull()) 8043 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8044 8045 MachineFunction &MF = getMachineFunction(); 8046 MachineMemOperand *MMO = MF.getMachineMemOperand( 8047 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 8048 Alignment, AAInfo); 8049 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO, 8050 IsCompressing); 8051 } 8052 8053 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8054 SDValue Val, SDValue Ptr, SDValue Mask, 8055 SDValue EVL, EVT SVT, 8056 MachineMemOperand *MMO, 8057 bool IsCompressing) { 8058 EVT VT = Val.getValueType(); 8059 8060 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8061 if (VT == SVT) 8062 return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask, 8063 EVL, VT, MMO, ISD::UNINDEXED, 8064 /*IsTruncating*/ false, IsCompressing); 8065 8066 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8067 "Should only be a truncating store, not extending!"); 8068 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8069 assert(VT.isVector() == SVT.isVector() && 8070 "Cannot use trunc store to convert to or from a vector!"); 8071 assert((!VT.isVector() || 8072 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8073 "Cannot use trunc store to change the number of vector elements!"); 8074 8075 SDVTList VTs = getVTList(MVT::Other); 8076 SDValue Undef = getUNDEF(Ptr.getValueType()); 8077 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 8078 FoldingSetNodeID ID; 8079 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8080 ID.AddInteger(SVT.getRawBits()); 8081 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8082 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8083 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8084 ID.AddInteger(MMO->getFlags()); 8085 void *IP = nullptr; 8086 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8087 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8088 return SDValue(E, 0); 8089 } 8090 auto *N = 8091 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8092 ISD::UNINDEXED, true, IsCompressing, SVT, MMO); 8093 createOperands(N, Ops); 8094 8095 CSEMap.InsertNode(N, IP); 8096 InsertNode(N); 8097 SDValue V(N, 0); 8098 NewSDValueDbgMsg(V, "Creating new node: ", this); 8099 return V; 8100 } 8101 8102 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, 8103 SDValue Base, SDValue Offset, 8104 ISD::MemIndexedMode AM) { 8105 auto *ST = cast<VPStoreSDNode>(OrigStore); 8106 assert(ST->getOffset().isUndef() && "Store is already an indexed store!"); 8107 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8108 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base, 8109 Offset, ST->getMask(), ST->getVectorLength()}; 8110 FoldingSetNodeID ID; 8111 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8112 ID.AddInteger(ST->getMemoryVT().getRawBits()); 8113 ID.AddInteger(ST->getRawSubclassData()); 8114 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 8115 ID.AddInteger(ST->getMemOperand()->getFlags()); 8116 void *IP = nullptr; 8117 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 8118 return SDValue(E, 0); 8119 8120 auto *N = newSDNode<VPStoreSDNode>( 8121 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(), 8122 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand()); 8123 createOperands(N, Ops); 8124 8125 CSEMap.InsertNode(N, IP); 8126 InsertNode(N); 8127 SDValue V(N, 0); 8128 NewSDValueDbgMsg(V, "Creating new node: ", this); 8129 return V; 8130 } 8131 8132 SDValue SelectionDAG::getStridedLoadVP( 8133 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8134 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8135 SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 8136 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8137 const MDNode *Ranges, bool IsExpanding) { 8138 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8139 8140 MMOFlags |= MachineMemOperand::MOLoad; 8141 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 8142 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 8143 // clients. 8144 if (PtrInfo.V.isNull()) 8145 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 8146 8147 uint64_t Size = MemoryLocation::UnknownSize; 8148 MachineFunction &MF = getMachineFunction(); 8149 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 8150 Alignment, AAInfo, Ranges); 8151 return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask, 8152 EVL, MemVT, MMO, IsExpanding); 8153 } 8154 8155 SDValue SelectionDAG::getStridedLoadVP( 8156 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8157 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8158 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) { 8159 bool Indexed = AM != ISD::UNINDEXED; 8160 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 8161 8162 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL}; 8163 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 8164 : getVTList(VT, MVT::Other); 8165 FoldingSetNodeID ID; 8166 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops); 8167 ID.AddInteger(VT.getRawBits()); 8168 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>( 8169 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 8170 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8171 8172 void *IP = nullptr; 8173 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8174 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO); 8175 return SDValue(E, 0); 8176 } 8177 8178 auto *N = 8179 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM, 8180 ExtType, IsExpanding, MemVT, MMO); 8181 createOperands(N, Ops); 8182 CSEMap.InsertNode(N, IP); 8183 InsertNode(N); 8184 SDValue V(N, 0); 8185 NewSDValueDbgMsg(V, "Creating new node: ", this); 8186 return V; 8187 } 8188 8189 SDValue SelectionDAG::getStridedLoadVP( 8190 EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride, 8191 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment, 8192 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8193 const MDNode *Ranges, bool IsExpanding) { 8194 SDValue Undef = getUNDEF(Ptr.getValueType()); 8195 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8196 Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment, 8197 MMOFlags, AAInfo, Ranges, IsExpanding); 8198 } 8199 8200 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain, 8201 SDValue Ptr, SDValue Stride, 8202 SDValue Mask, SDValue EVL, 8203 MachineMemOperand *MMO, 8204 bool IsExpanding) { 8205 SDValue Undef = getUNDEF(Ptr.getValueType()); 8206 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8207 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding); 8208 } 8209 8210 SDValue SelectionDAG::getExtStridedLoadVP( 8211 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8212 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, 8213 MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment, 8214 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8215 bool IsExpanding) { 8216 SDValue Undef = getUNDEF(Ptr.getValueType()); 8217 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8218 Stride, Mask, EVL, PtrInfo, MemVT, Alignment, 8219 MMOFlags, AAInfo, nullptr, IsExpanding); 8220 } 8221 8222 SDValue SelectionDAG::getExtStridedLoadVP( 8223 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8224 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, 8225 MachineMemOperand *MMO, bool IsExpanding) { 8226 SDValue Undef = getUNDEF(Ptr.getValueType()); 8227 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8228 Stride, Mask, EVL, MemVT, MMO, IsExpanding); 8229 } 8230 8231 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL, 8232 SDValue Base, SDValue Offset, 8233 ISD::MemIndexedMode AM) { 8234 auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad); 8235 assert(SLD->getOffset().isUndef() && 8236 "Strided load is already a indexed load!"); 8237 // Don't propagate the invariant or dereferenceable flags. 8238 auto MMOFlags = 8239 SLD->getMemOperand()->getFlags() & 8240 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8241 return getStridedLoadVP( 8242 AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(), 8243 Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(), 8244 SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags, 8245 SLD->getAAInfo(), nullptr, SLD->isExpandingLoad()); 8246 } 8247 8248 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL, 8249 SDValue Val, SDValue Ptr, 8250 SDValue Offset, SDValue Stride, 8251 SDValue Mask, SDValue EVL, EVT MemVT, 8252 MachineMemOperand *MMO, 8253 ISD::MemIndexedMode AM, 8254 bool IsTruncating, bool IsCompressing) { 8255 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8256 bool Indexed = AM != ISD::UNINDEXED; 8257 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 8258 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 8259 : getVTList(MVT::Other); 8260 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL}; 8261 FoldingSetNodeID ID; 8262 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8263 ID.AddInteger(MemVT.getRawBits()); 8264 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8265 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8266 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8267 void *IP = nullptr; 8268 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8269 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8270 return SDValue(E, 0); 8271 } 8272 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8273 VTs, AM, IsTruncating, 8274 IsCompressing, MemVT, MMO); 8275 createOperands(N, Ops); 8276 8277 CSEMap.InsertNode(N, IP); 8278 InsertNode(N); 8279 SDValue V(N, 0); 8280 NewSDValueDbgMsg(V, "Creating new node: ", this); 8281 return V; 8282 } 8283 8284 SDValue SelectionDAG::getTruncStridedStoreVP( 8285 SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride, 8286 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT, 8287 Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8288 bool IsCompressing) { 8289 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8290 8291 MMOFlags |= MachineMemOperand::MOStore; 8292 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8293 8294 if (PtrInfo.V.isNull()) 8295 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8296 8297 MachineFunction &MF = getMachineFunction(); 8298 MachineMemOperand *MMO = MF.getMachineMemOperand( 8299 PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo); 8300 return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT, 8301 MMO, IsCompressing); 8302 } 8303 8304 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL, 8305 SDValue Val, SDValue Ptr, 8306 SDValue Stride, SDValue Mask, 8307 SDValue EVL, EVT SVT, 8308 MachineMemOperand *MMO, 8309 bool IsCompressing) { 8310 EVT VT = Val.getValueType(); 8311 8312 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8313 if (VT == SVT) 8314 return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()), 8315 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED, 8316 /*IsTruncating*/ false, IsCompressing); 8317 8318 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8319 "Should only be a truncating store, not extending!"); 8320 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8321 assert(VT.isVector() == SVT.isVector() && 8322 "Cannot use trunc store to convert to or from a vector!"); 8323 assert((!VT.isVector() || 8324 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8325 "Cannot use trunc store to change the number of vector elements!"); 8326 8327 SDVTList VTs = getVTList(MVT::Other); 8328 SDValue Undef = getUNDEF(Ptr.getValueType()); 8329 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL}; 8330 FoldingSetNodeID ID; 8331 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8332 ID.AddInteger(SVT.getRawBits()); 8333 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8334 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8335 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8336 void *IP = nullptr; 8337 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8338 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8339 return SDValue(E, 0); 8340 } 8341 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8342 VTs, ISD::UNINDEXED, true, 8343 IsCompressing, SVT, MMO); 8344 createOperands(N, Ops); 8345 8346 CSEMap.InsertNode(N, IP); 8347 InsertNode(N); 8348 SDValue V(N, 0); 8349 NewSDValueDbgMsg(V, "Creating new node: ", this); 8350 return V; 8351 } 8352 8353 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore, 8354 const SDLoc &DL, SDValue Base, 8355 SDValue Offset, 8356 ISD::MemIndexedMode AM) { 8357 auto *SST = cast<VPStridedStoreSDNode>(OrigStore); 8358 assert(SST->getOffset().isUndef() && 8359 "Strided store is already an indexed store!"); 8360 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8361 SDValue Ops[] = { 8362 SST->getChain(), SST->getValue(), Base, Offset, SST->getStride(), 8363 SST->getMask(), SST->getVectorLength()}; 8364 FoldingSetNodeID ID; 8365 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8366 ID.AddInteger(SST->getMemoryVT().getRawBits()); 8367 ID.AddInteger(SST->getRawSubclassData()); 8368 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 8369 void *IP = nullptr; 8370 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8371 return SDValue(E, 0); 8372 8373 auto *N = newSDNode<VPStridedStoreSDNode>( 8374 DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(), 8375 SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand()); 8376 createOperands(N, Ops); 8377 8378 CSEMap.InsertNode(N, IP); 8379 InsertNode(N); 8380 SDValue V(N, 0); 8381 NewSDValueDbgMsg(V, "Creating new node: ", this); 8382 return V; 8383 } 8384 8385 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8386 ArrayRef<SDValue> Ops, MachineMemOperand *MMO, 8387 ISD::MemIndexType IndexType) { 8388 assert(Ops.size() == 6 && "Incompatible number of operands"); 8389 8390 FoldingSetNodeID ID; 8391 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops); 8392 ID.AddInteger(VT.getRawBits()); 8393 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>( 8394 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8395 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8396 ID.AddInteger(MMO->getFlags()); 8397 void *IP = nullptr; 8398 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8399 cast<VPGatherSDNode>(E)->refineAlignment(MMO); 8400 return SDValue(E, 0); 8401 } 8402 8403 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8404 VT, MMO, IndexType); 8405 createOperands(N, Ops); 8406 8407 assert(N->getMask().getValueType().getVectorElementCount() == 8408 N->getValueType(0).getVectorElementCount() && 8409 "Vector width mismatch between mask and data"); 8410 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8411 N->getValueType(0).getVectorElementCount().isScalable() && 8412 "Scalable flags of index and data do not match"); 8413 assert(ElementCount::isKnownGE( 8414 N->getIndex().getValueType().getVectorElementCount(), 8415 N->getValueType(0).getVectorElementCount()) && 8416 "Vector width mismatch between index and data"); 8417 assert(isa<ConstantSDNode>(N->getScale()) && 8418 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8419 "Scale should be a constant power of 2"); 8420 8421 CSEMap.InsertNode(N, IP); 8422 InsertNode(N); 8423 SDValue V(N, 0); 8424 NewSDValueDbgMsg(V, "Creating new node: ", this); 8425 return V; 8426 } 8427 8428 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8429 ArrayRef<SDValue> Ops, 8430 MachineMemOperand *MMO, 8431 ISD::MemIndexType IndexType) { 8432 assert(Ops.size() == 7 && "Incompatible number of operands"); 8433 8434 FoldingSetNodeID ID; 8435 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops); 8436 ID.AddInteger(VT.getRawBits()); 8437 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>( 8438 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8439 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8440 ID.AddInteger(MMO->getFlags()); 8441 void *IP = nullptr; 8442 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8443 cast<VPScatterSDNode>(E)->refineAlignment(MMO); 8444 return SDValue(E, 0); 8445 } 8446 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8447 VT, MMO, IndexType); 8448 createOperands(N, Ops); 8449 8450 assert(N->getMask().getValueType().getVectorElementCount() == 8451 N->getValue().getValueType().getVectorElementCount() && 8452 "Vector width mismatch between mask and data"); 8453 assert( 8454 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8455 N->getValue().getValueType().getVectorElementCount().isScalable() && 8456 "Scalable flags of index and data do not match"); 8457 assert(ElementCount::isKnownGE( 8458 N->getIndex().getValueType().getVectorElementCount(), 8459 N->getValue().getValueType().getVectorElementCount()) && 8460 "Vector width mismatch between index and data"); 8461 assert(isa<ConstantSDNode>(N->getScale()) && 8462 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8463 "Scale should be a constant power of 2"); 8464 8465 CSEMap.InsertNode(N, IP); 8466 InsertNode(N); 8467 SDValue V(N, 0); 8468 NewSDValueDbgMsg(V, "Creating new node: ", this); 8469 return V; 8470 } 8471 8472 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8473 SDValue Base, SDValue Offset, SDValue Mask, 8474 SDValue PassThru, EVT MemVT, 8475 MachineMemOperand *MMO, 8476 ISD::MemIndexedMode AM, 8477 ISD::LoadExtType ExtTy, bool isExpanding) { 8478 bool Indexed = AM != ISD::UNINDEXED; 8479 assert((Indexed || Offset.isUndef()) && 8480 "Unindexed masked load with an offset!"); 8481 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 8482 : getVTList(VT, MVT::Other); 8483 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 8484 FoldingSetNodeID ID; 8485 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 8486 ID.AddInteger(MemVT.getRawBits()); 8487 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 8488 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 8489 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8490 ID.AddInteger(MMO->getFlags()); 8491 void *IP = nullptr; 8492 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8493 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 8494 return SDValue(E, 0); 8495 } 8496 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8497 AM, ExtTy, isExpanding, MemVT, MMO); 8498 createOperands(N, Ops); 8499 8500 CSEMap.InsertNode(N, IP); 8501 InsertNode(N); 8502 SDValue V(N, 0); 8503 NewSDValueDbgMsg(V, "Creating new node: ", this); 8504 return V; 8505 } 8506 8507 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 8508 SDValue Base, SDValue Offset, 8509 ISD::MemIndexedMode AM) { 8510 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 8511 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 8512 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 8513 Offset, LD->getMask(), LD->getPassThru(), 8514 LD->getMemoryVT(), LD->getMemOperand(), AM, 8515 LD->getExtensionType(), LD->isExpandingLoad()); 8516 } 8517 8518 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 8519 SDValue Val, SDValue Base, SDValue Offset, 8520 SDValue Mask, EVT MemVT, 8521 MachineMemOperand *MMO, 8522 ISD::MemIndexedMode AM, bool IsTruncating, 8523 bool IsCompressing) { 8524 assert(Chain.getValueType() == MVT::Other && 8525 "Invalid chain type"); 8526 bool Indexed = AM != ISD::UNINDEXED; 8527 assert((Indexed || Offset.isUndef()) && 8528 "Unindexed masked store with an offset!"); 8529 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 8530 : getVTList(MVT::Other); 8531 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 8532 FoldingSetNodeID ID; 8533 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 8534 ID.AddInteger(MemVT.getRawBits()); 8535 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 8536 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8537 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8538 ID.AddInteger(MMO->getFlags()); 8539 void *IP = nullptr; 8540 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8541 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 8542 return SDValue(E, 0); 8543 } 8544 auto *N = 8545 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8546 IsTruncating, IsCompressing, MemVT, MMO); 8547 createOperands(N, Ops); 8548 8549 CSEMap.InsertNode(N, IP); 8550 InsertNode(N); 8551 SDValue V(N, 0); 8552 NewSDValueDbgMsg(V, "Creating new node: ", this); 8553 return V; 8554 } 8555 8556 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 8557 SDValue Base, SDValue Offset, 8558 ISD::MemIndexedMode AM) { 8559 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 8560 assert(ST->getOffset().isUndef() && 8561 "Masked store is already a indexed store!"); 8562 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 8563 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 8564 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 8565 } 8566 8567 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8568 ArrayRef<SDValue> Ops, 8569 MachineMemOperand *MMO, 8570 ISD::MemIndexType IndexType, 8571 ISD::LoadExtType ExtTy) { 8572 assert(Ops.size() == 6 && "Incompatible number of operands"); 8573 8574 FoldingSetNodeID ID; 8575 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 8576 ID.AddInteger(MemVT.getRawBits()); 8577 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 8578 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy)); 8579 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8580 ID.AddInteger(MMO->getFlags()); 8581 void *IP = nullptr; 8582 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8583 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 8584 return SDValue(E, 0); 8585 } 8586 8587 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8588 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8589 VTs, MemVT, MMO, IndexType, ExtTy); 8590 createOperands(N, Ops); 8591 8592 assert(N->getPassThru().getValueType() == N->getValueType(0) && 8593 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 8594 assert(N->getMask().getValueType().getVectorElementCount() == 8595 N->getValueType(0).getVectorElementCount() && 8596 "Vector width mismatch between mask and data"); 8597 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8598 N->getValueType(0).getVectorElementCount().isScalable() && 8599 "Scalable flags of index and data do not match"); 8600 assert(ElementCount::isKnownGE( 8601 N->getIndex().getValueType().getVectorElementCount(), 8602 N->getValueType(0).getVectorElementCount()) && 8603 "Vector width mismatch between index and data"); 8604 assert(isa<ConstantSDNode>(N->getScale()) && 8605 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8606 "Scale should be a constant power of 2"); 8607 8608 CSEMap.InsertNode(N, IP); 8609 InsertNode(N); 8610 SDValue V(N, 0); 8611 NewSDValueDbgMsg(V, "Creating new node: ", this); 8612 return V; 8613 } 8614 8615 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8616 ArrayRef<SDValue> Ops, 8617 MachineMemOperand *MMO, 8618 ISD::MemIndexType IndexType, 8619 bool IsTrunc) { 8620 assert(Ops.size() == 6 && "Incompatible number of operands"); 8621 8622 FoldingSetNodeID ID; 8623 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 8624 ID.AddInteger(MemVT.getRawBits()); 8625 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 8626 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc)); 8627 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8628 ID.AddInteger(MMO->getFlags()); 8629 void *IP = nullptr; 8630 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8631 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 8632 return SDValue(E, 0); 8633 } 8634 8635 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8636 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8637 VTs, MemVT, MMO, IndexType, IsTrunc); 8638 createOperands(N, Ops); 8639 8640 assert(N->getMask().getValueType().getVectorElementCount() == 8641 N->getValue().getValueType().getVectorElementCount() && 8642 "Vector width mismatch between mask and data"); 8643 assert( 8644 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8645 N->getValue().getValueType().getVectorElementCount().isScalable() && 8646 "Scalable flags of index and data do not match"); 8647 assert(ElementCount::isKnownGE( 8648 N->getIndex().getValueType().getVectorElementCount(), 8649 N->getValue().getValueType().getVectorElementCount()) && 8650 "Vector width mismatch between index and data"); 8651 assert(isa<ConstantSDNode>(N->getScale()) && 8652 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8653 "Scale should be a constant power of 2"); 8654 8655 CSEMap.InsertNode(N, IP); 8656 InsertNode(N); 8657 SDValue V(N, 0); 8658 NewSDValueDbgMsg(V, "Creating new node: ", this); 8659 return V; 8660 } 8661 8662 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 8663 // select undef, T, F --> T (if T is a constant), otherwise F 8664 // select, ?, undef, F --> F 8665 // select, ?, T, undef --> T 8666 if (Cond.isUndef()) 8667 return isConstantValueOfAnyType(T) ? T : F; 8668 if (T.isUndef()) 8669 return F; 8670 if (F.isUndef()) 8671 return T; 8672 8673 // select true, T, F --> T 8674 // select false, T, F --> F 8675 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 8676 return CondC->isZero() ? F : T; 8677 8678 // TODO: This should simplify VSELECT with constant condition using something 8679 // like this (but check boolean contents to be complete?): 8680 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 8681 // return T; 8682 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 8683 // return F; 8684 8685 // select ?, T, T --> T 8686 if (T == F) 8687 return T; 8688 8689 return SDValue(); 8690 } 8691 8692 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 8693 // shift undef, Y --> 0 (can always assume that the undef value is 0) 8694 if (X.isUndef()) 8695 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 8696 // shift X, undef --> undef (because it may shift by the bitwidth) 8697 if (Y.isUndef()) 8698 return getUNDEF(X.getValueType()); 8699 8700 // shift 0, Y --> 0 8701 // shift X, 0 --> X 8702 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 8703 return X; 8704 8705 // shift X, C >= bitwidth(X) --> undef 8706 // All vector elements must be too big (or undef) to avoid partial undefs. 8707 auto isShiftTooBig = [X](ConstantSDNode *Val) { 8708 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 8709 }; 8710 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 8711 return getUNDEF(X.getValueType()); 8712 8713 return SDValue(); 8714 } 8715 8716 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 8717 SDNodeFlags Flags) { 8718 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 8719 // (an undef operand can be chosen to be Nan/Inf), then the result of this 8720 // operation is poison. That result can be relaxed to undef. 8721 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 8722 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 8723 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 8724 (YC && YC->getValueAPF().isNaN()); 8725 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 8726 (YC && YC->getValueAPF().isInfinity()); 8727 8728 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 8729 return getUNDEF(X.getValueType()); 8730 8731 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 8732 return getUNDEF(X.getValueType()); 8733 8734 if (!YC) 8735 return SDValue(); 8736 8737 // X + -0.0 --> X 8738 if (Opcode == ISD::FADD) 8739 if (YC->getValueAPF().isNegZero()) 8740 return X; 8741 8742 // X - +0.0 --> X 8743 if (Opcode == ISD::FSUB) 8744 if (YC->getValueAPF().isPosZero()) 8745 return X; 8746 8747 // X * 1.0 --> X 8748 // X / 1.0 --> X 8749 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 8750 if (YC->getValueAPF().isExactlyValue(1.0)) 8751 return X; 8752 8753 // X * 0.0 --> 0.0 8754 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 8755 if (YC->getValueAPF().isZero()) 8756 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 8757 8758 return SDValue(); 8759 } 8760 8761 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 8762 SDValue Ptr, SDValue SV, unsigned Align) { 8763 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 8764 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 8765 } 8766 8767 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8768 ArrayRef<SDUse> Ops) { 8769 switch (Ops.size()) { 8770 case 0: return getNode(Opcode, DL, VT); 8771 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 8772 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 8773 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 8774 default: break; 8775 } 8776 8777 // Copy from an SDUse array into an SDValue array for use with 8778 // the regular getNode logic. 8779 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 8780 return getNode(Opcode, DL, VT, NewOps); 8781 } 8782 8783 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8784 ArrayRef<SDValue> Ops) { 8785 SDNodeFlags Flags; 8786 if (Inserter) 8787 Flags = Inserter->getFlags(); 8788 return getNode(Opcode, DL, VT, Ops, Flags); 8789 } 8790 8791 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8792 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8793 unsigned NumOps = Ops.size(); 8794 switch (NumOps) { 8795 case 0: return getNode(Opcode, DL, VT); 8796 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 8797 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 8798 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 8799 default: break; 8800 } 8801 8802 #ifndef NDEBUG 8803 for (auto &Op : Ops) 8804 assert(Op.getOpcode() != ISD::DELETED_NODE && 8805 "Operand is DELETED_NODE!"); 8806 #endif 8807 8808 switch (Opcode) { 8809 default: break; 8810 case ISD::BUILD_VECTOR: 8811 // Attempt to simplify BUILD_VECTOR. 8812 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 8813 return V; 8814 break; 8815 case ISD::CONCAT_VECTORS: 8816 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 8817 return V; 8818 break; 8819 case ISD::SELECT_CC: 8820 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 8821 assert(Ops[0].getValueType() == Ops[1].getValueType() && 8822 "LHS and RHS of condition must have same type!"); 8823 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8824 "True and False arms of SelectCC must have same type!"); 8825 assert(Ops[2].getValueType() == VT && 8826 "select_cc node must be of same type as true and false value!"); 8827 break; 8828 case ISD::BR_CC: 8829 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 8830 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8831 "LHS/RHS of comparison should match types!"); 8832 break; 8833 case ISD::VP_ADD: 8834 case ISD::VP_SUB: 8835 // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR 8836 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 8837 Opcode = ISD::VP_XOR; 8838 break; 8839 case ISD::VP_MUL: 8840 // If it is VP_MUL mask operation then turn it to VP_AND 8841 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 8842 Opcode = ISD::VP_AND; 8843 break; 8844 } 8845 8846 // Memoize nodes. 8847 SDNode *N; 8848 SDVTList VTs = getVTList(VT); 8849 8850 if (VT != MVT::Glue) { 8851 FoldingSetNodeID ID; 8852 AddNodeIDNode(ID, Opcode, VTs, Ops); 8853 void *IP = nullptr; 8854 8855 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8856 return SDValue(E, 0); 8857 8858 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8859 createOperands(N, Ops); 8860 8861 CSEMap.InsertNode(N, IP); 8862 } else { 8863 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8864 createOperands(N, Ops); 8865 } 8866 8867 N->setFlags(Flags); 8868 InsertNode(N); 8869 SDValue V(N, 0); 8870 NewSDValueDbgMsg(V, "Creating new node: ", this); 8871 return V; 8872 } 8873 8874 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8875 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 8876 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 8877 } 8878 8879 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8880 ArrayRef<SDValue> Ops) { 8881 SDNodeFlags Flags; 8882 if (Inserter) 8883 Flags = Inserter->getFlags(); 8884 return getNode(Opcode, DL, VTList, Ops, Flags); 8885 } 8886 8887 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8888 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8889 if (VTList.NumVTs == 1) 8890 return getNode(Opcode, DL, VTList.VTs[0], Ops); 8891 8892 #ifndef NDEBUG 8893 for (auto &Op : Ops) 8894 assert(Op.getOpcode() != ISD::DELETED_NODE && 8895 "Operand is DELETED_NODE!"); 8896 #endif 8897 8898 switch (Opcode) { 8899 case ISD::STRICT_FP_EXTEND: 8900 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 8901 "Invalid STRICT_FP_EXTEND!"); 8902 assert(VTList.VTs[0].isFloatingPoint() && 8903 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 8904 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8905 "STRICT_FP_EXTEND result type should be vector iff the operand " 8906 "type is vector!"); 8907 assert((!VTList.VTs[0].isVector() || 8908 VTList.VTs[0].getVectorNumElements() == 8909 Ops[1].getValueType().getVectorNumElements()) && 8910 "Vector element count mismatch!"); 8911 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 8912 "Invalid fpext node, dst <= src!"); 8913 break; 8914 case ISD::STRICT_FP_ROUND: 8915 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 8916 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8917 "STRICT_FP_ROUND result type should be vector iff the operand " 8918 "type is vector!"); 8919 assert((!VTList.VTs[0].isVector() || 8920 VTList.VTs[0].getVectorNumElements() == 8921 Ops[1].getValueType().getVectorNumElements()) && 8922 "Vector element count mismatch!"); 8923 assert(VTList.VTs[0].isFloatingPoint() && 8924 Ops[1].getValueType().isFloatingPoint() && 8925 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 8926 isa<ConstantSDNode>(Ops[2]) && 8927 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 8928 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 8929 "Invalid STRICT_FP_ROUND!"); 8930 break; 8931 #if 0 8932 // FIXME: figure out how to safely handle things like 8933 // int foo(int x) { return 1 << (x & 255); } 8934 // int bar() { return foo(256); } 8935 case ISD::SRA_PARTS: 8936 case ISD::SRL_PARTS: 8937 case ISD::SHL_PARTS: 8938 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 8939 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 8940 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8941 else if (N3.getOpcode() == ISD::AND) 8942 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 8943 // If the and is only masking out bits that cannot effect the shift, 8944 // eliminate the and. 8945 unsigned NumBits = VT.getScalarSizeInBits()*2; 8946 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 8947 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8948 } 8949 break; 8950 #endif 8951 } 8952 8953 // Memoize the node unless it returns a flag. 8954 SDNode *N; 8955 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 8956 FoldingSetNodeID ID; 8957 AddNodeIDNode(ID, Opcode, VTList, Ops); 8958 void *IP = nullptr; 8959 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8960 return SDValue(E, 0); 8961 8962 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8963 createOperands(N, Ops); 8964 CSEMap.InsertNode(N, IP); 8965 } else { 8966 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8967 createOperands(N, Ops); 8968 } 8969 8970 N->setFlags(Flags); 8971 InsertNode(N); 8972 SDValue V(N, 0); 8973 NewSDValueDbgMsg(V, "Creating new node: ", this); 8974 return V; 8975 } 8976 8977 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8978 SDVTList VTList) { 8979 return getNode(Opcode, DL, VTList, None); 8980 } 8981 8982 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8983 SDValue N1) { 8984 SDValue Ops[] = { N1 }; 8985 return getNode(Opcode, DL, VTList, Ops); 8986 } 8987 8988 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8989 SDValue N1, SDValue N2) { 8990 SDValue Ops[] = { N1, N2 }; 8991 return getNode(Opcode, DL, VTList, Ops); 8992 } 8993 8994 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8995 SDValue N1, SDValue N2, SDValue N3) { 8996 SDValue Ops[] = { N1, N2, N3 }; 8997 return getNode(Opcode, DL, VTList, Ops); 8998 } 8999 9000 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9001 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 9002 SDValue Ops[] = { N1, N2, N3, N4 }; 9003 return getNode(Opcode, DL, VTList, Ops); 9004 } 9005 9006 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9007 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 9008 SDValue N5) { 9009 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 9010 return getNode(Opcode, DL, VTList, Ops); 9011 } 9012 9013 SDVTList SelectionDAG::getVTList(EVT VT) { 9014 return makeVTList(SDNode::getValueTypeList(VT), 1); 9015 } 9016 9017 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 9018 FoldingSetNodeID ID; 9019 ID.AddInteger(2U); 9020 ID.AddInteger(VT1.getRawBits()); 9021 ID.AddInteger(VT2.getRawBits()); 9022 9023 void *IP = nullptr; 9024 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9025 if (!Result) { 9026 EVT *Array = Allocator.Allocate<EVT>(2); 9027 Array[0] = VT1; 9028 Array[1] = VT2; 9029 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 9030 VTListMap.InsertNode(Result, IP); 9031 } 9032 return Result->getSDVTList(); 9033 } 9034 9035 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 9036 FoldingSetNodeID ID; 9037 ID.AddInteger(3U); 9038 ID.AddInteger(VT1.getRawBits()); 9039 ID.AddInteger(VT2.getRawBits()); 9040 ID.AddInteger(VT3.getRawBits()); 9041 9042 void *IP = nullptr; 9043 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9044 if (!Result) { 9045 EVT *Array = Allocator.Allocate<EVT>(3); 9046 Array[0] = VT1; 9047 Array[1] = VT2; 9048 Array[2] = VT3; 9049 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 9050 VTListMap.InsertNode(Result, IP); 9051 } 9052 return Result->getSDVTList(); 9053 } 9054 9055 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 9056 FoldingSetNodeID ID; 9057 ID.AddInteger(4U); 9058 ID.AddInteger(VT1.getRawBits()); 9059 ID.AddInteger(VT2.getRawBits()); 9060 ID.AddInteger(VT3.getRawBits()); 9061 ID.AddInteger(VT4.getRawBits()); 9062 9063 void *IP = nullptr; 9064 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9065 if (!Result) { 9066 EVT *Array = Allocator.Allocate<EVT>(4); 9067 Array[0] = VT1; 9068 Array[1] = VT2; 9069 Array[2] = VT3; 9070 Array[3] = VT4; 9071 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 9072 VTListMap.InsertNode(Result, IP); 9073 } 9074 return Result->getSDVTList(); 9075 } 9076 9077 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 9078 unsigned NumVTs = VTs.size(); 9079 FoldingSetNodeID ID; 9080 ID.AddInteger(NumVTs); 9081 for (unsigned index = 0; index < NumVTs; index++) { 9082 ID.AddInteger(VTs[index].getRawBits()); 9083 } 9084 9085 void *IP = nullptr; 9086 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9087 if (!Result) { 9088 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 9089 llvm::copy(VTs, Array); 9090 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 9091 VTListMap.InsertNode(Result, IP); 9092 } 9093 return Result->getSDVTList(); 9094 } 9095 9096 9097 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 9098 /// specified operands. If the resultant node already exists in the DAG, 9099 /// this does not modify the specified node, instead it returns the node that 9100 /// already exists. If the resultant node does not exist in the DAG, the 9101 /// input node is returned. As a degenerate case, if you specify the same 9102 /// input operands as the node already has, the input node is returned. 9103 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 9104 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 9105 9106 // Check to see if there is no change. 9107 if (Op == N->getOperand(0)) return N; 9108 9109 // See if the modified node already exists. 9110 void *InsertPos = nullptr; 9111 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 9112 return Existing; 9113 9114 // Nope it doesn't. Remove the node from its current place in the maps. 9115 if (InsertPos) 9116 if (!RemoveNodeFromCSEMaps(N)) 9117 InsertPos = nullptr; 9118 9119 // Now we update the operands. 9120 N->OperandList[0].set(Op); 9121 9122 updateDivergence(N); 9123 // If this gets put into a CSE map, add it. 9124 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9125 return N; 9126 } 9127 9128 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 9129 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 9130 9131 // Check to see if there is no change. 9132 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 9133 return N; // No operands changed, just return the input node. 9134 9135 // See if the modified node already exists. 9136 void *InsertPos = nullptr; 9137 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 9138 return Existing; 9139 9140 // Nope it doesn't. Remove the node from its current place in the maps. 9141 if (InsertPos) 9142 if (!RemoveNodeFromCSEMaps(N)) 9143 InsertPos = nullptr; 9144 9145 // Now we update the operands. 9146 if (N->OperandList[0] != Op1) 9147 N->OperandList[0].set(Op1); 9148 if (N->OperandList[1] != Op2) 9149 N->OperandList[1].set(Op2); 9150 9151 updateDivergence(N); 9152 // If this gets put into a CSE map, add it. 9153 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9154 return N; 9155 } 9156 9157 SDNode *SelectionDAG:: 9158 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 9159 SDValue Ops[] = { Op1, Op2, Op3 }; 9160 return UpdateNodeOperands(N, Ops); 9161 } 9162 9163 SDNode *SelectionDAG:: 9164 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9165 SDValue Op3, SDValue Op4) { 9166 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 9167 return UpdateNodeOperands(N, Ops); 9168 } 9169 9170 SDNode *SelectionDAG:: 9171 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9172 SDValue Op3, SDValue Op4, SDValue Op5) { 9173 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 9174 return UpdateNodeOperands(N, Ops); 9175 } 9176 9177 SDNode *SelectionDAG:: 9178 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 9179 unsigned NumOps = Ops.size(); 9180 assert(N->getNumOperands() == NumOps && 9181 "Update with wrong number of operands"); 9182 9183 // If no operands changed just return the input node. 9184 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 9185 return N; 9186 9187 // See if the modified node already exists. 9188 void *InsertPos = nullptr; 9189 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 9190 return Existing; 9191 9192 // Nope it doesn't. Remove the node from its current place in the maps. 9193 if (InsertPos) 9194 if (!RemoveNodeFromCSEMaps(N)) 9195 InsertPos = nullptr; 9196 9197 // Now we update the operands. 9198 for (unsigned i = 0; i != NumOps; ++i) 9199 if (N->OperandList[i] != Ops[i]) 9200 N->OperandList[i].set(Ops[i]); 9201 9202 updateDivergence(N); 9203 // If this gets put into a CSE map, add it. 9204 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9205 return N; 9206 } 9207 9208 /// DropOperands - Release the operands and set this node to have 9209 /// zero operands. 9210 void SDNode::DropOperands() { 9211 // Unlike the code in MorphNodeTo that does this, we don't need to 9212 // watch for dead nodes here. 9213 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 9214 SDUse &Use = *I++; 9215 Use.set(SDValue()); 9216 } 9217 } 9218 9219 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 9220 ArrayRef<MachineMemOperand *> NewMemRefs) { 9221 if (NewMemRefs.empty()) { 9222 N->clearMemRefs(); 9223 return; 9224 } 9225 9226 // Check if we can avoid allocating by storing a single reference directly. 9227 if (NewMemRefs.size() == 1) { 9228 N->MemRefs = NewMemRefs[0]; 9229 N->NumMemRefs = 1; 9230 return; 9231 } 9232 9233 MachineMemOperand **MemRefsBuffer = 9234 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 9235 llvm::copy(NewMemRefs, MemRefsBuffer); 9236 N->MemRefs = MemRefsBuffer; 9237 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 9238 } 9239 9240 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 9241 /// machine opcode. 9242 /// 9243 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9244 EVT VT) { 9245 SDVTList VTs = getVTList(VT); 9246 return SelectNodeTo(N, MachineOpc, VTs, None); 9247 } 9248 9249 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9250 EVT VT, SDValue Op1) { 9251 SDVTList VTs = getVTList(VT); 9252 SDValue Ops[] = { Op1 }; 9253 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9254 } 9255 9256 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9257 EVT VT, SDValue Op1, 9258 SDValue Op2) { 9259 SDVTList VTs = getVTList(VT); 9260 SDValue Ops[] = { Op1, Op2 }; 9261 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9262 } 9263 9264 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9265 EVT VT, SDValue Op1, 9266 SDValue Op2, SDValue Op3) { 9267 SDVTList VTs = getVTList(VT); 9268 SDValue Ops[] = { Op1, Op2, Op3 }; 9269 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9270 } 9271 9272 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9273 EVT VT, ArrayRef<SDValue> Ops) { 9274 SDVTList VTs = getVTList(VT); 9275 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9276 } 9277 9278 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9279 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 9280 SDVTList VTs = getVTList(VT1, VT2); 9281 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9282 } 9283 9284 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9285 EVT VT1, EVT VT2) { 9286 SDVTList VTs = getVTList(VT1, VT2); 9287 return SelectNodeTo(N, MachineOpc, VTs, None); 9288 } 9289 9290 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9291 EVT VT1, EVT VT2, EVT VT3, 9292 ArrayRef<SDValue> Ops) { 9293 SDVTList VTs = getVTList(VT1, VT2, VT3); 9294 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9295 } 9296 9297 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9298 EVT VT1, EVT VT2, 9299 SDValue Op1, SDValue Op2) { 9300 SDVTList VTs = getVTList(VT1, VT2); 9301 SDValue Ops[] = { Op1, Op2 }; 9302 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9303 } 9304 9305 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9306 SDVTList VTs,ArrayRef<SDValue> Ops) { 9307 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 9308 // Reset the NodeID to -1. 9309 New->setNodeId(-1); 9310 if (New != N) { 9311 ReplaceAllUsesWith(N, New); 9312 RemoveDeadNode(N); 9313 } 9314 return New; 9315 } 9316 9317 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 9318 /// the line number information on the merged node since it is not possible to 9319 /// preserve the information that operation is associated with multiple lines. 9320 /// This will make the debugger working better at -O0, were there is a higher 9321 /// probability having other instructions associated with that line. 9322 /// 9323 /// For IROrder, we keep the smaller of the two 9324 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 9325 DebugLoc NLoc = N->getDebugLoc(); 9326 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 9327 N->setDebugLoc(DebugLoc()); 9328 } 9329 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 9330 N->setIROrder(Order); 9331 return N; 9332 } 9333 9334 /// MorphNodeTo - This *mutates* the specified node to have the specified 9335 /// return type, opcode, and operands. 9336 /// 9337 /// Note that MorphNodeTo returns the resultant node. If there is already a 9338 /// node of the specified opcode and operands, it returns that node instead of 9339 /// the current one. Note that the SDLoc need not be the same. 9340 /// 9341 /// Using MorphNodeTo is faster than creating a new node and swapping it in 9342 /// with ReplaceAllUsesWith both because it often avoids allocating a new 9343 /// node, and because it doesn't require CSE recalculation for any of 9344 /// the node's users. 9345 /// 9346 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 9347 /// As a consequence it isn't appropriate to use from within the DAG combiner or 9348 /// the legalizer which maintain worklists that would need to be updated when 9349 /// deleting things. 9350 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 9351 SDVTList VTs, ArrayRef<SDValue> Ops) { 9352 // If an identical node already exists, use it. 9353 void *IP = nullptr; 9354 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 9355 FoldingSetNodeID ID; 9356 AddNodeIDNode(ID, Opc, VTs, Ops); 9357 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 9358 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 9359 } 9360 9361 if (!RemoveNodeFromCSEMaps(N)) 9362 IP = nullptr; 9363 9364 // Start the morphing. 9365 N->NodeType = Opc; 9366 N->ValueList = VTs.VTs; 9367 N->NumValues = VTs.NumVTs; 9368 9369 // Clear the operands list, updating used nodes to remove this from their 9370 // use list. Keep track of any operands that become dead as a result. 9371 SmallPtrSet<SDNode*, 16> DeadNodeSet; 9372 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 9373 SDUse &Use = *I++; 9374 SDNode *Used = Use.getNode(); 9375 Use.set(SDValue()); 9376 if (Used->use_empty()) 9377 DeadNodeSet.insert(Used); 9378 } 9379 9380 // For MachineNode, initialize the memory references information. 9381 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 9382 MN->clearMemRefs(); 9383 9384 // Swap for an appropriately sized array from the recycler. 9385 removeOperands(N); 9386 createOperands(N, Ops); 9387 9388 // Delete any nodes that are still dead after adding the uses for the 9389 // new operands. 9390 if (!DeadNodeSet.empty()) { 9391 SmallVector<SDNode *, 16> DeadNodes; 9392 for (SDNode *N : DeadNodeSet) 9393 if (N->use_empty()) 9394 DeadNodes.push_back(N); 9395 RemoveDeadNodes(DeadNodes); 9396 } 9397 9398 if (IP) 9399 CSEMap.InsertNode(N, IP); // Memoize the new node. 9400 return N; 9401 } 9402 9403 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 9404 unsigned OrigOpc = Node->getOpcode(); 9405 unsigned NewOpc; 9406 switch (OrigOpc) { 9407 default: 9408 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 9409 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9410 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 9411 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9412 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 9413 #include "llvm/IR/ConstrainedOps.def" 9414 } 9415 9416 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 9417 9418 // We're taking this node out of the chain, so we need to re-link things. 9419 SDValue InputChain = Node->getOperand(0); 9420 SDValue OutputChain = SDValue(Node, 1); 9421 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 9422 9423 SmallVector<SDValue, 3> Ops; 9424 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 9425 Ops.push_back(Node->getOperand(i)); 9426 9427 SDVTList VTs = getVTList(Node->getValueType(0)); 9428 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 9429 9430 // MorphNodeTo can operate in two ways: if an existing node with the 9431 // specified operands exists, it can just return it. Otherwise, it 9432 // updates the node in place to have the requested operands. 9433 if (Res == Node) { 9434 // If we updated the node in place, reset the node ID. To the isel, 9435 // this should be just like a newly allocated machine node. 9436 Res->setNodeId(-1); 9437 } else { 9438 ReplaceAllUsesWith(Node, Res); 9439 RemoveDeadNode(Node); 9440 } 9441 9442 return Res; 9443 } 9444 9445 /// getMachineNode - These are used for target selectors to create a new node 9446 /// with specified return type(s), MachineInstr opcode, and operands. 9447 /// 9448 /// Note that getMachineNode returns the resultant node. If there is already a 9449 /// node of the specified opcode and operands, it returns that node instead of 9450 /// the current one. 9451 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9452 EVT VT) { 9453 SDVTList VTs = getVTList(VT); 9454 return getMachineNode(Opcode, dl, VTs, None); 9455 } 9456 9457 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9458 EVT VT, SDValue Op1) { 9459 SDVTList VTs = getVTList(VT); 9460 SDValue Ops[] = { Op1 }; 9461 return getMachineNode(Opcode, dl, VTs, Ops); 9462 } 9463 9464 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9465 EVT VT, SDValue Op1, SDValue Op2) { 9466 SDVTList VTs = getVTList(VT); 9467 SDValue Ops[] = { Op1, Op2 }; 9468 return getMachineNode(Opcode, dl, VTs, Ops); 9469 } 9470 9471 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9472 EVT VT, SDValue Op1, SDValue Op2, 9473 SDValue Op3) { 9474 SDVTList VTs = getVTList(VT); 9475 SDValue Ops[] = { Op1, Op2, Op3 }; 9476 return getMachineNode(Opcode, dl, VTs, Ops); 9477 } 9478 9479 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9480 EVT VT, ArrayRef<SDValue> Ops) { 9481 SDVTList VTs = getVTList(VT); 9482 return getMachineNode(Opcode, dl, VTs, Ops); 9483 } 9484 9485 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9486 EVT VT1, EVT VT2, SDValue Op1, 9487 SDValue Op2) { 9488 SDVTList VTs = getVTList(VT1, VT2); 9489 SDValue Ops[] = { Op1, Op2 }; 9490 return getMachineNode(Opcode, dl, VTs, Ops); 9491 } 9492 9493 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9494 EVT VT1, EVT VT2, SDValue Op1, 9495 SDValue Op2, SDValue Op3) { 9496 SDVTList VTs = getVTList(VT1, VT2); 9497 SDValue Ops[] = { Op1, Op2, Op3 }; 9498 return getMachineNode(Opcode, dl, VTs, Ops); 9499 } 9500 9501 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9502 EVT VT1, EVT VT2, 9503 ArrayRef<SDValue> Ops) { 9504 SDVTList VTs = getVTList(VT1, VT2); 9505 return getMachineNode(Opcode, dl, VTs, Ops); 9506 } 9507 9508 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9509 EVT VT1, EVT VT2, EVT VT3, 9510 SDValue Op1, SDValue Op2) { 9511 SDVTList VTs = getVTList(VT1, VT2, VT3); 9512 SDValue Ops[] = { Op1, Op2 }; 9513 return getMachineNode(Opcode, dl, VTs, Ops); 9514 } 9515 9516 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9517 EVT VT1, EVT VT2, EVT VT3, 9518 SDValue Op1, SDValue Op2, 9519 SDValue Op3) { 9520 SDVTList VTs = getVTList(VT1, VT2, VT3); 9521 SDValue Ops[] = { Op1, Op2, Op3 }; 9522 return getMachineNode(Opcode, dl, VTs, Ops); 9523 } 9524 9525 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9526 EVT VT1, EVT VT2, EVT VT3, 9527 ArrayRef<SDValue> Ops) { 9528 SDVTList VTs = getVTList(VT1, VT2, VT3); 9529 return getMachineNode(Opcode, dl, VTs, Ops); 9530 } 9531 9532 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9533 ArrayRef<EVT> ResultTys, 9534 ArrayRef<SDValue> Ops) { 9535 SDVTList VTs = getVTList(ResultTys); 9536 return getMachineNode(Opcode, dl, VTs, Ops); 9537 } 9538 9539 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 9540 SDVTList VTs, 9541 ArrayRef<SDValue> Ops) { 9542 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 9543 MachineSDNode *N; 9544 void *IP = nullptr; 9545 9546 if (DoCSE) { 9547 FoldingSetNodeID ID; 9548 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 9549 IP = nullptr; 9550 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9551 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 9552 } 9553 } 9554 9555 // Allocate a new MachineSDNode. 9556 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9557 createOperands(N, Ops); 9558 9559 if (DoCSE) 9560 CSEMap.InsertNode(N, IP); 9561 9562 InsertNode(N); 9563 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 9564 return N; 9565 } 9566 9567 /// getTargetExtractSubreg - A convenience function for creating 9568 /// TargetOpcode::EXTRACT_SUBREG nodes. 9569 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9570 SDValue Operand) { 9571 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9572 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 9573 VT, Operand, SRIdxVal); 9574 return SDValue(Subreg, 0); 9575 } 9576 9577 /// getTargetInsertSubreg - A convenience function for creating 9578 /// TargetOpcode::INSERT_SUBREG nodes. 9579 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9580 SDValue Operand, SDValue Subreg) { 9581 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9582 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 9583 VT, Operand, Subreg, SRIdxVal); 9584 return SDValue(Result, 0); 9585 } 9586 9587 /// getNodeIfExists - Get the specified node if it's already available, or 9588 /// else return NULL. 9589 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9590 ArrayRef<SDValue> Ops) { 9591 SDNodeFlags Flags; 9592 if (Inserter) 9593 Flags = Inserter->getFlags(); 9594 return getNodeIfExists(Opcode, VTList, Ops, Flags); 9595 } 9596 9597 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9598 ArrayRef<SDValue> Ops, 9599 const SDNodeFlags Flags) { 9600 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9601 FoldingSetNodeID ID; 9602 AddNodeIDNode(ID, Opcode, VTList, Ops); 9603 void *IP = nullptr; 9604 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 9605 E->intersectFlagsWith(Flags); 9606 return E; 9607 } 9608 } 9609 return nullptr; 9610 } 9611 9612 /// doesNodeExist - Check if a node exists without modifying its flags. 9613 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 9614 ArrayRef<SDValue> Ops) { 9615 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9616 FoldingSetNodeID ID; 9617 AddNodeIDNode(ID, Opcode, VTList, Ops); 9618 void *IP = nullptr; 9619 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 9620 return true; 9621 } 9622 return false; 9623 } 9624 9625 /// getDbgValue - Creates a SDDbgValue node. 9626 /// 9627 /// SDNode 9628 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 9629 SDNode *N, unsigned R, bool IsIndirect, 9630 const DebugLoc &DL, unsigned O) { 9631 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9632 "Expected inlined-at fields to agree"); 9633 return new (DbgInfo->getAlloc()) 9634 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 9635 {}, IsIndirect, DL, O, 9636 /*IsVariadic=*/false); 9637 } 9638 9639 /// Constant 9640 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 9641 DIExpression *Expr, 9642 const Value *C, 9643 const DebugLoc &DL, unsigned O) { 9644 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9645 "Expected inlined-at fields to agree"); 9646 return new (DbgInfo->getAlloc()) 9647 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 9648 /*IsIndirect=*/false, DL, O, 9649 /*IsVariadic=*/false); 9650 } 9651 9652 /// FrameIndex 9653 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9654 DIExpression *Expr, unsigned FI, 9655 bool IsIndirect, 9656 const DebugLoc &DL, 9657 unsigned O) { 9658 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9659 "Expected inlined-at fields to agree"); 9660 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 9661 } 9662 9663 /// FrameIndex with dependencies 9664 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9665 DIExpression *Expr, unsigned FI, 9666 ArrayRef<SDNode *> Dependencies, 9667 bool IsIndirect, 9668 const DebugLoc &DL, 9669 unsigned O) { 9670 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9671 "Expected inlined-at fields to agree"); 9672 return new (DbgInfo->getAlloc()) 9673 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 9674 Dependencies, IsIndirect, DL, O, 9675 /*IsVariadic=*/false); 9676 } 9677 9678 /// VReg 9679 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 9680 unsigned VReg, bool IsIndirect, 9681 const DebugLoc &DL, unsigned O) { 9682 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9683 "Expected inlined-at fields to agree"); 9684 return new (DbgInfo->getAlloc()) 9685 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 9686 {}, IsIndirect, DL, O, 9687 /*IsVariadic=*/false); 9688 } 9689 9690 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 9691 ArrayRef<SDDbgOperand> Locs, 9692 ArrayRef<SDNode *> Dependencies, 9693 bool IsIndirect, const DebugLoc &DL, 9694 unsigned O, bool IsVariadic) { 9695 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9696 "Expected inlined-at fields to agree"); 9697 return new (DbgInfo->getAlloc()) 9698 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 9699 DL, O, IsVariadic); 9700 } 9701 9702 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 9703 unsigned OffsetInBits, unsigned SizeInBits, 9704 bool InvalidateDbg) { 9705 SDNode *FromNode = From.getNode(); 9706 SDNode *ToNode = To.getNode(); 9707 assert(FromNode && ToNode && "Can't modify dbg values"); 9708 9709 // PR35338 9710 // TODO: assert(From != To && "Redundant dbg value transfer"); 9711 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 9712 if (From == To || FromNode == ToNode) 9713 return; 9714 9715 if (!FromNode->getHasDebugValue()) 9716 return; 9717 9718 SDDbgOperand FromLocOp = 9719 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 9720 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 9721 9722 SmallVector<SDDbgValue *, 2> ClonedDVs; 9723 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 9724 if (Dbg->isInvalidated()) 9725 continue; 9726 9727 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 9728 9729 // Create a new location ops vector that is equal to the old vector, but 9730 // with each instance of FromLocOp replaced with ToLocOp. 9731 bool Changed = false; 9732 auto NewLocOps = Dbg->copyLocationOps(); 9733 std::replace_if( 9734 NewLocOps.begin(), NewLocOps.end(), 9735 [&Changed, FromLocOp](const SDDbgOperand &Op) { 9736 bool Match = Op == FromLocOp; 9737 Changed |= Match; 9738 return Match; 9739 }, 9740 ToLocOp); 9741 // Ignore this SDDbgValue if we didn't find a matching location. 9742 if (!Changed) 9743 continue; 9744 9745 DIVariable *Var = Dbg->getVariable(); 9746 auto *Expr = Dbg->getExpression(); 9747 // If a fragment is requested, update the expression. 9748 if (SizeInBits) { 9749 // When splitting a larger (e.g., sign-extended) value whose 9750 // lower bits are described with an SDDbgValue, do not attempt 9751 // to transfer the SDDbgValue to the upper bits. 9752 if (auto FI = Expr->getFragmentInfo()) 9753 if (OffsetInBits + SizeInBits > FI->SizeInBits) 9754 continue; 9755 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 9756 SizeInBits); 9757 if (!Fragment) 9758 continue; 9759 Expr = *Fragment; 9760 } 9761 9762 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 9763 // Clone the SDDbgValue and move it to To. 9764 SDDbgValue *Clone = getDbgValueList( 9765 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 9766 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 9767 Dbg->isVariadic()); 9768 ClonedDVs.push_back(Clone); 9769 9770 if (InvalidateDbg) { 9771 // Invalidate value and indicate the SDDbgValue should not be emitted. 9772 Dbg->setIsInvalidated(); 9773 Dbg->setIsEmitted(); 9774 } 9775 } 9776 9777 for (SDDbgValue *Dbg : ClonedDVs) { 9778 assert(is_contained(Dbg->getSDNodes(), ToNode) && 9779 "Transferred DbgValues should depend on the new SDNode"); 9780 AddDbgValue(Dbg, false); 9781 } 9782 } 9783 9784 void SelectionDAG::salvageDebugInfo(SDNode &N) { 9785 if (!N.getHasDebugValue()) 9786 return; 9787 9788 SmallVector<SDDbgValue *, 2> ClonedDVs; 9789 for (auto DV : GetDbgValues(&N)) { 9790 if (DV->isInvalidated()) 9791 continue; 9792 switch (N.getOpcode()) { 9793 default: 9794 break; 9795 case ISD::ADD: 9796 SDValue N0 = N.getOperand(0); 9797 SDValue N1 = N.getOperand(1); 9798 if (!isConstantIntBuildVectorOrConstantInt(N0) && 9799 isConstantIntBuildVectorOrConstantInt(N1)) { 9800 uint64_t Offset = N.getConstantOperandVal(1); 9801 9802 // Rewrite an ADD constant node into a DIExpression. Since we are 9803 // performing arithmetic to compute the variable's *value* in the 9804 // DIExpression, we need to mark the expression with a 9805 // DW_OP_stack_value. 9806 auto *DIExpr = DV->getExpression(); 9807 auto NewLocOps = DV->copyLocationOps(); 9808 bool Changed = false; 9809 for (size_t i = 0; i < NewLocOps.size(); ++i) { 9810 // We're not given a ResNo to compare against because the whole 9811 // node is going away. We know that any ISD::ADD only has one 9812 // result, so we can assume any node match is using the result. 9813 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 9814 NewLocOps[i].getSDNode() != &N) 9815 continue; 9816 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 9817 SmallVector<uint64_t, 3> ExprOps; 9818 DIExpression::appendOffset(ExprOps, Offset); 9819 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 9820 Changed = true; 9821 } 9822 (void)Changed; 9823 assert(Changed && "Salvage target doesn't use N"); 9824 9825 auto AdditionalDependencies = DV->getAdditionalDependencies(); 9826 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 9827 NewLocOps, AdditionalDependencies, 9828 DV->isIndirect(), DV->getDebugLoc(), 9829 DV->getOrder(), DV->isVariadic()); 9830 ClonedDVs.push_back(Clone); 9831 DV->setIsInvalidated(); 9832 DV->setIsEmitted(); 9833 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 9834 N0.getNode()->dumprFull(this); 9835 dbgs() << " into " << *DIExpr << '\n'); 9836 } 9837 } 9838 } 9839 9840 for (SDDbgValue *Dbg : ClonedDVs) { 9841 assert(!Dbg->getSDNodes().empty() && 9842 "Salvaged DbgValue should depend on a new SDNode"); 9843 AddDbgValue(Dbg, false); 9844 } 9845 } 9846 9847 /// Creates a SDDbgLabel node. 9848 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 9849 const DebugLoc &DL, unsigned O) { 9850 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 9851 "Expected inlined-at fields to agree"); 9852 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 9853 } 9854 9855 namespace { 9856 9857 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 9858 /// pointed to by a use iterator is deleted, increment the use iterator 9859 /// so that it doesn't dangle. 9860 /// 9861 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 9862 SDNode::use_iterator &UI; 9863 SDNode::use_iterator &UE; 9864 9865 void NodeDeleted(SDNode *N, SDNode *E) override { 9866 // Increment the iterator as needed. 9867 while (UI != UE && N == *UI) 9868 ++UI; 9869 } 9870 9871 public: 9872 RAUWUpdateListener(SelectionDAG &d, 9873 SDNode::use_iterator &ui, 9874 SDNode::use_iterator &ue) 9875 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 9876 }; 9877 9878 } // end anonymous namespace 9879 9880 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9881 /// This can cause recursive merging of nodes in the DAG. 9882 /// 9883 /// This version assumes From has a single result value. 9884 /// 9885 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 9886 SDNode *From = FromN.getNode(); 9887 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 9888 "Cannot replace with this method!"); 9889 assert(From != To.getNode() && "Cannot replace uses of with self"); 9890 9891 // Preserve Debug Values 9892 transferDbgValues(FromN, To); 9893 9894 // Iterate over all the existing uses of From. New uses will be added 9895 // to the beginning of the use list, which we avoid visiting. 9896 // This specifically avoids visiting uses of From that arise while the 9897 // replacement is happening, because any such uses would be the result 9898 // of CSE: If an existing node looks like From after one of its operands 9899 // is replaced by To, we don't want to replace of all its users with To 9900 // too. See PR3018 for more info. 9901 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9902 RAUWUpdateListener Listener(*this, UI, UE); 9903 while (UI != UE) { 9904 SDNode *User = *UI; 9905 9906 // This node is about to morph, remove its old self from the CSE maps. 9907 RemoveNodeFromCSEMaps(User); 9908 9909 // A user can appear in a use list multiple times, and when this 9910 // happens the uses are usually next to each other in the list. 9911 // To help reduce the number of CSE recomputations, process all 9912 // the uses of this user that we can find this way. 9913 do { 9914 SDUse &Use = UI.getUse(); 9915 ++UI; 9916 Use.set(To); 9917 if (To->isDivergent() != From->isDivergent()) 9918 updateDivergence(User); 9919 } while (UI != UE && *UI == User); 9920 // Now that we have modified User, add it back to the CSE maps. If it 9921 // already exists there, recursively merge the results together. 9922 AddModifiedNodeToCSEMaps(User); 9923 } 9924 9925 // If we just RAUW'd the root, take note. 9926 if (FromN == getRoot()) 9927 setRoot(To); 9928 } 9929 9930 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9931 /// This can cause recursive merging of nodes in the DAG. 9932 /// 9933 /// This version assumes that for each value of From, there is a 9934 /// corresponding value in To in the same position with the same type. 9935 /// 9936 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 9937 #ifndef NDEBUG 9938 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9939 assert((!From->hasAnyUseOfValue(i) || 9940 From->getValueType(i) == To->getValueType(i)) && 9941 "Cannot use this version of ReplaceAllUsesWith!"); 9942 #endif 9943 9944 // Handle the trivial case. 9945 if (From == To) 9946 return; 9947 9948 // Preserve Debug Info. Only do this if there's a use. 9949 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9950 if (From->hasAnyUseOfValue(i)) { 9951 assert((i < To->getNumValues()) && "Invalid To location"); 9952 transferDbgValues(SDValue(From, i), SDValue(To, i)); 9953 } 9954 9955 // Iterate over just the existing users of From. See the comments in 9956 // the ReplaceAllUsesWith above. 9957 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9958 RAUWUpdateListener Listener(*this, UI, UE); 9959 while (UI != UE) { 9960 SDNode *User = *UI; 9961 9962 // This node is about to morph, remove its old self from the CSE maps. 9963 RemoveNodeFromCSEMaps(User); 9964 9965 // A user can appear in a use list multiple times, and when this 9966 // happens the uses are usually next to each other in the list. 9967 // To help reduce the number of CSE recomputations, process all 9968 // the uses of this user that we can find this way. 9969 do { 9970 SDUse &Use = UI.getUse(); 9971 ++UI; 9972 Use.setNode(To); 9973 if (To->isDivergent() != From->isDivergent()) 9974 updateDivergence(User); 9975 } while (UI != UE && *UI == User); 9976 9977 // Now that we have modified User, add it back to the CSE maps. If it 9978 // already exists there, recursively merge the results together. 9979 AddModifiedNodeToCSEMaps(User); 9980 } 9981 9982 // If we just RAUW'd the root, take note. 9983 if (From == getRoot().getNode()) 9984 setRoot(SDValue(To, getRoot().getResNo())); 9985 } 9986 9987 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9988 /// This can cause recursive merging of nodes in the DAG. 9989 /// 9990 /// This version can replace From with any result values. To must match the 9991 /// number and types of values returned by From. 9992 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 9993 if (From->getNumValues() == 1) // Handle the simple case efficiently. 9994 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 9995 9996 // Preserve Debug Info. 9997 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9998 transferDbgValues(SDValue(From, i), To[i]); 9999 10000 // Iterate over just the existing users of From. See the comments in 10001 // the ReplaceAllUsesWith above. 10002 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 10003 RAUWUpdateListener Listener(*this, UI, UE); 10004 while (UI != UE) { 10005 SDNode *User = *UI; 10006 10007 // This node is about to morph, remove its old self from the CSE maps. 10008 RemoveNodeFromCSEMaps(User); 10009 10010 // A user can appear in a use list multiple times, and when this happens the 10011 // uses are usually next to each other in the list. To help reduce the 10012 // number of CSE and divergence recomputations, process all the uses of this 10013 // user that we can find this way. 10014 bool To_IsDivergent = false; 10015 do { 10016 SDUse &Use = UI.getUse(); 10017 const SDValue &ToOp = To[Use.getResNo()]; 10018 ++UI; 10019 Use.set(ToOp); 10020 To_IsDivergent |= ToOp->isDivergent(); 10021 } while (UI != UE && *UI == User); 10022 10023 if (To_IsDivergent != From->isDivergent()) 10024 updateDivergence(User); 10025 10026 // Now that we have modified User, add it back to the CSE maps. If it 10027 // already exists there, recursively merge the results together. 10028 AddModifiedNodeToCSEMaps(User); 10029 } 10030 10031 // If we just RAUW'd the root, take note. 10032 if (From == getRoot().getNode()) 10033 setRoot(SDValue(To[getRoot().getResNo()])); 10034 } 10035 10036 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 10037 /// uses of other values produced by From.getNode() alone. The Deleted 10038 /// vector is handled the same way as for ReplaceAllUsesWith. 10039 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 10040 // Handle the really simple, really trivial case efficiently. 10041 if (From == To) return; 10042 10043 // Handle the simple, trivial, case efficiently. 10044 if (From.getNode()->getNumValues() == 1) { 10045 ReplaceAllUsesWith(From, To); 10046 return; 10047 } 10048 10049 // Preserve Debug Info. 10050 transferDbgValues(From, To); 10051 10052 // Iterate over just the existing users of From. See the comments in 10053 // the ReplaceAllUsesWith above. 10054 SDNode::use_iterator UI = From.getNode()->use_begin(), 10055 UE = From.getNode()->use_end(); 10056 RAUWUpdateListener Listener(*this, UI, UE); 10057 while (UI != UE) { 10058 SDNode *User = *UI; 10059 bool UserRemovedFromCSEMaps = false; 10060 10061 // A user can appear in a use list multiple times, and when this 10062 // happens the uses are usually next to each other in the list. 10063 // To help reduce the number of CSE recomputations, process all 10064 // the uses of this user that we can find this way. 10065 do { 10066 SDUse &Use = UI.getUse(); 10067 10068 // Skip uses of different values from the same node. 10069 if (Use.getResNo() != From.getResNo()) { 10070 ++UI; 10071 continue; 10072 } 10073 10074 // If this node hasn't been modified yet, it's still in the CSE maps, 10075 // so remove its old self from the CSE maps. 10076 if (!UserRemovedFromCSEMaps) { 10077 RemoveNodeFromCSEMaps(User); 10078 UserRemovedFromCSEMaps = true; 10079 } 10080 10081 ++UI; 10082 Use.set(To); 10083 if (To->isDivergent() != From->isDivergent()) 10084 updateDivergence(User); 10085 } while (UI != UE && *UI == User); 10086 // We are iterating over all uses of the From node, so if a use 10087 // doesn't use the specific value, no changes are made. 10088 if (!UserRemovedFromCSEMaps) 10089 continue; 10090 10091 // Now that we have modified User, add it back to the CSE maps. If it 10092 // already exists there, recursively merge the results together. 10093 AddModifiedNodeToCSEMaps(User); 10094 } 10095 10096 // If we just RAUW'd the root, take note. 10097 if (From == getRoot()) 10098 setRoot(To); 10099 } 10100 10101 namespace { 10102 10103 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 10104 /// to record information about a use. 10105 struct UseMemo { 10106 SDNode *User; 10107 unsigned Index; 10108 SDUse *Use; 10109 }; 10110 10111 /// operator< - Sort Memos by User. 10112 bool operator<(const UseMemo &L, const UseMemo &R) { 10113 return (intptr_t)L.User < (intptr_t)R.User; 10114 } 10115 10116 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node 10117 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that 10118 /// the node already has been taken care of recursively. 10119 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener { 10120 SmallVector<UseMemo, 4> &Uses; 10121 10122 void NodeDeleted(SDNode *N, SDNode *E) override { 10123 for (UseMemo &Memo : Uses) 10124 if (Memo.User == N) 10125 Memo.User = nullptr; 10126 } 10127 10128 public: 10129 RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses) 10130 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {} 10131 }; 10132 10133 } // end anonymous namespace 10134 10135 bool SelectionDAG::calculateDivergence(SDNode *N) { 10136 if (TLI->isSDNodeAlwaysUniform(N)) { 10137 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 10138 "Conflicting divergence information!"); 10139 return false; 10140 } 10141 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 10142 return true; 10143 for (auto &Op : N->ops()) { 10144 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 10145 return true; 10146 } 10147 return false; 10148 } 10149 10150 void SelectionDAG::updateDivergence(SDNode *N) { 10151 SmallVector<SDNode *, 16> Worklist(1, N); 10152 do { 10153 N = Worklist.pop_back_val(); 10154 bool IsDivergent = calculateDivergence(N); 10155 if (N->SDNodeBits.IsDivergent != IsDivergent) { 10156 N->SDNodeBits.IsDivergent = IsDivergent; 10157 llvm::append_range(Worklist, N->uses()); 10158 } 10159 } while (!Worklist.empty()); 10160 } 10161 10162 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 10163 DenseMap<SDNode *, unsigned> Degree; 10164 Order.reserve(AllNodes.size()); 10165 for (auto &N : allnodes()) { 10166 unsigned NOps = N.getNumOperands(); 10167 Degree[&N] = NOps; 10168 if (0 == NOps) 10169 Order.push_back(&N); 10170 } 10171 for (size_t I = 0; I != Order.size(); ++I) { 10172 SDNode *N = Order[I]; 10173 for (auto U : N->uses()) { 10174 unsigned &UnsortedOps = Degree[U]; 10175 if (0 == --UnsortedOps) 10176 Order.push_back(U); 10177 } 10178 } 10179 } 10180 10181 #ifndef NDEBUG 10182 void SelectionDAG::VerifyDAGDivergence() { 10183 std::vector<SDNode *> TopoOrder; 10184 CreateTopologicalOrder(TopoOrder); 10185 for (auto *N : TopoOrder) { 10186 assert(calculateDivergence(N) == N->isDivergent() && 10187 "Divergence bit inconsistency detected"); 10188 } 10189 } 10190 #endif 10191 10192 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 10193 /// uses of other values produced by From.getNode() alone. The same value 10194 /// may appear in both the From and To list. The Deleted vector is 10195 /// handled the same way as for ReplaceAllUsesWith. 10196 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 10197 const SDValue *To, 10198 unsigned Num){ 10199 // Handle the simple, trivial case efficiently. 10200 if (Num == 1) 10201 return ReplaceAllUsesOfValueWith(*From, *To); 10202 10203 transferDbgValues(*From, *To); 10204 10205 // Read up all the uses and make records of them. This helps 10206 // processing new uses that are introduced during the 10207 // replacement process. 10208 SmallVector<UseMemo, 4> Uses; 10209 for (unsigned i = 0; i != Num; ++i) { 10210 unsigned FromResNo = From[i].getResNo(); 10211 SDNode *FromNode = From[i].getNode(); 10212 for (SDNode::use_iterator UI = FromNode->use_begin(), 10213 E = FromNode->use_end(); UI != E; ++UI) { 10214 SDUse &Use = UI.getUse(); 10215 if (Use.getResNo() == FromResNo) { 10216 UseMemo Memo = { *UI, i, &Use }; 10217 Uses.push_back(Memo); 10218 } 10219 } 10220 } 10221 10222 // Sort the uses, so that all the uses from a given User are together. 10223 llvm::sort(Uses); 10224 RAUOVWUpdateListener Listener(*this, Uses); 10225 10226 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 10227 UseIndex != UseIndexEnd; ) { 10228 // We know that this user uses some value of From. If it is the right 10229 // value, update it. 10230 SDNode *User = Uses[UseIndex].User; 10231 // If the node has been deleted by recursive CSE updates when updating 10232 // another node, then just skip this entry. 10233 if (User == nullptr) { 10234 ++UseIndex; 10235 continue; 10236 } 10237 10238 // This node is about to morph, remove its old self from the CSE maps. 10239 RemoveNodeFromCSEMaps(User); 10240 10241 // The Uses array is sorted, so all the uses for a given User 10242 // are next to each other in the list. 10243 // To help reduce the number of CSE recomputations, process all 10244 // the uses of this user that we can find this way. 10245 do { 10246 unsigned i = Uses[UseIndex].Index; 10247 SDUse &Use = *Uses[UseIndex].Use; 10248 ++UseIndex; 10249 10250 Use.set(To[i]); 10251 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 10252 10253 // Now that we have modified User, add it back to the CSE maps. If it 10254 // already exists there, recursively merge the results together. 10255 AddModifiedNodeToCSEMaps(User); 10256 } 10257 } 10258 10259 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 10260 /// based on their topological order. It returns the maximum id and a vector 10261 /// of the SDNodes* in assigned order by reference. 10262 unsigned SelectionDAG::AssignTopologicalOrder() { 10263 unsigned DAGSize = 0; 10264 10265 // SortedPos tracks the progress of the algorithm. Nodes before it are 10266 // sorted, nodes after it are unsorted. When the algorithm completes 10267 // it is at the end of the list. 10268 allnodes_iterator SortedPos = allnodes_begin(); 10269 10270 // Visit all the nodes. Move nodes with no operands to the front of 10271 // the list immediately. Annotate nodes that do have operands with their 10272 // operand count. Before we do this, the Node Id fields of the nodes 10273 // may contain arbitrary values. After, the Node Id fields for nodes 10274 // before SortedPos will contain the topological sort index, and the 10275 // Node Id fields for nodes At SortedPos and after will contain the 10276 // count of outstanding operands. 10277 for (SDNode &N : llvm::make_early_inc_range(allnodes())) { 10278 checkForCycles(&N, this); 10279 unsigned Degree = N.getNumOperands(); 10280 if (Degree == 0) { 10281 // A node with no uses, add it to the result array immediately. 10282 N.setNodeId(DAGSize++); 10283 allnodes_iterator Q(&N); 10284 if (Q != SortedPos) 10285 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 10286 assert(SortedPos != AllNodes.end() && "Overran node list"); 10287 ++SortedPos; 10288 } else { 10289 // Temporarily use the Node Id as scratch space for the degree count. 10290 N.setNodeId(Degree); 10291 } 10292 } 10293 10294 // Visit all the nodes. As we iterate, move nodes into sorted order, 10295 // such that by the time the end is reached all nodes will be sorted. 10296 for (SDNode &Node : allnodes()) { 10297 SDNode *N = &Node; 10298 checkForCycles(N, this); 10299 // N is in sorted position, so all its uses have one less operand 10300 // that needs to be sorted. 10301 for (SDNode *P : N->uses()) { 10302 unsigned Degree = P->getNodeId(); 10303 assert(Degree != 0 && "Invalid node degree"); 10304 --Degree; 10305 if (Degree == 0) { 10306 // All of P's operands are sorted, so P may sorted now. 10307 P->setNodeId(DAGSize++); 10308 if (P->getIterator() != SortedPos) 10309 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 10310 assert(SortedPos != AllNodes.end() && "Overran node list"); 10311 ++SortedPos; 10312 } else { 10313 // Update P's outstanding operand count. 10314 P->setNodeId(Degree); 10315 } 10316 } 10317 if (Node.getIterator() == SortedPos) { 10318 #ifndef NDEBUG 10319 allnodes_iterator I(N); 10320 SDNode *S = &*++I; 10321 dbgs() << "Overran sorted position:\n"; 10322 S->dumprFull(this); dbgs() << "\n"; 10323 dbgs() << "Checking if this is due to cycles\n"; 10324 checkForCycles(this, true); 10325 #endif 10326 llvm_unreachable(nullptr); 10327 } 10328 } 10329 10330 assert(SortedPos == AllNodes.end() && 10331 "Topological sort incomplete!"); 10332 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 10333 "First node in topological sort is not the entry token!"); 10334 assert(AllNodes.front().getNodeId() == 0 && 10335 "First node in topological sort has non-zero id!"); 10336 assert(AllNodes.front().getNumOperands() == 0 && 10337 "First node in topological sort has operands!"); 10338 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 10339 "Last node in topologic sort has unexpected id!"); 10340 assert(AllNodes.back().use_empty() && 10341 "Last node in topologic sort has users!"); 10342 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 10343 return DAGSize; 10344 } 10345 10346 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 10347 /// value is produced by SD. 10348 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 10349 for (SDNode *SD : DB->getSDNodes()) { 10350 if (!SD) 10351 continue; 10352 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 10353 SD->setHasDebugValue(true); 10354 } 10355 DbgInfo->add(DB, isParameter); 10356 } 10357 10358 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 10359 10360 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 10361 SDValue NewMemOpChain) { 10362 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 10363 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 10364 // The new memory operation must have the same position as the old load in 10365 // terms of memory dependency. Create a TokenFactor for the old load and new 10366 // memory operation and update uses of the old load's output chain to use that 10367 // TokenFactor. 10368 if (OldChain == NewMemOpChain || OldChain.use_empty()) 10369 return NewMemOpChain; 10370 10371 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 10372 OldChain, NewMemOpChain); 10373 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 10374 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 10375 return TokenFactor; 10376 } 10377 10378 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 10379 SDValue NewMemOp) { 10380 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 10381 SDValue OldChain = SDValue(OldLoad, 1); 10382 SDValue NewMemOpChain = NewMemOp.getValue(1); 10383 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 10384 } 10385 10386 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 10387 Function **OutFunction) { 10388 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 10389 10390 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 10391 auto *Module = MF->getFunction().getParent(); 10392 auto *Function = Module->getFunction(Symbol); 10393 10394 if (OutFunction != nullptr) 10395 *OutFunction = Function; 10396 10397 if (Function != nullptr) { 10398 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 10399 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 10400 } 10401 10402 std::string ErrorStr; 10403 raw_string_ostream ErrorFormatter(ErrorStr); 10404 ErrorFormatter << "Undefined external symbol "; 10405 ErrorFormatter << '"' << Symbol << '"'; 10406 report_fatal_error(Twine(ErrorFormatter.str())); 10407 } 10408 10409 //===----------------------------------------------------------------------===// 10410 // SDNode Class 10411 //===----------------------------------------------------------------------===// 10412 10413 bool llvm::isNullConstant(SDValue V) { 10414 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10415 return Const != nullptr && Const->isZero(); 10416 } 10417 10418 bool llvm::isNullFPConstant(SDValue V) { 10419 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 10420 return Const != nullptr && Const->isZero() && !Const->isNegative(); 10421 } 10422 10423 bool llvm::isAllOnesConstant(SDValue V) { 10424 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10425 return Const != nullptr && Const->isAllOnes(); 10426 } 10427 10428 bool llvm::isOneConstant(SDValue V) { 10429 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10430 return Const != nullptr && Const->isOne(); 10431 } 10432 10433 bool llvm::isMinSignedConstant(SDValue V) { 10434 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10435 return Const != nullptr && Const->isMinSignedValue(); 10436 } 10437 10438 SDValue llvm::peekThroughBitcasts(SDValue V) { 10439 while (V.getOpcode() == ISD::BITCAST) 10440 V = V.getOperand(0); 10441 return V; 10442 } 10443 10444 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 10445 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 10446 V = V.getOperand(0); 10447 return V; 10448 } 10449 10450 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 10451 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 10452 V = V.getOperand(0); 10453 return V; 10454 } 10455 10456 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 10457 if (V.getOpcode() != ISD::XOR) 10458 return false; 10459 V = peekThroughBitcasts(V.getOperand(1)); 10460 unsigned NumBits = V.getScalarValueSizeInBits(); 10461 ConstantSDNode *C = 10462 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 10463 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 10464 } 10465 10466 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 10467 bool AllowTruncation) { 10468 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10469 return CN; 10470 10471 // SplatVectors can truncate their operands. Ignore that case here unless 10472 // AllowTruncation is set. 10473 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 10474 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 10475 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 10476 EVT CVT = CN->getValueType(0); 10477 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 10478 if (AllowTruncation || CVT == VecEltVT) 10479 return CN; 10480 } 10481 } 10482 10483 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10484 BitVector UndefElements; 10485 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 10486 10487 // BuildVectors can truncate their operands. Ignore that case here unless 10488 // AllowTruncation is set. 10489 if (CN && (UndefElements.none() || AllowUndefs)) { 10490 EVT CVT = CN->getValueType(0); 10491 EVT NSVT = N.getValueType().getScalarType(); 10492 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10493 if (AllowTruncation || (CVT == NSVT)) 10494 return CN; 10495 } 10496 } 10497 10498 return nullptr; 10499 } 10500 10501 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 10502 bool AllowUndefs, 10503 bool AllowTruncation) { 10504 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10505 return CN; 10506 10507 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10508 BitVector UndefElements; 10509 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 10510 10511 // BuildVectors can truncate their operands. Ignore that case here unless 10512 // AllowTruncation is set. 10513 if (CN && (UndefElements.none() || AllowUndefs)) { 10514 EVT CVT = CN->getValueType(0); 10515 EVT NSVT = N.getValueType().getScalarType(); 10516 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10517 if (AllowTruncation || (CVT == NSVT)) 10518 return CN; 10519 } 10520 } 10521 10522 return nullptr; 10523 } 10524 10525 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 10526 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10527 return CN; 10528 10529 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10530 BitVector UndefElements; 10531 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 10532 if (CN && (UndefElements.none() || AllowUndefs)) 10533 return CN; 10534 } 10535 10536 if (N.getOpcode() == ISD::SPLAT_VECTOR) 10537 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 10538 return CN; 10539 10540 return nullptr; 10541 } 10542 10543 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 10544 const APInt &DemandedElts, 10545 bool AllowUndefs) { 10546 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10547 return CN; 10548 10549 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10550 BitVector UndefElements; 10551 ConstantFPSDNode *CN = 10552 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 10553 if (CN && (UndefElements.none() || AllowUndefs)) 10554 return CN; 10555 } 10556 10557 return nullptr; 10558 } 10559 10560 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 10561 // TODO: may want to use peekThroughBitcast() here. 10562 ConstantSDNode *C = 10563 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true); 10564 return C && C->isZero(); 10565 } 10566 10567 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 10568 // TODO: may want to use peekThroughBitcast() here. 10569 unsigned BitWidth = N.getScalarValueSizeInBits(); 10570 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10571 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 10572 } 10573 10574 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 10575 N = peekThroughBitcasts(N); 10576 unsigned BitWidth = N.getScalarValueSizeInBits(); 10577 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10578 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth; 10579 } 10580 10581 HandleSDNode::~HandleSDNode() { 10582 DropOperands(); 10583 } 10584 10585 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 10586 const DebugLoc &DL, 10587 const GlobalValue *GA, EVT VT, 10588 int64_t o, unsigned TF) 10589 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 10590 TheGlobal = GA; 10591 } 10592 10593 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 10594 EVT VT, unsigned SrcAS, 10595 unsigned DestAS) 10596 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 10597 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 10598 10599 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 10600 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 10601 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 10602 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 10603 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 10604 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 10605 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 10606 10607 // We check here that the size of the memory operand fits within the size of 10608 // the MMO. This is because the MMO might indicate only a possible address 10609 // range instead of specifying the affected memory addresses precisely. 10610 // TODO: Make MachineMemOperands aware of scalable vectors. 10611 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 10612 "Size mismatch!"); 10613 } 10614 10615 /// Profile - Gather unique data for the node. 10616 /// 10617 void SDNode::Profile(FoldingSetNodeID &ID) const { 10618 AddNodeIDNode(ID, this); 10619 } 10620 10621 namespace { 10622 10623 struct EVTArray { 10624 std::vector<EVT> VTs; 10625 10626 EVTArray() { 10627 VTs.reserve(MVT::VALUETYPE_SIZE); 10628 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i) 10629 VTs.push_back(MVT((MVT::SimpleValueType)i)); 10630 } 10631 }; 10632 10633 } // end anonymous namespace 10634 10635 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 10636 static ManagedStatic<EVTArray> SimpleVTArray; 10637 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 10638 10639 /// getValueTypeList - Return a pointer to the specified value type. 10640 /// 10641 const EVT *SDNode::getValueTypeList(EVT VT) { 10642 if (VT.isExtended()) { 10643 sys::SmartScopedLock<true> Lock(*VTMutex); 10644 return &(*EVTs->insert(VT).first); 10645 } 10646 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!"); 10647 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 10648 } 10649 10650 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 10651 /// indicated value. This method ignores uses of other values defined by this 10652 /// operation. 10653 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 10654 assert(Value < getNumValues() && "Bad value!"); 10655 10656 // TODO: Only iterate over uses of a given value of the node 10657 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 10658 if (UI.getUse().getResNo() == Value) { 10659 if (NUses == 0) 10660 return false; 10661 --NUses; 10662 } 10663 } 10664 10665 // Found exactly the right number of uses? 10666 return NUses == 0; 10667 } 10668 10669 /// hasAnyUseOfValue - Return true if there are any use of the indicated 10670 /// value. This method ignores uses of other values defined by this operation. 10671 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 10672 assert(Value < getNumValues() && "Bad value!"); 10673 10674 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 10675 if (UI.getUse().getResNo() == Value) 10676 return true; 10677 10678 return false; 10679 } 10680 10681 /// isOnlyUserOf - Return true if this node is the only use of N. 10682 bool SDNode::isOnlyUserOf(const SDNode *N) const { 10683 bool Seen = false; 10684 for (const SDNode *User : N->uses()) { 10685 if (User == this) 10686 Seen = true; 10687 else 10688 return false; 10689 } 10690 10691 return Seen; 10692 } 10693 10694 /// Return true if the only users of N are contained in Nodes. 10695 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 10696 bool Seen = false; 10697 for (const SDNode *User : N->uses()) { 10698 if (llvm::is_contained(Nodes, User)) 10699 Seen = true; 10700 else 10701 return false; 10702 } 10703 10704 return Seen; 10705 } 10706 10707 /// isOperand - Return true if this node is an operand of N. 10708 bool SDValue::isOperandOf(const SDNode *N) const { 10709 return is_contained(N->op_values(), *this); 10710 } 10711 10712 bool SDNode::isOperandOf(const SDNode *N) const { 10713 return any_of(N->op_values(), 10714 [this](SDValue Op) { return this == Op.getNode(); }); 10715 } 10716 10717 /// reachesChainWithoutSideEffects - Return true if this operand (which must 10718 /// be a chain) reaches the specified operand without crossing any 10719 /// side-effecting instructions on any chain path. In practice, this looks 10720 /// through token factors and non-volatile loads. In order to remain efficient, 10721 /// this only looks a couple of nodes in, it does not do an exhaustive search. 10722 /// 10723 /// Note that we only need to examine chains when we're searching for 10724 /// side-effects; SelectionDAG requires that all side-effects are represented 10725 /// by chains, even if another operand would force a specific ordering. This 10726 /// constraint is necessary to allow transformations like splitting loads. 10727 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 10728 unsigned Depth) const { 10729 if (*this == Dest) return true; 10730 10731 // Don't search too deeply, we just want to be able to see through 10732 // TokenFactor's etc. 10733 if (Depth == 0) return false; 10734 10735 // If this is a token factor, all inputs to the TF happen in parallel. 10736 if (getOpcode() == ISD::TokenFactor) { 10737 // First, try a shallow search. 10738 if (is_contained((*this)->ops(), Dest)) { 10739 // We found the chain we want as an operand of this TokenFactor. 10740 // Essentially, we reach the chain without side-effects if we could 10741 // serialize the TokenFactor into a simple chain of operations with 10742 // Dest as the last operation. This is automatically true if the 10743 // chain has one use: there are no other ordering constraints. 10744 // If the chain has more than one use, we give up: some other 10745 // use of Dest might force a side-effect between Dest and the current 10746 // node. 10747 if (Dest.hasOneUse()) 10748 return true; 10749 } 10750 // Next, try a deep search: check whether every operand of the TokenFactor 10751 // reaches Dest. 10752 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 10753 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 10754 }); 10755 } 10756 10757 // Loads don't have side effects, look through them. 10758 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 10759 if (Ld->isUnordered()) 10760 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 10761 } 10762 return false; 10763 } 10764 10765 bool SDNode::hasPredecessor(const SDNode *N) const { 10766 SmallPtrSet<const SDNode *, 32> Visited; 10767 SmallVector<const SDNode *, 16> Worklist; 10768 Worklist.push_back(this); 10769 return hasPredecessorHelper(N, Visited, Worklist); 10770 } 10771 10772 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 10773 this->Flags.intersectWith(Flags); 10774 } 10775 10776 SDValue 10777 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 10778 ArrayRef<ISD::NodeType> CandidateBinOps, 10779 bool AllowPartials) { 10780 // The pattern must end in an extract from index 0. 10781 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10782 !isNullConstant(Extract->getOperand(1))) 10783 return SDValue(); 10784 10785 // Match against one of the candidate binary ops. 10786 SDValue Op = Extract->getOperand(0); 10787 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 10788 return Op.getOpcode() == unsigned(BinOp); 10789 })) 10790 return SDValue(); 10791 10792 // Floating-point reductions may require relaxed constraints on the final step 10793 // of the reduction because they may reorder intermediate operations. 10794 unsigned CandidateBinOp = Op.getOpcode(); 10795 if (Op.getValueType().isFloatingPoint()) { 10796 SDNodeFlags Flags = Op->getFlags(); 10797 switch (CandidateBinOp) { 10798 case ISD::FADD: 10799 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 10800 return SDValue(); 10801 break; 10802 default: 10803 llvm_unreachable("Unhandled FP opcode for binop reduction"); 10804 } 10805 } 10806 10807 // Matching failed - attempt to see if we did enough stages that a partial 10808 // reduction from a subvector is possible. 10809 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 10810 if (!AllowPartials || !Op) 10811 return SDValue(); 10812 EVT OpVT = Op.getValueType(); 10813 EVT OpSVT = OpVT.getScalarType(); 10814 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 10815 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 10816 return SDValue(); 10817 BinOp = (ISD::NodeType)CandidateBinOp; 10818 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 10819 getVectorIdxConstant(0, SDLoc(Op))); 10820 }; 10821 10822 // At each stage, we're looking for something that looks like: 10823 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 10824 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 10825 // i32 undef, i32 undef, i32 undef, i32 undef> 10826 // %a = binop <8 x i32> %op, %s 10827 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 10828 // we expect something like: 10829 // <4,5,6,7,u,u,u,u> 10830 // <2,3,u,u,u,u,u,u> 10831 // <1,u,u,u,u,u,u,u> 10832 // While a partial reduction match would be: 10833 // <2,3,u,u,u,u,u,u> 10834 // <1,u,u,u,u,u,u,u> 10835 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 10836 SDValue PrevOp; 10837 for (unsigned i = 0; i < Stages; ++i) { 10838 unsigned MaskEnd = (1 << i); 10839 10840 if (Op.getOpcode() != CandidateBinOp) 10841 return PartialReduction(PrevOp, MaskEnd); 10842 10843 SDValue Op0 = Op.getOperand(0); 10844 SDValue Op1 = Op.getOperand(1); 10845 10846 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 10847 if (Shuffle) { 10848 Op = Op1; 10849 } else { 10850 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 10851 Op = Op0; 10852 } 10853 10854 // The first operand of the shuffle should be the same as the other operand 10855 // of the binop. 10856 if (!Shuffle || Shuffle->getOperand(0) != Op) 10857 return PartialReduction(PrevOp, MaskEnd); 10858 10859 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 10860 for (int Index = 0; Index < (int)MaskEnd; ++Index) 10861 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 10862 return PartialReduction(PrevOp, MaskEnd); 10863 10864 PrevOp = Op; 10865 } 10866 10867 // Handle subvector reductions, which tend to appear after the shuffle 10868 // reduction stages. 10869 while (Op.getOpcode() == CandidateBinOp) { 10870 unsigned NumElts = Op.getValueType().getVectorNumElements(); 10871 SDValue Op0 = Op.getOperand(0); 10872 SDValue Op1 = Op.getOperand(1); 10873 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10874 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10875 Op0.getOperand(0) != Op1.getOperand(0)) 10876 break; 10877 SDValue Src = Op0.getOperand(0); 10878 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 10879 if (NumSrcElts != (2 * NumElts)) 10880 break; 10881 if (!(Op0.getConstantOperandAPInt(1) == 0 && 10882 Op1.getConstantOperandAPInt(1) == NumElts) && 10883 !(Op1.getConstantOperandAPInt(1) == 0 && 10884 Op0.getConstantOperandAPInt(1) == NumElts)) 10885 break; 10886 Op = Src; 10887 } 10888 10889 BinOp = (ISD::NodeType)CandidateBinOp; 10890 return Op; 10891 } 10892 10893 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 10894 assert(N->getNumValues() == 1 && 10895 "Can't unroll a vector with multiple results!"); 10896 10897 EVT VT = N->getValueType(0); 10898 unsigned NE = VT.getVectorNumElements(); 10899 EVT EltVT = VT.getVectorElementType(); 10900 SDLoc dl(N); 10901 10902 SmallVector<SDValue, 8> Scalars; 10903 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 10904 10905 // If ResNE is 0, fully unroll the vector op. 10906 if (ResNE == 0) 10907 ResNE = NE; 10908 else if (NE > ResNE) 10909 NE = ResNE; 10910 10911 unsigned i; 10912 for (i= 0; i != NE; ++i) { 10913 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 10914 SDValue Operand = N->getOperand(j); 10915 EVT OperandVT = Operand.getValueType(); 10916 if (OperandVT.isVector()) { 10917 // A vector operand; extract a single element. 10918 EVT OperandEltVT = OperandVT.getVectorElementType(); 10919 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 10920 Operand, getVectorIdxConstant(i, dl)); 10921 } else { 10922 // A scalar operand; just use it as is. 10923 Operands[j] = Operand; 10924 } 10925 } 10926 10927 switch (N->getOpcode()) { 10928 default: { 10929 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 10930 N->getFlags())); 10931 break; 10932 } 10933 case ISD::VSELECT: 10934 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 10935 break; 10936 case ISD::SHL: 10937 case ISD::SRA: 10938 case ISD::SRL: 10939 case ISD::ROTL: 10940 case ISD::ROTR: 10941 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 10942 getShiftAmountOperand(Operands[0].getValueType(), 10943 Operands[1]))); 10944 break; 10945 case ISD::SIGN_EXTEND_INREG: { 10946 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 10947 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 10948 Operands[0], 10949 getValueType(ExtVT))); 10950 } 10951 } 10952 } 10953 10954 for (; i < ResNE; ++i) 10955 Scalars.push_back(getUNDEF(EltVT)); 10956 10957 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 10958 return getBuildVector(VecVT, dl, Scalars); 10959 } 10960 10961 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 10962 SDNode *N, unsigned ResNE) { 10963 unsigned Opcode = N->getOpcode(); 10964 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 10965 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 10966 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 10967 "Expected an overflow opcode"); 10968 10969 EVT ResVT = N->getValueType(0); 10970 EVT OvVT = N->getValueType(1); 10971 EVT ResEltVT = ResVT.getVectorElementType(); 10972 EVT OvEltVT = OvVT.getVectorElementType(); 10973 SDLoc dl(N); 10974 10975 // If ResNE is 0, fully unroll the vector op. 10976 unsigned NE = ResVT.getVectorNumElements(); 10977 if (ResNE == 0) 10978 ResNE = NE; 10979 else if (NE > ResNE) 10980 NE = ResNE; 10981 10982 SmallVector<SDValue, 8> LHSScalars; 10983 SmallVector<SDValue, 8> RHSScalars; 10984 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 10985 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 10986 10987 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 10988 SDVTList VTs = getVTList(ResEltVT, SVT); 10989 SmallVector<SDValue, 8> ResScalars; 10990 SmallVector<SDValue, 8> OvScalars; 10991 for (unsigned i = 0; i < NE; ++i) { 10992 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 10993 SDValue Ov = 10994 getSelect(dl, OvEltVT, Res.getValue(1), 10995 getBoolConstant(true, dl, OvEltVT, ResVT), 10996 getConstant(0, dl, OvEltVT)); 10997 10998 ResScalars.push_back(Res); 10999 OvScalars.push_back(Ov); 11000 } 11001 11002 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 11003 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 11004 11005 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 11006 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 11007 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 11008 getBuildVector(NewOvVT, dl, OvScalars)); 11009 } 11010 11011 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 11012 LoadSDNode *Base, 11013 unsigned Bytes, 11014 int Dist) const { 11015 if (LD->isVolatile() || Base->isVolatile()) 11016 return false; 11017 // TODO: probably too restrictive for atomics, revisit 11018 if (!LD->isSimple()) 11019 return false; 11020 if (LD->isIndexed() || Base->isIndexed()) 11021 return false; 11022 if (LD->getChain() != Base->getChain()) 11023 return false; 11024 EVT VT = LD->getValueType(0); 11025 if (VT.getSizeInBits() / 8 != Bytes) 11026 return false; 11027 11028 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 11029 auto LocDecomp = BaseIndexOffset::match(LD, *this); 11030 11031 int64_t Offset = 0; 11032 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 11033 return (Dist * Bytes == Offset); 11034 return false; 11035 } 11036 11037 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 11038 /// if it cannot be inferred. 11039 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 11040 // If this is a GlobalAddress + cst, return the alignment. 11041 const GlobalValue *GV = nullptr; 11042 int64_t GVOffset = 0; 11043 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 11044 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 11045 KnownBits Known(PtrWidth); 11046 llvm::computeKnownBits(GV, Known, getDataLayout()); 11047 unsigned AlignBits = Known.countMinTrailingZeros(); 11048 if (AlignBits) 11049 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 11050 } 11051 11052 // If this is a direct reference to a stack slot, use information about the 11053 // stack slot's alignment. 11054 int FrameIdx = INT_MIN; 11055 int64_t FrameOffset = 0; 11056 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 11057 FrameIdx = FI->getIndex(); 11058 } else if (isBaseWithConstantOffset(Ptr) && 11059 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 11060 // Handle FI+Cst 11061 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 11062 FrameOffset = Ptr.getConstantOperandVal(1); 11063 } 11064 11065 if (FrameIdx != INT_MIN) { 11066 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 11067 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 11068 } 11069 11070 return None; 11071 } 11072 11073 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 11074 /// which is split (or expanded) into two not necessarily identical pieces. 11075 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 11076 // Currently all types are split in half. 11077 EVT LoVT, HiVT; 11078 if (!VT.isVector()) 11079 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 11080 else 11081 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 11082 11083 return std::make_pair(LoVT, HiVT); 11084 } 11085 11086 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 11087 /// type, dependent on an enveloping VT that has been split into two identical 11088 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 11089 std::pair<EVT, EVT> 11090 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 11091 bool *HiIsEmpty) const { 11092 EVT EltTp = VT.getVectorElementType(); 11093 // Examples: 11094 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 11095 // custom VL=9 with enveloping VL=8/8 yields 8/1 11096 // custom VL=10 with enveloping VL=8/8 yields 8/2 11097 // etc. 11098 ElementCount VTNumElts = VT.getVectorElementCount(); 11099 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 11100 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 11101 "Mixing fixed width and scalable vectors when enveloping a type"); 11102 EVT LoVT, HiVT; 11103 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 11104 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11105 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 11106 *HiIsEmpty = false; 11107 } else { 11108 // Flag that hi type has zero storage size, but return split envelop type 11109 // (this would be easier if vector types with zero elements were allowed). 11110 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 11111 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11112 *HiIsEmpty = true; 11113 } 11114 return std::make_pair(LoVT, HiVT); 11115 } 11116 11117 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 11118 /// low/high part. 11119 std::pair<SDValue, SDValue> 11120 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 11121 const EVT &HiVT) { 11122 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 11123 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 11124 "Splitting vector with an invalid mixture of fixed and scalable " 11125 "vector types"); 11126 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 11127 N.getValueType().getVectorMinNumElements() && 11128 "More vector elements requested than available!"); 11129 SDValue Lo, Hi; 11130 Lo = 11131 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 11132 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 11133 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 11134 // IDX with the runtime scaling factor of the result vector type. For 11135 // fixed-width result vectors, that runtime scaling factor is 1. 11136 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 11137 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 11138 return std::make_pair(Lo, Hi); 11139 } 11140 11141 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT, 11142 const SDLoc &DL) { 11143 // Split the vector length parameter. 11144 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts). 11145 EVT VT = N.getValueType(); 11146 assert(VecVT.getVectorElementCount().isKnownEven() && 11147 "Expecting the mask to be an evenly-sized vector"); 11148 unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2; 11149 SDValue HalfNumElts = 11150 VecVT.isFixedLengthVector() 11151 ? getConstant(HalfMinNumElts, DL, VT) 11152 : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts)); 11153 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts); 11154 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts); 11155 return std::make_pair(Lo, Hi); 11156 } 11157 11158 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 11159 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 11160 EVT VT = N.getValueType(); 11161 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 11162 NextPowerOf2(VT.getVectorNumElements())); 11163 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 11164 getVectorIdxConstant(0, DL)); 11165 } 11166 11167 void SelectionDAG::ExtractVectorElements(SDValue Op, 11168 SmallVectorImpl<SDValue> &Args, 11169 unsigned Start, unsigned Count, 11170 EVT EltVT) { 11171 EVT VT = Op.getValueType(); 11172 if (Count == 0) 11173 Count = VT.getVectorNumElements(); 11174 if (EltVT == EVT()) 11175 EltVT = VT.getVectorElementType(); 11176 SDLoc SL(Op); 11177 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 11178 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 11179 getVectorIdxConstant(i, SL))); 11180 } 11181 } 11182 11183 // getAddressSpace - Return the address space this GlobalAddress belongs to. 11184 unsigned GlobalAddressSDNode::getAddressSpace() const { 11185 return getGlobal()->getType()->getAddressSpace(); 11186 } 11187 11188 Type *ConstantPoolSDNode::getType() const { 11189 if (isMachineConstantPoolEntry()) 11190 return Val.MachineCPVal->getType(); 11191 return Val.ConstVal->getType(); 11192 } 11193 11194 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 11195 unsigned &SplatBitSize, 11196 bool &HasAnyUndefs, 11197 unsigned MinSplatBits, 11198 bool IsBigEndian) const { 11199 EVT VT = getValueType(0); 11200 assert(VT.isVector() && "Expected a vector type"); 11201 unsigned VecWidth = VT.getSizeInBits(); 11202 if (MinSplatBits > VecWidth) 11203 return false; 11204 11205 // FIXME: The widths are based on this node's type, but build vectors can 11206 // truncate their operands. 11207 SplatValue = APInt(VecWidth, 0); 11208 SplatUndef = APInt(VecWidth, 0); 11209 11210 // Get the bits. Bits with undefined values (when the corresponding element 11211 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 11212 // in SplatValue. If any of the values are not constant, give up and return 11213 // false. 11214 unsigned int NumOps = getNumOperands(); 11215 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 11216 unsigned EltWidth = VT.getScalarSizeInBits(); 11217 11218 for (unsigned j = 0; j < NumOps; ++j) { 11219 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 11220 SDValue OpVal = getOperand(i); 11221 unsigned BitPos = j * EltWidth; 11222 11223 if (OpVal.isUndef()) 11224 SplatUndef.setBits(BitPos, BitPos + EltWidth); 11225 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 11226 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 11227 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 11228 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 11229 else 11230 return false; 11231 } 11232 11233 // The build_vector is all constants or undefs. Find the smallest element 11234 // size that splats the vector. 11235 HasAnyUndefs = (SplatUndef != 0); 11236 11237 // FIXME: This does not work for vectors with elements less than 8 bits. 11238 while (VecWidth > 8) { 11239 unsigned HalfSize = VecWidth / 2; 11240 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize); 11241 APInt LowValue = SplatValue.extractBits(HalfSize, 0); 11242 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize); 11243 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0); 11244 11245 // If the two halves do not match (ignoring undef bits), stop here. 11246 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 11247 MinSplatBits > HalfSize) 11248 break; 11249 11250 SplatValue = HighValue | LowValue; 11251 SplatUndef = HighUndef & LowUndef; 11252 11253 VecWidth = HalfSize; 11254 } 11255 11256 SplatBitSize = VecWidth; 11257 return true; 11258 } 11259 11260 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 11261 BitVector *UndefElements) const { 11262 unsigned NumOps = getNumOperands(); 11263 if (UndefElements) { 11264 UndefElements->clear(); 11265 UndefElements->resize(NumOps); 11266 } 11267 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 11268 if (!DemandedElts) 11269 return SDValue(); 11270 SDValue Splatted; 11271 for (unsigned i = 0; i != NumOps; ++i) { 11272 if (!DemandedElts[i]) 11273 continue; 11274 SDValue Op = getOperand(i); 11275 if (Op.isUndef()) { 11276 if (UndefElements) 11277 (*UndefElements)[i] = true; 11278 } else if (!Splatted) { 11279 Splatted = Op; 11280 } else if (Splatted != Op) { 11281 return SDValue(); 11282 } 11283 } 11284 11285 if (!Splatted) { 11286 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 11287 assert(getOperand(FirstDemandedIdx).isUndef() && 11288 "Can only have a splat without a constant for all undefs."); 11289 return getOperand(FirstDemandedIdx); 11290 } 11291 11292 return Splatted; 11293 } 11294 11295 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 11296 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 11297 return getSplatValue(DemandedElts, UndefElements); 11298 } 11299 11300 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 11301 SmallVectorImpl<SDValue> &Sequence, 11302 BitVector *UndefElements) const { 11303 unsigned NumOps = getNumOperands(); 11304 Sequence.clear(); 11305 if (UndefElements) { 11306 UndefElements->clear(); 11307 UndefElements->resize(NumOps); 11308 } 11309 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 11310 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 11311 return false; 11312 11313 // Set the undefs even if we don't find a sequence (like getSplatValue). 11314 if (UndefElements) 11315 for (unsigned I = 0; I != NumOps; ++I) 11316 if (DemandedElts[I] && getOperand(I).isUndef()) 11317 (*UndefElements)[I] = true; 11318 11319 // Iteratively widen the sequence length looking for repetitions. 11320 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 11321 Sequence.append(SeqLen, SDValue()); 11322 for (unsigned I = 0; I != NumOps; ++I) { 11323 if (!DemandedElts[I]) 11324 continue; 11325 SDValue &SeqOp = Sequence[I % SeqLen]; 11326 SDValue Op = getOperand(I); 11327 if (Op.isUndef()) { 11328 if (!SeqOp) 11329 SeqOp = Op; 11330 continue; 11331 } 11332 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 11333 Sequence.clear(); 11334 break; 11335 } 11336 SeqOp = Op; 11337 } 11338 if (!Sequence.empty()) 11339 return true; 11340 } 11341 11342 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 11343 return false; 11344 } 11345 11346 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 11347 BitVector *UndefElements) const { 11348 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 11349 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 11350 } 11351 11352 ConstantSDNode * 11353 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 11354 BitVector *UndefElements) const { 11355 return dyn_cast_or_null<ConstantSDNode>( 11356 getSplatValue(DemandedElts, UndefElements)); 11357 } 11358 11359 ConstantSDNode * 11360 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 11361 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 11362 } 11363 11364 ConstantFPSDNode * 11365 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 11366 BitVector *UndefElements) const { 11367 return dyn_cast_or_null<ConstantFPSDNode>( 11368 getSplatValue(DemandedElts, UndefElements)); 11369 } 11370 11371 ConstantFPSDNode * 11372 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 11373 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 11374 } 11375 11376 int32_t 11377 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 11378 uint32_t BitWidth) const { 11379 if (ConstantFPSDNode *CN = 11380 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 11381 bool IsExact; 11382 APSInt IntVal(BitWidth); 11383 const APFloat &APF = CN->getValueAPF(); 11384 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 11385 APFloat::opOK || 11386 !IsExact) 11387 return -1; 11388 11389 return IntVal.exactLogBase2(); 11390 } 11391 return -1; 11392 } 11393 11394 bool BuildVectorSDNode::getConstantRawBits( 11395 bool IsLittleEndian, unsigned DstEltSizeInBits, 11396 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const { 11397 // Early-out if this contains anything but Undef/Constant/ConstantFP. 11398 if (!isConstant()) 11399 return false; 11400 11401 unsigned NumSrcOps = getNumOperands(); 11402 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits(); 11403 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11404 "Invalid bitcast scale"); 11405 11406 // Extract raw src bits. 11407 SmallVector<APInt> SrcBitElements(NumSrcOps, 11408 APInt::getNullValue(SrcEltSizeInBits)); 11409 BitVector SrcUndeElements(NumSrcOps, false); 11410 11411 for (unsigned I = 0; I != NumSrcOps; ++I) { 11412 SDValue Op = getOperand(I); 11413 if (Op.isUndef()) { 11414 SrcUndeElements.set(I); 11415 continue; 11416 } 11417 auto *CInt = dyn_cast<ConstantSDNode>(Op); 11418 auto *CFP = dyn_cast<ConstantFPSDNode>(Op); 11419 assert((CInt || CFP) && "Unknown constant"); 11420 SrcBitElements[I] = 11421 CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits) 11422 : CFP->getValueAPF().bitcastToAPInt(); 11423 } 11424 11425 // Recast to dst width. 11426 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements, 11427 SrcBitElements, UndefElements, SrcUndeElements); 11428 return true; 11429 } 11430 11431 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian, 11432 unsigned DstEltSizeInBits, 11433 SmallVectorImpl<APInt> &DstBitElements, 11434 ArrayRef<APInt> SrcBitElements, 11435 BitVector &DstUndefElements, 11436 const BitVector &SrcUndefElements) { 11437 unsigned NumSrcOps = SrcBitElements.size(); 11438 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth(); 11439 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11440 "Invalid bitcast scale"); 11441 assert(NumSrcOps == SrcUndefElements.size() && 11442 "Vector size mismatch"); 11443 11444 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits; 11445 DstUndefElements.clear(); 11446 DstUndefElements.resize(NumDstOps, false); 11447 DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits)); 11448 11449 // Concatenate src elements constant bits together into dst element. 11450 if (SrcEltSizeInBits <= DstEltSizeInBits) { 11451 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits; 11452 for (unsigned I = 0; I != NumDstOps; ++I) { 11453 DstUndefElements.set(I); 11454 APInt &DstBits = DstBitElements[I]; 11455 for (unsigned J = 0; J != Scale; ++J) { 11456 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11457 if (SrcUndefElements[Idx]) 11458 continue; 11459 DstUndefElements.reset(I); 11460 const APInt &SrcBits = SrcBitElements[Idx]; 11461 assert(SrcBits.getBitWidth() == SrcEltSizeInBits && 11462 "Illegal constant bitwidths"); 11463 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits); 11464 } 11465 } 11466 return; 11467 } 11468 11469 // Split src element constant bits into dst elements. 11470 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits; 11471 for (unsigned I = 0; I != NumSrcOps; ++I) { 11472 if (SrcUndefElements[I]) { 11473 DstUndefElements.set(I * Scale, (I + 1) * Scale); 11474 continue; 11475 } 11476 const APInt &SrcBits = SrcBitElements[I]; 11477 for (unsigned J = 0; J != Scale; ++J) { 11478 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11479 APInt &DstBits = DstBitElements[Idx]; 11480 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits); 11481 } 11482 } 11483 } 11484 11485 bool BuildVectorSDNode::isConstant() const { 11486 for (const SDValue &Op : op_values()) { 11487 unsigned Opc = Op.getOpcode(); 11488 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 11489 return false; 11490 } 11491 return true; 11492 } 11493 11494 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 11495 // Find the first non-undef value in the shuffle mask. 11496 unsigned i, e; 11497 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 11498 /* search */; 11499 11500 // If all elements are undefined, this shuffle can be considered a splat 11501 // (although it should eventually get simplified away completely). 11502 if (i == e) 11503 return true; 11504 11505 // Make sure all remaining elements are either undef or the same as the first 11506 // non-undef value. 11507 for (int Idx = Mask[i]; i != e; ++i) 11508 if (Mask[i] >= 0 && Mask[i] != Idx) 11509 return false; 11510 return true; 11511 } 11512 11513 // Returns the SDNode if it is a constant integer BuildVector 11514 // or constant integer. 11515 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 11516 if (isa<ConstantSDNode>(N)) 11517 return N.getNode(); 11518 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 11519 return N.getNode(); 11520 // Treat a GlobalAddress supporting constant offset folding as a 11521 // constant integer. 11522 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 11523 if (GA->getOpcode() == ISD::GlobalAddress && 11524 TLI->isOffsetFoldingLegal(GA)) 11525 return GA; 11526 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11527 isa<ConstantSDNode>(N.getOperand(0))) 11528 return N.getNode(); 11529 return nullptr; 11530 } 11531 11532 // Returns the SDNode if it is a constant float BuildVector 11533 // or constant float. 11534 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 11535 if (isa<ConstantFPSDNode>(N)) 11536 return N.getNode(); 11537 11538 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 11539 return N.getNode(); 11540 11541 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11542 isa<ConstantFPSDNode>(N.getOperand(0))) 11543 return N.getNode(); 11544 11545 return nullptr; 11546 } 11547 11548 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 11549 assert(!Node->OperandList && "Node already has operands"); 11550 assert(SDNode::getMaxNumOperands() >= Vals.size() && 11551 "too many operands to fit into SDNode"); 11552 SDUse *Ops = OperandRecycler.allocate( 11553 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 11554 11555 bool IsDivergent = false; 11556 for (unsigned I = 0; I != Vals.size(); ++I) { 11557 Ops[I].setUser(Node); 11558 Ops[I].setInitial(Vals[I]); 11559 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 11560 IsDivergent |= Ops[I].getNode()->isDivergent(); 11561 } 11562 Node->NumOperands = Vals.size(); 11563 Node->OperandList = Ops; 11564 if (!TLI->isSDNodeAlwaysUniform(Node)) { 11565 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 11566 Node->SDNodeBits.IsDivergent = IsDivergent; 11567 } 11568 checkForCycles(Node); 11569 } 11570 11571 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 11572 SmallVectorImpl<SDValue> &Vals) { 11573 size_t Limit = SDNode::getMaxNumOperands(); 11574 while (Vals.size() > Limit) { 11575 unsigned SliceIdx = Vals.size() - Limit; 11576 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 11577 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 11578 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 11579 Vals.emplace_back(NewTF); 11580 } 11581 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 11582 } 11583 11584 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 11585 EVT VT, SDNodeFlags Flags) { 11586 switch (Opcode) { 11587 default: 11588 return SDValue(); 11589 case ISD::ADD: 11590 case ISD::OR: 11591 case ISD::XOR: 11592 case ISD::UMAX: 11593 return getConstant(0, DL, VT); 11594 case ISD::MUL: 11595 return getConstant(1, DL, VT); 11596 case ISD::AND: 11597 case ISD::UMIN: 11598 return getAllOnesConstant(DL, VT); 11599 case ISD::SMAX: 11600 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 11601 case ISD::SMIN: 11602 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 11603 case ISD::FADD: 11604 return getConstantFP(-0.0, DL, VT); 11605 case ISD::FMUL: 11606 return getConstantFP(1.0, DL, VT); 11607 case ISD::FMINNUM: 11608 case ISD::FMAXNUM: { 11609 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 11610 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 11611 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 11612 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 11613 APFloat::getLargest(Semantics); 11614 if (Opcode == ISD::FMAXNUM) 11615 NeutralAF.changeSign(); 11616 11617 return getConstantFP(NeutralAF, DL, VT); 11618 } 11619 } 11620 } 11621 11622 #ifndef NDEBUG 11623 static void checkForCyclesHelper(const SDNode *N, 11624 SmallPtrSetImpl<const SDNode*> &Visited, 11625 SmallPtrSetImpl<const SDNode*> &Checked, 11626 const llvm::SelectionDAG *DAG) { 11627 // If this node has already been checked, don't check it again. 11628 if (Checked.count(N)) 11629 return; 11630 11631 // If a node has already been visited on this depth-first walk, reject it as 11632 // a cycle. 11633 if (!Visited.insert(N).second) { 11634 errs() << "Detected cycle in SelectionDAG\n"; 11635 dbgs() << "Offending node:\n"; 11636 N->dumprFull(DAG); dbgs() << "\n"; 11637 abort(); 11638 } 11639 11640 for (const SDValue &Op : N->op_values()) 11641 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 11642 11643 Checked.insert(N); 11644 Visited.erase(N); 11645 } 11646 #endif 11647 11648 void llvm::checkForCycles(const llvm::SDNode *N, 11649 const llvm::SelectionDAG *DAG, 11650 bool force) { 11651 #ifndef NDEBUG 11652 bool check = force; 11653 #ifdef EXPENSIVE_CHECKS 11654 check = true; 11655 #endif // EXPENSIVE_CHECKS 11656 if (check) { 11657 assert(N && "Checking nonexistent SDNode"); 11658 SmallPtrSet<const SDNode*, 32> visited; 11659 SmallPtrSet<const SDNode*, 32> checked; 11660 checkForCyclesHelper(N, visited, checked, DAG); 11661 } 11662 #endif // !NDEBUG 11663 } 11664 11665 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 11666 checkForCycles(DAG->getRoot().getNode(), DAG, force); 11667 } 11668