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().trunc(EltSize); 145 return true; 146 } 147 if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) { 148 SplatVal = Op0->getValueAPF().bitcastToAPInt().trunc(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 switch (V.getOpcode()) { 2473 default: 2474 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, *this); 2475 case ISD::Constant: { 2476 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue(); 2477 APInt NewVal = CVal & DemandedBits; 2478 if (NewVal != CVal) 2479 return getConstant(NewVal, SDLoc(V), V.getValueType()); 2480 break; 2481 } 2482 case ISD::SRL: 2483 // Only look at single-use SRLs. 2484 if (!V.getNode()->hasOneUse()) 2485 break; 2486 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2487 // See if we can recursively simplify the LHS. 2488 unsigned Amt = RHSC->getZExtValue(); 2489 2490 // Watch out for shift count overflow though. 2491 if (Amt >= DemandedBits.getBitWidth()) 2492 break; 2493 APInt SrcDemandedBits = DemandedBits << Amt; 2494 if (SDValue SimplifyLHS = TLI->SimplifyMultipleUseDemandedBits( 2495 V.getOperand(0), SrcDemandedBits, *this)) 2496 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS, 2497 V.getOperand(1)); 2498 } 2499 break; 2500 } 2501 return SDValue(); 2502 } 2503 2504 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2505 /// use this predicate to simplify operations downstream. 2506 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2507 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2508 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2509 } 2510 2511 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2512 /// this predicate to simplify operations downstream. Mask is known to be zero 2513 /// for bits that V cannot have. 2514 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2515 unsigned Depth) const { 2516 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2517 } 2518 2519 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2520 /// DemandedElts. We use this predicate to simplify operations downstream. 2521 /// Mask is known to be zero for bits that V cannot have. 2522 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2523 const APInt &DemandedElts, 2524 unsigned Depth) const { 2525 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2526 } 2527 2528 /// MaskedVectorIsZero - Return true if 'Op' is known to be zero in 2529 /// DemandedElts. We use this predicate to simplify operations downstream. 2530 bool SelectionDAG::MaskedVectorIsZero(SDValue V, const APInt &DemandedElts, 2531 unsigned Depth /* = 0 */) const { 2532 APInt Mask = APInt::getAllOnes(V.getScalarValueSizeInBits()); 2533 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2534 } 2535 2536 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2537 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2538 unsigned Depth) const { 2539 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2540 } 2541 2542 /// isSplatValue - Return true if the vector V has the same value 2543 /// across all DemandedElts. For scalable vectors it does not make 2544 /// sense to specify which elements are demanded or undefined, therefore 2545 /// they are simply ignored. 2546 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2547 APInt &UndefElts, unsigned Depth) const { 2548 unsigned Opcode = V.getOpcode(); 2549 EVT VT = V.getValueType(); 2550 assert(VT.isVector() && "Vector type expected"); 2551 2552 if (!VT.isScalableVector() && !DemandedElts) 2553 return false; // No demanded elts, better to assume we don't know anything. 2554 2555 if (Depth >= MaxRecursionDepth) 2556 return false; // Limit search depth. 2557 2558 // Deal with some common cases here that work for both fixed and scalable 2559 // vector types. 2560 switch (Opcode) { 2561 case ISD::SPLAT_VECTOR: 2562 UndefElts = V.getOperand(0).isUndef() 2563 ? APInt::getAllOnes(DemandedElts.getBitWidth()) 2564 : APInt(DemandedElts.getBitWidth(), 0); 2565 return true; 2566 case ISD::ADD: 2567 case ISD::SUB: 2568 case ISD::AND: 2569 case ISD::XOR: 2570 case ISD::OR: { 2571 APInt UndefLHS, UndefRHS; 2572 SDValue LHS = V.getOperand(0); 2573 SDValue RHS = V.getOperand(1); 2574 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2575 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2576 UndefElts = UndefLHS | UndefRHS; 2577 return true; 2578 } 2579 return false; 2580 } 2581 case ISD::ABS: 2582 case ISD::TRUNCATE: 2583 case ISD::SIGN_EXTEND: 2584 case ISD::ZERO_EXTEND: 2585 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2586 default: 2587 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 2588 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 2589 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth); 2590 break; 2591 } 2592 2593 // We don't support other cases than those above for scalable vectors at 2594 // the moment. 2595 if (VT.isScalableVector()) 2596 return false; 2597 2598 unsigned NumElts = VT.getVectorNumElements(); 2599 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2600 UndefElts = APInt::getZero(NumElts); 2601 2602 switch (Opcode) { 2603 case ISD::BUILD_VECTOR: { 2604 SDValue Scl; 2605 for (unsigned i = 0; i != NumElts; ++i) { 2606 SDValue Op = V.getOperand(i); 2607 if (Op.isUndef()) { 2608 UndefElts.setBit(i); 2609 continue; 2610 } 2611 if (!DemandedElts[i]) 2612 continue; 2613 if (Scl && Scl != Op) 2614 return false; 2615 Scl = Op; 2616 } 2617 return true; 2618 } 2619 case ISD::VECTOR_SHUFFLE: { 2620 // Check if this is a shuffle node doing a splat or a shuffle of a splat. 2621 APInt DemandedLHS = APInt::getNullValue(NumElts); 2622 APInt DemandedRHS = APInt::getNullValue(NumElts); 2623 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2624 for (int i = 0; i != (int)NumElts; ++i) { 2625 int M = Mask[i]; 2626 if (M < 0) { 2627 UndefElts.setBit(i); 2628 continue; 2629 } 2630 if (!DemandedElts[i]) 2631 continue; 2632 if (M < (int)NumElts) 2633 DemandedLHS.setBit(M); 2634 else 2635 DemandedRHS.setBit(M - NumElts); 2636 } 2637 2638 // If we aren't demanding either op, assume there's no splat. 2639 // If we are demanding both ops, assume there's no splat. 2640 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) || 2641 (!DemandedLHS.isZero() && !DemandedRHS.isZero())) 2642 return false; 2643 2644 // See if the demanded elts of the source op is a splat or we only demand 2645 // one element, which should always be a splat. 2646 // TODO: Handle source ops splats with undefs. 2647 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) { 2648 APInt SrcUndefs; 2649 return (SrcElts.countPopulation() == 1) || 2650 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) && 2651 (SrcElts & SrcUndefs).isZero()); 2652 }; 2653 if (!DemandedLHS.isZero()) 2654 return CheckSplatSrc(V.getOperand(0), DemandedLHS); 2655 return CheckSplatSrc(V.getOperand(1), DemandedRHS); 2656 } 2657 case ISD::EXTRACT_SUBVECTOR: { 2658 // Offset the demanded elts by the subvector index. 2659 SDValue Src = V.getOperand(0); 2660 // We don't support scalable vectors at the moment. 2661 if (Src.getValueType().isScalableVector()) 2662 return false; 2663 uint64_t Idx = V.getConstantOperandVal(1); 2664 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2665 APInt UndefSrcElts; 2666 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 2667 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2668 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2669 return true; 2670 } 2671 break; 2672 } 2673 case ISD::ANY_EXTEND_VECTOR_INREG: 2674 case ISD::SIGN_EXTEND_VECTOR_INREG: 2675 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2676 // Widen the demanded elts by the src element count. 2677 SDValue Src = V.getOperand(0); 2678 // We don't support scalable vectors at the moment. 2679 if (Src.getValueType().isScalableVector()) 2680 return false; 2681 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2682 APInt UndefSrcElts; 2683 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts); 2684 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2685 UndefElts = UndefSrcElts.trunc(NumElts); 2686 return true; 2687 } 2688 break; 2689 } 2690 case ISD::BITCAST: { 2691 SDValue Src = V.getOperand(0); 2692 EVT SrcVT = Src.getValueType(); 2693 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits(); 2694 unsigned BitWidth = VT.getScalarSizeInBits(); 2695 2696 // Ignore bitcasts from unsupported types. 2697 // TODO: Add fp support? 2698 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger()) 2699 break; 2700 2701 // Bitcast 'small element' vector to 'large element' vector. 2702 if ((BitWidth % SrcBitWidth) == 0) { 2703 // See if each sub element is a splat. 2704 unsigned Scale = BitWidth / SrcBitWidth; 2705 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2706 APInt ScaledDemandedElts = 2707 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2708 for (unsigned I = 0; I != Scale; ++I) { 2709 APInt SubUndefElts; 2710 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I); 2711 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt); 2712 SubDemandedElts &= ScaledDemandedElts; 2713 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1)) 2714 return false; 2715 2716 // Here we can't do "MatchAnyBits" operation merge for undef bits. 2717 // Because some operation only use part value of the source. 2718 // Take llvm.fshl.* for example: 2719 // t1: v4i32 = Constant:i32<12>, undef:i32, Constant:i32<12>, undef:i32 2720 // t2: v2i64 = bitcast t1 2721 // t5: v2i64 = fshl t3, t4, t2 2722 // We can not convert t2 to {i64 undef, i64 undef} 2723 UndefElts |= APIntOps::ScaleBitMask(SubUndefElts, NumElts, 2724 /*MatchAllBits=*/true); 2725 } 2726 return true; 2727 } 2728 break; 2729 } 2730 } 2731 2732 return false; 2733 } 2734 2735 /// Helper wrapper to main isSplatValue function. 2736 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const { 2737 EVT VT = V.getValueType(); 2738 assert(VT.isVector() && "Vector type expected"); 2739 2740 APInt UndefElts; 2741 APInt DemandedElts; 2742 2743 // For now we don't support this with scalable vectors. 2744 if (!VT.isScalableVector()) 2745 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2746 return isSplatValue(V, DemandedElts, UndefElts) && 2747 (AllowUndefs || !UndefElts); 2748 } 2749 2750 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2751 V = peekThroughExtractSubvectors(V); 2752 2753 EVT VT = V.getValueType(); 2754 unsigned Opcode = V.getOpcode(); 2755 switch (Opcode) { 2756 default: { 2757 APInt UndefElts; 2758 APInt DemandedElts; 2759 2760 if (!VT.isScalableVector()) 2761 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2762 2763 if (isSplatValue(V, DemandedElts, UndefElts)) { 2764 if (VT.isScalableVector()) { 2765 // DemandedElts and UndefElts are ignored for scalable vectors, since 2766 // the only supported cases are SPLAT_VECTOR nodes. 2767 SplatIdx = 0; 2768 } else { 2769 // Handle case where all demanded elements are UNDEF. 2770 if (DemandedElts.isSubsetOf(UndefElts)) { 2771 SplatIdx = 0; 2772 return getUNDEF(VT); 2773 } 2774 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes(); 2775 } 2776 return V; 2777 } 2778 break; 2779 } 2780 case ISD::SPLAT_VECTOR: 2781 SplatIdx = 0; 2782 return V; 2783 case ISD::VECTOR_SHUFFLE: { 2784 if (VT.isScalableVector()) 2785 return SDValue(); 2786 2787 // Check if this is a shuffle node doing a splat. 2788 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2789 // getTargetVShiftNode currently struggles without the splat source. 2790 auto *SVN = cast<ShuffleVectorSDNode>(V); 2791 if (!SVN->isSplat()) 2792 break; 2793 int Idx = SVN->getSplatIndex(); 2794 int NumElts = V.getValueType().getVectorNumElements(); 2795 SplatIdx = Idx % NumElts; 2796 return V.getOperand(Idx / NumElts); 2797 } 2798 } 2799 2800 return SDValue(); 2801 } 2802 2803 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) { 2804 int SplatIdx; 2805 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) { 2806 EVT SVT = SrcVector.getValueType().getScalarType(); 2807 EVT LegalSVT = SVT; 2808 if (LegalTypes && !TLI->isTypeLegal(SVT)) { 2809 if (!SVT.isInteger()) 2810 return SDValue(); 2811 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 2812 if (LegalSVT.bitsLT(SVT)) 2813 return SDValue(); 2814 } 2815 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector, 2816 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2817 } 2818 return SDValue(); 2819 } 2820 2821 const APInt * 2822 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2823 const APInt &DemandedElts) const { 2824 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2825 V.getOpcode() == ISD::SRA) && 2826 "Unknown shift node"); 2827 unsigned BitWidth = V.getScalarValueSizeInBits(); 2828 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2829 // Shifting more than the bitwidth is not valid. 2830 const APInt &ShAmt = SA->getAPIntValue(); 2831 if (ShAmt.ult(BitWidth)) 2832 return &ShAmt; 2833 } 2834 return nullptr; 2835 } 2836 2837 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2838 SDValue V, const APInt &DemandedElts) const { 2839 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2840 V.getOpcode() == ISD::SRA) && 2841 "Unknown shift node"); 2842 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2843 return ValidAmt; 2844 unsigned BitWidth = V.getScalarValueSizeInBits(); 2845 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2846 if (!BV) 2847 return nullptr; 2848 const APInt *MinShAmt = nullptr; 2849 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2850 if (!DemandedElts[i]) 2851 continue; 2852 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2853 if (!SA) 2854 return nullptr; 2855 // Shifting more than the bitwidth is not valid. 2856 const APInt &ShAmt = SA->getAPIntValue(); 2857 if (ShAmt.uge(BitWidth)) 2858 return nullptr; 2859 if (MinShAmt && MinShAmt->ule(ShAmt)) 2860 continue; 2861 MinShAmt = &ShAmt; 2862 } 2863 return MinShAmt; 2864 } 2865 2866 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2867 SDValue V, const APInt &DemandedElts) const { 2868 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2869 V.getOpcode() == ISD::SRA) && 2870 "Unknown shift node"); 2871 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2872 return ValidAmt; 2873 unsigned BitWidth = V.getScalarValueSizeInBits(); 2874 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2875 if (!BV) 2876 return nullptr; 2877 const APInt *MaxShAmt = nullptr; 2878 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2879 if (!DemandedElts[i]) 2880 continue; 2881 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2882 if (!SA) 2883 return nullptr; 2884 // Shifting more than the bitwidth is not valid. 2885 const APInt &ShAmt = SA->getAPIntValue(); 2886 if (ShAmt.uge(BitWidth)) 2887 return nullptr; 2888 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2889 continue; 2890 MaxShAmt = &ShAmt; 2891 } 2892 return MaxShAmt; 2893 } 2894 2895 /// Determine which bits of Op are known to be either zero or one and return 2896 /// them in Known. For vectors, the known bits are those that are shared by 2897 /// every vector element. 2898 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 2899 EVT VT = Op.getValueType(); 2900 2901 // TOOD: Until we have a plan for how to represent demanded elements for 2902 // scalable vectors, we can just bail out for now. 2903 if (Op.getValueType().isScalableVector()) { 2904 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2905 return KnownBits(BitWidth); 2906 } 2907 2908 APInt DemandedElts = VT.isVector() 2909 ? APInt::getAllOnes(VT.getVectorNumElements()) 2910 : APInt(1, 1); 2911 return computeKnownBits(Op, DemandedElts, Depth); 2912 } 2913 2914 /// Determine which bits of Op are known to be either zero or one and return 2915 /// them in Known. The DemandedElts argument allows us to only collect the known 2916 /// bits that are shared by the requested vector elements. 2917 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 2918 unsigned Depth) const { 2919 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2920 2921 KnownBits Known(BitWidth); // Don't know anything. 2922 2923 // TOOD: Until we have a plan for how to represent demanded elements for 2924 // scalable vectors, we can just bail out for now. 2925 if (Op.getValueType().isScalableVector()) 2926 return Known; 2927 2928 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2929 // We know all of the bits for a constant! 2930 return KnownBits::makeConstant(C->getAPIntValue()); 2931 } 2932 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 2933 // We know all of the bits for a constant fp! 2934 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 2935 } 2936 2937 if (Depth >= MaxRecursionDepth) 2938 return Known; // Limit search depth. 2939 2940 KnownBits Known2; 2941 unsigned NumElts = DemandedElts.getBitWidth(); 2942 assert((!Op.getValueType().isVector() || 2943 NumElts == Op.getValueType().getVectorNumElements()) && 2944 "Unexpected vector size"); 2945 2946 if (!DemandedElts) 2947 return Known; // No demanded elts, better to assume we don't know anything. 2948 2949 unsigned Opcode = Op.getOpcode(); 2950 switch (Opcode) { 2951 case ISD::BUILD_VECTOR: 2952 // Collect the known bits that are shared by every demanded vector element. 2953 Known.Zero.setAllBits(); Known.One.setAllBits(); 2954 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 2955 if (!DemandedElts[i]) 2956 continue; 2957 2958 SDValue SrcOp = Op.getOperand(i); 2959 Known2 = computeKnownBits(SrcOp, Depth + 1); 2960 2961 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2962 if (SrcOp.getValueSizeInBits() != BitWidth) { 2963 assert(SrcOp.getValueSizeInBits() > BitWidth && 2964 "Expected BUILD_VECTOR implicit truncation"); 2965 Known2 = Known2.trunc(BitWidth); 2966 } 2967 2968 // Known bits are the values that are shared by every demanded element. 2969 Known = KnownBits::commonBits(Known, Known2); 2970 2971 // If we don't know any bits, early out. 2972 if (Known.isUnknown()) 2973 break; 2974 } 2975 break; 2976 case ISD::VECTOR_SHUFFLE: { 2977 // Collect the known bits that are shared by every vector element referenced 2978 // by the shuffle. 2979 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 2980 Known.Zero.setAllBits(); Known.One.setAllBits(); 2981 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 2982 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 2983 for (unsigned i = 0; i != NumElts; ++i) { 2984 if (!DemandedElts[i]) 2985 continue; 2986 2987 int M = SVN->getMaskElt(i); 2988 if (M < 0) { 2989 // For UNDEF elements, we don't know anything about the common state of 2990 // the shuffle result. 2991 Known.resetAll(); 2992 DemandedLHS.clearAllBits(); 2993 DemandedRHS.clearAllBits(); 2994 break; 2995 } 2996 2997 if ((unsigned)M < NumElts) 2998 DemandedLHS.setBit((unsigned)M % NumElts); 2999 else 3000 DemandedRHS.setBit((unsigned)M % NumElts); 3001 } 3002 // Known bits are the values that are shared by every demanded element. 3003 if (!!DemandedLHS) { 3004 SDValue LHS = Op.getOperand(0); 3005 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 3006 Known = KnownBits::commonBits(Known, Known2); 3007 } 3008 // If we don't know any bits, early out. 3009 if (Known.isUnknown()) 3010 break; 3011 if (!!DemandedRHS) { 3012 SDValue RHS = Op.getOperand(1); 3013 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 3014 Known = KnownBits::commonBits(Known, Known2); 3015 } 3016 break; 3017 } 3018 case ISD::CONCAT_VECTORS: { 3019 // Split DemandedElts and test each of the demanded subvectors. 3020 Known.Zero.setAllBits(); Known.One.setAllBits(); 3021 EVT SubVectorVT = Op.getOperand(0).getValueType(); 3022 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 3023 unsigned NumSubVectors = Op.getNumOperands(); 3024 for (unsigned i = 0; i != NumSubVectors; ++i) { 3025 APInt DemandedSub = 3026 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 3027 if (!!DemandedSub) { 3028 SDValue Sub = Op.getOperand(i); 3029 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 3030 Known = KnownBits::commonBits(Known, Known2); 3031 } 3032 // If we don't know any bits, early out. 3033 if (Known.isUnknown()) 3034 break; 3035 } 3036 break; 3037 } 3038 case ISD::INSERT_SUBVECTOR: { 3039 // Demand any elements from the subvector and the remainder from the src its 3040 // inserted into. 3041 SDValue Src = Op.getOperand(0); 3042 SDValue Sub = Op.getOperand(1); 3043 uint64_t Idx = Op.getConstantOperandVal(2); 3044 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 3045 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 3046 APInt DemandedSrcElts = DemandedElts; 3047 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 3048 3049 Known.One.setAllBits(); 3050 Known.Zero.setAllBits(); 3051 if (!!DemandedSubElts) { 3052 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 3053 if (Known.isUnknown()) 3054 break; // early-out. 3055 } 3056 if (!!DemandedSrcElts) { 3057 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3058 Known = KnownBits::commonBits(Known, Known2); 3059 } 3060 break; 3061 } 3062 case ISD::EXTRACT_SUBVECTOR: { 3063 // Offset the demanded elts by the subvector index. 3064 SDValue Src = Op.getOperand(0); 3065 // Bail until we can represent demanded elements for scalable vectors. 3066 if (Src.getValueType().isScalableVector()) 3067 break; 3068 uint64_t Idx = Op.getConstantOperandVal(1); 3069 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3070 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 3071 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3072 break; 3073 } 3074 case ISD::SCALAR_TO_VECTOR: { 3075 // We know about scalar_to_vector as much as we know about it source, 3076 // which becomes the first element of otherwise unknown vector. 3077 if (DemandedElts != 1) 3078 break; 3079 3080 SDValue N0 = Op.getOperand(0); 3081 Known = computeKnownBits(N0, Depth + 1); 3082 if (N0.getValueSizeInBits() != BitWidth) 3083 Known = Known.trunc(BitWidth); 3084 3085 break; 3086 } 3087 case ISD::BITCAST: { 3088 SDValue N0 = Op.getOperand(0); 3089 EVT SubVT = N0.getValueType(); 3090 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 3091 3092 // Ignore bitcasts from unsupported types. 3093 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 3094 break; 3095 3096 // Fast handling of 'identity' bitcasts. 3097 if (BitWidth == SubBitWidth) { 3098 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 3099 break; 3100 } 3101 3102 bool IsLE = getDataLayout().isLittleEndian(); 3103 3104 // Bitcast 'small element' vector to 'large element' scalar/vector. 3105 if ((BitWidth % SubBitWidth) == 0) { 3106 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 3107 3108 // Collect known bits for the (larger) output by collecting the known 3109 // bits from each set of sub elements and shift these into place. 3110 // We need to separately call computeKnownBits for each set of 3111 // sub elements as the knownbits for each is likely to be different. 3112 unsigned SubScale = BitWidth / SubBitWidth; 3113 APInt SubDemandedElts(NumElts * SubScale, 0); 3114 for (unsigned i = 0; i != NumElts; ++i) 3115 if (DemandedElts[i]) 3116 SubDemandedElts.setBit(i * SubScale); 3117 3118 for (unsigned i = 0; i != SubScale; ++i) { 3119 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 3120 Depth + 1); 3121 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 3122 Known.insertBits(Known2, SubBitWidth * Shifts); 3123 } 3124 } 3125 3126 // Bitcast 'large element' scalar/vector to 'small element' vector. 3127 if ((SubBitWidth % BitWidth) == 0) { 3128 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 3129 3130 // Collect known bits for the (smaller) output by collecting the known 3131 // bits from the overlapping larger input elements and extracting the 3132 // sub sections we actually care about. 3133 unsigned SubScale = SubBitWidth / BitWidth; 3134 APInt SubDemandedElts = 3135 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale); 3136 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 3137 3138 Known.Zero.setAllBits(); Known.One.setAllBits(); 3139 for (unsigned i = 0; i != NumElts; ++i) 3140 if (DemandedElts[i]) { 3141 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 3142 unsigned Offset = (Shifts % SubScale) * BitWidth; 3143 Known = KnownBits::commonBits(Known, 3144 Known2.extractBits(BitWidth, Offset)); 3145 // If we don't know any bits, early out. 3146 if (Known.isUnknown()) 3147 break; 3148 } 3149 } 3150 break; 3151 } 3152 case ISD::AND: 3153 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3154 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3155 3156 Known &= Known2; 3157 break; 3158 case ISD::OR: 3159 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3160 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3161 3162 Known |= Known2; 3163 break; 3164 case ISD::XOR: 3165 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3166 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3167 3168 Known ^= Known2; 3169 break; 3170 case ISD::MUL: { 3171 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3172 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3173 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3174 // TODO: SelfMultiply can be poison, but not undef. 3175 if (SelfMultiply) 3176 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison( 3177 Op.getOperand(0), DemandedElts, false, Depth + 1); 3178 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3179 3180 // If the multiplication is known not to overflow, the product of a number 3181 // with itself is non-negative. Only do this if we didn't already computed 3182 // the opposite value for the sign bit. 3183 if (Op->getFlags().hasNoSignedWrap() && 3184 Op.getOperand(0) == Op.getOperand(1) && 3185 !Known.isNegative()) 3186 Known.makeNonNegative(); 3187 break; 3188 } 3189 case ISD::MULHU: { 3190 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3191 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3192 Known = KnownBits::mulhu(Known, Known2); 3193 break; 3194 } 3195 case ISD::MULHS: { 3196 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3197 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3198 Known = KnownBits::mulhs(Known, Known2); 3199 break; 3200 } 3201 case ISD::UMUL_LOHI: { 3202 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3203 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3204 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3205 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3206 if (Op.getResNo() == 0) 3207 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3208 else 3209 Known = KnownBits::mulhu(Known, Known2); 3210 break; 3211 } 3212 case ISD::SMUL_LOHI: { 3213 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3214 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3215 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3216 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3217 if (Op.getResNo() == 0) 3218 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3219 else 3220 Known = KnownBits::mulhs(Known, Known2); 3221 break; 3222 } 3223 case ISD::UDIV: { 3224 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3225 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3226 Known = KnownBits::udiv(Known, Known2); 3227 break; 3228 } 3229 case ISD::AVGCEILU: { 3230 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3231 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3232 Known = Known.zext(BitWidth + 1); 3233 Known2 = Known2.zext(BitWidth + 1); 3234 KnownBits One = KnownBits::makeConstant(APInt(1, 1)); 3235 Known = KnownBits::computeForAddCarry(Known, Known2, One); 3236 Known = Known.extractBits(BitWidth, 1); 3237 break; 3238 } 3239 case ISD::SELECT: 3240 case ISD::VSELECT: 3241 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3242 // If we don't know any bits, early out. 3243 if (Known.isUnknown()) 3244 break; 3245 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3246 3247 // Only known if known in both the LHS and RHS. 3248 Known = KnownBits::commonBits(Known, Known2); 3249 break; 3250 case ISD::SELECT_CC: 3251 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3252 // If we don't know any bits, early out. 3253 if (Known.isUnknown()) 3254 break; 3255 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3256 3257 // Only known if known in both the LHS and RHS. 3258 Known = KnownBits::commonBits(Known, Known2); 3259 break; 3260 case ISD::SMULO: 3261 case ISD::UMULO: 3262 if (Op.getResNo() != 1) 3263 break; 3264 // The boolean result conforms to getBooleanContents. 3265 // If we know the result of a setcc has the top bits zero, use this info. 3266 // We know that we have an integer-based boolean since these operations 3267 // are only available for integer. 3268 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3269 TargetLowering::ZeroOrOneBooleanContent && 3270 BitWidth > 1) 3271 Known.Zero.setBitsFrom(1); 3272 break; 3273 case ISD::SETCC: 3274 case ISD::STRICT_FSETCC: 3275 case ISD::STRICT_FSETCCS: { 3276 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3277 // If we know the result of a setcc has the top bits zero, use this info. 3278 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3279 TargetLowering::ZeroOrOneBooleanContent && 3280 BitWidth > 1) 3281 Known.Zero.setBitsFrom(1); 3282 break; 3283 } 3284 case ISD::SHL: 3285 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3286 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3287 Known = KnownBits::shl(Known, Known2); 3288 3289 // Minimum shift low bits are known zero. 3290 if (const APInt *ShMinAmt = 3291 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3292 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3293 break; 3294 case ISD::SRL: 3295 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3296 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3297 Known = KnownBits::lshr(Known, Known2); 3298 3299 // Minimum shift high bits are known zero. 3300 if (const APInt *ShMinAmt = 3301 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3302 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3303 break; 3304 case ISD::SRA: 3305 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3306 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3307 Known = KnownBits::ashr(Known, Known2); 3308 // TODO: Add minimum shift high known sign bits. 3309 break; 3310 case ISD::FSHL: 3311 case ISD::FSHR: 3312 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3313 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3314 3315 // For fshl, 0-shift returns the 1st arg. 3316 // For fshr, 0-shift returns the 2nd arg. 3317 if (Amt == 0) { 3318 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3319 DemandedElts, Depth + 1); 3320 break; 3321 } 3322 3323 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3324 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3325 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3326 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3327 if (Opcode == ISD::FSHL) { 3328 Known.One <<= Amt; 3329 Known.Zero <<= Amt; 3330 Known2.One.lshrInPlace(BitWidth - Amt); 3331 Known2.Zero.lshrInPlace(BitWidth - Amt); 3332 } else { 3333 Known.One <<= BitWidth - Amt; 3334 Known.Zero <<= BitWidth - Amt; 3335 Known2.One.lshrInPlace(Amt); 3336 Known2.Zero.lshrInPlace(Amt); 3337 } 3338 Known.One |= Known2.One; 3339 Known.Zero |= Known2.Zero; 3340 } 3341 break; 3342 case ISD::SIGN_EXTEND_INREG: { 3343 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3344 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3345 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3346 break; 3347 } 3348 case ISD::CTTZ: 3349 case ISD::CTTZ_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 PossibleTZ = Known2.countMaxTrailingZeros(); 3353 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3354 Known.Zero.setBitsFrom(LowBits); 3355 break; 3356 } 3357 case ISD::CTLZ: 3358 case ISD::CTLZ_ZERO_UNDEF: { 3359 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3360 // If we have a known 1, its position is our upper bound. 3361 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3362 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3363 Known.Zero.setBitsFrom(LowBits); 3364 break; 3365 } 3366 case ISD::CTPOP: { 3367 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3368 // If we know some of the bits are zero, they can't be one. 3369 unsigned PossibleOnes = Known2.countMaxPopulation(); 3370 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3371 break; 3372 } 3373 case ISD::PARITY: { 3374 // Parity returns 0 everywhere but the LSB. 3375 Known.Zero.setBitsFrom(1); 3376 break; 3377 } 3378 case ISD::LOAD: { 3379 LoadSDNode *LD = cast<LoadSDNode>(Op); 3380 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3381 if (ISD::isNON_EXTLoad(LD) && Cst) { 3382 // Determine any common known bits from the loaded constant pool value. 3383 Type *CstTy = Cst->getType(); 3384 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3385 // If its a vector splat, then we can (quickly) reuse the scalar path. 3386 // NOTE: We assume all elements match and none are UNDEF. 3387 if (CstTy->isVectorTy()) { 3388 if (const Constant *Splat = Cst->getSplatValue()) { 3389 Cst = Splat; 3390 CstTy = Cst->getType(); 3391 } 3392 } 3393 // TODO - do we need to handle different bitwidths? 3394 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3395 // Iterate across all vector elements finding common known bits. 3396 Known.One.setAllBits(); 3397 Known.Zero.setAllBits(); 3398 for (unsigned i = 0; i != NumElts; ++i) { 3399 if (!DemandedElts[i]) 3400 continue; 3401 if (Constant *Elt = Cst->getAggregateElement(i)) { 3402 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3403 const APInt &Value = CInt->getValue(); 3404 Known.One &= Value; 3405 Known.Zero &= ~Value; 3406 continue; 3407 } 3408 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3409 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3410 Known.One &= Value; 3411 Known.Zero &= ~Value; 3412 continue; 3413 } 3414 } 3415 Known.One.clearAllBits(); 3416 Known.Zero.clearAllBits(); 3417 break; 3418 } 3419 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3420 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3421 Known = KnownBits::makeConstant(CInt->getValue()); 3422 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3423 Known = 3424 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3425 } 3426 } 3427 } 3428 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3429 // If this is a ZEXTLoad and we are looking at the loaded value. 3430 EVT VT = LD->getMemoryVT(); 3431 unsigned MemBits = VT.getScalarSizeInBits(); 3432 Known.Zero.setBitsFrom(MemBits); 3433 } else if (const MDNode *Ranges = LD->getRanges()) { 3434 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3435 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3436 } 3437 break; 3438 } 3439 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3440 EVT InVT = Op.getOperand(0).getValueType(); 3441 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3442 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3443 Known = Known.zext(BitWidth); 3444 break; 3445 } 3446 case ISD::ZERO_EXTEND: { 3447 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3448 Known = Known.zext(BitWidth); 3449 break; 3450 } 3451 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3452 EVT InVT = Op.getOperand(0).getValueType(); 3453 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3454 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3455 // If the sign bit is known to be zero or one, then sext will extend 3456 // it to the top bits, else it will just zext. 3457 Known = Known.sext(BitWidth); 3458 break; 3459 } 3460 case ISD::SIGN_EXTEND: { 3461 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3462 // If the sign bit is known to be zero or one, then sext will extend 3463 // it to the top bits, else it will just zext. 3464 Known = Known.sext(BitWidth); 3465 break; 3466 } 3467 case ISD::ANY_EXTEND_VECTOR_INREG: { 3468 EVT InVT = Op.getOperand(0).getValueType(); 3469 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3470 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3471 Known = Known.anyext(BitWidth); 3472 break; 3473 } 3474 case ISD::ANY_EXTEND: { 3475 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3476 Known = Known.anyext(BitWidth); 3477 break; 3478 } 3479 case ISD::TRUNCATE: { 3480 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3481 Known = Known.trunc(BitWidth); 3482 break; 3483 } 3484 case ISD::AssertZext: { 3485 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3486 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3487 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3488 Known.Zero |= (~InMask); 3489 Known.One &= (~Known.Zero); 3490 break; 3491 } 3492 case ISD::AssertAlign: { 3493 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3494 assert(LogOfAlign != 0); 3495 3496 // TODO: Should use maximum with source 3497 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3498 // well as clearing one bits. 3499 Known.Zero.setLowBits(LogOfAlign); 3500 Known.One.clearLowBits(LogOfAlign); 3501 break; 3502 } 3503 case ISD::FGETSIGN: 3504 // All bits are zero except the low bit. 3505 Known.Zero.setBitsFrom(1); 3506 break; 3507 case ISD::USUBO: 3508 case ISD::SSUBO: 3509 if (Op.getResNo() == 1) { 3510 // If we know the result of a setcc has the top bits zero, use this info. 3511 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3512 TargetLowering::ZeroOrOneBooleanContent && 3513 BitWidth > 1) 3514 Known.Zero.setBitsFrom(1); 3515 break; 3516 } 3517 LLVM_FALLTHROUGH; 3518 case ISD::SUB: 3519 case ISD::SUBC: { 3520 assert(Op.getResNo() == 0 && 3521 "We only compute knownbits for the difference here."); 3522 3523 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3524 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3525 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3526 Known, Known2); 3527 break; 3528 } 3529 case ISD::UADDO: 3530 case ISD::SADDO: 3531 case ISD::ADDCARRY: 3532 if (Op.getResNo() == 1) { 3533 // If we know the result of a setcc has the top bits zero, use this info. 3534 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3535 TargetLowering::ZeroOrOneBooleanContent && 3536 BitWidth > 1) 3537 Known.Zero.setBitsFrom(1); 3538 break; 3539 } 3540 LLVM_FALLTHROUGH; 3541 case ISD::ADD: 3542 case ISD::ADDC: 3543 case ISD::ADDE: { 3544 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3545 3546 // With ADDE and ADDCARRY, a carry bit may be added in. 3547 KnownBits Carry(1); 3548 if (Opcode == ISD::ADDE) 3549 // Can't track carry from glue, set carry to unknown. 3550 Carry.resetAll(); 3551 else if (Opcode == ISD::ADDCARRY) 3552 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3553 // the trouble (how often will we find a known carry bit). And I haven't 3554 // tested this very much yet, but something like this might work: 3555 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3556 // Carry = Carry.zextOrTrunc(1, false); 3557 Carry.resetAll(); 3558 else 3559 Carry.setAllZero(); 3560 3561 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3562 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3563 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3564 break; 3565 } 3566 case ISD::SREM: { 3567 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3568 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3569 Known = KnownBits::srem(Known, Known2); 3570 break; 3571 } 3572 case ISD::UREM: { 3573 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3574 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3575 Known = KnownBits::urem(Known, Known2); 3576 break; 3577 } 3578 case ISD::EXTRACT_ELEMENT: { 3579 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3580 const unsigned Index = Op.getConstantOperandVal(1); 3581 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3582 3583 // Remove low part of known bits mask 3584 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3585 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3586 3587 // Remove high part of known bit mask 3588 Known = Known.trunc(EltBitWidth); 3589 break; 3590 } 3591 case ISD::EXTRACT_VECTOR_ELT: { 3592 SDValue InVec = Op.getOperand(0); 3593 SDValue EltNo = Op.getOperand(1); 3594 EVT VecVT = InVec.getValueType(); 3595 // computeKnownBits not yet implemented for scalable vectors. 3596 if (VecVT.isScalableVector()) 3597 break; 3598 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3599 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3600 3601 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3602 // anything about the extended bits. 3603 if (BitWidth > EltBitWidth) 3604 Known = Known.trunc(EltBitWidth); 3605 3606 // If we know the element index, just demand that vector element, else for 3607 // an unknown element index, ignore DemandedElts and demand them all. 3608 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 3609 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3610 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3611 DemandedSrcElts = 3612 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3613 3614 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3615 if (BitWidth > EltBitWidth) 3616 Known = Known.anyext(BitWidth); 3617 break; 3618 } 3619 case ISD::INSERT_VECTOR_ELT: { 3620 // If we know the element index, split the demand between the 3621 // source vector and the inserted element, otherwise assume we need 3622 // the original demanded vector elements and the value. 3623 SDValue InVec = Op.getOperand(0); 3624 SDValue InVal = Op.getOperand(1); 3625 SDValue EltNo = Op.getOperand(2); 3626 bool DemandedVal = true; 3627 APInt DemandedVecElts = DemandedElts; 3628 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3629 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3630 unsigned EltIdx = CEltNo->getZExtValue(); 3631 DemandedVal = !!DemandedElts[EltIdx]; 3632 DemandedVecElts.clearBit(EltIdx); 3633 } 3634 Known.One.setAllBits(); 3635 Known.Zero.setAllBits(); 3636 if (DemandedVal) { 3637 Known2 = computeKnownBits(InVal, Depth + 1); 3638 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3639 } 3640 if (!!DemandedVecElts) { 3641 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3642 Known = KnownBits::commonBits(Known, Known2); 3643 } 3644 break; 3645 } 3646 case ISD::BITREVERSE: { 3647 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3648 Known = Known2.reverseBits(); 3649 break; 3650 } 3651 case ISD::BSWAP: { 3652 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3653 Known = Known2.byteSwap(); 3654 break; 3655 } 3656 case ISD::ABS: { 3657 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3658 Known = Known2.abs(); 3659 break; 3660 } 3661 case ISD::USUBSAT: { 3662 // The result of usubsat will never be larger than the LHS. 3663 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3664 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3665 break; 3666 } 3667 case ISD::UMIN: { 3668 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3669 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3670 Known = KnownBits::umin(Known, Known2); 3671 break; 3672 } 3673 case ISD::UMAX: { 3674 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3675 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3676 Known = KnownBits::umax(Known, Known2); 3677 break; 3678 } 3679 case ISD::SMIN: 3680 case ISD::SMAX: { 3681 // If we have a clamp pattern, we know that the number of sign bits will be 3682 // the minimum of the clamp min/max range. 3683 bool IsMax = (Opcode == ISD::SMAX); 3684 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3685 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3686 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3687 CstHigh = 3688 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3689 if (CstLow && CstHigh) { 3690 if (!IsMax) 3691 std::swap(CstLow, CstHigh); 3692 3693 const APInt &ValueLow = CstLow->getAPIntValue(); 3694 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3695 if (ValueLow.sle(ValueHigh)) { 3696 unsigned LowSignBits = ValueLow.getNumSignBits(); 3697 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3698 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3699 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3700 Known.One.setHighBits(MinSignBits); 3701 break; 3702 } 3703 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3704 Known.Zero.setHighBits(MinSignBits); 3705 break; 3706 } 3707 } 3708 } 3709 3710 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3711 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3712 if (IsMax) 3713 Known = KnownBits::smax(Known, Known2); 3714 else 3715 Known = KnownBits::smin(Known, Known2); 3716 3717 // For SMAX, if CstLow is non-negative we know the result will be 3718 // non-negative and thus all sign bits are 0. 3719 // TODO: There's an equivalent of this for smin with negative constant for 3720 // known ones. 3721 if (IsMax && CstLow) { 3722 const APInt &ValueLow = CstLow->getAPIntValue(); 3723 if (ValueLow.isNonNegative()) { 3724 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 3725 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits())); 3726 } 3727 } 3728 3729 break; 3730 } 3731 case ISD::FP_TO_UINT_SAT: { 3732 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT. 3733 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3734 Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits()); 3735 break; 3736 } 3737 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3738 if (Op.getResNo() == 1) { 3739 // The boolean result conforms to getBooleanContents. 3740 // If we know the result of a setcc has the top bits zero, use this info. 3741 // We know that we have an integer-based boolean since these operations 3742 // are only available for integer. 3743 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3744 TargetLowering::ZeroOrOneBooleanContent && 3745 BitWidth > 1) 3746 Known.Zero.setBitsFrom(1); 3747 break; 3748 } 3749 LLVM_FALLTHROUGH; 3750 case ISD::ATOMIC_CMP_SWAP: 3751 case ISD::ATOMIC_SWAP: 3752 case ISD::ATOMIC_LOAD_ADD: 3753 case ISD::ATOMIC_LOAD_SUB: 3754 case ISD::ATOMIC_LOAD_AND: 3755 case ISD::ATOMIC_LOAD_CLR: 3756 case ISD::ATOMIC_LOAD_OR: 3757 case ISD::ATOMIC_LOAD_XOR: 3758 case ISD::ATOMIC_LOAD_NAND: 3759 case ISD::ATOMIC_LOAD_MIN: 3760 case ISD::ATOMIC_LOAD_MAX: 3761 case ISD::ATOMIC_LOAD_UMIN: 3762 case ISD::ATOMIC_LOAD_UMAX: 3763 case ISD::ATOMIC_LOAD: { 3764 unsigned MemBits = 3765 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 3766 // If we are looking at the loaded value. 3767 if (Op.getResNo() == 0) { 3768 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 3769 Known.Zero.setBitsFrom(MemBits); 3770 } 3771 break; 3772 } 3773 case ISD::FrameIndex: 3774 case ISD::TargetFrameIndex: 3775 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3776 Known, getMachineFunction()); 3777 break; 3778 3779 default: 3780 if (Opcode < ISD::BUILTIN_OP_END) 3781 break; 3782 LLVM_FALLTHROUGH; 3783 case ISD::INTRINSIC_WO_CHAIN: 3784 case ISD::INTRINSIC_W_CHAIN: 3785 case ISD::INTRINSIC_VOID: 3786 // Allow the target to implement this method for its nodes. 3787 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3788 break; 3789 } 3790 3791 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3792 return Known; 3793 } 3794 3795 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3796 SDValue N1) const { 3797 // X + 0 never overflow 3798 if (isNullConstant(N1)) 3799 return OFK_Never; 3800 3801 KnownBits N1Known = computeKnownBits(N1); 3802 if (N1Known.Zero.getBoolValue()) { 3803 KnownBits N0Known = computeKnownBits(N0); 3804 3805 bool overflow; 3806 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3807 if (!overflow) 3808 return OFK_Never; 3809 } 3810 3811 // mulhi + 1 never overflow 3812 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3813 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3814 return OFK_Never; 3815 3816 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3817 KnownBits N0Known = computeKnownBits(N0); 3818 3819 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3820 return OFK_Never; 3821 } 3822 3823 return OFK_Sometime; 3824 } 3825 3826 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3827 EVT OpVT = Val.getValueType(); 3828 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3829 3830 // Is the constant a known power of 2? 3831 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3832 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3833 3834 // A left-shift of a constant one will have exactly one bit set because 3835 // shifting the bit off the end is undefined. 3836 if (Val.getOpcode() == ISD::SHL) { 3837 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3838 if (C && C->getAPIntValue() == 1) 3839 return true; 3840 } 3841 3842 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3843 // one bit set. 3844 if (Val.getOpcode() == ISD::SRL) { 3845 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3846 if (C && C->getAPIntValue().isSignMask()) 3847 return true; 3848 } 3849 3850 // Are all operands of a build vector constant powers of two? 3851 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3852 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3853 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3854 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3855 return false; 3856 })) 3857 return true; 3858 3859 // Is the operand of a splat vector a constant power of two? 3860 if (Val.getOpcode() == ISD::SPLAT_VECTOR) 3861 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0))) 3862 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2()) 3863 return true; 3864 3865 // More could be done here, though the above checks are enough 3866 // to handle some common cases. 3867 3868 // Fall back to computeKnownBits to catch other known cases. 3869 KnownBits Known = computeKnownBits(Val); 3870 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3871 } 3872 3873 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3874 EVT VT = Op.getValueType(); 3875 3876 // TODO: Assume we don't know anything for now. 3877 if (VT.isScalableVector()) 3878 return 1; 3879 3880 APInt DemandedElts = VT.isVector() 3881 ? APInt::getAllOnes(VT.getVectorNumElements()) 3882 : APInt(1, 1); 3883 return ComputeNumSignBits(Op, DemandedElts, Depth); 3884 } 3885 3886 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3887 unsigned Depth) const { 3888 EVT VT = Op.getValueType(); 3889 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3890 unsigned VTBits = VT.getScalarSizeInBits(); 3891 unsigned NumElts = DemandedElts.getBitWidth(); 3892 unsigned Tmp, Tmp2; 3893 unsigned FirstAnswer = 1; 3894 3895 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3896 const APInt &Val = C->getAPIntValue(); 3897 return Val.getNumSignBits(); 3898 } 3899 3900 if (Depth >= MaxRecursionDepth) 3901 return 1; // Limit search depth. 3902 3903 if (!DemandedElts || VT.isScalableVector()) 3904 return 1; // No demanded elts, better to assume we don't know anything. 3905 3906 unsigned Opcode = Op.getOpcode(); 3907 switch (Opcode) { 3908 default: break; 3909 case ISD::AssertSext: 3910 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3911 return VTBits-Tmp+1; 3912 case ISD::AssertZext: 3913 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3914 return VTBits-Tmp; 3915 3916 case ISD::BUILD_VECTOR: 3917 Tmp = VTBits; 3918 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3919 if (!DemandedElts[i]) 3920 continue; 3921 3922 SDValue SrcOp = Op.getOperand(i); 3923 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3924 3925 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3926 if (SrcOp.getValueSizeInBits() != VTBits) { 3927 assert(SrcOp.getValueSizeInBits() > VTBits && 3928 "Expected BUILD_VECTOR implicit truncation"); 3929 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3930 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3931 } 3932 Tmp = std::min(Tmp, Tmp2); 3933 } 3934 return Tmp; 3935 3936 case ISD::VECTOR_SHUFFLE: { 3937 // Collect the minimum number of sign bits that are shared by every vector 3938 // element referenced by the shuffle. 3939 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3940 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3941 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3942 for (unsigned i = 0; i != NumElts; ++i) { 3943 int M = SVN->getMaskElt(i); 3944 if (!DemandedElts[i]) 3945 continue; 3946 // For UNDEF elements, we don't know anything about the common state of 3947 // the shuffle result. 3948 if (M < 0) 3949 return 1; 3950 if ((unsigned)M < NumElts) 3951 DemandedLHS.setBit((unsigned)M % NumElts); 3952 else 3953 DemandedRHS.setBit((unsigned)M % NumElts); 3954 } 3955 Tmp = std::numeric_limits<unsigned>::max(); 3956 if (!!DemandedLHS) 3957 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 3958 if (!!DemandedRHS) { 3959 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 3960 Tmp = std::min(Tmp, Tmp2); 3961 } 3962 // If we don't know anything, early out and try computeKnownBits fall-back. 3963 if (Tmp == 1) 3964 break; 3965 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3966 return Tmp; 3967 } 3968 3969 case ISD::BITCAST: { 3970 SDValue N0 = Op.getOperand(0); 3971 EVT SrcVT = N0.getValueType(); 3972 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 3973 3974 // Ignore bitcasts from unsupported types.. 3975 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 3976 break; 3977 3978 // Fast handling of 'identity' bitcasts. 3979 if (VTBits == SrcBits) 3980 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 3981 3982 bool IsLE = getDataLayout().isLittleEndian(); 3983 3984 // Bitcast 'large element' scalar/vector to 'small element' vector. 3985 if ((SrcBits % VTBits) == 0) { 3986 assert(VT.isVector() && "Expected bitcast to vector"); 3987 3988 unsigned Scale = SrcBits / VTBits; 3989 APInt SrcDemandedElts = 3990 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale); 3991 3992 // Fast case - sign splat can be simply split across the small elements. 3993 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 3994 if (Tmp == SrcBits) 3995 return VTBits; 3996 3997 // Slow case - determine how far the sign extends into each sub-element. 3998 Tmp2 = VTBits; 3999 for (unsigned i = 0; i != NumElts; ++i) 4000 if (DemandedElts[i]) { 4001 unsigned SubOffset = i % Scale; 4002 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 4003 SubOffset = SubOffset * VTBits; 4004 if (Tmp <= SubOffset) 4005 return 1; 4006 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 4007 } 4008 return Tmp2; 4009 } 4010 break; 4011 } 4012 4013 case ISD::FP_TO_SINT_SAT: 4014 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT. 4015 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 4016 return VTBits - Tmp + 1; 4017 case ISD::SIGN_EXTEND: 4018 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 4019 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 4020 case ISD::SIGN_EXTEND_INREG: 4021 // Max of the input and what this extends. 4022 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 4023 Tmp = VTBits-Tmp+1; 4024 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4025 return std::max(Tmp, Tmp2); 4026 case ISD::SIGN_EXTEND_VECTOR_INREG: { 4027 SDValue Src = Op.getOperand(0); 4028 EVT SrcVT = Src.getValueType(); 4029 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements()); 4030 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 4031 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 4032 } 4033 case ISD::SRA: 4034 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4035 // SRA X, C -> adds C sign bits. 4036 if (const APInt *ShAmt = 4037 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 4038 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 4039 return Tmp; 4040 case ISD::SHL: 4041 if (const APInt *ShAmt = 4042 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 4043 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 4044 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4045 if (ShAmt->ult(Tmp)) 4046 return Tmp - ShAmt->getZExtValue(); 4047 } 4048 break; 4049 case ISD::AND: 4050 case ISD::OR: 4051 case ISD::XOR: // NOT is handled here. 4052 // Logical binary ops preserve the number of sign bits at the worst. 4053 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4054 if (Tmp != 1) { 4055 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4056 FirstAnswer = std::min(Tmp, Tmp2); 4057 // We computed what we know about the sign bits as our first 4058 // answer. Now proceed to the generic code that uses 4059 // computeKnownBits, and pick whichever answer is better. 4060 } 4061 break; 4062 4063 case ISD::SELECT: 4064 case ISD::VSELECT: 4065 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4066 if (Tmp == 1) return 1; // Early out. 4067 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4068 return std::min(Tmp, Tmp2); 4069 case ISD::SELECT_CC: 4070 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4071 if (Tmp == 1) return 1; // Early out. 4072 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 4073 return std::min(Tmp, Tmp2); 4074 4075 case ISD::SMIN: 4076 case ISD::SMAX: { 4077 // If we have a clamp pattern, we know that the number of sign bits will be 4078 // the minimum of the clamp min/max range. 4079 bool IsMax = (Opcode == ISD::SMAX); 4080 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 4081 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 4082 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 4083 CstHigh = 4084 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 4085 if (CstLow && CstHigh) { 4086 if (!IsMax) 4087 std::swap(CstLow, CstHigh); 4088 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 4089 Tmp = CstLow->getAPIntValue().getNumSignBits(); 4090 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 4091 return std::min(Tmp, Tmp2); 4092 } 4093 } 4094 4095 // Fallback - just get the minimum number of sign bits of the operands. 4096 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4097 if (Tmp == 1) 4098 return 1; // Early out. 4099 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4100 return std::min(Tmp, Tmp2); 4101 } 4102 case ISD::UMIN: 4103 case ISD::UMAX: 4104 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4105 if (Tmp == 1) 4106 return 1; // Early out. 4107 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4108 return std::min(Tmp, Tmp2); 4109 case ISD::SADDO: 4110 case ISD::UADDO: 4111 case ISD::SSUBO: 4112 case ISD::USUBO: 4113 case ISD::SMULO: 4114 case ISD::UMULO: 4115 if (Op.getResNo() != 1) 4116 break; 4117 // The boolean result conforms to getBooleanContents. Fall through. 4118 // If setcc returns 0/-1, all bits are sign bits. 4119 // We know that we have an integer-based boolean since these operations 4120 // are only available for integer. 4121 if (TLI->getBooleanContents(VT.isVector(), false) == 4122 TargetLowering::ZeroOrNegativeOneBooleanContent) 4123 return VTBits; 4124 break; 4125 case ISD::SETCC: 4126 case ISD::STRICT_FSETCC: 4127 case ISD::STRICT_FSETCCS: { 4128 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 4129 // If setcc returns 0/-1, all bits are sign bits. 4130 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 4131 TargetLowering::ZeroOrNegativeOneBooleanContent) 4132 return VTBits; 4133 break; 4134 } 4135 case ISD::ROTL: 4136 case ISD::ROTR: 4137 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4138 4139 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 4140 if (Tmp == VTBits) 4141 return VTBits; 4142 4143 if (ConstantSDNode *C = 4144 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 4145 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 4146 4147 // Handle rotate right by N like a rotate left by 32-N. 4148 if (Opcode == ISD::ROTR) 4149 RotAmt = (VTBits - RotAmt) % VTBits; 4150 4151 // If we aren't rotating out all of the known-in sign bits, return the 4152 // number that are left. This handles rotl(sext(x), 1) for example. 4153 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 4154 } 4155 break; 4156 case ISD::ADD: 4157 case ISD::ADDC: 4158 // Add can have at most one carry bit. Thus we know that the output 4159 // is, at worst, one more bit than the inputs. 4160 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4161 if (Tmp == 1) return 1; // Early out. 4162 4163 // Special case decrementing a value (ADD X, -1): 4164 if (ConstantSDNode *CRHS = 4165 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 4166 if (CRHS->isAllOnes()) { 4167 KnownBits Known = 4168 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 4169 4170 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4171 // sign bits set. 4172 if ((Known.Zero | 1).isAllOnes()) 4173 return VTBits; 4174 4175 // If we are subtracting one from a positive number, there is no carry 4176 // out of the result. 4177 if (Known.isNonNegative()) 4178 return Tmp; 4179 } 4180 4181 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4182 if (Tmp2 == 1) return 1; // Early out. 4183 return std::min(Tmp, Tmp2) - 1; 4184 case ISD::SUB: 4185 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4186 if (Tmp2 == 1) return 1; // Early out. 4187 4188 // Handle NEG. 4189 if (ConstantSDNode *CLHS = 4190 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 4191 if (CLHS->isZero()) { 4192 KnownBits Known = 4193 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 4194 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4195 // sign bits set. 4196 if ((Known.Zero | 1).isAllOnes()) 4197 return VTBits; 4198 4199 // If the input is known to be positive (the sign bit is known clear), 4200 // the output of the NEG has the same number of sign bits as the input. 4201 if (Known.isNonNegative()) 4202 return Tmp2; 4203 4204 // Otherwise, we treat this like a SUB. 4205 } 4206 4207 // Sub can have at most one carry bit. Thus we know that the output 4208 // is, at worst, one more bit than the inputs. 4209 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4210 if (Tmp == 1) return 1; // Early out. 4211 return std::min(Tmp, Tmp2) - 1; 4212 case ISD::MUL: { 4213 // The output of the Mul can be at most twice the valid bits in the inputs. 4214 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4215 if (SignBitsOp0 == 1) 4216 break; 4217 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 4218 if (SignBitsOp1 == 1) 4219 break; 4220 unsigned OutValidBits = 4221 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 4222 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 4223 } 4224 case ISD::SREM: 4225 // The sign bit is the LHS's sign bit, except when the result of the 4226 // remainder is zero. The magnitude of the result should be less than or 4227 // equal to the magnitude of the LHS. Therefore, the result should have 4228 // at least as many sign bits as the left hand side. 4229 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4230 case ISD::TRUNCATE: { 4231 // Check if the sign bits of source go down as far as the truncated value. 4232 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 4233 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4234 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4235 return NumSrcSignBits - (NumSrcBits - VTBits); 4236 break; 4237 } 4238 case ISD::EXTRACT_ELEMENT: { 4239 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 4240 const int BitWidth = Op.getValueSizeInBits(); 4241 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 4242 4243 // Get reverse index (starting from 1), Op1 value indexes elements from 4244 // little end. Sign starts at big end. 4245 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 4246 4247 // If the sign portion ends in our element the subtraction gives correct 4248 // result. Otherwise it gives either negative or > bitwidth result 4249 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 4250 } 4251 case ISD::INSERT_VECTOR_ELT: { 4252 // If we know the element index, split the demand between the 4253 // source vector and the inserted element, otherwise assume we need 4254 // the original demanded vector elements and the value. 4255 SDValue InVec = Op.getOperand(0); 4256 SDValue InVal = Op.getOperand(1); 4257 SDValue EltNo = Op.getOperand(2); 4258 bool DemandedVal = true; 4259 APInt DemandedVecElts = DemandedElts; 4260 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 4261 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 4262 unsigned EltIdx = CEltNo->getZExtValue(); 4263 DemandedVal = !!DemandedElts[EltIdx]; 4264 DemandedVecElts.clearBit(EltIdx); 4265 } 4266 Tmp = std::numeric_limits<unsigned>::max(); 4267 if (DemandedVal) { 4268 // TODO - handle implicit truncation of inserted elements. 4269 if (InVal.getScalarValueSizeInBits() != VTBits) 4270 break; 4271 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4272 Tmp = std::min(Tmp, Tmp2); 4273 } 4274 if (!!DemandedVecElts) { 4275 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 4276 Tmp = std::min(Tmp, Tmp2); 4277 } 4278 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4279 return Tmp; 4280 } 4281 case ISD::EXTRACT_VECTOR_ELT: { 4282 SDValue InVec = Op.getOperand(0); 4283 SDValue EltNo = Op.getOperand(1); 4284 EVT VecVT = InVec.getValueType(); 4285 // ComputeNumSignBits not yet implemented for scalable vectors. 4286 if (VecVT.isScalableVector()) 4287 break; 4288 const unsigned BitWidth = Op.getValueSizeInBits(); 4289 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4290 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4291 4292 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4293 // anything about sign bits. But if the sizes match we can derive knowledge 4294 // about sign bits from the vector operand. 4295 if (BitWidth != EltBitWidth) 4296 break; 4297 4298 // If we know the element index, just demand that vector element, else for 4299 // an unknown element index, ignore DemandedElts and demand them all. 4300 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 4301 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4302 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4303 DemandedSrcElts = 4304 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4305 4306 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4307 } 4308 case ISD::EXTRACT_SUBVECTOR: { 4309 // Offset the demanded elts by the subvector index. 4310 SDValue Src = Op.getOperand(0); 4311 // Bail until we can represent demanded elements for scalable vectors. 4312 if (Src.getValueType().isScalableVector()) 4313 break; 4314 uint64_t Idx = Op.getConstantOperandVal(1); 4315 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4316 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 4317 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4318 } 4319 case ISD::CONCAT_VECTORS: { 4320 // Determine the minimum number of sign bits across all demanded 4321 // elts of the input vectors. Early out if the result is already 1. 4322 Tmp = std::numeric_limits<unsigned>::max(); 4323 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4324 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4325 unsigned NumSubVectors = Op.getNumOperands(); 4326 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4327 APInt DemandedSub = 4328 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 4329 if (!DemandedSub) 4330 continue; 4331 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4332 Tmp = std::min(Tmp, Tmp2); 4333 } 4334 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4335 return Tmp; 4336 } 4337 case ISD::INSERT_SUBVECTOR: { 4338 // Demand any elements from the subvector and the remainder from the src its 4339 // inserted into. 4340 SDValue Src = Op.getOperand(0); 4341 SDValue Sub = Op.getOperand(1); 4342 uint64_t Idx = Op.getConstantOperandVal(2); 4343 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4344 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4345 APInt DemandedSrcElts = DemandedElts; 4346 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 4347 4348 Tmp = std::numeric_limits<unsigned>::max(); 4349 if (!!DemandedSubElts) { 4350 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4351 if (Tmp == 1) 4352 return 1; // early-out 4353 } 4354 if (!!DemandedSrcElts) { 4355 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4356 Tmp = std::min(Tmp, Tmp2); 4357 } 4358 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4359 return Tmp; 4360 } 4361 case ISD::ATOMIC_CMP_SWAP: 4362 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4363 case ISD::ATOMIC_SWAP: 4364 case ISD::ATOMIC_LOAD_ADD: 4365 case ISD::ATOMIC_LOAD_SUB: 4366 case ISD::ATOMIC_LOAD_AND: 4367 case ISD::ATOMIC_LOAD_CLR: 4368 case ISD::ATOMIC_LOAD_OR: 4369 case ISD::ATOMIC_LOAD_XOR: 4370 case ISD::ATOMIC_LOAD_NAND: 4371 case ISD::ATOMIC_LOAD_MIN: 4372 case ISD::ATOMIC_LOAD_MAX: 4373 case ISD::ATOMIC_LOAD_UMIN: 4374 case ISD::ATOMIC_LOAD_UMAX: 4375 case ISD::ATOMIC_LOAD: { 4376 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4377 // If we are looking at the loaded value. 4378 if (Op.getResNo() == 0) { 4379 if (Tmp == VTBits) 4380 return 1; // early-out 4381 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND) 4382 return VTBits - Tmp + 1; 4383 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4384 return VTBits - Tmp; 4385 } 4386 break; 4387 } 4388 } 4389 4390 // If we are looking at the loaded value of the SDNode. 4391 if (Op.getResNo() == 0) { 4392 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4393 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4394 unsigned ExtType = LD->getExtensionType(); 4395 switch (ExtType) { 4396 default: break; 4397 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4398 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4399 return VTBits - Tmp + 1; 4400 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4401 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4402 return VTBits - Tmp; 4403 case ISD::NON_EXTLOAD: 4404 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4405 // We only need to handle vectors - computeKnownBits should handle 4406 // scalar cases. 4407 Type *CstTy = Cst->getType(); 4408 if (CstTy->isVectorTy() && 4409 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() && 4410 VTBits == CstTy->getScalarSizeInBits()) { 4411 Tmp = VTBits; 4412 for (unsigned i = 0; i != NumElts; ++i) { 4413 if (!DemandedElts[i]) 4414 continue; 4415 if (Constant *Elt = Cst->getAggregateElement(i)) { 4416 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4417 const APInt &Value = CInt->getValue(); 4418 Tmp = std::min(Tmp, Value.getNumSignBits()); 4419 continue; 4420 } 4421 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4422 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4423 Tmp = std::min(Tmp, Value.getNumSignBits()); 4424 continue; 4425 } 4426 } 4427 // Unknown type. Conservatively assume no bits match sign bit. 4428 return 1; 4429 } 4430 return Tmp; 4431 } 4432 } 4433 break; 4434 } 4435 } 4436 } 4437 4438 // Allow the target to implement this method for its nodes. 4439 if (Opcode >= ISD::BUILTIN_OP_END || 4440 Opcode == ISD::INTRINSIC_WO_CHAIN || 4441 Opcode == ISD::INTRINSIC_W_CHAIN || 4442 Opcode == ISD::INTRINSIC_VOID) { 4443 unsigned NumBits = 4444 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4445 if (NumBits > 1) 4446 FirstAnswer = std::max(FirstAnswer, NumBits); 4447 } 4448 4449 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4450 // use this information. 4451 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4452 return std::max(FirstAnswer, Known.countMinSignBits()); 4453 } 4454 4455 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4456 unsigned Depth) const { 4457 unsigned SignBits = ComputeNumSignBits(Op, Depth); 4458 return Op.getScalarValueSizeInBits() - SignBits + 1; 4459 } 4460 4461 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4462 const APInt &DemandedElts, 4463 unsigned Depth) const { 4464 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth); 4465 return Op.getScalarValueSizeInBits() - SignBits + 1; 4466 } 4467 4468 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly, 4469 unsigned Depth) const { 4470 // Early out for FREEZE. 4471 if (Op.getOpcode() == ISD::FREEZE) 4472 return true; 4473 4474 // TODO: Assume we don't know anything for now. 4475 EVT VT = Op.getValueType(); 4476 if (VT.isScalableVector()) 4477 return false; 4478 4479 APInt DemandedElts = VT.isVector() 4480 ? APInt::getAllOnes(VT.getVectorNumElements()) 4481 : APInt(1, 1); 4482 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth); 4483 } 4484 4485 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, 4486 const APInt &DemandedElts, 4487 bool PoisonOnly, 4488 unsigned Depth) const { 4489 unsigned Opcode = Op.getOpcode(); 4490 4491 // Early out for FREEZE. 4492 if (Opcode == ISD::FREEZE) 4493 return true; 4494 4495 if (Depth >= MaxRecursionDepth) 4496 return false; // Limit search depth. 4497 4498 if (isIntOrFPConstant(Op)) 4499 return true; 4500 4501 switch (Opcode) { 4502 case ISD::UNDEF: 4503 return PoisonOnly; 4504 4505 case ISD::BUILD_VECTOR: 4506 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements - 4507 // this shouldn't affect the result. 4508 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) { 4509 if (!DemandedElts[i]) 4510 continue; 4511 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly, 4512 Depth + 1)) 4513 return false; 4514 } 4515 return true; 4516 4517 // TODO: Search for noundef attributes from library functions. 4518 4519 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef. 4520 4521 default: 4522 // Allow the target to implement this method for its nodes. 4523 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 4524 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 4525 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode( 4526 Op, DemandedElts, *this, PoisonOnly, Depth); 4527 break; 4528 } 4529 4530 return false; 4531 } 4532 4533 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4534 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4535 !isa<ConstantSDNode>(Op.getOperand(1))) 4536 return false; 4537 4538 if (Op.getOpcode() == ISD::OR && 4539 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4540 return false; 4541 4542 return true; 4543 } 4544 4545 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4546 // If we're told that NaNs won't happen, assume they won't. 4547 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4548 return true; 4549 4550 if (Depth >= MaxRecursionDepth) 4551 return false; // Limit search depth. 4552 4553 // TODO: Handle vectors. 4554 // If the value is a constant, we can obviously see if it is a NaN or not. 4555 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4556 return !C->getValueAPF().isNaN() || 4557 (SNaN && !C->getValueAPF().isSignaling()); 4558 } 4559 4560 unsigned Opcode = Op.getOpcode(); 4561 switch (Opcode) { 4562 case ISD::FADD: 4563 case ISD::FSUB: 4564 case ISD::FMUL: 4565 case ISD::FDIV: 4566 case ISD::FREM: 4567 case ISD::FSIN: 4568 case ISD::FCOS: { 4569 if (SNaN) 4570 return true; 4571 // TODO: Need isKnownNeverInfinity 4572 return false; 4573 } 4574 case ISD::FCANONICALIZE: 4575 case ISD::FEXP: 4576 case ISD::FEXP2: 4577 case ISD::FTRUNC: 4578 case ISD::FFLOOR: 4579 case ISD::FCEIL: 4580 case ISD::FROUND: 4581 case ISD::FROUNDEVEN: 4582 case ISD::FRINT: 4583 case ISD::FNEARBYINT: { 4584 if (SNaN) 4585 return true; 4586 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4587 } 4588 case ISD::FABS: 4589 case ISD::FNEG: 4590 case ISD::FCOPYSIGN: { 4591 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4592 } 4593 case ISD::SELECT: 4594 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4595 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4596 case ISD::FP_EXTEND: 4597 case ISD::FP_ROUND: { 4598 if (SNaN) 4599 return true; 4600 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4601 } 4602 case ISD::SINT_TO_FP: 4603 case ISD::UINT_TO_FP: 4604 return true; 4605 case ISD::FMA: 4606 case ISD::FMAD: { 4607 if (SNaN) 4608 return true; 4609 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4610 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4611 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4612 } 4613 case ISD::FSQRT: // Need is known positive 4614 case ISD::FLOG: 4615 case ISD::FLOG2: 4616 case ISD::FLOG10: 4617 case ISD::FPOWI: 4618 case ISD::FPOW: { 4619 if (SNaN) 4620 return true; 4621 // TODO: Refine on operand 4622 return false; 4623 } 4624 case ISD::FMINNUM: 4625 case ISD::FMAXNUM: { 4626 // Only one needs to be known not-nan, since it will be returned if the 4627 // other ends up being one. 4628 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4629 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4630 } 4631 case ISD::FMINNUM_IEEE: 4632 case ISD::FMAXNUM_IEEE: { 4633 if (SNaN) 4634 return true; 4635 // This can return a NaN if either operand is an sNaN, or if both operands 4636 // are NaN. 4637 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4638 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4639 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4640 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4641 } 4642 case ISD::FMINIMUM: 4643 case ISD::FMAXIMUM: { 4644 // TODO: Does this quiet or return the origina NaN as-is? 4645 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4646 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4647 } 4648 case ISD::EXTRACT_VECTOR_ELT: { 4649 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4650 } 4651 default: 4652 if (Opcode >= ISD::BUILTIN_OP_END || 4653 Opcode == ISD::INTRINSIC_WO_CHAIN || 4654 Opcode == ISD::INTRINSIC_W_CHAIN || 4655 Opcode == ISD::INTRINSIC_VOID) { 4656 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4657 } 4658 4659 return false; 4660 } 4661 } 4662 4663 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4664 assert(Op.getValueType().isFloatingPoint() && 4665 "Floating point type expected"); 4666 4667 // If the value is a constant, we can obviously see if it is a zero or not. 4668 // TODO: Add BuildVector support. 4669 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4670 return !C->isZero(); 4671 return false; 4672 } 4673 4674 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4675 assert(!Op.getValueType().isFloatingPoint() && 4676 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4677 4678 // If the value is a constant, we can obviously see if it is a zero or not. 4679 if (ISD::matchUnaryPredicate(Op, 4680 [](ConstantSDNode *C) { return !C->isZero(); })) 4681 return true; 4682 4683 // TODO: Recognize more cases here. 4684 switch (Op.getOpcode()) { 4685 default: break; 4686 case ISD::OR: 4687 if (isKnownNeverZero(Op.getOperand(1)) || 4688 isKnownNeverZero(Op.getOperand(0))) 4689 return true; 4690 break; 4691 } 4692 4693 return false; 4694 } 4695 4696 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4697 // Check the obvious case. 4698 if (A == B) return true; 4699 4700 // For for negative and positive zero. 4701 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4702 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4703 if (CA->isZero() && CB->isZero()) return true; 4704 4705 // Otherwise they may not be equal. 4706 return false; 4707 } 4708 4709 // Only bits set in Mask must be negated, other bits may be arbitrary. 4710 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) { 4711 if (isBitwiseNot(V, AllowUndefs)) 4712 return V.getOperand(0); 4713 4714 // Handle any_extend (not (truncate X)) pattern, where Mask only sets 4715 // bits in the non-extended part. 4716 ConstantSDNode *MaskC = isConstOrConstSplat(Mask); 4717 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND) 4718 return SDValue(); 4719 SDValue ExtArg = V.getOperand(0); 4720 if (ExtArg.getScalarValueSizeInBits() >= 4721 MaskC->getAPIntValue().getActiveBits() && 4722 isBitwiseNot(ExtArg, AllowUndefs) && 4723 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE && 4724 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType()) 4725 return ExtArg.getOperand(0).getOperand(0); 4726 return SDValue(); 4727 } 4728 4729 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) { 4730 // Match masked merge pattern (X & ~M) op (Y & M) 4731 // Including degenerate case (X & ~M) op M 4732 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask, 4733 SDValue Other) { 4734 if (SDValue NotOperand = 4735 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) { 4736 if (Other == NotOperand) 4737 return true; 4738 if (Other->getOpcode() == ISD::AND) 4739 return NotOperand == Other->getOperand(0) || 4740 NotOperand == Other->getOperand(1); 4741 } 4742 return false; 4743 }; 4744 if (A->getOpcode() == ISD::AND) 4745 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) || 4746 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B); 4747 return false; 4748 } 4749 4750 // FIXME: unify with llvm::haveNoCommonBitsSet. 4751 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4752 assert(A.getValueType() == B.getValueType() && 4753 "Values must have the same type"); 4754 if (haveNoCommonBitsSetCommutative(A, B) || 4755 haveNoCommonBitsSetCommutative(B, A)) 4756 return true; 4757 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A), 4758 computeKnownBits(B)); 4759 } 4760 4761 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 4762 SelectionDAG &DAG) { 4763 if (cast<ConstantSDNode>(Step)->isZero()) 4764 return DAG.getConstant(0, DL, VT); 4765 4766 return SDValue(); 4767 } 4768 4769 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4770 ArrayRef<SDValue> Ops, 4771 SelectionDAG &DAG) { 4772 int NumOps = Ops.size(); 4773 assert(NumOps != 0 && "Can't build an empty vector!"); 4774 assert(!VT.isScalableVector() && 4775 "BUILD_VECTOR cannot be used with scalable types"); 4776 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4777 "Incorrect element count in BUILD_VECTOR!"); 4778 4779 // BUILD_VECTOR of UNDEFs is UNDEF. 4780 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4781 return DAG.getUNDEF(VT); 4782 4783 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4784 SDValue IdentitySrc; 4785 bool IsIdentity = true; 4786 for (int i = 0; i != NumOps; ++i) { 4787 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4788 Ops[i].getOperand(0).getValueType() != VT || 4789 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4790 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4791 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4792 IsIdentity = false; 4793 break; 4794 } 4795 IdentitySrc = Ops[i].getOperand(0); 4796 } 4797 if (IsIdentity) 4798 return IdentitySrc; 4799 4800 return SDValue(); 4801 } 4802 4803 /// Try to simplify vector concatenation to an input value, undef, or build 4804 /// vector. 4805 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4806 ArrayRef<SDValue> Ops, 4807 SelectionDAG &DAG) { 4808 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4809 assert(llvm::all_of(Ops, 4810 [Ops](SDValue Op) { 4811 return Ops[0].getValueType() == Op.getValueType(); 4812 }) && 4813 "Concatenation of vectors with inconsistent value types!"); 4814 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4815 VT.getVectorElementCount() && 4816 "Incorrect element count in vector concatenation!"); 4817 4818 if (Ops.size() == 1) 4819 return Ops[0]; 4820 4821 // Concat of UNDEFs is UNDEF. 4822 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4823 return DAG.getUNDEF(VT); 4824 4825 // Scan the operands and look for extract operations from a single source 4826 // that correspond to insertion at the same location via this concatenation: 4827 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4828 SDValue IdentitySrc; 4829 bool IsIdentity = true; 4830 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4831 SDValue Op = Ops[i]; 4832 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4833 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4834 Op.getOperand(0).getValueType() != VT || 4835 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4836 Op.getConstantOperandVal(1) != IdentityIndex) { 4837 IsIdentity = false; 4838 break; 4839 } 4840 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4841 "Unexpected identity source vector for concat of extracts"); 4842 IdentitySrc = Op.getOperand(0); 4843 } 4844 if (IsIdentity) { 4845 assert(IdentitySrc && "Failed to set source vector of extracts"); 4846 return IdentitySrc; 4847 } 4848 4849 // The code below this point is only designed to work for fixed width 4850 // vectors, so we bail out for now. 4851 if (VT.isScalableVector()) 4852 return SDValue(); 4853 4854 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4855 // simplified to one big BUILD_VECTOR. 4856 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4857 EVT SVT = VT.getScalarType(); 4858 SmallVector<SDValue, 16> Elts; 4859 for (SDValue Op : Ops) { 4860 EVT OpVT = Op.getValueType(); 4861 if (Op.isUndef()) 4862 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4863 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4864 Elts.append(Op->op_begin(), Op->op_end()); 4865 else 4866 return SDValue(); 4867 } 4868 4869 // BUILD_VECTOR requires all inputs to be of the same type, find the 4870 // maximum type and extend them all. 4871 for (SDValue Op : Elts) 4872 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4873 4874 if (SVT.bitsGT(VT.getScalarType())) { 4875 for (SDValue &Op : Elts) { 4876 if (Op.isUndef()) 4877 Op = DAG.getUNDEF(SVT); 4878 else 4879 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4880 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4881 : DAG.getSExtOrTrunc(Op, DL, SVT); 4882 } 4883 } 4884 4885 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4886 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4887 return V; 4888 } 4889 4890 /// Gets or creates the specified node. 4891 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4892 FoldingSetNodeID ID; 4893 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4894 void *IP = nullptr; 4895 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4896 return SDValue(E, 0); 4897 4898 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4899 getVTList(VT)); 4900 CSEMap.InsertNode(N, IP); 4901 4902 InsertNode(N); 4903 SDValue V = SDValue(N, 0); 4904 NewSDValueDbgMsg(V, "Creating new node: ", this); 4905 return V; 4906 } 4907 4908 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4909 SDValue Operand) { 4910 SDNodeFlags Flags; 4911 if (Inserter) 4912 Flags = Inserter->getFlags(); 4913 return getNode(Opcode, DL, VT, Operand, Flags); 4914 } 4915 4916 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4917 SDValue Operand, const SDNodeFlags Flags) { 4918 assert(Operand.getOpcode() != ISD::DELETED_NODE && 4919 "Operand is DELETED_NODE!"); 4920 // Constant fold unary operations with an integer constant operand. Even 4921 // opaque constant will be folded, because the folding of unary operations 4922 // doesn't create new constants with different values. Nevertheless, the 4923 // opaque flag is preserved during folding to prevent future folding with 4924 // other constants. 4925 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4926 const APInt &Val = C->getAPIntValue(); 4927 switch (Opcode) { 4928 default: break; 4929 case ISD::SIGN_EXTEND: 4930 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4931 C->isTargetOpcode(), C->isOpaque()); 4932 case ISD::TRUNCATE: 4933 if (C->isOpaque()) 4934 break; 4935 LLVM_FALLTHROUGH; 4936 case ISD::ZERO_EXTEND: 4937 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4938 C->isTargetOpcode(), C->isOpaque()); 4939 case ISD::ANY_EXTEND: 4940 // Some targets like RISCV prefer to sign extend some types. 4941 if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT)) 4942 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4943 C->isTargetOpcode(), C->isOpaque()); 4944 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4945 C->isTargetOpcode(), C->isOpaque()); 4946 case ISD::UINT_TO_FP: 4947 case ISD::SINT_TO_FP: { 4948 APFloat apf(EVTToAPFloatSemantics(VT), 4949 APInt::getZero(VT.getSizeInBits())); 4950 (void)apf.convertFromAPInt(Val, 4951 Opcode==ISD::SINT_TO_FP, 4952 APFloat::rmNearestTiesToEven); 4953 return getConstantFP(apf, DL, VT); 4954 } 4955 case ISD::BITCAST: 4956 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 4957 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 4958 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 4959 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 4960 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 4961 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 4962 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 4963 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 4964 break; 4965 case ISD::ABS: 4966 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 4967 C->isOpaque()); 4968 case ISD::BITREVERSE: 4969 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 4970 C->isOpaque()); 4971 case ISD::BSWAP: 4972 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 4973 C->isOpaque()); 4974 case ISD::CTPOP: 4975 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 4976 C->isOpaque()); 4977 case ISD::CTLZ: 4978 case ISD::CTLZ_ZERO_UNDEF: 4979 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 4980 C->isOpaque()); 4981 case ISD::CTTZ: 4982 case ISD::CTTZ_ZERO_UNDEF: 4983 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 4984 C->isOpaque()); 4985 case ISD::FP16_TO_FP: 4986 case ISD::BF16_TO_FP: { 4987 bool Ignored; 4988 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf() 4989 : APFloat::BFloat(), 4990 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 4991 4992 // This can return overflow, underflow, or inexact; we don't care. 4993 // FIXME need to be more flexible about rounding mode. 4994 (void)FPV.convert(EVTToAPFloatSemantics(VT), 4995 APFloat::rmNearestTiesToEven, &Ignored); 4996 return getConstantFP(FPV, DL, VT); 4997 } 4998 case ISD::STEP_VECTOR: { 4999 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this)) 5000 return V; 5001 break; 5002 } 5003 } 5004 } 5005 5006 // Constant fold unary operations with a floating point constant operand. 5007 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 5008 APFloat V = C->getValueAPF(); // make copy 5009 switch (Opcode) { 5010 case ISD::FNEG: 5011 V.changeSign(); 5012 return getConstantFP(V, DL, VT); 5013 case ISD::FABS: 5014 V.clearSign(); 5015 return getConstantFP(V, DL, VT); 5016 case ISD::FCEIL: { 5017 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 5018 if (fs == APFloat::opOK || fs == APFloat::opInexact) 5019 return getConstantFP(V, DL, VT); 5020 break; 5021 } 5022 case ISD::FTRUNC: { 5023 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 5024 if (fs == APFloat::opOK || fs == APFloat::opInexact) 5025 return getConstantFP(V, DL, VT); 5026 break; 5027 } 5028 case ISD::FFLOOR: { 5029 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 5030 if (fs == APFloat::opOK || fs == APFloat::opInexact) 5031 return getConstantFP(V, DL, VT); 5032 break; 5033 } 5034 case ISD::FP_EXTEND: { 5035 bool ignored; 5036 // This can return overflow, underflow, or inexact; we don't care. 5037 // FIXME need to be more flexible about rounding mode. 5038 (void)V.convert(EVTToAPFloatSemantics(VT), 5039 APFloat::rmNearestTiesToEven, &ignored); 5040 return getConstantFP(V, DL, VT); 5041 } 5042 case ISD::FP_TO_SINT: 5043 case ISD::FP_TO_UINT: { 5044 bool ignored; 5045 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 5046 // FIXME need to be more flexible about rounding mode. 5047 APFloat::opStatus s = 5048 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 5049 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 5050 break; 5051 return getConstant(IntVal, DL, VT); 5052 } 5053 case ISD::BITCAST: 5054 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 5055 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5056 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16) 5057 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5058 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 5059 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5060 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 5061 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 5062 break; 5063 case ISD::FP_TO_FP16: 5064 case ISD::FP_TO_BF16: { 5065 bool Ignored; 5066 // This can return overflow, underflow, or inexact; we don't care. 5067 // FIXME need to be more flexible about rounding mode. 5068 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf() 5069 : APFloat::BFloat(), 5070 APFloat::rmNearestTiesToEven, &Ignored); 5071 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 5072 } 5073 } 5074 } 5075 5076 // Constant fold unary operations with a vector integer or float operand. 5077 switch (Opcode) { 5078 default: 5079 // FIXME: Entirely reasonable to perform folding of other unary 5080 // operations here as the need arises. 5081 break; 5082 case ISD::FNEG: 5083 case ISD::FABS: 5084 case ISD::FCEIL: 5085 case ISD::FTRUNC: 5086 case ISD::FFLOOR: 5087 case ISD::FP_EXTEND: 5088 case ISD::FP_TO_SINT: 5089 case ISD::FP_TO_UINT: 5090 case ISD::TRUNCATE: 5091 case ISD::ANY_EXTEND: 5092 case ISD::ZERO_EXTEND: 5093 case ISD::SIGN_EXTEND: 5094 case ISD::UINT_TO_FP: 5095 case ISD::SINT_TO_FP: 5096 case ISD::ABS: 5097 case ISD::BITREVERSE: 5098 case ISD::BSWAP: 5099 case ISD::CTLZ: 5100 case ISD::CTLZ_ZERO_UNDEF: 5101 case ISD::CTTZ: 5102 case ISD::CTTZ_ZERO_UNDEF: 5103 case ISD::CTPOP: { 5104 SDValue Ops = {Operand}; 5105 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops)) 5106 return Fold; 5107 } 5108 } 5109 5110 unsigned OpOpcode = Operand.getNode()->getOpcode(); 5111 switch (Opcode) { 5112 case ISD::STEP_VECTOR: 5113 assert(VT.isScalableVector() && 5114 "STEP_VECTOR can only be used with scalable types"); 5115 assert(OpOpcode == ISD::TargetConstant && 5116 VT.getVectorElementType() == Operand.getValueType() && 5117 "Unexpected step operand"); 5118 break; 5119 case ISD::FREEZE: 5120 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5121 if (isGuaranteedNotToBeUndefOrPoison(Operand)) 5122 return Operand; 5123 break; 5124 case ISD::TokenFactor: 5125 case ISD::MERGE_VALUES: 5126 case ISD::CONCAT_VECTORS: 5127 return Operand; // Factor, merge or concat of one node? No need. 5128 case ISD::BUILD_VECTOR: { 5129 // Attempt to simplify BUILD_VECTOR. 5130 SDValue Ops[] = {Operand}; 5131 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5132 return V; 5133 break; 5134 } 5135 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 5136 case ISD::FP_EXTEND: 5137 assert(VT.isFloatingPoint() && 5138 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 5139 if (Operand.getValueType() == VT) return Operand; // noop conversion. 5140 assert((!VT.isVector() || 5141 VT.getVectorElementCount() == 5142 Operand.getValueType().getVectorElementCount()) && 5143 "Vector element count mismatch!"); 5144 assert(Operand.getValueType().bitsLT(VT) && 5145 "Invalid fpext node, dst < src!"); 5146 if (Operand.isUndef()) 5147 return getUNDEF(VT); 5148 break; 5149 case ISD::FP_TO_SINT: 5150 case ISD::FP_TO_UINT: 5151 if (Operand.isUndef()) 5152 return getUNDEF(VT); 5153 break; 5154 case ISD::SINT_TO_FP: 5155 case ISD::UINT_TO_FP: 5156 // [us]itofp(undef) = 0, because the result value is bounded. 5157 if (Operand.isUndef()) 5158 return getConstantFP(0.0, DL, VT); 5159 break; 5160 case ISD::SIGN_EXTEND: 5161 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5162 "Invalid SIGN_EXTEND!"); 5163 assert(VT.isVector() == Operand.getValueType().isVector() && 5164 "SIGN_EXTEND result type type should be vector iff the operand " 5165 "type is vector!"); 5166 if (Operand.getValueType() == VT) return Operand; // noop extension 5167 assert((!VT.isVector() || 5168 VT.getVectorElementCount() == 5169 Operand.getValueType().getVectorElementCount()) && 5170 "Vector element count mismatch!"); 5171 assert(Operand.getValueType().bitsLT(VT) && 5172 "Invalid sext node, dst < src!"); 5173 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 5174 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5175 if (OpOpcode == ISD::UNDEF) 5176 // sext(undef) = 0, because the top bits will all be the same. 5177 return getConstant(0, DL, VT); 5178 break; 5179 case ISD::ZERO_EXTEND: 5180 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5181 "Invalid ZERO_EXTEND!"); 5182 assert(VT.isVector() == Operand.getValueType().isVector() && 5183 "ZERO_EXTEND result type type should be vector iff the operand " 5184 "type is vector!"); 5185 if (Operand.getValueType() == VT) return Operand; // noop extension 5186 assert((!VT.isVector() || 5187 VT.getVectorElementCount() == 5188 Operand.getValueType().getVectorElementCount()) && 5189 "Vector element count mismatch!"); 5190 assert(Operand.getValueType().bitsLT(VT) && 5191 "Invalid zext node, dst < src!"); 5192 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 5193 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 5194 if (OpOpcode == ISD::UNDEF) 5195 // zext(undef) = 0, because the top bits will be zero. 5196 return getConstant(0, DL, VT); 5197 break; 5198 case ISD::ANY_EXTEND: 5199 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5200 "Invalid ANY_EXTEND!"); 5201 assert(VT.isVector() == Operand.getValueType().isVector() && 5202 "ANY_EXTEND result type type should be vector iff the operand " 5203 "type is vector!"); 5204 if (Operand.getValueType() == VT) return Operand; // noop extension 5205 assert((!VT.isVector() || 5206 VT.getVectorElementCount() == 5207 Operand.getValueType().getVectorElementCount()) && 5208 "Vector element count mismatch!"); 5209 assert(Operand.getValueType().bitsLT(VT) && 5210 "Invalid anyext node, dst < src!"); 5211 5212 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5213 OpOpcode == ISD::ANY_EXTEND) 5214 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 5215 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5216 if (OpOpcode == ISD::UNDEF) 5217 return getUNDEF(VT); 5218 5219 // (ext (trunc x)) -> x 5220 if (OpOpcode == ISD::TRUNCATE) { 5221 SDValue OpOp = Operand.getOperand(0); 5222 if (OpOp.getValueType() == VT) { 5223 transferDbgValues(Operand, OpOp); 5224 return OpOp; 5225 } 5226 } 5227 break; 5228 case ISD::TRUNCATE: 5229 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5230 "Invalid TRUNCATE!"); 5231 assert(VT.isVector() == Operand.getValueType().isVector() && 5232 "TRUNCATE result type type should be vector iff the operand " 5233 "type is vector!"); 5234 if (Operand.getValueType() == VT) return Operand; // noop truncate 5235 assert((!VT.isVector() || 5236 VT.getVectorElementCount() == 5237 Operand.getValueType().getVectorElementCount()) && 5238 "Vector element count mismatch!"); 5239 assert(Operand.getValueType().bitsGT(VT) && 5240 "Invalid truncate node, src < dst!"); 5241 if (OpOpcode == ISD::TRUNCATE) 5242 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5243 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5244 OpOpcode == ISD::ANY_EXTEND) { 5245 // If the source is smaller than the dest, we still need an extend. 5246 if (Operand.getOperand(0).getValueType().getScalarType() 5247 .bitsLT(VT.getScalarType())) 5248 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5249 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 5250 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5251 return Operand.getOperand(0); 5252 } 5253 if (OpOpcode == ISD::UNDEF) 5254 return getUNDEF(VT); 5255 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes) 5256 return getVScale(DL, VT, Operand.getConstantOperandAPInt(0)); 5257 break; 5258 case ISD::ANY_EXTEND_VECTOR_INREG: 5259 case ISD::ZERO_EXTEND_VECTOR_INREG: 5260 case ISD::SIGN_EXTEND_VECTOR_INREG: 5261 assert(VT.isVector() && "This DAG node is restricted to vector types."); 5262 assert(Operand.getValueType().bitsLE(VT) && 5263 "The input must be the same size or smaller than the result."); 5264 assert(VT.getVectorMinNumElements() < 5265 Operand.getValueType().getVectorMinNumElements() && 5266 "The destination vector type must have fewer lanes than the input."); 5267 break; 5268 case ISD::ABS: 5269 assert(VT.isInteger() && VT == Operand.getValueType() && 5270 "Invalid ABS!"); 5271 if (OpOpcode == ISD::UNDEF) 5272 return getConstant(0, DL, VT); 5273 break; 5274 case ISD::BSWAP: 5275 assert(VT.isInteger() && VT == Operand.getValueType() && 5276 "Invalid BSWAP!"); 5277 assert((VT.getScalarSizeInBits() % 16 == 0) && 5278 "BSWAP types must be a multiple of 16 bits!"); 5279 if (OpOpcode == ISD::UNDEF) 5280 return getUNDEF(VT); 5281 // bswap(bswap(X)) -> X. 5282 if (OpOpcode == ISD::BSWAP) 5283 return Operand.getOperand(0); 5284 break; 5285 case ISD::BITREVERSE: 5286 assert(VT.isInteger() && VT == Operand.getValueType() && 5287 "Invalid BITREVERSE!"); 5288 if (OpOpcode == ISD::UNDEF) 5289 return getUNDEF(VT); 5290 break; 5291 case ISD::BITCAST: 5292 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 5293 "Cannot BITCAST between types of different sizes!"); 5294 if (VT == Operand.getValueType()) return Operand; // noop conversion. 5295 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 5296 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 5297 if (OpOpcode == ISD::UNDEF) 5298 return getUNDEF(VT); 5299 break; 5300 case ISD::SCALAR_TO_VECTOR: 5301 assert(VT.isVector() && !Operand.getValueType().isVector() && 5302 (VT.getVectorElementType() == Operand.getValueType() || 5303 (VT.getVectorElementType().isInteger() && 5304 Operand.getValueType().isInteger() && 5305 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 5306 "Illegal SCALAR_TO_VECTOR node!"); 5307 if (OpOpcode == ISD::UNDEF) 5308 return getUNDEF(VT); 5309 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 5310 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 5311 isa<ConstantSDNode>(Operand.getOperand(1)) && 5312 Operand.getConstantOperandVal(1) == 0 && 5313 Operand.getOperand(0).getValueType() == VT) 5314 return Operand.getOperand(0); 5315 break; 5316 case ISD::FNEG: 5317 // Negation of an unknown bag of bits is still completely undefined. 5318 if (OpOpcode == ISD::UNDEF) 5319 return getUNDEF(VT); 5320 5321 if (OpOpcode == ISD::FNEG) // --X -> X 5322 return Operand.getOperand(0); 5323 break; 5324 case ISD::FABS: 5325 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 5326 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 5327 break; 5328 case ISD::VSCALE: 5329 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5330 break; 5331 case ISD::CTPOP: 5332 if (Operand.getValueType().getScalarType() == MVT::i1) 5333 return Operand; 5334 break; 5335 case ISD::CTLZ: 5336 case ISD::CTTZ: 5337 if (Operand.getValueType().getScalarType() == MVT::i1) 5338 return getNOT(DL, Operand, Operand.getValueType()); 5339 break; 5340 case ISD::VECREDUCE_ADD: 5341 if (Operand.getValueType().getScalarType() == MVT::i1) 5342 return getNode(ISD::VECREDUCE_XOR, DL, VT, Operand); 5343 break; 5344 case ISD::VECREDUCE_SMIN: 5345 case ISD::VECREDUCE_UMAX: 5346 if (Operand.getValueType().getScalarType() == MVT::i1) 5347 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 5348 break; 5349 case ISD::VECREDUCE_SMAX: 5350 case ISD::VECREDUCE_UMIN: 5351 if (Operand.getValueType().getScalarType() == MVT::i1) 5352 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 5353 break; 5354 } 5355 5356 SDNode *N; 5357 SDVTList VTs = getVTList(VT); 5358 SDValue Ops[] = {Operand}; 5359 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 5360 FoldingSetNodeID ID; 5361 AddNodeIDNode(ID, Opcode, VTs, Ops); 5362 void *IP = nullptr; 5363 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5364 E->intersectFlagsWith(Flags); 5365 return SDValue(E, 0); 5366 } 5367 5368 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5369 N->setFlags(Flags); 5370 createOperands(N, Ops); 5371 CSEMap.InsertNode(N, IP); 5372 } else { 5373 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5374 createOperands(N, Ops); 5375 } 5376 5377 InsertNode(N); 5378 SDValue V = SDValue(N, 0); 5379 NewSDValueDbgMsg(V, "Creating new node: ", this); 5380 return V; 5381 } 5382 5383 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5384 const APInt &C2) { 5385 switch (Opcode) { 5386 case ISD::ADD: return C1 + C2; 5387 case ISD::SUB: return C1 - C2; 5388 case ISD::MUL: return C1 * C2; 5389 case ISD::AND: return C1 & C2; 5390 case ISD::OR: return C1 | C2; 5391 case ISD::XOR: return C1 ^ C2; 5392 case ISD::SHL: return C1 << C2; 5393 case ISD::SRL: return C1.lshr(C2); 5394 case ISD::SRA: return C1.ashr(C2); 5395 case ISD::ROTL: return C1.rotl(C2); 5396 case ISD::ROTR: return C1.rotr(C2); 5397 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5398 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5399 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5400 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5401 case ISD::SADDSAT: return C1.sadd_sat(C2); 5402 case ISD::UADDSAT: return C1.uadd_sat(C2); 5403 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5404 case ISD::USUBSAT: return C1.usub_sat(C2); 5405 case ISD::SSHLSAT: return C1.sshl_sat(C2); 5406 case ISD::USHLSAT: return C1.ushl_sat(C2); 5407 case ISD::UDIV: 5408 if (!C2.getBoolValue()) 5409 break; 5410 return C1.udiv(C2); 5411 case ISD::UREM: 5412 if (!C2.getBoolValue()) 5413 break; 5414 return C1.urem(C2); 5415 case ISD::SDIV: 5416 if (!C2.getBoolValue()) 5417 break; 5418 return C1.sdiv(C2); 5419 case ISD::SREM: 5420 if (!C2.getBoolValue()) 5421 break; 5422 return C1.srem(C2); 5423 case ISD::MULHS: { 5424 unsigned FullWidth = C1.getBitWidth() * 2; 5425 APInt C1Ext = C1.sext(FullWidth); 5426 APInt C2Ext = C2.sext(FullWidth); 5427 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5428 } 5429 case ISD::MULHU: { 5430 unsigned FullWidth = C1.getBitWidth() * 2; 5431 APInt C1Ext = C1.zext(FullWidth); 5432 APInt C2Ext = C2.zext(FullWidth); 5433 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5434 } 5435 case ISD::AVGFLOORS: { 5436 unsigned FullWidth = C1.getBitWidth() + 1; 5437 APInt C1Ext = C1.sext(FullWidth); 5438 APInt C2Ext = C2.sext(FullWidth); 5439 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5440 } 5441 case ISD::AVGFLOORU: { 5442 unsigned FullWidth = C1.getBitWidth() + 1; 5443 APInt C1Ext = C1.zext(FullWidth); 5444 APInt C2Ext = C2.zext(FullWidth); 5445 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5446 } 5447 case ISD::AVGCEILS: { 5448 unsigned FullWidth = C1.getBitWidth() + 1; 5449 APInt C1Ext = C1.sext(FullWidth); 5450 APInt C2Ext = C2.sext(FullWidth); 5451 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5452 } 5453 case ISD::AVGCEILU: { 5454 unsigned FullWidth = C1.getBitWidth() + 1; 5455 APInt C1Ext = C1.zext(FullWidth); 5456 APInt C2Ext = C2.zext(FullWidth); 5457 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5458 } 5459 } 5460 return llvm::None; 5461 } 5462 5463 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 5464 const GlobalAddressSDNode *GA, 5465 const SDNode *N2) { 5466 if (GA->getOpcode() != ISD::GlobalAddress) 5467 return SDValue(); 5468 if (!TLI->isOffsetFoldingLegal(GA)) 5469 return SDValue(); 5470 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5471 if (!C2) 5472 return SDValue(); 5473 int64_t Offset = C2->getSExtValue(); 5474 switch (Opcode) { 5475 case ISD::ADD: break; 5476 case ISD::SUB: Offset = -uint64_t(Offset); break; 5477 default: return SDValue(); 5478 } 5479 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 5480 GA->getOffset() + uint64_t(Offset)); 5481 } 5482 5483 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 5484 switch (Opcode) { 5485 case ISD::SDIV: 5486 case ISD::UDIV: 5487 case ISD::SREM: 5488 case ISD::UREM: { 5489 // If a divisor is zero/undef or any element of a divisor vector is 5490 // zero/undef, the whole op is undef. 5491 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 5492 SDValue Divisor = Ops[1]; 5493 if (Divisor.isUndef() || isNullConstant(Divisor)) 5494 return true; 5495 5496 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 5497 llvm::any_of(Divisor->op_values(), 5498 [](SDValue V) { return V.isUndef() || 5499 isNullConstant(V); }); 5500 // TODO: Handle signed overflow. 5501 } 5502 // TODO: Handle oversized shifts. 5503 default: 5504 return false; 5505 } 5506 } 5507 5508 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 5509 EVT VT, ArrayRef<SDValue> Ops) { 5510 // If the opcode is a target-specific ISD node, there's nothing we can 5511 // do here and the operand rules may not line up with the below, so 5512 // bail early. 5513 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 5514 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 5515 // foldCONCAT_VECTORS in getNode before this is called. 5516 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 5517 return SDValue(); 5518 5519 unsigned NumOps = Ops.size(); 5520 if (NumOps == 0) 5521 return SDValue(); 5522 5523 if (isUndef(Opcode, Ops)) 5524 return getUNDEF(VT); 5525 5526 // Handle binops special cases. 5527 if (NumOps == 2) { 5528 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1])) 5529 return CFP; 5530 5531 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) { 5532 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) { 5533 if (C1->isOpaque() || C2->isOpaque()) 5534 return SDValue(); 5535 5536 Optional<APInt> FoldAttempt = 5537 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 5538 if (!FoldAttempt) 5539 return SDValue(); 5540 5541 SDValue Folded = getConstant(*FoldAttempt, DL, VT); 5542 assert((!Folded || !VT.isVector()) && 5543 "Can't fold vectors ops with scalar operands"); 5544 return Folded; 5545 } 5546 } 5547 5548 // fold (add Sym, c) -> Sym+c 5549 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0])) 5550 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode()); 5551 if (TLI->isCommutativeBinOp(Opcode)) 5552 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1])) 5553 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode()); 5554 } 5555 5556 // This is for vector folding only from here on. 5557 if (!VT.isVector()) 5558 return SDValue(); 5559 5560 ElementCount NumElts = VT.getVectorElementCount(); 5561 5562 // See if we can fold through bitcasted integer ops. 5563 // TODO: Can we handle undef elements? 5564 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() && 5565 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT && 5566 Ops[0].getOpcode() == ISD::BITCAST && 5567 Ops[1].getOpcode() == ISD::BITCAST) { 5568 SDValue N1 = peekThroughBitcasts(Ops[0]); 5569 SDValue N2 = peekThroughBitcasts(Ops[1]); 5570 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 5571 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 5572 EVT BVVT = N1.getValueType(); 5573 if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) { 5574 bool IsLE = getDataLayout().isLittleEndian(); 5575 unsigned EltBits = VT.getScalarSizeInBits(); 5576 SmallVector<APInt> RawBits1, RawBits2; 5577 BitVector UndefElts1, UndefElts2; 5578 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) && 5579 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) && 5580 UndefElts1.none() && UndefElts2.none()) { 5581 SmallVector<APInt> RawBits; 5582 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) { 5583 Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]); 5584 if (!Fold) 5585 break; 5586 RawBits.push_back(*Fold); 5587 } 5588 if (RawBits.size() == NumElts.getFixedValue()) { 5589 // We have constant folded, but we need to cast this again back to 5590 // the original (possibly legalized) type. 5591 SmallVector<APInt> DstBits; 5592 BitVector DstUndefs; 5593 BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(), 5594 DstBits, RawBits, DstUndefs, 5595 BitVector(RawBits.size(), false)); 5596 EVT BVEltVT = BV1->getOperand(0).getValueType(); 5597 unsigned BVEltBits = BVEltVT.getSizeInBits(); 5598 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT)); 5599 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) { 5600 if (DstUndefs[I]) 5601 continue; 5602 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT); 5603 } 5604 return getBitcast(VT, getBuildVector(BVVT, DL, Ops)); 5605 } 5606 } 5607 } 5608 } 5609 5610 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)). 5611 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1)) 5612 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) && 5613 Ops[0].getOpcode() == ISD::STEP_VECTOR) { 5614 APInt RHSVal; 5615 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) { 5616 APInt NewStep = Opcode == ISD::MUL 5617 ? Ops[0].getConstantOperandAPInt(0) * RHSVal 5618 : Ops[0].getConstantOperandAPInt(0) << RHSVal; 5619 return getStepVector(DL, VT, NewStep); 5620 } 5621 } 5622 5623 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) { 5624 return !Op.getValueType().isVector() || 5625 Op.getValueType().getVectorElementCount() == NumElts; 5626 }; 5627 5628 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) { 5629 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE || 5630 Op.getOpcode() == ISD::BUILD_VECTOR || 5631 Op.getOpcode() == ISD::SPLAT_VECTOR; 5632 }; 5633 5634 // All operands must be vector types with the same number of elements as 5635 // the result type and must be either UNDEF or a build/splat vector 5636 // or UNDEF scalars. 5637 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) || 5638 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5639 return SDValue(); 5640 5641 // If we are comparing vectors, then the result needs to be a i1 boolean that 5642 // is then extended back to the legal result type depending on how booleans 5643 // are represented. 5644 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5645 ISD::NodeType ExtendCode = 5646 (Opcode == ISD::SETCC && SVT != VT.getScalarType()) 5647 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT)) 5648 : ISD::SIGN_EXTEND; 5649 5650 // Find legal integer scalar type for constant promotion and 5651 // ensure that its scalar size is at least as large as source. 5652 EVT LegalSVT = VT.getScalarType(); 5653 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5654 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5655 if (LegalSVT.bitsLT(VT.getScalarType())) 5656 return SDValue(); 5657 } 5658 5659 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We 5660 // only have one operand to check. For fixed-length vector types we may have 5661 // a combination of BUILD_VECTOR and SPLAT_VECTOR. 5662 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue(); 5663 5664 // Constant fold each scalar lane separately. 5665 SmallVector<SDValue, 4> ScalarResults; 5666 for (unsigned I = 0; I != NumVectorElts; I++) { 5667 SmallVector<SDValue, 4> ScalarOps; 5668 for (SDValue Op : Ops) { 5669 EVT InSVT = Op.getValueType().getScalarType(); 5670 if (Op.getOpcode() != ISD::BUILD_VECTOR && 5671 Op.getOpcode() != ISD::SPLAT_VECTOR) { 5672 if (Op.isUndef()) 5673 ScalarOps.push_back(getUNDEF(InSVT)); 5674 else 5675 ScalarOps.push_back(Op); 5676 continue; 5677 } 5678 5679 SDValue ScalarOp = 5680 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I); 5681 EVT ScalarVT = ScalarOp.getValueType(); 5682 5683 // Build vector (integer) scalar operands may need implicit 5684 // truncation - do this before constant folding. 5685 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) { 5686 // Don't create illegally-typed nodes unless they're constants or undef 5687 // - if we fail to constant fold we can't guarantee the (dead) nodes 5688 // we're creating will be cleaned up before being visited for 5689 // legalization. 5690 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() && 5691 !isa<ConstantSDNode>(ScalarOp) && 5692 TLI->getTypeAction(*getContext(), InSVT) != 5693 TargetLowering::TypeLegal) 5694 return SDValue(); 5695 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5696 } 5697 5698 ScalarOps.push_back(ScalarOp); 5699 } 5700 5701 // Constant fold the scalar operands. 5702 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps); 5703 5704 // Legalize the (integer) scalar constant if necessary. 5705 if (LegalSVT != SVT) 5706 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult); 5707 5708 // Scalar folding only succeeded if the result is a constant or UNDEF. 5709 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5710 ScalarResult.getOpcode() != ISD::ConstantFP) 5711 return SDValue(); 5712 ScalarResults.push_back(ScalarResult); 5713 } 5714 5715 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0]) 5716 : getBuildVector(VT, DL, ScalarResults); 5717 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5718 return V; 5719 } 5720 5721 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5722 EVT VT, SDValue N1, SDValue N2) { 5723 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5724 // should. That will require dealing with a potentially non-default 5725 // rounding mode, checking the "opStatus" return value from the APFloat 5726 // math calculations, and possibly other variations. 5727 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false); 5728 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false); 5729 if (N1CFP && N2CFP) { 5730 APFloat C1 = N1CFP->getValueAPF(); // make copy 5731 const APFloat &C2 = N2CFP->getValueAPF(); 5732 switch (Opcode) { 5733 case ISD::FADD: 5734 C1.add(C2, APFloat::rmNearestTiesToEven); 5735 return getConstantFP(C1, DL, VT); 5736 case ISD::FSUB: 5737 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5738 return getConstantFP(C1, DL, VT); 5739 case ISD::FMUL: 5740 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5741 return getConstantFP(C1, DL, VT); 5742 case ISD::FDIV: 5743 C1.divide(C2, APFloat::rmNearestTiesToEven); 5744 return getConstantFP(C1, DL, VT); 5745 case ISD::FREM: 5746 C1.mod(C2); 5747 return getConstantFP(C1, DL, VT); 5748 case ISD::FCOPYSIGN: 5749 C1.copySign(C2); 5750 return getConstantFP(C1, DL, VT); 5751 case ISD::FMINNUM: 5752 return getConstantFP(minnum(C1, C2), DL, VT); 5753 case ISD::FMAXNUM: 5754 return getConstantFP(maxnum(C1, C2), DL, VT); 5755 case ISD::FMINIMUM: 5756 return getConstantFP(minimum(C1, C2), DL, VT); 5757 case ISD::FMAXIMUM: 5758 return getConstantFP(maximum(C1, C2), DL, VT); 5759 default: break; 5760 } 5761 } 5762 if (N1CFP && Opcode == ISD::FP_ROUND) { 5763 APFloat C1 = N1CFP->getValueAPF(); // make copy 5764 bool Unused; 5765 // This can return overflow, underflow, or inexact; we don't care. 5766 // FIXME need to be more flexible about rounding mode. 5767 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5768 &Unused); 5769 return getConstantFP(C1, DL, VT); 5770 } 5771 5772 switch (Opcode) { 5773 case ISD::FSUB: 5774 // -0.0 - undef --> undef (consistent with "fneg undef") 5775 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true)) 5776 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef()) 5777 return getUNDEF(VT); 5778 LLVM_FALLTHROUGH; 5779 5780 case ISD::FADD: 5781 case ISD::FMUL: 5782 case ISD::FDIV: 5783 case ISD::FREM: 5784 // If both operands are undef, the result is undef. If 1 operand is undef, 5785 // the result is NaN. This should match the behavior of the IR optimizer. 5786 if (N1.isUndef() && N2.isUndef()) 5787 return getUNDEF(VT); 5788 if (N1.isUndef() || N2.isUndef()) 5789 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5790 } 5791 return SDValue(); 5792 } 5793 5794 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5795 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5796 5797 // There's no need to assert on a byte-aligned pointer. All pointers are at 5798 // least byte aligned. 5799 if (A == Align(1)) 5800 return Val; 5801 5802 FoldingSetNodeID ID; 5803 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5804 ID.AddInteger(A.value()); 5805 5806 void *IP = nullptr; 5807 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5808 return SDValue(E, 0); 5809 5810 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5811 Val.getValueType(), A); 5812 createOperands(N, {Val}); 5813 5814 CSEMap.InsertNode(N, IP); 5815 InsertNode(N); 5816 5817 SDValue V(N, 0); 5818 NewSDValueDbgMsg(V, "Creating new node: ", this); 5819 return V; 5820 } 5821 5822 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5823 SDValue N1, SDValue N2) { 5824 SDNodeFlags Flags; 5825 if (Inserter) 5826 Flags = Inserter->getFlags(); 5827 return getNode(Opcode, DL, VT, N1, N2, Flags); 5828 } 5829 5830 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1, 5831 SDValue &N2) const { 5832 if (!TLI->isCommutativeBinOp(Opcode)) 5833 return; 5834 5835 // Canonicalize: 5836 // binop(const, nonconst) -> binop(nonconst, const) 5837 bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1); 5838 bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2); 5839 bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1); 5840 bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2); 5841 if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP)) 5842 std::swap(N1, N2); 5843 5844 // Canonicalize: 5845 // binop(splat(x), step_vector) -> binop(step_vector, splat(x)) 5846 else if (N1.getOpcode() == ISD::SPLAT_VECTOR && 5847 N2.getOpcode() == ISD::STEP_VECTOR) 5848 std::swap(N1, N2); 5849 } 5850 5851 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5852 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5853 assert(N1.getOpcode() != ISD::DELETED_NODE && 5854 N2.getOpcode() != ISD::DELETED_NODE && 5855 "Operand is DELETED_NODE!"); 5856 5857 canonicalizeCommutativeBinop(Opcode, N1, N2); 5858 5859 auto *N1C = dyn_cast<ConstantSDNode>(N1); 5860 auto *N2C = dyn_cast<ConstantSDNode>(N2); 5861 5862 // Don't allow undefs in vector splats - we might be returning N2 when folding 5863 // to zero etc. 5864 ConstantSDNode *N2CV = 5865 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true); 5866 5867 switch (Opcode) { 5868 default: break; 5869 case ISD::TokenFactor: 5870 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5871 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5872 // Fold trivial token factors. 5873 if (N1.getOpcode() == ISD::EntryToken) return N2; 5874 if (N2.getOpcode() == ISD::EntryToken) return N1; 5875 if (N1 == N2) return N1; 5876 break; 5877 case ISD::BUILD_VECTOR: { 5878 // Attempt to simplify BUILD_VECTOR. 5879 SDValue Ops[] = {N1, N2}; 5880 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5881 return V; 5882 break; 5883 } 5884 case ISD::CONCAT_VECTORS: { 5885 SDValue Ops[] = {N1, N2}; 5886 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5887 return V; 5888 break; 5889 } 5890 case ISD::AND: 5891 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5892 assert(N1.getValueType() == N2.getValueType() && 5893 N1.getValueType() == VT && "Binary operator types must match!"); 5894 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5895 // worth handling here. 5896 if (N2CV && N2CV->isZero()) 5897 return N2; 5898 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X 5899 return N1; 5900 break; 5901 case ISD::OR: 5902 case ISD::XOR: 5903 case ISD::ADD: 5904 case ISD::SUB: 5905 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5906 assert(N1.getValueType() == N2.getValueType() && 5907 N1.getValueType() == VT && "Binary operator types must match!"); 5908 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5909 // it's worth handling here. 5910 if (N2CV && N2CV->isZero()) 5911 return N1; 5912 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5913 VT.getVectorElementType() == MVT::i1) 5914 return getNode(ISD::XOR, DL, VT, N1, N2); 5915 break; 5916 case ISD::MUL: 5917 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5918 assert(N1.getValueType() == N2.getValueType() && 5919 N1.getValueType() == VT && "Binary operator types must match!"); 5920 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5921 return getNode(ISD::AND, DL, VT, N1, N2); 5922 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5923 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5924 const APInt &N2CImm = N2C->getAPIntValue(); 5925 return getVScale(DL, VT, MulImm * N2CImm); 5926 } 5927 break; 5928 case ISD::UDIV: 5929 case ISD::UREM: 5930 case ISD::MULHU: 5931 case ISD::MULHS: 5932 case ISD::SDIV: 5933 case ISD::SREM: 5934 case ISD::SADDSAT: 5935 case ISD::SSUBSAT: 5936 case ISD::UADDSAT: 5937 case ISD::USUBSAT: 5938 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5939 assert(N1.getValueType() == N2.getValueType() && 5940 N1.getValueType() == VT && "Binary operator types must match!"); 5941 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5942 // fold (add_sat x, y) -> (or x, y) for bool types. 5943 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5944 return getNode(ISD::OR, DL, VT, N1, N2); 5945 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5946 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5947 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5948 } 5949 break; 5950 case ISD::SMIN: 5951 case ISD::UMAX: 5952 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5953 assert(N1.getValueType() == N2.getValueType() && 5954 N1.getValueType() == VT && "Binary operator types must match!"); 5955 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5956 return getNode(ISD::OR, DL, VT, N1, N2); 5957 break; 5958 case ISD::SMAX: 5959 case ISD::UMIN: 5960 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5961 assert(N1.getValueType() == N2.getValueType() && 5962 N1.getValueType() == VT && "Binary operator types must match!"); 5963 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5964 return getNode(ISD::AND, DL, VT, N1, N2); 5965 break; 5966 case ISD::FADD: 5967 case ISD::FSUB: 5968 case ISD::FMUL: 5969 case ISD::FDIV: 5970 case ISD::FREM: 5971 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5972 assert(N1.getValueType() == N2.getValueType() && 5973 N1.getValueType() == VT && "Binary operator types must match!"); 5974 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5975 return V; 5976 break; 5977 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5978 assert(N1.getValueType() == VT && 5979 N1.getValueType().isFloatingPoint() && 5980 N2.getValueType().isFloatingPoint() && 5981 "Invalid FCOPYSIGN!"); 5982 break; 5983 case ISD::SHL: 5984 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5985 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5986 const APInt &ShiftImm = N2C->getAPIntValue(); 5987 return getVScale(DL, VT, MulImm << ShiftImm); 5988 } 5989 LLVM_FALLTHROUGH; 5990 case ISD::SRA: 5991 case ISD::SRL: 5992 if (SDValue V = simplifyShift(N1, N2)) 5993 return V; 5994 LLVM_FALLTHROUGH; 5995 case ISD::ROTL: 5996 case ISD::ROTR: 5997 assert(VT == N1.getValueType() && 5998 "Shift operators return type must be the same as their first arg"); 5999 assert(VT.isInteger() && N2.getValueType().isInteger() && 6000 "Shifts only work on integers"); 6001 assert((!VT.isVector() || VT == N2.getValueType()) && 6002 "Vector shift amounts must be in the same as their first arg"); 6003 // Verify that the shift amount VT is big enough to hold valid shift 6004 // amounts. This catches things like trying to shift an i1024 value by an 6005 // i8, which is easy to fall into in generic code that uses 6006 // TLI.getShiftAmount(). 6007 assert(N2.getValueType().getScalarSizeInBits() >= 6008 Log2_32_Ceil(VT.getScalarSizeInBits()) && 6009 "Invalid use of small shift amount with oversized value!"); 6010 6011 // Always fold shifts of i1 values so the code generator doesn't need to 6012 // handle them. Since we know the size of the shift has to be less than the 6013 // size of the value, the shift/rotate count is guaranteed to be zero. 6014 if (VT == MVT::i1) 6015 return N1; 6016 if (N2CV && N2CV->isZero()) 6017 return N1; 6018 break; 6019 case ISD::FP_ROUND: 6020 assert(VT.isFloatingPoint() && 6021 N1.getValueType().isFloatingPoint() && 6022 VT.bitsLE(N1.getValueType()) && 6023 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 6024 "Invalid FP_ROUND!"); 6025 if (N1.getValueType() == VT) return N1; // noop conversion. 6026 break; 6027 case ISD::AssertSext: 6028 case ISD::AssertZext: { 6029 EVT EVT = cast<VTSDNode>(N2)->getVT(); 6030 assert(VT == N1.getValueType() && "Not an inreg extend!"); 6031 assert(VT.isInteger() && EVT.isInteger() && 6032 "Cannot *_EXTEND_INREG FP types"); 6033 assert(!EVT.isVector() && 6034 "AssertSExt/AssertZExt type should be the vector element type " 6035 "rather than the vector type!"); 6036 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 6037 if (VT.getScalarType() == EVT) return N1; // noop assertion. 6038 break; 6039 } 6040 case ISD::SIGN_EXTEND_INREG: { 6041 EVT EVT = cast<VTSDNode>(N2)->getVT(); 6042 assert(VT == N1.getValueType() && "Not an inreg extend!"); 6043 assert(VT.isInteger() && EVT.isInteger() && 6044 "Cannot *_EXTEND_INREG FP types"); 6045 assert(EVT.isVector() == VT.isVector() && 6046 "SIGN_EXTEND_INREG type should be vector iff the operand " 6047 "type is vector!"); 6048 assert((!EVT.isVector() || 6049 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 6050 "Vector element counts must match in SIGN_EXTEND_INREG"); 6051 assert(EVT.bitsLE(VT) && "Not extending!"); 6052 if (EVT == VT) return N1; // Not actually extending 6053 6054 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 6055 unsigned FromBits = EVT.getScalarSizeInBits(); 6056 Val <<= Val.getBitWidth() - FromBits; 6057 Val.ashrInPlace(Val.getBitWidth() - FromBits); 6058 return getConstant(Val, DL, ConstantVT); 6059 }; 6060 6061 if (N1C) { 6062 const APInt &Val = N1C->getAPIntValue(); 6063 return SignExtendInReg(Val, VT); 6064 } 6065 6066 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 6067 SmallVector<SDValue, 8> Ops; 6068 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 6069 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 6070 SDValue Op = N1.getOperand(i); 6071 if (Op.isUndef()) { 6072 Ops.push_back(getUNDEF(OpVT)); 6073 continue; 6074 } 6075 ConstantSDNode *C = cast<ConstantSDNode>(Op); 6076 APInt Val = C->getAPIntValue(); 6077 Ops.push_back(SignExtendInReg(Val, OpVT)); 6078 } 6079 return getBuildVector(VT, DL, Ops); 6080 } 6081 break; 6082 } 6083 case ISD::FP_TO_SINT_SAT: 6084 case ISD::FP_TO_UINT_SAT: { 6085 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 6086 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 6087 assert(N1.getValueType().isVector() == VT.isVector() && 6088 "FP_TO_*INT_SAT type should be vector iff the operand type is " 6089 "vector!"); 6090 assert((!VT.isVector() || VT.getVectorNumElements() == 6091 N1.getValueType().getVectorNumElements()) && 6092 "Vector element counts must match in FP_TO_*INT_SAT"); 6093 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 6094 "Type to saturate to must be a scalar."); 6095 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 6096 "Not extending!"); 6097 break; 6098 } 6099 case ISD::EXTRACT_VECTOR_ELT: 6100 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 6101 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 6102 element type of the vector."); 6103 6104 // Extract from an undefined value or using an undefined index is undefined. 6105 if (N1.isUndef() || N2.isUndef()) 6106 return getUNDEF(VT); 6107 6108 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 6109 // vectors. For scalable vectors we will provide appropriate support for 6110 // dealing with arbitrary indices. 6111 if (N2C && N1.getValueType().isFixedLengthVector() && 6112 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 6113 return getUNDEF(VT); 6114 6115 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 6116 // expanding copies of large vectors from registers. This only works for 6117 // fixed length vectors, since we need to know the exact number of 6118 // elements. 6119 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 6120 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 6121 unsigned Factor = 6122 N1.getOperand(0).getValueType().getVectorNumElements(); 6123 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 6124 N1.getOperand(N2C->getZExtValue() / Factor), 6125 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 6126 } 6127 6128 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 6129 // lowering is expanding large vector constants. 6130 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 6131 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 6132 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 6133 N1.getValueType().isFixedLengthVector()) && 6134 "BUILD_VECTOR used for scalable vectors"); 6135 unsigned Index = 6136 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 6137 SDValue Elt = N1.getOperand(Index); 6138 6139 if (VT != Elt.getValueType()) 6140 // If the vector element type is not legal, the BUILD_VECTOR operands 6141 // are promoted and implicitly truncated, and the result implicitly 6142 // extended. Make that explicit here. 6143 Elt = getAnyExtOrTrunc(Elt, DL, VT); 6144 6145 return Elt; 6146 } 6147 6148 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 6149 // operations are lowered to scalars. 6150 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 6151 // If the indices are the same, return the inserted element else 6152 // if the indices are known different, extract the element from 6153 // the original vector. 6154 SDValue N1Op2 = N1.getOperand(2); 6155 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 6156 6157 if (N1Op2C && N2C) { 6158 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 6159 if (VT == N1.getOperand(1).getValueType()) 6160 return N1.getOperand(1); 6161 if (VT.isFloatingPoint()) { 6162 assert(VT.getSizeInBits() > N1.getOperand(1).getValueType().getSizeInBits()); 6163 return getFPExtendOrRound(N1.getOperand(1), DL, VT); 6164 } 6165 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 6166 } 6167 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 6168 } 6169 } 6170 6171 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 6172 // when vector types are scalarized and v1iX is legal. 6173 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 6174 // Here we are completely ignoring the extract element index (N2), 6175 // which is fine for fixed width vectors, since any index other than 0 6176 // is undefined anyway. However, this cannot be ignored for scalable 6177 // vectors - in theory we could support this, but we don't want to do this 6178 // without a profitability check. 6179 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6180 N1.getValueType().isFixedLengthVector() && 6181 N1.getValueType().getVectorNumElements() == 1) { 6182 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 6183 N1.getOperand(1)); 6184 } 6185 break; 6186 case ISD::EXTRACT_ELEMENT: 6187 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 6188 assert(!N1.getValueType().isVector() && !VT.isVector() && 6189 (N1.getValueType().isInteger() == VT.isInteger()) && 6190 N1.getValueType() != VT && 6191 "Wrong types for EXTRACT_ELEMENT!"); 6192 6193 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 6194 // 64-bit integers into 32-bit parts. Instead of building the extract of 6195 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 6196 if (N1.getOpcode() == ISD::BUILD_PAIR) 6197 return N1.getOperand(N2C->getZExtValue()); 6198 6199 // EXTRACT_ELEMENT of a constant int is also very common. 6200 if (N1C) { 6201 unsigned ElementSize = VT.getSizeInBits(); 6202 unsigned Shift = ElementSize * N2C->getZExtValue(); 6203 const APInt &Val = N1C->getAPIntValue(); 6204 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 6205 } 6206 break; 6207 case ISD::EXTRACT_SUBVECTOR: { 6208 EVT N1VT = N1.getValueType(); 6209 assert(VT.isVector() && N1VT.isVector() && 6210 "Extract subvector VTs must be vectors!"); 6211 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 6212 "Extract subvector VTs must have the same element type!"); 6213 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 6214 "Cannot extract a scalable vector from a fixed length vector!"); 6215 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6216 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 6217 "Extract subvector must be from larger vector to smaller vector!"); 6218 assert(N2C && "Extract subvector index must be a constant"); 6219 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6220 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 6221 N1VT.getVectorMinNumElements()) && 6222 "Extract subvector overflow!"); 6223 assert(N2C->getAPIntValue().getBitWidth() == 6224 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6225 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 6226 6227 // Trivial extraction. 6228 if (VT == N1VT) 6229 return N1; 6230 6231 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 6232 if (N1.isUndef()) 6233 return getUNDEF(VT); 6234 6235 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 6236 // the concat have the same type as the extract. 6237 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 6238 VT == N1.getOperand(0).getValueType()) { 6239 unsigned Factor = VT.getVectorMinNumElements(); 6240 return N1.getOperand(N2C->getZExtValue() / Factor); 6241 } 6242 6243 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 6244 // during shuffle legalization. 6245 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 6246 VT == N1.getOperand(1).getValueType()) 6247 return N1.getOperand(1); 6248 break; 6249 } 6250 } 6251 6252 // Perform trivial constant folding. 6253 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 6254 return SV; 6255 6256 // Canonicalize an UNDEF to the RHS, even over a constant. 6257 if (N1.isUndef()) { 6258 if (TLI->isCommutativeBinOp(Opcode)) { 6259 std::swap(N1, N2); 6260 } else { 6261 switch (Opcode) { 6262 case ISD::SUB: 6263 return getUNDEF(VT); // fold op(undef, arg2) -> undef 6264 case ISD::SIGN_EXTEND_INREG: 6265 case ISD::UDIV: 6266 case ISD::SDIV: 6267 case ISD::UREM: 6268 case ISD::SREM: 6269 case ISD::SSUBSAT: 6270 case ISD::USUBSAT: 6271 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 6272 } 6273 } 6274 } 6275 6276 // Fold a bunch of operators when the RHS is undef. 6277 if (N2.isUndef()) { 6278 switch (Opcode) { 6279 case ISD::XOR: 6280 if (N1.isUndef()) 6281 // Handle undef ^ undef -> 0 special case. This is a common 6282 // idiom (misuse). 6283 return getConstant(0, DL, VT); 6284 LLVM_FALLTHROUGH; 6285 case ISD::ADD: 6286 case ISD::SUB: 6287 case ISD::UDIV: 6288 case ISD::SDIV: 6289 case ISD::UREM: 6290 case ISD::SREM: 6291 return getUNDEF(VT); // fold op(arg1, undef) -> undef 6292 case ISD::MUL: 6293 case ISD::AND: 6294 case ISD::SSUBSAT: 6295 case ISD::USUBSAT: 6296 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 6297 case ISD::OR: 6298 case ISD::SADDSAT: 6299 case ISD::UADDSAT: 6300 return getAllOnesConstant(DL, VT); 6301 } 6302 } 6303 6304 // Memoize this node if possible. 6305 SDNode *N; 6306 SDVTList VTs = getVTList(VT); 6307 SDValue Ops[] = {N1, N2}; 6308 if (VT != MVT::Glue) { 6309 FoldingSetNodeID ID; 6310 AddNodeIDNode(ID, Opcode, VTs, Ops); 6311 void *IP = nullptr; 6312 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6313 E->intersectFlagsWith(Flags); 6314 return SDValue(E, 0); 6315 } 6316 6317 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6318 N->setFlags(Flags); 6319 createOperands(N, Ops); 6320 CSEMap.InsertNode(N, IP); 6321 } else { 6322 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6323 createOperands(N, Ops); 6324 } 6325 6326 InsertNode(N); 6327 SDValue V = SDValue(N, 0); 6328 NewSDValueDbgMsg(V, "Creating new node: ", this); 6329 return V; 6330 } 6331 6332 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6333 SDValue N1, SDValue N2, SDValue N3) { 6334 SDNodeFlags Flags; 6335 if (Inserter) 6336 Flags = Inserter->getFlags(); 6337 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 6338 } 6339 6340 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6341 SDValue N1, SDValue N2, SDValue N3, 6342 const SDNodeFlags Flags) { 6343 assert(N1.getOpcode() != ISD::DELETED_NODE && 6344 N2.getOpcode() != ISD::DELETED_NODE && 6345 N3.getOpcode() != ISD::DELETED_NODE && 6346 "Operand is DELETED_NODE!"); 6347 // Perform various simplifications. 6348 switch (Opcode) { 6349 case ISD::FMA: { 6350 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6351 assert(N1.getValueType() == VT && N2.getValueType() == VT && 6352 N3.getValueType() == VT && "FMA types must match!"); 6353 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6354 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 6355 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 6356 if (N1CFP && N2CFP && N3CFP) { 6357 APFloat V1 = N1CFP->getValueAPF(); 6358 const APFloat &V2 = N2CFP->getValueAPF(); 6359 const APFloat &V3 = N3CFP->getValueAPF(); 6360 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 6361 return getConstantFP(V1, DL, VT); 6362 } 6363 break; 6364 } 6365 case ISD::BUILD_VECTOR: { 6366 // Attempt to simplify BUILD_VECTOR. 6367 SDValue Ops[] = {N1, N2, N3}; 6368 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6369 return V; 6370 break; 6371 } 6372 case ISD::CONCAT_VECTORS: { 6373 SDValue Ops[] = {N1, N2, N3}; 6374 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6375 return V; 6376 break; 6377 } 6378 case ISD::SETCC: { 6379 assert(VT.isInteger() && "SETCC result type must be an integer!"); 6380 assert(N1.getValueType() == N2.getValueType() && 6381 "SETCC operands must have the same type!"); 6382 assert(VT.isVector() == N1.getValueType().isVector() && 6383 "SETCC type should be vector iff the operand type is vector!"); 6384 assert((!VT.isVector() || VT.getVectorElementCount() == 6385 N1.getValueType().getVectorElementCount()) && 6386 "SETCC vector element counts must match!"); 6387 // Use FoldSetCC to simplify SETCC's. 6388 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 6389 return V; 6390 // Vector constant folding. 6391 SDValue Ops[] = {N1, N2, N3}; 6392 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) { 6393 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 6394 return V; 6395 } 6396 break; 6397 } 6398 case ISD::SELECT: 6399 case ISD::VSELECT: 6400 if (SDValue V = simplifySelect(N1, N2, N3)) 6401 return V; 6402 break; 6403 case ISD::VECTOR_SHUFFLE: 6404 llvm_unreachable("should use getVectorShuffle constructor!"); 6405 case ISD::VECTOR_SPLICE: { 6406 if (cast<ConstantSDNode>(N3)->isNullValue()) 6407 return N1; 6408 break; 6409 } 6410 case ISD::INSERT_VECTOR_ELT: { 6411 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 6412 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 6413 // for scalable vectors where we will generate appropriate code to 6414 // deal with out-of-bounds cases correctly. 6415 if (N3C && N1.getValueType().isFixedLengthVector() && 6416 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 6417 return getUNDEF(VT); 6418 6419 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 6420 if (N3.isUndef()) 6421 return getUNDEF(VT); 6422 6423 // If the inserted element is an UNDEF, just use the input vector. 6424 if (N2.isUndef()) 6425 return N1; 6426 6427 break; 6428 } 6429 case ISD::INSERT_SUBVECTOR: { 6430 // Inserting undef into undef is still undef. 6431 if (N1.isUndef() && N2.isUndef()) 6432 return getUNDEF(VT); 6433 6434 EVT N2VT = N2.getValueType(); 6435 assert(VT == N1.getValueType() && 6436 "Dest and insert subvector source types must match!"); 6437 assert(VT.isVector() && N2VT.isVector() && 6438 "Insert subvector VTs must be vectors!"); 6439 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 6440 "Cannot insert a scalable vector into a fixed length vector!"); 6441 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6442 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 6443 "Insert subvector must be from smaller vector to larger vector!"); 6444 assert(isa<ConstantSDNode>(N3) && 6445 "Insert subvector index must be constant"); 6446 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6447 (N2VT.getVectorMinNumElements() + 6448 cast<ConstantSDNode>(N3)->getZExtValue()) <= 6449 VT.getVectorMinNumElements()) && 6450 "Insert subvector overflow!"); 6451 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 6452 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6453 "Constant index for INSERT_SUBVECTOR has an invalid size"); 6454 6455 // Trivial insertion. 6456 if (VT == N2VT) 6457 return N2; 6458 6459 // If this is an insert of an extracted vector into an undef vector, we 6460 // can just use the input to the extract. 6461 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6462 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 6463 return N2.getOperand(0); 6464 break; 6465 } 6466 case ISD::BITCAST: 6467 // Fold bit_convert nodes from a type to themselves. 6468 if (N1.getValueType() == VT) 6469 return N1; 6470 break; 6471 } 6472 6473 // Memoize node if it doesn't produce a flag. 6474 SDNode *N; 6475 SDVTList VTs = getVTList(VT); 6476 SDValue Ops[] = {N1, N2, N3}; 6477 if (VT != MVT::Glue) { 6478 FoldingSetNodeID ID; 6479 AddNodeIDNode(ID, Opcode, VTs, Ops); 6480 void *IP = nullptr; 6481 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6482 E->intersectFlagsWith(Flags); 6483 return SDValue(E, 0); 6484 } 6485 6486 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6487 N->setFlags(Flags); 6488 createOperands(N, Ops); 6489 CSEMap.InsertNode(N, IP); 6490 } else { 6491 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6492 createOperands(N, Ops); 6493 } 6494 6495 InsertNode(N); 6496 SDValue V = SDValue(N, 0); 6497 NewSDValueDbgMsg(V, "Creating new node: ", this); 6498 return V; 6499 } 6500 6501 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6502 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 6503 SDValue Ops[] = { N1, N2, N3, N4 }; 6504 return getNode(Opcode, DL, VT, Ops); 6505 } 6506 6507 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6508 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6509 SDValue N5) { 6510 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6511 return getNode(Opcode, DL, VT, Ops); 6512 } 6513 6514 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 6515 /// the incoming stack arguments to be loaded from the stack. 6516 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 6517 SmallVector<SDValue, 8> ArgChains; 6518 6519 // Include the original chain at the beginning of the list. When this is 6520 // used by target LowerCall hooks, this helps legalize find the 6521 // CALLSEQ_BEGIN node. 6522 ArgChains.push_back(Chain); 6523 6524 // Add a chain value for each stack argument. 6525 for (SDNode *U : getEntryNode().getNode()->uses()) 6526 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U)) 6527 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 6528 if (FI->getIndex() < 0) 6529 ArgChains.push_back(SDValue(L, 1)); 6530 6531 // Build a tokenfactor for all the chains. 6532 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 6533 } 6534 6535 /// getMemsetValue - Vectorized representation of the memset value 6536 /// operand. 6537 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 6538 const SDLoc &dl) { 6539 assert(!Value.isUndef()); 6540 6541 unsigned NumBits = VT.getScalarSizeInBits(); 6542 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 6543 assert(C->getAPIntValue().getBitWidth() == 8); 6544 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 6545 if (VT.isInteger()) { 6546 bool IsOpaque = VT.getSizeInBits() > 64 || 6547 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 6548 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 6549 } 6550 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 6551 VT); 6552 } 6553 6554 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 6555 EVT IntVT = VT.getScalarType(); 6556 if (!IntVT.isInteger()) 6557 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 6558 6559 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 6560 if (NumBits > 8) { 6561 // Use a multiplication with 0x010101... to extend the input to the 6562 // required length. 6563 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 6564 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 6565 DAG.getConstant(Magic, dl, IntVT)); 6566 } 6567 6568 if (VT != Value.getValueType() && !VT.isInteger()) 6569 Value = DAG.getBitcast(VT.getScalarType(), Value); 6570 if (VT != Value.getValueType()) 6571 Value = DAG.getSplatBuildVector(VT, dl, Value); 6572 6573 return Value; 6574 } 6575 6576 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 6577 /// used when a memcpy is turned into a memset when the source is a constant 6578 /// string ptr. 6579 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 6580 const TargetLowering &TLI, 6581 const ConstantDataArraySlice &Slice) { 6582 // Handle vector with all elements zero. 6583 if (Slice.Array == nullptr) { 6584 if (VT.isInteger()) 6585 return DAG.getConstant(0, dl, VT); 6586 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 6587 return DAG.getConstantFP(0.0, dl, VT); 6588 if (VT.isVector()) { 6589 unsigned NumElts = VT.getVectorNumElements(); 6590 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 6591 return DAG.getNode(ISD::BITCAST, dl, VT, 6592 DAG.getConstant(0, dl, 6593 EVT::getVectorVT(*DAG.getContext(), 6594 EltVT, NumElts))); 6595 } 6596 llvm_unreachable("Expected type!"); 6597 } 6598 6599 assert(!VT.isVector() && "Can't handle vector type here!"); 6600 unsigned NumVTBits = VT.getSizeInBits(); 6601 unsigned NumVTBytes = NumVTBits / 8; 6602 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 6603 6604 APInt Val(NumVTBits, 0); 6605 if (DAG.getDataLayout().isLittleEndian()) { 6606 for (unsigned i = 0; i != NumBytes; ++i) 6607 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 6608 } else { 6609 for (unsigned i = 0; i != NumBytes; ++i) 6610 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6611 } 6612 6613 // If the "cost" of materializing the integer immediate is less than the cost 6614 // of a load, then it is cost effective to turn the load into the immediate. 6615 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6616 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6617 return DAG.getConstant(Val, dl, VT); 6618 return SDValue(); 6619 } 6620 6621 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6622 const SDLoc &DL, 6623 const SDNodeFlags Flags) { 6624 EVT VT = Base.getValueType(); 6625 SDValue Index; 6626 6627 if (Offset.isScalable()) 6628 Index = getVScale(DL, Base.getValueType(), 6629 APInt(Base.getValueSizeInBits().getFixedSize(), 6630 Offset.getKnownMinSize())); 6631 else 6632 Index = getConstant(Offset.getFixedSize(), DL, VT); 6633 6634 return getMemBasePlusOffset(Base, Index, DL, Flags); 6635 } 6636 6637 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6638 const SDLoc &DL, 6639 const SDNodeFlags Flags) { 6640 assert(Offset.getValueType().isInteger()); 6641 EVT BasePtrVT = Ptr.getValueType(); 6642 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6643 } 6644 6645 /// Returns true if memcpy source is constant data. 6646 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6647 uint64_t SrcDelta = 0; 6648 GlobalAddressSDNode *G = nullptr; 6649 if (Src.getOpcode() == ISD::GlobalAddress) 6650 G = cast<GlobalAddressSDNode>(Src); 6651 else if (Src.getOpcode() == ISD::ADD && 6652 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6653 Src.getOperand(1).getOpcode() == ISD::Constant) { 6654 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6655 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6656 } 6657 if (!G) 6658 return false; 6659 6660 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6661 SrcDelta + G->getOffset()); 6662 } 6663 6664 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6665 SelectionDAG &DAG) { 6666 // On Darwin, -Os means optimize for size without hurting performance, so 6667 // only really optimize for size when -Oz (MinSize) is used. 6668 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6669 return MF.getFunction().hasMinSize(); 6670 return DAG.shouldOptForSize(); 6671 } 6672 6673 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6674 SmallVector<SDValue, 32> &OutChains, unsigned From, 6675 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6676 SmallVector<SDValue, 16> &OutStoreChains) { 6677 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6678 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6679 SmallVector<SDValue, 16> GluedLoadChains; 6680 for (unsigned i = From; i < To; ++i) { 6681 OutChains.push_back(OutLoadChains[i]); 6682 GluedLoadChains.push_back(OutLoadChains[i]); 6683 } 6684 6685 // Chain for all loads. 6686 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6687 GluedLoadChains); 6688 6689 for (unsigned i = From; i < To; ++i) { 6690 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6691 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6692 ST->getBasePtr(), ST->getMemoryVT(), 6693 ST->getMemOperand()); 6694 OutChains.push_back(NewStore); 6695 } 6696 } 6697 6698 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6699 SDValue Chain, SDValue Dst, SDValue Src, 6700 uint64_t Size, Align Alignment, 6701 bool isVol, bool AlwaysInline, 6702 MachinePointerInfo DstPtrInfo, 6703 MachinePointerInfo SrcPtrInfo, 6704 const AAMDNodes &AAInfo) { 6705 // Turn a memcpy of undef to nop. 6706 // FIXME: We need to honor volatile even is Src is undef. 6707 if (Src.isUndef()) 6708 return Chain; 6709 6710 // Expand memcpy to a series of load and store ops if the size operand falls 6711 // below a certain threshold. 6712 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6713 // rather than maybe a humongous number of loads and stores. 6714 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6715 const DataLayout &DL = DAG.getDataLayout(); 6716 LLVMContext &C = *DAG.getContext(); 6717 std::vector<EVT> MemOps; 6718 bool DstAlignCanChange = false; 6719 MachineFunction &MF = DAG.getMachineFunction(); 6720 MachineFrameInfo &MFI = MF.getFrameInfo(); 6721 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6722 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6723 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6724 DstAlignCanChange = true; 6725 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6726 if (!SrcAlign || Alignment > *SrcAlign) 6727 SrcAlign = Alignment; 6728 assert(SrcAlign && "SrcAlign must be set"); 6729 ConstantDataArraySlice Slice; 6730 // If marked as volatile, perform a copy even when marked as constant. 6731 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6732 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6733 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6734 const MemOp Op = isZeroConstant 6735 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6736 /*IsZeroMemset*/ true, isVol) 6737 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6738 *SrcAlign, isVol, CopyFromConstant); 6739 if (!TLI.findOptimalMemOpLowering( 6740 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6741 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6742 return SDValue(); 6743 6744 if (DstAlignCanChange) { 6745 Type *Ty = MemOps[0].getTypeForEVT(C); 6746 Align NewAlign = DL.getABITypeAlign(Ty); 6747 6748 // Don't promote to an alignment that would require dynamic stack 6749 // realignment. 6750 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6751 if (!TRI->hasStackRealignment(MF)) 6752 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6753 NewAlign = NewAlign.previous(); 6754 6755 if (NewAlign > Alignment) { 6756 // Give the stack frame object a larger alignment if needed. 6757 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6758 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6759 Alignment = NewAlign; 6760 } 6761 } 6762 6763 // Prepare AAInfo for loads/stores after lowering this memcpy. 6764 AAMDNodes NewAAInfo = AAInfo; 6765 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6766 6767 MachineMemOperand::Flags MMOFlags = 6768 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6769 SmallVector<SDValue, 16> OutLoadChains; 6770 SmallVector<SDValue, 16> OutStoreChains; 6771 SmallVector<SDValue, 32> OutChains; 6772 unsigned NumMemOps = MemOps.size(); 6773 uint64_t SrcOff = 0, DstOff = 0; 6774 for (unsigned i = 0; i != NumMemOps; ++i) { 6775 EVT VT = MemOps[i]; 6776 unsigned VTSize = VT.getSizeInBits() / 8; 6777 SDValue Value, Store; 6778 6779 if (VTSize > Size) { 6780 // Issuing an unaligned load / store pair that overlaps with the previous 6781 // pair. Adjust the offset accordingly. 6782 assert(i == NumMemOps-1 && i != 0); 6783 SrcOff -= VTSize - Size; 6784 DstOff -= VTSize - Size; 6785 } 6786 6787 if (CopyFromConstant && 6788 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6789 // It's unlikely a store of a vector immediate can be done in a single 6790 // instruction. It would require a load from a constantpool first. 6791 // We only handle zero vectors here. 6792 // FIXME: Handle other cases where store of vector immediate is done in 6793 // a single instruction. 6794 ConstantDataArraySlice SubSlice; 6795 if (SrcOff < Slice.Length) { 6796 SubSlice = Slice; 6797 SubSlice.move(SrcOff); 6798 } else { 6799 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6800 SubSlice.Array = nullptr; 6801 SubSlice.Offset = 0; 6802 SubSlice.Length = VTSize; 6803 } 6804 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6805 if (Value.getNode()) { 6806 Store = DAG.getStore( 6807 Chain, dl, Value, 6808 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6809 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6810 OutChains.push_back(Store); 6811 } 6812 } 6813 6814 if (!Store.getNode()) { 6815 // The type might not be legal for the target. This should only happen 6816 // if the type is smaller than a legal type, as on PPC, so the right 6817 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6818 // to Load/Store if NVT==VT. 6819 // FIXME does the case above also need this? 6820 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6821 assert(NVT.bitsGE(VT)); 6822 6823 bool isDereferenceable = 6824 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6825 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6826 if (isDereferenceable) 6827 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6828 6829 Value = DAG.getExtLoad( 6830 ISD::EXTLOAD, dl, NVT, Chain, 6831 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6832 SrcPtrInfo.getWithOffset(SrcOff), VT, 6833 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo); 6834 OutLoadChains.push_back(Value.getValue(1)); 6835 6836 Store = DAG.getTruncStore( 6837 Chain, dl, Value, 6838 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6839 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo); 6840 OutStoreChains.push_back(Store); 6841 } 6842 SrcOff += VTSize; 6843 DstOff += VTSize; 6844 Size -= VTSize; 6845 } 6846 6847 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6848 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6849 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6850 6851 if (NumLdStInMemcpy) { 6852 // It may be that memcpy might be converted to memset if it's memcpy 6853 // of constants. In such a case, we won't have loads and stores, but 6854 // just stores. In the absence of loads, there is nothing to gang up. 6855 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6856 // If target does not care, just leave as it. 6857 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6858 OutChains.push_back(OutLoadChains[i]); 6859 OutChains.push_back(OutStoreChains[i]); 6860 } 6861 } else { 6862 // Ld/St less than/equal limit set by target. 6863 if (NumLdStInMemcpy <= GluedLdStLimit) { 6864 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6865 NumLdStInMemcpy, OutLoadChains, 6866 OutStoreChains); 6867 } else { 6868 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6869 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6870 unsigned GlueIter = 0; 6871 6872 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6873 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6874 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6875 6876 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6877 OutLoadChains, OutStoreChains); 6878 GlueIter += GluedLdStLimit; 6879 } 6880 6881 // Residual ld/st. 6882 if (RemainingLdStInMemcpy) { 6883 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6884 RemainingLdStInMemcpy, OutLoadChains, 6885 OutStoreChains); 6886 } 6887 } 6888 } 6889 } 6890 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6891 } 6892 6893 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6894 SDValue Chain, SDValue Dst, SDValue Src, 6895 uint64_t Size, Align Alignment, 6896 bool isVol, bool AlwaysInline, 6897 MachinePointerInfo DstPtrInfo, 6898 MachinePointerInfo SrcPtrInfo, 6899 const AAMDNodes &AAInfo) { 6900 // Turn a memmove of undef to nop. 6901 // FIXME: We need to honor volatile even is Src is undef. 6902 if (Src.isUndef()) 6903 return Chain; 6904 6905 // Expand memmove to a series of load and store ops if the size operand falls 6906 // below a certain threshold. 6907 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6908 const DataLayout &DL = DAG.getDataLayout(); 6909 LLVMContext &C = *DAG.getContext(); 6910 std::vector<EVT> MemOps; 6911 bool DstAlignCanChange = false; 6912 MachineFunction &MF = DAG.getMachineFunction(); 6913 MachineFrameInfo &MFI = MF.getFrameInfo(); 6914 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6915 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6916 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6917 DstAlignCanChange = true; 6918 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6919 if (!SrcAlign || Alignment > *SrcAlign) 6920 SrcAlign = Alignment; 6921 assert(SrcAlign && "SrcAlign must be set"); 6922 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6923 if (!TLI.findOptimalMemOpLowering( 6924 MemOps, Limit, 6925 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6926 /*IsVolatile*/ true), 6927 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6928 MF.getFunction().getAttributes())) 6929 return SDValue(); 6930 6931 if (DstAlignCanChange) { 6932 Type *Ty = MemOps[0].getTypeForEVT(C); 6933 Align NewAlign = DL.getABITypeAlign(Ty); 6934 if (NewAlign > Alignment) { 6935 // Give the stack frame object a larger alignment if needed. 6936 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6937 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6938 Alignment = NewAlign; 6939 } 6940 } 6941 6942 // Prepare AAInfo for loads/stores after lowering this memmove. 6943 AAMDNodes NewAAInfo = AAInfo; 6944 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6945 6946 MachineMemOperand::Flags MMOFlags = 6947 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6948 uint64_t SrcOff = 0, DstOff = 0; 6949 SmallVector<SDValue, 8> LoadValues; 6950 SmallVector<SDValue, 8> LoadChains; 6951 SmallVector<SDValue, 8> OutChains; 6952 unsigned NumMemOps = MemOps.size(); 6953 for (unsigned i = 0; i < NumMemOps; i++) { 6954 EVT VT = MemOps[i]; 6955 unsigned VTSize = VT.getSizeInBits() / 8; 6956 SDValue Value; 6957 6958 bool isDereferenceable = 6959 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6960 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6961 if (isDereferenceable) 6962 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6963 6964 Value = DAG.getLoad( 6965 VT, dl, Chain, 6966 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6967 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo); 6968 LoadValues.push_back(Value); 6969 LoadChains.push_back(Value.getValue(1)); 6970 SrcOff += VTSize; 6971 } 6972 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6973 OutChains.clear(); 6974 for (unsigned i = 0; i < NumMemOps; i++) { 6975 EVT VT = MemOps[i]; 6976 unsigned VTSize = VT.getSizeInBits() / 8; 6977 SDValue Store; 6978 6979 Store = DAG.getStore( 6980 Chain, dl, LoadValues[i], 6981 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6982 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6983 OutChains.push_back(Store); 6984 DstOff += VTSize; 6985 } 6986 6987 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6988 } 6989 6990 /// Lower the call to 'memset' intrinsic function into a series of store 6991 /// operations. 6992 /// 6993 /// \param DAG Selection DAG where lowered code is placed. 6994 /// \param dl Link to corresponding IR location. 6995 /// \param Chain Control flow dependency. 6996 /// \param Dst Pointer to destination memory location. 6997 /// \param Src Value of byte to write into the memory. 6998 /// \param Size Number of bytes to write. 6999 /// \param Alignment Alignment of the destination in bytes. 7000 /// \param isVol True if destination is volatile. 7001 /// \param AlwaysInline Makes sure no function call is generated. 7002 /// \param DstPtrInfo IR information on the memory pointer. 7003 /// \returns New head in the control flow, if lowering was successful, empty 7004 /// SDValue otherwise. 7005 /// 7006 /// The function tries to replace 'llvm.memset' intrinsic with several store 7007 /// operations and value calculation code. This is usually profitable for small 7008 /// memory size or when the semantic requires inlining. 7009 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 7010 SDValue Chain, SDValue Dst, SDValue Src, 7011 uint64_t Size, Align Alignment, bool isVol, 7012 bool AlwaysInline, MachinePointerInfo DstPtrInfo, 7013 const AAMDNodes &AAInfo) { 7014 // Turn a memset of undef to nop. 7015 // FIXME: We need to honor volatile even is Src is undef. 7016 if (Src.isUndef()) 7017 return Chain; 7018 7019 // Expand memset to a series of load/store ops if the size operand 7020 // falls below a certain threshold. 7021 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7022 std::vector<EVT> MemOps; 7023 bool DstAlignCanChange = false; 7024 MachineFunction &MF = DAG.getMachineFunction(); 7025 MachineFrameInfo &MFI = MF.getFrameInfo(); 7026 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 7027 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 7028 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 7029 DstAlignCanChange = true; 7030 bool IsZeroVal = 7031 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero(); 7032 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize); 7033 7034 if (!TLI.findOptimalMemOpLowering( 7035 MemOps, Limit, 7036 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 7037 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 7038 return SDValue(); 7039 7040 if (DstAlignCanChange) { 7041 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 7042 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 7043 if (NewAlign > Alignment) { 7044 // Give the stack frame object a larger alignment if needed. 7045 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 7046 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 7047 Alignment = NewAlign; 7048 } 7049 } 7050 7051 SmallVector<SDValue, 8> OutChains; 7052 uint64_t DstOff = 0; 7053 unsigned NumMemOps = MemOps.size(); 7054 7055 // Find the largest store and generate the bit pattern for it. 7056 EVT LargestVT = MemOps[0]; 7057 for (unsigned i = 1; i < NumMemOps; i++) 7058 if (MemOps[i].bitsGT(LargestVT)) 7059 LargestVT = MemOps[i]; 7060 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 7061 7062 // Prepare AAInfo for loads/stores after lowering this memset. 7063 AAMDNodes NewAAInfo = AAInfo; 7064 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 7065 7066 for (unsigned i = 0; i < NumMemOps; i++) { 7067 EVT VT = MemOps[i]; 7068 unsigned VTSize = VT.getSizeInBits() / 8; 7069 if (VTSize > Size) { 7070 // Issuing an unaligned load / store pair that overlaps with the previous 7071 // pair. Adjust the offset accordingly. 7072 assert(i == NumMemOps-1 && i != 0); 7073 DstOff -= VTSize - Size; 7074 } 7075 7076 // If this store is smaller than the largest store see whether we can get 7077 // the smaller value for free with a truncate. 7078 SDValue Value = MemSetValue; 7079 if (VT.bitsLT(LargestVT)) { 7080 if (!LargestVT.isVector() && !VT.isVector() && 7081 TLI.isTruncateFree(LargestVT, VT)) 7082 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 7083 else 7084 Value = getMemsetValue(Src, VT, DAG, dl); 7085 } 7086 assert(Value.getValueType() == VT && "Value with wrong type."); 7087 SDValue Store = DAG.getStore( 7088 Chain, dl, Value, 7089 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 7090 DstPtrInfo.getWithOffset(DstOff), Alignment, 7091 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone, 7092 NewAAInfo); 7093 OutChains.push_back(Store); 7094 DstOff += VT.getSizeInBits() / 8; 7095 Size -= VTSize; 7096 } 7097 7098 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 7099 } 7100 7101 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 7102 unsigned AS) { 7103 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 7104 // pointer operands can be losslessly bitcasted to pointers of address space 0 7105 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 7106 report_fatal_error("cannot lower memory intrinsic in address space " + 7107 Twine(AS)); 7108 } 7109 } 7110 7111 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 7112 SDValue Src, SDValue Size, Align Alignment, 7113 bool isVol, bool AlwaysInline, bool isTailCall, 7114 MachinePointerInfo DstPtrInfo, 7115 MachinePointerInfo SrcPtrInfo, 7116 const AAMDNodes &AAInfo) { 7117 // Check to see if we should lower the memcpy to loads and stores first. 7118 // For cases within the target-specified limits, this is the best choice. 7119 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7120 if (ConstantSize) { 7121 // Memcpy with size zero? Just return the original chain. 7122 if (ConstantSize->isZero()) 7123 return Chain; 7124 7125 SDValue Result = getMemcpyLoadsAndStores( 7126 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7127 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7128 if (Result.getNode()) 7129 return Result; 7130 } 7131 7132 // Then check to see if we should lower the memcpy with target-specific 7133 // code. If the target chooses to do this, this is the next best. 7134 if (TSI) { 7135 SDValue Result = TSI->EmitTargetCodeForMemcpy( 7136 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 7137 DstPtrInfo, SrcPtrInfo); 7138 if (Result.getNode()) 7139 return Result; 7140 } 7141 7142 // If we really need inline code and the target declined to provide it, 7143 // use a (potentially long) sequence of loads and stores. 7144 if (AlwaysInline) { 7145 assert(ConstantSize && "AlwaysInline requires a constant size!"); 7146 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 7147 ConstantSize->getZExtValue(), Alignment, 7148 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo); 7149 } 7150 7151 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7152 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7153 7154 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 7155 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 7156 // respect volatile, so they may do things like read or write memory 7157 // beyond the given memory regions. But fixing this isn't easy, and most 7158 // people don't care. 7159 7160 // Emit a library call. 7161 TargetLowering::ArgListTy Args; 7162 TargetLowering::ArgListEntry Entry; 7163 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7164 Entry.Node = Dst; Args.push_back(Entry); 7165 Entry.Node = Src; Args.push_back(Entry); 7166 7167 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7168 Entry.Node = Size; Args.push_back(Entry); 7169 // FIXME: pass in SDLoc 7170 TargetLowering::CallLoweringInfo CLI(*this); 7171 CLI.setDebugLoc(dl) 7172 .setChain(Chain) 7173 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 7174 Dst.getValueType().getTypeForEVT(*getContext()), 7175 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 7176 TLI->getPointerTy(getDataLayout())), 7177 std::move(Args)) 7178 .setDiscardResult() 7179 .setTailCall(isTailCall); 7180 7181 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7182 return CallResult.second; 7183 } 7184 7185 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 7186 SDValue Dst, SDValue Src, SDValue Size, 7187 Type *SizeTy, unsigned ElemSz, 7188 bool isTailCall, 7189 MachinePointerInfo DstPtrInfo, 7190 MachinePointerInfo SrcPtrInfo) { 7191 // Emit a library call. 7192 TargetLowering::ArgListTy Args; 7193 TargetLowering::ArgListEntry Entry; 7194 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7195 Entry.Node = Dst; 7196 Args.push_back(Entry); 7197 7198 Entry.Node = Src; 7199 Args.push_back(Entry); 7200 7201 Entry.Ty = SizeTy; 7202 Entry.Node = Size; 7203 Args.push_back(Entry); 7204 7205 RTLIB::Libcall LibraryCall = 7206 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7207 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7208 report_fatal_error("Unsupported element size"); 7209 7210 TargetLowering::CallLoweringInfo CLI(*this); 7211 CLI.setDebugLoc(dl) 7212 .setChain(Chain) 7213 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7214 Type::getVoidTy(*getContext()), 7215 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7216 TLI->getPointerTy(getDataLayout())), 7217 std::move(Args)) 7218 .setDiscardResult() 7219 .setTailCall(isTailCall); 7220 7221 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7222 return CallResult.second; 7223 } 7224 7225 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 7226 SDValue Src, SDValue Size, Align Alignment, 7227 bool isVol, bool isTailCall, 7228 MachinePointerInfo DstPtrInfo, 7229 MachinePointerInfo SrcPtrInfo, 7230 const AAMDNodes &AAInfo) { 7231 // Check to see if we should lower the memmove to loads and stores first. 7232 // For cases within the target-specified limits, this is the best choice. 7233 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7234 if (ConstantSize) { 7235 // Memmove with size zero? Just return the original chain. 7236 if (ConstantSize->isZero()) 7237 return Chain; 7238 7239 SDValue Result = getMemmoveLoadsAndStores( 7240 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7241 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7242 if (Result.getNode()) 7243 return Result; 7244 } 7245 7246 // Then check to see if we should lower the memmove with target-specific 7247 // code. If the target chooses to do this, this is the next best. 7248 if (TSI) { 7249 SDValue Result = 7250 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 7251 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 7252 if (Result.getNode()) 7253 return Result; 7254 } 7255 7256 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7257 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7258 7259 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 7260 // not be safe. See memcpy above for more details. 7261 7262 // Emit a library call. 7263 TargetLowering::ArgListTy Args; 7264 TargetLowering::ArgListEntry Entry; 7265 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7266 Entry.Node = Dst; Args.push_back(Entry); 7267 Entry.Node = Src; Args.push_back(Entry); 7268 7269 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7270 Entry.Node = Size; Args.push_back(Entry); 7271 // FIXME: pass in SDLoc 7272 TargetLowering::CallLoweringInfo CLI(*this); 7273 CLI.setDebugLoc(dl) 7274 .setChain(Chain) 7275 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 7276 Dst.getValueType().getTypeForEVT(*getContext()), 7277 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 7278 TLI->getPointerTy(getDataLayout())), 7279 std::move(Args)) 7280 .setDiscardResult() 7281 .setTailCall(isTailCall); 7282 7283 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7284 return CallResult.second; 7285 } 7286 7287 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 7288 SDValue Dst, SDValue Src, SDValue Size, 7289 Type *SizeTy, unsigned ElemSz, 7290 bool isTailCall, 7291 MachinePointerInfo DstPtrInfo, 7292 MachinePointerInfo SrcPtrInfo) { 7293 // Emit a library call. 7294 TargetLowering::ArgListTy Args; 7295 TargetLowering::ArgListEntry Entry; 7296 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7297 Entry.Node = Dst; 7298 Args.push_back(Entry); 7299 7300 Entry.Node = Src; 7301 Args.push_back(Entry); 7302 7303 Entry.Ty = SizeTy; 7304 Entry.Node = Size; 7305 Args.push_back(Entry); 7306 7307 RTLIB::Libcall LibraryCall = 7308 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7309 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7310 report_fatal_error("Unsupported element size"); 7311 7312 TargetLowering::CallLoweringInfo CLI(*this); 7313 CLI.setDebugLoc(dl) 7314 .setChain(Chain) 7315 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7316 Type::getVoidTy(*getContext()), 7317 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7318 TLI->getPointerTy(getDataLayout())), 7319 std::move(Args)) 7320 .setDiscardResult() 7321 .setTailCall(isTailCall); 7322 7323 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7324 return CallResult.second; 7325 } 7326 7327 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 7328 SDValue Src, SDValue Size, Align Alignment, 7329 bool isVol, bool AlwaysInline, bool isTailCall, 7330 MachinePointerInfo DstPtrInfo, 7331 const AAMDNodes &AAInfo) { 7332 // Check to see if we should lower the memset to stores first. 7333 // For cases within the target-specified limits, this is the best choice. 7334 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7335 if (ConstantSize) { 7336 // Memset with size zero? Just return the original chain. 7337 if (ConstantSize->isZero()) 7338 return Chain; 7339 7340 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7341 ConstantSize->getZExtValue(), Alignment, 7342 isVol, false, DstPtrInfo, AAInfo); 7343 7344 if (Result.getNode()) 7345 return Result; 7346 } 7347 7348 // Then check to see if we should lower the memset with target-specific 7349 // code. If the target chooses to do this, this is the next best. 7350 if (TSI) { 7351 SDValue Result = TSI->EmitTargetCodeForMemset( 7352 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo); 7353 if (Result.getNode()) 7354 return Result; 7355 } 7356 7357 // If we really need inline code and the target declined to provide it, 7358 // use a (potentially long) sequence of loads and stores. 7359 if (AlwaysInline) { 7360 assert(ConstantSize && "AlwaysInline requires a constant size!"); 7361 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7362 ConstantSize->getZExtValue(), Alignment, 7363 isVol, true, DstPtrInfo, AAInfo); 7364 assert(Result && 7365 "getMemsetStores must return a valid sequence when AlwaysInline"); 7366 return Result; 7367 } 7368 7369 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7370 7371 // Emit a library call. 7372 auto &Ctx = *getContext(); 7373 const auto& DL = getDataLayout(); 7374 7375 TargetLowering::CallLoweringInfo CLI(*this); 7376 // FIXME: pass in SDLoc 7377 CLI.setDebugLoc(dl).setChain(Chain); 7378 7379 ConstantSDNode *ConstantSrc = dyn_cast<ConstantSDNode>(Src); 7380 const bool SrcIsZero = ConstantSrc && ConstantSrc->isZero(); 7381 const char *BzeroName = getTargetLoweringInfo().getLibcallName(RTLIB::BZERO); 7382 7383 // Helper function to create an Entry from Node and Type. 7384 const auto CreateEntry = [](SDValue Node, Type *Ty) { 7385 TargetLowering::ArgListEntry Entry; 7386 Entry.Node = Node; 7387 Entry.Ty = Ty; 7388 return Entry; 7389 }; 7390 7391 // If zeroing out and bzero is present, use it. 7392 if (SrcIsZero && BzeroName) { 7393 TargetLowering::ArgListTy Args; 7394 Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx))); 7395 Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx))); 7396 CLI.setLibCallee( 7397 TLI->getLibcallCallingConv(RTLIB::BZERO), Type::getVoidTy(Ctx), 7398 getExternalSymbol(BzeroName, TLI->getPointerTy(DL)), std::move(Args)); 7399 } else { 7400 TargetLowering::ArgListTy Args; 7401 Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx))); 7402 Args.push_back(CreateEntry(Src, Src.getValueType().getTypeForEVT(Ctx))); 7403 Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx))); 7404 CLI.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 7405 Dst.getValueType().getTypeForEVT(Ctx), 7406 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 7407 TLI->getPointerTy(DL)), 7408 std::move(Args)); 7409 } 7410 7411 CLI.setDiscardResult().setTailCall(isTailCall); 7412 7413 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7414 return CallResult.second; 7415 } 7416 7417 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 7418 SDValue Dst, SDValue Value, SDValue Size, 7419 Type *SizeTy, unsigned ElemSz, 7420 bool isTailCall, 7421 MachinePointerInfo DstPtrInfo) { 7422 // Emit a library call. 7423 TargetLowering::ArgListTy Args; 7424 TargetLowering::ArgListEntry Entry; 7425 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7426 Entry.Node = Dst; 7427 Args.push_back(Entry); 7428 7429 Entry.Ty = Type::getInt8Ty(*getContext()); 7430 Entry.Node = Value; 7431 Args.push_back(Entry); 7432 7433 Entry.Ty = SizeTy; 7434 Entry.Node = Size; 7435 Args.push_back(Entry); 7436 7437 RTLIB::Libcall LibraryCall = 7438 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7439 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7440 report_fatal_error("Unsupported element size"); 7441 7442 TargetLowering::CallLoweringInfo CLI(*this); 7443 CLI.setDebugLoc(dl) 7444 .setChain(Chain) 7445 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7446 Type::getVoidTy(*getContext()), 7447 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7448 TLI->getPointerTy(getDataLayout())), 7449 std::move(Args)) 7450 .setDiscardResult() 7451 .setTailCall(isTailCall); 7452 7453 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7454 return CallResult.second; 7455 } 7456 7457 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7458 SDVTList VTList, ArrayRef<SDValue> Ops, 7459 MachineMemOperand *MMO) { 7460 FoldingSetNodeID ID; 7461 ID.AddInteger(MemVT.getRawBits()); 7462 AddNodeIDNode(ID, Opcode, VTList, Ops); 7463 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7464 ID.AddInteger(MMO->getFlags()); 7465 void* IP = nullptr; 7466 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7467 cast<AtomicSDNode>(E)->refineAlignment(MMO); 7468 return SDValue(E, 0); 7469 } 7470 7471 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7472 VTList, MemVT, MMO); 7473 createOperands(N, Ops); 7474 7475 CSEMap.InsertNode(N, IP); 7476 InsertNode(N); 7477 return SDValue(N, 0); 7478 } 7479 7480 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 7481 EVT MemVT, SDVTList VTs, SDValue Chain, 7482 SDValue Ptr, SDValue Cmp, SDValue Swp, 7483 MachineMemOperand *MMO) { 7484 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 7485 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 7486 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 7487 7488 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 7489 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7490 } 7491 7492 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7493 SDValue Chain, SDValue Ptr, SDValue Val, 7494 MachineMemOperand *MMO) { 7495 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 7496 Opcode == ISD::ATOMIC_LOAD_SUB || 7497 Opcode == ISD::ATOMIC_LOAD_AND || 7498 Opcode == ISD::ATOMIC_LOAD_CLR || 7499 Opcode == ISD::ATOMIC_LOAD_OR || 7500 Opcode == ISD::ATOMIC_LOAD_XOR || 7501 Opcode == ISD::ATOMIC_LOAD_NAND || 7502 Opcode == ISD::ATOMIC_LOAD_MIN || 7503 Opcode == ISD::ATOMIC_LOAD_MAX || 7504 Opcode == ISD::ATOMIC_LOAD_UMIN || 7505 Opcode == ISD::ATOMIC_LOAD_UMAX || 7506 Opcode == ISD::ATOMIC_LOAD_FADD || 7507 Opcode == ISD::ATOMIC_LOAD_FSUB || 7508 Opcode == ISD::ATOMIC_LOAD_FMAX || 7509 Opcode == ISD::ATOMIC_LOAD_FMIN || 7510 Opcode == ISD::ATOMIC_SWAP || 7511 Opcode == ISD::ATOMIC_STORE) && 7512 "Invalid Atomic Op"); 7513 7514 EVT VT = Val.getValueType(); 7515 7516 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 7517 getVTList(VT, MVT::Other); 7518 SDValue Ops[] = {Chain, Ptr, Val}; 7519 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7520 } 7521 7522 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7523 EVT VT, SDValue Chain, SDValue Ptr, 7524 MachineMemOperand *MMO) { 7525 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 7526 7527 SDVTList VTs = getVTList(VT, MVT::Other); 7528 SDValue Ops[] = {Chain, Ptr}; 7529 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7530 } 7531 7532 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 7533 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 7534 if (Ops.size() == 1) 7535 return Ops[0]; 7536 7537 SmallVector<EVT, 4> VTs; 7538 VTs.reserve(Ops.size()); 7539 for (const SDValue &Op : Ops) 7540 VTs.push_back(Op.getValueType()); 7541 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 7542 } 7543 7544 SDValue SelectionDAG::getMemIntrinsicNode( 7545 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 7546 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 7547 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 7548 if (!Size && MemVT.isScalableVector()) 7549 Size = MemoryLocation::UnknownSize; 7550 else if (!Size) 7551 Size = MemVT.getStoreSize(); 7552 7553 MachineFunction &MF = getMachineFunction(); 7554 MachineMemOperand *MMO = 7555 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 7556 7557 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 7558 } 7559 7560 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 7561 SDVTList VTList, 7562 ArrayRef<SDValue> Ops, EVT MemVT, 7563 MachineMemOperand *MMO) { 7564 assert((Opcode == ISD::INTRINSIC_VOID || 7565 Opcode == ISD::INTRINSIC_W_CHAIN || 7566 Opcode == ISD::PREFETCH || 7567 ((int)Opcode <= std::numeric_limits<int>::max() && 7568 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 7569 "Opcode is not a memory-accessing opcode!"); 7570 7571 // Memoize the node unless it returns a flag. 7572 MemIntrinsicSDNode *N; 7573 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7574 FoldingSetNodeID ID; 7575 AddNodeIDNode(ID, Opcode, VTList, Ops); 7576 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 7577 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 7578 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7579 ID.AddInteger(MMO->getFlags()); 7580 void *IP = nullptr; 7581 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7582 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 7583 return SDValue(E, 0); 7584 } 7585 7586 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7587 VTList, MemVT, MMO); 7588 createOperands(N, Ops); 7589 7590 CSEMap.InsertNode(N, IP); 7591 } else { 7592 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7593 VTList, MemVT, MMO); 7594 createOperands(N, Ops); 7595 } 7596 InsertNode(N); 7597 SDValue V(N, 0); 7598 NewSDValueDbgMsg(V, "Creating new node: ", this); 7599 return V; 7600 } 7601 7602 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 7603 SDValue Chain, int FrameIndex, 7604 int64_t Size, int64_t Offset) { 7605 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 7606 const auto VTs = getVTList(MVT::Other); 7607 SDValue Ops[2] = { 7608 Chain, 7609 getFrameIndex(FrameIndex, 7610 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 7611 true)}; 7612 7613 FoldingSetNodeID ID; 7614 AddNodeIDNode(ID, Opcode, VTs, Ops); 7615 ID.AddInteger(FrameIndex); 7616 ID.AddInteger(Size); 7617 ID.AddInteger(Offset); 7618 void *IP = nullptr; 7619 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7620 return SDValue(E, 0); 7621 7622 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 7623 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 7624 createOperands(N, Ops); 7625 CSEMap.InsertNode(N, IP); 7626 InsertNode(N); 7627 SDValue V(N, 0); 7628 NewSDValueDbgMsg(V, "Creating new node: ", this); 7629 return V; 7630 } 7631 7632 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 7633 uint64_t Guid, uint64_t Index, 7634 uint32_t Attr) { 7635 const unsigned Opcode = ISD::PSEUDO_PROBE; 7636 const auto VTs = getVTList(MVT::Other); 7637 SDValue Ops[] = {Chain}; 7638 FoldingSetNodeID ID; 7639 AddNodeIDNode(ID, Opcode, VTs, Ops); 7640 ID.AddInteger(Guid); 7641 ID.AddInteger(Index); 7642 void *IP = nullptr; 7643 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 7644 return SDValue(E, 0); 7645 7646 auto *N = newSDNode<PseudoProbeSDNode>( 7647 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 7648 createOperands(N, Ops); 7649 CSEMap.InsertNode(N, IP); 7650 InsertNode(N); 7651 SDValue V(N, 0); 7652 NewSDValueDbgMsg(V, "Creating new node: ", this); 7653 return V; 7654 } 7655 7656 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7657 /// MachinePointerInfo record from it. This is particularly useful because the 7658 /// code generator has many cases where it doesn't bother passing in a 7659 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7660 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7661 SelectionDAG &DAG, SDValue Ptr, 7662 int64_t Offset = 0) { 7663 // If this is FI+Offset, we can model it. 7664 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7665 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7666 FI->getIndex(), Offset); 7667 7668 // If this is (FI+Offset1)+Offset2, we can model it. 7669 if (Ptr.getOpcode() != ISD::ADD || 7670 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7671 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7672 return Info; 7673 7674 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7675 return MachinePointerInfo::getFixedStack( 7676 DAG.getMachineFunction(), FI, 7677 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7678 } 7679 7680 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7681 /// MachinePointerInfo record from it. This is particularly useful because the 7682 /// code generator has many cases where it doesn't bother passing in a 7683 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7684 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7685 SelectionDAG &DAG, SDValue Ptr, 7686 SDValue OffsetOp) { 7687 // If the 'Offset' value isn't a constant, we can't handle this. 7688 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7689 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7690 if (OffsetOp.isUndef()) 7691 return InferPointerInfo(Info, DAG, Ptr); 7692 return Info; 7693 } 7694 7695 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7696 EVT VT, const SDLoc &dl, SDValue Chain, 7697 SDValue Ptr, SDValue Offset, 7698 MachinePointerInfo PtrInfo, EVT MemVT, 7699 Align Alignment, 7700 MachineMemOperand::Flags MMOFlags, 7701 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7702 assert(Chain.getValueType() == MVT::Other && 7703 "Invalid chain type"); 7704 7705 MMOFlags |= MachineMemOperand::MOLoad; 7706 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7707 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7708 // clients. 7709 if (PtrInfo.V.isNull()) 7710 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7711 7712 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7713 MachineFunction &MF = getMachineFunction(); 7714 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7715 Alignment, AAInfo, Ranges); 7716 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7717 } 7718 7719 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7720 EVT VT, const SDLoc &dl, SDValue Chain, 7721 SDValue Ptr, SDValue Offset, EVT MemVT, 7722 MachineMemOperand *MMO) { 7723 if (VT == MemVT) { 7724 ExtType = ISD::NON_EXTLOAD; 7725 } else if (ExtType == ISD::NON_EXTLOAD) { 7726 assert(VT == MemVT && "Non-extending load from different memory type!"); 7727 } else { 7728 // Extending load. 7729 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7730 "Should only be an extending load, not truncating!"); 7731 assert(VT.isInteger() == MemVT.isInteger() && 7732 "Cannot convert from FP to Int or Int -> FP!"); 7733 assert(VT.isVector() == MemVT.isVector() && 7734 "Cannot use an ext load to convert to or from a vector!"); 7735 assert((!VT.isVector() || 7736 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7737 "Cannot use an ext load to change the number of vector elements!"); 7738 } 7739 7740 bool Indexed = AM != ISD::UNINDEXED; 7741 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7742 7743 SDVTList VTs = Indexed ? 7744 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7745 SDValue Ops[] = { Chain, Ptr, Offset }; 7746 FoldingSetNodeID ID; 7747 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7748 ID.AddInteger(MemVT.getRawBits()); 7749 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7750 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7751 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7752 ID.AddInteger(MMO->getFlags()); 7753 void *IP = nullptr; 7754 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7755 cast<LoadSDNode>(E)->refineAlignment(MMO); 7756 return SDValue(E, 0); 7757 } 7758 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7759 ExtType, MemVT, MMO); 7760 createOperands(N, Ops); 7761 7762 CSEMap.InsertNode(N, IP); 7763 InsertNode(N); 7764 SDValue V(N, 0); 7765 NewSDValueDbgMsg(V, "Creating new node: ", this); 7766 return V; 7767 } 7768 7769 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7770 SDValue Ptr, MachinePointerInfo PtrInfo, 7771 MaybeAlign Alignment, 7772 MachineMemOperand::Flags MMOFlags, 7773 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7774 SDValue Undef = getUNDEF(Ptr.getValueType()); 7775 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7776 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7777 } 7778 7779 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7780 SDValue Ptr, MachineMemOperand *MMO) { 7781 SDValue Undef = getUNDEF(Ptr.getValueType()); 7782 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7783 VT, MMO); 7784 } 7785 7786 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7787 EVT VT, SDValue Chain, SDValue Ptr, 7788 MachinePointerInfo PtrInfo, EVT MemVT, 7789 MaybeAlign Alignment, 7790 MachineMemOperand::Flags MMOFlags, 7791 const AAMDNodes &AAInfo) { 7792 SDValue Undef = getUNDEF(Ptr.getValueType()); 7793 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7794 MemVT, Alignment, MMOFlags, AAInfo); 7795 } 7796 7797 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7798 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7799 MachineMemOperand *MMO) { 7800 SDValue Undef = getUNDEF(Ptr.getValueType()); 7801 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7802 MemVT, MMO); 7803 } 7804 7805 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7806 SDValue Base, SDValue Offset, 7807 ISD::MemIndexedMode AM) { 7808 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7809 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7810 // Don't propagate the invariant or dereferenceable flags. 7811 auto MMOFlags = 7812 LD->getMemOperand()->getFlags() & 7813 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7814 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7815 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7816 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7817 } 7818 7819 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7820 SDValue Ptr, MachinePointerInfo PtrInfo, 7821 Align Alignment, 7822 MachineMemOperand::Flags MMOFlags, 7823 const AAMDNodes &AAInfo) { 7824 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7825 7826 MMOFlags |= MachineMemOperand::MOStore; 7827 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7828 7829 if (PtrInfo.V.isNull()) 7830 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7831 7832 MachineFunction &MF = getMachineFunction(); 7833 uint64_t Size = 7834 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7835 MachineMemOperand *MMO = 7836 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7837 return getStore(Chain, dl, Val, Ptr, MMO); 7838 } 7839 7840 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7841 SDValue Ptr, MachineMemOperand *MMO) { 7842 assert(Chain.getValueType() == MVT::Other && 7843 "Invalid chain type"); 7844 EVT VT = Val.getValueType(); 7845 SDVTList VTs = getVTList(MVT::Other); 7846 SDValue Undef = getUNDEF(Ptr.getValueType()); 7847 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7848 FoldingSetNodeID ID; 7849 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7850 ID.AddInteger(VT.getRawBits()); 7851 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7852 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7853 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7854 ID.AddInteger(MMO->getFlags()); 7855 void *IP = nullptr; 7856 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7857 cast<StoreSDNode>(E)->refineAlignment(MMO); 7858 return SDValue(E, 0); 7859 } 7860 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7861 ISD::UNINDEXED, false, VT, MMO); 7862 createOperands(N, Ops); 7863 7864 CSEMap.InsertNode(N, IP); 7865 InsertNode(N); 7866 SDValue V(N, 0); 7867 NewSDValueDbgMsg(V, "Creating new node: ", this); 7868 return V; 7869 } 7870 7871 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7872 SDValue Ptr, MachinePointerInfo PtrInfo, 7873 EVT SVT, Align Alignment, 7874 MachineMemOperand::Flags MMOFlags, 7875 const AAMDNodes &AAInfo) { 7876 assert(Chain.getValueType() == MVT::Other && 7877 "Invalid chain type"); 7878 7879 MMOFlags |= MachineMemOperand::MOStore; 7880 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7881 7882 if (PtrInfo.V.isNull()) 7883 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7884 7885 MachineFunction &MF = getMachineFunction(); 7886 MachineMemOperand *MMO = MF.getMachineMemOperand( 7887 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7888 Alignment, AAInfo); 7889 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7890 } 7891 7892 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7893 SDValue Ptr, EVT SVT, 7894 MachineMemOperand *MMO) { 7895 EVT VT = Val.getValueType(); 7896 7897 assert(Chain.getValueType() == MVT::Other && 7898 "Invalid chain type"); 7899 if (VT == SVT) 7900 return getStore(Chain, dl, Val, Ptr, MMO); 7901 7902 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7903 "Should only be a truncating store, not extending!"); 7904 assert(VT.isInteger() == SVT.isInteger() && 7905 "Can't do FP-INT conversion!"); 7906 assert(VT.isVector() == SVT.isVector() && 7907 "Cannot use trunc store to convert to or from a vector!"); 7908 assert((!VT.isVector() || 7909 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7910 "Cannot use trunc store to change the number of vector elements!"); 7911 7912 SDVTList VTs = getVTList(MVT::Other); 7913 SDValue Undef = getUNDEF(Ptr.getValueType()); 7914 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7915 FoldingSetNodeID ID; 7916 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7917 ID.AddInteger(SVT.getRawBits()); 7918 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7919 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7920 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7921 ID.AddInteger(MMO->getFlags()); 7922 void *IP = nullptr; 7923 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7924 cast<StoreSDNode>(E)->refineAlignment(MMO); 7925 return SDValue(E, 0); 7926 } 7927 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7928 ISD::UNINDEXED, true, SVT, MMO); 7929 createOperands(N, Ops); 7930 7931 CSEMap.InsertNode(N, IP); 7932 InsertNode(N); 7933 SDValue V(N, 0); 7934 NewSDValueDbgMsg(V, "Creating new node: ", this); 7935 return V; 7936 } 7937 7938 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7939 SDValue Base, SDValue Offset, 7940 ISD::MemIndexedMode AM) { 7941 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7942 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7943 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7944 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7945 FoldingSetNodeID ID; 7946 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7947 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7948 ID.AddInteger(ST->getRawSubclassData()); 7949 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7950 ID.AddInteger(ST->getMemOperand()->getFlags()); 7951 void *IP = nullptr; 7952 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7953 return SDValue(E, 0); 7954 7955 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7956 ST->isTruncatingStore(), ST->getMemoryVT(), 7957 ST->getMemOperand()); 7958 createOperands(N, Ops); 7959 7960 CSEMap.InsertNode(N, IP); 7961 InsertNode(N); 7962 SDValue V(N, 0); 7963 NewSDValueDbgMsg(V, "Creating new node: ", this); 7964 return V; 7965 } 7966 7967 SDValue SelectionDAG::getLoadVP( 7968 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, 7969 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, 7970 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 7971 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 7972 const MDNode *Ranges, bool IsExpanding) { 7973 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7974 7975 MMOFlags |= MachineMemOperand::MOLoad; 7976 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7977 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7978 // clients. 7979 if (PtrInfo.V.isNull()) 7980 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7981 7982 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7983 MachineFunction &MF = getMachineFunction(); 7984 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7985 Alignment, AAInfo, Ranges); 7986 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT, 7987 MMO, IsExpanding); 7988 } 7989 7990 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM, 7991 ISD::LoadExtType ExtType, EVT VT, 7992 const SDLoc &dl, SDValue Chain, SDValue Ptr, 7993 SDValue Offset, SDValue Mask, SDValue EVL, 7994 EVT MemVT, MachineMemOperand *MMO, 7995 bool IsExpanding) { 7996 bool Indexed = AM != ISD::UNINDEXED; 7997 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7998 7999 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 8000 : getVTList(VT, MVT::Other); 8001 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL}; 8002 FoldingSetNodeID ID; 8003 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops); 8004 ID.AddInteger(VT.getRawBits()); 8005 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>( 8006 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 8007 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8008 ID.AddInteger(MMO->getFlags()); 8009 void *IP = nullptr; 8010 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8011 cast<VPLoadSDNode>(E)->refineAlignment(MMO); 8012 return SDValue(E, 0); 8013 } 8014 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8015 ExtType, IsExpanding, MemVT, MMO); 8016 createOperands(N, Ops); 8017 8018 CSEMap.InsertNode(N, IP); 8019 InsertNode(N); 8020 SDValue V(N, 0); 8021 NewSDValueDbgMsg(V, "Creating new node: ", this); 8022 return V; 8023 } 8024 8025 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 8026 SDValue Ptr, SDValue Mask, SDValue EVL, 8027 MachinePointerInfo PtrInfo, 8028 MaybeAlign Alignment, 8029 MachineMemOperand::Flags MMOFlags, 8030 const AAMDNodes &AAInfo, const MDNode *Ranges, 8031 bool IsExpanding) { 8032 SDValue Undef = getUNDEF(Ptr.getValueType()); 8033 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 8034 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges, 8035 IsExpanding); 8036 } 8037 8038 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 8039 SDValue Ptr, SDValue Mask, SDValue EVL, 8040 MachineMemOperand *MMO, bool IsExpanding) { 8041 SDValue Undef = getUNDEF(Ptr.getValueType()); 8042 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 8043 Mask, EVL, VT, MMO, IsExpanding); 8044 } 8045 8046 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 8047 EVT VT, SDValue Chain, SDValue Ptr, 8048 SDValue Mask, SDValue EVL, 8049 MachinePointerInfo PtrInfo, EVT MemVT, 8050 MaybeAlign Alignment, 8051 MachineMemOperand::Flags MMOFlags, 8052 const AAMDNodes &AAInfo, bool IsExpanding) { 8053 SDValue Undef = getUNDEF(Ptr.getValueType()); 8054 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 8055 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr, 8056 IsExpanding); 8057 } 8058 8059 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 8060 EVT VT, SDValue Chain, SDValue Ptr, 8061 SDValue Mask, SDValue EVL, EVT MemVT, 8062 MachineMemOperand *MMO, bool IsExpanding) { 8063 SDValue Undef = getUNDEF(Ptr.getValueType()); 8064 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 8065 EVL, MemVT, MMO, IsExpanding); 8066 } 8067 8068 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, 8069 SDValue Base, SDValue Offset, 8070 ISD::MemIndexedMode AM) { 8071 auto *LD = cast<VPLoadSDNode>(OrigLoad); 8072 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 8073 // Don't propagate the invariant or dereferenceable flags. 8074 auto MMOFlags = 8075 LD->getMemOperand()->getFlags() & 8076 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8077 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 8078 LD->getChain(), Base, Offset, LD->getMask(), 8079 LD->getVectorLength(), LD->getPointerInfo(), 8080 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(), 8081 nullptr, LD->isExpandingLoad()); 8082 } 8083 8084 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 8085 SDValue Ptr, SDValue Offset, SDValue Mask, 8086 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, 8087 ISD::MemIndexedMode AM, bool IsTruncating, 8088 bool IsCompressing) { 8089 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8090 bool Indexed = AM != ISD::UNINDEXED; 8091 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 8092 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 8093 : getVTList(MVT::Other); 8094 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL}; 8095 FoldingSetNodeID ID; 8096 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8097 ID.AddInteger(MemVT.getRawBits()); 8098 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8099 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8100 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8101 ID.AddInteger(MMO->getFlags()); 8102 void *IP = nullptr; 8103 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8104 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8105 return SDValue(E, 0); 8106 } 8107 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8108 IsTruncating, IsCompressing, MemVT, MMO); 8109 createOperands(N, Ops); 8110 8111 CSEMap.InsertNode(N, IP); 8112 InsertNode(N); 8113 SDValue V(N, 0); 8114 NewSDValueDbgMsg(V, "Creating new node: ", this); 8115 return V; 8116 } 8117 8118 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8119 SDValue Val, SDValue Ptr, SDValue Mask, 8120 SDValue EVL, MachinePointerInfo PtrInfo, 8121 EVT SVT, Align Alignment, 8122 MachineMemOperand::Flags MMOFlags, 8123 const AAMDNodes &AAInfo, 8124 bool IsCompressing) { 8125 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8126 8127 MMOFlags |= MachineMemOperand::MOStore; 8128 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8129 8130 if (PtrInfo.V.isNull()) 8131 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8132 8133 MachineFunction &MF = getMachineFunction(); 8134 MachineMemOperand *MMO = MF.getMachineMemOperand( 8135 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 8136 Alignment, AAInfo); 8137 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO, 8138 IsCompressing); 8139 } 8140 8141 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8142 SDValue Val, SDValue Ptr, SDValue Mask, 8143 SDValue EVL, EVT SVT, 8144 MachineMemOperand *MMO, 8145 bool IsCompressing) { 8146 EVT VT = Val.getValueType(); 8147 8148 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8149 if (VT == SVT) 8150 return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask, 8151 EVL, VT, MMO, ISD::UNINDEXED, 8152 /*IsTruncating*/ false, IsCompressing); 8153 8154 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8155 "Should only be a truncating store, not extending!"); 8156 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8157 assert(VT.isVector() == SVT.isVector() && 8158 "Cannot use trunc store to convert to or from a vector!"); 8159 assert((!VT.isVector() || 8160 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8161 "Cannot use trunc store to change the number of vector elements!"); 8162 8163 SDVTList VTs = getVTList(MVT::Other); 8164 SDValue Undef = getUNDEF(Ptr.getValueType()); 8165 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 8166 FoldingSetNodeID ID; 8167 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8168 ID.AddInteger(SVT.getRawBits()); 8169 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8170 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8171 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8172 ID.AddInteger(MMO->getFlags()); 8173 void *IP = nullptr; 8174 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8175 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8176 return SDValue(E, 0); 8177 } 8178 auto *N = 8179 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8180 ISD::UNINDEXED, true, IsCompressing, SVT, MMO); 8181 createOperands(N, Ops); 8182 8183 CSEMap.InsertNode(N, IP); 8184 InsertNode(N); 8185 SDValue V(N, 0); 8186 NewSDValueDbgMsg(V, "Creating new node: ", this); 8187 return V; 8188 } 8189 8190 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, 8191 SDValue Base, SDValue Offset, 8192 ISD::MemIndexedMode AM) { 8193 auto *ST = cast<VPStoreSDNode>(OrigStore); 8194 assert(ST->getOffset().isUndef() && "Store is already an indexed store!"); 8195 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8196 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base, 8197 Offset, ST->getMask(), ST->getVectorLength()}; 8198 FoldingSetNodeID ID; 8199 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8200 ID.AddInteger(ST->getMemoryVT().getRawBits()); 8201 ID.AddInteger(ST->getRawSubclassData()); 8202 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 8203 ID.AddInteger(ST->getMemOperand()->getFlags()); 8204 void *IP = nullptr; 8205 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 8206 return SDValue(E, 0); 8207 8208 auto *N = newSDNode<VPStoreSDNode>( 8209 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(), 8210 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand()); 8211 createOperands(N, Ops); 8212 8213 CSEMap.InsertNode(N, IP); 8214 InsertNode(N); 8215 SDValue V(N, 0); 8216 NewSDValueDbgMsg(V, "Creating new node: ", this); 8217 return V; 8218 } 8219 8220 SDValue SelectionDAG::getStridedLoadVP( 8221 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8222 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8223 SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 8224 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8225 const MDNode *Ranges, bool IsExpanding) { 8226 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8227 8228 MMOFlags |= MachineMemOperand::MOLoad; 8229 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 8230 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 8231 // clients. 8232 if (PtrInfo.V.isNull()) 8233 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 8234 8235 uint64_t Size = MemoryLocation::UnknownSize; 8236 MachineFunction &MF = getMachineFunction(); 8237 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 8238 Alignment, AAInfo, Ranges); 8239 return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask, 8240 EVL, MemVT, MMO, IsExpanding); 8241 } 8242 8243 SDValue SelectionDAG::getStridedLoadVP( 8244 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8245 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8246 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) { 8247 bool Indexed = AM != ISD::UNINDEXED; 8248 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 8249 8250 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL}; 8251 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 8252 : getVTList(VT, MVT::Other); 8253 FoldingSetNodeID ID; 8254 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops); 8255 ID.AddInteger(VT.getRawBits()); 8256 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>( 8257 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 8258 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8259 8260 void *IP = nullptr; 8261 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8262 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO); 8263 return SDValue(E, 0); 8264 } 8265 8266 auto *N = 8267 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM, 8268 ExtType, IsExpanding, MemVT, MMO); 8269 createOperands(N, Ops); 8270 CSEMap.InsertNode(N, IP); 8271 InsertNode(N); 8272 SDValue V(N, 0); 8273 NewSDValueDbgMsg(V, "Creating new node: ", this); 8274 return V; 8275 } 8276 8277 SDValue SelectionDAG::getStridedLoadVP( 8278 EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride, 8279 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment, 8280 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8281 const MDNode *Ranges, bool IsExpanding) { 8282 SDValue Undef = getUNDEF(Ptr.getValueType()); 8283 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8284 Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment, 8285 MMOFlags, AAInfo, Ranges, IsExpanding); 8286 } 8287 8288 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain, 8289 SDValue Ptr, SDValue Stride, 8290 SDValue Mask, SDValue EVL, 8291 MachineMemOperand *MMO, 8292 bool IsExpanding) { 8293 SDValue Undef = getUNDEF(Ptr.getValueType()); 8294 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8295 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding); 8296 } 8297 8298 SDValue SelectionDAG::getExtStridedLoadVP( 8299 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8300 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, 8301 MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment, 8302 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8303 bool IsExpanding) { 8304 SDValue Undef = getUNDEF(Ptr.getValueType()); 8305 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8306 Stride, Mask, EVL, PtrInfo, MemVT, Alignment, 8307 MMOFlags, AAInfo, nullptr, IsExpanding); 8308 } 8309 8310 SDValue SelectionDAG::getExtStridedLoadVP( 8311 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8312 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, 8313 MachineMemOperand *MMO, bool IsExpanding) { 8314 SDValue Undef = getUNDEF(Ptr.getValueType()); 8315 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8316 Stride, Mask, EVL, MemVT, MMO, IsExpanding); 8317 } 8318 8319 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL, 8320 SDValue Base, SDValue Offset, 8321 ISD::MemIndexedMode AM) { 8322 auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad); 8323 assert(SLD->getOffset().isUndef() && 8324 "Strided load is already a indexed load!"); 8325 // Don't propagate the invariant or dereferenceable flags. 8326 auto MMOFlags = 8327 SLD->getMemOperand()->getFlags() & 8328 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8329 return getStridedLoadVP( 8330 AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(), 8331 Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(), 8332 SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags, 8333 SLD->getAAInfo(), nullptr, SLD->isExpandingLoad()); 8334 } 8335 8336 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL, 8337 SDValue Val, SDValue Ptr, 8338 SDValue Offset, SDValue Stride, 8339 SDValue Mask, SDValue EVL, EVT MemVT, 8340 MachineMemOperand *MMO, 8341 ISD::MemIndexedMode AM, 8342 bool IsTruncating, bool IsCompressing) { 8343 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8344 bool Indexed = AM != ISD::UNINDEXED; 8345 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 8346 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 8347 : getVTList(MVT::Other); 8348 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL}; 8349 FoldingSetNodeID ID; 8350 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8351 ID.AddInteger(MemVT.getRawBits()); 8352 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8353 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8354 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8355 void *IP = nullptr; 8356 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8357 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8358 return SDValue(E, 0); 8359 } 8360 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8361 VTs, AM, IsTruncating, 8362 IsCompressing, MemVT, MMO); 8363 createOperands(N, Ops); 8364 8365 CSEMap.InsertNode(N, IP); 8366 InsertNode(N); 8367 SDValue V(N, 0); 8368 NewSDValueDbgMsg(V, "Creating new node: ", this); 8369 return V; 8370 } 8371 8372 SDValue SelectionDAG::getTruncStridedStoreVP( 8373 SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride, 8374 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT, 8375 Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8376 bool IsCompressing) { 8377 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8378 8379 MMOFlags |= MachineMemOperand::MOStore; 8380 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8381 8382 if (PtrInfo.V.isNull()) 8383 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8384 8385 MachineFunction &MF = getMachineFunction(); 8386 MachineMemOperand *MMO = MF.getMachineMemOperand( 8387 PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo); 8388 return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT, 8389 MMO, IsCompressing); 8390 } 8391 8392 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL, 8393 SDValue Val, SDValue Ptr, 8394 SDValue Stride, SDValue Mask, 8395 SDValue EVL, EVT SVT, 8396 MachineMemOperand *MMO, 8397 bool IsCompressing) { 8398 EVT VT = Val.getValueType(); 8399 8400 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8401 if (VT == SVT) 8402 return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()), 8403 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED, 8404 /*IsTruncating*/ false, IsCompressing); 8405 8406 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8407 "Should only be a truncating store, not extending!"); 8408 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8409 assert(VT.isVector() == SVT.isVector() && 8410 "Cannot use trunc store to convert to or from a vector!"); 8411 assert((!VT.isVector() || 8412 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8413 "Cannot use trunc store to change the number of vector elements!"); 8414 8415 SDVTList VTs = getVTList(MVT::Other); 8416 SDValue Undef = getUNDEF(Ptr.getValueType()); 8417 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL}; 8418 FoldingSetNodeID ID; 8419 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8420 ID.AddInteger(SVT.getRawBits()); 8421 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8422 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8423 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8424 void *IP = nullptr; 8425 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8426 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8427 return SDValue(E, 0); 8428 } 8429 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8430 VTs, ISD::UNINDEXED, true, 8431 IsCompressing, SVT, MMO); 8432 createOperands(N, Ops); 8433 8434 CSEMap.InsertNode(N, IP); 8435 InsertNode(N); 8436 SDValue V(N, 0); 8437 NewSDValueDbgMsg(V, "Creating new node: ", this); 8438 return V; 8439 } 8440 8441 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore, 8442 const SDLoc &DL, SDValue Base, 8443 SDValue Offset, 8444 ISD::MemIndexedMode AM) { 8445 auto *SST = cast<VPStridedStoreSDNode>(OrigStore); 8446 assert(SST->getOffset().isUndef() && 8447 "Strided store is already an indexed store!"); 8448 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8449 SDValue Ops[] = { 8450 SST->getChain(), SST->getValue(), Base, Offset, SST->getStride(), 8451 SST->getMask(), SST->getVectorLength()}; 8452 FoldingSetNodeID ID; 8453 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8454 ID.AddInteger(SST->getMemoryVT().getRawBits()); 8455 ID.AddInteger(SST->getRawSubclassData()); 8456 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 8457 void *IP = nullptr; 8458 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8459 return SDValue(E, 0); 8460 8461 auto *N = newSDNode<VPStridedStoreSDNode>( 8462 DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(), 8463 SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand()); 8464 createOperands(N, Ops); 8465 8466 CSEMap.InsertNode(N, IP); 8467 InsertNode(N); 8468 SDValue V(N, 0); 8469 NewSDValueDbgMsg(V, "Creating new node: ", this); 8470 return V; 8471 } 8472 8473 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8474 ArrayRef<SDValue> Ops, MachineMemOperand *MMO, 8475 ISD::MemIndexType IndexType) { 8476 assert(Ops.size() == 6 && "Incompatible number of operands"); 8477 8478 FoldingSetNodeID ID; 8479 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops); 8480 ID.AddInteger(VT.getRawBits()); 8481 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>( 8482 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8483 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8484 ID.AddInteger(MMO->getFlags()); 8485 void *IP = nullptr; 8486 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8487 cast<VPGatherSDNode>(E)->refineAlignment(MMO); 8488 return SDValue(E, 0); 8489 } 8490 8491 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8492 VT, MMO, IndexType); 8493 createOperands(N, Ops); 8494 8495 assert(N->getMask().getValueType().getVectorElementCount() == 8496 N->getValueType(0).getVectorElementCount() && 8497 "Vector width mismatch between mask and data"); 8498 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8499 N->getValueType(0).getVectorElementCount().isScalable() && 8500 "Scalable flags of index and data do not match"); 8501 assert(ElementCount::isKnownGE( 8502 N->getIndex().getValueType().getVectorElementCount(), 8503 N->getValueType(0).getVectorElementCount()) && 8504 "Vector width mismatch between index and data"); 8505 assert(isa<ConstantSDNode>(N->getScale()) && 8506 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8507 "Scale should be a constant power of 2"); 8508 8509 CSEMap.InsertNode(N, IP); 8510 InsertNode(N); 8511 SDValue V(N, 0); 8512 NewSDValueDbgMsg(V, "Creating new node: ", this); 8513 return V; 8514 } 8515 8516 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8517 ArrayRef<SDValue> Ops, 8518 MachineMemOperand *MMO, 8519 ISD::MemIndexType IndexType) { 8520 assert(Ops.size() == 7 && "Incompatible number of operands"); 8521 8522 FoldingSetNodeID ID; 8523 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops); 8524 ID.AddInteger(VT.getRawBits()); 8525 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>( 8526 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8527 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8528 ID.AddInteger(MMO->getFlags()); 8529 void *IP = nullptr; 8530 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8531 cast<VPScatterSDNode>(E)->refineAlignment(MMO); 8532 return SDValue(E, 0); 8533 } 8534 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8535 VT, MMO, IndexType); 8536 createOperands(N, Ops); 8537 8538 assert(N->getMask().getValueType().getVectorElementCount() == 8539 N->getValue().getValueType().getVectorElementCount() && 8540 "Vector width mismatch between mask and data"); 8541 assert( 8542 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8543 N->getValue().getValueType().getVectorElementCount().isScalable() && 8544 "Scalable flags of index and data do not match"); 8545 assert(ElementCount::isKnownGE( 8546 N->getIndex().getValueType().getVectorElementCount(), 8547 N->getValue().getValueType().getVectorElementCount()) && 8548 "Vector width mismatch between index and data"); 8549 assert(isa<ConstantSDNode>(N->getScale()) && 8550 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8551 "Scale should be a constant power of 2"); 8552 8553 CSEMap.InsertNode(N, IP); 8554 InsertNode(N); 8555 SDValue V(N, 0); 8556 NewSDValueDbgMsg(V, "Creating new node: ", this); 8557 return V; 8558 } 8559 8560 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8561 SDValue Base, SDValue Offset, SDValue Mask, 8562 SDValue PassThru, EVT MemVT, 8563 MachineMemOperand *MMO, 8564 ISD::MemIndexedMode AM, 8565 ISD::LoadExtType ExtTy, bool isExpanding) { 8566 bool Indexed = AM != ISD::UNINDEXED; 8567 assert((Indexed || Offset.isUndef()) && 8568 "Unindexed masked load with an offset!"); 8569 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 8570 : getVTList(VT, MVT::Other); 8571 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 8572 FoldingSetNodeID ID; 8573 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 8574 ID.AddInteger(MemVT.getRawBits()); 8575 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 8576 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 8577 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8578 ID.AddInteger(MMO->getFlags()); 8579 void *IP = nullptr; 8580 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8581 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 8582 return SDValue(E, 0); 8583 } 8584 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8585 AM, ExtTy, isExpanding, MemVT, MMO); 8586 createOperands(N, Ops); 8587 8588 CSEMap.InsertNode(N, IP); 8589 InsertNode(N); 8590 SDValue V(N, 0); 8591 NewSDValueDbgMsg(V, "Creating new node: ", this); 8592 return V; 8593 } 8594 8595 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 8596 SDValue Base, SDValue Offset, 8597 ISD::MemIndexedMode AM) { 8598 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 8599 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 8600 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 8601 Offset, LD->getMask(), LD->getPassThru(), 8602 LD->getMemoryVT(), LD->getMemOperand(), AM, 8603 LD->getExtensionType(), LD->isExpandingLoad()); 8604 } 8605 8606 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 8607 SDValue Val, SDValue Base, SDValue Offset, 8608 SDValue Mask, EVT MemVT, 8609 MachineMemOperand *MMO, 8610 ISD::MemIndexedMode AM, bool IsTruncating, 8611 bool IsCompressing) { 8612 assert(Chain.getValueType() == MVT::Other && 8613 "Invalid chain type"); 8614 bool Indexed = AM != ISD::UNINDEXED; 8615 assert((Indexed || Offset.isUndef()) && 8616 "Unindexed masked store with an offset!"); 8617 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 8618 : getVTList(MVT::Other); 8619 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 8620 FoldingSetNodeID ID; 8621 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 8622 ID.AddInteger(MemVT.getRawBits()); 8623 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 8624 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8625 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8626 ID.AddInteger(MMO->getFlags()); 8627 void *IP = nullptr; 8628 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8629 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 8630 return SDValue(E, 0); 8631 } 8632 auto *N = 8633 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8634 IsTruncating, IsCompressing, MemVT, MMO); 8635 createOperands(N, Ops); 8636 8637 CSEMap.InsertNode(N, IP); 8638 InsertNode(N); 8639 SDValue V(N, 0); 8640 NewSDValueDbgMsg(V, "Creating new node: ", this); 8641 return V; 8642 } 8643 8644 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 8645 SDValue Base, SDValue Offset, 8646 ISD::MemIndexedMode AM) { 8647 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 8648 assert(ST->getOffset().isUndef() && 8649 "Masked store is already a indexed store!"); 8650 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 8651 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 8652 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 8653 } 8654 8655 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8656 ArrayRef<SDValue> Ops, 8657 MachineMemOperand *MMO, 8658 ISD::MemIndexType IndexType, 8659 ISD::LoadExtType ExtTy) { 8660 assert(Ops.size() == 6 && "Incompatible number of operands"); 8661 8662 FoldingSetNodeID ID; 8663 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 8664 ID.AddInteger(MemVT.getRawBits()); 8665 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 8666 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy)); 8667 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8668 ID.AddInteger(MMO->getFlags()); 8669 void *IP = nullptr; 8670 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8671 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 8672 return SDValue(E, 0); 8673 } 8674 8675 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8676 VTs, MemVT, MMO, IndexType, ExtTy); 8677 createOperands(N, Ops); 8678 8679 assert(N->getPassThru().getValueType() == N->getValueType(0) && 8680 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 8681 assert(N->getMask().getValueType().getVectorElementCount() == 8682 N->getValueType(0).getVectorElementCount() && 8683 "Vector width mismatch between mask and data"); 8684 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8685 N->getValueType(0).getVectorElementCount().isScalable() && 8686 "Scalable flags of index and data do not match"); 8687 assert(ElementCount::isKnownGE( 8688 N->getIndex().getValueType().getVectorElementCount(), 8689 N->getValueType(0).getVectorElementCount()) && 8690 "Vector width mismatch between index and data"); 8691 assert(isa<ConstantSDNode>(N->getScale()) && 8692 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8693 "Scale should be a constant power of 2"); 8694 8695 CSEMap.InsertNode(N, IP); 8696 InsertNode(N); 8697 SDValue V(N, 0); 8698 NewSDValueDbgMsg(V, "Creating new node: ", this); 8699 return V; 8700 } 8701 8702 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8703 ArrayRef<SDValue> Ops, 8704 MachineMemOperand *MMO, 8705 ISD::MemIndexType IndexType, 8706 bool IsTrunc) { 8707 assert(Ops.size() == 6 && "Incompatible number of operands"); 8708 8709 FoldingSetNodeID ID; 8710 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 8711 ID.AddInteger(MemVT.getRawBits()); 8712 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 8713 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc)); 8714 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8715 ID.AddInteger(MMO->getFlags()); 8716 void *IP = nullptr; 8717 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8718 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 8719 return SDValue(E, 0); 8720 } 8721 8722 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8723 VTs, MemVT, MMO, IndexType, IsTrunc); 8724 createOperands(N, Ops); 8725 8726 assert(N->getMask().getValueType().getVectorElementCount() == 8727 N->getValue().getValueType().getVectorElementCount() && 8728 "Vector width mismatch between mask and data"); 8729 assert( 8730 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8731 N->getValue().getValueType().getVectorElementCount().isScalable() && 8732 "Scalable flags of index and data do not match"); 8733 assert(ElementCount::isKnownGE( 8734 N->getIndex().getValueType().getVectorElementCount(), 8735 N->getValue().getValueType().getVectorElementCount()) && 8736 "Vector width mismatch between index and data"); 8737 assert(isa<ConstantSDNode>(N->getScale()) && 8738 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8739 "Scale should be a constant power of 2"); 8740 8741 CSEMap.InsertNode(N, IP); 8742 InsertNode(N); 8743 SDValue V(N, 0); 8744 NewSDValueDbgMsg(V, "Creating new node: ", this); 8745 return V; 8746 } 8747 8748 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 8749 // select undef, T, F --> T (if T is a constant), otherwise F 8750 // select, ?, undef, F --> F 8751 // select, ?, T, undef --> T 8752 if (Cond.isUndef()) 8753 return isConstantValueOfAnyType(T) ? T : F; 8754 if (T.isUndef()) 8755 return F; 8756 if (F.isUndef()) 8757 return T; 8758 8759 // select true, T, F --> T 8760 // select false, T, F --> F 8761 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 8762 return CondC->isZero() ? F : T; 8763 8764 // TODO: This should simplify VSELECT with constant condition using something 8765 // like this (but check boolean contents to be complete?): 8766 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 8767 // return T; 8768 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 8769 // return F; 8770 8771 // select ?, T, T --> T 8772 if (T == F) 8773 return T; 8774 8775 return SDValue(); 8776 } 8777 8778 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 8779 // shift undef, Y --> 0 (can always assume that the undef value is 0) 8780 if (X.isUndef()) 8781 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 8782 // shift X, undef --> undef (because it may shift by the bitwidth) 8783 if (Y.isUndef()) 8784 return getUNDEF(X.getValueType()); 8785 8786 // shift 0, Y --> 0 8787 // shift X, 0 --> X 8788 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 8789 return X; 8790 8791 // shift X, C >= bitwidth(X) --> undef 8792 // All vector elements must be too big (or undef) to avoid partial undefs. 8793 auto isShiftTooBig = [X](ConstantSDNode *Val) { 8794 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 8795 }; 8796 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 8797 return getUNDEF(X.getValueType()); 8798 8799 return SDValue(); 8800 } 8801 8802 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 8803 SDNodeFlags Flags) { 8804 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 8805 // (an undef operand can be chosen to be Nan/Inf), then the result of this 8806 // operation is poison. That result can be relaxed to undef. 8807 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 8808 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 8809 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 8810 (YC && YC->getValueAPF().isNaN()); 8811 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 8812 (YC && YC->getValueAPF().isInfinity()); 8813 8814 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 8815 return getUNDEF(X.getValueType()); 8816 8817 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 8818 return getUNDEF(X.getValueType()); 8819 8820 if (!YC) 8821 return SDValue(); 8822 8823 // X + -0.0 --> X 8824 if (Opcode == ISD::FADD) 8825 if (YC->getValueAPF().isNegZero()) 8826 return X; 8827 8828 // X - +0.0 --> X 8829 if (Opcode == ISD::FSUB) 8830 if (YC->getValueAPF().isPosZero()) 8831 return X; 8832 8833 // X * 1.0 --> X 8834 // X / 1.0 --> X 8835 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 8836 if (YC->getValueAPF().isExactlyValue(1.0)) 8837 return X; 8838 8839 // X * 0.0 --> 0.0 8840 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 8841 if (YC->getValueAPF().isZero()) 8842 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 8843 8844 return SDValue(); 8845 } 8846 8847 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 8848 SDValue Ptr, SDValue SV, unsigned Align) { 8849 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 8850 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 8851 } 8852 8853 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8854 ArrayRef<SDUse> Ops) { 8855 switch (Ops.size()) { 8856 case 0: return getNode(Opcode, DL, VT); 8857 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 8858 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 8859 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 8860 default: break; 8861 } 8862 8863 // Copy from an SDUse array into an SDValue array for use with 8864 // the regular getNode logic. 8865 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 8866 return getNode(Opcode, DL, VT, NewOps); 8867 } 8868 8869 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8870 ArrayRef<SDValue> Ops) { 8871 SDNodeFlags Flags; 8872 if (Inserter) 8873 Flags = Inserter->getFlags(); 8874 return getNode(Opcode, DL, VT, Ops, Flags); 8875 } 8876 8877 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8878 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8879 unsigned NumOps = Ops.size(); 8880 switch (NumOps) { 8881 case 0: return getNode(Opcode, DL, VT); 8882 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 8883 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 8884 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 8885 default: break; 8886 } 8887 8888 #ifndef NDEBUG 8889 for (auto &Op : Ops) 8890 assert(Op.getOpcode() != ISD::DELETED_NODE && 8891 "Operand is DELETED_NODE!"); 8892 #endif 8893 8894 switch (Opcode) { 8895 default: break; 8896 case ISD::BUILD_VECTOR: 8897 // Attempt to simplify BUILD_VECTOR. 8898 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 8899 return V; 8900 break; 8901 case ISD::CONCAT_VECTORS: 8902 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 8903 return V; 8904 break; 8905 case ISD::SELECT_CC: 8906 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 8907 assert(Ops[0].getValueType() == Ops[1].getValueType() && 8908 "LHS and RHS of condition must have same type!"); 8909 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8910 "True and False arms of SelectCC must have same type!"); 8911 assert(Ops[2].getValueType() == VT && 8912 "select_cc node must be of same type as true and false value!"); 8913 break; 8914 case ISD::BR_CC: 8915 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 8916 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8917 "LHS/RHS of comparison should match types!"); 8918 break; 8919 case ISD::VP_ADD: 8920 case ISD::VP_SUB: 8921 // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR 8922 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 8923 Opcode = ISD::VP_XOR; 8924 break; 8925 case ISD::VP_MUL: 8926 // If it is VP_MUL mask operation then turn it to VP_AND 8927 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 8928 Opcode = ISD::VP_AND; 8929 break; 8930 case ISD::VP_REDUCE_MUL: 8931 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND 8932 if (VT == MVT::i1) 8933 Opcode = ISD::VP_REDUCE_AND; 8934 break; 8935 case ISD::VP_REDUCE_ADD: 8936 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR 8937 if (VT == MVT::i1) 8938 Opcode = ISD::VP_REDUCE_XOR; 8939 break; 8940 case ISD::VP_REDUCE_SMAX: 8941 case ISD::VP_REDUCE_UMIN: 8942 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to 8943 // VP_REDUCE_AND. 8944 if (VT == MVT::i1) 8945 Opcode = ISD::VP_REDUCE_AND; 8946 break; 8947 case ISD::VP_REDUCE_SMIN: 8948 case ISD::VP_REDUCE_UMAX: 8949 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to 8950 // VP_REDUCE_OR. 8951 if (VT == MVT::i1) 8952 Opcode = ISD::VP_REDUCE_OR; 8953 break; 8954 } 8955 8956 // Memoize nodes. 8957 SDNode *N; 8958 SDVTList VTs = getVTList(VT); 8959 8960 if (VT != MVT::Glue) { 8961 FoldingSetNodeID ID; 8962 AddNodeIDNode(ID, Opcode, VTs, Ops); 8963 void *IP = nullptr; 8964 8965 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8966 return SDValue(E, 0); 8967 8968 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8969 createOperands(N, Ops); 8970 8971 CSEMap.InsertNode(N, IP); 8972 } else { 8973 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8974 createOperands(N, Ops); 8975 } 8976 8977 N->setFlags(Flags); 8978 InsertNode(N); 8979 SDValue V(N, 0); 8980 NewSDValueDbgMsg(V, "Creating new node: ", this); 8981 return V; 8982 } 8983 8984 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8985 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 8986 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 8987 } 8988 8989 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8990 ArrayRef<SDValue> Ops) { 8991 SDNodeFlags Flags; 8992 if (Inserter) 8993 Flags = Inserter->getFlags(); 8994 return getNode(Opcode, DL, VTList, Ops, Flags); 8995 } 8996 8997 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8998 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8999 if (VTList.NumVTs == 1) 9000 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags); 9001 9002 #ifndef NDEBUG 9003 for (auto &Op : Ops) 9004 assert(Op.getOpcode() != ISD::DELETED_NODE && 9005 "Operand is DELETED_NODE!"); 9006 #endif 9007 9008 switch (Opcode) { 9009 case ISD::STRICT_FP_EXTEND: 9010 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 9011 "Invalid STRICT_FP_EXTEND!"); 9012 assert(VTList.VTs[0].isFloatingPoint() && 9013 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 9014 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 9015 "STRICT_FP_EXTEND result type should be vector iff the operand " 9016 "type is vector!"); 9017 assert((!VTList.VTs[0].isVector() || 9018 VTList.VTs[0].getVectorNumElements() == 9019 Ops[1].getValueType().getVectorNumElements()) && 9020 "Vector element count mismatch!"); 9021 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 9022 "Invalid fpext node, dst <= src!"); 9023 break; 9024 case ISD::STRICT_FP_ROUND: 9025 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 9026 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 9027 "STRICT_FP_ROUND result type should be vector iff the operand " 9028 "type is vector!"); 9029 assert((!VTList.VTs[0].isVector() || 9030 VTList.VTs[0].getVectorNumElements() == 9031 Ops[1].getValueType().getVectorNumElements()) && 9032 "Vector element count mismatch!"); 9033 assert(VTList.VTs[0].isFloatingPoint() && 9034 Ops[1].getValueType().isFloatingPoint() && 9035 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 9036 isa<ConstantSDNode>(Ops[2]) && 9037 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 9038 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 9039 "Invalid STRICT_FP_ROUND!"); 9040 break; 9041 #if 0 9042 // FIXME: figure out how to safely handle things like 9043 // int foo(int x) { return 1 << (x & 255); } 9044 // int bar() { return foo(256); } 9045 case ISD::SRA_PARTS: 9046 case ISD::SRL_PARTS: 9047 case ISD::SHL_PARTS: 9048 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 9049 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 9050 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 9051 else if (N3.getOpcode() == ISD::AND) 9052 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 9053 // If the and is only masking out bits that cannot effect the shift, 9054 // eliminate the and. 9055 unsigned NumBits = VT.getScalarSizeInBits()*2; 9056 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 9057 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 9058 } 9059 break; 9060 #endif 9061 } 9062 9063 // Memoize the node unless it returns a flag. 9064 SDNode *N; 9065 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 9066 FoldingSetNodeID ID; 9067 AddNodeIDNode(ID, Opcode, VTList, Ops); 9068 void *IP = nullptr; 9069 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 9070 return SDValue(E, 0); 9071 9072 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 9073 createOperands(N, Ops); 9074 CSEMap.InsertNode(N, IP); 9075 } else { 9076 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 9077 createOperands(N, Ops); 9078 } 9079 9080 N->setFlags(Flags); 9081 InsertNode(N); 9082 SDValue V(N, 0); 9083 NewSDValueDbgMsg(V, "Creating new node: ", this); 9084 return V; 9085 } 9086 9087 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 9088 SDVTList VTList) { 9089 return getNode(Opcode, DL, VTList, None); 9090 } 9091 9092 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9093 SDValue N1) { 9094 SDValue Ops[] = { N1 }; 9095 return getNode(Opcode, DL, VTList, Ops); 9096 } 9097 9098 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9099 SDValue N1, SDValue N2) { 9100 SDValue Ops[] = { N1, N2 }; 9101 return getNode(Opcode, DL, VTList, Ops); 9102 } 9103 9104 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9105 SDValue N1, SDValue N2, SDValue N3) { 9106 SDValue Ops[] = { N1, N2, N3 }; 9107 return getNode(Opcode, DL, VTList, Ops); 9108 } 9109 9110 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9111 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 9112 SDValue Ops[] = { N1, N2, N3, N4 }; 9113 return getNode(Opcode, DL, VTList, Ops); 9114 } 9115 9116 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9117 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 9118 SDValue N5) { 9119 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 9120 return getNode(Opcode, DL, VTList, Ops); 9121 } 9122 9123 SDVTList SelectionDAG::getVTList(EVT VT) { 9124 return makeVTList(SDNode::getValueTypeList(VT), 1); 9125 } 9126 9127 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 9128 FoldingSetNodeID ID; 9129 ID.AddInteger(2U); 9130 ID.AddInteger(VT1.getRawBits()); 9131 ID.AddInteger(VT2.getRawBits()); 9132 9133 void *IP = nullptr; 9134 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9135 if (!Result) { 9136 EVT *Array = Allocator.Allocate<EVT>(2); 9137 Array[0] = VT1; 9138 Array[1] = VT2; 9139 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 9140 VTListMap.InsertNode(Result, IP); 9141 } 9142 return Result->getSDVTList(); 9143 } 9144 9145 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 9146 FoldingSetNodeID ID; 9147 ID.AddInteger(3U); 9148 ID.AddInteger(VT1.getRawBits()); 9149 ID.AddInteger(VT2.getRawBits()); 9150 ID.AddInteger(VT3.getRawBits()); 9151 9152 void *IP = nullptr; 9153 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9154 if (!Result) { 9155 EVT *Array = Allocator.Allocate<EVT>(3); 9156 Array[0] = VT1; 9157 Array[1] = VT2; 9158 Array[2] = VT3; 9159 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 9160 VTListMap.InsertNode(Result, IP); 9161 } 9162 return Result->getSDVTList(); 9163 } 9164 9165 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 9166 FoldingSetNodeID ID; 9167 ID.AddInteger(4U); 9168 ID.AddInteger(VT1.getRawBits()); 9169 ID.AddInteger(VT2.getRawBits()); 9170 ID.AddInteger(VT3.getRawBits()); 9171 ID.AddInteger(VT4.getRawBits()); 9172 9173 void *IP = nullptr; 9174 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9175 if (!Result) { 9176 EVT *Array = Allocator.Allocate<EVT>(4); 9177 Array[0] = VT1; 9178 Array[1] = VT2; 9179 Array[2] = VT3; 9180 Array[3] = VT4; 9181 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 9182 VTListMap.InsertNode(Result, IP); 9183 } 9184 return Result->getSDVTList(); 9185 } 9186 9187 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 9188 unsigned NumVTs = VTs.size(); 9189 FoldingSetNodeID ID; 9190 ID.AddInteger(NumVTs); 9191 for (unsigned index = 0; index < NumVTs; index++) { 9192 ID.AddInteger(VTs[index].getRawBits()); 9193 } 9194 9195 void *IP = nullptr; 9196 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9197 if (!Result) { 9198 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 9199 llvm::copy(VTs, Array); 9200 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 9201 VTListMap.InsertNode(Result, IP); 9202 } 9203 return Result->getSDVTList(); 9204 } 9205 9206 9207 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 9208 /// specified operands. If the resultant node already exists in the DAG, 9209 /// this does not modify the specified node, instead it returns the node that 9210 /// already exists. If the resultant node does not exist in the DAG, the 9211 /// input node is returned. As a degenerate case, if you specify the same 9212 /// input operands as the node already has, the input node is returned. 9213 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 9214 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 9215 9216 // Check to see if there is no change. 9217 if (Op == N->getOperand(0)) return N; 9218 9219 // See if the modified node already exists. 9220 void *InsertPos = nullptr; 9221 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 9222 return Existing; 9223 9224 // Nope it doesn't. Remove the node from its current place in the maps. 9225 if (InsertPos) 9226 if (!RemoveNodeFromCSEMaps(N)) 9227 InsertPos = nullptr; 9228 9229 // Now we update the operands. 9230 N->OperandList[0].set(Op); 9231 9232 updateDivergence(N); 9233 // If this gets put into a CSE map, add it. 9234 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9235 return N; 9236 } 9237 9238 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 9239 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 9240 9241 // Check to see if there is no change. 9242 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 9243 return N; // No operands changed, just return the input node. 9244 9245 // See if the modified node already exists. 9246 void *InsertPos = nullptr; 9247 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 9248 return Existing; 9249 9250 // Nope it doesn't. Remove the node from its current place in the maps. 9251 if (InsertPos) 9252 if (!RemoveNodeFromCSEMaps(N)) 9253 InsertPos = nullptr; 9254 9255 // Now we update the operands. 9256 if (N->OperandList[0] != Op1) 9257 N->OperandList[0].set(Op1); 9258 if (N->OperandList[1] != Op2) 9259 N->OperandList[1].set(Op2); 9260 9261 updateDivergence(N); 9262 // If this gets put into a CSE map, add it. 9263 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9264 return N; 9265 } 9266 9267 SDNode *SelectionDAG:: 9268 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 9269 SDValue Ops[] = { Op1, Op2, Op3 }; 9270 return UpdateNodeOperands(N, Ops); 9271 } 9272 9273 SDNode *SelectionDAG:: 9274 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9275 SDValue Op3, SDValue Op4) { 9276 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 9277 return UpdateNodeOperands(N, Ops); 9278 } 9279 9280 SDNode *SelectionDAG:: 9281 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9282 SDValue Op3, SDValue Op4, SDValue Op5) { 9283 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 9284 return UpdateNodeOperands(N, Ops); 9285 } 9286 9287 SDNode *SelectionDAG:: 9288 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 9289 unsigned NumOps = Ops.size(); 9290 assert(N->getNumOperands() == NumOps && 9291 "Update with wrong number of operands"); 9292 9293 // If no operands changed just return the input node. 9294 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 9295 return N; 9296 9297 // See if the modified node already exists. 9298 void *InsertPos = nullptr; 9299 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 9300 return Existing; 9301 9302 // Nope it doesn't. Remove the node from its current place in the maps. 9303 if (InsertPos) 9304 if (!RemoveNodeFromCSEMaps(N)) 9305 InsertPos = nullptr; 9306 9307 // Now we update the operands. 9308 for (unsigned i = 0; i != NumOps; ++i) 9309 if (N->OperandList[i] != Ops[i]) 9310 N->OperandList[i].set(Ops[i]); 9311 9312 updateDivergence(N); 9313 // If this gets put into a CSE map, add it. 9314 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9315 return N; 9316 } 9317 9318 /// DropOperands - Release the operands and set this node to have 9319 /// zero operands. 9320 void SDNode::DropOperands() { 9321 // Unlike the code in MorphNodeTo that does this, we don't need to 9322 // watch for dead nodes here. 9323 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 9324 SDUse &Use = *I++; 9325 Use.set(SDValue()); 9326 } 9327 } 9328 9329 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 9330 ArrayRef<MachineMemOperand *> NewMemRefs) { 9331 if (NewMemRefs.empty()) { 9332 N->clearMemRefs(); 9333 return; 9334 } 9335 9336 // Check if we can avoid allocating by storing a single reference directly. 9337 if (NewMemRefs.size() == 1) { 9338 N->MemRefs = NewMemRefs[0]; 9339 N->NumMemRefs = 1; 9340 return; 9341 } 9342 9343 MachineMemOperand **MemRefsBuffer = 9344 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 9345 llvm::copy(NewMemRefs, MemRefsBuffer); 9346 N->MemRefs = MemRefsBuffer; 9347 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 9348 } 9349 9350 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 9351 /// machine opcode. 9352 /// 9353 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9354 EVT VT) { 9355 SDVTList VTs = getVTList(VT); 9356 return SelectNodeTo(N, MachineOpc, VTs, None); 9357 } 9358 9359 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9360 EVT VT, SDValue Op1) { 9361 SDVTList VTs = getVTList(VT); 9362 SDValue Ops[] = { Op1 }; 9363 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9364 } 9365 9366 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9367 EVT VT, SDValue Op1, 9368 SDValue Op2) { 9369 SDVTList VTs = getVTList(VT); 9370 SDValue Ops[] = { Op1, Op2 }; 9371 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9372 } 9373 9374 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9375 EVT VT, SDValue Op1, 9376 SDValue Op2, SDValue Op3) { 9377 SDVTList VTs = getVTList(VT); 9378 SDValue Ops[] = { Op1, Op2, Op3 }; 9379 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9380 } 9381 9382 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9383 EVT VT, ArrayRef<SDValue> Ops) { 9384 SDVTList VTs = getVTList(VT); 9385 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9386 } 9387 9388 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9389 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 9390 SDVTList VTs = getVTList(VT1, VT2); 9391 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9392 } 9393 9394 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9395 EVT VT1, EVT VT2) { 9396 SDVTList VTs = getVTList(VT1, VT2); 9397 return SelectNodeTo(N, MachineOpc, VTs, None); 9398 } 9399 9400 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9401 EVT VT1, EVT VT2, EVT VT3, 9402 ArrayRef<SDValue> Ops) { 9403 SDVTList VTs = getVTList(VT1, VT2, VT3); 9404 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9405 } 9406 9407 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9408 EVT VT1, EVT VT2, 9409 SDValue Op1, SDValue Op2) { 9410 SDVTList VTs = getVTList(VT1, VT2); 9411 SDValue Ops[] = { Op1, Op2 }; 9412 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9413 } 9414 9415 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9416 SDVTList VTs,ArrayRef<SDValue> Ops) { 9417 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 9418 // Reset the NodeID to -1. 9419 New->setNodeId(-1); 9420 if (New != N) { 9421 ReplaceAllUsesWith(N, New); 9422 RemoveDeadNode(N); 9423 } 9424 return New; 9425 } 9426 9427 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 9428 /// the line number information on the merged node since it is not possible to 9429 /// preserve the information that operation is associated with multiple lines. 9430 /// This will make the debugger working better at -O0, were there is a higher 9431 /// probability having other instructions associated with that line. 9432 /// 9433 /// For IROrder, we keep the smaller of the two 9434 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 9435 DebugLoc NLoc = N->getDebugLoc(); 9436 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 9437 N->setDebugLoc(DebugLoc()); 9438 } 9439 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 9440 N->setIROrder(Order); 9441 return N; 9442 } 9443 9444 /// MorphNodeTo - This *mutates* the specified node to have the specified 9445 /// return type, opcode, and operands. 9446 /// 9447 /// Note that MorphNodeTo returns the resultant node. If there is already a 9448 /// node of the specified opcode and operands, it returns that node instead of 9449 /// the current one. Note that the SDLoc need not be the same. 9450 /// 9451 /// Using MorphNodeTo is faster than creating a new node and swapping it in 9452 /// with ReplaceAllUsesWith both because it often avoids allocating a new 9453 /// node, and because it doesn't require CSE recalculation for any of 9454 /// the node's users. 9455 /// 9456 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 9457 /// As a consequence it isn't appropriate to use from within the DAG combiner or 9458 /// the legalizer which maintain worklists that would need to be updated when 9459 /// deleting things. 9460 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 9461 SDVTList VTs, ArrayRef<SDValue> Ops) { 9462 // If an identical node already exists, use it. 9463 void *IP = nullptr; 9464 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 9465 FoldingSetNodeID ID; 9466 AddNodeIDNode(ID, Opc, VTs, Ops); 9467 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 9468 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 9469 } 9470 9471 if (!RemoveNodeFromCSEMaps(N)) 9472 IP = nullptr; 9473 9474 // Start the morphing. 9475 N->NodeType = Opc; 9476 N->ValueList = VTs.VTs; 9477 N->NumValues = VTs.NumVTs; 9478 9479 // Clear the operands list, updating used nodes to remove this from their 9480 // use list. Keep track of any operands that become dead as a result. 9481 SmallPtrSet<SDNode*, 16> DeadNodeSet; 9482 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 9483 SDUse &Use = *I++; 9484 SDNode *Used = Use.getNode(); 9485 Use.set(SDValue()); 9486 if (Used->use_empty()) 9487 DeadNodeSet.insert(Used); 9488 } 9489 9490 // For MachineNode, initialize the memory references information. 9491 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 9492 MN->clearMemRefs(); 9493 9494 // Swap for an appropriately sized array from the recycler. 9495 removeOperands(N); 9496 createOperands(N, Ops); 9497 9498 // Delete any nodes that are still dead after adding the uses for the 9499 // new operands. 9500 if (!DeadNodeSet.empty()) { 9501 SmallVector<SDNode *, 16> DeadNodes; 9502 for (SDNode *N : DeadNodeSet) 9503 if (N->use_empty()) 9504 DeadNodes.push_back(N); 9505 RemoveDeadNodes(DeadNodes); 9506 } 9507 9508 if (IP) 9509 CSEMap.InsertNode(N, IP); // Memoize the new node. 9510 return N; 9511 } 9512 9513 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 9514 unsigned OrigOpc = Node->getOpcode(); 9515 unsigned NewOpc; 9516 switch (OrigOpc) { 9517 default: 9518 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 9519 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9520 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 9521 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9522 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 9523 #include "llvm/IR/ConstrainedOps.def" 9524 } 9525 9526 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 9527 9528 // We're taking this node out of the chain, so we need to re-link things. 9529 SDValue InputChain = Node->getOperand(0); 9530 SDValue OutputChain = SDValue(Node, 1); 9531 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 9532 9533 SmallVector<SDValue, 3> Ops; 9534 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 9535 Ops.push_back(Node->getOperand(i)); 9536 9537 SDVTList VTs = getVTList(Node->getValueType(0)); 9538 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 9539 9540 // MorphNodeTo can operate in two ways: if an existing node with the 9541 // specified operands exists, it can just return it. Otherwise, it 9542 // updates the node in place to have the requested operands. 9543 if (Res == Node) { 9544 // If we updated the node in place, reset the node ID. To the isel, 9545 // this should be just like a newly allocated machine node. 9546 Res->setNodeId(-1); 9547 } else { 9548 ReplaceAllUsesWith(Node, Res); 9549 RemoveDeadNode(Node); 9550 } 9551 9552 return Res; 9553 } 9554 9555 /// getMachineNode - These are used for target selectors to create a new node 9556 /// with specified return type(s), MachineInstr opcode, and operands. 9557 /// 9558 /// Note that getMachineNode returns the resultant node. If there is already a 9559 /// node of the specified opcode and operands, it returns that node instead of 9560 /// the current one. 9561 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9562 EVT VT) { 9563 SDVTList VTs = getVTList(VT); 9564 return getMachineNode(Opcode, dl, VTs, None); 9565 } 9566 9567 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9568 EVT VT, SDValue Op1) { 9569 SDVTList VTs = getVTList(VT); 9570 SDValue Ops[] = { Op1 }; 9571 return getMachineNode(Opcode, dl, VTs, Ops); 9572 } 9573 9574 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9575 EVT VT, SDValue Op1, SDValue Op2) { 9576 SDVTList VTs = getVTList(VT); 9577 SDValue Ops[] = { Op1, Op2 }; 9578 return getMachineNode(Opcode, dl, VTs, Ops); 9579 } 9580 9581 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9582 EVT VT, SDValue Op1, SDValue Op2, 9583 SDValue Op3) { 9584 SDVTList VTs = getVTList(VT); 9585 SDValue Ops[] = { Op1, Op2, Op3 }; 9586 return getMachineNode(Opcode, dl, VTs, Ops); 9587 } 9588 9589 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9590 EVT VT, ArrayRef<SDValue> Ops) { 9591 SDVTList VTs = getVTList(VT); 9592 return getMachineNode(Opcode, dl, VTs, Ops); 9593 } 9594 9595 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9596 EVT VT1, EVT VT2, SDValue Op1, 9597 SDValue Op2) { 9598 SDVTList VTs = getVTList(VT1, VT2); 9599 SDValue Ops[] = { Op1, Op2 }; 9600 return getMachineNode(Opcode, dl, VTs, Ops); 9601 } 9602 9603 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9604 EVT VT1, EVT VT2, SDValue Op1, 9605 SDValue Op2, SDValue Op3) { 9606 SDVTList VTs = getVTList(VT1, VT2); 9607 SDValue Ops[] = { Op1, Op2, Op3 }; 9608 return getMachineNode(Opcode, dl, VTs, Ops); 9609 } 9610 9611 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9612 EVT VT1, EVT VT2, 9613 ArrayRef<SDValue> Ops) { 9614 SDVTList VTs = getVTList(VT1, VT2); 9615 return getMachineNode(Opcode, dl, VTs, Ops); 9616 } 9617 9618 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9619 EVT VT1, EVT VT2, EVT VT3, 9620 SDValue Op1, SDValue Op2) { 9621 SDVTList VTs = getVTList(VT1, VT2, VT3); 9622 SDValue Ops[] = { Op1, Op2 }; 9623 return getMachineNode(Opcode, dl, VTs, Ops); 9624 } 9625 9626 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9627 EVT VT1, EVT VT2, EVT VT3, 9628 SDValue Op1, SDValue Op2, 9629 SDValue Op3) { 9630 SDVTList VTs = getVTList(VT1, VT2, VT3); 9631 SDValue Ops[] = { Op1, Op2, Op3 }; 9632 return getMachineNode(Opcode, dl, VTs, Ops); 9633 } 9634 9635 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9636 EVT VT1, EVT VT2, EVT VT3, 9637 ArrayRef<SDValue> Ops) { 9638 SDVTList VTs = getVTList(VT1, VT2, VT3); 9639 return getMachineNode(Opcode, dl, VTs, Ops); 9640 } 9641 9642 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9643 ArrayRef<EVT> ResultTys, 9644 ArrayRef<SDValue> Ops) { 9645 SDVTList VTs = getVTList(ResultTys); 9646 return getMachineNode(Opcode, dl, VTs, Ops); 9647 } 9648 9649 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 9650 SDVTList VTs, 9651 ArrayRef<SDValue> Ops) { 9652 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 9653 MachineSDNode *N; 9654 void *IP = nullptr; 9655 9656 if (DoCSE) { 9657 FoldingSetNodeID ID; 9658 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 9659 IP = nullptr; 9660 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9661 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 9662 } 9663 } 9664 9665 // Allocate a new MachineSDNode. 9666 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9667 createOperands(N, Ops); 9668 9669 if (DoCSE) 9670 CSEMap.InsertNode(N, IP); 9671 9672 InsertNode(N); 9673 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 9674 return N; 9675 } 9676 9677 /// getTargetExtractSubreg - A convenience function for creating 9678 /// TargetOpcode::EXTRACT_SUBREG nodes. 9679 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9680 SDValue Operand) { 9681 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9682 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 9683 VT, Operand, SRIdxVal); 9684 return SDValue(Subreg, 0); 9685 } 9686 9687 /// getTargetInsertSubreg - A convenience function for creating 9688 /// TargetOpcode::INSERT_SUBREG nodes. 9689 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9690 SDValue Operand, SDValue Subreg) { 9691 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9692 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 9693 VT, Operand, Subreg, SRIdxVal); 9694 return SDValue(Result, 0); 9695 } 9696 9697 /// getNodeIfExists - Get the specified node if it's already available, or 9698 /// else return NULL. 9699 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9700 ArrayRef<SDValue> Ops) { 9701 SDNodeFlags Flags; 9702 if (Inserter) 9703 Flags = Inserter->getFlags(); 9704 return getNodeIfExists(Opcode, VTList, Ops, Flags); 9705 } 9706 9707 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9708 ArrayRef<SDValue> Ops, 9709 const SDNodeFlags Flags) { 9710 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9711 FoldingSetNodeID ID; 9712 AddNodeIDNode(ID, Opcode, VTList, Ops); 9713 void *IP = nullptr; 9714 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 9715 E->intersectFlagsWith(Flags); 9716 return E; 9717 } 9718 } 9719 return nullptr; 9720 } 9721 9722 /// doesNodeExist - Check if a node exists without modifying its flags. 9723 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 9724 ArrayRef<SDValue> Ops) { 9725 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9726 FoldingSetNodeID ID; 9727 AddNodeIDNode(ID, Opcode, VTList, Ops); 9728 void *IP = nullptr; 9729 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 9730 return true; 9731 } 9732 return false; 9733 } 9734 9735 /// getDbgValue - Creates a SDDbgValue node. 9736 /// 9737 /// SDNode 9738 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 9739 SDNode *N, unsigned R, bool IsIndirect, 9740 const DebugLoc &DL, unsigned O) { 9741 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9742 "Expected inlined-at fields to agree"); 9743 return new (DbgInfo->getAlloc()) 9744 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 9745 {}, IsIndirect, DL, O, 9746 /*IsVariadic=*/false); 9747 } 9748 9749 /// Constant 9750 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 9751 DIExpression *Expr, 9752 const Value *C, 9753 const DebugLoc &DL, unsigned O) { 9754 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9755 "Expected inlined-at fields to agree"); 9756 return new (DbgInfo->getAlloc()) 9757 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 9758 /*IsIndirect=*/false, DL, O, 9759 /*IsVariadic=*/false); 9760 } 9761 9762 /// FrameIndex 9763 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9764 DIExpression *Expr, unsigned FI, 9765 bool IsIndirect, 9766 const DebugLoc &DL, 9767 unsigned O) { 9768 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9769 "Expected inlined-at fields to agree"); 9770 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 9771 } 9772 9773 /// FrameIndex with dependencies 9774 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9775 DIExpression *Expr, unsigned FI, 9776 ArrayRef<SDNode *> Dependencies, 9777 bool IsIndirect, 9778 const DebugLoc &DL, 9779 unsigned O) { 9780 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9781 "Expected inlined-at fields to agree"); 9782 return new (DbgInfo->getAlloc()) 9783 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 9784 Dependencies, IsIndirect, DL, O, 9785 /*IsVariadic=*/false); 9786 } 9787 9788 /// VReg 9789 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 9790 unsigned VReg, bool IsIndirect, 9791 const DebugLoc &DL, unsigned O) { 9792 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9793 "Expected inlined-at fields to agree"); 9794 return new (DbgInfo->getAlloc()) 9795 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 9796 {}, IsIndirect, DL, O, 9797 /*IsVariadic=*/false); 9798 } 9799 9800 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 9801 ArrayRef<SDDbgOperand> Locs, 9802 ArrayRef<SDNode *> Dependencies, 9803 bool IsIndirect, const DebugLoc &DL, 9804 unsigned O, bool IsVariadic) { 9805 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9806 "Expected inlined-at fields to agree"); 9807 return new (DbgInfo->getAlloc()) 9808 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 9809 DL, O, IsVariadic); 9810 } 9811 9812 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 9813 unsigned OffsetInBits, unsigned SizeInBits, 9814 bool InvalidateDbg) { 9815 SDNode *FromNode = From.getNode(); 9816 SDNode *ToNode = To.getNode(); 9817 assert(FromNode && ToNode && "Can't modify dbg values"); 9818 9819 // PR35338 9820 // TODO: assert(From != To && "Redundant dbg value transfer"); 9821 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 9822 if (From == To || FromNode == ToNode) 9823 return; 9824 9825 if (!FromNode->getHasDebugValue()) 9826 return; 9827 9828 SDDbgOperand FromLocOp = 9829 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 9830 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 9831 9832 SmallVector<SDDbgValue *, 2> ClonedDVs; 9833 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 9834 if (Dbg->isInvalidated()) 9835 continue; 9836 9837 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 9838 9839 // Create a new location ops vector that is equal to the old vector, but 9840 // with each instance of FromLocOp replaced with ToLocOp. 9841 bool Changed = false; 9842 auto NewLocOps = Dbg->copyLocationOps(); 9843 std::replace_if( 9844 NewLocOps.begin(), NewLocOps.end(), 9845 [&Changed, FromLocOp](const SDDbgOperand &Op) { 9846 bool Match = Op == FromLocOp; 9847 Changed |= Match; 9848 return Match; 9849 }, 9850 ToLocOp); 9851 // Ignore this SDDbgValue if we didn't find a matching location. 9852 if (!Changed) 9853 continue; 9854 9855 DIVariable *Var = Dbg->getVariable(); 9856 auto *Expr = Dbg->getExpression(); 9857 // If a fragment is requested, update the expression. 9858 if (SizeInBits) { 9859 // When splitting a larger (e.g., sign-extended) value whose 9860 // lower bits are described with an SDDbgValue, do not attempt 9861 // to transfer the SDDbgValue to the upper bits. 9862 if (auto FI = Expr->getFragmentInfo()) 9863 if (OffsetInBits + SizeInBits > FI->SizeInBits) 9864 continue; 9865 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 9866 SizeInBits); 9867 if (!Fragment) 9868 continue; 9869 Expr = *Fragment; 9870 } 9871 9872 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 9873 // Clone the SDDbgValue and move it to To. 9874 SDDbgValue *Clone = getDbgValueList( 9875 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 9876 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 9877 Dbg->isVariadic()); 9878 ClonedDVs.push_back(Clone); 9879 9880 if (InvalidateDbg) { 9881 // Invalidate value and indicate the SDDbgValue should not be emitted. 9882 Dbg->setIsInvalidated(); 9883 Dbg->setIsEmitted(); 9884 } 9885 } 9886 9887 for (SDDbgValue *Dbg : ClonedDVs) { 9888 assert(is_contained(Dbg->getSDNodes(), ToNode) && 9889 "Transferred DbgValues should depend on the new SDNode"); 9890 AddDbgValue(Dbg, false); 9891 } 9892 } 9893 9894 void SelectionDAG::salvageDebugInfo(SDNode &N) { 9895 if (!N.getHasDebugValue()) 9896 return; 9897 9898 SmallVector<SDDbgValue *, 2> ClonedDVs; 9899 for (auto DV : GetDbgValues(&N)) { 9900 if (DV->isInvalidated()) 9901 continue; 9902 switch (N.getOpcode()) { 9903 default: 9904 break; 9905 case ISD::ADD: 9906 SDValue N0 = N.getOperand(0); 9907 SDValue N1 = N.getOperand(1); 9908 if (!isConstantIntBuildVectorOrConstantInt(N0) && 9909 isConstantIntBuildVectorOrConstantInt(N1)) { 9910 uint64_t Offset = N.getConstantOperandVal(1); 9911 9912 // Rewrite an ADD constant node into a DIExpression. Since we are 9913 // performing arithmetic to compute the variable's *value* in the 9914 // DIExpression, we need to mark the expression with a 9915 // DW_OP_stack_value. 9916 auto *DIExpr = DV->getExpression(); 9917 auto NewLocOps = DV->copyLocationOps(); 9918 bool Changed = false; 9919 for (size_t i = 0; i < NewLocOps.size(); ++i) { 9920 // We're not given a ResNo to compare against because the whole 9921 // node is going away. We know that any ISD::ADD only has one 9922 // result, so we can assume any node match is using the result. 9923 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 9924 NewLocOps[i].getSDNode() != &N) 9925 continue; 9926 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 9927 SmallVector<uint64_t, 3> ExprOps; 9928 DIExpression::appendOffset(ExprOps, Offset); 9929 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 9930 Changed = true; 9931 } 9932 (void)Changed; 9933 assert(Changed && "Salvage target doesn't use N"); 9934 9935 auto AdditionalDependencies = DV->getAdditionalDependencies(); 9936 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 9937 NewLocOps, AdditionalDependencies, 9938 DV->isIndirect(), DV->getDebugLoc(), 9939 DV->getOrder(), DV->isVariadic()); 9940 ClonedDVs.push_back(Clone); 9941 DV->setIsInvalidated(); 9942 DV->setIsEmitted(); 9943 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 9944 N0.getNode()->dumprFull(this); 9945 dbgs() << " into " << *DIExpr << '\n'); 9946 } 9947 } 9948 } 9949 9950 for (SDDbgValue *Dbg : ClonedDVs) { 9951 assert(!Dbg->getSDNodes().empty() && 9952 "Salvaged DbgValue should depend on a new SDNode"); 9953 AddDbgValue(Dbg, false); 9954 } 9955 } 9956 9957 /// Creates a SDDbgLabel node. 9958 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 9959 const DebugLoc &DL, unsigned O) { 9960 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 9961 "Expected inlined-at fields to agree"); 9962 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 9963 } 9964 9965 namespace { 9966 9967 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 9968 /// pointed to by a use iterator is deleted, increment the use iterator 9969 /// so that it doesn't dangle. 9970 /// 9971 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 9972 SDNode::use_iterator &UI; 9973 SDNode::use_iterator &UE; 9974 9975 void NodeDeleted(SDNode *N, SDNode *E) override { 9976 // Increment the iterator as needed. 9977 while (UI != UE && N == *UI) 9978 ++UI; 9979 } 9980 9981 public: 9982 RAUWUpdateListener(SelectionDAG &d, 9983 SDNode::use_iterator &ui, 9984 SDNode::use_iterator &ue) 9985 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 9986 }; 9987 9988 } // end anonymous namespace 9989 9990 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9991 /// This can cause recursive merging of nodes in the DAG. 9992 /// 9993 /// This version assumes From has a single result value. 9994 /// 9995 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 9996 SDNode *From = FromN.getNode(); 9997 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 9998 "Cannot replace with this method!"); 9999 assert(From != To.getNode() && "Cannot replace uses of with self"); 10000 10001 // Preserve Debug Values 10002 transferDbgValues(FromN, To); 10003 10004 // Iterate over all the existing uses of From. New uses will be added 10005 // to the beginning of the use list, which we avoid visiting. 10006 // This specifically avoids visiting uses of From that arise while the 10007 // replacement is happening, because any such uses would be the result 10008 // of CSE: If an existing node looks like From after one of its operands 10009 // is replaced by To, we don't want to replace of all its users with To 10010 // too. See PR3018 for more info. 10011 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 10012 RAUWUpdateListener Listener(*this, UI, UE); 10013 while (UI != UE) { 10014 SDNode *User = *UI; 10015 10016 // This node is about to morph, remove its old self from the CSE maps. 10017 RemoveNodeFromCSEMaps(User); 10018 10019 // A user can appear in a use list multiple times, and when this 10020 // happens the uses are usually next to each other in the list. 10021 // To help reduce the number of CSE recomputations, process all 10022 // the uses of this user that we can find this way. 10023 do { 10024 SDUse &Use = UI.getUse(); 10025 ++UI; 10026 Use.set(To); 10027 if (To->isDivergent() != From->isDivergent()) 10028 updateDivergence(User); 10029 } while (UI != UE && *UI == User); 10030 // Now that we have modified User, add it back to the CSE maps. If it 10031 // already exists there, recursively merge the results together. 10032 AddModifiedNodeToCSEMaps(User); 10033 } 10034 10035 // If we just RAUW'd the root, take note. 10036 if (FromN == getRoot()) 10037 setRoot(To); 10038 } 10039 10040 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 10041 /// This can cause recursive merging of nodes in the DAG. 10042 /// 10043 /// This version assumes that for each value of From, there is a 10044 /// corresponding value in To in the same position with the same type. 10045 /// 10046 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 10047 #ifndef NDEBUG 10048 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 10049 assert((!From->hasAnyUseOfValue(i) || 10050 From->getValueType(i) == To->getValueType(i)) && 10051 "Cannot use this version of ReplaceAllUsesWith!"); 10052 #endif 10053 10054 // Handle the trivial case. 10055 if (From == To) 10056 return; 10057 10058 // Preserve Debug Info. Only do this if there's a use. 10059 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 10060 if (From->hasAnyUseOfValue(i)) { 10061 assert((i < To->getNumValues()) && "Invalid To location"); 10062 transferDbgValues(SDValue(From, i), SDValue(To, i)); 10063 } 10064 10065 // Iterate over just the existing users of From. See the comments in 10066 // the ReplaceAllUsesWith above. 10067 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 10068 RAUWUpdateListener Listener(*this, UI, UE); 10069 while (UI != UE) { 10070 SDNode *User = *UI; 10071 10072 // This node is about to morph, remove its old self from the CSE maps. 10073 RemoveNodeFromCSEMaps(User); 10074 10075 // A user can appear in a use list multiple times, and when this 10076 // happens the uses are usually next to each other in the list. 10077 // To help reduce the number of CSE recomputations, process all 10078 // the uses of this user that we can find this way. 10079 do { 10080 SDUse &Use = UI.getUse(); 10081 ++UI; 10082 Use.setNode(To); 10083 if (To->isDivergent() != From->isDivergent()) 10084 updateDivergence(User); 10085 } while (UI != UE && *UI == User); 10086 10087 // Now that we have modified User, add it back to the CSE maps. If it 10088 // already exists there, recursively merge the results together. 10089 AddModifiedNodeToCSEMaps(User); 10090 } 10091 10092 // If we just RAUW'd the root, take note. 10093 if (From == getRoot().getNode()) 10094 setRoot(SDValue(To, getRoot().getResNo())); 10095 } 10096 10097 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 10098 /// This can cause recursive merging of nodes in the DAG. 10099 /// 10100 /// This version can replace From with any result values. To must match the 10101 /// number and types of values returned by From. 10102 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 10103 if (From->getNumValues() == 1) // Handle the simple case efficiently. 10104 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 10105 10106 // Preserve Debug Info. 10107 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 10108 transferDbgValues(SDValue(From, i), To[i]); 10109 10110 // Iterate over just the existing users of From. See the comments in 10111 // the ReplaceAllUsesWith above. 10112 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 10113 RAUWUpdateListener Listener(*this, UI, UE); 10114 while (UI != UE) { 10115 SDNode *User = *UI; 10116 10117 // This node is about to morph, remove its old self from the CSE maps. 10118 RemoveNodeFromCSEMaps(User); 10119 10120 // A user can appear in a use list multiple times, and when this happens the 10121 // uses are usually next to each other in the list. To help reduce the 10122 // number of CSE and divergence recomputations, process all the uses of this 10123 // user that we can find this way. 10124 bool To_IsDivergent = false; 10125 do { 10126 SDUse &Use = UI.getUse(); 10127 const SDValue &ToOp = To[Use.getResNo()]; 10128 ++UI; 10129 Use.set(ToOp); 10130 To_IsDivergent |= ToOp->isDivergent(); 10131 } while (UI != UE && *UI == User); 10132 10133 if (To_IsDivergent != From->isDivergent()) 10134 updateDivergence(User); 10135 10136 // Now that we have modified User, add it back to the CSE maps. If it 10137 // already exists there, recursively merge the results together. 10138 AddModifiedNodeToCSEMaps(User); 10139 } 10140 10141 // If we just RAUW'd the root, take note. 10142 if (From == getRoot().getNode()) 10143 setRoot(SDValue(To[getRoot().getResNo()])); 10144 } 10145 10146 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 10147 /// uses of other values produced by From.getNode() alone. The Deleted 10148 /// vector is handled the same way as for ReplaceAllUsesWith. 10149 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 10150 // Handle the really simple, really trivial case efficiently. 10151 if (From == To) return; 10152 10153 // Handle the simple, trivial, case efficiently. 10154 if (From.getNode()->getNumValues() == 1) { 10155 ReplaceAllUsesWith(From, To); 10156 return; 10157 } 10158 10159 // Preserve Debug Info. 10160 transferDbgValues(From, To); 10161 10162 // Iterate over just the existing users of From. See the comments in 10163 // the ReplaceAllUsesWith above. 10164 SDNode::use_iterator UI = From.getNode()->use_begin(), 10165 UE = From.getNode()->use_end(); 10166 RAUWUpdateListener Listener(*this, UI, UE); 10167 while (UI != UE) { 10168 SDNode *User = *UI; 10169 bool UserRemovedFromCSEMaps = false; 10170 10171 // A user can appear in a use list multiple times, and when this 10172 // happens the uses are usually next to each other in the list. 10173 // To help reduce the number of CSE recomputations, process all 10174 // the uses of this user that we can find this way. 10175 do { 10176 SDUse &Use = UI.getUse(); 10177 10178 // Skip uses of different values from the same node. 10179 if (Use.getResNo() != From.getResNo()) { 10180 ++UI; 10181 continue; 10182 } 10183 10184 // If this node hasn't been modified yet, it's still in the CSE maps, 10185 // so remove its old self from the CSE maps. 10186 if (!UserRemovedFromCSEMaps) { 10187 RemoveNodeFromCSEMaps(User); 10188 UserRemovedFromCSEMaps = true; 10189 } 10190 10191 ++UI; 10192 Use.set(To); 10193 if (To->isDivergent() != From->isDivergent()) 10194 updateDivergence(User); 10195 } while (UI != UE && *UI == User); 10196 // We are iterating over all uses of the From node, so if a use 10197 // doesn't use the specific value, no changes are made. 10198 if (!UserRemovedFromCSEMaps) 10199 continue; 10200 10201 // Now that we have modified User, add it back to the CSE maps. If it 10202 // already exists there, recursively merge the results together. 10203 AddModifiedNodeToCSEMaps(User); 10204 } 10205 10206 // If we just RAUW'd the root, take note. 10207 if (From == getRoot()) 10208 setRoot(To); 10209 } 10210 10211 namespace { 10212 10213 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 10214 /// to record information about a use. 10215 struct UseMemo { 10216 SDNode *User; 10217 unsigned Index; 10218 SDUse *Use; 10219 }; 10220 10221 /// operator< - Sort Memos by User. 10222 bool operator<(const UseMemo &L, const UseMemo &R) { 10223 return (intptr_t)L.User < (intptr_t)R.User; 10224 } 10225 10226 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node 10227 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that 10228 /// the node already has been taken care of recursively. 10229 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener { 10230 SmallVector<UseMemo, 4> &Uses; 10231 10232 void NodeDeleted(SDNode *N, SDNode *E) override { 10233 for (UseMemo &Memo : Uses) 10234 if (Memo.User == N) 10235 Memo.User = nullptr; 10236 } 10237 10238 public: 10239 RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses) 10240 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {} 10241 }; 10242 10243 } // end anonymous namespace 10244 10245 bool SelectionDAG::calculateDivergence(SDNode *N) { 10246 if (TLI->isSDNodeAlwaysUniform(N)) { 10247 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 10248 "Conflicting divergence information!"); 10249 return false; 10250 } 10251 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 10252 return true; 10253 for (auto &Op : N->ops()) { 10254 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 10255 return true; 10256 } 10257 return false; 10258 } 10259 10260 void SelectionDAG::updateDivergence(SDNode *N) { 10261 SmallVector<SDNode *, 16> Worklist(1, N); 10262 do { 10263 N = Worklist.pop_back_val(); 10264 bool IsDivergent = calculateDivergence(N); 10265 if (N->SDNodeBits.IsDivergent != IsDivergent) { 10266 N->SDNodeBits.IsDivergent = IsDivergent; 10267 llvm::append_range(Worklist, N->uses()); 10268 } 10269 } while (!Worklist.empty()); 10270 } 10271 10272 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 10273 DenseMap<SDNode *, unsigned> Degree; 10274 Order.reserve(AllNodes.size()); 10275 for (auto &N : allnodes()) { 10276 unsigned NOps = N.getNumOperands(); 10277 Degree[&N] = NOps; 10278 if (0 == NOps) 10279 Order.push_back(&N); 10280 } 10281 for (size_t I = 0; I != Order.size(); ++I) { 10282 SDNode *N = Order[I]; 10283 for (auto U : N->uses()) { 10284 unsigned &UnsortedOps = Degree[U]; 10285 if (0 == --UnsortedOps) 10286 Order.push_back(U); 10287 } 10288 } 10289 } 10290 10291 #ifndef NDEBUG 10292 void SelectionDAG::VerifyDAGDivergence() { 10293 std::vector<SDNode *> TopoOrder; 10294 CreateTopologicalOrder(TopoOrder); 10295 for (auto *N : TopoOrder) { 10296 assert(calculateDivergence(N) == N->isDivergent() && 10297 "Divergence bit inconsistency detected"); 10298 } 10299 } 10300 #endif 10301 10302 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 10303 /// uses of other values produced by From.getNode() alone. The same value 10304 /// may appear in both the From and To list. The Deleted vector is 10305 /// handled the same way as for ReplaceAllUsesWith. 10306 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 10307 const SDValue *To, 10308 unsigned Num){ 10309 // Handle the simple, trivial case efficiently. 10310 if (Num == 1) 10311 return ReplaceAllUsesOfValueWith(*From, *To); 10312 10313 transferDbgValues(*From, *To); 10314 10315 // Read up all the uses and make records of them. This helps 10316 // processing new uses that are introduced during the 10317 // replacement process. 10318 SmallVector<UseMemo, 4> Uses; 10319 for (unsigned i = 0; i != Num; ++i) { 10320 unsigned FromResNo = From[i].getResNo(); 10321 SDNode *FromNode = From[i].getNode(); 10322 for (SDNode::use_iterator UI = FromNode->use_begin(), 10323 E = FromNode->use_end(); UI != E; ++UI) { 10324 SDUse &Use = UI.getUse(); 10325 if (Use.getResNo() == FromResNo) { 10326 UseMemo Memo = { *UI, i, &Use }; 10327 Uses.push_back(Memo); 10328 } 10329 } 10330 } 10331 10332 // Sort the uses, so that all the uses from a given User are together. 10333 llvm::sort(Uses); 10334 RAUOVWUpdateListener Listener(*this, Uses); 10335 10336 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 10337 UseIndex != UseIndexEnd; ) { 10338 // We know that this user uses some value of From. If it is the right 10339 // value, update it. 10340 SDNode *User = Uses[UseIndex].User; 10341 // If the node has been deleted by recursive CSE updates when updating 10342 // another node, then just skip this entry. 10343 if (User == nullptr) { 10344 ++UseIndex; 10345 continue; 10346 } 10347 10348 // This node is about to morph, remove its old self from the CSE maps. 10349 RemoveNodeFromCSEMaps(User); 10350 10351 // The Uses array is sorted, so all the uses for a given User 10352 // are next to each other in the list. 10353 // To help reduce the number of CSE recomputations, process all 10354 // the uses of this user that we can find this way. 10355 do { 10356 unsigned i = Uses[UseIndex].Index; 10357 SDUse &Use = *Uses[UseIndex].Use; 10358 ++UseIndex; 10359 10360 Use.set(To[i]); 10361 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 10362 10363 // Now that we have modified User, add it back to the CSE maps. If it 10364 // already exists there, recursively merge the results together. 10365 AddModifiedNodeToCSEMaps(User); 10366 } 10367 } 10368 10369 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 10370 /// based on their topological order. It returns the maximum id and a vector 10371 /// of the SDNodes* in assigned order by reference. 10372 unsigned SelectionDAG::AssignTopologicalOrder() { 10373 unsigned DAGSize = 0; 10374 10375 // SortedPos tracks the progress of the algorithm. Nodes before it are 10376 // sorted, nodes after it are unsorted. When the algorithm completes 10377 // it is at the end of the list. 10378 allnodes_iterator SortedPos = allnodes_begin(); 10379 10380 // Visit all the nodes. Move nodes with no operands to the front of 10381 // the list immediately. Annotate nodes that do have operands with their 10382 // operand count. Before we do this, the Node Id fields of the nodes 10383 // may contain arbitrary values. After, the Node Id fields for nodes 10384 // before SortedPos will contain the topological sort index, and the 10385 // Node Id fields for nodes At SortedPos and after will contain the 10386 // count of outstanding operands. 10387 for (SDNode &N : llvm::make_early_inc_range(allnodes())) { 10388 checkForCycles(&N, this); 10389 unsigned Degree = N.getNumOperands(); 10390 if (Degree == 0) { 10391 // A node with no uses, add it to the result array immediately. 10392 N.setNodeId(DAGSize++); 10393 allnodes_iterator Q(&N); 10394 if (Q != SortedPos) 10395 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 10396 assert(SortedPos != AllNodes.end() && "Overran node list"); 10397 ++SortedPos; 10398 } else { 10399 // Temporarily use the Node Id as scratch space for the degree count. 10400 N.setNodeId(Degree); 10401 } 10402 } 10403 10404 // Visit all the nodes. As we iterate, move nodes into sorted order, 10405 // such that by the time the end is reached all nodes will be sorted. 10406 for (SDNode &Node : allnodes()) { 10407 SDNode *N = &Node; 10408 checkForCycles(N, this); 10409 // N is in sorted position, so all its uses have one less operand 10410 // that needs to be sorted. 10411 for (SDNode *P : N->uses()) { 10412 unsigned Degree = P->getNodeId(); 10413 assert(Degree != 0 && "Invalid node degree"); 10414 --Degree; 10415 if (Degree == 0) { 10416 // All of P's operands are sorted, so P may sorted now. 10417 P->setNodeId(DAGSize++); 10418 if (P->getIterator() != SortedPos) 10419 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 10420 assert(SortedPos != AllNodes.end() && "Overran node list"); 10421 ++SortedPos; 10422 } else { 10423 // Update P's outstanding operand count. 10424 P->setNodeId(Degree); 10425 } 10426 } 10427 if (Node.getIterator() == SortedPos) { 10428 #ifndef NDEBUG 10429 allnodes_iterator I(N); 10430 SDNode *S = &*++I; 10431 dbgs() << "Overran sorted position:\n"; 10432 S->dumprFull(this); dbgs() << "\n"; 10433 dbgs() << "Checking if this is due to cycles\n"; 10434 checkForCycles(this, true); 10435 #endif 10436 llvm_unreachable(nullptr); 10437 } 10438 } 10439 10440 assert(SortedPos == AllNodes.end() && 10441 "Topological sort incomplete!"); 10442 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 10443 "First node in topological sort is not the entry token!"); 10444 assert(AllNodes.front().getNodeId() == 0 && 10445 "First node in topological sort has non-zero id!"); 10446 assert(AllNodes.front().getNumOperands() == 0 && 10447 "First node in topological sort has operands!"); 10448 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 10449 "Last node in topologic sort has unexpected id!"); 10450 assert(AllNodes.back().use_empty() && 10451 "Last node in topologic sort has users!"); 10452 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 10453 return DAGSize; 10454 } 10455 10456 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 10457 /// value is produced by SD. 10458 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 10459 for (SDNode *SD : DB->getSDNodes()) { 10460 if (!SD) 10461 continue; 10462 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 10463 SD->setHasDebugValue(true); 10464 } 10465 DbgInfo->add(DB, isParameter); 10466 } 10467 10468 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 10469 10470 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 10471 SDValue NewMemOpChain) { 10472 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 10473 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 10474 // The new memory operation must have the same position as the old load in 10475 // terms of memory dependency. Create a TokenFactor for the old load and new 10476 // memory operation and update uses of the old load's output chain to use that 10477 // TokenFactor. 10478 if (OldChain == NewMemOpChain || OldChain.use_empty()) 10479 return NewMemOpChain; 10480 10481 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 10482 OldChain, NewMemOpChain); 10483 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 10484 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 10485 return TokenFactor; 10486 } 10487 10488 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 10489 SDValue NewMemOp) { 10490 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 10491 SDValue OldChain = SDValue(OldLoad, 1); 10492 SDValue NewMemOpChain = NewMemOp.getValue(1); 10493 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 10494 } 10495 10496 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 10497 Function **OutFunction) { 10498 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 10499 10500 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 10501 auto *Module = MF->getFunction().getParent(); 10502 auto *Function = Module->getFunction(Symbol); 10503 10504 if (OutFunction != nullptr) 10505 *OutFunction = Function; 10506 10507 if (Function != nullptr) { 10508 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 10509 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 10510 } 10511 10512 std::string ErrorStr; 10513 raw_string_ostream ErrorFormatter(ErrorStr); 10514 ErrorFormatter << "Undefined external symbol "; 10515 ErrorFormatter << '"' << Symbol << '"'; 10516 report_fatal_error(Twine(ErrorFormatter.str())); 10517 } 10518 10519 //===----------------------------------------------------------------------===// 10520 // SDNode Class 10521 //===----------------------------------------------------------------------===// 10522 10523 bool llvm::isNullConstant(SDValue V) { 10524 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10525 return Const != nullptr && Const->isZero(); 10526 } 10527 10528 bool llvm::isNullFPConstant(SDValue V) { 10529 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 10530 return Const != nullptr && Const->isZero() && !Const->isNegative(); 10531 } 10532 10533 bool llvm::isAllOnesConstant(SDValue V) { 10534 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10535 return Const != nullptr && Const->isAllOnes(); 10536 } 10537 10538 bool llvm::isOneConstant(SDValue V) { 10539 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10540 return Const != nullptr && Const->isOne(); 10541 } 10542 10543 bool llvm::isMinSignedConstant(SDValue V) { 10544 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10545 return Const != nullptr && Const->isMinSignedValue(); 10546 } 10547 10548 SDValue llvm::peekThroughBitcasts(SDValue V) { 10549 while (V.getOpcode() == ISD::BITCAST) 10550 V = V.getOperand(0); 10551 return V; 10552 } 10553 10554 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 10555 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 10556 V = V.getOperand(0); 10557 return V; 10558 } 10559 10560 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 10561 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 10562 V = V.getOperand(0); 10563 return V; 10564 } 10565 10566 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 10567 if (V.getOpcode() != ISD::XOR) 10568 return false; 10569 V = peekThroughBitcasts(V.getOperand(1)); 10570 unsigned NumBits = V.getScalarValueSizeInBits(); 10571 ConstantSDNode *C = 10572 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 10573 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 10574 } 10575 10576 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 10577 bool AllowTruncation) { 10578 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10579 return CN; 10580 10581 // SplatVectors can truncate their operands. Ignore that case here unless 10582 // AllowTruncation is set. 10583 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 10584 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 10585 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 10586 EVT CVT = CN->getValueType(0); 10587 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 10588 if (AllowTruncation || CVT == VecEltVT) 10589 return CN; 10590 } 10591 } 10592 10593 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10594 BitVector UndefElements; 10595 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 10596 10597 // BuildVectors can truncate their operands. Ignore that case here unless 10598 // AllowTruncation is set. 10599 if (CN && (UndefElements.none() || AllowUndefs)) { 10600 EVT CVT = CN->getValueType(0); 10601 EVT NSVT = N.getValueType().getScalarType(); 10602 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10603 if (AllowTruncation || (CVT == NSVT)) 10604 return CN; 10605 } 10606 } 10607 10608 return nullptr; 10609 } 10610 10611 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 10612 bool AllowUndefs, 10613 bool AllowTruncation) { 10614 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10615 return CN; 10616 10617 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10618 BitVector UndefElements; 10619 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 10620 10621 // BuildVectors can truncate their operands. Ignore that case here unless 10622 // AllowTruncation is set. 10623 if (CN && (UndefElements.none() || AllowUndefs)) { 10624 EVT CVT = CN->getValueType(0); 10625 EVT NSVT = N.getValueType().getScalarType(); 10626 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10627 if (AllowTruncation || (CVT == NSVT)) 10628 return CN; 10629 } 10630 } 10631 10632 return nullptr; 10633 } 10634 10635 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 10636 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10637 return CN; 10638 10639 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10640 BitVector UndefElements; 10641 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 10642 if (CN && (UndefElements.none() || AllowUndefs)) 10643 return CN; 10644 } 10645 10646 if (N.getOpcode() == ISD::SPLAT_VECTOR) 10647 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 10648 return CN; 10649 10650 return nullptr; 10651 } 10652 10653 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 10654 const APInt &DemandedElts, 10655 bool AllowUndefs) { 10656 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10657 return CN; 10658 10659 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10660 BitVector UndefElements; 10661 ConstantFPSDNode *CN = 10662 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 10663 if (CN && (UndefElements.none() || AllowUndefs)) 10664 return CN; 10665 } 10666 10667 return nullptr; 10668 } 10669 10670 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 10671 // TODO: may want to use peekThroughBitcast() here. 10672 ConstantSDNode *C = 10673 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true); 10674 return C && C->isZero(); 10675 } 10676 10677 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 10678 ConstantSDNode *C = 10679 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true); 10680 return C && C->isOne(); 10681 } 10682 10683 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 10684 N = peekThroughBitcasts(N); 10685 unsigned BitWidth = N.getScalarValueSizeInBits(); 10686 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10687 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth; 10688 } 10689 10690 HandleSDNode::~HandleSDNode() { 10691 DropOperands(); 10692 } 10693 10694 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 10695 const DebugLoc &DL, 10696 const GlobalValue *GA, EVT VT, 10697 int64_t o, unsigned TF) 10698 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 10699 TheGlobal = GA; 10700 } 10701 10702 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 10703 EVT VT, unsigned SrcAS, 10704 unsigned DestAS) 10705 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 10706 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 10707 10708 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 10709 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 10710 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 10711 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 10712 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 10713 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 10714 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 10715 10716 // We check here that the size of the memory operand fits within the size of 10717 // the MMO. This is because the MMO might indicate only a possible address 10718 // range instead of specifying the affected memory addresses precisely. 10719 // TODO: Make MachineMemOperands aware of scalable vectors. 10720 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 10721 "Size mismatch!"); 10722 } 10723 10724 /// Profile - Gather unique data for the node. 10725 /// 10726 void SDNode::Profile(FoldingSetNodeID &ID) const { 10727 AddNodeIDNode(ID, this); 10728 } 10729 10730 namespace { 10731 10732 struct EVTArray { 10733 std::vector<EVT> VTs; 10734 10735 EVTArray() { 10736 VTs.reserve(MVT::VALUETYPE_SIZE); 10737 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i) 10738 VTs.push_back(MVT((MVT::SimpleValueType)i)); 10739 } 10740 }; 10741 10742 } // end anonymous namespace 10743 10744 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 10745 static ManagedStatic<EVTArray> SimpleVTArray; 10746 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 10747 10748 /// getValueTypeList - Return a pointer to the specified value type. 10749 /// 10750 const EVT *SDNode::getValueTypeList(EVT VT) { 10751 if (VT.isExtended()) { 10752 sys::SmartScopedLock<true> Lock(*VTMutex); 10753 return &(*EVTs->insert(VT).first); 10754 } 10755 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!"); 10756 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 10757 } 10758 10759 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 10760 /// indicated value. This method ignores uses of other values defined by this 10761 /// operation. 10762 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 10763 assert(Value < getNumValues() && "Bad value!"); 10764 10765 // TODO: Only iterate over uses of a given value of the node 10766 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 10767 if (UI.getUse().getResNo() == Value) { 10768 if (NUses == 0) 10769 return false; 10770 --NUses; 10771 } 10772 } 10773 10774 // Found exactly the right number of uses? 10775 return NUses == 0; 10776 } 10777 10778 /// hasAnyUseOfValue - Return true if there are any use of the indicated 10779 /// value. This method ignores uses of other values defined by this operation. 10780 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 10781 assert(Value < getNumValues() && "Bad value!"); 10782 10783 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 10784 if (UI.getUse().getResNo() == Value) 10785 return true; 10786 10787 return false; 10788 } 10789 10790 /// isOnlyUserOf - Return true if this node is the only use of N. 10791 bool SDNode::isOnlyUserOf(const SDNode *N) const { 10792 bool Seen = false; 10793 for (const SDNode *User : N->uses()) { 10794 if (User == this) 10795 Seen = true; 10796 else 10797 return false; 10798 } 10799 10800 return Seen; 10801 } 10802 10803 /// Return true if the only users of N are contained in Nodes. 10804 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 10805 bool Seen = false; 10806 for (const SDNode *User : N->uses()) { 10807 if (llvm::is_contained(Nodes, User)) 10808 Seen = true; 10809 else 10810 return false; 10811 } 10812 10813 return Seen; 10814 } 10815 10816 /// isOperand - Return true if this node is an operand of N. 10817 bool SDValue::isOperandOf(const SDNode *N) const { 10818 return is_contained(N->op_values(), *this); 10819 } 10820 10821 bool SDNode::isOperandOf(const SDNode *N) const { 10822 return any_of(N->op_values(), 10823 [this](SDValue Op) { return this == Op.getNode(); }); 10824 } 10825 10826 /// reachesChainWithoutSideEffects - Return true if this operand (which must 10827 /// be a chain) reaches the specified operand without crossing any 10828 /// side-effecting instructions on any chain path. In practice, this looks 10829 /// through token factors and non-volatile loads. In order to remain efficient, 10830 /// this only looks a couple of nodes in, it does not do an exhaustive search. 10831 /// 10832 /// Note that we only need to examine chains when we're searching for 10833 /// side-effects; SelectionDAG requires that all side-effects are represented 10834 /// by chains, even if another operand would force a specific ordering. This 10835 /// constraint is necessary to allow transformations like splitting loads. 10836 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 10837 unsigned Depth) const { 10838 if (*this == Dest) return true; 10839 10840 // Don't search too deeply, we just want to be able to see through 10841 // TokenFactor's etc. 10842 if (Depth == 0) return false; 10843 10844 // If this is a token factor, all inputs to the TF happen in parallel. 10845 if (getOpcode() == ISD::TokenFactor) { 10846 // First, try a shallow search. 10847 if (is_contained((*this)->ops(), Dest)) { 10848 // We found the chain we want as an operand of this TokenFactor. 10849 // Essentially, we reach the chain without side-effects if we could 10850 // serialize the TokenFactor into a simple chain of operations with 10851 // Dest as the last operation. This is automatically true if the 10852 // chain has one use: there are no other ordering constraints. 10853 // If the chain has more than one use, we give up: some other 10854 // use of Dest might force a side-effect between Dest and the current 10855 // node. 10856 if (Dest.hasOneUse()) 10857 return true; 10858 } 10859 // Next, try a deep search: check whether every operand of the TokenFactor 10860 // reaches Dest. 10861 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 10862 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 10863 }); 10864 } 10865 10866 // Loads don't have side effects, look through them. 10867 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 10868 if (Ld->isUnordered()) 10869 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 10870 } 10871 return false; 10872 } 10873 10874 bool SDNode::hasPredecessor(const SDNode *N) const { 10875 SmallPtrSet<const SDNode *, 32> Visited; 10876 SmallVector<const SDNode *, 16> Worklist; 10877 Worklist.push_back(this); 10878 return hasPredecessorHelper(N, Visited, Worklist); 10879 } 10880 10881 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 10882 this->Flags.intersectWith(Flags); 10883 } 10884 10885 SDValue 10886 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 10887 ArrayRef<ISD::NodeType> CandidateBinOps, 10888 bool AllowPartials) { 10889 // The pattern must end in an extract from index 0. 10890 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10891 !isNullConstant(Extract->getOperand(1))) 10892 return SDValue(); 10893 10894 // Match against one of the candidate binary ops. 10895 SDValue Op = Extract->getOperand(0); 10896 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 10897 return Op.getOpcode() == unsigned(BinOp); 10898 })) 10899 return SDValue(); 10900 10901 // Floating-point reductions may require relaxed constraints on the final step 10902 // of the reduction because they may reorder intermediate operations. 10903 unsigned CandidateBinOp = Op.getOpcode(); 10904 if (Op.getValueType().isFloatingPoint()) { 10905 SDNodeFlags Flags = Op->getFlags(); 10906 switch (CandidateBinOp) { 10907 case ISD::FADD: 10908 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 10909 return SDValue(); 10910 break; 10911 default: 10912 llvm_unreachable("Unhandled FP opcode for binop reduction"); 10913 } 10914 } 10915 10916 // Matching failed - attempt to see if we did enough stages that a partial 10917 // reduction from a subvector is possible. 10918 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 10919 if (!AllowPartials || !Op) 10920 return SDValue(); 10921 EVT OpVT = Op.getValueType(); 10922 EVT OpSVT = OpVT.getScalarType(); 10923 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 10924 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 10925 return SDValue(); 10926 BinOp = (ISD::NodeType)CandidateBinOp; 10927 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 10928 getVectorIdxConstant(0, SDLoc(Op))); 10929 }; 10930 10931 // At each stage, we're looking for something that looks like: 10932 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 10933 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 10934 // i32 undef, i32 undef, i32 undef, i32 undef> 10935 // %a = binop <8 x i32> %op, %s 10936 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 10937 // we expect something like: 10938 // <4,5,6,7,u,u,u,u> 10939 // <2,3,u,u,u,u,u,u> 10940 // <1,u,u,u,u,u,u,u> 10941 // While a partial reduction match would be: 10942 // <2,3,u,u,u,u,u,u> 10943 // <1,u,u,u,u,u,u,u> 10944 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 10945 SDValue PrevOp; 10946 for (unsigned i = 0; i < Stages; ++i) { 10947 unsigned MaskEnd = (1 << i); 10948 10949 if (Op.getOpcode() != CandidateBinOp) 10950 return PartialReduction(PrevOp, MaskEnd); 10951 10952 SDValue Op0 = Op.getOperand(0); 10953 SDValue Op1 = Op.getOperand(1); 10954 10955 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 10956 if (Shuffle) { 10957 Op = Op1; 10958 } else { 10959 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 10960 Op = Op0; 10961 } 10962 10963 // The first operand of the shuffle should be the same as the other operand 10964 // of the binop. 10965 if (!Shuffle || Shuffle->getOperand(0) != Op) 10966 return PartialReduction(PrevOp, MaskEnd); 10967 10968 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 10969 for (int Index = 0; Index < (int)MaskEnd; ++Index) 10970 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 10971 return PartialReduction(PrevOp, MaskEnd); 10972 10973 PrevOp = Op; 10974 } 10975 10976 // Handle subvector reductions, which tend to appear after the shuffle 10977 // reduction stages. 10978 while (Op.getOpcode() == CandidateBinOp) { 10979 unsigned NumElts = Op.getValueType().getVectorNumElements(); 10980 SDValue Op0 = Op.getOperand(0); 10981 SDValue Op1 = Op.getOperand(1); 10982 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10983 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10984 Op0.getOperand(0) != Op1.getOperand(0)) 10985 break; 10986 SDValue Src = Op0.getOperand(0); 10987 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 10988 if (NumSrcElts != (2 * NumElts)) 10989 break; 10990 if (!(Op0.getConstantOperandAPInt(1) == 0 && 10991 Op1.getConstantOperandAPInt(1) == NumElts) && 10992 !(Op1.getConstantOperandAPInt(1) == 0 && 10993 Op0.getConstantOperandAPInt(1) == NumElts)) 10994 break; 10995 Op = Src; 10996 } 10997 10998 BinOp = (ISD::NodeType)CandidateBinOp; 10999 return Op; 11000 } 11001 11002 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 11003 assert(N->getNumValues() == 1 && 11004 "Can't unroll a vector with multiple results!"); 11005 11006 EVT VT = N->getValueType(0); 11007 unsigned NE = VT.getVectorNumElements(); 11008 EVT EltVT = VT.getVectorElementType(); 11009 SDLoc dl(N); 11010 11011 SmallVector<SDValue, 8> Scalars; 11012 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 11013 11014 // If ResNE is 0, fully unroll the vector op. 11015 if (ResNE == 0) 11016 ResNE = NE; 11017 else if (NE > ResNE) 11018 NE = ResNE; 11019 11020 unsigned i; 11021 for (i= 0; i != NE; ++i) { 11022 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 11023 SDValue Operand = N->getOperand(j); 11024 EVT OperandVT = Operand.getValueType(); 11025 if (OperandVT.isVector()) { 11026 // A vector operand; extract a single element. 11027 EVT OperandEltVT = OperandVT.getVectorElementType(); 11028 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 11029 Operand, getVectorIdxConstant(i, dl)); 11030 } else { 11031 // A scalar operand; just use it as is. 11032 Operands[j] = Operand; 11033 } 11034 } 11035 11036 switch (N->getOpcode()) { 11037 default: { 11038 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 11039 N->getFlags())); 11040 break; 11041 } 11042 case ISD::VSELECT: 11043 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 11044 break; 11045 case ISD::SHL: 11046 case ISD::SRA: 11047 case ISD::SRL: 11048 case ISD::ROTL: 11049 case ISD::ROTR: 11050 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 11051 getShiftAmountOperand(Operands[0].getValueType(), 11052 Operands[1]))); 11053 break; 11054 case ISD::SIGN_EXTEND_INREG: { 11055 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 11056 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 11057 Operands[0], 11058 getValueType(ExtVT))); 11059 } 11060 } 11061 } 11062 11063 for (; i < ResNE; ++i) 11064 Scalars.push_back(getUNDEF(EltVT)); 11065 11066 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 11067 return getBuildVector(VecVT, dl, Scalars); 11068 } 11069 11070 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 11071 SDNode *N, unsigned ResNE) { 11072 unsigned Opcode = N->getOpcode(); 11073 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 11074 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 11075 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 11076 "Expected an overflow opcode"); 11077 11078 EVT ResVT = N->getValueType(0); 11079 EVT OvVT = N->getValueType(1); 11080 EVT ResEltVT = ResVT.getVectorElementType(); 11081 EVT OvEltVT = OvVT.getVectorElementType(); 11082 SDLoc dl(N); 11083 11084 // If ResNE is 0, fully unroll the vector op. 11085 unsigned NE = ResVT.getVectorNumElements(); 11086 if (ResNE == 0) 11087 ResNE = NE; 11088 else if (NE > ResNE) 11089 NE = ResNE; 11090 11091 SmallVector<SDValue, 8> LHSScalars; 11092 SmallVector<SDValue, 8> RHSScalars; 11093 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 11094 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 11095 11096 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 11097 SDVTList VTs = getVTList(ResEltVT, SVT); 11098 SmallVector<SDValue, 8> ResScalars; 11099 SmallVector<SDValue, 8> OvScalars; 11100 for (unsigned i = 0; i < NE; ++i) { 11101 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 11102 SDValue Ov = 11103 getSelect(dl, OvEltVT, Res.getValue(1), 11104 getBoolConstant(true, dl, OvEltVT, ResVT), 11105 getConstant(0, dl, OvEltVT)); 11106 11107 ResScalars.push_back(Res); 11108 OvScalars.push_back(Ov); 11109 } 11110 11111 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 11112 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 11113 11114 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 11115 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 11116 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 11117 getBuildVector(NewOvVT, dl, OvScalars)); 11118 } 11119 11120 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 11121 LoadSDNode *Base, 11122 unsigned Bytes, 11123 int Dist) const { 11124 if (LD->isVolatile() || Base->isVolatile()) 11125 return false; 11126 // TODO: probably too restrictive for atomics, revisit 11127 if (!LD->isSimple()) 11128 return false; 11129 if (LD->isIndexed() || Base->isIndexed()) 11130 return false; 11131 if (LD->getChain() != Base->getChain()) 11132 return false; 11133 EVT VT = LD->getValueType(0); 11134 if (VT.getSizeInBits() / 8 != Bytes) 11135 return false; 11136 11137 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 11138 auto LocDecomp = BaseIndexOffset::match(LD, *this); 11139 11140 int64_t Offset = 0; 11141 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 11142 return (Dist * Bytes == Offset); 11143 return false; 11144 } 11145 11146 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 11147 /// if it cannot be inferred. 11148 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 11149 // If this is a GlobalAddress + cst, return the alignment. 11150 const GlobalValue *GV = nullptr; 11151 int64_t GVOffset = 0; 11152 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 11153 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 11154 KnownBits Known(PtrWidth); 11155 llvm::computeKnownBits(GV, Known, getDataLayout()); 11156 unsigned AlignBits = Known.countMinTrailingZeros(); 11157 if (AlignBits) 11158 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 11159 } 11160 11161 // If this is a direct reference to a stack slot, use information about the 11162 // stack slot's alignment. 11163 int FrameIdx = INT_MIN; 11164 int64_t FrameOffset = 0; 11165 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 11166 FrameIdx = FI->getIndex(); 11167 } else if (isBaseWithConstantOffset(Ptr) && 11168 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 11169 // Handle FI+Cst 11170 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 11171 FrameOffset = Ptr.getConstantOperandVal(1); 11172 } 11173 11174 if (FrameIdx != INT_MIN) { 11175 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 11176 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 11177 } 11178 11179 return None; 11180 } 11181 11182 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 11183 /// which is split (or expanded) into two not necessarily identical pieces. 11184 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 11185 // Currently all types are split in half. 11186 EVT LoVT, HiVT; 11187 if (!VT.isVector()) 11188 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 11189 else 11190 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 11191 11192 return std::make_pair(LoVT, HiVT); 11193 } 11194 11195 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 11196 /// type, dependent on an enveloping VT that has been split into two identical 11197 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 11198 std::pair<EVT, EVT> 11199 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 11200 bool *HiIsEmpty) const { 11201 EVT EltTp = VT.getVectorElementType(); 11202 // Examples: 11203 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 11204 // custom VL=9 with enveloping VL=8/8 yields 8/1 11205 // custom VL=10 with enveloping VL=8/8 yields 8/2 11206 // etc. 11207 ElementCount VTNumElts = VT.getVectorElementCount(); 11208 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 11209 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 11210 "Mixing fixed width and scalable vectors when enveloping a type"); 11211 EVT LoVT, HiVT; 11212 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 11213 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11214 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 11215 *HiIsEmpty = false; 11216 } else { 11217 // Flag that hi type has zero storage size, but return split envelop type 11218 // (this would be easier if vector types with zero elements were allowed). 11219 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 11220 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11221 *HiIsEmpty = true; 11222 } 11223 return std::make_pair(LoVT, HiVT); 11224 } 11225 11226 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 11227 /// low/high part. 11228 std::pair<SDValue, SDValue> 11229 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 11230 const EVT &HiVT) { 11231 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 11232 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 11233 "Splitting vector with an invalid mixture of fixed and scalable " 11234 "vector types"); 11235 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 11236 N.getValueType().getVectorMinNumElements() && 11237 "More vector elements requested than available!"); 11238 SDValue Lo, Hi; 11239 Lo = 11240 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 11241 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 11242 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 11243 // IDX with the runtime scaling factor of the result vector type. For 11244 // fixed-width result vectors, that runtime scaling factor is 1. 11245 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 11246 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 11247 return std::make_pair(Lo, Hi); 11248 } 11249 11250 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT, 11251 const SDLoc &DL) { 11252 // Split the vector length parameter. 11253 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts). 11254 EVT VT = N.getValueType(); 11255 assert(VecVT.getVectorElementCount().isKnownEven() && 11256 "Expecting the mask to be an evenly-sized vector"); 11257 unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2; 11258 SDValue HalfNumElts = 11259 VecVT.isFixedLengthVector() 11260 ? getConstant(HalfMinNumElts, DL, VT) 11261 : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts)); 11262 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts); 11263 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts); 11264 return std::make_pair(Lo, Hi); 11265 } 11266 11267 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 11268 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 11269 EVT VT = N.getValueType(); 11270 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 11271 NextPowerOf2(VT.getVectorNumElements())); 11272 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 11273 getVectorIdxConstant(0, DL)); 11274 } 11275 11276 void SelectionDAG::ExtractVectorElements(SDValue Op, 11277 SmallVectorImpl<SDValue> &Args, 11278 unsigned Start, unsigned Count, 11279 EVT EltVT) { 11280 EVT VT = Op.getValueType(); 11281 if (Count == 0) 11282 Count = VT.getVectorNumElements(); 11283 if (EltVT == EVT()) 11284 EltVT = VT.getVectorElementType(); 11285 SDLoc SL(Op); 11286 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 11287 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 11288 getVectorIdxConstant(i, SL))); 11289 } 11290 } 11291 11292 // getAddressSpace - Return the address space this GlobalAddress belongs to. 11293 unsigned GlobalAddressSDNode::getAddressSpace() const { 11294 return getGlobal()->getType()->getAddressSpace(); 11295 } 11296 11297 Type *ConstantPoolSDNode::getType() const { 11298 if (isMachineConstantPoolEntry()) 11299 return Val.MachineCPVal->getType(); 11300 return Val.ConstVal->getType(); 11301 } 11302 11303 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 11304 unsigned &SplatBitSize, 11305 bool &HasAnyUndefs, 11306 unsigned MinSplatBits, 11307 bool IsBigEndian) const { 11308 EVT VT = getValueType(0); 11309 assert(VT.isVector() && "Expected a vector type"); 11310 unsigned VecWidth = VT.getSizeInBits(); 11311 if (MinSplatBits > VecWidth) 11312 return false; 11313 11314 // FIXME: The widths are based on this node's type, but build vectors can 11315 // truncate their operands. 11316 SplatValue = APInt(VecWidth, 0); 11317 SplatUndef = APInt(VecWidth, 0); 11318 11319 // Get the bits. Bits with undefined values (when the corresponding element 11320 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 11321 // in SplatValue. If any of the values are not constant, give up and return 11322 // false. 11323 unsigned int NumOps = getNumOperands(); 11324 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 11325 unsigned EltWidth = VT.getScalarSizeInBits(); 11326 11327 for (unsigned j = 0; j < NumOps; ++j) { 11328 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 11329 SDValue OpVal = getOperand(i); 11330 unsigned BitPos = j * EltWidth; 11331 11332 if (OpVal.isUndef()) 11333 SplatUndef.setBits(BitPos, BitPos + EltWidth); 11334 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 11335 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 11336 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 11337 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 11338 else 11339 return false; 11340 } 11341 11342 // The build_vector is all constants or undefs. Find the smallest element 11343 // size that splats the vector. 11344 HasAnyUndefs = (SplatUndef != 0); 11345 11346 // FIXME: This does not work for vectors with elements less than 8 bits. 11347 while (VecWidth > 8) { 11348 unsigned HalfSize = VecWidth / 2; 11349 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize); 11350 APInt LowValue = SplatValue.extractBits(HalfSize, 0); 11351 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize); 11352 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0); 11353 11354 // If the two halves do not match (ignoring undef bits), stop here. 11355 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 11356 MinSplatBits > HalfSize) 11357 break; 11358 11359 SplatValue = HighValue | LowValue; 11360 SplatUndef = HighUndef & LowUndef; 11361 11362 VecWidth = HalfSize; 11363 } 11364 11365 SplatBitSize = VecWidth; 11366 return true; 11367 } 11368 11369 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 11370 BitVector *UndefElements) const { 11371 unsigned NumOps = getNumOperands(); 11372 if (UndefElements) { 11373 UndefElements->clear(); 11374 UndefElements->resize(NumOps); 11375 } 11376 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 11377 if (!DemandedElts) 11378 return SDValue(); 11379 SDValue Splatted; 11380 for (unsigned i = 0; i != NumOps; ++i) { 11381 if (!DemandedElts[i]) 11382 continue; 11383 SDValue Op = getOperand(i); 11384 if (Op.isUndef()) { 11385 if (UndefElements) 11386 (*UndefElements)[i] = true; 11387 } else if (!Splatted) { 11388 Splatted = Op; 11389 } else if (Splatted != Op) { 11390 return SDValue(); 11391 } 11392 } 11393 11394 if (!Splatted) { 11395 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 11396 assert(getOperand(FirstDemandedIdx).isUndef() && 11397 "Can only have a splat without a constant for all undefs."); 11398 return getOperand(FirstDemandedIdx); 11399 } 11400 11401 return Splatted; 11402 } 11403 11404 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 11405 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 11406 return getSplatValue(DemandedElts, UndefElements); 11407 } 11408 11409 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 11410 SmallVectorImpl<SDValue> &Sequence, 11411 BitVector *UndefElements) const { 11412 unsigned NumOps = getNumOperands(); 11413 Sequence.clear(); 11414 if (UndefElements) { 11415 UndefElements->clear(); 11416 UndefElements->resize(NumOps); 11417 } 11418 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 11419 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 11420 return false; 11421 11422 // Set the undefs even if we don't find a sequence (like getSplatValue). 11423 if (UndefElements) 11424 for (unsigned I = 0; I != NumOps; ++I) 11425 if (DemandedElts[I] && getOperand(I).isUndef()) 11426 (*UndefElements)[I] = true; 11427 11428 // Iteratively widen the sequence length looking for repetitions. 11429 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 11430 Sequence.append(SeqLen, SDValue()); 11431 for (unsigned I = 0; I != NumOps; ++I) { 11432 if (!DemandedElts[I]) 11433 continue; 11434 SDValue &SeqOp = Sequence[I % SeqLen]; 11435 SDValue Op = getOperand(I); 11436 if (Op.isUndef()) { 11437 if (!SeqOp) 11438 SeqOp = Op; 11439 continue; 11440 } 11441 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 11442 Sequence.clear(); 11443 break; 11444 } 11445 SeqOp = Op; 11446 } 11447 if (!Sequence.empty()) 11448 return true; 11449 } 11450 11451 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 11452 return false; 11453 } 11454 11455 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 11456 BitVector *UndefElements) const { 11457 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 11458 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 11459 } 11460 11461 ConstantSDNode * 11462 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 11463 BitVector *UndefElements) const { 11464 return dyn_cast_or_null<ConstantSDNode>( 11465 getSplatValue(DemandedElts, UndefElements)); 11466 } 11467 11468 ConstantSDNode * 11469 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 11470 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 11471 } 11472 11473 ConstantFPSDNode * 11474 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 11475 BitVector *UndefElements) const { 11476 return dyn_cast_or_null<ConstantFPSDNode>( 11477 getSplatValue(DemandedElts, UndefElements)); 11478 } 11479 11480 ConstantFPSDNode * 11481 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 11482 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 11483 } 11484 11485 int32_t 11486 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 11487 uint32_t BitWidth) const { 11488 if (ConstantFPSDNode *CN = 11489 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 11490 bool IsExact; 11491 APSInt IntVal(BitWidth); 11492 const APFloat &APF = CN->getValueAPF(); 11493 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 11494 APFloat::opOK || 11495 !IsExact) 11496 return -1; 11497 11498 return IntVal.exactLogBase2(); 11499 } 11500 return -1; 11501 } 11502 11503 bool BuildVectorSDNode::getConstantRawBits( 11504 bool IsLittleEndian, unsigned DstEltSizeInBits, 11505 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const { 11506 // Early-out if this contains anything but Undef/Constant/ConstantFP. 11507 if (!isConstant()) 11508 return false; 11509 11510 unsigned NumSrcOps = getNumOperands(); 11511 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits(); 11512 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11513 "Invalid bitcast scale"); 11514 11515 // Extract raw src bits. 11516 SmallVector<APInt> SrcBitElements(NumSrcOps, 11517 APInt::getNullValue(SrcEltSizeInBits)); 11518 BitVector SrcUndeElements(NumSrcOps, false); 11519 11520 for (unsigned I = 0; I != NumSrcOps; ++I) { 11521 SDValue Op = getOperand(I); 11522 if (Op.isUndef()) { 11523 SrcUndeElements.set(I); 11524 continue; 11525 } 11526 auto *CInt = dyn_cast<ConstantSDNode>(Op); 11527 auto *CFP = dyn_cast<ConstantFPSDNode>(Op); 11528 assert((CInt || CFP) && "Unknown constant"); 11529 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits) 11530 : CFP->getValueAPF().bitcastToAPInt(); 11531 } 11532 11533 // Recast to dst width. 11534 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements, 11535 SrcBitElements, UndefElements, SrcUndeElements); 11536 return true; 11537 } 11538 11539 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian, 11540 unsigned DstEltSizeInBits, 11541 SmallVectorImpl<APInt> &DstBitElements, 11542 ArrayRef<APInt> SrcBitElements, 11543 BitVector &DstUndefElements, 11544 const BitVector &SrcUndefElements) { 11545 unsigned NumSrcOps = SrcBitElements.size(); 11546 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth(); 11547 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11548 "Invalid bitcast scale"); 11549 assert(NumSrcOps == SrcUndefElements.size() && 11550 "Vector size mismatch"); 11551 11552 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits; 11553 DstUndefElements.clear(); 11554 DstUndefElements.resize(NumDstOps, false); 11555 DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits)); 11556 11557 // Concatenate src elements constant bits together into dst element. 11558 if (SrcEltSizeInBits <= DstEltSizeInBits) { 11559 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits; 11560 for (unsigned I = 0; I != NumDstOps; ++I) { 11561 DstUndefElements.set(I); 11562 APInt &DstBits = DstBitElements[I]; 11563 for (unsigned J = 0; J != Scale; ++J) { 11564 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11565 if (SrcUndefElements[Idx]) 11566 continue; 11567 DstUndefElements.reset(I); 11568 const APInt &SrcBits = SrcBitElements[Idx]; 11569 assert(SrcBits.getBitWidth() == SrcEltSizeInBits && 11570 "Illegal constant bitwidths"); 11571 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits); 11572 } 11573 } 11574 return; 11575 } 11576 11577 // Split src element constant bits into dst elements. 11578 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits; 11579 for (unsigned I = 0; I != NumSrcOps; ++I) { 11580 if (SrcUndefElements[I]) { 11581 DstUndefElements.set(I * Scale, (I + 1) * Scale); 11582 continue; 11583 } 11584 const APInt &SrcBits = SrcBitElements[I]; 11585 for (unsigned J = 0; J != Scale; ++J) { 11586 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11587 APInt &DstBits = DstBitElements[Idx]; 11588 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits); 11589 } 11590 } 11591 } 11592 11593 bool BuildVectorSDNode::isConstant() const { 11594 for (const SDValue &Op : op_values()) { 11595 unsigned Opc = Op.getOpcode(); 11596 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 11597 return false; 11598 } 11599 return true; 11600 } 11601 11602 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 11603 // Find the first non-undef value in the shuffle mask. 11604 unsigned i, e; 11605 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 11606 /* search */; 11607 11608 // If all elements are undefined, this shuffle can be considered a splat 11609 // (although it should eventually get simplified away completely). 11610 if (i == e) 11611 return true; 11612 11613 // Make sure all remaining elements are either undef or the same as the first 11614 // non-undef value. 11615 for (int Idx = Mask[i]; i != e; ++i) 11616 if (Mask[i] >= 0 && Mask[i] != Idx) 11617 return false; 11618 return true; 11619 } 11620 11621 // Returns the SDNode if it is a constant integer BuildVector 11622 // or constant integer. 11623 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 11624 if (isa<ConstantSDNode>(N)) 11625 return N.getNode(); 11626 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 11627 return N.getNode(); 11628 // Treat a GlobalAddress supporting constant offset folding as a 11629 // constant integer. 11630 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 11631 if (GA->getOpcode() == ISD::GlobalAddress && 11632 TLI->isOffsetFoldingLegal(GA)) 11633 return GA; 11634 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11635 isa<ConstantSDNode>(N.getOperand(0))) 11636 return N.getNode(); 11637 return nullptr; 11638 } 11639 11640 // Returns the SDNode if it is a constant float BuildVector 11641 // or constant float. 11642 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 11643 if (isa<ConstantFPSDNode>(N)) 11644 return N.getNode(); 11645 11646 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 11647 return N.getNode(); 11648 11649 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11650 isa<ConstantFPSDNode>(N.getOperand(0))) 11651 return N.getNode(); 11652 11653 return nullptr; 11654 } 11655 11656 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 11657 assert(!Node->OperandList && "Node already has operands"); 11658 assert(SDNode::getMaxNumOperands() >= Vals.size() && 11659 "too many operands to fit into SDNode"); 11660 SDUse *Ops = OperandRecycler.allocate( 11661 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 11662 11663 bool IsDivergent = false; 11664 for (unsigned I = 0; I != Vals.size(); ++I) { 11665 Ops[I].setUser(Node); 11666 Ops[I].setInitial(Vals[I]); 11667 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 11668 IsDivergent |= Ops[I].getNode()->isDivergent(); 11669 } 11670 Node->NumOperands = Vals.size(); 11671 Node->OperandList = Ops; 11672 if (!TLI->isSDNodeAlwaysUniform(Node)) { 11673 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 11674 Node->SDNodeBits.IsDivergent = IsDivergent; 11675 } 11676 checkForCycles(Node); 11677 } 11678 11679 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 11680 SmallVectorImpl<SDValue> &Vals) { 11681 size_t Limit = SDNode::getMaxNumOperands(); 11682 while (Vals.size() > Limit) { 11683 unsigned SliceIdx = Vals.size() - Limit; 11684 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 11685 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 11686 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 11687 Vals.emplace_back(NewTF); 11688 } 11689 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 11690 } 11691 11692 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 11693 EVT VT, SDNodeFlags Flags) { 11694 switch (Opcode) { 11695 default: 11696 return SDValue(); 11697 case ISD::ADD: 11698 case ISD::OR: 11699 case ISD::XOR: 11700 case ISD::UMAX: 11701 return getConstant(0, DL, VT); 11702 case ISD::MUL: 11703 return getConstant(1, DL, VT); 11704 case ISD::AND: 11705 case ISD::UMIN: 11706 return getAllOnesConstant(DL, VT); 11707 case ISD::SMAX: 11708 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 11709 case ISD::SMIN: 11710 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 11711 case ISD::FADD: 11712 return getConstantFP(-0.0, DL, VT); 11713 case ISD::FMUL: 11714 return getConstantFP(1.0, DL, VT); 11715 case ISD::FMINNUM: 11716 case ISD::FMAXNUM: { 11717 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 11718 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 11719 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 11720 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 11721 APFloat::getLargest(Semantics); 11722 if (Opcode == ISD::FMAXNUM) 11723 NeutralAF.changeSign(); 11724 11725 return getConstantFP(NeutralAF, DL, VT); 11726 } 11727 } 11728 } 11729 11730 #ifndef NDEBUG 11731 static void checkForCyclesHelper(const SDNode *N, 11732 SmallPtrSetImpl<const SDNode*> &Visited, 11733 SmallPtrSetImpl<const SDNode*> &Checked, 11734 const llvm::SelectionDAG *DAG) { 11735 // If this node has already been checked, don't check it again. 11736 if (Checked.count(N)) 11737 return; 11738 11739 // If a node has already been visited on this depth-first walk, reject it as 11740 // a cycle. 11741 if (!Visited.insert(N).second) { 11742 errs() << "Detected cycle in SelectionDAG\n"; 11743 dbgs() << "Offending node:\n"; 11744 N->dumprFull(DAG); dbgs() << "\n"; 11745 abort(); 11746 } 11747 11748 for (const SDValue &Op : N->op_values()) 11749 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 11750 11751 Checked.insert(N); 11752 Visited.erase(N); 11753 } 11754 #endif 11755 11756 void llvm::checkForCycles(const llvm::SDNode *N, 11757 const llvm::SelectionDAG *DAG, 11758 bool force) { 11759 #ifndef NDEBUG 11760 bool check = force; 11761 #ifdef EXPENSIVE_CHECKS 11762 check = true; 11763 #endif // EXPENSIVE_CHECKS 11764 if (check) { 11765 assert(N && "Checking nonexistent SDNode"); 11766 SmallPtrSet<const SDNode*, 32> visited; 11767 SmallPtrSet<const SDNode*, 32> checked; 11768 checkForCyclesHelper(N, visited, checked, DAG); 11769 } 11770 #endif // !NDEBUG 11771 } 11772 11773 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 11774 checkForCycles(DAG->getRoot().getNode(), DAG, force); 11775 } 11776